From f797a5367c2748ff8121ba109572e5f538ea74dc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:19:34 +0800 Subject: [PATCH 001/201] build: take the four tool crates out of the workspace members bin/mega-evme, bin/mega-t8n, crates/mega-state-test and crates/state-test still target the legacy engine. Their sources stay untouched; they rejoin the workspace when they are ported to Satin. --- Cargo.lock | 1028 +--------------------------------------------------- Cargo.toml | 15 +- 2 files changed, 8 insertions(+), 1035 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2b72f2d86..bb39fcd76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -339,7 +339,6 @@ dependencies = [ "alloy-signer", "alloy-sol-types", "alloy-transport", - "alloy-transport-http", "async-stream", "async-trait", "auto_impl", @@ -350,13 +349,11 @@ dependencies = [ "lru", "parking_lot", "pin-project", - "reqwest", "serde", "serde_json", "thiserror", "tokio", "tracing", - "url", "wasmtimer", ] @@ -391,17 +388,14 @@ dependencies = [ "alloy-json-rpc", "alloy-primitives", "alloy-transport", - "alloy-transport-http", "futures", "pin-project", - "reqwest", "serde", "serde_json", "tokio", "tokio-stream", "tower", "tracing", - "url", "wasmtimer", ] @@ -570,21 +564,6 @@ dependencies = [ "wasmtimer", ] -[[package]] -name = "alloy-transport-http" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90aa6825760905898c106aba9c804b131816a15041523e80b6d4fe7af6380ada" -dependencies = [ - "alloy-json-rpc", - "alloy-transport", - "reqwest", - "serde_json", - "tower", - "tracing", - "url", -] - [[package]] name = "alloy-trie" version = "0.9.0" @@ -634,56 +613,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - [[package]] name = "anstyle" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.103" @@ -911,7 +846,7 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber 0.2.25", + "tracing-subscriber", ] [[package]] @@ -1004,16 +939,6 @@ dependencies = [ "serde", ] -[[package]] -name = "assert-json-diff" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" -dependencies = [ - "serde", - "serde_json", -] - [[package]] name = "async-stream" version = "0.3.6" @@ -1047,12 +972,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - [[package]] name = "aurora-engine-modexp" version = "1.2.0" @@ -1370,7 +1289,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", - "clap_derive", ] [[package]] @@ -1379,22 +1297,8 @@ version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" dependencies = [ - "anstream", "anstyle", "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.5.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.104", ] [[package]] @@ -1475,18 +1379,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "console" -version = "0.15.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" -dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "windows-sys 0.59.0", -] - [[package]] name = "const-hex" version = "1.14.1" @@ -1541,16 +1433,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-sys" version = "0.8.7" @@ -1693,24 +1575,6 @@ dependencies = [ "parking_lot_core", ] -[[package]] -name = "deadpool" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" -dependencies = [ - "deadpool-runtime", - "lazy_static", - "num_cpus", - "tokio", -] - -[[package]] -name = "deadpool-runtime" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" - [[package]] name = "delegate" version = "0.13.4" @@ -1817,27 +1681,6 @@ dependencies = [ "crypto-common 0.2.2", ] -[[package]] -name = "dirs" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.61.2", -] - [[package]] name = "displaydoc" version = "0.2.5" @@ -1917,21 +1760,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "encode_unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" - -[[package]] -name = "encoding_rs" -version = "0.8.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" -dependencies = [ - "cfg-if", -] - [[package]] name = "enum-ordinalize" version = "4.3.0" @@ -2059,21 +1887,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -2263,25 +2076,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "h2" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap 2.10.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "half" version = "2.6.0" @@ -2292,12 +2086,6 @@ dependencies = [ "crunchy", ] -[[package]] -name = "hash-db" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" - [[package]] name = "hashbrown" version = "0.12.3" @@ -2382,41 +2170,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.12" @@ -2426,87 +2179,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "hyper" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1744436df46f0bde35af3eda22aeaba453aada65d8f1c171cd8a5f59030bd69f" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "pin-utils", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" -dependencies = [ - "base64", - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "system-configuration", - "tokio", - "tower-service", - "tracing", - "windows-registry", -] - [[package]] name = "iana-time-zone" version = "0.1.63" @@ -2681,34 +2353,6 @@ dependencies = [ "serde", ] -[[package]] -name = "indicatif" -version = "0.17.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" -dependencies = [ - "console", - "number_prefix", - "portable-atomic", - "web-time", -] - -[[package]] -name = "ipnet" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f867b9d1d896b67beb18518eda36fdb77a32ea590de864f1325b294a6d14397" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "is-terminal" version = "0.4.16" @@ -2720,12 +2364,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itertools" version = "0.10.5" @@ -2844,15 +2482,6 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" -[[package]] -name = "libredox" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" -dependencies = [ - "libc", -] - [[package]] name = "libsecp256k1" version = "0.7.2" @@ -2946,15 +2575,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "matchers" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" -dependencies = [ - "regex-automata", -] - [[package]] name = "mega-evm" version = "1.7.1" @@ -2992,66 +2612,7 @@ dependencies = [ ] [[package]] -name = "mega-evme" -version = "1.7.1" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-json-rpc", - "alloy-network", - "alloy-primitives", - "alloy-provider", - "alloy-rpc-client", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", - "alloy-serde", - "alloy-sol-types", - "alloy-transport", - "alloy-transport-http", - "clap", - "dirs", - "mega-evm", - "mega-evme", - "mega-state-test", - "op-alloy-consensus", - "op-alloy-network", - "op-alloy-rpc-types", - "reqwest", - "revm-inspectors", - "rstest", - "serde", - "serde_json", - "tempfile", - "thiserror", - "tokio", - "tower", - "tracing", - "tracing-subscriber 0.3.20", - "wiremock", -] - -[[package]] -name = "mega-state-test" -version = "1.7.1" -dependencies = [ - "alloy-eips", - "alloy-primitives", - "alloy-rlp", - "alloy-serde", - "hash-db", - "indicatif", - "k256", - "mega-evm", - "plain_hasher", - "serde", - "serde_json", - "thiserror", - "triehash", - "walkdir", -] - -[[package]] -name = "mega-system-contracts" +name = "mega-system-contracts" version = "1.7.1" dependencies = [ "alloy-primitives", @@ -3061,61 +2622,12 @@ dependencies = [ "serde_json", ] -[[package]] -name = "mega-t8n" -version = "1.7.1" -dependencies = [ - "alloy-consensus", - "alloy-primitives", - "alloy-serde", - "clap", - "mega-evm", - "mega-state-test", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "memchr" version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mio" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" -dependencies = [ - "libc", - "wasi 0.11.1+wasi-snapshot-preview1", - "windows-sys 0.61.2", -] - -[[package]] -name = "native-tls" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - [[package]] name = "nix" version = "0.31.3" @@ -3128,15 +2640,6 @@ dependencies = [ "libc", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num" version = "0.4.3" @@ -3260,12 +2763,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - [[package]] name = "nybbles" version = "0.4.3" @@ -3286,12 +2783,6 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "oorandom" version = "11.1.5" @@ -3306,13 +2797,9 @@ checksum = "0c88d2940558fd69f8f07b3cbd7bb3c02fc7d31159c1a7ba9deede50e7881024" dependencies = [ "alloy-consensus", "alloy-eips", - "alloy-network", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth", - "alloy-serde", "derive_more", - "serde", "thiserror", ] @@ -3322,41 +2809,6 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a79f352fc3893dcd670172e615afef993a41798a1d3fc0db88a3e60ef2e70ecc" -[[package]] -name = "op-alloy-network" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7071d7c3457d02aa0d35799cb8fbd93eabd51a21d100dcf411f4fcab6fdd2ea5" -dependencies = [ - "alloy-consensus", - "alloy-network", - "alloy-primitives", - "alloy-provider", - "alloy-rpc-types-eth", - "alloy-signer", - "op-alloy-consensus", - "op-alloy-rpc-types", -] - -[[package]] -name = "op-alloy-rpc-types" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f22201e53e8cbb67a053e88b534b4e7f02265c5406994bf35978482a9ad0ae26" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-network-primitives", - "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", - "derive_more", - "op-alloy-consensus", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "op-revm" version = "8.1.0" @@ -3386,55 +2838,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" -[[package]] -name = "openssl" -version = "0.10.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - -[[package]] -name = "openssl-sys" -version = "0.9.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "p256" version = "0.13.2" @@ -3770,21 +3173,6 @@ dependencies = [ "spki", ] -[[package]] -name = "pkg-config" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" - -[[package]] -name = "plain_hasher" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e19e6491bdde87c2c43d70f4c194bc8a758f2eb732df00f61e43f7362e3b4cc" -dependencies = [ - "crunchy", -] - [[package]] name = "plotters" version = "0.3.7" @@ -3813,12 +3201,6 @@ dependencies = [ "plotters-backend", ] -[[package]] -name = "portable-atomic" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" - [[package]] name = "potential_utf" version = "0.1.4" @@ -4062,17 +3444,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "redox_users" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" -dependencies = [ - "getrandom 0.2.16", - "libredox", - "thiserror", -] - [[package]] name = "ref-cast" version = "1.0.24" @@ -4122,52 +3493,6 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" -[[package]] -name = "relative-path" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" - -[[package]] -name = "reqwest" -version = "0.12.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" -dependencies = [ - "base64", - "bytes", - "encoding_rs", - "futures-core", - "h2", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-tls", - "hyper-util", - "js-sys", - "log", - "mime", - "native-tls", - "percent-encoding", - "pin-project-lite", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-native-tls", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "revm" version = "27.1.0" @@ -4582,20 +3907,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.16", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - [[package]] name = "ripemd" version = "0.1.3" @@ -4615,33 +3926,6 @@ dependencies = [ "rustc-hex", ] -[[package]] -name = "rstest" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" -dependencies = [ - "rstest_macros", - "rustc_version 0.4.1", -] - -[[package]] -name = "rstest_macros" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f168d99749d307be9de54d23fd226628d99768225ef08f6ffb52e0182a27746" -dependencies = [ - "cfg-if", - "glob", - "proc-macro2", - "quote", - "regex", - "relative-path", - "rustc_version 0.4.1", - "syn 2.0.104", - "unicode-ident", -] - [[package]] name = "rug" version = "1.27.0" @@ -4731,39 +4015,6 @@ dependencies = [ "windows-sys 0.60.2", ] -[[package]] -name = "rustls" -version = "0.23.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" -dependencies = [ - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rustversion" version = "1.0.21" @@ -4797,15 +4048,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "schannel" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "schemars" version = "0.9.0" @@ -4892,29 +4134,6 @@ dependencies = [ "cc", ] -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "semver" version = "0.11.0" @@ -4994,18 +4213,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - [[package]] name = "serde_with" version = "3.14.1" @@ -5092,15 +4299,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -5138,16 +4336,6 @@ dependencies = [ "serde", ] -[[package]] -name = "socket2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" -dependencies = [ - "libc", - "windows-sys 0.60.2", -] - [[package]] name = "sp1-lib" version = "5.0.8" @@ -5216,16 +4404,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" -[[package]] -name = "state-test" -version = "1.7.1" -dependencies = [ - "clap", - "mega-evm", - "mega-state-test", - "serde_json", -] - [[package]] name = "static_assertions" version = "1.1.0" @@ -5314,9 +4492,6 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] [[package]] name = "synstructure" @@ -5329,27 +4504,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "system-configuration" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" -dependencies = [ - "bitflags", - "core-foundation", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "tap" version = "1.0.1" @@ -5389,15 +4543,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "thread_local" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" -dependencies = [ - "cfg-if", -] - [[package]] name = "threadpool" version = "1.8.1" @@ -5473,13 +4618,8 @@ version = "1.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ - "bytes", - "libc", - "mio", "pin-project-lite", - "socket2", "tokio-macros", - "windows-sys 0.61.2", ] [[package]] @@ -5493,26 +4633,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - [[package]] name = "tokio-stream" version = "0.1.17" @@ -5565,25 +4685,6 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" -dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", "tower-layer", "tower-service", ] @@ -5641,38 +4742,6 @@ dependencies = [ "tracing-core", ] -[[package]] -name = "tracing-subscriber" -version = "0.3.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex-automata", - "sharded-slab", - "thread_local", - "tracing", - "tracing-core", -] - -[[package]] -name = "triehash" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1631b201eb031b563d2e85ca18ec8092508e262a3196ce9bd10a67ec87b9f5c" -dependencies = [ - "hash-db", - "rlp", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - [[package]] name = "typenum" version = "1.20.0" @@ -5721,12 +4790,6 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - [[package]] name = "url" version = "2.5.7" @@ -5745,24 +4808,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "version_check" version = "0.9.5" @@ -5788,15 +4839,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -5838,19 +4880,6 @@ dependencies = [ "wasm-bindgen-shared", ] -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" -dependencies = [ - "cfg-if", - "js-sys", - "once_cell", - "wasm-bindgen", - "web-sys", -] - [[package]] name = "wasm-bindgen-macro" version = "0.2.100" @@ -5907,16 +4936,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "winapi-util" version = "0.1.11" @@ -5973,17 +4992,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-registry" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" -dependencies = [ - "windows-link 0.1.3", - "windows-result", - "windows-strings", -] - [[package]] name = "windows-result" version = "0.3.4" @@ -6002,15 +5010,6 @@ dependencies = [ "windows-link 0.1.3", ] -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.59.0" @@ -6175,29 +5174,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "wiremock" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" -dependencies = [ - "assert-json-diff", - "base64", - "deadpool", - "futures", - "http", - "http-body-util", - "hyper", - "hyper-util", - "log", - "once_cell", - "regex", - "serde", - "serde_json", - "tokio", - "url", -] - [[package]] name = "wit-bindgen-rt" version = "0.39.0" diff --git a/Cargo.toml b/Cargo.toml index d76c60501..24f58a1da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,11 @@ [workspace] -members = [ - "bin/mega-evme", - "bin/mega-t8n", - "crates/mega-evm", - "crates/mega-state-test", - "crates/state-test", - "crates/system-contracts", -] -default-members = ["crates/mega-evm", "bin/mega-evme", "bin/mega-t8n"] +# The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, +# `crates/state-test`) still target the legacy engine; their sources are kept +# untouched and they rejoin the workspace when T10.1 (state-test), T10.2 +# (mega-evme) and T10.3 (mega-t8n) port them to Satin. +members = ["crates/mega-evm", "crates/system-contracts"] +default-members = ["crates/mega-evm"] exclude = [] # Explicitly set the resolver to version 2, which is the default for packages with edition >= 2021 From 80d13bffe718b7bc403ca4cf6b90abd982a2790a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:21:46 +0800 Subject: [PATCH 002/201] test: apply the test inventory to the integration tests Delete the 274 integration tests the test inventory marks legacy-only or retired (125 + 149) and move the 691 that survive into Satin under tests/_pending/, unchanged apart from the deletions. _pending has no main.rs, so Cargo does not build it; its README names the owning mechanism for every file. compute_gas/snapshot.txt goes with the per-opcode counter it pinned (D40). --- crates/mega-evm/tests/_pending/README.md | 134 +++ .../block_executor/accessed_block_hashes.rs | 0 .../block_executor/block_limits.rs | 0 .../block_executor/canonical_schedule.rs | 0 .../block_executor/deposit_da_exemption.rs | 0 .../block_executor/inspector.rs | 0 .../{ => _pending}/block_executor/main.rs | 1 - .../block_executor/sequencer_registry.rs | 0 .../trait_factory_runtime_limits.rs | 0 .../{ => _pending}/compute_gas/claims.rs | 215 ---- .../tests/{ => _pending}/compute_gas/main.rs | 80 -- .../{ => _pending}/equivalence/evm_state.rs | 0 .../tests/{ => _pending}/equivalence/main.rs | 0 .../mini_rex/access_beneficiary_balance.rs | 0 .../mini_rex/block_env_access_tracking.rs | 0 .../mini_rex/block_env_gas_limit.rs | 0 .../mini_rex/compute_gas_limit.rs | 162 --- .../mini_rex/contract_size_limit.rs | 60 -- .../tests/{ => _pending}/mini_rex/db_error.rs | 0 .../tests/{ => _pending}/mini_rex/gas.rs | 195 ---- .../tests/{ => _pending}/mini_rex/main.rs | 1 - .../mini_rex/mega_system_transaction.rs | 0 .../tests/{ => _pending}/mini_rex/oracle.rs | 229 ----- .../_pending/mini_rex/state_growth_limit.rs | 221 ++++ .../mini_rex/tx_data_and_kv_update_limit.rs | 281 ----- .../{ => _pending}/mutation/access_evm.rs | 0 .../tests/{ => _pending}/mutation/block.rs | 0 .../{ => _pending}/mutation/constants.rs | 19 - .../{ => _pending}/mutation/external_exec.rs | 0 .../tests/{ => _pending}/mutation/main.rs | 1 - .../mega-evm/tests/{ => _pending}/rex/main.rs | 2 - .../tests/{ => _pending}/rex/oracle.rs | 0 .../tests/{ => _pending}/rex/storage_gas.rs | 52 - .../{ => _pending}/rex2/keyless_deploy.rs | 91 -- .../tests/{ => _pending}/rex2/main.rs | 1 - .../tests/{ => _pending}/rex2/oracle_hint.rs | 25 - .../{ => _pending}/rex3/keyless_deploy.rs | 25 - .../tests/{ => _pending}/rex3/main.rs | 0 .../{ => _pending}/rex3/oracle_gas_limit.rs | 68 -- .../{ => _pending}/rex3/system_address.rs | 0 .../{ => _pending}/rex4/access_control.rs | 79 -- .../rex4/beneficiary_detention.rs | 56 - .../{ => _pending}/rex4/create_safety.rs | 109 -- .../tests/{ => _pending}/rex4/deployment.rs | 10 - .../rex4/eip7702_delegation_cycle.rs | 18 - .../tests/{ => _pending}/rex4/frame_limits.rs | 247 ----- .../{ => _pending}/rex4/gas_detention.rs | 27 - .../rex4/intrinsic_limit_bypass.rs | 0 .../{ => _pending}/rex4/keyless_deploy.rs | 77 -- .../{ => _pending}/rex4/limit_control.rs | 12 - .../tests/{ => _pending}/rex4/main.rs | 2 - .../rex4/storage_call_stipend.rs | 272 ----- .../rex5/apply_pending_changes_gas_budget.rs | 0 .../rex5/call_too_deep_guard.rs | 25 - .../rex5/callcode_storage_gas.rs | 34 - .../rex5/create2_empty_initcode.rs | 25 - .../rex5/create2_resize_gas_metering.rs | 31 - .../tests/{ => _pending}/rex5/db_error.rs | 0 .../rex5/deposit_caller_accounting.rs | 36 - .../rex5/deposit_create_storage_gas.rs | 19 - .../{ => _pending}/rex5/eip7702_metering.rs | 0 .../rex5/eip7702_state_growth.rs | 33 - .../rex5/frame_target_updated_dedup.rs | 85 -- .../{ => _pending}/rex5/gas_validation.rs | 35 - .../rex5/interceptor_selector_probe.rs | 0 .../rex5/keyless_deploy_dispatch_parity.rs | 0 .../rex5/keyless_empty_code_logs.rs | 40 - .../{ => _pending}/rex5/keyless_fee_free.rs | 35 - .../rex5/keyless_gas_cap_postcap_recheck.rs | 36 - .../rex5/keyless_replay_barrier.rs | 45 - .../tests/{ => _pending}/rex5/main.rs | 1 - .../rex5/oracle_hint_metering.rs | 59 -- .../rex5/pre_block_system_calls.rs | 103 -- .../rex5/precompile_compute_gas.rs | 204 ---- .../{ => _pending}/rex5/sandbox_accounting.rs | 549 ---------- .../rex5/selfdestruct_beneficiary.rs | 34 - .../rex5/sstore_storage_gas_error.rs | 0 .../{ => _pending}/rex5/stipend_accounting.rs | 356 ------- .../{ => _pending}/rex5/system_tx_replay.rs | 0 .../rex6/beneficiary_detention.rs | 90 -- .../tests/{ => _pending}/rex6/common.rs | 0 .../rex6/create2_metering_order.rs | 141 --- .../rex6/create_frame_accounting.rs | 96 -- .../rex6/eip7702_authority_accounting.rs | 0 .../tests/{ => _pending}/rex6/error_paths.rs | 0 .../rex6/fee_reward_accounting.rs | 57 -- .../rex6/frame_local_accounting.rs | 89 -- .../rex6/keyless_sandbox_hardening.rs | 68 -- .../tests/{ => _pending}/rex6/main.rs | 1 - .../rex6/oracle_hint_volatile_access.rs | 16 - .../rex6/self_transfer_account_dedup.rs | 60 -- .../rex6/sequencer_registry_rotation.rs | 104 -- .../rex6/system_tx_metering_exemption.rs | 42 - .../tests/block_executor/partial_ladder.rs | 404 -------- .../mega-evm/tests/compute_gas/snapshot.txt | 429 -------- .../tests/mini_rex/disallow_selfdestruct.rs | 55 - .../tests/mini_rex/state_growth_limit.rs | 807 --------------- crates/mega-evm/tests/mutation/limit.rs | 115 --- crates/mega-evm/tests/rex/intrinsic_gas.rs | 317 ------ crates/mega-evm/tests/rex2/selfdestruct.rs | 25 - .../mega-evm/tests/rex4/frame_state_growth.rs | 962 ------------------ .../tests/rex4/selfdestruct_state_growth.rs | 609 ----------- .../mega-evm/tests/rex5/create_atomicity.rs | 281 ----- .../tests/rex6/metering_order_parity.rs | 240 ----- 104 files changed, 355 insertions(+), 9210 deletions(-) create mode 100644 crates/mega-evm/tests/_pending/README.md rename crates/mega-evm/tests/{ => _pending}/block_executor/accessed_block_hashes.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/block_limits.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/canonical_schedule.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/deposit_da_exemption.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/inspector.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/main.rs (91%) rename crates/mega-evm/tests/{ => _pending}/block_executor/sequencer_registry.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/trait_factory_runtime_limits.rs (100%) rename crates/mega-evm/tests/{ => _pending}/compute_gas/claims.rs (79%) rename crates/mega-evm/tests/{ => _pending}/compute_gas/main.rs (91%) rename crates/mega-evm/tests/{ => _pending}/equivalence/evm_state.rs (100%) rename crates/mega-evm/tests/{ => _pending}/equivalence/main.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/access_beneficiary_balance.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/block_env_access_tracking.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/block_env_gas_limit.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/compute_gas_limit.rs (87%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/contract_size_limit.rs (81%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/db_error.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/gas.rs (80%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/main.rs (91%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/mega_system_transaction.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/oracle.rs (78%) create mode 100644 crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs rename crates/mega-evm/tests/{ => _pending}/mini_rex/tx_data_and_kv_update_limit.rs (82%) rename crates/mega-evm/tests/{ => _pending}/mutation/access_evm.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mutation/block.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mutation/constants.rs (76%) rename crates/mega-evm/tests/{ => _pending}/mutation/external_exec.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mutation/main.rs (99%) rename crates/mega-evm/tests/{ => _pending}/rex/main.rs (76%) rename crates/mega-evm/tests/{ => _pending}/rex/oracle.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex/storage_gas.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex2/keyless_deploy.rs (94%) rename crates/mega-evm/tests/{ => _pending}/rex2/main.rs (80%) rename crates/mega-evm/tests/{ => _pending}/rex2/oracle_hint.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex3/keyless_deploy.rs (84%) rename crates/mega-evm/tests/{ => _pending}/rex3/main.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex3/oracle_gas_limit.rs (83%) rename crates/mega-evm/tests/{ => _pending}/rex3/system_address.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex4/access_control.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex4/beneficiary_detention.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex4/create_safety.rs (52%) rename crates/mega-evm/tests/{ => _pending}/rex4/deployment.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex4/eip7702_delegation_cycle.rs (95%) rename crates/mega-evm/tests/{ => _pending}/rex4/frame_limits.rs (73%) rename crates/mega-evm/tests/{ => _pending}/rex4/gas_detention.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex4/intrinsic_limit_bypass.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex4/keyless_deploy.rs (77%) rename crates/mega-evm/tests/{ => _pending}/rex4/limit_control.rs (98%) rename crates/mega-evm/tests/{ => _pending}/rex4/main.rs (83%) rename crates/mega-evm/tests/{ => _pending}/rex4/storage_call_stipend.rs (69%) rename crates/mega-evm/tests/{ => _pending}/rex5/apply_pending_changes_gas_budget.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/call_too_deep_guard.rs (90%) rename crates/mega-evm/tests/{ => _pending}/rex5/callcode_storage_gas.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/create2_empty_initcode.rs (87%) rename crates/mega-evm/tests/{ => _pending}/rex5/create2_resize_gas_metering.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/db_error.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/deposit_caller_accounting.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/deposit_create_storage_gas.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex5/eip7702_metering.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/eip7702_state_growth.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/frame_target_updated_dedup.rs (75%) rename crates/mega-evm/tests/{ => _pending}/rex5/gas_validation.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/interceptor_selector_probe.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_deploy_dispatch_parity.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_empty_code_logs.rs (85%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_fee_free.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_gas_cap_postcap_recheck.rs (89%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_replay_barrier.rs (87%) rename crates/mega-evm/tests/{ => _pending}/rex5/main.rs (97%) rename crates/mega-evm/tests/{ => _pending}/rex5/oracle_hint_metering.rs (89%) rename crates/mega-evm/tests/{ => _pending}/rex5/pre_block_system_calls.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/precompile_compute_gas.rs (57%) rename crates/mega-evm/tests/{ => _pending}/rex5/sandbox_accounting.rs (57%) rename crates/mega-evm/tests/{ => _pending}/rex5/selfdestruct_beneficiary.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex5/sstore_storage_gas_error.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/stipend_accounting.rs (60%) rename crates/mega-evm/tests/{ => _pending}/rex5/system_tx_replay.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/beneficiary_detention.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex6/common.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/create2_metering_order.rs (79%) rename crates/mega-evm/tests/{ => _pending}/rex6/create_frame_accounting.rs (69%) rename crates/mega-evm/tests/{ => _pending}/rex6/eip7702_authority_accounting.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/error_paths.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/fee_reward_accounting.rs (90%) rename crates/mega-evm/tests/{ => _pending}/rex6/frame_local_accounting.rs (67%) rename crates/mega-evm/tests/{ => _pending}/rex6/keyless_sandbox_hardening.rs (85%) rename crates/mega-evm/tests/{ => _pending}/rex6/main.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex6/oracle_hint_volatile_access.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex6/self_transfer_account_dedup.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex6/sequencer_registry_rotation.rs (79%) rename crates/mega-evm/tests/{ => _pending}/rex6/system_tx_metering_exemption.rs (89%) delete mode 100644 crates/mega-evm/tests/block_executor/partial_ladder.rs delete mode 100644 crates/mega-evm/tests/compute_gas/snapshot.txt delete mode 100644 crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs delete mode 100644 crates/mega-evm/tests/mini_rex/state_growth_limit.rs delete mode 100644 crates/mega-evm/tests/mutation/limit.rs delete mode 100644 crates/mega-evm/tests/rex/intrinsic_gas.rs delete mode 100644 crates/mega-evm/tests/rex2/selfdestruct.rs delete mode 100644 crates/mega-evm/tests/rex4/frame_state_growth.rs delete mode 100644 crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs delete mode 100644 crates/mega-evm/tests/rex5/create_atomicity.rs delete mode 100644 crates/mega-evm/tests/rex6/metering_order_parity.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md new file mode 100644 index 000000000..366fdd8d4 --- /dev/null +++ b/crates/mega-evm/tests/_pending/README.md @@ -0,0 +1,134 @@ +# Pending tests + +Tests of the legacy engine that survive into Satin but cannot run until the ticket that owns them lands. +The dispositions come from the T0 test inventory of the Satin work order, and T2.1 applied them mechanically. +Every test T0 marks 仅 legacy (legacy-only) or 废弃 (retired) was deleted; every other test was moved here unchanged. +The decision ids (`Dnn`) refer to the Satin decision table. + +## How this directory is excluded from the build + +Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`. +`_pending/` has no `main.rs`, so nothing below it is compiled, formatted or linted. +Do not add a `_pending/main.rs`. + +## Rules for the owning ticket + +- Port the rows your ticket owns into a real test target, adapting them to the Satin API and the decision cited in the table. +- 保留 (keep) rows keep their scenario and expectation; 重写 (rewrite) rows keep the scenario and take the new expectation from the cited decision; 待定 (undecided) rows wait for their decision. +- Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. +- Files under `mutation/` are machine-generated mutant killers; T2.2 regenerates them against the Satin sources instead of porting them by hand. +- Files under `src/` are the inline unit-test modules of the legacy core, extracted when T2.1 replaced `crates/mega-evm/src`. + The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. +- Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. + +## Tests per owning ticket + +| Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | +|---|---:|---:|---:|---:|---:|---:| +| T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | +| T2.3 | 19 | 19 | 0 | 8 | 11 | 0 | +| T3.1 | 30 | 30 | 0 | 1 | 29 | 0 | +| T3.2 | 72 | 72 | 0 | 23 | 49 | 0 | +| T3.3 | 24 | 24 | 0 | 0 | 24 | 0 | +| T3.4 | 27 | 27 | 0 | 0 | 27 | 0 | +| T4.1 | 47 | 47 | 0 | 40 | 7 | 0 | +| T4.2 | 82 | 82 | 0 | 75 | 7 | 0 | +| T4.3 | 57 | 57 | 0 | 0 | 36 | 21 | +| T5.1 | 17 | 17 | 0 | 0 | 17 | 0 | +| T5.2 | 15 | 15 | 0 | 11 | 4 | 0 | +| T6.1 | 57 | 57 | 0 | 48 | 9 | 0 | +| T6.2 | 17 | 17 | 0 | 13 | 4 | 0 | +| T6.3 | 77 | 77 | 0 | 67 | 10 | 0 | +| T7 | 73 | 73 | 0 | 28 | 45 | 0 | +| T8.1 | 45 | 45 | 0 | 35 | 10 | 0 | +| T9 | 4 | 4 | 0 | 1 | 3 | 0 | +| — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | +| **Total** | **691** | **691** | **0** | **371** | **292** | **28** | + +## Files + +Each cell lists `disposition count (ticket · decision)`. + +| File | Tests | Owners | +|---|---:|---| +| `block_executor/accessed_block_hashes.rs` | 1 | 保留 1 (T8.1) | +| `block_executor/block_limits.rs` | 14 | 保留 12 (T8.1 · D47); 待定 2 (T4.3 · D46) | +| `block_executor/canonical_schedule.rs` | 1 | 重写 1 (T8.1 · single Satin fork; T15 owns the doc side) | +| `block_executor/deposit_da_exemption.rs` | 4 | 保留 4 (T8.1 · D23) | +| `block_executor/inspector.rs` | 3 | 保留 1 (T9); 重写 2 (T9 · D39/D41) | +| `block_executor/sequencer_registry.rs` | 8 | 保留 8 (T6.2) | +| `block_executor/trait_factory_runtime_limits.rs` | 4 | 重写 4 (T8.1 · D10 (200M execution cap replaces compute-gas runtime limit)) | +| `compute_gas/claims.rs` | 14 | 保留 2 (T6.1); 重写 2 (T3.4 · D53 (compute = regular spent; state spill excluded)); 保留 1 (T3.1 · D04 (KZG 100k)); 待定 5 (— · no D-id: preload-warm addresses charged cold (precompile / beneficiary / access-list) is absent from DECISIONS.md); 重写 2 (T3.1 · D13); 重写 1 (T3.1 · D11); 重写 1 (T4.1 · D33/D48) | +| `compute_gas/main.rs` | 1 | 重写 1 (T3.4 · D53) | +| `equivalence/evm_state.rs` | 3 | 保留 3 (T2.3) | +| `mini_rex/access_beneficiary_balance.rs` | 10 | 保留 9 (T4.2 · D08); 重写 1 (T5.1 · D48) | +| `mini_rex/block_env_access_tracking.rs` | 3 | 保留 3 (T4.2) | +| `mini_rex/block_env_gas_limit.rs` | 16 | 保留 13 (T4.2 · D08 cap 20M/1M unchanged); 重写 3 (T5.1 · D48 (detention halt -> revert-class)) | +| `mini_rex/compute_gas_limit.rs` | 25 | 重写 23 (T3.4 · D10/D40/D53 (compute derived from Gas; 200M cap)); 重写 2 (T4.2 · D48) | +| `mini_rex/contract_size_limit.rs` | 12 | 重写 12 (T3.1 · D04 (512 KiB kept; initcode bound under Osaka/EIP-3860 not pinned in DECISIONS.md)) | +| `mini_rex/db_error.rs` | 4 | 保留 4 (T2.3) | +| `mini_rex/gas.rs` | 26 | 重写 14 (T3.2 · D12 (state gas x m via pricing hook)); 重写 6 (T3.2 · D12/D13); 待定 2 (— · no D-id: 98/100 forwarding; D1 §2.5 says frame semantics follow 8037 (63/64) but DECISIONS.md is silent); 重写 4 (T3.1 · D11/D55 (7976 floor)) | +| `mini_rex/mega_system_transaction.rs` | 15 | 保留 15 (T6.1 · D51) | +| `mini_rex/oracle.rs` | 13 | 重写 3 (T5.1 · D48); 保留 5 (T4.2); 保留 4 (T6.3); 重写 1 (T6.2 · deploy at Satin activation) | +| `mini_rex/state_growth_limit.rs` | 4 | 重写 4 (T4.3 · D45 (state-gas limit)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | 保留 18 (T4.1 · data-size numbers unchanged); 重写 4 (T5.1 · D48); 待定 6 (T4.3 · D46 (count kept as output per R1b; limit semantics undecided)) | +| `mutation/access_evm.rs` | 10 | 保留 6 (T4.2 · T2.2 regenerates); 保留 2 (T3.2 · T2.2 regenerates); 保留 1 (T8.1 · T2.2 regenerates); 重写 1 (T3.1 · D11) | +| `mutation/block.rs` | 22 | 保留 14 (T8.1 · T2.2 regenerates); 重写 5 (T8.1 · single spec / Satin schedule); 待定 1 (T4.3 · D46); 重写 1 (T3.4 · D53); 重写 1 (T4.3 · D45) | +| `mutation/constants.rs` | 4 | 重写 2 (T3.1 · D04); 保留 2 (T4.1 · 13,107,200 unchanged) | +| `mutation/external_exec.rs` | 8 | 保留 2 (T8.1 · T2.2 regenerates); 保留 6 (T3.2 · T2.2 regenerates) | +| `rex/oracle.rs` | 3 | 重写 3 (T4.2 · D08 (mark at actual load: same outcome via SLOAD)) | +| `rex/storage_gas.rs` | 15 | 重写 15 (T3.2 · D12 (base price and min-bucket value change; multiplier logic kept)) | +| `rex2/keyless_deploy.rs` | 37 | 重写 13 (T7 · D1 §2.6 native CREATE sub-frame; D37/D38); 保留 19 (T7 · validation rules 1-9 unchanged); 保留 1 (T7 · rule 4 (tx nonce == 0) unchanged); 重写 3 (T7 · D36); 重写 1 (T6.2 · deploy at Satin activation) | +| `rex2/oracle_hint.rs` | 6 | 保留 6 (T6.3) | +| `rex3/keyless_deploy.rs` | 2 | 重写 2 (T6.1 · D15 (explicit 100k compute) / D48) | +| `rex3/oracle_gas_limit.rs` | 8 | 保留 7 (T4.2 · D08); 重写 1 (T5.1 · D48) | +| `rex3/system_address.rs` | 2 | 保留 2 (T4.2 · D51) | +| `rex4/access_control.rs` | 48 | 保留 46 (T6.3); 重写 2 (T4.2 · D07 (rejected volatile read pays static gas)) | +| `rex4/beneficiary_detention.rs` | 13 | 保留 12 (T4.2 · D08); 重写 1 (T5.1 · D48) | +| `rex4/create_safety.rs` | 1 | 保留 1 (T2.2 · canonical revm behaviour (differential harness)) | +| `rex4/deployment.rs` | 2 | 重写 2 (T6.2 · deploy at Satin activation) | +| `rex4/eip7702_delegation_cycle.rs` | 9 | 保留 8 (T3.2 · account inspection on the pricing path); 保留 1 (T2.3) | +| `rex4/frame_limits.rs` | 20 | 保留 10 (T4.1 · data-size per-frame 98% kept); 重写 1 (T5.1 · D48); 待定 9 (T4.3 · D46) | +| `rex4/gas_detention.rs` | 5 | 保留 3 (T4.2); 重写 2 (T5.1 · D48/D53) | +| `rex4/intrinsic_limit_bypass.rs` | 13 | 重写 6 (T4.1 · D48/D49 (overflow outcome shape)); 待定 3 (T4.3 · D46); 保留 3 (T4.1); 重写 1 (T9 · D41) | +| `rex4/keyless_deploy.rs` | 2 | 保留 2 (T7 · native sub-frame inherits env) | +| `rex4/limit_control.rs` | 14 | 重写 9 (T6.3 · D40 (remaining compute derived from Gas)); 保留 5 (T6.1) | +| `rex4/storage_call_stipend.rs` | 12 | 重写 12 (T3.3 · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | +| `rex5/apply_pending_changes_gas_budget.rs` | 4 | 重写 4 (T5.2 · D51 (system source m = 1; F1b reservoir split)) | +| `rex5/call_too_deep_guard.rs` | 4 | 保留 4 (T6.1 · T2.3 synthetic-result contract) | +| `rex5/callcode_storage_gas.rs` | 6 | 重写 3 (T3.2 · D12); 保留 3 (T3.2 · pricing-failure propagation) | +| `rex5/create2_empty_initcode.rs` | 5 | 保留 5 (T2.2 · canonical revm behaviour (differential harness)) | +| `rex5/create2_resize_gas_metering.rs` | 2 | 保留 2 (T2.2 · canonical behaviour) | +| `rex5/db_error.rs` | 4 | 重写 3 (T7 · native path surfaces DB errors); 保留 1 (T6.1) | +| `rex5/deposit_caller_accounting.rs` | 7 | 重写 7 (T6.1 · D16 (kept; must not double-charge with 2780)) | +| `rex5/deposit_create_storage_gas.rs` | 4 | 重写 4 (T3.2 · D12/D37) | +| `rex5/eip7702_metering.rs` | 4 | 重写 4 (T3.2 · D12/D45) | +| `rex5/eip7702_state_growth.rs` | 8 | 重写 8 (T4.3 · D28/D31/D45 (7702 authorization matrix)) | +| `rex5/frame_target_updated_dedup.rs` | 5 | 重写 5 (T2.3 · D50/D56 write-record layer) | +| `rex5/gas_validation.rs` | 4 | 重写 4 (T3.1 · D49/D55 (intrinsic state component; floor vs cap)) | +| `rex5/interceptor_selector_probe.rs` | 6 | 保留 6 (T6.1) | +| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | 保留 3 (T6.1) | +| `rex5/keyless_empty_code_logs.rs` | 2 | 重写 2 (T7 · native sub-frame keeps logs inherently) | +| `rex5/keyless_fee_free.rs` | 12 | 重写 8 (T7 · D16/D37/D38 (GASPRICE native; materialisation explicit)); 保留 4 (T7 · rules unchanged) | +| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | 重写 3 (T7 · native sub-frame gas handling) | +| `rex5/keyless_replay_barrier.rs` | 3 | 重写 3 (T7 · D36 (real nonce increment)) | +| `rex5/oracle_hint_metering.rs` | 9 | 保留 7 (T6.3 · D50 (hint not charged history; data-size metering kept)); 重写 1 (T6.3 · D11 intrinsic number); 重写 1 (T5.1 · D48) | +| `rex5/pre_block_system_calls.rs` | 11 | 保留 11 (T5.2) | +| `rex5/precompile_compute_gas.rs` | 3 | 重写 3 (T3.1 · D04/D40 (assert via gas_used)) | +| `rex5/sandbox_accounting.rs` | 9 | 重写 9 (T7 · native sub-frame: parent tracker sees child directly) | +| `rex5/selfdestruct_beneficiary.rs` | 7 | 重写 4 (T4.3 · D45 (state gas via new-account site)); 保留 2 (T4.2); 保留 1 (T4.1) | +| `rex5/sstore_storage_gas_error.rs` | 1 | 保留 1 (T3.2 · pricing-failure path) | +| `rex5/stipend_accounting.rs` | 6 | 重写 6 (T3.3 · D14 (history-only allowance lifecycle)) | +| `rex5/system_tx_replay.rs` | 12 | 保留 12 (T6.1) | +| `rex6/beneficiary_detention.rs` | 16 | 保留 13 (T4.2 · D08); 保留 2 (T4.1 · D50 write record 40 B); 重写 1 (T4.3 · D45) | +| `rex6/create2_metering_order.rs` | 11 | 保留 11 (T2.2 · canonical halt reasons; D04 512 KiB boundary) | +| `rex6/create_frame_accounting.rs` | 3 | 重写 2 (T2.3 · D50/D56 write-record layer); 保留 1 (T3.2) | +| `rex6/eip7702_authority_accounting.rs` | 18 | 重写 18 (T4.3 · D12/D28/D31/D45 (7702 matrix; T3.2 for the SALT half)) | +| `rex6/error_paths.rs` | 4 | 保留 2 (T3.2); 保留 2 (T2.2 · canonical) | +| `rex6/fee_reward_accounting.rs` | 6 | 重写 6 (T3.3 · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | +| `rex6/frame_local_accounting.rs` | 3 | 保留 3 (T4.1 · LOG base 32 unchanged) | +| `rex6/keyless_sandbox_hardening.rs` | 3 | 重写 1 (T7 · D44 / EIP-6780 native); 保留 2 (T7 · canonical CREATE rules) | +| `rex6/oracle_hint_volatile_access.rs` | 4 | 保留 4 (T6.3) | +| `rex6/self_transfer_account_dedup.rs` | 5 | 重写 4 (T2.3 · D50/D56); 保留 1 (T4.1) | +| `rex6/sequencer_registry_rotation.rs` | 6 | 保留 5 (T6.2); 保留 1 (T8.1 · params validation at load) | +| `rex6/system_tx_metering_exemption.rs` | 3 | 重写 3 (T3.2 · D51 (m = 1 for system source; history exempt)) | diff --git a/crates/mega-evm/tests/block_executor/accessed_block_hashes.rs b/crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/accessed_block_hashes.rs rename to crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs diff --git a/crates/mega-evm/tests/block_executor/block_limits.rs b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/block_limits.rs rename to crates/mega-evm/tests/_pending/block_executor/block_limits.rs diff --git a/crates/mega-evm/tests/block_executor/canonical_schedule.rs b/crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/canonical_schedule.rs rename to crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs diff --git a/crates/mega-evm/tests/block_executor/deposit_da_exemption.rs b/crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/deposit_da_exemption.rs rename to crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs diff --git a/crates/mega-evm/tests/block_executor/inspector.rs b/crates/mega-evm/tests/_pending/block_executor/inspector.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/inspector.rs rename to crates/mega-evm/tests/_pending/block_executor/inspector.rs diff --git a/crates/mega-evm/tests/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs similarity index 91% rename from crates/mega-evm/tests/block_executor/main.rs rename to crates/mega-evm/tests/_pending/block_executor/main.rs index 1ab0ed938..1d7f9b265 100644 --- a/crates/mega-evm/tests/block_executor/main.rs +++ b/crates/mega-evm/tests/_pending/block_executor/main.rs @@ -5,6 +5,5 @@ mod block_limits; mod canonical_schedule; mod deposit_da_exemption; mod inspector; -mod partial_ladder; mod sequencer_registry; mod trait_factory_runtime_limits; diff --git a/crates/mega-evm/tests/block_executor/sequencer_registry.rs b/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/sequencer_registry.rs rename to crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs diff --git a/crates/mega-evm/tests/block_executor/trait_factory_runtime_limits.rs b/crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/trait_factory_runtime_limits.rs rename to crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs diff --git a/crates/mega-evm/tests/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs similarity index 79% rename from crates/mega-evm/tests/compute_gas/claims.rs rename to crates/mega-evm/tests/_pending/compute_gas/claims.rs index 7f4fa05fe..6539fd31e 100644 --- a/crates/mega-evm/tests/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -146,53 +146,6 @@ fn test_interception_costs_the_same_as_a_plain_call() { } } -/// Spec: [Transaction Intrinsic Gas] — "A node MUST NOT include `MegaETH`'s intrinsic storage gas -/// additions ... in the recorded compute gas, even though both are added to the same intrinsic gas -/// total charged against the transaction's gas limit." -/// -/// Rex adds `TX_INTRINSIC_STORAGE_GAS` (39,000) on top of `MiniRex`'s intrinsic. With empty -/// calldata that flat charge is the *only* intrinsic difference between the two specs, so it -/// isolates cleanly: `gas_used` must rise by exactly 39,000 while `compute_gas` must not move at -/// all. -#[test] -fn test_intrinsic_compute_gas_excludes_megaeth_storage_gas() { - const TX_INTRINSIC_STORAGE_GAS: u64 = 39_000; - - // A bare transfer to an account that already exists: no code, no storage gas, no calldata. - let build = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_balance(EXISTING_TARGET, U256::from(ONE_ETH)) - }; - - let mini_rex = transact(MegaSpecId::MINI_REX, build()); - let rex = transact(MegaSpecId::REX, build()); - - assert_eq!( - mini_rex.compute_gas, rex.compute_gas, - "the 39,000 intrinsic storage gas must not enter compute gas (MiniRex={} Rex={})", - mini_rex.compute_gas, rex.compute_gas - ); - assert_eq!( - rex.gas_used.checked_sub(mini_rex.gas_used).unwrap_or_else(|| panic!( - "Rex must not charge less total gas than MiniRex (MiniRex={} Rex={})", - mini_rex.gas_used, rex.gas_used - )), - TX_INTRINSIC_STORAGE_GAS, - "Rex must charge exactly {TX_INTRINSIC_STORAGE_GAS} more total gas than MiniRex \ - (MiniRex={} Rex={})", - mini_rex.gas_used, - rex.gas_used - ); - assert!( - rex.gas_used > rex.compute_gas, - "the storage intrinsic must still be charged against the gas limit \ - (gas_used={} compute_gas={})", - rex.gas_used, - rex.compute_gas - ); -} - /// Spec: [Refund Exclusion] — "A node MUST NOT subtract EVM gas refunds from compute gas usage. /// Refunds affect final gas settlement but do not reduce the compute gas recorded during /// execution." @@ -249,41 +202,6 @@ fn test_refunds_do_not_reduce_compute_gas() { } } -/// Spec: [Precompiles] — "For a transaction whose recipient is a precompile, the invocation runs -/// before any call-frame budget exists", and the effective gas limit then reduces to the -/// transaction-level remaining compute gas, net of the recorded intrinsic gas. -/// -/// A direct transaction with empty calldata to the KZG precompile under a 30,000 tx compute -/// limit: the intrinsic records 21,000, leaving 9,000 of transaction-level remainder. The -/// forwarded cap is that remainder, which is below the precompile's 100,000 minimum cost, so the -/// invocation fails and records exactly the 9,000 cap — total recorded compute gas is exactly -/// the 30,000 limit. A cap that ignored the recorded intrinsic (forwarding 30,000) or one derived -/// from an undefined frame budget would shift the total away from the limit. -#[test] -fn test_direct_precompile_transaction_cap_is_the_tx_level_remainder() { - const TX_COMPUTE_LIMIT: u64 = 30_000; - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::REX5) { - continue; - } - let limits = - EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(TX_COMPUTE_LIMIT); - let (result, usage) = - transact_with_limits(spec, base_db(Bytes::new()), PRECOMPILE_KZG, limits); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "{spec_name}: the underfunded direct precompile transaction should halt, got \ - {result:?}" - ); - assert_eq!( - usage.compute_gas, TX_COMPUTE_LIMIT, - "{spec_name}: the no-frame cap must be the transaction-level remainder, so intrinsic \ - plus the recorded cap must equal the tx compute limit exactly" - ); - } -} - /// Spec: [Precompiles], the KZG branch — "`KZG_POINT_EVALUATION_GAS_COST`, when the invocation /// targeted the KZG point-evaluation precompile and its effective gas limit was at least /// `KZG_POINT_EVALUATION_GAS_COST`". @@ -385,94 +303,6 @@ fn corpus_program(name: &str) -> crate::Program { .unwrap_or_else(|| panic!("corpus must contain {name}")) } -/// Spec: [Forwarded Gas Exclusion] — "`forwarded_child_gas` MUST be the child frame's gas limit, -/// less the standard EVM `CALL_STIPEND` when all of the following hold: the spec is Rex5 or later, -/// the call scheme is `CALL` or `CALLCODE`, and the call transfers non-zero value." -/// -/// The snapshot records the resulting numbers but not the rule. This test states it: the exclusion -/// makes the parent record exactly `CALL_STIPEND` more compute gas from Rex5 onward, and only for -/// the qualifying scheme-and-value combination. Each of the rule's three conditions gets a -/// negative case, so dropping any one of them fails here. -#[test] -fn test_call_stipend_is_excluded_from_forwarded_gas_only_when_the_rule_applies() { - /// The inherited EVM's value-transfer call stipend. - const CALL_STIPEND: u64 = 2_300; - - let delta_rex4_to_rex5 = |name: &str| -> i64 { - let program = corpus_program(name); - let rex4 = transact(MegaSpecId::REX4, (program.build_db)()); - let rex5 = transact(MegaSpecId::REX5, (program.build_db)()); - assert_eq!(rex4.outcome, "success", "{name}: Rex4 run should succeed"); - assert_eq!(rex5.outcome, "success", "{name}: Rex5 run should succeed"); - rex5.compute_gas as i64 - rex4.compute_gas as i64 - }; - - // Qualifying: CALL and CALLCODE that transfer value. - for name in ["call_value_to_existing", "call_value_to_empty", "callcode_value"] { - assert_eq!( - delta_rex4_to_rex5(name), - CALL_STIPEND as i64, - "{name}: Rex5 must exclude CALL_STIPEND from the forwarded amount, making the parent \ - record exactly {CALL_STIPEND} more compute gas than Rex4" - ); - } - - // Non-qualifying by scheme: DELEGATECALL and STATICCALL never carry a stipend. - // Non-qualifying by value: a CALL with value == 0 does not receive one either. - for name in ["delegatecall", "staticcall", "call_no_value_to_code"] { - assert_eq!( - delta_rex4_to_rex5(name), - 0, - "{name}: does not satisfy the scheme-and-value condition, so Rex5 must record the \ - same compute gas as Rex4" - ); - } -} - -/// Spec: [Contract Creation Memory Expansion] — the three-way split of which window records -/// `CREATE2`'s wrapper-side memory-expansion gas (MiniRex–Rex4 second window skipped on inner -/// failure / Rex5 separate eager window / Rex6 folded into the single window). -/// -/// The split is observable only on the failure path, where the expansion happens but the inner -/// opcode never completes. On the success path all three arrangements must agree — that agreement -/// is the spec's claim that Rex6 is behavior-preserving there. -#[test] -fn test_create2_memory_expansion_window_differs_only_on_the_failure_path() { - let readings = |name: &str| { - let program = corpus_program(name); - [MegaSpecId::MINI_REX, MegaSpecId::REX4, MegaSpecId::REX5, MegaSpecId::REX6] - .map(|spec| transact(spec, (program.build_db)()).compute_gas) - }; - - // Success path: the window arrangement is unobservable, so every spec must agree. - let [succ_mini, succ_rex4, succ_rex5, succ_rex6] = readings("create2_with_initcode"); - assert_eq!( - [succ_mini, succ_rex4, succ_rex5], - [succ_rex6; 3], - "on the straight-line success path every spec must record the same CREATE2 compute gas \ - (MiniRex={succ_mini} Rex4={succ_rex4} Rex5={succ_rex5} Rex6={succ_rex6})" - ); - - // Failure path: the initcode is oversized, so the memory expansion runs but the inner opcode - // rejects. Only Rex5's eager recording captures the expansion. - let [fail_mini, fail_rex4, fail_rex5, fail_rex6] = readings("create2_oversized_initcode"); - assert_eq!( - fail_mini, fail_rex4, - "MiniRex and Rex4 both skip the trailing record when the inner opcode fails \ - (MiniRex={fail_mini} Rex4={fail_rex4})" - ); - assert_eq!( - fail_rex6, fail_rex4, - "Rex6 halts before the expansion, so it records the same as the specs that skip the \ - trailing record (Rex4={fail_rex4} Rex6={fail_rex6})" - ); - assert!( - fail_rex5 > fail_rex4, - "Rex5 records the memory-expansion gas eagerly, before the inner opcode rejects, so it \ - must record strictly more than the others (Rex4={fail_rex4} Rex5={fail_rex5})" - ); -} - /// Builds a caller that STATICCALLs `callee`, forwarding all available gas (`GAS`), and returns the /// callee's reported remaining gas as the transaction output. fn forwarding_probe() -> (Bytes, Bytes) { @@ -506,51 +336,6 @@ fn forwarding_probe() -> (Bytes, Bytes) { (caller, callee) } -/// Spec: [Forwarded Gas Exclusion] — "Under `MiniRex`, `CALLCODE`, `DELEGATECALL`, and `STATICCALL` -/// do not apply the 98/100 forwarding cap ... From Rex onward these three opcodes are subject to -/// the same forwarding cap as `CALL`." -/// -/// Without `MegaETH`'s cap, `STATICCALL` forwards the inherited EVM's 63/64 (98.4375%); with it, -/// the forwarded amount is capped at 98/100. Rex is therefore strictly stingier than `MiniRex`, and -/// the gap is large enough at this gas limit to be unambiguous. -/// -/// This pins the frozen `MiniRex` quirk: if a refactor ever "fixes" `MiniRex` by routing these -/// opcodes through the cap, replay for MiniRex-era blocks breaks, and this test fails. -#[test] -fn test_minirex_staticcall_is_not_subject_to_the_forwarding_cap() { - let (caller_code, callee_code) = forwarding_probe(); - let build = || base_db(caller_code.clone()).account_code(CALLEE, callee_code.clone()); - - let forwarded = |spec| { - let o = transact_output(spec, build()); - U256::from_be_slice(&o).to::() - }; - - let mini_rex = forwarded(MegaSpecId::MINI_REX); - let rex = forwarded(MegaSpecId::REX); - - assert!( - mini_rex > rex, - "MiniRex STATICCALL must forward more than Rex (uncapped 63/64 vs capped 98/100): \ - MiniRex={mini_rex} Rex={rex}" - ); - - // 63/64 = 98.4375%, 98/100 = 98%. Confirm each side lands on its own rule rather than merely - // differing, using the caller's pre-call remaining gas reconstructed from the forwarded amount. - let ratio_bp = |fwd: u64, base: u64| fwd * 10_000 / base; - let base = mini_rex * 64 / 63; // caller's remaining before the MiniRex forward - assert!( - (9_800..=9_850).contains(&ratio_bp(mini_rex, base)), - "MiniRex should forward ~63/64 (9843 bp), got {} bp", - ratio_bp(mini_rex, base) - ); - assert!( - (9_750..=9_805).contains(&ratio_bp(rex, base)), - "Rex should forward ~98/100 (9800 bp), got {} bp", - ratio_bp(rex, base) - ); -} - /// The inherited EVM's cold account access cost (EIP-2929). const COLD_ACCOUNT_ACCESS_COST: u64 = 2_600; /// The inherited EVM's warm account access cost (EIP-2929 `WARM_STORAGE_READ_COST`). diff --git a/crates/mega-evm/tests/compute_gas/main.rs b/crates/mega-evm/tests/_pending/compute_gas/main.rs similarity index 91% rename from crates/mega-evm/tests/compute_gas/main.rs rename to crates/mega-evm/tests/_pending/compute_gas/main.rs index 44b9904bf..970fb979d 100644 --- a/crates/mega-evm/tests/compute_gas/main.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/main.rs @@ -818,86 +818,6 @@ fn snapshot_path() -> std::path::PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/compute_gas/snapshot.txt") } -#[test] -fn test_compute_gas_snapshot_matches() { - let actual = render_snapshot(); - let path = snapshot_path(); - - if std::env::var_os("UPDATE_COMPUTE_GAS_SNAPSHOT").is_some() { - std::fs::write(&path, &actual).expect("failed to write snapshot"); - return; - } - - let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| { - panic!( - "missing snapshot at {}: {e}\n\ - Generate it with: UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas", - path.display() - ) - }); - - if actual != expected { - // Report the first differing line to keep the failure readable. - let diff = expected - .lines() - .zip(actual.lines()) - .enumerate() - .find(|(_, (e, a))| e != a) - .map(|(i, (e, a))| format!("line {}:\n expected: {e}\n actual: {a}", i + 1)) - .unwrap_or_else(|| "snapshots differ in length".to_string()); - panic!( - "compute-gas snapshot mismatch.\n{diff}\n\n\ - If this change is intentional, review it against docs/spec/evm/compute-gas.md and \ - regenerate with:\n UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas" - ); - } -} - -/// Rex7 is the unstable spec and carries no behavior of its own yet: it delegates its instruction -/// table, runtime limits, and precompile set to Rex6 unchanged. -/// -/// The snapshot alone does not pin this. Its rows differ by the spec-name column, so a Rex7 row -/// that drifted from its Rex6 counterpart would still render as a well-formed snapshot and could be -/// blessed by a regeneration. Comparing the readings directly makes the first accidental Rex7 -/// divergence a failure. When Rex7 gains its first deliberate behavior change, this test is -/// expected to fail and should be narrowed to the corpus entries that behavior does not reach. -#[test] -fn test_rex7_matches_rex6_on_every_program() { - for program in corpus() { - let rex6 = transact(MegaSpecId::REX6, (program.build_db)()); - let rex7 = transact(MegaSpecId::REX7, (program.build_db)()); - assert_eq!( - (rex7.compute_gas, rex7.gas_used, &rex7.outcome), - (rex6.compute_gas, rex6.gas_used, &rex6.outcome), - "{}: Rex7 must be behaviorally identical to Rex6 \ - (Rex6: compute_gas={} gas_used={} outcome={}; \ - Rex7: compute_gas={} gas_used={} outcome={})", - program.name, - rex6.compute_gas, - rex6.gas_used, - rex6.outcome, - rex7.compute_gas, - rex7.gas_used, - rex7.outcome, - ); - } -} - -/// Equivalence does not meter compute gas at all — no instruction wrappers, no precompile -/// recording. This is stated normatively in the spec's Overview; pin it directly so a wrapper -/// accidentally applied to the Equivalence table fails here rather than only shifting a number. -#[test] -fn test_equivalence_records_no_compute_gas() { - for program in corpus() { - let o = transact(MegaSpecId::EQUIVALENCE, (program.build_db)()); - assert_eq!( - o.compute_gas, 0, - "{}: Equivalence must not record compute gas, got {}", - program.name, o.compute_gas - ); - } -} - /// Compute gas is the sole non-revertible resource dimension: a child frame that reverts still /// contributes its consumption to the transaction total. #[test] diff --git a/crates/mega-evm/tests/equivalence/evm_state.rs b/crates/mega-evm/tests/_pending/equivalence/evm_state.rs similarity index 100% rename from crates/mega-evm/tests/equivalence/evm_state.rs rename to crates/mega-evm/tests/_pending/equivalence/evm_state.rs diff --git a/crates/mega-evm/tests/equivalence/main.rs b/crates/mega-evm/tests/_pending/equivalence/main.rs similarity index 100% rename from crates/mega-evm/tests/equivalence/main.rs rename to crates/mega-evm/tests/_pending/equivalence/main.rs diff --git a/crates/mega-evm/tests/mini_rex/access_beneficiary_balance.rs b/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/access_beneficiary_balance.rs rename to crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs diff --git a/crates/mega-evm/tests/mini_rex/block_env_access_tracking.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/block_env_access_tracking.rs rename to crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs diff --git a/crates/mega-evm/tests/mini_rex/block_env_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/block_env_gas_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs diff --git a/crates/mega-evm/tests/mini_rex/compute_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs similarity index 87% rename from crates/mega-evm/tests/mini_rex/compute_gas_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs index 7fd21894b..59a0a1598 100644 --- a/crates/mega-evm/tests/mini_rex/compute_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs @@ -232,47 +232,6 @@ fn test_compute_gas_limit_exceeded() { assert!(halt_actual > halt_limit); } -#[test] -fn test_compute_gas_refund_on_limit_exceeded() { - let mut bytecode = BytecodeBuilder::default(); - // Add many operations (need execution gas > 21,000 for validation) - for _ in 0..2000 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(10_000_000) // High tx gas limit for validation - .build_fill(); - - // First measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Compute gas tracks only opcode execution gas (intrinsic gas is reset after validation) - // 2000 iterations of (PUSH1 + PUSH1 + ADD + POP) = 2000 × 11 = 22,000 gas - assert!(actual_usage >= 22_000, "Expected at least 22,000 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Call with low compute gas limit just below actual usage - let limit = actual_usage - 1000; - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded, but remaining gas is refunded - assert!(is_compute_gas_limit_exceeded(&result)); - assert_eq!(compute_gas_used, result.result.gas_used()); - assert!(result.result.gas_used() < 43_000); -} - // ============================================================================ // INSTRUCTION COVERAGE TESTS // ============================================================================ @@ -658,101 +617,6 @@ fn test_compute_gas_limit_resets_after_volatile_access_rex1() { ); } -/// Test that compute gas limit is NOT reset between transactions in pre-Rex1 specs. -/// -/// Before Rex1, the compute gas limit was not reset between transactions. This test verifies -/// that the old behavior is preserved for backward compatibility: after accessing volatile data -/// (like oracle), the lowered compute gas limit persists to subsequent transactions. -#[test] -fn test_compute_gas_limit_not_reset_pre_rex1() { - use mega_evm::{ - constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, MegaTransaction, ORACLE_CONTRACT_ADDRESS, - }; - use revm::ExecuteEvm; - - // Contract 1: Calls the oracle, which lowers compute_gas_limit to 1M - let oracle_caller = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - // Contract 2: Expensive contract that uses >1M compute gas via SHA3 operations. - // In pre-Rex1, this will fail because the limit is stuck at 1M from oracle access. - let mut expensive_builder = BytecodeBuilder::default(); - expensive_builder = - expensive_builder.push_number(0xdeadbeefu32).push_number(0u8).append(MSTORE); - for _ in 0..30000 { - expensive_builder = - expensive_builder.push_number(32u8).push_number(0u8).append(KECCAK256).append(POP); - } - let expensive_contract = expensive_builder.append(STOP).build(); - - let compute_gas_limit: u64 = 10_000_000; // 10M - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_code(CONTRACT, oracle_caller) - .account_code(CONTRACT2, expensive_contract); - - // Use REX spec (pre-Rex1) where limits are NOT reset between transactions - let mut context = MegaContext::new(db, MegaSpecId::REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(compute_gas_limit) - .with_oracle_access_compute_gas_limit(ORACLE_ACCESS_COMPUTE_GAS), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - // TX1: Call oracle contract - this lowers compute_gas_limit to 1M - let tx1 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1).unwrap(); - assert!(result1.result.is_success(), "TX1 should succeed"); - - // Verify TX1 lowered the compute_gas_limit to oracle limit - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "TX1 should have lowered compute_gas_limit to oracle access limit" - ); - - // TX2: Expensive contract that uses >1M compute gas on the SAME EVM instance. - // In pre-Rex1, this should FAIL because the limit is stuck at 1M. - let tx2 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT2).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result2 = evm.transact_one(tx2).unwrap(); - - // TX2 should fail because the limit was NOT reset (pre-Rex1 behavior) - assert!( - !result2.is_success(), - "TX2 should fail in pre-Rex1 because compute_gas_limit was NOT reset. \ - The limit should be stuck at {} from oracle access in TX1", - ORACLE_ACCESS_COMPUTE_GAS - ); - - // Verify the limit is still at the lowered oracle limit (not reset) - let actual_limit = evm.ctx_ref().additional_limit.borrow().compute_gas_limit(); - assert_eq!( - actual_limit, ORACLE_ACCESS_COMPUTE_GAS, - "compute_gas_limit should still be at oracle limit ({}) in pre-Rex1, not reset to {}", - ORACLE_ACCESS_COMPUTE_GAS, compute_gas_limit - ); -} - // ============================================================================ // SPEC COMPARISON TESTS // ============================================================================ @@ -781,32 +645,6 @@ fn test_compute_gas_tracked_in_mini_rex() { assert!(compute_gas_used > 0); } -#[test] -fn test_compute_gas_not_tracked_in_equivalence() { - let bytecode = BytecodeBuilder::default() - .append(PUSH1) - .append(1) - .append(PUSH1) - .append(2) - .append(ADD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::EQUIVALENCE, &mut db, 10_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // In EQUIVALENCE, compute gas should NOT be tracked - assert_eq!(compute_gas_used, 0); -} - // ============================================================================ // PRECOMPILE TESTS // ============================================================================ diff --git a/crates/mega-evm/tests/mini_rex/contract_size_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs similarity index 81% rename from crates/mega-evm/tests/mini_rex/contract_size_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs index 02b14ec19..fb6da8fc2 100644 --- a/crates/mega-evm/tests/mini_rex/contract_size_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs @@ -43,26 +43,6 @@ fn initcode_size_limit_test_case(spec: MegaSpecId, initcode_size: usize, success } } -/// Test that verifies `EQUIVALENCE` spec allows deployment with EIP-3860 max initcode size. -#[test] -fn test_equivalence_eip3860_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip3860::MAX_INITCODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects deployment with `MiniRex` max initcode size. -#[test] -fn test_equivalence_minirex_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - constants::mini_rex::MAX_INITCODE_SIZE, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows deployment with EIP-3860 max initcode size. #[test] fn test_minirex_eip3860_max_initcode_size() { @@ -137,26 +117,6 @@ fn contract_size_limit_test_case(spec: MegaSpecId, contract_size: usize, success } } -/// Test that verifies `EQUIVALENCE` spec allows deployment with EIP-170 max code size. -#[test] -fn test_equivalence_eip170_max_code_size() { - contract_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects deployment with `MiniRex` max contract size. -#[test] -fn test_equivalence_minirex_max_contract_size() { - contract_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - constants::mini_rex::MAX_CONTRACT_SIZE, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows deployment with EIP-170 max code size. #[test] fn test_minirex_eip170_max_code_size() { @@ -252,26 +212,6 @@ fn contract_factory_code_size_limit_test_case( } } -/// Test that verifies `EQUIVALENCE` spec allows CREATE opcode with EIP-170 max code size. -#[test] -fn test_equivalence_create_eip170_max_code_size() { - contract_factory_code_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects CREATE opcode with EIP-170 max code size + 1. -#[test] -fn test_equivalence_create_eip170_max_code_size_plus_one() { - contract_factory_code_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE + 1, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows CREATE opcode with EIP-170 max code size. #[test] fn test_minirex_create_eip170_max_code_size() { diff --git a/crates/mega-evm/tests/mini_rex/db_error.rs b/crates/mega-evm/tests/_pending/mini_rex/db_error.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/db_error.rs rename to crates/mega-evm/tests/_pending/mini_rex/db_error.rs diff --git a/crates/mega-evm/tests/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs similarity index 80% rename from crates/mega-evm/tests/mini_rex/gas.rs rename to crates/mega-evm/tests/_pending/mini_rex/gas.rs index 249d00cbe..ce85a7c4d 100644 --- a/crates/mega-evm/tests/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -193,17 +193,6 @@ fn test_sstore_clear_with_bucket_expansion() { sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Clear, 1, 21_206); } -/// Tests SSTORE uses standard EVM gas costs in equivalence spec, not `MegaETH`'s increased costs. -#[test] -fn test_sstore_gas_unchanged_in_equivalence_spec() { - sstore_test_case( - MegaSpecId::EQUIVALENCE, - UpdateMode::Set, - 0, - 21_006 + constants::equivalence::SSTORE_SET + constants::equivalence::COLD_SLOAD_COST, - ); -} - /// Tests EIP-2929: First SSTORE to a slot charges cold access penalty (2100 gas), subsequent /// SSTOREs to the same slot in the same transaction use warm pricing. #[test] @@ -332,12 +321,6 @@ fn test_ether_transfer_to_existent_account() { ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 21_000); } -/// Tests ether transfer uses standard EVM gas costs in equivalence spec. -#[test] -fn test_ether_transfer_gas_unchanged_in_equivalence_spec() { - ether_transfer_test_case(MegaSpecId::EQUIVALENCE, UpdateMode::Reset, 0, 21_000); -} - /// Executes a nested ether transfer test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -429,12 +412,6 @@ fn test_nested_ether_transfer_to_existent_account() { nested_ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 30_316); } -/// Tests nested ether transfer uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_ether_transfer_gas_unchanged_in_equivalence_spec() { - nested_ether_transfer_test_case(MegaSpecId::EQUIVALENCE, UpdateMode::Reset, 0, 30_316); -} - /// Executes a create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -496,12 +473,6 @@ fn test_create_contract_to_non_existent_account_with_bucket_expansion() { ); } -/// Tests CREATE uses standard EVM gas costs in equivalence spec. -#[test] -fn test_create_contract_gas_unchanged_in_equivalence_spec() { - create_contract_test_case(MegaSpecId::EQUIVALENCE, 0, 53_554); -} - /// Executes a nested create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -597,17 +568,6 @@ fn test_nested_create_contract_to_non_existent_account_with_bucket_expansion() { ); } -/// Tests nested CREATE uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_create_contract_gas_unchanged_in_equivalence_spec() { - nested_create_contract_test_case( - MegaSpecId::EQUIVALENCE, - false, - 0, - 21_255 + constants::equivalence::CREATE, - ); -} - /// Tests nested CREATE2 charges `CREATE_GAS` plu`NEW_ACCOUNT_GAS`AS plus KECCAK256 cost. #[test] fn test_nested_create2_contract_to_non_existent_account() { @@ -636,17 +596,6 @@ fn test_nested_create2_contract_to_non_existent_account_with_bucket_expansion() ); } -/// Tests nested CREATE2 uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_create2_contract_gas_unchanged_in_equivalence_spec() { - nested_create_contract_test_case( - MegaSpecId::EQUIVALENCE, - true, - 0, - 21_270 + constants::equivalence::CREATE, - ); -} - /// Executes a calldata test case, verifying gas usage for calldata scenarios. /// /// # Arguments @@ -675,21 +624,6 @@ fn calldata_test_case(spec: MegaSpecId, expected_gas_ assert_eq!(gas_used, expected_gas_used); } -/// Tests calldata charges additional per-byte cost in `MegaETH` (100x standard cost). -#[test] -fn test_calldata_additional_cost() { - calldata_test_case::<1024>( - MegaSpecId::MINI_REX, - 133_640, // 21,000 base + 110 gas/byte × 1,024 bytes (10 intrinsic + 100 storage floor) - ); -} - -/// Tests calldata uses standard EVM gas costs in equivalence spec. -#[test] -fn test_calldata_no_additional_cost_in_equivalence_spec() { - calldata_test_case::<1024>(MegaSpecId::EQUIVALENCE, 31_240); -} - /// Executes a log test case, verifying gas usage for log scenarios. /// /// # Arguments @@ -730,23 +664,6 @@ fn log_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests LOG charges additional per-byte and per-topic cost in `MegaETH` (100x standard cost). -#[test] -fn test_log_additional_cost() { - log_test_case::<1, 1024>( - MegaSpecId::MINI_REX, - 30_049 + - constants::mini_rex::LOG_TOPIC_STORAGE_GAS + - constants::mini_rex::LOG_DATA_STORAGE_GAS * 1024, - ); -} - -/// Tests LOG uses standard EVM gas costs in equivalence spec. -#[test] -fn test_log_no_additional_cost_in_equivalence_spec() { - log_test_case::<1, 1024>(MegaSpecId::EQUIVALENCE, 30_049); -} - /// Executes a gas forward test case, verifying gas usage for gas forwarding scenarios. /// /// # Arguments @@ -849,18 +766,6 @@ fn test_gas_forward_to_create_in_mini_rex() { gas_forward_test_case(MegaSpecId::MINI_REX, true, 1_003_520_000); } -/// Tests gas forwarding to CALL uses standard 63/64 rule in equivalence spec. -#[test] -fn test_gas_forward_to_call_in_equivalence_spec() { - gas_forward_test_case(MegaSpecId::EQUIVALENCE, false, 1_008_000_000); -} - -/// Tests gas forwarding to CREATE uses standard 63/64 rule in equivalence spec. -#[test] -fn test_gas_forward_to_create_in_equivalence_spec() { - gas_forward_test_case(MegaSpecId::EQUIVALENCE, true, 1_008_000_000); -} - /// Executes a floor gas test case, verifying gas usage includes additional floor gas costs. /// /// # Arguments @@ -905,13 +810,6 @@ fn test_floor_gas_large_calldata_mini_rex() { floor_gas_test_case(MegaSpecId::MINI_REX, 1024, 471_560); } -/// Tests floor gas is not charged in EQUIVALENCE spec. -#[test] -fn test_floor_gas_no_additional_cost_in_equivalence_spec() { - // Test with 100 bytes of calldata - should not include additional floor gas - floor_gas_test_case(MegaSpecId::EQUIVALENCE, 100, 25_000); -} - /// Tests floor gas with empty calldata (edge case). #[test] fn test_floor_gas_empty_calldata() { @@ -924,96 +822,3 @@ fn test_floor_gas_minimal_calldata() { floor_gas_test_case(MegaSpecId::MINI_REX, 1, 21_440); } -/// Tests that insufficient gas for account creation storage gas results in OOG (not invalid tx). -/// This transaction has enough gas for intrinsic costs but not for account creation storage. -#[test] -fn test_mini_rex_insufficient_storage_gas_for_new_account_oog() { - use mega_evm::SaltEnv; - use std::convert::Infallible; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - let new_account = address!("9000000000000000000000000000000000000009"); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(new_account); - let multiplier = 10u64; - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * multiplier); - - // MiniRex account creation storage gas: 2,000,000 × 10 = 20,000,000 - // Intrinsic: 21,000 - // Set gas limit to cover intrinsic but not storage: 22,000 - let insufficient_gas_limit = 22_000; - - // Override gas limit in the test - let mut context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(new_account), - data: Bytes::new(), - value: U256::from(1), - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Transaction should succeed but execution should be OOG - assert!(!res.result.is_success()); - assert!(res.result.is_halt()); - assert_eq!(res.result.gas_used(), insufficient_gas_limit); -} - -/// Tests that insufficient gas for contract creation storage gas results in OOG (not invalid tx). -#[test] -fn test_mini_rex_insufficient_storage_gas_for_contract_creation_oog() { - use mega_evm::SaltEnv; - use std::convert::Infallible; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - // Empty init code to minimize calldata gas - let init_code = Bytes::new(); - let created_address = CALLER.create(0); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(created_address); - let multiplier = 10u64; - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * multiplier); - - // MiniRex contract creation storage gas: 2,000,000 × 10 = 20,000,000 - // Base intrinsic for CREATE: 21,000 + 32,000 (CREATE base) = 53,000 - // Set gas limit to cover intrinsic but not storage: 60,000 - let insufficient_gas_limit = 60_000; - - let mut context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Create, - data: init_code, - value: U256::ZERO, - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Transaction should succeed but execution should be OOG - assert!(!res.result.is_success()); - assert!(res.result.is_halt()); - assert_eq!(res.result.gas_used(), insufficient_gas_limit); -} diff --git a/crates/mega-evm/tests/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs similarity index 91% rename from crates/mega-evm/tests/mini_rex/main.rs rename to crates/mega-evm/tests/_pending/mini_rex/main.rs index aee27a700..eb146393a 100644 --- a/crates/mega-evm/tests/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -6,7 +6,6 @@ mod block_env_gas_limit; mod compute_gas_limit; mod contract_size_limit; mod db_error; -mod disallow_selfdestruct; mod gas; mod mega_system_transaction; mod oracle; diff --git a/crates/mega-evm/tests/mini_rex/mega_system_transaction.rs b/crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/mega_system_transaction.rs rename to crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs diff --git a/crates/mega-evm/tests/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs similarity index 78% rename from crates/mega-evm/tests/mini_rex/oracle.rs rename to crates/mega-evm/tests/_pending/mini_rex/oracle.rs index 481f463e7..ad81f9376 100644 --- a/crates/mega-evm/tests/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -78,158 +78,6 @@ fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool ) } -/// Test that calling the oracle contract is detected. -#[test] -fn test_oracle_access_detected_on_call() { - // Create bytecode that calls the oracle contract - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "Compute gas limit should be set to oracle access limit" - ); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - -/// Test that calling a non-oracle contract is not detected as oracle access. -#[test] -fn test_oracle_access_not_detected_on_regular_call() { - const OTHER_CONTRACT: alloy_primitives::Address = - address!("3000000000000000000000000000000000000003"); - - // Create bytecode that calls a different contract (not oracle) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(OTHER_CONTRACT) // callee: some other contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected"); -} - -/// Test that oracle access is not detected when no CALL is made. -#[test] -fn test_oracle_access_not_detected_without_call() { - // Simple bytecode that doesn't call anything - let bytecode = BytecodeBuilder::default().push_number(42u8).stop().build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected"); -} - -/// Test that oracle access is NOT detected in EQUIVALENCE spec (uses standard CALL). -/// Oracle detection only works in `MINI_REX` spec with custom CALL instruction. -#[test] -fn test_oracle_access_not_detected_in_equivalence_spec() { - // Create bytecode that calls the oracle contract - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - // Oracle detection only works in MINI_REX spec, not EQUIVALENCE - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = execute_transaction( - MegaSpecId::EQUIVALENCE, - &mut db, - &external_envs, - NoOpInspector, - CALLEE, - ); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected in EQUIVALENCE spec"); -} - -/// Test that oracle access is detected with explicit 0 value parameter. -#[test] -fn test_oracle_access_detected_with_explicit_zero_value() { - // Create bytecode that calls the oracle contract with explicit 0 wei value - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei (explicit) - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - -/// Test that multiple calls to oracle are still tracked (should not fail). -#[test] -fn test_oracle_access_detected_on_multiple_calls() { - // Create bytecode that calls the oracle contract twice - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args again - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract again - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - /// Test that contract runs out of gas when trying to execute expensive operations after oracle /// access. #[test] @@ -995,80 +843,3 @@ fn test_mega_system_address_exempted_from_oracle_tracking() { ); } -/// Test that STATICCALL to oracle is NOT detected in MiniRex. -/// -/// In MiniRex, STATICCALL bypasses oracle access detection along with CALLCODE and -/// DELEGATECALL. Rex fixes this by adding STATICCALL to the detection path. -#[test] -fn test_mini_rex_staticcall_oracle_access_not_detected() { - // STATICCALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(STATICCALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "STATICCALL to oracle should not be detected in MiniRex"); -} - -/// Test that DELEGATECALL to oracle is NOT detected in MiniRex. -/// -/// DELEGATECALL sets `target_address` to the caller's own address (not oracle), so the oracle -/// detection check in `frame_init` does not match. -#[test] -fn test_mini_rex_delegatecall_oracle_access_not_detected() { - // DELEGATECALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(DELEGATECALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "DELEGATECALL to oracle should not be detected in MiniRex"); -} - -/// Test that CALLCODE to oracle is NOT detected in MiniRex. -/// -/// CALLCODE sets `target_address` to the caller's own address (not oracle), so the oracle -/// detection check in `frame_init` does not match. -#[test] -fn test_mini_rex_callcode_oracle_access_not_detected() { - // CALLCODE: gas, addr, value, argsOff, argsLen, retOff, retLen (7 args) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff, value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALLCODE) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "CALLCODE to oracle should not be detected in MiniRex"); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs new file mode 100644 index 000000000..e7af3b48f --- /dev/null +++ b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs @@ -0,0 +1,221 @@ +//! Tests for the state growth limit feature of the `MegaETH` EVM. +//! +//! These tests verify that the state growth limit functionality correctly tracks and limits +//! the creation of new accounts and storage slots during transaction execution. + +use std::convert::Infallible; + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + MegaTransactionError, +}; +use revm::{ + bytecode::opcode::*, + context::{ + result::{EVMError, ExecutionResult, ResultAndState}, + tx::TxEnvBuilder, + TxEnv, + }, + handler::EvmTr, + Database, DatabaseCommit, +}; + +// Test addresses +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0000000000000000000000000000000000100001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); +const NEW_ACCOUNT: Address = address!("0000000000000000000000000000000000100003"); + +// ============================================================================ +// HELPER FUNCTIONS +// ============================================================================ + +/// Executes a transaction with specified state growth limit. +/// +/// Returns the execution result and the actual state growth used. +fn transact( + spec: MegaSpecId, + db: &mut MemoryDatabase, + state_growth_limit: u64, + tx: TxEnv, +) -> Result<(ResultAndState, u64), EVMError> { + let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), + ); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; + + let ctx = evm.ctx_ref(); + let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; + Ok((r, state_growth)) +} + +/// Checks if the execution result indicates that the state growth limit was exceeded. +fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { + matches!( + &result.result, + ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } + ) +} + +/// Creates a default transaction builder calling a contract. +fn default_tx_builder(to: Address) -> TxEnvBuilder { + TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) +} + +// ============================================================================ +// BASIC STATE GROWTH TRACKING TESTS +// ============================================================================ + +// ============================================================================ +// NET GROWTH MODEL TESTS +// ============================================================================ + +// ============================================================================ +// FRAME-BASED TRACKING TESTS +// ============================================================================ + +// ============================================================================ +// LIMIT ENFORCEMENT TESTS +// ============================================================================ + +#[test] +fn test_limit_exactly_at_limit() { + // Create exactly 3 slots with limit of 3 + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .sstore(U256::from(2), U256::from(3)) // +1 + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_success()); + assert_eq!(state_growth, 3, "Exactly at limit should succeed"); +} + +#[test] +fn test_limit_exceeded_by_one() { + // Try to create 4 slots with limit of 3 + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .sstore(U256::from(2), U256::from(3)) // +1 + .sstore(U256::from(3), U256::from(4)) // +1 (exceeds limit) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); + + // Verify the halt reason details - the actual growth is preserved in the halt reason + match &result.result { + ExecutionResult::Halt { + reason: MegaHaltReason::StateGrowthLimitExceeded { limit, actual }, + .. + } => { + assert_eq!(*limit, 3); + assert_eq!(*actual, 4, "Should report actual growth that exceeded limit"); + } + _ => panic!("Expected StateGrowthLimitExceeded halt"), + } +} + +#[test] +fn test_limit_exceeded_in_nested_call() { + // Child creates 2 slots + let child_code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .stop() + .build(); + + // Parent creates 2 slots, then calls child (total would be 4, limit is 3) + let parent_code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(0_u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(CONTRACT) // child address + .push_number(10_000_000_u64) // gas + .append(CALL) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, parent_code) + .account_code(CONTRACT, child_code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); +} + +#[test] +fn test_state_reverted_when_exceeding_limit() { + // Create 2 slots, then exceed limit on 3rd (with limit of 2) + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(100)) // +1 + .sstore(U256::from(1), U256::from(200)) // +1 + .sstore(U256::from(2), U256::from(300)) // +1 (exceeds) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); + + // State should not be committed + db.commit(result.state); + + // Verify the storage was not persisted + let storage_0 = db.storage(CALLEE, U256::from(0)).unwrap(); + let storage_1 = db.storage(CALLEE, U256::from(1)).unwrap(); + let storage_2 = db.storage(CALLEE, U256::from(2)).unwrap(); + + assert_eq!(storage_0, U256::ZERO, "Storage should be reverted"); + assert_eq!(storage_1, U256::ZERO, "Storage should be reverted"); + assert_eq!(storage_2, U256::ZERO, "Storage should be reverted"); +} + +// ============================================================================ +// COMPLEX SCENARIOS TESTS +// ============================================================================ + +// ============================================================================ +// TRACKER MIGRATION COVERAGE TESTS +// ============================================================================ + diff --git a/crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs similarity index 82% rename from crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs index ceb11ef87..ba3ca221c 100644 --- a/crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs @@ -640,23 +640,6 @@ fn test_nested_creation_revert() { // SPEC COMPARISON TESTS // ============================================================================ -/// Test that data size and KV update counts are not measured in EQUIVALENCE spec. -/// -/// This test verifies that when using the EQUIVALENCE spec, the data size and -/// KV update counting functionality is disabled. This ensures that the EQUIVALENCE -/// spec behaves like standard Ethereum without the additional data limit tracking -/// that is present in the `MINI_REX` spec. -#[test] -fn test_data_size_and_kv_update_count_are_not_measured_in_equivalence_spec() { - let mut db = MemoryDatabase::default(); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::EQUIVALENCE, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - assert_eq!(kv_update_count, 0); - assert_eq!(data_size, 0); -} - // ============================================================================ // LIMIT ENFORCEMENT TESTS // ============================================================================ @@ -1003,173 +986,6 @@ fn test_limits_reset_across_multiple_transactions() { // GAS PRESERVATION TESTS // ============================================================================ -/// Test that remaining gas is preserved (not consumed) when data limit is exceeded. -/// -/// This test verifies that when a transaction exceeds the data limit, the remaining -/// gas is refunded to the sender rather than being consumed as a penalty. This ensures -/// fair gas accounting where users only pay for work actually performed. -#[test] -fn test_data_limit_exceeded_preserves_remaining_gas() { - let mut db = MemoryDatabase::default(); - - // Simple contract with one SSTORE - let code = BytecodeBuilder::default() - .push_number(1u8) - .push_number(0u8) - .append(SSTORE) - .append(STOP) - .build(); - - db.set_account_code(CALLEE, code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Run with limit that will be exceeded - // Base tx + caller update + storage slot write - 1 (just under minimum needed) - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Verify the transaction halted due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify gas accounting - remaining gas should be significant - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Most gas should remain since we barely started execution - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining (transaction barely started), but got {}", - gas_remaining - ); -} - -/// Test that remaining gas is preserved when KV update limit is exceeded. -/// -/// This verifies that KV limit violations don't consume all gas as penalty, -/// but rather preserve the remaining gas for refund to the sender. -#[test] -fn test_kv_update_limit_exceeded_preserves_remaining_gas() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - - // Value transfer creates 2 KV updates (caller and callee account updates) - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CALLEE) - .value(U256::from(1)) - .gas_limit(1_000_000_000) - .build_fill(); - - // Set KV limit to 1 (will exceed on the 2nd update) - let (result, _, _) = transact( - MegaSpecId::MINI_REX, - &mut db, - u64::MAX, - 2 - 1, // Same as test_kv_update_limit_just_exceed - tx, - ) - .unwrap(); - - // Verify the transaction halted due to KV limit - assert!(is_kv_update_limit_exceeded(&result), "Expected KV update limit exceeded"); - - // Verify gas accounting - most gas should remain - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Transaction barely started before hitting limit - assert!( - gas_remaining > 997_000_000, - "Expected >997m gas remaining (transaction barely started), but got {}", - gas_remaining - ); -} - -/// Test that remaining gas is preserved when data limit is exceeded in a nested call. -/// -/// This test verifies that when a nested call exceeds the data limit: -/// 1. The nested call preserves its remaining gas -/// 2. The parent call also preserves its remaining gas -/// 3. Both amounts are refunded to the transaction sender -#[test] -fn test_nested_call_data_limit_exceeded_preserves_gas() { - let mut db = MemoryDatabase::default(); - - // Parent contract that calls library - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // value, argOffset, argLen, returnOffset, returnLen - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - - // Library that does SLOAD and SSTORE - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SLOAD, SSTORE, STOP]).build(); - db.set_account_code(LIBRARY, library_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Same limit as test_data_limit_exceed_in_nested_call - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Verify halt due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify significant gas remains from both parent and child - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Should have most of the gas remaining (stopped very early) - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining in nested call scenario, got {}", - gas_remaining - ); -} - -/// Test that gas is correctly preserved across multiple limit-exceeding operations. -/// -/// This test creates a scenario with multiple operations that exceed limits, -/// verifying that gas accounting remains correct throughout. -#[test] -fn test_multiple_operations_with_limit_exceeded_preserves_gas() { - let mut db = MemoryDatabase::default(); - - // Contract that does a few SSTOREs - let code = BytecodeBuilder::default() - .push_number(1u8) - .push_number(0u8) - .append(SSTORE) - .push_number(2u8) - .push_number(1u8) - .append(SSTORE) - .push_number(3u8) - .push_number(2u8) - .append(SSTORE) - .append(STOP) - .build(); - - db.set_account_code(CALLEE, code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Set limit to allow: base tx + caller update + only 1 storage write - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Should halt due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify gas is preserved - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Should have significant gas remaining (stopped after 1 write instead of 3) - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining with multiple operations, got {}", - gas_remaining - ); -} - // ============================================================================ // TRACKER MIGRATION COVERAGE TESTS // ============================================================================ @@ -1347,100 +1163,3 @@ impl Inspector for GasSpendingInspector { } } -/// Test that `rescue_gas` correctly preserves remaining gas when an inspector calls -/// `spend_all()` in `call_end`, for the `inspect_frame_init` early-return path. -/// -/// The KV limit is exceeded in `before_frame_init` (value transfer creates 2 KV updates -/// but limit is 1), so `frame_init` returns an error result immediately. `try_rescue_gas` -/// captures the gas before `frame_end` → `call_end` fires on the inspector. -/// Without the fix, the inspector's `spend_all()` would zero the gas before rescue. -#[test] -fn test_rescue_gas_with_gas_spending_inspector_frame_init() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CALLEE) - .value(U256::from(1)) - .gas_limit(1_000_000_000) - .build_fill(); - - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(2 - 1), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut inspector = GasSpendingInspector; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(is_kv_update_limit_exceeded(&result), "Expected KV update limit exceeded"); - - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 997_000_000, - "Expected >997m gas remaining (rescue_gas should capture gas before inspector spend_all), got {}", - gas_remaining - ); -} - -/// Test that `rescue_gas` correctly preserves remaining gas when an inspector calls -/// `spend_all()` in `call_end`, for the `inspect_frame_run` path. -/// -/// The data limit is exceeded during SSTORE execution inside a nested call. -/// `after_frame_run` rescues gas, then `frame_end` → `call_end` fires on the inspector. -/// Without the fix, the inspector's `spend_all()` would zero the gas before rescue. -#[test] -fn test_rescue_gas_with_gas_spending_inspector_frame_run() { - let mut db = MemoryDatabase::default(); - - // Parent contract that calls a library - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(LIBRARY) - .append(GAS) - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - - // Library that does SSTORE, which will exceed the data limit - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SSTORE, STOP]).build(); - db.set_account_code(LIBRARY, library_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Set data limit tight enough that SSTORE exceeds it - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(tight_limit) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut inspector = GasSpendingInspector; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining (rescue_gas should capture gas before inspector spend_all), got {}", - gas_remaining - ); -} diff --git a/crates/mega-evm/tests/mutation/access_evm.rs b/crates/mega-evm/tests/_pending/mutation/access_evm.rs similarity index 100% rename from crates/mega-evm/tests/mutation/access_evm.rs rename to crates/mega-evm/tests/_pending/mutation/access_evm.rs diff --git a/crates/mega-evm/tests/mutation/block.rs b/crates/mega-evm/tests/_pending/mutation/block.rs similarity index 100% rename from crates/mega-evm/tests/mutation/block.rs rename to crates/mega-evm/tests/_pending/mutation/block.rs diff --git a/crates/mega-evm/tests/mutation/constants.rs b/crates/mega-evm/tests/_pending/mutation/constants.rs similarity index 76% rename from crates/mega-evm/tests/mutation/constants.rs rename to crates/mega-evm/tests/_pending/mutation/constants.rs index 904d37882..9e9cf316c 100644 --- a/crates/mega-evm/tests/mutation/constants.rs +++ b/crates/mega-evm/tests/_pending/mutation/constants.rs @@ -47,25 +47,6 @@ fn test_mini_rex_block_data_limit() { assert_eq!(mini_rex::BLOCK_DATA_LIMIT, 13_107_200); } -/// Pins `mini_rex::TX_DATA_LIMIT` (`BLOCK_DATA_LIMIT * 25 / 100`, 25% of block). -/// -/// Kills `constants.rs:62:58 replace / with *` and `:62:53 replace * with +`. -#[test] -fn test_mini_rex_tx_data_limit() { - assert_eq!(mini_rex::TX_DATA_LIMIT, mini_rex::BLOCK_DATA_LIMIT * 25 / 100); - assert_eq!(mini_rex::TX_DATA_LIMIT, 3_276_800); -} - -/// Pins `mini_rex::TX_KV_UPDATE_LIMIT` -/// (`BLOCK_KV_UPDATE_LIMIT * 25 / 100`, 25% of block). -/// -/// Kills `constants.rs:68:68 replace / with *` and `:68:63 replace * with +`. -#[test] -fn test_mini_rex_tx_kv_update_limit() { - assert_eq!(mini_rex::TX_KV_UPDATE_LIMIT, mini_rex::BLOCK_KV_UPDATE_LIMIT * 25 / 100); - assert_eq!(mini_rex::TX_KV_UPDATE_LIMIT, 125_000); -} - /// Pins `rex::TX_DATA_LIMIT` (`12 * 1024 * 1024 + 512 * 1024`, same as the /// block data limit). /// diff --git a/crates/mega-evm/tests/mutation/external_exec.rs b/crates/mega-evm/tests/_pending/mutation/external_exec.rs similarity index 100% rename from crates/mega-evm/tests/mutation/external_exec.rs rename to crates/mega-evm/tests/_pending/mutation/external_exec.rs diff --git a/crates/mega-evm/tests/mutation/main.rs b/crates/mega-evm/tests/_pending/mutation/main.rs similarity index 99% rename from crates/mega-evm/tests/mutation/main.rs rename to crates/mega-evm/tests/_pending/mutation/main.rs index b7478369f..15ef02a6f 100644 --- a/crates/mega-evm/tests/mutation/main.rs +++ b/crates/mega-evm/tests/_pending/mutation/main.rs @@ -46,4 +46,3 @@ mod access_evm; mod block; mod constants; mod external_exec; -mod limit; diff --git a/crates/mega-evm/tests/rex/main.rs b/crates/mega-evm/tests/_pending/rex/main.rs similarity index 76% rename from crates/mega-evm/tests/rex/main.rs rename to crates/mega-evm/tests/_pending/rex/main.rs index 2706ccd5e..f474f301d 100644 --- a/crates/mega-evm/tests/rex/main.rs +++ b/crates/mega-evm/tests/_pending/rex/main.rs @@ -1,5 +1,3 @@ //! Tests for Rex hardfork features. - -mod intrinsic_gas; mod oracle; mod storage_gas; diff --git a/crates/mega-evm/tests/rex/oracle.rs b/crates/mega-evm/tests/_pending/rex/oracle.rs similarity index 100% rename from crates/mega-evm/tests/rex/oracle.rs rename to crates/mega-evm/tests/_pending/rex/oracle.rs diff --git a/crates/mega-evm/tests/rex/storage_gas.rs b/crates/mega-evm/tests/_pending/rex/storage_gas.rs similarity index 93% rename from crates/mega-evm/tests/rex/storage_gas.rs rename to crates/mega-evm/tests/_pending/rex/storage_gas.rs index 7042dd19f..a9455333d 100644 --- a/crates/mega-evm/tests/rex/storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex/storage_gas.rs @@ -557,58 +557,6 @@ fn test_combined_contract_creation_and_sstore() { assert_eq!(gas_used, expected_total); } -#[test] -fn test_rex_vs_minirex_comparison() { - // Compare REX vs Mini-Rex storage gas costs - // Mini-Rex: 2,000,000 × multiplier - // REX: base × (multiplier - 1) where base is 20k/25k/32k - - let mut db_rex = MemoryDatabase::default(); - let mut db_minirex = MemoryDatabase::default(); - - db_rex.set_account_balance(CALLER, U256::from(10_000_000_000_000u64)); - db_minirex.set_account_balance(CALLER, U256::from(10_000_000_000_000u64)); - - let multiplier = 10u64; - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - // Account creation comparison - let rex_result = transact( - MegaSpecId::REX, - &mut db_rex, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000_000, - ) - .expect("REX transaction should succeed"); - - let minirex_result = transact( - MegaSpecId::MINI_REX, - &mut db_minirex, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000_000, - ) - .expect("Mini-Rex transaction should succeed"); - - // REX should charge less for dynamic operations but has higher intrinsic - // REX: 21k + 39k + 25k×(10-1) = 285k - // Mini-Rex: 21k + 0 + 2M×10 = 20,021k - assert!( - rex_result.result.gas_used() < minirex_result.result.gas_used(), - "REX should charge less total gas than Mini-Rex for account creation" - ); -} - #[test] fn test_large_multiplier_linear_scaling() { // Verify storage gas scales linearly even with large multipliers diff --git a/crates/mega-evm/tests/rex2/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs similarity index 94% rename from crates/mega-evm/tests/rex2/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs index 180647020..cf4024147 100644 --- a/crates/mega-evm/tests/rex2/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs @@ -379,66 +379,6 @@ fn test_keyless_deploy_contract_already_exists_deploy_address_in_witness_rex6() ); } -/// Pre-REX6 replay parity: the journaled read is gated to REX6+. Pre-REX6 (sealed) must keep using -/// the raw, unjournaled DB read for the occupancy check, so the deploy address must NOT appear in -/// the returned `EvmState` / witness — no retroactive behavior change. -#[test] -fn test_keyless_deploy_contract_already_exists_deploy_address_not_in_witness_pre_rex6() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::ContractAlreadyExists); - assert!( - !result.state.contains_key(&CREATE2_FACTORY_CONTRACT), - "pre-REX6 (sealed) must keep the raw DB read: the deploy address must NOT appear in the \ - returned EvmState — no retroactive witness change", - ); -} - -/// Regression guard for the critical issue this fix's review caught: journaling the deploy- -/// address occupancy read pre-REX5 corrupts the legacy sandbox-state merge -/// (`apply_sandbox_state_legacy` / `merge_evm_state_optional_status` with `merge_status = false`), -/// which copies `info`/storage for an already-`Occupied` journal entry but does NOT merge account -/// status. A deploy address pre-inserted into the journal by the occupancy check (as a -/// `LoadedAsNotExisting|Cold` placeholder) would hit that `Occupied` branch instead of the -/// `Vacant` one, losing the `Created|Touched` status the successfully deployed contract needs to -/// survive `revm`'s commit (which discards untouched accounts). This test performs a full -/// `db.commit(result.state)` round trip and confirms the deployed contract's code is actually -/// present afterward — the exact thing a `state.get(..).info.code` check on the raw `EvmState` -/// (as the other success tests in this file do) would NOT catch, since `info` is still copied -/// correctly; only the `AccountStatus` bits needed for `commit()` to keep the account are lost. -#[test] -fn test_keyless_deploy_pre_rex6_success_still_commits_deployed_code() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - assert!(result.result.is_success(), "keyless deploy should succeed: {:?}", result.result); - - db.commit(result.state); - let deployed = db.basic(CREATE2_FACTORY_CONTRACT).unwrap(); - assert!( - deployed.is_some_and(|info| info.code_hash == CREATE2_FACTORY_CODE_HASH), - "the deployed contract must survive a commit() round trip on pre-REX6 — a regression \ - here means the occupancy-check journal read is corrupting the legacy state merge", - ); -} - /// REX6 twin of the test above: under REX6 the step-7 occupancy check journals the deploy /// address (cold, via `inspect_account_code_hash`) *before* the sandbox runs, so at merge time /// the address is already an occupied journal entry rather than a fresh one. The merge must @@ -1009,37 +949,6 @@ fn test_keyless_deploy_signer_nonce_too_high() { // Spec Version Tests // ============================================================================= -#[test] -fn test_keyless_deploy_not_available_before_rex2() { - // In REX1, the keyless deploy contract is not deployed at the address. - // Calling an address with no code succeeds with empty output (no deployment occurs). - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX1, // Before REX2 - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // In REX1, there's no code at the keyless deploy address, so the call succeeds - // with empty output (calling an address with no code returns success). - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success (no-op) in REX1, got: {:?}", - result - ); - - // Verify that the contract was NOT deployed (no code at target address) - assert!( - !state.contains_key(&CREATE2_FACTORY_CONTRACT), - "Contract should NOT be deployed in REX1" - ); -} - #[test] fn test_keyless_deploy_not_intercepted_for_inner_calls() { // Keyless deploy should only work for top-level calls (depth == 0). diff --git a/crates/mega-evm/tests/rex2/main.rs b/crates/mega-evm/tests/_pending/rex2/main.rs similarity index 80% rename from crates/mega-evm/tests/rex2/main.rs rename to crates/mega-evm/tests/_pending/rex2/main.rs index 4a20cfef8..af70245a9 100644 --- a/crates/mega-evm/tests/rex2/main.rs +++ b/crates/mega-evm/tests/_pending/rex2/main.rs @@ -2,4 +2,3 @@ mod keyless_deploy; mod oracle_hint; -mod selfdestruct; diff --git a/crates/mega-evm/tests/rex2/oracle_hint.rs b/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs similarity index 93% rename from crates/mega-evm/tests/rex2/oracle_hint.rs rename to crates/mega-evm/tests/_pending/rex2/oracle_hint.rs index 35ca8314d..908d73b3d 100644 --- a/crates/mega-evm/tests/rex2/oracle_hint.rs +++ b/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs @@ -187,31 +187,6 @@ fn test_on_hint_called_on_rex2() { assert_eq!(hints[0].data, hint_data, "Hint data should match"); } -/// Test that `on_hint` is NOT called when Rex1 is enabled (pre-Rex2). -#[test] -fn test_on_hint_not_called_on_rex1() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - // Main contract that calls sendHint on the oracle contract - let main_code = create_call_send_hint_bytecode(user_topic, &hint_data); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - // Deploy the actual v1.1.0 oracle contract - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let result = execute_transaction(MegaSpecId::REX1, &mut db, &external_envs, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that on_hint was NOT called - let hints = external_envs.recorded_hints(); - assert!(hints.is_empty(), "Should NOT have recorded any hints on Rex1"); -} - /// Test that `on_hint` is NOT called for calls to non-oracle contracts. /// Even if a contract has a sendHint function, it must be the oracle contract /// for the hint to be intercepted. diff --git a/crates/mega-evm/tests/rex3/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs similarity index 84% rename from crates/mega-evm/tests/rex3/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs index 7259b7b3d..7c75ed261 100644 --- a/crates/mega-evm/tests/rex3/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs @@ -86,31 +86,6 @@ fn test_rex3_keyless_deploy_records_compute_gas() { ); } -/// Test that Rex2 keyless deploy does NOT count toward compute gas (backward compat). -#[test] -fn test_rex2_keyless_deploy_does_not_record_compute_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let (result, compute_gas_used) = execute_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - - // In Rex2, keyless deploy returns early before compute gas tracking. - // The only compute gas recorded should be intrinsic tx gas, NOT the keyless deploy overhead. - assert!( - compute_gas_used < constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - "Rex2 compute gas ({}) should NOT include keyless deploy overhead ({})", - compute_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - /// Test that keyless deploy halts when compute gas limit is set below the 100K overhead. /// In Rex3, the 100K overhead is recorded as compute gas, so if the compute gas limit /// is lower than 100K, the transaction should fail. diff --git a/crates/mega-evm/tests/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs similarity index 100% rename from crates/mega-evm/tests/rex3/main.rs rename to crates/mega-evm/tests/_pending/rex3/main.rs diff --git a/crates/mega-evm/tests/rex3/oracle_gas_limit.rs b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs similarity index 83% rename from crates/mega-evm/tests/rex3/oracle_gas_limit.rs rename to crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs index 96901b85e..327f491c8 100644 --- a/crates/mega-evm/tests/rex3/oracle_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs @@ -141,74 +141,6 @@ fn test_rex3_call_oracle_without_sload_no_detention() { ); } -/// Test that REX2 still uses CALL-based oracle access detection (1M limit). -#[test] -fn test_rex2_oracle_access_still_uses_1m_compute_gas_limit() { - // For Rex2, just calling oracle (no code needed) triggers detention - let bytecode = build_call_oracle_bytecode(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX2, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert_eq!( - compute_gas_limit, - mega_evm::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - "REX2 compute gas limit should be 1M after oracle access" - ); -} - -/// Test that a transaction consuming >1M but <20M compute gas after oracle access succeeds -/// under REX3 but fails under REX2. -/// -/// Rex3 path: CALL oracle (with SLOAD code) triggers 20M detention, then ~4.4M SSTOREs succeed. -/// Rex2 path: CALL oracle triggers 1M detention, then ~4.4M SSTOREs exceed the limit. -#[test] -fn test_oracle_access_succeeds_rex3_fails_rex2() { - // Oracle contract code for Rex3 - performs SLOAD to trigger detention - let oracle_code = build_oracle_sload_code(); - - // Build callee bytecode: call oracle, then do ~200 SSTOREs (~4.4M compute gas) - let mut builder = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP); - - // 200 SSTOREs to unique slots: ~200 * 22,100 = ~4.4M compute gas - for i in 1..=200u32 { - builder = builder.push_number(i).push_number(i).append(SSTORE); - } - let bytecode = builder.append(STOP).build(); - - // REX3: should succeed (4.4M < 20M limit) - let mut db_rex3 = MemoryDatabase::default(); - db_rex3.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db_rex3.set_account_code(CALLEE, bytecode.clone()); - let (result_rex3, _) = execute_transaction(MegaSpecId::REX3, &mut db_rex3, CALLEE); - assert!( - result_rex3.is_success(), - "REX3 transaction should succeed: ~4.4M compute gas is within the 20M oracle access limit" - ); - - // REX2: should fail (4.4M > 1M limit). No oracle code needed - CALL triggers detention. - let mut db_rex2 = MemoryDatabase::default(); - db_rex2.set_account_code(CALLEE, bytecode); - let (result_rex2, _) = execute_transaction(MegaSpecId::REX2, &mut db_rex2, CALLEE); - assert!( - !result_rex2.is_success(), - "REX2 transaction should fail: ~4.4M compute gas exceeds the 1M oracle access limit" - ); - assert!( - is_volatile_data_access_oog(&result_rex2), - "REX2 should fail with VolatileDataAccessOutOfGas" - ); -} - /// Test that REX3 still enforces the 20M limit (not unlimited). /// A transaction consuming >20M compute gas after oracle SLOAD should still fail. #[test] diff --git a/crates/mega-evm/tests/rex3/system_address.rs b/crates/mega-evm/tests/_pending/rex3/system_address.rs similarity index 100% rename from crates/mega-evm/tests/rex3/system_address.rs rename to crates/mega-evm/tests/_pending/rex3/system_address.rs diff --git a/crates/mega-evm/tests/rex4/access_control.rs b/crates/mega-evm/tests/_pending/rex4/access_control.rs similarity index 96% rename from crates/mega-evm/tests/rex4/access_control.rs rename to crates/mega-evm/tests/_pending/rex4/access_control.rs index 8ef61d7c2..8b0465a27 100644 --- a/crates/mega-evm/tests/rex4/access_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/access_control.rs @@ -502,39 +502,6 @@ fn test_delegatecall_also_restricted() { // 7. BACKWARD COMPATIBILITY // ============================================================================ -/// On Rex3, calling the access control address has no special effect (contract not deployed). -#[test] -fn test_pre_rex4_no_interception() { - // On Rex3, the access control contract is not deployed, so calling it - // should not activate any volatile access restrictions. - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: attempt to call disableVolatileDataAccess, then call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - // Use Rex3 spec - let mut context = MegaContext::new(&mut db, MegaSpecId::REX3); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // The child should succeed (TIMESTAMP not blocked on Rex3) - assert!(result.result.is_success(), "On Rex3, volatile access should NOT be disabled"); - assert_log_call_status(&result, 0, true); -} - // ============================================================================ // 8. CONDITIONAL VOLATILE OPCODES // ============================================================================ @@ -2028,49 +1995,3 @@ fn test_blocked_selfdestruct_beneficiary_does_not_pollute_tracker() { ); } -/// On Rex3 (pre-Rex4), SELFDESTRUCT targeting the beneficiary should NOT be checked or -/// restricted for volatile data access. The volatile data check is Rex4-only. -#[test] -fn test_selfdestruct_beneficiary_not_restricted_pre_rex4() { - let beneficiary = Address::ZERO; - - // Child: SELFDESTRUCT targeting the beneficiary - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // Parent: call child, log call status - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - // Use Rex3 spec (pre-Rex4) - let mut context = MegaContext::new(&mut db, MegaSpecId::REX3); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // SELFDESTRUCT targeting beneficiary should succeed on Rex3 - assert!( - result.result.is_success(), - "On Rex3, SELFDESTRUCT to beneficiary should not be restricted" - ); - assert_log_call_status(&result, 0, true); - - // Volatile data tracker should NOT have marked beneficiary balance access - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "On Rex3, SELFDESTRUCT to beneficiary should not mark volatile data access" - ); -} diff --git a/crates/mega-evm/tests/rex4/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs similarity index 93% rename from crates/mega-evm/tests/rex4/beneficiary_detention.rs rename to crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs index 0fc5f4859..5944b95e9 100644 --- a/crates/mega-evm/tests/rex4/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs @@ -387,35 +387,6 @@ fn test_caller_is_beneficiary_eager_detention() { // TEST 5b: Caller is beneficiary — pre-REX4 no eager detention // ============================================================================ -/// Pre-REX4 specs never had eager beneficiary detention at TX start. -/// Same scenario as test 5 but with REX3: `detained_limit` should remain at TX limit. -#[test] -fn test_caller_is_beneficiary_pre_rex4_no_eager_detention() { - // Simple code: just STOP. We check detained_limit, not remainingComputeGas - // (MegaLimitControl interception is REX4-only). - let callee_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(BENEFICIARY, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = TxEnvBuilder::default() - .caller(BENEFICIARY) - .call(CALLEE) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact_with_spec(MegaSpecId::REX3, &mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx) - .unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - detained_limit, 200_000_000, - "Pre-REX4 caller=beneficiary: detained limit should remain at TX limit (no eager detention)" - ); -} - // ============================================================================ // TEST 6: Recipient is beneficiary — eager detention from TX start // ============================================================================ @@ -456,33 +427,6 @@ fn test_recipient_is_beneficiary_eager_detention() { // TEST 6b: Recipient is beneficiary — pre-REX4 no eager detention // ============================================================================ -/// Pre-REX4 specs never had eager beneficiary detention at TX start. -/// Same scenario as test 6 but with REX3: `detained_limit` should remain at TX limit. -#[test] -fn test_recipient_is_beneficiary_pre_rex4_no_eager_detention() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact_with_spec(MegaSpecId::REX3, &mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx) - .unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - detained_limit, 200_000_000, - "Pre-REX4 recipient=beneficiary: detained limit should remain at TX limit (no eager detention)" - ); -} - // ============================================================================ // TEST 7: SELFBALANCE in beneficiary contract triggers detention (integration) // ============================================================================ diff --git a/crates/mega-evm/tests/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs similarity index 52% rename from crates/mega-evm/tests/rex4/create_safety.rs rename to crates/mega-evm/tests/_pending/rex4/create_safety.rs index dab3c32c4..133657771 100644 --- a/crates/mega-evm/tests/rex4/create_safety.rs +++ b/crates/mega-evm/tests/_pending/rex4/create_safety.rs @@ -149,112 +149,3 @@ fn run_create2_and_get_compute_gas( (res.result, compute_gas) } -#[test] -fn test_create2_memory_expansion_recorded_as_compute_gas() { - // 32000-byte initcode -> 1000 words -> ~4953 gas of memory expansion. - const INITCODE_LEN: u64 = 32_000; - let words = INITCODE_LEN.div_ceil(32); - let expected_expansion = memory_expansion_gas(INITCODE_LEN); - // KECCAK256 over the initcode (charged inside CREATE2). - let expected_hash = 6 * words; - // CREATE2 per-initcode-word cost (part of CREATE2's static charge). - let expected_init_word = 2 * words; - // Sum of all three initcode_len-scaled costs. The expansion cost is what the wrapper must - // record into the compute gas tracker. - let expected_extra = expected_expansion + expected_hash + expected_init_word; - - let (baseline_result, baseline_compute_gas) = run_create2_and_get_compute_gas(0, 10_000_000); - assert!( - matches!(baseline_result, ExecutionResult::Success { .. }), - "baseline CREATE2 with empty initcode should succeed: {:?}", - baseline_result - ); - - let (big_result, big_compute_gas) = run_create2_and_get_compute_gas(INITCODE_LEN, 10_000_000); - assert!( - matches!(big_result, ExecutionResult::Success { .. }), - "large-initcode CREATE2 should succeed: {:?}", - big_result - ); - - // The delta should equal the sum of all three initcode-length-scaled costs (within a - // small tolerance for the differing PUSH opcode used to push the length itself: PUSH0 - // for 0 vs PUSHn for 32000). If the wrapper failed to record the expansion gas, the - // delta would be short by `expected_expansion`. - let delta = big_compute_gas - baseline_compute_gas; - let diff = delta.abs_diff(expected_extra); - assert!( - diff < 50, - "compute gas delta ({}) should ~equal expansion ({}) + hash ({}) + init_word ({}) = {}; \ - baseline={}, big={}, diff={}. If diff is close to {}, the wrapper's resize_memory! \ - consumed interpreter gas but never recorded it into the compute gas tracker.", - delta, - expected_expansion, - expected_hash, - expected_init_word, - expected_extra, - baseline_compute_gas, - big_compute_gas, - diff, - expected_expansion, - ); -} - -#[test] -fn test_create2_resize_gas_skipped_when_canonical_create2_oogs() { - // Verifies the deferred-recording semantics: when the inner CREATE2 OOGs (after the - // wrapper's resize_memory! has already consumed interpreter gas), the compute gas - // tracker must NOT receive the resize_gas. This mirrors `wrap_op_compute_gas`'s - // "skip on inner error" pattern — historically the canonical CREATE2's expansion gas - // was only recorded when the inner instruction completed without an EVM error. - // - // Strategy: pick a tx gas budget tight enough that, after intrinsic + bytecode + the - // wrapper's resize, the remaining gas cannot cover the canonical CREATE2's static - // base cost (32_000). The two runs (small vs big initcode) both halt with OutOfGas. - // With deferred recording: compute gas delta ≈ 1 (just the differing PUSH opcode for - // the length argument). With (hypothetical) immediate recording: delta would be - // ≈ 1 + expected_expansion. - const INITCODE_LEN: u64 = 32_000; - let expected_expansion = memory_expansion_gas(INITCODE_LEN); - - // REX4 intrinsic = 21_000 (base) + 39_000 (REX TX_INTRINSIC_STORAGE_GAS) = 60_000. - // After intrinsic, leave 31_000 for the frame: PUSHes (~9) + (for big run) resize - // (~4953) + canonical CREATE2 base (32_000+). Small run has ~30_992 for canonical's - // 32_000 base → OOG; big run has ~26_038 for canonical's 40_000 (32k base + 2k init - // + 6k keccak) → also OOG. Both halt inside canonical CREATE2. - let tight_gas: u64 = 91_000; - - let (small_result, small_compute_gas) = run_create2_and_get_compute_gas(0, tight_gas); - let (big_result, big_compute_gas) = run_create2_and_get_compute_gas(INITCODE_LEN, tight_gas); - - // Both must OOG (otherwise the test premise is broken and the assertion below is - // not actually exercising the deferred-recording path). - assert!( - matches!(small_result, ExecutionResult::Halt { .. }), - "small-initcode run should OOG inside canonical CREATE2 at tight_gas={}: {:?}", - tight_gas, - small_result - ); - assert!( - matches!(big_result, ExecutionResult::Halt { .. }), - "big-initcode run should OOG inside canonical CREATE2 at tight_gas={}: {:?}", - tight_gas, - big_result - ); - - // The only legitimate compute-gas difference between the two runs is the length-PUSH - // opcode (PUSH0 vs PUSHn, ~1 gas). If the wrapper recorded resize_gas eagerly, the - // big-initcode run would also be charged ~`expected_expansion` extra, putting the - // delta near 4953 instead of near 0. - let delta = big_compute_gas.abs_diff(small_compute_gas); - assert!( - delta < 50, - "compute gas delta on OOG ({}) should be ~0; got small={}, big={}. If delta is \ - close to expected_expansion ({}), the resize gas leaked into the tracker even \ - though the inner CREATE2 errored — the deferred-recording skip path is broken.", - delta, - small_compute_gas, - big_compute_gas, - expected_expansion, - ); -} diff --git a/crates/mega-evm/tests/rex4/deployment.rs b/crates/mega-evm/tests/_pending/rex4/deployment.rs similarity index 92% rename from crates/mega-evm/tests/rex4/deployment.rs rename to crates/mega-evm/tests/_pending/rex4/deployment.rs index 0c339519e..29578d4c1 100644 --- a/crates/mega-evm/tests/rex4/deployment.rs +++ b/crates/mega-evm/tests/_pending/rex4/deployment.rs @@ -164,13 +164,3 @@ fn test_rex4_system_contract_deployment_is_idempotent() { }); } -#[test] -fn test_rex3_boundary_does_not_deploy_rex4_system_contracts() { - with_executor(MegaSpecId::REX3, rex3_chain_spec(), |executor| { - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let db_ref = executor.evm_mut().db_mut(); - assert_contract_not_deployed(db_ref, ACCESS_CONTROL_ADDRESS, "MegaAccessControl"); - assert_contract_not_deployed(db_ref, LIMIT_CONTROL_ADDRESS, "MegaLimitControl"); - }); -} diff --git a/crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs similarity index 95% rename from crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs rename to crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs index d348fe450..c574a0268 100644 --- a/crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs +++ b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs @@ -482,21 +482,3 @@ fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { ); } -/// Pre-REX4: `inspect_storage` follows EIP-7702 delegation (original behavior), so the -/// delegate's journal gets polluted with the delegator's storage value. -/// DELEGATE's slot 1 `original_value` will be 42 (DELEGATOR's value) instead of 99. -#[test] -fn test_inspect_storage_pollutes_delegate_journal_pre_rex4() { - let result = run_inspect_storage_pollution_scenario(MegaSpecId::REX3); - - let delegate_account = result.state.get(&DELEGATE).expect("DELEGATE should be in state"); - let slot = - delegate_account.storage.get(&U256::from(1)).expect("slot 1 should exist in DELEGATE"); - // Pre-REX4 preserves the old behavior: inspect_storage follows delegation and - // pollutes the delegate's journal with the delegator's storage value. - assert_eq!( - slot.original_value(), - U256::from(42), - "Pre-REX4: DELEGATE's slot 1 original_value should be 42 (polluted from DELEGATOR)" - ); -} diff --git a/crates/mega-evm/tests/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs similarity index 73% rename from crates/mega-evm/tests/rex4/frame_limits.rs rename to crates/mega-evm/tests/_pending/rex4/frame_limits.rs index 92ec811e7..61f2455c7 100644 --- a/crates/mega-evm/tests/rex4/frame_limits.rs +++ b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs @@ -454,50 +454,6 @@ fn test_data_size_child_exceed_followed_by_sibling_success() { assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(98)); } -#[test] -fn test_data_size_rex3_no_per_frame_limits() { - // REX3: child writes 99 slots with TX limit = 100 slots → succeeds (TX-level only). - let limit = tx_intrinsic_data_size() + n_sstore_data(99); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX3, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame data size limits"); - assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(99)); -} - -#[test] -fn test_data_size_rex3_tx_exceed_halts() { - // REX3: child exceeds TX-level limit → Halt (not Revert). - let limit = n_sstore_data(10); - let child_code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(MegaSpecId::REX3, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level data size exceed"); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - // ============================================================================ // KV UPDATE PER-FRAME LIMITS // ============================================================================ @@ -726,49 +682,6 @@ fn test_kv_update_child_exceed_followed_by_sibling_success() { assert_eq!(kv_updates, 1 + 98); } -#[test] -fn test_kv_update_rex3_no_per_frame_limits() { - // REX3: child writes 99 KV ops with TX limit = 100 → succeeds. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX3, &mut db, u64::MAX, 100, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame KV limits"); - assert_eq!(kv_updates, 1 + 99); -} - -#[test] -fn test_kv_update_rex3_tx_exceed_halts() { - // REX3: child exceeds TX-level KV limit → Halt. - let child_code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - // KV limit = 10: caller(1) + 10 sstores = 11 > 10 - let (result, _, _) = transact_data_kv(MegaSpecId::REX3, &mut db, u64::MAX, 10, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level KV exceed"); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - )); -} - // ============================================================================ // COMPUTE GAS PER-FRAME LIMITS // ============================================================================ @@ -793,163 +706,3 @@ fn burn_gas_code(target_gas: u64) -> Bytes { Bytes::from(code) } -#[test] -fn test_compute_gas_child_exceeds_budget_frame_local_revert() { - // TX limit = 2_000_000; child budget = 1_960_000. - // Burn 1_970_000 in child (> frame budget). Keep total TX usage under 2_000_000 - // so this remains frame-local and parent can continue. - let tx_limit = 2_000_000_u64; - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child frame-local revert"); - assert!(!result.result.is_halt(), "Should NOT be halt"); -} - -#[test] -fn test_compute_gas_child_gas_still_counts_despite_revert() { - // Unlike StateGrowth, ComputeGas is persistent: even after per-frame revert, - // the child's gas is counted in the parent's total. - // Set TX limit high (2_000_000). Child budget = 1_960_000. Child burns 1_970_000. - // Parent's total compute gas should INCLUDE the child's gas. - - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - // Child budget = 2_000_000 * 98 / 100 = 1_960_000. - // Child burns 1_970_000 > 1_960_000 → per-frame revert. - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, 2_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Child's gas persists — total should be significantly more than just the parent's minimal ops. - // The parent itself uses very little gas (just the CALL setup and POP/STOP). - assert!( - compute_gas > 1_900_000, - "Child's gas should be counted despite revert: got {compute_gas}" - ); -} - -#[test] -fn test_compute_gas_revert_data_encodes_mega_limit_exceeded() { - // kind=2 (ComputeGas), limit=child's frame budget - let tx_limit = 2_000_000_u64; - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 2, "kind should be 2 (ComputeGas)"); - assert!( - decoded.limit <= tx_limit * 98 / 100, - "limit should be <= 98% of tx limit after parent pre-call gas; got {}", - decoded.limit - ); -} - -#[test] -fn test_compute_gas_rex3_no_per_frame_limits() { - // REX3: no per-frame compute gas limits. Child with budget 98% frame budget - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX3, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame compute gas limits"); -} - -#[test] -fn test_compute_gas_sibling_frames_independent() { - // After child A reverts (per-frame exceed), child B still gets a fresh budget. - // TX limit = 2_500_000. Child A budget = 2_450_000, burns 2_460_000 → Revert. - // Parent remaining after A's gas (persistent) is still enough for child B. - // Child B burns 10 gas and succeeds. - // - // This test mainly verifies the TX doesn't halt after multiple children run. - let tx_limit = 2_500_000_u64; - let child_a_code = burn_gas_code(2_460_000); // > 2_450_000 (98% of 2_500_000) - let child_b_code = burn_gas_code(10); // tiny gas, should succeed - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 5_000_000) - .append(POP) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(CONTRACT2) - .push_number(5_000_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "TX should succeed with multiple children"); -} - -#[test] -fn test_compute_gas_top_level_exceed_is_frame_local_revert() { - // Top-level frame exceeds its own remaining compute budget in Rex4: should Revert, not Halt. - // Burn more than the first-frame budget after intrinsic compute gas is deducted. - let tx_limit = 2_000_000_u64; - let code = burn_gas_code(tx_limit); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(matches!(result.result, ExecutionResult::Revert { .. })); - assert!(!result.result.is_halt()); - assert!(compute_gas > tx_limit, "Persistent compute gas should still exceed the TX limit"); -} diff --git a/crates/mega-evm/tests/rex4/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs similarity index 91% rename from crates/mega-evm/tests/rex4/gas_detention.rs rename to crates/mega-evm/tests/_pending/rex4/gas_detention.rs index 821bd2d90..e46299e7e 100644 --- a/crates/mega-evm/tests/rex4/gas_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs @@ -266,30 +266,3 @@ fn test_rex4_multiple_volatile_accesses_first_wins() { ); } -/// Pre-REX4: Same scenario as `test_rex4_volatile_access_after_heavy_compute_succeeds` -/// but with `MINI_REX` spec — should halt immediately (backward compatibility). -#[test] -fn test_pre_rex4_absolute_cap_preserved() { - // Burn 25M compute gas, then access TIMESTAMP. - // Pre-REX4 absolute cap = 20M. 25M > 20M -> halts immediately. - let builder = append_burn_gas(BytecodeBuilder::default(), 25_000_000); - let code = builder.append(TIMESTAMP).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, _compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::MINI_REX, &mut db, 1_000_000_000, BLOCK_ENV_CAP, tx) - .unwrap(); - - assert!( - is_volatile_data_access_oog(&result.result), - "Pre-REX4 should halt with absolute cap when usage exceeds 20M before access" - ); - assert_eq!( - detained_limit, BLOCK_ENV_CAP, - "Pre-REX4 detained limit should be the absolute cap (20M)" - ); -} diff --git a/crates/mega-evm/tests/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs similarity index 100% rename from crates/mega-evm/tests/rex4/intrinsic_limit_bypass.rs rename to crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs diff --git a/crates/mega-evm/tests/rex4/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs similarity index 77% rename from crates/mega-evm/tests/rex4/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs index d570507e2..4fdd31303 100644 --- a/crates/mega-evm/tests/rex4/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs @@ -236,61 +236,6 @@ fn test_rex4_keyless_deploy_uses_salt_env() { ); } -/// Rex3 keyless deploy ignores the salt env (backward compatibility). -/// -/// Pre-Rex4 sandbox always uses `EmptyExternalEnv`, so changing bucket capacity -/// should not affect sandbox `gas_used`. -#[test] -fn test_rex3_keyless_deploy_ignores_salt_env() { - // Run with default bucket capacity - let mut db_default = MemoryDatabase::default(); - db_default.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let env_default = TestExternalEnvs::::new(); - let (result_default, gas_default) = execute_keyless_deploy_with_envs( - MegaSpecId::REX3, - &mut db_default, - &env_default, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_default.is_success(), - "Default deploy should succeed, got: {:?}", - result_default - ); - - // Run with elevated bucket capacity - let mut db_high = MemoryDatabase::default(); - db_high.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let high_capacity = (MIN_BUCKET_SIZE as u64) * 2; - let env_high = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket_id(), high_capacity) - .with_bucket_capacity(deployer_bucket_id(), high_capacity); - let (result_high, gas_high) = execute_keyless_deploy_with_envs( - MegaSpecId::REX3, - &mut db_high, - &env_high, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_high.is_success(), - "High-capacity deploy should succeed, got: {:?}", - result_high - ); - - // Pre-REX4 sandbox uses EmptyExternalEnv, so gas should be the same regardless of capacity - assert_eq!( - gas_default, gas_high, - "REX3 sandbox gas should be the same regardless of bucket capacity: default={}, high={}", - gas_default, gas_high, - ); -} - /// Rex4 keyless deploy sandbox forwards oracle hints emitted in constructors. #[test] fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { @@ -317,25 +262,3 @@ fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { assert_eq!(hints[0].data, Bytes::copy_from_slice(hint_data), "hint data should match"); } -/// Rex3 keyless deploy sandbox keeps the historical empty oracle env behavior. -#[test] -fn test_rex3_keyless_deploy_constructor_ignores_oracle_env() { - let topic = B256::repeat_byte(0x22); - let hint_data = b"rex3-sandbox-hint"; - let init_code = create_constructor_send_hint_init_code(topic, hint_data); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - let (result, _) = - execute_keyless_deploy_with_envs(MegaSpecId::REX3, &mut db, &external_envs, tx_bytes); - - assert!(result.is_success(), "keyless deploy should succeed, got: {:?}", result); - assert!( - external_envs.recorded_hints().is_empty(), - "pre-REX4 sandbox should not forward oracle hints", - ); -} diff --git a/crates/mega-evm/tests/rex4/limit_control.rs b/crates/mega-evm/tests/_pending/rex4/limit_control.rs similarity index 98% rename from crates/mega-evm/tests/rex4/limit_control.rs rename to crates/mega-evm/tests/_pending/rex4/limit_control.rs index 0e0b93ba2..71606207f 100644 --- a/crates/mega-evm/tests/rex4/limit_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/limit_control.rs @@ -733,15 +733,3 @@ fn test_callcode_not_intercepted() { // 6. BACKWARD COMPATIBILITY // ============================================================================ -/// On Rex3, calling the address has no special interception behavior. -#[test] -fn test_pre_rex4_no_interception() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(MegaSpecId::REX3, &mut db, direct_query_tx(LIMIT_CONTROL_ADDRESS)).unwrap(); - - assert!(result.result.is_success()); - let output = result.result.output().expect("success must include output"); - assert!(output.is_empty(), "REX3 should not intercept this system contract call"); -} diff --git a/crates/mega-evm/tests/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs similarity index 83% rename from crates/mega-evm/tests/rex4/main.rs rename to crates/mega-evm/tests/_pending/rex4/main.rs index dde7619c9..b75668583 100644 --- a/crates/mega-evm/tests/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -6,10 +6,8 @@ mod create_safety; mod deployment; mod eip7702_delegation_cycle; mod frame_limits; -mod frame_state_growth; mod gas_detention; mod intrinsic_limit_bypass; mod keyless_deploy; mod limit_control; -mod selfdestruct_state_growth; mod storage_call_stipend; diff --git a/crates/mega-evm/tests/rex4/storage_call_stipend.rs b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs similarity index 69% rename from crates/mega-evm/tests/rex4/storage_call_stipend.rs rename to crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs index 1a5fa49b6..4983a2355 100644 --- a/crates/mega-evm/tests/rex4/storage_call_stipend.rs +++ b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs @@ -281,28 +281,6 @@ fn test_log1_in_receive_succeeds_under_rex4() { } } -/// Under REX3 (pre-REX4), the same CALL should fail because `STORAGE_CALL_STIPEND` is not -/// available and the callee only gets 2,300 gas which is insufficient for LOG1 (4,500). -#[test] -fn test_log1_in_receive_fails_under_rex3() { - let sender_code = build_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX3, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "inner CALL should fail under REX3 (no STORAGE_CALL_STIPEND)" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - /// The storage-call stipend only applies to internal `CALL`/`CALLCODE`, not to the /// top-level transaction frame. #[test] @@ -366,68 +344,6 @@ fn test_callcode_gets_storage_call_stipend() { } } -/// `STORAGE_CALL_STIPEND` should be burned on return. -/// When the callee does nothing (STOP), the parent should NOT recover the stipend as free gas. -/// We verify this by comparing `gas_used` with and without value transfer. -#[test] -fn test_storage_call_stipend_burned_on_return() { - // Contract that CALLs EMPTY_RECEIVER with value (gets stipend, stipend should be burned) - let sender_with_value = build_transfer_contract(EMPTY_RECEIVER); - // Contract that CALLs EMPTY_RECEIVER without value (no stipend) - let sender_no_value = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value = 0 (no transfer) - .push_address(EMPTY_RECEIVER) - .push_number(0_u64) // gas = 0 - .append(CALL) - .append(STOP) - .build(); - let empty_code = BytecodeBuilder::default().append(STOP).build(); - - // Test with value transfer (gets STORAGE_CALL_STIPEND) - let mut db_with_value = - setup_db(&[(SENDER_CONTRACT, sender_with_value), (EMPTY_RECEIVER, empty_code.clone())]); - let result_with_value = transact(MegaSpecId::REX4, &mut db_with_value, default_tx()).unwrap(); - let gas_used_with_value = match &result_with_value.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("expected Success, got {other:?}"), - }; - - // The gas_used should NOT include the burned STORAGE_CALL_STIPEND as "free" gas. - // If the stipend leaked, the parent would have more remaining gas, resulting in lower gas_used. - // We verify that gas_used is at least what we'd expect with the CALLVALUE cost. - // CALLVALUE cost = 9000, so the transfer CALL should cost the parent at least 9000 more. - let sender_no_value_addr = address!("0000000000000000000000000000000000200004"); - let mut db_no_value = - setup_db(&[(sender_no_value_addr, sender_no_value), (EMPTY_RECEIVER, empty_code)]); - let tx_no_value = TxEnvBuilder::default() - .caller(CALLER) - .call(sender_no_value_addr) - .gas_limit(100_000_000) - .build_fill(); - let result_no_value = transact(MegaSpecId::REX4, &mut db_no_value, tx_no_value).unwrap(); - let gas_used_no_value = match &result_no_value.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("expected Success, got {other:?}"), - }; - - // With value transfer: parent pays CALLVALUE (9000), but recovers the original - // CALL_STIPEND (2300) as unused gas. Net cost ≈ 6700. - // Without value: no CALLVALUE cost, no stipend. - // The difference should be approximately CALLVALUE - CALL_STIPEND = 6700. - // If STORAGE_CALL_STIPEND (23000) leaked, the difference would be negative - // (parent would gain ~23000 free gas, far exceeding the CALLVALUE cost). - let diff = gas_used_with_value.saturating_sub(gas_used_no_value); - assert!( - diff >= 6000, - "STORAGE_CALL_STIPEND should be burned, not leaked. \ - gas_used_with_value={gas_used_with_value}, gas_used_no_value={gas_used_no_value}, diff={diff}" - ); -} - /// CALL without value transfer should NOT receive `STORAGE_CALL_STIPEND`. #[test] fn test_no_stipend_without_value_transfer() { @@ -532,41 +448,6 @@ fn test_staticcall_no_storage_call_stipend() { assert!(matches!(result.result, ExecutionResult::Success { .. }), "STATICCALL should succeed"); } -/// When the callee reverts, the `STORAGE_CALL_STIPEND` should still be burned -/// (not returned to the parent). -#[test] -fn test_storage_call_stipend_burned_on_revert() { - // Receiver that emits LOG1 then reverts - let receiver_code = BytecodeBuilder::default() - .push_number(0xdeadbeef_u64) - .push_number(0_u64) - .push_number(0_u64) - .append(LOG1) - .revert() - .build(); - let sender_code = build_transfer_contract(RECEIVER); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - // Inner CALL reverts, so success_flag = 0 - assert_eq!(success_flag, U256::ZERO, "inner CALL should revert"); - } - other => panic!("expected outer Success (inner revert), got {other:?}"), - } - // The key check: the transaction's total gas_used should be reasonable. - // The STORAGE_CALL_STIPEND should have been burned, not leaked back to the parent. - let gas_used = match &result.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - _ => unreachable!(), - }; - // Gas used should be at least the intrinsic + CALLVALUE cost. - // If stipend leaked, gas_used would be much lower. - assert!(gas_used > 21_000 + 9_000, "gas_used should reflect CALLVALUE cost, got {gas_used}"); -} - /// `STORAGE_CALL_STIPEND` must NOT be usable for pure computation. /// A callee that only does compute (PUSH/POP loops, no LOG or storage ops) should still /// be limited to `CALL_STIPEND` (2,300) worth of compute gas. @@ -685,45 +566,6 @@ fn test_intercepted_value_call_does_not_leak_storage_call_stipend() { ); } -/// Top-level keyless deploy interception must preserve the gas already consumed by the -/// interceptor itself. -#[test] -fn test_top_level_keyless_deploy_value_call_preserves_gas_accounting() { - let call_data = Bytes::from( - IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::new(), - gasLimitOverride: U256::ZERO, - } - .abi_encode(), - ); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(KEYLESS_DEPLOY_ADDRESS) - .gas_limit(200_000) - .data(call_data) - .value(U256::from(1_u64)) - .build_fill(); - - let mut rex3_db = setup_db(&[]); - let rex3_result = transact(MegaSpecId::REX3, &mut rex3_db, tx.clone()).unwrap(); - let rex3_gas_used = match rex3_result.result { - ExecutionResult::Revert { gas_used, .. } => gas_used, - other => panic!("expected Revert, got {other:?}"), - }; - - let mut rex4_db = setup_db(&[]); - let rex4_result = transact(MegaSpecId::REX4, &mut rex4_db, tx).unwrap(); - let rex4_gas_used = match rex4_result.result { - ExecutionResult::Revert { gas_used, .. } => gas_used, - other => panic!("expected Revert, got {other:?}"), - }; - - assert_eq!( - rex4_gas_used, rex3_gas_used, - "REX4 should preserve keyless-deploy interceptor gas accounting on top-level value calls" - ); -} - /// Nested value-transferring calls: A calls B with value, B calls C with value. /// Both B and C should independently receive and burn their own `STORAGE_CALL_STIPEND`, /// exercising the stipend stack push/pop alignment across multiple depth levels. @@ -844,117 +686,3 @@ fn test_stipend_not_leaked_on_frame_local_limit_exceed() { ); } -/// When CALL with value targets an EOA (no code), revm's `frame_init` returns a Result -/// immediately without creating an interpreter frame. The `STORAGE_CALL_STIPEND` must -/// still be burned via `before_frame_return_result` and not leak to the parent. -/// -/// This exercises the `after_frame_init` Result path, which is distinct from the normal -/// frame execution path tested by `test_storage_call_stipend_burned_on_return`. -#[test] -fn test_stipend_burned_on_eoa_value_transfer() { - let sender_code = build_transfer_contract(EOA_RECEIVER); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - db.set_account_balance(EOA_RECEIVER, U256::from(1_000_000u128)); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!(success_flag, U256::from(1), "inner CALL to EOA should succeed"); - } - other => panic!("expected Success, got {other:?}"), - } - - let gas_used = match &result.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - _ => unreachable!(), - }; - // Intrinsic gas + CALL costs (cold access 2,600 + value transfer 9,000 + - // gas_stipend deduction 2,300) + parent opcodes. - // If the 23,000 stipend leaked via the after_frame_init Result path, - // gas_used would drop by ~23,000. - assert!( - gas_used > 50_000, - "gas_used {gas_used} is too low — STORAGE_CALL_STIPEND may have leaked on EOA transfer" - ); -} - -/// On the REX4 legacy-inflation path, when a value-transferring child frame that received a -/// `STORAGE_CALL_STIPEND` hits a TX-level detained compute-gas limit, `rescue_gas` must EXCLUDE -/// the stipend from the gas rescued back to the sender (system-granted gas must not leak). -/// -/// This pins the exact `gas_used` so the stipend exclusion is observable end-to-end: with the -/// exclusion (correct) the rescued gas is capped at the pre-stipend limit; without it the full -/// child `gas.remaining()` is rescued, refunding ~13k extra gas and lowering `gas_used`. -/// -/// Kills the mutant `current_frame_stipend -> 0` in `storage_call_stipend.rs`: with the mutant, -/// `effective_remaining_for_rescue` skips the exclusion and `gas_used` drops from `69_321` to -/// `56_325`. -#[test] -fn test_stipend_excluded_from_rescued_gas_on_tx_level_detention_exceed() { - let sender_code = build_value_call_contract(RECEIVER, 100_000); - let receiver_code = - append_burn_gas(BytecodeBuilder::default().append(TIMESTAMP).append(POP), 20_000) - .append(STOP) - .build(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let tx = default_tx(); - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX4, &mut db, tx, limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, - gas_used, - } => { - // Exact gas_used with the stipend correctly excluded from the rescued gas. - // If `current_frame_stipend` returns 0 (mutant), the exclusion is skipped, the full - // child `gas.remaining()` is rescued, and gas_used drops to 56_325. - assert_eq!( - *gas_used, 69_321, - "STORAGE_CALL_STIPEND must be excluded from rescued gas on TX-level exceed; \ - a lower gas_used means the system-granted stipend leaked back to the sender" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas halt, got {other:?}"), - } -} - -/// If a value-transferring child frame with an active `STORAGE_CALL_STIPEND` hits a TX-level -/// detained compute gas limit, `rescue_gas` must cap the refund at the pre-stipend limit instead -/// of panicking in debug builds. -#[test] -fn test_stipend_with_tx_level_detention_exceed_does_not_panic() { - let sender_code = build_value_call_contract(RECEIVER, 100_000); - let receiver_code = - append_burn_gas(BytecodeBuilder::default().append(TIMESTAMP).append(POP), 20_000) - .append(STOP) - .build(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let tx = default_tx(); - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX4, &mut db, tx, limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { limit, .. }, - gas_used, - } => { - assert!( - *limit <= 1_000_000, - "detained limit should stay within the tx compute gas limit, got {limit}" - ); - assert!( - *gas_used < 200_000, - "gas_used should reflect rescued gas rather than the full child gas limit, got {gas_used}" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas, got {other:?}"), - } -} diff --git a/crates/mega-evm/tests/rex5/apply_pending_changes_gas_budget.rs b/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs similarity index 100% rename from crates/mega-evm/tests/rex5/apply_pending_changes_gas_budget.rs rename to crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs diff --git a/crates/mega-evm/tests/rex5/call_too_deep_guard.rs b/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs similarity index 90% rename from crates/mega-evm/tests/rex5/call_too_deep_guard.rs rename to crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs index 7ad6fa40a..009cf52f1 100644 --- a/crates/mega-evm/tests/rex5/call_too_deep_guard.rs +++ b/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs @@ -122,31 +122,6 @@ fn test_rex5_depth_boundary_allows_call_at_limit() { assert_eq!(outcome.result.result, InstructionResult::Return); } -#[test] -fn test_pre_rex5_depth_guard_disabled() { - // REX4: the depth guard is intentionally absent for backward compatibility — the - // interceptor still fires at any depth, matching pre-fix behavior. This pins the - // replay invariant for stable specs. - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX4); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected interceptor Call result"); - }; - // The interceptor still fires under REX4, producing its synthetic Return result. - assert_eq!( - outcome.result.result, - InstructionResult::Return, - "pre-REX5 must preserve existing behavior (interceptor fires at any depth)", - ); -} - #[test] fn test_rex5_exceeded_tx_limit_wins_over_call_too_deep() { // Priority-ordering regression: when both a TX-level additional-limit exceed AND diff --git a/crates/mega-evm/tests/rex5/callcode_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs similarity index 92% rename from crates/mega-evm/tests/rex5/callcode_storage_gas.rs rename to crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs index f664a68ee..6193eaf91 100644 --- a/crates/mega-evm/tests/rex5/callcode_storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs @@ -227,24 +227,6 @@ fn test_rex5_callcode_from_eip7702_authority_no_storage_gas() { // CALLCODE: Pre-Rex5 frozen behavior — bug preserved // ============================================================================ -/// Pre-Rex5 (Rex4) preserves the original (buggy) behavior: a value-transferring -/// `CALLCODE` to an empty code-source charges new-account storage gas based on the -/// code-source's bucket. This test pins that behavior so a future regression in -/// stable-spec semantics is caught. -#[test] -fn test_rex4_callcode_to_empty_charges_new_account_storage_gas() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX4, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX4, bytecode, 10); - - let expected_extra = NEW_ACCOUNT_STORAGE_GAS_BASE * 9; - assert_eq!( - gas_mult10 - gas_mult1, - expected_extra, - "Rex4 (frozen) must keep charging new-account storage gas against the code-source bucket", - ); -} - // ============================================================================ // CALL: behavior unchanged — value-transferring CALL to empty target still charges // ============================================================================ @@ -266,22 +248,6 @@ fn test_rex5_call_to_empty_still_charges_new_account_storage_gas() { ); } -/// Pre-Rex5 (Rex4) `CALL` behavior is unchanged: value-transferring CALL to an -/// empty target charges new-account storage gas based on the target's bucket. -#[test] -fn test_rex4_call_to_empty_charges_new_account_storage_gas() { - let bytecode = call_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX4, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX4, bytecode, 10); - - let expected_extra = NEW_ACCOUNT_STORAGE_GAS_BASE * 9; - assert_eq!( - gas_mult10 - gas_mult1, - expected_extra, - "Rex4 CALL must charge new-account storage gas against the target bucket", - ); -} - // ============================================================================ // Error-path tests — coverage for FatalExternalError branches in call_code // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/create2_empty_initcode.rs b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs similarity index 87% rename from crates/mega-evm/tests/rex5/create2_empty_initcode.rs rename to crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs index c1a96a17b..01457e980 100644 --- a/crates/mega-evm/tests/rex5/create2_empty_initcode.rs +++ b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs @@ -113,21 +113,6 @@ fn test_rex5_create2_len_nonzero_offset_max_still_halts() { ); } -/// REX4 (pre-REX5) baseline: same input MUST halt — the stable-spec path runs -/// `as_usize_or_fail!(U256::MAX)` and surfaces an `InvalidOperandOOG`-shaped -/// halt. Frozen for replay parity; pinned so a future change that backports the -/// short-circuit to stable specs is caught here. -#[test] -fn test_rex4_create2_len_zero_offset_max_halts() { - let code = build_create2_empty_initcode_at_offset(U256::MAX); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "REX4 CREATE2(len=0, offset=U256::MAX) must halt (frozen stable-spec behavior); \ - got {result:?}", - ); -} - /// REX5: `CREATE2(len=0, offset=large_finite)` MUST succeed without paying for /// memory expansion. Without the short-circuit, `resize_memory!(1<<30, 0)` /// quadratically prices the implied range — pricing canonical revm explicitly @@ -163,16 +148,6 @@ fn test_rex5_create2_len_zero_offset_zero_succeeds() { assert!(result.is_success(), "REX5 CREATE2(len=0, offset=0) must succeed; got {result:?}",); } -/// REX4: `CREATE2(len=0, offset=0)` happy path — pinned to confirm pre-REX5 -/// still succeeds via the frozen "observe offset (=0), trivial resize, slice -/// empty, hash empty" sequence. -#[test] -fn test_rex4_create2_len_zero_offset_zero_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!(result.is_success(), "REX4 CREATE2(len=0, offset=0) must succeed; got {result:?}",); -} - /// REX5 vs REX4 deployed-address parity for `len=0, offset=0`. Both must derive /// the same address `creator.create2(0, KECCAK_EMPTY)` — REX5 via the /// short-circuit, REX4 via `keccak256(slice_len(0, 0))` which equals diff --git a/crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs similarity index 86% rename from crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs rename to crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs index f695721f7..ed1c754ee 100644 --- a/crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs +++ b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs @@ -89,37 +89,6 @@ fn test_rex5_create2_with_non_trivial_resize_succeeds() { ); } -/// REX4 baseline: same scenario under the pre-REX5 spec succeeds via the trailing -/// late-record path. Pinned to guarantee replay parity is preserved. -#[test] -fn test_rex4_create2_with_non_trivial_resize_succeeds() { - let (result, compute) = transact_create2(MegaSpecId::REX4, INITCODE_LEN); - assert!(result.is_success(), "REX4 CREATE2 happy path must succeed; got {result:?}"); - assert!( - compute > 0, - "REX4 compute_gas tracker must register usage including resize_gas; got {compute}", - ); -} - -/// Cross-spec parity: REX5's early-record path and pre-REX5's late-record path must -/// register the same `resize_gas` total on a successful CREATE2. A multi-KiB delta -/// would indicate either a double-count under REX5 (early + trailing both recording -/// the same `resize_gas`) or a miss-count (early-record path skipped without the -/// trailing block taking over). -#[test] -fn test_create2_compute_gas_parity_across_specs() { - let (result_rex5, compute_rex5) = transact_create2(MegaSpecId::REX5, INITCODE_LEN); - let (result_rex4, compute_rex4) = transact_create2(MegaSpecId::REX4, INITCODE_LEN); - assert!(result_rex5.is_success(), "REX5 must succeed; got {result_rex5:?}"); - assert!(result_rex4.is_success(), "REX4 must succeed; got {result_rex4:?}"); - - let diff = compute_rex5.abs_diff(compute_rex4); - assert!( - diff < 1_000, - "REX5 ({compute_rex5}) vs REX4 ({compute_rex4}) compute_gas must agree within 1K gas — diff = {diff}", - ); -} - /// Runs a CREATE2 contract built from raw bytecode (used to construct stack-underflow /// scenarios that `build_create2_contract` cannot express). Mirrors `transact_create2`. fn transact_create2_with_code( diff --git a/crates/mega-evm/tests/rex5/db_error.rs b/crates/mega-evm/tests/_pending/rex5/db_error.rs similarity index 100% rename from crates/mega-evm/tests/rex5/db_error.rs rename to crates/mega-evm/tests/_pending/rex5/db_error.rs diff --git a/crates/mega-evm/tests/rex5/deposit_caller_accounting.rs b/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs similarity index 92% rename from crates/mega-evm/tests/rex5/deposit_caller_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs index 19dacf310..91767300f 100644 --- a/crates/mega-evm/tests/rex5/deposit_caller_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs @@ -234,42 +234,6 @@ fn test_rex5_non_empty_caller_no_extra_charge() { let _ = gas_normal; // referenced for clarity; precise inequality is implicit via growth check. } -/// REX4 replay parity: under stable REX4, deposit-driven caller materialisation -/// does NOT charge caller-side storage gas and does NOT record a state-growth -/// event. Any drift here breaks replay of historical REX4 blocks. -#[test] -fn test_rex4_baseline_behaviour() { - let db_empty = - MemoryDatabase::default().account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_empty = make_op_deposit_tx(EMPTY_CALLER, 1_000_000u128, TARGET_CONTRACT); - let (res_empty, evm_empty) = transact_with(MegaSpecId::REX4, db_empty, tx_empty); - let res_empty = res_empty.expect("ok"); - assert!(res_empty.result.is_success()); - - let db_funded = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_funded = make_op_deposit_tx(FUNDED_CALLER, 1_000_000u128, TARGET_CONTRACT); - let (res_funded, evm_funded) = transact_with(MegaSpecId::REX4, db_funded, tx_funded); - let res_funded = res_funded.expect("ok"); - assert!(res_funded.result.is_success()); - - // REX4: empty vs funded must produce identical gas usage on the deposit-caller path - // (the only legitimate gas delta would come from the deposit-caller rule, which is REX5-gated). - assert_eq!( - res_empty.result.gas_used(), - res_funded.result.gas_used(), - "REX4 deposit gas must be identical between empty and funded caller", - ); - // REX4: state_growth must be unaffected by the deposit caller materialisation. - let growth_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage().state_growth; - let growth_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage().state_growth; - assert_eq!( - growth_empty, growth_funded, - "REX4 state_growth must not differ between empty and funded caller", - ); -} - /// Routes every account to a single high-capacity bucket so the new-account /// storage gas charge under REX5 (`25_000 × (multiplier - 1)`) is non-zero. #[derive(Debug, Clone, Copy)] diff --git a/crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs similarity index 91% rename from crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs rename to crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs index c1ace9870..c70520043 100644 --- a/crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs @@ -147,25 +147,6 @@ fn test_deposit_create_storage_gas_uses_state_nonce() { ); } -/// Same diverging-nonce setup under REX4: pre-REX5 prices storage gas at -/// `caller.create(tx.nonce)`, which lands in the default cheap bucket. -#[test] -fn test_pre_rex5_preserves_tx_nonce_storage_gas_pricing() { - let mut db = seed_caller(STATE_NONCE); - let envs = envs_with_heavy_bucket_at(STATE_NONCE); - let gas_limit = 50_000_000; - let tx = deposit_create_tx(TX_NONCE, gas_limit); - - let res = run(MegaSpecId::REX4, &mut db, &envs, tx); - - assert!(res.result.is_success(), "deposit CREATE must succeed: {:?}", res.result); - let gas_used = res.result.gas_used(); - assert!( - gas_used < EXPECTED_HEAVY_STORAGE_GAS, - "expected gas_used < {EXPECTED_HEAVY_STORAGE_GAS} (cheap bucket), got {gas_used}", - ); -} - /// Non-deposit CREATE under REX5: `tx.nonce == state.nonce`, so the /// state-nonce read returns the same value as `tx.nonce()` did. #[test] diff --git a/crates/mega-evm/tests/rex5/eip7702_metering.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs similarity index 100% rename from crates/mega-evm/tests/rex5/eip7702_metering.rs rename to crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs diff --git a/crates/mega-evm/tests/rex5/eip7702_state_growth.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs similarity index 92% rename from crates/mega-evm/tests/rex5/eip7702_state_growth.rs rename to crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs index aaf77b308..189fbfb49 100644 --- a/crates/mega-evm/tests/rex5/eip7702_state_growth.rs +++ b/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs @@ -106,39 +106,6 @@ fn test_rex5_new_authority_state_growth() { ); } -/// The same transaction under REX4 should NOT include authority accounts in state growth. -/// -/// Pre-REX5, EIP-7702 authority accounts are not counted toward state growth. -#[test] -fn test_rex4_single_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // REX4 does not count authority accounts in state growth. - assert_eq!( - usage.state_growth, 0, - "REX4 should not count authority accounts in state growth: {}", - usage.state_growth - ); -} - /// REX5 with two new authorities should count +2 state growth. #[test] fn test_rex5_two_new_authorities_state_growth() { diff --git a/crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs b/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs similarity index 75% rename from crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs rename to crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs index d3cd9ee2f..16d38dab5 100644 --- a/crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs +++ b/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs @@ -128,23 +128,6 @@ fn test_rex5_two_value_calls_dedup_parent_kv() { assert_eq!(data_size, intrinsic_data_size() + 3 * ACCOUNT_INFO_WRITE_SIZE); } -#[test] -fn test_rex4_two_value_calls_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_value_calls_code()); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5 behavior: the CALLEE parent update is charged on BOTH calls. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double-charged) + 1 (CONTRACT) + 1 (CONTRACT2) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); - assert_eq!(data_size, intrinsic_data_size() + 4 * ACCOUNT_INFO_WRITE_SIZE); -} - // ============================================================================ // CREATE followed by value-transferring CALL // ============================================================================ @@ -174,22 +157,6 @@ fn test_rex5_create_then_call_dedup_parent_kv() { assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE update across CREATE and CALL"); } -#[test] -fn test_rex4_create_then_call_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, create_then_call_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5 behavior: CALLEE parent charged both by CREATE and by the subsequent CALL. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double-charged) + 1 (created) + 1 (CONTRACT) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); -} - // ============================================================================ // Two consecutive CREATEs from the same parent // ============================================================================ @@ -218,22 +185,6 @@ fn test_rex5_two_creates_dedup_parent_kv() { assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE across both CREATEs"); } -#[test] -fn test_rex4_two_creates_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_creates_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5: CALLEE parent charged on BOTH CREATEs. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double) + 2 (created accounts) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); -} - // ============================================================================ // Reverted child still discards its accumulated charges // ============================================================================ @@ -265,23 +216,6 @@ fn test_rex5_reverted_child_drops_discardable_charges() { assert_eq!(data_size, intrinsic_data_size(), "Reverted child's data size must be dropped"); } -#[test] -fn test_rex4_reverted_child_drops_discardable_charges() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, call_that_reverts_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success(), "outer TX succeeds even though child reverts"); - - // Existing revert behavior must stay unchanged pre-Rex5. - assert_eq!(kv_updates, 1); - assert_eq!(data_size, intrinsic_data_size()); -} - // ============================================================================ // Reverted first child followed by a successful second child (revert-then-retry) // ============================================================================ @@ -320,22 +254,3 @@ fn test_rex5_reverted_first_child_flag_reset_allows_second_charge() { assert_eq!(data_size, intrinsic_data_size() + 2 * ACCOUNT_INFO_WRITE_SIZE); } -#[test] -fn test_rex4_reverted_first_child_flag_not_set() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, revert_then_succeed_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5: flag is never set, so both calls charge the parent independently. - // KV updates: 1 (caller nonce) + 1 (CALLEE from 1st call, dropped on revert) - // + 1 (CALLEE from 2nd call) + 1 (CONTRACT2) = 3. - // Note: the first call's CALLEE charge is dropped on revert, so Rex4 also gives 3 here. - // The overcounting in Rex4 manifests when BOTH calls succeed (tested separately above). - assert_eq!(kv_updates, 3); -} diff --git a/crates/mega-evm/tests/rex5/gas_validation.rs b/crates/mega-evm/tests/_pending/rex5/gas_validation.rs similarity index 86% rename from crates/mega-evm/tests/rex5/gas_validation.rs rename to crates/mega-evm/tests/_pending/rex5/gas_validation.rs index 86b91faba..f6d7752c7 100644 --- a/crates/mega-evm/tests/rex5/gas_validation.rs +++ b/crates/mega-evm/tests/_pending/rex5/gas_validation.rs @@ -222,41 +222,6 @@ fn test_rex5_valid_tx_still_passes() { // second pre-REX5 code path (REX adds `TX_INTRINSIC_STORAGE_GAS`, so MINI_REX and REX..REX4 walk // Mega-step-D differently). -/// REX4 (stable spec) must preserve the historical bug-shape behavior: `validate()` accepts -/// the tx, `pre_execution()` debits and bumps, and execution synthesizes an OOG halt with -/// `gas_used == gas_limit`. This test fails loudly if any future change leaks the REX5 -/// rejection back into a stable spec. -#[test] -fn test_rex4_preserves_legacy_oog_after_full_gas_charge() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000u64)); - - let multiplier = 10u64; - let external_envs = external_envs_with_hot_account(NEW_ACCOUNT, multiplier); - - // Same scenario shape as the REX5 test, with a gas limit that covers intrinsic+REX - // intrinsic-storage but not new-account storage gas. - let insufficient_gas_limit = 80_000; - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(NEW_ACCOUNT), - data: Bytes::new(), - value: U256::from(1), - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - - let res = run_tx(MegaSpecId::REX4, &mut db, external_envs, tx) - .expect("pre-REX5 specs must NOT reject this as a validation error"); - assert!(!res.result.is_success(), "REX4 must still produce a halt, not success"); - assert!(res.result.is_halt(), "REX4 must still produce a halt-shaped result"); - assert_eq!( - res.result.gas_used(), - insufficient_gas_limit, - "REX4 must still consume the entire gas limit (bug-shape preserved)" - ); -} - // `_` to prove `InvalidTransaction` from `revm::context::result` is reachable via the // public re-export and to catch a future revm bump that drops the variant. const _: fn() = || { diff --git a/crates/mega-evm/tests/rex5/interceptor_selector_probe.rs b/crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs similarity index 100% rename from crates/mega-evm/tests/rex5/interceptor_selector_probe.rs rename to crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs diff --git a/crates/mega-evm/tests/rex5/keyless_deploy_dispatch_parity.rs b/crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs similarity index 100% rename from crates/mega-evm/tests/rex5/keyless_deploy_dispatch_parity.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs diff --git a/crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs b/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs similarity index 85% rename from crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs index a04aee7ab..c70e692e0 100644 --- a/crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs @@ -242,46 +242,6 @@ fn test_rex5_keyless_empty_code_forwards_log_to_parent_receipt() { ); } -/// REX4 (pre-REX5 frozen): same input MUST return success-style with -/// `EmptyCodeDeployed` errorData, but the parent receipt MUST contain NO logs -/// (legacy "drop logs" behavior, preserved for replay parity). -#[test] -fn test_rex4_keyless_empty_code_drops_logs_for_replay_parity() { - let topic = - B256::from_slice(&hex!("ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11")); - let init_code = build_log1_then_empty_return_init_code(topic); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // REX4 sandbox is NOT fee-free — fund signer so the inner tx can pay - // `gas_limit_override × signed_gas_price` upfront. - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000u128)); - - // REX4 sandbox debits `gas_limit_override × signed_gas_price` from signer at - // pre-execution. With `signed_gas_price = 100 gwei`, an override of 1M gas - // costs 0.0001 ETH — well within the 1 ETH funding above. Using - // `LARGE_GAS_LIMIT_OVERRIDE` (10^10) here would demand 10^21 wei = 1000 ETH - // and trip the `InsufficientBalance` precheck before the sandbox can run. - let rex4_gas_limit_override: u64 = 1_000_000; - let result = - run_keyless_outer(MegaSpecId::REX4, &mut db, keyless_tx_bytes, rex4_gas_limit_override); - - let error_data = extract_error_data(&result); - let decoded_err = decode_error_result(&error_data); - assert!( - matches!(decoded_err, Some(KeylessDeployError::EmptyCodeDeployed { .. })), - "REX4 empty-code path must surface EmptyCodeDeployed in errorData; got {decoded_err:?}", - ); - - let logs = result.logs(); - assert!( - logs.is_empty(), - "REX4 empty-code path must NOT forward sandbox logs (frozen for replay parity); \ - got logs = {logs:?}", - ); -} - /// REX5 with an empty-code constructor that emits NO logs MUST report /// `EmptyCodeDeployed` AND a zero-length receipt log list. Pins that the /// `SandboxCompletion::EmptyCode` wiring forwards exactly the logs the sandbox emitted, not diff --git a/crates/mega-evm/tests/rex5/keyless_fee_free.rs b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs similarity index 96% rename from crates/mega-evm/tests/rex5/keyless_fee_free.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs index 746f3e9f9..3c8bf8483 100644 --- a/crates/mega-evm/tests/rex5/keyless_fee_free.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs @@ -235,41 +235,6 @@ fn test_rex5_value_zero_signer_zero_balance_deploys_successfully() { // 2. REX4 keeps the `gas_cost + value` balance precheck // ============================================================================ -/// REX4 (frozen spec): the sandbox's pre-execution balance check must reject an -/// unfunded signer, because pre-Rex5 runs the sandbox as a non-deposit tx that -/// debits `gas_limit × gas_price` from the signer. The fee-free simplification -/// is REX5-only. -#[test] -fn test_rex4_unfunded_signer_still_rejected_by_balance_precheck() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // signer NOT funded; pre-Rex5 gas_cost > 0 so balance check trips. - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - _ => panic!( - "REX4 must revert when sandbox pre-check rejects unfunded signer; got {result:?}" - ), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - assert!( - matches!(err, KeylessDeployError::InsufficientBalance), - "REX4 must reject unfunded signer with InsufficientBalance; got {err:?}", - ); -} - // ============================================================================ // 3. value > 0 still requires the signer to fund the transfer (REX5) // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs b/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs similarity index 89% rename from crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs index 67429f4e1..f8181ede7 100644 --- a/crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs @@ -208,42 +208,6 @@ fn test_rex5_envelope_above_signed_min_proceeds_normally() { ); } -/// REX4 parity: same envelope-too-small setup must NOT produce the post-cap -/// `GasLimitTooLow` shape under the pre-REX5 spec (no cap is applied, so the -/// recheck never sees a capped value smaller than `tx_gas_limit`). Any other -/// outcome — sandbox OOG, balance precheck, etc. — is acceptable as the -/// baseline; we just pin that the new REX5 path is genuinely REX5-gated. -#[test] -fn test_rex4_envelope_too_small_does_not_fire_post_cap_recheck() { - let (keyless_tx_bytes, signer) = build_keyless_tx(); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Fund signer enough to cover the REX4 sandbox's `gas_limit × gas_price` - // balance precheck when the sandbox runs uncapped at `LARGE_OVERRIDE`. - db.set_account_balance(signer, U256::from(100_000_000_000_000_000_000u128)); - - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - keyless_tx_bytes, - LARGE_OVERRIDE, - TIGHT_OUTER_GAS, - ); - - if let ExecutionResult::Revert { output, .. } = &result { - if let Some(KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit }) = - decode_error_result(output) - { - assert!( - provided_gas_limit >= tx_gas_limit, - "REX4 must not produce the post-cap-capped GasLimitTooLow shape; \ - got provided_gas_limit ({provided_gas_limit}) < tx_gas_limit ({tx_gas_limit})", - ); - } - } -} - /// Post-cap recheck must fire on the materialization-drain shape: outer envelope is /// fat enough to clear intrinsic + `KEYLESS_DEPLOY_OVERHEAD_GAS` without dipping below /// `tx_gas_limit`, but `charge_caller_materialization_pre_sandbox` for an unfunded diff --git a/crates/mega-evm/tests/rex5/keyless_replay_barrier.rs b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs similarity index 87% rename from crates/mega-evm/tests/rex5/keyless_replay_barrier.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs index fab84fa55..cc0dc2cce 100644 --- a/crates/mega-evm/tests/rex5/keyless_replay_barrier.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs @@ -201,51 +201,6 @@ fn test_keyless_signer_charge_implies_replay_barrier() { ); } -/// REX4 (stable spec) must preserve the historical bug-shape behavior on the same input: -/// outer call returns `Success` with errorData (not Revert), the signer IS fee-debited, -/// and no replay barrier is installed (signer nonce stays 0, deploy address has no code). -/// This test fails loudly if any future change leaks the REX5 sandbox-validate rejection -/// back into a stable spec. -#[test] -fn test_rex4_keyless_preserves_signer_charge_without_barrier() { - let mut db = MemoryDatabase::default(); - - let signer_starting_balance = U256::from(1_000_000_000_000_000_000_000u128); // 1000 ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, signer_starting_balance); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let contract_bucket = - ::bucket_id_for_account(CREATE2_FACTORY_CONTRACT); - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket, MIN_BUCKET_SIZE as u64 * 2); - - let gas_limit_override = 120_000; - - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - external_envs, - Bytes::from_static(CREATE2_FACTORY_TX), - gas_limit_override, - ); - - // Outer call surfaces as Success — the keyless interceptor returns success-with-error-data - // on inner failure under stable specs, so the relayer is not penalized. - assert!( - result.is_success(), - "REX4 keyless inner-fail path MUST keep returning outer Success; got {result:?}", - ); - // Signer IS charged for the full sandbox gas budget (the historical drain shape). - let signer_after = account_info(&mut db, CREATE2_FACTORY_DEPLOYER); - assert!( - signer_after.balance < signer_starting_balance, - "REX4: signer balance must be reduced (stable bug-shape preserved)", - ); - // No barrier installed: nonce stays at 0, deploy address has no code → still replayable. - assert_eq!(signer_after.nonce, 0, "REX4: signer nonce must stay replayable"); - assert!(!has_code(&mut db, CREATE2_FACTORY_CONTRACT), "REX4: deploy address must remain empty",); -} - // ============================================================================ // 2. Runtime-revert path: signer charge AND nonce bump (barrier consumed) // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs similarity index 97% rename from crates/mega-evm/tests/rex5/main.rs rename to crates/mega-evm/tests/_pending/rex5/main.rs index f1e341aac..1282dc08f 100644 --- a/crates/mega-evm/tests/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -5,7 +5,6 @@ mod call_too_deep_guard; mod callcode_storage_gas; mod create2_empty_initcode; mod create2_resize_gas_metering; -mod create_atomicity; mod db_error; mod deposit_caller_accounting; mod deposit_create_storage_gas; diff --git a/crates/mega-evm/tests/rex5/oracle_hint_metering.rs b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs similarity index 89% rename from crates/mega-evm/tests/rex5/oracle_hint_metering.rs rename to crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs index 6e7451a1d..e64e732cd 100644 --- a/crates/mega-evm/tests/rex5/oracle_hint_metering.rs +++ b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs @@ -164,34 +164,6 @@ fn test_rex5_zero_gas_send_hint_does_not_forward() { assert!(hints.is_empty(), "zero-gas sendHint must not forward to on_hint (REX5)",); } -/// Pre-REX5 baseline: zero-gas sendHint still forwards. Pinned to guarantee replay -/// determinism on stable specs. -#[test] -fn test_rex4_zero_gas_send_hint_still_forwards() { - let code = build_send_hint_bytecode(TOPIC, 64, 0); - let (result, hints, _) = run_with_oracle(MegaSpecId::REX4, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "REX4 must keep the pre-REX5 unmetered, zero-gas-accepting path",); -} - -/// REX4 replay parity: a normal sendHint with a large payload under REX4 must NOT -/// be charged against `data_size_used`. This pins the pre-REX5 unmetered invariant — -/// if hint metering accidentally activated on stable specs, the data-size lane -/// would grow and replay of historical REX4 blocks would diverge. -#[test] -fn test_rex4_does_not_meter_send_hint_payload() { - let payload_size = 1024; - let code = build_send_hint_bytecode(TOPIC, payload_size, 100_000); - let (result, hints, data_size) = run_with_oracle(MegaSpecId::REX4, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "REX4 must still forward normal sendHints"); - assert!( - data_size < payload_size as u64, - "REX4 must NOT charge the {payload_size}-byte payload against data_size (got {})", - data_size, - ); -} - /// REX5 invariant 2: a normal sendHint with positive gas still forwards to `on_hint` /// (parity with the pre-REX5 happy path). #[test] @@ -389,37 +361,6 @@ fn test_rex5_trailing_junk_after_valid_send_hint_is_metered() { assert!(hints.is_empty(), "trailing junk must NOT forward when over budget"); } -/// The REX5 `input_bytes.len()` charge is strictly larger than the legacy -/// `data.len() + 32` formula. Verified by comparing REX5 (with metering) to REX4 -/// (no metering, baseline pinned by `test_rex4_does_not_meter_send_hint_payload`) -/// for a `sendHint(topic, empty data)` call: the encoded ABI envelope is -/// `selector(4) + topic(32) + data_offset(32) + data_length(32) = 100` bytes; the -/// legacy formula would have charged `0 + HINT_TOPIC_BYTES = 32` bytes. A regression -/// that restored the legacy `call.data.len() + 32` charge would shrink `extra` below -/// the legacy threshold. -#[test] -fn test_rex5_charge_is_strictly_more_conservative_than_legacy_formula() { - let code = build_send_hint_bytecode(TOPIC, 0, 100_000); // empty `data` - let (_, _, rex4) = run_with_oracle(MegaSpecId::REX4, code.clone(), u64::MAX); - let (_, _, rex5) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - - let new_charge: u64 = 100; // input_bytes.len() for sendHint(topic, empty) - let pre_fix_charge: u64 = 32; // legacy: data.len() + HINT_TOPIC_BYTES - - let extra = rex5 - .checked_sub(rex4) - .expect("REX5 must record at least as much data_size as REX4 for identical bytecode"); - assert!( - extra >= new_charge, - "REX5 must charge at least input_bytes.len()={new_charge} more than REX4 (got {extra})", - ); - assert!( - extra > pre_fix_charge, - "post-fix REX5 must charge strictly more than the legacy formula \ - (data.len()+32={pre_fix_charge}); got extra={extra}", - ); -} - /// REX5 invariant: consecutive `sendHint` calls in the same TX accumulate their /// `input_bytes.len()` charges into the TX `persistent_usage` lane. With a budget sized /// for one call but not two, the first sendHint must forward and the second must be diff --git a/crates/mega-evm/tests/rex5/pre_block_system_calls.rs b/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs similarity index 86% rename from crates/mega-evm/tests/rex5/pre_block_system_calls.rs rename to crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs index 2e7b1f1e7..bd52867ca 100644 --- a/crates/mega-evm/tests/rex5/pre_block_system_calls.rs +++ b/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs @@ -247,109 +247,6 @@ fn test_rex5_block_rejected_when_beacon_root_pre_block_call_halts() { ); } -/// Same heavy-SALT scenario under a Rex4 chain spec: pre-REX5 keeps its -/// existing accept-and-commit-empty behavior so historical replay is -/// byte-for-byte deterministic. -#[test] -fn test_pre_rex5_preserves_silent_pre_block_call_failure() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex4_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX4, BLOCK_GAS_LIMIT), - ); - - executor - .apply_pre_execution_changes() - .expect("pre-REX5 must accept a halted pre-block system call"); - - // The OOG'd SSTORE never wrote the parent hash to the ring-buffer slot the - // contract targets, `(block.number - 1) % 8191`. - let storage_after = executor - .evm_mut() - .db_mut() - .storage( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - U256::from((ACTIVATION_BLOCK - 1) % 8191), - ) - .unwrap(); - let parent_hash_word = U256::from_be_bytes(B256::from([0x29; 32]).0); - assert_ne!( - storage_after, parent_hash_word, - "history-storage slot 0 must not contain the parent hash; the SSTORE OOG'd", - ); -} - -/// The counterpart to `test_rex5_block_aware_budget_accepts_pre_block_call_above_30m`: on a -/// pre-REX5 chain the same ≈100M-per-SSTORE costs must still OOG, because pre-REX5 keeps -/// revm's upstream-fixed 30M budget for replay parity. The budget selection must follow the -/// `REX5` spec exactly — a gate at any earlier spec would run these historical blocks with -/// the block-aware budget and commit writes that mainnet history does not contain. The block -/// is still accepted (no fail-closed pre-REX5), but neither contract's slot may be written. -#[test] -fn test_pre_rex5_keeps_upstream_30m_budget_for_pre_block_calls() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(medium_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex4_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX4, BLOCK_GAS_LIMIT), - ); - - executor - .apply_pre_execution_changes() - .expect("pre-REX5 must accept the halted pre-block system calls"); - - // EIP-2935: the ≈100M SSTORE OOG'd inside the 30M budget, so the ring-buffer slot the - // contract writes the parent hash to — `(block.number - 1) % 8191` — must stay empty. - let history_slot = executor - .evm_mut() - .db_mut() - .storage( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - U256::from((ACTIVATION_BLOCK - 1) % 8191), - ) - .unwrap(); - assert_ne!( - history_slot, - U256::from_be_bytes(B256::from([0x29; 32]).0), - "EIP-2935 must stay on the 30M budget pre-REX5, so the ≈100M write cannot land", - ); - - // EIP-4788: same for the beacon-roots timestamp slot (the contract's ring buffer keys - // slots by `timestamp % 8191`). - let timestamp_slot = U256::from(1_800_000_000u64 % 8191); - let stored_timestamp = executor - .evm_mut() - .db_mut() - .storage(alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, timestamp_slot) - .unwrap(); - assert_ne!( - stored_timestamp, - U256::from(1_800_000_000u64), - "EIP-4788 must stay on the 30M budget pre-REX5, so the ≈100M writes cannot land", - ); -} - /// Medium SALT makes each EIP-2935 / EIP-4788 SSTORE cost ≈ 100M of /// dynamic storage gas — above revm's upstream-fixed 30M default but /// within the REX5 `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` diff --git a/crates/mega-evm/tests/rex5/precompile_compute_gas.rs b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs similarity index 57% rename from crates/mega-evm/tests/rex5/precompile_compute_gas.rs rename to crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs index a3cf42465..33371005f 100644 --- a/crates/mega-evm/tests/rex5/precompile_compute_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs @@ -177,130 +177,6 @@ fn kzg_wrapper_bytecode(input: &[u8], forwarded_gas: u64) -> Bytes { // TESTS // ============================================================================ -/// A precompile CALL that fails with `PrecompileOOG` should record the full forwarded gas -/// as compute gas in REX5, but 0 in REX4. -/// -/// ecrecover (address 0x01) costs 3000 gas. Forwarding only 2999 gas triggers -/// `PrecompileOOG`. The parent permanently loses the 2999 gas (`is_ok_or_revert()` is -/// false -> no refund), but pre-REX5 specs record 0 compute gas because `spent()` = 0. -/// REX5 fixes this by recording `limit()` (= forwarded gas) on error paths. -#[test] -fn test_rex5_precompile_oog_records_forwarded_gas_as_compute_gas() { - // ecrecover requires 3000 gas. Forward only 2999 to trigger PrecompileOOG. - let forwarded_gas: u64 = 2_999; - - // Contract: store 128 bytes of input in memory (ecrecover expects 128 bytes), - // then CALL ecrecover with insufficient gas. - let code = BytecodeBuilder::default() - // Write 128 bytes of zeros at memory offset 0 (valid-length but invalid-content - // input for ecrecover, but irrelevant because it will OOG before processing). - .mstore(0, [0u8; 32]) - .mstore(32, [0u8; 32]) - .mstore(64, [0u8; 32]) - .mstore(96, [0u8; 32]) - // CALL ecrecover with 128-byte input but only 2999 gas - .push_number(32_u64) // retSize - .push_number(128_u64) // retOffset - .push_number(128_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ECRECOVER) - .push_number(forwarded_gas) // gas (< 3000, triggers OOG) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, compute_gas_rex5) = transact(MegaSpecId::REX5, &mut db, tx.clone()); - assert!( - result_rex5.result.is_success(), - "outer tx should succeed (precompile failure is caught by CALL)" - ); - - let (result_rex4, compute_gas_rex4) = transact(MegaSpecId::REX4, &mut db, tx); - assert!( - result_rex4.result.is_success(), - "outer tx should succeed (precompile failure is caught by CALL)" - ); - - // REX5 should record more compute gas because the failing precompile's forwarded gas - // is now counted. REX4 records 0 for the failing precompile path (spent() = 0). - assert!( - compute_gas_rex5 > compute_gas_rex4, - "REX5 compute gas ({compute_gas_rex5}) should be higher than REX4 ({compute_gas_rex4}) \ - due to PrecompileOOG compute gas accounting" - ); - - // The difference should be approximately the forwarded gas amount. - let diff = compute_gas_rex5 - compute_gas_rex4; - assert!( - diff >= forwarded_gas, - "compute gas difference ({diff}) should be at least the forwarded gas ({forwarded_gas})" - ); -} - -/// A precompile CALL that fails with `PrecompileError` (not OOG) should also record -/// the full forwarded gas as compute gas in REX5. -/// -/// Blake2f (0x09) requires exactly 213 bytes of input. Calling it with wrong-length -/// input triggers `PrecompileError::Other`, which is distinct from `PrecompileOOG`. -/// Both error types hit the same `!is_ok_or_revert()` branch, but this test guards -/// against future regressions that might split the handling. -#[test] -fn test_rex5_precompile_error_records_forwarded_gas_as_compute_gas() { - let forwarded_gas: u64 = 50_000; - - // Contract: CALL blake2f with 1 byte of input (wrong length → PrecompileError). - let code = BytecodeBuilder::default() - // Store 1 byte at memory[0] - .mstore(0, [0xffu8; 1]) - // CALL blake2f with 1-byte input - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(1_u64) // argsSize = 1 (invalid: blake2f requires 213) - .push_number(31_u64) // argsOffset (last byte of the 32-byte word) - .push_number(0_u64) // value - .push_address(BLAKE2F) - .push_number(forwarded_gas) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, compute_gas_rex5) = transact(MegaSpecId::REX5, &mut db, tx.clone()); - assert!(result_rex5.result.is_success(), "outer tx should succeed"); - - let (result_rex4, compute_gas_rex4) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result_rex4.result.is_success(), "outer tx should succeed"); - - // Same pattern as OOG test: REX5 records forwarded gas, REX4 records 0. - assert!( - compute_gas_rex5 > compute_gas_rex4, - "REX5 compute gas ({compute_gas_rex5}) should be higher than REX4 ({compute_gas_rex4}) \ - due to PrecompileError compute gas accounting" - ); - - let diff = compute_gas_rex5 - compute_gas_rex4; - assert!( - diff >= forwarded_gas, - "compute gas difference ({diff}) should be at least the forwarded gas ({forwarded_gas})" - ); -} - // ============================================================================ // KZG fixed-cost compute-gas accounting (REX5) // ============================================================================ @@ -398,83 +274,3 @@ fn test_rex5_kzg_invalid_input_length_records_exact_gas_cost() { ); } -/// Cap-induced OOG: `tx_compute_gas_limit = KZG_GAS_COST - 1` so the REX5 cap -/// drives `effective_gas_limit < KZG_GAS_COST`. The wrapper's own -/// `gas_limit < GAS_COST` pre-check fires before verification runs; the -/// recorded compute-gas matches the cap, **not** `KZG_GAS_COST` — the -/// fixed-cost arm must not fire on this path. -#[test] -fn test_rex5_kzg_cap_induced_oog_still_records_capped_limit() { - // `forwarded_gas` is deliberately set well above KZG_GAS_COST. The wrapper - // contract pushes this onto the stack as the CALL opcode's `gas` argument, - // but it does NOT bound the precompile here — `tx_compute_gas_limit` does, - // via the REX5 cap inside `PrecompilesMap::run`. Setting `forwarded_gas` - // small enough to OOG on its own would exercise a different code path. - let forwarded_gas: u64 = 500_000; - let tx_compute_gas_limit = KZG_GAS_COST - 1; - let code = kzg_wrapper_bytecode(&valid_kzg_input(), forwarded_gas); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // The outer tx may halt (TX-level compute limit exceeded) — `transact_raw` - // returns `ResultAndState` either way. We only care about the compute-gas - // tracker's final value. - let (_, compute_gas) = - transact_with_compute_limit(MegaSpecId::REX5, &mut db, tx, Some(tx_compute_gas_limit)); - - // If the fixed-cost arm had fired, the precompile alone would contribute - // KZG_GAS_COST and total compute_gas would be >= KZG_GAS_COST. With the cap - // engaging at GAS_COST - 1 the precompile contribution is bounded by the cap. - assert!( - compute_gas < KZG_GAS_COST, - "cap-induced OOG must NOT take the fixed-cost arm (compute_gas={compute_gas}, \ - KZG_GAS_COST={KZG_GAS_COST}). If it had fired, the precompile contribution \ - alone would equal KZG_GAS_COST." - ); - // Total compute_gas is bounded by the TX-level cap (clamped at limit on overflow). - assert!( - compute_gas <= tx_compute_gas_limit, - "total compute_gas ({compute_gas}) must not exceed tx_compute_gas_limit \ - ({tx_compute_gas_limit})" - ); -} - -/// Stable-spec replay-preservation guard. REX4 keeps the KZG -/// verification-failure precompile contribution at 0 compute-gas; any change -/// to this would shift `tx_compute_gas_used` on historical REX4 blocks and -/// break byte-for-byte replay. -/// -/// Assertion strategy: this test cannot assert `compute_gas == 0` because the -/// wrapper contract's MSTORE / PUSH / CALL opcodes themselves consume some -/// compute-gas (~23k observed). The bound pinned here is "the precompile -/// contributes strictly less than `KZG_GAS_COST` on REX4". The differential -/// test `test_rex5_kzg_invalid_proof_records_exact_gas_cost` separately -/// asserts `REX5 - REX4 == KZG_GAS_COST`, which together with this bound pins -/// the per-spec contribution exactly. -#[test] -fn test_rex4_kzg_invalid_proof_keeps_zero_compute_gas() { - let forwarded_gas: u64 = 500_000; - let code = kzg_wrapper_bytecode(&invalid_proof_kzg_input(), forwarded_gas); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, compute_gas) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.result.is_success(), "outer tx should succeed (KZG failure caught by CALL)"); - assert!( - compute_gas < KZG_GAS_COST, - "REX4 precompile contribution must remain 0. Total compute_gas \ - ({compute_gas}) >= KZG_GAS_COST ({KZG_GAS_COST}) indicates the precompile \ - alone contributed KZG_GAS_COST — a replay-determinism regression where the \ - REX5 fixed-cost arm silently activated on REX4." - ); -} diff --git a/crates/mega-evm/tests/rex5/sandbox_accounting.rs b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs similarity index 57% rename from crates/mega-evm/tests/rex5/sandbox_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs index 584454505..d9e13f7cd 100644 --- a/crates/mega-evm/tests/rex5/sandbox_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs @@ -391,27 +391,6 @@ fn test_rex5_sandbox_success_propagates_resource_usage() { assert!(usage.state_growth > 0, "state growth should include new account from sandbox"); } -/// REX4 sandbox does NOT propagate resource usage to the parent transaction. -/// -/// The same constructor that works in REX5 should have zero state growth in REX4 -/// because sandbox usage is not propagated. -#[test] -fn test_rex4_sandbox_does_not_propagate_resource_usage() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(minimal_1byte_constructor(42)); - let mut db = funded_signer_db(signer); - - let (result, usage) = - execute_keyless_deploy(MegaSpecId::REX4, &mut db, tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - assert!(result.is_success(), "keyless deploy should succeed: {result:?}"); - - // The sandbox's storage writes should NOT appear in parent usage in REX4. - assert_eq!( - usage.state_growth, 0, - "REX4 should not propagate sandbox state growth, got: {}", - usage.state_growth - ); -} - /// Executes a keyless deploy with custom runtime limits, returning the full `ResultAndState`. fn execute_keyless_deploy_with_limits( spec: MegaSpecId, @@ -466,507 +445,6 @@ fn assert_preflight_failure_without_sandbox_state( error } -/// REX5 must fail the sandbox internally when the parent's remaining state-growth budget is -/// smaller than the sandbox's required state growth. -/// -/// Regression test for the upfront-cap design: tightening the parent state-growth limit -/// should now make the sandbox fail internally, returning success-style `errorData` -/// instead of letting the sandbox succeed and halting the outer transaction afterwards. -#[test] -fn test_rex5_sandbox_tight_state_growth_budget_fails_inside_sandbox() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(42)); - assert!(baseline_usage.state_growth > 0, "baseline deploy should consume state growth"); - - // Give the parent slightly less state growth than the successful sandbox needs. - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_state_growth_limit(baseline_usage.state_growth.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // The outer transaction should still return successfully with encoded execution failure. - assert!( - result_and_state.result.is_success(), - "outer transaction should return success-style failure, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - - // The deployed contract must NOT exist in the finalized state. - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract code must not survive sandbox-internal limit failure"); -} - -/// REX5: when `record_deposit_caller_creation` (inside -/// `charge_caller_materialization_pre_sandbox`) latches a non-frame-local -/// `StateGrowthLimitExceeded`, the keyless-deploy interceptor MUST emit the canonical -/// exceeding-limit OOG halt — with parent gas rescued — at the latch point. -/// -/// If the conversion is deferred, `before_frame_return_result::` still rewrites the -/// final Revert into a Halt at tx end, but its docstring's "gas should already have been -/// rescued at the point where the limit was exceeded" precondition is violated: -/// `after_frame_run`'s `try_rescue_gas` does not run on the interceptor short-circuit -/// path, so the parent loses its entire outer gas budget. -/// -/// The deploy address is pre-occupied with code so a deferred halt is observable: the -/// flow would reach the `ContractAlreadyExists` check and surface -/// `Revert(ContractAlreadyExists())` instead of the canonical state-growth Halt — which -/// the halt-vs-Revert assertion below distinguishes. -#[test] -fn test_rex5_pre_sandbox_materialization_state_growth_overflow_halts_immediately() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - // Signer must be empty (no balance, no nonce, no code) to enter the materialization - // branch — `AccountInfo::is_empty()` is the gate. Funding it would short-circuit the - // branch before the state-growth latch could fire. - let mut db = MemoryDatabase::default(); - // Pre-occupy the deploy address. The state-growth halt MUST fire before the - // `ContractAlreadyExists` check; if it ever fires later, the check surfaces - // `Revert(ContractAlreadyExists())` and the assertions below catch the regression. - let preexisting_code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - db.set_account_code(deploy_address, preexisting_code.clone()); - - // `tx_state_growth_limit = 0` so the materialization-side `+1` immediately overflows - // the TX-level state-growth budget on `record_deposit_caller_creation`. - let tx_limits = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0); - - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Must be a canonical exceeding-limit Halt, NOT a business-error Revert. - let halt_reason = match &result_and_state.result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - ExecutionResult::Revert { output, .. } => { - let err = decode_error_result(output); - panic!( - "state-growth overflow must produce a canonical Halt, not a business \ - Revert; got Revert with selector {err:?}", - ); - } - other => panic!("expected Halt, got {other:?}"), - }; - assert!( - matches!(halt_reason, MegaHaltReason::StateGrowthLimitExceeded { limit: 0, actual: 1 }), - "halt reason must be the canonical StateGrowthLimitExceeded {{ limit: 0, actual: 1 }}, \ - got {halt_reason:?}", - ); - - // Signer never bumped — the sandbox was never constructed. - let signer_nonce = result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!(signer_nonce, 0, "signer nonce must remain 0 when halt fires pre-sandbox"); - - // Deploy address's pre-existing code is untouched. - if let Some(acc) = result_and_state.state.get(&deploy_address) { - if let Some(code) = &acc.info.code { - assert_eq!( - code.bytes_slice(), - preexisting_code.as_ref(), - "pre-existing deploy-address code must not be overwritten", - ); - } - } - - // Gas was rescued — the unspent outer budget is returned to the sender; only the - // dispatch overhead, materialization charge, and tx intrinsic are reported as used. - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); -} - -/// REX5 preflights sandbox intrinsic compute gas before starting sandbox execution. -/// -/// If the parent's remaining compute budget cannot fit the sandbox transaction's intrinsic -/// compute gas, the sandbox must not start and signer state must not be merged. -#[test] -fn test_rex5_sandbox_intrinsic_compute_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_compute = intrinsic_compute_gas(&outer_tx); - let sandbox_intrinsic_compute = intrinsic_compute_gas(&sandbox_tx); - assert!(sandbox_intrinsic_compute > 0, "sandbox tx should have intrinsic compute gas"); - - // Parent limit = outer_intrinsic + overhead + sandbox_intrinsic - 1. Just below what - // the sandbox's own intrinsic recording would consume; preflight must reject. - let tx_limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit( - outer_intrinsic_compute + - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + - sandbox_intrinsic_compute - - 1, - ); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); -} - -/// REX5 preflights sandbox intrinsic data size before starting sandbox execution. -/// -/// This covers the `before_tx_start()` path where the sandbox tracker records base tx size, -/// input bytes, and caller account update as tx-level persistent usage. -#[test] -fn test_rex5_sandbox_intrinsic_data_size_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(7); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_data_size = intrinsic_data_size(&outer_tx); - let sandbox_intrinsic_data_size = intrinsic_data_size(&sandbox_tx); - assert!(sandbox_intrinsic_data_size > 0, "sandbox tx should have intrinsic data size"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(outer_intrinsic_data_size + sandbox_intrinsic_data_size - 1); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); -} - -/// REX5 preflights sandbox intrinsic KV updates before starting sandbox execution. -/// -/// This covers the `before_tx_start()` path where the sandbox tracker records the -/// sandbox caller account update as TX-level persistent usage. -#[test] -fn test_rex5_sandbox_intrinsic_kv_update_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(7); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_kv_updates = intrinsic_kv_updates(&outer_tx); - let sandbox_intrinsic_kv_updates = intrinsic_kv_updates(&sandbox_tx); - assert!(sandbox_intrinsic_kv_updates > 0, "sandbox tx should have intrinsic KV updates"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_updates_limit(outer_intrinsic_kv_updates + sandbox_intrinsic_kv_updates - 1); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - let error = - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); - assert!( - matches!(error, KeylessDeployError::ParentBudgetExceeded { kind: LimitKind::KVUpdate, .. }), - "KV preflight should reject with ParentBudgetExceeded(KVUpdate), got: {error:?}" - ); -} - -/// REX5 must fail the sandbox internally when the parent's remaining KV-update budget is -/// smaller than the sandbox's required KV updates. -/// -/// This covers execution-time KV updates after intrinsic preflight has passed, so the -/// sandbox should return a success-style failure and must not deploy the contract. -#[test] -fn test_rex5_sandbox_tight_kv_update_budget_fails_inside_sandbox() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.kv_updates > 0, "baseline deploy should consume KV updates"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_updates_limit(baseline_usage.kv_updates.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert!( - result_and_state.result.is_success(), - "outer transaction should return success-style failure, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract code must not survive sandbox KV limit failure"); -} - -/// REX5 must reject the outer transaction cleanly when a sandbox TX-level overflow on the -/// compute-gas dimension pushes the parent over its limit. -/// -/// The safety net in `merge_and_reject_if_overflow` detects post-merge overflow, refuses to -/// merge sandbox state (preventing the deployed contract from surviving via the unchecked -/// direct journal write), absorbs the sandbox's EVM gas via `record_cost` on the outer -/// caller, and rescues the remaining gas. Without this safety net the outer caller would -/// be seized the full parent gas AND the deployed contract would persist on a "halt" tx. -#[test] -fn test_rex5_sandbox_compute_gas_overflow_rejects_cleanly() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(42)); - assert!(baseline_usage.compute_gas > 0, "baseline deploy should consume compute gas"); - - // Tighten parent's compute gas limit just below what the full deploy needs so the - // sandbox's merged usage overshoots parent's remaining envelope by a single opcode. - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(baseline_usage.compute_gas.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Outer tx must halt — the parent's compute budget does not fit the sandbox. - assert!( - result_and_state.result.is_halt(), - "outer transaction should halt on sandbox compute gas overflow, got: {:?}", - result_and_state.result, - ); - - // The halt must NOT consume the full parent tx gas: the safety net rescues remaining - // gas and only charges the caller for the KeylessDeploy overhead plus sandbox gas. - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); - - // Deployed contract must NOT survive — the safety net skipped `apply_sandbox_state`. - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract must not survive outer reject"); - - // Signer state must NOT be modified — sandbox state was never merged. - let signer_nonce = result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!( - signer_nonce, 0, - "signer nonce must not be bumped on sandbox overflow reject, got: {signer_nonce}" - ); -} - -/// REX5 must reject cleanly when a sandbox TX-level data-size overflow — either intrinsic -/// or opcode-level — pushes the parent over its limit. -/// -/// The sandbox's `DataSizeTracker::before_tx_start` records the base transaction size, -/// the input length, and the caller account update as non-discardable TX-level usage. -/// Even if the frame-local check would normally revert a sandbox frame on data-size -/// exceed, TX-level overflow (when persistent usage alone is above cap) takes the -/// non-frame-local path and must be rejected by the safety net. -#[test] -fn test_rex5_sandbox_data_size_overflow_rejects_cleanly() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.data_size > 0, "baseline deploy should consume data size"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(baseline_usage.data_size.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Either outer halts (TX-level overflow path) or outer returns a success-style failure - // (frame-local revert path inside sandbox). Both are acceptable, but in the halt case - // the safety net must have rescued gas and prevented state survival. - if result_and_state.result.is_halt() { - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract must not survive outer reject"); - let signer_nonce = - result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!( - signer_nonce, 0, - "signer nonce must not be bumped on sandbox overflow reject, got: {signer_nonce}" - ); - } else { - // Frame-local revert path: sandbox failed internally, returned errorData. - assert!( - result_and_state.result.is_success(), - "outer transaction should be success-style failure if not halted, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - } -} - -/// REX5 should succeed when the parent's remaining compute-gas budget exactly matches the -/// sandbox's baseline compute usage. -/// -/// Companion to the state-growth exact-fit boundary test: covers compute gas, the other -/// dimension where overshoot from a single opcode would break the cap invariant. -#[test] -fn test_rex5_sandbox_exact_remaining_compute_gas_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.compute_gas > 0, "baseline deploy should consume compute gas"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(baseline_usage.compute_gas); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should succeed when the parent's remaining data-size budget exactly matches the -/// sandbox's baseline data-size usage. -#[test] -fn test_rex5_sandbox_exact_remaining_data_size_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.data_size > 0, "baseline deploy should consume data size"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(baseline_usage.data_size); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should succeed when the parent's remaining KV-update budget exactly matches the -/// sandbox's baseline KV usage. -#[test] -fn test_rex5_sandbox_exact_remaining_kv_updates_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.kv_updates > 0, "baseline deploy should consume KV updates"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(baseline_usage.kv_updates); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should still succeed when the parent's remaining state-growth budget exactly matches -/// the sandbox's required state growth. -/// -/// This boundary test guards the capped-limit math: the sandbox should be allowed to -/// consume the full remaining budget, and merging its usage back must not make the outer -/// transaction fail afterwards. -#[test] -fn test_rex5_sandbox_exact_remaining_budget_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(99)); - assert!(baseline_usage.state_growth > 0, "baseline deploy should consume state growth"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(baseline_usage.state_growth); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - /// Shared assertion: the outer tx succeeds, returns the expected deploy address with /// empty `errorData`, and the deployed bytecode survives in the finalized state. /// Used by both exact-remaining-budget boundary tests. @@ -1157,33 +635,6 @@ fn test_rex5_sandbox_outer_gas_used_includes_sandbox_gas_used_on_success() { ); } -/// REX4 parity: outer `gas_used` does NOT include `sandbox_gas_used`. Replay -/// determinism — pre-REX5 behavior must be preserved byte-for-byte. -#[test] -fn test_rex4_sandbox_outer_gas_used_excludes_sandbox_gas_used() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - let (result, _usage, _volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX4, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - let outer_gas_used = result.gas_used(); - let decoded = decode_keyless_deploy_return(&result); - let sandbox_gas_used = decoded.gasUsed; - - assert!( - outer_gas_used < constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + sandbox_gas_used, - "REX4: outer gas_used ({}) must NOT include sandbox gas_used ({}); only \ - dispatch overhead ({}) plus relayer-frame ops should be charged", - outer_gas_used, - sandbox_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - /// REX5 sandbox: on in-sandbox failure (`EmptyCodeDeployed` via STOP-only /// constructor), the outer `gas_used` must still include `sandbox_gas_used`. #[test] diff --git a/crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs similarity index 93% rename from crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs rename to crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index a9cca7fd5..e45281c84 100644 --- a/crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -97,40 +97,6 @@ fn test_rex5_selfdestruct_to_empty_beneficiary_records_state_growth() { ); } -/// SELFDESTRUCT to an empty beneficiary should NOT record additional metering in REX4. -/// -/// REX4 does not have the SELFDESTRUCT beneficiary metering hook. The baseline usage -/// from REX4 should be lower than REX5 for the same scenario. -#[test] -fn test_rex4_selfdestruct_to_empty_beneficiary_comparison() { - let code = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code.clone()) - .account_balance(CONTRACT, U256::from(1_000_000u64)) - }; - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, usage_rex5) = transact(MegaSpecId::REX5, &mut build_db(), tx.clone()); - assert!(result_rex5.result.is_success(), "REX5 should succeed: {result_rex5:?}"); - - let (result_rex4, usage_rex4) = transact(MegaSpecId::REX4, &mut build_db(), tx); - assert!(result_rex4.result.is_success(), "REX4 should succeed: {result_rex4:?}"); - - // REX5 should have higher state growth due to beneficiary metering. - assert!( - usage_rex5.state_growth > usage_rex4.state_growth, - "REX5 state growth ({}) should be higher than REX4 ({}) due to beneficiary metering", - usage_rex5.state_growth, - usage_rex4.state_growth - ); -} - /// SELFDESTRUCT with zero balance should NOT charge new-account fees. /// /// When a contract has zero balance and selfdestructs to an empty address, diff --git a/crates/mega-evm/tests/rex5/sstore_storage_gas_error.rs b/crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs similarity index 100% rename from crates/mega-evm/tests/rex5/sstore_storage_gas_error.rs rename to crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs diff --git a/crates/mega-evm/tests/rex5/stipend_accounting.rs b/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs similarity index 60% rename from crates/mega-evm/tests/rex5/stipend_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs index 1d8894235..0fe4872f0 100644 --- a/crates/mega-evm/tests/rex5/stipend_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs @@ -360,104 +360,6 @@ fn build_keccak256_leaky_receiver() -> Bytes { // Parent compute-gas attribution: +CALL_STIPEND delta on value-transfer CALL // ============================================================================ -/// REX5 records `CALL_STIPEND` (2,300) of additional parent compute-gas per -/// value-transferring `CALL`. REX4 under-counts by exactly that amount. -#[test] -fn test_call_value_transfer_parent_compute_gas_delta_rex5_vs_rex4() { - let sender_code = build_zero_gas_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "REX5 must record exactly +CALL_STIPEND (2,300) more parent compute-gas \ - than REX4 for a single value-transferring CALL" - ); -} - -/// Same invariant for `CALLCODE`. -#[test] -fn test_callcode_value_transfer_parent_compute_gas_delta_rex5_vs_rex4() { - let sender_code = build_zero_gas_callcode_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "REX5 must record exactly +CALL_STIPEND (2,300) more parent compute-gas \ - than REX4 for a single value-transferring CALLCODE" - ); -} - -/// DELEGATECALL receives no `CALL_STIPEND` from revm, so the fix must not -/// adjust its parent compute-gas attribution. REX4 and REX5 must record -/// identical parent compute-gas for a DELEGATECALL. -#[test] -fn test_delegatecall_parent_compute_gas_parity_across_specs() { - let sender_code = build_delegatecall_contract(RECEIVER, 100_000); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, rex4_compute, - "DELEGATECALL has no CALL_STIPEND; REX4 and REX5 must record identical \ - parent compute-gas" - ); -} - -/// STATICCALL receives no `CALL_STIPEND` from revm (no value transfer -/// semantics). Same parity guard as DELEGATECALL. -#[test] -fn test_staticcall_parent_compute_gas_parity_across_specs() { - let sender_code = build_staticcall_contract(RECEIVER, 100_000); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, rex4_compute, - "STATICCALL has no CALL_STIPEND; REX4 and REX5 must record identical \ - parent compute-gas" - ); -} - // ============================================================================ // Storage allowance coverage per charging site // ============================================================================ @@ -484,131 +386,6 @@ fn test_log1_value_transfer_succeeds_at_zero_gas_rex5() { } } -/// First-time-write SSTORE inside `receive()` succeeds on REX5 when forwarded gas -/// covers the standard EIP-2200 cost. The 20,000 Mega `sstore_set_storage_gas` -/// surcharge drains from the 23,000 allowance. -#[test] -fn test_sstore_in_receive_succeeds_at_minimum_envelope_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 22_500); - let receiver_code = build_sstore_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: first-time SSTORE in receive() must succeed when forwarded gas \ - covers standard EIP-2200 cost; Mega surcharge drains from allowance" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the SSTORE-in-receive fixture: same forwarded amount must -/// succeed via legacy `gas.limit()` inflation. -#[test] -fn test_sstore_in_receive_succeeds_at_minimum_envelope_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 22_500); - let receiver_code = build_sstore_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX4: same fixture must succeed via legacy inflation" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// SELFDESTRUCT to an empty beneficiary inside `receive()` succeeds on REX5 when -/// forwarded gas covers the standard EVM cost plus the residual portion of the -/// Mega new-account surcharge (25,000 − 23,000 = 2,000 at multiplier=2). The -/// allowance covers 23,000 of the surcharge; the residual comes from forwarded gas. -#[test] -fn test_selfdestruct_in_receive_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 50_000); - let receiver_code = build_selfdestruct_receiver(FRESH_TARGET); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: SELFDESTRUCT to empty beneficiary must succeed; allowance \ - drains the Mega surcharge" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the SELFDESTRUCT-in-receive fixture. -#[test] -fn test_selfdestruct_in_receive_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 50_000); - let receiver_code = build_selfdestruct_receiver(FRESH_TARGET); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// Nested value-transfer CALL B → C where C is empty exercises the -/// `wrap_call_with_storage_gas!` drain site. B's allowance covers 23,000 of the -/// 25,000 new-account surcharge; C receives its own fresh allowance because B → C -/// is itself a value-transfer CALL. Forwarded gas covers the residual + standard -/// CALL EVM costs. -#[test] -fn test_nested_call_to_empty_account_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_nested_value_call_receiver(FRESH_TARGET, 50_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: nested value-transfer CALL to fresh empty target must succeed; \ - each frame gets its own allowance" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the nested CALL-to-empty fixture. -#[test] -fn test_nested_call_to_empty_account_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_nested_value_call_receiver(FRESH_TARGET, 50_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - // ============================================================================ // Compute-leak isolation: stipend cannot fund compute-only opcodes // ============================================================================ @@ -674,93 +451,10 @@ fn test_storage_stipend_unused_portion_does_not_inflate_caller_gas_rex5() { ); } -/// CREATE2 inside a value-transferring child's `receive()` exercises the -/// `storage_gas_ext::create` drain site. With generous forwarded gas, both specs -/// succeed: REX5 drains 23,000 of the 32,000 `create_contract_storage_gas` -/// (multiplier=2) from the allowance; REX4 covers it via legacy inflation. -#[test] -fn test_create2_in_receive_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_create2_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: CREATE2 inside stipend-receiving frame must succeed" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for CREATE2-in-receive. -#[test] -fn test_create2_in_receive_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_create2_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - // ============================================================================ // Negative controls // ============================================================================ -/// Stipend (REX5 allowance or REX4 inflated gas) bridges at most its 23,000 -/// portion. A child forwarded gas below the standard EVM opcode cost must fail -/// the inner CALL on both specs. Fixture: SSTORE receiver with 5,000 forwarded -/// gas (well below the 22,100 EIP-2200 cost). -#[test] -fn test_sstore_underforward_fails_on_both_specs() { - // Forward only 5,000 EVM gas — far below the 22,100 standard SSTORE cost. - // Effective gas = 5,000 + CALL_STIPEND = 7,300, still well below the - // standard SSTORE cost — child must OOG on both specs regardless of stipend. - let sender_code = build_value_transfer_with_gas(RECEIVER, 5_000); - let receiver_code = build_sstore_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex5_db = setup_db(&contracts); - let rex5_result = transact(MegaSpecId::REX5, &mut rex5_db, default_tx()).unwrap(); - let mut rex4_db = setup_db(&contracts); - let rex4_result = transact(MegaSpecId::REX4, &mut rex4_db, default_tx()).unwrap(); - - // Both specs return successfully at the OUTER tx level (the parent's CALL - // returns failure but the parent contract itself returns the flag = 0). - // What we assert: the INNER CALL flag is 0 on both specs. - match &rex5_result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX5: under-forwarded SSTORE child must fail" - ); - } - other => panic!("REX5: expected outer Success, got {other:?}"), - } - match &rex4_result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX4: under-forwarded SSTORE child must fail — stipend can't bridge \ - beyond its 23,000 size" - ); - } - other => panic!("REX4: expected outer Success, got {other:?}"), - } -} - // ============================================================================ // Synthetic interceptor frame stack alignment // ============================================================================ @@ -784,19 +478,6 @@ fn test_intercepted_value_call_stack_alignment_rex5() { ); } -/// REX4 parity for the synthetic interceptor stack alignment. -#[test] -fn test_intercepted_value_call_stack_alignment_rex4_parity() { - let sender_code = build_intercepted_value_call(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - assert!( - matches!(result.result, ExecutionResult::Success { .. } | ExecutionResult::Revert { .. }), - "REX4 parity guard" - ); -} - /// The stipend is granted only to internal (depth > 0) value-transferring /// CALL/CALLCODE. A top-level value-transfer transaction must NOT receive /// the stipend on either spec; LOG1 in the receiver should fail under both @@ -825,43 +506,6 @@ fn test_top_level_value_transfer_does_not_get_stipend_rex5() { // TX-level rescue + revert path inside a stipend-receiving child // ============================================================================ -/// Value-transferring child enters with a stipend allowance, accesses TIMESTAMP -/// to trigger volatile-data detention, then burns compute past the detained -/// `tx_compute_gas_limit`. REX5's `rescue_gas` returns `gas.remaining()` directly -/// (the allowance never bled into `gas.limit()`), so the rescue path produces a -/// bounded refund without panic; the halt is `VolatileDataAccessOutOfGas` and -/// `gas_used` reflects the rescued gas (far below the forwarded child-frame gas). -#[test] -fn test_stipend_receiving_child_tx_level_rescue_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 100_000); - let receiver_code = build_timestamp_detention_receiver(20_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX5, &mut db, default_tx(), limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { limit, .. }, - gas_used, - } => { - assert!( - *limit <= 1_000_000, - "detained limit should stay within the tx compute gas limit, got {limit}" - ); - assert!( - *gas_used < 200_000, - "REX5 rescue_gas must refund excess gas — gas_used {gas_used} indicates no \ - refund occurred. Allowance must NOT inflate the rescued amount; it never \ - entered gas.limit() on REX5" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas, got {other:?}"), - } -} - /// Stipend-receiving child drains its allowance via SSTORE then REVERTs. The /// drained allowance is consumed — it does not refund across the revert. Outer /// tx succeeds, inner CALL flag is 0, SSTORE state is rolled back, and the diff --git a/crates/mega-evm/tests/rex5/system_tx_replay.rs b/crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs similarity index 100% rename from crates/mega-evm/tests/rex5/system_tx_replay.rs rename to crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs diff --git a/crates/mega-evm/tests/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs similarity index 91% rename from crates/mega-evm/tests/rex6/beneficiary_detention.rs rename to crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs index e6b4fbc26..4b448da87 100644 --- a/crates/mega-evm/tests/rex6/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs @@ -204,34 +204,6 @@ fn test_rex6_selfdestruct_source_eq_beneficiary_disabled_reverts() { assert_eq!(usage.state_growth, 0, "no on_selfdestruct_new_account: {}", usage.state_growth); } -/// REX5 baseline for the source-side case above. Same code and setup; REX5's outer wrapper -/// checks only the stack target, so a source-side SELFDESTRUCT to a non-beneficiary target -/// succeeds. Freeze-guards the pre-REX6 behavior. -#[test] -fn test_rex5_selfdestruct_source_eq_beneficiary_disabled_does_not_revert() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(EMPTY_NON_BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - assert!( - result.result.is_success(), - "REX5 must NOT revert the SELFDESTRUCT — the source-side check is REX6-only; got: {result:?}", - ); -} - /// REX6: SELFDESTRUCT with the stack target == beneficiary, volatile disabled. /// Same target-side case that REX5 already covers: the REX6 wrapper must still /// revert here. The source-side check is additive, and the target-side check is @@ -313,40 +285,6 @@ fn test_rex6_call_to_eip7702_delegator_to_beneficiary_disabled_reverts() { ); } -/// REX5 baseline: same setup, but REX5's wrapper compares the raw stack -/// operand (DELEGATOR != BENEFICIARY), so no revert. The CALL succeeds and the -/// delegate's STOP runs. -#[test] -fn test_rex5_call_to_eip7702_delegator_to_beneficiary_disabled_does_not_revert() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(DELEGATOR_TO_BENEFICIARY) - .push_number(100_000_u64) - .append(CALL) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code) - .account_code(BENEFICIARY, beneficiary_code); - set_eip7702_delegation(&mut db, DELEGATOR_TO_BENEFICIARY, BENEFICIARY); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - assert!( - result.result.is_success(), - "REX5 wrapper must NOT revert — compares raw stack operand only: {result:?}", - ); -} - /// REX6: A CALL to an EIP-7702 delegator pointing at the beneficiary, with /// volatile access enabled, must engage beneficiary detention via /// `MegaContext::load_account_delegated`'s resolved-delegate mark. @@ -481,34 +419,6 @@ fn test_rex6_selfdestruct_to_empty_target_still_records_state_growth() { // SELFDESTRUCT target-side freeze, enabled-path detention, self-target, DB-error // ============================================================================ -/// REX5 must still revert SELFDESTRUCT when the stack target is the beneficiary under disabled -/// volatile access: the target-side guard is spec-independent, only the source-side guard is -/// REX6-only. Mirrors `test_rex6_selfdestruct_target_eq_beneficiary_disabled_still_reverts`. -#[test] -fn test_rex5_selfdestruct_target_eq_beneficiary_disabled_still_reverts() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - let output = result.result.output().expect("REX5 must still revert on target==beneficiary"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "REX5 target-side revert must be preserved by the hand-written wrapper: {output:?}", - ); -} - /// With volatile access enabled, a SELFDESTRUCT whose source is the beneficiary engages detention /// purely via the entry mark: reaching beneficiary-as-executor requires entering its frame (here /// the tx recipient is the beneficiary, so `on_new_tx` eagerly marks the beneficiary balance), so diff --git a/crates/mega-evm/tests/rex6/common.rs b/crates/mega-evm/tests/_pending/rex6/common.rs similarity index 100% rename from crates/mega-evm/tests/rex6/common.rs rename to crates/mega-evm/tests/_pending/rex6/common.rs diff --git a/crates/mega-evm/tests/rex6/create2_metering_order.rs b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs similarity index 79% rename from crates/mega-evm/tests/rex6/create2_metering_order.rs rename to crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs index 4f815d543..f411f4d41 100644 --- a/crates/mega-evm/tests/rex6/create2_metering_order.rs +++ b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs @@ -171,29 +171,6 @@ fn db_with(code: Bytes) -> MemoryDatabase { .account_code(CONTRACT, code) } -#[test] -fn test_create2_happy_path_compute_gas_identical_rex5_rex6() { - let r5 = transact_default(MegaSpecId::REX5, db_with(build_create2_contract())); - let r6 = transact_default(MegaSpecId::REX6, db_with(build_create2_contract())); - - assert!(r5.is_success(), "REX5 CREATE2 happy path must succeed; got {:?}", r5.result); - assert!(r6.is_success(), "REX6 CREATE2 happy path must succeed; got {:?}", r6.result); - - // The REX6 single recording (resize + inner, taken once after the body) equals the REX5 eager - // resize record + inner record exactly — no double count, no miss count. - assert_eq!( - r5.compute_gas, r6.compute_gas, - "CREATE2 happy-path compute_gas must be identical; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - // The EVM-gas operations are byte-identical across the two orders. - assert_eq!( - r5.gas_used, r6.gas_used, - "CREATE2 happy-path gas_used must be identical; REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - #[test] fn test_create2_missing_salt_consistent_rex5_rex6() { // Three CREATE2 operands, salt OMITTED: the wrapper's `stack.inspect::<3>()` fails, halting @@ -225,93 +202,6 @@ fn test_create2_missing_salt_consistent_rex5_rex6() { ); } -#[test] -fn test_create2_compute_limit_divergence_rex5_rex6() { - // Measure the compute-gas usage accumulated before the CREATE2 opcode (TX intrinsic + the four - // operand pushes), then place the limit just above it — inside the memory-expansion window. - let usage_before_create2 = - transact_default(MegaSpecId::REX6, db_with(build_pushes_only_contract())).compute_gas; - let compute_limit = usage_before_create2 + 100; - - let limits = - |spec| EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - - let r5 = - transact(MegaSpecId::REX5, db_with(build_create2_contract()), limits(MegaSpecId::REX5)); - let r6 = - transact(MegaSpecId::REX6, db_with(build_create2_contract()), limits(MegaSpecId::REX6)); - - // Both transactions exceed the compute-gas limit and fail. - assert!(!r5.is_success(), "REX5 must fail under the tight compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must fail under the tight compute limit; got {:?}", r6.result); - - // REX5 halts at the eager resize record, before the inner CREATE2 executes: its reading covers - // only the memory-expansion gas on top of the pre-CREATE2 usage. - assert!( - r5.compute_gas < usage_before_create2 + 15_000, - "REX5 should halt at the eager resize record (memory-expansion only); \ - usage_before={usage_before_create2}, got {}", - r5.compute_gas - ); - // REX6 defers recording until after the inner CREATE2 has executed, so it additionally records - // the inner opcode's compute gas (CREATE2 base cost 32,000 + initcode word cost) before the - // limit check fires. - assert!( - r6.compute_gas > usage_before_create2 + 30_000, - "REX6 should record the inner CREATE2 compute gas before the limit fires; \ - usage_before={usage_before_create2}, got {}", - r6.compute_gas - ); - assert!( - r6.compute_gas > r5.compute_gas, - "REX6 records strictly more compute gas than REX5 under the tight limit; \ - REX5={} REX6={}", - r5.compute_gas, - r6.compute_gas - ); -} - -#[test] -fn test_create2_late_record_skipped_on_compute_limit_halt_pre_rex5() { - // Pre-REX5 path through `storage_gas_ext::create` records the CREATE2 memory-expansion gas in - // a trailing `if resize_gas > 0 { compute_gas!(...) }` block AFTER the post-body compute-gas - // recording. If the compute-gas limit trips at the post-body recording, the late-record block - // MUST be skipped — otherwise it adds `resize_gas` to the tracker after the OOG halt was - // already set, diverging from the pre-PR behavior on a frozen spec. - // - // Pin to REX4 (last pre-REX5 spec) so `compute_created_address` leaves `resize_gas > 0` and - // the late-record block has real work to skip. - let spec = MegaSpecId::REX4; - - // Happy path: with a generous limit, the late-record runs successfully, so the final - // tracker equals `previous + body_gas + resize_gas`. - let happy = transact_default(spec, db_with(build_create2_contract())).compute_gas; - - // Measure the pre-CREATE2 compute-gas usage so we can position the limit precisely. - let usage_before_create2 = - transact_default(spec, db_with(build_pushes_only_contract())).compute_gas; - - // Position the limit just past the pre-CREATE2 usage so the limit trips inside - // `record_storage_compute_gas!` immediately after the inner CREATE2 body completes. - let compute_limit = usage_before_create2 + 100; - let limits = EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - let tight = transact(spec, db_with(build_create2_contract()), limits); - - assert!(!tight.is_success(), "tight compute limit must halt; got {:?}", tight.result); - - // With the fix, `record_storage_compute_gas!` halts and returns, so the late-record block - // does not run — `tight.compute_gas` is strictly less than `happy` by approximately the - // memory-expansion gas of the 32 KiB initcode. Without the fix, the late-record block adds - // `resize_gas` to the tracker after the halt, making `tight.compute_gas == happy`. - assert!( - tight.compute_gas < happy, - "pre-REX5 CREATE2 late-record block must be skipped on post-body halt; \ - happy={} tight={}", - happy, - tight.compute_gas - ); -} - /// An oversized CREATE2 initcode must halt with `CreateInitCodeSizeLimit` under REX6 /// BEFORE any memory-expansion/copy/keccak256 prework runs, not after. /// @@ -348,37 +238,6 @@ fn test_create2_oversized_initcode_halts_before_prework_rex6() { ); } -/// Pre-REX6 replay parity: the early size check is gated to REX6 only. REX5 (sealed) must keep -/// performing the resize/copy/keccak256 prework before any size check runs — no retroactive fix. -/// For the same 10 MiB initcode as the REX6 test above, REX5's `resize_memory!` itself exhausts the -/// gas limit and halts with `MemoryOOG`, never reaching the canonical EIP-3860 check at all — -/// contrasted with REX6's immediate `CreateInitCodeSizeLimit` above. This is the direct, -/// observable proof that pre-REX6 still performs the prework this finding is about. -#[test] -fn test_create2_oversized_initcode_pre_rex6_still_does_prework() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, far past the 548,864-byte cap - - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(HUGE_INITCODE_LEN) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code)); - - assert!( - matches!(&r5.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("OutOfGas(Memory)")), - "REX5 (sealed) must still attempt resize_memory! for an oversized initcode and halt \ - with an OutOfGas(Memory) halt (MemoryOOG), never reaching the canonical EIP-3860 \ - check; got {:?}", - r5.result, - ); -} - /// Halt-reason parity for a "moderately" oversized initcode (bigger than the 548,864-byte cap, /// but small enough that `resize_memory!`'s own gas cost stays well within the 100M tx gas /// limit). Both specs reach `CreateInitCodeSizeLimit` — REX5 via the slower prework-then-inner- diff --git a/crates/mega-evm/tests/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs similarity index 69% rename from crates/mega-evm/tests/rex6/create_frame_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs index 5ee963336..2d7958ecd 100644 --- a/crates/mega-evm/tests/rex6/create_frame_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs @@ -84,32 +84,6 @@ fn first_create_address() -> Address { CALLER.create(0) } -/// REX6: a CREATE deploying to an address that ALREADY exists (pre-funded balance-only) must -/// NOT record a state-growth account-creation event; a fresh-address CREATE still records +1. -#[test] -fn test_rex6_create_to_prefunded_address_records_no_state_growth() { - // --- fresh address: no pre-existing account --- - let db_fresh = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let (res_fresh, evm_fresh) = run(MegaSpecId::REX6, db_fresh, stop_init_code()); - assert!(res_fresh.result.is_success(), "fresh CREATE must succeed: {:?}", res_fresh.result); - let growth_fresh = evm_fresh.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - // --- prefunded address: target already has a balance-only account --- - let db_prefunded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_balance(first_create_address(), U256::from(1u64)); - let (res_pre, evm_pre) = run(MegaSpecId::REX6, db_prefunded, stop_init_code()); - assert!(res_pre.result.is_success(), "prefunded CREATE must succeed: {:?}", res_pre.result); - let growth_pre = evm_pre.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - assert_eq!( - growth_fresh.saturating_sub(growth_pre), - 1, - "REX6 CREATE must record +1 state_growth only for a net-new address \ - (fresh={growth_fresh}, prefunded={growth_pre})", - ); -} - const OUTER_CREATOR: Address = Address::new([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xDE, 0x00, 0xFF, @@ -217,76 +191,6 @@ fn run_create_with_limits( alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError") } -/// A CREATE whose Mega code-deposit-storage charge runs out of gas while the frame's data-size -/// budget is simultaneously exceeded is absorbed into the frame-local `Revert` and its unspent -/// child gas is returned to the caller — identically on REX6 and pre-REX6. The frame-local absorb -/// treats an already-failed CREATE the same as a successful-but-over-limit one, so REX5 and REX6 -/// produce the same result class and the same `gas_used` (no spec divergence on this path). -/// -/// Setup: the constructor RETURNs an 8_000-byte runtime blob. The Mega code-deposit-storage charge -/// (`CODEDEPOSIT_STORAGE_GAS` per byte) far exceeds the 400_000-gas frame budget, so the frame -/// returns `OutOfGas`. At the same time the runtime blob overshoots the tiny `tx_data_size_limit` -/// (2000 bytes), so the frame-local data-size limit is also exceeded — the exact edge where the -/// absorb fires. -#[test] -fn test_rex6_create_oog_over_limit_matches_rex5_frozen() { - // Runtime blob large enough that the code-deposit-storage charge cannot fit in `GAS`, and - // large enough to overshoot DATA_SIZE_LIMIT so the frame-local data-size limit also trips. - const CODE_LEN: u32 = 8_000; - const DATA_SIZE_LIMIT: u64 = 2_000; - // Frame gas budget far below the code-deposit-storage charge (CODE_LEN * 10_000), so the - // charge runs OutOfGas; large enough for the constructor + intrinsic to run first. - const GAS: u64 = 400_000; - - let r5 = run_create_with_limits(MegaSpecId::REX5, DATA_SIZE_LIMIT, CODE_LEN, GAS); - let r6 = run_create_with_limits(MegaSpecId::REX6, DATA_SIZE_LIMIT, CODE_LEN, GAS); - - // Both specs absorb the failed CREATE into the frame-local Revert. - assert!( - matches!(r5.result, ExecutionResult::Revert { .. }), - "REX5 absorbs the OutOfGas CREATE into a frame-local Revert: {:?}", - r5.result, - ); - assert!( - matches!(r6.result, ExecutionResult::Revert { .. }), - "REX6 absorbs the OutOfGas CREATE into a frame-local Revert identically to REX5: {:?}", - r6.result, - ); - - // Same result class → same returned gas; no REX6 burn-vs-refund divergence on this path. - assert_eq!( - r6.result.gas_used(), - r5.result.gas_used(), - "REX6 must return the absorbed CREATE's gas identically to REX5 \ - (rex5_gas_used={}, rex6_gas_used={})", - r5.result.gas_used(), - r6.result.gas_used(), - ); -} - -/// Pre-REX6 freeze: under REX5 a CREATE records state growth unconditionally, so deploying to a -/// pre-funded (already-existing) address records the same state growth as deploying to a fresh -/// one — the net-new distinction is REX6-only. -#[test] -fn test_rex5_freeze_create_state_growth_unconditional() { - let db_fresh = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let (rf, ef) = run(MegaSpecId::REX5, db_fresh, stop_init_code()); - assert!(rf.result.is_success(), "REX5 fresh CREATE must succeed"); - let fresh = ef.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - let db_pre = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_balance(first_create_address(), U256::from(1u64)); - let (rp, ep) = run(MegaSpecId::REX5, db_pre, stop_init_code()); - assert!(rp.result.is_success(), "REX5 prefunded CREATE must succeed"); - let pre = ep.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - assert_eq!( - fresh, pre, - "REX5 must record CREATE state_growth unconditionally (fresh={fresh}, prefunded={pre})", - ); -} - /// REX6: a DB failure while inspecting the CREATE target for the net-new state-growth check must /// surface as an error, not be silently swallowed. A normal `MemoryDatabase` is infallible, so the /// `inspect_account(created_address, ..)?` error branch is only exercised by injecting a DB read diff --git a/crates/mega-evm/tests/rex6/eip7702_authority_accounting.rs b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs similarity index 100% rename from crates/mega-evm/tests/rex6/eip7702_authority_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs diff --git a/crates/mega-evm/tests/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs similarity index 100% rename from crates/mega-evm/tests/rex6/error_paths.rs rename to crates/mega-evm/tests/_pending/rex6/error_paths.rs diff --git a/crates/mega-evm/tests/rex6/fee_reward_accounting.rs b/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs similarity index 90% rename from crates/mega-evm/tests/rex6/fee_reward_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs index fcf239f2f..e6442557c 100644 --- a/crates/mega-evm/tests/rex6/fee_reward_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs @@ -405,63 +405,6 @@ fn test_rex6_beneficiary_tip_materialization_records_accounting() { // REX5 freeze guard // ============================================================================ -/// REX5 freeze guard: under `MegaSpecId::REX5` the fee-reward path must record -/// **no** fee-recipient accounting. An empty vs pre-funded `BASE_FEE_RECIPIENT` -/// must produce byte-identical `state_growth`, `data_size`, and `kv_updates`. -#[test] -fn test_rex5_freeze_no_fee_recipient_accounting() { - // --- Run A: BASE_FEE_RECIPIENT absent (would materialise under REX6) ---------- - let db_empty = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - - let (res_empty, evm_empty) = - transact_with_spec(MegaSpecId::REX5, db_empty, BASEFEE, make_call_tx()); - assert!( - res_empty.expect("REX5 empty run must not produce a validation error").result.is_success(), - "REX5 empty run: tx must succeed", - ); - let empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - // --- Run B: BASE_FEE_RECIPIENT pre-funded ------------------------------------ - let db_funded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)); - - let (res_funded, evm_funded) = - transact_with_spec(MegaSpecId::REX5, db_funded, BASEFEE, make_call_tx()); - assert!( - res_funded - .expect("REX5 funded run must not produce a validation error") - .result - .is_success(), - "REX5 funded run: tx must succeed", - ); - let funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - // Under REX5 the fee-reward path is frozen: no accounting is recorded for any - // fee-recipient balance change, so all usage fields must be identical. - assert_eq!( - empty.state_growth, funded.state_growth, - "REX5: state_growth must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.state_growth, funded.state_growth, - ); - assert_eq!( - empty.data_size, funded.data_size, - "REX5: data_size must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.data_size, funded.data_size, - ); - assert_eq!( - empty.kv_updates, funded.kv_updates, - "REX5: kv_updates must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.kv_updates, funded.kv_updates, - ); -} - // ============================================================================ // Recipient dedup (beneficiary coincides with a fee vault) // ============================================================================ diff --git a/crates/mega-evm/tests/rex6/frame_local_accounting.rs b/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs similarity index 67% rename from crates/mega-evm/tests/rex6/frame_local_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs index 1da0b99f8..1a9e95c14 100644 --- a/crates/mega-evm/tests/rex6/frame_local_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs @@ -61,20 +61,6 @@ fn test_rex6_log0_empty_charges_base_overhead_vs_rex5() { ); } -#[test] -fn test_rex5_log0_empty_is_free_frozen() { - // Freeze guard: under REX5, LOG0(0,0) contributes ZERO data_size beyond the no-log baseline - // (preserved byte-for-byte pre-REX6). - let with_log = transact_default(MegaSpecId::REX5, base_db(log0_empty_code())); - let no_log = - transact_default(MegaSpecId::REX5, base_db(BytecodeBuilder::default().stop().build())); - assert_eq!( - with_log.data_size, no_log.data_size, - "REX5 LOG0(0,0) must remain free in data_size (frozen); with_log={} no_log={}", - with_log.data_size, no_log.data_size, - ); -} - #[test] fn test_rex6_log1_with_data_base_plus_topics_plus_data() { // LOG1 with 32 bytes of data: REX6 = REX5 + LOG_BASE_SIZE (one log → one base overhead); the @@ -139,27 +125,6 @@ fn tight_compute_limits() -> EvmTxRuntimeLimits { limits } -#[test] -fn test_rex6_compute_abort_at_call_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, compute_abort_db(), tight_compute_limits()); - let r6 = transact(MegaSpecId::REX6, compute_abort_db(), tight_compute_limits()); - // Both halt (frame-local compute-limit Revert) at the CALL. - assert!(!r5.is_success(), "REX5 must halt on the compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt on the compute limit; got {:?}", r6.result); - // REX5 swallows the forwarded gas (~98% of the 100M tx limit) → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before halting → gas_used stays small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas (not swallow it); gas_used={}", - r6.gas_used, - ); -} - /// DB where [`CONTRACT`] performs a `CREATE` with a one-byte init code, forwarding gas to the init /// frame. The `CREATE` is the first compute-significant opcode, so its compute overhead overruns /// the tight budget while the child `NewFrame(Create)` is pending and its forwarded gas deducted. @@ -179,27 +144,6 @@ fn compute_abort_create_db() -> MemoryDatabase { .account_balance(CONTRACT, U256::from(ONE_ETH)) } -#[test] -fn test_rex6_compute_abort_at_create_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, compute_abort_create_db(), tight_compute_limits()); - let r6 = transact(MegaSpecId::REX6, compute_abort_create_db(), tight_compute_limits()); - // Both halt (frame-local compute-limit Revert) at the CREATE. - assert!(!r5.is_success(), "REX5 must halt on the compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt on the compute limit; got {:?}", r6.result); - // REX5 swallows the gas forwarded to the discarded init frame → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before halting → gas_used stays small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas (not swallow it); gas_used={}", - r6.gas_used, - ); -} - /// DB where [`CONTRACT`] accesses volatile block env (`TIMESTAMP`) to arm a relative compute-gas /// detention cap, then performs a gas-forwarding CALL to a code-bearing target. With a tight /// detention cap and a large per-frame budget, the CALL's own compute overshoots the *tx-level* @@ -235,39 +179,6 @@ fn tx_level_detention_limits() -> EvmTxRuntimeLimits { limits } -/// The forwarded gas is returned to the parent on a *tx-level* (detained) compute-limit halt at a -/// CALL, not only on the frame-local one: a child `NewFrame` whose gas revm already deducted is -/// discarded when the detained `OutOfGas` fires, so without the erase that gas is swallowed into -/// `gas_used`. REX6 returns it; pre-REX6 leaves it swallowed. -#[test] -fn test_rex6_tx_level_compute_abort_at_call_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, tx_level_detained_abort_db(), tx_level_detention_limits()); - let r6 = transact(MegaSpecId::REX6, tx_level_detained_abort_db(), tx_level_detention_limits()); - // Both halt at the tx-level detained limit (a Halt, distinct from the frame-local Revert). - assert!( - matches!(r5.result, ExecutionResult::Halt { .. }), - "REX5 must hit the tx-level detained OutOfGas (Halt), not a frame-local Revert; got {:?}", - r5.result, - ); - assert!( - matches!(r6.result, ExecutionResult::Halt { .. }), - "REX6 must hit the tx-level detained OutOfGas (Halt), not a frame-local Revert; got {:?}", - r6.result, - ); - // REX5 swallows the gas forwarded to the discarded child → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before the detained halt → gas_used small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas on a tx-level halt too; gas_used={}", - r6.gas_used, - ); -} - #[test] fn test_rex6_two_logs_charge_two_base_overheads() { // Two LOG0(0,0) → two per-log base overheads under REX6. diff --git a/crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs b/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs similarity index 85% rename from crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs rename to crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs index 852e4c8a7..2191f405c 100644 --- a/crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs +++ b/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs @@ -269,74 +269,6 @@ fn test_rex6_create_then_selfdestruct_surfaces_as_empty_code() { // Keyless dispatch-overhead OOG rescues parent gas // ============================================================================ -/// REX6: when the `KEYLESS_DEPLOY_OVERHEAD_GAS` charge exceeds the -/// `AdditionalLimit`'s tx-level compute-gas cap, the outer Gas counter's -/// unused remainder must be rescued. Pre-REX6 leaves the unused remainder -/// fully spent so the sender pays the entire outer envelope for a halt that -/// barely touched anything. -/// -/// We compare the outer tx's reported `gas_used` between REX5 and REX6 and -/// pin both an inequality (REX6 < REX5) and an absolute lower bound on the -/// rescue delta. The bound is set well below the realistic rescue amount -/// (≈ outer envelope − intrinsic − overhead) but high enough that a -/// partial-rescue regression (e.g., rescuing only the overhead, or missing -/// the post-overhead remainder) would fail it. -#[test] -fn test_rex6_keyless_overhead_oog_rescues_parent_gas() { - // Minimal init code — never executes because the 100K overhead halts first. - let init_code = - BytecodeBuilder::default().push_number(0_u8).push_number(0_u8).append(RETURN).build(); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - // Squeeze tx compute gas below 100K so the keyless overhead record overflows. - let tx_compute_gas_limit: u64 = 50_000; - - let build_db = || { - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - db - }; - - let mut db_rex5 = build_db(); - let result_rex5 = run_keyless_outer( - MegaSpecId::REX5, - &mut db_rex5, - keyless_tx_bytes.clone(), - LARGE_GAS_LIMIT_OVERRIDE, - Some(tx_compute_gas_limit), - None, - ); - - let mut db_rex6 = build_db(); - let result_rex6 = run_keyless_outer( - MegaSpecId::REX6, - &mut db_rex6, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - Some(tx_compute_gas_limit), - None, - ); - - let gas_used_rex5 = result_rex5.gas_used(); - let gas_used_rex6 = result_rex6.gas_used(); - assert!( - gas_used_rex6 < gas_used_rex5, - "REX6 must rescue parent gas on tx-level compute exceed: REX6={gas_used_rex6} \ - < REX5={gas_used_rex5}", - ); - - // Pin the rescue delta against a conservative lower bound. With - // `OUTER_GAS_LIMIT = 30_000_000`, the rescued amount should be roughly the - // outer envelope minus the intrinsic + 100K overhead. A partial-rescue - // regression (only the overhead, or only the storage-stipend slice) would - // produce a delta well under 25M and fail this assertion. - let rescue_delta = gas_used_rex5 - gas_used_rex6; - assert!( - rescue_delta >= 25_000_000, - "REX6 rescue delta too small: {rescue_delta} (REX5={gas_used_rex5}, REX6={gas_used_rex6})", - ); -} - // ============================================================================ // Bytecode invariant pins (EIP-3541 / EIP-170 enforcement reaches the // sandbox dispatch path) diff --git a/crates/mega-evm/tests/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs similarity index 96% rename from crates/mega-evm/tests/rex6/main.rs rename to crates/mega-evm/tests/_pending/rex6/main.rs index 8f33582f0..a6e652c07 100644 --- a/crates/mega-evm/tests/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -13,7 +13,6 @@ mod error_paths; mod fee_reward_accounting; mod frame_local_accounting; mod keyless_sandbox_hardening; -mod metering_order_parity; mod oracle_hint_volatile_access; mod self_transfer_account_dedup; mod sequencer_registry_rotation; diff --git a/crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs similarity index 93% rename from crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs rename to crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs index d20a8c65a..26f8dd531 100644 --- a/crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs +++ b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs @@ -223,19 +223,3 @@ fn test_rex6_disabled_send_hint_is_not_metered_against_data_size() { assert!(hints.is_empty(), "a disabled sendHint call must not forward"); } -/// REX5 replay parity: the guard is gated to REX6+. REX5 is sealed and must keep forwarding -/// `sendHint` regardless of the volatile-access-disabled state — no retroactive behavior change. -#[test] -fn test_rex5_disabled_frame_still_forwards_send_hint() { - let code = - call_send_hint(call_disable_volatile_data_access(BytecodeBuilder::default()), 64, 100_000) - .stop() - .build(); - let (result, hints) = run_with_oracle(MegaSpecId::REX5, code, None); - assert!(result.is_success(), "outer tx must succeed: {result:?}"); - assert_eq!( - hints.len(), - 1, - "REX5 (sealed) must keep forwarding sendHint regardless of volatile-access-disabled state", - ); -} diff --git a/crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs similarity index 86% rename from crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs rename to crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs index e156f860f..ad50882a0 100644 --- a/crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs +++ b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs @@ -126,20 +126,6 @@ fn test_rex6_top_level_self_transfer_no_double_count() { ); } -/// REX5 baseline: the same top-level `A -> A` transfer still double-counts (frozen). -#[test] -fn test_rex5_top_level_self_transfer_still_double_counts() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX5, A); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX5 A->A value transfer keeps the frozen duplicate account-info write (data_size)", - ); - assert_eq!( - kv_delta, 1, - "REX5 A->A value transfer keeps the frozen duplicate account-info write (kv_updates)", - ); -} - // ============================================================================ // Non-self transfer: A -> B (unchanged on every spec) // ============================================================================ @@ -154,16 +140,6 @@ fn test_rex6_non_self_transfer_counts_target() { assert_eq!(kv_delta, 1, "REX6 A->B value transfer must record the target write (kv_updates)"); } -#[test] -fn test_rex5_non_self_transfer_counts_target() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX5, B); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX5 A->B value transfer must record the target write (data_size)", - ); - assert_eq!(kv_delta, 1, "REX5 A->B value transfer must record the target write (kv_updates)"); -} - // ============================================================================ // Nested self-call with value: A's code CALLs A with value // ============================================================================ @@ -255,24 +231,6 @@ fn test_rex6_nested_self_call_with_value_counts_once() { ); } -/// REX5 baseline: the nested `A -> A` value call double-counts A — the delta over an inner -/// `value=0` self-call is two account-info writes (caller + target), frozen. -#[test] -fn test_rex5_nested_self_call_with_value_double_counts() { - let (data_value, kv_value) = nested_usage(MegaSpecId::REX5, 1); - let (data_zero, kv_zero) = nested_usage(MegaSpecId::REX5, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 2 * ACCOUNT_INFO_WRITE_SIZE, - "REX5 nested A->A value call double-counts (caller + target) in data_size", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 2, - "REX5 nested A->A value call double-counts (caller + target) in kv_updates", - ); -} - // ============================================================================ // Nested self-call where the parent frame already did a value transfer // (`parent_needs_update == false` arm of the dedup predicate) @@ -350,24 +308,6 @@ fn test_rex6_nested_pnu_false_self_transfer_counts_once() { ); } -/// REX5 baseline: the self-targeted second call still records `SELF_CALLER` a second time (frozen), -/// so the delta is three account-info writes. -#[test] -fn test_rex5_nested_pnu_false_self_transfer_double_counts() { - let (data_value, kv_value) = nested_two_call_usage(MegaSpecId::REX5, 1); - let (data_zero, kv_zero) = nested_two_call_usage(MegaSpecId::REX5, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 3 * ACCOUNT_INFO_WRITE_SIZE, - "REX5 keeps the frozen duplicate SELF_CALLER target write (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 3, - "REX5 keeps the frozen duplicate SELF_CALLER target write (kv_updates)", - ); -} - // ============================================================================ // Zero-value call records no account-info write (unchanged) // ============================================================================ diff --git a/crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs similarity index 79% rename from crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs rename to crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs index e8934b409..97664c952 100644 --- a/crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs +++ b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs @@ -261,110 +261,6 @@ fn test_rex6_bootstrap_deploys_v2_and_resolves_system_address() { ); } -/// The grandfathering boundary case: a rotation scheduled under v1.0.0 whose activation block -/// is exactly the Rex6 activation block. In that single block the executor must both upgrade -/// the bytecode in place (preserving all live storage) and apply the due rotation. -#[test] -fn test_rex6_upgrade_block_applies_v1_scheduled_rotation() { - let (new_sequencer, _) = new_sequencer_keypair(); - let activation_block = 1000u64; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - seed_v1_registry_with_pending_rotation(&mut db, new_sequencer, activation_block); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = executor_factory().create_executor( - &mut state, - block_ctx(), - evm_env_at_block(activation_block), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - drop(executor); - - // The upgrade landed... - assert_eq!( - registry_code_hash(&mut state), - SEQUENCER_REGISTRY_CODE_HASH_REX6, - "registry must run v2.0.0 after the Rex6 activation block" - ); - assert_eq!( - read_registry_slot(&mut state, MIN_ROTATION_DELAY), - U256::from(MIN_ROTATION_DELAY_BLOCKS), - ); - // ...the grandfathered rotation flipped in the same block... - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the v1-scheduled rotation must activate normally across the upgrade" - ); - assert_eq!(read_registry_slot(&mut state, PENDING_SEQUENCER), U256::ZERO); - assert_eq!(read_registry_slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), U256::ZERO); - // ...and untouched live storage survived the upgrade. - assert_eq!( - read_registry_slot(&mut state, ADMIN), - U256::from_be_bytes(BOOTSTRAP_ADMIN.into_word().0), - "live admin slot must survive the in-place upgrade" - ); - assert_eq!( - read_registry_slot(&mut state, CURRENT_SYSTEM_ADDRESS), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - ); -} - -/// The common mainnet upgrade shape: a rotation scheduled under v1.0.0 whose activation block -/// lands AFTER the Rex6 activation block. The upgrade block must swap the bytecode without -/// flipping the not-yet-due rotation, and the later activation block must flip it under the -/// v2.0.0 bytecode. -#[test] -fn test_rex6_v1_scheduled_rotation_activates_after_upgrade_block() { - let (new_sequencer, _) = new_sequencer_keypair(); - let upgrade_block = 1000u64; - let activation_block = upgrade_block + 50; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - seed_v1_registry_with_pending_rotation(&mut db, new_sequencer, activation_block); - - let mut state = State::builder().with_database(&mut db).build(); - let factory = executor_factory(); - - // Upgrade block: bytecode swaps, but the rotation is not yet due and must stay pending. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(upgrade_block)); - executor.apply_pre_execution_changes().expect("upgrade block pre-execution should succeed"); - drop(executor); - - assert_eq!(registry_code_hash(&mut state), SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(BOOTSTRAP_SEQUENCER.into_word().0), - "a not-yet-due rotation must not flip on the upgrade block" - ); - assert_eq!( - read_registry_slot(&mut state, PENDING_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the pending rotation must survive the upgrade untouched" - ); - assert_eq!( - read_registry_slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), - U256::from(activation_block), - ); - - // Activation block: the rotation flips under the v2.0.0 bytecode. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(activation_block)); - executor.apply_pre_execution_changes().expect("activation block pre-execution should succeed"); - drop(executor); - - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the v1-scheduled rotation must flip at its activation block under v2.0.0" - ); - assert_eq!(read_registry_slot(&mut state, PENDING_SEQUENCER), U256::ZERO); -} - /// Full v2.0.0 round trip through normal transactions: the admin schedules a rotation with /// the new key's EIP-712 possession proof in one block, and the rotation activates in a /// later block's pre-execution phase. diff --git a/crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs similarity index 89% rename from crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs rename to crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs index 01c7dbd1a..6362475fd 100644 --- a/crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs +++ b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs @@ -222,48 +222,6 @@ fn test_rex6_pre_block_calls_accepted_under_heavy_salt() { assert!(saw_beacon_root, "EIP-4788 pre-block call must succeed and commit under REX6"); } -/// Parity counterpart to the test above: the identical heavy-SALT setup, but with -/// `cfg.spec = REX5` and a REX5-only chain spec, must reject the block. This pins the parity -/// claim — exemption is only in effect under REX6 — inside this file rather than relying on the -/// reader to cross-reference the REX5 test suite. -#[test] -fn test_rex5_pre_block_calls_rejected_under_heavy_salt() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let block_ctx = MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx, - evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("REX5 must reject the heavy-SALT EIP-2935 pre-block call"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "Expected BlockHashContractCall, got: {validation_err:?}" - ); -} - // ============================================================================ // 2. Sequencer mega system tx (oracle write) succeeds under heavy SALT // ============================================================================ diff --git a/crates/mega-evm/tests/block_executor/partial_ladder.rs b/crates/mega-evm/tests/block_executor/partial_ladder.rs deleted file mode 100644 index 0a49dd341..000000000 --- a/crates/mega-evm/tests/block_executor/partial_ladder.rs +++ /dev/null @@ -1,404 +0,0 @@ -//! End-to-end tests for pre-block setup on partial and rollback hardfork ladders. -//! -//! Pre-block setup (system-contract predeploys, the EIP-2935/EIP-4788 fail-closed checks, the -//! `SequencerRegistry` bootstrap) is gated on the resolved spec position-compared via -//! `reaches`, not on per-fork registration and not on the behavior projection. These tests pin -//! both directions of that choice: -//! -//! - A *partial* ladder — a config scheduling a later fork without its predecessors — must still -//! run every lower fork's setup, rather than silently skipping it. -//! - A *rollback* window — mainnet's `MiniRex1`, which maps back to `EQUIVALENCE` — must keep -//! running the setup that earlier forks already activated, rather than retracting it. - -use std::{ - convert::Infallible, - sync::{Arc, Mutex}, -}; - -use alloy_evm::{ - block::{BlockExecutor, BlockValidationError, OnStateHook, StateChangeSource}, - EvmEnv, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, bytes, Address, Bytes, B256, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, - MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaSpecId, ScheduleError, - SequencerRegistryConfig, SequencerRegistryRex6Config, TestExternalEnvs, ACCESS_CONTROL_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, KEYLESS_DEPLOY_ADDRESS, LIMIT_CONTROL_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX5, - SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH_REX6, -}; -use mega_system_contracts::sequencer_registry::storage_slots::MIN_ROTATION_DELAY; -use revm::{ - context::BlockEnv, - database::{Database as _, State}, - state::{AccountInfo, Bytecode, EvmState}, -}; - -const BLOCK_NUMBER: u64 = 1000; -const BLOCK_GAS_LIMIT: u64 = 30_000_000; -const MIN_ROTATION_DELAY_BLOCKS: u64 = 100; - -const BOOTSTRAP_SEQUENCER: Address = address!("0x4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("0x5000000000000000000000000000000000000005"); - -/// Runtime bytecode that unconditionally reverts (`PUSH0 PUSH0 REVERT`). Installed at the -/// EIP-2935 history-storage address to force a failing pre-block system call. -/// -/// A heavy SALT bucket — the mechanism `tests/rex5/pre_block_system_calls.rs` uses — cannot force -/// the failure here: the pre-block call's caller is `eip4788::SYSTEM_ADDRESS`, which counts as -/// system-originated, so from Rex6 the transaction is exempt from resource metering and its -/// storage writes are charged un-scaled. Bucket capacity no longer influences the outcome. -const ALWAYS_REVERT_CODE: Bytes = bytes!("0x5f5ffd"); - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -/// A partial ladder: Rex6 activates while Rex5 is registered but never activates, and no earlier -/// fork is registered at all. `Rex5` must be present as an entry to carry -/// [`SequencerRegistryConfig`] — parameter lookup is activation-independent, but `with_params` -/// requires the entry to exist. -fn rex6_only_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with_params(sequencer_registry_config()) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }) -} - -fn create_evm_env(spec: MegaSpecId, timestamp: u64) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let block_env = BlockEnv { - number: U256::from(BLOCK_NUMBER), - timestamp: U256::from(timestamp), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -/// Non-zero parent hash and beacon root on a non-genesis block, so both EIP helpers actually -/// issue their system call rather than taking the genesis-skip early return. -fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ) -} - -fn install_code(db: &mut MemoryDatabase, address: Address, code: Bytes) { - let bytecode = Bytecode::new_raw(code); - db.insert_account_info( - address, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -fn install_eip_contracts(db: &mut MemoryDatabase) { - install_code( - db, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_CODE.clone(), - ); - install_code( - db, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_CODE.clone(), - ); -} - -/// Records every account observed by the on-state hook, so a test can assert that a read-only -/// pre-block outcome reached the witness path. -#[derive(Debug, Default, Clone)] -struct RecordingStateHook { - accounts: Arc>>, -} - -impl OnStateHook for RecordingStateHook { - fn on_state(&mut self, _source: StateChangeSource, state: &EvmState) { - self.accounts.lock().unwrap().extend(state.keys().copied()); - } -} - -/// A config that activates Rex6 without ever activating Rex5 must still materialize every -/// lower-spec predeploy — at the Rex5 Oracle version — and bootstrap the `SequencerRegistry` at -/// v2.0.0. Under per-fork gating none of this ran. -#[test] -fn test_partial_ladder_runs_lower_fork_setup() { - let chain_spec = rex6_only_chain_spec(); - // Precondition: this really is a partial ladder (no activation event below Rex6), and the - // executing spec is Rex6. The `is_*_active_at_timestamp` predicates cannot state this — they - // project the scheduled spec, which a partial ladder keeps high by design. - assert_eq!(chain_spec.mega_fork_activation(MegaHardfork::Rex5), ForkCondition::Never); - assert_eq!(chain_spec.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - assert_eq!(chain_spec.spec_id(0), MegaSpecId::REX6); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - executor.apply_pre_execution_changes().expect("partial-ladder pre-block setup must succeed"); - - for address in [ - ORACLE_CONTRACT_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - KEYLESS_DEPLOY_ADDRESS, - ACCESS_CONTROL_ADDRESS, - LIMIT_CONTROL_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - ] { - let info = state.basic(address).unwrap(); - assert!( - info.is_some_and(|i| i.code_hash != revm::primitives::KECCAK_EMPTY), - "{address} must be deployed on a partial ladder" - ); - } - - // The Oracle takes its Rex5 bytecode, and the registry its Rex6 bytecode with the seeded - // rotation delay — i.e. the position drives version selection too, not just the on/off gate. - assert_eq!( - state.basic(ORACLE_CONTRACT_ADDRESS).unwrap().unwrap().code_hash, - ORACLE_CONTRACT_CODE_HASH_REX5 - ); - assert_eq!( - state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, - SEQUENCER_REGISTRY_CODE_HASH_REX6 - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY).unwrap(), - U256::from(MIN_ROTATION_DELAY_BLOCKS) - ); -} - -/// The Rex5 fail-closed rule on pre-block system calls must be enforced on a partial ladder too. -/// Under per-fork gating the Rex5 check was skipped and a reverting EIP-2935 call was silently -/// accepted. -/// -/// Kept separate from the deployment test above: a pre-block EIP failure returns before the -/// predeploy loop is reached, so one block cannot assert both. -#[test] -fn test_partial_ladder_enforces_pre_block_fail_closed() { - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - // Break EIP-2935 specifically. - install_code(&mut db, alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, ALWAYS_REVERT_CODE); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex6_only_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("a reverting EIP-2935 pre-block call must reject the block"); - let alloy_evm::block::BlockExecutionError::Validation(validation_err) = &err else { - panic!("expected a validation error, got: {err:?}"); - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "expected BlockHashContractCall, got: {validation_err:?}" - ); - // Assert the *specific* failure. Both gating styles reject this block, but for different - // reasons: under per-fork gating the Rex5 check is skipped and the reverting call is - // accepted, only for `resolve_system_address` to later trip over the registry that was - // never deployed. Matching on the error variant alone would pass either way. - assert!( - format!("{validation_err:?}").contains("EIP-2935 pre-block system call did not succeed"), - "block must be rejected by the EIP-2935 fail-closed check itself, got: {validation_err:?}" - ); -} - -/// A config that activates Rex6 with no Rex5 entry at all cannot carry the -/// [`SequencerRegistryConfig`] the Rex5 bootstrap requires. Pre-block setup must fail closed -/// with a configuration error rather than silently skipping the registry. -/// -/// This drives `pre_execution_changes` directly rather than `apply_pre_execution_changes`: the -/// latter also runs `resolve_system_address`, which gates on the executing spec and so raises the -/// same error under either gating style. Only the pre-block setup step distinguishes them — -/// under per-fork gating it returns `Ok`, having quietly skipped the registry entirely. -#[test] -fn test_rex6_without_any_rex5_entry_fails_closed() { - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - let err = executor - .pre_execution_changes() - .expect_err("Rex5 setup without its config must fail rather than be skipped"); - assert!( - format!("{err:?}").contains("SequencerRegistryConfig not configured"), - "expected the missing-config error, got: {err:?}" - ); -} - -/// The load-time params roster (`validate_schedule` → `MissingParams`) and the block-time -/// fail-closed checks are written independently but must cover the same requirements: one -/// config missing a required params type has to fail BOTH surfaces. A params rule registered -/// on only one side — a schedule accepted at load that dies at the fork's first block, or a -/// load-time rule with no execution-time counterpart — fails this pairing. -#[test] -fn test_missing_params_fail_at_load_time_and_pre_block_alike() { - let ladder_through = |top: MegaHardfork| { - MegaHardfork::VARIANTS - .iter() - .copied() - .filter(|fork| { - !fork.spec_id().is_alias() && fork.spec_id() as u8 <= top.spec_id() as u8 - }) - .fold(MegaHardforkConfig::default(), |config, fork| { - config.with(fork, ForkCondition::Timestamp(0)) - }) - }; - let run_pre_block = |chain_spec: MegaHardforkConfig, spec: MegaSpecId| { - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = MegaBlockExecutorFactory::new( - chain_spec, - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(spec, 0), - ); - executor - .pre_execution_changes() - .err() - .map(|err| format!("{err:?}")) - .expect("a schedule missing required params must fail pre-block execution") - }; - - // Rex5 scheduled without `SequencerRegistryConfig`. - let rex5_without_params = ladder_through(MegaHardfork::Rex5); - assert_eq!( - rex5_without_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig" - }) - ); - let err = run_pre_block(rex5_without_params, MegaSpecId::REX5); - assert!(err.contains("SequencerRegistryConfig not configured"), "got: {err}"); - - // Rex6 scheduled with the Rex5 params attached but without `SequencerRegistryRex6Config`. - let rex6_without_params = - ladder_through(MegaHardfork::Rex6).with_params(sequencer_registry_config()); - assert_eq!( - rex6_without_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config" - }) - ); - let err = run_pre_block(rex6_without_params, MegaSpecId::REX6); - assert!(err.contains("SequencerRegistryRex6Config not configured"), "got: {err}"); -} - -/// Mainnet's `MiniRex1` window rolls the executing spec back to `EQUIVALENCE` while `MiniRex`'s -/// predeploys remain installed. Pre-block setup must keep emitting their read-only outcomes: -/// dropping them would remove the accounts from the on-state hook that feeds the stateless -/// witness and the state-sync transition shard — a replay-observable change on frozen history. -#[test] -fn test_rollback_window_still_emits_predeploy_witness_entries() { - let chain_spec = mega_evm::mainnet_hardforks(); - let ForkCondition::Timestamp(timestamp) = - chain_spec.mega_fork_activation(MegaHardfork::MiniRex1) - else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - // Precondition: inside the window the scheduled spec is the alias rung and its behavior - // projects back to EQUIVALENCE. - assert_eq!(chain_spec.spec_id(timestamp), MegaSpecId::MINI_REX_1); - assert_eq!(chain_spec.spec_id(timestamp).behavior(), MegaSpecId::EQUIVALENCE); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - // Both MiniRex predeploys are already installed, as they would be on mainnet by then, so the - // deploy takes its idempotent read-only path. - install_code(&mut db, ORACLE_CONTRACT_ADDRESS, mega_evm::ORACLE_CONTRACT_CODE); - install_code( - &mut db, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - mega_evm::HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::MINI_REX_1, timestamp), - ); - - let recorder = RecordingStateHook::default(); - let accounts = recorder.accounts.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - executor.apply_pre_execution_changes().expect("rollback-window pre-block setup must succeed"); - - let observed = accounts.lock().unwrap(); - for address in [ORACLE_CONTRACT_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS] { - assert!( - observed.contains(&address), - "{address} must still reach the witness hook during the rollback window" - ); - } - - // The rollback window is pre-Rex2, so the Oracle keeps its v1.0.0 bytecode. - assert_eq!( - state.basic(ORACLE_CONTRACT_ADDRESS).unwrap().unwrap().code_hash, - ORACLE_CONTRACT_CODE_HASH - ); -} diff --git a/crates/mega-evm/tests/compute_gas/snapshot.txt b/crates/mega-evm/tests/compute_gas/snapshot.txt deleted file mode 100644 index 000b0fef1..000000000 --- a/crates/mega-evm/tests/compute_gas/snapshot.txt +++ /dev/null @@ -1,429 +0,0 @@ -# Cross-spec compute-gas snapshot. -# -# Generated by `crates/mega-evm/tests/compute_gas`. Do not edit by hand. -# Regenerate: UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas -# -# `compute_gas` is the post-transaction compute-gas tracker reading; `gas_used` is the -# receipt value, which is neither counter nor their sum: refunds lower it, gas consumed -# outside a completed window raises it, and the calldata floor can raise it further. -# -# Frozen specs (Equivalence through Rex6) must never change: a diff there is a -# replay-breaking regression. -# -# program spec compute_gas gas_used outcome - -intrinsic_only Equivalence 0 21000 success -intrinsic_only MiniRex 21000 21000 success -intrinsic_only MiniRex1 0 21000 success -intrinsic_only MiniRex2 21000 21000 success -intrinsic_only Rex 21000 60000 success -intrinsic_only Rex1 21000 60000 success -intrinsic_only Rex2 21000 60000 success -intrinsic_only Rex3 21000 60000 success -intrinsic_only Rex4 21000 60000 success -intrinsic_only Rex5 21000 60000 success -intrinsic_only Rex6 21000 60000 success -intrinsic_only Rex7 21000 60000 success - -plain_arithmetic Equivalence 0 21352 success -plain_arithmetic MiniRex 21352 21352 success -plain_arithmetic MiniRex1 0 21352 success -plain_arithmetic MiniRex2 21352 21352 success -plain_arithmetic Rex 21352 60352 success -plain_arithmetic Rex1 21352 60352 success -plain_arithmetic Rex2 21352 60352 success -plain_arithmetic Rex3 21352 60352 success -plain_arithmetic Rex4 21352 60352 success -plain_arithmetic Rex5 21352 60352 success -plain_arithmetic Rex6 21352 60352 success -plain_arithmetic Rex7 21352 60352 success - -plain_memory_expansion Equivalence 0 21437 success -plain_memory_expansion MiniRex 21437 21437 success -plain_memory_expansion MiniRex1 0 21437 success -plain_memory_expansion MiniRex2 21437 21437 success -plain_memory_expansion Rex 21437 60437 success -plain_memory_expansion Rex1 21437 60437 success -plain_memory_expansion Rex2 21437 60437 success -plain_memory_expansion Rex3 21437 60437 success -plain_memory_expansion Rex4 21437 60437 success -plain_memory_expansion Rex5 21437 60437 success -plain_memory_expansion Rex6 21437 60437 success -plain_memory_expansion Rex7 21437 60437 success - -volatile_timestamp Equivalence 0 21004 success -volatile_timestamp MiniRex 21004 21004 success -volatile_timestamp MiniRex1 0 21004 success -volatile_timestamp MiniRex2 21004 21004 success -volatile_timestamp Rex 21004 60004 success -volatile_timestamp Rex1 21004 60004 success -volatile_timestamp Rex2 21004 60004 success -volatile_timestamp Rex3 21004 60004 success -volatile_timestamp Rex4 21004 60004 success -volatile_timestamp Rex5 21004 60004 success -volatile_timestamp Rex6 21004 60004 success -volatile_timestamp Rex7 21004 60004 success - -sstore_zero_to_nonzero Equivalence 0 43106 success -sstore_zero_to_nonzero MiniRex 43106 2043106 success -sstore_zero_to_nonzero MiniRex1 0 43106 success -sstore_zero_to_nonzero MiniRex2 43106 2043106 success -sstore_zero_to_nonzero Rex 43106 82106 success -sstore_zero_to_nonzero Rex1 43106 82106 success -sstore_zero_to_nonzero Rex2 43106 82106 success -sstore_zero_to_nonzero Rex3 43106 82106 success -sstore_zero_to_nonzero Rex4 43106 82106 success -sstore_zero_to_nonzero Rex5 43106 82106 success -sstore_zero_to_nonzero Rex6 43106 82106 success -sstore_zero_to_nonzero Rex7 43106 82106 success - -sstore_nonzero_to_nonzero Equivalence 0 26006 success -sstore_nonzero_to_nonzero MiniRex 26006 26006 success -sstore_nonzero_to_nonzero MiniRex1 0 26006 success -sstore_nonzero_to_nonzero MiniRex2 26006 26006 success -sstore_nonzero_to_nonzero Rex 26006 65006 success -sstore_nonzero_to_nonzero Rex1 26006 65006 success -sstore_nonzero_to_nonzero Rex2 26006 65006 success -sstore_nonzero_to_nonzero Rex3 26006 65006 success -sstore_nonzero_to_nonzero Rex4 26006 65006 success -sstore_nonzero_to_nonzero Rex5 26006 65006 success -sstore_nonzero_to_nonzero Rex6 26006 65006 success -sstore_nonzero_to_nonzero Rex7 26006 65006 success - -sstore_nonzero_to_zero Equivalence 0 21206 success -sstore_nonzero_to_zero MiniRex 26006 21206 success -sstore_nonzero_to_zero MiniRex1 0 21206 success -sstore_nonzero_to_zero MiniRex2 26006 21206 success -sstore_nonzero_to_zero Rex 26006 60206 success -sstore_nonzero_to_zero Rex1 26006 60206 success -sstore_nonzero_to_zero Rex2 26006 60206 success -sstore_nonzero_to_zero Rex3 26006 60206 success -sstore_nonzero_to_zero Rex4 26006 60206 success -sstore_nonzero_to_zero Rex5 26006 60206 success -sstore_nonzero_to_zero Rex6 26006 60206 success -sstore_nonzero_to_zero Rex7 26006 60206 success - -log0_empty Equivalence 0 21381 success -log0_empty MiniRex 21381 21381 success -log0_empty MiniRex1 0 21381 success -log0_empty MiniRex2 21381 21381 success -log0_empty Rex 21381 60381 success -log0_empty Rex1 21381 60381 success -log0_empty Rex2 21381 60381 success -log0_empty Rex3 21381 60381 success -log0_empty Rex4 21381 60381 success -log0_empty Rex5 21381 60381 success -log0_empty Rex6 21381 60381 success -log0_empty Rex7 21381 60381 success - -log1_32bytes Equivalence 0 22027 success -log1_32bytes MiniRex 22027 28337 success -log1_32bytes MiniRex1 0 22027 success -log1_32bytes MiniRex2 22027 28337 success -log1_32bytes Rex 22027 67337 success -log1_32bytes Rex1 22027 67337 success -log1_32bytes Rex2 22027 67337 success -log1_32bytes Rex3 22027 67337 success -log1_32bytes Rex4 22027 67337 success -log1_32bytes Rex5 22027 67337 success -log1_32bytes Rex6 22027 67337 success -log1_32bytes Rex7 22027 67337 success - -log4_128bytes Equivalence 0 23965 success -log4_128bytes MiniRex 23965 49205 success -log4_128bytes MiniRex1 0 23965 success -log4_128bytes MiniRex2 23965 49205 success -log4_128bytes Rex 23965 88205 success -log4_128bytes Rex1 23965 88205 success -log4_128bytes Rex2 23965 88205 success -log4_128bytes Rex3 23965 88205 success -log4_128bytes Rex4 23965 88205 success -log4_128bytes Rex5 23965 88205 success -log4_128bytes Rex6 23965 88205 success -log4_128bytes Rex7 23965 88205 success - -log2_log3_sequence Equivalence 0 24176 success -log2_log3_sequence MiniRex 24176 48046 success -log2_log3_sequence MiniRex1 0 24176 success -log2_log3_sequence MiniRex2 24176 48046 success -log2_log3_sequence Rex 24176 87046 success -log2_log3_sequence Rex1 24176 87046 success -log2_log3_sequence Rex2 24176 87046 success -log2_log3_sequence Rex3 24176 87046 success -log2_log3_sequence Rex4 24176 87046 success -log2_log3_sequence Rex5 24176 87046 success -log2_log3_sequence Rex6 24176 87046 success -log2_log3_sequence Rex7 24176 87046 success - -call_no_value_to_code Equivalence 0 23621 success -call_no_value_to_code MiniRex 23621 23621 success -call_no_value_to_code MiniRex1 0 23621 success -call_no_value_to_code MiniRex2 23621 23621 success -call_no_value_to_code Rex 23621 62621 success -call_no_value_to_code Rex1 23621 62621 success -call_no_value_to_code Rex2 23621 62621 success -call_no_value_to_code Rex3 23621 62621 success -call_no_value_to_code Rex4 23621 62621 success -call_no_value_to_code Rex5 23621 62621 success -call_no_value_to_code Rex6 23621 62621 success -call_no_value_to_code Rex7 23621 62621 success - -call_value_to_empty Equivalence 0 55321 success -call_value_to_empty MiniRex 55321 2055321 success -call_value_to_empty MiniRex1 0 55321 success -call_value_to_empty MiniRex2 55321 2055321 success -call_value_to_empty Rex 55321 94321 success -call_value_to_empty Rex1 55321 94321 success -call_value_to_empty Rex2 55321 94321 success -call_value_to_empty Rex3 55321 94321 success -call_value_to_empty Rex4 55321 94321 success -call_value_to_empty Rex5 57621 94321 success -call_value_to_empty Rex6 57621 94321 success -call_value_to_empty Rex7 57621 94321 success - -call_value_to_existing Equivalence 0 30321 success -call_value_to_existing MiniRex 30321 30321 success -call_value_to_existing MiniRex1 0 30321 success -call_value_to_existing MiniRex2 30321 30321 success -call_value_to_existing Rex 30321 69321 success -call_value_to_existing Rex1 30321 69321 success -call_value_to_existing Rex2 30321 69321 success -call_value_to_existing Rex3 30321 69321 success -call_value_to_existing Rex4 30321 69321 success -call_value_to_existing Rex5 32621 69321 success -call_value_to_existing Rex6 32621 69321 success -call_value_to_existing Rex7 32621 69321 success - -callcode_value Equivalence 0 30321 success -callcode_value MiniRex 30321 30321 success -callcode_value MiniRex1 0 30321 success -callcode_value MiniRex2 30321 30321 success -callcode_value Rex 30321 69321 success -callcode_value Rex1 30321 69321 success -callcode_value Rex2 30321 69321 success -callcode_value Rex3 30321 69321 success -callcode_value Rex4 30321 69321 success -callcode_value Rex5 32621 69321 success -callcode_value Rex6 32621 69321 success -callcode_value Rex7 32621 69321 success - -delegatecall Equivalence 0 23618 success -delegatecall MiniRex 23618 23618 success -delegatecall MiniRex1 0 23618 success -delegatecall MiniRex2 23618 23618 success -delegatecall Rex 23618 62618 success -delegatecall Rex1 23618 62618 success -delegatecall Rex2 23618 62618 success -delegatecall Rex3 23618 62618 success -delegatecall Rex4 23618 62618 success -delegatecall Rex5 23618 62618 success -delegatecall Rex6 23618 62618 success -delegatecall Rex7 23618 62618 success - -staticcall Equivalence 0 23618 success -staticcall MiniRex 23618 23618 success -staticcall MiniRex1 0 23618 success -staticcall MiniRex2 23618 23618 success -staticcall Rex 23618 62618 success -staticcall Rex1 23618 62618 success -staticcall Rex2 23618 62618 success -staticcall Rex3 23618 62618 success -staticcall Rex4 23618 62618 success -staticcall Rex5 23618 62618 success -staticcall Rex6 23618 62618 success -staticcall Rex7 23618 62618 success - -nested_calls_depth3 Equivalence 0 26236 success -nested_calls_depth3 MiniRex 26236 26236 success -nested_calls_depth3 MiniRex1 0 26236 success -nested_calls_depth3 MiniRex2 26236 26236 success -nested_calls_depth3 Rex 26236 65236 success -nested_calls_depth3 Rex1 26236 65236 success -nested_calls_depth3 Rex2 26236 65236 success -nested_calls_depth3 Rex3 26236 65236 success -nested_calls_depth3 Rex4 26236 65236 success -nested_calls_depth3 Rex5 26236 65236 success -nested_calls_depth3 Rex6 26236 65236 success -nested_calls_depth3 Rex7 26236 65236 success - -create_empty_initcode Equivalence 0 53009 success -create_empty_initcode MiniRex 53009 2053009 success -create_empty_initcode MiniRex1 0 53009 success -create_empty_initcode MiniRex2 53009 2053009 success -create_empty_initcode Rex 53009 92009 success -create_empty_initcode Rex1 53009 92009 success -create_empty_initcode Rex2 53009 92009 success -create_empty_initcode Rex3 53009 92009 success -create_empty_initcode Rex4 53009 92009 success -create_empty_initcode Rex5 53009 92009 success -create_empty_initcode Rex6 53009 92009 success -create_empty_initcode Rex7 53009 92009 success - -create2_empty_initcode Equivalence 0 53012 success -create2_empty_initcode MiniRex 53012 2053012 success -create2_empty_initcode MiniRex1 0 53012 success -create2_empty_initcode MiniRex2 53012 2053012 success -create2_empty_initcode Rex 53012 92012 success -create2_empty_initcode Rex1 53012 92012 success -create2_empty_initcode Rex2 53012 92012 success -create2_empty_initcode Rex3 53012 92012 success -create2_empty_initcode Rex4 53012 92012 success -create2_empty_initcode Rex5 53012 92012 success -create2_empty_initcode Rex6 53012 92012 success -create2_empty_initcode Rex7 53012 92012 success - -create2_with_initcode Equivalence 0 53032 success -create2_with_initcode MiniRex 53032 2053032 success -create2_with_initcode MiniRex1 0 53032 success -create2_with_initcode MiniRex2 53032 2053032 success -create2_with_initcode Rex 53032 92032 success -create2_with_initcode Rex1 53032 92032 success -create2_with_initcode Rex2 53032 92032 success -create2_with_initcode Rex3 53032 92032 success -create2_with_initcode Rex4 53032 92032 success -create2_with_initcode Rex5 53032 92032 success -create2_with_initcode Rex6 53032 92032 success -create2_with_initcode Rex7 53032 92032 success - -create_deploying_runtime_code Equivalence 0 59431 success -create_deploying_runtime_code MiniRex 59431 2379431 success -create_deploying_runtime_code MiniRex1 0 59431 success -create_deploying_runtime_code MiniRex2 59431 2379431 success -create_deploying_runtime_code Rex 59431 418431 success -create_deploying_runtime_code Rex1 59431 418431 success -create_deploying_runtime_code Rex2 59431 418431 success -create_deploying_runtime_code Rex3 59431 418431 success -create_deploying_runtime_code Rex4 59431 418431 success -create_deploying_runtime_code Rex5 59431 418431 success -create_deploying_runtime_code Rex6 59431 418431 success -create_deploying_runtime_code Rex7 59431 418431 success - -create2_far_memory_offset Equivalence 0 67367 success -create2_far_memory_offset MiniRex 67367 2067367 success -create2_far_memory_offset MiniRex1 0 67367 success -create2_far_memory_offset MiniRex2 67367 2067367 success -create2_far_memory_offset Rex 67367 106367 success -create2_far_memory_offset Rex1 67367 106367 success -create2_far_memory_offset Rex2 67367 106367 success -create2_far_memory_offset Rex3 67367 106367 success -create2_far_memory_offset Rex4 67367 106367 success -create2_far_memory_offset Rex5 67367 106367 success -create2_far_memory_offset Rex6 67367 106367 success -create2_far_memory_offset Rex7 67367 106367 success - -create2_oversized_initcode Equivalence 0 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex1 0 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex2 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex1 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex2 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex3 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex4 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex5 763907 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex6 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex7 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) - -selfdestruct_to_empty Equivalence 0 53603 success -selfdestruct_to_empty MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty MiniRex1 0 53603 success -selfdestruct_to_empty MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex2 53603 92603 success -selfdestruct_to_empty Rex3 53603 92603 success -selfdestruct_to_empty Rex4 53603 92603 success -selfdestruct_to_empty Rex5 53603 92603 success -selfdestruct_to_empty Rex6 53603 92603 success -selfdestruct_to_empty Rex7 53603 92603 success - -selfdestruct_to_existing Equivalence 0 28603 success -selfdestruct_to_existing MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing MiniRex1 0 28603 success -selfdestruct_to_existing MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex2 28603 67603 success -selfdestruct_to_existing Rex3 28603 67603 success -selfdestruct_to_existing Rex4 28603 67603 success -selfdestruct_to_existing Rex5 28603 67603 success -selfdestruct_to_existing Rex6 28603 67603 success -selfdestruct_to_existing Rex7 28603 67603 success - -selfdestruct_to_self Equivalence 0 26003 success -selfdestruct_to_self MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self MiniRex1 0 26003 success -selfdestruct_to_self MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex2 26003 65003 success -selfdestruct_to_self Rex3 26003 65003 success -selfdestruct_to_self Rex4 26003 65003 success -selfdestruct_to_self Rex5 26003 65003 success -selfdestruct_to_self Rex6 26003 65003 success -selfdestruct_to_self Rex7 26003 65003 success - -precompile_identity Equivalence 0 21157 success -precompile_identity MiniRex 23657 23657 success -precompile_identity MiniRex1 0 21157 success -precompile_identity MiniRex2 23657 23657 success -precompile_identity Rex 23657 62657 success -precompile_identity Rex1 23657 62657 success -precompile_identity Rex2 23657 62657 success -precompile_identity Rex3 23657 62657 success -precompile_identity Rex4 23657 62657 success -precompile_identity Rex5 23657 62657 success -precompile_identity Rex6 23657 62657 success -precompile_identity Rex7 23657 62657 success - -precompile_sha256 Equivalence 0 21211 success -precompile_sha256 MiniRex 23711 23711 success -precompile_sha256 MiniRex1 0 21211 success -precompile_sha256 MiniRex2 23711 23711 success -precompile_sha256 Rex 23711 62711 success -precompile_sha256 Rex1 23711 62711 success -precompile_sha256 Rex2 23711 62711 success -precompile_sha256 Rex3 23711 62711 success -precompile_sha256 Rex4 23711 62711 success -precompile_sha256 Rex5 23711 62711 success -precompile_sha256 Rex6 23711 62711 success -precompile_sha256 Rex7 23711 62711 success - -precompile_kzg_invalid_input Equivalence 0 221133 success -precompile_kzg_invalid_input MiniRex 23633 223633 success -precompile_kzg_invalid_input MiniRex1 0 221133 success -precompile_kzg_invalid_input MiniRex2 23633 223633 success -precompile_kzg_invalid_input Rex 23633 262633 success -precompile_kzg_invalid_input Rex1 23633 262633 success -precompile_kzg_invalid_input Rex2 23633 262633 success -precompile_kzg_invalid_input Rex3 23633 262633 success -precompile_kzg_invalid_input Rex4 23633 262633 success -precompile_kzg_invalid_input Rex5 123633 262633 success -precompile_kzg_invalid_input Rex6 123633 262633 success -precompile_kzg_invalid_input Rex7 123633 262633 success - -precompile_underfunded Equivalence 0 21140 success -precompile_underfunded MiniRex 23639 23640 success -precompile_underfunded MiniRex1 0 21140 success -precompile_underfunded MiniRex2 23639 23640 success -precompile_underfunded Rex 23639 62640 success -precompile_underfunded Rex1 23639 62640 success -precompile_underfunded Rex2 23639 62640 success -precompile_underfunded Rex3 23639 62640 success -precompile_underfunded Rex4 23639 62640 success -precompile_underfunded Rex5 23640 62640 success -precompile_underfunded Rex6 23640 62640 success -precompile_underfunded Rex7 23640 62640 success - -reverting_subcall Equivalence 0 24326 success -reverting_subcall MiniRex 24326 24326 success -reverting_subcall MiniRex1 0 24326 success -reverting_subcall MiniRex2 24326 24326 success -reverting_subcall Rex 24326 63326 success -reverting_subcall Rex1 24326 63326 success -reverting_subcall Rex2 24326 63326 success -reverting_subcall Rex3 24326 63326 success -reverting_subcall Rex4 24326 63326 success -reverting_subcall Rex5 24326 63326 success -reverting_subcall Rex6 24326 63326 success -reverting_subcall Rex7 24326 63326 success diff --git a/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs b/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs deleted file mode 100644 index 5aae3f245..000000000 --- a/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Tests for the disabled SELFDESTRUCT opcode in the Mini-Rex spec. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::{ - bytecode::opcode::{PUSH0, SELFDESTRUCT}, - context::result::{ExecutionResult, ResultAndState}, - }, - test_utils::{transact, MemoryDatabase}, - *, -}; - -/// Test that verifies the SELFDESTRUCT opcode works normally before the Mini-Rex hardfork. -/// This test ensures that contracts using the SELFDESTRUCT opcode execute successfully -/// and consume the expected amount of gas when using the `EQUIVALENCE` spec. -#[test] -fn test_selfdestruct_allowed_before_mini_rex() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::EQUIVALENCE, &mut db, caller, callee, Bytes::default(), U256::ZERO); - assert!(result.is_ok()); - assert_eq!(result.unwrap().result.gas_used(), 26004); -} - -/// Test that verifies the SELFDESTRUCT opcode is disabled and returns `InvalidFEOpcode` after -/// the Mini-Rex hardfork. This test ensures that contracts attempting to use the SELFDESTRUCT -/// opcode are properly rejected with the correct halt reason when using the `MINI_REX` spec. -#[test] -fn test_selfdestruct_disallowed_after_mini_rex() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO); - assert!(matches!( - result, - Ok(ResultAndState { - result: ExecutionResult::Halt { - reason: MegaHaltReason::Base(OpHaltReason::Base(EthHaltReason::InvalidFEOpcode)), - .. - }, - .. - }) - )); -} diff --git a/crates/mega-evm/tests/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/mini_rex/state_growth_limit.rs deleted file mode 100644 index 431cabc30..000000000 --- a/crates/mega-evm/tests/mini_rex/state_growth_limit.rs +++ /dev/null @@ -1,807 +0,0 @@ -//! Tests for the state growth limit feature of the `MegaETH` EVM. -//! -//! These tests verify that the state growth limit functionality correctly tracks and limits -//! the creation of new accounts and storage slots during transaction execution. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, DatabaseCommit, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const NEW_ACCOUNT: Address = address!("0000000000000000000000000000000000100003"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified state growth limit. -/// -/// Returns the execution result and the actual state growth used. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -/// Checks if the execution result indicates that the state growth limit was exceeded. -fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } - ) -} - -/// Creates a default transaction builder calling a contract. -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -// ============================================================================ -// BASIC STATE GROWTH TRACKING TESTS -// ============================================================================ - -#[test] -fn test_empty_transaction() { - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Empty transaction should have zero state growth"); -} - -#[test] -fn test_create_new_account_via_value_transfer() { - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // Transfer value to a new account - let tx = default_tx_builder(NEW_ACCOUNT).value(U256::from(100)).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Creating new account via value transfer should count as +1"); -} - -#[test] -fn test_create_new_storage_slot() { - // Contract that writes to a single storage slot - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(42)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Writing to empty storage slot should count as +1"); -} - -#[test] -fn test_clear_storage_slot() { - // Contract that writes to a slot then clears it - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(42)) // Write: 0 -> 42 (+1) - .sstore(U256::from(0), U256::from(0)) // Clear: 42 -> 0 (-1) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Creating then clearing a slot should result in zero net growth"); -} - -#[test] -fn test_contract_creation() { - // Simple contract to deploy - let deployed_code = BytecodeBuilder::default().stop().build(); - - // Deployment code that returns the contract code - let init_code = BytecodeBuilder::default().return_with_data(deployed_code).build(); - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - // CREATE transaction - let tx = TxEnvBuilder::default() - .caller(CALLER) - .create() - .data(init_code) - .gas_limit(10_000_000) - .build_fill(); - - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Contract creation should count as +1"); -} - -#[test] -fn test_multiple_writes_same_slot() { - // Contract that writes to the same slot multiple times - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // First write: 0 -> 1 (+1) - .sstore(U256::from(0), U256::from(2)) // Overwrite: 1 -> 2 (0) - .sstore(U256::from(0), U256::from(3)) // Overwrite: 2 -> 3 (0) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Multiple writes to same slot should only count first write"); -} - -// ============================================================================ -// NET GROWTH MODEL TESTS -// ============================================================================ - -#[test] -fn test_net_growth_calculation() { - // Create 3 slots, clear 1 slot -> net growth = 2 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Net growth should be 3 - 1 = 2"); -} - -#[test] -fn test_growth_eventually_zero() { - // Create and clear multiple slots, ending at zero - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .sstore(U256::from(1), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "All creates and clears should cancel out to zero"); -} - -#[test] -fn test_multiple_operations_net_growth() { - // Complex sequence: create 5, clear 2 -> net 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(1)) // +1 - .sstore(U256::from(2), U256::from(1)) // +1 - .sstore(U256::from(3), U256::from(1)) // +1 - .sstore(U256::from(4), U256::from(1)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .sstore(U256::from(1), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Net growth should be 5 - 2 = 3"); -} - -#[test] -fn test_storage_slot_already_exists() { - // Write to a slot that already has a value (should not count) - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(100)) // Modify existing slot (0) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // Pre-populate the storage slot - db.set_account_storage(CALLEE, U256::from(0), U256::from(42)); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Modifying existing storage slot should not count as growth"); -} - -// ============================================================================ -// FRAME-BASED TRACKING TESTS -// ============================================================================ - -#[test] -fn test_simple_call_executes() { - // First, verify that a simple CALL actually executes the child code - // Child returns a specific value to prove it executed - let child_code = BytecodeBuilder::default().return_with_data(vec![0x42_u8]).build(); - - // Parent calls child and checks return value - let parent_code = BytecodeBuilder::default() - .push_number(32_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - // CALL result is on stack (1 = success, 0 = failure) - .assert_stack_value(0, U256::from(1)) // Verify CALL succeeded - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed if child executes"); -} - -#[test] -fn test_nested_call_successful_child() { - // Child contract that creates a storage slot - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in child - .stop() - .build(); - - // Parent contract that creates a storage slot and calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in parent - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - increased - .append(CALL) - // Check if CALL succeeded - .assert_stack_value(0, U256::from(1)) // CALL should return 1 on success - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Parent and child growth should both count"); -} - -#[test] -fn test_nested_call_reverting_child() { - // Child contract that creates a storage slot then reverts - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in child (will be discarded) - .revert() - .build(); - - // Parent contract that creates a storage slot and calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in parent - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Child growth should be discarded on revert"); -} - -#[test] -fn test_deeply_nested_calls() { - // Level 2 contract: creates 1 slot - let level2_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .stop() - .build(); - - // Level 1 contract: creates 1 slot, calls level 2 - let level1_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // level 2 address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - // Level 0 (parent): creates 1 slot, calls level 1 - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CALLEE) // level 1 address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(address!("0000000000000000000000000000000000100010"), parent_code) - .account_code(CALLEE, level1_code) - .account_code(CONTRACT, level2_code); - - let tx = default_tx_builder(address!("0000000000000000000000000000000000100010")).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "All levels should contribute to growth"); -} - -#[test] -fn test_parent_creates_child_reverts() { - // Child that reverts after creating state - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 (will be discarded) - .sstore(U256::from(1), U256::from(2)) // +1 (will be discarded) - .revert() - .build(); - - // Parent creates 3 slots, calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Only parent growth should count"); -} - -#[test] -fn test_both_parent_and_child_create_state() { - // Child creates 2 slots - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .stop() - .build(); - - // Parent creates 3 slots, calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5, "Parent (3) + child (2) = 5 total growth"); -} - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -#[test] -fn test_limit_exactly_at_limit() { - // Create exactly 3 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Exactly at limit should succeed"); -} - -#[test] -fn test_limit_exceeded_by_one() { - // Try to create 4 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .sstore(U256::from(3), U256::from(4)) // +1 (exceeds limit) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // Verify the halt reason details - the actual growth is preserved in the halt reason - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit, actual }, - .. - } => { - assert_eq!(*limit, 3); - assert_eq!(*actual, 4, "Should report actual growth that exceeded limit"); - } - _ => panic!("Expected StateGrowthLimitExceeded halt"), - } -} - -#[test] -fn test_limit_exceeded_in_nested_call() { - // Child creates 2 slots - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .stop() - .build(); - - // Parent creates 2 slots, then calls child (total would be 4, limit is 3) - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); -} - -#[test] -fn test_state_reverted_when_exceeding_limit() { - // Create 2 slots, then exceed limit on 3rd (with limit of 2) - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(100)) // +1 - .sstore(U256::from(1), U256::from(200)) // +1 - .sstore(U256::from(2), U256::from(300)) // +1 (exceeds) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // State should not be committed - db.commit(result.state); - - // Verify the storage was not persisted - let storage_0 = db.storage(CALLEE, U256::from(0)).unwrap(); - let storage_1 = db.storage(CALLEE, U256::from(1)).unwrap(); - let storage_2 = db.storage(CALLEE, U256::from(2)).unwrap(); - - assert_eq!(storage_0, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_1, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_2, U256::ZERO, "Storage should be reverted"); -} - -#[test] -fn test_gas_preserved_on_limit_exceeded() { - // Create slots until limit exceeded - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 (exceeds) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let gas_limit = 10_000_000_u64; - let tx = TxEnvBuilder::default().caller(CALLER).call(CALLEE).gas_limit(gas_limit).build_fill(); - - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // Gas should not all be consumed - let gas_used = result.result.gas_used(); - assert!(gas_used < gas_limit, "Gas should be preserved on limit exceeded, not all consumed"); -} - -// ============================================================================ -// COMPLEX SCENARIOS TESTS -// ============================================================================ - -#[test] -fn test_mixed_operations() { - // Contract that creates account via CREATE and writes storage - let deployed_code = BytecodeBuilder::default().stop().build(); - - let init_code = BytecodeBuilder::default().return_with_data(deployed_code).build(); - - // Main contract: writes storage then creates contract - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 storage - .sstore(U256::from(1), U256::from(2)) // +1 storage - .push_number(0_u64) // value - .mstore(0x00, init_code.clone()) // Store init code in memory - .push_number(init_code.len() as u64) // size - .push_number(0x00_u64) // offset - .append(CREATE) // +1 account - .append(POP) // Pop created address - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "2 storage slots + 1 account = 3 growth"); -} - -#[test] -fn test_multiple_transactions_reset_counters() { - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // First transaction - let tx1 = default_tx_builder(CALLEE).nonce(0).build_fill(); - let (result1, state_growth1) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx1).unwrap(); - assert!(result1.result.is_success()); - assert_eq!(state_growth1, 1); - - // Commit first transaction - db.commit(result1.state); - - // Second transaction - counter should reset, but slot is now non-zero - let tx2 = default_tx_builder(CALLEE).nonce(1).build_fill(); - let (result2, state_growth2) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx2).unwrap(); - assert!(result2.result.is_success()); - assert_eq!(state_growth2, 0, "Second tx should have 0 growth as slot already exists"); -} - -#[test] -fn test_state_growth_tracked_in_mini_rex() { - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(1)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "MINI_REX spec should track state growth"); -} - -#[test] -fn test_state_growth_not_tracked_in_equivalence() { - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(1)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::EQUIVALENCE, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "EQUIVALENCE spec should not track state growth"); -} - -// ============================================================================ -// TRACKER MIGRATION COVERAGE TESTS -// ============================================================================ - -/// Tests that when a child frame both writes a storage slot (+1 growth) and resets it back -/// to zero (-1 refund), then reverts, BOTH the growth and the refund are discarded. -/// -/// This exercises the new tracker's separate `discardable_usage` and `refund` fields -/// (vs the old tracker's single `i64 discardable`), ensuring they are both dropped on revert. -#[test] -fn test_child_write_and_refund_both_discarded_on_revert() { - // Child: write slot 0 from 0→1 (+1 growth), then reset slot 0 from 1→0 (-1 refund), then REVERT - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // growth: +1 - .sstore(U256::from(0), U256::from(0)) // refund: -1 - .revert() - .build(); - - // Parent: write slot 5 from 0→1 (+1 growth), CALL child, STOP - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(5), U256::from(1)) // growth: +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - // Only parent's slot 5 write should count; child's write (+1) and refund (-1) both discarded. - assert_eq!( - state_growth, 1, - "Child's growth and refund should both be discarded on revert, leaving only parent's +1" - ); -} diff --git a/crates/mega-evm/tests/mutation/limit.rs b/crates/mega-evm/tests/mutation/limit.rs deleted file mode 100644 index 2c0d065cc..000000000 --- a/crates/mega-evm/tests/mutation/limit.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Attempts to kill the frame-interaction mutants in `src/limit/limit.rs`: -//! -//! * `:585` — `AdditionalLimit::before_frame_run -> Option` replaced with -//! `None`. The four sub-tracker `before_frame_run` calls use the default trait no-op, so the only -//! behavioral effect of this hook is its early `check_limit()` halt: when a TX-level limit was -//! already latched (e.g. a CREATE child frame whose `after_frame_init` recording of the created -//! account tipped the KV/data budget over), the hook short-circuits the frame *before* its init -//! code runs. The mutant drops that short-circuit, so the init code runs. -//! -//! * `:676` — `&&` replaced with `||` in the `duplicate_return_frame_result` guard of -//! `before_frame_return_result`. The flag distinguishes the two `last_frame_result` / -//! `frame_return_result` calls for a top-level frame that has child frames. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const FACTORY: Address = address!("0000000000000000000000000000000000200001"); - -/// Constructor (init) code that runs `SSTORE(0, 1)` then `RETURN(0, 1)`: 8 bytes, -/// `PUSH1 1 PUSH0 SSTORE PUSH1 1 PUSH0 RETURN`. The SSTORE makes the constructor's execution -/// observable in gas and state: if the created frame is short-circuited at `before_frame_run`, -/// the SSTORE never runs. -fn create_init_code() -> Vec { - vec![PUSH1, 0x01, PUSH0, SSTORE, PUSH1, 0x01, PUSH0, RETURN] -} - -/// Factory that stores the init code in memory and CREATEs a contract from it, then STOPs. -fn create_factory_code() -> Bytes { - let init = create_init_code(); - let init_len = init.len() as u64; - BytecodeBuilder::default() - .mstore(0, init) // left-aligned init code at offset 0 - .push_number(init_len) // size - .push_number(0_u64) // offset - .push_number(0_u64) // value - .append(CREATE) - .append(POP) - .append(STOP) - .build() -} - -fn transact_with_kv_limit( - db: &mut MemoryDatabase, - kv_update_limit: u64, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(kv_update_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// A CREATE child frame whose `after_frame_init` records the created account's KV update, -/// tipping the TX over the KV-update budget, must be short-circuited at `before_frame_run` -/// before its constructor body executes. The transaction halts with `KVUpdateLimitExceeded`. -/// -/// This pins `gas_used`: if `before_frame_run` is mutated to always return `None`, the -/// constructor's SSTORE runs before the exceed is re-detected in `after_frame_run`, -/// changing the gas consumed by the create frame and therefore the transaction `gas_used`. -#[test] -fn test_before_frame_run_short_circuits_already_exceeded_create_frame() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - db.set_account_code(FACTORY, create_factory_code()); - - // KV updates: caller nonce (1) + factory nonce (1) + created account (1) = 3. - // The created-account KV is recorded in the CREATE frame's `after_frame_init`; with a - // budget of 2 it tips the limit over, so `before_frame_run` must short-circuit the - // constructor. - let tx = - TxEnvBuilder::default().caller(CALLER).call(FACTORY).gas_limit(10_000_000).build_fill(); - - let result = transact_with_kv_limit(&mut db, 2, tx).unwrap(); - - let gas_used = match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, - gas_used, - } => *gas_used, - other => panic!("expected KVUpdateLimitExceeded halt, got {other:?}"), - }; - // Pinned `gas_used` with the constructor short-circuited at `before_frame_run`. - // Calibrated against the unmutated build; the `-> None` mutant lets the constructor run - // and produces a different value. - assert_eq!( - gas_used, GAS_USED_SHORT_CIRCUITED, - "before_frame_run must short-circuit the over-budget CREATE frame before its \ - constructor runs; a different gas_used means the short-circuit was dropped" - ); -} - -/// Calibrated `gas_used` for the unmutated build, where `before_frame_run` short-circuits the -/// over-budget CREATE frame before its SSTORE constructor runs. -const GAS_USED_SHORT_CIRCUITED: u64 = 2_053_023; diff --git a/crates/mega-evm/tests/rex/intrinsic_gas.rs b/crates/mega-evm/tests/rex/intrinsic_gas.rs deleted file mode 100644 index 034a4a64f..000000000 --- a/crates/mega-evm/tests/rex/intrinsic_gas.rs +++ /dev/null @@ -1,317 +0,0 @@ -//! Tests for Rex hardfork additional intrinsic gas costs. - -use std::convert::Infallible; - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - constants, test_utils::MemoryDatabase, EVMError, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, MegaTransactionError, TestExternalEnvs, -}; -use revm::{ - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); - -/// Base intrinsic gas cost for all transactions -const BASE_INTRINSIC_GAS: u64 = 21_000; - -/// Executes a transaction on the EVM. -#[allow(clippy::too_many_arguments)] -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Tests that Rex hardfork adds 39,000 gas to base transaction cost for simple transfer. -#[test] -fn test_rex_intrinsic_gas_simple_transfer() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // Rex: 21,000 (base) + 39,000 (Rex intrinsic storage gas) = 60,000 - assert_eq!(gas_used, BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that `MiniRex` does NOT charge the additional 39,000 intrinsic gas. -#[test] -fn test_mini_rex_no_additional_intrinsic_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::MINI_REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // `MiniRex`: only 21,000 (base) - no additional intrinsic gas - assert_eq!(gas_used, BASE_INTRINSIC_GAS); -} - -/// Tests that `Equivalence` spec does NOT charge the additional 39,000 intrinsic gas. -#[test] -fn test_equivalence_no_additional_intrinsic_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::EQUIVALENCE, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // `Equivalence`: only 21,000 (base) - no additional intrinsic gas - assert_eq!(gas_used, BASE_INTRINSIC_GAS); -} - -/// Tests `Rex` intrinsic gas with calldata (combines calldata costs + intrinsic storage gas). -#[test] -fn test_rex_intrinsic_gas_with_calldata() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - // Create calldata with 100 bytes (all non-zero for maximum gas cost) - let calldata = Bytes::from(vec![1u8; 100]); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // `Rex` inherits `MiniRex` calldata costs and adds 39,000 intrinsic storage gas - // For 100 bytes of non-zero calldata: - // - MiniRex base cost: 38,600 (from floor gas test calculations) - // - Rex intrinsic storage gas: 39,000 - // Total: 77,600 - let expected_gas = 77_600; - assert_eq!(gas_used, expected_gas); -} - -/// Tests that Rex transaction fails if gas limit is below intrinsic gas requirement. -#[test] -fn test_rex_intrinsic_gas_insufficient_gas_limit() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - // Set gas limit to just below the Rex intrinsic gas (60,000) - let insufficient_gas_limit = BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS - 1; - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - insufficient_gas_limit, - ); - - // Transaction should fail due to insufficient gas - assert!(res.is_err()); -} - -/// Tests that Rex intrinsic gas applies to contract creation transactions. -#[test] -fn test_rex_intrinsic_gas_contract_creation() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - // Simple contract bytecode that does nothing (PUSH0 PUSH0 RETURN) - let init_code = Bytes::from(vec![0x5f, 0x5f, 0xf3]); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - None, // None means CREATE - init_code, - U256::ZERO, - 10_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // Should include the Rex intrinsic storage gas + other costs - // At minimum, it should be more than base + Rex intrinsic - assert!(gas_used >= BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that `Rex` intrinsic gas is exactly 39,000 more than `MiniRex` for same transaction. -#[test] -fn test_rex_vs_mini_rex_gas_difference() { - let mut db_rex = MemoryDatabase::default(); - db_rex.set_account_balance(CALLER, U256::from(1_000_000)); - db_rex.set_account_balance(CALLEE, U256::from(100)); - - let mut db_mini_rex = MemoryDatabase::default(); - db_mini_rex.set_account_balance(CALLER, U256::from(1_000_000)); - db_mini_rex.set_account_balance(CALLEE, U256::from(100)); - - // Use empty calldata for simplest comparison - let calldata = Bytes::new(); - - let res_rex = transact( - MegaSpecId::REX, - &mut db_rex, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata.clone(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - let res_mini_rex = transact( - MegaSpecId::MINI_REX, - &mut db_mini_rex, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res_rex.result.is_success()); - assert!(res_mini_rex.result.is_success()); - - let gas_used_rex = res_rex.result.gas_used(); - let gas_used_mini_rex = res_mini_rex.result.gas_used(); - - // For transactions without calldata, the difference should be exactly - // the Rex intrinsic storage gas (39,000) - assert_eq!(gas_used_rex - gas_used_mini_rex, constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that Rex intrinsic gas applies even for zero-value transfers. -#[test] -fn test_rex_intrinsic_gas_zero_value_transfer() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, // Zero value transfer - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // Rex: 21,000 (base) + 39,000 (Rex intrinsic storage gas) = 60,000 - assert_eq!(gas_used, BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests Rex intrinsic gas with new account creation (combines new account gas + intrinsic gas). -#[test] -fn test_rex_intrinsic_gas_new_account_creation() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - // CALLEE doesn't exist in db (new account) - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), // Non-zero value to trigger new account gas - 10_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // Rex charges: - // - Base: 21,000 - // - Rex intrinsic storage gas: 39,000 - // Total: 2,060,000 - let expected_gas = BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS; - assert_eq!(gas_used, expected_gas); -} diff --git a/crates/mega-evm/tests/rex2/selfdestruct.rs b/crates/mega-evm/tests/rex2/selfdestruct.rs deleted file mode 100644 index baff77d9b..000000000 --- a/crates/mega-evm/tests/rex2/selfdestruct.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! Tests for the SELFDESTRUCT opcode behavior in Rex2. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::{ - bytecode::opcode::{PUSH0, SELFDESTRUCT}, - context::result::{ExecutionResult, ResultAndState}, - }, - test_utils::{transact, MemoryDatabase}, - *, -}; - -#[test] -fn test_selfdestruct_allowed_in_rex2() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = transact(MegaSpecId::REX2, &mut db, caller, callee, Bytes::default(), U256::ZERO); - - assert!(matches!(result, Ok(ResultAndState { result: ExecutionResult::Success { .. }, .. }))); -} diff --git a/crates/mega-evm/tests/rex4/frame_state_growth.rs b/crates/mega-evm/tests/rex4/frame_state_growth.rs deleted file mode 100644 index 80ee392ef..000000000 --- a/crates/mega-evm/tests/rex4/frame_state_growth.rs +++ /dev/null @@ -1,962 +0,0 @@ -//! Tests for Rex4 per-frame state growth limits. -//! -//! Rex4 introduces per-frame state growth budgets: each inner call frame receives -//! `remaining * 98 / 100` of the parent's remaining state growth budget. -//! When a frame exceeds its budget, it reverts (not halts) with ABI-encoded -//! `MegaLimitExceeded(uint8 kind, uint64 limit)` revert data. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolError; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaSpecId, - MegaTransaction, MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, DatabaseCommit, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); -const CONTRACT3: Address = address!("0000000000000000000000000000000000100004"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified state growth limit. -/// -/// Returns the execution result and the actual state growth used. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -/// Checks if the execution result indicates that the state growth limit was exceeded (TX-level). -fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } - ) -} - -/// Creates a default transaction builder calling a contract. -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -/// Builds bytecode that writes `n` distinct storage slots (slot 0..n-1) to non-zero values. -fn write_n_slots(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - builder -} - -/// Builds bytecode that writes `n` slots and then clears `m` of them back to zero. -fn write_n_clear_m_slots(builder: BytecodeBuilder, n: u64, m: u64) -> BytecodeBuilder { - let mut b = write_n_slots(builder, n); - for i in 0..m { - b = b.sstore(U256::from(i), U256::from(0)); - } - b -} - -/// Appends a CALL to `target` with the given gas amount onto the builder. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Appends a CALL that captures the return data: calls `target`, then copies RETURNDATASIZE -/// bytes of return data to memory offset 0, then RETURNs it. -fn append_call_and_return_revert_data( - builder: BytecodeBuilder, - target: Address, - gas: u64, -) -> BytecodeBuilder { - append_call(builder, target, gas) - .append(POP) // discard CALL success flag - // Copy return data to memory - .append(RETURNDATASIZE) // size - .push_number(0_u64) // dataOffset - .push_number(0_u64) // destOffset - .append(RETURNDATACOPY) - // Return the return data - .append(RETURNDATASIZE) - .push_number(0_u64) // offset - .append(RETURN) -} - -// ============================================================================ -// 1. BASIC PER-FRAME BUDGET ALLOCATION -// ============================================================================ - -#[test] -fn test_top_level_frame_gets_full_tx_limit() { - // Top-level frame should get the full TX limit (no 98/100 reduction). - let code = write_n_slots(BytecodeBuilder::default(), 100).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 100, "Top-level frame should be able to use full TX limit"); -} - -#[test] -fn test_child_frame_budget_is_98_percent_of_parent() { - // TX limit = 100 → child budget = 100 * 98/100 = 98 - // Child creates 98 slots → should succeed - let child_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 98, "Child with budget 98 should succeed creating 98 slots"); -} - -#[test] -fn test_child_frame_exceeds_98_percent_budget() { - // TX limit = 100 → child budget = 98 - // Child creates 99 slots → exceeds per-frame budget → reverted - // Parent continues → TX succeeds - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child's frame-local revert"); - assert_eq!(state_growth, 0, "Child's growth should be discarded on frame-local revert"); -} - -#[test] -fn test_grandchild_budget_progressive_reduction() { - // TX limit = 1000 - // Child budget = 1000 * 98/100 = 980 - // Grandchild budget = 980 * 98/100 = 960 - // Grandchild creates 960 slots → succeeds - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 960).stop().build(); - - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 960, "Grandchild should succeed within 960 budget"); -} - -#[test] -fn test_grandchild_exceeds_progressive_budget() { - // TX limit = 1000, grandchild budget = 960 - // Grandchild creates 961 → exceeds → reverted - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 961).stop().build(); - - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent/child should succeed after grandchild revert"); - assert_eq!(state_growth, 0, "Grandchild's 961 slots discarded on revert"); -} - -#[test] -fn test_child_budget_accounts_for_parent_usage() { - // TX limit = 1000, parent creates 200 slots (remaining = 800) - // Child budget = 800 * 98/100 = 784 - // Child creates 784 → succeeds - let child_code = write_n_slots(BytecodeBuilder::default(), 784).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 200 + 784, "Parent (200) + child (784) = 984"); -} - -#[test] -fn test_child_exceeds_budget_after_parent_usage() { - // TX limit = 1000, parent uses 200, child budget = 784 - // Child creates 785 → exceeds → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 785).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 200, "Only parent's 200 slots should persist"); -} - -#[test] -fn test_sibling_frames_get_independent_budgets() { - // TX limit = 1000 - // Child A: creates 100 slots, succeeds → parent remaining = 900 - // Child B: budget = 900 * 98/100 = 882, creates 882 → succeeds - let child_a_code = write_n_slots(BytecodeBuilder::default(), 100).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 882).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 100 + 882, "Child A (100) + Child B (882) = 982"); -} - -#[test] -fn test_zero_remaining_budget_child_gets_zero() { - // TX limit = 100, parent creates 100 slots (remaining = 0) - // Child budget = 0 * 98/100 = 0 → child creates 1 slot → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 1).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 100); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed"); - assert_eq!(state_growth, 100, "Only parent's 100 slots should persist"); -} - -#[test] -fn test_small_remaining_budget_integer_division() { - // TX limit = 100, parent creates 99 slots (remaining = 1) - // Child budget = 1 * 98/100 = 0 (integer floor division) - // Child creates 1 slot → exceeds 0 → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 1).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 99); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed"); - assert_eq!(state_growth, 99, "Only parent's 99 slots"); -} - -// ============================================================================ -// 2. FRAME-LOCAL ABSORPTION SEMANTICS -// ============================================================================ - -#[test] -fn test_frame_local_exceed_reverts_not_halts() { - // TX limit = 100, child budget = 98, child creates 99 → reverted (absorbed) - // Overall TX result is success, NOT halt. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Should be success, not halt"); - assert!(!result.result.is_halt(), "Should NOT be halt"); -} - -#[test] -fn test_frame_local_exceed_gas_returned_to_parent() { - // Child exceeds, parent continues executing (proving gas was returned). - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - // Parent: CALL child (reverts), then write own slot to prove it continues. - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .append(POP) - .sstore(U256::from(0), U256::from(42)) // prove parent continues - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let gas_limit = 100_000_000_u64; - let tx = TxEnvBuilder::default().caller(CALLER).call(CALLEE).gas_limit(gas_limit).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Parent wrote 1 slot after child revert"); - let gas_used = result.result.gas_used(); - assert!(gas_used < gas_limit, "Gas should not be fully consumed"); -} - -#[test] -fn test_frame_local_exceed_child_state_discarded() { - // Child exceeds and reverts → child's storage writes not persisted. - // Parent's writes are persisted. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(42)); // parent write - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Only parent's slot counts"); - - // Commit and verify storage - db.commit(result.state); - - let parent_val = db.storage(CALLEE, U256::from(0)).unwrap(); - assert_eq!(parent_val, U256::from(42), "Parent storage should persist"); - - let child_val = db.storage(CONTRACT, U256::from(0)).unwrap(); - assert_eq!(child_val, U256::ZERO, "Child storage should be reverted"); -} - -#[test] -fn test_parent_continues_after_child_exceed() { - // Parent creates 2 slots, calls child (exceeds), parent creates 2 more. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(1), U256::from(2)); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000) - .append(POP) - .sstore(U256::from(2), U256::from(3)) - .sstore(U256::from(3), U256::from(4)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 4, "Parent's 4 slots should persist, child's discarded"); -} - -#[test] -fn test_top_level_exceed_is_frame_local_revert() { - // In Rex4, even the top-level frame uses per-frame enforcement. - // TX limit = 10, top-level frame creates 11 slots → per-frame exceed → Revert. - // (This differs from pre-Rex4, where this would be a TX-level Halt.) - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 10, tx).unwrap(); - - assert!( - matches!(result.result, ExecutionResult::Revert { .. }), - "Rex4 top-level exceed should be a revert, not halt" - ); -} - -#[test] -fn test_child_exceed_followed_by_sibling_success() { - // Child A exceeds (reverted), Child B succeeds within budget. - // TX limit = 100, each child budget = 98. - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 50).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 50, "Only Child B's 50 slots should persist"); -} - -// ============================================================================ -// 3. REVERT DATA ENCODING -// ============================================================================ - -#[test] -fn test_revert_data_contains_mega_limit_exceeded() { - // TX limit = 100 → child budget = 98. - // Child exceeds → parent captures revert data → TX returns it. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - // Parent: CALL child, copy return data to memory, RETURN it. - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - // Decode the revert data - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 3, "kind should be 3 (StateGrowth)"); - assert_eq!(decoded.limit, 98, "limit should be the child's per-frame budget (98)"); -} - -#[test] -fn test_revert_data_limit_value_matches_frame_budget() { - // TX limit = 1000, parent uses 200, child budget = 800 * 98/100 = 784 - // Child exceeds → revert data says limit = 784. - let child_code = write_n_slots(BytecodeBuilder::default(), 785).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call_and_return_revert_data(parent_code, CONTRACT, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 3, "kind should be 3 (StateGrowth)"); - assert_eq!(decoded.limit, 784, "limit should be 784 (800 * 98/100)"); -} - -#[test] -fn test_revert_data_empty_for_tx_level_exceed() { - // REX3 (pre-Rex4): child exceeds TX-level state growth → Halt, no revert data. - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 10, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); -} - -// ============================================================================ -// 4. NESTED FRAME SCENARIOS -// ============================================================================ - -#[test] -fn test_deeply_nested_budget_propagation() { - // TX limit = 1000 - // Level 0 (parent): budget = 1000 - // Level 1 (A): budget = 1000 * 98/100 = 980 - // Level 2 (B): budget = 980 * 98/100 = 960 - // Level 3 (C): budget = 960 * 98/100 = 940 - // C creates 940 slots → succeeds - let level3_code = write_n_slots(BytecodeBuilder::default(), 940).stop().build(); - - let level2_code = - append_call(BytecodeBuilder::default(), CONTRACT3, 80_000_000).append(POP).stop().build(); - - let level1_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 85_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, level1_code) - .account_code(CONTRACT2, level2_code) - .account_code(CONTRACT3, level3_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 940, "Level 3 should succeed with 940 slots"); -} - -#[test] -fn test_deeply_nested_exceed() { - // Same setup but C creates 941 → exceeds 940 budget → reverted at level 3. - let level3_code = write_n_slots(BytecodeBuilder::default(), 941).stop().build(); - - let level2_code = - append_call(BytecodeBuilder::default(), CONTRACT3, 80_000_000).append(POP).stop().build(); - - let level1_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 85_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, level1_code) - .account_code(CONTRACT2, level2_code) - .account_code(CONTRACT3, level3_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent chain should succeed"); - assert_eq!(state_growth, 0, "Level 3's growth discarded on revert"); -} - -#[test] -fn test_nested_child_reverts_growth_discarded() { - // Parent (3 slots) → Child (2 slots, succeeds) → Grandchild (creates 5, REVERTs normally) - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 5).revert().build(); - - let child_code = write_n_slots(BytecodeBuilder::default(), 2); - let child_code = append_call(child_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 3); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5, "Parent (3) + child (2) = 5; grandchild's 5 discarded"); -} - -#[test] -fn test_nested_exceed_absorbed_at_correct_level() { - // Parent → Child → Grandchild exceeds per-frame budget - // Grandchild reverted, Child continues (writes 2 slots), Parent succeeds. - // TX limit = 1000 - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 961).stop().build(); - - let child_code = append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000) - .append(POP) // grandchild reverted - .sstore(U256::from(0), U256::from(1)) // child continues - .sstore(U256::from(1), U256::from(2)) - .stop() - .build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Only child's 2 slots should persist"); -} - -#[test] -fn test_multiple_nested_exceeds() { - // Parent calls Child A (exceeds), then Child B (exceeds), then Child C (within budget). - // TX limit = 100, each child budget = 98. - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_c_code = write_n_slots(BytecodeBuilder::default(), 50).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 30_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 30_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT3, 30_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code) - .account_code(CONTRACT3, child_c_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 50, "Only Child C's 50 slots should persist"); -} - -// ============================================================================ -// 5. BACKWARD COMPATIBILITY -// ============================================================================ - -#[test] -fn test_rex3_no_per_frame_limits() { - // REX3 spec: no per-frame limits. Child creates 99 slots with TX limit = 100 → succeeds - // (only TX-level check: 99 <= 100). - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame limits"); - assert_eq!(state_growth, 99); -} - -#[test] -fn test_rex3_exceed_halts_not_reverts() { - // REX3 spec, TX limit = 10, creates 11 slots → Halt (TX-level exceed). - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 10, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level exceed"); - assert!(is_state_growth_limit_exceeded(&result)); -} - -// ============================================================================ -// 6. REFUND AND NET GROWTH INTERACTIONS -// ============================================================================ - -#[test] -fn test_refund_increases_remaining_budget() { - // TX limit = 100, child budget = 98 - // Child creates 90 slots, clears 50 back to zero. - // Net = 90 - 50 = 40, within budget (98) → succeeds. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 90, 50).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 40, "Net growth = 90 - 50 = 40"); -} - -#[test] -fn test_child_within_budget_after_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 40 slots, clears 10 → net = 30, within budget (49) → succeeds. - // Note: the frame-local check is eager — `used` must not exceed `limit` at any point - // during execution. Here the peak usage (40) is within the budget (49). - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 40, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 30, "Net growth = 40 - 10 = 30"); -} - -#[test] -fn test_child_exceed_with_insufficient_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 60, clears 10 → net = 50 > 49 → exceeds → reverted. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 60, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 0, "Child's growth discarded on revert"); -} - -#[test] -fn test_eager_check_reverts_despite_future_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 50 slots, then would clear 10 → final net would be 40. - // But the eager check fires when net reaches 50 (at slot 50), exceeding budget 49. - // The child reverts before reaching the clearing step. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 50, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 0, "Child's growth discarded — eager check reverted before refunds"); -} - -#[test] -fn test_rex3_eager_check_halts_despite_future_refunds() { - // REX3: TX limit = 50, no per-frame limits. - // Code creates 51 slots, then would clear 10 → final net would be 41. - // But the eager TX-level check fires when net reaches 51, exceeding limit 50. - // The TX halts before reaching the clearing step. - let code = write_n_clear_m_slots(BytecodeBuilder::default(), 51, 10).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level exceed"); - assert!(is_state_growth_limit_exceeded(&result)); -} - -#[test] -fn test_create_clear_create_within_budget() { - // TX limit = 52 → child budget = 52 * 98/100 = 50 - // Child: create 40 slots (net=40), clear 10 (net=30), create 20 more (net=50). - // Net never exceeds 50 at any point → child succeeds. - let mut b = write_n_slots(BytecodeBuilder::default(), 40); - for i in 0..10_u64 { - b = b.sstore(U256::from(i), U256::from(0)); - } - for i in 40..60_u64 { - b = b.sstore(U256::from(i), U256::from(i + 1)); - } - let child_code = b.stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 52, tx).unwrap(); - - assert!(result.result.is_success(), "Child should succeed — net never exceeds 50"); - assert_eq!(state_growth, 50, "Net growth = 40 - 10 + 20 = 50"); -} - -#[test] -fn test_rex3_create_clear_create_within_budget() { - // REX3: TX limit = 50, no per-frame limits. - // Code: create 40 slots (net=40), clear 10 (net=30), create 20 more (net=50). - // Net never exceeds 50 → TX succeeds. - let mut b = write_n_slots(BytecodeBuilder::default(), 40); - for i in 0..10_u64 { - b = b.sstore(U256::from(i), U256::from(0)); - } - for i in 40..60_u64 { - b = b.sstore(U256::from(i), U256::from(i + 1)); - } - let code = b.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "TX should succeed — net never exceeds 50"); - assert_eq!(state_growth, 50, "Net growth = 40 - 10 + 20 = 50"); -} - -#[test] -fn test_child_refund_reflected_in_sibling_budget() { - // TX limit = 100 - // Child A: creates 10 slots, clears 5 → net = 5, succeeds. - // Parent remaining after Child A = 100 - 5 = 95. - // Child B budget = 95 * 98/100 = 93. - // Child B creates 93 slots → succeeds. - // This proves Child A's refunds flow back to the parent, giving Child B a larger budget - // than if the gross usage (10) were used (which would yield 90 * 98/100 = 88). - let child_a_code = write_n_clear_m_slots(BytecodeBuilder::default(), 10, 5).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 93).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5 + 93, "Child A net (5) + Child B (93) = 98"); -} diff --git a/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs b/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs deleted file mode 100644 index a67b545bf..000000000 --- a/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs +++ /dev/null @@ -1,609 +0,0 @@ -//! Regression tests for Finding 3: SELFDESTRUCT State Growth Overcounting. -//! -//! Before the fix, `StateGrowthTracker` recorded +1 for CREATE and +1 per new storage slot, -//! but had no SELFDESTRUCT hook. When a same-TX-created contract selfdestructed (EIP-6780), -//! the committed state had neither the account nor its storage, yet the tracker still -//! reported positive growth. -//! -//! The fix adds an `after_selfdestruct` hook that records refunds for the account and its -//! new storage slots when a `CreatedLocal` account is destroyed. Gated to REX4 only. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); -const CALLEE: Address = address!("0000000000000000000000000000000000500001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000500002"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let state_growth = evm.ctx_ref().additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Builds init code bytes: `body` opcodes followed by SELFDESTRUCT to CALLER. -fn init_code_selfdestruct(body: BytecodeBuilder) -> Vec { - body.push_address(CALLER).append(SELFDESTRUCT).build_vec() -} - -/// Builds init code: N SSTOREs then SELFDESTRUCT. -fn init_code_sstore_selfdestruct(n: u64) -> Vec { - let mut builder = BytecodeBuilder::default(); - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - init_code_selfdestruct(builder) -} - -/// Builds bytecode that CREATEs a contract with the given init code bytes. -fn create_with_init(builder: BytecodeBuilder, init_code: &[u8]) -> BytecodeBuilder { - let mut b = builder; - for (i, chunk) in init_code.chunks(32).enumerate() { - let mut word = [0u8; 32]; - word[..chunk.len()].copy_from_slice(chunk); - b = b.mstore(i * 32, word); - } - b.push_number(init_code.len() as u64).push_number(0_u64).push_number(0_u64).append(CREATE) -} - -/// Builds bytecode that CREATE2s a contract with the given init code bytes and salt. -fn create2_with_init(builder: BytecodeBuilder, init_code: &[u8], salt: u64) -> BytecodeBuilder { - let mut b = builder; - for (i, chunk) in init_code.chunks(32).enumerate() { - let mut word = [0u8; 32]; - word[..chunk.len()].copy_from_slice(chunk); - b = b.mstore(i * 32, word); - } - b.push_number(salt) - .push_number(init_code.len() as u64) - .push_number(0_u64) - .push_number(0_u64) - .append(CREATE2) -} - -/// Builds bytecode for a CALL to `target` with given gas. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(target) - .push_number(gas) - .append(CALL) -} - -// ============================================================================ -// TEST 1: CREATE + SELFDESTRUCT — net growth = 0 -// ============================================================================ - -#[test] -fn test_create_selfdestruct_zero_growth() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 2: CREATE + SSTORE + SELFDESTRUCT — net growth = 0 -// ============================================================================ - -#[test] -fn test_create_sstore_selfdestruct_zero_growth() { - let init_code = init_code_sstore_selfdestruct(1); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + 1 SSTORE + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 3: CREATE + N SSTOREs + SELFDESTRUCT — all slots refunded -// ============================================================================ - -#[test] -fn test_create_multiple_sstore_selfdestruct_zero_growth() { - let init_code = init_code_sstore_selfdestruct(5); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + 5 SSTOREs + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 4: Cross-frame CREATE then SELFDESTRUCT -// ============================================================================ - -/// Child frame creates a contract (returns runtime code with SELFDESTRUCT). -/// Parent frame then calls the created contract, triggering SELFDESTRUCT. -#[test] -fn test_cross_frame_create_then_selfdestruct() { - // Runtime code: PUSH20(CALLER) SELFDESTRUCT - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: store runtime in memory, RETURN it. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CALLEE: CREATE → store address in memory → CALL it → STOP - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code) - // Stack: [created_addr]. Store it. - .push_number(0x100_u64) - .append(MSTORE) - // CALL the created contract - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) // load created_addr - .push_number(50_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Cross-frame create+selfdestruct should succeed"); - assert_eq!( - state_growth, 0, - "Cross-frame CREATE then SELFDESTRUCT should produce zero net growth" - ); -} - -// ============================================================================ -// TEST 5: Ancestor revert discards SELFDESTRUCT refund -// ============================================================================ - -/// Child frame creates a contract and successfully selfdestructs it, then returns -/// to parent. Parent then REVERTs. Both the creation growth and the refund from -/// the destruction must be discarded together. -#[test] -fn test_ancestor_revert_discards_selfdestruct_refund() { - // Runtime code for the created contract: SELFDESTRUCT to CALLER. - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: store runtime in memory, RETURN it. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CONTRACT: CREATE a child, store its address, CALL it (triggers SELFDESTRUCT), - // then REVERT the entire frame. - let contract_code = create_with_init(BytecodeBuilder::default(), &init_code) - .push_number(0x100_u64) - .append(MSTORE) // store created addr - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) // load created addr - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Now REVERT the entire frame — should discard both creation growth and refund. - .push_number(0_u64) - .push_number(0_u64) - .append(REVERT) - .build(); - - // CALLEE: CALL CONTRACT (which will revert), POP, STOP. - let callee_code = - append_call(BytecodeBuilder::default(), CONTRACT, 1_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(CONTRACT, contract_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Top-level should succeed after child revert"); - assert_eq!( - state_growth, 0, - "Ancestor revert should discard both creation growth and SELFDESTRUCT refund" - ); -} - -// ============================================================================ -// TEST 6: Pre-existing account SELFDESTRUCT — no refund -// ============================================================================ - -#[test] -fn test_pre_existing_account_selfdestruct_no_refund() { - let contract_code = - BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).stop().build(); - let callee_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(CONTRACT, contract_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Pre-existing account SELFDESTRUCT should not produce refund"); -} - -// ============================================================================ -// TEST 7: Ephemeral create-destroy loop -// ============================================================================ - -#[test] -fn test_ephemeral_create_destroy_loop() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - - let mut callee = BytecodeBuilder::default(); - for _ in 0..3 { - callee = create_with_init(callee, &init_code).append(POP); - } - let callee_code = callee.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - // Limit = 1: would fail if any net growth accumulated. - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1, tx).unwrap(); - - assert!(result.result.is_success(), "Ephemeral create-destroy loop should succeed"); - assert_eq!(state_growth, 0, "Ephemeral loop should produce zero net growth"); -} - -// ============================================================================ -// TEST 8: CREATE2 + SELFDESTRUCT — zero growth -// ============================================================================ - -#[test] -fn test_create2_selfdestruct_zero_growth() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create2_with_init(BytecodeBuilder::default(), &init_code, 42).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE2 + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 9: Pre-REX4 — overcounting preserved -// ============================================================================ - -/// On REX3, the refund hook is not active. Same-TX CREATE+SELFDESTRUCT still -/// shows +1 state growth (the old overcounting behavior preserved for replay). -#[test] -fn test_pre_rex4_selfdestruct_overcounting_preserved() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 1, - "Pre-REX4: CREATE + SELFDESTRUCT should still show +1 (overcounting preserved)" - ); -} - -// ============================================================================ -// TEST 10: SSTORE-then-clear before SELFDESTRUCT — cleared slots not counted -// ============================================================================ - -/// A same-TX-created contract writes a storage slot and then clears it (back to zero) -/// before SELFDESTRUCT. The refund logic filters on -/// `original_value().is_zero() && !present_value().is_zero()`, so cleared slots -/// must NOT be counted in the refund. Only the account itself is refunded. -#[test] -fn test_sstore_then_clear_before_selfdestruct_zero_growth() { - // Init code: SSTORE(0, 42), SSTORE(1, 99), SSTORE(0, 0), then SELFDESTRUCT. - // Slot 0 is set then cleared → present_value = 0, should not be refunded. - // Slot 1 remains non-zero → should be refunded. - // Net: CREATE +1 (account), slot 1 +1, SELFDESTRUCT refunds -1 (account) -1 (slot 1) = 0. - let init_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(42)) // set slot 0 - .sstore(U256::from(1), U256::from(99)) // set slot 1 - .sstore(U256::from(0), U256::ZERO) // clear slot 0 - .push_address(CALLER) - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 0, - "SSTORE-then-clear slot should not be counted in refund; net growth should be 0" - ); -} - -// ============================================================================ -// TEST 11: SELFDESTRUCT with mixed set-and-cleared slots -// ============================================================================ - -/// A same-TX-created contract writes 3 slots: 2 remain non-zero, 1 is cleared. -/// The refund should only count the 2 remaining slots plus the account itself. -#[test] -fn test_selfdestruct_mixed_set_and_cleared_slots() { - // Init code: SSTORE(0, 1), SSTORE(1, 2), SSTORE(2, 3), SSTORE(1, 0), SELFDESTRUCT. - // Slot 0: non-zero → refunded. - // Slot 1: set then cleared → NOT refunded. - // Slot 2: non-zero → refunded. - // Net: CREATE +1 (account), slot 0 +1, slot 1 +1 (then cleared, -1 from tracker), - // slot 2 +1, SELFDESTRUCT refunds -1 (account) -2 (slots 0 and 2) = 0. - let init_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(1), U256::from(2)) - .sstore(U256::from(2), U256::from(3)) - .sstore(U256::from(1), U256::ZERO) // clear slot 1 - .push_address(CALLER) - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 0, - "Cleared slot should not be counted in refund; net growth should be 0" - ); -} - -// ============================================================================ -// TEST 12: SELFDESTRUCT refund makes boundary difference -// ============================================================================ - -/// Set `state_growth_limit` = 2. Create a contract with 2 SSTOREs (growth = 3: -/// 1 account + 2 slots), then SELFDESTRUCT it (growth = 0 after refund -3). -/// Then write 2 new SSTOREs on the callee (growth = 2). Without refunds, -/// the total growth would be 5 (exceeding limit=2). With refunds, the -/// SELFDESTRUCT clears the first 3, leaving only the callee's 2 SSTOREs. -#[test] -fn test_selfdestruct_refund_enables_reuse_at_boundary() { - let init_code_sd = init_code_sstore_selfdestruct(2); - - // CALLEE: CREATE (2 SSTOREs + SELFDESTRUCT), POP, then write 2 SSTOREs on callee itself. - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code_sd) - .append(POP) - .sstore(U256::from(100), U256::from(1)) - .sstore(U256::from(101), U256::from(2)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 2, tx).unwrap(); - - assert!( - result.result.is_success(), - "SELFDESTRUCT refunds should free up budget for callee's SSTOREs" - ); - assert_eq!( - state_growth, 2, - "Net growth should be 2 (callee's 2 new SSTOREs; created contract refunded)" - ); -} - -// ============================================================================ -// TEST 13: SELFDESTRUCT to self -// ============================================================================ - -/// A same-TX-created contract selfdestructs to its own address. The refund should -/// still work correctly since the `address` parameter (the selfdestructing account) -/// is the one inspected, regardless of `target`. -#[test] -fn test_selfdestruct_to_self_zero_growth() { - // Init code: PUSH20(self_address)... but we can't know the address at build time. - // Instead, use ADDRESS opcode to push the current contract's address, then SELFDESTRUCT. - let init_code = BytecodeBuilder::default() - .append(ADDRESS) // push own address - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "SELFDESTRUCT to self should produce zero net growth"); -} - -// ============================================================================ -// TEST 14: Repeated SELFDESTRUCT must not double-refund -// ============================================================================ - -/// A same-TX-created contract is selfdestructed twice in the same transaction. -/// The second SELFDESTRUCT must not produce an additional refund. -/// After both destructions, one new SSTORE should bring net growth to 1. -#[test] -fn test_repeated_selfdestruct_no_double_refund() { - // Runtime code: SELFDESTRUCT to CALLER. - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: return runtime. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CALLEE: CREATE contract, store addr, CALL it twice (two SELFDESTRUCTs), - // then write one new SSTORE to produce +1 growth. - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code) - // Store created address - .push_number(0x100_u64) - .append(MSTORE) - // First CALL: triggers SELFDESTRUCT (first effective destruction) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Second CALL: triggers SELFDESTRUCT again (previously_destroyed = true) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Write one new storage slot to produce +1 net growth - .sstore(U256::from(999), U256::from(1)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - // CREATE +1, first SELFDESTRUCT -1, second SELFDESTRUCT should NOT -1 again, - // new SSTORE +1. Net = 1. - assert_eq!( - state_growth, 1, - "Repeated SELFDESTRUCT must not double-refund. Expected net growth = 1 \ - (create +1, first destroy -1, SSTORE +1), got {state_growth}" - ); -} diff --git a/crates/mega-evm/tests/rex5/create_atomicity.rs b/crates/mega-evm/tests/rex5/create_atomicity.rs deleted file mode 100644 index 2ddb94c34..000000000 --- a/crates/mega-evm/tests/rex5/create_atomicity.rs +++ /dev/null @@ -1,281 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! Tests for REX5 CREATE atomicity. -//! -//! Under `MegaSpecId::REX5`, a frame-local compute-gas exceed caused by -//! the canonical code-deposit charge must take effect before -//! `process_next_action` commits the CREATE checkpoint. The result is -//! `Revert` and no code is deployed. Pre-REX5 keeps its existing -//! split-outcome behavior (`Revert` result with committed code). - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, EthHaltReason, EvmTxRuntimeLimits, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, OpHaltReason, TestExternalEnvs, -}; -use revm::{ - context::{ - result::{ExecutionResult, Output, ResultAndState}, - TxEnv, - }, - state::EvmState, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); - -/// Build init code that returns `code_len` bytes of zeros from memory[0..code_len]. -/// -/// Layout (PUSH3 used so we can pick large code_len up to ~16M): -/// PUSH3 // 4 bytes -/// PUSH1 0 // 2 bytes -/// RETURN // 1 byte -/// Total: 7 bytes. -/// -/// Compute gas inside the constructor: 3 (PUSH3) + 3 (PUSH1) + 0 (RETURN) -/// + memory expansion gas for `code_len`. -fn return_zeros_initcode(code_len: u32) -> Bytes { - let bytes = code_len.to_be_bytes(); - let mut code = Vec::with_capacity(7); - code.push(0x62); // PUSH3 - code.extend_from_slice(&bytes[1..]); // 3-byte big-endian length - code.push(0x60); // PUSH1 - code.push(0x00); - code.push(0xf3); // RETURN - Bytes::from(code) -} - -/// Build init code that returns `code_len` bytes starting with 0xEF (EIP-3541 -/// prohibited prefix) — the rest is whatever was in memory (zeros). Used to -/// pin the EIP-3541 branch of the helper predicate. -fn return_ef_prefix_initcode() -> Bytes { - // Constructor: - // PUSH1 0xEF // value - // PUSH1 0 // memory offset - // MSTORE8 // store 1 byte at offset 0 - // PUSH1 0x10 // length = 16 bytes - // PUSH1 0 // memory offset - // RETURN - Bytes::from(vec![0x60, 0xef, 0x60, 0x00, 0x53, 0x60, 0x10, 0x60, 0x00, 0xf3]) -} - -fn run_create( - spec: MegaSpecId, - tx_compute_gas_limit: u64, - init_code: Bytes, - inspector: bool, -) -> ResultAndState { - run_create_with_gas_limit(spec, tx_compute_gas_limit, 100_000_000, init_code, inspector) -} - -fn run_create_with_gas_limit( - spec: MegaSpecId, - tx_compute_gas_limit: u64, - tx_gas_limit: u64, - init_code: Bytes, - inspector: bool, -) -> ResultAndState { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(tx_compute_gas_limit); - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs(TestExternalEnvs::::new().into()) - .with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: tx_gas_limit, - gas_price: 0, - data: init_code, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - if inspector { - // Default no-op inspector — forces inspect_frame_run path. - let mut evm = MegaEvm::new(context).with_inspector(revm::inspector::NoOpInspector {}); - alloy_evm::Evm::transact_raw(&mut evm, tx) - .expect("transact (inspector) should not surface EVMError") - } else { - let mut evm = MegaEvm::new(context); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError") - } -} - -/// Returns true if the post-state delta contains a non-empty code account -/// at the deployed address. Looking at `state.code` is more reliable than -/// scanning the journal because it reflects what `transact_raw` reports as -/// the committed state delta. -fn deployed_account_has_code(state: &EvmState, deployed_address: Address) -> bool { - state - .get(&deployed_address) - .map(|acc| { - acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false) || - acc.info.code_hash != revm::primitives::KECCAK_EMPTY - }) - .unwrap_or(false) -} - -/// Constructor returns 8000 bytes; canonical `code_len * 200` = 1.6M. -const CODE_LEN: u32 = 8_000; - -/// Per-frame compute budget calibrated so only the code-deposit charge -/// can overshoot: constructor + intrinsic stay well below 1M. -const TIGHT_COMPUTE_BUDGET: u64 = 1_000_000; - -/// Per-frame compute budget large enough to cover code-deposit too. -const GENEROUS_COMPUTE_BUDGET: u64 = 4_000_000; - -/// Under REX5, a tight compute budget that overshoots only on the -/// code-deposit charge produces a `Revert` result with no committed code. -#[test] -fn test_create_compute_gas_exceed_during_codedeposit_does_not_split_outcome() { - let res = - run_create(MegaSpecId::REX5, TIGHT_COMPUTE_BUDGET, return_zeros_initcode(CODE_LEN), false); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!( - !deployed_account_has_code(&res.state, deployed_address), - "deployed account at {deployed_address} must not have code; state entry: {:?}", - res.state.get(&deployed_address) - ); -} - -/// Same fixture under REX4: pre-REX5 keeps its existing split-outcome -/// behavior (`Revert` result with code already committed by -/// `return_create`). -#[test] -fn test_pre_rex5_preserves_split_outcome() { - let res = - run_create(MegaSpecId::REX4, TIGHT_COMPUTE_BUDGET, return_zeros_initcode(CODE_LEN), false); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!( - deployed_account_has_code(&res.state, deployed_address), - "REX4 split outcome: deployed account at {deployed_address} must have code; \ - state entry: {:?}", - res.state.get(&deployed_address) - ); -} - -/// Generous compute budget allows CREATE to commit normally. -#[test] -fn test_create_compute_gas_within_budget_still_commits_normally() { - let res = run_create( - MegaSpecId::REX5, - GENEROUS_COMPUTE_BUDGET, - return_zeros_initcode(CODE_LEN), - false, - ); - - assert!(res.result.is_success(), "got: {:?}", res.result); - - let deployed_address = match &res.result { - ExecutionResult::Success { output: Output::Create(_, Some(addr)), .. } => *addr, - other => panic!("Expected Create output with address, got: {other:?}"), - }; - assert_eq!(deployed_address, CALLER.create(0)); - assert!(deployed_account_has_code(&res.state, deployed_address)); -} - -/// `inspect_frame_run` shares the same hooks as `frame_run`; the REX5 -/// behavior must apply identically on the inspector path. -#[test] -fn test_inspect_frame_run_path_matches_frame_run() { - let res = run_create( - MegaSpecId::REX5, - TIGHT_COMPUTE_BUDGET, - return_zeros_initcode(CODE_LEN), - true, // forces inspect_frame_run path - ); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// A CREATE whose constructor returns code starting with 0xEF takes -/// `return_create`'s EIP-3541 revert path; the pre-charge must not fire, -/// so a generous compute budget produces a clean reject. -#[test] -fn test_create_with_eip3541_prefix_skips_pre_charge() { - let res = - run_create(MegaSpecId::REX5, GENEROUS_COMPUTE_BUDGET, return_ef_prefix_initcode(), false); - - // op-revm classifies the EIP-3541 reject as either Halt or Revert - // depending on wrapping; what matters is no success and no code. - assert!( - matches!(&res.result, ExecutionResult::Halt { .. } | ExecutionResult::Revert { .. }), - "got: {:?}", - res.result - ); - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// `gas.remaining() < code_deposit_gas` at RETURN must skip the REX5 pre-charge: -/// revm's `return_create` reverts on its own with `OutOfGas`. A spurious -/// pre-charge would surface as `ComputeGasLimitExceeded` instead, so the halt -/// reason discriminates the two paths. -#[test] -fn test_create_insufficient_gas_for_code_deposit_skips_pre_charge() { - // tx gas (1_650_000) just below code_deposit_gas (CODE_LEN * 200 = 1_600_000) - // plus constructor cost, so revm's record_cost on the deposit fails. - let res = run_create_with_gas_limit( - MegaSpecId::REX5, - TIGHT_COMPUTE_BUDGET, - 1_650_000, - return_zeros_initcode(CODE_LEN), - false, - ); - - let reason = match &res.result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - other => panic!("Expected Halt, got: {other:?}"), - }; - assert!( - matches!(reason, MegaHaltReason::Base(OpHaltReason::Base(EthHaltReason::OutOfGas(_)))), - "got: {reason:?}", - ); - - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// A CREATE whose constructor returns more than `max_code_size` bytes -/// takes `return_create`'s EIP-170 revert path; the pre-charge must not -/// fire, so a generous compute budget produces a clean reject. -#[test] -fn test_create_with_oversized_code_skips_pre_charge() { - // Larger than both EIP-170 (0x6000) and EIP-7907 (0xc000). - const OVERSIZE_CODE_LEN: u32 = 64_000; - let res = run_create( - MegaSpecId::REX5, - GENEROUS_COMPUTE_BUDGET, - return_zeros_initcode(OVERSIZE_CODE_LEN), - false, - ); - - assert!(!res.result.is_success(), "got: {:?}", res.result); - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} diff --git a/crates/mega-evm/tests/rex6/metering_order_parity.rs b/crates/mega-evm/tests/rex6/metering_order_parity.rs deleted file mode 100644 index 70c1c01d0..000000000 --- a/crates/mega-evm/tests/rex6/metering_order_parity.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! REX6 unifies the per-opcode gas-metering order: compute gas is recorded exactly once, after the -//! opcode body has fully executed, with the storage gas charged in the opcode excluded. -//! -//! For every storage-affecting opcode **except CREATE2**, the pre-REX6 layering already followed -//! this order (nothing consumes EVM gas before the storage-gas charge), so the REX6 canonical path -//! must be byte-for-byte behavior-preserving relative to REX5: identical execution result, -//! compute-gas tracker reading, and `gas_used`. -//! -//! These tests pin that equivalence. CREATE2's intended divergence on the failure path is covered -//! in [`super::create2_metering_order`]. - -use crate::common::{transact, transact_default, CALLER, CONTRACT, EMPTY_TARGET}; -use alloy_primitives::{Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaSpecId, -}; -use revm::bytecode::opcode::{ - CALL, CALLCODE, CREATE, DELEGATECALL, LOG1, SELFDESTRUCT, SSTORE, STATICCALL, STOP, -}; - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// Runs `build_db()` under REX5 and REX6 (identical runtime limits) and asserts the execution -/// result, compute-gas reading, and `gas_used` are identical — i.e. the REX6 canonical metering -/// order reproduces the frozen REX5 behavior exactly. -fn assert_rex5_rex6_parity( - label: &str, - expect_success: bool, - build_db: impl Fn() -> MemoryDatabase, -) { - let r5 = transact_default(MegaSpecId::REX5, build_db()); - let r6 = transact_default(MegaSpecId::REX6, build_db()); - - assert_eq!( - r5.is_success(), - expect_success, - "{label}: REX5 success expectation mismatch; got {:?}", - r5.result - ); - assert_eq!( - r5.is_success(), - r6.is_success(), - "{label}: success mismatch REX5={:?} REX6={:?}", - r5.result, - r6.result - ); - assert_eq!( - r5.compute_gas, r6.compute_gas, - "{label}: compute_gas must be identical (behavior-preserving); REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - assert_eq!( - r5.gas_used, r6.gas_used, - "{label}: gas_used must be identical (behavior-preserving); REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - -fn base_db(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) -} - -#[test] -fn test_sstore_metering_parity_rex5_rex6() { - // SSTORE zero -> non-zero triggers the dynamic storage-gas path in `storage_gas_ext::sstore`. - let code = BytecodeBuilder::default().sstore(U256::from(7), U256::from(99)).stop().build(); - assert_rex5_rex6_parity("SSTORE", true, || base_db(code.clone())); -} - -#[test] -fn test_log_metering_parity_rex5_rex6() { - // LOG1 with 32 bytes of data exercises the topic + data storage-gas charge in - // `storage_gas_ext::log`. Stack for LOG1 pops offset, len, topic (offset on top). - let code = BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .push_number(0xabcu64) // topic0 - .push_number(32u64) // len - .push_number(0u64) // offset - .append(LOG1) - .stop() - .build(); - assert_rex5_rex6_parity("LOG1", true, || base_db(code.clone())); -} - -#[test] -fn test_call_value_transfer_metering_parity_rex5_rex6() { - // CALL transferring value to an empty account exercises the new-account storage-gas path in - // `storage_gas_ext::call`. Stack pops gas, to, value, aoff, asz, roff, rsz (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(CALL) - .stop() - .build(); - assert_rex5_rex6_parity("CALL", true, || base_db(code.clone())); -} - -#[test] -fn test_create_metering_parity_rex5_rex6() { - // CREATE (non-CREATE2) with empty initcode. Stack pops value, offset, length (value on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .stop() - .build(); - assert_rex5_rex6_parity("CREATE", true, || base_db(code.clone())); -} - -#[test] -fn test_selfdestruct_new_beneficiary_metering_parity_rex5_rex6() { - // SELFDESTRUCT to an empty, non-beneficiary target while the contract holds balance exercises - // the new-account storage-gas path in `storage_gas_ext::selfdestruct` (REX5+). - let code = BytecodeBuilder::default().push_address(EMPTY_TARGET).append(SELFDESTRUCT).build(); - assert_rex5_rex6_parity("SELFDESTRUCT", true, || base_db(code.clone())); -} - -#[test] -fn test_delegatecall_metering_parity_rex5_rex6() { - // DELEGATECALL has no value operand, so `storage_charged` is always 0; this pins the - // `storage_gas_ext::delegate_call` REX6 path. Stack pops gas, to, argsOffset, argsSize, - // retOffset, retSize (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(DELEGATECALL) - .stop() - .build(); - assert_rex5_rex6_parity("DELEGATECALL", true, || base_db(code.clone())); -} - -#[test] -fn test_staticcall_metering_parity_rex5_rex6() { - // STATICCALL has no value operand either; same stack layout as DELEGATECALL. - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(STATICCALL) - .stop() - .build(); - assert_rex5_rex6_parity("STATICCALL", true, || base_db(code.clone())); -} - -/// Pushes the same operands as a `SSTORE(slot=7, value=99)` but stops before the SSTORE byte, so -/// the run measures the compute-gas accumulated up to the opcode under test (TX intrinsic + the -/// two PUSH instructions). This is the same baseline-measurement trick used by -/// `super::create2_metering_order::build_pushes_only_contract`. -fn build_sstore_pushes_only_contract() -> Bytes { - BytecodeBuilder::default() - .push_u256(U256::from(99u64)) // value - .push_u256(U256::from(7u64)) // slot - .append(STOP) - .build() -} - -fn build_sstore_contract() -> Bytes { - BytecodeBuilder::default() - .push_u256(U256::from(99u64)) // value - .push_u256(U256::from(7u64)) // slot - .append(SSTORE) - .append(STOP) - .build() -} - -#[test] -fn test_sstore_compute_limit_halt_parity_rex5_rex6() { - // Place the compute-gas limit just past the pre-SSTORE usage so the limit trips after the - // storage-gas charge (storage gas doesn't bill compute) and after the inner SSTORE body has - // run — i.e. at the post-body `record_storage_compute_gas!` call. This is the consensus- - // critical halt boundary the REX6 metering-order claim rests on: REX5 ↔ REX6 must be - // byte-identical here, since nothing between `gas_before` and the storage charge consumes - // EVM gas on the non-CREATE2 opcodes. - let usage_before_sstore = - transact_default(MegaSpecId::REX6, base_db(build_sstore_pushes_only_contract())) - .compute_gas; - let compute_limit = usage_before_sstore + 100; - - let limits = - |spec| EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - - let r5 = transact(MegaSpecId::REX5, base_db(build_sstore_contract()), limits(MegaSpecId::REX5)); - let r6 = transact(MegaSpecId::REX6, base_db(build_sstore_contract()), limits(MegaSpecId::REX6)); - - assert!(!r5.is_success(), "REX5 must halt under the tight compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt under the tight compute limit; got {:?}", r6.result); - assert_eq!( - format!("{:?}", r5.result), - format!("{:?}", r6.result), - "SSTORE halt: result must be identical; REX5={:?} REX6={:?}", - r5.result, - r6.result - ); - assert_eq!( - r5.compute_gas, r6.compute_gas, - "SSTORE halt: compute_gas must be identical; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - assert_eq!( - r5.gas_used, r6.gas_used, - "SSTORE halt: gas_used must be identical; REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - -#[test] -fn test_callcode_value_transfer_metering_parity_rex5_rex6() { - // CALLCODE with value transfer goes through the same `new_account_storage_gas` charge path as - // CALL (via `storage_gas_ext::call_code`). Stack pops gas, to, value, aoff, asz, roff, rsz - // (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(CALLCODE) - .stop() - .build(); - assert_rex5_rex6_parity("CALLCODE", true, || base_db(code.clone())); -} From a812ca7d3b421ae9b4f27cd93848219642977230 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:28:17 +0800 Subject: [PATCH 003/201] build!: move to the revm and op-revm forks and take out the legacy core revm 27.1 -> 40.0.3 with all twelve revm crates patched to the megaeth fork (rev 43485bf7), op-revm 8.1 -> 20.0.0 from the OP monorepo revision the node locks (f67d87cd) patched to the megaeth op-revm fork (rev 817e36e9), alloy-evm 0.15 -> 0.36, alloy-op-evm 0.15 -> 0.32, revm-inspectors 0.27 -> 0.40, alloy 1.x -> 2.x, alloy-primitives 1.6. The workspace becomes 2.0.0-alpha.1 (path-dependency versions in lockstep) and MSRV 1.94 (op-revm). The legacy core cannot build on revm 40, so its sources leave in the same commit: src/, the two examples and every bench target (the test gates rebuild them; the bench inputs under benches/data and benches/fixtures stay). The 181 inline unit tests the test inventory keeps move to tests/_pending/src/; the 107 it marks legacy-only or retired go with the code. The 11 mutants suppressions on limit/* go with limit/. --- Cargo.lock | 1927 ++----------- Cargo.toml | 84 +- crates/mega-evm/Cargo.toml | 56 +- crates/mega-evm/benches/attack_replay.rs | 436 --- crates/mega-evm/benches/block_bench.rs | 484 ---- crates/mega-evm/benches/common/mod.rs | 156 -- crates/mega-evm/benches/common/subject.rs | 443 --- crates/mega-evm/benches/common/workload.rs | 116 - crates/mega-evm/benches/comp_cost.rs | 1130 -------- crates/mega-evm/benches/ctt.rs | 170 -- crates/mega-evm/benches/enriched_tx.rs | 103 - crates/mega-evm/benches/mega_bench.rs | 971 ------- crates/mega-evm/benches/revm_bench.rs | 279 -- crates/mega-evm/benches/transact.rs | 96 - .../examples/beneficiary_access_tracking.rs | 205 -- .../mega-evm/examples/block_env_tracking.rs | 184 -- crates/mega-evm/src/AGENTS.md | 33 - crates/mega-evm/src/access/AGENTS.md | 32 - crates/mega-evm/src/access/mod.rs | 12 - crates/mega-evm/src/access/tracker.rs | 305 --- crates/mega-evm/src/access/volatile.rs | 186 -- crates/mega-evm/src/block/AGENTS.md | 70 - crates/mega-evm/src/block/chain.rs | 256 -- crates/mega-evm/src/block/eips.rs | 272 -- crates/mega-evm/src/block/executor.rs | 751 ------ crates/mega-evm/src/block/factory.rs | 205 -- crates/mega-evm/src/block/hardfork.rs | 1167 -------- crates/mega-evm/src/block/helpers.rs | 390 --- crates/mega-evm/src/block/limit.rs | 1147 -------- crates/mega-evm/src/block/mod.rs | 109 - crates/mega-evm/src/block/result.rs | 240 -- crates/mega-evm/src/constants.rs | 210 -- crates/mega-evm/src/evm/AGENTS.md | 30 - crates/mega-evm/src/evm/context.rs | 882 ------ crates/mega-evm/src/evm/execution.rs | 1591 ----------- crates/mega-evm/src/evm/factory.rs | 218 -- crates/mega-evm/src/evm/host.rs | 1282 --------- crates/mega-evm/src/evm/instructions.rs | 2385 ----------------- crates/mega-evm/src/evm/interfaces.rs | 236 -- crates/mega-evm/src/evm/limit.rs | 185 -- crates/mega-evm/src/evm/mod.rs | 622 ----- crates/mega-evm/src/evm/precompiles.rs | 758 ------ crates/mega-evm/src/evm/result.rs | 195 -- crates/mega-evm/src/evm/spec.rs | 506 ---- crates/mega-evm/src/evm/state.rs | 396 --- crates/mega-evm/src/external/AGENTS.md | 32 - crates/mega-evm/src/external/factory.rs | 41 - crates/mega-evm/src/external/gas.rs | 300 --- crates/mega-evm/src/external/hasher/NOTICE.md | 27 - .../mega-evm/src/external/hasher/convert.rs | 90 - .../mega-evm/src/external/hasher/fallback.rs | 144 - crates/mega-evm/src/external/mod.rs | 114 - crates/mega-evm/src/external/oracle.rs | 62 - crates/mega-evm/src/external/salt.rs | 111 - crates/mega-evm/src/external/test_utils.rs | 308 --- crates/mega-evm/src/lib.rs | 66 +- crates/mega-evm/src/limit/AGENTS.md | 36 - crates/mega-evm/src/limit/compute_gas.rs | 270 -- crates/mega-evm/src/limit/data_size.rs | 406 --- crates/mega-evm/src/limit/frame_limit.rs | 648 ----- crates/mega-evm/src/limit/kv_update.rs | 298 -- crates/mega-evm/src/limit/limit.rs | 1153 -------- crates/mega-evm/src/limit/mod.rs | 208 -- crates/mega-evm/src/limit/state_growth.rs | 380 --- .../src/limit/storage_call_stipend.rs | 215 -- crates/mega-evm/src/sandbox/error.rs | 335 --- crates/mega-evm/src/sandbox/execution.rs | 1616 ----------- crates/mega-evm/src/sandbox/mod.rs | 105 - crates/mega-evm/src/sandbox/state.rs | 516 ---- crates/mega-evm/src/sandbox/state_merge.rs | 910 ------- crates/mega-evm/src/system/AGENTS.md | 57 - crates/mega-evm/src/system/deploy.rs | 386 --- crates/mega-evm/src/system/intercept.rs | 619 ----- crates/mega-evm/src/system/keyless_deploy.rs | 141 - crates/mega-evm/src/system/mod.rs | 40 - crates/mega-evm/src/system/oracle.rs | 605 ----- .../mega-evm/src/system/sequencer_registry.rs | 1494 ----------- crates/mega-evm/src/system/tx.rs | 213 -- crates/mega-evm/src/test_utils/bytes.rs | 10 - crates/mega-evm/src/test_utils/database.rs | 195 -- crates/mega-evm/src/test_utils/evm.rs | 45 - crates/mega-evm/src/test_utils/inspectors.rs | 343 --- crates/mega-evm/src/test_utils/mod.rs | 13 - crates/mega-evm/src/test_utils/opcode_gen.rs | 213 -- crates/mega-evm/src/types.rs | 13 - crates/mega-evm/tests/_pending/README.md | 64 +- .../tests/_pending/src/access/volatile.rs | 85 + .../tests/_pending/src/block/chain.rs | 100 + .../mega-evm/tests/_pending/src/block/eips.rs | 92 + .../tests/_pending/src/block/hardfork.rs | 233 ++ .../tests/_pending/src/block/helpers.rs | 205 ++ .../tests/_pending/src/block/limit.rs | 97 + .../tests/_pending/src/block/result.rs | 65 + .../tests/_pending/src/evm/context.rs | 111 + .../tests/_pending/src/evm/factory.rs | 41 + .../mega-evm/tests/_pending/src/evm/host.rs | 424 +++ crates/mega-evm/tests/_pending/src/evm/mod.rs | 233 ++ .../tests/_pending/src/evm/precompiles.rs | 211 ++ .../mega-evm/tests/_pending/src/evm/result.rs | 57 + .../mega-evm/tests/_pending/src/evm/spec.rs | 63 + .../mega-evm/tests/_pending/src/evm/state.rs | 43 + .../tests/_pending/src/external/gas.rs | 120 + .../_pending}/src/external/hasher/mod.rs | 72 +- .../tests/_pending/src/external/mod.rs | 21 + .../tests/_pending/src/external/test_utils.rs | 22 + .../tests/_pending/src/limit/compute_gas.rs | 28 + .../tests/_pending/src/limit/data_size.rs | 26 + .../tests/_pending/src/limit/frame_limit.rs | 127 + .../tests/_pending/src/limit/kv_update.rs | 19 + .../tests/_pending/src/limit/limit.rs | 98 + .../mega-evm/tests/_pending/src/limit/mod.rs | 54 + .../tests/_pending/src/sandbox/error.rs | 50 + .../tests/_pending/src/sandbox/execution.rs | 159 ++ .../{ => tests/_pending}/src/sandbox/tx.rs | 115 +- .../_pending}/src/system/control.rs | 85 +- .../tests/_pending/src/system/deploy.rs | 150 ++ .../tests/_pending/src/system/intercept.rs | 114 + .../_pending/src/system/keyless_deploy.rs | 64 + .../_pending}/src/system/limit_control.rs | 60 +- .../tests/_pending/src/system/oracle.rs | 257 ++ .../_pending/src/system/sequencer_registry.rs | 778 ++++++ .../mega-evm/tests/_pending/src/system/tx.rs | 79 + .../_pending/src/test_utils/opcode_gen.rs | 57 + mutants/suppressions.toml | 139 +- 124 files changed, 4653 insertions(+), 34454 deletions(-) delete mode 100644 crates/mega-evm/benches/attack_replay.rs delete mode 100644 crates/mega-evm/benches/block_bench.rs delete mode 100644 crates/mega-evm/benches/common/mod.rs delete mode 100644 crates/mega-evm/benches/common/subject.rs delete mode 100644 crates/mega-evm/benches/common/workload.rs delete mode 100644 crates/mega-evm/benches/comp_cost.rs delete mode 100644 crates/mega-evm/benches/ctt.rs delete mode 100644 crates/mega-evm/benches/enriched_tx.rs delete mode 100644 crates/mega-evm/benches/mega_bench.rs delete mode 100644 crates/mega-evm/benches/revm_bench.rs delete mode 100644 crates/mega-evm/benches/transact.rs delete mode 100644 crates/mega-evm/examples/beneficiary_access_tracking.rs delete mode 100644 crates/mega-evm/examples/block_env_tracking.rs delete mode 100644 crates/mega-evm/src/AGENTS.md delete mode 100644 crates/mega-evm/src/access/AGENTS.md delete mode 100644 crates/mega-evm/src/access/mod.rs delete mode 100644 crates/mega-evm/src/access/tracker.rs delete mode 100644 crates/mega-evm/src/access/volatile.rs delete mode 100644 crates/mega-evm/src/block/AGENTS.md delete mode 100644 crates/mega-evm/src/block/chain.rs delete mode 100644 crates/mega-evm/src/block/eips.rs delete mode 100644 crates/mega-evm/src/block/executor.rs delete mode 100644 crates/mega-evm/src/block/factory.rs delete mode 100644 crates/mega-evm/src/block/hardfork.rs delete mode 100644 crates/mega-evm/src/block/helpers.rs delete mode 100644 crates/mega-evm/src/block/limit.rs delete mode 100644 crates/mega-evm/src/block/mod.rs delete mode 100644 crates/mega-evm/src/block/result.rs delete mode 100644 crates/mega-evm/src/constants.rs delete mode 100644 crates/mega-evm/src/evm/AGENTS.md delete mode 100644 crates/mega-evm/src/evm/context.rs delete mode 100644 crates/mega-evm/src/evm/execution.rs delete mode 100644 crates/mega-evm/src/evm/factory.rs delete mode 100644 crates/mega-evm/src/evm/host.rs delete mode 100644 crates/mega-evm/src/evm/instructions.rs delete mode 100644 crates/mega-evm/src/evm/interfaces.rs delete mode 100644 crates/mega-evm/src/evm/limit.rs delete mode 100644 crates/mega-evm/src/evm/mod.rs delete mode 100644 crates/mega-evm/src/evm/precompiles.rs delete mode 100644 crates/mega-evm/src/evm/result.rs delete mode 100644 crates/mega-evm/src/evm/spec.rs delete mode 100644 crates/mega-evm/src/evm/state.rs delete mode 100644 crates/mega-evm/src/external/AGENTS.md delete mode 100644 crates/mega-evm/src/external/factory.rs delete mode 100644 crates/mega-evm/src/external/gas.rs delete mode 100644 crates/mega-evm/src/external/hasher/NOTICE.md delete mode 100644 crates/mega-evm/src/external/hasher/convert.rs delete mode 100644 crates/mega-evm/src/external/hasher/fallback.rs delete mode 100644 crates/mega-evm/src/external/mod.rs delete mode 100644 crates/mega-evm/src/external/oracle.rs delete mode 100644 crates/mega-evm/src/external/salt.rs delete mode 100644 crates/mega-evm/src/external/test_utils.rs delete mode 100644 crates/mega-evm/src/limit/AGENTS.md delete mode 100644 crates/mega-evm/src/limit/compute_gas.rs delete mode 100644 crates/mega-evm/src/limit/data_size.rs delete mode 100644 crates/mega-evm/src/limit/frame_limit.rs delete mode 100644 crates/mega-evm/src/limit/kv_update.rs delete mode 100644 crates/mega-evm/src/limit/limit.rs delete mode 100644 crates/mega-evm/src/limit/mod.rs delete mode 100644 crates/mega-evm/src/limit/state_growth.rs delete mode 100644 crates/mega-evm/src/limit/storage_call_stipend.rs delete mode 100644 crates/mega-evm/src/sandbox/error.rs delete mode 100644 crates/mega-evm/src/sandbox/execution.rs delete mode 100644 crates/mega-evm/src/sandbox/mod.rs delete mode 100644 crates/mega-evm/src/sandbox/state.rs delete mode 100644 crates/mega-evm/src/sandbox/state_merge.rs delete mode 100644 crates/mega-evm/src/system/AGENTS.md delete mode 100644 crates/mega-evm/src/system/deploy.rs delete mode 100644 crates/mega-evm/src/system/intercept.rs delete mode 100644 crates/mega-evm/src/system/keyless_deploy.rs delete mode 100644 crates/mega-evm/src/system/mod.rs delete mode 100644 crates/mega-evm/src/system/oracle.rs delete mode 100644 crates/mega-evm/src/system/sequencer_registry.rs delete mode 100644 crates/mega-evm/src/system/tx.rs delete mode 100644 crates/mega-evm/src/test_utils/bytes.rs delete mode 100644 crates/mega-evm/src/test_utils/database.rs delete mode 100644 crates/mega-evm/src/test_utils/evm.rs delete mode 100644 crates/mega-evm/src/test_utils/inspectors.rs delete mode 100644 crates/mega-evm/src/test_utils/mod.rs delete mode 100644 crates/mega-evm/src/test_utils/opcode_gen.rs delete mode 100644 crates/mega-evm/src/types.rs create mode 100644 crates/mega-evm/tests/_pending/src/access/volatile.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/chain.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/eips.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/hardfork.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/helpers.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/limit.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/result.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/context.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/factory.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/host.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/mod.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/precompiles.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/result.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/spec.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/state.rs create mode 100644 crates/mega-evm/tests/_pending/src/external/gas.rs rename crates/mega-evm/{ => tests/_pending}/src/external/hasher/mod.rs (57%) create mode 100644 crates/mega-evm/tests/_pending/src/external/mod.rs create mode 100644 crates/mega-evm/tests/_pending/src/external/test_utils.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/compute_gas.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/data_size.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/frame_limit.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/kv_update.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/limit.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/mod.rs create mode 100644 crates/mega-evm/tests/_pending/src/sandbox/error.rs create mode 100644 crates/mega-evm/tests/_pending/src/sandbox/execution.rs rename crates/mega-evm/{ => tests/_pending}/src/sandbox/tx.rs (75%) rename crates/mega-evm/{ => tests/_pending}/src/system/control.rs (60%) create mode 100644 crates/mega-evm/tests/_pending/src/system/deploy.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/intercept.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs rename crates/mega-evm/{ => tests/_pending}/src/system/limit_control.rs (63%) create mode 100644 crates/mega-evm/tests/_pending/src/system/oracle.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/tx.rs create mode 100644 crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs diff --git a/Cargo.lock b/Cargo.lock index bb39fcd76..cd249dfae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,17 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addchain" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2e69442aa5628ea6951fa33e24efe8313f4321a91bd729fc2f75bdfc858570" -dependencies = [ - "num-bigint 0.3.3", - "num-integer", - "num-traits", -] - [[package]] name = "ahash" version = "0.8.12" @@ -53,9 +42,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90d103d3e440ad6f703dd71a5b58a6abd24834563bde8a5fabe706e00242f810" +checksum = "0b836b372d3b742b7c083d2617d6e68563cd5dadbd8752c461a935a756551e69" dependencies = [ "alloy-eips", "alloy-primitives", @@ -64,6 +53,7 @@ dependencies = [ "alloy-trie", "alloy-tx-macros", "auto_impl", + "borsh", "c-kzg", "derive_more", "either", @@ -79,9 +69,9 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48ead76c8c84ab3a50c31c56bc2c748c2d64357ad2131c32f9b10ab790a25e1a" +checksum = "b1befb37485ea71e8599e32ffd76c98af7c3720a34741d30abd87f41c3148407" dependencies = [ "alloy-consensus", "alloy-eips", @@ -132,9 +122,9 @@ dependencies = [ [[package]] name = "alloy-eip7928" -version = "0.3.7" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b827a6d7784fe3eb3489d40699407a4cdcce74271421a01bdffe60cf573bb16" +checksum = "6a12e1dc70236cfb8e79b96dd8544aed47c39e2f45dc6b51c3703e969e052faa" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -146,9 +136,9 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "1.8.3" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6ef28c9fdad22d4eec52d894f5f2673a0895f1e5ef196734568e68c0f6caca8" +checksum = "ca3e76d47e8de277cb55e7e77fa38adde835162fc01cddbe1b258b5e0a86035b" dependencies = [ "alloy-eip2124", "alloy-eip2930", @@ -164,14 +154,14 @@ dependencies = [ "either", "serde", "serde_with", - "sha2 0.10.9", + "sha2", ] [[package]] name = "alloy-evm" -version = "0.15.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28de0dd1bbb0634ef7c3715e8e60176b77b82f8b6b15b2e35fe64cf6640f6550" +checksum = "a6e494529570a4d25eb4d1a7456d8f969c3202aceaf703e4006cec5f730aee96" dependencies = [ "alloy-consensus", "alloy-eips", @@ -180,17 +170,16 @@ dependencies = [ "alloy-sol-types", "auto_impl", "derive_more", - "op-alloy-consensus", - "op-revm 8.1.0", - "revm 27.1.0", + "revm", "thiserror", + "tracing", ] [[package]] name = "alloy-hardforks" -version = "0.2.13" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165210652f71dfc094b051602bafd691f506c54050a174b1cba18fb5ef706a3" +checksum = "865371fb677c005f7cb0ea9c2847a1ba4fdb042caf6428b1769fee20368bbfc7" dependencies = [ "alloy-chains", "alloy-eip2124", @@ -201,9 +190,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5513d5e6bd1cba6bdcf5373470f559f320c05c8c59493b6e98912fbe6733943f" +checksum = "7c36c9d7f9021601b04bfef14a4b64849f6d73116a4e91e071d7fbfe10247901" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -211,52 +200,11 @@ dependencies = [ "serde_json", ] -[[package]] -name = "alloy-json-rpc" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003f46c54f22854a32b9cc7972660a476968008ad505427eabab49225309ec40" -dependencies = [ - "alloy-primitives", - "alloy-sol-types", - "http", - "serde", - "serde_json", - "thiserror", - "tracing", -] - -[[package]] -name = "alloy-network" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612296e6b723470bb1101420a73c63dfd535aa9bf738ce09951aedbd4ab7292e" -dependencies = [ - "alloy-consensus", - "alloy-consensus-any", - "alloy-eips", - "alloy-json-rpc", - "alloy-network-primitives", - "alloy-primitives", - "alloy-rpc-types-any", - "alloy-rpc-types-eth", - "alloy-serde", - "alloy-signer", - "alloy-sol-types", - "async-trait", - "auto_impl", - "derive_more", - "futures-utils-wasm", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "alloy-network-primitives" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0e7918396eecd69d9c907046ec8a93fb09b89e2f325d5e7ea9c4e3929aa0dd2" +checksum = "8795eecf50374a0dd942caff57922c59333c9991ead9eccbbc1709f55d73c7c2" dependencies = [ "alloy-consensus", "alloy-eips", @@ -265,34 +213,6 @@ dependencies = [ "serde", ] -[[package]] -name = "alloy-op-evm" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0afe768962308a08b42fddef8a4296324f140b5a8dd0d4360038229885ce9434" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-evm", - "alloy-op-hardforks", - "alloy-primitives", - "auto_impl", - "op-alloy-consensus", - "op-revm 8.1.0", - "revm 27.1.0", -] - -[[package]] -name = "alloy-op-hardforks" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3417f4187eaf7f7fb0d7556f0197bca26f0b23c4bb3aca0c9d566dc1c5d727a2" -dependencies = [ - "alloy-chains", - "alloy-hardforks", - "auto_impl", -] - [[package]] name = "alloy-primitives" version = "1.6.0" @@ -304,7 +224,7 @@ dependencies = [ "cfg-if", "const-hex", "derive_more", - "foldhash 0.2.0", + "foldhash", "hashbrown 0.17.1", "indexmap 2.10.0", "itoa", @@ -321,47 +241,11 @@ dependencies = [ "sha3", ] -[[package]] -name = "alloy-provider" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55c1313a527a2e464d067c031f3c2ec073754ef615cc0eabca702fd0fe35729c" -dependencies = [ - "alloy-chains", - "alloy-consensus", - "alloy-eips", - "alloy-json-rpc", - "alloy-network", - "alloy-network-primitives", - "alloy-primitives", - "alloy-rpc-client", - "alloy-rpc-types-eth", - "alloy-signer", - "alloy-sol-types", - "alloy-transport", - "async-stream", - "async-trait", - "auto_impl", - "dashmap", - "either", - "futures", - "futures-utils-wasm", - "lru", - "parking_lot", - "pin-project", - "serde", - "serde_json", - "thiserror", - "tokio", - "tracing", - "wasmtimer", -] - [[package]] name = "alloy-rlp" -version = "0.3.12" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f70d83b765fdc080dbcd4f4db70d8d23fe4761f2f02ebfa9146b833900634b4" +checksum = "24671b1f62edcf0f9b62994c7bf72cd621a04a4b99f5020ece1a647b40e2f103" dependencies = [ "alloy-rlp-derive", "arrayvec", @@ -370,51 +254,20 @@ dependencies = [ [[package]] name = "alloy-rlp-derive" -version = "0.3.12" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64b728d511962dda67c1bc7ea7c03736ec275ed2cf4c35d9585298ac9ccf3b73" +checksum = "9d4311c03125e8a18296504560b9de3d75ecbd0dcda7f71e6cf2a196d57e6fba" dependencies = [ "proc-macro2", "quote", "syn 2.0.104", ] -[[package]] -name = "alloy-rpc-client" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c89883fe6b7381744cbe80fef638ac488ead4f1956a4278956a1362c71cd2e" -dependencies = [ - "alloy-json-rpc", - "alloy-primitives", - "alloy-transport", - "futures", - "pin-project", - "serde", - "serde_json", - "tokio", - "tokio-stream", - "tower", - "tracing", - "wasmtimer", -] - -[[package]] -name = "alloy-rpc-types-any" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbf6d1766ca41e90ac21c4bc5cbc5e9e965978a25873c3f90b3992d905db4cb" -dependencies = [ - "alloy-consensus-any", - "alloy-rpc-types-eth", - "alloy-serde", -] - [[package]] name = "alloy-rpc-types-eth" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15e4831b71eea9d20126a411c1c09facf1d01d5cac84fd51d532d3c429cfc26" +checksum = "756eb5803e70985be4066b636194ccb5f6629e5d141817c1f0c50cea8350bf5c" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -433,9 +286,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "1.0.24" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6a854af3fe8fce1cfe319fcf84ee8ba8cda352b14d3dd4221405b5fc6cce9e1" +checksum = "1933d60c2f51b8906103484ea2ca2218357264dbf16f948f7c2dd4ac5818e1d8" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -447,35 +300,20 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "1.8.3" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ece63b89294b8614ab3f483560c08d016930f842bf36da56bf0b764a15c11e" +checksum = "cc142e40df0c3eb5983b1637a68ab33471d8d22b8f402c9ed8260411a4e89d86" dependencies = [ "alloy-primitives", "serde", "serde_json", ] -[[package]] -name = "alloy-signer" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc39ad2c0a3d2da8891f4081565780703a593f090f768f884049aa3aa929cbc" -dependencies = [ - "alloy-primitives", - "async-trait", - "auto_impl", - "either", - "elliptic-curve", - "k256", - "thiserror", -] - [[package]] name = "alloy-sol-macro" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3ce480400051b5217f19d6e9a82d9010cdde20f1ae9c00d53591e4a1afbb312" +checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", @@ -487,9 +325,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro-expander" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d792e205ed3b72f795a8044c52877d2e6b6e9b1d13f431478121d8d4eaa9028" +checksum = "63ec265e5d65d725175f6ca7711c970824c90ef9c0d1f1973711d4150ee612dd" dependencies = [ "alloy-sol-macro-input", "const-hex", @@ -498,16 +336,16 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", + "sha3", "syn 2.0.104", "syn-solidity", - "tiny-keccak", ] [[package]] name = "alloy-sol-macro-input" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd1247a8f90b465ef3f1207627547ec16940c35597875cdc09c49d58b19693c" +checksum = "89bf01077f18650876cfa682eb1f949967b5cde03f1a51c955c469d2c9b4aa67" dependencies = [ "const-hex", "dunce", @@ -521,19 +359,19 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "954d1b2533b9b2c7959652df3076954ecb1122a28cc740aa84e7b0a49f6ac0a9" +checksum = "857b470ecdd2ed38beaf82ad1a38c516a8ff75266750f38b9eeed001d575241b" dependencies = [ "serde", - "winnow", + "winnow 1.0.4", ] [[package]] name = "alloy-sol-types" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70319350969a3af119da6fb3e9bddb1bce66c9ea933600cb297c8b1850ad2a3c" +checksum = "384cf252de0db2dec52821eac037a7f57e2aa33fe5b900ce6fe39973402341f1" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -541,52 +379,29 @@ dependencies = [ "serde", ] -[[package]] -name = "alloy-transport" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cae82426d98f8bc18f53c5223862907cac30ab8fc5e4cd2bb50808e6d3ab43d8" -dependencies = [ - "alloy-json-rpc", - "auto_impl", - "base64", - "derive_more", - "futures", - "futures-utils-wasm", - "parking_lot", - "serde", - "serde_json", - "thiserror", - "tokio", - "tower", - "tracing", - "url", - "wasmtimer", -] - [[package]] name = "alloy-trie" -version = "0.9.0" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bada1fc392a33665de0dc50d401a3701b62583c655e3522a323490a5da016962" +checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" dependencies = [ "alloy-primitives", "alloy-rlp", - "arrayvec", "derive_more", "nybbles", "serde", "smallvec", + "thiserror", "tracing", ] [[package]] name = "alloy-tx-macros" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae109e33814b49fc0a62f2528993aa8a2dd346c26959b151f05441dc0b9da292" +checksum = "25484345e4d89c259235e200d4f895eba33e70f125f4e8bb37a7aa69a97bd656" dependencies = [ - "darling", + "darling 0.23.0", "proc-macro2", "quote", "syn 2.0.104", @@ -673,7 +488,7 @@ dependencies = [ "fnv", "hashbrown 0.15.4", "itertools 0.13.0", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "zeroize", @@ -690,7 +505,7 @@ dependencies = [ "ark-serialize 0.3.0", "ark-std 0.3.0", "derivative", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "rustc_version 0.3.3", @@ -710,7 +525,7 @@ dependencies = [ "derivative", "digest 0.10.7", "itertools 0.10.5", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "rustc_version 0.4.1", @@ -731,7 +546,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "zeroize", @@ -773,7 +588,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "quote", "syn 1.0.109", @@ -785,7 +600,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "proc-macro2", "quote", @@ -798,7 +613,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "proc-macro2", "quote", @@ -831,7 +646,7 @@ dependencies = [ "ark-relations", "ark-std 0.5.0", "educe", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "tracing", @@ -867,7 +682,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint 0.4.6", + "num-bigint", ] [[package]] @@ -880,7 +695,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint 0.4.6", + "num-bigint", ] [[package]] @@ -935,42 +750,6 @@ name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" -dependencies = [ - "serde", -] - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] [[package]] name = "aurora-engine-modexp" @@ -999,12 +778,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" -[[package]] -name = "az" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b7e4c2464d97fe331d41de9d5db0def0a96f4d823b8b32a2efd503578988973" - [[package]] name = "base16ct" version = "0.2.0" @@ -1023,15 +796,6 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - [[package]] name = "bit-set" version = "0.8.0" @@ -1085,28 +849,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "blake3" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -1231,17 +973,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" -[[package]] -name = "chacha20" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "rand_core 0.10.1", -] - [[package]] name = "chrono" version = "0.4.41" @@ -1418,17 +1149,11 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "constant_time_eq" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" - [[package]] name = "convert_case" -version = "0.7.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" dependencies = [ "unicode-segmentation", ] @@ -1482,12 +1207,6 @@ dependencies = [ "itertools 0.10.5", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - [[package]] name = "crunchy" version = "0.2.4" @@ -1531,8 +1250,18 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", ] [[package]] @@ -1542,6 +1271,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" dependencies = [ "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.104", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ "ident_case", "proc-macro2", "quote", @@ -1556,23 +1298,20 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ - "darling_core", + "darling_core 0.21.3", "quote", "syn 2.0.104", ] [[package]] -name = "dashmap" -version = "6.1.0" +name = "darling_macro" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", + "darling_core 0.23.0", + "quote", + "syn 2.0.104", ] [[package]] @@ -1630,22 +1369,23 @@ dependencies = [ [[package]] name = "derive_more" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ "convert_case", "proc-macro2", "quote", + "rustc_version 0.4.1", "syn 2.0.104", "unicode-xid", ] @@ -1681,17 +1421,6 @@ dependencies = [ "crypto-common 0.2.2", ] -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "dunce" version = "1.0.5" @@ -1830,38 +1559,21 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "byteorder", - "ff_derive", "rand_core 0.6.4", "subtle", ] [[package]] -name = "ff_derive" -version = "0.13.1" +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fixed-hash" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f10d12652036b0e99197587c6ba87a8fc3031986499973c030d8b44fcc151b60" -dependencies = [ - "addchain", - "num-bigint 0.3.3", - "num-integer", - "num-traits", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "fixed-hash" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" +checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" dependencies = [ "byteorder", "rand 0.8.5", @@ -1875,134 +1587,18 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - [[package]] name = "funty" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" -[[package]] -name = "futures" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" - -[[package]] -name = "futures-executor" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" - -[[package]] -name = "futures-macro" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - -[[package]] -name = "futures-sink" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" - -[[package]] -name = "futures-task" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" - -[[package]] -name = "futures-util" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "futures-utils-wasm" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" - -[[package]] -name = "gcd" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d758ba1b47b00caf47f24925c0074ecb20d6dfcffe7f6d53395c0465674841a" - [[package]] name = "generic-array" version = "0.14.7" @@ -2046,7 +1642,6 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", - "rand_core 0.10.1", ] [[package]] @@ -2055,16 +1650,6 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" -[[package]] -name = "gmp-mpfr-sys" -version = "1.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66d61197a68f6323b9afa616cf83d55d69191e1bf364d4eb7d35ae18defe776" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - [[package]] name = "group" version = "0.13.0" @@ -2092,12 +1677,6 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - [[package]] name = "hashbrown" version = "0.15.4" @@ -2105,8 +1684,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" dependencies = [ "allocator-api2", - "equivalent", - "foldhash 0.1.5", ] [[package]] @@ -2115,7 +1692,7 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash 0.2.0", + "foldhash", "serde", "serde_core", ] @@ -2159,17 +1736,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "http" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "hybrid-array" version = "0.4.12" @@ -2203,114 +1769,12 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_collections" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" -dependencies = [ - "displaydoc", - "potential_utf", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" - -[[package]] -name = "icu_properties" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" - -[[package]] -name = "icu_provider" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - [[package]] name = "impl-codec" version = "0.6.0" @@ -2373,15 +1837,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.13.0" @@ -2427,7 +1882,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2 0.10.9", + "sha2", ] [[package]] @@ -2450,20 +1905,6 @@ dependencies = [ "sha3-asm", ] -[[package]] -name = "kzg-rs" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9201effeea3fcc93b587904ae2df9ce97e433184b9d6d299e9ebc9830a546636" -dependencies = [ - "ff", - "hex", - "serde_arrays", - "sha2 0.10.9", - "sp1_bls12_381", - "spin", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -2482,93 +1923,23 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" -[[package]] -name = "libsecp256k1" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79019718125edc905a079a70cfa5f3820bc76139fc91d6f9abc27ea2a887139" -dependencies = [ - "arrayref", - "base64", - "digest 0.9.0", - "libsecp256k1-core", - "libsecp256k1-gen-ecmult", - "libsecp256k1-gen-genmult", - "rand 0.8.5", - "serde", - "sha2 0.9.9", -] - -[[package]] -name = "libsecp256k1-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" -dependencies = [ - "crunchy", - "digest 0.9.0", - "subtle", -] - -[[package]] -name = "libsecp256k1-gen-ecmult" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809" -dependencies = [ - "libsecp256k1-core", -] - -[[package]] -name = "libsecp256k1-gen-genmult" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c" -dependencies = [ - "libsecp256k1-core", -] - [[package]] name = "linux-raw-sys" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" -[[package]] -name = "litemap" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" -[[package]] -name = "lru" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "227748d55f2f0ab4735d87fd623798cb6b664512fe979705f829c9f81c934465" -dependencies = [ - "hashbrown 0.15.4", -] - [[package]] name = "macro-string" -version = "0.1.4" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b27834086c65ec3f9387b096d66e99f221cf081c2b738042aa252bcd41204e3" +checksum = "59a9dbbfc75d2688ed057456ce8a3ee3f48d12eec09229f560f3643b9f275653" dependencies = [ "proc-macro2", "quote", @@ -2577,43 +1948,30 @@ dependencies = [ [[package]] name = "mega-evm" -version = "1.7.1" +version = "2.0.0-alpha.1" dependencies = [ "alloy-consensus", - "alloy-eips", "alloy-evm", "alloy-hardforks", - "alloy-op-evm", - "alloy-op-hardforks", "alloy-primitives", "alloy-sol-types", "auto_impl", - "bitflags", "codspeed-criterion-compat", "delegate", "derive_more", - "hex", "mega-evm", "mega-system-contracts", - "once_cell", "op-alloy-consensus", - "op-alloy-flz", - "op-revm 20.0.0", - "op-revm 8.1.0", - "rand 0.10.2", - "revm 27.1.0", - "revm 38.0.0", + "op-revm", + "revm", "revm-inspectors", "serde", "serde_json", - "sha2 0.10.9", - "thiserror", - "tracing", ] [[package]] name = "mega-system-contracts" -version = "1.7.1" +version = "2.0.0-alpha.1" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -2640,13 +1998,22 @@ dependencies = [ "libc", ] +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" +dependencies = [ + "serde", +] + [[package]] name = "num" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-complex", "num-integer", "num-iter", @@ -2654,17 +2021,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-bigint" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6f7833f2cbf2360a6cfd58cd41a53aa7a90bd4c202f5b1c7dd2ed73c57b2c3" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - [[package]] name = "num-bigint" version = "0.4.6" @@ -2716,7 +2072,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", ] @@ -2757,7 +2113,6 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77e878c846a8abae00dd069496dbe8751b16ac1c3d6bd2a7283a938e8228f90d" dependencies = [ - "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.104", @@ -2791,9 +2146,8 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "op-alloy-consensus" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c88d2940558fd69f8f07b3cbd7bb3c02fc7d31159c1a7ba9deede50e7881024" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2803,41 +2157,16 @@ dependencies = [ "thiserror", ] -[[package]] -name = "op-alloy-flz" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79f352fc3893dcd670172e615afef993a41798a1d3fc0db88a3e60ef2e70ecc" - -[[package]] -name = "op-revm" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce1dc7533f4e5716c55cd3d62488c6200cb4dfda96e0c75a7e484652464343b" -dependencies = [ - "auto_impl", - "once_cell", - "revm 27.1.0", - "serde", -] - [[package]] name = "op-revm" version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cfe618e3426e7a65b74f105aa706cfc92cd100ade8a6588a15c6ac3002e467" +source = "git+https://github.com/megaeth-labs/op-revm?rev=817e36e92bf3cfc0985def0f36e72fc1b737b175#817e36e92bf3cfc0985def0f36e72fc1b737b175" dependencies = [ "auto_impl", - "revm 38.0.0", + "revm", "serde", ] -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "p256" version = "0.13.2" @@ -2847,128 +2176,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2 0.10.9", -] - -[[package]] -name = "p3-baby-bear" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7521838ecab2ddf4f7bc4ceebad06ec02414729598485c1ada516c39900820e8" -dependencies = [ - "num-bigint 0.4.6", - "p3-field", - "p3-mds", - "p3-poseidon2", - "p3-symmetric", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-dft" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46414daedd796f1eefcdc1811c0484e4bced5729486b6eaba9521c572c76761a" -dependencies = [ - "p3-field", - "p3-matrix", - "p3-maybe-rayon", - "p3-util", - "tracing", -] - -[[package]] -name = "p3-field" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48948a0516b349e9d1cdb95e7236a6ee010c44e68c5cc78b4b92bf1c4022a0d9" -dependencies = [ - "itertools 0.12.1", - "num-bigint 0.4.6", - "num-traits", - "p3-util", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-matrix" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4de3f373589477cb735ea58e125898ed20935e03664b4614c7fac258b3c42f" -dependencies = [ - "itertools 0.12.1", - "p3-field", - "p3-maybe-rayon", - "p3-util", - "rand 0.8.5", - "serde", - "tracing", -] - -[[package]] -name = "p3-maybe-rayon" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3968ad1160310296eb04f91a5f4edfa38fe1d6b2b8cd6b5c64e6f9b7370979e" - -[[package]] -name = "p3-mds" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2356b1ed0add6d5dfbf7a338ce534a6fde827374394a52cec16a0840af6e97c9" -dependencies = [ - "itertools 0.12.1", - "p3-dft", - "p3-field", - "p3-matrix", - "p3-symmetric", - "p3-util", - "rand 0.8.5", -] - -[[package]] -name = "p3-poseidon2" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da1eec7e1b6900581bedd95e76e1ef4975608dd55be9872c9d257a8a9651c3a" -dependencies = [ - "gcd", - "p3-field", - "p3-mds", - "p3-symmetric", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-symmetric" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edb439bea1d822623b41ff4b51e3309e80d13cadf8b86d16ffd5e6efb9fdc360" -dependencies = [ - "itertools 0.12.1", - "p3-field", - "serde", -] - -[[package]] -name = "p3-util" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c2c2010678b9332b563eaa38364915b585c1a94b5ca61e2c7541c087ddda5c" -dependencies = [ - "serde", -] - -[[package]] -name = "pairing" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" -dependencies = [ - "group", + "sha2", ] [[package]] @@ -2999,41 +2207,12 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link 0.2.1", -] - [[package]] name = "paste" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - [[package]] name = "pest" version = "2.8.1" @@ -3045,38 +2224,17 @@ dependencies = [ "ucd-trie", ] -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_macros 0.11.3", - "phf_shared 0.11.3", - "serde", -] - [[package]] name = "phf" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros 0.13.1", - "phf_shared 0.13.1", + "phf_macros", + "phf_shared", "serde", ] -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared 0.11.3", - "rand 0.8.5", -] - [[package]] name = "phf_generator" version = "0.13.1" @@ -3084,20 +2242,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared 0.13.1", -] - -[[package]] -name = "phf_macros" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" -dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", - "proc-macro2", - "quote", - "syn 2.0.104", + "phf_shared", ] [[package]] @@ -3106,22 +2251,13 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator 0.13.1", - "phf_shared 0.13.1", + "phf_generator", + "phf_shared", "proc-macro2", "quote", "syn 2.0.104", ] -[[package]] -name = "phf_shared" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" -dependencies = [ - "siphasher", -] - [[package]] name = "phf_shared" version = "0.13.1" @@ -3131,38 +2267,12 @@ dependencies = [ "siphasher", ] -[[package]] -name = "pin-project" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkcs8" version = "0.10.2" @@ -3201,15 +2311,6 @@ dependencies = [ "plotters-backend", ] -[[package]] -name = "potential_utf" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" -dependencies = [ - "zerovec", -] - [[package]] name = "powerfmt" version = "0.2.0" @@ -3361,17 +2462,6 @@ dependencies = [ "serde", ] -[[package]] -name = "rand" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - [[package]] name = "rand_chacha" version = "0.3.1" @@ -3411,12 +2501,6 @@ dependencies = [ "serde", ] -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - [[package]] name = "rand_xorshift" version = "0.4.0" @@ -3435,15 +2519,6 @@ dependencies = [ "rustversion", ] -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - [[package]] name = "ref-cast" version = "1.0.24" @@ -3495,312 +2570,160 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "revm" -version = "27.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6bf82101a1ad8a2b637363a37aef27f88b4efc8a6e24c72bf5f64923dc5532" -dependencies = [ - "revm-bytecode 6.2.1", - "revm-context 8.0.4", - "revm-context-interface 9.0.0", - "revm-database 7.0.4", - "revm-database-interface 7.0.4", - "revm-handler 8.1.0", - "revm-inspector 8.1.0", - "revm-interpreter 24.0.0", - "revm-precompile 25.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", -] - -[[package]] -name = "revm" -version = "38.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91202d39dbe8e8d10e9e8f2b76c30da68ecd1d25be69ba6d853ad0d03a3a398a" +version = "40.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode 10.0.0", - "revm-context 16.0.1", - "revm-context-interface 17.0.1", - "revm-database 13.0.1", - "revm-database-interface 11.0.1", - "revm-handler 18.1.0", - "revm-inspector 19.0.0", - "revm-interpreter 35.0.1", - "revm-precompile 34.0.0", - "revm-primitives 23.0.0", - "revm-state 11.0.1", -] - -[[package]] -name = "revm-bytecode" -version = "6.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d800e6c2119457ded5b0af71634eb2468040bf97de468eee5a730272a106da0" -dependencies = [ - "bitvec", - "phf 0.11.3", - "revm-primitives 20.2.1", - "serde", + "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 = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdbb3a3d735efa94c91f2ef6bf20a35f99a77bc78f3e25bd758336901bdf9661" +version = "11.0.1" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", - "phf 0.13.1", - "revm-primitives 23.0.0", + "phf", + "revm-primitives", "serde", ] [[package]] name = "revm-context" -version = "8.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd508416a35a4d8a9feaf5ccd06ac6d6661cd31ee2dc0252f9f7316455d71f9" -dependencies = [ - "cfg-if", - "derive-where", - "revm-bytecode 6.2.1", - "revm-context-interface 9.0.0", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", - "serde", -] - -[[package]] -name = "revm-context" -version = "16.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f68d928d8b228e0faeb1c6ed75c4fde7d124f1ddf9119b67e7a0ad4041237d" +version = "18.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", "cfg-if", "derive-where", - "revm-bytecode 10.0.0", - "revm-context-interface 17.0.1", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-context-interface" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc90302642d21c8f93e0876e201f3c5f7913c4fcb66fb465b0fd7b707dfe1c79" -dependencies = [ - "alloy-eip2930", - "alloy-eip7702", - "auto_impl", - "either", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "revm-bytecode", + "revm-context-interface", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", ] [[package]] name = "revm-context-interface" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3758e6167c4ba7a59a689c519a047edaefcd4c37d74f279b93ed87bc8aece4" +version = "19.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip2930", "alloy-eip7702", "auto_impl", "either", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-database" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40000c7d917c865f6c232a78581b78e70c43f52db17282bd1b52d4f0565bc8a2" -dependencies = [ - "alloy-eips", - "alloy-provider", - "alloy-transport", - "revm-bytecode 6.2.1", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", - "tokio", ] [[package]] name = "revm-database" -version = "13.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c281a1f11d3bcb8c0bba1199ed6bcb001d1aeb3d4fb366819e14f88723989a4e" +version = "15.0.2" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eips", - "revm-bytecode 10.0.0", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-database-interface" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4ccea7a168cba1196b1e57dd3e22c36047208c135f600f8e58cbe7d49957dba" -dependencies = [ - "auto_impl", - "either", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "derive_more", + "revm-bytecode", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", - "tokio", ] [[package]] name = "revm-database-interface" -version = "11.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89efb9832a4e3742bb4ded5f7fe5bf905e8860e69427d4dfec153484fc6d304" +version = "12.1.1" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-primitives", + "revm-state", "serde", "thiserror", ] [[package]] name = "revm-handler" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1529c8050e663be64010e80ec92bf480315d21b1f2dbf65540028653a621b27d" +version = "20.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "derive-where", - "revm-bytecode 6.2.1", - "revm-context 8.0.4", - "revm-context-interface 9.0.0", - "revm-database-interface 7.0.4", - "revm-interpreter 24.0.0", - "revm-precompile 25.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", - "serde", -] - -[[package]] -name = "revm-handler" -version = "18.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "783e903d6922b7f5f9a940d1bb229530502d2924b1aed9d5ca5a94ebf065d460" -dependencies = [ - "auto_impl", - "derive-where", - "revm-bytecode 10.0.0", - "revm-context 16.0.1", - "revm-context-interface 17.0.1", - "revm-database-interface 11.0.1", - "revm-interpreter 35.0.1", - "revm-precompile 34.0.0", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-bytecode", + "revm-context", + "revm-context-interface", + "revm-database-interface", + "revm-interpreter", + "revm-precompile", + "revm-primitives", + "revm-state", "serde", ] [[package]] name = "revm-inspector" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78db140e332489094ef314eaeb0bd1849d6d01172c113ab0eb6ea8ab9372926" +version = "21.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", - "revm-context 8.0.4", - "revm-database-interface 7.0.4", - "revm-handler 8.1.0", - "revm-interpreter 24.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", - "serde", - "serde_json", -] - -[[package]] -name = "revm-inspector" -version = "19.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8216ad58422090d0daa9eb430e0a081f7ad07e7fd30681dee71f8420c99624e0" -dependencies = [ - "auto_impl", - "either", - "revm-context 16.0.1", - "revm-database-interface 11.0.1", - "revm-handler 18.1.0", - "revm-interpreter 35.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-context", + "revm-database-interface", + "revm-handler", + "revm-interpreter", + "revm-primitives", + "revm-state", "serde", "serde_json", ] [[package]] name = "revm-inspectors" -version = "0.27.3" +version = "0.40.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2483827fec2c31db4ada14e0b5523c377d1084337d1dbe135faaf14c218ab1af" +checksum = "e93b96ddc470322a7294b8aecad862480625a9f1346d42fea51b1cce54afdb05" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", "alloy-rpc-types-trace", - "alloy-sol-types", - "anstyle", - "colorchoice", - "revm 27.1.0", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "revm-interpreter" -version = "24.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff9d7d9d71e8a33740b277b602165b6e3d25fff091ba3d7b5a8d373bf55f28a7" -dependencies = [ - "revm-bytecode 6.2.1", - "revm-context-interface 9.0.0", - "revm-primitives 20.2.1", + "alloy-sol-types", + "anstyle", + "colorchoice", + "revm", "serde", + "serde_json", + "thiserror", ] [[package]] name = "revm-interpreter" -version = "35.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ece9f41b69658c15d748288a4dbdfc06a63f3ce93d983af440de3f1631dce6a" +version = "37.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode 10.0.0", - "revm-context-interface 17.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-bytecode", + "revm-context-interface", + "revm-primitives", + "revm-state", "serde", ] [[package]] name = "revm-precompile" -version = "25.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cee3f336b83621294b4cfe84d817e3eef6f3d0fce00951973364cc7f860424d" +version = "36.0.3" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3813,87 +2736,34 @@ dependencies = [ "c-kzg", "cfg-if", "k256", - "kzg-rs", - "libsecp256k1", - "once_cell", - "p256", - "revm-primitives 20.2.1", - "ripemd", - "rug", - "secp256k1 0.31.1", - "sha2 0.10.9", -] - -[[package]] -name = "revm-precompile" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a346a8cc6c8c39bd65306641c692191299c0a7b63d38810e39e8fe9b92378660" -dependencies = [ - "ark-bls12-381", - "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", - "arrayref", - "aurora-engine-modexp", - "c-kzg", - "cfg-if", - "k256", "p256", - "revm-context-interface 17.0.1", - "revm-primitives 23.0.0", + "revm-context-interface", + "revm-primitives", "ripemd", "secp256k1 0.31.1", - "sha2 0.10.9", -] - -[[package]] -name = "revm-primitives" -version = "20.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa29d9da06fe03b249b6419b33968ecdf92ad6428e2f012dc57bcd619b5d94e" -dependencies = [ - "alloy-primitives", - "num_enum", - "once_cell", - "serde", + "sha2", ] [[package]] name = "revm-primitives" -version = "23.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c99bda77d9661521ba0b4bc04558c6692074f01e65dd420fa3b893033d9b8a2" +version = "24.0.1" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-primitives", - "num_enum", "once_cell", "serde", ] [[package]] name = "revm-state" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d7f39ea56df3bfbb3c81c99b1f028d26f205b6004156baffbf1a4f84b46cfa" -dependencies = [ - "bitflags", - "revm-bytecode 6.2.1", - "revm-primitives 20.2.1", - "serde", -] - -[[package]] -name = "revm-state" -version = "11.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c32490ed687dba31c3c882beb8c20408bdd30ef96690d8f145b0ee9a87040bfe" +version = "12.0.1" +source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip7928", "bitflags", - "revm-bytecode 10.0.0", - "revm-primitives 23.0.0", + "nonmax", + "revm-bytecode", + "revm-primitives", "serde", ] @@ -3926,18 +2796,6 @@ dependencies = [ "rustc-hex", ] -[[package]] -name = "rug" -version = "1.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4207e8d668e5b8eb574bda8322088ccd0d7782d3d03c7e8d562e82ed82bdcbc3" -dependencies = [ - "az", - "gmp-mpfr-sys", - "libc", - "libm", -] - [[package]] name = "ruint" version = "1.17.2" @@ -3951,7 +2809,7 @@ dependencies = [ "bytes", "fastrlp 0.3.1", "fastrlp 0.4.0", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "parity-scale-codec", @@ -4072,12 +2930,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "sec1" version = "0.7.3" @@ -4171,15 +3023,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde_arrays" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a16b99c5ea4fe3daccd14853ad260ec00ea043b2708d1fd1da3106dcd8d9df" -dependencies = [ - "serde", -] - [[package]] name = "serde_core" version = "1.0.228" @@ -4239,7 +3082,7 @@ version = "3.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "327ada00f7d64abaac1e55a6911e90cf665aa051b9a561c7006c157f4633135e" dependencies = [ - "darling", + "darling 0.21.3", "proc-macro2", "quote", "syn 2.0.104", @@ -4255,19 +3098,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.9.0", - "opaque-debug", -] - [[package]] name = "sha2" version = "0.10.9" @@ -4321,12 +3151,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" -[[package]] -name = "slab" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" - [[package]] name = "smallvec" version = "1.15.1" @@ -4336,58 +3160,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sp1-lib" -version = "5.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fbb6e3d8741c0fcdaa37e74d2dd9a2bdcbf958d192e438eec59e8071e08124c" -dependencies = [ - "bincode", - "serde", - "sp1-primitives", -] - -[[package]] -name = "sp1-primitives" -version = "5.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4d2be9803acce74985f8861b6d5eb375ad1c5f176a68c2c735755937248f25e" -dependencies = [ - "bincode", - "blake3", - "cfg-if", - "hex", - "lazy_static", - "num-bigint 0.4.6", - "p3-baby-bear", - "p3-field", - "p3-poseidon2", - "p3-symmetric", - "serde", - "sha2 0.10.9", -] - -[[package]] -name = "sp1_bls12_381" -version = "0.8.0-sp1-5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac255e1704ebcdeec5e02f6a0ebc4d2e9e6b802161938330b6810c13a610c583" -dependencies = [ - "cfg-if", - "ff", - "group", - "pairing", - "rand_core 0.6.4", - "sp1-lib", - "subtle", -] - -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - [[package]] name = "spki" version = "0.7.3" @@ -4398,12 +3170,6 @@ dependencies = [ "der", ] -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - [[package]] name = "static_assertions" version = "1.1.0" @@ -4476,29 +3242,23 @@ dependencies = [ ] [[package]] -name = "syn-solidity" -version = "1.4.1" +name = "syn" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff790eb176cc81bb8936aed0f7b9f14fc4670069a2d371b3e3b0ecce908b2cb3" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ - "paste", "proc-macro2", "quote", - "syn 2.0.104", + "unicode-ident", ] [[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" - -[[package]] -name = "synstructure" -version = "0.13.2" +name = "syn-solidity" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "ec005042c7d952febc1a3ef5b0f6674e9054aa836877a31c90b20e25b3d31744" dependencies = [ + "paste", "proc-macro2", "quote", "syn 2.0.104", @@ -4525,22 +3285,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.12" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.12" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] @@ -4583,25 +3343,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - -[[package]] -name = "tinystr" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" -dependencies = [ - "displaydoc", - "zerovec", -] - [[package]] name = "tinytemplate" version = "1.2.1" @@ -4612,52 +3353,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "tokio" -version = "1.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" -dependencies = [ - "pin-project-lite", - "tokio-macros", -] - -[[package]] -name = "tokio-macros" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - -[[package]] -name = "tokio-stream" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", - "tokio-util", -] - -[[package]] -name = "tokio-util" -version = "0.7.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - [[package]] name = "toml_datetime" version = "0.6.11" @@ -4672,35 +3367,9 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap 2.10.0", "toml_datetime", - "winnow", -] - -[[package]] -name = "tower" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tower-layer", - "tower-service", + "winnow 0.7.12", ] -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - [[package]] name = "tracing" version = "0.1.41" @@ -4790,24 +3459,6 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "url" -version = "2.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - [[package]] name = "valuable" version = "0.1.1" @@ -4912,20 +3563,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "wasmtimer" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c598d6b99ea013e35844697fc4670d08339d5cda15588f193c6beedd12f644b" -dependencies = [ - "futures", - "js-sys", - "parking_lot", - "pin-utils", - "slab", - "wasm-bindgen", -] - [[package]] name = "web-sys" version = "0.3.77" @@ -5174,6 +3811,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "wit-bindgen-rt" version = "0.39.0" @@ -5183,12 +3829,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "writeable" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" - [[package]] name = "wyz" version = "0.5.1" @@ -5198,29 +3838,6 @@ dependencies = [ "tap", ] -[[package]] -name = "yoke" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.8.26" @@ -5241,27 +3858,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "zerofrom" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", - "synstructure", -] - [[package]] name = "zeroize" version = "1.8.1" @@ -5281,36 +3877,3 @@ dependencies = [ "quote", "syn 2.0.104", ] - -[[package]] -name = "zerotrie" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] diff --git a/Cargo.toml b/Cargo.toml index 24f58a1da..516b04f6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,9 +12,9 @@ exclude = [] # https://doc.rust-lang.org/edition-guide/rust-2021/default-cargo-resolver.html resolver = "2" [workspace.package] -version = "1.7.1" +version = "2.0.0-alpha.1" edition = "2021" -rust-version = "1.91" +rust-version = "1.94" license = "MIT OR Apache-2.0" homepage = "https://github.com/megaeth-labs/mega-evm" repository = "https://github.com/megaeth-labs/mega-evm" @@ -119,38 +119,42 @@ too_long_first_doc_paragraph = "allow" [workspace.dependencies] # megaeth -mega-evm = { path = "./crates/mega-evm", version = "1.7.1", default-features = false } -mega-state-test = { path = "./crates/mega-state-test", version = "1.7.1", default-features = false } -mega-system-contracts = { path = "./crates/system-contracts", version = "1.7.1", default-features = false } +mega-evm = { path = "./crates/mega-evm", version = "2.0.0-alpha.1", default-features = false } +mega-state-test = { path = "./crates/mega-state-test", version = "2.0.0-alpha.1", default-features = false } +mega-system-contracts = { path = "./crates/system-contracts", version = "2.0.0-alpha.1", default-features = false } # revm -op-revm = { version = "8.1.0", default-features = false } -revm = { version = "27.1.0", default-features = false } -revm-inspectors = { version = "0.27.3", default-features = false } +# revm stays pinned to the crates.io version the megaeth fork is based on; `[patch.crates-io]` +# below redirects all twelve revm crates to the fork. op-revm and the OP alloy crates have no +# crates.io release for revm 40: they come from the OP monorepo revision the node locks, and +# op-revm is redirected to the megaeth fork of it by the second patch block. +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +revm = { version = "=40.0.3", default-features = false } +revm-inspectors = { version = "0.40.1", default-features = false } # alloy -alloy-consensus = { version = "1.0.23", default-features = false } -alloy-eips = { version = "1.0.23", default-features = false } -alloy-evm = { version = "0.15.0", default-features = false } -alloy-hardforks = { version = "0.2.7", default-features = false } -alloy-json-rpc = { version = "1.0.41", default-features = false } -alloy-network = { version = "1.0.41", default-features = false } -alloy-op-evm = { version = "0.15.0", default-features = false } -alloy-op-hardforks = { version = "0.2.2", default-features = false } -alloy-primitives = { version = "1.3.0", default-features = false, features = ["map-foldhash"] } -alloy-provider = { version = "1.0.41", default-features = false } -alloy-rlp = { version = "0.3.12", default-features = false } -alloy-rpc-client = { version = "1.0.41", default-features = false } -alloy-rpc-types-eth = { version = "1.0.24", default-features = false, features = ["serde"] } -alloy-rpc-types-trace = { version = "1.0.22", default-features = false } -alloy-serde = { version = "1.0.23", default-features = false } -alloy-sol-types = { version = "1.0.23", default-features = false } -alloy-transport = { version = "1.0.41", default-features = false } -alloy-transport-http = { version = "1.0.41", default-features = false } -op-alloy-consensus = { version = "0.18.12", default-features = false, features = ["k256"] } +alloy-consensus = { version = "2.0.5", default-features = false } +alloy-eips = { version = "2.0.5", default-features = false } +alloy-evm = { version = "0.36.0", default-features = false } +alloy-hardforks = { version = "0.4.7", default-features = false } +alloy-json-rpc = { version = "2.1.1", default-features = false } +alloy-network = { version = "2.0.5", default-features = false } +alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +alloy-op-hardforks = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +alloy-primitives = { version = "1.6.0", default-features = false, features = ["map-foldhash"] } +alloy-provider = { version = "2.0.5", default-features = false } +alloy-rlp = { version = "0.3.16", default-features = false } +alloy-rpc-client = { version = "2.1.1", default-features = false } +alloy-rpc-types-eth = { version = "2.0.5", default-features = false, features = ["serde"] } +alloy-rpc-types-trace = { version = "2.0.5", default-features = false } +alloy-serde = { version = "2.1.1", default-features = false } +alloy-sol-types = { version = "1.6.0", default-features = false } +alloy-transport = { version = "2.1.1", default-features = false } +alloy-transport-http = { version = "2.1.1", default-features = false } +op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false, features = ["k256"] } op-alloy-flz = { version = "0.13.1", default-features = false } -op-alloy-network = { version = "0.18.12", default-features = false } -op-alloy-rpc-types = { version = "0.18.12", default-features = false } +op-alloy-network = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +op-alloy-rpc-types = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } # misc auto_impl = { version = "1.3", default-features = false } @@ -221,3 +225,25 @@ strip = "none" inherits = "release" lto = "fat" codegen-units = 1 + +[patch.crates-io] +# megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). +# Pinned by commit until the fork tags it v40.0.3-mega.1; all twelve crates move together, +# otherwise the build resolves a second copy of revm. +revm = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } + +[patch."https://github.com/ethereum-optimism/optimism"] +# megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built +# against the revm commit above. Pinned by commit until the fork tags it v20.0.0-mega.2. +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "817e36e92bf3cfc0985def0f36e72fc1b737b175" } diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index dccf6eaf6..feaf570e9 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -15,32 +15,24 @@ workspace = true [dependencies] # alloy alloy-consensus = { workspace = true, features = ["k256"] } -alloy-eips.workspace = true alloy-evm.workspace = true alloy-hardforks.workspace = true -alloy-op-evm.workspace = true -alloy-op-hardforks.workspace = true alloy-primitives.workspace = true alloy-sol-types.workspace = true op-alloy-consensus.workspace = true -op-alloy-flz.workspace = true -op-revm = { workspace = true, features = ["dev", "serde", "kzg-rs"] } +op-revm = { workspace = true, features = ["dev", "serde"] } # revm -revm = { workspace = true, features = ["dev", "serde", "kzg-rs"] } +revm = { workspace = true, features = ["dev", "serde"] } # megaeth mega-system-contracts = { workspace = true, default-features = false } # misc auto_impl.workspace = true -bitflags.workspace = true delegate.workspace = true -derive_more.workspace = true -once_cell.workspace = true +derive_more = { workspace = true, features = ["deref"] } serde = { workspace = true, features = ["derive"] } -thiserror.workspace = true -tracing.workspace = true [dev-dependencies] # CodSpeed drop-in: `codspeed-criterion-compat` re-exports criterion's API, so @@ -48,49 +40,11 @@ tracing.workspace = true # it behaves exactly like criterion; under `cargo codspeed` it runs each bench # once under valgrind and reports layout-insensitive instruction counts. criterion = { package = "codspeed-criterion-compat", version = "5.0.1", default-features = false, features = ["cargo_bench_support", "html_reports", "plotters"] } -hex.workspace = true mega-evm = { path = ".", features = ["test-utils"] } -op-revm-latest = { package = "op-revm", version = "20.0.0", default-features = false, features = ["dev", "serde", "std"] } -rand = { workspace = true, features = ["thread_rng"] } revm-inspectors = { workspace = true, features = ["std"] } -# Pin to the revm version `op-revm-latest` depends on so both `_latest` baselines share one revm tree. -revm-latest = { package = "revm", version = "38.0.0", default-features = false, features = ["dev", "serde", "std"] } -serde_json.workspace = true -sha2.workspace = true +serde_json = { workspace = true, features = ["std"] } [features] default = ["std", "revm/default", "op-revm/default"] -std = ["revm/std", "op-revm/std", "revm/alloydb", "mega-system-contracts/std"] +std = ["revm/std", "op-revm/std", "mega-system-contracts/std"] test-utils = [] - -[[bench]] -name = "attack_replay" -harness = false - -[[bench]] -name = "block_bench" -harness = false - -[[bench]] -name = "comp_cost" -harness = false - -[[bench]] -name = "ctt" -harness = false - -[[bench]] -name = "enriched_tx" -harness = false - -[[bench]] -name = "mega_bench" -harness = false - -[[bench]] -name = "revm_bench" -harness = false - -[[bench]] -name = "transact" -harness = false diff --git a/crates/mega-evm/benches/attack_replay.rs b/crates/mega-evm/benches/attack_replay.rs deleted file mode 100644 index 60a7d4cdc..000000000 --- a/crates/mega-evm/benches/attack_replay.rs +++ /dev/null @@ -1,436 +0,0 @@ -//! Benchmark replay of a real mainnet attack contract deployment. -//! -//! Loads a saved prestate snapshot (captured via `debug_traceCall` + -//! `prestateTracer` on `MegaETH` mainnet at a fixed block) and replays the -//! deploy through `MegaEvm` for both supported specs, alongside a vanilla -//! revm baseline executing the same CREATE on the same in-memory state. -//! -//! ## Motivation -//! -//! Production sequencer-monitor measurements on this exact transaction: -//! -//! | path | wall time | -//! |-------------------------------------|-----------| -//! | `mega-evm` + Tracer + `RocksDB` state | ~33 ms | -//! | vanilla revm + `RocksDB` state | ~1.4 ms | -//! -//! The bench reproduces the same ratio in a hermetic, `RocksDB`-free -//! environment: -//! -//! | arm | wall time | -//! |--------------------------------------|-----------| -//! | `mega-evm` `EQUIVALENCE` spec | ~1.15 ms | -//! | `mega-evm` `MINI_REX` spec | ~35.9 ms | -//! | vanilla revm | ~1.10 ms | -//! -//! Both specs execute the same 205,951 opcodes and deploy the same 582-byte -//! runtime; the 30× gap between `EQUIVALENCE` and `MINI_REX` comes entirely -//! from the multi-dimensional `AdditionalLimit` accounting (quadratic LOG / -//! compute / storage / data / KV buckets) that `MINI_REX` enables. -//! -//! Pairing the `mega-evm` and `pure_revm` arms gives a hermetic regression -//! target for any limit-tracker / hot-path optimization (e.g. caching -//! `net_usage` in `FrameLimitTracker`). -//! -//! ## Run -//! -//! ```bash -//! cargo bench --bench attack_replay -//! ``` - -#![allow(missing_docs)] - -use std::{ - collections::HashMap, - str::FromStr, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, - }, -}; - -use alloy_primitives::{hex, Address, Bytes, B256, U256}; -use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; -use mega_evm::{ - test_utils::MemoryDatabase, EmptyExternalEnv, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, -}; -use revm::{ - context::{ - result::{ExecResultAndState, ExecutionResult, Output}, - tx::TxEnvBuilder, - TxEnv, - }, - interpreter::{interpreter::EthInterpreter, Interpreter}, - primitives::TxKind, - Context, ExecuteEvm, InspectEvm, Inspector, MainBuilder, MainContext, -}; -use serde_json::Value; - -/// Captured fixture; see `fixtures/known_attack_deploy.json` for provenance. -const FIXTURE_JSON: &str = include_str!("fixtures/known_attack_deploy.json"); - -/// Parsed transaction fields. Kept simple — manual extraction so the fixture -/// can stay free-form JSON without requiring serde feature flags on alloy. -struct TxFixture { - caller: Address, - nonce: u64, - gas_limit: u64, - max_fee_per_gas: u128, - max_priority_fee_per_gas: u128, - value: U256, - chain_id: u64, - input: Bytes, -} - -/// Per-account snapshot entry from `prestateTracer`. -struct AccountFixture { - balance: U256, - nonce: u64, - code: Bytes, - storage: Vec<(B256, U256)>, -} - -/// Block environment captured at the same block as `prestate`. -struct BlockFixture { - number: u64, - timestamp: u64, - base_fee_per_gas: u64, - gas_limit: u64, - beneficiary: Address, - mix_hash: B256, -} - -fn parse_u256(v: &Value) -> U256 { - let s = v.as_str().unwrap(); - if let Some(stripped) = s.strip_prefix("0x") { - U256::from_str_radix(stripped, 16).unwrap() - } else { - U256::from_str_radix(s, 10).unwrap() - } -} - -fn parse_bytes(v: &Value) -> Bytes { - let s = v.as_str().unwrap(); - Bytes::from(hex::decode(s.trim_start_matches("0x")).unwrap()) -} - -fn parse_address(v: &Value) -> Address { - let s = v.as_str().unwrap(); - Address::from_str(s).unwrap() -} - -fn load_fixture() -> (TxFixture, HashMap, BlockFixture) { - let json: Value = serde_json::from_str(FIXTURE_JSON).expect("fixture json parses"); - - let tx_obj = &json["tx"]; - let tx = TxFixture { - caller: parse_address(&tx_obj["caller"]), - nonce: tx_obj["nonce"].as_u64().unwrap(), - gas_limit: tx_obj["gas_limit"].as_u64().unwrap(), - max_fee_per_gas: tx_obj["max_fee_per_gas"].as_u64().unwrap() as u128, - max_priority_fee_per_gas: tx_obj["max_priority_fee_per_gas"].as_u64().unwrap() as u128, - value: parse_u256(&tx_obj["value"]), - chain_id: tx_obj["chain_id"].as_u64().unwrap(), - input: parse_bytes(&tx_obj["input"]), - }; - - let mut prestate = HashMap::new(); - for (addr_str, acc) in json["prestate"].as_object().unwrap() { - let addr = Address::from_str(addr_str).unwrap(); - let balance = acc.get("balance").map(parse_u256).unwrap_or_default(); - let nonce = acc.get("nonce").and_then(|v| v.as_u64()).unwrap_or(0); - let code = acc.get("code").map(parse_bytes).unwrap_or_default(); - let storage: Vec<(B256, U256)> = acc - .get("storage") - .and_then(|s| s.as_object()) - .map(|m| m.iter().map(|(k, v)| (B256::from_str(k).unwrap(), parse_u256(v))).collect()) - .unwrap_or_default(); - prestate.insert(addr, AccountFixture { balance, nonce, code, storage }); - } - - let blk = &json["block"]; - let block = BlockFixture { - number: blk["number"].as_u64().unwrap(), - timestamp: blk["timestamp"].as_u64().unwrap(), - base_fee_per_gas: blk["base_fee_per_gas"].as_u64().unwrap(), - gas_limit: blk["gas_limit"].as_u64().unwrap(), - beneficiary: parse_address(&blk["beneficiary"]), - mix_hash: B256::from_str(blk["mix_hash"].as_str().unwrap()).unwrap(), - }; - - (tx, prestate, block) -} - -/// Build a fresh `MemoryDatabase` populated with the captured prestate. -/// Called inside the per-iteration setup so each measurement starts from -/// the same on-chain state. -fn build_db(prestate: &HashMap) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - for (addr, acc) in prestate { - db.set_account_balance(*addr, acc.balance); - if acc.nonce > 0 { - db.set_account_nonce(*addr, acc.nonce); - } - if !acc.code.is_empty() { - db.set_account_code(*addr, acc.code.clone()); - } - for (slot, value) in &acc.storage { - db.set_account_storage(*addr, (*slot).into(), *value); - } - } - db -} - -/// Build a `MegaContext` from the captured fixture for the given spec. -/// -/// **`chain_id` matters**: leaving the default (1) silently sends `mega-evm` -/// down a short-circuit path that skips most of the limit-tracker work, -/// producing artificially-fast bench numbers (~80 µs vs ~36 ms). The -/// fixture's `chain_id` (4326 = `MegaETH` mainnet) must be threaded through. -fn build_mega_context( - spec: MegaSpecId, - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) -> MegaContext { - let db = build_db(prestate); - let mut ctx = MegaContext::new(db, spec); - ctx.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - // MegaContext derefs to OpContext — cfg lives on the inner context. - ctx.cfg.chain_id = tx_fixture.chain_id; - ctx.modify_block(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }); - ctx -} - -/// Build the `MegaTransaction` for the captured deploy. -fn build_mega_tx(tx: &TxFixture) -> MegaTransaction { - let inner = TxEnvBuilder::new() - .caller(tx.caller) - .create() - .data(tx.input.clone()) - .gas_limit(tx.gas_limit) - .gas_price(tx.max_fee_per_gas) - .gas_priority_fee(Some(tx.max_priority_fee_per_gas)) - .nonce(tx.nonce) - .value(tx.value) - .chain_id(Some(tx.chain_id)) - .build_fill(); - let mut mega_tx = MegaTransaction::new(inner); - // The handler expects `enveloped_tx` to be set for EIP-2718 typed txns, - // but the value isn't consumed by the limit-check / EVM path. Use empty. - mega_tx.enveloped_tx = Some(Bytes::new()); - mega_tx -} - -/// Build a vanilla revm `TxEnv` mirroring the captured fixture. -fn build_revm_tx(tx_fixture: &TxFixture) -> TxEnv { - TxEnv { - caller: tx_fixture.caller, - gas_limit: tx_fixture.gas_limit, - gas_price: tx_fixture.max_fee_per_gas, - gas_priority_fee: Some(tx_fixture.max_priority_fee_per_gas), - kind: TxKind::Create, - value: tx_fixture.value, - data: tx_fixture.input.clone(), - nonce: tx_fixture.nonce, - chain_id: Some(tx_fixture.chain_id), - ..Default::default() - } -} - -/// Minimal `Inspector` that just counts how many opcodes the interpreter -/// executed. Used as a sanity check that the bench is not silently -/// short-circuiting. The count is exposed via a shared atomic so it can be -/// read back after the EVM consumes the inspector by value. -#[derive(Clone, Default)] -struct OpcodeCounter { - steps: Arc, -} - -impl Inspector for OpcodeCounter { - fn step(&mut self, _interp: &mut Interpreter, _ctx: &mut CTX) { - self.steps.fetch_add(1, Ordering::Relaxed); - } -} - -/// Minimum opcode count we expect the deploy to execute. If the bench -/// silently short-circuits (e.g. wrong `chain_id` in setup, validation -/// reject wrapped as `Ok`), step count drops to single digits — assert -/// catches that before users mistake an early-exit for a "fast" bench. -const MIN_EXPECTED_OPCODE_STEPS: u64 = 100_000; - -fn sanity_check_mega( - name: &str, - spec: MegaSpecId, - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) { - // First run: confirm Success variant + inspect deployed output / state. - let ctx = build_mega_context(spec, prestate, block, tx_fixture); - let mut evm = MegaEvm::new(ctx); - let ExecResultAndState { result, state } = - evm.transact(build_mega_tx(tx_fixture)).expect("mega evm.transact ok"); - - let variant = match &result { - ExecutionResult::Success { reason, output, .. } => match output { - Output::Create(code, addr) => format!( - "Success(Create, reason={reason:?}, deployed_code_len={}, addr={:?})", - code.len(), - addr, - ), - Output::Call(data) => { - format!("Success(Call, reason={reason:?}, output_len={})", data.len()) - } - }, - ExecutionResult::Revert { output, .. } => format!("Revert(output_len={})", output.len()), - ExecutionResult::Halt { reason, .. } => format!("Halt({reason:?})"), - }; - let slot_count: usize = state.values().map(|a| a.storage.len()).sum(); - eprintln!( - "sanity[{name}]: gas_used={} variant={} accounts={} storage_slots={}", - result.gas_used(), - variant, - state.len(), - slot_count, - ); - assert!( - result.is_success(), - "deploy did not succeed on {name} — prestate / block env / spec config incomplete: {variant}", - ); - - // Second run: count opcode steps actually executed. Without this, a - // short-circuit (e.g. tx rejected in validation but wrapped as Ok) - // would look like a fast benchmark instead of failing loudly. - let ctx = build_mega_context(spec, prestate, block, tx_fixture); - let counter = OpcodeCounter::default(); - let counter_handle = counter.clone(); - let mut evm = MegaEvm::new(ctx).with_inspector(counter); - let _ = evm.inspect_one_tx(build_mega_tx(tx_fixture)).expect("inspect_one_tx ok"); - let steps = counter_handle.steps.load(Ordering::Relaxed); - eprintln!("sanity[{name}]: opcode_steps={}", steps); - assert!( - steps >= MIN_EXPECTED_OPCODE_STEPS, - "bench appears to short-circuit on {name}: only {steps} opcode steps \ - executed (expected ≥ {MIN_EXPECTED_OPCODE_STEPS}). Check that \ - chain_id and block env are wired correctly.", - ); -} - -fn sanity_check_pure_revm( - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) { - let mut evm = Context::mainnet() - .modify_cfg_chained(|cfg| { - cfg.chain_id = tx_fixture.chain_id; - cfg.disable_balance_check = true; - cfg.disable_base_fee = true; - }) - .modify_block_chained(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }) - .with_db(build_db(prestate)) - .build_mainnet(); - let res = evm.transact_one(build_revm_tx(tx_fixture)).expect("revm transact_one ok"); - let variant = match &res { - ExecutionResult::Success { output: Output::Create(code, _), .. } => { - format!("Success(Create, deployed_code_len={})", code.len()) - } - ExecutionResult::Success { .. } => "Success(non-Create)".to_string(), - ExecutionResult::Revert { output, .. } => format!("Revert(output_len={})", output.len()), - ExecutionResult::Halt { reason, .. } => format!("Halt({reason:?})"), - }; - eprintln!("sanity[pure_revm]: gas_used={} variant={}", res.gas_used(), variant); - assert!( - variant.starts_with("Success(Create"), - "pure revm did not deploy successfully: {variant}", - ); -} - -fn bench_attack_replay(c: &mut Criterion) { - let (tx_fixture, prestate, block) = load_fixture(); - - // Run all sanity checks first so failures abort before criterion warms up. - for (name, spec) in - [("equivalence", MegaSpecId::EQUIVALENCE), ("mini_rex", MegaSpecId::MINI_REX)] - { - sanity_check_mega(name, spec, &prestate, &block, &tx_fixture); - } - sanity_check_pure_revm(&prestate, &block, &tx_fixture); - - let mut group = c.benchmark_group("attack_replay"); - - for (name, spec) in - [("equivalence", MegaSpecId::EQUIVALENCE), ("mini_rex", MegaSpecId::MINI_REX)] - { - group.bench_function(name, |b| { - b.iter_batched( - || { - let ctx = build_mega_context(spec, &prestate, &block, &tx_fixture); - (MegaEvm::new(ctx), build_mega_tx(&tx_fixture)) - }, - |(mut evm, mega_tx)| black_box(evm.transact(black_box(mega_tx))), - BatchSize::SmallInput, - ) - }); - } - - // Apples-to-apples comparison arm: vanilla revm running the same CREATE - // on the same in-memory state. With the bench setup correct, this comes - // back at ~1.1 ms — very close to the `equivalence` arm — which is what - // we expect: same opcodes, similar interpreter overhead. The interesting - // delta is `mini_rex` vs both at ~36 ms, isolating the cost of the - // multi-dimensional `AdditionalLimit` accounting. - // - // Note: vanilla revm doesn't enforce OP-stack rules (L1 data fee, etc.) - // and uses its own SpecId set, but for a self-contained CREATE that - // doesn't touch L1Block / OP-specific precompiles, the opcode-level - // work is the same. - group.bench_function("pure_revm", |b| { - b.iter_batched( - || { - let evm = Context::mainnet() - .modify_cfg_chained(|cfg| { - cfg.chain_id = tx_fixture.chain_id; - cfg.disable_balance_check = true; - cfg.disable_base_fee = true; - }) - .modify_block_chained(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }) - .with_db(build_db(&prestate)) - .build_mainnet(); - (evm, build_revm_tx(&tx_fixture)) - }, - |(mut evm, tx)| black_box(evm.transact_one(black_box(tx))), - BatchSize::SmallInput, - ) - }); - - group.finish(); -} - -criterion_group!(benches, bench_attack_replay); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/block_bench.rs b/crates/mega-evm/benches/block_bench.rs deleted file mode 100644 index d2b019743..000000000 --- a/crates/mega-evm/benches/block_bench.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! Benchmarks for the block executor pipeline. -//! -//! Measures the full production path: `pre_execution_changes` (system contract -//! deployment), transaction execution, and `post_execution_changes`. - -#![allow(missing_docs)] - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, SequencerRegistryConfig, TestExternalEnvs, ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, - ORACLE_CONTRACT_CODE_REX5, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, -}; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, - INITIAL_SYSTEM_ADDRESS, -}; -use revm::{ - bytecode::opcode::{ADD, LOG1, POP, SSTORE}, - context::BlockEnv, - database::State, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); - -/// Create a recovered legacy transaction for block execution. -fn create_call_tx( - nonce: u64, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Create a contract deployment transaction. -fn create_deploy_tx( - nonce: u64, - gas_limit: u64, - init_code: Bytes, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Hardfork schedule coherent with `spec`: everything through the spec's rung is active from -/// genesis, with the params Rex5+ pre-block setup needs. Each benchmark row therefore measures -/// one complete per-spec world — pre-block setup included — matching the executor's rule that -/// setup follows the executing spec. (A REX6+ row would additionally need -/// `SequencerRegistryRex6Config` attached here.) -fn hardforks_for(spec: MegaSpecId) -> MegaHardforkConfig { - let mut config = MegaHardforkConfig::default().with_all_activated_through(spec); - if spec.reaches(MegaSpecId::REX5) { - config = config.with_params(SequencerRegistryConfig { - rex5_initial_sequencer: MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: MEGA_SYSTEM_ADDRESS, - }); - } - config -} - -/// Create block EVM environment. -fn block_evm_env(spec: MegaSpecId) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn rex5_steady_state_db(contract_code: &Bytes) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Predeploy all REX5 system contracts so this benchmark measures the steady-state - // pre-block path instead of repeatedly paying first-deploy cost. - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX5); - db.set_account_code( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - ); - db.set_account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); - db.set_account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); - db.set_account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE); - - // Seed the bootstrap SequencerRegistry slots exactly once so deploy stays idempotent - // and resolve_system_address reads committed steady-state data. - let initial_address = U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SYSTEM_ADDRESS, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SEQUENCER, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_FROM_BLOCK, U256::from(1000)); - - db -} - -/// Simple contract: just STOPs. -fn empty_contract() -> Bytes { - BytecodeBuilder::default().stop().build() -} - -/// Contract that does 10 SSTOREs + 5 LOG1s + 50 ADDs. -fn mixed_contract() -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..10u64 { - builder = builder.push_number(i + 1).push_number(i).append(SSTORE); - } - for _ in 0..5 { - builder = builder.push_number(0xbeef_u64).push_number(32u64).push_number(0u64).append(LOG1); - } - for _ in 0..50 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.stop().build() -} - -// -// ============================================================================ -// Block Executor Pipeline Benchmarks -// ============================================================================ -// - -/// Benchmark a complete block with N empty transactions. -fn bench_block_empty_txs(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_empty_txs"); - group.sample_size(10); - - let contract_code = empty_contract(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - for n_txs in [1, 10, 50] { - group.bench_function(format!("{spec_name}/{n_txs}_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..n_txs { - let tx = create_call_tx(i, 1_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - } - group.finish(); -} - -/// Benchmark a complete block with N mixed workload transactions. -fn bench_block_mixed_txs(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_mixed_txs"); - group.sample_size(10); - - let contract_code = mixed_contract(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - for n_txs in [1, 10] { - group.bench_function(format!("{spec_name}/{n_txs}_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..n_txs { - let tx = create_call_tx(i, 10_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - } - group.finish(); -} - -/// Benchmark contract deployment through the block executor. -fn bench_block_deploy(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_deploy"); - group.sample_size(10); - - // Init code that deploys a small runtime: PUSH1 0x00 PUSH1 0x00 RETURN - let init_code: Bytes = vec![0x60, 0x00, 0x60, 0x00, 0xf3].into(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - group.bench_function(format!("{spec_name}/deploy_1"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - let nonce = 0u64; - let tx = create_deploy_tx(nonce, 10_000_000, init_code.clone()); - let gas = executor.execute_transaction(&tx).expect("deploy should succeed"); - black_box(gas); - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - group.finish(); -} - -/// Benchmark spec comparison for block execution. -/// -/// NOTE: Each spec runs against its own coherent world (`hardforks_for(spec)`), pre-block -/// setup included: `EQUIVALENCE` deploys nothing while `REX5` bootstraps its predeploys and -/// registry inside every iteration. Rows therefore compare whole-block costs per spec, not -/// isolated EVM execution deltas — for the latter, the cross-spec compute-gas snapshot -/// (`tests/compute_gas/`) is the tool. -fn bench_block_spec_comparison(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_spec_comparison"); - group.sample_size(10); - - let contract_code = mixed_contract(); - let specs: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - ]; - - for &(spec_name, spec) in specs { - group.bench_function(format!("{spec_name}/5_mixed_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..5u64 { - let tx = create_call_tx(i, 10_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - group.finish(); -} - -/// Benchmark the full REX5 pre-block path. -/// -/// `bootstrap` starts from an empty DB and pays first-deploy cost for the REX5 system contracts. -/// `no_change` starts from a steady-state DB where all deploy-only contracts already exist and -/// the `SequencerRegistry` has no pending changes. -fn bench_rex5_pre_block(c: &mut Criterion) { - let mut group = c.benchmark_group("rex5_pre_block"); - group.sample_size(10); - - let contract_code = empty_contract(); - let spec = MegaSpecId::REX5; - - // Bootstrap block: first REX5 pre-block on an empty state. - group.bench_function("bootstrap", |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - black_box(()); - }) - }); - - // Steady-state block: all deploy-only system contracts already exist and the registry has no - // pending changes. - group.bench_function("no_change", |b| { - let baseline_db = rex5_steady_state_db(&contract_code); - - b.iter(|| { - let mut db = baseline_db.clone(); - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - black_box(()); - }) - }); - - group.finish(); -} - -/// Benchmark hardfork-config resolution on the real mainnet schedule. -/// -/// The position-projected predicates (`is_rex_5_active_at_timestamp`) are what downstream node -/// components call once per block; `spec_id` is the executor's per-block resolution; -/// `validate_schedule` is a once-per-config-load cost. Resolution's descending early-exit scan -/// keeps the per-query cost at one or two activation lookups for chains near the top of the -/// ladder, which this benchmark pins. -fn bench_hardfork_resolution(c: &mut Criterion) { - use mega_evm::MegaHardforks; - - let mut group = c.benchmark_group("hardfork_resolution"); - let schedule = mega_evm::mainnet_hardforks(); - // A timestamp after the last scheduled fork: every real query happens here. - let ts = 1_800_000_000u64; - - group.bench_function("is_rex_5_active_at_timestamp", |b| { - b.iter(|| black_box(schedule.is_rex_5_active_at_timestamp(black_box(ts)))) - }); - group.bench_function("spec_id", |b| b.iter(|| black_box(schedule.spec_id(black_box(ts))))); - group.bench_function("validate_schedule", |b| { - b.iter(|| black_box(schedule.validate_schedule())) - }); - - group.finish(); -} - -criterion_group!( - benches, - bench_block_empty_txs, - bench_block_mixed_txs, - bench_block_deploy, - bench_block_spec_comparison, - bench_rex5_pre_block, - bench_hardfork_resolution, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/common/mod.rs b/crates/mega-evm/benches/common/mod.rs deleted file mode 100644 index 0d75c1c70..000000000 --- a/crates/mega-evm/benches/common/mod.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Shared bench harness comparing mega-evm against vanilla revm and op-revm. -//! -//! A bench declares a backend-agnostic [`Workload`] (accounts + transactions) -//! and registers it across a fixed set of [`Subject`](subject::Subject) rows: -//! the four vanilla baselines (`revm_pinned`, `revm_latest`, `op_revm_pinned`, -//! `op_revm_latest`) and the mega specs. Every row runs the same scenario, so a -//! single criterion group yields a comparable gap table. -//! -//! Bench files pull this in with a plain `mod common;` (resolved via the -//! standard `common/mod.rs` sibling-folder lookup). Each criterion bench target -//! compiles as its own binary, so this module is compiled once per target. - -#![allow(dead_code)] // each bench target uses a subset of the harness -#![allow(unreachable_pub)] // included as a shared bench module, so `pub` items appear unreachable in lint terms - -pub mod subject; -pub mod workload; - -use core::convert::Infallible; - -use mega_evm::{MegaSpecId, TestExternalEnvs}; -pub use subject::MegaWithEnv; -use subject::{Mega, OpRevmLatest, OpRevmPinned, RevmLatest, RevmPinned, Subject}; -pub use workload::{Account, TxSpec, Workload}; - -/// Mega specs registered by [`register_all`] and [`register_mega`]. Shared so -/// every bench file emits the same mega rows. Benches needing a different set -/// (single spec, SELFDESTRUCT-relevant specs, …) pass their own list to -/// [`register_mega_specs`]. -pub const SPEC_IDS: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - // REX5 vs REX6 isolates the cost of the unified gas-metering order: REX6 routes the - // storage-affecting opcodes (SSTORE, CALL, etc.) through the canonical - // charge-storage / run-body / record-compute-once path. - ("rex6", MegaSpecId::REX6), - // Rex7 delegates to Rex6 entirely, so the pair reads as a no-op today. It is registered from - // the spec's first day anyway: this is the frozen baseline every later Rex7 measurement is - // compared against, and a row added only once Rex7 has behavior would arrive with nothing to - // compare to. - ("rex7", MegaSpecId::REX7), -]; - -type Group<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>; - -fn baseline_subjects() -> Vec> { - vec![Box::new(RevmPinned), Box::new(RevmLatest), Box::new(OpRevmPinned), Box::new(OpRevmLatest)] -} - -fn mega_subjects(specs: &[(&'static str, MegaSpecId)]) -> Vec> { - specs.iter().map(|&(name, spec)| Box::new(Mega { name, spec }) as Box).collect() -} - -/// Run each subject as one row of `group`, named `` or, when `variant` -/// is non-empty, `/` (e.g. `revm_pinned/log0_32b`) so every -/// row shares a single variant axis. -fn run_subjects(group: &mut Group<'_>, variant: &str, w: &Workload, subjects: &[Box]) { - for subject in subjects { - let row = if variant.is_empty() { - subject.name().to_string() - } else { - format!("{}/{variant}", subject.name()) - }; - group.bench_function(row, |b| b.iter(|| subject.run(w))); - } -} - -/// Register the four baselines plus the [`SPEC_IDS`] mega rows. -pub fn register_all(group: &mut Group<'_>, w: &Workload) { - register_all_suffixed(group, "", w); -} - -/// [`register_all`] with a `/variant` suffix on every row. -pub fn register_all_suffixed(group: &mut Group<'_>, variant: &str, w: &Workload) { - let mut subjects = baseline_subjects(); - subjects.extend(mega_subjects(SPEC_IDS)); - run_subjects(group, variant, w, &subjects); -} - -/// Register only the [`SPEC_IDS`] mega rows (no vanilla baselines). -pub fn register_mega(group: &mut Group<'_>, w: &Workload) { - register_mega_suffixed(group, "", w); -} - -/// [`register_mega`] with a `/variant` suffix on every row. -pub fn register_mega_suffixed(group: &mut Group<'_>, variant: &str, w: &Workload) { - run_subjects(group, variant, w, &mega_subjects(SPEC_IDS)); -} - -/// Register mega rows for a caller-supplied spec list (e.g. a single spec, or -/// the SELFDESTRUCT-relevant specs). -pub fn register_mega_specs( - group: &mut Group<'_>, - specs: &[(&'static str, MegaSpecId)], - w: &Workload, -) { - register_mega_specs_suffixed(group, specs, "", w); -} - -/// [`register_mega_specs`] with a `/variant` suffix on every row. -pub fn register_mega_specs_suffixed( - group: &mut Group<'_>, - specs: &[(&'static str, MegaSpecId)], - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &mega_subjects(specs)); -} - -/// Register three isolation rows for one spec + workload under a `/variant` -/// suffix, in order: -/// -/// 1. `revm_pinned` — the env-agnostic absolute floor (no mega overhead). -/// 2. `baseline_name` — `Mega` over `EmptyExternalEnv`, where the external-env path (SALT / oracle) -/// short-circuits to constants (no hash, no map lookup). -/// 3. `active_name` — `MegaWithEnv` over the supplied `env`, exercising the real external-env path -/// (e.g. crowded SALT buckets or oracle storage). -/// -/// The `active_name` − `baseline_name` gap isolates the external-env path cost -/// while holding spec and workload fixed. Shared by the SALT and oracle benches. -pub fn register_env_isolation( - group: &mut Group<'_>, - spec: MegaSpecId, - baseline_name: &'static str, - active_name: &'static str, - env: TestExternalEnvs, - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &[Box::new(RevmPinned)]); - run_subjects(group, variant, w, &[Box::new(Mega { name: baseline_name, spec })]); - run_subjects(group, variant, w, &[Box::new(MegaWithEnv { name: active_name, spec, env })]); -} - -/// Like [`register_env_isolation`] but omits the `revm_pinned` floor row. -/// -/// Use this to register more than one spec's env-isolation rows in the SAME -/// group: call [`register_env_isolation`] for the first spec (registering the -/// shared `revm_pinned` floor plus that spec's baseline + active env rows), -/// then call this floor-less variant for each additional spec. The -/// `revm_pinned` row must appear only once per group — registering it twice -/// panics with a duplicate benchmark-id error. -pub fn register_env_isolation_mega_only( - group: &mut Group<'_>, - spec: MegaSpecId, - baseline_name: &'static str, - active_name: &'static str, - env: TestExternalEnvs, - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &[Box::new(Mega { name: baseline_name, spec })]); - run_subjects(group, variant, w, &[Box::new(MegaWithEnv { name: active_name, spec, env })]); -} diff --git a/crates/mega-evm/benches/common/subject.rs b/crates/mega-evm/benches/common/subject.rs deleted file mode 100644 index d3dc946a9..000000000 --- a/crates/mega-evm/benches/common/subject.rs +++ /dev/null @@ -1,443 +0,0 @@ -//! Benchmark subjects: one per EVM stack being compared. -//! -//! A [`Subject`] turns a backend-agnostic [`Workload`] into a concrete run on -//! its own stack. The shared loop/assert/measure skeleton lives once in -//! [`run_workload`]; each subject only supplies how to *build* its EVM and how -//! to *execute* one tx, so the success assertion can never drift between stacks. -//! -//! What makes the vanilla rows comparable — the target hardfork and the -//! operator-fee zero-out — is defined once in the "Comparability baseline" -//! section below, not repeated per stack. -//! -//! `_latest` types come from a cargo `package` rename in `Cargo.toml`. Both -//! `_latest` subjects share one revm tree because the chosen `op-revm` version -//! already pulls the chosen `revm` version transitively. - -use alloy_primitives::{Address, Bytes, U256}; -use core::convert::Infallible; -use criterion::black_box; -use mega_evm::{ - revm::inspector::NoOpInspector, test_utils::MemoryDatabase, EmptyExternalEnv, MegaContext, - MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, -}; -use op_revm::{ - DefaultOp as _, OpBuilder as _, OpContext as OpContextPinned, OpSpecId as OpSpecIdPinned, - OpTransaction as OpTransactionPinned, -}; -use op_revm_latest::{ - DefaultOp as _, OpBuilder as _, OpContext as OpContextLatest, OpSpecId as OpSpecIdLatest, - OpTransaction as OpTransactionLatest, -}; -use revm::{ - context::{tx::TxEnvBuilder, TxEnv}, - database::EmptyDB as EmptyDBPinned, - primitives::hardfork::SpecId as SpecIdPinned, - Context as ContextPinned, ExecuteEvm, MainBuilder as _, MainContext as _, -}; -use revm_latest::{ - bytecode::Bytecode as BytecodeLatest, - context::{tx::TxEnvBuilder as TxEnvBuilderLatest, TxEnv as TxEnvLatest}, - database::{CacheDB as CacheDBLatest, EmptyDB as EmptyDBLatest}, - primitives::hardfork::SpecId as SpecIdLatest, - Context as ContextLatest, ExecuteEvm as _, MainBuilder as _, MainContext as _, -}; -use std::{cell::RefCell, rc::Rc}; - -use super::workload::{Account, TxSpec, Workload}; - -// -// ============================================================================ -// Comparability baseline — single source of truth for what makes the vanilla -// rows comparable. Change a value here and every baseline moves together; CI's -// baseline-gap table assumes the rows all sit on one fork. -// ============================================================================ -// - -/// Target hardfork for the vanilla `revm` rows. Cancun keeps every baseline on -/// one fork and predates EIP-7825's `tx_gas_limit_cap` (2^24), so the -/// multi-gigagas `gas_limit` workloads are not truncated. (`revm_latest`'s -/// `MainContext::mainnet()` would otherwise default to Osaka and trip the cap.) -const REVM_FORK: SpecIdPinned = SpecIdPinned::CANCUN; -const REVM_FORK_LATEST: SpecIdLatest = SpecIdLatest::CANCUN; - -/// Target hardfork for the op rows. Holocene maps to eth Cancun, matching the -/// `revm` rows above. Needed because `DefaultOp::op()` hard-codes `BEDROCK` -/// (eth Merge) regardless of the enum default — without this the op rows would -/// sit on a different fork and the op-vs-revm gap would reflect a hardfork -/// difference rather than a version one. -const OP_FORK: OpSpecIdPinned = OpSpecIdPinned::HOLOCENE; -const OP_FORK_LATEST: OpSpecIdLatest = OpSpecIdLatest::HOLOCENE; - -/// Zero the operator fee so the op and mega rows are comparable to the revm -/// rows, which carry no such fee. A macro rather than a fn: the three `chain` -/// types come from distinct crates (op-revm pinned/latest, mega-evm) and share -/// no common trait — only the field names line up. -macro_rules! zero_operator_fee { - ($chain:expr) => {{ - $chain.operator_fee_scalar = Some(U256::ZERO); - $chain.operator_fee_constant = Some(U256::ZERO); - }}; -} - -// -// ============================================================================ -// Subject trait + shared run skeleton. -// ============================================================================ -// - -/// One row of a criterion group — a specific EVM stack at a specific config. -pub trait Subject { - /// Row name as it appears in the criterion group (e.g. `revm_pinned`). - fn name(&self) -> &str; - /// Build a fresh DB + EVM from the workload, run every tx on that one - /// reused instance, and (unless the workload opts out) assert each - /// succeeds. Implementations delegate to [`run_workload`]. - fn run(&self, workload: &Workload); -} - -/// The one place the per-tx loop, success assertion, and `black_box` live. -/// -/// `build` constructs the (stack-specific) EVM once; `exec` runs a single tx -/// and returns its `is_success()`. Keeping the skeleton here means the success -/// check can never drift or be forgotten on one stack — the bug that the old -/// per-stack `run` bodies were prone to. The generic `E` is inferred from -/// `build`, so no stack has to spell out its verbose revm `Evm<…>` type. -/// -/// On failure the panic names the row and tx index; the concrete result is not -/// surfaced because `exec` has already abstracted away the stack's distinct -/// `ExecutionResult` type (it `black_box`es the result for the optimizer). -fn run_workload( - name: &str, - workload: &Workload, - build: impl FnOnce() -> E, - exec: impl Fn(&mut E, &TxSpec) -> bool, -) { - let mut evm = build(); - for (i, tx) in workload.txs.iter().enumerate() { - let success = exec(&mut evm, tx); - if workload.assert_success { - assert!(success, "{name} tx #{i} should succeed"); - } - } -} - -// -// ============================================================================ -// Database builders — written once, fed to every subject of each stack. -// ============================================================================ -// - -/// Seed a pinned-revm `MemoryDatabase` from the workload accounts. Shared by -/// the `*_pinned` baselines and every `mega_*` subject. -fn build_pinned_db(accounts: &[Account]) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - for account in accounts { - db = db.account_balance(account.address, account.balance); - if let Some(code) = &account.code { - db = db.account_code(account.address, code.clone()); - } - for (slot, value) in &account.storage { - db = db.account_storage(account.address, *slot, *value); - } - } - db -} - -/// Seed a latest-revm `CacheDB` from the workload accounts. Shared by both -/// `*_latest` baselines. -fn build_latest_db(accounts: &[Account]) -> CacheDBLatest { - let mut builder = LatestDbBuilder::new(); - for account in accounts { - builder = builder.account_balance(account.address, account.balance); - if let Some(code) = &account.code { - builder = builder.account_code(account.address, code.clone()); - } - for (slot, value) in &account.storage { - builder = builder.account_storage(account.address, *slot, *value); - } - } - builder.build() -} - -/// Translate a [`TxSpec`] into a pinned-revm `TxEnv`, used by the `revm_pinned`, -/// `op_revm_pinned`, and `mega_*` subjects (mega-evm re-exports the same pinned -/// revm crate). -fn pinned_tx_env(tx: &TxSpec) -> TxEnv { - TxEnvBuilder::new() - .caller(tx.caller) - .call(tx.target) - .gas_limit(tx.gas_limit) - .value(tx.value) - .data(tx.data.clone()) - .build_fill() -} - -/// Translate a [`TxSpec`] into a latest-revm `TxEnv`. -fn latest_tx_env(tx: &TxSpec) -> TxEnvLatest { - TxEnvBuilderLatest::new() - .caller(tx.caller) - .call(tx.target) - .gas_limit(tx.gas_limit) - .value(tx.value) - .data(tx.data.clone()) - .build_fill() -} - -// -// ============================================================================ -// Mega subject. -// ============================================================================ -// - -/// `MegaEvm` at a single spec. One instance per benchmarked spec. -pub struct Mega { - pub name: &'static str, - pub spec: MegaSpecId, -} - -impl Subject for Mega { - fn name(&self) -> &str { - self.name - } - - fn run(&self, workload: &Workload) { - let spec = self.spec; - run_workload( - self.name, - workload, - || { - let mut context = MegaContext::new(build_pinned_db(&workload.accounts), spec); - context.modify_chain(|chain| zero_operator_fee!(chain)); - MegaEvm::<_, NoOpInspector, EmptyExternalEnv>::new(context) - }, - |evm, tx| { - // Wrap into a `MegaTransaction` with an empty envelope, matching - // what the production tx-pool would attach. - let mut mega_tx = MegaTransaction::new(pinned_tx_env(tx)); - mega_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(mega_tx).expect("mega transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// MegaWithEnv subject. -// ============================================================================ -// - -/// `MegaEvm` at a single spec over a configurable `TestExternalEnvs` (crowded -/// SALT buckets and/or oracle storage). Used by the SALT and oracle benches. -/// The `env` is cloned per build so each iteration starts from the same config. -pub struct MegaWithEnv { - pub name: &'static str, - pub spec: MegaSpecId, - pub env: TestExternalEnvs, -} - -impl Subject for MegaWithEnv { - fn name(&self) -> &str { - self.name - } - - fn run(&self, workload: &Workload) { - let spec = self.spec; - let env = self.env.clone(); - run_workload( - self.name, - workload, - || { - let db = build_pinned_db(&workload.accounts); - let salt = Rc::new(env.clone()); - let oracle = Rc::new(RefCell::new(env.clone())); - let mut context = MegaContext::new_with_ext_envs(db, spec, salt, oracle); - context.modify_chain(|chain| zero_operator_fee!(chain)); - MegaEvm::<_, NoOpInspector, TestExternalEnvs>::new(context) - }, - |evm, tx| { - let mut mega_tx = MegaTransaction::new(pinned_tx_env(tx)); - mega_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(mega_tx).expect("mega transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// Baseline subjects. Fork pins and the operator-fee zero-out come from the -// Comparability baseline section above. -// ============================================================================ -// - -/// Vanilla `revm` at the version mega-evm currently pins (fork: [`REVM_FORK`]). -pub struct RevmPinned; - -impl Subject for RevmPinned { - fn name(&self) -> &str { - "revm_pinned" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - ContextPinned::mainnet() - .modify_cfg_chained(|cfg| cfg.spec = REVM_FORK) - .with_db(build_pinned_db(&workload.accounts)) - .build_mainnet() - }, - |evm, tx| { - let r = evm.transact(pinned_tx_env(tx)).expect("revm_pinned transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// Vanilla `revm` at the latest crates.io release (fork: [`REVM_FORK_LATEST`]). -pub struct RevmLatest; - -impl Subject for RevmLatest { - fn name(&self) -> &str { - "revm_latest" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - ContextLatest::mainnet() - .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(REVM_FORK_LATEST)) - .with_db(build_latest_db(&workload.accounts)) - .build_mainnet() - }, - |evm, tx| { - let r = evm.transact(latest_tx_env(tx)).expect("revm_latest transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// `op-revm` at the version mega-evm currently pins (fork: [`OP_FORK`], -/// operator fee = 0). -pub struct OpRevmPinned; - -impl Subject for OpRevmPinned { - fn name(&self) -> &str { - "op_revm_pinned" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - let mut ctx = >::op() - .with_db(build_pinned_db(&workload.accounts)); - ctx.modify_cfg(|cfg| cfg.spec = OP_FORK); - ctx.modify_chain(|chain| zero_operator_fee!(chain)); - ctx.build_op() - }, - |evm, tx| { - let mut op_tx = OpTransactionPinned::new(pinned_tx_env(tx)); - op_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(op_tx).expect("op_revm_pinned transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// `op-revm` at the latest crates.io release (fork: [`OP_FORK_LATEST`], -/// operator fee = 0). -pub struct OpRevmLatest; - -impl Subject for OpRevmLatest { - fn name(&self) -> &str { - "op_revm_latest" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - let mut ctx = >::op() - .with_db(build_latest_db(&workload.accounts)); - ctx.modify_cfg(|cfg| cfg.spec = OP_FORK_LATEST); - ctx.modify_chain(|chain| zero_operator_fee!(chain)); - ctx.build_op() - }, - |evm, tx| { - let mut op_tx = OpTransactionLatest::new(latest_tx_env(tx)); - op_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(op_tx).expect("op_revm_latest transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// CacheDB builder for the latest revm stack. -// ============================================================================ -// - -/// Fluent builder for a `CacheDB` from the latest revm stack, mirroring -/// `MemoryDatabase`'s API so [`build_latest_db`] can seed it the same way -/// [`build_pinned_db`] seeds the pinned database. -#[derive(Default)] -struct LatestDbBuilder { - db: CacheDBLatest, -} - -impl LatestDbBuilder { - fn new() -> Self { - Self { db: CacheDBLatest::new(EmptyDBLatest::default()) } - } - - fn account_code(mut self, address: Address, code: Bytes) -> Self { - let bytecode = BytecodeLatest::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.info.code = Some(bytecode); - entry.info.code_hash = code_hash; - self - } - - fn account_balance(mut self, address: Address, balance: U256) -> Self { - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.info.balance = balance; - self - } - - fn account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.storage.insert(slot, value); - self - } - - fn build(self) -> CacheDBLatest { - self.db - } -} diff --git a/crates/mega-evm/benches/common/workload.rs b/crates/mega-evm/benches/common/workload.rs deleted file mode 100644 index 0d234bd78..000000000 --- a/crates/mega-evm/benches/common/workload.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Backend-agnostic description of a bench scenario. -//! -//! A [`Workload`] names the accounts to seed and the transactions to run, -//! without referring to any particular revm version or EVM type. Each -//! [`Subject`](crate::common::subject::Subject) translates the same `Workload` -//! into its own stack, so a scenario is written once and compared across every -//! row of a criterion group. - -use alloy_primitives::{Address, Bytes, U256}; - -/// A single account to seed into the database before a workload runs. -/// -/// Built fluently: `Account::new(addr).balance(b).code(c).storage(slot, v)`. -/// Omitted fields default to zero balance, no code, and no storage — an -/// `Account` with all defaults still forces the account to exist, which differs -/// from leaving it out of the workload entirely. -#[derive(Clone)] -pub struct Account { - pub address: Address, - pub balance: U256, - pub code: Option, - pub storage: Vec<(U256, U256)>, -} - -impl Account { - pub fn new(address: Address) -> Self { - Self { address, balance: U256::ZERO, code: None, storage: Vec::new() } - } - - pub fn balance(mut self, balance: U256) -> Self { - self.balance = balance; - self - } - - pub fn code(mut self, code: Bytes) -> Self { - self.code = Some(code); - self - } - - pub fn storage(mut self, slot: U256, value: U256) -> Self { - self.storage.push((slot, value)); - self - } -} - -/// A single `transact()` call, backend-agnostic. Mirrors the minimal set of -/// fields every adapter needs; kept deliberately small so it does not tie the -/// abstraction to one revm version's `TxEnv` (the pinned and latest stacks are -/// separate crates and each translates this into its own envelope). -#[derive(Clone)] -pub struct TxSpec { - pub caller: Address, - pub target: Address, - pub gas_limit: u64, - pub value: U256, - pub data: Bytes, -} - -impl TxSpec { - /// A call from `caller` to `target` with a 30M gas limit, no value, no data. - pub fn call(caller: Address, target: Address) -> Self { - Self { caller, target, gas_limit: 30_000_000, value: U256::ZERO, data: Bytes::new() } - } - - pub fn gas_limit(mut self, gas_limit: u64) -> Self { - self.gas_limit = gas_limit; - self - } - - pub fn value(mut self, value: U256) -> Self { - self.value = value; - self - } - - pub fn data(mut self, data: Bytes) -> Self { - self.data = data; - self - } -} - -/// A complete bench scenario: the accounts to seed and the transactions to run. -/// -/// Single-shot benches pass one tx via [`Workload::single`]; `transfer_multi` -/// passes the whole batch and a subject loops over it on one reused EVM. -#[derive(Clone)] -pub struct Workload { - pub accounts: Vec, - pub txs: Vec, - /// When `true` (the default) every subject asserts each tx returns a - /// successful result. Set to `false` via [`Workload::allow_halt`] for - /// scenarios that legitimately halt under some specs (e.g. SELFDESTRUCT - /// disabled, or DELEGATECALL falling through to absent bytecode). - pub assert_success: bool, -} - -impl Workload { - pub fn new(accounts: Vec, txs: Vec) -> Self { - Self { accounts, txs, assert_success: true } - } - - /// A workload running a single transaction. - pub fn single(accounts: Vec, tx: TxSpec) -> Self { - Self::new(accounts, vec![tx]) - } - - /// Opt out of the per-tx `is_success()` assertion. Use for scenarios where - /// halting is the expected outcome under at least one benchmarked spec. - /// - /// The relaxed check accepts *any* non-success result — a revert as well as - /// a halt — not only halts; the name reflects the intended use rather than a - /// revert-vs-halt distinction. - pub fn allow_halt(mut self) -> Self { - self.assert_success = false; - self - } -} diff --git a/crates/mega-evm/benches/comp_cost.rs b/crates/mega-evm/benches/comp_cost.rs deleted file mode 100644 index 141332c71..000000000 --- a/crates/mega-evm/benches/comp_cost.rs +++ /dev/null @@ -1,1130 +0,0 @@ -//! Benchmarks for CPU-intensive EVM opcodes and precompiles. -//! -//! This benchmark suite measures the computational cost of various EVM operations -//! to understand their real-world performance characteristics across different -//! EVM specifications (`EQUIVALENCE` vs `MINI_REX`). -//! -//! The benchmarks are organized into several categories: -//! - Cryptographic hash operations (KECCAK256, SHA256, BLAKE2F) -//! - Arithmetic operations (EXP, ADDMOD, MULMOD, DIV, etc.) -//! - Elliptic curve precompiles (ECRECOVER, ECADD, ECMUL, ECPAIRING) -//! - Modular exponentiation (MODEXP) - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{ADD, ADDRESS, EXP, GAS, KECCAK256, POP, STATICCALL}, - context::{ - result::{ExecResultAndState, ExecutionResult}, - tx::TxEnvBuilder, - }, - precompile::{ - blake2, bls12_381, bn128, - hash::{RIPEMD160, SHA256}, - kzg_point_evaluation, modexp, - secp256k1::ECRECOVER, - }, - primitives::hardfork::SpecId, - Context as RevmContext, ExecuteEvm, MainBuilder as _, MainContext as _, -}; -use sha2::{Digest, Sha256 as Sha256Hash}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -/// Specification IDs to benchmark against. REX5 is included so the precompile -/// hot path (compute-gas cap + Gas normalization in `PrecompilesMap::run`) is -/// measured against the pre-REX5 baseline. -const SPEC_IDS: &[(&str, MegaSpecId)] = &[ - // ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex5", MegaSpecId::REX5), -]; - -// -// ============================================================================ -// Common Utility Functions -// ============================================================================ -// - -/// Execute bytecode with the given spec and return the transaction execution result. -fn execute_bytecode( - bytecode: &Bytes, - spec: MegaSpecId, -) -> ExecResultAndState> { - let db = MemoryDatabase::default() - .account_code(CONTRACT, bytecode.clone()) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(10_000_000_000u64).build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let r = evm.transact(mega_tx).expect("transaction should succeed"); - assert!(r.result.is_success(), "transaction should succeed: {:?}", r.result); - assert!(r.result.gas_used() > 21000, "transaction should spend more than 21000 gas"); - r -} - -/// Execute bytecode with the given spec and return gas used. -fn execute_and_get_gas(bytecode: &Bytes, spec: MegaSpecId) -> u64 { - execute_bytecode(bytecode, spec).result.gas_used() -} - -/// Run `bytecode` on vanilla revm at PRAGUE (has all precompiles incl. BLS12-381, -/// no EIP-7825 tx-gas cap). The no-mega floor for precompile benchmarks. -/// -/// Mirrors `execute_bytecode`'s measurement boundary: the full execution result is -/// kept alive through `black_box` before being dropped, so the optimizer cannot -/// elide result construction for the revm row while keeping it for the mega rows — -/// an asymmetry that would underestimate the revm floor and inflate the gap. -fn execute_bytecode_revm(bytecode: &Bytes) -> bool { - let db = MemoryDatabase::default() - .account_code(CONTRACT, bytecode.clone()) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - let mut evm = RevmContext::mainnet() - .modify_cfg_chained(|cfg| cfg.spec = SpecId::PRAGUE) - .with_db(db) - .build_mainnet(); - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(10_000_000_000u64).build_fill(); - let r = evm.transact(tx).expect("revm transact"); - assert!(r.result.is_success(), "revm precompile bench tx should succeed: {:?}", r.result); - let success = r.result.is_success(); - black_box(r); - success -} - -/// Print gas for each spec, then bench a `revm_pinned` row and one row per spec. -/// -/// The `revm_pinned` row runs vanilla revm at PRAGUE — the no-mega floor. -/// One row per `SPEC_IDS` entry follows so the mega-vs-revm gap is visible. -fn bench_precompile_group(c: &mut Criterion, group_name: &str, bytecode: Bytes) { - let mut group = c.benchmark_group(group_name); - println!("\n=== Gas consumption for {group_name} ==="); - for &(spec_name, spec) in SPEC_IDS { - println!(" {spec_name} spec: {} gas", execute_and_get_gas(&bytecode, spec)); - } - println!(); - group.bench_function("revm_pinned", |b| { - b.iter(|| black_box(execute_bytecode_revm(black_box(&bytecode)))) - }); - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - group.finish(); -} - -// -// ============================================================================ -// Simple Opcodes -// ============================================================================ -// - -fn generate_add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(1_u64); - builder = builder.push_number(2_u64); - builder = builder.append(ADD); - builder = builder.append(POP); - } - builder.build() -} - -/// Benchmark ADD opcode. -fn bench_add_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - let mut group = c.benchmark_group("add"); - let bytecode = generate_add_bytecode(ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for add ({}x iterations) ===", ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - group.finish(); -} - -fn generate_address_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(ADDRESS); - builder = builder.append(POP); - } - builder.build() -} - -/// Benchmark ADDRESS opcode. -fn bench_address_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - let mut group = c.benchmark_group("address"); - let bytecode = generate_address_bytecode(ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for address ({}x iterations) ===", ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); -} - -// -// ============================================================================ -// KECCAK256 Benchmarks -// ============================================================================ -// - -/// Generate bytecode that benchmarks KECCAK256 opcode with specified data size. -fn generate_keccak256_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - // Call KECCAK256 multiple times - for _ in 0..iterations { - builder = builder.push_number(data_size as u64); // size - builder = builder.push_number(0_u64); // offset - builder = builder.append(KECCAK256); - builder = builder.append(POP); // remove hash result from stack - } - - builder.build() -} - -/// Benchmark KECCAK256 opcode with varying data sizes. -fn bench_keccak256_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - let mut group = c.benchmark_group(format!("keccak256_{}", size_name)); - let bytecode = generate_keccak256_bytecode(data_size, ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!( - "\n=== Gas consumption for keccak256_{} ({}x iterations) ===", - size_name, ITERATIONS - ); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); - } -} - -// -// ============================================================================ -// EXP (Exponentiation) Benchmarks -// ============================================================================ -// - -/// Generate bytecode that benchmarks EXP opcode with specified exponent size. -fn generate_exp_bytecode(exponent_bits: u32, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Create an exponent with the specified number of bits set - let exponent = if exponent_bits == 256 { - U256::MAX - } else if exponent_bits == 0 { - U256::ZERO - } else { - (U256::from(1) << exponent_bits) - U256::from(1) - }; - - let base = U256::from(3); // Use 3 as base for exponentiation - - // Call EXP multiple times - for _ in 0..iterations { - builder = builder.push_u256(exponent); - builder = builder.push_u256(base); - builder = builder.append(EXP); - builder = builder.append(POP); // remove result from stack - } - - builder.build() -} - -/// Benchmark EXP opcode with varying exponent sizes. -fn bench_exp_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("256bit", 256)]; - - for (size_name, exponent_bits) in test_cases { - let mut group = c.benchmark_group(format!("exp_{}", size_name)); - let bytecode = generate_exp_bytecode(exponent_bits, ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for exp_{} ({}x iterations) ===", size_name, ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); - } -} - -// -// ============================================================================ -// ECRECOVER Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECRECOVER precompile. -fn generate_ecrecover_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECRECOVER input (hash, v, r, s) - let r = bytes!("0x9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac8038825608"); - let s = bytes!("0x4f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada"); - let v = U256::from(28); - let hash = bytes!("0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3"); - let _signer = address!("0x7156526fbd7a3c72969b54f64e42c10fbb768c8a"); - - // Store input data in memory - builder = builder.mstore(0, hash); // hash at offset 0 - builder = builder.mstore(32, v.to_be_bytes_vec()); // v at offset 32 - builder = builder.mstore(64, &r); // r at offset 64 - builder = builder.mstore(96, &s); // s at offset 96 - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (hash + v + r + s = 128 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*ECRECOVER.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); // remove success flag - } - - builder.build() -} - -/// Benchmark ECRECOVER precompile. -fn bench_ecrecover_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecrecover", generate_ecrecover_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// SHA256 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls SHA256 precompile. -fn generate_sha256_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (SHA256 outputs 32 bytes) - builder = builder.push_number(data_size as u64 + 32); // retOffset - builder = builder.push_number(data_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*SHA256.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark SHA256 precompile with varying input sizes. -fn bench_sha256_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_sha256_{}", size_name), - generate_sha256_bytecode(data_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// RIPEMD160 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls RIPEMD160 precompile. -fn generate_ripemd160_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (RIPEMD160 outputs 32 bytes, padded) - builder = builder.push_number(data_size as u64 + 32); // retOffset - builder = builder.push_number(data_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*RIPEMD160.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark RIPEMD160 precompile with varying input sizes. -fn bench_ripemd160_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_ripemd160_{}", size_name), - generate_ripemd160_bytecode(data_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// MODEXP Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls MODEXP precompile with specified modulus size. -fn generate_modexp_bytecode(modulus_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MODEXP input format: - // - let base_len = modulus_size; - let exp_len = modulus_size; - let mod_len = modulus_size; - - // Create sample values (using simple patterns for testing) - let base = vec![0x03u8; base_len]; - let exponent = vec![0xFFu8; exp_len]; - let modulus = vec![0x05u8; mod_len]; - - // Store lengths (each 32 bytes) - builder = builder.mstore(0, U256::from(base_len).to_be_bytes_vec()); - builder = builder.mstore(32, U256::from(exp_len).to_be_bytes_vec()); - builder = builder.mstore(64, U256::from(mod_len).to_be_bytes_vec()); - - // Store base, exponent, and modulus - builder = builder.mstore(96, base); - builder = builder.mstore(96 + base_len, exponent); - builder = builder.mstore(96 + base_len + exp_len, modulus); - - let input_size = 96 + base_len + exp_len + mod_len; - - for _ in 0..iterations { - builder = builder.push_number(mod_len as u64); // retSize (output size = modulus size) - builder = builder.push_number(input_size as u64 + 32); // retOffset - builder = builder.push_number(input_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*modexp::BYZANTIUM.address()); - builder = builder.append(GAS); // gas (modexp can be expensive) - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark MODEXP precompile with varying modulus sizes. -fn bench_modexp_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32)]; - - for (size_name, modulus_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_modexp_{}", size_name), - generate_modexp_bytecode(modulus_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// ECADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECADD precompile. -fn generate_ecadd_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECADD input: two points on alt_bn128 curve - // Point 1: (1, 2) - let x1 = U256::from(1); - let y1 = U256::from(2); - // Point 2: (1, 2) - doubling the point - let x2 = U256::from(1); - let y2 = U256::from(2); - - // Store input data in memory - builder = builder.mstore(0, x1.to_be_bytes_vec()); - builder = builder.mstore(32, y1.to_be_bytes_vec()); - builder = builder.mstore(64, x2.to_be_bytes_vec()); - builder = builder.mstore(96, y2.to_be_bytes_vec()); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (x, y = 64 bytes) - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (two points = 128 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::add::ADDRESS); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECADD precompile. -fn bench_ecadd_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecadd", generate_ecadd_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// ECMUL Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECMUL precompile. -fn generate_ecmul_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECMUL input: point and scalar - // Point: (1, 2) - let x = U256::from(1); - let y = U256::from(2); - // Scalar - let scalar = U256::from(2); - - // Store input data in memory - builder = builder.mstore(0, x.to_be_bytes_vec()); - builder = builder.mstore(32, y.to_be_bytes_vec()); - builder = builder.mstore(64, scalar.to_be_bytes_vec()); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (x, y = 64 bytes) - builder = builder.push_number(96_u64); // retOffset - builder = builder.push_number(96_u64); // argsSize (point + scalar = 96 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::mul::ADDRESS); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECMUL precompile. -fn bench_ecmul_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecmul", generate_ecmul_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// ECPAIRING Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECPAIRING precompile with specified number of pairing points. -fn generate_ecpairing_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECPAIRING input: pairs of (G1 point, G2 point) - // For simplicity, we'll use the identity elements which are valid points - // G1 point (x, y) - using generator point (1, 2) - let g1_x1 = bytes!("0x2cf44499d5d27bb186308b7af7af02ac5bc9eeb6a3d147c186b21fb1b76e18da"); - let g1_y1 = bytes!("0x2c0f001f52110ccfe69108924926e45f0b0c868df0e7bde1fe16d3242dc715f6"); - let g1_x2 = bytes!("0x1fb19bb476f6b9e44e2a32234da8212f61cd63919354bc06aef31e3cfaff3ebc"); - let g1_y2 = bytes!("0x22606845ff186793914e03e21df544c34ffe2f2f3504de8a79d9159eca2d98d9"); - let g1_x3 = bytes!("0x2bd368e28381e8eccb5fa81fc26cf3f048eea9abfdd85d7ed3ab3698d63e4f90"); - let g1_y3 = bytes!("0x2fe02e47887507adf0ff1743cbac6ba291e66f59be6bd763950bb16041a0a85e"); - - let g2_x1 = bytes!("0x0000000000000000000000000000000000000000000000000000000000000001"); - let g2_y1 = bytes!("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"); - let g2_x2 = bytes!("0x1971ff0471b09fa93caaf13cbf443c1aede09cc4328f5a62aad45f40ec133eb4"); - let g2_y2 = bytes!("0x091058a3141822985733cbdddfed0fd8d6c104e9e9eff40bf5abfef9ab163bc7"); - let g2_x3 = bytes!("0x2a23af9a5ce2ba2796c1f4e453a370eb0af8c212d9dc9acd8fc02c2e907baea2"); - let g2_y3 = bytes!("0x23a8eb0b0996252cb548a4487da97b02422ebc0e834613f954de6c7e0afdc1fc"); - - // Store pairing input data in memory - builder = builder.mstore(0, &g1_x1); - builder = builder.mstore(32, &g1_y1); - builder = builder.mstore(64, &g1_x2); - builder = builder.mstore(96, &g1_y2); - builder = builder.mstore(128, &g1_x3); - builder = builder.mstore(160, &g1_y3); - - // G2 point (128 bytes) - builder = builder.mstore(192, &g2_x1); - builder = builder.mstore(224, &g2_y1); - builder = builder.mstore(256, &g2_x2); - builder = builder.mstore(288, &g2_y2); - builder = builder.mstore(320, &g2_x3); - builder = builder.mstore(352, &g2_y3); - - let input_size = 384; - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (returns 32 bytes: 0 or 1) - builder = builder.push_number(input_size as u64 + 32); // retOffset - builder = builder.push_number(input_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::pair::ADDRESS); - builder = builder.append(GAS); // gas (pairing needs more gas) - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECPAIRING precompile with varying number of pairing points. -fn bench_ecpairing_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecpairing", generate_ecpairing_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// BLAKE2F Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLAKE2F precompile with specified number of rounds. -fn generate_blake2f_bytecode(rounds: u32, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // BLAKE2F input format (213 bytes total): - // - rounds (4 bytes, big-endian) - // - h (64 bytes, state vector) - // - m (128 bytes, message block) - // - t (16 bytes, offset counters) - // - f (1 byte, final block indicator) - - let rounds_bytes = rounds.to_be_bytes(); - let h = [0x08u8; 64]; // Initial state vector - let m = [0xFFu8; 128]; // Message block - let t = [0x00u8; 16]; // Offset counters - let f = [0x00u8]; // Final block indicator (0 = not final) - - // Store BLAKE2F input in memory - builder = builder.mstore(0, rounds_bytes); - builder = builder.mstore(4, h); - builder = builder.mstore(68, m); - builder = builder.mstore(196, t); - builder = builder.mstore(212, f); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (BLAKE2F returns 64 bytes) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(213_u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*blake2::FUN.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLAKE2F precompile with varying number of rounds. -fn bench_blake2f_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("1round", 1)]; - - for (rounds_name, rounds) in test_cases { - bench_precompile_group( - c, - &format!("precompile_blake2f_{}", rounds_name), - generate_blake2f_bytecode(rounds, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// KZG Point Evaluation Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls KZG Point Evaluation precompile. -fn generate_kzg_point_evaluation_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // KZG Point Evaluation input (192 bytes total): - // - versioned_hash (32 bytes) - // - z (32 bytes) - // - y (32 bytes) - // - commitment (48 bytes) - // - proof (48 bytes) - - // Sample data from EIP-4844 test vectors - let commitment = bytes!("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7"); - let mut versioned_hash = Sha256Hash::digest(&commitment).to_vec(); - versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG - let z = bytes!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"); - let y = bytes!("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9"); - let proof = bytes!("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c"); - - // Store KZG input in memory - builder = builder.mstore(0, versioned_hash); - builder = builder.mstore(32, &z); - builder = builder.mstore(64, &y); - builder = builder.mstore(96, &commitment); - builder = builder.mstore(144, &proof); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (returns 64 bytes) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(192_u64); // argsSize (total input size) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*kzg_point_evaluation::POINT_EVALUATION.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark KZG Point Evaluation precompile. -fn bench_kzg_point_evaluation_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_kzg_point_evaluation", - generate_kzg_point_evaluation_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G1ADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G1ADD precompile. -fn generate_bls12_381_g1add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G1ADD input: two G1 points (128 bytes each = 256 bytes total) - // Official EIP-2537 test vector - let g1_add_input = bytes!("0000000000000000000000000000000012196c5a43d69224d8713389285f26b98f86ee910ab3dd668e413738282003cc5b7357af9a7af54bb713d62255e80f560000000000000000000000000000000006ba8102bfbeea4416b710c73e8cce3032c31c6269c44906f8ac4f7874ce99fb17559992486528963884ce429a992fee000000000000000000000000000000000001101098f5c39893765766af4512a0c74e1bb89bc7e6fdf14e3e7337d257cc0f94658179d83320b99f31ff94cd2bac0000000000000000000000000000000003e1a9f9f44ca2cdab4f43a1a3ee3470fdf90b2fc228eb3b709fcd72f014838ac82a6d797aeefed9a0804b22ed1ce8f7"); - - // Store the input - builder = builder.mstore(0, &g1_add_input); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(256_u64); // argsSize (two G1 points) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g1_add::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G1ADD precompile. -fn bench_bls12_381_g1add_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g1add", - generate_bls12_381_g1add_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G1MSM Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G1MSM precompile. -fn generate_bls12_381_g1msm_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G1MSM input: G1 point (128 bytes) + scalar (32 bytes) = 160 bytes per pair - // Official EIP-2537 test vector (double-and-add worst case) - let g1_msm_input = bytes!("0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - - // Store the input - builder = builder.mstore(0, &g1_msm_input); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(160_u64); // retOffset - builder = builder.push_number(160_u64); // argsSize (one G1 point + scalar) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g1_msm::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G1MSM precompile. -fn bench_bls12_381_g1msm_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g1msm", - generate_bls12_381_g1msm_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G2ADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G2ADD precompile. -fn generate_bls12_381_g2add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G2ADD input: two G2 points (256 bytes each = 512 bytes total) - // Official EIP-2537 test vector - let g2_add_input = bytes!("0000000000000000000000000000000018c0ada6351b70661f053365deae56910798bd2ace6e2bf6ba4192d1a229967f6af6ca1c9a8a11ebc0a232344ee0f6d6000000000000000000000000000000000cc70a587f4652039d8117b6103858adcd9728f6aebe230578389a62da0042b7623b1c0436734f463cfdd187d20903240000000000000000000000000000000009f50bd7beedb23328818f9ffdafdb6da6a4dd80c5a9048ab8b154df3cad938ccede829f1156f769d9e149791e8e0cd900000000000000000000000000000000079ba50d2511631b20b6d6f3841e616e9d11b68ec3368cd60129d9d4787ab56c4e9145a38927e51c9cd6271d493d938800000000000000000000000000000000192fa5d8732ff9f38e0b1cf12eadfd2608f0c7a39aced7746837833ae253bb57ef9c0d98a4b69eeb2950901917e99d1e0000000000000000000000000000000009aeb10c372b5ef1010675c6a4762fda33636489c23b581c75220589afbc0cc46249f921eea02dd1b761e036ffdbae220000000000000000000000000000000002d225447600d49f932b9dd3ca1e6959697aa603e74d8666681a2dca8160c3857668ae074440366619eb8920256c4e4a00000000000000000000000000000000174882cdd3551e0ce6178861ff83e195fecbcffd53a67b6f10b4431e423e28a480327febe70276036f60bb9c99cf7633"); - - // Store the input - builder = builder.mstore(0, &g2_add_input); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(512_u64); // retOffset - builder = builder.push_number(512_u64); // argsSize (two G2 points) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g2_add::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G2ADD precompile. -fn bench_bls12_381_g2add_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g2add", - generate_bls12_381_g2add_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G2MSM Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G2MSM precompile. -fn generate_bls12_381_g2msm_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G2MSM input: G2 point (256 bytes) + scalar (32 bytes) = 288 bytes per pair - // Official EIP-2537 test vector (double-and-add worst case) - let g2_msm_input = bytes!("00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79beffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - - // Store the input - builder = builder.mstore(0, &g2_msm_input); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(288_u64); // retOffset - builder = builder.push_number(288_u64); // argsSize (one G2 point + scalar) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g2_msm::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G2MSM precompile. -fn bench_bls12_381_g2msm_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g2msm", - generate_bls12_381_g2msm_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 PAIRING Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 PAIRING precompile. -fn generate_bls12_381_pairing_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // PAIRING input: 2 pairs (G1 point + G2 point) * 2 = 768 bytes - // Official EIP-2537 test vector for 2 pairs - let pairing_input = bytes!("0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be"); - - // Store the input - builder = builder.mstore(0, &pairing_input); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (returns 32 bytes: 0 or 1) - builder = builder.push_number(768_u64); // retOffset - builder = builder.push_number(768_u64); // argsSize (2 pairs = 768 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::pairing::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 PAIRING precompile. -fn bench_bls12_381_pairing_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_pairing", - generate_bls12_381_pairing_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 MAP_FP_TO_G1 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 `MAP_FP_TO_G1` precompile. -fn generate_bls12_381_map_fp_to_g1_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MAP_FP_TO_G1 input: field element (64 bytes padded) - // Using value 1 with proper padding (16 bytes padding + 48 bytes data) - let mut fp_element = vec![0u8; 64]; - fp_element[63] = 1; // Set to 1 - - // Store field element - builder = builder.mstore(0, &fp_element); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(64_u64); // retOffset - builder = builder.push_number(64_u64); // argsSize (one field element) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::map_fp_to_g1::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 `MAP_FP_TO_G1` precompile. -fn bench_bls12_381_map_fp_to_g1_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_map_fp_to_g1", - generate_bls12_381_map_fp_to_g1_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 MAP_FP2_TO_G2 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 `MAP_FP2_TO_G2` precompile. -fn generate_bls12_381_map_fp2_to_g2_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MAP_FP2_TO_G2 input: Fp2 element (128 bytes padded = 2 * 64 bytes) - // Using a simple valid Fp2 element: (1, 0) with proper padding - // Each component is 64 bytes: 16 bytes padding + 48 bytes data - let mut fp2_element = vec![0u8; 128]; - // Set first component to 1 (at byte 63, the last byte of first 64-byte chunk) - fp2_element[63] = 1; - - // Store Fp2 element - builder = builder.mstore(0, &fp2_element); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (one Fp2 element) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::map_fp2_to_g2::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 `MAP_FP2_TO_G2` precompile. -fn bench_bls12_381_map_fp2_to_g2_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_map_fp2_to_g2", - generate_bls12_381_map_fp2_to_g2_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// Criterion Configuration -// ============================================================================ -// - -criterion_group!( - benches, - bench_add_opcode, - bench_address_opcode, - bench_keccak256_opcode, - bench_exp_opcode, - bench_ecrecover_precompile, - bench_sha256_precompile, - bench_ripemd160_precompile, - bench_modexp_precompile, - bench_ecadd_precompile, - bench_ecmul_precompile, - bench_ecpairing_precompile, - bench_blake2f_precompile, - bench_kzg_point_evaluation_precompile, - bench_bls12_381_g1add_precompile, - bench_bls12_381_g1msm_precompile, - bench_bls12_381_g2add_precompile, - bench_bls12_381_g2msm_precompile, - bench_bls12_381_pairing_precompile, - bench_bls12_381_map_fp_to_g1_precompile, - bench_bls12_381_map_fp2_to_g2_precompile, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/ctt.rs b/crates/mega-evm/benches/ctt.rs deleted file mode 100644 index 3bc2ea830..000000000 --- a/crates/mega-evm/benches/ctt.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Benchmarks for the `ConcurrencyTortureTest` batchTransfer operation. -//! -//! This benchmark suite measures the performance of the `batchTransfer` function -//! from the `ConcurrencyTortureTest` (CTT) contract, comparing performance across -//! different EVM specifications (`EQUIVALENCE` vs `MINI_REX`). - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId, MegaTransaction}; -use revm::{context::tx::TxEnvBuilder, primitives::KECCAK_EMPTY, ExecuteCommitEvm, ExecuteEvm}; - -const DEPLOYER: Address = address!("0000000000000000000000000000000000100000"); -const CALLER: Address = address!("0000000000000000000000000000000000100001"); - -/// CTT deployment bytecode. Compiled at commit 0bcd874ab95f1300d1796888cd2ce087e1773b55 of -/// git@github.com:megaeth-labs/concurrency-torture-test.git -const CTT_DEPLOY_CODE: Bytes = bytes!("0x6101406040523461033557604051601f611f4b38819003918201601f19168301916001600160401b038311848410176102165780849260809460405283398101031261033557805190602081015191606060408301519201516001831180610328575b156102ce5760648211610275578260805260a05260c052801561026157808083049206820180831161024d57610096610339565b9081525f808052602052517fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb55560015b81811061022a5760405161077d8082016001600160401b03811183821017610216578291611365833903905ff0801561020b576001600160a01b031660e0526040516101008082016001600160401b03811183821017610216578291611ae2833903905ff0801561020b576001600160a01b0316610100526040516103698082016001600160401b03811183821017610216578291611be2833903905ff0801561020b576001600160a01b03166101205260405161100c908161035982396080518181816102f90152818161081e015281816108d60152610bb1015260a051818181610369015281816108fc01528181610e3f0152610ebf015260c0518181816102bf0152818161089c0152610b88015260e05181818161016c01526109340152610100518181816103a10152610570015261012051818181610279015261069f0152f35b6040513d5f823e3d90fd5b634e487b7160e01b5f52604160045260245ffd5b600190610235610339565b848152815f525f60205260405f2090519055016100c6565b634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b60405162461bcd60e51b815260206004820152602b60248201527f4354543a20626c6f636b496e666f5265616450657263656e74616765206d757360448201526a074206265203c3d203130360ac1b6064820152608490fd5b60405162461bcd60e51b815260206004820152602c60248201527f4354543a2063656c6c436f756e74206d757374206265206265747765656e203260448201526b020616e64203130302c3030360a41b6064820152608490fd5b50620186a0831115610062565b5f80fd5b60405190602082016001600160401b038111838210176102165760405256fe60806040526004361015610011575f80fd5b5f3560e01c806305d48b21146101145780630d3eadda1461010f5780631941fd141461010a5780635a5173b314610105578063660844f01461010057806374eee84c146100fb5780637b49b4ae146100f657806382106275146100f157806396e17e4d146100ec5780639f366f67146100e7578063a8ae91cd146100e2578063b1444901146100dd578063c77e41dd146100d8578063dd70c8ec146100d3578063fd433182146100ce5763fd65f099146100c9575f80fd5b610429565b61040c565b6103f2565b6103d0565b61038c565b610352565b61031c565b6102e2565b6102a8565b610264565b61021f565b6101e0565b6101c4565b61019b565b610157565b61013b565b60809060031901126101375760043590602435906044359060643590565b5f80fd5b346101375761015561014c36610119565b9291909161051e565b005b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137576020366003190112610137576004355f525f602052602060405f2054604051908152f35b34610137575f3660031901126101375760206040516127108152f35b346101375760206101fc6101f336610119565b929190916105d6565b6040516001600160a01b039091168152f35b6001600160a01b0381160361013757565b346101375760203660031901126101375760043561023c8161020e565b60018060a01b03165f526001602052602067ffffffffffffffff60405f205416604051908152f35b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346101375760a0366003190112610137576004356004811015610137576101fc602091602435604435606435916084359361072f565b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137575f3660031901126101375760206103ea610812565b604051908152f35b346101375761015561040336610119565b92919091610870565b34610137575f366003190112610137576020600254604051908152f35b346101375761015561043a36610119565b92919091610ad9565b1561044a57565b60405162461bcd60e51b815260206004820152602c60248201527f4354543a206e756d53656e6465727320616e64206e756d52656365697665727360448201526b0206d757374206265203e20360a41b6064820152608490fd5b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff8211176104da57604052565b6104a4565b3d15610519573d9067ffffffffffffffff82116104da576040519161050e601f8201601f1916602001846104b8565b82523d5f602084013e565b606090565b905f938493831515806105aa575b61053590610443565b604051926020840194630d02bd9760e31b865260248501526044840152606483015260848201526084815261056b60a4826104b8565b5190827f00000000000000000000000000000000000000000000000000000000000000005af16105996104df565b90156105a25750565b602081519101fd5b5082151561052c565b9081602091031261013757516105c88161020e565b90565b6040513d5f823e3d90fd5b90929161069a60209383151580610708575b6105f190610443565b325f908152600160205260409020610653908290610618905b5467ffffffffffffffff1690565b6040519061064e826106408b8201600d906c10d4915055114c97d0d2125311609a1b81520190565b03601f1981018452836104b8565b610eaa565b60405163318600cf60e01b8152600481019190915230602482015260448101949094526064840195909552608483019190915260a4820193909352918290819060c4820190565b03815f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1908115610703575f916106da575090565b6105c8915060203d6020116106fc575b6106f481836104b8565b8101906105b3565b503d6106ea565b6105cb565b508515156105e8565b6004111561071b57565b634e487b7160e01b5f52602160045260245ffd5b939291909361073d81610711565b80610750575061074c93610ad9565b5f90565b61075981610711565b6001810361076b575061074c93610870565b61077481610711565b60028103610786575061074c9361051e565b80610792600392610711565b036107a0576105c8936105d6565b60405162461bcd60e51b81526020600482015260166024820152754354543a20496e76616c69642063616c6c207479706560501b6044820152606490fd5b634e487b7160e01b5f52601160045260245ffd5b600101908160011161080057565b6107de565b9190820180921161080057565b5f9060025461086a575f7f00000000000000000000000000000000000000000000000000000000000000005b808210610849575050565b9092835f525f60205260405f2054810180911161080057926001019061083e565b5f199150565b905f9384938315158061095d575b61088790610443565b6040519260208401946317f613d160e31b86527f0000000000000000000000000000000000000000000000000000000000000000602486015260448501526064840152608483015260a48201527f000000000000000000000000000000000000000000000000000000000000000060c48201527f000000000000000000000000000000000000000000000000000000000000000060e482015260e48152610930610104826104b8565b51907f00000000000000000000000000000000000000000000000000000000000000005af46105996104df565b5082151561087e565b1561096d57565b60405162461bcd60e51b815260206004820152602660248201527f4354543a20726561644f6e6c7950657263656e74616765206d7573742062652060448201526503c3d203130360d41b6064820152608490fd5b67ffffffffffffffff60019116019067ffffffffffffffff821161080057565b81156109eb570690565b634e487b7160e01b5f52601260045260245ffd5b15610a0657565b60405162461bcd60e51b815260206004820152602860248201527f4354543a20696e73756666696369656e742062616c616e636520696e2073656e60448201526719195c8818d95b1b60c21b6064820152608490fd5b15610a6357565b60405162461bcd60e51b815260206004820152602d60248201527f4354543a207472616e7366657220776f756c64206f766572666c6f772072656360448201526c65697665722062616c616e636560981b6064820152608490fd5b9190820391821161080057565b5f1981146108005760010190565b9081151580610e20575b610aec90610443565b610af96064841115610966565b325f908152600160205260409020610b1990610b149061060a565b6109c1565b325f908152600160205260409020805467ffffffffffffffff191667ffffffffffffffff83161790555f935f95610b82604051610b7c81610b6e60208201600a9069424c4f434b5f494e464f60b01b81520190565b03601f1981018352826104b8565b84610e29565b606481067f000000000000000000000000000000000000000000000000000000000000000011610df7575b505f7f00000000000000000000000000000000000000000000000000000000000000009083151593612711915b888110610c0f57505050505050505050610bf390610f63565b03610bfa57565b610c0d610c08600254610acb565b600255565b565b868b8487610c3e88610c3983604051610c3381610b6e8c6020830160209181520190565b88610eaa565b6109e1565b92868b610c52865f525f60205260405f2090565b54968791610dac575b505050610c869291610b6e610c80610c39936040519283916020830160209181520190565b8d610eaa565b5f5b8b8110610c9d57505050506001905b01610bda565b808b610cd18a610c398d600196610ccb8c610b6e604051938492602084019091604092825260208201520190565b85610eaa565b808614610da55780610d4186610d3b81610d137f77a84327eb5534e95fa55d5a8a7ccc7e19c6cee0e9777fd78e8dda84b2275fac965f525f60205260405f2090565b549b610d21828210156109ff565b610d368d610d2f8482610805565b1015610a5c565b610abe565b99610805565b9088610d54895f525f60205260405f2090565b5581610d67825f525f60205260405f2090565b556040805167ffffffffffffffff95909516855260208501889052840188905260608401899052608084015260a0830152329160c090a25b01610c88565b5050610d9f565b84610ddd92610dd69261064e8c610640604051948592602084019091604092825260208201520190565b6064900690565b10610dea5786858d610c5b565b5050505050600190610c97565b610e0a919750610e0f9296506009900690565b6107f2565b93610e1985610f63565b955f610bad565b50801515610ae3565b6020610e9f605c600194604051938491818301967f000000000000000000000000000000000000000000000000000000000000000088523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f1981018352826104b8565b519020906105c85790565b90610f1f605c602092604051938491818301967f000000000000000000000000000000000000000000000000000000000000000088523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f1981018352826104b8565b519020905f905b808210610f3257505090565b9091600190604051610f5881610b6e876020830195869091604092825260208201520190565b519020920190610f26565b60018103610f7057504890565b60028103610f7d57504a90565b60038103610f8a57504690565b60048103610f9757504190565b60058103610fa457504490565b60068103610fb157504590565b60078103610fbe57504390565b60088103610fcb57504490565b60090361074c57429056fea26469706673582212205cf443ae3ff796f483da8f3136046f6f42b4741de464846b1af03f977336b13864736f6c634300081e003360808060405234601557610763908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c63bfb09e8814610024575f80fd5b346103385760e03660031901126103385760043560843560243560443560a43560643560c4358415158061032f575b61005c9061033c565b6100686001841161039d565b61007560648311156103e9565b610087325f52600160205260405f2090565b926100a261009d855467ffffffffffffffff1690565b610458565b8094555f965f986100e66040516100df816100d160208201600a9069424c4f434b5f494e464f60b01b81520190565b03601f19810183528261047d565b87866105b8565b906064820610610306575b506127115f5b88811061011a578a6101088b6106b6565b0361010f57005b600280546001019055005b610197858c84868b6101508a61014b846100d16101448c6040519283916020830160209181520190565b858a61061d565b6104b3565b938c6101a361019c858b8661016c8b5f525f60205260405f2090565b805460408051602081019590955284018190529d909c9083606081015b03601f19810185528461047d565b61061d565b6064900690565b106102f757916101cb61014b926101d96101df96956040519384916020830160209181520190565b03601f19810184528361047d565b8d61061d565b8b8b89898c5f945b8510610200575050505050505050506001905b016100f7565b61022c9291858561014b936101978e610189604051958692602084019091604092825260208201520190565b8085146102ed57907f77a84327eb5534e95fa55d5a8a7ccc7e19c6cee0e9777fd78e8dda84b2275fac61029897836102a38761029d8161027660019a995f525f60205260405f2090565b9586549e8f610287848410156104ec565b61029184826104df565b1015610549565b6105ab565b9b6104df565b8a8a55918290556040805167ffffffffffffffff959095168552602085018890528401889052606084018a9052608084015260a0830152329160c090a25b018b89898f8d906101e7565b50506001906102e1565b505050505050506001906101fa565b61031991995061031e9298506009900690565b6104d1565b95610328876106b6565b975f6100f1565b50831515610053565b5f80fd5b1561034357565b60405162461bcd60e51b815260206004820152602c60248201527f4354543a206e756d53656e6465727320616e64206e756d52656365697665727360448201526b0206d757374206265203e20360a41b6064820152608490fd5b156103a457565b60405162461bcd60e51b815260206004820152601960248201527f4354543a206e756d43656c6c73206d757374206265203e2031000000000000006044820152606490fd5b156103f057565b60405162461bcd60e51b815260206004820152602660248201527f4354543a20726561644f6e6c7950657263656e74616765206d7573742062652060448201526503c3d203130360d41b6064820152608490fd5b634e487b7160e01b5f52601160045260245ffd5b67ffffffffffffffff60019116019067ffffffffffffffff821161047857565b610444565b90601f8019910116810190811067ffffffffffffffff82111761049f57604052565b634e487b7160e01b5f52604160045260245ffd5b81156104bd570690565b634e487b7160e01b5f52601260045260245ffd5b600101908160011161047857565b9190820180921161047857565b156104f357565b60405162461bcd60e51b815260206004820152602860248201527f4354543a20696e73756666696369656e742062616c616e636520696e2073656e60448201526719195c8818d95b1b60c21b6064820152608490fd5b1561055057565b60405162461bcd60e51b815260206004820152602d60248201527f4354543a207472616e7366657220776f756c64206f766572666c6f772072656360448201526c65697665722062616c616e636560981b6064820152608490fd5b9190820391821161047857565b909161060f605c60019460206040519485928284019788523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f19810183528261047d565b5190209061061a5790565b90565b9190605c6106729160206040519485928284019788523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f19810183528261047d565b519020905f905b80821061068557505090565b90916001906040516106ab816100d1876020830195869091604092825260208201520190565b519020920190610679565b600181036106c357504890565b600281036106d057504a90565b600381036106dd57504690565b600481036106ea57504190565b600581036106f757504490565b6006810361070457504590565b6007810361071157504390565b6008810361071e57504490565b600903610729574290565b5f9056fea2646970667358221220a4bcc3777bb41dc90dbc866c57aa4c6ea571d71031195916664ccb5fd8163e4764736f6c634300081e00336080806040523460145760e790816100198239f35b5f80fdfe60808060405260043610156011575f80fd5b5f905f3560e01c636815ecb8146025575f80fd5b3460ad57608036600319011260ad57333b1560ad5763fd65f09960e01b815260043560048201526024356024820152604435604482015260643560648201525f8160848183335af1801560a2576079575080f35b905067ffffffffffffffff8111608e57604052005b634e487b7160e01b5f52604160045260245ffd5b6040513d5f823e3d90fd5b5f80fdfea2646970667358221220f175208873a77bf072379c6ff131eeaae1326bd45c2f48995824ed2c602ed5a664736f6c634300081e00336080806040523460155761034f908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c63318600cf14610024575f80fd5b346100895760c0366003190112610089576024356001600160a01b03811681036100895761006b6100859161005860443590565b6064356084359160a43593600435610121565b6040516001600160a01b0390911681529081906020820190565b0390f35b5f80fd5b90601f8019910116810190811067ffffffffffffffff8211176100af57604052565b634e487b7160e01b5f52604160045260245ffd5b805191908290602001825e015f815290565b156100dc57565b60405162461bcd60e51b815260206004820152601e60248201527f4354543a2043524541544532206465706c6f796d656e74206661696c656400006044820152606490fd5b946101a79294610199946101229660405197610140602082018a61008d565b8089526101f860208a01396040519460018060a01b0316602086015260408501526060840152608083015260a082015260a0815261017f60c08261008d565b6040519283916101936020840180976100c3565b906100c3565b03601f19810183528261008d565b51905ff5906101c06001600160a01b03831615156100d5565b6040516001600160a01b03831681527f916f35ba24f3be9802a8b5ffca961b5cd764d08fcfd24c270bc1c58b948e886290602090a156fe60808060405260a08161012280380380916018828560b2565b83398101031260ae5780516001600160a01b0381169081900360ae576020820151906040830151906080606085015194015192813b1560ae575f6084928195604051978896879563fd65f09960e01b875260048701526024860152604485015260648401525af1801560a3576096575b604051603990816100e98239f35b5f609e9160b2565b5f6088565b6040513d5f823e3d90fd5b5f80fd5b601f909101601f19168101906001600160401b0382119082101760d457604052565b634e487b7160e01b5f52604160045260245ffdfe5f80fdfea2646970667358221220c1b785695bcc466bc621dad0960a0d161ccc9db357b5516454f683de2fc4397264736f6c634300081e0033a26469706673582212200de4490c305b2997f987b3670cef90af77fd7a480fffe15b04ab7ea8bda349b964736f6c634300081e0033"); -const TOTAL_SUPPLY: u64 = 1_000_000_000; -const CELL_COUNT: u64 = 100; -const BLOCK_INFO_READ_PERCENTAGE: u64 = 20; -const SEED: [u8; 32] = *b"test-seed-for-ctt-benchmarking!!"; - -/// Deploy CTT contract and return the deployed address and post-deployment database -fn deploy_ctt(spec: MegaSpecId) -> (Address, MemoryDatabase) { - let creation_code = CTT_DEPLOY_CODE; - - // Encode constructor parameters: (blockInfoReadPercentage, totalSupply, cellCount, seed) - let mut constructor_args = Vec::new(); - constructor_args.extend_from_slice(&U256::from(BLOCK_INFO_READ_PERCENTAGE).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&U256::from(TOTAL_SUPPLY).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&U256::from(CELL_COUNT).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&SEED); - - let mut deploy_data = creation_code.to_vec(); - deploy_data.extend_from_slice(&constructor_args); - - // Set up database with deployer and caller balances - let mut db = MemoryDatabase::default() - .account_balance(DEPLOYER, U256::from(10).pow(U256::from(18))) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - - let mut context = MegaContext::new(&mut db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - // Deploy contract (CREATE transaction with no 'to' address) - let tx = TxEnvBuilder::new() - .gas_limit(1_000_000_000) - .caller(DEPLOYER) - .create() - .data(Bytes::from(deploy_data)) - .build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.transact_commit(mega_tx).expect("deployment should succeed"); - assert!(result.is_success(), "CTT deployment failed"); - - // Calculate the deployed contract address: keccak256(rlp([sender, nonce]))[12:] - // For the first transaction from DEPLOYER, nonce is 0 - let deployed_address = DEPLOYER.create(0); - - // check if the deployment is successful - let deployed_info = &db.load_account(deployed_address).unwrap().info; - deployed_info.code.as_ref().expect("code should be present"); - assert_ne!(deployed_info.code_hash, KECCAK_EMPTY); - - (deployed_address, db) -} - -/// Encode a call to batchTransfer(uint256,uint256,uint256,uint256) -/// Function selector: 0xfd65f099 -fn encode_batch_transfer_call( - num_senders: u64, - num_receivers: u64, - read_only_percentage: u64, - complexity: u64, -) -> Bytes { - let mut calldata = Vec::with_capacity(4 + 32 * 4); - - // Function selector: batchTransfer(uint256,uint256,uint256,uint256) - calldata.extend_from_slice(&[0xfd, 0x65, 0xf0, 0x99]); - - // Encode parameters (all uint256) - calldata.extend_from_slice(&U256::from(num_senders).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(num_receivers).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(read_only_percentage).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(complexity).to_be_bytes::<32>()); - - Bytes::from(calldata) -} - -/// Helper function to execute a single benchmark iteration -fn execute_batch_transfer( - spec: MegaSpecId, - db: MemoryDatabase, - contract_addr: Address, - calldata: &Bytes, -) { - let mut context = MegaContext::new(black_box(db), black_box(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(contract_addr).data(calldata.clone()).build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.transact(mega_tx).expect("transaction should succeed"); - assert!(result.result.is_success()); - black_box(result); -} - -/// Benchmark batchTransfer with different contention patterns -fn bench_ctt_batch_transfer(c: &mut Criterion) { - // Deploy CTT once per spec to get the initial state - let (ctt_addr_eq, initial_db_eq) = deploy_ctt(MegaSpecId::EQUIVALENCE); - let (ctt_addr_mr, initial_db_mr) = deploy_ctt(MegaSpecId::MINI_REX); - - // Test cases: (name, numSenders, numReceivers, complexity) - let test_cases = [ - ("low_contention_1x1", 1, 1, 0), - ("medium_contention_5x5", 5, 5, 0), - ("high_contention_10x10", 10, 10, 0), - ("little_complexity_1x1", 1, 1, 5), - ("medium_complexity_1x1", 1, 1, 50), - ("high_complexity_1x1", 1, 1, 100), - ("some_complexity_5x5", 5, 5, 25), - ]; - - for (test_name, num_senders, num_receivers, complexity) in test_cases { - let mut group = c.benchmark_group(format!("batch_transfer_{}", test_name)); - let calldata = encode_batch_transfer_call(num_senders, num_receivers, 0, complexity); - - group.bench_function("equivalence", |b| { - b.iter(|| { - execute_batch_transfer( - MegaSpecId::EQUIVALENCE, - initial_db_eq.clone(), - ctt_addr_eq, - &calldata, - ) - }) - }); - - group.bench_function("mini_rex", |b| { - b.iter(|| { - execute_batch_transfer( - MegaSpecId::MINI_REX, - initial_db_mr.clone(), - ctt_addr_mr, - &calldata, - ) - }) - }); - - group.finish(); - } -} - -criterion_group!(benches, bench_ctt_batch_transfer); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/enriched_tx.rs b/crates/mega-evm/benches/enriched_tx.rs deleted file mode 100644 index 65eb8954c..000000000 --- a/crates/mega-evm/benches/enriched_tx.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Benchmarks the cost of `MegaTransactionExt::{tx_size, estimated_da_size}` recompute vs the -//! `EnrichedMegaTx` cached fields. -//! -//! `EnrichedMegaTx` exists to precompute `tx_size`/`da_size` once (e.g. via `new_slow` from a -//! mempool-cached value) so block-execution callers can reuse them instead of recomputing on -//! every access. Three rows: -//! - `recompute_via_tx_unwrap` mirrors the `alloy_evm` block-execution path's call pattern -//! (`tx.tx().estimated_da_size()` / `tx.tx().tx_size()`), which unwraps `EnrichedMegaTx` down to -//! the raw inner transaction and always hits the recomputing default impl. -//! - `via_trait_dispatch` mirrors `MegaBlockExecutor::run_transaction`'s call pattern -//! (`tx.estimated_da_size()` / `tx.tx_size()` on the outer wrapper), which dispatches to the -//! stored fields for an `EnrichedMegaTx`. -//! - `cached_fields` reads the wrapper's precomputed fields directly, the floor -//! `via_trait_dispatch` should match. - -#![allow(missing_docs)] - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_evm::RecoveredTx; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, U256}; -use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; -use mega_evm::{EnrichedMegaTx, MegaTransactionExt, MegaTxEnvelope}; - -const CALLER: Address = address!("2000000000000000000000000000000000000001"); -const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - -/// Calldata sizes spanning a plain transfer up to a large multicall-style payload. -const CALLDATA_SIZES: &[usize] = &[0, 68, 180, 1000]; - -fn enriched_tx(calldata_len: usize) -> EnrichedMegaTx> { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from(vec![0xabu8; calldata_len]), - }; - let envelope = MegaTxEnvelope::Legacy(Signed::new_unchecked( - tx, - Signature::test_signature(), - Default::default(), - )); - let recovered = Recovered::new_unchecked(envelope, CALLER); - EnrichedMegaTx::new_slow(recovered) -} - -/// The `alloy_evm` block-execution path's pattern: `tx.tx().()` unwraps `EnrichedMegaTx` -/// down to the raw inner transaction, so `tx_size`/`estimated_da_size` always hit the recomputing -/// default impl even when the wrapper carries precomputed fields. -fn bench_recompute_via_tx_unwrap(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/recompute_via_tx_unwrap"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx.tx()).estimated_da_size()) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx.tx()).tx_size()) - }); - } - group.finish(); -} - -/// `MegaBlockExecutor::run_transaction`'s call pattern: `tx.()` called directly on the -/// outer `EnrichedMegaTx`, dispatching to the stored fields via `MegaTransactionExt`. -fn bench_via_trait_dispatch(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/via_trait_dispatch"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).estimated_da_size()) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).tx_size()) - }); - } - group.finish(); -} - -/// Reading `EnrichedMegaTx`'s precomputed fields directly. -fn bench_cached_fields(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/cached_fields"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).da_size) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).tx_size) - }); - } - group.finish(); -} - -criterion_group!( - benches, - bench_recompute_via_tx_unwrap, - bench_via_trait_dispatch, - bench_cached_fields -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/mega_bench.rs b/crates/mega-evm/benches/mega_bench.rs deleted file mode 100644 index a29a3b282..000000000 --- a/crates/mega-evm/benches/mega_bench.rs +++ /dev/null @@ -1,971 +0,0 @@ -//! Benchmarks for mega-evm specific features. -//! -//! These benchmarks exercise code paths unique to mega-evm: -//! - **`volatile_data`**: Gas detention from block env opcodes (COINBASE, TIMESTAMP, etc.) -//! - **`gas_detention_computation`**: Impact of gas detention on subsequent heavy computation -//! - **`log_opcodes`**: LOG0-LOG4 with dual gas model (compute + storage gas) -//! - **`sstore_heavy`**: SSTORE-intensive workloads triggering resource limit tracking -//! - **`system_contract_single` / `system_contract_100x`**: System contract call interception -//! overhead -//! - **`delegatecall_system_contract`**: DELEGATECALL vs CALL to system contracts -//! - **`oracle_sload`**: Oracle forced-cold SLOAD vs regular SLOAD -//! - **`create_deploy`**: CREATE/CREATE2 contract deployment with resource tracking -//! - **`selfdestruct`**: SELFDESTRUCT behavior across specs -//! - **`call_value_empty_account`**: CALL with value to empty accounts (dynamic gas) -//! - **`mixed_workload`**: Realistic combined workload -//! - **`eip7702_authlist`**: REX5 pre-execution authority-list scan scaling with list size -//! - **`staticcall_selfdestruct`**: SELFDESTRUCT inside a STATICCALL frame vs a STOP control - -#![allow(missing_docs)] - -use alloy_eips::eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}; -use alloy_primitives::{address, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - revm::inspector::NoOpInspector, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EmptyExternalEnv, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{ - ADD, CALL, COINBASE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, LOG1, LOG2, LOG4, NUMBER, - POP, PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STATICCALL, STOP, TIMESTAMP, - }, - context::tx::TxEnvBuilder, - ExecuteEvm as _, -}; - -mod common; -use common::{ - register_all, register_all_suffixed, register_mega_specs, register_mega_specs_suffixed, - register_mega_suffixed, Account, TxSpec, Workload, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const SECONDARY: Address = address!("0000000000000000000000000000000000100003"); - -/// Gas limit shared by every mega-feature workload — high enough that the -/// bench never halts on the EVM gas limit, leaving mega's own resource limits -/// as the only relevant ceiling. -const FEATURE_GAS_LIMIT: u64 = 10_000_000_000; - -/// A funded `CALLER` calling a contract at `CONTRACT` holding `code`, under the -/// shared feature gas limit with empty calldata. Covers most mega benches; the -/// few with extra accounts or a different target build their `Workload` inline. -fn mega_contract_workload(code: Bytes) -> Workload { - Workload::single( - vec![ - Account::new(CONTRACT).code(code), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) -} - -// -// ============================================================================ -// Volatile Data Access Benchmarks -// ============================================================================ -// - -const VOLATILE_ITERATIONS: usize = 100; - -fn generate_baseline_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() -} - -fn generate_coinbase_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(COINBASE).append(POP); - } - builder.build() -} - -fn generate_timestamp_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(TIMESTAMP).append(POP); - } - builder.build() -} - -fn generate_number_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(NUMBER).append(POP); - } - builder.build() -} - -fn bench_volatile_data(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("baseline_add", generate_baseline_bytecode(VOLATILE_ITERATIONS)), - ("coinbase", generate_coinbase_bytecode(VOLATILE_ITERATIONS)), - ("timestamp", generate_timestamp_bytecode(VOLATILE_ITERATIONS)), - ("number", generate_number_bytecode(VOLATILE_ITERATIONS)), - ]; - - let mut group = c.benchmark_group("volatile_data"); - for (variant, bytecode) in variants { - register_mega_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// Gas Detention + Computation Benchmark -// ============================================================================ -// -// Measures the impact of gas detention on subsequent heavy computation. -// After accessing volatile data, every subsequent opcode must check the -// detained compute gas limit. This benchmark isolates that overhead. -// - -fn bench_gas_detention_computation(c: &mut Criterion) { - // Heavy computation only (500 ADD ops) — no volatile access - let computation_only = { - let mut builder = BytecodeBuilder::default(); - for _ in 0..500 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() - }; - - // Volatile access THEN heavy computation (COINBASE + 500 ADD ops) - // Every ADD after COINBASE must check the detained gas cap. - let volatile_then_compute = { - let mut builder = BytecodeBuilder::default(); - builder = builder.append(COINBASE).append(POP); - for _ in 0..500 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() - }; - - let mut group = c.benchmark_group("gas_detention_computation"); - register_mega_suffixed( - &mut group, - "compute_only_500", - &mega_contract_workload(computation_only), - ); - register_mega_suffixed( - &mut group, - "volatile_then_compute_500", - &mega_contract_workload(volatile_then_compute), - ); - group.finish(); -} - -// -// ============================================================================ -// LOG Opcode Benchmarks -// ============================================================================ -// - -const LOG_ITERATIONS: usize = 50; - -fn generate_log0_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(data_size as u64).push_number(0u64).append(LOG0); - } - builder.build() -} - -fn generate_log2_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0xdead_beef_u64) - .push_number(0xcafe_babe_u64) - .push_number(data_size as u64) - .push_number(0u64) - .append(LOG2); - } - builder.build() -} - -fn generate_log4_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0x1111_u64) - .push_number(0x2222_u64) - .push_number(0x3333_u64) - .push_number(0x4444_u64) - .push_number(data_size as u64) - .push_number(0u64) - .append(LOG4); - } - builder.build() -} - -fn bench_log_opcodes(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("log0_32b", generate_log0_bytecode(LOG_ITERATIONS, 32)), - ("log0_256b", generate_log0_bytecode(LOG_ITERATIONS, 256)), - ("log2_32b", generate_log2_bytecode(LOG_ITERATIONS, 32)), - ("log4_32b", generate_log4_bytecode(LOG_ITERATIONS, 32)), - ("log4_256b", generate_log4_bytecode(LOG_ITERATIONS, 256)), - ]; - - let mut group = c.benchmark_group("log_opcodes"); - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// SSTORE Heavy Benchmarks -// ============================================================================ -// - -const SSTORE_ITERATIONS: usize = 100; - -fn generate_sstore_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder.push_number(i as u64 + 1).push_number(i as u64).append(SSTORE); - } - builder.build() -} - -fn generate_sload_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder.push_number(i as u64).append(SLOAD).append(POP); - } - builder.build() -} - -fn generate_sstore_sload_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder - .push_number(i as u64 + 1) - .push_number(i as u64) - .append(SSTORE) - .push_number(i as u64) - .append(SLOAD) - .append(POP); - } - builder.build() -} - -fn bench_sstore(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("sstore_100", generate_sstore_bytecode(SSTORE_ITERATIONS)), - ("sload_100", generate_sload_bytecode(SSTORE_ITERATIONS)), - ("sstore_sload_100", generate_sstore_sload_bytecode(SSTORE_ITERATIONS)), - ]; - - let mut group = c.benchmark_group("sstore_heavy"); - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// CREATE / CREATE2 Contract Deployment Benchmarks -// ============================================================================ -// -// Exercises: -// - forward_gas_ext (98/100 gas forwarding rule) -// - storage_gas_ext (SALT dynamic gas for new account/contract) -// - State growth tracking -// - Data size tracking (deployed code size) -// - -/// Build bytecode that deploys a minimal contract via CREATE. -/// The init code stores a small runtime bytecode and returns it. -fn make_create_bytecode(n_deploys: usize) -> Bytes { - // Init code that deploys an empty contract: PUSH1 0x00 PUSH1 0x00 RETURN. - let init_code: [u8; 5] = [0x60, 0x00, 0x60, 0x00, 0xf3]; - - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, init_code); - - for _ in 0..n_deploys { - builder = builder - .push_number(5u64) // size of init code - .push_number(0u64) // memory offset - .push_number(0u64) // value - .append(CREATE) - .append(POP); // discard deployed address - } - builder.build() -} - -/// Build bytecode that deploys a minimal contract via CREATE2 with varying salts. -fn make_create2_bytecode(n_deploys: usize) -> Bytes { - let init_code: [u8; 5] = [0x60, 0x00, 0x60, 0x00, 0xf3]; - - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, init_code); - - for i in 0..n_deploys { - builder = builder - .push_number(i as u64) // salt (different each time) - .push_number(5u64) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(POP); - } - builder.build() -} - -fn bench_create_deploy(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = - &[("create_10", make_create_bytecode(10)), ("create2_10", make_create2_bytecode(10))]; - - let mut group = c.benchmark_group("create_deploy"); - group.sample_size(10); - - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// SELFDESTRUCT Benchmark -// ============================================================================ -// -// SELFDESTRUCT behavior varies by spec: -// - EQUIVALENCE: Standard EIP-6780 behavior -// - MINI_REX ~ REX1: Disabled (halts execution) -// - REX2+: Re-enabled with EIP-6780 semantics -// - REX4+: Also marks beneficiary balance access for gas detention -// - -fn bench_selfdestruct(c: &mut Criterion) { - // SELFDESTRUCT(target) — send remaining balance to target - let selfdestruct_code: Bytes = vec![PUSH0, SELFDESTRUCT].into(); - - // Specs where SELFDESTRUCT is allowed - let selfdestruct_specs: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("rex2", MegaSpecId::REX2), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - ]; - - let mut group = c.benchmark_group("selfdestruct"); - // A subject rebuilds the DB from the workload each iteration (SELFDESTRUCT - // modifies state), and `allow_halt` covers the specs where it is disabled. - let workload = mega_contract_workload(selfdestruct_code).allow_halt(); - register_mega_specs(&mut group, selfdestruct_specs, &workload); - group.finish(); -} - -// -// ============================================================================ -// CALL with Value to Empty Account Benchmark -// ============================================================================ -// -// When CALL transfers value to an empty (non-existent) account, mega-evm -// charges dynamic account creation gas via SALT bucket pricing. -// This benchmark compares: -// - CALL with value to existing account (no creation cost) -// - CALL with value to empty account (triggers account creation gas) -// - -fn bench_call_value_empty_account(c: &mut Criterion) { - let existing_target: Address = address!("cccccccccccccccccccccccccccccccccccccccc"); - let empty_target: Address = address!("dddddddddddddddddddddddddddddddddddddddd"); - - // Build bytecode: CALL(gas, target, value=1wei, argsOff=0, argsLen=0, retOff=0, retLen=0) - let make_call_with_value = |target: Address, n: usize| -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..n { - builder = builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value = 1 wei - .push_address(target) - .append(GAS) - .append(CALL) - .append(POP); - } - builder.build() - }; - - let call_existing = make_call_with_value(existing_target, 50); - let call_empty = make_call_with_value(empty_target, 50); - - let mut group = c.benchmark_group("call_value_empty_account"); - - // Variant: existing target has a balance; CALL hits an existing account. - let existing = Workload::single( - vec![ - Account::new(CONTRACT).code(call_existing), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - Account::new(existing_target).balance(U256::from(1)), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ); - register_all_suffixed(&mut group, "existing_account_50", &existing); - - // Variant: empty target — CALL with value triggers account creation gas. - register_all_suffixed(&mut group, "empty_account_50", &mega_contract_workload(call_empty)); - - group.finish(); -} - -// -// ============================================================================ -// System Contract Interception Benchmarks -// ============================================================================ -// - -/// Oracle contract address. -const ORACLE_ADDRESS: Address = address!("6342000000000000000000000000000000000001"); - -fn make_staticcall_bytecode(target: Address, selector: [u8; 4]) -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, selector); - builder = builder - .push_number(32u64) - .push_number(32u64) - .push_number(4u64) - .push_number(0u64) - .push_address(target) - .append(GAS) - .append(STATICCALL) - .append(POP); - builder.build() -} - -fn make_repeated_staticcall_bytecode( - target: Address, - selector: [u8; 4], - iterations: usize, -) -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, selector); - for _ in 0..iterations { - builder = builder - .push_number(32u64) - .push_number(32u64) - .push_number(4u64) - .push_number(0u64) - .push_address(target) - .append(GAS) - .append(STATICCALL) - .append(POP); - } - builder.build() -} - -fn bench_system_contract(c: &mut Criterion) { - let access_control_addr: Address = address!("6342000000000000000000000000000000000004"); - let is_disabled_selector: [u8; 4] = [0x9e, 0x8e, 0x7b, 0xc0]; - let limit_control_addr: Address = address!("6342000000000000000000000000000000000005"); - let remaining_gas_selector: [u8; 4] = [0xde, 0x85, 0xee, 0xf5]; - let empty_contract_code = Bytes::from_static(&[STOP]); - - // A `CONTRACT` that STATICCALLs `SECONDARY` (a regular contract), used as - // the non-system-contract baseline for the interception comparison. - let regular_workload = |code: Bytes| { - Workload::single( - vec![ - Account::new(CONTRACT).code(code), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - Account::new(SECONDARY).code(empty_contract_code.clone()), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) - }; - - // REX5 is included so the `frame_init` hot path additions (CALL_STACK_LIMIT - // depth guard + zero-copy `peek_selector`) are measured against REX4 as the - // pre-fix baseline. Both specs go through the same interceptor dispatch on - // CALL/STATICCALL to a system contract, so the delta isolates the new logic. - const SYSTEM_CONTRACT_SPECS: &[(&str, MegaSpecId)] = - &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - // Single call benchmarks - { - let mut group = c.benchmark_group("system_contract_single"); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "access_control", - &mega_contract_workload(make_staticcall_bytecode( - access_control_addr, - is_disabled_selector, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "limit_control", - &mega_contract_workload(make_staticcall_bytecode( - limit_control_addr, - remaining_gas_selector, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "regular_contract", - ®ular_workload(make_staticcall_bytecode(SECONDARY, [0x00, 0x00, 0x00, 0x00])), - ); - group.finish(); - } - - // Repeated calls (100 iterations) - { - let n = 100; - let mut group = c.benchmark_group("system_contract_100x"); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "access_control", - &mega_contract_workload(make_repeated_staticcall_bytecode( - access_control_addr, - is_disabled_selector, - n, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "limit_control", - &mega_contract_workload(make_repeated_staticcall_bytecode( - limit_control_addr, - remaining_gas_selector, - n, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "regular_contract", - ®ular_workload(make_repeated_staticcall_bytecode( - SECONDARY, - [0x00, 0x00, 0x00, 0x00], - n, - )), - ); - group.finish(); - } -} - -// -// ============================================================================ -// DELEGATECALL to System Contract Benchmark -// ============================================================================ -// -// System contracts are intercepted on CALL but NOT on DELEGATECALL. -// DELEGATECALL falls through to on-chain bytecode (or reverts if no code). -// This is a security-relevant boundary. -// - -fn bench_delegatecall_system_contract(c: &mut Criterion) { - let access_control_addr: Address = address!("6342000000000000000000000000000000000004"); - let is_disabled_selector: [u8; 4] = [0x9e, 0x8e, 0x7b, 0xc0]; - let rex4: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4)]; - - // STATICCALL to system contract — intercepted, returns result - let staticcall_code = make_staticcall_bytecode(access_control_addr, is_disabled_selector); - - // DELEGATECALL to system contract — NOT intercepted, falls through - let delegatecall_code = { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, is_disabled_selector); - // DELEGATECALL(gas, target, argsOffset, argsSize, retOffset, retSize) - builder = builder - .push_number(32u64) // retSize - .push_number(32u64) // retOffset - .push_number(4u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(access_control_addr) - .append(GAS) - .append(DELEGATECALL) - .append(POP); - builder.build() - }; - - let mut group = c.benchmark_group("delegatecall_system_contract"); - register_mega_specs_suffixed( - &mut group, - rex4, - "staticcall_intercepted", - &mega_contract_workload(staticcall_code), - ); - // DELEGATECALL falls through to absent bytecode and may halt, so allow it. - register_mega_specs_suffixed( - &mut group, - rex4, - "delegatecall_not_intercepted", - &mega_contract_workload(delegatecall_code).allow_halt(), - ); - group.finish(); -} - -// -// ============================================================================ -// Oracle SLOAD Benchmark -// ============================================================================ -// - -fn bench_oracle_sload(c: &mut Criterion) { - let sload_bytecode = generate_sload_bytecode(50); - - let mut group = c.benchmark_group("oracle_sload"); - // Regular SLOAD against a normal contract. - register_mega_suffixed( - &mut group, - "regular_sload_50", - &mega_contract_workload(sload_bytecode.clone()), - ); - // Oracle SLOAD: the same bytecode runs at the oracle address, where reads - // are forced cold. - let oracle = Workload::single( - vec![ - Account::new(ORACLE_ADDRESS).code(sload_bytecode), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, ORACLE_ADDRESS).gas_limit(FEATURE_GAS_LIMIT), - ); - register_mega_suffixed(&mut group, "oracle_sload_50", &oracle); - group.finish(); -} - -// -// ============================================================================ -// Mixed Workload Benchmark -// ============================================================================ -// - -fn generate_mixed_workload_bytecode() -> Bytes { - let mut builder = BytecodeBuilder::default(); - // Volatile data access - builder = builder.append(TIMESTAMP).append(POP).append(COINBASE).append(POP); - // Storage writes - for i in 0..20u64 { - builder = builder.push_number(i + 1).push_number(i).append(SSTORE); - } - // Log emissions - for _ in 0..10 { - builder = - builder.push_number(0xdead_beef_u64).push_number(32u64).push_number(0u64).append(LOG1); - } - // Computation - for _ in 0..50 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() -} - -fn bench_mixed_workload(c: &mut Criterion) { - let mut group = c.benchmark_group("mixed_workload"); - register_all(&mut group, &mega_contract_workload(generate_mixed_workload_bytecode())); - group.finish(); -} - -// -// ============================================================================ -// EIP-7702 Authorization-List Scaling Benchmark -// ============================================================================ -// -// REX5 records state growth for EIP-7702 authority accounts during -// pre-execution (`record_eip7702_authority_state_growth`). For each -// authorization it consults a transaction-local collection of already-seen -// authorities; with a `Vec` that lookup is O(N) per authorization, hence O(N²) -// over the list — a node-CPU amplification an attacker can drive with ~1200 -// unique authorities in one 30M-gas type-4 tx. The `BTreeMap`-based -// implementation bounds the pass at O(N log N). -// -// The benchmark sweeps the authority count so a quadratic term shows up as -// super-linear growth (a map-based implementation grows linearly). Authorities -// are pre-recovered (`RecoveredAuthority::Valid`) so no ecrecover cost dilutes -// the measured scan; each is distinct and absent from state, so every one -// passes validation and exercises the full lookup. -// -// This bench builds the mega EVM directly instead of going through the -// `Workload` harness: `TxSpec` is deliberately backend-agnostic and carries no -// authorization list, and only mega rows are meaningful for this REX5-only -// pre-execution path. -// - -const AUTH_DELEGATE: Address = address!("0000000000000000000000000000000000900001"); - -fn make_recovered_auth_list(n: usize) -> Vec { - (0..n) - .map(|i| { - let mut bytes = [0u8; 20]; - bytes[12..20].copy_from_slice(&((i as u64) + 0x0010_0000).to_be_bytes()); - RecoveredAuthorization::new_unchecked( - // chain_id 0 = chain-agnostic, always valid regardless of cfg - Authorization { chain_id: U256::ZERO, address: AUTH_DELEGATE, nonce: 0 }, - RecoveredAuthority::Valid(Address::from(bytes)), - ) - }) - .collect() -} - -fn bench_eip7702_authlist(c: &mut Criterion) { - let mut group = c.benchmark_group("eip7702_authlist"); - for &n in &[150usize, 400, 800, 1200] { - let auth_list = make_recovered_auth_list(n); - let db = - MemoryDatabase::default().account_balance(CALLER, U256::from(10).pow(U256::from(24))); - group.bench_function(format!("rex5/{n}"), |b| { - b.iter(|| { - let mut context = MegaContext::new(db.clone(), MegaSpecId::REX5); - // Match the harness's Mega subject: the op-revm base panics on - // unset operator-fee fields, so zero them explicitly. - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::<_, NoOpInspector, EmptyExternalEnv>::new(context); - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(100_000_000) - .authorization_list_recovered(auth_list.clone()) - .build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - black_box(evm.transact(mega_tx)) - }) - }); - } - group.finish(); -} - -// -// ============================================================================ -// STATICCALL → SELFDESTRUCT Unmetered-Work Benchmark -// ============================================================================ -// -// Without the `is_static` early-exit guard, the REX5 SELFDESTRUCT wrapper -// (`storage_gas_ext::selfdestruct`) inspects the beneficiary and caller -// accounts and runs SALT account-creation pricing BEFORE the inner interpreter -// reaches revm's static-context check and halts. Inside a STATICCALL frame -// that host work is always wasted: the frame reverts. An attacker repeats it -// via STATICCALL → selfdestruct in a loop. -// -// The parent loops fixed-gas STATICCALLs to a SELFDESTRUCT child; a STOP-child -// row is the control the early-exit guard must NOT change, so the wasted host -// work is the difference between the two rows. -// - -const SD_CHILD: Address = address!("00000000000000000000000000000000000a0001"); - -/// Parent that performs `iterations` STATICCALLs to `target`, each forwarding a -/// fixed `gas_each` (not all remaining gas, so one reverting child cannot drain -/// the parent), then STOPs. -fn make_repeated_staticcall_fixedgas(target: Address, gas_each: u64, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(target) - .push_number(gas_each) // forwarded gas (fixed) - .append(STATICCALL) - .append(POP); - } - builder.append(STOP).build() -} - -fn bench_staticcall_selfdestruct(c: &mut Criterion) { - const ITERS: usize = 500; - const GAS_EACH: u64 = 200_000; - let parent_code = make_repeated_staticcall_fixedgas(SD_CHILD, GAS_EACH, ITERS); - // SELFDESTRUCT(beneficiary=0): halts on the static-context check inside revm. - let sd_child: Bytes = vec![PUSH0, SELFDESTRUCT].into(); - // control: pure STOP — same STATICCALL frame cost, no SELFDESTRUCT host work. - let stop_child: Bytes = vec![STOP].into(); - - let workload = |child_code: Bytes| { - Workload::single( - vec![ - Account::new(CONTRACT).code(parent_code.clone()), - // fund the child so the SELFDESTRUCT `has_value` branch (SALT - // pricing) triggers - Account::new(SD_CHILD).code(child_code).balance(U256::from(1u64)), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) - }; - - const REX5_ONLY: &[(&str, MegaSpecId)] = &[("rex5", MegaSpecId::REX5)]; - let mut group = c.benchmark_group("staticcall_selfdestruct"); - register_mega_specs_suffixed( - &mut group, - REX5_ONLY, - &format!("selfdestruct_child/{ITERS}"), - &workload(sd_child), - ); - register_mega_specs_suffixed( - &mut group, - REX5_ONLY, - &format!("stop_child/{ITERS}"), - &workload(stop_child), - ); - group.finish(); -} - -// -// ============================================================================ -// SALT Dynamic-Gas Benchmarks -// ============================================================================ -// -// Isolates the SALT dynamic-gas path cost. For each storage-write workload, -// three rows run the SAME spec + workload: -// - `revm_pinned`: the env-agnostic absolute floor (no mega overhead). -// - `rex5`: mega over `EmptyExternalEnv`, where the SALT path short-circuits to a constant -// `MIN_BUCKET_SIZE` (no hash, no map lookup). -// - `rex5_salt`: mega over a crowded `TestExternalEnvs` (FNV hash + HashMap lookup + multiply -// per touched bucket). -// The `rex5_salt` − `rex5` gap is the isolated SALT-path cost. -// -// There is NO multiplier sweep: the bucket-capacity multiplier changes the gas -// AMOUNT charged, not the compute performed, so it does not move wall-clock time -// (verified empirically — x1 ≈ x32). A single crowded capacity -// (32 × MIN_BUCKET_SIZE) keeps the multiply operand non-trivial; what exercises -// the path is the number of distinct buckets touched, which `sstore_100` already -// drives to ~100. -// -// Only SSTORE / new-account / CREATE consult the SALT bucket multiplier; LOG -// storage gas uses a FIXED 10× multiplier (compile-time constants charged in -// `storage_gas_ext::log` without calling `load_bucket_cost_multiplier`), so a -// LOG workload would show ~0 gap — the crowded `TestExternalEnvs` is inert for -// LOG. The workloads below are therefore limited to `sstore_100` and `create_10`, -// both of which genuinely drive `load_bucket_cost_multiplier`. - -fn bench_salt_dynamic_gas(c: &mut Criterion) { - use mega_evm::MIN_BUCKET_SIZE; - - let workloads: &[(&str, Bytes)] = &[ - ("sstore_100", generate_sstore_bytecode(SSTORE_ITERATIONS)), - ("create_10", make_create_bytecode(10)), - ]; - - let mut group = c.benchmark_group("salt_dynamic_gas"); - for (wl_name, bytecode) in workloads { - let workload = mega_contract_workload(bytecode.clone()); - let crowded = mega_evm::TestExternalEnvs::::new() - .with_default_bucket_capacity(32 * MIN_BUCKET_SIZE as u64); - common::register_env_isolation( - &mut group, - MegaSpecId::REX5, - "rex5", - "rex5_salt", - crowded, - wl_name, - &workload, - ); - } - group.finish(); -} - -// -// ============================================================================ -// Oracle Real-Data Benchmark -// ============================================================================ -// -// Characterizes the real oracle SLOAD path (`host.rs::sload`), which no prior -// bench drove with populated oracle storage. At the oracle address `sload` -// forks on `get_oracle_storage(key)`: `Some(value)` early-returns and bypasses -// the journal entirely (oracle HIT); `None` falls through to the full journal -// SLOAD (`inner.sload`) for each slot (oracle MISS). -// -// Three rows, same shape as bench_salt_dynamic_gas: -// - `revm_pinned`: raw SLOAD floor — no oracle machinery at all. -// - ``: oracle SLOAD MISS — Mega over EmptyExternalEnv, where `get_oracle_storage` -// returns `None` and each slot falls through to the journal SLOAD. -// - `_oracle`: oracle SLOAD HIT — MegaWithEnv over populated TestExternalEnvs, where -// `get_oracle_storage` serves real data and early-returns past the journal. -// -// The `_oracle` − `` gap is the HIT-vs-MISS *structural* cost of the -// oracle SLOAD path (early-return vs journal traversal), NOT an isolated -// `get_oracle_storage` lookup microcost. The path forks structurally on hit vs -// miss, so — unlike the SALT bucket-multiply — the lookup cost cannot be isolated -// further; this bench characterizes the hit / miss / floor costs of the real -// oracle path. Address-based oracle gas detention fires identically on both mega -// rows, so it does not enter the gap. -// - -fn bench_oracle_real_data(c: &mut Criterion) { - let sload_bytecode = generate_sload_bytecode(50); - let workload = Workload::single( - vec![ - Account::new(ORACLE_ADDRESS).code(sload_bytecode), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, ORACLE_ADDRESS).gas_limit(FEATURE_GAS_LIMIT), - ); - - // Populate the first 50 oracle slots with non-zero values. - let mut env = mega_evm::TestExternalEnvs::::new(); - for slot in 0u64..50 { - env = env.with_oracle_storage(U256::from(slot), U256::from(slot + 1)); - } - - let mut group = c.benchmark_group("oracle_real_data"); - // REX4: includes the revm_pinned floor row (registered only once per group). - common::register_env_isolation( - &mut group, - MegaSpecId::REX4, - "rex4", - "rex4_oracle", - env.clone(), - "oracle_sload_50", - &workload, - ); - // REX5: omit revm_pinned (already registered above — duplicate IDs panic). - common::register_env_isolation_mega_only( - &mut group, - MegaSpecId::REX5, - "rex5", - "rex5_oracle", - env, - "oracle_sload_50", - &workload, - ); - group.finish(); -} - -criterion_group!( - benches, - bench_volatile_data, - bench_gas_detention_computation, - bench_log_opcodes, - bench_sstore, - bench_create_deploy, - bench_selfdestruct, - bench_call_value_empty_account, - bench_system_contract, - bench_delegatecall_system_contract, - bench_oracle_sload, - bench_oracle_real_data, - bench_mixed_workload, - bench_eip7702_authlist, - bench_staticcall_selfdestruct, - bench_salt_dynamic_gas, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/revm_bench.rs b/crates/mega-evm/benches/revm_bench.rs deleted file mode 100644 index 47cefe542..000000000 --- a/crates/mega-evm/benches/revm_bench.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Benchmarks ported from upstream revm. -//! -//! These benchmarks are adapted from revm's revme bench suite to measure equivalent -//! workloads through mega-evm's execution pipeline, enabling performance comparison -//! between vanilla revm, op-revm, and mega-evm. -//! -//! Each workload runs against five layers so a single `cargo bench` produces a -//! comparable table: -//! -//! 1. `revm_pinned` — vanilla `revm::Evm` at the version mega-evm currently pins. -//! 2. `revm_latest` — vanilla `revm::Evm` at the latest crates.io release. -//! 3. `op_revm_pinned` — `op_revm::OpEvm` at the version mega-evm currently pins (operator fee = -//! 0). -//! 4. `op_revm_latest` — `op_revm::OpEvm` at the latest crates.io release (operator fee = 0). -//! 5. `mega_` — `MegaEvm` at `EQUIVALENCE` / `MINI_REX` / `REX4` / `REX5`. -//! -//! Ported workloads: -//! - **snailtracer**: CPU-intensive ray tracer exercising many opcodes -//! - **analysis**: ERC20-like contract bytecode execution -//! - **subcall**: Multi-level contract call performance (1000 iterations) -//! - **`transfer_multi`**: Batch transaction execution (1000 transfers) -//! -//! New workloads must avoid touching mega-evm's per-tx resource limits -//! (compute gas / data size / KV updates / state growth) under any spec, or the -//! `mega_*` row would halt early and skew the baseline comparison. -//! Likewise, every vanilla baseline is pinned to a Cancun-equivalent fork -//! (`revm` rows to Cancun, `op-revm` rows to Holocene) in `common::subject`, so -//! a new workload must execute successfully under Cancun semantics on every row. - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{criterion_group, criterion_main, Criterion}; -use revm::bytecode::opcode; - -mod common; -use common::{register_all, Account, TxSpec, Workload}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -const SUBCALL_TARGET_A: Address = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); -const SUBCALL_TARGET_B: Address = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - -// -// ============================================================================ -// Snailtracer Benchmark -// ============================================================================ -// -// A CPU-intensive ray tracer that exercises many opcodes. -// This is the standard EVM performance benchmark from upstream revm. -// - -const SNAILTRACER_BYTES: &str = include_str!("data/snailtracer.hex"); - -fn bench_snailtracer(c: &mut Criterion) { - let bytecode = Bytes::from(hex::decode(SNAILTRACER_BYTES).unwrap()); - let calldata = bytes!("30627b7c"); - let caller_balance = U256::from(10).pow(U256::from(18)); - - let mut group = c.benchmark_group("snailtracer"); - group.sample_size(10); - - let workload = Workload::single( - vec![Account::new(CONTRACT).code(bytecode), Account::new(CALLER).balance(caller_balance)], - TxSpec::call(CALLER, CONTRACT).gas_limit(1_000_000_000).data(calldata), - ); - register_all(&mut group, &workload); - group.finish(); -} - -// -// ============================================================================ -// Analysis Benchmark -// ============================================================================ -// -// Exercises ERC20-like contract bytecode execution. -// Measures bytecode analysis and execution performance. -// - -const ANALYSIS_BYTES: &str = include_str!("data/analysis.hex"); - -fn bench_analysis(c: &mut Criterion) { - let bytecode = Bytes::from(hex::decode(ANALYSIS_BYTES).unwrap()); - let calldata = bytes!("8035F0CE"); - let caller_balance = U256::from(10).pow(U256::from(18)); - - let mut group = c.benchmark_group("analysis"); - - let workload = Workload::single( - vec![Account::new(CONTRACT).code(bytecode), Account::new(CALLER).balance(caller_balance)], - TxSpec::call(CALLER, CONTRACT).gas_limit(10_000_000_000).data(calldata), - ); - register_all(&mut group, &workload); - group.finish(); -} - -// -// ============================================================================ -// Subcall Benchmarks -// ============================================================================ -// -// Measures contract CALL overhead with three variants: -// - 1000 subcalls with 1 wei value transfer -// - 1000 subcalls with no value (same account) -// - 1000 nested subcalls (each target does another subcall) -// - -/// Constructs bytecode that loops 1000 times, each iteration doing a CALL to `target` -/// with the given `value` (0 or 1 wei). -fn make_loop_call_bytecode(target: Address, value: u8) -> Bytes { - let mut code = vec![ - opcode::PUSH2, - 0x03, - 0xE8, // PUSH2 1000 — loop counter - opcode::JUMPDEST, // loop_start at offset 3 - opcode::PUSH1, - 0x00, // retSize - opcode::PUSH1, - 0x00, // retOffset - opcode::PUSH1, - 0x00, // argsSize - opcode::PUSH1, - 0x00, // argsOffset - opcode::PUSH1, - value, // value - opcode::PUSH20, // target address - ]; - code.extend_from_slice(target.as_slice()); - code.extend_from_slice(&[ - opcode::GAS, // forward all remaining gas - opcode::CALL, - opcode::POP, // discard success/failure - opcode::PUSH1, - 0x01, // decrement counter - opcode::SWAP1, - opcode::SUB, - opcode::DUP1, // duplicate counter for JUMPI check - opcode::PUSH1, - 0x03, // jump target (JUMPDEST offset) - opcode::JUMPI, // jump back if counter != 0 - opcode::POP, // clean up remaining counter (0) - opcode::STOP, - ]); - code.into() -} - -/// Minimal contract that just STOPs. -fn make_stop_bytecode() -> Bytes { - Bytes::from_static(&[opcode::STOP]) -} - -/// Constructs bytecode that does a single CALL (no value) to `target`, then STOPs. -fn make_subcall_bytecode(target: Address) -> Bytes { - let mut code = vec![ - opcode::PUSH1, - 0x00, // retSize - opcode::PUSH1, - 0x00, // retOffset - opcode::PUSH1, - 0x00, // argsSize - opcode::PUSH1, - 0x00, // argsOffset - opcode::PUSH1, - 0x00, // value (no transfer) - opcode::PUSH20, // target address - ]; - code.extend_from_slice(target.as_slice()); - code.extend_from_slice(&[opcode::GAS, opcode::CALL, opcode::POP, opcode::STOP]); - Bytes::from(code) -} - -/// Benchmark one subcall variant across the 4 baselines and mega specs. The -/// contract at `CONTRACT` drives the loop, so the tx itself just calls it with -/// a high gas limit and no value. -fn bench_subcall_variant( - group: &mut criterion::BenchmarkGroup<'_, criterion::measurement::WallTime>, - accounts: Vec, -) { - const SUBCALL_GAS_LIMIT: u64 = 10_000_000_000; - let workload = - Workload::single(accounts, TxSpec::call(CALLER, CONTRACT).gas_limit(SUBCALL_GAS_LIMIT)); - register_all(group, &workload); -} - -fn bench_subcall(c: &mut Criterion) { - let caller_balance = U256::from(u128::MAX); - - // Variant 1: 1000 subcalls each transferring 1 wei - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 1); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_transfer_1wei"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(stop_code), - ], - ); - group.finish(); - } - - // Variant 2: 1000 subcalls with no value transfer - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 0); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_no_value"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(stop_code), - ], - ); - group.finish(); - } - - // Variant 3: 1000 nested subcalls (each target does another subcall) - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 0); - let subcall_code = make_subcall_bytecode(SUBCALL_TARGET_B); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_nested"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(subcall_code), - Account::new(SUBCALL_TARGET_B).code(stop_code), - ], - ); - group.finish(); - } -} - -// -// ============================================================================ -// Transfer Multi Benchmark -// ============================================================================ -// -// Measures batch transaction execution: 1000 sequential ether transfers run on -// one reused EVM (a subject loops the workload's tx list internally). -// - -fn bench_transfer_multi(c: &mut Criterion) { - let mut group = c.benchmark_group("transfer_multi_1000"); - group.sample_size(10); - - let base = U256::from(10_000); - let targets: Vec
= - (0..1000u64).map(|i| Address::from_word((base + U256::from(i)).into())).collect(); - let caller_balance = U256::from(3_000_000_000u64); - let target_balance = U256::from(3_000_000_000u64); - - let mut accounts = vec![Account::new(CALLER).balance(caller_balance)]; - accounts.extend(targets.iter().map(|t| Account::new(*t).balance(target_balance))); - - let txs: Vec = targets - .iter() - .map(|t| TxSpec::call(CALLER, *t).value(U256::from(1)).gas_limit(100_000)) - .collect(); - - let workload = Workload::new(accounts, txs); - register_all(&mut group, &workload); - group.finish(); -} - -criterion_group!(benches, bench_snailtracer, bench_analysis, bench_subcall, bench_transfer_multi,); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs deleted file mode 100644 index 6636c3322..000000000 --- a/crates/mega-evm/benches/transact.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Benchmarks for the `ExecuteEvm::transact()` interface. -//! -//! Each workload runs against four vanilla baselines (`revm_pinned`, -//! `revm_latest`, `op_revm_pinned`, `op_revm_latest`) and four mega specs -//! (`EQUIVALENCE`, `MINI_REX`, `REX4`, `REX5`) so a single bench produces a -//! cross-row gap table. -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{criterion_group, criterion_main, Criterion}; -use revm::primitives::{keccak256, B256}; - -mod common; -use common::{register_all, Account, TxSpec, Workload}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const WETH9_ADDRESS: Address = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); - -/// WETH9 deployed runtime bytecode. -const WETH9_RUNTIME_CODE: Bytes = bytes!("6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b9578063095ea7b31461014757806318160ddd146101a157806323b872dd146101ca5780632e1a7d4d14610243578063313ce5671461026657806370a082311461029557806395d89b41146102e2578063a9059cbb14610370578063d0e30db0146103ca578063dd62ed3e146103d4575b6100b7610440565b005b34156100c457600080fd5b6100cc6104dd565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561010c5780820151818401526020810190506100f1565b50505050905090810190601f1680156101395780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015257600080fd5b610187600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061057b565b604051808215151515815260200191505060405180910390f35b34156101ac57600080fd5b6101b461066d565b6040518082815260200191505060405180910390f35b34156101d557600080fd5b610229600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061068c565b604051808215151515815260200191505060405180910390f35b341561024e57600080fd5b61026460048080359060200190919050506109d9565b005b341561027157600080fd5b610279610b05565b604051808260ff1660ff16815260200191505060405180910390f35b34156102a057600080fd5b6102cc600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b18565b6040518082815260200191505060405180910390f35b34156102ed57600080fd5b6102f5610b30565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561033557808201518184015260208101905061031a565b50505050905090810190601f1680156103625780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561037b57600080fd5b6103b0600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610bce565b604051808215151515815260200191505060405180910390f35b6103d2610440565b005b34156103df57600080fd5b61042a600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610be3565b6040518082815260200191505060405180910390f35b34600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055503373ffffffffffffffffffffffffffffffffffffffff167fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c346040518082815260200191505060405180910390a2565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105735780601f1061054857610100808354040283529160200191610573565b820191906000526020600020905b81548152906001019060200180831161055657829003601f168201915b505050505081565b600081600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60003073ffffffffffffffffffffffffffffffffffffffff1631905090565b600081600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101515156106dc57600080fd5b3373ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16141580156107b457507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205414155b156108cf5781600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015151561084457600080fd5b81600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b81600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a2757600080fd5b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f193505050501515610ab457600080fd5b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65826040518082815260200191505060405180910390a250565b600260009054906101000a900460ff1681565b60036020528060005260406000206000915090505481565b60018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610bc65780601f10610b9b57610100808354040283529160200191610bc6565b820191906000526020600020905b815481529060010190602001808311610ba957829003601f168201915b505050505081565b6000610bdb33848461068c565b905092915050565b60046020528160005260406000206020528060005260406000206000915091505054815600a165627a7a72305820deb4c2ccab3c2fdca32ab3f46728389c2fe2c165d5fafa07661e4e004f6c344a0029"); - -/// Calculate the storage slot for an ERC20 balance mapping. -/// Solidity mapping storage slot = keccak256(abi.encode(key, slot)) -fn erc20_balance_slot(address: Address, mapping_slot: u8) -> B256 { - let mut data = [0u8; 64]; - // Encode address (left-padded to 32 bytes) - data[12..32].copy_from_slice(address.as_slice()); - // Encode mapping slot - data[63] = mapping_slot; - keccak256(data) -} - -/// Benchmark empty transaction (call with no value or data). -fn bench_empty_transaction(c: &mut Criterion) { - let mut group = c.benchmark_group("empty_transaction"); - // No accounts seeded — caller and callee don't exist (gas price is zero, so - // the caller needs no balance), matching the original workload. - let workload = Workload::single(vec![], TxSpec::call(CALLER, CALLEE)); - register_all(&mut group, &workload); - group.finish(); -} - -/// Benchmark simple ether transfer between existing accounts. -fn bench_simple_ether_transfer(c: &mut Criterion) { - let mut group = c.benchmark_group("simple_ether_transfer"); - let workload = Workload::single( - vec![ - Account::new(CALLER).balance(U256::from(1000)), - Account::new(CALLEE).balance(U256::from(100)), - ], - TxSpec::call(CALLER, CALLEE), - ); - register_all(&mut group, &workload); - group.finish(); -} - -/// Benchmark WETH9 ERC20 transfer. -fn bench_weth9_transfer(c: &mut Criterion) { - let mut group = c.benchmark_group("weth9_transfer"); - - // Transfer amount: 100 WETH - let transfer_amount = U256::from(100) * U256::from(10).pow(U256::from(18)); - - // Encode transfer(address,uint256) call. Function selector: 0xa9059cbb. - let mut calldata = Vec::with_capacity(68); - calldata.extend_from_slice(&[0xa9, 0x05, 0x9c, 0xbb]); - calldata.extend_from_slice(&[0u8; 12]); - calldata.extend_from_slice(CALLEE.as_slice()); - calldata.extend_from_slice(&transfer_amount.to_be_bytes::<32>()); - let calldata = Bytes::from(calldata); - - let caller_weth_balance = U256::from(1000) * U256::from(10).pow(U256::from(18)); - let caller_gas_balance = U256::from(10).pow(U256::from(18)); - let balance_slot: U256 = erc20_balance_slot(CALLER, 3).into(); - - let workload = Workload::single( - vec![ - Account::new(WETH9_ADDRESS) - .code(WETH9_RUNTIME_CODE) - .storage(balance_slot, caller_weth_balance), - Account::new(CALLER).balance(caller_gas_balance), - ], - TxSpec::call(CALLER, WETH9_ADDRESS).data(calldata), - ); - register_all(&mut group, &workload); - group.finish(); -} - -criterion_group!( - benches, - bench_empty_transaction, - bench_simple_ether_transfer, - bench_weth9_transfer -); -criterion_main!(benches); diff --git a/crates/mega-evm/examples/beneficiary_access_tracking.rs b/crates/mega-evm/examples/beneficiary_access_tracking.rs deleted file mode 100644 index ddf76e290..000000000 --- a/crates/mega-evm/examples/beneficiary_access_tracking.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! This example demonstrates the beneficiary access detection feature. -//! It creates contracts that access beneficiary account data and shows how -//! the system can detect when such access occurs during execution. -//! -//! The contracts tested are: -//! 1. Contract 1: Reads beneficiary balance (should trigger access detection) -//! 2. Contract 2: Does NOT access beneficiary data (should not trigger detection) -//! 3. Contract 3: Accesses beneficiary via different operations (should trigger detection) - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{MegaContext, MegaEvm, MegaSpecId, MegaTransaction}; -use revm::{ - bytecode::opcode::{BALANCE, CALLER, POP, PUSH20, STOP}, - context::{BlockEnv, ContextSetters, ContextTr, TxEnv}, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - primitives::TxKind, - state::{AccountInfo, Bytecode}, -}; - -fn main() -> Result<(), Box> { - println!("=== Beneficiary Access Tracking Demo ===\n"); - - // Create database and EVM context - let mut db = CacheDB::::default(); - let spec = MegaSpecId::MINI_REX; - let beneficiary = address!("0000000000000000000000000000000000000001"); - - // Contract 1: Reads beneficiary balance - let contract1_address = address!("0000000000000000000000000000000000100001"); - let mut contract1_code = vec![]; - // Push beneficiary address onto stack - contract1_code.push(PUSH20); - contract1_code.extend(beneficiary.as_slice()); - // Get balance of beneficiary - contract1_code.push(BALANCE); - contract1_code.push(POP); // Remove result from stack - contract1_code.push(STOP); - set_account_code(&mut db, contract1_address, contract1_code.into()); - - // Contract 2: Does NOT access beneficiary (uses CALLER) - let contract2_address = address!("0000000000000000000000000000000000100002"); - let contract2_code = vec![CALLER, POP, STOP]; - set_account_code(&mut db, contract2_address, contract2_code.into()); - - // Contract 3: Accesses beneficiary balance (same as contract 1, but separate test) - let contract3_address = address!("0000000000000000000000000000000000100003"); - let mut contract3_code = vec![]; - // Push beneficiary address onto stack - contract3_code.push(PUSH20); - contract3_code.extend(beneficiary.as_slice()); - // Get balance of beneficiary - contract3_code.push(BALANCE); - contract3_code.push(POP); - contract3_code.push(STOP); - set_account_code(&mut db, contract3_address, contract3_code.into()); - - // Create EVM instance with properly configured context - let mut context = MegaContext::new(db, spec); - - // Set the beneficiary in the block environment - let block_env = BlockEnv { beneficiary, ..Default::default() }; - context.set_block(block_env); - - // Set operator fee fields to zero to avoid panic in MINI_REX spec - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - - let mut evm = MegaEvm::new(context); - - let caller = address!("0000000000000000000000000000000000100000"); - - // Test Contract 1 (reads beneficiary balance) - println!("Testing Contract 1 (reads beneficiary balance):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx1 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract1_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, // Use reasonable gas limit - ..Default::default() - }, - ..Default::default() - }; - - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1)?; - println!(" Transaction successful: {}", result1.result.is_success()); - println!(" Gas used: {}", result1.result.gas_used()); - - // Verify that beneficiary access was detected - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!( - beneficiary_accessed, - "Contract 1 should have detected beneficiary access (balance read)!" - ); - assert!(result1.result.is_success(), "Contract 1 transaction should succeed"); - - // Reset for next transaction - evm.ctx_mut().reset_volatile_data_access(); - println!(" After reset: no beneficiary access detected\n"); - - // Test Contract 2 (does NOT access beneficiary) - println!("Testing Contract 2 (does NOT access beneficiary):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx2 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract2_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, - ..Default::default() - }, - ..Default::default() - }; - - let result2 = alloy_evm::Evm::transact_raw(&mut evm, tx2)?; - println!(" Transaction successful: {}", result2.result.is_success()); - println!(" Gas used: {}", result2.result.gas_used()); - - // Verify that beneficiary was NOT accessed - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!(!beneficiary_accessed, "Contract 2 should NOT have detected beneficiary access!"); - assert!(result2.result.is_success(), "Contract 2 transaction should succeed"); - - // Reset for next transaction - evm.ctx_mut().reset_volatile_data_access(); - println!(" After reset: no beneficiary access detected\n"); - - // Test Contract 3 (accesses beneficiary balance) - println!("Testing Contract 3 (accesses beneficiary balance):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx3 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract3_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, - ..Default::default() - }, - ..Default::default() - }; - - let result3 = alloy_evm::Evm::transact_raw(&mut evm, tx3)?; - println!(" Transaction successful: {}", result3.result.is_success()); - println!(" Gas used: {}", result3.result.gas_used()); - - // Verify that beneficiary access was detected - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!( - beneficiary_accessed, - "Contract 3 should have detected beneficiary access (balance read)!" - ); - assert!(result3.result.is_success(), "Contract 3 transaction should succeed"); - - println!("\n=== Tracking Summary ==="); - println!("✅ Beneficiary access tracking is working correctly!"); - println!("✅ Contract 1 (balance read): Access tracked = true"); - println!("✅ Contract 2 (no access): Access tracked = false"); - println!("✅ Contract 3 (balance read): Access tracked = true"); - println!("✅ All tracking tests passed!"); - println!( - "\nThe system can accurately track when transactions access beneficiary account data." - ); - println!( - "This detection mechanism can be used for monitoring, analytics, or enforcement purposes." - ); - - Ok(()) -} - -/// Helper function to set account code -fn set_account_code(db: &mut CacheDB, address: alloy_primitives::Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = AccountInfo { code: Some(bytecode), code_hash, ..Default::default() }; - db.insert_account_info(address, account_info); -} diff --git a/crates/mega-evm/examples/block_env_tracking.rs b/crates/mega-evm/examples/block_env_tracking.rs deleted file mode 100644 index d42d02c22..000000000 --- a/crates/mega-evm/examples/block_env_tracking.rs +++ /dev/null @@ -1,184 +0,0 @@ -//! This example demonstrates the block environment access tracking in the EVM. -//! It creates three contracts that use different block environment accesses and -//! tests the tracking functionality. -//! -//! The contracts are: -//! 1. Contract 1: Uses single block environment access (NUMBER opcode) -//! 2. Contract 2: Uses multiple block environment accesses (NUMBER, TIMESTAMP, BASEFEE opcodes) -//! 3. Contract 3: Does NOT use block environment (CALLER opcode) - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{MegaContext, MegaEvm, MegaSpecId, MegaTransaction, VolatileDataAccess}; -use revm::{ - bytecode::opcode::{BASEFEE, CALLER, NUMBER, POP, STOP, TIMESTAMP}, - context::{ContextTr, TxEnv}, - database::{CacheDB, EmptyDB}, - primitives::TxKind, - state::{AccountInfo, Bytecode}, -}; - -fn main() -> Result<(), Box> { - // Create database and EVM context - let mut db = CacheDB::::default(); - let spec = MegaSpecId::MINI_REX; - - // Contract 1: Uses single block environment access (NUMBER opcode) - let contract1_address = address!("0000000000000000000000000000000000100001"); - let contract1_code = vec![NUMBER, STOP]; // Read block number then stop - set_account_code(&mut db, contract1_address, contract1_code.into()); - - // Contract 2: Uses multiple block environment accesses - let contract2_address = address!("0000000000000000000000000000000000100002"); - let contract2_code = vec![ - NUMBER, POP, // Read block number - TIMESTAMP, POP, // Read timestamp - BASEFEE, POP, // Read base fee - STOP, - ]; - set_account_code(&mut db, contract2_address, contract2_code.into()); - - // Contract 3: Does NOT use block environment (CALLER opcode) - let contract3_address = address!("0000000000000000000000000000000000100003"); - let contract3_code = vec![CALLER, STOP]; // Read caller then stop - set_account_code(&mut db, contract3_address, contract3_code.into()); - - // Create EVM instance with properly configured L1BlockInfo - let mut context = MegaContext::new(db, spec); - // Set operator fee fields to zero to avoid panic in MINI_REX (ISTHMUS) spec - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - let mut evm = MegaEvm::new(context); - - let caller = address!("0000000000000000000000000000000000100000"); - - println!("=== Block Environment Access Tracking Demo ===\n"); - - // Test Contract 1 (single block env access) - println!("Testing Contract 1 (uses NUMBER opcode):"); - - // Ensure clean state - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 1 - let tx1 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract1_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - ..Default::default() - }, - ..Default::default() - }; - - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1)?; - println!(" Transaction result: {:?}", result1.result.is_success()); - - let accesses1 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses1.is_empty()); - - // Show detailed access information - println!(" Access count: {}", accesses1.count_block_env_accessed()); - println!( - " Has accessed BlockNumber: {}", - accesses1.contains(VolatileDataAccess::BLOCK_NUMBER) - ); - - assert_eq!(accesses1.count_block_env_accessed(), 1); - assert!(accesses1.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(!accesses1.is_empty(), "Contract 1 should have accessed block env"); - - // Reset for next transaction - evm.reset_volatile_data_access(); - println!(" After reset: {}\n", evm.get_block_env_accesses().is_empty()); - - // Test Contract 2 (multiple block env accesses) - println!("Testing Contract 2 (uses NUMBER, TIMESTAMP, BASEFEE opcodes):"); - - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 2 - let tx2 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract2_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - nonce: 0, // Reset nonce for new transaction - ..Default::default() - }, - ..Default::default() - }; - - let result2 = alloy_evm::Evm::transact_raw(&mut evm, tx2)?; - println!(" Transaction result: {:?}", result2.result.is_success()); - - let accesses2 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses2.is_empty()); - - // Show detailed access information - println!(" Access count: {}", accesses2.count_block_env_accessed()); - println!( - " Has accessed BlockNumber: {}", - accesses2.contains(VolatileDataAccess::BLOCK_NUMBER) - ); - println!(" Has accessed Timestamp: {}", accesses2.contains(VolatileDataAccess::TIMESTAMP)); - println!(" Has accessed BaseFee: {}", accesses2.contains(VolatileDataAccess::BASE_FEE)); - - assert_eq!(accesses2.count_block_env_accessed(), 3); - assert!(accesses2.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(accesses2.contains(VolatileDataAccess::TIMESTAMP)); - assert!(accesses2.contains(VolatileDataAccess::BASE_FEE)); - assert!(!accesses2.is_empty(), "Contract 2 should have accessed block env"); - - // Reset for next transaction - evm.reset_volatile_data_access(); - println!(" After reset: {}\n", evm.get_block_env_accesses().is_empty()); - - // Test Contract 3 (does NOT access block env) - println!("Testing Contract 3 (uses CALLER opcode):"); - - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 3 - let tx3 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract3_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - nonce: 0, // Reset nonce for new transaction - ..Default::default() - }, - ..Default::default() - }; - - let result3 = alloy_evm::Evm::transact_raw(&mut evm, tx3)?; - println!(" Transaction result: {:?}", result3.result.is_success()); - - let accesses3 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses3.is_empty()); - - println!(" Access count: {}", accesses3.count_block_env_accessed()); - - assert_eq!(accesses3.count_block_env_accessed(), 0); - assert!(accesses3.is_empty(), "Contract 3 should NOT have accessed block env"); - - println!(" Demo finished"); - - Ok(()) -} - -/// Helper function to set account code -fn set_account_code(db: &mut CacheDB, address: alloy_primitives::Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = AccountInfo { code: Some(bytecode), code_hash, ..Default::default() }; - db.insert_account_info(address, account_info); -} diff --git a/crates/mega-evm/src/AGENTS.md b/crates/mega-evm/src/AGENTS.md deleted file mode 100644 index 0eab71d1c..000000000 --- a/crates/mega-evm/src/AGENTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Core MegaEVM crate implementation layer that composes execution, block processing, limits, system contracts, and external environments. - -## STRUCTURE -- `lib.rs`: crate module wiring, public re-exports, type aliases. -- `evm/`: transaction execution engine, instruction table, host hooks, context and factory. -- `block/`: block executor, hardfork mapping, block-level limit pipeline. -- `limit/`: per-tx and per-frame resource trackers plus exceed handling. -- `system/`: system contract addresses, deployment helpers, frame interceptors. -- `access/`: volatile-data access bitmaps and disable/enable depth tracking. -- `external/`: SALT and oracle external environment contracts and factories. -- `sandbox/`: isolated execution paths used by special flows. -- `constants.rs`: per-spec limits and gas constants used across modules. - -## KEY PATTERNS -- `no_std` discipline is active for this crate. -- Use `#[cfg(not(feature = "std"))] use alloc as std;` when std collections are required. -- Spec progression is additive for behavior-introducing specs; alias rungs (`MINI_REX_1`, `MINI_REX_2`) re-execute an earlier behavior instead. -- Keep behavior gates explicit via `spec.is_enabled(...)` at call sites. -- Per-frame trackers must stay stack-aligned with EVM frame lifecycle hooks. -- Intercepted synthetic frame results must keep tracker alignment via empty-frame pushes. -- Keep aliases in `lib.rs` aligned with canonical `Mega*` types. - -## WHERE TO LOOK -- Add or modify opcode semantics: `evm/instructions.rs` and `evm/host.rs`. -- Add transaction-level runtime constraints: `limit/limit.rs` and tracker submodules. -- Add block inclusion or accounting rules: `block/limit.rs` and `block/executor.rs`. -- Add/adjust hardfork activation logic: `block/hardfork.rs`. -- Add system contract deployment or interception behavior: `system/*.rs` plus block pre-execution deployment calls. -- Add external dependency plumbing: `external/factory.rs`, `external/gas.rs`, `external/oracle.rs`, `external/salt.rs`. -- Add reusable constants: `constants.rs`. diff --git a/crates/mega-evm/src/access/AGENTS.md b/crates/mega-evm/src/access/AGENTS.md deleted file mode 100644 index aca629b6e..000000000 --- a/crates/mega-evm/src/access/AGENTS.md +++ /dev/null @@ -1,32 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Volatile-data access tracking primitives used to enforce compute-gas detention and Rex4 subtree-level volatile access disable. - -## STRUCTURE -- `mod.rs`: public module exports. -- `tracker.rs`: mutable tracker state, cap merge logic, and depth-scoped disable semantics. -- `volatile.rs`: bitflags and typed conversions for volatile access categories. - -## KEY PATTERNS -- Tracker stores both a bitmap of accessed categories and the most restrictive raw detention cap. -- Cap aggregation is order-independent via min-cap merge. -- Disable scope is depth-based. -- `disable_access(depth)` keeps the shallower depth if already active. -- `enable_access(caller_depth)` only succeeds when caller is at or above activation depth. -- `enable_access_if_returning(current_depth)` prevents disable leakage into sibling frames. -- Reset clears access state and disable depth, but preserves configured cap parameters. - -## ANTI-PATTERNS -- Do not store spec-dependent effective detained limits in this module. -- This module stores raw caps only. -- Do not clear `disable_depth` on every frame return. -- Only clear when returning above the activation depth. -- Do not mutate bitmap bits from unrelated subsystems. -- Access marks should come from host/instruction touch points only. - -## WHERE TO LOOK -- Adjust volatile category mapping bits: `volatile.rs`. -- Change detention cap merge policy: `tracker.rs::apply_or_create_limit`. -- Change disable/enable call-tree semantics: `tracker.rs::{disable_access,enable_access,enable_access_if_returning}`. -- Change beneficiary/oracle detection helpers: `tracker.rs` and host call sites in `../evm/host.rs`. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs deleted file mode 100644 index 6fe86ff36..000000000 --- a/crates/mega-evm/src/access/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! Volatile data access tracking for the `MegaETH` EVM. -//! -//! Volatile data means those data that may be modified by the system (e.g., sequencer, oracle, or -//! payload builder). Once a transaction accesses volatile data, the system will immediate limit -//! the remaining gas in all message calls to a small amount of gas, forcing the transaction to -//! finish execution soon. These restrictions are necessary to prevent `DoS` attacks on EVM. - -mod tracker; -mod volatile; - -pub use tracker::*; -pub use volatile::*; diff --git a/crates/mega-evm/src/access/tracker.rs b/crates/mega-evm/src/access/tracker.rs deleted file mode 100644 index 8ea5e3437..000000000 --- a/crates/mega-evm/src/access/tracker.rs +++ /dev/null @@ -1,305 +0,0 @@ -use crate::{VolatileDataAccess, VolatileDataAccessType, ORACLE_CONTRACT_ADDRESS}; -use alloy_primitives::Address; - -/// A tracker for volatile data access with compute gas limit enforcement. -/// -/// This tracker manages volatile data access detection (block environment, beneficiary, oracle) -/// and tracks the compute gas detention cap to prevent `DoS` attacks. -/// -/// # Compute Gas Limit Enforcement -/// -/// When volatile data is first accessed in a transaction, this tracker records the cap value: -/// - `BLOCK_ENV_ACCESS_COMPUTE_GAS` (20M) for block environment or beneficiary -/// - `ORACLE_ACCESS_COMPUTE_GAS` (configurable: 1M pre-Rex3, 20M Rex3+) for oracle contract -/// -/// The cap value stored here is the **raw** per-access-type cap. How it is applied depends on -/// the spec: -/// - **Pre-REX4**: The cap is an **absolute** compute gas limit for the transaction. -/// - **REX4+**: The cap is **relative** — `ComputeGasTracker::set_detained_limit()` adds current -/// usage to produce the effective limit (`usage_at_access + cap`). -/// -/// If additional volatile data is accessed with a different cap, the **most restrictive** -/// (minimum) raw cap is stored. -/// The caller is responsible for applying this cap to the `AdditionalLimit`. -/// -/// # Key Properties -/// -/// - **Type-Specific Caps**: Block env/beneficiary access → 20M compute gas, Oracle access → -/// configurable (1M pre-Rex3, 20M Rex3+) -/// - **Most Restrictive Wins**: Multiple accesses with different caps → minimum cap applied -/// - **Order Independent**: Oracle→BlockEnv or BlockEnv→Oracle both result in same final cap -/// - **Compute Gas Only**: Only limits compute gas costs, not storage gas cost -/// -/// # Example Flows -/// -/// ## Example 1: Block env then oracle (pre-Rex3, oracle limit = 1M) -/// ```ignore -/// // Transaction starts with compute gas limit of 30M -/// TIMESTAMP opcode: -/// - Marks block_env_accessed -/// - Compute gas limit tracked as 20M -/// -/// CALL(oracle) opcode: -/// - Marks oracle_accessed -/// - Compute gas limit lowered to min(20M, 1M) = 1M -/// -/// // Caller applies 1M compute gas limit to AdditionalLimit -/// ``` -/// -/// ## Example 2: Oracle then block env (pre-Rex3, order independent) -/// ```ignore -/// // Transaction starts with compute gas limit of 30M -/// CALL(oracle) opcode: -/// - Marks oracle_accessed -/// - Compute gas limit tracked as 1M -/// -/// TIMESTAMP opcode: -/// - Marks block_env_accessed -/// - Compute gas limit remains min(1M, 20M) = 1M -/// -/// // Caller applies 1M compute gas limit to AdditionalLimit -/// ``` -/// -/// In Rex3+, the oracle access limit is also 20M, so both limits are equal. -#[derive(Debug, Clone)] -pub struct VolatileDataAccessTracker { - /// Unified bitmap tracking all types of volatile data access. - /// Includes block environment fields, beneficiary balance, and oracle access. - volatile_data_accessed: VolatileDataAccess, - /// The compute gas limit to enforce when volatile data is accessed. - compute_gas_limit: Option, - /// Compute gas limit when accessing block environment data. - block_env_access_limit: u64, - /// Compute gas limit when accessing oracle data. - oracle_access_limit: u64, - - /// The journal depth at which `disableVolatileDataAccess()` was activated (Rex4+). - /// `None` means inactive. `Some(depth)` means calls with - /// `journal.depth() >= depth` are restricted. - disable_depth: Option, -} - -impl VolatileDataAccessTracker { - /// Creates a new tracker with no accesses recorded and configurable limits. - pub fn new(block_env_access_limit: u64, oracle_access_limit: u64) -> Self { - Self { - volatile_data_accessed: VolatileDataAccess::empty(), - compute_gas_limit: None, - block_env_access_limit, - oracle_access_limit, - disable_depth: None, - } - } - - /// Checks if any volatile data has been accessed. - /// If so, the remaining gas in all message calls will be limited to a small amount of gas, - /// forcing the transaction to finish execution soon. - pub fn accessed(&self) -> bool { - !self.volatile_data_accessed.is_empty() - } - - /// Returns the bitmap of volatile data accessed during transaction execution. - /// Returns None if no volatile data has been accessed. - pub fn get_volatile_data_info(&self) -> Option { - self.accessed().then_some(self.volatile_data_accessed) - } - - /// Returns the compute gas limit for the accessed volatile data. - /// Returns None if no volatile data has been accessed. - pub fn get_compute_gas_limit(&self) -> Option { - self.compute_gas_limit - } - - /// Returns the bitmap of block environment data accessed during transaction execution. - pub fn get_block_env_accesses(&self) -> VolatileDataAccess { - self.volatile_data_accessed.block_env_only() - } - - /// Returns the bitmap of all volatile data accessed during transaction execution. - pub fn get_volatile_data_accessed(&self) -> VolatileDataAccess { - self.volatile_data_accessed - } - - /// Marks that a specific type of block environment has been accessed. - pub fn mark_block_env_accessed(&mut self, access_type: VolatileDataAccessType) { - self.volatile_data_accessed.insert(access_type.into()); - self.apply_or_create_limit(self.block_env_access_limit); - } - - /// Checks if beneficiary balance has been accessed. - pub fn has_accessed_beneficiary_balance(&self) -> bool { - self.volatile_data_accessed.has_beneficiary_balance_access() - } - - /// Marks that beneficiary balance has been accessed. - pub fn mark_beneficiary_balance_accessed(&mut self) { - self.volatile_data_accessed.insert(VolatileDataAccess::BENEFICIARY_BALANCE); - self.apply_or_create_limit(self.block_env_access_limit); - } - - /// Checks if the oracle contract has been accessed. - pub fn has_accessed_oracle(&self) -> bool { - self.volatile_data_accessed.has_oracle_access() - } - - /// Checks if the given address is the oracle contract address and marks it as accessed. - /// Applies the oracle access gas limit, which may further restrict gas if a less - /// restrictive limit was already in place. - pub fn check_and_mark_oracle_access(&mut self, address: &Address) -> bool { - if address == &ORACLE_CONTRACT_ADDRESS { - self.volatile_data_accessed.insert(VolatileDataAccess::ORACLE); - self.apply_or_create_limit(self.oracle_access_limit); - true - } else { - false - } - } - - /// Applies a compute gas limit or creates a new one if none exists. - /// If a limit already exists, applies the more restrictive limit (minimum of current and new). - fn apply_or_create_limit(&mut self, limit: u64) { - if let Some(current_limit) = self.compute_gas_limit { - // A limit already exists - apply the more restrictive one - self.compute_gas_limit = Some(current_limit.min(limit)); - } else { - // First volatile data access - set the initial limit - self.compute_gas_limit = Some(limit); - } - } - - /// Activates the volatile data access disable at the given depth. - /// - /// When active, `volatile_access_disabled(depth)` returns `true` for any - /// `depth` greater than or equal to `disable_depth`, causing the caller and - /// inner calls that access volatile data to revert with - /// `VolatileDataAccessDisabled()`. - /// - /// If already active, keeps the shallower (more restrictive) depth. - pub fn disable_access(&mut self, depth: usize) { - match self.disable_depth { - Some(current) if depth >= current => {} - _ => self.disable_depth = Some(depth), - } - } - - /// Checks if volatile data access is disabled at the given journal depth. - /// Returns `true` if `disable_depth` is set and `current_depth >= disable_depth`. - pub fn volatile_access_disabled(&self, current_depth: usize) -> bool { - self.disable_depth.is_some_and(|d| current_depth >= d) - } - - /// Re-enables volatile data access. - /// - /// Succeeds (returns `true`) if access is not disabled, or the caller is at the same - /// depth or shallower than the disabling frame (`caller_depth <= disable_depth`). - /// Fails (returns `false`) if a parent frame disabled access (`caller_depth > disable_depth`). - pub fn enable_access(&mut self, caller_depth: usize) -> bool { - match self.disable_depth { - None => true, - Some(d) if caller_depth <= d => { - self.disable_depth = None; - true - } - Some(_) => false, - } - } - - /// Deactivates the disable if the current depth has dropped below the disable depth. - /// - /// Called on frame return to ensure the disable only applies to the activating frame's - /// subtree and does not leak to sibling calls. - /// When the journal depth drops strictly below the disable depth, the frame that called - /// `disableVolatileDataAccess()` has returned and the restriction is no longer in scope. - pub fn enable_access_if_returning(&mut self, current_depth: usize) { - if self.disable_depth.is_some_and(|d| current_depth < d) { - self.disable_depth = None; - } - } - - /// Resets all access tracking for a new transaction. - /// Preserves the configured limits (only resets access state). - pub fn reset(&mut self) { - self.volatile_data_accessed = VolatileDataAccess::empty(); - self.compute_gas_limit = None; - self.disable_depth = None; - } - - /// Unions a volatile-access bitmap snapshot into this tracker. - /// Footprint only — the parameter type intentionally excludes detention state - /// (`compute_gas_limit`, `disable_depth`), which is frame-local. - pub fn merge_accesses_from_bitmap(&mut self, other_bitmap: VolatileDataAccess) { - self.volatile_data_accessed |= other_bitmap; - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::VolatileDataAccessType; - - #[test] - fn test_merge_accesses_from_bitmap_unions_bitmap_and_preserves_other_state() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - - parent.mark_block_env_accessed(VolatileDataAccessType::Timestamp); - let parent_cap_before = parent.get_compute_gas_limit(); - assert_eq!(parent_cap_before, Some(20_000_000)); - assert!(parent.get_volatile_data_accessed().contains(VolatileDataAccess::TIMESTAMP)); - - let snapshot = VolatileDataAccess::BLOCK_NUMBER | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - - let merged = parent.get_volatile_data_accessed(); - assert!(merged.contains(VolatileDataAccess::TIMESTAMP)); - assert!(merged.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(merged.contains(VolatileDataAccess::ORACLE)); - assert!(!merged.contains(VolatileDataAccess::BENEFICIARY_BALANCE)); - - assert_eq!(parent.get_compute_gas_limit(), parent_cap_before); - assert!(!parent.volatile_access_disabled(0)); - assert!(!parent.volatile_access_disabled(10)); - } - - #[test] - fn test_merge_accesses_from_bitmap_empty_snapshot_is_noop() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - parent.mark_beneficiary_balance_accessed(); - let before_bitmap = parent.get_volatile_data_accessed(); - let before_cap = parent.get_compute_gas_limit(); - - parent.merge_accesses_from_bitmap(VolatileDataAccess::empty()); - - assert_eq!(parent.get_volatile_data_accessed(), before_bitmap); - assert_eq!(parent.get_compute_gas_limit(), before_cap); - } - - #[test] - fn test_merge_accesses_from_bitmap_into_empty_parent_copies_bitmap_only() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - let snapshot = VolatileDataAccess::COINBASE | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - - let merged = parent.get_volatile_data_accessed(); - assert!(merged.contains(VolatileDataAccess::COINBASE)); - assert!(merged.contains(VolatileDataAccess::ORACLE)); - assert_eq!(parent.get_compute_gas_limit(), None); - assert!(!parent.volatile_access_disabled(0)); - assert!(!parent.volatile_access_disabled(3)); - } - - #[test] - fn test_merge_accesses_from_bitmap_is_idempotent() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - let snapshot = VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - let after_first = parent.get_volatile_data_accessed(); - let cap_after_first = parent.get_compute_gas_limit(); - - parent.merge_accesses_from_bitmap(snapshot); - assert_eq!(parent.get_volatile_data_accessed(), after_first); - assert_eq!(parent.get_compute_gas_limit(), cap_after_first); - } -} diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs deleted file mode 100644 index 7d403357f..000000000 --- a/crates/mega-evm/src/access/volatile.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Volatile data access bitflags. - -use bitflags::bitflags; -use serde::{Deserialize, Serialize}; - -bitflags! { - /// Unified bitmap for tracking all types of volatile data access. - /// - /// This combines both fine-grained block environment tracking and coarse-grained - /// tracking of beneficiary balance and oracle contract access. - /// - /// Bits 0-9: Specific block environment fields (10 bits) - /// Bit 10: Beneficiary balance access - /// Bit 11: Oracle contract access - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] - pub struct VolatileDataAccess: u16 { - // Block environment fields (bits 0-9) - /// Block number (NUMBER opcode) - const BLOCK_NUMBER = 1 << 0; - /// Block timestamp (TIMESTAMP opcode) - const TIMESTAMP = 1 << 1; - /// Block coinbase/beneficiary (COINBASE opcode) - const COINBASE = 1 << 2; - /// Block difficulty (DIFFICULTY opcode) - const DIFFICULTY = 1 << 3; - /// Block gas limit (GASLIMIT opcode) - const GAS_LIMIT = 1 << 4; - /// Base fee per gas (BASEFEE opcode) - const BASE_FEE = 1 << 5; - /// Previous block randomness (PREVRANDAO opcode) - const PREV_RANDAO = 1 << 6; - /// Block hash lookup (BLOCKHASH opcode) - const BLOCK_HASH = 1 << 7; - /// Blob base fee per gas (BLOBBASEFEE opcode) - const BLOB_BASE_FEE = 1 << 8; - /// Blob hash lookup (BLOBHASH opcode) - const BLOB_HASH = 1 << 9; - - // Other volatile data types (bits 10-11) - /// Beneficiary balance was accessed - const BENEFICIARY_BALANCE = 1 << 10; - /// Oracle contract was accessed - const ORACLE = 1 << 11; - } -} - -impl VolatileDataAccess { - /// Mask for all block environment access flags (bits 0-9). - const BLOCK_ENV_MASK: u16 = 0b0000_0011_1111_1111; - - /// Checks if any block environment data has been accessed. - pub fn has_block_env_access(self) -> bool { - (self.bits() & Self::BLOCK_ENV_MASK) != 0 - } - - /// Checks if beneficiary balance has been accessed. - pub fn has_beneficiary_balance_access(self) -> bool { - self.contains(Self::BENEFICIARY_BALANCE) - } - - /// Checks if oracle contract has been accessed. - pub fn has_oracle_access(self) -> bool { - self.contains(Self::ORACLE) - } - - /// Counts the number of distinct block environment fields accessed. - pub fn count_block_env_accessed(self) -> usize { - (self.bits() & Self::BLOCK_ENV_MASK).count_ones() as usize - } - - /// Counts the number of distinct block environment fields accessed. - /// This is an alias for `count_block_env_accessed` for backward compatibility. - pub fn count_accessed(self) -> usize { - self.count_block_env_accessed() - } - - /// Gets the raw bitmap value. - pub const fn raw(self) -> u16 { - self.bits() - } - - /// Converts a single-bit flag to its bit position as a `u8`. - /// This matches the `VolatileDataAccessType` Solidity enum discriminant. - /// - /// # Panics - /// - /// Panics if `self` is empty (no bits set). - pub fn as_u8(self) -> u8 { - debug_assert!(!self.is_empty(), "cannot convert empty VolatileDataAccess to u8"); - self.bits().trailing_zeros() as u8 - } - - /// Returns only the block environment access portion as a separate bitflag. - /// This is useful for compatibility with code that expects only block env flags. - pub fn block_env_only(self) -> Self { - Self::from_bits_truncate(self.bits() & Self::BLOCK_ENV_MASK) - } -} - -impl From for VolatileDataAccess { - fn from(ty: crate::VolatileDataAccessType) -> Self { - Self::from_bits_truncate(1 << (ty as u8)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::VolatileDataAccessType; - - #[test] - fn test_empty_access_has_no_flags() { - let access = VolatileDataAccess::empty(); - - assert!(!access.has_block_env_access()); - assert!(!access.has_beneficiary_balance_access()); - assert!(!access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 0); - assert_eq!(access.count_accessed(), 0); - assert_eq!(access.block_env_only(), VolatileDataAccess::empty()); - assert_eq!(access.raw(), 0); - } - - #[test] - fn test_block_env_helpers_ignore_non_block_flags() { - let access = VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::BLOB_HASH | - VolatileDataAccess::BENEFICIARY_BALANCE | - VolatileDataAccess::ORACLE; - - assert!(access.has_block_env_access()); - assert!(access.has_beneficiary_balance_access()); - assert!(access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 2); - assert_eq!(access.count_accessed(), 2); - assert_eq!( - access.block_env_only(), - VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH - ); - assert_eq!(access.raw(), access.bits()); - } - - #[test] - fn test_from_volatile_data_access_type_covers_all_variants() { - let expected: &[(VolatileDataAccessType, VolatileDataAccess)] = &[ - (VolatileDataAccessType::BlockNumber, VolatileDataAccess::BLOCK_NUMBER), - (VolatileDataAccessType::Timestamp, VolatileDataAccess::TIMESTAMP), - (VolatileDataAccessType::Coinbase, VolatileDataAccess::COINBASE), - (VolatileDataAccessType::Difficulty, VolatileDataAccess::DIFFICULTY), - (VolatileDataAccessType::GasLimit, VolatileDataAccess::GAS_LIMIT), - (VolatileDataAccessType::BaseFee, VolatileDataAccess::BASE_FEE), - (VolatileDataAccessType::PrevRandao, VolatileDataAccess::PREV_RANDAO), - (VolatileDataAccessType::BlockHash, VolatileDataAccess::BLOCK_HASH), - (VolatileDataAccessType::BlobBaseFee, VolatileDataAccess::BLOB_BASE_FEE), - (VolatileDataAccessType::BlobHash, VolatileDataAccess::BLOB_HASH), - (VolatileDataAccessType::Beneficiary, VolatileDataAccess::BENEFICIARY_BALANCE), - (VolatileDataAccessType::Oracle, VolatileDataAccess::ORACLE), - ]; - - for &(access_type, expected_flag) in expected { - let converted = VolatileDataAccess::from(access_type); - assert_eq!(converted, expected_flag); - assert_eq!(converted.as_u8(), expected_flag.as_u8()); - } - } - - #[test] - fn test_all_block_env_flags_counted_correctly() { - let all_block_env = VolatileDataAccess::BLOCK_NUMBER | - VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::COINBASE | - VolatileDataAccess::DIFFICULTY | - VolatileDataAccess::GAS_LIMIT | - VolatileDataAccess::BASE_FEE | - VolatileDataAccess::PREV_RANDAO | - VolatileDataAccess::BLOCK_HASH | - VolatileDataAccess::BLOB_BASE_FEE | - VolatileDataAccess::BLOB_HASH; - - assert_eq!(all_block_env.count_block_env_accessed(), 10); - assert!(all_block_env.has_block_env_access()); - assert!(!all_block_env.has_beneficiary_balance_access()); - assert!(!all_block_env.has_oracle_access()); - assert_eq!(all_block_env.block_env_only(), all_block_env); - } -} diff --git a/crates/mega-evm/src/block/AGENTS.md b/crates/mega-evm/src/block/AGENTS.md deleted file mode 100644 index 090883e3c..000000000 --- a/crates/mega-evm/src/block/AGENTS.md +++ /dev/null @@ -1,70 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Block execution orchestration for MegaETH, including hardfork-to-spec resolution, system pre/post calls, and block-level resource admission. - -## STRUCTURE -- `executor.rs`: `MegaBlockExecutor` lifecycle, pre/post execution changes, tx commit policy. -- `factory.rs`: executor factory wiring from hardfork config and EVM factory. -- `hardfork.rs`: `MegaHardfork` definitions, activation checks, spec mapping. -- `chain.rs`: canonical chain IDs and per-chain hardfork activation schedules (mainnet, testnet, all-activated fallback for unknown chains). -- `limit.rs`: `BlockLimits` config and `BlockLimiter` pre/post checks. -- `eips.rs`: EIP system calls (blockhashes, beacon root, balance increments). -- `helpers.rs`: utility helpers for block execution. -- `result.rs`: block execution result types. - -## KEY PATTERNS -- Pre-execution and post-execution limits are intentionally separated. -- Pre-checks reject/skip before execution. -- Post-checks can drop outcomes before commit. -- System contract deployments are idempotent state patches, position-gated on the resolved spec. -- Executor constructor asserts hardfork/spec coherence for non-test builds. -- Block limiter state is cumulative and must be updated only on committed outcomes. -- `pre_execution_changes` collects `Option` outcomes from each helper into a vector; `commit_system_call_outcomes` walks them and calls `system_caller.on_state(source, &state)` **before** `db.commit(state)` for every entry. The `on_state` hook feeds the stateless witness generator with the complete read/write set. Helpers must therefore return all accounts and slots they touched (including reads). See `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT` for the helper-side contract. - -## INVARIANT MAP -The structural invariants of the spec ladder and fork schedule, indexed by where each is enforced and when it fires. -Guards live next to the tables they guard; this map is the index, not the home. - -Compile time (const assertions and exhaustive matches; a violation fails `cargo build`): -- `MegaSpecId::ALL` lists every spec in ladder order without gaps: `is_ladder_prefix` assertion in `evm/spec.rs`. -- The `behavior()` projection is flat — no alias chains or cycles, no upward targets: `is_flat_projection` assertion in `evm/spec.rs`. -- The fork→spec map is strictly ascending and therefore 1:1: `climbs_the_spec_ladder` assertion in `hardfork.rs`. -- Every new spec must be placed everywhere it matters: exhaustive matches in `ladder_index` (`evm/spec.rs`), the instruction table (`evm/instructions.rs`), precompiles (`evm/precompiles.rs`), and runtime limits (`evm/limit.rs`) fail compilation until the variant is wired; its fork is forced the same way by the matches on the fork enum in `MegaHardfork::spec_id` (`hardfork.rs`) and block limits (`limit.rs`). - -Chain-config load time: -- A published schedule climbs the ladder in activation order with required params attached: `MegaHardforks::validate_schedule` (`hardfork.rs`); `hardfork_schedule` (`chain.rs`) debug-asserts it, and node startup should call it. -- Per-fork params invariants hold: `HardforkParams::validate` runs inside `with_params` and panics at load time, not at the fork's first block. - -Block execution time: -- The cfg spec equals the schedule's resolution: executor constructor assert (compiled out under `test`/`test-utils`; pre-block setup reads the same cfg spec as `resolve_system_address`, so a tool overriding the cfg spec gets a coherent what-if rather than a hybrid block). -- A scheduled fork whose params are missing fails closed at its first block: registry checks in `executor.rs` and `system/sequencer_registry.rs`. - -Test time (`cargo test`): -- Alias dispatch grouping agrees with `behavior()`: reconciliation tests in `evm/instructions.rs`, `evm/precompiles.rs`, `evm/limit.rs`, and `limit.rs`. -- The resolved spec equals the maximum over activated forks on every schedule shape: `test_resolved_spec_is_the_maximum_over_activated_forks` (`hardfork.rs`). -- Position projections coincide with raw activation events: parity tests on every canonical schedule (`hardfork.rs`) and on a fully staged synthetic ladder (`tests/mutation/block.rs`). -- The const checkers themselves reject malformed inputs (the real tables can never exercise the negative path): `test_is_ladder_prefix_rejects_malformed_lists`, `test_is_flat_projection_rejects_malformed_tables`, `test_climbs_the_spec_ladder_rejects_malformed_lists`. -- Golden tables pin what derivation cannot: spec names and discriminant positions (`ALL_SPECS` in `evm/spec.rs`), the exact fork→spec pairs (`hardfork.rs`), and the pairing of load-time and pre-block params rules (`tests/block_executor/partial_ladder.rs`). - -CI: -- Spec-gate mutation testing probes boundary shifts and dispatch misroutes: `mutants/operators/spec-gate/` (behavior-introducing specs only; alias rungs are not on the behavior axis). - -## ANTI-PATTERNS -- Do not apply post-execution limit counters before a tx outcome is commit-eligible. -- Do not bypass `pre_execution_changes` in replay or simulation paths that aim for chain equivalence. -- Do not infer spec from tx fields. -- Gate on the one resolved spec through the right projection: `spec.is_enabled(MegaSpecId::X)` compares BEHAVIOR (both sides project through `behavior()`, so alias windows roll semantics back), `spec.reaches(MegaSpecId::X)` compares POSITION (one-way setup; alias windows do not retract it). The `is__active_at_timestamp` predicates are position projections for behavior-introducing forks and raw event queries for alias forks (`is_mini_rex_1/2_active_at_timestamp`), whose occurrence is not recoverable from the ladder; `mega_fork_activation` answers raw scheduling for any fork. -- A published chain schedule must pass `MegaHardforks::validate_schedule` (rung gaps, activation ordering, required per-fork params). The execution layer stays tolerant of malformed schedules — position-compared setup stays additive — but that tolerance is the fail-safe, not permission to publish one; `hardfork_schedule` debug-asserts it and node startup should check it. A new `HardforkParams` type must be registered in `validate_schedule`. -- One spec, two projections. `spec_id` is monotone (forks map 1:1 onto an ascending ladder; rollbacks are alias rungs like `MINI_REX_1`). Behavior (`is_enabled`) gates execution semantics: EVM behavior, block limits, transaction classification — it rolls back inside an alias window. Position (`reaches`) gates one-way chain setup: system-contract predeploys, pre-block rules, expected installed bytecode versions — retracting it during a rollback window would drop the Oracle predeploys' read-only witness entries that the on-state hook feeds to stateless proofs and the state-sync transition shard. -- Do not express "a chain running spec N" as `with_all_activated().without(fork)`. Removing a middle rung leaves later forks active, so the resolved spec stays at the top of the ladder. Use `with_all_activated_through(MegaSpecId::N)`. -- Do not hardcode gas-limit assumptions outside `BlockLimits` plumbing. -- Do not commit outcomes without first firing `on_state`. The two-step `on_state` → `commit` ordering is the witness-recorder contract; swapping or skipping it corrupts stateless proofs. - -## WHERE TO LOOK -- Add a new hardfork activation condition: `hardfork.rs` and `MegaHardforkConfig` wiring. -- Change when a fork activates on mainnet/testnet (or the unknown-chain fallback): `chain.rs`. -- Change tx inclusion behavior under block pressure: `limit.rs` and `executor.rs::run_transaction`/commit methods. -- Add pre-block or post-block system call: `eips.rs` and `executor.rs::{pre_execution_changes,post_execution_changes}`. -- Change block-level default limits for a hardfork: `limit.rs::from_hardfork_and_block_gas_limit`. -- Surface new block execution metadata: `result.rs`. diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs deleted file mode 100644 index 885542a6f..000000000 --- a/crates/mega-evm/src/block/chain.rs +++ /dev/null @@ -1,256 +0,0 @@ -//! Canonical per-chain `MegaETH` hardfork schedules. -//! -//! This is the single source of truth for when each [`MegaHardfork`] activates on -//! the known `MegaETH` chains. Tools that need a real chain schedule (the -//! `mega-evme` replay command, Foundry-based tooling, integration tests) should -//! use [`hardfork_schedule`] rather than re-declaring timestamps locally. -//! -//! Per-fork parameters that are chain-specific data — the -//! [`SequencerRegistryConfig`] seeded at Rex5 activation and the -//! [`SequencerRegistryRex6Config`] seeded at Rex6 activation — are attached here too. - -use alloy_hardforks::ForkCondition; -use alloy_primitives::address; - -use crate::{ - MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaSpecId, SequencerRegistryConfig, - SequencerRegistryRex6Config, MEGA_SYSTEM_ADDRESS, -}; - -/// `MegaETH` mainnet chain ID. -pub const MAINNET_CHAIN_ID: u64 = 4326; - -/// `MegaETH` testnet v2 chain ID. -pub const TESTNET_CHAIN_ID: u64 = 6343; - -/// Governance parameter seeded into the v2.0.0 `SequencerRegistry` at Rex6 init on both -/// live networks: the minimum scheduling-to-activation delay (`_minRotationDelay`), in -/// blocks. Must equal the `rex6MinRotationDelay` the operator genesis attaches; the live -/// value is readable via `minRotationDelay()` on `0x6342…0006`. One constant for both -/// schedules, so a network diverging from the other is a deliberate edit rather than a -/// silent difference. -const REX6_MIN_ROTATION_DELAY: u64 = 21_600; - -/// Canonical hardfork schedule for `MegaETH` mainnet (chain `4326`). -pub fn mainnet_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(1764845637)) - .with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(1764849932)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(1764851940)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(1766282400)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(1770246000)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(1771639200)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(1776659200)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(1780632000)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1787626800)) - // Seeded values read from the on-chain SequencerRegistry (0x6342…0006) at - // Rex5 init: INITIAL_SEQUENCER (slot 5) and the admin (slot 2). At replay - // time these only satisfy the activation guard — the live system address - // is read from forked registry storage. - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: address!("0x7a49197dd1ebb8d38c67e4eb7626af6ade432445"), - rex5_initial_admin: address!("0x92e0e0b15e3e99b32c9ed9ad284f939553c7b7d6"), - }) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: REX6_MIN_ROTATION_DELAY, - }) -} - -/// Canonical hardfork schedule for `MegaETH` testnet v2 (chain `6343`). -pub fn testnet_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::MiniRex1, ForkCondition::Never) - .with(MegaHardfork::MiniRex2, ForkCondition::Never) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(1764694618)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(1766147599)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(1770116400)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(1771380000)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(1776400000)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(1780459200)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1786330800)) - // Seeded values read from the on-chain SequencerRegistry (0x6342…0006) at - // Rex5 init on testnet: INITIAL_SEQUENCER (slot 5) and the admin (slot 2). - // At replay time these only satisfy the activation guard — the live system - // address is read from forked registry storage. - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: address!("0xB8DB54eBA7Ae650d14F362de461516a4FF1551FC"), - rex5_initial_admin: address!("0x1d9BD232C44B39341e670B735c7F423c40426b34"), - }) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: REX6_MIN_ROTATION_DELAY, - }) -} - -/// All `MegaETH` hardforks activated at genesis. -/// -/// Used for unknown chains and local/standalone execution where the chain has no -/// published schedule. Rex5 requires a [`SequencerRegistryConfig`] (block -/// execution fails pre-block without one), and an unknown chain has no published -/// roles, so both roles are seeded with [`MEGA_SYSTEM_ADDRESS`] as a -/// placeholder. The placeholder only matters when bootstrapping a fresh -/// registry: on a chain whose registry is already deployed, the live roles are -/// read from the registry's storage. -/// -/// Rex6 (active at genesis here too) likewise requires a -/// [`SequencerRegistryRex6Config`] for the v2.0.0 registry deploy. The fallback -/// seeds the smallest valid rotation delay (1 block) so local and dev chains can -/// exercise rotations without friction; a real network must attach a -/// governance-approved value in its published schedule when it schedules Rex6. -/// -/// The rung is named explicitly rather than inherited from [`MegaSpecId::default`]. -/// These chains run at genesis, so the rung *is* their semantics from block zero, -/// with no fork boundary to separate an old rule from a new one. Introducing a spec -/// must therefore not move them: a devnet that produced history under this fallback -/// would otherwise replay differently — through [`hardfork_schedule`], which is what -/// `mega-evme replay` resolves an unknown chain ID with — against the same binary -/// that produced it. Advancing this rung is a deliberate edit; it currently names -/// `REX7`, the unstable development head, which carries no behavior of its own yet, -/// so dev chains track the newest semantics at no cost. -pub fn all_activated_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with_all_activated_through(MegaSpecId::REX7) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: MEGA_SYSTEM_ADDRESS, - }) - .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }) -} - -/// Returns the canonical hardfork schedule for a chain ID. -/// -/// Mainnet (`4326`) and testnet v2 (`6343`) use their published schedules; any -/// other chain gets [`all_activated_hardforks`]. -pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { - let schedule = match chain_id { - MAINNET_CHAIN_ID => mainnet_hardforks(), - TESTNET_CHAIN_ID => testnet_hardforks(), - _ => all_activated_hardforks(), - }; - // The canonical schedules are edited by hand; a malformed edit must fail at the first - // resolution, not at the first block that happens to expose it. - debug_assert_eq!(schedule.validate_schedule(), Ok(())); - schedule -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{MegaHardfork, MegaHardforks, MegaSpecId}; - - #[test] - fn test_mainnet_schedule_resolves_specs_by_timestamp() { - let hf = mainnet_hardforks(); - assert_eq!(hf.spec_id(1764851940), MegaSpecId::REX); - assert_eq!(hf.spec_id(1776659200), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780631999), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780632000), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1787626799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1787626800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } - - #[test] - fn test_testnet_schedule_resolves_specs_by_timestamp() { - let hf = testnet_hardforks(); - assert_eq!(hf.spec_id(1776400000), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780459199), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780459200), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1786330799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1786330800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } - - #[test] - fn test_schedule_dispatch_by_chain_id() { - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1780632000), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1780459200), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1787626800), MegaSpecId::REX6); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1786330800), MegaSpecId::REX6); - // Unknown chain: every fork up to the pinned rung, active at genesis. - assert_eq!(hardfork_schedule(1).spec_id(0), MegaSpecId::REX7); - } - - #[test] - fn test_canonical_schedules_activate_rex6_and_pin_rex7_never() { - // Rex6 is scheduled on both networks at the published timestamps (testnet - // 2026-08-10, mainnet 2026-08-25) and carries the governance-seeded rotation - // delay. Rex7 is still unstable and must not appear in a canonical schedule - // until governance publishes a timestamp: an accidental entry here would - // fork the live chains at that timestamp. - for (hf, rex6_activation) in - [(mainnet_hardforks(), 1787626800), (testnet_hardforks(), 1786330800)] - { - assert_eq!( - hf.mega_fork_activation(MegaHardfork::Rex6), - ForkCondition::Timestamp(rex6_activation) - ); - assert_eq!(hf.mega_fork_activation(MegaHardfork::Rex7), ForkCondition::Never); - // Rex6 is therefore the terminal spec on both chains, at any later timestamp. - assert_eq!(hf.spec_id(u64::MAX), MegaSpecId::REX6); - let params = hf - .fork_params::() - .expect("canonical schedules must carry a SequencerRegistryRex6Config"); - assert_eq!(params.rex6_min_rotation_delay, 21600); - } - } - - #[test] - fn test_unknown_chain_fallback_carries_sequencer_registry_config() { - // Rex5 block execution fails pre-block without a SequencerRegistryConfig, - // so the all-activated fallback must attach placeholder roles. - let hf = hardfork_schedule(999_999); - assert_eq!(hf.spec_id(0), MegaSpecId::REX7); - let params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryConfig"); - assert_eq!(params.rex5_initial_sequencer, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.rex5_initial_admin, MEGA_SYSTEM_ADDRESS); - // Rex6 is also active at genesis in the fallback, and the v2.0.0 registry - // deploy fails pre-block without a SequencerRegistryRex6Config — without - // this, every unknown-chain block aborts before the registry can deploy. - let rex6_params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryRex6Config"); - assert!(rex6_params.rex6_min_rotation_delay > 0); - } - - /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. - /// - /// Unknown chains run their rung from genesis, so it is their semantics from block zero with - /// no fork boundary. Introducing a spec must therefore leave them alone: registering a fork - /// above the pinned rung would rewrite what history they have already produced means, and - /// `mega-evme replay` resolves an unknown chain ID through this same schedule. - /// - /// A newly introduced spec leaves this test green — the pin holding still is the safe - /// direction, so nothing fails to force a decision. What the test pins is drift: the - /// fallback silently following `MegaSpecId::default` again (it fails here once the default - /// advances past the rung), and the rung advancing without this `RUNG` constant being edited - /// in the same change. - #[test] - fn test_unknown_chain_fallback_pins_its_rung() { - let hf = all_activated_hardforks(); - const RUNG: MegaSpecId = MegaSpecId::REX7; - - assert_eq!(hf.spec_id(0), RUNG, "the rung applies from genesis"); - assert_eq!(hf.spec_id(u64::MAX), RUNG, "and is terminal — no later fork is registered"); - - for fork in MegaHardfork::VARIANTS { - let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; - assert_eq!( - registered, - RUNG.is_enabled(fork.spec_id()), - "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" - ); - } - } -} diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs deleted file mode 100644 index 13056deb6..000000000 --- a/crates/mega-evm/src/block/eips.rs +++ /dev/null @@ -1,272 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, string::ToString}; - -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - Evm, -}; -use alloy_primitives::{Address, B256, U256}; -use revm::{ - context_interface::result::ResultAndState, - database::State, - state::{Account, EvmState}, - Database, Inspector, -}; - -use crate::{ - block::hardfork::MegaHardforks, ExternalEnvTypes, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, -}; - -/// Applies the pre-block call to the [EIP-2935] blockhashes contract, using the given block, -/// chain specification, and EVM. -/// -/// If Prague is not activated, or the block is the genesis block, then this is a no-op, and no -/// state changes are made. -/// -/// Note: this does not commit the state changes to the database, it only transact the call. -/// -/// Returns `None` if Prague is not active or the block is the genesis block, otherwise returns the -/// result of the call. -/// -/// Rex5+: the system call is issued with `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` -/// (matching `SequencerRegistry` pre-block helpers) instead of revm's upstream-fixed 30M -/// default. The EIP-2935 history-storage write cost depends on Rex5 dynamic storage gas, so -/// the 30M default is no longer guaranteed to be enough on high-SALT-bucket blocks. -/// Pre-Rex5 keeps the original `transact_system_call` (30M) path for replay parity. -/// -/// [EIP-2935]: https://eips.ethereum.org/EIPS/eip-2935 -#[inline] -pub(crate) fn transact_blockhashes_contract_call( - hardforks: H, - setup_spec: MegaSpecId, - parent_block_hash: B256, - evm: &mut MegaEvm, -) -> Result>, BlockExecutionError> -where - H: MegaHardforks, - DB: alloy_evm::Database, - ExtEnvs: ExternalEnvTypes, - INSP: Inspector>, -{ - let block_timestamp: u64 = evm.block().timestamp.saturating_to(); - if !hardforks.is_prague_active_at_timestamp(block_timestamp) { - return Ok(None); - } - - // if the block number is zero (genesis block) then no system transaction may occur as per - // EIP-2935 - if evm.block().number.is_zero() { - return Ok(None); - } - - let res = if setup_spec.reaches(MegaSpecId::REX5) { - let gas_limit = - evm.block().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - parent_block_hash.0.into(), - gas_limit, - ) - } else { - evm.transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - parent_block_hash.0.into(), - ) - }; - - match res { - Ok(res) => Ok(Some(res)), - Err(e) => { - Err(BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) - } - } -} - -/// Applies the pre-block call to the [EIP-4788] beacon block root contract, using the given block, -/// chain spec, EVM. -/// -/// Note: this does not commit the state changes to the database, it only transact the call. -/// -/// Returns `None` if Cancun is not active or the block is the genesis block, otherwise returns the -/// result of the call. -/// -/// Rex5+: see [`transact_blockhashes_contract_call`] for the gas-limit override rationale — -/// the beacon-root SSTORE shares the same dynamic-storage-gas exposure. -/// -/// [EIP-4788]: https://eips.ethereum.org/EIPS/eip-4788 -#[inline] -pub(crate) fn transact_beacon_root_contract_call( - hardforks: H, - setup_spec: MegaSpecId, - parent_beacon_block_root: Option, - evm: &mut MegaEvm, -) -> Result>, BlockExecutionError> -where - H: MegaHardforks, - DB: alloy_evm::Database, - ExtEnvs: ExternalEnvTypes, - INSP: Inspector>, -{ - let block_timestamp: u64 = evm.block().timestamp.saturating_to(); - if !hardforks.is_cancun_active_at_timestamp(block_timestamp) { - return Ok(None); - } - - let parent_beacon_block_root = - parent_beacon_block_root.ok_or(BlockValidationError::MissingParentBeaconBlockRoot)?; - - // if the block number is zero (genesis block) then the parent beacon block root must - // be 0x0 and no system transaction may occur as per EIP-4788 - if evm.block().number.is_zero() { - if !parent_beacon_block_root.is_zero() { - return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { - parent_beacon_block_root, - } - .into()); - } - return Ok(None); - } - - let res = if setup_spec.reaches(MegaSpecId::REX5) { - let gas_limit = - evm.block().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - gas_limit, - ) - } else { - evm.transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - ) - }; - - match res { - Ok(res) => Ok(Some(res)), - Err(e) => Err(BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: e.to_string(), - } - .into()), - } -} - -/// Transacts the balance increments and returns the post evm state. Note that the changes are not -/// committed to the given db. -pub(crate) fn transact_balance_increments( - balances: impl IntoIterator, - db: &mut State, -) -> Result, DB::Error> { - let balances = balances.into_iter(); - let mut state = EvmState::default(); - - for (address, balance_increment) in balances { - if balance_increment == 0 { - continue; - } - let cache_account = db.load_cache_account(address)?; - let account_info = cache_account.account_info().unwrap_or_default(); - let mut account = Account::default().with_info(account_info); - account.info.balance += U256::from(balance_increment); - account.mark_touch(); - state.insert(address, account); - } - - Ok(Some(state)) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; - - #[test] - fn test_balance_increment_commit_equivalence() { - // This is the most important test: verify that our approach is equivalent - // to the original increment_balances + balance_increment_state approach - - // Setup: create two identical database states - let addr1 = address!("0x1000000000000000000000000000000000000001"); - let addr2 = address!("0x2000000000000000000000000000000000000002"); - let addr3 = address!("0x3000000000000000000000000000000000000003"); - - // Fund only addr1 and addr2, but leave addr3 empty (non-existent) - let setup_db = |db: &mut InMemoryDB| { - for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { - db.insert_account_info( - addr, - AccountInfo { - balance: U256::from(balance), - nonce, - code_hash: alloy_primitives::B256::ZERO, - code: None, - }, - ); - } - }; - - // Setup database 1: will use original approach (increment_balances) - let mut db1 = InMemoryDB::default(); - setup_db(&mut db1); - let mut state1 = State::builder().with_database(&mut db1).build(); - - // Setup database 2: will use our approach (transact_balance_increments + commit) - let mut db2 = InMemoryDB::default(); - setup_db(&mut db2); - let mut state2 = State::builder().with_database(&mut db2).build(); - - // Apply balance increments - let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; - - // Method 1: Original approach - state1 - .increment_balances(balance_increments.clone()) - .expect("increment_balances should succeed"); - - // Method 2: Refactored approach (transact + commit, matching the actual usage pattern) - // The refactoring separates increment_balances into two steps: - // 1. transact_balance_increments() - produces EvmState delta - // 2. commit() - integrates the delta and fixes status transitions - // This allows extracting the intermediate state for system_caller.on_state() hooks - let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) - .expect("transact_balance_increments should succeed") - .expect("Should return state"); - - // Commit the state changes (this applies proper status transitions via apply_evm_state) - state2.commit(result_state); - - // Verify final states match after both approaches - for (addr, _expected_increment) in balance_increments { - let account1 = state1.load_cache_account(addr).expect("Should load from state1"); - let account2 = state2.load_cache_account(addr).expect("Should load from state2"); - - let info1 = account1.account_info().expect("Should have account info"); - let info2 = account2.account_info().expect("Should have account info"); - - assert_eq!( - info1.balance, info2.balance, - "Balance for {:?} should be identical after both methods", - addr - ); - assert_eq!(info1.nonce, info2.nonce, "Nonce for {:?} should be identical", addr); - assert_eq!( - info1.code_hash, info2.code_hash, - "Code hash for {:?} should be identical", - addr - ); - assert_eq!( - account1.status, account2.status, - "Account status for {:?} should be identical after both methods", - addr - ); - } - } -} diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs deleted file mode 100644 index c4ddfea54..000000000 --- a/crates/mega-evm/src/block/executor.rs +++ /dev/null @@ -1,751 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, collections::BTreeMap, vec::Vec}; - -use alloy_consensus::{Eip658Value, Header, Transaction, TxReceipt}; -use alloy_eips::{Encodable2718, Typed2718}; -pub use alloy_evm::block::CommitChanges; -use alloy_evm::{ - block::{ - state_changes::post_block_balance_increments, BlockExecutionError, BlockExecutionResult, - BlockValidationError, ExecutableTx, OnStateHook, StateChangePostBlockSource, - StateChangePreBlockSource, StateChangeSource, SystemCaller, - }, - eth::receipt_builder::ReceiptBuilderCtx, - Database, Evm as _, FromRecoveredTx, FromTxWithEncoded, IntoTxEnv, RecoveredTx, -}; -use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; -use alloy_primitives::B256; -use op_alloy_consensus::OpDepositReceipt; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; -use revm::{ - context::result::{ExecResultAndState, ExecutionResult}, - database::State, - handler::EvmTr, - DatabaseCommit, Inspector, -}; - -use crate::{ - block::eips, flat_system_contract_specs_for, is_apply_pending_changes_due, - resolve_system_address, transact_apply_pending_changes, transact_deploy, - transact_deploy_sequencer_registry_for, BlockLimiter, BlockMegaTransactionOutcome, BucketId, - MegaBlockExecutionCtx, MegaHardforks, MegaSpecId, MegaSystemCallOutcome, MegaTransaction, - MegaTransactionExt, MegaTransactionOutcome, SequencerRegistryConfig, - SequencerRegistryRex6Config, -}; - -/// Block executor for the `MegaETH` chain. -/// -/// A block executor that processes transactions within a block using `MegaETH`-specific -/// EVM specifications and optimizations. This executor wraps the Optimism block executor -/// and provides access to `MegaETH` features such as enhanced security measures, increased -/// contract size limits, and block environment access tracking for parallel execution. -/// -/// # Generic Parameters -/// -/// - `H`: The hardfork configuration implementing `MegaHardforks` -/// - `E`: The EVM type implementing `alloy_evm::Evm` -/// - `R`: The receipt builder implementing `OpReceiptBuilder` -/// -/// # Implementation Strategy -/// -/// This executor uses the delegation pattern to efficiently wrap the underlying Optimism -/// block executor (`OpBlockExecutor`) while providing MegaETH-specific customizations. -/// The delegation ensures minimal overhead while maintaining full compatibility with -/// the Optimism EVM infrastructure. -pub struct MegaBlockExecutor { - hardforks: H, - receipt_builder: R, - ctx: MegaBlockExecutionCtx, - system_caller: SystemCaller, - /// The inner evm instance. - pub evm: E, - /// The block limiter for tracking the limit usage. - pub block_limiter: BlockLimiter, - /// The receipts for the transactions in the block. - pub receipts: Vec, -} - -impl core::fmt::Debug for MegaBlockExecutor { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethBlockExecutor").finish_non_exhaustive() - } -} - -impl<'db, DB, H, R, INSP, ExtEnvs> - MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - H: MegaHardforks + Clone, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder, -{ - /// Create a new block executor. - /// - /// # Parameters - /// - /// - `evm`: The EVM instance to use for transaction execution - /// - `ctx`: The block execution context for tracking access patterns - /// - `hardforks`: The hardforks configuration implementing [`MegaHardforks`] - /// - `receipt_builder`: The receipt builder for processing transaction receipts - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn new( - evm: crate::MegaEvm<&'db mut State, INSP, ExtEnvs>, - ctx: MegaBlockExecutionCtx, - hardforks: H, - receipt_builder: R, - ) -> Self { - // Sanity check: spec id must match hardfork - let block_timestamp = evm.block().timestamp.saturating_to(); - #[cfg(not(any(test, feature = "test-utils")))] - { - use crate::HostExt; - let spec_id = evm.spec_id(); - let expected_spec_id = hardforks.spec_id(block_timestamp); - assert_eq!( - spec_id, expected_spec_id, - "The spec id {} in cfg env must match the expected spec id {} for timestamp {}", - spec_id, expected_spec_id, block_timestamp - ); - } - assert!( - hardforks.is_regolith_active_at_timestamp(block_timestamp), - "mega-evm assumes Regolith hardfork is always active" - ); - assert!( - hardforks.is_canyon_active_at_timestamp(block_timestamp), - "mega-evm assumes Canyon hardfork is always active" - ); - assert!( - hardforks.is_isthmus_active_at_timestamp(block_timestamp), - "mega-evm assumes Isthmus hardfork is always active" - ); - - #[cfg(not(any(test, feature = "test-utils")))] - assert!( - ctx.block_limits.block_gas_limit == evm.block().gas_limit, - "block gas limit must be set to the block env gas limit" - ); - - Self { - hardforks: hardforks.clone(), - receipt_builder, - receipts: Vec::new(), - block_limiter: ctx.block_limits.to_block_limiter(), - ctx, - evm, - system_caller: SystemCaller::new(hardforks), - } - } - - /// Gets a mutable reference to the inspector in the `MegaEVM`. - pub fn inspector_mut(&mut self) -> &mut INSP { - self.evm.inspector_mut() - } - - /// Gets a reference to the inspector in the `MegaEVM`. - pub fn inspector(&self) -> &INSP { - self.evm.inspector() - } -} - -impl<'db, DB, C, R, INSP, ExtEnvs> - MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - C: MegaHardforks, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder< - Transaction: Transaction + Encodable2718 + MegaTransactionExt, - Receipt: TxReceipt, - >, -{ - /// Make pre-execution changes on the state. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn pre_execution_changes( - &mut self, - ) -> Result, BlockExecutionError> { - let mut outcomes = Vec::new(); - - // In MegaETH, the Spurious Dragon hardfork is always active, so we can safely set the state - // clear flag to true. - self.evm.db_mut().set_state_clear_flag(true); - - // Every pre-block gate below derives from the executing spec in the EVM's cfg — the - // same source `resolve_system_address` reads — compared by POSITION (`reaches`): setup - // stays additive by construction — a config that schedules only a later fork still gets - // every earlier fork's predeploys and fail-closed checks, and an alias window - // (`MINI_REX_1`, live on mainnet) rolls back behavior without dropping the Oracle - // predeploys or their read-only witness entries. On node paths the constructor asserts - // this spec equals the schedule's resolution; tools that override the cfg spec get a - // coherent what-if (setup and execution move together) instead of a hybrid block. - let setup_spec = self.evm.ctx().mega_spec(); - let is_rex_5 = setup_spec.reaches(MegaSpecId::REX5); - - // EIP-2935 - let result_and_state = eips::transact_blockhashes_contract_call( - &self.hardforks, - setup_spec, - self.ctx.parent_hash, - &mut self.evm, - )?; - if let Some(ExecResultAndState { result, state }) = result_and_state { - if is_rex_5 && !result.is_success() { - return Err(BlockValidationError::BlockHashContractCall { - message: std::format!( - "EIP-2935 pre-block system call did not succeed: {result:?}" - ), - } - .into()); - } - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PreBlock(StateChangePreBlockSource::BlockHashesContract), - state, - }); - } - - // EIP-4788 - let result_and_state = eips::transact_beacon_root_contract_call( - &self.hardforks, - setup_spec, - self.ctx.parent_beacon_block_root, - &mut self.evm, - )?; - if let Some(ExecResultAndState { result, state }) = result_and_state { - if is_rex_5 && !result.is_success() { - let parent_beacon_block_root = - self.ctx.parent_beacon_block_root.unwrap_or_default(); - return Err(BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: std::format!( - "EIP-4788 pre-block system call did not succeed: {result:?}" - ), - } - .into()); - } - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PreBlock(StateChangePreBlockSource::BeaconRootContract), - state, - }); - } - - // In MegaETH, the Isthmus hardfork is always active, which means the Canyon hardfork has - // already activated and the create2 deployer is already deployed, so we can safely assume - // that `ensure_create2_deployer` function will never be called. - - // Flat system contracts (Oracle, high-precision timestamp Oracle, KeylessDeploy, - // MegaAccessControl, MegaLimitControl) share one deploy path via the canonical - // registry. We tentatively use `StateChangeSource::Transaction(0)` as the state - // change source, as alloy defines no specific source for these predeploys. - for spec in flat_system_contract_specs_for(setup_spec) { - let state = - transact_deploy(self.evm.db_mut(), &spec).map_err(BlockExecutionError::other)?; - outcomes - .push(MegaSystemCallOutcome { source: StateChangeSource::Transaction(0), state }); - } - - // Rex5 hardfork: deploy SequencerRegistry (first block only) and apply pending - // role changes if any are due. - let block_number = self.evm.block().number.to::(); - if is_rex_5 { - // Deploy: seeds system address, sequencer, admin, and initialFromBlock - // into storage on first deploy. - // Cloned so the helper below can take `&mut self`; a few words, once per block. - let params = self - .hardforks - .fork_params::() - .ok_or_else(|| BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistryConfig not configured".into(), - })? - .clone(); - let rex6_params = self.hardforks.fork_params::().cloned(); - - // The deploy and apply-pending-changes outcomes commit in push order, while the - // apply system call always executes against the not-yet-committed state and thus - // carries the pre-deploy account info in its result. Pre-Rex6 both record the - // same v1.0.0 code, so the order is irrelevant; at the Rex6 activation block the - // deploy performs the in-place v1 → v2 bytecode upgrade (when a v1 registry - // exists), and an apply outcome committed after it would overwrite the upgraded - // account info with the stale pre-upgrade code. From Rex6 the apply call - // therefore runs BEFORE the deploy so the upgrade outcome commits last; the - // `applyPendingChanges()` logic is identical in v1/v2 (v2 changes only rotation - // scheduling), so its semantics do not depend on which side of the deploy it - // executes. Pre-Rex6 blocks keep the original deploy-then-apply order untouched. - let is_rex_6 = setup_spec.reaches(MegaSpecId::REX6); - - if !is_rex_6 { - self.push_deploy_sequencer_registry_outcome( - setup_spec, - rex6_params.as_ref(), - block_number, - ¶ms, - &mut outcomes, - )?; - } - - // Apply pending role changes if any are due. - // NOTE: The pre-check reads from the DB *before* the deploy outcome is committed. - // On the bootstrap block, the registry account does not yet exist in the DB, - // so the pre-check returns false. This is correct because deploy does not seed - // any pending slots. - let (due, witness_state) = - is_apply_pending_changes_due(self.evm.db_mut(), block_number)?; - // Always push the witness state (read-only account + slot records). - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::Transaction(0), - state: witness_state, - }); - if due { - let ExecResultAndState { state, .. } = - transact_apply_pending_changes(&mut self.evm)?; - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::Transaction(0), - state, - }); - } - - if is_rex_6 { - self.push_deploy_sequencer_registry_outcome( - setup_spec, - rex6_params.as_ref(), - block_number, - ¶ms, - &mut outcomes, - )?; - } - } - - Ok(outcomes) - } - - /// Runs the `SequencerRegistry` deploy (bootstrap, in-place upgrade, or idempotent no-op) - /// and pushes its outcome. - fn push_deploy_sequencer_registry_outcome( - &mut self, - setup_spec: MegaSpecId, - rex6_params: Option<&SequencerRegistryRex6Config>, - block_number: u64, - params: &SequencerRegistryConfig, - outcomes: &mut Vec, - ) -> Result<(), BlockExecutionError> { - let result_and_state = transact_deploy_sequencer_registry_for( - setup_spec, - rex6_params, - block_number, - self.evm.db_mut(), - params, - )?; - if let Some(state) = result_and_state { - outcomes - .push(MegaSystemCallOutcome { source: StateChangeSource::Transaction(0), state }); - } - Ok(()) - } - - /// Make post-execution changes on the state. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn post_execution_changes( - &mut self, - ) -> Result, BlockExecutionError> { - let mut outcomes = Vec::new(); - - // post block balance increments - let balance_increments = - post_block_balance_increments::
(&self.hardforks, self.evm.block(), &[], None); - // self.evm - // .db_mut() - // .increment_balances(balance_increments.clone()) - // .map_err(|_| BlockValidationError::IncrementBalanceFailed)?; - // let state = balance_increment_state(&balance_increments, self.evm.db_mut())?; - let state = eips::transact_balance_increments(balance_increments, self.evm.db_mut()) - .map_err(BlockExecutionError::other)?; - if let Some(state) = state { - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PostBlock(StateChangePostBlockSource::BalanceIncrements), - state, - }); - } - - Ok(outcomes) - } - - /// Commit the system call outcomes to the internal state of the block executor. - pub fn commit_system_call_outcomes( - &mut self, - outcomes: Vec, - ) -> Result<(), BlockExecutionError> { - for outcome in outcomes { - self.system_caller.on_state(outcome.source, &outcome.state); - self.evm.db_mut().commit(outcome.state); - } - - Ok(()) - } - - /// Alias to [`MegaBlockExecutor::run_transaction`]. - pub fn execute_mega_transaction( - &mut self, - tx: Tx, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv - + RecoveredTx - + MegaTransactionExt - + Encodable2718 - + Copy, - { - self.run_transaction(tx) - } - - /// Execute a transaction with a commit condition function without committing the execution - /// result to the block executor's inner state. - /// - /// `tx_size`/`da_size` are resolved from `Tx` through [`MegaTransactionExt`]: a `Tx` that - /// carries precomputed values (e.g. [`crate::EnrichedMegaTx`]) reuses them, while any other - /// `Tx` falls back to the trait's default, which recomputes them from the EIP-2718 encoding. - /// The choice is resolved at compile time by trait dispatch, so callers do not pick a - /// variant — this is the single execution entry point regardless of whether the transaction - /// carries a size cache. - /// - /// The `alloy_evm` block-execution path - /// ([`alloy_evm::block::BlockExecutor::execute_transaction_with_commit_condition`]) does not - /// route through this method: its `tx: impl ExecutableTx` parameter cannot be required - /// to implement [`MegaTransactionExt`], so it recomputes the sizes itself and calls - /// [`MegaBlockExecutor::run_transaction_with_sizes`] directly. - /// - /// # Correctness - /// - /// `tx_size`/`da_size` feed directly into [`BlockLimiter::pre_execution_check`]'s - /// `tx_encode_size_limit`/`tx_da_size_limit`/block cumulative-size checks. When `Tx` - /// overrides the defaults with cached values, those values are trusted with no validation - /// against the real encoded transaction: callers MUST ensure `Tx::tx_size()`/ - /// `Tx::estimated_da_size()` accurately reflect `tx`'s actual EIP-2718 encoding — an - /// understated value lets a transaction bypass a limit it should have been rejected by. - /// This is safe for the sequencer's own block-building path (the cache is computed by the - /// same trusted process, e.g. at mempool insertion), but a `Tx` whose cached sizes could - /// come from an untrusted or stale source (e.g. block validation of another party's block) - /// must not be fed here without first re-establishing that invariant. A `Tx` that uses the - /// recomputing default (e.g. a bare `Recovered<...>`) is unconditionally safe. - /// - /// A `debug_assert` cross-checks the resolved values against a fresh recompute, so a caller - /// bug is caught in tests/CI; it is compiled out in release builds. For the recomputing - /// default it is a no-op; for a cached override it is the real safety net. - /// - /// # Parameters - /// - /// - `tx`: The transaction to execute. - /// - /// # Returns - /// - /// Returns the execution outcome of the transaction. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn run_transaction( - &mut self, - tx: Tx, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv - + RecoveredTx - + MegaTransactionExt - + Encodable2718 - + Copy, - { - let tx_size = tx.tx_size(); - let da_size = tx.estimated_da_size(); - debug_assert_eq!( - tx_size, - tx.encode_2718_len() as u64, - "run_transaction: Tx-reported tx_size does not match a fresh recompute from the \ - encoded transaction" - ); - debug_assert_eq!( - da_size, - op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()), - "run_transaction: Tx-reported da_size does not match a fresh recompute from the \ - encoded transaction" - ); - self.run_transaction_with_sizes(tx, tx_size, da_size) - } - - /// Shared body of [`MegaBlockExecutor::run_transaction`] and the `alloy_evm` - /// block-execution path: `tx_size`/`da_size` are resolved by the caller (recomputed or read - /// from a cache), this only consumes them. - /// - /// This is the escape hatch for callers whose `Tx` cannot implement [`MegaTransactionExt`] - /// (e.g. the `alloy_evm` `ExecutableTx`-constrained path): they resolve the sizes themselves - /// and pass them in. Prefer [`MegaBlockExecutor::run_transaction`] otherwise, which resolves - /// the sizes for you and cross-checks any cached values. - pub fn run_transaction_with_sizes( - &mut self, - tx: Tx, - tx_size: u64, - da_size: u64, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - let is_deposit = tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE; - - // Check transaction-level and block-level limits before transaction execution - self.block_limiter.pre_execution_check( - tx.tx().tx_hash(), - tx.tx().gas_limit(), - tx_size, - da_size, - is_deposit, - )?; - - // Cache the depositor account prior to the state transition for the deposit nonce. - // - // Note that in MegaETH, the Regolith hardfork is always active, so we always have deposit - // nonces. In addition, regular transactions don't have deposit - // nonces, so we don't need to touch the DB for those. - let depositor = is_deposit - .then(|| { - self.evm - .db_mut() - .load_cache_account(*tx.signer()) - .map(|acc| acc.account_info().unwrap_or_default()) - }) - .transpose() - .map_err(BlockExecutionError::other)?; - - let hash = tx.tx().trie_hash(); - - // Execute transaction. - let outcome = self - .evm - .execute_transaction(tx.into_tx_env()) - .map_err(move |err| BlockExecutionError::evm(err, hash))?; - - Ok(BlockMegaTransactionOutcome { tx, tx_size, da_size, depositor, inner: outcome }) - } - - /// Alias to [`MegaBlockExecutor::commit_transaction_outcome`]. - pub fn commit_execution_outcome( - &mut self, - outcome: BlockMegaTransactionOutcome, - ) -> Result - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - self.commit_transaction_outcome(outcome) - } - - /// Commit the execution outcome of a transaction. - /// - /// This method commits the execution outcome of a transaction to the block executor's inner - /// state. - /// - /// # Parameters - /// - /// - `outcome`: The execution outcome of the transaction. - /// - /// # Returns - /// - /// Returns the gas used by the transaction. - pub fn commit_transaction_outcome( - &mut self, - outcome: BlockMegaTransactionOutcome, - ) -> Result - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - // Re-validate limits at commit time to handle parallel execution race conditions. - // Between run_transaction() and commit_transaction_outcome(), other transactions - // may have been committed, potentially exceeding block limits. - self.block_limiter.pre_execution_check( - outcome.tx.tx().tx_hash(), - outcome.tx.tx().gas_limit(), - outcome.tx_size, - outcome.da_size, - outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE, - )?; - - // Accumulate post-execution resource usage into block-level counters. - // This does not validate limits; over-limit enforcement happens in - // `pre_execution_check` before the next transaction. - self.block_limiter.post_execution_update(&outcome)?; - - let BlockMegaTransactionOutcome { tx, depositor, inner, .. } = outcome; - let MegaTransactionOutcome { result, state, .. } = inner; - let gas_used = result.gas_used(); - - self.system_caller.on_state(StateChangeSource::Transaction(self.receipts.len()), &state); - - let block_gas_used = self.block_limiter.block_gas_used; - self.receipts.push( - match self.receipt_builder.build_receipt(ReceiptBuilderCtx { - tx: tx.tx(), - result, - cumulative_gas_used: block_gas_used, - evm: &self.evm, - state: &state, - }) { - Ok(receipt) => receipt, - Err(ctx) => { - let receipt = alloy_consensus::Receipt { - // Success flag was added in `EIP-658: Embedding transaction status code - // in receipts`. - status: Eip658Value::Eip658(ctx.result.is_success()), - cumulative_gas_used: block_gas_used, - logs: ctx.result.into_logs(), - }; - - self.receipt_builder.build_deposit_receipt(OpDepositReceipt { - inner: receipt, - // The deposit receipt version was introduced in Canyon to indicate an - // update to how receipt hashes should be computed - // when set. The state transition process ensures - // this is only set for post-Canyon deposit - // transactions. In MegaETH, Canyon is always active. - deposit_receipt_version: depositor.is_some().then_some(1), - deposit_nonce: depositor.map(|account| account.nonce), - }) - } - }, - ); - - self.evm.db_mut().commit(state); - - Ok(gas_used) - } - - /// Get the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn get_accessed_bucket_ids(&self) -> Vec { - self.evm.ctx_ref().dynamic_storage_gas_cost.borrow().get_bucket_ids() - } - - /// Get the block hashes used during transaction execution. - /// - /// # Returns - /// - /// Returns the block hashes used during transaction execution. - pub fn get_accessed_block_hashes(&self) -> BTreeMap { - self.evm.db().block_hashes.clone() - } - - /// Clears the recorded block hash accesses. - /// - /// Block hash reads accumulate in the executor's database across every - /// transaction executed so far. Callers that need to attribute BLOCKHASH - /// reads to a single transaction (e.g. replay fixture dumping) clear the - /// record before executing it. The record is a cache: a cleared hash is - /// simply re-fetched from the underlying database on the next access, so - /// execution results are unaffected. - pub fn clear_accessed_block_hashes(&mut self) { - self.evm.db_mut().block_hashes.clear(); - } -} - -/// Implementation of `alloy_evm::block::BlockExecutor` for `MegaETH` block executor. -/// -/// This implementation delegates all block execution operations to the underlying -/// Optimism block executor while providing MegaETH-specific customizations through -/// the configured chain specification and EVM factory. -impl<'db, DB, C, R, INSP, ExtEnvs> alloy_evm::block::BlockExecutor - for MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - C: MegaHardforks, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder< - Transaction: Transaction + Encodable2718 + MegaTransactionExt, - Receipt: TxReceipt, - >, - crate::MegaTransaction: FromRecoveredTx + FromTxWithEncoded, -{ - type Transaction = R::Transaction; - - type Receipt = R::Receipt; - - type Evm = crate::MegaEvm<&'db mut State, INSP, ExtEnvs>; - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::apply_pre_execution_changes`. Changes there should be - /// synced. - fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { - let outcomes = self.pre_execution_changes()?; - self.commit_system_call_outcomes(outcomes)?; - - // After all pre-block outcomes are committed, resolve the system address for this block. - // This reads _currentSystemAddress from the now-committed SequencerRegistry storage. - // The returned EvmState captures the read as a witness record. Inside the resolver the - // behavior projection gates whether dynamic resolution applies, and the position - // projection selects the expected registry bytecode version. - let spec = self.evm.ctx().mega_spec(); - let (system_address, read_state) = - resolve_system_address(&self.hardforks, spec, self.evm.db_mut())?; - if let Some(state) = read_state { - self.system_caller.on_state(StateChangeSource::Transaction(0), &state); - self.evm.db_mut().commit(state); - } - self.evm.ctx_mut().set_system_address(system_address); - - Ok(()) - } - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::execute_transaction_with_commit_condition`. Changes there - /// should be synced. - fn execute_transaction_with_commit_condition( - &mut self, - tx: impl ExecutableTx, - f: impl FnOnce(&ExecutionResult<::HaltReason>) -> CommitChanges, - ) -> Result, BlockExecutionError> { - // `tx: impl ExecutableTx` cannot be required to implement `MegaTransactionExt`, so - // this path recomputes the sizes from the raw inner transaction and bypasses - // `run_transaction` (which reads them via the trait). See `run_transaction`'s docs. - let tx_size = tx.tx().encode_2718_len() as u64; - let da_size = tx.tx().estimated_da_size(); - let outcome = self.run_transaction_with_sizes(tx, tx_size, da_size)?; - if f(&outcome.result).should_commit() { - let gas_used = self.commit_execution_outcome(outcome)?; - Ok(Some(gas_used)) - } else { - Ok(None) - } - } - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::finish`. Changes there should be - /// synced. - fn finish( - mut self, - ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { - let outcomes = self.post_execution_changes()?; - self.commit_system_call_outcomes(outcomes)?; - - let gas_used = self.receipts.last().map(|r| r.cumulative_gas_used()).unwrap_or_default(); - Ok(( - self.evm, - BlockExecutionResult { - receipts: self.receipts, - requests: Default::default(), - gas_used, - }, - )) - } - - fn set_state_hook(&mut self, hook: Option>) { - self.system_caller.with_state_hook(hook); - } - - fn evm_mut(&mut self) -> &mut Self::Evm { - &mut self.evm - } - - fn evm(&self) -> &Self::Evm { - &self.evm - } -} diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs deleted file mode 100644 index 096640c86..000000000 --- a/crates/mega-evm/src/block/factory.rs +++ /dev/null @@ -1,205 +0,0 @@ -use alloy_consensus::{Transaction, TxReceipt}; -use alloy_eips::Encodable2718; -use alloy_evm::{ - block::BlockExecutorFor, Database, EvmEnv, EvmFactory, FromRecoveredTx, FromTxWithEncoded, -}; -use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; -use alloy_primitives::{Bytes, B256}; -use revm::{database::State, inspector::NoOpInspector, Inspector}; - -use crate::{BlockLimits, MegaBlockExecutor, MegaEvm, MegaHardforks, MegaSpecId, MegaTxEnvelope}; - -/// `MegaETH` block executor factory. -/// -/// A factory for creating block executors configured with MegaETH-specific specifications -/// and optimizations. This factory encapsulates the chain specification, EVM factory, -/// and receipt builder needed to create block executors that support `MegaETH` features -/// such as enhanced security measures and increased contract size limits. -/// -/// # Generic Parameters -/// -/// - `Hardforks`: The hardforks implementing [`MegaHardforks`] -/// - `EvmF`: The EVM factory type implementing [`alloy_evm::EvmFactory`] -/// - `ReceiptBuilder`: The receipt builder implementing [`OpReceiptBuilder`] to build op-stack -/// receipts -/// -/// # Implementation Details -/// -/// The factory implements `alloy_evm::block::BlockExecutorFactory` and delegates -/// to the underlying Optimism EVM implementation while providing MegaETH-specific -/// customizations through the configured chain specification and EVM factory. -#[derive(Debug, Clone)] -pub struct MegaBlockExecutorFactory { - receipt_builder: ReceiptBuilder, - hardforks: Hardforks, - evm_factory: EvmF, -} - -impl MegaBlockExecutorFactory -where - ReceiptBuilder: OpReceiptBuilder, -{ - /// Create a new block executor factory. - /// - /// # Parameters - /// - /// - `spec`: The chain specification (e.g., `SpecId::MINI_REX` or `SpecId::EQUIVALENCE`) - /// - `evm_factory`: The EVM factory for creating EVM instances - /// - `receipt_builder`: The receipt builder for processing transaction receipts - /// - /// # Returns - /// - /// A new `BlockExecutorFactory` instance configured with the provided parameters. - pub fn new(hardforks: Hardforks, evm_factory: EvmF, receipt_builder: ReceiptBuilder) -> Self { - Self { receipt_builder, hardforks, evm_factory } - } - - /// Returns a reference to the EVM factory. - pub fn evm_factory_ref(&self) -> &EvmF { - &self.evm_factory - } - - /// Returns a mutable reference to the EVM factory. - pub fn evm_factory_mut(&mut self) -> &mut EvmF { - &mut self.evm_factory - } -} - -impl - MegaBlockExecutorFactory, ReceiptBuilder> -where - Hardforks: MegaHardforks + Clone, - ReceiptBuilder: OpReceiptBuilder + Clone, - crate::MegaTransaction: FromRecoveredTx, - ExtEnvFactory: crate::ExternalEnvFactory + Clone, -{ - /// Create a new block executor. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. - /// - `block_ctx`: The block execution context for tracking access patterns. - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn create_executor<'a, DB>( - &self, - db: &'a mut State, - block_ctx: MegaBlockExecutionCtx, - evm_env: EvmEnv, - ) -> MegaBlockExecutor< - Hardforks, - MegaEvm<&'a mut State, NoOpInspector, ExtEnvFactory::EnvTypes>, - ReceiptBuilder, - > - where - DB: Database + 'a, - { - let runtime_limits = block_ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = self.evm_factory.create_evm(db, evm_env).with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, block_ctx, self.hardforks.clone(), self.receipt_builder.clone()) - } - - /// Create a new block executor with an inspector. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. - /// - `block_ctx`: The block execution context for tracking access patterns. - /// - `inspector`: The inspector to use for debugging and monitoring. - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn create_executor_with_inspector<'a, DB, I>( - &self, - db: &'a mut State, - block_ctx: MegaBlockExecutionCtx, - evm_env: EvmEnv, - inspector: I, - ) -> MegaBlockExecutor< - Hardforks, - MegaEvm<&'a mut State, I, ExtEnvFactory::EnvTypes>, - ReceiptBuilder, - > - where - DB: Database + 'a, - I: Inspector, ExtEnvFactory::EnvTypes>> + 'a, - { - let runtime_limits = block_ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = self - .evm_factory - .create_evm_with_inspector(db, evm_env, inspector) - .with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, block_ctx, self.hardforks.clone(), self.receipt_builder.clone()) - } -} - -impl alloy_evm::block::BlockExecutorFactory - for MegaBlockExecutorFactory, ReceiptBuilder> -where - ReceiptBuilder: OpReceiptBuilder, - Hardforks: MegaHardforks + Clone, - ExtEnvFactory: crate::ExternalEnvFactory + Clone, - crate::MegaTransaction: FromRecoveredTx - + FromTxWithEncoded, - Self: 'static, -{ - type EvmFactory = crate::MegaEvmFactory; - type ExecutionCtx<'a> = MegaBlockExecutionCtx; - type Transaction = ReceiptBuilder::Transaction; - type Receipt = ReceiptBuilder::Receipt; - - fn evm_factory(&self) -> &Self::EvmFactory { - self.evm_factory_ref() - } - - fn create_executor<'a, DB, I>( - &'a self, - evm: ::Evm<&'a mut State, I>, - ctx: Self::ExecutionCtx<'a>, - ) -> impl BlockExecutorFor<'a, Self, DB, I> - where - DB: Database + 'a, - I: Inspector<::Context<&'a mut State>> + 'a, - { - // Synchronize EVM tx runtime limits with the block context's BlockLimits. - // This mirrors the inherent factory paths above which apply this - // unconditionally on every spec since introduction. Without this, the - // trait impl path silently ran against whatever limits the caller did - // or did not pre-apply via with_tx_runtime_limits, leaving an asymmetry - // between the inherent and trait construction routes. - let runtime_limits = ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = evm.with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, ctx, &self.hardforks, &self.receipt_builder) - } -} - -/// Block execution context for the `MegaETH` chain. -#[derive(Debug, Clone)] -pub struct MegaBlockExecutionCtx { - /// Parent block hash. - pub parent_hash: B256, - /// Parent beacon block root. - pub parent_beacon_block_root: Option, - /// The block's extra data. - pub extra_data: Bytes, - - /// The block limits. - pub block_limits: BlockLimits, -} - -impl MegaBlockExecutionCtx { - /// Create a new block execution context with default limits. - pub fn new( - parent_hash: B256, - parent_beacon_block_root: Option, - extra_data: Bytes, - block_limits: BlockLimits, - ) -> Self { - Self { parent_hash, parent_beacon_block_root, extra_data, block_limits } - } -} diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs deleted file mode 100644 index 82e02404e..000000000 --- a/crates/mega-evm/src/block/hardfork.rs +++ /dev/null @@ -1,1167 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; - -use alloy_hardforks::{hardfork, EthereumHardfork, EthereumHardforks, ForkCondition, Hardfork}; -use alloy_op_hardforks::{OpHardfork, OpHardforks}; -use alloy_primitives::{BlockTimestamp, U256}; -use auto_impl::auto_impl; -use core::any::Any; -use std::{boxed::Box, sync::Arc, vec::Vec}; - -use crate::{MegaSpecId, SequencerRegistryConfig, SequencerRegistryRex6Config}; - -hardfork! { - /// The name of MegaETH hardforks. It is expected to mix with [`EthereumHardfork`] and - /// [`OpHardfork`]. - #[derive(serde::Serialize, serde::Deserialize)] - MegaHardfork { - /// The first hardfork. - MiniRex, - /// The first alias hardfork: rolls behavior back to Equivalence on its own rung. - MiniRex1, - /// The second alias hardfork: restores MiniRex behavior on its own rung. - MiniRex2, - /// The fourth hardfork. - Rex, - /// The fifth hardfork (first patch to Rex). - Rex1, - /// The sixth hardfork (second patch to Rex). - Rex2, - /// The seventh hardfork (third patch to Rex). - Rex3, - /// The eighth hardfork (fourth patch to Rex). - Rex4, - /// The ninth hardfork (fifth patch to Rex). - Rex5, - /// The tenth hardfork (sixth patch to Rex). - Rex6, - /// The eleventh hardfork (seventh patch to Rex). - Rex7, - } -} - -impl MegaHardfork { - /// Whether this fork introduces new behavior — its spec is not an alias. Alias forks - /// (`MiniRex1`, `MiniRex2`) schedule a rung whose behavior belongs to an earlier spec. - pub(crate) fn introduces_behavior(self) -> bool { - !self.spec_id().is_alias() - } - - /// Gets the `MegaSpecId` associated with this hardfork. - #[allow(clippy::match_same_arms)] - pub const fn spec_id(&self) -> MegaSpecId { - // Note: MiniRex1 and MiniRex2 map to alias specs: rungs of their own whose - // behavior projects to previously released specs. - match self { - Self::MiniRex => MegaSpecId::MINI_REX, - Self::MiniRex1 => MegaSpecId::MINI_REX_1, - Self::MiniRex2 => MegaSpecId::MINI_REX_2, - Self::Rex => MegaSpecId::REX, - Self::Rex1 => MegaSpecId::REX1, - Self::Rex2 => MegaSpecId::REX2, - Self::Rex3 => MegaSpecId::REX3, - Self::Rex4 => MegaSpecId::REX4, - Self::Rex5 => MegaSpecId::REX5, - Self::Rex6 => MegaSpecId::REX6, - Self::Rex7 => MegaSpecId::REX7, - } - } -} - -/// Whether each fork in `forks` maps to a strictly higher spec rung than the fork before it. -/// -/// This is the invariant the fork→spec map rests on: the reverse scan in -/// [`MegaHardforks::hardfork`] and the skipped-rung rule in -/// [`MegaHardforks::validate_schedule`] assume declaration order climbs the ladder, and -/// strictness pins injectivity — no two forks share a rung, so the map stays 1:1 and the -/// resolved spec is monotone on any ordered schedule. -/// -/// Shared by the compile-time assertion below and by the test that feeds it malformed lists, -/// so the checker itself is exercised — the real `VARIANTS` always satisfies the property it -/// checks. -const fn climbs_the_spec_ladder(forks: &[MegaHardfork]) -> bool { - let mut i = 1; - while i < forks.len() { - if forks[i - 1].spec_id() as u8 >= forks[i].spec_id() as u8 { - return false; - } - i += 1; - } - true -} - -const _: () = assert!( - climbs_the_spec_ladder(MegaHardfork::VARIANTS), - "every hardfork must map to a strictly higher spec rung than the fork declared before it — \ - express a rollback as a new alias rung, not by reusing an earlier spec" -); - -/// Validation error returned by [`HardforkParams::validate`]. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] -#[display("{message}")] -pub struct HardforkParamsError { - /// Human-readable description of the invalid field or invariant. - pub message: std::string::String, -} - -/// Marker trait for per-fork parameters. -/// -/// Each params type is pinned to exactly one [`MegaHardfork`] variant via `FORK`. -/// This lets [`MegaHardforks::fork_params`] return a typed reference without -/// requiring the caller to specify the fork separately. -pub trait HardforkParams: Any + core::fmt::Debug + Send + Sync { - /// The hardfork this params type belongs to. - const FORK: MegaHardfork; - - /// Validates construction-time invariants (no cross-fork context required). - /// - /// Called by [`MegaHardforkConfig::with_params`] so misconfiguration is caught - /// at chain-config load time rather than at the first block where the fork activates. - /// The default implementation accepts any value. - fn validate(&self) -> Result<(), HardforkParamsError> { - Ok(()) - } -} - -/// Extends [`OpHardforks`] with `MegaETH` helper methods. -/// -/// Forks map 1:1 onto specs, so [`spec_id`](Self::spec_id) — the latest activated fork's spec — -/// is monotone: it only ever climbs. Rollbacks are expressed by *alias specs* (`MINI_REX_1`, -/// `MINI_REX_2`): rungs of their own whose behavior projects to an earlier spec. One resolved -/// value is therefore read through two projections: -/// -/// - `spec.is_enabled(X)` — the BEHAVIOR gate: both sides project through [`MegaSpecId::behavior`], -/// so execution semantics roll back inside an alias window. -/// - `spec.reaches(X)` — the POSITION gate: raw rung comparison for one-way chain setup -/// (predeploys, bytecode versions, pre-block rules), which a rollback does not retract. -/// -/// The `is__active_at_timestamp` predicates are position projections for -/// behavior-introducing forks (additive on schedules that omit a predecessor) and raw event -/// queries for alias forks, whose occurrence is not recoverable from the ladder. To ask about -/// the raw scheduling event of any fork, use `mega_fork_activation` directly. To check a -/// schedule for well-formedness (rung gaps, ordering, required params), use -/// [`validate_schedule`](Self::validate_schedule). -#[auto_impl(&, Box, Arc)] -pub trait MegaHardforks: OpHardforks { - /// Retrieves [`ForkCondition`] by a [`MegaHardfork`]. If `fork` is not present, returns - /// [`ForkCondition::Never`]. - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; - - /// Returns a type-erased reference to per-fork parameters, if configured. - /// - /// Most forks carry no parameters and the default implementation returns `None`. - fn fork_params_any(&self, _fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - None - } - - /// Returns a typed reference to per-fork parameters. - /// - /// `P::FORK` identifies the fork. Returns `None` if the fork has no params configured. - fn fork_params(&self) -> Option<&P> { - self.fork_params_any(P::FORK)?.downcast_ref::

() - } - - /// Returns the current `MegaHardfork` active at the given timestamp. - /// - /// Resolution walks the declaration ladder from the top: the latest-declared fork whose - /// activation event has occurred wins. Declaration order is chronological, so at equal - /// activation timestamps the later-declared fork prevails. Driven off - /// [`MegaHardfork::VARIANTS`] so a newly declared fork joins resolution without a second - /// hand-written ladder here. - /// - /// Resolution reads raw activation events - /// ([`mega_fork_activation`](Self::mega_fork_activation)); with the 1:1 ascending fork->spec - /// map, the resolved spec is monotone in time on any ordered schedule. - fn hardfork(&self, timestamp: BlockTimestamp) -> Option { - MegaHardfork::VARIANTS - .iter() - .rev() - .find(|fork| self.mega_fork_activation(**fork).active_at_timestamp(timestamp)) - .copied() - } - - /// Returns the current `MegaSpecId` for the given block timestamp. - fn spec_id(&self, timestamp: BlockTimestamp) -> MegaSpecId { - self.hardfork(timestamp).map_or(MegaSpecId::EQUIVALENCE, |h| h.spec_id()) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::MINI_REX`], the - /// spec introduced by [`MegaHardfork::MiniRex`]. Position-projected (`reaches`) — see the trait - /// docs; for the raw activation event use - /// [`mega_fork_activation`](Self::mega_fork_activation). - fn is_mini_rex_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::MINI_REX) - } - - /// Returns `true` if the [`MegaHardfork::MiniRex1`] activation event has occurred at the - /// given block timestamp. - /// - /// `MiniRex1` schedules the alias rung [`MegaSpecId::MINI_REX_1`], whose occurrence is not - /// recoverable from the ladder position (later rungs stand above it whether or not it was - /// ever scheduled), so this predicate stays a raw event query, unlike the - /// position-projected predicates of behavior-introducing forks. - fn is_mini_rex_1_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.mega_fork_activation(MegaHardfork::MiniRex1).active_at_timestamp(timestamp) - } - - /// Returns `true` if the [`MegaHardfork::MiniRex2`] activation event has occurred at the - /// given block timestamp. - /// - /// `MiniRex2` schedules the alias rung [`MegaSpecId::MINI_REX_2`], whose occurrence is not - /// recoverable from the ladder position, so this predicate stays a raw event query, unlike - /// the position-projected predicates of behavior-introducing forks. - fn is_mini_rex_2_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.mega_fork_activation(MegaHardfork::MiniRex2).active_at_timestamp(timestamp) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX`], the rung - /// introduced by [`MegaHardfork::Rex`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX1`], the rung - /// introduced by [`MegaHardfork::Rex1`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_1_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX1) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX2`], the rung - /// introduced by [`MegaHardfork::Rex2`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_2_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX2) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX3`], the rung - /// introduced by [`MegaHardfork::Rex3`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_3_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX3) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX4`], the rung - /// introduced by [`MegaHardfork::Rex4`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_4_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX4) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX5`], the rung - /// introduced by [`MegaHardfork::Rex5`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_5_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX5) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX6`], the rung - /// introduced by [`MegaHardfork::Rex6`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_6_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX6) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX7`], the rung - /// introduced by [`MegaHardfork::Rex7`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_7_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX7) - } - - /// Checks the schedule for well-formedness, i.e., that it describes a chain climbing the - /// spec ladder rung by rung. - /// - /// This is the fail-fast complement to the fail-safe execution layer: block execution - /// tolerates a malformed schedule (setup gates compare rung positions, so a skipped rung's - /// setup still runs), but a real chain's published schedule with a skipped rung is almost - /// certainly a configuration mistake. Chain-config authors and node startup - /// paths should call this and refuse a schedule that does not validate. - /// - /// Checked, in order: - /// - /// - Every registered `MegaHardfork` activates by [`ForkCondition::Timestamp`] (or is - /// [`ForkCondition::Never`]). Block-number and TTD conditions never report active to the - /// timestamp-scoped resolution here and would silently deactivate the fork. - /// - Scheduled forks activate in declaration order: a later-declared fork must not activate - /// strictly before an earlier-declared one. - /// - No skipped rungs: a behavior-introducing fork may be unscheduled only if no scheduled fork - /// maps to an equal-or-higher rung. Alias forks are exempt as the *missing* side — testnet - /// legitimately never schedules `MiniRex1`/`MiniRex2` — but an alias scheduled without its - /// base is itself a skipped rung (the alias's rung sits above the base's). - /// - Per-fork parameters required by a scheduled fork are present (`Rex5` requires - /// [`SequencerRegistryConfig`](crate::SequencerRegistryConfig), `Rex6` requires - /// [`SequencerRegistryRex6Config`](crate::SequencerRegistryRex6Config)). This surfaces a - /// missing config at load time rather than at the first block of the fork. A new - /// [`HardforkParams`] type must be registered here. - fn validate_schedule(&self) -> Result<(), ScheduleError> { - let scheduled = - |fork: MegaHardfork| self.mega_fork_activation(fork) != ForkCondition::Never; - - let mut prev: Option<(MegaHardfork, u64)> = None; - for fork in MegaHardfork::VARIANTS { - match self.mega_fork_activation(*fork) { - ForkCondition::Never => {} - ForkCondition::Timestamp(timestamp) => { - if let Some((earlier, earlier_timestamp)) = prev { - if timestamp < earlier_timestamp { - return Err(ScheduleError::UnorderedForks { - earlier, - earlier_timestamp, - later: *fork, - later_timestamp: timestamp, - }); - } - } - prev = Some((*fork, timestamp)); - } - _ => return Err(ScheduleError::NonTimestampActivation { fork: *fork }), - } - } - - for fork in MegaHardfork::VARIANTS { - if !fork.introduces_behavior() || scheduled(*fork) { - continue; - } - if let Some(above) = MegaHardfork::VARIANTS - .iter() - .find(|g| scheduled(**g) && g.spec_id() >= fork.spec_id()) - { - return Err(ScheduleError::SkippedRung { missing: *fork, scheduled: *above }); - } - } - - if scheduled(MegaHardfork::Rex5) && self.fork_params::().is_none() - { - return Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig", - }); - } - if scheduled(MegaHardfork::Rex6) && - self.fork_params::().is_none() - { - return Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config", - }); - } - - Ok(()) - } -} - -/// A malformed hardfork schedule, as reported by [`MegaHardforks::validate_schedule`]. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] -pub enum ScheduleError { - /// A later-declared fork activates strictly before an earlier-declared one. - #[display( - "hardfork {later:?} (t={later_timestamp}) activates before {earlier:?} (t={earlier_timestamp})" - )] - UnorderedForks { - /// The earlier-declared fork. - earlier: MegaHardfork, - /// Activation timestamp of the earlier-declared fork. - earlier_timestamp: u64, - /// The later-declared fork that activates too early. - later: MegaHardfork, - /// Activation timestamp of the later-declared fork. - later_timestamp: u64, - }, - /// A spec-introducing fork is unscheduled while a fork of an equal-or-higher spec is - /// scheduled — the ladder skips a rung. - #[display("hardfork {missing:?} is unscheduled but {scheduled:?} is scheduled above it")] - SkippedRung { - /// The unscheduled spec-introducing fork. - missing: MegaHardfork, - /// A scheduled fork whose spec is equal or higher. - scheduled: MegaHardfork, - }, - /// A `MegaHardfork` is registered with a block-number or TTD condition, which the - /// timestamp-scoped resolution never reports as active. - #[display("hardfork {fork:?} must activate by timestamp, not block number or TTD")] - NonTimestampActivation { - /// The fork with a non-timestamp activation condition. - fork: MegaHardfork, - }, - /// A scheduled fork requires per-fork parameters that are not attached. - #[display("hardfork {fork:?} is scheduled but its {params} params are not configured")] - MissingParams { - /// The scheduled fork whose params are missing. - fork: MegaHardfork, - /// The required params type. - params: &'static str, - }, -} - -/// A single fork entry: identity, activation condition, and optional per-fork parameters. -#[derive(Debug)] -struct ForkEntry { - fork: Box, - condition: ForkCondition, - params: Option>, -} - -impl Clone for ForkEntry { - fn clone(&self) -> Self { - Self { fork: self.fork.clone(), condition: self.condition, params: self.params.clone() } - } -} - -/// Configuration of the hardforks for `MegaETH`. It by default includes no `MegaHardfork` but -/// includes all hardforks before and including Optimism Isthmus. Optimism Isthmus is the hardfork -/// where `MegaETH` is established. -/// -/// Per-fork parameters (e.g., [`SequencerRegistryConfig`](crate::SequencerRegistryConfig)) are -/// embedded in the corresponding fork entry via [`with_params`](Self::with_params). -#[derive(Debug, Clone)] -pub struct MegaHardforkConfig { - entries: Vec, -} - -impl Default for MegaHardforkConfig { - fn default() -> Self { - Self::new() - } -} - -impl From for MegaHardforkConfig -where - I: Iterator, - H: Hardfork + 'static, -{ - fn from(iter: I) -> Self { - Self { - entries: iter - .map(|(h, c)| ForkEntry { - fork: Box::new(h) as Box, - condition: c, - params: None, - }) - .collect(), - } - } -} - -impl MegaHardforkConfig { - /// Creates a new hardfork configuration with the default hardforks, i.e., all hardforks before - /// and including Optimism Isthmus are enabled. Optimism Isthmus is the hardfork where - /// `MegaETH` is established. - pub fn new() -> Self { - let forks: Vec<(Box, ForkCondition)> = vec![ - (EthereumHardfork::Frontier.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Homestead.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Dao.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Tangerine.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::SpuriousDragon.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Byzantium.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Constantinople.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Petersburg.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Istanbul.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Berlin.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::London.boxed(), ForkCondition::Block(0)), - ( - EthereumHardfork::Paris.boxed(), - ForkCondition::TTD { - activation_block_number: 0, - fork_block: None, - total_difficulty: U256::ZERO, - }, - ), - (OpHardfork::Bedrock.boxed(), ForkCondition::Block(0)), - (OpHardfork::Regolith.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Shanghai.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Canyon.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Cancun.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Ecotone.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Fjord.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Granite.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Holocene.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Prague.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Isthmus.boxed(), ForkCondition::Timestamp(0)), - ]; - Self { - entries: forks - .into_iter() - .map(|(fork, condition)| ForkEntry { fork, condition, params: None }) - .collect(), - } - } - - /// Sets all `MegaHardfork` to be activated at timestamp 0. - pub fn with_all_activated(self) -> Self { - self.with_all_activated_through(MegaSpecId::default()) - } - - /// Activates every `MegaHardfork` whose spec is enabled under `spec` at timestamp 0, and - /// leaves every later fork unregistered. - /// - /// This is how to express "a chain running spec N": the resulting config resolves to `spec` - /// at any timestamp. Removing only the next fork up is not equivalent — the ladder runs past - /// it, so the config would resolve to the newest fork still registered rather than to `spec`, - /// and it would silently drift again the next time a spec is introduced. On top of the wrong - /// resolved spec, the leftover later forks also keep the scheduled spec high, so every - /// pre-block setup gate below them stays open. - /// - /// The *activations* in the result are a function of `spec` alone, not of what the config - /// held before: a later fork already registered is removed rather than left in place, so the - /// resolved spec does not depend on builder call order. Per-fork params are the exception: - /// params on a kept fork are preserved, while params on a removed fork are dropped with its - /// entry and are not restored by a later climb back up — re-attach them with - /// [`with_params`](Self::with_params). - /// - /// Alias forks sit on their own rungs above their base (`MINI_REX_1`/`MINI_REX_2` above - /// `MINI_REX`), so climbing through a rung includes everything below it — aliases and - /// bases alike — with no special casing. - pub fn with_all_activated_through(mut self, spec: MegaSpecId) -> Self { - for fork in MegaHardfork::VARIANTS { - if spec.reaches(fork.spec_id()) { - self.insert(*fork, ForkCondition::Timestamp(0)); - } else { - self = self.without(*fork); - } - } - self - } - - /// Attaches per-fork parameters to the entry identified by `P::FORK`. - /// - /// The fork must already exist in the config (via [`with`](Self::with) or default). - /// Panics if the fork is not found or if `params.validate()` returns an error. - pub fn with_params(mut self, params: P) -> Self { - if let Err(e) = params.validate() { - panic!("Invalid params for fork {:?}: {}", P::FORK, e.message,); - } - let entry = - self.entries.iter_mut().find(|e| e.fork.name() == P::FORK.name()).unwrap_or_else( - || { - panic!( - "Cannot attach params to fork {:?}: fork not registered in config. \ - Call .with({:?}, condition) first.", - P::FORK, - P::FORK, - ) - }, - ); - entry.params = Some(Arc::new(params)); - self - } - - /// Removes a `MegaHardfork` from the configuration, i.e., equivalent to setting the fork - /// condition to [`ForkCondition::Never`]. - /// - /// Deliberately private: `with_all_activated().without(fork)` reads as "a chain running the - /// spec below `fork`" but does not express it — the forks above `fork` stay registered, so - /// the config resolves above the intended rung and silently climbs again with the next spec. - /// Say it with [`with_all_activated_through`](Self::with_all_activated_through) instead. - /// - /// This narrows an idiom, not a capability: [`with`](Self::with) with - /// [`ForkCondition::Never`] produces the same unregistered fork, and must stay public because - /// the canonical schedules use it for exactly that (testnet's `MiniRex1` / `MiniRex2` never - /// activate). Writing a gap that way is at least visibly deliberate, and it keeps the entry - /// so [`with_params`](Self::with_params) can still attach to it. - fn without(mut self, hardfork: MegaHardfork) -> Self { - self.entries.retain(|e| e.fork.name() != hardfork.name()); - self - } - - /// Creates a new hardfork configuration with the given hardfork and condition. - pub fn with(mut self, hardfork: impl Hardfork, condition: ForkCondition) -> Self { - self.insert(hardfork, condition); - self - } - - /// Inserts a new hardfork into the configuration. If the hardfork is already present, it will - /// be overwritten (condition updated, params preserved). - pub fn insert(&mut self, hardfork: impl Hardfork, condition: ForkCondition) { - let index = self.entries.iter().position(|e| e.fork.name() == hardfork.name()); - if let Some(index) = index { - self.entries[index].condition = condition; - } else { - self.entries.push(ForkEntry { fork: Box::new(hardfork), condition, params: None }); - } - } - - /// Gets `ForkCondition` by a [`Hardfork`]. If the hardfork is not present, returns `None`. - pub fn get(&self, hardfork: impl Hardfork) -> Option<&ForkCondition> { - self.entries.iter().find(|e| e.fork.name() == hardfork.name()).map(|e| &e.condition) - } -} - -impl EthereumHardforks for MegaHardforkConfig { - fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, - } - } -} - -impl OpHardforks for MegaHardforkConfig { - fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, - } - } -} - -impl MegaHardforks for MegaHardforkConfig { - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, - } - } - - fn fork_params_any(&self, fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - self.entries.iter().find(|e| e.fork.name() == fork.name()).and_then(|e| e.params.as_deref()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::SequencerRegistryConfig; - - #[test] - fn test_climbs_the_spec_ladder_rejects_malformed_lists() { - // The real `VARIANTS` is checked at compile time by the const assertion; only - // rejection cases can detect a weakened guard inside the checker. - assert!(climbs_the_spec_ladder(MegaHardfork::VARIANTS)); - assert!(climbs_the_spec_ladder(&[]), "the empty list climbs trivially"); - assert!(climbs_the_spec_ladder(&[MegaHardfork::Rex]), "a single fork climbs trivially"); - assert!( - climbs_the_spec_ladder(&[MegaHardfork::MiniRex, MegaHardfork::Rex5]), - "gaps are fine — strictly ascending is the property, contiguity is not" - ); - - assert!( - !climbs_the_spec_ladder(&[MegaHardfork::Rex, MegaHardfork::MiniRex]), - "a fork mapping below its predecessor must be rejected" - ); - assert!( - !climbs_the_spec_ladder(&[MegaHardfork::Rex, MegaHardfork::Rex]), - "two forks sharing a rung must be rejected — the map must stay 1:1" - ); - } - - #[test] - fn test_mega_hardfork_spec_ids_match_expected_specs() { - // Note: MiniRex1 and MiniRex2 map to alias rungs whose behavior reverts to earlier specs. - let cases = [ - (MegaHardfork::MiniRex, MegaSpecId::MINI_REX), - (MegaHardfork::MiniRex1, MegaSpecId::MINI_REX_1), - (MegaHardfork::MiniRex2, MegaSpecId::MINI_REX_2), - (MegaHardfork::Rex, MegaSpecId::REX), - (MegaHardfork::Rex1, MegaSpecId::REX1), - (MegaHardfork::Rex2, MegaSpecId::REX2), - (MegaHardfork::Rex3, MegaSpecId::REX3), - (MegaHardfork::Rex4, MegaSpecId::REX4), - (MegaHardfork::Rex5, MegaSpecId::REX5), - (MegaHardfork::Rex6, MegaSpecId::REX6), - (MegaHardfork::Rex7, MegaSpecId::REX7), - ]; - - for (hardfork, expected_spec) in cases { - assert_eq!(hardfork.spec_id(), expected_spec); - } - } - - #[test] - fn test_default_config_contains_upstream_forks_and_no_mega_forks() { - let config = MegaHardforkConfig::default(); - - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Frontier), - ForkCondition::Block(0) - ); - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Prague), - ForkCondition::Timestamp(0) - ); - assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); - assert_eq!(config.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_config_builder_helpers_override_and_remove_hardforks() { - let mut config = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(10)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(80)); - - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(10))); - assert_eq!(config.get(MegaHardfork::Rex4), Some(&ForkCondition::Timestamp(80))); - - config.insert(MegaHardfork::MiniRex, ForkCondition::Timestamp(20)); - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(20))); - - let config = config.without(MegaHardfork::MiniRex); - assert_eq!(config.get(MegaHardfork::MiniRex), None); - - let from_iter = MegaHardforkConfig::from( - [ - (MegaHardfork::MiniRex, ForkCondition::Timestamp(1)), - (MegaHardfork::Rex2, ForkCondition::Timestamp(2)), - ] - .into_iter(), - ); - assert_eq!(from_iter.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(1))); - assert_eq!(from_iter.get(MegaHardfork::Rex2), Some(&ForkCondition::Timestamp(2))); - } - - #[test] - fn test_with_all_activated_enables_all_mega_hardforks() { - let config = MegaHardforkConfig::default().with_all_activated(); - - // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list - // that declares the enum. A second hand-written list here would assert only that the - // forks someone remembered to name are activated — a new fork missing from both the - // builder and the list would fail neither. - for hardfork in MegaHardfork::VARIANTS { - assert_eq!( - config.mega_fork_activation(*hardfork), - ForkCondition::Timestamp(0), - "{hardfork:?}" - ); - } - } - - #[test] - fn test_fork_params_typed_access() { - let params = SequencerRegistryConfig { - rex5_initial_sequencer: alloy_primitives::address!( - "0x2222222222222222222222222222222222222222" - ), - rex5_initial_admin: alloy_primitives::address!( - "0x3333333333333333333333333333333333333333" - ), - }; - - let config = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(params.clone()); - - let retrieved = config - .fork_params::() - .expect("should have SequencerRegistryConfig"); - assert_eq!(retrieved, ¶ms); - } - - #[test] - fn test_fork_params_none_when_not_configured() { - let config = - MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); - - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_default_validate_accepts_any_value() { - #[derive(Debug)] - struct NullParams; - - impl HardforkParams for NullParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - } - - assert!(NullParams.validate().is_ok()); - } - - #[test] - fn test_hardfork_params_error_display() { - let e = HardforkParamsError { message: "something went wrong".into() }; - assert_eq!(e.to_string(), "something went wrong"); - } - - #[test] - #[should_panic(expected = "Invalid params for fork")] - fn test_with_params_panics_on_validation_error() { - #[derive(Debug)] - struct AlwaysErrParams; - - impl HardforkParams for AlwaysErrParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - - fn validate(&self) -> Result<(), HardforkParamsError> { - Err(HardforkParamsError { message: "intentional test error".into() }) - } - } - - MegaHardforkConfig::default().with_all_activated().with_params(AlwaysErrParams); - } - - /// Mainnet runs a real behavior rollback: inside the `MiniRex1` window the scheduled spec - /// is the alias rung `MINI_REX_1` — behavior projects to `EQUIVALENCE` while position keeps - /// one-way setup (the Oracle predeploys) enabled. - #[test] - fn test_mainnet_rollback_window_behavior_rolls_back_setup_stays() { - let hf = crate::mainnet_hardforks(); - let ForkCondition::Timestamp(rollback_start) = - hf.mega_fork_activation(MegaHardfork::MiniRex1) - else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - let ForkCondition::Timestamp(rollback_end) = - hf.mega_fork_activation(MegaHardfork::MiniRex2) - else { - panic!("mainnet must schedule MiniRex2 by timestamp"); - }; - assert!(rollback_start < rollback_end, "the rollback window must be non-empty"); - - for ts in [rollback_start, rollback_start + 1, rollback_end - 1] { - let spec = hf.spec_id(ts); - assert_eq!(spec, MegaSpecId::MINI_REX_1, "the scheduled spec is monotone"); - assert_eq!(spec.behavior(), MegaSpecId::EQUIVALENCE, "behavior rolls back"); - // Behavior gates turn MiniRex features off; position gates keep its setup. - assert!(!spec.is_enabled(MegaSpecId::MINI_REX)); - assert!(spec.reaches(MegaSpecId::MINI_REX)); - assert!(hf.is_mini_rex_active_at_timestamp(ts)); - } - } - - /// The scheduled spec's position reproduces every per-fork activation event exactly, for - /// every behavior-introducing fork, on every canonical schedule. This is what makes the - /// position-projected predicates a no-op switch on well-formed ladders. - /// - /// Forks that introduce no new behavior — `MiniRex1` (rollback to `EQUIVALENCE`) and - /// `MiniRex2` (restoration to `MINI_REX`) — may be omitted from a schedule whose ladder - /// climbs past their rungs, so their activation events are not recoverable from position and - /// nothing may gate on them this way. The predicate is derived rather than hardcoded so a - /// future rollback fork is classified automatically. - #[test] - fn test_position_matches_per_fork_activation_for_behavior_introducing_forks() { - for hf in [ - crate::mainnet_hardforks(), - crate::testnet_hardforks(), - crate::all_activated_hardforks(), - ] { - let mut stamps = std::vec![0u64, u64::MAX]; - for fork in MegaHardfork::VARIANTS { - if let ForkCondition::Timestamp(t) = hf.mega_fork_activation(*fork) { - stamps.extend([t.saturating_sub(1), t, t.saturating_add(1)]); - } - } - - for ts in stamps { - let resolved = hf.spec_id(ts); - for fork in MegaHardfork::VARIANTS { - if !fork.introduces_behavior() { - continue; - } - assert_eq!( - resolved.reaches(fork.spec_id()), - hf.mega_fork_activation(*fork).active_at_timestamp(ts), - "position disagrees with per-fork activation for {fork:?} at ts={ts}" - ); - } - } - } - } - - /// On a partial ladder — a config that schedules a later fork without its predecessors — the - /// resolved spec still enables every lower spec, and the spec-introducing predicates, being - /// position projections, report active for forks that were never scheduled. Gating on either - /// can therefore not silently skip a predecessor's behavior; only the raw activation events - /// distinguish the missing rungs. - #[test] - fn test_partial_ladder_resolved_spec_enables_unscheduled_predecessors() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)); - - assert_eq!(hf.mega_fork_activation(MegaHardfork::Rex5), ForkCondition::Never); - assert_eq!(hf.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - - let resolved = hf.spec_id(0); - assert_eq!(resolved, MegaSpecId::REX6); - for spec in [MegaSpecId::MINI_REX, MegaSpecId::REX2, MegaSpecId::REX4, MegaSpecId::REX5] { - assert!(resolved.is_enabled(spec), "{spec:?} must be enabled on a partial ladder"); - } - // The predicates project the position: unscheduled predecessors still report active. - assert!(hf.is_rex_5_active_at_timestamp(0), "Rex5 predicate projects the position"); - assert!(hf.is_mini_rex_active_at_timestamp(0), "MiniRex predicate projects the position"); - } - - /// `with_all_activated_through` is the well-formed way to express "a chain running spec N": - /// the resolved spec is exactly `N` at any timestamp. The specs under test come from - /// [`MegaSpecId::ALL`], so a newly introduced spec is covered here automatically instead of - /// depending on a hand-written list. - #[test] - fn test_with_all_activated_through_resolves_to_that_spec() { - for spec in MegaSpecId::ALL.iter().copied() { - let config = MegaHardforkConfig::default().with_all_activated_through(spec); - assert_eq!(config.spec_id(0), spec, "{spec:?} at genesis"); - assert_eq!(config.spec_id(u64::MAX), spec, "{spec:?} must be terminal"); - - // The same contract must hold when the config already carries later forks: the - // builder states the whole ladder, so it removes what it does not activate. Without - // that, the resolved spec would depend on which builder ran last. - let downgraded = - MegaHardforkConfig::default().with_all_activated().with_all_activated_through(spec); - assert_eq!(downgraded.spec_id(u64::MAX), spec, "{spec:?} from an activated config"); - } - } - - /// Removing a middle rung does NOT express "a chain running spec N". It is the partial-ladder - /// shape: the resolved spec follows the newest fork still registered, and — with the - /// predicate projected from its position — keeps every lower gate open. - #[test] - fn test_removing_a_middle_rung_does_not_lower_the_spec() { - let partial = - MegaHardforkConfig::default().with_all_activated().without(MegaHardfork::Rex4); - - assert_eq!( - partial.mega_fork_activation(MegaHardfork::Rex4), - ForkCondition::Never, - "Rex4 itself is unregistered" - ); - assert_ne!(partial.spec_id(0), MegaSpecId::REX4, "the resolved spec is not lowered"); - assert!( - partial.spec_id(0).is_enabled(MegaSpecId::REX4), - "the resolved spec still enables the removed fork's spec" - ); - assert!(partial.is_rex_4_active_at_timestamp(0), "the projected predicate stays open"); - } - - /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered - /// by block number never contributes its own spec to it. `spec_id`/`hardfork` share this - /// limitation; every canonical schedule uses `Timestamp` or `Never`, and - /// `validate_schedule` rejects anything else. - #[test] - fn test_resolution_ignores_block_numbered_forks() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(0)); - - assert!( - !hf.mega_fork_activation(MegaHardfork::MiniRex).active_at_timestamp(0), - "block-numbered forks are not timestamped" - ); - // The resolved spec comes from Rex alone; it still covers MINI_REX by ordinal - // inclusion, so the projected predicate reports active even though the MiniRex event - // itself never fires. - assert_eq!(hf.spec_id(0), MegaSpecId::REX); - assert!(hf.spec_id(0).is_enabled(MegaSpecId::MINI_REX)); - assert!(hf.is_mini_rex_active_at_timestamp(0)); - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::MiniRex }) - ); - } - - /// The resolved spec must equal the naive maximum over all activated forks, on every - /// schedule shape: canonical ladders, rollback windows, partial ladders, block-numbered - /// conditions, and the empty config. Under the 1:1 ascending fork→spec map the latest - /// activated fork IS the maximum; the const assertion on `climbs_the_spec_ladder` pins that - /// statically for declaration order, and this pins it dynamically across schedule shapes. - #[test] - fn test_resolved_spec_is_the_maximum_over_activated_forks() { - let configs = [ - crate::mainnet_hardforks(), - crate::testnet_hardforks(), - crate::all_activated_hardforks(), - MegaHardforkConfig::new(), - // Partial ladders: a lone top rung, and a lone alias fork. - MegaHardforkConfig::new().with(MegaHardfork::Rex6, ForkCondition::Timestamp(7)), - MegaHardforkConfig::new().with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(7)), - // Non-timestamp conditions never contribute. - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(7)), - ]; - let rungs: Vec = MegaSpecId::ALL - .iter() - .map(|spec| MegaHardforkConfig::default().with_all_activated_through(*spec)) - .collect(); - - for hf in configs.iter().chain(rungs.iter()) { - let mut stamps = std::vec![0u64, u64::MAX]; - for fork in MegaHardfork::VARIANTS { - if let ForkCondition::Timestamp(t) = hf.mega_fork_activation(*fork) { - stamps.extend([t.saturating_sub(1), t, t.saturating_add(1)]); - } - } - for ts in stamps { - let naive = MegaHardfork::VARIANTS - .iter() - .filter(|fork| hf.mega_fork_activation(**fork).active_at_timestamp(ts)) - .map(|fork| fork.spec_id()) - .max() - .unwrap_or(MegaSpecId::EQUIVALENCE); - assert_eq!(hf.spec_id(ts), naive, "resolved spec diverges at ts={ts}"); - } - } - } - - /// Alias-fork predicates stay raw event queries: they are not recoverable from a spec - /// ordinal, so they must not be projected from the resolved spec. Testnet is the live case - /// — its resolved spec climbs the whole ladder while `MiniRex1`/`MiniRex2` are never - /// scheduled. - #[test] - fn test_alias_fork_predicates_stay_event_scoped() { - let hf = crate::testnet_hardforks(); - let ts = u64::MAX; - assert!(hf.spec_id(ts).is_enabled(MegaSpecId::REX5), "the resolved spec is high"); - assert!(!hf.is_mini_rex_1_active_at_timestamp(ts), "MiniRex1 never happened on testnet"); - assert!(!hf.is_mini_rex_2_active_at_timestamp(ts), "MiniRex2 never happened on testnet"); - - // On mainnet both events did happen, and the predicates report them. - let hf = crate::mainnet_hardforks(); - assert!(hf.is_mini_rex_1_active_at_timestamp(ts)); - assert!(hf.is_mini_rex_2_active_at_timestamp(ts)); - } - - /// Every canonical schedule and every `with_all_activated_through` rung is well-formed. - /// `with_all_activated_through(EQUIVALENCE)` is the edge worth pinning: it registers no - /// fork at all (a patch without its base would be an orphan) and resolves to - /// `EQUIVALENCE` by default. - #[test] - fn test_validate_schedule_accepts_well_formed_ladders() { - assert_eq!(crate::mainnet_hardforks().validate_schedule(), Ok(())); - assert_eq!(crate::testnet_hardforks().validate_schedule(), Ok(())); - assert_eq!(crate::all_activated_hardforks().validate_schedule(), Ok(())); - assert_eq!(MegaHardforkConfig::new().validate_schedule(), Ok(()), "no mega forks is fine"); - - for spec in MegaSpecId::ALL.iter().copied() { - let mut config = MegaHardforkConfig::default().with_all_activated_through(spec); - if spec.is_enabled(MegaSpecId::REX5) { - config = config.with_params(SequencerRegistryConfig { - rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, - }); - } - if spec.is_enabled(MegaSpecId::REX6) { - config = - config.with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }); - } - assert_eq!(config.validate_schedule(), Ok(()), "{spec:?} rung must validate"); - } - } - - /// A partial ladder is executable (position-gated setup stays additive) but not a valid - /// published schedule: `validate_schedule` is the fail-fast side of that split. - #[test] - fn test_validate_schedule_rejects_skipped_rungs() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::MiniRex, - scheduled: MegaHardfork::Rex6 - }) - ); - } - - /// A gap in the middle of the ladder is flagged too, naming the first missing rung. Unlike - /// the lowest rung (whose empty prefix makes it trivially spec-introducing), this exercises - /// the prefix classification for real: `Rex` counts as a rung only because every - /// earlier-declared fork maps strictly below it. - #[test] - fn test_validate_schedule_rejects_skipped_middle_rung() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::Rex, - scheduled: MegaHardfork::Rex2 - }) - ); - } - - /// Scheduling an alias fork without its base is the rollback of a fork that never - /// happened. Under the ascending 1:1 map this is just a skipped rung — the alias's spec - /// sits above its base's — so the general rung check catches it without a dedicated rule. - #[test] - fn test_validate_schedule_rejects_alias_without_base() { - let hf = - MegaHardforkConfig::new().with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(0)); - - assert_eq!(hf.spec_id(0), MegaSpecId::MINI_REX_1); - assert_eq!(hf.spec_id(0).behavior(), MegaSpecId::EQUIVALENCE, "execution unaffected"); - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::MiniRex, - scheduled: MegaHardfork::MiniRex1 - }) - ); - } - - #[test] - fn test_validate_schedule_rejects_unordered_forks() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(50)); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::UnorderedForks { - earlier: MegaHardfork::MiniRex, - earlier_timestamp: 100, - later: MegaHardfork::Rex, - later_timestamp: 50, - }) - ); - } - - /// A scheduled fork whose required params are missing fails at validation time instead of at - /// the first block of the fork. - #[test] - fn test_validate_schedule_requires_scheduled_fork_params() { - let rex5_no_params = - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5); - assert_eq!( - rex5_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig" - }) - ); - - let rex6_no_params = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, - }); - assert_eq!( - rex6_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config" - }) - ); - } - - #[test] - fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { - let config = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(200)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(300)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(400)) - .with(MegaHardfork::Rex7, ForkCondition::Timestamp(500)); - - assert_eq!(config.hardfork(99), None); - assert_eq!(config.hardfork(100), Some(MegaHardfork::MiniRex)); - assert_eq!(config.hardfork(200), Some(MegaHardfork::Rex4)); - assert_eq!(config.hardfork(300), Some(MegaHardfork::Rex5)); - assert_eq!(config.hardfork(400), Some(MegaHardfork::Rex6)); - assert_eq!(config.hardfork(500), Some(MegaHardfork::Rex7)); - assert_eq!(config.spec_id(99), MegaSpecId::EQUIVALENCE); - assert_eq!(config.spec_id(100), MegaSpecId::MINI_REX); - assert_eq!(config.spec_id(200), MegaSpecId::REX4); - assert_eq!(config.spec_id(300), MegaSpecId::REX5); - assert_eq!(config.spec_id(400), MegaSpecId::REX6); - assert_eq!(config.spec_id(500), MegaSpecId::REX7); - } -} diff --git a/crates/mega-evm/src/block/helpers.rs b/crates/mega-evm/src/block/helpers.rs deleted file mode 100644 index d612e3519..000000000 --- a/crates/mega-evm/src/block/helpers.rs +++ /dev/null @@ -1,390 +0,0 @@ -use alloy_consensus::{transaction::Recovered, Transaction}; -use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization, Encodable2718, Typed2718}; -use alloy_evm::{IntoTxEnv, RecoveredTx}; -use alloy_primitives::{Address, Bytes, ChainId, Selector, TxHash, TxKind, B256, U256}; -use auto_impl::auto_impl; -use delegate::delegate; - -use crate::MegaTxEnvelope; - -/// Helper trait that allows attaching extra information to a transaction. -#[auto_impl(&)] -pub trait MegaTransactionExt { - /// Get the estimated data availability size of the transaction. - /// - /// Note: the default implementation is not efficient since it does not cache the `da_size` and - /// always recalculates it. - fn estimated_da_size(&self) -> u64 - where - Self: Encodable2718, - { - op_alloy_flz::tx_estimated_size_fjord_bytes(self.encoded_2718().as_slice()) - } - - /// Get the EIP-2718 encoded size of the transaction in bytes. - fn tx_size(&self) -> u64 - where - Self: Encodable2718, - { - self.encode_2718_len() as u64 - } - - /// Get the transaction hash. - fn tx_hash(&self) -> TxHash; -} - -impl MegaTransactionExt for Recovered { - fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() - } -} - -impl MegaTransactionExt for Recovered<&MegaTxEnvelope> { - fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() - } -} - -impl MegaTransactionExt for MegaTxEnvelope { - fn tx_hash(&self) -> TxHash { - self.tx_hash() - } -} - -/// A wrapper that allows attaching additional information to a transaction. -#[derive( - Debug, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::AsRef, derive_more::AsMut, -)] -pub struct EnrichedMegaTx { - #[deref] - #[deref_mut] - #[as_ref] - #[as_mut] - inner: T, - - /// The transaction hash. - pub tx_hash: TxHash, - - /// The estimated data availability size of the transaction. - pub da_size: u64, - - /// The EIP-2718 encoded size of the transaction in bytes. - pub tx_size: u64, -} - -impl EnrichedMegaTx { - /// Create a new `WithDASize` wrapper with a known data availability size. - /// - /// `da_size`/`tx_size` are trusted as-is and not validated against `inner`'s actual - /// encoding. When this wrapper reaches [`crate::MegaBlockExecutor::run_transaction`], these - /// values are read via [`MegaTransactionExt`] and used directly for - /// `tx_da_size_limit`/`tx_encode_size_limit`/block cumulative-size enforcement, so an - /// inaccurate value can let a transaction bypass a limit it should have been rejected by. - /// Only pass values computed from `inner` itself (e.g. by a trusted mempool at insertion - /// time); prefer [`EnrichedMegaTx::new_slow`] when in doubt. - pub fn new(inner: T, tx_hash: TxHash, da_size: u64, tx_size: u64) -> Self { - Self { inner, tx_hash, da_size, tx_size } - } -} - -impl EnrichedMegaTx { - /// Create a new `WithDASize` wrapper and do the computation to estimate the data availability - /// size. - pub fn new_slow(inner: T) -> Self { - Self { - tx_hash: inner.trie_hash(), - da_size: op_alloy_flz::tx_estimated_size_fjord_bytes(inner.encoded_2718().as_slice()), - tx_size: inner.encode_2718_len() as u64, - inner, - } - } -} - -impl Encodable2718 for EnrichedMegaTx { - delegate! { - to self.inner { - fn type_flag(&self) -> Option; - fn encode_2718_len(&self) -> usize; - fn encode_2718(&self, out: &mut dyn alloy_primitives::bytes::BufMut); - } - } -} - -impl MegaTransactionExt for EnrichedMegaTx { - fn estimated_da_size(&self) -> u64 { - self.da_size - } - - fn tx_size(&self) -> u64 { - self.tx_size - } - - fn tx_hash(&self) -> TxHash { - self.tx_hash - } -} - -impl Typed2718 for EnrichedMegaTx { - delegate! { - to self.inner { - fn ty(&self) -> u8; - fn is_type(&self, ty: u8) -> bool; - fn is_legacy(&self) -> bool; - fn is_eip2930(&self) -> bool; - fn is_eip1559(&self) -> bool; - fn is_eip4844(&self) -> bool; - fn is_eip7702(&self) -> bool; - } - } -} - -impl Transaction for EnrichedMegaTx { - delegate! { - to self.inner { - fn chain_id(&self) -> Option; - fn nonce(&self) -> u64; - fn gas_limit(&self) -> u64; - fn gas_price(&self) -> Option; - fn max_fee_per_gas(&self) -> u128; - fn max_priority_fee_per_gas(&self) -> Option; - fn max_fee_per_blob_gas(&self) -> Option; - fn priority_fee_or_price(&self) -> u128; - fn effective_gas_price(&self, base_fee: Option) -> u128; - fn is_dynamic_fee(&self) -> bool; - fn kind(&self) -> TxKind; - fn is_create(&self) -> bool; - fn value(&self) -> U256; - fn input(&self) -> &Bytes; - fn access_list(&self) -> Option<&AccessList>; - fn blob_versioned_hashes(&self) -> Option<&[B256]>; - fn authorization_list(&self) -> Option<&[SignedAuthorization]>; - fn authorization_count(&self) -> Option; - fn effective_tip_per_gas(&self, base_fee: u64) -> Option; - fn to(&self) -> Option

; - fn function_selector(&self) -> Option<&Selector>; - fn blob_count(&self) -> Option; - fn blob_gas_used(&self) -> Option; - } - } -} - -impl> RecoveredTx for EnrichedMegaTx { - delegate! { - to self.inner { - fn tx(&self) -> &Tx; - fn signer(&self) -> &Address; - } - } -} - -impl> IntoTxEnv for EnrichedMegaTx { - delegate! { - to self.inner { - fn into_tx_env(self) -> Tx; - } - } -} - -impl Copy for EnrichedMegaTx {} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; - use alloy_primitives::{address, bytes::BufMut, Signature}; - use revm::context::TxEnv; - - const CALLER: Address = address!("2000000000000000000000000000000000000001"); - const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - - #[derive(Debug, Clone)] - struct MockTx { - nonce: u64, - gas_limit: u64, - value: U256, - input: Bytes, - } - - impl Typed2718 for MockTx { - fn ty(&self) -> u8 { - 0 - } - } - - impl Encodable2718 for MockTx { - fn encode_2718_len(&self) -> usize { - self.input.len() - } - - fn encode_2718(&self, out: &mut dyn BufMut) { - out.put_slice(&self.input); - } - } - - impl Transaction for MockTx { - fn chain_id(&self) -> Option { - Some(1) - } - - fn nonce(&self) -> u64 { - self.nonce - } - - fn gas_limit(&self) -> u64 { - self.gas_limit - } - - fn gas_price(&self) -> Option { - Some(9) - } - - fn max_fee_per_gas(&self) -> u128 { - 9 - } - - fn max_priority_fee_per_gas(&self) -> Option { - None - } - - fn max_fee_per_blob_gas(&self) -> Option { - None - } - - fn priority_fee_or_price(&self) -> u128 { - 9 - } - - fn effective_gas_price(&self, _base_fee: Option) -> u128 { - 9 - } - - fn is_dynamic_fee(&self) -> bool { - false - } - - fn kind(&self) -> TxKind { - TxKind::Call(CONTRACT) - } - - fn is_create(&self) -> bool { - false - } - - fn value(&self) -> U256 { - self.value - } - - fn input(&self) -> &Bytes { - &self.input - } - - fn access_list(&self) -> Option<&AccessList> { - None - } - - fn blob_versioned_hashes(&self) -> Option<&[B256]> { - None - } - - fn authorization_list(&self) -> Option<&[SignedAuthorization]> { - None - } - } - - #[derive(Debug, Clone)] - struct MockRecoveredTx { - tx: TxEnv, - signer: Address, - } - - impl RecoveredTx for MockRecoveredTx { - fn tx(&self) -> &TxEnv { - &self.tx - } - - fn signer(&self) -> &Address { - &self.signer - } - } - - impl IntoTxEnv for MockRecoveredTx { - fn into_tx_env(self) -> TxEnv { - self.tx - } - } - - fn legacy_tx() -> TxLegacy { - TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - } - } - - fn legacy_envelope() -> MegaTxEnvelope { - MegaTxEnvelope::Legacy(Signed::new_unchecked( - legacy_tx(), - Signature::test_signature(), - Default::default(), - )) - } - - #[test] - fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx.clone(), CALLER); - - assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); - assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); - assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); - assert!(MegaTransactionExt::tx_size(&tx) > 0); - } - - #[test] - fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { - let tx = MockTx { - nonce: 7, - gas_limit: 21_000, - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - }; - let expected_hash = tx.trie_hash(); - let expected_da_size = - op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()); - let expected_tx_size = tx.encode_2718_len() as u64; - - let enriched = EnrichedMegaTx::new_slow(tx); - - assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); - assert_eq!(enriched.da_size, expected_da_size); - assert_eq!(enriched.tx_size, expected_tx_size); - assert_eq!(enriched.nonce(), 7); - assert_eq!(enriched.gas_limit(), 21_000); - assert_eq!(enriched.value(), U256::from(11)); - assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); - } - - #[test] - fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { - let tx_env = TxEnv { - caller: CALLER, - gas_limit: 21_000, - kind: TxKind::Call(CONTRACT), - value: U256::from(11), - data: Bytes::from_static(&[0xaa, 0xbb]), - ..Default::default() - }; - let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; - let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); - - assert_eq!(enriched.tx(), &tx_env); - assert_eq!(*enriched.signer(), CALLER); - - let converted: TxEnv = enriched.into_tx_env(); - assert_eq!(converted, tx_env); - } -} diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs deleted file mode 100644 index bdf5fd3b8..000000000 --- a/crates/mega-evm/src/block/limit.rs +++ /dev/null @@ -1,1147 +0,0 @@ -//! Block-level resource limit enforcement for `MegaETH`. -//! -//! This module provides comprehensive limit tracking and enforcement for block-level resources -//! in the `MegaETH` EVM. It implements a two-phase checking system to optimize block construction -//! while preventing spam attacks and ensuring fair resource allocation. -//! -//! # Overview -//! -//! `MegaEVM` enforces **6 types of limits**, each with both **transaction-level** and -//! **block-level** variants: -//! -//! 1. **Gas Limit** - Traditional EVM gas consumption -//! 2. **Transaction Size Limit** - EIP-2718 encoded transaction size -//! 3. **Data Availability (DA) Size Limit** - Compressed DA size -//! 4. **Compute Gas Limit** - Actual computational cost (separate from standard gas) -//! 5. **Data Size Limit** - Total execution data generated -//! 6. **KV Update Limit** - Storage operations count -//! -//! # Two-Phase Checking Strategy -//! -//! ## Phase 1: Pre-execution Checks (Limits 1-3) -//! -//! **When**: Before transaction execution -//! **What**: Validates gas limit, transaction size, and DA size -//! **Purpose**: Fast rejection of oversized transactions without expensive execution -//! -//! ### Transaction-level Violations -//! - **Error**: [`MegaTxLimitExceededError`] -//! - **Action**: Transaction is **rejected permanently** (invalid transaction) -//! - **Reason**: Transaction exceeds individual limit (e.g., gas > `tx_gas_limit`) -//! - **Example**: A transaction declares 50M gas when limit is 30M gas -//! -//! ### Block-level Violations -//! - **Error**: [`MegaBlockLimitExceededError`] or -//! [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`] -//! - **Action**: Transaction is **skipped**, try next transaction -//! - **Reason**: Including this transaction would exceed block capacity -//! - **Example**: Block has 5M gas remaining, transaction needs 10M gas -//! -//! ## Phase 2: Post-execution Checks (Limits 4-6) -//! -//! **When**: After transaction execution, before state commitment -//! **What**: Validates compute gas, data size, and KV updates -//! **Purpose**: Enforce limits based on actual execution results -//! -//! ### Transaction-level Enforcement (During Execution) -//! - **Location**: Enforced in [`crate::evm::limit::AdditionalLimit`] -//! - **Behavior**: Transaction halts with `OutOfGas`, remaining gas preserved -//! - **Result**: Transaction fails (status=0) but is **still included in block** -//! - **Reason**: Failed transactions consume resources and must be recorded on-chain -//! -//! ### Block-level Enforcement (Before Next Transaction) -//! - The first transaction that causes the block to exceed limits is **allowed to execute and be -//! included** -//! - **Pre-execution check**: Before executing the next transaction, check if block limit has -//! already been exceeded -//! - **Action**: If limit already exceeded, reject transaction before execution -//! - **Reason**: Maximize block utilization by not wasting valid transaction execution -//! - **Example**: Block has 10MB data limit. TX1 uses 6MB (included), TX2 uses 8MB (included, total -//! 14MB exceeds limit), TX3 is rejected before execution -//! -//! # Architecture -//! -//! The module consists of two main types: -//! -//! - [`BlockLimits`]: Configuration struct defining all limit thresholds -//! - [`BlockLimiter`]: Stateful tracker that enforces limits and accumulates resource usage -//! -//! # Limit Types -//! -//! ## Pre-execution Limits (Checked before execution) -//! -//! 1. **Gas Limit** -//! - Tx-level: `tx_gas_limit` - Maximum gas per transaction -//! - Block-level: `block_gas_limit` - Total gas available in block -//! -//! 2. **Transaction Size Limit** -//! - Tx-level: `tx_encode_size_limit` - Maximum encoded transaction size -//! - Block-level: `block_txs_encode_size_limit` - Total uncompressed transaction size in block -//! -//! 3. **Data Availability Size Limit** -//! - Tx-level: `tx_da_size_limit` - Maximum DA size per transaction -//! - Block-level: `block_da_size_limit` - Total compressed DA size in block -//! - **Note**: Deposit transactions are exempt from DA size limit checks -//! -//! ## Post-execution Limits (Checked during/after execution) -//! -//! 4. **Compute Gas Limit** -//! - Tx-level: `tx_compute_gas_limit` - Maximum compute gas per transaction -//! - Block-level: `block_compute_gas_limit` - Total compute gas in block -//! -//! 5. **Data Size Limit** -//! - Tx-level: `tx_data_limit` - Maximum data per transaction -//! - Block-level: `block_txs_data_limit` - Total execution data in block -//! - Includes: tx data, logs, storage writes, account updates, contract code -//! -//! 6. **KV Update Limit** -//! - Tx-level: `tx_kv_update_limit` - Maximum storage updates per transaction -//! - Block-level: `block_kv_update_limit` - Total storage updates in block -//! - Tracks: SSTORE operations and account updates -//! -//! # Deposit Transaction Exemptions -//! -//! Deposit transactions (Optimism Layer 1 to Layer 2 deposits) receive special treatment: -//! -//! - **DA Size Limit Exemption**: Deposit transactions are exempt from both transaction-level and -//! block-level Data Availability size limit checks during pre-execution validation -//! - **Rationale**: Deposit transactions are trustless L1→L2 messages that cannot be censored. They -//! must be included in blocks regardless of their DA size to maintain bridge integrity -//! - **Tracking**: Deposit DA sizes are **not** accumulated into the block DA usage counter -//! (`post_execution_update` skips them), so `block_da_size_used` reflects non-deposit -//! transactions only -//! - **Other Limits**: Deposit transactions are still subject to all other limits (gas, tx size, -//! compute gas, data size, KV updates) -//! -//! # Block Building Workflow -//! -//! For each transaction in the mempool: -//! -//! 1. **Pre-execution check** - [`BlockLimiter::pre_execution_check`] -//! - If tx-level violation → Reject permanently -//! - If block-level violation → Skip, try next transaction -//! -//! 2. **Execute transaction** - [`crate::MegaBlockExecutor::execute_mega_transaction`] -//! - During execution, tx-level limits (4-6) are enforced in EVM -//! - If exceeded → Transaction fails but continues to step 3 -//! -//! 3. **Post-execution update** - [`BlockLimiter::post_execution_update`] -//! - Accumulates resource usage from the executed transaction into block-level counters -//! - Does not validate post-execution limits; over-limit enforcement happens before admitting -//! the next transaction in [`BlockLimiter::pre_execution_check`] -//! -//! 4. **Commit transaction** - [`crate::MegaBlockExecutor::commit_execution_outcome`] -//! - Include in block (with success or failed receipt) -//! - Update block usage counters -//! -//! # Configuration -//! -//! ## For EQUIVALENCE Specification (Optimism Isthmus Compatible) -//! -//! ```rust,ignore -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .fit_equivalence(); -//! ``` -//! -//! ## For `MINI_REX` Specification (Enhanced with Additional Limits) -//! -//! ```rust,ignore -//! use mega_evm::constants::mini_rex; -//! -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .fit_mini_rex(); // Sets all MINI_REX limits automatically -//! ``` -//! -//! Or configure manually: -//! -//! ```rust,ignore -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .with_tx_compute_gas_limit(mini_rex::TX_COMPUTE_GAS_LIMIT) -//! .with_block_txs_data_limit(mini_rex::BLOCK_DATA_LIMIT) -//! .with_block_kv_update_limit(mini_rex::BLOCK_KV_UPDATE_LIMIT); -//! ``` -//! -//! # Error Handling -//! -//! ## Transaction-level Errors (Permanent Rejection) -//! - [`MegaTxLimitExceededError::TransactionGasLimit`] - Gas limit too high -//! - [`MegaTxLimitExceededError::TransactionEncodeSizeLimit`] - Transaction too large -//! - [`MegaTxLimitExceededError::DataAvailabilitySizeLimit`] - DA size too large -//! -//! ## Block-level Errors (Skip and Try Next) -//! - [`MegaBlockLimitExceededError::ComputeGasLimit`] - Would exceed block compute gas -//! - [`MegaBlockLimitExceededError::TransactionDataLimit`] - Would exceed block data limit -//! - [`MegaBlockLimitExceededError::KVUpdateLimit`] - Would exceed block KV updates -//! - [`MegaBlockLimitExceededError::TransactionEncodeSizeLimit`] - Would exceed block tx size -//! - [`MegaBlockLimitExceededError::DataAvailabilitySizeLimit`] - Would exceed block DA size -//! - [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`] - Insufficient gas -//! -//! # See Also -//! -//! - [`crate::evm::limit`] - Transaction-level limit enforcement during execution -//! - [`crate::MegaBlockExecutor`] - Block executor that orchestrates limit checks - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::boxed::Box; - -use alloy_consensus::Transaction; -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - RecoveredTx, -}; -use alloy_primitives::TxHash; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; - -use crate::{ - BlockMegaTransactionOutcome, EvmTxRuntimeLimits, MegaBlockLimitExceededError, MegaHardfork, - MegaTransactionExt, MegaTxLimitExceededError, -}; - -/// Configuration for block-level resource limits. The block-level resource limits are associated -/// with a specific `MegaHardfork` instead of a `MegaSpecId`. In constrast, `EvmTxRuntimeLimits` is -/// associated with a `MegaSpecId`. -/// -/// This struct defines the thresholds for various resource limits that govern transaction -/// inclusion and block construction. Limits are categorized into two groups: -/// -/// 1. **Pre-execution limits**: Checked before transaction execution (gas, size, DA size) -/// 2. **Post-execution limits**: Checked after execution (data size, KV updates) -/// -/// # Default Behavior -/// -/// By default, most limits are set to `u64::MAX` (effectively unlimited) except for: -/// - `block_txs_data_limit`: Set to [`crate::constants::mini_rex::BLOCK_DATA_LIMIT`] -/// - `block_kv_update_limit`: Set to [`crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT`] -/// - `block_gas_limit`: Auto-set from the EVM block environment (cannot be manually configured) -/// -/// # Builder Pattern -/// -/// Use builder methods to configure specific limits: -/// -/// ```rust,ignore -/// let limits = BlockLimits::default() -/// .with_tx_gas_limit(15_000_000) -/// .with_block_txs_encode_size_limit(1_000_000) -/// .with_block_txs_data_limit(5_000); -/// ``` -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct BlockLimits { - /// Maximum gas limit for a single transaction. - /// - /// Transactions with gas limits exceeding this value will be rejected with - /// [`MegaTxLimitExceededError::TransactionGasLimit`]. - pub tx_gas_limit: u64, - - /// Total gas limit for the block. - /// - /// Transactions that would cause the cumulative block gas to exceed this limit are rejected - /// with [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`]. - pub block_gas_limit: u64, - - /// Maximum encoded size (in bytes) for a single transaction. - /// - /// This limit applies to the transaction's EIP-2718 encoded size. Transactions exceeding - /// this size will be rejected with [`MegaTxLimitExceededError::TransactionEncodeSizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub tx_encode_size_limit: u64, - - /// Maximum cumulative size (in bytes) of all transaction bodies in a block. - /// - /// This limit applies to the **uncompressed** transaction size. For compressed data - /// availability limits, see [`block_da_size_limit`](Self::block_da_size_limit). - /// - /// Transactions that would cause the cumulative block transaction size to exceed this - /// limit are rejected with [`MegaBlockLimitExceededError::TransactionEncodeSizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub block_txs_encode_size_limit: u64, - - /// Maximum data availability size (in bytes) for a single transaction. - /// - /// This represents the compressed size for data availability purposes. Transactions - /// exceeding this size will be rejected with - /// [`MegaTxLimitExceededError::DataAvailabilitySizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub tx_da_size_limit: u64, - - /// Maximum cumulative data availability size (in bytes) for all transactions in a block. - /// - /// This applies to the **compressed** transaction size for data availability. For - /// uncompressed transaction body limits, see - /// [`block_txs_encode_size_limit`](Self::block_txs_encode_size_limit). - /// - /// Transactions that would cause the cumulative block DA size to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::DataAvailabilitySizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub block_da_size_limit: u64, - - /// Maximum data size of a single transaction's execution outcome, i.e., encoded transaction - /// object, encoded state changes, logs, etc. The data will need to be saved and transmitted - /// over network. - pub tx_data_limit: u64, - - /// Maximum cumulative data size (in bytes) of all transactions' execution outcomes from block - /// execution. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total data produced by all transactions in the block, including - /// logs, return data, and other execution artifacts. - /// - /// Transactions that would cause the cumulative block data to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::TransactionDataLimit`], and their state - /// changes are **not committed**. - /// - /// Note: Transaction-level data limits are enforced separately in the `MegaEVM`. - /// Transactions exceeding transaction-level limits may still be included but marked - /// as failed. - pub block_txs_data_limit: u64, - - /// Maximum key-value updates for a single transaction. - pub tx_kv_update_limit: u64, - - /// Maximum cumulative key-value updates allowed in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total number of storage slot updates (SSTORE operations) across - /// all transactions in the block. - /// - /// Transactions that would cause the cumulative KV updates to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::KVUpdateLimit`], and their state changes - /// are **not committed**. - /// - /// Note: Transaction-level KV update limits are enforced separately in the `MegaEVM`. - /// Transactions exceeding transaction-level limits may still be included but marked - /// as failed. - pub block_kv_update_limit: u64, - - /// Maximum compute gas limit for a single transaction. - pub tx_compute_gas_limit: u64, - - /// Maximum cumulative compute gas limit for all transactions in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total compute gas consumed by all transactions in the block. - /// - /// Transactions that would cause the cumulative block compute gas to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::ComputeGasLimit`], and their state changes - /// are **not committed**. - pub block_compute_gas_limit: u64, - - /// Maximum state growth limit for a single transaction. - pub tx_state_growth_limit: u64, - - /// Maximum cumulative state growth limit for all transactions in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total state growth consumed by all transactions in the block. - /// - /// Transactions that would cause the cumulative block state growth to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::StateGrowthLimit`], and their state changes - /// are **not committed**. - pub block_state_growth_limit: u64, - - /// Compute gas limit when accessing block environment data. - /// - /// When a transaction accesses volatile block environment data (e.g., TIMESTAMP, COINBASE), - /// the compute gas is capped to this limit to prevent `DoS` attacks. - pub block_env_access_compute_gas_limit: u64, - - /// Compute gas limit when accessing oracle data. - /// - /// When a transaction accesses the oracle contract, the compute gas is capped to this - /// limit to prevent `DoS` attacks. - pub oracle_access_compute_gas_limit: u64, -} - -impl BlockLimits { - /// Creates a new block limits instance with no limits. - pub fn no_limits() -> Self { - Self { - tx_gas_limit: u64::MAX, - block_gas_limit: u64::MAX, - tx_encode_size_limit: u64::MAX, - block_txs_encode_size_limit: u64::MAX, - tx_da_size_limit: u64::MAX, - block_da_size_limit: u64::MAX, - tx_data_limit: u64::MAX, - block_txs_data_limit: u64::MAX, - tx_kv_update_limit: u64::MAX, - block_kv_update_limit: u64::MAX, - tx_compute_gas_limit: u64::MAX, - block_compute_gas_limit: u64::MAX, - tx_state_growth_limit: u64::MAX, - block_state_growth_limit: u64::MAX, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - /// Creates a new block limits instance from a hardfork and a block gas limit. - pub fn from_hardfork_and_block_gas_limit(hardfork: MegaHardfork, block_gas_limit: u64) -> Self { - let spec = hardfork.spec_id(); - let tx_runtime_limits = EvmTxRuntimeLimits::from_spec(spec); - let limits = Self::no_limits() - .with_tx_runtime_limits(tx_runtime_limits) - .with_block_gas_limit(block_gas_limit); - match hardfork { - MegaHardfork::Rex | - MegaHardfork::Rex1 | - MegaHardfork::Rex2 | - MegaHardfork::Rex3 | - MegaHardfork::Rex4 | - MegaHardfork::Rex5 | - MegaHardfork::Rex6 | - MegaHardfork::Rex7 => Self { - block_txs_data_limit: crate::constants::mini_rex::BLOCK_DATA_LIMIT, - block_kv_update_limit: crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - block_state_growth_limit: crate::constants::rex::BLOCK_STATE_GROWTH_LIMIT, - ..limits - }, - MegaHardfork::MiniRex | MegaHardfork::MiniRex2 => Self { - block_txs_data_limit: crate::constants::mini_rex::BLOCK_DATA_LIMIT, - block_kv_update_limit: crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - ..limits - }, - MegaHardfork::MiniRex1 => limits, - } - } -} - -impl BlockLimits { - /// Sets the related fields - pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { - self.tx_data_limit = limits.tx_data_size_limit; - self.tx_kv_update_limit = limits.tx_kv_updates_limit; - self.tx_compute_gas_limit = limits.tx_compute_gas_limit; - self.tx_state_growth_limit = limits.tx_state_growth_limit; - self.block_env_access_compute_gas_limit = limits.block_env_access_compute_gas_limit; - self.oracle_access_compute_gas_limit = limits.oracle_access_compute_gas_limit; - self - } - - /// Set a custom transaction gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction gas limit. Transactions with gas limits - /// exceeding this value will be rejected. - /// - /// # Parameters - /// - /// - `limit`: Maximum gas limit for a single transaction - /// - /// # Example - /// - /// ```rust,ignore - /// let limits = BlockLimits::default() - /// .with_tx_gas_limit(15_000_000); - /// ``` - pub fn with_tx_gas_limit(mut self, limit: u64) -> Self { - self.tx_gas_limit = limit; - self - } - - /// Set a custom block gas limit. - /// - /// **Warning**: This setting is **overridden** during block executor initialization. - /// The block gas limit is automatically set from the EVM block environment's gas limit. - /// This method exists for testing purposes only. - /// - /// # Parameters - /// - /// - `limit`: Block gas limit (will be overridden at runtime) - pub fn with_block_gas_limit(mut self, limit: u64) -> Self { - self.block_gas_limit = limit; - self - } - - /// Set a custom transaction encode size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction encode size limit. - pub fn with_tx_encode_size_limit(mut self, limit: u64) -> Self { - self.tx_encode_size_limit = limit; - self - } - - /// Set a custom block transactions encode size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block transactions encode size limit. - pub fn with_block_txs_encode_size_limit(mut self, limit: u64) -> Self { - self.block_txs_encode_size_limit = limit; - self - } - - /// Set a custom transaction data availability size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction data availability size limit. - pub fn with_tx_da_size_limit(mut self, limit: u64) -> Self { - self.tx_da_size_limit = limit; - self - } - - /// Set a custom block data availability size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified data availability size limit. - pub fn with_block_da_size_limit(mut self, limit: u64) -> Self { - self.block_da_size_limit = limit; - self - } - - /// Set a custom transaction data limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction data limit. - pub fn with_tx_data_limit(mut self, limit: u64) -> Self { - self.tx_data_limit = limit; - self - } - - /// Set a custom block transactions data limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block transactions data limit. - pub fn with_block_txs_data_limit(mut self, limit: u64) -> Self { - self.block_txs_data_limit = limit; - self - } - - /// Set a custom transaction KV update limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction KV update limit. - pub fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { - self.tx_kv_update_limit = limit; - self - } - - /// Set a custom block KV update limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified KV update limit. - pub fn with_block_kv_update_limit(mut self, limit: u64) -> Self { - self.block_kv_update_limit = limit; - self - } - - /// Set a custom transaction compute gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction compute gas limit. - pub fn with_tx_compute_gas_limit(mut self, limit: u64) -> Self { - self.tx_compute_gas_limit = limit; - self - } - - /// Set a custom block compute gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block compute gas limit. - pub fn with_block_compute_gas_limit(mut self, limit: u64) -> Self { - self.block_compute_gas_limit = limit; - self - } - - /// Set a custom transaction state growth limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction state growth limit. - pub fn with_tx_state_growth_limit(mut self, limit: u64) -> Self { - self.tx_state_growth_limit = limit; - self - } - - /// Set a custom block state growth limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block state growth limit. - pub fn with_block_state_growth_limit(mut self, limit: u64) -> Self { - self.block_state_growth_limit = limit; - self - } - - /// Set a custom compute gas limit when accessing block environment data. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block environment access compute gas limit. - pub fn with_block_env_access_compute_gas_limit(mut self, limit: u64) -> Self { - self.block_env_access_compute_gas_limit = limit; - self - } - - /// Set a custom compute gas limit when accessing oracle data. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified oracle access compute gas limit. - pub fn with_oracle_access_compute_gas_limit(mut self, limit: u64) -> Self { - self.oracle_access_compute_gas_limit = limit; - self - } - - /// Create a new block limiter from these limits. - /// - /// This converts the limit configuration into a stateful [`BlockLimiter`] that tracks - /// resource usage and enforces the configured limits throughout block execution. - /// - /// # Returns - /// - /// A new [`BlockLimiter`] initialized with zero usage for all tracked resources. - /// - /// # Example - /// - /// ```rust,ignore - /// let limits = BlockLimits::default().with_block_txs_data_limit(5_000); - /// let limiter = limits.to_block_limiter(); - /// ``` - pub fn to_block_limiter(self) -> BlockLimiter { - BlockLimiter { - limits: self, - block_gas_used: 0, - block_data_used: 0, - block_kv_updates_used: 0, - block_tx_size_used: 0, - block_da_size_used: 0, - block_compute_gas_used: 0, - block_state_growth_used: 0, - } - } - - /// Convert the block limits to the runtime limits for a single transaction. - pub fn to_evm_tx_runtime_limits(&self) -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: self.tx_data_limit, - tx_kv_updates_limit: self.tx_kv_update_limit, - tx_compute_gas_limit: self.tx_compute_gas_limit, - tx_state_growth_limit: self.tx_state_growth_limit, - block_env_access_compute_gas_limit: self.block_env_access_compute_gas_limit, - oracle_access_compute_gas_limit: self.oracle_access_compute_gas_limit, - } - } -} - -/// Stateful block resource limiter that tracks usage and enforces limits. -/// -/// This struct maintains cumulative resource usage throughout block execution and validates -/// that each transaction stays within both transaction-level and block-level limits. It -/// provides a two-phase checking mechanism: -/// -/// 1. **Pre-execution**: Validates limits that can be determined before execution (gas limit, -/// transaction size, DA size) -/// 2. **Post-execution**: Validates limits based on execution results (data size, KV updates) and -/// updates the usage accumulators -/// -/// # Resource Tracking -/// -/// The limiter tracks five cumulative metrics: -/// - Gas consumed by all transactions -/// - Total transaction body size -/// - Total data availability size -/// - Total execution data generated -/// - Total key-value storage updates -/// -/// # Usage Pattern -/// -/// ```rust,ignore -/// let mut limiter = BlockLimits::default().to_block_limiter(); -/// -/// for tx in transactions { -/// // Pre-execution check -/// limiter.pre_execution_check(tx.hash(), tx.gas_limit(), tx.size(), tx.da_size(), is_deposit)?; -/// -/// let outcome = execute_transaction(tx); -/// -/// // Post-execution update -/// limiter.post_execution_update(&outcome)?; -/// } -/// ``` -#[derive(Debug, Clone)] -pub struct BlockLimiter { - /// The configured resource limits. - pub limits: BlockLimits, - - /// Cumulative gas consumed by all committed transactions in the block. - pub block_gas_used: u64, - - /// Cumulative encoded size of all transaction bodies in the block (uncompressed). - pub block_tx_size_used: u64, - - /// Cumulative data availability size for all transactions in the block (compressed). - pub block_da_size_used: u64, - - /// Cumulative execution data generated by all transactions in the block. - /// - /// This includes the encoded transaction object, logs, return data, and other execution - /// artifacts. - pub block_data_used: u64, - - /// Cumulative key-value storage updates performed by all transactions in the block. - /// - /// This tracks the total number of SSTORE operations across all transactions. - pub block_kv_updates_used: u64, - - /// Cumulative compute gas consumed by all transactions in the block. - pub block_compute_gas_used: u64, - - /// Cumulative state growth consumed by all transactions in the block. - pub block_state_growth_used: u64, -} - -impl BlockLimiter { - /// Create a new block limiter with the specified limits. - /// - /// Initializes a limiter with all resource usage counters set to zero. - /// - /// # Parameters - /// - /// - `limits`: The resource limit configuration - /// - /// # Returns - /// - /// A new limiter ready to track resource usage - pub fn new(limits: BlockLimits) -> Self { - Self { - limits, - block_gas_used: 0, - block_data_used: 0, - block_kv_updates_used: 0, - block_tx_size_used: 0, - block_da_size_used: 0, - block_compute_gas_used: 0, - block_state_growth_used: 0, - } - } - - /// Validate transaction against pre-execution limits. - /// - /// This method validates that a transaction can be included in the block by checking - /// limits that are known before execution: - /// - Single transaction gas limit - /// - Remaining block gas capacity - /// - Single transaction size limit - /// - Remaining block transaction size capacity - /// - Single transaction DA size limit - /// - Remaining block DA size capacity - /// - /// **Important**: This method does **not** modify any state. It only performs validation. - /// Call [`post_execution_update`](Self::post_execution_update) after execution to update - /// usage counters. - /// - /// # Parameters - /// - /// - `tx_hash`: Transaction hash for error reporting - /// - `gas_limit`: Transaction's declared gas limit - /// - `tx_size`: Transaction's encoded size in bytes (EIP-2718 encoding) - /// - `da_size`: Transaction's compressed data availability size in bytes - /// - `is_deposit`: Whether the transaction is an L1-to-L2 deposit (exempt from DA size limits) - /// - /// # Returns - /// - /// - `Ok(())`: Transaction passes all pre-execution checks - /// - `Err(BlockExecutionError)`: Transaction violates one or more limits - /// - /// # Errors - /// - /// Returns [`BlockExecutionError::Validation`] containing either: - /// - [`MegaTxLimitExceededError`]: Transaction exceeds its own limits (invalid transaction) - /// - [`MegaBlockLimitExceededError`]: Transaction would exceed block capacity - /// - [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`][] - Insufficient - /// remaining gas in block - /// - /// # Example - /// - /// ```rust,ignore - /// let mut limiter = BlockLimits::default().to_block_limiter(); - /// - /// limiter.pre_execution_check( - /// tx.hash(), - /// tx.gas_limit(), - /// tx.encode_2718_len() as u64, - /// tx.estimated_da_size(), - /// tx.is_deposit(), - /// )?; - /// ``` - pub fn pre_execution_check( - &self, - tx_hash: TxHash, - gas_limit: u64, - tx_size: u64, - da_size: u64, - is_deposit: bool, - ) -> Result<(), BlockExecutionError> { - // Check single transaction gas limit - if gas_limit > self.limits.tx_gas_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::TransactionGasLimit { - tx_gas_limit: gas_limit, - limit: self.limits.tx_gas_limit, - }), - })); - } - - // Check block gas limit - if self.block_gas_used.saturating_add(gas_limit) > self.limits.block_gas_limit { - return Err(BlockExecutionError::Validation( - BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { - transaction_gas_limit: gas_limit, - block_available_gas: self - .limits - .block_gas_limit - .saturating_sub(self.block_gas_used), - }, - )); - } - - // Check single transaction size limit - if tx_size > self.limits.tx_encode_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::TransactionEncodeSizeLimit { - tx_size, - limit: self.limits.tx_encode_size_limit, - }), - })); - } - - // Check block transaction size limit - if tx_size.saturating_add(self.block_tx_size_used) > self.limits.block_txs_encode_size_limit - { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::TransactionEncodeSizeLimit { - block_used: self.block_tx_size_used, - tx_used: tx_size, - limit: self.limits.block_txs_encode_size_limit, - }), - })); - } - - // Deposit transactions are exempt from data availability size limits - if !is_deposit { - // Check single transaction data availability size limit - if da_size > self.limits.tx_da_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::DataAvailabilitySizeLimit { - da_size, - limit: self.limits.tx_da_size_limit, - }), - })); - } - - // Check block data availability size limit - if da_size.saturating_add(self.block_da_size_used) > self.limits.block_da_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: self.block_da_size_used, - tx_used: da_size, - limit: self.limits.block_da_size_limit, - }), - })); - } - } - - // Check block-level data limit - if self.block_data_used >= self.limits.block_txs_data_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::TransactionDataLimit { - block_used: self.block_data_used, - limit: self.limits.block_txs_data_limit, - }), - })); - } - - // Check block-level kv update limit - if self.block_kv_updates_used >= self.limits.block_kv_update_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::KVUpdateLimit { - block_used: self.block_kv_updates_used, - limit: self.limits.block_kv_update_limit, - }), - })); - } - - // Check block-level compute gas limit - if self.block_compute_gas_used >= self.limits.block_compute_gas_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::ComputeGasLimit { - block_used: self.block_compute_gas_used, - limit: self.limits.block_compute_gas_limit, - }), - })); - } - - // Check block-level state growth limit - if self.block_state_growth_used >= self.limits.block_state_growth_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::StateGrowthLimit { - block_used: self.block_state_growth_used, - limit: self.limits.block_state_growth_limit, - }), - })); - } - - Ok(()) - } - - /// Update usage counters after transaction execution. - /// - /// This method is called **after** transaction execution to accumulate the executed - /// transaction's resource usage into the limiter's block-level counters. It does **not** - /// validate post-execution limits — over-limit enforcement happens in - /// [`pre_execution_check`](Self::pre_execution_check) before admitting the next transaction. - /// The transaction may cause the block to exceed limits, which is intentional to maximize - /// block utilization. - /// - /// The return type remains `Result` to leave room for future fallible post-execution logic; - /// the current implementation always returns `Ok(())`. - /// - /// # Parameters - /// - /// - `outcome`: The transaction execution outcome containing resource usage information - /// - /// # Returns - /// - /// - `Ok(())`: Usage counters updated successfully - /// - /// # State Modification - /// - /// This method updates all cumulative usage counters: - /// - `block_gas_used += gas_used` - /// - `block_tx_size_used += tx_size_used` - /// - `block_da_size_used += da_size_used` (only for non-deposit transactions) - /// - `block_data_used += data_size_used` - /// - `block_kv_updates_used += kv_updates_used` - /// - `block_compute_gas_used += compute_gas_used` - /// - `block_state_growth_used += state_growth_used` - /// - /// **Note**: The block may exceed limits after this update. This is intentional - the first - /// transaction that causes the block to exceed is allowed to be included. - /// - /// # Example - /// - /// ```rust,ignore - /// let outcome = executor.execute_mega_transaction(tx)?; - /// - /// // Accumulates usage; may cause block-level counters to exceed limits. - /// limiter.post_execution_update(&outcome)?; - /// - /// // Commit the transaction state - /// executor.commit_execution_outcome(outcome)?; - /// ``` - pub fn post_execution_update( - &mut self, - outcome: &BlockMegaTransactionOutcome>, - ) -> Result<(), BlockExecutionError> { - let is_deposit = outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE; - - self.post_execution_update_raw( - outcome.result.gas_used(), - outcome.tx_size, - outcome.da_size, - outcome.data_size, - outcome.kv_updates, - outcome.compute_gas_used, - outcome.state_growth_used, - is_deposit, - ); - - Ok(()) - } - - /// Update usage counters after transaction execution using raw values. - /// - /// This mirrors [`post_execution_update`](Self::post_execution_update) but takes precomputed - /// resource usage values instead of a full execution outcome. - #[allow(clippy::too_many_arguments)] - pub fn post_execution_update_raw( - &mut self, - gas_used: u64, - tx_size: u64, - da_size: u64, - tx_data: u64, - kv_updates: u64, - compute_gas_used: u64, - state_growth_used: u64, - is_deposit: bool, - ) { - // Block gas limit. No need to check here since it's checked before transaction execution. - self.block_gas_used = self.block_gas_used.saturating_add(gas_used); - - // Block tx size limit, no need to check here since it's checked before transaction - // execution. - self.block_tx_size_used = self.block_tx_size_used.saturating_add(tx_size); - - // Block da size limit, no need to check here since it's checked before transaction - // execution. Only appliable for non-deposit transactions. - if !is_deposit { - self.block_da_size_used = self.block_da_size_used.saturating_add(da_size); - } - - // Block data limit, no need to check here since we allow the last transaction to exceed the - // limit. - self.block_data_used = self.block_data_used.saturating_add(tx_data); - - // Block kv updates limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_kv_updates_used = self.block_kv_updates_used.saturating_add(kv_updates); - - // Block compute gas limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_compute_gas_used = self.block_compute_gas_used.saturating_add(compute_gas_used); - - // Block state growth limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_state_growth_used = - self.block_state_growth_used.saturating_add(state_growth_used); - } - - /// Returns true if any block-level limit has been reached or exceeded. - pub fn is_block_limit_reached(&self) -> bool { - self.block_gas_used >= self.limits.block_gas_limit || - self.block_tx_size_used >= self.limits.block_txs_encode_size_limit || - self.block_da_size_used >= self.limits.block_da_size_limit || - self.block_data_used >= self.limits.block_txs_data_limit || - self.block_kv_updates_used >= self.limits.block_kv_update_limit || - self.block_compute_gas_used >= self.limits.block_compute_gas_limit || - self.block_state_growth_used >= self.limits.block_state_growth_limit - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::B256; - - /// Alias forks must configure exactly their behavior target's block limits: the - /// hand-written arm grouping in `from_hardfork_and_block_gas_limit` is reconciled with - /// `behavior()`, mirroring the instruction-table/precompile/runtime-limit reconciliation - /// tests. Driven off `VARIANTS` and `is_alias`, so a future alias fork joins automatically. - #[test] - fn test_alias_forks_use_their_behavior_targets_block_limits() { - const GAS: u64 = 1_000_000; - let alias_forks = - MegaHardfork::VARIANTS.iter().copied().filter(|fork| fork.spec_id().is_alias()); - let mut seen = 0; - for fork in alias_forks { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(fork, GAS); - let target = fork.spec_id().behavior(); - let expected = match MegaHardfork::VARIANTS - .iter() - .copied() - .find(|base| base.spec_id() as u8 == target as u8) - { - Some(base_fork) => BlockLimits::from_hardfork_and_block_gas_limit(base_fork, GAS), - // The target predates every fork (EQUIVALENCE): no block-level limits apply. - None => BlockLimits::no_limits() - .with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(fork.spec_id())) - .with_block_gas_limit(GAS), - }; - assert_eq!(limits, expected, "{fork:?} must mirror its behavior target {target:?}"); - seen += 1; - } - assert_eq!(seen, 2, "MiniRex1 and MiniRex2 are the alias forks under reconciliation"); - } - - fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = block_gas_limit; - limits.tx_gas_limit = u64::MAX; - limits - } - - fn limits_with_block_tx_size(block_txs_encode_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_txs_encode_size_limit = block_txs_encode_size_limit; - limits - } - - fn limits_with_block_da_size(block_da_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_da_size_limit = block_da_size_limit; - limits - } - - #[test] - fn test_pre_execution_check_block_gas_addition_saturates() { - // Block has very high accumulated usage and a transaction with a near-`u64::MAX` - // gas limit; unchecked addition would wrap and accidentally pass the limit check. - let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); - limiter.block_gas_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); - assert!(result.is_err(), "saturating_add must keep the rejection in place"); - } - - #[test] - fn test_pre_execution_check_block_tx_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_tx_size(1_000_000)); - limiter.block_tx_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); - assert!(result.is_err()); - } - - #[test] - fn test_pre_execution_check_block_da_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_da_size(1_000_000)); - limiter.block_da_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); - assert!(result.is_err()); - } - - #[test] - fn test_post_execution_update_raw_saturates_all_counters() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_gas_used = u64::MAX - 1; - limiter.block_tx_size_used = u64::MAX - 1; - limiter.block_da_size_used = u64::MAX - 1; - limiter.block_data_used = u64::MAX - 1; - limiter.block_kv_updates_used = u64::MAX - 1; - limiter.block_compute_gas_used = u64::MAX - 1; - limiter.block_state_growth_used = u64::MAX - 1; - - limiter.post_execution_update_raw( - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - false, - ); - - assert_eq!(limiter.block_gas_used, u64::MAX); - assert_eq!(limiter.block_tx_size_used, u64::MAX); - assert_eq!(limiter.block_da_size_used, u64::MAX); - assert_eq!(limiter.block_data_used, u64::MAX); - assert_eq!(limiter.block_kv_updates_used, u64::MAX); - assert_eq!(limiter.block_compute_gas_used, u64::MAX); - assert_eq!(limiter.block_state_growth_used, u64::MAX); - } - - #[test] - fn test_post_execution_update_raw_skips_da_for_deposits() { - // Deposit transactions should not advance `block_da_size_used`, even when the value - // would otherwise saturate. - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_da_size_used = 100; - - limiter.post_execution_update_raw(0, 0, u64::MAX, 0, 0, 0, 0, true); - - assert_eq!(limiter.block_da_size_used, 100); - } -} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs deleted file mode 100644 index 0340cd82c..000000000 --- a/crates/mega-evm/src/block/mod.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Block execution abstraction for the `MegaETH` EVM. -//! -//! This module provides comprehensive block execution functionality specifically tailored for -//! the `MegaETH` chain, built on top of the Optimism EVM (`op-revm`) with MegaETH-specific -//! customizations and optimizations. -//! -//! # Architecture -//! -//! The block execution system consists of five main components: -//! -//! 1. **[`MegaBlockExecutorFactory`]**: Factory for creating block executors with `MegaETH` -//! specifications -//! 2. **[`MegaBlockExecutor`]**: The actual executor that processes transactions within a block -//! 3. **[`BlockLimits`]**: Configuration for block-level resource limits -//! 4. **[`BlockLimiter`]**: Stateful tracker that enforces limits and accumulates resource usage -//! 5. **[`MegaBlockExecutionCtx`]**: Context for block execution including parent hash and limits -//! -//! # Pre-Block State Changes and Witness Recording -//! -//! [`MegaBlockExecutor::pre_execution_changes`] collects `Option` outcomes from each -//! pre-block helper, and [`MegaBlockExecutor::commit_system_call_outcomes`] walks them calling -//! `system_caller.on_state(source, &state)` **before** `db.commit(state)` for every entry. The -//! `on_state` hook feeds the stateless witness generator with the complete read/write set, so -//! helpers must return all accounts and slots they touched — including pure reads on -//! idempotent no-change paths. See `crates/mega-evm/src/system/AGENTS.md` → -//! `PRE-BLOCK STATE CHANGE CONTRACT` for the helper-side contract. -//! -//! # Resource Limit Enforcement -//! -//! `MegaETH` implements a comprehensive resource limiting system to prevent `DoS` attacks and -//! ensure fair resource allocation. The system enforces limits at two levels: -//! -//! ## Transaction-level Limits -//! -//! Individual transactions are validated against: -//! - Gas limit per transaction -//! - Transaction body size -//! - Data availability (DA) size -//! -//! ## Block-level Limits -//! -//! Cumulative resource usage across all transactions in a block is validated against: -//! - Total gas consumption -//! - Total transaction size -//! - Total DA size -//! - Total execution data (logs, return data) -//! - Total key-value storage updates -//! -//! Limits are checked in two phases: -//! - **Pre-execution**: Gas, transaction size, and DA size (fast, no execution needed) -//! - **Post-execution**: Data size and KV updates (after execution, before commit) -//! -//! # EVM Specifications -//! -//! `MegaETH` supports two EVM specifications: -//! -//! - **`EQUIVALENCE`**: Maintains equivalence with Optimism Isthmus EVM (default) -//! - **`MINI_REX`**: Enhanced version with additional resource limits and modified gas costs -//! -//! # Usage Example -//! -//! ```rust,ignore -//! use mega_evm::{MegaBlockExecutorFactory, MegaBlockExecutionCtx, BlockLimits}; -//! -//! // Configure block limits -//! let limits = BlockLimits::default() -//! .with_block_txs_encode_size_limit(1_000_000) -//! .with_block_txs_data_limit(10_000); -//! -//! // Create execution context -//! let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_root, extra_data) -//! .with_block_limits(limits); -//! -//! // Create executor factory -//! let factory = MegaBlockExecutorFactory::new(spec, evm_factory, receipt_builder); -//! -//! // Create and use executor -//! let mut executor = factory.create_executor_with_config(&mut state, ctx, evm_config); -//! executor.apply_pre_execution_changes()?; -//! executor.execute_transaction(tx)?; -//! let (evm, result) = executor.finish()?; -//! ``` -//! -//! # Performance Considerations -//! -//! The `MegaETH` block executor is optimized for high-performance blockchain operations: -//! -//! - Efficient delegation to the underlying Optimism EVM implementation -//! - Minimal overhead for MegaETH-specific features -//! - Two-phase limit checking minimizes unnecessary execution -//! - Support for parallel execution through access tracking -//! - Optimized gas calculations for modified opcodes - -mod chain; -mod eips; -mod executor; -mod factory; -mod hardfork; -mod helpers; -mod limit; -mod result; - -pub use chain::*; -pub use executor::*; -pub use factory::*; -pub use hardfork::*; -pub use helpers::*; -pub use limit::*; -pub use result::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs deleted file mode 100644 index beb5ee2c0..000000000 --- a/crates/mega-evm/src/block/result.rs +++ /dev/null @@ -1,240 +0,0 @@ -use alloy_evm::InvalidTxError; -use revm::state::AccountInfo; - -use crate::MegaTransactionOutcome; - -/// The execution outcome of a transaction in `MegaETH`. -/// -/// This struct contains additional information about the transaction execution on top of the -/// standard EVM's execution result and state. -#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)] -pub struct BlockMegaTransactionOutcome { - /// The transaction. - pub tx: T, - /// The transaction size in bytes. - pub tx_size: u64, - /// The transaction data availability size in bytes. - pub da_size: u64, - /// The depositor account info. - pub depositor: Option, - /// The transaction execution outcome. - #[deref] - #[deref_mut] - pub inner: MegaTransactionOutcome, -} - -/// Error type for additional reasons of an invalid transaction. If one transaction is invalid, it -/// will never be able to be included in a block and should be discarded. -#[derive(Debug, Clone, thiserror::Error)] -pub enum MegaTxLimitExceededError { - /// Transaction gas limit exceeded. - #[error("Transaction gas limit exceeded: tx_gas_limit={tx_gas_limit} > limit={limit}")] - TransactionGasLimit { - /// Transaction gas limit used by current transaction - tx_gas_limit: u64, - /// Transaction gas limit limit - limit: u64, - }, - /// Transaction encode size limit exceeded. - #[error("Transaction encode size limit exceeded: tx_size={tx_size} > limit={limit}")] - TransactionEncodeSizeLimit { - /// Transaction encode size used by current transaction - tx_size: u64, - /// Transaction encode size limit - limit: u64, - }, - - /// Transaction data availability size limit exceeded. - #[error( - "Transaction data availability size limit exceeded: da_size={da_size} > limit={limit}" - )] - DataAvailabilitySizeLimit { - /// Data availability size used by current transaction - da_size: u64, - /// Data availability size limit - limit: u64, - }, -} - -impl MegaTxLimitExceededError { - /// The amount of the resource used by the current transaction. - pub fn usage(&self) -> u64 { - match self { - Self::TransactionGasLimit { tx_gas_limit, .. } => *tx_gas_limit, - Self::TransactionEncodeSizeLimit { tx_size, .. } => *tx_size, - Self::DataAvailabilitySizeLimit { da_size, .. } => *da_size, - } - } - - /// The limit of the resource. - pub fn limit(&self) -> u64 { - match self { - Self::TransactionGasLimit { limit, .. } | - Self::TransactionEncodeSizeLimit { limit, .. } | - Self::DataAvailabilitySizeLimit { limit, .. } => *limit, - } - } -} - -impl InvalidTxError for MegaTxLimitExceededError { - fn is_nonce_too_low(&self) -> bool { - false - } -} - -/// Error type for block-level limit exceeded. These errors are thrown when the block has already -/// exceeded its limit (from a previous transaction) and no more transactions can be added. -#[derive(Debug, Clone, thiserror::Error)] -pub enum MegaBlockLimitExceededError { - /// Block transactions data limit reached. - #[error("Block transactions data limit reached: block_used={block_used} >= limit={limit}")] - TransactionDataLimit { - /// Transaction data used by block so far - block_used: u64, - /// Block transactions data limit - limit: u64, - }, - - /// Block KV update limit reached. - #[error("Block KV update limit reached: block_used={block_used} >= limit={limit}")] - KVUpdateLimit { - /// KV updates used by block so far - block_used: u64, - /// Block KV update limit - limit: u64, - }, - - /// Block compute gas limit reached. - #[error("Block compute gas limit reached: block_used={block_used} >= limit={limit}")] - ComputeGasLimit { - /// Compute gas used by block so far - block_used: u64, - /// Block compute gas limit - limit: u64, - }, - - /// Block transactions encode size limit exceeded. - #[error("Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}")] - TransactionEncodeSizeLimit { - /// Transaction encode size used by block so far - block_used: u64, - /// Transaction encode size used by current transaction - tx_used: u64, - /// Block transactions encode size limit - limit: u64, - }, - - /// Block data availability size limit exceeded. - #[error("Block data availability size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}")] - DataAvailabilitySizeLimit { - /// Data availability size used by block so far - block_used: u64, - /// Data availability size used by current transaction - tx_used: u64, - /// Block data availability size limit - limit: u64, - }, - - /// Block state growth limit reached. - #[error("Block state growth limit reached: block_used={block_used} >= limit={limit}")] - StateGrowthLimit { - /// State growth used by block so far - block_used: u64, - /// Block state growth limit - limit: u64, - }, -} - -impl MegaBlockLimitExceededError { - /// The total amount of the resource used by the block so far. - pub fn block_used(&self) -> u64 { - match self { - Self::TransactionDataLimit { block_used, .. } | - Self::KVUpdateLimit { block_used, .. } | - Self::ComputeGasLimit { block_used, .. } | - Self::TransactionEncodeSizeLimit { block_used, .. } | - Self::DataAvailabilitySizeLimit { block_used, .. } | - Self::StateGrowthLimit { block_used, .. } => *block_used, - } - } - - /// The limit of the resource. - pub fn limit(&self) -> u64 { - match self { - Self::TransactionDataLimit { limit, .. } | - Self::KVUpdateLimit { limit, .. } | - Self::ComputeGasLimit { limit, .. } | - Self::TransactionEncodeSizeLimit { limit, .. } | - Self::DataAvailabilitySizeLimit { limit, .. } | - Self::StateGrowthLimit { limit, .. } => *limit, - } - } -} - -impl InvalidTxError for MegaBlockLimitExceededError { - fn is_nonce_too_low(&self) -> bool { - false - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_transaction_limit_error_reports_usage_and_limit() { - let cases = [ - (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), - ( - MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, - 101, - 100, - ), - ( - MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, - 11, - 10, - ), - ]; - - for (error, expected_usage, expected_limit) in cases { - assert_eq!(error.usage(), expected_usage); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } - } - - #[test] - fn test_block_limit_error_reports_block_usage_and_limit() { - let cases = [ - (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), - (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 2, limit: 11 }, 2, 11), - (MegaBlockLimitExceededError::ComputeGasLimit { block_used: 3, limit: 12 }, 3, 12), - ( - MegaBlockLimitExceededError::TransactionEncodeSizeLimit { - block_used: 4, - tx_used: 1, - limit: 13, - }, - 4, - 13, - ), - ( - MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: 5, - tx_used: 1, - limit: 14, - }, - 5, - 14, - ), - (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 6, limit: 15 }, 6, 15), - ]; - - for (error, expected_block_used, expected_limit) in cases { - assert_eq!(error.block_used(), expected_block_used); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } - } -} diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs deleted file mode 100644 index 8afafdfd6..000000000 --- a/crates/mega-evm/src/constants.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! Constants for the `MegaETH` EVM. -//! -//! It groups the constants for different EVM specs as sub-modules. - -/// Constants for the `EQUIVALENCE` spec. -pub mod equivalence { - use revm::interpreter::gas; - - /// Constants inherited from `revm`. - pub use gas::{ - BASE, BLOCKHASH, CALLVALUE, CALL_STIPEND, CODEDEPOSIT, COLD_ACCOUNT_ACCESS_COST, - COLD_SLOAD_COST, CREATE, KECCAK256WORD, LOG, LOGDATA, LOGTOPIC, NEWACCOUNT, SSTORE_RESET, - SSTORE_SET, STANDARD_TOKEN_COST, TOTAL_COST_FLOOR_PER_TOKEN, VERYLOW, WARM_SSTORE_RESET, - WARM_STORAGE_READ_COST, - }; - pub use revm::primitives::STACK_LIMIT; -} - -/// Constants for the `MINI_REX` spec. -pub mod mini_rex { - /// The maximum contract size for the `MINI_REX` spec. - pub const MAX_CONTRACT_SIZE: usize = 512 * 1024; - /// The additional initcode size for the `MINI_REX` spec. The initcode size is limited to - /// `MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE`. - pub const ADDITIONAL_INITCODE_SIZE: usize = 24 * 1024; - /// The maximum initcode size for the `MINI_REX` spec. - pub const MAX_INITCODE_SIZE: usize = MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE; - - /// The maximum compute gas allowed per transaction for the `MINI_REX` spec. - pub const TX_COMPUTE_GAS_LIMIT: u64 = 1_000_000_000; - - /// The base storage gas cost for setting a storage slot to a non-zero value for the `MINI_REX` - /// spec. Actual cost is dynamically scaled by SALT bucket capacity: `SSTORE_SET_GAS × - /// (bucket_capacity / MIN_BUCKET_SIZE)`. - pub const SSTORE_SET_STORAGE_GAS: u64 = 2_000_000; - /// The base storage gas cost for creating a new account for the `MINI_REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `NEW_ACCOUNT_GAS × - /// (bucket_capacity / MIN_BUCKET_SIZE)`. Applied when transaction targets new account, CALL - /// with transfer to empty account, or CREATE operations. - pub const NEW_ACCOUNT_STORAGE_GAS: u64 = 2_000_000; - /// Storage gas cost per byte for code deposit during contract creation in `MINI_REX` spec. - pub const CODEDEPOSIT_STORAGE_GAS: u64 = 10_000; - /// The storage gas cost for `LOGDATA` for the `MINI_REX` spec, i.e., gas cost per byte for log - /// data. - pub const LOG_DATA_STORAGE_GAS: u64 = super::equivalence::LOGDATA * 10; - /// The storage gas cost for `LOGTOPIC` for the `MINI_REX` spec, i.e., gas cost per topic for - /// log. - pub const LOG_TOPIC_STORAGE_GAS: u64 = super::equivalence::LOGTOPIC * 10; - /// The additional gas cost for `CALLDATA` for the `MINI_REX` spec, i.e., gas cost per token - /// (one byte) for call data. This is charged on top of the calldata cost of standard EVM. - pub const CALLDATA_STANDARD_TOKEN_STORAGE_GAS: u64 = - super::equivalence::STANDARD_TOKEN_COST * 10; - /// The additional gas cost for EIP-7623 floor gas cost, i.e., gas cost per token (one byte) - /// for call data. This is charged on top of the floor cost of standard EVM. - pub const CALLDATA_STANDARD_TOKEN_STORAGE_FLOOR_GAS: u64 = - super::equivalence::TOTAL_COST_FLOOR_PER_TOKEN * 10; - - /// The maximum amount of data allowed to generate from a block for the `MINI_REX` spec. - pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; // 12.5 MB - /// The maximum data size allowed per transaction for the `MINI_REX` spec. - /// Transactions exceeding this limit halt with `OutOfGas`, preserving remaining gas. - pub const TX_DATA_LIMIT: u64 = BLOCK_DATA_LIMIT * 25 / 100; // 25% of the block limit - /// The maximum amount of key-value updates allowed to generate from a block for the `MINI_REX` - /// spec. - pub const BLOCK_KV_UPDATE_LIMIT: u64 = 500_000; - /// The maximum amount of key-value updates allowed to generate from a transaction for the - /// `MINI_REX` spec. - pub const TX_KV_UPDATE_LIMIT: u64 = BLOCK_KV_UPDATE_LIMIT * 25 / 100; // 25% of the block limit - - /// Gas limit after block environment or beneficiary data access. - /// When block environment data or beneficiary account data is accessed, the compute gas - /// is limited to force the transaction to complete quickly and prevent `DoS` attacks. - /// - /// - **Pre-REX4**: This is an **absolute** cap on the transaction's total compute gas. - /// - **REX4+**: This is a **relative** cap — it limits post-access compute gas. The effective - /// limit becomes `current_usage + BLOCK_ENV_ACCESS_COMPUTE_GAS` at the point of access. - pub const BLOCK_ENV_ACCESS_COMPUTE_GAS: u64 = 20_000_000; - - /// Gas limit after oracle contract access. - /// When oracle contract is accessed, the compute gas is limited to force the transaction - /// to complete quickly and prevent `DoS` attacks. - /// - /// - **Pre-REX4**: This is an **absolute** cap on the transaction's total compute gas. - /// - **REX4+**: This is a **relative** cap — it limits post-access compute gas. The effective - /// limit becomes `current_usage + ORACLE_ACCESS_COMPUTE_GAS` at the point of access. - /// - /// Note: If block environment was accessed first (20M compute gas limit), then oracle is - /// accessed, the compute gas will be further restricted to this lower limit (1M compute - /// gas). - pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 1_000_000; -} - -/// Constants for the `REX2` spec. -pub mod rex2 { - /// Fixed overhead gas for the keylessDeploy operation. - /// This covers the cost of RLP decoding, signature recovery, and state filtering. - pub const KEYLESS_DEPLOY_OVERHEAD_GAS: u64 = 100_000; -} - -/// Constants for the `REX3` spec. -pub mod rex3 { - /// Gas limit after oracle contract access for the `REX3` spec. - /// Increased from 1M (used in `MINI_REX` through `REX2`) to 20M, giving oracle-accessing - /// transactions more room for post-oracle computation. - pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; -} - -/// Constants for the `REX4` spec. -pub mod rex4 { - /// Numerator of the fraction of parent's remaining resource budget forwarded to a child - /// frame. Applies to all four resource dimensions (data size, KV updates, compute gas, - /// state growth). - /// Child budget = `parent_remaining` * NUMERATOR / DENOMINATOR. - pub const FRAME_LIMIT_NUMERATOR: u64 = 98; - /// Denominator of the per-frame resource budget forwarding fraction. - pub const FRAME_LIMIT_DENOMINATOR: u64 = 100; - - /// Additional call stipend for storage operations in CALL/CALLCODE with value transfer. - /// - /// `MegaETH`'s 10x storage gas multiplier on LOG opcodes causes even a simple `LOG1` to cost - /// 4,500 gas (750 compute + 3,750 storage), exceeding the EVM's `CALL_STIPEND` of 2,300. - /// This breaks `transfer()` / `send()` to contracts that emit events in `receive()`. - /// - /// When an internal CALL or CALLCODE transfers value (value > 0), the callee receives this - /// extra gas on top of the standard `CALL_STIPEND`. - /// The callee's compute gas limit remains at the original level (`forwarded_gas + - /// CALL_STIPEND`), so the extra gas can only be consumed by storage gas operations (e.g., - /// the 10x LOG topic/data costs). - /// On return, unused `STORAGE_CALL_STIPEND` is burned — it is never returned to the caller. - pub const STORAGE_CALL_STIPEND: u64 = 23_000; -} - -/// Constants for the `REX5` spec. -pub mod rex5 { - /// Floor for the gas limit assigned to REX5 pre-block system calls that opt - /// into the live block gas budget via - /// [`crate::MegaEvm::transact_system_call_with_gas_limit`] — currently the - /// `SequencerRegistry.applyPendingChanges()`, EIP-2935 history-storage, and - /// EIP-4788 beacon-roots pre-block calls. - /// - /// The value (30M) matches the historical revm system-call default at the - /// time REX5 was specified — see the `gas_limit(30_000_000)` literal in - /// [`revm::handler::SystemCallTx::new_system_tx_with_caller`]'s `TxEnv` impl - /// (`revm-handler/src/system_call.rs`). - /// revm does not export this as a `pub const`, so we mirror the literal here - /// instead of aliasing it. Do NOT raise this value to follow upstream - /// changes — the floor must remain at the historical 30M to preserve - /// backward compatibility for REX5 chains whose block gas limit is smaller - /// than any new upstream default. Lifting it would silently increase the - /// minimum guaranteed budget and become observable via the `GAS` opcode - /// inside `applyPendingChanges()`. - /// - /// Keeping the floor at the historical default ensures test harnesses or - /// chains configured with a sub-30M block gas limit still receive the - /// budget that pre-REX5 / EIP-2935 / EIP-4788 system calls have always - /// gotten. - pub const SYSTEM_CALL_GAS_LIMIT_FLOOR: u64 = 30_000_000; -} - -/// Constants for the `REX6` spec. -pub mod rex6 {} - -/// Constants for the `REX7` spec. -pub mod rex7 {} - -/// Constants for the `REX` spec. -pub mod rex { - /// Additional storage gas cost added to transaction intrinsic gas for the `REX` spec. - /// This is charged on top of the base 21,000 intrinsic gas for all transactions. - pub const TX_INTRINSIC_STORAGE_GAS: u64 = 39_000; - - /// The base storage gas cost for setting a storage slot to a non-zero value for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `SSTORE_SET_STORAGE_GAS_BASE × - /// (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const SSTORE_SET_STORAGE_GAS_BASE: u64 = 20_000; - - /// The base storage gas cost for creating a new account for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `NEW_ACCOUNT_STORAGE_GAS_BASE × - /// (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const NEW_ACCOUNT_STORAGE_GAS_BASE: u64 = 25_000; - - /// The base storage gas cost for creating a new contract for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: - /// `CONTRACT_CREATION_STORAGE_GAS_BASE × (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const CONTRACT_CREATION_STORAGE_GAS_BASE: u64 = 32_000; - - /// The maximum compute gas limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit fail on the compute-gas limit path. - /// The exact surface result depends on the current spec's top-level/frame-local semantics. - pub const TX_COMPUTE_GAS_LIMIT: u64 = 200_000_000; - - /// The maximum data size limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `DataLimitExceeded`, preserving remaining gas. - pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; // Same with the block data limit - - /// The maximum key-value updates limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `KVUpdateLimitExceeded`, preserving remaining - /// gas. - pub const TX_KV_UPDATE_LIMIT: u64 = 500_000; // Same with the block kv update limit - - /// The maximum state growth limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `StateGrowthLimitExceeded`, preserving remaining - /// gas. - pub const TX_STATE_GROWTH_LIMIT: u64 = 1000; - - /// The maximum state growth limit for a block for the `REX` spec. - /// Blocks exceeding this limit halt with `StateGrowthLimitExceeded`, preserving remaining - /// gas. - pub const BLOCK_STATE_GROWTH_LIMIT: u64 = 1000; -} diff --git a/crates/mega-evm/src/evm/AGENTS.md b/crates/mega-evm/src/evm/AGENTS.md deleted file mode 100644 index 0245c104b..000000000 --- a/crates/mega-evm/src/evm/AGENTS.md +++ /dev/null @@ -1,30 +0,0 @@ -# AGENTS.md - -## OVERVIEW -MegaEVM execution core that wraps revm/op-revm with MegaETH instruction tables, host behavior, and execution interfaces. - -## STRUCTURE -- `mod.rs`: `MegaEvm` wrapper, inspector toggling, execution convenience APIs. -- `context.rs`: execution context composition and state wiring. -- `execution.rs`: transaction execution flow and result shaping. -- `factory.rs`: `MegaEvmFactory` builder for context and external env wiring. -- `instructions.rs`: spec-layered opcode table and extension wrappers. -- `host.rs`: host overrides for volatile tracking, oracle reads, SALT gas hooks. -- `limit.rs`: EVM-facing limit helpers and runtime-limit adaptation. -- `spec.rs`: `MegaSpecId` parsing/ordering utilities. - -## KEY PATTERNS -- Instruction semantics are layered wrappers, not ad-hoc per-opcode mutations. -- Preserve wrapper ordering when changing opcode stacks. -- Spec upgrades extend prior tables by overriding changed opcodes only. -- Host methods mark volatile accesses before delegating to inner host behavior. -- Oracle `sload` handling forces cold semantics for deterministic replay. -- `MegaEvm` methods read aggregate resource usage from `additional_limit` after execution. -- Keep inspector and non-inspector paths behaviorally aligned. - -## WHERE TO LOOK -- New spec opcode delta: `instructions.rs` (`mini_rex`, `rex`, `rex2`, `rex3`, `rex4`, `rex5`, `rex6`, `rex7` tables; `rex6` and `rex7` currently alias their predecessor, expressing their deltas as `is_enabled` dispatch inside the shared handlers). -- Volatile access detention trigger changes: `host.rs` and volatile wrappers in `instructions.rs`. -- Call forwarding and stipend interplay: `instructions.rs` + `../limit/storage_call_stipend.rs`. -- New external gas pricing path: `host.rs` gas helper methods. -- Execution result fields exposed to callers: `execution.rs` and `mod.rs::execute_transaction`. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs deleted file mode 100644 index 886022cff..000000000 --- a/crates/mega-evm/src/evm/context.rs +++ /dev/null @@ -1,882 +0,0 @@ -//! # `MegaETH` EVM Context -//! -//! This module provides the core context implementation for the `MegaETH` EVM. -//! The [`Context`] struct wraps the underlying `OpStack` context and provides -//! additional MegaETH-specific functionality including gas cost oracles, -//! additional limits, and block environment access tracking. -//! -//! ## Key Features -//! -//! - **Gas Cost Oracle**: Tracks and manages gas costs during transaction execution -//! - **Additional Limits**: Enforces data and KV update limits beyond standard EVM limits -//! - **Block Environment Access Tracking**: Monitors which block environment data is accessed -//! - **Spec Management**: Handles different `MegaETH` specification versions - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{rc::Rc, vec::Vec}; - -use alloy_evm::Database; -use alloy_primitives::Address; -use core::cell::RefCell; -use delegate::delegate; -use op_revm::{DefaultOp, L1BlockInfo, OpContext, OpSpecId}; -use revm::{ - context::{BlockEnv, CfgEnv, ContextSetters, ContextTr, LocalContext}, - context_interface::context::ContextError, - database::EmptyDB, - Journal, -}; - -use crate::{ - constants, is_system_originated, AdditionalLimit, BucketId, DynamicGasCost, EmptyExternalEnv, - EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, TxRuntimeLimit, - VolatileDataAccess, VolatileDataAccessTracker, VolatileDataAccessType, -}; - -/// `MegaETH` EVM context type. This struct wraps [`OpContext`] and implements the [`ContextTr`] -/// trait to be used as the context for the [`crate::Evm`]. -#[derive(Debug, derive_more::Deref, derive_more::DerefMut)] -pub struct MegaContext { - /// The inner context. - #[deref] - #[deref_mut] - pub(crate) inner: OpContext, - /// The `MegaETH` spec id. The inner context contains the `OpSpecId`. - /// The `OpSpec` in the `inner` context should be the corresponding [`OpSpecId`] for the - /// [`SpecId`]. - pub(crate) spec: MegaSpecId, - - /// Whether to disable the post-transaction reward to beneficiary. - pub(crate) disable_beneficiary: bool, - - /// Additional limits for the EVM. - pub additional_limit: Rc>, - - /// Shared SALT environment handle. - pub(crate) salt_env: Rc, - - /// Calculator for dynamic gas costs during transaction execution. - pub dynamic_storage_gas_cost: Rc>>>, - - /// The oracle environment. - pub oracle_env: Rc>, - - /* Internal state variables */ - /// Tracker for volatile data access (block environment, beneficiary, oracle) - /// and volatile data access disable (`MegaAccessControl` system contract). - pub volatile_data_tracker: Rc>, - - /// Set to `true` when this context is itself a sandbox execution. - /// - /// Suppresses sandbox interception (preventing recursive sandboxing) and signals other - /// Mega hooks to defer to outer-frame accounting (e.g., the Rex5+ deposit-caller - /// materialization charge in `validate`, which is paid by the outer keyless-deploy call - /// before the sandbox runs). - pub(crate) inside_sandbox: Rc>, - - /// The system address for the current block. - /// Pre-REX5: always `MEGA_SYSTEM_ADDRESS` (the legacy hardcoded constant). - /// REX5+: resolved from `SequencerRegistry` storage in `apply_pre_execution_changes`. - pub(crate) system_address: Address, -} - -impl Default for MegaContext { - fn default() -> Self { - Self::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE) - } -} - -/* Constructors */ -impl MegaContext { - /// Creates a new `MegaContext` with [`EmptyExternalEnv`]. - /// - /// This constructor initializes a new `MegaETH` EVM context with default settings. - /// For the `MINI_REX` specification, it automatically configures appropriate - /// contract size and initcode size limits. - /// - /// # Arguments - /// - /// * `db` - The database implementation to use for state storage - /// * `spec` - The `MegaETH` specification version to use - /// - /// # Returns - /// - /// Returns a new `MegaContext` instance with default configuration. - pub fn new(db: DB, spec: MegaSpecId) -> Self { - // `OpContext::default()` starts with block number 0, so the parent block number is also 0. - let salt_env = Rc::new(EmptyExternalEnv); - Self::new_with_shared_ext_envs(db, spec, salt_env, Rc::new(RefCell::new(EmptyExternalEnv))) - } -} - -#[cfg(any(test, feature = "test-utils"))] -impl MegaContext { - /// Test/bench-only public wrapper over [`new_with_shared_ext_envs`] so a - /// bench can build a context over a configurable external environment - /// (e.g. `TestExternalEnvs` with crowded buckets or oracle storage). - pub fn new_with_ext_envs( - db: DB, - spec: MegaSpecId, - salt_env: Rc, - oracle_env: Rc>, - ) -> Self { - Self::new_with_shared_ext_envs(db, spec, salt_env, oracle_env) - } -} - -impl MegaContext { - /// Creates a new `MegaContext` with shared external environment references. - /// - /// Unlike [`MegaContext::new`] which uses [`EmptyExternalEnv`], this constructor accepts - /// existing `Rc` references to share a parent context's salt env and oracle env. - /// This ensures the sandbox uses the same dynamic gas pricing as the parent. - /// - /// # Arguments - /// - /// * `db` - The database implementation to use for state storage - /// * `spec` - The `MegaETH` specification version to use - /// * `salt_env` - Shared salt environment from the parent context - /// * `oracle_env` - Shared oracle environment from the parent context - /// - /// # Returns - /// - /// Returns a new `MegaContext` instance sharing the parent's external environments while - /// keeping a fresh dynamic gas cost cache local to the new context. - pub(crate) fn new_with_shared_ext_envs( - db: DB, - spec: MegaSpecId, - salt_env: Rc, - oracle_env: Rc>, - ) -> Self { - let mut inner = - revm::Context::op().with_db(db).with_cfg(CfgEnv::new_with_spec(spec.into_op_spec())); - - if spec.is_enabled(MegaSpecId::MINI_REX) { - inner.cfg.limit_contract_code_size = Some(constants::mini_rex::MAX_CONTRACT_SIZE); - inner.cfg.limit_contract_initcode_size = Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - - let tx_limits = EvmTxRuntimeLimits::from_spec(spec); - Self { - spec, - disable_beneficiary: false, - additional_limit: Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))), - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - inner.block.number.to::().saturating_sub(1), - ))), - oracle_env, - volatile_data_tracker: Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))), - inside_sandbox: Rc::new(RefCell::new(false)), - system_address: crate::MEGA_SYSTEM_ADDRESS, - inner, - } - } -} - -impl MegaContext { - /// Creates a new `Context` from an existing `OpContext`. - /// - /// This constructor is useful when you already have a configured `OpContext` - /// and want to wrap it with MegaETH-specific functionality. The specification - /// in the provided context must match the `spec` parameter. - /// - /// # Arguments - /// - /// * `context` - The existing `OpStack` context to wrap - /// * `spec` - The `MegaETH` specification version (must match context spec) - /// * `external_envs` - The external environments for gas cost calculations - /// - /// # Returns - /// - /// Returns a new `Context` instance wrapping the provided context. - #[deprecated(note = "Use `MegaContext::new` instead")] - pub fn new_with_context( - context: OpContext, - spec: MegaSpecId, - external_envs: ExternalEnvs, - ) -> Self { - let mut inner = context; - - // spec in context must keep the same with parameter `spec` - inner.cfg.spec = spec.into_op_spec(); - - // For the `MINI_REX` spec, we override the contract size and initcode size limits if they - // not set in the given `OpContext`. - if spec.is_enabled(MegaSpecId::MINI_REX) { - if inner.cfg.limit_contract_code_size.is_none() { - inner.cfg.limit_contract_code_size = Some(constants::mini_rex::MAX_CONTRACT_SIZE); - } - if inner.cfg.limit_contract_initcode_size.is_none() { - inner.cfg.limit_contract_initcode_size = - Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - } - - let tx_limits = EvmTxRuntimeLimits::from_spec(spec); - let salt_env = Rc::new(external_envs.salt_env); - Self { - spec, - disable_beneficiary: false, - additional_limit: Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))), - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - inner.block.number.to::().saturating_sub(1), - ))), - oracle_env: Rc::new(RefCell::new(external_envs.oracle_env)), - volatile_data_tracker: Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))), - inside_sandbox: Rc::new(RefCell::new(false)), - system_address: crate::MEGA_SYSTEM_ADDRESS, - inner, - } - } - - /// Sets the [`Database`] used by the EVM. - /// - /// This method allows changing the underlying database implementation - /// while preserving all other context configuration. - /// - /// # Arguments - /// - /// * `db` - The new database implementation - /// - /// # Returns - /// - /// Returns a new `Context` with the updated database type. - pub fn with_db(self, db: ODB) -> MegaContext { - MegaContext { - inner: self.inner.with_db(db), - spec: self.spec, - disable_beneficiary: self.disable_beneficiary, - additional_limit: self.additional_limit, - salt_env: self.salt_env, - dynamic_storage_gas_cost: self.dynamic_storage_gas_cost, - oracle_env: self.oracle_env, - volatile_data_tracker: self.volatile_data_tracker, - inside_sandbox: self.inside_sandbox, - system_address: self.system_address, - } - } - - /// Sets the [`Transaction`] to be executed by the EVM. - /// - /// This method configures the transaction to be executed and automatically - /// resets internal state for the new transaction. - /// - /// # Arguments - /// - /// * `tx` - The transaction to execute - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_tx(mut self, tx: crate::MegaTransaction) -> Self { - self.inner = self.inner.with_tx(tx); - self - } - - /// Sets the [`BlockEnv`] for the EVM. - /// - /// This method configures the block environment and automatically - /// resets internal state for the new block. - /// - /// # Arguments - /// - /// * `block` - The block environment configuration - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_block(mut self, block: BlockEnv) -> Self { - self.inner = self.inner.with_block(block); - // Reset internal state for new block - self.on_new_block(); - self - } - - /// Sets the [`CfgEnv`] for the EVM. - /// - /// This method configures the EVM environment settings. For the `MINI_REX` - /// specification, it automatically applies appropriate contract size limits - /// if they are not already set in the configuration. - /// - /// # Arguments - /// - /// * `cfg` - The configuration environment - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { - self.spec = cfg.spec; - self.inner = self.inner.with_cfg(cfg.into_op_cfg()); - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - if self.inner.cfg.limit_contract_code_size.is_none() { - self.inner.cfg.limit_contract_code_size = - Some(constants::mini_rex::MAX_CONTRACT_SIZE); - } - if self.inner.cfg.limit_contract_initcode_size.is_none() { - self.inner.cfg.limit_contract_initcode_size = - Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - } - self - } - - /// Sets the external environments for the EVM. - /// - /// This method updates the external environments used for gas cost calculations, - /// including the salt environment and oracle environment. When setting new - /// external environments, the dynamic gas cost calculator and oracle environment - /// are reinitialized with the new configurations. - /// - /// # Arguments - /// - /// * `external_envs` - The new external environments configuration - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_external_envs( - self, - external_envs: ExternalEnvs, - ) -> MegaContext { - let parent_block_number = self.inner.block.number.to::().saturating_sub(1); - let spec = self.spec; - let salt_env = Rc::new(external_envs.salt_env); - MegaContext { - inner: self.inner, - spec, - disable_beneficiary: self.disable_beneficiary, - additional_limit: self.additional_limit, - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - parent_block_number, - ))), - oracle_env: Rc::new(RefCell::new(external_envs.oracle_env)), - volatile_data_tracker: self.volatile_data_tracker, - inside_sandbox: self.inside_sandbox, - system_address: self.system_address, - } - } - - /// Sets the Op Stack's [`L1BlockInfo`] for the EVM. - /// - /// This method configures the L1 block information used by the `OpStack` - /// for cross-layer communication and state management. - /// - /// # Arguments - /// - /// * `chain` - The L1 block information - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_chain(mut self, chain: L1BlockInfo) -> Self { - self.inner = self.inner.with_chain(chain); - self - } - - /// Sets the transaction limits for the EVM. - pub fn with_tx_runtime_limits(mut self, tx_limits: EvmTxRuntimeLimits) -> Self { - self.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(self.spec, tx_limits))); - self.volatile_data_tracker = Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))); - self - } -} - -/* Getters */ -impl MegaContext { - /// Gets the `MegaETH` specification ID. - /// - /// Returns the specification version currently configured for this context. - /// - /// # Returns - /// - /// Returns the [`SpecId`] representing the current `MegaETH` specification. - pub fn mega_spec(&self) -> MegaSpecId { - self.spec - } - - /// Gets the system address for the current block. - /// - /// Pre-REX5: always `MEGA_SYSTEM_ADDRESS`. - /// REX5+: resolved from `SequencerRegistry` storage in `apply_pre_execution_changes`. - pub fn system_address(&self) -> Address { - self.system_address - } - - /// Sets the system address for the current block. - pub(crate) fn set_system_address(&mut self, address: Address) { - self.system_address = address; - } - - /// Returns whether this context is itself a sandbox execution. - /// - /// When `true`, sandbox interception (e.g., keyless deploy) is suppressed to prevent - /// recursive sandboxing, and Mega hooks defer to outer-frame accounting (e.g., the - /// Rex5+ deposit-caller materialization charge in `validate`). - #[inline] - pub fn is_inside_sandbox(&self) -> bool { - *self.inside_sandbox.borrow() - } - - /// Sets whether this context is itself a sandbox execution. - #[inline] - pub(crate) fn set_inside_sandbox(&self, value: bool) { - *self.inside_sandbox.borrow_mut() = value; - } - - /// Builder method to mark this context as itself a sandbox execution. - /// - /// Used when constructing a sandbox's own context to prevent recursive interception. - #[inline] - pub fn with_inside_sandbox(self, value: bool) -> Self { - self.set_inside_sandbox(value); - self - } - - /// Gets the current total data size generated from transaction execution. - /// - /// # Returns - /// - /// Returns the current total data size in bytes generated so far. The data size is reset at the - /// beginning of each transaction. - pub fn generated_data_size(&self) -> u64 { - self.additional_limit.borrow().data_size.tx_usage() - } - - /// Gets the current total number of key-value updates performed during transaction execution. - /// - /// # Returns - /// - /// Returns the current total number of KV operations performed so far. The count is reset at - /// the beginning of each transaction. - pub fn kv_update_count(&self) -> u64 { - self.additional_limit.borrow().kv_update.tx_usage() - } - - /// Gets the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn accessed_bucket_ids(&self) -> Vec { - self.dynamic_storage_gas_cost.borrow().get_bucket_ids() - } - - /// Consumes the context and converts it into the inner `OpContext`. - /// - /// This method extracts the underlying `OpStack` context, discarding - /// all MegaETH-specific state and configuration. - /// - /// # Returns - /// - /// Returns the inner `OpContext`. - pub fn into_inner(self) -> OpContext { - self.inner - } -} - -/* Block Environment Access Tracking */ -impl MegaContext { - /// Returns the bitmap of block environment data accessed during transaction execution. - /// - /// This method provides information about which block environment fields - /// have been accessed during the current transaction, which is useful for - /// optimization and analysis purposes. - /// - /// # Returns - /// - /// Returns a [`VolatileDataAccess`] bitmap indicating accessed fields. - pub fn get_block_env_accesses(&self) -> VolatileDataAccess { - self.volatile_data_tracker.borrow().get_block_env_accesses() - } - - /// Resets the volatile data access tracker for new transactions. - /// - /// This method clears the volatile data access tracker, preparing the context for a new - /// transaction. - pub fn reset_volatile_data_access(&mut self) { - self.volatile_data_tracker.borrow_mut().reset(); - } - - /// Marks that a specific type of block environment has been accessed. - /// - /// This internal method is used to track which block environment fields - /// are being accessed during transaction execution. - /// - /// # Arguments - /// - /// * `access_type` - The type of block environment access to record - pub(crate) fn mark_block_env_accessed(&self, access_type: VolatileDataAccessType) { - self.volatile_data_tracker.borrow_mut().mark_block_env_accessed(access_type); - } -} - -/* Beneficiary Access Tracking */ -impl MegaContext { - /// Disables the beneficiary reward. - pub fn disable_beneficiary(&mut self) { - self.disable_beneficiary = true; - } - - /// Check if address is beneficiary and mark access if so. - /// Returns true if beneficiary was accessed. - pub(crate) fn check_and_mark_beneficiary_balance_access(&self, address: &Address) -> bool { - if self.inner.block.beneficiary == *address { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - true - } else { - false - } - } - - /// Check if the transaction caller or recipient is the beneficiary - pub(crate) fn check_tx_beneficiary_access(&self) { - let tx = &self.inner.tx; - let beneficiary = self.inner.block.beneficiary; - - // Check if caller is beneficiary - if tx.base.caller == beneficiary { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - } - - // Check if recipient is beneficiary (for calls) - if let revm::primitives::TxKind::Call(recipient) = tx.base.kind { - if recipient == beneficiary { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - } - } - } -} - -/* Hooks */ -impl MegaContext { - /// Resets the internal state for a new block. - /// - /// This method is called when transitioning to a new block and updates - /// the dynamic gas cost calculator and additional limits accordingly. - pub(crate) fn on_new_block(&self) { - // The dynamic gas cost calculator is only enabled when the `MINI_REX` spec is enabled. - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - self.dynamic_storage_gas_cost.borrow_mut().on_new_block(&self.inner.block); - } - } - - /// Resets the internal state for a new transaction. - /// - /// This method is called when starting a new transaction and resets - /// block environment access tracking and additional limits. - /// - /// If transaction-only intrinsic resource usage exceeds a configured limit, - /// `before_tx_start()` sets `has_exceeded_limit` so that the subsequent - /// `frame_result_if_exceeding_limit()` or `before_frame_init()` call produces a normal - /// execution failure on the standard additional-limit path. - /// - /// DB-dependent pre-frame usage may still be recorded later during pre-execution. - pub(crate) fn on_new_tx(&mut self) { - self.reset_volatile_data_access(); - - // The additional-limit lifecycle (reset → intrinsic accounting) exists only for MINI_REX+. - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - self.additional_limit.borrow_mut().reset(); - self.additional_limit.borrow_mut().before_tx_start(&self.inner.tx); - } - - // REX6+: exempt system-originated transactions (see `crate::is_system_originated`) from - // MegaETH per-tx resource metering. - if self.spec.is_enabled(MegaSpecId::REX6) && - is_system_originated(&self.inner.tx, self.system_address) - { - self.additional_limit.borrow_mut().mark_exempt(); - } - - // Mark beneficiary access AFTER additional_limit.reset() so that the volatile - // tracker marking from check_tx_beneficiary_access can be synchronized into - // additional_limit below, rather than being cleared by the reset. - // - // Gated to REX4: pre-REX4 specs never had eager beneficiary detention at TX start. - // Changing pre-REX4 behavior would alter historical replay results. - self.check_tx_beneficiary_access(); - if self.spec.is_enabled(MegaSpecId::REX4) { - let compute_gas_limit = self.volatile_data_tracker.borrow().get_compute_gas_limit(); - if let Some(limit) = compute_gas_limit { - self.additional_limit.borrow_mut().set_compute_gas_limit(limit); - } - } - } -} - -/// Implementation of the `ContextTr` trait for `Context`. -/// -/// This implementation delegates most methods to the inner `OpContext` while -/// maintaining the MegaETH-specific functionality. The trait provides access -/// to the core EVM context components like transaction, block, configuration, -/// database, journal, and chain information. -impl ContextTr for MegaContext { - type Block = BlockEnv; - type Tx = crate::MegaTransaction; - type Cfg = CfgEnv; - type Db = DB; - type Journal = Journal; - type Chain = L1BlockInfo; - type Local = LocalContext; - - delegate! { - to self.inner { - fn tx(&self) -> &Self::Tx; - fn block(&self) -> &Self::Block; - fn cfg(&self) -> &Self::Cfg; - fn journal(&self) -> &Self::Journal; - fn journal_mut(&mut self) -> &mut Self::Journal; - fn journal_ref(&self) -> &Self::Journal; - fn db(&self) -> &Self::Db; - fn db_mut(&mut self) -> &mut Self::Db; - fn chain(&self) -> &Self::Chain; - fn chain_mut(&mut self) -> &mut Self::Chain; - fn local(&self) -> &Self::Local; - fn local_mut(&mut self) -> &mut Self::Local; - fn error(&mut self) -> &mut Result<(), ContextError<::Error>>; - fn tx_journal_mut(&mut self) -> (&Self::Tx, &mut Self::Journal); - fn tx_local_mut(&mut self) -> (&Self::Tx, &mut Self::Local); - } - } -} - -/// Implementation of the `ContextSetters` trait for `Context`. -/// -/// This implementation provides methods to update the context state, with -/// special handling for transaction updates to reset internal state. -impl ContextSetters for MegaContext { - delegate! { - to self.inner { - fn set_block(&mut self, block: Self::Block); - fn set_tx(&mut self, tx: Self::Tx); - } - } -} - -/// A convenient trait to convert a `CfgEnv` into a `CfgEnv`. -/// -/// This trait provides a conversion method for `OpStack` configuration environments -/// to `MegaETH` configuration environments, preserving all configuration fields -/// while changing the specification type. -pub trait IntoMegaethCfgEnv { - /// Converts to `CfgEnv`. - fn into_megaeth_cfg(self, spec: MegaSpecId) -> CfgEnv; -} - -/// A convenient trait to convert a `CfgEnv` into a `CfgEnv`. -/// -/// This trait provides a conversion method for `MegaETH` configuration environments -/// to `OpStack` configuration environments, preserving all configuration fields -/// while changing the specification type. -pub trait IntoOpCfgEnv { - /// Converts to `CfgEnv`. - fn into_op_cfg(self) -> CfgEnv; -} - -/// Implementation of `IntoOpCfgEnv` for `CfgEnv`. -/// -/// This implementation converts a `MegaETH` configuration environment to an -/// `OpStack` configuration environment by copying all relevant fields. -impl IntoOpCfgEnv for CfgEnv { - /// Converts to `CfgEnv`. - /// - /// This method creates a new `OpStack` configuration environment with the - /// same settings as the `MegaETH` configuration, converting the specification ID. - /// - /// # Returns - /// - /// Returns a new `CfgEnv` with all fields copied from `self`. - /// - /// # Note - /// - /// When the fields of [`CfgEnv`] change, this function needs to be updated - /// to include the new fields. - fn into_op_cfg(self) -> CfgEnv { - let mut op_cfg = CfgEnv::new_with_spec(OpSpecId::from(self.spec)); - op_cfg.chain_id = self.chain_id; - op_cfg.tx_chain_id_check = self.tx_chain_id_check; - op_cfg.limit_contract_code_size = self.limit_contract_code_size; - op_cfg.limit_contract_initcode_size = self.limit_contract_initcode_size; - op_cfg.disable_nonce_check = self.disable_nonce_check; - op_cfg.max_blobs_per_tx = self.max_blobs_per_tx; - op_cfg.blob_base_fee_update_fraction = self.blob_base_fee_update_fraction; - op_cfg.tx_gas_limit_cap = self.tx_gas_limit_cap; - op_cfg.memory_limit = self.memory_limit; - op_cfg.disable_balance_check = self.disable_balance_check; - op_cfg.disable_block_gas_limit = self.disable_block_gas_limit; - op_cfg.disable_eip3541 = self.disable_eip3541; - op_cfg.disable_eip3607 = self.disable_eip3607; - op_cfg.disable_base_fee = self.disable_base_fee; - op_cfg - } -} - -/// Implementation of `IntoMegaethCfgEnv` for `CfgEnv`. -/// -/// This implementation converts an `OpStack` configuration environment to a -/// `MegaETH` configuration environment by copying all relevant fields. -impl IntoMegaethCfgEnv for CfgEnv { - /// Converts to `CfgEnv`. - /// - /// This method creates a new `MegaETH` configuration environment with the - /// same settings as the `OpStack` configuration, using the provided specification ID. - /// - /// # Arguments - /// - /// * `spec` - The `MegaETH` specification ID to use in the new configuration - /// - /// # Returns - /// - /// Returns a new `CfgEnv` with all fields copied from `self`. - /// - /// # Note - /// - /// When the fields of [`CfgEnv`] change, this function needs to be updated - /// to include the new fields. - fn into_megaeth_cfg(self, spec: MegaSpecId) -> CfgEnv { - let mut cfg = CfgEnv::new_with_spec(spec); - cfg.chain_id = self.chain_id; - cfg.tx_chain_id_check = self.tx_chain_id_check; - cfg.limit_contract_code_size = self.limit_contract_code_size; - cfg.limit_contract_initcode_size = self.limit_contract_initcode_size; - cfg.disable_nonce_check = self.disable_nonce_check; - cfg.max_blobs_per_tx = self.max_blobs_per_tx; - cfg.blob_base_fee_update_fraction = self.blob_base_fee_update_fraction; - cfg.tx_gas_limit_cap = self.tx_gas_limit_cap; - cfg.memory_limit = self.memory_limit; - cfg.disable_balance_check = self.disable_balance_check; - cfg.disable_block_gas_limit = self.disable_block_gas_limit; - cfg.disable_eip3541 = self.disable_eip3541; - cfg.disable_eip3607 = self.disable_eip3607; - cfg.disable_base_fee = self.disable_base_fee; - cfg - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use alloy_primitives::address; - use revm::{context::CfgEnv, database::EmptyDB}; - - use crate::TestExternalEnvs; - - #[test] - fn test_with_cfg_updates_spec() { - // Create context with initial spec - let mut context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Verify initial state - assert_eq!(context.mega_spec(), MegaSpecId::EQUIVALENCE); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::EQUIVALENCE)); - - // Create new config with different spec - let new_cfg = CfgEnv::new_with_spec(MegaSpecId::MINI_REX); - - // Apply new config using with_cfg - context = context.with_cfg(new_cfg); - - // Verify that both the context's spec and inner config's spec are updated - assert_eq!(context.mega_spec(), MegaSpecId::MINI_REX); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::MINI_REX)); - } - - #[test] - fn test_with_cfg_spec_consistency() { - let context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Test multiple spec transitions - let specs_to_test = [MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]; - - let mut current_context = context; - for spec in specs_to_test { - let cfg = CfgEnv::new_with_spec(spec); - current_context = current_context.with_cfg(cfg); - - // Verify consistency between context spec and inner config spec - assert_eq!(current_context.mega_spec(), spec); - assert_eq!(current_context.inner.cfg.spec, OpSpecId::from(spec)); - } - } - - /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. - #[test] - fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { - let external_envs = TestExternalEnvs::new(); - let parent = MegaContext::new(EmptyDB::default(), MegaSpecId::REX4) - .with_external_envs(external_envs.into()); - let parent_address = address!("0000000000000000000000000000000000100001"); - let sandbox_address = address!("0000000000000000000000000000000000100002"); - - parent - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(parent_address) - .expect("parent bucket lookup should succeed"); - let parent_bucket_ids = parent.accessed_bucket_ids(); - - let sandbox = - MegaContext::<_, TestExternalEnvs>::new_with_shared_ext_envs( - EmptyDB::default(), - MegaSpecId::REX4, - Rc::clone(&parent.salt_env), - Rc::clone(&parent.oracle_env), - ) - .with_block(parent.block().clone()) - .with_chain(parent.chain().clone()) - .with_inside_sandbox(true); - sandbox - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(sandbox_address) - .expect("sandbox bucket lookup should succeed"); - - assert_eq!(parent.accessed_bucket_ids(), parent_bucket_ids); - assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); - } - - /// The test/bench-only `new_with_ext_envs` wrapper builds a `MegaContext` - /// over a caller-supplied external environment (`TestExternalEnvs`), at the - /// requested spec and wired to the given SALT/oracle handles. - #[test] - fn test_new_with_ext_envs_builds_over_configurable_env() { - let env = TestExternalEnvs::::new(); - let context = - MegaContext::<_, TestExternalEnvs>::new_with_ext_envs( - EmptyDB::default(), - MegaSpecId::REX5, - Rc::new(env.clone()), - Rc::new(RefCell::new(env)), - ); - - assert_eq!(context.mega_spec(), MegaSpecId::REX5); - // The supplied SALT env is wired through: a bucket lookup against the - // dynamic-gas cache succeeds. - context - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(address!("0000000000000000000000000000000000100003")) - .expect("bucket lookup against the supplied env should succeed"); - } -} diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs deleted file mode 100644 index a34c6ea8a..000000000 --- a/crates/mega-evm/src/evm/execution.rs +++ /dev/null @@ -1,1591 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{collections::BTreeMap, string::ToString, vec::Vec}; - -use alloy_evm::{precompiles::PrecompilesMap, Database}; -use alloy_primitives::{Address, Bytes, TxKind, U256}; -use delegate::delegate; -use op_revm::{ - constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, - handler::{IsTxError, OpHandler}, - transaction::deposit::DEPOSIT_TRANSACTION_TYPE, - OpHaltReason, OpTransactionError, -}; -use revm::{ - context::{ - result::{ExecutionResult, FromStringError, InvalidTransaction}, - transaction::{AuthorizationTr, TransactionType}, - Block, Cfg, ContextError, ContextTr, FrameStack, JournalTr, LocalContextTr, Transaction, - }, - handler::{ - evm::{ContextDbError, FrameInitResult}, - instructions::InstructionProvider, - post_execution::output as post_execution_output, - pre_execution::validate_account_nonce_and_code, - EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, FrameTr, Handler, - ItemOrResult, - }, - inspector::{ - handler::{frame_end, frame_start}, - inspect_instructions, InspectorEvmTr, InspectorFrame, InspectorHandler, - }, - interpreter::{ - gas::get_tokens_in_calldata, interpreter::EthInterpreter, interpreter_action::FrameInit, - CallOutcome, CallScheme, CreateOutcome, FrameInput, Gas, InitialAndFloorGas, - InstructionResult, InterpreterAction, InterpreterResult, - }, - primitives::CALL_STACK_LIMIT, - Inspector, Journal, -}; - -use crate::{ - constants, dispatch_system_contract_interceptors, is_deposit_like_transaction, - is_mega_system_transaction_with, limit::ACCOUNT_INFO_WRITE_SIZE, sent_from_system_address, - ExternalEnvTypes, HostExt, JournalInspectTr, MegaContext, MegaEvm, MegaHaltReason, - MegaInstructions, MegaSpecId, MegaTransactionError, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, -}; - -/// Revm handler for `MegaETH`. It internally wraps the [`op_revm::handler::OpHandler`] and inherits -/// most functionalities from Optimism. -#[allow(missing_debug_implementations)] -pub struct MegaHandler { - op: OpHandler, -} - -impl MegaHandler { - /// Create a new `MegaethHandler`. - pub fn new() -> Self { - Self { op: OpHandler::new() } - } -} - -impl Default for MegaHandler { - fn default() -> Self { - Self::new() - } -} - -impl MegaHandler -where - DB: Database, - ExtEnvs: ExternalEnvTypes, - EVM: EvmTr>, - ERROR: FromStringError + From, -{ - /// The hook to be called in `revm::handler::Handler::run_without_catch_error` and - /// `revm::handler::InspectorHandler::inspect_run_without_catch_error`. - /// - /// Promotes a legacy `system_address` transaction into the OP deposit-style path so it - /// bypasses signature, nonce, and fee validation. REX5+ restores nonce and chain-id - /// checks before the promotion (the deposit path otherwise drops them, leaving the - /// transaction replayable). Pre-REX5 specs preserve the original behavior so existing - /// chain replay is unaffected. - #[inline] - fn before_run(&self, evm: &mut EVM) -> Result<(), ERROR> { - let ctx = evm.ctx_mut(); - let spec = ctx.spec; - if spec.is_enabled(MegaSpecId::MINI_REX) { - let system_address = ctx.system_address; - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - // Honor the same `CfgEnv` toggles as the canonical revm validate path. - // Ordinary txs are already filtered by the upstream validate path before - // reaching this promotion logic, so keeping system txs aligned here does - // not introduce a separate replay-only escape hatch. - let cfg = ctx.cfg(); - let cfg_chain_id = cfg.chain_id; - let tx_chain_id_check = cfg.tx_chain_id_check; - let disable_nonce_check = cfg.disable_nonce_check; - let disable_eip3607 = cfg.disable_eip3607; - let tx = ctx.tx(); - - if sent_from_system_address(tx, system_address) { - // Whitelist rejection has no canonical `InvalidTransaction` variant; keep the - // existing string-error shape pre-REX5 callers already expect. - if !is_mega_system_transaction_with(tx, system_address) { - return Err(FromStringError::from_string( - "Mega system transaction callee is not in the whitelist".to_string(), - )); - } - - if is_rex5_enabled { - if tx_chain_id_check { - match tx.chain_id() { - None => return Err(InvalidTransaction::MissingChainId.into()), - Some(cid) if cid != cfg_chain_id => { - return Err(InvalidTransaction::InvalidChainId.into()); - } - Some(_) => {} - } - } - - // Inspect without warming so validation does not mutate the EIP-2929 - // access list. The journal cache still lets consecutive in-block system - // txs observe committed nonce bumps. - let tx_nonce = tx.nonce(); - // EIP-3607 reads `info.code`; pass `load_code = true` so the - // `code_by_hash` is paid here rather than silently bypassing the - // guard against a lazy-code DB. - let state_account = ctx - .journal_mut() - .inspect_account(system_address, true) - .map_err(|e| -> ERROR { - FromStringError::from_string(format!( - "Mega system transaction state read failed: {e:?}" - )) - })?; - validate_account_nonce_and_code( - &mut state_account.info, - tx_nonce, - disable_eip3607, - disable_nonce_check, - )?; - } - - // Mark the tx as deposit-style for `OpHandler` and force gas_price to 0 - // so fee / L1 / operator / beneficiary accounting all degenerate to no-ops. - let tx = &mut ctx.inner.tx; - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.base.gas_price = 0; - } - } - - ctx.on_new_tx(); - Ok(()) - } - - /// The hook to be called in `revm::handler::Handler::execution` and - /// `revm::inspector::InspectorHandler::inspect_execution` to check if the initial gas exceeds - /// the tx gas limit, if so, we halt with out of gas. - #[inline] - fn before_execution( - &self, - evm: &mut EVM, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result, ERROR> { - // Check if the initial gas exceeds the tx gas limit, if so, we halt with out of gas - let ctx = evm.ctx(); - let tx = ctx.tx(); - if tx.gas_limit() < init_and_floor_gas.initial_gas { - // If not sufficient gas, we halt with out of gas - let oog_frame_result = gen_oog_frame_result(tx.kind(), tx.gas_limit()); - return Ok(Some(oog_frame_result)); - } - Ok(None) - } -} - -/// A fee recipient's pre-reward state, captured before delegating to op-revm so the -/// post-reward diff can tell whether the credit changed or materialised the account. -struct FeeRecipientSnapshot { - address: Address, - balance: U256, - was_empty: bool, -} - -/// One EIP-7702 authorization that would actually apply, as determined by the read-only -/// pre-application scan in [`MegaHandler::scan_applied_eip7702_authorizations`]. -struct AppliedAuthorization { - /// The recovered authority account the authorization delegates. - authority: Address, - /// `true` if applying the authorization materializes an account that does not yet exist. - creates_authority: bool, -} - -impl MegaHandler -where - DB: Database, - ExtEnvs: ExternalEnvTypes, - EVM: EvmTr>, - ERROR: From + FromStringError, -{ - /// Read-only scan of a transaction's EIP-7702 authorization list, mirroring revm's auth-list - /// application order: the chain-id / `u64::MAX`-nonce / non-empty-non-7702-code gates, the - /// per-authority account-nonce match, and the sequential simulated-nonce tracking for repeated - /// authorities. Returns the authorizations that would actually apply; it does not mutate - /// delegation bytecode (revm's `apply_eip7702_auth_list` does that later). This is the single - /// shared source of the gating logic for the REX5 state-growth pass and the REX6 consolidated - /// accounting, so the two cannot drift. - /// - /// `caller_nonce_already_bumped` selects the caller-nonce baseline: for a call tx, - /// `validate_against_state_and_deduct_caller` bumps the caller's nonce by 1 before - /// `apply_eip7702_auth_list` checks it. A scan running after that bump (REX5, in - /// `pre_execution`) passes `true`; one running before it (REX6, in `validate`) passes `false`, - /// so a self-authorization (`authority == caller`) is compared against `caller.nonce + 1` and - /// matches the real application. Each net-new authority appears at most once (the simulated - /// nonce dedupes repeats), so callers may treat the `creates_authority` entries as a set. - fn scan_applied_eip7702_authorizations( - &self, - evm: &mut EVM, - caller_nonce_already_bumped: bool, - ) -> Result, ERROR> { - let ctx = evm.ctx_mut(); - let chain_id = ctx.cfg().chain_id; - let (tx, journal) = ctx.tx_journal_mut(); - let caller = tx.caller(); - // Transaction-local simulated auth-list state, mirroring revm's sequential processing - // when the same authority appears multiple times in one tx. A `BTreeMap` keeps - // per-authorization lookup/update at O(log N) instead of the O(N) linear scan a `Vec` - // would need, bounding the whole pass at O(N log N) (an attacker could otherwise drive - // O(N²) node CPU with many unique authorities in one tx). The map is only ever keyed, - // never iterated for output, so the produced `applied` list is unchanged. - let mut simulated_authorities = BTreeMap::::new(); - let mut applied = Vec::new(); - for authorization in tx.authorization_list() { - let auth_chain_id = authorization.chain_id(); - if !auth_chain_id.is_zero() && auth_chain_id != U256::from(chain_id) { - continue; - } - if authorization.nonce() == u64::MAX { - continue; - } - let Some(authority) = authorization.authority() else { - continue; - }; - - let (authority_nonce, creates_authority) = if let Some(nonce) = - simulated_authorities.get(&authority).copied() - { - (nonce, false) - } else { - // No-warm read: this scan is a pre-flight count and must not change the - // access list. Authority warming is owned by revm's authorization application; - // `inspect_account` keeps that boundary clean. - let authority_acc = journal.inspect_account(authority, true)?; - if let Some(bytecode) = &authority_acc.info.code { - if !bytecode.is_empty() && !bytecode.is_eip7702() { - continue; - } - } - // Mirror the call tx caller's own nonce bump for a self-authorization, unless this - // scan already runs after that bump. Type-4 txs are always calls (a missing `to` - // is rejected at validation as `Eip7702CannotBeCreate`), so no `is_call` guard is - // needed — the authorization list is non-empty only for calls. - let effective_nonce = if !caller_nonce_already_bumped && authority == caller { - authority_acc.info.nonce.saturating_add(1) - } else { - authority_acc.info.nonce - }; - ( - effective_nonce, - authority_acc.is_empty() && - authority_acc.is_loaded_as_not_existing_not_touched(), - ) - }; - - if authorization.nonce() != authority_nonce { - continue; - } - - applied.push(AppliedAuthorization { authority, creates_authority }); - let next_nonce = authority_nonce.saturating_add(1); - // insert overwrites an existing entry and inserts a new one otherwise, - // matching the prior find-or-push. - simulated_authorities.insert(authority, next_nonce); - } - Ok(applied) - } - - /// Records REX5 state growth for EIP-7702 authorizations that create authority accounts. - /// - /// Runs in `pre_execution` (after the caller nonce bump) and charges only the state-growth - /// dimension; overflow is latched into `AdditionalLimit::has_exceeded_limit` and surfaced as - /// the normal execution failure at the first frame. The caller gates this to the REX5-only - /// path (REX5 on, REX6 off, type-4 tx); REX6+ accounts for every per-authorization effect in - /// the consolidated `validate`-time scan (`record_rex6_eip7702_authority_accounting`) instead. - #[inline] - fn record_rex5_eip7702_authority_state_growth(&self, evm: &mut EVM) -> Result<(), ERROR> { - // Pre-execution pass runs after the caller nonce bump. - let applied = self.scan_applied_eip7702_authorizations(evm, true)?; - let authority_creations = - applied.iter().filter(|auth| auth.creates_authority).count() as u64; - if authority_creations > 0 { - evm.ctx_mut() - .additional_limit - .borrow_mut() - .on_rex5_eip7702_authority_creations(authority_creations); - } - - Ok(()) - } - - /// Side-effect-free read of a fee recipient's balance and emptiness. - /// - /// Uses `inspect_account` (no warming) so reading the recipients to account the - /// post-execution reward does not perturb gas or the access list. - fn fee_recipient_balance_and_emptiness( - evm: &mut EVM, - address: Address, - ) -> Result<(U256, bool), ERROR> { - let info = &evm - .ctx_mut() - .journal_mut() - .inspect_account(address, false) - .map_err(|e| { - ERROR::from_string(format!( - "Failed to inspect fee recipient {address} for REX6 reward accounting: {e:?}", - )) - })? - .info; - Ok((info.balance, info.is_empty())) - } - - /// Snapshots the distinct accounts op-revm credits in the post-execution reward path, - /// each with its pre-reward balance and emptiness. - /// - /// The set is the block beneficiary plus the L1 / base-fee / operator fee vaults. - /// It is deduplicated because the block beneficiary may coincide with a fee vault, and - /// op-revm would otherwise issue two `balance_incr`s to the same on-chain account — which - /// is still a single account write. - fn snapshot_fee_recipients(evm: &mut EVM) -> Result, ERROR> { - let recipients = [ - evm.ctx().block().beneficiary(), - L1_FEE_RECIPIENT, - BASE_FEE_RECIPIENT, - OPERATOR_FEE_RECIPIENT, - ]; - let mut snapshots: Vec = Vec::with_capacity(recipients.len()); - for address in recipients { - if snapshots.iter().any(|snapshot| snapshot.address == address) { - continue; - } - let (balance, was_empty) = Self::fee_recipient_balance_and_emptiness(evm, address)?; - snapshots.push(FeeRecipientSnapshot { address, balance, was_empty }); - } - Ok(snapshots) - } - - /// REX6 consolidated EIP-7702 authorization accounting. - /// - /// Runs in `validate`, before the gas-limit check and fee affordability, and is the single - /// source of truth for per-authorization effects — replacing the pre-REX6 split between the - /// ungated `before_tx_start` DataSize/KV charges and the pre-execution state-growth scan: - /// - charges data size +40 / KV +1 for every *applied* authority (one that passed the chain-id - /// / nonce / code gates), not every recoverable one; - /// - charges state growth +1 for each *net-new* authority and returns its address so the caller - /// can add the dynamic SALT account-creation gas to `initial_gas`; - /// - marks beneficiary detention when an applied authority is the block beneficiary. - /// - /// Returns the net-new authority addresses; the caller uses them both to charge SALT gas and - /// to avoid double-charging an auth-materialized value-transfer recipient. The caller gates - /// this to REX6 type-4 transactions; pre-REX6 keeps the old split frozen. - #[inline] - fn record_rex6_eip7702_authority_accounting( - &self, - evm: &mut EVM, - ) -> Result, ERROR> { - // Runs in validate, before the caller nonce bump. - let applied = self.scan_applied_eip7702_authorizations(evm, false)?; - - // Record per-applied-authority resources + beneficiary detention. Dynamic SALT gas is - // charged by the caller from `materialized` (the net-new authorities). - let ctx = evm.ctx_mut(); - let beneficiary = ctx.inner.block.beneficiary; - let mut materialized = Vec::new(); - let mut beneficiary_applied = false; - for auth in applied { - ctx.additional_limit - .borrow_mut() - .on_rex6_eip7702_authority_applied(auth.creates_authority); - if auth.creates_authority { - // The scanner yields each net-new authority once, so `materialized` stays a set. - debug_assert!(!materialized.contains(&auth.authority)); - materialized.push(auth.authority); - } - if auth.authority == beneficiary { - beneficiary_applied = true; - } - } - - // An applied authority that is the block beneficiary mutates beneficiary state, so mark - // it and re-derive the REX4 beneficiary detention cap — the cap set at `on_new_tx` - // predates this scan and would otherwise miss the authority-side access. - if beneficiary_applied { - ctx.check_and_mark_beneficiary_balance_access(&beneficiary); - if let Some(limit) = ctx.volatile_data_tracker.borrow().get_compute_gas_limit() { - ctx.additional_limit.borrow_mut().set_compute_gas_limit(limit); - } - } - - Ok(materialized) - } -} - -impl MegaEvm { - /// This is the hook to be called in the beginning of the `frame_run` and `inspect_frame_run` - /// functions. This function checks if the additional limit is already exceeded, if so, we - /// should immediately stop and synthesize an interpreter action and return it. - #[inline] - fn before_frame_run( - ctx: &MegaContext, - frame: &EthFrame, - ) -> Result, ContextDbError>> { - // Check if the additional limit is already exceeded, if so, we should immediately stop - // and synthesize an interpreter action. - if ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - if let Some(interpreter_result) = - ctx.additional_limit.borrow_mut().before_frame_run(frame) - { - return Ok(Some(InterpreterAction::Return(interpreter_result))); - } - } - Ok(None) - } - - /// This is the hook to be called in the `frame_run` and `inspect_frame_run` - /// functions after the instructions are executed. Apply `MiniRex` additional limits after - /// running instructions. - /// - /// This handles: - /// - Charging `CODEDEPOSIT_STORAGE_GAS` for successful create operations - /// - Updating additional limits via `after_create_frame_run` - /// - Recording gas remaining for later compute gas tracking - /// - /// Returns `Some(gas_remaining)` if `MiniRex` is enabled and action is a Return, - /// for use in `after_frame_run`. - #[inline] - fn after_frame_run_instructions( - ctx: &MegaContext, - frame: &EthFrame, - action: &mut InterpreterAction, - ) -> Result<(), ContextDbError>> { - if !ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - return Ok(()); - } - let is_rex5 = ctx.spec.is_enabled(MegaSpecId::REX5); - - if let InterpreterAction::Return(interpreter_result) = action { - // Charge storage gas cost for the number of bytes - if frame.data.is_create() && interpreter_result.is_ok() { - let code_deposit_storage_gas = constants::mini_rex::CODEDEPOSIT_STORAGE_GAS * - interpreter_result.output.len() as u64; - if !interpreter_result.gas.record_cost(code_deposit_storage_gas) { - interpreter_result.result = InstructionResult::OutOfGas; - } - } - - // REX5+: pre-charge canonical code-deposit compute gas before - // process_next_action commits the CREATE checkpoint. Skip when - // revm's return_create would not charge it; the existing - // limit-side hook below owns the result-marking on exceed. - if is_rex5 && frame.data.is_create() { - let cfg = ctx.cfg(); - if will_return_create_charge_code_deposit( - interpreter_result, - cfg.max_code_size(), - cfg.spec().into(), - cfg.is_eip3541_disabled(), - ) { - let code_len = interpreter_result.output.len() as u64; - let canonical_code_deposit_gas = - code_len.saturating_mul(revm::interpreter::gas::CODEDEPOSIT); - let _ = ctx - .additional_limit - .borrow_mut() - .record_compute_gas(canonical_code_deposit_gas); - } - } - } - - // Update additional limits. MiniRex is guaranteed to be enabled here. - ctx.additional_limit.borrow_mut().after_frame_run_instructions(frame, action); - - Ok(()) - } - - /// Apply `MiniRex` additional limits after frame action processing. - /// - /// Under REX5+ for CREATE results, the code-deposit compute gas was - /// already pre-charged in [`after_frame_run_instructions`]; pass - /// `None` here so the post-action hook does not double-record. - #[inline] - fn after_frame_run( - ctx: &MegaContext, - frame_output: &mut ItemOrResult, - gas_remaining_before_process_action: Option, - ) -> Result<(), ContextDbError>> { - if !ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - return Ok(()); - } - let is_rex5 = ctx.spec.is_enabled(MegaSpecId::REX5); - - if let ItemOrResult::Result(frame_result) = frame_output { - // REX5+: code-deposit compute gas for CREATE results was already - // pre-charged. Skip post-action recording so we don't double-count. - let pass_through = if is_rex5 && matches!(frame_result, FrameResult::Create(_)) { - None - } else { - gas_remaining_before_process_action - }; - ctx.additional_limit.borrow_mut().after_frame_run(frame_result, pass_through); - } - - Ok(()) - } -} - -/// Mirrors `revm_handler::frame::return_create`'s pre-commit predicate. -/// Returns `true` iff `return_create` would charge `code_len * CODEDEPOSIT` -/// from the interpreter gas and commit the checkpoint. -/// -/// REVIEW ON UPSTREAM BUMP: keep in lockstep with -/// `revm-handler::frame::return_create`. Any revm bump that touches the -/// predicate inputs (`is_ok`, EIP-3541 gate, EIP-170 gate, code-deposit -/// gas availability) requires re-auditing this helper. -fn will_return_create_charge_code_deposit( - interpreter_result: &InterpreterResult, - max_code_size: usize, - runtime_spec_id: revm::primitives::hardfork::SpecId, - is_eip3541_disabled: bool, -) -> bool { - use revm::primitives::hardfork::SpecId; - - if !interpreter_result.result.is_ok() { - return false; - } - if !is_eip3541_disabled && - runtime_spec_id.is_enabled_in(SpecId::LONDON) && - interpreter_result.output.first() == Some(&0xEF) - { - return false; - } - if runtime_spec_id.is_enabled_in(SpecId::SPURIOUS_DRAGON) && - interpreter_result.output.len() > max_code_size - { - return false; - } - let code_deposit_gas = (interpreter_result.output.len() as u64) - .saturating_mul(revm::interpreter::gas::CODEDEPOSIT); - interpreter_result.gas.remaining() >= code_deposit_gas -} - -impl Handler - for MegaHandler -where - EVM: EvmTr, Frame = FRAME>, - ERROR: EvmTrError - + From - + From - + FromStringError - + IsTxError - + core::fmt::Debug, - FRAME: FrameTr, -{ - type Evm = EVM; - - type Error = ERROR; - - type HaltReason = MegaHaltReason; - - delegate! { - to self.op { - fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error>; - fn validate_against_state_and_deduct_caller( - &self, - evm: &mut Self::Evm, - ) -> Result<(), Self::Error>; - fn reimburse_caller(&self, evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult) -> Result<(), Self::Error>; - fn refund(&self, evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult, eip7702_refund: i64); - } - } - - fn pre_execution(&self, evm: &mut Self::Evm) -> Result { - self.validate_against_state_and_deduct_caller(evm)?; - self.load_accounts(evm)?; - // EIP-7702 authority state-growth handling, split by spec era. Only type-4 txs reach - // either branch, and no exempt (system-originated) tx is type-4 here — system txs are - // legacy-typed pre-promotion / deposit-typed post-promotion, and a type-4 system caller is - // rejected earlier in `before_run` — so neither branch consults `is_exempt()`. - if evm.ctx().tx().tx_type() == TransactionType::Eip7702 { - if evm.ctx().spec.is_enabled(MegaSpecId::REX6) { - // `validate()` (`record_rex6_eip7702_authority_accounting`) already charged every - // applied authority against the pre-frame resource dimensions it touches (a - // persistent account write on `data_size` + `kv_update`; `state_growth` for net-new - // authorities; and — when an applied authority is the block beneficiary — a lowered - // detention cap that the intrinsic `compute_gas` can then exceed). If any of those - // pushed the tx over a per-tx limit, the first frame halts anyway — but - // `apply_eip7702_auth_list` `mark_touch`es every authority in pre-execution, and a - // HALT (unlike an `Err`) does not roll those pre-frame writes back. Skip the whole - // list so the halt discards them. - // - // Gate on `AdditionalLimit::limit_exceeded()`: that is the exact condition - // `frame_result_if_exceeding_limit` halts on, so skipping here covers every - // pre-frame dimension (`DataSize`/`KVUpdate`/`ComputeGas`/`StateGrowth`) that could - // trigger that halt — including compute overflows and any dimension added later — - // with no risk of the check and the halt disagreeing. (It is false for both - // `WithinLimit` and `Exempt`, matching the halt path.) `Ok(0)` forgoes the - // existing-authority EIP-7702 refund (`post_execution::refund` records it - // unconditionally) — the intended all-or-nothing consequence of skipping the whole - // list (see `test_rex6_authority_state_growth_overflow_forgoes_refund`). - if evm.ctx().additional_limit.borrow().limit_exceeded() { - return Ok(0); - } - } else if evm.ctx().spec.is_enabled(MegaSpecId::REX5) { - // REX5 runs the authority state-growth scan here in pre-execution; REX6 folds it - // into `validate()`'s accounting above instead. - self.record_rex5_eip7702_authority_state_growth(evm)?; - } - } - - self.apply_eip7702_auth_list(evm) - } - - fn run_system_call( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - // system call does not call `pre_execution` and `post_execution`, so we need to extract - // some logic from them. - let ctx = evm.ctx_mut(); - ctx.on_new_tx(); - - // dummy values that are not used. - let init_and_floor_gas = InitialAndFloorGas::new(0, 0); - // call execution and than output. - match self - .execution(evm, &init_and_floor_gas) - .and_then(|exec_result| self.execution_result(evm, exec_result)) - { - out @ Ok(_) => out, - Err(e) => self.catch_error(evm, e), - } - } - - fn run_without_catch_error( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - self.before_run(evm)?; - - let init_and_floor_gas = self.validate(evm)?; - let eip7702_refund = self.pre_execution(evm)? as i64; - let mut exec_result = self.execution(evm, &init_and_floor_gas)?; - self.post_execution(evm, &mut exec_result, init_and_floor_gas, eip7702_refund)?; - - // Prepare the output - self.execution_result(evm, exec_result) - } - - /// This function copies the logic from `revm::handler::Handler::validate` to and - /// add additional storage gas cost for calldata. - /// - /// REX5+ adds a final initial+floor gas validation after all Mega-side dynamic storage gas - /// has been accounted for. Pre-REX5 specs keep the historical mid-sequence check exactly - /// where it was so byte-for-byte replay is preserved. - fn validate(&self, evm: &mut Self::Evm) -> Result { - self.validate_env(evm)?; - let mut initial_and_floor_gas = self.validate_initial_tx_gas(evm)?; - - // REX6 only (gated on type-4 tx + REX6 spec): consolidated EIP-7702 authorization - // accounting. Records the per-applied-authority DataSize/KV/StateGrowth + beneficiary - // detention, and returns the net-new authority addresses so the caller folds the dynamic - // SALT account-creation gas into `initial_gas` before the gas-limit / fee-affordability - // check. Pre-REX6 / non-EIP-7702 produces `Vec::new()` and the SALT-gas loop is a no-op. - let record_rex6_accounting = { - let ctx = evm.ctx(); - ctx.spec.is_enabled(MegaSpecId::REX6) && ctx.tx().tx_type() == TransactionType::Eip7702 - }; - let materialized_authorities = if record_rex6_accounting { - self.record_rex6_eip7702_authority_accounting(evm)? - } else { - Vec::new() - }; - - let ctx = evm.ctx_mut(); - let is_mini_rex_enabled = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex_enabled = ctx.spec.is_enabled(MegaSpecId::REX); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - if is_mini_rex_enabled { - // record the initial gas cost as compute gas cost, limit exceeding will be captured in - // `frame_init` function. - ctx.additional_limit() - .borrow_mut() - .record_compute_gas(initial_and_floor_gas.initial_gas); - - // MegaETH MiniRex modification: calldata storage gas costs (10x the standard EVM rates) - // - Standard tokens: 40 gas per token (vs 4) - // - EIP-7623 floor: 100 gas per token (vs 10) - let tokens_in_calldata = get_tokens_in_calldata(ctx.tx().input(), true); - let calldata_storage_gas = - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_GAS * tokens_in_calldata; - initial_and_floor_gas.initial_gas += calldata_storage_gas; - let floor_calldata_storage_gas = - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_FLOOR_GAS * tokens_in_calldata; - initial_and_floor_gas.floor_gas += floor_calldata_storage_gas; - - // MegaETH Rex modification: additional intrinsic storage gas cost - // Add 39,000 gas on top of base intrinsic gas for all transactions - if is_rex_enabled { - initial_and_floor_gas.initial_gas += constants::rex::TX_INTRINSIC_STORAGE_GAS; - } - - // Pre-REX5: keep the historical mid-sequence initial-gas check here so existing - // stable-spec replays produce exactly the same OOG-after-fee-charge result on - // transactions whose final Mega-adjusted initial_gas exceeds gas_limit only after - // CREATE/new-account storage gas is added below. - // - // REX5+: this mid-sequence check is deferred to the final check below, which runs - // after CREATE/new-account storage gas has also been added so a transaction that - // cannot fit its final Mega-side intrinsic+storage gas is rejected as a validation - // error before pre_execution() debits the sender or bumps the nonce. - if !is_rex5_enabled && initial_and_floor_gas.initial_gas > ctx.tx().gas_limit() { - return Err(InvalidTransaction::CallGasCostMoreThanGasLimit { - gas_limit: ctx.tx().gas_limit(), - initial_gas: initial_and_floor_gas.initial_gas, - } - .into()); - } - - // MegaETH modification: additional storage gas cost for creating account - let kind = ctx.tx().kind(); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - let (callee_address, storage_gas) = match kind { - TxKind::Create => { - let caller = ctx.tx().caller(); - // REX5+: derive the created address from the caller's - // state nonce — the same value `make_create_frame` uses - // for the actual deployment. Pre-REX5 keeps `tx.nonce()`. - let nonce = if is_rex5_enabled { - ctx.journal_mut() - .inspect_account(caller, false) - .map_err(|e| { - Self::Error::from_string(format!( - "Failed to inspect caller account for CREATE storage gas: {e:?}", - )) - })? - .info - .nonce - } else { - ctx.tx().nonce() - }; - let created_address = caller.create(nonce); - - let storage_gas = if is_rex_enabled { - // Rex spec distinguishes between contract creation and account creation. - ctx.create_contract_storage_gas(created_address) - } else { - // Mini-Rex spec does not distinguish between contract creation and account - // creation. - ctx.new_account_storage_gas(created_address) - }; - (created_address, storage_gas) - } - TxKind::Call(address) => { - // Reading emptiness through the journal (instead of the raw DB) is - // observationally equivalent on every spec, relying on two invariants: - // pre-REX6 the journal holds no entries when `validate` runs (each - // transaction's journal is drained at finalize, and access-list warming / - // `deduct_caller` only run in `pre_execution`, after `validate`), so the - // read observes exactly the DB value; and the cold entry the read inserts - // is the call target, which frame init loads for every call transaction - // anyway, so the transaction's returned state gains no new account. - // Under REX6 the authority scan above may have journaled applied - // authorities already; for those the read observes the applied - // delegation, which is the intended REX6 semantics. - let new_account = !ctx.tx().value().is_zero() && - ctx.journal_mut().inspect_account(address, false)?.info.is_empty() && - // If an applied EIP-7702 authorization materializes this recipient, its - // creation gas is charged via the authority SALT gas below — don't - // double-charge the value-transfer new-account gas for the same account. - !materialized_authorities.contains(&address); - let storage_gas = - if new_account { ctx.new_account_storage_gas(address) } else { Some(0) }; - (address, storage_gas) - } - }; - initial_and_floor_gas.initial_gas += storage_gas.ok_or_else(|| { - let err_str = - format!("Failed to get storage gas for callee address: {callee_address}",); - Self::Error::from_string(err_str) - })?; - - // REX6: dynamic SALT account-creation gas for each net-new EIP-7702 authority, - // folded into initial_gas so it is enforced against gas_limit / fee affordability. - // `materialized_authorities` is empty pre-REX6, so this is a no-op on stable specs. - for authority in &materialized_authorities { - let authority_storage_gas = - ctx.new_account_storage_gas(*authority).ok_or_else(|| { - Self::Error::from_string(format!( - "Failed to get storage gas for EIP-7702 authority: {authority}", - )) - })?; - initial_and_floor_gas.initial_gas += authority_storage_gas; - } - - // REX5+: charge dynamic new-account storage gas for a deposit-driven caller - // materialisation (either `tx.mint() > 0` balance increment or pre-execution - // nonce bump). Mirrors the `TxKind::Call(address) with value` branch above, - // but for the caller side. Detection runs here so we observe the pre- - // pre-execution state — `OpHandler::pre_execution` (run after `validate`) is - // what actually materialises the caller account. - // - // `data_size` / `kv_update` are intentionally NOT touched: their - // `before_tx_start` hooks already record the caller's account-info write - // unconditionally for every transaction. Only `state_growth` (which has no - // pre-existing caller-side accounting) and intrinsic gas need the charge. - // Skip this branch inside sandbox contexts: the sandbox view of `caller`'s nonce - // is overridden to 0 by `SandboxDb`, which would mis-classify a previously - // materialised signer as empty on retry. The keyless-deploy outer flow charges - // caller materialisation explicitly via `charge_caller_materialization_pre_sandbox` - // before constructing the sandbox tx, based on the parent journal-visible state. - if is_rex5_enabled && !ctx.is_inside_sandbox() { - let caller = ctx.tx().caller(); - let system_address = ctx.system_address; - if is_deposit_like_transaction(&ctx.inner.tx, system_address) { - // Journal read equivalence: as for the recipient emptiness check above, - // the journal is empty at `validate` time on frozen specs (drained at the - // previous transaction's finalize, warmed only in `pre_execution`), so - // this observes the raw DB value, and the inserted cold entry is the - // caller, which `deduct_caller` loads for every transaction anyway. - let caller_is_empty = - ctx.journal_mut().inspect_account(caller, false)?.info.is_empty(); - if caller_is_empty { - // Self-call corner: if the deposit is a `TxKind::Call(caller)` with - // non-zero `value` AND the same empty caller as callee, the existing - // callee branch above has already charged `new_account_storage_gas(caller)` - // for the same account materialisation. Don't charge the gas a second - // time — but still record the state-growth event (the existing branch - // never records state_growth; the +1 here reflects the single account - // materialisation that pre_execution will perform). - let already_charged_as_callee = matches!( - ctx.tx().kind(), - TxKind::Call(addr) if addr == caller, - ) && !ctx.tx().value().is_zero(); - if !already_charged_as_callee { - let storage_gas = - ctx.new_account_storage_gas(caller).ok_or_else(|| { - let err_str = format!( - "Failed to get storage gas for deposit caller: {caller}", - ); - Self::Error::from_string(err_str) - })?; - initial_and_floor_gas.initial_gas += storage_gas; - } - ctx.additional_limit.borrow_mut().record_deposit_caller_creation(); - } - } - } - - // REX5+: final initial+floor gas validation, after every Mega-side storage gas - // contribution has been added. A transaction that fails either bound is rejected - // here as a canonical validation error so callers see Err(...) rather than an - // ExecutionResult::Halt with full gas spent — i.e. fees and nonce stay untouched - // when the tx cannot fit its final intrinsic+storage gas requirement. - if is_rex5_enabled { - let gas_limit = ctx.tx().gas_limit(); - if initial_and_floor_gas.initial_gas > gas_limit { - return Err(InvalidTransaction::CallGasCostMoreThanGasLimit { - gas_limit, - initial_gas: initial_and_floor_gas.initial_gas, - } - .into()); - } - if initial_and_floor_gas.floor_gas > gas_limit { - return Err(InvalidTransaction::GasFloorMoreThanGasLimit { - gas_limit, - gas_floor: initial_and_floor_gas.floor_gas, - } - .into()); - } - } - } - - Ok(initial_and_floor_gas) - } - - /// This function copies the logic from `revm::handler::Handler::execution` to and - /// add new account storage gas - #[inline] - fn execution( - &mut self, - evm: &mut Self::Evm, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result { - if let Some(oog_frame_result) = self.before_execution(evm, init_and_floor_gas)? { - return Ok(oog_frame_result); - } - - let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas; - // Create first frame action - let first_frame_input = self.first_frame_input(evm, gas_limit)?; - - // Run execution loop - let mut frame_result = self.run_exec_loop(evm, first_frame_input)?; - - // Handle last frame result - self.last_frame_result(evm, &mut frame_result)?; - Ok(frame_result) - } - - fn reward_beneficiary( - &self, - evm: &mut Self::Evm, - exec_result: &mut <::Frame as FrameTr>::FrameResult, - ) -> Result<(), Self::Error> { - if evm.ctx().disable_beneficiary { - return Ok(()); - } - - // Pre-REX6: frozen. Delegate unchanged so stable-spec replay is byte-for-byte — - // the post-execution fee-reward materialisations remain unaccounted exactly as - // historical REX5-and-earlier blocks recorded them. - if !evm.ctx().spec.is_enabled(MegaSpecId::REX6) { - return self.op.reward_beneficiary(evm, exec_result); - } - - // REX6: op-revm credits the beneficiary + fee vaults HERE, after `last_frame_result` - // finalised the trackers — so these writes escape DataSize / KV / StateGrowth unless - // accounted now. Deposit / keyless-sandbox txs credit nothing (op-revm early-returns), - // so the diff naturally records nothing for them. - let snapshots = Self::snapshot_fee_recipients(evm)?; - - self.op.reward_beneficiary(evm, exec_result)?; - - for snapshot in snapshots { - let (balance, now_empty) = - Self::fee_recipient_balance_and_emptiness(evm, snapshot.address)?; - if balance == snapshot.balance { - continue; - } - // One account-info write = 40 bytes DataSize + 1 KV update; a newly materialised - // account also counts as +1 StateGrowth. TX-persistent lane (frames are gone). - let mut limit = evm.ctx().additional_limit.borrow_mut(); - limit.data_size.merge_persistent_usage(ACCOUNT_INFO_WRITE_SIZE); - limit.kv_update.merge_persistent_usage(1); - if snapshot.was_empty && !now_empty { - limit.state_growth.merge_persistent_usage(1); - } - } - - Ok(()) - } - - fn last_frame_result( - &mut self, - evm: &mut Self::Evm, - frame_result: &mut <::Frame as FrameTr>::FrameResult, - ) -> Result<(), Self::Error> { - let is_mini_rex = evm.ctx().spec.is_enabled(MegaSpecId::MINI_REX); - if is_mini_rex { - // Update the additional limit before returning the frame result - evm.ctx().additional_limit.borrow_mut().before_frame_return_result::(frame_result) - } - - // Call the inner last_frame_result function first - // This will finalize gas accounting according to REVM's rules: - // - Spends all gas_limit - // - Only refunds remaining gas if is_ok_or_revert() - self.op.last_frame_result(evm, frame_result)?; - - // After REVM's gas accounting, we need to return the rescued gas from additional limits. - if is_mini_rex { - let ctx = evm.ctx_mut(); - - let additional_limit = ctx.additional_limit.borrow(); - let gas = frame_result.gas_mut(); - gas.erase_cost(additional_limit.rescued_gas); - } - - Ok(()) - } - - fn execution_result( - &mut self, - evm: &mut Self::Evm, - result: <::Frame as FrameTr>::FrameResult, - ) -> Result, Self::Error> { - // Capture volatile data info for error reporting - let volatile_info = evm - .ctx() - .spec - .is_enabled(MegaSpecId::MINI_REX) - .then(|| { - let volatile_data_tracker = evm.ctx().volatile_data_tracker.borrow(); - volatile_data_tracker.get_volatile_data_info() - }) - .flatten(); - - // Deposit-style sandbox txs: bypass op-revm's HaltedDepositPostRegolith conversion so - // that a runtime halt surfaces as `Ok(Halt(actual_reason, actual_gas_used))` instead of - // being squashed into `FailedDeposit(gas_limit)`. The keyless-deploy outer flow needs - // the real halt reason to distinguish runtime halts (which must merge sandbox state and - // charge `sandbox_gas_used` against the outer gas counter) from validation-rejects - // (which still flow through `catch_error` and produce `FailedDeposit`). - let result = if evm.ctx().is_inside_sandbox() && - evm.ctx().tx().tx_type() == DEPOSIT_TRANSACTION_TYPE - { - match core::mem::replace(evm.ctx().error(), Ok(())) { - Err(ContextError::Db(e)) => return Err(e.into()), - Err(ContextError::Custom(e)) => return Err(Self::Error::from_string(e)), - Ok(_) => (), - } - let exec_result = - post_execution_output(evm.ctx(), result).map_haltreason(OpHaltReason::Base); - evm.ctx().journal_mut().commit_tx(); - evm.ctx().chain_mut().clear_tx_l1_cost(); - evm.ctx().local_mut().clear(); - evm.frame_stack().clear(); - exec_result - } else { - self.op.execution_result(evm, result)? - }; - Ok(result.map_haltreason(|reason| { - let mut additional_limit = evm.ctx().additional_limit.borrow_mut(); - if additional_limit.is_exceeding_limit_halt(&reason) { - if let Some(access_type) = volatile_info { - if let Some(halt) = - additional_limit.detained_compute_gas_halt_reason(access_type) - { - return halt; - } - } - // normal additional limit exceeded (no volatile data access, or detention - // was not more restrictive than the per-tx compute gas limit) - additional_limit - .check_limit() - .maybe_halt_reason() - .expect("should have a halt reason") - } else { - // not due to additional limit exceeded - MegaHaltReason::Base(reason) - } - })) - } - - fn catch_error( - &self, - evm: &mut Self::Evm, - error: Self::Error, - ) -> Result, Self::Error> { - let result = self.op.catch_error(evm, error)?; - Ok(result.map_haltreason(MegaHaltReason::Base)) - } -} - -impl InspectorHandler - for MegaHandler> -where - DB: Database, - MegaContext: ContextTr>, - Journal: revm::inspector::JournalExt, - EVM: InspectorEvmTr< - Context = MegaContext, - Frame = EthFrame, - Inspector: Inspector< - <::Evm as EvmTr>::Context, - EthInterpreter, - >, - >, - ERROR: EvmTrError - + From - + From - + FromStringError - + IsTxError - + core::fmt::Debug, -{ - type IT = EthInterpreter; - - fn inspect_run_without_catch_error( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - self.before_run(evm)?; - - let init_and_floor_gas = self.validate(evm)?; - let eip7702_refund = self.pre_execution(evm)? as i64; - let mut frame_result = self.inspect_execution(evm, &init_and_floor_gas)?; - self.post_execution(evm, &mut frame_result, init_and_floor_gas, eip7702_refund)?; - self.execution_result(evm, frame_result) - } - - /// This function copies the logic from `Handler::execution` to add - /// new account storage gas and early OOG check with inspector support. - #[inline] - fn inspect_execution( - &mut self, - evm: &mut Self::Evm, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result { - if let Some(oog_frame_result) = self.before_execution(evm, init_and_floor_gas)? { - return Ok(oog_frame_result); - } - - let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas; - // Create first frame action - let first_frame_input = self.first_frame_input(evm, gas_limit)?; - - // Run execution loop with inspector - let mut frame_result = self.inspect_run_exec_loop(evm, first_frame_input)?; - - // Handle last frame result - self.last_frame_result(evm, &mut frame_result)?; - Ok(frame_result) - } -} - -impl revm::handler::EvmTr for MegaEvm -where - DB: Database, -{ - type Context = MegaContext; - - type Instructions = MegaInstructions; - - type Precompiles = PrecompilesMap; - - type Frame = EthFrame; - - #[inline] - fn ctx(&mut self) -> &mut Self::Context { - &mut self.inner.ctx - } - - #[inline] - fn ctx_ref(&self) -> &Self::Context { - &self.inner.ctx - } - - #[inline] - fn ctx_instructions(&mut self) -> (&mut Self::Context, &mut Self::Instructions) { - (&mut self.inner.ctx, &mut self.inner.instruction) - } - - #[inline] - fn ctx_precompiles(&mut self) -> (&mut Self::Context, &mut Self::Precompiles) { - (&mut self.inner.ctx, &mut self.inner.precompiles) - } - - fn frame_stack(&mut self) -> &mut FrameStack { - &mut self.inner.frame_stack - } - - fn frame_init( - &mut self, - mut frame_init: ::FrameInit, - ) -> Result, ContextDbError> { - let is_mini_rex_enabled = self.ctx().spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX); - let is_rex3_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX3); - let is_rex4_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX4); - let is_rex5_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX5); - let additional_limit = self.ctx().additional_limit.clone(); - - // Check if this is a call to the oracle contract and mark it as accessed. - // This handles both direct transaction calls and internal CALL operations. - // Rex3+: Oracle access gas detention is triggered by SLOAD (not CALL), so skip this - // CALL-based check for Rex3 and later specs. - // - // The check uses `target_address` which equals the oracle address for CALL and - // STATICCALL, but equals the caller's address for CALLCODE and DELEGATECALL (since - // those execute in the caller's state context). CALLCODE and DELEGATECALL are therefore - // never detected here by design — they do not access oracle state. - // - // MiniRex: Only CALL triggers oracle access detection. STATICCALL, CALLCODE, and - // DELEGATECALL bypass it. - // Rex: STATICCALL is added to oracle access detection (unifying CALL-like behavior). - if is_mini_rex_enabled && !is_rex3_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - let detect_oracle = match call_inputs.scheme { - CallScheme::Call => true, - // Rex fixes the bug in MiniRex where STATICCALL bypasses oracle access - // detection. - CallScheme::StaticCall => is_rex_enabled, - // CALLCODE and DELEGATECALL have target_address = caller (not oracle), - // so check_and_mark_oracle_access would never match anyway. - CallScheme::CallCode | CallScheme::DelegateCall => false, - }; - // Mega system address is exempted from volatile data access enforcement. - if detect_oracle && call_inputs.caller != self.ctx().system_address { - let volatile_data_tracker = self.ctx().volatile_data_tracker.clone(); - let mut tracker = volatile_data_tracker.borrow_mut(); - if tracker.check_and_mark_oracle_access(&call_inputs.target_address) { - if let Some(compute_gas_limit) = tracker.get_compute_gas_limit() { - additional_limit.borrow_mut().set_compute_gas_limit(compute_gas_limit); - } - } - } - } - } - - // REX4+: If a TX-level limit is already exceeded (e.g., intrinsic DataSize/KVUpdate - // overflow from before_tx_start), abort before interceptor dispatch. Interceptors - // return synthetic results that skip before_frame_init(), which would otherwise - // catch the exceeded limit. - // - // Gated to REX4 only: pre-REX4 specs use TX-global check_limit() which catches - // intrinsic overflow during execution. Changing pre-REX4 behavior would break replay. - if is_rex4_enabled { - // Separate borrow scope: the RefMut must be dropped before push_empty_frame - // borrows again. - let exceeded = additional_limit - .borrow_mut() - .frame_result_if_exceeding_limit(&frame_init.frame_input); - if let Some(frame_result) = exceeded { - additional_limit.borrow_mut().push_empty_frame(); - return Ok(FrameInitResult::Result(frame_result)); - } - } - - // REX5+: enforce `CALL_STACK_LIMIT` before interceptor dispatch. Interceptors - // short-circuit before revm's `make_call_frame` runs its own depth check, so - // without this guard a system contract could be invoked at unbounded depth. - // Scope mirrors interceptor dispatch (Call/StaticCall only); other schemes still - // flow into revm where its own depth check applies. - if is_rex5_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) && - frame_init.depth > CALL_STACK_LIMIT as usize - { - let frame_result = gen_call_too_deep_result(call_inputs); - additional_limit.borrow_mut().push_empty_frame(); - return Ok(FrameInitResult::Result(frame_result)); - } - } - } - - // System contract interception dispatch. - // Each interceptor checks target address and ABI-decodes function selectors. - // Side-effect interceptors (oracle hint) usually return None. - // Short-circuiting paths return Some(FrameResult). - // These synthetic results skip `AdditionalLimit::before_frame_init`; we only push an - // empty tracking frame to keep the additional-limit stacks aligned. - // - // Only `CALL` and `STATICCALL` enter interceptor dispatch. `CALLCODE` and - // `DELEGATECALL` execute in the caller's state context, so intercepting them - // would apply system-contract logic in the wrong state context — the scheme - // guard enforces this policy explicitly rather than relying on upstream - // call-frame semantics to keep `target_address` distinct. - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { - if let Some(result) = - dispatch_system_contract_interceptors(self.ctx(), call_inputs, frame_init.depth) - { - // Push an empty frame to keep the limit tracker stack balanced: - // `frame_return_result` / `last_frame_result` will pop a frame, but - // `after_frame_init` (which normally pushes) was skipped. - if is_mini_rex_enabled { - additional_limit.borrow_mut().push_empty_frame(); - } - return Ok(FrameInitResult::Result(result)); - } - } - } - - if is_mini_rex_enabled { - if let Some(frame_result) = additional_limit - .borrow_mut() - .before_frame_init(&mut frame_init, self.ctx().journal_mut())? - { - return Ok(FrameInitResult::Result(frame_result)); - } - } - - // call the inner frame_init function to initialize the frame - let init_result = self.inner.frame_init(frame_init)?; - - // Apply the additional limits only when the `MINI_REX` spec is enabled. - if is_mini_rex_enabled { - additional_limit.borrow_mut().after_frame_init(&init_result); - } - - Ok(init_result) - } - - /// This method copies the logic from `revm::handler::EvmTr::frame_run` to and add additional - /// logic before `process_next_action` to handle the additional limit. - #[inline] - fn frame_run( - &mut self, - ) -> Result, ContextDbError> { - let frame = self.inner.frame_stack.get(); - let context = &mut self.inner.ctx; - let instructions = &mut self.inner.instruction; - - // Before frame_run Hook - let mut action = if let Some(action) = Self::before_frame_run(context, frame)? { - action - } else { - frame.interpreter.run_plain(instructions.instruction_table(), context) - }; - - // After frame_run instructions Hook - Self::after_frame_run_instructions(context, frame, &mut action)?; - - // Record gas remaining before frame action processing - let gas_remaining_before = match (&action, context.spec.is_enabled(MegaSpecId::MINI_REX)) { - (InterpreterAction::Return(interpreter_result), true) => { - Some(interpreter_result.gas.remaining()) - } - _ => None, - }; - - // Process the frame action, it may need to create a new frame or return the current frame - // result. - let mut frame_output = frame - .process_next_action::<_, ContextDbError>(context, action) - .inspect(|i| { - if i.is_result() { - frame.set_finished(true); - } - })?; - - // After frame_run Hook - Self::after_frame_run(context, &mut frame_output, gas_remaining_before)?; - - Ok(frame_output) - } - - fn frame_return_result( - &mut self, - mut result: ::FrameResult, - ) -> Result< - Option<::FrameResult>, - ContextDbError, - > { - let ctx = self.ctx_ref(); - let is_mini_rex = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - // Apply the additional limits only when the `MINI_REX` spec is enabled. - if is_mini_rex { - // call the `on_frame_return` function to update the `AdditionalLimit` if the limit is - // exceeded, return the error frame result - ctx.additional_limit.borrow_mut().before_frame_return_result::(&mut result); - } - - // Call the inner frame_return_result function to return the frame result. - let ret = self.inner.frame_return_result(result)?; - - // Rex4+: Re-enable volatile data access when the disabling frame has returned. - // The inner handler has already popped the frame and committed/reverted the journal, - // so journal depth is decremented at this point. If it dropped below disable_depth, - // the frame that invoked disableVolatileDataAccess() has returned and the disable - // should no longer restrict sibling calls. - if self.ctx_ref().spec.is_enabled(MegaSpecId::REX4) { - let depth = self.ctx_ref().journal_ref().depth(); - self.ctx_ref().volatile_data_tracker.borrow_mut().enable_access_if_returning(depth); - } - - Ok(ret) - } -} - -impl revm::inspector::InspectorEvmTr - for MegaEvm -where - DB: Database, - INSP: Inspector>, -{ - type Inspector = INSP; - - fn inspector(&mut self) -> &mut Self::Inspector { - &mut self.inner.inspector - } - - fn ctx_inspector(&mut self) -> (&mut Self::Context, &mut Self::Inspector) { - (&mut self.inner.ctx, &mut self.inner.inspector) - } - - fn ctx_inspector_frame( - &mut self, - ) -> (&mut Self::Context, &mut Self::Inspector, &mut Self::Frame) { - (&mut self.inner.ctx, &mut self.inner.inspector, self.inner.frame_stack.get()) - } - - fn ctx_inspector_frame_instructions( - &mut self, - ) -> (&mut Self::Context, &mut Self::Inspector, &mut Self::Frame, &mut Self::Instructions) { - ( - &mut self.inner.ctx, - &mut self.inner.inspector, - self.inner.frame_stack.get(), - &mut self.inner.instruction, - ) - } - - /// Override `inspect_frame_init` to handle the case when inspector returns early. - /// - /// When an inspector's `call` or `create` hook returns `Some(outcome)`, the default - /// implementation returns early without calling `frame_init`. This means no frame is - /// pushed to the additional limit trackers. However, `frame_return_result` will still - /// be called and expect to pop a frame. - /// - /// To keep the frame stacks aligned, we push a dummy frame when inspector returns early. - #[inline] - fn inspect_frame_init( - &mut self, - mut frame_init: ::FrameInit, - ) -> Result, ContextDbError> { - let (ctx, inspector) = self.ctx_inspector(); - let is_mini_rex_enabled = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex4_enabled = ctx.spec.is_enabled(MegaSpecId::REX4); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - - // Check if inspector wants to skip this call/create - if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - // Inspector intercepted — `frame_init()` is skipped entirely, so neither - // `frame_result_if_exceeding_limit` nor `before_frame_init` would run. - // - // The priority order below mirrors `frame_init`'s exact order so that a - // TX-level additional-limit exceed is reported instead of being shadowed by - // a CallTooDeep guard: - // 1. TX-level limit exceed (REX4+) - // 2. CALL_STACK_LIMIT depth guard (REX5+) - // 3. Deliver the inspector's synthetic output - // Each early-return path calls `frame_end` to keep inspector callbacks paired. - - // (1) REX4+: if a TX-level limit is already exceeded (e.g., intrinsic - // overflow), abort to ensure correct gas rescue before inspector callbacks. - // Gated to REX4 to avoid changing stable spec behavior. - if is_rex4_enabled { - let exceeded = ctx - .additional_limit - .borrow_mut() - .frame_result_if_exceeding_limit(&frame_init.frame_input); - if let Some(mut frame_result) = exceeded { - ctx.additional_limit.borrow_mut().push_empty_frame(); - frame_end(ctx, inspector, &frame_init.frame_input, &mut frame_result); - return Ok(ItemOrResult::Result(frame_result)); - } - } - // (2) REX5+: enforce CALL_STACK_LIMIT for Call/StaticCall so an inspector - // cannot deliver a synthetic call result at unbounded depth, mirroring the - // protection added to `frame_init` before interceptor dispatch. - if is_rex5_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) && - frame_init.depth > CALL_STACK_LIMIT as usize - { - let mut frame_result = gen_call_too_deep_result(call_inputs); - ctx.additional_limit.borrow_mut().push_empty_frame(); - frame_end(ctx, inspector, &frame_init.frame_input, &mut frame_result); - return Ok(ItemOrResult::Result(frame_result)); - } - } - } - // (3) MINI_REX+: push empty frame to keep the limit tracker stack balanced - // (`before_frame_return_result` will pop). - if is_mini_rex_enabled { - ctx.additional_limit.borrow_mut().push_empty_frame(); - } - frame_end(ctx, inspector, &frame_init.frame_input, &mut output); - return Ok(ItemOrResult::Result(output)); - } - - // Normal path - delegate to frame_init (which pushes a real frame) - let frame_input = frame_init.frame_input.clone(); - if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { - let (ctx, inspector) = self.ctx_inspector(); - frame_end(ctx, inspector, &frame_input, &mut output); - return Ok(ItemOrResult::Result(output)); - } - - // Frame created successfully - initialize the interpreter - let (ctx, inspector, frame) = self.ctx_inspector_frame(); - inspector.initialize_interp(frame.interpreter(), ctx); - Ok(ItemOrResult::Item(frame)) - } - - /// This method copies the logic from `MegaEvm::frame_run` with inspector support. - /// It adds the same additional limit checks while using `inspect_instructions` instead of - /// `run_plain`. - #[inline] - fn inspect_frame_run( - &mut self, - ) -> Result, ContextDbError> { - let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); - - let mut action = if let Some(action) = Self::before_frame_run(ctx, frame)? { - action - } else { - inspect_instructions( - ctx, - frame.interpreter(), - inspector, - instructions.instruction_table(), - ) - }; - - // Apply additional limits and storage gas cost - Self::after_frame_run_instructions(ctx, frame, &mut action)?; - - // Record gas remaining before frame action processing - let gas_remaining_before = match (&action, ctx.spec.is_enabled(MegaSpecId::MINI_REX)) { - (InterpreterAction::Return(interpreter_result), true) => { - Some(interpreter_result.gas.remaining()) - } - _ => None, - }; - - // Process the frame action, it may need to create a new frame or return the current frame - // result. - let mut frame_output = frame - .process_next_action::<_, ContextDbError>(ctx, action) - .inspect(|i| { - if i.is_result() { - frame.set_finished(true); - } - })?; - - // After frame_run Hook - Self::after_frame_run(ctx, &mut frame_output, gas_remaining_before)?; - - // Call frame_end for inspector callback - if let ItemOrResult::Result(frame_result) = &mut frame_output { - let (ctx, inspector, frame) = self.ctx_inspector_frame(); - frame_end(ctx, inspector, frame.frame_input(), frame_result); - } - - Ok(frame_output) - } -} - -/// Builds a `FrameResult` matching revm's `make_call_frame` `CallTooDeep` return: -/// `Gas::new(gas_limit)` (no spend, fully refundable to caller via `erase_cost`), -/// empty output, and the caller's `return_memory_offset`. -/// -/// Used by the REX5+ depth guard that runs before system-contract interceptor dispatch. -/// Interceptors short-circuit before revm's own depth check, so without this guard a -/// system contract could be invoked at any call-stack depth. -fn gen_call_too_deep_result(call_inputs: &revm::interpreter::CallInputs) -> FrameResult { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::CallTooDeep, - Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) -} - -/// Builds a top-level `FrameResult` for the case where `validate()` returned an -/// `initial_gas` that exceeds the transaction's `gas_limit` by the time -/// `before_execution` re-checks it. -/// -/// The frame result carries `InstructionResult::OutOfGas` with `Gas::new_spent(gas_limit)` -/// (entire tx budget burnt, no remaining), matching how an EVM-level OOG halt is -/// represented for top-level transactions. The `FrameResult` variant (`Call` vs `Create`) -/// is chosen by `tx_kind` so the downstream output helper can extract the right -/// fields without re-matching on transaction kind. -/// -/// Called from `MegaHandler::before_execution` when `tx.gas_limit() < init_gas`, -/// which can happen after `MegaHandler::validate` has added any MegaETH-specific -/// intrinsic gas (calldata storage gas, REX intrinsic storage gas, callee-side -/// new-account storage gas, or the REX5+ deposit-caller storage gas). -fn gen_oog_frame_result(tx_kind: TxKind, gas_limit: u64) -> FrameResult { - match tx_kind { - TxKind::Call(_address) => FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - Default::default(), - )), - TxKind::Create => FrameResult::Create(CreateOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - None, - )), - } -} diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs deleted file mode 100644 index bc2d8927f..000000000 --- a/crates/mega-evm/src/evm/factory.rs +++ /dev/null @@ -1,218 +0,0 @@ -use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; -use op_revm::L1BlockInfo; -use revm::{context::result::EVMError, Inspector}; - -use crate::{ - DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, MegaContext, - MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, -}; - -/// Factory for creating `MegaETH` EVM instances. -/// -/// The `EvmFactory` is responsible for creating EVM instances configured with `MegaETH`-specific -/// specifications and optimizations. It encapsulates the `external_envs` service and provides -/// methods to create EVM instances with different configurations. -/// -/// # Type Parameters -/// -/// - `Oracle`: The `external_envs` service to provide deterministic external information during EVM -/// execution. Must implement [`ExternalEnvs`] and [`Clone`] traits. -/// -/// # Usage -/// -/// ```rust -/// use alloy_evm::{EvmEnv, EvmFactory}; -/// use mega_evm::{MegaEvmFactory, MegaSpecId}; -/// use revm::database::{CacheDB, EmptyDB}; -/// -/// // Create a factory with default external_envs -/// let factory = MegaEvmFactory::default(); -/// -/// // Create EVM instance -/// let db = CacheDB::::default(); -/// let evm_env = EvmEnv::default(); -/// let evm = factory.create_evm(db, evm_env); -/// ``` -/// -/// # Implementation Details -/// -/// The factory implements [`alloy_evm::EvmFactory`] and provides `MegaETH`-specific -/// customizations through the configured `external_envs` service and chain specifications. -#[derive(derive_more::Debug, Clone)] -#[non_exhaustive] -pub struct MegaEvmFactory { - /// The `external_envs` service to provide deterministic external information during EVM - /// execution. - external_env_factory: ExtEnvFactory, - - /// A builder function to build dynamic precompiles for the EVM. - #[debug(ignore)] - dyn_precompiles_builder: Option, -} - -impl Default for MegaEvmFactory { - /// Creates a new [`EvmFactory`] instance with the default [`DefaultExternalEnvs`]. - /// - /// This is the recommended way to create a factory when no custom `external_envs` is needed. - /// The `DefaultExternalEnvs` provides a no-operation implementation that doesn't perform - /// any external environment queries. - fn default() -> Self { - Self::new() - } -} - -impl MegaEvmFactory { - /// Creates a new [`EvmFactory`] instance with the given `external_envs`. - /// - /// # Parameters - /// - /// - `external_envs`: The `external_envs` service to provide deterministic external information - /// during EVM execution - /// - /// # Returns - /// - /// A new `EvmFactory` instance configured with the provided `external_envs`. - pub fn new() -> Self { - Self { external_env_factory: EmptyExternalEnv, dyn_precompiles_builder: None } - } -} - -impl MegaEvmFactory { - /// Sets the builder function to build dynamic precompiles for the EVM. - pub fn with_dyn_precompiles_builder( - mut self, - dyn_precompiles_builder: DynPrecompilesBuilder, - ) -> Self { - self.dyn_precompiles_builder = Some(dyn_precompiles_builder); - self - } - - /// Returns a reference to the external environment factory. - /// - /// This is useful for inspecting or cloning the factory after construction, - /// since the field is private and the struct is `#[non_exhaustive]`. - pub fn external_env_factory(&self) -> &ExtEnvFactory { - &self.external_env_factory - } - - /// Sets the external environment factory for the EVM. - /// - /// # Parameters - /// - /// - `external_env_factory`: The external environment factory to use for the EVM. - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_external_env_factory( - self, - external_env_factory: NewExtEnvFactory, - ) -> MegaEvmFactory { - MegaEvmFactory { - external_env_factory, - dyn_precompiles_builder: self.dyn_precompiles_builder, - } - } -} - -impl alloy_evm::EvmFactory - for MegaEvmFactory -{ - type Evm>> = - MegaEvm; - type Context = MegaContext; - type Tx = MegaTransaction; - type Error = - EVMError; - type HaltReason = MegaHaltReason; - type Spec = MegaSpecId; - type Precompiles = PrecompilesMap; - - /// Creates a new `Evm` instance with the provided database and EVM environment. - /// - /// This method constructs a new `Context` using the given database, the specification from the - /// EVM environment, and the factory's `external_envs`. It then sets up the transaction, block, - /// config, and chain environment for the context, and finally returns a new `Evm` instance - /// using the [`NoOpInspector`] as the default inspector. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. - /// - /// # Returns - /// - /// A new [`Evm`] instance configured with the provided database and environment. - fn create_evm( - &self, - db: DB, - evm_env: EvmEnv, - ) -> Self::Evm { - let spec_id = *evm_env.spec_id(); - let block_number = evm_env.block_env.number.to(); - let runtime_limits = EvmTxRuntimeLimits::from_spec(spec_id); - let ctx = MegaContext::new(db, spec_id) - .with_external_envs(self.external_env_factory.external_envs(block_number)) - .with_tx(MegaTransaction::default()) - .with_block(evm_env.block_env) - .with_cfg(evm_env.cfg_env) - .with_chain(L1BlockInfo::default()) - .with_tx_runtime_limits(runtime_limits); - // The builder is an external closure with no exhaustive match over `MegaSpecId`, so it - // receives the behavior projection: dynamic precompiles are execution semantics, and a - // builder keyed on exact specs must not see an alias rung during a rollback window. The - // context above keeps the raw rung. - MegaEvm::new(ctx).with_dyn_precompiles( - self.dyn_precompiles_builder - .as_ref() - .map_or_else(Default::default, |builder| builder(spec_id.behavior())), - ) - } - - fn create_evm_with_inspector>>( - &self, - db: DB, - input: EvmEnv, - inspector: I, - ) -> Self::Evm { - Self::create_evm(self, db, input).with_inspector(inspector) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_external_env_factory_getter() { - let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); - - let got: &EmptyExternalEnv = factory.external_env_factory(); - - // Verify the getter returns a stable reference to the same field. - assert!(core::ptr::eq(got, factory.external_env_factory())); - } - - #[test] - fn test_dyn_precompiles_builder_receives_the_behavior_spec() { - use alloy_evm::EvmFactory as _; - use core::sync::atomic::{AtomicU8, Ordering}; - - // The builder must see the behavior projection, never an alias rung: an external - // builder keyed on exact specs would otherwise install a different precompile set - // during a rollback window. - static SEEN_SPEC: AtomicU8 = AtomicU8::new(u8::MAX); - - let factory = - MegaEvmFactory::new().with_dyn_precompiles_builder(std::sync::Arc::new(|spec| { - SEEN_SPEC.store(spec as u8, Ordering::SeqCst); - revm::primitives::HashMap::default() - })); - - let mut evm_env = EvmEnv::::default(); - evm_env.cfg_env.spec = MegaSpecId::MINI_REX_1; - let _evm = factory.create_evm(crate::test_utils::MemoryDatabase::default(), evm_env); - - assert_eq!(SEEN_SPEC.load(Ordering::SeqCst), MegaSpecId::EQUIVALENCE as u8); - } -} diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs deleted file mode 100644 index 2cc8ee2bc..000000000 --- a/crates/mega-evm/src/evm/host.rs +++ /dev/null @@ -1,1282 +0,0 @@ -use core::cell::RefCell; - -#[cfg(not(feature = "std"))] -use alloc as std; -use mega_system_contracts::access_control::IMegaAccessControl::VolatileDataAccessType; -use std::{format, rc::Rc}; - -use crate::{ - AdditionalLimit, ExternalEnvTypes, MegaContext, MegaSpecId, OracleEnv, - VolatileDataAccessTracker, ORACLE_CONTRACT_ADDRESS, -}; -use alloy_evm::Database; -use alloy_primitives::{Address, Bytes, Log, B256, U256}; -use delegate::delegate; -use revm::{ - context::{ContextTr, JournalTr}, - context_interface::{context::ContextError, journaled_state::AccountLoad}, - interpreter::{Host, SStoreResult, SelfDestructResult, StateLoad}, - primitives::{hash_map::Entry, StorageKey, KECCAK_EMPTY}, - state::{Account, Bytecode, EvmStorageSlot}, - Journal, -}; - -impl Host for MegaContext { - // Block environment related methods - with tracking - fn basefee(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BaseFee); - self.inner.basefee() - } - - fn gas_limit(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::GasLimit); - self.inner.gas_limit() - } - - fn difficulty(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::Difficulty); - self.inner.difficulty() - } - - fn prevrandao(&self) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::PrevRandao); - self.inner.prevrandao() - } - - fn block_number(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BlockNumber); - self.inner.block_number() - } - - fn timestamp(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::Timestamp); - self.inner.timestamp() - } - - fn beneficiary(&self) -> Address { - self.mark_block_env_accessed(VolatileDataAccessType::Coinbase); - self.inner.beneficiary() - } - - fn block_hash(&mut self, number: u64) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::BlockHash); - self.inner.block_hash(number) - } - - // Blob-related block environment methods - with tracking - fn blob_gasprice(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BlobBaseFee); - self.inner.blob_gasprice() - } - - fn blob_hash(&self, number: usize) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::BlobHash); - self.inner.blob_hash(number) - } - - delegate! { - to self.inner { - fn chain_id(&self) -> U256; - fn effective_gas_price(&self) -> U256; - fn log(&mut self, log: Log); - fn caller(&self) -> Address; - fn max_initcode_size(&self) -> usize; - fn sstore( - &mut self, - address: Address, - key: U256, - value: U256, - ) -> Option>; - fn tstore(&mut self, address: Address, key: U256, value: U256); - fn tload(&mut self, address: Address, key: U256) -> U256; - } - } - - fn selfdestruct( - &mut self, - address: Address, - target: Address, - ) -> Option> { - // Rex4+: Mark beneficiary balance access when SELFDESTRUCT targets the beneficiary. - // This enables gas detention and the disableVolatileDataAccess check in the instruction - // wrapper. - if self.spec.is_enabled(MegaSpecId::REX4) { - self.check_and_mark_beneficiary_balance_access(&target); - } - - // Rex4+: Before inner selfdestruct mutates account status, inspect the account - // to compute state growth refund for same-TX-created accounts (EIP-6780). - // Uses non-delegating inspect_account to ensure we enumerate storage on the - // actual selfdestructed address, not a delegation target. - let selfdestruct_refund = if self.spec.is_enabled(MegaSpecId::REX4) { - let journal = &mut self.inner.journaled_state; - // inspect_account may fail if DB errors; treat as no refund. - inspect_account(journal, address, false).ok().and_then(|account| { - // Only refund if the account was created in this transaction (EIP-6780: - // only same-TX-created accounts are actually destroyed by SELFDESTRUCT). - // Use CreatedLocal flag which matches revm's is_created_locally() check. - if !account.status.contains(revm::state::AccountStatus::CreatedLocal) { - return None; - } - // Count new storage slots: original was zero, current is non-zero. - let slot_count = account - .storage - .values() - .filter(|slot| { - slot.original_value().is_zero() && !slot.present_value().is_zero() - }) - .count() as u64; - // +1 for the account itself (counted in before_frame_init) + slot count. - Some(1 + slot_count) - }) - } else { - None - }; - - let result = self.inner.selfdestruct(address, target); - - // Record state growth refund only on the first effective destruction. - // Repeated SELFDESTRUCT on the same account still returns a result but with - // `previously_destroyed == true` — refunding again would double-count. - if let Some(refund) = selfdestruct_refund { - if let Some(ref state_load) = result { - if !state_load.data.previously_destroyed { - self.additional_limit.borrow_mut().on_selfdestruct(refund); - } - } - } - - result - } - - fn sload(&mut self, address: Address, key: U256) -> Option> { - if self.spec.is_enabled(MegaSpecId::MINI_REX) && address == ORACLE_CONTRACT_ADDRESS { - // Rex3+: Mark oracle access for gas detention on SLOAD rather than CALL. - // The actual gas limit enforcement happens in the SLOAD instruction wrapper - // (detain_gas_ext::sload in instructions.rs). - // Mega system address transactions are exempted from oracle gas detention. - // Note: This checks the transaction sender (from TxEnv) via Host::caller(), - // unlike the pre-Rex3 CALL-based path which checked the frame-level caller. - if self.spec.is_enabled(MegaSpecId::REX3) && self.caller() != self.system_address { - self.volatile_data_tracker.borrow_mut().check_and_mark_oracle_access(&address); - } - - // if the oracle env provides a value, return it. Otherwise, fallback to the inner - // context. - if let Some(value) = self.oracle_env.borrow().get_oracle_storage(key) { - // Accessing oracle contract storage is forced to be cold access, since it always - // reads from the outside world (oracle_env). - return Some(StateLoad::new(value, true)); - } - } - let state_load = self.inner.sload(address, key); - state_load.map(|mut state_load| { - if self.spec.is_enabled(MegaSpecId::MINI_REX) && address == ORACLE_CONTRACT_ADDRESS { - // It is indistinguishable to tell whether a storage access of oracle contract is - // warm or not even if it is loaded from the inner journal state. This is because - // the current execution may be a replay of existing blocks and we cannot know - // whether the payload builder read from the oracle_env or not. So we force such - // sload always to be cold access to ensure consistent gas cost. - state_load.is_cold = true; - } - state_load - }) - } - - fn balance(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.balance(address) - } - - fn load_account_delegated(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - // Rex6+: also mark the EIP-7702 delegate of `address` if any, so a CALL whose - // target delegates to the beneficiary triggers detention even though the raw stack - // operand doesn't match. The Rex4 path only marked the raw input. A resolve DB error - // falls back to the raw address (no delegate mark) — the `load_account_delegated` below - // remains responsible for surfacing the failure. - if self.spec.is_enabled(MegaSpecId::REX6) { - let resolved = self.best_effort_resolve_eip7702_delegate_address(address); - if resolved != address { - self.check_and_mark_beneficiary_balance_access(&resolved); - } - } - self.inner.load_account_delegated(address) - } - - fn load_account_code(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.load_account_code(address) - } - - fn load_account_code_hash(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.load_account_code_hash(address) - } -} - -/// Extension trait for the `Host` trait that provides additional functionality for `MegaETH`. -/// -/// Gas cost methods (`sstore_set_storage_gas`, `new_account_storage_gas`, -/// `create_contract_storage_gas`) follow the same error-handling pattern as revm's `Host` trait: -/// on error, stash the error in `self.error()` and return `None`. -/// This ensures that `FatalExternalError` always has a stashed error for revm to drain. -pub trait HostExt: Host { - /// Gets the `MegaSpecId` of the current execution context. - fn spec_id(&self) -> MegaSpecId; - - /// Gets the `AdditionalLimit` instance. Only used when the `MINI_REX` spec is enabled. - fn additional_limit(&self) -> &Rc>; - - /// Gets the gas cost for setting a storage slot to a non-zero value. Only used when the - /// `MINI_REX` spec is enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn sstore_set_storage_gas(&mut self, address: Address, key: U256) -> Option; - - /// Gets the gas cost for creating a new account. Only used when the `MINI_REX` spec is enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn new_account_storage_gas(&mut self, address: Address) -> Option; - - /// Gets the gas cost for creating a new contract. Only used when the `REX` spec is - /// enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn create_contract_storage_gas(&mut self, address: Address) -> Option; - - /// Gets the volatile data tracker. Only used when the `MINI_REX` spec is enabled. - fn volatile_data_tracker(&self) -> &Rc>; - - /// Checks if volatile data access should cause a revert at the current call depth. - /// Returns `true` if `disableVolatileDataAccess()` was called and the current - /// journal depth is deeper than the activation depth. - fn volatile_access_disabled(&self) -> bool; - - /// Returns the block beneficiary address without triggering volatile data tracking. - /// Used by instruction handlers to pre-check whether an opcode targets the beneficiary. - fn beneficiary_address(&self) -> Address; - - /// Resolves the EIP-7702 delegate of `address` one hop on a best-effort basis, returning - /// `address` itself when there is no delegate or when the resolve hits a DB error. - /// - /// Unlike [`JournalInspectTr::resolve_eip7702_delegate_address`], a DB failure here is NOT - /// stashed in `self.error()`. This is for prechecks and side-marks (the beneficiary-volatile - /// guard, the detention side-mark) that compare the delegate against a known address and must - /// never turn a transaction into an error on their own — e.g. a malformed CALL that underflows - /// before it ever runs the target must keep its `StackUnderflow`, not a spurious DB error from - /// eagerly loading a delegate's code it never needs. The opcode's real execution path reads the - /// account again and owns surfacing any genuine DB error. - fn best_effort_resolve_eip7702_delegate_address(&mut self, address: Address) -> Address; -} - -impl HostExt for MegaContext { - #[inline] - fn spec_id(&self) -> MegaSpecId { - self.spec - } - - #[inline] - fn additional_limit(&self) -> &Rc> { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - &self.additional_limit - } - - #[inline] - fn sstore_set_storage_gas(&mut self, address: Address, key: U256) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - // System-tx exemption (REX6+ `LimitCheck::Exempt` stamp): charge un-scaled (min-bucket) - // storage gas so the write never depends on SALT bucket capacity and can never OOG as - // buckets grow. This path also avoids querying the SALT env. - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().sstore_set_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().sstore_set_gas(address, key); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn new_account_storage_gas(&mut self, address: Address) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().new_account_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().new_account_gas(address); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn create_contract_storage_gas(&mut self, address: Address) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().create_contract_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().create_contract_gas(address); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn volatile_data_tracker(&self) -> &Rc> { - &self.volatile_data_tracker - } - - #[inline] - fn volatile_access_disabled(&self) -> bool { - let current_depth = self.journal_ref().depth(); - self.volatile_data_tracker.borrow().volatile_access_disabled(current_depth) - } - - #[inline] - fn beneficiary_address(&self) -> Address { - self.inner.block.beneficiary - } - - #[inline] - fn best_effort_resolve_eip7702_delegate_address(&mut self, address: Address) -> Address { - // Resolve through the journal directly so a DB error propagates as `Err` here (and is - // discarded) rather than being stashed into `self.error()` by - // `MegaContext::inspect_account`. - let spec = self.spec; - self.inner - .journaled_state - .resolve_eip7702_delegate_address(spec, address) - .unwrap_or(address) - } -} - -/// Trait to inspect the journal's internal state without marking any accounts or storage slots as -/// warm. -/// -/// # EIP-7702 address semantics -/// -/// Address handling is intentionally split by call-site purpose. The guiding rule: follow the -/// delegate ONLY to (1) execute the delegate's code and (2) decide whether an operand observes the -/// block beneficiary's state. Everything that *attributes* balance / nonce / storage / state-growth -/// / data-size uses the ORIGINAL address — a delegated account's state is its own, not the -/// delegate's. Before adding a new 7702-touching call site, find its row in this table and use the -/// listed address; do not re-derive the raw-vs-delegate decision ad-hoc. -/// -/// | Purpose | Address | Mechanism | Spec gate | -/// | --- | --- | --- | --- | -/// | Code / execution target | delegate | revm's `load_account_delegated` (not these primitives) | revm-owned | -/// | Storage / SALT / state-growth / account-write accounting | original | `inspect_account` | REX5+ original; pre-REX5 followed the delegate (frozen) | -/// | CALL-family beneficiary / volatile-access check | delegate | `resolve_eip7702_delegate_address` | REX6+ only; `<=` REX5 compares the raw operand (frozen) | -/// | Validate-time authorization accounting | original authority | `inspect_account` with `load_code = true` (EIP-7702 / EIP-3607 detection) | scan-wide | -/// -/// `inspect_account_delegated` follows the delegate; it backs the frozen pre-REX5 accounting path -/// and any caller that genuinely needs the delegate's account. New accounting call sites should use -/// `inspect_account` (original address), not this. -/// -/// To improve performance, when journal does not have the account or storage slot, it will be -/// loaded from the database and cached in the journal. -/// However, since we explicitly mark the account or storage slot as cold, this pre-loading before -/// executing the original instruction will make no difference on gas cost. -/// -/// Both `Journal` and `MegaContext` implement this trait: -/// - `Journal`: `DBError = DB::Error` — returns DB errors for propagation. -/// - `MegaContext`: `DBError = ()` — stashes errors in `self.error()` and returns `Err(())`. -pub trait JournalInspectTr { - /// The error type returned on DB failures. - type DBError: core::fmt::Debug; - - /// Inspect the account at the given address without marking it as warm and without - /// following EIP-7702 delegation. - /// - /// Loads the account from the database into the journal cache (so subsequent - /// in-block reads see this committed state), then explicitly marks it cold so the - /// inspection does not show up in EIP-2929's access list and produces no - /// `account_warmed` journal entry. Use this for metering inspections where the - /// authority's own state matters (e.g., new-account storage-gas premium, SALT - /// bucket lookup, state-growth emptiness check) rather than the delegate's state, - /// and for validate-path reads (nonce, code) that must not participate in the - /// access-list accounting the execution path will perform later. - /// - /// When `load_code` is `true`, additionally invokes `code_by_hash` if the database - /// left `info.code` lazy (production reth-style `StateProviderDatabase::basic` - /// returns `code: None` for accounts with on-chain bytecode, deferring code load). - /// Set this only on call sites that read `info.code` (EIP-7702 detection, EIP-3607 - /// check) — the cheaper `false` path skips `code_by_hash` for every other cold - /// first-touch. Parallels revm's `JournalTr::load_account_optional(.., load_code, - /// ..)` shape. - fn inspect_account( - &mut self, - address: Address, - load_code: bool, - ) -> Result<&mut Account, Self::DBError>; - - /// Inspect the account at the given address without marking it as warm. - /// If the account is EIP-7702 type, follows delegation. - /// - /// Starting from REX4, resolves exactly one hop (matching upstream revm behavior). - /// Pre-REX4, follows delegation recursively but detects cycles to prevent stack overflow. - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, Self::DBError>; - - /// Inspect the storage at the given address and key without marking it as warm. - /// - /// Starting from REX4, storage is always loaded from the original address without following - /// EIP-7702 delegation (matching upstream revm's sload behavior). - /// Pre-REX4 specs retain the original behavior that follows delegation. - fn inspect_storage( - &mut self, - spec: MegaSpecId, - address: Address, - key: StorageKey, - ) -> Result<&EvmStorageSlot, Self::DBError>; - - /// Resolve the EIP-7702 delegate of `address` one hop and return the target address. - /// - /// Returns `address` itself when the account is not EIP-7702-delegated. Hydrates `info.code` - /// on REX5+ so EIP-7702 detection works against lazy-code databases (mirrors - /// `inspect_account_delegated`'s rule for stable-spec freeze). - /// - /// Callers gate this on REX6 (the only place it is used). EIP-7702 does not exist on earlier - /// specs, so an account there simply has no delegate code and resolves to `address` — no - /// pre-REX4 special case is needed. - /// - /// Useful for instruction-wrapper checks that need to compare the effective code-running - /// address against a known target (e.g., the block beneficiary) before delegating to revm. - fn resolve_eip7702_delegate_address( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result { - let load_code = spec.is_enabled(MegaSpecId::REX5); - let account = self.inspect_account(address, load_code)?; - let delegate = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(c) => Some(c.address()), - _ => None, - }); - Ok(delegate.unwrap_or(address)) - } -} - -/// Load an account into the journal cache without following EIP-7702 delegation -/// and mark it cold. When `load_code` is `true`, additionally invokes -/// `code_by_hash` if the database left `info.code` lazy. -/// -/// The occupied branch's `code_by_hash` hydration is load-bearing and must -/// stay: removing it would shift observable behavior on stable specs (a second -/// `inspect_account` against the same lazy-code DB would no longer see hydrated -/// code). -fn inspect_account( - journal: &mut Journal, - address: Address, - load_code: bool, -) -> Result<&mut Account, ::Error> { - let transaction_id = journal.transaction_id; - match journal.inner.state.entry(address) { - Entry::Occupied(entry) => { - let account = entry.into_mut(); - if account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { - // Load code if not loaded before - account.info.code = Some(journal.database.code_by_hash(account.info.code_hash)?); - } - Ok(account) - } - Entry::Vacant(entry) => { - let mut account = journal - .database - .basic(address)? - .map(|info| info.into()) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - if load_code && account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { - account.info.code = Some(journal.database.code_by_hash(account.info.code_hash)?); - } - // deliberately mark the account as cold since we are only inspecting it, not warming - // it. - account.mark_cold(); - Ok(entry.insert(account)) - } - } -} - -/// Cold occupancy read that returns an account's `code_hash` and loads it into the journal (so it -/// appears in the returned `EvmState` / witness) but — unlike [`inspect_account`] — never hydrates -/// `info.code`, even when the account is already resident (`inspect_account`'s already-loaded -/// branch force-loads code via `code_by_hash` regardless of its `load_code` argument). An occupancy -/// check needs only the hash; forcing `code_by_hash` on an already-warmed occupied address would -/// require its bytecode in a stateless witness that need only carry the account proof, turning the -/// expected revert into a spurious DB error on replay. -/// -/// Only [`Journal`] needs this (the REX6 keyless-deploy occupancy check calls it on -/// `ctx.journal_mut()`), so it is a free function rather than a `JournalInspectTr` method. -pub(crate) fn inspect_account_code_hash( - journal: &mut Journal, - address: Address, -) -> Result::Error> { - let transaction_id = journal.transaction_id; - match journal.inner.state.entry(address) { - Entry::Occupied(entry) => Ok(entry.get().info.code_hash), - Entry::Vacant(entry) => { - let mut account = journal - .database - .basic(address)? - .map(|info| info.into()) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - account.mark_cold(); - Ok(entry.insert(account).info.code_hash) - } - } -} - -impl JournalInspectTr for Journal { - type DBError = ::Error; - - fn inspect_account( - &mut self, - address: Address, - load_code: bool, - ) -> Result<&mut Account, Self::DBError> { - inspect_account(self, address, load_code) - } - - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, Self::DBError> { - // REX5+ hydrates code before the 7702 detection below; pre-REX5 must not — - // stable specs preserve the latent lazy-DB EIP-7702 detection gap. - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - - let account = inspect_account(self, address, is_rex5_enabled)?; - - let delegated_address = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(code) => Some(code.address()), - _ => None, - }); - let Some(delegated_address) = delegated_address else { - // Not delegated — reload to satisfy borrow checker and return. - let account = self.inner.state.get_mut(&address).unwrap(); - return Ok(account); - }; - - if spec.is_enabled(MegaSpecId::REX4) { - // REX4+: resolve exactly one hop (matching upstream revm behavior). - return inspect_account(self, delegated_address, is_rex5_enabled); - } - - // Pre-REX4: follow delegation recursively with cycle detection. - // Stays on non-hydrating `inspect_account` (load_code = false) deliberately — - // pre-REX4 is pre-REX5, so the lazy-DB EIP-7702 detection gap is the frozen - // behavior on these specs. - let mut current = delegated_address; - let mut visited = std::vec![address]; - loop { - let account = inspect_account(self, current, false)?; - let next = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(code) => Some(code.address()), - _ => None, - }); - let Some(next) = next else { - // End of chain — reload and return. - let account = self.inner.state.get_mut(¤t).unwrap(); - return Ok(account); - }; - if visited.contains(&next) { - // Cycle detected — stop here. - let account = self.inner.state.get_mut(¤t).unwrap(); - return Ok(account); - } - visited.push(current); - current = next; - } - } - - fn inspect_storage( - &mut self, - spec: MegaSpecId, - address: Address, - key: StorageKey, - ) -> Result<&EvmStorageSlot, Self::DBError> { - let transaction_id = self.transaction_id; - let is_rex4_enabled = spec.is_enabled(MegaSpecId::REX4); - // EIP-7702 storage semantics: storage belongs to the original address (delegator), - // not the delegate. So `is_created` must be checked on the original address — an - // EOA delegating via 7702 is never CREATEd, so its flag is always false. Checking - // the delegate's flag instead would mistakenly short-circuit storage reads when the - // delegate happens to be a freshly-CREATEd contract in the same tx, corrupting - // SSTORE accounting (gas / kv_updates / data_size) on the delegator's slots. - // Fold two inspect_account calls into one hydrating load on REX4 path. - // inspect_account's occupied branch hydrates lazy code unconditionally, - // so the old second (always-occupied) pass hydrated the same code that - // load_code=true hydrates inline here — identical final account state, - // identical DB-call sequence and error position, one fewer state.entry lookup. - // Newly-created accounts must short-circuit storage misses to ZERO before any DB call. - // Querying here would otherwise trigger a witness lookup for a slot with no meaningful - // pre-state value, which breaks stateless replay when CREATE lands on a pre-funded - // address: its `Loaded` cache status bypasses revm's `State::storage` short-circuit and - // exposes the call to the witness backend. - let is_newly_created; - let account = if is_rex4_enabled { - let account = inspect_account(self, address, true)?; - is_newly_created = account.is_created(); - debug_assert!(account.info.code_hash == KECCAK_EMPTY || account.info.code.is_some()); - account - } else { - // Non-REX4: is_created must be read on the original address (an EOA delegating - // via 7702 is never CREATEd), but the storage account follows delegation — - // genuinely two different accounts, so the two loads cannot be folded. - is_newly_created = inspect_account(self, address, false)?.is_created(); - self.inspect_account_delegated(spec, address)? - }; - // REX4/REX5 hot path: use entry() API for a single HashMap probe. - // The prologue guarantees the account is in inner.state; reload via get_mut - // to narrow the borrow from &mut self to &mut inner.state, keeping - // self.database reachable for the miss path. - if is_rex4_enabled { - let account = self.inner.state.get_mut(&address).unwrap(); - return match account.storage.entry(key) { - Entry::Occupied(entry) => Ok(entry.into_mut()), - Entry::Vacant(entry) => { - let slot_value = if is_newly_created { - U256::ZERO - } else { - self.database.storage(address, key)? - }; - let mut slot = EvmStorageSlot::new(slot_value, transaction_id); - slot.mark_cold(); - Ok(entry.insert(slot)) - } - }; - } - - // Pre-REX4: original contains_key + reload pattern (genuinely two different accounts). - if account.storage.contains_key(&key) { - // Need to reload account to satisfy borrow checker. - let account = self.inspect_account_delegated(spec, address)?; - return Ok(account.storage.get(&key).unwrap()); - } - // Slot doesn't exist. For newly-created accounts, post-CREATE storage is - // guaranteed empty (EIP-161 / EIP-6780), so return ZERO without touching the DB. - let slot_value = - if is_newly_created { U256::ZERO } else { self.database.storage(address, key)? }; - let mut slot = EvmStorageSlot::new(slot_value, transaction_id); - // deliberately mark the slot as cold since we are only inspecting it, not warming it - slot.mark_cold(); - // Load account again to bypass the borrow checker and insert the slot - let account = self.inspect_account_delegated(spec, address)?; - account.storage.insert(key, slot); - // Return reference to the newly inserted slot - Ok(account.storage.get(&key).expect("slot should exist")) - } -} - -/// `MegaContext` delegates to `Journal` and stashes DB errors via `self.error()`. -/// -/// On DB error, the real error is stashed as `ContextError::Custom` and `Err(())` is returned. -/// Callers should halt with `FatalExternalError` when receiving `Err`. -impl JournalInspectTr for MegaContext { - type DBError = (); - - fn inspect_account(&mut self, address: Address, load_code: bool) -> Result<&mut Account, ()> { - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_account(address, load_code).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) - } - - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, ()> { - // Split borrow: `journaled_state` and `error` are sibling fields on the inner context, - // so we can borrow them independently to avoid the double-call workaround. - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_account_delegated(spec, address).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) - } - - fn inspect_storage( - &mut self, - spec: MegaSpecId, - address: Address, - key: StorageKey, - ) -> Result<&EvmStorageSlot, ()> { - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_storage(spec, address, key).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256}; - use core::cell::Cell; - use revm::{ - primitives::HashMap, - state::{AccountInfo, Bytecode}, - Database, - }; - - /// Minimal `revm::Database` implementation that mimics the production - /// `reth`-style `StateProviderDatabase` contract: `basic()` returns - /// `AccountInfo { code: None, code_hash: }` for accounts with - /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via - /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — - /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache - /// miss against it would always see the code already hydrated. - #[derive(Default)] - struct LazyCodeDatabase { - accounts: HashMap, - codes: HashMap, - storage_calls: Cell, - } - - impl LazyCodeDatabase { - fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { - let code = Bytecode::new_raw(bytecode); - let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); - self.codes.insert(code_hash, code); - self - } - - fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { - let code = Bytecode::new_eip7702(delegate); - let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); - self.codes.insert(code_hash, code); - self - } - - fn storage_calls(&self) -> usize { - self.storage_calls.get() - } - } - - impl revm::Database for LazyCodeDatabase { - type Error = core::convert::Infallible; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without - // populating `code`, even when the account has on-chain bytecode. - Ok(self.accounts.get(&address).cloned()) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) - } - - fn storage(&mut self, _address: Address, _index: U256) -> Result { - self.storage_calls.set(self.storage_calls.get() + 1); - Ok(U256::ZERO) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } - } - - /// `inspect_account(addr, false)` must not hydrate `info.code` on the vacant - /// branch — callers that need it pass `load_code = true`. - #[test] - fn test_inspect_account_vacant_path_does_not_hydrate_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); // PUSH1 1 PUSH1 1 ADD - let expected_hash = keccak256(&bytecode); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let account = - inspect_account(&mut journal, ADDR, false).expect("inspect_account must succeed"); - - assert_eq!( - account.info.code_hash, expected_hash, - "code_hash must propagate from the database's `basic()` result", - ); - assert!( - account.info.code.is_none(), - "`load_code = false` must leave `info.code` as-is on the vacant branch", - ); - } - - /// `inspect_account(addr, true)` hydrates `info.code` from `code_by_hash` on - /// first cold inspection against a lazy-code database. - #[test] - fn test_inspect_account_with_load_code_hydrates_lazy_bytecode_on_first_touch() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); - let mut journal = Journal::new(db); - - let account = inspect_account(&mut journal, ADDR, true) - .expect("inspect_account must succeed on first cold-touch"); - let hydrated = account - .info - .code - .as_ref() - .expect("`load_code = true` must populate `info.code` from code_by_hash"); - assert_eq!( - hydrated.original_bytes().as_ref(), - bytecode.as_ref(), - "hydrated bytecode must match what `code_by_hash` would return", - ); - } - - /// The occupied-branch hydration must keep firing — a second `inspect_account` - /// against the same lazy-DB address must observe hydrated `info.code` even with - /// `load_code = false`. - #[test] - fn test_inspect_account_occupied_branch_hydrates_on_second_inspection() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let first_code_hash = inspect_account(&mut journal, ADDR, false) - .expect("first inspection must succeed") - .info - .code_hash; - let second = - inspect_account(&mut journal, ADDR, false).expect("second inspection must succeed"); - - assert_eq!( - second.info.code_hash, first_code_hash, - "code_hash must be identical across cache miss and cache hit", - ); - assert!( - second.info.code.is_some(), - "second inspection must observe the hydrated code via the occupied-branch \ - `code_by_hash` load", - ); - } - - /// `inspect_account(addr, true)` must short-circuit on EOAs — the `code_hash != - /// KECCAK_EMPTY` guard keeps `code_by_hash` off the hot path. - #[test] - fn test_inspect_account_with_load_code_leaves_eoa_code_empty() { - const EOA: Address = address!("00000000000000000000000000000000000000cc"); - - let mut db = LazyCodeDatabase::default(); - db.accounts.insert( - EOA, - AccountInfo { - balance: U256::from(1_000_000u64), - nonce: 5, - code_hash: KECCAK_EMPTY, - code: None, - }, - ); - let mut journal = Journal::new(db); - - let account = inspect_account(&mut journal, EOA, true) - .expect("inspect_account must succeed and be a no-op on EOAs"); - assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); - assert!( - account.info.code.is_none(), - "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ - `code_by_hash` off the hot path for accounts without on-chain code", - ); - } - - /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate - /// `info.code` — on either branch. In particular the occupied branch must not fall through to - /// `code_by_hash` the way `inspect_account(.., false)` does (see - /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets the - /// REX6 keyless-deploy occupancy check decide on the hash alone, without demanding an - /// already-warmed occupied address's bytecode in a stateless witness carrying only its proof. - #[test] - fn test_inspect_account_code_hash_never_hydrates_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let expected_hash = keccak256(&bytecode); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - // Vacant cache-miss: returns the hash from `basic()` without hydrating code. - let vacant_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("vacant read must succeed"); - assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "vacant branch must not hydrate info.code", - ); - - // The address is now resident with `code == None`. `inspect_account` would hydrate on this - // occupied branch; `inspect_account_code_hash` must not. - let occupied_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("occupied read must succeed"); - assert_eq!( - occupied_hash, expected_hash, - "occupied branch must return the cached code_hash" - ); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "inspect_account_code_hash must NOT hydrate info.code on the occupied branch", - ); - } - - /// `resolve_eip7702_delegate_address` hydrates lazy delegation bytecode only from REX5: - /// pin both sides of the boundary so a shifted gate (e.g. REX4) fails here. At REX4 a - /// lazy-code delegator resolves to itself (its `0xef0100…` code is never loaded); at REX5 - /// the same first cold touch loads the code and follows the hop. - #[test] - fn test_resolve_eip7702_delegate_loads_code_from_rex5_exactly() { - const DELEGATOR: Address = address!("00000000000000000000000000000000000000e1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000e2"); - - // REX4: no hydration — the delegation is invisible and resolution degrades to identity. - let db = LazyCodeDatabase::default().with_eip7702_delegation(DELEGATOR, DELEGATE); - let mut journal = Journal::new(db); - let resolved = journal - .resolve_eip7702_delegate_address(MegaSpecId::REX4, DELEGATOR) - .expect("resolve must succeed"); - assert_eq!(resolved, DELEGATOR, "REX4 must not load code, so the hop is not followed"); - assert!( - journal.inner.state.get(&DELEGATOR).is_some_and(|a| a.info.code.is_none()), - "REX4 resolution must leave the delegator's code lazy", - ); - - // REX5: the first cold touch hydrates the delegation bytecode and follows the hop. - let db = LazyCodeDatabase::default().with_eip7702_delegation(DELEGATOR, DELEGATE); - let mut journal = Journal::new(db); - let resolved = journal - .resolve_eip7702_delegate_address(MegaSpecId::REX5, DELEGATOR) - .expect("resolve must succeed"); - assert_eq!(resolved, DELEGATE, "REX5 must hydrate the code and follow the hop"); - } - - /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the - /// very first cold inspection against a lazy-code database. Regression guard: - /// any refactor that re-introduces a code-None branch silently degrades the - /// walk to "treat the delegator as a regular EOA". - #[test] - fn test_inspect_account_delegated_follows_eip7702_on_cold_first_touch() { - use revm::context::JournalTr; - - const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); - let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); // PUSH1 0x42 PUSH1 0 SSTORE - - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_bytecode.clone()); - - let mut journal = Journal::new(db); - - let resolved = journal - .inspect_account_delegated(MegaSpecId::REX5, DELEGATOR) - .expect("inspect_account_delegated must succeed on a cold-cache first touch"); - - // The resolved account must be the delegate, not the delegator. The only way - // to distinguish them is the code: the delegator's code is the EIP-7702 - // designation pointing at DELEGATE; the delegate's code is the raw bytecode. - let hydrated = resolved.info.code.as_ref().expect( - "delegate's bytecode must be hydrated by the inner inspect_account call — \ - without the vacant-path hydration, the cold-touch on DELEGATE would leave \ - code as None and any subsequent EIP-7702 walk would see a wrongly-empty target", - ); - assert!( - !matches!(hydrated, Bytecode::Eip7702(_)), - "resolved account must NOT be the delegator (whose code is the EIP-7702 \ - designation); got: {hydrated:?}", - ); - assert_eq!( - hydrated.original_bytes().as_ref(), - delegate_bytecode.as_ref(), - "resolved account's code must match the delegate's raw bytecode — confirms \ - the delegation was followed exactly one hop", - ); - } - - /// Pre-REX5 `inspect_account_delegated` must NOT hydrate `info.code` — the - /// latent EIP-7702 lazy-DB detection gap is the frozen observable behavior of - /// stable specs (hydrating would flip `state_clear_aware_is_empty` and the - /// SALT-bucket nonce in CALL/CREATE/state-growth, breaking spec immutability). - #[test] - fn test_inspect_account_delegated_does_not_hydrate_pre_rex5() { - use revm::context::JournalTr; - - const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); - let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); - - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_bytecode); - - let mut journal = Journal::new(db); - - // REX4 (pre-REX5): the one-hop walk runs but `code = None` against the - // lazy DB hides the 7702 designation, so the walk returns the delegator. - let resolved = journal - .inspect_account_delegated(MegaSpecId::REX4, DELEGATOR) - .expect("inspect_account_delegated must succeed on pre-REX5"); - - assert!( - resolved.info.code.is_none(), - "pre-REX5: `inspect_account_delegated` must NOT hydrate `info.code` — the \ - latent lazy-DB EIP-7702 detection gap on stable specs is intentionally \ - preserved. Resolved account's code: {:?}", - resolved.info.code, - ); - } - - /// Pins the `LazyCodeDatabase` fixture's contract against the production - /// `revm::Database` shape it is modeling: `basic()` returns - /// `code: None` for known accounts, `None` for unknown addresses; - /// `code_by_hash()` falls back to empty bytecode for an unknown hash; - /// `storage()` and `block_hash()` are inert stubs (no tests exercise them via - /// `inspect_account`, but they must remain wired so the fixture is a complete - /// `revm::Database`). If the fixture ever drifts (e.g. someone "helpfully" - /// makes `basic()` eagerly populate `code` like `MemoryDatabase` does), the - /// inspect-account tests above silently lose their load-bearing property — - /// this test fails fast in that case. - #[test] - fn test_lazy_code_database_fixture_pins_reth_style_contract() { - const KNOWN: Address = address!("00000000000000000000000000000000000000ee"); - let bytecode = Bytes::from_static(&[0x00]); - let mut db = LazyCodeDatabase::default().with_account_code(KNOWN, bytecode); - - let known = db.basic(KNOWN).unwrap().expect("known account must resolve"); - assert!( - known.code.is_none(), - "LazyCodeDatabase::basic must NOT pre-populate code — that is the \ - behavior `inspect_account` is being tested against", - ); - assert!( - db.basic(Address::ZERO).unwrap().is_none(), - "unknown address must return None from basic()", - ); - - let unknown_hash = keccak256([0xffu8]); - assert_eq!( - db.code_by_hash(unknown_hash).unwrap().original_bytes().len(), - 0, - "unknown code_hash must fall back to empty bytecode", - ); - - assert_eq!(db.storage(KNOWN, U256::ZERO).unwrap(), U256::ZERO); - assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); - } - - // === inspect_storage coverage tests (PR #334) === - - #[test] - fn test_inspect_storage_rex4_slot_hit_returns_existing_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(3); - let expected_value = U256::from(42); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected_value, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let spec = MegaSpecId::REX4; - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on existing slot"); - - assert_eq!( - slot.present_value, expected_value, - "REX4 slot hit must return the pre-seeded value" - ); - assert!(slot.is_cold, "inspected slot must remain cold"); - } - - #[test] - fn test_inspect_storage_rex4_slot_miss_inserts_and_returns_db_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000cc"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(7); - let spec = MegaSpecId::REX4; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on absent slot"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "absent slot on non-created account must return ZERO from database" - ); - assert!(slot.is_cold, "newly inserted slot must be marked cold"); - - let calls_after_first = journal.database.storage_calls(); - let slot2 = - journal.inspect_storage(spec, ADDR, key).expect("second inspect_storage must succeed"); - - assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); - assert_eq!( - journal.database.storage_calls(), - calls_after_first, - "second inspect_storage on the same slot must hit the cache, not the DB", - ); - } - - #[test] - fn test_inspect_storage_rex4_newly_created_short_circuits_db() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - { - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - account.mark_created(); - } - - let key = U256::from(1); - let spec = MegaSpecId::REX4; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on newly-created account"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "newly-created account must return ZERO without querying database" - ); - assert!(slot.is_cold, "slot must be marked cold"); - } - - #[test] - fn test_inspect_storage_pre_rex4_uses_delegation_path() { - const ADDR: Address = address!("00000000000000000000000000000000000000ee"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000ed"); - let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(ADDR, DELEGATE) - .with_account_code(DELEGATE, delegate_code); - let mut journal = Journal::new(db); - - let key = U256::from(5); - let expected = U256::from(123); - let spec = MegaSpecId::MINI_REX; - - // Preload the delegator so the subsequent occupied-branch inspection hydrates the - // EIP-7702 designation and the pre-REX4 delegated walk can follow it. - let _ = inspect_account(&mut journal, ADDR, false).unwrap(); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, DELEGATE, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed pre-REX4"); - - assert_eq!( - slot.present_value, expected, - "pre-REX4 storage inspection must follow the delegator to the delegate's slot", - ); - assert!(slot.is_cold, "slot must be marked cold"); - assert_eq!( - journal.database.storage_calls(), - 0, - "delegate slot pre-seeded in the cache must be returned without hitting the DB", - ); - } - - #[test] - fn test_inspect_storage_pre_rex4_newly_created_short_circuits_db() { - const ADDR: Address = address!("00000000000000000000000000000000000000ef"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - { - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - account.mark_created(); - } - - let key = U256::from(6); - let spec = MegaSpecId::MINI_REX; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed pre-REX4 on newly-created account"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "pre-REX4 newly-created account must return ZERO without querying database" - ); - assert!(slot.is_cold, "slot must be marked cold"); - assert_eq!( - journal.database.storage_calls(), - 0, - "newly-created pre-REX4 path must not hit the database storage lookup", - ); - } - - #[test] - fn test_inspect_storage_rex4_ignores_eip7702_delegation() { - const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); - const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); - let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_code); - let mut journal = Journal::new(db); - - let key = U256::from(2); - let expected = U256::from(99); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, DELEGATOR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let spec = MegaSpecId::REX4; - let slot = journal - .inspect_storage(spec, DELEGATOR, key) - .expect("inspect_storage must succeed for REX4 delegator"); - - assert_eq!( - slot.present_value, expected, - "REX4 must read storage from delegator (original address), not delegate" - ); - } -} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs deleted file mode 100644 index f92675325..000000000 --- a/crates/mega-evm/src/evm/instructions.rs +++ /dev/null @@ -1,2385 +0,0 @@ -use core::cmp::min; - -use crate::{ - constants::{self}, - ExternalEnvTypes, HostExt, JournalInspectTr, MegaContext, MegaSpecId, -}; -use alloy_evm::Database; -use alloy_primitives::{keccak256, Bytes, U256}; -use revm::{ - context::ContextTr, - handler::instructions::{EthInstructions, InstructionProvider}, - interpreter::{ - as_usize_or_fail, as_usize_or_fail_ret, gas, gas_or_fail, - instructions::{self, control, utility::IntoAddress}, - interpreter::EthInterpreter, - interpreter_types::{InputsTr, LoopControl, MemoryTr, RuntimeFlag}, - resize_memory, CallScheme, FrameInput, Instruction, InstructionContext, InstructionResult, - InstructionTable, InterpreterAction, InterpreterTypes, SStoreResult, Stack, - }, - primitives::KECCAK_EMPTY, -}; - -/// `MegaInstructions` is the instruction table for `MegaETH`. -/// -/// This instruction table implements a multi-dimensional gas model and customizes certain opcodes -/// for `MegaETH` specifications: -/// -/// # Multi-Dimensional Gas Model -/// -/// All instructions track gas usage across multiple dimensions: -/// - **Compute Gas**: Standard EVM operation costs (arithmetic, control flow, memory, etc.) -/// - **Storage Gas**: Dynamic costs for persistent storage operations (SSTORE, CREATE, CALL with -/// transfer) -/// - **Log Storage Gas**: Additional costs for persisting event logs (10x standard costs) -/// -/// This separation allows for independent pricing and limiting of different resource types. -/// -/// # Customized Opcodes -/// -/// ## LOG Opcodes (LOG0-LOG4) -/// - Compute gas: Standard EVM costs (375 + 375×topics + `8×data_bytes`) -/// - Storage gas: 10x multiplier (3,750×topics + `80×data_bytes`) -/// - Data limit enforcement: Halts when total transaction data exceeds 3.125 MB -/// -/// ## SELFDESTRUCT Opcode -/// - Disabled in Mini-Rex, Rex, and Rex1 specs -/// - Re-enabled in Rex2 with EIP-6780 semantics -/// - When disabled, halts with `InvalidFEOpcode` to prevent contract destruction -/// -/// ## SSTORE Opcode -/// - Compute gas: Standard EIP-2200/EIP-2929 costs -/// - Storage gas: Dynamic bucket-based costs only when setting zero → non-zero -/// - Data/KV limit enforcement: Tracks 40 bytes + 1 KV update per storage slot modification -/// -/// ## CREATE/CREATE2 Opcodes -/// - Compute gas: Standard costs (32,000 for CREATE, 6 gas/word for CREATE2 hashing) -/// - Storage gas: Dynamic bucket-based costs for new account creation -/// - Gas forwarding: 98/100 rule (2% withheld vs. standard 1.5%) -/// - Data/KV tracking: 40 bytes + 1 KV update per account creation -/// -/// ## CALL-like Opcode -/// - Compute gas: Standard call costs -/// - Storage gas: Dynamic bucket-based costs for new account creation (when transferring to empty -/// account) -/// - REX4+: Value-transferring `CALL`/`CALLCODE` receives additional `STORAGE_CALL_STIPEND` for -/// storage-gas-heavy operations such as `LOG` -/// - REX4+: Compute gas remains capped at the original `forwarded_gas + CALL_STIPEND`, so the extra -/// stipend cannot be used for pure computation -/// - Gas forwarding: 98/100 rule (2% withheld vs. standard 1.5%) -/// - Oracle detection: Handled at frame level (in `frame_init`), applies gas detention for both -/// direct transaction calls and internal CALL operations -/// - Data/KV tracking: 40 bytes + 2 KV updates when transferring to empty account -/// -/// ## Volatile Data Access Opcodes -/// Block environment opcodes (TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE, -/// BLOCKHASH, BLOBBASEFEE, BLOBHASH) and beneficiary-accessing opcodes (BALANCE, EXTCODESIZE, -/// EXTCODECOPY, EXTCODEHASH) implement immediate gas detention to prevent `DoS` attacks. -/// -/// # Gas Detention Mechanism -/// -/// When volatile data (block environment, beneficiary, or oracle) is accessed, the system -/// implements a gas detention mechanism: -/// 1. The compute gas limit is lowered based on the type of volatile data: -/// - Block environment or beneficiary: `BLOCK_ENV_ACCESS_COMPUTE_GAS` (20M gas) -/// - Oracle contract: `ORACLE_ACCESS_COMPUTE_GAS` (1M gas pre-Rex3, 20M gas Rex3+) -/// -/// In pre-REX4, this is an **absolute** cap on total compute gas. -/// In REX4+, this is a **relative** cap: `usage_at_access + cap`. -/// 2. Most restrictive limit wins: If multiple volatile data types are accessed, the minimum (most -/// restrictive) effective limit applies, regardless of access order -/// 3. Detained gas is tracked and refunded at transaction end -/// 4. Users only pay for actual work performed, not for enforcement gas -/// 5. This prevents `DoS` attacks while maintaining fair gas accounting -/// -/// # Instruction Layering Architecture -/// -/// ## Extension Modules (Inner → Outer) -/// -/// Each opcode handler is composed of one or more extension module wrappers, applied from -/// innermost (closest to revm) to outermost: -/// -/// 1. **`compute_gas_ext`** — Tracks compute gas usage for every opcode. Wraps the raw revm -/// instruction and records how much gas was consumed. -/// 2. **`storage_gas_ext`** — Adds dynamic storage gas costs (SSTORE, CALL with value transfer, -/// CREATE, LOG). Wraps `compute_gas_ext` handlers. -/// 3. **`additional_limit_ext`** — Enforces multidimensional resource limits (data size, KV -/// updates). Wraps `storage_gas_ext` handlers. -/// 4. **`forward_gas_ext`** — Enforces the 98/100 gas forwarding rule for CALL-like and CREATE -/// opcodes. Wraps `storage_gas_ext` handlers. -/// 5. **`volatile_data_ext`** — Applies gas detention on volatile data access (block env, -/// beneficiary, oracle) and pre-execution disable checks (Rex4+). Wraps `compute_gas_ext` or -/// `forward_gas_ext` handlers depending on the opcode. -/// -/// ## Spec Progression and Opcode Overrides -/// -/// Each behavior-introducing spec builds on the previous one; the alias specs have no table of -/// their own and select their behavior target's (see [`MegaInstructions::new`]). Only the -/// opcodes that change are listed: -/// -/// - **EQUIVALENCE**: Standard revm mainnet instruction table (no custom wrappers). -/// - **`MINI_REX`** (base custom table): All 256 opcodes initialized from scratch. -/// - Most opcodes: `compute_gas_ext::*` -/// - Block env opcodes (TIMESTAMP, NUMBER, etc.): `volatile_data_ext::*` -/// - BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH: `volatile_data_ext::*` -/// - SLOAD: `compute_gas_ext::sload` -/// - SSTORE: `additional_limit_ext` → `storage_gas_ext` -/// - LOG0–LOG4: `additional_limit_ext` → `storage_gas_ext` -/// - CALL: `forward_gas_ext` → `storage_gas_ext` -/// - CREATE, CREATE2: `forward_gas_ext` → `storage_gas_ext` -/// - CALLCODE, DELEGATECALL, STATICCALL: `compute_gas_ext::*` (bug: missing `forward_gas_ext`) -/// - SELFDESTRUCT: disabled (`control::invalid`) -/// - **REX / REX1** (extends `MINI_REX)`: -/// - CALLCODE: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - DELEGATECALL: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - STATICCALL: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - **REX2** (extends REX): -/// - SELFDESTRUCT: `compute_gas_ext::selfdestruct` (re-enabled with EIP-6780) -/// - **REX3** (extends REX2): -/// - SLOAD: `volatile_data_ext::sload` → `compute_gas_ext::sload` (oracle gas detention) -/// - **REX4** (extends REX3): -/// - CALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - STATICCALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - DELEGATECALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - CALLCODE: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - **REX5** (extends REX4): -/// - SELFDESTRUCT: `volatile_data_ext::selfdestruct_with_beneficiary_guard` → -/// `storage_gas_ext::selfdestruct` (new-account storage gas, beneficiary-volatile guard -/// outermost) -/// - **REX6** (extends REX5): unifies the per-opcode gas-metering order. The table wiring is -/// unchanged. Storage-affecting handlers (SSTORE, LOG, CALL-family, CREATE/CREATE2) all follow a -/// canonical order: charge storage gas → run the raw opcode body → record compute gas exactly -/// once via `record_storage_compute_gas!` after the body completes, excluding the storage gas. -/// For SSTORE / LOG / CALL-family this is byte-equivalent to the pre-REX6 layering (nothing -/// between `gas_before` and the storage charge debits EVM gas), so `storage_gas_ext::*` records -/// compute inline on every spec — no `if REX6` branch is needed. SELFDESTRUCT keeps its -/// delegation to `compute_gas_ext::selfdestruct`, whose trailing `record_compute_gas_all_dims` -/// check records the same single compute window while latching the pre-recorded data/KV/state -/// usage. CREATE2 is the one real behavior change: REX6+ short-circuits to `create_rex6`, which -/// folds the memory-expansion gas into the single post-body recording instead of recording it as -/// a separate eager entry as REX5 did. -/// -/// Note: chains terminating at `storage_gas_ext` (rather than `compute_gas_ext`) reflect the -/// canonical metering order above — `storage_gas_ext::*` records compute gas internally via -/// `record_storage_compute_gas!`, so there is no separate `compute_gas_ext` layer below it. -/// -/// # Assumptions -/// -/// This instruction table is only used when the `MINI_REX` spec (or later) is enabled, so we can -/// safely assume that all features before and including Mini-Rex are enabled. -#[derive(Clone)] -pub struct MegaInstructions { - spec: MegaSpecId, - inner: EthInstructions>, -} - -impl core::fmt::Debug for MegaInstructions { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethInstructions").field("spec", &self.spec).finish_non_exhaustive() - } -} - -impl MegaInstructions { - /// Create a new `MegaethInstructions` with the given spec id. - pub fn new(spec: MegaSpecId) -> Self { - // An alias spec is grouped with its `behavior()` target so it executes exactly the - // target's table; the grouping must agree with `behavior()`, pinned by - // `test_alias_specs_use_their_behavior_targets_table`. - let instruction_table = match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => EthInstructions::new_mainnet(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => { - EthInstructions::new(mini_rex::instruction_table::< - EthInterpreter, - MegaContext, - >()) - } - MegaSpecId::REX | MegaSpecId::REX1 => EthInstructions::new(rex::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX2 => EthInstructions::new(rex2::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX3 => EthInstructions::new(rex3::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX4 => EthInstructions::new(rex4::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX5 => EthInstructions::new(rex5::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX6 => EthInstructions::new(rex6::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX7 => EthInstructions::new(rex7::instruction_table::< - EthInterpreter, - MegaContext, - >()), - }; - Self { spec, inner: instruction_table } - } -} - -impl InstructionProvider - for MegaInstructions -{ - type Context = MegaContext; - type InterpreterTypes = EthInterpreter; - - fn instruction_table(&self) -> &InstructionTable { - self.inner.instruction_table() - } -} - -mod rex { - use super::*; - - /// Returns the instruction table for the `REX` and `REX1` specs. - /// - /// Changes from Mini-Rex (bugfix — adds missing `forward_gas_ext` wrapping): - /// - CALLCODE: `forward_gas_ext` → `storage_gas_ext` - /// - DELEGATECALL: `forward_gas_ext` → `storage_gas_ext` - /// - STATICCALL: `forward_gas_ext` → `storage_gas_ext` - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = mini_rex::instruction_table::(); - - // Mini-Rex mistakenly not modifying these three call-like opcodes. They are fixed in Rex - table[CALLCODE as usize] = forward_gas_ext::call_code; - table[DELEGATECALL as usize] = forward_gas_ext::delegate_call; - table[STATICCALL as usize] = forward_gas_ext::static_call; - - table - } -} - -mod rex2 { - use super::*; - - /// Returns the instruction table for the `REX2` spec. - /// - /// Changes from Rex: - /// - SELFDESTRUCT: `compute_gas_ext::selfdestruct` (re-enabled with EIP-6780 semantics) - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex::instruction_table::(); - - table[SELFDESTRUCT as usize] = compute_gas_ext::selfdestruct; - - table - } -} - -mod rex3 { - use super::*; - - /// Returns the instruction table for the `REX3` spec. - /// - /// Changes from Rex2: - /// - SLOAD: `volatile_data_ext::sload` → `compute_gas_ext::sload` (oracle gas detention). This - /// replaces the CALL-based oracle access detection used in earlier specs. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex2::instruction_table::(); - - // Rex3: SLOAD triggers gas detention for oracle contract access. - // The host's sload() method marks oracle access in the volatile data tracker, - // then the detain_gas_ext wrapper applies the compute gas limit. - table[SLOAD as usize] = volatile_data_ext::sload; - - table - } -} - -mod rex4 { - use super::*; - - /// Returns the instruction table for the `REX4` spec. - /// - /// Changes from Rex3: - /// - CALL: `volatile_data_ext::call` → `forward_gas_ext` → `storage_gas_ext` - /// - STATICCALL: `volatile_data_ext::static_call` → `forward_gas_ext` → `storage_gas_ext` - /// - DELEGATECALL: `volatile_data_ext::delegate_call` → `forward_gas_ext` → `storage_gas_ext` - /// - CALLCODE: `volatile_data_ext::call_code` → `forward_gas_ext` → `storage_gas_ext` - /// - SELFDESTRUCT: `volatile_data_ext::selfdestruct` → `compute_gas_ext::selfdestruct` - /// - SELFBALANCE: `volatile_data_ext::selfbalance` → `compute_gas_ext::selfbalance` - /// - /// The `volatile_data_ext` wrapper checks if the target address is the beneficiary and - /// volatile data access is disabled — if so, reverts before executing. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex3::instruction_table::(); - - // Rex4: CALL-like opcodes check for beneficiary volatile access disabled. - table[CALL as usize] = volatile_data_ext::call; - table[STATICCALL as usize] = volatile_data_ext::static_call; - table[DELEGATECALL as usize] = volatile_data_ext::delegate_call; - table[CALLCODE as usize] = volatile_data_ext::call_code; - - // Rex4: SELFDESTRUCT checks for beneficiary volatile access. - table[SELFDESTRUCT as usize] = volatile_data_ext::selfdestruct; - - // Rex4: SELFBALANCE checks for beneficiary volatile access (when the executing - // contract is the beneficiary, SELFBALANCE triggers gas detention). - table[SELFBALANCE as usize] = volatile_data_ext::selfbalance; - - table - } -} - -mod rex5 { - use super::*; - - /// Returns the instruction table for the `REX5` spec. - /// - /// Changes from Rex4: - /// - SELFDESTRUCT: `volatile_data_ext::selfdestruct_with_beneficiary_guard` → - /// `storage_gas_ext::selfdestruct`. The outer wrapper keeps the beneficiary-volatile guard - /// outermost (matching the SSTORE / LOG layering) and slots the new-account storage-gas - /// charge between the guard and the inner opcode, so disabled-volatile frames short-circuit - /// ahead of any storage-layer side effects (account inspection, dynamic gas charge, - /// `on_selfdestruct_new_account` record). - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex4::instruction_table::(); - - // REX5: SELFDESTRUCT charges storage gas for new beneficiary accounts, - // gated behind the beneficiary-volatile guard. - table[SELFDESTRUCT as usize] = volatile_data_ext::selfdestruct_with_beneficiary_guard; - - table - } -} - -mod rex6 { - use super::*; - - /// Returns the instruction table for the `REX6` spec. - /// - /// Changes from Rex5: the instruction *table* is unchanged (same handler functions as Rex5). - /// Every Rex6 behavior difference is expressed as internal `spec.is_enabled(MegaSpecId::REX6)` - /// dispatch inside the shared handlers, never as a swapped table entry: - /// - the storage-affecting handlers (SSTORE, LOG, CALL-family, CREATE/CREATE2) charge storage - /// gas, run their body, then record compute gas exactly once (via - /// [`record_storage_compute_gas!`]) with the storage gas excluded; SELFDESTRUCT keeps its - /// delegation to `compute_gas_ext::selfdestruct`, whose trailing all-dimension check records - /// the same single compute window while latching the pre-recorded data/KV/state usage; - /// - `storage_gas_ext::selfdestruct` additionally records existing-target balance-update - /// accounting, and its outer volatile wrapper - /// (`volatile_data_ext::selfdestruct_with_beneficiary_guard`) additionally guards the - /// executing contract (source) against the beneficiary; - /// - the CALL-family volatile wrappers, on the `disableVolatileDataAccess` path, resolve the - /// stack target's one-hop EIP-7702 delegate before the beneficiary comparison. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - rex5::instruction_table::() - } -} - -mod rex7 { - use super::*; - - /// Returns the instruction table for the `REX7` spec. - /// - /// Changes from Rex6: none yet. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - rex6::instruction_table::() - } -} - -/// Macro to record compute gas and check if the limit has been exceeded. If the limit is exceeded, -/// the interpreter halts and returns. -macro_rules! compute_gas { - ($interpreter:expr, $additional_limit:expr, $gas_used:expr $(,$ret:expr)?) => { - if !$additional_limit.record_compute_gas($gas_used) { - $interpreter.halt($additional_limit.exceeding_instruction_result()); - return $($ret)?; - } - }; -} - -/// Macro to run the inner instruction and abort if the instruction result is an error. -macro_rules! run_inner_instruction_or_abort { - ($inner_fn:path, $context:expr) => { - let ctx = InstructionContext::<'_, H, WIRE> { - interpreter: &mut *$context.interpreter, - host: &mut *$context.host, - }; - $inner_fn(ctx); - if $context - .interpreter - .bytecode - .instruction_result() - .is_some_and(|result| result.is_error()) - { - return; - } - }; -} - -/// Records an opcode's compute gas in a single measurement window and enforces the compute-gas -/// limit. The REX6 storage-affecting handlers invoke it directly with the storage gas they -/// charged; plain opcodes use the leaner inline recording in -/// `compute_gas_ext::wrap_op_compute_gas`, which implements the same forwarded-gas exclusion -/// without the REX6 abort-path handling (unreachable from those wrappers). -/// -/// `$gas_before` MUST be the interpreter gas remaining captured at the very top of the handler, -/// before any storage-gas charge or wrapper-side EVM-gas work (e.g. CREATE2 memory expansion), so -/// the single measurement window covers all of the opcode's compute work. The recorded amount is -/// `($gas_before − gas_after) − $storage_charged − forwarded_child_gas`: the storage gas charged -/// inside the window is subtracted back out, and gas forwarded to a child frame is excluded (the -/// child records its own compute gas). The forwarded-gas exclusion is spec-aware — REX5+ excludes -/// the revm-side `CALL_STIPEND`, pre-REX5 does not — so the result is identical to the pre-existing -/// inline recording on every spec. -/// -/// Because nothing consumes EVM gas before the storage charge for the non-CREATE2 opcodes, the REX6 -/// storage handlers record the same compute gas, at the same point, as the pre-REX6 layering; -/// CREATE2 differs only by folding its memory-expansion gas into this single window instead of -/// recording it separately. -/// -/// On exceeding the compute-gas limit, halts the interpreter and returns from the enclosing -/// instruction handler. The early return mirrors [`compute_gas!`] so a trailing statement after -/// this macro (e.g. the pre-REX5 `resize_gas` late-record in `storage_gas_ext::create`) is only -/// reached on the non-halt path; without the return, a halt here would let a later `compute_gas!` -/// add gas to the tracker after the OOG was already set. -macro_rules! record_storage_compute_gas { - ($context:expr, $gas_before:expr, $storage_charged:expr) => {{ - let gas_after = $context.interpreter.gas.remaining(); - let mut gas_used = $gas_before.saturating_sub(gas_after).saturating_sub($storage_charged); - // Exclude gas forwarded to a child frame. REX5+ excludes the revm-side `CALL_STIPEND` - // (added by value-transferring CALL/CALLCODE without deducting from the parent) so the - // parent's compute gas is not under-counted; pre-REX5 subtracts the full child gas limit - // for replay parity. `forwarded_child_gas` records that deducted amount so the abort path - // below can return it to the parent. - let mut forwarded_child_gas: u64 = 0; - match $context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - let stipend_from_revm = if $context.host.spec_id().is_enabled(MegaSpecId::REX5) && - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode) && - call_inputs.transfers_value() - { - gas::CALL_STIPEND - } else { - 0 - }; - let parent_contributed = call_inputs.gas_limit.saturating_sub(stipend_from_revm); - forwarded_child_gas = parent_contributed; - gas_used = gas_used.saturating_sub(parent_contributed); - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - forwarded_child_gas = create_inputs.gas_limit; - gas_used = gas_used.saturating_sub(create_inputs.gas_limit); - } - _ => {} - } - // On a compute-limit halt the pending child `NewFrame` is discarded (the child never runs), - // but revm already deducted the forwarded gas and the outer `forward_gas_ext` erase is - // skipped on this abort path. REX6+: return that gas to the parent before halting. - let is_rex6 = $context.host.spec_id().is_enabled(MegaSpecId::REX6); - let exceeding_result = { - let mut additional_limit = $context.host.additional_limit().borrow_mut(); - if additional_limit.record_compute_gas(gas_used) { - None - } else { - Some(additional_limit.exceeding_instruction_result()) - } - }; - if let Some(result) = exceeding_result { - if is_rex6 { - $context.interpreter.gas.erase_cost(forwarded_child_gas); - } - $context.interpreter.halt(result); - return; - } - }}; -} - -mod mini_rex { - use super::*; - - /// Returns the instruction table for the `MINI_REX` spec. - /// - /// This is the base custom table — all 256 opcodes are initialized from scratch with - /// compute gas tracking. Key opcode layering: - /// - Most opcodes: `compute_gas_ext::*` (compute gas tracking only) - /// - Block env opcodes: `volatile_data_ext::*` (gas detention) - /// - BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH: `volatile_data_ext::*` (conditional) - /// - SSTORE: `additional_limit_ext` → `storage_gas_ext` - /// - LOG0–LOG4: `additional_limit_ext` → `storage_gas_ext` - /// - CALL: `forward_gas_ext` → `storage_gas_ext` - /// - CREATE, CREATE2: `forward_gas_ext` → `storage_gas_ext` - /// - CALLCODE, DELEGATECALL, STATICCALL: `compute_gas_ext::*` (bug: missing `forward_gas_ext`) - /// - SELFDESTRUCT: disabled (`control::invalid`) - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] { - use revm::bytecode::opcode::*; - let mut table = [control::unknown as Instruction; 256]; - - table[STOP as usize] = compute_gas_ext::stop; - table[ADD as usize] = compute_gas_ext::add; - table[MUL as usize] = compute_gas_ext::mul; - table[SUB as usize] = compute_gas_ext::sub; - table[DIV as usize] = compute_gas_ext::div; - table[SDIV as usize] = compute_gas_ext::sdiv; - table[MOD as usize] = compute_gas_ext::rem; - table[SMOD as usize] = compute_gas_ext::smod; - table[ADDMOD as usize] = compute_gas_ext::addmod; - table[MULMOD as usize] = compute_gas_ext::mulmod; - table[EXP as usize] = compute_gas_ext::exp; - table[SIGNEXTEND as usize] = compute_gas_ext::signextend; - - table[LT as usize] = compute_gas_ext::lt; - table[GT as usize] = compute_gas_ext::gt; - table[SLT as usize] = compute_gas_ext::slt; - table[SGT as usize] = compute_gas_ext::sgt; - table[EQ as usize] = compute_gas_ext::eq; - table[ISZERO as usize] = compute_gas_ext::iszero; - table[AND as usize] = compute_gas_ext::bitand; - table[OR as usize] = compute_gas_ext::bitor; - table[XOR as usize] = compute_gas_ext::bitxor; - table[NOT as usize] = compute_gas_ext::not; - table[BYTE as usize] = compute_gas_ext::byte; - table[SHL as usize] = compute_gas_ext::shl; - table[SHR as usize] = compute_gas_ext::shr; - table[SAR as usize] = compute_gas_ext::sar; - table[CLZ as usize] = compute_gas_ext::clz; - - table[KECCAK256 as usize] = compute_gas_ext::keccak256; - - table[ADDRESS as usize] = compute_gas_ext::address; - table[BALANCE as usize] = volatile_data_ext::balance; - table[ORIGIN as usize] = compute_gas_ext::origin; - table[CALLER as usize] = compute_gas_ext::caller; - table[CALLVALUE as usize] = compute_gas_ext::callvalue; - table[CALLDATALOAD as usize] = compute_gas_ext::calldataload; - table[CALLDATASIZE as usize] = compute_gas_ext::calldatasize; - table[CALLDATACOPY as usize] = compute_gas_ext::calldatacopy; - table[CODESIZE as usize] = compute_gas_ext::codesize; - table[CODECOPY as usize] = compute_gas_ext::codecopy; - - table[GASPRICE as usize] = compute_gas_ext::gasprice; - table[EXTCODESIZE as usize] = volatile_data_ext::extcodesize; - table[EXTCODECOPY as usize] = volatile_data_ext::extcodecopy; - table[EXTCODEHASH as usize] = volatile_data_ext::extcodehash; - table[RETURNDATASIZE as usize] = compute_gas_ext::returndatasize; - table[RETURNDATACOPY as usize] = compute_gas_ext::returndatacopy; - table[BLOCKHASH as usize] = volatile_data_ext::blockhash; - table[COINBASE as usize] = volatile_data_ext::coinbase; - table[TIMESTAMP as usize] = volatile_data_ext::timestamp; - table[NUMBER as usize] = volatile_data_ext::block_number; - table[DIFFICULTY as usize] = volatile_data_ext::difficulty; - table[GASLIMIT as usize] = volatile_data_ext::gas_limit_opcode; - table[CHAINID as usize] = compute_gas_ext::chainid; - table[SELFBALANCE as usize] = compute_gas_ext::selfbalance; - table[BASEFEE as usize] = volatile_data_ext::basefee; - table[BLOBBASEFEE as usize] = volatile_data_ext::blobbasefee; - table[BLOBHASH as usize] = volatile_data_ext::blobhash; - - table[POP as usize] = compute_gas_ext::pop; - table[MLOAD as usize] = compute_gas_ext::mload; - table[MSTORE as usize] = compute_gas_ext::mstore; - table[MSTORE8 as usize] = compute_gas_ext::mstore8; - table[SLOAD as usize] = compute_gas_ext::sload; - table[SSTORE as usize] = additional_limit_ext::sstore; - table[JUMP as usize] = compute_gas_ext::jump; - table[JUMPI as usize] = compute_gas_ext::jumpi; - table[PC as usize] = compute_gas_ext::pc; - table[MSIZE as usize] = compute_gas_ext::msize; - table[GAS as usize] = compute_gas_ext::gas; - table[JUMPDEST as usize] = compute_gas_ext::jumpdest; - table[TLOAD as usize] = compute_gas_ext::tload; - table[TSTORE as usize] = compute_gas_ext::tstore; - table[MCOPY as usize] = compute_gas_ext::mcopy; - - table[PUSH0 as usize] = compute_gas_ext::push0; - table[PUSH1 as usize] = compute_gas_ext::push1; - table[PUSH2 as usize] = compute_gas_ext::push2; - table[PUSH3 as usize] = compute_gas_ext::push3; - table[PUSH4 as usize] = compute_gas_ext::push4; - table[PUSH5 as usize] = compute_gas_ext::push5; - table[PUSH6 as usize] = compute_gas_ext::push6; - table[PUSH7 as usize] = compute_gas_ext::push7; - table[PUSH8 as usize] = compute_gas_ext::push8; - table[PUSH9 as usize] = compute_gas_ext::push9; - table[PUSH10 as usize] = compute_gas_ext::push10; - table[PUSH11 as usize] = compute_gas_ext::push11; - table[PUSH12 as usize] = compute_gas_ext::push12; - table[PUSH13 as usize] = compute_gas_ext::push13; - table[PUSH14 as usize] = compute_gas_ext::push14; - table[PUSH15 as usize] = compute_gas_ext::push15; - table[PUSH16 as usize] = compute_gas_ext::push16; - table[PUSH17 as usize] = compute_gas_ext::push17; - table[PUSH18 as usize] = compute_gas_ext::push18; - table[PUSH19 as usize] = compute_gas_ext::push19; - table[PUSH20 as usize] = compute_gas_ext::push20; - table[PUSH21 as usize] = compute_gas_ext::push21; - table[PUSH22 as usize] = compute_gas_ext::push22; - table[PUSH23 as usize] = compute_gas_ext::push23; - table[PUSH24 as usize] = compute_gas_ext::push24; - table[PUSH25 as usize] = compute_gas_ext::push25; - table[PUSH26 as usize] = compute_gas_ext::push26; - table[PUSH27 as usize] = compute_gas_ext::push27; - table[PUSH28 as usize] = compute_gas_ext::push28; - table[PUSH29 as usize] = compute_gas_ext::push29; - table[PUSH30 as usize] = compute_gas_ext::push30; - table[PUSH31 as usize] = compute_gas_ext::push31; - table[PUSH32 as usize] = compute_gas_ext::push32; - - table[DUP1 as usize] = compute_gas_ext::dup1; - table[DUP2 as usize] = compute_gas_ext::dup2; - table[DUP3 as usize] = compute_gas_ext::dup3; - table[DUP4 as usize] = compute_gas_ext::dup4; - table[DUP5 as usize] = compute_gas_ext::dup5; - table[DUP6 as usize] = compute_gas_ext::dup6; - table[DUP7 as usize] = compute_gas_ext::dup7; - table[DUP8 as usize] = compute_gas_ext::dup8; - table[DUP9 as usize] = compute_gas_ext::dup9; - table[DUP10 as usize] = compute_gas_ext::dup10; - table[DUP11 as usize] = compute_gas_ext::dup11; - table[DUP12 as usize] = compute_gas_ext::dup12; - table[DUP13 as usize] = compute_gas_ext::dup13; - table[DUP14 as usize] = compute_gas_ext::dup14; - table[DUP15 as usize] = compute_gas_ext::dup15; - table[DUP16 as usize] = compute_gas_ext::dup16; - - table[SWAP1 as usize] = compute_gas_ext::swap1; - table[SWAP2 as usize] = compute_gas_ext::swap2; - table[SWAP3 as usize] = compute_gas_ext::swap3; - table[SWAP4 as usize] = compute_gas_ext::swap4; - table[SWAP5 as usize] = compute_gas_ext::swap5; - table[SWAP6 as usize] = compute_gas_ext::swap6; - table[SWAP7 as usize] = compute_gas_ext::swap7; - table[SWAP8 as usize] = compute_gas_ext::swap8; - table[SWAP9 as usize] = compute_gas_ext::swap9; - table[SWAP10 as usize] = compute_gas_ext::swap10; - table[SWAP11 as usize] = compute_gas_ext::swap11; - table[SWAP12 as usize] = compute_gas_ext::swap12; - table[SWAP13 as usize] = compute_gas_ext::swap13; - table[SWAP14 as usize] = compute_gas_ext::swap14; - table[SWAP15 as usize] = compute_gas_ext::swap15; - table[SWAP16 as usize] = compute_gas_ext::swap16; - - table[LOG0 as usize] = additional_limit_ext::log::<0, _, _>; - table[LOG1 as usize] = additional_limit_ext::log::<1, _, _>; - table[LOG2 as usize] = additional_limit_ext::log::<2, _, _>; - table[LOG3 as usize] = additional_limit_ext::log::<3, _, _>; - table[LOG4 as usize] = additional_limit_ext::log::<4, _, _>; - - table[CREATE as usize] = forward_gas_ext::create; - table[CREATE2 as usize] = forward_gas_ext::create2; - table[CALL as usize] = forward_gas_ext::call; - table[CALLCODE as usize] = compute_gas_ext::call_code; - table[DELEGATECALL as usize] = compute_gas_ext::delegate_call; - table[STATICCALL as usize] = compute_gas_ext::static_call; - - table[INVALID as usize] = compute_gas_ext::invalid; - table[RETURN as usize] = compute_gas_ext::ret; - table[REVERT as usize] = compute_gas_ext::revert; - table[SELFDESTRUCT as usize] = control::invalid; - - table - } -} - -/// Call-like and create-like opcode handlers with 98/100 gas forwarding rule. -/// -/// This module provides wrapper implementations for CALL, CALLCODE, DELEGATECALL, STATICCALL, -/// CREATE, and CREATE2 opcodes that enforce the 98/100 gas forwarding rule (retaining 2% of -/// remaining gas in the parent call instead of the standard 1/64). -/// -/// The wrappers: -/// 1. Check for value transfer (CALL and CALLCODE only) to account for call stipend -/// 2. Call the underlying opcode implementation -/// 3. Cap the forwarded gas to 98% of the parent's remaining gas -/// 4. Preserve the call stipend (2300 gas) when value is transferred (CALL/CALLCODE only) -/// 5. Support both Call and Create frame types -pub mod forward_gas_ext { - use super::*; - - /// Macro to wrap call-like and create-like opcodes with 98/100 gas forwarding rule. - /// - /// This macro generates a wrapper function that: - /// 1. Optionally checks for value transfer (`has_transfer`) for CALL opcode - /// 2. Calls the wrapped opcode handler - /// 3. Caps the forwarded gas to 98/100 of the remaining gas - /// 4. Adjusts for call stipend if value is being transferred - /// 5. Supports both Call and Create frame types - /// - /// # Parameters - /// - `$fn_name`: Name of the generated function - /// - `$opcode_name`: String name of the opcode (for documentation) - /// - `$wrapped_fn`: Path to the wrapped instruction implementation - /// - `$has_transfer_logic`: Expression to determine if value is being transferred (e.g., - /// `has_transfer` or `false`) - macro_rules! wrap_gas_cap { - ($fn_name:ident, $opcode_name:expr, $wrapped_fn:path, $has_transfer_logic:expr) => { - #[doc = concat!("`", $opcode_name, "` opcode with 98/100 gas forwarding rule.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Determine if there's a value transfer (only applies to CALL opcode). - let has_transfer = $has_transfer_logic(&context); - - // Call the wrapped opcode handler. - run_inner_instruction_or_abort!($wrapped_fn, context); - - // Cap the forwarded gas to the child call/create to the 98/100 of the remaining - // gas. - match context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - // The forwarded gas to the child call should be further restricted to the - // 98/100 of the remaining gas. Here, we first recover the total - // gas left in the parent call and then cap the child call gas - // limit if necessary. - - // We recover the forwarded gas to the child call from the parent call. - let child_gas = call_inputs.gas_limit as u128; - // There may be a call stipend if there is value to be transferred. - let transfer_gas_stipend = - if has_transfer { gas::CALL_STIPEND as u128 } else { 0 }; - let forwarded_gas = child_gas - transfer_gas_stipend; // Safe from underflow - - // Recover the remaining gas in the parent call before forwarding to the - // child call. - let parent_original_gas_left = - context.interpreter.gas.remaining() as u128 + forwarded_gas; - - // Calculate the amount of gas that should be returned to the parent call - // under the 98/100 rule. - let forwarded_gas_cap = - parent_original_gas_left - parent_original_gas_left * 2 / 100; - let capped_forwarded_gas = min(forwarded_gas, forwarded_gas_cap); - let gas_to_return = forwarded_gas - capped_forwarded_gas; // Safe from underflow - - // Recalculate the child gas - let new_child_gas = capped_forwarded_gas + transfer_gas_stipend; - - // Return the gas to the parent call. - context.interpreter.gas.erase_cost(gas_to_return as u64); - - // Set the child call gas limit to the capped value. - // Note: REX4+ STORAGE_CALL_STIPEND is applied later in - // AdditionalLimit::before_frame_init, which owns the full - // stipend lifecycle (grant → compute cap → burn on return). - call_inputs.gas_limit = new_child_gas as u64; - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - // The forwarded gas to the child create should be further restricted to the - // 98/100 of the remaining gas. CREATE opcodes don't have a call - // stipend, so the logic is simpler. - - // We recover the forwarded gas from the parent call. - let child_gas = create_inputs.gas_limit as u128; - let forwarded_gas = child_gas; // No stipend for CREATE - - // Recover the remaining gas in the parent call before forwarding to the - // child create. - let parent_original_gas_left = - context.interpreter.gas.remaining() as u128 + forwarded_gas; - - // Calculate the amount of gas that should be returned to the parent call - // under the 98/100 rule. - let forwarded_gas_cap = - parent_original_gas_left - parent_original_gas_left * 2 / 100; - let capped_forwarded_gas = min(forwarded_gas, forwarded_gas_cap); - let gas_to_return = forwarded_gas - capped_forwarded_gas; // Safe from underflow - - // Return the gas to the parent call. - context.interpreter.gas.erase_cost(gas_to_return as u64); - - // Set the child create gas limit to the capped value. - create_inputs.gas_limit = capped_forwarded_gas as u64; - } - _ => {} - } - } - }; - } - - // Helper function to check if CALL has value transfer - #[inline] - fn check_call_has_transfer< - WIRE: InterpreterTypes, - H: HostExt + ?Sized, - >( - context: &InstructionContext<'_, H, WIRE>, - ) -> bool { - if let Some(value) = context.interpreter.stack.inspect::<2>() { - !value.is_zero() - } else { - false - } - } - - // Helper function for opcodes without value transfer - #[inline] - fn no_transfer, H: HostExt + ?Sized>( - _context: &InstructionContext<'_, H, WIRE>, - ) -> bool { - false - } - - wrap_gas_cap!(call, "CALL", storage_gas_ext::call, check_call_has_transfer); - wrap_gas_cap!(call_code, "CALLCODE", storage_gas_ext::call_code, check_call_has_transfer); - wrap_gas_cap!(delegate_call, "DELEGATECALL", storage_gas_ext::delegate_call, no_transfer); - wrap_gas_cap!(static_call, "STATICCALL", storage_gas_ext::static_call, no_transfer); - wrap_gas_cap!(create, "CREATE", storage_gas_ext::create::, no_transfer); - wrap_gas_cap!(create2, "CREATE2", storage_gas_ext::create::, no_transfer); -} - -/** Volatile data access opcode handlers with compute gas limit enforcement. - -These custom instruction handlers override opcodes that access volatile data (block environment, -beneficiary account data, oracle contract) to lower the compute gas limit. -This prevents `DoS` attacks while allowing storage operations to continue with full transaction gas. - -# Compute Gas Limit Enforcement - -When volatile data is accessed: -1. The opcode executes normally (calls host method, processes data) -2. If this is the first volatile data access in the transaction: - - The compute gas limit is lowered based on the type: - * Block environment or beneficiary: `BLOCK_ENV_ACCESS_REMAINING_GAS` (20M compute gas) - * Oracle contract: `ORACLE_ACCESS_REMAINING_GAS` (1M compute gas) -3. Most restrictive limit wins: If additional volatile data with different limit is accessed, - the minimum (most restrictive) limit is applied, regardless of access order -4. All subsequent compute operations are limited by this compute gas limit -5. Storage operations (SSTORE, account creation) continue with full transaction gas - -# Volatile Data Access Disable (Rex4+) - -When `disableVolatileDataAccess()` is active, the handlers check **before** executing the -opcode and revert immediately if the access would be volatile. -This ensures that disabled volatile accesses do not pollute the tracker's `volatile_data_accessed` -bitmap or lower the `compute_gas_limit`. - -# Two Categories of Opcodes - -## Block Environment Opcodes (Always Volatile) -These opcodes ALWAYS access volatile data and apply 20M compute gas limit: -- TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE, BLOCKHASH, BLOBBASEFEE, BLOBHASH - -## Account-Accessing Opcodes (Conditionally Volatile) -These opcodes only SOMETIMES access volatile data (20M compute gas limit when volatile): -- `BALANCE(beneficiary_address)` → volatile, applies 20M compute gas limit -- `BALANCE(other_address)` → not volatile, no limit -- EXTCODESIZE/EXTCODECOPY/EXTCODEHASH → same conditional behavior - -For conditional opcodes, the instruction handler peeks the target address from the stack before -executing the opcode to determine if the access would be volatile. - -## Oracle SLOAD (Rex3+) -SLOAD targeting the oracle contract is volatile and applies the oracle compute gas limit. -The target address comes from `interpreter.input.target_address()` (not from the stack). -*/ -pub mod volatile_data_ext { - use super::*; - - use alloy_primitives::Address; - - use crate::{ - volatile_data_access_disabled_revert_data, VolatileDataAccessType, ORACLE_CONTRACT_ADDRESS, - }; - - /// Applies the compute gas limit from the volatile data tracker to the additional limit. - /// - /// This is safe to call unconditionally after any instruction: `get_compute_gas_limit()` - /// returns `None` if no volatile data has been accessed in this transaction, and if a - /// prior instruction already set the limit, re-applying the same value is idempotent. - macro_rules! apply_compute_gas_limit { - ($context:expr) => { - let compute_gas_limit = - $context.host.volatile_data_tracker().borrow().get_compute_gas_limit(); - if let Some(limit) = compute_gas_limit { - $context.host.additional_limit().borrow_mut().set_compute_gas_limit(limit); - } - }; - } - - /// Macro to create opcode handlers for **unconditionally volatile** opcodes. - /// - /// These opcodes (TIMESTAMP, NUMBER, etc.) always access volatile data. - /// The handler: - /// 1. Checks if volatile data access is disabled (Rex4+) — if so, reverts immediately - /// **before** executing the opcode, avoiding any side effects on the tracker. - /// 2. Executes the original instruction. - /// 3. Applies the compute gas limit via `apply_compute_gas_limit!`. - macro_rules! wrap_op_detain_gas_unconditional { - ($fn_name:ident, $opcode_name:expr, $original_fn:path, $access_type:expr) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas limit enforcement on volatile data access.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: revert before executing if volatile data access is disabled. - if context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data($access_type), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!($original_fn, context); - apply_compute_gas_limit!(context); - } - }; - } - - /// Macro to create opcode handlers for **conditionally volatile** opcodes. - /// - /// These opcodes (BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH) are volatile only when - /// targeting the block beneficiary address. - /// The handler: - /// 1. Peeks the target address from the stack (position 0) without consuming it. - /// 2. If the target is the beneficiary and volatile access is disabled, reverts immediately - /// **before** executing the opcode. - /// 3. Otherwise executes the instruction normally and applies gas detention if volatile data - /// was accessed. - macro_rules! wrap_op_detain_gas_conditional { - ($fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas limit enforcement on volatile data access.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Peek the target address from the stack to check if it's the beneficiary. - // Rex4+: If targeting the beneficiary while volatile access is disabled, revert - // before executing the opcode to avoid polluting the tracker. - if let Some(addr_word) = context.interpreter.stack.inspect::<0>() { - let target: Address = addr_word.into_address(); - let beneficiary = context.host.beneficiary_address(); - if target == beneficiary && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - - run_inner_instruction_or_abort!($original_fn, context); - apply_compute_gas_limit!(context); - } - }; - } - - // Unconditional volatile opcodes — always access volatile data, no stack inspection needed. - wrap_op_detain_gas_unconditional!( - timestamp, - "TIMESTAMP", - compute_gas_ext::timestamp, - VolatileDataAccessType::Timestamp - ); - wrap_op_detain_gas_unconditional!( - block_number, - "NUMBER", - compute_gas_ext::number, - VolatileDataAccessType::BlockNumber - ); - wrap_op_detain_gas_unconditional!( - difficulty, - "DIFFICULTY", - compute_gas_ext::difficulty, - VolatileDataAccessType::Difficulty - ); - wrap_op_detain_gas_unconditional!( - gas_limit_opcode, - "GASLIMIT", - compute_gas_ext::gaslimit, - VolatileDataAccessType::GasLimit - ); - wrap_op_detain_gas_unconditional!( - basefee, - "BASEFEE", - compute_gas_ext::basefee, - VolatileDataAccessType::BaseFee - ); - wrap_op_detain_gas_unconditional!( - coinbase, - "COINBASE", - compute_gas_ext::coinbase, - VolatileDataAccessType::Coinbase - ); - wrap_op_detain_gas_unconditional!( - blockhash, - "BLOCKHASH", - compute_gas_ext::blockhash, - VolatileDataAccessType::BlockHash - ); - wrap_op_detain_gas_unconditional!( - blobbasefee, - "BLOBBASEFEE", - compute_gas_ext::blobbasefee, - VolatileDataAccessType::BlobBaseFee - ); - wrap_op_detain_gas_unconditional!( - blobhash, - "BLOBHASH", - compute_gas_ext::blobhash, - VolatileDataAccessType::BlobHash - ); - - // Conditional volatile opcodes — volatile only when targeting the block beneficiary. - wrap_op_detain_gas_conditional!(balance, "BALANCE", compute_gas_ext::balance); - wrap_op_detain_gas_conditional!(extcodesize, "EXTCODESIZE", compute_gas_ext::extcodesize); - wrap_op_detain_gas_conditional!(extcodecopy, "EXTCODECOPY", compute_gas_ext::extcodecopy); - wrap_op_detain_gas_conditional!(extcodehash, "EXTCODEHASH", compute_gas_ext::extcodehash); - wrap_op_detain_gas_conditional!(selfdestruct, "SELFDESTRUCT", compute_gas_ext::selfdestruct); - - /// REX5+ SELFDESTRUCT outer wrapper: beneficiary volatile-access guard ahead of the - /// `storage_gas_ext::selfdestruct` layer (which under REX6 also records the existing-target - /// balance-update accounting), then the compute-gas-limit application. - /// - /// This is the conditional-volatile shape of [`wrap_op_detain_gas_conditional`] (it cannot be - /// macro-generated because of the extra REX6 source check below): when volatile access is - /// disabled and the stack target is the beneficiary, revert before any storage-layer side - /// effect. REX6 additionally guards the executing contract (the *source*, whose balance is read - /// and zeroed): REX5 inspected only the stack target, so when the source itself was the - /// beneficiary its state was still observed without `disableVolatileDataAccess` rejecting. - /// The source check is REX6-gated, leaving REX5 byte-for-byte frozen. When volatile access is - /// *enabled*, the beneficiary is already balance-marked before its own code runs (it is reached - /// as the tx recipient or a CALL target, both of which mark it), so detention engages without a - /// SELFDESTRUCT-specific hook. - #[inline] - pub fn selfdestruct_with_beneficiary_guard< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - if context.host.volatile_access_disabled() { - let beneficiary = context.host.beneficiary_address(); - // Confirm the SELFDESTRUCT has a target operand first: a stack-underflow SELFDESTRUCT - // must keep revm's `StackUnderflow` halt and not be pre-empted by a beneficiary revert. - // The guards apply only once the opcode actually acts on a target. - if let Some(addr_word) = context.interpreter.stack.inspect::<0>() { - let target: Address = addr_word.into_address(); - // REX6: the executing contract (source) reading and zeroing its own balance is - // itself a beneficiary observation. Frozen off pre-REX6, where only the stack - // target below was guarded. - if context.host.spec_id().is_enabled(MegaSpecId::REX6) && - context.interpreter.input.target_address() == beneficiary - { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - // All specs: the stack target (the value-transfer destination). - if target == beneficiary { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - } - - run_inner_instruction_or_abort!(super::storage_gas_ext::selfdestruct, context); - apply_compute_gas_limit!(context); - } - - /// `SELFBALANCE` opcode with compute gas limit enforcement on volatile data access. - /// - /// SELFBALANCE is conditionally volatile when the current contract is the beneficiary. - /// Unlike the other beneficiary-conditional opcodes (BALANCE, EXTCODESIZE, etc.), - /// the target comes from `interpreter.input.target_address()` (the executing contract), - /// not from a stack operand, so `wrap_op_detain_gas_conditional` cannot be reused. - #[inline] - pub fn selfbalance( - context: InstructionContext<'_, H, WIRE>, - ) { - let target = context.interpreter.input.target_address(); - let beneficiary = context.host.beneficiary_address(); - if target == beneficiary && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data(VolatileDataAccessType::Beneficiary), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!(compute_gas_ext::selfbalance, context); - apply_compute_gas_limit!(context); - } - - /// `SLOAD` opcode with compute gas limit enforcement on volatile data access. - /// - /// SLOAD is conditionally volatile when targeting the oracle contract. - /// Unlike the beneficiary-conditional opcodes, the target address comes from - /// `interpreter.input.target_address()` (the current contract), not from the stack. - /// - /// The handler checks if the SLOAD targets the oracle contract and volatile access is - /// disabled — if so, reverts before executing the instruction. - #[inline] - pub fn sload( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: If SLOAD targets the oracle contract and volatile access is disabled, - // revert before executing to avoid polluting the tracker. - let target = context.interpreter.input.target_address(); - if target == ORACLE_CONTRACT_ADDRESS && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data(VolatileDataAccessType::Oracle), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!(compute_gas_ext::sload, context); - apply_compute_gas_limit!(context); - } - - /// Macro to create opcode handlers for **conditionally volatile CALL-like** opcodes. - /// - /// These opcodes (CALL, STATICCALL, DELEGATECALL, CALLCODE) are volatile only when - /// targeting the block beneficiary address. - /// - /// When volatile access is disabled, the handler peeks the stack target (position 1) and - /// reverts **before** executing the opcode if the target is the beneficiary — avoiding tracker - /// pollution via `load_account_delegated`. Under REX6 it compares the target's one-hop EIP-7702 - /// delegate so a call to a delegator pointing at the beneficiary is also caught; that - /// resolution (a DB read) is gated behind the disabled check so it stays off the enabled - /// path, where the raw call proceeds and `load_account_delegated` marks the resolved - /// delegate instead. `<=` REX5 compares the raw stack operand (frozen). Otherwise it - /// delegates to the existing `forward_gas_ext` handler. - macro_rules! wrap_call_volatile_check { - ($fn_name:ident, $opcode_name:expr, $inner_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with volatile data access disabled check for beneficiary.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: If targeting the beneficiary while volatile access is disabled, revert before - // executing the opcode to avoid polluting the tracker. Only this disabled path can - // revert and only it needs the EIP-7702 delegate resolved, so the resolve (a DB read) - // is gated behind the disabled check to keep it off the common (enabled) hot path — - // enabled-access detention is marked by `load_account_delegated` during the CALL on the - // resolved delegate. - if context.host.volatile_access_disabled() { - // Peek the target address from the stack (position 1 for CALL-like opcodes: - // stack layout is [gas_limit, to, ...]). - if let Some(addr_word) = context.interpreter.stack.inspect::<1>() { - let target: Address = addr_word.into_address(); - let beneficiary = context.host.beneficiary_address(); - let spec = context.host.spec_id(); - // The raw target already being the beneficiary observes beneficiary state - // regardless of where it itself delegates, so check it first — `||` short-circuits - // so no EIP-7702 delegate is resolved (and no DB read happens) in that case. - // REX6 otherwise resolves the delegate one hop so a CALL to a delegator `A` whose - // code points at `B == beneficiary` is also caught; <= REX5 compares the raw - // operand (frozen). The resolve is best-effort: a DB error (e.g. the delegate's - // code failing to load) falls back to the raw target WITHOUT stashing a - // `ctx.error`, so a malformed CALL that underflows before it ever runs the target - // keeps its `StackUnderflow` rather than surfacing a spurious DB error from this - // precheck. The opcode's real execution path reads the account again and owns - // surfacing any genuine failure. - if target == beneficiary || - (spec.is_enabled(MegaSpecId::REX6) && - context.host.best_effort_resolve_eip7702_delegate_address(target) == - beneficiary) - { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - } - - // Delegate to the existing forward_gas_ext handler via reborrow so that - // `context` remains usable for `apply_compute_gas_limit!` afterward. - { - let ctx = InstructionContext::<'_, H, WIRE> { - interpreter: &mut *context.interpreter, - host: &mut *context.host, - }; - $inner_fn(ctx); - } - - // Propagate the detained compute gas limit if the CALL triggered beneficiary - // access (via `host.load_account_delegated()` inside the CALL handler). - // `apply_compute_gas_limit!` only touches the tracker and `AdditionalLimit`, - // not interpreter state, so it is safe in any interpreter state (including - // `NewFrame` after a successful CALL). - apply_compute_gas_limit!(context); - } - }; - } - - // Conditionally volatile CALL-like opcodes — volatile only when targeting the block - // beneficiary. These wrap forward_gas_ext handlers with a pre-execution beneficiary check. - wrap_call_volatile_check!(call, "CALL", forward_gas_ext::call); - wrap_call_volatile_check!(static_call, "STATICCALL", forward_gas_ext::static_call); - wrap_call_volatile_check!(delegate_call, "DELEGATECALL", forward_gas_ext::delegate_call); - wrap_call_volatile_check!(call_code, "CALLCODE", forward_gas_ext::call_code); -} - -/// Extends opcodes with additional limit (kv update limit, data limit, etc.) enforcement. -pub mod additional_limit_ext { - use super::*; - - /// `SSTORE` opcode implementation with data size and KV update limit enforcement. - /// - /// This wrapper adds limit tracking on top of [`storage_gas_ext::sstore`], which handles - /// compute gas tracking and storage gas costs. - /// - /// # Data Size and KV Update Tracking - /// - /// When first writing non-zero value to originally-zero slot: - /// - Adds 40 bytes to transaction data size - /// - Adds 1 KV update count - /// - /// # Limit Enforcement - /// - /// Halts with `OutOfGas` when data (3.125 MB) or KV (1,000) limits exceeded. - /// - /// # Refund Logic - /// - /// Refunds data/KV when slot reset to original value. - pub fn sstore< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Load storage slot values before executing the instruction - let target_address = context.interpreter.input.target_address(); - let Some(index) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let mega_spec = context.host.spec_id(); - let Ok(slot) = context.host.inspect_storage(mega_spec, target_address, index) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let (original_value, present_value) = (slot.original_value(), slot.present_value()); - let Some(new_value) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let loaded_data = SStoreResult { original_value, present_value, new_value }; - - // Execute the original SSTORE instruction - run_inner_instruction_or_abort!(storage_gas_ext::sstore, context); - - // KV update bomb and data bomb (only when first writing non-zero value to originally zero - // slot): check if the number of key-value updates or the total data size will exceed the - // limit, if so, halt. - let additional_limit = context.host.additional_limit(); - let mut additional_limit = additional_limit.borrow_mut(); - if !additional_limit.on_sstore(target_address, index, &loaded_data) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } - - /// `LOG` opcode implementation with data size limit enforcement. - /// - /// This wrapper adds data limit tracking on top of [`storage_gas_ext::log`], which handles - /// compute gas tracking and storage gas costs. - /// - /// # Data Size Limit Enforcement - /// - /// After log emission, checks if total transaction data size exceeds `TX_DATA_LIMIT` (3.125 - /// MB). Halts when data limit exceeded. - pub fn log< - const N: usize, - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Get the log data length before executing the instruction - let Some(len) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let len = as_usize_or_fail!(context.interpreter, len); - - // Execute the original LOG instruction - run_inner_instruction_or_abort!(storage_gas_ext::log::, context); - - // Record the size of the log topics and data. If the total data size exceeds the limit, we - // halt. - let additional_limit = context.host.additional_limit(); - let mut additional_limit = additional_limit.borrow_mut(); - if !additional_limit.on_log(N as u64, len as u64) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } -} - -/// Extends opcodes with storage gas cost on top of `compute_gas_ext`. -pub mod storage_gas_ext { - use super::*; - use alloy_primitives::Address; - - /// Address-selector for opcodes where the storage account is the stack `to` address (e.g. - /// CALL). - fn storage_addr_from_to(_mega_spec: MegaSpecId, _current: Address, to: Address) -> Address { - to - } - - /// Address-selector for CALLCODE: Rex5+ uses the current frame's address because CALLCODE - /// executes borrowed code in the caller's own storage context; pre-Rex5 preserves the frozen - /// behavior of metering against the code-source (stack `to`). - fn storage_addr_for_callcode(mega_spec: MegaSpecId, current: Address, to: Address) -> Address { - if mega_spec.is_enabled(MegaSpecId::REX5) { - current - } else { - to - } - } - - /// Macro to charge storage gas for new account creation before calling the wrapped instruction. - /// - /// This macro generates a wrapper function that: - /// 1. Inspects the target address (stack position 1) and value (stack position 2) - /// 2. Resolves the storage account address via `$select_addr` - /// 3. Checks if the storage account is empty and value transfer is non-zero - /// 4. Charges storage gas for new account creation if applicable - /// 5. Calls the wrapped instruction implementation - /// - /// # Call Opcode Behavior - /// - /// The generated `CALL` and `CALLCODE` implementations add: - /// - /// **Dynamic New Account Gas**: When calling empty account with value transfer: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - /// # Parameters - /// - `$fn_name`: Name of the generated function - /// - `$opcode_name`: String name of the opcode (for documentation) - /// - `$raw_fn`: Path to the raw inner opcode implementation (no compute-gas wrapper) - /// - `$has_transfer_logic`: `true` if the opcode can transfer value (inspects stack position 2) - /// - `$select_addr` (optional): Path to a `fn(MegaSpecId, current: Address, to: Address) -> - /// Address` function that returns the address to check for emptiness and charge - /// `new_account_storage_gas` against. `current` is the current frame's address; `to` is the - /// stack position-1 address. Defaults to [`storage_addr_from_to`]. - /// - /// # Metering order - /// - /// Runs `$raw_fn` directly and records compute gas exactly once after the body completes via - /// [`record_storage_compute_gas!`], excluding the storage gas charged above. Nothing consumes - /// EVM gas between the `gas_before` capture and the storage-gas charge (only stack inspects, - /// host account reads, and additional-limit operations), so this single-window form records - /// the same compute gas as the pre-REX6 "wrap the inner with `compute_gas_ext`" layering on - /// every spec — the recorded amount is `body_gas` either way. - macro_rules! wrap_call_with_storage_gas { - ($fn_name:ident, $opcode_name:expr, $raw_fn:path, $has_transfer_logic:expr) => { - wrap_call_with_storage_gas!( - $fn_name, - $opcode_name, - $raw_fn, - $has_transfer_logic, - storage_addr_from_to - ); - }; - ($fn_name:ident, $opcode_name:expr, $raw_fn:path, $has_transfer_logic:expr, $select_addr:path) => { - #[doc = concat!("`", $opcode_name, "` opcode implementation modified from `revm` with compute gas tracking and dynamically-scaled storage gas costs.")] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers all of the - // opcode's compute work. - let gas_before = context.interpreter.gas.remaining(); - let spec = context.interpreter.runtime_flag.spec_id(); - let Some(to) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let to = to.into_address(); - let mega_spec = context.host.spec_id(); - let current_address = context.interpreter.input.target_address(); - let storage_address = $select_addr(mega_spec, current_address, to); - let Ok(storage_account) = (if mega_spec.is_enabled(MegaSpecId::REX5) { - context.host.inspect_account(storage_address, false) - } else { - context.host.inspect_account_delegated(mega_spec, storage_address) - }) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let is_empty = storage_account.state_clear_aware_is_empty(spec); - let has_transfer = if $has_transfer_logic { - let Some(value) = context.interpreter.stack.inspect::<2>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - !value.is_zero() - } else { - false - }; - // Charge additional storage gas cost for creating a new account. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - // `storage_charged` is the EVM gas actually debited for storage gas, so the REX6 - // single compute recording below can exclude it from the measured window. - let storage_charged = if is_empty && has_transfer { - let Some(new_account_storage_gas) = - context.host.new_account_storage_gas(storage_address) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(new_account_storage_gas); - let charged = new_account_storage_gas - drained; - gas!(context.interpreter, charged); - charged - } else { - 0 - }; - - // Run the raw opcode and record compute gas once after the body completes - // (canonical metering order). Byte-equivalent to the pre-REX6 layering on every - // spec because nothing between the `gas_before` capture and the storage charge - // above consumes EVM gas. - run_inner_instruction_or_abort!($raw_fn, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - }; - } - - wrap_call_with_storage_gas!(call, "CALL", instructions::contract::call, true); - wrap_call_with_storage_gas!( - delegate_call, - "DELEGATECALL", - instructions::contract::delegate_call, - false - ); - wrap_call_with_storage_gas!( - static_call, - "STATICCALL", - instructions::contract::static_call, - false - ); - wrap_call_with_storage_gas!( - call_code, - "CALLCODE", - instructions::contract::call_code, - true, - storage_addr_for_callcode - ); - - /// Inspects the creator account and computes the address a `CREATE`/`CREATE2` would deploy to. - /// - /// Shared by the pre-REX6 [`create`] and the REX6 [`create_rex6`] handlers so the address - /// computation lives in one place. For CREATE2 this expands memory to hash the initcode, which - /// debits EVM gas: - /// - /// - When `record_resize_eagerly` is `true` (pre-REX6 with REX5 enabled), the memory-expansion - /// gas is recorded into the compute-gas tracker immediately — the same position and timing as - /// the original inline code — and the returned `resize_gas` is `0`. - /// - When `record_resize_eagerly` is `false`, the gas is left unrecorded and returned, so the - /// caller decides when to record it: the pre-REX5 late-record path, or the REX6 single-window - /// folding in [`record_storage_compute_gas!`]. - /// - /// Returns `None` if a precondition failed (stack underflow, oversized operand, a REX6 - /// oversized-initcode halt, memory OOG, external DB error, or an eager compute-gas-limit - /// exceed) and the interpreter was halted. - fn compute_created_address< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: &mut InstructionContext<'_, H, WIRE>, - spec: MegaSpecId, - record_resize_eagerly: bool, - ) -> Option<(Address, u64)> { - // The current execution contract (the caller). Load it without marking it warm (it is - // already warm since the current frame began). REX5+ uses non-delegating inspection to get - // the authority's own state. - let creator_address = context.interpreter.input.target_address(); - let Ok(creator) = (if spec.is_enabled(MegaSpecId::REX5) { - context.host.inspect_account(creator_address, false) - } else { - context.host.inspect_account_delegated(spec, creator_address) - }) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return None; - }; - - let mut resize_gas: u64 = 0; - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - let created_address = if IS_CREATE2 { - let Some(initcode_offset) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - let Some(initcode_len) = context.interpreter.stack.inspect::<2>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - // REX5+: validate the salt operand before running `resize_memory!` and the copy / - // keccak block, so a missing salt halts with `StackUnderflow` without - // performing the expensive memory work. Pre-REX5 keeps the original "resize - // first, salt last" order. - let rex5_salt = if is_rex5_enabled { - let Some(salt) = context.interpreter.stack.inspect::<3>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - Some(salt) - } else { - None - }; - - // REX5+: when `initcode_len == 0`, mirror canonical revm CREATE2 — ignore the offset - // entirely (no conversion, no memory expansion, no slice, no keccak) and use - // `KECCAK_EMPTY`. Pre-REX5 keeps the "observe offset, resize, slice, hash" sequence. - let initcode_hash = if is_rex5_enabled && initcode_len.is_zero() { - KECCAK_EMPTY - } else { - // Convert `initcode_len` before `initcode_offset` (matching canonical revm's - // `create`, which pops/converts `len` first): both operands halt with the same - // `InstructionResult::InvalidOperandOOG` reason when they don't fit in a - // `usize` (see `as_usize_or_fail_ret!`'s default reason), so this reordering - // does not change pre-REX6 behavior — but it matters for the REX6 size check - // below, which must run before `initcode_offset` is ever touched so that an - // oversized `initcode_len` halts with `CreateInitCodeSizeLimit` even when - // `initcode_offset` does not fit in a `usize` either. - let initcode_len = as_usize_or_fail_ret!(context.interpreter, initcode_len, None); - - // REX6: EIP-3860 initcode-size halt, matching revm's canonical - // ordering intent (`revm::interpreter::instructions::contract::create`) — halt - // BEFORE `initcode_offset` conversion, `resize_memory!`/copy/keccak256/address- - // derivation, not after. Pre-REX6 performs that prework before the halt - // eventually fires inside the inner opcode call below; that ordering is - // non-consensus under REX6 when the halt fires before the inner opcode - // completes (committed gas/state is identical either way — - // `record_resize_eagerly=false` means the resize gas is not yet recorded at - // this point, so skipping it here charges nothing that a later, slower path - // would have charged — only the halt timing / node CPU differ), but changing - // pre-REX6 timing would perturb sealed-spec replay, so this is gated to REX6 - // only. A REX6 static frame never reaches this check: [`create_rex6`] rejects - // static frames before entering this helper. - if spec.is_enabled(MegaSpecId::REX6) && - initcode_len > context.host.max_initcode_size() - { - context.interpreter.halt(InstructionResult::CreateInitCodeSizeLimit); - return None; - } - - let initcode_offset = - as_usize_or_fail_ret!(context.interpreter, initcode_offset, None); - - // Expand memory before slicing so the read can never go out of bounds. The inner - // CREATE2 also calls `resize_memory!`, which is a no-op once memory already fits. - let gas_before_resize = context.interpreter.gas.remaining(); - resize_memory!(context.interpreter, initcode_offset, initcode_len, None); - resize_gas = gas_before_resize.saturating_sub(context.interpreter.gas.remaining()); - - // Eager recording (pre-REX6 / REX5): record the expansion gas immediately to align - // its timing with revm's EVM-gas debit, then zero `resize_gas` so the caller's - // late-record path does not double-count. - if record_resize_eagerly && resize_gas > 0 { - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, resize_gas, None); - resize_gas = 0; - } - - let code = Bytes::copy_from_slice( - context.interpreter.memory.slice_len(initcode_offset, initcode_len).as_ref(), - ); - keccak256(&code) - }; - - let salt = if let Some(s) = rex5_salt { - s - } else { - let Some(salt) = context.interpreter.stack.inspect::<3>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - salt - }; - - creator_address.create2(salt.to_be_bytes(), initcode_hash) - } else { - creator_address.create(creator.info.nonce) - }; - - Some((created_address, resize_gas)) - } - - /// `CREATE`/`CREATE2` opcode implementation modified from `revm` with compute gas tracking and - /// dynamically-scaled storage gas costs. - /// - /// # Differences from the standard EVM - /// - /// 1. **Dynamic New Account Gas**: Additional storage gas for new account creation: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - /// # Assumptions - /// - /// This is the entry point for `CREATE`/`CREATE2` from `MINI_REX` onward. REX6+ short- - /// circuits to [`create_rex6`] at the top; the body below is the pre-REX6 path, which can - /// assume all features up to and including `MINI_REX` are enabled. - pub fn create< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - mut context: InstructionContext<'_, H, WIRE>, - ) { - let spec = context.host.spec_id(); - - // REX6+: canonical metering order — fold the CREATE2 memory-expansion gas into a single - // compute-gas recording taken after the body completes (see `create_rex6`), instead of - // the pre-REX6 split `resize_gas` recording handled below. - if spec.is_enabled(MegaSpecId::REX6) { - create_rex6::(context); - return; - } - - // Inspect the creator and compute the created address. REX5+ records the CREATE2 - // memory-expansion gas eagerly inside the helper (the same position and timing as the - // original inline code); pre-REX5 leaves it in `resize_gas` for the late-record path below. - let Some((created_address, resize_gas)) = compute_created_address::( - &mut context, - spec, - spec.is_enabled(MegaSpecId::REX5), - ) else { - return; - }; - - // Charge storage gas cost for creating a new contract - let create_contract_storage_gas = if spec.is_enabled(MegaSpecId::REX) { - // Rex spec distinguishes between contract creation and account creation. - context.host.create_contract_storage_gas(created_address) - } else { - // Mini-Rex spec does not distinguish between contract creation and account creation. - context.host.new_account_storage_gas(created_address) - }; - let Some(create_contract_storage_gas) = create_contract_storage_gas else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(create_contract_storage_gas); - gas!(context.interpreter, create_contract_storage_gas - drained); - - // Capture, run raw, record — `gas_before` here is captured after the storage debit and - // after `compute_created_address`'s eager `resize_gas` record (REX5+), so the recorded - // amount equals the inner opcode's body gas. Byte-equivalent to the old per-`IS_CREATE2` - // dispatch through `compute_gas_ext::{create, create2}`, which captured at the same - // point. - let gas_before = context.interpreter.gas.remaining(); - run_inner_instruction_or_abort!( - instructions::contract::create::<_, IS_CREATE2, _>, - context - ); - record_storage_compute_gas!(context, gas_before, 0); - - // Pre-REX5 late-record path for the CREATE2 initcode memory-expansion gas. - // Preserved verbatim for replay parity: pre-REX5 keeps the original "skip on inner - // error" semantics where storage-gas OOG and inner-CREATE2 failure both skip this - // recording. REX5+ already recorded `resize_gas` above (and zeroed it), so this - // branch is a no-op under REX5. - if resize_gas > 0 { - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, resize_gas); - } - } - - /// `CREATE`/`CREATE2` under the REX6+ canonical metering order. - /// - /// Records the opcode's compute gas exactly once, after the inner opcode completes, via - /// [`record_storage_compute_gas!`]. This folds the CREATE2 memory-expansion (`resize_memory!`) - /// gas into the single compute window instead of the pre-REX6 split recording (REX5 recorded it - /// eagerly before the storage charge; pre-REX5 recorded it after the inner op). The storage gas - /// charged for contract creation is excluded from the recorded compute gas. - /// - /// On the straight-line success path the total compute gas equals the pre-REX6 amount. The two - /// differ only when a compute-limit or storage-gas-OOG halt occurs between the memory expansion - /// and inner-op completion: REX6 records compute gas only once the body has fully executed, so - /// a partial memory expansion that never reaches the inner opcode is not recorded against - /// the compute-gas limit (its EVM gas is still debited). - /// - /// REX6 implies REX5 (and REX), so the REX5 operand validation and the contract-creation - /// storage-gas path are taken unconditionally here. - fn create_rex6< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - mut context: InstructionContext<'_, H, WIRE>, - ) { - // Canonical revm's `create` runs `require_non_staticcall!` before any operand read, - // memory work, address derivation, or storage-gas charge, so a static-frame - // `CREATE`/`CREATE2` halts here first. This unifies the halt reasons the prework below - // would otherwise produce in a static frame — stack underflow from operand inspection, - // memory OOG from an unaffordable resize, storage-gas OOG from the creation charge, or - // a fatal external error from the storage-pricing lookup — into the canonical - // `StateChangeDuringStaticCall`. No spec gate: [`create`] dispatches here exactly when - // REX6 is enabled. Pre-REX6 keeps the prework-first order (changing sealed-spec halt - // reasons would perturb replay). Every reachable path is an all-gas-consuming halt, so - // committed gas and state are identical either way. - if context.interpreter.runtime_flag.is_static() { - context.interpreter.halt(InstructionResult::StateChangeDuringStaticCall); - return; - } - - // Captured before any gas movement so the single compute window covers the wrapper-side - // CREATE2 memory expansion as well as the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - let spec = context.host.spec_id(); - - // Inspect the creator and compute the created address. `record_resize_eagerly = false`: - // the CREATE2 memory-expansion gas is left unrecorded so it folds into the single compute - // window closed by `record_storage_compute_gas!` below. - let Some((created_address, _resize_gas)) = - compute_created_address::(&mut context, spec, false) - else { - return; - }; - - // Charge storage gas cost for creating a new contract. REX6 implies REX, so the - // contract-creation cost path applies. `storage_charged` is excluded from the compute - // recording below. - let Some(create_contract_storage_gas) = - context.host.create_contract_storage_gas(created_address) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - // REX6 implies REX5: drain the storage stipend allowance first. - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(create_contract_storage_gas); - let storage_charged = create_contract_storage_gas - drained; - gas!(context.interpreter, storage_charged); - - // Run the raw inner create opcode (no `compute_gas_ext` wrapper — REX6 records compute gas - // once below). - if IS_CREATE2 { - run_inner_instruction_or_abort!(instructions::contract::create::<_, true, _>, context); - } else { - run_inner_instruction_or_abort!(instructions::contract::create::<_, false, _>, context); - } - - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `LOG` opcode implementation modified from `revm` with compute gas tracking, increased - /// storage gas costs, and data size limit enforcement. - /// - /// # Differences from the standard EVM - /// - /// 1. **Storage Gas Costs**: Additional storage gas charged for log storage: - /// - Topic storage: 3,750 gas per topic (10x standard topic cost) - /// - Data storage: 80 gas per byte (10x standard data cost) - /// - /// # Assumptions - /// - /// This alternative implementation of `LOG` is only used when the `MINI_REX` spec is enabled. - pub fn log< - const N: usize, - WIRE: InterpreterTypes, - H: HostExt + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - let Some(len) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let len = as_usize_or_fail!(context.interpreter, len); - - // Charge storage gas cost for log topics and data before instruction execution. - // REX5 drains the allowance on the `Some(amount)` arm; the `None` (overflow) arm - // is passed through unchanged to preserve the OOG halt. - let log_storage_cost = { - let topic_cost = constants::mini_rex::LOG_TOPIC_STORAGE_GAS.checked_mul(N as u64); - let data_cost = constants::mini_rex::LOG_DATA_STORAGE_GAS.checked_mul(len as u64); - topic_cost.and_then(|topic| data_cost.and_then(|cost| cost.checked_add(topic))) - }; - let log_storage_cost = log_storage_cost.map(|amount| { - let drained = - context.host.additional_limit().borrow_mut().try_consume_storage_stipend(amount); - amount - drained - }); - gas_or_fail!(context.interpreter, log_storage_cost); - // `gas_or_fail!` halts and returns on the `None` (overflow) arm, so reaching here means the - // cost was `Some`; this is the storage gas actually charged, excluded from the compute - // recording below. Assert the invariant with `expect` rather than `unwrap_or(0)`: a silent - // `0` here would make `record_storage_compute_gas!` over-count compute gas by the full LOG - // storage cost. - let storage_charged = - log_storage_cost.expect("gas_or_fail! above halts and returns on None"); - - // Run the raw opcode and record compute gas once after the body completes (canonical - // metering order). Byte-equivalent to the pre-REX6 per-`N` `compute_gas_ext::logK` - // dispatch on every spec because nothing between `gas_before` and the `gas_or_fail!` above - // consumes EVM gas. The wrapper is only ever instantiated for `N` in `0..=4`, so the - // generic `instructions::host::log::` covers every valid call site. - run_inner_instruction_or_abort!(instructions::host::log::, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `SSTORE` opcode implementation modified from `revm` with compute gas tracking and - /// dynamically-scaled storage gas costs. - /// - /// # Differences from the standard EVM - /// - /// 1. **Dynamic Storage Gas**: Additional storage gas ONLY when setting originally-zero slot to - /// non-zero: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - Not charged for updating already-non-zero slots or resetting to zero - /// - /// # Assumptions - /// - /// This alternative implementation of `SSTORE` is only used when the `MINI_REX` spec is - /// enabled, so we can safely assume that all features before and including Mini-Rex are - /// enabled. - pub fn sstore< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - // The address to the underlying execution contract state - let target_address = context.interpreter.input.target_address(); - // The storage slot to write - let Some(index) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - // The storage slot values - let mega_spec = context.host.spec_id(); - let Ok(slot) = context.host.inspect_storage(mega_spec, target_address, index) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let (original_value, present_value) = (slot.original_value(), slot.present_value()); - let Some(new_value) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - - // Charge storage gas cost before the instruction is executed. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - // `storage_charged` is the EVM gas actually debited for storage gas, excluded from the - // single compute recording below. - let storage_charged = - if original_value.is_zero() && present_value.is_zero() && !new_value.is_zero() { - let Some(sstore_set_storage_gas) = - context.host.sstore_set_storage_gas(target_address, index) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(sstore_set_storage_gas); - let charged = sstore_set_storage_gas - drained; - gas!(context.interpreter, charged); - charged - } else { - 0 - }; - - // Run the raw opcode and record compute gas once after the body completes (canonical - // metering order). Byte-equivalent to the pre-REX6 `compute_gas_ext::sstore` layering on - // every spec because nothing between `gas_before` and the storage charge above consumes - // EVM gas. - run_inner_instruction_or_abort!(instructions::host::sstore, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `SELFDESTRUCT` opcode implementation with storage gas metering for - /// new beneficiary account creation (REX5+). - /// - /// When SELFDESTRUCT sends remaining balance to an empty beneficiary, charges: - /// - Storage gas for new account creation (dynamic bucket-based cost) - /// - Data size (+40 for account info write) - /// - KV update (+1) - /// - State growth (+1) - /// - /// This wrapper sits between `volatile_data_ext` and `compute_gas_ext` in the - /// REX5 SELFDESTRUCT dispatch chain - /// (`volatile_data_ext::selfdestruct_with_beneficiary_guard` → `storage_gas_ext::selfdestruct` - /// → `compute_gas_ext::selfdestruct`), matching the layering used by SSTORE - /// and LOG. The beneficiary-volatile guard runs in the outer - /// `volatile_data_ext::selfdestruct_with_beneficiary_guard` ahead of any side effects below. - /// - /// REX6 additionally records the `DataSize` +40 / KV +1 of a balance credit to an existing - /// *distinct* beneficiary — the account-info write the frame-init / `target_updated` path never - /// sees — via the REX6-gated arm below; pre-REX6 records nothing for an existing target. The - /// rest of the body, and all ≤REX5 behavior, is unchanged. - pub fn selfdestruct< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Inside a static frame, revm's inner SELFDESTRUCT halts on the - // static-context check without changing state. Skip the mega host work below - // (two account inspections, SALT account-creation pricing, the storage-gas - // stipend draw and tracker write) — the frame reverts and discards all of it - // anyway — and let the inner instruction produce the identical halt. This is - // behavior-neutral: the static halt is exceptional, so the frame's gas and - // tracked usage are the same whether or not the host work ran first. The table - // installs this wrapper only for REX5+, so pre-REX5 specs never reach here. - if context.interpreter.runtime_flag.is_static() { - run_inner_instruction_or_abort!(compute_gas_ext::selfdestruct, context); - // Defensive: unreachable in practice — a static SELFDESTRUCT always halts - // inside the inner instruction, so the macro returns early above. - return; - } - - let eth_spec = context.interpreter.runtime_flag.spec_id(); - - // Peek beneficiary address from stack (SELFDESTRUCT uses stack position 0) - let Some(target) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let target = target.into_address(); - - // Use non-delegating inspection (REX5+) - let Ok(target_account) = context.host.inspect_account(target, false) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let is_empty = target_account.state_clear_aware_is_empty(eth_spec); - - // Check if caller has balance (value will be transferred to beneficiary) - let caller = context.interpreter.input.target_address(); - let Ok(caller_account) = context.host.inspect_account(caller, false) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let has_value = !caller_account.info.balance.is_zero(); - - if is_empty && has_value { - // Charge storage gas for creating a new account. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - let Some(cost) = context.host.new_account_storage_gas(target) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = - context.host.additional_limit().borrow_mut().try_consume_storage_stipend(cost); - gas!(context.interpreter, cost - drained); - - // Record resource usage for new beneficiary account - context.host.additional_limit().borrow_mut().on_selfdestruct_new_account(); - } else if context.host.spec_id().is_enabled(MegaSpecId::REX6) && - has_value && - caller != target - { - // REX6: a balance credit to an existing *distinct* beneficiary performs an account-info - // write the frame-init / `target_updated` path never sees — record DataSize +40 / KV +1 - // (no `StateGrowth`, the account already exists; no storage gas, the bucket is paid). - // SELFDESTRUCT to self (`caller == target`) is an EIP-6780 balance no-op on a - // non-same-tx-created account (and a burn-to-self on a same-tx-created one) — neither - // is a distinct-target credit, so record nothing. Pre-REX6 records nothing - // for any existing target. - context.host.additional_limit().borrow_mut().on_selfdestruct_existing_account(); - } - - // Delegate to compute_gas_ext::selfdestruct (the volatile-disabled guard - // ran in the outer `volatile_data_ext::selfdestruct_with_beneficiary_guard` wrapper). - run_inner_instruction_or_abort!(compute_gas_ext::selfdestruct, context); - } -} - -/// Compute gas recording implementation. TODO: add more doc -pub mod compute_gas_ext { - use super::*; - - /// Macro to wrap the original instruction implementation with compute gas tracking. - /// - /// Two variants: - /// - default: "simple" opcodes that can never spawn a child frame. The compute gas used is - /// simply `gas_before - gas_after`. These opcodes never set an `InterpreterAction::NewFrame`, - /// so the child-gas-subtraction match (below) would always fall through to `_` — it is - /// omitted entirely to keep the per-opcode hot path lean. - /// - `@frame`: the call/create family (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`/ - /// `CREATE`/`CREATE2`), the only opcodes that set `NewFrame`. These must subtract the gas - /// forwarded to the child frame so the parent's compute gas is not over-counted. - macro_rules! wrap_op_compute_gas { - ($fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas tracking.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured before the inner opcode runs. Plain opcodes charge no storage gas, so - // the measurement window starting here covers exactly the opcode's compute work. - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!($original_fn, context); - - let gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, gas_used); - } - }; - (@frame $fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas tracking.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!($original_fn, context); - - let mut gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - // Subtract the gas forwarded to the child. REX5 excludes the revm-side - // `CALL_STIPEND` (added by value-transferring CALL/CALLCODE without - // deducting from the parent) so parent compute-gas is not under-counted. - // Pre-REX5 keeps the legacy raw-`gas_limit` subtraction for replay parity. - match context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - let stipend_from_revm = if context - .host - .spec_id() - .is_enabled(MegaSpecId::REX5) && - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode) && - call_inputs.transfers_value() - { - gas::CALL_STIPEND - } else { - 0 - }; - let parent_contributed = - call_inputs.gas_limit.saturating_sub(stipend_from_revm); - gas_used = gas_used.saturating_sub(parent_contributed); - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - gas_used = gas_used.saturating_sub(create_inputs.gas_limit); - } - _ => {} - } - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, gas_used); - } - }; - } - - wrap_op_compute_gas!(stop, "STOP", instructions::control::stop); - wrap_op_compute_gas!(add, "ADD", instructions::arithmetic::add); - wrap_op_compute_gas!(mul, "MUL", instructions::arithmetic::mul); - wrap_op_compute_gas!(sub, "SUB", instructions::arithmetic::sub); - wrap_op_compute_gas!(div, "DIV", instructions::arithmetic::div); - wrap_op_compute_gas!(sdiv, "SDIV", instructions::arithmetic::sdiv); - wrap_op_compute_gas!(rem, "MOD", instructions::arithmetic::rem); - wrap_op_compute_gas!(smod, "SMOD", instructions::arithmetic::smod); - wrap_op_compute_gas!(addmod, "ADDMOD", instructions::arithmetic::addmod); - wrap_op_compute_gas!(mulmod, "MULMOD", instructions::arithmetic::mulmod); - wrap_op_compute_gas!(exp, "EXP", instructions::arithmetic::exp); - wrap_op_compute_gas!(signextend, "SIGNEXTEND", instructions::arithmetic::signextend); - - wrap_op_compute_gas!(lt, "LT", instructions::bitwise::lt); - wrap_op_compute_gas!(gt, "GT", instructions::bitwise::gt); - wrap_op_compute_gas!(slt, "SLT", instructions::bitwise::slt); - wrap_op_compute_gas!(sgt, "SGT", instructions::bitwise::sgt); - wrap_op_compute_gas!(eq, "EQ", instructions::bitwise::eq); - wrap_op_compute_gas!(iszero, "ISZERO", instructions::bitwise::iszero); - wrap_op_compute_gas!(bitand, "AND", instructions::bitwise::bitand); - wrap_op_compute_gas!(bitor, "OR", instructions::bitwise::bitor); - wrap_op_compute_gas!(bitxor, "XOR", instructions::bitwise::bitxor); - wrap_op_compute_gas!(not, "NOT", instructions::bitwise::not); - wrap_op_compute_gas!(byte, "BYTE", instructions::bitwise::byte); - wrap_op_compute_gas!(shl, "SHL", instructions::bitwise::shl); - wrap_op_compute_gas!(shr, "SHR", instructions::bitwise::shr); - wrap_op_compute_gas!(sar, "SAR", instructions::bitwise::sar); - wrap_op_compute_gas!(clz, "CLZ", instructions::bitwise::clz); - - wrap_op_compute_gas!(keccak256, "KECCAK256", instructions::system::keccak256); - - wrap_op_compute_gas!(address, "ADDRESS", instructions::system::address); - wrap_op_compute_gas!(balance, "BALANCE", instructions::host::balance); - wrap_op_compute_gas!(origin, "ORIGIN", instructions::tx_info::origin); - wrap_op_compute_gas!(caller, "CALLER", instructions::system::caller); - wrap_op_compute_gas!(callvalue, "CALLVALUE", instructions::system::callvalue); - wrap_op_compute_gas!(calldataload, "CALLDATALOAD", instructions::system::calldataload); - wrap_op_compute_gas!(calldatasize, "CALLDATASIZE", instructions::system::calldatasize); - wrap_op_compute_gas!(calldatacopy, "CALLDATACOPY", instructions::system::calldatacopy); - wrap_op_compute_gas!(codesize, "CODESIZE", instructions::system::codesize); - wrap_op_compute_gas!(codecopy, "CODECOPY", instructions::system::codecopy); - - wrap_op_compute_gas!(gasprice, "GASPRICE", instructions::tx_info::gasprice); - wrap_op_compute_gas!(extcodesize, "EXTCODESIZE", instructions::host::extcodesize); - wrap_op_compute_gas!(extcodecopy, "EXTCODECOPY", instructions::host::extcodecopy); - wrap_op_compute_gas!(returndatasize, "RETURNDATASIZE", instructions::system::returndatasize); - wrap_op_compute_gas!(returndatacopy, "RETURNDATACOPY", instructions::system::returndatacopy); - wrap_op_compute_gas!(extcodehash, "EXTCODEHASH", instructions::host::extcodehash); - wrap_op_compute_gas!(blockhash, "BLOCKHASH", instructions::host::blockhash); - wrap_op_compute_gas!(coinbase, "COINBASE", instructions::block_info::coinbase); - wrap_op_compute_gas!(timestamp, "TIMESTAMP", instructions::block_info::timestamp); - wrap_op_compute_gas!(number, "NUMBER", instructions::block_info::block_number); - wrap_op_compute_gas!(difficulty, "DIFFICULTY", instructions::block_info::difficulty); - wrap_op_compute_gas!(gaslimit, "GASLIMIT", instructions::block_info::gaslimit); - wrap_op_compute_gas!(chainid, "CHAINID", instructions::block_info::chainid); - wrap_op_compute_gas!(selfbalance, "SELFBALANCE", instructions::host::selfbalance); - wrap_op_compute_gas!(basefee, "BASEFEE", instructions::block_info::basefee); - wrap_op_compute_gas!(blobhash, "BLOBHASH", instructions::tx_info::blob_hash); - wrap_op_compute_gas!(blobbasefee, "BLOBBASEFEE", instructions::block_info::blob_basefee); - - wrap_op_compute_gas!(pop, "POP", instructions::stack::pop); - wrap_op_compute_gas!(mload, "MLOAD", instructions::memory::mload); - wrap_op_compute_gas!(mstore, "MSTORE", instructions::memory::mstore); - wrap_op_compute_gas!(mstore8, "MSTORE8", instructions::memory::mstore8); - wrap_op_compute_gas!(sload, "SLOAD", instructions::host::sload); - wrap_op_compute_gas!(jump, "JUMP", instructions::control::jump); - wrap_op_compute_gas!(jumpi, "JUMPI", instructions::control::jumpi); - wrap_op_compute_gas!(pc, "PC", instructions::control::pc); - wrap_op_compute_gas!(msize, "MSIZE", instructions::memory::msize); - wrap_op_compute_gas!(gas, "GAS", instructions::system::gas); - wrap_op_compute_gas!(jumpdest, "JUMPDEST", instructions::control::jumpdest); - wrap_op_compute_gas!(tload, "TLOAD", instructions::host::tload); - wrap_op_compute_gas!(tstore, "TSTORE", instructions::host::tstore); - wrap_op_compute_gas!(mcopy, "MCOPY", instructions::memory::mcopy); - - wrap_op_compute_gas!(push0, "PUSH0", instructions::stack::push0); - wrap_op_compute_gas!(push1, "PUSH1", instructions::stack::push::<1, _, _>); - wrap_op_compute_gas!(push2, "PUSH2", instructions::stack::push::<2, _, _>); - wrap_op_compute_gas!(push3, "PUSH3", instructions::stack::push::<3, _, _>); - wrap_op_compute_gas!(push4, "PUSH4", instructions::stack::push::<4, _, _>); - wrap_op_compute_gas!(push5, "PUSH5", instructions::stack::push::<5, _, _>); - wrap_op_compute_gas!(push6, "PUSH6", instructions::stack::push::<6, _, _>); - wrap_op_compute_gas!(push7, "PUSH7", instructions::stack::push::<7, _, _>); - wrap_op_compute_gas!(push8, "PUSH8", instructions::stack::push::<8, _, _>); - wrap_op_compute_gas!(push9, "PUSH9", instructions::stack::push::<9, _, _>); - wrap_op_compute_gas!(push10, "PUSH10", instructions::stack::push::<10, _, _>); - wrap_op_compute_gas!(push11, "PUSH11", instructions::stack::push::<11, _, _>); - wrap_op_compute_gas!(push12, "PUSH12", instructions::stack::push::<12, _, _>); - wrap_op_compute_gas!(push13, "PUSH13", instructions::stack::push::<13, _, _>); - wrap_op_compute_gas!(push14, "PUSH14", instructions::stack::push::<14, _, _>); - wrap_op_compute_gas!(push15, "PUSH15", instructions::stack::push::<15, _, _>); - wrap_op_compute_gas!(push16, "PUSH16", instructions::stack::push::<16, _, _>); - wrap_op_compute_gas!(push17, "PUSH17", instructions::stack::push::<17, _, _>); - wrap_op_compute_gas!(push18, "PUSH18", instructions::stack::push::<18, _, _>); - wrap_op_compute_gas!(push19, "PUSH19", instructions::stack::push::<19, _, _>); - wrap_op_compute_gas!(push20, "PUSH20", instructions::stack::push::<20, _, _>); - wrap_op_compute_gas!(push21, "PUSH21", instructions::stack::push::<21, _, _>); - wrap_op_compute_gas!(push22, "PUSH22", instructions::stack::push::<22, _, _>); - wrap_op_compute_gas!(push23, "PUSH23", instructions::stack::push::<23, _, _>); - wrap_op_compute_gas!(push24, "PUSH24", instructions::stack::push::<24, _, _>); - wrap_op_compute_gas!(push25, "PUSH25", instructions::stack::push::<25, _, _>); - wrap_op_compute_gas!(push26, "PUSH26", instructions::stack::push::<26, _, _>); - wrap_op_compute_gas!(push27, "PUSH27", instructions::stack::push::<27, _, _>); - wrap_op_compute_gas!(push28, "PUSH28", instructions::stack::push::<28, _, _>); - wrap_op_compute_gas!(push29, "PUSH29", instructions::stack::push::<29, _, _>); - wrap_op_compute_gas!(push30, "PUSH30", instructions::stack::push::<30, _, _>); - wrap_op_compute_gas!(push31, "PUSH31", instructions::stack::push::<31, _, _>); - wrap_op_compute_gas!(push32, "PUSH32", instructions::stack::push::<32, _, _>); - - wrap_op_compute_gas!(dup1, "DUP1", instructions::stack::dup::<1, _, _>); - wrap_op_compute_gas!(dup2, "DUP2", instructions::stack::dup::<2, _, _>); - wrap_op_compute_gas!(dup3, "DUP3", instructions::stack::dup::<3, _, _>); - wrap_op_compute_gas!(dup4, "DUP4", instructions::stack::dup::<4, _, _>); - wrap_op_compute_gas!(dup5, "DUP5", instructions::stack::dup::<5, _, _>); - wrap_op_compute_gas!(dup6, "DUP6", instructions::stack::dup::<6, _, _>); - wrap_op_compute_gas!(dup7, "DUP7", instructions::stack::dup::<7, _, _>); - wrap_op_compute_gas!(dup8, "DUP8", instructions::stack::dup::<8, _, _>); - wrap_op_compute_gas!(dup9, "DUP9", instructions::stack::dup::<9, _, _>); - wrap_op_compute_gas!(dup10, "DUP10", instructions::stack::dup::<10, _, _>); - wrap_op_compute_gas!(dup11, "DUP11", instructions::stack::dup::<11, _, _>); - wrap_op_compute_gas!(dup12, "DUP12", instructions::stack::dup::<12, _, _>); - wrap_op_compute_gas!(dup13, "DUP13", instructions::stack::dup::<13, _, _>); - wrap_op_compute_gas!(dup14, "DUP14", instructions::stack::dup::<14, _, _>); - wrap_op_compute_gas!(dup15, "DUP15", instructions::stack::dup::<15, _, _>); - wrap_op_compute_gas!(dup16, "DUP16", instructions::stack::dup::<16, _, _>); - - wrap_op_compute_gas!(swap1, "SWAP1", instructions::stack::swap::<1, _, _>); - wrap_op_compute_gas!(swap2, "SWAP2", instructions::stack::swap::<2, _, _>); - wrap_op_compute_gas!(swap3, "SWAP3", instructions::stack::swap::<3, _, _>); - wrap_op_compute_gas!(swap4, "SWAP4", instructions::stack::swap::<4, _, _>); - wrap_op_compute_gas!(swap5, "SWAP5", instructions::stack::swap::<5, _, _>); - wrap_op_compute_gas!(swap6, "SWAP6", instructions::stack::swap::<6, _, _>); - wrap_op_compute_gas!(swap7, "SWAP7", instructions::stack::swap::<7, _, _>); - wrap_op_compute_gas!(swap8, "SWAP8", instructions::stack::swap::<8, _, _>); - wrap_op_compute_gas!(swap9, "SWAP9", instructions::stack::swap::<9, _, _>); - wrap_op_compute_gas!(swap10, "SWAP10", instructions::stack::swap::<10, _, _>); - wrap_op_compute_gas!(swap11, "SWAP11", instructions::stack::swap::<11, _, _>); - wrap_op_compute_gas!(swap12, "SWAP12", instructions::stack::swap::<12, _, _>); - wrap_op_compute_gas!(swap13, "SWAP13", instructions::stack::swap::<13, _, _>); - wrap_op_compute_gas!(swap14, "SWAP14", instructions::stack::swap::<14, _, _>); - wrap_op_compute_gas!(swap15, "SWAP15", instructions::stack::swap::<15, _, _>); - wrap_op_compute_gas!(swap16, "SWAP16", instructions::stack::swap::<16, _, _>); - - wrap_op_compute_gas!(@frame call_code, "CALLCODE", instructions::contract::call_code); - wrap_op_compute_gas!(ret, "RETURN", instructions::control::ret); - wrap_op_compute_gas!(@frame delegate_call, "DELEGATECALL", instructions::contract::delegate_call); - wrap_op_compute_gas!(@frame static_call, "STATICCALL", instructions::contract::static_call); - - wrap_op_compute_gas!(revert, "REVERT", instructions::control::revert); - wrap_op_compute_gas!(invalid, "INVALID", instructions::control::invalid); - - /// `SELFDESTRUCT` opcode with compute gas tracking. - /// - /// Unlike the default wrapper, the trailing check fans out across all four limit - /// dimensions (`record_compute_gas_all_dims`): the REX5 storage wrapper records - /// beneficiary data/KV/state usage *before* the inner instruction runs, without - /// latching, and those dimensions must latch (and halt) here — only once the inner - /// instruction has succeeded. Latching at the recording site instead would stick - /// even when the inner instruction subsequently fails and the frame's discardable - /// usage is rolled back. - pub fn selfdestruct( - context: InstructionContext<'_, H, WIRE>, - ) { - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!(instructions::host::selfdestruct, context); - - let gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - let mut additional_limit = context.host.additional_limit().borrow_mut(); - if !additional_limit.record_compute_gas_all_dims(gas_used) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } -} - -/// Trait to inspect the stack elements. -pub trait StackInspectTr { - /// Inspect the N-th element of the stack. The top of the stack is the 0-th element. - /// If the stack is too short, return None. - fn inspect(&self) -> Option; -} - -impl StackInspectTr for Stack { - fn inspect(&self) -> Option { - if N >= self.len() { - return None; - } - let index = self.len() - 1 - N; - // SAFETY: the index must be within the bounds of the stack - Some(unsafe { *self.data().get_unchecked(index) }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - - /// Every alias spec must select exactly its `behavior()` target's instruction - /// table — the match in `MegaInstructions::new` states the alias→target mapping a - /// second time, and this test is the reconciliation between the two. Both tables - /// come from the same monomorphization, so identical arms produce identical fn - /// pointers and `fn_addr_eq` compares them reliably. - #[test] - fn test_alias_specs_use_their_behavior_targets_table() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - let alias = MegaInstructions::::new(*spec); - let target = MegaInstructions::::new(spec.behavior()); - let (alias_table, target_table) = - (alias.instruction_table(), target.instruction_table()); - for opcode in 0..=0xff_usize { - assert!( - core::ptr::fn_addr_eq(alias_table[opcode], target_table[opcode]), - "{spec:?} table diverges from its behavior target {:?} at opcode {opcode:#04x}", - spec.behavior(), - ); - } - } - } -} diff --git a/crates/mega-evm/src/evm/interfaces.rs b/crates/mega-evm/src/evm/interfaces.rs deleted file mode 100644 index 4f46cb05f..000000000 --- a/crates/mega-evm/src/evm/interfaces.rs +++ /dev/null @@ -1,236 +0,0 @@ -use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; -use alloy_primitives::{Address, Bytes}; -use revm::{ - context::{ - result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, - BlockEnv, ContextSetters, ContextTr, - }, - handler::{EthFrame, EvmTr, SystemCallTx}, - interpreter::interpreter::EthInterpreter, - state::EvmState, - DatabaseCommit, InspectEvm, Inspector, SystemCallEvm, -}; - -use crate::{ - ExternalEnvTypes, IntoMegaethCfgEnv, MegaContext, MegaEvm, MegaHaltReason, MegaHandler, - MegaSpecId, MegaTransaction, MegaTransactionError, -}; - -/// Implementation of [`alloy_evm::Evm`] for `MegaETH` EVM. -/// -/// This implementation provides the core EVM interface required by the Alloy EVM framework, -/// enabling seamless integration with Alloy-based applications while providing `MegaETH`-specific -/// customizations and optimizations. -impl alloy_evm::Evm for MegaEvm -where - DB: Database, - INSP: Inspector>, -{ - type DB = DB; - type Tx = MegaTransaction; - type Error = EVMError; - type HaltReason = MegaHaltReason; - type Spec = MegaSpecId; - type Precompiles = PrecompilesMap; - type Inspector = INSP; - - fn block(&self) -> &BlockEnv { - self.block_env_ref() - } - - fn chain_id(&self) -> u64 { - self.ctx_ref().cfg.chain_id - } - - fn transact_raw( - &mut self, - tx: Self::Tx, - ) -> Result, Self::Error> { - if self.inspect { - InspectEvm::inspect_tx(self, tx) - } else { - revm::ExecuteEvm::transact(self, tx) - } - } - - /// Transact a system call. - /// - /// This method enables system calls within the `MegaETH` EVM, following the same - /// pattern as the Optimism EVM. System calls are special transactions that can - /// interact with the underlying system without going through the normal transaction - /// validation process. - /// - /// # Parameters - /// - /// - `caller`: The address making the system call - /// - `contract`: The target contract address - /// - `data`: The call data to execute - /// - /// # Returns - /// - /// The execution result and state changes from the system call. - /// - /// # Note - /// - /// This function copies the logic from `alloy_op_evm::OpEvm::transact_system_call` - /// to maintain compatibility with the Optimism EVM system call interface. The - /// transaction's gas limit follows revm's upstream-fixed 30M default. Callers that - /// need to use the live block gas budget — e.g. REX5 pre-block helpers whose cost is - /// sensitive to dynamic storage gas — should use - /// [`MegaEvm::transact_system_call_with_gas_limit`] instead. - fn transact_system_call( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - ) -> Result, Self::Error> { - self.transact_system_call_with_caller_finalize(caller, contract, data) - } - - fn finish(self) -> (Self::DB, EvmEnv) - where - Self: Sized, - { - let spec = self.inner.ctx.mega_spec(); - let revm::Context { block: block_env, cfg: cfg_env, journaled_state, .. } = - self.inner.ctx.into_inner(); - let cfg_env = cfg_env.into_megaeth_cfg(spec); - (journaled_state.database, EvmEnv { block_env, cfg_env }) - } - - fn set_inspector_enabled(&mut self, enabled: bool) { - self.inspect = enabled; - } - - fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { - (&self.inner.ctx.journaled_state.database, &self.inner.inspector, &self.inner.precompiles) - } - - fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { - ( - &mut self.inner.ctx.journaled_state.database, - &mut self.inner.inspector, - &mut self.inner.precompiles, - ) - } -} - -impl revm::ExecuteEvm for MegaEvm -where - DB: Database, -{ - type Tx = MegaTransaction; - type Block = BlockEnv; - 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.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run(&mut h, self) - } - - fn finalize(&mut self) -> Self::State { - self.inner.ctx.journal_mut().finalize() - } - - fn replay( - &mut self, - ) -> Result, Self::Error> { - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run(&mut h, self).map(|result| { - let state = self.finalize(); - ExecResultAndState::new(result, state) - }) - } -} - -impl revm::ExecuteCommitEvm for MegaEvm -where - DB: Database + DatabaseCommit, -{ - fn commit(&mut self, state: Self::State) { - self.ctx().db_mut().commit(state); - } -} - -impl revm::InspectEvm for MegaEvm -where - DB: Database, - INSP: Inspector>, -{ - type Inspector = INSP; - - fn set_inspector(&mut self, inspector: Self::Inspector) { - self.inner.inspector = inspector; - } - - fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { - self.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::inspector::InspectorHandler::inspect_run(&mut h, self) - } -} - -impl revm::InspectCommitEvm for MegaEvm -where - DB: Database + DatabaseCommit, - INSP: Inspector>, -{ -} - -impl revm::SystemCallEvm for MegaEvm -where - DB: Database, -{ - fn transact_system_call_with_caller( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - ) -> Result { - self.ctx().set_tx(::new_system_tx_with_caller( - caller, contract, data, - )); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run_system_call(&mut h, self) - } -} - -impl MegaEvm -where - DB: Database, -{ - /// Transact a system call with an explicit gas limit and finalize. - /// - /// Behaves like [`alloy_evm::Evm::transact_system_call`] but lets the caller specify - /// the gas limit instead of relying on revm's upstream-fixed 30M default. This is - /// intended for REX5+ pre-block helpers (e.g. `transact_apply_pending_changes` in - /// `system::sequencer_registry`) whose real cost is sensitive to dynamic storage gas - /// and is no longer guaranteed to fit within 30M on activation blocks. - /// - /// The recommended argument is - /// `block.gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR)`. - pub fn transact_system_call_with_gas_limit( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, - ) -> Result, EVMError> { - let mut tx = - ::new_system_tx_with_caller(caller, contract, data); - tx.base.gas_limit = gas_limit; - self.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run_system_call(&mut h, self).map(|result| { - let state = self.inner.ctx.journal_mut().finalize(); - ResultAndState { result, state } - }) - } -} diff --git a/crates/mega-evm/src/evm/limit.rs b/crates/mega-evm/src/evm/limit.rs deleted file mode 100644 index b9111abb8..000000000 --- a/crates/mega-evm/src/evm/limit.rs +++ /dev/null @@ -1,185 +0,0 @@ -use crate::MegaSpecId; - -/// Runtime limits for a single transaction. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct EvmTxRuntimeLimits { - // ====== Limits enforced during transaction execution ====== - /// Maximum data size for a single transaction. - pub tx_data_size_limit: u64, - /// Maximum key-value updates for a single transaction. - pub tx_kv_updates_limit: u64, - /// Maximum compute gas limit for a single transaction. - pub tx_compute_gas_limit: u64, - /// Maximum state growth limit for a single transaction. - pub tx_state_growth_limit: u64, - /// Compute gas limit when accessing block environment data. - pub block_env_access_compute_gas_limit: u64, - /// Compute gas limit when accessing oracle data. - pub oracle_access_compute_gas_limit: u64, -} - -impl EvmTxRuntimeLimits { - /// Creates a new `TxLimits` instance from the given `MegaSpecId`. - pub fn from_spec(spec: MegaSpecId) -> Self { - // An alias spec is grouped with its `behavior()` target so it runs under exactly the - // target's limits; the grouping must agree with `behavior()`, pinned by - // `test_alias_specs_use_their_behavior_targets_limits`. - match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => Self::equivalence(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => Self::mini_rex(), - MegaSpecId::REX | MegaSpecId::REX1 | MegaSpecId::REX2 => Self::rex(), - MegaSpecId::REX3 => Self::rex3(), - MegaSpecId::REX4 => Self::rex4(), - MegaSpecId::REX5 => Self::rex5(), - MegaSpecId::REX6 => Self::rex6(), - MegaSpecId::REX7 => Self::rex7(), - } - } - - /// No limits. - pub fn no_limits() -> Self { - Self { - tx_data_size_limit: u64::MAX, - tx_kv_updates_limit: u64::MAX, - tx_compute_gas_limit: u64::MAX, - tx_state_growth_limit: u64::MAX, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - /// Limits for the `EQUIVALENCE` spec. - pub fn equivalence() -> Self { - Self::no_limits() - } - - /// Limits for the `MINI_REX` spec. - pub fn mini_rex() -> Self { - Self { - tx_data_size_limit: crate::constants::mini_rex::TX_DATA_LIMIT, - tx_kv_updates_limit: crate::constants::mini_rex::TX_KV_UPDATE_LIMIT, - tx_compute_gas_limit: crate::constants::mini_rex::TX_COMPUTE_GAS_LIMIT, - block_env_access_compute_gas_limit: - crate::constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - oracle_access_compute_gas_limit: crate::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - ..Self::equivalence() - } - } - - /// Limits for the `REX` spec. - pub fn rex() -> Self { - Self { - tx_data_size_limit: crate::constants::rex::TX_DATA_LIMIT, - tx_kv_updates_limit: crate::constants::rex::TX_KV_UPDATE_LIMIT, - tx_compute_gas_limit: crate::constants::rex::TX_COMPUTE_GAS_LIMIT, - tx_state_growth_limit: crate::constants::rex::TX_STATE_GROWTH_LIMIT, - block_env_access_compute_gas_limit: - crate::constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - oracle_access_compute_gas_limit: crate::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - } - } - - /// Limits for the `REX3` spec. - fn rex3() -> Self { - Self { - oracle_access_compute_gas_limit: crate::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - ..Self::rex() - } - } - - /// Limits for the `REX4` spec. - /// - /// Currently identical to Rex3 limits. - /// Per-frame state growth budgets are handled by `FrameLimitTracker`. - fn rex4() -> Self { - Self::rex3() - } - - /// Limits for the `REX5` spec. - /// - /// Currently identical to Rex4 limits. - fn rex5() -> Self { - Self::rex4() - } - - /// Limits for the `REX6` spec. - /// - /// Currently identical to Rex5 limits. - fn rex6() -> Self { - Self::rex5() - } - - /// Limits for the `REX7` spec. - /// - /// Currently identical to Rex6 limits. - fn rex7() -> Self { - Self::rex6() - } -} - -impl EvmTxRuntimeLimits { - /// Sets the maximum data size for a single transaction. - pub fn with_tx_data_size_limit(mut self, tx_data_size_limit: u64) -> Self { - self.tx_data_size_limit = tx_data_size_limit; - self - } - - /// Sets the maximum key-value updates for a single transaction. - pub fn with_tx_kv_updates_limit(mut self, tx_kv_updates_limit: u64) -> Self { - self.tx_kv_updates_limit = tx_kv_updates_limit; - self - } - - /// Sets the maximum compute gas limit for a single transaction. - pub fn with_tx_compute_gas_limit(mut self, tx_compute_gas_limit: u64) -> Self { - self.tx_compute_gas_limit = tx_compute_gas_limit; - self - } - - /// Sets the maximum state growth limit for a single transaction. - pub fn with_tx_state_growth_limit(mut self, tx_state_growth_limit: u64) -> Self { - self.tx_state_growth_limit = tx_state_growth_limit; - self - } - - /// Sets the compute gas limit when accessing block environment data. - pub fn with_block_env_access_compute_gas_limit( - mut self, - block_env_access_compute_gas_limit: u64, - ) -> Self { - self.block_env_access_compute_gas_limit = block_env_access_compute_gas_limit; - self - } - - /// Sets the compute gas limit when accessing oracle data. - pub fn with_oracle_access_compute_gas_limit( - mut self, - oracle_access_compute_gas_limit: u64, - ) -> Self { - self.oracle_access_compute_gas_limit = oracle_access_compute_gas_limit; - self - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Every alias spec must run under exactly its `behavior()` target's limits — the - /// match in `from_spec` states the alias→target mapping a second time, and this - /// test is the reconciliation between the two. - #[test] - fn test_alias_specs_use_their_behavior_targets_limits() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - assert_eq!( - EvmTxRuntimeLimits::from_spec(*spec), - EvmTxRuntimeLimits::from_spec(spec.behavior()), - "{spec:?} limits diverge from its behavior target {:?}", - spec.behavior(), - ); - } - } -} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs deleted file mode 100644 index 5ddf94f2f..000000000 --- a/crates/mega-evm/src/evm/mod.rs +++ /dev/null @@ -1,622 +0,0 @@ -//! EVM implementation for the `MegaETH` chain. -//! -//! This module provides the core EVM implementation specifically tailored for the `MegaETH` -//! chain, built on top of the Optimism EVM (`op-revm`) with MegaETH-specific customizations -//! and optimizations. -//! -//! # Architecture -//! -//! The EVM implementation consists of two main components: -//! -//! 1. **`EvmFactory`**: Factory for creating EVM instances with `MegaETH` specifications -//! 2. **`Evm`**: The main EVM instance that wraps the Optimism EVM with `MegaETH` customizations -//! -//! # EVM Specifications -//! -//! `MegaETH` supports multiple EVM specifications: -//! -//! - **`EQUIVALENCE`**: Maintains equivalence with Optimism Isthmus EVM -//! - **`MINI_REX`**: Enhanced version with quadratic LOG costs and disabled SELFDESTRUCT -//! - **`REX`**: Fixes `MiniRex` call opcode inconsistencies and refines storage gas -//! - **`REX1`**: Resets compute gas limits between transactions -//! - **`REX2`**: Re-enables SELFDESTRUCT with EIP-6780 semantics -//! - **`REX3`**: Increases oracle gas limit to 20M, moves oracle detention to SLOAD-based, tracks -//! keyless deploy compute gas -//! - **`REX4`**: Per-call-frame resource budgets, relative gas detention, storage gas stipend, -//! `MegaAccessControl` and `MegaLimitControl` system contracts - -mod context; -mod execution; -mod factory; -mod host; -mod instructions; -mod interfaces; -mod limit; -mod precompiles; -mod result; -mod spec; -mod state; - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{collections::BTreeMap, vec::Vec}; - -use alloy_primitives::{Address, B256}; -pub use context::*; -pub use execution::*; -pub use factory::*; -pub use host::*; -pub use instructions::*; -#[allow(unused_imports, unreachable_pub)] -pub use interfaces::*; -pub use limit::*; -pub use precompiles::*; -pub use result::*; -pub use spec::*; -pub use state::*; - -use alloy_evm::{ - precompiles::{DynPrecompile, PrecompilesMap}, - Database, -}; -use revm::{ - context::{result::ResultAndState, BlockEnv, ContextTr}, - handler::{EthFrame, EvmTr}, - inspector::NoOpInspector, - interpreter::interpreter::EthInterpreter, - primitives::HashMap, - ExecuteEvm, InspectEvm, Inspector, Journal, -}; - -use crate::{BucketId, ExternalEnvTypes, LimitUsage, MegaTransaction}; - -/// The main EVM implementation for the `MegaETH` chain. -/// -/// This struct wraps the underlying Optimism EVM (`OpEvm`) with `MegaETH`-specific customizations -/// and optimizations. It provides access to enhanced security features, increased limits, and -/// block environment access tracking capabilities. -/// -/// # Type Parameters -/// -/// - `DB`: The database type implementing [`Database`] -/// - `INSP`: The inspector type implementing [`Inspector`] -/// - `Oracle`: The `external_envs` type implementing [`ExternalEnvs`] -/// -/// # Implementation Details -/// -/// The EVM uses delegation to efficiently wrap the underlying Optimism EVM while providing -/// `MegaETH`-specific customizations through the configured context, instructions, and precompiles. -#[allow(missing_debug_implementations)] -#[allow(clippy::type_complexity)] -pub struct MegaEvm { - inner: revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - >, - /// Whether to enable the inspector at runtime. - inspect: bool, -} - -impl core::fmt::Debug - for MegaEvm -{ - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethEvm").field("inspect", &self.inspect).finish_non_exhaustive() - } -} - -impl core::ops::Deref - for MegaEvm -{ - type Target = revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - >; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl core::ops::DerefMut - for MegaEvm -{ - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.inner - } -} - -impl MegaEvm { - /// Creates a new `MegaETH` EVM instance. - /// - /// # Parameters - /// - /// - `context`: The `MegaETH` context containing database, configuration, and `external_envs` - /// - `inspect`: The inspector to use for debugging and monitoring - /// - /// # Returns - /// - /// A new `Evm` instance configured with the provided context and inspector. - pub fn new(context: MegaContext) -> Self { - let spec = context.mega_spec(); - Self { - inner: revm::context::Evm::new_with_inspector( - context, - NoOpInspector, - MegaInstructions::new(spec), - PrecompilesMap::from_static(MegaPrecompiles::new_with_spec(spec).precompiles()), - ), - inspect: false, - } - } -} - -impl MegaEvm { - /// Creates a new `MegaETH` EVM instance with the given inspector enabled at runtime. - /// - /// # Parameters - /// - /// - `inspector`: The new inspector to use for debugging and monitoring - /// - /// # Returns - /// - /// A new `Evm` instance with the specified inspector enabled. - pub fn with_inspector(self, inspector: I) -> MegaEvm { - let inner = revm::context::Evm::new_with_inspector( - self.inner.ctx, - inspector, - self.inner.instruction, - self.inner.precompiles, - ); - MegaEvm { inner, inspect: true } - } - - /// Creates a new `MegaETH` EVM instance with the inspector disabled at runtime. - /// - /// # Returns - /// - /// A new `Evm` instance with the inspector disabled. - pub fn without_inspector(self) -> MegaEvm { - let inner = revm::context::Evm::new_with_inspector( - self.inner.ctx, - NoOpInspector, - self.inner.instruction, - self.inner.precompiles, - ); - MegaEvm { inner, inspect: false } - } - - /// Sets the transaction runtime limits for the EVM. - pub fn with_tx_runtime_limits(self, tx_limits: EvmTxRuntimeLimits) -> Self { - let inner = revm::context::Evm { - ctx: self.inner.ctx.with_tx_runtime_limits(tx_limits), - inspector: self.inner.inspector, - instruction: self.inner.instruction, - precompiles: self.inner.precompiles, - frame_stack: self.inner.frame_stack, - }; - Self { inner, inspect: self.inspect } - } - - /// Adds or overrides dynamic precompiles in the EVM. - /// - /// # Parameters - /// - /// - `dyn_precompiles`: The dynamic precompiles to add to the EVM, overriding the existing - /// precompiles if they already exist. - /// - /// # Returns - /// - /// A new `Evm` instance with the dynamic precompiles added. - fn with_dyn_precompiles(self, dyn_precompiles: HashMap) -> Self { - let mut precompiles = self.inner.precompiles; - // Apply the dynamic precompiles to the precompiles map. If the precompile already exists, - // it will be overridden with the dynamic precompile. - for (address, dyn_precompile) in dyn_precompiles { - precompiles.apply_precompile(&address, move |_| Some(dyn_precompile)); - } - let inner = revm::context::Evm { - ctx: self.inner.ctx, - inspector: self.inner.inspector, - instruction: self.inner.instruction, - precompiles, - frame_stack: self.inner.frame_stack, - }; - Self { inner, inspect: self.inspect } - } -} - -impl MegaEvm { - /// Provides a reference to the block environment. - /// - /// The block environment contains information about the current block being processed, - /// including block number, timestamp, gas limit, and other block-specific data. - #[inline] - pub fn block_env_ref(&self) -> &BlockEnv { - &self.ctx_ref().block - } - - /// Provides a mutable reference to the block environment. - /// - /// This allows modification of block environment data during EVM execution, - /// which is useful for testing and simulation scenarios. - #[inline] - pub fn block_env_mut(&mut self) -> &mut BlockEnv { - &mut self.ctx().block - } - - /// Provides a reference to the journaled state. - /// - /// The journaled state tracks all state changes during transaction execution, - /// enabling rollback capabilities and state management. - #[inline] - pub fn journaled_state(&self) -> &Journal { - &self.ctx_ref().journaled_state - } - - /// Provides a mutable reference to the journaled state. - /// - /// This allows direct manipulation of the journaled state for advanced - /// use cases and testing scenarios. - #[inline] - pub fn journaled_state_mut(&mut self) -> &mut Journal { - &mut self.ctx().journaled_state - } - - /// Consumes self and returns the journaled state. - /// - /// This is useful when you need to extract the final state after EVM execution - /// and no longer need the EVM instance. - #[inline] - #[deprecated(note = "Use `into_inner` instead")] - pub fn into_journaled_state(self) -> Journal { - self.inner.ctx.inner.journaled_state - } - - /// Consumes the `MegaEvm` instance and returns the inner EVM. - /// - /// This method is typically used after EVM execution when you need to access - /// the underlying EVM components and no longer require the `MegaEvm` wrapper. - #[inline] - #[allow(clippy::type_complexity)] - pub fn into_inner( - self, - ) -> revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - > { - self.inner - } -} - -impl MegaEvm -where - DB: Database, - INSP: Inspector>, - ExtEnvs: ExternalEnvTypes, -{ - /// Execute a transaction and return the outcome. If the inspector is set, it will be used to - /// inspect the transaction. - /// Users can use [`MegaEvm::with_inspector`] to set up a custom inspector. - /// Users can use [`MegaEvm::without_inspector`] to disable the inspector. - /// - /// # Parameters - /// - /// - `tx`: The transaction to execute - /// - /// # Returns - /// - /// The outcome of the transaction. - pub fn execute_transaction( - &mut self, - tx: MegaTransaction, - ) -> Result> { - let ResultAndState { result, state } = if self.inspect { - InspectEvm::inspect_tx(self, tx)? - } else { - ExecuteEvm::transact(self, tx)? - }; - let additional_limit = self.ctx().additional_limit.borrow(); - let LimitUsage { data_size, kv_updates, compute_gas, state_growth } = - additional_limit.get_usage(); - Ok(MegaTransactionOutcome { - result, - state, - data_size, - kv_updates, - compute_gas_used: compute_gas, - state_growth_used: state_growth, - }) - } - - /// Inspect a transaction and return the outcome. The inspector used is the one set up already - /// in the EVM. Use [`MegaEvm::with_inspector`] to set up a custom inspector. - /// - /// # Parameters - /// - /// - `tx`: The transaction to inspect - /// - /// # Returns - /// - /// The outcome of the transaction. - #[deprecated( - since = "1.0.2", - note = "Use `MegaEvm::execute_transaction` instead, which will automatically use the inspector if it is set up" - )] - pub fn inspect_transaction( - &mut self, - tx: MegaTransaction, - ) -> Result> { - let ResultAndState { result, state } = InspectEvm::inspect_tx(self, tx)?; - let additional_limit = self.ctx().additional_limit.borrow(); - let LimitUsage { data_size, kv_updates, compute_gas, state_growth } = - additional_limit.get_usage(); - Ok(MegaTransactionOutcome { - result, - state, - data_size, - kv_updates, - compute_gas_used: compute_gas, - state_growth_used: state_growth, - }) - } - - /// Get the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn get_accessed_bucket_ids(&self) -> Vec { - self.ctx_ref().dynamic_storage_gas_cost.borrow().get_bucket_ids() - } -} - -impl MegaEvm { - /// Get the block hashes used during transaction execution. - /// - /// # Returns - /// - /// Returns the block hashes used during transaction execution. - pub fn get_accessed_block_hashes(&self) -> BTreeMap { - self.db_ref().get_accessed_block_hashes() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use alloy_primitives::{address, Bytes, U256}; - use revm::{ - context::{ - result::{ExecResultAndState, ExecutionResult}, - ContextSetters, TxEnv, - }, - database::State, - inspector::NoOpInspector, - state::EvmState, - ExecuteCommitEvm, ExecuteEvm, InspectEvm, SystemCallEvm, - }; - - const CALLER: Address = address!("4000000000000000000000000000000000000001"); - const CALLEE: Address = address!("5000000000000000000000000000000000000001"); - - fn configure_context(db: DB) -> MegaContext { - let mut context = MegaContext::new(db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context - } - - fn tx_env() -> TxEnv { - TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::ZERO, - data: Bytes::new(), - ..Default::default() - } - } - - fn mega_tx() -> MegaTransaction { - let mut tx = MegaTransaction::new(tx_env()); - tx.enveloped_tx = Some(Bytes::new()); - tx - } - - #[test] - fn test_mega_evm_builder_chain_produces_working_evm() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let context = configure_context(&mut db); - let evm = MegaEvm::new(context); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(777); - let evm = evm.with_tx_runtime_limits(limits); - assert_eq!(evm.ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, 777); - - let evm = evm.with_dyn_precompiles(HashMap::default()); - let evm = evm.with_inspector(NoOpInspector); - let evm = evm.without_inspector(); - - let inner = evm.into_inner(); - assert_eq!(inner.ctx.block.gas_limit, u64::MAX); - } - - #[test] - fn test_alloy_evm_interface_methods_execute_transactions() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - assert_eq!(alloy_evm::Evm::chain_id(&evm), evm.ctx_ref().cfg.chain_id); - assert_eq!(alloy_evm::Evm::block(&evm).gas_limit, evm.ctx_ref().block.gas_limit); - - alloy_evm::Evm::set_inspector_enabled(&mut evm, true); - assert!(evm.inspect); - let (_db_ref, _inspector, _precompiles) = alloy_evm::Evm::components(&evm); - let (_db_ref_mut, _inspector_mut, _precompiles_mut) = - alloy_evm::Evm::components_mut(&mut evm); - - let result = alloy_evm::Evm::transact_raw(&mut evm, mega_tx()).unwrap(); - assert!(result.result.is_success()); - - let system_call = - alloy_evm::Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()).unwrap(); - assert!(system_call.result.is_success()); - - let (_db_back, evm_env) = alloy_evm::Evm::finish(evm); - assert_eq!(evm_env.cfg_env.spec, MegaSpecId::REX4); - } - - #[test] - fn test_revm_execute_one_finalize_commit_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let block = revm::context::BlockEnv { gas_limit: 222_222, ..Default::default() }; - ExecuteEvm::set_block(&mut evm, block); - assert_eq!(evm.block_env_ref().gas_limit, 222_222); - - let one: ExecutionResult = - ExecuteEvm::transact_one(&mut evm, mega_tx()).unwrap(); - assert!(one.is_success()); - let state = ExecuteEvm::finalize(&mut evm); - ExecuteCommitEvm::commit(&mut evm, state); - } - - #[test] - fn test_revm_replay_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - evm.ctx().set_tx(mega_tx()); - let replay: ExecResultAndState, EvmState> = - ExecuteEvm::replay(&mut evm).unwrap(); - assert!(replay.result.is_success()); - } - - #[test] - fn test_revm_inspect_one_tx_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - InspectEvm::set_inspector(&mut evm, NoOpInspector); - let inspected: ExecutionResult = - InspectEvm::inspect_one_tx(&mut evm, mega_tx()).unwrap(); - assert!(inspected.is_success()); - } - - #[test] - fn test_revm_system_call_with_caller_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let system_call: ExecutionResult = - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - assert!(system_call.is_success()); - } - - #[test] - fn test_transact_system_call_with_gas_limit_uses_passed_value() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) - .unwrap(); - assert!(result.result.is_success()); - // The custom gas limit must be applied to the underlying tx. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 123_456_789); - } - - #[test] - fn test_default_system_call_keeps_upstream_30m_gas_limit() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context.block.gas_limit = 100_000_000; - let mut evm = MegaEvm::new(context); - - // The default system-call entry point must NOT be widened by REX5 — only the - // explicit `transact_system_call_with_gas_limit` path should pick up the live - // block budget. This preserves byte-level behavior of EIP-2935 / EIP-4788 - // pre-block calls across all specs. - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - // Literal, not `SYSTEM_CALL_GAS_LIMIT_FLOOR`: this assertion verifies revm's - // upstream hardcoded default. If upstream ever drifts from our floor, this - // test should fail loudly rather than be auto-aligned by our constant. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 30_000_000); - } - - #[test] - fn test_mega_evm_exposes_state_wrapper_block_hashes() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(7, B256::from([7_u8; 32])); - - let evm = MegaEvm::new(configure_context(&mut state)); - assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); - } - - #[test] - fn test_convenience_execution_methods_work() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)).with_inspector(NoOpInspector); - - let executed = evm.execute_transaction(mega_tx()).unwrap(); - assert!(executed.result.is_success()); - - #[allow(deprecated)] - let inspected = evm.inspect_transaction(mega_tx()).unwrap(); - assert!(inspected.result.is_success()); - } - - #[test] - fn test_execute_transaction_fails_with_insufficient_balance() { - let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::from(1_000_000), - data: Bytes::new(), - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.execute_transaction(tx); - assert!(result.is_err()); - } -} diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs deleted file mode 100644 index d1bc95e43..000000000 --- a/crates/mega-evm/src/evm/precompiles.rs +++ /dev/null @@ -1,758 +0,0 @@ -//! Custom precompiles for `MegaETH` EVM. -//! -//! This module provides custom precompile implementations with `MegaETH`-specific -//! gas cost overrides. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, string::String, sync::Arc}; - -use crate::{ExternalEnvTypes, MegaContext, MegaSpecId}; -use alloy_evm::{ - precompiles::{DynPrecompile, PrecompilesMap}, - Database, -}; -use delegate::delegate; -use once_cell::race::OnceBox; -use op_revm::{OpContext, OpSpecId}; -use revm::{ - context::Cfg, - context_interface::ContextTr, - handler::{EthPrecompiles, PrecompileProvider}, - interpreter::{Gas, InputsImpl, InterpreterResult}, - precompile::Precompiles, - primitives::{Address, HashMap}, -}; - -/// `MegaETH` precompile provider with custom gas cost overrides. -#[derive(Debug, Clone)] -pub struct MegaPrecompiles { - /// Inner precompile provider from op-revm. - inner: EthPrecompiles, - /// The `MegaETH` specification ID. - spec: MegaSpecId, -} - -impl MegaPrecompiles { - /// Create a new precompile provider with the given `MegaETH` spec. - #[inline] - pub fn new_with_spec(spec: MegaSpecId) -> Self { - // Get base precompiles from op-revm. An alias spec is grouped with its `behavior()` - // target so it gets exactly the target's precompiles; the grouping must agree with - // `behavior()`, pinned by `test_alias_specs_use_their_behavior_targets_precompiles`. - let inner = match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => op_revm::precompiles::isthmus(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => mini_rex(), - MegaSpecId::REX | - MegaSpecId::REX1 | - MegaSpecId::REX2 | - MegaSpecId::REX3 | - MegaSpecId::REX4 | - MegaSpecId::REX5 | - MegaSpecId::REX6 | - MegaSpecId::REX7 => rex(), - }; - - Self { inner: EthPrecompiles { precompiles: inner, spec: spec.into_eth_spec() }, spec } - } - - /// Get the precompiles for the current spec. - /// - /// This method returns precompiles with custom gas cost overrides for `MINI_REX` spec. - #[inline] - pub fn precompiles(&self) -> &'static Precompiles { - // For now, just use the inner precompiles - // Custom gas costs will be applied in the run() method - self.inner.precompiles - } -} - -/// Precompiles for the `REX` spec. -pub fn rex() -> &'static Precompiles { - static INSTANCE: OnceBox = OnceBox::new(); - INSTANCE.get_or_init(|| Box::new(mini_rex().clone())) -} - -/// Precompiles for the `MINI_REX` spec. -pub fn mini_rex() -> &'static Precompiles { - static INSTANCE: OnceBox = OnceBox::new(); - INSTANCE.get_or_init(|| { - let mut precompiles = op_revm::precompiles::isthmus().clone(); - // Use the OSAKA modexp precompile for MINI_REX - precompiles - .extend([revm::precompile::modexp::OSAKA, kzg_point_evaluation::KZG_POINT_EVALUATION]); - Box::new(precompiles) - }) -} - -/// Customized KZG point evaluation precompile module. -pub mod kzg_point_evaluation { - use revm::{ - precompile::{PrecompileError, PrecompileWithAddress}, - primitives::Address, - }; - - /// Address of the KZG point evaluation precompile (re-export of the upstream - /// constant). Local re-export so call-sites can refer to `GAS_COST` and - /// `ADDRESS` through the same module path. - pub const ADDRESS: Address = revm::precompile::kzg_point_evaluation::ADDRESS; - - /// Gas cost for the KZG point evaluation precompile. - pub const GAS_COST: u64 = 100_000; - - /// KZG point evaluation precompile. This is the modified version of the original precompile - /// with a custom gas cost. - pub const KZG_POINT_EVALUATION: PrecompileWithAddress = - PrecompileWithAddress(ADDRESS, |input, gas_limit| { - if gas_limit < GAS_COST { - return Err(PrecompileError::OutOfGas); - } - let mut output = revm::precompile::kzg_point_evaluation::run(input, gas_limit)?; - output.gas_used = GAS_COST; - Ok(output) - }); -} - -impl PrecompileProvider for MegaPrecompiles -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 - } - - delegate! { - to self.inner { - fn run( - &mut self, - context: &mut CTX, - address: &Address, - inputs: &InputsImpl, - is_static: bool, - gas_limit: u64, - ) -> Result, String>; - fn warm_addresses(&self) -> Box>; - fn contains(&self, address: &Address) -> bool; - } - } -} - -impl Default for MegaPrecompiles { - fn default() -> Self { - Self::new_with_spec(MegaSpecId::EQUIVALENCE) - } -} - -impl PrecompileProvider> - for PrecompilesMap -{ - type Output = InterpreterResult; - - #[inline] - fn set_spec(&mut self, _spec: OpSpecId) -> bool { - // The table is already correct and unchanged: MegaEvm bakes it at construction - // from MegaSpecId. Rebuilding from OpSpecId would lose Mega-specific overrides - // because all current Mega specs map to the same OpSpecId. - false - } - - #[inline] - fn run( - &mut self, - context: &mut MegaContext, - address: &Address, - inputs: &InputsImpl, - is_static: bool, - gas_limit: u64, - ) -> Result, String> { - // REX5+: cap forwarded gas at the current compute-gas remaining so a precompile - // cannot spend more compute gas than the per-frame / TX-level budget permits. - // Pre-REX5 keeps the original forwarding semantics for backward compatibility. - let is_rex5_enabled = context.spec.is_enabled(MegaSpecId::REX5); - let effective_gas_limit = if is_rex5_enabled { - let remaining = context.additional_limit.borrow().current_call_remaining_compute_gas(); - gas_limit.min(remaining) - } else { - gas_limit - }; - - let maybe_output = PrecompileProvider::>::run( - self, - context, - address, - inputs, - is_static, - effective_gas_limit, - )?; - - Ok(maybe_output.map(|mut output| { - // Normalize the returned Gas back to the caller's original `gas_limit` budget - // ONLY on `is_ok_or_revert` paths — those are the paths where the caller's - // refund logic (`EthFrame::return_result` and `Handler::last_frame_result`, - // both gated on `is_ok_or_revert()`) actually consumes `gas.remaining()`. - // - // Halt paths (`PrecompileOOG`, `PrecompileError`) skip the refund entirely: - // the parent burns the full forwarded `gas_limit` regardless of the Gas - // object's reported `remaining`. Leaving revm's vanilla `Gas::new(effective)` - // on those paths keeps the post-cap halt result semantically identical to - // an uncapped precompile OOG, matches what tracers / inspectors expect, and - // makes the "cap forced an OOG" behavior locally indistinguishable from - // "user just forwarded too little gas". - // - // The normalize preserves the precompile's `refunded()` value (today every - // standard revm precompile leaves refunded == 0, but custom precompiles - // injected via `PrecompilesMap` may set a refund, and a future EIP - // precompile could also). Memory expansion gas is not preserved because - // precompiles do not allocate from `Gas::memory` — memory expansion is - // the caller-interpreter's responsibility and is settled before the - // precompile is invoked. - if is_rex5_enabled && output.result.is_ok_or_revert() { - let spent = output.gas.spent(); - let refunded = output.gas.refunded(); - let mut normalized = Gas::new(gas_limit); - normalized.set_spent(spent); - normalized.record_refund(refunded); - output.gas = normalized; - } - // Compute-gas recording on REX5+: - // - // * Success / revert: revm called `record_cost`, so `spent()` already reflects the - // actually-consumed amount. Use it. - // * Fixed-cost precompile that reached past its wrapper gas pre-check (today: KZG with - // `limit() >= GAS_COST`): record the declared fixed cost. revm's `PrecompileError` - // halt still consumes the parent's forwarded `gas_limit` from the EVM-gas meter, so - // compute-gas here is intentionally a separate number from the EVM-gas burn. - // * All other error paths (non-KZG, or KZG with `limit() < GAS_COST` meaning the - // wrapper's pre-check itself OOG'd before verification could run): revm did not call - // `record_cost`, so `spent() == 0`. The parent still permanently loses the forwarded - // amount, so record `limit()` to match the EVM-gas burn. - if is_rex5_enabled { - let compute_gas = if output.result.is_ok_or_revert() { - output.gas.spent() - } else if address == &kzg_point_evaluation::ADDRESS && - output.gas.limit() >= kzg_point_evaluation::GAS_COST - { - // KZG with the wrapper's `gas_limit < GAS_COST` pre-check passed: upstream - // verification ran and returned a non-OOG error - // (`BlobInvalidInputLength` / `BlobMismatchedVersion` / - // `BlobVerifyKzgProofFailed`). Charge the fixed cost regardless of which - // error variant fired. Using the structural predicate - // (`limit() >= GAS_COST`) instead of an error-variant match keeps this arm - // robust against upstream KZG adding new non-OOG variants. - kzg_point_evaluation::GAS_COST - } else { - output.gas.limit() - }; - context.additional_limit.borrow_mut().record_compute_gas(compute_gas); - } else if context.spec.is_enabled(MegaSpecId::MINI_REX) { - context.additional_limit.borrow_mut().record_compute_gas(output.gas.spent()); - } - output - })) - } - - #[inline] - fn warm_addresses(&self) -> Box> { - PrecompileProvider::>::warm_addresses(self) - } - - #[inline] - fn contains(&self, address: &Address) -> bool { - PrecompileProvider::>::contains(self, address) - } -} - -/// A builder function to build dynamic precompiles for a given [`MegaSpecId`]. -/// -/// The spec passed to the builder is the behavior projection and is never an alias spec: -/// dynamic precompiles are execution semantics, so during an alias window the builder is -/// invoked with the alias's behavior target (e.g. `EQUIVALENCE` while `MINI_REX_1` is the -/// resolved spec). -pub type DynPrecompilesBuilder = - Arc HashMap + Send + Sync>; - -#[cfg(test)] -mod tests { - #[cfg(not(feature = "std"))] - use alloc as std; - use std::{rc::Rc, vec::Vec}; - - use super::{kzg_point_evaluation::GAS_COST, mini_rex, rex, MegaPrecompiles}; - use crate::{ - test_utils::MemoryDatabase, AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaSpecId, - }; - use alloy_evm::precompiles::PrecompilesMap; - use alloy_primitives::Bytes; - use core::cell::RefCell; - use revm::{ - handler::PrecompileProvider, - interpreter::{InputsImpl, InstructionResult}, - }; - use sha2::{Digest, Sha256}; - - /// Every alias spec must get exactly its `behavior()` target's precompile set — the - /// match in `new_with_spec` states the alias→target mapping a second time, and this - /// test is the reconciliation between the two. The sets are `&'static`, so pointer - /// identity is the exact form of "same set". - #[test] - fn test_alias_specs_use_their_behavior_targets_precompiles() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - let alias = MegaPrecompiles::new_with_spec(*spec); - let target = MegaPrecompiles::new_with_spec(spec.behavior()); - assert!( - core::ptr::eq(alias.precompiles(), target.precompiles()), - "{spec:?} precompiles diverge from its behavior target {:?}", - spec.behavior(), - ); - } - } - - /// Generate valid KZG Point Evaluation test data from EIP-4844 test vectors. - fn generate_kzg_test_input() -> InputsImpl { - let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); - let mut versioned_hash = Sha256::digest(&commitment).to_vec(); - versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG - let z = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000") - .unwrap(); - let y = hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9") - .unwrap(); - let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); - - let mut input = Vec::new(); - input.extend_from_slice(&versioned_hash); - input.extend_from_slice(&z); - input.extend_from_slice(&y); - input.extend_from_slice(&commitment); - input.extend_from_slice(&proof); - - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - InputsImpl { - target_address: address, - bytecode_address: Some(address), - caller_address: address, - input: revm::interpreter::CallInput::Bytes(Bytes::from(input)), - call_value: Default::default(), - } - } - - /// Mirror of `generate_kzg_test_input()` but with the last byte of the proof - /// flipped — structurally valid (192 bytes, matching versioned hash) but - /// upstream verification returns `PrecompileError::BlobVerifyKzgProofFailed`. - fn generate_invalid_proof_kzg_test_input() -> InputsImpl { - let mut inputs = generate_kzg_test_input(); - let bytes = match inputs.input { - revm::interpreter::CallInput::Bytes(b) => b, - _ => panic!("expected Bytes"), - }; - let mut buf = bytes.to_vec(); - let last = buf.len() - 1; - buf[last] ^= 0x01; - inputs.input = revm::interpreter::CallInput::Bytes(Bytes::from(buf)); - inputs - } - - fn set_spec_for_context( - precompiles_map: &mut PrecompilesMap, - _context: &MegaContext, - spec: op_revm::OpSpecId, - ) -> bool { - >>::set_spec( - precompiles_map, - spec, - ) - } - - #[test] - fn test_rex_and_mini_rex_precompiles_have_distinct_statics() { - assert!(!core::ptr::eq(rex(), mini_rex())); - } - - #[test] - fn test_kzg_precompile_sufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - assert!(result.is_ok(), "Precompile should succeed with sufficient gas"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_exact_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST); - assert!(result.is_ok(), "Precompile should succeed with exact GAS_COST"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_set_spec_preserves_mega_kzg_override() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - - let changed = - set_spec_for_context(&mut precompiles_map, &context, op_revm::OpSpecId::ISTHMUS); - assert!(!changed, "Mega precompile table must remain unchanged"); - - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_insufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 50_000); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_one_below_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST - 1); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_zero_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 0); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - /// Replaces the context's `additional_limit` with one whose `tx_compute_gas_limit` - /// is set to `limit`, so tests can exercise the REX5 compute-gas cap path with a - /// small remaining budget without having to pre-record large gas amounts. - fn set_tx_compute_gas_limit( - context: &mut MegaContext, - spec: MegaSpecId, - limit: u64, - ) { - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: limit, - ..EvmTxRuntimeLimits::from_spec(spec) - }; - context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); - } - - #[test] - fn test_kzg_precompile_rex5_compute_gas_cap_succeeds() { - // REX5: forward gas_limit > GAS_COST > remaining compute. Cap should engage but - // the precompile still fits within the remaining compute budget, so it succeeds. - // Caller-visible Gas must be normalized back to the original gas_limit. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST + 1_000); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - // Spent reflects the precompile's actual cost. - assert_eq!(output.gas.spent(), GAS_COST); - // Limit was normalized back to the caller's forwarded gas so the caller sees the - // correct refund (forwarded_gas - GAS_COST) instead of (effective_gas_limit - GAS_COST). - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - // The compute-gas tracker records the actual spent. - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, GAS_COST,); - } - - #[test] - fn test_kzg_precompile_rex5_compute_gas_cap_oogs() { - // Cap forces PrecompileOOG. Compute is charged `output.gas.limit()` - // (= remaining budget under the cap), exactly exhausting the meter. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - let compute_gas_limit = GAS_COST - 1; - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, compute_gas_limit); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 1_000_000); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::PrecompileOOG)); - assert_eq!(output.gas.spent(), 0); - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, compute_gas_limit); - } - - #[test] - fn test_kzg_precompile_rex5_no_cap_when_remaining_sufficient() { - // REX5: when remaining compute already exceeds the forwarded gas_limit, the cap - // is a no-op and the path behaves identically to pre-REX5. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 200_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - } - - #[test] - fn test_kzg_precompile_rex5_cap_at_exact_gas_cost() { - // REX5 boundary: remaining compute equals exactly GAS_COST. The precompile must - // succeed (cost == effective_gas_limit), spending GAS_COST, with normalization - // yielding remaining = gas_limit - GAS_COST. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, GAS_COST); - } - - /// REX5 boundary mirror of `test_kzg_precompile_rex5_cap_at_exact_gas_cost`, - /// but with an invalid-proof input so upstream returns - /// `BlobVerifyKzgProofFailed`. `tx_compute_gas_limit == GAS_COST` forces the - /// outer cap to `effective_gas_limit == GAS_COST`, so the wrapper's - /// `gas_limit < GAS_COST` pre-check passes by exactly one, upstream KZG runs - /// verification, fails on the flipped proof, and revm constructs the failure - /// `Gas` with `Gas::new(effective_gas_limit)` — leaving `output.gas.limit() == - /// GAS_COST` because halt paths skip the success-side normalization to the - /// caller's original `gas_limit`. Recorded compute-gas must equal `GAS_COST`. - /// - /// Lives in the inline unit-test module rather than - /// `tests/rex5/precompile_compute_gas.rs` because the integration helper - /// cannot reliably hit `remaining == GAS_COST` at the precompile call site: - /// opcode-level compute-gas consumed by a wrapper contract's MSTORE / PUSH / - /// CALL sequence shifts the actual `remaining` below `tx_compute_gas_limit` - /// by a brittle amount. Direct `precompiles_map.run()` bypasses that - /// pre-work and gives an exact boundary. - #[test] - fn test_kzg_precompile_rex5_cap_at_exact_gas_cost_fail() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_invalid_proof_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - // Upstream rejects the invalid proof with `BlobVerifyKzgProofFailed` → - // `InstructionResult::PrecompileError` (NOT `PrecompileOOG`). - assert!( - matches!(output.result, InstructionResult::PrecompileError), - "expected PrecompileError on invalid-proof at the cap boundary; got {:?}", - output.result - ); - // Halt paths skip the success-side normalization, so output.gas keeps revm's - // vanilla `Gas::new(effective_gas_limit)`. effective_gas_limit was capped to - // exactly GAS_COST, so limit() == GAS_COST. spent() is 0 because revm did not - // call record_cost on the error path. - assert_eq!(output.gas.limit(), GAS_COST); - assert_eq!(output.gas.spent(), 0); - // Joint invariant pinned here: result variant (PrecompileError) + limit value - // (GAS_COST) + recorded compute-gas (GAS_COST) at the exact boundary where the - // fixed-cost arm's `limit() >= GAS_COST` predicate transitions. - assert_eq!( - context.additional_limit.borrow().get_usage().compute_gas, - GAS_COST, - "at the exact-cap boundary on a verification failure, the recorded \ - compute-gas must equal GAS_COST" - ); - } - - /// End-to-end verification that the REX5+ `Gas` normalization on `PrecompileOOG` does NOT - /// affect caller gas accounting. - /// - /// Context: the REX5+ precompile wrapper re-wraps the returned `Gas` to use the - /// caller's original `gas_limit` on success and revert paths so the caller-side - /// `erase_cost(remaining)` refund accounts for the full forwarded budget minus - /// actual spent. The OOG path leaves revm's vanilla `Gas::new(effective_gas_limit)` - /// in place — `PrecompileOOG` is a halt (`return_error!`, not `return_revert!`), - /// so neither `EthFrame::return_result` (parent CALL) nor `Handler::last_frame_result` - /// (top-level TX) calls `erase_cost` for it. The caller is meant to burn the - /// forwarded gas regardless of the Gas object's reported remaining. - /// - /// This test pins that behavior: a top-level TX directly invoking KZG with the cap - /// forcing OOG must consume the full `tx.gas_limit`, NOT refund the user. - #[test] - fn test_kzg_precompile_rex5_oog_via_cap_burns_full_tx_gas() { - use crate::{MegaEvm, MegaTransaction}; - use alloy_primitives::{address, Bytes as BytesT, U256}; - use revm::context::{tx::TxEnvBuilder, BlockEnv, ContextSetters}; - - let caller = address!("0000000000000000000000000000000000600000"); - - let mut db = MemoryDatabase::default().account_balance(caller, U256::from(10_000_000)); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - // Tight TX-level compute-gas budget that's smaller than KZG's GAS_COST. - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: GAS_COST - 1, - ..EvmTxRuntimeLimits::from_spec(MegaSpecId::REX5) - }; - context.additional_limit = - Rc::new(RefCell::new(AdditionalLimit::new(MegaSpecId::REX5, tx_limits))); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - // Build a valid KZG-input calldata so the precompile would proceed up to its - // gas-cost check (which is the OOG trigger under the cap). - let valid_kzg_input = match generate_kzg_test_input().input { - revm::interpreter::CallInput::Bytes(b) => b, - _ => panic!("expected Bytes"), - }; - - let tx_gas_limit = 1_000_000u64; - let tx = TxEnvBuilder::default() - .caller(caller) - .call(revm::precompile::kzg_point_evaluation::ADDRESS) - .gas_limit(tx_gas_limit) - .gas_price(1) - .data(valid_kzg_input) - .build_fill(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(BytesT::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - - // The TX must halt (precompile OOG'd because cap forced effective_gas_limit < GAS_COST). - assert!(!result.result.is_success(), "tx must halt: cap forced precompile OOG",); - // Critical invariant: the receipt's gas_used reports the FULL tx.gas_limit. If - // the Gas-normalization breaks refund accounting on the OOG path, gas_used would - // be far smaller (sender refunded most of tx.gas_limit despite the halt). - assert_eq!( - result.result.gas_used(), - tx_gas_limit, - "OOG'd precompile call must burn the full tx.gas_limit (normalization must NOT \ - leak a refund through the halt path)", - ); - } - - #[test] - fn test_kzg_precompile_pre_rex5_does_not_cap() { - // Pre-REX5 (REX4): the cap is intentionally disabled for backward compatibility. - // Even with a very small tx_compute_gas_limit, the precompile is invoked with - // the original forwarded gas; compute-gas overshoot is detected only after the - // fact (the existing behavior). - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX4, GAS_COST - 1); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX4).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - // Precompile runs with full forwarded gas and succeeds, spending GAS_COST. - // The post-hoc record_compute_gas call pushes the tracker over the limit, but - // that detection happens via check_limit elsewhere, not in this path. - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - } -} diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs deleted file mode 100644 index bbe6cf129..000000000 --- a/crates/mega-evm/src/evm/result.rs +++ /dev/null @@ -1,195 +0,0 @@ -use alloy_evm::block::StateChangeSource; -pub use alloy_evm::InvalidTxError; -use alloy_primitives::Address; -pub use op_revm::{OpHaltReason, OpTransactionError}; -use revm::{context::result::ExecutionResult, state::EvmState}; -pub use revm::{ - context::result::{EVMError, InvalidTransaction}, - context_interface::{ - result::HaltReason as EthHaltReason, transaction::TransactionError as TransactionErrorTr, - }, -}; -use serde::{Deserialize, Serialize}; - -use crate::VolatileDataAccess; - -/// The execution outcome of a transaction in `MegaETH`. -/// -/// This struct contains additional information about the transaction execution on top of the -/// standard EVM's execution result and state. -#[derive(Debug, Clone)] -pub struct MegaTransactionOutcome { - /// The transaction execution result. - pub result: ExecutionResult, - /// The post-execution evm state. - pub state: EvmState, - /// The data size usage in bytes. - pub data_size: u64, - /// The number of KV updates. - pub kv_updates: u64, - /// The compute gas used. - pub compute_gas_used: u64, - /// The state growth used. - pub state_growth_used: u64, -} - -/// The execution outcome of system call in `MegaETH`. -#[derive(Debug, Clone)] -pub struct MegaSystemCallOutcome { - /// Source of the state change - pub source: StateChangeSource, - /// The post-call evm state - pub state: EvmState, -} - -/// `MegaETH` transaction validation error type. -/// -/// TODO: This is currently a type alias due to constraints from `op_revm::OpHandler`. -/// `OpHandler` requires `ERROR: From`, but we cannot satisfy this -/// for `EVMError` due to Rust's orphan rules. -/// -/// To add custom transaction error variants, we need to: -/// 1. Stop using `OpHandler` directly -/// 2. Implement all handler methods manually without delegating to `OpHandler` -/// 3. Then we can use a custom enum like: ``` pub enum MegaTransactionError { -/// Base(OpTransactionError), CustomVariant, } ``` -pub type MegaTransactionError = OpTransactionError; - -/// `MegaETH` halt reason type, with additional MegaETH-specific halt reasons. -/// -/// It is a wrapper around `OpHaltReason`, which internally wraps `EthHaltReason`. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum MegaHaltReason { - /// Base [`OpHaltReason`] - Base(OpHaltReason), - /// Data limit exceeded - DataLimitExceeded { - /// The configured data limit - limit: u64, - /// The actual data generated - actual: u64, - }, - /// KV update limit exceeded - KVUpdateLimitExceeded { - /// The configured KV update limit - limit: u64, - /// The actual KV update count - actual: u64, - }, - /// Compute gas limit exceeded - ComputeGasLimitExceeded { - /// The configured compute gas limit - limit: u64, - /// The actual compute gas usage - actual: u64, - }, - /// State growth limit exceeded - StateGrowthLimitExceeded { - /// The configured state growth limit - limit: u64, - /// The actual state growth usage - actual: u64, - }, - /// System transaction's callee is not in the whitelist - SystemTxInvalidCallee { - /// address called - callee: Address, - }, - /// Out of gas due to volatile data access limit enforcement. - /// The transaction exceeded the compute gas limit imposed after accessing volatile data - /// (block environment, beneficiary, or oracle contract). - VolatileDataAccessOutOfGas { - /// Bitflags indicating which volatile data was accessed. - /// Can check specific accesses using `has_block_env_access()`, - /// `has_beneficiary_balance_access()`, `has_oracle_access()` - access_type: VolatileDataAccess, - /// The effective detained compute gas limit that was exceeded. - /// In REX4+ this is `usage_at_access + cap` (relative); pre-REX4 it equals the raw cap - /// (absolute). Always satisfies `actual > limit`. - limit: u64, - /// The actual compute gas usage - actual: u64, - }, -} - -impl From for MegaHaltReason { - fn from(value: EthHaltReason) -> Self { - Self::Base(OpHaltReason::Base(value)) - } -} - -impl From for MegaHaltReason { - fn from(value: OpHaltReason) -> Self { - Self::Base(value) - } -} - -impl TryFrom for EthHaltReason { - type Error = MegaHaltReason; - - fn try_from(value: MegaHaltReason) -> Result { - match value { - MegaHaltReason::Base(reason) => Ok(reason.try_into()?), - MegaHaltReason::DataLimitExceeded { .. } | - MegaHaltReason::KVUpdateLimitExceeded { .. } | - MegaHaltReason::ComputeGasLimitExceeded { .. } | - MegaHaltReason::StateGrowthLimitExceeded { .. } | - MegaHaltReason::SystemTxInvalidCallee { .. } | - MegaHaltReason::VolatileDataAccessOutOfGas { .. } => Err(value), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use revm::context::result::OutOfGasError; - - #[test] - fn test_base_halt_reasons_convert_roundtrip() { - let eth_reason = EthHaltReason::OutOfGas(OutOfGasError::Basic); - let mega_from_eth = MegaHaltReason::from(eth_reason); - let mega_from_op = MegaHaltReason::from(OpHaltReason::Base(eth_reason)); - - assert_eq!(mega_from_eth, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(mega_from_op, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(EthHaltReason::try_from(mega_from_eth).unwrap(), eth_reason); - assert_eq!(EthHaltReason::try_from(mega_from_op).unwrap(), eth_reason); - } - - #[test] - fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { - let reason = MegaHaltReason::VolatileDataAccessOutOfGas { - access_type: VolatileDataAccess::ORACLE, - limit: 100, - actual: 101, - }; - - assert_eq!(EthHaltReason::try_from(reason.clone()), Err(reason)); - } - - #[test] - fn test_op_specific_halt_reason_does_not_convert_to_eth() { - let op_reason = OpHaltReason::FailedDeposit; - let mega = MegaHaltReason::from(op_reason.clone()); - assert_eq!(mega, MegaHaltReason::Base(op_reason)); - assert!(EthHaltReason::try_from(mega).is_err()); - } - - #[test] - fn test_all_mega_specific_variants_fail_eth_conversion() { - let variants: Vec = vec![ - MegaHaltReason::DataLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::KVUpdateLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::ComputeGasLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::StateGrowthLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::SystemTxInvalidCallee { callee: Address::ZERO }, - ]; - for variant in variants { - assert!( - EthHaltReason::try_from(variant).is_err(), - "mega-specific variant should not convert to EthHaltReason" - ); - } - } -} diff --git a/crates/mega-evm/src/evm/spec.rs b/crates/mega-evm/src/evm/spec.rs deleted file mode 100644 index 925804225..000000000 --- a/crates/mega-evm/src/evm/spec.rs +++ /dev/null @@ -1,506 +0,0 @@ -//! Definitions of the `MegaETH` EVM versions (`SpecId`). - -use core::{ - fmt::{self, Display}, - str::FromStr, -}; -pub use op_revm::OpSpecId; -pub use revm::primitives::hardfork::{SpecId as EthSpecId, UnknownHardfork}; -use serde::{Deserialize, Serialize}; - -/// `MegaETH` spec id, defining different versions of the `MegaETH` EVM. -/// -/// Each `MegaETH` EVM version corresponds to a version of the Optimism EVM, which means the -/// behavior of the `MegaETH` EVM inherits and is customized on top of that version of the Optimism -/// EVM. Similarly, each Optimism EVM version also corresponds to a Ethereum EVM version. The -/// corresponding relations are as follows: -/// - [`SpecId::EQUIVALENCE`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX_1`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX_2`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX1`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX2`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX3`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX4`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX5`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX6`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX7`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// -/// The `Default` variant tracks the latest spec, which may still be unstable; -/// callers that need a stable spec must select it explicitly instead of -/// relying on `Default::default()`. -#[repr(u8)] -#[derive( - Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize, -)] -#[allow(non_camel_case_types, clippy::upper_case_acronyms, missing_docs)] -#[non_exhaustive] -pub enum MegaSpecId { - /// The EVM version when no `MegaETH` harfork is enabled. The behavior of the EVM - /// should be equivalent to the [`OpSpecId::ISTHMUS`] of the Optimism EVM. - EQUIVALENCE, - /// The EVM version for the *Mini-Rex* hardfork of `MegaETH`. - MINI_REX, - /// Alias spec for the `MiniRex1` hardfork: scheduled as its own rung, executes - /// [`MegaSpecId::EQUIVALENCE`] behavior (`behavior()` projects there). - MINI_REX_1, - /// Alias spec for the `MiniRex2` hardfork: scheduled as its own rung, executes - /// [`MegaSpecId::MINI_REX`] behavior (`behavior()` projects there). - MINI_REX_2, - /// The EVM version for the *Rex* hardfork of `MegaETH`. - REX, - /// The EVM version for the *Rex1* hardfork of `MegaETH`. - REX1, - /// The EVM version for the *Rex2* hardfork of `MegaETH`. - REX2, - /// The EVM version for the *Rex3* hardfork of `MegaETH`. - REX3, - /// The EVM version for the *Rex4* hardfork of `MegaETH`. - REX4, - /// The EVM version for the *Rex5* hardfork of `MegaETH`. - REX5, - /// The EVM version for the *Rex6* hardfork of `MegaETH`. - REX6, - /// The EVM version for the *Rex7* hardfork of `MegaETH`. - #[default] - REX7, -} - -/// String identifiers for `MegaETH` EVM versions. -#[allow(missing_docs)] -pub mod name { - /// The string identifier for the *Equivalence* version of the `MegaETH` EVM. - pub const EQUIVALENCE: &str = "Equivalence"; - /// The string identifier for the *Mini-Rex* version of the `MegaETH` EVM. - pub const MINI_REX: &str = "MiniRex"; - /// The string identifier for the `MiniRex1` alias spec. - pub const MINI_REX_1: &str = "MiniRex1"; - /// The string identifier for the `MiniRex2` alias spec. - pub const MINI_REX_2: &str = "MiniRex2"; - /// The string identifier for the *Rex* version of the `MegaETH` EVM. - pub const REX: &str = "Rex"; - /// The string identifier for the *Rex1* version of the `MegaETH` EVM. - pub const REX1: &str = "Rex1"; - /// The string identifier for the *Rex2* version of the `MegaETH` EVM. - pub const REX2: &str = "Rex2"; - /// The string identifier for the *Rex3* version of the `MegaETH` EVM. - pub const REX3: &str = "Rex3"; - /// The string identifier for the *Rex4* version of the `MegaETH` EVM. - pub const REX4: &str = "Rex4"; - /// The string identifier for the *Rex5* version of the `MegaETH` EVM. - pub const REX5: &str = "Rex5"; - /// The string identifier for the *Rex6* version of the `MegaETH` EVM. - pub const REX6: &str = "Rex6"; - /// The string identifier for the *Rex7* version of the `MegaETH` EVM. - pub const REX7: &str = "Rex7"; -} - -impl MegaSpecId { - /// Every spec in the progression, oldest first. - /// - /// The single point to enumerate specs from: sweeps and tables that list specs by hand - /// drift silently when a variant is added. Completeness is enforced in two steps — - /// introducing a variant is a compile error in `ladder_index`'s exhaustive match (and the - /// `is_ladder_prefix` const assertion ties each entry here to its ladder position), and - /// `test_all_ends_at_the_latest_spec` fails until the new spec is appended here. - pub const ALL: &'static [Self] = &[ - Self::EQUIVALENCE, - Self::MINI_REX, - Self::MINI_REX_1, - Self::MINI_REX_2, - Self::REX, - Self::REX1, - Self::REX2, - Self::REX3, - Self::REX4, - Self::REX5, - Self::REX6, - Self::REX7, - ]; - - /// Converts the [`SpecId`] into its corresponding [`EthSpecId`]. - pub const fn into_eth_spec(self) -> EthSpecId { - self.into_op_spec().into_eth_spec() - } - - /// Converts the [`SpecId`] into its corresponding [`OpSpecId`]. - pub const fn into_op_spec(self) -> OpSpecId { - match self { - Self::MINI_REX | - Self::MINI_REX_1 | - Self::MINI_REX_2 | - Self::EQUIVALENCE | - Self::REX | - Self::REX1 | - Self::REX2 | - Self::REX3 | - Self::REX4 | - Self::REX5 | - Self::REX6 | - Self::REX7 => OpSpecId::ISTHMUS, - } - } - - /// The behavior this spec executes: alias specs project to the spec whose behavior they - /// reuse; every other spec is its own behavior. - /// - /// The projection must stay flat — every target is a concrete spec at or below the - /// projecting rung, never another alias — which the `is_flat_projection` const assertion - /// below pins at compile time. - pub const fn behavior(self) -> Self { - match self { - Self::MINI_REX_1 => Self::EQUIVALENCE, - Self::MINI_REX_2 => Self::MINI_REX, - other => other, - } - } - - /// Whether this spec is an alias — a rung whose behavior belongs to another spec. - /// Derived from [`behavior`](Self::behavior), so a future alias needs only its projection - /// arm; there is no second list to extend. - pub const fn is_alias(self) -> bool { - self.behavior() as u8 != self as u8 - } - - /// Returns `true` if `other`'s BEHAVIOR is enabled under `self` — the gate for execution - /// semantics. Both sides project through [`behavior`](Self::behavior) first, so an alias - /// spec enables exactly what its behavior target enables (`MINI_REX_1` does NOT enable - /// `MINI_REX`). - pub const fn is_enabled(self, other: Self) -> bool { - other.behavior() as u8 <= self.behavior() as u8 - } - - /// Returns `true` if the ladder has REACHED `other`'s rung — the gate for one-way chain - /// setup. Position comparison, no behavior projection: during an alias window the ladder - /// stands above the specs it rolled back from, so their setup stays in place. - pub const fn reaches(self, other: Self) -> bool { - other as u8 <= self as u8 - } -} - -/// Position on the spec progression, 0 = `EQUIVALENCE`. -/// -/// Not an API — the `u8` discriminant already carries the ordinal. This exists to be an -/// exhaustive match: introducing a spec fails compilation here until the variant is placed, -/// and the const assertion below fails until [`MegaSpecId::ALL`] lists it at that position. -const fn ladder_index(spec: MegaSpecId) -> usize { - match spec { - MegaSpecId::EQUIVALENCE => 0, - MegaSpecId::MINI_REX => 1, - MegaSpecId::MINI_REX_1 => 2, - MegaSpecId::MINI_REX_2 => 3, - MegaSpecId::REX => 4, - MegaSpecId::REX1 => 5, - MegaSpecId::REX2 => 6, - MegaSpecId::REX3 => 7, - MegaSpecId::REX4 => 8, - MegaSpecId::REX5 => 9, - MegaSpecId::REX6 => 10, - MegaSpecId::REX7 => 11, - } -} - -/// Whether `list` is a prefix of the spec ladder: entry `i` is exactly the spec at ladder -/// position `i` — in order, without gaps, starting from `EQUIVALENCE`. -/// -/// Shared by the compile-time assertion on [`MegaSpecId::ALL`] below and by the test that -/// feeds it malformed lists, so the checker itself is exercised — a weakened guard here would -/// otherwise pass silently, since the real `ALL` always satisfies the property it checks. -const fn is_ladder_prefix(list: &[MegaSpecId]) -> bool { - let mut i = 0; - while i < list.len() { - if ladder_index(list[i]) != i { - return false; - } - i += 1; - } - true -} - -const _: () = assert!( - is_ladder_prefix(MegaSpecId::ALL), - "MegaSpecId::ALL must list every spec in ladder order, without gaps" -); - -/// The target `spec` projects to under a behavior `table` of `(spec, target)` pairs; a spec -/// absent from the table is its own target, mirroring [`MegaSpecId::behavior`]'s identity arm. -const fn project(table: &[(MegaSpecId, MegaSpecId)], spec: MegaSpecId) -> MegaSpecId { - let mut i = 0; - while i < table.len() { - if table[i].0 as u8 == spec as u8 { - return table[i].1; - } - i += 1; - } - spec -} - -/// Whether a behavior table is flat: every target is a fixed point of the table and sits at -/// or below the spec projecting onto it. -/// -/// The fixed-point check rejects chains and cycles in one property — a chain `A→B→C` fails -/// because `B`'s own target is `C`, a cycle `A→B→A` because `B` projects back to `A` — either -/// way [`MegaSpecId::behavior`]'s single-step lookup would silently resolve half-way. The -/// downward check rejects an alias projecting upward, which would execute semantics whose -/// one-way setup (gated by [`MegaSpecId::reaches`], a position below the target's rung) never -/// ran. -/// -/// The table is passed as data so the checker can be fed malformed shapes: the compile-time -/// assertion below checks the real projection, and the test exercises the rejection cases the -/// real table can never produce — a weakened guard here would otherwise pass silently. -const fn is_flat_projection(table: &[(MegaSpecId, MegaSpecId)]) -> bool { - let mut i = 0; - while i < table.len() { - let (spec, target) = table[i]; - if project(table, target) as u8 != target as u8 { - return false; - } - if target as u8 > spec as u8 { - return false; - } - // A key that appears twice would make `project` ambiguous (first match wins); - // reject the table outright rather than trusting the lookup order. - let mut j = 0; - while j < i { - if table[j].0 as u8 == spec as u8 { - return false; - } - j += 1; - } - i += 1; - } - true -} - -/// [`MegaSpecId::behavior`] as data: every spec in [`MegaSpecId::ALL`] paired with its -/// projection target. -const fn behavior_table() -> [(MegaSpecId, MegaSpecId); MegaSpecId::ALL.len()] { - let mut table = [(MegaSpecId::EQUIVALENCE, MegaSpecId::EQUIVALENCE); MegaSpecId::ALL.len()]; - let mut i = 0; - while i < table.len() { - table[i] = (MegaSpecId::ALL[i], MegaSpecId::ALL[i].behavior()); - i += 1; - } - table -} - -const _: () = { - let table = behavior_table(); - assert!( - is_flat_projection(&table), - "behavior() targets must be concrete specs at or below the projecting rung" - ); -}; - -impl From for &'static str { - /// Converts the [`SpecId`] into its corresponding string identifier. - fn from(spec_id: MegaSpecId) -> Self { - match spec_id { - MegaSpecId::EQUIVALENCE => name::EQUIVALENCE, - MegaSpecId::MINI_REX => name::MINI_REX, - MegaSpecId::MINI_REX_1 => name::MINI_REX_1, - MegaSpecId::MINI_REX_2 => name::MINI_REX_2, - MegaSpecId::REX => name::REX, - MegaSpecId::REX1 => name::REX1, - MegaSpecId::REX2 => name::REX2, - MegaSpecId::REX3 => name::REX3, - MegaSpecId::REX4 => name::REX4, - MegaSpecId::REX5 => name::REX5, - MegaSpecId::REX6 => name::REX6, - MegaSpecId::REX7 => name::REX7, - } - } -} - -impl FromStr for MegaSpecId { - type Err = UnknownHardfork; - - /// Converts the string identifier into its corresponding [`SpecId`]. - fn from_str(s: &str) -> Result { - match s { - name::EQUIVALENCE => Ok(Self::EQUIVALENCE), - name::MINI_REX => Ok(Self::MINI_REX), - name::MINI_REX_1 => Ok(Self::MINI_REX_1), - name::MINI_REX_2 => Ok(Self::MINI_REX_2), - name::REX => Ok(Self::REX), - name::REX1 => Ok(Self::REX1), - name::REX2 => Ok(Self::REX2), - name::REX3 => Ok(Self::REX3), - name::REX4 => Ok(Self::REX4), - name::REX5 => Ok(Self::REX5), - name::REX6 => Ok(Self::REX6), - name::REX7 => Ok(Self::REX7), - _ => Err(UnknownHardfork), - } - } -} - -impl From for revm::primitives::hardfork::SpecId { - /// Converts the [`SpecId`] into its corresponding [`EthSpecId`]. - fn from(spec_id: MegaSpecId) -> Self { - spec_id.into_eth_spec() - } -} - -impl From for OpSpecId { - /// Converts the [`SpecId`] into its corresponding [`OpSpecId`]. - fn from(spec_id: MegaSpecId) -> Self { - spec_id.into_op_spec() - } -} - -impl Display for MegaSpecId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s: &'static str = (*self).into(); - write!(f, "{}", s) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The one golden spec table: every spec with its string identifier and its pinned ladder - /// position. The spec column must be exactly [`MegaSpecId::ALL`] (asserted in the - /// round-trip test); the name and position columns stay hand-written — deriving either - /// from the code under test would make its check vacuous. - const ALL_SPECS: [(MegaSpecId, &str, u8); 12] = [ - (MegaSpecId::EQUIVALENCE, name::EQUIVALENCE, 0), - (MegaSpecId::MINI_REX, name::MINI_REX, 1), - (MegaSpecId::MINI_REX_1, name::MINI_REX_1, 2), - (MegaSpecId::MINI_REX_2, name::MINI_REX_2, 3), - (MegaSpecId::REX, name::REX, 4), - (MegaSpecId::REX1, name::REX1, 5), - (MegaSpecId::REX2, name::REX2, 6), - (MegaSpecId::REX3, name::REX3, 7), - (MegaSpecId::REX4, name::REX4, 8), - (MegaSpecId::REX5, name::REX5, 9), - (MegaSpecId::REX6, name::REX6, 10), - (MegaSpecId::REX7, name::REX7, 11), - ]; - - #[test] - fn test_spec_names_roundtrip_and_display() { - // The spec column must be exactly `MegaSpecId::ALL`, so a newly introduced spec cannot - // be forgotten here. - assert!(ALL_SPECS.iter().map(|(spec, _, _)| *spec).eq(MegaSpecId::ALL.iter().copied())); - - for (spec, expected_name, _) in ALL_SPECS { - assert_eq!(<&'static str>::from(spec), expected_name); - assert_eq!(MegaSpecId::from_str(expected_name).unwrap(), spec); - assert_eq!(spec.to_string(), expected_name); - } - - assert_eq!(MegaSpecId::default(), MegaSpecId::REX7); - assert_eq!(MegaSpecId::from_str("unknown"), Err(UnknownHardfork)); - } - - /// The completeness anchor for [`MegaSpecId::ALL`]: `Default` tracks the latest spec (its - /// own assertion above pins which), so a variant added without extending `ALL` fails here - /// once the default advances. The const assertion on `ladder_index` covers order and gaps; - /// this covers the tail. - #[test] - fn test_all_ends_at_the_latest_spec() { - assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); - } - - #[test] - fn test_ladder_positions_are_pinned() { - // A downstream variant-index codec (bincode-style) of `MegaSpecId` — or of a - // container holding it — silently misreads old data if discriminants renumber. - // Pinning every position turns any future renumbering into a loud diff on the - // golden table, where the review attention is. - assert_eq!(ALL_SPECS.len(), MegaSpecId::ALL.len()); - for (spec, _, position) in ALL_SPECS { - assert_eq!(spec as u8, position, "{spec:?} moved on the ladder"); - } - } - - #[test] - fn test_is_ladder_prefix_rejects_malformed_lists() { - assert!(is_ladder_prefix(MegaSpecId::ALL)); - assert!(is_ladder_prefix(&[]), "the empty prefix is a ladder prefix"); - assert!(is_ladder_prefix(&[MegaSpecId::EQUIVALENCE, MegaSpecId::MINI_REX])); - - assert!( - !is_ladder_prefix(&[MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]), - "reordered entries must be rejected" - ); - assert!( - !is_ladder_prefix(&[MegaSpecId::MINI_REX]), - "a list not starting at the ladder base must be rejected" - ); - assert!( - !is_ladder_prefix(&[MegaSpecId::EQUIVALENCE, MegaSpecId::REX]), - "a skipped rung must be rejected" - ); - } - - #[test] - fn test_is_flat_projection_rejects_malformed_tables() { - assert!(is_flat_projection(&behavior_table())); - assert!(is_flat_projection(&[]), "the empty table is flat"); - assert!( - is_flat_projection(&[(MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE)]), - "a target absent from the table projects to itself" - ); - - assert!( - !is_flat_projection(&[ - (MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE), - (MegaSpecId::MINI_REX_2, MegaSpecId::MINI_REX_1), - ]), - "a chain — an alias targeting another alias — must be rejected" - ); - assert!( - !is_flat_projection(&[ - (MegaSpecId::EQUIVALENCE, MegaSpecId::MINI_REX), - (MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE), - ]), - "a projection cycle must be rejected" - ); - assert!( - !is_flat_projection(&[(MegaSpecId::MINI_REX, MegaSpecId::REX)]), - "an alias projecting to a higher rung must be rejected" - ); - assert!( - !is_flat_projection(&[ - (MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE), - (MegaSpecId::MINI_REX_1, MegaSpecId::MINI_REX), - ]), - "a duplicate key must be rejected — it would make the projection ambiguous" - ); - } - - #[test] - fn test_all_specs_map_to_isthmus_and_prague() { - for spec in MegaSpecId::ALL.iter().copied() { - assert_eq!(spec.into_op_spec(), OpSpecId::ISTHMUS); - assert_eq!(spec.into_eth_spec(), EthSpecId::PRAGUE); - assert_eq!(revm::primitives::hardfork::SpecId::from(spec), EthSpecId::PRAGUE); - assert_eq!(OpSpecId::from(spec), OpSpecId::ISTHMUS); - } - } - - #[test] - fn test_spec_order_is_backward_compatible() { - assert!(MegaSpecId::REX4.is_enabled(MegaSpecId::REX3)); - assert!(MegaSpecId::REX4.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::MINI_REX.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX2.is_enabled(MegaSpecId::REX1)); - assert!(MegaSpecId::REX5.is_enabled(MegaSpecId::REX4)); - assert!(MegaSpecId::REX5.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX6.is_enabled(MegaSpecId::REX5)); - assert!(MegaSpecId::REX6.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX7.is_enabled(MegaSpecId::REX6)); - assert!(MegaSpecId::REX7.is_enabled(MegaSpecId::EQUIVALENCE)); - - assert!(!MegaSpecId::EQUIVALENCE.is_enabled(MegaSpecId::MINI_REX)); - assert!(!MegaSpecId::REX1.is_enabled(MegaSpecId::REX2)); - assert!(!MegaSpecId::REX3.is_enabled(MegaSpecId::REX4)); - assert!(!MegaSpecId::REX4.is_enabled(MegaSpecId::REX5)); - assert!(!MegaSpecId::REX5.is_enabled(MegaSpecId::REX6)); - assert!(!MegaSpecId::REX6.is_enabled(MegaSpecId::REX7)); - } -} diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs deleted file mode 100644 index 4c5681c59..000000000 --- a/crates/mega-evm/src/evm/state.rs +++ /dev/null @@ -1,396 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::collections::BTreeMap; - -use alloy_primitives::{map::hash_map::Entry, B256}; -use revm::state::{Account, AccountStatus, EvmState, EvmStorage}; - -use auto_impl::auto_impl; -use revm::{database::State, Database}; - -/// A helper trait to get the block hashes used during transaction execution. -#[auto_impl(&, &mut, Box, Rc, Arc)] -pub trait BlockHashes { - /// Get the block hashes used during transaction execution. - fn get_accessed_block_hashes(&self) -> BTreeMap; -} - -impl BlockHashes for State { - fn get_accessed_block_hashes(&self) -> BTreeMap { - self.block_hashes.clone() - } -} - -/// Merges the other [`EvmState`] into the current one with account status also merged. -/// See more details in the [`merge_evm_state_optional_status`] function. -pub fn merge_evm_state(this: &mut EvmState, other: &EvmState) { - merge_evm_state_optional_status(this, other, true); -} - -/// Merges the other [`EvmState`] into the current one. The account status may or may not be merged -/// according to the `merge_status` parameter. -/// -/// # Assumption -/// -/// - The `other` `EvmState` is the result of the execution of a single transaction, or the merged -/// result of another [`merge_evm_state`] call. It must not be a partial `EvmState` in the middle -/// of a transaction execution. -/// - This function assumes that Cancun hardfork (EIP-6780) is activated. -/// - This function only works correctly post Cancun. -/// -/// # Algorithm -/// -/// Post Cancun (with EIP-6780), the account status is `SelfDestructed` only when the account is -/// created in the same transaction, i.e., if `SelfDestructed` flag is set, it must be "created -> -/// selfdestructed" in the same transaction and `Created` flag is also set. When merging `EvmState`s -/// (base `EvmState` <- new `EvmState`), we are doing this for each account: -/// - If the `SelfDestructed` (and `Created`) flag is set in the account status of the new -/// `EvmState`, override the account with an empty, touched account. -/// - Otherwise, we override the corresponding account and storage slots in the base `EvmState`. -/// -/// # Coldness -/// -/// When merging the state, if an account or storage slot exists in `this`, its coldness is -/// preserved; if an account or storage slot does not exist in `this`, it is marked as cold. -/// -/// # Account Status -/// -/// Optionally: -/// - `CreatedLocal` and `SelfDestructedLocal` on the `other` `EvmState` is cleared since they only -/// matter in the execution of the same transaction, while this merging between transactions. -/// - The `Cold` flag in the `this` `EvmState` is preserved. -/// - For other flags, they are merged from `other` into `this`. -/// -/// We merge the state even if the account is not marked as `Touched`. This is because we may need -/// to know which account is read but not written to obtain `ReadSet` for witness generation. -pub fn merge_evm_state_optional_status(this: &mut EvmState, other: &EvmState, merge_status: bool) { - for (address, account) in other { - if account.is_selfdestructed() { - // if the account is selfdestructed, we assert that the account is also created and do - // nothing. - assert!( - account.is_created(), - "Account is selfdestructed but not created. EIP-6780 must be applied." - ); - // we will put an empty (equivalent to non-existent) account in the base state. - // NOTE: we want to avoid marking an account as `SelfDestructed` since this may result - // in a `BundleAccount` with `wipe_storage = true`. The underlying database in fact - // cannot process such wiping storage action. Here, we do an early interpretation of - // `SelfDestruct` by overriding the account with a default (empty) one and marking it as - // `Touched`. The rationale is: - // 1. The account is effectively selfdestructed, so its result state is equivalent to an - // empty account. - // 2. There is no need to wipe storage in the database since this account is just - // created and destructed, there must be no storage data in the database. - // 3. The account needs to be marked as `Touched` in case it pre-exists in the database - // and needs to be deleted. - let mut empty_account = Account::default().with_touched_mark(); - match this.entry(*address) { - Entry::Occupied(mut occupied_entry) => { - if occupied_entry.get().status.contains(AccountStatus::Cold) { - // if the account was cold, we need to preserve the coldness - empty_account.mark_cold(); - } - occupied_entry.insert(empty_account); - } - Entry::Vacant(vacant_entry) => { - // if the account didn't exist, we mark it as cold - vacant_entry.insert(empty_account.with_cold_mark()); - } - } - continue; - } - - // merge regardless of whether the account is touched or not - match this.entry(*address) { - Entry::Vacant(v) => { - // if the account didn't exist, we mark it as cold - let mut merged_account = account.clone().with_cold_mark(); - // all storage slots should be marked as cold - for slot in merged_account.storage.values_mut() { - slot.mark_cold(); - } - // `CreatedLocal` and `SelfDestructedLocal` are cleared since they only matter in - // the execution of the same transaction, while this merging between transactions. - merged_account.unmark_created_locally(); - merged_account.unmark_selfdestructed_locally(); - v.insert(merged_account); - } - Entry::Occupied(mut v) => { - let this_account = v.get_mut(); - merge_account_state(this_account, account, merge_status); - } - } - } -} - -/// Merges the other [`Account`] into the current one. -/// -/// # Assumption -/// -/// The other account to merge is not flagged as `SelfDestructed`. See more details in -/// the [`merge_evm_state`] function. -fn merge_account_state(this: &mut Account, other: &Account, merge_status: bool) { - this.info = other.info.clone(); - merge_evm_storage(&mut this.storage, &other.storage); - if merge_status { - merge_account_status(&mut this.status, other.status); - } -} - -/// Merges the other [`AccountStatus`] into the current one. -/// -/// # Assumption -/// -/// The other [`AccountStatus`] to merge is not flagged as `SelfDestructed`. See more details in -/// the [`merge_evm_state`] function. -fn merge_account_status(this: &mut AccountStatus, mut other: AccountStatus) { - assert!( - !other.contains(AccountStatus::SelfDestructed), - "Account is selfdestructed and should not be merged." - ); - // The coldness of `this` account should be preserved. - // Remove the flags that only matter in the execution of the same transaction, while this - // merging between transactions. - other -= AccountStatus::Cold | AccountStatus::CreatedLocal | AccountStatus::SelfDestructedLocal; - - if this.contains(AccountStatus::SelfDestructed) && other.contains(AccountStatus::Created) { - // if `this` account is selfdestructed, and `other` account is created, - // we should no longer mark `this` as selfdestructed. - *this -= AccountStatus::SelfDestructed; - } - - // Other status flags are simply merged into `this`. - *this |= other; -} - -/// Merges the other [`EvmStorage`] into the current one. -/// -/// See more details in the [`merge_evm_state`] function. -fn merge_evm_storage(this: &mut EvmStorage, other: &EvmStorage) { - for (slot, slot_value) in other { - match this.entry(*slot) { - Entry::Vacant(v) => { - let mut slot = slot_value.clone(); - // If this slot is not loaded, we mark it as cold. - slot.mark_cold(); - v.insert(slot); - } - Entry::Occupied(mut v) => { - let this_slot = v.get_mut(); - this_slot.present_value = slot_value.present_value; - // The coldness of the slot is preserved. - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Address, B256, U256}; - use revm::{ - database::{InMemoryDB, State}, - state::{AccountInfo, EvmStorageSlot}, - }; - - const TEST_ADDRESS: Address = address!("1000000000000000000000000000000000000001"); - - fn account_with_status(status: AccountStatus) -> Account { - Account { - info: AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: B256::ZERO, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status, - } - } - - #[test] - fn test_state_exposes_accessed_block_hashes() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(1, B256::ZERO); - state.block_hashes.insert(2, B256::from([2_u8; 32])); - - let hashes = state.get_accessed_block_hashes(); - assert_eq!(hashes.len(), 2); - assert_eq!(hashes.get(&1), Some(&B256::ZERO)); - assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); - } - - #[test] - fn test_merge_evm_state_replaces_created_selfdestructed_accounts_with_empty_touched_accounts() { - let mut this = EvmState::default(); - this.insert(TEST_ADDRESS, Account::default().with_cold_mark()); - - let mut other_account = account_with_status(AccountStatus::Created); - other_account.mark_selfdestruct(); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - merge_evm_state(&mut this, &other); - - let merged = this.get_mut(&TEST_ADDRESS).unwrap(); - assert!(merged.is_touched()); - assert!(!merged.is_selfdestructed()); - assert_eq!(merged.info, AccountInfo::default()); - assert!(merged.storage.is_empty()); - assert!(merged.mark_warm_with_transaction_id(0), "coldness should be preserved"); - } - - #[test] - fn test_merge_evm_state_marks_new_accounts_and_storage_as_cold_and_clears_local_flags() { - let mut other_account = - account_with_status(AccountStatus::Created | AccountStatus::CreatedLocal); - other_account.status |= AccountStatus::SelfDestructedLocal; - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(5), 0)); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert!(merged.status.contains(AccountStatus::Cold)); - assert!(merged.status.contains(AccountStatus::Created)); - assert!(!merged.status.contains(AccountStatus::CreatedLocal)); - assert!(!merged.status.contains(AccountStatus::SelfDestructedLocal)); - - let mut slot = merged.storage.get(&U256::from(1)).unwrap().clone(); - assert_eq!(slot.present_value(), U256::from(5)); - assert!(slot.mark_warm_with_transaction_id(0), "new slots should be marked cold"); - } - - #[test] - fn test_merge_evm_state_optional_status_can_skip_or_merge_status_flags() { - let mut base_account = - account_with_status(AccountStatus::SelfDestructed | AccountStatus::Cold); - let mut base_slot = EvmStorageSlot::new(U256::from(1), 0); - base_slot.mark_cold(); - base_account.storage.insert(U256::from(1), base_slot); - let base_state = EvmState::from_iter([(TEST_ADDRESS, base_account)]); - - let mut other_account = - account_with_status(AccountStatus::Created | AccountStatus::CreatedLocal); - other_account.info.balance = U256::from(9); - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(9), 0)); - let other_state = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut without_status_merge = base_state.clone(); - merge_evm_state_optional_status(&mut without_status_merge, &other_state, false); - let without_status_merge_account = without_status_merge.get(&TEST_ADDRESS).unwrap(); - assert!(without_status_merge_account.status.contains(AccountStatus::SelfDestructed)); - assert!(without_status_merge_account.status.contains(AccountStatus::Cold)); - assert!(!without_status_merge_account.status.contains(AccountStatus::Created)); - assert_eq!( - without_status_merge_account.storage.get(&U256::from(1)).unwrap().present_value(), - U256::from(9) - ); - let mut preserved_slot = - without_status_merge_account.storage.get(&U256::from(1)).unwrap().clone(); - assert!(preserved_slot.mark_warm_with_transaction_id(0)); - - let mut with_status_merge = base_state; - merge_evm_state(&mut with_status_merge, &other_state); - let with_status_merge_account = with_status_merge.get(&TEST_ADDRESS).unwrap(); - assert!(!with_status_merge_account.is_selfdestructed()); - assert!(with_status_merge_account.status.contains(AccountStatus::Created)); - assert!(with_status_merge_account.status.contains(AccountStatus::Cold)); - } - - #[test] - fn test_merge_empty_other_state_is_noop() { - let mut this = - EvmState::from_iter([(TEST_ADDRESS, account_with_status(AccountStatus::Cold))]); - let other = EvmState::default(); - - merge_evm_state(&mut this, &other); - - assert_eq!(this.len(), 1); - let account = this.get(&TEST_ADDRESS).unwrap(); - assert_eq!(account.info.balance, U256::from(1)); - } - - #[test] - fn test_merge_evm_state_overwrites_existing_account_storage_and_preserves_slot_coldness() { - let addr2 = address!("2000000000000000000000000000000000000001"); - - let mut base_account = account_with_status(AccountStatus::Touched | AccountStatus::Cold); - let mut base_slot = EvmStorageSlot::new(U256::from(10), 0); - base_slot.mark_cold(); - base_account.storage.insert(U256::from(1), base_slot); - base_account.storage.insert(U256::from(2), EvmStorageSlot::new(U256::from(20), 0)); - let mut this = EvmState::from_iter([(TEST_ADDRESS, base_account)]); - - let mut other_account = account_with_status(AccountStatus::Touched); - other_account.info.balance = U256::from(99); - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::from(10), U256::from(42), 0)); - other_account - .storage - .insert(U256::from(3), EvmStorageSlot::new_changed(U256::ZERO, U256::from(77), 0)); - let other = EvmState::from_iter([ - (TEST_ADDRESS, other_account), - (addr2, account_with_status(AccountStatus::Touched)), - ]); - - merge_evm_state(&mut this, &other); - - assert_eq!(this.len(), 2); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert_eq!(merged.info.balance, U256::from(99)); - assert_eq!(merged.storage.get(&U256::from(1)).unwrap().present_value(), U256::from(42),); - { - let mut existing_slot = merged.storage.get(&U256::from(1)).unwrap().clone(); - assert!( - existing_slot.mark_warm_with_transaction_id(0), - "existing slot should have preserved original coldness" - ); - } - assert_eq!(merged.storage.get(&U256::from(2)).unwrap().present_value(), U256::from(20),); - let mut new_slot = merged.storage.get(&U256::from(3)).unwrap().clone(); - assert_eq!(new_slot.present_value(), U256::from(77)); - assert!(new_slot.mark_warm_with_transaction_id(0), "new slot from other should be cold"); - - let new_account = this.get(&addr2).unwrap(); - assert!(new_account.status.contains(AccountStatus::Cold)); - } - - #[test] - fn test_merge_selfdestructed_account_not_in_base_is_inserted_as_cold_empty() { - let mut other_account = account_with_status(AccountStatus::Created); - other_account.mark_selfdestruct(); - other_account.info.balance = U256::from(999); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert!(merged.is_touched()); - assert!(!merged.is_selfdestructed()); - assert_eq!(merged.info, AccountInfo::default()); - assert!(merged.status.contains(AccountStatus::Cold)); - } - - #[test] - #[should_panic(expected = "EIP-6780 must be applied")] - fn test_merge_evm_state_panics_for_selfdestructed_account_without_created_flag() { - let mut other_account = account_with_status(AccountStatus::Touched); - other_account.mark_selfdestruct(); - other_account.status.remove(AccountStatus::Created); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - } -} diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md deleted file mode 100644 index 7a8370421..000000000 --- a/crates/mega-evm/src/external/AGENTS.md +++ /dev/null @@ -1,32 +0,0 @@ -# AGENTS.md - -## OVERVIEW -External dependency abstraction for block-scoped SALT and oracle data consumed during EVM execution. - -## STRUCTURE -- `mod.rs`: `ExternalEnvTypes`, `ExternalEnvs`, and `EmptyExternalEnv` defaults. -- `factory.rs`: `ExternalEnvFactory` trait for block-scoped environment creation. -- `salt.rs`: SALT trait and bucket-id derivation rules. -- `oracle.rs`: oracle trait for storage reads and hint side effects. -- `gas.rs`: dynamic storage gas calculator with per-bucket multiplier cache. -- `hasher/`: hashing utilities used for deterministic bucket-id computation. - -## KEY PATTERNS -- Block context is captured at environment creation time, not passed per query. -- SALT and oracle are independent traits but consumed together via `ExternalEnvs` bundle. -- Dynamic gas multipliers are cached by bucket id and reset on new parent block. -- External errors are propagated to host and then stashed in EVM context error channel. -- `EmptyExternalEnv` must stay deterministic and side-effect free. - -## ANTI-PATTERNS -- Do not query live chain state directly from opcode handlers. -- All external reads should route through trait objects created by `ExternalEnvFactory`. -- Do not bypass bucket multiplier cache for repeated bucket ids in one block. -- Do not couple oracle hint side effects to SALT behavior. -- Keep SALT and oracle traits independently testable. - -## WHERE TO LOOK -- Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. -- Change bucket multiplier formula: `gas.rs`. -- Change oracle storage retrieval behavior: `oracle.rs` trait impls and `evm/host.rs` integration. -- Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. diff --git a/crates/mega-evm/src/external/factory.rs b/crates/mega-evm/src/external/factory.rs deleted file mode 100644 index 3a1062dec..000000000 --- a/crates/mega-evm/src/external/factory.rs +++ /dev/null @@ -1,41 +0,0 @@ -use alloy_primitives::BlockNumber; -use auto_impl::auto_impl; - -use crate::{ExternalEnvTypes, ExternalEnvs}; - -/// Factory for creating block-specific external environment instances. -/// -/// This trait is responsible for instantiating external oracles at a specific block height, -/// ensuring all oracle queries during EVM execution operate on a consistent snapshot of state. -/// -/// # Design Pattern -/// -/// External environments (SALT and Oracle) do not take block parameters in their methods. -/// Instead, the factory creates block-aware instances that encapsulate the block context, -/// allowing implementations to: -/// - Read state from the appropriate block height -/// - Cache block-specific data for the execution lifetime -/// - Ensure deterministic behavior across repeated executions -/// -/// # Usage -/// -/// This factory is typically called once per block when initializing the EVM. The returned -/// [`ExternalEnvs`] are then used throughout transaction execution within that block. -#[auto_impl(&, Box, Arc)] -pub trait ExternalEnvFactory { - /// The concrete types for SALT and Oracle environments this factory produces. - type EnvTypes: ExternalEnvTypes; - - /// Creates external environment instances for executing EVM operations at the specified block. - /// - /// # Arguments - /// - /// * `block` - The block number at which EVM execution will occur. This is the block height - /// specified in [`BlockEnv`](revm::context::BlockEnv), and oracle queries should read state - /// from the parent block (block - 1). - /// - /// # Returns - /// - /// A container with SALT and Oracle environment instances configured for the given block. - fn external_envs(&self, block: BlockNumber) -> ExternalEnvs; -} diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs deleted file mode 100644 index 2fe08f173..000000000 --- a/crates/mega-evm/src/external/gas.rs +++ /dev/null @@ -1,300 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use core::fmt::Debug; -use revm::primitives::hash_map::Entry; - -use alloy_primitives::{Address, BlockNumber, U256}; -use revm::{context::BlockEnv, primitives::HashMap}; - -use crate::{constants, BucketId, MegaSpecId, SaltEnv, MIN_BUCKET_SIZE}; - -/// Calculator for dynamic gas costs based on bucket capacity. -#[derive(Debug)] -pub struct DynamicGasCost { - /// The spec id. - spec: MegaSpecId, - /// The parent block number. - parent_block: BlockNumber, - /// The external environment for SALT bucket information. - salt_env: SaltEnvImpl, - /// Cache of the bucket cost multiplier for each bucket Id. The multiplier will be used to - /// multiply [`SSTORE_SET_GAS`] to get the actual gas cost for setting a storage slot. - bucket_cost_mulitipers: HashMap, -} - -impl DynamicGasCost { - /// Creates a new [`DynamicGasCost`]. - pub fn new(spec: MegaSpecId, salt_env: SaltEnvImpl, parent_block: BlockNumber) -> Self { - Self { spec, parent_block, salt_env, bucket_cost_mulitipers: HashMap::default() } - } - - /// Resets the cache of the bucket cost multiplier. - pub fn reset(&mut self, parent_block: BlockNumber) { - self.bucket_cost_mulitipers.clear(); - self.parent_block = parent_block; - } - - /// Gets the bucket IDs used during transaction execution. - pub fn get_bucket_ids(&self) -> Vec { - self.bucket_cost_mulitipers.keys().copied().collect() - } - - /// `SSTORE_SET` storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - /// - /// Single source of the per-spec `SSTORE_SET` dynamic storage-gas formula, shared by the - /// SALT-driven path ([`sstore_set_gas`](Self::sstore_set_gas)) and the REX6 system-exempt - /// unscaled path ([`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled)). - fn sstore_set_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::SSTORE_SET_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::SSTORE_SET_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// `NEW_ACCOUNT` storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - fn new_account_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// CREATE storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - fn create_contract_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// Calculates the gas cost for setting a storage slot to a non-zero value. This overrides the - /// [`SSTORE_SET`](revm::interpreter::gas::SSTORE_SET) gas cost in the original EVM. - pub fn sstore_set_gas( - &mut self, - address: Address, - key: U256, - ) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_slot(address, key); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.sstore_set_gas_for_multiplier(multiplier)) - } - - /// Calculates the gas cost for creating a new account. This overrides the - /// [`NEWACCOUNT`](revm::interpreter::gas::NEWACCOUNT) gas cost in the original EVM. - pub fn new_account_gas(&mut self, address: Address) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_account(address); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.new_account_gas_for_multiplier(multiplier)) - } - - /// Calculates the gas cost for creating a new contract. This overrides the - /// [`CREATE`](revm::interpreter::gas::CREATE) gas cost in the original EVM. - pub fn create_contract_gas(&mut self, address: Address) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_account(address); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.create_contract_gas_for_multiplier(multiplier)) - } - - /// SALT-unscaled `SSTORE_SET` storage gas: the cost a write would pay if the target bucket - /// were at its minimum capacity, equivalent to taking the REX-family formula - /// `base × (multiplier − 1)` to `0`. REX6+ charges system-originated transactions this so - /// their storage cost is independent of how full SALT buckets actually are. Unlike - /// [`sstore_set_gas`](Self::sstore_set_gas) this does not query the SALT env or record bucket - /// access. - /// - /// REX-family only: the production caller (`HostExt::sstore_set_storage_gas` under the - /// REX6-gated `LimitCheck::Exempt` stamp) is unreachable pre-REX, and the "0 additional - /// storage gas" property holds only for the REX-family `base × (multiplier − 1)` formula. - pub fn sstore_set_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - // `multiplier = 1` ≡ bucket at minimum capacity, no excess to charge for — - // REX-family `base × (multiplier − 1)` evaluates to `0`. - self.sstore_set_gas_for_multiplier(1) - } - - /// SALT-unscaled `NEW_ACCOUNT` storage gas. - /// See [`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled). - pub fn new_account_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - self.new_account_gas_for_multiplier(1) - } - - /// SALT-unscaled CREATE storage gas. - /// See [`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled). - pub fn create_contract_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - self.create_contract_gas_for_multiplier(1) - } - - /// Loads the bucket cost multiplier for a given bucket Id. - fn load_bucket_cost_multiplier( - &mut self, - bucket_id: BucketId, - ) -> Result { - match self.bucket_cost_mulitipers.entry(bucket_id) { - Entry::Occupied(occupied_entry) => Ok(*occupied_entry.get()), - Entry::Vacant(vacant_entry) => { - let capacity = self.salt_env.get_bucket_capacity(bucket_id)?; - assert!( - capacity >= MIN_BUCKET_SIZE as u64, - "SaltEnv returned bucket_capacity={capacity} below MIN_BUCKET_SIZE ({})", - MIN_BUCKET_SIZE, - ); - let multiplier = capacity / MIN_BUCKET_SIZE as u64; - vacant_entry.insert(multiplier); - Ok(multiplier) - } - } - } -} - -impl DynamicGasCost { - pub(crate) fn on_new_block(&mut self, block: &BlockEnv) { - self.reset(block.number.to::().saturating_sub(1)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::external::test_utils::TestExternalEnvs; - - fn cost_with_capacity(spec: MegaSpecId, capacity: u64) -> DynamicGasCost { - // Map the bucket id that the simple bucket hasher will produce for the zero address / - // zero slot to the requested capacity. - let bucket_for_account = - ::bucket_id_for_account(Address::ZERO); - let bucket_for_slot = - ::bucket_id_for_slot(Address::ZERO, U256::ZERO); - let env = TestExternalEnvs::new() - .with_bucket_capacity(bucket_for_account, capacity) - .with_bucket_capacity(bucket_for_slot, capacity); - DynamicGasCost::new(spec, env, 0) - } - - /// `MIN_BUCKET_SIZE * u64::MAX` cannot be represented in `u64`; verify the hardened - /// arithmetic does not panic and saturates instead of wrapping. - #[test] - fn test_sstore_set_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_new_account_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_create_contract_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - /// REX6 system-exempt path: the unscaled cost (`multiplier = 1`) is `0` for the REX-family - /// formula `base × (multiplier − 1)`, and is independent of the actual bucket capacity. This - /// is what makes a system call's storage cost immune to SALT bucket scaling. - #[test] - fn test_unscaled_gas_is_zero_for_rex_and_independent_of_capacity() { - for capacity in [MIN_BUCKET_SIZE as u64, 1_280_000, u64::MAX] { - let cost = cost_with_capacity(MegaSpecId::REX6, capacity); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - } - - /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX - /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a - /// tightened gate (e.g. REX1) fails here. - #[test] - fn test_unscaled_gas_is_available_from_rex_exactly() { - let cost = cost_with_capacity(MegaSpecId::REX, MIN_BUCKET_SIZE as u64); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - - /// Pre-REX callers must trip the debug assert — a loosened gate (e.g. `MiniRex`) would - /// silently serve the REX-family formula to a spec that prices storage differently. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_sstore_set_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .sstore_set_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_new_account_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .new_account_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_create_contract_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .create_contract_gas_unscaled(); - } - - /// `MiniRex` prices contract creation with the flat `NEW_ACCOUNT_STORAGE_GAS × multiplier` - /// formula; REX switches to `CONTRACT_CREATION_STORAGE_GAS_BASE × (multiplier − 1)`. Pin - /// the boundary from the `MiniRex` side so a loosened REX gate fails here. - #[test] - fn test_create_contract_gas_uses_mini_rex_formula_before_rex() { - let cost = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64); - assert_eq!( - cost.create_contract_gas_for_multiplier(3), - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(3), - ); - assert_ne!( - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(3), - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE.saturating_mul(2), - "the two formulas must disagree for this pin to mean anything", - ); - } - - /// The unscaled result equals the SALT-driven result evaluated at the minimum bucket - /// capacity, confirming the shared formula helper produces consistent values across both paths. - #[test] - fn test_unscaled_matches_salt_path_at_min_capacity() { - let mut cost = cost_with_capacity(MegaSpecId::REX6, MIN_BUCKET_SIZE as u64); - assert_eq!( - cost.sstore_set_gas_unscaled(), - cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(), - ); - } -} diff --git a/crates/mega-evm/src/external/hasher/NOTICE.md b/crates/mega-evm/src/external/hasher/NOTICE.md deleted file mode 100644 index b9dec4196..000000000 --- a/crates/mega-evm/src/external/hasher/NOTICE.md +++ /dev/null @@ -1,27 +0,0 @@ -# Third Party Attribution - -## AHash Crate - -**Source**: [ahash v0.8.12](https://github.com/tkaitchuck/aHash) -**License**: Apache License 2.0 -**Copyright**: Copyright (c) 2019 Tom Kaitchuck -**Repository**: https://github.com/tkaitchuck/aHash - -### Files Derived from AHash - -- `convert.rs` - Extracted from `src/convert.rs` -- `fallback.rs` - Derived from `src/fallback_hash.rs` and related modules - -### Modifications Made - -The code has been extracted and modified for deterministic cross-platform behavior: - -1. **Deterministic algorithm selection**: Always uses the fallback "folded multiply" algorithm with true 128-bit multiplication instead of platform-specific optimizations -2. **Fixed seeds**: Uses predetermined seeds rather than random generation for reproducible results -3. **Consensus compatibility**: Ensures identical hash values across all platforms and architectures -4. **Module structure**: Reorganized into separate modules for better maintainability - -### Original License - -The original AHash crate is licensed under the Apache License 2.0. The full license text can be found at: -https://www.apache.org/licenses/LICENSE-2.0 diff --git a/crates/mega-evm/src/external/hasher/convert.rs b/crates/mega-evm/src/external/hasher/convert.rs deleted file mode 100644 index 36c5c975f..000000000 --- a/crates/mega-evm/src/external/hasher/convert.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Derived from AHash v0.8.12 - see NOTICE.md for full attribution - -pub(crate) trait ReadFromSlice { - fn read_u16(&self) -> (u16, &[u8]); - fn read_u32(&self) -> (u32, &[u8]); - fn read_u64(&self) -> (u64, &[u8]); - fn read_u128(&self) -> (u128, &[u8]); - fn read_last_u32(&self) -> u32; - fn read_last_u64(&self) -> u64; - fn read_last_u128(&self) -> u128; -} - -macro_rules! as_array { - ($input:expr, $len:expr) => {{ - { - #[inline(always)] - fn as_array(slice: &[T]) -> &[T; $len] { - core::convert::TryFrom::try_from(slice).unwrap() - } - as_array($input) - } - }}; -} - -// The original salt crate uses zerocopy::transmute! (native endian). We use from_le_bytes -// to match behavior on all current targets (x86_64, riscv64 — both little-endian) without -// requiring the zerocopy dependency. -#[inline(always)] -fn u16_from_le_bytes(bytes: &[u8; 2]) -> u16 { - u16::from_le_bytes(*bytes) -} - -#[inline(always)] -fn u32_from_le_bytes(bytes: &[u8; 4]) -> u32 { - u32::from_le_bytes(*bytes) -} - -#[inline(always)] -fn u64_from_le_bytes(bytes: &[u8; 8]) -> u64 { - u64::from_le_bytes(*bytes) -} - -#[inline(always)] -fn u128_from_le_bytes(bytes: &[u8; 16]) -> u128 { - u128::from_le_bytes(*bytes) -} - -impl ReadFromSlice for [u8] { - #[inline(always)] - fn read_u16(&self) -> (u16, &[u8]) { - let (value, rest) = self.split_at(2); - (u16_from_le_bytes(as_array!(value, 2)), rest) - } - - #[inline(always)] - fn read_u32(&self) -> (u32, &[u8]) { - let (value, rest) = self.split_at(4); - (u32_from_le_bytes(as_array!(value, 4)), rest) - } - - #[inline(always)] - fn read_u64(&self) -> (u64, &[u8]) { - let (value, rest) = self.split_at(8); - (u64_from_le_bytes(as_array!(value, 8)), rest) - } - - #[inline(always)] - fn read_u128(&self) -> (u128, &[u8]) { - let (value, rest) = self.split_at(16); - (u128_from_le_bytes(as_array!(value, 16)), rest) - } - - #[inline(always)] - fn read_last_u32(&self) -> u32 { - let (_, value) = self.split_at(self.len() - 4); - u32_from_le_bytes(as_array!(value, 4)) - } - - #[inline(always)] - fn read_last_u64(&self) -> u64 { - let (_, value) = self.split_at(self.len() - 8); - u64_from_le_bytes(as_array!(value, 8)) - } - - #[inline(always)] - fn read_last_u128(&self) -> u128 { - let (_, value) = self.split_at(self.len() - 16); - u128_from_le_bytes(as_array!(value, 16)) - } -} diff --git a/crates/mega-evm/src/external/hasher/fallback.rs b/crates/mega-evm/src/external/hasher/fallback.rs deleted file mode 100644 index dd39d6abb..000000000 --- a/crates/mega-evm/src/external/hasher/fallback.rs +++ /dev/null @@ -1,144 +0,0 @@ -// Derived from AHash v0.8.12 - see NOTICE.md for full attribution - -use super::convert::ReadFromSlice; - -#[inline(always)] -fn read_small(data: &[u8]) -> [u64; 2] { - debug_assert!(data.len() <= 8); - if data.len() >= 2 { - if data.len() >= 4 { - [data.read_u32().0 as u64, data.read_last_u32() as u64] - } else { - [data.read_u16().0 as u64, data[data.len() - 1] as u64] - } - } else if !data.is_empty() { - [data[0] as u64, data[0] as u64] - } else { - [0, 0] - } -} - -const PI2: [u64; 4] = - [0x4528_21e6_38d0_1377, 0xbe54_66cf_34e9_0c6c, 0xc0ac_29b7_c97c_50dd, 0x3f84_d5b5_b547_0917]; - -const MULTIPLE: u64 = 6364136223846793005; -const ROT: u32 = 23; - -#[inline(always)] -const fn folded_multiply(s: u64, by: u64) -> u64 { - let result = (s as u128).wrapping_mul(by as u128); - ((result & 0xffff_ffff_ffff_ffff) as u64) ^ ((result >> 64) as u64) -} - -#[derive(Debug, Clone)] -pub(crate) struct RandomState { - k0: u64, - k1: u64, - k2: u64, - k3: u64, -} - -impl RandomState { - #[inline] - pub(super) const fn with_seeds(k0: u64, k1: u64, k2: u64, k3: u64) -> Self { - Self { k0: k0 ^ PI2[0], k1: k1 ^ PI2[1], k2: k2 ^ PI2[2], k3: k3 ^ PI2[3] } - } -} - -#[derive(Debug, Clone)] -pub(crate) struct DeterministicHasher { - buffer: u64, - pad: u64, - extra_keys: [u64; 2], -} - -impl DeterministicHasher { - #[inline(always)] - fn update(&mut self, new_data: u64) { - self.buffer = folded_multiply(new_data ^ self.buffer, MULTIPLE); - } - - #[inline(always)] - fn large_update(&mut self, new_data: u128) { - let block: [u64; 2] = [new_data as u64, (new_data >> 64) as u64]; - let combined = - folded_multiply(block[0] ^ self.extra_keys[0], block[1] ^ self.extra_keys[1]); - self.buffer = (self.buffer.wrapping_add(self.pad) ^ combined).rotate_left(ROT); - } -} - -impl core::hash::Hasher for DeterministicHasher { - #[inline] - fn write_u8(&mut self, i: u8) { - self.update(i as u64); - } - - #[inline] - fn write_u16(&mut self, i: u16) { - self.update(i as u64); - } - - #[inline] - fn write_u32(&mut self, i: u32) { - self.update(i as u64); - } - - #[inline] - fn write_u64(&mut self, i: u64) { - self.update(i); - } - - #[inline] - fn write_u128(&mut self, i: u128) { - self.large_update(i); - } - - #[inline] - fn write_usize(&mut self, i: usize) { - self.write_u64(i as u64); - } - - #[inline] - fn write(&mut self, input: &[u8]) { - let mut data = input; - let length = data.len() as u64; - - self.buffer = self.buffer.wrapping_add(length).wrapping_mul(MULTIPLE); - - if data.len() > 8 { - if data.len() > 16 { - let tail = data.read_last_u128(); - self.large_update(tail); - while data.len() > 16 { - let (block, rest) = data.read_u128(); - self.large_update(block); - data = rest; - } - } else { - let front = data.read_u64().0; - let back = data.read_last_u64(); - let combined = (front as u128) | ((back as u128) << 64); - self.large_update(combined); - } - } else { - let value = read_small(data); - let combined = (value[0] as u128) | ((value[1] as u128) << 64); - self.large_update(combined); - } - } - - #[inline] - fn finish(&self) -> u64 { - let rot = (self.buffer & 63) as u32; - folded_multiply(self.buffer, self.pad).rotate_left(rot) - } -} - -impl core::hash::BuildHasher for RandomState { - type Hasher = DeterministicHasher; - - #[inline] - fn build_hasher(&self) -> Self::Hasher { - DeterministicHasher { buffer: self.k1, pad: self.k0, extra_keys: [self.k2, self.k3] } - } -} diff --git a/crates/mega-evm/src/external/mod.rs b/crates/mega-evm/src/external/mod.rs deleted file mode 100644 index feb0fb4a0..000000000 --- a/crates/mega-evm/src/external/mod.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! External environment for EVM execution. -//! -//! This module provides interfaces for accessing external data sources during EVM execution: -//! - **SALT**: Bucket capacity information for dynamic gas pricing -//! - **Oracle**: Storage from the `MegaETH` oracle contract -//! -//! # Architecture -//! -//! External environments follow a factory pattern: -//! 1. [`ExternalEnvFactory`] creates block-specific environment instances -//! 2. [`ExternalEnvs`] bundles SALT and Oracle implementations -//! 3. Individual oracle methods (e.g., [`SaltEnv::get_bucket_capacity`]) provide data -//! -//! Block context is established at factory creation time, not per oracle call, ensuring -//! consistent state snapshots throughout execution. - -use alloy_primitives::BlockNumber; -use auto_impl::auto_impl; -use core::fmt::Debug; - -mod factory; -mod gas; -#[cfg(any(test, feature = "test-utils"))] -mod hasher; -mod oracle; -mod salt; -#[cfg(any(test, feature = "test-utils"))] -mod test_utils; - -pub use factory::*; -pub use gas::*; -#[cfg(any(test, feature = "test-utils"))] -pub use hasher::*; -pub use oracle::*; -pub use salt::*; -#[cfg(any(test, feature = "test-utils"))] -pub use test_utils::*; - -/// Type-level specification of external environment implementations. -/// -/// This trait associates concrete SALT and Oracle types, allowing generic code to work -/// with any compatible environment configuration. -#[auto_impl(&, Box, Arc)] -pub trait ExternalEnvTypes { - /// SALT environment implementation for bucket capacity queries. - type SaltEnv: SaltEnv; - /// Oracle environment implementation for system contract storage queries. - type OracleEnv: OracleEnv; -} - -/// Tuple implementation for convenient pairing of SALT and Oracle environments. -impl ExternalEnvTypes for (A, B) { - type SaltEnv = A; - type OracleEnv = B; -} - -/// Bundle of external environment instances for a specific execution context. -/// -/// This struct holds concrete SALT and Oracle implementations that are used during -/// EVM execution. Typically created by [`ExternalEnvFactory::external_envs`] at the -/// start of block processing. -#[derive(Debug, Clone)] -pub struct ExternalEnvs { - /// SALT environment for bucket capacity queries and dynamic gas calculation. - pub salt_env: T::SaltEnv, - /// Oracle environment for reading system contract storage. - pub oracle_env: T::OracleEnv, -} - -impl Default for ExternalEnvs { - fn default() -> Self { - Self { salt_env: EmptyExternalEnv, oracle_env: EmptyExternalEnv } - } -} - -/// No-op external environment for testing or when oracle functionality is disabled. -/// -/// This implementation: -/// - Returns minimum bucket capacity for all SALT queries -/// - Returns `None` for all Oracle storage queries -/// - Assigns all accounts and storage slots to bucket 0 -#[derive(Debug, Default, Clone, Copy)] -pub struct EmptyExternalEnv; - -impl ExternalEnvTypes for EmptyExternalEnv { - type SaltEnv = Self; - type OracleEnv = Self; -} - -impl ExternalEnvFactory for EmptyExternalEnv { - type EnvTypes = Self; - - fn external_envs(&self, _block: BlockNumber) -> ExternalEnvs { - ExternalEnvs { salt_env: *self, oracle_env: *self } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{OracleEnv, SaltEnv, MIN_BUCKET_SIZE}; - use alloy_primitives::{Address, Bytes, B256, U256}; - - #[test] - fn test_empty_external_env_factory_returns_minimum_bucket_and_no_oracle() { - let envs = EmptyExternalEnv.external_envs(42); - - assert_eq!(envs.salt_env.get_bucket_capacity(123).unwrap(), MIN_BUCKET_SIZE as u64); - assert_eq!(envs.oracle_env.get_oracle_storage(U256::from(7)), None); - envs.oracle_env.on_hint(Address::ZERO, B256::ZERO, Bytes::new()); - assert_eq!(::bucket_id_for_account(Address::ZERO), 0); - assert_eq!(::bucket_id_for_slot(Address::ZERO, U256::ZERO), 0); - } -} diff --git a/crates/mega-evm/src/external/oracle.rs b/crates/mega-evm/src/external/oracle.rs deleted file mode 100644 index 303638e4d..000000000 --- a/crates/mega-evm/src/external/oracle.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! Oracle environment trait and implementations. - -use core::fmt::Debug; - -use alloy_primitives::{Address, Bytes, B256, U256}; -use auto_impl::auto_impl; - -use crate::EmptyExternalEnv; - -/// An oracle service that provides external information to the EVM. This trait provides a mechanism -/// for the EVM to query storage slots from the `MegaETH` oracle contract. -/// -/// Typically, one implementation of this trait can be a reader of the underlying blockchain -/// database of `MegaETH` to provide deterministic oracle data during EVM execution. -#[auto_impl(&, Box, Arc)] -pub trait OracleEnv: Debug + Unpin { - /// Gets the storage value at a specific slot of the `MegaETH` oracle contract. - /// - /// # Arguments - /// - /// * `slot` - The storage slot to query - /// - /// # Returns - /// - /// The storage value at the given slot of the oracle contract. If the oracle does not provide a - /// value, the result will be `None`. - fn get_oracle_storage(&self, slot: U256) -> Option; - - /// Receives hints emitted on-chain by the oracle contract. A hint is a message sent from - /// on-chain to the oracle service backend (on the sequencer). - /// - /// # Arguments - /// - /// Invoking the `sendHint(bytes32 topic, bytes data)` function on the oracle contract during - /// transaction execution will trigger this method synchronously. - /// - `from` - The address that called the `sendHint` function. This is useful for off-chain - /// access control, as the `msg.sender` cannot be faked. On-chain access control can be - /// enforced in a periphery contract which directly calls `sendHint`. - /// - `topic` - The user-defined hint topic. - /// - `data` - The additional context data for the hint. - /// - /// The order of hinting ([`Self::on_hint`]) and oracle reading ([`Self::get_oracle_storage`]) - /// is guaranteed preserved, i.e., if the on-chain transaction emits a hint log first and then - /// tries to read oracle data, `on_hint` is guaranteed to be called before `get_oracle_storage`. - /// - /// One example application is telling the off-chain oracle service which data needs to be - /// fetched before it provides any oracle data. Handling hints is completely optional for the - /// oracle service backend. - /// - /// # Warning - /// - /// This method is called synchronously during transaction execution. Therefore, it should not - /// perform any heavy computations, which otherwise will block the transaction execution and - /// lower the EVM performance. - fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} -} - -impl OracleEnv for EmptyExternalEnv { - fn get_oracle_storage(&self, _slot: U256) -> Option { - None - } -} diff --git a/crates/mega-evm/src/external/salt.rs b/crates/mega-evm/src/external/salt.rs deleted file mode 100644 index 77dc611df..000000000 --- a/crates/mega-evm/src/external/salt.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! This module defines the `SaltEnv` trait, which provides bucket capacity information for dynamic -//! gas pricing. Storage slots and accounts are organized into buckets, and the gas cost scales -//! with bucket capacity to incentivize efficient resource allocation. - -use core::{ - convert::Infallible, - fmt::{Debug, Display}, -}; - -use alloy_primitives::{Address, U256}; -use auto_impl::auto_impl; - -use crate::EmptyExternalEnv; - -/// SALT bucket identifier. Accounts and storage slots are mapped to buckets, which have -/// dynamic capacities that affect gas costs. -pub type BucketId = u32; - -/// Number of bits to represent the minimum bucket size (8 bits = 256 slots). -pub const MIN_BUCKET_SIZE_BITS: usize = 8; - -/// Minimum capacity of a SALT bucket in number of slots (256). -/// -/// Buckets hold accounts or storage slots and can grow beyond this size. The gas cost -/// multiplier is calculated as `capacity / MIN_BUCKET_SIZE`, so a bucket at minimum -/// capacity has a 1x multiplier. -pub const MIN_BUCKET_SIZE: usize = 1 << MIN_BUCKET_SIZE_BITS; - -/// Interface for SALT bucket capacity information. -/// -/// This trait provides bucket capacity data needed for dynamic gas pricing. Implementations -/// typically read from the underlying blockchain database to ensure deterministic execution. -/// -/// # Block-Awareness -/// -/// This trait does not take a block parameter. Block context is provided when the environment -/// is created via [`ExternalEnvFactory::external_envs`](crate::ExternalEnvFactory::external_envs), -/// allowing implementations to snapshot state at a specific block. -/// -/// # Bucket ID Calculation -/// -/// The trait provides default methods [`bucket_id_for_account`](SaltEnv::bucket_id_for_account) -/// and [`bucket_id_for_slot`](SaltEnv::bucket_id_for_slot) that can be overridden by -/// implementations to customize bucket assignment logic. -#[auto_impl(&, Box, Rc, Arc)] -pub trait SaltEnv: Debug + Unpin { - /// Error type returned when bucket capacity cannot be retrieved. - type Error: Display; - - /// Returns the current capacity of the specified bucket. - /// - /// # Gas Cost Calculation - /// - /// The returned capacity is used to calculate a gas multiplier: - /// ```text - /// multiplier = capacity / MIN_BUCKET_SIZE - /// ``` - /// This multiplier scales the base storage gas costs, making operations more expensive - /// as buckets grow. - /// - /// # Arguments - /// - /// * `bucket_id` - The bucket to query - /// - /// # Returns - /// - /// The bucket's capacity in number of slots, or an error if unavailable. - fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result; - - /// Maps an account address to its bucket ID. - /// - /// This method determines which bucket tracks the account creation gas costs. - /// The default implementation can be overridden to customize bucket assignment. - /// - /// # Arguments - /// - /// * `account` - The account address to map - fn bucket_id_for_account(account: Address) -> BucketId; - - /// Maps a storage slot to its bucket ID. - /// - /// This method determines which bucket tracks the storage slot's gas costs. - /// The default implementation can be overridden to customize bucket assignment. - /// - /// # Arguments - /// - /// * `address` - The contract address owning the storage - /// * `key` - The storage slot key - fn bucket_id_for_slot(address: Address, key: U256) -> BucketId; -} - -/// No-op implementation that returns minimum bucket size for all buckets. -/// -/// This implementation assigns all accounts and storage slots to bucket 0 with minimum -/// capacity, effectively disabling dynamic gas pricing. Useful for testing or when SALT -/// functionality is not needed. -impl SaltEnv for EmptyExternalEnv { - type Error = Infallible; - - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Ok(MIN_BUCKET_SIZE as u64) - } - - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 as BucketId - } - - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 as BucketId - } -} diff --git a/crates/mega-evm/src/external/test_utils.rs b/crates/mega-evm/src/external/test_utils.rs deleted file mode 100644 index 04da5bb0d..000000000 --- a/crates/mega-evm/src/external/test_utils.rs +++ /dev/null @@ -1,308 +0,0 @@ -//! In-memory external environment implementations. -//! -//! Provides [`TestExternalEnvs`], a configurable in-memory implementation of SALT and Oracle -//! environments backed by `HashMap`s. -//! Unlike [`EmptyExternalEnv`](crate::EmptyExternalEnv) which returns hardcoded defaults, -//! this implementation allows setting specific bucket capacities and oracle storage values. -//! -//! # Use Cases -//! -//! - **Unit and integration tests**: Configure bucket capacities and oracle storage to exercise -//! specific gas pricing and oracle access paths without a real database. -//! - **CLI tools** (e.g., `mega-evme`): Simulate EVM execution with user-specified bucket -//! capacities and oracle state, useful for offline transaction analysis and debugging. -//! - **Standalone EVM runners**: Any context where a full node database is unavailable but -//! controllable external environment state is needed. - -#[cfg(not(feature = "std"))] -use alloc as std; -use core::{ - cell::RefCell, - convert::Infallible, - fmt::{Debug, Display}, -}; -use std::{rc::Rc, vec::Vec}; - -use alloy_primitives::{Address, BlockNumber, Bytes, B256, U256}; -use revm::primitives::HashMap; - -use crate::{BucketId, ExternalEnvFactory, ExternalEnvTypes, ExternalEnvs, OracleEnv, SaltEnv}; - -/// Strategy trait for computing bucket IDs from raw key bytes. -/// -/// Implementations determine how account addresses and storage slot keys are mapped to -/// SALT bucket IDs. The trait only requires a single static method, making it zero-cost -/// to parameterize [`TestExternalEnvs`] over different hashing strategies. -pub trait BucketHasher: Debug + Clone + Unpin + 'static { - /// Computes a bucket ID from the given key bytes. - fn bucket_id(key: &[u8]) -> BucketId; -} - -/// Simple deterministic hasher for tests. -/// -/// Uses FNV-1a to produce consistent bucket IDs. This is NOT the real SALT hash algorithm; -/// tests only need consistency (same input produces same output), not compatibility with -/// the production SALT trie. -#[derive(Debug, Clone, Copy)] -pub struct SimpleBucketHasher; - -impl BucketHasher for SimpleBucketHasher { - fn bucket_id(key: &[u8]) -> BucketId { - let mut hash: u64 = 0xcbf29ce484222325; - for &byte in key { - hash ^= byte as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - // Map to valid bucket range [NUM_META_BUCKETS, NUM_BUCKETS) - const NUM_BUCKETS: u64 = 1 << 24; // 16,777,216 - const NUM_META_BUCKETS: u64 = NUM_BUCKETS / 256; // 65,536 - const NUM_KV_BUCKETS: u64 = NUM_BUCKETS - NUM_META_BUCKETS; - (hash % NUM_KV_BUCKETS + NUM_META_BUCKETS) as BucketId - } -} - -/// A recorded oracle hint from `on_hint` calls. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RecordedHint { - /// The sender address who called `sendHint`. - pub from: Address, - /// The user-defined hint topic. - pub topic: B256, - /// The hint data. - pub data: Bytes, -} - -/// In-memory external environment implementation backed by `HashMap`s. -/// -/// Provides configurable SALT bucket capacities, oracle storage values, and oracle hint -/// recording, all stored in memory. -/// Suitable for unit tests, integration tests, CLI tools, and any standalone EVM execution -/// context where a real node database is unavailable. -/// -/// # Bucket Hashing -/// -/// The `Hasher` type parameter controls how account addresses and storage slot keys are -/// mapped to bucket IDs. -/// The default [`SimpleBucketHasher`] uses FNV-1a — sufficient for tests where only -/// consistency matters, not production compatibility. -/// For production-compatible bucket IDs (matching the `salt` crate), supply a hasher that -/// implements the real SALT hashing algorithm. -/// -/// # Example -/// ```ignore -/// let env = TestExternalEnvs::new() -/// .with_bucket_capacity(123, 512) // Set bucket 123 to 512 capacity -/// .with_oracle_storage(U256::ZERO, U256::from(42)); // Set oracle slot 0 to 42 -/// ``` -#[derive(derive_more::Debug, Clone)] -pub struct TestExternalEnvs { - #[debug(ignore)] - _phantom: core::marker::PhantomData<(Error, Hasher)>, - /// Oracle contract storage values. Maps storage slot keys to their values. - oracle_storage: Rc>>, - /// Bucket capacities. Maps bucket IDs to their capacity values. - /// Buckets not in this map default to [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE) or - /// `default_bucket_capacity` if set. - bucket_capacity: Rc>>, - /// Fallback capacity for buckets not in `bucket_capacity`. - /// When `None`, falls back to [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). - default_bucket_capacity: Rc>>, - /// Recorded hints from `on_hint` calls. Used for testing the hint mechanism. - recorded_hints: Rc>>, -} - -impl Default for TestExternalEnvs { - fn default() -> Self { - Self::new() - } -} - -impl From> - for ExternalEnvs> -{ - fn from(value: TestExternalEnvs) -> Self { - Self { salt_env: value.clone(), oracle_env: value } - } -} - -impl<'a, H: BucketHasher> From<&'a TestExternalEnvs> - for ExternalEnvs<&'a TestExternalEnvs> -{ - fn from(value: &'a TestExternalEnvs) -> Self { - ExternalEnvs { salt_env: value.clone(), oracle_env: value.clone() } - } -} - -impl - TestExternalEnvs -{ - /// Creates a new environment with empty bucket capacity and oracle storage. - pub fn new() -> Self { - Self { - _phantom: core::marker::PhantomData, - oracle_storage: Rc::new(RefCell::new(HashMap::default())), - bucket_capacity: Rc::new(RefCell::new(HashMap::default())), - default_bucket_capacity: Rc::new(RefCell::new(None)), - recorded_hints: Rc::new(RefCell::new(Vec::new())), - } - } - - /// Returns all recorded hints from `on_hint` calls. - /// - /// This is useful for testing that the hint mechanism is working correctly. - pub fn recorded_hints(&self) -> Vec { - self.recorded_hints.borrow().clone() - } - - /// Clears all recorded hints. - pub fn clear_recorded_hints(&self) { - self.recorded_hints.borrow_mut().clear(); - } - - /// Configures a bucket to have a specific capacity. - /// - /// This affects the gas multiplier calculation for operations on accounts or storage - /// slots mapped to this bucket. The multiplier will be `capacity / MIN_BUCKET_SIZE`. - /// - /// # Arguments - /// - /// * `bucket_id` - The bucket ID to configure - /// * `capacity` - The bucket capacity in number of slots - /// - /// # Returns - /// - /// `self` for method chaining - pub fn with_bucket_capacity(self, bucket_id: BucketId, capacity: u64) -> Self { - self.bucket_capacity.borrow_mut().insert(bucket_id, capacity); - self - } - - /// Sets a fallback capacity returned for every bucket not configured via - /// [`with_bucket_capacity`]. Lets a bench exercise the dynamic-gas multiplier - /// without computing the bucket id of each touched slot. - pub fn with_default_bucket_capacity(self, capacity: u64) -> Self { - *self.default_bucket_capacity.borrow_mut() = Some(capacity); - self - } - - /// Removes all configured bucket capacities. - /// - /// After calling this, all buckets will return the configured `default_bucket_capacity` if - /// set, otherwise [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). - pub fn clear_bucket_capacity(&self) { - self.bucket_capacity.borrow_mut().clear(); - } - - /// Configures a storage slot in the oracle contract to have a specific value. - /// - /// # Arguments - /// - /// * `slot` - The storage slot key - /// * `value` - The value to store - /// - /// # Returns - /// - /// `self` for method chaining - pub fn with_oracle_storage(self, slot: U256, value: U256) -> Self { - self.oracle_storage.borrow_mut().insert(slot, value); - self - } - - /// Removes all configured oracle storage values. - /// - /// After calling this, all oracle storage queries will return `None`. - pub fn clear_oracle_storage(&self) { - self.oracle_storage.borrow_mut().clear(); - } - - /// Returns the configured bucket capacities as `(bucket_id, capacity)` pairs. - /// - /// Used to snapshot the effective external environment into a self-validating - /// fixture. - pub fn bucket_capacities(&self) -> Vec<(BucketId, u64)> { - self.bucket_capacity.borrow().iter().map(|(&id, &cap)| (id, cap)).collect() - } - - /// Returns the configured oracle storage as `(slot, value)` pairs. - /// - /// Used to snapshot the effective external environment into a self-validating - /// fixture. - pub fn oracle_storage(&self) -> Vec<(U256, U256)> { - self.oracle_storage.borrow().iter().map(|(&slot, &value)| (slot, value)).collect() - } -} - -impl ExternalEnvFactory - for TestExternalEnvs -{ - type EnvTypes = Self; - - fn external_envs(&self, _block: BlockNumber) -> ExternalEnvs { - ExternalEnvs { salt_env: self.clone(), oracle_env: self.clone() } - } -} - -impl ExternalEnvTypes - for TestExternalEnvs -{ - type SaltEnv = Self; - - type OracleEnv = Self; -} - -/// Length of a storage slot key in bytes (32 bytes for U256). -const SLOT_KEY_LEN: usize = B256::len_bytes(); -/// Length of an account address in bytes (20 bytes). -const PLAIN_ACCOUNT_KEY_LEN: usize = Address::len_bytes(); -/// Length of a combined address+slot key (52 bytes = 20 + 32). -const PLAIN_STORAGE_KEY_LEN: usize = PLAIN_ACCOUNT_KEY_LEN + SLOT_KEY_LEN; - -/// SALT environment implementation with configurable bucket ID hashing. -impl SaltEnv for TestExternalEnvs { - type Error = Error; - - fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result { - Ok(self.bucket_capacity.borrow().get(&bucket_id).copied().unwrap_or_else(|| { - self.default_bucket_capacity.borrow().unwrap_or(crate::MIN_BUCKET_SIZE as u64) - })) - } - - fn bucket_id_for_account(account: Address) -> BucketId { - Hasher::bucket_id(account.as_slice()) - } - - fn bucket_id_for_slot(address: Address, key: U256) -> BucketId { - Hasher::bucket_id( - address.concat_const::(key.into()).as_slice(), - ) - } -} - -impl OracleEnv for TestExternalEnvs { - fn get_oracle_storage(&self, slot: U256) -> Option { - self.oracle_storage.borrow().get(&slot).copied() - } - - fn on_hint(&self, from: Address, topic: B256, data: Bytes) { - self.recorded_hints.borrow_mut().push(RecordedHint { from, topic, data }); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_with_default_bucket_capacity_applies_to_all_buckets() { - use crate::external::salt::SaltEnv; - let env = - TestExternalEnvs::::new().with_default_bucket_capacity(2048); - // Any bucket id not explicitly configured now returns the default, not MIN_BUCKET_SIZE. - assert_eq!(env.get_bucket_capacity(123), Ok(2048)); - assert_eq!(env.get_bucket_capacity(999), Ok(2048)); - // An explicit per-bucket capacity still wins. - let env = env.with_bucket_capacity(123, 512); - assert_eq!(env.get_bucket_capacity(123), Ok(512)); - assert_eq!(env.get_bucket_capacity(999), Ok(2048)); - } -} diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index ce129a5af..7e7cdda04 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -1,71 +1,7 @@ -//! The EVM implementation for the `MegaETH`. -#![cfg_attr(not(test), warn(unused_crate_dependencies))] +//! The EVM implementation for the `MegaETH` Satin engine. #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] #[cfg_attr(not(feature = "std"), macro_use)] #[cfg(not(feature = "std"))] extern crate alloc; - -mod access; -mod block; -pub mod constants; -mod evm; -mod external; -mod limit; -pub mod sandbox; -mod system; -#[cfg(any(test, feature = "test-utils"))] -pub mod test_utils; -mod types; - -pub use access::*; -pub use block::*; -pub use evm::*; -pub use external::*; -pub use limit::*; -pub use system::*; -pub use types::*; - -/* Re-export of upstream types */ -pub use alloy_consensus; -pub use alloy_eips; -pub use alloy_evm; -pub use alloy_hardforks; -pub use alloy_op_evm; -pub use alloy_op_hardforks; -pub use alloy_primitives; -pub use alloy_sol_types; -pub use op_alloy_consensus; -pub use op_alloy_flz; -pub use op_revm; -pub use revm::{self, context::either::Either, primitives::HashMap}; - -/* Alias of the mega-evm types */ -/// Alias for [`MegaTransaction`] -pub type Transaction = MegaTransaction; -/// Alias for [`MegaSpecId`] -pub type SpecId = MegaSpecId; -/// Alias for [`MegaHaltReason`] -pub type HaltReason = MegaHaltReason; -/// Alias for [`MegaTransactionError`] -pub type TransactionError = MegaTransactionError; -/// Alias for [`MegaPrecompiles`] -pub type Precompiles = MegaPrecompiles; -/// Alias for [`MegaTxType`] -pub type TxType = MegaTxType; -/// Alias for [`MegaInstructions`] -pub type Instructions = MegaInstructions; -/// Alias for [`MegaHandler`] -pub type Handler = MegaHandler; -/// Alias for [`MegaEvm`] -pub type Evm = MegaEvm; -/// Alias for [`MegaEvmFactory`] -pub type EvmFactory = MegaEvmFactory; -/// Alias for [`MegaContext`] -pub type Context = MegaContext; -/// Alias for [`MegaBlockExecutor`] -pub type BlockExecutor = MegaBlockExecutor; -/// Alias for [`MegaBlockExecutorFactory`] -pub type BlockExecutorFactory = - MegaBlockExecutorFactory; diff --git a/crates/mega-evm/src/limit/AGENTS.md b/crates/mega-evm/src/limit/AGENTS.md deleted file mode 100644 index c4799024d..000000000 --- a/crates/mega-evm/src/limit/AGENTS.md +++ /dev/null @@ -1,36 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Resource metering subsystem for transaction and frame limits across compute gas, data size, KV updates, and state growth. - -## STRUCTURE -- `limit.rs`: `AdditionalLimit` coordinator and frame/tx lifecycle hooks. -- `compute_gas.rs`: compute gas tracking, detention limits, frame budgets. -- `data_size.rs`: tx/frame data accounting with revert-aware discard paths. -- `kv_update.rs`: tx/frame KV accounting with revert-aware discard paths. -- `state_growth.rs`: net-new account/slot growth accounting. -- `frame_limit.rs`: generic 98/100 frame-limit tracker utilities. -- `storage_call_stipend.rs`: dual-mode stipend — REX5+ separated allowance drained at `storage_gas_ext` sites; REX4 legacy inflation with compute cap and burn-on-return. -- `mod.rs`: `LimitKind`, `LimitCheck`, revert-data ABI surface. - -## KEY PATTERNS -- Limit-check order is deterministic and shared by all opcode paths. -- Distinguish TX-level exceed (halt/OutOfGas) from frame-local exceed (revert). -- All trackers push/pop per-frame in lockstep with EVM frame lifecycle hooks. -- Synthetic frame results still require empty-frame pushes for stack alignment. -- Gas rescue must exclude any system-granted stipend gas. -- Revert paths must roll back discardable usage for data/KV/state growth trackers. - -## ANTI-PATTERNS -- Do not introduce per-frame gas grants without explicit unwind-on-return behavior. -- Do not encode frame-local exceeds as halts. -- They must be reverts with bounded payload. -- Do not read tracker totals after an exceeded-limit revert path unless using tracker-owned finalized APIs. -- Avoid duplicating limit checks inside opcode handlers when the tracker already enforces the same dimension. - -## WHERE TO LOOK -- New limit dimension: add tracker module, wire into `AdditionalLimit`, extend `LimitKind`/`LimitCheck`. -- Change exceed semantics or revert data: `mod.rs` and `limit.rs` helper builders. -- Change compute detention behavior: `compute_gas.rs` and detention callers in `evm` module. -- Change frame budget forwarding logic: `frame_limit.rs` and each tracker’s frame hooks. -- Change storage call stipend semantics: `storage_call_stipend.rs` and `limit.rs` integration points. diff --git a/crates/mega-evm/src/limit/compute_gas.rs b/crates/mega-evm/src/limit/compute_gas.rs deleted file mode 100644 index d37e27cac..000000000 --- a/crates/mega-evm/src/limit/compute_gas.rs +++ /dev/null @@ -1,270 +0,0 @@ -use revm::{handler::FrameResult, interpreter::interpreter_action::FrameInit}; - -use super::{ - frame_limit::{FrameLimitTracker, TxRuntimeLimit}, - LimitCheck, LimitKind, -}; -use crate::{JournalInspectTr, MegaSpecId}; - -/// A frame-limit-based compute gas tracker using `FrameLimitTracker`. -/// -/// Unlike the other trackers (`DataSizeTracker`, `KVUpdateTracker`, `StateGrowthTracker`), compute -/// gas is **always persistent**: CPU cycles cannot be undone, so even if a child frame reverts, -/// its compute gas still counts toward the parent's total. All gas is recorded as -/// `persistent_usage`, never as `discardable_usage` or `refund`. -/// -/// In Rex4+, compute gas is enforced at **both** per-frame and TX level: -/// - **Per-frame**: Each inner call frame receives `remaining * 98 / 100` of the parent's remaining -/// compute gas budget. When a frame exceeds its budget, it reverts (not halts). However, since -/// gas is always persistent, the parent's total gas still increases by the child's actual gas -/// used — per-frame limits act as "early termination guardrails", not budget protection. -/// - **TX-level (detained)**: The effective TX limit may be dynamically lowered by gas detention -/// (volatile data access). In Rex4+ the cap is **relative** to current usage at the access point -/// (`current_usage + cap`), while pre-Rex4 it is absolute. This remains a TX-level halt for all -/// specs including Rex4+. -/// -/// In pre-Rex4, compute gas is enforced at the TX level only. -/// -/// Compute gas is NOT recorded via `TxRuntimeLimit` lifecycle hooks. Instead it is -/// recorded externally via `record_gas_used()` called from: -/// - `compute_gas!` macro in `instructions.rs` (per-opcode) -/// - `execution.rs` frame completion (code deposit cost + initial gas) -/// - `precompiles.rs` (precompile gas) -/// - `sandbox/execution.rs` (sandbox gas) -#[derive(Debug, Clone)] -pub(crate) struct ComputeGasTracker { - rex1_enabled: bool, - rex4_enabled: bool, - /// The effective compute gas limit, which may be dynamically lowered by gas detention - /// (volatile data access). Always <= `frame_tracker.tx_limit()`. - detained_limit: u64, - frame_tracker: FrameLimitTracker<()>, -} - -impl ComputeGasTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - detained_limit: tx_limit, - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - rex1_enabled: spec.is_enabled(MegaSpecId::REX1), - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - } - } - - /// Pushes a new frame onto the tracker. - /// - /// - **Rex4+ top-level**: budget = `tx_entry.remaining()` (accounts for intrinsic compute gas - /// already recorded before the first frame is pushed). - /// - **Rex4+ nested**: budget = parent's remaining × 98/100 (generic behavior). - /// - **Pre-Rex4**: `u64::MAX` (TX-level enforcement only). - fn push_frame(&mut self) { - if self.rex4_enabled { - self.frame_tracker.push_frame(()); - } else { - self.frame_tracker.push_frame_with_limit(u64::MAX, ()); - } - } - - /// Sets the detained compute gas limit (takes the minimum of current and new effective limit). - /// This is used to dynamically lower the compute gas limit when volatile data is accessed. - /// - /// - **REX4+**: The cap is **relative** to current usage — allows `cap` more compute gas after - /// the access point. Effective limit = `current_usage + cap`. - /// - **Pre-REX4**: The cap is **absolute** — effective limit = `cap`. - pub(crate) fn set_detained_limit(&mut self, cap: u64) { - let new_limit = if self.rex4_enabled { - // REX4+: cap is relative to current usage (limits post-access computation) - self.tx_usage().saturating_add(cap) - } else { - // Pre-REX4: cap is absolute - cap - }; - self.detained_limit = self.detained_limit.min(new_limit); - } - - /// Returns the remaining compute gas of the current call. - /// - /// In Rex4+, returns the minimum of the caller's per-frame remaining compute gas - /// and the TX-level detained remaining. This ensures the returned value reflects - /// the actual compute gas available before execution halts, whether due to - /// per-frame budget exhaustion or TX-level gas detention (e.g., after volatile - /// data access like TIMESTAMP). - /// If no frame exists yet (direct TX → system contract), returns the TX-level - /// remaining which accounts for intrinsic compute gas. - /// In pre-Rex4, falls back to TX-level remaining compute gas. - /// - /// Called during system contract interception, before the callee's frame is pushed. - /// At that point `frame_stack.last()` is the caller's frame, so - /// `current_frame_remaining()` gives the caller's remaining compute gas. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = self.tx_limit().saturating_sub(self.tx_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } - - /// Returns the current detained compute gas limit. - pub(crate) fn detained_limit(&self) -> u64 { - self.detained_limit - } - - /// Returns `true` when gas detention is the binding TX-level constraint, i.e., the detained - /// limit is tighter than the base TX limit AND actual usage exceeds it. - pub(crate) fn is_detained_exceed(&self) -> bool { - let used = self.tx_usage(); - used > self.detained_limit && self.detained_limit < self.frame_tracker.tx_limit() - } - - /// Caps the current (top) frame's compute gas budget. - /// - /// Used by the **REX4 legacy** `STORAGE_CALL_STIPEND` path: the child's total gas - /// (`gas_limit`) is inflated by `STORAGE_CALL_STIPEND`, but compute gas must remain - /// bounded at the original `forwarded_gas + CALL_STIPEND` so the extra storage stipend - /// cannot be spent on compute opcodes. This method tightens the per-frame compute gas - /// limit to enforce that cap. - /// - /// REX5+ does not call this method: under the separated-allowance model the child's - /// `gas.limit()` is never inflated, so the per-frame compute budget already equals the - /// pre-inflation amount naturally. - pub(crate) fn cap_current_frame_limit(&mut self, cap: u64) { - if let Some(frame) = self.frame_tracker.frame_mut() { - frame.limit = frame.limit.min(cap); - } - } - - /// Records compute gas as persistent usage in the current frame. - /// If no frame exists (before `frame_init` or after last frame pop), - /// records to the `tx_entry`. - /// - /// Compute gas is always persistent because CPU cycles cannot be undone. - #[inline] - pub(crate) fn record_gas_used(&mut self, gas: u64) { - if !self.frame_tracker.add_frame_persistent(gas) { - self.frame_tracker.add_tx_persistent(gas); - } - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox compute gas consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } -} - -impl TxRuntimeLimit for ComputeGasTracker { - /// Returns the current effective compute gas limit for the entire transaction (may be - /// detained/lowered by volatile data access). - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit().min(self.detained_limit) - } - - /// Returns the current total compute gas used across all frames. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - // Rex1+: reset detained limit to original TX limit between transactions. - // Pre-Rex1: the detained limit persists across transactions. - if self.rex1_enabled { - self.detained_limit = self.frame_tracker.tx_limit(); - } - } - - /// Returns whether the compute gas limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first (`frame_local`: true on exceed), then falls - /// through to the TX-level detained check. Gas detention is always TX-level (`frame_local`: - /// false) across all specs — accessing volatile data caps the whole transaction. - /// - /// Note: unlike state growth in Rex4+, we intentionally do NOT return early on - /// frame-within-limit. Compute gas has TX-scope components (e.g., pre-frame intrinsic compute - /// gas recorded in `tx_entry`) and TX-level detention (`detained_limit`) that can exceed even - /// when the current frame budget is still within limit. - #[inline] - fn check_limit(&self) -> LimitCheck { - if self.rex4_enabled { - let frame_check = self.frame_tracker.exceeds_current_frame_limit(LimitKind::ComputeGas); - if frame_check.exceeded_limit() { - return frame_check; - } - // Do not early-return on frame WithinLimit: - // 1) pre-frame intrinsic compute gas is recorded in `tx_entry`, outside current frame - // budget; - // 2) `detained_limit` can be lowered at runtime by volatile-data access. - // So TX-level detained check must still run even when frame check is within limit. - } - // TX-level detained check (all specs): total usage vs effective limit (min of tx/detained). - let limit = self.tx_limit(); - let used = self.tx_usage(); - if used > limit { - LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - frame_local: false, - limit, - used, - } - } else { - LimitCheck::WithinLimit - } - } - - #[inline] - fn push_empty_frame(&mut self) { - self.push_frame(); - } - - /// Push a new frame when a child call/create starts. - /// Compute gas does not need any data from the `frame_init` input. - #[inline] - fn before_frame_init>( - &mut self, - _frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - self.push_frame(); - Ok(()) - } - - /// Pop frame when returning. Since all gas is recorded as `persistent_usage`, - /// the SUCCESS flag has no effect (only `discardable_usage` and `refund` differ, - /// both are always 0 for compute gas). We use the actual result for convention. - #[inline] - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - self.frame_tracker.pop_frame(result.instruction_result().is_ok()); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Usage exactly equal to the detained limit must NOT count as a detained exceed: - /// the predicate is strictly-greater-than (`used > detained_limit`), not `>=`. - #[test] - fn test_is_detained_exceed_is_strict_at_boundary() { - // tx_limit = 100, detained lowered to 50 (< tx_limit, so detention is binding). - let mut tracker = ComputeGasTracker::new(MegaSpecId::MINI_REX, 100); - tracker.set_detained_limit(50); - - // Usage exactly at the detained limit: not exceeded. - tracker.record_gas_used(50); - assert!( - !tracker.is_detained_exceed(), - "usage == detained_limit must not be a detained exceed" - ); - - // One unit over the limit: exceeded. - tracker.record_gas_used(1); - assert!(tracker.is_detained_exceed(), "usage > detained_limit must be a detained exceed"); - } -} diff --git a/crates/mega-evm/src/limit/data_size.rs b/crates/mega-evm/src/limit/data_size.rs deleted file mode 100644 index ab3840004..000000000 --- a/crates/mega-evm/src/limit/data_size.rs +++ /dev/null @@ -1,406 +0,0 @@ -use alloy_primitives::{Address, U256}; -use revm::{ - context::{transaction::AuthorizationTr, Transaction}, - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, InterpreterAction, - SStoreResult, - }, -}; - -use super::frame_limit::CallFrameInfo; -use crate::{FrameLimitTracker, MegaSpecId, TxRuntimeLimit}; - -/// The number of bytes for the base transaction data. -pub const BASE_TX_SIZE: u64 = 110; -/// The number of bytes for the each EIP-7702 authorization. -pub const AUTHORIZATION_SIZE: u64 = 101; -/// The number of bytes for the each log topic. -pub const LOG_TOPIC_SIZE: u64 = 32; -/// The number of bytes for the salt key. -pub const SALT_KEY_SIZE: u64 = 8; -/// The number of bytes for the salt value delta of the account info. We assume the XOR delta -/// of address, nonce, and code hash is very small, so we can ignore them. The only significant -/// delta is the balance. We over-estimate it to 32 bytes. -pub const SALT_VALUE_DELTA_ACCOUNT_INFO_SIZE: u64 = 32; -/// The number of bytes for the salt value XOR delta of the storage slot. We over-estimate it to -/// 32 bytes. -pub const SALT_VALUE_DELTA_STORAGE_SLOT_SIZE: u64 = 32; -/// The originated data size for reading an account info. -pub const ACCOUNT_INFO_WRITE_SIZE: u64 = SALT_KEY_SIZE + SALT_VALUE_DELTA_ACCOUNT_INFO_SIZE; -/// The originated data size for writing a storage slot. -pub const STORAGE_SLOT_WRITE_SIZE: u64 = SALT_KEY_SIZE + SALT_VALUE_DELTA_STORAGE_SLOT_SIZE; -/// REX6+ per-log base overhead: one value unit (`LOG_TOPIC_SIZE`) for the address every receipt log -/// carries, so an empty `LOG0` is not free in the `data_size` lane. -pub const LOG_BASE_SIZE: u64 = 32; - -/// A tracker for the total data size (in bytes) generated from transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware tracking with per-frame budgets (Rex4+). -/// -/// In Rex4+, data size is enforced at the per-frame level: each inner call frame receives -/// `remaining * 98 / 100` of the parent's remaining data size budget. -/// When a frame exceeds its budget, it reverts (not halts) and its discardable data is dropped, -/// protecting the parent's budget. -/// In pre-Rex4, data size is enforced at the TX level only. -/// -/// ## Tracked Data Types -/// -/// **Non-discardable (permanent):** -/// - Transaction base data: 110 bytes -/// - Calldata: actual byte length -/// - Access lists: sum of access entry sizes -/// - EIP-7702 authorizations: 101 bytes per authorization -/// - Transaction caller account update: 40 bytes -/// - EIP-7702 authority account updates: 40 bytes each -/// -/// **Discardable (reverted on frame revert):** -/// - Log data: 32 bytes per topic + data length -/// - Storage writes: 40 bytes (only when original ≠ new value, refunded when reset to original) -/// - Account updates from calls/creates: 40 bytes each -/// - Contract code: actual deployed bytecode size -#[derive(Debug, Clone)] -pub(crate) struct DataSizeTracker { - rex4_enabled: bool, - rex5_enabled: bool, - rex6_enabled: bool, - frame_tracker: FrameLimitTracker, -} - -impl DataSizeTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - } - } - - /// Returns whether there is at least one active frame on the stack. - pub(crate) fn has_active_frame(&self) -> bool { - self.frame_tracker.has_active_frame() - } - - /// Records discardable data in the current frame. - fn record_discardable(&mut self, size: u64) { - self.frame_tracker.add_frame_discardable(size); - } - - /// Records discardable usage into the PARENT frame (one below the top). Used for a - /// child-CREATE's creator-side account-info write, whose on-chain effect (the creator - /// nonce bump) is undone only by the parent's revert, not the child's. - fn record_parent_discardable(&mut self, size: u64) { - self.frame_tracker.add_parent_discardable(size); - } - - /// Records a refund (negative data) in the current frame. - fn record_refund(&mut self, size: u64) { - self.frame_tracker.add_frame_refund(size); - } - - /// REX5+: meter an oracle-hint payload against the TX intrinsic data-size lane. - /// - /// Hints are a TX-scoped side-channel into the off-chain oracle backend. They do not - /// belong to any call frame (the inner Oracle frame may revert, but the hint has already - /// flowed out), so we record into `tx_entry.persistent_usage` — the same lane as calldata - /// — rather than the current frame's discardable usage. - pub(crate) fn record_oracle_hint_bytes(&mut self, len: u64) { - self.frame_tracker.add_tx_persistent(len); - } - - /// Records an account info write (40 bytes) as discardable data in the current frame. - /// - /// Used by SELFDESTRUCT beneficiary metering (REX5+) to charge data size for - /// creating a new beneficiary account. - pub(crate) fn record_account_write(&mut self) { - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Records an account info write (40 bytes) as TX-level persistent (non-discardable) data. - /// - /// Used by the REX6 EIP-7702 authorization scan, which runs in `validate` before any frame - /// exists, so the charge cannot go through the frame-scoped `record_account_write`. - pub(crate) fn record_persistent_account_write(&mut self) { - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox data size consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining data size budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for DataSizeTracker { - /// Returns the current effective data size limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current total data size across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the data size limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic overflow when no frame exists yet - /// (intrinsic usage is recorded in `tx_entry` before the first frame is pushed). - /// In pre-Rex4, checks total data size across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.rex4_enabled { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::DataSize); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: defense-in-depth safety net. - // In Rex4+ during execution, per-frame budgets are derived from remaining TX - // budget, so this should only exceed when no frame exists (intrinsic overflow). - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - // Defense-in-depth: pre-REX5, the only mid-execution writer to `tx_entry` is - // `before_tx_start` (which runs before any frame is pushed), so a TX-level - // exceed with an active frame indicates a budget-accounting bug. REX5+ adds - // `record_oracle_hint_bytes` which legitimately writes to `tx_entry` mid- - // execution to meter oracle-hint payloads as TX-scoped side-channel cost, so - // the invariant is only asserted on pre-REX5 specs. - debug_assert!( - !self.rex4_enabled || self.rex5_enabled || !self.frame_tracker.has_active_frame(), - "DataSize TX-level exceeded with active frame — budget invariant violated" - ); - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::DataSize, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// Records the data size of a transaction at the start of execution. - /// - /// This includes: - /// - 110 bytes base transaction data - /// - Calldata byte length - /// - Access list sizes - /// - EIP-7702 authorizations (101 bytes each) + authority account updates (40 bytes each) - /// - Caller account update (40 bytes) - /// - /// All recorded as pre-frame (non-discardable) since no frame exists yet. - fn before_tx_start(&mut self, tx: &crate::MegaTransaction) { - // TX intrinsic data (non-discardable, recorded before any frame is pushed) - let mut size = BASE_TX_SIZE; - size += tx.input().len() as u64; - size += tx - .access_list() - .map(|item| item.map(|access| access.size() as u64).sum::()) - .unwrap_or_default(); - size += tx.authorization_list_len() as u64 * AUTHORIZATION_SIZE; - self.frame_tracker.add_tx_persistent(size); - - // EIP-7702 authority account updates (non-discardable). - // - // Pre-REX6: charged here for every authorization with a recoverable authority, even ones - // that fail the chain-id / nonce / code application gates and never write the account. - // REX6+ moves this charge into the journal-aware authorization scan in `validate` so only - // *applied* authorities are charged; skip it here. - if !self.rex6_enabled { - for authorization in tx.authorization_list() { - if authorization.authority().is_some() { - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - - // Caller account update (non-discardable) - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Called when inspector intercepts and skips a call/create. - /// - /// Pushes an empty frame so `before_frame_return_result` can pop it to keep - /// the frame stack aligned with the EVM's call stack. - #[inline] - fn push_empty_frame(&mut self) { - self.frame_tracker.push_dummy_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Pushes a new frame and records account info updates: - /// - **Call with value transfer**: Updates parent's account info if not yet marked, then - /// records target account info update (40 bytes each). - /// - **Create**: Updates parent's account info if not yet marked (caller nonce increment). - /// Created address is set later in `after_frame_init_on_frame`. - /// - **Call without transfer**: No account info updates. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - let has_transfer = call_inputs.transfers_value(); - let parent_needs_update = - self.frame_tracker.push_call_frame(call_inputs.target_address, has_transfer); - if has_transfer { - if parent_needs_update { - // Parent's account info update goes to child's discardable. - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - // A value transfer to the caller itself touches a single account, already - // accounted by the caller-side write above (or, at the top level, by the - // `before_tx_start` caller record). Recording the target side again would - // double-count that one account, so skip it under REX6. - if !(self.rex6_enabled && call_inputs.target_address == call_inputs.caller) { - // Record target account info update in child's discardable. - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - FrameInput::Create(_) => { - let parent_needs_update = self.frame_tracker.push_create_frame(); - if parent_needs_update { - if self.rex6_enabled { - // The creator's nonce bump survives the child's revert (revm bumps it - // before the create checkpoint), so charge it to the parent frame — - // see `FrameLimitTracker::add_parent_discardable`. - self.record_parent_discardable(ACCOUNT_INFO_WRITE_SIZE); - } else { - // Pre-REX6: the creator nonce-bump charge is bundled into the child frame's - // discardable lane (frozen behavior). - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a new execution frame is successfully initialized. - /// - /// For CREATE frames, records the created address and its account info update (40 bytes). - fn after_frame_init_on_frame(&mut self, frame: &EthFrame) { - if frame.data.is_create() { - let created_address = - frame.data.created_address().expect("created address is none for create frame"); - self.frame_tracker.set_created_address(created_address); - // Record account info update for created address - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - - /// Hook called after a frame finishes running. - /// - /// For CREATE frames, records the deployed contract bytecode size as discardable data. - fn after_frame_run<'a>( - &mut self, - frame: &'a EthFrame, - action: &'a mut InterpreterAction, - ) { - if let InterpreterAction::Return(interpreter_result) = action { - if frame.data.is_create() { - let code_size = interpreter_result.output.len() as u64; - self.record_discardable(code_size); - } - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Pops the current frame from the tracker: - /// - **On success**: merges the frame's data into the parent frame. - /// - **On revert/failure**: discards the frame's discardable data. - /// - /// Rex5+: if the reverting child had set the parent's account-update flag, the flag - /// is reset so the next successful call from the same parent still charges the parent - /// account (avoiding undercounting after a revert-then-retry pattern). The unwind is - /// owned by `FrameLimitTracker::pop_frame_unwind_parent`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - let is_success = result.instruction_result().is_ok(); - self.frame_tracker.pop_frame_unwind_parent(is_success); - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// Records SSTORE data based on the storage slot's state transition: - /// - /// | Original == Present | Original == New | Effect | Reason | - /// |---------------------|-----------------|------------------------|-------------------------| - /// | yes | yes | — | No change | - /// | yes | no | +40 bytes (discardable)| First write to slot | - /// | no | yes | -40 bytes (refund) | Reset to original value | - /// | no | no | — | Rewrite, no new data | - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - if store_result.is_original_eq_present() { - if !store_result.is_original_eq_new() { - // First write to slot: original == present, but new differs - self.record_discardable(STORAGE_SLOT_WRITE_SIZE); - } - } else if store_result.is_original_eq_new() { - // Reset to original: refund - self.record_refund(STORAGE_SLOT_WRITE_SIZE); - } - } - - /// Hook called when a log is emitted. - /// - /// Records `LOG_BASE_SIZE` (REX6+ only) + `num_topics * 32` + `data_size` as discardable. - fn after_log(&mut self, num_topics: u64, data_size: u64) { - let base = if self.rex6_enabled { LOG_BASE_SIZE } else { 0 }; - let size = base + num_topics * LOG_TOPIC_SIZE + data_size; - self.record_discardable(size); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The originated data-size constants are *sums* of their salt key/value components, - /// not products. Pin the values against independent literals so an arithmetic slip - /// (e.g. `+` -> `*`) is caught (8 + 32 = 40, not 8 * 32 = 256). - #[test] - fn test_originated_data_size_constants() { - assert_eq!(STORAGE_SLOT_WRITE_SIZE, 40); - assert_eq!(ACCOUNT_INFO_WRITE_SIZE, 40); - } - - /// `has_active_frame` must reflect the underlying frame stack, not a constant. - #[test] - fn test_has_active_frame_reflects_frame_stack() { - let mut tracker = DataSizeTracker::new(MegaSpecId::MINI_REX, u64::MAX); - assert!(!tracker.has_active_frame(), "no frame pushed yet"); - tracker.push_empty_frame(); - assert!(tracker.has_active_frame(), "a frame is on the stack"); - } -} diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs deleted file mode 100644 index 6ff0b5df1..000000000 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ /dev/null @@ -1,648 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use alloy_primitives::{Address, U256}; -use revm::{ - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, InterpreterAction, SStoreResult, - }, -}; -use std::vec::Vec; - -use crate::{constants, JournalInspectTr, MegaSpecId, MegaTransaction}; - -use super::{LimitCheck, LimitKind}; - -/// Per-frame metadata for trackers that need account update deduplication -/// (data size and KV update trackers). -/// -/// All fields are private to this module: the -/// `push_call_frame` / `push_create_frame` / `pop_frame_unwind_parent` methods on -/// `FrameLimitTracker` own the invariant that wires `target_updated` and -/// `charged_parent_update` together. Callers should not touch these fields directly. -#[derive(Debug, Clone, Default)] -pub(crate) struct CallFrameInfo { - /// The target address of the frame. `None` during CREATE until the address is known. - target_address: Option
, - /// Whether this frame's target address has been marked as updated. - target_updated: bool, - /// True when this frame caused the parent's `target_updated` to be flipped to `true` - /// (Rex5+ only). Used by `pop_frame_unwind_parent` to undo the parent flag on revert, - /// so a subsequent successful call from the same parent still charges the parent account. - charged_parent_update: bool, -} - -#[derive(Debug, Clone)] -pub(crate) struct FrameLimitTracker { - /// Top-level (TX-scope) entry. Holds the TX limit and accumulates usage - /// from pre-frame data and from the last frame pop. - tx_entry: FrameLimitEntry<()>, - /// Stack of child frame entries. - frame_stack: Vec>, - /// Whether Rex4 (per-frame budgeting) is active. Used by the `CallFrameInfo` - /// specialization to choose between `push_frame` (Rex4+) and `push_frame_with_limit` - /// (`u64::MAX` for pre-Rex4) when constructing call/create/intercept frames. - /// Other instantiations (`FrameLimitTracker<()>`) currently do not consult this flag. - rex4_enabled: bool, - /// Whether Rex5 (parent account update dedup) is active. Used by the `CallFrameInfo` - /// specialization to gate the `target_updated` mutation in `push_call_frame` / - /// `push_create_frame` and the matching unwind in `pop_frame_unwind_parent`. - /// Other instantiations do not consult this flag. - rex5_enabled: bool, - /// Whether Rex6 is active. Used by the `CallFrameInfo` specialization: a CREATE's - /// creator-side charge survives the child's revert (revm bumps the creator nonce before the - /// create checkpoint), so under Rex6 `push_create_frame` does not arm the - /// `charged_parent_update` unwind — a reverted-then-retried CREATE must not charge the - /// creator account update twice. Rex5 keeps the (over-unwinding) frozen behavior. - rex6_enabled: bool, - - /// Cached `Σ(persistent_usage + discardable_usage)` across `tx_entry` and every entry on - /// `frame_stack`. Maintained incrementally so `net_usage()` is O(1) instead of O(depth) - /// per opcode. See `net_usage()` for the invariant and `pop_frame` for the revert delta. - cached_total_used: u64, - /// Cached `Σ refund` across `tx_entry` and every entry on `frame_stack`. Maintained - /// together with `cached_total_used` so `net_usage = saturating_sub(used, refund)` is - /// a single subtraction. - cached_total_refund: u64, -} - -/// Per-frame budget entry on the frame stack. -#[derive(Debug, Clone)] -pub(crate) struct FrameLimitEntry { - /// Maximum usage allowed in this frame. - pub(crate) limit: u64, - - // The three budget fields below MUST only be mutated through `FrameLimitTracker`'s - // cache-aware helpers (`add_tx_persistent`, `add_frame_persistent`, - // `add_frame_discardable`, `add_frame_refund`) or through `pop_frame`'s explicit - // cache deltas. Writing them directly desyncs `cached_total_used` / - // `cached_total_refund` and silently corrupts every subsequent `net_usage()` result. - /// Persistent usage in this frame even if it is reverted. - persistent_usage: u64, - /// Discardable usage if this frame is reverted. - discardable_usage: u64, - /// Refund usage in this frame. - refund: u64, - - /// Additional information about the frame. - #[allow(dead_code)] - pub(crate) info: I, -} - -impl FrameLimitEntry { - pub(crate) fn new(limit: u64, info: I) -> Self { - Self { limit, persistent_usage: 0, discardable_usage: 0, refund: 0, info } - } - - /// Returns the remaining budget for this frame. - /// - /// Computed as `limit - (used - refund)`, clamped to `[0, limit]`. - /// The net usage (`used - refund`) is computed first to stay consistent with - /// the exceed check in `exceeds_current_frame_limit`. - #[inline] - pub(crate) fn remaining(&self) -> u64 { - self.limit.saturating_sub(self.used().saturating_sub(self.refund)) - } - - /// Returns usage for this frame. - #[inline] - pub(crate) fn used(&self) -> u64 { - self.persistent_usage.checked_add(self.discardable_usage).expect("overflow") - } -} - -impl FrameLimitTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - tx_entry: FrameLimitEntry::new(tx_limit, ()), - frame_stack: Vec::new(), - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - cached_total_used: 0, - cached_total_refund: 0, - } - } - - /// Returns the TX-level limit. - pub(crate) fn tx_limit(&self) -> u64 { - self.tx_entry.limit - } - - /// Resets the tracker for a new transaction. - pub(crate) fn reset(&mut self) { - self.tx_entry.persistent_usage = 0; - self.tx_entry.discardable_usage = 0; - self.tx_entry.refund = 0; - self.frame_stack.clear(); - self.cached_total_used = 0; - self.cached_total_refund = 0; - } - - /// Returns the remaining budget of the current frame. - /// - /// If the frame stack is non-empty, returns the top frame's remaining budget. - /// If the frame stack is empty (before the first frame is pushed), returns - /// the TX-level remaining which accounts for pre-frame usage (e.g. intrinsic charges). - pub(crate) fn current_frame_remaining(&self) -> u64 { - match self.frame_stack.last() { - Some(entry) => entry.remaining(), - None => self.tx_entry.remaining(), - } - } - - /// Returns the maximum limit that can be forwarded to the next frame. - /// - /// - **Nested frame**: parent's remaining × 98/100. - /// - **Top-level frame** (empty stack): `tx_entry.remaining()`, which accounts for pre-frame - /// intrinsic usage (e.g., calldata size, access lists) already charged into `tx_entry`. - /// - /// Individual trackers that need a different top-level budget should use - /// `push_frame_with_limit()` instead of `push_frame()`. - fn max_forward_limit(&self) -> u64 { - match self.frame_stack.last() { - Some(entry) => { - let remaining = u128::from(entry.remaining()); - let numerator = u128::from(constants::rex4::FRAME_LIMIT_NUMERATOR); - let denominator = u128::from(constants::rex4::FRAME_LIMIT_DENOMINATOR); - ((remaining * numerator) / denominator) as u64 - } - None => self.tx_entry.remaining(), - } - } - - pub(crate) fn push_frame(&mut self, info: I) { - self.frame_stack.push(FrameLimitEntry::new(self.max_forward_limit(), info)); - } - - /// Pops the current frame from the stack and merges its usage into the parent. - /// - /// On success: `persistent_usage`, `discardable_usage`, and `refund` are all merged. - /// On failure: only `persistent_usage` is merged; `discardable_usage` and `refund` are dropped. - /// - /// Cache invariant: every mutation to `persistent_usage` / `discardable_usage` / `refund` - /// — whether via the public helpers or via this pop — keeps `cached_total_used` and - /// `cached_total_refund` in sync. On revert the child's `discardable_usage` and `refund` - /// are subtracted from the cache because they vanish (they are neither kept on the child - /// nor merged into the parent). - pub(crate) fn pop_frame(&mut self, success: bool) -> Option> { - let child = self.frame_stack.pop(); - if let Some(child) = &child { - if let Some(parent) = self.frame_stack.last_mut() { - // Persistent usage is always preserved: move from child slot to parent slot. - // The cache already counts it once, so no cache update is needed here. - parent.persistent_usage += child.persistent_usage; - if success { - // Discardable & refund are preserved on success — same total, just relocated - // from child entry to parent entry. Cache stays the same. - parent.discardable_usage += child.discardable_usage; - parent.refund += child.refund; - } else { - // Revert: child's discardable_usage and refund vanish entirely. Subtract them - // from the cache to maintain the `Σ(persistent + discardable) - Σ refund` - // invariant. - self.cached_total_used -= child.discardable_usage; - self.cached_total_refund -= child.refund; - } - } else { - // Last frame popped — merge into tx_entry. Same cache reasoning as the parent - // branch above. - self.tx_entry.persistent_usage += child.persistent_usage; - if success { - self.tx_entry.discardable_usage += child.discardable_usage; - self.tx_entry.refund += child.refund; - } else { - self.cached_total_used -= child.discardable_usage; - self.cached_total_refund -= child.refund; - } - } - } - child - } - - /// Returns whether the current frame has exceeded its frame-local limit. - /// If exceeded, `frame_local` is always `true` since this checks per-frame budgets. - pub(crate) fn exceeds_current_frame_limit(&self, kind: LimitKind) -> LimitCheck { - match self.frame_stack.last() { - Some(entry) if entry.used().saturating_sub(entry.refund) > entry.limit => { - LimitCheck::ExceedsLimit { - kind, - limit: entry.limit, - used: entry.used(), - frame_local: true, - } - } - _ => LimitCheck::WithinLimit, - } - } - - /// Returns a mutable reference to the current (top) frame entry. - pub(crate) fn frame_mut(&mut self) -> Option<&mut FrameLimitEntry> { - self.frame_stack.last_mut() - } - - /// Returns whether there is at least one active frame on the stack. - pub(crate) fn has_active_frame(&self) -> bool { - !self.frame_stack.is_empty() - } - - /// Pushes a new frame with a custom limit, bypassing `max_forward_limit()`. - /// - /// Used by pre-Rex4 specs (`u64::MAX`, per-frame limits not enforced) and by any tracker that - /// intentionally wants to bypass the default `max_forward_limit()` behavior. - pub(crate) fn push_frame_with_limit(&mut self, limit: u64, info: I) { - self.frame_stack.push(FrameLimitEntry::new(limit, info)); - } - - /// Returns the total net usage across `tx_entry` and all frames on the stack. - /// Net usage = Σ(`persistent_usage` + `discardable_usage`) - Σ(refund), clamped to 0. - /// - /// O(1): served from `cached_total_used` / `cached_total_refund`, which are maintained - /// incrementally by `add_tx_persistent`, `add_frame_persistent`, `add_frame_discardable`, - /// `add_frame_refund`, and `pop_frame`. - #[inline] - pub(crate) fn net_usage(&self) -> u64 { - let net_usage = self.cached_total_used.saturating_sub(self.cached_total_refund); - #[cfg(debug_assertions)] - assert_eq!( - net_usage, - self.net_usage_uncached(), - "cached net_usage must match uncached reference" - ); - net_usage - } - - /// Reference implementation of `net_usage` that walks `tx_entry + frame_stack` directly. - /// Active only in debug builds (gated by `cfg(debug_assertions)`), where it backs the - /// per-call assertion inside `net_usage()` so the incremental cache is verified against - /// the slow O(depth) walk on every opcode in tests and dev runs. Release builds - /// (including `cargo bench` and production) compile this out entirely. - #[cfg(any(debug_assertions, test))] - fn net_usage_uncached(&self) -> u64 { - let mut total_used: u64 = self.tx_entry.used(); - let mut total_refund: u64 = self.tx_entry.refund; - for entry in &self.frame_stack { - total_used += entry.used(); - total_refund += entry.refund; - } - total_used.saturating_sub(total_refund) - } - - /// Adds `n` to `tx_entry.persistent_usage` and keeps the cache in sync. - /// - /// Used by trackers to record intrinsic / pre-frame usage (e.g. base TX size, - /// EIP-7702 authority updates, caller account update). The current frame stack - /// may be empty (pre-`frame_init`) or non-empty (`compute_gas`'s fallback when no - /// frame exists). - #[inline] - pub(crate) fn add_tx_persistent(&mut self, n: u64) { - self.tx_entry.persistent_usage += n; - self.cached_total_used += n; - } - - /// Adds `n` to the current top frame's `persistent_usage` and keeps the cache in sync. - /// Returns `false` (and does nothing) when the frame stack is empty — callers that - /// need a tx-level fallback must check the return value. - #[inline] - pub(crate) fn add_frame_persistent(&mut self, n: u64) -> bool { - match self.frame_stack.last_mut() { - Some(entry) => { - entry.persistent_usage += n; - self.cached_total_used += n; - true - } - None => false, - } - } - - /// Adds `n` to the current top frame's `discardable_usage` and keeps the cache in sync. - /// No-op when the frame stack is empty (discardable usage requires a frame to be - /// discardable into; pre-frame usage is always persistent). - #[inline] - pub(crate) fn add_frame_discardable(&mut self, n: u64) { - if let Some(entry) = self.frame_stack.last_mut() { - entry.discardable_usage += n; - self.cached_total_used += n; - } - } - - /// Adds `n` to the current top frame's `refund` and keeps the cache in sync. - /// No-op when the frame stack is empty. - #[inline] - pub(crate) fn add_frame_refund(&mut self, n: u64) { - if let Some(entry) = self.frame_stack.last_mut() { - entry.refund += n; - self.cached_total_refund += n; - } - } - - /// Adds `n` to the parent frame's `discardable_usage` (the frame directly beneath the - /// current top) and keeps the cache in sync. No-op when the current frame is top-level. - /// - /// Used by REX6 CREATE accounting to charge the creator's nonce-bump account-info write to - /// the parent (creator) frame instead of the child (created) frame. revm increments the - /// creator's nonce *before* it takes the create checkpoint, so the nonce bump survives the - /// created contract's revert and is undone only if the creator's own frame reverts. - /// Recording the charge on the parent's discardable lane matches that lifetime: it is kept - /// when the child reverts and dropped only with the parent. - /// - /// This is the opposite of a value-transferring CALL, whose balance moves *are* rolled back - /// when the callee reverts — those are correctly charged to the child's discardable lane. - #[inline] - pub(crate) fn add_parent_discardable(&mut self, n: u64) { - if let Some((_current, below)) = self.frame_stack.split_last_mut() { - if let Some(parent) = below.last_mut() { - parent.discardable_usage += n; - self.cached_total_used += n; - } - } - } -} - -impl FrameLimitTracker { - /// Pushes a new `CallFrameInfo` frame using the per-spec budget choice: - /// - **Rex4+**: `max_forward_limit()` (parent × 98/100, or `tx_entry.remaining()` at top - /// level). - /// - **Pre-Rex4**: `u64::MAX` since per-frame limits are not enforced. - fn push_call_frame_info(&mut self, info: CallFrameInfo) { - if self.rex4_enabled { - self.push_frame(info); - } else { - self.push_frame_with_limit(u64::MAX, info); - } - } - - /// Pushes a synthetic frame for inspector / access-control interception paths. - /// - /// No parent-flag mutation: an intercepted call is short-circuited before any - /// state-modifying account update is recorded, so the parent does not need to be marked. - /// The frame exists only to keep the per-tracker frame stack aligned with the EVM's call - /// stack so that the matching `pop_frame_unwind_parent` finds an entry to pop. - pub(crate) fn push_dummy_frame(&mut self) { - self.push_call_frame_info(CallFrameInfo::default()); - } - - /// Pushes a CALL frame and updates the parent's dedup flag. - /// - /// Returns `true` when the parent's account info should be charged by the caller - /// (i.e., the parent has not been marked updated yet *and* this call transfers value). - /// Rex5+: the parent's `target_updated` flag is set so subsequent value-transferring - /// calls from the same parent frame don't double-charge the caller account; the - /// `charged_parent_update` flag is recorded on the new child so a revert can unwind it. - /// Pre-Rex5: the parent flag is left untouched, preserving pre-Rex5 semantics. - pub(crate) fn push_call_frame(&mut self, target: Address, has_transfer: bool) -> bool { - let rex5_enabled = self.rex5_enabled; - let parent_needs_update = has_transfer && - match self.frame_mut() { - Some(entry) if !entry.info.target_updated => { - if rex5_enabled { - entry.info.target_updated = true; - } - true - } - _ => false, - }; - let charged_parent_update = rex5_enabled && parent_needs_update; - self.push_call_frame_info(CallFrameInfo { - target_address: Some(target), - target_updated: has_transfer, - charged_parent_update, - }); - parent_needs_update - } - - /// Pushes a CREATE frame and updates the parent's dedup flag. - /// - /// Returns `true` when the parent's account info should be charged by the caller - /// (i.e., the parent has not been marked updated yet — CREATE always increments the - /// caller's nonce, so there is no `has_transfer` gate). - /// The created address is unknown at push time; callers should fill it in via - /// `set_created_address` once `frame_init` completes. - /// Rex5+ deduplication semantics match `push_call_frame`. - pub(crate) fn push_create_frame(&mut self) -> bool { - let rex5_enabled = self.rex5_enabled; - let parent_needs_update = match self.frame_mut() { - Some(entry) if !entry.info.target_updated => { - if rex5_enabled { - entry.info.target_updated = true; - } - true - } - _ => false, - }; - // Rex6: the creator's nonce bump survives the child CREATE's revert, and its charge - // lives on the parent's discardable lane — do not arm the unwind, or a - // revert-then-retry CREATE re-charges the same creator account update. Rex5 keeps the - // frozen unwind (its charge lived on the child lane and was dropped with it). - let charged_parent_update = rex5_enabled && parent_needs_update && !self.rex6_enabled; - self.push_call_frame_info(CallFrameInfo { - target_address: None, - target_updated: true, - charged_parent_update, - }); - parent_needs_update - } - - /// Records the created address on the current CREATE frame. - /// - /// Asserts that the current frame's `target_address` has not already been set, - /// matching the previous inline behavior. Does nothing if the frame stack is empty. - pub(crate) fn set_created_address(&mut self, addr: Address) { - if let Some(entry) = self.frame_mut() { - assert!(entry.info.target_address.is_none(), "created account already recorded"); - entry.info.target_address = Some(addr); - } - } - - /// Pops the current frame and, on revert, unwinds the parent's `target_updated` flag - /// if this child set it. - /// - /// Rex5+ only: when the reverting child had `charged_parent_update` set, the parent's - /// `target_updated` is reset so the next successful call from the same parent still - /// charges the parent account (avoiding undercounting after a revert-then-retry pattern). - /// Pre-Rex5 child frames have `charged_parent_update = false`, so this method behaves - /// identically to `pop_frame` for older specs. - pub(crate) fn pop_frame_unwind_parent(&mut self, success: bool) { - let child = self.pop_frame(success); - if !success { - if let Some(child_entry) = child { - if child_entry.info.charged_parent_update { - // charged_parent_update=true implies a parent frame exists - // (the flag is only set when frame_mut() returned Some). - self.frame_mut() - .expect("parent frame must exist when charged_parent_update is true") - .info - .target_updated = false; - } - } - } - } -} - -pub(crate) trait TxRuntimeLimit { - fn tx_limit(&self) -> u64; - fn tx_usage(&self) -> u64; - fn reset(&mut self); - fn check_limit(&self) -> LimitCheck; - - #[inline] - fn before_tx_start(&mut self, _tx: &MegaTransaction) {} - #[inline] - fn push_empty_frame(&mut self) {} - #[inline] - fn before_frame_init>( - &mut self, - _frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - Ok(()) - } - #[inline] - fn after_frame_init_on_frame(&mut self, _frame: &EthFrame) {} - #[inline] - fn before_frame_run(&mut self, _frame: &EthFrame) {} - #[inline] - fn after_frame_run<'a>( - &mut self, - _frame: &'a EthFrame, - _action: &'a mut InterpreterAction, - ) { - } - #[inline] - fn before_frame_return_result(&mut self, _result: &FrameResult) {} - #[inline] - fn after_sstore( - &mut self, - _target_address: Address, - _slot: U256, - _store_result: &SStoreResult, - ) { - } - fn after_log(&mut self, _num_topics: u64, _data_size: u64) {} - #[inline] - fn after_selfdestruct(&mut self, _refund: u64) {} -} - -#[cfg(test)] -mod tests { - use alloy_primitives::address; - - use super::*; - - const ADDR: Address = address!("0000000000000000000000000000000000001234"); - - /// `set_created_address` on an empty frame stack must be a no-op. - #[test] - fn test_set_created_address_empty_stack_is_noop() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - // No frame on the stack — should not panic, just do nothing. - t.set_created_address(ADDR); - } - - /// `set_created_address` panics when called twice on the same CREATE frame - /// (invariant: `target_address` must be `None` when first filled in). - #[test] - #[should_panic(expected = "created account already recorded")] - fn test_set_created_address_duplicate_panics() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_create_frame(); - t.set_created_address(ADDR); - t.set_created_address(ADDR); // second call must panic - } - - /// Drives `FrameLimitTracker` through a representative sequence of pushes, mutations, - /// and pops (both success and revert) and asserts that the cached `net_usage()` stays - /// in sync with the uncached reference walk after every step. This is the load-bearing - /// guarantee of the cache-based refactor: any future change that introduces a new - /// mutation site without going through a helper will break this test. - #[test] - fn test_net_usage_cache_matches_uncached() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); - - // Pre-frame intrinsic usage goes to tx_entry. - t.add_tx_persistent(100); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // add_frame_persistent on empty stack must be a no-op and return false. - assert!(!t.add_frame_persistent(50)); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // add_frame_discardable / add_frame_refund are no-ops on empty stack. - t.add_frame_discardable(50); - t.add_frame_refund(50); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 100); - - // Push frame 1 and mix in persistent/discardable/refund. - t.push_frame(()); - assert!(t.add_frame_persistent(20)); - t.add_frame_discardable(30); - t.add_frame_refund(10); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 2 (nested) and mutate. - t.push_frame(()); - assert!(t.add_frame_persistent(7)); - t.add_frame_discardable(15); - t.add_frame_refund(3); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 3 (deeper) and revert it — discardable & refund must vanish from cache, - // persistent must merge into the parent (frame 2). - t.push_frame(()); - assert!(t.add_frame_persistent(5)); - t.add_frame_discardable(11); - t.add_frame_refund(2); - let before_revert = t.net_usage(); - let popped = t.pop_frame(false).expect("frame 3 popped"); - assert_eq!(popped.discardable_usage, 11); - assert_eq!(popped.refund, 2); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // After revert: cache should drop the child's discardable (11) and refund (2), - // so net_usage changes by -(11) + 2 = -9 vs before. - assert_eq!(t.net_usage(), before_revert - 9); - - // Push frame 3 again and pop it successfully — discardable/refund merge into parent, - // cache is unchanged by the pop itself (totals are invariant under transfer). - t.push_frame(()); - assert!(t.add_frame_persistent(4)); - t.add_frame_discardable(6); - t.add_frame_refund(1); - let before_success = t.net_usage(); - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), before_success); - - // Pop frame 2 with success → merge into frame 1. - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Pop the last frame (frame 1) with revert → discardable/refund vanish, persistent - // merges into tx_entry. - let before_last_revert = t.net_usage(); - let frame_1 = t.pop_frame(false).expect("frame 1 popped"); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // The popped frame's discardable/refund leave the cache. - assert_eq!(t.net_usage(), before_last_revert - frame_1.discardable_usage + frame_1.refund); - - // Reset returns the cache to zero in sync with the entries. - t.reset(); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); - } - - /// Verifies that a refund exceeding the cumulative usage clamps `net_usage()` to 0, - /// matching the saturating semantics of the uncached reference. This guards against - /// signed-style accounting bugs where refunds outrun used and an unsigned subtraction - /// would otherwise wrap. - #[test] - fn test_net_usage_saturates_when_refund_exceeds_used() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_frame(()); - t.add_frame_discardable(10); - t.add_frame_refund(100); - assert_eq!(t.net_usage(), 0); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - } -} diff --git a/crates/mega-evm/src/limit/kv_update.rs b/crates/mega-evm/src/limit/kv_update.rs deleted file mode 100644 index 6b2615cdb..000000000 --- a/crates/mega-evm/src/limit/kv_update.rs +++ /dev/null @@ -1,298 +0,0 @@ -use alloy_primitives::{Address, U256}; -use revm::{ - context::{transaction::AuthorizationTr, Transaction}, - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, SStoreResult, - }, -}; - -use super::frame_limit::{CallFrameInfo, FrameLimitTracker, TxRuntimeLimit}; -use crate::{MegaSpecId, MegaTransaction}; - -/// A counter for tracking key-value storage operations during transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware counting. -/// -/// In Rex4+, KV updates are enforced at the per-frame level: each inner call frame receives -/// `remaining * 98 / 100` of the parent's remaining KV update budget. -/// When a frame exceeds its budget, it reverts (not halts) and its discardable KV updates are -/// dropped, protecting the parent's budget. -/// In pre-Rex4, KV updates are enforced at the TX level only. -/// Units are 1 per KV operation (not bytes). -/// -/// ## Tracked Operations -/// -/// **Non-discardable (permanent):** -/// - Transaction caller account update: 1 KV update -/// - EIP-7702 authority account updates: 1 KV update each -/// -/// **Discardable (reverted on frame revert):** -/// - Storage writes: 1 KV update (only when original ≠ new value, refunded when reset to original) -/// - Account updates from CREATE: 1 KV update for created account -/// - Account updates from CALL with transfer: 2 KV updates (caller + callee) -#[derive(Debug, Clone)] -pub(crate) struct KVUpdateTracker { - rex4_enabled: bool, - rex6_enabled: bool, - frame_tracker: FrameLimitTracker, -} - -impl KVUpdateTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - } - } - - /// Records a discardable KV update in the current frame. - fn record_discardable(&mut self, n: u64) { - self.frame_tracker.add_frame_discardable(n); - } - - /// Records discardable usage into the PARENT frame (one below the top). Used for a - /// child-CREATE's creator-side account-info write, whose on-chain effect (the creator - /// nonce bump) is undone only by the parent's revert, not the child's. - fn record_parent_discardable(&mut self, n: u64) { - self.frame_tracker.add_parent_discardable(n); - } - - /// Records a KV update refund in the current frame. - fn record_refund(&mut self, n: u64) { - self.frame_tracker.add_frame_refund(n); - } - - /// Records a single account update as discardable KV update in the current frame. - /// - /// Used by SELFDESTRUCT beneficiary metering (REX5+) to charge a KV update for - /// creating a new beneficiary account. - pub(crate) fn record_account_update(&mut self) { - self.record_discardable(1); - } - - /// Records a single account update as TX-level persistent (non-discardable) KV usage. - /// - /// Used by the REX6 EIP-7702 authorization scan, which runs in `validate` before any frame - /// exists, so the charge cannot go through the frame-scoped `record_account_update`. - pub(crate) fn record_persistent_account_update(&mut self) { - self.frame_tracker.add_tx_persistent(1); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox KV update consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining KV update budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for KVUpdateTracker { - /// Returns the current effective KV update limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current total KV update count across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the KV update limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic overflow when no frame exists yet - /// (intrinsic usage is recorded in `tx_entry` before the first frame is pushed). - /// In pre-Rex4, checks total KV updates across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.rex4_enabled { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::KVUpdate); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: defense-in-depth safety net. - // In Rex4+ during execution, per-frame budgets are derived from remaining TX - // budget, so this should only exceed when no frame exists (intrinsic overflow). - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - debug_assert!( - !self.rex4_enabled || !self.frame_tracker.has_active_frame(), - "KVUpdate TX-level exceeded with active frame — budget invariant violated" - ); - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::KVUpdate, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// Records the KV updates at the start of a transaction. - /// - /// This includes: - /// - EIP-7702 authority account updates (1 each) - /// - Caller account update (1) - /// - /// All recorded as pre-frame (non-discardable) since no frame exists yet. - fn before_tx_start(&mut self, tx: &MegaTransaction) { - // EIP-7702 authority account updates (non-discardable). - // - // Pre-REX6: charged here for every recoverable authority, including ones that fail the - // application gates. REX6+ moves this into the journal-aware authorization scan in - // `validate` so only *applied* authorities are charged; skip here. - if !self.rex6_enabled { - for authorization in tx.authorization_list() { - if authorization.authority().is_some() { - self.frame_tracker.add_tx_persistent(1); - } - } - } - - // Caller account update (non-discardable) - self.frame_tracker.add_tx_persistent(1); - } - - #[inline] - fn push_empty_frame(&mut self) { - self.frame_tracker.push_dummy_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Records KV updates for account info changes: - /// - **Call with value transfer**: Parent account update (1, if not yet marked) + target - /// account update (1). - /// - **Create**: Parent account update (1, if not yet marked). Created address is set later in - /// `after_frame_init_on_frame`. - /// - **Call without transfer**: No KV updates. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - let has_transfer = call_inputs.transfers_value(); - let parent_needs_update = - self.frame_tracker.push_call_frame(call_inputs.target_address, has_transfer); - if has_transfer { - if parent_needs_update { - // Parent's account info update goes to child's discardable. - self.record_discardable(1); - } - // A value transfer to the caller itself touches a single account, already - // accounted by the caller-side write above (or, at the top level, by the - // transaction-start caller record). Recording the target side again would - // double-count that one account, so skip it under REX6. - if !(self.rex6_enabled && call_inputs.target_address == call_inputs.caller) { - // Record target account info update in child's discardable. - self.record_discardable(1); - } - } - } - FrameInput::Create(_) => { - let parent_needs_update = self.frame_tracker.push_create_frame(); - if parent_needs_update { - if self.rex6_enabled { - // The creator's nonce bump survives the child's revert (revm bumps it - // before the create checkpoint), so charge it to the parent frame — - // see `FrameLimitTracker::add_parent_discardable`. - self.record_parent_discardable(1); - } else { - // Pre-REX6: the creator nonce-bump charge is bundled into the child frame's - // discardable lane (frozen behavior). - self.record_discardable(1); - } - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a new execution frame is successfully initialized. - /// - /// For CREATE frames, records the created address and its account info update (1 KV). - fn after_frame_init_on_frame(&mut self, frame: &EthFrame) { - if frame.data.is_create() { - let created_address = - frame.data.created_address().expect("created address is none for create frame"); - self.frame_tracker.set_created_address(created_address); - // Record account info update for created address - self.record_discardable(1); - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Rex5+: if the reverting child had set the parent's account-update flag, the flag - /// is reset so the next successful call from the same parent still charges the parent - /// account (avoiding undercounting after a revert-then-retry pattern). The unwind is - /// owned by `FrameLimitTracker::pop_frame_unwind_parent`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - let is_success = result.instruction_result().is_ok(); - self.frame_tracker.pop_frame_unwind_parent(is_success); - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// | Original == Present | Original == New | Effect | Reason | - /// |---------------------|-----------------|------------|-------------------------| - /// | yes | yes | — | No change | - /// | yes | no | +1 (disc.) | First write to slot | - /// | no | yes | +1 (refund)| Reset to original value | - /// | no | no | — | Rewrite, no new KV | - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - if store_result.is_original_eq_present() { - if !store_result.is_original_eq_new() { - self.record_discardable(1); - } - } else if store_result.is_original_eq_new() { - self.record_refund(1); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `record_account_update` must charge exactly one KV update against the current frame - /// (used by REX5+ SELFDESTRUCT-beneficiary metering); it must not be a no-op. - #[test] - fn test_record_account_update_charges_one_kv() { - let mut tracker = KVUpdateTracker::new(MegaSpecId::MINI_REX, u64::MAX); - tracker.push_empty_frame(); - assert_eq!(tracker.tx_usage(), 0); - tracker.record_account_update(); - assert_eq!(tracker.tx_usage(), 1, "record_account_update must add exactly 1 KV update"); - } -} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs deleted file mode 100644 index 2bcec8b8b..000000000 --- a/crates/mega-evm/src/limit/limit.rs +++ /dev/null @@ -1,1153 +0,0 @@ -use core::ops::Range; - -use alloy_primitives::{Address, Bytes, U256}; -use op_revm::OpHaltReason; -use revm::{ - context::result::{HaltReason, OutOfGasError}, - handler::{EthFrame, FrameResult, ItemOrResult}, - interpreter::{ - gas::calculate_initial_tx_gas_for_tx, interpreter::EthInterpreter, - interpreter_action::FrameInit, CallOutcome, CreateOutcome, FrameInput, Gas, - InstructionResult, InterpreterAction, InterpreterResult, SStoreResult, - }, -}; - -use super::{ - compute_gas, data_size, frame_limit::TxRuntimeLimit, kv_update, state_growth, - storage_call_stipend, -}; -use crate::{ - EvmTxRuntimeLimits, JournalInspectTr, MegaHaltReason, MegaSpecId, MegaTransaction, - VolatileDataAccess, -}; - -use super::LimitCheck; - -/// Additional limits for the `MegaETH` EVM beyond standard EVM limits. -/// -/// This struct coordinates four independent resource limits: compute gas, data size, -/// key-value updates, and state growth. Each limit is tracked separately and enforced during -/// transaction execution. -/// -/// ## TX-Level Halt Enforcement -/// -/// TX-level exceed is represented as `InstructionResult::OutOfGas`. -/// Remaining gas is rescued and later refunded to the sender. -/// - **Compute gas**: TX-level check is always active (`min(tx_limit, detained_limit)`). -/// - **Data size / KV update**: TX-level fallthrough is active in all specs. In Rex4+ it catches -/// intrinsic overflow (when the frame stack is empty) and serves as a safety net behind the -/// per-frame check. -/// - **State growth**: TX-level fallthrough catches Rex5 pre-frame authority usage and serves as a -/// safety net behind the per-frame check. -/// -/// ## Per-Frame Enforcement (Rex4+) -/// -/// In Rex4+, all four limits use per-frame budgets. -/// Each inner call frame receives `remaining * 98 / 100` of the parent's remaining budget. -/// When a frame exceeds its per-frame budget, it **reverts** (not halts) and gas returns to -/// the parent frame, which can continue executing: -/// - **State growth**: Reverted child's growth is discarded (`discardable_usage` dropped). -/// - **Data size**: Reverted child's discardable data is dropped, protecting parent's budget. -/// - **KV updates**: Reverted child's discardable KV ops are dropped, protecting parent's budget. -/// - **Compute gas**: Reverted child's gas still counts toward parent (gas is always persistent). -/// Per-frame limits act as "early termination guardrails" only, not budget protection. Compute -/// gas still retains TX-level detained checking in all specs. -/// -/// # Tracking Details -/// -/// - **Compute Gas**: Tracks gas consumption from EVM instructions during execution, monitoring the -/// computational cost separate from the standard gas limit -/// - **Data Size**: Tracks transaction data (110 bytes base + calldata + access lists + -/// authorizations), caller/authority account updates (40 bytes each), log data, storage writes -/// (40 bytes when original ≠ new), account updates from calls/creates (40 bytes), and contract -/// code size -/// - **KV Updates**: Tracks transaction caller + authority updates, storage writes (when original ≠ -/// new), and account updates from value transfers and creates -/// - **State Growth**: Tracks net new accounts + net new storage slots -/// -/// Additionally, this struct manages the `STORAGE_CALL_STIPEND` (Rex4+): extra gas granted to -/// value-transferring `CALL`/`CALLCODE` for storage operations. REX5+ tracks the stipend as a -/// separated internal allowance drained at the `storage_gas_ext` charging sites; REX4 retains -/// the legacy `gas.limit()` inflation with a per-frame compute gas cap and burn-on-return. -#[derive(Debug)] -pub struct AdditionalLimit { - /// Carries the tx's current limit-check verdict. - /// - /// Once stamped to a non-[`LimitCheck::WithinLimit`] value, the sub-tracker pass in - /// [`check_limit`](Self::check_limit) is bypassed and individual tracker usage values may - /// no longer be reliable (subsequent frames revert and their discardable usage is dropped). - /// Legitimate writers: [`check_limit`](Self::check_limit) (latches `ExceedsLimit`), - /// [`mark_exempt`](Self::mark_exempt) (stamps `Exempt`), - /// [`reset`](Self::reset) (clears to `WithinLimit`), and - /// [`before_frame_return_result`](Self::before_frame_return_result) (absorbs a frame-local - /// `ExceedsLimit` back to `WithinLimit`). Everything else reads via - /// [`check_limit`](Self::check_limit) or - /// [`exceeded_limit`](LimitCheck::exceeded_limit) / [`is_exempt`](LimitCheck::is_exempt). - pub(crate) has_exceeded_limit: LimitCheck, - - /// The total remaining gas after the limit exceeds. - pub rescued_gas: u64, - - /// The original limits set by the EVM. Some of the limits may be overridden (such as the - /// compute gas limit) during transaction execution. We keep the original limits to be able to - /// reset the limits before each transaction. - pub limits: EvmTxRuntimeLimits, - - /// A tracker for the state growth during transaction execution. - pub(crate) state_growth: state_growth::StateGrowthTracker, - - /// A tracker for the total data size (in bytes) generated from a transaction execution. - pub(crate) data_size: data_size::DataSizeTracker, - - /// A tracker for the total KV updates during transaction execution. - pub(crate) kv_update: kv_update::KVUpdateTracker, - - /// A tracker for the total compute gas consumed during transaction execution. - pub(crate) compute_gas: compute_gas::ComputeGasTracker, - - /// A tracker for the `STORAGE_CALL_STIPEND` granted to value-transferring calls (REX4+). - pub(crate) storage_call_stipend: storage_call_stipend::StorageCallStipendTracker, -} - -/// The usage of the additional limits. -#[derive(Clone, Copy, Debug, Default)] -pub struct LimitUsage { - /// The data size usage in bytes. - pub data_size: u64, - /// The number of KV updates. - pub kv_updates: u64, - /// The compute gas usage. - pub compute_gas: u64, - /// The state growth. - pub state_growth: u64, -} - -impl AdditionalLimit { - /// Creates a new `AdditionalLimit` instance from the given `MegaSpecId`. - pub fn new(spec: MegaSpecId, limits: EvmTxRuntimeLimits) -> Self { - Self { - has_exceeded_limit: LimitCheck::WithinLimit, - rescued_gas: 0, - limits, - state_growth: state_growth::StateGrowthTracker::new(spec, limits.tx_state_growth_limit), - data_size: data_size::DataSizeTracker::new(spec, limits.tx_data_size_limit), - kv_update: kv_update::KVUpdateTracker::new(spec, limits.tx_kv_updates_limit), - compute_gas: compute_gas::ComputeGasTracker::new(spec, limits.tx_compute_gas_limit), - storage_call_stipend: storage_call_stipend::StorageCallStipendTracker::new(spec), - } - } -} - -impl AdditionalLimit { - /// The [`InstructionResult`] to indicate that the limit is exceeded (TX-level). - /// - /// This constant is used for TX-level additional-limit exceeds. - /// For TX-level exceeds, this is `OutOfGas` (halt path, with rescued gas refund). - /// For frame-local exceeds (Rex4+), use - /// `exceeding_instruction_result()` which returns `Revert` instead. - pub const EXCEEDING_LIMIT_INSTRUCTION_RESULT: InstructionResult = InstructionResult::OutOfGas; - - /// Returns the appropriate [`InstructionResult`] for the current limit exceed. - /// - /// - **Frame-local (Rex4+)**: `Revert` — gas returns to the parent frame naturally. - /// - **TX-level**: `OutOfGas` — halt, gas consumed (rescued via `rescued_gas`). - #[inline] - pub(crate) fn exceeding_instruction_result(&self) -> InstructionResult { - if self.has_exceeded_limit.is_frame_local() { - InstructionResult::Revert - } else { - Self::EXCEEDING_LIMIT_INSTRUCTION_RESULT - } - } - - /// Resets the internal state for a new transaction or block. - /// - /// This method clears both the data size tracker and KV update counter, - /// preparing the limit system for a new execution context. - /// - /// Each tracker internally handles spec-gated behavior (e.g., `ComputeGasTracker` - /// resets the detained limit only for Rex1+). - pub fn reset(&mut self) { - self.has_exceeded_limit = LimitCheck::WithinLimit; - self.rescued_gas = 0; - self.compute_gas.reset(); - self.state_growth.reset(); - self.data_size.reset(); - self.kv_update.reset(); - self.storage_call_stipend.reset(); - } - - /// Test-only setter for [`has_exceeded_limit`](Self::has_exceeded_limit). Bypasses every - /// invariant maintained by the normal write paths (sticky `Exempt`, sub-tracker latching, - /// frame-local absorb). Integration tests use this to construct specific pre-latched states - /// — production code must not. - #[cfg(any(test, feature = "test-utils"))] - #[doc(hidden)] - pub fn set_has_exceeded_limit_for_test(&mut self, state: LimitCheck) { - self.has_exceeded_limit = state; - } - - /// Marks the current transaction as exempt from `MegaETH` per-tx resource metering by stamping - /// `has_exceeded_limit = LimitCheck::Exempt`. REX6+ uses this for system-originated - /// transactions (see [`crate::is_system_originated`]); cleared by [`reset`](Self::reset). - /// - /// `Exempt` is sticky: [`check_limit`](Self::check_limit) short-circuits on it, so no later - /// sub-tracker overflow can latch over it, and every direct read of `has_exceeded_limit` - /// observes the exemption as "not exceeded" via - /// [`exceeded_limit`](LimitCheck::exceeded_limit). The host storage-gas charging sites - /// additionally consult [`is_exempt`](LimitCheck::is_exempt) to charge the SALT-unscaled - /// cost, since SALT-scaled storage gas is charged to interpreter gas and is not tracked here. - /// - /// `current_call_remaining_*` queries (compute gas, data size, KV updates, state growth) still - /// report `limit − usage` against the configured limit while exempt, but the limit is not - /// enforced — so a caller that uses these values to make admission or sizing decisions for an - /// exempt tx will get a number that is not load-bearing. Today's consumers - /// (`MegaLimitControl.remainingComputeGas`, the `KeylessDeploy` sandbox sub-limits, oracle - /// hint precompile) are unreachable from a system-originated tx; revisit this if a future - /// system contract joins the mega whitelist and would consult them. - #[inline] - pub(crate) fn mark_exempt(&mut self) { - self.has_exceeded_limit = LimitCheck::Exempt; - } - - /// Gets the usage of the additional limits. - #[inline] - pub fn get_usage(&self) -> LimitUsage { - LimitUsage { - data_size: self.data_size.tx_usage(), - kv_updates: self.kv_update.tx_usage(), - compute_gas: self.compute_gas.tx_usage(), - state_growth: self.state_growth.tx_usage(), - } - } - - /// Checks whether the Rex5 sandbox's TX-level pre-frame intrinsic usage fits inside - /// `limits`. - /// - /// Runs a trial `AdditionalLimit` through the same entry points production uses — - /// `before_tx_start` (data size / KV updates) and `record_compute_gas(initial_gas)` - /// (intrinsic compute gas, via `MegaHandler::validate`) — then returns its `check_limit()` - /// result. Reusing production logic keeps tracker changes and dimension-priority ordering - /// in sync automatically. Consumed by the `KeylessDeploy` preflight. - /// - /// Any future TX-level persistent usage recorded before the first frame through a different - /// path MUST be added here too when it can be computed from the transaction alone. DB-dependent - /// contributions, such as REX5 EIP-7702 net-new authority state growth, are recorded during - /// pre-execution once the journal is available. Missing additions do not fail open — the - /// `KeylessDeploy` post-merge overflow check still catches residual overflow — but the failure - /// mode degrades from the preflight fast-path (pre-sandbox revert with `ParentBudgetExceeded`) - /// to an outer `OutOfGas` halt after sandbox setup has already run. - pub(crate) fn intrinsic_check_for_tx( - spec: MegaSpecId, - tx: &MegaTransaction, - limits: EvmTxRuntimeLimits, - ) -> LimitCheck { - debug_assert!(spec.is_enabled(MegaSpecId::REX5)); - let mut trial = Self::new(spec, limits); - trial.before_tx_start(tx); - - let initial_and_floor_gas = calculate_initial_tx_gas_for_tx(tx, spec.into_eth_spec()); - trial.record_compute_gas(initial_and_floor_gas.initial_gas); - - trial.check_limit() - } - - /// Pushes an empty frame to all trackers so `before_frame_return_result` can pop - /// them to keep stacks aligned with the EVM's call stack. - /// - /// Used when `frame_init` returns an early `Result` (e.g., inspector interception, - /// access control interception) without going through `after_frame_init`. - #[inline] - pub(crate) fn push_empty_frame(&mut self) { - self.state_growth.push_empty_frame(); - self.data_size.push_empty_frame(); - self.kv_update.push_empty_frame(); - self.compute_gas.push_empty_frame(); - self.storage_call_stipend.push_empty_frame(); - } - - /// Returns the current effective compute gas limit (may be detained/lowered by volatile - /// data access). - #[inline] - pub fn compute_gas_limit(&self) -> u64 { - self.compute_gas.tx_limit() - } - - /// Returns the remaining compute gas of the current call. - /// - /// In Rex4+, returns the minimum of the caller's per-frame remaining compute gas - /// and the TX-level detained remaining, reflecting the actual gas available before - /// execution halts (whether due to frame budget or gas detention). - /// If no frame exists yet (direct TX → system contract), returns the TX-level - /// remaining which accounts for intrinsic compute gas. - /// In pre-Rex4, falls back to TX-level remaining compute gas. - #[inline] - pub fn current_call_remaining_compute_gas(&self) -> u64 { - self.compute_gas.current_call_remaining() - } - - /// Returns the remaining data size budget for the current call frame. - #[inline] - pub fn current_call_remaining_data_size(&self) -> u64 { - self.data_size.current_call_remaining() - } - - /// Returns the remaining KV update budget for the current call frame. - #[inline] - pub fn current_call_remaining_kv_updates(&self) -> u64 { - self.kv_update.current_call_remaining() - } - - /// Returns the remaining state growth budget for the current call frame. - #[inline] - pub fn current_call_remaining_state_growth(&self) -> u64 { - self.state_growth.current_call_remaining() - } - - /// Returns the detained compute gas limit (independent of the natural TX limit). - /// This is the limit set by volatile data access gas detention. - #[inline] - pub fn detained_compute_gas_limit(&self) -> u64 { - self.compute_gas.detained_limit() - } - - /// Returns the halt reason when gas detention is the binding compute gas constraint. - /// Otherwise (detention was not more restrictive than the base TX limit), returns `None`. - #[inline] - pub(crate) fn detained_compute_gas_halt_reason( - &self, - access_type: VolatileDataAccess, - ) -> Option { - self.compute_gas.is_detained_exceed().then(|| MegaHaltReason::VolatileDataAccessOutOfGas { - access_type, - limit: self.compute_gas.detained_limit(), - actual: self.compute_gas.tx_usage(), - }) - } - - /// Sets the compute gas limit to a new value. - /// This is used to dynamically lower the compute gas limit when volatile data is accessed. - /// The new limit must be lower than the current limit. - #[inline] - pub fn set_compute_gas_limit(&mut self, new_limit: u64) { - self.compute_gas.set_detained_limit(new_limit); - } - - /// Checks if any of the configured limits have been exceeded. - /// - /// This method examines data size, KV update, compute gas, and state growth in fixed order - /// and returns the first exceeded limit. - /// - /// # Returns - /// - /// Returns a [`LimitCheck`] indicating whether limits have been exceeded - /// and which specific limit was exceeded if any. - #[inline] - pub fn check_limit(&mut self) -> LimitCheck { - // Sticky short-circuit: `Exempt` (REX6+ system-originated tx; usage is still accumulated - // by individual trackers for `get_usage` and block-level accounting, only the halt - // decision is suppressed) and already-latched `ExceedsLimit` both bypass the sub-tracker - // pass. For `Exempt` this also neutralizes gas detention (which runs through - // `compute_gas.check_limit()` below), so protocol-mandated execution can never halt on - // metering — e.g. when SALT buckets grow. The standard EVM `gas_limit` remains the - // runaway guard. - if !self.has_exceeded_limit.within_limit() { - return self.has_exceeded_limit; - } - - let data_size_check = self.data_size.check_limit(); - if data_size_check.exceeded_limit() { - self.has_exceeded_limit = data_size_check; - return self.has_exceeded_limit; - } - - let kv_update_check = self.kv_update.check_limit(); - if kv_update_check.exceeded_limit() { - self.has_exceeded_limit = kv_update_check; - return self.has_exceeded_limit; - } - - // Per-frame compute gas check (Rex4+) and TX-level detained check (all specs). - let compute_gas_check = self.compute_gas.check_limit(); - if compute_gas_check.exceeded_limit() { - self.has_exceeded_limit = compute_gas_check; - return self.has_exceeded_limit; - } - - // State growth check: - // - Rex4+: frame-local budget check. - // - pre-Rex4: TX-level check inside `state_growth.check_limit()`. - let state_growth_check = self.state_growth.check_limit(); - if state_growth_check.exceeded_limit() { - self.has_exceeded_limit = state_growth_check; - return self.has_exceeded_limit; - } - - self.has_exceeded_limit - } - - /// `true` when a per-tx resource limit has already been latched as exceeded — the exact - /// condition [`frame_result_if_exceeding_limit`](Self::frame_result_if_exceeding_limit) halts - /// the transaction on. `WithinLimit` and `Exempt` both return `false`. Reads the latched - /// aggregate; call [`check_limit`](Self::check_limit) first if a fresh evaluation is needed. - #[inline] - pub(crate) fn limit_exceeded(&self) -> bool { - self.has_exceeded_limit.exceeded_limit() - } - - /// Checks if the halt reason indicates that the limit has been exceeded. - /// - /// # Arguments - /// - /// * `halt_reason` - The halt reason to check - /// - /// # Returns - /// - /// Returns `true` if the halt reason indicates that the limit has been exceeded, `false` - /// otherwise. - pub fn is_exceeding_limit_halt(&mut self, halt_reason: &OpHaltReason) -> bool { - matches!(halt_reason, &OpHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic))) && - self.check_limit().exceeded_limit() - } -} - -/* Hooks for transaction execution lifecycle. */ -impl AdditionalLimit { - /// Records the compute gas used and returns `false` if the limit has been exceeded. - /// - /// This runs on every metered opcode, so it is the hottest hook in the whole tracker. - /// `#[inline]` lets the record + within-limit check fold directly into the per-opcode - /// wrapper, removing a call across the `RefMut` boundary. - #[inline] - pub(crate) fn record_compute_gas(&mut self, compute_gas_used: u64) -> bool { - // Record unconditionally, even when another dimension has already latched an exceed: - // the compute work was performed, and the recorded total feeds the transaction outcome - // and block-level compute accounting. Skipping the record would under-report compute - // usage for transactions halted on a non-compute dimension (e.g. intrinsic data size - // latched in `before_tx_start` before `validate` records the initial gas). - self.compute_gas.record_gas_used(compute_gas_used); - // Sticky short-circuit, mirroring `check_limit`: an already-latched `ExceedsLimit` is - // surfaced immediately, and `Exempt` (REX6+ system-originated tx) suppresses the halt - // decision — including the compute-gas / detained check below — while the recording - // above still feeds `get_usage` and block-level accounting. - if !self.has_exceeded_limit.within_limit() { - return !self.has_exceeded_limit.exceeded_limit(); - } - // Debug-only guard for the latch protocol: the compute-only fast path below is sound - // only if every non-compute mutation site already latched its own exceed. If a - // non-compute dimension is over limit but not yet latched, some mutation site is missing - // its `check_limit()` — catch it here in tests, not in production. The sub-tracker - // `check_limit()` calls are non-mutating, so this compiles out of release builds. (The - // one pre-inner recorder, SELFDESTRUCT, routes through `record_compute_gas_all_dims`, not - // this method, so it never trips this.) - debug_assert!( - !self.data_size.check_limit().exceeded_limit() && - !self.kv_update.check_limit().exceeded_limit() && - !self.state_growth.check_limit().exceeded_limit(), - "non-compute limit exceeded without latching: a mutation site is missing check_limit()", - ); - // Recording compute gas can only change the compute-gas dimension, so check just that one - // (`compute_gas.check_limit()` covers both the Rex4+ per-frame budget and the TX-level - // detained limit) instead of fanning out to all four sub-trackers. The other three - // dimensions only change at their own mutation sites (`on_sstore`, `on_log`, - // `record_oracle_hint_bytes`, the frame-lifecycle hooks), each of which runs - // `check_limit()` itself and latches any exceed into `has_exceeded_limit` — which the - // short-circuit above then surfaces here. The one exception is SELFDESTRUCT's pre-inner - // `on_selfdestruct_new_account` / `on_selfdestruct_existing_account`, which deliberately - // do not latch; their dimensions latch in the trailing `record_compute_gas_all_dims`. - let check = self.compute_gas.check_limit(); - if check.exceeded_limit() { - self.has_exceeded_limit = check; - return false; - } - true - } - - /// Records the compute gas used and checks ALL four limit dimensions (the - /// pre-optimization fan-out), returning `false` if any has been exceeded. - /// - /// Retained for SELFDESTRUCT: its REX5 storage wrapper records beneficiary - /// data/KV/state usage *before* the inner instruction runs, without latching - /// (the inner instruction may still fail, in which case the frame pops that - /// discardable usage). The fan-out here latches those dimensions only after the - /// inner instruction has succeeded, with `check_limit`'s dimension priority. - /// Hot-path opcodes use [`Self::record_compute_gas`] instead. - #[inline] - pub(crate) fn record_compute_gas_all_dims(&mut self, compute_gas_used: u64) -> bool { - self.compute_gas.record_gas_used(compute_gas_used); - !self.check_limit().exceeded_limit() - } - - /// Records the current frame's remaining gas on a TX-level limit exceed so it can be - /// refunded to the sender. The storage-stipend tracker decides how `gas.remaining()` - /// maps to the refundable balance — see - /// `StorageCallStipendTracker::effective_remaining_for_rescue`. - pub(crate) fn rescue_gas(&mut self, gas: &Gas) { - self.rescued_gas += self.storage_call_stipend.effective_remaining_for_rescue(gas); - } - - /// Drains up to `amount` from the current frame's storage stipend allowance and - /// returns the portion drained. Caller charges the residual via the original site's - /// gas-charging macro. Returns 0 pre-REX5 (the legacy path covers storage via - /// `gas.limit()` inflation). - pub(crate) fn try_consume_storage_stipend(&mut self, amount: u64) -> u64 { - self.storage_call_stipend.try_consume(amount) - } - - /// Rescue remaining gas from a frame result if a TX-level additional limit has been - /// exceeded. - /// - /// This must be called before any inspector callback (`frame_end`) that might modify the - /// gas via `spend_all()`, so the correct `gas.remaining()` value is captured. - /// The rescued gas is later refunded to the transaction sender in `last_frame_result`. - pub(crate) fn try_rescue_gas(&mut self, gas: &Gas) { - let limit_check = self.check_limit(); - if limit_check.exceeded_limit() && !limit_check.is_frame_local() { - self.rescue_gas(gas); - } - } - - /// Hook called when a new transaction starts. - /// - /// Records transaction-only intrinsic resource usage that can be computed from the - /// transaction itself (calldata size, access lists, EIP-7702 authority account update - /// footprint, caller account update, etc.) and checks TX-level limits. - /// - /// DB-dependent pre-frame usage is recorded later once the journal is available. - /// In particular, REX5 EIP-7702 net-new authority state growth is accounted during - /// pre-execution rather than here because `before_tx_start()` cannot tell whether an - /// authority account already exists. - /// - /// If the recorded usage already exceeds a configured limit, sets `has_exceeded_limit` - /// so that the subsequent `frame_result_if_exceeding_limit()` or `before_frame_init()` - /// call produces a normal execution failure (Halt), keeping the failure on the standard - /// additional-limit path. - /// - /// Intrinsic overflow detection works through each tracker's own `check_limit()`, which - /// includes a TX-level fallthrough that catches `tx_usage > tx_limit` even when the frame - /// stack is empty (before the first frame is pushed). - pub(crate) fn before_tx_start(&mut self, tx: &MegaTransaction) { - self.state_growth.before_tx_start(tx); - self.data_size.before_tx_start(tx); - self.kv_update.before_tx_start(tx); - self.check_limit(); - } - - /// Records REX5 EIP-7702 authority accounts that are net-new state entries — the state-growth - /// dimension only. Data size and KV updates for REX5 are charged upfront in `before_tx_start` - /// for every authorization with a recoverable authority, independent of application. - /// - /// Runs in pre-execution after the authorization scan identifies net-new authorities and - /// before revm writes the delegation bytecode; the net-new check needs DB / journal state, - /// so this cannot live in `before_tx_start`. - /// - /// REX6+ replaces this with the per-applied-authority hook - /// [`AdditionalLimit::on_rex6_eip7702_authority_applied`], which records all three resource - /// dimensions in a single call. - /// - /// Latches any TX-level overflow into `has_exceeded_limit` via `check_limit`; the next frame - /// boundary surfaces it as the normal execution failure. - pub(crate) fn on_rex5_eip7702_authority_creations(&mut self, amount: u64) { - self.state_growth.record_authority_creations(amount); - self.check_limit(); - } - - /// Records the resource footprint of a single *applied* EIP-7702 authorization — one that - /// passed the chain-id / `u64::MAX`-nonce / recoverable-authority / code gates and therefore - /// writes the authority account — as TX-level persistent usage across all three dimensions. - /// - /// Every applied authorization writes the authority account (delegation code + nonce bump), - /// so it always costs data size (+40) and a KV update (+1). A net-new authority account - /// additionally counts as state growth (+1) — the caller passes `creates_authority` for that. - /// The matching dynamic SALT account-creation gas is folded into `initial_gas` by the caller. - /// - /// REX5 splits the same accounting into two paths: data size / KV charged unconditionally in - /// `before_tx_start` (covers skipped authorizations too), and state growth via - /// [`AdditionalLimit::on_rex5_eip7702_authority_creations`]. REX6 consolidates them so only - /// applied authorizations pay. - pub(crate) fn on_rex6_eip7702_authority_applied(&mut self, creates_authority: bool) { - self.data_size.record_persistent_account_write(); - self.kv_update.record_persistent_account_update(); - if creates_authority { - self.state_growth.record_authority_creations(1); - } - self.check_limit(); - } - - /// Hook called before a new execution frame is initialized. Returns `Some(FrameResult)` if the - /// limit is exceeded and the frame should terminate early with the returned `FrameResult`. - /// - /// For REX4+ value-transferring internal `CALL`/`CALLCODE`, this method also applies the - /// `STORAGE_CALL_STIPEND`: it inflates `gas_limit`, caps the per-frame compute gas budget - /// at the original gas limit, and pushes the stipend amount to the burn stack. - pub(crate) fn before_frame_init>( - &mut self, - frame_init: &mut FrameInit, - journal: &mut JOURNAL, - ) -> Result, JOURNAL::DBError> { - // Push new frame in frame limit trackers. - self.state_growth.before_frame_init(frame_init, journal)?; - self.data_size.before_frame_init(frame_init, journal)?; - self.kv_update.before_frame_init(frame_init, journal)?; - self.compute_gas.before_frame_init(frame_init, journal)?; - - // REX4+: detect value-transferring CALL/CALLCODE, inflate gas_limit, push stipend - // to stack, and cap per-frame compute gas budget. - self.storage_call_stipend.before_frame_init(frame_init, &mut self.compute_gas); - - if self.check_limit().exceeded_limit() { - return Ok(self.create_exceeded_limit_result(&frame_init.frame_input)); - } - - Ok(None) - } - - /// Checks whether a TX-level limit was already exceeded before the first frame starts - /// (e.g., intrinsic `DataSize` or `KVUpdate` overflow from `before_tx_start()`). - /// - /// Called from two sites that would otherwise skip `before_frame_init()`: - /// - `frame_init()` before system contract interceptor dispatch (REX4+). - /// - `inspect_frame_init()` before inspector early-return (REX4+). - /// - /// Without this check, an intrinsic overflow would never be converted into a real - /// failure and gas rescue would be missed. - /// - /// Returns `Some(FrameResult)` if a TX-level limit is already exceeded. - pub(crate) fn frame_result_if_exceeding_limit( - &mut self, - frame_input: &FrameInput, - ) -> Option { - if !self.limit_exceeded() { - return None; - } - self.create_exceeded_limit_result(frame_input) - } - - /// Creates a `FrameResult` for an exceeded limit and rescues remaining gas. - /// - /// Shared by `before_frame_init` (limit exceeded after pushing sub-tracker frames) - /// and `frame_result_if_exceeding_limit` (intrinsic overflow before frame push). - fn create_exceeded_limit_result(&mut self, frame_input: &FrameInput) -> Option { - let (gas_limit, return_memory_offset) = match frame_input { - FrameInput::Call(inputs) => { - (inputs.gas_limit, Some(inputs.return_memory_offset.clone())) - } - FrameInput::Create(inputs) => (inputs.gas_limit, None), - FrameInput::Empty => unreachable!(), - }; - let output = self.has_exceeded_limit.revert_data(); - let result = create_exceeding_limit_frame_result( - self.exceeding_instruction_result(), - Gas::new(gas_limit), - return_memory_offset, - output, - ); - self.try_rescue_gas(result.gas()); - Some(result) - } - - /// Hook called when a new execution frame is successfully initialized in `frame_init` and needs - /// to be run (i.e., target address has code). - pub(crate) fn after_frame_init( - &mut self, - init_result: &ItemOrResult<&mut EthFrame, FrameResult>, - ) { - if let ItemOrResult::Item(frame) = &init_result { - self.state_growth.after_frame_init_on_frame(frame); - self.data_size.after_frame_init_on_frame(frame); - self.kv_update.after_frame_init_on_frame(frame); - self.compute_gas.after_frame_init_on_frame(frame); - } else if let ItemOrResult::Result(result) = init_result { - // Rescue gas if a TX-level limit was exceeded. This covers the - // before_frame_init early-return path and any other Result from frame_init. - self.try_rescue_gas(result.gas()); - } - } - - /// Hook called before a frame run. If the limit is exceeded, return an interpreter result - /// indicating that the limit is exceeded. - pub(crate) fn before_frame_run( - &mut self, - frame: &EthFrame, - ) -> Option { - self.state_growth.before_frame_run(frame); - self.data_size.before_frame_run(frame); - self.kv_update.before_frame_run(frame); - self.compute_gas.before_frame_run(frame); - - if self.check_limit().exceeded_limit() { - let output = self.has_exceeded_limit.revert_data(); - return Some(create_exceeding_interpreter_result( - self.exceeding_instruction_result(), - frame.interpreter.gas, - output, - )); - } - None - } - - /// Hook called after frame action processing in `frame_run`. - /// - /// Records compute gas cost induced in frame action processing (e.g., code deposit cost), - /// marks the frame result as exceeding limit if needed, and rescues gas if a TX-level limit - /// was exceeded (before any inspector callback that might modify gas). - pub(crate) fn after_frame_run( - &mut self, - result: &mut FrameResult, - gas_remaining_before_process_action: Option, - ) { - if let Some(gas_remaining_before) = gas_remaining_before_process_action { - let compute_gas_cost = gas_remaining_before.saturating_sub(result.gas().remaining()); - if !self.record_compute_gas(compute_gas_cost) { - mark_frame_result_as_exceeding_limit( - result, - self.exceeding_instruction_result(), - Default::default(), - ); - } - } - // Rescue gas if a TX-level additional limit has been exceeded. - // This must happen before any inspector callback (`frame_end`) that might modify - // the gas via `spend_all()`, so the correct `gas.remaining()` value is captured. - self.try_rescue_gas(result.gas()); - } - - /// Hook called when a frame finishes running in `frame_run`. If the limit is exceeded, mark - /// in place the interpreter result as exceeding the limit. - pub(crate) fn after_frame_run_instructions<'a>( - &mut self, - frame: &'a EthFrame, - action: &'a mut InterpreterAction, - ) { - self.state_growth.after_frame_run(frame, action); - self.data_size.after_frame_run(frame, action); - self.kv_update.after_frame_run(frame, action); - self.compute_gas.after_frame_run(frame, action); - - if let InterpreterAction::Return(interpreter_result) = action { - if frame.data.is_create() { - // Fast-path: a TX-level limit was latched earlier; pick it up without re-running - // sub-tracker checks. Under `Exempt`, the predicate is false, so the exemption - // passes through unchanged. - if self.limit_exceeded() { - let output = self.has_exceeded_limit.revert_data(); - mark_interpreter_result_as_exceeding_limit( - interpreter_result, - self.exceeding_instruction_result(), - output, - ); - return; - } - - // The sub-tracker `after_frame_run` calls above may have recorded new usage; run - // a fresh check to catch overflow first detected at this frame end. - if self.check_limit().exceeded_limit() { - let output = self.has_exceeded_limit.revert_data(); - mark_interpreter_result_as_exceeding_limit( - interpreter_result, - self.exceeding_instruction_result(), - output, - ); - } - } - } - } - - /// Hook called when returning a frame result to parent frame in `frame_return_result` or - /// `last_frame_result`. May modify the frame result in place if the limit is exceeded. - pub(crate) fn before_frame_return_result( - &mut self, - result: &mut FrameResult, - ) { - // TRUE if the current function is called twice for the top-level frame. If the top-level - // frame has child frames, the top-level frame's result will be handled twice (one via - // `EvmTr::frame_return_result`, the other via `Handler::last_frame_result`). This flag is - // used to distinguish these two cases. - let duplicate_return_frame_result = LAST_FRAME && !self.data_size.has_active_frame(); - - // Pop frame from the frame limit trackers. - self.state_growth.before_frame_return_result::(result); - self.data_size.before_frame_return_result::(result); - self.kv_update.before_frame_return_result::(result); - self.compute_gas.before_frame_return_result::(result); - - // Pop stipend from stack and burn unused stipend (Rex4+). - self.storage_call_stipend.before_frame_return_result::(result); - - // Frame-level limit handling (Rex4+): check if the child frame exceeded its - // frame-local budget. The detection may not have happened during execution, so - // we call check_limit() here to ensure it's caught. - // If frame-local, absorb it — clear the exceed flag and change to Revert so - // remaining gas returns to the caller. State changes are reverted by revm's - // Revert handling. This works at any depth including the top-level frame. - let limit_check = self.check_limit(); - if limit_check.exceeded_limit() && !duplicate_return_frame_result { - if limit_check.is_frame_local() { - let output = limit_check.revert_data(); - self.has_exceeded_limit = LimitCheck::WithinLimit; - match result { - FrameResult::Call(o) => { - o.result.result = InstructionResult::Revert; - o.result.output = output; - } - FrameResult::Create(o) => { - o.result.result = InstructionResult::Revert; - o.result.output = output; - } - } - } else { - // Gas should already have been rescued at the point where the limit was - // exceeded (frame_result_if_exceeding_limit, before_frame_init, - // after_frame_init, or after_frame_run). - // Just mark the result as exceeding the limit. - mark_frame_result_as_exceeding_limit( - result, - Self::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); - } - } - } - - /// Merges resource usage from a sandbox execution into this tracker. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox resource consumption - /// back to the parent transaction. - pub(crate) fn merge_usage(&mut self, usage: LimitUsage) { - self.compute_gas.merge_persistent_usage(usage.compute_gas); - self.data_size.merge_persistent_usage(usage.data_size); - self.kv_update.merge_persistent_usage(usage.kv_updates); - self.state_growth.merge_persistent_usage(usage.state_growth); - } - - /// Hook called when an orginally zero storage slot is written non-zero value for the first time - /// in the transaction. Returns `false` if the limit has been exceeded. - pub(crate) fn on_sstore( - &mut self, - target_address: Address, - slot: U256, - store_result: &SStoreResult, - ) -> bool { - self.state_growth.after_sstore(target_address, slot, store_result); - self.data_size.after_sstore(target_address, slot, store_result); - self.kv_update.after_sstore(target_address, slot, store_result); - - !self.check_limit().exceeded_limit() - } - - /// REX5+: record that the current transaction's caller account is being materialised - /// by deposit pre-execution (mint balance increment, nonce bump, or both). - /// - /// Routes a `+1` to `state_growth`'s TX intrinsic lane only. Does **not** touch - /// `data_size` or `kv_update`: their `before_tx_start` hooks already record the - /// caller's account-info write unconditionally for every transaction (protocol-level - /// definition: one caller account-info write per tx). Adding a second record here - /// would double-count. - /// - /// Must be called exactly once per deposit-like transaction, only when the caller - /// account is empty at validation time (before `OpHandler::pre_execution` runs). - pub(crate) fn record_deposit_caller_creation(&mut self) { - self.state_growth.record_deposit_caller_creation(); - let _ = self.check_limit(); - } - - /// REX5+: meter an oracle-hint payload against the TX data-size budget. - /// - /// Records `len` bytes into the TX intrinsic data-size lane (same lane as calldata) and - /// runs `check_limit()` so `has_exceeded_limit` is flipped to a TX-level exceed if the - /// recording overflows. - /// - /// Returns `true` if the recording stayed within the limit, `false` otherwise. - /// - /// **Caller contract**: on `false`, do NOT synthesize a result. Return `None` from the - /// interceptor and let the next `frame_init` step (`before_frame_init` → - /// `create_exceeded_limit_result`) produce the canonical TX-level `OutOfGas` halt with - /// rescued gas. This keeps the failure shape identical to any other data-size overflow. - pub(crate) fn record_oracle_hint_bytes(&mut self, len: u64) -> bool { - self.data_size.record_oracle_hint_bytes(len); - !self.check_limit().exceeded_limit() - } - - /// Hook called when a log is written. Returns `false` if the limit has been exceeded. - pub(crate) fn on_log(&mut self, num_topics: u64, data_size: u64) -> bool { - self.state_growth.after_log(num_topics, data_size); - self.data_size.after_log(num_topics, data_size); - - !self.check_limit().exceeded_limit() - } - - /// Hook called after a SELFDESTRUCT on a same-TX-created account (REX4+). - /// - /// Records state growth refund for the destroyed account and its new storage slots. - /// The caller is responsible for computing the total refund before calling this. - pub(crate) fn on_selfdestruct(&mut self, refund: u64) { - self.state_growth.after_selfdestruct(refund); - } - - /// Records resource usage when SELFDESTRUCT creates a new beneficiary account (REX5+). - /// - /// Charges data size (+40 for account info write), KV update (+1), and state growth (+1). - pub(crate) fn on_selfdestruct_new_account(&mut self) { - // Account info write: same as DataSizeTracker's ACCOUNT_INFO_WRITE_SIZE (40 bytes) - self.data_size.record_account_write(); - self.kv_update.record_account_update(); - self.state_growth.record_growth(1); - } - - /// Records resource usage when SELFDESTRUCT transfers balance to an existing - /// beneficiary account (REX6+). - /// - /// Charges data size (+40 for account info write) and KV update (+1). The target - /// already exists, so no `StateGrowth` is recorded. SELFDESTRUCT does not push a call - /// frame, so the `target_updated` dedup path in `FrameLimitTracker` never sees the - /// balance write to an existing target — hence this dedicated hook. - pub(crate) fn on_selfdestruct_existing_account(&mut self) { - self.data_size.record_account_write(); - self.kv_update.record_account_update(); - } -} - -/// Creates a `FrameResult` indicating that the limit is exceeded. -/// -/// This utility function creates a frame result that signals limit exceeded. -/// -/// # Arguments -/// -/// * `gas_limit` - The gas limit of the transaction -/// * `return_memory_offset` - The memory offset of the return value if the frame is a call frame. -/// `None` if the frame is a create frame -/// -/// # Returns -/// -/// A `FrameResult` indicating that the limit is exceeded with the given instruction result. -fn create_exceeding_limit_frame_result( - instruction_result: InstructionResult, - gas: Gas, - return_memory_offset: Option>, - output: Bytes, -) -> FrameResult { - match return_memory_offset { - None => FrameResult::Create(CreateOutcome::new( - create_exceeding_interpreter_result(instruction_result, gas, output), - None, - )), - Some(return_memory_offset) => FrameResult::Call(CallOutcome::new( - create_exceeding_interpreter_result(instruction_result, gas, output), - return_memory_offset, - )), - } -} - -/// Creates an interpreter result indicating that the limit is exceeded. -fn create_exceeding_interpreter_result( - instruction_result: InstructionResult, - gas: Gas, - output: Bytes, -) -> InterpreterResult { - InterpreterResult::new(instruction_result, output, gas) -} - -/// Marks an existing interpreter result as exceeding the limit. -fn mark_interpreter_result_as_exceeding_limit( - result: &mut InterpreterResult, - instruction_result: InstructionResult, - output: Bytes, -) { - result.result = instruction_result; - result.output = output; -} - -/// Marks a frame result as exceeding the limit. -pub(crate) fn mark_frame_result_as_exceeding_limit( - result: &mut FrameResult, - instruction_result: InstructionResult, - output: Bytes, -) { - match result { - FrameResult::Call(call_outcome) => { - mark_interpreter_result_as_exceeding_limit( - &mut call_outcome.result, - instruction_result, - output, - ); - } - FrameResult::Create(create_outcome) => { - mark_interpreter_result_as_exceeding_limit( - &mut create_outcome.result, - instruction_result, - output, - ); - } - } -} - -#[cfg(test)] -mod metering_exemption_tests { - use super::*; - - /// Tiny per-dimension limits so a single recording trivially exceeds them. - fn tiny_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 1, - tx_kv_updates_limit: 1, - tx_compute_gas_limit: 1, - tx_state_growth_limit: 1, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - #[test] - fn test_metering_enforced_when_not_exempt() { - // Default (non-exempt): halted once compute gas exceeds the (tiny) limit. The REX6 × - // system-origin gate that would stamp `Exempt` lives in `MegaContext::on_new_tx`; here we - // exercise the tracker directly. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - assert!(!al.record_compute_gas(1_000_000), "non-exempt tx must report exceeded limit"); - assert!(al.check_limit().exceeded_limit()); - } - - #[test] - fn test_metering_bypassed_when_exempt() { - // When the system-tx exemption is stamped, `check_limit` short-circuits on the sticky - // `Exempt` state, covering the four dimensions *and* gas detention, so the same - // over-limit usage never halts. Usage is still recorded (only the halt decision is - // suppressed). - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.record_compute_gas(1_000_000), "exempt tx must not report exceeded limit"); - assert!(!al.check_limit().exceeded_limit()); - assert!(al.check_limit().is_exempt(), "check_limit must surface the sticky Exempt state"); - assert!(al.get_usage().compute_gas >= 1_000_000, "usage is still accumulated while exempt"); - } - - #[test] - fn test_detained_compute_gas_does_not_halt_when_exempt() { - // Gas detention lowers the detained compute-gas limit; enforcement runs through the same - // `check_limit` chokepoint, so the exemption neutralizes detention too. - let mut al = - AdditionalLimit::new(MegaSpecId::REX6, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX6)); - al.mark_exempt(); - al.set_compute_gas_limit(1); // detain hard - assert!(al.record_compute_gas(10_000_000), "exempt tx must ignore gas detention"); - assert!(!al.check_limit().exceeded_limit()); - } - - #[test] - fn test_reset_clears_exempt() { - // The sticky `Exempt` state must not leak to the next transaction reusing the same tracker. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.has_exceeded_limit.is_exempt()); - al.reset(); - assert!(!al.has_exceeded_limit.is_exempt(), "reset must clear the sticky Exempt state"); - assert!( - al.has_exceeded_limit.within_limit(), - "reset must restore the WithinLimit baseline" - ); - assert!(!al.record_compute_gas(1_000_000), "after reset, metering is enforced again"); - } -} - -#[cfg(test)] -mod tests { - use revm::context::tx::TxEnvBuilder; - - use super::{super::LimitKind, *}; - - fn test_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 100, - tx_kv_updates_limit: 1_000, - tx_compute_gas_limit: 1_000_000, - tx_state_growth_limit: 1_000, - block_env_access_compute_gas_limit: 1_000_000, - oracle_access_compute_gas_limit: 1_000_000, - } - } - - /// Returns the latched limit kind, or `None` when within limit. - fn latched_kind(limit: &AdditionalLimit) -> Option { - match limit.has_exceeded_limit { - LimitCheck::ExceedsLimit { kind, .. } => Some(kind), - LimitCheck::WithinLimit | LimitCheck::Exempt => None, - } - } - - /// Compute gas must be recorded even when another dimension has already latched an - /// exceed: the work was performed, and the recorded total feeds the transaction outcome - /// and block-level compute accounting. A skipped record would under-report compute usage - /// for transactions halted on a non-compute dimension. - /// - /// This pins the `validate()` path: `before_tx_start` latches intrinsic data-size - /// overflow before any frame exists, then the initial gas is recorded. - #[test] - fn test_record_compute_gas_records_after_other_dimension_latched() { - let mut limit = AdditionalLimit::new(MegaSpecId::REX5, test_limits()); - - // Latch the data-size dimension at its mutation site: intrinsic transaction data - // (110-byte base + 200 bytes of calldata) exceeds the 100-byte limit. - let tx = MegaTransaction::new( - TxEnvBuilder::new() - .caller(Address::ZERO) - .call(Address::ZERO) - .data(vec![0u8; 200].into()) - .build_fill(), - ); - limit.before_tx_start(&tx); - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - - // The trailing compute-gas record of the same opcode must still surface the latched - // exceed AND record the gas. - assert!(!limit.record_compute_gas(5_000), "latched exceed must surface as false"); - assert_eq!( - limit.get_usage().compute_gas, - 5_000, - "compute gas must be recorded even after another dimension latched", - ); - - // The latched kind is preserved (not overwritten by the compute-gas check). - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - } - - /// SELFDESTRUCT's beneficiary usage is recorded *before* the inner instruction runs and - /// must NOT latch at the recording site: the inner instruction can still fail (out of - /// gas, DB error), in which case the frame pops the discardable usage and a latch taken - /// at recording time would stick and misattribute the failure. The latch belongs to the - /// trailing all-dimension check, which only runs after the inner instruction succeeds. - #[test] - fn test_selfdestruct_usage_latches_only_at_trailing_check() { - let mut limits = test_limits(); - // Below the 40-byte account-info write, so the beneficiary creation exceeds it. - limits.tx_data_size_limit = 10; - let mut limit = AdditionalLimit::new(MegaSpecId::REX5, limits); - // Simulate an active call frame (SELFDESTRUCT always runs inside one). - limit.push_empty_frame(); - - // Recording site: usage recorded, but no latch yet (inner instruction may still fail). - limit.on_selfdestruct_new_account(); - assert_eq!(latched_kind(&limit), None, "recording site must not latch"); - - // Trailing all-dimension check (runs only after inner success): latches and halts. - assert!(!limit.record_compute_gas_all_dims(100), "trailing check must surface exceed"); - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - } - - /// `intrinsic_check_for_tx` is a REX5-only preflight (EIP-7702 authority growth); - /// its `debug_assert!(spec.is_enabled(REX5))` precondition must reject a pre-REX5 - /// spec. Calling it at REX4 must trip the assert. - /// - /// Kills the spec-gate mutant `is_enabled(MegaSpecId::REX5) -> is_enabled(REX4)` at - /// limit.rs:203: under the mutant the precondition would silently accept REX4 and the - /// call would return a `LimitCheck` instead of panicking. - #[test] - #[should_panic(expected = "REX5")] - #[cfg(debug_assertions)] - fn test_intrinsic_check_for_tx_requires_rex5_spec() { - let tx = MegaTransaction::new( - TxEnvBuilder::new().caller(Address::ZERO).call(Address::ZERO).build_fill(), - ); - // REX4 < REX5: the precondition assert must fire. - let _ = AdditionalLimit::intrinsic_check_for_tx(MegaSpecId::REX4, &tx, test_limits()); - } -} diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs deleted file mode 100644 index a536565af..000000000 --- a/crates/mega-evm/src/limit/mod.rs +++ /dev/null @@ -1,208 +0,0 @@ -use alloy_primitives::Bytes; -use alloy_sol_types::SolError; - -mod compute_gas; -mod data_size; -mod frame_limit; -mod kv_update; -#[allow(clippy::module_inception)] -mod limit; -mod state_growth; -mod storage_call_stipend; - -pub use data_size::*; -pub(crate) use frame_limit::{FrameLimitTracker, TxRuntimeLimit}; -pub use limit::*; - -use crate::MegaHaltReason; - -alloy_sol_types::sol! { - /// ABI-encoded error emitted as revert data when a frame-local resource limit is exceeded. - #[derive(Debug, PartialEq, Eq)] - error MegaLimitExceeded(uint8 kind, uint64 limit); -} - -/// Identifies which resource limit was exceeded. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum LimitKind { - /// Data size limit (bytes of data transmitted and stored). - DataSize, - /// Key-value update limit (number of state-modifying operations). - KVUpdate, - /// Compute gas limit (cumulative EVM instruction gas). - ComputeGas, - /// State growth limit (net new accounts and storage slots). - StateGrowth, -} - -impl LimitKind { - /// Returns the discriminant value used in ABI-encoded revert data. - pub const fn as_u8(&self) -> u8 { - match self { - Self::DataSize => 0, - Self::KVUpdate => 1, - Self::ComputeGas => 2, - Self::StateGrowth => 3, - } - } - - /// Converts a discriminant value back to a `LimitKind`. - pub const fn from_u8(kind: u8) -> Option { - match kind { - 0 => Some(Self::DataSize), - 1 => Some(Self::KVUpdate), - 2 => Some(Self::ComputeGas), - 3 => Some(Self::StateGrowth), - _ => None, - } - } -} - -/// Result of a limit check. -/// -/// Carries three semantically distinct states: limits passed; a limit was exceeded (with -/// metadata for the halt path); or per-tx metering is exempt (REX6+ system-originated tx — -/// see [`crate::is_system_originated`]). The `Exempt` state is **sticky**: once `AdditionalLimit` -/// stores it in `has_exceeded_limit`, `check_limit` short-circuits and the sub-tracker checks -/// are skipped, so no later overflow can overwrite it. -#[derive(Debug, Default, Clone, Copy)] -pub enum LimitCheck { - /// All limits are within their configured thresholds. - #[default] - WithinLimit, - /// A limit has been exceeded. - ExceedsLimit { - /// Which resource limit was exceeded. - kind: LimitKind, - /// The configured limit. - limit: u64, - /// The current usage. - used: u64, - /// Whether this exceed is from a frame-local budget (absorbable at frame boundary) - /// vs a TX-level limit (must propagate to halt the transaction). - frame_local: bool, - }, - /// Per-tx metering is exempt: REX6+ system-originated tx (see - /// [`crate::is_system_originated`]). Behaves as not-exceeded for halt decisions; sticky as - /// described on the enum. Sub-tracker `check_limit` impls never produce this variant — - /// only `AdditionalLimit::has_exceeded_limit` carries it, set via - /// [`AdditionalLimit::mark_exempt`](super::AdditionalLimit::mark_exempt). - Exempt, -} - -impl LimitCheck { - /// Returns `true` if a resource limit has been exceeded. - /// - /// `Exempt` returns `false`: per-tx metering is suppressed, so the halt path must not fire. - #[inline] - pub const fn exceeded_limit(&self) -> bool { - matches!(self, Self::ExceedsLimit { .. }) - } - - /// Returns `true` strictly when no limit check has been performed yet or the last check passed. - /// - /// `Exempt` returns `false`: it is a distinct sticky state, not a "passed" result. Callers - /// that just want to gate the halt path should use [`exceeded_limit`](Self::exceeded_limit) - /// (its negation), not this predicate. - #[inline] - pub const fn within_limit(&self) -> bool { - matches!(self, Self::WithinLimit) - } - - /// Returns `true` when per-tx metering is suppressed for the current transaction. - #[inline] - pub const fn is_exempt(&self) -> bool { - matches!(self, Self::Exempt) - } - - /// Returns whether this is a frame-local exceed. - #[inline] - pub const fn is_frame_local(&self) -> bool { - matches!(self, Self::ExceedsLimit { frame_local: true, .. }) - } - - /// Returns ABI-encoded revert data for a frame-local limit exceed. - /// - /// Encodes as `MegaLimitExceeded(uint8 kind, uint64 limit)`. Returns empty bytes for - /// `WithinLimit` and `Exempt` (neither produces a frame-local revert). - pub fn revert_data(&self) -> Bytes { - match self { - Self::ExceedsLimit { kind, limit, .. } => { - MegaLimitExceeded { kind: kind.as_u8(), limit: *limit }.abi_encode().into() - } - Self::WithinLimit | Self::Exempt => Bytes::new(), - } - } - - /// Returns the [`MegaHaltReason`] if a limit has been exceeded. - /// - /// `WithinLimit` and `Exempt` both return `None`: neither halts the transaction. - pub fn maybe_halt_reason(&self) -> Option { - match self { - Self::ExceedsLimit { kind: LimitKind::DataSize, limit, used, .. } => { - Some(MegaHaltReason::DataLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::KVUpdate, limit, used, .. } => { - Some(MegaHaltReason::KVUpdateLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::ComputeGas, limit, used, .. } => { - Some(MegaHaltReason::ComputeGasLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used, .. } => { - Some(MegaHaltReason::StateGrowthLimitExceeded { limit: *limit, actual: *used }) - } - Self::WithinLimit | Self::Exempt => None, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Pins the predicate truth-table for the `Exempt` variant so a future change that flips one - /// predicate (e.g., reverting `exceeded_limit` to `!matches!(WithinLimit)`) is caught here - /// rather than silently re-enabling halts for exempt txs. - #[test] - fn test_limit_check_exempt_predicate_truth_table() { - let exempt = LimitCheck::Exempt; - assert!(!exempt.exceeded_limit()); - assert!(!exempt.within_limit()); - assert!(exempt.is_exempt()); - assert!(!exempt.is_frame_local()); - assert!(exempt.revert_data().is_empty()); - assert!(exempt.maybe_halt_reason().is_none()); - } - - /// `within_limit` must mirror the enum variant exactly, not return a constant. - #[test] - fn test_within_limit_reflects_variant() { - assert!(LimitCheck::WithinLimit.within_limit()); - let exceeded = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: 150, - frame_local: false, - }; - assert!(!exceeded.within_limit()); - } - - /// Every `LimitKind` discriminant must survive an `as_u8` -> `from_u8` round-trip, - /// and unknown discriminants must map to `None`. - #[test] - fn test_limit_kind_u8_roundtrip() { - for kind in [ - LimitKind::DataSize, - LimitKind::KVUpdate, - LimitKind::ComputeGas, - LimitKind::StateGrowth, - ] { - assert_eq!( - LimitKind::from_u8(kind.as_u8()), - Some(kind), - "round-trip failed for {kind:?}" - ); - } - assert_eq!(LimitKind::from_u8(4), None); - } -} diff --git a/crates/mega-evm/src/limit/state_growth.rs b/crates/mega-evm/src/limit/state_growth.rs deleted file mode 100644 index 758eafbc6..000000000 --- a/crates/mega-evm/src/limit/state_growth.rs +++ /dev/null @@ -1,380 +0,0 @@ -//! # State Growth Tracking -//! -//! This module implements tracking of **net state growth** during transaction execution. -//! State growth measures the expansion of blockchain state by counting new accounts and -//! storage slots created, offset by any that are cleared. -//! -//! ## What Counts as State Growth -//! -//! State growth is measured in discrete units, where each unit represents: -//! -//! - **+1** for creating a new account via `CREATE` / `CREATE2` (net-new address under REX6+; -//! unconditional under pre-REX6) or via `CALL` with value transfer to an empty account -//! - **+1** for each valid EIP-7702 authorization that creates a previously non-existent authority -//! account (Rex5+) -//! - **+1** for writing a storage slot from zero to non-zero for the first time -//! - **-1** for clearing a storage slot back to zero (only when the slot was empty at transaction -//! start) -//! -//! ## Net Growth Model -//! -//! This implementation uses a **net growth** model, meaning: -//! - The counter increases when state is created -//! - The counter decreases when state is cleared -//! - The internal `total_growth` can temporarily become negative during execution -//! - The externally reported growth is clamped to a minimum of zero -//! -//! ### Example: Net Growth Calculation -//! -//! ```text -//! Transaction creates 3 new storage slots: total_growth = +3 -//! Transaction clears 1 slot back to zero: total_growth = +2 -//! Transaction clears 2 more slots: total_growth = 0 -//! ``` -//! -//! ## Frame-Based Tracking -//! -//! State growth is tracked using a frame stack that mirrors the EVM's call frame stack. -//! This ensures proper handling of reverts: -//! -//! - Each `CALL`/`CREATE` pushes a new frame -//! - Growth within a frame is tracked as "discardable" (can be reverted) -//! - On successful frame exit, growth is merged into the parent frame -//! - On failed frame exit (revert), growth is discarded -//! -//! ### Example: Frame Revert Behavior -//! -//! ```text -//! Main transaction starts: Frame 0: discardable = 0 -//! Main creates 2 storage slots: Frame 0: discardable = 2, total = 2 -//! Main calls contract A: Frame 1: discardable = 0 -//! Contract A creates 3 storage slots: Frame 1: discardable = 3, total = 5 -//! Contract A calls contract B: Frame 2: discardable = 0 -//! Contract B creates 1 storage slot: Frame 2: discardable = 1, total = 6 -//! Contract B reverts: Frame 2 discarded, total = 5 -//! Contract A completes successfully: Frame 1 merged to Frame 0, total = 5 -//! Transaction completes: Final growth = 5 -//! ``` -//! -//! ## EIP-161 Compliance -//! -//! The tracker implements EIP-161 account clearing rules: -//! - Only `CALL`-like opcodes with value transfer to empty accounts count as creating an account -//! - `CALL` without value transfer to empty accounts does not count (empty account remains empty) -//! -//! ## Storage Slot Tracking -//! -//! Storage slot state transitions are tracked based on three values: -//! - `original_value`: Value at the start of the transaction -//! - `present_value`: Current value before the SSTORE -//! - `new_value`: Value being written -//! -//! Only transitions that affect the **transaction-level** state growth are counted: -//! - `(zero, zero, non-zero)`: First write to empty slot → **+1** -//! - `(zero, non-zero, zero)`: Clear a slot that was empty at transaction start → **-1** -//! - Other transitions: No change (slot was already non-zero at transaction start) - -use alloy_primitives::{Address, U256}; -use revm::{ - handler::FrameResult, - interpreter::{interpreter_action::FrameInit, FrameInput, SStoreResult}, - primitives::hardfork::SpecId, -}; - -use crate::{FrameLimitTracker, JournalInspectTr, MegaSpecId, TxRuntimeLimit}; - -/// A tracker for net state growth during transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware tracking with per-frame budgets (Rex4+). -/// -/// State growth measures the expansion of blockchain state by counting new accounts and -/// storage slots created, offset by any that are cleared: -/// -/// - **+1** for creating a new account via `CREATE` / `CREATE2` (net-new address under REX6+; -/// unconditional under pre-REX6) or via `CALL` with value transfer to an empty account (EIP-161) -/// - **+1** for each valid EIP-7702 authorization that creates a previously non-existent authority -/// account (Rex5+) -/// - **+1** for writing a storage slot from zero to non-zero for the first time -/// - **-1** for clearing a storage slot back to zero (only when the slot was empty at transaction -/// start) -/// -/// See module-level documentation for details on the net growth model and frame-based tracking. -#[derive(Debug, Clone)] -pub(crate) struct StateGrowthTracker { - spec: MegaSpecId, - frame_tracker: FrameLimitTracker<()>, -} - -impl StateGrowthTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { spec, frame_tracker: FrameLimitTracker::new(spec, tx_limit) } - } - - /// Pushes a new frame onto the tracker. - /// - /// For Rex4+, delegates to `FrameLimitTracker::push_frame()` which uses - /// `tx_entry.remaining()` for the top-level frame and parent's remaining × 98/100 - /// for nested frames. - /// For pre-Rex4, pushes with `u64::MAX` since per-frame limits are not enforced - /// (the TX-level check in `check_limit()` uses `net_usage()` instead). - fn push_frame(&mut self) { - if self.spec.is_enabled(MegaSpecId::REX4) { - self.frame_tracker.push_frame(()); - } else { - self.frame_tracker.push_frame_with_limit(u64::MAX, ()); - } - } - - /// Records positive state growth in the current frame. - pub(crate) fn record_growth(&mut self, n: u64) { - // For state growth, all growth in the current transaction is discardable on revert. - self.frame_tracker.add_frame_discardable(n); - } - - /// Records a refund (negative growth) in the current frame. - fn record_refund(&mut self, n: u64) { - self.frame_tracker.add_frame_refund(n); - } - - /// REX5+: record +1 net state growth for the materialisation of an empty deposit - /// caller during `OpHandler::pre_execution` (mint balance increment and/or nonce - /// bump). This event does not correspond to any EVM frame, so the +1 is written - /// directly to the TX intrinsic lane (`tx_entry.persistent_usage`) — same lane - /// `before_tx_start` uses for other intrinsic accounting. - pub(crate) fn record_deposit_caller_creation(&mut self) { - self.frame_tracker.add_tx_persistent(1); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox state growth consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Records EIP-7702 authority accounts that were created by pre-execution auth processing. - /// - /// This is TX-level persistent usage because authorization-list changes are applied before the - /// first EVM frame and are not discarded by frame revert. - pub(crate) fn record_authority_creations(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining state growth budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.spec.is_enabled(MegaSpecId::REX4) { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for StateGrowthTracker { - /// Returns the current effective state growth limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current net state growth across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - /// Resets the tracker to its initial state. - /// - /// This clears the frame stack, preparing the tracker for a new transaction. - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the state growth limit has been exceeded. - /// - /// For Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic usage written directly to `tx_entry` — - /// notably the REX5+ deposit-caller-creation record and Rex5 pre-frame authority - /// usage — and any frame-level overflow that has already been popped into `tx_entry`. - /// For pre-Rex4, checks total net growth across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.spec.is_enabled(MegaSpecId::REX4) { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::StateGrowth); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: catches Rex5 pre-frame authority usage and any - // future TX-level state-growth contribution. - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::StateGrowth, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// No-op. - /// - /// REX5 EIP-7702 authority state growth is journal-dependent, so it is recorded later during - /// pre-execution via `record_authority_creations()` rather than from transaction-only data. - fn before_tx_start(&mut self, _tx: &crate::MegaTransaction) {} - - /// Called when inspector intercepts and skips a call/create. - /// - /// Pushes an empty frame so `before_frame_return_result` can pop it to keep - /// the frame stack aligned with the EVM's call stack. - #[inline] - fn push_empty_frame(&mut self) { - self.push_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Pushes a new frame onto the tracker and records any state growth caused by - /// the frame initialization itself: - /// - /// - **Call with value transfer to empty account**: +1 growth (EIP-161 compliant). Only - /// `CALL`-like opcodes with value transfer to empty accounts count as creating an account. - /// `CALL` without value transfer does not count (empty account remains empty). - /// - **Create** (`CREATE` / `CREATE2`): +1 growth when deploying to a net-new address (REX6+); - /// unconditional +1 for pre-REX6 specs. - /// - **Call without value transfer** or **call to non-empty account**: no growth. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - self.push_frame(); - - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - // EIP-161: only value transfers to empty accounts count as creating an account. - if call_inputs.transfers_value() { - // REX5+: use non-delegating inspection to get the authority's own state. - let to_account = if self.spec.is_enabled(MegaSpecId::REX5) { - journal.inspect_account(call_inputs.target_address, false)? - } else { - journal.inspect_account_delegated(self.spec, call_inputs.target_address)? - }; - let is_empty = to_account.state_clear_aware_is_empty(SpecId::PRAGUE); - if is_empty { - self.record_growth(1); - } - } - } - FrameInput::Create(create_inputs) => { - if self.spec.is_enabled(MegaSpecId::REX6) { - // REX6: count only net-new accounts. `before_frame_init` runs before revm bumps - // the caller nonce, so the caller's current state nonce is the `old_nonce` the - // deployment uses; derive the target and skip the +1 when it already exists - // (e.g. a pre-funded balance-only account). - let caller_nonce = - journal.inspect_account(create_inputs.caller, false)?.info.nonce; - let created_address = create_inputs.created_address(caller_nonce); - let to_account = journal.inspect_account(created_address, false)?; - if to_account.state_clear_aware_is_empty(SpecId::PRAGUE) { - self.record_growth(1); - } - } else { - self.record_growth(1); - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// Updates the frame's growth and refund counters based on the storage slot's state - /// transition. - /// Only transitions that affect **transaction-level** state growth are counted: - /// - /// | Original | Present | New | Effect | Reason | - /// |----------|---------|-------|------------|---------------------------------------------| - /// | zero | zero | non-0 | +1 growth | First write to empty slot | - /// | zero | non-0 | zero | +1 refund | Clear slot that was empty at tx start | - /// | zero | non-0 | non-0 | — | Already counted when first written | - /// | non-0 | * | * | — | Slot existed at tx start, no growth change | - /// - /// # Examples - /// - /// ```text - /// Slot starts at 0, write 5: +1 (new storage) - /// Slot starts at 0, write 5, write 10: +1 (only counted once) - /// Slot starts at 0, write 5, write 0: 0 (created then cleared via refund) - /// Slot starts at 5, write 10: 0 (already existed) - /// ``` - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - match ( - store_result.original_value.is_zero(), - store_result.present_value.is_zero(), - store_result.new_value.is_zero(), - ) { - (true, true, false) => { - // First write to empty slot: slot goes from zero to non-zero → +1 - self.record_growth(1); - } - (true, false, true) => { - // Clear slot: was zero at tx start, became non-zero, now back to zero → -1 - self.record_refund(1); - } - _ => { - // No state growth change: - // - (zero, non-zero, non-zero): Already counted when first written - // - (non-zero, _, _): Slot existed at tx start, modifications don't count - } - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Pops the current frame from the tracker and handles its accumulated state growth: - /// - **On success**: merges the frame's growth and refunds into the parent frame via - /// `pop_frame::()`. - /// - **On revert/failure**: discards the frame's discardable growth (refunds and persistent - /// usage are still propagated) via `pop_frame::()`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - self.frame_tracker.pop_frame(result.instruction_result().is_ok()); - } - - /// Hook called after a SELFDESTRUCT on a same-TX-created account (REX4+). - /// - /// Records a refund for the account and its new storage slots that were - /// previously counted as state growth. This is frame-aware: if the frame reverts, - /// both the SELFDESTRUCT and the refund are discarded together. - fn after_selfdestruct(&mut self, refund: u64) { - self.record_refund(refund); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `reset` must clear accumulated TX-level state-growth usage so a tracker reused - /// across transactions does not leak growth from the previous one. - #[test] - fn test_reset_clears_accumulated_usage() { - let mut tracker = StateGrowthTracker::new(MegaSpecId::MINI_REX, 100); - tracker.record_deposit_caller_creation(); - assert_eq!(tracker.tx_usage(), 1, "recorded growth should be reflected in tx_usage"); - - tracker.reset(); - assert_eq!(tracker.tx_usage(), 0, "reset must clear accumulated state growth"); - } -} diff --git a/crates/mega-evm/src/limit/storage_call_stipend.rs b/crates/mega-evm/src/limit/storage_call_stipend.rs deleted file mode 100644 index 93a99bbc7..000000000 --- a/crates/mega-evm/src/limit/storage_call_stipend.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Tracks the `STORAGE_CALL_STIPEND` granted to value-transferring `CALL` / `CALLCODE` -//! frames. Two spec-gated models share this tracker. -//! -//! REX5+ uses a separated allowance: `call_inputs.gas_limit` is not inflated, and the -//! five `storage_gas_ext` charging sites (CALL/CALLCODE new-account, CREATE/CREATE2, -//! SSTORE first-time-write, LOG, SELFDESTRUCT) drain `try_consume` before charging the -//! residual against EVM `Gas`. `additional_limit_ext::{sstore, log}` are not consumers — -//! they check non-gas dimensions only. -//! -//! REX4 uses the legacy inflation: `call_inputs.gas_limit` is inflated by -//! `STORAGE_CALL_STIPEND`, the per-frame compute budget is capped at the pre-inflation -//! limit, and unused stipend is burned on return by clamping `gas.remaining()`. Preserved -//! byte-for-byte for replay parity. -//! -//! Pre-REX4 specs do not grant a stipend; both models collapse to a zero-allowance no-op. -//! Synthetic system-contract interception results that short-circuit `frame_init` push a -//! zero-allowance entry for stack alignment. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use revm::{ - handler::FrameResult, - interpreter::{interpreter_action::FrameInit, CallScheme, FrameInput, Gas}, -}; - -use super::compute_gas; -use crate::{constants, MegaSpecId}; - -/// Tracks per-frame `STORAGE_CALL_STIPEND` grants. -/// -/// See the module-level doc for the dual-mode (REX5+ separated allowance vs REX4 -/// legacy inflation) design and its rationale. -#[derive(Debug, Clone)] -pub(crate) struct StorageCallStipendTracker { - /// Per-spec stipend grant amount. 0 for pre-REX4 (disabled). - stipend_amount: u64, - /// `true` for REX5+ (separated-allowance model); `false` for REX4 and pre-REX4 - /// (legacy inflation model, including the no-stipend case where - /// `stipend_amount == 0`). - rex5_enabled: bool, - /// Per-frame stipend state. Pushed in `before_frame_init` / `push_empty_frame`, - /// popped in `before_frame_return_result`. - stack: Vec, -} - -/// Per-frame stipend state. -/// -/// `remaining` is the REX5+ separated-allowance balance. `legacy_inflated` is `true` -/// iff this frame was granted a REX4 `gas.limit()` inflation and must burn unused -/// stipend on return; `false` for REX5+ grants, empty frames, and pre-REX4. -#[derive(Debug, Clone, Copy, Default)] -struct StipendFrame { - remaining: u64, - legacy_inflated: bool, -} - -impl StorageCallStipendTracker { - pub(crate) fn new(spec: MegaSpecId) -> Self { - Self { - stipend_amount: Self::stipend_for_spec(spec), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - stack: Vec::new(), - } - } - - /// Returns the stipend amount for the given spec. Zero for pre-REX4. - fn stipend_for_spec(spec: MegaSpecId) -> u64 { - if spec.is_enabled(MegaSpecId::REX4) { - constants::rex4::STORAGE_CALL_STIPEND - } else { - 0 - } - } - - pub(crate) fn reset(&mut self) { - self.stack.clear(); - } - - /// Pushes a zero-allowance entry for an empty frame (synthetic system-contract - /// interception result or inspector early-return). Keeps the stack aligned with - /// the EVM frame stack so subsequent pops match. - pub(crate) fn push_empty_frame(&mut self) { - self.stack.push(StipendFrame::default()); - } - - /// Drains up to `amount` from the current frame's allowance and returns the - /// portion drained. The caller charges the residual via the original site's - /// gas-charging macro (`gas!` or `gas_or_fail!`). Returns 0 pre-REX5; REX4 covers - /// storage via `gas.limit()` inflation and does not draw from this allowance. - pub(crate) fn try_consume(&mut self, amount: u64) -> u64 { - if !self.rex5_enabled { - return 0; - } - let Some(frame) = self.stack.last_mut() else { - return 0; - }; - let drained = frame.remaining.min(amount); - frame.remaining -= drained; - drained - } - - /// Pushes a per-frame entry. REX5+ records the grant as an internal allowance. - /// REX4 inflates `call_inputs.gas_limit`, caps the per-frame compute budget, and - /// records the pre-inflation limit for the return-time burn clamp. - /// - /// Must be called **after** `compute_gas.before_frame_init()` so the compute frame - /// exists for the REX4 cap-tightening. - pub(crate) fn before_frame_init( - &mut self, - frame_init: &mut FrameInit, - compute_gas: &mut compute_gas::ComputeGasTracker, - ) { - if !self.detect_grant(frame_init) { - self.stack.push(StipendFrame::default()); - return; - } - - if self.rex5_enabled { - // REX5+ separated-allowance model: no gas_limit mutation, no compute cap. - self.stack - .push(StipendFrame { remaining: self.stipend_amount, legacy_inflated: false }); - return; - } - - // REX4 legacy inflation model. - let FrameInput::Call(call_inputs) = &mut frame_init.frame_input else { - // `detect_grant` only returns true for Call frames, so this branch is - // unreachable. Defend against future divergence. - self.stack.push(StipendFrame::default()); - return; - }; - let pre_inflation_limit = call_inputs.gas_limit; - call_inputs.gas_limit = call_inputs.gas_limit.saturating_add(self.stipend_amount); - compute_gas.cap_current_frame_limit(pre_inflation_limit); - // REX4 stores the full grant in `remaining` so `current_frame_stipend()` can - // surface it to `effective_remaining_for_rescue`. `try_consume` is a no-op on - // REX4, so the value stays static. - self.stack.push(StipendFrame { remaining: self.stipend_amount, legacy_inflated: true }); - } - - /// Pops the per-frame entry. REX4 also burns unused stipend by clamping - /// `gas.remaining()` to `gas.limit().saturating_sub(stipend_amount)` so the caller - /// never recovers more than the pre-stipend limit. Deriving the cap from - /// post-inflation `gas.limit()` matches the saturating-add at inflation time. - /// REX5 has nothing to burn (the allowance never entered `gas.limit()`). - /// - /// `LAST_FRAME` matches the other trackers' hook signature so the top-level - /// duplicate `last_frame_result` call can safely no-op on an empty stack. - pub(crate) fn before_frame_return_result( - &mut self, - result: &mut FrameResult, - ) { - assert!(LAST_FRAME || !self.stack.is_empty(), "frame stack is empty"); - let frame = self.stack.pop().unwrap_or_default(); - if self.rex5_enabled { - // REX5+: nothing to burn — `gas.limit()` never held stipend. - return; - } - if frame.legacy_inflated { - let gas = result.gas_mut(); - // Derive the burn cap from post-inflation `gas.limit()` so the saturating - // arithmetic mirrors the inflation site exactly. - let original_limit = gas.limit().saturating_sub(self.stipend_amount); - let burn = gas.remaining().saturating_sub(original_limit); - if burn > 0 { - let _ = gas.record_cost(burn); - } - } - } - - /// Current frame's stipend balance. REX5: remaining (un-drained) allowance. REX4: - /// the original grant amount (static; used by `effective_remaining_for_rescue` to - /// exclude the inflated portion from the rescued-gas refund). Pre-REX4: 0. - pub(crate) fn current_frame_stipend(&self) -> u64 { - self.stack.last().map(|frame| frame.remaining).unwrap_or(0) - } - - /// Portion of `gas.remaining()` to add to `rescued_gas` on a TX-level limit exceed. - /// REX5 returns `gas.remaining()` directly (allowance never entered `gas.limit()`). - /// REX4 excludes the current frame's stipend so system-granted gas is not refunded - /// to the sender. - pub(crate) fn effective_remaining_for_rescue(&self, gas: &Gas) -> u64 { - if self.rex5_enabled { - return gas.remaining(); - } - let stipend = self.current_frame_stipend(); - if stipend > 0 { - let original_limit = gas.limit().saturating_sub(stipend); - gas.remaining().min(original_limit) - } else { - gas.remaining() - } - } - - /// Returns `true` if the given `frame_init` qualifies for a stipend grant. - /// - /// The stipend is granted to value-transferring internal `CALL`/`CALLCODE` - /// frames (depth > 0). Top-level transaction frames, non-value-transfer - /// CALL/CALLCODE, DELEGATECALL/STATICCALL, and CREATE/CREATE2 do not qualify. - fn detect_grant(&self, frame_init: &FrameInit) -> bool { - if self.stipend_amount == 0 { - return false; - } - let FrameInput::Call(call_inputs) = &frame_init.frame_input else { - return false; - }; - let is_internal_call = frame_init.depth != 0; - let is_value_transfer = call_inputs.transfers_value(); - let is_call_or_callcode = - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode); - is_internal_call && is_value_transfer && is_call_or_callcode - } -} diff --git a/crates/mega-evm/src/sandbox/error.rs b/crates/mega-evm/src/sandbox/error.rs deleted file mode 100644 index c5e84d22c..000000000 --- a/crates/mega-evm/src/sandbox/error.rs +++ /dev/null @@ -1,335 +0,0 @@ -//! Error types for sandbox execution. - -use alloy_primitives::Bytes; -use alloy_sol_types::SolError; -use mega_system_contracts::keyless_deploy::IKeylessDeploy; - -use crate::{LimitKind, MegaHaltReason}; - -/// Error types for keyless deployment operations. -/// -/// Most variants map directly to Solidity errors defined in `IKeylessDeploy`. -/// Internal-only variants are mapped at the ABI boundary by `encode_error_result`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum KeylessDeployError { - /// The transaction data is malformed (invalid RLP encoding) - MalformedEncoding, - /// The transaction is not a contract creation (to address is not empty) - NotContractCreation, - /// The transaction is not pre-EIP-155 (v must be 27 or 28) - NotPreEIP155, - /// The nonce in the signed transaction is not zero - NonZeroTxNonce { - /// The nonce value in the signed transaction - tx_nonce: u64, - }, - /// The call tried to transfer ether (maps to `NoEtherTransfer`) - NoEtherTransfer, - /// Failed to recover signer from signature (invalid signature) - InvalidSignature, - /// The signer does not have enough balance to cover the sandbox tx's pre-execution - /// debit: `gas_limit × gas_price + value` on pre-Rex5 specs, `value` only on Rex5+ - /// (where the sandbox tx is fee-free and only the `value` transfer needs funding). - InsufficientBalance, - /// The deploy address already has code (contract already exists) - ContractAlreadyExists, - /// The signer nonce is higher than allowed for keyless deploy - SignerNonceTooHigh { - /// The on-chain nonce of the recovered signer - signer_nonce: u64, - }, - /// The sandbox execution reverted - ExecutionReverted { - /// The gas used - gas_used: u64, - /// The output - output: Bytes, - }, - /// The sandbox execution halted (out of gas, stack overflow, etc.) - ExecutionHalted { - /// The gas used - gas_used: u64, - /// The reason - reason: MegaHaltReason, - }, - /// Rex5 preflight rejected the call: the parent's remaining TX-level budget for some - /// dimension is smaller than the sandbox's known pre-frame intrinsic usage, so the - /// sandbox is guaranteed to fail internally and is not started. - /// - /// Returned as a Revert (like other validation errors) since no sandbox execution - /// has started and no signer state needs to persist. - ParentBudgetExceeded { - /// The dimension whose parent remaining is too small. - kind: LimitKind, - /// The parent's remaining limit for that dimension, i.e. the cap the sandbox - /// would have been given. - limit: u64, - /// The sandbox's known pre-frame intrinsic usage for that dimension. - used: u64, - }, - /// Contract creation succeeded but returned empty bytecode - EmptyCodeDeployed { - /// The gas used - gas_used: u64, - }, - /// Contract creation succeeded but no address was returned (unexpected EVM behavior) - NoContractCreated, - /// The created contract address doesn't match the expected address (internal bug) - AddressMismatch, - /// The gas limit override is less than the gas limit in the keyless transaction - GasLimitTooLow { - /// The gas limit from the keyless transaction - tx_gas_limit: u64, - /// The gas limit override provided by the caller - provided_gas_limit: u64, - }, - /// The remaining compute gas is insufficient to pay for the keyless deploy overhead. - InsufficientComputeGas { - /// The configured compute gas limit - limit: u64, - /// The actual compute gas usage - used: u64, - }, - /// The keyless transaction's init code exceeds the configured maximum init code size. - /// - /// Rex5+ only: the sandbox runs as an OP deposit-like transaction which bypasses - /// op-revm's `validate_env` (where revm's EIP-3860 size check lives), so the sandbox - /// must re-enforce the limit itself against `cfg().max_initcode_size()`. - InitCodeTooLarge { - /// The init code length in bytes. - size: u64, - /// The configured max init code size. - max: u64, - }, - /// The recovered signer has non-empty, non-EIP-7702 bytecode in parent state. - /// - /// Rex5+ only: the deposit-style sandbox bypasses op-revm's EIP-3607 check (which - /// normally lives in `validate_account_nonce_and_code`), so the sandbox enforces it - /// itself before constructing the sandbox transaction. - SignerHasCode, - /// Internal sandbox failure (DB I/O, header validation, etc.). - /// Selector-only so the top-level error ABI stays stable and does not depend on - /// upstream revm/op-revm `Display` text. The interceptor only runs at call depth 0, - /// so this returndata has no inner caller to read it and never reaches a consensus - /// root; the selector-only shape is for off-chain decoder/tooling stability. - InternalError, - /// Sandbox rejected the inner transaction as a tx-validation error - /// (`IsTxError::is_tx_error() == true`). A dedicated selector lets relayer-side - /// decoders distinguish this from a genuine internal failure. Selector-only for the - /// same ABI-stability reason as `InternalError`. - InvalidTransaction, - /// The keylessDeploy call was not intercepted (only returned by Solidity contract for inner - /// calls) - NotIntercepted, -} - -/// Encodes a keyless deploy error as ABI-encoded revert data. -/// -/// Uses the generated Solidity error bindings from IKeylessDeploy.sol. -pub fn encode_error_result(error: KeylessDeployError) -> Bytes { - match error { - KeylessDeployError::MalformedEncoding => { - IKeylessDeploy::MalformedEncoding {}.abi_encode().into() - } - KeylessDeployError::NotContractCreation => { - IKeylessDeploy::NotContractCreation {}.abi_encode().into() - } - KeylessDeployError::NotPreEIP155 => IKeylessDeploy::NotPreEIP155 {}.abi_encode().into(), - KeylessDeployError::NonZeroTxNonce { tx_nonce } => { - IKeylessDeploy::NonZeroTxNonce { txNonce: tx_nonce }.abi_encode().into() - } - KeylessDeployError::NoEtherTransfer => { - IKeylessDeploy::NoEtherTransfer {}.abi_encode().into() - } - KeylessDeployError::InvalidSignature => { - IKeylessDeploy::InvalidSignature {}.abi_encode().into() - } - KeylessDeployError::InsufficientBalance => { - IKeylessDeploy::InsufficientBalance {}.abi_encode().into() - } - KeylessDeployError::ContractAlreadyExists => { - IKeylessDeploy::ContractAlreadyExists {}.abi_encode().into() - } - KeylessDeployError::SignerNonceTooHigh { signer_nonce } => { - IKeylessDeploy::SignerNonceTooHigh { signerNonce: signer_nonce }.abi_encode().into() - } - KeylessDeployError::ExecutionReverted { gas_used, output } => { - IKeylessDeploy::ExecutionReverted { gasUsed: gas_used, output }.abi_encode().into() - } - KeylessDeployError::ExecutionHalted { gas_used, .. } => { - IKeylessDeploy::ExecutionHalted { gasUsed: gas_used }.abi_encode().into() - } - KeylessDeployError::ParentBudgetExceeded { kind, limit, used } => { - IKeylessDeploy::ParentBudgetExceeded { kind: kind.as_u8(), limit, used } - .abi_encode() - .into() - } - KeylessDeployError::EmptyCodeDeployed { gas_used } => { - IKeylessDeploy::EmptyCodeDeployed { gasUsed: gas_used }.abi_encode().into() - } - KeylessDeployError::NoContractCreated => { - IKeylessDeploy::NoContractCreated {}.abi_encode().into() - } - KeylessDeployError::AddressMismatch => { - IKeylessDeploy::AddressMismatch {}.abi_encode().into() - } - KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } => { - IKeylessDeploy::GasLimitTooLow { - txGasLimit: tx_gas_limit, - providedGasLimit: provided_gas_limit, - } - .abi_encode() - .into() - } - KeylessDeployError::InsufficientComputeGas { limit, used } => { - IKeylessDeploy::InsufficientComputeGas { limit, used }.abi_encode().into() - } - KeylessDeployError::InitCodeTooLarge { size, max } => { - IKeylessDeploy::InitCodeTooLarge { size, max }.abi_encode().into() - } - KeylessDeployError::SignerHasCode => IKeylessDeploy::SignerHasCode {}.abi_encode().into(), - KeylessDeployError::InternalError => IKeylessDeploy::InternalError {}.abi_encode().into(), - KeylessDeployError::InvalidTransaction => { - IKeylessDeploy::InvalidTransaction {}.abi_encode().into() - } - KeylessDeployError::NotIntercepted => IKeylessDeploy::NotIntercepted {}.abi_encode().into(), - } -} - -/// Decodes ABI-encoded revert data into a `KeylessDeployError`. -/// -/// Returns `None` if the data doesn't match any known error format. -/// -/// Note: For `ExecutionHalted`, the halt reason cannot be recovered from ABI encoding, -/// so a default `OutOfGas` reason is used. -pub fn decode_error_result(output: &[u8]) -> Option { - if IKeylessDeploy::NoEtherTransfer::abi_decode(output).is_ok() { - return Some(KeylessDeployError::NoEtherTransfer); - } - if IKeylessDeploy::MalformedEncoding::abi_decode(output).is_ok() { - return Some(KeylessDeployError::MalformedEncoding); - } - if IKeylessDeploy::NotContractCreation::abi_decode(output).is_ok() { - return Some(KeylessDeployError::NotContractCreation); - } - if IKeylessDeploy::NotPreEIP155::abi_decode(output).is_ok() { - return Some(KeylessDeployError::NotPreEIP155); - } - if let Ok(e) = IKeylessDeploy::NonZeroTxNonce::abi_decode(output) { - return Some(KeylessDeployError::NonZeroTxNonce { tx_nonce: e.txNonce }); - } - if IKeylessDeploy::InvalidSignature::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InvalidSignature); - } - if IKeylessDeploy::InsufficientBalance::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InsufficientBalance); - } - if IKeylessDeploy::ContractAlreadyExists::abi_decode(output).is_ok() { - return Some(KeylessDeployError::ContractAlreadyExists); - } - if let Ok(e) = IKeylessDeploy::SignerNonceTooHigh::abi_decode(output) { - return Some(KeylessDeployError::SignerNonceTooHigh { signer_nonce: e.signerNonce }); - } - if let Ok(e) = IKeylessDeploy::ExecutionReverted::abi_decode(output) { - return Some(KeylessDeployError::ExecutionReverted { - gas_used: e.gasUsed, - output: e.output, - }); - } - if let Ok(e) = IKeylessDeploy::ExecutionHalted::abi_decode(output) { - // Note: The actual halt reason is lost in ABI encoding, use OutOfGas as placeholder - return Some(KeylessDeployError::ExecutionHalted { - gas_used: e.gasUsed, - reason: MegaHaltReason::Base(op_revm::OpHaltReason::Base( - revm::context::result::HaltReason::OutOfGas( - revm::context::result::OutOfGasError::Basic, - ), - )), - }); - } - if let Ok(e) = IKeylessDeploy::ParentBudgetExceeded::abi_decode(output) { - return Some(KeylessDeployError::ParentBudgetExceeded { - kind: LimitKind::from_u8(e.kind)?, - limit: e.limit, - used: e.used, - }); - } - if let Ok(e) = IKeylessDeploy::EmptyCodeDeployed::abi_decode(output) { - return Some(KeylessDeployError::EmptyCodeDeployed { gas_used: e.gasUsed }); - } - if IKeylessDeploy::NoContractCreated::abi_decode(output).is_ok() { - return Some(KeylessDeployError::NoContractCreated); - } - if IKeylessDeploy::AddressMismatch::abi_decode(output).is_ok() { - return Some(KeylessDeployError::AddressMismatch); - } - if let Ok(e) = IKeylessDeploy::GasLimitTooLow::abi_decode(output) { - return Some(KeylessDeployError::GasLimitTooLow { - tx_gas_limit: e.txGasLimit, - provided_gas_limit: e.providedGasLimit, - }); - } - if let Ok(e) = IKeylessDeploy::InitCodeTooLarge::abi_decode(output) { - return Some(KeylessDeployError::InitCodeTooLarge { size: e.size, max: e.max }); - } - if IKeylessDeploy::SignerHasCode::abi_decode(output).is_ok() { - return Some(KeylessDeployError::SignerHasCode); - } - if IKeylessDeploy::InvalidTransaction::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InvalidTransaction); - } - if IKeylessDeploy::InternalError::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InternalError); - } - if IKeylessDeploy::NotIntercepted::abi_decode(output).is_ok() { - return Some(KeylessDeployError::NotIntercepted); - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `InternalError` and `InvalidTransaction` carry no payload on the wire, so a - /// roundtrip MUST produce the same variant. Pinned because these selectors are the - /// off-chain error ABI (RPC, traces, relayer decoders); a divergence between - /// `encode_error_result` and `decode_error_result` would silently break those decoders. - #[test] - fn test_internal_error_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InternalError); - // Selector-only: the encoded form is exactly the 4-byte Solidity selector. - assert_eq!(encoded.len(), 4, "InternalError must be selector-only"); - assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::InternalError))); - } - - #[test] - fn test_invalid_transaction_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InvalidTransaction); - assert_eq!(encoded.len(), 4, "InvalidTransaction must be selector-only"); - assert!(matches!( - decode_error_result(&encoded), - Some(KeylessDeployError::InvalidTransaction) - )); - } - - /// `InitCodeTooLarge { size, max }` is an externally visible ABI selector. Pinning the - /// round-trip catches any drift between the Solidity error definition and the Rust - /// encode/decode (e.g. forgotten arm in `encode_error_result` or `decode_error_result`, - /// or accidental field reordering). - #[test] - fn test_init_code_too_large_roundtrip_preserves_size_and_max() { - let original = KeylessDeployError::InitCodeTooLarge { size: 600_000, max: 548_864 }; - let encoded = encode_error_result(original.clone()); - let decoded = decode_error_result(&encoded).expect("must decode"); - assert_eq!(decoded, original); - } - - /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. - #[test] - fn test_signer_has_code_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::SignerHasCode); - assert_eq!(encoded.len(), 4, "SignerHasCode must be selector-only"); - assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::SignerHasCode))); - } -} diff --git a/crates/mega-evm/src/sandbox/execution.rs b/crates/mega-evm/src/sandbox/execution.rs deleted file mode 100644 index 2782bbf72..000000000 --- a/crates/mega-evm/src/sandbox/execution.rs +++ /dev/null @@ -1,1616 +0,0 @@ -//! Keyless deploy sandbox execution. -//! -//! Implements Nick's Method deterministic deployment via an isolated sandbox. See the -//! module-level `Spam Protection` section in `sandbox/mod.rs` for the invariants that -//! govern when each path is taken (normal completion / Rex5 preflight reject / Rex5 -//! residual-overflow reject / Rex5 sandbox-`validate()` reject). -//! -//! The Rex5 defense layers are implemented here as: `sandbox_runtime_limits` (upfront -//! cap), `sandbox_intrinsic_overflow_error` (preflight), and `reject_if_tx_limit_overflow` -//! (post-merge safety net). -//! -//! Rex5+ runs the sandbox transaction as an OP deposit-like transaction -//! (`gas_price = 0` plus `deposit.source_hash` set, via -//! `build_fee_free_sandbox_deposit_tx`). The deposit-style sandbox tx never debits -//! the inner signer for gas, never credits coinbase or any OP fee vault, and is -//! covered by the outer transaction's own fee model: `gas_limit_override` is -//! pre-debited from the outer `Gas` counter before the sandbox runs and -//! `refund_unused_sandbox_gas` returns the unused portion on exit, mirroring revm's -//! standard message-call accounting. The signer's only state change is the -//! `make_create_frame` nonce bump that serves as the replay barrier. -//! -//! A Rex5 sandbox-`validate()` rejection — the final Mega-side intrinsic / floor -//! gas check inside `MegaHandler::validate` — surfaces in two distinct ways: -//! op-revm's deposit `catch_error` converts tx-validation errors into -//! `Ok(Halt(FailedDeposit, gas_used = gas_limit))`; `process_sandbox_transact_result` -//! maps that back to `KeylessDeployError::InvalidTransaction` so the outer -//! keyless-deploy call surfaces as `Revert`, the sandbox state (including the -//! deposit-`catch_error` nonce bump) is dropped, and `apply_sandbox_post_accounting` -//! is never invoked. Pre-Rex5 specs run the sandbox as a non-deposit transaction: -//! sandbox `pre_execution` debits the signer at the signed gas price, and -//! validation errors propagate as standard `Err(InvalidTransaction)`. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{rc::Rc, vec::Vec}; - -use alloy_consensus::{Signed, Transaction as AlloyTransaction, TxLegacy}; -use alloy_evm::{Database as AlloyDatabase, Evm}; -use alloy_primitives::{Address, Bytes, Log, TxKind, U256}; -use alloy_sol_types::SolCall; -use mega_system_contracts::keyless_deploy::IKeylessDeploy; -use op_revm::{handler::IsTxError, L1BlockInfo}; -use revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - BlockEnv, Cfg, ContextTr, TxEnv, - }, - context_interface::Transaction, - handler::FrameResult, - interpreter::{CallOutcome, Gas, Host, InstructionResult, InterpreterResult}, - primitives::KECCAK_EMPTY, - state::{AccountInfo, EvmState}, - Database as RevmDatabase, -}; -use tracing::{error, warn}; - -use crate::{ - constants, inspect_account_code_hash, mark_frame_result_as_exceeding_limit, AdditionalLimit, - EvmTxRuntimeLimits, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitUsage, MegaContext, - MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, TxRuntimeLimit, VolatileDataAccess, - SANDBOX_TX_SOURCE_HASH, -}; - -use super::{ - state_merge::apply_sandbox_state, - tx::{calculate_keyless_deploy_address, decode_keyless_tx, recover_signer}, -}; - -use super::{ - error::{encode_error_result, KeylessDeployError}, - state::SandboxDb, -}; - -/// Executes a keyless deploy call and returns the frame result. -/// -/// Implements Nick's Method contract deployment: -/// -/// 1. Validates the call (no ether transfer). -/// 2. Decodes the pre-EIP-155 transaction from calldata. -/// 3. Rex5+: pre-checks `keyless_tx.input().len() <= cfg().max_initcode_size()` — op-revm's deposit -/// path bypasses revm's `validate_env`, so the sandbox enforces the configured initcode size -/// limit itself. -/// 4. Validates the gas limit override against the transaction's gas limit. -/// 5. Recovers the signer and calculates the deploy address. -/// 6. Rex5+: pre-charges `new_account_storage_gas(deploy_signer)` against the outer Gas counter -/// when the parent-visible signer is unmaterialized (alongside `KEYLESS_DEPLOY_OVERHEAD_GAS`, -/// retained on every sandbox outcome — see `charge_caller_materialization_pre_sandbox`), then -/// preflights known sandbox intrinsic usage against the parent's remaining resource envelope and -/// reverts with `ParentBudgetExceeded` if it would not fit. -/// 7. Executes contract creation in an isolated sandbox environment. Rex5+ runs the sandbox tx as -/// an OP deposit-like, fee-free transaction with `gas_limit_override` pre-debited from the outer -/// Gas counter. -/// 8. On sandbox completion, refunds the unused portion of the reservation to the outer Gas counter -/// and either merges state (normal path) or rejects without merging (Rex5 overflow safety net), -/// via `apply_sandbox_post_accounting`. -/// -/// Must only be called at `depth == 0` (enforced by `evm/execution.rs`); a wrapping contract -/// must not be able to intercept and revert the charge. See the module-level `Spam Protection` -/// section for the full payment invariants across the Rex5 defense layers (preflight, -/// upfront cap, post-merge safety net, sandbox-`validate()` rejection). -pub fn execute_keyless_deploy_call( - ctx: &mut MegaContext, - call_inputs: &revm::interpreter::CallInputs, - tx_bytes: &Bytes, - gas_limit_override: U256, -) -> FrameResult { - let mut gas = Gas::new(call_inputs.gas_limit); - let return_memory_offset = call_inputs.return_memory_offset.clone(); - - // Frame-result constructors. Using macros (rather than closures) so each call site - // can move `gas` / `return_memory_offset` without borrow-checker conflicts. - // `make_halt!` delegates to the module-level `oog_frame_result` so the OOG shape is - // shared with `reject_if_tx_limit_overflow`. - macro_rules! make_halt { - () => { - oog_frame_result(gas.limit(), &return_memory_offset) - }; - } - - macro_rules! make_error { - ($error:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new(InstructionResult::Revert, encode_error_result($error), gas), - return_memory_offset, - )) - }; - } - - macro_rules! make_success { - ($gas_used:expr, $deployed_address:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - IKeylessDeploy::keylessDeployCall::abi_encode_returns( - &IKeylessDeploy::keylessDeployReturn { - gasUsed: $gas_used, - deployedAddress: $deployed_address, - errorData: Bytes::new(), - }, - ) - .into(), - gas, - ), - return_memory_offset, - )) - }; - } - - // Builds a success-style frame result with the error encoded in `errorData`. Used for - // in-sandbox failures (paired with `apply_sandbox_state` so the consumed replay barrier - // — the signer nonce bump from `make_create_frame` — is merged into the parent). - macro_rules! make_execution_failure { - ($gas_used:expr, $error:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, // Success, not Revert - IKeylessDeploy::keylessDeployCall::abi_encode_returns( - &IKeylessDeploy::keylessDeployReturn { - gasUsed: $gas_used, - deployedAddress: Address::ZERO, - errorData: encode_error_result($error).to_vec().into(), - }, - ) - .into(), - gas, - ), - return_memory_offset, - )) - }; - } - - // Step 1: charge the fixed dispatch overhead (100K covers RLP decoding, sig recovery, - // state filtering). Rex3+ also records it as compute gas. - let cost = constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS; - let has_sufficient_gas = gas.record_cost(cost); - if !has_sufficient_gas { - return make_halt!(); - } - if ctx.spec.is_enabled(MegaSpecId::REX3) { - let mut additional_limit = ctx.additional_limit.borrow_mut(); - if !additional_limit.record_compute_gas(cost) { - let crate::LimitCheck::ExceedsLimit { limit, used, frame_local, .. } = - additional_limit.compute_gas.check_limit() - else { - unreachable!() - }; - return if frame_local { - // Frame-local: revert; gas returns to caller. - make_error!(KeylessDeployError::InsufficientComputeGas { limit, used }) - } else { - // TX-level: halt with OOG, marked as exceeding. - // - // REX6+: rescue the outer `Gas`'s unspent portion (after the - // `KEYLESS_DEPLOY_OVERHEAD_GAS` charge) so it is refunded to the sender, - // matching the per-opcode `compute_gas!` path's TX-level-exceed rescue. - // The eventual `make_halt!` spends `gas.limit()` at the frame level; - // `last_frame_result` then erases `rescued_gas` from the final spend, so - // the receipt's `gas_used` excludes the rescued amount. Pre-REX6 specs - // leave the un-rescued full-spend in place for replay parity. - if ctx.spec.is_enabled(MegaSpecId::REX6) { - additional_limit.try_rescue_gas(&gas); - } - let mut result = make_halt!(); - mark_frame_result_as_exceeding_limit( - &mut result, - crate::AdditionalLimit::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); - result - }; - } - } - - // Step 2: keyless deploys are fee-free. - if !call_inputs.value.get().is_zero() { - return make_error!(KeylessDeployError::NoEtherTransfer); - } - - // Step 3: decode the keyless transaction (Nick's Method requires nonce = 0). - let keyless_tx = match decode_keyless_tx(tx_bytes, ctx.spec) { - Ok(tx) => tx, - Err(e) => return make_error!(e), - }; - if keyless_tx.nonce() != 0 { - return make_error!(KeylessDeployError::NonZeroTxNonce { tx_nonce: keyless_tx.nonce() }); - } - - // Rex5+: enforce the configured init code size limit. Pre-Rex5 specs run the sandbox - // through op-revm's non-deposit path, where revm's `validate_env` enforces it for us. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - let max = ctx.cfg().max_initcode_size(); - let size = keyless_tx.input().len(); - if size > max { - return make_error!(KeylessDeployError::InitCodeTooLarge { - size: size as u64, - max: max as u64, - }); - } - } - - // Step 4: validate `gasLimitOverride` covers the keyless tx's own gas limit. The - // Rex5+ cap is deferred to step 4b below so it observes the materialization charge. - let tx_gas_limit = keyless_tx.gas_limit(); - let mut gas_limit_override_u64: u64 = gas_limit_override.try_into().unwrap_or(u64::MAX); - if gas_limit_override_u64 < tx_gas_limit { - return make_error!(KeylessDeployError::GasLimitTooLow { - tx_gas_limit, - provided_gas_limit: gas_limit_override_u64, - }); - } - - // Step 5: recover the signer and restrict keyless deploys to signer nonce ≤ 1. - // Allowing 1 keeps deploys possible when the signer previously attempted the raw - // keyless tx and failed under MegaETH's gas regime. - let deploy_signer = match recover_signer(&keyless_tx) { - Ok(addr) => addr, - Err(e) => return make_error!(e), - }; - let deploy_address = calculate_keyless_deploy_address(deploy_signer); - - // Rex5+ reads the deploy signer's parent-state account info once via a cold-marked - // `inspect_account`, then drives the upcoming nonce check, EIP-3607 enforcement, and - // materialization charge from that single source. The helper itself gates `load_code` - // on `cfg.disable_eip3607` to preserve the canonical revm - // `validate_account_nonce_and_code` no-`code_by_hash` short-circuit. Pre-Rex5 keeps - // the raw-DB `get_account_nonce` path unchanged to preserve stable-spec semantics - // (no journal cache write for the signer). - let rex5_signer_info = if ctx.spec.is_enabled(MegaSpecId::REX5) { - match inspect_signer_parent_state(ctx, deploy_signer) { - Ok(info) => Some(info), - Err(e) => return make_error!(e), - } - } else { - None - }; - - let signer_nonce = if let Some(info) = &rex5_signer_info { - info.nonce - } else { - match get_account_nonce(ctx, deploy_signer) { - Ok(nonce) => nonce, - Err(e) => return make_error!(e), - } - }; - if signer_nonce > 1 { - return make_error!(KeylessDeployError::SignerNonceTooHigh { signer_nonce }); - } - - if let Some(signer_info) = &rex5_signer_info { - // Rex5+: re-enforce the EIP-3607 caller-with-code check that the deposit-style - // sandbox would otherwise bypass via op-revm's - // `validate_against_state_and_deduct_caller`. - if let Err(e) = validate_signer_code(ctx, signer_info) { - return make_error!(e); - } - - // Rex5+: pre-charge deploy-signer materialization gas (and record the state-growth - // event) before the sandbox is constructed, alongside `KEYLESS_DEPLOY_OVERHEAD_GAS`. - // Upfront timing makes the charge symmetric across all sandbox outcomes (success, - // in-sandbox failure, sandbox-validate reject) and prevents the relayer from sizing - // the outer budget to exclude materialization. - match charge_caller_materialization_pre_sandbox( - ctx, - &mut gas, - deploy_signer, - signer_info, - &return_memory_offset, - ) { - Err(e) => return make_error!(e), - Ok(Some(halt)) => return halt, - Ok(None) => {} - } - } - - // Step 4b: Rex5+ cap of `gas_limit_override` to the outer's remaining gas. Runs after - // materialization has been debited so the reservation in step 8b only covers the - // sandbox envelope itself. - // - // After the cap, re-enforce the signer's "must execute with at least `tx_gas_limit`" - // guarantee. The relayer can shrink the outer envelope so that `gas.remaining()` - // drops below the keyless `tx_gas_limit`, in which case the cap brings the override - // below the signed minimum. Rejecting here with the same `GasLimitTooLow` shape - // surfaces the failure cleanly instead of letting the sandbox OOG silently. The - // pre-cap check above (Step 4) is retained so a relayer passing - // `override < tx_gas_limit` outright still fails before the signer-recovery / - // materialization work. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - gas_limit_override_u64 = gas_limit_override_u64.min(gas.remaining()); - if gas_limit_override_u64 < tx_gas_limit { - return make_error!(KeylessDeployError::GasLimitTooLow { - tx_gas_limit, - provided_gas_limit: gas_limit_override_u64, - }); - } - } - - // Step 6: build the sandbox transaction (nonce forced to 0, raw keyless RLP carried - // in `enveloped_tx`). Rex5+ runs the sandbox tx as an OP deposit-like transaction - // (gas_price=0, source_hash set) so caller balance is never debited for gas; pre-Rex5 - // keeps the original signed gas price. - let sandbox_tx = if ctx.spec.is_enabled(MegaSpecId::REX5) { - build_fee_free_sandbox_deposit_tx( - deploy_signer, - &keyless_tx, - tx_bytes, - gas_limit_override_u64, - ) - } else { - let tx = TxEnv { - caller: deploy_signer, - kind: TxKind::Create, - data: keyless_tx.input().clone(), - value: keyless_tx.value(), - gas_limit: gas_limit_override_u64, - gas_price: keyless_tx.effective_gas_price(None), - nonce: 0, - ..Default::default() - }; - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(tx_bytes.clone()); - mega_tx - }; - - // Step 7: check the deterministic deploy address isn't already occupied. - // - // REX6 reads occupancy through the journaled, cold `inspect_account_code_hash` so the deploy - // address lands in the returned `EvmState` / witness; pre-REX6 keeps the raw `database.basic` - // read that bypasses the journal. The gate is load-bearing: the pre-REX5 legacy merge - // (`apply_sandbox_state_legacy`, `merge_status = false`) does not carry `AccountStatus` through - // an already-`Occupied` journal entry, so journaling this read there would drop a deployed - // address's `Created|Touched` status and let `commit()` discard it — silently losing successful - // pre-REX5 deploys (guarded by - // `test_keyless_deploy_pre_rex6_success_still_commits_deployed_code`). Only the witness - // changes, not the `ContractAlreadyExists` decision — the interceptor fires only at - // `depth == 0`, so while access-list warming may already have journaled `deploy_address` - // (read-only, same `code_hash` as the database), no reachable path can have changed its - // `code_hash` before this check (writing EIP-7702 delegation code to it would require the - // deploy address's own signing key, which does not exist for a CREATE-derived address). - // - // `inspect_account_code_hash` (not `inspect_account(.., false)`) because the occupancy decision - // needs only `code_hash`: `inspect_account`'s already-resident branch force-loads `info.code` - // via `code_by_hash` regardless of `load_code`, so if the outer tx's access list pre-warmed an - // occupied `deploy_address`, that read would demand the address's bytecode in a stateless - // witness carrying only its account proof and turn the expected revert into a spurious DB - // error. - if ctx.spec.is_enabled(MegaSpecId::REX6) { - let deploy_code_hash = inspect_account_code_hash(ctx.journal_mut(), deploy_address) - .map_err(|e| { - error!( - error = %e, - deploy_address = ?deploy_address, - "keyless deploy deploy-address state read failed", - ); - KeylessDeployError::InternalError - }); - match deploy_code_hash { - Ok(code_hash) if code_hash != KECCAK_EMPTY => { - return make_error!(KeylessDeployError::ContractAlreadyExists); - } - Err(e) => return make_error!(e), - _ => {} - } - } else { - let deploy_account = ctx.journal_mut().database.basic(deploy_address).map_err(|e| { - error!( - error = %e, - deploy_address = ?deploy_address, - "keyless deploy deploy-address state read failed", - ); - KeylessDeployError::InternalError - }); - match deploy_account { - Ok(Some(info)) if info.code_hash != KECCAK_EMPTY => { - return make_error!(KeylessDeployError::ContractAlreadyExists); - } - Err(e) => return make_error!(e), - _ => {} - } - } - - // Step 8: Rex5+ preflight. Short-circuits before sandbox setup when the sandbox's - // pre-frame intrinsic alone would exceed the parent's envelope. - let sandbox_tx_limits = - ctx.spec.is_enabled(MegaSpecId::REX5).then(|| sandbox_runtime_limits(ctx)); - if let Some(error) = sandbox_intrinsic_overflow_error(ctx.spec, &sandbox_tx, sandbox_tx_limits) - { - return make_error!(error); - } - - // Step 8b: Rex5+ pre-debit the sandbox's gas reservation from the outer gas counter, - // mirroring revm's standard message-call shape (pre-debit on entry, refund unused on - // exit). The unconditional success follows from step 4b's - // `gas_limit_override.min(gas.remaining())` cap — there is no intervening gas - // movement between the cap and this debit. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - let ok = gas.record_cost(gas_limit_override_u64); - debug_assert!( - ok, - "Rex5+ sandbox pre-debit must succeed: gas_limit_override is capped to gas.remaining()", - ); - } - - // Step 9: Execute sandbox and apply state changes. - match execute_keyless_deploy_sandbox(ctx, sandbox_tx, sandbox_tx_limits) { - SandboxOutcome::Completed { state, completion, limit_usage, volatile_accesses } => { - let gas_used = completion.gas_used(); - - if ctx.spec.is_enabled(MegaSpecId::REX5) { - if let Some(halt) = apply_sandbox_post_accounting( - ctx, - &mut gas, - limit_usage, - volatile_accesses, - gas_limit_override_u64, - gas_used, - &return_memory_offset, - ) { - return halt; - } - } - - if let Err(e) = apply_sandbox_state(ctx, state, deploy_signer) { - return make_error!(e); - } - - // Dispatch ABI return shape. `Deployed` and `EmptyCode` both forward - // constructor logs into the parent receipt (run-to-completion EVM side - // effect); `ExecutionFailed` (Revert / Halt) does not, because revm's - // own frame accounting already rolled the failed frame's logs back. - match completion { - SandboxCompletion::Deployed { gas_used, deploy_address: deployed, logs } => { - if deployed != deploy_address { - return make_error!(KeylessDeployError::AddressMismatch); - } - for log in logs { - ctx.log(log); - } - make_success!(gas_used, deployed) - } - SandboxCompletion::EmptyCode { gas_used, logs } => { - for log in logs { - ctx.log(log); - } - make_execution_failure!( - gas_used, - KeylessDeployError::EmptyCodeDeployed { gas_used } - ) - } - SandboxCompletion::ExecutionFailed { gas_used, error } => { - // Success-style outer return so the merged sandbox state (signer - // nonce bump from `make_create_frame`, plus any committed sandbox - // writes) persists; outer caller sees the failure reason in - // `errorData`. - make_execution_failure!(gas_used, error) - } - } - } - SandboxOutcome::Rejected(e) => { - // Sandbox bailed before producing a frame — typically a validate-reject - // (`FailedDeposit` → `InvalidTransaction`) or an internal error. Refund - // the full reservation; the materialization charge already applied - // upfront is intentionally retained, mirroring the upfront - // `KEYLESS_DEPLOY_OVERHEAD_GAS` charge. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - gas.erase_cost(gas_limit_override_u64); - } - make_error!(e) - } - } -} - -/// Builds a sandbox transaction that runs as an OP deposit-like transaction. -/// -/// Rex5+ only: `source_hash` makes op-revm treat the tx as a deposit (skips L1/operator -/// fee, `validate_env`, balance / nonce check, and `reward_beneficiary` distribution); -/// `gas_price = 0` keeps the deposit-path caller balance escrow at zero so the inner -/// signer is never charged for sandbox gas. `deposit.mint` is explicitly `None` to -/// guarantee no ETH is minted to the signer. -fn build_fee_free_sandbox_deposit_tx( - deploy_signer: Address, - keyless_tx: &Signed, - raw_tx_bytes: &Bytes, - gas_limit: u64, -) -> MegaTransaction { - let tx = TxEnv { - caller: deploy_signer, - kind: TxKind::Create, - data: keyless_tx.input().clone(), - value: keyless_tx.value(), - gas_limit, - gas_price: 0, - nonce: 0, - ..Default::default() - }; - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(raw_tx_bytes.clone()); - mega_tx.deposit.source_hash = SANDBOX_TX_SOURCE_HASH; - mega_tx.deposit.mint = None; - mega_tx -} - -/// Executes the contract creation in a sandbox environment. -/// -/// Uses a type-erased `SandboxDb` to prevent infinite type instantiation. -/// -/// # Arguments -/// -/// * `ctx` - The parent context to execute in -/// * `sandbox_tx` - The transaction to execute, with `enveloped_tx` set to the original raw keyless -/// deploy transaction bytes -pub(crate) fn execute_keyless_deploy_sandbox( - ctx: &mut MegaContext, - sandbox_tx: MegaTransaction, - sandbox_tx_limits: Option, -) -> SandboxOutcome { - let deploy_signer = sandbox_tx.caller(); - let gas_limit = sandbox_tx.gas_limit(); - let gas_price = sandbox_tx.gas_price(); - let value = sandbox_tx.value(); - - // Extract values we need BEFORE borrowing the journal - let mega_spec = ctx.mega_spec(); - let block = ctx.block().clone(); - let chain = ctx.chain().clone(); - - // REX4+: Clone Rc references to parent's external envs before `journal_mut()` mutably - // borrows `ctx`, after which its fields are no longer accessible. - let shared_external_envs = mega_spec - .is_enabled(MegaSpecId::REX4) - .then(|| (Rc::clone(&ctx.salt_env), Rc::clone(&ctx.oracle_env))); - - // Deliberately do not merge `DynamicGasCost.accessed_bucket_ids` back into the - // parent. Sandbox and parent share the same immutable-in-block `SaltEnv`, while - // the sandbox's dynamic-gas cache is intentionally local to that context. - // Revisit if `SaltEnv` becomes block-mutable or bucket ids become a primary - // parallel-EVM conflict signal. - let journal = ctx.journal_mut(); - - // Create type-erased sandbox database with split borrows: - // - Immutable reference to journal state (for cached accounts) - // - Mutable reference to underlying database (for cache misses) - // Override the signer's nonce to 0 for keyless deploy (Nick's Method requires nonce=0) - let mut sandbox_db = SandboxDb::new(&journal.inner.state, &mut journal.database) - .with_nonce_override(deploy_signer); - - // Check signer balance - let signer_account = match sandbox_db.basic(deploy_signer) { - Ok(info) => info.unwrap_or_default(), - Err(e) => { - error!( - error = %e, - deploy_signer = ?deploy_signer, - "keyless deploy signer balance read failed", - ); - return SandboxOutcome::Rejected(KeylessDeployError::InternalError); - } - }; - - // Ensure signer can cover the transfer (and pre-Rex5 also the gas escrow). - // Rex5+ runs the sandbox as a fee-free deposit-like tx (gas_price=0), so the only - // remaining requirement is enough balance for `value`. Pre-Rex5 keeps the - // `gas_cost + value` check, matching its non-deposit sandbox path. - let total_cost = if mega_spec.is_enabled(MegaSpecId::REX5) { - value - } else { - let gas_cost = U256::from(gas_limit) * U256::from(gas_price); - match gas_cost.checked_add(value) { - Some(total) => total, - None => return SandboxOutcome::Rejected(KeylessDeployError::InsufficientBalance), - } - }; - if signer_account.balance < total_cost { - return SandboxOutcome::Rejected(KeylessDeployError::InsufficientBalance); - } - - // Execute sandbox - using type-erased SandboxDb prevents infinite type instantiation. - // The two branches differ only in which MegaContext constructor to use: REX4+ shares - // the parent's salt and oracle envs, while pre-REX4 creates an EmptyExternalEnv for - // backward compatibility. Everything after context construction is identical and is - // factored into `run_sandbox_ctx`. - if let Some((salt_env, oracle_env)) = shared_external_envs { - let sandbox_ctx = MegaContext::<_, ExtEnvs>::new_with_shared_ext_envs( - sandbox_db, mega_spec, salt_env, oracle_env, - ); - run_sandbox_ctx(sandbox_ctx, sandbox_tx, sandbox_tx_limits, block, chain) - } else { - let sandbox_ctx = MegaContext::new(sandbox_db, mega_spec); - run_sandbox_ctx(sandbox_ctx, sandbox_tx, sandbox_tx_limits, block, chain) - } -} - -/// Applies the shared sandbox-context configuration, runs the sandbox tx, and returns the -/// processed outcome. Factored out of `execute_keyless_deploy_sandbox` so the REX4+ and -/// pre-REX4 branches only differ in the `MegaContext` constructor they call. -fn run_sandbox_ctx( - sandbox_ctx: MegaContext, - sandbox_tx: MegaTransaction, - sandbox_tx_limits: Option, - block: BlockEnv, - chain: L1BlockInfo, -) -> SandboxOutcome { - let sandbox_ctx = match sandbox_tx_limits { - Some(limits) => sandbox_ctx.with_tx_runtime_limits(limits), - None => sandbox_ctx, - }; - let sandbox_ctx = sandbox_ctx.with_block(block).with_chain(chain).with_inside_sandbox(true); - let is_rex5_enabled = sandbox_ctx.mega_spec().is_enabled(MegaSpecId::REX5); - let is_rex6_enabled = sandbox_ctx.mega_spec().is_enabled(MegaSpecId::REX6); - let mut sandbox_evm = MegaEvm::new(sandbox_ctx); - let result = sandbox_evm.transact_raw(sandbox_tx); - let limit_usage = sandbox_evm.ctx.additional_limit.borrow().get_usage(); - let volatile_accesses = - sandbox_evm.ctx.volatile_data_tracker.borrow().get_volatile_data_accessed(); - process_sandbox_transact_result( - result, - limit_usage, - volatile_accesses, - is_rex5_enabled, - is_rex6_enabled, - ) -} - -/// Outcome of sandbox execution. -/// -/// Splits the two questions the caller actually has to answer separately: -/// -/// - **`Completed` vs `Rejected`** — did the sandbox EVM run far enough to produce merge-able side -/// effects (state / resource usage / volatile-access footprint / logs)? `Rejected` means the -/// sandbox bailed before producing a frame (validate-reject or internal error); nothing should be -/// applied to the parent context. -/// - **`SandboxCompletion::{Deployed, EmptyCode, ExecutionFailed}`** — when the sandbox did -/// complete, what wire shape should the outer caller report? -/// -/// Logs naturally live on the completion variants where the EVM ran to a -/// non-reverted exit (`Deployed` and `EmptyCode`). `ExecutionFailed` covers -/// Revert / Halt — revm's own frame accounting already rolled those logs back, -/// so there is nothing to forward. -#[derive(Debug)] -pub enum SandboxOutcome { - /// Sandbox EVM ran to a frame exit (success, empty-code success, revert, or - /// halt). State, resource usage, and volatile-access footprint are - /// merge-able into the parent context. - Completed { - /// Sandbox state to merge into the parent context. - state: EvmState, - /// Wire-shape dispatch for what the outer caller should report. - completion: SandboxCompletion, - /// Resource usage from the sandbox's additional limit trackers. - limit_usage: LimitUsage, - /// Volatile-access footprint to merge into the parent after sandbox return. - volatile_accesses: VolatileDataAccess, - }, - /// Sandbox bailed before producing a frame (validate-reject `InvalidTransaction` - /// or `InternalError`). No state, resource usage, or volatile-access footprint - /// applies — the outer caller must refund the full pre-debited reservation. - Rejected(KeylessDeployError), -} - -/// Wire-shape dispatch for a completed sandbox execution. -/// -/// `Deployed` and `EmptyCode` both surface as success-shape outer returns: the -/// outer caller forwards their logs into the parent receipt before encoding the -/// ABI response. `EmptyCodeDeployed` is an ABI-layer "deploy did not stick" -/// signal — it is *not* an EVM execution failure. Pre-REX5 collapses -/// `EmptyCode` into `ExecutionFailed { error: EmptyCodeDeployed }` so logs are -/// dropped, preserving the frozen replay behavior. -/// -/// `ExecutionFailed` covers Revert / Halt. revm rolled the frame's logs back -/// inside the sandbox; there is nothing to forward to the parent. -#[derive(Debug)] -pub enum SandboxCompletion { - /// Inner CREATE succeeded with non-empty runtime bytecode. - Deployed { - /// Gas consumed by the sandbox EVM execution. - gas_used: u64, - /// Address at which the contract was deployed. - deploy_address: Address, - /// Logs emitted by the constructor; forwarded into the parent receipt. - logs: Vec, - }, - /// Inner CREATE succeeded but returned empty runtime bytecode. - /// - /// REX5+ only. Pre-REX5 routes empty-code through `ExecutionFailed` with - /// `EmptyCodeDeployed` so logs are dropped, preserving the frozen replay - /// behavior. - EmptyCode { - /// Gas consumed by the sandbox EVM execution. - gas_used: u64, - /// Logs emitted by the constructor; forwarded into the parent receipt - /// per the keyless-deploy spec's "merged state includes ... logs when - /// applicable" rule. - logs: Vec, - }, - /// Sandbox EVM execution did not result in a successful deploy reachable - /// by the parent. - /// - /// Covers two cases that share an ABI wire shape but have different - /// underlying reasons for not forwarding logs: - /// - `ExecutionResult::Revert` and `ExecutionResult::Halt` — revm already rolled the failed - /// frame's logs back inside the sandbox; nothing exists to forward. - /// - Pre-REX5 `EmptyCodeDeployed` — the constructor ran successfully and emitted logs, but - /// pre-REX5 deliberately drops them at this layer for replay parity. REX5+ uses - /// [`SandboxCompletion::EmptyCode`] to forward them instead. - ExecutionFailed { - /// Gas consumed by the sandbox EVM execution before the failure. - gas_used: u64, - /// ABI-encoded failure reason. - error: KeylessDeployError, - }, -} - -impl SandboxCompletion { - /// Returns the gas consumed by the sandbox EVM. Used by the outer caller to - /// compute the unused reservation to refund. - pub(crate) fn gas_used(&self) -> u64 { - match self { - Self::Deployed { gas_used, .. } | - Self::EmptyCode { gas_used, .. } | - Self::ExecutionFailed { gas_used, .. } => *gas_used, - } - } -} - -/// Processes the result of sandbox EVM execution into a [`SandboxOutcome`]. -/// -/// Handles all execution result variants (success, revert, halt) and transact errors. -/// -/// `transact_raw` errors are split into two `KeylessDeployError` variants by selector -/// so relayer-side decoders can tell them apart: -/// - `InvalidTransaction` when `IsTxError::is_tx_error()` returns `true`. -/// - `InternalError` for everything else (DB I/O, header validation, `EVMError::Custom`). -/// -/// `is_rex5_enabled` gates the empty-code branch: REX5+ produces -/// [`SandboxCompletion::EmptyCode`] (which forwards the constructor's emitted logs into -/// the parent receipt per the keyless-deploy spec), pre-REX5 collapses to -/// [`SandboxCompletion::ExecutionFailed`] with `EmptyCodeDeployed` so logs are dropped -/// for replay parity. -/// -/// `is_rex6_enabled` enables the EIP-6780 SELFDESTRUCT check: when revm reports -/// `Success { Output::Create(bytecode, addr) }` but the sandbox-state account at `addr` has -/// `is_selfdestructed() == true` (same-tx create + SELFDESTRUCT), `apply_sandbox_state`'s -/// `apply_sandbox_created_selfdestruct` will zero balance/storage and leave no code at the -/// merged address — so reporting `Deployed { addr }` would surface a non-zero -/// `deployedAddress` for an address that has no on-chain code after merge. REX6 collapses -/// this case onto the same empty-code branch as `bytecode.is_empty()` (REX6 implies REX5, -/// so logs forward via `SandboxCompletion::EmptyCode`); the outer caller returns -/// `EmptyCodeDeployed` with `deployedAddress = 0x0`. Pre-REX6 specs preserve the original -/// surface (`Deployed { addr }` returned for create+SELFDESTRUCT) for replay parity. -fn process_sandbox_transact_result( - result: Result, E>, - limit_usage: LimitUsage, - volatile_accesses: VolatileDataAccess, - is_rex5_enabled: bool, - is_rex6_enabled: bool, -) -> SandboxOutcome { - let completed = |state, completion| SandboxOutcome::Completed { - state, - completion, - limit_usage, - volatile_accesses, - }; - - match result { - Ok(ResultAndState { result: exec_result, state: sandbox_state }) => match exec_result { - ExecutionResult::Success { gas_used, output, logs, .. } => { - let revm::context::result::Output::Create(bytecode, Some(created_addr)) = output - else { - // Contract creation didn't return an address — should never happen - // (the sandbox tx always asks for `TxKind::Create`), but we return - // a Rejected outcome instead of panicking to avoid crashing the node. - return SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated); - }; - // REX6: also treat same-tx create + SELFDESTRUCT as empty-code. revm reports - // `Success` with the constructor's returned bytecode, but - // `apply_sandbox_created_selfdestruct` zeroes the account on merge — so the - // parent-visible code at `created_addr` is empty. Folding into the same arm - // as `bytecode.is_empty()` produces a consistent `EmptyCodeDeployed` outcome - // (logs forwarded under REX5+). - let selfdestructed = is_rex6_enabled && - sandbox_state - .get(&created_addr) - .is_some_and(|account| account.is_selfdestructed()); - if bytecode.is_empty() || selfdestructed { - // REX5+: surface as `EmptyCode` so the outer caller forwards the - // constructor's logs into the parent receipt before returning - // success-style `EmptyCodeDeployed` errorData. Pre-REX5 collapses - // back to `ExecutionFailed { EmptyCodeDeployed }` so logs are - // dropped, preserving the frozen replay behavior. - if is_rex5_enabled { - return completed( - sandbox_state, - SandboxCompletion::EmptyCode { gas_used, logs }, - ); - } - return completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::EmptyCodeDeployed { gas_used }, - }, - ); - } - completed( - sandbox_state, - SandboxCompletion::Deployed { gas_used, deploy_address: created_addr, logs }, - ) - } - ExecutionResult::Revert { gas_used, output } => completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::ExecutionReverted { gas_used, output }, - }, - ), - ExecutionResult::Halt { gas_used, reason } => { - // `FailedDeposit` on this path means op-revm's deposit `catch_error` wrapped a - // sandbox tx-validation failure into a synthetic halt. Runtime halts under the - // deposit-style sandbox tx are intercepted in `MegaHandler::execution_result` - // and surface here with their real halt reason instead, so they fall through to - // the normal `ExecutionHalted` failure branch and consume the Nick's-Method - // replay barrier as expected. Validation rejects must NOT consume the barrier, - // so we drop the discarded sandbox state and surface as Rejected. - if matches!(reason, MegaHaltReason::Base(op_revm::OpHaltReason::FailedDeposit)) { - warn!(gas_used, "keyless deploy sandbox failed deposit (validation-reject)",); - return SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction); - } - // The halt `reason` is dropped on the ABI wire (the Solidity error - // carries only `gasUsed`) and `decode_error_result` synthesizes a - // placeholder on the way back, so node-side `tracing` is the only - // place the real cause is observable. - warn!( - reason = ?reason, - gas_used, - "keyless deploy sandbox halted", - ); - completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::ExecutionHalted { gas_used, reason }, - }, - ) - } - }, - // Split tx-validation rejections (selector `InvalidTransaction`) from genuine - // internal failures (selector `InternalError`) so relayer-side decoders can tell - // them apart. Both are selector-only on the wire — see `encode_error_result`. - Err(e) if e.is_tx_error() => { - warn!( - error = %e, - "keyless deploy sandbox transaction rejected during validation", - ); - SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction) - } - Err(e) => { - error!( - error = %e, - "keyless deploy sandbox failed with internal error", - ); - SandboxOutcome::Rejected(KeylessDeployError::InternalError) - } - } -} - -/// Rex5+ post-sandbox accounting. Order is load-bearing: -/// (a) merge multidim usage — always; survives any later halt -/// (b) merge volatile bitmap — always; survives any later halt -/// (c) refund unused sandbox gas — always; pure `erase_cost`, never halts -/// (d) reject if tx-level overflow — may halt with exceeding mark -/// -/// (a) and (b) run before the halt-deciding helper so the parent transaction's -/// reported footprint reflects what the sandbox actually accessed even on halt -/// paths. The caller invokes `apply_sandbox_state` only after this returns -/// `None`, following the standard "halted transactions commit only -/// pre-execution state" convention. -/// -/// `reservation` is the amount pre-debited from the outer `gas` before the -/// sandbox ran (step 8b in `execute_keyless_deploy_call`); `sandbox_gas_used` is -/// the amount the sandbox actually consumed (read from -/// [`SandboxCompletion::gas_used`]). Their difference is the unused reservation -/// that must be returned to the outer frame — mirroring revm's standard CALL -/// semantics. -/// -/// Caller-side spec gating keeps this path Rex5-only. -fn apply_sandbox_post_accounting( - ctx: &MegaContext, - gas: &mut Gas, - limit_usage: LimitUsage, - volatile_accesses: VolatileDataAccess, - reservation: u64, - sandbox_gas_used: u64, - return_memory_offset: &core::ops::Range, -) -> Option { - merge_sandbox_limit_usage(ctx, limit_usage); - ctx.volatile_data_tracker.borrow_mut().merge_accesses_from_bitmap(volatile_accesses); - refund_unused_sandbox_gas(gas, reservation, sandbox_gas_used); - reject_if_tx_limit_overflow(ctx, gas, return_memory_offset) -} - -/// If the deploy signer is unmaterialized in the parent journal-visible state, -/// pre-charges `new_account_storage_gas(deploy_signer)` against the outer Gas -/// counter and records a deposit-caller state-growth event. Mirrors the upfront -/// `KEYLESS_DEPLOY_OVERHEAD_GAS` charge in step 1: paid before the sandbox runs, -/// retained even when the sandbox is never constructed (e.g., sandbox-validate -/// reject), so the relayer cannot squeeze the sandbox into a budget that excludes -/// the parent's materialization-side state-growth invariant. -/// -/// `signer_info` is the parent-state `AccountInfo` loaded by -/// `inspect_signer_parent_state`. Treating absent/empty alike via `is_empty()` -/// (rather than re-reading the DB) keeps the materialization decision aligned with -/// what the upstream `make_create_frame` will observe for the same signer. -/// -/// Returns: -/// - `Ok(None)` when the signer was already materialized, or the charge fit and the resulting -/// state-growth event was within the parent's TX-level budget; -/// - `Ok(Some(halt))` when either the outer Gas could not absorb the charge (plain OOG), or -/// recording the state-growth event tripped a non-frame-local TX-level limit (canonical -/// exceeding-limit OOG, with parent gas rescued — see `reject_if_tx_limit_overflow`); -/// - `Err(InternalError)` when the dynamic-gas computation fails. -fn charge_caller_materialization_pre_sandbox( - ctx: &MegaContext, - gas: &mut Gas, - deploy_signer: Address, - signer_info: &AccountInfo, - return_memory_offset: &core::ops::Range, -) -> Result, KeylessDeployError> { - if !signer_info.is_empty() { - return Ok(None); - } - - // Call `DynamicGasCost::new_account_gas` directly rather than the `HostExt` helper: - // the helper stashes the SALT/env error into `ctx.error()`, which the outer transaction's - // own `execution_result` would later drain into an EVM-level `Err(Custom)` — breaking - // the spec contract that this failure surfaces as a `Revert(InternalError())` selector - // and leaves the outer transaction otherwise well-formed. - let caller_storage_gas = - ctx.dynamic_storage_gas_cost.borrow_mut().new_account_gas(deploy_signer).map_err(|e| { - error!( - error = %e, - deploy_signer = ?deploy_signer, - "pre-sandbox caller storage gas computation failed", - ); - KeylessDeployError::InternalError - })?; - if !gas.record_cost(caller_storage_gas) { - return Ok(Some(oog_frame_result(gas.limit(), return_memory_offset))); - } - // `record_deposit_caller_creation` can latch `has_exceeded_limit` to a non-frame-local - // `StateGrowthLimitExceeded`. Convert it to the canonical exceeding-limit OOG halt - // (with rescued gas) here — interceptor short-circuit bypasses `after_frame_run`'s - // standard `try_rescue_gas` hook, so any subsequent Revert-shaped error in this - // function would let `before_frame_return_result::` convert it to a Halt - // without ever rescuing the parent gas. - ctx.additional_limit.borrow_mut().record_deposit_caller_creation(); - if let Some(halt) = reject_if_tx_limit_overflow(ctx, gas, return_memory_offset) { - return Ok(Some(halt)); - } - Ok(None) -} - -/// Merges the sandbox's multidim usage into the parent's trackers. -/// -/// This merge is intentionally not undone on later halt paths, because -/// block-level multidim counters survive halts. -fn merge_sandbox_limit_usage( - ctx: &MegaContext, - limit_usage: LimitUsage, -) { - ctx.additional_limit.borrow_mut().merge_usage(limit_usage); -} - -/// Returns the unused portion of the sandbox's pre-debited gas reservation to the -/// outer frame. Mirrors revm's standard CALL semantics: pre-debit on entry, refund -/// `reservation - used` on exit. Pure `Gas::erase_cost`, never halts. -fn refund_unused_sandbox_gas(gas: &mut Gas, reservation: u64, sandbox_gas_used: u64) { - // Sandbox cannot consume more than the reservation it was given (revm's frame - // accounting enforces `gas_used ≤ gas_limit`), but `saturating_sub` keeps the - // arithmetic defensive against any future change in how `gas_used` is reported. - let unused = reservation.saturating_sub(sandbox_gas_used); - if unused > 0 { - gas.erase_cost(unused); - } -} - -/// Rejects the outer call when already-merged sandbox usage pushes the parent -/// over a non-frame-local TX-level limit. -/// -/// Returns `Some(FrameResult)` when the outer handler must short-circuit -/// (rescue remaining gas, return as exceeding-limit OOG), `None` when the -/// merged usage fits. -/// -/// State must not be merged after this returns `Some(_)`; the footprint -/// side effects already applied by `apply_sandbox_post_accounting` remain. -fn reject_if_tx_limit_overflow( - ctx: &MegaContext, - gas: &Gas, - return_memory_offset: &core::ops::Range, -) -> Option { - let mut limit = ctx.additional_limit.borrow_mut(); - let limit_check = limit.check_limit(); - if !limit_check.exceeded_limit() || limit_check.is_frame_local() { - return None; - } - limit.rescue_gas(gas); - let mut result = oog_frame_result(gas.limit(), return_memory_offset); - mark_frame_result_as_exceeding_limit( - &mut result, - crate::AdditionalLimit::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); - Some(result) -} - -/// Single source of truth for the `OutOfGas` halt `FrameResult` shape (empty return -/// data, all gas consumed). Callers that need the exceeding-limit marker apply -/// `mark_frame_result_as_exceeding_limit` on the returned value. -fn oog_frame_result(gas_limit: u64, return_memory_offset: &core::ops::Range) -> FrameResult { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - return_memory_offset.clone(), - )) -} - -/// Rex5+ preflight: rejects the outer call when the sandbox's known pre-frame intrinsic -/// usage alone would not fit inside the parent's remaining envelope. -/// -/// Running such a sandbox is guaranteed to fail internally, so this short-circuits before -/// sandbox EVM construction, signer balance DB read, and halt/rescue teardown — using a -/// lightweight trial-run via `AdditionalLimit::intrinsic_check_for_tx`. -/// -/// Returns `Some(KeylessDeployError::ParentBudgetExceeded { .. })` when the outer call -/// should revert, or `None` when the sandbox is permitted to start. -fn sandbox_intrinsic_overflow_error( - spec: MegaSpecId, - sandbox_tx: &MegaTransaction, - sandbox_tx_limits: Option, -) -> Option { - let limits = sandbox_tx_limits?; - match AdditionalLimit::intrinsic_check_for_tx(spec, sandbox_tx, limits) { - LimitCheck::ExceedsLimit { kind, limit, used, .. } => { - Some(KeylessDeployError::ParentBudgetExceeded { kind, limit, used }) - } - // `intrinsic_check_for_tx` builds a fresh trial tracker that never has `Exempt` stamped, - // so only the two real outcomes are reachable here. - LimitCheck::WithinLimit | LimitCheck::Exempt => None, - } -} - -/// Derives the sandbox's TX runtime limits from the parent's remaining budgets. -/// -/// Tightens the four resource dimensions (compute gas, data size, KV updates, state growth) -/// to the parent's frame-local remaining capacity. The base is the parent's active -/// `EvmTxRuntimeLimits` (not spec defaults), so any custom detention caps -/// (`block_env_access_compute_gas_limit`, `oracle_access_compute_gas_limit`) are -/// preserved. -/// -/// Intrinsic usage is NOT pre-subtracted here — the sandbox's own tracker records it -/// during transaction startup, so double-subtracting would leave the sandbox -/// under-budgeted. Pre-frame intrinsic overflow is instead caught by -/// `sandbox_intrinsic_overflow_error`, and any future TX-level persistent contribution -/// added before the first sandbox frame MUST be mirrored in -/// `AdditionalLimit::intrinsic_check_for_tx` to keep the preflight estimator sound. -fn sandbox_runtime_limits( - ctx: &MegaContext, -) -> EvmTxRuntimeLimits { - let parent_limit = ctx.additional_limit.borrow(); - let limits = parent_limit.limits; - - limits - .with_tx_compute_gas_limit(parent_limit.current_call_remaining_compute_gas()) - .with_tx_data_size_limit(parent_limit.current_call_remaining_data_size()) - .with_tx_kv_updates_limit(parent_limit.current_call_remaining_kv_updates()) - .with_tx_state_growth_limit(parent_limit.current_call_remaining_state_growth()) -} - -/// Reads an account nonce from the journal cache first, then falls back to the backing database. -fn get_account_nonce( - ctx: &mut MegaContext, - address: Address, -) -> Result { - let journal = ctx.journal_mut(); - if let Some(acc) = journal.state.get(&address) { - return Ok(acc.info.nonce); - } - Ok(journal - .database - .basic(address) - .map_err(|e| { - error!( - error = %e, - address = ?address, - "keyless deploy nonce read failed", - ); - KeylessDeployError::InternalError - })? - .map(|info| info.nonce) - .unwrap_or(0)) -} - -/// Loads the deploy signer's parent-state `AccountInfo` via `JournalInspectTr::inspect_account` -/// (cold-marked) for Rex5+. -/// -/// The single lookup feeds the nonce check, the EIP-3607 caller-with-code check, and the -/// materialization `is_empty()` check from one source — keeping the "cold-marked, no -/// EIP-2929 pollution" contract documented in one place. -/// -/// `load_code` is derived from `!cfg.disable_eip3607`: EIP-3607 needs the bytecode to -/// distinguish a real contract from an EIP-7702 delegation designation, but when -/// `disable_eip3607 = true` the canonical revm `validate_account_nonce_and_code` -/// short-circuits without touching `code_by_hash`. The nonce check reads `info.nonce` -/// and the materialization check reads `info.is_empty()` (which uses `code_hash`, not the -/// hydrated bytes), so neither requires the bytecode to be loaded. -/// -/// Edge case — the `disable_eip3607 = true` no-`code_by_hash` short-circuit holds only when -/// the signer is not already present in the parent journal cache as a lazy-code occupied -/// entry. `inspect_account`'s occupied branch unconditionally invokes `code_by_hash` on -/// `code_hash != KECCAK_EMPTY && info.code.is_none()` regardless of `load_code` — this -/// hydration is load-bearing for the pre-REX5 EIP-7702 detection path in -/// `inspect_account_delegated` (see `evm/host.rs`) and changing it would shift behavior on -/// frozen specs. In the normal third-party relayer keyless-deploy flow the signer is -/// recovered from the inner RLP at step 5 of `execute_keyless_deploy_call` and the outer -/// EVM has not touched it before that, so the signer's journal entry is vacant when this -/// helper runs. If an outer transaction or replay harness has already cached the signer -/// (e.g., the relayer happens to be the signer, or a witness / stateless harness pre-fills -/// the journal with lazy-code entries), the occupied-entry caveat above applies. -fn inspect_signer_parent_state( - ctx: &mut MegaContext, - address: Address, -) -> Result { - let load_code = !ctx.cfg().disable_eip3607; - let account = ctx.journal_mut().inspect_account(address, load_code).map_err(|e| { - error!( - error = %e, - address = ?address, - "keyless deploy signer parent-state inspection failed", - ); - KeylessDeployError::InternalError - })?; - Ok(account.info.clone()) -} - -/// Enforces the EIP-3607 caller-with-code rule against the provided parent-state info, -/// honoring `cfg.disable_eip3607` exactly like the canonical revm path. -/// -/// The op-revm deposit path skips this check in `validate_against_state_and_deduct_caller`, -/// so the sandbox enforces it itself for Rex5+ to keep the no-contract-sender invariant. -/// The lookup itself lives in `inspect_signer_parent_state`; this function only inspects -/// the resulting info. -fn validate_signer_code( - ctx: &MegaContext, - signer_info: &AccountInfo, -) -> Result<(), KeylessDeployError> { - if ctx.cfg().disable_eip3607 { - return Ok(()); - } - if let Some(code) = &signer_info.code { - if !code.is_empty() && !code.is_eip7702() { - return Err(KeylessDeployError::SignerHasCode); - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use revm::context::result::Output; - - /// Test error type that lets us drive `process_sandbox_transact_result`'s - /// `Err` arms (which map to `SandboxOutcome::Rejected`) directly without - /// standing up a full sandbox EVM. The two arms differ only by - /// `IsTxError::is_tx_error()`, so a single struct with a configurable flag - /// covers both selector mappings. - struct FakeTxErr { - is_tx: bool, - msg: &'static str, - } - - impl core::fmt::Display for FakeTxErr { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(self.msg) - } - } - - impl IsTxError for FakeTxErr { - fn is_tx_error(&self) -> bool { - self.is_tx - } - } - - /// The sandbox's create transaction always asks for `TxKind::Create`, but if revm - /// ever surfaces a `Success` with `Output::Call` for that input shape the merge code - /// would otherwise unwrap into an address-less success. Pin the defensive - /// `NoContractCreated` mapping. - #[test] - fn test_process_result_call_output_maps_to_no_contract_created() { - let result: Result, FakeTxErr> = Ok(ResultAndState { - result: ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas_used: 1, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Call(Bytes::new()), - }, - state: EvmState::default(), - }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated)), - "unexpected: {out:?}", - ); - } - - /// `Output::Create(_, None)` — Create succeeded but revm did not return an address. - /// Same defensive `NoContractCreated` shape as the Call branch. - #[test] - fn test_process_result_create_without_address_maps_to_no_contract_created() { - let result: Result, FakeTxErr> = Ok(ResultAndState { - result: ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas_used: 1, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Create(Bytes::from_static(&[0x60, 0x00]), None), - }, - state: EvmState::default(), - }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated)), - "unexpected: {out:?}", - ); - } - - /// `transact_raw` error where `is_tx_error()` is `false` (DB I/O, header validation, - /// `EVMError::Custom`, etc.) MUST map to the selector-only `InternalError`. Pinned - /// because a regression that re-collapses this into `InvalidTransaction` would - /// silently re-classify infrastructure failures as user-input rejections. - #[test] - fn test_process_result_non_tx_error_maps_to_internal_error() { - let result: Result, FakeTxErr> = - Err(FakeTxErr { is_tx: false, msg: "db blew up" }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::InternalError)), - "unexpected: {out:?}", - ); - } - - /// Mirror of the above for `is_tx_error() == true`: MUST map to - /// `InvalidTransaction` with its dedicated selector. - #[test] - fn test_process_result_tx_error_maps_to_invalid_transaction() { - let result: Result, FakeTxErr> = - Err(FakeTxErr { is_tx: true, msg: "intrinsic gas too low" }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction)), - "unexpected: {out:?}", - ); - } - - /// `get_account_nonce`: cache miss path on a failing DB MUST map the underlying - /// `DBError` to selector-only `InternalError`. This is the only sandbox-internal - /// call site that reads a nonce via the parent journal database directly (rather - /// than via the journal cache or `SandboxDb` fallthrough), so the `error!` `map_err` - /// is the only place the failure can be classified. - #[test] - fn test_get_account_nonce_db_error_maps_to_internal_error() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - // Cache is empty → cache miss → DB fallback → injected error. - let out = get_account_nonce(&mut ctx, signer); - assert!(matches!(out, Err(KeylessDeployError::InternalError)), "unexpected: {out:?}"); - } - - /// `get_account_nonce` MUST take the journal-cache branch (without re-reading the - /// database) when the address is already present in `journal.inner.state`. Pinned - /// because the cache-hit branch and the DB-fallback branch return identical values on - /// the happy path; only an end-to-end harness or a direct unit assertion can tell them - /// apart. - #[test] - fn test_get_account_nonce_returns_cached_nonce_without_touching_database() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - use revm::{primitives::KECCAK_EMPTY, state::AccountInfo}; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - // DB fails on every `basic(signer)` call. The cache-hit branch is the only way - // `get_account_nonce` can return successfully — if the DB-fallback branch is taken, - // the test fails with the injected error. - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - // Seed the journal cache directly so `get_account_nonce` finds the signer in - // `journal.inner.state` and short-circuits before reaching the DB fallback. - let cached_info = - AccountInfo { nonce: 7, balance: U256::ZERO, code_hash: KECCAK_EMPTY, code: None }; - ctx.journal_mut().inner.state.insert(signer, cached_info.into()); - - let nonce = get_account_nonce(&mut ctx, signer).expect("cache hit must not error"); - assert_eq!(nonce, 7, "cache-hit nonce must reflect the seeded journal entry"); - } - - /// `inspect_signer_parent_state` MUST surface an `inspect_account` DB failure as - /// `Err(KeylessDeployError::InternalError)`. This is the only Rex5+ pre-sandbox call - /// site that performs the parent-state read — every downstream check (`signer_nonce`, - /// `validate_signer_code`, materialization) inspects the returned `AccountInfo` - /// without touching the DB again, so the `error!` `map_err` here is the only place - /// the failure can be classified. - #[test] - fn test_inspect_signer_parent_state_db_error_maps_to_internal_error() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - let out = inspect_signer_parent_state(&mut ctx, signer); - assert!( - matches!(out, Err(KeylessDeployError::InternalError)), - "inspect_account DB error must map to InternalError; got {out:?}", - ); - } - - /// `inspect_signer_parent_state` MUST NOT invoke `code_by_hash` when - /// `cfg.disable_eip3607 = true` AND the signer is not yet present in the parent - /// journal cache — i.e., the vacant-branch path used by the normal keyless-deploy flow - /// when the signer is not pre-cached in the parent journal (signer recovered from inner - /// RLP at step 5 of `execute_keyless_deploy_call`, after which only this helper - /// inspects it). - /// - /// Pin the contract that the canonical revm `validate_account_nonce_and_code` - /// short-circuits without hydrating the signer's bytecode on the vacant path; without - /// this, a DB whose `code_by_hash` fails turns an EIP-3607-disabled precheck into - /// `InternalError`. The pre-cached lazy-code occupied path is a documented edge case - /// (see `inspect_signer_parent_state` docstring) — `inspect_account`'s occupied branch - /// unconditionally hydrates and that behavior is load-bearing for stable specs. - /// - /// The workspace's `MemoryDatabase` eagerly inlines `AccountInfo.code` inside `basic()`, - /// so the in-tree integration tests cannot exercise this lazy-code shape — hence a - /// dedicated `revm::Database` impl here that mirrors reth's - /// `StateProviderDatabase::basic` contract (`code: None`, real `code_hash`). - #[test] - fn test_inspect_signer_parent_state_skips_code_by_hash_on_vacant_when_eip3607_disabled() { - use alloy_primitives::{address, keccak256, B256}; - use revm::{bytecode::Bytecode, primitives::Bytes as PrimitivesBytes}; - - #[derive(Debug, Default)] - struct LazyCodeSignerDb { - signer: Address, - signer_info: AccountInfo, - } - - impl RevmDatabase for LazyCodeSignerDb { - type Error = core::convert::Infallible; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - if address == self.signer { - // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo with - // `code: None` even when `code_hash` references real on-chain bytecode. - Ok(Some(self.signer_info.clone())) - } else { - Ok(None) - } - } - - fn code_by_hash(&mut self, _code_hash: B256) -> Result { - panic!( - "code_by_hash must not be called on the vacant signer path when \ - disable_eip3607 = true (canonical validate_account_nonce_and_code \ - short-circuit)", - ); - } - - fn storage(&mut self, _address: Address, _index: U256) -> Result { - Ok(U256::ZERO) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } - } - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let bytecode = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - let code_hash = keccak256(&bytecode); - let signer_info = AccountInfo { nonce: 0, balance: U256::ZERO, code_hash, code: None }; - let db = LazyCodeSignerDb { signer, signer_info }; - - let mut ctx = MegaContext::<_, crate::EmptyExternalEnv>::new(db, MegaSpecId::REX5); - ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); - - let info = inspect_signer_parent_state(&mut ctx, signer) - .expect("lookup must succeed without hydrating code"); - assert_eq!(info.code_hash, code_hash, "code_hash must propagate from the DB"); - assert!( - info.code.is_none(), - "disable_eip3607 = true must leave info.code as None on the vacant branch", - ); - } - - /// `validate_signer_code` MUST be a no-op when `cfg.disable_eip3607 = true`, even - /// when the provided `AccountInfo` has bytecode that would otherwise trip the - /// caller-with-code check. Mirrors the canonical revm `validate_account_nonce_and_code` - /// semantics and pins the early-return contract. - #[test] - fn test_validate_signer_code_disable_eip3607_short_circuits() { - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use revm::{ - bytecode::Bytecode, - primitives::{keccak256, Bytes as PrimitivesBytes}, - }; - - let code_bytes = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - let code_hash = keccak256(&code_bytes); - let signer_info = AccountInfo { - nonce: 0, - balance: U256::ZERO, - code_hash, - code: Some(Bytecode::new_raw(code_bytes)), - }; - - let mut ctx = - MegaContext::<_, EmptyExternalEnv>::new(MemoryDatabase::default(), MegaSpecId::REX5); - ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); - - let out = validate_signer_code(&ctx, &signer_info); - assert!( - matches!(out, Ok(())), - "disable_eip3607 must short-circuit before the code inspection; got {out:?}", - ); - } - - /// `charge_caller_materialization_pre_sandbox` MUST surface a SALT/dynamic-gas failure - /// as `Err(KeylessDeployError::InternalError)` without writing to `ctx.error()`. - /// - /// The contract is load-bearing: op-revm's `Handler::execution_result` drains - /// `ctx.error()` and converts any non-empty `ContextError` into an EVM-level - /// `Err(Custom(...))`. Routing a SALT failure through the - /// `HostExt::new_account_storage_gas` helper — which stashes the error into - /// `ctx.error()` — would promote an interceptor-level failure into a whole-transaction - /// execution error and break the `InternalError()` selector contract. The - /// pre-sandbox charge path must therefore call `DynamicGasCost::new_account_gas` - /// directly and keep the error local. - #[test] - fn test_charge_caller_materialization_salt_failure_returns_internal_error_without_ctx_pollution( - ) { - use crate::{test_utils::MemoryDatabase, BucketId, OracleEnv, SaltEnv}; - use alloy_primitives::{address, B256}; - use core::fmt::{self, Display, Formatter}; - - // Minimal `SaltEnv` whose `get_bucket_capacity` always fails. This drives - // `DynamicGasCost::new_account_gas` (called from - // `charge_caller_materialization_pre_sandbox`) to return `Err`, exercising the - // failure-handling path under test. - #[derive(Debug, Clone, Copy)] - struct AlwaysFailSalt; - - #[derive(Debug, Clone)] - struct InjectedSaltError; - impl Display for InjectedSaltError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.write_str("injected SALT failure") - } - } - - impl SaltEnv for AlwaysFailSalt { - type Error = InjectedSaltError; - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err(InjectedSaltError) - } - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } - } - - #[derive(Debug, Clone, Copy)] - struct NoopOracle; - impl OracleEnv for NoopOracle { - fn get_oracle_storage(&self, _slot: U256) -> Option { - None - } - fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} - } - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let db = MemoryDatabase::default(); - let envs: crate::ExternalEnvs<(AlwaysFailSalt, NoopOracle)> = - crate::ExternalEnvs { salt_env: AlwaysFailSalt, oracle_env: NoopOracle }; - let mut ctx = MegaContext::new(db, MegaSpecId::REX5).with_external_envs(envs); - - let mut gas = Gas::new(10_000_000); - let return_memory_offset = 0..0; - - // Signer is unmaterialized (default `AccountInfo` is `is_empty()` == true) - // → the materialization branch fires. - let signer_info = AccountInfo::default(); - let out = charge_caller_materialization_pre_sandbox( - &ctx, - &mut gas, - signer, - &signer_info, - &return_memory_offset, - ); - assert!( - matches!(out, Err(KeylessDeployError::InternalError)), - "SALT failure must surface as InternalError, got {out:?}", - ); - - // The whole point of the fix: ctx.error() must NOT have been polluted, so the outer - // transaction's `execution_result` doesn't drain it into `Err(Custom)`. - let ctx_error = core::mem::replace(ctx.error(), Ok(())); - assert!( - matches!(ctx_error, Ok(())), - "ctx.error() must remain Ok after a SALT failure in the pre-sandbox charge; \ - got {ctx_error:?}", - ); - - // record_deposit_caller_creation must NOT have fired either. - assert_eq!( - ctx.additional_limit.borrow().get_usage().state_growth, - 0, - "deposit-caller state-growth must not be recorded when the storage gas computation fails", - ); - } -} diff --git a/crates/mega-evm/src/sandbox/mod.rs b/crates/mega-evm/src/sandbox/mod.rs deleted file mode 100644 index c59c9889c..000000000 --- a/crates/mega-evm/src/sandbox/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Sandbox execution environment for keyless contract deployment. -//! -//! This module provides isolated EVM execution for implementing "Nick's Method" - a technique -//! for deterministic contract deployment that allows deploying contracts to the same address -//! across different chains using pre-EIP-155 transactions. -//! -//! # Overview -//! -//! The sandbox executes keyless deployment transactions in an isolated environment, then -//! applies only the resulting state changes to the parent context. This approach: -//! -//! - Validates pre-EIP-155 legacy transactions -//! - Recovers the signer and computes the deterministic deploy address -//! - Executes contract creation with a nonce override of 0 -//! - Merges state changes back to the parent journal -//! -//! # Spam Protection -//! -//! The sandbox is designed to guarantee that **every execution that starts and completes is paid -//! for** — either by the signer through merged sandbox state on normal completion, or by the -//! outer caller through `record_cost` on Rex5 residual-overflow rejects. This prevents spam -//! attacks where an attacker triggers execution but avoids paying. -//! -//! ## General Protections -//! -//! 1. **Top-level only (`depth == 0`)**: Sandbox interception only occurs for direct transaction -//! calls. Calls from contracts (depth > 0) hit the Solidity fallback which reverts with -//! `NotIntercepted()`. This prevents wrapping the call to observe and revert. -//! -//! 2. **Execution errors return success**: Failures like `ExecutionReverted`, `ExecutionHalted`, -//! and `EmptyCodeDeployed` return normally with error data so state changes (including the -//! signer's balance deduction via merged state) are committed. -//! -//! 3. **Atomic state application**: `apply_sandbox_state` is the sole writer that makes a deploy -//! (and the signer-side charge) survive. Pre-Rex5 keeps the legacy direct merge for replay -//! compatibility, while Rex5 records stateful diffs in the parent journal so a later outer-frame -//! revert or halt can unwind them. -//! -//! ## Rex5 Resource-Envelope Defenses -//! -//! Rex5 adds three layers to keep a parent-budget-exceeding sandbox from either corrupting -//! accounting or escaping its charge: -//! -//! 1. **Upfront cap**: sandbox TX limits are tightened to the parent's remaining envelope before -//! execution starts, so normal execution cannot escape the envelope. -//! -//! 2. **Intrinsic preflight**: if the sandbox's known pre-frame intrinsic usage alone would exceed -//! the envelope, the outer call reverts with `ParentBudgetExceeded` before any sandbox EVM -//! construction. -//! -//! 3. **Post-merge safety net**: residual overflow (e.g., a single-opcode overshoot at a TX-level -//! compute-gas check) is caught after the sandbox completes. On this path the sandbox state is -//! NOT merged, the sandbox's EVM gas is charged to the outer caller via `record_cost`, remaining -//! outer gas is rescued for refund, and the outer call halts with `OutOfGas` — matching the revm -//! "halted transactions commit only pre-execution state" convention. Only this path halts the -//! outer call. -//! -//! # Module Structure -//! -//! - `execution` - Core sandbox execution logic and the main entry point -//! [`execute_keyless_deploy_call`] -//! - `state` - Type-erased database wrapper ([`SandboxDb`]) for isolated execution -//! - `state_merge` - Replay-safe merge of sandbox state into the parent journal -//! - `tx` - Transaction decoding and validation for pre-EIP-155 transactions -//! - `error` - Error types ([`KeylessDeployError`]) that map to Solidity errors in `IKeylessDeploy` -//! -//! # Type Erasure Strategy -//! -//! A key challenge in implementing sandbox execution is preventing infinite type instantiation. -//! If `MegaContext` creates a sandbox with `MegaContext`, the compiler would attempt -//! to instantiate `MegaContext>>`, causing an Internal Compiler -//! Error (ICE) during monomorphization. -//! -//! The solution is [`SandboxDb`], a type-erased database wrapper: -//! -//! ```text -//! MegaContext -//! └─> sandbox execution -//! └─> MegaContext // SandboxDb is a concrete type, not MegaContext<...> -//! ``` -//! -//! [`SandboxDb`] implements the `Database` trait while internally holding a type-erased -//! reference to the parent database via the `ErasedDatabase` trait. This breaks the recursive -//! type chain while still allowing the sandbox to read from the parent's state. -//! -//! # Usage -//! -//! The sandbox is invoked automatically when a call to the `KeylessDeploy` precompile is -//! intercepted in `MegaContext::call`. The entry point is [`execute_keyless_deploy_call`], -//! which validates the transaction, creates a sandbox environment, executes the deployment, -//! and returns the result. -//! -//! [`execute_keyless_deploy_call`]: execution::execute_keyless_deploy_call -//! [`SandboxDb`]: state::SandboxDb - -mod error; -mod execution; -mod state; -mod state_merge; -mod tx; - -pub use error::*; -pub use execution::*; -pub use state::*; -pub use tx::*; diff --git a/crates/mega-evm/src/sandbox/state.rs b/crates/mega-evm/src/sandbox/state.rs deleted file mode 100644 index 1376745b9..000000000 --- a/crates/mega-evm/src/sandbox/state.rs +++ /dev/null @@ -1,516 +0,0 @@ -//! Sandbox database for isolated EVM execution. -//! -//! This module uses type erasure to prevent infinite type instantiation -//! (`SandboxDb>`) that would cause a compiler ICE during monomorphization. - -#![allow(unreachable_pub)] // Types are pub for trait impls but module is private - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{ - boxed::Box, - string::{String, ToString}, -}; - -use alloy_primitives::{map::HashMap, Address, B256}; -use core::cell::RefCell; -use revm::{ - database::DBErrorMarker, - primitives::{StorageKey, StorageValue, KECCAK_EMPTY}, - state::{AccountInfo, Bytecode, EvmState}, - Database, -}; - -/// Error type for sandbox database operations. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SandboxDbError(String); - -impl core::fmt::Display for SandboxDbError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.0) - } -} - -impl core::error::Error for SandboxDbError {} -impl DBErrorMarker for SandboxDbError {} - -/// Type-erased database trait for sandbox operations. -/// -/// This trait erases the concrete database type to prevent infinite type -/// instantiation when creating nested sandboxes. -/// -/// # Why not `Box`? -/// -/// The [`Database`] trait has an associated type `Error`, which makes it not -/// object-safe. You cannot use `Box` directly because the compiler -/// doesn't know what error type to use at runtime: -/// -/// ```ignore -/// pub trait Database { -/// type Error; // This makes it NOT object-safe -/// fn basic(&mut self, ...) -> Result<..., Self::Error>; -/// } -/// ``` -/// -/// Even `Box>` won't work because the trait -/// requires `Self::Error` to match exactly - you can't erase a `DB::Error` into -/// a different type through a trait object. -/// -/// This `ErasedDatabase` trait solves the problem by: -/// 1. Having no associated types (all methods return our fixed [`SandboxDbError`]) -/// 2. Converting errors via `.to_string()` in the [`DatabaseWrapper`] implementation -trait ErasedDatabase { - fn basic(&self, address: Address) -> Result, SandboxDbError>; - fn storage(&self, address: Address, index: StorageKey) -> Result; - fn block_hash(&self, number: u64) -> Result; - fn code_by_hash(&self, code_hash: B256) -> Result; -} - -/// Wrapper that implements [`ErasedDatabase`] for any [`Database`] type. -/// -/// Uses `RefCell` for interior mutability since `Database` methods take `&mut self`. -struct DatabaseWrapper<'a, DB> { - db: RefCell<&'a mut DB>, -} - -impl ErasedDatabase for DatabaseWrapper<'_, DB> -where - DB::Error: core::fmt::Display, -{ - #[inline] - fn basic(&self, address: Address) -> Result, SandboxDbError> { - self.db.borrow_mut().basic(address).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn storage(&self, address: Address, index: StorageKey) -> Result { - self.db.borrow_mut().storage(address, index).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn block_hash(&self, number: u64) -> Result { - self.db.borrow_mut().block_hash(number).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn code_by_hash(&self, code_hash: B256) -> Result { - self.db.borrow_mut().code_by_hash(code_hash).map_err(|e| SandboxDbError(e.to_string())) - } -} - -/// A sandbox database for isolated EVM execution. -/// -/// Used for keyless deploy sandbox where we need to read from the parent state -/// directly without cloning the entire state upfront. -/// -/// **Important**: This type uses lifetime parameters to hold references to the -/// parent journal's state and database, avoiding expensive cloning. Values are -/// cloned lazily only when accessed. -pub struct SandboxDb<'a> { - /// Reference to the parent journal's state. - journal_state: &'a EvmState, - /// Type-erased reference to the underlying database for cache misses. - db: Box, - /// Index from `code_hash` to address for O(1) bytecode lookup. - code_index: HashMap, - /// Address whose nonce should be overridden to 0 (for keyless deploy). - nonce_override_address: Option
, -} - -impl<'a> core::fmt::Debug for SandboxDb<'a> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("SandboxDb").finish_non_exhaustive() - } -} - -impl<'a> SandboxDb<'a> { - /// Creates a new sandbox database with references to the journal's state and database. - /// - /// This does NOT clone the state or database - it holds references and clones values - /// lazily when accessed. The `code_index` is built upfront for O(1) bytecode lookup. - /// - /// # Arguments - /// - /// * `state` - Reference to the journal's cached state - /// * `db` - Mutable reference to the underlying database for cache misses - /// - /// # Split Borrowing - /// - /// This constructor takes separate references to state and database to allow - /// split borrowing at the call site. The caller should do: - /// ```ignore - /// let journal = ctx.journal_mut(); - /// let sandbox_db = SandboxDb::new(&journal.inner.state, &mut journal.database); - /// ``` - pub fn new(state: &'a EvmState, db: &'a mut DB) -> Self - where - DB: Database, - DB::Error: core::fmt::Display, - { - // Build code index for O(1) bytecode lookup - let mut code_index = HashMap::default(); - for (addr, account) in state { - if let Some(code) = &account.info.code { - if !code.is_empty() { - code_index.insert(account.info.code_hash, *addr); - } - } - } - - Self { - journal_state: state, - db: Box::new(DatabaseWrapper { db: RefCell::new(db) }), - code_index, - nonce_override_address: None, - } - } - - /// Sets an address whose nonce should be overridden to 0. - /// - /// This is used for keyless deploy where the transaction must have nonce=0 - /// regardless of the signer's actual nonce in the database. - pub fn with_nonce_override(mut self, address: Address) -> Self { - self.nonce_override_address = Some(address); - self - } -} - -impl Database for SandboxDb<'_> { - type Error = SandboxDbError; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - // Check journal state first - clone only when accessed - if let Some(account) = self.journal_state.get(&address) { - let mut info = account.info.clone(); - // Override nonce to 0 for the keyless deploy signer - if self.nonce_override_address == Some(address) { - info.nonce = 0; - } - return Ok(Some(info)); - } - // Not found in journal state - query underlying database - let result = self.db.basic(address)?; - // Override nonce to 0 for the keyless deploy signer - if let Some(mut info) = result { - if self.nonce_override_address == Some(address) { - info.nonce = 0; - } - return Ok(Some(info)); - } - Ok(None) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - if code_hash == KECCAK_EMPTY { - return Ok(Bytecode::default()); - } - - // Use index for O(1) lookup in journal state - if let Some(addr) = self.code_index.get(&code_hash) { - if let Some(account) = self.journal_state.get(addr) { - return Ok(account.info.code.clone().unwrap_or_default()); - } - } - - // Not found in journal state - query underlying database - self.db.code_by_hash(code_hash) - } - - fn storage( - &mut self, - address: Address, - index: StorageKey, - ) -> Result { - // Check journal state for cached storage values - if let Some(account) = self.journal_state.get(&address) { - if let Some(slot) = account.storage.get(&index) { - return Ok(slot.present_value); - } - } - // Not found in journal state - query underlying database - self.db.storage(address, index) - } - - fn block_hash(&mut self, number: u64) -> Result { - // Block hashes are not stored in journal state - query database - self.db.block_hash(number) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256, Bytes, U256}; - use revm::{ - context::JournalTr, - database::EmptyDB, - state::{AccountStatus, EvmStorageSlot}, - Journal, - }; - - const TEST_ADDR_1: Address = address!("1111111111111111111111111111111111111111"); - const TEST_ADDR_2: Address = address!("2222222222222222222222222222222222222222"); - const TEST_ADDR_3: Address = address!("3333333333333333333333333333333333333333"); - - fn create_test_journal() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - // Add a test account to the journal - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from(1000), - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_1, account); - journal - } - - fn create_journal_with_contract() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - - // Create bytecode and compute its hash - let bytecode_bytes = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); // PUSH0 PUSH0 RETURN - let bytecode = Bytecode::new_raw(bytecode_bytes.clone()); - let code_hash = keccak256(&bytecode_bytes); - - // Add contract account with bytecode - let contract_account = revm::state::Account { - info: AccountInfo { balance: U256::ZERO, nonce: 1, code_hash, code: Some(bytecode) }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_2, contract_account); - journal - } - - fn create_journal_with_storage() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - - // Add account with storage - let mut storage = HashMap::default(); - storage.insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - storage - .insert(U256::from(100), EvmStorageSlot::new_changed(U256::ZERO, U256::from(999), 0)); - - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from(5000), - nonce: 10, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage, - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_1, account); - journal - } - - // ==================== basic() tests ==================== - - #[test] - fn test_basic_returns_account_from_journal() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let result = sandbox.basic(TEST_ADDR_1).unwrap(); - assert!(result.is_some()); - let info = result.unwrap(); - assert_eq!(info.balance, U256::from(1000)); - assert_eq!(info.nonce, 1); - } - - #[test] - fn test_basic_queries_database_on_cache_miss() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // TEST_ADDR_3 is not in journal, so it queries EmptyDB which returns None - let result = sandbox.basic(TEST_ADDR_3).unwrap(); - assert!(result.is_none()); - } - - #[test] - fn test_basic_returns_contract_account_info() { - let mut journal = create_journal_with_contract(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let result = sandbox.basic(TEST_ADDR_2).unwrap(); - assert!(result.is_some()); - let info = result.unwrap(); - assert_eq!(info.nonce, 1); - assert_ne!(info.code_hash, KECCAK_EMPTY); - } - - // ==================== storage() tests ==================== - - #[test] - fn test_storage_returns_value_from_journal() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let value = sandbox.storage(TEST_ADDR_1, U256::from(1)).unwrap(); - assert_eq!(value, U256::from(42)); - - let value = sandbox.storage(TEST_ADDR_1, U256::from(100)).unwrap(); - assert_eq!(value, U256::from(999)); - } - - #[test] - fn test_storage_returns_zero_for_unset_slot_in_journal() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Slot 50 is not set in journal storage, queries database (EmptyDB returns zero) - let value = sandbox.storage(TEST_ADDR_1, U256::from(50)).unwrap(); - assert_eq!(value, U256::ZERO); - } - - #[test] - fn test_storage_queries_database_for_unknown_account() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // TEST_ADDR_3 not in journal, queries EmptyDB which returns zero - let value = sandbox.storage(TEST_ADDR_3, U256::from(1)).unwrap(); - assert_eq!(value, U256::ZERO); - } - - // ==================== code_by_hash() tests ==================== - - #[test] - fn test_code_by_hash_returns_empty_for_keccak_empty() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let code = sandbox.code_by_hash(KECCAK_EMPTY).unwrap(); - assert!(code.is_empty()); - } - - #[test] - fn test_code_by_hash_returns_bytecode_from_journal_via_index() { - let mut journal = create_journal_with_contract(); - - // Get the code hash from the contract account - let code_hash = journal.inner.state.get(&TEST_ADDR_2).unwrap().info.code_hash; - - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let code = sandbox.code_by_hash(code_hash).unwrap(); - assert!(!code.is_empty()); - // Bytecode may have padding, so check it starts with our expected bytes - assert!(code.bytes_slice().starts_with(&[0x60, 0x00, 0x60, 0x00, 0xf3])); - } - - #[test] - fn test_code_by_hash_queries_database_for_unknown_hash() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Random hash not in journal - queries EmptyDB which returns empty bytecode - let unknown_hash = keccak256(b"unknown code"); - let code = sandbox.code_by_hash(unknown_hash).unwrap(); - assert!(code.is_empty()); - } - - #[test] - fn test_code_index_built_correctly() { - let mut journal = create_journal_with_contract(); - let code_hash = journal.inner.state.get(&TEST_ADDR_2).unwrap().info.code_hash; - - let sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Verify code_index contains the mapping - assert!(sandbox.code_index.contains_key(&code_hash)); - assert_eq!(sandbox.code_index.get(&code_hash), Some(&TEST_ADDR_2)); - } - - #[test] - fn test_code_index_excludes_empty_code() { - let mut journal = create_test_journal(); - let sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Account with no code should not be in code_index - assert!(!sandbox.code_index.contains_key(&KECCAK_EMPTY)); - assert!(sandbox.code_index.is_empty()); - } - - // ==================== block_hash() tests ==================== - - #[test] - fn test_block_hash_queries_database() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Block hash is always queried from database - // EmptyDB returns keccak256(block_number) - let hash = sandbox.block_hash(100).unwrap(); - assert_ne!(hash, B256::ZERO); // EmptyDB returns non-zero hash - } - - #[test] - fn test_block_hash_different_blocks_different_hashes() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let hash_100 = sandbox.block_hash(100).unwrap(); - let hash_200 = sandbox.block_hash(200).unwrap(); - - assert_ne!(hash_100, hash_200); - } - - // ==================== Multiple accounts tests ==================== - - #[test] - fn test_multiple_accounts_in_journal() { - let mut journal = Journal::::new(EmptyDB::default()); - - // Add multiple accounts - for (i, addr) in [TEST_ADDR_1, TEST_ADDR_2, TEST_ADDR_3].iter().enumerate() { - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from((i + 1) * 1000), - nonce: i as u64, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(*addr, account); - } - - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Verify all accounts are accessible - let info1 = sandbox.basic(TEST_ADDR_1).unwrap().unwrap(); - assert_eq!(info1.balance, U256::from(1000)); - - let info2 = sandbox.basic(TEST_ADDR_2).unwrap().unwrap(); - assert_eq!(info2.balance, U256::from(2000)); - - let info3 = sandbox.basic(TEST_ADDR_3).unwrap().unwrap(); - assert_eq!(info3.balance, U256::from(3000)); - } - - // ==================== Journal priority tests ==================== - - #[test] - fn test_journal_state_takes_priority_over_database() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Storage slot 1 has value 42 in journal - // Even if database had a different value, journal takes priority - let value = sandbox.storage(TEST_ADDR_1, U256::from(1)).unwrap(); - assert_eq!(value, U256::from(42)); - } -} diff --git a/crates/mega-evm/src/sandbox/state_merge.rs b/crates/mega-evm/src/sandbox/state_merge.rs deleted file mode 100644 index 4ec3c5013..000000000 --- a/crates/mega-evm/src/sandbox/state_merge.rs +++ /dev/null @@ -1,910 +0,0 @@ -//! Sandbox state merge logic. -//! -//! Keeps the execution entry point focused on validation and sandbox orchestration while this -//! module owns the replay-sensitive details of applying sandbox state to the parent journal. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use alloy_evm::Database as AlloyDatabase; -use alloy_primitives::{Address, U256}; -use revm::{context::ContextTr, primitives::KECCAK_EMPTY, state::EvmState, Journal, JournalEntry}; -use tracing::error; - -use crate::{ - merge_evm_state_optional_status, ExternalEnvTypes, JournalInspectTr, MegaContext, MegaSpecId, -}; - -use super::error::KeylessDeployError; - -/// Applies all state changes from sandbox execution to the parent journal. -/// -/// All accounts from the sandbox view are merged into the parent journal — including accounts that -/// were only read and not written — because the `ReadSet` for stateless witness generation requires -/// knowing which accounts a sandbox touched. -/// -/// Coldness metadata is NOT merged: sandbox state changes are treated as a silent database update -/// that does not affect the parent transaction's own observable coldness-dependent gas costs. -/// Pre-Rex5 also keeps the legacy "do not merge status into existing parent accounts" behavior. -/// Rex5 records only the status entries needed for stateful diffs, such as created/touched account -/// markers, so normal journal commit/revert semantics stay correct. -/// -/// The sandbox runs with the signer's nonce overridden to `0` (Nick's Method), and the post-CREATE -/// nonce of `1` is intentionally preserved in the merged state to record that the signer has been -/// used for a keyless deploy. -/// -/// Pre-Rex5 keeps the legacy direct merge for replay compatibility. Rex5 records state-changing -/// diffs as journal entries so that an outer-frame revert or halt unwinds the sandbox's effects via -/// the normal checkpoint-revert mechanism. The Rex5 merge still keeps read-only accounts, bytecode, -/// and storage slots in the parent journal cache for witness generation; revm's default journal -/// entries can mark those cache entries cold again but cannot remove them from the cache map. -pub(super) fn apply_sandbox_state( - ctx: &mut MegaContext, - sandbox_state: EvmState, - _deploy_signer: Address, -) -> Result<(), KeylessDeployError> { - if ctx.spec.is_enabled(MegaSpecId::REX5) { - apply_sandbox_state_journaled(ctx, sandbox_state) - } else { - apply_sandbox_state_legacy(ctx, &sandbox_state); - Ok(()) - } -} - -/// Applies sandbox state with the pre-Rex5 direct merge. -/// -/// This intentionally bypasses revm journal entries to preserve historical replay semantics for -/// stable specs. -fn apply_sandbox_state_legacy( - ctx: &mut MegaContext, - sandbox_state: &EvmState, -) { - let journal = ctx.journal_mut(); - merge_evm_state_optional_status(&mut journal.state, sandbox_state, false); -} - -/// Applies sandbox state through an internal journal checkpoint. -/// -/// The checkpoint makes defensive merge errors atomic: partial journal entries are reverted before -/// the error is returned, while successful entries are committed into the caller's active -/// checkpoint. -fn apply_sandbox_state_journaled( - ctx: &mut MegaContext, - sandbox_state: EvmState, -) -> Result<(), KeylessDeployError> { - let journal = ctx.journal_mut(); - let checkpoint = journal.inner.checkpoint(); - match apply_sandbox_state_journaled_inner(journal, sandbox_state) { - Ok(()) => { - journal.inner.checkpoint_commit(); - Ok(()) - } - Err(error) => { - journal.inner.checkpoint_revert(checkpoint); - Err(error) - } - } -} - -/// Replays sandbox account diffs into the parent journal as revm journal entries. -/// -/// Stateful diffs become revertible by any enclosing frame checkpoint. Read/cache-only accounts, -/// bytecode, and storage slots may remain in the parent journal cache for witness generation. -fn apply_sandbox_state_journaled_inner( - journal: &mut Journal, - sandbox_state: EvmState, -) -> Result<(), KeylessDeployError> { - for (address, sandbox_account) in &sandbox_state { - // Ensure the account is loaded into the parent journal cache without warming it. - // Sandbox state merge must preserve the parent's own observable coldness-dependent gas - // semantics. `load_code = false` — this path doesn't read `info.code`. - journal.inspect_account(*address, false).map_err(|e| { - error!( - error = %e, - address = ?address, - "sandbox merge inspect_account failed", - ); - KeylessDeployError::InternalError - })?; - - if sandbox_account.is_selfdestructed() { - apply_sandbox_created_selfdestruct(journal, *address, sandbox_account)?; - continue; - } - - // Snapshot parent state before applying diffs. - let parent_balance = journal.inner.state.get(address).unwrap().info.balance; - let parent_nonce = journal.inner.state.get(address).unwrap().info.nonce; - let parent_code_hash = journal.inner.state.get(address).unwrap().info.code_hash; - - if sandbox_account.is_created() { - ensure_sandbox_create_can_merge(parent_nonce, parent_code_hash)?; - mark_account_created_for_sandbox_merge(journal, *address); - zero_parent_storage_absent_from_sandbox(journal, *address, sandbox_account); - } - - // Balance diff. - if sandbox_account.info.balance != parent_balance { - journal.inner.journal.push(JournalEntry::BalanceChange { - address: *address, - old_balance: parent_balance, - }); - journal.inner.state.get_mut(address).unwrap().info.balance = - sandbox_account.info.balance; - } - - if sandbox_account.info.nonce < parent_nonce { - error!( - address = ?address, - parent_nonce, - sandbox_nonce = sandbox_account.info.nonce, - "sandbox merge would decrease parent account nonce", - ); - return Err(KeylessDeployError::InternalError); - } - - // Nonce diff (one NonceChange entry per increment for correct revert). - let nonce_diff = sandbox_account.info.nonce - parent_nonce; - for _ in 0..nonce_diff { - journal.inner.journal.push(JournalEntry::NonceChange { address: *address }); - } - if nonce_diff > 0 { - journal.inner.state.get_mut(address).unwrap().info.nonce = sandbox_account.info.nonce; - } - - // Code diff. - if sandbox_account.info.code_hash == parent_code_hash { - // Treat empty cached bytecode as missing: when `code_hash != KECCAK_EMPTY` but the - // parent's loaded `info.code` is empty, the cache is stale (e.g. an `EmptyDB` returned - // a default Bytecode for the hash) and should be replaced by the sandbox's real load. - let parent_code_missing = journal - .inner - .state - .get(address) - .unwrap() - .info - .code - .as_ref() - .is_none_or(|code| code.is_empty()); - if parent_code_hash != KECCAK_EMPTY && parent_code_missing { - if let Some(code) = &sandbox_account.info.code { - // Preserve the old merge behavior for read-only code loads: bytecode cached by - // the sandbox is witness/cache metadata, not a stateful code change. - journal.inner.state.get_mut(address).unwrap().info.code = Some(code.clone()); - } - } - } else { - if parent_code_hash != KECCAK_EMPTY { - error!( - address = ?address, - "sandbox merge would replace non-empty parent code", - ); - return Err(KeylessDeployError::InternalError); - } - let Some(code) = &sandbox_account.info.code else { - error!( - address = ?address, - "sandbox account changed code hash without bytecode", - ); - return Err(KeylessDeployError::InternalError); - }; - journal.inner.set_code_with_hash( - *address, - code.clone(), - sandbox_account.info.code_hash, - ); - } - - // Touch — sandbox-modified accounts are genuinely touched in the parent tx. - if sandbox_account.is_touched() { - journal.inner.touch(*address); - } - - // Storage merge mirrors `merge_evm_state_optional_status(..., false)`: existing - // parent slots keep their original/cold metadata and only `present_value` changes; - // slots absent from the parent are inserted as cold, including read-only slots. - for (key, sandbox_slot) in &sandbox_account.storage { - let parent_slot = - journal.inner.state.get(address).and_then(|a| a.storage.get(key)).cloned(); - let had_value = parent_slot - .as_ref() - .map(|slot| slot.present_value) - .unwrap_or_else(|| sandbox_slot.original_value()); - if sandbox_slot.present_value != had_value { - journal.inner.journal.push(JournalEntry::StorageChanged { - key: *key, - had_value, - address: *address, - }); - } - - if let Some(parent_slot) = - journal.inner.state.get_mut(address).unwrap().storage.get_mut(key) - { - parent_slot.present_value = sandbox_slot.present_value; - } else { - let mut merged_slot = sandbox_slot.clone(); - merged_slot.mark_cold(); - journal.inner.state.get_mut(address).unwrap().storage.insert(*key, merged_slot); - } - } - } - - Ok(()) -} - -/// Validates that a sandbox-created account can be merged as a new parent account. -/// -/// Creating over an account with nonce or code would not match EVM `CREATE` semantics and is -/// treated as an internal merge invariant violation. -fn ensure_sandbox_create_can_merge( - parent_nonce: u64, - parent_code_hash: alloy_primitives::B256, -) -> Result<(), KeylessDeployError> { - if parent_nonce != 0 || parent_code_hash != KECCAK_EMPTY { - error!( - parent_nonce, - parent_code_hash = ?parent_code_hash, - "sandbox merge would create over non-empty parent account", - ); - return Err(KeylessDeployError::InternalError); - } - Ok(()) -} - -/// Marks an account as locally created and records the matching journal entry. -/// -/// The `AccountCreated` entry is required so final commit clears stale database storage and -/// checkpoint revert restores the previous account status. -fn mark_account_created_for_sandbox_merge( - journal: &mut Journal, - address: Address, -) { - let is_created_globally = journal.inner.state.get_mut(&address).unwrap().mark_created_locally(); - journal.inner.journal.push(JournalEntry::AccountCreated { address, is_created_globally }); -} - -/// Clears loaded parent storage slots that are absent from a sandbox-created account. -/// -/// A created account replaces any stale storage at the same address, so parent slots not present in -/// the sandbox result must be journaled to zero before commit. -fn zero_parent_storage_absent_from_sandbox( - journal: &mut Journal, - address: Address, - sandbox_account: &revm::state::Account, -) { - let parent_keys = - journal.inner.state.get(&address).unwrap().storage.keys().copied().collect::>(); - - for key in parent_keys { - if sandbox_account.storage.contains_key(&key) { - continue; - } - zero_parent_storage_slot(journal, address, key); - } -} - -/// Journals a loaded parent storage slot to zero when it still has a non-zero value. -fn zero_parent_storage_slot( - journal: &mut Journal, - address: Address, - key: U256, -) { - let had_value = journal - .inner - .state - .get(&address) - .and_then(|account| account.storage.get(&key)) - .map(|slot| slot.present_value()) - .unwrap_or_default(); - if had_value.is_zero() { - return; - } - journal.inner.journal.push(JournalEntry::StorageChanged { key, had_value, address }); - journal.inner.state.get_mut(&address).unwrap().storage.get_mut(&key).unwrap().present_value = - U256::ZERO; -} - -/// Applies the merge result for an account created and selfdestructed inside the sandbox. -/// -/// The parent commit must observe an empty created account: existing balance and loaded storage are -/// journaled to zero while the created marker is preserved. -fn apply_sandbox_created_selfdestruct( - journal: &mut Journal, - address: Address, - sandbox_account: &revm::state::Account, -) -> Result<(), KeylessDeployError> { - if !sandbox_account.is_created() { - error!( - address = ?address, - "sandbox selfdestructed account was not created in the sandbox", - ); - return Err(KeylessDeployError::InternalError); - } - - let parent = journal.inner.state.get(&address).unwrap(); - ensure_sandbox_create_can_merge(parent.info.nonce, parent.info.code_hash)?; - - mark_account_created_for_sandbox_merge(journal, address); - journal.inner.touch(address); - - let old_balance = journal.inner.state.get(&address).unwrap().info.balance; - if !old_balance.is_zero() { - journal.inner.journal.push(JournalEntry::BalanceChange { address, old_balance }); - journal.inner.state.get_mut(&address).unwrap().info.balance = U256::ZERO; - } - - let parent_keys = - journal.inner.state.get(&address).unwrap().storage.keys().copied().collect::>(); - for key in parent_keys { - zero_parent_storage_slot(journal, address, key); - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Bytes}; - use revm::{ - context_interface::journaled_state::JournalTr, - database::EmptyDB, - state::{Account, AccountInfo, EvmStorageSlot}, - Database, DatabaseCommit, - }; - - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - - fn sandbox_created_account(code: Bytes) -> Account { - let code = revm::bytecode::Bytecode::new_raw(code); - let code_hash = revm::primitives::keccak256(code.bytes_slice()); - let mut account = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash, - code: Some(code), - }); - account.mark_touch(); - account.mark_created(); - account - } - - #[test] - fn test_rex4_apply_sandbox_state_uses_legacy_direct_merge() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX4); - let checkpoint = JournalTr::checkpoint(ctx.journal_mut()); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - account - .storage - .insert(U256::from(0), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let journal = ctx.journal_mut(); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_created(), - "legacy merge should preserve created status for a newly inserted account" - ); - - JournalTr::checkpoint_revert(journal, checkpoint); - assert!( - journal.inner.state.contains_key(&deploy_addr), - "pre-Rex5 keeps the legacy direct-merge semantics instead of journal rollback" - ); - } - - /// Proves that `apply_sandbox_state` records journal entries for stateful diffs: - /// after a checkpoint-revert the parent values are restored, while revm may keep - /// cold cache/read-set entries that are not committed as state changes. - #[test] - fn test_rex5_apply_sandbox_state_revert_restores_parent() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let getter_addr = address!("cccccccccccccccccccccccccccccccccccc0003"); - let original_balance = U256::from(1_000_000u64); - let read_only_slot = U256::from(7); - let read_only_value = U256::from(123); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - - // Seed signer in parent state with known balance and nonce. - journal.inner.state.insert(signer, { - let mut acc = Account::from(AccountInfo { - balance: original_balance, - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - acc.mark_touch(); - acc - }); - let getter_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x01])); - let getter_code_hash = revm::primitives::keccak256(getter_code.bytes_slice()); - journal.inner.state.insert(getter_addr, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: getter_code_hash, - code: None, - }); - acc.mark_cold(); - acc - }); - - // Take a checkpoint before applying sandbox state. - let checkpoint = JournalTr::checkpoint(journal); - - // Build sandbox state: signer paid gas (lower balance, nonce bumped), - // deploy_addr is a new account with code and a storage slot. - let mut sandbox_state = EvmState::default(); - - // Signer: balance decreased, nonce = 1. - sandbox_state.insert(signer, { - let mut acc = Account::from(AccountInfo { - balance: U256::from(500_000u64), - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }); - acc.mark_touch(); - acc - }); - - // Deploy address: new account with code and storage. - sandbox_state.insert(deploy_addr, { - let mut acc = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - acc.storage - .insert(U256::from(0), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - acc - }); - sandbox_state.insert(getter_addr, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: getter_code_hash, - code: Some(getter_code), - }); - acc.storage.insert(read_only_slot, EvmStorageSlot::new(read_only_value, 0)); - acc - }); - - // Apply sandbox state — should record journal entries. - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - - // Verify merge applied. - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.balance, - U256::from(500_000u64), - "signer balance should reflect sandbox deduction" - ); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.nonce, - 1, - "signer nonce should be bumped" - ); - assert!( - journal.inner.state.contains_key(&deploy_addr), - "deploy address should exist after merge" - ); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_created(), - "created account status must be preserved for final commit" - ); - assert!( - journal.inner.state.get(&signer).unwrap().is_touched(), - "stateful signer diff should leave signer touched" - ); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_touched(), - "stateful deploy diff should leave deployed account touched" - ); - assert!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .info - .code - .as_ref() - .is_some_and(|code| !code.is_empty()), - "read-only bytecode loaded by sandbox should be cached for witnesses" - ); - assert_eq!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .storage - .get(&read_only_slot) - .map(|slot| slot.present_value()), - Some(read_only_value), - "read-only storage loaded by sandbox should be cached for witnesses" - ); - - // Revert to checkpoint — should undo all sandbox state changes. - JournalTr::checkpoint_revert(journal, checkpoint); - - // Verify parent state is restored. - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.balance, - original_balance, - "signer balance should be restored after revert" - ); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.nonce, - 0, - "signer nonce should be restored after revert" - ); - // deploy_addr was loaded from EmptyDB by apply_sandbox_state, so it can remain in - // the cache (AccountWarmed revert marks it cold, but does not remove it). Its - // stateful values must still be reverted. - if let Some(deploy_account) = journal.inner.state.get(&deploy_addr) { - assert_eq!( - deploy_account.info.code_hash, KECCAK_EMPTY, - "deployed code should be reverted" - ); - assert_eq!(deploy_account.info.nonce, 0, "deploy address nonce should be reverted"); - assert_eq!( - deploy_account.storage.get(&U256::from(0)).map(|slot| slot.present_value()), - Some(U256::ZERO), - "deployed storage should be reverted to the pre-sandbox value" - ); - } - assert!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .info - .code - .as_ref() - .is_some_and(|code| !code.is_empty()), - "read-only bytecode cache may remain after revert" - ); - assert_eq!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .storage - .get(&read_only_slot) - .map(|slot| slot.present_value()), - Some(read_only_value), - "read-only storage cache may remain after revert without becoming a stateful diff" - ); - } - - #[test] - fn test_rex5_apply_sandbox_state_error_reverts_partial_merge() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let original_balance = U256::from(1_000_000u64); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - journal.inner.state.insert(target, { - Account::from(AccountInfo { - balance: original_balance, - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - let journal_len_before = journal.inner.journal.len(); - let depth_before = journal.inner.depth; - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut account = Account::from(AccountInfo { - balance: U256::from(500_000u64), - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - account.mark_touch(); - account - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("nonce decrease should fail defensively"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&target).unwrap().info.balance, - original_balance, - "partial balance diff must be reverted on merge error" - ); - assert_eq!( - journal.inner.state.get(&target).unwrap().info.nonce, - 1, - "parent nonce must be restored on merge error" - ); - assert_eq!( - journal.inner.journal.len(), - journal_len_before, - "partial journal entries must be removed on merge error" - ); - assert_eq!(journal.inner.depth, depth_before, "checkpoint depth must be balanced"); - } - - #[test] - fn test_rex5_apply_sandbox_state_created_commit_clears_stale_storage() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let stale_slot = U256::from(9); - let deployed_slot = U256::from(0); - let mut db = MemoryDatabase::default(); - db.set_account_storage(deploy_addr, stale_slot, U256::from(99)); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - account - .storage - .insert(deployed_slot, EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let state = JournalTr::finalize(ctx.journal_mut()); - ctx.db_mut().commit(state); - - assert_eq!( - ctx.db_mut().storage(deploy_addr, deployed_slot).unwrap(), - U256::from(42), - "deployed storage should be committed" - ); - assert_eq!( - ctx.db_mut().storage(deploy_addr, stale_slot).unwrap(), - U256::ZERO, - "created-account commit must clear stale database storage" - ); - } - - #[test] - fn test_rex5_apply_sandbox_state_created_selfdestruct_revert_restores_parent() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let original_balance = U256::from(7); - let storage_slot = U256::from(3); - let original_storage = U256::from(11); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - journal.inner.state.insert(deploy_addr, { - let mut account = Account::from(AccountInfo { - balance: original_balance, - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - account.storage.insert(storage_slot, EvmStorageSlot::new(original_storage, 0)); - account - }); - let checkpoint = JournalTr::checkpoint(journal); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = Account::from(AccountInfo::default()); - account.mark_touch(); - account.mark_created(); - account.mark_selfdestruct(); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&deploy_addr).unwrap().info.balance, - U256::ZERO, - "created+selfdestructed account should be empty after merge" - ); - assert_eq!( - journal - .inner - .state - .get(&deploy_addr) - .unwrap() - .storage - .get(&storage_slot) - .unwrap() - .present_value(), - U256::ZERO, - "created+selfdestructed account should clear loaded parent storage" - ); - - JournalTr::checkpoint_revert(journal, checkpoint); - - let restored = journal.inner.state.get(&deploy_addr).unwrap(); - assert_eq!( - restored.info.balance, original_balance, - "balance should be restored after revert" - ); - assert_eq!( - restored.storage.get(&storage_slot).unwrap().present_value(), - original_storage, - "storage should be restored after revert" - ); - assert!(!restored.is_created(), "created marker should be reverted with the checkpoint"); - } - - /// Parent has non-empty code and the sandbox attempts to install a different code - /// hash — defensive merge MUST reject. Pinned because silently overwriting code on a - /// live account would let a keyless deploy hijack any address whose code happened to - /// be loaded into the cache during the parent's prior steps. - #[test] - fn test_rex5_apply_sandbox_state_rejects_non_empty_parent_code_replacement() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - // Parent: an existing contract with non-empty code. - let parent_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x01])); - let parent_code_hash = revm::primitives::keccak256(parent_code.bytes_slice()); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(target, { - Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - code_hash: parent_code_hash, - code: Some(parent_code), - }) - }); - - // Sandbox: tries to replace with a different code hash. - let sandbox_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x02])); - let sandbox_code_hash = revm::primitives::keccak256(sandbox_code.bytes_slice()); - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - code_hash: sandbox_code_hash, - code: Some(sandbox_code), - }); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject code replacement"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// Sandbox account reports a non-empty `code_hash` but no `info.code` payload. - /// Defensive merge MUST reject because the inner `set_code_with_hash` call would - /// otherwise panic / silently install no bytecode. - #[test] - fn test_rex5_apply_sandbox_state_rejects_code_hash_without_bytecode() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - // Parent: empty (KECCAK_EMPTY) so the "different code_hash, parent is empty" branch fires. - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - // Non-empty code_hash but `code: None` — exactly the invariant violation. - code_hash: revm::primitives::keccak256([0x60u8, 0x00]), - code: None, - }); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject mismatched code_hash without bytecode"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `ensure_sandbox_create_can_merge`: sandbox is marked `is_created()` but the - /// parent already has a non-zero nonce (not an empty slot). Defensive merge MUST - /// reject — committing a CREATE over an existing account would silently overwrite - /// its on-chain state. - #[test] - fn test_rex5_apply_sandbox_state_rejects_create_over_non_empty_parent_nonce() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(deploy_addr, { - Account::from(AccountInfo { - balance: U256::ZERO, - // Non-zero nonce triggers the rejection. - nonce: 5, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - - let mut sandbox_state = EvmState::default(); - sandbox_state - .insert(deploy_addr, sandbox_created_account(Bytes::from_static(&[0x60, 0x00]))); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject CREATE over non-empty parent"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `inspect_account` may surface a `DBError` (the DB call fails mid-merge). The - /// merge MUST translate that into the selector-only `InternalError` and revert any - /// partial journal entries via the inner checkpoint. Without this guard a DB blip - /// could leave a partially merged sandbox state in the parent journal. - #[test] - fn test_rex5_apply_sandbox_state_db_error_during_inspect_maps_to_internal_error() { - use crate::test_utils::ErrorInjectingDatabase; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - // The merge's first DB-touching step is the `inspect_account` call for each - // sandbox-modified address. Fail that lookup for `target`. - db.fail_on_account = Some(target); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo::default()); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("inspect_account DB error must surface as InternalError"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `apply_sandbox_created_selfdestruct` guard: sandbox account is selfdestructed - /// but NOT marked `is_created()`. That's not a same-tx CREATE+SELFDESTRUCT — it's - /// the sandbox trying to wipe an account that existed before the keyless tx. - /// Defensive merge MUST reject. - #[test] - fn test_rex5_apply_sandbox_state_rejects_selfdestruct_without_created_marker() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(target, { - Account::from(AccountInfo { - balance: U256::from(1u64), - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo::default()); - acc.mark_touch(); - // No `mark_created()`: this is the invariant violation. - acc.mark_selfdestruct(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject selfdestruct without created marker"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } -} diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md deleted file mode 100644 index dd2ad6442..000000000 --- a/crates/mega-evm/src/system/AGENTS.md +++ /dev/null @@ -1,57 +0,0 @@ -# AGENTS.md - -## OVERVIEW -System contract integration layer with canonical addresses, deployment transactions, and frame-init interception logic. - -## STRUCTURE -- `deploy.rs`: shared deployment primitive — declarative `SystemContractSpec`, the uniform `transact_deploy` state patch, and the `flat_system_contract_specs()` registry of all flat (storage-less) contracts. -- `oracle.rs`: oracle contract address, code constants, spec builder. -- `keyless_deploy.rs`: keyless deploy address, code constants, spec builder. -- `control.rs`: MegaAccessControl address, selectors, spec builder, revert payload builders. -- `limit_control.rs`: MegaLimitControl address and spec builder. -- `sequencer_registry.rs`: SequencerRegistry address, seeded deploy, role-change application, system-address resolution. -- `intercept.rs`: interceptor dispatch and synthetic frame-result handling. -- `tx.rs`: helpers for system/deposit-like transaction construction. - -## KEY PATTERNS -- Deployment helpers are idempotent and keyed by code hash equality. -- Gating happens in each contract's `_spec()` builder, which takes the resolved `MegaSpecId` and gates on `spec.reaches(...)` — POSITION comparison, so alias (rollback) windows do not retract deploys. Nothing in the deploy layer takes a hardfork config — the spec builders and the crate-private `*_for` helpers receive the resolved spec and typed params, so a per-fork activation gate cannot be reintroduced. The `pub` `transact_deploy_*` wrappers keep their `(hardforks, block_timestamp)` shape for external callers and resolve everything themselves. -- Builders must never gate on `is_enabled` (behavior): predeploys are one-way, and a hardfork that rolls behavior back does not un-deploy them or change which bytecode version is expected to be installed. -- Interceptors return `None` to fall through to on-chain bytecode on unknown selectors. -- View/control interceptors reject non-zero transfer values with `NonZeroTransfer()`. -- Synthetic interceptor results bypass normal child-frame init and require empty tracking frame push by caller. -- Keep selector constants and ABI encode/decode paths aligned with `mega-system-contracts` interfaces. -- Pre-block helpers (`transact_deploy_*`, `transact_apply_pending_changes`, etc.) return `Option` and let the block executor commit. They never call `db.commit(...)` directly — the executor fires `system_caller.on_state(source, &state)` between collection and commit, and that hook feeds the stateless witness generator. See `PRE-BLOCK STATE CHANGE CONTRACT` below. - -## PRE-BLOCK STATE CHANGE CONTRACT - -Pre-block helpers in this module participate in the `pre_execution_changes` → `commit_system_call_outcomes` pipeline on `MegaBlockExecutor`. The contract for a new or modified helper: - -- **Never call `db.commit(...)` inside the helper.** Return the prepared state; let the executor commit. -- **Return `Ok(None)` only when the step is gated out entirely** — wrong hardfork, feature disabled, etc. Not as an "already up to date" shortcut. -- **On an idempotent no-change path** (e.g., the contract is already deployed with the correct code hash), return `Some(EvmState)` that carries the observed account as a read-only entry: `Account { info, ..Default::default() }` with no `touched`/`created` flags. Returning `None` here is a bug — the account disappears from the stateless witness read set and the generated proof is incomplete. -- **On a real-change path**, include every account and storage slot the helper touched, including slots read in preparation for the change. The witness recorder must see the complete set. - -The returned `EvmState` serves two purposes, both load-bearing: - -1. **Commit** — `db.commit(state)` applies the writes. -2. **Witness recording** — `system_caller.on_state(source, &state)` runs before commit and feeds the stateless witness generator with the full read/write set for that outcome. Without this, a stateless client cannot verify the block against its pre-state. - -The counterpart block-executor side (collection, `on_state`, commit order) is documented in `crates/mega-evm/src/block/AGENTS.md`. - -## ANTI-PATTERNS -- Do not intercept unknown selectors with a synthetic revert unless spec requires it. -- Preserve on-chain-bytecode fallback for unknown calls. -- Do not accept value transfers for view/control interceptors unless explicitly specified and tested. -- Do not deploy system bytecode by raw literals in this crate. -- Reuse constants generated by `mega-system-contracts`. -- Do not call `db.commit(...)` inside a helper that participates in `pre_execution_changes`. It bypasses the `on_state` witness-recorder hook and silently produces incomplete stateless proofs. -- Do not return `None` from a helper on a "no change needed" path. Return `Some(EvmState)` with the account entries observed, even when nothing is written. - -## WHERE TO LOOK -- Add a new flat (storage-less) system contract deployment: new `.rs` with a `_spec()` builder, registered in `deploy.rs::flat_system_contract_specs()`. -- Add a stateful system contract with bespoke deploy logic (seeded storage, migration guards): own `transact_deploy_*` helper called from `block/executor.rs::pre_execution_changes` — see `sequencer_registry.rs`. -- Add interceptor method behavior: `intercept.rs` for decode/dispatch and revert policy. -- Change access-control volatile disable semantics: `control.rs` + `intercept.rs` + `access/tracker.rs`. -- Change keyless deploy interception entrypoint: `intercept.rs` and `keyless_deploy.rs`. -- Update system contract address or code hash references: corresponding module constant definitions. diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs deleted file mode 100644 index 1b9a753f1..000000000 --- a/crates/mega-evm/src/system/deploy.rs +++ /dev/null @@ -1,386 +0,0 @@ -//! Shared primitive for deploying `MegaETH` system (predeploy) contracts. -//! -//! Every system contract is materialized by the same state patch: set the -//! predeploy account's bytecode (idempotently, keyed on code hash), optionally -//! seed flat storage slots, and mark the account touched (and created on a fresh -//! deploy). The only things that differ per contract are the address, the -//! bytecode (which can vary by spec, e.g. the Oracle's v1.0.0 → v1.1.0 → v2.0.0 -//! line), whether an in-place upgrade should still mark the account created, and -//! whether any storage is seeded. -//! -//! [`SystemContractSpec`] captures those differences declaratively and -//! [`transact_deploy`] applies them uniformly, so the per-contract -//! `transact_deploy_*` wrappers and external tooling (foundry, `mega-evme`) share -//! one deployment path instead of re-implementing the pattern. -//! -//! Like the per-contract functions, `transact_deploy` does NOT commit to the -//! database — it returns the [`EvmState`] witness for the caller to commit. - -#[cfg(not(feature = "std"))] -use alloc as std; - -use alloy_evm::Database; -use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; -use revm::{ - database::State, - state::{Account, Bytecode, EvmState, EvmStorageSlot}, -}; -use std::vec::Vec; - -use crate::{MegaHardforks, MegaSpecId}; - -/// Declarative description of a single system-contract deployment. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SystemContractSpec { - /// Predeploy address the bytecode is installed at. - pub address: Address, - /// Runtime bytecode to install (already version-selected for the spec). - pub code: Bytes, - /// Keccak-256 hash of `code`. Used for the idempotence check. - pub code_hash: B256, - /// Flat storage slots to seed `(slot, value)` on a fresh deploy. Empty for - /// every contract except the `SequencerRegistry`. - pub seed: Vec<(U256, U256)>, - /// Whether an in-place bytecode upgrade of an already-existing account should - /// still mark it `created` (which clears its storage on commit). - /// - /// - `false` for the standard contracts (an upgrade preserves storage). - /// - For the Oracle this is `true` pre-Rex5 and `false` on Rex5+, preserving the canonical - /// mainnet state at the Rex2 boundary. - /// - `true` for the `SequencerRegistry` (always a fresh, seeded deploy). - pub force_create_on_upgrade: bool, -} - -impl SystemContractSpec { - /// A spec with no seeded storage and standard (storage-preserving) upgrade - /// semantics. - pub fn new(address: Address, code: Bytes, code_hash: B256) -> Self { - Self { address, code, code_hash, seed: Vec::new(), force_create_on_upgrade: false } - } - - /// Sets the seeded storage slots applied on a fresh deploy. - /// - /// Seeding applies only when the account is (re)created — a fresh deploy, or - /// an in-place upgrade with - /// [`with_force_create_on_upgrade`](Self::with_force_create_on_upgrade). A non-empty seed - /// on a storage-preserving upgrade is therefore ignored. - pub fn with_seed(mut self, seed: Vec<(U256, U256)>) -> Self { - self.seed = seed; - self - } - - /// Sets whether an in-place upgrade marks the account created. - pub fn with_force_create_on_upgrade(mut self, force: bool) -> Self { - self.force_create_on_upgrade = force; - self - } -} - -/// Deploys a system contract described by `spec`, returning the [`EvmState`] -/// witness (account + any seeded storage). The caller commits it. -/// -/// If the contract is already deployed with the matching code hash, the account -/// is returned read-only (marked neither touched nor created, no seeding) so it -/// is recorded in the witness without changing state. -pub fn transact_deploy( - db: &mut State, - spec: &SystemContractSpec, -) -> Result { - // The spec's `code_hash` must be the hash of its `code`. The per-contract - // `*_spec` builders derive both from one bytecode constant, so this only - // guards against a future hand-built spec installing code under a wrong hash. - debug_assert_eq!( - keccak256(spec.code.as_ref()), - spec.code_hash, - "SystemContractSpec code_hash does not match code for {:?}", - spec.address - ); - - let acc = db.load_cache_account(spec.address)?; - - // Already deployed with the correct code — record the read, change nothing. - let existing_info = acc.account_info(); - if let Some(account_info) = &existing_info { - if account_info.code_hash == spec.code_hash { - return Ok(EvmState::from_iter([( - spec.address, - Account { info: account_info.clone(), ..Default::default() }, - )])); - } - } - - let account_existed = existing_info.is_some(); - let mut acc_info = existing_info.unwrap_or_default(); - acc_info.code_hash = spec.code_hash; - acc_info.code = Some(Bytecode::new_raw(spec.code.clone())); - - let mut revm_acc: Account = acc_info.into(); - revm_acc.mark_touch(); - // Mark created on a fresh deploy, or when the contract opts to clear storage - // on an in-place upgrade. Not marking created preserves existing storage. - if !account_existed || spec.force_create_on_upgrade { - revm_acc.mark_created(); - // Seed only on (re)creation. Seeding onto an account whose storage is - // preserved (an in-place upgrade) would mix genesis slots into live - // storage and record a wrong `original_value` for an already-set slot. - for (slot, value) in &spec.seed { - revm_acc.storage.insert(*slot, EvmStorageSlot::new_changed(U256::ZERO, *value, 0)); - } - } - - Ok(EvmState::from_iter([(spec.address, revm_acc)])) -} - -/// Returns the deploy descriptors for the "flat" system contracts active at the -/// given block timestamp, in deploy order: Oracle, high-precision timestamp -/// Oracle, `KeylessDeploy`, `MegaAccessControl`, `MegaLimitControl`. -/// -/// This is the canonical, single-source-of-truth list both the block executor -/// and `mega-evme` iterate to materialize predeploys, instead of each hardcoding -/// the per-contract gate and bytecode selection. -/// -/// The `SequencerRegistry` (Rex5) is intentionally excluded: it seeds storage -/// from chain-config parameters, guards against overwriting foreign state, and is -/// paired with a pre-block `applyPendingChanges` system call — see -/// [`transact_deploy_sequencer_registry`](crate::transact_deploy_sequencer_registry). -pub fn flat_system_contract_specs( - hardforks: impl MegaHardforks, - block_timestamp: u64, -) -> Vec { - flat_system_contract_specs_for(hardforks.spec_id(block_timestamp)) -} - -/// [`flat_system_contract_specs`] against an already-resolved spec. -/// -/// The block executor resolves the spec once per block and calls this directly; the public -/// wrapper above resolves it for callers that hold a hardfork config. -pub(crate) fn flat_system_contract_specs_for(spec: MegaSpecId) -> Vec { - // Compose the per-contract spec builders (each its own single source of gate - // + bytecode-version selection). `None` entries (inactive contracts) drop out. - [ - super::oracle::oracle_spec(spec), - super::oracle::high_precision_timestamp_oracle_spec(spec), - super::keyless_deploy::keyless_deploy_spec(spec), - super::control::access_control_spec(spec), - super::limit_control::limit_control_spec(spec), - ] - .into_iter() - .flatten() - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - MegaHardfork, MegaHardforkConfig, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX2, - ORACLE_CONTRACT_CODE_HASH_REX5, - }; - use alloy_hardforks::ForkCondition; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, Database as _, DatabaseCommit}; - - fn addrs(specs: &[SystemContractSpec]) -> Vec
{ - specs.iter().map(|s| s.address).collect() - } - - const SEEDED_ADDR: Address = address!("0x6342000000000000000000000000000000000099"); - const SEED_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); - const UNRELATED_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); - - /// Builds a spec whose code hash differs from any pre-existing account, so - /// `transact_deploy` takes the bytecode-upgrade path rather than the - /// idempotent early return. - fn seeded_spec(force_create_on_upgrade: bool) -> SystemContractSpec { - let code = Bytes::from_static(&[0x60, 0x00]); - let code_hash = keccak256(&code); - SystemContractSpec::new(SEEDED_ADDR, code, code_hash) - .with_seed(Vec::from([(SEED_SLOT, U256::from(42))])) - .with_force_create_on_upgrade(force_create_on_upgrade) - } - - /// An in-place upgrade that does NOT recreate the account must not write seed - /// slots: doing so would mix genesis storage into preserved live storage and - /// record a wrong `original_value`. Guards the `force_create_on_upgrade = - /// false` + non-empty `seed` configuration that no current contract uses. - #[test] - fn test_seed_skipped_on_storage_preserving_upgrade() { - let mut db = InMemoryDB::default(); - // Pre-existing account with different bytecode (so the upgrade path runs) - // and a live value at the slot the spec would otherwise seed. - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - db.insert_account_storage(SEEDED_ADDR, SEED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_touched()); - assert!(!account.is_created(), "storage-preserving upgrade must not recreate"); - assert!( - !account.storage.contains_key(&SEED_SLOT), - "seed must not be written when storage is preserved" - ); - - // Committing the upgrade must leave the pre-existing slot at its old value. - state.commit(result); - assert_eq!( - state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), - U256::from(99), - "preserved storage must keep its pre-upgrade value after commit" - ); - } - - /// The same spec with `force_create_on_upgrade = true` recreates the account - /// and therefore does seed — the path the `SequencerRegistry` relies on. - #[test] - fn test_seed_written_on_force_created_upgrade() { - let mut db = InMemoryDB::default(); - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - // An unrelated live slot that recreation must clear. - db.insert_account_storage(SEEDED_ADDR, UNRELATED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(true)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "force_create_on_upgrade must recreate"); - let slot = account.storage.get(&SEED_SLOT).expect("seed slot must be written"); - assert_eq!(slot.present_value, U256::from(42)); - assert_eq!(slot.original_value, U256::ZERO); - - // Recreation clears prior storage: after commit the seed slot holds its - // value and the unrelated pre-existing slot reads back as zero. - state.commit(result); - assert_eq!(state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), U256::from(42)); - assert_eq!( - state.storage(SEEDED_ADDR, UNRELATED_SLOT).unwrap(), - U256::ZERO, - "recreation must clear unrelated pre-existing storage" - ); - } - - /// A fresh deploy seeds regardless of `force_create_on_upgrade`. - #[test] - fn test_seed_written_on_fresh_deploy() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "fresh deploy creates the account"); - assert_eq!( - account.storage.get(&SEED_SLOT).expect("seed slot must be written").present_value, - U256::from(42) - ); - } - - #[test] - fn test_registry_empty_before_mini_rex() { - // MiniRex activates at timestamp 100; nothing is active before it. - let hf = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)); - assert!(flat_system_contract_specs(&hf, 99).is_empty()); - } - - #[test] - fn test_registry_grows_with_hardforks_and_picks_oracle_version() { - let hf = MegaHardforkConfig::default().with_all_activated(); - let specs = flat_system_contract_specs(&hf, 0); - // Rex5 active → all five flat contracts, in deploy order, Oracle first. - assert_eq!(specs.len(), 5); - assert_eq!(specs[0].address, ORACLE_CONTRACT_ADDRESS); - // Rex5 → Oracle v2.0.0 and NOT force-created on upgrade. - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(!specs[0].force_create_on_upgrade); - // SequencerRegistry is intentionally not in the flat registry. - assert!(!addrs(&specs).contains(&crate::SEQUENCER_REGISTRY_ADDRESS)); - } - - /// Inside mainnet's `MiniRex1` rollback window the registry must still yield both `MiniRex` - /// predeploys. Gating on the executing spec (`EQUIVALENCE` there) would drop them, and with - /// them their read-only witness entries — a replay-observable change on frozen history. - #[test] - fn test_registry_survives_mainnet_rollback_window() { - let hf = crate::mainnet_hardforks(); - let ForkCondition::Timestamp(ts) = hf.mega_fork_activation(MegaHardfork::MiniRex1) else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - - let spec = hf.spec_id(ts); - assert_eq!(spec, crate::MegaSpecId::MINI_REX_1); - assert_eq!(spec.behavior(), crate::MegaSpecId::EQUIVALENCE); - - // The single scheduled spec keeps setup via position comparison even while its - // behavior projects back to EQUIVALENCE. - let specs = flat_system_contract_specs(&hf, ts); - assert_eq!( - addrs(&specs), - [ORACLE_CONTRACT_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS] - ); - // Still the pre-Rex2 bytecode line, with the pre-Rex5 upgrade semantics. - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH); - assert!(specs[0].force_create_on_upgrade); - } - - /// A config that schedules Rex6 without Rex5 must still materialize every lower-spec - /// predeploy, at the Rex5 Oracle version. Under per-fork gating none of them deployed. - #[test] - fn test_registry_complete_on_partial_ladder() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)); - - assert_eq!( - hf.mega_fork_activation(MegaHardfork::MiniRex), - ForkCondition::Never, - "no lower fork is scheduled" - ); - - let specs = flat_system_contract_specs(&hf, 0); - assert_eq!(specs.len(), 5, "the partial ladder must still deploy all five flat contracts"); - assert_eq!(specs[0].address, ORACLE_CONTRACT_ADDRESS); - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(!specs[0].force_create_on_upgrade); - } - - #[test] - fn test_registry_oracle_version_by_spec() { - // Only MiniRex active: Oracle v1.0.0, force-created on upgrade (pre-Rex5), - // and just Oracle + high-precision Oracle. - let mini = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let mini = flat_system_contract_specs(&mini, 0); - assert_eq!(mini.len(), 2); - assert_eq!(mini[0].code_hash, ORACLE_CONTRACT_CODE_HASH); - assert!(mini[0].force_create_on_upgrade); - - // Rex2 active but not Rex5: Oracle v1.1.0, still force-created on upgrade. - let rex2 = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - let rex2 = flat_system_contract_specs(&rex2, 0); - assert_eq!(rex2[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); - assert!(rex2[0].force_create_on_upgrade); - } -} diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs deleted file mode 100644 index 6420340e4..000000000 --- a/crates/mega-evm/src/system/intercept.rs +++ /dev/null @@ -1,619 +0,0 @@ -//! Trait and implementations for system contract call interception in `frame_init`. -//! -//! System contracts are intercepted before normal EVM frame initialization. -//! Each interceptor checks whether the call targets its contract address, -//! decodes the ABI input, and either performs a side-effect (returning `None` -//! to continue normal execution) or returns a synthetic [`FrameResult`] to -//! short-circuit frame creation. - -use alloy_evm::Database; -use alloy_primitives::Bytes; -use alloy_sol_types::{SolCall, SolError}; -use revm::{ - context::{ContextTr, LocalContextTr}, - handler::FrameResult, - interpreter::{CallInput, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult}, -}; - -use crate::{ - sandbox::execute_keyless_deploy_call, ExternalEnvTypes, IKeylessDeploy, IMegaAccessControl, - IMegaLimitControl, IOracle, MegaContext, MegaSpecId, OracleEnv, ACCESS_CONTROL_ADDRESS, - DISABLED_BY_PARENT_REVERT_DATA, KEYLESS_DEPLOY_ADDRESS, LIMIT_CONTROL_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; - -/// The result of a system contract call interception attempt. -/// -/// - `None`: The interceptor did not handle this call. The caller should try the next interceptor -/// or proceed with normal frame initialization. -/// - `Some(FrameResult)`: The interceptor handled the call and produced a synthetic result. The -/// caller should return this as `FrameInitResult::Result` and push an empty frame to keep the -/// limit tracker stack balanced. -pub type InterceptResult = Option; - -alloy_sol_types::sol! { - /// Shared error used by view/control system contract interceptors when value is sent. - error NonZeroTransfer(); -} - -/// Reads the first four bytes of a call input without materializing the full payload. -/// -/// Returns `None` when the input is shorter than four bytes. For -/// [`CallInput::SharedBuffer`], only the four-byte head slice is borrowed from -/// shared memory — the trailing bytes are never read. -#[inline] -fn peek_selector(input: &CallInput, ctx: &CTX) -> Option<[u8; 4]> { - let mut out = [0u8; 4]; - match input { - CallInput::Bytes(bytes) => { - if bytes.len() < 4 { - return None; - } - out.copy_from_slice(&bytes[..4]); - Some(out) - } - CallInput::SharedBuffer(range) => { - if range.len() < 4 { - return None; - } - let head = range.start..range.start + 4; - let slice = ctx.local().shared_memory_buffer_slice(head)?; - out.copy_from_slice(&slice); - Some(out) - } - } -} - -/// Trait for intercepting calls to system contracts during `frame_init`. -/// -/// Implementors check whether an incoming call matches their contract address and function -/// selectors, then either perform a side-effect or return a synthetic result. -/// -/// # Contract -/// -/// - The caller guarantees that `call_inputs` comes from a `FrameInput::Call`. Create frames are -/// never dispatched to interceptors. -/// - When the method returns `Some(FrameResult)`, the caller is responsible for calling -/// `additional_limit.push_empty_frame()` to keep the frame tracker stack balanced. -/// - Returning `Some(FrameResult)` produces a **synthetic** result that bypasses -/// `AdditionalLimit::before_frame_init`. The caller only pushes an empty tracking frame for stack -/// alignment; no per-frame gas adjustments (stipend, compute cap, etc.) are applied. If a future -/// interceptor needs full child-frame gas semantics, it must go through the normal frame -/// lifecycle instead of returning a synthetic result. -/// - When the method returns `None`, the caller proceeds as if no interception occurred. -pub trait SystemContractInterceptor { - /// Attempts to intercept a call to a system contract. - /// - /// # Arguments - /// - /// * `ctx` - The EVM context providing access to all `MegaETH` state. - /// * `call_inputs` - The call inputs (target address, input data, gas limit, caller, etc.). - /// * `depth` - The frame depth from `FrameInit::depth`, which equals the caller's journal - /// depth. - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult; -} - -/// Dispatches system contract interceptors in order. -/// -/// Returns `Some(FrameResult)` if any interceptor handled the call, `None` otherwise. -/// The caller is responsible for calling `push_empty_frame()` when `Some` is returned. -pub fn dispatch_system_contract_interceptors( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, -) -> InterceptResult { - let spec = ctx.spec; - - // Oracle Hint (Rex2+) — side-effect only, never returns Some. - // The assertion makes the invariant explicit so a future change that returns - // Some(FrameResult) is caught in debug builds rather than silently ignored. - if spec.is_enabled(OracleHintInterceptor::ACTIVATION_SPEC) { - let hint_result = OracleHintInterceptor::intercept(ctx, call_inputs, depth); - debug_assert!( - hint_result.is_none(), - "OracleHintInterceptor must be side-effect only and never short-circuit", - ); - } - - // Keyless Deploy (Rex2+) - if spec.is_enabled(KeylessDeployInterceptor::ACTIVATION_SPEC) { - if let Some(result) = KeylessDeployInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - // Access Control (Rex4+) - if spec.is_enabled(AccessControlInterceptor::ACTIVATION_SPEC) { - if let Some(result) = AccessControlInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - // MegaLimitControl (Rex4+) - if spec.is_enabled(LimitControlInterceptor::ACTIVATION_SPEC) { - if let Some(result) = LimitControlInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - None -} - -/// Returns a synthetic revert result when the call carries non-zero transferred value. -/// -/// This is used by view-style system contract interceptors to prevent silently accepting -/// value-bearing calls. -fn reject_non_zero_transfer(call_inputs: &CallInputs) -> InterceptResult { - if call_inputs.transfer_value().is_some_and(|value| !value.is_zero()) { - return Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Revert, - Bytes::copy_from_slice(&NonZeroTransfer::SELECTOR), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))); - } - None -} - -/// Interceptor for oracle hint calls (`IOracle::sendHint`). -/// -/// When a call to the oracle contract matches the `sendHint(bytes32,bytes)` selector, the -/// hint is forwarded to the oracle service backend via `OracleEnv::on_hint`. -/// Execution continues normally (no early return). -#[derive(Debug)] -pub struct OracleHintInterceptor; - -impl OracleHintInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX2; -} - -impl SystemContractInterceptor - for OracleHintInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != ORACLE_CONTRACT_ADDRESS { - return None; - } - - // REX6 mirrors the SLOAD volatile-access guard (`instructions::sload`) on this surface. - // Unlike SLOAD, `on_hint` forwarding is not gated on the disabled-subtree tracker on - // pre-REX6 specs, so a disabled (or since-reverted) child can still leak a hint to the - // off-chain backend there. The hint is an off-chain side-channel, not consensus - // state, so skip forwarding (return `None`) instead of reverting like SLOAD does — a - // revert here would change the caller's on-chain control flow for what should be a - // silently-dropped side effect. Uses the caller's depth passed by the dispatcher (not - // `HostExt::volatile_access_disabled`, which reads the current journal depth — at this - // point in `frame_init` that still is the caller's depth, but `depth` is the documented, - // explicit contract). Gated to REX6 (not retroactive to REX4/REX5): this restricts - // previously-ungated behavior and REX5 is sealed. - if ctx.spec.is_enabled(MegaSpecId::REX6) && - ctx.volatile_data_tracker.borrow().volatile_access_disabled(depth) - { - return None; - } - - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - - // REX5+: zero-gas calls cannot run the canonical Oracle bytecode anyway. Skip the - // hint forwarding and let the inner frame OOG canonically. Pre-REX5 the - // interceptor forwarded the hint regardless of `gas_limit`, which let a caller - // push payloads to the off-chain backend for free while the inner Oracle frame - // OOG'd. REX5+ closes that side channel. - if is_rex5_enabled && call_inputs.gas_limit == 0 { - return None; - } - - // REX5+: peek the selector first so non-matching dispatch never materializes the - // (potentially huge) calldata. For `sendHint` the full payload is still needed to - // decode the `bytes data` argument, but the allocation cost is now paid at most - // once per legitimate `sendHint` call. - if is_rex5_enabled { - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector != IOracle::sendHintCall::SELECTOR { - return None; - } - let input_bytes = call_inputs.input.bytes(ctx); - - // Meter the materialized payload against the TX data-size budget BEFORE - // decoding. The host has already paid the materialization cost; charge the - // raw `input_bytes.len()` so a caller cannot force unmetered host work by - // appending huge trailing bytes after a valid ABI envelope — - // `alloy_sol_types::abi_decode` silently accepts trailing junk (pinned by - // `test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls` - // below). This also subsumes the malformed-payload case: bytes are charged - // whether or not `abi_decode` later succeeds. - // - // The hint is a TX-scoped side-channel into the off-chain oracle backend - // (not consensus state), so we record into the TX intrinsic lane — same as - // calldata. On overflow: do NOT forward the hint, and do NOT synthesize a - // result. Returning `None` lets the next `before_frame_init` step observe - // the freshly-flipped `has_exceeded_limit` and produce the canonical - // TX-level `OutOfGas` halt via `create_exceeded_limit_result`. The failure - // shape (and rescued-gas refund) matches every other data-size overflow. - // - // Direct top-level Oracle transactions intentionally pay both the normal - // intrinsic calldata charge and this hint-side-channel charge. - let within = ctx - .additional_limit - .borrow_mut() - .record_oracle_hint_bytes(input_bytes.len() as u64); - if !within { - return None; - } - - // Trailing junk after a valid ABI envelope is silently dropped by - // `abi_decode`; a malformed envelope is rejected outright. In either case - // we have already charged for the host-side materialization above, so we - // just fall through without forwarding on the rejection path. - let Ok(call) = IOracle::sendHintCall::abi_decode(&input_bytes) else { - return None; - }; - - ctx.oracle_env.borrow().on_hint(call_inputs.caller, call.topic, call.data); - return None; - } - - // Pre-REX5 path verbatim — preserves replay determinism on stable specs. - let input_bytes = call_inputs.input.bytes(ctx); - if let Ok(call) = IOracle::sendHintCall::abi_decode(&input_bytes) { - ctx.oracle_env.borrow().on_hint(call_inputs.caller, call.topic, call.data); - } - - // Side-effect only — do not short-circuit. - None - } -} - -/// Interceptor for keyless deploy calls (`IKeylessDeploy::keylessDeploy`). -/// -/// Intercepts top-level calls to the keyless deploy contract, decodes the pre-EIP-155 -/// transaction, and executes deployment in a sandbox. -/// Only active when sandbox is not disabled (to prevent infinite recursion) and the call -/// is at depth 0. -#[derive(Debug)] -pub struct KeylessDeployInterceptor; - -impl KeylessDeployInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX2; -} - -impl SystemContractInterceptor - for KeylessDeployInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - // Only intercept at top-level and when sandbox is not disabled. - if ctx.is_inside_sandbox() || depth != 0 { - return None; - } - - if call_inputs.target_address != KEYLESS_DEPLOY_ADDRESS { - return None; - } - - // Peek selector before materializing calldata. The full payload is still - // decoded for the `(bytes, uint64)` args after the selector matches. - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector != IKeylessDeploy::keylessDeployCall::SELECTOR { - return None; - } - let input_bytes = call_inputs.input.bytes(ctx); - let call = IKeylessDeploy::keylessDeployCall::abi_decode(&input_bytes).ok()?; - Some(execute_keyless_deploy_call( - ctx, - call_inputs, - &call.keylessDeploymentTransaction, - call.gasLimitOverride, - )) - } -} - -/// Interceptor for `MegaAccessControl` system contract calls. -/// -/// Handles three functions: -/// - `disableVolatileDataAccess()`: activates volatile data access restriction at the caller's -/// depth. -/// - `enableVolatileDataAccess()`: re-enables volatile data access. Reverts with -/// `DisabledByParent()` if a parent frame disabled it. -/// - `isVolatileDataAccessDisabled()`: queries whether volatile data access is disabled at the -/// caller's depth. -#[derive(Debug)] -pub struct AccessControlInterceptor; - -impl AccessControlInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX4; -} - -impl AccessControlInterceptor { - /// Handles `disableVolatileDataAccess()`. Caller is the journal-depth of the frame - /// that issued the call; see `intercept`'s comment for the mapping rationale. - /// - /// Takes `&MegaContext` because the mutation goes through the interior `RefCell` - /// on `volatile_data_tracker`; the context itself is read immutably. - fn handle_disable( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - ctx.volatile_data_tracker.borrow_mut().disable_access(caller_journal_depth); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } - - fn handle_enable( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let success = ctx.volatile_data_tracker.borrow_mut().enable_access(caller_journal_depth); - let result = if success { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) - } else { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Revert, - Bytes::copy_from_slice(&DISABLED_BY_PARENT_REVERT_DATA), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) - }; - Some(result) - } - - fn handle_is_disabled( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let disabled = - ctx.volatile_data_tracker.borrow().volatile_access_disabled(caller_journal_depth); - let output = - IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&disabled); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::from(output), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } -} - -impl SystemContractInterceptor - for AccessControlInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != ACCESS_CONTROL_ADDRESS { - return None; - } - - // depth equals the caller's journal depth (because journal.depth = frame.depth + 1, - // and the caller's frame.depth = frame_init.depth - 1). - let caller_journal_depth = depth; - - // Admission is selector-match alone; do not add a length check. The historical - // `abi_decode::<()>` admission accepted selector + arbitrary trailing bytes, - // and that decision is consensus-visible under stable specs. - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR { - return Self::handle_disable(ctx, call_inputs, caller_journal_depth); - } - if selector == IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR { - return Self::handle_enable(ctx, call_inputs, caller_journal_depth); - } - if selector == IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR { - return Self::handle_is_disabled(ctx, call_inputs, caller_journal_depth); - } - // Unknown selector — not intercepted. - None - } -} - -/// Interceptor for `MegaLimitControl` system contract calls. -/// -/// Handles: -/// - `remainingComputeGas()`: returns remaining compute gas of the current call. -#[derive(Debug)] -pub struct LimitControlInterceptor; - -impl LimitControlInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX4; -} - -impl LimitControlInterceptor { - fn handle_remaining_compute_gas( - ctx: &MegaContext, - call_inputs: &CallInputs, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let remaining = ctx.additional_limit.borrow().current_call_remaining_compute_gas(); - let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&remaining); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::from(output), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } -} - -impl SystemContractInterceptor - for LimitControlInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - _depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != LIMIT_CONTROL_ADDRESS { - return None; - } - - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector == IMegaLimitControl::remainingComputeGasCall::SELECTOR { - return Self::handle_remaining_compute_gas(ctx, call_inputs); - } - // Unknown selector — not intercepted. - None - } -} - -#[cfg(test)] -mod tests { - use alloy_primitives::{Bytes, U256}; - use alloy_sol_types::SolCall; - use revm::{ - bytecode::opcode::{CALLCODE, MSTORE, RETURN}, - context::tx::TxEnvBuilder, - }; - - use crate::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, - }; - - const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; - - /// Pins the `abi_decode`-accepts-trailing-junk behaviour of `alloy-sol-types`'s - /// `decode_sequence::<()>` for parameterless system-contract methods. The - /// interceptor dispatch's selector-only admission relies on this: if a future - /// alloy upgrade rejects trailing bytes, historical replays would diverge from - /// the original `abi_decode` admission and break replay determinism on stable - /// specs. - #[test] - fn test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls() { - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let exact = selector; - let with_junk: Vec = selector.iter().copied().chain(core::iter::once(0xff)).collect(); - let with_pad: Vec = selector.iter().copied().chain([0u8; 32]).collect(); - - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&exact).is_ok(), - "exact 4-byte selector must decode", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_junk).is_ok(), - "current alloy-sol-types accepts selector+1B junk for empty-tuple decode; if this \ - fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_pad).is_ok(), - "current alloy-sol-types accepts selector+32B padding for empty-tuple decode; if \ - this fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - } - - /// Unit test for the explicit call-scheme guard in `frame_init`. - /// - /// A `CALLCODE` to a system contract address with a recognized selector must NOT be - /// intercepted. - /// The scheme guard rejects it before any interceptor sees the call. - /// The call falls through to on-chain bytecode, which reverts with `NotIntercepted()`, - /// leaving the `CALLCODE` success flag as 0. - #[test] - fn test_callcode_scheme_guard_skips_interception() { - let code = BytecodeBuilder::default() - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize (selector length) - .push_number(0_u64) // argsOffset (selector at memory[0]) - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALLCODE) // success flag (0=fail, 1=success) on stack - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let caller = alloy_primitives::address!("0000000000000000000000000000000000300000"); - let contract = alloy_primitives::address!("0000000000000000000000000000000000300001"); - - let mut db = MemoryDatabase::default() - .account_balance(caller, U256::from(1_000_000)) - .account_code(contract, code) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default() - .caller(caller) - .call(contract) - .gas_limit(100_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "outer tx should succeed"); - - let output = result.result.output().expect("should have output"); - let success_flag = U256::from_be_slice(output); - assert_eq!( - success_flag, - U256::ZERO, - "CALLCODE to system contract must not be intercepted — scheme guard must reject it" - ); - } -} diff --git a/crates/mega-evm/src/system/keyless_deploy.rs b/crates/mega-evm/src/system/keyless_deploy.rs deleted file mode 100644 index cd1acf6a3..000000000 --- a/crates/mega-evm/src/system/keyless_deploy.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! The keyless deploy system contract for the `MegaETH` EVM. -//! -//! This contract enables deploying contracts using pre-EIP-155 transactions (Nick's Method) -//! with custom gas limits, solving the problem of contracts failing to deploy on `MegaETH` -//! due to the different gas model. -//! -//! ## Nick's Method Overview -//! -//! Nick's Method allows deterministic contract deployment across different EVM chains without -//! needing the deployer's private key: -//! -//! 1. Create a contract deployment transaction (to = null, nonce = 0) -//! 2. Generate a random signature (v, r, s) with v = 27 or 28 (pre-EIP-155) -//! 3. Recover the signer address from the signature (nobody knows this private key) -//! 4. Fund the signer address with enough ETH for gas -//! 5. Broadcast the signed transaction -//! -//! The deployment address is deterministic: `keccak256(rlp([signer, 0]))[12:]` - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -// Re-export error types and transaction functions from sandbox -pub use crate::sandbox::{ - calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, recover_signer, - KeylessDeployError, -}; - -/// The address of the keyless deploy system contract. -pub const KEYLESS_DEPLOY_ADDRESS: Address = address!("0x6342000000000000000000000000000000000003"); - -/// The code of the keyless deploy contract (version 1.0.0). -pub use mega_system_contracts::keyless_deploy::V1_0_0_CODE as KEYLESS_DEPLOY_CODE; - -/// The code hash of the keyless deploy contract (version 1.0.0). -pub use mega_system_contracts::keyless_deploy::V1_0_0_CODE_HASH as KEYLESS_DEPLOY_CODE_HASH; - -pub use mega_system_contracts::keyless_deploy::IKeylessDeploy; - -/// Ensures the keyless deploy contract is deployed in the designated address and returns the -/// state changes. Note that the database `db` is not modified in this function. The caller is -/// responsible to commit the changes to database. -pub fn transact_deploy_keyless_deploy_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - keyless_deploy_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the keyless-deploy contract active under -/// `spec`, or `None` if `REX2` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn keyless_deploy_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX2).then(|| { - SystemContractSpec::new( - KEYLESS_DEPLOY_ADDRESS, - KEYLESS_DEPLOY_CODE, - KEYLESS_DEPLOY_CODE_HASH, - ) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::MegaHardforkConfig; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_deploy_keyless_deploy_contract_on_fresh_db() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert!(account.is_touched()); - assert!(account.is_created(), "fresh deploy must mark account as created"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - } - - /// Covers the `account_existed = true` branch: an account already exists with wrong code, - /// so the deploy updates the code without marking the account as created. - #[test] - fn test_deploy_keyless_deploy_contract_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - KEYLESS_DEPLOY_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "in-place bytecode update of an existing account must not mark it as created" - ); - } - - #[test] - fn test_deploy_keyless_deploy_contract_requires_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // A complete ladder topping out at Rex1: Rex2 is genuinely not reached. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX1); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Should succeed"); - assert_eq!(result, None, "should not deploy before Rex2 activation"); - } -} diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs deleted file mode 100644 index 6ef1847fb..000000000 --- a/crates/mega-evm/src/system/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! System contract and transaction helpers. -//! -//! # Pre-Block Helper Contract -//! -//! Deploy helpers and pre-block system-call helpers in this module -//! (`transact_deploy_*`, `transact_apply_pending_changes`, etc.) **must never** call -//! `db.commit(...)` directly. They return `Option` (or -//! `Option>`), and the block executor commits the collected outcomes -//! after running its `on_state` hook so the stateless witness generator captures the full -//! read/write set. -//! -//! Specifically: -//! -//! - Return `Ok(None)` only when the step is gated out entirely (wrong hardfork, etc.). -//! - On an idempotent "no change" path (e.g., the contract is already deployed with the correct -//! code hash), return `Some(EvmState)` containing the observed account as a read-only entry -//! (`Account { info, ..Default::default() }`, no `touched`/`created` flags). Returning `None` -//! here loses the account from the witness read set. -//! - On a real-change path, include every account and slot the helper touched, including slots read -//! in preparation for the change. -//! -//! See `crate::block` module docs for the executor side of this contract. - -mod control; -mod deploy; -mod intercept; -mod keyless_deploy; -mod limit_control; -mod oracle; -mod sequencer_registry; -mod tx; - -pub use control::*; -pub use deploy::*; -pub use intercept::*; -pub use keyless_deploy::*; -pub use limit_control::*; -pub use oracle::*; -pub use sequencer_registry::*; -pub use tx::*; diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs deleted file mode 100644 index fe9a9fa05..000000000 --- a/crates/mega-evm/src/system/oracle.rs +++ /dev/null @@ -1,605 +0,0 @@ -//! The oracle system contract for the `MegaETH` EVM. The oracle contract is implemented in -//! `../../../system-contracts/contracts/Oracle.sol`. - -use alloy_evm::Database; -use alloy_primitives::{address, b256, bytes, Address, Bytes, B256}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the oracle system contract. -pub const ORACLE_CONTRACT_ADDRESS: Address = address!("0x6342000000000000000000000000000000000001"); - -/// The code of the oracle contract (version 1.0.0, pre-Rex2). -pub use mega_system_contracts::oracle::V1_0_0_CODE as ORACLE_CONTRACT_CODE; - -/// The code hash of the oracle contract (version 1.0.0, pre-Rex2). -pub use mega_system_contracts::oracle::V1_0_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH; - -/// The code of the oracle contract (version 1.1.0, Rex2+). -/// This version includes the `sendHint` function for the oracle hint mechanism. -pub use mega_system_contracts::oracle::V1_1_0_CODE as ORACLE_CONTRACT_CODE_REX2; - -/// The code hash of the oracle contract (version 1.1.0, Rex2+). -pub use mega_system_contracts::oracle::V1_1_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH_REX2; - -/// The code of the oracle contract (version 2.0.0, Rex5+). -/// This version reads the authorized system address from `SequencerRegistry` instead of -/// using a constructor `immutable`, enabling system address change without redeployment. -pub use mega_system_contracts::oracle::V2_0_0_CODE as ORACLE_CONTRACT_CODE_REX5; - -/// The code hash of the oracle contract (version 2.0.0, Rex5+). -pub use mega_system_contracts::oracle::V2_0_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH_REX5; - -pub use mega_system_contracts::oracle::IOracle; - -/// Ensures the oracle contract is deployed in the designated address and returns the state changes. -/// Note that the database `db` is not modified in this function. The caller is responsible to -/// commit the changes to database. -/// -/// The deployed bytecode depends on the scheduled spec: -/// - Pre-Rex2: v1.0.0 bytecode (without `sendHint` function) -/// - Rex2 to Rex4: v1.1.0 bytecode (with `sendHint` function for oracle hints) -/// - Rex5+: v2.0.0 bytecode (reads the system address from the `SequencerRegistry`) -pub fn transact_deploy_oracle_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - oracle_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the Oracle contract active under `spec`, -/// or `None` if `MINI_REX` is not yet enabled. -/// -/// Single source of the Oracle's gate, bytecode-version selection, and upgrade -/// semantics — shared by [`transact_deploy_oracle_contract`] and the deploy -/// registry ([`flat_system_contract_specs`](crate::flat_system_contract_specs)). -/// -/// `spec` is the scheduled spec, gated by position (`reaches`) rather than behavior: an Oracle -/// already installed under `MINI_REX` stays installed through an alias (rollback) window. -pub(crate) fn oracle_spec(spec: MegaSpecId) -> Option { - if !spec.reaches(MegaSpecId::MINI_REX) { - return None; - } - - // Select the appropriate bytecode based on the spec. - // - Pre-Rex2: v1.0.0 (without `sendHint`) - // - Rex2-Rex4: v1.1.0 (with `sendHint`) - // - Rex5+: v2.0.0 (reads system address from SequencerRegistry) - let rex5 = spec.reaches(MegaSpecId::REX5); - let (target_code, target_code_hash) = if rex5 { - (ORACLE_CONTRACT_CODE_REX5, ORACLE_CONTRACT_CODE_HASH_REX5) - } else if spec.reaches(MegaSpecId::REX2) { - (ORACLE_CONTRACT_CODE_REX2, ORACLE_CONTRACT_CODE_HASH_REX2) - } else { - (ORACLE_CONTRACT_CODE, ORACLE_CONTRACT_CODE_HASH) - }; - - // Starting from Rex5 we stop marking the account as created on in-place bytecode upgrades so - // that the existing Oracle storage is preserved across the upgrade. Pre-Rex5 the old behaviour - // is preserved to maintain canonical mainnet state at the Rex2 activation boundary (where - // mainnet had non-zero DB-backed Oracle storage that was cleared by the old code). - Some( - SystemContractSpec::new(ORACLE_CONTRACT_ADDRESS, target_code, target_code_hash) - .with_force_create_on_upgrade(!rex5), - ) -} - -/// The address of the high precision timestamp oracle contract. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS: Address = - address!("0x6342000000000000000000000000000000000002"); - -/// The code hash of the high precision timestamp oracle contract. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH: B256 = - b256!("0x1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2"); - -/// The code of the high precision timestamp oracle contract. The oracle contract address is -/// embedded in to the contract code. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE: Bytes = bytes!("0x608060405234801561000f575f5ffd5b5060043610610064575f3560e01c806382ab890a1161004d57806382ab890a146100f55780638582b7bc1461010a578063b80777ea1461013f575f5ffd5b806328af7f3c146100685780633e6890fb146100a9575b5f5ffd5b61008f7f000000000000000000000000000000000000000000000000000000000000000881565b60405163ffffffff90911681526020015b60405180910390f35b6100d07f000000000000000000000000634200000000000000000000000000000000000181565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100a0565b6101086101033660046103b6565b610147565b005b6101317f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016100a0565b610131610154565b6101515f82610165565b50565b5f5f61015f5f610245565b92915050565b8161016f8161031a565b73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000063420000000000000000000000000000000000011663fbc0d0356101d5857f00000000000000000000000000000000000000000000000000000000000000006103cd565b60405160e083901b7fffffffff000000000000000000000000000000000000000000000000000000001681526004810191909152602481018590526044015f604051808303815f87803b15801561022a575f5ffd5b505af115801561023c573d5f5f3e3d5ffd5b50505050505050565b5f816102508161031a565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000634200000000000000000000000000000000000116637eba7ba66102b6857f00000000000000000000000000000000000000000000000000000000000000006103cd565b6040518263ffffffff1660e01b81526004016102d491815260200190565b602060405180830381865afa1580156102ef573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103139190610405565b9392505050565b63ffffffff7f00000000000000000000000000000000000000000000000000000000000000081661034c8260016103cd565b10610151576040517fef94d8420000000000000000000000000000000000000000000000000000000081526004810182905263ffffffff7f000000000000000000000000000000000000000000000000000000000000000816602482015260440160405180910390fd5b5f602082840312156103c6575f5ffd5b5035919050565b8082018082111561015f577f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f60208284031215610415575f5ffd5b505191905056fea2646970667358221220290614c973d24b9016b73a6b3fa98b2485a5c324199ceeb767818495dbe785e864736f6c634300081e0033"); - -/// Ensures the high precision timestamp oracle contract is deployed in the designated address and -/// returns the state changes. Note that the database `db` is not modified in this function. The -/// caller is responsible to commit the changes to database. -pub fn transact_deploy_high_precision_timestamp_oracle( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - high_precision_timestamp_oracle_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the high-precision timestamp Oracle -/// active under `spec`, or `None` if `MINI_REX` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see [`oracle_spec`]. -pub(crate) fn high_precision_timestamp_oracle_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::MINI_REX).then(|| { - SystemContractSpec::new( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - ) - }) -} - -#[cfg(test)] -mod tests { - use crate::MegaHardforkConfig; - - use super::*; - use alloy_primitives::keccak256; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_oracle_contract_code_hash_matches() { - // Compute the keccak256 hash of the oracle contract code (v1.0.0, pre-Rex2) - let computed_hash = keccak256(&ORACLE_CONTRACT_CODE); - - // Verify it matches the hardcoded constant - assert_eq!( - computed_hash, ORACLE_CONTRACT_CODE_HASH, - "Oracle contract code hash mismatch: computed {}, expected {}", - computed_hash, ORACLE_CONTRACT_CODE_HASH - ); - } - - #[test] - fn test_oracle_contract_code_hash_rex2_matches() { - // Compute the keccak256 hash of the oracle contract code (v1.1.0, Rex2+) - let computed_hash = keccak256(&ORACLE_CONTRACT_CODE_REX2); - - // Verify it matches the hardcoded constant - assert_eq!( - computed_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Oracle contract Rex2 code hash mismatch: computed {}, expected {}", - computed_hash, ORACLE_CONTRACT_CODE_HASH_REX2 - ); - } - - #[test] - fn test_deploy_oracle_contract_on_fresh_db() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5, so we expect Rex5 (v2.0.0) bytecode - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&ORACLE_CONTRACT_ADDRESS), - "State changes should contain oracle contract address" - ); - - // Verify the account in the state changes - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info (Rex5 = v2.0.0 bytecode) - let info = &account.info; - assert_eq!( - info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match the v2.0.0 value" - ); - assert!(info.code.is_some(), "Code should be set"); - - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - ORACLE_CONTRACT_CODE_REX5, - "Code bytes should match the v2.0.0 value" - ); - } - - #[test] - fn test_deploy_oracle_contract_idempotent() { - // Create a database with the oracle contract already deployed correctly (Rex5 = v2.0.0) - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX5, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX5)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should return state with the account marked as read (no update needed) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - assert_eq!( - result.len(), - 1, - "Deployment should return state with account marked as read when contract is already correctly deployed" - ); - - // Verify the account is in the result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_with_wrong_code_hash() { - // Create a database with the oracle address already having different code - let mut db = InMemoryDB::default(); - - // Insert an account with wrong code hash at the oracle address - let wrong_code = bytes!("0x6000"); - let wrong_code_hash = keccak256(&wrong_code); - - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex2 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should update the contract with correct code (Rex5 = v2.0.0 bytecode) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned (contract was updated) - assert_eq!(result.len(), 1, "Should have state changes to update the contract"); - - // Verify the updated account has the correct code hash - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should be updated to v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_marks_account_as_touched() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Get the account from result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist in result"); - - // Verify the account is marked as touched (required for state changes to be committed) - assert!( - account.is_touched(), - "Deployed account must be marked as touched for state changes to take effect" - ); - assert!(account.is_created(), "Account should be marked as created"); - } - - #[test] - fn test_deploy_oracle_contract_pre_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // A complete ladder topping out at Rex1 (pre-Rex2, pre-Rex5). - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX1); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH, - "Should deploy v1.0.0 bytecode pre-Rex2" - ); - } - - #[test] - fn test_deploy_oracle_contract_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // Activate Rex2 but not Rex5 - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Should deploy v1.1.0 bytecode on Rex2 (pre-Rex5)" - ); - } - - #[test] - fn test_deploy_oracle_contract_rex5() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // Activate all including Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Should deploy v2.0.0 bytecode on Rex5" - ); - } - - #[test] - fn test_deploy_oracle_contract_upgrade_to_rex2() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex2 active, Rex5 not active - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Should upgrade to v1.1.0 bytecode on Rex2 activation" - ); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!( - account.is_created(), - "Pre-Rex5 Oracle upgrades must still mark the account as created to match canonical mainnet state" - ); - } - - #[test] - fn test_deploy_oracle_contract_upgrade_to_rex5() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX2, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX2)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Should upgrade to v2.0.0 bytecode on Rex5 activation" - ); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!( - !account.is_created(), - "In-place bytecode upgrade must not mark the existing account as created, otherwise existing storage gets cleared on commit" - ); - } - - #[test] - fn test_high_precision_timestamp_oracle_deployment() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the high precision timestamp oracle contract - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), - "State changes should contain high precision timestamp oracle address" - ); - - // Verify the account in the state changes - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info - let info = &account.info; - assert_eq!( - info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash should match the expected value" - ); - assert!(info.code.is_some(), "Code should be set"); - - // Verify code matches - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - "Code bytes should match the expected value" - ); - - // Verify code hash matches computed hash - let computed_hash = keccak256(&HIGH_PRECISION_TIMESTAMP_ORACLE_CODE); - assert_eq!( - computed_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash constant should match computed hash" - ); - } - - /// Canonical-state regression: upgrading Oracle v1.0.0 → v1.1.0 at the Rex2 boundary - /// (pre-Rex5) MUST preserve the old `mark_created()` behaviour so that replay against - /// canonical mainnet state (which was built with the old code) produces the same state root. - /// On mainnet mainnet had non-zero DB-backed Oracle storage at the Rex2 boundary, and the old - /// code cleared it; the gated fix must not retroactively change that. - #[test] - fn test_oracle_storage_cleared_at_rex2_upgrade_canonical_behaviour() { - let stored_slot = revm::primitives::U256::from(42); - let stored_value = revm::primitives::U256::from(0xdeadbeefu64); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE)), - }, - ); - db.insert_account_storage(ORACLE_CONTRACT_ADDRESS, stored_slot, stored_value) - .expect("Should insert storage slot"); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex2 active, Rex5 NOT active → pre-Rex5 path → old behaviour preserved. - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); - assert!(account.is_touched()); - assert!( - account.is_created(), - "pre-Rex5: Oracle upgrade must still mark created to match canonical mainnet state" - ); - - // Commit the upgrade: because is_created=true the cache treats this as newly_created and - // storage is cleared — matching the canonical mainnet state root. - revm::DatabaseCommit::commit(&mut state, result); - - let read_back = revm::Database::storage(&mut state, ORACLE_CONTRACT_ADDRESS, stored_slot) - .expect("Storage read should succeed"); - assert_eq!( - read_back, - revm::primitives::U256::ZERO, - "pre-Rex5: Oracle storage must be cleared at Rex2 upgrade to match canonical mainnet state" - ); - } - - /// Regression: upgrading the Oracle bytecode from v1.1.0 (Rex2) to v2.0.0 (Rex5) - /// must not clear existing Oracle storage. - #[test] - fn test_oracle_storage_survives_rex2_to_rex5_upgrade() { - let stored_slot = revm::primitives::U256::from(7); - let stored_value = revm::primitives::U256::from(0xcafebabeu64); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX2, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX2)), - }, - ); - db.insert_account_storage(ORACLE_CONTRACT_ADDRESS, stored_slot, stored_value) - .expect("Should insert storage slot"); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex5 active → upgrade target is v2.0.0. - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Sanity check: this is an upgrade, not a fresh deploy. - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(account.is_touched()); - assert!(!account.is_created(), "upgrade must not mark account as created"); - - revm::DatabaseCommit::commit(&mut state, result); - - let read_back = revm::Database::storage(&mut state, ORACLE_CONTRACT_ADDRESS, stored_slot) - .expect("Storage read should succeed"); - assert_eq!(read_back, stored_value, "Oracle storage must survive bytecode upgrade"); - } - - /// Covers the `account_existed = true` branch in - /// `transact_deploy_high_precision_timestamp_oracle`: when the account already exists with - /// wrong code, the deploy updates the code without marking the account as created. - #[test] - fn test_high_precision_timestamp_oracle_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "existing account must not be marked as created on code update" - ); - } -} diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs deleted file mode 100644 index 1b7a64758..000000000 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ /dev/null @@ -1,1494 +0,0 @@ -//! The `SequencerRegistry` system contract for the `MegaETH` EVM. -//! -//! Tracks two independent roles: system address (Oracle/system-tx authority) and -//! sequencer (mini-block signing). Each role has its own change lifecycle. -//! -//! Unlike intercepted system contracts (`LimitControl`, `AccessControl`), this contract runs -//! normal on-chain bytecode. It does not have an interceptor. -//! -//! Deployed via raw state patch with initial storage seeded at deploy time. -//! Due changes are applied via a single pre-block EVM system call to -//! `applyPendingChanges()`, following the same pattern as EIP-2935 and EIP-4788. -//! The current system transaction sender should always be read through -//! [`resolve_system_address`], which returns the legacy constant for pre-REX5 and -//! reads the on-chain `SequencerRegistry` state for REX5+. - -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - Database, -}; -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, - INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, -}; -use revm::{ - context_interface::result::ResultAndState, - database::State, - primitives::KECCAK_EMPTY, - state::{Account, Bytecode, EvmState, EvmStorageSlot}, - Database as RevmDatabase, -}; - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use crate::{ - HardforkParams, HardforkParamsError, MegaHardfork, MegaHardforks, SystemContractSpec, - MEGA_SYSTEM_ADDRESS, -}; - -/// The address of the `SequencerRegistry` system contract. -pub const SEQUENCER_REGISTRY_ADDRESS: Address = - address!("0x6342000000000000000000000000000000000006"); - -/// The code of the `SequencerRegistry` contract (version 1.0.0, pre-Rex6). -pub use mega_system_contracts::sequencer_registry::V1_0_0_CODE as SEQUENCER_REGISTRY_CODE; - -/// The code hash of the `SequencerRegistry` contract (version 1.0.0, pre-Rex6). -pub use mega_system_contracts::sequencer_registry::V1_0_0_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH; - -/// The code of the `SequencerRegistry` contract (version 2.0.0, Rex6+). -/// This version requires an EIP-712 possession proof by the new sequencer key and a minimum -/// scheduling-to-activation delay when scheduling a sequencer change. -pub use mega_system_contracts::sequencer_registry::V2_0_0_CODE as SEQUENCER_REGISTRY_CODE_REX6; - -/// The code hash of the `SequencerRegistry` contract (version 2.0.0, Rex6+). -pub use mega_system_contracts::sequencer_registry::V2_0_0_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH_REX6; - -pub use mega_system_contracts::sequencer_registry::ISequencerRegistry; - -/// Bootstrap configuration for `SequencerRegistry` (attached to Rex5 via [`HardforkParams`]). -/// -/// The initial system address is fixed to [`MEGA_SYSTEM_ADDRESS`] at genesis and is not -/// configurable: pre-Rex5 components (payload executor, txpool, replay) all assume the -/// system tx sender equals the legacy constant, and a configurable initial value would -/// silently break those invariants. After Rex5 activation, the system address can be -/// rotated via the registry's scheduling/apply flow. -/// -/// Field names carry an explicit `rex5_` prefix because these values seed the -/// `SequencerRegistry` only when Rex5 activates; pre-Rex5 blocks read the system address -/// from the legacy constant and ignore this struct entirely. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SequencerRegistryConfig { - /// The initial sequencer (mini-block signing key) seeded at Rex5 activation. - pub rex5_initial_sequencer: Address, - /// The initial admin for the registry, seeded at Rex5 activation. - pub rex5_initial_admin: Address, -} - -impl HardforkParams for SequencerRegistryConfig { - const FORK: MegaHardfork = MegaHardfork::Rex5; - - fn validate(&self) -> Result<(), HardforkParamsError> { - if self.rex5_initial_sequencer.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.rex5_initial_sequencer must not be zero".into(), - }); - } - if self.rex5_initial_admin.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.rex5_initial_admin must not be zero".into(), - }); - } - Ok(()) - } -} - -/// Rotation-hardening configuration for `SequencerRegistry` v2.0.0 (attached to Rex6 via -/// [`HardforkParams`]). -/// -/// The value seeds the registry's `_minRotationDelay` storage slot when Rex6 activates: -/// on a fresh Rex6 bootstrap it is written alongside the other seeded slots, and on the -/// in-place v1.0.0 → v2.0.0 upgrade it is the only slot written. The contract exposes no -/// setter, so this is the effective delay until a future bytecode upgrade. -/// -/// Kept separate from the Rex5-pinned [`SequencerRegistryConfig`], with the same -/// fork-prefixed field-naming convention. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SequencerRegistryRex6Config { - /// The minimum number of blocks between scheduling a sequencer change and its activation - /// block, seeded into the registry at Rex6 activation. - pub rex6_min_rotation_delay: u64, -} - -impl HardforkParams for SequencerRegistryRex6Config { - const FORK: MegaHardfork = MegaHardfork::Rex6; - - fn validate(&self) -> Result<(), HardforkParamsError> { - // A zero delay disables the reaction window the field exists to guarantee, so it is a - // structural invariant rather than a policy choice. - if self.rex6_min_rotation_delay == 0 { - return Err(HardforkParamsError { - message: "SequencerRegistryRex6Config.rex6_min_rotation_delay must not be zero" - .into(), - }); - } - Ok(()) - } -} - -/// Encodes an address into its `U256` storage representation (standard Solidity address-in-slot). -fn address_to_storage_value(address: Address) -> U256 { - U256::from_be_bytes(address.into_word().0) -} - -/// Reads a committed `SequencerRegistry` storage slot. -fn read_registry_storage( - db: &mut State, - slot: U256, -) -> Result { - RevmDatabase::storage(db, SEQUENCER_REGISTRY_ADDRESS, slot).map_err(BlockExecutionError::other) -} - -/// Returns whether a pending role change is due and records every storage read into the witness -/// account. -fn is_role_due( - db: &mut State, - account: &mut Account, - pending_slot: U256, - activation_slot: U256, - block_number: u64, -) -> Result { - let pending = read_registry_storage(db, pending_slot)?; - // Read-only witness entry: record the slot access without marking it as changed. - account.storage.insert(pending_slot, EvmStorageSlot::new(pending, 0)); - if pending.is_zero() { - return Ok(false); - } - - let activation_block = read_registry_storage(db, activation_slot)?; - account.storage.insert(activation_slot, EvmStorageSlot::new(activation_block, 0)); - - Ok(block_number >= activation_block.saturating_to::()) -} - -/// Deploys the `SequencerRegistry` contract and seeds initial storage. -/// -/// The installed bytecode depends on the active hardfork: -/// - Rex5 (pre-Rex6): v1.0.0. -/// - Rex6+: v2.0.0 (rotation hardening: EIP-712 possession proof + minimum rotation delay). -/// -/// On first deploy, writes the flat storage slots: -/// - `_currentSystemAddress`, `_currentSequencer`, `_admin` -/// - `_initialSystemAddress`, `_initialSequencer`, `_initialFromBlock` -/// - `_minRotationDelay` (v2.0.0 only) -/// -/// At the Rex6 boundary, an already-deployed v1.0.0 registry is upgraded **in place**: the -/// bytecode is swapped to v2.0.0 and only the new `_minRotationDelay` slot is written, while -/// all live state (roles, pending changes, histories) is preserved. A pending sequencer change -/// scheduled under v1.0.0 therefore still activates normally under v2.0.0. -/// -/// The dynamic change-history arrays remain empty on bootstrap and grow only when -/// `applyPendingChanges()` commits a due change. -/// If already deployed with the correct code hash, returns the account as-is. -pub fn transact_deploy_sequencer_registry( - hardforks: impl MegaHardforks, - block_timestamp: u64, - current_block_number: u64, - db: &mut State, - config: &SequencerRegistryConfig, -) -> Result, BlockExecutionError> { - let spec = hardforks.spec_id(block_timestamp); - let rex6_config = hardforks.fork_params::(); - transact_deploy_sequencer_registry_for(spec, rex6_config, current_block_number, db, config) -} - -/// [`transact_deploy_sequencer_registry`] against an already-resolved spec. -/// -/// The block executor resolves the spec once per block and calls this directly; the public -/// wrapper above resolves it for callers that hold a hardfork config. Like the flat-registry -/// spec builders, this deliberately does not take a hardfork config — everything a deploy -/// depends on arrives resolved (the spec and the typed params), so a per-fork activation gate -/// cannot be reintroduced here. -pub(crate) fn transact_deploy_sequencer_registry_for( - spec: crate::MegaSpecId, - rex6_config: Option<&SequencerRegistryRex6Config>, - current_block_number: u64, - db: &mut State, - config: &SequencerRegistryConfig, -) -> Result, BlockExecutionError> { - // Gate and bytecode selection follow the scheduled spec, not per-fork registration: - // a registry once deployed stays deployed through a spec rollback, and a config that - // schedules only a later fork must still get the Rex5 bootstrap. - if !spec.reaches(crate::MegaSpecId::REX5) { - return Ok(None); - } - - // Belt-and-braces: `with_params` already calls `validate()` at chain-config load time. - debug_assert!( - config.validate().is_ok(), - "SequencerRegistryConfig::validate() failed at deploy time — \ - this should have been caught by with_params()" - ); - - // Select the bytecode version and, for v2.0.0, resolve the seeded minimum rotation delay. - // The Rex6 params are required as soon as Rex6 is active: failing fast here surfaces a - // misconfigured chain at the activation block instead of deploying an unseeded registry. - let rex6 = spec.reaches(crate::MegaSpecId::REX6); - let (target_code, target_code_hash) = if rex6 { - (SEQUENCER_REGISTRY_CODE_REX6, SEQUENCER_REGISTRY_CODE_HASH_REX6) - } else { - (SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_HASH) - }; - let min_rotation_delay = if rex6 { - let params = rex6_config.ok_or_else(|| BlockValidationError::BlockHashContractCall { - message: "Rex6 active but SequencerRegistryRex6Config not configured".into(), - })?; - debug_assert!( - params.validate().is_ok(), - "SequencerRegistryRex6Config::validate() failed at deploy time — \ - this should have been caught by with_params()" - ); - Some(U256::from(params.rex6_min_rotation_delay)) - } else { - None - }; - - // Guard against silently overwriting a foreign stateful contract, and handle - // the Rex6 v1.0.0 → v2.0.0 in-place upgrade. Both are specific to the registry - // (which carries change history); the generic deploy below otherwise - // overwrites bytecode in place. - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - if let Some(account_info) = acc.account_info() { - if rex6 && account_info.code_hash == SEQUENCER_REGISTRY_CODE_HASH { - // Rex6 boundary: in-place, storage-preserving v1.0.0 → v2.0.0 upgrade. The account - // is intentionally NOT marked created (that would clear live roles, pending changes - // and histories on commit), so it cannot go through the generic force-create - // deploy below; the only storage write is the new `_minRotationDelay` slot, which - // no v1.0.0 code path has ever touched. - let mut acc_info = account_info; - acc_info.code_hash = target_code_hash; - acc_info.code = Some(Bytecode::new_raw(target_code)); - - let mut revm_acc: Account = acc_info.into(); - revm_acc.mark_touch(); - - let original = read_registry_storage(db, MIN_ROTATION_DELAY)?; - let delay = min_rotation_delay.expect("Rex6 upgrade path implies Rex6 params"); - revm_acc - .storage - .insert(MIN_ROTATION_DELAY, EvmStorageSlot::new_changed(original, delay, 0)); - - return Ok(Some(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, revm_acc)]))); - } - if account_info.code_hash != target_code_hash && account_info.code_hash != KECCAK_EMPTY { - return Err(BlockValidationError::BlockHashContractCall { - message: format!( - "SequencerRegistry at {} has unexpected code hash {} (expected {}); \ - refusing to overwrite stateful contract storage without migration", - SEQUENCER_REGISTRY_ADDRESS, account_info.code_hash, target_code_hash, - ), - } - .into()); - } - } - - // Seed initial storage (flat slots only, no dynamic arrays). - // The initial system address is fixed to MEGA_SYSTEM_ADDRESS at genesis — see - // [`SequencerRegistryConfig`] for rationale. - let initial_system_address = address_to_storage_value(MEGA_SYSTEM_ADDRESS); - let initial_sequencer = address_to_storage_value(config.rex5_initial_sequencer); - let initial_admin = address_to_storage_value(config.rex5_initial_admin); - let initial_from_block = U256::from(current_block_number); - let mut seed = Vec::from([ - (CURRENT_SYSTEM_ADDRESS, initial_system_address), - (CURRENT_SEQUENCER, initial_sequencer), - (ADMIN, initial_admin), - (INITIAL_SYSTEM_ADDRESS, initial_system_address), - (INITIAL_SEQUENCER, initial_sequencer), - (INITIAL_FROM_BLOCK, initial_from_block), - ]); - // v2.0.0 fresh deploys additionally seed the minimum rotation delay. - if let Some(delay) = min_rotation_delay { - seed.push((MIN_ROTATION_DELAY, delay)); - } - - // The registry is always a fresh, seeded deploy (force_create), and the - // generic deploy returns the account read-only when it is already present - // with the matching code hash. (The Rex6 storage-preserving upgrade never - // reaches this point — it is handled above.) - let spec = SystemContractSpec::new(SEQUENCER_REGISTRY_ADDRESS, target_code, target_code_hash) - .with_seed(seed) - .with_force_create_on_upgrade(true); - let state = crate::transact_deploy(db, &spec).map_err(BlockExecutionError::other)?; - Ok(Some(state)) -} - -/// Returns `(due, witness_state)` where `due` indicates whether the caller should issue -/// the pre-block `applyPendingChanges()` system call. -/// -/// The returned `EvmState` captures all reads (account + storage slots) as a witness record. -/// The executor MUST push this into outcomes regardless of `due` so that the reads enter -/// the stateless witness via `system_caller.on_state()`. -pub(crate) fn is_apply_pending_changes_due( - db: &mut State, - block_number: u64, -) -> Result<(bool, EvmState), BlockExecutionError> { - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - - let Some(info) = acc.account_info() else { - // Account does not exist — record a not-existing account entry for the witness. - let account = Account::new_not_existing(0); - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - return Ok((false, state)); - }; - - // Account exists — build a read-only account entry to record all slot reads. - let mut account = Account { info, ..Default::default() }; - - let system_address_due = is_role_due( - db, - &mut account, - PENDING_SYSTEM_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - block_number, - )?; - let sequencer_due = - is_role_due(db, &mut account, PENDING_SEQUENCER, SEQUENCER_ACTIVATION_BLOCK, block_number)?; - - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - Ok((system_address_due || sequencer_due, state)) -} - -/// Executes the pre-block `applyPendingChanges()` system call on the `SequencerRegistry`. -/// -/// This single system call applies both the system address change and the sequencer -/// change if they are due in the current block. -/// Caller should gate this with [`is_apply_pending_changes_due`] to avoid an EVM -/// call on every block. -/// -/// The system call is issued with `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` -/// instead of the upstream-fixed 30M. `applyPendingChanges()` writes role-rotation -/// slots whose actual cost depends on REX dynamic storage gas, so the upstream default -/// is no longer guaranteed to be enough on activation blocks. -pub(crate) fn transact_apply_pending_changes( - evm: &mut crate::MegaEvm, -) -> Result, BlockExecutionError> -where - DB: alloy_evm::Database, - ExtEnvs: crate::ExternalEnvTypes, -{ - let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); - let gas_limit = - evm.block_env_ref().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - let result_and_state = match evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - gas_limit, - ) { - Ok(res) => res, - Err(e) => { - return Err(BlockValidationError::BlockHashContractCall { - message: format!("SequencerRegistry applyPendingChanges() system call failed: {e}"), - } - .into()); - } - }; - - if !result_and_state.result.is_success() { - return Err(BlockValidationError::BlockHashContractCall { - message: "SequencerRegistry applyPendingChanges() reverted or halted".into(), - } - .into()); - } - - Ok(result_and_state) -} - -/// Resolves the current system address. -/// -/// Must be called after `commit_system_call_outcomes()` so that `SequencerRegistry` is -/// already deployed and its storage committed. -/// -/// - Pre-REX5: returns `(MEGA_SYSTEM_ADDRESS, None)`. -/// - REX5: reads `_currentSystemAddress` from committed registry storage. -/// -/// The single `spec` is read through two projections that answer different questions: -/// `is_enabled` (behavior) gates whether dynamic system-address resolution applies — an alias -/// window whose behavior projects below REX5 returns [`MEGA_SYSTEM_ADDRESS`] again — while -/// `reaches` (position) selects which registry bytecode version the pre-block deploy installed, -/// which a rollback does not change. -/// -/// The optional `EvmState` captures account + slot reads as a witness record. -/// The executor MUST commit this via `system_caller.on_state()` + `db.commit()`. -pub fn resolve_system_address( - hardforks: impl MegaHardforks, - spec: crate::MegaSpecId, - db: &mut State, -) -> Result<(Address, Option), BlockExecutionError> { - // One spec, two projections: `is_enabled` (behavior) gates whether dynamic resolution - // applies at all; `reaches` (position) selects the installed bytecode version below. - if !spec.is_enabled(crate::MegaSpecId::REX5) { - return Ok((MEGA_SYSTEM_ADDRESS, None)); - } - - // Fail fast if Rex5 is active but params are not configured. - hardforks.fork_params::().ok_or_else(|| { - BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistryConfig not configured".into(), - } - })?; - - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - - // Unreachable: deploy always runs and commits before resolve. - let Some(info) = acc.account_info() else { - return Err(BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistry account does not exist".into(), - } - .into()); - }; - - // Unreachable: deploy verifies the code hash before seeding storage. The expected version - // follows the scheduled spec, matching what the pre-block deploy installed: the - // bytecode was already swapped to v2.0.0 at the Rex6 activation block, so an exact match - // holds on every block. - let expected_code_hash = if spec.reaches(crate::MegaSpecId::REX6) { - SEQUENCER_REGISTRY_CODE_HASH_REX6 - } else { - SEQUENCER_REGISTRY_CODE_HASH - }; - if info.code_hash != expected_code_hash { - return Err(BlockValidationError::BlockHashContractCall { - message: format!( - "SequencerRegistry code hash mismatch: expected {}, got {}", - expected_code_hash, info.code_hash - ), - } - .into()); - } - - // Build read-only witness: account entry + slot read. - let mut account = Account { info, ..Default::default() }; - let value = read_registry_storage(db, CURRENT_SYSTEM_ADDRESS)?; - // Read-only witness entry: record the slot access without marking it as changed. - account.storage.insert(CURRENT_SYSTEM_ADDRESS, EvmStorageSlot::new(value, 0)); - - // Unreachable: deploy seeds a non-zero initial system address. - if value.is_zero() { - return Err(BlockValidationError::BlockHashContractCall { - message: "SequencerRegistry deployed but _currentSystemAddress is zero".into(), - } - .into()); - } - - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - - Ok((Address::from_word(value.into()), Some(state))) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256, B256}; - use mega_system_contracts::sequencer_registry::storage_slots::PENDING_ADMIN; - use revm::{ - context::BlockEnv, - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - use crate::{MegaHardforkConfig, MegaSpecId}; - - const TEST_SEQUENCER: Address = address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); - const TEST_ADMIN: Address = address!("0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); - /// A non-system test address, used as a stand-in for a `_currentSystemAddress` that has - /// already been rotated away from the genesis `MEGA_SYSTEM_ADDRESS`. Distinct from - /// genesis so tests can tell the two apart. - const TEST_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); - - const TEST_MIN_ROTATION_DELAY: u64 = 100; - - fn test_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: TEST_SEQUENCER, - rex5_initial_admin: TEST_ADMIN, - } - } - - fn test_rex6_config() -> SequencerRegistryRex6Config { - SequencerRegistryRex6Config { rex6_min_rotation_delay: TEST_MIN_ROTATION_DELAY } - } - - /// A chain running Rex5: the pre-upgrade world where the registry runs v1.0.0. - fn rex5_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX5) - .with_params(test_config()) - } - - /// All hardforks including Rex6, with both registry param sets attached. - fn rex6_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()) - .with_params(test_rex6_config()) - } - - #[test] - fn test_code_hash_matches() { - assert_eq!(keccak256(&SEQUENCER_REGISTRY_CODE), SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(keccak256(&SEQUENCER_REGISTRY_CODE_REX6), SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_ne!(SEQUENCER_REGISTRY_CODE_HASH, SEQUENCER_REGISTRY_CODE_HASH_REX6); - } - - /// Verifies that Rust slot constants match the Solidity storage layout. - /// These values come from `forge inspect SequencerRegistry storage-layout`. - /// If the Solidity field order changes, this test MUST be updated. - #[test] - fn test_slot_constants_match_solidity_layout() { - assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::from(0), "_currentSystemAddress = slot 0"); - assert_eq!(CURRENT_SEQUENCER, U256::from(1), "_currentSequencer = slot 1"); - assert_eq!(ADMIN, U256::from(2), "_admin = slot 2"); - assert_eq!(PENDING_ADMIN, U256::from(3), "_pendingAdmin = slot 3"); - assert_eq!(INITIAL_SYSTEM_ADDRESS, U256::from(4), "_initialSystemAddress = slot 4"); - assert_eq!(INITIAL_SEQUENCER, U256::from(5), "_initialSequencer = slot 5"); - assert_eq!(INITIAL_FROM_BLOCK, U256::from(6), "_initialFromBlock = slot 6"); - assert_eq!(PENDING_SYSTEM_ADDRESS, U256::from(7), "_pendingSystemAddress = slot 7"); - assert_eq!( - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(8), - "_systemAddressActivationBlock = slot 8" - ); - assert_eq!(PENDING_SEQUENCER, U256::from(9), "_pendingSequencer = slot 9"); - assert_eq!( - SEQUENCER_ACTIVATION_BLOCK, - U256::from(10), - "_sequencerActivationBlock = slot 10" - ); - // Slots 11 (_systemAddressHistory) and 12 (_sequencerHistory) are dynamic arrays. - assert_eq!(MIN_ROTATION_DELAY, U256::from(13), "_minRotationDelay = slot 13 (v2.0.0+)"); - } - - #[test] - fn test_deploy_requires_rex5() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - MegaHardforkConfig::default(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap(); - assert_eq!(result, None); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_sequencer() { - let mut config = test_config(); - config.rex5_initial_sequencer = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_sequencer must be rejected"); - assert!( - err.message.contains("rex5_initial_sequencer must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_admin() { - let mut config = test_config(); - config.rex5_initial_admin = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_admin must be rejected"); - assert!( - err.message.contains("rex5_initial_admin must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_deploy_seeds_storage() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(account.storage.len(), 6, "should write exactly 6 flat slots"); - - assert_eq!( - account.storage.get(&CURRENT_SYSTEM_ADDRESS).unwrap().present_value(), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - "initial system address is hardcoded to MEGA_SYSTEM_ADDRESS", - ); - assert_eq!( - account.storage.get(&INITIAL_SYSTEM_ADDRESS).unwrap().present_value(), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - "_initialSystemAddress is hardcoded to MEGA_SYSTEM_ADDRESS", - ); - assert_eq!( - account.storage.get(&CURRENT_SEQUENCER).unwrap().present_value(), - U256::from_be_bytes(TEST_SEQUENCER.into_word().0), - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value(), - U256::from_be_bytes(TEST_ADMIN.into_word().0), - ); - assert_eq!( - account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), - U256::from(1000), - ); - } - - #[test] - fn test_deploy_is_idempotent() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 2000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "idempotent deploy should not re-create"); - assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); - } - - #[test] - fn test_deploy_wrong_existing_code_hash_returns_error() { - let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: wrong_code.hash_slow(), - code: Some(wrong_code), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let err = - transact_deploy_sequencer_registry(&hardforks, 0, 2000, &mut state, &test_config()) - .expect_err("wrong code hash must fail closed"); - - let msg = err.to_string(); - assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); - assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); - } - - #[test] - fn test_deploy_on_top_of_eoa_with_balance() { - let mut db = InMemoryDB::default(); - // Simulate an EOA that received ETH before Rex5. - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() // code_hash = KECCAK_EMPTY - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - // Pre-existing balance is preserved. - assert_eq!(account.info.balance, U256::from(1_000_000)); - } - - #[test] - fn test_validate_rejects_zero_min_rotation_delay() { - let config = SequencerRegistryRex6Config { rex6_min_rotation_delay: 0 }; - let err = config.validate().expect_err("zero rex6_min_rotation_delay must be rejected"); - assert!( - err.message.contains("rex6_min_rotation_delay must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_deploy_fresh_at_rex6_seeds_v2_with_min_rotation_delay() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - account.storage.len(), - 7, - "fresh Rex6 deploy writes the 6 bootstrap slots plus _minRotationDelay" - ); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value(), - U256::from_be_bytes(TEST_ADMIN.into_word().0), - ); - assert_eq!( - account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), - U256::from(1000), - ); - } - - #[test] - fn test_deploy_rex6_upgrades_v1_in_place_preserving_storage() { - // A live V1 registry with a pending sequencer change and a non-empty history. The Rex6 - // upgrade must swap only the bytecode and write only the new _minRotationDelay slot. - let pending_sequencer = address!("0x1111111111111111111111111111111111111111"); - let sequencer_history_length_slot = U256::from(12); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - TEST_SEQUENCER.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - pending_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(2000), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - sequencer_history_length_slot, - U256::from(1), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1500, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "in-place upgrade must not recreate the account"); - assert!(account.is_touched()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!(account.storage.len(), 1, "only _minRotationDelay is written on upgrade"); - let slot = account.storage.get(&MIN_ROTATION_DELAY).unwrap(); - assert_eq!(slot.original_value(), U256::ZERO); - assert_eq!(slot.present_value(), U256::from(TEST_MIN_ROTATION_DELAY)); - - // After commit, the live pre-upgrade storage must be intact next to the new slot. - revm::DatabaseCommit::commit(&mut state, result); - assert_eq!( - read_registry_storage(&mut state, PENDING_SEQUENCER).unwrap(), - U256::from_be_bytes(pending_sequencer.into_word().0), - ); - assert_eq!( - read_registry_storage(&mut state, SEQUENCER_ACTIVATION_BLOCK).unwrap(), - U256::from(2000), - ); - assert_eq!( - read_registry_storage(&mut state, sequencer_history_length_slot).unwrap(), - U256::from(1), - ); - assert_eq!( - read_registry_storage(&mut state, MIN_ROTATION_DELAY).unwrap(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - assert_eq!( - read_registry_storage(&mut state, CURRENT_SEQUENCER).unwrap(), - U256::from_be_bytes(TEST_SEQUENCER.into_word().0), - ); - } - - #[test] - fn test_deploy_rex6_is_idempotent_when_v2_present() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "idempotent deploy should not re-create"); - assert!(!account.is_touched(), "idempotent deploy should not touch the account"); - assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); - } - - #[test] - fn test_deploy_rex6_missing_config_errors() { - // Rex6 active but only the Rex5 params attached: deploy must fail fast instead of - // installing a v2.0.0 registry with an unseeded _minRotationDelay. - let hardforks = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()); - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .expect_err("missing Rex6 params must fail closed"); - assert!( - err.to_string().contains("SequencerRegistryRex6Config not configured"), - "unexpected message: {err}" - ); - } - - #[test] - fn test_deploy_rex6_on_top_of_eoa_with_balance() { - let mut db = InMemoryDB::default(); - // Simulate an EOA that received ETH before the registry was ever deployed. Even at - // Rex6 this is a fresh bootstrap, not a storage-preserving upgrade: the full seed - // (including _minRotationDelay) must be written. - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!(account.info.balance, U256::from(1_000_000)); - assert_eq!(account.storage.len(), 7); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - } - - #[test] - fn test_deploy_rex6_wrong_existing_code_hash_errors() { - let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: wrong_code.hash_slow(), - code: Some(wrong_code), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .expect_err("wrong code hash must fail closed"); - - let msg = err.to_string(); - assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); - assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); - } - - #[test] - fn test_resolve_rex6_expects_v2_code_hash() { - // A V2 registry resolves normally at REX6. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - assert!(witness.is_some()); - } - - #[test] - fn test_resolve_rex6_rejects_v1_code_hash() { - // At REX6 the pre-block deploy has already upgraded the bytecode, so a V1 code hash at - // resolve time is a broken pipeline and must fail closed. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state) - .expect_err("V1 code hash at REX6 must fail closed"); - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_resolve_pre_rex5_returns_legacy() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, _) = - resolve_system_address(MegaHardforkConfig::default(), MegaSpecId::REX4, &mut state) - .unwrap(); - assert_eq!(addr, MEGA_SYSTEM_ADDRESS); - } - - #[test] - fn test_resolve_rex5_returns_stored_system_address_with_witness() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - - // Witness must capture the registry account and the CURRENT_SYSTEM_ADDRESS slot. - let witness = witness.expect("post-deploy resolve must produce witness"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("registry account in witness"); - assert_eq!(acc.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert!( - acc.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), - "witness must include CURRENT_SYSTEM_ADDRESS slot" - ); - assert_eq!(acc.storage.len(), 1, "witness should contain exactly one slot"); - let slot = acc.storage.get(&CURRENT_SYSTEM_ADDRESS).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - - #[test] - fn test_resolve_rex5_zero_slot_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state); - assert!(result.is_err(), "zero _currentSystemAddress should be an error"); - } - - #[test] - fn test_resolve_rex5_missing_registry_errors() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let err = resolve_system_address(&hardforks, MegaSpecId::REX5, &mut state) - .expect_err("missing registry at Rex5 must fail closed"); - assert!(err.to_string().contains("does not exist")); - } - - #[test] - fn test_resolve_rex5_wrong_code_hash_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: B256::ZERO, - code: Some(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state) - .expect_err("wrong code hash must fail closed"); - - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_is_apply_pending_changes_due_no_registry() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must contain a not-existing account entry. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert_eq!(acc.status, revm::state::AccountStatus::LoadedAsNotExisting); - assert!(acc.storage.is_empty(), "no-registry witness should have no slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_no_pending() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must include both PENDING_* slots (both zero = no change pending). - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert!( - acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS), - "witness must include PENDING_SYSTEM_ADDRESS" - ); - assert!( - acc.storage.contains_key(&PENDING_SEQUENCER), - "witness must include PENDING_SEQUENCER" - ); - // No activation slots needed because both pending values are zero. - assert_eq!(acc.storage.len(), 2, "no-pending witness should have exactly 2 slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_system_address_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_addr = address!("0x1111111111111111111111111111111111111111"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_addr.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - // Not yet due at block 999. - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 999).unwrap(); - assert!(!due, "not yet due"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - - // Exactly due at block 1000 (fresh State to avoid cache from prior call). - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(due, "exactly due"); - // Both roles' pending slots are always read into the witness. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - } - - #[test] - fn test_is_apply_pending_changes_due_sequencer_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(500), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 500).unwrap(); - assert!(due); - // System address has no pending change (slot is zero) so only PENDING_SYSTEM_ADDRESS - // is read. Then sequencer path reads PENDING_SEQUENCER + SEQUENCER_ACTIVATION_BLOCK. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 3); - } - - #[test] - fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_sys = address!("0x1111111111111111111111111111111111111111"); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_sys.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1001), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!( - due, - "sequencer change should still trigger the pre-block call when the system address is not due yet" - ); - // System address is not due (activation at 1001) but its pending slot + activation - // slot are still read. Then the sequencer path reads its own pending + activation. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 4, "both roles' slots should be in the witness"); - for slot_key in [ - PENDING_SYSTEM_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - PENDING_SEQUENCER, - SEQUENCER_ACTIVATION_BLOCK, - ] { - let slot = acc.storage.get(&slot_key).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - } - - #[test] - fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let next_system_address = address!("0x1111111111111111111111111111111111111111"); - let next_sequencer = address!("0x2222222222222222222222222222222222222222"); - - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - TEST_SEQUENCER.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - next_system_address.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - next_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let result = - transact_apply_pending_changes(&mut evm).expect("applyPendingChanges() should succeed"); - let state = result.state; - drop(evm); - - revm::DatabaseCommit::commit(&mut db, state); - - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS) - .unwrap(), - address_to_storage_value(next_system_address), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER) - .unwrap(), - address_to_storage_value(next_sequencer), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - } - - #[test] - fn test_transact_apply_pending_changes_uses_block_gas_limit() { - // Block gas_limit > 30M must be passed through to the system call so that - // applyPendingChanges() can absorb the variable cost from REX dynamic - // storage gas instead of being capped at the upstream-fixed 30M. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 250_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!(revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, 250_000_000); - } - - #[test] - fn test_transact_apply_pending_changes_respects_30m_floor() { - // When the block gas limit is below the 30M floor, the system call must - // still receive at least the historical default budget. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 1_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!( - revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, - crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR, - ); - } - - #[test] - fn test_transact_apply_pending_changes_errors_when_registry_reverts() { - let revert_code = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: revert_code.hash_slow(), - code: Some(revert_code), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let err = transact_apply_pending_changes(&mut evm) - .expect_err("reverting registry bytecode must fail closed"); - - assert!(err.to_string().contains("reverted or halted")); - } -} diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs deleted file mode 100644 index 4d3fcc06f..000000000 --- a/crates/mega-evm/src/system/tx.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! System transaction for the `MegaETH` EVM. -//! -//! The mega system transaction is a special protocol-maintenance transaction with minimal -//! side effects: -//! - no transaction fee (no L2 gas fee, no L1 data fee, no base fee, etc.), thus no state change to -//! the block beneficiary or any fee vaults. -//! - system address's nonce still bumps as normal transactions -//! -//! This module contains constants, types, and utilities related to mega system transactions. - -use alloy_primitives::{address, b256, Address, TxKind, B256}; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; -use revm::context::Transaction; - -use crate::{types::MegaTransaction, ORACLE_CONTRACT_ADDRESS}; - -/// The `MegaETH` system address for deposit-like transaction processing. -/// Normal transactions sent from this address are processed as deposit transactions, -/// bypassing signature validation, nonce verification, and fee deduction. -/// -/// It can only call whitelisted addresses. -pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); - -/// The whitelist of addresses that are allowed to be called by the `MegaETH` system address. -pub const MEGA_SYSTEM_TX_WHITELIST: &[Address] = &[ORACLE_CONTRACT_ADDRESS]; - -/// The source hash of the `MegaETH` system transaction, used to set the `source_hash` field of the -/// op deposit info. The value is `keccak256("MEGA_SYSTEM_TRANSACTION")`. -pub const MEGA_SYSTEM_TRANSACTION_SOURCE_HASH: B256 = - b256!("852c082c0faff590c6300c2c34815d1f79882552fa95ba413cd5aeb1dba84957"); - -/// The source hash of the `MegaETH` keyless-deploy sandbox transaction. Used to set the -/// `source_hash` field of the op deposit info so the sandbox tx is treated as a deposit-like -/// transaction (bypasses L1/operator fee, validation, fee distribution). The value is -/// `keccak256("MEGA_SANDBOX_TRANSACTION")`. -pub const SANDBOX_TX_SOURCE_HASH: B256 = - b256!("3bc757a39ecb6dc5b5e5715352016c2b6fd38968a78cc57e878d9be249bc62f4"); - -/// Checks if a transaction is sent from the given system address. -pub fn sent_from_system_address(tx: &MegaTransaction, system_address: Address) -> bool { - tx.caller() == system_address -} - -/// Checks if a transaction is a mega system transaction using the given system address. -/// A mega system transaction is a legacy transaction that is submitted by the system address -/// and calls a whitelisted address in `MEGA_SYSTEM_TX_WHITELIST`. -pub fn is_mega_system_transaction_with(tx: &MegaTransaction, system_address: Address) -> bool { - check_if_mega_system_transaction(tx.caller(), tx.tx_type(), tx.kind(), system_address) -} - -/// Checks if a transaction is a mega system transaction. -/// -/// # Arguments -/// -/// * `tx_signer` - The signer of the transaction -/// * `tx_type` - The type of the transaction -/// * `tx_kind` - The kind of the transaction -/// * `system_address` - The current system address for this block -/// -/// # Returns -/// -/// Returns `true` if the transaction is a mega system transaction, `false` otherwise. -pub fn check_if_mega_system_transaction( - tx_signer: Address, - tx_type: u8, - tx_kind: TxKind, - system_address: Address, -) -> bool { - if tx_type == 0x0 && tx_signer == system_address { - // a mega system transaction must be a legacy transaction - match tx_kind { - TxKind::Create => false, - TxKind::Call(address) => MEGA_SYSTEM_TX_WHITELIST.contains(&address), - } - } else { - false - } -} - -/// Checks if a transaction should be processed as a deposit-like transaction. -/// -/// This includes both actual deposit transactions (`DEPOSIT_TRANSACTION_TYPE`) and normal -/// transactions from the `MegaETH` system address (mega system transactions). -/// -/// # Arguments -/// -/// * `tx` - The transaction to check -/// -/// # Returns -/// -/// Returns `true` if the transaction should be processed as deposit-like, `false` otherwise. -pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address) -> bool { - // Check if it's an actual deposit transaction - if tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { - return true; - } - - // Check if it's from the mega system address - is_mega_system_transaction_with(tx, system_address) -} - -/// Checks if a transaction is *system-originated*: produced by the protocol itself or by the -/// sequencer acting as the system address, as opposed to any user transaction. -/// -/// A transaction is system-originated when either: -/// - its caller is the EIP-2935 / EIP-4788 system address (`0xff..fe`), which is how mega-evm's own -/// pre-block system calls (block-hash, beacon-root, `SequencerRegistry`) are issued; or -/// - it is a mega system transaction: a legacy transaction from `system_address` calling a -/// whitelisted contract (see [`is_mega_system_transaction_with`]). -/// -/// Neither branch can be produced by a user: `0xff..fe` has no key and is only ever set as -/// caller by the protocol's own pre-block helpers, and matching `system_address` requires the -/// protocol's deposit-injection path. In particular this deliberately does **not** match an -/// arbitrary user deposit transaction (`DEPOSIT_TRANSACTION_TYPE`), unlike -/// [`is_deposit_like_transaction`]. -/// -/// REX6+ uses this to exempt system-originated execution from `MegaETH`'s per-transaction resource -/// metering (SALT-scaled storage gas, the four `AdditionalLimit` dimensions, and gas detention), -/// so protocol-mandated state changes can never fail due to metering — e.g. when SALT buckets -/// grow. The standard EVM `gas_limit` still bounds the work as a runaway guard. -/// -/// The exemption is evaluated in `MegaContext::on_new_tx`, which runs *after* `before_run` has -/// already deposit-promoted a mega system tx (stamping [`MEGA_SYSTEM_TRANSACTION_SOURCE_HASH`] and -/// flipping `tx_type()` to a deposit). The source-hash branch below therefore carries the match for -/// promoted txs; the `is_mega_system_transaction_with` branch covers the pre-promotion shape for -/// any other caller. Both the source hash and the system-address+whitelist gate are protocol-set, -/// so a user deposit (different source hash, non-system caller) is never matched — unlike -/// [`is_deposit_like_transaction`]. -pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bool { - // Internal pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) use `0xff..fe` and - // run via `run_system_call`, so they are never deposit-promoted. - tx.caller() == alloy_eips::eip4788::SYSTEM_ADDRESS || - // A mega system tx that `before_run` has already promoted to a deposit. - tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH || - // A mega system tx in its original (pre-promotion) legacy shape. - is_mega_system_transaction_with(tx, system_address) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::TxKind; - - const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; - const USER: Address = address!("0000000000000000000000000000000000009999"); - const NON_WHITELIST: Address = address!("00000000000000000000000000000000000000ab"); - - /// Builds a legacy (type 0x0) call transaction with the given caller and callee. - fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { - let mut tx = MegaTransaction::default(); - tx.base.tx_type = 0; - tx.base.caller = caller; - tx.base.kind = TxKind::Call(to); - tx - } - - #[test] - fn test_is_system_originated_matches_eip_system_address_caller() { - // The protocol's own pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) - // use `0xff..fe` as caller; it matches regardless of the resolved system address or target. - let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(is_system_originated(&tx, USER)); - } - - #[test] - fn test_is_system_originated_matches_mega_system_tx() { - // Sequencer mega system tx: legacy tx from the system address to a whitelisted contract. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { - // System address calling a non-whitelisted contract is not a mega system tx. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NON_WHITELIST); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_matches_promoted_mega_system_tx() { - // `before_run` promotes a mega system tx to a deposit (stamping the source hash and - // flipping `tx_type()`) *before* `on_new_tx` evaluates the exemption. The promoted shape - // must still be recognized as system-originated. - let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "promotion flips tx_type to deposit"); - assert!( - !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), - "the legacy-typed check no longer matches after promotion", - ); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "but the source-hash branch does"); - } - - #[test] - fn test_is_system_originated_rejects_user_tx() { - let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_user_deposit_tx() { - // Anti-bypass: a user deposit transaction (non-system caller) must NOT be treated as - // system-originated, even though `is_deposit_like_transaction` classifies any deposit as - // deposit-like. Otherwise a user could craft a deposit to escape SALT-scaled storage gas. - let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - // A non-zero deposit source hash makes `tx_type()` report `DEPOSIT_TRANSACTION_TYPE`. - tx.deposit.source_hash = B256::repeat_byte(0x11); - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } -} diff --git a/crates/mega-evm/src/test_utils/bytes.rs b/crates/mega-evm/src/test_utils/bytes.rs deleted file mode 100644 index 1432aca19..000000000 --- a/crates/mega-evm/src/test_utils/bytes.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -/// Pads the bytes to the right with 0s to make it a multiple of the length. -pub fn right_pad_bytes(bytes: impl AsRef<[u8]>, multiple_of: usize) -> Vec { - let bytes = bytes.as_ref().to_vec(); - let padding = (multiple_of - (bytes.len() % multiple_of)) % multiple_of; - [bytes, vec![0u8; padding]].concat() -} diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs deleted file mode 100644 index 4bfb1817b..000000000 --- a/crates/mega-evm/src/test_utils/database.rs +++ /dev/null @@ -1,195 +0,0 @@ -use core::convert::Infallible; - -use alloy_primitives::{Address, Bytes, B256, U256}; -use delegate::delegate; -use revm::{ - database::{AccountState, CacheDB, DBErrorMarker, EmptyDB}, - primitives::{HashMap, StorageKey, StorageValue}, - state::{Account, AccountInfo, Bytecode}, -}; - -/// A memory database for testing purposes. -#[derive(Debug, Default, Clone, derive_more::Deref, derive_more::DerefMut)] -pub struct MemoryDatabase { - #[deref] - #[deref_mut] - db: CacheDB, -} - -impl MemoryDatabase { - /// Creates a new `MemoryDatabase` from a `CacheDB`. - pub fn from_cache_db(db: CacheDB) -> Self { - Self { db } - } - - /// Sets the code for an account in the database. - pub fn set_account_code(&mut self, address: Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = self.db.load_account(address).unwrap(); - account_info.info.code = Some(bytecode); - account_info.info.code_hash = code_hash; - account_info.account_state = AccountState::None; - } - - /// Sets the code for an account in the database. - pub fn account_code(mut self, address: Address, code: Bytes) -> Self { - self.set_account_code(address, code); - self - } - - /// Installs an account whose code is *lazy*: `basic()` returns `code: None` with `code_hash` - /// set, so loading the code requires a `code_by_hash` call. Mirrors production reth's - /// `StateProviderDatabase::basic`, which defers code loading. Lets a code-load failure be - /// exercised independently of `basic()`. - pub fn account_lazy_code(mut self, address: Address, code_hash: B256) -> Self { - let account_info = self.db.load_account(address).unwrap(); - account_info.info.code = None; - account_info.info.code_hash = code_hash; - account_info.account_state = AccountState::None; - self - } - - /// Sets the balance for an account in the database. - pub fn set_account_balance(&mut self, address: Address, balance: U256) { - let account_info = self.db.load_account(address).unwrap(); - account_info.info.balance = balance; - account_info.account_state = AccountState::None; - } - - /// Sets the balance for an account in the database. - pub fn account_balance(mut self, address: Address, balance: U256) -> Self { - self.set_account_balance(address, balance); - self - } - - /// Sets the nonce for an account in the database. - pub fn set_account_nonce(&mut self, address: Address, nonce: u64) { - let account_info = self.db.load_account(address).unwrap(); - account_info.info.nonce = nonce; - account_info.account_state = AccountState::None; - } - - /// Sets the nonce for an account in the database. - pub fn account_nonce(mut self, address: Address, nonce: u64) -> Self { - self.set_account_nonce(address, nonce); - self - } - - /// Sets the storage for an account in the database. - pub fn set_account_storage( - &mut self, - address: Address, - storage_key: StorageKey, - value: StorageValue, - ) { - let account_info = self.db.load_account(address).unwrap(); - account_info.storage.insert(storage_key, value); - account_info.account_state = AccountState::None; - } - - /// Sets the storage for an account in the database. - pub fn account_storage( - mut self, - address: Address, - storage_key: StorageKey, - value: StorageValue, - ) -> Self { - self.set_account_storage(address, storage_key, value); - self - } -} - -impl revm::Database for MemoryDatabase { - type Error = Infallible; - - delegate! { - to self.db { - fn basic(&mut self, address: Address) -> Result, Self::Error>; - fn code_by_hash(&mut self, code_hash: B256) -> Result; - fn storage(&mut self, address: Address, index: StorageKey) -> Result; - fn block_hash(&mut self, number: u64) -> Result; - } - } -} - -impl revm::DatabaseCommit for MemoryDatabase { - delegate! { - to self.db { - fn commit(&mut self, changes: revm::primitives::HashMap); - } - } -} - -/// Error type for [`ErrorInjectingDatabase`]. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] -#[display("{_0}")] -pub struct InjectedDbError(#[error(not(source))] pub String); - -impl DBErrorMarker for InjectedDbError {} - -/// A database wrapper that injects errors on configurable account or storage lookups. -/// -/// Used to test DB error handling paths (e.g., `FatalExternalError` when `inspect_*` fails). -/// Wraps a [`MemoryDatabase`] and can be configured to fail on specific `basic()` or `storage()` -/// calls. -#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)] -pub struct ErrorInjectingDatabase { - #[deref] - #[deref_mut] - inner: MemoryDatabase, - /// When set, `basic()` calls for this address return an error. - pub fail_on_account: Option
, - /// When set, `storage()` calls for this (address, key) return an error. - pub fail_on_storage: Option<(Address, StorageKey)>, - /// When set, `code_by_hash()` calls for this hash return an error. Lets a code load fail - /// independently of `basic()` (mirrors a node missing a contract's code), to exercise the - /// `load_code = true` inspect paths in isolation. - pub fail_on_code_by_hash: Option, -} - -impl ErrorInjectingDatabase { - /// Creates a new `ErrorInjectingDatabase` wrapping the given [`MemoryDatabase`]. - pub fn new(inner: MemoryDatabase) -> Self { - Self { inner, fail_on_account: None, fail_on_storage: None, fail_on_code_by_hash: None } - } -} - -impl revm::Database for ErrorInjectingDatabase { - type Error = InjectedDbError; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - if self.fail_on_account == Some(address) { - return Err(InjectedDbError(format!("injected basic() error for {address}"))); - } - self.inner.basic(address).map_err(|e| match e {}) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - if self.fail_on_code_by_hash == Some(code_hash) { - return Err(InjectedDbError(format!("injected code_by_hash() error for {code_hash}"))); - } - self.inner.code_by_hash(code_hash).map_err(|e| match e {}) - } - - fn storage( - &mut self, - address: Address, - index: StorageKey, - ) -> Result { - if self.fail_on_storage == Some((address, index)) { - return Err(InjectedDbError(format!("injected storage() error for {address}:{index}"))); - } - self.inner.storage(address, index).map_err(|e| match e {}) - } - - fn block_hash(&mut self, number: u64) -> Result { - self.inner.block_hash(number).map_err(|e| match e {}) - } -} - -impl revm::DatabaseCommit for ErrorInjectingDatabase { - fn commit(&mut self, changes: HashMap) { - self.inner.commit(changes); - } -} diff --git a/crates/mega-evm/src/test_utils/evm.rs b/crates/mega-evm/src/test_utils/evm.rs deleted file mode 100644 index 58f0ef1e2..000000000 --- a/crates/mega-evm/src/test_utils/evm.rs +++ /dev/null @@ -1,45 +0,0 @@ -use alloy_primitives::{Address, Bytes, TxKind, U256}; -use core::fmt::Debug; -use revm::{ - context::{ - result::{EVMError, ResultAndState}, - TxEnv, - }, - Database, -}; - -use crate::{ - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, -}; - -/// Executes a transaction on the EVM. -pub fn transact( - spec: MegaSpecId, - db: DB, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, -) -> Result, EVMError> -where - DB: Database + Debug, - DB::Error: Send + Sync + Debug + 'static, -{ - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit: 1000000000000000000, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} diff --git a/crates/mega-evm/src/test_utils/inspectors.rs b/crates/mega-evm/src/test_utils/inspectors.rs deleted file mode 100644 index b1e40a1df..000000000 --- a/crates/mega-evm/src/test_utils/inspectors.rs +++ /dev/null @@ -1,343 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{rc::Rc, vec::Vec}; - -use core::cell::RefCell; -use revm::{ - bytecode::OpCode, - context::{ContextTr, JournalTr}, - interpreter::{ - interpreter_types::Jumps, CallInputs, CallOutcome, CreateInputs, Interpreter, - InterpreterTypes, - }, - Inspector, -}; - -/// A smart pointer wrapper around `Rc>` that provides shared mutable access. -/// -/// This type is used throughout the trace tree to allow multiple references to the same -/// node while maintaining interior mutability. It automatically derefs to the inner -/// `Rc>`. -#[derive(Debug, derive_more::Deref)] -pub struct Pointer(#[deref] Rc>); - -impl Clone for Pointer { - /// Clones the pointer (increments reference count), not the underlying data. - fn clone(&self) -> Self { - Self(self.0.clone()) - } -} - -impl From for Pointer { - /// Wraps a value in a new `Pointer`. - fn from(value: T) -> Self { - Self(Rc::new(RefCell::new(value))) - } -} - -impl Pointer { - /// Clones the underlying data (not just the pointer). - pub fn clone_inner(&self) -> T { - self.0.borrow().clone() - } -} - -/// A path to a specific node in the trace tree. -/// -/// Each element represents the child index at that level of the tree. -/// For example, `vec![0, 2, 1]` means: first child -> third child -> second child. -pub type NodeLocation = Vec; - -/// A location of an item within a node's sections. -/// -/// `(section_index, item_index)` where sections are interleaved with child calls. -pub type ItemLocation = (usize, usize); - -/// A complete location representing a specific item in the trace tree. -/// -/// Combines a node location (path through call tree) with an item location -/// (position within that node's items). -#[derive(Debug)] -pub struct TraceLocation { - /// Path to the node containing the item. - pub call: NodeLocation, - /// Position of the item within the node. - pub item: ItemLocation, -} - -/// A node in a hierarchical trace tree structure. -/// -/// This represents a call frame (either a message call or contract creation) and maintains -/// a tree structure where: -/// - Each node contains metadata about the call (via `META`) -/// - Items (via `ITEM`) are stored in sections that are interleaved with child calls -/// - The structure allows reconstructing the exact chronological order of events -/// -/// # Structure -/// -/// Items are organized into sections, where sections are separated by child calls: -/// ```text -/// [items before first child] -> [first child] -> [items after first child] -> [second child] -> ... -/// ``` -/// -/// This allows the tree to maintain both hierarchical structure and chronological ordering. -#[derive(Debug, Clone)] -#[allow(dead_code)] -pub struct TraceNode { - /// Metadata about this call (e.g., call inputs, creation inputs). - pub meta: META, - /// Reference to the parent node, if any. - pub parent: Option>, - /// Sections of items. There is always one more section than children. - /// Sections are interleaved with children to maintain chronological order. - pub sections: Vec>>, - /// Child nodes representing nested calls. - pub childrens: Vec>, -} - -impl TraceNode { - /// Creates a new trace node with the given metadata and optional parent. - /// - /// If a parent is provided, this node is automatically added as a child of the parent. - pub fn new(meta: META, parent: Option>) -> Pointer { - let this: Pointer = - Self { meta, parent: parent.clone(), sections: vec![Vec::new()], childrens: vec![] } - .into(); - if let Some(p) = parent { - p.borrow_mut().add_child(this.clone()); - } - this - } - - /// Returns the last item added to this node across all sections. - pub fn last_item(&self) -> Option> { - self.sections.iter().flatten().last().cloned() - } - - /// Adds an item to the current section (after the last child). - pub fn add_item(&mut self, item: ITEM) { - self.sections[self.childrens.len()].push(item.into()); - } - - /// Adds a child node and creates a new section for subsequent items. - fn add_child>>(&mut self, child: T) { - self.childrens.push(child.into()); - self.sections.push(Vec::new()); - } -} - -impl Pointer> { - /// Returns a flattened view of all items in the tree in chronological order. - pub fn flattened_items(&self) -> Vec> { - let mut items = Vec::new(); - for i in 0..self.borrow().childrens.len() { - items.extend(self.borrow().sections[i].iter().cloned()); - items.extend(self.borrow().childrens[i].flattened_items()); - } - items.extend(self.borrow().sections[self.borrow().childrens.len()].iter().cloned()); - items - } - - /// Retrieves a node at the specified location in the tree. - /// - /// Returns `None` if the location is invalid (out of bounds). - pub fn get_node(&self, location: NodeLocation) -> Option { - if location.is_empty() { - Some(self.clone()) - } else { - self.borrow().childrens[location[0]].get_node(location[1..].to_vec()) - } - } - - /// Retrieves an item at the specified location within this node. - /// - /// Returns `None` if the location is invalid (out of bounds). - pub fn get_item(&self, location: ItemLocation) -> Option> { - self.borrow().sections.get(location.0).and_then(|section| section.get(location.1)).cloned() - } - - /// Retrieves an item using a complete trace location (node path + item position). - /// - /// Returns `None` if either the node location or item location is invalid. - pub fn get_item_nested(&self, location: TraceLocation) -> Option> { - self.get_node(location.call).and_then(|n| n.get_item(location.item)) - } - - /// Iterates over all items in the tree in chronological order. - /// - /// For each item, calls the provided function with: - /// - The node location (path to the node containing the item) - /// - The node itself - /// - The item location within the node - /// - The item - pub fn iterate_with(&self, mut f: F) - where - F: FnMut(NodeLocation, Self, ItemLocation, Pointer), - { - self.iterate_with_inner(&mut f, vec![]); - } - - /// Internal helper for recursive iteration maintaining the current node location. - fn iterate_with_inner(&self, f: &mut F, node_location: NodeLocation) - where - F: FnMut(NodeLocation, Self, ItemLocation, Pointer), - { - let sections = &self.borrow().sections; - for (section_idx, section) in sections.iter().enumerate() { - for (item_idx, item) in section.iter().enumerate() { - f(node_location.clone(), self.clone(), (section_idx, item_idx), item.clone()); - } - if section_idx < sections.len() - 1 { - let mut child_node_location = node_location.clone(); - child_node_location.push(section_idx); - self.borrow().childrens[section_idx].iterate_with_inner(f, child_node_location); - } - } - } -} - -/// Represents gas information for a single opcode execution. -#[derive(Clone)] -pub struct OpcodeGasInfo { - /// The opcode executed. - pub opcode: OpCode, - /// Gas remaining before the opcode execution. - pub gas_before: u64, - /// Gas remaining after the opcode execution. - pub gas_after: u64, - /// Call depth when this opcode was executed. - pub depth: u64, -} - -impl core::fmt::Debug for OpcodeGasInfo { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!( - f, - "{}[depth={}] gas: {} -> {} (cost: {})", - self.opcode.as_str(), - self.depth, - self.gas_before, - self.gas_after, - self.gas_cost() - ) - } -} - -impl OpcodeGasInfo { - /// Calculates the gas cost of this opcode execution. - pub fn gas_cost(&self) -> u64 { - self.gas_before.saturating_sub(self.gas_after) - } -} - -/// Metadata for a trace node representing either a call or create operation. -#[derive(Debug, Clone)] -pub enum MsgCallMeta { - /// A message call (CALL, CALLCODE, DELEGATECALL, STATICCALL). - Call(CallInputs), - /// A contract creation (CREATE, CREATE2). - Create(CreateInputs), -} - -/// An inspector that collects a hierarchical view of gas left before and after each opcode. -#[derive(Debug, Default)] -pub struct GasInspector { - /// Stack of currently active call frames. - pub stack: Vec>>, - /// Root of the trace tree containing all opcode executions. - pub trace: Option>>, -} - -impl GasInspector { - /// Creates a new enabled `GasInspector`. - pub fn new() -> Self { - Self::default() - } - - /// Clears all recorded gas information. - pub fn clear(&mut self) { - self.trace = None; - self.stack = vec![]; - } - - /// Returns a flattened view of all opcode records in chronological order. - /// This traverses the call tree and collects all opcodes in execution order. - pub fn records(&self) -> Vec { - self.trace - .as_ref() - .map(|t| t.flattened_items().into_iter().map(|p| p.clone_inner()).collect()) - .unwrap_or_default() - } -} - -impl Inspector for GasInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - // Create a new trace node for this call - let parent = self.stack.last().cloned(); - let msg_call = TraceNode::new(MsgCallMeta::Call(inputs.clone()), parent); - self.stack.push(msg_call.clone()); - // Set as root trace if this is the first call - if self.trace.is_none() { - self.trace = Some(msg_call); - } - None - } - - fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { - // Pop the call from the stack when it completes - self.stack.pop(); - } - - fn create( - &mut self, - _context: &mut CTX, - inputs: &mut CreateInputs, - ) -> Option { - // Create a new trace node for this contract creation - let parent = self.stack.last().cloned(); - let msg_call = TraceNode::new(MsgCallMeta::Create(inputs.clone()), parent); - self.stack.push(msg_call.clone()); - // Set as root trace if this is the first operation - if self.trace.is_none() { - self.trace = Some(msg_call); - } - None - } - - fn create_end( - &mut self, - _context: &mut CTX, - _inputs: &CreateInputs, - _outcome: &mut revm::interpreter::CreateOutcome, - ) { - // Pop the create from the stack when it completes - self.stack.pop(); - } - - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - // Record gas state before opcode execution - let gas_before = interp.gas.remaining(); - let opcode = interp.bytecode.opcode(); - let depth = context.journal().depth(); - let step = OpcodeGasInfo { - opcode: OpCode::new(opcode).unwrap(), - gas_before, - gas_after: gas_before, // Will be updated in step_end - depth: depth as u64, - }; - if let Some(c) = self.stack.last_mut() { - c.borrow_mut().add_item(step) - } - } - - fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { - // Update the gas_after field with the actual gas remaining after execution - let current = self - .stack - .last() - .as_ref() - .and_then(|c| c.borrow_mut().last_item()) - .expect("current is not None"); - current.borrow_mut().gas_after = interp.gas.remaining(); - } -} diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs deleted file mode 100644 index 3e6f7c544..000000000 --- a/crates/mega-evm/src/test_utils/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Test utilities for the `MegaETH` EVM. - -mod bytes; -mod database; -mod evm; -mod inspectors; -mod opcode_gen; - -pub use bytes::*; -pub use database::*; -pub use evm::*; -pub use inspectors::*; -pub use opcode_gen::*; diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs deleted file mode 100644 index 788cecb32..000000000 --- a/crates/mega-evm/src/test_utils/opcode_gen.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! This module provides utility functions to generate EVM bytecode. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use alloy_primitives::{Address, Bytes, U256}; -use revm::bytecode::opcode::{ - DUP1, EQ, INVALID, JUMPDEST, JUMPI, MSTORE, PUSH0, RETURN, REVERT, SSTORE, STOP, -}; - -use crate::test_utils::right_pad_bytes; - -/// A builder for assembling EVM bytecode. -#[derive(Debug, Default)] -pub struct BytecodeBuilder { - code: Vec, -} - -impl BytecodeBuilder { - /// Build the bytecode. - pub fn build(self) -> Bytes { - self.code.into() - } - - /// Build the bytecode as a vector. - pub fn build_vec(self) -> Vec { - self.code - } - - /// Get the length of the bytecode. - pub fn len(&self) -> usize { - self.code.len() - } - - /// Check if the bytecode is empty. - pub fn is_empty(&self) -> bool { - self.code.is_empty() - } - - /// Append a single opcode or byte. - pub fn append(mut self, opcode: u8) -> Self { - self.code.push(opcode); - self - } - - /// Append a series of opcodes or bytes. - pub fn append_many(mut self, items: impl IntoIterator) -> Self { - self.code.extend(items); - self - } - - /// Append a PUSH opcode and the bytes to push. - pub fn push_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self { - let bytes: &[u8] = bytes.as_ref(); - assert!(bytes.len() <= 32); - self.code.push(PUSH0 + bytes.len() as u8); - self.code.extend(bytes.to_vec()); - self - } - - /// Append a PUSH opcode and the number to push. - pub fn push_number + Copy>(self, number: T) -> Self { - let num = number.into(); - let bytes = match core::mem::size_of::() { - 1 => (num as u8).to_be_bytes().to_vec(), - 2 => (num as u16).to_be_bytes().to_vec(), - 4 => (num as u32).to_be_bytes().to_vec(), - 8 => (num as u64).to_be_bytes().to_vec(), - 16 => num.to_be_bytes().to_vec(), - _ => panic!("Unsupported integer size"), - }; - self.push_bytes(bytes) - } - - /// Append a PUSH opcode and the address to push. - pub fn push_address(self, address: Address) -> Self { - self.push_bytes(address) - } - - /// Append a PUSH opcode and the u256 value to push. - pub fn push_u256(self, value: U256) -> Self { - self.push_bytes(value.to_be_bytes_vec()) - } - - /// Append a series of MSTORE opcodes to store the given bytes at the given offset. - pub fn mstore(self, offset: usize, bytes: impl AsRef<[u8]>) -> Self { - let bytes = bytes.as_ref().to_vec(); - let padded_bytes = right_pad_bytes(bytes, 32); - let mut this = self; - for (i, chunk) in padded_bytes.chunks(32).enumerate() { - this = this.push_bytes(chunk); - this = this.push_number((offset + i * 32) as u64); - this.code.push(MSTORE); - } - this - } - - /// Append a SSTORE opcode to store the given value at the given slot. - pub fn sstore(mut self, slot: U256, value: U256) -> Self { - self = self.push_u256(value); - self = self.push_u256(slot); - self.code.push(SSTORE); - self - } - - /// Append a REVERT opcode with empty return data. - pub fn revert(self) -> Self { - self.append_many([PUSH0, PUSH0, REVERT]) - } - - /// Append a REVERT opcode with the given return data. - pub fn revert_with_data(mut self, data: impl AsRef<[u8]>) -> Self { - let data_len = data.as_ref().len(); - self = self.mstore(0x0, data); - self = self.push_number(data_len as u64); - self = self.push_number(0x0_u64); - self = self.append(REVERT); - self - } - - /// Append a RETURN opcode with empty return data. - pub fn return_empty(self) -> Self { - self.append_many([PUSH0, PUSH0, RETURN]) - } - - /// Append a RETURN opcode with the given return data. - pub fn return_with_data(mut self, data: impl AsRef<[u8]>) -> Self { - let data_len = data.as_ref().len(); - self = self.mstore(0x0, data); - self = self.push_number(data_len as u64); - self = self.push_number(0x0_u64); - self = self.append(RETURN); - self - } - - /// Append an assmembly snippet that checks whether the value at the given stack position is - /// equal to the given value. - /// - /// If not, call INVALID opcode. - /// - /// This snippet will left the stack unchanged after execution. - pub fn assert_stack_value(mut self, stack_position: usize, value: U256) -> Self { - self = self - .append(DUP1 + stack_position as u8) // duplicate the value at the given stack position to check - .push_u256(value) - .append(EQ); - let code_len = self.len(); - self = - self.push_number(code_len as u64 + 1 + 8 + 2).append_many([JUMPI, INVALID, JUMPDEST]); - self - } - - /// Append a STOP opcode. - pub fn stop(mut self) -> Self { - self = self.append(STOP); - self - } -} - -#[cfg(test)] -mod tests { - use core::convert::Infallible; - - use alloy_primitives::address; - use revm::context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - }; - - use crate::{ - test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, - }; - - use super::*; - - fn execute_bytecode( - bytecode: Bytes, - ) -> Result, EVMError> { - let contract = address!("0000000000000000000000000000000000100001"); - let mut db = MemoryDatabase::default(); - db.set_account_code(contract, bytecode); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default().call(contract).gas_limit(1_000_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) - } - - #[test] - fn test_assert_stack_value_success() { - let mut builder = BytecodeBuilder::default().push_number(0x2333u64); - builder = builder.assert_stack_value(0, U256::from(0x2333u64)); - let bytecode = builder.build(); - let result = execute_bytecode(bytecode); - assert!(result.unwrap().result.is_success(), "Transaction should succeed"); - } - - #[test] - fn test_assert_stack_value_failure() { - let mut builder = BytecodeBuilder::default().push_number(0x2333u64); - builder = builder.assert_stack_value(0, U256::from(0x9999u64)); - let bytecode = builder.build(); - let result = execute_bytecode(bytecode); - assert!(result.unwrap().result.is_halt(), "Transaction should fail"); - } -} diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs deleted file mode 100644 index 2ef9e0ce2..000000000 --- a/crates/mega-evm/src/types.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Common type definitions for the `MegaETH` EVM. - -use revm::context::TxEnv; - -/// `MegaETH` transaction type used in revm. -pub type MegaTransaction = op_revm::OpTransaction; -/// `MegaETH` transaction builder type used in revm. -pub type MegaTransactionBuilder = op_revm::transaction::abstraction::OpTransactionBuilder; - -/// `MegaETH` transaction type. -pub type MegaTxType = op_alloy_consensus::OpTxType; -/// `MegaETH` transaction envelope type. -pub type MegaTxEnvelope = op_alloy_consensus::OpTxEnvelope; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 366fdd8d4..f7bc5cf8d 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -25,25 +25,26 @@ Do not add a `_pending/main.rs`. | Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | |---|---:|---:|---:|---:|---:|---:| +| T2.1 | 21 | 0 | 21 | 15 | 6 | 0 | | T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | -| T2.3 | 19 | 19 | 0 | 8 | 11 | 0 | -| T3.1 | 30 | 30 | 0 | 1 | 29 | 0 | -| T3.2 | 72 | 72 | 0 | 23 | 49 | 0 | -| T3.3 | 24 | 24 | 0 | 0 | 24 | 0 | +| T2.3 | 40 | 19 | 21 | 21 | 19 | 0 | +| T3.1 | 36 | 30 | 6 | 7 | 29 | 0 | +| T3.2 | 87 | 72 | 15 | 29 | 58 | 0 | +| T3.3 | 28 | 24 | 4 | 4 | 24 | 0 | | T3.4 | 27 | 27 | 0 | 0 | 27 | 0 | -| T4.1 | 47 | 47 | 0 | 40 | 7 | 0 | -| T4.2 | 82 | 82 | 0 | 75 | 7 | 0 | -| T4.3 | 57 | 57 | 0 | 0 | 36 | 21 | +| T4.1 | 49 | 47 | 2 | 42 | 7 | 0 | +| T4.2 | 87 | 82 | 5 | 79 | 8 | 0 | +| T4.3 | 58 | 57 | 1 | 0 | 36 | 22 | | T5.1 | 17 | 17 | 0 | 0 | 17 | 0 | -| T5.2 | 15 | 15 | 0 | 11 | 4 | 0 | -| T6.1 | 57 | 57 | 0 | 48 | 9 | 0 | -| T6.2 | 17 | 17 | 0 | 13 | 4 | 0 | +| T5.2 | 18 | 15 | 3 | 14 | 4 | 0 | +| T6.1 | 65 | 57 | 8 | 56 | 9 | 0 | +| T6.2 | 67 | 17 | 50 | 62 | 5 | 0 | | T6.3 | 77 | 77 | 0 | 67 | 10 | 0 | -| T7 | 73 | 73 | 0 | 28 | 45 | 0 | -| T8.1 | 45 | 45 | 0 | 35 | 10 | 0 | +| T7 | 89 | 73 | 16 | 43 | 46 | 0 | +| T8.1 | 74 | 45 | 29 | 55 | 19 | 0 | | T9 | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **691** | **691** | **0** | **371** | **292** | **28** | +| **Total** | **872** | **691** | **181** | **516** | **327** | **29** | ## Files @@ -132,3 +133,40 @@ Each cell lists `disposition count (ticket · decision)`. | `rex6/self_transfer_account_dedup.rs` | 5 | 重写 4 (T2.3 · D50/D56); 保留 1 (T4.1) | | `rex6/sequencer_registry_rotation.rs` | 6 | 保留 5 (T6.2); 保留 1 (T8.1 · params validation at load) | | `rex6/system_tx_metering_exemption.rs` | 3 | 重写 3 (T3.2 · D51 (m = 1 for system source; history exempt)) | +| `src/access/volatile.rs` | 4 | 保留 4 (T4.2) | +| `src/block/chain.rs` | 5 | 重写 4 (T8.1 · Satin activation timestamps; fallback pin = Satin); 保留 1 (T8.1) | +| `src/block/eips.rs` | 1 | 保留 1 (T8.1) | +| `src/block/hardfork.rs` | 12 | 重写 3 (T8.1 · single fork); 保留 9 (T8.1) | +| `src/block/helpers.rs` | 3 | 保留 3 (T8.1) | +| `src/block/limit.rs` | 5 | 保留 5 (T8.1) | +| `src/block/result.rs` | 2 | 重写 2 (T8.1 · D48 (error shape)) | +| `src/evm/context.rs` | 4 | 重写 2 (T2.1 · single spec); 保留 2 (T2.1 · T3.2 for the SALT cache test) | +| `src/evm/factory.rs` | 2 | 保留 1 (T2.1); 重写 1 (T2.1 · no behaviour projection) | +| `src/evm/host.rs` | 11 | 保留 10 (T2.3 · Host observation layer (D33) on the revm 40 journal); 保留 1 (T3.2) | +| `src/evm/mod.rs` | 11 | 保留 8 (T2.1); 保留 3 (T5.2) | +| `src/evm/precompiles.rs` | 6 | 保留 6 (T3.1 · D04) | +| `src/evm/result.rs` | 4 | 重写 4 (T2.3 · D17/D48 (halt-reason set changes)) | +| `src/evm/spec.rs` | 3 | 重写 3 (T2.1 · single rung; Karst/Osaka; legacy names must error) | +| `src/evm/state.rs` | 1 | 保留 1 (T8.1) | +| `src/external/gas.rs` | 9 | 重写 9 (T3.2 · D12/D51) | +| `src/external/hasher/mod.rs` | 5 | 保留 5 (T3.2) | +| `src/external/mod.rs` | 1 | 保留 1 (T2.1) | +| `src/external/test_utils.rs` | 1 | 保留 1 (T2.1) | +| `src/limit/compute_gas.rs` | 1 | 重写 1 (T4.2 · D40/D48) | +| `src/limit/data_size.rs` | 2 | 保留 2 (T4.1) | +| `src/limit/frame_limit.rs` | 4 | 重写 4 (T2.3 · data-size-only per-frame tracker) | +| `src/limit/kv_update.rs` | 1 | 待定 1 (T4.3 · D46) | +| `src/limit/limit.rs` | 4 | 保留 4 (T3.3 · D51) | +| `src/limit/mod.rs` | 3 | 保留 3 (T2.3) | +| `src/sandbox/error.rs` | 4 | 保留 4 (T7 · error types kept (T2.1 list)) | +| `src/sandbox/execution.rs` | 2 | 保留 1 (T7 · rule); 重写 1 (T7 · D16) | +| `src/sandbox/tx.rs` | 10 | 保留 10 (T7 · rules 1-9 helpers kept (T2.1 list)) | +| `src/system/control.rs` | 8 | 保留 8 (T6.2 · T6.1 for selector/revert-data tests) | +| `src/system/deploy.rs` | 4 | 保留 3 (T6.2); 重写 1 (T6.2 · single version) | +| `src/system/intercept.rs` | 2 | 保留 2 (T6.1) | +| `src/system/keyless_deploy.rs` | 2 | 保留 2 (T6.2) | +| `src/system/limit_control.rs` | 5 | 保留 5 (T6.2) | +| `src/system/oracle.rs` | 7 | 保留 7 (T6.2 · v2.0.0 only) | +| `src/system/sequencer_registry.rs` | 24 | 保留 24 (T6.2 · T5.2 for transact_apply_pending_changes) | +| `src/system/tx.rs` | 6 | 保留 6 (T6.1 · D51) | +| `src/test_utils/opcode_gen.rs` | 2 | 保留 2 (T2.1) | diff --git a/crates/mega-evm/tests/_pending/src/access/volatile.rs b/crates/mega-evm/tests/_pending/src/access/volatile.rs new file mode 100644 index 000000000..86e019238 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/access/volatile.rs @@ -0,0 +1,85 @@ +//! Unit tests extracted from `crates/mega-evm/src/access/volatile.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/access/volatile.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::VolatileDataAccessType; + + #[test] + fn test_empty_access_has_no_flags() { + let access = VolatileDataAccess::empty(); + + assert!(!access.has_block_env_access()); + assert!(!access.has_beneficiary_balance_access()); + assert!(!access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 0); + assert_eq!(access.count_accessed(), 0); + assert_eq!(access.block_env_only(), VolatileDataAccess::empty()); + assert_eq!(access.raw(), 0); + } + + #[test] + fn test_block_env_helpers_ignore_non_block_flags() { + let access = VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::BLOB_HASH | + VolatileDataAccess::BENEFICIARY_BALANCE | + VolatileDataAccess::ORACLE; + + assert!(access.has_block_env_access()); + assert!(access.has_beneficiary_balance_access()); + assert!(access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 2); + assert_eq!(access.count_accessed(), 2); + assert_eq!( + access.block_env_only(), + VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH + ); + assert_eq!(access.raw(), access.bits()); + } + + #[test] + fn test_from_volatile_data_access_type_covers_all_variants() { + let expected: &[(VolatileDataAccessType, VolatileDataAccess)] = &[ + (VolatileDataAccessType::BlockNumber, VolatileDataAccess::BLOCK_NUMBER), + (VolatileDataAccessType::Timestamp, VolatileDataAccess::TIMESTAMP), + (VolatileDataAccessType::Coinbase, VolatileDataAccess::COINBASE), + (VolatileDataAccessType::Difficulty, VolatileDataAccess::DIFFICULTY), + (VolatileDataAccessType::GasLimit, VolatileDataAccess::GAS_LIMIT), + (VolatileDataAccessType::BaseFee, VolatileDataAccess::BASE_FEE), + (VolatileDataAccessType::PrevRandao, VolatileDataAccess::PREV_RANDAO), + (VolatileDataAccessType::BlockHash, VolatileDataAccess::BLOCK_HASH), + (VolatileDataAccessType::BlobBaseFee, VolatileDataAccess::BLOB_BASE_FEE), + (VolatileDataAccessType::BlobHash, VolatileDataAccess::BLOB_HASH), + (VolatileDataAccessType::Beneficiary, VolatileDataAccess::BENEFICIARY_BALANCE), + (VolatileDataAccessType::Oracle, VolatileDataAccess::ORACLE), + ]; + + for &(access_type, expected_flag) in expected { + let converted = VolatileDataAccess::from(access_type); + assert_eq!(converted, expected_flag); + assert_eq!(converted.as_u8(), expected_flag.as_u8()); + } + } + + #[test] + fn test_all_block_env_flags_counted_correctly() { + let all_block_env = VolatileDataAccess::BLOCK_NUMBER | + VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::COINBASE | + VolatileDataAccess::DIFFICULTY | + VolatileDataAccess::GAS_LIMIT | + VolatileDataAccess::BASE_FEE | + VolatileDataAccess::PREV_RANDAO | + VolatileDataAccess::BLOCK_HASH | + VolatileDataAccess::BLOB_BASE_FEE | + VolatileDataAccess::BLOB_HASH; + + assert_eq!(all_block_env.count_block_env_accessed(), 10); + assert!(all_block_env.has_block_env_access()); + assert!(!all_block_env.has_beneficiary_balance_access()); + assert!(!all_block_env.has_oracle_access()); + assert_eq!(all_block_env.block_env_only(), all_block_env); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/chain.rs b/crates/mega-evm/tests/_pending/src/block/chain.rs new file mode 100644 index 000000000..43a9b5cc1 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/chain.rs @@ -0,0 +1,100 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/chain.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/chain.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MegaHardfork, MegaHardforks, MegaSpecId}; + + #[test] + fn test_mainnet_schedule_resolves_specs_by_timestamp() { + let hf = mainnet_hardforks(); + assert_eq!(hf.spec_id(1764851940), MegaSpecId::REX); + assert_eq!(hf.spec_id(1776659200), MegaSpecId::REX4); + // Just before Rex5, still Rex4; at/after Rex5, Rex5. + assert_eq!(hf.spec_id(1780631999), MegaSpecId::REX4); + assert_eq!(hf.spec_id(1780632000), MegaSpecId::REX5); + // Just before Rex6, still Rex5; at/after Rex6, Rex6. + assert_eq!(hf.spec_id(1787626799), MegaSpecId::REX5); + assert_eq!(hf.spec_id(1787626800), MegaSpecId::REX6); + // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. + assert!(hf.fork_params::().is_some()); + assert!(hf.fork_params::().is_some()); + } + + #[test] + fn test_testnet_schedule_resolves_specs_by_timestamp() { + let hf = testnet_hardforks(); + assert_eq!(hf.spec_id(1776400000), MegaSpecId::REX4); + // Just before Rex5, still Rex4; at/after Rex5, Rex5. + assert_eq!(hf.spec_id(1780459199), MegaSpecId::REX4); + assert_eq!(hf.spec_id(1780459200), MegaSpecId::REX5); + // Just before Rex6, still Rex5; at/after Rex6, Rex6. + assert_eq!(hf.spec_id(1786330799), MegaSpecId::REX5); + assert_eq!(hf.spec_id(1786330800), MegaSpecId::REX6); + // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. + assert!(hf.fork_params::().is_some()); + assert!(hf.fork_params::().is_some()); + } + + #[test] + fn test_schedule_dispatch_by_chain_id() { + assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1780632000), MegaSpecId::REX5); + assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1780459200), MegaSpecId::REX5); + assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1787626800), MegaSpecId::REX6); + assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1786330800), MegaSpecId::REX6); + // Unknown chain: every fork up to the pinned rung, active at genesis. + assert_eq!(hardfork_schedule(1).spec_id(0), MegaSpecId::REX7); + } + + #[test] + fn test_unknown_chain_fallback_carries_sequencer_registry_config() { + // Rex5 block execution fails pre-block without a SequencerRegistryConfig, + // so the all-activated fallback must attach placeholder roles. + let hf = hardfork_schedule(999_999); + assert_eq!(hf.spec_id(0), MegaSpecId::REX7); + let params = hf + .fork_params::() + .expect("fallback schedule must carry a SequencerRegistryConfig"); + assert_eq!(params.rex5_initial_sequencer, MEGA_SYSTEM_ADDRESS); + assert_eq!(params.rex5_initial_admin, MEGA_SYSTEM_ADDRESS); + // Rex6 is also active at genesis in the fallback, and the v2.0.0 registry + // deploy fails pre-block without a SequencerRegistryRex6Config — without + // this, every unknown-chain block aborts before the registry can deploy. + let rex6_params = hf + .fork_params::() + .expect("fallback schedule must carry a SequencerRegistryRex6Config"); + assert!(rex6_params.rex6_min_rotation_delay > 0); + } + + /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. + /// + /// Unknown chains run their rung from genesis, so it is their semantics from block zero with + /// no fork boundary. Introducing a spec must therefore leave them alone: registering a fork + /// above the pinned rung would rewrite what history they have already produced means, and + /// `mega-evme replay` resolves an unknown chain ID through this same schedule. + /// + /// A newly introduced spec leaves this test green — the pin holding still is the safe + /// direction, so nothing fails to force a decision. What the test pins is drift: the + /// fallback silently following `MegaSpecId::default` again (it fails here once the default + /// advances past the rung), and the rung advancing without this `RUNG` constant being edited + /// in the same change. + #[test] + fn test_unknown_chain_fallback_pins_its_rung() { + let hf = all_activated_hardforks(); + const RUNG: MegaSpecId = MegaSpecId::REX7; + + assert_eq!(hf.spec_id(0), RUNG, "the rung applies from genesis"); + assert_eq!(hf.spec_id(u64::MAX), RUNG, "and is terminal — no later fork is registered"); + + for fork in MegaHardfork::VARIANTS { + let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; + assert_eq!( + registered, + RUNG.is_enabled(fork.spec_id()), + "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" + ); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/eips.rs b/crates/mega-evm/tests/_pending/src/block/eips.rs new file mode 100644 index 000000000..f9b491a21 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/eips.rs @@ -0,0 +1,92 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/eips.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/eips.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::address; + use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; + + #[test] + fn test_balance_increment_commit_equivalence() { + // This is the most important test: verify that our approach is equivalent + // to the original increment_balances + balance_increment_state approach + + // Setup: create two identical database states + let addr1 = address!("0x1000000000000000000000000000000000000001"); + let addr2 = address!("0x2000000000000000000000000000000000000002"); + let addr3 = address!("0x3000000000000000000000000000000000000003"); + + // Fund only addr1 and addr2, but leave addr3 empty (non-existent) + let setup_db = |db: &mut InMemoryDB| { + for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { + db.insert_account_info( + addr, + AccountInfo { + balance: U256::from(balance), + nonce, + code_hash: alloy_primitives::B256::ZERO, + code: None, + }, + ); + } + }; + + // Setup database 1: will use original approach (increment_balances) + let mut db1 = InMemoryDB::default(); + setup_db(&mut db1); + let mut state1 = State::builder().with_database(&mut db1).build(); + + // Setup database 2: will use our approach (transact_balance_increments + commit) + let mut db2 = InMemoryDB::default(); + setup_db(&mut db2); + let mut state2 = State::builder().with_database(&mut db2).build(); + + // Apply balance increments + let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; + + // Method 1: Original approach + state1 + .increment_balances(balance_increments.clone()) + .expect("increment_balances should succeed"); + + // Method 2: Refactored approach (transact + commit, matching the actual usage pattern) + // The refactoring separates increment_balances into two steps: + // 1. transact_balance_increments() - produces EvmState delta + // 2. commit() - integrates the delta and fixes status transitions + // This allows extracting the intermediate state for system_caller.on_state() hooks + let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) + .expect("transact_balance_increments should succeed") + .expect("Should return state"); + + // Commit the state changes (this applies proper status transitions via apply_evm_state) + state2.commit(result_state); + + // Verify final states match after both approaches + for (addr, _expected_increment) in balance_increments { + let account1 = state1.load_cache_account(addr).expect("Should load from state1"); + let account2 = state2.load_cache_account(addr).expect("Should load from state2"); + + let info1 = account1.account_info().expect("Should have account info"); + let info2 = account2.account_info().expect("Should have account info"); + + assert_eq!( + info1.balance, info2.balance, + "Balance for {:?} should be identical after both methods", + addr + ); + assert_eq!(info1.nonce, info2.nonce, "Nonce for {:?} should be identical", addr); + assert_eq!( + info1.code_hash, info2.code_hash, + "Code hash for {:?} should be identical", + addr + ); + assert_eq!( + account1.status, account2.status, + "Account status for {:?} should be identical after both methods", + addr + ); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/hardfork.rs b/crates/mega-evm/tests/_pending/src/block/hardfork.rs new file mode 100644 index 000000000..36daeb6a6 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/hardfork.rs @@ -0,0 +1,233 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/hardfork.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/hardfork.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::SequencerRegistryConfig; + + #[test] + fn test_mega_hardfork_spec_ids_match_expected_specs() { + // Note: MiniRex1 and MiniRex2 map to alias rungs whose behavior reverts to earlier specs. + let cases = [ + (MegaHardfork::MiniRex, MegaSpecId::MINI_REX), + (MegaHardfork::MiniRex1, MegaSpecId::MINI_REX_1), + (MegaHardfork::MiniRex2, MegaSpecId::MINI_REX_2), + (MegaHardfork::Rex, MegaSpecId::REX), + (MegaHardfork::Rex1, MegaSpecId::REX1), + (MegaHardfork::Rex2, MegaSpecId::REX2), + (MegaHardfork::Rex3, MegaSpecId::REX3), + (MegaHardfork::Rex4, MegaSpecId::REX4), + (MegaHardfork::Rex5, MegaSpecId::REX5), + (MegaHardfork::Rex6, MegaSpecId::REX6), + (MegaHardfork::Rex7, MegaSpecId::REX7), + ]; + + for (hardfork, expected_spec) in cases { + assert_eq!(hardfork.spec_id(), expected_spec); + } + } + + #[test] + fn test_default_config_contains_upstream_forks_and_no_mega_forks() { + let config = MegaHardforkConfig::default(); + + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Frontier), + ForkCondition::Block(0) + ); + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Prague), + ForkCondition::Timestamp(0) + ); + assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); + assert_eq!(config.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_config_builder_helpers_override_and_remove_hardforks() { + let mut config = MegaHardforkConfig::new() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(10)) + .with(MegaHardfork::Rex4, ForkCondition::Timestamp(80)); + + assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(10))); + assert_eq!(config.get(MegaHardfork::Rex4), Some(&ForkCondition::Timestamp(80))); + + config.insert(MegaHardfork::MiniRex, ForkCondition::Timestamp(20)); + assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(20))); + + let config = config.without(MegaHardfork::MiniRex); + assert_eq!(config.get(MegaHardfork::MiniRex), None); + + let from_iter = MegaHardforkConfig::from( + [ + (MegaHardfork::MiniRex, ForkCondition::Timestamp(1)), + (MegaHardfork::Rex2, ForkCondition::Timestamp(2)), + ] + .into_iter(), + ); + assert_eq!(from_iter.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(1))); + assert_eq!(from_iter.get(MegaHardfork::Rex2), Some(&ForkCondition::Timestamp(2))); + } + + #[test] + fn test_with_all_activated_enables_all_mega_hardforks() { + let config = MegaHardforkConfig::default().with_all_activated(); + + // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list + // that declares the enum. A second hand-written list here would assert only that the + // forks someone remembered to name are activated — a new fork missing from both the + // builder and the list would fail neither. + for hardfork in MegaHardfork::VARIANTS { + assert_eq!( + config.mega_fork_activation(*hardfork), + ForkCondition::Timestamp(0), + "{hardfork:?}" + ); + } + } + + #[test] + fn test_fork_params_typed_access() { + let params = SequencerRegistryConfig { + rex5_initial_sequencer: alloy_primitives::address!( + "0x2222222222222222222222222222222222222222" + ), + rex5_initial_admin: alloy_primitives::address!( + "0x3333333333333333333333333333333333333333" + ), + }; + + let config = MegaHardforkConfig::default() + .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) + .with_params(params.clone()); + + let retrieved = config + .fork_params::() + .expect("should have SequencerRegistryConfig"); + assert_eq!(retrieved, ¶ms); + } + + #[test] + fn test_fork_params_none_when_not_configured() { + let config = + MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); + + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_default_validate_accepts_any_value() { + #[derive(Debug)] + struct NullParams; + + impl HardforkParams for NullParams { + const FORK: MegaHardfork = MegaHardfork::Rex4; + } + + assert!(NullParams.validate().is_ok()); + } + + #[test] + fn test_hardfork_params_error_display() { + let e = HardforkParamsError { message: "something went wrong".into() }; + assert_eq!(e.to_string(), "something went wrong"); + } + + #[test] + #[should_panic(expected = "Invalid params for fork")] + fn test_with_params_panics_on_validation_error() { + #[derive(Debug)] + struct AlwaysErrParams; + + impl HardforkParams for AlwaysErrParams { + const FORK: MegaHardfork = MegaHardfork::Rex4; + + fn validate(&self) -> Result<(), HardforkParamsError> { + Err(HardforkParamsError { message: "intentional test error".into() }) + } + } + + MegaHardforkConfig::default().with_all_activated().with_params(AlwaysErrParams); + } + + /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered + /// by block number never contributes its own spec to it. `spec_id`/`hardfork` share this + /// limitation; every canonical schedule uses `Timestamp` or `Never`, and + /// `validate_schedule` rejects anything else. + #[test] + fn test_resolution_ignores_block_numbered_forks() { + let hf = MegaHardforkConfig::new() + .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) + .with(MegaHardfork::Rex, ForkCondition::Timestamp(0)); + + assert!( + !hf.mega_fork_activation(MegaHardfork::MiniRex).active_at_timestamp(0), + "block-numbered forks are not timestamped" + ); + // The resolved spec comes from Rex alone; it still covers MINI_REX by ordinal + // inclusion, so the projected predicate reports active even though the MiniRex event + // itself never fires. + assert_eq!(hf.spec_id(0), MegaSpecId::REX); + assert!(hf.spec_id(0).is_enabled(MegaSpecId::MINI_REX)); + assert!(hf.is_mini_rex_active_at_timestamp(0)); + assert_eq!( + hf.validate_schedule(), + Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::MiniRex }) + ); + } + + /// A scheduled fork whose required params are missing fails at validation time instead of at + /// the first block of the fork. + #[test] + fn test_validate_schedule_requires_scheduled_fork_params() { + let rex5_no_params = + MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5); + assert_eq!( + rex5_no_params.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Rex5, + params: "SequencerRegistryConfig" + }) + ); + + let rex6_no_params = MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(SequencerRegistryConfig { + rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, + rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, + }); + assert_eq!( + rex6_no_params.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Rex6, + params: "SequencerRegistryRex6Config" + }) + ); + } + + #[test] + fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { + let config = MegaHardforkConfig::default() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) + .with(MegaHardfork::Rex4, ForkCondition::Timestamp(200)) + .with(MegaHardfork::Rex5, ForkCondition::Timestamp(300)) + .with(MegaHardfork::Rex6, ForkCondition::Timestamp(400)) + .with(MegaHardfork::Rex7, ForkCondition::Timestamp(500)); + + assert_eq!(config.hardfork(99), None); + assert_eq!(config.hardfork(100), Some(MegaHardfork::MiniRex)); + assert_eq!(config.hardfork(200), Some(MegaHardfork::Rex4)); + assert_eq!(config.hardfork(300), Some(MegaHardfork::Rex5)); + assert_eq!(config.hardfork(400), Some(MegaHardfork::Rex6)); + assert_eq!(config.hardfork(500), Some(MegaHardfork::Rex7)); + assert_eq!(config.spec_id(99), MegaSpecId::EQUIVALENCE); + assert_eq!(config.spec_id(100), MegaSpecId::MINI_REX); + assert_eq!(config.spec_id(200), MegaSpecId::REX4); + assert_eq!(config.spec_id(300), MegaSpecId::REX5); + assert_eq!(config.spec_id(400), MegaSpecId::REX6); + assert_eq!(config.spec_id(500), MegaSpecId::REX7); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/helpers.rs b/crates/mega-evm/tests/_pending/src/block/helpers.rs new file mode 100644 index 000000000..b04f83479 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/helpers.rs @@ -0,0 +1,205 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/helpers.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/helpers.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; + use alloy_primitives::{address, bytes::BufMut, Signature}; + use revm::context::TxEnv; + + const CALLER: Address = address!("2000000000000000000000000000000000000001"); + const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); + + #[derive(Debug, Clone)] + struct MockTx { + nonce: u64, + gas_limit: u64, + value: U256, + input: Bytes, + } + + impl Typed2718 for MockTx { + fn ty(&self) -> u8 { + 0 + } + } + + impl Encodable2718 for MockTx { + fn encode_2718_len(&self) -> usize { + self.input.len() + } + + fn encode_2718(&self, out: &mut dyn BufMut) { + out.put_slice(&self.input); + } + } + + impl Transaction for MockTx { + fn chain_id(&self) -> Option { + Some(1) + } + + fn nonce(&self) -> u64 { + self.nonce + } + + fn gas_limit(&self) -> u64 { + self.gas_limit + } + + fn gas_price(&self) -> Option { + Some(9) + } + + fn max_fee_per_gas(&self) -> u128 { + 9 + } + + fn max_priority_fee_per_gas(&self) -> Option { + None + } + + fn max_fee_per_blob_gas(&self) -> Option { + None + } + + fn priority_fee_or_price(&self) -> u128 { + 9 + } + + fn effective_gas_price(&self, _base_fee: Option) -> u128 { + 9 + } + + fn is_dynamic_fee(&self) -> bool { + false + } + + fn kind(&self) -> TxKind { + TxKind::Call(CONTRACT) + } + + fn is_create(&self) -> bool { + false + } + + fn value(&self) -> U256 { + self.value + } + + fn input(&self) -> &Bytes { + &self.input + } + + fn access_list(&self) -> Option<&AccessList> { + None + } + + fn blob_versioned_hashes(&self) -> Option<&[B256]> { + None + } + + fn authorization_list(&self) -> Option<&[SignedAuthorization]> { + None + } + } + + #[derive(Debug, Clone)] + struct MockRecoveredTx { + tx: TxEnv, + signer: Address, + } + + impl RecoveredTx for MockRecoveredTx { + fn tx(&self) -> &TxEnv { + &self.tx + } + + fn signer(&self) -> &Address { + &self.signer + } + } + + impl IntoTxEnv for MockRecoveredTx { + fn into_tx_env(self) -> TxEnv { + self.tx + } + } + + fn legacy_tx() -> TxLegacy { + TxLegacy { + chain_id: Some(1), + nonce: 7, + gas_price: 9, + gas_limit: 21_000, + to: TxKind::Call(CONTRACT), + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + } + } + + fn legacy_envelope() -> MegaTxEnvelope { + MegaTxEnvelope::Legacy(Signed::new_unchecked( + legacy_tx(), + Signature::test_signature(), + Default::default(), + )) + } + + #[test] + fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { + let tx = legacy_envelope(); + let recovered = Recovered::new_unchecked(tx.clone(), CALLER); + + assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); + assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); + assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); + assert!(MegaTransactionExt::tx_size(&tx) > 0); + } + + #[test] + fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { + let tx = MockTx { + nonce: 7, + gas_limit: 21_000, + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + }; + let expected_hash = tx.trie_hash(); + let expected_da_size = + op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()); + let expected_tx_size = tx.encode_2718_len() as u64; + + let enriched = EnrichedMegaTx::new_slow(tx); + + assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); + assert_eq!(enriched.da_size, expected_da_size); + assert_eq!(enriched.tx_size, expected_tx_size); + assert_eq!(enriched.nonce(), 7); + assert_eq!(enriched.gas_limit(), 21_000); + assert_eq!(enriched.value(), U256::from(11)); + assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); + } + + #[test] + fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { + let tx_env = TxEnv { + caller: CALLER, + gas_limit: 21_000, + kind: TxKind::Call(CONTRACT), + value: U256::from(11), + data: Bytes::from_static(&[0xaa, 0xbb]), + ..Default::default() + }; + let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; + let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); + + assert_eq!(enriched.tx(), &tx_env); + assert_eq!(*enriched.signer(), CALLER); + + let converted: TxEnv = enriched.into_tx_env(); + assert_eq!(converted, tx_env); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/limit.rs b/crates/mega-evm/tests/_pending/src/block/limit.rs new file mode 100644 index 000000000..21355e416 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/limit.rs @@ -0,0 +1,97 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/limit.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/limit.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::B256; + + fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_gas_limit = block_gas_limit; + limits.tx_gas_limit = u64::MAX; + limits + } + + fn limits_with_block_tx_size(block_txs_encode_size_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_txs_encode_size_limit = block_txs_encode_size_limit; + limits + } + + fn limits_with_block_da_size(block_da_size_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_da_size_limit = block_da_size_limit; + limits + } + + #[test] + fn test_pre_execution_check_block_gas_addition_saturates() { + // Block has very high accumulated usage and a transaction with a near-`u64::MAX` + // gas limit; unchecked addition would wrap and accidentally pass the limit check. + let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); + limiter.block_gas_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); + assert!(result.is_err(), "saturating_add must keep the rejection in place"); + } + + #[test] + fn test_pre_execution_check_block_tx_size_addition_saturates() { + let mut limiter = BlockLimiter::new(limits_with_block_tx_size(1_000_000)); + limiter.block_tx_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); + assert!(result.is_err()); + } + + #[test] + fn test_pre_execution_check_block_da_size_addition_saturates() { + let mut limiter = BlockLimiter::new(limits_with_block_da_size(1_000_000)); + limiter.block_da_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); + assert!(result.is_err()); + } + + #[test] + fn test_post_execution_update_raw_saturates_all_counters() { + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_gas_used = u64::MAX - 1; + limiter.block_tx_size_used = u64::MAX - 1; + limiter.block_da_size_used = u64::MAX - 1; + limiter.block_data_used = u64::MAX - 1; + limiter.block_kv_updates_used = u64::MAX - 1; + limiter.block_compute_gas_used = u64::MAX - 1; + limiter.block_state_growth_used = u64::MAX - 1; + + limiter.post_execution_update_raw( + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + false, + ); + + assert_eq!(limiter.block_gas_used, u64::MAX); + assert_eq!(limiter.block_tx_size_used, u64::MAX); + assert_eq!(limiter.block_da_size_used, u64::MAX); + assert_eq!(limiter.block_data_used, u64::MAX); + assert_eq!(limiter.block_kv_updates_used, u64::MAX); + assert_eq!(limiter.block_compute_gas_used, u64::MAX); + assert_eq!(limiter.block_state_growth_used, u64::MAX); + } + + #[test] + fn test_post_execution_update_raw_skips_da_for_deposits() { + // Deposit transactions should not advance `block_da_size_used`, even when the value + // would otherwise saturate. + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_da_size_used = 100; + + limiter.post_execution_update_raw(0, 0, u64::MAX, 0, 0, 0, 0, true); + + assert_eq!(limiter.block_da_size_used, 100); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/result.rs b/crates/mega-evm/tests/_pending/src/block/result.rs new file mode 100644 index 000000000..f6c8256ad --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/result.rs @@ -0,0 +1,65 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/result.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/result.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_transaction_limit_error_reports_usage_and_limit() { + let cases = [ + (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), + ( + MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, + 101, + 100, + ), + ( + MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, + 11, + 10, + ), + ]; + + for (error, expected_usage, expected_limit) in cases { + assert_eq!(error.usage(), expected_usage); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + } + } + + #[test] + fn test_block_limit_error_reports_block_usage_and_limit() { + let cases = [ + (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 2, limit: 11 }, 2, 11), + (MegaBlockLimitExceededError::ComputeGasLimit { block_used: 3, limit: 12 }, 3, 12), + ( + MegaBlockLimitExceededError::TransactionEncodeSizeLimit { + block_used: 4, + tx_used: 1, + limit: 13, + }, + 4, + 13, + ), + ( + MegaBlockLimitExceededError::DataAvailabilitySizeLimit { + block_used: 5, + tx_used: 1, + limit: 14, + }, + 5, + 14, + ), + (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 6, limit: 15 }, 6, 15), + ]; + + for (error, expected_block_used, expected_limit) in cases { + assert_eq!(error.block_used(), expected_block_used); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/context.rs b/crates/mega-evm/tests/_pending/src/evm/context.rs new file mode 100644 index 000000000..3da3c179a --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/context.rs @@ -0,0 +1,111 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/context.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/context.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + use alloy_primitives::address; + use revm::{context::CfgEnv, database::EmptyDB}; + + use crate::TestExternalEnvs; + + #[test] + fn test_with_cfg_updates_spec() { + // Create context with initial spec + let mut context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); + + // Verify initial state + assert_eq!(context.mega_spec(), MegaSpecId::EQUIVALENCE); + assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::EQUIVALENCE)); + + // Create new config with different spec + let new_cfg = CfgEnv::new_with_spec(MegaSpecId::MINI_REX); + + // Apply new config using with_cfg + context = context.with_cfg(new_cfg); + + // Verify that both the context's spec and inner config's spec are updated + assert_eq!(context.mega_spec(), MegaSpecId::MINI_REX); + assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::MINI_REX)); + } + + #[test] + fn test_with_cfg_spec_consistency() { + let context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); + + // Test multiple spec transitions + let specs_to_test = [MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]; + + let mut current_context = context; + for spec in specs_to_test { + let cfg = CfgEnv::new_with_spec(spec); + current_context = current_context.with_cfg(cfg); + + // Verify consistency between context spec and inner config spec + assert_eq!(current_context.mega_spec(), spec); + assert_eq!(current_context.inner.cfg.spec, OpSpecId::from(spec)); + } + } + + /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. + #[test] + fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { + let external_envs = TestExternalEnvs::new(); + let parent = MegaContext::new(EmptyDB::default(), MegaSpecId::REX4) + .with_external_envs(external_envs.into()); + let parent_address = address!("0000000000000000000000000000000000100001"); + let sandbox_address = address!("0000000000000000000000000000000000100002"); + + parent + .dynamic_storage_gas_cost + .borrow_mut() + .new_account_gas(parent_address) + .expect("parent bucket lookup should succeed"); + let parent_bucket_ids = parent.accessed_bucket_ids(); + + let sandbox = + MegaContext::<_, TestExternalEnvs>::new_with_shared_ext_envs( + EmptyDB::default(), + MegaSpecId::REX4, + Rc::clone(&parent.salt_env), + Rc::clone(&parent.oracle_env), + ) + .with_block(parent.block().clone()) + .with_chain(parent.chain().clone()) + .with_inside_sandbox(true); + sandbox + .dynamic_storage_gas_cost + .borrow_mut() + .new_account_gas(sandbox_address) + .expect("sandbox bucket lookup should succeed"); + + assert_eq!(parent.accessed_bucket_ids(), parent_bucket_ids); + assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); + } + + /// The test/bench-only `new_with_ext_envs` wrapper builds a `MegaContext` + /// over a caller-supplied external environment (`TestExternalEnvs`), at the + /// requested spec and wired to the given SALT/oracle handles. + #[test] + fn test_new_with_ext_envs_builds_over_configurable_env() { + let env = TestExternalEnvs::::new(); + let context = + MegaContext::<_, TestExternalEnvs>::new_with_ext_envs( + EmptyDB::default(), + MegaSpecId::REX5, + Rc::new(env.clone()), + Rc::new(RefCell::new(env)), + ); + + assert_eq!(context.mega_spec(), MegaSpecId::REX5); + // The supplied SALT env is wired through: a bucket lookup against the + // dynamic-gas cache succeeds. + context + .dynamic_storage_gas_cost + .borrow_mut() + .new_account_gas(address!("0000000000000000000000000000000000100003")) + .expect("bucket lookup against the supplied env should succeed"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/factory.rs b/crates/mega-evm/tests/_pending/src/evm/factory.rs new file mode 100644 index 000000000..21de89a5a --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/factory.rs @@ -0,0 +1,41 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/factory.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/factory.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_external_env_factory_getter() { + let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); + + let got: &EmptyExternalEnv = factory.external_env_factory(); + + // Verify the getter returns a stable reference to the same field. + assert!(core::ptr::eq(got, factory.external_env_factory())); + } + + #[test] + fn test_dyn_precompiles_builder_receives_the_behavior_spec() { + use alloy_evm::EvmFactory as _; + use core::sync::atomic::{AtomicU8, Ordering}; + + // The builder must see the behavior projection, never an alias rung: an external + // builder keyed on exact specs would otherwise install a different precompile set + // during a rollback window. + static SEEN_SPEC: AtomicU8 = AtomicU8::new(u8::MAX); + + let factory = + MegaEvmFactory::new().with_dyn_precompiles_builder(std::sync::Arc::new(|spec| { + SEEN_SPEC.store(spec as u8, Ordering::SeqCst); + revm::primitives::HashMap::default() + })); + + let mut evm_env = EvmEnv::::default(); + evm_env.cfg_env.spec = MegaSpecId::MINI_REX_1; + let _evm = factory.create_evm(crate::test_utils::MemoryDatabase::default(), evm_env); + + assert_eq!(SEEN_SPEC.load(Ordering::SeqCst), MegaSpecId::EQUIVALENCE as u8); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/host.rs b/crates/mega-evm/tests/_pending/src/evm/host.rs new file mode 100644 index 000000000..7852c5b45 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/host.rs @@ -0,0 +1,424 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/host.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/host.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, keccak256}; + use core::cell::Cell; + use revm::{ + primitives::HashMap, + state::{AccountInfo, Bytecode}, + Database, + }; + + /// Minimal `revm::Database` implementation that mimics the production + /// `reth`-style `StateProviderDatabase` contract: `basic()` returns + /// `AccountInfo { code: None, code_hash: }` for accounts with + /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via + /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — + /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache + /// miss against it would always see the code already hydrated. + #[derive(Default)] + struct LazyCodeDatabase { + accounts: HashMap, + codes: HashMap, + storage_calls: Cell, + } + + impl LazyCodeDatabase { + fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { + let code = Bytecode::new_raw(bytecode); + let code_hash = code.hash_slow(); + self.accounts.insert( + address, + AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, + ); + self.codes.insert(code_hash, code); + self + } + + fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { + let code = Bytecode::new_eip7702(delegate); + let code_hash = code.hash_slow(); + self.accounts.insert( + address, + AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, + ); + self.codes.insert(code_hash, code); + self + } + + fn storage_calls(&self) -> usize { + self.storage_calls.get() + } + } + + impl revm::Database for LazyCodeDatabase { + type Error = core::convert::Infallible; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without + // populating `code`, even when the account has on-chain bytecode. + Ok(self.accounts.get(&address).cloned()) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) + } + + fn storage(&mut self, _address: Address, _index: U256) -> Result { + self.storage_calls.set(self.storage_calls.get() + 1); + Ok(U256::ZERO) + } + + fn block_hash(&mut self, _number: u64) -> Result { + Ok(B256::ZERO) + } + } + + /// `inspect_account(addr, false)` must not hydrate `info.code` on the vacant + /// branch — callers that need it pass `load_code = true`. + #[test] + fn test_inspect_account_vacant_path_does_not_hydrate_code() { + const ADDR: Address = address!("00000000000000000000000000000000000000aa"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); // PUSH1 1 PUSH1 1 ADD + let expected_hash = keccak256(&bytecode); + + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let account = + inspect_account(&mut journal, ADDR, false).expect("inspect_account must succeed"); + + assert_eq!( + account.info.code_hash, expected_hash, + "code_hash must propagate from the database's `basic()` result", + ); + assert!( + account.info.code.is_none(), + "`load_code = false` must leave `info.code` as-is on the vacant branch", + ); + } + + /// `inspect_account(addr, true)` hydrates `info.code` from `code_by_hash` on + /// first cold inspection against a lazy-code database. + #[test] + fn test_inspect_account_with_load_code_hydrates_lazy_bytecode_on_first_touch() { + const ADDR: Address = address!("00000000000000000000000000000000000000aa"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); + let mut journal = Journal::new(db); + + let account = inspect_account(&mut journal, ADDR, true) + .expect("inspect_account must succeed on first cold-touch"); + let hydrated = account + .info + .code + .as_ref() + .expect("`load_code = true` must populate `info.code` from code_by_hash"); + assert_eq!( + hydrated.original_bytes().as_ref(), + bytecode.as_ref(), + "hydrated bytecode must match what `code_by_hash` would return", + ); + } + + /// The occupied-branch hydration must keep firing — a second `inspect_account` + /// against the same lazy-DB address must observe hydrated `info.code` even with + /// `load_code = false`. + #[test] + fn test_inspect_account_occupied_branch_hydrates_on_second_inspection() { + const ADDR: Address = address!("00000000000000000000000000000000000000bb"); + let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let first_code_hash = inspect_account(&mut journal, ADDR, false) + .expect("first inspection must succeed") + .info + .code_hash; + let second = + inspect_account(&mut journal, ADDR, false).expect("second inspection must succeed"); + + assert_eq!( + second.info.code_hash, first_code_hash, + "code_hash must be identical across cache miss and cache hit", + ); + assert!( + second.info.code.is_some(), + "second inspection must observe the hydrated code via the occupied-branch \ + `code_by_hash` load", + ); + } + + /// `inspect_account(addr, true)` must short-circuit on EOAs — the `code_hash != + /// KECCAK_EMPTY` guard keeps `code_by_hash` off the hot path. + #[test] + fn test_inspect_account_with_load_code_leaves_eoa_code_empty() { + const EOA: Address = address!("00000000000000000000000000000000000000cc"); + + let mut db = LazyCodeDatabase::default(); + db.accounts.insert( + EOA, + AccountInfo { + balance: U256::from(1_000_000u64), + nonce: 5, + code_hash: KECCAK_EMPTY, + code: None, + }, + ); + let mut journal = Journal::new(db); + + let account = inspect_account(&mut journal, EOA, true) + .expect("inspect_account must succeed and be a no-op on EOAs"); + assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); + assert!( + account.info.code.is_none(), + "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ + `code_by_hash` off the hot path for accounts without on-chain code", + ); + } + + /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate + /// `info.code` — on either branch. In particular the occupied branch must not fall through to + /// `code_by_hash` the way `inspect_account(.., false)` does (see + /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets the + /// REX6 keyless-deploy occupancy check decide on the hash alone, without demanding an + /// already-warmed occupied address's bytecode in a stateless witness carrying only its proof. + #[test] + fn test_inspect_account_code_hash_never_hydrates_code() { + const ADDR: Address = address!("00000000000000000000000000000000000000dd"); + let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST + let expected_hash = keccak256(&bytecode); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + // Vacant cache-miss: returns the hash from `basic()` without hydrating code. + let vacant_hash = + inspect_account_code_hash(&mut journal, ADDR).expect("vacant read must succeed"); + assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); + assert!( + journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), + "vacant branch must not hydrate info.code", + ); + + // The address is now resident with `code == None`. `inspect_account` would hydrate on this + // occupied branch; `inspect_account_code_hash` must not. + let occupied_hash = + inspect_account_code_hash(&mut journal, ADDR).expect("occupied read must succeed"); + assert_eq!( + occupied_hash, expected_hash, + "occupied branch must return the cached code_hash" + ); + assert!( + journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), + "inspect_account_code_hash must NOT hydrate info.code on the occupied branch", + ); + } + + /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the + /// very first cold inspection against a lazy-code database. Regression guard: + /// any refactor that re-introduces a code-None branch silently degrades the + /// walk to "treat the delegator as a regular EOA". + #[test] + fn test_inspect_account_delegated_follows_eip7702_on_cold_first_touch() { + use revm::context::JournalTr; + + const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); + const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); + let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); // PUSH1 0x42 PUSH1 0 SSTORE + + let db = LazyCodeDatabase::default() + .with_eip7702_delegation(DELEGATOR, DELEGATE) + .with_account_code(DELEGATE, delegate_bytecode.clone()); + + let mut journal = Journal::new(db); + + let resolved = journal + .inspect_account_delegated(MegaSpecId::REX5, DELEGATOR) + .expect("inspect_account_delegated must succeed on a cold-cache first touch"); + + // The resolved account must be the delegate, not the delegator. The only way + // to distinguish them is the code: the delegator's code is the EIP-7702 + // designation pointing at DELEGATE; the delegate's code is the raw bytecode. + let hydrated = resolved.info.code.as_ref().expect( + "delegate's bytecode must be hydrated by the inner inspect_account call — \ + without the vacant-path hydration, the cold-touch on DELEGATE would leave \ + code as None and any subsequent EIP-7702 walk would see a wrongly-empty target", + ); + assert!( + !matches!(hydrated, Bytecode::Eip7702(_)), + "resolved account must NOT be the delegator (whose code is the EIP-7702 \ + designation); got: {hydrated:?}", + ); + assert_eq!( + hydrated.original_bytes().as_ref(), + delegate_bytecode.as_ref(), + "resolved account's code must match the delegate's raw bytecode — confirms \ + the delegation was followed exactly one hop", + ); + } + + /// Pins the `LazyCodeDatabase` fixture's contract against the production + /// `revm::Database` shape it is modeling: `basic()` returns + /// `code: None` for known accounts, `None` for unknown addresses; + /// `code_by_hash()` falls back to empty bytecode for an unknown hash; + /// `storage()` and `block_hash()` are inert stubs (no tests exercise them via + /// `inspect_account`, but they must remain wired so the fixture is a complete + /// `revm::Database`). If the fixture ever drifts (e.g. someone "helpfully" + /// makes `basic()` eagerly populate `code` like `MemoryDatabase` does), the + /// inspect-account tests above silently lose their load-bearing property — + /// this test fails fast in that case. + #[test] + fn test_lazy_code_database_fixture_pins_reth_style_contract() { + const KNOWN: Address = address!("00000000000000000000000000000000000000ee"); + let bytecode = Bytes::from_static(&[0x00]); + let mut db = LazyCodeDatabase::default().with_account_code(KNOWN, bytecode); + + let known = db.basic(KNOWN).unwrap().expect("known account must resolve"); + assert!( + known.code.is_none(), + "LazyCodeDatabase::basic must NOT pre-populate code — that is the \ + behavior `inspect_account` is being tested against", + ); + assert!( + db.basic(Address::ZERO).unwrap().is_none(), + "unknown address must return None from basic()", + ); + + let unknown_hash = keccak256([0xffu8]); + assert_eq!( + db.code_by_hash(unknown_hash).unwrap().original_bytes().len(), + 0, + "unknown code_hash must fall back to empty bytecode", + ); + + assert_eq!(db.storage(KNOWN, U256::ZERO).unwrap(), U256::ZERO); + assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); + } + + // === inspect_storage coverage tests (PR #334) === + + #[test] + fn test_inspect_storage_rex4_slot_hit_returns_existing_value() { + const ADDR: Address = address!("00000000000000000000000000000000000000bb"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let key = U256::from(3); + let expected_value = U256::from(42); + { + let tid = journal.transaction_id; + let account = inspect_account(&mut journal, ADDR, false).unwrap(); + let mut slot = EvmStorageSlot::new(expected_value, tid); + slot.mark_cold(); + account.storage.insert(key, slot); + } + + let spec = MegaSpecId::REX4; + let slot = journal + .inspect_storage(spec, ADDR, key) + .expect("inspect_storage must succeed on existing slot"); + + assert_eq!( + slot.present_value, expected_value, + "REX4 slot hit must return the pre-seeded value" + ); + assert!(slot.is_cold, "inspected slot must remain cold"); + } + + #[test] + fn test_inspect_storage_rex4_slot_miss_inserts_and_returns_db_value() { + const ADDR: Address = address!("00000000000000000000000000000000000000cc"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let key = U256::from(7); + let spec = MegaSpecId::REX4; + + let slot = journal + .inspect_storage(spec, ADDR, key) + .expect("inspect_storage must succeed on absent slot"); + + assert_eq!( + slot.present_value, + U256::ZERO, + "absent slot on non-created account must return ZERO from database" + ); + assert!(slot.is_cold, "newly inserted slot must be marked cold"); + + let calls_after_first = journal.database.storage_calls(); + let slot2 = + journal.inspect_storage(spec, ADDR, key).expect("second inspect_storage must succeed"); + + assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); + assert_eq!( + journal.database.storage_calls(), + calls_after_first, + "second inspect_storage on the same slot must hit the cache, not the DB", + ); + } + + #[test] + fn test_inspect_storage_rex4_newly_created_short_circuits_db() { + const ADDR: Address = address!("00000000000000000000000000000000000000dd"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + { + let account = inspect_account(&mut journal, ADDR, false).unwrap(); + account.mark_created(); + } + + let key = U256::from(1); + let spec = MegaSpecId::REX4; + + let slot = journal + .inspect_storage(spec, ADDR, key) + .expect("inspect_storage must succeed on newly-created account"); + + assert_eq!( + slot.present_value, + U256::ZERO, + "newly-created account must return ZERO without querying database" + ); + assert!(slot.is_cold, "slot must be marked cold"); + } + + #[test] + fn test_inspect_storage_rex4_ignores_eip7702_delegation() { + const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); + const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); + let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default() + .with_eip7702_delegation(DELEGATOR, DELEGATE) + .with_account_code(DELEGATE, delegate_code); + let mut journal = Journal::new(db); + + let key = U256::from(2); + let expected = U256::from(99); + { + let tid = journal.transaction_id; + let account = inspect_account(&mut journal, DELEGATOR, false).unwrap(); + let mut slot = EvmStorageSlot::new(expected, tid); + slot.mark_cold(); + account.storage.insert(key, slot); + } + + let spec = MegaSpecId::REX4; + let slot = journal + .inspect_storage(spec, DELEGATOR, key) + .expect("inspect_storage must succeed for REX4 delegator"); + + assert_eq!( + slot.present_value, expected, + "REX4 must read storage from delegator (original address), not delegate" + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs new file mode 100644 index 000000000..f2cd103b1 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/mod.rs @@ -0,0 +1,233 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/mod.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/mod.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use alloy_primitives::{address, Bytes, U256}; + use revm::{ + context::{ + result::{ExecResultAndState, ExecutionResult}, + ContextSetters, TxEnv, + }, + database::State, + inspector::NoOpInspector, + state::EvmState, + ExecuteCommitEvm, ExecuteEvm, InspectEvm, SystemCallEvm, + }; + + const CALLER: Address = address!("4000000000000000000000000000000000000001"); + const CALLEE: Address = address!("5000000000000000000000000000000000000001"); + + fn configure_context(db: DB) -> MegaContext { + let mut context = MegaContext::new(db, MegaSpecId::REX4); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + context + } + + fn tx_env() -> TxEnv { + TxEnv { + caller: CALLER, + gas_limit: 100_000, + kind: alloy_primitives::TxKind::Call(CALLEE), + value: U256::ZERO, + data: Bytes::new(), + ..Default::default() + } + } + + fn mega_tx() -> MegaTransaction { + let mut tx = MegaTransaction::new(tx_env()); + tx.enveloped_tx = Some(Bytes::new()); + tx + } + + #[test] + fn test_mega_evm_builder_chain_produces_working_evm() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let context = configure_context(&mut db); + let evm = MegaEvm::new(context); + + let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(777); + let evm = evm.with_tx_runtime_limits(limits); + assert_eq!(evm.ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, 777); + + let evm = evm.with_dyn_precompiles(HashMap::default()); + let evm = evm.with_inspector(NoOpInspector); + let evm = evm.without_inspector(); + + let inner = evm.into_inner(); + assert_eq!(inner.ctx.block.gas_limit, u64::MAX); + } + + #[test] + fn test_alloy_evm_interface_methods_execute_transactions() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + + assert_eq!(alloy_evm::Evm::chain_id(&evm), evm.ctx_ref().cfg.chain_id); + assert_eq!(alloy_evm::Evm::block(&evm).gas_limit, evm.ctx_ref().block.gas_limit); + + alloy_evm::Evm::set_inspector_enabled(&mut evm, true); + assert!(evm.inspect); + let (_db_ref, _inspector, _precompiles) = alloy_evm::Evm::components(&evm); + let (_db_ref_mut, _inspector_mut, _precompiles_mut) = + alloy_evm::Evm::components_mut(&mut evm); + + let result = alloy_evm::Evm::transact_raw(&mut evm, mega_tx()).unwrap(); + assert!(result.result.is_success()); + + let system_call = + alloy_evm::Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()).unwrap(); + assert!(system_call.result.is_success()); + + let (_db_back, evm_env) = alloy_evm::Evm::finish(evm); + assert_eq!(evm_env.cfg_env.spec, MegaSpecId::REX4); + } + + #[test] + fn test_revm_execute_one_finalize_commit_works() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + let block = revm::context::BlockEnv { gas_limit: 222_222, ..Default::default() }; + ExecuteEvm::set_block(&mut evm, block); + assert_eq!(evm.block_env_ref().gas_limit, 222_222); + + let one: ExecutionResult = + ExecuteEvm::transact_one(&mut evm, mega_tx()).unwrap(); + assert!(one.is_success()); + let state = ExecuteEvm::finalize(&mut evm); + ExecuteCommitEvm::commit(&mut evm, state); + } + + #[test] + fn test_revm_replay_works() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + evm.ctx().set_tx(mega_tx()); + let replay: ExecResultAndState, EvmState> = + ExecuteEvm::replay(&mut evm).unwrap(); + assert!(replay.result.is_success()); + } + + #[test] + fn test_revm_inspect_one_tx_works() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + InspectEvm::set_inspector(&mut evm, NoOpInspector); + let inspected: ExecutionResult = + InspectEvm::inspect_one_tx(&mut evm, mega_tx()).unwrap(); + assert!(inspected.is_success()); + } + + #[test] + fn test_revm_system_call_with_caller_works() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + let system_call: ExecutionResult = + SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) + .unwrap(); + assert!(system_call.is_success()); + } + + #[test] + fn test_transact_system_call_with_gas_limit_uses_passed_value() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + + let result = evm + .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) + .unwrap(); + assert!(result.result.is_success()); + // The custom gas limit must be applied to the underlying tx. + assert_eq!(evm.inner.ctx.tx.base.gas_limit, 123_456_789); + } + + #[test] + fn test_default_system_call_keeps_upstream_30m_gas_limit() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + context.block.gas_limit = 100_000_000; + let mut evm = MegaEvm::new(context); + + // The default system-call entry point must NOT be widened by REX5 — only the + // explicit `transact_system_call_with_gas_limit` path should pick up the live + // block budget. This preserves byte-level behavior of EIP-2935 / EIP-4788 + // pre-block calls across all specs. + SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) + .unwrap(); + // Literal, not `SYSTEM_CALL_GAS_LIMIT_FLOOR`: this assertion verifies revm's + // upstream hardcoded default. If upstream ever drifts from our floor, this + // test should fail loudly rather than be auto-aligned by our constant. + assert_eq!(evm.inner.ctx.tx.base.gas_limit, 30_000_000); + } + + #[test] + fn test_mega_evm_exposes_state_wrapper_block_hashes() { + let mut db = MemoryDatabase::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(7, B256::from([7_u8; 32])); + + let evm = MegaEvm::new(configure_context(&mut state)); + assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); + } + + #[test] + fn test_convenience_execution_methods_work() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)).with_inspector(NoOpInspector); + + let executed = evm.execute_transaction(mega_tx()).unwrap(); + assert!(executed.result.is_success()); + + #[allow(deprecated)] + let inspected = evm.inspect_transaction(mega_tx()).unwrap(); + assert!(inspected.result.is_success()); + } + + #[test] + fn test_execute_transaction_fails_with_insufficient_balance() { + let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + + let mut tx = MegaTransaction::new(TxEnv { + caller: CALLER, + gas_limit: 100_000, + kind: alloy_primitives::TxKind::Call(CALLEE), + value: U256::from(1_000_000), + data: Bytes::new(), + ..Default::default() + }); + tx.enveloped_tx = Some(Bytes::new()); + + let result = evm.execute_transaction(tx); + assert!(result.is_err()); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs new file mode 100644 index 000000000..a412c03f3 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs @@ -0,0 +1,211 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/precompiles.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/precompiles.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + #[cfg(not(feature = "std"))] + use alloc as std; + use std::{rc::Rc, vec::Vec}; + + use super::{kzg_point_evaluation::GAS_COST, mini_rex, rex, MegaPrecompiles}; + use crate::{ + test_utils::MemoryDatabase, AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaSpecId, + }; + use alloy_evm::precompiles::PrecompilesMap; + use alloy_primitives::Bytes; + use core::cell::RefCell; + use revm::{ + handler::PrecompileProvider, + interpreter::{InputsImpl, InstructionResult}, + }; + use sha2::{Digest, Sha256}; + + /// Generate valid KZG Point Evaluation test data from EIP-4844 test vectors. + fn generate_kzg_test_input() -> InputsImpl { + let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); + let mut versioned_hash = Sha256::digest(&commitment).to_vec(); + versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG + let z = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000") + .unwrap(); + let y = hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9") + .unwrap(); + let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); + + let mut input = Vec::new(); + input.extend_from_slice(&versioned_hash); + input.extend_from_slice(&z); + input.extend_from_slice(&y); + input.extend_from_slice(&commitment); + input.extend_from_slice(&proof); + + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + InputsImpl { + target_address: address, + bytecode_address: Some(address), + caller_address: address, + input: revm::interpreter::CallInput::Bytes(Bytes::from(input)), + call_value: Default::default(), + } + } + + /// Mirror of `generate_kzg_test_input()` but with the last byte of the proof + /// flipped — structurally valid (192 bytes, matching versioned hash) but + /// upstream verification returns `PrecompileError::BlobVerifyKzgProofFailed`. + fn generate_invalid_proof_kzg_test_input() -> InputsImpl { + let mut inputs = generate_kzg_test_input(); + let bytes = match inputs.input { + revm::interpreter::CallInput::Bytes(b) => b, + _ => panic!("expected Bytes"), + }; + let mut buf = bytes.to_vec(); + let last = buf.len() - 1; + buf[last] ^= 0x01; + inputs.input = revm::interpreter::CallInput::Bytes(Bytes::from(buf)); + inputs + } + + fn set_spec_for_context( + precompiles_map: &mut PrecompilesMap, + _context: &MegaContext, + spec: op_revm::OpSpecId, + ) -> bool { + >>::set_spec( + precompiles_map, + spec, + ) + } + + #[test] + fn test_kzg_precompile_sufficient_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); + assert!(result.is_ok(), "Precompile should succeed with sufficient gas"); + let output = result.unwrap().unwrap(); + assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_kzg_precompile_exact_gas_limit() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST); + assert!(result.is_ok(), "Precompile should succeed with exact GAS_COST"); + let output = result.unwrap().unwrap(); + assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_set_spec_preserves_mega_kzg_override() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + + let changed = + set_spec_for_context(&mut precompiles_map, &context, op_revm::OpSpecId::ISTHMUS); + assert!(!changed, "Mega precompile table must remain unchanged"); + + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); + let output = result.expect("run ok").expect("Some output"); + assert!(matches!(output.result, InstructionResult::Return)); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_kzg_precompile_insufficient_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 50_000); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + #[test] + fn test_kzg_precompile_one_below_gas_limit() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST - 1); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + #[test] + fn test_kzg_precompile_zero_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 0); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + /// Replaces the context's `additional_limit` with one whose `tx_compute_gas_limit` + /// is set to `limit`, so tests can exercise the REX5 compute-gas cap path with a + /// small remaining budget without having to pre-record large gas amounts. + fn set_tx_compute_gas_limit( + context: &mut MegaContext, + spec: MegaSpecId, + limit: u64, + ) { + let tx_limits = EvmTxRuntimeLimits { + tx_compute_gas_limit: limit, + ..EvmTxRuntimeLimits::from_spec(spec) + }; + context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); + } + +} diff --git a/crates/mega-evm/tests/_pending/src/evm/result.rs b/crates/mega-evm/tests/_pending/src/evm/result.rs new file mode 100644 index 000000000..044576f3a --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/result.rs @@ -0,0 +1,57 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/result.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/result.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use revm::context::result::OutOfGasError; + + #[test] + fn test_base_halt_reasons_convert_roundtrip() { + let eth_reason = EthHaltReason::OutOfGas(OutOfGasError::Basic); + let mega_from_eth = MegaHaltReason::from(eth_reason); + let mega_from_op = MegaHaltReason::from(OpHaltReason::Base(eth_reason)); + + assert_eq!(mega_from_eth, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); + assert_eq!(mega_from_op, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); + assert_eq!(EthHaltReason::try_from(mega_from_eth).unwrap(), eth_reason); + assert_eq!(EthHaltReason::try_from(mega_from_op).unwrap(), eth_reason); + } + + #[test] + fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { + let reason = MegaHaltReason::VolatileDataAccessOutOfGas { + access_type: VolatileDataAccess::ORACLE, + limit: 100, + actual: 101, + }; + + assert_eq!(EthHaltReason::try_from(reason.clone()), Err(reason)); + } + + #[test] + fn test_op_specific_halt_reason_does_not_convert_to_eth() { + let op_reason = OpHaltReason::FailedDeposit; + let mega = MegaHaltReason::from(op_reason.clone()); + assert_eq!(mega, MegaHaltReason::Base(op_reason)); + assert!(EthHaltReason::try_from(mega).is_err()); + } + + #[test] + fn test_all_mega_specific_variants_fail_eth_conversion() { + let variants: Vec = vec![ + MegaHaltReason::DataLimitExceeded { limit: 1, actual: 2 }, + MegaHaltReason::KVUpdateLimitExceeded { limit: 1, actual: 2 }, + MegaHaltReason::ComputeGasLimitExceeded { limit: 1, actual: 2 }, + MegaHaltReason::StateGrowthLimitExceeded { limit: 1, actual: 2 }, + MegaHaltReason::SystemTxInvalidCallee { callee: Address::ZERO }, + ]; + for variant in variants { + assert!( + EthHaltReason::try_from(variant).is_err(), + "mega-specific variant should not convert to EthHaltReason" + ); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/spec.rs b/crates/mega-evm/tests/_pending/src/evm/spec.rs new file mode 100644 index 000000000..d01d0a472 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/spec.rs @@ -0,0 +1,63 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/spec.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/spec.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// The one golden spec table: every spec with its string identifier and its pinned ladder + /// position. The spec column must be exactly [`MegaSpecId::ALL`] (asserted in the + /// round-trip test); the name and position columns stay hand-written — deriving either + /// from the code under test would make its check vacuous. + const ALL_SPECS: [(MegaSpecId, &str, u8); 12] = [ + (MegaSpecId::EQUIVALENCE, name::EQUIVALENCE, 0), + (MegaSpecId::MINI_REX, name::MINI_REX, 1), + (MegaSpecId::MINI_REX_1, name::MINI_REX_1, 2), + (MegaSpecId::MINI_REX_2, name::MINI_REX_2, 3), + (MegaSpecId::REX, name::REX, 4), + (MegaSpecId::REX1, name::REX1, 5), + (MegaSpecId::REX2, name::REX2, 6), + (MegaSpecId::REX3, name::REX3, 7), + (MegaSpecId::REX4, name::REX4, 8), + (MegaSpecId::REX5, name::REX5, 9), + (MegaSpecId::REX6, name::REX6, 10), + (MegaSpecId::REX7, name::REX7, 11), + ]; + + #[test] + fn test_spec_names_roundtrip_and_display() { + // The spec column must be exactly `MegaSpecId::ALL`, so a newly introduced spec cannot + // be forgotten here. + assert!(ALL_SPECS.iter().map(|(spec, _, _)| *spec).eq(MegaSpecId::ALL.iter().copied())); + + for (spec, expected_name, _) in ALL_SPECS { + assert_eq!(<&'static str>::from(spec), expected_name); + assert_eq!(MegaSpecId::from_str(expected_name).unwrap(), spec); + assert_eq!(spec.to_string(), expected_name); + } + + assert_eq!(MegaSpecId::default(), MegaSpecId::REX7); + assert_eq!(MegaSpecId::from_str("unknown"), Err(UnknownHardfork)); + } + + /// The completeness anchor for [`MegaSpecId::ALL`]: `Default` tracks the latest spec (its + /// own assertion above pins which), so a variant added without extending `ALL` fails here + /// once the default advances. The const assertion on `ladder_index` covers order and gaps; + /// this covers the tail. + #[test] + fn test_all_ends_at_the_latest_spec() { + assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); + } + + #[test] + fn test_all_specs_map_to_isthmus_and_prague() { + for spec in MegaSpecId::ALL.iter().copied() { + assert_eq!(spec.into_op_spec(), OpSpecId::ISTHMUS); + assert_eq!(spec.into_eth_spec(), EthSpecId::PRAGUE); + assert_eq!(revm::primitives::hardfork::SpecId::from(spec), EthSpecId::PRAGUE); + assert_eq!(OpSpecId::from(spec), OpSpecId::ISTHMUS); + } + } + +} diff --git a/crates/mega-evm/tests/_pending/src/evm/state.rs b/crates/mega-evm/tests/_pending/src/evm/state.rs new file mode 100644 index 000000000..2e5fb02f8 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/state.rs @@ -0,0 +1,43 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/state.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/state.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, Address, B256, U256}; + use revm::{ + database::{InMemoryDB, State}, + state::{AccountInfo, EvmStorageSlot}, + }; + + const TEST_ADDRESS: Address = address!("1000000000000000000000000000000000000001"); + + fn account_with_status(status: AccountStatus) -> Account { + Account { + info: AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: B256::ZERO, + code: None, + }, + transaction_id: 0, + storage: Default::default(), + status, + } + } + + #[test] + fn test_state_exposes_accessed_block_hashes() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(1, B256::ZERO); + state.block_hashes.insert(2, B256::from([2_u8; 32])); + + let hashes = state.get_accessed_block_hashes(); + assert_eq!(hashes.len(), 2); + assert_eq!(hashes.get(&1), Some(&B256::ZERO)); + assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); + } + +} diff --git a/crates/mega-evm/tests/_pending/src/external/gas.rs b/crates/mega-evm/tests/_pending/src/external/gas.rs new file mode 100644 index 000000000..58719dd9a --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/external/gas.rs @@ -0,0 +1,120 @@ +//! Unit tests extracted from `crates/mega-evm/src/external/gas.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/gas.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::external::test_utils::TestExternalEnvs; + + fn cost_with_capacity(spec: MegaSpecId, capacity: u64) -> DynamicGasCost { + // Map the bucket id that the simple bucket hasher will produce for the zero address / + // zero slot to the requested capacity. + let bucket_for_account = + ::bucket_id_for_account(Address::ZERO); + let bucket_for_slot = + ::bucket_id_for_slot(Address::ZERO, U256::ZERO); + let env = TestExternalEnvs::new() + .with_bucket_capacity(bucket_for_account, capacity) + .with_bucket_capacity(bucket_for_slot, capacity); + DynamicGasCost::new(spec, env, 0) + } + + /// `MIN_BUCKET_SIZE * u64::MAX` cannot be represented in `u64`; verify the hardened + /// arithmetic does not panic and saturates instead of wrapping. + #[test] + fn test_sstore_set_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + #[test] + fn test_new_account_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.new_account_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.new_account_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + #[test] + fn test_create_contract_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.create_contract_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.create_contract_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + /// REX6 system-exempt path: the unscaled cost (`multiplier = 1`) is `0` for the REX-family + /// formula `base × (multiplier − 1)`, and is independent of the actual bucket capacity. This + /// is what makes a system call's storage cost immune to SALT bucket scaling. + #[test] + fn test_unscaled_gas_is_zero_for_rex_and_independent_of_capacity() { + for capacity in [MIN_BUCKET_SIZE as u64, 1_280_000, u64::MAX] { + let cost = cost_with_capacity(MegaSpecId::REX6, capacity); + assert_eq!(cost.sstore_set_gas_unscaled(), 0); + assert_eq!(cost.new_account_gas_unscaled(), 0); + assert_eq!(cost.create_contract_gas_unscaled(), 0); + } + } + + /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX + /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a + /// tightened gate (e.g. REX1) fails here. + #[test] + fn test_unscaled_gas_is_available_from_rex_exactly() { + let cost = cost_with_capacity(MegaSpecId::REX, MIN_BUCKET_SIZE as u64); + assert_eq!(cost.sstore_set_gas_unscaled(), 0); + assert_eq!(cost.new_account_gas_unscaled(), 0); + assert_eq!(cost.create_contract_gas_unscaled(), 0); + } + + /// Pre-REX callers must trip the debug assert — a loosened gate (e.g. `MiniRex`) would + /// silently serve the REX-family formula to a spec that prices storage differently. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_sstore_set_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .sstore_set_gas_unscaled(); + } + + /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_new_account_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .new_account_gas_unscaled(); + } + + /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_create_contract_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .create_contract_gas_unscaled(); + } + + /// The unscaled result equals the SALT-driven result evaluated at the minimum bucket + /// capacity, confirming the shared formula helper produces consistent values across both paths. + #[test] + fn test_unscaled_matches_salt_path_at_min_capacity() { + let mut cost = cost_with_capacity(MegaSpecId::REX6, MIN_BUCKET_SIZE as u64); + assert_eq!( + cost.sstore_set_gas_unscaled(), + cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(), + ); + } +} diff --git a/crates/mega-evm/src/external/hasher/mod.rs b/crates/mega-evm/tests/_pending/src/external/hasher/mod.rs similarity index 57% rename from crates/mega-evm/src/external/hasher/mod.rs rename to crates/mega-evm/tests/_pending/src/external/hasher/mod.rs index 7e1178d37..319a85d97 100644 --- a/crates/mega-evm/src/external/hasher/mod.rs +++ b/crates/mega-evm/tests/_pending/src/external/hasher/mod.rs @@ -1,72 +1,6 @@ -//! Deterministic hashing for mapping keys to SALT buckets. -//! -//! This module provides the [`AHashBucketHasher`] which implements [`BucketHasher`] using -//! a vendored subset of `AHash` v0.8.12's deterministic fallback algorithm. -//! This ensures identical bucket ID results across all platforms, matching the production -//! `salt` crate's behavior. -//! -//! # Attribution -//! -//! The hashing implementation is derived from [AHash v0.8.12](https://github.com/tkaitchuck/aHash) -//! under Apache License 2.0. See [`NOTICE.md`](./NOTICE.md) for full attribution. - -mod convert; -mod fallback; - -use self::fallback::RandomState; -use crate::{BucketHasher, BucketId, MIN_BUCKET_SIZE}; -use core::hash::{BuildHasher, Hasher}; - -/// Width of each trie level in bits (256-ary trie). -const TRIE_WIDTH_BITS: usize = 8; - -/// Number of levels in the main SALT trie. -const MAIN_TRIE_LEVELS: usize = 4; - -/// Total number of buckets: 256^3 = 16,777,216. -const NUM_BUCKETS: usize = 1 << ((MAIN_TRIE_LEVELS - 1) * TRIE_WIDTH_BITS); - -/// Number of metadata buckets reserved at the start: 65,536. -const NUM_META_BUCKETS: usize = NUM_BUCKETS / MIN_BUCKET_SIZE; - -/// Number of key-value data buckets: 16,711,680. -const NUM_KV_BUCKETS: usize = NUM_BUCKETS - NUM_META_BUCKETS; - -/// Fixed seeds derived from the lower 32 bytes of keccak256("Make Ethereum Great Again"). -const HASHER_SEEDS: [u64; 4] = [0x921321f4, 0x2ccb667e, 0x60d68842, 0x077ada9d]; - -/// Computes a deterministic 64-bit hash of the input bytes using the `AHash` fallback algorithm. -#[inline(always)] -fn hash(bytes: &[u8]) -> u64 { - static HASH_BUILDER: RandomState = - RandomState::with_seeds(HASHER_SEEDS[0], HASHER_SEEDS[1], HASHER_SEEDS[2], HASHER_SEEDS[3]); - - let mut hasher = HASH_BUILDER.build_hasher(); - hasher.write(bytes); - hasher.finish() -} - -/// Maps a plain key (account address or address+slot) to a SALT bucket ID. -/// -/// Returns a bucket ID in the range `[NUM_META_BUCKETS, NUM_BUCKETS)`. -/// The first `NUM_META_BUCKETS` buckets are reserved for metadata storage. -#[inline(always)] -fn bucket_id(key: &[u8]) -> BucketId { - (hash(key) % NUM_KV_BUCKETS as u64 + NUM_META_BUCKETS as u64) as BucketId -} - -/// AHash-based bucket hasher matching the production `salt` crate's deterministic algorithm. -/// -/// This hasher uses the vendored `AHash` v0.8.12 fallback (folded-multiply) with fixed seeds -/// to produce bucket IDs identical to the `salt` crate on all platforms. -#[derive(Debug, Clone, Copy)] -pub struct AHashBucketHasher; - -impl BucketHasher for AHashBucketHasher { - fn bucket_id(key: &[u8]) -> BucketId { - bucket_id(key) - } -} +//! Unit tests extracted from `crates/mega-evm/src/external/hasher/mod.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/hasher/mod.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/external/mod.rs b/crates/mega-evm/tests/_pending/src/external/mod.rs new file mode 100644 index 000000000..75955b551 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/external/mod.rs @@ -0,0 +1,21 @@ +//! Unit tests extracted from `crates/mega-evm/src/external/mod.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/mod.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{OracleEnv, SaltEnv, MIN_BUCKET_SIZE}; + use alloy_primitives::{Address, Bytes, B256, U256}; + + #[test] + fn test_empty_external_env_factory_returns_minimum_bucket_and_no_oracle() { + let envs = EmptyExternalEnv.external_envs(42); + + assert_eq!(envs.salt_env.get_bucket_capacity(123).unwrap(), MIN_BUCKET_SIZE as u64); + assert_eq!(envs.oracle_env.get_oracle_storage(U256::from(7)), None); + envs.oracle_env.on_hint(Address::ZERO, B256::ZERO, Bytes::new()); + assert_eq!(::bucket_id_for_account(Address::ZERO), 0); + assert_eq!(::bucket_id_for_slot(Address::ZERO, U256::ZERO), 0); + } +} diff --git a/crates/mega-evm/tests/_pending/src/external/test_utils.rs b/crates/mega-evm/tests/_pending/src/external/test_utils.rs new file mode 100644 index 000000000..e4d802cba --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/external/test_utils.rs @@ -0,0 +1,22 @@ +//! Unit tests extracted from `crates/mega-evm/src/external/test_utils.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/test_utils.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_with_default_bucket_capacity_applies_to_all_buckets() { + use crate::external::salt::SaltEnv; + let env = + TestExternalEnvs::::new().with_default_bucket_capacity(2048); + // Any bucket id not explicitly configured now returns the default, not MIN_BUCKET_SIZE. + assert_eq!(env.get_bucket_capacity(123), Ok(2048)); + assert_eq!(env.get_bucket_capacity(999), Ok(2048)); + // An explicit per-bucket capacity still wins. + let env = env.with_bucket_capacity(123, 512); + assert_eq!(env.get_bucket_capacity(123), Ok(512)); + assert_eq!(env.get_bucket_capacity(999), Ok(2048)); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs new file mode 100644 index 000000000..e43e59eaa --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs @@ -0,0 +1,28 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/compute_gas.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/compute_gas.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// Usage exactly equal to the detained limit must NOT count as a detained exceed: + /// the predicate is strictly-greater-than (`used > detained_limit`), not `>=`. + #[test] + fn test_is_detained_exceed_is_strict_at_boundary() { + // tx_limit = 100, detained lowered to 50 (< tx_limit, so detention is binding). + let mut tracker = ComputeGasTracker::new(MegaSpecId::MINI_REX, 100); + tracker.set_detained_limit(50); + + // Usage exactly at the detained limit: not exceeded. + tracker.record_gas_used(50); + assert!( + !tracker.is_detained_exceed(), + "usage == detained_limit must not be a detained exceed" + ); + + // One unit over the limit: exceeded. + tracker.record_gas_used(1); + assert!(tracker.is_detained_exceed(), "usage > detained_limit must be a detained exceed"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/data_size.rs b/crates/mega-evm/tests/_pending/src/limit/data_size.rs new file mode 100644 index 000000000..e97f9e27e --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/data_size.rs @@ -0,0 +1,26 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/data_size.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/data_size.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// The originated data-size constants are *sums* of their salt key/value components, + /// not products. Pin the values against independent literals so an arithmetic slip + /// (e.g. `+` -> `*`) is caught (8 + 32 = 40, not 8 * 32 = 256). + #[test] + fn test_originated_data_size_constants() { + assert_eq!(STORAGE_SLOT_WRITE_SIZE, 40); + assert_eq!(ACCOUNT_INFO_WRITE_SIZE, 40); + } + + /// `has_active_frame` must reflect the underlying frame stack, not a constant. + #[test] + fn test_has_active_frame_reflects_frame_stack() { + let mut tracker = DataSizeTracker::new(MegaSpecId::MINI_REX, u64::MAX); + assert!(!tracker.has_active_frame(), "no frame pushed yet"); + tracker.push_empty_frame(); + assert!(tracker.has_active_frame(), "a frame is on the stack"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs b/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs new file mode 100644 index 000000000..a7ba67f45 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs @@ -0,0 +1,127 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/frame_limit.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/frame_limit.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use alloy_primitives::address; + + use super::*; + + const ADDR: Address = address!("0000000000000000000000000000000000001234"); + + /// `set_created_address` on an empty frame stack must be a no-op. + #[test] + fn test_set_created_address_empty_stack_is_noop() { + let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); + // No frame on the stack — should not panic, just do nothing. + t.set_created_address(ADDR); + } + + /// `set_created_address` panics when called twice on the same CREATE frame + /// (invariant: `target_address` must be `None` when first filled in). + #[test] + #[should_panic(expected = "created account already recorded")] + fn test_set_created_address_duplicate_panics() { + let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); + t.push_create_frame(); + t.set_created_address(ADDR); + t.set_created_address(ADDR); // second call must panic + } + + /// Drives `FrameLimitTracker` through a representative sequence of pushes, mutations, + /// and pops (both success and revert) and asserts that the cached `net_usage()` stays + /// in sync with the uncached reference walk after every step. This is the load-bearing + /// guarantee of the cache-based refactor: any future change that introduces a new + /// mutation site without going through a helper will break this test. + #[test] + fn test_net_usage_cache_matches_uncached() { + let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + assert_eq!(t.net_usage(), 0); + + // Pre-frame intrinsic usage goes to tx_entry. + t.add_tx_persistent(100); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + + // add_frame_persistent on empty stack must be a no-op and return false. + assert!(!t.add_frame_persistent(50)); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + // add_frame_discardable / add_frame_refund are no-ops on empty stack. + t.add_frame_discardable(50); + t.add_frame_refund(50); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + assert_eq!(t.net_usage(), 100); + + // Push frame 1 and mix in persistent/discardable/refund. + t.push_frame(()); + assert!(t.add_frame_persistent(20)); + t.add_frame_discardable(30); + t.add_frame_refund(10); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + + // Push frame 2 (nested) and mutate. + t.push_frame(()); + assert!(t.add_frame_persistent(7)); + t.add_frame_discardable(15); + t.add_frame_refund(3); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + + // Push frame 3 (deeper) and revert it — discardable & refund must vanish from cache, + // persistent must merge into the parent (frame 2). + t.push_frame(()); + assert!(t.add_frame_persistent(5)); + t.add_frame_discardable(11); + t.add_frame_refund(2); + let before_revert = t.net_usage(); + let popped = t.pop_frame(false).expect("frame 3 popped"); + assert_eq!(popped.discardable_usage, 11); + assert_eq!(popped.refund, 2); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + // After revert: cache should drop the child's discardable (11) and refund (2), + // so net_usage changes by -(11) + 2 = -9 vs before. + assert_eq!(t.net_usage(), before_revert - 9); + + // Push frame 3 again and pop it successfully — discardable/refund merge into parent, + // cache is unchanged by the pop itself (totals are invariant under transfer). + t.push_frame(()); + assert!(t.add_frame_persistent(4)); + t.add_frame_discardable(6); + t.add_frame_refund(1); + let before_success = t.net_usage(); + t.pop_frame(true); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + assert_eq!(t.net_usage(), before_success); + + // Pop frame 2 with success → merge into frame 1. + t.pop_frame(true); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + + // Pop the last frame (frame 1) with revert → discardable/refund vanish, persistent + // merges into tx_entry. + let before_last_revert = t.net_usage(); + let frame_1 = t.pop_frame(false).expect("frame 1 popped"); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + // The popped frame's discardable/refund leave the cache. + assert_eq!(t.net_usage(), before_last_revert - frame_1.discardable_usage + frame_1.refund); + + // Reset returns the cache to zero in sync with the entries. + t.reset(); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + assert_eq!(t.net_usage(), 0); + } + + /// Verifies that a refund exceeding the cumulative usage clamps `net_usage()` to 0, + /// matching the saturating semantics of the uncached reference. This guards against + /// signed-style accounting bugs where refunds outrun used and an unsigned subtraction + /// would otherwise wrap. + #[test] + fn test_net_usage_saturates_when_refund_exceeds_used() { + let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); + t.push_frame(()); + t.add_frame_discardable(10); + t.add_frame_refund(100); + assert_eq!(t.net_usage(), 0); + assert_eq!(t.net_usage(), t.net_usage_uncached()); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs new file mode 100644 index 000000000..5ae7a27e1 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs @@ -0,0 +1,19 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/kv_update.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/kv_update.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// `record_account_update` must charge exactly one KV update against the current frame + /// (used by REX5+ SELFDESTRUCT-beneficiary metering); it must not be a no-op. + #[test] + fn test_record_account_update_charges_one_kv() { + let mut tracker = KVUpdateTracker::new(MegaSpecId::MINI_REX, u64::MAX); + tracker.push_empty_frame(); + assert_eq!(tracker.tx_usage(), 0); + tracker.record_account_update(); + assert_eq!(tracker.tx_usage(), 1, "record_account_update must add exactly 1 KV update"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/limit.rs b/crates/mega-evm/tests/_pending/src/limit/limit.rs new file mode 100644 index 000000000..2b55341e1 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/limit.rs @@ -0,0 +1,98 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/limit.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/limit.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod metering_exemption_tests { + use super::*; + + /// Tiny per-dimension limits so a single recording trivially exceeds them. + fn tiny_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits { + tx_data_size_limit: 1, + tx_kv_updates_limit: 1, + tx_compute_gas_limit: 1, + tx_state_growth_limit: 1, + block_env_access_compute_gas_limit: u64::MAX, + oracle_access_compute_gas_limit: u64::MAX, + } + } + + #[test] + fn test_metering_enforced_when_not_exempt() { + // Default (non-exempt): halted once compute gas exceeds the (tiny) limit. The REX6 × + // system-origin gate that would stamp `Exempt` lives in `MegaContext::on_new_tx`; here we + // exercise the tracker directly. + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + assert!(!al.record_compute_gas(1_000_000), "non-exempt tx must report exceeded limit"); + assert!(al.check_limit().exceeded_limit()); + } + + #[test] + fn test_metering_bypassed_when_exempt() { + // When the system-tx exemption is stamped, `check_limit` short-circuits on the sticky + // `Exempt` state, covering the four dimensions *and* gas detention, so the same + // over-limit usage never halts. Usage is still recorded (only the halt decision is + // suppressed). + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + al.mark_exempt(); + assert!(al.record_compute_gas(1_000_000), "exempt tx must not report exceeded limit"); + assert!(!al.check_limit().exceeded_limit()); + assert!(al.check_limit().is_exempt(), "check_limit must surface the sticky Exempt state"); + assert!(al.get_usage().compute_gas >= 1_000_000, "usage is still accumulated while exempt"); + } + + #[test] + fn test_detained_compute_gas_does_not_halt_when_exempt() { + // Gas detention lowers the detained compute-gas limit; enforcement runs through the same + // `check_limit` chokepoint, so the exemption neutralizes detention too. + let mut al = + AdditionalLimit::new(MegaSpecId::REX6, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX6)); + al.mark_exempt(); + al.set_compute_gas_limit(1); // detain hard + assert!(al.record_compute_gas(10_000_000), "exempt tx must ignore gas detention"); + assert!(!al.check_limit().exceeded_limit()); + } + + #[test] + fn test_reset_clears_exempt() { + // The sticky `Exempt` state must not leak to the next transaction reusing the same tracker. + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + al.mark_exempt(); + assert!(al.has_exceeded_limit.is_exempt()); + al.reset(); + assert!(!al.has_exceeded_limit.is_exempt(), "reset must clear the sticky Exempt state"); + assert!( + al.has_exceeded_limit.within_limit(), + "reset must restore the WithinLimit baseline" + ); + assert!(!al.record_compute_gas(1_000_000), "after reset, metering is enforced again"); + } +} + +#[cfg(test)] +mod tests { + use revm::context::tx::TxEnvBuilder; + + use super::{super::LimitKind, *}; + + fn test_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits { + tx_data_size_limit: 100, + tx_kv_updates_limit: 1_000, + tx_compute_gas_limit: 1_000_000, + tx_state_growth_limit: 1_000, + block_env_access_compute_gas_limit: 1_000_000, + oracle_access_compute_gas_limit: 1_000_000, + } + } + + /// Returns the latched limit kind, or `None` when within limit. + fn latched_kind(limit: &AdditionalLimit) -> Option { + match limit.has_exceeded_limit { + LimitCheck::ExceedsLimit { kind, .. } => Some(kind), + LimitCheck::WithinLimit | LimitCheck::Exempt => None, + } + } + +} diff --git a/crates/mega-evm/tests/_pending/src/limit/mod.rs b/crates/mega-evm/tests/_pending/src/limit/mod.rs new file mode 100644 index 000000000..aeca2a5fb --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/mod.rs @@ -0,0 +1,54 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/mod.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/mod.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the predicate truth-table for the `Exempt` variant so a future change that flips one + /// predicate (e.g., reverting `exceeded_limit` to `!matches!(WithinLimit)`) is caught here + /// rather than silently re-enabling halts for exempt txs. + #[test] + fn test_limit_check_exempt_predicate_truth_table() { + let exempt = LimitCheck::Exempt; + assert!(!exempt.exceeded_limit()); + assert!(!exempt.within_limit()); + assert!(exempt.is_exempt()); + assert!(!exempt.is_frame_local()); + assert!(exempt.revert_data().is_empty()); + assert!(exempt.maybe_halt_reason().is_none()); + } + + /// `within_limit` must mirror the enum variant exactly, not return a constant. + #[test] + fn test_within_limit_reflects_variant() { + assert!(LimitCheck::WithinLimit.within_limit()); + let exceeded = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 150, + frame_local: false, + }; + assert!(!exceeded.within_limit()); + } + + /// Every `LimitKind` discriminant must survive an `as_u8` -> `from_u8` round-trip, + /// and unknown discriminants must map to `None`. + #[test] + fn test_limit_kind_u8_roundtrip() { + for kind in [ + LimitKind::DataSize, + LimitKind::KVUpdate, + LimitKind::ComputeGas, + LimitKind::StateGrowth, + ] { + assert_eq!( + LimitKind::from_u8(kind.as_u8()), + Some(kind), + "round-trip failed for {kind:?}" + ); + } + assert_eq!(LimitKind::from_u8(4), None); + } +} diff --git a/crates/mega-evm/tests/_pending/src/sandbox/error.rs b/crates/mega-evm/tests/_pending/src/sandbox/error.rs new file mode 100644 index 000000000..ac6df1027 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/sandbox/error.rs @@ -0,0 +1,50 @@ +//! Unit tests extracted from `crates/mega-evm/src/sandbox/error.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/error.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// `InternalError` and `InvalidTransaction` carry no payload on the wire, so a + /// roundtrip MUST produce the same variant. Pinned because these selectors are the + /// off-chain error ABI (RPC, traces, relayer decoders); a divergence between + /// `encode_error_result` and `decode_error_result` would silently break those decoders. + #[test] + fn test_internal_error_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::InternalError); + // Selector-only: the encoded form is exactly the 4-byte Solidity selector. + assert_eq!(encoded.len(), 4, "InternalError must be selector-only"); + assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::InternalError))); + } + + #[test] + fn test_invalid_transaction_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::InvalidTransaction); + assert_eq!(encoded.len(), 4, "InvalidTransaction must be selector-only"); + assert!(matches!( + decode_error_result(&encoded), + Some(KeylessDeployError::InvalidTransaction) + )); + } + + /// `InitCodeTooLarge { size, max }` is an externally visible ABI selector. Pinning the + /// round-trip catches any drift between the Solidity error definition and the Rust + /// encode/decode (e.g. forgotten arm in `encode_error_result` or `decode_error_result`, + /// or accidental field reordering). + #[test] + fn test_init_code_too_large_roundtrip_preserves_size_and_max() { + let original = KeylessDeployError::InitCodeTooLarge { size: 600_000, max: 548_864 }; + let encoded = encode_error_result(original.clone()); + let decoded = decode_error_result(&encoded).expect("must decode"); + assert_eq!(decoded, original); + } + + /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. + #[test] + fn test_signer_has_code_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::SignerHasCode); + assert_eq!(encoded.len(), 4, "SignerHasCode must be selector-only"); + assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::SignerHasCode))); + } +} diff --git a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs new file mode 100644 index 000000000..3ead4fb4d --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs @@ -0,0 +1,159 @@ +//! Unit tests extracted from `crates/mega-evm/src/sandbox/execution.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/execution.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use revm::context::result::Output; + + /// Test error type that lets us drive `process_sandbox_transact_result`'s + /// `Err` arms (which map to `SandboxOutcome::Rejected`) directly without + /// standing up a full sandbox EVM. The two arms differ only by + /// `IsTxError::is_tx_error()`, so a single struct with a configurable flag + /// covers both selector mappings. + struct FakeTxErr { + is_tx: bool, + msg: &'static str, + } + + impl core::fmt::Display for FakeTxErr { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.msg) + } + } + + impl IsTxError for FakeTxErr { + fn is_tx_error(&self) -> bool { + self.is_tx + } + } + + /// `validate_signer_code` MUST be a no-op when `cfg.disable_eip3607 = true`, even + /// when the provided `AccountInfo` has bytecode that would otherwise trip the + /// caller-with-code check. Mirrors the canonical revm `validate_account_nonce_and_code` + /// semantics and pins the early-return contract. + #[test] + fn test_validate_signer_code_disable_eip3607_short_circuits() { + use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use revm::{ + bytecode::Bytecode, + primitives::{keccak256, Bytes as PrimitivesBytes}, + }; + + let code_bytes = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); + let code_hash = keccak256(&code_bytes); + let signer_info = AccountInfo { + nonce: 0, + balance: U256::ZERO, + code_hash, + code: Some(Bytecode::new_raw(code_bytes)), + }; + + let mut ctx = + MegaContext::<_, EmptyExternalEnv>::new(MemoryDatabase::default(), MegaSpecId::REX5); + ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); + + let out = validate_signer_code(&ctx, &signer_info); + assert!( + matches!(out, Ok(())), + "disable_eip3607 must short-circuit before the code inspection; got {out:?}", + ); + } + + /// `charge_caller_materialization_pre_sandbox` MUST surface a SALT/dynamic-gas failure + /// as `Err(KeylessDeployError::InternalError)` without writing to `ctx.error()`. + /// + /// The contract is load-bearing: op-revm's `Handler::execution_result` drains + /// `ctx.error()` and converts any non-empty `ContextError` into an EVM-level + /// `Err(Custom(...))`. Routing a SALT failure through the + /// `HostExt::new_account_storage_gas` helper — which stashes the error into + /// `ctx.error()` — would promote an interceptor-level failure into a whole-transaction + /// execution error and break the `InternalError()` selector contract. The + /// pre-sandbox charge path must therefore call `DynamicGasCost::new_account_gas` + /// directly and keep the error local. + #[test] + fn test_charge_caller_materialization_salt_failure_returns_internal_error_without_ctx_pollution( + ) { + use crate::{test_utils::MemoryDatabase, BucketId, OracleEnv, SaltEnv}; + use alloy_primitives::{address, B256}; + use core::fmt::{self, Display, Formatter}; + + // Minimal `SaltEnv` whose `get_bucket_capacity` always fails. This drives + // `DynamicGasCost::new_account_gas` (called from + // `charge_caller_materialization_pre_sandbox`) to return `Err`, exercising the + // failure-handling path under test. + #[derive(Debug, Clone, Copy)] + struct AlwaysFailSalt; + + #[derive(Debug, Clone)] + struct InjectedSaltError; + impl Display for InjectedSaltError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str("injected SALT failure") + } + } + + impl SaltEnv for AlwaysFailSalt { + type Error = InjectedSaltError; + fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { + Err(InjectedSaltError) + } + fn bucket_id_for_account(_account: Address) -> BucketId { + 0 + } + fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { + 0 + } + } + + #[derive(Debug, Clone, Copy)] + struct NoopOracle; + impl OracleEnv for NoopOracle { + fn get_oracle_storage(&self, _slot: U256) -> Option { + None + } + fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} + } + + let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); + let db = MemoryDatabase::default(); + let envs: crate::ExternalEnvs<(AlwaysFailSalt, NoopOracle)> = + crate::ExternalEnvs { salt_env: AlwaysFailSalt, oracle_env: NoopOracle }; + let mut ctx = MegaContext::new(db, MegaSpecId::REX5).with_external_envs(envs); + + let mut gas = Gas::new(10_000_000); + let return_memory_offset = 0..0; + + // Signer is unmaterialized (default `AccountInfo` is `is_empty()` == true) + // → the materialization branch fires. + let signer_info = AccountInfo::default(); + let out = charge_caller_materialization_pre_sandbox( + &ctx, + &mut gas, + signer, + &signer_info, + &return_memory_offset, + ); + assert!( + matches!(out, Err(KeylessDeployError::InternalError)), + "SALT failure must surface as InternalError, got {out:?}", + ); + + // The whole point of the fix: ctx.error() must NOT have been polluted, so the outer + // transaction's `execution_result` doesn't drain it into `Err(Custom)`. + let ctx_error = core::mem::replace(ctx.error(), Ok(())); + assert!( + matches!(ctx_error, Ok(())), + "ctx.error() must remain Ok after a SALT failure in the pre-sandbox charge; \ + got {ctx_error:?}", + ); + + // record_deposit_caller_creation must NOT have fired either. + assert_eq!( + ctx.additional_limit.borrow().get_usage().state_growth, + 0, + "deposit-caller state-growth must not be recorded when the storage gas computation fails", + ); + } +} diff --git a/crates/mega-evm/src/sandbox/tx.rs b/crates/mega-evm/tests/_pending/src/sandbox/tx.rs similarity index 75% rename from crates/mega-evm/src/sandbox/tx.rs rename to crates/mega-evm/tests/_pending/src/sandbox/tx.rs index ed9cd3adc..ea2cbae97 100644 --- a/crates/mega-evm/src/sandbox/tx.rs +++ b/crates/mega-evm/tests/_pending/src/sandbox/tx.rs @@ -1,104 +1,6 @@ -//! Keyless deploy transaction types and functions. -//! -//! This module provides functions for decoding and validating pre-EIP-155 legacy transactions -//! used in Nick's Method for deterministic contract deployment. -//! -//! # Two-Phase Validation -//! -//! Transaction validation occurs in two distinct phases: -//! -//! ## Phase 1: RLP Decoding ([`decode_keyless_tx`]) -//! -//! Structural validation of the transaction format: -//! - Valid RLP encoding of a legacy transaction -//! - No trailing bytes after the RLP payload (Rex5+; rejected as `MalformedEncoding`) -//! - EIP-2718 typed envelopes (0x01, 0x02, etc.) rejected as `MalformedEncoding` -//! - `to` field must be empty (contract creation) -//! - `v` must be 27 or 28 (pre-EIP-155, no chain ID) -//! -//! ## Phase 2: Signature Recovery ([`recover_signer`]) -//! -//! Cryptographic validation of the signature: -//! - Signature components (r, s) must be valid secp256k1 curve points -//! - Invalid/corrupted signatures fail with `InvalidSignature` -//! - Recovery uses alloy's ECDSA implementation -//! -//! # Security Notes -//! -//! - **Signature modification changes identity**: Altering r or s values produces a different -//! recovered signer address, not an invalid signature. -//! - **Empty initcode is allowed**: Transactions with empty `data` pass decoding but result in -//! `EmptyCodeDeployed` during execution. - -use alloy_consensus::{transaction::RlpEcdsaDecodableTx, Signed, TxLegacy}; -use alloy_primitives::Address; - -use crate::MegaSpecId; - -use super::error::KeylessDeployError; - -/// Decodes a pre-EIP-155 legacy transaction from RLP bytes. -/// -/// The expected RLP structure is: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` -/// -/// # Validation -/// - The RLP encoding must be valid -/// - Rex5+: the input must not contain trailing bytes after the RLP transaction -/// - The `to` field must be empty (contract creation) -/// - The `v` value must be 27 or 28 (pre-EIP-155) -/// -/// # Returns -/// - `Ok(Signed)` if the transaction is valid -/// - `Err(KeylessDeployError::MalformedEncoding)` on invalid RLP or trailing bytes (REX5+) -/// - `Err(KeylessDeployError::NotContractCreation)` if `to` is not empty -/// - `Err(KeylessDeployError::NotPreEIP155)` if a chain id is present -pub fn decode_keyless_tx( - rlp_bytes: &[u8], - spec: MegaSpecId, -) -> Result, KeylessDeployError> { - let mut buf = rlp_bytes; - let signed = - TxLegacy::rlp_decode_signed(&mut buf).map_err(|_| KeylessDeployError::MalformedEncoding)?; - - // Rex5+: Reject trailing bytes. The raw input is reused as `enveloped_tx` for L1 data-fee - // accounting, so any bytes past the signed RLP payload would otherwise be silently - // charged without being part of the signed transaction. - // Pre-Rex5 behavior (accepted trailing bytes) is preserved for replay compatibility. - if spec.is_enabled(MegaSpecId::REX5) && !buf.is_empty() { - return Err(KeylessDeployError::MalformedEncoding); - } - - if !signed.tx().to.is_create() { - return Err(KeylessDeployError::NotContractCreation); - } - if signed.tx().chain_id.is_some() { - return Err(KeylessDeployError::NotPreEIP155); - } - Ok(signed) -} - -/// Recovers the signer address from a keyless deployment transaction. -/// -/// Uses alloy's built-in signature recovery to derive the signer address -/// from the signed transaction. -/// -/// # Returns -/// - `Ok(Address)` - The recovered signer address -/// - `Err(KeylessDeployError::InvalidSignature)` - If signature recovery fails -pub fn recover_signer(signed_tx: &Signed) -> Result { - signed_tx.recover_signer().map_err(|_| KeylessDeployError::InvalidSignature) -} - -/// Calculates the deployment address for a contract created by the given signer. -/// -/// For Nick's Method, the nonce is always 0, so the deployment address is: -/// `keccak256(rlp([signer, 0]))[12:]` -/// -/// This is equivalent to `signer.create(0)` in alloy. -#[inline] -pub fn calculate_keyless_deploy_address(signer: Address) -> Address { - signer.create(0) -} +//! Unit tests extracted from `crates/mega-evm/src/sandbox/tx.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/tx.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. #[allow(missing_docs, unused)] #[cfg(any(test, feature = "test-utils"))] @@ -283,15 +185,4 @@ pub mod tests { assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } - #[test] - fn test_decode_accepts_trailing_bytes_pre_rex5() { - // Pre-Rex5 (Rex2–Rex4): trailing bytes were silently accepted for replay compatibility. - let mut with_trailing = CREATE2_FACTORY_TX.to_vec(); - with_trailing.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX4); - assert!(result.is_ok(), "pre-Rex5 should accept trailing bytes"); - - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX2); - assert!(result.is_ok(), "pre-Rex5 should accept trailing bytes"); - } } diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/tests/_pending/src/system/control.rs similarity index 60% rename from crates/mega-evm/src/system/control.rs rename to crates/mega-evm/tests/_pending/src/system/control.rs index 7ac6bbf0b..7613fcb7e 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/tests/_pending/src/system/control.rs @@ -1,74 +1,6 @@ -//! The access control system contract for the `MegaETH` EVM. -//! -//! This contract provides functions to control access restrictions during EVM execution. -//! The first function, `disableVolatileDataAccess()`, prevents inner calls from accessing -//! volatile data (block env fields, beneficiary balance, oracle). - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use alloy_sol_types::SolError; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the access control system contract. -pub const ACCESS_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000004"); - -/// The code of the access control contract (version 1.0.0). -pub use mega_system_contracts::access_control::V1_0_0_CODE as ACCESS_CONTROL_CODE; - -/// The code hash of the access control contract (version 1.0.0). -pub use mega_system_contracts::access_control::V1_0_0_CODE_HASH as ACCESS_CONTROL_CODE_HASH; - -pub use mega_system_contracts::access_control::IMegaAccessControl; -pub use IMegaAccessControl::VolatileDataAccessType; - -/// Selector for `VolatileDataAccessDisabled(uint8)` custom error. -/// Selector: `keccak256("VolatileDataAccessDisabled(uint8)")[0..4]`. -pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; - -/// Builds the full ABI-encoded revert data for `VolatileDataAccessDisabled(uint8 accessType)`. -pub fn volatile_data_access_disabled_revert_data( - access_type: VolatileDataAccessType, -) -> alloy_primitives::Bytes { - alloy_primitives::Bytes::from( - ::abi_encode( - &IMegaAccessControl::VolatileDataAccessDisabled { accessType: access_type }, - ), - ) -} - -/// ABI-encoded revert data for `DisabledByParent()` custom error. -pub const DISABLED_BY_PARENT_REVERT_DATA: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; - -/// Ensures the access control contract is deployed in the designated address and returns the -/// state changes. -/// The caller is responsible for committing the returned `EvmState` changes to the database. -pub fn transact_deploy_access_control_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - access_control_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the access-control contract active under -/// `spec`, or `None` if `REX4` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn access_control_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX4).then(|| { - SystemContractSpec::new( - ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE, - ACCESS_CONTROL_CODE_HASH, - ) - }) -} +//! Unit tests extracted from `crates/mega-evm/src/system/control.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/control.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { @@ -117,17 +49,6 @@ mod tests { assert_eq!(decoded.accessType, VolatileDataAccessType::Oracle); } - #[test] - fn test_deploy_access_control_contract_requires_rex4() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = - transact_deploy_access_control_contract(MegaHardforkConfig::default(), 0, &mut state) - .unwrap(); - assert_eq!(result, None); - } - #[test] fn test_deploy_access_control_contract_on_fresh_db() { let mut db = InMemoryDB::default(); diff --git a/crates/mega-evm/tests/_pending/src/system/deploy.rs b/crates/mega-evm/tests/_pending/src/system/deploy.rs new file mode 100644 index 000000000..5238b5246 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/deploy.rs @@ -0,0 +1,150 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/deploy.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/deploy.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + MegaHardfork, MegaHardforkConfig, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX2, + ORACLE_CONTRACT_CODE_HASH_REX5, + }; + use alloy_hardforks::ForkCondition; + use alloy_primitives::address; + use revm::{database::InMemoryDB, state::AccountInfo, Database as _, DatabaseCommit}; + + fn addrs(specs: &[SystemContractSpec]) -> Vec
{ + specs.iter().map(|s| s.address).collect() + } + + const SEEDED_ADDR: Address = address!("0x6342000000000000000000000000000000000099"); + const SEED_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); + const UNRELATED_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); + + /// Builds a spec whose code hash differs from any pre-existing account, so + /// `transact_deploy` takes the bytecode-upgrade path rather than the + /// idempotent early return. + fn seeded_spec(force_create_on_upgrade: bool) -> SystemContractSpec { + let code = Bytes::from_static(&[0x60, 0x00]); + let code_hash = keccak256(&code); + SystemContractSpec::new(SEEDED_ADDR, code, code_hash) + .with_seed(Vec::from([(SEED_SLOT, U256::from(42))])) + .with_force_create_on_upgrade(force_create_on_upgrade) + } + + /// An in-place upgrade that does NOT recreate the account must not write seed + /// slots: doing so would mix genesis storage into preserved live storage and + /// record a wrong `original_value`. Guards the `force_create_on_upgrade = + /// false` + non-empty `seed` configuration that no current contract uses. + #[test] + fn test_seed_skipped_on_storage_preserving_upgrade() { + let mut db = InMemoryDB::default(); + // Pre-existing account with different bytecode (so the upgrade path runs) + // and a live value at the slot the spec would otherwise seed. + let existing_code = Bytes::from_static(&[0xfe]); + db.insert_account_info( + SEEDED_ADDR, + AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: keccak256(&existing_code), + code: Some(Bytecode::new_raw(existing_code)), + }, + ); + db.insert_account_storage(SEEDED_ADDR, SEED_SLOT, U256::from(99)).unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_touched()); + assert!(!account.is_created(), "storage-preserving upgrade must not recreate"); + assert!( + !account.storage.contains_key(&SEED_SLOT), + "seed must not be written when storage is preserved" + ); + + // Committing the upgrade must leave the pre-existing slot at its old value. + state.commit(result); + assert_eq!( + state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), + U256::from(99), + "preserved storage must keep its pre-upgrade value after commit" + ); + } + + /// The same spec with `force_create_on_upgrade = true` recreates the account + /// and therefore does seed — the path the `SequencerRegistry` relies on. + #[test] + fn test_seed_written_on_force_created_upgrade() { + let mut db = InMemoryDB::default(); + let existing_code = Bytes::from_static(&[0xfe]); + db.insert_account_info( + SEEDED_ADDR, + AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: keccak256(&existing_code), + code: Some(Bytecode::new_raw(existing_code)), + }, + ); + // An unrelated live slot that recreation must clear. + db.insert_account_storage(SEEDED_ADDR, UNRELATED_SLOT, U256::from(99)).unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(true)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_created(), "force_create_on_upgrade must recreate"); + let slot = account.storage.get(&SEED_SLOT).expect("seed slot must be written"); + assert_eq!(slot.present_value, U256::from(42)); + assert_eq!(slot.original_value, U256::ZERO); + + // Recreation clears prior storage: after commit the seed slot holds its + // value and the unrelated pre-existing slot reads back as zero. + state.commit(result); + assert_eq!(state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), U256::from(42)); + assert_eq!( + state.storage(SEEDED_ADDR, UNRELATED_SLOT).unwrap(), + U256::ZERO, + "recreation must clear unrelated pre-existing storage" + ); + } + + /// A fresh deploy seeds regardless of `force_create_on_upgrade`. + #[test] + fn test_seed_written_on_fresh_deploy() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_created(), "fresh deploy creates the account"); + assert_eq!( + account.storage.get(&SEED_SLOT).expect("seed slot must be written").present_value, + U256::from(42) + ); + } + + #[test] + fn test_registry_oracle_version_by_spec() { + // Only MiniRex active: Oracle v1.0.0, force-created on upgrade (pre-Rex5), + // and just Oracle + high-precision Oracle. + let mini = + MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); + let mini = flat_system_contract_specs(&mini, 0); + assert_eq!(mini.len(), 2); + assert_eq!(mini[0].code_hash, ORACLE_CONTRACT_CODE_HASH); + assert!(mini[0].force_create_on_upgrade); + + // Rex2 active but not Rex5: Oracle v1.1.0, still force-created on upgrade. + let rex2 = MegaHardforkConfig::default() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) + .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); + let rex2 = flat_system_contract_specs(&rex2, 0); + assert_eq!(rex2[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); + assert!(rex2[0].force_create_on_upgrade); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/intercept.rs b/crates/mega-evm/tests/_pending/src/system/intercept.rs new file mode 100644 index 000000000..65742e3a8 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/intercept.rs @@ -0,0 +1,114 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/intercept.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/intercept.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use alloy_primitives::{Bytes, U256}; + use alloy_sol_types::SolCall; + use revm::{ + bytecode::opcode::{CALLCODE, MSTORE, RETURN}, + context::tx::TxEnvBuilder, + }; + + use crate::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + }; + + const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = + IMegaLimitControl::remainingComputeGasCall::SELECTOR; + + /// Pins the `abi_decode`-accepts-trailing-junk behaviour of `alloy-sol-types`'s + /// `decode_sequence::<()>` for parameterless system-contract methods. The + /// interceptor dispatch's selector-only admission relies on this: if a future + /// alloy upgrade rejects trailing bytes, historical replays would diverge from + /// the original `abi_decode` admission and break replay determinism on stable + /// specs. + #[test] + fn test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls() { + let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; + let exact = selector; + let with_junk: Vec = selector.iter().copied().chain(core::iter::once(0xff)).collect(); + let with_pad: Vec = selector.iter().copied().chain([0u8; 32]).collect(); + + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&exact).is_ok(), + "exact 4-byte selector must decode", + ); + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_junk).is_ok(), + "current alloy-sol-types accepts selector+1B junk for empty-tuple decode; if this \ + fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ + selector probe before landing", + ); + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_pad).is_ok(), + "current alloy-sol-types accepts selector+32B padding for empty-tuple decode; if \ + this fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ + selector probe before landing", + ); + } + + /// Unit test for the explicit call-scheme guard in `frame_init`. + /// + /// A `CALLCODE` to a system contract address with a recognized selector must NOT be + /// intercepted. + /// The scheme guard rejects it before any interceptor sees the call. + /// The call falls through to on-chain bytecode, which reverts with `NotIntercepted()`, + /// leaving the `CALLCODE` success flag as 0. + #[test] + fn test_callcode_scheme_guard_skips_interception() { + let code = BytecodeBuilder::default() + .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) + // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(4_u64) // argsSize (selector length) + .push_number(0_u64) // argsOffset (selector at memory[0]) + .push_number(0_u64) // value + .push_address(LIMIT_CONTROL_ADDRESS) + .push_number(100_000_u64) // gas + .append(CALLCODE) // success flag (0=fail, 1=success) on stack + .push_number(0_u64) + .append(MSTORE) + .push_number(32_u64) + .push_number(0_u64) + .append(RETURN) + .build(); + + let caller = alloy_primitives::address!("0000000000000000000000000000000000300000"); + let contract = alloy_primitives::address!("0000000000000000000000000000000000300001"); + + let mut db = MemoryDatabase::default() + .account_balance(caller, U256::from(1_000_000)) + .account_code(contract, code) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); + + let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = MegaEvm::new(context); + let tx = TxEnvBuilder::default() + .caller(caller) + .call(contract) + .gas_limit(100_000_000) + .build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + + let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); + assert!(result.result.is_success(), "outer tx should succeed"); + + let output = result.result.output().expect("should have output"); + let success_flag = U256::from_be_slice(output); + assert_eq!( + success_flag, + U256::ZERO, + "CALLCODE to system contract must not be intercepted — scheme guard must reject it" + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs new file mode 100644 index 000000000..fd6f4b55f --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs @@ -0,0 +1,64 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/keyless_deploy.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/keyless_deploy.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::MegaHardforkConfig; + use revm::{ + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + #[test] + fn test_deploy_keyless_deploy_contract_on_fresh_db() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); + assert!(account.is_touched()); + assert!(account.is_created(), "fresh deploy must mark account as created"); + assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); + } + + /// Covers the `account_existed = true` branch: an account already exists with wrong code, + /// so the deploy updates the code without marking the account as created. + #[test] + fn test_deploy_keyless_deploy_contract_existing_account_not_marked_created() { + let wrong_code = alloy_primitives::bytes!("0x6000"); + let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + KEYLESS_DEPLOY_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); + assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); + assert!(account.is_touched()); + assert!( + !account.is_created(), + "in-place bytecode update of an existing account must not mark it as created" + ); + } + +} diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/tests/_pending/src/system/limit_control.rs similarity index 63% rename from crates/mega-evm/src/system/limit_control.rs rename to crates/mega-evm/tests/_pending/src/system/limit_control.rs index 43c387970..1a9632e0b 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/tests/_pending/src/system/limit_control.rs @@ -1,49 +1,6 @@ -//! The `MegaLimitControl` system contract for the `MegaETH` EVM. -//! -//! This contract currently provides a read-only query to return remaining compute gas -//! of the current call. -//! The runtime result is produced by EVM interception, not by executing on-chain bytecode. - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the `MegaLimitControl` system contract. -pub const LIMIT_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000005"); - -/// The code of the `MegaLimitControl` contract (version 1.0.0). -pub use mega_system_contracts::limit_control::V1_0_0_CODE as LIMIT_CONTROL_CODE; - -/// The code hash of the `MegaLimitControl` contract (version 1.0.0). -pub use mega_system_contracts::limit_control::V1_0_0_CODE_HASH as LIMIT_CONTROL_CODE_HASH; - -pub use mega_system_contracts::limit_control::IMegaLimitControl; - -/// Ensures the `MegaLimitControl` contract is deployed in the designated address and returns -/// the state changes. -/// The caller is responsible for committing the returned `EvmState` changes to the database. -pub fn transact_deploy_limit_control_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - limit_control_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the `MegaLimitControl` contract active -/// under `spec`, or `None` if `REX4` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn limit_control_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX4).then(|| { - SystemContractSpec::new(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, LIMIT_CONTROL_CODE_HASH) - }) -} +//! Unit tests extracted from `crates/mega-evm/src/system/limit_control.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/limit_control.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { @@ -63,17 +20,6 @@ mod tests { assert_eq!(computed_hash, LIMIT_CONTROL_CODE_HASH); } - #[test] - fn test_deploy_limit_control_contract_requires_rex4() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = - transact_deploy_limit_control_contract(MegaHardforkConfig::default(), 0, &mut state) - .unwrap(); - assert_eq!(result, None); - } - #[test] fn test_deploy_limit_control_contract_on_fresh_db() { let mut db = InMemoryDB::default(); diff --git a/crates/mega-evm/tests/_pending/src/system/oracle.rs b/crates/mega-evm/tests/_pending/src/system/oracle.rs new file mode 100644 index 000000000..dced446b8 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/oracle.rs @@ -0,0 +1,257 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/oracle.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/oracle.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use crate::MegaHardforkConfig; + + use super::*; + use alloy_primitives::keccak256; + use revm::{ + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + #[test] + fn test_deploy_oracle_contract_on_fresh_db() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex5, so we expect Rex5 (v2.0.0) bytecode + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the oracle contract + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned + assert_eq!(result.len(), 1, "Should have state changes for one account"); + assert!( + result.contains_key(&ORACLE_CONTRACT_ADDRESS), + "State changes should contain oracle contract address" + ); + + // Verify the account in the state changes + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert!(account.is_touched(), "Account should be marked as touched"); + assert!(account.is_created(), "Account should be marked as created"); + + // Verify the account info (Rex5 = v2.0.0 bytecode) + let info = &account.info; + assert_eq!( + info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should match the v2.0.0 value" + ); + assert!(info.code.is_some(), "Code should be set"); + + let code = info.code.as_ref().unwrap(); + assert_eq!( + code.original_bytes(), + ORACLE_CONTRACT_CODE_REX5, + "Code bytes should match the v2.0.0 value" + ); + } + + #[test] + fn test_deploy_oracle_contract_idempotent() { + // Create a database with the oracle contract already deployed correctly (Rex5 = v2.0.0) + let mut db = InMemoryDB::default(); + db.insert_account_info( + ORACLE_CONTRACT_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: ORACLE_CONTRACT_CODE_HASH_REX5, + code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX5)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex5 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy should return state with the account marked as read (no update needed) + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + assert_eq!( + result.len(), + 1, + "Deployment should return state with account marked as read when contract is already correctly deployed" + ); + + // Verify the account is in the result + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should match v2.0.0 bytecode" + ); + } + + #[test] + fn test_deploy_oracle_contract_with_wrong_code_hash() { + // Create a database with the oracle address already having different code + let mut db = InMemoryDB::default(); + + // Insert an account with wrong code hash at the oracle address + let wrong_code = bytes!("0x6000"); + let wrong_code_hash = keccak256(&wrong_code); + + db.insert_account_info( + ORACLE_CONTRACT_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex2 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy should update the contract with correct code (Rex5 = v2.0.0 bytecode) + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned (contract was updated) + assert_eq!(result.len(), 1, "Should have state changes to update the contract"); + + // Verify the updated account has the correct code hash + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should be updated to v2.0.0 bytecode" + ); + } + + #[test] + fn test_deploy_oracle_contract_marks_account_as_touched() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the oracle contract + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Get the account from result + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist in result"); + + // Verify the account is marked as touched (required for state changes to be committed) + assert!( + account.is_touched(), + "Deployed account must be marked as touched for state changes to take effect" + ); + assert!(account.is_created(), "Account should be marked as created"); + } + + #[test] + fn test_deploy_oracle_contract_rex5() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + // Activate all including Rex5 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Should deploy v2.0.0 bytecode on Rex5" + ); + } + + #[test] + fn test_high_precision_timestamp_oracle_deployment() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the high precision timestamp oracle contract + let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned + assert_eq!(result.len(), 1, "Should have state changes for one account"); + assert!( + result.contains_key(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), + "State changes should contain high precision timestamp oracle address" + ); + + // Verify the account in the state changes + let account = + result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); + assert!(account.is_touched(), "Account should be marked as touched"); + assert!(account.is_created(), "Account should be marked as created"); + + // Verify the account info + let info = &account.info; + assert_eq!( + info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + "Code hash should match the expected value" + ); + assert!(info.code.is_some(), "Code should be set"); + + // Verify code matches + let code = info.code.as_ref().unwrap(); + assert_eq!( + code.original_bytes(), + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, + "Code bytes should match the expected value" + ); + + // Verify code hash matches computed hash + let computed_hash = keccak256(&HIGH_PRECISION_TIMESTAMP_ORACLE_CODE); + assert_eq!( + computed_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + "Code hash constant should match computed hash" + ); + } + + /// Covers the `account_existed = true` branch in + /// `transact_deploy_high_precision_timestamp_oracle`: when the account already exists with + /// wrong code, the deploy updates the code without marking the account as created. + #[test] + fn test_high_precision_timestamp_oracle_existing_account_not_marked_created() { + let wrong_code = alloy_primitives::bytes!("0x6000"); + let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = + result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); + assert_eq!(account.info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH); + assert!(account.is_touched()); + assert!( + !account.is_created(), + "existing account must not be marked as created on code update" + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs new file mode 100644 index 000000000..8f3dec40a --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -0,0 +1,778 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/sequencer_registry.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/sequencer_registry.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, keccak256, B256}; + use mega_system_contracts::sequencer_registry::storage_slots::PENDING_ADMIN; + use revm::{ + context::BlockEnv, + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + use crate::{MegaHardforkConfig, MegaSpecId}; + + const TEST_SEQUENCER: Address = address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); + const TEST_ADMIN: Address = address!("0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); + /// A non-system test address, used as a stand-in for a `_currentSystemAddress` that has + /// already been rotated away from the genesis `MEGA_SYSTEM_ADDRESS`. Distinct from + /// genesis so tests can tell the two apart. + const TEST_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); + + const TEST_MIN_ROTATION_DELAY: u64 = 100; + + fn test_config() -> SequencerRegistryConfig { + SequencerRegistryConfig { + rex5_initial_sequencer: TEST_SEQUENCER, + rex5_initial_admin: TEST_ADMIN, + } + } + + fn test_rex6_config() -> SequencerRegistryRex6Config { + SequencerRegistryRex6Config { rex6_min_rotation_delay: TEST_MIN_ROTATION_DELAY } + } + + /// A chain running Rex5: the pre-upgrade world where the registry runs v1.0.0. + fn rex5_hardforks() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX5) + .with_params(test_config()) + } + + /// All hardforks including Rex6, with both registry param sets attached. + fn rex6_hardforks() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(test_config()) + .with_params(test_rex6_config()) + } + + /// Verifies that Rust slot constants match the Solidity storage layout. + /// These values come from `forge inspect SequencerRegistry storage-layout`. + /// If the Solidity field order changes, this test MUST be updated. + #[test] + fn test_slot_constants_match_solidity_layout() { + assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::from(0), "_currentSystemAddress = slot 0"); + assert_eq!(CURRENT_SEQUENCER, U256::from(1), "_currentSequencer = slot 1"); + assert_eq!(ADMIN, U256::from(2), "_admin = slot 2"); + assert_eq!(PENDING_ADMIN, U256::from(3), "_pendingAdmin = slot 3"); + assert_eq!(INITIAL_SYSTEM_ADDRESS, U256::from(4), "_initialSystemAddress = slot 4"); + assert_eq!(INITIAL_SEQUENCER, U256::from(5), "_initialSequencer = slot 5"); + assert_eq!(INITIAL_FROM_BLOCK, U256::from(6), "_initialFromBlock = slot 6"); + assert_eq!(PENDING_SYSTEM_ADDRESS, U256::from(7), "_pendingSystemAddress = slot 7"); + assert_eq!( + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(8), + "_systemAddressActivationBlock = slot 8" + ); + assert_eq!(PENDING_SEQUENCER, U256::from(9), "_pendingSequencer = slot 9"); + assert_eq!( + SEQUENCER_ACTIVATION_BLOCK, + U256::from(10), + "_sequencerActivationBlock = slot 10" + ); + // Slots 11 (_systemAddressHistory) and 12 (_sequencerHistory) are dynamic arrays. + assert_eq!(MIN_ROTATION_DELAY, U256::from(13), "_minRotationDelay = slot 13 (v2.0.0+)"); + } + + #[test] + fn test_validate_rejects_zero_rex5_initial_sequencer() { + let mut config = test_config(); + config.rex5_initial_sequencer = Address::ZERO; + let err = config.validate().expect_err("zero rex5_initial_sequencer must be rejected"); + assert!( + err.message.contains("rex5_initial_sequencer must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_validate_rejects_zero_rex5_initial_admin() { + let mut config = test_config(); + config.rex5_initial_admin = Address::ZERO; + let err = config.validate().expect_err("zero rex5_initial_admin must be rejected"); + assert!( + err.message.contains("rex5_initial_admin must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_validate_rejects_zero_min_rotation_delay() { + let config = SequencerRegistryRex6Config { rex6_min_rotation_delay: 0 }; + let err = config.validate().expect_err("zero rex6_min_rotation_delay must be rejected"); + assert!( + err.message.contains("rex6_min_rotation_delay must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_deploy_fresh_at_rex6_seeds_v2_with_min_rotation_delay() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 1000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(account.is_created()); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); + assert_eq!( + account.storage.len(), + 7, + "fresh Rex6 deploy writes the 6 bootstrap slots plus _minRotationDelay" + ); + assert_eq!( + account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), + U256::from(TEST_MIN_ROTATION_DELAY), + ); + assert_eq!( + account.storage.get(&ADMIN).unwrap().present_value(), + U256::from_be_bytes(TEST_ADMIN.into_word().0), + ); + assert_eq!( + account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), + U256::from(1000), + ); + } + + #[test] + fn test_deploy_rex6_is_idempotent_when_v2_present() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 2000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(!account.is_created(), "idempotent deploy should not re-create"); + assert!(!account.is_touched(), "idempotent deploy should not touch the account"); + assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); + } + + #[test] + fn test_deploy_rex6_missing_config_errors() { + // Rex6 active but only the Rex5 params attached: deploy must fail fast instead of + // installing a v2.0.0 registry with an unseeded _minRotationDelay. + let hardforks = MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(test_config()); + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let err = + transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) + .expect_err("missing Rex6 params must fail closed"); + assert!( + err.to_string().contains("SequencerRegistryRex6Config not configured"), + "unexpected message: {err}" + ); + } + + #[test] + fn test_deploy_rex6_on_top_of_eoa_with_balance() { + let mut db = InMemoryDB::default(); + // Simulate an EOA that received ETH before the registry was ever deployed. Even at + // Rex6 this is a fresh bootstrap, not a storage-preserving upgrade: the full seed + // (including _minRotationDelay) must be written. + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 1000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(account.is_created()); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); + assert_eq!(account.info.balance, U256::from(1_000_000)); + assert_eq!(account.storage.len(), 7); + assert_eq!( + account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), + U256::from(TEST_MIN_ROTATION_DELAY), + ); + } + + #[test] + fn test_deploy_rex6_wrong_existing_code_hash_errors() { + let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: wrong_code.hash_slow(), + code: Some(wrong_code), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let err = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 2000, + &mut state, + &test_config(), + ) + .expect_err("wrong code hash must fail closed"); + + let msg = err.to_string(); + assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); + assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); + } + + #[test] + fn test_resolve_rex6_expects_v2_code_hash() { + // A V2 registry resolves normally at REX6. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (addr, witness) = + resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state).unwrap(); + assert_eq!(addr, TEST_SYSTEM_ADDRESS); + assert!(witness.is_some()); + } + + #[test] + fn test_resolve_rex6_rejects_v1_code_hash() { + // At REX6 the pre-block deploy has already upgraded the bytecode, so a V1 code hash at + // resolve time is a broken pipeline and must fail closed. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let err = resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state) + .expect_err("V1 code hash at REX6 must fail closed"); + assert!(err.to_string().contains("code hash mismatch")); + } + + #[test] + fn test_resolve_rex5_returns_stored_system_address_with_witness() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (addr, witness) = + resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state).unwrap(); + assert_eq!(addr, TEST_SYSTEM_ADDRESS); + + // Witness must capture the registry account and the CURRENT_SYSTEM_ADDRESS slot. + let witness = witness.expect("post-deploy resolve must produce witness"); + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("registry account in witness"); + assert_eq!(acc.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert!( + acc.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), + "witness must include CURRENT_SYSTEM_ADDRESS slot" + ); + assert_eq!(acc.storage.len(), 1, "witness should contain exactly one slot"); + let slot = acc.storage.get(&CURRENT_SYSTEM_ADDRESS).expect("slot must exist"); + assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); + assert_eq!(slot.original_value(), slot.present_value()); + } + + #[test] + fn test_resolve_rex5_zero_slot_errors() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state); + assert!(result.is_err(), "zero _currentSystemAddress should be an error"); + } + + #[test] + fn test_resolve_rex5_missing_registry_errors() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = rex5_hardforks(); + + let err = resolve_system_address(&hardforks, MegaSpecId::REX5, &mut state) + .expect_err("missing registry at Rex5 must fail closed"); + assert!(err.to_string().contains("does not exist")); + } + + #[test] + fn test_resolve_rex5_wrong_code_hash_errors() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: B256::ZERO, + code: Some(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let err = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state) + .expect_err("wrong code hash must fail closed"); + + assert!(err.to_string().contains("code hash mismatch")); + } + + #[test] + fn test_is_apply_pending_changes_due_no_registry() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(!due); + // Witness must contain a not-existing account entry. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); + assert_eq!(acc.status, revm::state::AccountStatus::LoadedAsNotExisting); + assert!(acc.storage.is_empty(), "no-registry witness should have no slots"); + } + + #[test] + fn test_is_apply_pending_changes_due_no_pending() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(!due); + // Witness must include both PENDING_* slots (both zero = no change pending). + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); + assert!( + acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS), + "witness must include PENDING_SYSTEM_ADDRESS" + ); + assert!( + acc.storage.contains_key(&PENDING_SEQUENCER), + "witness must include PENDING_SEQUENCER" + ); + // No activation slots needed because both pending values are zero. + assert_eq!(acc.storage.len(), 2, "no-pending witness should have exactly 2 slots"); + } + + #[test] + fn test_is_apply_pending_changes_due_system_address_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_addr = address!("0x1111111111111111111111111111111111111111"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + new_addr.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + // Not yet due at block 999. + let mut state = State::builder().with_database(&mut db).build(); + let (due, witness) = is_apply_pending_changes_due(&mut state, 999).unwrap(); + assert!(!due, "not yet due"); + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + + // Exactly due at block 1000 (fresh State to avoid cache from prior call). + let mut state = State::builder().with_database(&mut db).build(); + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(due, "exactly due"); + // Both roles' pending slots are always read into the witness. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + } + + #[test] + fn test_is_apply_pending_changes_due_sequencer_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_seq = address!("0x2222222222222222222222222222222222222222"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + new_seq.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(500), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 500).unwrap(); + assert!(due); + // System address has no pending change (slot is zero) so only PENDING_SYSTEM_ADDRESS + // is read. Then sequencer path reads PENDING_SEQUENCER + SEQUENCER_ACTIVATION_BLOCK. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); + assert_eq!(acc.storage.len(), 3); + } + + #[test] + fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_sys = address!("0x1111111111111111111111111111111111111111"); + let new_seq = address!("0x2222222222222222222222222222222222222222"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + new_sys.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1001), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + new_seq.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!( + due, + "sequencer change should still trigger the pre-block call when the system address is not due yet" + ); + // System address is not due (activation at 1001) but its pending slot + activation + // slot are still read. Then the sequencer path reads its own pending + activation. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); + assert_eq!(acc.storage.len(), 4, "both roles' slots should be in the witness"); + for slot_key in [ + PENDING_SYSTEM_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + PENDING_SEQUENCER, + SEQUENCER_ACTIVATION_BLOCK, + ] { + let slot = acc.storage.get(&slot_key).expect("slot must exist"); + assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); + assert_eq!(slot.original_value(), slot.present_value()); + } + } + + #[test] + fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let next_system_address = address!("0x1111111111111111111111111111111111111111"); + let next_sequencer = address!("0x2222222222222222222222222222222222222222"); + + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SEQUENCER, + TEST_SEQUENCER.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + next_system_address.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + next_sequencer.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + let result = + transact_apply_pending_changes(&mut evm).expect("applyPendingChanges() should succeed"); + let state = result.state; + drop(evm); + + revm::DatabaseCommit::commit(&mut db, state); + + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS) + .unwrap(), + address_to_storage_value(next_system_address), + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER) + .unwrap(), + address_to_storage_value(next_sequencer), + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage( + &mut db, + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + ) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage( + &mut db, + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + ) + .unwrap(), + U256::ZERO, + ); + } + + #[test] + fn test_transact_apply_pending_changes_uses_block_gas_limit() { + // Block gas_limit > 30M must be passed through to the system call so that + // applyPendingChanges() can absorb the variable cost from REX dynamic + // storage gas instead of being capped at the upstream-fixed 30M. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 250_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + transact_apply_pending_changes(&mut evm).expect("system call should succeed"); + assert_eq!(revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, 250_000_000); + } + + #[test] + fn test_transact_apply_pending_changes_respects_30m_floor() { + // When the block gas limit is below the 30M floor, the system call must + // still receive at least the historical default budget. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 1_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + transact_apply_pending_changes(&mut evm).expect("system call should succeed"); + assert_eq!( + revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, + crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR, + ); + } + + #[test] + fn test_transact_apply_pending_changes_errors_when_registry_reverts() { + let revert_code = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: revert_code.hash_slow(), + code: Some(revert_code), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + let err = transact_apply_pending_changes(&mut evm) + .expect_err("reverting registry bytecode must fail closed"); + + assert!(err.to_string().contains("reverted or halted")); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/tx.rs b/crates/mega-evm/tests/_pending/src/system/tx.rs new file mode 100644 index 000000000..0905bf354 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/tx.rs @@ -0,0 +1,79 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/tx.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/tx.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::TxKind; + + const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; + const USER: Address = address!("0000000000000000000000000000000000009999"); + const NON_WHITELIST: Address = address!("00000000000000000000000000000000000000ab"); + + /// Builds a legacy (type 0x0) call transaction with the given caller and callee. + fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { + let mut tx = MegaTransaction::default(); + tx.base.tx_type = 0; + tx.base.caller = caller; + tx.base.kind = TxKind::Call(to); + tx + } + + #[test] + fn test_is_system_originated_matches_eip_system_address_caller() { + // The protocol's own pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) + // use `0xff..fe` as caller; it matches regardless of the resolved system address or target. + let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(is_system_originated(&tx, USER)); + } + + #[test] + fn test_is_system_originated_matches_mega_system_tx() { + // Sequencer mega system tx: legacy tx from the system address to a whitelisted contract. + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { + // System address calling a non-whitelisted contract is not a mega system tx. + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NON_WHITELIST); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_matches_promoted_mega_system_tx() { + // `before_run` promotes a mega system tx to a deposit (stamping the source hash and + // flipping `tx_type()`) *before* `on_new_tx` evaluates the exemption. The promoted shape + // must still be recognized as system-originated. + let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "promotion flips tx_type to deposit"); + assert!( + !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), + "the legacy-typed check no longer matches after promotion", + ); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "but the source-hash branch does"); + } + + #[test] + fn test_is_system_originated_rejects_user_tx() { + let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_rejects_user_deposit_tx() { + // Anti-bypass: a user deposit transaction (non-system caller) must NOT be treated as + // system-originated, even though `is_deposit_like_transaction` classifies any deposit as + // deposit-like. Otherwise a user could craft a deposit to escape SALT-scaled storage gas. + let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + // A non-zero deposit source hash makes `tx_type()` report `DEPOSIT_TRANSACTION_TYPE`. + tx.deposit.source_hash = B256::repeat_byte(0x11); + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); + assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } +} diff --git a/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs b/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs new file mode 100644 index 000000000..e1bf5b278 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs @@ -0,0 +1,57 @@ +//! Unit tests extracted from `crates/mega-evm/src/test_utils/opcode_gen.rs` when T2.1 replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/test_utils/opcode_gen.rs`. +//! Owning tickets are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use core::convert::Infallible; + + use alloy_primitives::address; + use revm::context::{ + result::{EVMError, ResultAndState}, + tx::TxEnvBuilder, + }; + + use crate::{ + test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + MegaTransaction, MegaTransactionError, + }; + + use super::*; + + fn execute_bytecode( + bytecode: Bytes, + ) -> Result, EVMError> { + let contract = address!("0000000000000000000000000000000000100001"); + let mut db = MemoryDatabase::default(); + db.set_account_code(contract, bytecode); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + let tx = TxEnvBuilder::default().call(contract).gas_limit(1_000_000_000).build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + alloy_evm::Evm::transact_raw(&mut evm, tx) + } + + #[test] + fn test_assert_stack_value_success() { + let mut builder = BytecodeBuilder::default().push_number(0x2333u64); + builder = builder.assert_stack_value(0, U256::from(0x2333u64)); + let bytecode = builder.build(); + let result = execute_bytecode(bytecode); + assert!(result.unwrap().result.is_success(), "Transaction should succeed"); + } + + #[test] + fn test_assert_stack_value_failure() { + let mut builder = BytecodeBuilder::default().push_number(0x2333u64); + builder = builder.assert_stack_value(0, U256::from(0x9999u64)); + let bytecode = builder.build(); + let result = execute_bytecode(bytecode); + assert!(result.unwrap().result.is_halt(), "Transaction should fail"); + } +} diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 8894c2255..3fc4e64cf 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -43,85 +43,7 @@ # entries against real source for exactly this reason. # ───────────────────────────────────────────────────────────────────────────── -# crates/mega-evm/src/limit/ survivors. -# -# The real test gap here — `AdditionalLimit::before_frame_run -> None` -# (limit.rs:585) — is closed behaviorally by -# `crates/mega-evm/tests/mutation/limit.rs`. The remaining survivors below are -# provably equivalent / dead and are recorded here with justification. - -# --- Dead `tx_limit()` trait methods (equivalent: zero call sites) ---------------- -# -# `::tx_limit` is a -# trivial passthrough to the inherent `FrameLimitTracker::tx_limit()`. Every internal -# consumer (each tracker's own `check_limit()` / `current_call_remaining()`, and -# `AdditionalLimit`) calls `self.frame_tracker.tx_limit()` directly; the *trait* method -# on these three trackers is never invoked anywhere in the crate (verified by grepping -# all `.tx_limit()` call sites — only `ComputeGasTracker`'s trait method is live, since -# its `check_limit` calls `self.tx_limit()` and composes it with `detained_limit`). -# Because the function is dead, replacing its body (`-> 0` / `-> 1`) cannot change any -# observable behavior: the full mega-evm test suite passes with the mutation applied. -# These are required only to satisfy the `TxRuntimeLimit` trait contract. -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/data_size.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/kv_update.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/state_growth.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- effective_remaining_for_rescue boundary (equivalent) ------------------------- -# -# `if stipend > 0 { gas.remaining().min(gas.limit() - stipend) } else { gas.remaining() }`. -# The `> 0` -> `>= 0` mutant only diverges when `stipend == 0`, in which case the then- -# branch computes `gas.remaining().min(gas.limit() - 0) = gas.remaining().min(gas.limit())`. -# Since `gas.remaining() <= gas.limit()` is invariant in revm (remaining starts at limit and -# only decreases; the REX4 stipend inflates both limit and remaining together), this equals -# `gas.remaining()` — identical to the else-branch. The four other mutants in this function -# are caught by the rex4 storage_call_stipend tests; only this true boundary equivalent -# survives. -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/storage_call_stipend.rs" -mutant = "replace > with >= in StorageCallStipendTracker::effective_remaining_for_rescue" -justification = "Equivalent: the > vs >= boundary only differs when stipend == 0, where the then-branch reduces to gas.remaining().min(gas.limit()) == gas.remaining() (the else-branch) because remaining <= limit is invariant. No reachable input observes the difference." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- before_frame_return_result de-dup flag (equivalent) -------------------------- -# -# `let duplicate_return_frame_result = LAST_FRAME && !has_active_frame();`. The `&&` -> `||` -# mutant can only diverge when (a) LAST_FRAME is true while a frame is still active, or -# (b) LAST_FRAME is false while no frame is active. Neither is reachable: the `` -# (`last_frame_result`) call always runs after the frame's tracker has already been popped -# by the preceding `` (`frame_return_result`) pass, so `has_active_frame()` is always -# false at `` calls (making `&& X` == `|| X` == true); and at `` calls -# LAST_FRAME is false. The full mega-evm suite — including all nested/parent-child/sibling -# and top-level frame-local & TX-level-detention exceed tests — passes with the mutant -# applied, confirming no observable difference. -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/limit.rs" -mutant = "replace && with || in AdditionalLimit::before_frame_return_result" -justification = "Equivalent: at every (last_frame_result) call has_active_frame() is already false (the frame was popped by the preceding frame_return_result pass), so LAST_FRAME && !has_active == LAST_FRAME || !has_active == true; at calls LAST_FRAME is false in both. Full suite (incl. all multi-frame exceed tests) green with the mutant." -reviewer = "improve-mutation-score (William Aaron Cheung)" +# crates/mega-evm/src/external/ survivors. # --- EmptyExternalEnv::external_envs (equivalent) --------------------------------- # EmptyExternalEnv is a unit struct. The real body constructs @@ -257,62 +179,3 @@ file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace > with >= in ::write" justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs at len == 16, where both the mid branch (front | (back<<64)) and the large branch (read_last_u128, with no loop pass since 16 is not > 16) feed the identical le_u128(bytes[0..16]) to a single large_update. Same buffer, same bucket id; no input distinguishes them. The line-108 and line-112 mutants sharing this text are non-equivalent and are caught by the len-8 / len-32 tests." reviewer = "improve-mutation-score (William Aaron Cheung)" - -# ───────────────────────────────────────────────────────────────────────────── -# spec-gate operator survivors (universalmutator + comby; scripts/umutate.py). -# -# Equivalent mutants of backward-compat spec gates in src/limit/. The one real -# survivor (limit.rs:203) is closed behaviorally by -# `test_intrinsic_check_for_tx_requires_rex5_spec`. The state_growth entries use -# the full `file:line:col:` form because three sites share identical source text. - -# --- data_size.rs:173 defensive invariant guard (equivalent) ----------------- -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/data_size.rs" -mutant = "spec-gate rex5_enabled: spec.is_enabled(MegaSpecId::REX5), -> rex5_enabled: spec.is_enabled(MegaSpecId::REX4)," -justification = "Equivalent: rex5_enabled only feeds the debug_assert! at data_size.rs:173, which executes only inside the `used > limit` branch with an active frame — a TX-level data-size exceed while a frame is live. Pre-REX5 that state is unreachable in valid execution (before_tx_start, the only mid-execution tx_entry writer, runs before any frame; an exceed there halts before a frame is pushed). Relaxing the guard to REX4 cannot change behavior on any reachable input." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- frame_limit.rs:113 per-frame derivation gate (equivalent: coupled) ------- -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/frame_limit.rs" -mutant = "spec-gate rex4_enabled: spec.is_enabled(MegaSpecId::REX4), -> rex4_enabled: spec.is_enabled(MegaSpecId::REX3)," -justification = "Equivalent (coupled gates): frame_limit rex4_enabled gates only per-frame limit DERIVATION (push_call_frame_info, line 339). ENFORCEMENT (exceeds_current_frame_limit) is gated separately on each dimension's own REX4 check. Shifting derivation to REX3 sets per-frame limits that no dimension checks at REX3 — their checks stay TX-level — so net_usage and every limit outcome are unchanged." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- state_growth.rs REX4 per-frame gates (equivalent: coupled/REX5-only) ----- -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:121:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent (coupled): push_frame shifted to REX3 derives per-frame state-growth limits at REX3, but check_limit (line 206, unmutated) skips the per-frame check pre-REX4 and uses TX-level net_usage only. The derived frame limits are never read, so no observable change." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:206:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent (coupled): check_limit shifted to REX3 runs the per-frame check at REX3, but push_frame (line 121, unmutated) pushes frames with u64::MAX limit pre-REX4, so exceeds_current_frame_limit never fires and control falls through to the identical TX-level check." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:169:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent: current_call_remaining is only read when building a child sandbox budget (sandbox/execution.rs:1037, KeylessDeploy, REX5+); it is never called at REX3/REX4. And at REX3 frames carry u64::MAX limits (push_frame, line 121), so frame_remaining.min(tx_remaining) == tx_remaining regardless." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:169:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX5) {" -justification = "Equivalent: current_call_remaining is only read by the REX5+ KeylessDeploy sandbox (sandbox/execution.rs:1037). The REX4->REX5 shift differs only at exactly REX4, where the function is never called — no observable change." -reviewer = "improve-mutation-score (William Aaron Cheung)" From 093f16c1e76f5db3871c5676ab2f04aae1be48f5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:32:39 +0800 Subject: [PATCH 004/201] feat: add MegaSpecId::SATIN, MegaHardfork::Satin and the chain activation table Satin is a single-spec engine: MegaSpecId has one rung, SATIN, running on Karst / Osaka. Display and FromStr use "Satin" and serde the variant name "SATIN", the same forms the legacy specs use. Legacy names (Equivalence .. Rex7) fail to parse with ParseMegaSpecError::Legacy and are never mapped to Satin. The discriminant continues after the legacy ladder (12). MegaHardfork has the single fork Satin. The activation table carries the mainnet and testnet chain ids with the Satin timestamp unset. The three spec tests the test inventory assigns to the Satin skeleton are ported here (the Isthmus/Prague mapping test now pins Karst/Osaka). --- crates/mega-evm/src/block/chain.rs | 51 ++++ crates/mega-evm/src/block/hardfork.rs | 51 ++++ crates/mega-evm/src/block/mod.rs | 7 + crates/mega-evm/src/evm/mod.rs | 5 + crates/mega-evm/src/evm/spec.rs | 235 ++++++++++++++++++ crates/mega-evm/src/lib.rs | 6 + crates/mega-evm/tests/_pending/README.md | 5 +- .../mega-evm/tests/_pending/src/evm/spec.rs | 63 ----- 8 files changed, 357 insertions(+), 66 deletions(-) create mode 100644 crates/mega-evm/src/block/chain.rs create mode 100644 crates/mega-evm/src/block/hardfork.rs create mode 100644 crates/mega-evm/src/block/mod.rs create mode 100644 crates/mega-evm/src/evm/mod.rs create mode 100644 crates/mega-evm/src/evm/spec.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/spec.rs diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs new file mode 100644 index 000000000..90edcbda0 --- /dev/null +++ b/crates/mega-evm/src/block/chain.rs @@ -0,0 +1,51 @@ +//! Per-chain activation of the `MegaETH` hardforks of the Satin engine. +//! +//! This is the single place that records when each [`MegaHardfork`](crate::MegaHardfork) +//! activates on the known `MegaETH` chains. The node chainspecs decide the schedule; this table +//! mirrors it for tools that replay a real chain. + +use alloy_primitives::BlockTimestamp; + +/// `MegaETH` mainnet chain ID. +pub const MAINNET_CHAIN_ID: u64 = 4326; + +/// `MegaETH` testnet v2 chain ID. +pub const TESTNET_CHAIN_ID: u64 = 6343; + +/// Activation timestamps of the Satin-engine hardforks on one chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChainActivation { + /// The chain the timestamps belong to. + pub chain_id: u64, + /// When [`MegaHardfork::Satin`](crate::MegaHardfork::Satin) activates; `None` while it is + /// not scheduled. + pub satin: Option, +} + +/// Activation table of the known `MegaETH` chains. +pub const CHAIN_ACTIVATIONS: [ChainActivation; 2] = [ + ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: None }, + ChainActivation { chain_id: TESTNET_CHAIN_ID, satin: None }, +]; + +/// The activation table of a known chain, or `None` for any other chain. +pub fn chain_activation(chain_id: u64) -> Option { + CHAIN_ACTIVATIONS.iter().find(|activation| activation.chain_id == chain_id).copied() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_known_chains_have_satin_unscheduled() { + assert_eq!(MAINNET_CHAIN_ID, 4326); + assert_eq!(TESTNET_CHAIN_ID, 6343); + for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID] { + let activation = chain_activation(chain_id).expect("known chain"); + assert_eq!(activation.chain_id, chain_id); + assert_eq!(activation.satin, None, "Satin has no activation timestamp yet"); + } + assert_eq!(chain_activation(1), None); + } +} diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs new file mode 100644 index 000000000..aa364f4af --- /dev/null +++ b/crates/mega-evm/src/block/hardfork.rs @@ -0,0 +1,51 @@ +//! `MegaETH` hardforks of the Satin engine. + +use alloy_hardforks::hardfork; + +use crate::MegaSpecId; + +hardfork! { + /// `MegaETH` network upgrades that schedule a Satin-engine spec. It is expected to mix with + /// `EthereumHardfork` and `OpHardfork`. + /// + /// The forks of the legacy engine (`MiniRex` through `Rex7`) are not variants here; a chain + /// runs them on the legacy engine up to the Satin activation. + #[derive(serde::Serialize, serde::Deserialize)] + MegaHardfork { + /// Activates [`MegaSpecId::SATIN`]. + Satin, + } +} + +impl MegaHardfork { + /// The spec this hardfork activates. + pub const fn spec_id(&self) -> MegaSpecId { + match self { + Self::Satin => MegaSpecId::SATIN, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MegaSpecId; + use alloy_hardforks::Hardfork; + use core::str::FromStr; + + #[test] + fn test_satin_fork_schedules_the_satin_spec() { + assert_eq!(MegaHardfork::VARIANTS, &[MegaHardfork::Satin]); + assert_eq!(MegaHardfork::Satin.spec_id(), MegaSpecId::SATIN); + assert_eq!(Hardfork::name(&MegaHardfork::Satin), "Satin"); + assert_eq!(MegaHardfork::Satin.to_string(), "Satin"); + } + + #[test] + fn test_legacy_fork_names_do_not_parse() { + assert_eq!(MegaHardfork::from_str("Satin").unwrap(), MegaHardfork::Satin); + for legacy in ["MiniRex", "MiniRex1", "MiniRex2", "Rex", "Rex1", "Rex6", "Rex7"] { + assert!(MegaHardfork::from_str(legacy).is_err(), "{legacy} must not parse"); + } + } +} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs new file mode 100644 index 000000000..34a23e246 --- /dev/null +++ b/crates/mega-evm/src/block/mod.rs @@ -0,0 +1,7 @@ +//! Block-level pieces of the Satin engine. + +mod chain; +mod hardfork; + +pub use chain::*; +pub use hardfork::*; diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs new file mode 100644 index 000000000..c9b7a5143 --- /dev/null +++ b/crates/mega-evm/src/evm/mod.rs @@ -0,0 +1,5 @@ +//! The Satin EVM. + +mod spec; + +pub use spec::*; diff --git a/crates/mega-evm/src/evm/spec.rs b/crates/mega-evm/src/evm/spec.rs new file mode 100644 index 000000000..8f17d59bb --- /dev/null +++ b/crates/mega-evm/src/evm/spec.rs @@ -0,0 +1,235 @@ +//! The `MegaETH` EVM spec of the Satin engine (`MegaSpecId`). + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{ + fmt::{self, Display}, + str::FromStr, +}; +use std::string::String; + +pub use op_revm::OpSpecId; +pub use revm::primitives::hardfork::SpecId as EthSpecId; +use serde::{Deserialize, Serialize}; + +/// `MegaETH` spec id: the EVM behavior the Satin engine executes. +/// +/// Satin is a single-spec engine. The specs of the legacy engine (`Equivalence` through `Rex7`) +/// are not variants here and never parse to one; they are executed by the legacy engine. +/// +/// Each spec runs on top of an Optimism spec, which in turn runs on top of an Ethereum spec: +/// - [`MegaSpecId::SATIN`] -> [`OpSpecId::KARST`] -> [`EthSpecId::OSAKA`] +/// +/// The discriminants continue after the legacy ladder (`EQUIVALENCE` = 0 through `REX7` = 11), +/// so a raw `as u8` of a Satin spec never aliases a legacy one. +#[repr(u8)] +#[derive( + Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize, +)] +#[allow(non_camel_case_types, clippy::upper_case_acronyms)] +#[non_exhaustive] +pub enum MegaSpecId { + /// The Satin spec: Karst / Osaka base with EIP-8037 state gas and the EIP-2780 intrinsic + /// cost, under a 200M execution cap. + #[default] + SATIN = 12, +} + +/// String identifiers of the `MegaETH` specs. +pub mod name { + /// The string identifier of [`MegaSpecId::SATIN`](super::MegaSpecId::SATIN). + pub const SATIN: &str = "Satin"; +} + +/// The string identifiers of the legacy engine's specs. +/// +/// Parsing one of them fails with [`ParseMegaSpecError::Legacy`]: the Satin engine does not +/// execute legacy specs, and a legacy name is never mapped to a Satin spec. +pub const LEGACY_SPEC_NAMES: &[&str] = &[ + "Equivalence", + "MiniRex", + "MiniRex1", + "MiniRex2", + "Rex", + "Rex1", + "Rex2", + "Rex3", + "Rex4", + "Rex5", + "Rex6", + "Rex7", +]; + +impl MegaSpecId { + /// Every spec, oldest first. + pub const ALL: &'static [Self] = &[Self::SATIN]; + + /// The Optimism spec this spec runs on. + pub const fn into_op_spec(self) -> OpSpecId { + match self { + Self::SATIN => OpSpecId::KARST, + } + } + + /// The Ethereum spec this spec runs on. + pub const fn into_eth_spec(self) -> EthSpecId { + self.into_op_spec().into_eth_spec() + } + + /// The string identifier of this spec. + pub const fn name(self) -> &'static str { + match self { + Self::SATIN => name::SATIN, + } + } +} + +/// Error returned when a string does not name a Satin spec. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ParseMegaSpecError { + /// The string names a spec of the legacy engine. + Legacy(String), + /// The string names no known spec. + Unknown, +} + +impl Display for ParseMegaSpecError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Legacy(name) => { + write!(f, "{name} is a spec of the legacy engine; Satin does not execute it") + } + Self::Unknown => f.write_str("unknown MegaETH spec name"), + } + } +} + +impl core::error::Error for ParseMegaSpecError {} + +impl FromStr for MegaSpecId { + type Err = ParseMegaSpecError; + + fn from_str(s: &str) -> Result { + match s { + name::SATIN => Ok(Self::SATIN), + legacy if LEGACY_SPEC_NAMES.contains(&legacy) => { + Err(ParseMegaSpecError::Legacy(legacy.into())) + } + _ => Err(ParseMegaSpecError::Unknown), + } + } +} + +impl From for &'static str { + fn from(spec: MegaSpecId) -> Self { + spec.name() + } +} + +impl From for OpSpecId { + fn from(spec: MegaSpecId) -> Self { + spec.into_op_spec() + } +} + +impl From for EthSpecId { + fn from(spec: MegaSpecId) -> Self { + spec.into_eth_spec() + } +} + +impl Display for MegaSpecId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::str::FromStr; + + /// Every spec name of the legacy engine, written out by hand so the rejection check does + /// not read the list it is checking. + const LEGACY_NAMES: [&str; 12] = [ + "Equivalence", + "MiniRex", + "MiniRex1", + "MiniRex2", + "Rex", + "Rex1", + "Rex2", + "Rex3", + "Rex4", + "Rex5", + "Rex6", + "Rex7", + ]; + + #[test] + fn test_spec_names_roundtrip_and_display() { + assert_eq!(MegaSpecId::SATIN.to_string(), "Satin"); + assert_eq!(<&'static str>::from(MegaSpecId::SATIN), "Satin"); + assert_eq!(MegaSpecId::from_str("Satin"), Ok(MegaSpecId::SATIN)); + assert_eq!(MegaSpecId::from_str("satin"), Err(ParseMegaSpecError::Unknown)); + assert_eq!(MegaSpecId::from_str(""), Err(ParseMegaSpecError::Unknown)); + } + + #[test] + fn test_legacy_spec_names_are_rejected_not_mapped() { + for name in LEGACY_NAMES { + assert_eq!( + MegaSpecId::from_str(name), + Err(ParseMegaSpecError::Legacy(name.into())), + "{name} must not parse to a Satin spec" + ); + } + assert_eq!(LEGACY_SPEC_NAMES, LEGACY_NAMES.as_slice()); + } + + #[test] + fn test_parse_error_names_the_legacy_engine() { + let err = MegaSpecId::from_str("Rex6").unwrap_err(); + assert_eq!( + err.to_string(), + "Rex6 is a spec of the legacy engine; Satin does not execute it" + ); + assert_eq!( + MegaSpecId::from_str("Rex8").unwrap_err().to_string(), + "unknown MegaETH spec name" + ); + } + + #[test] + fn test_serde_uses_the_variant_name() { + assert_eq!(serde_json::to_string(&MegaSpecId::SATIN).unwrap(), "\"SATIN\""); + assert_eq!(serde_json::from_str::("\"SATIN\"").unwrap(), MegaSpecId::SATIN); + for legacy in ["\"REX6\"", "\"REX7\"", "\"EQUIVALENCE\"", "\"Satin\""] { + assert!( + serde_json::from_str::(legacy).is_err(), + "{legacy} must not deserialize" + ); + } + } + + #[test] + fn test_all_ends_at_the_latest_spec() { + assert_eq!(MegaSpecId::ALL, &[MegaSpecId::SATIN]); + assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); + } + + /// A raw `as u8` of a Satin spec never aliases a legacy rung (`EQUIVALENCE` = 0 through + /// `REX7` = 11). + #[test] + fn test_discriminant_continues_after_the_legacy_ladder() { + assert_eq!(MegaSpecId::SATIN as u8, 12); + } + + #[test] + fn test_all_specs_map_to_karst_and_osaka() { + assert_eq!(MegaSpecId::SATIN.into_op_spec(), OpSpecId::KARST); + assert_eq!(MegaSpecId::SATIN.into_eth_spec(), EthSpecId::OSAKA); + assert_eq!(OpSpecId::from(MegaSpecId::SATIN), OpSpecId::KARST); + assert_eq!(EthSpecId::from(MegaSpecId::SATIN), EthSpecId::OSAKA); + } +} diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 7e7cdda04..6e9a0e7dc 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -5,3 +5,9 @@ #[cfg_attr(not(feature = "std"), macro_use)] #[cfg(not(feature = "std"))] extern crate alloc; + +mod block; +mod evm; + +pub use block::*; +pub use evm::*; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index f7bc5cf8d..16a46b126 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -25,7 +25,7 @@ Do not add a `_pending/main.rs`. | Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | |---|---:|---:|---:|---:|---:|---:| -| T2.1 | 21 | 0 | 21 | 15 | 6 | 0 | +| T2.1 | 18 | 0 | 18 | 15 | 3 | 0 | | T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | | T2.3 | 40 | 19 | 21 | 21 | 19 | 0 | | T3.1 | 36 | 30 | 6 | 7 | 29 | 0 | @@ -44,7 +44,7 @@ Do not add a `_pending/main.rs`. | T8.1 | 74 | 45 | 29 | 55 | 19 | 0 | | T9 | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **872** | **691** | **181** | **516** | **327** | **29** | +| **Total** | **869** | **691** | **178** | **516** | **324** | **29** | ## Files @@ -146,7 +146,6 @@ Each cell lists `disposition count (ticket · decision)`. | `src/evm/mod.rs` | 11 | 保留 8 (T2.1); 保留 3 (T5.2) | | `src/evm/precompiles.rs` | 6 | 保留 6 (T3.1 · D04) | | `src/evm/result.rs` | 4 | 重写 4 (T2.3 · D17/D48 (halt-reason set changes)) | -| `src/evm/spec.rs` | 3 | 重写 3 (T2.1 · single rung; Karst/Osaka; legacy names must error) | | `src/evm/state.rs` | 1 | 保留 1 (T8.1) | | `src/external/gas.rs` | 9 | 重写 9 (T3.2 · D12/D51) | | `src/external/hasher/mod.rs` | 5 | 保留 5 (T3.2) | diff --git a/crates/mega-evm/tests/_pending/src/evm/spec.rs b/crates/mega-evm/tests/_pending/src/evm/spec.rs deleted file mode 100644 index d01d0a472..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/spec.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/spec.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/spec.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// The one golden spec table: every spec with its string identifier and its pinned ladder - /// position. The spec column must be exactly [`MegaSpecId::ALL`] (asserted in the - /// round-trip test); the name and position columns stay hand-written — deriving either - /// from the code under test would make its check vacuous. - const ALL_SPECS: [(MegaSpecId, &str, u8); 12] = [ - (MegaSpecId::EQUIVALENCE, name::EQUIVALENCE, 0), - (MegaSpecId::MINI_REX, name::MINI_REX, 1), - (MegaSpecId::MINI_REX_1, name::MINI_REX_1, 2), - (MegaSpecId::MINI_REX_2, name::MINI_REX_2, 3), - (MegaSpecId::REX, name::REX, 4), - (MegaSpecId::REX1, name::REX1, 5), - (MegaSpecId::REX2, name::REX2, 6), - (MegaSpecId::REX3, name::REX3, 7), - (MegaSpecId::REX4, name::REX4, 8), - (MegaSpecId::REX5, name::REX5, 9), - (MegaSpecId::REX6, name::REX6, 10), - (MegaSpecId::REX7, name::REX7, 11), - ]; - - #[test] - fn test_spec_names_roundtrip_and_display() { - // The spec column must be exactly `MegaSpecId::ALL`, so a newly introduced spec cannot - // be forgotten here. - assert!(ALL_SPECS.iter().map(|(spec, _, _)| *spec).eq(MegaSpecId::ALL.iter().copied())); - - for (spec, expected_name, _) in ALL_SPECS { - assert_eq!(<&'static str>::from(spec), expected_name); - assert_eq!(MegaSpecId::from_str(expected_name).unwrap(), spec); - assert_eq!(spec.to_string(), expected_name); - } - - assert_eq!(MegaSpecId::default(), MegaSpecId::REX7); - assert_eq!(MegaSpecId::from_str("unknown"), Err(UnknownHardfork)); - } - - /// The completeness anchor for [`MegaSpecId::ALL`]: `Default` tracks the latest spec (its - /// own assertion above pins which), so a variant added without extending `ALL` fails here - /// once the default advances. The const assertion on `ladder_index` covers order and gaps; - /// this covers the tail. - #[test] - fn test_all_ends_at_the_latest_spec() { - assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); - } - - #[test] - fn test_all_specs_map_to_isthmus_and_prague() { - for spec in MegaSpecId::ALL.iter().copied() { - assert_eq!(spec.into_op_spec(), OpSpecId::ISTHMUS); - assert_eq!(spec.into_eth_spec(), EthSpecId::PRAGUE); - assert_eq!(revm::primitives::hardfork::SpecId::from(spec), EthSpecId::PRAGUE); - assert_eq!(OpSpecId::from(spec), OpSpecId::ISTHMUS); - } - } - -} From db854078c5ec09946e5ea627e88f5c5ca59610d2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:43:56 +0800 Subject: [PATCH 005/201] feat: carry the external environment interfaces over unchanged ExternalEnvFactory, ExternalEnvTypes, ExternalEnvs, SaltEnv, OracleEnv, EmptyExternalEnv, the bucket hasher and TestExternalEnvs come back from the legacy core as they were, with their seven unit tests. gas.rs (DynamicGasCost) stays out: it belongs to SALT pricing. --- crates/mega-evm/src/external/AGENTS.md | 29 ++ crates/mega-evm/src/external/factory.rs | 41 +++ crates/mega-evm/src/external/hasher/NOTICE.md | 27 ++ .../mega-evm/src/external/hasher/convert.rs | 90 +++++ .../mega-evm/src/external/hasher/fallback.rs | 144 ++++++++ .../_pending => }/src/external/hasher/mod.rs | 72 +++- crates/mega-evm/src/external/mod.rs | 112 +++++++ crates/mega-evm/src/external/oracle.rs | 62 ++++ crates/mega-evm/src/external/salt.rs | 111 +++++++ crates/mega-evm/src/external/test_utils.rs | 308 ++++++++++++++++++ crates/mega-evm/src/lib.rs | 2 + crates/mega-evm/tests/_pending/README.md | 9 +- .../tests/_pending/src/external/mod.rs | 21 -- .../tests/_pending/src/external/test_utils.rs | 22 -- 14 files changed, 998 insertions(+), 52 deletions(-) create mode 100644 crates/mega-evm/src/external/AGENTS.md create mode 100644 crates/mega-evm/src/external/factory.rs create mode 100644 crates/mega-evm/src/external/hasher/NOTICE.md create mode 100644 crates/mega-evm/src/external/hasher/convert.rs create mode 100644 crates/mega-evm/src/external/hasher/fallback.rs rename crates/mega-evm/{tests/_pending => }/src/external/hasher/mod.rs (57%) create mode 100644 crates/mega-evm/src/external/mod.rs create mode 100644 crates/mega-evm/src/external/oracle.rs create mode 100644 crates/mega-evm/src/external/salt.rs create mode 100644 crates/mega-evm/src/external/test_utils.rs delete mode 100644 crates/mega-evm/tests/_pending/src/external/mod.rs delete mode 100644 crates/mega-evm/tests/_pending/src/external/test_utils.rs diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md new file mode 100644 index 000000000..272fd6417 --- /dev/null +++ b/crates/mega-evm/src/external/AGENTS.md @@ -0,0 +1,29 @@ +# AGENTS.md + +## OVERVIEW +External dependency abstraction for block-scoped SALT and oracle data consumed during EVM execution. + +## STRUCTURE +- `mod.rs`: `ExternalEnvTypes`, `ExternalEnvs`, and `EmptyExternalEnv` defaults. +- `factory.rs`: `ExternalEnvFactory` trait for block-scoped environment creation. +- `salt.rs`: SALT trait and bucket-id derivation rules. +- `oracle.rs`: oracle trait for storage reads and hint side effects. +- SALT pricing (the state-gas price hook that consumes `SaltEnv`) is not here yet; T3.2 adds it. +- `hasher/`: hashing utilities used for deterministic bucket-id computation. + +## KEY PATTERNS +- Block context is captured at environment creation time, not passed per query. +- SALT and oracle are independent traits but consumed together via `ExternalEnvs` bundle. +- External errors are propagated to host and then stashed in EVM context error channel. +- `EmptyExternalEnv` must stay deterministic and side-effect free. + +## ANTI-PATTERNS +- Do not query live chain state directly from opcode handlers. +- All external reads should route through trait objects created by `ExternalEnvFactory`. +- Do not couple oracle hint side effects to SALT behavior. +- Keep SALT and oracle traits independently testable. + +## WHERE TO LOOK +- Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. +- Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration arrives with T6.3). +- Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. diff --git a/crates/mega-evm/src/external/factory.rs b/crates/mega-evm/src/external/factory.rs new file mode 100644 index 000000000..3a1062dec --- /dev/null +++ b/crates/mega-evm/src/external/factory.rs @@ -0,0 +1,41 @@ +use alloy_primitives::BlockNumber; +use auto_impl::auto_impl; + +use crate::{ExternalEnvTypes, ExternalEnvs}; + +/// Factory for creating block-specific external environment instances. +/// +/// This trait is responsible for instantiating external oracles at a specific block height, +/// ensuring all oracle queries during EVM execution operate on a consistent snapshot of state. +/// +/// # Design Pattern +/// +/// External environments (SALT and Oracle) do not take block parameters in their methods. +/// Instead, the factory creates block-aware instances that encapsulate the block context, +/// allowing implementations to: +/// - Read state from the appropriate block height +/// - Cache block-specific data for the execution lifetime +/// - Ensure deterministic behavior across repeated executions +/// +/// # Usage +/// +/// This factory is typically called once per block when initializing the EVM. The returned +/// [`ExternalEnvs`] are then used throughout transaction execution within that block. +#[auto_impl(&, Box, Arc)] +pub trait ExternalEnvFactory { + /// The concrete types for SALT and Oracle environments this factory produces. + type EnvTypes: ExternalEnvTypes; + + /// Creates external environment instances for executing EVM operations at the specified block. + /// + /// # Arguments + /// + /// * `block` - The block number at which EVM execution will occur. This is the block height + /// specified in [`BlockEnv`](revm::context::BlockEnv), and oracle queries should read state + /// from the parent block (block - 1). + /// + /// # Returns + /// + /// A container with SALT and Oracle environment instances configured for the given block. + fn external_envs(&self, block: BlockNumber) -> ExternalEnvs; +} diff --git a/crates/mega-evm/src/external/hasher/NOTICE.md b/crates/mega-evm/src/external/hasher/NOTICE.md new file mode 100644 index 000000000..b9dec4196 --- /dev/null +++ b/crates/mega-evm/src/external/hasher/NOTICE.md @@ -0,0 +1,27 @@ +# Third Party Attribution + +## AHash Crate + +**Source**: [ahash v0.8.12](https://github.com/tkaitchuck/aHash) +**License**: Apache License 2.0 +**Copyright**: Copyright (c) 2019 Tom Kaitchuck +**Repository**: https://github.com/tkaitchuck/aHash + +### Files Derived from AHash + +- `convert.rs` - Extracted from `src/convert.rs` +- `fallback.rs` - Derived from `src/fallback_hash.rs` and related modules + +### Modifications Made + +The code has been extracted and modified for deterministic cross-platform behavior: + +1. **Deterministic algorithm selection**: Always uses the fallback "folded multiply" algorithm with true 128-bit multiplication instead of platform-specific optimizations +2. **Fixed seeds**: Uses predetermined seeds rather than random generation for reproducible results +3. **Consensus compatibility**: Ensures identical hash values across all platforms and architectures +4. **Module structure**: Reorganized into separate modules for better maintainability + +### Original License + +The original AHash crate is licensed under the Apache License 2.0. The full license text can be found at: +https://www.apache.org/licenses/LICENSE-2.0 diff --git a/crates/mega-evm/src/external/hasher/convert.rs b/crates/mega-evm/src/external/hasher/convert.rs new file mode 100644 index 000000000..36c5c975f --- /dev/null +++ b/crates/mega-evm/src/external/hasher/convert.rs @@ -0,0 +1,90 @@ +// Derived from AHash v0.8.12 - see NOTICE.md for full attribution + +pub(crate) trait ReadFromSlice { + fn read_u16(&self) -> (u16, &[u8]); + fn read_u32(&self) -> (u32, &[u8]); + fn read_u64(&self) -> (u64, &[u8]); + fn read_u128(&self) -> (u128, &[u8]); + fn read_last_u32(&self) -> u32; + fn read_last_u64(&self) -> u64; + fn read_last_u128(&self) -> u128; +} + +macro_rules! as_array { + ($input:expr, $len:expr) => {{ + { + #[inline(always)] + fn as_array(slice: &[T]) -> &[T; $len] { + core::convert::TryFrom::try_from(slice).unwrap() + } + as_array($input) + } + }}; +} + +// The original salt crate uses zerocopy::transmute! (native endian). We use from_le_bytes +// to match behavior on all current targets (x86_64, riscv64 — both little-endian) without +// requiring the zerocopy dependency. +#[inline(always)] +fn u16_from_le_bytes(bytes: &[u8; 2]) -> u16 { + u16::from_le_bytes(*bytes) +} + +#[inline(always)] +fn u32_from_le_bytes(bytes: &[u8; 4]) -> u32 { + u32::from_le_bytes(*bytes) +} + +#[inline(always)] +fn u64_from_le_bytes(bytes: &[u8; 8]) -> u64 { + u64::from_le_bytes(*bytes) +} + +#[inline(always)] +fn u128_from_le_bytes(bytes: &[u8; 16]) -> u128 { + u128::from_le_bytes(*bytes) +} + +impl ReadFromSlice for [u8] { + #[inline(always)] + fn read_u16(&self) -> (u16, &[u8]) { + let (value, rest) = self.split_at(2); + (u16_from_le_bytes(as_array!(value, 2)), rest) + } + + #[inline(always)] + fn read_u32(&self) -> (u32, &[u8]) { + let (value, rest) = self.split_at(4); + (u32_from_le_bytes(as_array!(value, 4)), rest) + } + + #[inline(always)] + fn read_u64(&self) -> (u64, &[u8]) { + let (value, rest) = self.split_at(8); + (u64_from_le_bytes(as_array!(value, 8)), rest) + } + + #[inline(always)] + fn read_u128(&self) -> (u128, &[u8]) { + let (value, rest) = self.split_at(16); + (u128_from_le_bytes(as_array!(value, 16)), rest) + } + + #[inline(always)] + fn read_last_u32(&self) -> u32 { + let (_, value) = self.split_at(self.len() - 4); + u32_from_le_bytes(as_array!(value, 4)) + } + + #[inline(always)] + fn read_last_u64(&self) -> u64 { + let (_, value) = self.split_at(self.len() - 8); + u64_from_le_bytes(as_array!(value, 8)) + } + + #[inline(always)] + fn read_last_u128(&self) -> u128 { + let (_, value) = self.split_at(self.len() - 16); + u128_from_le_bytes(as_array!(value, 16)) + } +} diff --git a/crates/mega-evm/src/external/hasher/fallback.rs b/crates/mega-evm/src/external/hasher/fallback.rs new file mode 100644 index 000000000..dd39d6abb --- /dev/null +++ b/crates/mega-evm/src/external/hasher/fallback.rs @@ -0,0 +1,144 @@ +// Derived from AHash v0.8.12 - see NOTICE.md for full attribution + +use super::convert::ReadFromSlice; + +#[inline(always)] +fn read_small(data: &[u8]) -> [u64; 2] { + debug_assert!(data.len() <= 8); + if data.len() >= 2 { + if data.len() >= 4 { + [data.read_u32().0 as u64, data.read_last_u32() as u64] + } else { + [data.read_u16().0 as u64, data[data.len() - 1] as u64] + } + } else if !data.is_empty() { + [data[0] as u64, data[0] as u64] + } else { + [0, 0] + } +} + +const PI2: [u64; 4] = + [0x4528_21e6_38d0_1377, 0xbe54_66cf_34e9_0c6c, 0xc0ac_29b7_c97c_50dd, 0x3f84_d5b5_b547_0917]; + +const MULTIPLE: u64 = 6364136223846793005; +const ROT: u32 = 23; + +#[inline(always)] +const fn folded_multiply(s: u64, by: u64) -> u64 { + let result = (s as u128).wrapping_mul(by as u128); + ((result & 0xffff_ffff_ffff_ffff) as u64) ^ ((result >> 64) as u64) +} + +#[derive(Debug, Clone)] +pub(crate) struct RandomState { + k0: u64, + k1: u64, + k2: u64, + k3: u64, +} + +impl RandomState { + #[inline] + pub(super) const fn with_seeds(k0: u64, k1: u64, k2: u64, k3: u64) -> Self { + Self { k0: k0 ^ PI2[0], k1: k1 ^ PI2[1], k2: k2 ^ PI2[2], k3: k3 ^ PI2[3] } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct DeterministicHasher { + buffer: u64, + pad: u64, + extra_keys: [u64; 2], +} + +impl DeterministicHasher { + #[inline(always)] + fn update(&mut self, new_data: u64) { + self.buffer = folded_multiply(new_data ^ self.buffer, MULTIPLE); + } + + #[inline(always)] + fn large_update(&mut self, new_data: u128) { + let block: [u64; 2] = [new_data as u64, (new_data >> 64) as u64]; + let combined = + folded_multiply(block[0] ^ self.extra_keys[0], block[1] ^ self.extra_keys[1]); + self.buffer = (self.buffer.wrapping_add(self.pad) ^ combined).rotate_left(ROT); + } +} + +impl core::hash::Hasher for DeterministicHasher { + #[inline] + fn write_u8(&mut self, i: u8) { + self.update(i as u64); + } + + #[inline] + fn write_u16(&mut self, i: u16) { + self.update(i as u64); + } + + #[inline] + fn write_u32(&mut self, i: u32) { + self.update(i as u64); + } + + #[inline] + fn write_u64(&mut self, i: u64) { + self.update(i); + } + + #[inline] + fn write_u128(&mut self, i: u128) { + self.large_update(i); + } + + #[inline] + fn write_usize(&mut self, i: usize) { + self.write_u64(i as u64); + } + + #[inline] + fn write(&mut self, input: &[u8]) { + let mut data = input; + let length = data.len() as u64; + + self.buffer = self.buffer.wrapping_add(length).wrapping_mul(MULTIPLE); + + if data.len() > 8 { + if data.len() > 16 { + let tail = data.read_last_u128(); + self.large_update(tail); + while data.len() > 16 { + let (block, rest) = data.read_u128(); + self.large_update(block); + data = rest; + } + } else { + let front = data.read_u64().0; + let back = data.read_last_u64(); + let combined = (front as u128) | ((back as u128) << 64); + self.large_update(combined); + } + } else { + let value = read_small(data); + let combined = (value[0] as u128) | ((value[1] as u128) << 64); + self.large_update(combined); + } + } + + #[inline] + fn finish(&self) -> u64 { + let rot = (self.buffer & 63) as u32; + folded_multiply(self.buffer, self.pad).rotate_left(rot) + } +} + +impl core::hash::BuildHasher for RandomState { + type Hasher = DeterministicHasher; + + #[inline] + fn build_hasher(&self) -> Self::Hasher { + DeterministicHasher { buffer: self.k1, pad: self.k0, extra_keys: [self.k2, self.k3] } + } +} diff --git a/crates/mega-evm/tests/_pending/src/external/hasher/mod.rs b/crates/mega-evm/src/external/hasher/mod.rs similarity index 57% rename from crates/mega-evm/tests/_pending/src/external/hasher/mod.rs rename to crates/mega-evm/src/external/hasher/mod.rs index 319a85d97..7e1178d37 100644 --- a/crates/mega-evm/tests/_pending/src/external/hasher/mod.rs +++ b/crates/mega-evm/src/external/hasher/mod.rs @@ -1,6 +1,72 @@ -//! Unit tests extracted from `crates/mega-evm/src/external/hasher/mod.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/hasher/mod.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Deterministic hashing for mapping keys to SALT buckets. +//! +//! This module provides the [`AHashBucketHasher`] which implements [`BucketHasher`] using +//! a vendored subset of `AHash` v0.8.12's deterministic fallback algorithm. +//! This ensures identical bucket ID results across all platforms, matching the production +//! `salt` crate's behavior. +//! +//! # Attribution +//! +//! The hashing implementation is derived from [AHash v0.8.12](https://github.com/tkaitchuck/aHash) +//! under Apache License 2.0. See [`NOTICE.md`](./NOTICE.md) for full attribution. + +mod convert; +mod fallback; + +use self::fallback::RandomState; +use crate::{BucketHasher, BucketId, MIN_BUCKET_SIZE}; +use core::hash::{BuildHasher, Hasher}; + +/// Width of each trie level in bits (256-ary trie). +const TRIE_WIDTH_BITS: usize = 8; + +/// Number of levels in the main SALT trie. +const MAIN_TRIE_LEVELS: usize = 4; + +/// Total number of buckets: 256^3 = 16,777,216. +const NUM_BUCKETS: usize = 1 << ((MAIN_TRIE_LEVELS - 1) * TRIE_WIDTH_BITS); + +/// Number of metadata buckets reserved at the start: 65,536. +const NUM_META_BUCKETS: usize = NUM_BUCKETS / MIN_BUCKET_SIZE; + +/// Number of key-value data buckets: 16,711,680. +const NUM_KV_BUCKETS: usize = NUM_BUCKETS - NUM_META_BUCKETS; + +/// Fixed seeds derived from the lower 32 bytes of keccak256("Make Ethereum Great Again"). +const HASHER_SEEDS: [u64; 4] = [0x921321f4, 0x2ccb667e, 0x60d68842, 0x077ada9d]; + +/// Computes a deterministic 64-bit hash of the input bytes using the `AHash` fallback algorithm. +#[inline(always)] +fn hash(bytes: &[u8]) -> u64 { + static HASH_BUILDER: RandomState = + RandomState::with_seeds(HASHER_SEEDS[0], HASHER_SEEDS[1], HASHER_SEEDS[2], HASHER_SEEDS[3]); + + let mut hasher = HASH_BUILDER.build_hasher(); + hasher.write(bytes); + hasher.finish() +} + +/// Maps a plain key (account address or address+slot) to a SALT bucket ID. +/// +/// Returns a bucket ID in the range `[NUM_META_BUCKETS, NUM_BUCKETS)`. +/// The first `NUM_META_BUCKETS` buckets are reserved for metadata storage. +#[inline(always)] +fn bucket_id(key: &[u8]) -> BucketId { + (hash(key) % NUM_KV_BUCKETS as u64 + NUM_META_BUCKETS as u64) as BucketId +} + +/// AHash-based bucket hasher matching the production `salt` crate's deterministic algorithm. +/// +/// This hasher uses the vendored `AHash` v0.8.12 fallback (folded-multiply) with fixed seeds +/// to produce bucket IDs identical to the `salt` crate on all platforms. +#[derive(Debug, Clone, Copy)] +pub struct AHashBucketHasher; + +impl BucketHasher for AHashBucketHasher { + fn bucket_id(key: &[u8]) -> BucketId { + bucket_id(key) + } +} #[cfg(test)] mod tests { diff --git a/crates/mega-evm/src/external/mod.rs b/crates/mega-evm/src/external/mod.rs new file mode 100644 index 000000000..e0b6c4277 --- /dev/null +++ b/crates/mega-evm/src/external/mod.rs @@ -0,0 +1,112 @@ +//! External environment for EVM execution. +//! +//! This module provides interfaces for accessing external data sources during EVM execution: +//! - **SALT**: Bucket capacity information for dynamic gas pricing +//! - **Oracle**: Storage from the `MegaETH` oracle contract +//! +//! # Architecture +//! +//! External environments follow a factory pattern: +//! 1. [`ExternalEnvFactory`] creates block-specific environment instances +//! 2. [`ExternalEnvs`] bundles SALT and Oracle implementations +//! 3. Individual oracle methods (e.g., [`SaltEnv::get_bucket_capacity`]) provide data +//! +//! Block context is established at factory creation time, not per oracle call, ensuring +//! consistent state snapshots throughout execution. + +use alloy_primitives::BlockNumber; +use auto_impl::auto_impl; +use core::fmt::Debug; + +mod factory; +#[cfg(any(test, feature = "test-utils"))] +mod hasher; +mod oracle; +mod salt; +#[cfg(any(test, feature = "test-utils"))] +mod test_utils; + +pub use factory::*; +#[cfg(any(test, feature = "test-utils"))] +pub use hasher::*; +pub use oracle::*; +pub use salt::*; +#[cfg(any(test, feature = "test-utils"))] +pub use test_utils::*; + +/// Type-level specification of external environment implementations. +/// +/// This trait associates concrete SALT and Oracle types, allowing generic code to work +/// with any compatible environment configuration. +#[auto_impl(&, Box, Arc)] +pub trait ExternalEnvTypes { + /// SALT environment implementation for bucket capacity queries. + type SaltEnv: SaltEnv; + /// Oracle environment implementation for system contract storage queries. + type OracleEnv: OracleEnv; +} + +/// Tuple implementation for convenient pairing of SALT and Oracle environments. +impl ExternalEnvTypes for (A, B) { + type SaltEnv = A; + type OracleEnv = B; +} + +/// Bundle of external environment instances for a specific execution context. +/// +/// This struct holds concrete SALT and Oracle implementations that are used during +/// EVM execution. Typically created by [`ExternalEnvFactory::external_envs`] at the +/// start of block processing. +#[derive(Debug, Clone)] +pub struct ExternalEnvs { + /// SALT environment for bucket capacity queries and dynamic gas calculation. + pub salt_env: T::SaltEnv, + /// Oracle environment for reading system contract storage. + pub oracle_env: T::OracleEnv, +} + +impl Default for ExternalEnvs { + fn default() -> Self { + Self { salt_env: EmptyExternalEnv, oracle_env: EmptyExternalEnv } + } +} + +/// No-op external environment for testing or when oracle functionality is disabled. +/// +/// This implementation: +/// - Returns minimum bucket capacity for all SALT queries +/// - Returns `None` for all Oracle storage queries +/// - Assigns all accounts and storage slots to bucket 0 +#[derive(Debug, Default, Clone, Copy)] +pub struct EmptyExternalEnv; + +impl ExternalEnvTypes for EmptyExternalEnv { + type SaltEnv = Self; + type OracleEnv = Self; +} + +impl ExternalEnvFactory for EmptyExternalEnv { + type EnvTypes = Self; + + fn external_envs(&self, _block: BlockNumber) -> ExternalEnvs { + ExternalEnvs { salt_env: *self, oracle_env: *self } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{OracleEnv, SaltEnv, MIN_BUCKET_SIZE}; + use alloy_primitives::{Address, Bytes, B256, U256}; + + #[test] + fn test_empty_external_env_factory_returns_minimum_bucket_and_no_oracle() { + let envs = EmptyExternalEnv.external_envs(42); + + assert_eq!(envs.salt_env.get_bucket_capacity(123).unwrap(), MIN_BUCKET_SIZE as u64); + assert_eq!(envs.oracle_env.get_oracle_storage(U256::from(7)), None); + envs.oracle_env.on_hint(Address::ZERO, B256::ZERO, Bytes::new()); + assert_eq!(::bucket_id_for_account(Address::ZERO), 0); + assert_eq!(::bucket_id_for_slot(Address::ZERO, U256::ZERO), 0); + } +} diff --git a/crates/mega-evm/src/external/oracle.rs b/crates/mega-evm/src/external/oracle.rs new file mode 100644 index 000000000..303638e4d --- /dev/null +++ b/crates/mega-evm/src/external/oracle.rs @@ -0,0 +1,62 @@ +//! Oracle environment trait and implementations. + +use core::fmt::Debug; + +use alloy_primitives::{Address, Bytes, B256, U256}; +use auto_impl::auto_impl; + +use crate::EmptyExternalEnv; + +/// An oracle service that provides external information to the EVM. This trait provides a mechanism +/// for the EVM to query storage slots from the `MegaETH` oracle contract. +/// +/// Typically, one implementation of this trait can be a reader of the underlying blockchain +/// database of `MegaETH` to provide deterministic oracle data during EVM execution. +#[auto_impl(&, Box, Arc)] +pub trait OracleEnv: Debug + Unpin { + /// Gets the storage value at a specific slot of the `MegaETH` oracle contract. + /// + /// # Arguments + /// + /// * `slot` - The storage slot to query + /// + /// # Returns + /// + /// The storage value at the given slot of the oracle contract. If the oracle does not provide a + /// value, the result will be `None`. + fn get_oracle_storage(&self, slot: U256) -> Option; + + /// Receives hints emitted on-chain by the oracle contract. A hint is a message sent from + /// on-chain to the oracle service backend (on the sequencer). + /// + /// # Arguments + /// + /// Invoking the `sendHint(bytes32 topic, bytes data)` function on the oracle contract during + /// transaction execution will trigger this method synchronously. + /// - `from` - The address that called the `sendHint` function. This is useful for off-chain + /// access control, as the `msg.sender` cannot be faked. On-chain access control can be + /// enforced in a periphery contract which directly calls `sendHint`. + /// - `topic` - The user-defined hint topic. + /// - `data` - The additional context data for the hint. + /// + /// The order of hinting ([`Self::on_hint`]) and oracle reading ([`Self::get_oracle_storage`]) + /// is guaranteed preserved, i.e., if the on-chain transaction emits a hint log first and then + /// tries to read oracle data, `on_hint` is guaranteed to be called before `get_oracle_storage`. + /// + /// One example application is telling the off-chain oracle service which data needs to be + /// fetched before it provides any oracle data. Handling hints is completely optional for the + /// oracle service backend. + /// + /// # Warning + /// + /// This method is called synchronously during transaction execution. Therefore, it should not + /// perform any heavy computations, which otherwise will block the transaction execution and + /// lower the EVM performance. + fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} +} + +impl OracleEnv for EmptyExternalEnv { + fn get_oracle_storage(&self, _slot: U256) -> Option { + None + } +} diff --git a/crates/mega-evm/src/external/salt.rs b/crates/mega-evm/src/external/salt.rs new file mode 100644 index 000000000..77dc611df --- /dev/null +++ b/crates/mega-evm/src/external/salt.rs @@ -0,0 +1,111 @@ +//! This module defines the `SaltEnv` trait, which provides bucket capacity information for dynamic +//! gas pricing. Storage slots and accounts are organized into buckets, and the gas cost scales +//! with bucket capacity to incentivize efficient resource allocation. + +use core::{ + convert::Infallible, + fmt::{Debug, Display}, +}; + +use alloy_primitives::{Address, U256}; +use auto_impl::auto_impl; + +use crate::EmptyExternalEnv; + +/// SALT bucket identifier. Accounts and storage slots are mapped to buckets, which have +/// dynamic capacities that affect gas costs. +pub type BucketId = u32; + +/// Number of bits to represent the minimum bucket size (8 bits = 256 slots). +pub const MIN_BUCKET_SIZE_BITS: usize = 8; + +/// Minimum capacity of a SALT bucket in number of slots (256). +/// +/// Buckets hold accounts or storage slots and can grow beyond this size. The gas cost +/// multiplier is calculated as `capacity / MIN_BUCKET_SIZE`, so a bucket at minimum +/// capacity has a 1x multiplier. +pub const MIN_BUCKET_SIZE: usize = 1 << MIN_BUCKET_SIZE_BITS; + +/// Interface for SALT bucket capacity information. +/// +/// This trait provides bucket capacity data needed for dynamic gas pricing. Implementations +/// typically read from the underlying blockchain database to ensure deterministic execution. +/// +/// # Block-Awareness +/// +/// This trait does not take a block parameter. Block context is provided when the environment +/// is created via [`ExternalEnvFactory::external_envs`](crate::ExternalEnvFactory::external_envs), +/// allowing implementations to snapshot state at a specific block. +/// +/// # Bucket ID Calculation +/// +/// The trait provides default methods [`bucket_id_for_account`](SaltEnv::bucket_id_for_account) +/// and [`bucket_id_for_slot`](SaltEnv::bucket_id_for_slot) that can be overridden by +/// implementations to customize bucket assignment logic. +#[auto_impl(&, Box, Rc, Arc)] +pub trait SaltEnv: Debug + Unpin { + /// Error type returned when bucket capacity cannot be retrieved. + type Error: Display; + + /// Returns the current capacity of the specified bucket. + /// + /// # Gas Cost Calculation + /// + /// The returned capacity is used to calculate a gas multiplier: + /// ```text + /// multiplier = capacity / MIN_BUCKET_SIZE + /// ``` + /// This multiplier scales the base storage gas costs, making operations more expensive + /// as buckets grow. + /// + /// # Arguments + /// + /// * `bucket_id` - The bucket to query + /// + /// # Returns + /// + /// The bucket's capacity in number of slots, or an error if unavailable. + fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result; + + /// Maps an account address to its bucket ID. + /// + /// This method determines which bucket tracks the account creation gas costs. + /// The default implementation can be overridden to customize bucket assignment. + /// + /// # Arguments + /// + /// * `account` - The account address to map + fn bucket_id_for_account(account: Address) -> BucketId; + + /// Maps a storage slot to its bucket ID. + /// + /// This method determines which bucket tracks the storage slot's gas costs. + /// The default implementation can be overridden to customize bucket assignment. + /// + /// # Arguments + /// + /// * `address` - The contract address owning the storage + /// * `key` - The storage slot key + fn bucket_id_for_slot(address: Address, key: U256) -> BucketId; +} + +/// No-op implementation that returns minimum bucket size for all buckets. +/// +/// This implementation assigns all accounts and storage slots to bucket 0 with minimum +/// capacity, effectively disabling dynamic gas pricing. Useful for testing or when SALT +/// functionality is not needed. +impl SaltEnv for EmptyExternalEnv { + type Error = Infallible; + + fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { + Ok(MIN_BUCKET_SIZE as u64) + } + + fn bucket_id_for_account(_account: Address) -> BucketId { + 0 as BucketId + } + + fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { + 0 as BucketId + } +} diff --git a/crates/mega-evm/src/external/test_utils.rs b/crates/mega-evm/src/external/test_utils.rs new file mode 100644 index 000000000..04da5bb0d --- /dev/null +++ b/crates/mega-evm/src/external/test_utils.rs @@ -0,0 +1,308 @@ +//! In-memory external environment implementations. +//! +//! Provides [`TestExternalEnvs`], a configurable in-memory implementation of SALT and Oracle +//! environments backed by `HashMap`s. +//! Unlike [`EmptyExternalEnv`](crate::EmptyExternalEnv) which returns hardcoded defaults, +//! this implementation allows setting specific bucket capacities and oracle storage values. +//! +//! # Use Cases +//! +//! - **Unit and integration tests**: Configure bucket capacities and oracle storage to exercise +//! specific gas pricing and oracle access paths without a real database. +//! - **CLI tools** (e.g., `mega-evme`): Simulate EVM execution with user-specified bucket +//! capacities and oracle state, useful for offline transaction analysis and debugging. +//! - **Standalone EVM runners**: Any context where a full node database is unavailable but +//! controllable external environment state is needed. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{ + cell::RefCell, + convert::Infallible, + fmt::{Debug, Display}, +}; +use std::{rc::Rc, vec::Vec}; + +use alloy_primitives::{Address, BlockNumber, Bytes, B256, U256}; +use revm::primitives::HashMap; + +use crate::{BucketId, ExternalEnvFactory, ExternalEnvTypes, ExternalEnvs, OracleEnv, SaltEnv}; + +/// Strategy trait for computing bucket IDs from raw key bytes. +/// +/// Implementations determine how account addresses and storage slot keys are mapped to +/// SALT bucket IDs. The trait only requires a single static method, making it zero-cost +/// to parameterize [`TestExternalEnvs`] over different hashing strategies. +pub trait BucketHasher: Debug + Clone + Unpin + 'static { + /// Computes a bucket ID from the given key bytes. + fn bucket_id(key: &[u8]) -> BucketId; +} + +/// Simple deterministic hasher for tests. +/// +/// Uses FNV-1a to produce consistent bucket IDs. This is NOT the real SALT hash algorithm; +/// tests only need consistency (same input produces same output), not compatibility with +/// the production SALT trie. +#[derive(Debug, Clone, Copy)] +pub struct SimpleBucketHasher; + +impl BucketHasher for SimpleBucketHasher { + fn bucket_id(key: &[u8]) -> BucketId { + let mut hash: u64 = 0xcbf29ce484222325; + for &byte in key { + hash ^= byte as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + // Map to valid bucket range [NUM_META_BUCKETS, NUM_BUCKETS) + const NUM_BUCKETS: u64 = 1 << 24; // 16,777,216 + const NUM_META_BUCKETS: u64 = NUM_BUCKETS / 256; // 65,536 + const NUM_KV_BUCKETS: u64 = NUM_BUCKETS - NUM_META_BUCKETS; + (hash % NUM_KV_BUCKETS + NUM_META_BUCKETS) as BucketId + } +} + +/// A recorded oracle hint from `on_hint` calls. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RecordedHint { + /// The sender address who called `sendHint`. + pub from: Address, + /// The user-defined hint topic. + pub topic: B256, + /// The hint data. + pub data: Bytes, +} + +/// In-memory external environment implementation backed by `HashMap`s. +/// +/// Provides configurable SALT bucket capacities, oracle storage values, and oracle hint +/// recording, all stored in memory. +/// Suitable for unit tests, integration tests, CLI tools, and any standalone EVM execution +/// context where a real node database is unavailable. +/// +/// # Bucket Hashing +/// +/// The `Hasher` type parameter controls how account addresses and storage slot keys are +/// mapped to bucket IDs. +/// The default [`SimpleBucketHasher`] uses FNV-1a — sufficient for tests where only +/// consistency matters, not production compatibility. +/// For production-compatible bucket IDs (matching the `salt` crate), supply a hasher that +/// implements the real SALT hashing algorithm. +/// +/// # Example +/// ```ignore +/// let env = TestExternalEnvs::new() +/// .with_bucket_capacity(123, 512) // Set bucket 123 to 512 capacity +/// .with_oracle_storage(U256::ZERO, U256::from(42)); // Set oracle slot 0 to 42 +/// ``` +#[derive(derive_more::Debug, Clone)] +pub struct TestExternalEnvs { + #[debug(ignore)] + _phantom: core::marker::PhantomData<(Error, Hasher)>, + /// Oracle contract storage values. Maps storage slot keys to their values. + oracle_storage: Rc>>, + /// Bucket capacities. Maps bucket IDs to their capacity values. + /// Buckets not in this map default to [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE) or + /// `default_bucket_capacity` if set. + bucket_capacity: Rc>>, + /// Fallback capacity for buckets not in `bucket_capacity`. + /// When `None`, falls back to [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). + default_bucket_capacity: Rc>>, + /// Recorded hints from `on_hint` calls. Used for testing the hint mechanism. + recorded_hints: Rc>>, +} + +impl Default for TestExternalEnvs { + fn default() -> Self { + Self::new() + } +} + +impl From> + for ExternalEnvs> +{ + fn from(value: TestExternalEnvs) -> Self { + Self { salt_env: value.clone(), oracle_env: value } + } +} + +impl<'a, H: BucketHasher> From<&'a TestExternalEnvs> + for ExternalEnvs<&'a TestExternalEnvs> +{ + fn from(value: &'a TestExternalEnvs) -> Self { + ExternalEnvs { salt_env: value.clone(), oracle_env: value.clone() } + } +} + +impl + TestExternalEnvs +{ + /// Creates a new environment with empty bucket capacity and oracle storage. + pub fn new() -> Self { + Self { + _phantom: core::marker::PhantomData, + oracle_storage: Rc::new(RefCell::new(HashMap::default())), + bucket_capacity: Rc::new(RefCell::new(HashMap::default())), + default_bucket_capacity: Rc::new(RefCell::new(None)), + recorded_hints: Rc::new(RefCell::new(Vec::new())), + } + } + + /// Returns all recorded hints from `on_hint` calls. + /// + /// This is useful for testing that the hint mechanism is working correctly. + pub fn recorded_hints(&self) -> Vec { + self.recorded_hints.borrow().clone() + } + + /// Clears all recorded hints. + pub fn clear_recorded_hints(&self) { + self.recorded_hints.borrow_mut().clear(); + } + + /// Configures a bucket to have a specific capacity. + /// + /// This affects the gas multiplier calculation for operations on accounts or storage + /// slots mapped to this bucket. The multiplier will be `capacity / MIN_BUCKET_SIZE`. + /// + /// # Arguments + /// + /// * `bucket_id` - The bucket ID to configure + /// * `capacity` - The bucket capacity in number of slots + /// + /// # Returns + /// + /// `self` for method chaining + pub fn with_bucket_capacity(self, bucket_id: BucketId, capacity: u64) -> Self { + self.bucket_capacity.borrow_mut().insert(bucket_id, capacity); + self + } + + /// Sets a fallback capacity returned for every bucket not configured via + /// [`with_bucket_capacity`]. Lets a bench exercise the dynamic-gas multiplier + /// without computing the bucket id of each touched slot. + pub fn with_default_bucket_capacity(self, capacity: u64) -> Self { + *self.default_bucket_capacity.borrow_mut() = Some(capacity); + self + } + + /// Removes all configured bucket capacities. + /// + /// After calling this, all buckets will return the configured `default_bucket_capacity` if + /// set, otherwise [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). + pub fn clear_bucket_capacity(&self) { + self.bucket_capacity.borrow_mut().clear(); + } + + /// Configures a storage slot in the oracle contract to have a specific value. + /// + /// # Arguments + /// + /// * `slot` - The storage slot key + /// * `value` - The value to store + /// + /// # Returns + /// + /// `self` for method chaining + pub fn with_oracle_storage(self, slot: U256, value: U256) -> Self { + self.oracle_storage.borrow_mut().insert(slot, value); + self + } + + /// Removes all configured oracle storage values. + /// + /// After calling this, all oracle storage queries will return `None`. + pub fn clear_oracle_storage(&self) { + self.oracle_storage.borrow_mut().clear(); + } + + /// Returns the configured bucket capacities as `(bucket_id, capacity)` pairs. + /// + /// Used to snapshot the effective external environment into a self-validating + /// fixture. + pub fn bucket_capacities(&self) -> Vec<(BucketId, u64)> { + self.bucket_capacity.borrow().iter().map(|(&id, &cap)| (id, cap)).collect() + } + + /// Returns the configured oracle storage as `(slot, value)` pairs. + /// + /// Used to snapshot the effective external environment into a self-validating + /// fixture. + pub fn oracle_storage(&self) -> Vec<(U256, U256)> { + self.oracle_storage.borrow().iter().map(|(&slot, &value)| (slot, value)).collect() + } +} + +impl ExternalEnvFactory + for TestExternalEnvs +{ + type EnvTypes = Self; + + fn external_envs(&self, _block: BlockNumber) -> ExternalEnvs { + ExternalEnvs { salt_env: self.clone(), oracle_env: self.clone() } + } +} + +impl ExternalEnvTypes + for TestExternalEnvs +{ + type SaltEnv = Self; + + type OracleEnv = Self; +} + +/// Length of a storage slot key in bytes (32 bytes for U256). +const SLOT_KEY_LEN: usize = B256::len_bytes(); +/// Length of an account address in bytes (20 bytes). +const PLAIN_ACCOUNT_KEY_LEN: usize = Address::len_bytes(); +/// Length of a combined address+slot key (52 bytes = 20 + 32). +const PLAIN_STORAGE_KEY_LEN: usize = PLAIN_ACCOUNT_KEY_LEN + SLOT_KEY_LEN; + +/// SALT environment implementation with configurable bucket ID hashing. +impl SaltEnv for TestExternalEnvs { + type Error = Error; + + fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result { + Ok(self.bucket_capacity.borrow().get(&bucket_id).copied().unwrap_or_else(|| { + self.default_bucket_capacity.borrow().unwrap_or(crate::MIN_BUCKET_SIZE as u64) + })) + } + + fn bucket_id_for_account(account: Address) -> BucketId { + Hasher::bucket_id(account.as_slice()) + } + + fn bucket_id_for_slot(address: Address, key: U256) -> BucketId { + Hasher::bucket_id( + address.concat_const::(key.into()).as_slice(), + ) + } +} + +impl OracleEnv for TestExternalEnvs { + fn get_oracle_storage(&self, slot: U256) -> Option { + self.oracle_storage.borrow().get(&slot).copied() + } + + fn on_hint(&self, from: Address, topic: B256, data: Bytes) { + self.recorded_hints.borrow_mut().push(RecordedHint { from, topic, data }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_with_default_bucket_capacity_applies_to_all_buckets() { + use crate::external::salt::SaltEnv; + let env = + TestExternalEnvs::::new().with_default_bucket_capacity(2048); + // Any bucket id not explicitly configured now returns the default, not MIN_BUCKET_SIZE. + assert_eq!(env.get_bucket_capacity(123), Ok(2048)); + assert_eq!(env.get_bucket_capacity(999), Ok(2048)); + // An explicit per-bucket capacity still wins. + let env = env.with_bucket_capacity(123, 512); + assert_eq!(env.get_bucket_capacity(123), Ok(512)); + assert_eq!(env.get_bucket_capacity(999), Ok(2048)); + } +} diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 6e9a0e7dc..a5399470d 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -8,6 +8,8 @@ extern crate alloc; mod block; mod evm; +mod external; pub use block::*; pub use evm::*; +pub use external::*; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 16a46b126..948d432b3 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -25,11 +25,11 @@ Do not add a `_pending/main.rs`. | Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | |---|---:|---:|---:|---:|---:|---:| -| T2.1 | 18 | 0 | 18 | 15 | 3 | 0 | +| T2.1 | 16 | 0 | 16 | 13 | 3 | 0 | | T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | | T2.3 | 40 | 19 | 21 | 21 | 19 | 0 | | T3.1 | 36 | 30 | 6 | 7 | 29 | 0 | -| T3.2 | 87 | 72 | 15 | 29 | 58 | 0 | +| T3.2 | 82 | 72 | 10 | 24 | 58 | 0 | | T3.3 | 28 | 24 | 4 | 4 | 24 | 0 | | T3.4 | 27 | 27 | 0 | 0 | 27 | 0 | | T4.1 | 49 | 47 | 2 | 42 | 7 | 0 | @@ -44,7 +44,7 @@ Do not add a `_pending/main.rs`. | T8.1 | 74 | 45 | 29 | 55 | 19 | 0 | | T9 | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **869** | **691** | **178** | **516** | **324** | **29** | +| **Total** | **862** | **691** | **171** | **509** | **324** | **29** | ## Files @@ -148,9 +148,6 @@ Each cell lists `disposition count (ticket · decision)`. | `src/evm/result.rs` | 4 | 重写 4 (T2.3 · D17/D48 (halt-reason set changes)) | | `src/evm/state.rs` | 1 | 保留 1 (T8.1) | | `src/external/gas.rs` | 9 | 重写 9 (T3.2 · D12/D51) | -| `src/external/hasher/mod.rs` | 5 | 保留 5 (T3.2) | -| `src/external/mod.rs` | 1 | 保留 1 (T2.1) | -| `src/external/test_utils.rs` | 1 | 保留 1 (T2.1) | | `src/limit/compute_gas.rs` | 1 | 重写 1 (T4.2 · D40/D48) | | `src/limit/data_size.rs` | 2 | 保留 2 (T4.1) | | `src/limit/frame_limit.rs` | 4 | 重写 4 (T2.3 · data-size-only per-frame tracker) | diff --git a/crates/mega-evm/tests/_pending/src/external/mod.rs b/crates/mega-evm/tests/_pending/src/external/mod.rs deleted file mode 100644 index 75955b551..000000000 --- a/crates/mega-evm/tests/_pending/src/external/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/external/mod.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/mod.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::{OracleEnv, SaltEnv, MIN_BUCKET_SIZE}; - use alloy_primitives::{Address, Bytes, B256, U256}; - - #[test] - fn test_empty_external_env_factory_returns_minimum_bucket_and_no_oracle() { - let envs = EmptyExternalEnv.external_envs(42); - - assert_eq!(envs.salt_env.get_bucket_capacity(123).unwrap(), MIN_BUCKET_SIZE as u64); - assert_eq!(envs.oracle_env.get_oracle_storage(U256::from(7)), None); - envs.oracle_env.on_hint(Address::ZERO, B256::ZERO, Bytes::new()); - assert_eq!(::bucket_id_for_account(Address::ZERO), 0); - assert_eq!(::bucket_id_for_slot(Address::ZERO, U256::ZERO), 0); - } -} diff --git a/crates/mega-evm/tests/_pending/src/external/test_utils.rs b/crates/mega-evm/tests/_pending/src/external/test_utils.rs deleted file mode 100644 index e4d802cba..000000000 --- a/crates/mega-evm/tests/_pending/src/external/test_utils.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/external/test_utils.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/test_utils.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_with_default_bucket_capacity_applies_to_all_buckets() { - use crate::external::salt::SaltEnv; - let env = - TestExternalEnvs::::new().with_default_bucket_capacity(2048); - // Any bucket id not explicitly configured now returns the default, not MIN_BUCKET_SIZE. - assert_eq!(env.get_bucket_capacity(123), Ok(2048)); - assert_eq!(env.get_bucket_capacity(999), Ok(2048)); - // An explicit per-bucket capacity still wins. - let env = env.with_bucket_capacity(123, 512); - assert_eq!(env.get_bucket_capacity(123), Ok(512)); - assert_eq!(env.get_bucket_capacity(999), Ok(2048)); - } -} From ead9335dca115b1becad333fa51318bcc5d5df69 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:48:07 +0800 Subject: [PATCH 006/201] feat: add the provisional constants table and the shared types constants.rs holds the Satin placeholders in one table, each marked provisional: CPSB 1,530 (slot 97,920, account 183,600), CPHB 88, the 200,000,000 execution cap and the Rex6 data-size limits. types.rs names the transaction, halt reason, error and envelope types. The transaction is alloy-op-evm's OpTx, which carries the signed-tx conversions the node's block executor uses, so the core now depends on alloy-op-evm (its op-revm edge resolves to the op-revm fork). --- Cargo.lock | 1669 ++++++++++++++++++++++++++++-- crates/mega-evm/Cargo.toml | 9 +- crates/mega-evm/src/constants.rs | 61 ++ crates/mega-evm/src/lib.rs | 3 + crates/mega-evm/src/types.rs | 22 + 5 files changed, 1678 insertions(+), 86 deletions(-) create mode 100644 crates/mega-evm/src/constants.rs create mode 100644 crates/mega-evm/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index cd249dfae..60ff93aa3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -31,13 +31,13 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "alloy-chains" -version = "0.2.6" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4195a29a4b87137b2bb02105e746102873bc03561805cf45c0e510c961f160e6" +checksum = "c1c4f6f6f020f38a4ef079428b5c7009e913bf8102e4d65a90c6cb2cf93800eb" dependencies = [ "alloy-primitives", "num_enum", - "strum", + "phf 0.14.0", ] [[package]] @@ -152,6 +152,8 @@ dependencies = [ "c-kzg", "derive_more", "either", + "ethereum_ssz", + "ethereum_ssz_derive", "serde", "serde_with", "sha2", @@ -167,6 +169,8 @@ dependencies = [ "alloy-eips", "alloy-hardforks", "alloy-primitives", + "alloy-rpc-types-engine", + "alloy-rpc-types-eth", "alloy-sol-types", "auto_impl", "derive_more", @@ -175,6 +179,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "alloy-genesis" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0680a2f7d4bbc6f48c0cb43368fa544918a1fa291e772bdb47c834ade338f363" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-serde", + "alloy-trie", + "borsh", + "serde", + "serde_with", +] + [[package]] name = "alloy-hardforks" version = "0.4.8" @@ -200,6 +219,47 @@ dependencies = [ "serde_json", ] +[[package]] +name = "alloy-json-rpc" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a523ca087dda941e53f6ecde5bf5df78b9dbe760f3f77488e13dbf355de4a84" +dependencies = [ + "alloy-primitives", + "alloy-sol-types", + "http", + "serde", + "serde_json", + "thiserror", + "tracing", +] + +[[package]] +name = "alloy-network" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f263c8d752b15e19b7c2d3cbad00338ec2d7cc923a46cd1ff98aea2fa333166b" +dependencies = [ + "alloy-consensus", + "alloy-consensus-any", + "alloy-eips", + "alloy-json-rpc", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-types-any", + "alloy-rpc-types-eth", + "alloy-serde", + "alloy-signer", + "alloy-sol-types", + "async-trait", + "auto_impl", + "derive_more", + "futures-utils-wasm", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "alloy-network-primitives" version = "2.4.2" @@ -213,6 +273,34 @@ dependencies = [ "serde", ] +[[package]] +name = "alloy-op-evm" +version = "0.32.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-evm", + "alloy-op-hardforks", + "alloy-primitives", + "auto_impl", + "op-alloy", + "op-revm", + "revm", + "thiserror", +] + +[[package]] +name = "alloy-op-hardforks" +version = "0.5.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-chains", + "alloy-hardforks", + "alloy-primitives", + "auto_impl", +] + [[package]] name = "alloy-primitives" version = "1.6.0" @@ -241,6 +329,48 @@ dependencies = [ "sha3", ] +[[package]] +name = "alloy-provider" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef487e44dfae9c87cb732989d3f43682f65aefb11a0f56045b26be357f671fcf" +dependencies = [ + "alloy-chains", + "alloy-consensus", + "alloy-eips", + "alloy-json-rpc", + "alloy-network", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-client", + "alloy-rpc-types-debug", + "alloy-rpc-types-eth", + "alloy-rpc-types-trace", + "alloy-signer", + "alloy-sol-types", + "alloy-transport", + "alloy-transport-http", + "async-stream", + "async-trait", + "auto_impl", + "dashmap", + "either", + "futures", + "futures-utils-wasm", + "http", + "lru", + "parking_lot", + "pin-project", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", + "url", + "wasmtimer", +] + [[package]] name = "alloy-rlp" version = "0.3.16" @@ -263,6 +393,76 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "alloy-rpc-client" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98267c2d47f9c185b575bac3f772a8ca66bcbd712693535e50980c12eab80a42" +dependencies = [ + "alloy-json-rpc", + "alloy-primitives", + "alloy-transport", + "alloy-transport-http", + "futures", + "pin-project", + "reqwest", + "serde", + "serde_json", + "tokio", + "tokio-stream", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-rpc-types-any" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1176430031ba27abfb51b95516cf71e8ce3ff4172c72f3136627f0f89813a739" +dependencies = [ + "alloy-consensus-any", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-serde", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-rpc-types-debug" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a97960aa11b9984a18580b8dfbfc3eacfce1befa0d588b03ccc0bc5563d01f8" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "derive_more", + "serde", + "serde_with", +] + +[[package]] +name = "alloy-rpc-types-engine" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a43d7b6b86be4885c7a76f1dfcde9651af2d419ff571e8ee7257de47101203b" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "derive_more", + "ethereum_ssz", + "ethereum_ssz_derive", + "rand 0.8.5", + "serde", + "strum", +] + [[package]] name = "alloy-rpc-types-eth" version = "2.4.2" @@ -309,6 +509,21 @@ dependencies = [ "serde_json", ] +[[package]] +name = "alloy-signer" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c84f88f8a29d2607f98993687ed55a5943ba06819bc2126bb078dca54be943" +dependencies = [ + "alloy-primitives", + "async-trait", + "auto_impl", + "either", + "elliptic-curve", + "k256", + "thiserror", +] + [[package]] name = "alloy-sol-macro" version = "1.6.0" @@ -379,6 +594,45 @@ dependencies = [ "serde", ] +[[package]] +name = "alloy-transport" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" +dependencies = [ + "alloy-json-rpc", + "auto_impl", + "base64 0.22.1", + "derive_more", + "futures", + "futures-utils-wasm", + "parking_lot", + "serde", + "serde_json", + "thiserror", + "tokio", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-transport-http" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" +dependencies = [ + "alloy-json-rpc", + "alloy-transport", + "itertools 0.14.0", + "reqwest", + "serde_json", + "tower", + "tracing", + "url", +] + [[package]] name = "alloy-trie" version = "0.9.5" @@ -751,6 +1005,45 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "aurora-engine-modexp" version = "1.2.0" @@ -790,6 +1083,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.0" @@ -827,6 +1126,12 @@ dependencies = [ "hex-conservative", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.11.1" @@ -903,6 +1208,15 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -958,6 +1272,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1207,6 +1523,18 @@ dependencies = [ "itertools 0.10.5", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "crunchy" version = "0.2.4" @@ -1244,16 +1572,6 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "darling" -version = "0.21.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" -dependencies = [ - "darling_core 0.21.3", - "darling_macro 0.21.3", -] - [[package]] name = "darling" version = "0.23.0" @@ -1265,17 +1583,13 @@ dependencies = [ ] [[package]] -name = "darling_core" -version = "0.21.3" +name = "darling" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.104", + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -1293,14 +1607,16 @@ dependencies = [ ] [[package]] -name = "darling_macro" -version = "0.21.3" +name = "darling_core" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" dependencies = [ - "darling_core 0.21.3", + "ident_case", + "proc-macro2", "quote", - "syn 2.0.104", + "strsim", + "syn 3.0.6", ] [[package]] @@ -1315,29 +1631,85 @@ dependencies = [ ] [[package]] -name = "delegate" -version = "0.13.4" +name = "darling_macro" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6178a82cf56c836a3ba61a7935cdb1c49bfaa6fa4327cd5bf554a503087de26b" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ - "proc-macro2", + "darling_core 0.24.1", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] -name = "der" -version = "0.7.10" +name = "dashmap" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" dependencies = [ - "const-oid", - "zeroize", + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", ] [[package]] -name = "deranged" -version = "0.5.3" +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + +[[package]] +name = "delegate" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6178a82cf56c836a3ba61a7935cdb1c49bfaa6fa4327cd5bf554a503087de26b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d630bccd429a5bb5a64b5e94f693bfc48c9f8566418fda4c494cc94f911f87cc" dependencies = [ @@ -1421,6 +1793,17 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "dunce" version = "1.0.5" @@ -1525,6 +1908,46 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "ethereum_serde_utils" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38df44a7a271ab43835678f9215b53cc2523e4714a215da6643d83dc110245da" +dependencies = [ + "alloy-primitives", + "hex", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "ethereum_ssz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e462875ad8693755ea8913d6e905715c76ea4836e2254e18c9cf0f7a8f8c2a13" +dependencies = [ + "alloy-primitives", + "ethereum_serde_utils", + "itertools 0.14.0", + "serde", + "serde_derive", + "smallvec", + "typenum", +] + +[[package]] +name = "ethereum_ssz_derive" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf022360bdbe9456eda5f35718a50476d5b2a0d51a97ed4eae27420737a6fba" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "fastrand" version = "2.3.0" @@ -1593,12 +2016,115 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "funty" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "futures-utils-wasm" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" + [[package]] name = "generic-array" version = "0.14.7" @@ -1677,6 +2203,12 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.4" @@ -1692,6 +2224,8 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", + "equivalent", "foldhash", "serde", "serde_core", @@ -1736,6 +2270,45 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "hybrid-array" version = "0.4.12" @@ -1745,6 +2318,49 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.63" @@ -1769,12 +2385,116 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "impl-codec" version = "0.6.0" @@ -1817,6 +2537,12 @@ dependencies = [ "serde", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is-terminal" version = "0.4.16" @@ -1861,6 +2587,70 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "jiff" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.77" @@ -1929,12 +2719,36 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" +[[package]] +name = "lru" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "macro-string" version = "0.2.0" @@ -1953,6 +2767,7 @@ dependencies = [ "alloy-consensus", "alloy-evm", "alloy-hardforks", + "alloy-op-evm", "alloy-primitives", "alloy-sol-types", "auto_impl", @@ -1986,13 +2801,45 @@ version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "modular-bitfield" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2956e537fc68236d2aa048f55704f231cc93f1c4de42fe1ecb5bd7938061fc4a" +dependencies = [ + "modular-bitfield-impl", + "static_assertions", +] + +[[package]] +name = "modular-bitfield-impl" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b43b4fd69e3437618106f7754f34021b831a514f9e1a98ae863cabcd8d8dad" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "nix" version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.11.1", "cfg-if", "cfg_aliases", "libc", @@ -2137,6 +2984,10 @@ name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +dependencies = [ + "critical-section", + "portable-atomic", +] [[package]] name = "oorandom" @@ -2144,6 +2995,18 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "op-alloy" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "op-alloy-consensus", + "op-alloy-network", + "op-alloy-provider", + "op-alloy-rpc-types", + "op-alloy-rpc-types-engine", +] + [[package]] name = "op-alloy-consensus" version = "2.0.0" @@ -2151,9 +3014,84 @@ source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b6 dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-network", "alloy-primitives", "alloy-rlp", + "alloy-rpc-types-eth", + "alloy-serde", + "bytes", + "derive_more", + "reth-codecs", + "reth-zstd-compressors", + "serde", + "serde_with", + "thiserror", +] + +[[package]] +name = "op-alloy-network" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-provider", + "alloy-rpc-types-eth", + "op-alloy-consensus", + "op-alloy-rpc-types", +] + +[[package]] +name = "op-alloy-provider" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-network", + "alloy-primitives", + "alloy-provider", + "alloy-rpc-types-engine", + "alloy-transport", + "async-trait", + "op-alloy-rpc-types-engine", +] + +[[package]] +name = "op-alloy-rpc-types" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-network", + "alloy-network-primitives", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-serde", "derive_more", + "op-alloy-consensus", + "reth-rpc-traits", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "op-alloy-rpc-types-engine" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-engine", + "alloy-serde", + "ethereum_ssz", + "ethereum_ssz_derive", + "op-alloy-consensus", + "serde", + "sha2", + "snap", "thiserror", ] @@ -2188,6 +3126,7 @@ dependencies = [ "arrayvec", "bitvec", "byte-slice-cast", + "bytes", "const_format", "impl-trait-for-tuples", "parity-scale-codec-derive", @@ -2207,12 +3146,41 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + [[package]] name = "paste" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pest" version = "2.8.1" @@ -2231,10 +3199,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ "phf_macros", - "phf_shared", + "phf_shared 0.13.1", "serde", ] +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_shared 0.14.0", +] + [[package]] name = "phf_generator" version = "0.13.1" @@ -2242,7 +3219,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.13.1", ] [[package]] @@ -2252,7 +3229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.104", @@ -2267,12 +3244,47 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + [[package]] name = "pkcs8" version = "0.10.2" @@ -2283,6 +3295,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "plotters" version = "0.3.7" @@ -2311,6 +3329,30 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -2394,7 +3436,7 @@ checksum = "6fcdab19deb5195a31cf7726a210015ff1496ba1464fd42cb4f537b8b01b471f" dependencies = [ "bit-set", "bit-vec", - "bitflags", + "bitflags 2.11.1", "lazy_static", "num-traits", "rand 0.9.4", @@ -2414,9 +3456,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" -version = "1.0.40" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -2519,6 +3561,15 @@ dependencies = [ "rustversion", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.11.1", +] + [[package]] name = "ref-cast" version = "1.0.24" @@ -2532,7 +3583,97 @@ dependencies = [ name = "ref-cast-impl" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7" +checksum = "1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "regex" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "reth-codecs" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c37bb4d1bac98661bf9128e1141b969034640d68697b22f70377e492fd332c" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-trie", + "bytes", + "modular-bitfield", + "parity-scale-codec", + "reth-codecs-derive", + "reth-zstd-compressors", + "serde", +] + +[[package]] +name = "reth-codecs-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ceeb8dab90194305d3f7e3f043a22d2db1fb54b6dcf5d8e75c5a4fa8540e1f57" dependencies = [ "proc-macro2", "quote", @@ -2540,33 +3681,52 @@ dependencies = [ ] [[package]] -name = "regex" -version = "1.11.3" +name = "reth-primitives-traits" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c" +checksum = "9102518f0bbf99bc8f0e656a56fb2a7513248630275b608d3706076a82fde42b" dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-eth", + "alloy-trie", + "bytes", + "derive_more", + "once_cell", + "revm-bytecode", + "revm-primitives", + "revm-state", + "secp256k1 0.30.0", + "serde", + "thiserror", ] [[package]] -name = "regex-automata" -version = "0.4.11" +name = "reth-rpc-traits" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad" +checksum = "9fa03a2c9681c385ae1c72b169ac9c3525163b71db0b3362f16e8929e19e45fd" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-signer", + "reth-primitives-traits", + "thiserror", ] [[package]] -name = "regex-syntax" -version = "0.8.5" +name = "reth-zstd-compressors" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +checksum = "dc0e86cf594718932d42cebce1fa48292fb7b92721f7c914631add1ca970e814" +dependencies = [ + "zstd", +] [[package]] name = "revm" @@ -2592,7 +3752,7 @@ version = "11.0.1" source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", - "phf", + "phf 0.13.1", "revm-primitives", "serde", ] @@ -2760,7 +3920,7 @@ version = "12.0.1" source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip7928", - "bitflags", + "bitflags 2.11.1", "nonmax", "revm-bytecode", "revm-primitives", @@ -2866,7 +4026,7 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ - "bitflags", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys", @@ -2891,12 +4051,6 @@ dependencies = [ "wait-timeout", ] -[[package]] -name = "ryu" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" - [[package]] name = "same-file" version = "1.0.6" @@ -2930,6 +4084,12 @@ dependencies = [ "serde_json", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "sec1" version = "0.7.3" @@ -3045,32 +4205,34 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ "indexmap 2.10.0", "itoa", "memchr", - "ryu", "serde", + "serde_core", + "zmij", ] [[package]] name = "serde_with" -version = "3.14.1" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c522100790450cf78eeac1507263d0a350d4d5b30df0c8e1fe051a10c22b376e" +checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" dependencies = [ - "base64", + "base64 0.23.1", + "bs58", "chrono", "hex", "indexmap 1.9.3", "indexmap 2.10.0", + "jiff", "schemars 0.9.0", "schemars 1.0.4", - "serde", - "serde_derive", + "serde_core", "serde_json", "serde_with_macros", "time", @@ -3078,14 +4240,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.14.1" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327ada00f7d64abaac1e55a6911e90cf665aa051b9a561c7006c157f4633135e" +checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" dependencies = [ - "darling 0.21.3", + "darling 0.24.1", "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] @@ -3151,6 +4313,12 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.15.1" @@ -3160,6 +4328,22 @@ dependencies = [ "serde", ] +[[package]] +name = "snap" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "spki" version = "0.7.3" @@ -3170,6 +4354,12 @@ dependencies = [ "der", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "static_assertions" version = "1.1.0" @@ -3264,6 +4454,26 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "tap" version = "1.0.1" @@ -3343,6 +4553,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -3353,6 +4573,62 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml_datetime" version = "0.6.11" @@ -3370,6 +4646,51 @@ dependencies = [ "winnow 0.7.12", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.11.1", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.41" @@ -3411,6 +4732,12 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.0" @@ -3459,6 +4786,25 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "valuable" version = "0.1.1" @@ -3490,6 +4836,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -3531,6 +4886,19 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.100" @@ -3563,6 +4931,20 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasmtimer" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c598d6b99ea013e35844697fc4670d08339d5cda15588f193c6beedd12f644b" +dependencies = [ + "futures", + "js-sys", + "parking_lot", + "pin-utils", + "slab", + "wasm-bindgen", +] + [[package]] name = "web-sys" version = "0.3.77" @@ -3826,9 +5208,15 @@ version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "wyz" version = "0.5.1" @@ -3838,6 +5226,29 @@ dependencies = [ "tap", ] +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.26" @@ -3858,6 +5269,27 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + [[package]] name = "zeroize" version = "1.8.1" @@ -3877,3 +5309,70 @@ dependencies = [ "quote", "syn 2.0.104", ] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index feaf570e9..635dbcd1f 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -17,6 +17,7 @@ workspace = true alloy-consensus = { workspace = true, features = ["k256"] } alloy-evm.workspace = true alloy-hardforks.workspace = true +alloy-op-evm.workspace = true alloy-primitives.workspace = true alloy-sol-types.workspace = true op-alloy-consensus.workspace = true @@ -46,5 +47,11 @@ serde_json = { workspace = true, features = ["std"] } [features] default = ["std", "revm/default", "op-revm/default"] -std = ["revm/std", "op-revm/std", "mega-system-contracts/std"] +std = [ + "alloy-evm/std", + "alloy-op-evm/std", + "mega-system-contracts/std", + "op-revm/std", + "revm/std", +] test-utils = [] diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs new file mode 100644 index 000000000..6e39a0d76 --- /dev/null +++ b/crates/mega-evm/src/constants.rs @@ -0,0 +1,61 @@ +//! Numeric constants of the Satin engine. +//! +//! Every value is *provisional*: the numbers follow the default candidate of the Satin work +//! order and stay open until the economics sign-off. A constant that no code reads yet is here +//! so the whole placeholder set can be reviewed in one place. +//! +//! | Constant | Value | Meaning | Read from | +//! |---|---:|---|---| +//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | T3.1 | +//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | T3.1 | +//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | T3.1 | +//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | T3.3 | +//! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | now | +//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | T4.1 | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | T4.1 | +//! +//! The storage call stipend and the per-transaction and per-block state-gas limits are further +//! placeholders; T3.3 and T4.3 add them with the mechanisms that read them. + +use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; + +/// Gas per byte of new state, the EIP-8037 `COST_PER_STATE_BYTE`. Provisional. +pub const COST_PER_STATE_BYTE: u64 = 1_530; + +/// State gas of one new storage slot: the EIP-8037 slot size times +/// [`COST_PER_STATE_BYTE`]. Provisional. +pub const SLOT_STATE_GAS: u64 = SSTORE_SET_BYTES * COST_PER_STATE_BYTE; + +/// State gas of one new account: the EIP-8037 account size times +/// [`COST_PER_STATE_BYTE`]. Provisional. +pub const ACCOUNT_STATE_GAS: u64 = NEW_ACCOUNT_BYTES * COST_PER_STATE_BYTE; + +/// Gas per history byte (logs, deployed code, write records, transaction body). Provisional. +pub const COST_PER_HISTORY_BYTE: u64 = 88; + +/// The execution cap: the most regular gas one transaction may spend. Gas above it goes to +/// the EIP-8037 state-gas reservoir. Provisional. +pub const TX_GAS_LIMIT_CAP: u64 = 200_000_000; + +/// The most data one transaction may produce, 12.5 MiB as in Rex6. Provisional. +pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; + +/// The most data one block may produce, 12.5 MiB as in Rex6. Provisional. +pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; + +#[cfg(test)] +mod tests { + use super::*; + + /// The placeholder values as the Satin work order states them (candidate 1). + #[test] + fn test_provisional_values_match_the_work_order() { + assert_eq!(COST_PER_STATE_BYTE, 1_530); + assert_eq!(SLOT_STATE_GAS, 97_920); + assert_eq!(ACCOUNT_STATE_GAS, 183_600); + assert_eq!(COST_PER_HISTORY_BYTE, 88); + assert_eq!(TX_GAS_LIMIT_CAP, 200_000_000); + assert_eq!(TX_DATA_LIMIT, 13_107_200); + assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); + } +} diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index a5399470d..d7e437226 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -7,9 +7,12 @@ extern crate alloc; mod block; +pub mod constants; mod evm; mod external; +mod types; pub use block::*; pub use evm::*; pub use external::*; +pub use types::*; diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs new file mode 100644 index 000000000..a2588c7c4 --- /dev/null +++ b/crates/mega-evm/src/types.rs @@ -0,0 +1,22 @@ +//! Common type definitions of the Satin engine. +//! +//! The result and error types are aliases of the OP ones for now; T2.3 decides the result and +//! gas types the engine exposes. + +/// `MegaETH` transaction as the EVM executes it. +/// +/// It is alloy-op-evm's wrapper of [`op_revm::OpTransaction`], which carries the conversions +/// from signed transactions that the node's block executor needs. +pub type MegaTransaction = alloy_op_evm::OpTx; + +/// Why a transaction halted. +pub type MegaHaltReason = op_revm::OpHaltReason; + +/// Transaction validation error, as the alloy-evm interface reports it. +pub type MegaTransactionError = alloy_op_evm::OpTxError; + +/// `MegaETH` transaction type. +pub type MegaTxType = op_alloy_consensus::OpTxType; + +/// `MegaETH` transaction envelope type. +pub type MegaTxEnvelope = op_alloy_consensus::OpTxEnvelope; From 4a620d1e4ef7acf948c3e63f2fbbb751f78ba913 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:49:02 +0800 Subject: [PATCH 007/201] test: carry the test utilities over MemoryDatabase, ErrorInjectingDatabase, BytecodeBuilder, GasInspector and right_pad_bytes come back from the legacy core; the only change is the DatabaseCommit signature, which takes EvmState on revm 40. transact() and the BytecodeBuilder execution tests follow with the engine. --- crates/mega-evm/src/lib.rs | 2 + crates/mega-evm/src/test_utils/bytes.rs | 10 + crates/mega-evm/src/test_utils/database.rs | 195 +++++++++++ crates/mega-evm/src/test_utils/inspectors.rs | 343 +++++++++++++++++++ crates/mega-evm/src/test_utils/mod.rs | 11 + crates/mega-evm/src/test_utils/opcode_gen.rs | 159 +++++++++ 6 files changed, 720 insertions(+) create mode 100644 crates/mega-evm/src/test_utils/bytes.rs create mode 100644 crates/mega-evm/src/test_utils/database.rs create mode 100644 crates/mega-evm/src/test_utils/inspectors.rs create mode 100644 crates/mega-evm/src/test_utils/mod.rs create mode 100644 crates/mega-evm/src/test_utils/opcode_gen.rs diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index d7e437226..505a9a6bd 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -10,6 +10,8 @@ mod block; pub mod constants; mod evm; mod external; +#[cfg(any(test, feature = "test-utils"))] +pub mod test_utils; mod types; pub use block::*; diff --git a/crates/mega-evm/src/test_utils/bytes.rs b/crates/mega-evm/src/test_utils/bytes.rs new file mode 100644 index 000000000..1432aca19 --- /dev/null +++ b/crates/mega-evm/src/test_utils/bytes.rs @@ -0,0 +1,10 @@ +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +/// Pads the bytes to the right with 0s to make it a multiple of the length. +pub fn right_pad_bytes(bytes: impl AsRef<[u8]>, multiple_of: usize) -> Vec { + let bytes = bytes.as_ref().to_vec(); + let padding = (multiple_of - (bytes.len() % multiple_of)) % multiple_of; + [bytes, vec![0u8; padding]].concat() +} diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs new file mode 100644 index 000000000..47afb46ca --- /dev/null +++ b/crates/mega-evm/src/test_utils/database.rs @@ -0,0 +1,195 @@ +use core::convert::Infallible; + +use alloy_primitives::{Address, Bytes, B256, U256}; +use delegate::delegate; +use revm::{ + database::{AccountState, CacheDB, DBErrorMarker, EmptyDB}, + primitives::{StorageKey, StorageValue}, + state::{AccountInfo, Bytecode, EvmState}, +}; + +/// A memory database for testing purposes. +#[derive(Debug, Default, Clone, derive_more::Deref, derive_more::DerefMut)] +pub struct MemoryDatabase { + #[deref] + #[deref_mut] + db: CacheDB, +} + +impl MemoryDatabase { + /// Creates a new `MemoryDatabase` from a `CacheDB`. + pub fn from_cache_db(db: CacheDB) -> Self { + Self { db } + } + + /// Sets the code for an account in the database. + pub fn set_account_code(&mut self, address: Address, code: Bytes) { + let bytecode = Bytecode::new_legacy(code); + let code_hash = bytecode.hash_slow(); + let account_info = self.db.load_account(address).unwrap(); + account_info.info.code = Some(bytecode); + account_info.info.code_hash = code_hash; + account_info.account_state = AccountState::None; + } + + /// Sets the code for an account in the database. + pub fn account_code(mut self, address: Address, code: Bytes) -> Self { + self.set_account_code(address, code); + self + } + + /// Installs an account whose code is *lazy*: `basic()` returns `code: None` with `code_hash` + /// set, so loading the code requires a `code_by_hash` call. Mirrors production reth's + /// `StateProviderDatabase::basic`, which defers code loading. Lets a code-load failure be + /// exercised independently of `basic()`. + pub fn account_lazy_code(mut self, address: Address, code_hash: B256) -> Self { + let account_info = self.db.load_account(address).unwrap(); + account_info.info.code = None; + account_info.info.code_hash = code_hash; + account_info.account_state = AccountState::None; + self + } + + /// Sets the balance for an account in the database. + pub fn set_account_balance(&mut self, address: Address, balance: U256) { + let account_info = self.db.load_account(address).unwrap(); + account_info.info.balance = balance; + account_info.account_state = AccountState::None; + } + + /// Sets the balance for an account in the database. + pub fn account_balance(mut self, address: Address, balance: U256) -> Self { + self.set_account_balance(address, balance); + self + } + + /// Sets the nonce for an account in the database. + pub fn set_account_nonce(&mut self, address: Address, nonce: u64) { + let account_info = self.db.load_account(address).unwrap(); + account_info.info.nonce = nonce; + account_info.account_state = AccountState::None; + } + + /// Sets the nonce for an account in the database. + pub fn account_nonce(mut self, address: Address, nonce: u64) -> Self { + self.set_account_nonce(address, nonce); + self + } + + /// Sets the storage for an account in the database. + pub fn set_account_storage( + &mut self, + address: Address, + storage_key: StorageKey, + value: StorageValue, + ) { + let account_info = self.db.load_account(address).unwrap(); + account_info.storage.insert(storage_key, value); + account_info.account_state = AccountState::None; + } + + /// Sets the storage for an account in the database. + pub fn account_storage( + mut self, + address: Address, + storage_key: StorageKey, + value: StorageValue, + ) -> Self { + self.set_account_storage(address, storage_key, value); + self + } +} + +impl revm::Database for MemoryDatabase { + type Error = Infallible; + + delegate! { + to self.db { + fn basic(&mut self, address: Address) -> Result, Self::Error>; + fn code_by_hash(&mut self, code_hash: B256) -> Result; + fn storage(&mut self, address: Address, index: StorageKey) -> Result; + fn block_hash(&mut self, number: u64) -> Result; + } + } +} + +impl revm::DatabaseCommit for MemoryDatabase { + delegate! { + to self.db { + fn commit(&mut self, changes: EvmState); + } + } +} + +/// Error type for [`ErrorInjectingDatabase`]. +#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] +#[display("{_0}")] +pub struct InjectedDbError(#[error(not(source))] pub String); + +impl DBErrorMarker for InjectedDbError {} + +/// A database wrapper that injects errors on configurable account or storage lookups. +/// +/// Used to test DB error handling paths (e.g., `FatalExternalError` when `inspect_*` fails). +/// Wraps a [`MemoryDatabase`] and can be configured to fail on specific `basic()` or `storage()` +/// calls. +#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)] +pub struct ErrorInjectingDatabase { + #[deref] + #[deref_mut] + inner: MemoryDatabase, + /// When set, `basic()` calls for this address return an error. + pub fail_on_account: Option
, + /// When set, `storage()` calls for this (address, key) return an error. + pub fail_on_storage: Option<(Address, StorageKey)>, + /// When set, `code_by_hash()` calls for this hash return an error. Lets a code load fail + /// independently of `basic()` (mirrors a node missing a contract's code), to exercise the + /// `load_code = true` inspect paths in isolation. + pub fail_on_code_by_hash: Option, +} + +impl ErrorInjectingDatabase { + /// Creates a new `ErrorInjectingDatabase` wrapping the given [`MemoryDatabase`]. + pub fn new(inner: MemoryDatabase) -> Self { + Self { inner, fail_on_account: None, fail_on_storage: None, fail_on_code_by_hash: None } + } +} + +impl revm::Database for ErrorInjectingDatabase { + type Error = InjectedDbError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + if self.fail_on_account == Some(address) { + return Err(InjectedDbError(format!("injected basic() error for {address}"))); + } + self.inner.basic(address).map_err(|e| match e {}) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + if self.fail_on_code_by_hash == Some(code_hash) { + return Err(InjectedDbError(format!("injected code_by_hash() error for {code_hash}"))); + } + self.inner.code_by_hash(code_hash).map_err(|e| match e {}) + } + + fn storage( + &mut self, + address: Address, + index: StorageKey, + ) -> Result { + if self.fail_on_storage == Some((address, index)) { + return Err(InjectedDbError(format!("injected storage() error for {address}:{index}"))); + } + self.inner.storage(address, index).map_err(|e| match e {}) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.inner.block_hash(number).map_err(|e| match e {}) + } +} + +impl revm::DatabaseCommit for ErrorInjectingDatabase { + fn commit(&mut self, changes: EvmState) { + self.inner.commit(changes); + } +} diff --git a/crates/mega-evm/src/test_utils/inspectors.rs b/crates/mega-evm/src/test_utils/inspectors.rs new file mode 100644 index 000000000..b1e40a1df --- /dev/null +++ b/crates/mega-evm/src/test_utils/inspectors.rs @@ -0,0 +1,343 @@ +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{rc::Rc, vec::Vec}; + +use core::cell::RefCell; +use revm::{ + bytecode::OpCode, + context::{ContextTr, JournalTr}, + interpreter::{ + interpreter_types::Jumps, CallInputs, CallOutcome, CreateInputs, Interpreter, + InterpreterTypes, + }, + Inspector, +}; + +/// A smart pointer wrapper around `Rc>` that provides shared mutable access. +/// +/// This type is used throughout the trace tree to allow multiple references to the same +/// node while maintaining interior mutability. It automatically derefs to the inner +/// `Rc>`. +#[derive(Debug, derive_more::Deref)] +pub struct Pointer(#[deref] Rc>); + +impl Clone for Pointer { + /// Clones the pointer (increments reference count), not the underlying data. + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl From for Pointer { + /// Wraps a value in a new `Pointer`. + fn from(value: T) -> Self { + Self(Rc::new(RefCell::new(value))) + } +} + +impl Pointer { + /// Clones the underlying data (not just the pointer). + pub fn clone_inner(&self) -> T { + self.0.borrow().clone() + } +} + +/// A path to a specific node in the trace tree. +/// +/// Each element represents the child index at that level of the tree. +/// For example, `vec![0, 2, 1]` means: first child -> third child -> second child. +pub type NodeLocation = Vec; + +/// A location of an item within a node's sections. +/// +/// `(section_index, item_index)` where sections are interleaved with child calls. +pub type ItemLocation = (usize, usize); + +/// A complete location representing a specific item in the trace tree. +/// +/// Combines a node location (path through call tree) with an item location +/// (position within that node's items). +#[derive(Debug)] +pub struct TraceLocation { + /// Path to the node containing the item. + pub call: NodeLocation, + /// Position of the item within the node. + pub item: ItemLocation, +} + +/// A node in a hierarchical trace tree structure. +/// +/// This represents a call frame (either a message call or contract creation) and maintains +/// a tree structure where: +/// - Each node contains metadata about the call (via `META`) +/// - Items (via `ITEM`) are stored in sections that are interleaved with child calls +/// - The structure allows reconstructing the exact chronological order of events +/// +/// # Structure +/// +/// Items are organized into sections, where sections are separated by child calls: +/// ```text +/// [items before first child] -> [first child] -> [items after first child] -> [second child] -> ... +/// ``` +/// +/// This allows the tree to maintain both hierarchical structure and chronological ordering. +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct TraceNode { + /// Metadata about this call (e.g., call inputs, creation inputs). + pub meta: META, + /// Reference to the parent node, if any. + pub parent: Option>, + /// Sections of items. There is always one more section than children. + /// Sections are interleaved with children to maintain chronological order. + pub sections: Vec>>, + /// Child nodes representing nested calls. + pub childrens: Vec>, +} + +impl TraceNode { + /// Creates a new trace node with the given metadata and optional parent. + /// + /// If a parent is provided, this node is automatically added as a child of the parent. + pub fn new(meta: META, parent: Option>) -> Pointer { + let this: Pointer = + Self { meta, parent: parent.clone(), sections: vec![Vec::new()], childrens: vec![] } + .into(); + if let Some(p) = parent { + p.borrow_mut().add_child(this.clone()); + } + this + } + + /// Returns the last item added to this node across all sections. + pub fn last_item(&self) -> Option> { + self.sections.iter().flatten().last().cloned() + } + + /// Adds an item to the current section (after the last child). + pub fn add_item(&mut self, item: ITEM) { + self.sections[self.childrens.len()].push(item.into()); + } + + /// Adds a child node and creates a new section for subsequent items. + fn add_child>>(&mut self, child: T) { + self.childrens.push(child.into()); + self.sections.push(Vec::new()); + } +} + +impl Pointer> { + /// Returns a flattened view of all items in the tree in chronological order. + pub fn flattened_items(&self) -> Vec> { + let mut items = Vec::new(); + for i in 0..self.borrow().childrens.len() { + items.extend(self.borrow().sections[i].iter().cloned()); + items.extend(self.borrow().childrens[i].flattened_items()); + } + items.extend(self.borrow().sections[self.borrow().childrens.len()].iter().cloned()); + items + } + + /// Retrieves a node at the specified location in the tree. + /// + /// Returns `None` if the location is invalid (out of bounds). + pub fn get_node(&self, location: NodeLocation) -> Option { + if location.is_empty() { + Some(self.clone()) + } else { + self.borrow().childrens[location[0]].get_node(location[1..].to_vec()) + } + } + + /// Retrieves an item at the specified location within this node. + /// + /// Returns `None` if the location is invalid (out of bounds). + pub fn get_item(&self, location: ItemLocation) -> Option> { + self.borrow().sections.get(location.0).and_then(|section| section.get(location.1)).cloned() + } + + /// Retrieves an item using a complete trace location (node path + item position). + /// + /// Returns `None` if either the node location or item location is invalid. + pub fn get_item_nested(&self, location: TraceLocation) -> Option> { + self.get_node(location.call).and_then(|n| n.get_item(location.item)) + } + + /// Iterates over all items in the tree in chronological order. + /// + /// For each item, calls the provided function with: + /// - The node location (path to the node containing the item) + /// - The node itself + /// - The item location within the node + /// - The item + pub fn iterate_with(&self, mut f: F) + where + F: FnMut(NodeLocation, Self, ItemLocation, Pointer), + { + self.iterate_with_inner(&mut f, vec![]); + } + + /// Internal helper for recursive iteration maintaining the current node location. + fn iterate_with_inner(&self, f: &mut F, node_location: NodeLocation) + where + F: FnMut(NodeLocation, Self, ItemLocation, Pointer), + { + let sections = &self.borrow().sections; + for (section_idx, section) in sections.iter().enumerate() { + for (item_idx, item) in section.iter().enumerate() { + f(node_location.clone(), self.clone(), (section_idx, item_idx), item.clone()); + } + if section_idx < sections.len() - 1 { + let mut child_node_location = node_location.clone(); + child_node_location.push(section_idx); + self.borrow().childrens[section_idx].iterate_with_inner(f, child_node_location); + } + } + } +} + +/// Represents gas information for a single opcode execution. +#[derive(Clone)] +pub struct OpcodeGasInfo { + /// The opcode executed. + pub opcode: OpCode, + /// Gas remaining before the opcode execution. + pub gas_before: u64, + /// Gas remaining after the opcode execution. + pub gas_after: u64, + /// Call depth when this opcode was executed. + pub depth: u64, +} + +impl core::fmt::Debug for OpcodeGasInfo { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!( + f, + "{}[depth={}] gas: {} -> {} (cost: {})", + self.opcode.as_str(), + self.depth, + self.gas_before, + self.gas_after, + self.gas_cost() + ) + } +} + +impl OpcodeGasInfo { + /// Calculates the gas cost of this opcode execution. + pub fn gas_cost(&self) -> u64 { + self.gas_before.saturating_sub(self.gas_after) + } +} + +/// Metadata for a trace node representing either a call or create operation. +#[derive(Debug, Clone)] +pub enum MsgCallMeta { + /// A message call (CALL, CALLCODE, DELEGATECALL, STATICCALL). + Call(CallInputs), + /// A contract creation (CREATE, CREATE2). + Create(CreateInputs), +} + +/// An inspector that collects a hierarchical view of gas left before and after each opcode. +#[derive(Debug, Default)] +pub struct GasInspector { + /// Stack of currently active call frames. + pub stack: Vec>>, + /// Root of the trace tree containing all opcode executions. + pub trace: Option>>, +} + +impl GasInspector { + /// Creates a new enabled `GasInspector`. + pub fn new() -> Self { + Self::default() + } + + /// Clears all recorded gas information. + pub fn clear(&mut self) { + self.trace = None; + self.stack = vec![]; + } + + /// Returns a flattened view of all opcode records in chronological order. + /// This traverses the call tree and collects all opcodes in execution order. + pub fn records(&self) -> Vec { + self.trace + .as_ref() + .map(|t| t.flattened_items().into_iter().map(|p| p.clone_inner()).collect()) + .unwrap_or_default() + } +} + +impl Inspector for GasInspector { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + // Create a new trace node for this call + let parent = self.stack.last().cloned(); + let msg_call = TraceNode::new(MsgCallMeta::Call(inputs.clone()), parent); + self.stack.push(msg_call.clone()); + // Set as root trace if this is the first call + if self.trace.is_none() { + self.trace = Some(msg_call); + } + None + } + + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { + // Pop the call from the stack when it completes + self.stack.pop(); + } + + fn create( + &mut self, + _context: &mut CTX, + inputs: &mut CreateInputs, + ) -> Option { + // Create a new trace node for this contract creation + let parent = self.stack.last().cloned(); + let msg_call = TraceNode::new(MsgCallMeta::Create(inputs.clone()), parent); + self.stack.push(msg_call.clone()); + // Set as root trace if this is the first operation + if self.trace.is_none() { + self.trace = Some(msg_call); + } + None + } + + fn create_end( + &mut self, + _context: &mut CTX, + _inputs: &CreateInputs, + _outcome: &mut revm::interpreter::CreateOutcome, + ) { + // Pop the create from the stack when it completes + self.stack.pop(); + } + + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + // Record gas state before opcode execution + let gas_before = interp.gas.remaining(); + let opcode = interp.bytecode.opcode(); + let depth = context.journal().depth(); + let step = OpcodeGasInfo { + opcode: OpCode::new(opcode).unwrap(), + gas_before, + gas_after: gas_before, // Will be updated in step_end + depth: depth as u64, + }; + if let Some(c) = self.stack.last_mut() { + c.borrow_mut().add_item(step) + } + } + + fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + // Update the gas_after field with the actual gas remaining after execution + let current = self + .stack + .last() + .as_ref() + .and_then(|c| c.borrow_mut().last_item()) + .expect("current is not None"); + current.borrow_mut().gas_after = interp.gas.remaining(); + } +} diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs new file mode 100644 index 000000000..1b69e04fd --- /dev/null +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -0,0 +1,11 @@ +//! Test utilities for the `MegaETH` EVM. + +mod bytes; +mod database; +mod inspectors; +mod opcode_gen; + +pub use bytes::*; +pub use database::*; +pub use inspectors::*; +pub use opcode_gen::*; diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs new file mode 100644 index 000000000..b78579640 --- /dev/null +++ b/crates/mega-evm/src/test_utils/opcode_gen.rs @@ -0,0 +1,159 @@ +//! This module provides utility functions to generate EVM bytecode. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + +use alloy_primitives::{Address, Bytes, U256}; +use revm::bytecode::opcode::{ + DUP1, EQ, INVALID, JUMPDEST, JUMPI, MSTORE, PUSH0, RETURN, REVERT, SSTORE, STOP, +}; + +use crate::test_utils::right_pad_bytes; + +/// A builder for assembling EVM bytecode. +#[derive(Debug, Default)] +pub struct BytecodeBuilder { + code: Vec, +} + +impl BytecodeBuilder { + /// Build the bytecode. + pub fn build(self) -> Bytes { + self.code.into() + } + + /// Build the bytecode as a vector. + pub fn build_vec(self) -> Vec { + self.code + } + + /// Get the length of the bytecode. + pub fn len(&self) -> usize { + self.code.len() + } + + /// Check if the bytecode is empty. + pub fn is_empty(&self) -> bool { + self.code.is_empty() + } + + /// Append a single opcode or byte. + pub fn append(mut self, opcode: u8) -> Self { + self.code.push(opcode); + self + } + + /// Append a series of opcodes or bytes. + pub fn append_many(mut self, items: impl IntoIterator) -> Self { + self.code.extend(items); + self + } + + /// Append a PUSH opcode and the bytes to push. + pub fn push_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self { + let bytes: &[u8] = bytes.as_ref(); + assert!(bytes.len() <= 32); + self.code.push(PUSH0 + bytes.len() as u8); + self.code.extend(bytes.to_vec()); + self + } + + /// Append a PUSH opcode and the number to push. + pub fn push_number + Copy>(self, number: T) -> Self { + let num = number.into(); + let bytes = match core::mem::size_of::() { + 1 => (num as u8).to_be_bytes().to_vec(), + 2 => (num as u16).to_be_bytes().to_vec(), + 4 => (num as u32).to_be_bytes().to_vec(), + 8 => (num as u64).to_be_bytes().to_vec(), + 16 => num.to_be_bytes().to_vec(), + _ => panic!("Unsupported integer size"), + }; + self.push_bytes(bytes) + } + + /// Append a PUSH opcode and the address to push. + pub fn push_address(self, address: Address) -> Self { + self.push_bytes(address) + } + + /// Append a PUSH opcode and the u256 value to push. + pub fn push_u256(self, value: U256) -> Self { + self.push_bytes(value.to_be_bytes_vec()) + } + + /// Append a series of MSTORE opcodes to store the given bytes at the given offset. + pub fn mstore(self, offset: usize, bytes: impl AsRef<[u8]>) -> Self { + let bytes = bytes.as_ref().to_vec(); + let padded_bytes = right_pad_bytes(bytes, 32); + let mut this = self; + for (i, chunk) in padded_bytes.chunks(32).enumerate() { + this = this.push_bytes(chunk); + this = this.push_number((offset + i * 32) as u64); + this.code.push(MSTORE); + } + this + } + + /// Append a SSTORE opcode to store the given value at the given slot. + pub fn sstore(mut self, slot: U256, value: U256) -> Self { + self = self.push_u256(value); + self = self.push_u256(slot); + self.code.push(SSTORE); + self + } + + /// Append a REVERT opcode with empty return data. + pub fn revert(self) -> Self { + self.append_many([PUSH0, PUSH0, REVERT]) + } + + /// Append a REVERT opcode with the given return data. + pub fn revert_with_data(mut self, data: impl AsRef<[u8]>) -> Self { + let data_len = data.as_ref().len(); + self = self.mstore(0x0, data); + self = self.push_number(data_len as u64); + self = self.push_number(0x0_u64); + self = self.append(REVERT); + self + } + + /// Append a RETURN opcode with empty return data. + pub fn return_empty(self) -> Self { + self.append_many([PUSH0, PUSH0, RETURN]) + } + + /// Append a RETURN opcode with the given return data. + pub fn return_with_data(mut self, data: impl AsRef<[u8]>) -> Self { + let data_len = data.as_ref().len(); + self = self.mstore(0x0, data); + self = self.push_number(data_len as u64); + self = self.push_number(0x0_u64); + self = self.append(RETURN); + self + } + + /// Append an assmembly snippet that checks whether the value at the given stack position is + /// equal to the given value. + /// + /// If not, call INVALID opcode. + /// + /// This snippet will left the stack unchanged after execution. + pub fn assert_stack_value(mut self, stack_position: usize, value: U256) -> Self { + self = self + .append(DUP1 + stack_position as u8) // duplicate the value at the given stack position to check + .push_u256(value) + .append(EQ); + let code_len = self.len(); + self = + self.push_number(code_len as u64 + 1 + 8 + 2).append_many([JUMPI, INVALID, JUMPDEST]); + self + } + + /// Append a STOP opcode. + pub fn stop(mut self) -> Self { + self = self.append(STOP); + self + } +} From d7a42548a5b035fe6ea8649e2c3b05cadf7e97b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:57:24 +0800 Subject: [PATCH 008/201] build: align clippy's MSRV with the workspace (1.94) --- clippy.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clippy.toml b/clippy.toml index bdc50bb3f..058aa492e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,4 +1,4 @@ -msrv = "1.86" +msrv = "1.94" too-large-for-stack = 128 doc-valid-idents = [ "P2P", From cc02c00231921cec17569abb1d6419687768a97e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:57:24 +0800 Subject: [PATCH 009/201] feat: run Satin through op-revm's OpEvm MegaContext wraps op-revm's context shape (MegaTransaction, L1BlockInfo) and holds the MegaSpecId configuration next to the OpSpecId one op-revm executes on; both are written together. The spec fixes Karst on the Osaka gas table, EIP-8037 and EIP-2780 on, a 200M tx_gas_limit_cap, and EIP-7708 and the system-call reservoir margin off, whatever configuration the caller passes. Every Host and context method delegates to the wrapped context. MegaEvm wraps OpEvm over MegaContext with op-revm's precompiles and implements revm's execution, inspection and system-call traits and alloy-evm's Evm; MegaEvmFactory implements alloy-evm's EvmFactory and feeds each EVM the external environments of its block. Tests: an empty transaction, a value transfer and one SSTORE run through MegaEvm and through op-revm's OpEvm on the same CfgEnv and agree on every ResultGas field, the logs and the state; the empty transaction leaves exactly the gas above the 200M cap in the reservoir. Twelve of the unit tests the test inventory assigns to the Satin skeleton are ported; four that need later work are parked under the common execution layer, the Satin gas table, SALT pricing and the block executor with the reason in the pending README. test_utils::transact now takes the spec and the gas limit. --- crates/mega-evm/src/evm/context.rs | 356 ++++++++++++++++ crates/mega-evm/src/evm/factory.rs | 149 +++++++ crates/mega-evm/src/evm/mod.rs | 387 ++++++++++++++++++ crates/mega-evm/src/test_utils/evm.rs | 43 ++ crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/opcode_gen.rs | 51 +++ crates/mega-evm/tests/_pending/README.md | 27 +- .../tests/_pending/src/evm/context.rs | 61 --- .../tests/_pending/src/evm/factory.rs | 10 - crates/mega-evm/tests/_pending/src/evm/mod.rs | 106 ----- .../_pending/src/test_utils/opcode_gen.rs | 57 --- crates/mega-evm/tests/satin/equivalence.rs | 158 +++++++ crates/mega-evm/tests/satin/main.rs | 3 + 13 files changed, 1166 insertions(+), 244 deletions(-) create mode 100644 crates/mega-evm/src/evm/context.rs create mode 100644 crates/mega-evm/src/evm/factory.rs create mode 100644 crates/mega-evm/src/test_utils/evm.rs delete mode 100644 crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs create mode 100644 crates/mega-evm/tests/satin/equivalence.rs create mode 100644 crates/mega-evm/tests/satin/main.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs new file mode 100644 index 000000000..a17f05dc8 --- /dev/null +++ b/crates/mega-evm/src/evm/context.rs @@ -0,0 +1,356 @@ +//! The execution context of the Satin engine. + +use delegate::delegate; +use op_revm::{L1BlockInfo, OpSpecId}; +use revm::{ + context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, + context_interface::{ + cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::LoadError, + journaled_state::{AccountInfoLoad, AccountLoad}, + }, + primitives::{Address, Bytes, Log, StorageKey, StorageValue, B256, U256}, + Database, Journal, +}; + +use crate::{ + constants, EmptyExternalEnv, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, +}; + +/// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` +/// transaction type. +pub type MegaInnerContext = + Context, DB, Journal, L1BlockInfo>; + +/// Execution context of the Satin engine. +/// +/// It wraps op-revm's context and adds what `MegaETH` execution needs on top: the `MegaETH` +/// spec and the external environments (SALT, oracle). The configuration is kept twice: the +/// [`MegaSpecId`] view that callers see and the [`OpSpecId`] view op-revm executes on. Both are +/// written together, only through [`MegaContext::with_cfg`], so they cannot drift apart. +/// +/// Every [`Host`](revm::interpreter::Host) method and every context accessor delegates to the +/// wrapped context; later tickets override the ones `MegaETH` prices or meters differently. +#[derive(Debug)] +pub struct MegaContext { + inner: MegaInnerContext, + cfg: CfgEnv, + external_envs: ExternalEnvs, +} + +impl MegaContext { + /// Creates a context over `db` that executes `spec`, without external environments. + pub fn new(db: DB, spec: MegaSpecId) -> Self { + Self::new_with_external_envs(db, spec, ExternalEnvs::default()) + } +} + +impl MegaContext { + /// Creates a context over `db` that executes `spec` with the given external environments. + pub fn new_with_external_envs( + db: DB, + spec: MegaSpecId, + external_envs: ExternalEnvs, + ) -> Self { + let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); + let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); + Self { inner, cfg, external_envs } + } + + /// Replaces the configuration. + /// + /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas table, the + /// EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and the system-call + /// state-gas margin. Every other field (chain id, limits, disabled checks) is taken from + /// `cfg`. + pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { + let cfg = spec_cfg(cfg); + self.inner = self.inner.with_cfg(op_cfg(&cfg)); + self.cfg = cfg; + self + } + + /// Replaces the block environment. + pub fn with_block(mut self, block: BlockEnv) -> Self { + self.inner.block = block; + self + } + + /// Replaces the transaction. + pub fn with_tx(mut self, tx: MegaTransaction) -> Self { + self.inner.tx = tx; + self + } + + /// Replaces the L1 block info. + pub fn with_chain(mut self, chain: L1BlockInfo) -> Self { + self.inner.chain = chain; + self + } + + /// Modifies the L1 block info in place. + pub fn modify_chain(&mut self, f: impl FnOnce(&mut L1BlockInfo)) { + f(&mut self.inner.chain); + } + + /// The spec this context executes. + pub const fn spec(&self) -> MegaSpecId { + self.cfg.spec + } + + /// The configuration as callers see it, keyed by [`MegaSpecId`]. + /// + /// [`ContextTr::cfg`] returns the [`OpSpecId`] view op-revm executes on. + pub const fn mega_cfg(&self) -> &CfgEnv { + &self.cfg + } + + /// The external environments (SALT, oracle) of this context. + pub const fn external_envs(&self) -> &ExternalEnvs { + &self.external_envs + } + + /// Consumes the context and returns the database, the configuration and the block. + pub fn into_parts(self) -> (DB, CfgEnv, BlockEnv) { + let Context { block, journaled_state, .. } = self.inner; + (journaled_state.database, self.cfg, block) + } +} + +/// Sets the configuration fields the spec fixes. +/// +/// Satin runs on the Osaka gas table of its Karst base, with EIP-8037 state gas and the EIP-2780 +/// intrinsic cost switched on and gas above the execution cap going to the state-gas reservoir. +/// The EIP-7708 transfer logs and the system-call reservoir margin stay off until T3.1 and T5.2 +/// switch them on. +fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { + cfg.gas_params = GasParams::new_spec(cfg.spec.into_eth_spec()); + cfg.enable_amsterdam_eip8037 = true; + cfg.enable_amsterdam_eip2780 = true; + cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); + cfg.enable_amsterdam_eip7708 = false; + cfg.system_call_state_gas_margin_in_reservoir = false; + cfg +} + +/// The op-revm view of `cfg`: the same fields, keyed by the Optimism spec. +fn op_cfg(cfg: &CfgEnv) -> CfgEnv { + cfg.clone().with_spec_and_gas_params(cfg.spec.into_op_spec(), cfg.gas_params.clone()) +} + +impl ContextTr for MegaContext { + type Block = BlockEnv; + type Tx = MegaTransaction; + type Cfg = CfgEnv; + type Db = DB; + type Journal = Journal; + type Chain = L1BlockInfo; + type Local = LocalContext; + + delegate! { + to self.inner { + fn all( + &self, + ) -> ( + &BlockEnv, + &MegaTransaction, + &CfgEnv, + &DB, + &Journal, + &L1BlockInfo, + &LocalContext, + ); + fn all_mut( + &mut self, + ) -> ( + &BlockEnv, + &MegaTransaction, + &CfgEnv, + &mut Journal, + &mut L1BlockInfo, + &mut LocalContext, + ); + fn error(&mut self) -> &mut Result<(), ContextError>; + } + } +} + +impl ContextSetters for MegaContext { + delegate! { + to self.inner { + fn set_tx(&mut self, tx: MegaTransaction); + fn set_block(&mut self, block: BlockEnv); + } + } +} + +impl revm::context_interface::Host + for MegaContext +{ + delegate! { + to self.inner { + fn basefee(&self) -> U256; + fn blob_gasprice(&self) -> U256; + fn gas_limit(&self) -> U256; + fn difficulty(&self) -> U256; + fn prevrandao(&self) -> Option; + fn block_number(&self) -> U256; + fn timestamp(&self) -> U256; + fn beneficiary(&self) -> Address; + fn slot_num(&self) -> U256; + fn chain_id(&self) -> U256; + fn effective_gas_price(&self) -> U256; + fn caller(&self) -> Address; + fn blob_hash(&self, number: usize) -> Option; + fn max_initcode_size(&self) -> usize; + fn gas_params(&self) -> &GasParams; + fn is_amsterdam_eip8037_enabled(&self) -> bool; + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; + fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; + fn block_hash(&mut self, number: u64) -> Option; + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn log(&mut self, log: Log); + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Option>; + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn sload(&mut self, address: Address, key: StorageKey) -> Option>; + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn balance(&mut self, address: Address) -> Option>; + fn load_account_delegated(&mut self, address: Address) -> Option>; + fn load_account_code(&mut self, address: Address) -> Option>; + fn load_account_code_hash(&mut self, address: Address) -> Option>; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{EthSpecId, SaltEnv, TestExternalEnvs}; + use core::convert::Infallible; + use revm::database::EmptyDB; + + /// Asserts both configuration views carry the Satin switches. + fn assert_satin_switches(ctx: &MegaContext) { + let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); + assert_eq!(mega.spec, MegaSpecId::SATIN); + assert_eq!(op.spec, OpSpecId::KARST); + for (eip8037, eip2780, cap, eip7708, margin) in [ + ( + mega.enable_amsterdam_eip8037, + mega.enable_amsterdam_eip2780, + mega.tx_gas_limit_cap, + mega.enable_amsterdam_eip7708, + mega.system_call_state_gas_margin_in_reservoir, + ), + ( + op.enable_amsterdam_eip8037, + op.enable_amsterdam_eip2780, + op.tx_gas_limit_cap, + op.enable_amsterdam_eip7708, + op.system_call_state_gas_margin_in_reservoir, + ), + ] { + assert!(eip8037, "EIP-8037 must be on"); + assert!(eip2780, "EIP-2780 must be on"); + assert_eq!(cap, Some(200_000_000), "execution cap"); + assert!(!eip7708, "EIP-7708 stays off until T3.1"); + assert!(!margin, "the system-call reservoir margin stays off until T5.2"); + } + let osaka = GasParams::new_spec(EthSpecId::OSAKA); + assert_eq!(mega.gas_params.table(), osaka.table()); + assert_eq!(op.gas_params.table(), osaka.table()); + } + + #[test] + fn test_new_context_carries_the_satin_switches() { + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert_satin_switches(&ctx); + } + + /// A caller's configuration cannot switch off what the spec fixes; every other field is + /// taken from it. + #[test] + fn test_with_cfg_updates_spec() { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = 4326; + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.tx_gas_limit_cap = Some(1 << 24); + cfg.enable_amsterdam_eip7708 = true; + cfg.system_call_state_gas_margin_in_reservoir = true; + cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); + + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); + + assert_satin_switches(&ctx); + assert_eq!(ctx.mega_cfg().chain_id, 4326); + assert_eq!(ctx.cfg().chain_id, 4326); + } + + /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. + #[test] + fn test_with_cfg_spec_consistency() { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = 6343; + cfg.limit_contract_code_size = Some(512 * 1024); + cfg.disable_nonce_check = true; + + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); + let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); + + assert_eq!(op.spec, mega.spec.into_op_spec()); + assert_eq!(op.chain_id, 6343); + assert_eq!(op.limit_contract_code_size, Some(512 * 1024)); + assert!(op.disable_nonce_check); + assert_eq!( + mega.clone().with_spec_and_gas_params(op.spec, mega.gas_params.clone()), + op.clone() + ); + } + + /// The external environments given at construction are the ones the context exposes. + #[test] + fn test_new_with_ext_envs_builds_over_configurable_env() { + let env = TestExternalEnvs::::new().with_bucket_capacity(7, 1_024); + let ctx = MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs::from(env), + ); + + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert_eq!(ctx.external_envs().salt_env.get_bucket_capacity(7).unwrap(), 1_024); + assert_satin_switches(&ctx); + } +} diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs new file mode 100644 index 000000000..83865e3ee --- /dev/null +++ b/crates/mega-evm/src/evm/factory.rs @@ -0,0 +1,149 @@ +//! Factory of Satin EVMs for alloy-evm consumers. + +use alloy_evm::{Database, EvmEnv}; +use op_revm::{precompiles::OpPrecompiles, OpHaltReason}; +use revm::{ + context::{result::EVMError, BlockEnv, DBErrorMarker}, + inspector::NoOpInspector, + Inspector, +}; + +use crate::{ + EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionError, +}; + +/// Creates [`MegaEvm`]s for alloy-evm consumers such as a node's block executor. +/// +/// The factory holds the [`ExternalEnvFactory`] that supplies each EVM with the SALT and oracle +/// environments of the block it executes. +#[derive(Clone, Debug, Default)] +pub struct MegaEvmFactory { + external_env_factory: ExtEnvFactory, +} + +impl MegaEvmFactory { + /// Creates a factory whose EVMs have no external environments. + pub const fn new() -> Self { + Self { external_env_factory: EmptyExternalEnv } + } +} + +impl MegaEvmFactory { + /// The external environment factory. + pub const fn external_env_factory(&self) -> &ExtEnvFactory { + &self.external_env_factory + } + + /// Replaces the external environment factory. + pub fn with_external_env_factory( + self, + external_env_factory: F, + ) -> MegaEvmFactory { + MegaEvmFactory { external_env_factory } + } +} + +impl alloy_evm::EvmFactory for MegaEvmFactory { + type Evm>> = + MegaEvm; + type Context = MegaContext; + type Tx = MegaTransaction; + type Error = EVMError; + type HaltReason = OpHaltReason; + type Spec = MegaSpecId; + type BlockEnv = BlockEnv; + type Precompiles = OpPrecompiles; + + /// Creates an EVM for the block in `evm_env`, with the external environments of that block. + /// + /// The configuration fields the spec fixes are set from the spec (see + /// [`MegaContext::with_cfg`]). + fn create_evm( + &self, + db: DB, + evm_env: EvmEnv, + ) -> Self::Evm { + let EvmEnv { cfg_env, block_env } = evm_env; + let external_envs = + self.external_env_factory.external_envs(block_env.number.saturating_to()); + let ctx = MegaContext::new_with_external_envs(db, cfg_env.spec, external_envs) + .with_cfg(cfg_env) + .with_block(block_env); + MegaEvm::new(ctx) + } + + fn create_evm_with_inspector>>( + &self, + db: DB, + input: EvmEnv, + inspector: I, + ) -> Self::Evm { + self.create_evm(db, input).with_inspector(inspector) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, ExternalEnvs}; + use alloy_evm::{Evm, EvmFactory}; + use alloy_primitives::{BlockNumber, U256}; + use core::cell::Cell; + use revm::context::CfgEnv; + + #[test] + fn test_external_env_factory_getter() { + let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); + + let got: &EmptyExternalEnv = factory.external_env_factory(); + + assert!(core::ptr::eq(got, factory.external_env_factory())); + } + + /// Whatever configuration the caller passes, the EVM runs with the switches the spec fixes. + #[test] + fn test_create_evm_applies_the_spec_switches() { + let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg_env.chain_id = 4326; + cfg_env.tx_gas_limit_cap = Some(1 << 24); + cfg_env.enable_amsterdam_eip8037 = false; + let block_env = BlockEnv { number: U256::from(5), ..Default::default() }; + + let evm = MegaEvmFactory::new() + .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env, block_env }); + + assert_eq!(evm.chain_id(), 4326); + assert_eq!(evm.cfg_env().tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); + assert!(evm.cfg_env().enable_amsterdam_eip8037); + assert_eq!(evm.block().number, U256::from(5)); + } + + /// Records the block number each EVM's external environments are created for. + #[derive(Debug, Default)] + struct RecordingFactory(Cell>); + + impl ExternalEnvFactory for RecordingFactory { + type EnvTypes = EmptyExternalEnv; + + fn external_envs(&self, block: BlockNumber) -> ExternalEnvs { + self.0.set(Some(block)); + ExternalEnvs::default() + } + } + + #[test] + fn test_create_evm_takes_the_external_envs_of_the_block() { + let factory = MegaEvmFactory::new().with_external_env_factory(RecordingFactory::default()); + let block_env = BlockEnv { number: U256::from(1_234), ..Default::default() }; + + let evm = factory.create_evm_with_inspector( + MemoryDatabase::default(), + EvmEnv { cfg_env: CfgEnv::new_with_spec(MegaSpecId::SATIN), block_env }, + NoOpInspector, + ); + + assert_eq!(factory.external_env_factory().0.get(), Some(1_234)); + assert!(evm.is_inspecting()); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index c9b7a5143..5d69424c8 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,5 +1,392 @@ //! The Satin EVM. +//! +//! [`MegaEvm`] wraps op-revm's [`OpEvm`] over a [`MegaContext`] configured for the Satin spec. +//! It adds no `MegaETH` behavior yet: SALT pricing, history gas, resource limits, detention and +//! the system contracts arrive with T3 through T8. +mod context; +mod factory; mod spec; +pub use context::*; +pub use factory::*; pub use spec::*; + +use alloy_evm::EvmEnv; +use alloy_op_evm::map_op_err; +use op_revm::{precompiles::OpPrecompiles, OpEvm, OpHaltReason, OpTransactionError}; +use revm::{ + context::{ + result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, + BlockEnv, CfgEnv, ContextTr, + }, + handler::{instructions::EthInstructions, system_call::SystemCallEvm}, + inspector::{InspectCommitEvm, InspectEvm, InspectSystemCallEvm, Inspector, NoOpInspector}, + interpreter::interpreter::EthInterpreter, + primitives::{Address, Bytes}, + state::EvmState, + Database, DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, +}; + +use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; + +/// The instruction table of the Satin engine. +pub type MegaInstructions = EthInstructions>; + +/// The op-revm EVM a [`MegaEvm`] wraps. +/// +/// It runs op-revm's precompile set for the base spec; T3.1 replaces it with the Satin set. +pub type MegaInnerEvm = + OpEvm, INSP, MegaInstructions, OpPrecompiles>; + +/// The Satin EVM. +/// +/// Executes transactions through op-revm's handler on a [`MegaContext`]. It implements revm's +/// execution traits ([`ExecuteEvm`], [`InspectEvm`], [`SystemCallEvm`] and their commit +/// variants) and alloy-evm's [`Evm`](alloy_evm::Evm), which is what a node's block executor +/// drives. +#[allow(missing_debug_implementations)] +pub struct MegaEvm { + inner: MegaInnerEvm, + /// Whether [`alloy_evm::Evm::transact_raw`] runs the inspector. + inspect: bool, +} + +impl MegaEvm { + /// Creates an EVM over `ctx`, without an inspector. + pub fn new(ctx: MegaContext) -> Self { + Self { inner: OpEvm::new(ctx, NoOpInspector), inspect: false } + } +} + +impl MegaEvm { + /// Replaces the inspector. The new inspector runs on every alloy-evm + /// [`transact`](alloy_evm::Evm::transact) until it is disabled again. + pub fn with_inspector(self, inspector: I) -> MegaEvm { + MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true } + } + + /// The execution context. + pub const fn ctx(&self) -> &MegaContext { + &self.inner.0.ctx + } + + /// The execution context, mutably. + pub const fn ctx_mut(&mut self) -> &mut MegaContext { + &mut self.inner.0.ctx + } + + /// Whether alloy-evm's [`transact`](alloy_evm::Evm::transact) runs the inspector. + pub const fn is_inspecting(&self) -> bool { + self.inspect + } + + /// Consumes the EVM and returns the op-revm EVM it wraps. + pub fn into_inner(self) -> MegaInnerEvm { + self.inner + } +} + +impl ExecuteEvm for MegaEvm { + type ExecutionResult = ExecutionResult; + type State = EvmState; + type Error = EVMError; + type Tx = MegaTransaction; + type Block = BlockEnv; + + fn set_block(&mut self, block: Self::Block) { + self.inner.set_block(block); + } + + fn transact_one(&mut self, tx: Self::Tx) -> Result { + self.inner.transact_one(tx) + } + + fn finalize(&mut self) -> Self::State { + self.inner.finalize() + } + + fn replay( + &mut self, + ) -> Result, Self::Error> { + self.inner.replay() + } +} + +impl ExecuteCommitEvm + for MegaEvm +{ + fn commit(&mut self, state: Self::State) { + self.inner.commit(state); + } +} + +impl InspectEvm for MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + type Inspector = INSP; + + fn set_inspector(&mut self, inspector: Self::Inspector) { + self.inner.set_inspector(inspector); + } + + fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { + self.inner.inspect_one_tx(tx) + } +} + +impl InspectCommitEvm for MegaEvm +where + DB: Database + DatabaseCommit, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ +} + +impl SystemCallEvm for MegaEvm { + fn system_call_one_with_caller( + &mut self, + caller: Address, + system_contract_address: Address, + data: Bytes, + ) -> Result { + self.inner.system_call_one_with_caller(caller, system_contract_address, data) + } +} + +impl InspectSystemCallEvm for MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + fn inspect_one_system_call_with_caller( + &mut self, + caller: Address, + system_contract_address: Address, + data: Bytes, + ) -> Result { + self.inner.inspect_one_system_call_with_caller(caller, system_contract_address, data) + } +} + +impl alloy_evm::Evm for MegaEvm +where + DB: alloy_evm::Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + type DB = DB; + type Tx = MegaTransaction; + type Error = EVMError; + type HaltReason = OpHaltReason; + type Spec = MegaSpecId; + type BlockEnv = BlockEnv; + type Precompiles = OpPrecompiles; + type Inspector = INSP; + + fn block(&self) -> &BlockEnv { + self.ctx().block() + } + + fn cfg_env(&self) -> &CfgEnv { + self.ctx().mega_cfg() + } + + fn chain_id(&self) -> u64 { + self.ctx().mega_cfg().chain_id + } + + fn transact_raw( + &mut self, + tx: Self::Tx, + ) -> Result, Self::Error> { + let result = if self.inspect { + InspectEvm::inspect_tx(&mut self.inner, tx) + } else { + ExecuteEvm::transact(&mut self.inner, tx) + }; + result.map_err(map_op_err) + } + + fn transact_system_call( + &mut self, + caller: Address, + contract: Address, + data: Bytes, + ) -> Result, Self::Error> { + self.inner.system_call_with_caller(caller, contract, data).map_err(map_op_err) + } + + fn finish(self) -> (Self::DB, EvmEnv) { + let (db, cfg_env, block_env) = self.inner.0.ctx.into_parts(); + (db, EvmEnv { cfg_env, block_env }) + } + + fn set_inspector_enabled(&mut self, enabled: bool) { + self.inspect = enabled; + } + + fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { + let evm = &self.inner.0; + (evm.ctx.db(), &evm.inspector, &evm.precompiles) + } + + fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { + let evm = &mut self.inner.0; + (evm.ctx.db_mut(), &mut evm.inspector, &mut evm.precompiles) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::MemoryDatabase; + use alloy_evm::{Evm, EvmError}; + use alloy_op_evm::OpTx; + use alloy_primitives::{address, TxKind, U256}; + use op_revm::{L1BlockInfo, OpTransaction}; + use revm::{ + context::{result::InvalidTransaction, ContextSetters, TxEnv}, + database::State, + DatabaseRef, + }; + use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; + + const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); + const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); + + fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_chain(L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + }) + } + + fn tx(value: U256) -> MegaTransaction { + OpTx(OpTransaction { + base: TxEnv { + caller: CALLER, + gas_limit: 100_000, + kind: TxKind::Call(CALLEE), + value, + ..Default::default() + }, + enveloped_tx: Some(Bytes::new()), + ..Default::default() + }) + } + + fn funded_db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()) + } + + #[test] + fn test_mega_evm_builder_chain_produces_working_evm() { + let mut db = funded_db(); + let evm = MegaEvm::new(context(&mut db)); + assert!(!evm.is_inspecting()); + + let mut evm = evm.with_inspector(NoOpInspector); + assert!(evm.is_inspecting()); + assert!(evm.transact_raw(tx(U256::ZERO)).unwrap().result.is_success()); + + let inner = evm.into_inner(); + assert_eq!(inner.0.ctx.spec(), MegaSpecId::SATIN); + } + + #[test] + fn test_alloy_evm_interface_methods_execute_transactions() { + let mut db = funded_db(); + let mut evm = MegaEvm::new( + context(&mut db).with_block(BlockEnv { gas_limit: 222_222, ..Default::default() }), + ); + + assert_eq!(evm.chain_id(), evm.ctx().cfg().chain_id); + assert_eq!(evm.cfg_env().spec, MegaSpecId::SATIN); + assert_eq!(evm.block().gas_limit, 222_222); + + evm.set_inspector_enabled(true); + assert!(evm.is_inspecting()); + evm.set_inspector_enabled(false); + let (_db, _inspector, _precompiles) = evm.components(); + let (_db, _inspector, _precompiles) = evm.components_mut(); + + assert!(evm.transact_raw(tx(U256::ZERO)).unwrap().result.is_success()); + let system_call = Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()); + assert!(system_call.unwrap().result.is_success()); + + let (_db, evm_env) = evm.finish(); + assert_eq!(evm_env.cfg_env.spec, MegaSpecId::SATIN); + assert_eq!(evm_env.cfg_env.tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); + assert_eq!(evm_env.block_env.gas_limit, 222_222); + } + + #[test] + fn test_revm_execute_one_finalize_commit_works() { + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + ExecuteEvm::set_block(&mut evm, BlockEnv { gas_limit: 222_222, ..Default::default() }); + assert_eq!(evm.block().gas_limit, 222_222); + + let result = ExecuteEvm::transact_one(&mut evm, tx(U256::from(7))).unwrap(); + assert!(result.is_success()); + let state = ExecuteEvm::finalize(&mut evm); + ExecuteCommitEvm::commit(&mut evm, state); + drop(evm); + + assert_eq!(db.basic_ref(CALLEE).unwrap().unwrap().balance, U256::from(7)); + } + + #[test] + fn test_revm_replay_works() { + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + evm.ctx_mut().set_tx(tx(U256::ZERO)); + let replay = ExecuteEvm::replay(&mut evm).unwrap(); + assert!(replay.result.is_success()); + assert!(replay.state.contains_key(&CALLER)); + } + + #[test] + fn test_revm_inspect_one_tx_works() { + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)) + .with_inspector(TracingInspector::new(TracingInspectorConfig::default_parity())); + let result = InspectEvm::inspect_one_tx(&mut evm, tx(U256::ZERO)).unwrap(); + assert!(result.is_success()); + + let traces = evm.inspector().traces(); + assert_eq!(traces.nodes().len(), 1, "one call frame"); + assert_eq!(traces.nodes()[0].trace.address, CALLEE); + } + + #[test] + fn test_execute_transaction_fails_with_insufficient_balance() { + let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(context(&mut db)); + + let err = evm.transact_raw(tx(U256::from(1_000_000))).unwrap_err(); + let invalid = + err.as_invalid_tx_err().and_then(alloy_evm::InvalidTxError::as_invalid_tx_err); + assert!(matches!(invalid, Some(InvalidTransaction::LackOfFundForMaxFee { .. })), "{err:?}"); + } + + #[test] + fn test_finish_returns_the_database() { + let mut state = State::builder().with_database(funded_db()).build(); + let mut evm = MegaEvm::new(context(&mut state)); + assert!(Evm::transact_commit(&mut evm, tx(U256::from(5))).unwrap().is_success()); + let (db, _) = evm.finish(); + assert_eq!( + db.cache.accounts[&CALLEE].account.as_ref().unwrap().info.balance, + U256::from(5) + ); + } +} diff --git a/crates/mega-evm/src/test_utils/evm.rs b/crates/mega-evm/src/test_utils/evm.rs new file mode 100644 index 000000000..ccb8298c3 --- /dev/null +++ b/crates/mega-evm/src/test_utils/evm.rs @@ -0,0 +1,43 @@ +use alloy_evm::{Database, Evm}; +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use op_revm::{L1BlockInfo, OpTransaction}; +use revm::context::{ + result::{EVMError, ResultAndState}, + TxEnv, +}; + +use crate::{MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionError}; + +/// Executes one transaction on a fresh [`MegaEvm`] over `db` and returns its result and state +/// without committing. +/// +/// The L1 fees are zero (operator fee zero, empty enveloped transaction) and so is the gas +/// price, so the caller needs no balance beyond `value`. A `gas_limit` above the execution cap +/// puts the excess into the state-gas reservoir. +pub fn transact( + spec: MegaSpecId, + db: DB, + caller: Address, + callee: Option
, + data: Bytes, + value: U256, + gas_limit: u64, +) -> Result, EVMError> { + let context = MegaContext::new(db, spec).with_chain(L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + }); + let tx = TxEnv { + caller, + kind: callee.map_or(TxKind::Create, TxKind::Call), + data, + value, + gas_limit, + ..Default::default() + }; + let tx = + OpTx(OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() }); + MegaEvm::new(context).transact_raw(tx) +} diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 1b69e04fd..3e6f7c544 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -2,10 +2,12 @@ mod bytes; mod database; +mod evm; mod inspectors; mod opcode_gen; pub use bytes::*; pub use database::*; +pub use evm::*; pub use inspectors::*; pub use opcode_gen::*; diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs index b78579640..a5dca8e55 100644 --- a/crates/mega-evm/src/test_utils/opcode_gen.rs +++ b/crates/mega-evm/src/test_utils/opcode_gen.rs @@ -157,3 +157,54 @@ impl BytecodeBuilder { self } } + +#[cfg(test)] +mod tests { + use core::convert::Infallible; + + use alloy_primitives::address; + use revm::context::result::{EVMError, ResultAndState}; + + use crate::{ + test_utils::{transact, MemoryDatabase}, + MegaHaltReason, MegaSpecId, MegaTransactionError, + }; + + use super::*; + + fn execute_bytecode( + bytecode: Bytes, + ) -> Result, EVMError> { + let caller = address!("0000000000000000000000000000000000100000"); + let contract = address!("0000000000000000000000000000000000100001"); + let mut db = MemoryDatabase::default(); + db.set_account_code(contract, bytecode); + transact( + MegaSpecId::SATIN, + &mut db, + caller, + Some(contract), + Bytes::new(), + U256::ZERO, + 1_000_000, + ) + } + + #[test] + fn test_assert_stack_value_success() { + let mut builder = BytecodeBuilder::default().push_number(0x2333u64); + builder = builder.assert_stack_value(0, U256::from(0x2333u64)); + let bytecode = builder.build(); + let result = execute_bytecode(bytecode); + assert!(result.unwrap().result.is_success(), "Transaction should succeed"); + } + + #[test] + fn test_assert_stack_value_failure() { + let mut builder = BytecodeBuilder::default().push_number(0x2333u64); + builder = builder.assert_stack_value(0, U256::from(0x9999u64)); + let bytecode = builder.build(); + let result = execute_bytecode(bytecode); + assert!(result.unwrap().result.is_halt(), "Transaction should fail"); + } +} diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 948d432b3..96f6168fe 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -25,11 +25,10 @@ Do not add a `_pending/main.rs`. | Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | |---|---:|---:|---:|---:|---:|---:| -| T2.1 | 16 | 0 | 16 | 13 | 3 | 0 | | T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | -| T2.3 | 40 | 19 | 21 | 21 | 19 | 0 | -| T3.1 | 36 | 30 | 6 | 7 | 29 | 0 | -| T3.2 | 82 | 72 | 10 | 24 | 58 | 0 | +| T2.3 | 41 | 19 | 22 | 22 | 19 | 0 | +| T3.1 | 37 | 30 | 7 | 7 | 30 | 0 | +| T3.2 | 83 | 72 | 11 | 25 | 58 | 0 | | T3.3 | 28 | 24 | 4 | 4 | 24 | 0 | | T3.4 | 27 | 27 | 0 | 0 | 27 | 0 | | T4.1 | 49 | 47 | 2 | 42 | 7 | 0 | @@ -41,10 +40,19 @@ Do not add a `_pending/main.rs`. | T6.2 | 67 | 17 | 50 | 62 | 5 | 0 | | T6.3 | 77 | 77 | 0 | 67 | 10 | 0 | | T7 | 89 | 73 | 16 | 43 | 46 | 0 | -| T8.1 | 74 | 45 | 29 | 55 | 19 | 0 | +| T8.1 | 75 | 45 | 30 | 56 | 19 | 0 | | T9 | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **862** | **691** | **171** | **509** | **324** | **29** | +| **Total** | **850** | **691** | **159** | **499** | **322** | **29** | + +## Tests T0 assigns to T2.1 that are parked under another ticket + +| File | Test | Parked under | Reason | +|---|---|---|---| +| `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | T3.2 | exercises the dynamic storage-gas cache that SALT pricing brings back | +| `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | T3.1 | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | +| `src/evm/mod.rs` | `test_convenience_execution_methods_work` | T2.3 | `execute_transaction` returns the transaction outcome type that T2.3 defines | +| `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | T8.1 | reads the accessed-block-hash record, which returns with the block executor | ## Files @@ -140,10 +148,10 @@ Each cell lists `disposition count (ticket · decision)`. | `src/block/helpers.rs` | 3 | 保留 3 (T8.1) | | `src/block/limit.rs` | 5 | 保留 5 (T8.1) | | `src/block/result.rs` | 2 | 重写 2 (T8.1 · D48 (error shape)) | -| `src/evm/context.rs` | 4 | 重写 2 (T2.1 · single spec); 保留 2 (T2.1 · T3.2 for the SALT cache test) | -| `src/evm/factory.rs` | 2 | 保留 1 (T2.1); 重写 1 (T2.1 · no behaviour projection) | +| `src/evm/context.rs` | 1 | 保留 1 (T3.2 · T3.2 for the SALT cache test) | +| `src/evm/factory.rs` | 1 | 重写 1 (T3.1 · no behaviour projection) | | `src/evm/host.rs` | 11 | 保留 10 (T2.3 · Host observation layer (D33) on the revm 40 journal); 保留 1 (T3.2) | -| `src/evm/mod.rs` | 11 | 保留 8 (T2.1); 保留 3 (T5.2) | +| `src/evm/mod.rs` | 5 | 保留 3 (T5.2); 保留 1 (T8.1); 保留 1 (T2.3) | | `src/evm/precompiles.rs` | 6 | 保留 6 (T3.1 · D04) | | `src/evm/result.rs` | 4 | 重写 4 (T2.3 · D17/D48 (halt-reason set changes)) | | `src/evm/state.rs` | 1 | 保留 1 (T8.1) | @@ -165,4 +173,3 @@ Each cell lists `disposition count (ticket · decision)`. | `src/system/oracle.rs` | 7 | 保留 7 (T6.2 · v2.0.0 only) | | `src/system/sequencer_registry.rs` | 24 | 保留 24 (T6.2 · T5.2 for transact_apply_pending_changes) | | `src/system/tx.rs` | 6 | 保留 6 (T6.1 · D51) | -| `src/test_utils/opcode_gen.rs` | 2 | 保留 2 (T2.1) | diff --git a/crates/mega-evm/tests/_pending/src/evm/context.rs b/crates/mega-evm/tests/_pending/src/evm/context.rs index 3da3c179a..864b5feca 100644 --- a/crates/mega-evm/tests/_pending/src/evm/context.rs +++ b/crates/mega-evm/tests/_pending/src/evm/context.rs @@ -11,44 +11,6 @@ mod tests { use crate::TestExternalEnvs; - #[test] - fn test_with_cfg_updates_spec() { - // Create context with initial spec - let mut context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Verify initial state - assert_eq!(context.mega_spec(), MegaSpecId::EQUIVALENCE); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::EQUIVALENCE)); - - // Create new config with different spec - let new_cfg = CfgEnv::new_with_spec(MegaSpecId::MINI_REX); - - // Apply new config using with_cfg - context = context.with_cfg(new_cfg); - - // Verify that both the context's spec and inner config's spec are updated - assert_eq!(context.mega_spec(), MegaSpecId::MINI_REX); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::MINI_REX)); - } - - #[test] - fn test_with_cfg_spec_consistency() { - let context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Test multiple spec transitions - let specs_to_test = [MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]; - - let mut current_context = context; - for spec in specs_to_test { - let cfg = CfgEnv::new_with_spec(spec); - current_context = current_context.with_cfg(cfg); - - // Verify consistency between context spec and inner config spec - assert_eq!(current_context.mega_spec(), spec); - assert_eq!(current_context.inner.cfg.spec, OpSpecId::from(spec)); - } - } - /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. #[test] fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { @@ -85,27 +47,4 @@ mod tests { assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); } - /// The test/bench-only `new_with_ext_envs` wrapper builds a `MegaContext` - /// over a caller-supplied external environment (`TestExternalEnvs`), at the - /// requested spec and wired to the given SALT/oracle handles. - #[test] - fn test_new_with_ext_envs_builds_over_configurable_env() { - let env = TestExternalEnvs::::new(); - let context = - MegaContext::<_, TestExternalEnvs>::new_with_ext_envs( - EmptyDB::default(), - MegaSpecId::REX5, - Rc::new(env.clone()), - Rc::new(RefCell::new(env)), - ); - - assert_eq!(context.mega_spec(), MegaSpecId::REX5); - // The supplied SALT env is wired through: a bucket lookup against the - // dynamic-gas cache succeeds. - context - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(address!("0000000000000000000000000000000000100003")) - .expect("bucket lookup against the supplied env should succeed"); - } } diff --git a/crates/mega-evm/tests/_pending/src/evm/factory.rs b/crates/mega-evm/tests/_pending/src/evm/factory.rs index 21de89a5a..3fdb3d831 100644 --- a/crates/mega-evm/tests/_pending/src/evm/factory.rs +++ b/crates/mega-evm/tests/_pending/src/evm/factory.rs @@ -6,16 +6,6 @@ mod tests { use super::*; - #[test] - fn test_external_env_factory_getter() { - let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); - - let got: &EmptyExternalEnv = factory.external_env_factory(); - - // Verify the getter returns a stable reference to the same field. - assert!(core::ptr::eq(got, factory.external_env_factory())); - } - #[test] fn test_dyn_precompiles_builder_receives_the_behavior_spec() { use alloy_evm::EvmFactory as _; diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs index f2cd103b1..993004bac 100644 --- a/crates/mega-evm/tests/_pending/src/evm/mod.rs +++ b/crates/mega-evm/tests/_pending/src/evm/mod.rs @@ -47,94 +47,6 @@ mod tests { tx } - #[test] - fn test_mega_evm_builder_chain_produces_working_evm() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let context = configure_context(&mut db); - let evm = MegaEvm::new(context); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(777); - let evm = evm.with_tx_runtime_limits(limits); - assert_eq!(evm.ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, 777); - - let evm = evm.with_dyn_precompiles(HashMap::default()); - let evm = evm.with_inspector(NoOpInspector); - let evm = evm.without_inspector(); - - let inner = evm.into_inner(); - assert_eq!(inner.ctx.block.gas_limit, u64::MAX); - } - - #[test] - fn test_alloy_evm_interface_methods_execute_transactions() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - assert_eq!(alloy_evm::Evm::chain_id(&evm), evm.ctx_ref().cfg.chain_id); - assert_eq!(alloy_evm::Evm::block(&evm).gas_limit, evm.ctx_ref().block.gas_limit); - - alloy_evm::Evm::set_inspector_enabled(&mut evm, true); - assert!(evm.inspect); - let (_db_ref, _inspector, _precompiles) = alloy_evm::Evm::components(&evm); - let (_db_ref_mut, _inspector_mut, _precompiles_mut) = - alloy_evm::Evm::components_mut(&mut evm); - - let result = alloy_evm::Evm::transact_raw(&mut evm, mega_tx()).unwrap(); - assert!(result.result.is_success()); - - let system_call = - alloy_evm::Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()).unwrap(); - assert!(system_call.result.is_success()); - - let (_db_back, evm_env) = alloy_evm::Evm::finish(evm); - assert_eq!(evm_env.cfg_env.spec, MegaSpecId::REX4); - } - - #[test] - fn test_revm_execute_one_finalize_commit_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let block = revm::context::BlockEnv { gas_limit: 222_222, ..Default::default() }; - ExecuteEvm::set_block(&mut evm, block); - assert_eq!(evm.block_env_ref().gas_limit, 222_222); - - let one: ExecutionResult = - ExecuteEvm::transact_one(&mut evm, mega_tx()).unwrap(); - assert!(one.is_success()); - let state = ExecuteEvm::finalize(&mut evm); - ExecuteCommitEvm::commit(&mut evm, state); - } - - #[test] - fn test_revm_replay_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - evm.ctx().set_tx(mega_tx()); - let replay: ExecResultAndState, EvmState> = - ExecuteEvm::replay(&mut evm).unwrap(); - assert!(replay.result.is_success()); - } - - #[test] - fn test_revm_inspect_one_tx_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - InspectEvm::set_inspector(&mut evm, NoOpInspector); - let inspected: ExecutionResult = - InspectEvm::inspect_one_tx(&mut evm, mega_tx()).unwrap(); - assert!(inspected.is_success()); - } - #[test] fn test_revm_system_call_with_caller_works() { let mut db = MemoryDatabase::default() @@ -212,22 +124,4 @@ mod tests { assert!(inspected.result.is_success()); } - #[test] - fn test_execute_transaction_fails_with_insufficient_balance() { - let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::from(1_000_000), - data: Bytes::new(), - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.execute_transaction(tx); - assert!(result.is_err()); - } } diff --git a/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs b/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs deleted file mode 100644 index e1bf5b278..000000000 --- a/crates/mega-evm/tests/_pending/src/test_utils/opcode_gen.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/test_utils/opcode_gen.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/test_utils/opcode_gen.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use core::convert::Infallible; - - use alloy_primitives::address; - use revm::context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - }; - - use crate::{ - test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, - }; - - use super::*; - - fn execute_bytecode( - bytecode: Bytes, - ) -> Result, EVMError> { - let contract = address!("0000000000000000000000000000000000100001"); - let mut db = MemoryDatabase::default(); - db.set_account_code(contract, bytecode); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default().call(contract).gas_limit(1_000_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) - } - - #[test] - fn test_assert_stack_value_success() { - let mut builder = BytecodeBuilder::default().push_number(0x2333u64); - builder = builder.assert_stack_value(0, U256::from(0x2333u64)); - let bytecode = builder.build(); - let result = execute_bytecode(bytecode); - assert!(result.unwrap().result.is_success(), "Transaction should succeed"); - } - - #[test] - fn test_assert_stack_value_failure() { - let mut builder = BytecodeBuilder::default().push_number(0x2333u64); - builder = builder.assert_stack_value(0, U256::from(0x9999u64)); - let bytecode = builder.build(); - let result = execute_bytecode(bytecode); - assert!(result.unwrap().result.is_halt(), "Transaction should fail"); - } -} diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs new file mode 100644 index 000000000..b8d59cbfa --- /dev/null +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -0,0 +1,158 @@ +//! `MegaEvm` on Satin adds nothing to op-revm yet. +//! +//! The same transaction on the same `CfgEnv`, block and L1 info must produce the same result +//! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and +//! the resulting state. Once later tickets add `MegaETH` behavior (SALT pricing, history gas, +//! limits), these cases stay the baseline that shows where the two diverge on purpose. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, +}; +use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use revm::{ + context::{ + result::{ExecResultAndState, ExecutionResult}, + BlockEnv, CfgEnv, Context, ContextTr, TxEnv, + }, + inspector::NoOpInspector, + state::EvmState, + ExecuteEvm, Journal, +}; + +const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); +const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); + +type Outcome = ExecResultAndState, EvmState>; +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +fn block() -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1_800_000_000u64), + gas_limit: 10_000_000_000, + ..Default::default() + } +} + +fn l1_block_info() -> L1BlockInfo { + L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + } +} + +fn op_tx(tx: TxEnv) -> OpTransaction { + OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() } +} + +/// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the +/// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes and that `CfgEnv`. +fn run_both(db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, CfgEnv) { + let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) + .with_block(block()) + .with_chain(l1_block_info()); + let cfg = ctx.cfg().clone(); + let mut mega = MegaEvm::new(ctx); + let mega_outcome = mega.transact(OpTx(op_tx(tx.clone()))).unwrap(); + + let op_ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_block(block()) + .with_chain(l1_block_info()); + let mut op = OpEvm::new(op_ctx, NoOpInspector); + let op_outcome = op.transact(op_tx(tx)).unwrap(); + + (mega_outcome, op_outcome, cfg) +} + +/// Asserts the two outcomes agree field by field, then as a whole so a field added later is +/// covered too. +fn assert_same(mega: &Outcome, op: &Outcome) { + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); + assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); + assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); + assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); + assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); + assert_eq!(m, o, "ResultGas"); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result, op.result, "execution result"); + assert_eq!(mega.state, op.state, "state"); +} + +/// Both engines run on the Satin configuration: Karst with EIP-8037 and EIP-2780 switched on +/// and the 200M execution cap. +fn assert_satin_cfg(cfg: &CfgEnv) { + assert_eq!(cfg.spec, OpSpecId::KARST); + assert!(cfg.enable_amsterdam_eip8037); + assert!(cfg.enable_amsterdam_eip2780); + assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); +} + +#[test] +fn test_empty_transaction_matches_op_revm() { + // The gas limit exceeds the execution cap, so the rest goes to the EIP-8037 reservoir; an + // empty call draws no state gas, so all of it is left over. + let reservoir = 1_000_000; + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: TX_GAS_LIMIT_CAP + reservoir, + ..Default::default() + }; + let (mega, op, cfg) = run_both(MemoryDatabase::default(), tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.result.gas().reservoir_remaining(), reservoir); + assert_same(&mega, &op); +} + +#[test] +fn test_value_transfer_matches_op_revm() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value: U256::from(1_000), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.state[&CALLEE].info.balance, U256::from(1_000)); + assert_same(&mega, &op); +} + +#[test] +fn test_sstore_matches_op_revm() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.state[&CALLEE].storage[&U256::ZERO].present_value, U256::from(42)); + assert_same(&mega, &op); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs new file mode 100644 index 000000000..449988970 --- /dev/null +++ b/crates/mega-evm/tests/satin/main.rs @@ -0,0 +1,3 @@ +//! Tests of the Satin engine. + +mod equivalence; From 9c4d5cdfeb5994262d0fa5aebb49fea6d6e46fd9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 10:58:38 +0800 Subject: [PATCH 010/201] feat: move the keyless deployment helpers to system/keyless as data-only modules The RLP decoding, signer recovery, deploy-address derivation and the IKeylessDeploy error ABI move from the retired sandbox module with their fourteen unit tests. Satin has one spec, so decode_keyless_tx drops its spec argument and always rejects trailing bytes (the Rex5 rule); the pre-Rex5 acceptance test goes. ParentBudgetExceeded goes too: it named the sandbox preflight, which the native CREATE sub-frame (native keyless deployment) retires. --- crates/mega-evm/src/lib.rs | 1 + crates/mega-evm/src/system/keyless/error.rs | 306 ++++++++++++++++++ crates/mega-evm/src/system/keyless/mod.rs | 13 + .../src/sandbox => src/system/keyless}/tx.rs | 127 ++++++-- crates/mega-evm/src/system/mod.rs | 6 + crates/mega-evm/tests/_pending/README.md | 6 +- .../tests/_pending/src/sandbox/error.rs | 50 --- 7 files changed, 437 insertions(+), 72 deletions(-) create mode 100644 crates/mega-evm/src/system/keyless/error.rs create mode 100644 crates/mega-evm/src/system/keyless/mod.rs rename crates/mega-evm/{tests/_pending/src/sandbox => src/system/keyless}/tx.rs (74%) create mode 100644 crates/mega-evm/src/system/mod.rs delete mode 100644 crates/mega-evm/tests/_pending/src/sandbox/error.rs diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 505a9a6bd..f6f178047 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -10,6 +10,7 @@ mod block; pub mod constants; mod evm; mod external; +pub mod system; #[cfg(any(test, feature = "test-utils"))] pub mod test_utils; mod types; diff --git a/crates/mega-evm/src/system/keyless/error.rs b/crates/mega-evm/src/system/keyless/error.rs new file mode 100644 index 000000000..029bee46c --- /dev/null +++ b/crates/mega-evm/src/system/keyless/error.rs @@ -0,0 +1,306 @@ +//! Error types of keyless deployment. + +use alloy_primitives::Bytes; +use alloy_sol_types::SolError; +use mega_system_contracts::keyless_deploy::IKeylessDeploy; + +use crate::MegaHaltReason; + +/// Error types for keyless deployment operations. +/// +/// Most variants map directly to Solidity errors defined in `IKeylessDeploy`. +/// Internal-only variants are mapped at the ABI boundary by `encode_error_result`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeylessDeployError { + /// The transaction data is malformed (invalid RLP encoding) + MalformedEncoding, + /// The transaction is not a contract creation (to address is not empty) + NotContractCreation, + /// The transaction is not pre-EIP-155 (v must be 27 or 28) + NotPreEIP155, + /// The nonce in the signed transaction is not zero + NonZeroTxNonce { + /// The nonce value in the signed transaction + tx_nonce: u64, + }, + /// The call tried to transfer ether (maps to `NoEtherTransfer`) + NoEtherTransfer, + /// Failed to recover signer from signature (invalid signature) + InvalidSignature, + /// The signer does not have enough balance to cover the sandbox tx's pre-execution + /// debit: `gas_limit × gas_price + value` on pre-Rex5 specs, `value` only on Rex5+ + /// (where the sandbox tx is fee-free and only the `value` transfer needs funding). + InsufficientBalance, + /// The deploy address already has code (contract already exists) + ContractAlreadyExists, + /// The signer nonce is higher than allowed for keyless deploy + SignerNonceTooHigh { + /// The on-chain nonce of the recovered signer + signer_nonce: u64, + }, + /// The sandbox execution reverted + ExecutionReverted { + /// The gas used + gas_used: u64, + /// The output + output: Bytes, + }, + /// The sandbox execution halted (out of gas, stack overflow, etc.) + ExecutionHalted { + /// The gas used + gas_used: u64, + /// The reason + reason: MegaHaltReason, + }, + /// Contract creation succeeded but returned empty bytecode + EmptyCodeDeployed { + /// The gas used + gas_used: u64, + }, + /// Contract creation succeeded but no address was returned (unexpected EVM behavior) + NoContractCreated, + /// The created contract address doesn't match the expected address (internal bug) + AddressMismatch, + /// The gas limit override is less than the gas limit in the keyless transaction + GasLimitTooLow { + /// The gas limit from the keyless transaction + tx_gas_limit: u64, + /// The gas limit override provided by the caller + provided_gas_limit: u64, + }, + /// The remaining compute gas is insufficient to pay for the keyless deploy overhead. + InsufficientComputeGas { + /// The configured compute gas limit + limit: u64, + /// The actual compute gas usage + used: u64, + }, + /// The keyless transaction's init code exceeds the configured maximum init code size. + /// + /// Rex5+ only: the sandbox runs as an OP deposit-like transaction which bypasses + /// op-revm's `validate_env` (where revm's EIP-3860 size check lives), so the sandbox + /// must re-enforce the limit itself against `cfg().max_initcode_size()`. + InitCodeTooLarge { + /// The init code length in bytes. + size: u64, + /// The configured max init code size. + max: u64, + }, + /// The recovered signer has non-empty, non-EIP-7702 bytecode in parent state. + /// + /// Rex5+ only: the deposit-style sandbox bypasses op-revm's EIP-3607 check (which + /// normally lives in `validate_account_nonce_and_code`), so the sandbox enforces it + /// itself before constructing the sandbox transaction. + SignerHasCode, + /// Internal sandbox failure (DB I/O, header validation, etc.). + /// Selector-only so the top-level error ABI stays stable and does not depend on + /// upstream revm/op-revm `Display` text. The interceptor only runs at call depth 0, + /// so this returndata has no inner caller to read it and never reaches a consensus + /// root; the selector-only shape is for off-chain decoder/tooling stability. + InternalError, + /// Sandbox rejected the inner transaction as a tx-validation error + /// (`IsTxError::is_tx_error() == true`). A dedicated selector lets relayer-side + /// decoders distinguish this from a genuine internal failure. Selector-only for the + /// same ABI-stability reason as `InternalError`. + InvalidTransaction, + /// The keylessDeploy call was not intercepted (only returned by Solidity contract for inner + /// calls) + NotIntercepted, +} + +/// Encodes a keyless deploy error as ABI-encoded revert data. +/// +/// Uses the generated Solidity error bindings from IKeylessDeploy.sol. +pub fn encode_error_result(error: KeylessDeployError) -> Bytes { + match error { + KeylessDeployError::MalformedEncoding => { + IKeylessDeploy::MalformedEncoding {}.abi_encode().into() + } + KeylessDeployError::NotContractCreation => { + IKeylessDeploy::NotContractCreation {}.abi_encode().into() + } + KeylessDeployError::NotPreEIP155 => IKeylessDeploy::NotPreEIP155 {}.abi_encode().into(), + KeylessDeployError::NonZeroTxNonce { tx_nonce } => { + IKeylessDeploy::NonZeroTxNonce { txNonce: tx_nonce }.abi_encode().into() + } + KeylessDeployError::NoEtherTransfer => { + IKeylessDeploy::NoEtherTransfer {}.abi_encode().into() + } + KeylessDeployError::InvalidSignature => { + IKeylessDeploy::InvalidSignature {}.abi_encode().into() + } + KeylessDeployError::InsufficientBalance => { + IKeylessDeploy::InsufficientBalance {}.abi_encode().into() + } + KeylessDeployError::ContractAlreadyExists => { + IKeylessDeploy::ContractAlreadyExists {}.abi_encode().into() + } + KeylessDeployError::SignerNonceTooHigh { signer_nonce } => { + IKeylessDeploy::SignerNonceTooHigh { signerNonce: signer_nonce }.abi_encode().into() + } + KeylessDeployError::ExecutionReverted { gas_used, output } => { + IKeylessDeploy::ExecutionReverted { gasUsed: gas_used, output }.abi_encode().into() + } + KeylessDeployError::ExecutionHalted { gas_used, .. } => { + IKeylessDeploy::ExecutionHalted { gasUsed: gas_used }.abi_encode().into() + } + KeylessDeployError::EmptyCodeDeployed { gas_used } => { + IKeylessDeploy::EmptyCodeDeployed { gasUsed: gas_used }.abi_encode().into() + } + KeylessDeployError::NoContractCreated => { + IKeylessDeploy::NoContractCreated {}.abi_encode().into() + } + KeylessDeployError::AddressMismatch => { + IKeylessDeploy::AddressMismatch {}.abi_encode().into() + } + KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } => { + IKeylessDeploy::GasLimitTooLow { + txGasLimit: tx_gas_limit, + providedGasLimit: provided_gas_limit, + } + .abi_encode() + .into() + } + KeylessDeployError::InsufficientComputeGas { limit, used } => { + IKeylessDeploy::InsufficientComputeGas { limit, used }.abi_encode().into() + } + KeylessDeployError::InitCodeTooLarge { size, max } => { + IKeylessDeploy::InitCodeTooLarge { size, max }.abi_encode().into() + } + KeylessDeployError::SignerHasCode => IKeylessDeploy::SignerHasCode {}.abi_encode().into(), + KeylessDeployError::InternalError => IKeylessDeploy::InternalError {}.abi_encode().into(), + KeylessDeployError::InvalidTransaction => { + IKeylessDeploy::InvalidTransaction {}.abi_encode().into() + } + KeylessDeployError::NotIntercepted => IKeylessDeploy::NotIntercepted {}.abi_encode().into(), + } +} + +/// Decodes ABI-encoded revert data into a `KeylessDeployError`. +/// +/// Returns `None` if the data doesn't match any known error format. +/// +/// Note: For `ExecutionHalted`, the halt reason cannot be recovered from ABI encoding, +/// so a default `OutOfGas` reason is used. +pub fn decode_error_result(output: &[u8]) -> Option { + if IKeylessDeploy::NoEtherTransfer::abi_decode(output).is_ok() { + return Some(KeylessDeployError::NoEtherTransfer); + } + if IKeylessDeploy::MalformedEncoding::abi_decode(output).is_ok() { + return Some(KeylessDeployError::MalformedEncoding); + } + if IKeylessDeploy::NotContractCreation::abi_decode(output).is_ok() { + return Some(KeylessDeployError::NotContractCreation); + } + if IKeylessDeploy::NotPreEIP155::abi_decode(output).is_ok() { + return Some(KeylessDeployError::NotPreEIP155); + } + if let Ok(e) = IKeylessDeploy::NonZeroTxNonce::abi_decode(output) { + return Some(KeylessDeployError::NonZeroTxNonce { tx_nonce: e.txNonce }); + } + if IKeylessDeploy::InvalidSignature::abi_decode(output).is_ok() { + return Some(KeylessDeployError::InvalidSignature); + } + if IKeylessDeploy::InsufficientBalance::abi_decode(output).is_ok() { + return Some(KeylessDeployError::InsufficientBalance); + } + if IKeylessDeploy::ContractAlreadyExists::abi_decode(output).is_ok() { + return Some(KeylessDeployError::ContractAlreadyExists); + } + if let Ok(e) = IKeylessDeploy::SignerNonceTooHigh::abi_decode(output) { + return Some(KeylessDeployError::SignerNonceTooHigh { signer_nonce: e.signerNonce }); + } + if let Ok(e) = IKeylessDeploy::ExecutionReverted::abi_decode(output) { + return Some(KeylessDeployError::ExecutionReverted { + gas_used: e.gasUsed, + output: e.output, + }); + } + if let Ok(e) = IKeylessDeploy::ExecutionHalted::abi_decode(output) { + // Note: The actual halt reason is lost in ABI encoding, use OutOfGas as placeholder + return Some(KeylessDeployError::ExecutionHalted { + gas_used: e.gasUsed, + reason: MegaHaltReason::Base(revm::context::result::HaltReason::OutOfGas( + revm::context::result::OutOfGasError::Basic, + )), + }); + } + if let Ok(e) = IKeylessDeploy::EmptyCodeDeployed::abi_decode(output) { + return Some(KeylessDeployError::EmptyCodeDeployed { gas_used: e.gasUsed }); + } + if IKeylessDeploy::NoContractCreated::abi_decode(output).is_ok() { + return Some(KeylessDeployError::NoContractCreated); + } + if IKeylessDeploy::AddressMismatch::abi_decode(output).is_ok() { + return Some(KeylessDeployError::AddressMismatch); + } + if let Ok(e) = IKeylessDeploy::GasLimitTooLow::abi_decode(output) { + return Some(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: e.txGasLimit, + provided_gas_limit: e.providedGasLimit, + }); + } + if let Ok(e) = IKeylessDeploy::InitCodeTooLarge::abi_decode(output) { + return Some(KeylessDeployError::InitCodeTooLarge { size: e.size, max: e.max }); + } + if IKeylessDeploy::SignerHasCode::abi_decode(output).is_ok() { + return Some(KeylessDeployError::SignerHasCode); + } + if IKeylessDeploy::InvalidTransaction::abi_decode(output).is_ok() { + return Some(KeylessDeployError::InvalidTransaction); + } + if IKeylessDeploy::InternalError::abi_decode(output).is_ok() { + return Some(KeylessDeployError::InternalError); + } + if IKeylessDeploy::NotIntercepted::abi_decode(output).is_ok() { + return Some(KeylessDeployError::NotIntercepted); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `InternalError` and `InvalidTransaction` carry no payload on the wire, so a + /// roundtrip MUST produce the same variant. Pinned because these selectors are the + /// off-chain error ABI (RPC, traces, relayer decoders); a divergence between + /// `encode_error_result` and `decode_error_result` would silently break those decoders. + #[test] + fn test_internal_error_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::InternalError); + // Selector-only: the encoded form is exactly the 4-byte Solidity selector. + assert_eq!(encoded.len(), 4, "InternalError must be selector-only"); + assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::InternalError))); + } + + #[test] + fn test_invalid_transaction_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::InvalidTransaction); + assert_eq!(encoded.len(), 4, "InvalidTransaction must be selector-only"); + assert!(matches!( + decode_error_result(&encoded), + Some(KeylessDeployError::InvalidTransaction) + )); + } + + /// `InitCodeTooLarge { size, max }` is an externally visible ABI selector. Pinning the + /// round-trip catches any drift between the Solidity error definition and the Rust + /// encode/decode (e.g. forgotten arm in `encode_error_result` or `decode_error_result`, + /// or accidental field reordering). + #[test] + fn test_init_code_too_large_roundtrip_preserves_size_and_max() { + let original = KeylessDeployError::InitCodeTooLarge { size: 600_000, max: 548_864 }; + let encoded = encode_error_result(original.clone()); + let decoded = decode_error_result(&encoded).expect("must decode"); + assert_eq!(decoded, original); + } + + /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. + #[test] + fn test_signer_has_code_roundtrip_is_selector_only() { + let encoded = encode_error_result(KeylessDeployError::SignerHasCode); + assert_eq!(encoded.len(), 4, "SignerHasCode must be selector-only"); + assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::SignerHasCode))); + } +} diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs new file mode 100644 index 000000000..38b4dbbc2 --- /dev/null +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -0,0 +1,13 @@ +//! Keyless deployment (Nick's Method): the transaction format, its validation rules and the +//! error ABI. +//! +//! These are data-only helpers: decoding the pre-EIP-155 transaction, recovering its signer, +//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. T6.1 +//! adds the interceptor that dispatches `keylessDeploy` calls, and T7 executes the deployment +//! as a native CREATE sub-frame. + +mod error; +mod tx; + +pub use error::*; +pub use tx::*; diff --git a/crates/mega-evm/tests/_pending/src/sandbox/tx.rs b/crates/mega-evm/src/system/keyless/tx.rs similarity index 74% rename from crates/mega-evm/tests/_pending/src/sandbox/tx.rs rename to crates/mega-evm/src/system/keyless/tx.rs index ea2cbae97..8f2d1e199 100644 --- a/crates/mega-evm/tests/_pending/src/sandbox/tx.rs +++ b/crates/mega-evm/src/system/keyless/tx.rs @@ -1,6 +1,98 @@ -//! Unit tests extracted from `crates/mega-evm/src/sandbox/tx.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/tx.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Keyless deploy transaction types and functions. +//! +//! This module provides functions for decoding and validating pre-EIP-155 legacy transactions +//! used in Nick's Method for deterministic contract deployment. +//! +//! # Two-Phase Validation +//! +//! Transaction validation occurs in two distinct phases: +//! +//! ## Phase 1: RLP Decoding ([`decode_keyless_tx`]) +//! +//! Structural validation of the transaction format: +//! - Valid RLP encoding of a legacy transaction +//! - No trailing bytes after the RLP payload (rejected as `MalformedEncoding`) +//! - EIP-2718 typed envelopes (0x01, 0x02, etc.) rejected as `MalformedEncoding` +//! - `to` field must be empty (contract creation) +//! - `v` must be 27 or 28 (pre-EIP-155, no chain ID) +//! +//! ## Phase 2: Signature Recovery ([`recover_signer`]) +//! +//! Cryptographic validation of the signature: +//! - Signature components (r, s) must be valid secp256k1 curve points +//! - Invalid/corrupted signatures fail with `InvalidSignature` +//! - Recovery uses alloy's ECDSA implementation +//! +//! # Security Notes +//! +//! - **Signature modification changes identity**: Altering r or s values produces a different +//! recovered signer address, not an invalid signature. +//! - **Empty initcode is allowed**: Transactions with empty `data` pass decoding but result in +//! `EmptyCodeDeployed` during execution. + +use alloy_consensus::{transaction::RlpEcdsaDecodableTx, Signed, TxLegacy}; +use alloy_primitives::Address; + +use super::error::KeylessDeployError; + +/// Decodes a pre-EIP-155 legacy transaction from RLP bytes. +/// +/// The expected RLP structure is: `[nonce, gasPrice, gasLimit, to, value, data, v, r, s]` +/// +/// # Validation +/// - The RLP encoding must be valid +/// - The input must not contain trailing bytes after the RLP transaction +/// - The `to` field must be empty (contract creation) +/// - The `v` value must be 27 or 28 (pre-EIP-155) +/// +/// # Returns +/// - `Ok(Signed)` if the transaction is valid +/// - `Err(KeylessDeployError::MalformedEncoding)` on invalid RLP or trailing bytes +/// - `Err(KeylessDeployError::NotContractCreation)` if `to` is not empty +/// - `Err(KeylessDeployError::NotPreEIP155)` if a chain id is present +pub fn decode_keyless_tx(rlp_bytes: &[u8]) -> Result, KeylessDeployError> { + let mut buf = rlp_bytes; + let signed = + TxLegacy::rlp_decode_signed(&mut buf).map_err(|_| KeylessDeployError::MalformedEncoding)?; + + // Reject trailing bytes. The raw input is reused as `enveloped_tx` for L1 data-fee + // accounting, so any bytes past the signed RLP payload would otherwise be silently + // charged without being part of the signed transaction. + if !buf.is_empty() { + return Err(KeylessDeployError::MalformedEncoding); + } + + if !signed.tx().to.is_create() { + return Err(KeylessDeployError::NotContractCreation); + } + if signed.tx().chain_id.is_some() { + return Err(KeylessDeployError::NotPreEIP155); + } + Ok(signed) +} + +/// Recovers the signer address from a keyless deployment transaction. +/// +/// Uses alloy's built-in signature recovery to derive the signer address +/// from the signed transaction. +/// +/// # Returns +/// - `Ok(Address)` - The recovered signer address +/// - `Err(KeylessDeployError::InvalidSignature)` - If signature recovery fails +pub fn recover_signer(signed_tx: &Signed) -> Result { + signed_tx.recover_signer().map_err(|_| KeylessDeployError::InvalidSignature) +} + +/// Calculates the deployment address for a contract created by the given signer. +/// +/// For Nick's Method, the nonce is always 0, so the deployment address is: +/// `keccak256(rlp([signer, 0]))[12:]` +/// +/// This is equivalent to `signer.create(0)` in alloy. +#[inline] +pub fn calculate_keyless_deploy_address(signer: Address) -> Address { + signer.create(0) +} #[allow(missing_docs, unused)] #[cfg(any(test, feature = "test-utils"))] @@ -72,8 +164,8 @@ pub mod tests { #[test] fn test_decode_create2_factory_deployment() { // The canonical CREATE2 factory deployment - a well-known pre-EIP-155 transaction - let signed = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5) - .expect("should decode CREATE2 factory tx"); + let signed = + decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode CREATE2 factory tx"); let tx = signed.tx(); assert_eq!(tx.nonce, 0); @@ -105,7 +197,7 @@ pub mod tests { #[test] fn test_recover_signer_create2_factory() { // Verify we can recover the correct signer from the CREATE2 factory tx - let tx = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5).expect("should decode"); + let tx = decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode"); let signer = recover_signer(&tx).expect("should recover signer"); // The canonical CREATE2 factory signer address @@ -115,7 +207,7 @@ pub mod tests { #[test] fn test_calculate_create2_factory_deploy_address() { // Verify the deployment address calculation matches the known CREATE2 factory address - let tx = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5).expect("should decode"); + let tx = decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode"); let signer = recover_signer(&tx).expect("should recover signer"); let deploy_address = calculate_keyless_deploy_address(signer); @@ -127,7 +219,7 @@ pub mod tests { fn test_decode_rejects_post_eip155_chain_1() { // Transaction generated with: cast mktx ... --chain 1 --create 0x6080604052 // v = 1 * 2 + 35 + 1 = 38 (0x26) - let result = decode_keyless_tx(POST_EIP155_CHAIN_1_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(POST_EIP155_CHAIN_1_TX); assert_eq!(result, Err(KeylessDeployError::NotPreEIP155)); } @@ -135,7 +227,7 @@ pub mod tests { fn test_decode_rejects_post_eip155_chain_1337() { // Transaction generated with: cast mktx ... --chain 1337 --create 0x6080604052 // v = 1337 * 2 + 35 + 0 = 2709 (0x0a95) - let result = decode_keyless_tx(POST_EIP155_CHAIN_1337_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(POST_EIP155_CHAIN_1337_TX); assert_eq!(result, Err(KeylessDeployError::NotPreEIP155)); } @@ -143,7 +235,7 @@ pub mod tests { fn test_decode_rejects_non_contract_creation() { // Transaction with to=0x4242...42 (not a contract creation) // Generated with: cast mktx ... --legacy 0x4242424242424242424242424242424242424242 - let result = decode_keyless_tx(NON_CONTRACT_CREATION_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(NON_CONTRACT_CREATION_TX); assert_eq!(result, Err(KeylessDeployError::NotContractCreation)); } @@ -151,13 +243,13 @@ pub mod tests { fn test_decode_rejects_malformed_rlp() { // Random bytes, not valid RLP let invalid_rlp = hex!("deadbeef"); - let result = decode_keyless_tx(&invalid_rlp, MegaSpecId::REX5); + let result = decode_keyless_tx(&invalid_rlp); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } #[test] fn test_decode_rejects_empty_input() { - let result = decode_keyless_tx(&[], MegaSpecId::REX5); + let result = decode_keyless_tx(&[]); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } @@ -165,24 +257,23 @@ pub mod tests { fn test_decode_rejects_truncated_rlp() { // Truncate the CREATE2 factory tx let truncated = &CREATE2_FACTORY_TX[..CREATE2_FACTORY_TX.len() - 10]; - let result = decode_keyless_tx(truncated, MegaSpecId::REX5); + let result = decode_keyless_tx(truncated); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } #[test] - fn test_decode_rejects_trailing_bytes_rex5() { - // Rex5+: trailing bytes after the signed RLP payload are rejected to prevent + fn test_decode_rejects_trailing_bytes() { + // Trailing bytes after the signed RLP payload are rejected to prevent // unsigned bytes from affecting `enveloped_tx` / L1 data-fee accounting. let mut with_trailing = CREATE2_FACTORY_TX.to_vec(); with_trailing.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX5); + let result = decode_keyless_tx(&with_trailing); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); // A single trailing byte must also be rejected. let mut with_one_trailing = CREATE2_FACTORY_TX.to_vec(); with_one_trailing.push(0x00); - let result = decode_keyless_tx(&with_one_trailing, MegaSpecId::REX5); + let result = decode_keyless_tx(&with_one_trailing); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } - } diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs new file mode 100644 index 000000000..192392163 --- /dev/null +++ b/crates/mega-evm/src/system/mod.rs @@ -0,0 +1,6 @@ +//! System contracts of the Satin engine. +//! +//! Filled by T6.1 (interceptor dispatch), T6.2 (deployment at activation) and T6.3 (oracle and +//! control contracts). For now it holds only the keyless-deployment data helpers. + +pub mod keyless; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 96f6168fe..f3eb3b003 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -39,11 +39,11 @@ Do not add a `_pending/main.rs`. | T6.1 | 65 | 57 | 8 | 56 | 9 | 0 | | T6.2 | 67 | 17 | 50 | 62 | 5 | 0 | | T6.3 | 77 | 77 | 0 | 67 | 10 | 0 | -| T7 | 89 | 73 | 16 | 43 | 46 | 0 | +| T7 | 75 | 73 | 2 | 29 | 46 | 0 | | T8.1 | 75 | 45 | 30 | 56 | 19 | 0 | | T9 | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **850** | **691** | **159** | **499** | **322** | **29** | +| **Total** | **836** | **691** | **145** | **485** | **322** | **29** | ## Tests T0 assigns to T2.1 that are parked under another ticket @@ -162,9 +162,7 @@ Each cell lists `disposition count (ticket · decision)`. | `src/limit/kv_update.rs` | 1 | 待定 1 (T4.3 · D46) | | `src/limit/limit.rs` | 4 | 保留 4 (T3.3 · D51) | | `src/limit/mod.rs` | 3 | 保留 3 (T2.3) | -| `src/sandbox/error.rs` | 4 | 保留 4 (T7 · error types kept (T2.1 list)) | | `src/sandbox/execution.rs` | 2 | 保留 1 (T7 · rule); 重写 1 (T7 · D16) | -| `src/sandbox/tx.rs` | 10 | 保留 10 (T7 · rules 1-9 helpers kept (T2.1 list)) | | `src/system/control.rs` | 8 | 保留 8 (T6.2 · T6.1 for selector/revert-data tests) | | `src/system/deploy.rs` | 4 | 保留 3 (T6.2); 重写 1 (T6.2 · single version) | | `src/system/intercept.rs` | 2 | 保留 2 (T6.1) | diff --git a/crates/mega-evm/tests/_pending/src/sandbox/error.rs b/crates/mega-evm/tests/_pending/src/sandbox/error.rs deleted file mode 100644 index ac6df1027..000000000 --- a/crates/mega-evm/tests/_pending/src/sandbox/error.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/sandbox/error.rs` when T2.1 replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/error.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// `InternalError` and `InvalidTransaction` carry no payload on the wire, so a - /// roundtrip MUST produce the same variant. Pinned because these selectors are the - /// off-chain error ABI (RPC, traces, relayer decoders); a divergence between - /// `encode_error_result` and `decode_error_result` would silently break those decoders. - #[test] - fn test_internal_error_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InternalError); - // Selector-only: the encoded form is exactly the 4-byte Solidity selector. - assert_eq!(encoded.len(), 4, "InternalError must be selector-only"); - assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::InternalError))); - } - - #[test] - fn test_invalid_transaction_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InvalidTransaction); - assert_eq!(encoded.len(), 4, "InvalidTransaction must be selector-only"); - assert!(matches!( - decode_error_result(&encoded), - Some(KeylessDeployError::InvalidTransaction) - )); - } - - /// `InitCodeTooLarge { size, max }` is an externally visible ABI selector. Pinning the - /// round-trip catches any drift between the Solidity error definition and the Rust - /// encode/decode (e.g. forgotten arm in `encode_error_result` or `decode_error_result`, - /// or accidental field reordering). - #[test] - fn test_init_code_too_large_roundtrip_preserves_size_and_max() { - let original = KeylessDeployError::InitCodeTooLarge { size: 600_000, max: 548_864 }; - let encoded = encode_error_result(original.clone()); - let decoded = decode_error_result(&encoded).expect("must decode"); - assert_eq!(decoded, original); - } - - /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. - #[test] - fn test_signer_has_code_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::SignerHasCode); - assert_eq!(encoded.len(), 4, "SignerHasCode must be selector-only"); - assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::SignerHasCode))); - } -} From 922f309b3a83673124be8f83ae4c79bfc445f382 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:01:49 +0800 Subject: [PATCH 011/201] feat: add the limit and access placeholders and the block executor skeleton limit/ and access/ are empty modules whose doc line names the mechanisms that fill them (the observe-stage-commit layer and the abort protocol, the data-size limit, detention, the state-gas limits and the KV count). MegaBlockExecutor only owns its EVM for now; block execution lands on it with the block executor. --- crates/mega-evm/src/access/mod.rs | 3 ++ crates/mega-evm/src/block/executor.rs | 54 +++++++++++++++++++++++++++ crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/src/limit/mod.rs | 4 ++ 4 files changed, 63 insertions(+) create mode 100644 crates/mega-evm/src/access/mod.rs create mode 100644 crates/mega-evm/src/block/executor.rs create mode 100644 crates/mega-evm/src/limit/mod.rs diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs new file mode 100644 index 000000000..704d6e913 --- /dev/null +++ b/crates/mega-evm/src/access/mod.rs @@ -0,0 +1,3 @@ +//! Volatile-data access tracking (block environment, beneficiary, oracle) behind gas detention. +//! +//! Empty until T4.2 fills it. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs new file mode 100644 index 000000000..7efe581e9 --- /dev/null +++ b/crates/mega-evm/src/block/executor.rs @@ -0,0 +1,54 @@ +//! Block executor of the Satin engine. +//! +//! T8.1 builds block execution here: alloy-evm's `BlockExecutor` over a +//! [`MegaEvm`](crate::MegaEvm), the Karst block rules, the pre-block system calls (T5.2) and +//! deployments (T6.2), and the block-level limits. + +/// Executes the transactions of one block on a Satin EVM. +/// +/// A skeleton for now: it owns the EVM and hands it back. +#[derive(Debug)] +pub struct MegaBlockExecutor { + evm: E, +} + +impl MegaBlockExecutor { + /// Creates an executor that runs the block on `evm`. + pub const fn new(evm: E) -> Self { + Self { evm } + } + + /// The EVM the block runs on. + pub const fn evm(&self) -> &E { + &self.evm + } + + /// The EVM the block runs on, mutably. + pub const fn evm_mut(&mut self) -> &mut E { + &mut self.evm + } + + /// Consumes the executor and returns its EVM. + pub fn into_evm(self) -> E { + self.evm + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId}; + use alloy_evm::Evm; + use revm::context::BlockEnv; + + #[test] + fn test_executor_hands_back_its_evm() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) + .with_block(BlockEnv { gas_limit: 30_000_000, ..Default::default() }); + let mut executor = MegaBlockExecutor::new(MegaEvm::new(ctx)); + + assert_eq!(executor.evm().block().gas_limit, 30_000_000); + executor.evm_mut().set_inspector_enabled(true); + assert!(executor.into_evm().is_inspecting()); + } +} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 34a23e246..edf9ede21 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -1,7 +1,9 @@ //! Block-level pieces of the Satin engine. mod chain; +mod executor; mod hardfork; pub use chain::*; +pub use executor::*; pub use hardfork::*; diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs new file mode 100644 index 000000000..d9e14a636 --- /dev/null +++ b/crates/mega-evm/src/limit/mod.rs @@ -0,0 +1,4 @@ +//! Resource limits of the Satin engine. +//! +//! Empty until T2.3 (the observe-stage-commit layer and the abort protocol), T4.1 (data size), +//! T4.2 (detention caps) and T4.3 (state-gas limits and the KV count) fill it. From 0783855c4340bf4080abdafe037ced2b5b7fef11 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:01:49 +0800 Subject: [PATCH 012/201] feat: define the crate's public surface Re-export the upstream crates consumers must build against (revm, op-revm, alloy-evm, alloy-op-evm, alloy-primitives, alloy-hardforks, alloy-consensus, alloy-sol-types, op-alloy-consensus), keep the short aliases (SpecId, Evm, EvmFactory, Context, BlockExecutor, ...), and warn on unused crate dependencies again. derive_more is only used by the test utilities, so it becomes an optional dependency of the test-utils feature. --- crates/mega-evm/Cargo.toml | 4 ++-- crates/mega-evm/src/lib.rs | 39 +++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 635dbcd1f..30eb51885 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -32,7 +32,7 @@ mega-system-contracts = { workspace = true, default-features = false } # misc auto_impl.workspace = true delegate.workspace = true -derive_more = { workspace = true, features = ["deref"] } +derive_more = { workspace = true, optional = true, features = ["debug", "deref", "deref_mut", "display", "error"] } serde = { workspace = true, features = ["derive"] } [dev-dependencies] @@ -54,4 +54,4 @@ std = [ "op-revm/std", "revm/std", ] -test-utils = [] +test-utils = ["dep:derive_more"] diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index f6f178047..f19f185ee 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -1,15 +1,21 @@ //! The EVM implementation for the `MegaETH` Satin engine. +//! +//! Satin runs a single spec, [`MegaSpecId::SATIN`], on op-revm's Karst handler with EIP-8037 +//! state gas and the EIP-2780 intrinsic cost. The legacy engine (specs `Equivalence` through +//! `Rex7`) is a separate crate line; nothing here executes a legacy spec. +#![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] -#[cfg_attr(not(feature = "std"), macro_use)] #[cfg(not(feature = "std"))] extern crate alloc; +mod access; mod block; pub mod constants; mod evm; mod external; +mod limit; pub mod system; #[cfg(any(test, feature = "test-utils"))] pub mod test_utils; @@ -19,3 +25,34 @@ pub use block::*; pub use evm::*; pub use external::*; pub use types::*; + +/* Re-export of upstream crates, so consumers build against the exact versions used here */ +pub use alloy_consensus; +pub use alloy_evm; +pub use alloy_hardforks; +pub use alloy_op_evm; +pub use alloy_primitives; +pub use alloy_sol_types; +pub use op_alloy_consensus; +pub use op_revm; +pub use revm; + +/* Short aliases of the mega-evm types */ +/// Alias for [`MegaSpecId`] +pub type SpecId = MegaSpecId; +/// Alias for [`MegaTransaction`] +pub type Transaction = MegaTransaction; +/// Alias for [`MegaHaltReason`] +pub type HaltReason = MegaHaltReason; +/// Alias for [`MegaTransactionError`] +pub type TransactionError = MegaTransactionError; +/// Alias for [`MegaTxType`] +pub type TxType = MegaTxType; +/// Alias for [`MegaEvm`] +pub type Evm = MegaEvm; +/// Alias for [`MegaEvmFactory`] +pub type EvmFactory = MegaEvmFactory; +/// Alias for [`MegaContext`] +pub type Context = MegaContext; +/// Alias for [`MegaBlockExecutor`] +pub type BlockExecutor = MegaBlockExecutor; From 8d45bce50f3c29a50611e58b4906d4df1e794b9b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:04:25 +0800 Subject: [PATCH 013/201] test: add a transact bench skeleton for Satin Times ExecuteEvm::transact for an empty transaction and an ether transfer through MegaEvm and through op-revm's OpEvm on the same CfgEnv. It keeps one bench target alive until the test gates rebuild the suite. --- crates/mega-evm/Cargo.toml | 5 ++ crates/mega-evm/benches/transact.rs | 90 +++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 crates/mega-evm/benches/transact.rs diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 30eb51885..d2b1cbe59 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -55,3 +55,8 @@ std = [ "revm/std", ] test-utils = ["dep:derive_more"] + +# T2.2 rebuilds the benchmark suite on Satin; until then `transact` is the only target. +[[bench]] +name = "transact" +harness = false diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs new file mode 100644 index 000000000..1e584bbd1 --- /dev/null +++ b/crates/mega-evm/benches/transact.rs @@ -0,0 +1,90 @@ +//! `ExecuteEvm::transact` on the Satin engine next to op-revm's `OpEvm` on the same `CfgEnv`. +//! +//! A skeleton that keeps one benchmark target alive; T2.2 rebuilds the benchmark suite. Each +//! workload runs through `MegaEvm` (`satin`) and through `OpEvm` (`op_revm`), so the gap is the +//! wrapper's own cost. EVM construction is setup and is not measured. +#![allow(missing_docs)] + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use mega_evm::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId}; +use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use revm::{ + context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, + inspector::NoOpInspector, + ExecuteEvm, Journal, +}; + +const CALLER: Address = address!("0x0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0x0000000000000000000000000000000000100001"); + +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +fn l1_block_info() -> L1BlockInfo { + L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + } +} + +fn tx(value: U256) -> OpTransaction { + OpTransaction { + base: TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value, + gas_limit: 1_000_000, + ..Default::default() + }, + enveloped_tx: Some(Bytes::new()), + ..Default::default() + } +} + +fn mega_context(db: MemoryDatabase) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_chain(l1_block_info()) +} + +fn bench_transact(c: &mut Criterion) { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(1)); + let cfg = mega_context(db.clone()).cfg().clone(); + + let mut group = c.benchmark_group("transact"); + for (workload, value) in [("empty_transaction", U256::ZERO), ("ether_transfer", U256::from(1))] + { + group.bench_function(format!("{workload}/satin"), |b| { + b.iter_batched( + || MegaEvm::new(mega_context(db.clone())), + |mut evm| evm.transact(OpTx(tx(value))).unwrap(), + BatchSize::SmallInput, + ); + }); + group.bench_function(format!("{workload}/op_revm"), |b| { + b.iter_batched( + || { + let ctx = OpContext::new(db.clone(), OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_chain(l1_block_info()); + OpEvm::new(ctx, NoOpInspector) + }, + |mut evm| evm.transact(tx(value)).unwrap(), + BatchSize::SmallInput, + ); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_transact); +criterion_main!(benches); From 873bb38ea7a30b00013080ce8f1d748fb8fd8ee1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:12:35 +0800 Subject: [PATCH 014/201] test: close the mutation survivors of the Satin skeleton The diff-scoped cargo-mutants run over this series left three survivors. Two were test gaps: InspectEvm::set_inspector and MegaContext::modify_chain now have tests that observe them. The third, From for EthSpecId -> Default::default(), is equivalent while revm's default spec is Osaka, the spec SATIN maps to; it gets a line suppression, which stays live and turns into a no-op when a revm upgrade moves the default. --- crates/mega-evm/src/evm/context.rs | 7 +++++++ crates/mega-evm/src/evm/mod.rs | 8 ++++++++ mutants/suppressions.toml | 17 +++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index a17f05dc8..e5c96a0f1 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -339,6 +339,13 @@ mod tests { ); } + #[test] + fn test_modify_chain_edits_the_l1_block_info() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + ctx.modify_chain(|chain| chain.l2_block = Some(U256::from(42))); + assert_eq!(ctx.chain().l2_block, Some(U256::from(42))); + } + /// The external environments given at construction are the ones the context exposes. #[test] fn test_new_with_ext_envs_builds_over_configurable_env() { diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 5d69424c8..6facf7682 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -362,9 +362,17 @@ mod tests { let result = InspectEvm::inspect_one_tx(&mut evm, tx(U256::ZERO)).unwrap(); assert!(result.is_success()); + // The arena starts with one placeholder root node; the call fills it in. let traces = evm.inspector().traces(); assert_eq!(traces.nodes().len(), 1, "one call frame"); assert_eq!(traces.nodes()[0].trace.address, CALLEE); + + // A fresh inspector replaces the one that recorded the call. + InspectEvm::set_inspector( + &mut evm, + TracingInspector::new(TracingInspectorConfig::default_parity()), + ); + assert_eq!(evm.inspector().traces().nodes()[0].trace.address, Address::ZERO); } #[test] diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 3fc4e64cf..578cd0bda 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -179,3 +179,20 @@ file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace > with >= in ::write" justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs at len == 16, where both the mid branch (front | (back<<64)) and the large branch (read_last_u128, with no loop pass since 16 is not > 16) feed the identical le_u128(bytes[0..16]) to a single large_update. Same buffer, same bucket id; no input distinguishes them. The line-108 and line-112 mutants sharing this text are non-equivalent and are caught by the len-8 / len-32 tests." reviewer = "improve-mutation-score (William Aaron Cheung)" + +# ───────────────────────────────────────────────────────────────────────────── +# crates/mega-evm/src/evm/ survivors. + +# --- From for EthSpecId (equivalent while revm's default is Osaka) ----- +# `MegaSpecId` has the single variant SATIN, which maps to OSAKA. revm 40's +# `SpecId::default()` is also OSAKA, so the `Default::default()` mutant returns the +# same value for every input. A line entry keeps the mutant generated: once a revm +# upgrade moves the default, `test_all_specs_map_to_karst_and_osaka` kills it and this +# entry becomes a no-op. +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/evm/spec.rs" +mutant = "replace for EthSpecId>::from -> Self with Default::default()" +justification = "Equivalent: the only MegaSpecId (SATIN) maps to EthSpecId::OSAKA, which is revm 40.0.3's SpecId::default(), so Default::default() returns the same value on every input." +reviewer = "T2.1 author; to be confirmed in the Satin wave-1 PR review" From 56e6857d8fb2e00acc0a742c6e2cd08a58dbb37e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:13:27 +0800 Subject: [PATCH 015/201] docs: rewrite AGENTS.md for the Satin engine AGENTS.md now describes the satin branch: one spec (SATIN on Karst), the fork patches, the module table with the mechanism that fills each module, the _pending test layout, and the rule that today's main is the legacy engine and Satin is the only active spec. The unchanged conventions (test_ prefix, no_std, determinism, cargo sort, lint and format, one sentence per line, Prettier) stay as they were. The crate README follows, and REVIEW.md points at the parked mutation tests. --- AGENTS.md | 308 +++++++++++--------------------------- REVIEW.md | 1 + crates/mega-evm/README.md | 131 ++++------------ 3 files changed, 115 insertions(+), 325 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6f4e03b8d..8c5f0edbf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,14 +4,20 @@ This file provides guidance to AI agents (e.g., claude code, codex, cursor, etc. ## Project Overview -MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on **revm** and **op-revm** by customizing several hooks exposed by trait of revm. +MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on **revm** and **op-revm** by customizing the hooks revm exposes through its traits. + +This branch (`satin`) builds **Satin**, the new engine: a single spec on the MegaETH fork of revm 40.0.3 and the MegaETH fork of op-revm 20.0.0. +Today's `main` is the legacy engine; Satin is the only active spec. +The legacy engine (specs `Equivalence` through `Rex7`, the 1.x crate line on crates.io revm 27) is frozen and is not edited here. + +Satin is being built ticket by ticket from an empty skeleton. +The module table below says what exists and which ticket fills the rest. ## Build & Development Commands ```bash # Build cargo build -cargo build --release -p mega-evme # CLI tool # Test cargo test # all tests @@ -27,7 +33,7 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks +# Benchmarks (`transact` is the only target until T2.2 rebuilds the suite) cargo bench -p mega-evm --bench transact # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) @@ -42,214 +48,78 @@ Git submodules are required — clone with `--recursive` or run `git submodule u ## Workspace Structure -| Crate | Path | Purpose | -| ----------------------- | ------------------------- | ------------------------------------------------------------------------------------------- | -| `mega-evm` | `crates/mega-evm` | Core EVM implementation | -| `mega-system-contracts` | `crates/system-contracts` | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-state-test` | `crates/mega-state-test` | State-test fixtures + runner library (EEST-compatible, published; imported as `state_test`) | -| `state-test` | `crates/state-test` | Thin CLI front-end over `mega-state-test` (not published) | -| `mega-evme` | `bin/mega-evme` | CLI tool for EVM execution (`run`, `tx`, `replay`) | -| `mega-t8n` | `bin/mega-t8n` | Standalone state transition (t8n) tool | - -## Architecture - -### Spec System (`MegaSpecId`) - -Progression: `EQUIVALENCE` → `MINI_REX` → `MINI_REX_1` → `MINI_REX_2` → `REX` → `REX1` → `REX2` → `REX3` → `REX4` → `REX5` → `REX6` → `REX7` (`MINI_REX_1`/`MINI_REX_2` are alias rungs executing `EQUIVALENCE` and `MINI_REX` behavior respectively) - -- **Spec** defines EVM behavior (what the EVM does). - Defined in `crates/mega-evm/src/evm/spec.rs`. - The code base **MUST** maintain **backward-compatibility**, which means the semantics (i.e., EVM behaviors) must remain the same for existing specs. - The only exception for this is the **unstable** spec that is under active development (if exists, must be the latest one). - - _`REX7` is the current unstable spec under active development._ - When a new spec is introduced, this line should be updated to indicate the unstable spec. - - Frozen and activated are separate properties. - `REX6` is frozen and activated on both networks (see `block/chain.rs`); `REX7` has no activation timestamp yet. - Freezing forbids further semantic change; scheduling is a later, separate decision made in the node chainspecs and mirrored here in `block/chain.rs` for replay tooling. - - Specifications of each behavior-introducing spec can be found in the upgrade pages under `docs/spec/upgrades/`; alias rungs have no page of their own and are recorded in the upgrade overview and `docs/spec/hardfork-spec.md`. -- **Hardfork** (`MegaHardfork`) defines network upgrade events (when specs activate). - Every hardfork schedules a spec rung of its own — the fork→spec mapping is 1:1. - `MiniRex1` and `MiniRex2` schedule the alias specs `MINI_REX_1` and `MINI_REX_2`, whose `behavior()` projects to `EQUIVALENCE` and `MINI_REX` respectively. - Defined in `crates/mega-evm/src/block/hardfork.rs`. -- All specs use `OpSpecId::ISTHMUS` as the Optimism base layer. - But this is subject to change in the future. - -### Core Source Layout (`crates/mega-evm/src/`) - -- **`evm/`** — Core mega-evm logic: spec definitions, context, factory, execution pipeline, modified opcodes (LOG, SELFDESTRUCT), host hooks, precompiles. - This module collects all our modifications and customizations of EVM's behavior for mega-evm based on the revm. -- **`block/`** — Block execution: executor, factory, hardfork-to-spec mapping, limit enforcement, and the canonical per-chain hardfork schedules. - This module defines how a block in MegaETH block should be executed. - `block/chain.rs` is the single source of truth for the mainnet/testnet chain IDs and activation-timestamp schedules (`hardfork_schedule(chain_id)`, `MAINNET_CHAIN_ID`, `TESTNET_CHAIN_ID`, `mainnet_hardforks()`, `testnet_hardforks()`); look there to find or change when a fork activates on a given chain. - Its unknown-chain fallback pins a named spec rather than following the latest one, so introducing a spec does not move chains that run from genesis; advancing that pin is a deliberate edit made when a spec is sealed. - Forks map 1:1 onto an ascending spec ladder, so the resolved `spec_id` is monotone; rollbacks are alias specs (`MINI_REX_1`, `MINI_REX_2`) whose `behavior()` projects to an earlier spec. - One value, two projections that must not be confused: `is_enabled` compares behavior and gates EVM semantics (rolls back in alias windows); `reaches` compares ladder position and gates one-way chain setup such as predeploys and pre-block rules (never rolls back). - The `is__active_at_timestamp` predicates are position projections for behavior-introducing forks and raw event queries for alias forks, and `MegaHardforks::validate_schedule` is the load-time check that a published schedule climbs the ladder without gaps. -- **`limit/`** — Resource limit tracking: compute gas, data size, KV updates, state growth (each in its own module). - MegaETH introduces additional resource metering mechanism and this module implements their logic as utility structs to be used by mega-evm. -- **`access/`** — Block env access tracking and volatile data detection for parallel execution. - MegaETH incorporates parallel EVM, so it is essential to reduce the conflicts between transactions by restricting the access to some "hot" resources. - This module collects the logic of tracking the access to such hot resources during transaction execution. -- **`external/`** — External environmental context depended by mega-evm. - The execution of mega-evm relies on some external environment information, in addition to revm's normal BlockEnv and CfgEnv. -- **`system/`** — System contract integration. - MegaETH provides several system contracts that are predeployed on the chain. - Any modification of such system contract must induce a new Spec to ensure backward compatibility. -- **`sandbox/`** — Isolated EVM execution -- **`constants.rs`** — All numeric constants organized by spec -- **`types.rs`** — Shared type definitions - -### Key Concepts - -#### Backward Compatibility of Specs - -The spec system (`MegaSpecId`) forms a linear progression where each newer behavior-introducing spec includes all previous behaviors; the alias rungs are the exception, re-executing an earlier spec's behavior instead. -The codebase **MUST** maintain backward-compatibility: EVM semantics must never change for existing (stable) specs. -The only exception is the latest spec if explicitly marked as **unstable**. -Consequently: - -- Adding/modifying a system contract requires introducing a new spec. -- Changing gas costs, opcode behavior, or resource limits requires a new spec. -- Code should use `spec.is_enabled(MegaSpecId::X)` to gate spec-specific behavior. -- Modified opcodes (e.g., SELFDESTRUCT behavior varies by spec) are wired per-spec in the instruction table (`evm/instructions.rs`). - -#### Dual Gas Model (Compute Gas vs Storage Gas) - -MegaETH separates EVM gas into two independent dimensions tracked during execution: - -- **Compute gas**: Measures pure computational cost. - Every opcode's gas consumption is recorded via wrapped instructions in `evm/instructions.rs` — `compute_gas_ext::*` for plain opcodes and `storage_gas_ext::*` for storage-affecting opcodes (SSTORE, LOG, CALL-family, CREATE/CREATE2, SELFDESTRUCT) — both invoking the shared `record_storage_compute_gas!` primitive after the opcode body completes. - Subject to a per-spec compute gas limit and further restricted by gas detention (see below). -- **Storage gas**: Charges for persistent state modifications (SSTORE, account creation, contract deployment). - These costs scale dynamically with SALT bucket capacity (see External Environment Dependencies below). - LOG opcodes are charged in both dimensions: standard compute gas rates plus a storage gas multiplier on topic and data costs. - -Both dimensions are enforced independently. -A transaction can be halted by exceeding either limit. - -#### Multidimensional Resource Limits - -Beyond the dual gas model, mega-evm enforces **four independent per-transaction resource limits** via `AdditionalLimit` (`limit/limit.rs`): - -- **Compute gas** — Computational opcode cost -- **Data size** — Calldata + logs + storage writes + code deploy + account updates -- **KV updates** — Storage writes + account modifications (net, with refunds) -- **State growth** — Net new accounts + net new storage slots (not all specs enable this) - -Each dimension has its own per-spec limit defined in `constants.rs`. -All trackers are **frame-aware**: reverted inner calls discard their tracked usage, successful calls merge into the parent frame. -When any limit is exceeded, execution halts with `OutOfGas` and remaining gas is preserved for refund. - -#### Gas Detention (Volatile Data Access Restriction) - -MegaETH's parallel EVM needs to minimize conflicts between concurrent transactions. -"Volatile" data — block environment fields (NUMBER, TIMESTAMP, COINBASE, etc.), the beneficiary's account state, and the oracle contract — is frequently read by many transactions and thus a major source of conflicts. - -**Gas detention** restricts computation after volatile data is accessed by capping the remaining compute gas: - -- Different volatile data categories (block env/beneficiary, oracle) have different cap levels defined in `constants.rs`. -- The **most restrictive cap wins** when multiple volatile sources are accessed. -- Caps are applied via host hooks (`evm/host.rs`) that mark access in a `VolatileDataAccessTracker` (`access/tracker.rs`), then enforced after each volatile opcode via `wrap_op_detain_gas!` in `evm/instructions.rs`. +| Crate | Path | Member | Purpose | +| ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | +| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | +| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | +| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins with T10.1 | +| `state-test` | `crates/state-test` | no | State-test CLI; rejoins with T10.1 | +| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins with T10.2 | +| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins with T10.3 | -This forces transactions that touch volatile data to terminate quickly, reducing parallel execution conflicts without banning the access outright. -Detained gas is effectively refunded — users only pay for actual computation performed. +The four tool crates still target the legacy engine. +They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until their ticket ports them. -#### Storage Gas Stipend (Rex4+) +### Dependencies on the forks -MegaETH's 10× storage gas multiplier on LOG opcodes causes even `LOG1` to cost 4,500 gas, exceeding the EVM's `CALL_STIPEND` of 2,300. -Rex4 introduced `STORAGE_CALL_STIPEND` (23,000 gas) for internal (`depth > 0`) value-transferring `CALL`/`CALLCODE`; Rex5 reworked it into a separated allowance, so the tracker is dual-mode. -Under Rex5 the stipend is a per-frame allowance that does NOT inflate the child's `gas_limit`: it is drawn only at MegaETH's storage-gas surcharge sites (LOG topic/data, new-account materialization, first-time-write SSTORE, contract-creation storage, SELFDESTRUCT beneficiary creation), is structurally unspendable on compute, and is neither returned to the caller nor rescued for the sender — nothing is burned because nothing ever enters the frame's gas limit. -Under Rex4 (legacy mode) the stipend instead inflates the child's `gas_limit`, a per-frame compute gas cap keeps the extra gas usable only for storage-gas-heavy operations, and unused stipend is burned on return. +The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crates to the MegaETH fork with `[patch.crates-io]`. +`op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates (`alloy-op-evm`, `op-alloy-*`) come from the same monorepo revision. -The stipend lifecycle is managed by `StorageCallStipendTracker` (`limit/storage_call_stipend.rs`), which maintains a per-frame stack aligned with the EVM call stack. -The tracker's `before_frame_init` method is called inside `AdditionalLimit::before_frame_init`, after all four sub-trackers push their frames (so the compute gas frame exists for the Rex4 legacy-mode per-frame cap). +- Patch the twelve revm crates together, or the build resolves a second copy of revm. +- `cargo tree -i revm` must show exactly one revm, from the fork. +- The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. -The storage gas stipend is subject to the general gas leakage pitfalls described below. - -#### System Contracts - -MegaETH pre-deploys system contracts at well-known addresses (`0x634200...0001`, `0002`, `0003`, etc.). -They are deployed idempotently during `pre_execution_changes()` in `block/executor.rs`, gated by hardfork activation: - -| Contract | Address suffix | Purpose | -| ------------------------ | -------------- | --------------------------------------------------- | -| Oracle | `...0001` | External key-value storage with hint support | -| High-Precision Timestamp | `...0002` | Sub-second block timestamp | -| Keyless Deploy | `...0003` | Deterministic contract deployment via Nick's Method | -| MegaAccessControl | `...0004` | Access control (disableVolatileDataAccess) | -| MegaLimitControl | `...0005` | Limit query/control (currently remainingComputeGas) | -| SequencerRegistry | `...0006` | System address and sequencer role registry | - -Key design aspects: - -- Solidity sources in `crates/system-contracts/contracts/`, compiled by Foundry, with Rust ABI bindings generated via `alloy-sol-types`. -- Bytecode is versioned and hash-verified at build time (`crates/system-contracts/build.rs`). -- The **MEGA_SYSTEM_ADDRESS** can call whitelisted system contracts as deposit-like transactions — no signature or fee required. - This is how the sequencer updates oracle storage. -- **Any system contract modification requires a new spec** to preserve backward compatibility. - -#### External Environment Dependencies - -mega-evm requires external context beyond revm's standard `BlockEnv`/`CfgEnv`, provided via the `ExternalEnvFactory` trait (`external/factory.rs`): - -- **SALT environment** (`external/salt.rs`): Provides bucket capacity data for dynamic gas pricing. - Each account and storage slot maps to a SALT bucket; gas cost = base cost × (bucket_capacity / MIN_BUCKET_SIZE). - This makes storage operations more expensive in crowded state regions, preventing state bloat. - Implementation: `DynamicGasCost` struct (`external/gas.rs`) lazily caches bucket multipliers. -- **Oracle environment** (`external/oracle.rs`): Supplies storage values for the oracle contract via `get_oracle_storage(slot)`. - Oracle reads in `sload` are **always forced cold** for deterministic replay. - The `on_hint(from, topic, data)` callback enables synchronous oracle hints during execution. -- An `EmptyExternalEnv` implementation disables both features (returns minimum bucket size, no oracle data) for testing or standalone use. - -### Gas Leakage Pitfalls - -Any mechanism that grants, inflates, or adjusts gas on a per-frame basis (e.g., `STORAGE_CALL_STIPEND`, and any future per-frame gas adjustment) must account for all frame termination paths. -Failing to do so can cause system-granted gas to leak back to the parent call frame or the transaction sender. -The following paths are common sources of leakage: - -1. **System contract interception** (`system/intercept.rs`): Interceptors short-circuit `frame_init` before `AdditionalLimit::before_frame_init` runs, producing a synthetic `FrameResult` without a real child EVM frame. - Any per-frame gas adjustment applied in `before_frame_init` is skipped on this path. - The `push_empty_frame()` call maintains stack alignment but does not apply adjustments. - Synthetic results must not assume any per-frame gas mechanism was applied. -2. **Gas rescue on TX-level limit exceed** (`limit/limit.rs`): When a transaction-level resource limit is exceeded, `rescue_gas` captures remaining gas for sender refund. - If a frame's gas was inflated by a per-frame mechanism, the rescued amount must exclude the inflated portion — otherwise the sender recovers system-granted gas that should have been burned. -3. **Frame return** (`limit/limit.rs`): `before_frame_return_result` is the final hook before gas is returned to the parent. - Any per-frame gas adjustment must be unwound here (e.g., burning unused granted gas). - The unwinding must apply identically on success and revert — conditional unwinding can leak gas on one path. - -When adding a new per-frame gas mechanism, verify that all three paths handle it correctly and add tests for each. - -### Resource-Limit Check Protocol +## Architecture -The per-opcode hot path records and checks only the compute-gas dimension (`AdditionalLimit::record_compute_gas`). -Correctness of the other three dimensions (data size, KV updates, state growth) rests on a protocol instead of a per-opcode fan-out across all four trackers: +### Spec System (`MegaSpecId`) -1. **Every non-compute mutation site must latch.** - Any code that records data-size/KV/state-growth usage during execution (`on_sstore`, `on_log`, `record_oracle_hint_bytes`, the frame-lifecycle hooks) must run `check_limit()` itself, latching any exceed into `has_exceeded_limit`. - The latch is surfaced by the leading short-circuit of the next `record_compute_gas` call, so the halt lands on the same opcode as the pre-protocol fan-out did. -2. **Pre-inner recorders must NOT latch.** - A site that records usage _before_ its inner instruction executes (currently SELFDESTRUCT's two beneficiary recorders: empty-beneficiary creation and the REX6+ existing-beneficiary credit) must record without latching: the inner instruction can still fail, the frame then discards the usage, and an early latch would stick and rewrite the frame's real result. - Such opcodes use a trailing all-dimension check (`record_compute_gas_all_dims`) that runs only after the inner instruction succeeds. -3. **Compute gas is always recorded.** - `record_compute_gas` must record before surfacing any latched exceed — the recorded total feeds the transaction outcome and block-level compute accounting even for transactions halted on another dimension. +`MegaSpecId` has a single rung, `SATIN`, running on `OpSpecId::KARST` (Ethereum `OSAKA`). +`MegaHardfork` has the single fork `Satin`, which activates `SATIN`. -The protocol governs mutation sites that run during execution; the REX6+ post-execution fee-reward accounting is deliberately outside it. -That accounting merges usage into the transaction's reported totals and the block-level cumulative counters after the execution result is final, without latching, and never retroactively fails the transaction. +- `SATIN` is the unstable spec under active development: it has no activation timestamp yet (`block/chain.rs` lists the two chains with the Satin timestamp unset), and its behavior may change until it is sealed. +- Display and `FromStr` use `"Satin"`; serde uses the variant name `"SATIN"`. +- The legacy spec names (`Equivalence` … `Rex7`) parse to `ParseMegaSpecError::Legacy`; they are never mapped to Satin. +- There are no spec gates: a single-spec engine has nothing to gate. + The spec that follows Satin introduces the first `is_enabled`-style gate. -Rule 1 is backed by a `debug_assert!` in `record_compute_gas`: if a non-compute dimension is over its limit but not yet latched, the assert trips at the exact opcode whose mutation site forgot to call `check_limit()`. -The sub-tracker checks are non-mutating, so the guard compiles out of release builds. +### Core Source Layout (`crates/mega-evm/src/`) -When adding an opcode or mutation site that touches a non-compute dimension, decide whether it records after or before its inner instruction, follow the matching case above, and add a test asserting the exceed halts at that opcode. +| Module | Holds now | Filled by | +| -------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over op-revm's `OpEvm`; `MegaEvmFactory` (alloy-evm) | T2.3 (frame lifecycle, result and gas types, inspector entry), T3.1–T3.4 (gas table, SALT pricing, history gas, compute), T5, T8.2 | +| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton | T8.1 (executor, Karst block rules), T5.2 (pre-block calls), T6.2 (deployments) | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | T3.2 (SALT pricing), T6.3 (oracle) | +| `limit/` | nothing | T2.3 (observe-stage-commit layer, abort protocol), T4.1 (data size), T4.2 (detention), T4.3 (state-gas limits, KV count) | +| `access/` | nothing | T4.2 (volatile-data access tracking) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | T6.1 (interceptors), T6.2 (deployment), T6.3 (oracle and control contracts), T7 (keyless as a native CREATE sub-frame) | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by T3–T4; the numbers are signed off by T14 | +| `types.rs` | transaction, halt reason, error and envelope aliases | T2.3 | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact` | T8.2 extends `BytecodeBuilder` | + +### How Satin executes today + +- `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. + It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 state gas on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. + Gas above the 200M execution cap goes to the EIP-8037 reservoir. +- Every `Host` and context method delegates to op-revm's context, and `MegaEvm` delegates execution to `OpEvm`. + `tests/satin/equivalence.rs` pins that Satin currently equals op-revm on the same `CfgEnv`, field by field; a later ticket that changes behavior on purpose updates that baseline. +- The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here. + T2.3 defines Satin's frame, abort and write-record contracts; follow those once they land. ## Test Organization (`crates/mega-evm/tests/`) -Tests are organized by spec: `equivalence/`, `mini_rex/` (12 modules), `rex/`, `rex2/`, `rex3/`, `rex4/`, `rex5/`, `rex6/`, and `block_executor/`. -Each module tests specific features of that spec. +- `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). +- `_pending/` — the legacy tests the T0 inventory keeps, parked until their ticket ports them. + It has no `main.rs`, so Cargo does not build it; its `README.md` names the owner of every file. + When a ticket ports a pending test, it deletes it from `_pending/` in the same commit. +- Unit tests live next to the code in `#[cfg(test)] mod tests`. ## Version Control -The main branch is `main`, but it's protected. -All change should be made via PRs on GitHub. +`satin` is the integration branch of the new engine; pull requests for Satin target `satin`. +`main` carries the legacy engine and is not touched from Satin work. +Both are protected: all changes go through PRs on GitHub. ### Branch naming convention @@ -274,14 +144,14 @@ The commit message should be short and exclude any information of the agent itse When a PR creation is requested, the agent should: -1. Check if the repo is current on a different branch other than `main`. +1. Check if the repo is current on a different branch other than `satin` or `main`. If not, create and checkout to a new branch. Make sure to inform the user about this branch creation. 2. Commit the changes in the worktree before fix linting issues. 3. Run lint check, and fix any lint warnings, and then commit if there are any changes. 4. Format the code and commit if there are any changes. 5. Push to the remote. -6. Use `gh` CLI tool to create a PR. +6. Use `gh` CLI tool to create a PR against `satin`. When generating the PR title and description, consider the overall changes in this branch across commits. In the PR description, make sure a `Summary` section is put on the top. The PR will be merged with `Squash and Merge` operation, whose commit description should include the summary. @@ -295,9 +165,17 @@ When the agent is requested to implement a new feature or bug fix, it should con ## Caveats for Agents +- **Satin is the only active spec; the legacy engine is frozen.** + Do not add legacy specs, alias rungs or spec gates to this crate, and do not port a legacy mechanism the T0 inventory retired. + Behavior of the legacy specs is changed only on the legacy line, never here. +- **Build from the skeleton, one ticket at a time.** + Each module is filled by the ticket named in the module table; do not implement another ticket's mechanism to make yours work. + If a ticket needs an interface that belongs to another ticket, stub the smallest interface and name the owning ticket. - **Always test logic changes.** Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. +- **Keep the op-revm baseline honest.** + A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. This includes new or modified opcode behavior, gas mechanics, system contract interception, resource limit tracking, and block executor pipeline changes. @@ -309,30 +187,14 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Use `test_` prefix for Rust test function names.** New `#[test]` functions should be named with a `test_` prefix for consistency with this repository and upstream revm style. If editing nearby tests in the same module, align names to the same `test_` style when reasonable. -- **Do NOT modify behavior for existing stable specs.** - All specs through `REX6` are frozen; `REX7` is the unstable spec under active development. - A spec being frozen is independent of whether any network has scheduled it — a frozen spec is off-limits to behavior changes whether or not a timestamp has been published. - New EVM behavior, gas cost changes, or opcode modifications for stable specs **must** introduce a new spec and be gated with `spec.is_enabled(MegaSpecId::NEW_SPEC)`. - Never change what an existing stable spec does. -- **System contract changes require a new spec.** - Do not modify system contract Solidity sources or their Rust integration without also introducing a new spec for backward compatibility. -- **Override `HardforkParams::validate()` for every new params type.** - The default implementation accepts any value silently. - Override it with field-level invariant checks (e.g., non-zero addresses) so that `with_params()` panics loudly at chain-config load time rather than allowing the error to surface at the first block where the fork activates. - Also register the fork-requires-params rule in `MegaHardforks::validate_schedule` so a schedule that activates the fork without its params fails validation, not the fork's first block. -- **Pre-block helpers must return state, not commit directly.** - Any helper participating in `pre_execution_changes` (system contract deploys, pre-block system calls, etc.) MUST return `Option` and never call `db.commit(...)` directly. - Full convention: `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`. -- **Define value-transfer policy explicitly for system contract interceptors.** - For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor. - If a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. -- **Do not intercept unknown selectors for system contracts.** - Unknown selectors should fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. -- **Only `CALL` and `STATICCALL` reach interceptor dispatch.** - `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard in `frame_init` before any interceptor is consulted. - Do not expect these schemes to trigger system contract interception. -- **System contract interceptor tests must cover boundary behaviors.** - Include tests for normal intercepted path, non-zero value behavior, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE interception boundaries. +- **System contracts stay unchanged.** + Do not modify the Solidity sources or the generated bindings in `crates/system-contracts`; Satin reuses them. +- **Rules for system contract interceptors (T6 onwards).** + For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor; if a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. + Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. + Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. +- **Pre-block helpers must return state, not commit directly (T5.2, T6.2).** + Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. @@ -353,9 +215,9 @@ When the agent is requested to implement a new feature or bug fix, it should con Run `cargo fmt --all --check` before completion. - **Keep documentation up to date.** When making changes, always check whether related documentation needs updating. - The primary documentation is in `docs/`. + The primary documentation is in `docs/`; it still describes the legacy engine until T15 writes the Satin pages. The spec documentation is under `docs/spec/`, and the mega-evme documentation is under `docs/mega-evme/`. - Also update this `AGENTS.md` when relevant (e.g., unstable spec marker, spec progression list, system contract table). + Also update this `AGENTS.md` when relevant (e.g., the module table, the unstable-spec marker). - **One sentence, one line.** When writing markdown or similar format files, put each sentence in a separate line. - **Run Prettier on docs before committing.** diff --git a/REVIEW.md b/REVIEW.md index 259701ddf..ee2c0922b 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -55,6 +55,7 @@ This is the single most important correctness concern in mega-evm. - If a change affects cross-component behavior that cannot be covered by unit tests, suggest e2e tests in the review comment (these may live in the `test-client` repo). - For stateful systems (resource-limit trackers, gas-stipend lifecycle), assert state-machine invariants after each transition, not just at the end. - Tests under `crates/mega-evm/tests/mutation/` are generated mutation-killing system tests, each keyed to a specific surviving mutant. + On the `satin` branch the legacy ones are parked under `crates/mega-evm/tests/_pending/mutation/` until they are regenerated against the Satin sources. Their comments — especially the `file:line:col` mutation-location references — must be kept up to date when the referenced source moves. Flag any PR that shifts lines in a mutated source file but leaves a now-stale location reference (or an orphaned/renamed test) in `tests/mutation/`; a reference that no longer points at its mutant defeats the purpose of the linkage. These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index aaefbe1e4..bec5f3fe1 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -1,123 +1,50 @@ # mega-evm -A specialized Ethereum Virtual Machine (EVM) implementation tailored for MegaETH, built on top of [revm](https://github.com/bluealloy/revm) and [op-revm](https://github.com/bluealloy/op-revm). +The EVM of MegaETH, built on [revm](https://github.com/bluealloy/revm) and [op-revm](https://github.com/ethereum-optimism/optimism/tree/develop/rust/op-revm). -## EVM Version +This is the 2.x line: the **Satin** engine. +The legacy engine (specs `Equivalence` through `Rex7`) is the 1.x line. -- **Base EVM**: [revm v27.1.0 (v83)](https://github.com/bluealloy/revm) -- **Optimism EVM**: [op-revm v8.1.0 (v83)](https://github.com/bluealloy/op-revm) -- **Alloy EVM**: [alloy-evm v0.15.0](https://github.com/alloy-rs/alloy-evm) +## Base -## Terminology: Spec vs Hardfork +- **revm**: 40.0.3, from the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) (the revm 43 gas core with EIP-8037 and EIP-2780, plus MegaETH hooks) +- **op-revm**: 20.0.0, from the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) +- **alloy-evm**: 0.36; **alloy-op-evm**: 0.32 -This codebase distinguishes between two related concepts: +A consumer redirects all twelve revm crates and `op-revm` to the forks with `[patch]` entries; see this repository's root `Cargo.toml`. -- **Spec (`MegaSpecId`)**: Defines EVM behavior - what the EVM does. Values: `EQUIVALENCE`, `MINI_REX`, `MINI_REX_1`, `MINI_REX_2`, `REX`, `REX1`, `REX2`, `REX3`, `REX4`, `REX5`, `REX6`, `REX7` -- **Hardfork (`MegaHardfork`)**: Defines network upgrade events - when specs are activated. Values: `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` +## Spec and hardfork -The mapping between hardforks and specs is one-to-one: every hardfork schedules a spec rung of its own. -Rollbacks are expressed by alias specs whose behavior projects to an earlier spec: `MiniRex1` schedules `MINI_REX_1` (behavior: `EQUIVALENCE`) and `MiniRex2` schedules `MINI_REX_2` (behavior: `MINI_REX`). +- **Spec (`MegaSpecId`)** defines EVM behavior. Satin has a single spec, `SATIN`, running on Optimism Karst (Ethereum Osaka). +- **Hardfork (`MegaHardfork`)** defines when a spec activates. The single fork `Satin` activates `SATIN`; its timestamps are not scheduled yet. -## Key Features +The legacy spec names do not parse: `"Rex6".parse::()` fails with `ParseMegaSpecError::Legacy`. -### EQUIVALENCE Spec +## Status -- **Optimism Compatibility**: Maintains full compatibility with Optimism Isthmus EVM -- **Parallel Execution Support**: Block environment access tracking for conflict detection +Satin is under construction. +Today it runs transactions through op-revm with EIP-8037 state gas, the EIP-2780 intrinsic cost and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +SALT pricing, history gas, resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. -### MINI_REX Spec +## Quick start -- **Multidimensional Gas Model**: Independent tracking for compute gas (1B), data size (3.125 MB), and KV updates (125K) -- **Compute Gas Tracking**: Separate limit for computational work with gas detention for volatile data access -- **Dynamic Gas Costs**: SALT bucket-based scaling preventing state bloat -- **Split LOG Costs**: Compute gas (standard) + storage gas (10x multiplier) for independent resource pricing -- **SELFDESTRUCT Prohibition**: Complete disabling for contract integrity -- **Large Contract Support**: 512 KB contracts (21x increase from 24 KB) -- **Gas Detention**: Volatile data access (block env, beneficiary, oracle) triggers gas limiting with refunds -- **Enhanced Security**: Comprehensive limit enforcement preserving remaining gas on limit violations +```rust,ignore +use alloy_evm::Evm as _; +use mega_evm::{alloy_op_evm::OpTx, MegaContext, MegaEvm, MegaSpecId}; +use revm::{context::TxEnv, database::{CacheDB, EmptyDB}, primitives::TxKind}; -For complete MiniRex specification, see the [MiniRex upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/minirex.html). +let context = MegaContext::new(CacheDB::::default(), MegaSpecId::SATIN); +let mut evm = MegaEvm::new(context); -### REX Spec - -- **Refined Storage Gas Economics**: Optimized storage gas formulas with gradual scaling (20K-32K base costs vs. MiniRex's 2M) -- **Transaction Intrinsic Storage Gas**: 39,000 storage gas baseline for all transactions (total 60K with compute gas) -- **Zero Cost Fresh Storage**: Storage operations in minimum-sized SALT buckets charge 0 storage gas -- **Separate Contract Creation Cost**: Distinct storage gas for contract creation (32K base) vs. account creation (25K base) -- **Critical Security Fixes**: DELEGATECALL, STATICCALL, and CALLCODE now properly enforce 98/100 gas forwarding and oracle access detection -- **MiniRex Foundation**: Inherits all MiniRex features including multidimensional gas model, compute gas detention, and enhanced security - -For complete Rex specification, see the [Rex upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex.html). - -### REX1 Spec - -- **Limit Reset Fix**: Resets compute gas limits at the start of each transaction -- **No Other Behavioral Changes**: Inherits Rex semantics fully - -For complete Rex1 specification, see the [Rex1 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex1.html). - -### REX2 Spec - -- **SELFDESTRUCT Restored**: Re-enabled with EIP-6780 semantics -- **KeylessDeploy System Contract**: Enables keyless deployment (Nick's Method) with custom gas limits -- **Rex1 Baseline**: Inherits Rex1 behavior for all other features - -For complete Rex2 specification, see the [Rex2 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex2.html). - -### REX3 Spec - -- **Increased Oracle Access Gas Limit**: Oracle access compute gas limit raised from 1M to 20M, allowing more post-oracle computation -- **SLOAD-based Oracle Detention**: Oracle gas detention triggers on SLOAD from oracle storage instead of CALL to oracle contract -- **Keyless Deploy Compute Gas Tracking**: Records the 100K keyless deploy overhead as compute gas -- **Rex2 Baseline**: Inherits all Rex2 behavior - -For complete Rex3 specification, see the [Rex3 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex3.html). - -### REX4 Spec - -- **Per-Call-Frame Resource Budgets**: All four resource dimensions (compute gas, data size, KV updates, state growth) are bounded per call frame with 98/100 forwarding -- **Relative Gas Detention**: Effective detained limit is `current_usage + cap` instead of an absolute cap -- **Storage Gas Stipend**: Value-transferring CALL/CALLCODE receives an additional 23,000 gas for storage gas operations -- **MegaAccessControl System Contract**: Allows contracts to proactively disable volatile data access for a call subtree -- **MegaLimitControl System Contract**: Allows querying effective remaining compute gas under detention and call frame limits -- **Rex3 Baseline**: Inherits all Rex3 behavior - -For complete Rex4 specification, see the [Rex4 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex4.html). - -## Quick Start - -```rust -use mega_evm::{Context, Evm, SpecId, Transaction}; -use revm::{ - context::TxEnv, - database::{CacheDB, EmptyDB}, - inspector::NoOpInspector, - primitives::TxKind, -}; - -// Create EVM instance with MINI_REX spec -let mut db = CacheDB::::default(); -let spec = SpecId::MINI_REX; -let mut context = Context::new(db, spec); -let mut evm = Evm::new(context, NoOpInspector); - -// Execute transaction -let tx = Transaction { - base: TxEnv { - caller: address!("..."), - kind: TxKind::Call(target_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - ..Default::default() - }, +let tx = OpTx(op_revm::OpTransaction { + base: TxEnv { caller, kind: TxKind::Call(target), gas_limit: 1_000_000, ..Default::default() }, + enveloped_tx: Some(Default::default()), ..Default::default() -}; - -let result = alloy_evm::Evm::transact_raw(&mut evm, tx)?; +}); +let result = evm.transact_raw(tx)?; ``` ## Documentation -- [Full specification](https://megaeth-labs.github.io/mega-evm/) +- [Specification](https://megaeth-labs.github.io/mega-evm/) (describes the legacy engine until the Satin pages land) - [Architecture](../../ARCH.md) From fc8515718f0ad22cc0e0e79409ce82d6c115e1bb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:19:18 +0800 Subject: [PATCH 016/201] ci: keep the satin workflows runnable without the tool crates replay-bench builds state-test, which is no longer a workspace member: its bench job is disabled with if: false until state-test is ported to Satin (compare needs it and is skipped with it). The benchmark matrix shrinks to transact, the only bench target until the test gates rebuild the suite. The suppression-hygiene step grepped the spec-gate plan in a pipeline; on a single-spec engine the pack finds no gates, grep exits 1 and pipefail failed the step. The plan now runs on its own, so a planner failure still fails, and only the grep tolerates an empty result. --- .github/workflows/benchmark.yml | 5 ++++- .github/workflows/mutation.yml | 8 ++++++-- .github/workflows/replay-bench.yml | 5 +++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 485b160b7..09ec8906f 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -199,7 +199,10 @@ jobs: strategy: fail-fast: false matrix: - target: [revm_bench, mega_bench, block_bench, transact, comp_cost, ctt, attack_replay] + # On the satin branch `transact` is the only bench target until T2.2 + # rebuilds the suite; T2.2 restores the full list. Scheduled and + # comment-triggered runs use the default branch's copy of this file. + target: [transact] steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 0452f28e7..4629c98b3 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -317,8 +317,12 @@ jobs: # --colors never: CI forces CARGO_TERM_COLOR=always, which would otherwise # embed ANSI codes and break exact suppression matching. cargo mutants --list --package mega-evm --colors never > universe.txt - python3 scripts/umutate.py plan --packs spec-gate \ - | grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' >> universe.txt + # The plan runs on its own so a planner failure still fails the step. + # Its mutant lines are grepped separately: a single-spec engine (the + # satin branch) has no spec gates, the pack finds nothing, and grep's + # "no match" exit must not fail the step under pipefail. + python3 scripts/umutate.py plan --packs spec-gate > spec-gate-plan.txt + grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' spec-gate-plan.txt >> universe.txt || true echo "universe: $(wc -l < universe.txt) mutants" - name: Check for orphan suppressions run: | diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml index b371d8737..69dfc25ea 100644 --- a/.github/workflows/replay-bench.yml +++ b/.github/workflows/replay-bench.yml @@ -104,6 +104,11 @@ jobs: bench: name: Replay throughput needs: prepare + # Disabled on the satin branch: this job builds `state-test`, which is not a + # workspace member until T10.1 ports it to the Satin engine. T10.1 removes + # this line. (`compare` needs this job, so it is skipped with it.) Scheduled + # and comment-triggered runs use the default branch's copy of this file. + if: false runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 90 permissions: From eae79d33a64ef0d4055f404cdccda7065bfc0880 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:34:30 +0800 Subject: [PATCH 017/201] fix: keep ParentBudgetExceeded in the keyless error ABI The data-only keyless module dropped the variant because its kind field was the legacy LimitKind. It comes back with the raw kind code of the IKeylessDeploy error, so every error the interface declares still encodes and decodes; the Satin meaning of the code is left to the limit mechanisms that define the resource dimensions. --- crates/mega-evm/src/system/keyless/error.rs | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/mega-evm/src/system/keyless/error.rs b/crates/mega-evm/src/system/keyless/error.rs index 029bee46c..de7925f21 100644 --- a/crates/mega-evm/src/system/keyless/error.rs +++ b/crates/mega-evm/src/system/keyless/error.rs @@ -52,6 +52,17 @@ pub enum KeylessDeployError { /// The reason reason: MegaHaltReason, }, + /// The call's remaining budget in some resource dimension was below the deployment's + /// known upfront usage, so the deployment was not started. + ParentBudgetExceeded { + /// The resource dimension, as the raw `kind` code of the `IKeylessDeploy` error. The + /// Satin resource dimensions and their codes are not defined yet. + kind: u8, + /// The remaining budget in that dimension. + limit: u64, + /// The deployment's known upfront usage in that dimension. + used: u64, + }, /// Contract creation succeeded but returned empty bytecode EmptyCodeDeployed { /// The gas used @@ -144,6 +155,9 @@ pub fn encode_error_result(error: KeylessDeployError) -> Bytes { KeylessDeployError::ExecutionHalted { gas_used, .. } => { IKeylessDeploy::ExecutionHalted { gasUsed: gas_used }.abi_encode().into() } + KeylessDeployError::ParentBudgetExceeded { kind, limit, used } => { + IKeylessDeploy::ParentBudgetExceeded { kind, limit, used }.abi_encode().into() + } KeylessDeployError::EmptyCodeDeployed { gas_used } => { IKeylessDeploy::EmptyCodeDeployed { gasUsed: gas_used }.abi_encode().into() } @@ -225,6 +239,13 @@ pub fn decode_error_result(output: &[u8]) -> Option { )), }); } + if let Ok(e) = IKeylessDeploy::ParentBudgetExceeded::abi_decode(output) { + return Some(KeylessDeployError::ParentBudgetExceeded { + kind: e.kind, + limit: e.limit, + used: e.used, + }); + } if let Ok(e) = IKeylessDeploy::EmptyCodeDeployed::abi_decode(output) { return Some(KeylessDeployError::EmptyCodeDeployed { gas_used: e.gasUsed }); } @@ -296,6 +317,16 @@ mod tests { assert_eq!(decoded, original); } + /// `ParentBudgetExceeded` keeps every field of the ABI error through a round-trip. + #[test] + fn test_parent_budget_exceeded_roundtrip_preserves_fields() { + let original = + KeylessDeployError::ParentBudgetExceeded { kind: 3, limit: 1_000, used: 1_001 }; + let encoded = encode_error_result(original.clone()); + assert_eq!(encoded[..4], IKeylessDeploy::ParentBudgetExceeded::SELECTOR); + assert_eq!(decode_error_result(&encoded), Some(original)); + } + /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. #[test] fn test_signer_has_code_roundtrip_is_selector_only() { From d4374bb3576f36901d222e7fe18edc17254e568a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:36:30 +0800 Subject: [PATCH 018/201] test: share the zero-fee transaction setup and tighten the Satin tests test_utils gains zero_fee_l1_block_info() and op_transaction(), which the unit tests, the equivalence tests, the bench and transact() now share instead of four copies. The equivalence tests also check the gas table, EIP-7708 and the reservoir margin, and pin that the SSTORE draws no state gas on the Osaka table. The external-env getter test now observes the factory it was given, and the with_cfg test is named for what it checks. --- crates/mega-evm/benches/transact.rs | 35 ++++++++------------ crates/mega-evm/src/evm/context.rs | 2 +- crates/mega-evm/src/evm/factory.rs | 9 +++--- crates/mega-evm/src/evm/mod.rs | 25 +++++---------- crates/mega-evm/src/test_utils/evm.rs | 31 +++++++++++------- crates/mega-evm/tests/satin/equivalence.rs | 37 ++++++++++------------ 6 files changed, 64 insertions(+), 75 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 1e584bbd1..993887111 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -6,9 +6,12 @@ #![allow(missing_docs)] use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, TxKind, U256}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; -use mega_evm::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId}; +use mega_evm::{ + test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}, + MegaContext, MegaEvm, MegaSpecId, +}; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, @@ -28,30 +31,18 @@ type OpContext = Context< L1BlockInfo, >; -fn l1_block_info() -> L1BlockInfo { - L1BlockInfo { - operator_fee_scalar: Some(U256::ZERO), - operator_fee_constant: Some(U256::ZERO), - ..Default::default() - } -} - fn tx(value: U256) -> OpTransaction { - OpTransaction { - base: TxEnv { - caller: CALLER, - kind: TxKind::Call(CALLEE), - value, - gas_limit: 1_000_000, - ..Default::default() - }, - enveloped_tx: Some(Bytes::new()), + op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value, + gas_limit: 1_000_000, ..Default::default() - } + }) } fn mega_context(db: MemoryDatabase) -> MegaContext { - MegaContext::new(db, MegaSpecId::SATIN).with_chain(l1_block_info()) + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) } fn bench_transact(c: &mut Criterion) { @@ -75,7 +66,7 @@ fn bench_transact(c: &mut Criterion) { || { let ctx = OpContext::new(db.clone(), OpSpecId::KARST) .with_cfg(cfg.clone()) - .with_chain(l1_block_info()); + .with_chain(zero_fee_l1_block_info()); OpEvm::new(ctx, NoOpInspector) }, |mut evm| evm.transact(tx(value)).unwrap(), diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e5c96a0f1..2b1e88529 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -301,7 +301,7 @@ mod tests { /// A caller's configuration cannot switch off what the spec fixes; every other field is /// taken from it. #[test] - fn test_with_cfg_updates_spec() { + fn test_with_cfg_keeps_the_spec_switches() { let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); cfg.chain_id = 4326; cfg.enable_amsterdam_eip8037 = false; diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 83865e3ee..1874d067c 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -86,7 +86,7 @@ impl alloy_evm::EvmFactory for MegaEvmFactory #[cfg(test)] mod tests { use super::*; - use crate::{test_utils::MemoryDatabase, ExternalEnvs}; + use crate::{test_utils::MemoryDatabase, ExternalEnvs, SaltEnv, TestExternalEnvs}; use alloy_evm::{Evm, EvmFactory}; use alloy_primitives::{BlockNumber, U256}; use core::cell::Cell; @@ -94,11 +94,12 @@ mod tests { #[test] fn test_external_env_factory_getter() { - let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); + let factory = MegaEvmFactory::new() + .with_external_env_factory(TestExternalEnvs::new().with_bucket_capacity(7, 1_024)); - let got: &EmptyExternalEnv = factory.external_env_factory(); + let got: &TestExternalEnvs = factory.external_env_factory(); - assert!(core::ptr::eq(got, factory.external_env_factory())); + assert_eq!(got.get_bucket_capacity(7).unwrap(), 1_024); } /// Whatever configuration the caller passes, the EVM runs with the switches the spec fixes. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 6facf7682..6abc27542 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -244,11 +244,10 @@ where #[cfg(test)] mod tests { use super::*; - use crate::test_utils::MemoryDatabase; + use crate::test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}; use alloy_evm::{Evm, EvmError}; use alloy_op_evm::OpTx; use alloy_primitives::{address, TxKind, U256}; - use op_revm::{L1BlockInfo, OpTransaction}; use revm::{ context::{result::InvalidTransaction, ContextSetters, TxEnv}, database::State, @@ -260,25 +259,17 @@ mod tests { const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); fn context(db: DB) -> MegaContext { - MegaContext::new(db, MegaSpecId::SATIN).with_chain(L1BlockInfo { - operator_fee_scalar: Some(U256::ZERO), - operator_fee_constant: Some(U256::ZERO), - ..Default::default() - }) + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) } fn tx(value: U256) -> MegaTransaction { - OpTx(OpTransaction { - base: TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: TxKind::Call(CALLEE), - value, - ..Default::default() - }, - enveloped_tx: Some(Bytes::new()), + OpTx(op_transaction(TxEnv { + caller: CALLER, + gas_limit: 100_000, + kind: TxKind::Call(CALLEE), + value, ..Default::default() - }) + })) } fn funded_db() -> MemoryDatabase { diff --git a/crates/mega-evm/src/test_utils/evm.rs b/crates/mega-evm/src/test_utils/evm.rs index ccb8298c3..5a54bc43b 100644 --- a/crates/mega-evm/src/test_utils/evm.rs +++ b/crates/mega-evm/src/test_utils/evm.rs @@ -9,12 +9,27 @@ use revm::context::{ use crate::{MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionError}; +/// L1 block info with zero operator fee, so a transaction pays no L1-side fee. +pub fn zero_fee_l1_block_info() -> L1BlockInfo { + L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + } +} + +/// Wraps `tx` as a non-deposit OP transaction with an empty enveloped encoding, so its L1 data +/// fee is zero. +pub fn op_transaction(tx: TxEnv) -> OpTransaction { + OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() } +} + /// Executes one transaction on a fresh [`MegaEvm`] over `db` and returns its result and state /// without committing. /// -/// The L1 fees are zero (operator fee zero, empty enveloped transaction) and so is the gas -/// price, so the caller needs no balance beyond `value`. A `gas_limit` above the execution cap -/// puts the excess into the state-gas reservoir. +/// The L1 fees are zero (see [`zero_fee_l1_block_info`] and [`op_transaction`]) and so is the +/// gas price, so the caller needs no balance beyond `value`. A `gas_limit` above the execution +/// cap puts the excess into the state-gas reservoir. pub fn transact( spec: MegaSpecId, db: DB, @@ -24,11 +39,7 @@ pub fn transact( value: U256, gas_limit: u64, ) -> Result, EVMError> { - let context = MegaContext::new(db, spec).with_chain(L1BlockInfo { - operator_fee_scalar: Some(U256::ZERO), - operator_fee_constant: Some(U256::ZERO), - ..Default::default() - }); + let context = MegaContext::new(db, spec).with_chain(zero_fee_l1_block_info()); let tx = TxEnv { caller, kind: callee.map_or(TxKind::Create, TxKind::Call), @@ -37,7 +48,5 @@ pub fn transact( gas_limit, ..Default::default() }; - let tx = - OpTx(OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() }); - MegaEvm::new(context).transact_raw(tx) + MegaEvm::new(context).transact_raw(OpTx(op_transaction(tx))) } diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index b8d59cbfa..ef0643f47 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -6,10 +6,10 @@ //! limits), these cases stay the baseline that shows where the two diverge on purpose. use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, TxKind, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, - test_utils::{BytecodeBuilder, MemoryDatabase}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; @@ -18,7 +18,9 @@ use revm::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, + context_interface::cfg::GasParams, inspector::NoOpInspector, + primitives::hardfork::SpecId, state::EvmState, ExecuteEvm, Journal, }; @@ -45,34 +47,22 @@ fn block() -> BlockEnv { } } -fn l1_block_info() -> L1BlockInfo { - L1BlockInfo { - operator_fee_scalar: Some(U256::ZERO), - operator_fee_constant: Some(U256::ZERO), - ..Default::default() - } -} - -fn op_tx(tx: TxEnv) -> OpTransaction { - OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() } -} - /// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the /// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes and that `CfgEnv`. fn run_both(db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, CfgEnv) { let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) .with_block(block()) - .with_chain(l1_block_info()); + .with_chain(zero_fee_l1_block_info()); let cfg = ctx.cfg().clone(); let mut mega = MegaEvm::new(ctx); - let mega_outcome = mega.transact(OpTx(op_tx(tx.clone()))).unwrap(); + let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap(); let op_ctx = OpContext::new(db, OpSpecId::KARST) .with_cfg(cfg.clone()) .with_block(block()) - .with_chain(l1_block_info()); + .with_chain(zero_fee_l1_block_info()); let mut op = OpEvm::new(op_ctx, NoOpInspector); - let op_outcome = op.transact(op_tx(tx)).unwrap(); + let op_outcome = op.transact(op_transaction(tx)).unwrap(); (mega_outcome, op_outcome, cfg) } @@ -93,13 +83,17 @@ fn assert_same(mega: &Outcome, op: &Outcome) { assert_eq!(mega.state, op.state, "state"); } -/// Both engines run on the Satin configuration: Karst with EIP-8037 and EIP-2780 switched on -/// and the 200M execution cap. +/// Both engines run on the Satin configuration: Karst on the Osaka gas table, EIP-8037 and +/// EIP-2780 switched on, the 200M execution cap, EIP-7708 and the system-call reservoir margin +/// off. fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); + assert_eq!(cfg.gas_params.table(), GasParams::new_spec(SpecId::OSAKA).table()); assert!(cfg.enable_amsterdam_eip8037); assert!(cfg.enable_amsterdam_eip2780); assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); + assert!(!cfg.enable_amsterdam_eip7708); + assert!(!cfg.system_call_state_gas_margin_in_reservoir); } #[test] @@ -154,5 +148,8 @@ fn test_sstore_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); assert_eq!(mega.state[&CALLEE].storage[&U256::ZERO].present_value, U256::from(42)); + // The Osaka gas table has no state-gas prices, so the new slot draws no state gas even with + // EIP-8037 on. The Satin gas table (T3.1) prices it; this assertion changes with it. + assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); } From bf3e6d38ccb31acaf645c0eb264149536ddc12a1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:37:43 +0800 Subject: [PATCH 019/201] docs: fix review findings in the Satin docs AGENTS.md gets back two rules later mechanisms need (only CALL and STATICCALL reach interceptor dispatch; per-fork params are validated at load time) and says plainly that state gas is priced at zero until the Satin gas table lands; the crate README says the same and keeps one sentence per line. REVIEW.md's two pointers to moved or deleted files name both branches. The constants docs no longer cite an outside document. The pending README lists the 36 tests ported in place, which is why its counts sit below the test inventory's, and the manifest says why the bench inputs stay. --- AGENTS.md | 11 ++++++++--- REVIEW.md | 4 ++-- crates/mega-evm/Cargo.toml | 3 ++- crates/mega-evm/README.md | 9 ++++++--- crates/mega-evm/src/constants.rs | 8 ++++---- crates/mega-evm/tests/_pending/README.md | 18 ++++++++++++++++++ 6 files changed, 40 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8c5f0edbf..da6084f8c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,8 +100,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. -- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 state gas on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. Gas above the 200M execution cap goes to the EIP-8037 reservoir. + The Osaka gas table prices state gas at zero, so no transaction draws state gas until T3.1 installs the Satin gas table. - Every `Host` and context method delegates to op-revm's context, and `MegaEvm` delegates execution to `OpEvm`. `tests/satin/equivalence.rs` pins that Satin currently equals op-revm on the same `CfgEnv`, field by field; a later ticket that changes behavior on purpose updates that baseline. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here. @@ -187,12 +188,16 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Use `test_` prefix for Rust test function names.** New `#[test]` functions should be named with a `test_` prefix for consistency with this repository and upstream revm style. If editing nearby tests in the same module, align names to the same `test_` style when reasonable. -- **System contracts stay unchanged.** - Do not modify the Solidity sources or the generated bindings in `crates/system-contracts`; Satin reuses them. +- **System contracts carry over as they are.** + Satin reuses the Solidity sources and bindings in `crates/system-contracts`; changing a contract needs a decision of its own, not a side effect of an engine ticket. - **Rules for system contract interceptors (T6 onwards).** For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor; if a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. + Only `CALL` and `STATICCALL` reach interceptor dispatch; `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard before any interceptor is consulted. Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. +- **Validate per-fork parameters at load time (T8.1 onwards).** + A hardfork parameters type overrides `HardforkParams::validate()` with field-level invariant checks, so a bad chain config fails when it is loaded rather than at the fork's first block. + The fork-requires-params rule is registered in the schedule validation too, so a schedule that activates the fork without its params is rejected at load time. - **Pre-block helpers must return state, not commit directly (T5.2, T6.2).** Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. - **Respect `no_std` in `mega-evm` crate.** diff --git a/REVIEW.md b/REVIEW.md index ee2c0922b..dc1ebec4f 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,7 +24,7 @@ This is the single most important correctness concern in mega-evm. - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. - Pre-block helpers (system contract deploys, pre-exec system calls, etc.) must return `Option` for the block executor to commit — never call `db.commit(...)` directly. Even idempotent "no change" paths must return `Some(EvmState)` with a read-only account entry; silently returning `None` drops the account from the stateless witness read set and produces an incomplete proof. - See `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`. + On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the pre-block helpers arrive with T5.2 and T6.2. The same applies inside execution: read through the journal (`inspect_account`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state — and an early halt placed before the sandbox state merge drops that read set entirely. - Per-frame gas mechanisms (stipends, adjustments) must handle all frame termination paths: system contract interception, gas rescue on limit exceed, and frame return. Missing any path causes gas leakage. @@ -58,7 +58,7 @@ This is the single most important correctness concern in mega-evm. On the `satin` branch the legacy ones are parked under `crates/mega-evm/tests/_pending/mutation/` until they are regenerated against the Satin sources. Their comments — especially the `file:line:col` mutation-location references — must be kept up to date when the referenced source moves. Flag any PR that shifts lines in a mutated source file but leaves a now-stale location reference (or an orphaned/renamed test) in `tests/mutation/`; a reference that no longer points at its mutant defeats the purpose of the linkage. - These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. + These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs` (on `satin`: `crates/mega-evm/tests/_pending/mutation/main.rs`). - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. Missing the required explicit hardfork pin can silently bench the wrong fork when a shared bench subject defaults to a different one. diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index d2b1cbe59..1ca251453 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -56,7 +56,8 @@ std = [ ] test-utils = ["dep:derive_more"] -# T2.2 rebuilds the benchmark suite on Satin; until then `transact` is the only target. +# T2.2 rebuilds the benchmark suite on Satin; until then `transact` is the only target. The +# inputs under benches/data (revm_bench) and benches/fixtures (attack_replay) stay for it. [[bench]] name = "transact" harness = false diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index bec5f3fe1..d0b6f3dd7 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -15,15 +15,18 @@ A consumer redirects all twelve revm crates and `op-revm` to the forks with `[pa ## Spec and hardfork -- **Spec (`MegaSpecId`)** defines EVM behavior. Satin has a single spec, `SATIN`, running on Optimism Karst (Ethereum Osaka). -- **Hardfork (`MegaHardfork`)** defines when a spec activates. The single fork `Satin` activates `SATIN`; its timestamps are not scheduled yet. +- **Spec (`MegaSpecId`)** defines EVM behavior. + Satin has a single spec, `SATIN`, running on Optimism Karst (Ethereum Osaka). +- **Hardfork (`MegaHardfork`)** defines when a spec activates. + The single fork `Satin` activates `SATIN`; its timestamps are not scheduled yet. The legacy spec names do not parse: `"Rex6".parse::()` fails with `ParseMegaSpecError::Legacy`. ## Status Satin is under construction. -Today it runs transactions through op-revm with EIP-8037 state gas, the EIP-2780 intrinsic cost and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +Today it runs transactions through op-revm with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +It still uses the Osaka gas table, which prices state gas at zero, so no transaction draws state gas yet. SALT pricing, history gas, resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. ## Quick start diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 6e39a0d76..99081e9cc 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -1,8 +1,8 @@ //! Numeric constants of the Satin engine. //! -//! Every value is *provisional*: the numbers follow the default candidate of the Satin work -//! order and stay open until the economics sign-off. A constant that no code reads yet is here -//! so the whole placeholder set can be reviewed in one place. +//! Every value is *provisional*: a placeholder until the economics sign-off fixes the numbers. +//! A constant that no code reads yet is here so the whole placeholder set can be reviewed in +//! one place. //! //! | Constant | Value | Meaning | Read from | //! |---|---:|---|---| @@ -47,7 +47,7 @@ pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; mod tests { use super::*; - /// The placeholder values as the Satin work order states them (candidate 1). + /// The placeholder values, written out so a change to one is a visible diff. #[test] fn test_provisional_values_match_the_work_order() { assert_eq!(COST_PER_STATE_BYTE, 1_530); diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index f3eb3b003..e37761ad8 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -45,6 +45,24 @@ Do not add a `_pending/main.rs`. | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | | **Total** | **836** | **691** | **145** | **485** | **322** | **29** | +## Tests ported in place + +These rows came back with the code they test and run in `crates/mega-evm/src`, so the counts above are lower than T0's per-ticket totals by exactly these rows. + +| Legacy file | Owner in T0 | Tests | Now in | +|---|---|---:|---| +| `src/evm/context.rs` | T2.1 (3) | 3 | `src/evm/context.rs` | +| `src/evm/factory.rs` | T2.1 (1) | 1 | `src/evm/factory.rs` | +| `src/evm/mod.rs` | T2.1 (6) | 6 | `src/evm/mod.rs` | +| `src/evm/spec.rs` | T2.1 (3) | 3 | `src/evm/spec.rs` | +| `src/external/hasher/mod.rs` | T3.2 (5) | 5 | `src/external/hasher/mod.rs` | +| `src/external/mod.rs` | T2.1 (1) | 1 | `src/external/mod.rs` | +| `src/external/test_utils.rs` | T2.1 (1) | 1 | `src/external/test_utils.rs` | +| `src/sandbox/error.rs` | T7 (4) | 4 | `src/system/keyless/error.rs` | +| `src/sandbox/tx.rs` | T7 (10) | 10 | `src/system/keyless/tx.rs` | +| `src/test_utils/opcode_gen.rs` | T2.1 (2) | 2 | `src/test_utils/opcode_gen.rs` | +| **Total** | | **36** | | + ## Tests T0 assigns to T2.1 that are parked under another ticket | File | Test | Parked under | Reason | From 63126b303c9a8d44ac93716e82c1814bd055d7f3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:37:43 +0800 Subject: [PATCH 020/201] ci: fail the hygiene step on a grep error, not only on a planner error The spec-gate grep accepted any exit status; it now accepts only 1 (no match), so a real grep failure (exit 2) still fails the step. --- .github/workflows/mutation.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 4629c98b3..0adb0ae1e 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -319,10 +319,10 @@ jobs: cargo mutants --list --package mega-evm --colors never > universe.txt # The plan runs on its own so a planner failure still fails the step. # Its mutant lines are grepped separately: a single-spec engine (the - # satin branch) has no spec gates, the pack finds nothing, and grep's - # "no match" exit must not fail the step under pipefail. + # satin branch) has no spec gates and the pack finds nothing. grep's + # "no match" (exit 1) is accepted; a grep error (exit 2) still fails. python3 scripts/umutate.py plan --packs spec-gate > spec-gate-plan.txt - grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' spec-gate-plan.txt >> universe.txt || true + grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' spec-gate-plan.txt >> universe.txt || [ $? -eq 1 ] echo "universe: $(wc -l < universe.txt) mutants" - name: Check for orphan suppressions run: | From 98024a16b5b7e139669aef2134b8ef48b4558c00 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:51:11 +0800 Subject: [PATCH 021/201] build: pin the revm and op-revm forks by release tag --- Cargo.lock | 26 +++++++++++++------------- Cargo.toml | 31 +++++++++++++++---------------- 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 60ff93aa3..19e8534c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3098,7 +3098,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=817e36e92bf3cfc0985def0f36e72fc1b737b175#817e36e92bf3cfc0985def0f36e72fc1b737b175" +source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.2#260f65329f1f47b7412a1b2c1fda85453f66521c" dependencies = [ "auto_impl", "revm", @@ -3731,7 +3731,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "revm-bytecode", "revm-context", @@ -3749,7 +3749,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", "phf 0.13.1", @@ -3760,7 +3760,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", "cfg-if", @@ -3776,7 +3776,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3791,7 +3791,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eips", "derive_more", @@ -3805,7 +3805,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", @@ -3818,7 +3818,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "derive-where", @@ -3836,7 +3836,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", @@ -3871,7 +3871,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3883,7 +3883,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3907,7 +3907,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-primitives", "once_cell", @@ -3917,7 +3917,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=43485bf7de73b6ad92e9b5de4318eb96e2de2182#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip7928", "bitflags 2.11.1", diff --git a/Cargo.toml b/Cargo.toml index 516b04f6e..2f34cf7d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -228,22 +228,21 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). -# Pinned by commit until the fork tags it v40.0.3-mega.1; all twelve crates move together, -# otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "43485bf7de73b6ad92e9b5de4318eb96e2de2182" } +# All twelve crates move together, otherwise the build resolves a second copy of revm. +revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built -# against the revm commit above. Pinned by commit until the fork tags it v20.0.0-mega.2. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "817e36e92bf3cfc0985def0f36e72fc1b737b175" } +# against the revm tag above. +op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.2" } From 4835eebd500d8cccd2636857b6a79a688cd75ab7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:51:29 +0800 Subject: [PATCH 022/201] build: raise the MSRV to 1.94.1, the locked alloy 2.4 minimum --- Cargo.toml | 2 +- clippy.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2f34cf7d2..7fae74c56 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ resolver = "2" [workspace.package] version = "2.0.0-alpha.1" edition = "2021" -rust-version = "1.94" +rust-version = "1.94.1" license = "MIT OR Apache-2.0" homepage = "https://github.com/megaeth-labs/mega-evm" repository = "https://github.com/megaeth-labs/mega-evm" diff --git a/clippy.toml b/clippy.toml index 058aa492e..392025ce4 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,4 +1,4 @@ -msrv = "1.94" +msrv = "1.94.1" too-large-for-stack = 128 doc-valid-idents = [ "P2P", From 709c76ac08ed623fe8d49b6e13e0152a707daae4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:52:32 +0800 Subject: [PATCH 023/201] refactor: keep the op-revm implementation types crate-private --- crates/mega-evm/src/evm/context.rs | 2 +- crates/mega-evm/src/evm/factory.rs | 5 +++++ crates/mega-evm/src/evm/mod.rs | 13 +++++++++---- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 2b1e88529..d50fbb33e 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -20,7 +20,7 @@ use crate::{ /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` /// transaction type. -pub type MegaInnerContext = +pub(crate) type MegaInnerContext = Context, DB, Journal, L1BlockInfo>; /// Execution context of the Satin engine. diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 1874d067c..e8c4bf204 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -53,6 +53,11 @@ impl alloy_evm::EvmFactory for MegaEvmFactory type HaltReason = OpHaltReason; type Spec = MegaSpecId; type BlockEnv = BlockEnv; + /// op-revm's precompile set for the base spec. + /// + /// Provisional: the Satin precompile provider replaces this type when it lands, and code that + /// names `OpPrecompiles` through this associated type has no source-compatibility promise + /// across that change. type Precompiles = OpPrecompiles; /// Creates an EVM for the block in `evm_env`, with the external environments of that block. diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 6abc27542..5fae64b77 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -31,12 +31,12 @@ use revm::{ use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; /// The instruction table of the Satin engine. -pub type MegaInstructions = EthInstructions>; +pub(crate) type MegaInstructions = EthInstructions>; /// The op-revm EVM a [`MegaEvm`] wraps. /// /// It runs op-revm's precompile set for the base spec; T3.1 replaces it with the Satin set. -pub type MegaInnerEvm = +pub(crate) type MegaInnerEvm = OpEvm, INSP, MegaInstructions, OpPrecompiles>; /// The Satin EVM. @@ -82,7 +82,7 @@ impl MegaEvm { } /// Consumes the EVM and returns the op-revm EVM it wraps. - pub fn into_inner(self) -> MegaInnerEvm { + pub(crate) fn into_inner(self) -> MegaInnerEvm { self.inner } } @@ -185,6 +185,11 @@ where type HaltReason = OpHaltReason; type Spec = MegaSpecId; type BlockEnv = BlockEnv; + /// op-revm's precompile set for the base spec. + /// + /// Provisional: the Satin precompile provider replaces this type when it lands, and code that + /// names `OpPrecompiles` through this associated type has no source-compatibility promise + /// across that change. type Precompiles = OpPrecompiles; type Inspector = INSP; @@ -222,7 +227,7 @@ where } fn finish(self) -> (Self::DB, EvmEnv) { - let (db, cfg_env, block_env) = self.inner.0.ctx.into_parts(); + let (db, cfg_env, block_env) = self.into_inner().0.ctx.into_parts(); (db, EvmEnv { cfg_env, block_env }) } From 716666fce73b8191460e0954d140c5a059d76ee1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:55:02 +0800 Subject: [PATCH 024/201] style: format the crate-private instruction table alias --- crates/mega-evm/src/evm/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 5fae64b77..f86e328c4 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -31,7 +31,8 @@ use revm::{ use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; /// The instruction table of the Satin engine. -pub(crate) type MegaInstructions = EthInstructions>; +pub(crate) type MegaInstructions = + EthInstructions>; /// The op-revm EVM a [`MegaEvm`] wraps. /// From a2e15d692fd8ff94b8ebe52d335b9ec01e933e73 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:56:13 +0800 Subject: [PATCH 025/201] docs: name the owning mechanisms in comments and docs --- .github/workflows/benchmark.yml | 4 +- .github/workflows/replay-bench.yml | 2 +- AGENTS.md | 68 ++-- Cargo.toml | 3 +- REVIEW.md | 2 +- crates/mega-evm/Cargo.toml | 4 +- crates/mega-evm/benches/transact.rs | 2 +- crates/mega-evm/src/access/mod.rs | 2 +- crates/mega-evm/src/block/executor.rs | 6 +- crates/mega-evm/src/constants.rs | 18 +- crates/mega-evm/src/evm/context.rs | 11 +- crates/mega-evm/src/evm/mod.rs | 4 +- crates/mega-evm/src/external/AGENTS.md | 4 +- crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/src/system/keyless/mod.rs | 6 +- crates/mega-evm/src/system/mod.rs | 4 +- crates/mega-evm/src/types.rs | 4 +- crates/mega-evm/tests/_pending/README.md | 310 +++++++++--------- .../tests/_pending/src/access/volatile.rs | 4 +- .../tests/_pending/src/block/chain.rs | 4 +- .../mega-evm/tests/_pending/src/block/eips.rs | 4 +- .../tests/_pending/src/block/hardfork.rs | 4 +- .../tests/_pending/src/block/helpers.rs | 4 +- .../tests/_pending/src/block/limit.rs | 4 +- .../tests/_pending/src/block/result.rs | 4 +- .../tests/_pending/src/evm/context.rs | 4 +- .../tests/_pending/src/evm/factory.rs | 4 +- .../mega-evm/tests/_pending/src/evm/host.rs | 4 +- crates/mega-evm/tests/_pending/src/evm/mod.rs | 4 +- .../tests/_pending/src/evm/precompiles.rs | 4 +- .../mega-evm/tests/_pending/src/evm/result.rs | 4 +- .../mega-evm/tests/_pending/src/evm/state.rs | 4 +- .../tests/_pending/src/external/gas.rs | 4 +- .../tests/_pending/src/limit/compute_gas.rs | 4 +- .../tests/_pending/src/limit/data_size.rs | 4 +- .../tests/_pending/src/limit/frame_limit.rs | 4 +- .../tests/_pending/src/limit/kv_update.rs | 4 +- .../tests/_pending/src/limit/limit.rs | 4 +- .../mega-evm/tests/_pending/src/limit/mod.rs | 4 +- .../tests/_pending/src/sandbox/execution.rs | 4 +- .../tests/_pending/src/system/control.rs | 4 +- .../tests/_pending/src/system/deploy.rs | 4 +- .../tests/_pending/src/system/intercept.rs | 4 +- .../_pending/src/system/keyless_deploy.rs | 4 +- .../_pending/src/system/limit_control.rs | 4 +- .../tests/_pending/src/system/oracle.rs | 4 +- .../_pending/src/system/sequencer_registry.rs | 4 +- .../mega-evm/tests/_pending/src/system/tx.rs | 4 +- crates/mega-evm/tests/satin/equivalence.rs | 2 +- 49 files changed, 291 insertions(+), 289 deletions(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 09ec8906f..fca1291a1 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -199,8 +199,8 @@ jobs: strategy: fail-fast: false matrix: - # On the satin branch `transact` is the only bench target until T2.2 - # rebuilds the suite; T2.2 restores the full list. Scheduled and + # On the satin branch `transact` is the only bench target until the + # suite is rebuilt on Satin, which restores the full list. Scheduled and # comment-triggered runs use the default branch's copy of this file. target: [transact] steps: diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml index 69dfc25ea..808da589e 100644 --- a/.github/workflows/replay-bench.yml +++ b/.github/workflows/replay-bench.yml @@ -105,7 +105,7 @@ jobs: name: Replay throughput needs: prepare # Disabled on the satin branch: this job builds `state-test`, which is not a - # workspace member until T10.1 ports it to the Satin engine. T10.1 removes + # workspace member until it is ported to the Satin engine; the port removes # this line. (`compare` needs this job, so it is skipped with it.) Scheduled # and comment-triggered runs use the default branch's copy of this file. if: false diff --git a/AGENTS.md b/AGENTS.md index da6084f8c..c2051e1a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,8 @@ This branch (`satin`) builds **Satin**, the new engine: a single spec on the Meg Today's `main` is the legacy engine; Satin is the only active spec. The legacy engine (specs `Equivalence` through `Rex7`, the 1.x crate line on crates.io revm 27) is frozen and is not edited here. -Satin is being built ticket by ticket from an empty skeleton. -The module table below says what exists and which ticket fills the rest. +Satin is being built mechanism by mechanism from an empty skeleton. +The module table below says what exists and which mechanisms fill the rest. ## Build & Development Commands @@ -33,7 +33,7 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks (`transact` is the only target until T2.2 rebuilds the suite) +# Benchmarks (`transact` is the only target until the benchmark suite is rebuilt on Satin) cargo bench -p mega-evm --bench transact # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) @@ -52,13 +52,13 @@ Git submodules are required — clone with `--recursive` or run `git submodule u | ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | | `mega-evm` | `crates/mega-evm` | yes | The Satin engine | | `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins with T10.1 | -| `state-test` | `crates/state-test` | no | State-test CLI; rejoins with T10.1 | -| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins with T10.2 | -| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins with T10.3 | +| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | +| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | +| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | +| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | The four tool crates still target the legacy engine. -They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until their ticket ports them. +They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until they are ported to Satin. ### Dependencies on the forks @@ -84,17 +84,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over op-revm's `OpEvm`; `MegaEvmFactory` (alloy-evm) | T2.3 (frame lifecycle, result and gas types, inspector entry), T3.1–T3.4 (gas table, SALT pricing, history gas, compute), T5, T8.2 | -| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton | T8.1 (executor, Karst block rules), T5.2 (pre-block calls), T6.2 (deployments) | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | T3.2 (SALT pricing), T6.3 (oracle) | -| `limit/` | nothing | T2.3 (observe-stage-commit layer, abort protocol), T4.1 (data size), T4.2 (detention), T4.3 (state-gas limits, KV count) | -| `access/` | nothing | T4.2 (volatile-data access tracking) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | T6.1 (interceptors), T6.2 (deployment), T6.3 (oracle and control contracts), T7 (keyless as a native CREATE sub-frame) | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by T3–T4; the numbers are signed off by T14 | -| `types.rs` | transaction, halt reason, error and envelope aliases | T2.3 | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact` | T8.2 extends `BytecodeBuilder` | +| Module | Holds now | Filled by | +| -------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over op-revm's `OpEvm`; `MegaEvmFactory` (alloy-evm) | the common execution layer (frame lifecycle, result and gas types, inspector entry); the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM | +| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton | the block executor (Karst block rules), the pre-block system calls, the system contract deployments | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | nothing | the observe-stage-commit layer and abort protocol, the data-size limit, detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases | the common execution layer | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact` | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -102,18 +102,18 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. - The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. Gas above the 200M execution cap goes to the EIP-8037 reservoir. - The Osaka gas table prices state gas at zero, so no transaction draws state gas until T3.1 installs the Satin gas table. + The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. - Every `Host` and context method delegates to op-revm's context, and `MegaEvm` delegates execution to `OpEvm`. - `tests/satin/equivalence.rs` pins that Satin currently equals op-revm on the same `CfgEnv`, field by field; a later ticket that changes behavior on purpose updates that baseline. + `tests/satin/equivalence.rs` pins that Satin currently equals op-revm on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here. - T2.3 defines Satin's frame, abort and write-record contracts; follow those once they land. + The common execution layer defines Satin's frame, abort and write-record contracts; follow those once they land. ## Test Organization (`crates/mega-evm/tests/`) - `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). -- `_pending/` — the legacy tests the T0 inventory keeps, parked until their ticket ports them. - It has no `main.rs`, so Cargo does not build it; its `README.md` names the owner of every file. - When a ticket ports a pending test, it deletes it from `_pending/` in the same commit. +- `_pending/` — the legacy tests the test inventory keeps, parked until the mechanism they test lands. + It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. + The change that ports a pending test deletes it from `_pending/` in the same commit. - Unit tests live next to the code in `#[cfg(test)] mod tests`. ## Version Control @@ -167,11 +167,11 @@ When the agent is requested to implement a new feature or bug fix, it should con ## Caveats for Agents - **Satin is the only active spec; the legacy engine is frozen.** - Do not add legacy specs, alias rungs or spec gates to this crate, and do not port a legacy mechanism the T0 inventory retired. + Do not add legacy specs, alias rungs or spec gates to this crate, and do not port a legacy mechanism the legacy test inventory retired. Behavior of the legacy specs is changed only on the legacy line, never here. -- **Build from the skeleton, one ticket at a time.** - Each module is filled by the ticket named in the module table; do not implement another ticket's mechanism to make yours work. - If a ticket needs an interface that belongs to another ticket, stub the smallest interface and name the owning ticket. +- **Build from the skeleton, one mechanism at a time.** + Each module is filled by the mechanisms named in the module table; do not implement another mechanism to make yours work. + If a change needs an interface that belongs to another mechanism, stub the smallest interface and name the mechanism that owns it. - **Always test logic changes.** Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. @@ -189,16 +189,16 @@ When the agent is requested to implement a new feature or bug fix, it should con New `#[test]` functions should be named with a `test_` prefix for consistency with this repository and upstream revm style. If editing nearby tests in the same module, align names to the same `test_` style when reasonable. - **System contracts carry over as they are.** - Satin reuses the Solidity sources and bindings in `crates/system-contracts`; changing a contract needs a decision of its own, not a side effect of an engine ticket. -- **Rules for system contract interceptors (T6 onwards).** + Satin reuses the Solidity sources and bindings in `crates/system-contracts`; changing a contract needs a decision of its own, not a side effect of an engine change. +- **Rules for system contract interceptors (once the interceptors land).** For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor; if a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. Only `CALL` and `STATICCALL` reach interceptor dispatch; `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard before any interceptor is consulted. Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. -- **Validate per-fork parameters at load time (T8.1 onwards).** +- **Validate per-fork parameters at load time (once the block executor lands).** A hardfork parameters type overrides `HardforkParams::validate()` with field-level invariant checks, so a bad chain config fails when it is loaded rather than at the fork's first block. The fork-requires-params rule is registered in the schedule validation too, so a schedule that activates the fork without its params is rejected at load time. -- **Pre-block helpers must return state, not commit directly (T5.2, T6.2).** +- **Pre-block helpers must return state, not commit directly (pre-block system calls, system contract deployment).** Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. @@ -220,7 +220,7 @@ When the agent is requested to implement a new feature or bug fix, it should con Run `cargo fmt --all --check` before completion. - **Keep documentation up to date.** When making changes, always check whether related documentation needs updating. - The primary documentation is in `docs/`; it still describes the legacy engine until T15 writes the Satin pages. + The primary documentation is in `docs/`; it still describes the legacy engine until the Satin specification pages are written. The spec documentation is under `docs/spec/`, and the mega-evme documentation is under `docs/mega-evme/`. Also update this `AGENTS.md` when relevant (e.g., the module table, the unstable-spec marker). - **One sentence, one line.** diff --git a/Cargo.toml b/Cargo.toml index 7fae74c56..b4502668f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,8 +2,7 @@ [workspace] # The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, # `crates/state-test`) still target the legacy engine; their sources are kept -# untouched and they rejoin the workspace when T10.1 (state-test), T10.2 -# (mega-evme) and T10.3 (mega-t8n) port them to Satin. +# untouched and each rejoins the workspace when it is ported to Satin. members = ["crates/mega-evm", "crates/system-contracts"] default-members = ["crates/mega-evm"] exclude = [] diff --git a/REVIEW.md b/REVIEW.md index dc1ebec4f..b57b8c307 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,7 +24,7 @@ This is the single most important correctness concern in mega-evm. - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. - Pre-block helpers (system contract deploys, pre-exec system calls, etc.) must return `Option` for the block executor to commit — never call `db.commit(...)` directly. Even idempotent "no change" paths must return `Some(EvmState)` with a read-only account entry; silently returning `None` drops the account from the stateless witness read set and produces an incomplete proof. - On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the pre-block helpers arrive with T5.2 and T6.2. + On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the pre-block helpers arrive with the pre-block system calls and the system contract deployments. The same applies inside execution: read through the journal (`inspect_account`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state — and an early halt placed before the sandbox state merge drops that read set entirely. - Per-frame gas mechanisms (stipends, adjustments) must handle all frame termination paths: system contract interception, gas rescue on limit exceed, and frame return. Missing any path causes gas leakage. diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 1ca251453..a618e0884 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -56,8 +56,8 @@ std = [ ] test-utils = ["dep:derive_more"] -# T2.2 rebuilds the benchmark suite on Satin; until then `transact` is the only target. The -# inputs under benches/data (revm_bench) and benches/fixtures (attack_replay) stay for it. +# `transact` is the only target until the benchmark suite is rebuilt on Satin. The inputs +# under benches/data (revm_bench) and benches/fixtures (attack_replay) stay for the rebuild. [[bench]] name = "transact" harness = false diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 993887111..1743906c9 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -1,6 +1,6 @@ //! `ExecuteEvm::transact` on the Satin engine next to op-revm's `OpEvm` on the same `CfgEnv`. //! -//! A skeleton that keeps one benchmark target alive; T2.2 rebuilds the benchmark suite. Each +//! A skeleton that keeps one benchmark target alive until the benchmark suite is rebuilt. Each //! workload runs through `MegaEvm` (`satin`) and through `OpEvm` (`op_revm`), so the gap is the //! wrapper's own cost. EVM construction is setup and is not measured. #![allow(missing_docs)] diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 704d6e913..0a46ba7f8 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -1,3 +1,3 @@ //! Volatile-data access tracking (block environment, beneficiary, oracle) behind gas detention. //! -//! Empty until T4.2 fills it. +//! Empty until gas detention lands. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 7efe581e9..cd65aa3bc 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -1,8 +1,8 @@ //! Block executor of the Satin engine. //! -//! T8.1 builds block execution here: alloy-evm's `BlockExecutor` over a -//! [`MegaEvm`](crate::MegaEvm), the Karst block rules, the pre-block system calls (T5.2) and -//! deployments (T6.2), and the block-level limits. +//! Block execution lands here with the block executor: alloy-evm's `BlockExecutor` over a +//! [`MegaEvm`](crate::MegaEvm), the Karst block rules, the pre-block system calls and +//! system contract deployments, and the block-level limits. /// Executes the transactions of one block on a Satin EVM. /// diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 99081e9cc..f959e1633 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -4,18 +4,18 @@ //! A constant that no code reads yet is here so the whole placeholder set can be reviewed in //! one place. //! -//! | Constant | Value | Meaning | Read from | +//! | Constant | Value | Meaning | Read by | //! |---|---:|---|---| -//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | T3.1 | -//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | T3.1 | -//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | T3.1 | -//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | T3.3 | -//! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | now | -//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | T4.1 | -//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | T4.1 | +//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas table (not yet) | +//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | the Satin gas table (not yet) | +//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | the Satin gas table (not yet) | +//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas (not yet) | +//! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | the spec configuration | +//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the data-size limit (not yet) | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the data-size limit (not yet) | //! //! The storage call stipend and the per-transaction and per-block state-gas limits are further -//! placeholders; T3.3 and T4.3 add them with the mechanisms that read them. +//! placeholders; history gas and the state-gas limits add them when they land. use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index d50fbb33e..25dc4c259 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -122,8 +122,8 @@ impl MegaContext { /// /// Satin runs on the Osaka gas table of its Karst base, with EIP-8037 state gas and the EIP-2780 /// intrinsic cost switched on and gas above the execution cap going to the state-gas reservoir. -/// The EIP-7708 transfer logs and the system-call reservoir margin stay off until T3.1 and T5.2 -/// switch them on. +/// The EIP-7708 transfer logs and the system-call reservoir margin stay off until the Satin gas +/// table and the system-call reservoir split switch them on. fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.gas_params = GasParams::new_spec(cfg.spec.into_eth_spec()); cfg.enable_amsterdam_eip8037 = true; @@ -283,8 +283,11 @@ mod tests { assert!(eip8037, "EIP-8037 must be on"); assert!(eip2780, "EIP-2780 must be on"); assert_eq!(cap, Some(200_000_000), "execution cap"); - assert!(!eip7708, "EIP-7708 stays off until T3.1"); - assert!(!margin, "the system-call reservoir margin stays off until T5.2"); + assert!(!eip7708, "EIP-7708 stays off until the Satin gas table"); + assert!( + !margin, + "the system-call reservoir margin stays off until the reservoir split" + ); } let osaka = GasParams::new_spec(EthSpecId::OSAKA); assert_eq!(mega.gas_params.table(), osaka.table()); diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index f86e328c4..f2289d793 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -2,7 +2,7 @@ //! //! [`MegaEvm`] wraps op-revm's [`OpEvm`] over a [`MegaContext`] configured for the Satin spec. //! It adds no `MegaETH` behavior yet: SALT pricing, history gas, resource limits, detention and -//! the system contracts arrive with T3 through T8. +//! the system contracts are not here yet. mod context; mod factory; @@ -36,7 +36,7 @@ pub(crate) type MegaInstructions = /// The op-revm EVM a [`MegaEvm`] wraps. /// -/// It runs op-revm's precompile set for the base spec; T3.1 replaces it with the Satin set. +/// It runs op-revm's precompile set for the base spec until the Satin precompile set lands. pub(crate) type MegaInnerEvm = OpEvm, INSP, MegaInstructions, OpPrecompiles>; diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 272fd6417..29f2abe16 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -8,7 +8,7 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - `factory.rs`: `ExternalEnvFactory` trait for block-scoped environment creation. - `salt.rs`: SALT trait and bucket-id derivation rules. - `oracle.rs`: oracle trait for storage reads and hint side effects. -- SALT pricing (the state-gas price hook that consumes `SaltEnv`) is not here yet; T3.2 adds it. +- SALT pricing (the state-gas price hook that consumes `SaltEnv`) is not here yet. - `hasher/`: hashing utilities used for deterministic bucket-id computation. ## KEY PATTERNS @@ -25,5 +25,5 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d ## WHERE TO LOOK - Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. -- Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration arrives with T6.3). +- Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration is not here yet). - Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index d9e14a636..4e074c147 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -1,4 +1,4 @@ //! Resource limits of the Satin engine. //! -//! Empty until T2.3 (the observe-stage-commit layer and the abort protocol), T4.1 (data size), -//! T4.2 (detention caps) and T4.3 (state-gas limits and the KV count) fill it. +//! Empty until the observe-stage-commit layer and the abort protocol, the data-size limit, the +//! detention caps, and the state-gas limits and KV count land. diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 38b4dbbc2..875ba7aa7 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -2,9 +2,9 @@ //! error ABI. //! //! These are data-only helpers: decoding the pre-EIP-155 transaction, recovering its signer, -//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. T6.1 -//! adds the interceptor that dispatches `keylessDeploy` calls, and T7 executes the deployment -//! as a native CREATE sub-frame. +//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. The +//! interceptor that dispatches `keylessDeploy` calls and the deployment as a native CREATE +//! sub-frame are not here yet. mod error; mod tx; diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index 192392163..e046b0c6a 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -1,6 +1,6 @@ //! System contracts of the Satin engine. //! -//! Filled by T6.1 (interceptor dispatch), T6.2 (deployment at activation) and T6.3 (oracle and -//! control contracts). For now it holds only the keyless-deployment data helpers. +//! Filled when the interceptor dispatch, the deployment at activation and the oracle and control +//! contracts land. For now it holds only the keyless-deployment data helpers. pub mod keyless; diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs index a2588c7c4..02858a09f 100644 --- a/crates/mega-evm/src/types.rs +++ b/crates/mega-evm/src/types.rs @@ -1,7 +1,7 @@ //! Common type definitions of the Satin engine. //! -//! The result and error types are aliases of the OP ones for now; T2.3 decides the result and -//! gas types the engine exposes. +//! The result and error types are aliases of the OP ones for now; the common execution layer +//! decides the result and gas types the engine exposes when it lands. /// `MegaETH` transaction as the EVM executes it. /// diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e37761ad8..98c18cf81 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -1,8 +1,8 @@ # Pending tests -Tests of the legacy engine that survive into Satin but cannot run until the ticket that owns them lands. -The dispositions come from the T0 test inventory of the Satin work order, and T2.1 applied them mechanically. -Every test T0 marks 仅 legacy (legacy-only) or 废弃 (retired) was deleted; every other test was moved here unchanged. +Tests of the legacy engine that survive into Satin but cannot run until the mechanism that owns them lands. +The dispositions come from the test inventory of the Satin work order and were applied mechanically when the Satin skeleton replaced the legacy core. +Every test the inventory marks 仅 legacy (legacy-only) or 废弃 (retired) was deleted; every other test was moved here unchanged. The decision ids (`Dnn`) refer to the Satin decision table. ## How this directory is excluded from the build @@ -11,181 +11,181 @@ Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`. `_pending/` has no `main.rs`, so nothing below it is compiled, formatted or linted. Do not add a `_pending/main.rs`. -## Rules for the owning ticket +## Rules for porting -- Port the rows your ticket owns into a real test target, adapting them to the Satin API and the decision cited in the table. +- Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. - 保留 (keep) rows keep their scenario and expectation; 重写 (rewrite) rows keep the scenario and take the new expectation from the cited decision; 待定 (undecided) rows wait for their decision. - Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. -- Files under `mutation/` are machine-generated mutant killers; T2.2 regenerates them against the Satin sources instead of porting them by hand. -- Files under `src/` are the inline unit-test modules of the legacy core, extracted when T2.1 replaced `crates/mega-evm/src`. +- Files under `mutation/` are machine-generated mutant killers; the test gates regenerate them against the Satin sources instead of porting them by hand. +- Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. - Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. -## Tests per owning ticket +## Tests per owning mechanism -| Ticket | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | +| Owning mechanism | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | |---|---:|---:|---:|---:|---:|---:| -| T2.2 | 21 | 21 | 0 | 21 | 0 | 0 | -| T2.3 | 41 | 19 | 22 | 22 | 19 | 0 | -| T3.1 | 37 | 30 | 7 | 7 | 30 | 0 | -| T3.2 | 83 | 72 | 11 | 25 | 58 | 0 | -| T3.3 | 28 | 24 | 4 | 4 | 24 | 0 | -| T3.4 | 27 | 27 | 0 | 0 | 27 | 0 | -| T4.1 | 49 | 47 | 2 | 42 | 7 | 0 | -| T4.2 | 87 | 82 | 5 | 79 | 8 | 0 | -| T4.3 | 58 | 57 | 1 | 0 | 36 | 22 | -| T5.1 | 17 | 17 | 0 | 0 | 17 | 0 | -| T5.2 | 18 | 15 | 3 | 14 | 4 | 0 | -| T6.1 | 65 | 57 | 8 | 56 | 9 | 0 | -| T6.2 | 67 | 17 | 50 | 62 | 5 | 0 | -| T6.3 | 77 | 77 | 0 | 67 | 10 | 0 | -| T7 | 75 | 73 | 2 | 29 | 46 | 0 | -| T8.1 | 75 | 45 | 30 | 56 | 19 | 0 | -| T9 | 4 | 4 | 0 | 1 | 3 | 0 | +| the test gates | 21 | 21 | 0 | 21 | 0 | 0 | +| the common execution layer | 41 | 19 | 22 | 22 | 19 | 0 | +| the Satin gas table | 37 | 30 | 7 | 7 | 30 | 0 | +| SALT pricing | 83 | 72 | 11 | 25 | 58 | 0 | +| history gas | 28 | 24 | 4 | 4 | 24 | 0 | +| compute gas | 27 | 27 | 0 | 0 | 27 | 0 | +| the data-size limit | 49 | 47 | 2 | 42 | 7 | 0 | +| detention | 87 | 82 | 5 | 79 | 8 | 0 | +| the state-growth and KV limits | 58 | 57 | 1 | 0 | 36 | 22 | +| revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | +| the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | +| the system contract interceptors | 65 | 57 | 8 | 56 | 9 | 0 | +| system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | +| the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | +| native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | +| the block executor | 75 | 45 | 30 | 56 | 19 | 0 | +| inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | | **Total** | **836** | **691** | **145** | **485** | **322** | **29** | ## Tests ported in place -These rows came back with the code they test and run in `crates/mega-evm/src`, so the counts above are lower than T0's per-ticket totals by exactly these rows. +These rows came back with the code they test and run in `crates/mega-evm/src`, so the counts above are lower than the inventory's per-mechanism totals by exactly these rows. -| Legacy file | Owner in T0 | Tests | Now in | +| Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| -| `src/evm/context.rs` | T2.1 (3) | 3 | `src/evm/context.rs` | -| `src/evm/factory.rs` | T2.1 (1) | 1 | `src/evm/factory.rs` | -| `src/evm/mod.rs` | T2.1 (6) | 6 | `src/evm/mod.rs` | -| `src/evm/spec.rs` | T2.1 (3) | 3 | `src/evm/spec.rs` | -| `src/external/hasher/mod.rs` | T3.2 (5) | 5 | `src/external/hasher/mod.rs` | -| `src/external/mod.rs` | T2.1 (1) | 1 | `src/external/mod.rs` | -| `src/external/test_utils.rs` | T2.1 (1) | 1 | `src/external/test_utils.rs` | -| `src/sandbox/error.rs` | T7 (4) | 4 | `src/system/keyless/error.rs` | -| `src/sandbox/tx.rs` | T7 (10) | 10 | `src/system/keyless/tx.rs` | -| `src/test_utils/opcode_gen.rs` | T2.1 (2) | 2 | `src/test_utils/opcode_gen.rs` | +| `src/evm/context.rs` | the Satin skeleton (3) | 3 | `src/evm/context.rs` | +| `src/evm/factory.rs` | the Satin skeleton (1) | 1 | `src/evm/factory.rs` | +| `src/evm/mod.rs` | the Satin skeleton (6) | 6 | `src/evm/mod.rs` | +| `src/evm/spec.rs` | the Satin skeleton (3) | 3 | `src/evm/spec.rs` | +| `src/external/hasher/mod.rs` | SALT pricing (5) | 5 | `src/external/hasher/mod.rs` | +| `src/external/mod.rs` | the Satin skeleton (1) | 1 | `src/external/mod.rs` | +| `src/external/test_utils.rs` | the Satin skeleton (1) | 1 | `src/external/test_utils.rs` | +| `src/sandbox/error.rs` | native keyless deployment (4) | 4 | `src/system/keyless/error.rs` | +| `src/sandbox/tx.rs` | native keyless deployment (10) | 10 | `src/system/keyless/tx.rs` | +| `src/test_utils/opcode_gen.rs` | the Satin skeleton (2) | 2 | `src/test_utils/opcode_gen.rs` | | **Total** | | **36** | | -## Tests T0 assigns to T2.1 that are parked under another ticket +## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | |---|---|---|---| -| `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | T3.2 | exercises the dynamic storage-gas cache that SALT pricing brings back | -| `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | T3.1 | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | -| `src/evm/mod.rs` | `test_convenience_execution_methods_work` | T2.3 | `execute_transaction` returns the transaction outcome type that T2.3 defines | -| `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | T8.1 | reads the accessed-block-hash record, which returns with the block executor | +| `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | +| `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | the Satin gas table | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | +| `src/evm/mod.rs` | `test_convenience_execution_methods_work` | the common execution layer | `execute_transaction` returns the transaction outcome type that the common execution layer defines | +| `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | the block executor | reads the accessed-block-hash record, which returns with the block executor | ## Files -Each cell lists `disposition count (ticket · decision)`. +Each cell lists `disposition count (mechanism · decision)`. | File | Tests | Owners | |---|---:|---| -| `block_executor/accessed_block_hashes.rs` | 1 | 保留 1 (T8.1) | -| `block_executor/block_limits.rs` | 14 | 保留 12 (T8.1 · D47); 待定 2 (T4.3 · D46) | -| `block_executor/canonical_schedule.rs` | 1 | 重写 1 (T8.1 · single Satin fork; T15 owns the doc side) | -| `block_executor/deposit_da_exemption.rs` | 4 | 保留 4 (T8.1 · D23) | -| `block_executor/inspector.rs` | 3 | 保留 1 (T9); 重写 2 (T9 · D39/D41) | -| `block_executor/sequencer_registry.rs` | 8 | 保留 8 (T6.2) | -| `block_executor/trait_factory_runtime_limits.rs` | 4 | 重写 4 (T8.1 · D10 (200M execution cap replaces compute-gas runtime limit)) | -| `compute_gas/claims.rs` | 14 | 保留 2 (T6.1); 重写 2 (T3.4 · D53 (compute = regular spent; state spill excluded)); 保留 1 (T3.1 · D04 (KZG 100k)); 待定 5 (— · no D-id: preload-warm addresses charged cold (precompile / beneficiary / access-list) is absent from DECISIONS.md); 重写 2 (T3.1 · D13); 重写 1 (T3.1 · D11); 重写 1 (T4.1 · D33/D48) | -| `compute_gas/main.rs` | 1 | 重写 1 (T3.4 · D53) | -| `equivalence/evm_state.rs` | 3 | 保留 3 (T2.3) | -| `mini_rex/access_beneficiary_balance.rs` | 10 | 保留 9 (T4.2 · D08); 重写 1 (T5.1 · D48) | -| `mini_rex/block_env_access_tracking.rs` | 3 | 保留 3 (T4.2) | -| `mini_rex/block_env_gas_limit.rs` | 16 | 保留 13 (T4.2 · D08 cap 20M/1M unchanged); 重写 3 (T5.1 · D48 (detention halt -> revert-class)) | -| `mini_rex/compute_gas_limit.rs` | 25 | 重写 23 (T3.4 · D10/D40/D53 (compute derived from Gas; 200M cap)); 重写 2 (T4.2 · D48) | -| `mini_rex/contract_size_limit.rs` | 12 | 重写 12 (T3.1 · D04 (512 KiB kept; initcode bound under Osaka/EIP-3860 not pinned in DECISIONS.md)) | -| `mini_rex/db_error.rs` | 4 | 保留 4 (T2.3) | -| `mini_rex/gas.rs` | 26 | 重写 14 (T3.2 · D12 (state gas x m via pricing hook)); 重写 6 (T3.2 · D12/D13); 待定 2 (— · no D-id: 98/100 forwarding; D1 §2.5 says frame semantics follow 8037 (63/64) but DECISIONS.md is silent); 重写 4 (T3.1 · D11/D55 (7976 floor)) | -| `mini_rex/mega_system_transaction.rs` | 15 | 保留 15 (T6.1 · D51) | -| `mini_rex/oracle.rs` | 13 | 重写 3 (T5.1 · D48); 保留 5 (T4.2); 保留 4 (T6.3); 重写 1 (T6.2 · deploy at Satin activation) | -| `mini_rex/state_growth_limit.rs` | 4 | 重写 4 (T4.3 · D45 (state-gas limit)) | -| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | 保留 18 (T4.1 · data-size numbers unchanged); 重写 4 (T5.1 · D48); 待定 6 (T4.3 · D46 (count kept as output per R1b; limit semantics undecided)) | -| `mutation/access_evm.rs` | 10 | 保留 6 (T4.2 · T2.2 regenerates); 保留 2 (T3.2 · T2.2 regenerates); 保留 1 (T8.1 · T2.2 regenerates); 重写 1 (T3.1 · D11) | -| `mutation/block.rs` | 22 | 保留 14 (T8.1 · T2.2 regenerates); 重写 5 (T8.1 · single spec / Satin schedule); 待定 1 (T4.3 · D46); 重写 1 (T3.4 · D53); 重写 1 (T4.3 · D45) | -| `mutation/constants.rs` | 4 | 重写 2 (T3.1 · D04); 保留 2 (T4.1 · 13,107,200 unchanged) | -| `mutation/external_exec.rs` | 8 | 保留 2 (T8.1 · T2.2 regenerates); 保留 6 (T3.2 · T2.2 regenerates) | -| `rex/oracle.rs` | 3 | 重写 3 (T4.2 · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex/storage_gas.rs` | 15 | 重写 15 (T3.2 · D12 (base price and min-bucket value change; multiplier logic kept)) | -| `rex2/keyless_deploy.rs` | 37 | 重写 13 (T7 · D1 §2.6 native CREATE sub-frame; D37/D38); 保留 19 (T7 · validation rules 1-9 unchanged); 保留 1 (T7 · rule 4 (tx nonce == 0) unchanged); 重写 3 (T7 · D36); 重写 1 (T6.2 · deploy at Satin activation) | -| `rex2/oracle_hint.rs` | 6 | 保留 6 (T6.3) | -| `rex3/keyless_deploy.rs` | 2 | 重写 2 (T6.1 · D15 (explicit 100k compute) / D48) | -| `rex3/oracle_gas_limit.rs` | 8 | 保留 7 (T4.2 · D08); 重写 1 (T5.1 · D48) | -| `rex3/system_address.rs` | 2 | 保留 2 (T4.2 · D51) | -| `rex4/access_control.rs` | 48 | 保留 46 (T6.3); 重写 2 (T4.2 · D07 (rejected volatile read pays static gas)) | -| `rex4/beneficiary_detention.rs` | 13 | 保留 12 (T4.2 · D08); 重写 1 (T5.1 · D48) | -| `rex4/create_safety.rs` | 1 | 保留 1 (T2.2 · canonical revm behaviour (differential harness)) | -| `rex4/deployment.rs` | 2 | 重写 2 (T6.2 · deploy at Satin activation) | -| `rex4/eip7702_delegation_cycle.rs` | 9 | 保留 8 (T3.2 · account inspection on the pricing path); 保留 1 (T2.3) | -| `rex4/frame_limits.rs` | 20 | 保留 10 (T4.1 · data-size per-frame 98% kept); 重写 1 (T5.1 · D48); 待定 9 (T4.3 · D46) | -| `rex4/gas_detention.rs` | 5 | 保留 3 (T4.2); 重写 2 (T5.1 · D48/D53) | -| `rex4/intrinsic_limit_bypass.rs` | 13 | 重写 6 (T4.1 · D48/D49 (overflow outcome shape)); 待定 3 (T4.3 · D46); 保留 3 (T4.1); 重写 1 (T9 · D41) | -| `rex4/keyless_deploy.rs` | 2 | 保留 2 (T7 · native sub-frame inherits env) | -| `rex4/limit_control.rs` | 14 | 重写 9 (T6.3 · D40 (remaining compute derived from Gas)); 保留 5 (T6.1) | -| `rex4/storage_call_stipend.rs` | 12 | 重写 12 (T3.3 · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | -| `rex5/apply_pending_changes_gas_budget.rs` | 4 | 重写 4 (T5.2 · D51 (system source m = 1; F1b reservoir split)) | -| `rex5/call_too_deep_guard.rs` | 4 | 保留 4 (T6.1 · T2.3 synthetic-result contract) | -| `rex5/callcode_storage_gas.rs` | 6 | 重写 3 (T3.2 · D12); 保留 3 (T3.2 · pricing-failure propagation) | -| `rex5/create2_empty_initcode.rs` | 5 | 保留 5 (T2.2 · canonical revm behaviour (differential harness)) | -| `rex5/create2_resize_gas_metering.rs` | 2 | 保留 2 (T2.2 · canonical behaviour) | -| `rex5/db_error.rs` | 4 | 重写 3 (T7 · native path surfaces DB errors); 保留 1 (T6.1) | -| `rex5/deposit_caller_accounting.rs` | 7 | 重写 7 (T6.1 · D16 (kept; must not double-charge with 2780)) | -| `rex5/deposit_create_storage_gas.rs` | 4 | 重写 4 (T3.2 · D12/D37) | -| `rex5/eip7702_metering.rs` | 4 | 重写 4 (T3.2 · D12/D45) | -| `rex5/eip7702_state_growth.rs` | 8 | 重写 8 (T4.3 · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/frame_target_updated_dedup.rs` | 5 | 重写 5 (T2.3 · D50/D56 write-record layer) | -| `rex5/gas_validation.rs` | 4 | 重写 4 (T3.1 · D49/D55 (intrinsic state component; floor vs cap)) | -| `rex5/interceptor_selector_probe.rs` | 6 | 保留 6 (T6.1) | -| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | 保留 3 (T6.1) | -| `rex5/keyless_empty_code_logs.rs` | 2 | 重写 2 (T7 · native sub-frame keeps logs inherently) | -| `rex5/keyless_fee_free.rs` | 12 | 重写 8 (T7 · D16/D37/D38 (GASPRICE native; materialisation explicit)); 保留 4 (T7 · rules unchanged) | -| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | 重写 3 (T7 · native sub-frame gas handling) | -| `rex5/keyless_replay_barrier.rs` | 3 | 重写 3 (T7 · D36 (real nonce increment)) | -| `rex5/oracle_hint_metering.rs` | 9 | 保留 7 (T6.3 · D50 (hint not charged history; data-size metering kept)); 重写 1 (T6.3 · D11 intrinsic number); 重写 1 (T5.1 · D48) | -| `rex5/pre_block_system_calls.rs` | 11 | 保留 11 (T5.2) | -| `rex5/precompile_compute_gas.rs` | 3 | 重写 3 (T3.1 · D04/D40 (assert via gas_used)) | -| `rex5/sandbox_accounting.rs` | 9 | 重写 9 (T7 · native sub-frame: parent tracker sees child directly) | -| `rex5/selfdestruct_beneficiary.rs` | 7 | 重写 4 (T4.3 · D45 (state gas via new-account site)); 保留 2 (T4.2); 保留 1 (T4.1) | -| `rex5/sstore_storage_gas_error.rs` | 1 | 保留 1 (T3.2 · pricing-failure path) | -| `rex5/stipend_accounting.rs` | 6 | 重写 6 (T3.3 · D14 (history-only allowance lifecycle)) | -| `rex5/system_tx_replay.rs` | 12 | 保留 12 (T6.1) | -| `rex6/beneficiary_detention.rs` | 16 | 保留 13 (T4.2 · D08); 保留 2 (T4.1 · D50 write record 40 B); 重写 1 (T4.3 · D45) | -| `rex6/create2_metering_order.rs` | 11 | 保留 11 (T2.2 · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/create_frame_accounting.rs` | 3 | 重写 2 (T2.3 · D50/D56 write-record layer); 保留 1 (T3.2) | -| `rex6/eip7702_authority_accounting.rs` | 18 | 重写 18 (T4.3 · D12/D28/D31/D45 (7702 matrix; T3.2 for the SALT half)) | -| `rex6/error_paths.rs` | 4 | 保留 2 (T3.2); 保留 2 (T2.2 · canonical) | -| `rex6/fee_reward_accounting.rs` | 6 | 重写 6 (T3.3 · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | -| `rex6/frame_local_accounting.rs` | 3 | 保留 3 (T4.1 · LOG base 32 unchanged) | -| `rex6/keyless_sandbox_hardening.rs` | 3 | 重写 1 (T7 · D44 / EIP-6780 native); 保留 2 (T7 · canonical CREATE rules) | -| `rex6/oracle_hint_volatile_access.rs` | 4 | 保留 4 (T6.3) | -| `rex6/self_transfer_account_dedup.rs` | 5 | 重写 4 (T2.3 · D50/D56); 保留 1 (T4.1) | -| `rex6/sequencer_registry_rotation.rs` | 6 | 保留 5 (T6.2); 保留 1 (T8.1 · params validation at load) | -| `rex6/system_tx_metering_exemption.rs` | 3 | 重写 3 (T3.2 · D51 (m = 1 for system source; history exempt)) | -| `src/access/volatile.rs` | 4 | 保留 4 (T4.2) | -| `src/block/chain.rs` | 5 | 重写 4 (T8.1 · Satin activation timestamps; fallback pin = Satin); 保留 1 (T8.1) | -| `src/block/eips.rs` | 1 | 保留 1 (T8.1) | -| `src/block/hardfork.rs` | 12 | 重写 3 (T8.1 · single fork); 保留 9 (T8.1) | -| `src/block/helpers.rs` | 3 | 保留 3 (T8.1) | -| `src/block/limit.rs` | 5 | 保留 5 (T8.1) | -| `src/block/result.rs` | 2 | 重写 2 (T8.1 · D48 (error shape)) | -| `src/evm/context.rs` | 1 | 保留 1 (T3.2 · T3.2 for the SALT cache test) | -| `src/evm/factory.rs` | 1 | 重写 1 (T3.1 · no behaviour projection) | -| `src/evm/host.rs` | 11 | 保留 10 (T2.3 · Host observation layer (D33) on the revm 40 journal); 保留 1 (T3.2) | -| `src/evm/mod.rs` | 5 | 保留 3 (T5.2); 保留 1 (T8.1); 保留 1 (T2.3) | -| `src/evm/precompiles.rs` | 6 | 保留 6 (T3.1 · D04) | -| `src/evm/result.rs` | 4 | 重写 4 (T2.3 · D17/D48 (halt-reason set changes)) | -| `src/evm/state.rs` | 1 | 保留 1 (T8.1) | -| `src/external/gas.rs` | 9 | 重写 9 (T3.2 · D12/D51) | -| `src/limit/compute_gas.rs` | 1 | 重写 1 (T4.2 · D40/D48) | -| `src/limit/data_size.rs` | 2 | 保留 2 (T4.1) | -| `src/limit/frame_limit.rs` | 4 | 重写 4 (T2.3 · data-size-only per-frame tracker) | -| `src/limit/kv_update.rs` | 1 | 待定 1 (T4.3 · D46) | -| `src/limit/limit.rs` | 4 | 保留 4 (T3.3 · D51) | -| `src/limit/mod.rs` | 3 | 保留 3 (T2.3) | -| `src/sandbox/execution.rs` | 2 | 保留 1 (T7 · rule); 重写 1 (T7 · D16) | -| `src/system/control.rs` | 8 | 保留 8 (T6.2 · T6.1 for selector/revert-data tests) | -| `src/system/deploy.rs` | 4 | 保留 3 (T6.2); 重写 1 (T6.2 · single version) | -| `src/system/intercept.rs` | 2 | 保留 2 (T6.1) | -| `src/system/keyless_deploy.rs` | 2 | 保留 2 (T6.2) | -| `src/system/limit_control.rs` | 5 | 保留 5 (T6.2) | -| `src/system/oracle.rs` | 7 | 保留 7 (T6.2 · v2.0.0 only) | -| `src/system/sequencer_registry.rs` | 24 | 保留 24 (T6.2 · T5.2 for transact_apply_pending_changes) | -| `src/system/tx.rs` | 6 | 保留 6 (T6.1 · D51) | +| `block_executor/accessed_block_hashes.rs` | 1 | 保留 1 (the block executor) | +| `block_executor/block_limits.rs` | 14 | 保留 12 (the block executor · D47); 待定 2 (the state-growth and KV limits · D46) | +| `block_executor/canonical_schedule.rs` | 1 | 重写 1 (the block executor · single Satin fork; the specification pages own the doc side) | +| `block_executor/deposit_da_exemption.rs` | 4 | 保留 4 (the block executor · D23) | +| `block_executor/inspector.rs` | 3 | 保留 1 (inspector support); 重写 2 (inspector support · D39/D41) | +| `block_executor/sequencer_registry.rs` | 8 | 保留 8 (system contract deployment) | +| `block_executor/trait_factory_runtime_limits.rs` | 4 | 重写 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | +| `compute_gas/claims.rs` | 14 | 保留 2 (the system contract interceptors); 重写 2 (compute gas · D53 (compute = regular spent; state spill excluded)); 保留 1 (the Satin gas table · D04 (KZG 100k)); 待定 5 (— · no D-id: preload-warm addresses charged cold (precompile / beneficiary / access-list) is absent from DECISIONS.md); 重写 2 (the Satin gas table · D13); 重写 1 (the Satin gas table · D11); 重写 1 (the data-size limit · D33/D48) | +| `compute_gas/main.rs` | 1 | 重写 1 (compute gas · D53) | +| `equivalence/evm_state.rs` | 3 | 保留 3 (the common execution layer) | +| `mini_rex/access_beneficiary_balance.rs` | 10 | 保留 9 (detention · D08); 重写 1 (revert-class aborts · D48) | +| `mini_rex/block_env_access_tracking.rs` | 3 | 保留 3 (detention) | +| `mini_rex/block_env_gas_limit.rs` | 16 | 保留 13 (detention · D08 cap 20M/1M unchanged); 重写 3 (revert-class aborts · D48 (detention halt -> revert-class)) | +| `mini_rex/compute_gas_limit.rs` | 25 | 重写 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); 重写 2 (detention · D48) | +| `mini_rex/contract_size_limit.rs` | 12 | 重写 12 (the Satin gas table · D04 (512 KiB kept; initcode bound under Osaka/EIP-3860 not pinned in DECISIONS.md)) | +| `mini_rex/db_error.rs` | 4 | 保留 4 (the common execution layer) | +| `mini_rex/gas.rs` | 26 | 重写 14 (SALT pricing · D12 (state gas x m via pricing hook)); 重写 6 (SALT pricing · D12/D13); 待定 2 (— · no D-id: 98/100 forwarding; D1 §2.5 says frame semantics follow 8037 (63/64) but DECISIONS.md is silent); 重写 4 (the Satin gas table · D11/D55 (7976 floor)) | +| `mini_rex/mega_system_transaction.rs` | 15 | 保留 15 (the system contract interceptors · D51) | +| `mini_rex/oracle.rs` | 13 | 重写 3 (revert-class aborts · D48); 保留 5 (detention); 保留 4 (the oracle and control contracts); 重写 1 (system contract deployment · deploy at Satin activation) | +| `mini_rex/state_growth_limit.rs` | 4 | 重写 4 (the state-growth and KV limits · D45 (state-gas limit)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | 保留 18 (the data-size limit · data-size numbers unchanged); 重写 4 (revert-class aborts · D48); 待定 6 (the state-growth and KV limits · D46 (count kept as output per R1b; limit semantics undecided)) | +| `mutation/access_evm.rs` | 10 | 保留 6 (detention · the test gates regenerate); 保留 2 (SALT pricing · the test gates regenerate); 保留 1 (the block executor · the test gates regenerate); 重写 1 (the Satin gas table · D11) | +| `mutation/block.rs` | 22 | 保留 14 (the block executor · the test gates regenerate); 重写 5 (the block executor · single spec / Satin schedule); 待定 1 (the state-growth and KV limits · D46); 重写 1 (compute gas · D53); 重写 1 (the state-growth and KV limits · D45) | +| `mutation/constants.rs` | 4 | 重写 2 (the Satin gas table · D04); 保留 2 (the data-size limit · 13,107,200 unchanged) | +| `mutation/external_exec.rs` | 8 | 保留 2 (the block executor · the test gates regenerate); 保留 6 (SALT pricing · the test gates regenerate) | +| `rex/oracle.rs` | 3 | 重写 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | +| `rex/storage_gas.rs` | 15 | 重写 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | +| `rex2/keyless_deploy.rs` | 37 | 重写 13 (native keyless deployment · D1 §2.6 native CREATE sub-frame; D37/D38); 保留 19 (native keyless deployment · validation rules 1-9 unchanged); 保留 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); 重写 3 (native keyless deployment · D36); 重写 1 (system contract deployment · deploy at Satin activation) | +| `rex2/oracle_hint.rs` | 6 | 保留 6 (the oracle and control contracts) | +| `rex3/keyless_deploy.rs` | 2 | 重写 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | +| `rex3/oracle_gas_limit.rs` | 8 | 保留 7 (detention · D08); 重写 1 (revert-class aborts · D48) | +| `rex3/system_address.rs` | 2 | 保留 2 (detention · D51) | +| `rex4/access_control.rs` | 48 | 保留 46 (the oracle and control contracts); 重写 2 (detention · D07 (rejected volatile read pays static gas)) | +| `rex4/beneficiary_detention.rs` | 13 | 保留 12 (detention · D08); 重写 1 (revert-class aborts · D48) | +| `rex4/create_safety.rs` | 1 | 保留 1 (the test gates · canonical revm behaviour (differential harness)) | +| `rex4/deployment.rs` | 2 | 重写 2 (system contract deployment · deploy at Satin activation) | +| `rex4/eip7702_delegation_cycle.rs` | 9 | 保留 8 (SALT pricing · account inspection on the pricing path); 保留 1 (the common execution layer) | +| `rex4/frame_limits.rs` | 20 | 保留 10 (the data-size limit · data-size per-frame 98% kept); 重写 1 (revert-class aborts · D48); 待定 9 (the state-growth and KV limits · D46) | +| `rex4/gas_detention.rs` | 5 | 保留 3 (detention); 重写 2 (revert-class aborts · D48/D53) | +| `rex4/intrinsic_limit_bypass.rs` | 13 | 重写 6 (the data-size limit · D48/D49 (overflow outcome shape)); 待定 3 (the state-growth and KV limits · D46); 保留 3 (the data-size limit); 重写 1 (inspector support · D41) | +| `rex4/keyless_deploy.rs` | 2 | 保留 2 (native keyless deployment · native sub-frame inherits env) | +| `rex4/limit_control.rs` | 14 | 重写 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); 保留 5 (the system contract interceptors) | +| `rex4/storage_call_stipend.rs` | 12 | 重写 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | +| `rex5/apply_pending_changes_gas_budget.rs` | 4 | 重写 4 (the pre-block system calls · D51 (system source m = 1; F1b reservoir split)) | +| `rex5/call_too_deep_guard.rs` | 4 | 保留 4 (the system contract interceptors · the synthetic-result contract of the common execution layer) | +| `rex5/callcode_storage_gas.rs` | 6 | 重写 3 (SALT pricing · D12); 保留 3 (SALT pricing · pricing-failure propagation) | +| `rex5/create2_empty_initcode.rs` | 5 | 保留 5 (the test gates · canonical revm behaviour (differential harness)) | +| `rex5/create2_resize_gas_metering.rs` | 2 | 保留 2 (the test gates · canonical behaviour) | +| `rex5/db_error.rs` | 4 | 重写 3 (native keyless deployment · native path surfaces DB errors); 保留 1 (the system contract interceptors) | +| `rex5/deposit_caller_accounting.rs` | 7 | 重写 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | +| `rex5/deposit_create_storage_gas.rs` | 4 | 重写 4 (SALT pricing · D12/D37) | +| `rex5/eip7702_metering.rs` | 4 | 重写 4 (SALT pricing · D12/D45) | +| `rex5/eip7702_state_growth.rs` | 8 | 重写 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | +| `rex5/frame_target_updated_dedup.rs` | 5 | 重写 5 (the common execution layer · D50/D56 write-record layer) | +| `rex5/gas_validation.rs` | 4 | 重写 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | +| `rex5/interceptor_selector_probe.rs` | 6 | 保留 6 (the system contract interceptors) | +| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | 保留 3 (the system contract interceptors) | +| `rex5/keyless_empty_code_logs.rs` | 2 | 重写 2 (native keyless deployment · native sub-frame keeps logs inherently) | +| `rex5/keyless_fee_free.rs` | 12 | 重写 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); 保留 4 (native keyless deployment · rules unchanged) | +| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | 重写 3 (native keyless deployment · native sub-frame gas handling) | +| `rex5/keyless_replay_barrier.rs` | 3 | 重写 3 (native keyless deployment · D36 (real nonce increment)) | +| `rex5/oracle_hint_metering.rs` | 9 | 保留 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); 重写 1 (the oracle and control contracts · D11 intrinsic number); 重写 1 (revert-class aborts · D48) | +| `rex5/pre_block_system_calls.rs` | 11 | 保留 11 (the pre-block system calls) | +| `rex5/precompile_compute_gas.rs` | 3 | 重写 3 (the Satin gas table · D04/D40 (assert via gas_used)) | +| `rex5/sandbox_accounting.rs` | 9 | 重写 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | +| `rex5/selfdestruct_beneficiary.rs` | 7 | 重写 4 (the state-growth and KV limits · D45 (state gas via new-account site)); 保留 2 (detention); 保留 1 (the data-size limit) | +| `rex5/sstore_storage_gas_error.rs` | 1 | 保留 1 (SALT pricing · pricing-failure path) | +| `rex5/stipend_accounting.rs` | 6 | 重写 6 (history gas · D14 (history-only allowance lifecycle)) | +| `rex5/system_tx_replay.rs` | 12 | 保留 12 (the system contract interceptors) | +| `rex6/beneficiary_detention.rs` | 16 | 保留 13 (detention · D08); 保留 2 (the data-size limit · D50 write record 40 B); 重写 1 (the state-growth and KV limits · D45) | +| `rex6/create2_metering_order.rs` | 11 | 保留 11 (the test gates · canonical halt reasons; D04 512 KiB boundary) | +| `rex6/create_frame_accounting.rs` | 3 | 重写 2 (the common execution layer · D50/D56 write-record layer); 保留 1 (SALT pricing) | +| `rex6/eip7702_authority_accounting.rs` | 18 | 重写 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | +| `rex6/error_paths.rs` | 4 | 保留 2 (SALT pricing); 保留 2 (the test gates · canonical) | +| `rex6/fee_reward_accounting.rs` | 6 | 重写 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | +| `rex6/frame_local_accounting.rs` | 3 | 保留 3 (the data-size limit · LOG base 32 unchanged) | +| `rex6/keyless_sandbox_hardening.rs` | 3 | 重写 1 (native keyless deployment · D44 / EIP-6780 native); 保留 2 (native keyless deployment · canonical CREATE rules) | +| `rex6/oracle_hint_volatile_access.rs` | 4 | 保留 4 (the oracle and control contracts) | +| `rex6/self_transfer_account_dedup.rs` | 5 | 重写 4 (the common execution layer · D50/D56); 保留 1 (the data-size limit) | +| `rex6/sequencer_registry_rotation.rs` | 6 | 保留 5 (system contract deployment); 保留 1 (the block executor · params validation at load) | +| `rex6/system_tx_metering_exemption.rs` | 3 | 重写 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | +| `src/access/volatile.rs` | 4 | 保留 4 (detention) | +| `src/block/chain.rs` | 5 | 重写 4 (the block executor · Satin activation timestamps; fallback pin = Satin); 保留 1 (the block executor) | +| `src/block/eips.rs` | 1 | 保留 1 (the block executor) | +| `src/block/hardfork.rs` | 12 | 重写 3 (the block executor · single fork); 保留 9 (the block executor) | +| `src/block/helpers.rs` | 3 | 保留 3 (the block executor) | +| `src/block/limit.rs` | 5 | 保留 5 (the block executor) | +| `src/block/result.rs` | 2 | 重写 2 (the block executor · D48 (error shape)) | +| `src/evm/context.rs` | 1 | 保留 1 (SALT pricing · SALT pricing for the SALT cache test) | +| `src/evm/factory.rs` | 1 | 重写 1 (the Satin gas table · no behaviour projection) | +| `src/evm/host.rs` | 11 | 保留 10 (the common execution layer · Host observation layer (D33) on the revm 40 journal); 保留 1 (SALT pricing) | +| `src/evm/mod.rs` | 5 | 保留 3 (the pre-block system calls); 保留 1 (the block executor); 保留 1 (the common execution layer) | +| `src/evm/precompiles.rs` | 6 | 保留 6 (the Satin gas table · D04) | +| `src/evm/result.rs` | 4 | 重写 4 (the common execution layer · D17/D48 (halt-reason set changes)) | +| `src/evm/state.rs` | 1 | 保留 1 (the block executor) | +| `src/external/gas.rs` | 9 | 重写 9 (SALT pricing · D12/D51) | +| `src/limit/compute_gas.rs` | 1 | 重写 1 (detention · D40/D48) | +| `src/limit/data_size.rs` | 2 | 保留 2 (the data-size limit) | +| `src/limit/frame_limit.rs` | 4 | 重写 4 (the common execution layer · data-size-only per-frame tracker) | +| `src/limit/kv_update.rs` | 1 | 待定 1 (the state-growth and KV limits · D46) | +| `src/limit/limit.rs` | 4 | 保留 4 (history gas · D51) | +| `src/limit/mod.rs` | 3 | 保留 3 (the common execution layer) | +| `src/sandbox/execution.rs` | 2 | 保留 1 (native keyless deployment · rule); 重写 1 (native keyless deployment · D16) | +| `src/system/control.rs` | 8 | 保留 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | +| `src/system/deploy.rs` | 4 | 保留 3 (system contract deployment); 重写 1 (system contract deployment · single version) | +| `src/system/intercept.rs` | 2 | 保留 2 (the system contract interceptors) | +| `src/system/keyless_deploy.rs` | 2 | 保留 2 (system contract deployment) | +| `src/system/limit_control.rs` | 5 | 保留 5 (system contract deployment) | +| `src/system/oracle.rs` | 7 | 保留 7 (system contract deployment · v2.0.0 only) | +| `src/system/sequencer_registry.rs` | 24 | 保留 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/tx.rs` | 6 | 保留 6 (the system contract interceptors · D51) | diff --git a/crates/mega-evm/tests/_pending/src/access/volatile.rs b/crates/mega-evm/tests/_pending/src/access/volatile.rs index 86e019238..7aa7e6405 100644 --- a/crates/mega-evm/tests/_pending/src/access/volatile.rs +++ b/crates/mega-evm/tests/_pending/src/access/volatile.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/access/volatile.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/access/volatile.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/access/volatile.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/chain.rs b/crates/mega-evm/tests/_pending/src/block/chain.rs index 43a9b5cc1..ff0d74c55 100644 --- a/crates/mega-evm/tests/_pending/src/block/chain.rs +++ b/crates/mega-evm/tests/_pending/src/block/chain.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/chain.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/chain.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/chain.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/eips.rs b/crates/mega-evm/tests/_pending/src/block/eips.rs index f9b491a21..0bba32f6f 100644 --- a/crates/mega-evm/tests/_pending/src/block/eips.rs +++ b/crates/mega-evm/tests/_pending/src/block/eips.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/eips.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/eips.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/eips.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/hardfork.rs b/crates/mega-evm/tests/_pending/src/block/hardfork.rs index 36daeb6a6..5094ee39b 100644 --- a/crates/mega-evm/tests/_pending/src/block/hardfork.rs +++ b/crates/mega-evm/tests/_pending/src/block/hardfork.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/hardfork.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/hardfork.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/hardfork.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/helpers.rs b/crates/mega-evm/tests/_pending/src/block/helpers.rs index b04f83479..9a45b97fd 100644 --- a/crates/mega-evm/tests/_pending/src/block/helpers.rs +++ b/crates/mega-evm/tests/_pending/src/block/helpers.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/helpers.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/helpers.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/helpers.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/limit.rs b/crates/mega-evm/tests/_pending/src/block/limit.rs index 21355e416..ebe3786ae 100644 --- a/crates/mega-evm/tests/_pending/src/block/limit.rs +++ b/crates/mega-evm/tests/_pending/src/block/limit.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/limit.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/limit.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/limit.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/block/result.rs b/crates/mega-evm/tests/_pending/src/block/result.rs index f6c8256ad..a0c55ca24 100644 --- a/crates/mega-evm/tests/_pending/src/block/result.rs +++ b/crates/mega-evm/tests/_pending/src/block/result.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/result.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/block/result.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/result.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/context.rs b/crates/mega-evm/tests/_pending/src/evm/context.rs index 864b5feca..de57bad9d 100644 --- a/crates/mega-evm/tests/_pending/src/evm/context.rs +++ b/crates/mega-evm/tests/_pending/src/evm/context.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/context.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/context.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/context.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/factory.rs b/crates/mega-evm/tests/_pending/src/evm/factory.rs index 3fdb3d831..6e3a8b9da 100644 --- a/crates/mega-evm/tests/_pending/src/evm/factory.rs +++ b/crates/mega-evm/tests/_pending/src/evm/factory.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/factory.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/factory.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/factory.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/host.rs b/crates/mega-evm/tests/_pending/src/evm/host.rs index 7852c5b45..a092f529a 100644 --- a/crates/mega-evm/tests/_pending/src/evm/host.rs +++ b/crates/mega-evm/tests/_pending/src/evm/host.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/host.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/host.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/host.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs index 993004bac..7cdc0d824 100644 --- a/crates/mega-evm/tests/_pending/src/evm/mod.rs +++ b/crates/mega-evm/tests/_pending/src/evm/mod.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/mod.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/mod.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/mod.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs index a412c03f3..8f5e776b3 100644 --- a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs +++ b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/precompiles.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/precompiles.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/precompiles.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/result.rs b/crates/mega-evm/tests/_pending/src/evm/result.rs index 044576f3a..865b08472 100644 --- a/crates/mega-evm/tests/_pending/src/evm/result.rs +++ b/crates/mega-evm/tests/_pending/src/evm/result.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/result.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/result.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/result.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/evm/state.rs b/crates/mega-evm/tests/_pending/src/evm/state.rs index 2e5fb02f8..54b6172b8 100644 --- a/crates/mega-evm/tests/_pending/src/evm/state.rs +++ b/crates/mega-evm/tests/_pending/src/evm/state.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/state.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/evm/state.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/state.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/external/gas.rs b/crates/mega-evm/tests/_pending/src/external/gas.rs index 58719dd9a..271776c5d 100644 --- a/crates/mega-evm/tests/_pending/src/external/gas.rs +++ b/crates/mega-evm/tests/_pending/src/external/gas.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/external/gas.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/external/gas.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/gas.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs index e43e59eaa..8696695dc 100644 --- a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs +++ b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/compute_gas.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/compute_gas.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/compute_gas.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/data_size.rs b/crates/mega-evm/tests/_pending/src/limit/data_size.rs index e97f9e27e..e7a8ba712 100644 --- a/crates/mega-evm/tests/_pending/src/limit/data_size.rs +++ b/crates/mega-evm/tests/_pending/src/limit/data_size.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/data_size.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/data_size.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/data_size.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs b/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs index a7ba67f45..b9d899e16 100644 --- a/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs +++ b/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/frame_limit.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/frame_limit.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/frame_limit.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs index 5ae7a27e1..f7d03325d 100644 --- a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs +++ b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/kv_update.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/kv_update.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/kv_update.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/limit.rs b/crates/mega-evm/tests/_pending/src/limit/limit.rs index 2b55341e1..8a2bdf354 100644 --- a/crates/mega-evm/tests/_pending/src/limit/limit.rs +++ b/crates/mega-evm/tests/_pending/src/limit/limit.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/limit.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/limit.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/limit.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod metering_exemption_tests { diff --git a/crates/mega-evm/tests/_pending/src/limit/mod.rs b/crates/mega-evm/tests/_pending/src/limit/mod.rs index aeca2a5fb..77cc96754 100644 --- a/crates/mega-evm/tests/_pending/src/limit/mod.rs +++ b/crates/mega-evm/tests/_pending/src/limit/mod.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/mod.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/limit/mod.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/mod.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs index 3ead4fb4d..10b913932 100644 --- a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs +++ b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/sandbox/execution.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/sandbox/execution.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/execution.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/control.rs b/crates/mega-evm/tests/_pending/src/system/control.rs index 7613fcb7e..97b91a79f 100644 --- a/crates/mega-evm/tests/_pending/src/system/control.rs +++ b/crates/mega-evm/tests/_pending/src/system/control.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/control.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/control.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/control.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/deploy.rs b/crates/mega-evm/tests/_pending/src/system/deploy.rs index 5238b5246..b8c6f6ee1 100644 --- a/crates/mega-evm/tests/_pending/src/system/deploy.rs +++ b/crates/mega-evm/tests/_pending/src/system/deploy.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/deploy.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/deploy.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/deploy.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/intercept.rs b/crates/mega-evm/tests/_pending/src/system/intercept.rs index 65742e3a8..e6fb0a3e0 100644 --- a/crates/mega-evm/tests/_pending/src/system/intercept.rs +++ b/crates/mega-evm/tests/_pending/src/system/intercept.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/intercept.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/intercept.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/intercept.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs index fd6f4b55f..a87f1be64 100644 --- a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/keyless_deploy.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/keyless_deploy.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/keyless_deploy.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/limit_control.rs b/crates/mega-evm/tests/_pending/src/system/limit_control.rs index 1a9632e0b..b0e5cf5ce 100644 --- a/crates/mega-evm/tests/_pending/src/system/limit_control.rs +++ b/crates/mega-evm/tests/_pending/src/system/limit_control.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/limit_control.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/limit_control.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/limit_control.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/oracle.rs b/crates/mega-evm/tests/_pending/src/system/oracle.rs index dced446b8..c85499e48 100644 --- a/crates/mega-evm/tests/_pending/src/system/oracle.rs +++ b/crates/mega-evm/tests/_pending/src/system/oracle.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/oracle.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/oracle.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/oracle.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs index 8f3dec40a..8c7612abb 100644 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/sequencer_registry.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/sequencer_registry.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/sequencer_registry.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/_pending/src/system/tx.rs b/crates/mega-evm/tests/_pending/src/system/tx.rs index 0905bf354..4314fa100 100644 --- a/crates/mega-evm/tests/_pending/src/system/tx.rs +++ b/crates/mega-evm/tests/_pending/src/system/tx.rs @@ -1,6 +1,6 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/tx.rs` when T2.1 replaced the legacy core. +//! Unit tests extracted from `crates/mega-evm/src/system/tx.rs` when the Satin skeleton replaced the legacy core. //! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/tx.rs`. -//! Owning tickets are listed in `tests/_pending/README.md`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index ef0643f47..67dae6bae 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -149,7 +149,7 @@ fn test_sstore_matches_op_revm() { assert!(mega.result.is_success()); assert_eq!(mega.state[&CALLEE].storage[&U256::ZERO].present_value, U256::from(42)); // The Osaka gas table has no state-gas prices, so the new slot draws no state gas even with - // EIP-8037 on. The Satin gas table (T3.1) prices it; this assertion changes with it. + // EIP-8037 on. The Satin gas table prices it; this assertion changes with it. assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); } From a4f33c476d1d2bf6805831702b8595ec5f19a68d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:56:36 +0800 Subject: [PATCH 026/201] test: record the reviewer sign-off for the EthSpecId default suppression --- mutants/suppressions.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 578cd0bda..945b825b7 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -194,5 +194,5 @@ kind = "line" category = "equivalent" file = "crates/mega-evm/src/evm/spec.rs" mutant = "replace for EthSpecId>::from -> Self with Default::default()" -justification = "Equivalent: the only MegaSpecId (SATIN) maps to EthSpecId::OSAKA, which is revm 40.0.3's SpecId::default(), so Default::default() returns the same value on every input." -reviewer = "T2.1 author; to be confirmed in the Satin wave-1 PR review" +justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." +reviewer = "RealiCZ" From 5dfc8917e6baa13f17dde611e72c6b6212c4ef51 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 11:56:52 +0800 Subject: [PATCH 027/201] style: drop the trailing blank lines of the parked test files --- crates/mega-evm/tests/_pending/mini_rex/gas.rs | 1 - crates/mega-evm/tests/_pending/mini_rex/oracle.rs | 1 - crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs | 1 - .../tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs | 1 - crates/mega-evm/tests/_pending/rex4/access_control.rs | 1 - crates/mega-evm/tests/_pending/rex4/create_safety.rs | 1 - crates/mega-evm/tests/_pending/rex4/deployment.rs | 1 - crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs | 1 - crates/mega-evm/tests/_pending/rex4/frame_limits.rs | 1 - crates/mega-evm/tests/_pending/rex4/gas_detention.rs | 1 - crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs | 1 - crates/mega-evm/tests/_pending/rex4/limit_control.rs | 1 - crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs | 1 - .../mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs | 1 - crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs | 1 - .../mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs | 1 - 16 files changed, 16 deletions(-) diff --git a/crates/mega-evm/tests/_pending/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs index ce85a7c4d..c131f5235 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -821,4 +821,3 @@ fn test_floor_gas_empty_calldata() { fn test_floor_gas_minimal_calldata() { floor_gas_test_case(MegaSpecId::MINI_REX, 1, 21_440); } - diff --git a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs index ad81f9376..5d80ffc90 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -842,4 +842,3 @@ fn test_mega_system_address_exempted_from_oracle_tracking() { "Compute gas limit should NOT be set for mega system address transactions" ); } - diff --git a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs index e7af3b48f..4e1f5934e 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs @@ -218,4 +218,3 @@ fn test_state_reverted_when_exceeding_limit() { // ============================================================================ // TRACKER MIGRATION COVERAGE TESTS // ============================================================================ - diff --git a/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs index ba3ca221c..fb18534ff 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs @@ -1162,4 +1162,3 @@ impl Inspector for GasSpendingInspector { } } } - diff --git a/crates/mega-evm/tests/_pending/rex4/access_control.rs b/crates/mega-evm/tests/_pending/rex4/access_control.rs index 8b0465a27..976f8ab06 100644 --- a/crates/mega-evm/tests/_pending/rex4/access_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/access_control.rs @@ -1994,4 +1994,3 @@ fn test_blocked_selfdestruct_beneficiary_does_not_pollute_tracker() { "compute_gas_limit should not be set after blocked SELFDESTRUCT to beneficiary" ); } - diff --git a/crates/mega-evm/tests/_pending/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs index 133657771..363729117 100644 --- a/crates/mega-evm/tests/_pending/rex4/create_safety.rs +++ b/crates/mega-evm/tests/_pending/rex4/create_safety.rs @@ -148,4 +148,3 @@ fn run_create2_and_get_compute_gas( let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; (res.result, compute_gas) } - diff --git a/crates/mega-evm/tests/_pending/rex4/deployment.rs b/crates/mega-evm/tests/_pending/rex4/deployment.rs index 29578d4c1..de45f65ff 100644 --- a/crates/mega-evm/tests/_pending/rex4/deployment.rs +++ b/crates/mega-evm/tests/_pending/rex4/deployment.rs @@ -163,4 +163,3 @@ fn test_rex4_system_contract_deployment_is_idempotent() { ); }); } - diff --git a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs index c574a0268..dc06cb58d 100644 --- a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs +++ b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs @@ -481,4 +481,3 @@ fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { "REX4: DELEGATE's slot 1 original_value should be 99 (its own), not 42 (DELEGATOR's)" ); } - diff --git a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs index 61f2455c7..83bdcc404 100644 --- a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs +++ b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs @@ -705,4 +705,3 @@ fn burn_gas_code(target_gas: u64) -> Bytes { code.push(STOP); Bytes::from(code) } - diff --git a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs index e46299e7e..463179592 100644 --- a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs @@ -265,4 +265,3 @@ fn test_rex4_multiple_volatile_accesses_first_wins() { "Detained limit should be anchored at first access (~25M), got {detained_limit}" ); } - diff --git a/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs index 4fdd31303..b746a8277 100644 --- a/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs @@ -261,4 +261,3 @@ fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { assert_eq!(hints[0].topic, topic, "hint topic should match constructor input"); assert_eq!(hints[0].data, Bytes::copy_from_slice(hint_data), "hint data should match"); } - diff --git a/crates/mega-evm/tests/_pending/rex4/limit_control.rs b/crates/mega-evm/tests/_pending/rex4/limit_control.rs index 71606207f..fa5d1cb1c 100644 --- a/crates/mega-evm/tests/_pending/rex4/limit_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/limit_control.rs @@ -732,4 +732,3 @@ fn test_callcode_not_intercepted() { // ============================================================================ // 6. BACKWARD COMPATIBILITY // ============================================================================ - diff --git a/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs index 4983a2355..c629ec73d 100644 --- a/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs +++ b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs @@ -685,4 +685,3 @@ fn test_stipend_not_leaked_on_frame_local_limit_exceed() { "gas_used {gas_used} is too low — STORAGE_CALL_STIPEND may have leaked to parent" ); } - diff --git a/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs b/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs index 16d38dab5..7d66746ad 100644 --- a/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs +++ b/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs @@ -253,4 +253,3 @@ fn test_rex5_reverted_first_child_flag_reset_allows_second_charge() { ); assert_eq!(data_size, intrinsic_data_size() + 2 * ACCOUNT_INFO_WRITE_SIZE); } - diff --git a/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs index 33371005f..59a154f95 100644 --- a/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs @@ -273,4 +273,3 @@ fn test_rex5_kzg_invalid_input_length_records_exact_gas_cost() { on a wrong-length KZG call (REX5={compute_gas_rex5}, REX4={compute_gas_rex4})." ); } - diff --git a/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs index 26f8dd531..2f946ee1f 100644 --- a/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs +++ b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs @@ -222,4 +222,3 @@ fn test_rex6_disabled_send_hint_is_not_metered_against_data_size() { ); assert!(hints.is_empty(), "a disabled sendHint call must not forward"); } - From e0fc624dd6a78e60369ecf17a41e2168fdf77948 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 12:04:37 +0800 Subject: [PATCH 028/201] docs: say what lands on top of the Satin EVM wrapper --- crates/mega-evm/src/evm/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index f2289d793..f0e9d6b8c 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,8 +1,8 @@ //! The Satin EVM. //! //! [`MegaEvm`] wraps op-revm's [`OpEvm`] over a [`MegaContext`] configured for the Satin spec. -//! It adds no `MegaETH` behavior yet: SALT pricing, history gas, resource limits, detention and -//! the system contracts are not here yet. +//! It adds no `MegaETH` behavior yet; SALT pricing, history gas, resource limits, detention and +//! the system contracts land on top of it. mod context; mod factory; From 1769b36874e61af5e2608dee21b5929884f225db Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 13:32:31 +0800 Subject: [PATCH 029/201] docs: make the parked-test ledger English-only and drop the internal pointers --- crates/mega-evm/tests/_pending/README.md | 232 +++++++++++------------ 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 98c18cf81..0dfd535f5 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -1,9 +1,9 @@ # Pending tests Tests of the legacy engine that survive into Satin but cannot run until the mechanism that owns them lands. -The dispositions come from the test inventory of the Satin work order and were applied mechanically when the Satin skeleton replaced the legacy core. -Every test the inventory marks 仅 legacy (legacy-only) or 废弃 (retired) was deleted; every other test was moved here unchanged. -The decision ids (`Dnn`) refer to the Satin decision table. +The dispositions come from the test inventory made for the engine rewrite and were applied mechanically when the Satin skeleton replaced the legacy core. +Every test the inventory marks `legacy-only` or `retired` was deleted; every other test is marked `keep`, `rewrite` or `undecided` and was moved here unchanged. +Decision ids (`Dnn`) index the Satin decision table, the numbered list of design decisions behind this engine; it is published with the engine's specification. ## How this directory is excluded from the build @@ -14,7 +14,7 @@ Do not add a `_pending/main.rs`. ## Rules for porting - Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. -- 保留 (keep) rows keep their scenario and expectation; 重写 (rewrite) rows keep the scenario and take the new expectation from the cited decision; 待定 (undecided) rows wait for their decision. +- `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. - Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. - Files under `mutation/` are machine-generated mutant killers; the test gates regenerate them against the Satin sources instead of porting them by hand. - Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. @@ -23,7 +23,7 @@ Do not add a `_pending/main.rs`. ## Tests per owning mechanism -| Owning mechanism | Tests | From `tests/` | From `src/` | 保留 | 重写 | 待定 | +| Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the test gates | 21 | 21 | 0 | 21 | 0 | 0 | | the common execution layer | 41 | 19 | 22 | 22 | 19 | 0 | @@ -78,114 +78,114 @@ Each cell lists `disposition count (mechanism · decision)`. | File | Tests | Owners | |---|---:|---| -| `block_executor/accessed_block_hashes.rs` | 1 | 保留 1 (the block executor) | -| `block_executor/block_limits.rs` | 14 | 保留 12 (the block executor · D47); 待定 2 (the state-growth and KV limits · D46) | -| `block_executor/canonical_schedule.rs` | 1 | 重写 1 (the block executor · single Satin fork; the specification pages own the doc side) | -| `block_executor/deposit_da_exemption.rs` | 4 | 保留 4 (the block executor · D23) | -| `block_executor/inspector.rs` | 3 | 保留 1 (inspector support); 重写 2 (inspector support · D39/D41) | -| `block_executor/sequencer_registry.rs` | 8 | 保留 8 (system contract deployment) | -| `block_executor/trait_factory_runtime_limits.rs` | 4 | 重写 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | -| `compute_gas/claims.rs` | 14 | 保留 2 (the system contract interceptors); 重写 2 (compute gas · D53 (compute = regular spent; state spill excluded)); 保留 1 (the Satin gas table · D04 (KZG 100k)); 待定 5 (— · no D-id: preload-warm addresses charged cold (precompile / beneficiary / access-list) is absent from DECISIONS.md); 重写 2 (the Satin gas table · D13); 重写 1 (the Satin gas table · D11); 重写 1 (the data-size limit · D33/D48) | -| `compute_gas/main.rs` | 1 | 重写 1 (compute gas · D53) | -| `equivalence/evm_state.rs` | 3 | 保留 3 (the common execution layer) | -| `mini_rex/access_beneficiary_balance.rs` | 10 | 保留 9 (detention · D08); 重写 1 (revert-class aborts · D48) | -| `mini_rex/block_env_access_tracking.rs` | 3 | 保留 3 (detention) | -| `mini_rex/block_env_gas_limit.rs` | 16 | 保留 13 (detention · D08 cap 20M/1M unchanged); 重写 3 (revert-class aborts · D48 (detention halt -> revert-class)) | -| `mini_rex/compute_gas_limit.rs` | 25 | 重写 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); 重写 2 (detention · D48) | -| `mini_rex/contract_size_limit.rs` | 12 | 重写 12 (the Satin gas table · D04 (512 KiB kept; initcode bound under Osaka/EIP-3860 not pinned in DECISIONS.md)) | -| `mini_rex/db_error.rs` | 4 | 保留 4 (the common execution layer) | -| `mini_rex/gas.rs` | 26 | 重写 14 (SALT pricing · D12 (state gas x m via pricing hook)); 重写 6 (SALT pricing · D12/D13); 待定 2 (— · no D-id: 98/100 forwarding; D1 §2.5 says frame semantics follow 8037 (63/64) but DECISIONS.md is silent); 重写 4 (the Satin gas table · D11/D55 (7976 floor)) | -| `mini_rex/mega_system_transaction.rs` | 15 | 保留 15 (the system contract interceptors · D51) | -| `mini_rex/oracle.rs` | 13 | 重写 3 (revert-class aborts · D48); 保留 5 (detention); 保留 4 (the oracle and control contracts); 重写 1 (system contract deployment · deploy at Satin activation) | -| `mini_rex/state_growth_limit.rs` | 4 | 重写 4 (the state-growth and KV limits · D45 (state-gas limit)) | -| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | 保留 18 (the data-size limit · data-size numbers unchanged); 重写 4 (revert-class aborts · D48); 待定 6 (the state-growth and KV limits · D46 (count kept as output per R1b; limit semantics undecided)) | -| `mutation/access_evm.rs` | 10 | 保留 6 (detention · the test gates regenerate); 保留 2 (SALT pricing · the test gates regenerate); 保留 1 (the block executor · the test gates regenerate); 重写 1 (the Satin gas table · D11) | -| `mutation/block.rs` | 22 | 保留 14 (the block executor · the test gates regenerate); 重写 5 (the block executor · single spec / Satin schedule); 待定 1 (the state-growth and KV limits · D46); 重写 1 (compute gas · D53); 重写 1 (the state-growth and KV limits · D45) | -| `mutation/constants.rs` | 4 | 重写 2 (the Satin gas table · D04); 保留 2 (the data-size limit · 13,107,200 unchanged) | -| `mutation/external_exec.rs` | 8 | 保留 2 (the block executor · the test gates regenerate); 保留 6 (SALT pricing · the test gates regenerate) | -| `rex/oracle.rs` | 3 | 重写 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex/storage_gas.rs` | 15 | 重写 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | -| `rex2/keyless_deploy.rs` | 37 | 重写 13 (native keyless deployment · D1 §2.6 native CREATE sub-frame; D37/D38); 保留 19 (native keyless deployment · validation rules 1-9 unchanged); 保留 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); 重写 3 (native keyless deployment · D36); 重写 1 (system contract deployment · deploy at Satin activation) | -| `rex2/oracle_hint.rs` | 6 | 保留 6 (the oracle and control contracts) | -| `rex3/keyless_deploy.rs` | 2 | 重写 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | -| `rex3/oracle_gas_limit.rs` | 8 | 保留 7 (detention · D08); 重写 1 (revert-class aborts · D48) | -| `rex3/system_address.rs` | 2 | 保留 2 (detention · D51) | -| `rex4/access_control.rs` | 48 | 保留 46 (the oracle and control contracts); 重写 2 (detention · D07 (rejected volatile read pays static gas)) | -| `rex4/beneficiary_detention.rs` | 13 | 保留 12 (detention · D08); 重写 1 (revert-class aborts · D48) | -| `rex4/create_safety.rs` | 1 | 保留 1 (the test gates · canonical revm behaviour (differential harness)) | -| `rex4/deployment.rs` | 2 | 重写 2 (system contract deployment · deploy at Satin activation) | -| `rex4/eip7702_delegation_cycle.rs` | 9 | 保留 8 (SALT pricing · account inspection on the pricing path); 保留 1 (the common execution layer) | -| `rex4/frame_limits.rs` | 20 | 保留 10 (the data-size limit · data-size per-frame 98% kept); 重写 1 (revert-class aborts · D48); 待定 9 (the state-growth and KV limits · D46) | -| `rex4/gas_detention.rs` | 5 | 保留 3 (detention); 重写 2 (revert-class aborts · D48/D53) | -| `rex4/intrinsic_limit_bypass.rs` | 13 | 重写 6 (the data-size limit · D48/D49 (overflow outcome shape)); 待定 3 (the state-growth and KV limits · D46); 保留 3 (the data-size limit); 重写 1 (inspector support · D41) | -| `rex4/keyless_deploy.rs` | 2 | 保留 2 (native keyless deployment · native sub-frame inherits env) | -| `rex4/limit_control.rs` | 14 | 重写 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); 保留 5 (the system contract interceptors) | -| `rex4/storage_call_stipend.rs` | 12 | 重写 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | -| `rex5/apply_pending_changes_gas_budget.rs` | 4 | 重写 4 (the pre-block system calls · D51 (system source m = 1; F1b reservoir split)) | -| `rex5/call_too_deep_guard.rs` | 4 | 保留 4 (the system contract interceptors · the synthetic-result contract of the common execution layer) | -| `rex5/callcode_storage_gas.rs` | 6 | 重写 3 (SALT pricing · D12); 保留 3 (SALT pricing · pricing-failure propagation) | -| `rex5/create2_empty_initcode.rs` | 5 | 保留 5 (the test gates · canonical revm behaviour (differential harness)) | -| `rex5/create2_resize_gas_metering.rs` | 2 | 保留 2 (the test gates · canonical behaviour) | -| `rex5/db_error.rs` | 4 | 重写 3 (native keyless deployment · native path surfaces DB errors); 保留 1 (the system contract interceptors) | -| `rex5/deposit_caller_accounting.rs` | 7 | 重写 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | -| `rex5/deposit_create_storage_gas.rs` | 4 | 重写 4 (SALT pricing · D12/D37) | -| `rex5/eip7702_metering.rs` | 4 | 重写 4 (SALT pricing · D12/D45) | -| `rex5/eip7702_state_growth.rs` | 8 | 重写 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/frame_target_updated_dedup.rs` | 5 | 重写 5 (the common execution layer · D50/D56 write-record layer) | -| `rex5/gas_validation.rs` | 4 | 重写 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | -| `rex5/interceptor_selector_probe.rs` | 6 | 保留 6 (the system contract interceptors) | -| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | 保留 3 (the system contract interceptors) | -| `rex5/keyless_empty_code_logs.rs` | 2 | 重写 2 (native keyless deployment · native sub-frame keeps logs inherently) | -| `rex5/keyless_fee_free.rs` | 12 | 重写 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); 保留 4 (native keyless deployment · rules unchanged) | -| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | 重写 3 (native keyless deployment · native sub-frame gas handling) | -| `rex5/keyless_replay_barrier.rs` | 3 | 重写 3 (native keyless deployment · D36 (real nonce increment)) | -| `rex5/oracle_hint_metering.rs` | 9 | 保留 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); 重写 1 (the oracle and control contracts · D11 intrinsic number); 重写 1 (revert-class aborts · D48) | -| `rex5/pre_block_system_calls.rs` | 11 | 保留 11 (the pre-block system calls) | -| `rex5/precompile_compute_gas.rs` | 3 | 重写 3 (the Satin gas table · D04/D40 (assert via gas_used)) | -| `rex5/sandbox_accounting.rs` | 9 | 重写 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | -| `rex5/selfdestruct_beneficiary.rs` | 7 | 重写 4 (the state-growth and KV limits · D45 (state gas via new-account site)); 保留 2 (detention); 保留 1 (the data-size limit) | -| `rex5/sstore_storage_gas_error.rs` | 1 | 保留 1 (SALT pricing · pricing-failure path) | -| `rex5/stipend_accounting.rs` | 6 | 重写 6 (history gas · D14 (history-only allowance lifecycle)) | -| `rex5/system_tx_replay.rs` | 12 | 保留 12 (the system contract interceptors) | -| `rex6/beneficiary_detention.rs` | 16 | 保留 13 (detention · D08); 保留 2 (the data-size limit · D50 write record 40 B); 重写 1 (the state-growth and KV limits · D45) | -| `rex6/create2_metering_order.rs` | 11 | 保留 11 (the test gates · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/create_frame_accounting.rs` | 3 | 重写 2 (the common execution layer · D50/D56 write-record layer); 保留 1 (SALT pricing) | -| `rex6/eip7702_authority_accounting.rs` | 18 | 重写 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | -| `rex6/error_paths.rs` | 4 | 保留 2 (SALT pricing); 保留 2 (the test gates · canonical) | -| `rex6/fee_reward_accounting.rs` | 6 | 重写 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | -| `rex6/frame_local_accounting.rs` | 3 | 保留 3 (the data-size limit · LOG base 32 unchanged) | -| `rex6/keyless_sandbox_hardening.rs` | 3 | 重写 1 (native keyless deployment · D44 / EIP-6780 native); 保留 2 (native keyless deployment · canonical CREATE rules) | -| `rex6/oracle_hint_volatile_access.rs` | 4 | 保留 4 (the oracle and control contracts) | -| `rex6/self_transfer_account_dedup.rs` | 5 | 重写 4 (the common execution layer · D50/D56); 保留 1 (the data-size limit) | -| `rex6/sequencer_registry_rotation.rs` | 6 | 保留 5 (system contract deployment); 保留 1 (the block executor · params validation at load) | -| `rex6/system_tx_metering_exemption.rs` | 3 | 重写 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | -| `src/access/volatile.rs` | 4 | 保留 4 (detention) | -| `src/block/chain.rs` | 5 | 重写 4 (the block executor · Satin activation timestamps; fallback pin = Satin); 保留 1 (the block executor) | -| `src/block/eips.rs` | 1 | 保留 1 (the block executor) | -| `src/block/hardfork.rs` | 12 | 重写 3 (the block executor · single fork); 保留 9 (the block executor) | -| `src/block/helpers.rs` | 3 | 保留 3 (the block executor) | -| `src/block/limit.rs` | 5 | 保留 5 (the block executor) | -| `src/block/result.rs` | 2 | 重写 2 (the block executor · D48 (error shape)) | -| `src/evm/context.rs` | 1 | 保留 1 (SALT pricing · SALT pricing for the SALT cache test) | -| `src/evm/factory.rs` | 1 | 重写 1 (the Satin gas table · no behaviour projection) | -| `src/evm/host.rs` | 11 | 保留 10 (the common execution layer · Host observation layer (D33) on the revm 40 journal); 保留 1 (SALT pricing) | -| `src/evm/mod.rs` | 5 | 保留 3 (the pre-block system calls); 保留 1 (the block executor); 保留 1 (the common execution layer) | -| `src/evm/precompiles.rs` | 6 | 保留 6 (the Satin gas table · D04) | -| `src/evm/result.rs` | 4 | 重写 4 (the common execution layer · D17/D48 (halt-reason set changes)) | -| `src/evm/state.rs` | 1 | 保留 1 (the block executor) | -| `src/external/gas.rs` | 9 | 重写 9 (SALT pricing · D12/D51) | -| `src/limit/compute_gas.rs` | 1 | 重写 1 (detention · D40/D48) | -| `src/limit/data_size.rs` | 2 | 保留 2 (the data-size limit) | -| `src/limit/frame_limit.rs` | 4 | 重写 4 (the common execution layer · data-size-only per-frame tracker) | -| `src/limit/kv_update.rs` | 1 | 待定 1 (the state-growth and KV limits · D46) | -| `src/limit/limit.rs` | 4 | 保留 4 (history gas · D51) | -| `src/limit/mod.rs` | 3 | 保留 3 (the common execution layer) | -| `src/sandbox/execution.rs` | 2 | 保留 1 (native keyless deployment · rule); 重写 1 (native keyless deployment · D16) | -| `src/system/control.rs` | 8 | 保留 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | -| `src/system/deploy.rs` | 4 | 保留 3 (system contract deployment); 重写 1 (system contract deployment · single version) | -| `src/system/intercept.rs` | 2 | 保留 2 (the system contract interceptors) | -| `src/system/keyless_deploy.rs` | 2 | 保留 2 (system contract deployment) | -| `src/system/limit_control.rs` | 5 | 保留 5 (system contract deployment) | -| `src/system/oracle.rs` | 7 | 保留 7 (system contract deployment · v2.0.0 only) | -| `src/system/sequencer_registry.rs` | 24 | 保留 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | -| `src/system/tx.rs` | 6 | 保留 6 (the system contract interceptors · D51) | +| `block_executor/accessed_block_hashes.rs` | 1 | keep 1 (the block executor) | +| `block_executor/block_limits.rs` | 14 | keep 12 (the block executor · D47); undecided 2 (the state-growth and KV limits · D46) | +| `block_executor/canonical_schedule.rs` | 1 | rewrite 1 (the block executor · single Satin fork; the specification pages own the doc side) | +| `block_executor/deposit_da_exemption.rs` | 4 | keep 4 (the block executor · D23) | +| `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | +| `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | +| `block_executor/trait_factory_runtime_limits.rs` | 4 | rewrite 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | +| `compute_gas/claims.rs` | 14 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); keep 1 (the Satin gas table · D04 (KZG 100k)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 2 (the Satin gas table · D13); rewrite 1 (the Satin gas table · D11); rewrite 1 (the data-size limit · D33/D48) | +| `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | +| `equivalence/evm_state.rs` | 3 | keep 3 (the common execution layer) | +| `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | +| `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | +| `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | +| `mini_rex/contract_size_limit.rs` | 12 | rewrite 12 (the Satin gas table · D04 (512 KiB kept; the decision table does not pin the initcode bound under Osaka/EIP-3860)) | +| `mini_rex/db_error.rs` | 4 | keep 4 (the common execution layer) | +| `mini_rex/gas.rs` | 26 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)); rewrite 4 (the Satin gas table · D11/D55 (7976 floor)) | +| `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | +| `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | +| `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | +| `mutation/access_evm.rs` | 10 | keep 6 (detention · the test gates regenerate); keep 2 (SALT pricing · the test gates regenerate); keep 1 (the block executor · the test gates regenerate); rewrite 1 (the Satin gas table · D11) | +| `mutation/block.rs` | 22 | keep 14 (the block executor · the test gates regenerate); rewrite 5 (the block executor · single spec / Satin schedule); undecided 1 (the state-growth and KV limits · D46); rewrite 1 (compute gas · D53); rewrite 1 (the state-growth and KV limits · D45) | +| `mutation/constants.rs` | 4 | rewrite 2 (the Satin gas table · D04); keep 2 (the data-size limit · 13,107,200 unchanged) | +| `mutation/external_exec.rs` | 8 | keep 2 (the block executor · the test gates regenerate); keep 6 (SALT pricing · the test gates regenerate) | +| `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | +| `rex/storage_gas.rs` | 15 | rewrite 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | +| `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | +| `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | +| `rex3/keyless_deploy.rs` | 2 | rewrite 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | +| `rex3/oracle_gas_limit.rs` | 8 | keep 7 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | +| `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | +| `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `rex4/create_safety.rs` | 1 | keep 1 (the test gates · canonical revm behaviour (differential harness)) | +| `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | +| `rex4/eip7702_delegation_cycle.rs` | 9 | keep 8 (SALT pricing · account inspection on the pricing path); keep 1 (the common execution layer) | +| `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | +| `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | +| `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | +| `rex4/keyless_deploy.rs` | 2 | keep 2 (native keyless deployment · native sub-frame inherits env) | +| `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | +| `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | +| `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | +| `rex5/call_too_deep_guard.rs` | 4 | keep 4 (the system contract interceptors · the synthetic-result contract of the common execution layer) | +| `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | +| `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the test gates · canonical revm behaviour (differential harness)) | +| `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the test gates · canonical behaviour) | +| `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | +| `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | +| `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | +| `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | +| `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | +| `rex5/frame_target_updated_dedup.rs` | 5 | rewrite 5 (the common execution layer · D50/D56 write-record layer) | +| `rex5/gas_validation.rs` | 4 | rewrite 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | +| `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | +| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | +| `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | +| `rex5/keyless_fee_free.rs` | 12 | rewrite 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); keep 4 (native keyless deployment · rules unchanged) | +| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | rewrite 3 (native keyless deployment · native sub-frame gas handling) | +| `rex5/keyless_replay_barrier.rs` | 3 | rewrite 3 (native keyless deployment · D36 (real nonce increment)) | +| `rex5/oracle_hint_metering.rs` | 9 | keep 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); rewrite 1 (the oracle and control contracts · D11 intrinsic number); rewrite 1 (revert-class aborts · D48) | +| `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | +| `rex5/precompile_compute_gas.rs` | 3 | rewrite 3 (the Satin gas table · D04/D40 (assert via gas_used)) | +| `rex5/sandbox_accounting.rs` | 9 | rewrite 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | +| `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | +| `rex5/sstore_storage_gas_error.rs` | 1 | keep 1 (SALT pricing · pricing-failure path) | +| `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | +| `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | +| `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | +| `rex6/create2_metering_order.rs` | 11 | keep 11 (the test gates · canonical halt reasons; D04 512 KiB boundary) | +| `rex6/create_frame_accounting.rs` | 3 | rewrite 2 (the common execution layer · D50/D56 write-record layer); keep 1 (SALT pricing) | +| `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | +| `rex6/error_paths.rs` | 4 | keep 2 (SALT pricing); keep 2 (the test gates · canonical) | +| `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | +| `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | +| `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | +| `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | +| `rex6/self_transfer_account_dedup.rs` | 5 | rewrite 4 (the common execution layer · D50/D56); keep 1 (the data-size limit) | +| `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | +| `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | +| `src/access/volatile.rs` | 4 | keep 4 (detention) | +| `src/block/chain.rs` | 5 | rewrite 4 (the block executor · Satin activation timestamps; fallback pin = Satin); keep 1 (the block executor) | +| `src/block/eips.rs` | 1 | keep 1 (the block executor) | +| `src/block/hardfork.rs` | 12 | rewrite 3 (the block executor · single fork); keep 9 (the block executor) | +| `src/block/helpers.rs` | 3 | keep 3 (the block executor) | +| `src/block/limit.rs` | 5 | keep 5 (the block executor) | +| `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | +| `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | +| `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | +| `src/evm/host.rs` | 11 | keep 10 (the common execution layer · Host observation layer (D33) on the revm 40 journal); keep 1 (SALT pricing) | +| `src/evm/mod.rs` | 5 | keep 3 (the pre-block system calls); keep 1 (the block executor); keep 1 (the common execution layer) | +| `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | +| `src/evm/result.rs` | 4 | rewrite 4 (the common execution layer · D17/D48 (halt-reason set changes)) | +| `src/evm/state.rs` | 1 | keep 1 (the block executor) | +| `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | +| `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | +| `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | +| `src/limit/frame_limit.rs` | 4 | rewrite 4 (the common execution layer · data-size-only per-frame tracker) | +| `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | +| `src/limit/limit.rs` | 4 | keep 4 (history gas · D51) | +| `src/limit/mod.rs` | 3 | keep 3 (the common execution layer) | +| `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | +| `src/system/control.rs` | 8 | keep 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | +| `src/system/deploy.rs` | 4 | keep 3 (system contract deployment); rewrite 1 (system contract deployment · single version) | +| `src/system/intercept.rs` | 2 | keep 2 (the system contract interceptors) | +| `src/system/keyless_deploy.rs` | 2 | keep 2 (system contract deployment) | +| `src/system/limit_control.rs` | 5 | keep 5 (system contract deployment) | +| `src/system/oracle.rs` | 7 | keep 7 (system contract deployment · v2.0.0 only) | +| `src/system/sequencer_registry.rs` | 24 | keep 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/tx.rs` | 6 | keep 6 (the system contract interceptors · D51) | From 04a16eec1f52b5139c971b27aab3bf9f59e03ae8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 13:39:23 +0800 Subject: [PATCH 030/201] docs: reword two comments that point at later changes --- crates/mega-evm/src/evm/context.rs | 2 +- crates/mega-evm/tests/satin/equivalence.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 25dc4c259..6f84b10e2 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -31,7 +31,7 @@ pub(crate) type MegaInnerContext = /// written together, only through [`MegaContext::with_cfg`], so they cannot drift apart. /// /// Every [`Host`](revm::interpreter::Host) method and every context accessor delegates to the -/// wrapped context; later tickets override the ones `MegaETH` prices or meters differently. +/// wrapped context; later changes override the ones `MegaETH` prices or meters differently. #[derive(Debug)] pub struct MegaContext { inner: MegaInnerContext, diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 67dae6bae..fce269ed5 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -2,7 +2,7 @@ //! //! The same transaction on the same `CfgEnv`, block and L1 info must produce the same result //! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and -//! the resulting state. Once later tickets add `MegaETH` behavior (SALT pricing, history gas, +//! the resulting state. Once later changes add `MegaETH` behavior (SALT pricing, history gas, //! limits), these cases stay the baseline that shows where the two diverge on purpose. use alloy_op_evm::OpTx; From 6953c3994495f2a9fb8374bda6214439ab158dca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:02:04 +0800 Subject: [PATCH 031/201] test: add the JSON transaction scenario format and its MegaEvm runner --- AGENTS.md | 2 +- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/scenario.rs | 396 +++++++++++++++++++++ 3 files changed, 399 insertions(+), 1 deletion(-) create mode 100644 crates/mega-evm/src/test_utils/scenario.rs diff --git a/AGENTS.md b/AGENTS.md index c2051e1a8..4fafe413f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | | `types.rs` | transaction, halt reason, error and envelope aliases | the common execution layer | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact` | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 3e6f7c544..cd9b7c74e 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -5,9 +5,11 @@ mod database; mod evm; mod inspectors; mod opcode_gen; +mod scenario; pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; pub use opcode_gen::*; +pub use scenario::*; diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs new file mode 100644 index 000000000..f69878d6f --- /dev/null +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -0,0 +1,396 @@ +//! Transaction scenarios: a pre-state and a sequence of transactions, read from JSON. +//! +//! A [`Scenario`] is the input format of the differential harness (`crates/mega-differential`), +//! which runs every scenario through [`MegaEvm`] and through an independent EVM and compares the +//! two. The benches run slices of the same corpus, so their instruction counts move when the +//! semantics or the pricing of those scenarios move. +//! +//! The block, the configuration and the L1 fees are fixed, so a scenario is fully described by +//! its accounts and transactions: +//! +//! - the block is [`Scenario::block`]: number 1, timestamp 1, the scenario's coinbase, zero base +//! fee, unlimited gas; +//! - the configuration is what [`MegaContext`] fixes for the spec; +//! - the L1 fees are zero ([`zero_fee_l1_block_info`], [`op_transaction`]), and so is the gas +//! price, so the callers need no balance beyond the value they send. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{collections::BTreeMap, format, string::String, vec::Vec}; + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use core::convert::Infallible; +use revm::{ + context::{ + result::{EVMError, ResultAndState}, + transaction::{ + AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization, + }, + BlockEnv, TxEnv, + }, + Database, DatabaseCommit, +}; +use serde::Deserialize; + +use crate::{ + test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionError, +}; + +/// The outcome of one scenario transaction on [`MegaEvm`]. +pub type ScenarioTxOutcome = + Result, EVMError>; + +/// A pre-state and the transactions to run on it, in order. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Scenario { + /// Name of the scenario; the harness reports differences under it. + pub name: String, + /// The block beneficiary. + #[serde(default)] + pub coinbase: Address, + /// The accounts that exist before the first transaction. + pub pre: BTreeMap, + /// The transactions, run in order, each on the state the previous one left. + pub txs: Vec, +} + +/// An account of the pre-state. +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PreAccount { + /// Account nonce. + #[serde(default)] + pub nonce: u64, + /// Account balance. + #[serde(default)] + pub balance: U256, + /// Legacy bytecode; empty for an account without code. + #[serde(default)] + pub code: Bytes, + /// Storage slots. + #[serde(default)] + pub storage: BTreeMap, +} + +/// How a scenario transaction is run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TxSpecKind { + /// A message call to `to`. + #[default] + Call, + /// A contract-creation transaction with `data` as init code. + Create, + /// A system call to `to`, as a block executor makes one: no fee, no nonce, the engine's + /// system-call gas limit. + SystemCall, +} + +/// A scenario transaction. +/// +/// The nonce is the caller's nonce in the state the transaction runs on. The transaction type +/// follows from the lists: EIP-7702 with an authorization list, EIP-2930 with only an access +/// list, legacy otherwise. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TxSpec { + /// Sender. + pub caller: Address, + /// Target of a call or a system call; absent for a create. + #[serde(default)] + pub to: Option
, + /// Calldata, or init code for a create. + #[serde(default)] + pub data: Bytes, + /// Value sent. + #[serde(default)] + pub value: U256, + /// Gas limit. Required for calls and creates; a system call runs with the engine's + /// system-call gas limit and must not set one. + #[serde(default)] + pub gas_limit: Option, + /// How the transaction is run. + #[serde(default)] + pub kind: TxSpecKind, + /// EIP-2930 access list. + #[serde(default)] + pub access_list: Vec, + /// EIP-7702 authorization list. + #[serde(default)] + pub authorization_list: Vec, +} + +/// An EIP-2930 access list entry. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AccessListEntry { + /// Address to warm. + pub address: Address, + /// Storage keys of `address` to warm. + #[serde(default)] + pub storage_keys: Vec, +} + +/// An EIP-7702 authorization with its signer already recovered. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuthorizationEntry { + /// Chain id the authorization is valid on; zero for any chain. + #[serde(default)] + pub chain_id: U256, + /// Address the authority delegates to. + pub address: Address, + /// Nonce the authority must have. + pub nonce: u64, + /// The recovered signer; absent for a signature that does not recover. + #[serde(default)] + pub authority: Option
, +} + +impl Scenario { + /// Checks the fields that depend on the transaction kind. + pub fn validate(&self) -> Result<(), String> { + for (i, tx) in self.txs.iter().enumerate() { + let problem = match tx.kind { + TxSpecKind::Call if tx.to.is_none() => Some("a call needs `to`"), + TxSpecKind::Create if tx.to.is_some() => Some("a create must not set `to`"), + TxSpecKind::Create if !tx.authorization_list.is_empty() => { + Some("an EIP-7702 transaction cannot create") + } + TxSpecKind::Call | TxSpecKind::Create if tx.gas_limit.is_none() => { + Some("a call or a create needs `gas_limit`") + } + TxSpecKind::SystemCall if tx.to.is_none() => Some("a system call needs `to`"), + TxSpecKind::SystemCall + if tx.gas_limit.is_some() || + !tx.value.is_zero() || + !tx.access_list.is_empty() || + !tx.authorization_list.is_empty() => + { + Some("a system call takes only `caller`, `to` and `data`") + } + _ => None, + }; + if let Some(problem) = problem { + return Err(format!("{}: tx[{i}]: {problem}", self.name)); + } + } + Ok(()) + } + + /// The pre-state as a database. + pub fn database(&self) -> MemoryDatabase { + let mut db = MemoryDatabase::default(); + for (address, account) in &self.pre { + db.set_account_nonce(*address, account.nonce); + db.set_account_balance(*address, account.balance); + if !account.code.is_empty() { + db.set_account_code(*address, account.code.clone()); + } + for (slot, value) in &account.storage { + db.set_account_storage(*address, *slot, *value); + } + } + db + } + + /// The block every transaction of the scenario runs in. + pub fn block(&self) -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1), + beneficiary: self.coinbase, + basefee: 0, + gas_limit: u64::MAX, + ..Default::default() + } + } + + /// Runs every transaction on a fresh [`MegaEvm`] over `db`, committing the state of each + /// successful one before the next. Returns the outcomes in order and the final database. + pub fn run(&self, mut db: MemoryDatabase) -> (Vec, MemoryDatabase) { + let mut outcomes = Vec::with_capacity(self.txs.len()); + for tx in &self.txs { + let ctx = MegaContext::new(&mut db, MegaSpecId::SATIN) + .with_block(self.block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + let outcome = match tx.kind { + TxSpecKind::SystemCall => evm.transact_system_call( + tx.caller, + tx.to.expect("validated: a system call has a target"), + tx.data.clone(), + ), + TxSpecKind::Call | TxSpecKind::Create => { + let nonce = evm.db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); + evm.transact_raw(OpTx(op_transaction(tx.tx_env(nonce)))) + } + }; + drop(evm); + if let Ok(outcome) = &outcome { + db.commit(outcome.state.clone()); + } + outcomes.push(outcome); + } + (outcomes, db) + } +} + +impl TxSpec { + /// The EIP-2718 transaction type the lists imply. + pub fn tx_type(&self) -> u8 { + if !self.authorization_list.is_empty() { + 4 + } else if !self.access_list.is_empty() { + 1 + } else { + 0 + } + } + + /// The transaction as the EVM executes it, with `nonce` as the sender's nonce. + /// + /// Only meaningful for calls and creates; a system call is built by the engine. + pub fn tx_env(&self, nonce: u64) -> TxEnv { + let access_list = AccessList( + self.access_list + .iter() + .map(|entry| AccessListItem { + address: entry.address, + storage_keys: entry.storage_keys.iter().map(|key| (*key).into()).collect(), + }) + .collect(), + ); + let authorizations = self + .authorization_list + .iter() + .map(|entry| { + RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: entry.chain_id, + address: entry.address, + nonce: entry.nonce, + }, + entry.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + ) + }) + .collect(); + TxEnv::builder() + .tx_type(Some(self.tx_type())) + .caller(self.caller) + .kind(self.to.map_or(TxKind::Create, TxKind::Call)) + .data(self.data.clone()) + .value(self.value) + .gas_limit(self.gas_limit.unwrap_or_default()) + .gas_price(0) + .gas_priority_fee((self.tx_type() == 4).then_some(0)) + .nonce(nonce) + .access_list(access_list) + .authorization_list_recovered(authorizations) + .build_fill() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::BytecodeBuilder; + use alloy_primitives::address; + + const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); + const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); + + fn call(gas_limit: Option) -> TxSpec { + TxSpec { + caller: CALLER, + to: Some(CALLEE), + data: Bytes::new(), + value: U256::ZERO, + gas_limit, + kind: TxSpecKind::Call, + access_list: Vec::new(), + authorization_list: Vec::new(), + } + } + + fn scenario(txs: Vec) -> Scenario { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)).stop().build(); + Scenario { + name: "sstore".into(), + coinbase: Address::ZERO, + pre: [ + (CALLER, PreAccount { balance: U256::from(10), ..Default::default() }), + (CALLEE, PreAccount { nonce: 1, code, ..Default::default() }), + ] + .into_iter() + .collect(), + txs, + } + } + + #[test] + fn test_validate_rejects_a_call_without_gas_limit() { + assert!(scenario(vec![call(Some(100_000))]).validate().is_ok()); + let err = scenario(vec![call(None)]).validate().unwrap_err(); + assert_eq!(err, "sstore: tx[0]: a call or a create needs `gas_limit`"); + } + + #[test] + fn test_validate_rejects_a_system_call_with_gas_limit() { + let tx = TxSpec { kind: TxSpecKind::SystemCall, ..call(Some(100_000)) }; + let err = scenario(vec![tx]).validate().unwrap_err(); + assert_eq!(err, "sstore: tx[0]: a system call takes only `caller`, `to` and `data`"); + } + + /// Each transaction runs on the state the previous one committed, with the caller's + /// current nonce. + #[test] + fn test_run_commits_each_transaction_before_the_next() { + let scenario = scenario(vec![call(Some(100_000)), call(Some(100_000))]); + let (outcomes, mut db) = scenario.run(scenario.database()); + + assert_eq!(outcomes.len(), 2); + assert!(outcomes.iter().all(|outcome| outcome.as_ref().unwrap().result.is_success())); + assert_eq!(db.basic(CALLER).unwrap().unwrap().nonce, 2); + assert_eq!(db.storage(CALLEE, U256::ZERO).unwrap(), U256::from(7)); + } + + #[test] + fn test_tx_type_follows_the_lists() { + let mut tx = call(Some(100_000)); + assert_eq!(tx.tx_env(0).tx_type, 0); + tx.access_list.push(AccessListEntry { address: CALLEE, storage_keys: vec![U256::ZERO] }); + assert_eq!(tx.tx_env(0).tx_type, 1); + tx.authorization_list.push(AuthorizationEntry { + chain_id: U256::ZERO, + address: CALLEE, + nonce: 0, + authority: None, + }); + let env = tx.tx_env(3); + assert_eq!((env.tx_type, env.nonce, env.gas_priority_fee), (4, 3, Some(0))); + } + + #[test] + fn test_scenario_parses_from_json() { + let json = r#"{ + "name": "transfer", + "pre": { "0x0000000000000000000000000000000000000aaa": { "balance": "0x10" } }, + "txs": [{ + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "value": "0x1", + "gas_limit": 21000, + "access_list": [{ "address": "0x0000000000000000000000000000000000000bbb", "storage_keys": ["0x1"] }] + }] + }"#; + let scenario: Scenario = serde_json::from_str(json).unwrap(); + assert_eq!(scenario.pre[&CALLER].balance, U256::from(16)); + assert_eq!(scenario.txs[0].access_list[0].storage_keys, vec![U256::from(1)]); + assert!(serde_json::from_str::(&json.replace("gas_limit", "gas")).is_err()); + } +} From c784f5c758f2c7aae998a92b109f4997ea9ff8d1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:15:35 +0800 Subject: [PATCH 032/201] test: add the differential harness against stock revm 43 --- Cargo.lock | 637 +++++++++++++++--- Cargo.toml | 4 +- crates/mega-differential/Cargo.toml | 33 + crates/mega-differential/README.md | 112 +++ crates/mega-differential/deviations.json | 35 + .../scenarios/handwritten/code_deposit.json | 28 + .../code_deposit_large_spills.json | 28 + .../handwritten/create2_success.json | 28 + .../handwritten/create_address_collision.json | 34 + .../create_initcode_revert_after_spill.json | 28 + .../create_insufficient_endowment.json | 34 + .../create_revert_inside_reverting_call.json | 34 + .../scenarios/handwritten/create_success.json | 28 + .../handwritten/create_transaction.json | 21 + ...elegatecall_refill_of_a_parent_charge.json | 34 + .../handwritten/gas_limit_above_cap.json | 28 + .../handwritten/gas_limit_below_cap.json | 28 + .../nested_call_halt_with_spill.json | 34 + .../nested_call_revert_with_spill.json | 34 + .../selfdestruct_to_new_account.json | 34 + .../sstore_refill_after_spill.json | 28 + .../sstore_refill_no_prior_spill.json | 28 + .../handwritten/sstore_set_spills.json | 28 + .../sstore_set_within_reservoir.json | 28 + .../scenarios/handwritten/system_call.json | 26 + .../handwritten/two_txs_sequential.json | 36 + .../value_call_to_new_account.json | 28 + ...l_to_new_account_insufficient_balance.json | 28 + crates/mega-differential/src/diff.rs | 184 +++++ crates/mega-differential/src/lib.rs | 192 ++++++ crates/mega-differential/src/mega.rs | 107 +++ crates/mega-differential/src/oracle.rs | 358 ++++++++++ crates/mega-differential/src/record.rs | 85 +++ crates/mega-differential/src/registry.rs | 193 ++++++ crates/mega-differential/tests/claims.rs | 107 +++ crates/mega-differential/tests/corpus.rs | 14 + 36 files changed, 2664 insertions(+), 82 deletions(-) create mode 100644 crates/mega-differential/Cargo.toml create mode 100644 crates/mega-differential/README.md create mode 100644 crates/mega-differential/deviations.json create mode 100644 crates/mega-differential/scenarios/handwritten/code_deposit.json create mode 100644 crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json create mode 100644 crates/mega-differential/scenarios/handwritten/create2_success.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_address_collision.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_success.json create mode 100644 crates/mega-differential/scenarios/handwritten/create_transaction.json create mode 100644 crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json create mode 100644 crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json create mode 100644 crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json create mode 100644 crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json create mode 100644 crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json create mode 100644 crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json create mode 100644 crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json create mode 100644 crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json create mode 100644 crates/mega-differential/scenarios/handwritten/sstore_set_spills.json create mode 100644 crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json create mode 100644 crates/mega-differential/scenarios/handwritten/system_call.json create mode 100644 crates/mega-differential/scenarios/handwritten/two_txs_sequential.json create mode 100644 crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json create mode 100644 crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json create mode 100644 crates/mega-differential/src/diff.rs create mode 100644 crates/mega-differential/src/lib.rs create mode 100644 crates/mega-differential/src/mega.rs create mode 100644 crates/mega-differential/src/oracle.rs create mode 100644 crates/mega-differential/src/record.rs create mode 100644 crates/mega-differential/src/registry.rs create mode 100644 crates/mega-differential/tests/claims.rs create mode 100644 crates/mega-differential/tests/corpus.rs diff --git a/Cargo.lock b/Cargo.lock index 19e8534c3..e5fb52b97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,7 +156,7 @@ dependencies = [ "ethereum_ssz_derive", "serde", "serde_with", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -174,7 +174,7 @@ dependencies = [ "alloy-sol-types", "auto_impl", "derive_more", - "revm", + "revm 40.0.3", "thiserror", "tracing", ] @@ -286,7 +286,7 @@ dependencies = [ "auto_impl", "op-alloy", "op-revm", - "revm", + "revm 40.0.3", "thiserror", ] @@ -312,7 +312,7 @@ dependencies = [ "cfg-if", "const-hex", "derive_more", - "foldhash", + "foldhash 0.2.0", "hashbrown 0.17.1", "indexmap 2.10.0", "itoa", @@ -709,24 +709,48 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", ] +[[package]] +name = "ark-bls12-381" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be2ede2c0c96fa37d5d3484e8a59fec566c4a52b8c84bf993eaa6c67d7225a4c" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "ark-bn254" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", - "ark-r1cs-std", + "ark-r1cs-std 0.5.0", "ark-std 0.5.0", ] +[[package]] +name = "ark-bn254" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-r1cs-std 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "ark-ec" version = "0.5.0" @@ -735,7 +759,7 @@ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", "ark-ff 0.5.0", - "ark-poly", + "ark-poly 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", "educe", @@ -748,6 +772,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", + "itertools 0.14.0", + "num-bigint", + "num-integer", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ff" version = "0.3.0" @@ -806,6 +851,23 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ff" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7a806ac6c8307b929df4645776290a50ee2aac754ad09d8bdf73391309e43af" +dependencies = [ + "ark-ff-asm 0.6.0", + "ark-ff-macros 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "digest 0.10.7", + "educe", + "num-bigint", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ff-asm" version = "0.3.0" @@ -836,6 +898,16 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "ark-ff-asm" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1479009684adc073dff49a1025d3a7065b317a9ead25aaaca38cdc70058ba8a2" +dependencies = [ + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-ff-macros" version = "0.3.0" @@ -874,6 +946,19 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "ark-ff-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-poly" version = "0.5.0" @@ -889,15 +974,30 @@ dependencies = [ "hashbrown 0.15.4", ] +[[package]] +name = "ark-poly" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", +] + [[package]] name = "ark-r1cs-std" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", - "ark-relations", + "ark-relations 0.5.1", "ark-std 0.5.0", "educe", "num-bigint", @@ -906,6 +1006,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "ark-r1cs-std" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291f1c6628bfcac79b0dc2adbe401aa9100e2e96daa971645e0b18fc94de9a98" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-relations 0.6.0", + "ark-std 0.6.0", + "educe", + "itertools 0.14.0", + "num-bigint", + "num-integer", + "num-traits", + "tracing", +] + [[package]] name = "ark-relations" version = "0.5.1" @@ -915,7 +1033,23 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber", + "tracing-subscriber 0.2.25", +] + +[[package]] +name = "ark-relations" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4c11c797a64b8a23e22bf4e77bf582ac27bb21395e3183a9a506ba2561e9f9" +dependencies = [ + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "foldhash 0.1.5", + "indexmap 2.10.0", + "tracing", + "tracing-subscriber 0.3.23", ] [[package]] @@ -945,13 +1079,26 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" dependencies = [ - "ark-serialize-derive", + "ark-serialize-derive 0.5.0", "ark-std 0.5.0", "arrayvec", "digest 0.10.7", "num-bigint", ] +[[package]] +name = "ark-serialize" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b" +dependencies = [ + "ark-serialize-derive 0.6.0", + "ark-std 0.6.0", + "digest 0.10.7", + "num-bigint", + "serde_with", +] + [[package]] name = "ark-serialize-derive" version = "0.5.0" @@ -963,6 +1110,17 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "ark-serialize-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f153690697a2b91e5e1251ff98411ee5371500a111a0fd317a70e588eb300f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "ark-std" version = "0.3.0" @@ -993,6 +1151,16 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "ark-std" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155" +dependencies = [ + "num-traits", + "rand 0.8.5", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -1246,9 +1414,9 @@ dependencies = [ [[package]] name = "c-kzg" -version = "2.1.7" +version = "2.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6648ed1e4ea8e8a1a4a2c78e1cda29a3fd500bc622899c340d8525ea9a76b24a" +checksum = "38d04308254695569fdb9bfe3bacc1c91837a670d0806605eb82d63748fbd3a6" dependencies = [ "blst", "cc", @@ -2010,6 +2178,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" @@ -2226,7 +2400,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2672,7 +2846,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -2760,6 +2934,17 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "mega-differential" +version = "2.0.0-alpha.1" +dependencies = [ + "alloy-primitives", + "mega-evm", + "revm 43.0.0", + "serde", + "serde_json", +] + [[package]] name = "mega-evm" version = "2.0.0-alpha.1" @@ -2778,7 +2963,7 @@ dependencies = [ "mega-system-contracts", "op-alloy-consensus", "op-revm", - "revm", + "revm 40.0.3", "revm-inspectors", "serde", "serde_json", @@ -2854,6 +3039,15 @@ dependencies = [ "serde", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num" version = "0.4.3" @@ -3090,7 +3284,7 @@ dependencies = [ "ethereum_ssz_derive", "op-alloy-consensus", "serde", - "sha2", + "sha2 0.10.9", "snap", "thiserror", ] @@ -3101,7 +3295,7 @@ version = "20.0.0" source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.2#260f65329f1f47b7412a1b2c1fda85453f66521c" dependencies = [ "auto_impl", - "revm", + "revm 40.0.3", "serde", ] @@ -3114,7 +3308,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -3198,7 +3392,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros", + "phf_macros 0.13.1", "phf_shared 0.13.1", "serde", ] @@ -3209,7 +3403,9 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ + "phf_macros 0.14.0", "phf_shared 0.14.0", + "serde", ] [[package]] @@ -3222,19 +3418,42 @@ dependencies = [ "phf_shared 0.13.1", ] +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + [[package]] name = "phf_macros" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator", + "phf_generator 0.13.1", "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.104", ] +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -3696,9 +3915,9 @@ dependencies = [ "bytes", "derive_more", "once_cell", - "revm-bytecode", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", "secp256k1 0.30.0", "serde", "thiserror", @@ -3733,17 +3952,36 @@ name = "revm" version = "40.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" 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", + "revm-bytecode 11.0.1", + "revm-context 18.0.3", + "revm-context-interface 19.0.3", + "revm-database 15.0.2", + "revm-database-interface 12.1.1", + "revm-handler 20.0.3", + "revm-inspector 21.0.3", + "revm-interpreter 37.0.3", + "revm-precompile 36.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", +] + +[[package]] +name = "revm" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0d1681d52ee61171b838db4924827f63d659d4c3ad559aa3a57003f3dda3f7c" +dependencies = [ + "revm-bytecode 43.0.0", + "revm-context 43.0.2", + "revm-context-interface 43.0.1", + "revm-database 43.0.0", + "revm-database-interface 43.0.0", + "revm-handler 43.0.2", + "revm-inspector 43.0.2", + "revm-interpreter 43.0.1", + "revm-precompile 43.0.2", + "revm-primitives 43.0.0", + "revm-state 43.0.0", ] [[package]] @@ -3753,7 +3991,19 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "bitvec", "phf 0.13.1", - "revm-primitives", + "revm-primitives 24.0.1", + "serde", +] + +[[package]] +name = "revm-bytecode" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d38e16b72ec1c836ec8490562bfb21003165ea8bc496086bf345680a6e6c41" +dependencies = [ + "bitvec", + "phf 0.14.0", + "revm-primitives 43.0.0", "serde", ] @@ -3765,11 +4015,28 @@ dependencies = [ "bitvec", "cfg-if", "derive-where", - "revm-bytecode", - "revm-context-interface", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context-interface 19.0.3", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-context" +version = "43.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c16835bc2ead203219a18fcc84c2c71879ad6b890e8a71150cf7f10e4e355dc4" +dependencies = [ + "bitvec", + "cfg-if", + "derive-where", + "revm-bytecode 43.0.0", + "revm-context-interface 43.0.1", + "revm-database-interface 43.0.0", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", ] @@ -3782,9 +4049,25 @@ dependencies = [ "alloy-eip7702", "auto_impl", "either", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-context-interface" +version = "43.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b4109bdceaca5ee6e27bf41f6b156f2b15892dc5bb47d3530bc4d3b3060077" +dependencies = [ + "alloy-eip2930", + "alloy-eip7702", + "auto_impl", + "either", + "revm-database-interface 43.0.0", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", ] @@ -3795,10 +4078,26 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "alloy-eips", "derive_more", - "revm-bytecode", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-database" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31d764afa9a1c9278c05d40461b07319d21ccb39c1bdf0e9dde7e5ea7d9be53d" +dependencies = [ + "alloy-eips", + "derive_more", + "either", + "revm-bytecode 43.0.0", + "revm-database-interface 43.0.0", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", ] @@ -3809,8 +4108,22 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "either", - "revm-primitives", - "revm-state", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", + "thiserror", +] + +[[package]] +name = "revm-database-interface" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2a27e4440c2ef4932afdaa28a1d1ac8601504c7030c1a387b5e307d07d864d1" +dependencies = [ + "auto_impl", + "either", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", "thiserror", ] @@ -3822,14 +4135,33 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "derive-where", - "revm-bytecode", - "revm-context", - "revm-context-interface", - "revm-database-interface", - "revm-interpreter", - "revm-precompile", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context 18.0.3", + "revm-context-interface 19.0.3", + "revm-database-interface 12.1.1", + "revm-interpreter 37.0.3", + "revm-precompile 36.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-handler" +version = "43.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73a7409031d87ec281b74efff65d7a4dbea9d80727a55dbc7e4b3fd77b5e03fb" +dependencies = [ + "auto_impl", + "derive-where", + "revm-bytecode 43.0.0", + "revm-context 43.0.2", + "revm-context-interface 43.0.1", + "revm-database-interface 43.0.0", + "revm-interpreter 43.0.1", + "revm-precompile 43.0.2", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", ] @@ -3840,12 +4172,30 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "either", - "revm-context", - "revm-database-interface", - "revm-handler", - "revm-interpreter", - "revm-primitives", - "revm-state", + "revm-context 18.0.3", + "revm-database-interface 12.1.1", + "revm-handler 20.0.3", + "revm-interpreter 37.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", + "serde_json", +] + +[[package]] +name = "revm-inspector" +version = "43.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a56f37224afd628f7244aa6965609ada04b440ed8ab7a19f55e4291df5a0112" +dependencies = [ + "auto_impl", + "either", + "revm-context 43.0.2", + "revm-database-interface 43.0.0", + "revm-handler 43.0.2", + "revm-interpreter 43.0.1", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", "serde_json", ] @@ -3862,7 +4212,7 @@ dependencies = [ "alloy-sol-types", "anstyle", "colorchoice", - "revm", + "revm 40.0.3", "serde", "serde_json", "thiserror", @@ -3873,10 +4223,23 @@ name = "revm-interpreter" version = "37.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode", - "revm-context-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context-interface 19.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-interpreter" +version = "43.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "932f7fe05a2cdeb08195dd7e88a09a4da7c3660cdc6e62720839c77ba77f65aa" +dependencies = [ + "revm-bytecode 43.0.0", + "revm-context-interface 43.0.1", + "revm-primitives 43.0.0", + "revm-state 43.0.0", "serde", ] @@ -3885,9 +4248,9 @@ name = "revm-precompile" version = "36.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "ark-bls12-381", - "ark-bn254", - "ark-ec", + "ark-bls12-381 0.5.0", + "ark-bn254 0.5.0", + "ark-ec 0.5.0", "ark-ff 0.5.0", "ark-serialize 0.5.0", "arrayref", @@ -3897,11 +4260,35 @@ dependencies = [ "cfg-if", "k256", "p256", - "revm-context-interface", - "revm-primitives", - "ripemd", + "revm-context-interface 19.0.3", + "revm-primitives 24.0.1", + "ripemd 0.1.3", "secp256k1 0.31.1", - "sha2", + "sha2 0.10.9", +] + +[[package]] +name = "revm-precompile" +version = "43.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4dc0279f2a44770faa8c93d008df684440cf573c91b8e0e39d0d581abf7b3d" +dependencies = [ + "ark-bls12-381 0.6.0", + "ark-bn254 0.6.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "arrayref", + "aurora-engine-modexp", + "c-kzg", + "cfg-if", + "k256", + "p256", + "revm-context-interface 43.0.1", + "revm-primitives 43.0.0", + "ripemd 0.2.0", + "secp256k1 0.31.1", + "sha2 0.11.0", ] [[package]] @@ -3914,6 +4301,17 @@ dependencies = [ "serde", ] +[[package]] +name = "revm-primitives" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1f4ba1a5757fe4398262290422c371556fcebf236f762f7ed7ff2c56768a63c" +dependencies = [ + "alloy-primitives", + "once_cell", + "serde", +] + [[package]] name = "revm-state" version = "12.0.1" @@ -3922,8 +4320,22 @@ dependencies = [ "alloy-eip7928", "bitflags 2.11.1", "nonmax", - "revm-bytecode", - "revm-primitives", + "revm-bytecode 11.0.1", + "revm-primitives 24.0.1", + "serde", +] + +[[package]] +name = "revm-state" +version = "43.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd02082cf1baca01e8bc17456c45136bdc66632395a98db1c1a2afe4c6ea87f" +dependencies = [ + "alloy-eip7928", + "bitflags 2.11.1", + "nonmax", + "revm-bytecode 43.0.0", + "revm-primitives 43.0.0", "serde", ] @@ -3946,6 +4358,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "ripemd" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "rlp" version = "0.5.2" @@ -4271,6 +4692,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha3" version = "0.11.0" @@ -4291,6 +4723,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -4513,6 +4954,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "threadpool" version = "1.8.1" @@ -4715,14 +5165,25 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.34" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", "valuable", ] +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.2.25" @@ -4732,6 +5193,20 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index b4502668f..de0f2e4d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,9 @@ # The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, # `crates/state-test`) still target the legacy engine; their sources are kept # untouched and each rejoins the workspace when it is ported to Satin. -members = ["crates/mega-evm", "crates/system-contracts"] +# `crates/mega-differential` is a member but not a default member: it builds stock revm 43 as the +# oracle of the differential harness, so the commands run at the root stay on the engine's graph. +members = ["crates/mega-differential", "crates/mega-evm", "crates/system-contracts"] default-members = ["crates/mega-evm"] exclude = [] diff --git a/crates/mega-differential/Cargo.toml b/crates/mega-differential/Cargo.toml new file mode 100644 index 000000000..55b8c27b9 --- /dev/null +++ b/crates/mega-differential/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "mega-differential" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +description = "Differential harness: runs transaction scenarios through MegaEvm and through revm 43, field by field" +publish = false + +[lints] +workspace = true + +[dependencies] +# alloy +alloy-primitives = { workspace = true, features = ["serde"] } + +# revm +# The oracle: stock revm 43.0.0 from crates.io. The workspace's `[patch.crates-io] revm` points at +# the fork, whose version (40.0.3) does not satisfy `=43.0.0`, so this requirement resolves to the +# registry and the two revms sit side by side in this crate only. Default features stay off so the +# oracle adds no native precompile backend (c-kzg, blst, secp256k1) to the lockfile; it runs the +# pure-Rust ones. `dev` compiles the same optional configuration fields `mega-evm` compiles on the +# fork, so the oracle copies every one of them. +revm-oracle = { package = "revm", version = "=43.0.0", default-features = false, features = ["dev", "serde", "std"] } + +# megaeth +mega-evm = { workspace = true, features = ["default", "test-utils"] } + +# misc +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true, features = ["std"] } diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md new file mode 100644 index 000000000..046f7fe05 --- /dev/null +++ b/crates/mega-differential/README.md @@ -0,0 +1,112 @@ +# mega-differential + +The differential harness of the Satin engine. +It runs every scenario of a corpus through `MegaEvm` and through stock revm 43, and compares what the two report, field by field. +Every difference must be explained by the deviation registry, and every active registry entry must explain at least one difference. + +```bash +cargo test -p mega-differential --locked +``` + +The corpus test prints one summary line, for example: + +```text +differential: 23 scenarios, 834 fields compared, 69 deviations matched (op-base-fee-vault-touch x23, …), 0 unexplained, 0 stale registry entries +``` + +## The two arms + +**Left arm: `MegaEvm`.** +Each transaction runs on a fresh `MegaEvm` over a `MegaContext` for `MegaSpecId::SATIN`, through alloy-evm's `Evm::transact_raw` (system calls through `Evm::transact_system_call`). +The configuration is the one the spec fixes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 and EIP-2780 on, the 200,000,000 execution cap, EIP-7708 and the system-call reservoir margin off. +The L1 fees are zero (`test_utils::zero_fee_l1_block_info`), every transaction is a non-deposit one with an empty envelope, and the gas price is zero. +`mega-evm` is built with its default features, so the precompiles run on the same backends as in a node. + +**Right arm: the oracle.** +Stock `revm = "=43.0.0"` from crates.io, on its mainnet handler. +Its configuration is copied from the left arm's (`oracle::cfg`): the Ethereum spec the Satin spec runs on (Osaka), the gas table entry by entry, and every switch. +The fork numbers its gas ids as upstream does and adds its own at the top of the table (`tests/claims.rs` checks both, and that the fork-only prices are zero). +If `MegaEvm` switches on a mechanism revm 43 cannot run (EIP-7708 before Amsterdam, the system-call state-gas margin), `oracle::cfg` panics: the mechanism that switches it on has to model it or register the difference. +revm 43's `ResultGas` has no `reservoir_remaining`; the oracle reads the reservoir from the frame's gas at the point the fork records it (a handler that wraps revm 43's mainnet handler and only reads; a unit test checks it changes nothing else). + +Both arms share the scenario format and its loader, `mega_evm::test_utils::Scenario`. + +## How the two revms coexist + +The workspace redirects `revm` to the MegaETH fork with `[patch.crates-io]`. +A patch only replaces a crates.io dependency whose version requirement the patched crate satisfies: the fork is `revm 40.0.3`, and this crate asks for `=43.0.0`, which it does not satisfy, so the requirement resolves to the registry. +Both revms therefore sit in this crate's graph, and only here: the crate is a workspace member but not a default member, and nothing else depends on it. + +```bash +cargo tree -i revm --locked -p mega-evm # one revm, the fork +cargo tree -p mega-differential -i revm --locked # "ambiguous": revm@40.0.3 and revm@43.0.0 +cargo tree -p mega-differential -i revm@43.0.0 --locked +cargo tree -p mega-differential -i revm@40.0.3 --locked +``` + +The oracle is built without revm's default features, so it adds no native precompile backend (c-kzg, blst, secp256k1) to the build; it runs the pure-Rust ones. +Its `dev` feature compiles the same optional configuration fields `mega-evm` compiles on the fork, so each of them is copied. + +The lockfile is shared. +Cargo writes the version requirements of revm 43's optional dependencies into it even though they are not built, so adding the oracle moved two crates of the core's graph to newer semver-compatible releases: `c-kzg` 2.1.7 → 2.1.8 and `tracing-core` 0.1.34 → 0.1.36. + +## The corpus + +`scenarios/` holds one JSON file per scenario; the file stem is the scenario name. +The format is `mega_evm::test_utils::Scenario`: a coinbase, the pre-state accounts (nonce, balance, legacy code, storage) and the transactions, run in order. +A transaction is a `call`, a `create` or a `system_call`; it may carry an EIP-2930 access list and an EIP-7702 authorization list with the signer already recovered (`authority`, absent for a signature that does not recover). +The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. + +| Directory | Scenarios | Origin | +| -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | +| `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | + +The scenarios come from a reference harness that ran them at per-scenario state-gas prices and execution caps. +Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. +Gas limits at or below the reference cap are unchanged, and the system call lost its gas limit, since a system call runs with the engine's own. +Under the Osaka gas table state gas is priced at zero, so today the scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. + +To add a scenario, drop a JSON file into the directory of its origin; the loader rejects unknown fields, a name that is not the file stem, and a duplicate name. + +## What is compared + +For every transaction: + +- the outcome: `success`, `revert`, `halt:` or `error:`, with op-revm's naming wrappers taken off; +- every gas figure: each field of `ResultGas` as it serializes (`gas_spent`, `state_gas_spent`, `gas_refunded`, `floor_gas`, `reservoir_remaining`), so a field the fork adds shows up as a difference, and the derived `tx_gas_used`, `block_regular_gas_used`, `block_state_gas_used` and `final_refunded`; + history gas has no field of its own in `ResultGas` and is part of `gas_spent` and `block_regular_gas_used`; +- the output bytes and the created address; +- the logs; +- every touched account: created and self-destructed flags, balance, nonce, code hash, and the value of every slot the transaction changed. + +## The deviation registry + +`deviations.json` lists the accepted differences. + +```json +{ + "id": "op-base-fee-vault-touch", + "status": "active", + "scenario": "*", + "field": "tx[*].state[0x4200000000000000000000000000000000000019]", + "left": "created=false selfdestructed=false balance=0x0 …", + "right": "", + "mechanism": "…", + "reason": "…" +} +``` + +- `scenario`, `field`, `left` (the `MegaEvm` value) and `right` (the oracle's) are patterns in which `*` stands for any run of characters. + Keep them as narrow as the mechanism allows: an entry names one mechanism and the exact values it produces. +- `status` is `active` or `retired`; a retired entry keeps its history in `retired_reason` and explains nothing. +- The run fails on a difference no active entry explains, and on an active entry that explains nothing. + When a mechanism stops producing its difference, retire its entry. +- The `version` field is the format version this crate reads. + +The active entries today are op-revm's fee vaults: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. +`tests/claims.rs` checks that state clearing drops those empty accounts when the state is committed. + +## Relation to the equivalence tests + +`crates/mega-evm/tests/satin/equivalence.rs` compares `MegaEvm` with op-revm's `OpEvm` on the same fork, which pins that the Satin layer adds nothing to op-revm yet. +This harness compares `MegaEvm` with an independent implementation, which pins that the fork plus op-revm execute Ethereum semantics. diff --git a/crates/mega-differential/deviations.json b/crates/mega-differential/deviations.json new file mode 100644 index 000000000..975a63f31 --- /dev/null +++ b/crates/mega-differential/deviations.json @@ -0,0 +1,35 @@ +{ + "version": 1, + "deviations": [ + { + "id": "op-base-fee-vault-touch", + "status": "active", + "scenario": "*", + "field": "tx[*].state[0x4200000000000000000000000000000000000019]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "", + "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", + "reason": "After every non-deposit transaction op-revm credits the base fee to its vault predeploy 0x4200000000000000000000000000000000000019 with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." + }, + { + "id": "op-l1-fee-vault-touch", + "status": "active", + "scenario": "*", + "field": "tx[*].state[0x420000000000000000000000000000000000001a]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "", + "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", + "reason": "After every non-deposit transaction op-revm credits the L1 data fee to its vault predeploy 0x420000000000000000000000000000000000001a with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." + }, + { + "id": "op-operator-fee-vault-touch", + "status": "active", + "scenario": "*", + "field": "tx[*].state[0x420000000000000000000000000000000000001b]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "", + "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", + "reason": "After every non-deposit transaction op-revm credits the operator fee to its vault predeploy 0x420000000000000000000000000000000000001b with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/code_deposit.json b/crates/mega-differential/scenarios/handwritten/code_deposit.json new file mode 100644 index 000000000..3ead2c211 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/code_deposit.json @@ -0,0 +1,28 @@ +{ + "name": "code_deposit", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000000527f5b670000000000000000527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b670000000000000040527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000040670000000000000060527f52670000000000000060670000000000000000f3000000000000000000000000670000000000000080526700000000000000946700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json b/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json new file mode 100644 index 000000000..fbb3f4eb8 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json @@ -0,0 +1,28 @@ +{ + "name": "code_deposit_large_spills", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000000527f5b670000000000000000527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b670000000000000040527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000040670000000000000060527f527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000080527f5b5b670000000000000060527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000000a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000080527f5b5b5b5b5b5b5b5b6700000000000000c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67000000000000006700000000000000e0527fa0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000100527f5b5b5b6700000000000000c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000120527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000000e0527f5b5b5b5b5b5b5b670000000000000140527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67000000000000670000000000000160527f0100527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000180527f5b5b5b5b670000000000000120527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000001a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000140527f5b5b5b5b5b5b6700000000000001c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000006700000000000001e0527f000160527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000200527f5b5b5b5b5b670000000000000180527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000220527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000001a0527f5b5b5b5b5b670000000000000240527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000670000000000000260527f000001c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000280527f5b5b5b5b5b5b6700000000000001e0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000002a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000200527f5b5b5b5b6700000000000002c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000006700000000000002e0527f0000000220527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000300527f5b5b5b5b5b5b5b670000000000000240527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000320527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000260527f5b5b5b670000000000000340527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000670000000000000360527f000000000280527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000380527f5b5b5b5b5b5b5b5b6700000000000002a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000003a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000002c0527f5b5b6700000000000003c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67006700000000000003e0527f000000000002e0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000400527f5b5b5b5b5b5b5b5b5b670000000000000300527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000420527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000320527f5b670000000000000440527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67670000000000000460527f0000000000000340527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000480527f5b5b5b5b5b5b5b5b5b5b670000000000000360527f5b5b5b5b5b5b5b5b5b5b5b6700000000000004a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000380527f6700000000000004c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000004e0527f6700000000000003a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000500527f5b5b5b5b5b5b5b5b5b5b5b6700000000000003c0527f5b5b5b5b5b5b5b5b5b5b670000000000000520527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000003e052670000000000000540527f670000000000000400670000000000000000f300000000000000000000000000670000000000000560526700000000000005736700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create2_success.json b/crates/mega-differential/scenarios/handwritten/create2_success.json new file mode 100644 index 000000000..417a30118 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create2_success.json @@ -0,0 +1,28 @@ +{ + "name": "create2_success", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005f670000000000000000f5505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_address_collision.json b/crates/mega-differential/scenarios/handwritten/create_address_collision.json new file mode 100644 index 000000000..102e4aa1d --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_address_collision.json @@ -0,0 +1,34 @@ +{ + "name": "create_address_collision", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b000000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000002670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", + "storage": {} + }, + "0x4e4d52dd883900314328cde4a7050718ffd64bfc": { + "nonce": 1, + "balance": "0x0", + "code": "0x5b00", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json b/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json new file mode 100644 index 000000000..98dd8bf8e --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json @@ -0,0 +1,28 @@ +{ + "name": "create_initcode_revert_after_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f5f5ffd0000000000000000000000000000000000000000000000000000000000670000000000000000526700000000000000036700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json b/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json new file mode 100644 index 000000000..c22845a62 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json @@ -0,0 +1,34 @@ +{ + "name": "create_insufficient_endowment", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc6700000000000493e0f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b000000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000002670000000000000000f300006700000000000000205267000000000000003e6700000000000000006700000000000003e8f05000", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json b/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json new file mode 100644 index 000000000..252ec3c09 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json @@ -0,0 +1,34 @@ +{ + "name": "create_revert_inside_reverting_call", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc670000000000061a80f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f5f5ffd0000000000000000000000000000000000000000000000000000000000670000000000000000526700000000000000036700000000000000005ff0505f5ffd", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_success.json b/crates/mega-differential/scenarios/handwritten/create_success.json new file mode 100644 index 000000000..e3f8cf5d0 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_success.json @@ -0,0 +1,28 @@ +{ + "name": "create_success", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/create_transaction.json b/crates/mega-differential/scenarios/handwritten/create_transaction.json new file mode 100644 index 000000000..14cb8810e --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/create_transaction.json @@ -0,0 +1,21 @@ +{ + "name": "create_transaction", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "data": "0x7f5b5b00000000000000000000000000000000000000000000000000000000000067000000000000000052670000000000000003670000000000000000f3", + "value": "0x0", + "gas_limit": 200150000, + "kind": "create" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json b/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json new file mode 100644 index 000000000..4f007f6f3 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json @@ -0,0 +1,34 @@ +{ + "name": "delegatecall_refill_of_a_parent_charge", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5f5f5f730000000000000000000000000000000000000ccc67000000000002bf20f4505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000015500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json b/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json new file mode 100644 index 000000000..16ad0ce49 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json @@ -0,0 +1,28 @@ +{ + "name": "gas_limit_above_cap", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200500000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json b/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json new file mode 100644 index 000000000..1228af750 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json @@ -0,0 +1,28 @@ +{ + "name": "gas_limit_below_cap", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 650000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json b/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json new file mode 100644 index 000000000..d8e6e0bde --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json @@ -0,0 +1,34 @@ +{ + "name": "nested_call_halt_with_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1507f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000032557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000033555a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f000000000000000000000000000000000000000000000000000000000000000255fe", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json b/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json new file mode 100644 index 000000000..f928b1289 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json @@ -0,0 +1,34 @@ +{ + "name": "nested_call_revert_with_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5ffd", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json b/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json new file mode 100644 index 000000000..bc70f9bf0 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json @@ -0,0 +1,34 @@ +{ + "name": "selfdestruct_to_new_account", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x3e8", + "code": "0x730000000000000000000000000000000000000eeeff", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json b/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json new file mode 100644 index 000000000..bc24628c2 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_refill_after_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json b/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json new file mode 100644 index 000000000..925423c53 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_refill_no_prior_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json b/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json new file mode 100644 index 000000000..5bd91f6b5 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_set_spills", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json b/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json new file mode 100644 index 000000000..cc8b8ef40 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_set_within_reservoir", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/system_call.json b/crates/mega-differential/scenarios/handwritten/system_call.json new file mode 100644 index 000000000..4e82514d5 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/system_call.json @@ -0,0 +1,26 @@ +{ + "name": "system_call", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0xfffffffffffffffffffffffffffffffffffffffe", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "kind": "system_call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json b/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json new file mode 100644 index 000000000..9ab146327 --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json @@ -0,0 +1,36 @@ +{ + "name": "two_txs_sequential", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json new file mode 100644 index 000000000..3cd3608da --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json @@ -0,0 +1,28 @@ +{ + "name": "value_call_to_new_account", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x3e8", + "code": "0x5f5f5f5f670000000000000001730000000000000000000000000000000000000eee67000000000002bf20f1505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json new file mode 100644 index 000000000..ddfe0ec8c --- /dev/null +++ b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json @@ -0,0 +1,28 @@ +{ + "name": "value_call_to_new_account_insufficient_balance", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x1", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5f5f5f6700000000000f4240730000000000000000000000000000000000000eee67000000000002bf20f1505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/src/diff.rs b/crates/mega-differential/src/diff.rs new file mode 100644 index 000000000..1104345a0 --- /dev/null +++ b/crates/mega-differential/src/diff.rs @@ -0,0 +1,184 @@ +//! Field-by-field comparison of two scenario records. + +use std::{collections::BTreeSet, fmt::Display}; + +use crate::record::{AccountRecord, ScenarioRecord, TxRecord, ABSENT}; + +/// One field on which the two arms disagree. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Difference { + /// Scenario name. + pub scenario: String, + /// Field path, e.g. `tx[0].gas.gas_spent` or `tx[1].state[0x…].storage[0x1]`. + pub field: String, + /// The value `MegaEvm` reported. + pub left: String, + /// The value the oracle reported. + pub right: String, +} + +/// The differences between two records of one scenario, and how many fields were compared. +#[derive(Debug, Default)] +pub struct Comparison { + /// Fields on which the arms disagree. + pub differences: Vec, + /// Number of fields compared. + pub compared: usize, +} + +impl Comparison { + fn field(&mut self, scenario: &str, field: String, left: T, right: T) { + self.compared += 1; + if left != right { + self.differences.push(Difference { + scenario: scenario.to_string(), + field, + left: left.to_string(), + right: right.to_string(), + }); + } + } +} + +/// Compares the record `MegaEvm` produced (`left`) with the oracle's (`right`). +pub fn compare(scenario: &str, left: &ScenarioRecord, right: &ScenarioRecord) -> Comparison { + let mut cmp = Comparison::default(); + cmp.field(scenario, "tx_count".into(), left.len(), right.len()); + for (i, (l, r)) in left.iter().zip(right).enumerate() { + compare_tx(&mut cmp, scenario, &format!("tx[{i}]"), l, r); + } + cmp +} + +fn compare_tx(cmp: &mut Comparison, scenario: &str, at: &str, l: &TxRecord, r: &TxRecord) { + cmp.field(scenario, format!("{at}.outcome"), &l.outcome, &r.outcome); + for name in l.gas.keys().chain(r.gas.keys()).collect::>() { + cmp.field( + scenario, + format!("{at}.gas.{name}"), + render(l.gas.get(name)), + render(r.gas.get(name)), + ); + } + cmp.field(scenario, format!("{at}.output"), &l.output, &r.output); + cmp.field( + scenario, + format!("{at}.created"), + render(l.created.map(|address| format!("{address:#x}"))), + render(r.created.map(|address| format!("{address:#x}"))), + ); + cmp.field(scenario, format!("{at}.logs.len"), l.logs.len(), r.logs.len()); + for (j, (ll, rl)) in l.logs.iter().zip(&r.logs).enumerate() { + cmp.field(scenario, format!("{at}.logs[{j}]"), ll.render(), rl.render()); + } + for address in l.state.keys().chain(r.state.keys()).collect::>() { + let path = format!("{at}.state[{address:#x}]"); + match (l.state.get(address), r.state.get(address)) { + (Some(la), Some(ra)) => compare_account(cmp, scenario, &path, la, ra), + (la, ra) => cmp.field( + scenario, + path, + la.map_or_else(|| ABSENT.to_string(), AccountRecord::render), + ra.map_or_else(|| ABSENT.to_string(), AccountRecord::render), + ), + } + } +} + +fn compare_account( + cmp: &mut Comparison, + scenario: &str, + at: &str, + l: &AccountRecord, + r: &AccountRecord, +) { + cmp.field(scenario, format!("{at}.created"), l.created, r.created); + cmp.field(scenario, format!("{at}.selfdestructed"), l.selfdestructed, r.selfdestructed); + cmp.field(scenario, format!("{at}.balance"), l.balance, r.balance); + cmp.field(scenario, format!("{at}.nonce"), l.nonce, r.nonce); + cmp.field(scenario, format!("{at}.code_hash"), l.code_hash, r.code_hash); + for slot in l.storage.keys().chain(r.storage.keys()).collect::>() { + cmp.field( + scenario, + format!("{at}.storage[{slot:#x}]"), + render(l.storage.get(slot).map(|value| format!("{value:#x}"))), + render(r.storage.get(slot).map(|value| format!("{value:#x}"))), + ); + } +} + +/// Renders an optional value, with [`ABSENT`] for `None`. +fn render(value: Option) -> String { + value.map_or_else(|| ABSENT.to_string(), |value| value.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::record::LogRecord; + use alloy_primitives::{address, Address, Bytes, U256}; + use std::collections::BTreeMap; + + const A: Address = address!("0x0000000000000000000000000000000000000aaa"); + + fn tx() -> TxRecord { + TxRecord { + outcome: "success".into(), + gas: BTreeMap::from([("gas_spent".to_string(), 21_000)]), + state: BTreeMap::from([(A, AccountRecord { nonce: 1, ..Default::default() })]), + ..Default::default() + } + } + + #[test] + fn test_compare_equal_records_reports_nothing() { + let cmp = compare("s", &vec![tx()], &vec![tx()]); + assert!(cmp.differences.is_empty()); + // tx_count, outcome, one gas field, output, created, logs.len, five account fields. + assert_eq!(cmp.compared, 11); + } + + #[test] + fn test_compare_reports_each_differing_field() { + let mut right = tx(); + right.gas.insert("gas_spent".into(), 21_001); + right.gas.insert("reservoir_remaining".into(), 0); + right.state.get_mut(&A).unwrap().storage.insert(U256::from(1), U256::from(2)); + right.logs.push(LogRecord { address: A, topics: vec![], data: Bytes::new() }); + + let fields: Vec<(String, String, String)> = compare("s", &vec![tx()], &vec![right]) + .differences + .into_iter() + .map(|d| (d.field, d.left, d.right)) + .collect(); + + let at = format!("tx[0].state[{A:#x}]"); + assert_eq!( + fields, + vec![ + ("tx[0].gas.gas_spent".into(), "21000".into(), "21001".into()), + ("tx[0].gas.reservoir_remaining".into(), ABSENT.into(), "0".into()), + ("tx[0].logs.len".into(), "0".into(), "1".into()), + (format!("{at}.storage[0x1]"), ABSENT.into(), "0x2".into()), + ] + ); + } + + #[test] + fn test_compare_reports_an_account_only_one_arm_touched() { + let mut right = tx(); + right.state.clear(); + let differences = compare("s", &vec![tx()], &vec![right]).differences; + assert_eq!(differences.len(), 1); + assert_eq!(differences[0].field, "tx[0].state[0x0000000000000000000000000000000000000aaa]"); + assert!(differences[0].left.contains("nonce=1")); + assert_eq!(differences[0].right, ABSENT); + } + + #[test] + fn test_compare_reports_a_missing_transaction() { + let differences = compare("s", &vec![tx(), tx()], &vec![tx()]).differences; + assert_eq!(differences.len(), 1); + assert_eq!((differences[0].left.as_str(), differences[0].right.as_str()), ("2", "1")); + } +} diff --git a/crates/mega-differential/src/lib.rs b/crates/mega-differential/src/lib.rs new file mode 100644 index 000000000..338ea778b --- /dev/null +++ b/crates/mega-differential/src/lib.rs @@ -0,0 +1,192 @@ +//! Differential harness of the Satin engine. +//! +//! Runs every scenario of a corpus through `MegaEvm` (the left arm) and through stock revm 43 on +//! its mainnet handler (the right arm, the oracle), and compares what they report field by +//! field: every gas figure, the outcome, the output, the logs and every touched account. Each +//! difference must be explained by an active entry of the deviation registry, and every active +//! entry must explain at least one difference. +//! +//! See the crate README for the corpus, the registry and how the two revms coexist. + +use std::{ + collections::BTreeMap, + fmt::Write as _, + fs, + path::{Path, PathBuf}, +}; + +use mega_evm::test_utils::Scenario; + +pub mod diff; +pub mod mega; +pub mod oracle; +pub mod record; +pub mod registry; + +use diff::Difference; +use registry::Registry; + +/// Directory of the corpus, one subdirectory per origin. +pub fn corpus_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("scenarios") +} + +/// Path of the deviation registry. +pub fn registry_path() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("deviations.json") +} + +/// Loads every `*.json` scenario under `dir` (recursively), sorted by path. +/// +/// Every scenario must be valid, its name must be its file stem, and names must be unique. +pub fn load_corpus(dir: &Path) -> Result, String> { + let mut paths = Vec::new(); + collect_json(dir, &mut paths)?; + paths.sort(); + let mut names = BTreeMap::new(); + let mut scenarios = Vec::with_capacity(paths.len()); + for path in paths { + let text = fs::read_to_string(&path).map_err(|err| format!("{}: {err}", path.display()))?; + let scenario: Scenario = + serde_json::from_str(&text).map_err(|err| format!("{}: {err}", path.display()))?; + scenario.validate()?; + if path.file_stem().and_then(|stem| stem.to_str()) != Some(scenario.name.as_str()) { + return Err(format!("{}: the name must be the file stem", path.display())); + } + if let Some(other) = names.insert(scenario.name.clone(), path.clone()) { + return Err(format!("{}: name already used by {}", path.display(), other.display())); + } + scenarios.push(scenario); + } + Ok(scenarios) +} + +fn collect_json(dir: &Path, out: &mut Vec) -> Result<(), String> { + let entries = fs::read_dir(dir).map_err(|err| format!("{}: {err}", dir.display()))?; + for entry in entries { + let path = entry.map_err(|err| format!("{}: {err}", dir.display()))?.path(); + if path.is_dir() { + collect_json(&path, out)?; + } else if path.extension().is_some_and(|ext| ext == "json") { + out.push(path); + } + } + Ok(()) +} + +/// The outcome of a differential run. +#[derive(Debug, Default)] +pub struct Report { + /// Number of scenarios run. + pub scenarios: usize, + /// Number of fields compared. + pub compared: usize, + /// Differences an active registry entry explains, by entry id. + pub explained: BTreeMap>, + /// Differences no active entry explains, with the retired entry that would have, if any. + pub unexplained: Vec<(Difference, Option)>, + /// Active entries that explained nothing. + pub stale: Vec, +} + +impl Report { + /// Whether every difference is explained and every active entry explained one. + pub fn is_clean(&self) -> bool { + self.unexplained.is_empty() && self.stale.is_empty() + } + + /// The one-line summary printed at the end of a run. + pub fn summary(&self) -> String { + let matched: usize = self.explained.values().map(Vec::len).sum(); + let by_entry: Vec = + self.explained.iter().map(|(id, diffs)| format!("{id} x{}", diffs.len())).collect(); + format!( + "differential: {} scenarios, {} fields compared, {} deviations matched{}, {} unexplained, {} stale registry entries", + self.scenarios, + self.compared, + matched, + if by_entry.is_empty() { String::new() } else { format!(" ({})", by_entry.join(", ")) }, + self.unexplained.len(), + self.stale.len(), + ) + } + + /// Every unexplained difference and stale entry, one per line. + pub fn failures(&self) -> String { + let mut out = String::new(); + for (diff, retired) in &self.unexplained { + let _ = write!( + out, + "unexplained: {} {}: mega={} oracle={}", + diff.scenario, diff.field, diff.left, diff.right + ); + if let Some(id) = retired { + let _ = write!(out, " (matches retired entry {id})"); + } + out.push('\n'); + } + for id in &self.stale { + let _ = writeln!(out, "stale: active registry entry {id} explained no difference"); + } + out + } +} + +/// Runs every scenario through both arms and checks the differences against `registry`. +pub fn run(scenarios: &[Scenario], registry: &Registry) -> Report { + let comparisons: Vec = parallel_map(scenarios, |scenario| { + diff::compare(&scenario.name, &mega::run(scenario), &oracle::run(scenario)) + }); + let mut report = Report { scenarios: scenarios.len(), ..Default::default() }; + for comparison in comparisons { + report.compared += comparison.compared; + for difference in comparison.differences { + match registry.explain(&difference) { + Some(dev) => report.explained.entry(dev.id.clone()).or_default().push(difference), + None => { + let retired = registry.retired_match(&difference).map(|dev| dev.id.clone()); + report.unexplained.push((difference, retired)); + } + } + } + } + report.stale = registry + .deviations + .iter() + .filter(|dev| dev.status == registry::Status::Active) + .filter(|dev| !report.explained.contains_key(&dev.id)) + .map(|dev| dev.id.clone()) + .collect(); + report +} + +/// Maps `f` over `items` on all available cores, keeping the order. +fn parallel_map(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec { + let threads = std::thread::available_parallelism().map_or(1, usize::from); + let chunk = items.len().div_ceil(threads).max(1); + std::thread::scope(|scope| { + let handles: Vec<_> = items + .chunks(chunk) + .map(|chunk| scope.spawn(|| chunk.iter().map(&f).collect::>())) + .collect(); + handles.into_iter().flat_map(|handle| handle.join().expect("scenario panicked")).collect() + }) +} + +/// The `u64` fields of `value` as it serializes to a JSON object, by serialized name. +/// +/// Both arms read `ResultGas` through this, so a field the fork adds shows up on the left arm +/// as a difference until the oracle reports the same figure or the registry explains it. +fn serialized_u64_fields(value: &impl serde::Serialize) -> BTreeMap { + let serde_json::Value::Object(fields) = serde_json::to_value(value).expect("serializable") + else { + panic!("expected a JSON object"); + }; + fields + .into_iter() + .map(|(name, value)| { + let value = value.as_u64().unwrap_or_else(|| panic!("{name} is not a u64: {value}")); + (name, value) + }) + .collect() +} diff --git a/crates/mega-differential/src/mega.rs b/crates/mega-differential/src/mega.rs new file mode 100644 index 000000000..7008a8962 --- /dev/null +++ b/crates/mega-differential/src/mega.rs @@ -0,0 +1,107 @@ +//! The left arm: `MegaEvm`, configured as the Satin spec fixes it. + +use std::collections::BTreeMap; + +use mega_evm::{ + alloy_op_evm::OpTxError, + op_revm::{OpHaltReason, OpTransactionError}, + revm::{ + context::result::{EVMError, ExecutionResult, ResultGas}, + state::EvmState, + }, + test_utils::{Scenario, ScenarioTxOutcome}, +}; + +use crate::record::{AccountRecord, LogRecord, ScenarioRecord, TxRecord}; + +/// Runs `scenario` on `MegaEvm` and records every transaction. +pub fn run(scenario: &Scenario) -> ScenarioRecord { + let (outcomes, _db) = scenario.run(scenario.database()); + outcomes.iter().map(record).collect() +} + +fn record(outcome: &ScenarioTxOutcome) -> TxRecord { + let outcome = match outcome { + Ok(outcome) => outcome, + Err(err) => { + return TxRecord { outcome: format!("error:{}", error(err)), ..Default::default() } + } + }; + let result = &outcome.result; + TxRecord { + outcome: match result { + ExecutionResult::Success { .. } => "success".into(), + ExecutionResult::Revert { .. } => "revert".into(), + ExecutionResult::Halt { reason, .. } => format!("halt:{}", halt(reason)), + }, + gas: gas(result.gas()), + output: result.output().cloned().unwrap_or_default(), + created: result.created_address(), + logs: result + .logs() + .iter() + .map(|log| LogRecord { + address: log.address, + topics: log.topics().to_vec(), + data: log.data.data.clone(), + }) + .collect(), + state: state(&outcome.state), + } +} + +/// The gas figures of `gas`: its fields as it serializes them, which is every field it has, +/// and the derived values. +fn gas(gas: &ResultGas) -> BTreeMap { + let mut figures = crate::serialized_u64_fields(gas); + figures.insert("tx_gas_used".into(), gas.tx_gas_used()); + figures.insert("block_regular_gas_used".into(), gas.block_regular_gas_used()); + figures.insert("block_state_gas_used".into(), gas.block_state_gas_used()); + figures.insert("final_refunded".into(), gas.final_refunded()); + figures +} + +/// The halt reason with the OP wrapper taken off: op-revm wraps every Ethereum halt reason in +/// `OpHaltReason::Base`, which is naming, not behavior. A halt reason of op-revm's own keeps an +/// `op:` prefix. +fn halt(reason: &OpHaltReason) -> String { + match reason { + OpHaltReason::Base(reason) => format!("{reason:?}"), + other => format!("op:{other:?}"), + } +} + +/// The error with the OP wrappers taken off, the same way as [`halt`]. +fn error(err: &EVMError) -> String { + match err { + EVMError::Transaction(OpTxError(OpTransactionError::Base(invalid))) => { + format!("invalid:{invalid:?}") + } + EVMError::Transaction(OpTxError(other)) => format!("op:{other:?}"), + EVMError::Header(header) => format!("header:{header:?}"), + other => format!("other:{other:?}"), + } +} + +fn state(state: &EvmState) -> BTreeMap { + state + .iter() + .filter(|(_, account)| account.is_touched()) + .map(|(address, account)| { + let record = AccountRecord { + created: account.is_created(), + selfdestructed: account.is_selfdestructed(), + balance: account.info.balance, + nonce: account.info.nonce, + code_hash: account.info.code_hash, + storage: account + .storage + .iter() + .filter(|(_, slot)| slot.is_changed()) + .map(|(key, slot)| (*key, slot.present_value)) + .collect(), + }; + (*address, record) + }) + .collect() +} diff --git a/crates/mega-differential/src/oracle.rs b/crates/mega-differential/src/oracle.rs new file mode 100644 index 000000000..14911fc9b --- /dev/null +++ b/crates/mega-differential/src/oracle.rs @@ -0,0 +1,358 @@ +//! The right arm: stock revm 43 on its mainnet handler. +//! +//! The oracle takes its configuration from `MegaEvm`'s, field by field: the same Ethereum spec, +//! the same gas table (copied entry by entry), the same switches. It has no OP layer, so the +//! differences an OP-specific mechanism makes are the registry's to explain. + +use std::{cell::Cell, collections::BTreeMap, convert::Infallible, str::FromStr}; + +use mega_evm::{ + revm::context::CfgEnv as MegaCfgEnv, + test_utils::{Scenario, TxSpecKind}, + MegaContext, MegaSpecId, +}; +use revm_oracle::{ + context::{ + result::{EVMError, ExecutionResult, HaltReason, ResultGas}, + transaction::{ + AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization, + }, + BlockEnv, CfgEnv, ContextSetters, ContextTr, JournalTr, TxEnv, + }, + context_interface::cfg::GasParams, + database::{CacheDB, EmptyDB}, + handler::{ + system_call::SystemCallTx, EthFrame, EvmTr, FrameResult, FrameTr, Handler, MainnetHandler, + }, + interpreter::interpreter::EthInterpreter, + primitives::{hardfork::SpecId, TxKind}, + state::{AccountInfo, Bytecode, EvmState}, + Context, Database, DatabaseCommit, MainBuilder, MainContext, MainnetEvm, +}; + +use crate::record::{AccountRecord, LogRecord, ScenarioRecord, TxRecord}; + +type OracleDb = CacheDB; +type OracleEvm<'a> = MainnetEvm>; +type OracleError = EVMError; + +/// Runs `scenario` on revm 43 and records every transaction. +pub fn run(scenario: &Scenario) -> ScenarioRecord { + let cfg = cfg(); + let block = block(scenario); + let mut db = database(scenario); + let mut records = Vec::with_capacity(scenario.txs.len()); + for tx in &scenario.txs { + let mut evm = Context::mainnet() + .with_db(&mut db) + .with_cfg(cfg.clone()) + .with_block(block.clone()) + .build_mainnet(); + let mut probe = ReservoirProbe::default(); + let result = match tx.kind { + TxSpecKind::SystemCall => { + evm.ctx().set_tx(TxEnv::new_system_tx_with_caller( + tx.caller, + tx.to.expect("validated: a system call has a target"), + tx.data.clone(), + )); + probe.run_system_call(&mut evm) + } + TxSpecKind::Call | TxSpecKind::Create => { + let nonce = + evm.ctx().db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); + evm.ctx().set_tx(tx_env(tx, nonce)); + probe.run(&mut evm) + } + }; + let state = evm.ctx().journal_mut().finalize(); + drop(evm); + let record = match result { + Ok(result) => { + let record = record(&result, probe.reservoir.get(), &state); + db.commit(state); + record + } + Err(err) => { + TxRecord { outcome: format!("error:{}", error(&err)), ..Default::default() } + } + }; + records.push(record); + } + records +} + +/// The oracle's configuration: `MegaEvm`'s, field by field. +/// +/// # Panics +/// +/// If `MegaEvm` switches on a fork-only mechanism revm 43 cannot run: EIP-7708 transfer logs +/// before Amsterdam, or the system-call state-gas margin. The harness then needs a model of it or +/// a registry entry before it can compare. +pub fn cfg() -> CfgEnv { + let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); + let mega: &MegaCfgEnv = ctx.mega_cfg(); + let eth_spec: &'static str = mega.spec.into_eth_spec().into(); + let spec = SpecId::from_str(eth_spec).expect("revm 43 knows every spec the fork knows"); + assert!( + !mega.enable_amsterdam_eip7708 || spec.is_enabled_in(SpecId::AMSTERDAM), + "MegaEvm switches EIP-7708 on before Amsterdam, which revm 43 cannot do" + ); + assert!( + !mega.system_call_state_gas_margin_in_reservoir, + "MegaEvm reserves the system-call state-gas margin, which revm 43 does not have" + ); + + let mut cfg = CfgEnv::new_with_spec_and_gas_params(spec, gas_params(mega.gas_params.table())); + cfg.chain_id = mega.chain_id; + cfg.tx_chain_id_check = mega.tx_chain_id_check; + cfg.limit_contract_code_size = mega.limit_contract_code_size; + cfg.limit_contract_initcode_size = mega.limit_contract_initcode_size; + cfg.disable_nonce_check = mega.disable_nonce_check; + cfg.max_blobs_per_tx = mega.max_blobs_per_tx; + cfg.blob_base_fee_update_fraction = mega.blob_base_fee_update_fraction; + cfg.tx_gas_limit_cap = mega.tx_gas_limit_cap; + cfg.memory_limit = mega.memory_limit; + cfg.disable_balance_check = mega.disable_balance_check; + cfg.disable_block_gas_limit = mega.disable_block_gas_limit; + cfg.disable_eip3541 = mega.disable_eip3541; + cfg.disable_eip3607 = mega.disable_eip3607; + cfg.disable_eip7623 = mega.disable_eip7623; + cfg.disable_base_fee = mega.disable_base_fee; + cfg.enable_amsterdam_eip8037 = mega.enable_amsterdam_eip8037; + cfg.enable_amsterdam_eip2780 = mega.enable_amsterdam_eip2780; + cfg.amsterdam_eip7708_disabled = mega.amsterdam_eip7708_disabled; + cfg.amsterdam_eip8246_delayed_clear_disabled = mega.amsterdam_eip8246_delayed_clear_disabled; + cfg +} + +/// A revm 43 gas table holding `table` entry for entry. +/// +/// The fork numbers its gas ids as upstream does, so an index names the same price on both +/// sides; the fork's own ids sit at the top of the table, where upstream has none. +pub fn gas_params(table: &[u64; 256]) -> GasParams { + GasParams::new(std::sync::Arc::new(*table)) +} + +fn block(scenario: &Scenario) -> BlockEnv { + let mega = scenario.block(); + BlockEnv { + number: mega.number, + beneficiary: mega.beneficiary, + timestamp: mega.timestamp, + gas_limit: mega.gas_limit, + basefee: mega.basefee, + difficulty: mega.difficulty, + prevrandao: mega.prevrandao, + ..Default::default() + } +} + +fn database(scenario: &Scenario) -> OracleDb { + let mut db = OracleDb::default(); + for (address, account) in &scenario.pre { + let mut info = + AccountInfo { nonce: account.nonce, balance: account.balance, ..Default::default() }; + if !account.code.is_empty() { + let code = Bytecode::new_legacy(account.code.clone()); + info.code_hash = code.hash_slow(); + info.code = Some(code); + } + db.insert_account_info(*address, info); + for (slot, value) in &account.storage { + db.insert_account_storage(*address, *slot, *value).expect("in-memory database"); + } + } + db +} + +fn tx_env(tx: &mega_evm::test_utils::TxSpec, nonce: u64) -> TxEnv { + let access_list = AccessList( + tx.access_list + .iter() + .map(|entry| AccessListItem { + address: entry.address, + storage_keys: entry.storage_keys.iter().map(|key| (*key).into()).collect(), + }) + .collect(), + ); + let authorizations = tx + .authorization_list + .iter() + .map(|entry| { + RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: entry.chain_id, + address: entry.address, + nonce: entry.nonce, + }, + entry.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + ) + }) + .collect(); + TxEnv::builder() + .tx_type(Some(tx.tx_type())) + .caller(tx.caller) + .kind(tx.to.map_or(TxKind::Create, TxKind::Call)) + .data(tx.data.clone()) + .value(tx.value) + .gas_limit(tx.gas_limit.unwrap_or_default()) + .gas_price(0) + .gas_priority_fee((tx.tx_type() == 4).then_some(0)) + .nonce(nonce) + .access_list(access_list) + .authorization_list_recovered(authorizations) + .build_fill() +} + +/// revm 43's mainnet handler, reading the reservoir left over at the point the fork records it. +/// +/// revm 43's `ResultGas` has no `reservoir_remaining`. The fork reads it from the frame's gas +/// right after the refund, before the EIP-7623 floor may absorb it; this handler reads the same +/// gas at the same point, in the floor check that runs right after (for a system call, which +/// has no floor check, in `execution_result`, which gets the same gas). +#[derive(Default)] +struct ReservoirProbe<'a> { + inner: MainnetHandler, OracleError, EthFrame>, + reservoir: Cell>, +} + +impl<'a> Handler for ReservoirProbe<'a> { + type Evm = OracleEvm<'a>; + type Error = OracleError; + type HaltReason = HaltReason; + + fn eip7623_check_gas_floor( + &self, + evm: &mut Self::Evm, + exec_result: &mut FrameResult, + init_and_floor_gas: revm_oracle::context_interface::cfg::gas::InitialAndFloorGas, + ) { + self.reservoir.set(Some(exec_result.gas().reservoir())); + self.inner.eip7623_check_gas_floor(evm, exec_result, init_and_floor_gas); + } + + fn execution_result( + &mut self, + evm: &mut Self::Evm, + result: <::Frame as FrameTr>::FrameResult, + result_gas: ResultGas, + ) -> Result, Self::Error> { + if self.reservoir.get().is_none() { + self.reservoir.set(Some(result.gas().reservoir())); + } + self.inner.execution_result(evm, result, result_gas) + } +} + +fn record(result: &ExecutionResult, reservoir: Option, state: &EvmState) -> TxRecord { + TxRecord { + outcome: match result { + ExecutionResult::Success { .. } => "success".into(), + ExecutionResult::Revert { .. } => "revert".into(), + ExecutionResult::Halt { reason, .. } => format!("halt:{reason:?}"), + }, + gas: gas(result.gas(), reservoir), + output: result.output().cloned().unwrap_or_default(), + created: result.created_address(), + logs: result + .logs() + .iter() + .map(|log| LogRecord { + address: log.address, + topics: log.topics().to_vec(), + data: log.data.data.clone(), + }) + .collect(), + state: state + .iter() + .filter(|(_, account)| account.is_touched()) + .map(|(address, account)| { + let record = AccountRecord { + created: account.is_created(), + selfdestructed: account.is_selfdestructed(), + balance: account.info.balance, + nonce: account.info.nonce, + code_hash: account.info.code_hash, + storage: account + .storage + .iter() + .filter(|(_, slot)| slot.is_changed()) + .map(|(key, slot)| (*key, slot.present_value)) + .collect(), + }; + (*address, record) + }) + .collect(), + } +} + +/// The gas figures of `gas` as [`crate::mega`] names them, with the probed reservoir in place of +/// the field revm 43 lacks. +fn gas(gas: &ResultGas, reservoir: Option) -> BTreeMap { + let mut figures = crate::serialized_u64_fields(gas); + if let Some(reservoir) = reservoir { + figures.insert("reservoir_remaining".into(), reservoir); + } + figures.insert("tx_gas_used".into(), gas.tx_gas_used()); + figures.insert("block_regular_gas_used".into(), gas.block_regular_gas_used()); + figures.insert("block_state_gas_used".into(), gas.block_state_gas_used()); + figures.insert("final_refunded".into(), gas.final_refunded()); + figures +} + +fn error(err: &OracleError) -> String { + match err { + EVMError::Transaction(invalid) => format!("invalid:{invalid:?}"), + EVMError::Header(header) => format!("header:{header:?}"), + other => format!("other:{other:?}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use revm_oracle::{ExecuteEvm, SystemCallEvm}; + + /// Runs `scenario` with revm 43's own entry points instead of the probe. + fn run_stock(scenario: &Scenario) -> ScenarioRecord { + let mut db = database(scenario); + let mut records = Vec::new(); + for tx in &scenario.txs { + let mut evm = Context::mainnet() + .with_db(&mut db) + .with_cfg(cfg()) + .with_block(block(scenario)) + .build_mainnet(); + let outcome = match tx.kind { + TxSpecKind::SystemCall => { + evm.system_call_with_caller(tx.caller, tx.to.unwrap(), tx.data.clone()) + } + _ => { + let nonce = evm.ctx().db_mut().basic(tx.caller).unwrap().map_or(0, |i| i.nonce); + evm.transact(tx_env(tx, nonce)) + } + }; + drop(evm); + let outcome = outcome.unwrap(); + records.push(record(&outcome.result, None, &outcome.state)); + db.commit(outcome.state); + } + records + } + + /// The probe only reads the reservoir: without that figure, every scenario records the same + /// as through revm 43's own `transact` and `system_call_with_caller`. + #[test] + fn test_reservoir_probe_changes_nothing_else() { + let scenarios = crate::load_corpus(&crate::corpus_dir().join("handwritten")).unwrap(); + assert!(scenarios.iter().any(|s| s.txs.iter().any(|tx| tx.kind == TxSpecKind::SystemCall))); + for scenario in &scenarios { + let mut probed = run(scenario); + for record in &mut probed { + assert!(record.gas.remove("reservoir_remaining").is_some(), "{}", scenario.name); + } + assert_eq!(probed, run_stock(scenario), "{}", scenario.name); + } + } +} diff --git a/crates/mega-differential/src/record.rs b/crates/mega-differential/src/record.rs new file mode 100644 index 000000000..21cb4cb3c --- /dev/null +++ b/crates/mega-differential/src/record.rs @@ -0,0 +1,85 @@ +//! What an arm reports for a scenario, in a form both arms produce. +//! +//! Each arm turns its own result types into these records; the comparison only ever sees +//! records, so it cannot depend on which revm produced them. + +use std::collections::BTreeMap; + +use alloy_primitives::{Address, Bytes, B256, U256}; + +/// Marker for a value one arm has and the other does not. +pub const ABSENT: &str = ""; + +/// The records of every transaction of one scenario, in order. +pub type ScenarioRecord = Vec; + +/// What one transaction produced. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TxRecord { + /// `success`, `revert`, `halt:` or `error:`. + pub outcome: String, + /// Every gas figure of the result, by name: the fields of `ResultGas` as it serializes + /// them, the reservoir left over, and the derived values a block builder reads. + pub gas: BTreeMap, + /// Return or revert data. + pub output: Bytes, + /// Address a create transaction deployed to. + pub created: Option
, + /// Logs, in emission order. + pub logs: Vec, + /// Every account the transaction touched. + pub state: BTreeMap, +} + +/// A log entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LogRecord { + /// Emitting contract. + pub address: Address, + /// Topics. + pub topics: Vec, + /// Data. + pub data: Bytes, +} + +/// A touched account after the transaction. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AccountRecord { + /// Created in this transaction (its storage starts empty). + pub created: bool, + /// Self-destructed in this transaction. + pub selfdestructed: bool, + /// Balance. + pub balance: U256, + /// Nonce. + pub nonce: u64, + /// Code hash. + pub code_hash: B256, + /// The slots whose value the transaction changed, with their new value. + pub storage: BTreeMap, +} + +impl LogRecord { + /// One-line rendering used in difference reports and the registry. + pub fn render(&self) -> String { + let topics: Vec = self.topics.iter().map(|topic| format!("{topic}")).collect(); + format!("{:#x} [{}] {}", self.address, topics.join(","), self.data) + } +} + +impl AccountRecord { + /// One-line rendering used when only one arm has the account. + pub fn render(&self) -> String { + let storage: Vec = + self.storage.iter().map(|(slot, value)| format!("{slot:#x}={value:#x}")).collect(); + format!( + "created={} selfdestructed={} balance={:#x} nonce={} code_hash={} storage={{{}}}", + self.created, + self.selfdestructed, + self.balance, + self.nonce, + self.code_hash, + storage.join(","), + ) + } +} diff --git a/crates/mega-differential/src/registry.rs b/crates/mega-differential/src/registry.rs new file mode 100644 index 000000000..426e511df --- /dev/null +++ b/crates/mega-differential/src/registry.rs @@ -0,0 +1,193 @@ +//! The registry of accepted differences. +//! +//! Every difference between the arms must be explained by an active entry, and every active +//! entry must explain at least one difference; either failure fails the run. A mechanism that +//! stops producing its difference therefore shows up as a stale entry, to be retired, instead of +//! lingering as a blanket excuse. + +use serde::Deserialize; + +use crate::diff::Difference; + +/// Version of the registry format this crate reads. +pub const REGISTRY_VERSION: u64 = 1; + +/// The registry file. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Registry { + /// Format version; must be [`REGISTRY_VERSION`]. + pub version: u64, + /// The entries. + pub deviations: Vec, +} + +/// An accepted difference between `MegaEvm` and the oracle. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Deviation { + /// Stable identifier, used in reports. + pub id: String, + /// Whether the entry is in force. + pub status: Status, + /// Scenario names the entry covers (`*` matches any run of characters). + pub scenario: String, + /// Field path the entry covers (`*` matches any run of characters). + pub field: String, + /// The value `MegaEvm` reports (`*` matches any run of characters). + pub left: String, + /// The value the oracle reports (`*` matches any run of characters). + pub right: String, + /// The mechanism that makes the arms differ. + pub mechanism: String, + /// Why the difference is correct. + pub reason: String, + /// Why the entry was retired; required for a retired entry. + #[serde(default)] + pub retired_reason: Option, +} + +/// Status of a registry entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Status { + /// In force: it explains differences, and it must explain at least one. + Active, + /// Kept for the record; it explains nothing. + Retired, +} + +impl Registry { + /// Parses a registry and checks its entries are well formed. + pub fn from_json(json: &str) -> Result { + let registry: Self = serde_json::from_str(json).map_err(|err| err.to_string())?; + if registry.version != REGISTRY_VERSION { + return Err(format!( + "registry version {} (this harness reads {REGISTRY_VERSION})", + registry.version + )); + } + let mut ids = std::collections::BTreeSet::new(); + for dev in ®istry.deviations { + if !ids.insert(dev.id.as_str()) { + return Err(format!("duplicate registry id {}", dev.id)); + } + if dev.mechanism.trim().is_empty() || dev.reason.trim().is_empty() { + return Err(format!("{}: an entry names its mechanism and its reason", dev.id)); + } + if (dev.status == Status::Retired) != dev.retired_reason.is_some() { + return Err(format!( + "{}: a retired entry, and only one, has retired_reason", + dev.id + )); + } + } + Ok(registry) + } + + /// The active entry that explains `diff`, if any. + pub fn explain(&self, diff: &Difference) -> Option<&Deviation> { + self.deviations.iter().find(|dev| dev.status == Status::Active && dev.matches(diff)) + } + + /// A retired entry that would have explained `diff`, to point at in a failure report. + pub fn retired_match(&self, diff: &Difference) -> Option<&Deviation> { + self.deviations.iter().find(|dev| dev.status == Status::Retired && dev.matches(diff)) + } +} + +impl Deviation { + /// Whether this entry's patterns cover `diff`, whatever its status. + pub fn matches(&self, diff: &Difference) -> bool { + glob(&self.scenario, &diff.scenario) && + glob(&self.field, &diff.field) && + glob(&self.left, &diff.left) && + glob(&self.right, &diff.right) + } +} + +/// Matches `text` against `pattern`, where `*` stands for any run of characters (including +/// none) and every other character stands for itself. +pub fn glob(pattern: &str, text: &str) -> bool { + let mut parts = pattern.split('*'); + let first = parts.next().unwrap_or_default(); + let Some(mut rest) = text.strip_prefix(first) else { return false }; + let parts: Vec<&str> = parts.collect(); + let Some((last, middle)) = parts.split_last() else { return rest.is_empty() }; + for part in middle { + match rest.find(part) { + Some(at) => rest = &rest[at + part.len()..], + None => return false, + } + } + rest.len() >= last.len() && rest.ends_with(last) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(status: &str, extra: &str) -> String { + format!( + r#"{{"id": "d", "status": "{status}", "scenario": "call_*", "field": "tx[*].gas.gas_spent", + "left": "*", "right": "21000", "mechanism": "m", "reason": "r"{extra}}}"# + ) + } + + fn registry(entries: &[String]) -> Result { + Registry::from_json(&format!(r#"{{"version": 1, "deviations": [{}]}}"#, entries.join(","))) + } + + fn diff(scenario: &str, right: &str) -> Difference { + Difference { + scenario: scenario.into(), + field: "tx[0].gas.gas_spent".into(), + left: "21100".into(), + right: right.into(), + } + } + + #[test] + fn test_glob() { + assert!(glob("*", "")); + assert!(glob("abc", "abc")); + assert!(!glob("abc", "abcd")); + assert!(glob("a*c", "abbbc")); + assert!(glob("a*c", "ac")); + assert!(!glob("a*c", "ab")); + assert!(glob("*b*", "abc")); + assert!(glob("a*b*c", "aXbYc")); + assert!(!glob("a*b*c", "aXcYb")); + // The suffix may not reuse characters the prefix consumed. + assert!(!glob("ab*ba", "aba")); + } + + #[test] + fn test_active_entry_explains_matching_differences_only() { + let registry = registry(&[entry("active", "")]).unwrap(); + assert_eq!(registry.explain(&diff("call_1", "21000")).map(|d| d.id.as_str()), Some("d")); + assert!(registry.explain(&diff("create_1", "21000")).is_none(), "scenario pattern"); + assert!(registry.explain(&diff("call_1", "21001")).is_none(), "right value"); + } + + #[test] + fn test_retired_entry_explains_nothing() { + let registry = registry(&[entry("retired", r#", "retired_reason": "gone""#)]).unwrap(); + assert!(registry.explain(&diff("call_1", "21000")).is_none()); + assert_eq!( + registry.retired_match(&diff("call_1", "21000")).map(|d| d.id.as_str()), + Some("d") + ); + } + + #[test] + fn test_registry_rejects_malformed_entries() { + assert!(registry(&[entry("retired", "")]).unwrap_err().contains("retired_reason")); + assert!(registry(&[entry("active", r#", "retired_reason": "x""#)]).is_err()); + assert!(registry(&[entry("active", ""), entry("active", "")]) + .unwrap_err() + .contains("duplicate")); + assert!(Registry::from_json(r#"{"version": 2, "deviations": []}"#).is_err()); + assert!(registry(&[entry("paused", "")]).is_err()); + } +} diff --git a/crates/mega-differential/tests/claims.rs b/crates/mega-differential/tests/claims.rs new file mode 100644 index 000000000..6c4889737 --- /dev/null +++ b/crates/mega-differential/tests/claims.rs @@ -0,0 +1,107 @@ +//! Checks of what the harness and its registry claim about the two arms. + +use std::collections::BTreeMap; + +use mega_differential::oracle; +use mega_evm::{ + alloy_primitives::{address, Address, Bytes, U256}, + revm::{ + context_interface::cfg::gas_params::GasId as ForkGasId, + database::{states::bundle_state::BundleRetention, State}, + DatabaseCommit, + }, + test_utils::{PreAccount, Scenario, TxSpec, TxSpecKind}, + MegaContext, MegaSpecId, +}; +use revm_oracle::{ + context_interface::cfg::gas_params::GasId as OracleGasId, primitives::hardfork::SpecId, +}; + +const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); +const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); + +/// The gas ids the fork adds on top of upstream's. revm 43 has no price at these indexes. +const FORK_ONLY_GAS_IDS: &[&str] = &["code_deposit_history_gas"]; + +/// The oracle copies `MegaEvm`'s gas table index by index, which is only sound if every index +/// names the same price on both sides. +#[test] +fn test_gas_table_indexes_name_the_same_prices() { + let mut fork_only = Vec::new(); + for id in 0..=u8::MAX { + let (fork, oracle) = (ForkGasId::new(id).name(), OracleGasId::new(id).name()); + if oracle == "unknown" && fork != "unknown" { + fork_only.push(fork); + } else { + assert_eq!(fork, oracle, "gas id {id}"); + } + } + assert_eq!(fork_only, FORK_ONLY_GAS_IDS); +} + +/// A price only the fork has is one the oracle cannot charge, so it must be zero while the +/// corpus is expected to match; the mechanism that prices it registers the difference. +#[test] +fn test_fork_only_gas_ids_are_priced_at_zero() { + let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); + for name in FORK_ONLY_GAS_IDS { + let id = ForkGasId::from_name(name).unwrap(); + assert_eq!(ctx.mega_cfg().gas_params.get(id), 0, "{name}"); + } +} + +#[test] +fn test_oracle_runs_the_satin_configuration() { + let cfg = oracle::cfg(); + assert_eq!(cfg.spec, SpecId::OSAKA); + let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); + assert_eq!(cfg.gas_params.table(), ctx.mega_cfg().gas_params.table()); + assert!(cfg.enable_amsterdam_eip8037); + assert!(cfg.enable_amsterdam_eip2780); + assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); + assert_eq!(cfg.chain_id, ctx.mega_cfg().chain_id); +} + +/// The registry's vault entries rest on this: a vault op-revm touches with a zero fee is +/// dropped by state clearing when the transaction's state is committed. +#[test] +fn test_zero_fee_vault_touch_leaves_no_committed_account() { + let vaults = [ + address!("0x4200000000000000000000000000000000000019"), + address!("0x420000000000000000000000000000000000001a"), + address!("0x420000000000000000000000000000000000001b"), + ]; + let scenario = Scenario { + name: "transfer".into(), + coinbase: Address::ZERO, + pre: BTreeMap::from([( + CALLER, + PreAccount { balance: U256::from(10), ..Default::default() }, + )]), + txs: vec![TxSpec { + caller: CALLER, + to: Some(CALLEE), + data: Bytes::new(), + value: U256::from(1), + gas_limit: Some(100_000), + kind: TxSpecKind::Call, + access_list: Vec::new(), + authorization_list: Vec::new(), + }], + }; + let (outcomes, _) = scenario.run(scenario.database()); + let state = outcomes.into_iter().next().unwrap().unwrap().state; + for vault in vaults { + assert!(state[&vault].is_touched() && state[&vault].is_empty(), "{vault}"); + } + + let mut db = State::builder().with_database(scenario.database()).with_bundle_update().build(); + db.commit(state); + db.merge_transitions(BundleRetention::PlainState); + let bundle = db.take_bundle(); + + assert!(bundle.account(&CALLEE).is_some(), "the transfer itself is committed"); + for vault in vaults { + assert!(bundle.account(&vault).is_none(), "{vault}"); + } +} diff --git a/crates/mega-differential/tests/corpus.rs b/crates/mega-differential/tests/corpus.rs new file mode 100644 index 000000000..2986b1342 --- /dev/null +++ b/crates/mega-differential/tests/corpus.rs @@ -0,0 +1,14 @@ +//! Runs the whole corpus through both arms. + +use mega_differential::{corpus_dir, load_corpus, registry::Registry, registry_path, run}; + +#[test] +fn test_corpus_matches_the_oracle() { + let scenarios = load_corpus(&corpus_dir()).unwrap(); + let registry = Registry::from_json(&std::fs::read_to_string(registry_path()).unwrap()).unwrap(); + + let report = run(&scenarios, ®istry); + + println!("{}", report.summary()); + assert!(report.is_clean(), "{}\n{}", report.summary(), report.failures()); +} From 49f4c3cb67750a30c73cf9a0ba16a3a426fa4991 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:15:45 +0800 Subject: [PATCH 033/201] test: carry the execution-spec-test-derived corpus over to the differential harness --- crates/mega-differential/README.md | 7 +- ...t_state_gas_fork_Amsterdam_state_test.json | 31 ++++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 31 ++++++++ ...eation_cost_fork_Amsterdam_state_test.json | 28 +++++++ ...y_fork_Amsterdam_state_test_exact_fit.json | 28 +++++++ ...y_fork_Amsterdam_state_test_one_short.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_100M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_120M.json | 28 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 28 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_200M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_300M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_30M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_36M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_500M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_60M.json | 28 +++++++ ...n_detection_fork_Amsterdam_state_test.json | 35 ++++++++ ..._forwarding_fork_Amsterdam_state_test.json | 35 ++++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ...test_reservoir_in_cap_target_kind_new.json | 28 +++++++ ...test_reservoir_in_cap_target_kind_pre.json | 28 +++++++ ...test_reservoir_over_cap_target_kind_n.json | 28 +++++++ ...test_reservoir_over_cap_target_kind_p.json | 28 +++++++ ...Amsterdam_state_test_reservoir_in_cap.json | 28 +++++++ ...sterdam_state_test_reservoir_over_cap.json | 28 +++++++ ...t_state_gas_fork_Amsterdam_state_test.json | 32 ++++++++ ...ount_fork_Amsterdam_state_test_create.json | 28 +++++++ ...unt_fork_Amsterdam_state_test_create2.json | 28 +++++++ ...o_state_gas_fork_Amsterdam_state_test.json | 31 ++++++++ ...new_account_fork_Amsterdam_state_test.json | 31 ++++++++ ...t_state_gas_fork_Amsterdam_state_test.json | 28 +++++++ ...h_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ...d_block_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...as_fork_Amsterdam_state_test_at_floor.json | 23 ++++++ ...fork_Amsterdam_state_test_below_floor.json | 23 ++++++ ..._cap_fork_Amsterdam_state_test_at_cap.json | 27 +++++++ ...fork_Amsterdam_state_test_exceeds_cap.json | 27 +++++++ ...h_state_ops_fork_Amsterdam_state_test.json | 27 +++++++ ...f_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...y_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...with_sstore_fork_Amsterdam_state_test.json | 27 +++++++ ...m_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ...y_fork_Amsterdam_state_test_exact_fit.json | 27 +++++++ ...y_fork_Amsterdam_state_test_one_short.json | 27 +++++++ ...to_gas_left_fork_Amsterdam_state_test.json | 27 +++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 31 ++++++++ ..._test_call_call_value_new_account_cha.json | 36 +++++++++ ...sterdam_state_test_call_sstore_charge.json | 35 ++++++++ ...state_test_delegatecall_sstore_charge.json | 35 ++++++++ ...d_in_parent_fork_Amsterdam_state_test.json | 31 ++++++++ ...t_reservoir_fork_Amsterdam_state_test.json | 31 ++++++++ ...s_collision_fork_Amsterdam_state_test.json | 27 +++++++ ...ble_charged_fork_Amsterdam_state_test.json | 27 +++++++ ..._state_test_fail_mode_eip3541_slots_0.json | 27 +++++++ ..._state_test_fail_mode_eip3541_slots_1.json | 27 +++++++ ..._state_test_fail_mode_eip3541_slots_3.json | 27 +++++++ ...te_test_fail_mode_oog_deposit_slots_0.json | 27 +++++++ ...te_test_fail_mode_oog_deposit_slots_1.json | 27 +++++++ ...te_test_fail_mode_oog_deposit_slots_3.json | 27 +++++++ ...ATE2_state_test_charge_from_reservoir.json | 34 ++++++++ ...tate_test_charge_spills_from_gas_left.json | 34 ++++++++ ...EATE_state_test_charge_from_reservoir.json | 34 ++++++++ ...tate_test_charge_spills_from_gas_left.json | 34 ++++++++ ...e_CREATE2_state_test_existing_account.json | 30 +++++++ ...opcode_CREATE2_state_test_new_account.json | 27 +++++++ ...de_CREATE_state_test_existing_account.json | 30 +++++++ ..._opcode_CREATE_state_test_new_account.json | 27 +++++++ ...s_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...code_CREATE2_state_test_initcode_halt.json | 31 ++++++++ ...ode_CREATE2_state_test_invalid_prefix.json | 31 ++++++++ ...pcode_CREATE_state_test_initcode_halt.json | 31 ++++++++ ...code_CREATE_state_test_invalid_prefix.json | 31 ++++++++ ...rdam_create_opcode_CREATE2_state_test.json | 31 ++++++++ ...erdam_create_opcode_CREATE_state_test.json | 31 ++++++++ ...rdam_create_opcode_CREATE2_state_test.json | 35 ++++++++ ...erdam_create_opcode_CREATE_state_test.json | 35 ++++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ...t_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...new_account_fork_Amsterdam_state_test.json | 31 ++++++++ ...to_gas_left_fork_Amsterdam_state_test.json | 30 +++++++ ...rdam_create_opcode_CREATE2_state_test.json | 35 ++++++++ ...erdam_create_opcode_CREATE_state_test.json | 35 ++++++++ ...CREATE2_state_test_oog_on_create_base.json | 35 ++++++++ ...state_test_oog_on_init_code_word_cost.json | 35 ++++++++ ..._CREATE_state_test_oog_on_create_base.json | 35 ++++++++ ...state_test_oog_on_init_code_word_cost.json | 35 ++++++++ ...t_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...as_consumed_fork_Amsterdam_state_test.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_100M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_120M.json | 27 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 27 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_200M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_300M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_30M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_36M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_500M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_60M.json | 27 +++++++ ...voir_fork_Amsterdam_state_test_create.json | 27 +++++++ ...oir_fork_Amsterdam_state_test_create2.json | 27 +++++++ ...sterdam_state_test_all_frames_succeed.json | 31 ++++++++ ...state_test_middle_reverts_after_clear.json | 31 ++++++++ ...msterdam_state_test_top_level_reverts.json | 31 ++++++++ ...ble_charged_fork_Amsterdam_state_test.json | 31 ++++++++ ...oir_passing_fork_Amsterdam_state_test.json | 31 ++++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ..._state_cost_fork_Amsterdam_state_test.json | 27 +++++++ ...exceeds_cap_fork_Amsterdam_state_test.json | 27 +++++++ ...r_below_cap_fork_Amsterdam_state_test.json | 27 +++++++ ...t_above_cap_fork_Amsterdam_state_test.json | 27 +++++++ ...e_opcode_CREATE2_state_test_exact_gas.json | 31 ++++++++ ...code_CREATE2_state_test_short_one_gas.json | 31 ++++++++ ...te_opcode_CREATE_state_test_exact_gas.json | 31 ++++++++ ...pcode_CREATE_state_test_short_one_gas.json | 31 ++++++++ ...oir_passing_fork_Amsterdam_state_test.json | 35 ++++++++ ..._parent_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...ume_deepest_depth_10_create_collision.json | 79 +++++++++++++++++++ ...epest_depth_10_create_initcode_revert.json | 75 ++++++++++++++++++ ...e_deepest_depth_10_sstore_restoration.json | 75 ++++++++++++++++++ ...sume_deepest_depth_1_create_collision.json | 43 ++++++++++ ...eepest_depth_1_create_initcode_revert.json | 39 +++++++++ ...me_deepest_depth_1_sstore_restoration.json | 39 +++++++++ ...sume_deepest_depth_3_create_collision.json | 51 ++++++++++++ ...eepest_depth_3_create_initcode_revert.json | 47 +++++++++++ ...me_deepest_depth_3_sstore_restoration.json | 47 +++++++++++ ...consume_top_depth_10_create_collision.json | 79 +++++++++++++++++++ ...e_top_depth_10_create_initcode_revert.json | 75 ++++++++++++++++++ ...nsume_top_depth_10_sstore_restoration.json | 75 ++++++++++++++++++ ..._consume_top_depth_1_create_collision.json | 43 ++++++++++ ...me_top_depth_1_create_initcode_revert.json | 39 +++++++++ ...onsume_top_depth_1_sstore_restoration.json | 39 +++++++++ ..._consume_top_depth_3_create_collision.json | 51 ++++++++++++ ...me_top_depth_3_create_initcode_revert.json | 47 +++++++++++ ...onsume_top_depth_3_sstore_restoration.json | 47 +++++++++++ ...e_CREATE2_state_test_insufficient_gas.json | 34 ++++++++ ...ode_CREATE2_state_test_sufficient_gas.json | 34 ++++++++ ...de_CREATE_state_test_insufficient_gas.json | 34 ++++++++ ...code_CREATE_state_test_sufficient_gas.json | 34 ++++++++ ...msterdam_state_test_no_reservoir_halt.json | 27 +++++++ ...terdam_state_test_no_reservoir_revert.json | 27 +++++++ ...terdam_state_test_with_reservoir_halt.json | 27 +++++++ ...rdam_state_test_with_reservoir_revert.json | 27 +++++++ ...ked_by_halt_fork_Amsterdam_state_test.json | 40 ++++++++++ ...limits_fork_Amsterdam_state_test_100M.json | 27 +++++++ ...limits_fork_Amsterdam_state_test_120M.json | 27 +++++++ ...s_limits_fork_Amsterdam_state_test_1G.json | 27 +++++++ ...s_limits_fork_Amsterdam_state_test_1M.json | 27 +++++++ ...limits_fork_Amsterdam_state_test_200M.json | 27 +++++++ ...limits_fork_Amsterdam_state_test_300M.json | 27 +++++++ ..._limits_fork_Amsterdam_state_test_30M.json | 27 +++++++ ..._limits_fork_Amsterdam_state_test_36M.json | 27 +++++++ ...limits_fork_Amsterdam_state_test_500M.json | 27 +++++++ ..._limits_fork_Amsterdam_state_test_60M.json | 27 +++++++ ...s_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...r_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...ach_account_fork_Amsterdam_state_test.json | 27 +++++++ ...y_fork_Amsterdam_state_test_above_cap.json | 27 +++++++ ...dary_fork_Amsterdam_state_test_at_cap.json | 27 +++++++ ...y_fork_Amsterdam_state_test_below_cap.json | 27 +++++++ ..._and_revert_fork_Amsterdam_state_test.json | 31 ++++++++ ...ll_and_halt_fork_Amsterdam_state_test.json | 31 ++++++++ ..._and_revert_fork_Amsterdam_state_test.json | 31 ++++++++ ...rned_on_oog_fork_Amsterdam_state_test.json | 31 ++++++++ ...d_on_revert_fork_Amsterdam_state_test.json | 31 ++++++++ ...pth_fork_Amsterdam_state_test_depth_1.json | 39 +++++++++ ...th_fork_Amsterdam_state_test_depth_10.json | 75 ++++++++++++++++++ ...pth_fork_Amsterdam_state_test_depth_3.json | 47 +++++++++++ ...epth_fork_Amsterdam_state_test_direct.json | 35 ++++++++ ..._child_halt_fork_Amsterdam_state_test.json | 35 ++++++++ ...o_state_gas_fork_Amsterdam_state_test.json | 28 +++++++ ..._write_cost_fork_Amsterdam_state_test.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_100M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_120M.json | 28 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 28 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_200M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_300M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_30M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_36M.json | 28 +++++++ ...h_cpsb_fork_Amsterdam_state_test_500M.json | 28 +++++++ ...th_cpsb_fork_Amsterdam_state_test_60M.json | 28 +++++++ ...msterdam_state_test_funding_reservoir.json | 28 +++++++ ...rk_Amsterdam_state_test_funding_spill.json | 28 +++++++ ...n_detection_fork_Amsterdam_state_test.json | 36 +++++++++ ...stor_revert_fork_Amsterdam_state_test.json | 32 ++++++++ ...n_create_tx_fork_Amsterdam_state_test.json | 28 +++++++ ...o_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ ...een_reverts_fork_Amsterdam_state_test.json | 31 ++++++++ ..._child_halt_fork_Amsterdam_state_test.json | 39 +++++++++ ...nd_reversal_fork_Amsterdam_state_test.json | 30 +++++++ ...me_contract_fork_Amsterdam_state_test.json | 27 +++++++ ..._fork_Amsterdam_state_test_five_slots.json | 27 +++++++ ...fork_Amsterdam_state_test_single_slot.json | 27 +++++++ ...s_fork_Amsterdam_state_test_ten_slots.json | 27 +++++++ ..._to_nonzero_fork_Amsterdam_state_test.json | 30 +++++++ ...ero_to_zero_fork_Amsterdam_state_test.json | 30 +++++++ ...n_fork_Amsterdam_state_test_exact_gas.json | 31 ++++++++ ...rk_Amsterdam_state_test_short_one_gas.json | 31 ++++++++ ...n_detection_fork_Amsterdam_state_test.json | 35 ++++++++ ...h_cpsb_fork_Amsterdam_state_test_100M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_120M.json | 27 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 27 +++++++ ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_200M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_300M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_30M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_36M.json | 27 +++++++ ...h_cpsb_fork_Amsterdam_state_test_500M.json | 27 +++++++ ...th_cpsb_fork_Amsterdam_state_test_60M.json | 27 +++++++ ...erdam_call_opcode_CALLCODE_state_test.json | 39 +++++++++ ...Amsterdam_call_opcode_CALL_state_test.json | 39 +++++++++ ...m_call_opcode_DELEGATECALL_state_test.json | 39 +++++++++ ...opcode_CALLCODE_state_test_single_hop.json | 35 ++++++++ ...l_opcode_CALLCODE_state_test_ten_hops.json | 71 +++++++++++++++++ ...opcode_CALLCODE_state_test_three_hops.json | 43 ++++++++++ ...l_opcode_CALLCODE_state_test_two_hops.json | 39 +++++++++ ...de_DELEGATECALL_state_test_single_hop.json | 35 ++++++++ ...code_DELEGATECALL_state_test_ten_hops.json | 71 +++++++++++++++++ ...de_DELEGATECALL_state_test_three_hops.json | 43 ++++++++++ ...code_DELEGATECALL_state_test_two_hops.json | 39 +++++++++ ...erdam_call_opcode_CALLCODE_state_test.json | 39 +++++++++ ...m_call_opcode_DELEGATECALL_state_test.json | 39 +++++++++ ...rdam_create_opcode_CREATE2_state_test.json | 35 ++++++++ ...erdam_create_opcode_CREATE_state_test.json | 35 ++++++++ ...rdam_create_opcode_CREATE2_state_test.json | 27 +++++++ ...erdam_create_opcode_CREATE_state_test.json | 27 +++++++ ...tate_refund_fork_Amsterdam_state_test.json | 30 +++++++ ...e_test_depth_10_no_refund_create_oogs.json | 71 +++++++++++++++++ ...ate_test_depth_10_refund_funds_create.json | 71 +++++++++++++++++ ...te_test_depth_1_no_refund_create_oogs.json | 35 ++++++++ ...tate_test_depth_1_refund_funds_create.json | 35 ++++++++ ...te_test_depth_3_no_refund_create_oogs.json | 43 ++++++++++ ...tate_test_depth_3_refund_funds_create.json | 43 ++++++++++ ...tion_refund_fork_Amsterdam_state_test.json | 27 +++++++ ...erdam_call_opcode_CALLCODE_state_test.json | 35 ++++++++ ...Amsterdam_call_opcode_CALL_state_test.json | 35 ++++++++ ...m_call_opcode_DELEGATECALL_state_test.json | 35 ++++++++ ...terdam_typed_transaction_0_state_test.json | 27 +++++++ ...terdam_typed_transaction_1_state_test.json | 27 +++++++ ...terdam_typed_transaction_2_state_test.json | 27 +++++++ ...m_reservoir_fork_Amsterdam_state_test.json | 27 +++++++ ...om_gas_left_fork_Amsterdam_state_test.json | 27 +++++++ ..._test_multiple_sstores_from_reservoir.json | 27 +++++++ ...st_multiple_sstores_spill_to_gas_left.json | 27 +++++++ ...ate_test_single_sstore_from_reservoir.json | 27 +++++++ ..._test_single_sstore_spill_to_gas_left.json | 27 +++++++ ..._fork_Amsterdam_state_test_at_stipend.json | 31 ++++++++ ...rk_Amsterdam_state_test_below_stipend.json | 31 ++++++++ ..._to_nonzero_fork_Amsterdam_state_test.json | 27 +++++++ ...ero_to_zero_fork_Amsterdam_state_test.json | 27 +++++++ ...s_reservoir_fork_Amsterdam_state_test.json | 31 ++++++++ ...lear_credit_fork_Amsterdam_state_test.json | 35 ++++++++ ...as_fork_Amsterdam_state_test_no_spill.json | 31 ++++++++ ...e_gas_fork_Amsterdam_state_test_spill.json | 31 ++++++++ ...te_gas_fork_Amsterdam_state_test_halt.json | 27 +++++++ ...ate_gas_fork_Amsterdam_state_test_oog.json | 27 +++++++ ..._gas_fork_Amsterdam_state_test_revert.json | 27 +++++++ ...te_test_halt_own_and_propagated_spill.json | 31 ++++++++ ...k_Amsterdam_state_test_halt_own_spill.json | 27 +++++++ ...rdam_state_test_halt_propagated_spill.json | 31 ++++++++ ..._test_revert_own_and_propagated_spill.json | 31 ++++++++ ...Amsterdam_state_test_revert_own_spill.json | 27 +++++++ ...am_state_test_revert_propagated_spill.json | 31 ++++++++ ...d_state_gas_fork_Amsterdam_state_test.json | 27 +++++++ 264 files changed, 8540 insertions(+), 3 deletions(-) create mode 100644 crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json create mode 100644 crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json create mode 100644 crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json create mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json create mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json create mode 100644 crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json create mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json create mode 100644 crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json create mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json create mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json create mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json create mode 100644 crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json create mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json create mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json create mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json create mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json create mode 100644 crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json create mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json create mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json create mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json create mode 100644 crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json create mode 100644 crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json create mode 100644 crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 046f7fe05..bdb352f93 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 23 scenarios, 834 fields compared, 69 deviations matched (op-base-fee-vault-touch x23, …), 0 unexplained, 0 stale registry entries +differential: 286 scenarios, 10761 fields compared, 858 deviations matched (op-base-fee-vault-touch x286, …), 0 unexplained, 0 stale registry entries ``` ## The two arms @@ -60,11 +60,12 @@ The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | Directory | Scenarios | Origin | | -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | | `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | +| `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | -The scenarios come from a reference harness that ran them at per-scenario state-gas prices and execution caps. +Both sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. Gas limits at or below the reference cap are unchanged, and the system call lost its gas limit, since a system call runs with the engine's own. -Under the Osaka gas table state gas is priced at zero, so today the scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. +Under the Osaka gas table state gas is priced at zero, so today these scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. To add a scenario, drop a JSON file into the directory of its origin; the loader rejects unknown fields, a name that is not the file stem, and a duplicate name. diff --git a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..1caa4520e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x52046af6a4e2f4c607b63b582be53f06915040e3": { + "nonce": 1, + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x52046af6a4e2f4c607b63b582be53f06915040e3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..2dadfd539 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe02a60813fb94718ddd669258a39c113946a7a26": { + "nonce": 1, + "code": "0x600060006000600060017337f536464af59c8d7358cae965f92cbeadd58dcb620186a0f16000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe02a60813fb94718ddd669258a39c113946a7a26", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..5a8e07fab --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xca1c9efd74f1a6b6f21a1ecf6a9f3334c87164dc": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f15000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xca1c9efd74f1a6b6f21a1ecf6a9f3334c87164dc", + "data": "0x", + "value": "0x00", + "gas_limit": 200058230, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json new file mode 100644 index 000000000..415128309 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f100" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8", + "data": "0x", + "value": "0x00", + "gas_limit": 200053230, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json new file mode 100644 index 000000000..c6785c5f6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f100" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8", + "data": "0x", + "value": "0x00", + "gas_limit": 200053230, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json new file mode 100644 index 000000000..777cd31dd --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json new file mode 100644 index 000000000..654323465 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json new file mode 100644 index 000000000..7a2edfc74 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json new file mode 100644 index 000000000..1100c2936 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json new file mode 100644 index 000000000..fb3e6cc2a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json new file mode 100644 index 000000000..b173de2da --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json new file mode 100644 index 000000000..601665d93 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json new file mode 100644 index 000000000..5aa23b895 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json new file mode 100644 index 000000000..ac57b95da --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json new file mode 100644 index 000000000..cd870fc0c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..1c4e86ba4 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x3ef0adbd819089c276e7bac4d5c3844bbfc1b963": { + "nonce": 1, + "code": "0x6000600060006000600161dead6000f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x97d820929f41220187e4e5608702a49a70625fa5": { + "nonce": 1, + "code": "0x60006000600060006000733ef0adbd819089c276e7bac4d5c3844bbfc1b96362030520f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x97d820929f41220187e4e5608702a49a70625fa5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..d94f7eddf --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x093685b223a8eb80d2365b02a2346b00b7ca4e83": { + "nonce": 1, + "code": "0x6000600060006000600073634cc1a10e5dec3daef49aa355d43ab81d3b07206147d7f150" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x634cc1a10e5dec3daef49aa355d43ab81d3b0720": { + "nonce": 1, + "code": "0x614000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef63fffffffff1" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x093685b223a8eb80d2365b02a2346b00b7ca4e83", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..fb0506c26 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825": { + "nonce": 1, + "code": "0x60006000600060006000305af1506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json new file mode 100644 index 000000000..a4ef59126 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f1fe" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json new file mode 100644 index 000000000..9d9d68ee8 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600160086000f1fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json new file mode 100644 index 000000000..27bb4ba55 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f1fe" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json new file mode 100644 index 000000000..6dd42ff62 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600160086000f1fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json new file mode 100644 index 000000000..235701b63 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f160006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json new file mode 100644 index 000000000..71ca952af --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f160006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..4dc8e3b08 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,32 @@ +{ + "name": "test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd1eb0fb525ff1409c4938cca3a03f31ba0f831f3": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600160086001f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd1eb0fb525ff1409c4938cca3a03f31ba0f831f3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json new file mode 100644 index 000000000..ddcb3bb31 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x690da8229a8448e73cc9d03ef3f68f86cb9cd351": { + "nonce": 1, + "balance": "0x03", + "code": "0x7f30ff000000000000000000000000000000000000000000000000000000000000600052600260006001f08060205250600060006000600060016020515af1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x690da8229a8448e73cc9d03ef3f68f86cb9cd351", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json new file mode 100644 index 000000000..92502a31c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json @@ -0,0 +1,28 @@ +{ + "name": "test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0280b72062c43cbd14113e8ab12360868b5d7200": { + "nonce": 1, + "balance": "0x03", + "code": "0x7f30ff0000000000000000000000000000000000000000000000000000000000006000526000600260006001f58060205250600060006000600060016020515af1600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0280b72062c43cbd14113e8ab12360868b5d7200", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..9abd9478e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x32aa3856e9410279aa9c2933356e4cb403d68373": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173f36afef4dcb45e52f80cb039335952f77cec8960620186a0f1600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf36afef4dcb45e52f80cb039335952f77cec8960": { + "balance": "0x01" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x32aa3856e9410279aa9c2933356e4cb403d68373", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..dba8f4a2d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_call_value_transfer_new_account_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xebb3ed1a3b7767fca5a4d4a82bdcd8f9be5da5bc": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055", + "storage": { + "0x00": "0x02" + } + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xebb3ed1a3b7767fca5a4d4a82bdcd8f9be5da5bc", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..77bc133f1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,28 @@ +{ + "name": "test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x50a79fee82f1767e31cbef3d1c6761e3f338b869": { + "nonce": 1, + "balance": "0x0de0b6b3a7640000", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af2506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x50a79fee82f1767e31cbef3d1c6761e3f338b869", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..c7b8e5b33 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..7bfae053a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json new file mode 100644 index 000000000..7b0c06635 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json @@ -0,0 +1,23 @@ +{ + "name": "test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc0f6dc9e5836f54caadbf59cc69346c508e1992b", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200005350, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json new file mode 100644 index 000000000..a9f8b0bde --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json @@ -0,0 +1,23 @@ +{ + "name": "test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc0f6dc9e5836f54caadbf59cc69346c508e1992b", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200004750, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json new file mode 100644 index 000000000..ca0efd8cd --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0x010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json new file mode 100644 index 000000000..50921b181 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..b3dee5aed --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..bf30d27b1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..c30e9eb6e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3a4b2393c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_with_sstore_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3f5d35e46 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd7942304c419230163398d295036321e27e2e2fe": { + "nonce": 1, + "code": "0x60016000556000600101600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd7942304c419230163398d295036321e27e2e2fe", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json new file mode 100644 index 000000000..2a9117e16 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json @@ -0,0 +1,27 @@ +{ + "name": "test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200031256, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json new file mode 100644 index 000000000..f9dc8af00 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json @@ -0,0 +1,27 @@ +{ + "name": "test_charge_spill_boundary_fork_Amsterdam_state_test_one_short", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200031256, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..2902fa49b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_charge_spills_to_gas_left_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..235f901b8 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_child_call_uses_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf0fe41d947da36ba18bb17012d4e33ba81d852ec": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf0fe41d947da36ba18bb17012d4e33ba81d852ec", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json new file mode 100644 index 000000000..47d82e640 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json @@ -0,0 +1,36 @@ +{ + "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa61f3a41615e1900676200ed31c287ed5ad51f5f": { + "nonce": 1, + "code": "0x6000600060006000600073f207c059154dc6d35ff485a54cf0a466f0a06b115af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf207c059154dc6d35ff485a54cf0a466f0a06b11": { + "nonce": 1, + "balance": "0x01", + "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af15060006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xa61f3a41615e1900676200ed31c287ed5ad51f5f", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json new file mode 100644 index 000000000..3403361a5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json @@ -0,0 +1,35 @@ +{ + "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x921019ef0dfa80a772ac96256fb64605d3bd68c0": { + "nonce": 1, + "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x921019ef0dfa80a772ac96256fb64605d3bd68c0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json new file mode 100644 index 000000000..136f78389 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json @@ -0,0 +1,35 @@ +{ + "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x3eaf0d84225675074f75f21322e538a2f32a7263": { + "nonce": 1, + "code": "0x600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af450600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af450" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x3eaf0d84225675074f75f21322e538a2f32a7263", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..dba8e68e7 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x22d3d2785c604f63057c379f38cc9e3a758152f6": { + "nonce": 1, + "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f1600155" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x22d3d2785c604f63057c379f38cc9e3a758152f6", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..7eb999045 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x3279904096d6e2fb187b797bb27d79ef221bca59": { + "nonce": 1, + "code": "0x6000600060006000600073727cf77a2c6de3634297d278a2fda305010b1f2b6216e360f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x727cf77a2c6de3634297d278a2fda305010b1f2b": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000000000006110006000f36000526006601a6000f06000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x3279904096d6e2fb187b797bb27d79ef221bca59", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..db1471914 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_address_collision_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9f207d2415e91c7c19e3cd8aa806ce77db392bfe": { + "nonce": 1, + "code": "0x60006000526000600160006000f515156000556000600160006000f5600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x9f207d2415e91c7c19e3cd8aa806ce77db392bfe", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..58837e527 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc915407640e516d8e66e2774a4686ab6a3c7de67": { + "nonce": 1, + "code": "0x7f60016000556002600155600360025560046003556005600455600660055500006000526000601f60006000f550" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc915407640e516d8e66e2774a4686ab6a3c7de67", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json new file mode 100644 index 000000000..1376a92c6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5f3204dd0805d0204f0bfdcdc7dbd7701da926b1": { + "nonce": 1, + "code": "0x7f60ef60005360016000f3000000000000000000000000000000000000000000006000526000600a60006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5f3204dd0805d0204f0bfdcdc7dbd7701da926b1", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json new file mode 100644 index 000000000..a9b38512c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x820b460b61ebed793495cfa83446666c71f3e3a5": { + "nonce": 1, + "code": "0x7f600160005560ef60005360016000f300000000000000000000000000000000006000526000600f60006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x820b460b61ebed793495cfa83446666c71f3e3a5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json new file mode 100644 index 000000000..06ba868f0 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x651ebfcb9681510a3a27dac0d6b74fc15c0678a5": { + "nonce": 1, + "code": "0x7f60016000556002600155600360025560ef60005360016000f3000000000000006000526000601960006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x651ebfcb9681510a3a27dac0d6b74fc15c0678a5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json new file mode 100644 index 000000000..6fd697d87 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x97e3e4e25bc5398b1a2fb5b1923eb7df47df940c": { + "nonce": 1, + "code": "0x7f620100006000f3000000000000000000000000000000000000000000000000006000526000600760006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x97e3e4e25bc5398b1a2fb5b1923eb7df47df940c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json new file mode 100644 index 000000000..c347a794b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xded801e9b63939db16c75751ca035243294ffb28": { + "nonce": 1, + "code": "0x7f6001600055620100006000f300000000000000000000000000000000000000006000526000600c60006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xded801e9b63939db16c75751ca035243294ffb28", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json new file mode 100644 index 000000000..cd6d919e5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json @@ -0,0 +1,27 @@ +{ + "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x7d9ccb76a7972109192aceb974da5bea7e4eb38f": { + "nonce": 1, + "code": "0x7f600160005560026001556003600255620100006000f3000000000000000000006000526000601660006000f5600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x7d9ccb76a7972109192aceb974da5bea7e4eb38f", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json new file mode 100644 index 000000000..7f33a9a01 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json @@ -0,0 +1,34 @@ +{ + "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x126f16ee09ef8508c23bc5dd7205236eefcd2317": { + "balance": "0x01" + }, + "0x4c162f0a55391f16b0d28bad275badc55f8b4882": { + "nonce": 1, + "code": "0x60006000600060006000738249de02b4017aec8639b3601fc73ca713d5c85162089685f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8249de02b4017aec8639b3601fc73ca713d5c851": { + "nonce": 1, + "code": "0x7f600062070f605260006000f3000000000000000000000000000000000000000060005260006000600c60006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4c162f0a55391f16b0d28bad275badc55f8b4882", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json new file mode 100644 index 000000000..9f324b6f9 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json @@ -0,0 +1,34 @@ +{ + "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x126f16ee09ef8508c23bc5dd7205236eefcd2317": { + "balance": "0x01" + }, + "0x4c162f0a55391f16b0d28bad275badc55f8b4882": { + "nonce": 1, + "code": "0x60006000600060006000738249de02b4017aec8639b3601fc73ca713d5c85162089685f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8249de02b4017aec8639b3601fc73ca713d5c851": { + "nonce": 1, + "code": "0x7f600062070f605260006000f3000000000000000000000000000000000000000060005260006000600c60006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4c162f0a55391f16b0d28bad275badc55f8b4882", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json new file mode 100644 index 000000000..b8864f98c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json @@ -0,0 +1,34 @@ +{ + "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4637a0e95b0259c6fdd8377b35caba897a9c43ed": { + "nonce": 1, + "code": "0x7f600062070f605260006000f300000000000000000000000000000000000000006000526000600c60006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x61cadd8e8bf6a11d86ef8ce44fab9396d1897134": { + "balance": "0x01" + }, + "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d": { + "nonce": 1, + "code": "0x60006000600060006000734637a0e95b0259c6fdd8377b35caba897a9c43ed62089682f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json new file mode 100644 index 000000000..bae60e917 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json @@ -0,0 +1,34 @@ +{ + "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4637a0e95b0259c6fdd8377b35caba897a9c43ed": { + "nonce": 1, + "code": "0x7f600062070f605260006000f300000000000000000000000000000000000000006000526000600c60006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x61cadd8e8bf6a11d86ef8ce44fab9396d1897134": { + "balance": "0x01" + }, + "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d": { + "nonce": 1, + "code": "0x60006000600060006000734637a0e95b0259c6fdd8377b35caba897a9c43ed62089682f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json new file mode 100644 index 000000000..b53abd84b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json @@ -0,0 +1,30 @@ +{ + "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x27d27f776c2fa12c4500bc1cc2526c872253fa86": { + "balance": "0x01" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { + "nonce": 1, + "code": "0x600060005260006000600160006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json new file mode 100644 index 000000000..e26661a73 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { + "nonce": 1, + "code": "0x600060005260006000600160006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json new file mode 100644 index 000000000..5d77984da --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json @@ -0,0 +1,30 @@ +{ + "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x08690f601113d9f3d72976b307ee0bc961d897c0": { + "nonce": 1, + "code": "0x60006000526000600160006000f011600055" + }, + "0x1ef7073e8d0ab897fbc7c049d64b3b7526690e16": { + "balance": "0x01" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json new file mode 100644 index 000000000..9bd7de95c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x08690f601113d9f3d72976b307ee0bc961d897c0": { + "nonce": 1, + "code": "0x60006000526000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..372ebe958 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_charges_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x08690f601113d9f3d72976b307ee0bc961d897c0": { + "nonce": 1, + "code": "0x60006000526000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json new file mode 100644 index 000000000..84abf7121 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6eda05b2a84f3df765d26677e5f704a8f971339d": { + "nonce": 1, + "code": "0x6000600060006000600073c62643632aeea6e7020f95f73cbb708dd2066893623bd177f1" + }, + "0xc62643632aeea6e7020f95f73cbb708dd2066893": { + "nonce": 1, + "code": "0x7ffe000000000000000000000000000000000000000000000000000000000000006000526000600160006000f5506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6eda05b2a84f3df765d26677e5f704a8f971339d", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json new file mode 100644 index 000000000..d4dde5d77 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x82e020d72434259dc21dc51591598ea7bf43319c": { + "nonce": 1, + "code": "0x7f60ef60005360016000f3000000000000000000000000000000000000000000006000526000600a60006000f5506001600055" + }, + "0xc08db6086f8b0f2e1c32e65ee46c4696cca5b299": { + "nonce": 1, + "code": "0x600060006000600060007382e020d72434259dc21dc51591598ea7bf43319c623bd177f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc08db6086f8b0f2e1c32e65ee46c4696cca5b299", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json new file mode 100644 index 000000000..18e108d5b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6e3653822cd4eb3e013593e9968d22d625125d48": { + "nonce": 1, + "code": "0x6000600060006000600073de840839cfd1cd4491421a12838f89414c01295d623bd174f1" + }, + "0xde840839cfd1cd4491421a12838f89414c01295d": { + "nonce": 1, + "code": "0x7ffe00000000000000000000000000000000000000000000000000000000000000600052600160006000f0506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6e3653822cd4eb3e013593e9968d22d625125d48", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json new file mode 100644 index 000000000..a52e00477 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0992b6ed03a0ae71e10dcf76ea43ced6d28d4a88": { + "nonce": 1, + "code": "0x7f60ef60005360016000f300000000000000000000000000000000000000000000600052600a60006000f0506001600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe2888c6dd9f79a6f346c5ec4bf813bdbcef34053": { + "nonce": 1, + "code": "0x60006000600060006000730992b6ed03a0ae71e10dcf76ea43ced6d28d4a88623bd174f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe2888c6dd9f79a6f346c5ec4bf813bdbcef34053", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json new file mode 100644 index 000000000..002c87369 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5e2990598185fccd42e7e4568d91adc054a5f5c4": { + "nonce": 1, + "code": "0x6000600060006000600073f87b7124cc48c89c8922004bafdd9354b6ac2a13623bd177f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf87b7124cc48c89c8922004bafdd9354b6ac2a13": { + "nonce": 1, + "code": "0x7f620100016000f3000000000000000000000000000000000000000000000000006000526000600760006000f5506001600055" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5e2990598185fccd42e7e4568d91adc054a5f5c4", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json new file mode 100644 index 000000000..898662cbb --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x13ae54b3ad54c77e91d57822730ac94f7e6ff1f2": { + "nonce": 1, + "code": "0x6000600060006000600073ade9e3ac1853995069340b550d3b394ef9deac29623bd174f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xade9e3ac1853995069340b550d3b394ef9deac29": { + "nonce": 1, + "code": "0x7f620100016000f300000000000000000000000000000000000000000000000000600052600760006000f0506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x13ae54b3ad54c77e91d57822730ac94f7e6ff1f2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json new file mode 100644 index 000000000..5d9962269 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x133bf0f549d849e7897b57aeb721f9157c7cd744": { + "nonce": 1, + "code": "0x60006000526000600160006000f5506001600055" + }, + "0x19f9a3c049a708223f7143e6c0a0b76069210762": { + "nonce": 1, + "code": "0x6000600060006000600073133bf0f549d849e7897b57aeb721f9157c7cd744623bd177f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe177168a6ff286ea8adfe3890c3e3d6cd090226f": { + "nonce": 1, + "code": "0x00" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x19f9a3c049a708223f7143e6c0a0b76069210762", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json new file mode 100644 index 000000000..a2d4cf6c6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x46ccd78896bdccd93808b71816d48c6a71337682": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa36ac1a9c6f2a860e9bb73511cbef95a03e2a066": { + "nonce": 1, + "code": "0x6000600052600160006000f0506001600055" + }, + "0xdf1b17863c9ef2d9e7a39f9e41b9ded103bedeb3": { + "nonce": 1, + "code": "0x6000600060006000600073a36ac1a9c6f2a860e9bb73511cbef95a03e2a066623bd174f1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xdf1b17863c9ef2d9e7a39f9e41b9ded103bedeb3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..a40a318cf --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4d3af333455933fcf46214eb61dd4e57cca6ff1a": { + "nonce": 1, + "code": "0x6000600052600160006001f06000556001600155" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4d3af333455933fcf46214eb61dd4e57cca6ff1a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..c09605f20 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_insufficient_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf4a71fe68af3cdf3bca2dd99c2ed0ff53d00cc11": { + "nonce": 1, + "code": "0x6000600052600160006000f0600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf4a71fe68af3cdf3bca2dd99c2ed0ff53d00cc11", + "data": "0x", + "value": "0x00", + "gas_limit": 200009252, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..75c81375d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_create_no_double_charge_new_account_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x1d52400515dacf7f589ae51dfdff002c4a871027": { + "nonce": 1, + "code": "0x600060006000f0600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xbe93aacae1d2d3fdd3b4904cf99769af5fa65658": { + "nonce": 1, + "code": "0x60006000600060006000731d52400515dacf7f589ae51dfdff002c4a8710276201dcb0f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xbe93aacae1d2d3fdd3b4904cf99769af5fa65658", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3e5d44ad0 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json @@ -0,0 +1,30 @@ +{ + "name": "test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x22af32ea88308575e08326fe58f9af072821cff5": { + "nonce": 1, + "code": "0x6000600060006000f5506001600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x7415c7d4ba6a7ef22f6897b5cca5d378e2407f55": { + "balance": "0x01" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x22af32ea88308575e08326fe58f9af072821cff5", + "data": "0x", + "value": "0x00", + "gas_limit": 200052653, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json new file mode 100644 index 000000000..d13e02c9b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x968c4210528950e49d96feacc9d8f71ce9dd0cf7": { + "nonce": 1, + "code": "0x6000600060006000600073bad828646eb75618bdd15b07bae5f761e84fe919614e20f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0xbad828646eb75618bdd15b07bae5f761e84fe919": { + "nonce": 1, + "code": "0x600060005260006001601f6000f550" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x968c4210528950e49d96feacc9d8f71ce9dd0cf7", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json new file mode 100644 index 000000000..e6da93a8d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x3f48525deeff730b55641b8c167035de421e00e7": { + "nonce": 1, + "code": "0x6000600060006000600073f45668b615cda17f6291038243534145b19bac7a614e20f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf45668b615cda17f6291038243534145b19bac7a": { + "nonce": 1, + "code": "0x60006000526001601f6000f050" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x3f48525deeff730b55641b8c167035de421e00e7", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json new file mode 100644 index 000000000..b76ba4a03 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x31a6b906c71e604f8cedfdc8ec34f21fab005a2c": { + "nonce": 1, + "code": "0x6000600060006000f5" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd2f0b0725f3abe88cc7b0f1e95bc1988642b3573": { + "nonce": 1, + "code": "0x600060006000600060007331a6b906c71e604f8cedfdc8ec34f21fab005a2c6202fc1bf1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd2f0b0725f3abe88cc7b0f1e95bc1988642b3573", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json new file mode 100644 index 000000000..892b30a08 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8d6e42cd3fc67c90728bd4a8947e5705cdbff1d7": { + "nonce": 1, + "code": "0x60006000600060006000739c4d33c33c1c2feea130a11f2cdfa1bee80056b16202fc2ff1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0x9c4d33c33c1c2feea130a11f2cdfa1bee80056b1": { + "nonce": 1, + "code": "0x60006000526000602060006000f5" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8d6e42cd3fc67c90728bd4a8947e5705cdbff1d7", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json new file mode 100644 index 000000000..662633f45 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x04b758daed4e31b9762bcc4f63266c1ddfd82804": { + "nonce": 1, + "code": "0x6000600060006000600073a01c1b31989a6fdf79d3059ea4b3300591b794d56202fc18f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa01c1b31989a6fdf79d3059ea4b3300591b794d5": { + "nonce": 1, + "code": "0x600060006000f0" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x04b758daed4e31b9762bcc4f63266c1ddfd82804", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json new file mode 100644 index 000000000..3754e8a06 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json @@ -0,0 +1,35 @@ +{ + "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4007a2eaaef732f31a3ba0c270f10d747e338520": { + "nonce": 1, + "code": "0x6000600052602060006000f0" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8236ba8b4225119687d5e3318f1e15d3e4c11418": { + "nonce": 1, + "code": "0x60006000600060006000734007a2eaaef732f31a3ba0c270f10d747e3385206202fc26f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8236ba8b4225119687d5e3318f1e15d3e4c11418", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..47ff02b97 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x34be4080fa3a9e9ff22c2ec49e0b403dc385656c": { + "nonce": 1, + "code": "0x7f60006000fd000000000000000000000000000000000000000000000000000000600052600560006000f0600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x34be4080fa3a9e9ff22c2ec49e0b403dc385656c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..bcd451c1f --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825": { + "nonce": 1, + "code": "0x60006000600060006000305af1506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json new file mode 100644 index 000000000..b5c1e6325 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json new file mode 100644 index 000000000..93b3a583e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json new file mode 100644 index 000000000..6885f9f03 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json new file mode 100644 index 000000000..74db00c08 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json new file mode 100644 index 000000000..a449aac60 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json new file mode 100644 index 000000000..cfa1015c5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json new file mode 100644 index 000000000..bbb9567f5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json new file mode 100644 index 000000000..4b2e8d198 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json new file mode 100644 index 000000000..7576a4abd --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json new file mode 100644 index 000000000..efa9b76a1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2ee362aadf03068c89e52f09623d640781d902c2": { + "nonce": 1, + "code": "0x6000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json new file mode 100644 index 000000000..efc258553 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_with_reservoir_fork_Amsterdam_state_test_create", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x08690f601113d9f3d72976b307ee0bc961d897c0": { + "nonce": 1, + "code": "0x60006000526000600160006000f011600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json new file mode 100644 index 000000000..50508c687 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json @@ -0,0 +1,27 @@ +{ + "name": "test_create_with_reservoir_fork_Amsterdam_state_test_create2", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { + "nonce": 1, + "code": "0x600060005260006000600160006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json new file mode 100644 index 000000000..32e0ca0dc --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json @@ -0,0 +1,31 @@ +{ + "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x25da3158c44fd21895e84d8f3908acf61c089437": { + "nonce": 1, + "code": "0x60006000600160006000335af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xad110f9fa7b6b0f9a9c911e514c0616473e51e39": { + "nonce": 1, + "code": "0x36603758015760016000556001600155600060006000600060007325da3158c44fd21895e84d8f3908acf61c0894375af160025500600f5801565b60006000556000600155005b" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xad110f9fa7b6b0f9a9c911e514c0616473e51e39", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json new file mode 100644 index 000000000..d9aeac58a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json @@ -0,0 +1,31 @@ +{ + "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x01096b94dd617fe83942d88670785f010f6a98ba": { + "nonce": 1, + "code": "0x60006000600160006000335af15060006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe76309b881efcefeb092c92c812e5c6ace40764d": { + "nonce": 1, + "code": "0x36603758015760016000556001600155600060006000600060007301096b94dd617fe83942d88670785f010f6a98ba5af160025500600f5801565b60006000556000600155005b" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe76309b881efcefeb092c92c812e5c6ace40764d", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json new file mode 100644 index 000000000..ffa5bff86 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json @@ -0,0 +1,31 @@ +{ + "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x25da3158c44fd21895e84d8f3908acf61c089437": { + "nonce": 1, + "code": "0x60006000600160006000335af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6ed3b5f3632e4336b73347899b8b5b9da544be20": { + "nonce": 1, + "code": "0x36603b58015760016000556001600155600060006000600060007325da3158c44fd21895e84d8f3908acf61c0894375af160025560006000fd600f5801565b60006000556000600155005b" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6ed3b5f3632e4336b73347899b8b5b9da544be20", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..227f429e9 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x30f1585a288bca56a03a8e5cc2e12d2ef804b438": { + "nonce": 1, + "code": "0x60016000556002600155600360025560046003556005600455600660055500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfc9b6d6b58b8fe2bb98ab56d76071499dab8db27": { + "nonce": 1, + "code": "0x60006000600060007330f1585a288bca56a03a8e5cc2e12d2ef804b4385af450" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfc9b6d6b58b8fe2bb98ab56d76071499dab8db27", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..ef1432512 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_delegatecall_reservoir_passing_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x3fcbdf3601e9ce1a3c02ffcc0543e60c55d9548b": { + "nonce": 1, + "code": "0x600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f4" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x3fcbdf3601e9ce1a3c02ffcc0543e60c55d9548b", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..4f786017c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x315988212a396700879340d79c907964ffaf2dd6": { + "nonce": 1, + "code": "0x5a6000556001600055" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x315988212a396700879340d79c907964ffaf2dd6", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..04bf5fcb5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200006776, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..d6fd3bd66 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..2a4de988f --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..ed11d6d93 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json new file mode 100644 index 000000000..699273f03 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x20fcc0916f561c4de94b960c66095b0e3352c689": { + "nonce": 1, + "code": "0x36600060003760006000366000600073fa882ebef47fd1ada1c326c66f97cce6fdbbbffd6201be5bf100" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfa882ebef47fd1ada1c326c66f97cce6fdbbbffd": { + "nonce": 1, + "code": "0x36600060003762c0ffee3660006000f560005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x20fcc0916f561c4de94b960c66095b0e3352c689", + "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json new file mode 100644 index 000000000..7e46d4a8a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xafdada08181d5dbaacf18788b85122aa0d854554": { + "nonce": 1, + "code": "0x36600060003760006000366000600073fa882ebef47fd1ada1c326c66f97cce6fdbbbffd6201be5af100" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfa882ebef47fd1ada1c326c66f97cce6fdbbbffd": { + "nonce": 1, + "code": "0x36600060003762c0ffee3660006000f560005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xafdada08181d5dbaacf18788b85122aa0d854554", + "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json new file mode 100644 index 000000000..7c10a8b84 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x747c2e276047c0d2b7e6a4d8547efedcdb7f09b5": { + "nonce": 1, + "code": "0x36600060003760006000366000600073fd184434582c1cae53df720d5da5e5374c6c64b962015e58f100" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfd184434582c1cae53df720d5da5e5374c6c64b9": { + "nonce": 1, + "code": "0x3660006000373660006000f060005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x747c2e276047c0d2b7e6a4d8547efedcdb7f09b5", + "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json new file mode 100644 index 000000000..5982a48f0 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf42013f94f3e0d49fd4ad3240ff668c0284ac29f": { + "nonce": 1, + "code": "0x36600060003760006000366000600073fd184434582c1cae53df720d5da5e5374c6c64b962015e57f100" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfd184434582c1cae53df720d5da5e5374c6c64b9": { + "nonce": 1, + "code": "0x3660006000373660006000f060005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf42013f94f3e0d49fd4ad3240ff668c0284ac29f", + "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..695ea238d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_nested_calls_reservoir_passing_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0ecc504ac0640d87e828e30ed14b041bb6f1a48d": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef62030d40f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5829db418ba6428a4817553e0a237b3d88ae9424": { + "nonce": 1, + "code": "0x60006000600060006000730ecc504ac0640d87e828e30ed14b041bb6f1a48d620493e0f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5829db418ba6428a4817553e0a237b3d88ae9424", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..12603cdd7 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x981f21093384d81af297acec122f1e6758d1e1f4": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000000000000060016000f36000526005601b6000f050" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x981f21093384d81af297acec122f1e6758d1e1f4", + "data": "0x", + "value": "0x00", + "gas_limit": 200052851, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json new file mode 100644 index 000000000..47ee87c28 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json @@ -0,0 +1,79 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x053cb57511a8f413073b9c1d4edef9d4debcd928": { + "nonce": 1, + "code": "0x6000600060006000600073c5ecec6304ce12928c6a67cabb08d256a006c5315af15000" + }, + "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21": { + "nonce": 1, + "code": "0x60006000600060006000737158469335c38bc1d1a236bc9f2ba5f3027bd6075af15000" + }, + "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5468c4cf3cebdc08565e2731b0678f8bdd0428e2": { + "nonce": 1, + "code": "0x60006000600060006000735e213dd0505c705179c3ca8f26174dc4c67f5da75af15000" + }, + "0x569044e2f76aae923eacb369c31afbe3358095b5": { + "nonce": 1, + "code": "0x6000600060006000600073053cb57511a8f413073b9c1d4edef9d4debcd9285af15000" + }, + "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { + "nonce": 1, + "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" + }, + "0x5e213dd0505c705179c3ca8f26174dc4c67f5da7": { + "nonce": 1, + "code": "0x6000600060006000600073e0e7ff869e4a073bf8b9a266cd40d5e5504176845af15000" + }, + "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { + "nonce": 1, + "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" + }, + "0x7158469335c38bc1d1a236bc9f2ba5f3027bd607": { + "nonce": 1, + "code": "0x60006000600060006000735f4eeb3c9c7db8445457a762ccaaf3924d0a40345af15000" + }, + "0x9fb2a61c28e965b67bad0f1a265da1d7beda1d62": { + "nonce": 1, + "code": "0x6000600060006000600073569044e2f76aae923eacb369c31afbe3358095b55af15000" + }, + "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { + "nonce": 1, + "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xc5ecec6304ce12928c6a67cabb08d256a006c531": { + "nonce": 1, + "code": "0x6000600060006000600073113cd9a7a08ad3edbb3dfab7696233f53cc98d215af15000" + }, + "0xe0e7ff869e4a073bf8b9a266cd40d5e550417684": { + "nonce": 1, + "code": "0x60006000600060006000739fb2a61c28e965b67bad0f1a265da1d7beda1d625af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5468c4cf3cebdc08565e2731b0678f8bdd0428e2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json new file mode 100644 index 000000000..221f5d924 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0003ba5491594ab7b42b572e036b869fef6719fb": { + "nonce": 1, + "code": "0x6000600060006000600073667731961164968220cf97f105947de66aa5bfd55af15000" + }, + "0x1af1a7588cff04d361cd1bcf9076594a60b983f8": { + "nonce": 1, + "code": "0x60006000600060006000734595d106902775aaf3c152ca65045b042cd0357d5af15000" + }, + "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { + "nonce": 1, + "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" + }, + "0x4066f1f675e6c984d91709c3dbf02b7b500b0ff5": { + "nonce": 1, + "code": "0x60006000600060006000737cb7da08ac424947a7b49f71861a41c7b5fd05765af15000" + }, + "0x4595d106902775aaf3c152ca65045b042cd0357d": { + "nonce": 1, + "code": "0x6000600060006000600073b3fcedac2ed3a5eb6849401ada6a49a573ddaa6a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x667731961164968220cf97f105947de66aa5bfd5": { + "nonce": 1, + "code": "0x6000600060006000600073e00a48bf2af4aee51c02c8e53c15de9a450db3e85af15000" + }, + "0x7cb7da08ac424947a7b49f71861a41c7b5fd0576": { + "nonce": 1, + "code": "0x60006000600060006000731af1a7588cff04d361cd1bcf9076594a60b983f85af15000" + }, + "0x9825e48625413478150ba42de46b5ae120c0ab7a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a": { + "nonce": 1, + "code": "0x6000600060006000600073e7b23f996831b470eb579585972f4608ddb46ff55af15000" + }, + "0xe00a48bf2af4aee51c02c8e53c15de9a450db3e8": { + "nonce": 1, + "code": "0x60006000600060006000734066f1f675e6c984d91709c3dbf02b7b500b0ff55af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xe7b23f996831b470eb579585972f4608ddb46ff5": { + "nonce": 1, + "code": "0x6000600060006000600073fc0a156d0f29a14b2d217623d0e7f13ab70eb2d15af15000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { + "nonce": 1, + "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0003ba5491594ab7b42b572e036b869fef6719fb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json new file mode 100644 index 000000000..7d4e6e671 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0551d99e64f665f96a535ea329b0b7730b256f84": { + "nonce": 1, + "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" + }, + "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { + "nonce": 1, + "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" + }, + "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { + "nonce": 1, + "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x440df445bc999c4a7ad434728514b18d49af1f76": { + "nonce": 1, + "code": "0x60006000600060006000737b9a4ebbbcaa3b5ed869adf6cb131a885347deb95af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x595ad51569abfc814f56e2025df8465bc7c96daa": { + "nonce": 1, + "code": "0x6000600060006000600073f840c69a775450661d3faa91f9dc8677eb0bf5425af15000" + }, + "0x768599d3d827a10afdd46c7ee74e043cb491b3bb": { + "nonce": 1, + "code": "0x6000600060006000600073440df445bc999c4a7ad434728514b18d49af1f765af15000" + }, + "0x7a3f53d68397cf003560f9713a2452974812fd5f": { + "nonce": 1, + "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" + }, + "0x7b9a4ebbbcaa3b5ed869adf6cb131a885347deb9": { + "nonce": 1, + "code": "0x6000600060006000600073595ad51569abfc814f56e2025df8465bc7c96daa5af15000" + }, + "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { + "nonce": 1, + "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" + }, + "0x84946fbc7842859adbd3644faa294e443c0232df": { + "nonce": 1, + "code": "0x60006000600060006000737a3f53d68397cf003560f9713a2452974812fd5f5af15000" + }, + "0xd6d787820fcc0f2b5b345d2b4026cc455431413b": { + "nonce": 1, + "code": "0x600060006000600060007384946fbc7842859adbd3644faa294e443c0232df5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf840c69a775450661d3faa91f9dc8677eb0bf542": { + "nonce": 1, + "code": "0x6000600060006000600073d6d787820fcc0f2b5b345d2b4026cc455431413b5af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x768599d3d827a10afdd46c7ee74e043cb491b3bb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json new file mode 100644 index 000000000..7aa94188e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json @@ -0,0 +1,43 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { + "nonce": 1, + "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" + }, + "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { + "nonce": 1, + "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" + }, + "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { + "nonce": 1, + "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json new file mode 100644 index 000000000..4c0c6df5d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json @@ -0,0 +1,39 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { + "nonce": 1, + "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9825e48625413478150ba42de46b5ae120c0ab7a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { + "nonce": 1, + "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json new file mode 100644 index 000000000..344458457 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json @@ -0,0 +1,39 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0551d99e64f665f96a535ea329b0b7730b256f84": { + "nonce": 1, + "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" + }, + "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { + "nonce": 1, + "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { + "nonce": 1, + "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json new file mode 100644 index 000000000..ec5c26b55 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json @@ -0,0 +1,51 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21": { + "nonce": 1, + "code": "0x60006000600060006000737158469335c38bc1d1a236bc9f2ba5f3027bd6075af15000" + }, + "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { + "nonce": 1, + "code": "0x00" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { + "nonce": 1, + "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" + }, + "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { + "nonce": 1, + "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" + }, + "0x7158469335c38bc1d1a236bc9f2ba5f3027bd607": { + "nonce": 1, + "code": "0x60006000600060006000735f4eeb3c9c7db8445457a762ccaaf3924d0a40345af15000" + }, + "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { + "nonce": 1, + "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json new file mode 100644 index 000000000..b6211e441 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json @@ -0,0 +1,47 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { + "nonce": 1, + "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9825e48625413478150ba42de46b5ae120c0ab7a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a": { + "nonce": 1, + "code": "0x6000600060006000600073e7b23f996831b470eb579585972f4608ddb46ff55af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xe7b23f996831b470eb579585972f4608ddb46ff5": { + "nonce": 1, + "code": "0x6000600060006000600073fc0a156d0f29a14b2d217623d0e7f13ab70eb2d15af15000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { + "nonce": 1, + "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json new file mode 100644 index 000000000..2626d9016 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json @@ -0,0 +1,47 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0551d99e64f665f96a535ea329b0b7730b256f84": { + "nonce": 1, + "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" + }, + "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { + "nonce": 1, + "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" + }, + "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { + "nonce": 1, + "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x7a3f53d68397cf003560f9713a2452974812fd5f": { + "nonce": 1, + "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" + }, + "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { + "nonce": 1, + "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x7a3f53d68397cf003560f9713a2452974812fd5f", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json new file mode 100644 index 000000000..a9d8f43ce --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json @@ -0,0 +1,79 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { + "nonce": 1, + "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" + }, + "0x125a27e3431a378dd32b805d1eb035ea603af917": { + "nonce": 1, + "code": "0x6000600060006000600073af98241cb31fccd9afe08ba6e94cf71d017875805af15000" + }, + "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { + "nonce": 1, + "code": "0x600060006000f05000" + }, + "0x2e4775e29f96e843a5f9ce77698ab8877763aefe": { + "nonce": 1, + "code": "0x600060006000600060007368cd2fbe38167708072637d53fb335f4d292ab2f5af15000" + }, + "0x340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce": { + "nonce": 1, + "code": "0x6000600060006000600073d8e4f3ab4a9131945355462a94714b714da61ca45af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x68cd2fbe38167708072637d53fb335f4d292ab2f": { + "nonce": 1, + "code": "0x6000600060006000600073ea276b22eb502fd9743053ec1e2a9fee96dc49175af15000" + }, + "0x86715d19d83c63b8f13ce14db52ed6bd140c723e": { + "nonce": 1, + "code": "0x6000600060006000600073125a27e3431a378dd32b805d1eb035ea603af9175af15000" + }, + "0xaa08db400382913932b5337b5b9f58083cdf9923": { + "nonce": 1, + "code": "0x00" + }, + "0xaf98241cb31fccd9afe08ba6e94cf71d01787580": { + "nonce": 1, + "code": "0x6000600060006000600073d95df29596ec5594256fd86c85bfcfecd8f9dd7e5af15000" + }, + "0xd8e4f3ab4a9131945355462a94714b714da61ca4": { + "nonce": 1, + "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af15000" + }, + "0xd95df29596ec5594256fd86c85bfcfecd8f9dd7e": { + "nonce": 1, + "code": "0x60006000600060006000732e4775e29f96e843a5f9ce77698ab8877763aefe5af15000" + }, + "0xd9e23acd2ad6cd9fab5c78ba1dc86f1796036070": { + "nonce": 1, + "code": "0x600060006000600060007386715d19d83c63b8f13ce14db52ed6bd140c723e5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xea276b22eb502fd9743053ec1e2a9fee96dc4917": { + "nonce": 1, + "code": "0x6000600060006000600073340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce5af15000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd9e23acd2ad6cd9fab5c78ba1dc86f1796036070", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json new file mode 100644 index 000000000..337f5576d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { + "nonce": 1, + "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x517a726f8d693dc4aed7c032b5966211f5bd5e70": { + "nonce": 1, + "code": "0x6000600060006000600073744386689b43c80ac4d335c3783af4b06c46cf075af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x525b7c655228cb70c7fef4a7968323521a663f04": { + "nonce": 1, + "code": "0x6000600060006000600073bae123dc020b26f6257c336fa1f4e7f2a5a5fccf5af15000" + }, + "0x54041e3d292437d1643b29754e9e083f1768c00e": { + "nonce": 1, + "code": "0x6000600060006000600073c1854be81610463a79ca04b92ea63ba968f5af725af15000" + }, + "0x602994eb359e43b5bfc97fcf003be7d96bfd9691": { + "nonce": 1, + "code": "0x6000600060006000600073b6f864bf21a2bc9338850eb9af60d734287ea64d5af15000" + }, + "0x61e2c37aa43a458bc7458798179de42f1904d57a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" + }, + "0x744386689b43c80ac4d335c3783af4b06c46cf07": { + "nonce": 1, + "code": "0x600060006000600060007354041e3d292437d1643b29754e9e083f1768c00e5af15000" + }, + "0xb6f864bf21a2bc9338850eb9af60d734287ea64d": { + "nonce": 1, + "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af15000" + }, + "0xbae123dc020b26f6257c336fa1f4e7f2a5a5fccf": { + "nonce": 1, + "code": "0x6000600060006000600073dc3b4e24fbaa72dabbaf79304995970c83d952285af15000" + }, + "0xc1854be81610463a79ca04b92ea63ba968f5af72": { + "nonce": 1, + "code": "0x6000600060006000600073525b7c655228cb70c7fef4a7968323521a663f045af15000" + }, + "0xdc3b4e24fbaa72dabbaf79304995970c83d95228": { + "nonce": 1, + "code": "0x6000600060006000600073f039829f33edd9832f8c02f2c7bb8e7fa5b2a9bc5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf039829f33edd9832f8c02f2c7bb8e7fa5b2a9bc": { + "nonce": 1, + "code": "0x6000600060006000600073602994eb359e43b5bfc97fcf003be7d96bfd96915af15000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x517a726f8d693dc4aed7c032b5966211f5bd5e70", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json new file mode 100644 index 000000000..7d8d5aad5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2774ad7d5234681b2c0d65b2fca85ab39b9b91a1": { + "nonce": 1, + "code": "0x6000600060006000600073833905ba8cd7ad5c1c98476f86c0628be148ebea5af15000" + }, + "0x2b31bf922a1db1218ec41b676821bc34ae783281": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" + }, + "0x382dadf608e6ac15017cce80c1c608e96a8f3788": { + "nonce": 1, + "code": "0x6000600060006000600073d8ccf52b85eb2c7c59c1792ad1021d390120d79c5af15000" + }, + "0x4d92182b5a4d51e480cba616caa0a496f4efbda8": { + "nonce": 1, + "code": "0x6000600060006000600073c8790b08292677361b19ed416303aadfcfefc4db5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5d5da279fe0de991d67ada4beee9f3362bec2ead": { + "nonce": 1, + "code": "0x60006000600060006000734d92182b5a4d51e480cba616caa0a496f4efbda85af15000" + }, + "0x833905ba8cd7ad5c1c98476f86c0628be148ebea": { + "nonce": 1, + "code": "0x60006000600060006000735d5da279fe0de991d67ada4beee9f3362bec2ead5af15000" + }, + "0x8753f8aba8a5de40497bda3e9360642df4b6da98": { + "nonce": 1, + "code": "0x6000600060006000600073382dadf608e6ac15017cce80c1c608e96a8f37885af15000" + }, + "0xb1f4479dbaa6052a0991a02e1a0e970db0863cc9": { + "nonce": 1, + "code": "0x60006000600060006000732774ad7d5234681b2c0d65b2fca85ab39b9b91a15af15000" + }, + "0xc8790b08292677361b19ed416303aadfcfefc4db": { + "nonce": 1, + "code": "0x60006000600060006000738753f8aba8a5de40497bda3e9360642df4b6da985af15000" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xd8ccf52b85eb2c7c59c1792ad1021d390120d79c": { + "nonce": 1, + "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xff091f7082c73c848af84a40e617ae2eb9fa66c2": { + "nonce": 1, + "code": "0x6000600060006000600073b1f4479dbaa6052a0991a02e1a0e970db0863cc95af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xff091f7082c73c848af84a40e617ae2eb9fa66c2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json new file mode 100644 index 000000000..4d76e5faf --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json @@ -0,0 +1,43 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { + "nonce": 1, + "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" + }, + "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { + "nonce": 1, + "code": "0x600060006000f05000" + }, + "0x4b3b27f06c23f88cdef683e65080aa2a6d5fa6bd": { + "nonce": 1, + "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xaa08db400382913932b5337b5b9f58083cdf9923": { + "nonce": 1, + "code": "0x00" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4b3b27f06c23f88cdef683e65080aa2a6d5fa6bd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json new file mode 100644 index 000000000..1afc1d141 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json @@ -0,0 +1,39 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { + "nonce": 1, + "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x61e2c37aa43a458bc7458798179de42f1904d57a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" + }, + "0xd365ba83e1720b20c9fc0919ac037909751d59f9": { + "nonce": 1, + "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd365ba83e1720b20c9fc0919ac037909751d59f9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json new file mode 100644 index 000000000..4dd5f3780 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json @@ -0,0 +1,39 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2b31bf922a1db1218ec41b676821bc34ae783281": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc31d99b57607343a1d2306a80999bdcd583ad294": { + "nonce": 1, + "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc31d99b57607343a1d2306a80999bdcd583ad294", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json new file mode 100644 index 000000000..84b73f1f4 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json @@ -0,0 +1,51 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { + "nonce": 1, + "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" + }, + "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { + "nonce": 1, + "code": "0x600060006000f05000" + }, + "0x310e21851b068ba17ba59a9c71215d510663114a": { + "nonce": 1, + "code": "0x6000600060006000600073340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce": { + "nonce": 1, + "code": "0x6000600060006000600073d8e4f3ab4a9131945355462a94714b714da61ca45af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xaa08db400382913932b5337b5b9f58083cdf9923": { + "nonce": 1, + "code": "0x00" + }, + "0xd8e4f3ab4a9131945355462a94714b714da61ca4": { + "nonce": 1, + "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x310e21851b068ba17ba59a9c71215d510663114a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json new file mode 100644 index 000000000..8b1d39793 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json @@ -0,0 +1,47 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { + "nonce": 1, + "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x602994eb359e43b5bfc97fcf003be7d96bfd9691": { + "nonce": 1, + "code": "0x6000600060006000600073b6f864bf21a2bc9338850eb9af60d734287ea64d5af15000" + }, + "0x61e2c37aa43a458bc7458798179de42f1904d57a": { + "nonce": 1, + "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" + }, + "0xb16e09425098ead08d00ebaeb1ef519a2dc624be": { + "nonce": 1, + "code": "0x6000600060006000600073602994eb359e43b5bfc97fcf003be7d96bfd96915af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0xb6f864bf21a2bc9338850eb9af60d734287ea64d": { + "nonce": 1, + "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb16e09425098ead08d00ebaeb1ef519a2dc624be", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json new file mode 100644 index 000000000..b6ecfec03 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json @@ -0,0 +1,47 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2b31bf922a1db1218ec41b676821bc34ae783281": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" + }, + "0x2bc9cd0edff891c3eb19c8c940ba4d1fb7189a0e": { + "nonce": 1, + "code": "0x6000600060006000600073382dadf608e6ac15017cce80c1c608e96a8f37885af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x382dadf608e6ac15017cce80c1c608e96a8f3788": { + "nonce": 1, + "code": "0x6000600060006000600073d8ccf52b85eb2c7c59c1792ad1021d390120d79c5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xd8ccf52b85eb2c7c59c1792ad1021d390120d79c": { + "nonce": 1, + "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2bc9cd0edff891c3eb19c8c940ba4d1fb7189a0e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json new file mode 100644 index 000000000..8ff090e41 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json @@ -0,0 +1,34 @@ +{ + "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xab5aee4f8102143b17e076232012c5ce8624e0da": { + "nonce": 1, + "code": "0x6000600060006000600073c3cd8b141c1d255b786f6686191e43f748413001612ef6f1" + }, + "0xc3cd8b141c1d255b786f6686191e43f748413001": { + "nonce": 1, + "code": "0x6000600160006000f5" + }, + "0xe7d8cee81bd8c1979af7d7812c78228065a8dee5": { + "balance": "0x01" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xab5aee4f8102143b17e076232012c5ce8624e0da", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json new file mode 100644 index 000000000..6b21d5a2c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json @@ -0,0 +1,34 @@ +{ + "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x7d9ec00f3eed8ede627e8e8da26bd607eaba841c": { + "nonce": 1, + "code": "0x6000600060006000600073c3cd8b141c1d255b786f6686191e43f748413001612ef7f1" + }, + "0xc3cd8b141c1d255b786f6686191e43f748413001": { + "nonce": 1, + "code": "0x6000600160006000f5" + }, + "0xe7d8cee81bd8c1979af7d7812c78228065a8dee5": { + "balance": "0x01" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x7d9ec00f3eed8ede627e8e8da26bd607eaba841c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json new file mode 100644 index 000000000..57d218626 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json @@ -0,0 +1,34 @@ +{ + "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2a61375388141559b52e11dc3cece66a3e4a3cf6": { + "balance": "0x01" + }, + "0x45c43c77ccd9b82b494c776392e722ab2529b9b5": { + "nonce": 1, + "code": "0x6000600060006000600073853d5d321bb83315f6b3dafce43ec7e4157d4980612eedf1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x853d5d321bb83315f6b3dafce43ec7e4157d4980": { + "nonce": 1, + "code": "0x600160006000f0" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x45c43c77ccd9b82b494c776392e722ab2529b9b5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json new file mode 100644 index 000000000..d8640fbdc --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json @@ -0,0 +1,34 @@ +{ + "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2a61375388141559b52e11dc3cece66a3e4a3cf6": { + "balance": "0x01" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x853d5d321bb83315f6b3dafce43ec7e4157d4980": { + "nonce": 1, + "code": "0x600160006000f0" + }, + "0xed4eefcb238f28b838aba2f0f6a73e0b676464ba": { + "nonce": 1, + "code": "0x6000600060006000600073853d5d321bb83315f6b3dafce43ec7e4157d4980612eeef1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xed4eefcb238f28b838aba2f0f6a73e0b676464ba", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json new file mode 100644 index 000000000..6016c4c00 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json @@ -0,0 +1,27 @@ +{ + "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xefb126b3e865f609c6dd9a82c52e119a60884446": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000000000006001600055fe6000526006601a6000f06000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xefb126b3e865f609c6dd9a82c52e119a60884446", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json new file mode 100644 index 000000000..0447b473a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json @@ -0,0 +1,27 @@ +{ + "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5b735edc5956f051f66b55cfb3e20b7899aa8043": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000600160005560006000fd600052600a60166000f06000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5b735edc5956f051f66b55cfb3e20b7899aa8043", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json new file mode 100644 index 000000000..918f72df1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json @@ -0,0 +1,27 @@ +{ + "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xefb126b3e865f609c6dd9a82c52e119a60884446": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000000000006001600055fe6000526006601a6000f06000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xefb126b3e865f609c6dd9a82c52e119a60884446", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json new file mode 100644 index 000000000..2df149851 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json @@ -0,0 +1,27 @@ +{ + "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5b735edc5956f051f66b55cfb3e20b7899aa8043": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000600160005560006000fd600052600a60166000f06000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5b735edc5956f051f66b55cfb3e20b7899aa8043", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..a5fe0bcc3 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json @@ -0,0 +1,40 @@ +{ + "name": "test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x53ba30867bbd50d8066077dd79b1dbad087115f0": { + "nonce": 1, + "code": "0x6000600060006000600073e5a5932a96a75fec7ac2d96786731376406feaca620927c0f16000556001600155" + }, + "0x96336043ed535f3143be4c5d61fa845747280bc0": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005560006000600060006001335af15000" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xe5a5932a96a75fec7ac2d96786731376406feaca": { + "nonce": 1, + "code": "0x34603558015760016000556001600155600060006000600060007396336043ed535f3143be4c5d61fa845747280bc05af150fe60315801565b6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af15060006000556000600155005b" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x53ba30867bbd50d8066077dd79b1dbad087115f0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json new file mode 100644 index 000000000..7430f4581 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json new file mode 100644 index 000000000..b5a895c1c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json new file mode 100644 index 000000000..2ae543aac --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json new file mode 100644 index 000000000..55741a171 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json new file mode 100644 index 000000000..1a07a8c2a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json new file mode 100644 index 000000000..b08727d50 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json new file mode 100644 index 000000000..e171d934a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json new file mode 100644 index 000000000..fb9b4b668 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json new file mode 100644 index 000000000..3f7348d13 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json new file mode 100644 index 000000000..cb8305265 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json @@ -0,0 +1,27 @@ +{ + "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..d52971f37 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_refund_cap_includes_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..4feeb7e7e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3fcd3bb5c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xff5b195b5a743a15a4dd8bef51decbc40f020764": { + "nonce": 1, + "code": "0x7f00000000000000000000000000000000000000000000000000000060016000f36000525a6020526005601b6000f0505a6040526005601b6000f0505a60605260605160405103604051602051030360005500" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xff5b195b5a743a15a4dd8bef51decbc40f020764", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json new file mode 100644 index 000000000..46c270440 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json @@ -0,0 +1,27 @@ +{ + "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json new file mode 100644 index 000000000..ea9d22422 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json @@ -0,0 +1,27 @@ +{ + "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json new file mode 100644 index 000000000..f83d6ff7b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json @@ -0,0 +1,27 @@ +{ + "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..717a16fe6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x97af882916b3473f0f8acdad4deb404d8e0b49e7": { + "nonce": 1, + "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506001600055" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x97af882916b3473f0f8acdad4deb404d8e0b49e7", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..0de2a0e71 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8307bcc4c9612d6d1875d2d97edd850986bd253c": { + "nonce": 1, + "code": "0x60016000556001600155fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfb680a2dc482b540884c4a1aed2a7c5ec920a603": { + "nonce": 1, + "code": "0x60006000600060006000738307bcc4c9612d6d1875d2d97edd850986bd253c6207a120f15060016000556001600155" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfb680a2dc482b540884c4a1aed2a7c5ec920a603", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..40f8b92a6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9e6ec4eb938269f39fa7f791ef62859b45088d14": { + "nonce": 1, + "code": "0x6001600055600160015560006000fd" + }, + "0xd22f0bd65c9173af0826a2106e3fe6e9248e7b1b": { + "nonce": 1, + "code": "0x60006000600060006000739e6ec4eb938269f39fa7f791ef62859b45088d146207a120f15060016000556001600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd22f0bd65c9173af0826a2106e3fe6e9248e7b1b", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..255e7e38a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_reservoir_returned_on_oog_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9e39d16dc2ae00d8edff0816858346d089a62f19": { + "nonce": 1, + "code": "0x6000600060006000600073ec18af3fb3bbdc8967a4d68bf87b5a58053b4bf26064f1506001600055" + }, + "0xec18af3fb3bbdc8967a4d68bf87b5a58053b4bf2": { + "nonce": 1, + "code": "0xfe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x9e39d16dc2ae00d8edff0816858346d089a62f19", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..c3a7c6f1e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_reservoir_returned_on_revert_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4391c0c575a2677adfab1a4ddb038238f9dd01f0": { + "nonce": 1, + "code": "0x600060006000600060007343bbb24495f4107ab75aa339644d77b621ec0ee4620186a0f1506001600055" + }, + "0x43bbb24495f4107ab75aa339644d77b621ec0ee4": { + "nonce": 1, + "code": "0x60006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4391c0c575a2677adfab1a4ddb038238f9dd01f0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json new file mode 100644 index 000000000..cb064f11a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json @@ -0,0 +1,39 @@ +{ + "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { + "nonce": 1, + "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5104e8dfb400fa45528f1939767450df6969319e": { + "nonce": 1, + "code": "0x60006000556000600155600060025560006003556000600455" + }, + "0x7e8dd7bf50aad4bac65ba7009f3a28dc9b5095d6": { + "nonce": 1, + "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45060006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfe8fdcafa1baa1eeb585b46b2aff5d62b454acf0": { + "nonce": 1, + "code": "0x600160005560016001556001600255600160035560016004556000600060006000737e8dd7bf50aad4bac65ba7009f3a28dc9b5095d65af4506001600a556001600b556001600c556001600d556001600e55" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfe8fdcafa1baa1eeb585b46b2aff5d62b454acf0", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json new file mode 100644 index 000000000..4bf4b6af3 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json @@ -0,0 +1,75 @@ +{ + "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0d6dc1f2d223c764873a5e967ca4fcab4625474d": { + "nonce": 1, + "code": "0x600060006000600073c6ae4344e3c79e9b7300f6cb7cb4e1ea8b6279415af45000" + }, + "0x0e492b88ceca0e87c58a8a7731ec7e27a9f1bc6e": { + "nonce": 1, + "code": "0x6000600060006000730d6dc1f2d223c764873a5e967ca4fcab4625474d5af45000" + }, + "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { + "nonce": 1, + "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" + }, + "0x1df45fb03e8fc6903be1a92bcc784428050513fd": { + "nonce": 1, + "code": "0x60016000556001600155600160025560016003556001600455600060006000600073fa7629b29bab864c06d1ef65a74227e67b6667df5af4506001600a556001600b556001600c556001600d556001600e55" + }, + "0x20cd6b7ba966b9ea9889db4666188fd51ce420f0": { + "nonce": 1, + "code": "0x600060006000600073a6ef999b8ed332f940241c7f92fc3595e557e1eb5af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5104e8dfb400fa45528f1939767450df6969319e": { + "nonce": 1, + "code": "0x60006000556000600155600060025560006003556000600455" + }, + "0x6a01c38003a92aea11a96b08fa300a95f91bd3af": { + "nonce": 1, + "code": "0x6000600060006000738625a9441db50bd8d6e6161957087c2fecbdcdcf5af45000" + }, + "0x8625a9441db50bd8d6e6161957087c2fecbdcdcf": { + "nonce": 1, + "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45000" + }, + "0xa6ef999b8ed332f940241c7f92fc3595e557e1eb": { + "nonce": 1, + "code": "0x600060006000600073daa76ffe2f7b1a667cbfce190f46d90a5ae6dc015af45000" + }, + "0xc1a2f388d50af526c677f1f6a4ad26bc67dcab99": { + "nonce": 1, + "code": "0x6000600060006000730e492b88ceca0e87c58a8a7731ec7e27a9f1bc6e5af45000" + }, + "0xc6ae4344e3c79e9b7300f6cb7cb4e1ea8b627941": { + "nonce": 1, + "code": "0x60006000600060007320cd6b7ba966b9ea9889db4666188fd51ce420f05af45000" + }, + "0xdaa76ffe2f7b1a667cbfce190f46d90a5ae6dc01": { + "nonce": 1, + "code": "0x6000600060006000736a01c38003a92aea11a96b08fa300a95f91bd3af5af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfa7629b29bab864c06d1ef65a74227e67b6667df": { + "nonce": 1, + "code": "0x600060006000600073c1a2f388d50af526c677f1f6a4ad26bc67dcab995af45060006000fd" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x1df45fb03e8fc6903be1a92bcc784428050513fd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json new file mode 100644 index 000000000..338ceb360 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json @@ -0,0 +1,47 @@ +{ + "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { + "nonce": 1, + "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5104e8dfb400fa45528f1939767450df6969319e": { + "nonce": 1, + "code": "0x60006000556000600155600060025560006003556000600455" + }, + "0x6a01c38003a92aea11a96b08fa300a95f91bd3af": { + "nonce": 1, + "code": "0x6000600060006000738625a9441db50bd8d6e6161957087c2fecbdcdcf5af45000" + }, + "0x79d2892fe6487ea2a9fba5e84de7ed71694ed6ec": { + "nonce": 1, + "code": "0x6000600060006000736a01c38003a92aea11a96b08fa300a95f91bd3af5af45060006000fd" + }, + "0x8625a9441db50bd8d6e6161957087c2fecbdcdcf": { + "nonce": 1, + "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45000" + }, + "0xd7a970dca038fdb56ec2d0b7b36ff3c71eaa1784": { + "nonce": 1, + "code": "0x6001600055600160015560016002556001600355600160045560006000600060007379d2892fe6487ea2a9fba5e84de7ed71694ed6ec5af4506001600a556001600b556001600c556001600d556001600e55" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd7a970dca038fdb56ec2d0b7b36ff3c71eaa1784", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json new file mode 100644 index 000000000..d057a518e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json @@ -0,0 +1,35 @@ +{ + "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5104e8dfb400fa45528f1939767450df6969319e": { + "nonce": 1, + "code": "0x60006000556000600155600060025560006003556000600455" + }, + "0x6f54c4d99a08c1c7e6b8d65b4fd338996e587586": { + "nonce": 1, + "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45060006000fd" + }, + "0xb980ec1278699297a811e6a7f34d27d7cb686cda": { + "nonce": 1, + "code": "0x600160005560016001556001600255600160035560016004556000600060006000736f54c4d99a08c1c7e6b8d65b4fd338996e5875865af4506001600a556001600b556001600c556001600d556001600e55" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb980ec1278699297a811e6a7f34d27d7cb686cda", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..fbe61bc53 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6ab6b2485e767ba2f8f5c0526618184677377daa": { + "nonce": 1, + "code": "0x6000600060006000600073a2584bf1bb55ae3c006de0efdf56872a27544bf862061a80f16000556001600155" + }, + "0xa2584bf1bb55ae3c006de0efdf56872a27544bf8": { + "nonce": 1, + "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af150fe" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6ab6b2485e767ba2f8f5c0526618184677377daa", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..342e7ab27 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1": { + "nonce": 1, + "balance": "0x01", + "code": "0x73c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..f61a135aa --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1": { + "nonce": 1, + "balance": "0x01", + "code": "0x73c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1", + "data": "0x", + "value": "0x00", + "gas_limit": 200054900, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json new file mode 100644 index 000000000..e11aa2705 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json new file mode 100644 index 000000000..d0d779c9b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json new file mode 100644 index 000000000..b7ee26d42 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json new file mode 100644 index 000000000..1a31f2ef7 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json new file mode 100644 index 000000000..8d20d13c6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json new file mode 100644 index 000000000..73ca1c26b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json new file mode 100644 index 000000000..212e5aee6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json new file mode 100644 index 000000000..5f5e08e0b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json new file mode 100644 index 000000000..4232a5b90 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json new file mode 100644 index 000000000..fb2fc7d06 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf98202f4ec103ee8ed7218d60753af742278537e": { + "nonce": 1, + "balance": "0x01", + "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json new file mode 100644 index 000000000..eb0cefdfe --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { + "nonce": 1, + "balance": "0x01", + "code": "0x61deadff" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x895e76ae02c191381f7185dadef7dc9e0eae06b5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json new file mode 100644 index 000000000..d1961d14b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { + "nonce": 1, + "balance": "0x01", + "code": "0x61deadff" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x895e76ae02c191381f7185dadef7dc9e0eae06b5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..96ab1d9a2 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json @@ -0,0 +1,36 @@ +{ + "name": "test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9085a5d372760f4c4d295ef86317897367e479b3": { + "nonce": 1, + "code": "0x600060006000600060007396e10c7537ed10d01ff45bdb6c4740fb89ed5c1362030f9af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0x96e10c7537ed10d01ff45bdb6c4740fb89ed5c13": { + "nonce": 1, + "balance": "0x01", + "code": "0x61beefff" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x9085a5d372760f4c4d295ef86317897367e479b3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..a0583ea61 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json @@ -0,0 +1,32 @@ +{ + "name": "test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { + "nonce": 1, + "balance": "0x01", + "code": "0x61deadff" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfbb85e79c393dc0360ab6104bf657d70699d2540": { + "nonce": 1, + "code": "0x6000600060006000600073895e76ae02c191381f7185dadef7dc9e0eae06b55af15060006000fd" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfbb85e79c393dc0360ab6104bf657d70699d2540", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..aa065d2c1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json @@ -0,0 +1,28 @@ +{ + "name": "test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x892561f6d5f4204eb4892b936de9e93ef89b726a": { + "nonce": 1, + "balance": "0x01", + "code": "0x7f30ff000000000000000000000000000000000000000000000000000000000000600052600260006001f050" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x892561f6d5f4204eb4892b936de9e93ef89b726a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..99f7d83c4 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4c644737fbd0f4c3ed81e7978ef771cffb2cd623": { + "nonce": 1, + "code": "0x61deadff" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x4c644737fbd0f4c3ed81e7978ef771cffb2cd623", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..66fffe05e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5ec2961b7c04481e954aac60dbe3db73647a27a5": { + "nonce": 1, + "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506001600055" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5ec2961b7c04481e954aac60dbe3db73647a27a5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..f67adbce1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2a3649cfcbdab2b2df29f2179601e6bb016610f9": { + "nonce": 1, + "code": "0x6000600060006000600073e050ac2e4d9a47a60c134ed4b4973c975ab265cc620927c0f16000556001600155" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6a3af8fabbd77d2eb3816ad8db94d6dfc4a3aaa8": { + "nonce": 1, + "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af1506000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af15000" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xe050ac2e4d9a47a60c134ed4b4973c975ab265cc": { + "nonce": 1, + "code": "0x600160005560006000600060006000736a3af8fabbd77d2eb3816ad8db94d6dfc4a3aaa85af150fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2a3649cfcbdab2b2df29f2179601e6bb016610f9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..e9ffadb6d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json @@ -0,0 +1,30 @@ +{ + "name": "test_sstore_clear_refund_reversal_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf05d9e96149e1e67cce4d42c4ee70ac95428020c": { + "nonce": 1, + "code": "0x60006000556002600055", + "storage": { + "0x00": "0x01" + } + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf05d9e96149e1e67cce4d42c4ee70ac95428020c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..e8d476a40 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_direct_call_same_contract_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json new file mode 100644 index 000000000..01443d197 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { + "nonce": 1, + "code": "0x60016000556001600155600160025560016003556001600455" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json new file mode 100644 index 000000000..20120753d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json new file mode 100644 index 000000000..736f154ba --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x617bea927cf37c4412e3fce4f81e569abdc48455": { + "nonce": 1, + "code": "0x6001600055600160015560016002556001600355600160045560016005556001600655600160075560016008556001600955" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x617bea927cf37c4412e3fce4f81e569abdc48455", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..10cf9a8e4 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json @@ -0,0 +1,30 @@ +{ + "name": "test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xeff502b1e5727e779185bcd40007a2016c533b4d": { + "nonce": 1, + "code": "0x6002600055", + "storage": { + "0x00": "0x01" + } + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xeff502b1e5727e779185bcd40007a2016c533b4d", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..6b90e12e6 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json @@ -0,0 +1,30 @@ +{ + "name": "test_sstore_nonzero_to_zero_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x22d339df985a054d335af73613545d6008566b37": { + "nonce": 1, + "code": "0x6000600055", + "storage": { + "0x00": "0x01" + } + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x22d339df985a054d335af73613545d6008566b37", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json new file mode 100644 index 000000000..adbb7142b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { + "nonce": 1, + "code": "0x3660006000373660006000f0600055" + }, + "0xe6a324ee15bf48d590a092c37bff4e5c87cdd331": { + "nonce": 1, + "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b00af1" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe6a324ee15bf48d590a092c37bff4e5c87cdd331", + "data": "0x610001600081600b8239f300", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json new file mode 100644 index 000000000..fdfbf95af --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json @@ -0,0 +1,31 @@ +{ + "name": "test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x40738b6435c17fe77e4996fa9c5ed1d8336ee81f": { + "nonce": 1, + "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b009f1" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { + "nonce": 1, + "code": "0x3660006000373660006000f0600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x40738b6435c17fe77e4996fa9c5ed1d8336ee81f", + "data": "0x610001600081600b8239f300", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..aac03848a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { + "nonce": 1, + "code": "0x3660006000373660006000f0600055" + }, + "0xb3142ba4ad58a0f6e68805f7f855b4f7b6142182": { + "nonce": 1, + "code": "0x6001600055600160015560016002556001600355" + }, + "0xf083cf5ff7e72c6cd483173256c7082088409f7d": { + "nonce": 1, + "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b009f1506000600060006000600073b3142ba4ad58a0f6e68805f7f855b4f7b614218262025093f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf083cf5ff7e72c6cd483173256c7082088409f7d", + "data": "0x610001600081600b8239f300", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json new file mode 100644 index 000000000..17e21d5ec --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json new file mode 100644 index 000000000..e6c2fe0a7 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json new file mode 100644 index 000000000..8793d8709 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json new file mode 100644 index 000000000..b574e8c96 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json new file mode 100644 index 000000000..71297326d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json new file mode 100644 index 000000000..00c58ae43 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json new file mode 100644 index 000000000..1ff4cc522 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json new file mode 100644 index 000000000..6f42e6f72 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json new file mode 100644 index 000000000..28b6d4cd4 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json new file mode 100644 index 000000000..c47c82edb --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json new file mode 100644 index 000000000..7fd2c6c7c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa0c52572fa5328e29f88edeec85dcb351e52b3d2": { + "nonce": 1, + "code": "0x6000600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xcd5508542374230140d5034f296cc69db8bf307b": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xa0c52572fa5328e29f88edeec85dcb351e52b3d2", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json new file mode 100644 index 000000000..e5b63e5d0 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa8444717090cd23330d08d9e87bf42d227d1a203": { + "nonce": 1, + "code": "0x6000600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xcd5508542374230140d5034f296cc69db8bf307b": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xa8444717090cd23330d08d9e87bf42d227d1a203", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json new file mode 100644 index 000000000..1db173531 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xcd5508542374230140d5034f296cc69db8bf307b": { + "nonce": 1, + "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" + }, + "0xd11563b17bd6259fe338a6974845ed64d4373b77": { + "nonce": 1, + "code": "0x6001600055600060005500" + }, + "0xda705de478c87cceb6bc29ba16ed48a4be22a297": { + "nonce": 1, + "code": "0x600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xda705de478c87cceb6bc29ba16ed48a4be22a297", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json new file mode 100644 index 000000000..15cc5793c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x502d87dd8fc0a4b3389e1f3cf45b358ca65931bf": { + "nonce": 1, + "code": "0x600160005560006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x502d87dd8fc0a4b3389e1f3cf45b358ca65931bf", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json new file mode 100644 index 000000000..14d2cd1fa --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json @@ -0,0 +1,71 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x06a3a0082119a709a30e20f272a4f6acf1a4a188": { + "nonce": 1, + "code": "0x60006000600060006000730ecedbbade13d941b9a5a3cae25d460d37c071c25af25000" + }, + "0x0e32f98973de4965e5a94c046df0719cf287e4d3": { + "nonce": 1, + "code": "0x60006000600060006000731c574c3d836d61128c8700321f2d85c5e6027fae5af25000" + }, + "0x0ecedbbade13d941b9a5a3cae25d460d37c071c2": { + "nonce": 1, + "code": "0x60006000600060006000730e32f98973de4965e5a94c046df0719cf287e4d35af25000" + }, + "0x1c3d753788debf1c72853154110a4266671d5fb3": { + "nonce": 1, + "code": "0x600060006000600060007306a3a0082119a709a30e20f272a4f6acf1a4a1885af25000" + }, + "0x1c574c3d836d61128c8700321f2d85c5e6027fae": { + "nonce": 1, + "code": "0x6000600060006000600073200ccb62dcea9ceb6e6c5120fc41169ced10cade5af25000" + }, + "0x200ccb62dcea9ceb6e6c5120fc41169ced10cade": { + "nonce": 1, + "code": "0x6000600060006000600073c1a8eb07a893d6b77fb8dca17f0609fd544173715af25000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { + "nonce": 1, + "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" + }, + "0xc1a8eb07a893d6b77fb8dca17f0609fd54417371": { + "nonce": 1, + "code": "0x6000600060006000600073ce2b8b765a324df441554639c63f51041ecf41735af25000" + }, + "0xce2b8b765a324df441554639c63f51041ecf4173": { + "nonce": 1, + "code": "0x6000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af25000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfcd7bb271a3072c2f0829600a7220a4fd5a6c5fb": { + "nonce": 1, + "code": "0x600160005560006000600060006000731c3d753788debf1c72853154110a4266671d5fb35af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfcd7bb271a3072c2f0829600a7220a4fd5a6c5fb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json new file mode 100644 index 000000000..9550912b8 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json @@ -0,0 +1,43 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0x8a44f89da03e1ccdb1863429b2df1aa33551b45c": { + "nonce": 1, + "code": "0x60016000556000600060006000600073ce2b8b765a324df441554639c63f51041ecf41735af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { + "nonce": 1, + "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" + }, + "0xce2b8b765a324df441554639c63f51041ecf4173": { + "nonce": 1, + "code": "0x6000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af25000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x8a44f89da03e1ccdb1863429b2df1aa33551b45c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json new file mode 100644 index 000000000..41bac701a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x27c978b7268a99f80653ef0c370f2fb577fb8ec5": { + "nonce": 1, + "code": "0x60016000556000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { + "nonce": 1, + "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x27c978b7268a99f80653ef0c370f2fb577fb8ec5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json new file mode 100644 index 000000000..16480ccbf --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xe5414887bddc564fa91e136f8ecd5d11c2967b33": { + "nonce": 1, + "code": "0x60016000556000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe5414887bddc564fa91e136f8ecd5d11c2967b33", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json new file mode 100644 index 000000000..400ff0e5c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json @@ -0,0 +1,71 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { + "nonce": 1, + "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" + }, + "0x3b8acc4708b551d849131f41b9d960be2e7c905b": { + "nonce": 1, + "code": "0x600060006000600073dc81d7b2905163c6159329d5f16820fb6a554d885af45000" + }, + "0x499f3e9c99e571d817950d3d2cdf5a2df9791c84": { + "nonce": 1, + "code": "0x600060006000600073f4c687e3f29e0aa4f2b0d9b8420aa29b88f8dbdf5af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5b75b4547f441a232a390563dc9fae2ede7b7f88": { + "nonce": 1, + "code": "0x6000600060006000733b8acc4708b551d849131f41b9d960be2e7c905b5af45000" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0x806cf69271662bba0bac32ebd4e3f9e6d7c2b3a4": { + "nonce": 1, + "code": "0x6001600055600060006000600073ab2f92b511f6ed5cac4f1c8491ec3441019e1d9e5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xab2f92b511f6ed5cac4f1c8491ec3441019e1d9e": { + "nonce": 1, + "code": "0x600060006000600073f822f47c346ae7bed1440f68ab97a3e22b569e895af45000" + }, + "0xadea63edaf70d5cbbf53c24ce8b0cc22edc7e8fe": { + "nonce": 1, + "code": "0x600060006000600073499f3e9c99e571d817950d3d2cdf5a2df9791c845af45000" + }, + "0xdc81d7b2905163c6159329d5f16820fb6a554d88": { + "nonce": 1, + "code": "0x60006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af45000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf4c687e3f29e0aa4f2b0d9b8420aa29b88f8dbdf": { + "nonce": 1, + "code": "0x6000600060006000735b75b4547f441a232a390563dc9fae2ede7b7f885af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf822f47c346ae7bed1440f68ab97a3e22b569e89": { + "nonce": 1, + "code": "0x600060006000600073adea63edaf70d5cbbf53c24ce8b0cc22edc7e8fe5af45000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x806cf69271662bba0bac32ebd4e3f9e6d7c2b3a4", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json new file mode 100644 index 000000000..576b8e503 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json @@ -0,0 +1,43 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { + "nonce": 1, + "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0x70f06bc3d6620b7e5b4bf63aff29043588afbf8c": { + "nonce": 1, + "code": "0x6001600055600060006000600073dc81d7b2905163c6159329d5f16820fb6a554d885af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xdc81d7b2905163c6159329d5f16820fb6a554d88": { + "nonce": 1, + "code": "0x60006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af45000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x70f06bc3d6620b7e5b4bf63aff29043588afbf8c", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json new file mode 100644 index 000000000..c4702f642 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { + "nonce": 1, + "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0x7957016d354129b485e055f6ce731d9432924360": { + "nonce": 1, + "code": "0x600160005560006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x7957016d354129b485e055f6ce731d9432924360", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json new file mode 100644 index 000000000..515ca4d09 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xc08d2c1a3c9ee34a8606ff5ca8b67dcf690ff371": { + "nonce": 1, + "code": "0x600160015560006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25060006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xe44db291e334fc5110232f4e5430de845b2890f5": { + "nonce": 1, + "code": "0x60016000556000600060006000600073c08d2c1a3c9ee34a8606ff5ca8b67dcf690ff3715af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe44db291e334fc5110232f4e5430de845b2890f5", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json new file mode 100644 index 000000000..01de9a929 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json @@ -0,0 +1,39 @@ +{ + "name": "test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5e20a1397258703e454f569126db7bd67b4744fc": { + "nonce": 1, + "code": "0x6001600055600060006000600073c8987c8935b45c813a6d4541aafc2ebfbe6533225af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" + }, + "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { + "nonce": 1, + "code": "0x600060005500" + }, + "0xc8987c8935b45c813a6d4541aafc2ebfbe653322": { + "nonce": 1, + "code": "0x60016001556000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45060006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5e20a1397258703e454f569126db7bd67b4744fc", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json new file mode 100644 index 000000000..815cc9916 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8b687a302685d3225dff99bf426ac71f33b2cc9c": { + "nonce": 1, + "code": "0x7f6001600055600060005560006000fd00000000000000000000000000000000006000526000600f60006000f55060006000fd" + }, + "0x9924456800f3de93b685f6bd8ba2ff52445d7032": { + "nonce": 1, + "code": "0x60006000600060006000738b687a302685d3225dff99bf426ac71f33b2cc9c5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x9924456800f3de93b685f6bd8ba2ff52445d7032", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json new file mode 100644 index 000000000..4d2118c22 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xa6f584e4bf38391f364ba73cdfb5740dc7d989a4": { + "nonce": 1, + "code": "0x7f6001600055600060005560006000fd0000000000000000000000000000000000600052600f60006000f05060006000fd" + }, + "0xbbe7db18f80c7832998834d57dd751e52d92bdb9": { + "nonce": 1, + "code": "0x6000600060006000600073a6f584e4bf38391f364ba73cdfb5740dc7d989a45af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xbbe7db18f80c7832998834d57dd751e52d92bdb9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json new file mode 100644 index 000000000..209f32fb9 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5e85b8a9fe1249aa1a8e57406175f3873afa7811": { + "nonce": 1, + "code": "0x7f6001600055600060005560006000f3000000000000000000000000000000000060005260006000600f60006000f511600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5e85b8a9fe1249aa1a8e57406175f3873afa7811", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json new file mode 100644 index 000000000..7e31bff24 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x9be2be68c88060daffbb66e5bf419cf058feaaa7": { + "nonce": 1, + "code": "0x7f6001600055600060005560006000f300000000000000000000000000000000006000526000600f60006000f011600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x9be2be68c88060daffbb66e5bf419cf058feaaa7", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..e2544522b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json @@ -0,0 +1,30 @@ +{ + "name": "test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x45077657f5c26405afcf543a09ff0536a5ec4532": { + "nonce": 1, + "code": "0x60026000556001600055", + "storage": { + "0x00": "0x01" + } + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x45077657f5c26405afcf543a09ff0536a5ec4532", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json new file mode 100644 index 000000000..01f4671fd --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json @@ -0,0 +1,71 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { + "nonce": 1, + "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" + }, + "0x3485e345790048eee08c9b61267d87478aaf5039": { + "nonce": 1, + "code": "0x600060006000600073903d585436c21b3f66864dcd14c9c72535450cb35af45000" + }, + "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { + "nonce": 1, + "code": "0x60026000556002600155600060006000f050600160025500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5f701c5c2cfcb03e8315498d1b92d293a0c15549": { + "nonce": 1, + "code": "0x6000600060006000738262901b8f40b64fcaf05340648089e28b8e4f3d5af45000" + }, + "0x7f91850cafc84dd9fab50531a01acc66694acdf8": { + "nonce": 1, + "code": "0x600060006000600073fa5847f72174944848d78a95f7df0705e29732a15af45000" + }, + "0x8262901b8f40b64fcaf05340648089e28b8e4f3d": { + "nonce": 1, + "code": "0x600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" + }, + "0x870405f91f7b6ff0ca990c059ee6715d1cf5dc0f": { + "nonce": 1, + "code": "0x6000600060006000733485e345790048eee08c9b61267d87478aaf50395af45000" + }, + "0x903d585436c21b3f66864dcd14c9c72535450cb3": { + "nonce": 1, + "code": "0x600060006000600073993e7bf6a7c0220c0a83d43de66539ac7c3b81d65af45000" + }, + "0x993e7bf6a7c0220c0a83d43de66539ac7c3b81d6": { + "nonce": 1, + "code": "0x600060006000600073f6ef97d4300d93bf2558c8d32c233b5422ab3e295af45000" + }, + "0xaa7690e523c2d3e068453fcbc5f7d9ef91bd1ea2": { + "nonce": 1, + "code": "0x600160005560016001556000600060006000737f91850cafc84dd9fab50531a01acc66694acdf85af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf6ef97d4300d93bf2558c8d32c233b5422ab3e29": { + "nonce": 1, + "code": "0x6000600060006000735f701c5c2cfcb03e8315498d1b92d293a0c155495af45000" + }, + "0xfa5847f72174944848d78a95f7df0705e29732a1": { + "nonce": 1, + "code": "0x600060006000600073870405f91f7b6ff0ca990c059ee6715d1cf5dc0f5af45000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xaa7690e523c2d3e068453fcbc5f7d9ef91bd1ea2", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json new file mode 100644 index 000000000..045ef56e8 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json @@ -0,0 +1,71 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x123351ba1d1b575788d5e7d422dd0d5991bae228": { + "nonce": 1, + "code": "0x600060006000600073fee8ae183d5743fcd9ca7bb2a818ac8c6222b6955af45000" + }, + "0x12d946c11d5ca6ca04ff5d4a9f42791f03469758": { + "nonce": 1, + "code": "0x6000600060006000736f802627f1da31fac729620e8749f3faead0d2535af45000" + }, + "0x2bff1dbc074f103d7f14a0838b3e05964be16825": { + "nonce": 1, + "code": "0x60006000600060007312d946c11d5ca6ca04ff5d4a9f42791f034697585af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x56508517ac549895c936f4ce69ea05801f2b10a9": { + "nonce": 1, + "code": "0x600160005560016001556000600060006000736724c7ff678d110c88703b6038f9f3e6e3e571685af45000" + }, + "0x6724c7ff678d110c88703b6038f9f3e6e3e57168": { + "nonce": 1, + "code": "0x6000600060006000736f969a7bd5f36d33848eeb3fbe25f3ab570f690b5af45000" + }, + "0x6f802627f1da31fac729620e8749f3faead0d253": { + "nonce": 1, + "code": "0x600060006000600073efeb46955494de7ec79826d87a9dabeed4f5fb635af45000" + }, + "0x6f969a7bd5f36d33848eeb3fbe25f3ab570f690b": { + "nonce": 1, + "code": "0x600060006000600073123351ba1d1b575788d5e7d422dd0d5991bae2285af45000" + }, + "0x8936a6da1a28684143533123025e622069901dc6": { + "nonce": 1, + "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" + }, + "0x9308b92176a11e055f973ce308e71afc2faec231": { + "nonce": 1, + "code": "0x6000600060006000738936a6da1a28684143533123025e622069901dc65af45000" + }, + "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { + "nonce": 1, + "code": "0x60006000556000600155600060006000f050600160025500" + }, + "0xefeb46955494de7ec79826d87a9dabeed4f5fb63": { + "nonce": 1, + "code": "0x6000600060006000739308b92176a11e055f973ce308e71afc2faec2315af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfee8ae183d5743fcd9ca7bb2a818ac8c6222b695": { + "nonce": 1, + "code": "0x6000600060006000732bff1dbc074f103d7f14a0838b3e05964be168255af45000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x56508517ac549895c936f4ce69ea05801f2b10a9", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json new file mode 100644 index 000000000..695b28e8b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { + "nonce": 1, + "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" + }, + "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { + "nonce": 1, + "code": "0x60026000556002600155600060006000f050600160025500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xfa20484013e64b1fd58c2f25bc42d386464cf2c1": { + "nonce": 1, + "code": "0x60016000556001600155600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xfa20484013e64b1fd58c2f25bc42d386464cf2c1", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json new file mode 100644 index 000000000..82f95c659 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x2c0ac31d364ca8a2321630f06ec491d424523fae": { + "nonce": 1, + "code": "0x600160005560016001556000600060006000738936a6da1a28684143533123025e622069901dc65af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8936a6da1a28684143533123025e622069901dc6": { + "nonce": 1, + "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" + }, + "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { + "nonce": 1, + "code": "0x60006000556000600155600060006000f050600160025500" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2c0ac31d364ca8a2321630f06ec491d424523fae", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json new file mode 100644 index 000000000..dad7bbae8 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json @@ -0,0 +1,43 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x1ed438e9f55a47b766499a14b1e44155d5b60c9b": { + "nonce": 1, + "code": "0x600160005560016001556000600060006000735f701c5c2cfcb03e8315498d1b92d293a0c155495af45000" + }, + "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { + "nonce": 1, + "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" + }, + "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { + "nonce": 1, + "code": "0x60026000556002600155600060006000f050600160025500" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5f701c5c2cfcb03e8315498d1b92d293a0c15549": { + "nonce": 1, + "code": "0x6000600060006000738262901b8f40b64fcaf05340648089e28b8e4f3d5af45000" + }, + "0x8262901b8f40b64fcaf05340648089e28b8e4f3d": { + "nonce": 1, + "code": "0x600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x1ed438e9f55a47b766499a14b1e44155d5b60c9b", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json new file mode 100644 index 000000000..0b259a62f --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json @@ -0,0 +1,43 @@ +{ + "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0fbf9bd6a341fba0f8df9fd59308cc6108e49389": { + "nonce": 1, + "code": "0x60016000556001600155600060006000600073efeb46955494de7ec79826d87a9dabeed4f5fb635af45000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x8936a6da1a28684143533123025e622069901dc6": { + "nonce": 1, + "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" + }, + "0x9308b92176a11e055f973ce308e71afc2faec231": { + "nonce": 1, + "code": "0x6000600060006000738936a6da1a28684143533123025e622069901dc65af45000" + }, + "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { + "nonce": 1, + "code": "0x60006000556000600155600060006000f050600160025500" + }, + "0xefeb46955494de7ec79826d87a9dabeed4f5fb63": { + "nonce": 1, + "code": "0x6000600060006000739308b92176a11e055f973ce308e71afc2faec2315af45000" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0fbf9bd6a341fba0f8df9fd59308cc6108e49389", + "data": "0x", + "value": "0x00", + "gas_limit": 200121910, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..900d4182a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_restoration_refund_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { + "nonce": 1, + "code": "0x60016000556000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json new file mode 100644 index 000000000..a5594cf1a --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { + "nonce": 1, + "code": "0x6001600055600060005560006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6c3c798e2e8689bcfa1cd4118362859da59301a3": { + "nonce": 1, + "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6c3c798e2e8689bcfa1cd4118362859da59301a3", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json new file mode 100644 index 000000000..c29ccaab5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { + "nonce": 1, + "code": "0x6001600055600060005560006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc69c38a86504a4047bb75491f68f648750a22c85": { + "nonce": 1, + "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc69c38a86504a4047bb75491f68f648750a22c85", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json new file mode 100644 index 000000000..bdda777d7 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { + "nonce": 1, + "code": "0x6001600055600060005560006000fd" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb20f9c60dd952ad73afb8445cc40daa0dd2c9f4b": { + "nonce": 1, + "code": "0x600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb20f9c60dd952ad73afb8445cc40daa0dd2c9f4b", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json new file mode 100644 index 000000000..2f5d48809 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json new file mode 100644 index 000000000..a8c31ac91 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json new file mode 100644 index 000000000..03ec80390 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..7fc30e647 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..f6d97cb2e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json new file mode 100644 index 000000000..2aa1f9f4e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { + "nonce": 1, + "code": "0x60016000556001600155600160025560016003556001600455" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json new file mode 100644 index 000000000..409c557ad --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { + "nonce": 1, + "code": "0x60016000556001600155600160025560016003556001600455" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json new file mode 100644 index 000000000..34d9178a3 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json new file mode 100644 index 000000000..0b319c7a3 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json new file mode 100644 index 000000000..db2029e93 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json @@ -0,0 +1,31 @@ +{ + "name": "test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x92db0d1541f6727ee66c97c69cd4e5c6c7d6c438": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af1600055" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x92db0d1541f6727ee66c97c69cd4e5c6c7d6c438", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json new file mode 100644 index 000000000..94bcdedc9 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json @@ -0,0 +1,31 @@ +{ + "name": "test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf69d5ad8ffdfcb5e33186a1618a4d1acb979a3ba": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef610902f1600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xf69d5ad8ffdfcb5e33186a1618a4d1acb979a3ba", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..bd2d51c4e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_zero_to_nonzero_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..f314f4e5c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_sstore_zero_to_zero_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe28ddc6f7f6ca2da37aeebaa7c6b0805b5949be6": { + "nonce": 1, + "code": "0x6000600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe28ddc6f7f6ca2da37aeebaa7c6b0805b5949be6", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..95bb01360 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json @@ -0,0 +1,31 @@ +{ + "name": "test_staticcall_passes_reservoir_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6057d1e55c120acb71ac66ba43c26283a7573589": { + "nonce": 1, + "code": "0x30600052" + }, + "0x84ca9599720705b6813be1acad6ff45a50fc6108": { + "nonce": 1, + "code": "0x6000600060006000736057d1e55c120acb71ac66ba43c26283a7573589620186a0fa506001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x84ca9599720705b6813be1acad6ff45a50fc6108", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..9fe8044e5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json @@ -0,0 +1,35 @@ +{ + "name": "test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x5104e8dfb400fa45528f1939767450df6969319e": { + "nonce": 1, + "code": "0x60006000556000600155600060025560006003556000600455" + }, + "0x6f54c4d99a08c1c7e6b8d65b4fd338996e587586": { + "nonce": 1, + "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45060006000fd" + }, + "0xb980ec1278699297a811e6a7f34d27d7cb686cda": { + "nonce": 1, + "code": "0x600160005560016001556001600255600160035560016004556000600060006000736f54c4d99a08c1c7e6b8d65b4fd338996e5875865af4506001600a556001600b556001600c556001600d556001600e55" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb980ec1278699297a811e6a7f34d27d7cb686cda", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json new file mode 100644 index 000000000..0e0dc6c13 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { + "nonce": 1, + "code": "0x6001600055600060005560006000fd" + }, + "0x2bd72bd184d23ea3b68d41cd70854491f171997f": { + "nonce": 1, + "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2bd72bd184d23ea3b68d41cd70854491f171997f", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json new file mode 100644 index 000000000..91eab815d --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { + "nonce": 1, + "code": "0x6001600055600060005560006000fd" + }, + "0x2bd72bd184d23ea3b68d41cd70854491f171997f": { + "nonce": 1, + "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x2bd72bd184d23ea3b68d41cd70854491f171997f", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json new file mode 100644 index 000000000..c01d6b1b1 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6524df279f61e2ec1601dac01281b2d06a607772": { + "nonce": 1, + "code": "0x6001600055fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6524df279f61e2ec1601dac01281b2d06a607772", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json new file mode 100644 index 000000000..bccdbf3a5 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x1b6cf6d0ae353ff340e1f3951356d7dcec64b8e8": { + "nonce": 1, + "code": "0x600160005564174876e800600020" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x1b6cf6d0ae353ff340e1f3951356d7dcec64b8e8", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json new file mode 100644 index 000000000..cebd1b292 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb229c0dc861b48f5810722ac13332a9861fb2242", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json new file mode 100644 index 000000000..b48139755 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xd8da2dd52e320768f4e488cf4b9188268a0230dd": { + "nonce": 1, + "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af150fe" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xd8da2dd52e320768f4e488cf4b9188268a0230dd", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json new file mode 100644 index 000000000..1f9ebc84e --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x6524df279f61e2ec1601dac01281b2d06a607772": { + "nonce": 1, + "code": "0x6001600055fe" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x6524df279f61e2ec1601dac01281b2d06a607772", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json new file mode 100644 index 000000000..085566603 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x851bcae7cde3f214e0fc2a69fe8ba3251a0d5b56": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af150fe" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x851bcae7cde3f214e0fc2a69fe8ba3251a0d5b56", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json new file mode 100644 index 000000000..a6295e954 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xdf9bd1bc60f6cf9564c6053445b38b66c7b94fa6": { + "nonce": 1, + "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af15060006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xdf9bd1bc60f6cf9564c6053445b38b66c7b94fa6", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json new file mode 100644 index 000000000..a5459a84b --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xb229c0dc861b48f5810722ac13332a9861fb2242": { + "nonce": 1, + "code": "0x600160005560006000fd" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xb229c0dc861b48f5810722ac13332a9861fb2242", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json new file mode 100644 index 000000000..7b588bb77 --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json @@ -0,0 +1,31 @@ +{ + "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xc1420b3ed565b52fd874b2aaf0cf7fac5b2d9d5a": { + "nonce": 1, + "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af15060006000fd" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xc1420b3ed565b52fd874b2aaf0cf7fac5b2d9d5a", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..4b399c55c --- /dev/null +++ b/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe0312e9fddad3044789133bb09912bed5d8c1a00": { + "nonce": 1, + "code": "0x6001600055600160006110005e" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe0312e9fddad3044789133bb09912bed5d8c1a00", + "data": "0x", + "value": "0x00", + "gas_limit": 200006884, + "kind": "call" + } + ] +} From ef554aac6755deadd667c59669926fa477c06f80 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:23:26 +0800 Subject: [PATCH 034/201] test: decode delegation designators in scenario pre-states and let scenarios describe themselves --- crates/mega-differential/src/oracle.rs | 5 ++- crates/mega-differential/tests/claims.rs | 1 + crates/mega-evm/src/test_utils/scenario.rs | 45 ++++++++++++++++++++-- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/crates/mega-differential/src/oracle.rs b/crates/mega-differential/src/oracle.rs index 14911fc9b..aff70b187 100644 --- a/crates/mega-differential/src/oracle.rs +++ b/crates/mega-differential/src/oracle.rs @@ -154,7 +154,8 @@ fn database(scenario: &Scenario) -> OracleDb { let mut info = AccountInfo { nonce: account.nonce, balance: account.balance, ..Default::default() }; if !account.code.is_empty() { - let code = Bytecode::new_legacy(account.code.clone()); + let code = Bytecode::new_raw_checked(account.code.clone()) + .expect("validated: the pre-state code decodes"); info.code_hash = code.hash_slow(); info.code = Some(code); } @@ -345,7 +346,7 @@ mod tests { /// as through revm 43's own `transact` and `system_call_with_caller`. #[test] fn test_reservoir_probe_changes_nothing_else() { - let scenarios = crate::load_corpus(&crate::corpus_dir().join("handwritten")).unwrap(); + let scenarios = crate::load_corpus(&crate::corpus_dir()).unwrap(); assert!(scenarios.iter().any(|s| s.txs.iter().any(|tx| tx.kind == TxSpecKind::SystemCall))); for scenario in &scenarios { let mut probed = run(scenario); diff --git a/crates/mega-differential/tests/claims.rs b/crates/mega-differential/tests/claims.rs index 6c4889737..38227af98 100644 --- a/crates/mega-differential/tests/claims.rs +++ b/crates/mega-differential/tests/claims.rs @@ -73,6 +73,7 @@ fn test_zero_fee_vault_touch_leaves_no_committed_account() { ]; let scenario = Scenario { name: "transfer".into(), + description: String::new(), coinbase: Address::ZERO, pre: BTreeMap::from([( CALLER, diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index f69878d6f..9113d1e2d 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -30,6 +30,7 @@ use revm::{ }, BlockEnv, TxEnv, }, + state::{AccountInfo, Bytecode}, Database, DatabaseCommit, }; use serde::Deserialize; @@ -49,6 +50,9 @@ pub type ScenarioTxOutcome = pub struct Scenario { /// Name of the scenario; the harness reports differences under it. pub name: String, + /// What the scenario exercises, for the reader. + #[serde(default)] + pub description: String, /// The block beneficiary. #[serde(default)] pub coinbase: Address, @@ -152,8 +156,14 @@ pub struct AuthorizationEntry { } impl Scenario { - /// Checks the fields that depend on the transaction kind. + /// Checks that the pre-state code decodes and that each transaction carries the fields its + /// kind needs. pub fn validate(&self) -> Result<(), String> { + for (address, account) in &self.pre { + if let Err(err) = Bytecode::new_raw_checked(account.code.clone()) { + return Err(format!("{}: code of {address}: {err:?}", self.name)); + } + } for (i, tx) in self.txs.iter().enumerate() { let problem = match tx.kind { TxSpecKind::Call if tx.to.is_none() => Some("a call needs `to`"), @@ -183,14 +193,24 @@ impl Scenario { } /// The pre-state as a database. + /// + /// Code is decoded as the node decodes it: an EIP-7702 delegation designator becomes a + /// delegation, anything else legacy bytecode. pub fn database(&self) -> MemoryDatabase { let mut db = MemoryDatabase::default(); for (address, account) in &self.pre { - db.set_account_nonce(*address, account.nonce); - db.set_account_balance(*address, account.balance); + let mut info = AccountInfo { + nonce: account.nonce, + balance: account.balance, + ..Default::default() + }; if !account.code.is_empty() { - db.set_account_code(*address, account.code.clone()); + let code = Bytecode::new_raw_checked(account.code.clone()) + .expect("validated: the pre-state code decodes"); + info.code_hash = code.hash_slow(); + info.code = Some(code); } + db.insert_account_info(*address, info); for (slot, value) in &account.storage { db.set_account_storage(*address, *slot, *value); } @@ -321,6 +341,7 @@ mod tests { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)).stop().build(); Scenario { name: "sstore".into(), + description: String::new(), coinbase: Address::ZERO, pre: [ (CALLER, PreAccount { balance: U256::from(10), ..Default::default() }), @@ -359,6 +380,22 @@ mod tests { assert_eq!(db.storage(CALLEE, U256::ZERO).unwrap(), U256::from(7)); } + /// A delegation designator in the pre-state is a delegation, not legacy code that starts + /// with an invalid opcode. + #[test] + fn test_database_decodes_a_delegation_designator() { + let mut scenario = scenario(vec![]); + let designator: Bytes = [&[0xef, 0x01, 0x00][..], CALLEE.as_slice()].concat().into(); + scenario.pre.get_mut(&CALLER).unwrap().code = designator; + assert!(scenario.validate().is_ok()); + + let code = scenario.database().basic(CALLER).unwrap().unwrap().code.unwrap(); + assert!(code.is_eip7702()); + + scenario.pre.get_mut(&CALLER).unwrap().code = Bytes::from_static(&[0xef, 0x01, 0x00]); + assert!(scenario.validate().unwrap_err().starts_with("sstore: code of")); + } + #[test] fn test_tx_type_follows_the_lists() { let mut tx = call(Some(100_000)); From a1367c040a9e87b62e8da5f0fbc3818f40a7e7cf Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:23:53 +0800 Subject: [PATCH 035/201] test: group accepted differences by mechanism in the deviation registry --- crates/mega-differential/README.md | 31 +++-- crates/mega-differential/deviations.json | 46 ++++---- crates/mega-differential/src/lib.rs | 125 ++++++++++++++++---- crates/mega-differential/src/registry.rs | 144 ++++++++++++++++------- 4 files changed, 242 insertions(+), 104 deletions(-) diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index bdb352f93..088668200 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -2,7 +2,7 @@ The differential harness of the Satin engine. It runs every scenario of a corpus through `MegaEvm` and through stock revm 43, and compares what the two report, field by field. -Every difference must be explained by the deviation registry, and every active registry entry must explain at least one difference. +Every difference must be explained by the deviation registry, and every effect an active registry entry lists must explain at least one difference. ```bash cargo test -p mega-differential --locked @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 286 scenarios, 10761 fields compared, 858 deviations matched (op-base-fee-vault-touch x286, …), 0 unexplained, 0 stale registry entries +differential: 286 scenarios, 10761 fields compared, 858 deviations matched (op-fee-vault-touch x858), 0 unexplained, 0 stale registry effects ``` ## The two arms @@ -83,28 +83,33 @@ For every transaction: ## The deviation registry `deviations.json` lists the accepted differences. +An entry names one mechanism and every effect it has on the compared fields: ```json { - "id": "op-base-fee-vault-touch", + "id": "op-fee-vault-touch", "status": "active", "scenario": "*", - "field": "tx[*].state[0x4200000000000000000000000000000000000019]", - "left": "created=false selfdestructed=false balance=0x0 …", - "right": "", - "mechanism": "…", - "reason": "…" + "mechanism": "op-revm fee distribution: the OP handler's reward_beneficiary", + "reason": "…", + "effects": [ + { + "field": "tx[*].state[0x4200000000000000000000000000000000000019]", + "left": "created=false selfdestructed=false balance=0x0 …", + "right": "" + } + ] } ``` -- `scenario`, `field`, `left` (the `MegaEvm` value) and `right` (the oracle's) are patterns in which `*` stands for any run of characters. - Keep them as narrow as the mechanism allows: an entry names one mechanism and the exact values it produces. +- `scenario` and each effect's `field`, `left` (the `MegaEvm` value) and `right` (the oracle's) are patterns in which `*` stands for any run of characters. + Keep them as narrow as the mechanism allows: exact values, and a scenario pattern that covers only the scenarios the mechanism reaches. - `status` is `active` or `retired`; a retired entry keeps its history in `retired_reason` and explains nothing. -- The run fails on a difference no active entry explains, and on an active entry that explains nothing. - When a mechanism stops producing its difference, retire its entry. +- The run fails on a difference no effect of an active entry explains, and on an effect of an active entry that explains nothing. + When a mechanism stops producing an effect, remove the effect, or retire the entry when none is left. - The `version` field is the format version this crate reads. -The active entries today are op-revm's fee vaults: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. +The active entry today is op-revm's fee vaults: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. `tests/claims.rs` checks that state clearing drops those empty accounts when the state is committed. ## Relation to the equivalence tests diff --git a/crates/mega-differential/deviations.json b/crates/mega-differential/deviations.json index 975a63f31..a99ba36ee 100644 --- a/crates/mega-differential/deviations.json +++ b/crates/mega-differential/deviations.json @@ -2,34 +2,28 @@ "version": 1, "deviations": [ { - "id": "op-base-fee-vault-touch", + "id": "op-fee-vault-touch", "status": "active", "scenario": "*", - "field": "tx[*].state[0x4200000000000000000000000000000000000019]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "", - "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", - "reason": "After every non-deposit transaction op-revm credits the base fee to its vault predeploy 0x4200000000000000000000000000000000000019 with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." - }, - { - "id": "op-l1-fee-vault-touch", - "status": "active", - "scenario": "*", - "field": "tx[*].state[0x420000000000000000000000000000000000001a]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "", - "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", - "reason": "After every non-deposit transaction op-revm credits the L1 data fee to its vault predeploy 0x420000000000000000000000000000000000001a with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." - }, - { - "id": "op-operator-fee-vault-touch", - "status": "active", - "scenario": "*", - "field": "tx[*].state[0x420000000000000000000000000000000000001b]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "", - "mechanism": "op-revm fee distribution (the OP handler's reward_beneficiary)", - "reason": "After every non-deposit transaction op-revm credits the operator fee to its vault predeploy 0x420000000000000000000000000000000000001b with balance_incr, which touches the vault even when the amount is zero. The corpus runs with zero fees, so the vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. The entry stops matching once a transaction pays a non-zero fee of this kind: the vault then holds a balance and the difference must be re-attributed." + "mechanism": "op-revm fee distribution: the OP handler's reward_beneficiary", + "reason": "After every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to the BaseFeeVault (0x…19), L1FeeVault (0x…1a) and OperatorFeeVault (0x…1b) predeploys with balance_incr, which touches each vault even when the amount is zero. The corpus runs with zero fees, so each vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. An effect stops matching once a transaction pays a non-zero fee of its kind: the vault then holds a balance and the difference must be attributed again.", + "effects": [ + { + "field": "tx[*].state[0x4200000000000000000000000000000000000019]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "" + }, + { + "field": "tx[*].state[0x420000000000000000000000000000000000001a]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "" + }, + { + "field": "tx[*].state[0x420000000000000000000000000000000000001b]", + "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", + "right": "" + } + ] } ] } diff --git a/crates/mega-differential/src/lib.rs b/crates/mega-differential/src/lib.rs index 338ea778b..389e15ad7 100644 --- a/crates/mega-differential/src/lib.rs +++ b/crates/mega-differential/src/lib.rs @@ -3,13 +3,13 @@ //! Runs every scenario of a corpus through `MegaEvm` (the left arm) and through stock revm 43 on //! its mainnet handler (the right arm, the oracle), and compares what they report field by //! field: every gas figure, the outcome, the output, the logs and every touched account. Each -//! difference must be explained by an active entry of the deviation registry, and every active -//! entry must explain at least one difference. +//! difference must be explained by an active entry of the deviation registry, and every effect +//! an active entry lists must explain at least one difference. //! //! See the crate README for the corpus, the registry and how the two revms coexist. use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, fmt::Write as _, fs, path::{Path, PathBuf}, @@ -24,7 +24,7 @@ pub mod record; pub mod registry; use diff::Difference; -use registry::Registry; +use registry::{EffectRef, Registry}; /// Directory of the corpus, one subdirectory per origin. pub fn corpus_dir() -> PathBuf { @@ -85,12 +85,13 @@ pub struct Report { pub explained: BTreeMap>, /// Differences no active entry explains, with the retired entry that would have, if any. pub unexplained: Vec<(Difference, Option)>, - /// Active entries that explained nothing. - pub stale: Vec, + /// Effects of active entries that explained nothing, with their field pattern. + pub stale: Vec<(EffectRef, String)>, } impl Report { - /// Whether every difference is explained and every active entry explained one. + /// Whether every difference is explained and every effect of every active entry explained + /// one. pub fn is_clean(&self) -> bool { self.unexplained.is_empty() && self.stale.is_empty() } @@ -101,7 +102,7 @@ impl Report { let by_entry: Vec = self.explained.iter().map(|(id, diffs)| format!("{id} x{}", diffs.len())).collect(); format!( - "differential: {} scenarios, {} fields compared, {} deviations matched{}, {} unexplained, {} stale registry entries", + "differential: {} scenarios, {} fields compared, {} deviations matched{}, {} unexplained, {} stale registry effects", self.scenarios, self.compared, matched, @@ -111,7 +112,7 @@ impl Report { ) } - /// Every unexplained difference and stale entry, one per line. + /// Every unexplained difference and stale effect, one per line. pub fn failures(&self) -> String { let mut out = String::new(); for (diff, retired) in &self.unexplained { @@ -125,8 +126,9 @@ impl Report { } out.push('\n'); } - for id in &self.stale { - let _ = writeln!(out, "stale: active registry entry {id} explained no difference"); + for ((id, i), field) in &self.stale { + let _ = + writeln!(out, "stale: effect {i} ({field}) of active entry {id} explained nothing"); } out } @@ -134,28 +136,35 @@ impl Report { /// Runs every scenario through both arms and checks the differences against `registry`. pub fn run(scenarios: &[Scenario], registry: &Registry) -> Report { - let comparisons: Vec = parallel_map(scenarios, |scenario| { + let comparisons = parallel_map(scenarios, |scenario| { diff::compare(&scenario.name, &mega::run(scenario), &oracle::run(scenario)) }); - let mut report = Report { scenarios: scenarios.len(), ..Default::default() }; + check(comparisons, registry) +} + +/// Checks the comparisons of a run against `registry`. +pub fn check(comparisons: Vec, registry: &Registry) -> Report { + let mut report = Report { scenarios: comparisons.len(), ..Default::default() }; + let mut hit = BTreeSet::new(); for comparison in comparisons { report.compared += comparison.compared; for difference in comparison.differences { match registry.explain(&difference) { - Some(dev) => report.explained.entry(dev.id.clone()).or_default().push(difference), + Some(effect) => { + report.explained.entry(effect.0.clone()).or_default().push(difference); + hit.insert(effect); + } None => { - let retired = registry.retired_match(&difference).map(|dev| dev.id.clone()); + let retired = registry.retired_match(&difference).map(|(id, _)| id); report.unexplained.push((difference, retired)); } } } } report.stale = registry - .deviations - .iter() - .filter(|dev| dev.status == registry::Status::Active) - .filter(|dev| !report.explained.contains_key(&dev.id)) - .map(|dev| dev.id.clone()) + .active_effects() + .filter(|(effect, _)| !hit.contains(effect)) + .map(|(effect, spec)| (effect, spec.field.clone())) .collect(); report } @@ -190,3 +199,79 @@ fn serialized_u64_fields(value: &impl serde::Serialize) -> BTreeMap }) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + use diff::Comparison; + + fn registry() -> Registry { + Registry::from_json( + r#"{"version": 1, "deviations": [ + {"id": "fee", "status": "active", "scenario": "*", "mechanism": "m", "reason": "r", + "effects": [ + {"field": "tx[*].gas.gas_spent", "left": "2", "right": "1"}, + {"field": "tx[*].output", "left": "0x", "right": "0x01"}]}, + {"id": "old", "status": "retired", "scenario": "*", "mechanism": "m", "reason": "r", + "retired_reason": "gone", + "effects": [{"field": "tx[*].logs.len", "left": "*", "right": "*"}]} + ]}"#, + ) + .unwrap() + } + + fn comparison(diffs: &[(&str, &str, &str)]) -> Comparison { + Comparison { + differences: diffs + .iter() + .map(|(field, left, right)| Difference { + scenario: "s".into(), + field: (*field).into(), + left: (*left).into(), + right: (*right).into(), + }) + .collect(), + compared: 10, + } + } + + #[test] + fn test_check_is_clean_when_every_difference_and_effect_is_matched() { + let report = check( + vec![ + comparison(&[("tx[0].gas.gas_spent", "2", "1")]), + comparison(&[("tx[1].output", "0x", "0x01")]), + ], + ®istry(), + ); + assert!(report.is_clean(), "{}", report.failures()); + assert_eq!((report.scenarios, report.compared), (2, 20)); + assert_eq!(report.explained["fee"].len(), 2); + } + + #[test] + fn test_check_fails_on_an_unexplained_difference() { + let report = check( + vec![comparison(&[ + ("tx[0].gas.gas_spent", "2", "1"), + ("tx[0].output", "0x", "0x01"), + ("tx[0].gas.gas_spent", "3", "1"), + ("tx[0].logs.len", "1", "0"), + ])], + ®istry(), + ); + assert!(!report.is_clean()); + assert!(report.stale.is_empty()); + let failures = report.failures(); + assert!(failures.contains("unexplained: s tx[0].gas.gas_spent: mega=3 oracle=1\n")); + assert!(failures.contains("tx[0].logs.len: mega=1 oracle=0 (matches retired entry old)")); + } + + #[test] + fn test_check_fails_on_an_effect_that_explains_nothing() { + let report = check(vec![comparison(&[("tx[0].gas.gas_spent", "2", "1")])], ®istry()); + assert!(!report.is_clean()); + assert!(report.unexplained.is_empty()); + assert_eq!(report.stale, vec![(("fee".to_string(), 1), "tx[*].output".to_string())]); + } +} diff --git a/crates/mega-differential/src/registry.rs b/crates/mega-differential/src/registry.rs index 426e511df..242292c6c 100644 --- a/crates/mega-differential/src/registry.rs +++ b/crates/mega-differential/src/registry.rs @@ -1,9 +1,12 @@ //! The registry of accepted differences. //! -//! Every difference between the arms must be explained by an active entry, and every active -//! entry must explain at least one difference; either failure fails the run. A mechanism that -//! stops producing its difference therefore shows up as a stale entry, to be retired, instead of -//! lingering as a blanket excuse. +//! An entry names one mechanism and lists every effect it has on the compared fields, each as a +//! field and the two values. Every difference between the arms must be explained by an effect +//! of an active entry, and every effect of an active entry must explain at least one difference; +//! either failure fails the run. A mechanism that stops producing an effect therefore shows up as +//! a stale effect, to be removed or its entry retired, instead of lingering as a blanket excuse. + +use std::collections::BTreeSet; use serde::Deserialize; @@ -22,7 +25,7 @@ pub struct Registry { pub deviations: Vec, } -/// An accepted difference between `MegaEvm` and the oracle. +/// An accepted difference between `MegaEvm` and the oracle: one mechanism and its effects. #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct Deviation { @@ -32,31 +35,45 @@ pub struct Deviation { pub status: Status, /// Scenario names the entry covers (`*` matches any run of characters). pub scenario: String, - /// Field path the entry covers (`*` matches any run of characters). - pub field: String, - /// The value `MegaEvm` reports (`*` matches any run of characters). - pub left: String, - /// The value the oracle reports (`*` matches any run of characters). - pub right: String, /// The mechanism that makes the arms differ. pub mechanism: String, /// Why the difference is correct. pub reason: String, + /// What the mechanism changes, field by field. + pub effects: Vec, /// Why the entry was retired; required for a retired entry. #[serde(default)] pub retired_reason: Option, } +/// One field a mechanism changes, and the value on each arm. +/// +/// Each part is a pattern in which `*` matches any run of characters; every other character +/// stands for itself. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Effect { + /// Field path. + pub field: String, + /// The value `MegaEvm` reports. + pub left: String, + /// The value the oracle reports. + pub right: String, +} + /// Status of a registry entry. #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Status { - /// In force: it explains differences, and it must explain at least one. + /// In force: its effects explain differences, and each must explain at least one. Active, /// Kept for the record; it explains nothing. Retired, } +/// An effect of an entry, by entry id and position in its `effects`. +pub type EffectRef = (String, usize); + impl Registry { /// Parses a registry and checks its entries are well formed. pub fn from_json(json: &str) -> Result { @@ -67,7 +84,7 @@ impl Registry { registry.version )); } - let mut ids = std::collections::BTreeSet::new(); + let mut ids = BTreeSet::new(); for dev in ®istry.deviations { if !ids.insert(dev.id.as_str()) { return Err(format!("duplicate registry id {}", dev.id)); @@ -75,6 +92,9 @@ impl Registry { if dev.mechanism.trim().is_empty() || dev.reason.trim().is_empty() { return Err(format!("{}: an entry names its mechanism and its reason", dev.id)); } + if dev.effects.is_empty() { + return Err(format!("{}: an entry lists at least one effect", dev.id)); + } if (dev.status == Status::Retired) != dev.retired_reason.is_some() { return Err(format!( "{}: a retired entry, and only one, has retired_reason", @@ -85,22 +105,39 @@ impl Registry { Ok(registry) } - /// The active entry that explains `diff`, if any. - pub fn explain(&self, diff: &Difference) -> Option<&Deviation> { - self.deviations.iter().find(|dev| dev.status == Status::Active && dev.matches(diff)) + /// The effect of an active entry that explains `diff`, if any. + pub fn explain(&self, diff: &Difference) -> Option { + self.find(Status::Active, diff) + } + + /// The effect of a retired entry that would have explained `diff`, to point at in a failure + /// report. + pub fn retired_match(&self, diff: &Difference) -> Option { + self.find(Status::Retired, diff) } - /// A retired entry that would have explained `diff`, to point at in a failure report. - pub fn retired_match(&self, diff: &Difference) -> Option<&Deviation> { - self.deviations.iter().find(|dev| dev.status == Status::Retired && dev.matches(diff)) + /// Every effect of every active entry. + pub fn active_effects(&self) -> impl Iterator { + self.deviations.iter().filter(|dev| dev.status == Status::Active).flat_map(|dev| { + dev.effects.iter().enumerate().map(|(i, effect)| ((dev.id.clone(), i), effect)) + }) + } + + fn find(&self, status: Status, diff: &Difference) -> Option { + self.deviations + .iter() + .filter(|dev| dev.status == status && glob(&dev.scenario, &diff.scenario)) + .find_map(|dev| { + let i = dev.effects.iter().position(|effect| effect.matches(diff))?; + Some((dev.id.clone(), i)) + }) } } -impl Deviation { - /// Whether this entry's patterns cover `diff`, whatever its status. +impl Effect { + /// Whether this effect's patterns cover the field and values of `diff`. pub fn matches(&self, diff: &Difference) -> bool { - glob(&self.scenario, &diff.scenario) && - glob(&self.field, &diff.field) && + glob(&self.field, &diff.field) && glob(&self.left, &diff.left) && glob(&self.right, &diff.right) } @@ -127,10 +164,14 @@ pub fn glob(pattern: &str, text: &str) -> bool { mod tests { use super::*; - fn entry(status: &str, extra: &str) -> String { + const GAS_EFFECT: &str = r#"{"field": "tx[*].gas.gas_spent", "left": "*", "right": "21000"}"#; + const OUTPUT_EFFECT: &str = r#"{"field": "tx[*].output", "left": "0x", "right": "0x01"}"#; + + fn entry(id: &str, status: &str, effects: &[&str], extra: &str) -> String { format!( - r#"{{"id": "d", "status": "{status}", "scenario": "call_*", "field": "tx[*].gas.gas_spent", - "left": "*", "right": "21000", "mechanism": "m", "reason": "r"{extra}}}"# + r#"{{"id": "{id}", "status": "{status}", "scenario": "call_*", "mechanism": "m", + "reason": "r", "effects": [{}]{extra}}}"#, + effects.join(",") ) } @@ -138,11 +179,11 @@ mod tests { Registry::from_json(&format!(r#"{{"version": 1, "deviations": [{}]}}"#, entries.join(","))) } - fn diff(scenario: &str, right: &str) -> Difference { + fn diff(scenario: &str, field: &str, left: &str, right: &str) -> Difference { Difference { scenario: scenario.into(), - field: "tx[0].gas.gas_spent".into(), - left: "21100".into(), + field: field.into(), + left: left.into(), right: right.into(), } } @@ -164,30 +205,43 @@ mod tests { #[test] fn test_active_entry_explains_matching_differences_only() { - let registry = registry(&[entry("active", "")]).unwrap(); - assert_eq!(registry.explain(&diff("call_1", "21000")).map(|d| d.id.as_str()), Some("d")); - assert!(registry.explain(&diff("create_1", "21000")).is_none(), "scenario pattern"); - assert!(registry.explain(&diff("call_1", "21001")).is_none(), "right value"); + let registry = registry(&[entry("d", "active", &[GAS_EFFECT, OUTPUT_EFFECT], "")]).unwrap(); + let gas = |scenario, right| diff(scenario, "tx[0].gas.gas_spent", "21100", right); + + assert_eq!(registry.explain(&gas("call_1", "21000")), Some(("d".into(), 0))); + assert_eq!( + registry.explain(&diff("call_1", "tx[1].output", "0x", "0x01")), + Some(("d".into(), 1)) + ); + assert!(registry.explain(&gas("create_1", "21000")).is_none(), "scenario pattern"); + assert!(registry.explain(&gas("call_1", "21001")).is_none(), "right value"); + assert!(registry.explain(&diff("call_1", "tx[0].output", "0x", "0x02")).is_none()); } #[test] fn test_retired_entry_explains_nothing() { - let registry = registry(&[entry("retired", r#", "retired_reason": "gone""#)]).unwrap(); - assert!(registry.explain(&diff("call_1", "21000")).is_none()); - assert_eq!( - registry.retired_match(&diff("call_1", "21000")).map(|d| d.id.as_str()), - Some("d") - ); + let registry = + registry(&[entry("d", "retired", &[GAS_EFFECT], r#", "retired_reason": "gone""#)]) + .unwrap(); + let gas = diff("call_1", "tx[0].gas.gas_spent", "21100", "21000"); + assert!(registry.explain(&gas).is_none()); + assert_eq!(registry.retired_match(&gas), Some(("d".into(), 0))); + assert_eq!(registry.active_effects().count(), 0); } #[test] fn test_registry_rejects_malformed_entries() { - assert!(registry(&[entry("retired", "")]).unwrap_err().contains("retired_reason")); - assert!(registry(&[entry("active", r#", "retired_reason": "x""#)]).is_err()); - assert!(registry(&[entry("active", ""), entry("active", "")]) - .unwrap_err() - .contains("duplicate")); + let reject = |entries: &[String]| registry(entries).unwrap_err(); + assert!(reject(&[entry("d", "retired", &[GAS_EFFECT], "")]).contains("retired_reason")); + assert!(reject(&[entry("d", "active", &[GAS_EFFECT], r#", "retired_reason": "x""#)]) + .contains("retired_reason")); + assert!(reject(&[entry("d", "active", &[], "")]).contains("effect")); + assert!(reject(&[ + entry("d", "active", &[GAS_EFFECT], ""), + entry("d", "active", &[GAS_EFFECT], "") + ]) + .contains("duplicate")); assert!(Registry::from_json(r#"{"version": 2, "deviations": []}"#).is_err()); - assert!(registry(&[entry("paused", "")]).is_err()); + assert!(registry(&[entry("d", "paused", &[GAS_EFFECT], "")]).is_err()); } } From 8f259d727bba2efcf008e511664336f8d71d64af Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:24:22 +0800 Subject: [PATCH 036/201] test: cover EIP-7702, access lists, SELFDESTRUCT to existing accounts, logs and precompiles in the differential corpus --- crates/mega-differential/README.md | 18 ++++--- crates/mega-differential/deviations.json | 39 ++++++++++++++ .../harness/access_list_duplicates.json | 53 ++++++++++++++++++ .../harness/access_list_on_create.json | 27 ++++++++++ .../harness/access_list_unused_entries.json | 44 +++++++++++++++ .../access_list_warm_slots_and_account.json | 43 +++++++++++++++ .../harness/eip7702_authority_with_code.json | 38 +++++++++++++ .../eip7702_call_into_delegated_account.json | 41 ++++++++++++++ .../harness/eip7702_chain_id_mismatch.json | 40 ++++++++++++++ .../eip7702_delegate_existing_authority.json | 38 +++++++++++++ .../eip7702_delegate_new_authority.json | 34 ++++++++++++ .../eip7702_delegation_to_precompile.json | 34 ++++++++++++ .../harness/eip7702_invalid_signature.json | 33 ++++++++++++ .../harness/eip7702_nonce_mismatch.json | 38 +++++++++++++ .../harness/eip7702_redelegate_and_clear.json | 54 +++++++++++++++++++ .../harness/eip7702_self_sponsored.json | 34 ++++++++++++ ...702_two_authorizations_same_authority.json | 40 ++++++++++++++ .../equivalence_empty_transaction.json | 16 ++++++ .../scenarios/harness/equivalence_sstore.json | 20 +++++++ .../harness/equivalence_value_transfer.json | 20 +++++++ .../harness/logs_all_topic_counts.json | 23 ++++++++ .../logs_discarded_by_reverted_subcall.json | 26 +++++++++ .../scenarios/harness/precompile_blake2f.json | 31 +++++++++++ .../precompile_bls12_g1add_and_map.json | 34 ++++++++++++ .../harness/precompile_bn254_add.json | 23 ++++++++ .../precompile_bn254_mul_and_pairing.json | 34 ++++++++++++ ...mpile_bn254_pairing_at_op_input_limit.json | 23 ++++++++ ...ile_bn254_pairing_over_op_input_limit.json | 23 ++++++++ .../harness/precompile_ecrecover.json | 31 +++++++++++ .../scenarios/harness/precompile_modexp.json | 31 +++++++++++ .../harness/precompile_p256verify.json | 31 +++++++++++ .../precompile_point_evaluation_invalid.json | 23 ++++++++ .../precompile_ripemd160_and_identity.json | 34 ++++++++++++ .../scenarios/harness/precompile_sha256.json | 23 ++++++++ ...reated_in_same_tx_to_existing_account.json | 27 ++++++++++ .../selfdestruct_in_static_context.json | 30 +++++++++++ .../selfdestruct_to_existing_account.json | 27 ++++++++++ .../selfdestruct_to_existing_contract.json | 30 +++++++++++ .../harness/selfdestruct_to_self.json | 24 +++++++++ 39 files changed, 1226 insertions(+), 6 deletions(-) create mode 100644 crates/mega-differential/scenarios/harness/access_list_duplicates.json create mode 100644 crates/mega-differential/scenarios/harness/access_list_on_create.json create mode 100644 crates/mega-differential/scenarios/harness/access_list_unused_entries.json create mode 100644 crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json create mode 100644 crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json create mode 100644 crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json create mode 100644 crates/mega-differential/scenarios/harness/equivalence_sstore.json create mode 100644 crates/mega-differential/scenarios/harness/equivalence_value_transfer.json create mode 100644 crates/mega-differential/scenarios/harness/logs_all_topic_counts.json create mode 100644 crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_blake2f.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_add.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_ecrecover.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_modexp.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_p256verify.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_sha256.json create mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json create mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json create mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json create mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json create mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_self.json diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 088668200..0465bf491 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 286 scenarios, 10761 fields compared, 858 deviations matched (op-fee-vault-touch x858), 0 unexplained, 0 stale registry effects +differential: 323 scenarios, 12401 fields compared, 1004 deviations matched (op-fee-vault-touch x996, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects ``` ## The two arms @@ -53,7 +53,7 @@ Cargo writes the version requirements of revm 43's optional dependencies into it ## The corpus `scenarios/` holds one JSON file per scenario; the file stem is the scenario name. -The format is `mega_evm::test_utils::Scenario`: a coinbase, the pre-state accounts (nonce, balance, legacy code, storage) and the transactions, run in order. +The format is `mega_evm::test_utils::Scenario`: an optional description, a coinbase, the pre-state accounts (nonce, balance, code, storage; code is legacy bytecode or an EIP-7702 delegation designator) and the transactions, run in order. A transaction is a `call`, a `create` or a `system_call`; it may carry an EIP-2930 access list and an EIP-7702 authorization list with the signer already recovered (`authority`, absent for a signature that does not recover). The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. @@ -61,12 +61,14 @@ The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | | `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | | `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | +| `harness/` | 37 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, and the three cases of `crates/mega-evm/tests/satin/equivalence.rs` | -Both sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. +The first two sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. Gas limits at or below the reference cap are unchanged, and the system call lost its gas limit, since a system call runs with the engine's own. -Under the Osaka gas table state gas is priced at zero, so today these scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. +Under the Osaka gas table state gas is priced at zero, so today those scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. +Each scenario of `harness/` carries a `description` of what it exercises. To add a scenario, drop a JSON file into the directory of its origin; the loader rejects unknown fields, a name that is not the file stem, and a duplicate name. ## What is compared @@ -109,10 +111,14 @@ An entry names one mechanism and every effect it has on the compared fields: When a mechanism stops producing an effect, remove the effect, or retire the entry when none is left. - The `version` field is the format version this crate reads. -The active entry today is op-revm's fee vaults: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. -`tests/claims.rs` checks that state clearing drops those empty accounts when the state is committed. +The active entries today: + +- `op-fee-vault-touch`: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. + `tests/claims.rs` checks that state clearing drops those empty accounts when the state is committed. +- `op-karst-bn254-pairing-input-bound`: op-revm's Karst precompile set rejects a BN254 pairing input over 57,600 bytes, which Ethereum's pairing accepts; `harness/precompile_bn254_pairing_over_op_input_limit` crosses the bound and `harness/precompile_bn254_pairing_at_op_input_limit` stays on it. ## Relation to the equivalence tests `crates/mega-evm/tests/satin/equivalence.rs` compares `MegaEvm` with op-revm's `OpEvm` on the same fork, which pins that the Satin layer adds nothing to op-revm yet. This harness compares `MegaEvm` with an independent implementation, which pins that the fork plus op-revm execute Ethereum semantics. +The three equivalence cases are also scenarios here (`harness/equivalence_*`); the equivalence tests stay as they are, since they check a different claim that later changes update on purpose. diff --git a/crates/mega-differential/deviations.json b/crates/mega-differential/deviations.json index a99ba36ee..cbf51eb52 100644 --- a/crates/mega-differential/deviations.json +++ b/crates/mega-differential/deviations.json @@ -24,6 +24,45 @@ "right": "" } ] + }, + { + "id": "op-karst-bn254-pairing-input-bound", + "status": "active", + "scenario": "precompile_bn254_pairing_over_op_input_limit", + "mechanism": "op-revm's Karst precompile set: the BN254 pairing (0x08) rejects inputs over 57,600 bytes", + "reason": "op-revm bounds the BN254 pairing input on OP chains (57,600 bytes, 300 pairs, from Karst on); a longer input fails the precompile, which consumes the gas the call forwarded. Ethereum's pairing has no such bound, so revm 43 runs the 301 pairs and returns 1. The scenario's proxy records the failure: it stores no success flag and no return size, and the hash of empty return data. The failed call also leaves the precompile account untouched.", + "effects": [ + { + "field": "tx[0].gas.*", + "left": "29561930", + "right": "10608872" + }, + { + "field": "tx[0].output", + "left": "0x", + "right": "0x0000000000000000000000000000000000000000000000000000000000000001" + }, + { + "field": "tx[0].state[0x0000000000000000000000000000000000000008]", + "left": "", + "right": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}" + }, + { + "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x0]", + "left": "", + "right": "0x1" + }, + { + "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x1]", + "left": "", + "right": "0x20" + }, + { + "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x2]", + "left": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + "right": "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6" + } + ] } ] } diff --git a/crates/mega-differential/scenarios/harness/access_list_duplicates.json b/crates/mega-differential/scenarios/harness/access_list_duplicates.json new file mode 100644 index 000000000..9b7a478a3 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/access_list_duplicates.json @@ -0,0 +1,53 @@ +{ + "name": "access_list_duplicates", + "description": "The access list repeats an address and a storage key; each entry is charged.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0", + "0x0" + ] + }, + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0" + ] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/access_list_on_create.json b/crates/mega-differential/scenarios/harness/access_list_on_create.json new file mode 100644 index 000000000..b24bf325e --- /dev/null +++ b/crates/mega-differential/scenarios/harness/access_list_on_create.json @@ -0,0 +1,27 @@ +{ + "name": "access_list_on_create", + "description": "A contract-creation transaction with an access list (EIP-2930 type).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "data": "0x600160005560006000f3", + "value": "0x0", + "gas_limit": 1000000, + "kind": "create", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0" + ] + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/access_list_unused_entries.json b/crates/mega-differential/scenarios/harness/access_list_unused_entries.json new file mode 100644 index 000000000..07542bcc4 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/access_list_unused_entries.json @@ -0,0 +1,44 @@ +{ + "name": "access_list_unused_entries", + "description": "The access list warms accounts and slots the call never touches.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000fee", + "storage_keys": [ + "0x1", + "0x2", + "0x3" + ] + }, + { + "address": "0x0000000000000000000000000000000000000fef", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json b/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json new file mode 100644 index 000000000..aacca0ab9 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json @@ -0,0 +1,43 @@ +{ + "name": "access_list_warm_slots_and_account", + "description": "The access list warms slot 0 and slot 2 of the reader and the account it reads the balance of; slot 1 stays cold.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0", + "0x2" + ] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json b/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json new file mode 100644 index 000000000..4eade90e3 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json @@ -0,0 +1,38 @@ +{ + "name": "eip7702_authority_with_code", + "description": "The authority is a contract with ordinary code: the authorization is skipped and the contract code runs.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + }, + "0x0000000000000000000000000000000000000a11": { + "nonce": 1, + "code": "0x600560055500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 1, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json b/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json new file mode 100644 index 000000000..2f4672d31 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json @@ -0,0 +1,41 @@ +{ + "name": "eip7702_call_into_delegated_account", + "description": "A legacy transaction calls a delegated account directly, then a contract calls it and reads its EXTCODESIZE and EXTCODEHASH (those of the designator).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + }, + "0x0000000000000000000000000000000000000a11": { + "nonce": 1, + "code": "0xef01000000000000000000000000000000000000000de1" + }, + "0x0000000000000000000000000000000000000b0b": { + "code": "0x60006000600060006000730000000000000000000000000000000000000a115af1600055730000000000000000000000000000000000000a113b600155730000000000000000000000000000000000000a113f60025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000b0b", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json b/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json new file mode 100644 index 000000000..a04ebdad0 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json @@ -0,0 +1,40 @@ +{ + "name": "eip7702_chain_id_mismatch", + "description": "The authorization names another chain: it is skipped. A second authorization with chain id 0 (any chain) applies.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x7", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + }, + { + "chain_id": "0x0", + "address": "0x0000000000000000000000000000000000000de2", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json b/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json new file mode 100644 index 000000000..dda065264 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json @@ -0,0 +1,38 @@ +{ + "name": "eip7702_delegate_existing_authority", + "description": "The authority exists with nonce 3 and a balance: the authorization applies with the existing-account refund.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + }, + "0x0000000000000000000000000000000000000a11": { + "nonce": 3, + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 3, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json b/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json new file mode 100644 index 000000000..964eb05c3 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json @@ -0,0 +1,34 @@ +{ + "name": "eip7702_delegate_new_authority", + "description": "The authority does not exist: the authorization creates it with the delegation designator and nonce 1, and the call to it runs the delegate's code in its context.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json b/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json new file mode 100644 index 000000000..1859817bb --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json @@ -0,0 +1,34 @@ +{ + "name": "eip7702_delegation_to_precompile", + "description": "The authority delegates to the identity precompile: calling it runs no code.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x0102", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000004", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json b/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json new file mode 100644 index 000000000..48c822a8b --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json @@ -0,0 +1,33 @@ +{ + "name": "eip7702_invalid_signature", + "description": "The signature does not recover: the authorization is skipped and the call runs on an empty account.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0 + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json b/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json new file mode 100644 index 000000000..a9bb114d0 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json @@ -0,0 +1,38 @@ +{ + "name": "eip7702_nonce_mismatch", + "description": "The authorization's nonce is not the authority's: it is skipped.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + }, + "0x0000000000000000000000000000000000000a11": { + "nonce": 2, + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 5, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json b/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json new file mode 100644 index 000000000..4d3fd7974 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json @@ -0,0 +1,54 @@ +{ + "name": "eip7702_redelegate_and_clear", + "description": "The authority is delegated to one contract; the first transaction re-delegates it to another, the second clears the delegation with the zero address.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + }, + "0x0000000000000000000000000000000000000a11": { + "nonce": 1, + "code": "0xef01000000000000000000000000000000000000000de1" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de2", + "nonce": 1, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000000", + "nonce": 2, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json b/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json new file mode 100644 index 000000000..a7da16880 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json @@ -0,0 +1,34 @@ +{ + "name": "eip7702_self_sponsored", + "description": "The sender authorizes its own account: the sender's nonce is bumped before the authorization is checked, so the authorization carries nonce 1.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000aaa", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 1, + "authority": "0x0000000000000000000000000000000000000aaa" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json b/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json new file mode 100644 index 000000000..159ef174f --- /dev/null +++ b/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json @@ -0,0 +1,40 @@ +{ + "name": "eip7702_two_authorizations_same_authority", + "description": "Two authorizations for one authority with consecutive nonces: both apply, the last one wins.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + }, + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de2", + "nonce": 1, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json b/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json new file mode 100644 index 000000000..4fae32668 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json @@ -0,0 +1,16 @@ +{ + "name": "equivalence_empty_transaction", + "description": "An empty call whose gas limit exceeds the execution cap by 1,000,000: the excess goes to the EIP-8037 reservoir and, with no state gas drawn, is left over (equivalence.rs).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": {}, + "txs": [ + { + "caller": "0x4000000000000000000000000000000000000001", + "to": "0x5000000000000000000000000000000000000001", + "data": "0x", + "value": "0x0", + "gas_limit": 201000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/equivalence_sstore.json b/crates/mega-differential/scenarios/harness/equivalence_sstore.json new file mode 100644 index 000000000..20abeb11a --- /dev/null +++ b/crates/mega-differential/scenarios/harness/equivalence_sstore.json @@ -0,0 +1,20 @@ +{ + "name": "equivalence_sstore", + "description": "SSTORE(0, 42) into a fresh slot; the Osaka gas table prices no state gas (equivalence.rs).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x5000000000000000000000000000000000000001": { + "code": "0x602a60005500" + } + }, + "txs": [ + { + "caller": "0x4000000000000000000000000000000000000001", + "to": "0x5000000000000000000000000000000000000001", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json b/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json new file mode 100644 index 000000000..9939c02e3 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json @@ -0,0 +1,20 @@ +{ + "name": "equivalence_value_transfer", + "description": "A 1,000 wei transfer to an account that does not exist (equivalence.rs).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x4000000000000000000000000000000000000001": { + "balance": "0xde0b6b3a7640000" + } + }, + "txs": [ + { + "caller": "0x4000000000000000000000000000000000000001", + "to": "0x5000000000000000000000000000000000000001", + "data": "0x", + "value": "0x3e8", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json b/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json new file mode 100644 index 000000000..bb77d6ecd --- /dev/null +++ b/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json @@ -0,0 +1,23 @@ +{ + "name": "logs_all_topic_counts", + "description": "One LOG0 to LOG4 each, with data from memory.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000106": { + "code": "0x7f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2060005260206000a0600160206000a16002600160106000a260036002600160006000a3600460036002600160086018a400" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000106", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json b/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json new file mode 100644 index 000000000..ebd0cd5ce --- /dev/null +++ b/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json @@ -0,0 +1,26 @@ +{ + "name": "logs_discarded_by_reverted_subcall", + "description": "A sub-call logs and reverts: its log is dropped, the caller's logs before and after stay.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000106": { + "code": "0x60cd60005360016000a0600060006000600060007300000000000000000000000000000000000001075af160005560ef600053600760016000a100" + }, + "0x0000000000000000000000000000000000000107": { + "code": "0x60ab60005360016000a060006000fd" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000106", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_blake2f.json b/crates/mega-differential/scenarios/harness/precompile_blake2f.json new file mode 100644 index 000000000..657ac87df --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_blake2f.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_blake2f", + "description": "BLAKE2 F with the EIP-152 test vector (12 rounds over \"abc\"), then with a bad final-block flag.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009909": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000095afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009909", + "data": "0x0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009909", + "data": "0x0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000002", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json b/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json new file mode 100644 index 000000000..19686c6bb --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json @@ -0,0 +1,34 @@ +{ + "name": "precompile_bls12_g1add_and_map", + "description": "BLS12-381 G1 addition of two points at infinity, and mapping the field element 0 to G1.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x000000000000000000000000000000000000990b": { + "code": "0x3660006000376000600036600073000000000000000000000000000000000000000b5afa6000553d6001553d600060003e3d6000206002553d6000f3" + }, + "0x0000000000000000000000000000000000009910": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000105afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x000000000000000000000000000000000000990b", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009910", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_add.json b/crates/mega-differential/scenarios/harness/precompile_bn254_add.json new file mode 100644 index 000000000..c1695ae6b --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_bn254_add.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_bn254_add", + "description": "BN254 addition of the generator to itself.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009906": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000065afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009906", + "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json b/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json new file mode 100644 index 000000000..1e751f914 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json @@ -0,0 +1,34 @@ +{ + "name": "precompile_bn254_mul_and_pairing", + "description": "BN254 multiplication of the generator by 2, and a pairing check of the empty input.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009907": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000075afa6000553d6001553d600060003e3d6000206002553d6000f3" + }, + "0x0000000000000000000000000000000000009908": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009907", + "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009908", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json new file mode 100644 index 000000000..bd6a4064b --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_bn254_pairing_at_op_input_limit", + "description": "A BN254 pairing of 300 pairs of points at infinity, 57,600 bytes: the most op-revm's Karst pairing accepts.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009908": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009908", + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 30000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json new file mode 100644 index 000000000..247e4243c --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_bn254_pairing_over_op_input_limit", + "description": "A BN254 pairing of 301 pairs of points at infinity, 57,792 bytes: over the input bound op-revm's Karst pairing enforces, which Ethereum's does not have.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009908": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009908", + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 30000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_ecrecover.json b/crates/mega-differential/scenarios/harness/precompile_ecrecover.json new file mode 100644 index 000000000..4f47989bf --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_ecrecover.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_ecrecover", + "description": "ecrecover on a valid signature, then on one with v = 29.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009901": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000015afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001c9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001d9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_modexp.json b/crates/mega-differential/scenarios/harness/precompile_modexp.json new file mode 100644 index 000000000..507d63dce --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_modexp.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_modexp", + "description": "modexp 3^5 mod 7 with one-byte operands, then with a 64-byte exponent (the Osaka pricing).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009905": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000055afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001030507", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000103ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_p256verify.json b/crates/mega-differential/scenarios/harness/precompile_p256verify.json new file mode 100644 index 000000000..02f26260d --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_p256verify.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_p256verify", + "description": "P256VERIFY on 160 zero bytes (an invalid signature) and on a short input.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009a00": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000001005afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009a00", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009a00", + "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json new file mode 100644 index 000000000..53239dfbb --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_point_evaluation_invalid", + "description": "KZG point evaluation on 192 zero bytes: the versioned hash does not match, the call fails.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x000000000000000000000000000000000000990a": { + "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x000000000000000000000000000000000000990a", + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json b/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json new file mode 100644 index 000000000..c4d6165f5 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json @@ -0,0 +1,34 @@ +{ + "name": "precompile_ripemd160_and_identity", + "description": "RIPEMD-160 and identity on 100 bytes, each through its own proxy.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009903": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000035afa6000553d6001553d600060003e3d6000206002553d6000f3" + }, + "0x0000000000000000000000000000000000009904": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000045afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009903", + "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009904", + "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_sha256.json b/crates/mega-differential/scenarios/harness/precompile_sha256.json new file mode 100644 index 000000000..c4b432deb --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_sha256.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_sha256", + "description": "SHA-256 on 100 bytes.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009902": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000025afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009902", + "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json b/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json new file mode 100644 index 000000000..48f436af1 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json @@ -0,0 +1,27 @@ +{ + "name": "selfdestruct_created_in_same_tx_to_existing_account", + "description": "A contract created in the transaction self-destructs to an existing account from its init code: it is destroyed and the beneficiary gets its endowment.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000fac": { + "balance": "0x64", + "code": "0x3660006000373660006007f060005500" + }, + "0x0000000000000000000000000000000000000bee": { + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000fac", + "data": "0x730000000000000000000000000000000000000beeff", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json b/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json new file mode 100644 index 000000000..d99cc30f0 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json @@ -0,0 +1,30 @@ +{ + "name": "selfdestruct_in_static_context", + "description": "SELFDESTRUCT under STATICCALL halts the callee; the caller records the failure.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000d35": { + "balance": "0x3e8", + "code": "0x730000000000000000000000000000000000000beeff" + }, + "0x0000000000000000000000000000000000000bee": { + "balance": "0x5" + }, + "0x000000000000000000000000000000000000057a": { + "code": "0x6000600060006000730000000000000000000000000000000000000d355afa60005500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x000000000000000000000000000000000000057a", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json new file mode 100644 index 000000000..5839af49a --- /dev/null +++ b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json @@ -0,0 +1,27 @@ +{ + "name": "selfdestruct_to_existing_account", + "description": "A contract that predates the transaction self-destructs to an existing funded account: its balance moves, the contract stays (EIP-6780).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000d35": { + "balance": "0x3e8", + "code": "0x730000000000000000000000000000000000000beeff" + }, + "0x0000000000000000000000000000000000000bee": { + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000d35", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json new file mode 100644 index 000000000..f1f7b23a2 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json @@ -0,0 +1,30 @@ +{ + "name": "selfdestruct_to_existing_contract", + "description": "The beneficiary is a contract with code and storage; its code does not run.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000d35": { + "balance": "0x3e8", + "code": "0x730000000000000000000000000000000000000becff" + }, + "0x0000000000000000000000000000000000000bec": { + "code": "0x600160005500", + "storage": { + "0x3": "0x3" + } + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000d35", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json new file mode 100644 index 000000000..55a59a7d7 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json @@ -0,0 +1,24 @@ +{ + "name": "selfdestruct_to_self", + "description": "A contract that predates the transaction self-destructs to itself: the balance stays.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000d35": { + "balance": "0x3e8", + "code": "0x730000000000000000000000000000000000000d35ff" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000d35", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} From 3bd95ec4ff9be9a0287f89982490f2ef7097c147 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:24:54 +0800 Subject: [PATCH 037/201] ci: run the differential harness as the differential check --- .github/workflows/build-and-test.yml | 3 ++- .github/workflows/differential.yml | 34 ++++++++++++++++++++++++++++ crates/mega-differential/README.md | 2 ++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/differential.yml diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index fb57502e8..8dfc8a952 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -46,7 +46,8 @@ jobs: - name: Build run: cargo build - name: Run Test - run: cargo test --workspace + # The differential harness has its own job (differential.yml). + run: cargo test --workspace --exclude mega-differential no-std: runs-on: ubuntu-24.04 diff --git a/.github/workflows/differential.yml b/.github/workflows/differential.yml new file mode 100644 index 000000000..bcfeb2294 --- /dev/null +++ b/.github/workflows/differential.yml @@ -0,0 +1,34 @@ +name: Differential + +# Runs every scenario of the differential corpus through MegaEvm and through stock revm 43 and +# fails on any difference the deviation registry does not explain, or on a registry effect that +# explains nothing. See crates/mega-differential/README.md. + +on: + pull_request: + push: + branches: [satin] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + differential: + name: differential + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + - name: Run the corpus + run: cargo test -p mega-differential --locked -- --nocapture diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 0465bf491..7119a01d6 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -14,6 +14,8 @@ The corpus test prints one summary line, for example: differential: 323 scenarios, 12401 fields compared, 1004 deviations matched (op-fee-vault-touch x996, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects ``` +CI runs the same command as the `differential` job (`.github/workflows/differential.yml`), on every pull request and every push to `satin`. + ## The two arms **Left arm: `MegaEvm`.** From 451cbf17253d732fa597c978e325c4a129ef8d80 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:29:25 +0800 Subject: [PATCH 038/201] bench: add a differential-corpus slice and EVM construction to the Satin bench set --- .github/workflows/benchmark.yml | 4 +- AGENTS.md | 7 +++- crates/mega-evm/Cargo.toml | 13 +++++- crates/mega-evm/benches/corpus.rs | 63 ++++++++++++++++++++++++++++++ crates/mega-evm/benches/factory.rs | 41 +++++++++++++++++++ 5 files changed, 122 insertions(+), 6 deletions(-) create mode 100644 crates/mega-evm/benches/corpus.rs create mode 100644 crates/mega-evm/benches/factory.rs diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index fca1291a1..a7051b726 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -199,10 +199,10 @@ jobs: strategy: fail-fast: false matrix: - # On the satin branch `transact` is the only bench target until the + # The Satin bench set: `transact`, `corpus` and `factory`, until the # suite is rebuilt on Satin, which restores the full list. Scheduled and # comment-triggered runs use the default branch's copy of this file. - target: [transact] + target: [corpus, factory, transact] steps: - uses: actions/checkout@v4 with: diff --git a/AGENTS.md b/AGENTS.md index 4fafe413f..a30c38ecd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,10 +33,13 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks (`transact` is the only target until the benchmark suite is rebuilt on Satin) -cargo bench -p mega-evm --bench transact # wall-clock + HTML report +# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (a slice of the differential corpus), `factory` (EVM construction) +cargo bench -p mega-evm --bench # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) +# Differential harness: MegaEvm against stock revm 43 over the scenario corpus +cargo test -p mega-differential --locked + # no_std check (run against riscv target) cargo check -p mega-evm --target riscv64imac-unknown-none-elf --no-default-features diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index a618e0884..0918d6684 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -56,8 +56,17 @@ std = [ ] test-utils = ["dep:derive_more"] -# `transact` is the only target until the benchmark suite is rebuilt on Satin. The inputs -# under benches/data (revm_bench) and benches/fixtures (attack_replay) stay for the rebuild. +# The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (a slice of the differential +# corpus) and `factory` (EVM construction). The inputs under benches/data (revm_bench) and +# benches/fixtures (attack_replay) stay for the rebuild of the rest of the suite. +[[bench]] +name = "corpus" +harness = false + +[[bench]] +name = "factory" +harness = false + [[bench]] name = "transact" harness = false diff --git a/crates/mega-evm/benches/corpus.rs b/crates/mega-evm/benches/corpus.rs new file mode 100644 index 000000000..a79603acf --- /dev/null +++ b/crates/mega-evm/benches/corpus.rs @@ -0,0 +1,63 @@ +//! A slice of the differential corpus through `MegaEvm`. +//! +//! The inputs are scenarios of `crates/mega-differential/scenarios`, the corpus the differential +//! harness compares against stock revm 43, so an instruction-count change here means the +//! execution or the pricing of those scenarios moved. Each scenario runs all its transactions, +//! one fresh `MegaEvm` per transaction as the harness does; building the pre-state is setup and +//! is not measured. +#![allow(missing_docs)] + +use std::path::Path; + +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use mega_evm::test_utils::Scenario; + +/// `(bench id, scenario path under the corpus directory)`: a few scenarios of each origin, +/// spread over the mechanisms the corpus covers. +const SLICE: &[(&str, &str)] = &[ + ("sstore_set", "handwritten/sstore_set_spills"), + ("create", "handwritten/create_success"), + ("nested_revert", "handwritten/nested_call_revert_with_spill"), + ("two_txs", "handwritten/two_txs_sequential"), + ("system_call", "handwritten/system_call"), + ("calldata_floor", "eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test"), + ( + "nested_refund_depth_10", + "eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + ), + ("eip7702_delegation", "harness/eip7702_delegate_new_authority"), + ("access_list", "harness/access_list_warm_slots_and_account"), + ("selfdestruct", "harness/selfdestruct_created_in_same_tx_to_existing_account"), + ("logs", "harness/logs_all_topic_counts"), + ("ecrecover", "harness/precompile_ecrecover"), + ("modexp", "harness/precompile_modexp"), +]; + +fn load(path: &str) -> Scenario { + let file = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../mega-differential/scenarios") + .join(format!("{path}.json")); + let text = std::fs::read_to_string(&file).unwrap_or_else(|err| panic!("{file:?}: {err}")); + let scenario: Scenario = serde_json::from_str(&text).unwrap(); + scenario.validate().unwrap(); + scenario +} + +fn bench_corpus(c: &mut Criterion) { + let mut group = c.benchmark_group("corpus"); + for (id, path) in SLICE { + let scenario = load(path); + // The measured path must be the scenario's execution, not a rejected transaction. + let (outcomes, _) = scenario.run(scenario.database()); + for (i, outcome) in outcomes.iter().enumerate() { + assert!(outcome.is_ok(), "{path}: tx[{i}] is rejected: {outcome:?}"); + } + group.bench_function(*id, |b| { + b.iter_batched(|| scenario.database(), |db| scenario.run(db), BatchSize::SmallInput); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_corpus); +criterion_main!(benches); diff --git a/crates/mega-evm/benches/factory.rs b/crates/mega-evm/benches/factory.rs new file mode 100644 index 000000000..4d7832237 --- /dev/null +++ b/crates/mega-evm/benches/factory.rs @@ -0,0 +1,41 @@ +//! Construction of a `MegaEvm` through `MegaEvmFactory`, as a node's block executor makes one +//! per block. +//! +//! `create_evm` builds the context and applies the configuration the spec fixes; the EVM is +//! dropped inside the measurement, so its teardown counts too. +#![allow(missing_docs)] + +use alloy_evm::{EvmEnv, EvmFactory}; +use criterion::{criterion_group, criterion_main, Criterion}; +use mega_evm::{MegaEvmFactory, MegaSpecId}; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::EmptyDB, + inspector::NoOpInspector, +}; +use std::hint::black_box; + +fn evm_env() -> EvmEnv { + EvmEnv { cfg_env: CfgEnv::new_with_spec(MegaSpecId::SATIN), block_env: BlockEnv::default() } +} + +fn bench_factory(c: &mut Criterion) { + let factory = MegaEvmFactory::new(); + let mut group = c.benchmark_group("factory"); + group.bench_function("create_evm", |b| { + b.iter(|| drop(black_box(factory.create_evm(EmptyDB::default(), black_box(evm_env()))))); + }); + group.bench_function("create_evm_with_inspector", |b| { + b.iter(|| { + drop(black_box(factory.create_evm_with_inspector( + EmptyDB::default(), + black_box(evm_env()), + NoOpInspector, + ))) + }); + }); + group.finish(); +} + +criterion_group!(benches, bench_factory); +criterion_main!(benches); From 554764bf365e47679c3fab19a3f15b9da8d75f01 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:32:54 +0800 Subject: [PATCH 039/201] test: retire the parked legacy mutant killers --- REVIEW.md | 4 +- crates/mega-evm/tests/_pending/README.md | 23 +- .../tests/_pending/mutation/access_evm.rs | 479 -------------- .../mega-evm/tests/_pending/mutation/block.rs | 618 ------------------ .../tests/_pending/mutation/constants.rs | 59 -- .../tests/_pending/mutation/external_exec.rs | 347 ---------- .../mega-evm/tests/_pending/mutation/main.rs | 48 -- 7 files changed, 12 insertions(+), 1566 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/mutation/access_evm.rs delete mode 100644 crates/mega-evm/tests/_pending/mutation/block.rs delete mode 100644 crates/mega-evm/tests/_pending/mutation/constants.rs delete mode 100644 crates/mega-evm/tests/_pending/mutation/external_exec.rs delete mode 100644 crates/mega-evm/tests/_pending/mutation/main.rs diff --git a/REVIEW.md b/REVIEW.md index b57b8c307..eaef3f746 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -55,10 +55,10 @@ This is the single most important correctness concern in mega-evm. - If a change affects cross-component behavior that cannot be covered by unit tests, suggest e2e tests in the review comment (these may live in the `test-client` repo). - For stateful systems (resource-limit trackers, gas-stipend lifecycle), assert state-machine invariants after each transition, not just at the end. - Tests under `crates/mega-evm/tests/mutation/` are generated mutation-killing system tests, each keyed to a specific surviving mutant. - On the `satin` branch the legacy ones are parked under `crates/mega-evm/tests/_pending/mutation/` until they are regenerated against the Satin sources. + On the `satin` branch the directory does not exist yet: the legacy killers were keyed to mutants of the legacy sources and were retired, and the Satin sources leave no survivor; the first mechanism whose survivor needs a system-level killer creates it, with the conventions of `main`'s `crates/mega-evm/tests/mutation/main.rs`. Their comments — especially the `file:line:col` mutation-location references — must be kept up to date when the referenced source moves. Flag any PR that shifts lines in a mutated source file but leaves a now-stale location reference (or an orphaned/renamed test) in `tests/mutation/`; a reference that no longer points at its mutant defeats the purpose of the linkage. - These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs` (on `satin`: `crates/mega-evm/tests/_pending/mutation/main.rs`). + These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. Missing the required explicit hardfork pin can silently bench the wrong fork when a shared bench subject defaults to a different one. diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 0dfd535f5..763f8a517 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -16,7 +16,8 @@ Do not add a `_pending/main.rs`. - Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. - `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. - Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. -- Files under `mutation/` are machine-generated mutant killers; the test gates regenerate them against the Satin sources instead of porting them by hand. +- The 44 legacy mutant killers the inventory kept (`tests/mutation/`) are not here: each was keyed to a surviving mutant of the legacy sources, and the test gates found no survivor in the Satin sources to regenerate one for. + A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`. - Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. - Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. @@ -27,23 +28,23 @@ Do not add a `_pending/main.rs`. |---|---:|---:|---:|---:|---:|---:| | the test gates | 21 | 21 | 0 | 21 | 0 | 0 | | the common execution layer | 41 | 19 | 22 | 22 | 19 | 0 | -| the Satin gas table | 37 | 30 | 7 | 7 | 30 | 0 | -| SALT pricing | 83 | 72 | 11 | 25 | 58 | 0 | +| the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | +| SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | -| compute gas | 27 | 27 | 0 | 0 | 27 | 0 | -| the data-size limit | 49 | 47 | 2 | 42 | 7 | 0 | -| detention | 87 | 82 | 5 | 79 | 8 | 0 | -| the state-growth and KV limits | 58 | 57 | 1 | 0 | 36 | 22 | +| compute gas | 26 | 26 | 0 | 0 | 26 | 0 | +| the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | +| detention | 81 | 76 | 5 | 73 | 8 | 0 | +| the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | | the system contract interceptors | 65 | 57 | 8 | 56 | 9 | 0 | | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 75 | 45 | 30 | 56 | 19 | 0 | +| the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **836** | **691** | **145** | **485** | **322** | **29** | +| **Total** | **792** | **647** | **145** | **452** | **312** | **28** | ## Tests ported in place @@ -99,10 +100,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | | `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | -| `mutation/access_evm.rs` | 10 | keep 6 (detention · the test gates regenerate); keep 2 (SALT pricing · the test gates regenerate); keep 1 (the block executor · the test gates regenerate); rewrite 1 (the Satin gas table · D11) | -| `mutation/block.rs` | 22 | keep 14 (the block executor · the test gates regenerate); rewrite 5 (the block executor · single spec / Satin schedule); undecided 1 (the state-growth and KV limits · D46); rewrite 1 (compute gas · D53); rewrite 1 (the state-growth and KV limits · D45) | -| `mutation/constants.rs` | 4 | rewrite 2 (the Satin gas table · D04); keep 2 (the data-size limit · 13,107,200 unchanged) | -| `mutation/external_exec.rs` | 8 | keep 2 (the block executor · the test gates regenerate); keep 6 (SALT pricing · the test gates regenerate) | | `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | | `rex/storage_gas.rs` | 15 | rewrite 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | | `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | diff --git a/crates/mega-evm/tests/_pending/mutation/access_evm.rs b/crates/mega-evm/tests/_pending/mutation/access_evm.rs deleted file mode 100644 index 8592160f1..000000000 --- a/crates/mega-evm/tests/_pending/mutation/access_evm.rs +++ /dev/null @@ -1,479 +0,0 @@ -//! Value / behavioral tests that close surviving mutants in `crates/mega-evm/src/access/` and -//! the `crates/mega-evm/src/evm/mod.rs` accessor methods. -//! -//! The `access/*` modules carry inline `#[cfg(test)] mod tests`, but those unit tests do not kill -//! the relevant mutants: the mutation run builds the integration test targets, and (for -//! `VolatileDataAccess::as_u8`) the inline assertions are tautological — they compare -//! `converted.as_u8()` against `expected_flag.as_u8()`, so a `-> 0` / `-> 1` mutant changes both -//! sides identically and the equality still holds. These integration tests instead pin the exact -//! discriminant / boolean / option value through the crate's public API. -//! -//! Covered survivors: -//! * `access/volatile.rs:89` — `VolatileDataAccess::as_u8 -> 0` and `-> 1`. Killed by asserting the -//! exact bit-position discriminant of several distinct variants (so neither constant matches all -//! of them). -//! * `access/tracker.rs:131` — `has_accessed_beneficiary_balance -> true`. Killed by asserting it -//! is `false` on a fresh tracker. -//! * `access/tracker.rs:104` — `get_volatile_data_info -> Some(Default::default())`. Killed by -//! asserting it is `None` on a fresh (no-access) tracker; the mutant returns `Some(empty)`. -//! * `access/tracker.rs:180` — `disable_access` depth guard (`>=` vs `<`, and the match-guard -//! replaced with `true` / `false`). Killed by re-disabling at a deeper / shallower depth and -//! observing whether the shallower depth is retained. -//! * `evm/mod.rs:107` — `Debug for MegaEvm::fmt -> Ok(())`. Killed by asserting the formatted -//! output contains the struct name and field; the mutant writes nothing. -//! * `evm/mod.rs:251` — `block_env_mut -> Box::leak(Box::new(Default::default()))`. Killed by -//! mutating a field through `block_env_mut` and reading it back via `block_env_ref`; the mutant -//! writes to a throwaway leaked env so the read shows the original value. -//! * `evm/mod.rs:379` — `get_accessed_bucket_ids -> vec![]` and `vec![Default::default()]`. Killed -//! by executing an `SSTORE`-set transaction under `TestExternalEnvs` (non-zero bucket IDs) and -//! asserting the returned IDs are non-empty and equal the predicted (non-zero) bucket ID. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - constants, - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, TestExternalEnvs, - VolatileDataAccess, VolatileDataAccessTracker, MIN_BUCKET_SIZE, -}; -use revm::context::{BlockEnv, TxEnv}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); -/// Block beneficiary (coinbase) used by the `disable_beneficiary` tests. -const BENEFICIARY: Address = address!("3000000000000000000000000000000000000003"); - -// ============================================================================ -// access/volatile.rs — VolatileDataAccess::as_u8 discriminant encoder -// ============================================================================ - -/// `as_u8()` returns the single-set-bit position. Pinning several distinct variants kills both the -/// `-> 0` mutant (the `BENEFICIARY_BALANCE`/`ORACLE` cases are non-zero) and the `-> 1` mutant -/// (the `BLOCK_NUMBER` case is zero), since no single constant can satisfy all of them. -#[test] -fn test_as_u8_returns_exact_bit_position_for_each_variant() { - assert_eq!(VolatileDataAccess::BLOCK_NUMBER.as_u8(), 0, "BLOCK_NUMBER is bit 0"); - assert_eq!(VolatileDataAccess::TIMESTAMP.as_u8(), 1, "TIMESTAMP is bit 1"); - assert_eq!(VolatileDataAccess::COINBASE.as_u8(), 2, "COINBASE is bit 2"); - assert_eq!(VolatileDataAccess::BLOB_HASH.as_u8(), 9, "BLOB_HASH is bit 9"); - assert_eq!( - VolatileDataAccess::BENEFICIARY_BALANCE.as_u8(), - 10, - "BENEFICIARY_BALANCE is bit 10" - ); - assert_eq!(VolatileDataAccess::ORACLE.as_u8(), 11, "ORACLE is bit 11"); -} - -// ============================================================================ -// access/tracker.rs — VolatileDataAccessTracker accessors -// ============================================================================ - -fn new_tracker() -> VolatileDataAccessTracker { - VolatileDataAccessTracker::new(20_000_000, 20_000_000) -} - -/// A fresh tracker has not accessed the beneficiary balance. The `-> true` mutant flips this. -#[test] -fn test_has_accessed_beneficiary_balance_is_false_until_marked() { - let mut tracker = new_tracker(); - assert!( - !tracker.has_accessed_beneficiary_balance(), - "fresh tracker must report no beneficiary-balance access (kills the `-> true` mutant)" - ); - - tracker.mark_beneficiary_balance_accessed(); - assert!( - tracker.has_accessed_beneficiary_balance(), - "after marking, beneficiary-balance access must be reported" - ); -} - -/// A fresh tracker reports `None` for volatile-data info. The `-> Some(Default::default())` mutant -/// returns `Some(empty)`, which is `!= None`. -#[test] -fn test_get_volatile_data_info_is_none_until_accessed() { - let tracker = new_tracker(); - assert_eq!( - tracker.get_volatile_data_info(), - None, - "fresh tracker must report no volatile-data info (kills the `Some(empty)` mutant)" - ); - - let mut tracker = new_tracker(); - tracker.mark_beneficiary_balance_accessed(); - assert_eq!( - tracker.get_volatile_data_info(), - Some(VolatileDataAccess::BENEFICIARY_BALANCE), - "after a beneficiary access, the info must report exactly that access" - ); -} - -/// `disable_access` keeps the *shallower* (smaller) depth when already active and is a no-op when -/// the new depth is deeper. -/// -/// Killing the three `:180` mutants: -/// * `>=` → `<`: after `disable_access(5)` then `disable_access(8)`, the real code keeps depth 5 -/// (`8 >= 5` is a no-op). The mutant takes the else branch and overwrites with 8, so -/// `volatile_access_disabled(5)` would become false. -/// * guard → `false`: the guard is never taken, so `disable_access(8)` overwrites with 8 — same -/// observable failure as above. -/// * guard → `true`: the guard is always taken, so `disable_access(2)` becomes a no-op and the -/// shallower depth 2 is never adopted, leaving `volatile_access_disabled(2)` false. -#[test] -fn test_disable_access_keeps_shallower_depth() { - let mut tracker = new_tracker(); - - tracker.disable_access(5); - assert!(tracker.volatile_access_disabled(5), "depth 5 is disabled after disable_access(5)"); - assert!(!tracker.volatile_access_disabled(4), "depth 4 (shallower) is not disabled"); - - // Disabling at a deeper depth must NOT relax the restriction: depth 5 stays disabled. - // Real: `8 >= 5` → no-op, keeps 5. Mutants `<` / guard-`false`: overwrite with 8, so - // `volatile_access_disabled(5)` would become false (`5 >= 8` is false). - tracker.disable_access(8); - assert!( - tracker.volatile_access_disabled(5), - "re-disabling at a deeper depth must keep the shallower depth (kills `<` and guard-false)" - ); - - // Disabling at a shallower depth must tighten the restriction down to depth 2. - // Real: `2 >= 5` is false → else branch sets 2. Mutant guard-`true`: no-op, keeps 5, so - // `volatile_access_disabled(2)` would be false (`2 >= 5` is false). - tracker.disable_access(2); - assert!( - tracker.volatile_access_disabled(2), - "re-disabling at a shallower depth must adopt it (kills the guard-true mutant)" - ); -} - -// ============================================================================ -// evm/mod.rs — MegaEvm accessor methods -// ============================================================================ - -/// Build a bare `MegaEvm` over an empty in-memory database (no transaction executed). -fn empty_evm( - db: &mut MemoryDatabase, -) -> MegaEvm<&mut MemoryDatabase, revm::inspector::NoOpInspector, mega_evm::EmptyExternalEnv> { - let context = MegaContext::new(db, MegaSpecId::REX4); - MegaEvm::new(context) -} - -/// The `Debug` impl writes the struct name and the `inspect` field. The -/// `fmt -> Ok(Default::default())` mutant skips all writes, producing an empty body. -#[test] -fn test_debug_impl_writes_struct_name_and_field() { - let mut db = MemoryDatabase::default(); - let evm = empty_evm(&mut db); - - let rendered = format!("{evm:?}"); - assert!( - rendered.contains("MegaethEvm"), - "Debug output must contain the struct name, got: {rendered:?}" - ); - assert!( - rendered.contains("inspect"), - "Debug output must contain the `inspect` field, got: {rendered:?}" - ); -} - -/// `block_env_mut` must return a reference to the EVM's own block env, so a write through it is -/// visible via `block_env_ref`. The mutant returns a leaked default env, so the write is lost. -#[test] -fn test_block_env_mut_returns_live_block_env() { - let mut db = MemoryDatabase::default(); - let mut evm = empty_evm(&mut db); - - let sentinel = U256::from(0xABCD_u64); - evm.block_env_mut().number = sentinel; - - assert_eq!( - evm.block_env_ref().number, - sentinel, - "a write through block_env_mut must be observable via block_env_ref \ - (kills the leaked-default mutant)" - ); -} - -/// `get_accessed_bucket_ids` must report the SALT buckets touched during execution. An -/// `SSTORE`-set (zero → non-zero) records the slot's bucket. Under `TestExternalEnvs` the bucket -/// ID is non-zero, so the result distinguishes both the `vec![]` mutant (empty) and the -/// `vec![Default::default()]` mutant (`[0]`). -#[test] -fn test_get_accessed_bucket_ids_reports_touched_non_zero_bucket() { - let storage_slot = U256::from(1_u64); - - // Contract that sets storage slot 1 to a non-zero value, then stops. - let code = BytecodeBuilder::default().sstore(storage_slot, U256::from(1_u64)).stop().build(); - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - db.set_account_code(CONTRACT, code); - - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit: 10_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "SSTORE transaction should succeed: {:?}", result.result); - - // The SSTORE-set records the slot's bucket. Predict it from the same hasher the EVM uses. - let expected_bucket = - as SaltEnv>::bucket_id_for_slot(CONTRACT, storage_slot); - assert_ne!(expected_bucket, 0, "TestExternalEnvs must produce a non-zero bucket ID"); - - let buckets = evm.get_accessed_bucket_ids(); - assert!( - !buckets.is_empty(), - "an SSTORE-set transaction must record at least one accessed bucket (kills `vec![]`)" - ); - assert!( - buckets.contains(&expected_bucket), - "accessed buckets {buckets:?} must contain the SSTORE slot's bucket {expected_bucket} \ - (kills the `vec![Default::default()]` = [0] mutant)" - ); -} - -// ============================================================================ -// evm/context.rs:521 — MegaContext::disable_beneficiary -// ============================================================================ - -/// Runs a simple value-transfer transaction whose entire gas price is a priority fee (block -/// `basefee` is 0), and returns the block beneficiary's (coinbase's) post-transaction balance. -/// -/// When `disable` is true, `MegaContext::disable_beneficiary()` is called before execution; the -/// consumer at `evm/execution.rs:689` then skips `reward_beneficiary`, so the coinbase is NOT -/// credited the priority fee. Operator fees are zeroed so the only thing crediting the beneficiary -/// is the priority-fee reward. -fn beneficiary_balance_after_transfer(disable: bool) -> U256 { - const GAS_PRICE: u128 = 7; - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - - let block = BlockEnv { beneficiary: BENEFICIARY, basefee: 0, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - if disable { - context.disable_beneficiary(); - } - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - // Plain value transfer to a fresh account: no code runs, so the only beneficiary credit is - // the priority-fee reward. - kind: TxKind::Call(CONTRACT), - gas_limit: 1_000_000, - gas_price: GAS_PRICE, - value: U256::from(1_u64), - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "transfer should succeed: {:?}", result.result); - - result.state.get(&BENEFICIARY).map(|acct| acct.info.balance).unwrap_or(U256::ZERO) -} - -/// `disable_beneficiary()` must suppress the post-transaction coinbase reward. -/// -/// Control run (not disabled): the beneficiary is credited the priority fee, so its balance is -/// non-zero. Disabled run: the beneficiary reward is skipped, so its balance is zero. -/// -/// The `disable_beneficiary -> ()` no-op mutant never sets the flag, so the "disabled" run behaves -/// like the control and credits the beneficiary — making the `assert_eq!(disabled, ZERO)` below -/// fail, which kills the mutant. -#[test] -fn test_disable_beneficiary_suppresses_coinbase_reward() { - let credited = beneficiary_balance_after_transfer(false); - assert!( - credited > U256::ZERO, - "control run must credit the beneficiary the priority fee (sanity check)" - ); - - let suppressed = beneficiary_balance_after_transfer(true); - assert_eq!( - suppressed, - U256::ZERO, - "disable_beneficiary() must suppress the coinbase reward (kills the `-> ()` no-op mutant); \ - got {suppressed} vs control {credited}" - ); -} - -// ============================================================================ -// evm/execution.rs:167 — MegaHandler::before_execution intrinsic-gas boundary -// ============================================================================ - -/// Executes a plain call (no calldata, no access list, no value) to an existing code account that -/// immediately `STOP`s, with the given `gas_limit`, and returns the `transact_raw` outcome. -/// -/// Under REX the intrinsic gas of such a call is exactly `21000 + TX_INTRINSIC_STORAGE_GAS` -/// (no calldata words, no new-account creation since the callee already has code and the value is -/// zero). `MegaHandler::before_execution` (`evm/execution.rs:167`) halts the tx out-of-gas when -/// `gas_limit < initial_gas`. Operator fees and the basefee are zeroed so the only thing that can -/// make the tx fail at the boundary is that intrinsic-gas guard. -fn intrinsic_boundary_result( - gas_limit: u64, -) -> Result< - revm::context::result::ResultAndState, - revm::context::result::EVMError, -> { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - // Callee already exists (has code) and just STOPs, so the call adds no new-account storage gas - // and burns no execution gas beyond the intrinsic cost. - db.set_account_code(CONTRACT, BytecodeBuilder::default().stop().build()); - - let block = BlockEnv { basefee: 0, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit, - gas_price: 0, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// `before_execution` must allow a tx whose `gas_limit` equals its (fully Mega-adjusted) intrinsic -/// gas, and reject one below it. This pins the `<` boundary at `evm/execution.rs:167`. -/// -/// Under REX the intrinsic gas of the bare call above is `21000 + TX_INTRINSIC_STORAGE_GAS` -/// (= 60000). With `gas_limit == initial_gas` the real `gas_limit < initial_gas` check is `false`, -/// so `before_execution` returns `Ok(None)` and the tx executes and succeeds. The `<` → `<=` -/// mutant makes it `60000 <= 60000` → `true`, wrongly halting the exact-gas tx out-of-gas — caught -/// by the `is_success()` assertion below. The `gas_limit == initial_gas - 1` case pins the lower -/// side of the boundary: validation (`initial_gas > gas_limit`) rejects it as a transaction error. -#[test] -fn test_before_execution_allows_exact_intrinsic_gas() { - // Fully Mega-adjusted intrinsic gas for the bare REX call: base 21000 + the REX intrinsic - // storage surcharge. The `gas_used == intrinsic` assertion below self-validates this value. - let intrinsic: u64 = 21_000 + constants::rex::TX_INTRINSIC_STORAGE_GAS; - - // Exactly intrinsic gas: must execute and succeed (kills the `<` → `<=` mutant, which would - // OOG-halt this exact-gas tx). - let exact = intrinsic_boundary_result(intrinsic).expect("exact-gas tx must not be rejected"); - assert!( - exact.result.is_success(), - "a call with gas_limit == intrinsic gas ({intrinsic}) must succeed, not OOG-halt; \ - got {:?}", - exact.result - ); - assert_eq!( - exact.result.gas_used(), - intrinsic, - "the exact-gas call must consume exactly the intrinsic gas" - ); - - // One below intrinsic gas: must NOT succeed (pins the lower side of the boundary). Under REX - // this is surfaced as a `CallGasCostMoreThanGasLimit` validation error. - let one_below = intrinsic_boundary_result(intrinsic - 1); - assert!( - one_below.is_err() || !one_below.unwrap().result.is_success(), - "a call with gas_limit == intrinsic gas - 1 ({}) must fail the intrinsic-gas guard", - intrinsic - 1 - ); -} - -// ============================================================================ -// evm/context.rs:563 — MegaContext::on_new_block refreshes the dynamic gas cache -// ============================================================================ - -/// `on_new_block()` (invoked by `with_block`) must refresh the dynamic storage gas-cost -/// calculator for the new block. Concretely it calls `DynamicGasCost::on_new_block`, which -/// `reset`s the calculator and **clears its cached per-bucket cost multipliers**. The -/// `MegaContext::on_new_block -> ()` no-op mutant skips this, leaving a stale cached multiplier. -/// -/// Observable effect: under `MINI_REX` (but not REX), the SSTORE-set gas is -/// `SSTORE_SET_STORAGE_GAS * (capacity / MIN_BUCKET_SIZE)`. The calculator caches the multiplier -/// the first time a bucket is queried. If the underlying SALT bucket capacity changes between -/// blocks, the cached multiplier is stale until `on_new_block` clears it. -/// -/// The test primes the cache at capacity `C1`, then mutates the shared `TestExternalEnvs` bucket -/// capacity to `C2` (the env is shared by `Rc`), then calls `with_block` to drive -/// `on_new_block`, and asserts the recomputed SSTORE gas reflects `C2`. The no-op mutant keeps the -/// stale `C1` multiplier, so the assertion fails — killing the mutant. -#[test] -fn test_on_new_block_clears_stale_dynamic_gas_cache() { - let min_bucket = MIN_BUCKET_SIZE as u64; - // Two capacities yielding distinct multipliers (capacity / MIN_BUCKET_SIZE). - let cap_before = 2 * min_bucket; // multiplier 2 - let cap_after = 3 * min_bucket; // multiplier 3 - let base = constants::mini_rex::SSTORE_SET_STORAGE_GAS; - let gas_before = base * 2; - let gas_after = base * 3; - - let storage_slot = U256::from(7_u64); - let bucket = - as SaltEnv>::bucket_id_for_slot(CONTRACT, storage_slot); - - // Shared env handle. `with_bucket_capacity` mutates the shared `Rc` map and returns - // `self`; cloning shares the same map, so later edits are visible to the EVM's clone. - let env = TestExternalEnvs::::new().with_bucket_capacity(bucket, cap_before); - - let mut db = MemoryDatabase::default(); - // MINI_REX (not REX) so the gas formula is the simple `base * multiplier`. - let context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(env.clone().into()); - - // Prime the cache: the calculator now caches multiplier = cap_before / MIN_BUCKET_SIZE. - let primed = context - .dynamic_storage_gas_cost - .borrow_mut() - .sstore_set_gas(CONTRACT, storage_slot) - .unwrap(); - assert_eq!(primed, gas_before, "primed SSTORE gas must reflect the initial capacity"); - - // Change the shared bucket capacity. Without a cache clear, the calculator keeps `cap_before`. - env.clear_bucket_capacity(); - let _ = env.clone().with_bucket_capacity(bucket, cap_after); - assert_eq!( - as SaltEnv>::get_bucket_capacity(&env, bucket).unwrap(), - cap_after, - "the shared env must now report the new capacity" - ); - - // Drive `on_new_block` via the public `with_block`. Real code clears the stale cache; the - // no-op mutant leaves it. - let context = context.with_block(BlockEnv { number: U256::from(2_u64), ..Default::default() }); - - let recomputed = context - .dynamic_storage_gas_cost - .borrow_mut() - .sstore_set_gas(CONTRACT, storage_slot) - .unwrap(); - assert_eq!( - recomputed, gas_after, - "after on_new_block the dynamic gas cache must be refreshed to the new capacity \ - (kills the `on_new_block -> ()` no-op mutant; stale value would be {gas_before})" - ); -} diff --git a/crates/mega-evm/tests/_pending/mutation/block.rs b/crates/mega-evm/tests/_pending/mutation/block.rs deleted file mode 100644 index 0c55baac5..000000000 --- a/crates/mega-evm/tests/_pending/mutation/block.rs +++ /dev/null @@ -1,618 +0,0 @@ -//! Value/behavioral tests that close surviving mutants in `crates/mega-evm/src/block/`. -//! -//! The `src/block/*` modules carry inline `#[cfg(test)] mod tests`, but those unit tests are not -//! exercised by the mutation run (which builds the integration test targets). These integration -//! tests re-assert the same invariants through the crate's public API, using exact-value -//! assertions (never `> 0`, so the `-> 1` constant-return mutants die too). -//! -//! Covered survivors: -//! * `helpers.rs` — `MegaTransactionExt::{tx_size, tx_hash, estimated_da_size}` for -//! `MegaTxEnvelope`, `Recovered`, `Recovered<&MegaTxEnvelope>` and -//! `EnrichedMegaTx` (constant-return / `Default::default()` mutants). -//! * `limit.rs` — `BlockLimits::from_hardfork_and_block_gas_limit` per-field initializers (deleting -//! a field initializer makes it fall back to `..limits`, i.e. a different value). -//! * `hardfork.rs` — `MegaHardforks::is_*_active_at_timestamp` (`-> false` mutants). -//! * `chain.rs` — `hardfork_schedule` mainnet / testnet match arms (deleting an arm falls through -//! to the all-activated fallback, which has different activation conditions). - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_hardforks::ForkCondition; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, U256}; -use mega_evm::{ - constants, hardfork_schedule, mainnet_hardforks, testnet_hardforks, BlockLimits, - EnrichedMegaTx, MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaTransactionExt, - MegaTxEnvelope, MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000001"); -const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - -/// A known, non-zero cached tx hash baked into the test envelope. `MegaTxEnvelope::tx_hash` returns -/// the cached `Signed` hash, so storing a non-zero value here lets us distinguish the real accessor -/// from the `-> Default::default()` (== `TxHash::ZERO`) mutant. -const STORED_TX_HASH: alloy_primitives::B256 = - alloy_primitives::b256!("00000000000000000000000000000000000000000000000000000000000000aa"); - -/// A legacy transaction with a small, non-empty calldata so its encoded size and DA size are both -/// strictly greater than 1 (which kills both the `-> 0` and the `-> 1` constant-return mutants), -/// and a known non-zero cached hash so the `tx_hash` mutant is distinguishable. -fn legacy_envelope() -> MegaTxEnvelope { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - }; - MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), STORED_TX_HASH)) -} - -// ============================================================================ -// block/helpers.rs — MegaTransactionExt accessors -// ============================================================================ - -/// `MegaTxEnvelope::tx_size`/`estimated_da_size` must return the real encoded sizes (well above 1), -/// and `tx_hash` must return the real hash (not `Default::default()`). -#[test] -fn test_mega_tx_envelope_ext_returns_real_size_da_and_hash() { - let tx = legacy_envelope(); - - // A signed legacy tx with 5 bytes of calldata encodes to far more than 1 byte. - let tx_size = MegaTransactionExt::tx_size(&tx); - let da_size = MegaTransactionExt::estimated_da_size(&tx); - assert!(tx_size > 1, "tx_size collapsed to a constant: {tx_size}"); - assert!(da_size > 1, "estimated_da_size collapsed to a constant: {da_size}"); - - // tx_hash must return the cached hash, not Default::default() (== TxHash::ZERO). - let h = MegaTransactionExt::tx_hash(&tx); - assert_ne!(h, alloy_primitives::TxHash::ZERO, "tx_hash returned Default::default()"); - assert_eq!(h, STORED_TX_HASH, "tx_hash mismatch"); -} - -/// `Recovered::tx_hash` must return the inner envelope hash, not the default. -#[test] -fn test_recovered_mega_tx_envelope_ext_returns_real_hash() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx, CALLER); - - let h = MegaTransactionExt::tx_hash(&recovered); - assert_ne!(h, alloy_primitives::TxHash::ZERO, "recovered tx_hash returned Default::default()"); - assert_eq!(h, STORED_TX_HASH, "recovered tx_hash mismatch"); -} - -/// `Recovered<&MegaTxEnvelope>::tx_hash` must return the inner envelope hash, not the default. -/// Same shape as the owned `Recovered` case above, but for the by-reference impl -/// `MegaBlockExecutor::run_transaction` needs now that its bound is `MegaTransactionExt` (a -/// zero-copy `Recovered<&Tx>` is the common way a caller satisfies `Copy` without cloning the -/// transaction). -#[test] -fn test_recovered_ref_mega_tx_envelope_ext_returns_real_hash() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(&tx, CALLER); - - let h = MegaTransactionExt::tx_hash(&recovered); - assert_ne!( - h, - alloy_primitives::TxHash::ZERO, - "recovered-ref tx_hash returned Default::default()" - ); - assert_eq!(h, STORED_TX_HASH, "recovered-ref tx_hash mismatch"); -} - -/// `EnrichedMegaTx::{tx_size, estimated_da_size, tx_hash}` must dispatch to the stored fields, not -/// recompute from the inner transaction. Constructs the wrapper with stored values that -/// deliberately differ from what a fresh recomputation on the inner tx would produce, so a mutant -/// collapsing the override to a constant (or one that silently falls back to recomputing) is -/// distinguishable. -#[test] -fn test_enriched_mega_tx_ext_returns_stored_fields_not_recomputed() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx, CALLER); - - let real_da_size = MegaTransactionExt::estimated_da_size(&recovered); - let real_tx_size = MegaTransactionExt::tx_size(&recovered); - - const STORED_DA_SIZE: u64 = 424_242; - const STORED_TX_SIZE: u64 = 131_313; - assert_ne!(STORED_DA_SIZE, real_da_size, "stored da_size must differ from a fresh recompute"); - assert_ne!(STORED_TX_SIZE, real_tx_size, "stored tx_size must differ from a fresh recompute"); - - let enriched = EnrichedMegaTx::new(recovered, STORED_TX_HASH, STORED_DA_SIZE, STORED_TX_SIZE); - - assert_eq!( - MegaTransactionExt::estimated_da_size(&enriched), - STORED_DA_SIZE, - "estimated_da_size must return the stored field, not a recomputed value" - ); - assert_eq!( - MegaTransactionExt::tx_size(&enriched), - STORED_TX_SIZE, - "tx_size must return the stored field, not a recomputed value" - ); - assert_eq!( - MegaTransactionExt::tx_hash(&enriched), - STORED_TX_HASH, - "tx_hash must return the stored field, not Default::default()" - ); -} - -// ============================================================================ -// block/limit.rs — BlockLimits::from_hardfork_and_block_gas_limit -// ============================================================================ - -/// For a Rex hardfork, all three block-level field initializers must be set to their constants. -/// Deleting any initializer drops back to `..limits` (== `no_limits()` => `u64::MAX` for -/// state-growth, and the same `MiniRex` constants for data/kv), so asserting the exact value kills -/// the field-deletion mutants on lines 399/400/401. -#[test] -fn test_block_limits_from_rex_sets_all_three_block_fields() { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex4, 50_000_000); - - assert_eq!( - limits.block_txs_data_limit, - constants::mini_rex::BLOCK_DATA_LIMIT, - "block_txs_data_limit initializer dropped" - ); - assert_eq!( - limits.block_kv_update_limit, - constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - "block_kv_update_limit initializer dropped" - ); - assert_eq!( - limits.block_state_growth_limit, - constants::rex::BLOCK_STATE_GROWTH_LIMIT, - "block_state_growth_limit initializer dropped" - ); - assert_eq!(limits.block_gas_limit, 50_000_000, "block gas limit not applied"); -} - -/// For the `MiniRex` arm, `block_txs_data_limit` and `block_kv_update_limit` are set to the -/// `MiniRex` constants while `block_state_growth_limit` stays at the `no_limits()` default -/// (`u64::MAX`). Asserting the exact data/kv values kills the field-deletion mutants on lines -/// 405/406; the state-growth assertion pins the arm's distinct shape. -#[test] -fn test_block_limits_from_mini_rex_sets_data_and_kv_fields() { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::MiniRex, 30_000_000); - - assert_eq!( - limits.block_txs_data_limit, - constants::mini_rex::BLOCK_DATA_LIMIT, - "MiniRex block_txs_data_limit initializer dropped" - ); - assert_eq!( - limits.block_kv_update_limit, - constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - "MiniRex block_kv_update_limit initializer dropped" - ); - // MiniRex does not set a block state-growth limit; it inherits no_limits(). - assert_eq!( - limits.block_state_growth_limit, - u64::MAX, - "MiniRex must not set a block state-growth limit" - ); -} - -// ============================================================================ -// block/hardfork.rs — is_*_active_at_timestamp -// ============================================================================ - -/// Build a config where every named fork activates at a distinct, increasing timestamp so each -/// `is_*_active_at_timestamp` can be probed both before and at activation. -fn staged_config() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(200)) - .with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(300)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(400)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(500)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(600)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(700)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(800)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(900)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1000)) - .with(MegaHardfork::Rex7, ForkCondition::Timestamp(1100)) -} - -/// Each `is_*_active_at_timestamp` returns `true` at/after activation and `false` before, on a -/// complete ordered ladder (where the position-projected predicates coincide with the activation -/// events). This kills the `-> false` mutants on the predicate bodies in -/// `crates/mega-evm/src/block/hardfork.rs` at the lines referenced below. -/// -/// Every predicate is probed on **both** sides of its own activation, which is what pins the -/// spec each one projects. A behavior-introducing predicate's body is -/// `spec_id(t).reaches(MegaSpecId::X)`, so shifting `X` one rung either way is a -/// live mutation: shifting down makes the predicate fire at the rung below (caught by the -/// `false` assertion one second early), shifting up makes it stop firing at its own rung (caught -/// by the `true` assertion). A one-sided probe kills neither direction. -#[test] -fn test_hardfork_activation_predicates_are_true_at_activation() { - let cfg = staged_config(); - - // MiniRex (hardfork.rs:192) — spec-introducing (MINI_REX). Shifting down lands on - // EQUIVALENCE, which is enabled at every timestamp, so only the `false` side catches it. - assert!(!cfg.is_mini_rex_active_at_timestamp(99)); - assert!(cfg.is_mini_rex_active_at_timestamp(100)); - - // MiniRex1 (hardfork.rs:203) — alias fork, raw event query. - assert!(!cfg.is_mini_rex_1_active_at_timestamp(199)); - assert!(cfg.is_mini_rex_1_active_at_timestamp(200)); - - // MiniRex2 (hardfork.rs:213) — alias fork, raw event query. - assert!(!cfg.is_mini_rex_2_active_at_timestamp(299)); - assert!(cfg.is_mini_rex_2_active_at_timestamp(300)); - - // Rex (hardfork.rs:220). - assert!(!cfg.is_rex_active_at_timestamp(399)); - assert!(cfg.is_rex_active_at_timestamp(400)); - - // Rex1 (hardfork.rs:227). - assert!(!cfg.is_rex_1_active_at_timestamp(499)); - assert!(cfg.is_rex_1_active_at_timestamp(500)); - - // Rex2 (hardfork.rs:234). - assert!(!cfg.is_rex_2_active_at_timestamp(599)); - assert!(cfg.is_rex_2_active_at_timestamp(600)); - - // Rex3 (hardfork.rs:241). - assert!(!cfg.is_rex_3_active_at_timestamp(699)); - assert!(cfg.is_rex_3_active_at_timestamp(700)); - - // Rex4 (hardfork.rs:248). - assert!(!cfg.is_rex_4_active_at_timestamp(799)); - assert!(cfg.is_rex_4_active_at_timestamp(800)); - - // Rex5 (hardfork.rs:255). - assert!(!cfg.is_rex_5_active_at_timestamp(899)); - assert!(cfg.is_rex_5_active_at_timestamp(900)); - - // Rex6 (hardfork.rs:262). - assert!(!cfg.is_rex_6_active_at_timestamp(999)); - assert!(cfg.is_rex_6_active_at_timestamp(1000)); - - // Rex7 (hardfork.rs:269). - assert!(!cfg.is_rex_7_active_at_timestamp(1099)); - assert!(cfg.is_rex_7_active_at_timestamp(1100)); -} - -// ============================================================================ -// block/chain.rs — hardfork_schedule match arms -// ============================================================================ - -/// Deleting the `MAINNET_CHAIN_ID` arm makes `hardfork_schedule(4326)` fall through to the -/// all-activated fallback, which activates `MiniRex1` at genesis. The real mainnet schedule -/// activates `MiniRex1` at a specific non-zero timestamp, so the per-fork conditions distinguish -/// the two. -#[test] -fn test_hardfork_schedule_mainnet_arm_returns_mainnet_schedule() { - let from_dispatch = hardfork_schedule(MAINNET_CHAIN_ID); - let expected = mainnet_hardforks(); - - // MiniRex1 activation timestamp is mainnet-specific (1764845637), differs from the genesis - // activation of the all-activated fallback. - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - expected.get(MegaHardfork::MiniRex1), - "mainnet arm did not return the mainnet schedule" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - Some(&ForkCondition::Timestamp(1764845637)), - "mainnet MiniRex1 activation timestamp changed" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::Rex5), - Some(&ForkCondition::Timestamp(1780632000)), - "mainnet Rex5 activation timestamp changed" - ); -} - -/// Deleting the `TESTNET_CHAIN_ID` arm makes `hardfork_schedule(6343)` fall through to the -/// all-activated fallback. The testnet schedule sets MiniRex1/MiniRex2 to `Never` and Rex5 to a -/// testnet-specific timestamp, none of which the fallback reproduces. -#[test] -fn test_hardfork_schedule_testnet_arm_returns_testnet_schedule() { - let from_dispatch = hardfork_schedule(TESTNET_CHAIN_ID); - let expected = testnet_hardforks(); - - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - expected.get(MegaHardfork::MiniRex1), - "testnet arm did not return the testnet schedule" - ); - // Testnet disables MiniRex1 (Never) — the all-activated fallback would activate it at genesis. - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - Some(&ForkCondition::Never), - "testnet MiniRex1 should be Never" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::Rex5), - Some(&ForkCondition::Timestamp(1780459200)), - "testnet Rex5 activation timestamp changed" - ); -} - -// ============================================================================ -// block/limit.rs — BlockLimiter -// ============================================================================ -// -// `BlockLimiter` (`pub`, re-exported via `block::*`) is constructed directly with -// `BlockLimiter::new(BlockLimits)` and its `pub` usage counters are written directly, -// mirroring the inline `#[cfg(test)]` pattern at `limit.rs:1027+`. We start from -// `BlockLimits::no_limits()` (every limit == `u64::MAX`) and tighten exactly the one -// dimension under test, so the other clauses/checks cannot interfere. -// -// Covered survivors: -// * `pre_execution_check` boundary `>` checks (778/789/802/839): an at-limit value must return `Ok` -// (kills both `>`→`==` and `>`→`>=`, which error at equality); a strictly over-limit value must -// return the expected `Err`. -// * `post_execution_update` (947) `==`→`!=` on the deposit-type check: a non-deposit tx must -// advance `block_da_size_used`; a deposit tx must not. The `!=` mutant inverts both. -// * `is_block_limit_reached` (1011-1019): one per-dimension test with only that dimension at `used -// == limit` (others strictly below) asserting `true` kills that clause's `>=`→`<` and the -// adjacent `||`→`&&` (only one true clause ⇒ `&&` collapses to false); an all-below test -// asserting `false` kills the whole-fn `->true`, and the per-dimension trues kill the whole-fn -// `->false`. - -use alloy_consensus::transaction::Recovered as MegaRecovered; -use alloy_primitives::B256; -use mega_evm::{BlockLimiter, BlockMegaTransactionOutcome, MegaHaltReason, MegaTransactionOutcome}; -use revm::{ - context::result::{ExecutionResult, Output, SuccessReason}, - state::EvmState, -}; - -/// Builds a `BlockMegaTransactionOutcome` wrapping the given recovered tx, with the supplied -/// `da_size` and otherwise-zero usage, and a trivial `Success` execution result. Used to drive -/// `post_execution_update` and observe how the deposit-type branch routes the da accounting. -fn outcome_for( - tx: MegaRecovered, - da_size: u64, -) -> BlockMegaTransactionOutcome> { - BlockMegaTransactionOutcome { - tx, - tx_size: 0, - da_size, - depositor: None, - inner: MegaTransactionOutcome { - result: ExecutionResult::::Success { - reason: SuccessReason::Stop, - gas_used: 0, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Call(Bytes::new()), - }, - state: EvmState::default(), - data_size: 0, - kv_updates: 0, - compute_gas_used: 0, - state_growth_used: 0, - }, - } -} - -/// A non-deposit (legacy, tx type 0) recovered transaction. -fn legacy_recovered() -> MegaRecovered { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 0, - gas_price: 1, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO); - MegaRecovered::new_unchecked(MegaTxEnvelope::Legacy(signed), CALLER) -} - -// --------------------------------------------------------------------------- -// pre_execution_check boundaries -// --------------------------------------------------------------------------- - -/// 778:22 (`gas_limit > self.limits.tx_gas_limit`). A gas limit *equal* to the per-tx cap must -/// pass (kills `>`→`==` and `>`→`>=`, which both error at equality); one over must error. -#[test] -fn test_pre_execution_check_tx_gas_limit_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.tx_gas_limit = 1_000; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 1_000, 0, 0, false).is_ok(), - "gas_limit == tx_gas_limit must be admitted (boundary is strict `>`)" - ); - let over = limiter.pre_execution_check(B256::ZERO, 1_001, 0, 0, false); - assert!(over.is_err(), "gas_limit == tx_gas_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionGasLimit"), - "over-limit gas must report the per-tx gas-limit error" - ); -} - -/// 789:58 (`block_gas_used + gas_limit > block_gas_limit`). With `block_gas_used == 0`, a -/// `gas_limit` exactly equal to `block_gas_limit` must pass (kills `>`→`>=`); one over errors. -#[test] -fn test_pre_execution_check_block_gas_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 1_000; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 1_000, 0, 0, false).is_ok(), - "block_gas_used + gas_limit == block_gas_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 1_001, 0, 0, false); - assert!(over.is_err(), "block_gas_used + gas_limit == block_gas_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionGasLimitMoreThanAvailableBlockGas"), - "over-limit block gas must report the available-block-gas error" - ); -} - -/// 802:20 (`tx_size > self.limits.tx_encode_size_limit`). A `tx_size` equal to the cap must pass -/// (kills `>`→`==` and `>`→`>=`); one over errors. -#[test] -fn test_pre_execution_check_tx_size_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.tx_encode_size_limit = 500; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 0, 500, 0, false).is_ok(), - "tx_size == tx_encode_size_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 0, 501, 0, false); - assert!(over.is_err(), "tx_size == tx_encode_size_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionEncodeSizeLimit"), - "over-limit tx size must report the per-tx encode-size error" - ); -} - -/// 839:64 (`da_size + block_da_size_used > block_da_size_limit`). With `block_da_size_used == 0`, -/// a non-deposit `da_size` equal to `block_da_size_limit` must pass (kills `>`→`>=`); one over -/// errors. (`tx_da_size_limit` stays `u64::MAX`, so the per-tx da check at 828 never triggers.) -#[test] -fn test_pre_execution_check_block_da_size_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.block_da_size_limit = 800; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 0, 0, 800, false).is_ok(), - "da_size + block_da_size_used == block_da_size_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 0, 0, 801, false); - assert!( - over.is_err(), - "da_size + block_da_size_used == block_da_size_limit + 1 must be rejected" - ); - assert!( - format!("{:?}", over.unwrap_err()).contains("DataAvailabilitySizeLimit"), - "over-limit block da must report the data-availability error" - ); -} - -// --------------------------------------------------------------------------- -// post_execution_update — deposit-type branch (947 `==`→`!=`) -// --------------------------------------------------------------------------- - -/// 947 (`outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE`). A non-deposit (legacy) tx must -/// advance `block_da_size_used` by `da_size`. Under the `==`→`!=` mutant the legacy type is -/// (mis)classified as a deposit, so the da counter would stay at 0. -#[test] -fn test_post_execution_update_advances_da_for_non_deposit() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - let outcome = outcome_for(legacy_recovered(), 1_234); - - limiter.post_execution_update(&outcome).expect("post_execution_update should succeed"); - - assert_eq!( - limiter.block_da_size_used, 1_234, - "a non-deposit tx must accumulate da_size; the `==`→`!=` mutant would skip it (0)" - ); -} - -// --------------------------------------------------------------------------- -// is_block_limit_reached — per-dimension boundary + all-clause OR (1011-1019) -// --------------------------------------------------------------------------- - -/// All counters strictly below their limits ⇒ `false`. Kills the whole-fn `->true` mutant. -#[test] -fn test_is_block_limit_reached_all_below_is_false() { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 10; - limits.block_txs_encode_size_limit = 10; - limits.block_da_size_limit = 10; - limits.block_txs_data_limit = 10; - limits.block_kv_update_limit = 10; - limits.block_compute_gas_limit = 10; - limits.block_state_growth_limit = 10; - let mut limiter = BlockLimiter::new(limits); - limiter.block_gas_used = 9; - limiter.block_tx_size_used = 9; - limiter.block_da_size_used = 9; - limiter.block_data_used = 9; - limiter.block_kv_updates_used = 9; - limiter.block_compute_gas_used = 9; - limiter.block_state_growth_used = 9; - - assert!( - !limiter.is_block_limit_reached(), - "with every counter strictly below its limit the block is not full" - ); -} - -/// Helper: a limiter where exactly one dimension sits at `used == limit` and all others are -/// strictly below (limit 10, used 0). Asserting `true` kills that clause's `>=`→`<` (equality -/// would become false) and the adjacent `||`→`&&` (with a single true clause, `&&` ⇒ false). -macro_rules! only_dimension_at_limit { - ($limit_field:ident, $used_field:ident) => {{ - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 10; - limits.block_txs_encode_size_limit = 10; - limits.block_da_size_limit = 10; - limits.block_txs_data_limit = 10; - limits.block_kv_update_limit = 10; - limits.block_compute_gas_limit = 10; - limits.block_state_growth_limit = 10; - limits.$limit_field = 5; - let mut limiter = BlockLimiter::new(limits); - // all counters strictly below their (10) limits... - limiter.block_gas_used = 0; - limiter.block_tx_size_used = 0; - limiter.block_da_size_used = 0; - limiter.block_data_used = 0; - limiter.block_kv_updates_used = 0; - limiter.block_compute_gas_used = 0; - limiter.block_state_growth_used = 0; - // ...except the one under test, which sits exactly at its (5) limit. - limiter.$used_field = 5; - limiter - }}; -} - -#[test] -fn test_is_block_limit_reached_gas_dimension() { - let limiter = only_dimension_at_limit!(block_gas_limit, block_gas_used); - assert!(limiter.is_block_limit_reached(), "gas at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_tx_size_dimension() { - let limiter = only_dimension_at_limit!(block_txs_encode_size_limit, block_tx_size_used); - assert!(limiter.is_block_limit_reached(), "tx encode size at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_da_size_dimension() { - let limiter = only_dimension_at_limit!(block_da_size_limit, block_da_size_used); - assert!(limiter.is_block_limit_reached(), "da size at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_data_dimension() { - let limiter = only_dimension_at_limit!(block_txs_data_limit, block_data_used); - assert!(limiter.is_block_limit_reached(), "tx data at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_kv_updates_dimension() { - let limiter = only_dimension_at_limit!(block_kv_update_limit, block_kv_updates_used); - assert!(limiter.is_block_limit_reached(), "kv updates at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_compute_gas_dimension() { - let limiter = only_dimension_at_limit!(block_compute_gas_limit, block_compute_gas_used); - assert!(limiter.is_block_limit_reached(), "compute gas at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_state_growth_dimension() { - let limiter = only_dimension_at_limit!(block_state_growth_limit, block_state_growth_used); - assert!(limiter.is_block_limit_reached(), "state growth at limit ⇒ block full"); -} diff --git a/crates/mega-evm/tests/_pending/mutation/constants.rs b/crates/mega-evm/tests/_pending/mutation/constants.rs deleted file mode 100644 index 9e9cf316c..000000000 --- a/crates/mega-evm/tests/_pending/mutation/constants.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Value-pinning tests for the arithmetic `pub const` definitions in -//! `src/constants.rs`. -//! -//! Several constants are defined via compile-time arithmetic (e.g. -//! `12 * 1024 * 1024 + 512 * 1024`). Mutation testing replaces individual -//! operators (`*`→`+`, `+`→`-`, `/`→`*`, …) inside these expressions, which -//! changes the resulting numeric value but leaves the program compiling. None -//! of the targeted expressions are no-ops, so every operator swap is a true -//! behavioral change. -//! -//! Each test below asserts the constant equals its exact unmutated value. Any -//! arithmetic mutation on the relevant line yields a different value and is -//! therefore killed. - -use mega_evm::constants::{mini_rex, rex}; - -/// Pins `mini_rex::ADDITIONAL_INITCODE_SIZE` (`24 * 1024`). -/// -/// Kills `constants.rs:25:52 replace * with /` and `:25:52 replace * with +`. -#[test] -fn test_mini_rex_additional_initcode_size() { - assert_eq!(mini_rex::ADDITIONAL_INITCODE_SIZE, 24 * 1024); - assert_eq!(mini_rex::ADDITIONAL_INITCODE_SIZE, 24_576); -} - -/// Pins `mini_rex::MAX_INITCODE_SIZE` -/// (`MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE`). -/// -/// Kills `constants.rs:27:60 replace + with -`. -#[test] -fn test_mini_rex_max_initcode_size() { - // 512 * 1024 + 24 * 1024 = 524_288 + 24_576 - assert_eq!(mini_rex::MAX_INITCODE_SIZE, 548_864); - assert_eq!( - mini_rex::MAX_INITCODE_SIZE, - mini_rex::MAX_CONTRACT_SIZE + mini_rex::ADDITIONAL_INITCODE_SIZE - ); -} - -/// Pins `mini_rex::BLOCK_DATA_LIMIT` (`12 * 1024 * 1024 + 512 * 1024`, 12.5 MB). -/// -/// Kills `constants.rs:59:62 replace * with +`, `:59:56 replace + with -`, -/// `:59:62 replace * with /`, and `:59:56 replace + with *`. -#[test] -fn test_mini_rex_block_data_limit() { - assert_eq!(mini_rex::BLOCK_DATA_LIMIT, 12 * 1024 * 1024 + 512 * 1024); - assert_eq!(mini_rex::BLOCK_DATA_LIMIT, 13_107_200); -} - -/// Pins `rex::TX_DATA_LIMIT` (`12 * 1024 * 1024 + 512 * 1024`, same as the -/// block data limit). -/// -/// Kills the full operator-swap cluster on line 188: `+:53 with *`/`with -`, -/// `*:46 with +`/`with /`, `*:59 with +`/`with /`, and `*:39 with /`/`with +`. -#[test] -fn test_rex_tx_data_limit() { - assert_eq!(rex::TX_DATA_LIMIT, 12 * 1024 * 1024 + 512 * 1024); - assert_eq!(rex::TX_DATA_LIMIT, 13_107_200); -} diff --git a/crates/mega-evm/tests/_pending/mutation/external_exec.rs b/crates/mega-evm/tests/_pending/mutation/external_exec.rs deleted file mode 100644 index 28a205961..000000000 --- a/crates/mega-evm/tests/_pending/mutation/external_exec.rs +++ /dev/null @@ -1,347 +0,0 @@ -//! Value/behavioral tests that close surviving mutants in `crates/mega-evm/src/block/executor.rs` -//! and `crates/mega-evm/src/external/`. -//! -//! The `src/**` modules carry inline `#[cfg(test)] mod tests`, but those unit tests are not -//! exercised by the mutation run (which builds the integration test targets). These integration -//! tests re-assert the same invariants through the crate's public / `test-utils`-gated API. -//! -//! Covered survivors: -//! * `block/executor.rs:70` — `Debug::fmt` replaced with `Ok(Default::default())`. The real impl -//! writes the struct name; the mutant writes nothing. We pin the formatted output. -//! * `block/executor.rs:297` — `post_execution_changes -> Ok(vec![])`. The real body *always* -//! pushes exactly one `PostBlock(BalanceIncrements)` outcome (because -//! `eips::transact_balance_increments` unconditionally returns `Some(state)`), so a fresh -//! executor's `post_execution_changes()` returns a length-1 vec. The mutant returns length 0. -//! * `block/executor.rs:496` — `get_accessed_bucket_ids -> vec![]` and `-> -//! vec![Default::default()]` (i.e. `vec![0]`). After a transaction that performs an `SSTORE` -//! (zero→non-zero), the dynamic storage gas tracker records the slot's bucket id. With -//! `TestExternalEnvs`'s default `SimpleBucketHasher`, that id lies in `[NUM_META_BUCKETS, -//! NUM_BUCKETS)` (≥ `65_536`), so the returned set is non-empty and never `{0}` — killing both -//! variants. -//! * `external/hasher/fallback.rs:{109,112,120}` — value-changing mutations in -//! `DeterministicHasher::write`. `AHashBucketHasher` is the public, production-compatible hasher -//! whose contract is to reproduce SPECIFIC bucket ids matching the `salt` crate. We pin known -//! input→bucket-id pairs, one per affected `write` branch, against the documented expected values -//! (the same constants cross-checked against `salt` in `src/external/hasher/mod.rs`). The `125:47 -//! |`→`&` mutant is also killed by `ahash_bucket_id_small_input_is_pinned` (the small-input -//! combine), but the `125:47 |`→`^` mutant is provably equivalent and is recorded in -//! `mutants/suppressions.toml`: at line 125 the `|` ORs `value[0] as u128` (occupies only bits -//! 0..63) with `(value[1] as u128) << 64` (occupies only bits 64..127); the operands have -//! disjoint set bits for every input, so `| == ^` identically and no input distinguishes them. -//! * `external/hasher/fallback.rs:{108,112}` — the `>`→`>=` length-routing boundary mutants in -//! `write`. The full run hid these because no pinned input had a length sitting exactly on a -//! boundary; we add `len == {8,32}` inputs whose bucket id flips when the comparison does -//! (`ahash_bucket_id_len{8,32}_*`). The sibling line-109 `> 16`→`>= 16` is provably equivalent (a -//! len-16 input hashes identically either way — see the suppression note below) and is recorded -//! in `mutants/suppressions.toml`. -//! -//! The remaining `fallback.rs` survivors are recorded in `mutants/suppressions.toml` as -//! dead/unreachable code rather than killed here: the typed `write_u8/u16/u32/u64/u128 -> ()` -//! stubs and the two `^`→`|`/`&` mutants inside `update`. `AHashBucketHasher::bucket_id` drives -//! only the slice `write` (→ `large_update`); it never invokes the typed `write_uN` methods nor -//! `update`. Those are reachable solely via `core::hash::Hasher` trait dispatch on the -//! `pub(crate)`, non-re-exported `DeterministicHasher`, which no integration test (separate crate) -//! can construct — and no non-test caller anywhere in `mega-evm` invokes them. So no public-API -//! input distinguishes the mutants. -//! -//! `external/mod.rs:94` (`EmptyExternalEnv::external_envs` → -//! `ExternalEnvs::from(Default::default())`) is provably equivalent and is recorded in -//! `mutants/suppressions.toml` instead of being killed here: `EmptyExternalEnv` is a unit struct, -//! so both the real body (`ExternalEnvs { salt_env: EmptyExternalEnv, oracle_env: EmptyExternalEnv -//! }`) and the mutant (`From>` of the `Default` impl, which yields -//! the identical fields) construct the same value; no observable behavior distinguishes them. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{ - block::{BlockExecutor, StateChangePostBlockSource, StateChangeSource}, - EvmEnv, EvmFactory, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - AHashBucketHasher, BlockLimits, BucketHasher, MegaBlockExecutionCtx, MegaBlockExecutor, - MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, TestExternalEnvs, -}; -use revm::{context::BlockEnv, database::State}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const STORAGE_CONTRACT: Address = address!("1000000000000000000000000000000000000003"); - -/// Lower bound of the valid SALT bucket range (`NUM_BUCKETS / MIN_BUCKET_SIZE`, i.e. 256^3 / 256). -/// Both `SimpleBucketHasher` and `AHashBucketHasher` map keys into `[NUM_META_BUCKETS, -/// NUM_BUCKETS)`. -const NUM_META_BUCKETS: u32 = (1u32 << 24) / 256; // 65_536 - -fn create_transaction( - nonce: u64, - to: Address, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit: 1_000_000, - to: TxKind::Call(to), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Wires a `MegaBlockExecutor` over `state` at the `MiniRex` spec, with a `TestExternalEnvs` salt -/// environment (default `SimpleBucketHasher`). Mirrors -/// `tests/block_executor/accessed_block_hashes`. -macro_rules! build_executor { - ($state:expr) => {{ - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm = evm_factory.create_evm($state, EvmEnv::new(cfg_env, block_env)); - - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - MegaBlockExecutor::new(evm, block_ctx, chain_spec, OpAlloyReceiptBuilder::default()) - }}; -} - -// ============================================================================ -// block/executor.rs:70 — Debug::fmt -// ============================================================================ - -/// `Debug` for `MegaBlockExecutor` must write the struct name. The mutant returns `Ok(())` -/// without writing anything, producing an empty string. -#[test] -fn test_block_executor_debug_writes_struct_name() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let executor = build_executor!(&mut state); - - let rendered = format!("{executor:?}"); - assert!( - rendered.contains("MegaethBlockExecutor"), - "Debug output must name the struct, got {rendered:?}" - ); - assert!(!rendered.is_empty(), "Debug output must not be empty"); -} - -// ============================================================================ -// block/executor.rs:297 — post_execution_changes -// ============================================================================ - -/// `post_execution_changes` always produces exactly one `PostBlock(BalanceIncrements)` outcome, -/// because `eips::transact_balance_increments` unconditionally returns `Some(state)`. The mutant -/// drops it to an empty vec. -#[test] -fn test_post_execution_changes_yields_balance_increment_outcome() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = build_executor!(&mut state); - - let outcomes = - executor.post_execution_changes().expect("post_execution_changes should succeed"); - - assert_eq!( - outcomes.len(), - 1, - "post_execution_changes must yield exactly one system-call outcome; the mutant drops it" - ); - assert!( - matches!( - outcomes[0].source, - StateChangeSource::PostBlock(StateChangePostBlockSource::BalanceIncrements) - ), - "the single outcome must be the post-block balance-increment source, got {:?}", - outcomes[0].source - ); -} - -// ============================================================================ -// block/executor.rs:496 — get_accessed_bucket_ids -// ============================================================================ - -/// A contract that writes a non-zero value to a previously-zero storage slot, then stops. -/// The `SSTORE` triggers the dynamic SALT gas hook, recording the slot's bucket id. -fn sstore_contract() -> Bytes { - BytecodeBuilder::default().sstore(U256::from(7), U256::from(42)).stop().build() -} - -/// After a transaction performs an `SSTORE`, `get_accessed_bucket_ids` returns the non-empty set -/// of buckets touched. With the default `SimpleBucketHasher` every recorded id is in -/// `[NUM_META_BUCKETS, NUM_BUCKETS)` (≥ `65_536`), so the result is neither empty (kills `vec![]`) -/// nor `{0}` (kills `vec![Default::default()]`). -#[test] -fn test_get_accessed_bucket_ids_records_sstore_bucket() { - let mut db = MemoryDatabase::default(); - db.set_account_code(STORAGE_CONTRACT, sstore_contract()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = build_executor!(&mut state); - - executor - .execute_transaction(&create_transaction(0, STORAGE_CONTRACT)) - .expect("sstore tx should succeed"); - - let ids = executor.get_accessed_bucket_ids(); - assert!(!ids.is_empty(), "an SSTORE must record at least one accessed bucket id"); - assert!( - ids.iter().all(|&id| id >= NUM_META_BUCKETS), - "every recorded bucket id must lie in the valid KV range (>= {NUM_META_BUCKETS}); \ - a `vec![0]` mutant would violate this, got {ids:?}" - ); -} - -// ============================================================================ -// external/hasher/fallback.rs:{109,112,120,125} — DeterministicHasher::write branches -// ============================================================================ -// -// `AHashBucketHasher::bucket_id(key)` = `hash(key) % NUM_KV_BUCKETS + NUM_META_BUCKETS`, where -// `hash` is the deterministic AHash fallback. Its `write` routes by input length: -// -// * len <= 8 -> small branch; line 125 `|` combine -// * 9 <= len <= 16 -> mid branch; line 120 `|` combine, and the line-109 `> 16` outer guard -// (false here) selects this branch -// * len >= 17 -> large branch; the line-109 `> 16` outer guard (true) and the line-112 -// `while data.len() > 16` loop guard both gate the 16-byte block reads -// -// The four mutations (`>`→`==` on 109/112, `|`→`&` on 120/125) all change the produced hash for an -// input that hits their branch, hence change the bucket id. We pin one input per branch against the -// expected unmutated value. Expected hashes are the documented cross-checked values from -// `src/external/hasher/mod.rs` (`hash("hello") = 1027176506268606463`, etc.); expected bucket ids -// for the >=17-byte inputs are the documented `bucket_id` cross-check values from that same module. - -/// `NUM_KV_BUCKETS = NUM_BUCKETS - NUM_META_BUCKETS = 16_777_216 - 65_536`. -const NUM_KV_BUCKETS: u64 = (1u64 << 24) - ((1u64 << 24) / 256); -const NUM_META_BUCKETS_U64: u64 = (1u64 << 24) / 256; - -/// Maps a documented `hash(key)` value to the expected bucket id. -const fn bucket_id_from_hash(hash: u64) -> u32 { - (hash % NUM_KV_BUCKETS + NUM_META_BUCKETS_U64) as u32 -} - -/// `len <= 8` (small branch, line 125): `"hello"` is 5 bytes. -/// `hash("hello") = 1_027_176_506_268_606_463` (documented in `external/hasher/mod.rs`). -#[test] -fn test_ahash_bucket_id_small_input_is_pinned() { - assert_eq!( - AHashBucketHasher::bucket_id(b"hello"), - bucket_id_from_hash(1_027_176_506_268_606_463), - "small-input (<=8B) bucket id changed: a `|`->`&` mutant on the line-125 combine alters it" - ); -} - -/// `9 <= len <= 16` (mid branch, lines 120 and 109): `"hash test"` is 9 bytes. -/// `hash("hash test") = 2_116_618_212_096_523_432` (documented in `external/hasher/mod.rs`). -/// A `> 16`→`== 16` mutant on line 109 would route a 9-byte input identically, but a `>`→`==` -/// at line 109 also misroutes the boundary len 16 and all len >= 17 — covered by the large test — -/// while the `|`->`&` mutant on line 120 directly changes this 9-byte result. -#[test] -fn test_ahash_bucket_id_mid_input_is_pinned() { - assert_eq!( - AHashBucketHasher::bucket_id(b"hash test"), - bucket_id_from_hash(2_116_618_212_096_523_432), - "mid-input (9..=16B) bucket id changed: a `|`->`&` mutant on the line-120 combine alters it" - ); -} - -/// `len >= 17` (large branch, lines 109 + 112). -/// -/// `[0u8; 20]` -> bucket id `12_666_336`; the 52-byte address+slot key -> `9_450_146`; the 20-byte -/// `deadbeef` address -> `12_196_828`. All three are documented cross-check values from -/// `external/hasher/mod.rs`. At these lengths the loop `while data.len() > 16` runs at least once -/// (and three times for the 52-byte key); the `> 16`→`== 16` mutants on lines 109/112 skip or -/// misroute those reads, changing the hash. -#[test] -fn test_ahash_bucket_id_large_input_is_pinned() { - // 20-byte all-zero key: single loop iteration after the tail update. - assert_eq!( - AHashBucketHasher::bucket_id(&[0u8; 20]), - 12_666_336, - "large-input (20B) bucket id changed: a `> 16`->`== 16` mutant on line 109/112 alters it" - ); - - // 20-byte non-zero address: distinct branch input, documented cross-check value. - let addr: [u8; 20] = [ - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0a, 0x0b, - ]; - assert_eq!(AHashBucketHasher::bucket_id(&addr), 12_196_828, "20B address bucket id changed"); - - // 52-byte address+slot key: the loop iterates multiple times (52 -> 36 -> 20), so the - // line-112 `while data.len() > 16` guard is exercised across several reads. - let mut slot_key = [0u8; 52]; - slot_key[..20].copy_from_slice(&addr); - slot_key[51] = 1; - assert_eq!( - AHashBucketHasher::bucket_id(&slot_key), - 9_450_146, - "52B slot key bucket id changed: a `> 16`->`== 16` mutant truncates the block loop" - ); -} - -// ============================================================================ -// external/hasher/fallback.rs:{108,112} — length-routing boundary mutants -// ============================================================================ -// -// `write` routes by input length with three `>` comparisons. The full run hid the -// `>`→`>=` boundary variants because no pinned input had a length sitting exactly on a -// boundary. Each test below uses an input whose length lands on the relevant boundary so -// the `>`→`>=` flip changes which branch (or how many loop iterations) executes, and thus -// the produced hash and bucket id: -// -// * line 108 `data.len() > 8` : at len == 8 the original takes the small branch (read_small); -// `>= 8` reroutes len-8 input into the mid branch (read_u64 front + read_last_u64 back), a -// different combine. -// * line 112 `while data.len() > 16` : with a len that is a multiple of 16 (== 32), the loop hits -// `data.len() == 16` mid-iteration. `>` stops there (1 pass); `>= 16` runs a second read_u128 -// pass, changing the hash. -// -// The line-109 `> 16`→`>= 16` mutant is NOT here: it is provably equivalent (a len-16 input -// produces the identical single `large_update(le_u128(bytes[0..16]))` under both branches — -// the mid branch's `front | (back << 64)` reassembles the same little-endian u128 that the -// large branch's `read_last_u128` reads), so it is recorded in `mutants/suppressions.toml`. -// -// Expected bucket ids are the unmutated `AHashBucketHasher::bucket_id` outputs for these -// exact inputs (the production hasher's contract is to reproduce specific salt-compatible -// bucket ids), pinned the same way as the documented large-input cross-check values above. - -/// `len == 8` boundary (line 108 `> 8`). The small branch (`read_small`) is taken; a `>= 8` -/// mutant misroutes this input into the mid branch. -#[test] -fn test_ahash_bucket_id_len8_boundary_is_pinned() { - let key: [u8; 8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]; - assert_eq!( - AHashBucketHasher::bucket_id(&key), - 1_978_187, - "len-8 bucket id changed: a `> 8`->`>= 8` mutant on line 108 reroutes the small branch" - ); -} - -/// `len == 32` boundary (line 112 `while data.len() > 16`). The loop reaches `data.len() -/// == 16` after one 16-byte read; `>` stops (one pass) while a `>= 16` mutant runs a second -/// `read_u128` pass, changing the hash. -#[test] -fn test_ahash_bucket_id_len32_loop_boundary_is_pinned() { - let key: [u8; 32] = [0x22; 32]; - assert_eq!( - AHashBucketHasher::bucket_id(&key), - 10_093_090, - "len-32 bucket id changed: a `> 16`->`>= 16` mutant on the line-112 loop guard adds a pass" - ); -} diff --git a/crates/mega-evm/tests/_pending/mutation/main.rs b/crates/mega-evm/tests/_pending/mutation/main.rs deleted file mode 100644 index 15ef02a6f..000000000 --- a/crates/mega-evm/tests/_pending/mutation/main.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Auto-generated mutation-killing **system tests** for `crates/mega-evm/src/`. -//! -//! # What lives here -//! -//! This directory holds tests that were generated by the mutation-improvement -//! workflow (the `improve-mutation-score` skill) to close *specific* surviving -//! mutants surfaced by `cargo-mutants`. Each submodule targets the survivors of -//! one source area; every test maps back to a concrete mutant and kills it by -//! either asserting an exact value (constants, discriminants, computed limits) -//! or observing a behavioral difference through the public EVM harness. -//! -//! # Scope: system tests only -//! -//! Only **system / integration-level** tests belong here — those that exercise -//! mega-evm through its public (or `test-utils`-gated) API end-to-end, because -//! the mutant they kill is only observable through whole-EVM behavior. -//! -//! A mutant that can be killed by a **unit test** of one module does **not** -//! belong here: put that test inline next to the code it covers, in the source -//! module's own `#[cfg(test)] mod tests`. Reserve this directory for the cases -//! that genuinely need a full-execution harness to observe. -//! -//! Mutants found to be provably equivalent or dead are not tested at all — they -//! are recorded in `mutants/suppressions.toml` with a justification and reviewer. -//! -//! # Do not hand-edit -//! -//! These tests are **machine-generated and machine-maintained**. Treat them as -//! generated artifacts: -//! -//! - Do **not** rename, reword, or refactor them by hand — each test is keyed to a mutant, and -//! editing it can silently stop it from killing that mutant. -//! - Do **not** add unrelated assertions here; write ordinary tests in the relevant module or the -//! spec-organized suites under `tests/` instead. -//! - To close a *new* survivor, re-run the `improve-mutation-score` skill rather than authoring a -//! test here manually, so it stays linked to its mutant and the suppression bookkeeping stays -//! consistent. -//! -//! If a test here is wrong or stale, fix the source/suppression and regenerate; -//! don't patch the generated test in place. -//! -//! See `mutants/README.md` and the `improve-mutation-score` skill for the full -//! methodology. - -mod access_evm; -mod block; -mod constants; -mod external_exec; From 1255c9a56008b3bb2a92ae940c68681918cd0ddc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:36:52 +0800 Subject: [PATCH 040/201] test: port the test gates' parked CREATE and CREATE2 tests into the differential corpus --- crates/mega-differential/README.md | 6 +- .../create2_empty_initcode_large_offset.json | 23 + .../create2_empty_initcode_offset_max.json | 23 + .../create2_empty_initcode_offset_zero.json | 23 + .../harness/create2_initcode_10mib.json | 23 + .../harness/create2_initcode_32k.json | 23 + .../harness/create2_initcode_600k.json | 23 + .../harness/create2_initcode_at_limit.json | 23 + .../harness/create2_initcode_memory_oog.json | 23 + .../harness/create2_initcode_over_limit.json | 23 + .../harness/create2_missing_length.json | 23 + .../harness/create2_missing_offset.json | 23 + .../harness/create2_missing_salt.json | 23 + .../create2_nonempty_initcode_offset_max.json | 23 + ...sized_initcode_unrepresentable_offset.json | 23 + .../create2_static_empty_initcode.json | 29 + ...create2_static_empty_initcode_low_gas.json | 29 + .../create2_static_initcode_10mib.json | 29 + .../harness/create2_static_initcode_600k.json | 29 + .../create2_static_missing_operands.json | 29 + .../harness/create_static_low_gas.json | 29 + crates/mega-evm/tests/_pending/README.md | 38 +- .../tests/_pending/rex4/create_safety.rs | 150 ----- crates/mega-evm/tests/_pending/rex4/main.rs | 1 - .../_pending/rex5/create2_empty_initcode.rs | 168 ------ .../rex5/create2_resize_gas_metering.rs | 192 ------ crates/mega-evm/tests/_pending/rex5/main.rs | 2 - .../_pending/rex6/create2_metering_order.rs | 568 ------------------ .../tests/_pending/rex6/error_paths.rs | 50 +- crates/mega-evm/tests/_pending/rex6/main.rs | 1 - 30 files changed, 534 insertions(+), 1138 deletions(-) create mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json create mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json create mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_10mib.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_32k.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_600k.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json create mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json create mode 100644 crates/mega-differential/scenarios/harness/create2_missing_length.json create mode 100644 crates/mega-differential/scenarios/harness/create2_missing_offset.json create mode 100644 crates/mega-differential/scenarios/harness/create2_missing_salt.json create mode 100644 crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json create mode 100644 crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json create mode 100644 crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json create mode 100644 crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json create mode 100644 crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json create mode 100644 crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json create mode 100644 crates/mega-differential/scenarios/harness/create2_static_missing_operands.json create mode 100644 crates/mega-differential/scenarios/harness/create_static_low_gas.json delete mode 100644 crates/mega-evm/tests/_pending/rex4/create_safety.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 7119a01d6..935a1d7a0 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 323 scenarios, 12401 fields compared, 1004 deviations matched (op-fee-vault-touch x996, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects +differential: 343 scenarios, 13027 fields compared, 1064 deviations matched (op-fee-vault-touch x1056, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects ``` CI runs the same command as the `differential` job (`.github/workflows/differential.yml`), on every pull request and every push to `satin`. @@ -63,7 +63,7 @@ The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | | `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | | `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | -| `harness/` | 37 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, and the three cases of `crates/mega-evm/tests/satin/equivalence.rs` | +| `harness/` | 57 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | The first two sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. @@ -84,6 +84,8 @@ For every transaction: - the logs; - every touched account: created and self-destructed flags, balance, nonce, code hash, and the value of every slot the transaction changed. +The halt reason of an inner frame is not compared, only what it does to the gas, the state and its caller (a scenario that needs it records the call's success in storage). + ## The deviation registry `deviations.json` lists the accepted differences. diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json new file mode 100644 index 000000000..c28b038ab --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json @@ -0,0 +1,23 @@ +{ + "name": "create2_empty_initcode_large_offset", + "description": "CREATE2 with empty initcode at offset 2^30: no memory expansion is charged (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x6000600063400000006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json new file mode 100644 index 000000000..00a3cdc0e --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json @@ -0,0 +1,23 @@ +{ + "name": "create2_empty_initcode_offset_max", + "description": "CREATE2 with empty initcode at offset 2^256 - 1: the offset is ignored and the create succeeds (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json new file mode 100644 index 000000000..638c05391 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json @@ -0,0 +1,23 @@ +{ + "name": "create2_empty_initcode_offset_zero", + "description": "CREATE2 with empty initcode at offset 0 deploys empty code (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x6000600060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json b/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json new file mode 100644 index 000000000..96a3ee1ce --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_10mib", + "description": "CREATE2 of 10 MiB of initcode, far over the initcode size limit (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600062a0000060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_32k.json b/crates/mega-differential/scenarios/harness/create2_initcode_32k.json new file mode 100644 index 000000000..dbdedf34a --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_32k.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_32k", + "description": "CREATE2 of 32 KiB of zero initcode: a non-trivial memory expansion, then a STOP constructor (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600061800060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_600k.json b/crates/mega-differential/scenarios/harness/create2_initcode_600k.json new file mode 100644 index 000000000..52edbb713 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_600k.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_600k", + "description": "CREATE2 of 600,000 bytes of initcode, over the initcode size limit with an affordable memory expansion (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x6000620927c060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json b/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json new file mode 100644 index 000000000..9d77a1369 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_at_limit", + "description": "CREATE2 of exactly 49,152 bytes, the EIP-3860 initcode size limit the configuration carries today: it is accepted (ported from the legacy suite, whose bound was MegaETH's own).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600061c00060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json b/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json new file mode 100644 index 000000000..c71485ad6 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_memory_oog", + "description": "CREATE2 of 500,000 bytes of initcode under a 200,000 gas limit. Over the 49,152-byte initcode size limit the configuration carries today, the size check halts the frame before memory expansion; under a limit above 500,000 bytes the memory expansion would run out of gas instead (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x60006207a12060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 200000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json b/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json new file mode 100644 index 000000000..8a955582b --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json @@ -0,0 +1,23 @@ +{ + "name": "create2_initcode_over_limit", + "description": "CREATE2 of 49,153 bytes, one over the EIP-3860 initcode size limit (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600061c00160006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_length.json b/crates/mega-differential/scenarios/harness/create2_missing_length.json new file mode 100644 index 000000000..e37b7e871 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_missing_length.json @@ -0,0 +1,23 @@ +{ + "name": "create2_missing_length", + "description": "CREATE2 with two operands (no length) halts with a stack underflow (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x60006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_offset.json b/crates/mega-differential/scenarios/harness/create2_missing_offset.json new file mode 100644 index 000000000..85a8355f4 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_missing_offset.json @@ -0,0 +1,23 @@ +{ + "name": "create2_missing_offset", + "description": "CREATE2 with one operand (no offset) halts with a stack underflow (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x6000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_salt.json b/crates/mega-differential/scenarios/harness/create2_missing_salt.json new file mode 100644 index 000000000..c80bed8e2 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_missing_salt.json @@ -0,0 +1,23 @@ +{ + "name": "create2_missing_salt", + "description": "CREATE2 with three operands (no salt) halts with a stack underflow (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x61800060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json b/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json new file mode 100644 index 000000000..cce13f177 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json @@ -0,0 +1,23 @@ +{ + "name": "create2_nonempty_initcode_offset_max", + "description": "CREATE2 of one byte at offset 2^256 - 1: the offset does not fit and the frame halts (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json b/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json new file mode 100644 index 000000000..e41a24b40 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json @@ -0,0 +1,23 @@ +{ + "name": "create2_oversized_initcode_unrepresentable_offset", + "description": "CREATE2 of 49,153 bytes at an offset of 2^128 - 1 (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x0000000000000000000000000000000000000c2e": { + "code": "0x600061c0017f00000000000000000000000000000000ffffffffffffffffffffffffffffffff6000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000c2e", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json new file mode 100644 index 000000000..726af8673 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json @@ -0,0 +1,29 @@ +{ + "name": "create2_static_empty_initcode", + "description": "CREATE2 with empty initcode inside a STATICCALL (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0x6000600060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json new file mode 100644 index 000000000..1bab6597f --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json @@ -0,0 +1,29 @@ +{ + "name": "create2_static_empty_initcode_low_gas", + "description": "CREATE2 with empty initcode inside a STATICCALL that forwards 10,000 gas (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce612710fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0x6000600060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json b/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json new file mode 100644 index 000000000..6951c7797 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json @@ -0,0 +1,29 @@ +{ + "name": "create2_static_initcode_10mib", + "description": "CREATE2 of 10 MiB inside a STATICCALL (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0x600062a0000060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json b/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json new file mode 100644 index 000000000..d416c1c42 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json @@ -0,0 +1,29 @@ +{ + "name": "create2_static_initcode_600k", + "description": "CREATE2 of 600,000 bytes inside a STATICCALL; the caller records the failed call (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0x6000620927c060006000f500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json b/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json new file mode 100644 index 000000000..de7830a73 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json @@ -0,0 +1,29 @@ +{ + "name": "create2_static_missing_operands", + "description": "A bare CREATE2 on an empty stack inside a STATICCALL (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0xf500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/create_static_low_gas.json b/crates/mega-differential/scenarios/harness/create_static_low_gas.json new file mode 100644 index 000000000..365bb5d81 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/create_static_low_gas.json @@ -0,0 +1,29 @@ +{ + "name": "create_static_low_gas", + "description": "CREATE with empty initcode inside a STATICCALL that forwards 10,000 gas (ported from the legacy suite).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0x8ac7230489e80000" + }, + "0x00000000000000000000000000000000000005c2": { + "code": "0x60006000600060007300000000000000000000000000000000000005ce612710fa60005500", + "storage": { + "0x0": "0x7" + } + }, + "0x00000000000000000000000000000000000005ce": { + "code": "0x600060006000f000" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x00000000000000000000000000000000000005c2", + "data": "0x", + "value": "0x0", + "gas_limit": 100000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 763f8a517..5a9790117 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -26,7 +26,6 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| -| the test gates | 21 | 21 | 0 | 21 | 0 | 0 | | the common execution layer | 41 | 19 | 22 | 22 | 19 | 0 | | the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | @@ -44,7 +43,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **792** | **647** | **145** | **452** | **312** | **28** | +| **Total** | **771** | **626** | **145** | **431** | **312** | **28** | ## Tests ported in place @@ -64,6 +63,35 @@ These rows came back with the code they test and run in `crates/mega-evm/src`, s | `src/test_utils/opcode_gen.rs` | the Satin skeleton (2) | 2 | `src/test_utils/opcode_gen.rs` | | **Total** | | **36** | | +## Tests ported into the differential harness + +These 21 rows, owned by the test gates, pinned canonical CREATE and CREATE2 behavior; they are scenarios of `crates/mega-differential/scenarios/harness/` now, compared field by field against revm 43, so the counts above are lower than the inventory's by exactly these rows. +A scenario keeps the transaction of its test; the assertions on compute gas (not a Satin mechanism yet) and on the halt reason of a static callee (which the outer transaction does not expose) are not carried over. + +| Legacy file | Test | Scenarios | +|---|---|---| +| `rex4/create_safety.rs` | `test_create2_with_oversize_initcode_len_does_not_panic` | `create2_initcode_memory_oog` | +| `rex5/create2_empty_initcode.rs` | `test_create2_len_zero_offset_zero_succeeds_on_both_specs` | `create2_empty_initcode_offset_zero` | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_nonzero_offset_max_still_halts` | `create2_nonempty_initcode_offset_max` | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_large_offset_skips_memory_expansion` | `create2_empty_initcode_large_offset` | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_max_succeeds` | `create2_empty_initcode_offset_max` | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_zero_succeeds` | `create2_empty_initcode_offset_zero` | +| `rex5/create2_resize_gas_metering.rs` | `test_create2_missing_salt_halts_consistently_across_specs` | `create2_missing_salt` | +| `rex5/create2_resize_gas_metering.rs` | `test_rex5_create2_with_non_trivial_resize_succeeds` | `create2_initcode_32k` | +| `rex6/create2_metering_order.rs` | `test_create2_exact_boundary_initcode_length` | `create2_initcode_at_limit`, `create2_initcode_over_limit` | +| `rex6/create2_metering_order.rs` | `test_create2_missing_salt_consistent_rex5_rex6` | `create2_missing_salt` | +| `rex6/create2_metering_order.rs` | `test_create2_moderately_oversized_initcode_same_reason_both_specs` | `create2_initcode_600k` | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_initcode_halts_before_prework_rex6` | `create2_initcode_10mib` | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6` | `create2_oversized_initcode_unrepresentable_offset` | +| `rex6/create2_metering_order.rs` | `test_create2_static_hugely_oversized_initcode_halt_reason` | `create2_static_initcode_10mib` | +| `rex6/create2_metering_order.rs` | `test_create2_static_missing_operands_halt_reason` | `create2_static_missing_operands` | +| `rex6/create2_metering_order.rs` | `test_create2_static_oversized_initcode_reports_static_rejection` | `create2_static_initcode_600k` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_initcode_reports_static_rejection` | `create2_static_empty_initcode` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_low_gas_halt_reason` | `create2_static_empty_initcode_low_gas` | +| `rex6/create2_metering_order.rs` | `test_create_static_low_gas_halt_reason` | `create_static_low_gas` | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | `create2_missing_length` | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | `create2_missing_offset` | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | @@ -109,7 +137,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | | `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | | `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | -| `rex4/create_safety.rs` | 1 | keep 1 (the test gates · canonical revm behaviour (differential harness)) | | `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | | `rex4/eip7702_delegation_cycle.rs` | 9 | keep 8 (SALT pricing · account inspection on the pricing path); keep 1 (the common execution layer) | | `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | @@ -121,8 +148,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | | `rex5/call_too_deep_guard.rs` | 4 | keep 4 (the system contract interceptors · the synthetic-result contract of the common execution layer) | | `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | -| `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the test gates · canonical revm behaviour (differential harness)) | -| `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the test gates · canonical behaviour) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | | `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | @@ -145,10 +170,9 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | | `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | | `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | -| `rex6/create2_metering_order.rs` | 11 | keep 11 (the test gates · canonical halt reasons; D04 512 KiB boundary) | | `rex6/create_frame_accounting.rs` | 3 | rewrite 2 (the common execution layer · D50/D56 write-record layer); keep 1 (SALT pricing) | | `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | -| `rex6/error_paths.rs` | 4 | keep 2 (SALT pricing); keep 2 (the test gates · canonical) | +| `rex6/error_paths.rs` | 2 | keep 2 (SALT pricing) | | `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | | `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | | `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | diff --git a/crates/mega-evm/tests/_pending/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs deleted file mode 100644 index 363729117..000000000 --- a/crates/mega-evm/tests/_pending/rex4/create_safety.rs +++ /dev/null @@ -1,150 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! Regression tests for CREATE2 wrapper safety and compute-gas accounting. -//! -//! 1. CREATE2 with an out-of-bounds initcode slice must never trigger an interpreter panic. The -//! wrapper expands memory before reading the initcode slice; if memory expansion OOGs, the -//! canonical reject path runs without ever calling `slice_len` on unallocated memory. -//! 2. The expansion gas consumed by the wrapper's `resize_memory!` must be recorded into the -//! compute gas tracker. Otherwise the per-tx compute gas limit is undercounted by the initcode -//! memory-expansion cost, since the canonical CREATE2 path's own `resize_memory!` becomes a -//! no-op once memory is already sized. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ExecutionResult, TxEnv}, - handler::EvmTr, - state::{AccountInfo, Bytecode}, -}; - -const CALLER: Address = address!("1111111111111111111111111111111111111111"); -const CONTRACT_WITH_BAD_CREATE2: Address = address!("2222222222222222222222222222222222222222"); - -/// Runtime that performs CREATE2 with a length large enough to OOG the -/// canonical `resize_memory!` under a tight per-call gas budget, but -/// still under `MAX_INITCODE_SIZE` so the size check passes first. -/// -/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. -fn memory_oog_create2_runtime() -> Bytes { - BytecodeBuilder::default() - .push_number(0u8) // salt - .push_number(500_000u32) // length — large enough to OOG memory expansion - .push_number(0u8) // offset - .push_number(0u8) // value - .append(CREATE2) - .append(STOP) - .build() -} - -#[test] -fn test_create2_with_oversize_initcode_len_does_not_panic() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - let runtime = memory_oog_create2_runtime(); - let bytecode = Bytecode::new_raw(runtime); - db.insert_account_info( - CONTRACT_WITH_BAD_CREATE2, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - - let envs = TestExternalEnvs::::new(); - let limits = EvmTxRuntimeLimits::no_limits(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT_WITH_BAD_CREATE2), - gas_limit: 200_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - let res = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError"); - - assert!( - matches!( - res.result, - ExecutionResult::Success { .. } | - ExecutionResult::Halt { .. } | - ExecutionResult::Revert { .. } - ), - "got: {:?}", - res.result - ); -} - -const COMPUTE_GAS_TEST_CONTRACT: Address = address!("3333333333333333333333333333333333333333"); - -/// Build runtime bytecode that issues a single CREATE2 over a memory window of -/// `initcode_len` bytes starting at offset 0, then STOPs. The initcode memory is left -/// zero-initialized; CREATE2 will deploy an empty contract, which is fine for measuring -/// gas accounting (we only care that the wrapper ran and metered the memory expansion). -/// -/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. -fn create2_bytecode(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(initcode_len) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// EVM memory expansion gas: `3*words + words*words/512`. -fn memory_expansion_gas(len: u64) -> u64 { - let words = len.div_ceil(32); - 3 * words + words * words / 512 -} - -/// Run a single CREATE2 transaction at the REX4 spec and return the recorded compute gas. -fn run_create2_and_get_compute_gas( - initcode_len: u64, - gas_limit: u64, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - let bytecode = Bytecode::new_raw(create2_bytecode(initcode_len)); - db.insert_account_info( - COMPUTE_GAS_TEST_CONTRACT, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - - let envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Call(COMPUTE_GAS_TEST_CONTRACT), - gas_limit, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not fail"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (res.result, compute_gas) -} diff --git a/crates/mega-evm/tests/_pending/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index b75668583..5263b6fe0 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -2,7 +2,6 @@ mod access_control; mod beneficiary_detention; -mod create_safety; mod deployment; mod eip7702_delegation_cycle; mod frame_limits; diff --git a/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs deleted file mode 100644 index 01457e980..000000000 --- a/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! Regression suite for the REX5+ CREATE2 wrapper `len == 0` short-circuit. -//! -//! Canonical revm CREATE2 ignores the `offset` operand when `initcode_len == 0`: -//! no offset conversion, no memory expansion, no slice, no keccak. The initcode -//! hash is `KECCAK_EMPTY` and the deploy address is derived from -//! `creator.create2(salt, KECCAK_EMPTY)`. -//! -//! The Mega CREATE2 wrapper used to observe `offset` unconditionally, which -//! diverged from canonical revm in two ways: -//! -//! - A valid `CREATE2(value=0, offset=U256::MAX, len=0, salt=0)` halted inside -//! `as_usize_or_fail!(offset)` instead of succeeding with empty initcode. -//! - A `CREATE2(_, offset=large_finite, len=0, _)` over-charged memory-expansion EVM gas and (under -//! REX5+) recorded `resize_gas` into the `compute_gas` tracker even though canonical revm did -//! neither. -//! -//! REX5+ short-circuits `len == 0` before offset conversion / `resize_memory!` -//! / slice / `keccak256`, using the pre-computed `KECCAK_EMPTY`. Pre-REX5 keeps -//! the "observe offset, resize, slice, hash" sequence verbatim for replay -//! parity. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{CREATE2, STOP}, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); - -/// Runs a tx that invokes a CREATE2 contract built from raw bytecode and returns -/// the execution result plus the post-tx `compute_gas` tracker reading. -fn transact_create2_with_code( - spec: MegaSpecId, - code: Bytes, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// Builds bytecode that runs `CREATE2(value=0, offset, size=0, salt=0)`. -/// `offset` is pushed as a full 32-byte value so callers can exercise non-canonical -/// values such as `U256::MAX` or `1 << 30` that the short-circuit must tolerate. -fn build_create2_empty_initcode_at_offset(offset: U256) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // salt (depth 3) - .push_number(0_u64) // size = 0 (depth 2) - .push_u256(offset) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build() -} - -/// REX5: `CREATE2(len=0, offset=U256::MAX)` MUST succeed. -/// -/// Pins that the wrapper short-circuits before offset conversion when -/// `len == 0` — without the short-circuit, `as_usize_or_fail!(U256::MAX)` -/// would halt with `InvalidOperandOOG`. Post-short-circuit the initcode hash -/// is `KECCAK_EMPTY` and the inner CREATE2 deploys empty code at the -/// deterministic address `creator.create2(0, KECCAK_EMPTY)`. -#[test] -fn test_rex5_create2_len_zero_offset_max_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::MAX); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - result.is_success(), - "REX5 CREATE2(len=0, offset=U256::MAX) must succeed; got {result:?}", - ); -} - -/// REX5: the `len == 0` short-circuit MUST NOT engage when `len > 0`. -/// `CREATE2(len=1, offset=U256::MAX, ...)` must halt inside -/// `as_usize_or_fail!(offset)`, not silently succeed with `KECCAK_EMPTY` as -/// the initcode hash. Pins the `initcode_len.is_zero()` guard against a -/// regression that broadens it (e.g. an accidental `<=` comparison). -#[test] -fn test_rex5_create2_len_nonzero_offset_max_still_halts() { - let code = BytecodeBuilder::default() - .push_number(0_u64) // salt (depth 3) - .push_number(1_u64) // size = 1 (NON-zero) - .push_u256(U256::MAX) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "REX5 CREATE2(len=1, offset=U256::MAX) must halt — the len==0 short-circuit \ - must not engage for nonzero len; got {result:?}", - ); -} - -/// REX5: `CREATE2(len=0, offset=large_finite)` MUST succeed without paying for -/// memory expansion. Without the short-circuit, `resize_memory!(1<<30, 0)` -/// quadratically prices the implied range — pricing canonical revm explicitly -/// skips when `len == 0`. With the short-circuit the `compute_gas` reading -/// sits near the TX intrinsic baseline rather than balloon to MB-scale. -#[test] -fn test_rex5_create2_len_zero_large_offset_skips_memory_expansion() { - let offset = U256::from(1u64 << 30); - let code = build_create2_empty_initcode_at_offset(offset); - let (result, compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - result.is_success(), - "REX5 CREATE2(len=0, offset={offset}) must succeed; got {result:?}", - ); - // The wrapper short-circuit means no `resize_gas` is recorded under REX5, - // so the compute_gas tracker only holds the TX intrinsic (~21k base + a - // handful of bytes of calldata) plus the CREATE2 frame setup (~32k storage - // gas drained from stipend on REX5 — does NOT count against compute_gas). - // A regression that observes the offset would push compute_gas into the - // millions on a `1 << 30` byte range. - assert!( - compute < 100_000, - "REX5 CREATE2(len=0) should not record memory-expansion compute_gas; got {compute}", - ); -} - -/// REX5: `CREATE2(len=0, offset=0)` happy path — the short-circuit must not -/// break the canonical "small offset, empty initcode" success case. -#[test] -fn test_rex5_create2_len_zero_offset_zero_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!(result.is_success(), "REX5 CREATE2(len=0, offset=0) must succeed; got {result:?}",); -} - -/// REX5 vs REX4 deployed-address parity for `len=0, offset=0`. Both must derive -/// the same address `creator.create2(0, KECCAK_EMPTY)` — REX5 via the -/// short-circuit, REX4 via `keccak256(slice_len(0, 0))` which equals -/// `KECCAK_EMPTY`. Equality of `is_success` is a weaker form of address parity; -/// pinning the spec on it would require reading the deployed address out of the -/// execution result, which requires more plumbing. The success-only check is -/// sufficient for the wrapper-level invariant — if the REX5 short-circuit -/// produced a wrong hash, the inner CREATE2 would deploy to a different -/// address but `STOP` would still succeed at that other address. Direct -/// address-equality assertion is left as a follow-up. -#[test] -fn test_create2_len_zero_offset_zero_succeeds_on_both_specs() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result_rex5, _) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); - let (result_rex4, _) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!(result_rex5.is_success(), "REX5 must succeed; got {result_rex5:?}"); - assert!(result_rex4.is_success(), "REX4 must succeed; got {result_rex4:?}"); -} diff --git a/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs deleted file mode 100644 index ed1c754ee..000000000 --- a/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Regression suite for the REX5+ CREATE2 wrapper `resize_gas` recording rule. -//! -//! REX5+ validates the salt operand before `resize_memory!` / copy / keccak, -//! and records the memory-expansion gas (`resize_gas`) into the `compute_gas` -//! tracker immediately after `resize_memory!`. Pre-REX5 keeps the original -//! "resize first, salt last, record after inner CREATE2 returns" order -//! verbatim for replay parity. -//! -//! Coverage: -//! - Happy-path CREATE2 with measurable memory expansion succeeds under both specs. -//! - Cross-spec parity: the post-tx `compute_gas` tracker agrees within a small tolerance, pinning -//! that REX5 records `resize_gas` exactly once (no double-count from the trailing late-record -//! block, no miss-count from the early-record path being skipped). -//! - Stack-underflow consistency: a CREATE2 dispatched with only three operands halts with -//! `StackUnderflow` under both specs and leaks no `resize_gas` into the tracker. -//! -//! Failure-path verification (storage-gas OOG / inner CREATE2 halt under REX5 -//! retaining `resize_gas`, pre-REX5 skipping via the trailing block) is -//! delicate to engineer with stable gas tuning and is left to a follow-up. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{CREATE2, STOP}, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); - -/// Builds bytecode that runs `CREATE2(value=0, offset=0, size=initcode_len, salt=0)`. -/// The initcode region is zero-initialized; the canonical CREATE2 keccak256-hashes -/// the bytes and runs the resulting `STOP`-only constructor, deploying empty code. -/// Memory expansion gas inside the wrapper is a function of `initcode_len`. -fn build_create2_contract(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // salt - .push_number(initcode_len) // size - .push_number(0_u64) // offset - .push_number(0_u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// Runs a tx that invokes the CREATE2 contract and returns the execution result and -/// the post-tx `compute_gas` tracker reading. -fn transact_create2(spec: MegaSpecId, initcode_len: u64) -> (ExecutionResult, u64) { - let code = build_create2_contract(initcode_len); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// 32 KiB initcode: memory expansion gas inside the wrapper is in the ~5 K range, -/// large enough that a double-count or miss-count of `resize_gas` would be -/// visible against the cross-spec parity tolerance. -const INITCODE_LEN: u64 = 32 * 1024; - -/// REX5 happy path: CREATE2 with non-trivial memory expansion succeeds. The -/// `compute_gas` tracker registers usage that includes the `resize_gas` recorded -/// in the early-record path. -#[test] -fn test_rex5_create2_with_non_trivial_resize_succeeds() { - let (result, compute) = transact_create2(MegaSpecId::REX5, INITCODE_LEN); - assert!(result.is_success(), "REX5 CREATE2 happy path must succeed; got {result:?}"); - assert!( - compute > 0, - "REX5 compute_gas tracker must register usage including resize_gas; got {compute}", - ); -} - -/// Runs a CREATE2 contract built from raw bytecode (used to construct stack-underflow -/// scenarios that `build_create2_contract` cannot express). Mirrors `transact_create2`. -fn transact_create2_with_code( - spec: MegaSpecId, - code: Bytes, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// CREATE2 dispatched with only three stack operands (value, offset, length; salt -/// absent) must halt with `StackUnderflow` under both specs, and neither spec may -/// leak `resize_gas` into the `compute_gas` tracker on the halt path: -/// -/// - REX5: the wrapper inspects salt at position 3 BEFORE `resize_memory!`, so the early-record -/// block is unreachable when salt is missing. -/// - REX4: the wrapper inspects salt AFTER `resize_memory!`, but the trailing `if resize_gas > 0 { -/// ... }` block is skipped on the `StackUnderflow` halt. -/// -/// Equality of the post-tx `compute_gas` reading across REX4 and REX5 pins this -/// invariant — a regression that records `resize_gas` on either halt path would -/// produce a spec-asymmetric reading. -#[test] -fn test_create2_missing_salt_halts_consistently_across_specs() { - // Three CREATE2 args, salt OMITTED. Stack order from top (depth 0) at the - // CREATE2 instruction: - // depth 0: value - // depth 1: offset - // depth 2: length - // depth 3: → wrapper's `stack.inspect::<3>()` fails → StackUnderflow. - let code = BytecodeBuilder::default() - .push_number(INITCODE_LEN) // length (depth 2) - .push_number(0_u64) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - - let (result_rex5, compute_rex5) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); - let (result_rex4, compute_rex4) = transact_create2_with_code(MegaSpecId::REX4, code); - - // Both specs must halt with StackUnderflow. (Compare via Debug to avoid pinning the - // exact OpHaltReason → EthHaltReason wrapper path.) - let is_stack_underflow = |r: &ExecutionResult| -> bool { - matches!(r, ExecutionResult::Halt { reason, .. } if format!("{reason:?}").contains("StackUnderflow")) - }; - assert!( - is_stack_underflow(&result_rex5), - "REX5 must halt with StackUnderflow; got {result_rex5:?}", - ); - assert!( - is_stack_underflow(&result_rex4), - "REX4 must halt with StackUnderflow; got {result_rex4:?}", - ); - - // Neither spec leaks `resize_gas` into the compute_gas tracker on the - // stack-underflow path. The expected baseline for both specs is the TX - // intrinsic recorded by `validate()` (`record_compute_gas(initial_gas)`) and - // nothing more: - // - // - REX5: salt inspect at position 3 halts BEFORE `resize_memory!`, so the early-record block - // (`if is_rex5_enabled && resize_gas > 0 { ... }`) is never reached. - // - REX4: `resize_memory!` runs and burns EVM gas, but the late-record block at the wrapper's - // tail is skipped when the frame halts on the position-3 salt inspect. - // - // Equality between the two specs pins this consistency: any regression that - // records `resize_gas` on a halted CREATE2 (whether by moving the REX5 early - // record ahead of the salt check, or by running the REX4 late-record despite - // the halt) would produce a spec-asymmetric compute_gas reading exceeding the - // shared intrinsic baseline. - assert_eq!( - compute_rex5, compute_rex4, - "compute_gas must be identical across REX4 ({compute_rex4}) and REX5 ({compute_rex5}) \ - when CREATE2 halts on salt underflow — any divergence indicates resize_gas leaked into \ - the tracker on the halt path", - ); - // Sanity check that what's recorded is just the TX intrinsic (≈21k base + ~9 calldata - // bytes for the CREATE2 contract code). A multi-KiB reading would indicate that the - // wrapper recorded `resize_gas` despite the halt. - assert!( - compute_rex5 < 25_000, - "compute_gas reading should be near the TX intrinsic (~21k) on the halt path, \ - not include the {INITCODE_LEN}-byte resize_gas; got {compute_rex5}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 1282dc08f..8d06f7f51 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -3,8 +3,6 @@ mod apply_pending_changes_gas_budget; mod call_too_deep_guard; mod callcode_storage_gas; -mod create2_empty_initcode; -mod create2_resize_gas_metering; mod db_error; mod deposit_caller_accounting; mod deposit_create_storage_gas; diff --git a/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs deleted file mode 100644 index f411f4d41..000000000 --- a/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs +++ /dev/null @@ -1,568 +0,0 @@ -//! REX6 CREATE2 gas-metering order. -//! -//! REX6 folds the CREATE2 memory-expansion (`resize_memory!`) gas into the single compute-gas -//! recording taken after the inner opcode completes, instead of the pre-REX6 split recording (REX5 -//! recorded it eagerly before the storage charge; pre-REX5 recorded it after the inner op). -//! -//! Coverage: -//! - **Happy path**: REX6 records the same total compute gas as REX5 (and identical `gas_used`), -//! proving the single recording equals the REX5 eager-resize + inner sum with no double/miss -//! count. -//! - **Missing salt**: a CREATE2 with the salt operand absent halts with `StackUnderflow` under -//! both specs without leaking any `resize_gas` into the compute tracker. -//! - **Failure-path divergence**: under a compute-gas limit tight enough that the memory-expansion -//! gas crosses it, REX5 halts at the eager resize record (before the inner opcode runs) while -//! REX6 defers recording until after the inner opcode has executed — so REX6 records strictly -//! more compute gas. This is the intended, spec-defined behavior change of the canonical order. - -use std::{cell::RefCell, convert::Infallible, rc::Rc}; - -use crate::common::{transact, transact_default, CALLER, CONTRACT, EMPTY_TARGET}; -use alloy_primitives::{Bytes, U256}; -use mega_evm::{ - constants::mini_rex::MAX_INITCODE_SIZE, - test_utils::{BytecodeBuilder, MemoryDatabase}, - BucketHasher, BucketId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{CREATE, CREATE2, STATICCALL, STOP}, - context::{tx::TxEnvBuilder, ContextTr}, - inspector::Inspector, - interpreter::{ - interpreter_types::InterpreterTypes, CallInputs, CallOutcome, InstructionResult, - }, -}; - -/// Records the `InstructionResult` an inner call to [`EMPTY_TARGET`] halted with. Used to observe -/// the halt reason of a `CREATE2` executed inside a `STATICCALL` frame, which is otherwise not -/// visible in the outer transaction result. -#[derive(Clone, Default)] -struct InnerHaltCapture(Rc>>); - -impl Inspector for InnerHaltCapture { - fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { - if inputs.target_address == EMPTY_TARGET { - *self.0.borrow_mut() = Some(outcome.result.result); - } - } -} - -/// Routes every SALT lookup to [`STATIC_TEST_BUCKET_ID`] so a raised capacity scales the -/// contract-creation storage charge inside the static callee. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - STATIC_TEST_BUCKET_ID - } -} - -/// Bucket every SALT lookup is routed to under [`SingleBucketHasher`]. -const STATIC_TEST_BUCKET_ID: BucketId = 7; - -/// 2 × `MIN_BUCKET_SIZE` (256) → a 2× multiplier, so the REX-family contract-creation charge -/// `CONTRACT_CREATION_STORAGE_GAS_BASE × (multiplier − 1)` is 32,000 gas instead of the 0 a -/// minimum-capacity bucket yields. -const DOUBLED_BUCKET_CAPACITY: u64 = 512; - -/// Runs a tx to a contract that `STATICCALL`s [`EMPTY_TARGET`] (whose code is `inner_bytecode`) -/// with `forward_gas`, and returns the halt reason the static callee produced. A -/// `bucket_capacity` of `Some(DOUBLED_BUCKET_CAPACITY)` makes the contract-creation storage -/// charge nonzero (32,000 gas); `None` leaves every bucket at minimum capacity (charge = 0). -fn static_halt_reason_for_bytecode( - spec: MegaSpecId, - inner_bytecode: Bytes, - forward_gas: u64, - bucket_capacity: Option, -) -> Option { - let outer_staticcall = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(forward_gas) // gas - .append(STATICCALL) - .append(STOP) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, outer_staticcall) - .account_code(EMPTY_TARGET, inner_bytecode); - - let mut external_envs = TestExternalEnvs::::new(); - if let Some(capacity) = bucket_capacity { - external_envs = external_envs.with_bucket_capacity(STATIC_TEST_BUCKET_ID, capacity); - } - - let capture = InnerHaltCapture::default(); - let mut context = MegaContext::new(&mut db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context).with_inspector(capture.clone()); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let reason = *capture.0.borrow(); - reason -} - -/// `CREATE2(value=0, offset=0, size=initcode_len, salt=0)` then `STOP`, as the static callee. -fn static_create2_bytecode(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(initcode_len) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// Runs a static `CREATE2` with the given initcode length, ample forwarded gas, and -/// minimum-capacity buckets, returning its halt reason. -fn static_create2_halt_reason(spec: MegaSpecId, initcode_len: u64) -> Option { - static_halt_reason_for_bytecode(spec, static_create2_bytecode(initcode_len), 50_000_000, None) -} - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// 32 KiB initcode: the wrapper-side memory expansion gas is in the multi-KiB range, large enough -/// that a double-count or miss-count of the resize gas is visible, yet under the configured -/// initcode size limit (548,864 bytes — see `constants::mini_rex::MAX_INITCODE_SIZE`, well above -/// the vanilla EIP-3860 default) so the inner CREATE2 sets up a child frame rather than erroring. -const INITCODE_LEN: u64 = 32 * 1024; - -/// `CREATE2(value=0, offset=0, size=INITCODE_LEN, salt=0)` then `STOP`. The zero-initialized -/// initcode region keccak-hashes to a `STOP`-only constructor that deploys empty code. -fn build_create2_contract() -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(INITCODE_LEN) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// The same four operand pushes as [`build_create2_contract`] followed by `STOP` (no CREATE2). -/// Running this measures the compute-gas usage accumulated *before* the CREATE2 opcode, used to -/// place a compute-gas limit precisely inside the CREATE2 memory-expansion window. -fn build_pushes_only_contract() -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) - .push_number(INITCODE_LEN) - .push_number(0u64) - .push_number(0u64) - .stop() - .build() -} - -fn db_with(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) -} - -#[test] -fn test_create2_missing_salt_consistent_rex5_rex6() { - // Three CREATE2 operands, salt OMITTED: the wrapper's `stack.inspect::<3>()` fails, halting - // with `StackUnderflow` before any memory expansion under both specs. - let code = BytecodeBuilder::default() - .push_number(INITCODE_LEN) // length (depth 2) - .push_number(0u64) // offset (depth 1) - .push_number(0u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - let is_stack_underflow = |o: &crate::common::Outcome| { - matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")) - }; - assert!(is_stack_underflow(&r5), "REX5 must halt with StackUnderflow; got {:?}", r5.result); - assert!(is_stack_underflow(&r6), "REX6 must halt with StackUnderflow; got {:?}", r6.result); - - // Neither spec records any resize gas on the salt-underflow halt path: both readings equal the - // shared TX intrinsic baseline. - assert_eq!( - r5.compute_gas, r6.compute_gas, - "compute_gas must be identical on the salt-underflow halt path; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); -} - -/// An oversized CREATE2 initcode must halt with `CreateInitCodeSizeLimit` under REX6 -/// BEFORE any memory-expansion/copy/keccak256 prework runs, not after. -/// -/// A 10 MiB initcode is chosen so the memory-expansion gas would be enormous (quadratic word -/// cost, ~210M gas — far past the 100M tx gas limit) if `resize_memory!` ran. Without the fix, -/// `resize_memory!` itself would exhaust the gas limit first and halt with `MemoryOOG` — the -/// canonical EIP-3860 check inside the inner opcode is never reached. With the fix, the halt -/// fires immediately with `CreateInitCodeSizeLimit`, before `resize_memory!` is ever called. -/// `gas_used` is NOT a useful signal here: any non-revert exceptional halt (both `MemoryOOG` and -/// `CreateInitCodeSizeLimit`) consumes the full remaining gas regardless of when it fires — this -/// matches the finding's own claim that committed gas/state is identical under REX6 either way; -/// only the halt-reason label (and the avoided node CPU work) differ. -#[test] -fn test_create2_oversized_initcode_halts_before_prework_rex6() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, far past the 548,864-byte cap - - let code = BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(HUGE_INITCODE_LEN) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - assert!( - matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "REX6 must halt with CreateInitCodeSizeLimit (not MemoryOOG) for a 10 MiB initcode — \ - the halt must fire before resize_memory! ever runs, got {:?}", - r6.result, - ); -} - -/// Halt-reason parity for a "moderately" oversized initcode (bigger than the 548,864-byte cap, -/// but small enough that `resize_memory!`'s own gas cost stays well within the 100M tx gas -/// limit). Both specs reach `CreateInitCodeSizeLimit` — REX5 via the slower prework-then-inner- -/// check path (frozen, unpatched), REX6 via the immediate early check. -/// -/// `gas_used` is deliberately NOT compared here: both specs consume the tx's full gas limit -/// regardless (any non-revert exceptional halt does), so equality there is a trivial artifact of -/// halt semantics, not a meaningful check. What genuinely differs — and is asserted below — is -/// the internal `compute_gas` tracker: REX5 still eagerly records the ~742,895-gas memory -/// expansion for this length before it ever reaches the inner opcode's check, while REX6's early -/// halt never reaches that recording at all. This divergence is pre-existing REX6 metering-order -/// behavior (`create_rex6`'s single post-body recording), not something this fix changes — it is -/// asserted here only to document that "same halt reason" does not imply "identical internal -/// accounting," and so a future change collapsing this gap doesn't silently look like a -/// regression. -#[test] -fn test_create2_moderately_oversized_initcode_same_reason_both_specs() { - const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost is negligible - - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MODERATELY_OVERSIZED_LEN) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - let is_create_initcode_size_limit = |o: &crate::common::Outcome| { - matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")) - }; - assert!( - is_create_initcode_size_limit(&r5), - "REX5 must reach CreateInitCodeSizeLimit via the slower prework-then-inner-check path: {:?}", - r5.result, - ); - assert!( - is_create_initcode_size_limit(&r6), - "REX6 must reach CreateInitCodeSizeLimit via the immediate early check: {:?}", - r6.result, - ); - assert!( - r5.compute_gas > r6.compute_gas + 500_000, - "REX5 must still eagerly record the memory-expansion compute gas that REX6's early halt \ - skips; REX5={} REX6={}", - r5.compute_gas, - r6.compute_gas, - ); -} - -/// Exact-boundary test: `initcode_len == max_initcode_size()` must NOT halt (the -/// comparator is strict `>`, matching revm's own canonical check), and -/// `max_initcode_size() + 1` MUST halt with `CreateInitCodeSizeLimit`. Pins the comparator -/// itself — a future `>` → `>=` regression would make the boundary length halt on REX6 while -/// still succeeding pre-REX6, a real spec divergence that the "moderately oversized" test above -/// (600,000 bytes, well clear of the boundary) cannot catch. -#[test] -fn test_create2_exact_boundary_initcode_length() { - let at_limit = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MAX_INITCODE_SIZE as u64) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - let r6_at_limit = transact_default(MegaSpecId::REX6, db_with(at_limit)); - assert!( - r6_at_limit.is_success(), - "an initcode exactly at max_initcode_size must succeed (strict `>`, not `>=`): {:?}", - r6_at_limit.result, - ); - - let over_limit = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MAX_INITCODE_SIZE as u64 + 1) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - let r6_over_limit = transact_default(MegaSpecId::REX6, db_with(over_limit)); - assert!( - matches!(&r6_over_limit.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "one byte over max_initcode_size must halt with CreateInitCodeSizeLimit: {:?}", - r6_over_limit.result, - ); -} - -/// Operand-order test: an oversized `initcode_len` combined with an `initcode_offset` -/// that does not fit in a `usize` must still halt with `CreateInitCodeSizeLimit` on REX6 — the -/// size check runs before the offset is ever converted. -/// -/// The wrapper converts `initcode_len` first, then runs the REX6 size check, then converts -/// `initcode_offset`. If the conversion order were the reverse (offset first, as it was before -/// this fix), the unrepresentable offset would halt with `InvalidOperandOOG` -/// (`OutOfGas(InvalidOperand)`) and mask the intended EIP-3860 halt. Pre-REX6 has no early size -/// check, so it correctly halts on the offset overflow — the same `InvalidOperandOOG` reason both -/// operands share, which is why reordering their conversion is inert on sealed specs. -#[test] -fn test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6() { - // `len` is oversized but representable as `usize`; `offset` is > `usize::MAX`. - let code = BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(MAX_INITCODE_SIZE as u64 + 1) // size: oversized, but fits usize - .push_u256(U256::from(u128::MAX)) // offset: > usize::MAX (unrepresentable) - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let r6 = transact_default(MegaSpecId::REX6, db_with(code.clone())); - assert!( - matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "REX6 must halt with CreateInitCodeSizeLimit even when the offset is unrepresentable — \ - the size check must run before the offset is converted; got {:?}", - r6.result, - ); - - // Pre-REX6 (sealed) has no early size check, so the unrepresentable offset is what halts, with - // OutOfGas(InvalidOperand). It must NOT surface CreateInitCodeSizeLimit — this pins that the - // reorder did not change sealed-spec behavior. - let r5 = transact_default(MegaSpecId::REX5, db_with(code)); - assert!( - matches!(&r5.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("InvalidOperand")), - "REX5 (sealed) must halt on the offset overflow (OutOfGas(InvalidOperand)), not the REX6 \ - size check; got {:?}", - r5.result, - ); -} - -/// Static-call precedence: a `CREATE2` inside a `STATICCALL` with oversized initcode must report -/// the static-context rejection (`StateChangeDuringStaticCall`), NOT `CreateInitCodeSizeLimit`. -/// REX6 halts with `StateChangeDuringStaticCall` at the top of the REX6 create handler, before -/// any operand read, the size check, or any resize/copy/keccak256 prework runs. REX5 (sealed) has -/// no such hoist, so it reaches the same halt reason only after running that prework and falling -/// through to the inner opcode's own static guard. A "moderately" oversized length (over the cap, -/// but cheap to resize) is used so REX5's prework-then-inner-guard path stays affordable rather -/// than running out of gas on the resize. -#[test] -fn test_create2_static_oversized_initcode_reports_static_rejection() { - const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost negligible vs. gas - - let is_static_reject = |r: Option| { - matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) - }; - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, MODERATELY_OVERSIZED_LEN); - let r5 = static_create2_halt_reason(MegaSpecId::REX5, MODERATELY_OVERSIZED_LEN); - - assert!( - is_static_reject(r6), - "REX6 static oversized CREATE2 must halt with StateChangeDuringStaticCall, not \ - CreateInitCodeSizeLimit; got {r6:?}", - ); - assert!( - is_static_reject(r5), - "REX5 (sealed) static oversized CREATE2 halts with StateChangeDuringStaticCall; got {r5:?}", - ); - assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static-CREATE2 halt reason"); -} - -/// Static-call precedence at an unaffordable initcode length: a static `CREATE2` whose initcode -/// length would make `resize_memory!` prohibitively expensive must still halt with -/// `StateChangeDuringStaticCall` on REX6 — the hoisted guard fires before any operand conversion -/// or memory work is attempted, so the halt reason does not depend on whether the resize could -/// have been afforded. REX5 (sealed) has no such hoist: it attempts the resize, cannot afford it -/// out of the gas forwarded to the inner frame, and halts with a memory out-of-gas reason instead -/// — mirroring the non-static divergence pinned above, now shown to hold inside a static frame. -#[test] -fn test_create2_static_hugely_oversized_initcode_halt_reason() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, resize cost far exceeds forwarded gas - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, HUGE_INITCODE_LEN); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE2 with a hugely oversized initcode must halt with \ - StateChangeDuringStaticCall before resize_memory! is ever attempted; got {r6:?}", - ); - - let r5 = static_create2_halt_reason(MegaSpecId::REX5, HUGE_INITCODE_LEN); - assert_eq!( - r5, - Some(InstructionResult::MemoryOOG), - "REX5 (sealed) static CREATE2 must still attempt resize_memory! for a hugely oversized \ - initcode and halt with a memory out-of-gas reason, never reaching the static-call \ - rejection; got {r5:?}", - ); -} - -/// Zero-length boundary: a static `CREATE2` with `initcode_len == 0` reports the static rejection -/// on both specs. REX6 halts at the top of the create handler, before the zero-length shortcut -/// runs; REX5 (sealed) takes the shortcut, derives the address, attempts the contract-creation -/// storage charge, and only then reaches the inner opcode's static guard — same reason, different -/// path. The low-gas variant below distinguishes the two paths observably. -#[test] -fn test_create2_static_zero_length_initcode_reports_static_rejection() { - let is_static_reject = |r: Option| { - matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) - }; - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, 0); - let r5 = static_create2_halt_reason(MegaSpecId::REX5, 0); - - assert!( - is_static_reject(r6), - "REX6 static zero-length CREATE2 must halt with StateChangeDuringStaticCall via the \ - inner opcode's static guard; got {r6:?}", - ); - assert!( - is_static_reject(r5), - "REX5 (sealed) static zero-length CREATE2 halts with StateChangeDuringStaticCall; \ - got {r5:?}", - ); - assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static zero-length CREATE2 halt reason"); -} - -/// Observable split on the zero-length path: with the contract-creation storage charge made -/// nonzero (2× bucket capacity → 32,000 gas) and forwarded gas below it, REX5 (sealed) attempts -/// the charge on its way to the inner opcode and halts out-of-gas — while REX6 halts -/// `StateChangeDuringStaticCall` at the top of the create handler, before the address is derived -/// or the charge is attempted. Pins that the static rejection covers the zero-length shortcut -/// path. -#[test] -fn test_create2_static_zero_length_low_gas_halt_reason() { - let r6 = static_halt_reason_for_bytecode( - MegaSpecId::REX6, - static_create2_bytecode(0), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static zero-length CREATE2 must halt before the contract-creation storage charge; \ - got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode( - MegaSpecId::REX5, - static_create2_bytecode(0), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r5, - Some(InstructionResult::OutOfGas), - "REX5 (sealed) static zero-length CREATE2 must still attempt the contract-creation \ - storage charge first and halt out-of-gas when it cannot afford it; got {r5:?}", - ); -} - -/// The static rejection covers plain `CREATE`, not just `CREATE2`: same low-gas setup as the -/// zero-length test but with a `CREATE(value=0, offset=0, size=0)` callee. REX6 halts -/// `StateChangeDuringStaticCall` before the contract-creation storage charge; REX5 (sealed) -/// derives the address from the creator nonce, attempts the charge, and halts out-of-gas. -#[test] -fn test_create_static_low_gas_halt_reason() { - let create_bytecode = BytecodeBuilder::default() - .push_number(0u64) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .append(STOP) - .build(); - - let r6 = static_halt_reason_for_bytecode( - MegaSpecId::REX6, - create_bytecode.clone(), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE must halt before the contract-creation storage charge; got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode( - MegaSpecId::REX5, - create_bytecode, - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r5, - Some(InstructionResult::OutOfGas), - "REX5 (sealed) static CREATE must still attempt the contract-creation storage charge \ - first and halt out-of-gas when it cannot afford it; got {r5:?}", - ); -} - -/// The static rejection precedes operand inspection: a bare `CREATE2` on an empty stack halts -/// `StackUnderflow` on REX5 (sealed — operand inspection runs first) but -/// `StateChangeDuringStaticCall` on REX6, matching canonical revm, whose -/// `require_non_staticcall!` runs before the operand pops. -#[test] -fn test_create2_static_missing_operands_halt_reason() { - let bare_create2 = BytecodeBuilder::default().append(CREATE2).append(STOP).build(); - - let r6 = - static_halt_reason_for_bytecode(MegaSpecId::REX6, bare_create2.clone(), 50_000_000, None); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE2 with missing operands must halt with the static rejection, not \ - StackUnderflow; got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode(MegaSpecId::REX5, bare_create2, 50_000_000, None); - assert_eq!( - r5, - Some(InstructionResult::StackUnderflow), - "REX5 (sealed) static CREATE2 with missing operands halts with StackUnderflow; got {r5:?}", - ); -} - -// Not covered: static + `initcode_len` unrepresentable in `usize`. `static_create2_halt_reason` -// takes a `u64` length, which always fits in `usize` on the 64-bit targets the tests run on, so -// the case cannot be expressed without a raw-`U256` variant of the shared helper. diff --git a/crates/mega-evm/tests/_pending/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs index 50ba6d9c9..1dd596205 100644 --- a/crates/mega-evm/tests/_pending/rex6/error_paths.rs +++ b/crates/mega-evm/tests/_pending/rex6/error_paths.rs @@ -1,4 +1,4 @@ -//! REX6 CREATE/CREATE2/SSTORE error-path coverage for the unified-metering refactor. +//! REX6 CREATE/SSTORE error-path coverage for the unified-metering refactor. //! //! The REX6 canonical-metering rewrite of `storage_gas_ext` moved the storage-gas charge of //! CREATE (`create_rex6`) and SSTORE behind fresh early-return guards, and split CREATE2 operand @@ -10,9 +10,6 @@ //! `EVMError::Custom`, not silently charge zero storage gas. //! - **SSTORE storage-gas DB error** (`sstore`): the zero→non-zero `sstore_set_storage_gas` failure //! must do the same. -//! - **CREATE2 operand underflow** (`compute_created_address`): a CREATE2 missing its `offset` or -//! `length` operand must halt with `StackUnderflow` from the wrapper's own `stack.inspect::<1>()` -//! / `inspect::<2>()`, before any memory expansion. use std::convert::Infallible; @@ -24,11 +21,11 @@ use mega_evm::{ MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, SaltEnv, }; use revm::{ - bytecode::opcode::{CREATE, CREATE2, SSTORE, STOP}, + bytecode::opcode::{CREATE, SSTORE, STOP}, context::TxEnv, }; -use crate::common::{transact_default, CALLER, CONTRACT}; +use crate::common::{CALLER, CONTRACT}; const ONE_ETH: u128 = 1_000_000_000_000_000_000; @@ -137,44 +134,3 @@ fn test_rex6_sstore_salt_error_on_sstore_set_storage_gas() { assert_injected_salt_custom_error(transact_with_failing_salt(MegaSpecId::REX6, code)); } - -fn is_stack_underflow(result: &crate::common::Outcome) -> bool { - matches!(&result.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")) -} - -/// CREATE2 with only the `value` operand on the stack must halt with `StackUnderflow` from the -/// wrapper's `stack.inspect::<1>()` (the `offset` operand) inside `compute_created_address`, -/// before any memory expansion. -#[test] -fn test_rex6_create2_missing_offset_stack_underflow() { - // One operand on the stack (value); `offset` is absent. - let code = BytecodeBuilder::default().push_number(0u64).append(CREATE2).append(STOP).build(); - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code); - let outcome = transact_default(MegaSpecId::REX6, db); - - assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); -} - -/// CREATE2 with only `value` and `offset` on the stack must halt with `StackUnderflow` from the -/// wrapper's `stack.inspect::<2>()` (the `length` operand) inside `compute_created_address`. -#[test] -fn test_rex6_create2_missing_length_stack_underflow() { - // Two operands on the stack (offset, value); `length` is absent. - let code = BytecodeBuilder::default() - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code); - let outcome = transact_default(MegaSpecId::REX6, db); - - assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); -} diff --git a/crates/mega-evm/tests/_pending/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs index a6e652c07..a9c03a86b 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -6,7 +6,6 @@ mod beneficiary_detention; mod common; -mod create2_metering_order; mod create_frame_accounting; mod eip7702_authority_accounting; mod error_paths; From 3f2fae99d3e00d56a0b6879be25df81df7dee8c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:43:08 +0800 Subject: [PATCH 041/201] ci: let the mutation driver run one shard of a large mutant set --- scripts/mutation_test.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 90fddfe30..0ffaad6bf 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -8,6 +8,10 @@ # # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # Run scripts/mutation_gate.py afterwards to score + gate the run. +# +# MUTANTS_SHARD=k/n runs only shard k (0-based) of n of whichever mutant set the +# subcommand selects (cargo-mutants' own --shard), for a diff too large for one +# job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -35,6 +39,9 @@ fi EXCLUDE_ARGS=() [[ -n "$exclude_re_output" ]] && mapfile -t EXCLUDE_ARGS <<< "$exclude_re_output" +SHARD_ARGS=() +[[ -n "${MUTANTS_SHARD:-}" ]] && SHARD_ARGS=(--shard "$MUTANTS_SHARD") + run_mutants() { rm -rf "$OUT_DIR" mkdir -p "$(dirname "$OUT_DIR")" # cargo-mutants creates OUT_DIR itself but not its parents @@ -49,6 +56,7 @@ run_mutants() { --no-shuffle \ -vV \ "${EXCLUDE_ARGS[@]}" \ + "${SHARD_ARGS[@]}" \ "$@" || rc=$? # cargo-mutants exit codes (https://mutants.rs/exit-codes.html): 0 = all caught, From 824b62fe630fc9e96f7ef9abe3aef757c12cc9f2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:51:04 +0800 Subject: [PATCH 042/201] docs: write the test-gate policy into REVIEW.md and AGENTS.md --- AGENTS.md | 27 +++++++++++++++---------- REVIEW.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++ mutants/README.md | 8 +++++++- 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a30c38ecd..eb0aaae65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,15 +51,17 @@ Git submodules are required — clone with `--recursive` or run `git submodule u ## Workspace Structure -| Crate | Path | Member | Purpose | -| ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | -| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | -| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | -| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | -| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | -| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | - +| Crate | Path | Member | Purpose | +| ----------------------- | -------------------------- | ---------------- | ------------------------------------------------------------ | +| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | +| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | +| `mega-differential` | `crates/mega-differential` | yes, not default | Differential harness: `MegaEvm` against stock revm 43 | +| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | +| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | +| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | +| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | + +`mega-differential` builds stock revm 43 from crates.io next to the fork, as its oracle; it is not a default member, so the commands run at the root without `-p` or `--workspace` stay on the engine's graph. The four tool crates still target the legacy engine. They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until they are ported to Satin. @@ -69,7 +71,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates (`alloy-op-evm`, `op-alloy-*`) come from the same monorepo revision. - Patch the twelve revm crates together, or the build resolves a second copy of revm. -- `cargo tree -i revm` must show exactly one revm, from the fork. +- `cargo tree -i revm -p mega-evm` must show exactly one revm, from the fork; only `mega-differential`'s graph adds stock revm 43, as its oracle. - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. ## Architecture @@ -118,6 +120,8 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. The change that ports a pending test deletes it from `_pending/` in the same commit. - Unit tests live next to the code in `#[cfg(test)] mod tests`. +- `crates/mega-differential/scenarios/` — the differential corpus: JSON scenarios (`test_utils::Scenario`) that run through `MegaEvm` and through stock revm 43 and are compared field by field. + A behavior that should equal Ethereum's is pinned best as a scenario there. ## Version Control @@ -180,6 +184,9 @@ When the agent is requested to implement a new feature or bug fix, it should con The agent should always consider accompanying tests or suggest to add additional tests. - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. +- **Keep the differential harness clean.** + `cargo test -p mega-differential --locked` must pass: every difference between `MegaEvm` and stock revm 43 is explained by an effect of `crates/mega-differential/deviations.json`, and every effect there explains one. + A change that makes `MegaEvm` differ on purpose registers each effect with its mechanism and reason, as narrow as the mechanism allows (or teaches the oracle to model it); a change that removes a difference removes its effect. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. This includes new or modified opcode behavior, gas mechanics, system contract interception, resource limit tracking, and block executor pipeline changes. diff --git a/REVIEW.md b/REVIEW.md index eaef3f746..3de90e38e 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -75,6 +75,57 @@ This is the single most important correctness concern in mega-evm. The fixture runners have failed this repeatedly: an exception assertion accepting any `Err`, a setup failure skipping execution, a `zip` letting missing output pass, a duplicate test name silently overwriting, an `unwrap_or(default)` rewriting a contradictory fixture into a valid one, a filename-based skip, an unconditional prune before state-root validation. Benchmarks fail it the same way — an unfunded inner call, zero-byte initcode, a discarded inner-call result or an undeployed address means the measured path never runs, and a mock database that cannot fail a lookup cannot test its error path. +## Test gates + +These checks guard every change to the Satin engine. +`lint`, `test`, `no-std` and `require-label` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. + +### Differential harness + +- `crates/mega-differential` runs every scenario of its corpus (343 today: 23 hand-written, 263 derived from the execution-spec tests of EIP-8037, 57 written for the harness) through `MegaEvm` and through stock revm 43, and compares every gas figure, the outcome, the output, the logs and every touched account. +- The `differential` check (`.github/workflows/differential.yml`) runs it on every pull request and every push to `satin`; it must pass with no unexplained difference and no stale registry effect. +- A change that makes `MegaEvm` differ from revm 43 on purpose adds the effects to `crates/mega-differential/deviations.json` (mechanism, reason, exact values), or configures the oracle to model the mechanism. + Review a registry change like a spec change: an effect wider than its mechanism (a `*` where an exact value fits, a scenario pattern of `*` for a mechanism a few scenarios reach) hides the next regression. +- A change that removes a difference removes its effect; the harness fails on an effect that explains nothing. + +### Execution-spec tests + +- Engine-level execution-spec coverage on `MegaEvm` is the 263 execution-spec-derived scenarios of the differential harness, until the state-test tool is ported to Satin. +- `.github/workflows/exec-spec.yml` runs the fork's own runner on the execution-spec-test fixtures, at the fork tag `Cargo.lock` pins, and checks the Osaka and Amsterdam executed and skipped counts pinned in the workflow. + It checks the fork `MegaEvm` runs on, not `MegaEvm`, and it is not a required check. +- It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. + +### Instruction counts (CodSpeed) + +- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`), `corpus` (a slice of the differential corpus through `MegaEvm`) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. +- `codspeed.yml` runs them under instrumentation on every pull request that touches code and on every push to `satin`; the baseline a pull request is compared with is the latest `satin` push. +- Read regressions from the CodSpeed report on the pull request (the CodSpeed comment and the `CodSpeed Performance Analysis` check). + The regression threshold that fails that check is a setting of the repository's CodSpeed project; it is not recorded in this repository or in the reports CodSpeed posts, so this file does not state a number. + The check is not required: a flagged regression is fixed, or acknowledged in CodSpeed with the reason stated on the pull request. +- `corpus` moves when the semantics or the pricing of its scenarios move; a pricing change that moves it says so on the pull request. +- Locally, `cargo bench -p mega-evm --bench ` proves a bench runs to completion; its wall-clock numbers are not evidence. + +### Mutation testing + +- The `cargo-mutants gate` job mutates the lines a pull request changes and fails on a surviving mutant that no reviewed suppression covers. + Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. +- The job is bounded to 330 minutes. + Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. + Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. +- The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. + It starts to bite with the first `is_enabled` gate of the spec after Satin. +- The legacy mutant killers were retired with the legacy sources; a survivor in Satin code gets a new killer, next to the code or under `crates/mega-evm/tests/mutation/`. + +### Scheduled workflows + +- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, weekly benchmark, replay-bench, doc-audit, the weekly execution-spec run) stay inert until `satin` is the default branch. +- Run them on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. + - `mutation.yml`: the whole-crate cargo-mutants run, the spec-gate sweep and suppression hygiene. + - `benchmark.yml`: the Satin bench set on `satin`'s head, without a baseline (`-f aa_check=true` measures the noise floor). + - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. + - `doc-audit.yml`: the documentation audit of `satin`'s docs. + - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the state-test tool is ported. + ## Dev tools and test infrastructure Applies to `bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, `crates/state-test`, test utilities and benches — not consensus code, but `mega-state-test` is a published library and tool output feeds fixtures and indexers. Default severity cap `[Minor]`; raise only when the defect reaches that published API or corrupts a downstream fixture. diff --git a/mutants/README.md b/mutants/README.md index 83bdd5c0e..a62642fbf 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -12,7 +12,7 @@ Target: **`crates/mega-evm`**. |------|---------| | `.cargo/mutants.toml` | Canonical `cargo-mutants` config (scope, nextest, excludes, timeouts). | | `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating. | -| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `. | +| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `; `MUTANTS_SHARD=k/n` runs one shard. | | `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR. | | `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment. | @@ -26,8 +26,14 @@ python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' + +# Shard k of n of a large run (cargo-mutants' --shard), each into its own directory: +MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main ``` +The driver needs bash 4 or later and Python 3.11 or later on `PATH`; with the macOS defaults (bash 3.2, Python 3.9) it fails before mutating anything. +When to shard is in `REVIEW.md` (Test gates, Mutation testing). + ## The gate PR CI runs **diff-scoped** (`cargo mutants --in-diff`), so every mutant lives on a line the PR touched. From 451f7216524aa5d356c628fa65f8ad419edf4208 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 15:59:11 +0800 Subject: [PATCH 043/201] ci: run the execution-spec fixtures through the fork's runner at the pinned tag --- .github/workflows/exec-spec.yml | 147 ++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 .github/workflows/exec-spec.yml diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml new file mode 100644 index 000000000..db7306dfa --- /dev/null +++ b/.github/workflows/exec-spec.yml @@ -0,0 +1,147 @@ +name: Execution-spec tests + +# Runs the execution-spec-test fixtures with the revm fork's own runner (`scripts/run-tests.sh`, +# release mode) at the fork tag Cargo.lock pins, then counts the state tests the runner executes +# and skips for Osaka (the main fixtures) and Amsterdam (the glamsterdam devnet fixtures) and +# checks them against the numbers pinned below. +# +# An interim gate until the state-test tool is ported to Satin. It checks the fork MegaEvm runs +# on, not MegaEvm; MegaEvm meets execution-spec scenarios in the differential harness +# (crates/mega-differential/scenarios/eest). Not a required check. + +on: + workflow_dispatch: + # GitHub fires a schedule only from the default branch's copy of a workflow: this one runs + # weekly once `satin` is the default branch. Until then, dispatch it by hand on `satin`. + schedule: + - cron: "0 4 * * 1" # Weekly, Monday 4:00 UTC + pull_request: + paths: + - Cargo.lock + - Cargo.toml + - .github/workflows/exec-spec.yml + push: + branches: [satin] + paths: + - Cargo.lock + - Cargo.toml + - .github/workflows/exec-spec.yml + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + exec-spec: + name: execution-spec tests + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + # State tests the runner executes and skips, per fork, on the fixture releases + # `scripts/run-tests.sh` downloads at the pinned tag (main v5.4.0 develop fixtures, + # glamsterdam devnet v8.1.0). The skipped ones are the create-collision fixtures with + # storage the runner skips by name, and expected-exception transactions it cannot build + # (bad signatures, blob-hash creates). A change that moves the fork pin, and with it the + # runner or the fixtures, updates them. + OSAKA_EXECUTED: "19465" + OSAKA_SKIPPED: "52" + AMSTERDAM_EXECUTED: "15754" + AMSTERDAM_SKIPPED: "72" + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Read the fork pin from Cargo.lock + id: pin + run: | + sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) + if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then + printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2 + exit 1 + fi + tag=${sources#*tag=} + tag=${tag%%#*} + commit=${sources##*#} + echo "fork tag $tag at $commit" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "commit=$commit" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v4 + with: + repository: megaeth-labs/revm + ref: ${{ steps.pin.outputs.tag }} + path: revm-fork + persist-credentials: false + + - name: Check the tag names the locked revision + working-directory: revm-fork + env: + COMMIT: ${{ steps.pin.outputs.commit }} + run: test "$(git rev-parse HEAD)" = "$COMMIT" + + - name: Read the fork's toolchain + id: rust + working-directory: revm-fork + run: echo "channel=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)" >> "$GITHUB_OUTPUT" + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.rust.outputs.channel }} + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: revm-fork + cache-on-failure: true + + - name: Run the fork's execution-spec suites + working-directory: revm-fork + run: ./scripts/run-tests.sh clean cargo release + + - name: Count the Osaka and Amsterdam state tests + working-directory: revm-fork + run: | + set -euo pipefail + # State tests a fixture tree defines for a fork: one per post-state entry, keyed by the + # fixtures' fork name (`Osaka`). `$fork` in the jq program is a jq variable. + # shellcheck disable=SC2016 + defined() { + find "$1" -name '*.json' -print0 \ + | xargs -0 jq -r --arg fork "$2" '[.[] | .post[$fork] // [] | length] | add // 0' \ + | awk '{ n += $1 } END { print n + 0 }' + } + # State tests the runner executes for a fork, from its per-test JSON outcome on stderr, + # keyed by revm's spec id (`OSAKA`). Other stderr lines are not JSON and are dropped. + # shellcheck disable=SC2016 + executed() { + cargo run --release -p revme -- statetest --json-outcome --omit-progress "$1" \ + 2> outcomes.jsonl > /dev/null + jq -Rr --arg spec "$2" 'fromjson? | select(type == "object" and .fork == $spec) | .test' \ + outcomes.jsonl | wc -l | tr -d ' ' + } + check() { + local label=$1 dir=$2 fork=$3 spec=$4 want_executed=$5 want_skipped=$6 + local total ran skipped + total=$(defined "$dir" "$fork") + ran=$(executed "$dir" "$spec") + skipped=$((total - ran)) + echo "$label: $ran executed, $skipped skipped of $total defined ($dir)" + echo "| $label | $ran | $skipped | $total |" >> "$GITHUB_STEP_SUMMARY" + if [ "$ran" != "$want_executed" ] || [ "$skipped" != "$want_skipped" ]; then + echo "::error::$label: expected $want_executed executed and $want_skipped skipped, got $ran and $skipped" + return 1 + fi + } + { + echo "| Fixtures | Executed | Skipped | Defined |" + echo "|---|---:|---:|---:|" + } >> "$GITHUB_STEP_SUMMARY" + status=0 + check Osaka test-fixtures/main/develop/state_tests Osaka OSAKA \ + "$OSAKA_EXECUTED" "$OSAKA_SKIPPED" || status=1 + check Amsterdam test-fixtures/devnet/state_tests Amsterdam AMSTERDAM \ + "$AMSTERDAM_EXECUTED" "$AMSTERDAM_SKIPPED" || status=1 + exit "$status" From e214f4fe8f043228da89ad90f2c302687f2b613b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 16:07:35 +0800 Subject: [PATCH 044/201] docs: keep what the retired mutant killers cited in the pending ledger --- crates/mega-evm/tests/_pending/README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5a9790117..84fe008f7 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -17,7 +17,7 @@ Do not add a `_pending/main.rs`. - `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. - Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. - The 44 legacy mutant killers the inventory kept (`tests/mutation/`) are not here: each was keyed to a surviving mutant of the legacy sources, and the test gates found no survivor in the Satin sources to regenerate one for. - A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`. + A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`; what the retired rows cited is kept in "Retired mutant killers" below. - Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. - Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. @@ -63,6 +63,23 @@ These rows came back with the code they test and run in `crates/mega-evm/src`, s | `src/test_utils/opcode_gen.rs` | the Satin skeleton (2) | 2 | `src/test_utils/opcode_gen.rs` | | **Total** | | **36** | | +## Retired mutant killers + +What the retired `tests/mutation/` rows cited, for the mechanisms that own them. + +| Owning mechanism | Tests | Disposition | Decision | +|---|---:|---|---| +| the Satin gas table | 2 | rewrite | D04 | +| the Satin gas table | 1 | rewrite | D11 | +| SALT pricing | 8 | keep | the test gates regenerate | +| compute gas | 1 | rewrite | D53 | +| the data-size limit | 2 | keep | 13,107,200 unchanged | +| detention | 6 | keep | the test gates regenerate | +| the state-growth and KV limits | 1 | undecided | D46 | +| the state-growth and KV limits | 1 | rewrite | D45 | +| the block executor | 17 | keep | the test gates regenerate | +| the block executor | 5 | rewrite | single spec / Satin schedule | + ## Tests ported into the differential harness These 21 rows, owned by the test gates, pinned canonical CREATE and CREATE2 behavior; they are scenarios of `crates/mega-differential/scenarios/harness/` now, compared field by field against revm 43, so the counts above are lower than the inventory's by exactly these rows. From 075538a937e09a03ade00aa02791fe667ad79fde Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 16:10:17 +0800 Subject: [PATCH 045/201] test: share the arms' record code and tighten the scenario format --- crates/mega-differential/README.md | 5 +- crates/mega-differential/src/diff.rs | 52 +++++-------- crates/mega-differential/src/lib.rs | 4 +- crates/mega-differential/src/mega.rs | 73 ++---------------- crates/mega-differential/src/oracle.rs | 89 ++++++---------------- crates/mega-differential/src/record.rs | 64 ++++++++++++++++ crates/mega-differential/tests/claims.rs | 7 +- crates/mega-evm/src/test_utils/scenario.rs | 86 +++++++++++++-------- 8 files changed, 178 insertions(+), 202 deletions(-) diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 935a1d7a0..ba836b093 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -21,11 +21,12 @@ CI runs the same command as the `differential` job (`.github/workflows/different **Left arm: `MegaEvm`.** Each transaction runs on a fresh `MegaEvm` over a `MegaContext` for `MegaSpecId::SATIN`, through alloy-evm's `Evm::transact_raw` (system calls through `Evm::transact_system_call`). The configuration is the one the spec fixes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 and EIP-2780 on, the 200,000,000 execution cap, EIP-7708 and the system-call reservoir margin off. -The L1 fees are zero (`test_utils::zero_fee_l1_block_info`), every transaction is a non-deposit one with an empty envelope, and the gas price is zero. +The L1 fees are zero (`test_utils::zero_fee_l1_block_info`), every transaction is a non-deposit one with an empty envelope, and the gas price is the transaction's own (zero unless the scenario sets one). `mega-evm` is built with its default features, so the precompiles run on the same backends as in a node. **Right arm: the oracle.** Stock `revm = "=43.0.0"` from crates.io, on its mainnet handler. +The requirement pins the `revm` crate itself; its sub-crates resolve to the 43.0.x patch releases the lockfile holds (`revm-context`, `revm-handler`, `revm-inspector` and `revm-precompile` 43.0.2, `revm-context-interface` and `revm-interpreter` 43.0.1, the others 43.0.0). Its configuration is copied from the left arm's (`oracle::cfg`): the Ethereum spec the Satin spec runs on (Osaka), the gas table entry by entry, and every switch. The fork numbers its gas ids as upstream does and adds its own at the top of the table (`tests/claims.rs` checks both, and that the fork-only prices are zero). If `MegaEvm` switches on a mechanism revm 43 cannot run (EIP-7708 before Amsterdam, the system-call state-gas margin), `oracle::cfg` panics: the mechanism that switches it on has to model it or register the difference. @@ -56,7 +57,7 @@ Cargo writes the version requirements of revm 43's optional dependencies into it `scenarios/` holds one JSON file per scenario; the file stem is the scenario name. The format is `mega_evm::test_utils::Scenario`: an optional description, a coinbase, the pre-state accounts (nonce, balance, code, storage; code is legacy bytecode or an EIP-7702 delegation designator) and the transactions, run in order. -A transaction is a `call`, a `create` or a `system_call`; it may carry an EIP-2930 access list and an EIP-7702 authorization list with the signer already recovered (`authority`, absent for a signature that does not recover). +A transaction is a `call`, a `create` or a `system_call`; it may carry a `gas_price`, an EIP-2930 access list and an EIP-7702 authorization list with the signer already recovered (`authority`, absent for a signature that does not recover). The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | Directory | Scenarios | Origin | diff --git a/crates/mega-differential/src/diff.rs b/crates/mega-differential/src/diff.rs index 1104345a0..f1e9524fb 100644 --- a/crates/mega-differential/src/diff.rs +++ b/crates/mega-differential/src/diff.rs @@ -20,6 +20,8 @@ pub struct Difference { /// The differences between two records of one scenario, and how many fields were compared. #[derive(Debug, Default)] pub struct Comparison { + /// Scenario name. + pub scenario: String, /// Fields on which the arms disagree. pub differences: Vec, /// Number of fields compared. @@ -27,11 +29,11 @@ pub struct Comparison { } impl Comparison { - fn field(&mut self, scenario: &str, field: String, left: T, right: T) { + fn field(&mut self, field: String, left: T, right: T) { self.compared += 1; if left != right { self.differences.push(Difference { - scenario: scenario.to_string(), + scenario: self.scenario.clone(), field, left: left.to_string(), right: right.to_string(), @@ -42,41 +44,34 @@ impl Comparison { /// Compares the record `MegaEvm` produced (`left`) with the oracle's (`right`). pub fn compare(scenario: &str, left: &ScenarioRecord, right: &ScenarioRecord) -> Comparison { - let mut cmp = Comparison::default(); - cmp.field(scenario, "tx_count".into(), left.len(), right.len()); + let mut cmp = Comparison { scenario: scenario.to_string(), ..Default::default() }; + cmp.field("tx_count".into(), left.len(), right.len()); for (i, (l, r)) in left.iter().zip(right).enumerate() { - compare_tx(&mut cmp, scenario, &format!("tx[{i}]"), l, r); + compare_tx(&mut cmp, &format!("tx[{i}]"), l, r); } cmp } -fn compare_tx(cmp: &mut Comparison, scenario: &str, at: &str, l: &TxRecord, r: &TxRecord) { - cmp.field(scenario, format!("{at}.outcome"), &l.outcome, &r.outcome); +fn compare_tx(cmp: &mut Comparison, at: &str, l: &TxRecord, r: &TxRecord) { + cmp.field(format!("{at}.outcome"), &l.outcome, &r.outcome); for name in l.gas.keys().chain(r.gas.keys()).collect::>() { - cmp.field( - scenario, - format!("{at}.gas.{name}"), - render(l.gas.get(name)), - render(r.gas.get(name)), - ); + cmp.field(format!("{at}.gas.{name}"), render(l.gas.get(name)), render(r.gas.get(name))); } - cmp.field(scenario, format!("{at}.output"), &l.output, &r.output); + cmp.field(format!("{at}.output"), &l.output, &r.output); cmp.field( - scenario, format!("{at}.created"), render(l.created.map(|address| format!("{address:#x}"))), render(r.created.map(|address| format!("{address:#x}"))), ); - cmp.field(scenario, format!("{at}.logs.len"), l.logs.len(), r.logs.len()); + cmp.field(format!("{at}.logs.len"), l.logs.len(), r.logs.len()); for (j, (ll, rl)) in l.logs.iter().zip(&r.logs).enumerate() { - cmp.field(scenario, format!("{at}.logs[{j}]"), ll.render(), rl.render()); + cmp.field(format!("{at}.logs[{j}]"), ll.render(), rl.render()); } for address in l.state.keys().chain(r.state.keys()).collect::>() { let path = format!("{at}.state[{address:#x}]"); match (l.state.get(address), r.state.get(address)) { - (Some(la), Some(ra)) => compare_account(cmp, scenario, &path, la, ra), + (Some(la), Some(ra)) => compare_account(cmp, &path, la, ra), (la, ra) => cmp.field( - scenario, path, la.map_or_else(|| ABSENT.to_string(), AccountRecord::render), ra.map_or_else(|| ABSENT.to_string(), AccountRecord::render), @@ -85,21 +80,14 @@ fn compare_tx(cmp: &mut Comparison, scenario: &str, at: &str, l: &TxRecord, r: & } } -fn compare_account( - cmp: &mut Comparison, - scenario: &str, - at: &str, - l: &AccountRecord, - r: &AccountRecord, -) { - cmp.field(scenario, format!("{at}.created"), l.created, r.created); - cmp.field(scenario, format!("{at}.selfdestructed"), l.selfdestructed, r.selfdestructed); - cmp.field(scenario, format!("{at}.balance"), l.balance, r.balance); - cmp.field(scenario, format!("{at}.nonce"), l.nonce, r.nonce); - cmp.field(scenario, format!("{at}.code_hash"), l.code_hash, r.code_hash); +fn compare_account(cmp: &mut Comparison, at: &str, l: &AccountRecord, r: &AccountRecord) { + cmp.field(format!("{at}.created"), l.created, r.created); + cmp.field(format!("{at}.selfdestructed"), l.selfdestructed, r.selfdestructed); + cmp.field(format!("{at}.balance"), l.balance, r.balance); + cmp.field(format!("{at}.nonce"), l.nonce, r.nonce); + cmp.field(format!("{at}.code_hash"), l.code_hash, r.code_hash); for slot in l.storage.keys().chain(r.storage.keys()).collect::>() { cmp.field( - scenario, format!("{at}.storage[{slot:#x}]"), render(l.storage.get(slot).map(|value| format!("{value:#x}"))), render(r.storage.get(slot).map(|value| format!("{value:#x}"))), diff --git a/crates/mega-differential/src/lib.rs b/crates/mega-differential/src/lib.rs index 389e15ad7..b50b608e2 100644 --- a/crates/mega-differential/src/lib.rs +++ b/crates/mega-differential/src/lib.rs @@ -17,10 +17,11 @@ use std::{ use mega_evm::test_utils::Scenario; +#[macro_use] +pub mod record; pub mod diff; pub mod mega; pub mod oracle; -pub mod record; pub mod registry; use diff::Difference; @@ -222,6 +223,7 @@ mod tests { fn comparison(diffs: &[(&str, &str, &str)]) -> Comparison { Comparison { + scenario: "s".into(), differences: diffs .iter() .map(|(field, left, right)| Difference { diff --git a/crates/mega-differential/src/mega.rs b/crates/mega-differential/src/mega.rs index 7008a8962..1646fa834 100644 --- a/crates/mega-differential/src/mega.rs +++ b/crates/mega-differential/src/mega.rs @@ -1,18 +1,13 @@ //! The left arm: `MegaEvm`, configured as the Satin spec fixes it. -use std::collections::BTreeMap; - use mega_evm::{ alloy_op_evm::OpTxError, op_revm::{OpHaltReason, OpTransactionError}, - revm::{ - context::result::{EVMError, ExecutionResult, ResultGas}, - state::EvmState, - }, + revm::context::result::{EVMError, ExecutionResult}, test_utils::{Scenario, ScenarioTxOutcome}, }; -use crate::record::{AccountRecord, LogRecord, ScenarioRecord, TxRecord}; +use crate::record::{ScenarioRecord, TxRecord}; /// Runs `scenario` on `MegaEvm` and records every transaction. pub fn run(scenario: &Scenario) -> ScenarioRecord { @@ -21,46 +16,13 @@ pub fn run(scenario: &Scenario) -> ScenarioRecord { } fn record(outcome: &ScenarioTxOutcome) -> TxRecord { - let outcome = match outcome { - Ok(outcome) => outcome, - Err(err) => { - return TxRecord { outcome: format!("error:{}", error(err)), ..Default::default() } - } - }; - let result = &outcome.result; - TxRecord { - outcome: match result { - ExecutionResult::Success { .. } => "success".into(), - ExecutionResult::Revert { .. } => "revert".into(), - ExecutionResult::Halt { reason, .. } => format!("halt:{}", halt(reason)), - }, - gas: gas(result.gas()), - output: result.output().cloned().unwrap_or_default(), - created: result.created_address(), - logs: result - .logs() - .iter() - .map(|log| LogRecord { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data.clone(), - }) - .collect(), - state: state(&outcome.state), + match outcome { + // `ResultGas` serializes `reservoir_remaining` on the fork. + Ok(outcome) => tx_record!(ExecutionResult, &outcome.result, &outcome.state, halt, None), + Err(err) => TxRecord { outcome: format!("error:{}", error(err)), ..Default::default() }, } } -/// The gas figures of `gas`: its fields as it serializes them, which is every field it has, -/// and the derived values. -fn gas(gas: &ResultGas) -> BTreeMap { - let mut figures = crate::serialized_u64_fields(gas); - figures.insert("tx_gas_used".into(), gas.tx_gas_used()); - figures.insert("block_regular_gas_used".into(), gas.block_regular_gas_used()); - figures.insert("block_state_gas_used".into(), gas.block_state_gas_used()); - figures.insert("final_refunded".into(), gas.final_refunded()); - figures -} - /// The halt reason with the OP wrapper taken off: op-revm wraps every Ethereum halt reason in /// `OpHaltReason::Base`, which is naming, not behavior. A halt reason of op-revm's own keeps an /// `op:` prefix. @@ -82,26 +44,3 @@ fn error(err: &EVMError) -> String { other => format!("other:{other:?}"), } } - -fn state(state: &EvmState) -> BTreeMap { - state - .iter() - .filter(|(_, account)| account.is_touched()) - .map(|(address, account)| { - let record = AccountRecord { - created: account.is_created(), - selfdestructed: account.is_selfdestructed(), - balance: account.info.balance, - nonce: account.info.nonce, - code_hash: account.info.code_hash, - storage: account - .storage - .iter() - .filter(|(_, slot)| slot.is_changed()) - .map(|(key, slot)| (*key, slot.present_value)) - .collect(), - }; - (*address, record) - }) - .collect() -} diff --git a/crates/mega-differential/src/oracle.rs b/crates/mega-differential/src/oracle.rs index aff70b187..e3fca4c80 100644 --- a/crates/mega-differential/src/oracle.rs +++ b/crates/mega-differential/src/oracle.rs @@ -4,11 +4,11 @@ //! the same gas table (copied entry by entry), the same switches. It has no OP layer, so the //! differences an OP-specific mechanism makes are the registry's to explain. -use std::{cell::Cell, collections::BTreeMap, convert::Infallible, str::FromStr}; +use std::{cell::Cell, convert::Infallible, str::FromStr}; use mega_evm::{ - revm::context::CfgEnv as MegaCfgEnv, - test_utils::{Scenario, TxSpecKind}, + revm::context::{transaction::TransactionType as ScenarioTxType, CfgEnv as MegaCfgEnv}, + test_utils::{Scenario, ScenarioTxKind}, MegaContext, MegaSpecId, }; use revm_oracle::{ @@ -30,7 +30,7 @@ use revm_oracle::{ Context, Database, DatabaseCommit, MainBuilder, MainContext, MainnetEvm, }; -use crate::record::{AccountRecord, LogRecord, ScenarioRecord, TxRecord}; +use crate::record::{ScenarioRecord, TxRecord}; type OracleDb = CacheDB; type OracleEvm<'a> = MainnetEvm>; @@ -50,7 +50,7 @@ pub fn run(scenario: &Scenario) -> ScenarioRecord { .build_mainnet(); let mut probe = ReservoirProbe::default(); let result = match tx.kind { - TxSpecKind::SystemCall => { + ScenarioTxKind::SystemCall => { evm.ctx().set_tx(TxEnv::new_system_tx_with_caller( tx.caller, tx.to.expect("validated: a system call has a target"), @@ -58,7 +58,7 @@ pub fn run(scenario: &Scenario) -> ScenarioRecord { )); probe.run_system_call(&mut evm) } - TxSpecKind::Call | TxSpecKind::Create => { + ScenarioTxKind::Call | ScenarioTxKind::Create => { let nonce = evm.ctx().db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); evm.ctx().set_tx(tx_env(tx, nonce)); @@ -167,7 +167,7 @@ fn database(scenario: &Scenario) -> OracleDb { db } -fn tx_env(tx: &mega_evm::test_utils::TxSpec, nonce: u64) -> TxEnv { +fn tx_env(tx: &mega_evm::test_utils::ScenarioTx, nonce: u64) -> TxEnv { let access_list = AccessList( tx.access_list .iter() @@ -192,14 +192,14 @@ fn tx_env(tx: &mega_evm::test_utils::TxSpec, nonce: u64) -> TxEnv { }) .collect(); TxEnv::builder() - .tx_type(Some(tx.tx_type())) + .tx_type(Some(tx.tx_type() as u8)) .caller(tx.caller) .kind(tx.to.map_or(TxKind::Create, TxKind::Call)) .data(tx.data.clone()) .value(tx.value) - .gas_limit(tx.gas_limit.unwrap_or_default()) - .gas_price(0) - .gas_priority_fee((tx.tx_type() == 4).then_some(0)) + .gas_limit(tx.gas_limit.expect("a call or a create has a gas limit")) + .gas_price(tx.gas_price) + .gas_priority_fee((tx.tx_type() == ScenarioTxType::Eip7702).then_some(tx.gas_price)) .nonce(nonce) .access_list(access_list) .authorization_list_recovered(authorizations) @@ -247,59 +247,14 @@ impl<'a> Handler for ReservoirProbe<'a> { } fn record(result: &ExecutionResult, reservoir: Option, state: &EvmState) -> TxRecord { - TxRecord { - outcome: match result { - ExecutionResult::Success { .. } => "success".into(), - ExecutionResult::Revert { .. } => "revert".into(), - ExecutionResult::Halt { reason, .. } => format!("halt:{reason:?}"), - }, - gas: gas(result.gas(), reservoir), - output: result.output().cloned().unwrap_or_default(), - created: result.created_address(), - logs: result - .logs() - .iter() - .map(|log| LogRecord { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data.clone(), - }) - .collect(), - state: state - .iter() - .filter(|(_, account)| account.is_touched()) - .map(|(address, account)| { - let record = AccountRecord { - created: account.is_created(), - selfdestructed: account.is_selfdestructed(), - balance: account.info.balance, - nonce: account.info.nonce, - code_hash: account.info.code_hash, - storage: account - .storage - .iter() - .filter(|(_, slot)| slot.is_changed()) - .map(|(key, slot)| (*key, slot.present_value)) - .collect(), - }; - (*address, record) - }) - .collect(), - } -} - -/// The gas figures of `gas` as [`crate::mega`] names them, with the probed reservoir in place of -/// the field revm 43 lacks. -fn gas(gas: &ResultGas, reservoir: Option) -> BTreeMap { - let mut figures = crate::serialized_u64_fields(gas); - if let Some(reservoir) = reservoir { - figures.insert("reservoir_remaining".into(), reservoir); - } - figures.insert("tx_gas_used".into(), gas.tx_gas_used()); - figures.insert("block_regular_gas_used".into(), gas.block_regular_gas_used()); - figures.insert("block_state_gas_used".into(), gas.block_state_gas_used()); - figures.insert("final_refunded".into(), gas.final_refunded()); - figures + // revm 43's `ResultGas` has no `reservoir_remaining`; the probe supplies it. + tx_record!( + ExecutionResult, + result, + state, + |reason: &HaltReason| format!("{reason:?}"), + reservoir + ) } fn error(err: &OracleError) -> String { @@ -326,7 +281,7 @@ mod tests { .with_block(block(scenario)) .build_mainnet(); let outcome = match tx.kind { - TxSpecKind::SystemCall => { + ScenarioTxKind::SystemCall => { evm.system_call_with_caller(tx.caller, tx.to.unwrap(), tx.data.clone()) } _ => { @@ -347,7 +302,9 @@ mod tests { #[test] fn test_reservoir_probe_changes_nothing_else() { let scenarios = crate::load_corpus(&crate::corpus_dir()).unwrap(); - assert!(scenarios.iter().any(|s| s.txs.iter().any(|tx| tx.kind == TxSpecKind::SystemCall))); + assert!(scenarios + .iter() + .any(|s| s.txs.iter().any(|tx| tx.kind == ScenarioTxKind::SystemCall))); for scenario in &scenarios { let mut probed = run(scenario); for record in &mut probed { diff --git a/crates/mega-differential/src/record.rs b/crates/mega-differential/src/record.rs index 21cb4cb3c..a06c1def1 100644 --- a/crates/mega-differential/src/record.rs +++ b/crates/mega-differential/src/record.rs @@ -83,3 +83,67 @@ impl AccountRecord { ) } } + +/// Builds the [`TxRecord`] of an executed transaction, for either arm. +/// +/// Both revms expose the same accessors on their execution result, logs and state, but as +/// types of different crates, so one function cannot take both; this macro is that function, so +/// the two arms cannot drift apart in what they record. +/// +/// - `$exec`: the arm's `ExecutionResult` type, to match its variants; +/// - `$result`, `$state`: the result and the state the transaction produced; +/// - `$halt`: renders the arm's halt reason; +/// - `$reservoir`: the leftover reservoir when the arm's `ResultGas` does not serialize it. +macro_rules! tx_record { + ($exec:ident, $result:expr, $state:expr, $halt:expr, $reservoir:expr $(,)?) => {{ + let result = $result; + let gas = result.gas(); + let mut figures = $crate::serialized_u64_fields(gas); + if let Some(reservoir) = $reservoir { + figures.insert("reservoir_remaining".to_string(), reservoir); + } + figures.insert("tx_gas_used".to_string(), gas.tx_gas_used()); + figures.insert("block_regular_gas_used".to_string(), gas.block_regular_gas_used()); + figures.insert("block_state_gas_used".to_string(), gas.block_state_gas_used()); + figures.insert("final_refunded".to_string(), gas.final_refunded()); + $crate::record::TxRecord { + outcome: match result { + $exec::Success { .. } => "success".to_string(), + $exec::Revert { .. } => "revert".to_string(), + $exec::Halt { reason, .. } => format!("halt:{}", $halt(reason)), + }, + gas: figures, + output: result.output().cloned().unwrap_or_default(), + created: result.created_address(), + logs: result + .logs() + .iter() + .map(|log| $crate::record::LogRecord { + address: log.address, + topics: log.topics().to_vec(), + data: log.data.data.clone(), + }) + .collect(), + state: $state + .iter() + .filter(|(_, account)| account.is_touched()) + .map(|(address, account)| { + let record = $crate::record::AccountRecord { + created: account.is_created(), + selfdestructed: account.is_selfdestructed(), + balance: account.info.balance, + nonce: account.info.nonce, + code_hash: account.info.code_hash, + storage: account + .storage + .iter() + .filter(|(_, slot)| slot.is_changed()) + .map(|(key, slot)| (*key, slot.present_value)) + .collect(), + }; + (*address, record) + }) + .collect(), + } + }}; +} diff --git a/crates/mega-differential/tests/claims.rs b/crates/mega-differential/tests/claims.rs index 38227af98..b32768668 100644 --- a/crates/mega-differential/tests/claims.rs +++ b/crates/mega-differential/tests/claims.rs @@ -10,7 +10,7 @@ use mega_evm::{ database::{states::bundle_state::BundleRetention, State}, DatabaseCommit, }, - test_utils::{PreAccount, Scenario, TxSpec, TxSpecKind}, + test_utils::{PreAccount, Scenario, ScenarioTx, ScenarioTxKind}, MegaContext, MegaSpecId, }; use revm_oracle::{ @@ -79,13 +79,14 @@ fn test_zero_fee_vault_touch_leaves_no_committed_account() { CALLER, PreAccount { balance: U256::from(10), ..Default::default() }, )]), - txs: vec![TxSpec { + txs: vec![ScenarioTx { caller: CALLER, to: Some(CALLEE), data: Bytes::new(), value: U256::from(1), gas_limit: Some(100_000), - kind: TxSpecKind::Call, + gas_price: 0, + kind: ScenarioTxKind::Call, access_list: Vec::new(), authorization_list: Vec::new(), }], diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 9113d1e2d..6b2185c3a 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -11,8 +11,8 @@ //! - the block is [`Scenario::block`]: number 1, timestamp 1, the scenario's coinbase, zero base //! fee, unlimited gas; //! - the configuration is what [`MegaContext`] fixes for the spec; -//! - the L1 fees are zero ([`zero_fee_l1_block_info`], [`op_transaction`]), and so is the gas -//! price, so the callers need no balance beyond the value they send. +//! - the L1 fees are zero ([`zero_fee_l1_block_info`], [`op_transaction`]), and the gas price is +//! the transaction's own (zero unless it sets one). #[cfg(not(feature = "std"))] use alloc as std; @@ -27,6 +27,7 @@ use revm::{ result::{EVMError, ResultAndState}, transaction::{ AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization, + TransactionType, }, BlockEnv, TxEnv, }, @@ -59,7 +60,7 @@ pub struct Scenario { /// The accounts that exist before the first transaction. pub pre: BTreeMap, /// The transactions, run in order, each on the state the previous one left. - pub txs: Vec, + pub txs: Vec, } /// An account of the pre-state. @@ -83,7 +84,7 @@ pub struct PreAccount { /// How a scenario transaction is run. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] #[serde(rename_all = "snake_case")] -pub enum TxSpecKind { +pub enum ScenarioTxKind { /// A message call to `to`. #[default] Call, @@ -101,7 +102,7 @@ pub enum TxSpecKind { /// list, legacy otherwise. #[derive(Clone, Debug, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct TxSpec { +pub struct ScenarioTx { /// Sender. pub caller: Address, /// Target of a call or a system call; absent for a create. @@ -117,9 +118,13 @@ pub struct TxSpec { /// system-call gas limit and must not set one. #[serde(default)] pub gas_limit: Option, + /// Gas price. With the block's zero base fee it is the effective price of every + /// transaction type; zero by default, so a caller needs no balance for gas. + #[serde(default)] + pub gas_price: u128, /// How the transaction is run. #[serde(default)] - pub kind: TxSpecKind, + pub kind: ScenarioTxKind, /// EIP-2930 access list. #[serde(default)] pub access_list: Vec, @@ -166,17 +171,18 @@ impl Scenario { } for (i, tx) in self.txs.iter().enumerate() { let problem = match tx.kind { - TxSpecKind::Call if tx.to.is_none() => Some("a call needs `to`"), - TxSpecKind::Create if tx.to.is_some() => Some("a create must not set `to`"), - TxSpecKind::Create if !tx.authorization_list.is_empty() => { + ScenarioTxKind::Call if tx.to.is_none() => Some("a call needs `to`"), + ScenarioTxKind::Create if tx.to.is_some() => Some("a create must not set `to`"), + ScenarioTxKind::Create if !tx.authorization_list.is_empty() => { Some("an EIP-7702 transaction cannot create") } - TxSpecKind::Call | TxSpecKind::Create if tx.gas_limit.is_none() => { + ScenarioTxKind::Call | ScenarioTxKind::Create if tx.gas_limit.is_none() => { Some("a call or a create needs `gas_limit`") } - TxSpecKind::SystemCall if tx.to.is_none() => Some("a system call needs `to`"), - TxSpecKind::SystemCall + ScenarioTxKind::SystemCall if tx.to.is_none() => Some("a system call needs `to`"), + ScenarioTxKind::SystemCall if tx.gas_limit.is_some() || + tx.gas_price != 0 || !tx.value.is_zero() || !tx.access_list.is_empty() || !tx.authorization_list.is_empty() => @@ -196,6 +202,10 @@ impl Scenario { /// /// Code is decoded as the node decodes it: an EIP-7702 delegation designator becomes a /// delegation, anything else legacy bytecode. + /// + /// # Panics + /// + /// If the scenario does not [`validate`](Self::validate). pub fn database(&self) -> MemoryDatabase { let mut db = MemoryDatabase::default(); for (address, account) in &self.pre { @@ -232,6 +242,10 @@ impl Scenario { /// Runs every transaction on a fresh [`MegaEvm`] over `db`, committing the state of each /// successful one before the next. Returns the outcomes in order and the final database. + /// + /// # Panics + /// + /// If the scenario does not [`validate`](Self::validate). pub fn run(&self, mut db: MemoryDatabase) -> (Vec, MemoryDatabase) { let mut outcomes = Vec::with_capacity(self.txs.len()); for tx in &self.txs { @@ -240,12 +254,12 @@ impl Scenario { .with_chain(zero_fee_l1_block_info()); let mut evm = MegaEvm::new(ctx); let outcome = match tx.kind { - TxSpecKind::SystemCall => evm.transact_system_call( + ScenarioTxKind::SystemCall => evm.transact_system_call( tx.caller, tx.to.expect("validated: a system call has a target"), tx.data.clone(), ), - TxSpecKind::Call | TxSpecKind::Create => { + ScenarioTxKind::Call | ScenarioTxKind::Create => { let nonce = evm.db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); evm.transact_raw(OpTx(op_transaction(tx.tx_env(nonce)))) } @@ -260,21 +274,26 @@ impl Scenario { } } -impl TxSpec { +impl ScenarioTx { /// The EIP-2718 transaction type the lists imply. - pub fn tx_type(&self) -> u8 { + pub fn tx_type(&self) -> TransactionType { if !self.authorization_list.is_empty() { - 4 + TransactionType::Eip7702 } else if !self.access_list.is_empty() { - 1 + TransactionType::Eip2930 } else { - 0 + TransactionType::Legacy } } /// The transaction as the EVM executes it, with `nonce` as the sender's nonce. /// /// Only meaningful for calls and creates; a system call is built by the engine. + /// + /// # Panics + /// + /// If the transaction has no gas limit, which [`Scenario::validate`] rejects for a call or + /// a create. pub fn tx_env(&self, nonce: u64) -> TxEnv { let access_list = AccessList( self.access_list @@ -300,14 +319,16 @@ impl TxSpec { }) .collect(); TxEnv::builder() - .tx_type(Some(self.tx_type())) + .tx_type(Some(self.tx_type() as u8)) .caller(self.caller) .kind(self.to.map_or(TxKind::Create, TxKind::Call)) .data(self.data.clone()) .value(self.value) - .gas_limit(self.gas_limit.unwrap_or_default()) - .gas_price(0) - .gas_priority_fee((self.tx_type() == 4).then_some(0)) + .gas_limit(self.gas_limit.expect("a call or a create has a gas limit")) + .gas_price(self.gas_price) + .gas_priority_fee( + (self.tx_type() == TransactionType::Eip7702).then_some(self.gas_price), + ) .nonce(nonce) .access_list(access_list) .authorization_list_recovered(authorizations) @@ -324,20 +345,21 @@ mod tests { const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); - fn call(gas_limit: Option) -> TxSpec { - TxSpec { + fn call(gas_limit: Option) -> ScenarioTx { + ScenarioTx { caller: CALLER, to: Some(CALLEE), data: Bytes::new(), value: U256::ZERO, gas_limit, - kind: TxSpecKind::Call, + gas_price: 0, + kind: ScenarioTxKind::Call, access_list: Vec::new(), authorization_list: Vec::new(), } } - fn scenario(txs: Vec) -> Scenario { + fn scenario(txs: Vec) -> Scenario { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)).stop().build(); Scenario { name: "sstore".into(), @@ -362,7 +384,7 @@ mod tests { #[test] fn test_validate_rejects_a_system_call_with_gas_limit() { - let tx = TxSpec { kind: TxSpecKind::SystemCall, ..call(Some(100_000)) }; + let tx = ScenarioTx { kind: ScenarioTxKind::SystemCall, ..call(Some(100_000)) }; let err = scenario(vec![tx]).validate().unwrap_err(); assert_eq!(err, "sstore: tx[0]: a system call takes only `caller`, `to` and `data`"); } @@ -399,17 +421,19 @@ mod tests { #[test] fn test_tx_type_follows_the_lists() { let mut tx = call(Some(100_000)); - assert_eq!(tx.tx_env(0).tx_type, 0); + assert_eq!(tx.tx_env(0).tx_type, TransactionType::Legacy as u8); tx.access_list.push(AccessListEntry { address: CALLEE, storage_keys: vec![U256::ZERO] }); - assert_eq!(tx.tx_env(0).tx_type, 1); + assert_eq!(tx.tx_env(0).tx_type, TransactionType::Eip2930 as u8); tx.authorization_list.push(AuthorizationEntry { chain_id: U256::ZERO, address: CALLEE, nonce: 0, authority: None, }); + tx.gas_price = 5; let env = tx.tx_env(3); - assert_eq!((env.tx_type, env.nonce, env.gas_priority_fee), (4, 3, Some(0))); + assert_eq!(env.tx_type, TransactionType::Eip7702 as u8); + assert_eq!((env.nonce, env.gas_price, env.gas_priority_fee), (3, 5, Some(5))); } #[test] From a006e2221f6180ce31f234c79b7626c77a254b3b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 16:11:03 +0800 Subject: [PATCH 046/201] test: cover gas prices in the differential corpus --- crates/mega-differential/README.md | 4 +- .../scenarios/harness/fee_access_list.json | 44 +++++++++++++++++++ .../harness/fee_balance_below_max_fee.json | 21 +++++++++ .../scenarios/harness/fee_eip7702.json | 32 ++++++++++++++ .../harness/fee_reservoir_refund.json | 21 +++++++++ .../scenarios/harness/fee_revert.json | 24 ++++++++++ .../harness/fee_sstore_clear_refund.json | 27 ++++++++++++ .../scenarios/harness/fee_value_transfer.json | 21 +++++++++ crates/mega-differential/src/oracle.rs | 31 +++++++++---- 9 files changed, 215 insertions(+), 10 deletions(-) create mode 100644 crates/mega-differential/scenarios/harness/fee_access_list.json create mode 100644 crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json create mode 100644 crates/mega-differential/scenarios/harness/fee_eip7702.json create mode 100644 crates/mega-differential/scenarios/harness/fee_reservoir_refund.json create mode 100644 crates/mega-differential/scenarios/harness/fee_revert.json create mode 100644 crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json create mode 100644 crates/mega-differential/scenarios/harness/fee_value_transfer.json diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index ba836b093..4f2dbb96d 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 343 scenarios, 13027 fields compared, 1064 deviations matched (op-fee-vault-touch x1056, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects +differential: 350 scenarios, 13223 fields compared, 1082 deviations matched (op-fee-vault-touch x1074, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects ``` CI runs the same command as the `differential` job (`.github/workflows/differential.yml`), on every pull request and every push to `satin`. @@ -64,7 +64,7 @@ The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | | `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | | `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | -| `harness/` | 57 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | +| `harness/` | 64 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, gas prices (`fee_*`: the fee debit, the coinbase's fee and the refunds show up in balances), the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | The first two sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. diff --git a/crates/mega-differential/scenarios/harness/fee_access_list.json b/crates/mega-differential/scenarios/harness/fee_access_list.json new file mode 100644 index 000000000..25c14ffb5 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_access_list.json @@ -0,0 +1,44 @@ +{ + "name": "fee_access_list", + "description": "An EIP-2930 transaction at 4 gwei.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 4000000000, + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0", + "0x2" + ] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json b/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json new file mode 100644 index 000000000..1547e5975 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json @@ -0,0 +1,21 @@ +{ + "name": "fee_balance_below_max_fee", + "description": "The sender holds less than gas limit times gas price: the transaction is rejected before execution.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0x38d7ea4c68000" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x0000000000000000000000000000000000000b0d", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 10000000000 + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_eip7702.json b/crates/mega-differential/scenarios/harness/fee_eip7702.json new file mode 100644 index 000000000..f5bbded02 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_eip7702.json @@ -0,0 +1,32 @@ +{ + "name": "fee_eip7702", + "description": "An EIP-7702 transaction at 2 gwei, max fee and priority fee equal.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 2000000000, + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json b/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json new file mode 100644 index 000000000..8a9f3f407 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json @@ -0,0 +1,21 @@ +{ + "name": "fee_reservoir_refund", + "description": "An empty call at 1 gwei with a gas limit 1,000,000 over the execution cap: the unused reservoir and the unused regular gas are both refunded to the sender.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x0000000000000000000000000000000000000b0d", + "data": "0x", + "value": "0x0", + "gas_limit": 201000000, + "kind": "call", + "gas_price": 1000000000 + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_revert.json b/crates/mega-differential/scenarios/harness/fee_revert.json new file mode 100644 index 000000000..5b09b0ad4 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_revert.json @@ -0,0 +1,24 @@ +{ + "name": "fee_revert", + "description": "A call that reverts at 2 gwei: the sender pays for the gas used, the value stays.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + }, + "0x00000000000000000000000000000000000008e7": { + "code": "0x600160005560006000fd" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x00000000000000000000000000000000000008e7", + "data": "0x", + "value": "0x9", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 2000000000 + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json b/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json new file mode 100644 index 000000000..c4c74c3fa --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json @@ -0,0 +1,27 @@ +{ + "name": "fee_sstore_clear_refund", + "description": "Clearing a storage slot at 3 gwei: the clearing refund lowers what the sender pays.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + }, + "0x000000000000000000000000000000000000c1ea": { + "code": "0x600060005500", + "storage": { + "0x0": "0x5" + } + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x000000000000000000000000000000000000c1ea", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 3000000000 + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/fee_value_transfer.json b/crates/mega-differential/scenarios/harness/fee_value_transfer.json new file mode 100644 index 000000000..43cdf3f3c --- /dev/null +++ b/crates/mega-differential/scenarios/harness/fee_value_transfer.json @@ -0,0 +1,21 @@ +{ + "name": "fee_value_transfer", + "description": "A 1,000 wei transfer at 7 gwei: the sender pays value and gas, the coinbase gets the fee.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x000000000000000000000000000000000000fee0": { + "balance": "0xde0b6b3a7640000" + } + }, + "txs": [ + { + "caller": "0x000000000000000000000000000000000000fee0", + "to": "0x0000000000000000000000000000000000000b0d", + "data": "0x", + "value": "0x3e8", + "gas_limit": 1000000, + "kind": "call", + "gas_price": 7000000000 + } + ] +} diff --git a/crates/mega-differential/src/oracle.rs b/crates/mega-differential/src/oracle.rs index e3fca4c80..963e35fcb 100644 --- a/crates/mega-differential/src/oracle.rs +++ b/crates/mega-differential/src/oracle.rs @@ -290,27 +290,42 @@ mod tests { } }; drop(evm); - let outcome = outcome.unwrap(); - records.push(record(&outcome.result, None, &outcome.state)); - db.commit(outcome.state); + records.push(match outcome { + Ok(outcome) => { + let record = record(&outcome.result, None, &outcome.state); + db.commit(outcome.state); + record + } + Err(err) => { + TxRecord { outcome: format!("error:{}", error(&err)), ..Default::default() } + } + }); } records } /// The probe only reads the reservoir: without that figure, every scenario records the same - /// as through revm 43's own `transact` and `system_call_with_caller`. + /// as through revm 43's own `transact` and `system_call_with_caller`, rejected transactions + /// included. #[test] fn test_reservoir_probe_changes_nothing_else() { let scenarios = crate::load_corpus(&crate::corpus_dir()).unwrap(); - assert!(scenarios - .iter() - .any(|s| s.txs.iter().any(|tx| tx.kind == ScenarioTxKind::SystemCall))); + let txs = || scenarios.iter().flat_map(|s| &s.txs); + assert!(txs().any(|tx| tx.kind == ScenarioTxKind::SystemCall)); + let mut rejected = 0; for scenario in &scenarios { let mut probed = run(scenario); for record in &mut probed { - assert!(record.gas.remove("reservoir_remaining").is_some(), "{}", scenario.name); + if record.outcome.starts_with("error:") { + rejected += 1; + assert!(record.gas.is_empty(), "{}", scenario.name); + } else { + let reservoir = record.gas.remove("reservoir_remaining"); + assert!(reservoir.is_some(), "{}", scenario.name); + } } assert_eq!(probed, run_stock(scenario), "{}", scenario.name); } + assert!(rejected > 0, "the corpus has a rejected transaction"); } } From 8235e34dfbf18246dba9bd798fd72f6de0f85f1d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 16:20:41 +0800 Subject: [PATCH 047/201] ci: fail the execution-spec count when its runner fails --- .github/workflows/exec-spec.yml | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index db7306dfa..0c7c6529d 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -113,20 +113,30 @@ jobs: | xargs -0 jq -r --arg fork "$2" '[.[] | .post[$fork] // [] | length] | add // 0' \ | awk '{ n += $1 } END { print n + 0 }' } - # State tests the runner executes for a fork, from its per-test JSON outcome on stderr, - # keyed by revm's spec id (`OSAKA`). Other stderr lines are not JSON and are dropped. - # shellcheck disable=SC2016 - executed() { + # The script's run prints no counts, so the two state-test trees run once more with the + # runner's per-test JSON outcome on stderr (about a minute of the job). The build is + # the one the script made. + outcomes() { cargo run --release -p revme -- statetest --json-outcome --omit-progress "$1" \ 2> outcomes.jsonl > /dev/null - jq -Rr --arg spec "$2" 'fromjson? | select(type == "object" and .fork == $spec) | .test' \ + } + # State tests the runner executed for a fork, keyed by revm's spec id (`OSAKA`). Other + # stderr lines are not JSON and are dropped. `$spec` in the jq program is a jq variable. + # shellcheck disable=SC2016 + executed() { + jq -Rr --arg spec "$1" 'fromjson? | select(type == "object" and .fork == $spec) | .test' \ outcomes.jsonl | wc -l | tr -d ' ' } check() { local label=$1 dir=$2 fork=$3 spec=$4 want_executed=$5 want_skipped=$6 local total ran skipped total=$(defined "$dir" "$fork") - ran=$(executed "$dir" "$spec") + # `check` runs under `||`, where errexit is off: a failing run is reported here. + if ! outcomes "$dir"; then + echo "::error::$label: the runner failed on $dir" + return 1 + fi + ran=$(executed "$spec") skipped=$((total - ran)) echo "$label: $ran executed, $skipped skipped of $total defined ($dir)" echo "| $label | $ran | $skipped | $total |" >> "$GITHUB_STEP_SUMMARY" From d1e68c12a586bf583dde9a9c74d07c430c629312 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 16:20:42 +0800 Subject: [PATCH 048/201] docs: keep the corpus size out of REVIEW.md and qualify the execution-spec coverage --- REVIEW.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index 3de90e38e..87f276254 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -82,7 +82,7 @@ These checks guard every change to the Satin engine. ### Differential harness -- `crates/mega-differential` runs every scenario of its corpus (343 today: 23 hand-written, 263 derived from the execution-spec tests of EIP-8037, 57 written for the harness) through `MegaEvm` and through stock revm 43, and compares every gas figure, the outcome, the output, the logs and every touched account. +- `crates/mega-differential` runs every scenario of its corpus (listed in its README) through `MegaEvm` and through stock revm 43, and compares every gas figure, the outcome, the output, the logs and every touched account. - The `differential` check (`.github/workflows/differential.yml`) runs it on every pull request and every push to `satin`; it must pass with no unexplained difference and no stale registry effect. - A change that makes `MegaEvm` differ from revm 43 on purpose adds the effects to `crates/mega-differential/deviations.json` (mechanism, reason, exact values), or configures the oracle to model the mechanism. Review a registry change like a spec change: an effect wider than its mechanism (a `*` where an exact value fits, a scenario pattern of `*` for a mechanism a few scenarios reach) hides the next regression. @@ -91,6 +91,7 @@ These checks guard every change to the Satin engine. ### Execution-spec tests - Engine-level execution-spec coverage on `MegaEvm` is the 263 execution-spec-derived scenarios of the differential harness, until the state-test tool is ported to Satin. + They come from the EIP-8037 state tests; while the Osaka gas table prices state gas at zero they exercise the reservoir, refunds and regular gas, and their state-gas paths count once the Satin gas table prices state. - `.github/workflows/exec-spec.yml` runs the fork's own runner on the execution-spec-test fixtures, at the fork tag `Cargo.lock` pins, and checks the Osaka and Amsterdam executed and skipped counts pinned in the workflow. It checks the fork `MegaEvm` runs on, not `MegaEvm`, and it is not a required check. - It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. From 0f0e963bd9d1200f647cab80b87908eb25746e71 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:30:52 +0800 Subject: [PATCH 049/201] test: verify a KZG proof in the differential corpus The only point-evaluation scenario fed the precompile 192 zero bytes, whose versioned hash fails before verify_kzg_proof runs, so the corpus said nothing about the two arms' KZG backends: the left arm's c-kzg and the oracle's arkworks. Add a scenario with the c-kzg test vector (a matching versioned hash and a valid proof, returning the 64-byte field parameters) and one that repeats the commitment in place of the proof, so the call clears the hash check and fails in verification. Two failing calls agree as readily as two succeeding ones, so a claim test pins the left arm's status, return bytes and the proxy's slots for the valid scenario, and that the wrong-proof scenario differs from it only in the proof. Both arms agree on all four scenarios; no registry entry. --- crates/mega-differential/README.md | 5 +- .../precompile_point_evaluation_valid.json | 23 ++++++ ...ecompile_point_evaluation_wrong_proof.json | 23 ++++++ crates/mega-differential/tests/claims.rs | 72 ++++++++++++++++++- 4 files changed, 119 insertions(+), 4 deletions(-) create mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json create mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md index 4f2dbb96d..5cefaf0d4 100644 --- a/crates/mega-differential/README.md +++ b/crates/mega-differential/README.md @@ -11,7 +11,7 @@ cargo test -p mega-differential --locked The corpus test prints one summary line, for example: ```text -differential: 350 scenarios, 13223 fields compared, 1082 deviations matched (op-fee-vault-touch x1074, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects +differential: 352 scenarios, 13296 fields compared, 1088 deviations matched (op-fee-vault-touch x1080, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects ``` CI runs the same command as the `differential` job (`.github/workflows/differential.yml`), on every pull request and every push to `satin`. @@ -48,6 +48,7 @@ cargo tree -p mega-differential -i revm@40.0.3 --locked ``` The oracle is built without revm's default features, so it adds no native precompile backend (c-kzg, blst, secp256k1) to the build; it runs the pure-Rust ones. +A precompile scenario therefore compares two independent implementations: `harness/precompile_point_evaluation_valid` verifies the same KZG proof through the fork's c-kzg and through the oracle's arkworks, and `tests/claims.rs` pins what the left arm returns for it, so two calls that fail cannot stand in for a proof neither arm verified. Its `dev` feature compiles the same optional configuration fields `mega-evm` compiles on the fork, so each of them is copied. The lockfile is shared. @@ -64,7 +65,7 @@ The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. | -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | | `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | | `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | -| `harness/` | 64 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, gas prices (`fee_*`: the fee debit, the coinbase's fee and the refunds show up in balances), the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | +| `harness/` | 66 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, gas prices (`fee_*`: the fee debit, the coinbase's fee and the refunds show up in balances), the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | The first two sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json new file mode 100644 index 000000000..3a4c46728 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_point_evaluation_valid", + "description": "KZG point evaluation on a valid proof: the versioned hash matches the commitment and verification succeeds, so the call returns FIELD_ELEMENTS_PER_BLOB and the BLS modulus.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x000000000000000000000000000000000000990a": { + "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x000000000000000000000000000000000000990a", + "data": "0x01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff000000001522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e98f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json new file mode 100644 index 000000000..b71be9041 --- /dev/null +++ b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json @@ -0,0 +1,23 @@ +{ + "name": "precompile_point_evaluation_wrong_proof", + "description": "KZG point evaluation with the versioned hash of the commitment but the commitment repeated in place of the proof: a well-formed curve point that is not the proof, so the call reaches verification and fails there.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x000000000000000000000000000000000000990a": { + "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x000000000000000000000000000000000000990a", + "data": "0x01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff000000001522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e98f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b78f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-differential/tests/claims.rs b/crates/mega-differential/tests/claims.rs index b32768668..55f7ed57e 100644 --- a/crates/mega-differential/tests/claims.rs +++ b/crates/mega-differential/tests/claims.rs @@ -2,9 +2,9 @@ use std::collections::BTreeMap; -use mega_differential::oracle; +use mega_differential::{corpus_dir, mega, oracle}; use mega_evm::{ - alloy_primitives::{address, Address, Bytes, U256}, + alloy_primitives::{address, hex, keccak256, Address, Bytes, U256}, revm::{ context_interface::cfg::gas_params::GasId as ForkGasId, database::{states::bundle_state::BundleRetention, State}, @@ -20,6 +20,18 @@ use revm_oracle::{ const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); +/// The proxy of the `precompile_point_evaluation_*` scenarios: it calls the precompile and +/// records the call's status in slot 0, the size of the return data in slot 1 and its hash in +/// slot 2. +const KZG_PROXY: Address = address!("0x000000000000000000000000000000000000990a"); + +/// What a successful point evaluation returns: `FIELD_ELEMENTS_PER_BLOB` and the BLS modulus, +/// each as a 32-byte big-endian value. +const POINT_EVALUATION_OUTPUT: [u8; 64] = hex!( + "0000000000000000000000000000000000000000000000000000000000001000" + "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001" +); + /// The gas ids the fork adds on top of upstream's. revm 43 has no price at these indexes. const FORK_ONLY_GAS_IDS: &[&str] = &["code_deposit_history_gas"]; @@ -107,3 +119,59 @@ fn test_zero_fee_vault_touch_leaves_no_committed_account() { assert!(bundle.account(&vault).is_none(), "{vault}"); } } + +/// Reads a scenario of `scenarios/harness/` by name. +fn harness_scenario(name: &str) -> Scenario { + let path = corpus_dir().join("harness").join(format!("{name}.json")); + let scenario: Scenario = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + scenario.validate().unwrap(); + scenario +} + +/// The corpus compares the two arms, and two calls that fail agree as readily as two that +/// succeed, so the positive KZG case needs a pinned value on the left arm: this is what +/// `MegaEvm`'s KZG backend returns for a valid proof, and it is only produced after +/// `verify_kzg_proof` accepts it. +#[test] +fn test_point_evaluation_on_a_valid_proof_returns_the_field_parameters() { + let scenario = harness_scenario("precompile_point_evaluation_valid"); + let record = mega::run(&scenario); + + assert_eq!(record.len(), 1); + assert_eq!(record[0].outcome, "success"); + assert_eq!(record[0].output, Bytes::from_static(&POINT_EVALUATION_OUTPUT)); + // The proxy's record of the inner call: status 1, 64 bytes of return data, its hash. + assert_eq!( + record[0].state[&KZG_PROXY].storage, + BTreeMap::from([ + (U256::ZERO, U256::from(1)), + (U256::from(1), U256::from(64)), + (U256::from(2), keccak256(POINT_EVALUATION_OUTPUT).into()), + ]), + ); +} + +/// The wrong-proof scenario differs from the valid one only in the proof, so its versioned hash +/// still matches its commitment: the call gets past that check and fails in verification, with +/// no status, no return data and the hash of an empty return. +#[test] +fn test_point_evaluation_on_a_wrong_proof_fails_in_verification() { + let valid = harness_scenario("precompile_point_evaluation_valid"); + let scenario = harness_scenario("precompile_point_evaluation_wrong_proof"); + let (input, valid_input) = (&scenario.txs[0].data, &valid.txs[0].data); + + // | versioned hash 32 | z 32 | y 32 | commitment 48 | proof 48 | + assert_eq!(input[..144], valid_input[..144], "same versioned hash, z, y and commitment"); + assert_ne!(input[144..192], valid_input[144..192], "a different proof"); + + let record = mega::run(&scenario); + assert_eq!(record.len(), 1); + assert_eq!(record[0].outcome, "success"); + assert_eq!(record[0].output, Bytes::new()); + assert_eq!( + record[0].state[&KZG_PROXY].storage, + BTreeMap::from([(U256::from(2), keccak256([]).into())]), + "storing zero into an empty slot is not a change, so only the hash slot is recorded", + ); +} From 20e0c93afd52a860b5be1823a0e73a4381494e01 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:31:38 +0800 Subject: [PATCH 050/201] ci: fail the execution-spec count when a counting command fails `check` runs under `||`, so errexit is off inside it and the two command substitutions that count the defined and the executed state tests were unguarded: a pipeline that printed the expected number and then exited non-zero still passed the comparison. Guard both the way the runner call is guarded, each assigned on its own so it carries the command's status. Probed by extracting `check` from the workflow and sourcing it with stub `defined` / `executed` / `outcomes`: with all three succeeding it returns 0; with `defined` printing 19517 and returning 1, with `outcomes` returning 1, and with `executed` printing 19465 and returning 1 it returns 1 each time, and it still returns 1 on a count off by one. The same probe on the previous revision returns 0 for the failing `defined`. --- .github/workflows/exec-spec.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 0c7c6529d..fd9ea2698 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -130,13 +130,22 @@ jobs: check() { local label=$1 dir=$2 fork=$3 spec=$4 want_executed=$5 want_skipped=$6 local total ran skipped - total=$(defined "$dir" "$fork") - # `check` runs under `||`, where errexit is off: a failing run is reported here. + # `check` runs under `||`, where errexit is off, so every step is guarded here: a + # counting pipeline that prints the expected number and then fails would otherwise + # pass the comparison below. Each command substitution is assigned on its own so the + # assignment carries the command's status (`local total=$(...)` would mask it). + if ! total=$(defined "$dir" "$fork"); then + echo "::error::$label: counting the state tests $dir defines failed" + return 1 + fi if ! outcomes "$dir"; then echo "::error::$label: the runner failed on $dir" return 1 fi - ran=$(executed "$spec") + if ! ran=$(executed "$spec"); then + echo "::error::$label: counting the state tests the runner executed for $spec failed" + return 1 + fi skipped=$((total - ran)) echo "$label: $ran executed, $skipped skipped of $total defined ($dir)" echo "| $label | $ran | $skipped | $total |" >> "$GITHUB_STEP_SUMMARY" From 2331cd386d78c276bd0454dcf08151dc26f6155c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:33:59 +0800 Subject: [PATCH 051/201] docs: keep the static-callee halt reasons owed in the pending ledger Six of the CREATE and CREATE2 rows ported into the differential corpus asserted the halt reason of a static callee, which a scenario cannot: the harness compares what the transaction reports, and an inner frame's halt reason is not part of that. The mapping table said the assertion was not carried over, which reads as discharged. Name it as owed instead, and name the mechanisms that make it assertable again. --- crates/mega-evm/tests/_pending/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 84fe008f7..41e91be62 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -109,6 +109,9 @@ A scenario keeps the transaction of its test; the assertions on compute gas (not | `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | `create2_missing_length` | | `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | `create2_missing_offset` | +The halt reason of a static callee is still owed, not discharged: 6 of these rows asserted it, and a scenario cannot, because the harness compares what the transaction reports and the inner frame's halt reason is not part of that. +It becomes assertable with the common execution layer, which defines the frame outcome, and inspector support, which reaches an inner frame as it ends; whichever lands first re-adds the assertions next to its own tests. + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | From 676160db0588346b86d6bb6a20f79dde4158a557 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:35:24 +0800 Subject: [PATCH 052/201] docs: make the mutation reference numbers reproducible The reference point named a mutant count without the base it was taken against or the command pair that produces it, and `cargo mutants` on its own reports a different population: the driver excludes the function-scoped suppressions before generation and the gate filters the line-scoped ones after the run. --- REVIEW.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/REVIEW.md b/REVIEW.md index 87f276254..dddd79883 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -110,6 +110,8 @@ These checks guard every change to the Satin engine. - The `cargo-mutants gate` job mutates the lines a pull request changes and fails on a surviving mutant that no reviewed suppression covers. Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. + That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --suppressions mutants/suppressions.toml`. + Take the numbers from that pair, not from `cargo mutants` on its own: the driver turns the function-scoped suppressions into `--exclude-re` before generation, and the gate filters the line-scoped ones after the run, so the bare command reports a different population and a different survivor count. - The job is bounded to 330 minutes. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. From 925f712ca6c875a3ef7584ad00c5337df89c735e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:52:14 +0800 Subject: [PATCH 053/201] test: add a mutation scope for the test gates' own infrastructure The production mutation scope excludes test helpers as noise and tests only mega-evm, so the code that implements the gates was never mutated: the scenario runner's transaction conversion and its execute/commit loop, and the differential harness's record, comparison and registry modules. Every later mechanism's verdict rests on that code. Add a second scope for exactly those files, tested against both packages, so the whole differential corpus is among its killing tests. The production scope keeps its exclusions and the two are disjoint. A suppression may belong to either, so the suppression-hygiene job lists both into its mutant universe. --- .cargo/mutants-infra.toml | 26 ++++++++++ .cargo/mutants.toml | 11 ++++- .github/workflows/mutation.yml | 89 +++++++++++++++++++++++++++++++--- REVIEW.md | 6 +++ mutants/README.md | 24 ++++++--- scripts/mutation_test.sh | 30 ++++++++++-- 6 files changed, 169 insertions(+), 17 deletions(-) create mode 100644 .cargo/mutants-infra.toml diff --git a/.cargo/mutants-infra.toml b/.cargo/mutants-infra.toml new file mode 100644 index 000000000..302f97b29 --- /dev/null +++ b/.cargo/mutants-infra.toml @@ -0,0 +1,26 @@ +# cargo-mutants configuration for the test gates' own infrastructure. +# +# The canonical run (.cargo/mutants.toml) mutates mega-evm production code and excludes test +# helpers as noise. By that rule the code implementing the gates is helper code, but it is +# executable logic every later mechanism's verdict rests on: the scenario runner's transaction +# conversion and its execute/commit loop, and the differential harness's record, comparison and +# registry modules. This config mutates exactly those, with the differential tests among the +# killing tests; the production run keeps its exclusions unchanged. +# +# Selected by `scripts/mutation_test.sh infra`, which passes the file globs. See mutants/README.md. + +test_tool = "nextest" +# Both packages are tested: mega-evm's unit tests cover the scenario runner, and the differential +# crate's tests (the whole corpus through both arms) cover the record, comparison and registry +# modules. mega-differential is not a default member, so it has to be named here. +test_package = ["mega-evm", "mega-differential"] + +# Same pinned feature set as the production run, so the two generate comparable mutants. +additional_cargo_args = ["--all-features"] + +# No `**/test_utils/**` exclusion here: the scenario runner living under it is the subject. +exclude_globs = ["**/generated/**"] + +minimum_test_timeout = 120 +timeout_multiplier = 3.0 +copy_target = true diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index eb9f37b75..840fddfda 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -4,8 +4,15 @@ # (scripts/mutation_test.sh + scripts/mutation_gate.py) layers diff-scoping, # suppression metadata, and PR gating on top of it. See mutants/README.md. # -# Scope: only `mega-evm` is mutated. `mega-system-contracts` produces 0 mutants -# (its src/ is generated bytecode artifacts), so it is intentionally absent. +# Scope: only `mega-evm` production code is mutated. `mega-system-contracts` +# produces 0 mutants (its src/ is generated bytecode artifacts), so it is +# intentionally absent. +# +# There is a second scope, .cargo/mutants-infra.toml (`scripts/mutation_test.sh +# infra`): the code that implements the test gates themselves, which the +# `**/test_utils/**` exclusion below and the single `test_package` would +# otherwise leave unmutated. The two scopes are disjoint and are gated +# separately; this one keeps its exclusions. # Run tests with nextest (the project's standard runner) and restrict the test # command to the mutated package for speed. diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 0adb0ae1e..f5e6ecc93 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -1,11 +1,13 @@ name: Mutation Testing -# All mutation-testing CI lives here. Three concerns, one file: +# All mutation-testing CI lives here. Four concerns, one file: # * cargo-mutants gate — generic operators (diff-scoped on PRs, full nightly) +# * infrastructure gate — the same operators on the code that implements the +# test gates, which the production scope excludes # * spec-gate — universalmutator + comby custom operators for # backward-compat spec gates (diff PR + nightly sweep) # * suppression hygiene — flag suppressions that no longer match a live mutant -# All three share the scorer scripts/mutation_gate.py. See mutants/README.md. +# All four share the scorer scripts/mutation_gate.py. See mutants/README.md. on: workflow_dispatch: @@ -125,6 +127,66 @@ jobs: mutation-report.md if-no-files-found: ignore + # ── cargo-mutants: the test gates' own infrastructure ────────────────────── + # The second mutation scope (.cargo/mutants-infra.toml): the scenario runner's + # transaction conversion and execute/commit loop, and the differential + # harness's record, comparison and registry modules. The production scope + # excludes test helpers as noise and tests only mega-evm, so this executable + # logic is never mutated there. 80 mutants today, so the whole set runs rather + # than a diff slice. Informational: it is not a required check. + infra-mutants: + name: cargo-mutants infrastructure + needs: changes + # Always on nightly/dispatch; on PRs only when the mutated code, its + # configuration or the driver changed. + if: | + always() && + (github.event_name != 'pull_request' || needs.changes.outputs.infra == 'true') + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Install cargo-nextest + uses: taiki-e/install-action@nextest + + - name: Install cargo-mutants + uses: taiki-e/install-action@v2 + with: + tool: cargo-mutants@27.1.0 + + - name: Warm build cache + # Both packages, since both are tested for every mutant of this scope. + run: cargo nextest run -p mega-evm -p mega-differential --all-features --no-run + + - name: Run mutation testing + env: + OUT_DIR: target/mutants-infra + run: scripts/mutation_test.sh infra + + - name: Score and gate + run: | + python3 scripts/mutation_gate.py report \ + --results target/mutants-infra/mutants.out \ + --suppressions mutants/suppressions.toml \ + --summary "$GITHUB_STEP_SUMMARY" + + - name: Upload mutation artifacts + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutation-results-infra + path: target/mutants-infra/mutants.out + if-no-files-found: ignore + # ── spec-gate: diff-scoped blocking gate on PRs ──────────────────────────── # Only files+lines the PR changed are mutated, so most PRs generate zero # spec-gate mutants and this is near-instant. @@ -260,12 +322,14 @@ jobs: # ── suppression hygiene: gate on relevant PR changes, plus nightly ───────── # `changes` scopes the hygiene job to PRs that could orphan a suppression - # (suppressions, operators, or src edits); nightly/dispatch always run it. + # (suppressions, operators, or src edits) and the infrastructure job to PRs + # that touch its scope; nightly/dispatch always run both. changes: if: github.event_name == 'pull_request' runs-on: ubuntu-24.04 outputs: hygiene: ${{ steps.filter.outputs.hygiene }} + infra: ${{ steps.filter.outputs.infra }} steps: - uses: dorny/paths-filter@v3 id: filter @@ -275,6 +339,12 @@ jobs: - 'mutants/suppressions.toml' - 'mutants/operators/**' - 'crates/mega-evm/src/**' + infra: + - '.cargo/mutants-infra.toml' + - 'crates/mega-differential/src/**' + - 'crates/mega-evm/src/test_utils/scenario.rs' + - 'scripts/mutation_gate.py' + - 'scripts/mutation_test.sh' orphan-suppressions: name: suppression hygiene @@ -306,10 +376,10 @@ jobs: sudo curl -fsSL https://github.com/comby-tools/comby/releases/download/1.8.1/comby-1.8.1-x86_64-linux -o /usr/local/bin/comby sudo chmod +x /usr/local/bin/comby comby -version - - name: Build the full mutant universe (both engines) + - name: Build the full mutant universe (both engines, both scopes) run: | - # --package mega-evm: match the driver's scope (otherwise --list also - # covers the CLI bins in the virtual workspace's default-members, so a + # --package mega-evm: match the driver's production scope (otherwise --list + # also covers the CLI bins in the virtual workspace's default-members, so a # stale mega-evm suppression could be kept alive by a same-named mutant # in another crate). # No --exclude-re here, so function-suppressed mutants are included — @@ -317,6 +387,13 @@ jobs: # --colors never: CI forces CARGO_TERM_COLOR=always, which would otherwise # embed ANSI codes and break exact suppression matching. cargo mutants --list --package mega-evm --colors never > universe.txt + # The infrastructure scope is a second mutant population and a suppression may live in + # it, so it joins the universe. Listed through the driver, so its file list stays in + # one place, with SUPPRESS=/dev/null so the driver emits no --exclude-re and function- + # suppressed mutants stay in the universe here too. The grep drops the driver's + # trailing progress lines and fails the step if the scope lists nothing. + SUPPRESS=/dev/null scripts/mutation_test.sh infra --list --colors never \ + | grep -oE 'crates/[^:]+:[0-9]+:[0-9]+: .*' >> universe.txt # The plan runs on its own so a planner failure still fails the step. # Its mutant lines are grepped separately: a single-spec engine (the # satin branch) has no spec gates and the pack finds nothing. grep's diff --git a/REVIEW.md b/REVIEW.md index dddd79883..fd135c0c5 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -115,6 +115,12 @@ These checks guard every change to the Satin engine. - The job is bounded to 330 minutes. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. +- The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) and the differential harness's `record`, `diff` and `registry` modules, with both packages' tests — so the whole corpus — among the killing tests. + The production scope excludes test helpers as noise and tests only `mega-evm`, so that code is otherwise never mutated, though every later mechanism's verdict rests on it. + The two scopes are disjoint and the production one keeps its exclusions; a suppression may belong to either, and the suppression-hygiene job lists both scopes into its mutant universe. + The `cargo-mutants infrastructure` job runs the scope on a pull request that touches those files, either configuration, the driver or the gate, and nightly; it is bounded to 90 minutes and is not a required check. +- `record.rs` builds a transaction record in a macro, and cargo-mutants does not mutate macro bodies, so four mutants cover that file. + Both arms build their records through that macro, so a fault in it moves both arms together and the comparison cannot see it; what covers it is the absolute values pinned in `crates/mega-differential/tests/claims.rs`, and any claim about a positive result belongs there for the same reason. - The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. It starts to bite with the first `is_enabled` gate of the spec after Satin. - The legacy mutant killers were retired with the legacy sources; a survivor in Satin code gets a new killer, next to the code or under `crates/mega-evm/tests/mutation/`. diff --git a/mutants/README.md b/mutants/README.md index a62642fbf..2363c49c1 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -3,18 +3,25 @@ Mutation testing measures **test adequacy**: it deliberately introduces small faults ("mutants") into the source and checks whether the test suite catches them. A mutant that survives a green test run is a place where the code could be wrong and no test would notice — a test gap. -Target: **`crates/mega-evm`**. -(`mega-system-contracts` is excluded — its `src/` is generated bytecode artifacts and produces zero mutants.) +Two scopes, mutated and gated separately: + +- **production** — `crates/mega-evm`'s engine code, with generated code and test helpers excluded as noise. + (`mega-system-contracts` is excluded too — its `src/` is generated bytecode artifacts and produces zero mutants.) +- **infrastructure** — the code that implements the test gates, which the helper exclusion removes from the production scope: the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) and the differential harness's `record`, `diff` and `registry` modules. + Mutated against both packages' tests, so the whole differential corpus is among the killing tests. + +The two scopes are disjoint; a mutant belongs to exactly one of them. ## Layout | Path | Purpose | |------|---------| -| `.cargo/mutants.toml` | Canonical `cargo-mutants` config (scope, nextest, excludes, timeouts). | -| `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating. | -| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `; `MUTANTS_SHARD=k/n` runs one shard. | +| `.cargo/mutants.toml` | Canonical `cargo-mutants` config for the production scope (nextest, excludes, timeouts). | +| `.cargo/mutants-infra.toml` | Config for the infrastructure scope (no helper exclusion, both packages tested). | +| `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating, in either scope. | +| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `, `infra`; `MUTANTS_SHARD=k/n` runs one shard. | | `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR. | -| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment. | +| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment, and the infrastructure job. | ## Local use @@ -27,6 +34,11 @@ python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' +# The infrastructure scope (its own output directory, so it does not overwrite the production run): +OUT_DIR=target/mutants-infra scripts/mutation_test.sh infra +python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.out \ + --suppressions mutants/suppressions.toml + # Shard k of n of a large run (cargo-mutants' --shard), each into its own directory: MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main ``` diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 0ffaad6bf..3b90bfbee 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -5,6 +5,12 @@ # diff Mutate only lines changed vs (PR gate mode). # full Mutate the whole mega-evm crate (nightly mode; slow). # file Mutate files matching (local iteration). +# infra Mutate the test gates' own infrastructure (see INFRA_FILES below). +# +# `diff`, `full` and `file` run the production scope of .cargo/mutants.toml, which excludes test +# helpers as noise. `infra` runs the second scope, .cargo/mutants-infra.toml: the code that +# implements the gates is helper code by that rule, but every later mechanism's verdict rests on +# it, so it is mutated against both packages' tests. # # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # Run scripts/mutation_gate.py afterwards to score + gate the run. @@ -18,7 +24,17 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" OUT_DIR="${OUT_DIR:-$ROOT_DIR/target/mutants}" SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" JOBS="${JOBS:-$(nproc)}" -PKG="mega-evm" +PKG_ARGS=(--package mega-evm) +CONFIG_ARGS=() + +# The test gates' own executable logic: the scenario runner's transaction conversion and its +# execute/commit loop, and the differential harness's record, comparison and registry modules. +INFRA_FILES=( + crates/mega-evm/src/test_utils/scenario.rs + crates/mega-differential/src/record.rs + crates/mega-differential/src/diff.rs + crates/mega-differential/src/registry.rs +) cd "$ROOT_DIR" @@ -50,7 +66,8 @@ run_mutants() { # -vV: verbose progress + version banner, for diagnosable CI logs. local rc=0 cargo mutants \ - --package "$PKG" \ + "${CONFIG_ARGS[@]}" \ + "${PKG_ARGS[@]}" \ --jobs "$JOBS" \ --output "$OUT_DIR" \ --no-shuffle \ @@ -94,8 +111,15 @@ case "$cmd" in glob="${1:?usage: mutation_test.sh file }" run_mutants -f "$glob" ;; + infra) + PKG_ARGS=(--package mega-evm --package mega-differential) + CONFIG_ARGS=(--config "$ROOT_DIR/.cargo/mutants-infra.toml") + FILE_ARGS=() + for file in "${INFRA_FILES[@]}"; do FILE_ARGS+=(-f "$file"); done + run_mutants "${FILE_ARGS[@]}" "$@" + ;; *) - echo "usage: mutation_test.sh {diff |full|file }" >&2 + echo "usage: mutation_test.sh {diff |full|file |infra}" >&2 exit 2 ;; esac From daed59c86089d2d6fed7d09746f71be907a09dc4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 17:52:43 +0800 Subject: [PATCH 054/201] test: close the infrastructure mutation survivors The new scope's first run left 18 survivors of 80 mutants. Fifteen were real gaps, closed with six tests: - the rendering of a log and of an account, which is what the comparison reports and what a registry effect is a pattern over; - the middle segments of the registry's glob, each of which starts where the one before it ended; - that a registry entry names both a mechanism and a reason, neither blank; - the per-kind field rules of a scenario transaction, and the system-call shape field by field; - the fixed block, whose five values both arms run on. Three are equivalent: the block writes a timestamp, a base fee and a gas limit that revm's BlockEnv default already holds, so deleting the field yields the same block. They are suppressed as line entries, and the test that pins all five values kills them if an upstream default moves. The scope now reports 80 mutants, 73 caught, 0 survived, 3 suppressed, 4 unviable, PASS, in 7m46s with JOBS=8. --- REVIEW.md | 2 + crates/mega-differential/src/record.rs | 46 ++++++++++++++ crates/mega-differential/src/registry.rs | 20 ++++++ crates/mega-evm/src/test_utils/scenario.rs | 73 ++++++++++++++++++++-- mutants/suppressions.toml | 37 +++++++++++ 5 files changed, 174 insertions(+), 4 deletions(-) diff --git a/REVIEW.md b/REVIEW.md index fd135c0c5..b7a613c3b 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -119,6 +119,8 @@ These checks guard every change to the Satin engine. The production scope excludes test helpers as noise and tests only `mega-evm`, so that code is otherwise never mutated, though every later mechanism's verdict rests on it. The two scopes are disjoint and the production one keeps its exclusions; a suppression may belong to either, and the suppression-hygiene job lists both scopes into its mutant universe. The `cargo-mutants infrastructure` job runs the scope on a pull request that touches those files, either configuration, the driver or the gate, and nightly; it is bounded to 90 minutes and is not a required check. + Reference point, its first run on the corpus this file describes: 80 mutants, 73 caught, 0 survived, 3 suppressed, 4 unviable, in 7m46s on a 15-core laptop with `JOBS=8`. + The three suppressed ones write a `BlockEnv` field that already holds that value by default, so no test can distinguish them; the test that pins those values kills them the moment a revm upgrade moves a default. - `record.rs` builds a transaction record in a macro, and cargo-mutants does not mutate macro bodies, so four mutants cover that file. Both arms build their records through that macro, so a fault in it moves both arms together and the comparison cannot see it; what covers it is the absolute values pinned in `crates/mega-differential/tests/claims.rs`, and any claim about a positive result belongs there for the same reason. - The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. diff --git a/crates/mega-differential/src/record.rs b/crates/mega-differential/src/record.rs index a06c1def1..5300c708d 100644 --- a/crates/mega-differential/src/record.rs +++ b/crates/mega-differential/src/record.rs @@ -147,3 +147,49 @@ macro_rules! tx_record { } }}; } + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, b256, bytes}; + + const A: Address = address!("0x0000000000000000000000000000000000000aaa"); + + /// Two logs at the same index are compared as this one line, and a registry effect for a log + /// is a pattern over it, so the rendering carries every field of the log. + #[test] + fn test_log_record_renders_address_topics_and_data() { + let log = LogRecord { + address: A, + topics: vec![ + b256!("0x0000000000000000000000000000000000000000000000000000000000000001"), + b256!("0x0000000000000000000000000000000000000000000000000000000000000002"), + ], + data: bytes!("0xbeef"), + }; + assert_eq!(log.render(), format!("{A:#x} [{},{}] 0xbeef", log.topics[0], log.topics[1])); + let empty = LogRecord { topics: Vec::new(), data: Bytes::new(), ..log }; + assert_eq!(empty.render(), format!("{A:#x} [] 0x")); + } + + /// The same for an account only one arm touched, which is reported as its rendering. + #[test] + fn test_account_record_renders_every_field() { + let account = AccountRecord { + created: true, + selfdestructed: false, + balance: U256::from(7), + nonce: 3, + code_hash: B256::ZERO, + storage: BTreeMap::from([(U256::from(1), U256::from(2)), (U256::from(3), U256::ZERO)]), + }; + assert_eq!( + account.render(), + format!( + "created=true selfdestructed=false balance=0x7 nonce=3 code_hash={} \ + storage={{0x1=0x2,0x3=0x0}}", + B256::ZERO, + ), + ); + } +} diff --git a/crates/mega-differential/src/registry.rs b/crates/mega-differential/src/registry.rs index 242292c6c..ab458733d 100644 --- a/crates/mega-differential/src/registry.rs +++ b/crates/mega-differential/src/registry.rs @@ -201,6 +201,9 @@ mod tests { assert!(!glob("a*b*c", "aXcYb")); // The suffix may not reuse characters the prefix consumed. assert!(!glob("ab*ba", "aba")); + // Nor may a middle segment: each one starts after the one before it ended. + assert!(glob("*b*b*", "abb")); + assert!(!glob("*b*b*", "ab")); } #[test] @@ -244,4 +247,21 @@ mod tests { assert!(Registry::from_json(r#"{"version": 2, "deviations": []}"#).is_err()); assert!(registry(&[entry("d", "paused", &[GAS_EFFECT], "")]).is_err()); } + + /// An entry names its mechanism and its reason; either one blank is rejected, so a blanket + /// excuse cannot be filed under a name that says nothing. + #[test] + fn test_registry_requires_both_a_mechanism_and_a_reason() { + let named = |mechanism: &str, reason: &str| { + Registry::from_json(&format!( + r#"{{"version": 1, "deviations": [{{"id": "d", "status": "active", + "scenario": "*", "mechanism": "{mechanism}", "reason": "{reason}", + "effects": [{GAS_EFFECT}]}}]}}"# + )) + }; + assert!(named("m", "r").is_ok()); + assert!(named("", "r").unwrap_err().contains("names its mechanism and its reason")); + assert!(named("m", "").unwrap_err().contains("names its mechanism and its reason")); + assert!(named(" ", " \t ").is_err(), "blank is not a name"); + } } diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 6b2185c3a..b3bc3f827 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -382,11 +382,76 @@ mod tests { assert_eq!(err, "sstore: tx[0]: a call or a create needs `gas_limit`"); } + /// Each kind needs the fields of its own shape; a missing or an excess field is rejected + /// with the rule that names it, so a scenario cannot reach the arms as something else. #[test] - fn test_validate_rejects_a_system_call_with_gas_limit() { - let tx = ScenarioTx { kind: ScenarioTxKind::SystemCall, ..call(Some(100_000)) }; - let err = scenario(vec![tx]).validate().unwrap_err(); - assert_eq!(err, "sstore: tx[0]: a system call takes only `caller`, `to` and `data`"); + fn test_validate_rejects_a_transaction_that_does_not_match_its_kind() { + let reject = |tx: ScenarioTx| scenario(vec![tx]).validate().unwrap_err(); + let create = + || ScenarioTx { kind: ScenarioTxKind::Create, to: None, ..call(Some(100_000)) }; + + assert_eq!( + reject(ScenarioTx { to: None, ..call(Some(100_000)) }), + "sstore: tx[0]: a call needs `to`" + ); + assert_eq!( + reject(ScenarioTx { kind: ScenarioTxKind::Create, ..call(Some(100_000)) }), + "sstore: tx[0]: a create must not set `to`" + ); + assert_eq!( + reject(ScenarioTx { + authorization_list: vec![AuthorizationEntry { + chain_id: U256::ZERO, + address: CALLEE, + nonce: 0, + authority: None, + }], + ..create() + }), + "sstore: tx[0]: an EIP-7702 transaction cannot create" + ); + assert!(scenario(vec![create()]).validate().is_ok()); + } + + /// A system call is built by the engine, so it takes only what the engine does not fix; + /// each of the other fields is rejected on its own. + #[test] + fn test_validate_rejects_a_system_call_that_sets_an_engine_field() { + let system_call = || ScenarioTx { kind: ScenarioTxKind::SystemCall, ..call(None) }; + let reject = |tx: ScenarioTx| scenario(vec![tx]).validate().unwrap_err(); + let extra = "sstore: tx[0]: a system call takes only `caller`, `to` and `data`"; + let authorization = + AuthorizationEntry { chain_id: U256::ZERO, address: CALLEE, nonce: 0, authority: None }; + let access = AccessListEntry { address: CALLEE, storage_keys: Vec::new() }; + + assert!(scenario(vec![system_call()]).validate().is_ok()); + assert_eq!( + reject(ScenarioTx { to: None, ..system_call() }), + "sstore: tx[0]: a system call needs `to`" + ); + assert_eq!(reject(ScenarioTx { gas_limit: Some(100_000), ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { gas_price: 1, ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { value: U256::from(1), ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { access_list: vec![access], ..system_call() }), extra); + assert_eq!( + reject(ScenarioTx { authorization_list: vec![authorization], ..system_call() }), + extra + ); + } + + /// The block is the same for every scenario and for both arms of the differential harness, + /// except for the beneficiary, which the scenario sets. + #[test] + fn test_block_is_fixed_except_for_the_beneficiary() { + let mut scenario = scenario(vec![]); + scenario.coinbase = CALLEE; + let block = scenario.block(); + + assert_eq!(block.number, U256::from(1)); + assert_eq!(block.timestamp, U256::from(1)); + assert_eq!(block.beneficiary, CALLEE); + assert_eq!(block.basefee, 0); + assert_eq!(block.gas_limit, u64::MAX); } /// Each transaction runs on the state the previous one committed, with the caller's diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 945b825b7..9c3253769 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -196,3 +196,40 @@ file = "crates/mega-evm/src/evm/spec.rs" mutant = "replace for EthSpecId>::from -> Self with Default::default()" justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." reviewer = "RealiCZ" + +# ───────────────────────────────────────────────────────────────────────────── +# Infrastructure scope (.cargo/mutants-infra.toml) survivors. + +# --- Scenario::block field deletions that restore the same value (equivalent) ------ +# `Scenario::block` writes five fields over `..Default::default()`. Three of them write +# exactly what revm 40's `BlockEnv::default()` already holds — `timestamp: U256::ONE`, +# `basefee: 0`, `gas_limit: u64::MAX` — so deleting the field yields the identical +# BlockEnv for every scenario, and no scenario or unit test can distinguish it. The two +# that do differ from the default (`number`, and `beneficiary`, which carries the +# scenario's coinbase) are killed by `test_block_is_fixed_except_for_the_beneficiary`, +# which pins all five values: if a revm upgrade moves one of these defaults, that test +# kills the mutant and the entry below becomes a no-op. Line entries, so they stay +# generated and are re-checked on every run. +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field timestamp from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes U256::from(1) and revm 40's BlockEnv::default() already has timestamp: U256::ONE, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" + +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field basefee from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes 0 and revm 40's BlockEnv::default() already has basefee: 0, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" + +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field gas_limit from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes u64::MAX and revm 40's BlockEnv::default() already has gas_limit: u64::MAX, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" From c094be9f18bd3d8110a70f3502ab0b6f242c1671 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:17:57 +0800 Subject: [PATCH 055/201] feat: define the Satin gas ledgers, block counters and limit verdict types --- crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/src/block/result.rs | 54 +++++ crates/mega-evm/src/evm/mod.rs | 2 + crates/mega-evm/src/evm/result.rs | 154 +++++++++++++++ crates/mega-evm/src/lib.rs | 1 + crates/mega-evm/src/limit/mod.rs | 186 +++++++++++++++++- crates/mega-evm/src/types.rs | 18 +- crates/mega-evm/tests/_pending/README.md | 16 +- .../mega-evm/tests/_pending/src/evm/result.rs | 57 ------ .../mega-evm/tests/_pending/src/limit/mod.rs | 54 ----- 10 files changed, 424 insertions(+), 120 deletions(-) create mode 100644 crates/mega-evm/src/block/result.rs create mode 100644 crates/mega-evm/src/evm/result.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/result.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/mod.rs diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index edf9ede21..9141ade89 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -3,7 +3,9 @@ mod chain; mod executor; mod hardfork; +mod result; pub use chain::*; pub use executor::*; pub use hardfork::*; +pub use result::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs new file mode 100644 index 000000000..fb4868f8b --- /dev/null +++ b/crates/mega-evm/src/block/result.rs @@ -0,0 +1,54 @@ +//! What a block counts of its transactions' gas. + +use crate::MegaGasUsage; + +/// A block's gas, on the three ledgers its transactions spend on. +/// +/// The block executor fills it transaction by transaction with [`record`](Self::record) and +/// holds each counter to its own block limit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BlockGasCounters { + /// Regular gas: each transaction's regular ledger, at least its EIP-7623 floor. + pub execution: u64, + /// State gas. + pub state: u64, + /// History gas. + pub history: u64, +} + +impl BlockGasCounters { + /// Adds one transaction's gas. + pub const fn record(&mut self, gas: &MegaGasUsage) { + self.execution = self.execution.saturating_add(gas.block_execution_gas()); + self.state = self.state.saturating_add(gas.state); + self.history = self.history.saturating_add(gas.history); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_block_counters_add_each_ledger() { + let mut block = BlockGasCounters::default(); + let first = + MegaGasUsage { regular: 10, state: 20, history: 30, floor: 0, ..Default::default() }; + let floored = + MegaGasUsage { regular: 5, state: 1, history: 2, floor: 50, ..Default::default() }; + block.record(&first); + block.record(&floored); + assert_eq!(block, BlockGasCounters { execution: 60, state: 21, history: 32 }); + } + + #[test] + fn test_block_counters_saturate() { + let mut block = + BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX }; + block.record(&MegaGasUsage { regular: 1, state: 1, history: 1, ..Default::default() }); + assert_eq!( + block, + BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX } + ); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index f0e9d6b8c..db3d5c9b7 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -6,10 +6,12 @@ mod context; mod factory; +mod result; mod spec; pub use context::*; pub use factory::*; +pub use result::*; pub use spec::*; use alloy_evm::EvmEnv; diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs new file mode 100644 index 000000000..9d9767abd --- /dev/null +++ b/crates/mega-evm/src/evm/result.rs @@ -0,0 +1,154 @@ +//! What a Satin transaction reports: its gas by ledger. +//! +//! A transaction pays from the EIP-8037 pools (the reservoir first, then regular gas) on three +//! ledgers, counted apart: +//! +//! - **regular**: execution. It is the compute gas the resource limits meter. +//! - **state**: bytes added to the world state (EIP-8037 state gas). +//! - **history**: bytes appended to the chain's history (logs, deployed code, write records, the +//! transaction body). +//! +//! State or history gas that spilled from the reservoir onto regular gas stays on its own ledger, +//! so it is not compute. The ledgers are raw spend, before the refund; the receipt reports +//! [`gas_used`](MegaGasUsage::gas_used), which is their sum less the refund, at least the EIP-7623 +//! floor. + +use revm::context::result::ResultGas; + +/// The gas one transaction spent, by ledger, and what its receipt reports. +/// +/// `regular + state + history` is the transaction's raw spend, +/// [`ResultGas::total_gas_spent`]; [`gas_used`](Self::gas_used) is +/// [`ResultGas::tx_gas_used`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MegaGasUsage { + /// Regular gas spent: everything that is neither state nor history gas, before the refund. + pub regular: u64, + /// State gas spent, net of refills. + pub state: u64, + /// History gas spent, net of refills. + pub history: u64, + /// The EIP-8037 reservoir left unspent, which the sender gets back. + pub reservoir_remaining: u64, + /// The EIP-7623 floor the receipt's gas used cannot fall below. + pub floor: u64, + /// The gas used the receipt reports: the raw spend less the refund, at least the floor. + pub gas_used: u64, +} + +impl MegaGasUsage { + /// The ledgers of a transaction that settled into `result_gas` and spent `history` gas on + /// history. + /// + /// [`ResultGas`] has no history field; its total includes history gas, which is taken back + /// out of regular here. + pub const fn new(result_gas: &ResultGas, history: u64) -> Self { + let state = result_gas.state_gas_spent_final(); + Self { + regular: result_gas.total_gas_spent().saturating_sub(state).saturating_sub(history), + state, + history, + reservoir_remaining: result_gas.reservoir_remaining(), + floor: result_gas.floor_gas(), + gas_used: result_gas.tx_gas_used(), + } + } + + /// The regular gas a block counts for the transaction: the regular ledger, at least the + /// floor (EIP-8037 with EIP-7778). The refund does not lower it. + pub const fn block_execution_gas(&self) -> u64 { + if self.regular > self.floor { + self.regular + } else { + self.floor + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{LimitCheck, LimitKind, MegaHaltReason, MegaLimitExceeded}; + use alloy_sol_types::SolError; + use op_revm::OpHaltReason; + use revm::context::result::{HaltReason as EthHaltReason, OutOfGasError}; + + fn result_gas(total: u64, state: u64, refunded: u64, floor: u64) -> ResultGas { + ResultGas::default() + .with_total_gas_spent(total) + .with_state_gas_spent(state) + .with_refunded(refunded) + .with_floor_gas(floor) + .with_reservoir_remaining(5_000) + } + + /// The three ledgers add up to the raw spend; the receipt figure is the spend less the refund. + #[test] + fn test_ledgers_split_the_raw_spend() { + let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000); + assert_eq!(gas.regular, 60_000); + assert_eq!(gas.state, 30_000); + assert_eq!(gas.history, 10_000); + assert_eq!(gas.regular + gas.state + gas.history, 100_000); + assert_eq!(gas.reservoir_remaining, 5_000); + assert_eq!(gas.gas_used, 96_000); + assert_eq!(gas.block_execution_gas(), 60_000); + } + + /// The floor binds the receipt figure and the block's execution gas, not the ledgers. + #[test] + fn test_floor_binds_receipt_and_block_execution_gas() { + let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000); + assert_eq!(gas.regular, 25_000); + assert_eq!(gas.floor, 45_000); + assert_eq!(gas.gas_used, 45_000); + assert_eq!(gas.block_execution_gas(), 45_000); + } + + /// Satin's halt set is op-revm's: an Ethereum halt converts in and back out. + #[test] + fn test_base_halt_reasons_convert_roundtrip() { + let eth_reason = EthHaltReason::OutOfGas(OutOfGasError::Basic); + let mega = MegaHaltReason::from(eth_reason.clone()); + assert_eq!(mega, OpHaltReason::Base(eth_reason.clone())); + assert_eq!(EthHaltReason::try_from(mega).unwrap(), eth_reason); + } + + /// A limit stop is not a halt: it is a revert whose output is `MegaLimitExceeded`, for every + /// dimension. + #[test] + fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { + for kind in [ + LimitKind::DataSize, + LimitKind::KVUpdate, + LimitKind::ComputeGas, + LimitKind::StateGrowth, + ] { + let stop = LimitCheck::ExceedsLimit { kind, limit: 100, used: 101, frame_local: false }; + let decoded = MegaLimitExceeded::abi_decode(&stop.revert_data()).unwrap(); + assert_eq!(LimitKind::from_u8(decoded.kind), Some(kind)); + assert_eq!(decoded.limit, 100); + } + } + + /// The one halt reason op-revm adds, a failed deposit, has no Ethereum counterpart. + #[test] + fn test_op_specific_halt_reason_does_not_convert_to_eth() { + let mega = MegaHaltReason::FailedDeposit; + assert_eq!(EthHaltReason::try_from(mega.clone()), Err(mega)); + } + + /// No halt reason of Satin's own exists: every one but the failed deposit is Ethereum's. + #[test] + fn test_all_mega_specific_variants_fail_eth_conversion() { + let reasons = [ + MegaHaltReason::Base(EthHaltReason::OutOfGas(OutOfGasError::Basic)), + MegaHaltReason::Base(EthHaltReason::OpcodeNotFound), + MegaHaltReason::Base(EthHaltReason::CallTooDeep), + MegaHaltReason::FailedDeposit, + ]; + let converted = + reasons.iter().filter(|r| EthHaltReason::try_from((*r).clone()).is_ok()).count(); + assert_eq!(converted, reasons.len() - 1, "only the failed deposit is OP-specific"); + } +} diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index f19f185ee..9b6f76cfc 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -24,6 +24,7 @@ mod types; pub use block::*; pub use evm::*; pub use external::*; +pub use limit::*; pub use types::*; /* Re-export of upstream crates, so consumers build against the exact versions used here */ diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 4e074c147..0a805a7fc 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -1,4 +1,186 @@ //! Resource limits of the Satin engine. //! -//! Empty until the observe-stage-commit layer and the abort protocol, the data-size limit, the -//! detention caps, and the state-gas limits and KV count land. +//! The common execution layer defines what a limit reports when it is crossed: the dimension +//! ([`LimitKind`]), the verdict of a check ([`LimitCheck`]) and the revert data a stopped frame +//! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension (the data-size limit, +//! detention, the state-growth and KV limits) fill these in. + +use alloy_primitives::Bytes; +use alloy_sol_types::SolError; + +alloy_sol_types::sol! { + /// The revert data of a frame a resource limit stopped. + /// + /// `kind` is the [`LimitKind`] discriminant and `limit` the limit that was crossed. A frame + /// can revert with the same bytes on its own; whether a limit stopped the transaction is + /// reported by the transaction outcome, not read off the output. + #[derive(Debug, PartialEq, Eq)] + error MegaLimitExceeded(uint8 kind, uint64 limit); +} + +/// A resource dimension a limit meters. +/// +/// The discriminants are the `kind` of [`MegaLimitExceeded`] and keep the values the legacy engine +/// encoded, so a contract that decodes the legacy revert data decodes Satin's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LimitKind { + /// Bytes of data a transaction produces; metered by the data-size limit. + DataSize, + /// Key-value updates; metered by the state-growth and KV limits. + KVUpdate, + /// Compute gas, the regular gas a transaction spends; capped by detention. + ComputeGas, + /// Net new state; metered by the state-growth and KV limits. + StateGrowth, +} + +impl LimitKind { + /// The `kind` of [`MegaLimitExceeded`]. + pub const fn as_u8(&self) -> u8 { + match self { + Self::DataSize => 0, + Self::KVUpdate => 1, + Self::ComputeGas => 2, + Self::StateGrowth => 3, + } + } + + /// The dimension a `kind` of [`MegaLimitExceeded`] names, if any. + pub const fn from_u8(kind: u8) -> Option { + match kind { + 0 => Some(Self::DataSize), + 1 => Some(Self::KVUpdate), + 2 => Some(Self::ComputeGas), + 3 => Some(Self::StateGrowth), + _ => None, + } + } +} + +/// The verdict of a limit check. +/// +/// A transaction-level exceed stops the transaction: the frame that crosses it reverts, the +/// transaction is latched and every frame above reverts in turn. A frame-local exceed (a frame +/// budget) reverts the frame alone and its caller resumes. `Exempt` is sticky for the +/// transaction: nothing it does is stopped by a limit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum LimitCheck { + /// Every limit holds. + #[default] + WithinLimit, + /// A limit was crossed. + ExceedsLimit { + /// The dimension crossed. + kind: LimitKind, + /// The limit crossed. + limit: u64, + /// The usage that crossed it. + used: u64, + /// Whether the limit is a frame budget rather than a transaction-level limit. + frame_local: bool, + }, + /// The transaction is exempt from metering. + Exempt, +} + +impl LimitCheck { + /// Whether a limit was crossed. `Exempt` is not. + #[inline] + pub const fn exceeded_limit(&self) -> bool { + matches!(self, Self::ExceedsLimit { .. }) + } + + /// Whether the check passed. `Exempt` is a state of its own, not a pass. + #[inline] + pub const fn within_limit(&self) -> bool { + matches!(self, Self::WithinLimit) + } + + /// Whether the transaction is exempt from metering. + #[inline] + pub const fn is_exempt(&self) -> bool { + matches!(self, Self::Exempt) + } + + /// Whether a frame budget, rather than a transaction-level limit, was crossed. + #[inline] + pub const fn is_frame_local(&self) -> bool { + matches!(self, Self::ExceedsLimit { frame_local: true, .. }) + } + + /// The [`MegaLimitExceeded`] revert data of a crossed limit; empty otherwise. + pub fn revert_data(&self) -> Bytes { + match self { + Self::ExceedsLimit { kind, limit, .. } => { + MegaLimitExceeded { kind: kind.as_u8(), limit: *limit }.abi_encode().into() + } + Self::WithinLimit | Self::Exempt => Bytes::new(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `Exempt` passes no predicate that would stop a frame, and has no revert data. + #[test] + fn test_limit_check_exempt_predicate_truth_table() { + let exempt = LimitCheck::Exempt; + assert!(!exempt.exceeded_limit()); + assert!(!exempt.within_limit()); + assert!(exempt.is_exempt()); + assert!(!exempt.is_frame_local()); + assert!(exempt.revert_data().is_empty()); + } + + /// `within_limit` follows the variant. + #[test] + fn test_within_limit_reflects_variant() { + assert!(LimitCheck::WithinLimit.within_limit()); + let exceeded = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 150, + frame_local: false, + }; + assert!(!exceeded.within_limit()); + assert!(exceeded.exceeded_limit()); + assert!(!exceeded.is_frame_local()); + } + + /// Every discriminant survives the round trip, and an unknown one maps to nothing. + #[test] + fn test_limit_kind_u8_roundtrip() { + for (kind, expected) in [ + (LimitKind::DataSize, 0), + (LimitKind::KVUpdate, 1), + (LimitKind::ComputeGas, 2), + (LimitKind::StateGrowth, 3), + ] { + assert_eq!(kind.as_u8(), expected, "{kind:?}"); + assert_eq!( + LimitKind::from_u8(kind.as_u8()), + Some(kind), + "round-trip failed for {kind:?}" + ); + } + assert_eq!(LimitKind::from_u8(4), None); + } + + /// The revert data is the ABI encoding of `MegaLimitExceeded(uint8,uint64)`. + #[test] + fn test_revert_data_encodes_mega_limit_exceeded() { + let check = LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 7, + used: 9, + frame_local: true, + }; + let data = check.revert_data(); + assert_eq!(&data[..4], MegaLimitExceeded::SELECTOR.as_slice()); + let decoded = MegaLimitExceeded::abi_decode(&data).unwrap(); + assert_eq!(decoded, MegaLimitExceeded { kind: 3, limit: 7 }); + assert_eq!(MegaLimitExceeded::SIGNATURE, "MegaLimitExceeded(uint8,uint64)"); + } +} diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs index 02858a09f..636adb107 100644 --- a/crates/mega-evm/src/types.rs +++ b/crates/mega-evm/src/types.rs @@ -1,7 +1,17 @@ //! Common type definitions of the Satin engine. //! -//! The result and error types are aliases of the OP ones for now; the common execution layer -//! decides the result and gas types the engine exposes when it lands. +//! These stay aliases of the OP types, because Satin adds nothing to them: +//! +//! - [`MegaTransaction`], [`MegaTxType`] and [`MegaTxEnvelope`]: Satin executes OP transactions. +//! - [`MegaHaltReason`]: Satin halts only where the EVM does. A resource limit stops a transaction +//! with a revert whose output is [`MegaLimitExceeded`](crate::MegaLimitExceeded), not with a +//! halt, so the halt set is op-revm's. +//! - [`MegaTransactionError`]: Satin validates transactions as op-revm does. +//! +//! What Satin does add has types of its own: the gas a transaction spent by ledger +//! ([`MegaGasUsage`](crate::MegaGasUsage)), the limit verdict and revert data +//! ([`LimitCheck`](crate::LimitCheck), [`MegaLimitExceeded`](crate::MegaLimitExceeded)) and the +//! block's counters ([`BlockGasCounters`](crate::BlockGasCounters)). /// `MegaETH` transaction as the EVM executes it. /// @@ -9,7 +19,9 @@ /// from signed transactions that the node's block executor needs. pub type MegaTransaction = alloy_op_evm::OpTx; -/// Why a transaction halted. +/// Why a transaction halted: an EVM halt, or a failed deposit. +/// +/// A resource limit does not halt a transaction; see the module documentation. pub type MegaHaltReason = op_revm::OpHaltReason; /// Transaction validation error, as the alloy-evm interface reports it. diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 41e91be62..2cd8a2606 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -26,7 +26,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| -| the common execution layer | 41 | 19 | 22 | 22 | 19 | 0 | +| the common execution layer | 34 | 19 | 15 | 19 | 15 | 0 | | the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | @@ -43,7 +43,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **771** | **626** | **145** | **431** | **312** | **28** | +| **Total** | **764** | **626** | **138** | **428** | **308** | **28** | ## Tests ported in place @@ -112,6 +112,16 @@ A scenario keeps the transaction of its test; the assertions on compute gas (not The halt reason of a static callee is still owed, not discharged: 6 of these rows asserted it, and a scenario cannot, because the harness compares what the transaction reports and the inner frame's halt reason is not part of that. It becomes assertable with the common execution layer, which defines the frame outcome, and inspector support, which reaches an inner frame as it ends; whichever lands first re-adds the assertions next to its own tests. +## Tests ported by the common execution layer + +These 7 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | +| `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | +| **Total** | | **7** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | @@ -212,7 +222,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/evm/host.rs` | 11 | keep 10 (the common execution layer · Host observation layer (D33) on the revm 40 journal); keep 1 (SALT pricing) | | `src/evm/mod.rs` | 5 | keep 3 (the pre-block system calls); keep 1 (the block executor); keep 1 (the common execution layer) | | `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | -| `src/evm/result.rs` | 4 | rewrite 4 (the common execution layer · D17/D48 (halt-reason set changes)) | | `src/evm/state.rs` | 1 | keep 1 (the block executor) | | `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | @@ -220,7 +229,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/limit/frame_limit.rs` | 4 | rewrite 4 (the common execution layer · data-size-only per-frame tracker) | | `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | | `src/limit/limit.rs` | 4 | keep 4 (history gas · D51) | -| `src/limit/mod.rs` | 3 | keep 3 (the common execution layer) | | `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/control.rs` | 8 | keep 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | | `src/system/deploy.rs` | 4 | keep 3 (system contract deployment); rewrite 1 (system contract deployment · single version) | diff --git a/crates/mega-evm/tests/_pending/src/evm/result.rs b/crates/mega-evm/tests/_pending/src/evm/result.rs deleted file mode 100644 index 865b08472..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/result.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/result.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/result.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use revm::context::result::OutOfGasError; - - #[test] - fn test_base_halt_reasons_convert_roundtrip() { - let eth_reason = EthHaltReason::OutOfGas(OutOfGasError::Basic); - let mega_from_eth = MegaHaltReason::from(eth_reason); - let mega_from_op = MegaHaltReason::from(OpHaltReason::Base(eth_reason)); - - assert_eq!(mega_from_eth, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(mega_from_op, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(EthHaltReason::try_from(mega_from_eth).unwrap(), eth_reason); - assert_eq!(EthHaltReason::try_from(mega_from_op).unwrap(), eth_reason); - } - - #[test] - fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { - let reason = MegaHaltReason::VolatileDataAccessOutOfGas { - access_type: VolatileDataAccess::ORACLE, - limit: 100, - actual: 101, - }; - - assert_eq!(EthHaltReason::try_from(reason.clone()), Err(reason)); - } - - #[test] - fn test_op_specific_halt_reason_does_not_convert_to_eth() { - let op_reason = OpHaltReason::FailedDeposit; - let mega = MegaHaltReason::from(op_reason.clone()); - assert_eq!(mega, MegaHaltReason::Base(op_reason)); - assert!(EthHaltReason::try_from(mega).is_err()); - } - - #[test] - fn test_all_mega_specific_variants_fail_eth_conversion() { - let variants: Vec = vec![ - MegaHaltReason::DataLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::KVUpdateLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::ComputeGasLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::StateGrowthLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::SystemTxInvalidCallee { callee: Address::ZERO }, - ]; - for variant in variants { - assert!( - EthHaltReason::try_from(variant).is_err(), - "mega-specific variant should not convert to EthHaltReason" - ); - } - } -} diff --git a/crates/mega-evm/tests/_pending/src/limit/mod.rs b/crates/mega-evm/tests/_pending/src/limit/mod.rs deleted file mode 100644 index 77cc96754..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/mod.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/mod.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/mod.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// Pins the predicate truth-table for the `Exempt` variant so a future change that flips one - /// predicate (e.g., reverting `exceeded_limit` to `!matches!(WithinLimit)`) is caught here - /// rather than silently re-enabling halts for exempt txs. - #[test] - fn test_limit_check_exempt_predicate_truth_table() { - let exempt = LimitCheck::Exempt; - assert!(!exempt.exceeded_limit()); - assert!(!exempt.within_limit()); - assert!(exempt.is_exempt()); - assert!(!exempt.is_frame_local()); - assert!(exempt.revert_data().is_empty()); - assert!(exempt.maybe_halt_reason().is_none()); - } - - /// `within_limit` must mirror the enum variant exactly, not return a constant. - #[test] - fn test_within_limit_reflects_variant() { - assert!(LimitCheck::WithinLimit.within_limit()); - let exceeded = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: 150, - frame_local: false, - }; - assert!(!exceeded.within_limit()); - } - - /// Every `LimitKind` discriminant must survive an `as_u8` -> `from_u8` round-trip, - /// and unknown discriminants must map to `None`. - #[test] - fn test_limit_kind_u8_roundtrip() { - for kind in [ - LimitKind::DataSize, - LimitKind::KVUpdate, - LimitKind::ComputeGas, - LimitKind::StateGrowth, - ] { - assert_eq!( - LimitKind::from_u8(kind.as_u8()), - Some(kind), - "round-trip failed for {kind:?}" - ); - } - assert_eq!(LimitKind::from_u8(4), None); - } -} From a09ae50fb2db33af333ce15c2688291b86d9ad1a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:19:53 +0800 Subject: [PATCH 056/201] feat: run Satin through MegaHandler and MegaEvm's own frame lifecycle --- crates/mega-evm/src/evm/execution.rs | 237 +++++++++++++++++++++++++++ crates/mega-evm/src/evm/mod.rs | 106 ++++++++---- 2 files changed, 311 insertions(+), 32 deletions(-) create mode 100644 crates/mega-evm/src/evm/execution.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs new file mode 100644 index 000000000..d95045e74 --- /dev/null +++ b/crates/mega-evm/src/evm/execution.rs @@ -0,0 +1,237 @@ +//! The Satin handler and the frame lifecycle of [`MegaEvm`]. +//! +//! [`MegaHandler`] runs a transaction through op-revm's [`OpHandler`] and overrides the phases +//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] and [`InspectorEvmTr`] itself, so the +//! frame lifecycle (`frame_init`, `frame_run`, `frame_return_result`) is `MegaETH`'s own. + +use op_revm::{ + handler::{IsTxError, OpHandler}, + OpHaltReason, OpTransactionError, +}; +use revm::{ + context::{result::FromStringError, ContextError, ContextTr, FrameStack}, + context_interface::cfg::gas::GasTracker, + handler::{ + evm::{ContextDbError, FrameInitResult, FrameTr}, + EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, + }, + inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, + interpreter::{interpreter::EthInterpreter, interpreter_action::FrameInit, InitialAndFloorGas}, + Database, Inspector, Journal, +}; + +use op_revm::precompiles::OpPrecompiles; + +use crate::{ExternalEnvTypes, MegaContext, MegaEvm, MegaInstructions}; + +/// The Satin handler. +/// +/// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. +#[derive(Debug)] +pub struct MegaHandler { + op: OpHandler, +} + +impl MegaHandler { + /// Creates a handler. + pub fn new() -> Self { + Self { op: OpHandler::new() } + } +} + +impl Default for MegaHandler { + fn default() -> Self { + Self::new() + } +} + +impl Handler for MegaHandler +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + EVM: EvmTr, Frame = FRAME>, + ERROR: EvmTrError + From + FromStringError + IsTxError, + FRAME: FrameTr, +{ + type Evm = EVM; + type Error = ERROR; + type HaltReason = OpHaltReason; + + fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { + self.op.validate_env(evm) + } + + fn validate_against_state_and_deduct_caller( + &self, + evm: &mut Self::Evm, + init_and_floor_gas: &mut InitialAndFloorGas, + ) -> Result<(), Self::Error> { + self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) + } + + fn last_frame_result( + &mut self, + evm: &mut Self::Evm, + frame_result: &mut FrameResult, + parent_gas: &mut GasTracker, + ) -> Result<(), Self::Error> { + self.op.last_frame_result(evm, frame_result, parent_gas) + } + + fn reimburse_caller( + &self, + evm: &mut Self::Evm, + exec_result: &mut FrameResult, + ) -> Result<(), Self::Error> { + self.op.reimburse_caller(evm, exec_result) + } + + fn refund( + &self, + evm: &mut Self::Evm, + exec_result: &mut FrameResult, + eip7702_refund: i64, + ) -> Result<(), Self::Error> { + self.op.refund(evm, exec_result, eip7702_refund) + } + + fn reward_beneficiary( + &self, + evm: &mut Self::Evm, + exec_result: &mut FrameResult, + ) -> Result<(), Self::Error> { + self.op.reward_beneficiary(evm, exec_result) + } + + fn execution_result( + &mut self, + evm: &mut Self::Evm, + result: FrameResult, + result_gas: revm::context::result::ResultGas, + ) -> Result, Self::Error> { + self.op.execution_result(evm, result, result_gas) + } + + fn catch_error( + &self, + evm: &mut Self::Evm, + error: Self::Error, + ) -> Result, Self::Error> { + self.op.catch_error(evm, error) + } +} + +impl InspectorHandler for MegaHandler> +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + MegaContext: ContextTr>, + Journal: JournalExt, + EVM: InspectorEvmTr< + Context = MegaContext, + Frame = EthFrame, + Inspector: Inspector, EthInterpreter>, + >, + // Implied by `EvmTrError`, but the `ContextTr>` bound above stops + // the compiler from normalizing the context's database type down to `DB`. + ERROR: EvmTrError + + From + + From> + + From + + FromStringError + + IsTxError, +{ + type IT = EthInterpreter; +} + +impl EvmTr for MegaEvm { + type Context = MegaContext; + type Instructions = MegaInstructions; + type Precompiles = OpPrecompiles; + type Frame = EthFrame; + + #[inline] + fn all( + &self, + ) -> (&Self::Context, &Self::Instructions, &Self::Precompiles, &FrameStack) { + self.inner.all() + } + + #[inline] + fn all_mut( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack, + ) { + self.inner.all_mut() + } + + #[inline] + fn frame_init( + &mut self, + frame_init: FrameInit, + ) -> Result, ContextDbError> { + self.inner.frame_init(frame_init) + } + + #[inline] + fn frame_run( + &mut self, + ) -> Result, ContextDbError> { + self.inner.frame_run() + } + + #[inline] + fn frame_return_result( + &mut self, + result: FrameResult, + ) -> Result, ContextDbError> { + self.inner.frame_return_result(result) + } +} + +impl InspectorEvmTr for MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + type Inspector = INSP; + + #[inline] + fn all_inspector( + &self, + ) -> ( + &Self::Context, + &Self::Instructions, + &Self::Precompiles, + &FrameStack, + &Self::Inspector, + ) { + let evm = &self.inner; + (&evm.ctx, &evm.instruction, &evm.precompiles, &evm.frame_stack, &evm.inspector) + } + + #[inline] + fn all_mut_inspector( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack, + &mut Self::Inspector, + ) { + let evm = &mut self.inner; + ( + &mut evm.ctx, + &mut evm.instruction, + &mut evm.precompiles, + &mut evm.frame_stack, + &mut evm.inspector, + ) + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index db3d5c9b7..a0bc40420 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,29 +1,37 @@ //! The Satin EVM. //! -//! [`MegaEvm`] wraps op-revm's [`OpEvm`] over a [`MegaContext`] configured for the Satin spec. -//! It adds no `MegaETH` behavior yet; SALT pricing, history gas, resource limits, detention and -//! the system contracts land on top of it. +//! [`MegaEvm`] runs transactions on a [`MegaContext`] configured for the Satin spec through +//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame lifecycle +//! itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level mechanisms +//! plug in. mod context; +mod execution; mod factory; mod result; mod spec; pub use context::*; +pub use execution::*; pub use factory::*; pub use result::*; pub use spec::*; use alloy_evm::EvmEnv; use alloy_op_evm::map_op_err; -use op_revm::{precompiles::OpPrecompiles, OpEvm, OpHaltReason, OpTransactionError}; +use op_revm::{precompiles::OpPrecompiles, OpHaltReason, OpTransactionError}; use revm::{ context::{ result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, - BlockEnv, CfgEnv, ContextTr, + BlockEnv, CfgEnv, ContextSetters, ContextTr, FrameStack, JournalTr, + }, + handler::{ + instructions::EthInstructions, system_call::SystemCallEvm, EthFrame, Handler, SystemCallTx, + }, + inspector::{ + InspectCommitEvm, InspectEvm, InspectSystemCallEvm, Inspector, InspectorHandler, + NoOpInspector, }, - handler::{instructions::EthInstructions, system_call::SystemCallEvm}, - inspector::{InspectCommitEvm, InspectEvm, InspectSystemCallEvm, Inspector, NoOpInspector}, interpreter::interpreter::EthInterpreter, primitives::{Address, Bytes}, state::EvmState, @@ -36,15 +44,20 @@ use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransaction pub(crate) type MegaInstructions = EthInstructions>; -/// The op-revm EVM a [`MegaEvm`] wraps. +/// The revm EVM a [`MegaEvm`] wraps. /// /// It runs op-revm's precompile set for the base spec until the Satin precompile set lands. -pub(crate) type MegaInnerEvm = - OpEvm, INSP, MegaInstructions, OpPrecompiles>; +pub(crate) type MegaInnerEvm = revm::context::Evm< + MegaContext, + INSP, + MegaInstructions, + OpPrecompiles, + EthFrame, +>; /// The Satin EVM. /// -/// Executes transactions through op-revm's handler on a [`MegaContext`]. It implements revm's +/// Executes transactions through [`MegaHandler`] on a [`MegaContext`]. It implements revm's /// execution traits ([`ExecuteEvm`], [`InspectEvm`], [`SystemCallEvm`] and their commit /// variants) and alloy-evm's [`Evm`](alloy_evm::Evm), which is what a node's block executor /// drives. @@ -58,7 +71,15 @@ pub struct MegaEvm MegaEvm { /// Creates an EVM over `ctx`, without an inspector. pub fn new(ctx: MegaContext) -> Self { - Self { inner: OpEvm::new(ctx, NoOpInspector), inspect: false } + let spec = ctx.cfg().spec; + let inner = revm::context::Evm { + ctx, + inspector: NoOpInspector, + instruction: EthInstructions::new_mainnet_with_spec(spec.into()), + precompiles: OpPrecompiles::new_with_spec(spec), + frame_stack: FrameStack::new_prealloc(8), + }; + Self { inner, inspect: false } } } @@ -71,12 +92,17 @@ impl MegaEvm { /// The execution context. pub const fn ctx(&self) -> &MegaContext { - &self.inner.0.ctx + &self.inner.ctx } /// The execution context, mutably. pub const fn ctx_mut(&mut self) -> &mut MegaContext { - &mut self.inner.0.ctx + &mut self.inner.ctx + } + + /// The inspector. + pub const fn inspector(&self) -> &INSP { + &self.inner.inspector } /// Whether alloy-evm's [`transact`](alloy_evm::Evm::transact) runs the inspector. @@ -84,35 +110,40 @@ impl MegaEvm { self.inspect } - /// Consumes the EVM and returns the op-revm EVM it wraps. + /// Consumes the EVM and returns the revm EVM it wraps. pub(crate) fn into_inner(self) -> MegaInnerEvm { self.inner } } +/// The error a [`MegaEvm`] reports through revm's execution traits. +pub type MegaEvmError = EVMError; + impl ExecuteEvm for MegaEvm { type ExecutionResult = ExecutionResult; type State = EvmState; - type Error = EVMError; + type Error = MegaEvmError; type Tx = MegaTransaction; type Block = BlockEnv; fn set_block(&mut self, block: Self::Block) { - self.inner.set_block(block); + self.inner.ctx.set_block(block); } fn transact_one(&mut self, tx: Self::Tx) -> Result { - self.inner.transact_one(tx) + self.inner.ctx.set_tx(tx); + MegaHandler::<_, Self::Error, _>::new().run(self) } fn finalize(&mut self) -> Self::State { - self.inner.finalize() + self.inner.ctx.journal_mut().finalize() } fn replay( &mut self, ) -> Result, Self::Error> { - self.inner.replay() + let result = MegaHandler::<_, Self::Error, _>::new().run(self)?; + Ok(ExecResultAndState::new(result, self.finalize())) } } @@ -120,7 +151,7 @@ impl ExecuteComm for MegaEvm { fn commit(&mut self, state: Self::State) { - self.inner.commit(state); + self.inner.ctx.db_mut().commit(state); } } @@ -133,11 +164,12 @@ where type Inspector = INSP; fn set_inspector(&mut self, inspector: Self::Inspector) { - self.inner.set_inspector(inspector); + self.inner.inspector = inspector; } fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { - self.inner.inspect_one_tx(tx) + self.inner.ctx.set_tx(tx); + MegaHandler::<_, Self::Error, _>::new().inspect_run(self) } } @@ -156,7 +188,12 @@ impl SystemCallEvm for MegaEvm Result { - self.inner.system_call_one_with_caller(caller, system_contract_address, data) + self.inner.ctx.set_tx(MegaTransaction::new_system_tx_with_caller( + caller, + system_contract_address, + data, + )); + MegaHandler::<_, Self::Error, _>::new().run_system_call(self) } } @@ -172,7 +209,12 @@ where system_contract_address: Address, data: Bytes, ) -> Result { - self.inner.inspect_one_system_call_with_caller(caller, system_contract_address, data) + self.inner.ctx.set_tx(MegaTransaction::new_system_tx_with_caller( + caller, + system_contract_address, + data, + )); + MegaHandler::<_, Self::Error, _>::new().inspect_run_system_call(self) } } @@ -213,9 +255,9 @@ where tx: Self::Tx, ) -> Result, Self::Error> { let result = if self.inspect { - InspectEvm::inspect_tx(&mut self.inner, tx) + InspectEvm::inspect_tx(self, tx) } else { - ExecuteEvm::transact(&mut self.inner, tx) + ExecuteEvm::transact(self, tx) }; result.map_err(map_op_err) } @@ -226,11 +268,11 @@ where contract: Address, data: Bytes, ) -> Result, Self::Error> { - self.inner.system_call_with_caller(caller, contract, data).map_err(map_op_err) + SystemCallEvm::system_call_with_caller(self, caller, contract, data).map_err(map_op_err) } fn finish(self) -> (Self::DB, EvmEnv) { - let (db, cfg_env, block_env) = self.into_inner().0.ctx.into_parts(); + let (db, cfg_env, block_env) = self.into_inner().ctx.into_parts(); (db, EvmEnv { cfg_env, block_env }) } @@ -239,12 +281,12 @@ where } fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { - let evm = &self.inner.0; + let evm = &self.inner; (evm.ctx.db(), &evm.inspector, &evm.precompiles) } fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { - let evm = &mut self.inner.0; + let evm = &mut self.inner; (evm.ctx.db_mut(), &mut evm.inspector, &mut evm.precompiles) } } @@ -297,7 +339,7 @@ mod tests { assert!(evm.transact_raw(tx(U256::ZERO)).unwrap().result.is_success()); let inner = evm.into_inner(); - assert_eq!(inner.0.ctx.spec(), MegaSpecId::SATIN); + assert_eq!(inner.ctx.spec(), MegaSpecId::SATIN); } #[test] From 2c14b73b933787d3fcbe2ef2391c2f52cdca74c0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:32:59 +0800 Subject: [PATCH 057/201] feat: stage Host observations and commit write records after the opcode --- crates/mega-evm/src/evm/context.rs | 100 +-- crates/mega-evm/src/evm/execution.rs | 207 +++++- crates/mega-evm/src/evm/host.rs | 609 ++++++++++++++++++ crates/mega-evm/src/evm/instructions.rs | 116 ++++ crates/mega-evm/src/evm/mod.rs | 5 +- crates/mega-evm/src/limit/frame_limit.rs | 375 +++++++++++ crates/mega-evm/src/limit/limit.rs | 188 ++++++ crates/mega-evm/src/limit/mod.rs | 79 +++ crates/mega-evm/src/limit/record.rs | 137 ++++ crates/mega-evm/tests/_pending/README.md | 28 +- .../tests/_pending/equivalence/evm_state.rs | 92 --- .../tests/_pending/equivalence/main.rs | 3 - .../tests/_pending/mini_rex/db_error.rs | 222 ------- .../mega-evm/tests/_pending/mini_rex/main.rs | 1 - .../_pending/rex4/eip7702_delegation_cycle.rs | 119 ---- .../rex5/frame_target_updated_dedup.rs | 255 -------- crates/mega-evm/tests/_pending/rex5/main.rs | 1 - .../_pending/rex6/create_frame_accounting.rs | 132 ---- .../rex6/self_transfer_account_dedup.rs | 195 ------ .../mega-evm/tests/_pending/src/evm/host.rs | 301 --------- .../tests/_pending/src/limit/frame_limit.rs | 127 ---- crates/mega-evm/tests/satin/common.rs | 59 ++ crates/mega-evm/tests/satin/db_error.rs | 101 +++ crates/mega-evm/tests/satin/main.rs | 4 + crates/mega-evm/tests/satin/state.rs | 113 ++++ crates/mega-evm/tests/satin/write_records.rs | 514 +++++++++++++++ 26 files changed, 2534 insertions(+), 1549 deletions(-) create mode 100644 crates/mega-evm/src/evm/host.rs create mode 100644 crates/mega-evm/src/evm/instructions.rs create mode 100644 crates/mega-evm/src/limit/frame_limit.rs create mode 100644 crates/mega-evm/src/limit/limit.rs create mode 100644 crates/mega-evm/src/limit/record.rs delete mode 100644 crates/mega-evm/tests/_pending/equivalence/evm_state.rs delete mode 100644 crates/mega-evm/tests/_pending/equivalence/main.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/db_error.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/frame_limit.rs create mode 100644 crates/mega-evm/tests/satin/common.rs create mode 100644 crates/mega-evm/tests/satin/db_error.rs create mode 100644 crates/mega-evm/tests/satin/state.rs create mode 100644 crates/mega-evm/tests/satin/write_records.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 6f84b10e2..4e334a65a 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -4,18 +4,13 @@ use delegate::delegate; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, - context_interface::{ - cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, - context::{SStoreResult, SelfDestructResult, StateLoad}, - host::LoadError, - journaled_state::{AccountInfoLoad, AccountLoad}, - }, - primitives::{Address, Bytes, Log, StorageKey, StorageValue, B256, U256}, + context_interface::cfg::GasParams, Database, Journal, }; use crate::{ - constants, EmptyExternalEnv, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, + constants, AdditionalLimit, EmptyExternalEnv, ExternalEnvTypes, ExternalEnvs, MegaSpecId, + MegaTransaction, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -30,13 +25,16 @@ pub(crate) type MegaInnerContext = /// [`MegaSpecId`] view that callers see and the [`OpSpecId`] view op-revm executes on. Both are /// written together, only through [`MegaContext::with_cfg`], so they cannot drift apart. /// -/// Every [`Host`](revm::interpreter::Host) method and every context accessor delegates to the -/// wrapped context; later changes override the ones `MegaETH` prices or meters differently. +/// Every context accessor delegates to the wrapped context, and so does every +/// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing +/// opcode did (see the `host` module). It also carries the common execution layer's state for the +/// running transaction ([`AdditionalLimit`]). #[derive(Debug)] pub struct MegaContext { - inner: MegaInnerContext, + pub(crate) inner: MegaInnerContext, cfg: CfgEnv, external_envs: ExternalEnvs, + pub(crate) additional_limit: AdditionalLimit, } impl MegaContext { @@ -55,7 +53,7 @@ impl MegaContext { ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); - Self { inner, cfg, external_envs } + Self { inner, cfg, external_envs, additional_limit: AdditionalLimit::default() } } /// Replaces the configuration. @@ -111,6 +109,16 @@ impl MegaContext { &self.external_envs } + /// The common execution layer's state for the running (or last) transaction. + pub const fn additional_limit(&self) -> &AdditionalLimit { + &self.additional_limit + } + + /// Prepares the common execution layer for a new transaction or system call. + pub(crate) fn on_new_tx(&mut self) { + self.additional_limit.reset(); + } + /// Consumes the context and returns the database, the configuration and the block. pub fn into_parts(self) -> (DB, CfgEnv, BlockEnv) { let Context { block, journaled_state, .. } = self.inner; @@ -185,77 +193,11 @@ impl ContextSetters for MegaContext revm::context_interface::Host - for MegaContext -{ - delegate! { - to self.inner { - fn basefee(&self) -> U256; - fn blob_gasprice(&self) -> U256; - fn gas_limit(&self) -> U256; - fn difficulty(&self) -> U256; - fn prevrandao(&self) -> Option; - fn block_number(&self) -> U256; - fn timestamp(&self) -> U256; - fn beneficiary(&self) -> Address; - fn slot_num(&self) -> U256; - fn chain_id(&self) -> U256; - fn effective_gas_price(&self) -> U256; - fn caller(&self) -> Address; - fn blob_hash(&self, number: usize) -> Option; - fn max_initcode_size(&self) -> usize; - fn gas_params(&self) -> &GasParams; - fn is_amsterdam_eip8037_enabled(&self) -> bool; - fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; - fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; - fn block_hash(&mut self, number: u64) -> Option; - fn selfdestruct( - &mut self, - address: Address, - target: Address, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn log(&mut self, log: Log); - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn sstore( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - ) -> Option>; - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn sload(&mut self, address: Address, key: StorageKey) -> Option>; - fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); - fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; - fn load_account_info_skip_cold_load( - &mut self, - address: Address, - load_code: bool, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn balance(&mut self, address: Address) -> Option>; - fn load_account_delegated(&mut self, address: Address) -> Option>; - fn load_account_code(&mut self, address: Address) -> Option>; - fn load_account_code_hash(&mut self, address: Address) -> Option>; - } - } -} - #[cfg(test)] mod tests { use super::*; use crate::{EthSpecId, SaltEnv, TestExternalEnvs}; + use alloy_primitives::U256; use core::convert::Infallible; use revm::database::EmptyDB; diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index d95045e74..30fb9ae5c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -4,24 +4,37 @@ //! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] and [`InspectorEvmTr`] itself, so the //! frame lifecycle (`frame_init`, `frame_run`, `frame_return_result`) is `MegaETH`'s own. +#[cfg(not(feature = "std"))] +use alloc as std; use op_revm::{ handler::{IsTxError, OpHandler}, OpHaltReason, OpTransactionError, }; +use std::vec::Vec; + +use op_revm::precompiles::OpPrecompiles; use revm::{ - context::{result::FromStringError, ContextError, ContextTr, FrameStack}, - context_interface::cfg::gas::GasTracker, + context::{ + result::FromStringError, transaction::TransactionType, Cfg, ContextError, ContextTr, + FrameStack, JournalTr, Transaction, + }, + context_interface::{cfg::gas::GasTracker, journaled_state::entry::JournalEntry}, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, - EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, + EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, + PreExecutionOutput, + }, + inspector::{ + handler::{frame_end, frame_start}, + InspectorEvmTr, InspectorHandler, JournalExt, }, - inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, - interpreter::{interpreter::EthInterpreter, interpreter_action::FrameInit, InitialAndFloorGas}, + interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, InitialAndFloorGas, + }, + primitives::Address, Database, Inspector, Journal, }; -use op_revm::precompiles::OpPrecompiles; - use crate::{ExternalEnvTypes, MegaContext, MegaEvm, MegaInstructions}; /// The Satin handler. @@ -57,6 +70,46 @@ where type Error = ERROR; type HaltReason = OpHaltReason; + /// Resets the common execution layer, then validates as revm does. + fn validate(&self, evm: &mut Self::Evm) -> Result { + evm.ctx_mut().on_new_tx(); + self.validate_env(evm)?; + let mut init_and_floor_gas = self.validate_initial_tx_gas(evm)?; + self.validate_against_state_and_deduct_caller(evm, &mut init_and_floor_gas)?; + Ok(init_and_floor_gas) + } + + /// Resets the common execution layer for a system call, then builds its gas as revm does. + fn system_call_gas(&self, evm: &mut Self::Evm) -> GasTracker { + evm.ctx_mut().on_new_tx(); + let mut gas = self.tx_gas(evm, &InitialAndFloorGas::new(0, 0)); + let cfg = evm.ctx_ref().cfg(); + if cfg.system_call_state_gas_margin_in_reservoir() && cfg.is_amsterdam_eip8037_enabled() { + let margin = gas + .remaining() + .saturating_sub(revm::handler::system_call::SYSTEM_CALL_REGULAR_GAS_LIMIT); + gas.set_remaining(gas.remaining() - margin); + gas.set_reservoir(gas.reservoir() + margin); + } + gas + } + + /// revm's pre-execution, then the write records of the EIP-7702 authorities it applied. + fn pre_execution( + &self, + evm: &mut Self::Evm, + gas: &mut GasTracker, + ) -> Result, Self::Error> { + self.load_accounts(evm)?; + let checkpoint = evm.ctx().journal_mut().checkpoint(); + let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + return Ok(None); + }; + record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) + } + fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { self.op.validate_env(evm) } @@ -69,13 +122,20 @@ where self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } + /// Settles the outermost frame: pops its lane, then settles its gas into the transaction's as + /// op-revm does (op-revm replaces revm's settlement, so revm's never runs here), and keeps + /// the history gas the transaction spent. fn last_frame_result( &mut self, evm: &mut Self::Evm, frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - self.op.last_frame_result(evm, frame_result, parent_gas) + evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); + self.op.last_frame_result(evm, frame_result, parent_gas)?; + let history = frame_result.gas().history_gas_spent().max(0) as u64; + evm.ctx_mut().additional_limit.set_history_gas_spent(history); + Ok(()) } fn reimburse_caller( @@ -169,12 +229,46 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - self.inner.frame_init(frame_init) + let ctx = &mut self.inner.ctx; + ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); + // The creator of a nested creation, to tell afterwards whether revm bumped its nonce. + let creator = match &frame_init.frame_input { + FrameInput::Create(inputs) if frame_init.depth > 0 => { + Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) + } + _ => None, + }; + let outcome = match self.inner.frame_init(frame_init)? { + ItemOrResult::Item(frame) => Ok(frame.interpreter.input.target_address), + ItemOrResult::Result(result) => Err(result), + }; + let ctx = &mut self.inner.ctx; + match outcome { + Ok(address) => { + ctx.additional_limit.set_frame_address(address); + Ok(ItemOrResult::Item(self.inner.frame_stack.get())) + } + Err(result) => { + if let Some((creator, nonce)) = creator { + if account_nonce(ctx, creator) == nonce { + ctx.additional_limit.creation_did_not_bump_nonce(); + } + } + Ok(ItemOrResult::Result(result)) + } + } } #[inline] @@ -184,11 +278,14 @@ impl EvmTr for MegaEvm Result, ContextDbError> { + self.inner.ctx.additional_limit.on_frame_return(&result); self.inner.frame_return_result(result) } } @@ -234,4 +331,96 @@ where &mut evm.inspector, ) } + + /// revm's inspected frame start, with the lanes kept aligned: a frame the inspector answers + /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it. + #[inline] + fn inspect_frame_init( + &mut self, + mut frame_init: FrameInit, + ) -> Result, ContextDbError> { + let (ctx, inspector) = self.ctx_inspector(); + if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + ctx.additional_limit.push_empty_frame(); + frame_end(ctx, inspector, &frame_init.frame_input, &mut output); + return Ok(ItemOrResult::Result(output)); + } + let frame_input = frame_init.frame_input.clone(); + let logs_i = ctx.journal().logs().len(); + if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { + let (ctx, inspector) = self.ctx_inspector(); + // Logs the frame journaled without running: the EIP-7708 transfer log, and the logs + // of a precompile. + if ctx.journal().logs().len() != logs_i { + inspect_logs(ctx, inspector, logs_i); + } + // Custom precompiles gather their logs outside the journal. + if let FrameResult::Call(outcome) = &output { + if outcome.was_precompile_called { + for log in outcome.precompile_call_logs.clone() { + inspector.log(ctx, log); + } + } + } + frame_end(ctx, inspector, &frame_input, &mut output); + return Ok(ItemOrResult::Result(output)); + } + let (ctx, inspector, frame) = self.ctx_inspector_frame(); + if ctx.journal().logs().len() != logs_i { + inspect_logs(ctx, inspector, logs_i); + } + inspector.initialize_interp(&mut frame.interpreter, ctx); + Ok(ItemOrResult::Item(frame)) + } +} + +/// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. +#[cold] +#[inline(never)] +fn inspect_logs( + ctx: &mut MegaContext, + inspector: &mut INSP, + logs_i: usize, +) where + INSP: Inspector, EthInterpreter>, +{ + let logs = ctx.journal().logs()[logs_i..].to_vec(); + for log in logs { + inspector.log(ctx, log); + } +} + +/// The nonce of an account the journal holds; zero for one it does not. +fn account_nonce( + ctx: &MegaContext, + address: Address, +) -> u64 { + ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// Records the account writes of the EIP-7702 authorities applied since journal entry +/// `journal_i`: each applied authorization bumps its authority's nonce once, so the distinct +/// authorities other than the sender are the accounts written. The sender's write is part of the +/// transaction body. +fn record_applied_authorities( + ctx: &mut MegaContext, + journal_i: usize, +) { + if ctx.tx().tx_type() != TransactionType::Eip7702 { + return; + } + let caller = ctx.tx().caller(); + let target = ctx.tx().kind().to().copied(); + let mut authorities: Vec
= ctx.journal_ref().journal()[journal_i..] + .iter() + .filter_map(|entry| match entry { + JournalEntry::NonceBump { address } if *address != caller => Some(*address), + _ => None, + }) + .collect(); + authorities.sort_unstable(); + authorities.dedup(); + let target_is_authority = + target.is_some_and(|target| authorities.binary_search(&target).is_ok()); + ctx.additional_limit.record_applied_authorities(authorities.len() as u64, target_is_authority); } diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs new file mode 100644 index 000000000..0af5854e4 --- /dev/null +++ b/crates/mega-evm/src/evm/host.rs @@ -0,0 +1,609 @@ +//! The Host of the Satin engine, and the journal reads that observe without warming. +//! +//! # The Host only observes +//! +//! revm hands the Host the facts of every state-writing opcode: an `SSTORE`'s original, present and +//! new values, a log's topics and data, a `SELFDESTRUCT`'s balance and beneficiary. The Host +//! stages them ([`AdditionalLimit::stage_record`](crate::AdditionalLimit)) and records nothing. +//! The opcode's wrapper commits the staged record after the opcode completed, and discards it when +//! the opcode failed. Recording in the Host would count a write the opcode's own failure then takes +//! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the +//! frame with the record already counted. +//! +//! Every other Host method delegates to op-revm's context. + +use alloy_primitives::map::Entry; +use delegate::delegate; +use revm::{ + context_interface::{ + cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::LoadError, + journaled_state::{AccountInfoLoad, AccountLoad}, + }, + primitives::{Address, Bytes, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256}, + state::{Account, EvmStorageSlot}, + Database, Journal, +}; + +use crate::{ExternalEnvTypes, MegaContext, StagedRecord}; + +impl revm::context_interface::Host + for MegaContext +{ + delegate! { + to self.inner { + fn basefee(&self) -> U256; + fn blob_gasprice(&self) -> U256; + fn gas_limit(&self) -> U256; + fn difficulty(&self) -> U256; + fn prevrandao(&self) -> Option; + fn block_number(&self) -> U256; + fn timestamp(&self) -> U256; + fn beneficiary(&self) -> Address; + fn slot_num(&self) -> U256; + fn chain_id(&self) -> U256; + fn effective_gas_price(&self) -> U256; + fn caller(&self) -> Address; + fn blob_hash(&self, number: usize) -> Option; + fn max_initcode_size(&self) -> usize; + fn gas_params(&self) -> &GasParams; + fn is_amsterdam_eip8037_enabled(&self) -> bool; + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; + fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; + fn block_hash(&mut self, number: u64) -> Option; + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn sload(&mut self, address: Address, key: StorageKey) -> Option>; + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn balance(&mut self, address: Address) -> Option>; + fn load_account_delegated(&mut self, address: Address) -> Option>; + fn load_account_code(&mut self, address: Address) -> Option>; + fn load_account_code_hash(&mut self, address: Address) -> Option>; + } + } + + /// Writes the slot and stages the write's values. + #[inline] + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + let load = self.inner.sstore_skip_cold_load(address, key, value, skip_cold_load)?; + self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); + Ok(load) + } + + /// Writes the slot and stages the write's values. + #[inline] + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Option> { + let load = self.inner.sstore(address, key, value)?; + self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); + Some(load) + } + + /// Stages the log's topic count and data length, then appends it. + #[inline] + fn log(&mut self, log: Log) { + self.additional_limit.stage_record(StagedRecord::Log { + topics: log.topics().len() as u8, + data_len: log.data.data.len() as u64, + }); + self.inner.log(log); + } + + /// Destructs the account and stages whether value moved and where to. + #[inline] + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + let load = self.inner.selfdestruct(address, target, skip_cold_load)?; + self.additional_limit.stage_record(StagedRecord::SelfDestruct { + had_value: load.data.had_value, + target_exists: load.data.target_exists, + to_other_account: target != address, + }); + Ok(load) + } +} + +/// Journal reads that observe an account or a slot without warming it. +/// +/// A read loads what the journal does not hold yet into it, so the returned state and a +/// stateless witness carry it, and marks it cold, so it neither enters the EIP-2929 access list +/// nor leaves a journal entry. Execution that later touches the same account or slot pays for it +/// as if the read never happened. +pub trait JournalInspectTr { + /// The database error. + type DBError; + + /// The account at `address`, without following an EIP-7702 delegation. + /// + /// With `load_code`, the code of an account the database served without it is loaded. An + /// account the journal already holds always has its code loaded. + fn inspect_account( + &mut self, + address: Address, + load_code: bool, + ) -> Result<&mut Account, Self::DBError>; + + /// The code hash of the account at `address`. Never loads the code, so an occupancy check + /// needs only the account in a witness, not its bytecode. + fn inspect_account_code_hash(&mut self, address: Address) -> Result; + + /// The slot `key` of the account at `address`, which is always the account's own storage (an + /// EIP-7702 delegation does not move it). A slot of an account created in this transaction + /// is zero without a database read. + fn inspect_storage( + &mut self, + address: Address, + key: StorageKey, + ) -> Result<&EvmStorageSlot, Self::DBError>; +} + +impl JournalInspectTr for Journal { + type DBError = DB::Error; + + fn inspect_account( + &mut self, + address: Address, + load_code: bool, + ) -> Result<&mut Account, DB::Error> { + let transaction_id = self.transaction_id; + match self.inner.state.entry(address) { + Entry::Occupied(entry) => { + let account = entry.into_mut(); + if account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { + account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); + } + Ok(account) + } + Entry::Vacant(entry) => { + let mut account = self + .database + .basic(address)? + .map(Account::from) + .unwrap_or_else(|| Account::new_not_existing(transaction_id)); + if load_code && + account.info.code_hash != KECCAK_EMPTY && + account.info.code.is_none() + { + account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); + } + account.mark_cold(); + Ok(entry.insert(account)) + } + } + } + + fn inspect_account_code_hash(&mut self, address: Address) -> Result { + let transaction_id = self.transaction_id; + match self.inner.state.entry(address) { + Entry::Occupied(entry) => Ok(entry.get().info.code_hash), + Entry::Vacant(entry) => { + let mut account = self + .database + .basic(address)? + .map(Account::from) + .unwrap_or_else(|| Account::new_not_existing(transaction_id)); + account.mark_cold(); + Ok(entry.insert(account).info.code_hash) + } + } + } + + fn inspect_storage( + &mut self, + address: Address, + key: StorageKey, + ) -> Result<&EvmStorageSlot, DB::Error> { + let transaction_id = self.transaction_id; + let is_newly_created = self.inspect_account(address, true)?.is_created(); + let account = self.inner.state.get_mut(&address).expect("inspected above"); + match account.storage.entry(key) { + Entry::Occupied(entry) => Ok(entry.into_mut()), + Entry::Vacant(entry) => { + let value = if is_newly_created { + U256::ZERO + } else { + self.database.storage(address, key)? + }; + let mut slot = EvmStorageSlot::new(value, transaction_id); + slot.mark_cold(); + Ok(entry.insert(slot)) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, keccak256}; + use core::cell::Cell; + use revm::{ + context::JournalTr, + primitives::HashMap, + state::{AccountInfo, Bytecode}, + }; + + /// Minimal `revm::Database` implementation that mimics the production + /// `reth`-style `StateProviderDatabase` contract: `basic()` returns + /// `AccountInfo { code: None, code_hash: }` for accounts with + /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via + /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — + /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache + /// miss against it would always see the code already hydrated. + #[derive(Default)] + struct LazyCodeDatabase { + accounts: HashMap, + codes: HashMap, + storage_calls: Cell, + } + + impl LazyCodeDatabase { + fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { + let code = Bytecode::new_raw(bytecode); + let code_hash = code.hash_slow(); + self.accounts + .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); + self.codes.insert(code_hash, code); + self + } + + fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { + let code = Bytecode::new_eip7702(delegate); + let code_hash = code.hash_slow(); + self.accounts + .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); + self.codes.insert(code_hash, code); + self + } + + fn storage_calls(&self) -> usize { + self.storage_calls.get() + } + } + + impl revm::Database for LazyCodeDatabase { + type Error = core::convert::Infallible; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without + // populating `code`, even when the account has on-chain bytecode. + Ok(self.accounts.get(&address).cloned()) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) + } + + fn storage(&mut self, _address: Address, _index: U256) -> Result { + self.storage_calls.set(self.storage_calls.get() + 1); + Ok(U256::ZERO) + } + + fn block_hash(&mut self, _number: u64) -> Result { + Ok(B256::ZERO) + } + } + + /// `inspect_account(addr, false)` must not hydrate `info.code` on the vacant + /// branch — callers that need it pass `load_code = true`. + #[test] + fn test_inspect_account_vacant_path_does_not_hydrate_code() { + const ADDR: Address = address!("00000000000000000000000000000000000000aa"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); // PUSH1 1 PUSH1 1 ADD + let expected_hash = keccak256(&bytecode); + + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let account = journal.inspect_account(ADDR, false).expect("inspect_account must succeed"); + + assert_eq!( + account.info.code_hash, expected_hash, + "code_hash must propagate from the database's `basic()` result", + ); + assert!( + account.info.code.is_none(), + "`load_code = false` must leave `info.code` as-is on the vacant branch", + ); + } + + /// `inspect_account(addr, true)` hydrates `info.code` from `code_by_hash` on + /// first cold inspection against a lazy-code database. + #[test] + fn test_inspect_account_with_load_code_hydrates_lazy_bytecode_on_first_touch() { + const ADDR: Address = address!("00000000000000000000000000000000000000aa"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); + let mut journal = Journal::new(db); + + let account = journal + .inspect_account(ADDR, true) + .expect("inspect_account must succeed on first cold-touch"); + let hydrated = account + .info + .code + .as_ref() + .expect("`load_code = true` must populate `info.code` from code_by_hash"); + assert_eq!( + hydrated.original_bytes().as_ref(), + bytecode.as_ref(), + "hydrated bytecode must match what `code_by_hash` would return", + ); + } + + /// The occupied-branch hydration must keep firing — a second `inspect_account` + /// against the same lazy-DB address must observe hydrated `info.code` even with + /// `load_code = false`. + #[test] + fn test_inspect_account_occupied_branch_hydrates_on_second_inspection() { + const ADDR: Address = address!("00000000000000000000000000000000000000bb"); + let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let first_code_hash = journal + .inspect_account(ADDR, false) + .expect("first inspection must succeed") + .info + .code_hash; + let second = journal.inspect_account(ADDR, false).expect("second inspection must succeed"); + + assert_eq!( + second.info.code_hash, first_code_hash, + "code_hash must be identical across cache miss and cache hit", + ); + assert!( + second.info.code.is_some(), + "second inspection must observe the hydrated code via the occupied-branch \ + `code_by_hash` load", + ); + } + + /// `inspect_account(addr, true)` must short-circuit on EOAs — the `code_hash != + /// KECCAK_EMPTY` guard keeps `code_by_hash` off the hot path. + #[test] + fn test_inspect_account_with_load_code_leaves_eoa_code_empty() { + const EOA: Address = address!("00000000000000000000000000000000000000cc"); + + let mut db = LazyCodeDatabase::default(); + db.accounts.insert( + EOA, + AccountInfo { + balance: U256::from(1_000_000u64), + nonce: 5, + code_hash: KECCAK_EMPTY, + code: None, + ..Default::default() + }, + ); + let mut journal = Journal::new(db); + + let account = journal + .inspect_account(EOA, true) + .expect("inspect_account must succeed and be a no-op on EOAs"); + assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); + assert!( + account.info.code.is_none(), + "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ + `code_by_hash` off the hot path for accounts without on-chain code", + ); + } + + /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate + /// `info.code` — on either branch. In particular the occupied branch must not fall through to + /// `code_by_hash` the way `inspect_account(.., false)` does (see + /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets an + /// occupancy check decide on the hash alone, without demanding an already-warmed occupied + /// address's bytecode in a stateless witness carrying only its proof. + #[test] + fn test_inspect_account_code_hash_never_hydrates_code() { + const ADDR: Address = address!("00000000000000000000000000000000000000dd"); + let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST + let expected_hash = keccak256(&bytecode); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + // Vacant cache-miss: returns the hash from `basic()` without hydrating code. + let vacant_hash = + journal.inspect_account_code_hash(ADDR).expect("vacant read must succeed"); + assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); + assert!( + journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), + "vacant branch must not hydrate info.code", + ); + + // The address is now resident with `code == None`. `inspect_account` would hydrate on this + // occupied branch; `inspect_account_code_hash` must not. + let occupied_hash = + journal.inspect_account_code_hash(ADDR).expect("occupied read must succeed"); + assert_eq!( + occupied_hash, expected_hash, + "occupied branch must return the cached code_hash" + ); + assert!( + journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), + "inspect_account_code_hash must NOT hydrate info.code on the occupied branch", + ); + } + + /// Pins the `LazyCodeDatabase` fixture's contract against the production + /// `revm::Database` shape it is modeling: `basic()` returns + /// `code: None` for known accounts, `None` for unknown addresses; + /// `code_by_hash()` falls back to empty bytecode for an unknown hash; + /// `storage()` and `block_hash()` are inert stubs (no tests exercise them via + /// `inspect_account`, but they must remain wired so the fixture is a complete + /// `revm::Database`). If the fixture ever drifts (e.g. someone "helpfully" + /// makes `basic()` eagerly populate `code` like `MemoryDatabase` does), the + /// inspect-account tests above silently lose their load-bearing property — + /// this test fails fast in that case. + #[test] + fn test_lazy_code_database_fixture_pins_reth_style_contract() { + const KNOWN: Address = address!("00000000000000000000000000000000000000ee"); + let bytecode = Bytes::from_static(&[0x00]); + let mut db = LazyCodeDatabase::default().with_account_code(KNOWN, bytecode); + + let known = db.basic(KNOWN).unwrap().expect("known account must resolve"); + assert!( + known.code.is_none(), + "LazyCodeDatabase::basic must NOT pre-populate code — that is the \ + behavior `inspect_account` is being tested against", + ); + assert!( + db.basic(Address::ZERO).unwrap().is_none(), + "unknown address must return None from basic()", + ); + + let unknown_hash = keccak256([0xffu8]); + assert_eq!( + db.code_by_hash(unknown_hash).unwrap().original_bytes().len(), + 0, + "unknown code_hash must fall back to empty bytecode", + ); + + assert_eq!(db.storage(KNOWN, U256::ZERO).unwrap(), U256::ZERO); + assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); + } + + #[test] + fn test_inspect_storage_slot_hit_returns_existing_value() { + const ADDR: Address = address!("00000000000000000000000000000000000000bb"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let key = U256::from(3); + let expected_value = U256::from(42); + { + let tid = journal.transaction_id; + let account = journal.inspect_account(ADDR, false).unwrap(); + let mut slot = EvmStorageSlot::new(expected_value, tid); + slot.mark_cold(); + account.storage.insert(key, slot); + } + + let slot = journal + .inspect_storage(ADDR, key) + .expect("inspect_storage must succeed on existing slot"); + + assert_eq!( + slot.present_value, expected_value, + "a slot hit must return the pre-seeded value" + ); + assert!(slot.is_cold, "inspected slot must remain cold"); + } + + #[test] + fn test_inspect_storage_slot_miss_inserts_and_returns_db_value() { + const ADDR: Address = address!("00000000000000000000000000000000000000cc"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + let key = U256::from(7); + + let slot = journal + .inspect_storage(ADDR, key) + .expect("inspect_storage must succeed on absent slot"); + + assert_eq!( + slot.present_value, + U256::ZERO, + "absent slot on non-created account must return ZERO from database" + ); + assert!(slot.is_cold, "newly inserted slot must be marked cold"); + + let calls_after_first = journal.database.storage_calls(); + let slot2 = + journal.inspect_storage(ADDR, key).expect("second inspect_storage must succeed"); + + assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); + assert_eq!( + journal.database.storage_calls(), + calls_after_first, + "second inspect_storage on the same slot must hit the cache, not the DB", + ); + } + + #[test] + fn test_inspect_storage_newly_created_short_circuits_db() { + const ADDR: Address = address!("00000000000000000000000000000000000000dd"); + let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); + let mut journal = Journal::new(db); + + { + let account = journal.inspect_account(ADDR, false).unwrap(); + account.mark_created(); + } + + let key = U256::from(1); + + let slot = journal + .inspect_storage(ADDR, key) + .expect("inspect_storage must succeed on newly-created account"); + + assert_eq!( + slot.present_value, + U256::ZERO, + "newly-created account must return ZERO without querying database" + ); + assert!(slot.is_cold, "slot must be marked cold"); + } + + #[test] + fn test_inspect_storage_ignores_eip7702_delegation() { + const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); + const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); + let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); + let db = LazyCodeDatabase::default() + .with_eip7702_delegation(DELEGATOR, DELEGATE) + .with_account_code(DELEGATE, delegate_code); + let mut journal = Journal::new(db); + + let key = U256::from(2); + let expected = U256::from(99); + { + let tid = journal.transaction_id; + let account = journal.inspect_account(DELEGATOR, false).unwrap(); + let mut slot = EvmStorageSlot::new(expected, tid); + slot.mark_cold(); + account.storage.insert(key, slot); + } + + let slot = journal + .inspect_storage(DELEGATOR, key) + .expect("inspect_storage must succeed for a delegator"); + + assert_eq!( + slot.present_value, expected, + "storage is read from the delegator (original address), not the delegate" + ); + } +} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs new file mode 100644 index 000000000..8269e692b --- /dev/null +++ b/crates/mega-evm/src/evm/instructions.rs @@ -0,0 +1,116 @@ +//! The instruction table of the Satin engine. +//! +//! Every opcode runs revm's own instruction, except the three that write state the resource +//! limits count: `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT`. Each of those runs in a wrapper +//! that commits what the Host staged for it after the opcode completed: +//! +//! 1. discard any record staged before the opcode (nothing may commit it for this one); +//! 2. run revm's instruction, whose Host call stages the record; +//! 3. commit the record if the opcode completed, discard it if the opcode failed. +//! +//! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is +//! unchanged. + +use revm::{ + bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, + handler::instructions::EthInstructions, + interpreter::{ + instructions::host, interpreter::EthInterpreter, Instruction, InstructionContext, + InstructionExecResult, + }, + primitives::hardfork::SpecId, + Database, +}; + +use crate::{ExternalEnvTypes, MegaContext}; + +use super::MegaInstructions; + +/// The context an instruction of the Satin engine runs with. +type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; + +/// An instruction of the Satin engine. +type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; + +/// The Satin instruction table: revm's for the base spec, with `SSTORE`, `LOG0`..`LOG4` and +/// `SELFDESTRUCT` wrapped. +pub(crate) fn mega_instructions( + spec: SpecId, +) -> MegaInstructions { + let mut instructions = EthInstructions::new_mainnet_with_spec(spec); + let wrappers: [(u8, InstructionFn); 7] = [ + (SSTORE, sstore::), + (LOG0, log::<0, DB, ExtEnvs>), + (LOG1, log::<1, DB, ExtEnvs>), + (LOG2, log::<2, DB, ExtEnvs>), + (LOG3, log::<3, DB, ExtEnvs>), + (LOG4, log::<4, DB, ExtEnvs>), + (SELFDESTRUCT, selfdestruct::), + ]; + for (opcode, wrapper) in wrappers { + let static_gas = instructions.gas_table()[opcode as usize]; + instructions.insert_instruction(opcode, Instruction::new(wrapper), static_gas); + } + instructions +} + +/// Runs `inner` and commits the record its Host call staged once it completed. +/// +/// An opcode completes when it returns `Ok` or stops the frame successfully (`SELFDESTRUCT` +/// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the +/// staged write back with it. +#[inline(always)] +fn commit_after( + context: Ctx<'_, DB, ExtEnvs>, + inner: InstructionFn, +) -> InstructionExecResult { + let InstructionContext { interpreter, host } = context; + host.additional_limit.discard_stale_record(); + let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + let completed = match result { + Ok(()) => true, + Err(result) => result.is_ok(), + }; + if completed { + host.additional_limit.commit_staged_record(); + } else { + host.additional_limit.discard_staged_record(); + } + result +} + +/// `SSTORE`, committing the slot's write record. +fn sstore( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::sstore) +} + +/// `LOG0`..`LOG4`, committing the log's bytes. +fn log( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::log::>) +} + +/// `SELFDESTRUCT`, committing the beneficiary's write record. +fn selfdestruct( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::selfdestruct) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use revm::interpreter::instructions::gas_table_spec; + + /// The wrappers keep the static gas revm charges for their opcodes: the whole table is revm's. + #[test] + fn test_wrappers_keep_the_static_gas_table() { + let mega = mega_instructions::(SpecId::OSAKA); + assert_eq!(mega.gas_table(), &gas_table_spec(SpecId::OSAKA)); + assert_eq!(mega.spec, SpecId::OSAKA); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index a0bc40420..70e120d68 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -8,12 +8,15 @@ mod context; mod execution; mod factory; +mod host; +mod instructions; mod result; mod spec; pub use context::*; pub use execution::*; pub use factory::*; +pub use host::*; pub use result::*; pub use spec::*; @@ -75,7 +78,7 @@ impl MegaEvm, + /// Whether a write to the frame's own account is already counted, so a value transfer or a + /// creation from the frame does not count it again. + pub(crate) account_recorded: bool, + /// Whether this lane holds the record of its caller's account, made when the frame started + /// (a value transfer's sender, a creation's creator). Its failure discards that record, so the + /// caller's account is no longer recorded either. + pub(crate) holds_caller_record: bool, + /// Whether the caller's record on this lane is a creator's nonce, which survives the + /// creation's failure once the nonce was bumped. + pub(crate) creator_record: bool, + /// The most data-size bytes the frame may keep; `u64::MAX` when it has no budget. + pub(crate) budget: u64, +} + +impl Lane { + /// A lane for a frame running as `address`. + pub(crate) const fn new(address: Option
, account_recorded: bool, budget: u64) -> Self { + Self { + used: LimitUsage::ZERO, + refund: LimitUsage::ZERO, + address, + account_recorded, + holds_caller_record: false, + creator_record: false, + budget, + } + } + + /// A lane for a frame that does not run: a result built without an interpreter. + pub(crate) const fn empty() -> Self { + Self::new(None, false, u64::MAX) + } +} + +/// The lanes of the running transaction. +#[derive(Clone, Debug, Default)] +pub(crate) struct FrameLimitTracker { + /// What the transaction counted outside any running frame, and what the outermost frame kept. + tx_used: LimitUsage, + /// What the outermost frame kept of its refunds. + tx_refund: LimitUsage, + /// One lane per frame on the call stack, the running frame last. + lanes: Vec, + /// `tx_used` plus every lane's `used`. + total_used: LimitUsage, + /// `tx_refund` plus every lane's `refund`. + total_refund: LimitUsage, +} + +impl FrameLimitTracker { + /// Clears the tracker for a new transaction, keeping its allocation. + pub(crate) fn reset(&mut self) { + self.tx_used = LimitUsage::ZERO; + self.tx_refund = LimitUsage::ZERO; + self.lanes.clear(); + self.total_used = LimitUsage::ZERO; + self.total_refund = LimitUsage::ZERO; + } + + /// The number of lanes, which is the number of frames on the call stack. + pub(crate) fn depth(&self) -> usize { + self.lanes.len() + } + + /// What the transaction keeps if every running frame succeeds. + pub(crate) const fn net(&self) -> LimitUsage { + self.total_used.saturating_sub(self.total_refund) + } + + /// The running frame's lane. + pub(crate) fn current(&self) -> Option<&Lane> { + self.lanes.last() + } + + /// The running frame's lane, mutably. + pub(crate) fn current_mut(&mut self) -> Option<&mut Lane> { + self.lanes.last_mut() + } + + /// Pushes the lane of a frame that starts. + pub(crate) fn push(&mut self, lane: Lane) { + self.total_used = self.total_used.saturating_add(lane.used); + self.total_refund = self.total_refund.saturating_add(lane.refund); + self.lanes.push(lane); + } + + /// Counts `usage` on the running frame's lane, or on the transaction's outside any frame. + pub(crate) fn record(&mut self, usage: LimitUsage) { + match self.lanes.last_mut() { + Some(lane) => lane.used = lane.used.saturating_add(usage), + None => self.tx_used = self.tx_used.saturating_add(usage), + } + self.total_used = self.total_used.saturating_add(usage); + } + + /// Takes `usage` back on the running frame's lane. Outside any frame nothing is taken back. + pub(crate) fn refund(&mut self, usage: LimitUsage) { + if let Some(lane) = self.lanes.last_mut() { + lane.refund = lane.refund.saturating_add(usage); + self.total_refund = self.total_refund.saturating_add(usage); + } + } + + /// Records the running frame's caller's account on the running frame's lane, unless the + /// caller's lane already counts it. A `creator` record is a creation's nonce. + /// + /// Must run right after the running frame's lane was pushed, with the caller's lane below it. + pub(crate) fn record_caller(&mut self, creator: bool) { + let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; + if caller.account_recorded { + return; + } + caller.account_recorded = true; + lane.holds_caller_record = true; + lane.creator_record = creator; + lane.used = lane.used.saturating_add(WRITE_RECORD); + self.total_used = self.total_used.saturating_add(WRITE_RECORD); + } + + /// Drops the caller's record from the running frame's lane: the frame failed before the + /// write it stands for happened (a creation that did not bump the creator's nonce). + pub(crate) fn drop_caller_record(&mut self) { + let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; + if !lane.holds_caller_record { + return; + } + caller.account_recorded = false; + lane.holds_caller_record = false; + lane.creator_record = false; + lane.used = lane.used.saturating_sub(WRITE_RECORD); + self.total_used = self.total_used.saturating_sub(WRITE_RECORD); + } + + /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or + /// the transaction's), a failure discards it. + /// + /// A creator's record outlives the creation's failure; any other record of the caller dies + /// with it, and the caller's account stops counting as recorded. + pub(crate) fn pop(&mut self, success: bool) -> Option { + let lane = self.lanes.pop()?; + if success { + match self.lanes.last_mut() { + Some(caller) => { + caller.used = caller.used.saturating_add(lane.used); + caller.refund = caller.refund.saturating_add(lane.refund); + if lane.address.is_some() && lane.address == caller.address { + caller.account_recorded |= lane.account_recorded; + } + } + None => { + self.tx_used = self.tx_used.saturating_add(lane.used); + self.tx_refund = self.tx_refund.saturating_add(lane.refund); + } + } + return Some(lane); + } + self.total_used = self.total_used.saturating_sub(lane.used); + self.total_refund = self.total_refund.saturating_sub(lane.refund); + if let Some(caller) = self.lanes.last_mut() { + if lane.creator_record { + caller.used = caller.used.saturating_add(WRITE_RECORD); + self.total_used = self.total_used.saturating_add(WRITE_RECORD); + } else if lane.holds_caller_record { + caller.account_recorded = false; + } + } + Some(lane) + } + + /// [`net`](Self::net) recomputed from the lanes, for checking the cache. + #[cfg(test)] + pub(crate) fn net_uncached(&self) -> LimitUsage { + let mut used = self.tx_used; + let mut refund = self.tx_refund; + for lane in &self.lanes { + used = used.saturating_add(lane.used); + refund = refund.saturating_add(lane.refund); + } + used.saturating_sub(refund) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::address; + + const ADDR: Address = address!("0000000000000000000000000000000000001234"); + + const fn bytes(data_size: u64) -> LimitUsage { + LimitUsage { data_size, write_records: 0 } + } + + /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. + #[test] + fn test_set_created_address_empty_stack_is_noop() { + let mut t = FrameLimitTracker::default(); + t.record_caller(true); + assert_eq!(t.net(), LimitUsage::ZERO); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.record_caller(true); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.current().unwrap().holds_caller_record); + } + + /// A frame's caller is recorded once per caller frame: a second child finds it recorded. + #[test] + fn test_set_created_address_duplicate_panics() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + assert!(t.pop(true).is_some()); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); + assert_eq!(t.net(), WRITE_RECORD); + } + + /// The cached totals match the lanes after every push, record, refund and pop. + #[test] + fn test_net_usage_cache_matches_uncached() { + let mut t = FrameLimitTracker::default(); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), LimitUsage::ZERO); + + // Outside any frame, usage goes to the transaction and nothing is taken back. + t.record(bytes(100)); + t.refund(bytes(50)); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(100)); + + // Frame 1. + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.record(bytes(30)); + t.refund(bytes(10)); + assert_eq!(t.net(), t.net_uncached()); + + // Frame 2, nested. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(15)); + t.refund(bytes(3)); + assert_eq!(t.net(), t.net_uncached()); + + // Frame 3 fails: its usage and refund leave the totals. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(11)); + t.refund(bytes(2)); + let before_revert = t.net(); + let popped = t.pop(false).expect("frame 3 popped"); + assert_eq!((popped.used, popped.refund), (bytes(11), bytes(2))); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(before_revert.data_size - 9)); + + // Frame 3 again, succeeding: merging moves usage, the totals do not change. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(6)); + t.refund(bytes(1)); + let before_success = t.net(); + t.pop(true); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), before_success); + + // Frame 2 succeeds into frame 1; frame 1 fails. + t.pop(true); + assert_eq!(t.net(), t.net_uncached()); + let frame_1 = t.pop(false).expect("frame 1 popped"); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(100), "only the transaction's own usage is left"); + assert_eq!(frame_1.used.saturating_sub(frame_1.refund), bytes(30 + 15 + 6 - 10 - 3 - 1)); + + t.reset(); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.depth(), 0); + } + + /// A refund larger than the usage clamps the net at zero. + #[test] + fn test_net_usage_saturates_when_refund_exceeds_used() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(10)); + t.refund(bytes(100)); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + t.pop(true); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A value transfer's sender record dies with the child that failed, and the caller can be + /// recorded again; a creator's record survives the creation's failure. + #[test] + fn test_failed_child_discards_sender_record_but_keeps_creator_record() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(false); + t.record(WRITE_RECORD); + t.pop(false); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.current().unwrap().account_recorded, "the sender record died with the child"); + + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + t.record(WRITE_RECORD); + t.pop(false); + assert_eq!(t.net(), WRITE_RECORD, "the creator's nonce outlives the creation"); + assert!(t.current().unwrap().account_recorded); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A creation that fails before bumping the nonce takes the creator record back. + #[test] + fn test_drop_caller_record_rearms_the_caller() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + t.drop_caller_record(); + t.drop_caller_record(); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.lanes[0].account_recorded); + t.pop(false); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A child running as its caller's account hands its record flag back on success. + #[test] + fn test_same_account_child_merges_the_recorded_flag() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(Some(ADDR), true, u64::MAX)); + t.pop(true); + assert!(t.current().unwrap().account_recorded); + + let other = address!("0000000000000000000000000000000000005678"); + t.push(Lane::new(Some(other), false, u64::MAX)); + t.push(Lane::new(Some(other), false, u64::MAX)); + t.current_mut().unwrap().account_recorded = true; + t.pop(false); + assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); + } +} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs new file mode 100644 index 000000000..5c5f40463 --- /dev/null +++ b/crates/mega-evm/src/limit/limit.rs @@ -0,0 +1,188 @@ +//! The per-transaction state of the common execution layer. + +use alloy_primitives::Address; +use revm::{handler::FrameResult, interpreter::FrameInput}; + +use super::{ + frame_limit::{FrameLimitTracker, Lane}, + record::{RecordEffect, StagedRecord}, + LimitUsage, WRITE_RECORD, +}; + +/// What the common execution layer tracks for the running transaction: the per-frame lanes of +/// data-size bytes and write records, and the record the Host staged for the running opcode. +/// +/// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and +/// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) +/// and the frame lifecycle (lanes). +#[derive(Clone, Debug, Default)] +pub struct AdditionalLimit { + pub(crate) tracker: FrameLimitTracker, + staged: Option, + /// Whether the transaction's call target is an applied EIP-7702 authority, whose account + /// write the transaction's lane already counts. + target_is_authority: bool, + /// The history gas the settled transaction spent. + history_gas_spent: u64, +} + +impl AdditionalLimit { + /// Clears the state for a new transaction, keeping allocations. + pub(crate) fn reset(&mut self) { + self.tracker.reset(); + self.staged = None; + self.target_is_authority = false; + self.history_gas_spent = 0; + } + + /// What the transaction keeps so far: its data-size bytes and write records, with every + /// running frame counted as if it succeeds. + pub fn usage(&self) -> LimitUsage { + self.tracker.net() + } + + /// The history gas the last settled transaction spent. + pub const fn history_gas_spent(&self) -> u64 { + self.history_gas_spent + } + + /// Records the history gas the settled transaction spent. + pub(crate) const fn set_history_gas_spent(&mut self, history_gas_spent: u64) { + self.history_gas_spent = history_gas_spent; + } + + /* Observe, stage, commit */ + + /// The record the Host staged for the running opcode, if any. + pub const fn staged_record(&self) -> Option<&StagedRecord> { + self.staged.as_ref() + } + + /// Stages the facts the Host observed. Called by the Host, which records nothing itself. + #[inline] + pub(crate) fn stage_record(&mut self, record: StagedRecord) { + self.staged = Some(record); + } + + /// Commits the staged record to the running frame's lane. Called by an opcode's wrapper once + /// the opcode completed. + #[inline] + pub(crate) fn commit_staged_record(&mut self) { + let Some(record) = self.staged.take() else { return }; + match record.effect() { + RecordEffect::None => {} + RecordEffect::Record(usage) => self.tracker.record(usage), + RecordEffect::Refund(usage) => self.tracker.refund(usage), + } + } + + /// Discards the staged record. Called by an opcode's wrapper when the opcode failed, which + /// takes the observed write back with it. + #[inline] + pub(crate) fn discard_staged_record(&mut self) { + self.staged = None; + } + + /// Discards a record staged outside an opcode's wrapper. Called by each wrapper on entry, so + /// a record nobody committed cannot be committed for the wrong opcode. + #[inline] + pub(crate) fn discard_stale_record(&mut self) { + self.staged = None; + } + + /* Transaction-level records */ + + /// Records the account writes of the applied EIP-7702 authorities other than the sender: + /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is + /// one of them. + pub(crate) fn record_applied_authorities( + &mut self, + authorities: u64, + target_is_authority: bool, + ) { + self.target_is_authority = target_is_authority; + self.tracker.record(WRITE_RECORD.times(authorities)); + } + + /* Frame lanes */ + + /// Pushes the lane of a frame about to start and counts the writes its start makes: + /// + /// - a call that transfers value: the sender's account (once per sender frame) and the + /// recipient's, one record when they are the same account; + /// - a creation: the created account, and the creator's nonce (once per creator frame); + /// - the transaction's own frame: the value recipient or the created account. The sender's + /// account is part of the transaction body, not a record here. + pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) { + match input { + FrameInput::Call(inputs) => { + let target = inputs.target_address; + let transfers_value = inputs.transfers_value(); + if depth == 0 { + let written_outside = target == inputs.caller || self.target_is_authority; + self.tracker.push(Lane::new( + Some(target), + written_outside || transfers_value, + u64::MAX, + )); + if transfers_value && !written_outside { + self.tracker.record(WRITE_RECORD); + } + return; + } + let inherited = self.tracker.current().is_some_and(|caller| { + caller.address == Some(target) && caller.account_recorded + }); + self.tracker.push(Lane::new(Some(target), inherited || transfers_value, u64::MAX)); + if transfers_value { + self.tracker.record_caller(false); + if target != inputs.caller { + self.tracker.record(WRITE_RECORD); + } + } + } + FrameInput::Create(_) => { + self.tracker.push(Lane::new(None, true, u64::MAX)); + self.tracker.record(WRITE_RECORD); + if depth > 0 { + self.tracker.record_caller(true); + } + } + FrameInput::Empty => self.push_empty_frame(), + } + } + + /// Sets the account the running frame runs as, once known (a creation's address). + pub(crate) fn set_frame_address(&mut self, address: Address) { + if let Some(lane) = self.tracker.current_mut() { + lane.address = Some(address); + } + } + + /// Takes a creation's creator record back: the creation failed before bumping the nonce. + pub(crate) fn creation_did_not_bump_nonce(&mut self) { + self.tracker.drop_caller_record(); + } + + /// Pushes the lane of a frame answered without running: a result built without an + /// interpreter keeps the lanes aligned with the frames revm returns. + pub(crate) fn push_empty_frame(&mut self) { + self.tracker.push(Lane::empty()); + } + + /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, + /// a failure discards it. + pub(crate) fn on_frame_return(&mut self, result: &FrameResult) { + self.tracker.pop(result.instruction_result().is_ok()); + } + + /// Settles the transaction's outermost frame: pops its lane unless the frame already + /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever + /// it ran. + pub(crate) fn on_last_frame_return(&mut self, result: &FrameResult) { + debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); + if self.tracker.depth() == 1 { + self.on_frame_return(result); + } + } +} diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 0a805a7fc..32ed3cb92 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -4,10 +4,76 @@ //! ([`LimitKind`]), the verdict of a check ([`LimitCheck`]) and the revert data a stopped frame //! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension (the data-size limit, //! detention, the state-growth and KV limits) fill these in. +//! +//! It also counts what those limits meter at the sites the data-size limit counts: data-size +//! bytes and write records, on a lane per frame ([`AdditionalLimit`]). The Host stages what it +//! observes ([`StagedRecord`]) and the opcode commits it once it completed. + +mod frame_limit; +#[allow(clippy::module_inception)] +mod limit; +mod record; + +pub use limit::AdditionalLimit; +pub use record::StagedRecord; use alloy_primitives::Bytes; use alloy_sol_types::SolError; +/// Bytes of one write record: the key and value delta one account or storage write leaves in +/// the state diff. +pub const WRITE_RECORD_SIZE: u64 = 40; + +/// Bytes every log counts for the address it carries. +pub const LOG_BASE_SIZE: u64 = 32; + +/// Bytes every log topic counts. +pub const LOG_TOPIC_SIZE: u64 = 32; + +/// What a transaction or a frame counts: data-size bytes and write records. +/// +/// The KV count a node reports is the write-record count; it has no tracker of its own. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct LimitUsage { + /// Data-size bytes. + pub data_size: u64, + /// Account and storage write records. + pub write_records: u64, +} + +/// One write record. +pub(crate) const WRITE_RECORD: LimitUsage = + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; + +impl LimitUsage { + /// Nothing counted. + pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + + /// Both counters added, saturating. + pub const fn saturating_add(self, other: Self) -> Self { + Self { + data_size: self.data_size.saturating_add(other.data_size), + write_records: self.write_records.saturating_add(other.write_records), + } + } + + /// Both counters subtracted, saturating at zero. + pub const fn saturating_sub(self, other: Self) -> Self { + Self { + data_size: self.data_size.saturating_sub(other.data_size), + write_records: self.write_records.saturating_sub(other.write_records), + } + } + + /// Both counters multiplied by `n`, saturating. + pub const fn times(self, n: u64) -> Self { + Self { + data_size: self.data_size.saturating_mul(n), + write_records: self.write_records.saturating_mul(n), + } + } +} + alloy_sol_types::sol! { /// The revert data of a frame a resource limit stopped. /// @@ -123,6 +189,19 @@ impl LimitCheck { mod tests { use super::*; + #[test] + fn test_limit_usage_arithmetic_saturates() { + let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; + assert_eq!(max.saturating_add(WRITE_RECORD), max); + assert_eq!(LimitUsage::ZERO.saturating_sub(WRITE_RECORD), LimitUsage::ZERO); + assert_eq!(WRITE_RECORD.times(3), LimitUsage { data_size: 120, write_records: 3 }); + assert_eq!(WRITE_RECORD.times(u64::MAX).data_size, u64::MAX); + assert_eq!( + WRITE_RECORD.saturating_add(WRITE_RECORD).saturating_sub(WRITE_RECORD), + WRITE_RECORD + ); + } + /// `Exempt` passes no predicate that would stop a frame, and has no revert data. #[test] fn test_limit_check_exempt_predicate_truth_table() { diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs new file mode 100644 index 000000000..7bd927fce --- /dev/null +++ b/crates/mega-evm/src/limit/record.rs @@ -0,0 +1,137 @@ +//! The facts the Host observes for the opcode that is running. + +use revm::interpreter::SStoreResult; + +use super::{LimitUsage, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD}; + +/// What the Host saw an opcode do, staged until the opcode completes. +/// +/// The Host only observes: it stages the facts revm hands it and records nothing. The opcode's +/// wrapper commits the staged record once the opcode completed, or discards it when the opcode +/// failed after the Host call (an out-of-gas on the gas charged after the write, say), because the +/// failure takes the write back with it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StagedRecord { + /// An `SSTORE`: the slot's value at the start of the transaction, before the write, and + /// after it. + Sstore(SStoreResult), + /// A `LOG`: its topic count and data length. + Log { + /// Number of topics. + topics: u8, + /// Length of the data, in bytes. + data_len: u64, + }, + /// A `SELFDESTRUCT`. + SelfDestruct { + /// Whether the destructed account had a balance to move. + had_value: bool, + /// Whether the beneficiary existed before. + target_exists: bool, + /// Whether the beneficiary is another account than the destructed one. + to_other_account: bool, + }, +} + +/// How a committed record changes the running frame's usage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RecordEffect { + /// Nothing to count. + None, + /// Count this usage. + Record(LimitUsage), + /// Take this usage back. + Refund(LimitUsage), +} + +impl StagedRecord { + /// What committing the record counts, per site: + /// + /// - `SSTORE`: the first change of a slot in the transaction is one write record; writing the + /// slot back to its original value takes the record back. + /// - `LOG`: its bytes, one base record for the address, one per topic and the data. + /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account. + pub(crate) fn effect(&self) -> RecordEffect { + match self { + Self::Sstore(slot) => { + if slot.is_original_eq_present() { + if slot.is_original_eq_new() { + RecordEffect::None + } else { + RecordEffect::Record(WRITE_RECORD) + } + } else if slot.is_original_eq_new() { + RecordEffect::Refund(WRITE_RECORD) + } else { + RecordEffect::None + } + } + Self::Log { topics, data_len } => RecordEffect::Record(LimitUsage { + data_size: LOG_BASE_SIZE + .saturating_add(LOG_TOPIC_SIZE.saturating_mul(*topics as u64)) + .saturating_add(*data_len), + write_records: 0, + }), + Self::SelfDestruct { had_value, to_other_account, .. } => { + if *had_value && *to_other_account { + RecordEffect::Record(WRITE_RECORD) + } else { + RecordEffect::None + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::U256; + + fn sstore(original: u64, present: u64, new: u64) -> StagedRecord { + StagedRecord::Sstore(SStoreResult { + original_value: U256::from(original), + present_value: U256::from(present), + new_value: U256::from(new), + }) + } + + /// A slot counts once, on its first change in the transaction; writing it back to its + /// original value takes the record back; every other write counts nothing. + #[test] + fn test_sstore_record_rules() { + assert_eq!(sstore(0, 0, 1).effect(), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(5, 5, 0).effect(), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 0).effect(), RecordEffect::Refund(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 2).effect(), RecordEffect::None); + assert_eq!(sstore(3, 3, 3).effect(), RecordEffect::None); + assert_eq!(sstore(3, 4, 4).effect(), RecordEffect::None); + } + + /// A log is 32 bytes for its address, 32 per topic and its data. + #[test] + fn test_log_bytes() { + let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(); + assert_eq!(log(0, 0), RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 })); + assert_eq!( + log(4, 100), + RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) + ); + assert_eq!( + log(1, u64::MAX), + RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) + ); + } + + /// Only value that moves to another account is a beneficiary write. + #[test] + fn test_selfdestruct_record_rules() { + let sd = |had_value, to_other_account| { + StagedRecord::SelfDestruct { had_value, target_exists: true, to_other_account }.effect() + }; + assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sd(true, false), RecordEffect::None); + assert_eq!(sd(false, true), RecordEffect::None); + assert_eq!(sd(false, false), RecordEffect::None); + } +} diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 2cd8a2606..54d88b265 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -26,7 +26,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| -| the common execution layer | 34 | 19 | 15 | 19 | 15 | 0 | +| the common execution layer | 1 | 0 | 1 | 1 | 0 | 0 | | the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | @@ -43,7 +43,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **764** | **626** | **138** | **428** | **308** | **28** | +| **Total** | **731** | **607** | **124** | **410** | **293** | **28** | ## Tests ported in place @@ -114,13 +114,21 @@ It becomes assertable with the common execution layer, which defines the frame o ## Tests ported by the common execution layer -These 7 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 40 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `equivalence/evm_state.rs` | the common execution layer (3) | 3 | `tests/satin/state.rs` | +| `mini_rex/db_error.rs` | the common execution layer (4) | 4 | `tests/satin/db_error.rs` | +| `rex4/eip7702_delegation_cycle.rs` | the common execution layer (1) | 1 | `tests/satin/state.rs` | +| `rex5/frame_target_updated_dedup.rs` | the common execution layer (5) | 5 | `tests/satin/write_records.rs` | +| `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | +| `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | +| `src/evm/host.rs` | the common execution layer (10) | 10 | `src/evm/host.rs` | | `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | +| `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | -| **Total** | | **7** | | +| **Total** | | **40** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -146,13 +154,11 @@ Each cell lists `disposition count (mechanism · decision)`. | `block_executor/trait_factory_runtime_limits.rs` | 4 | rewrite 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | | `compute_gas/claims.rs` | 14 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); keep 1 (the Satin gas table · D04 (KZG 100k)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 2 (the Satin gas table · D13); rewrite 1 (the Satin gas table · D11); rewrite 1 (the data-size limit · D33/D48) | | `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | -| `equivalence/evm_state.rs` | 3 | keep 3 (the common execution layer) | | `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | | `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | | `mini_rex/contract_size_limit.rs` | 12 | rewrite 12 (the Satin gas table · D04 (512 KiB kept; the decision table does not pin the initcode bound under Osaka/EIP-3860)) | -| `mini_rex/db_error.rs` | 4 | keep 4 (the common execution layer) | | `mini_rex/gas.rs` | 26 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)); rewrite 4 (the Satin gas table · D11/D55 (7976 floor)) | | `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | | `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | @@ -168,7 +174,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | | `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | -| `rex4/eip7702_delegation_cycle.rs` | 9 | keep 8 (SALT pricing · account inspection on the pricing path); keep 1 (the common execution layer) | +| `rex4/eip7702_delegation_cycle.rs` | 8 | keep 8 (SALT pricing · account inspection on the pricing path) | | `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | | `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | @@ -183,7 +189,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | | `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | | `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/frame_target_updated_dedup.rs` | 5 | rewrite 5 (the common execution layer · D50/D56 write-record layer) | | `rex5/gas_validation.rs` | 4 | rewrite 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | | `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | | `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | @@ -200,14 +205,14 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | | `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | | `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | -| `rex6/create_frame_accounting.rs` | 3 | rewrite 2 (the common execution layer · D50/D56 write-record layer); keep 1 (SALT pricing) | +| `rex6/create_frame_accounting.rs` | 1 | keep 1 (SALT pricing) | | `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | | `rex6/error_paths.rs` | 2 | keep 2 (SALT pricing) | | `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | | `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | | `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | -| `rex6/self_transfer_account_dedup.rs` | 5 | rewrite 4 (the common execution layer · D50/D56); keep 1 (the data-size limit) | +| `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | | `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | @@ -219,14 +224,13 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | -| `src/evm/host.rs` | 11 | keep 10 (the common execution layer · Host observation layer (D33) on the revm 40 journal); keep 1 (SALT pricing) | +| `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | | `src/evm/mod.rs` | 5 | keep 3 (the pre-block system calls); keep 1 (the block executor); keep 1 (the common execution layer) | | `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | | `src/evm/state.rs` | 1 | keep 1 (the block executor) | | `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | | `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | -| `src/limit/frame_limit.rs` | 4 | rewrite 4 (the common execution layer · data-size-only per-frame tracker) | | `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | | `src/limit/limit.rs` | 4 | keep 4 (history gas · D51) | | `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | diff --git a/crates/mega-evm/tests/_pending/equivalence/evm_state.rs b/crates/mega-evm/tests/_pending/equivalence/evm_state.rs deleted file mode 100644 index 0d93c3466..000000000 --- a/crates/mega-evm/tests/_pending/equivalence/evm_state.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Tests for the EVM state. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::bytecode::opcode::{INVALID, PUSH0, SLOAD}, - test_utils::{transact, MemoryDatabase}, - *, -}; -use revm::database::StateBuilder; - -/// Test that verifies the EVM state correctly tracks storage access for non-existent storage slots. -/// This test ensures that when a contract performs an SLOAD operation on a storage slot that -/// doesn't exist (storage slot 0), the EVM state properly records this access and includes -/// the storage slot in the contract's storage map, even though the slot was previously -/// uninitialized. -#[test] -fn test_evm_state_zero_storage() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, revm::bytecode::opcode::SLOAD]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO) - .unwrap(); - let state = result.state; - let contract = state.get(&contract_address).unwrap(); - // the non-existent storage slot will present in the state - assert_eq!(contract.storage.len(), 1); - assert!(contract.storage.contains_key(&U256::ZERO)); -} - -/// Test that verifies EVM state includes storage reads from failed transactions. -/// -/// This test ensures that when a transaction fails (reverts), any storage reads -/// that occurred before the failure are still properly recorded in the EVM state. -/// The contract reads storage slot 0 and then executes INVALID to cause a revert, -/// but the storage access should still be tracked in the resulting state. -#[test] -fn test_evm_state_include_failed_tx_reads() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, SLOAD, INVALID]; // read slot 0 and then revert - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO) - .unwrap(); - let storage = &result.state.get(&contract_address).as_ref().unwrap().storage; - assert!(storage.contains_key(&U256::ZERO)); -} - -/// Test that when an existing empty account is called but with no state changes, the account is -/// still marked as destroyed according to EIP-161: Specification-d. At the end of the transaction, -/// any account touched by the execution of that transaction which is now empty SHALL instead become -/// non-existent (i.e. deleted), where an account is considered to be touched when it is involved in -/// any potentially state-changing operation. This includes, but is not limited to, being the -/// recipient of a transfer of zero value. -#[test] -fn test_state_clear_with_noop_call() { - let empty_account = address!("0000000000000000000000000000000000100001"); - let caller = address!("0000000000000000000000000000000000100000"); - let mut db = MemoryDatabase::default().account_nonce(empty_account, 0); - let mut state = StateBuilder::::default() - .with_database(&mut db) - .with_bundle_update() - .build(); - - // Call the non-existing account with no transfer - let result = transact( - MegaSpecId::REX, - &mut state, - caller, - Some(empty_account), - Bytes::default(), - U256::ZERO, - ) - .unwrap(); - // assert that the non-existing account is marked as touched - assert!(result.state.get(&empty_account).unwrap().is_touched()); - - // apply the state changes and get the transitions - let transitions = state.cache.apply_evm_state(result.state); - let (_, transition) = - transitions.iter().find(|(address, _)| *address == empty_account).unwrap(); - // assert that the storage is marked as destroyed - assert!(transition.storage_was_destroyed); -} diff --git a/crates/mega-evm/tests/_pending/equivalence/main.rs b/crates/mega-evm/tests/_pending/equivalence/main.rs deleted file mode 100644 index 89780e3d6..000000000 --- a/crates/mega-evm/tests/_pending/equivalence/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Tests for Equivalence spec (baseline EVM behavior). - -mod evm_state; diff --git a/crates/mega-evm/tests/_pending/mini_rex/db_error.rs b/crates/mega-evm/tests/_pending/mini_rex/db_error.rs deleted file mode 100644 index cd54ac334..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/db_error.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! Tests for DB error handling via `JournalInspectTr`. -//! -//! Verifies that when the database returns an error during `inspect_account_delegated` or -//! `inspect_storage`, the EVM properly halts with `FatalExternalError` and surfaces the error -//! as `EVMError::Custom`. - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, - EVMError, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::CALL, - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); -const TARGET: Address = address!("3000000000000000000000000000000000000003"); - -fn transact( - spec: MegaSpecId, - db: ErrorInjectingDatabase, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// When `inspect_storage` fails during SSTORE (in `additional_limit_ext::sstore`), -/// the EVM should halt with `FatalExternalError` and return `EVMError::Custom`. -#[test] -fn test_sstore_db_error_on_inspect_storage() { - let storage_key = U256::from(0x42); - let storage_value = U256::from(0x1); - - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when the SSTORE instruction's `inspect_storage` tries to read this slot. - db.fail_on_storage = Some((CALLEE, storage_key)); - - let result = transact( - MegaSpecId::MINI_REX, - db, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 1_000_000, - ); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected storage()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -/// When `inspect_account_delegated` fails during CALL with value transfer -/// (in `wrap_call_with_storage_gas!`), the EVM should halt with `FatalExternalError`. -#[test] -fn test_call_with_transfer_db_error_on_inspect_account() { - // Build bytecode that does CALL with value transfer to TARGET. - // CALL args: gas, addr, value, argsOffset, argsSize, retOffset, retSize - let bytecode = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value (non-zero to trigger value transfer path) - .push_address(TARGET) - .push_number(100_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when the CALL instruction's `inspect_account_delegated` tries to load TARGET. - db.fail_on_account = Some(TARGET); - - let result = transact( - MegaSpecId::MINI_REX, - db, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 1_000_000, - ); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected basic()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -/// Regression: `inspect_storage` must not query `DB::storage` for accounts created in the -/// current transaction. Their post-CREATE storage is guaranteed empty (EIP-161 / EIP-6780), -/// so any DB read returns ZERO at best — and fails outright under stateless replay, where -/// no witness exists for these slots when CREATE lands on a pre-funded address (its -/// `Loaded` cache status bypasses revm's `State::storage` short-circuit). -/// -/// The injected DB is configured to error on every `storage()` read of slot 0 at the -/// to-be-created address. With the fix, `inspect_storage` short-circuits to ZERO for -/// newly-created accounts and the error is never triggered, so the CREATE succeeds. -/// Without the fix, the constructor's SSTORE pre-read would surface `EVMError::Custom` -/// (mini-rex routes SSTORE through `additional_limit_ext::sstore`, which calls -/// `inspect_storage` to compute the original/present values before writing). -#[test] -fn test_inspect_storage_skips_db_for_newly_created_account() { - // Initcode: SSTORE slot 0 = 0x42; STOP. The SSTORE pre-read goes through - // `inspect_storage` and is the path the fix targets. - let initcode = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(0x42)).stop().build(); - - // CALLER's nonce starts at 0, so the top-level CREATE deploys to `CALLER.create(0)`. - let created = CALLER.create(0); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - // Pre-fund the future contract address so its DB cache status is `Loaded` rather than - // `Vacant` — this is the scenario that exposed the original bug. - inner_db.set_account_balance(created, U256::from(1)); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // The fix means this DB call must never happen. If it does, the test fails. - db.fail_on_storage = Some((created, U256::ZERO)); - - let result = transact(MegaSpecId::MINI_REX, db, CALLER, None, initcode, U256::ZERO, 10_000_000); - - let res = result.expect("CREATE should not surface a DB error"); - assert!( - res.result.is_success(), - "CREATE should succeed without DB::storage being queried, got: {:?}", - res.result - ); -} - -/// When `inspect_account_delegated` fails during STATICCALL (in `wrap_call_with_storage_gas!`), -/// the EVM should halt with `FatalExternalError`. -/// This tests a different code path from CALL-with-transfer: STATICCALL has no value parameter -/// but still calls `inspect_account_delegated` on the target to check `is_empty`. -/// -/// Uses REX spec because `wrap_call_with_storage_gas!` (which calls `inspect_account_delegated`) -/// is only wired for STATICCALL starting from REX (`MINI_REX` uses `compute_gas_ext::static_call` -/// which delegates directly to revm's handler without inspecting first). -#[test] -fn test_staticcall_db_error_on_inspect_account() { - // STATICCALL stack layout: gas, addr, argsOffset, argsSize, retOffset, retSize - let bytecode = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(TARGET) // addr - .push_number(100_000_u64) // gas - .append(revm::bytecode::opcode::STATICCALL) - .stop() - .build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when STATICCALL's `inspect_account_delegated` tries to load TARGET. - db.fail_on_account = Some(TARGET); - - let result = - transact(MegaSpecId::REX, db, CALLER, Some(CALLEE), Bytes::new(), U256::ZERO, 1_000_000); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected basic()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs index eb146393a..c94d58cc7 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -5,7 +5,6 @@ mod block_env_access_tracking; mod block_env_gas_limit; mod compute_gas_limit; mod contract_size_limit; -mod db_error; mod gas; mod mega_system_transaction; mod oracle; diff --git a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs index dc06cb58d..91f504a0c 100644 --- a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs +++ b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs @@ -16,12 +16,6 @@ //! The issue only manifests when a *contract* performs a CALL-family opcode targeting the //! poisoned address. //! -//! ## Storage isolation tests -//! -//! EIP-7702 delegation only affects code — storage always belongs to the original address. -//! `inspect_storage` (used by the wrapped SLOAD/SSTORE for storage gas accounting) must -//! access the original address's storage, not the delegate's. -//! //! ## EIP-7702 spec note //! //! EIP-7702 specifies that clients must resolve at most one level of delegation. @@ -368,116 +362,3 @@ fn test_delegation_cycle_via_create2() { "CREATE2 with cyclic delegation should complete without stack overflow" ); } - -// --------------------------------------------------------------------------- -// Storage isolation tests — verify `inspect_storage` uses the original address -// --------------------------------------------------------------------------- - -/// Builds a contract that sequentially CALLs `first` then `second`, returning the -/// 32-byte returndata from the second call. -fn build_two_calls_return_second(first: Address, second: Address) -> Bytes { - BytecodeBuilder::default() - // CALL first target (no returndata needed) - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(first) - .append(GAS) - .append(CALL) - .append(POP) // discard success flag - // CALL second target — capture 32 bytes of returndata at memory[0] - .push_number(32u8) // retLength - .append(PUSH0) // retOffset = 0 - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(second) - .append(GAS) - .append(CALL) - .append(POP) // discard success flag - // Return memory[0..32] - .push_number(32u8) // size - .append(PUSH0) // offset - .append(RETURN) - .build() -} - -/// Sets up and runs the `inspect_storage` pollution scenario for a given spec. -/// -/// Setup: -/// - DELEGATOR delegates to DELEGATE via EIP-7702. -/// - DELEGATE's code does `SSTORE(slot=1, 0x77)` then `SLOAD(1)` then RETURN. -/// - DELEGATOR has storage[1] = 42, DELEGATE has storage[1] = 99. -/// -/// PARENT's code does two sequential CALLs in one transaction: -/// 1. CALL DELEGATOR — runs DELEGATE's code in DELEGATOR's context. The wrapped SSTORE calls -/// `inspect_storage(DELEGATOR, 1)`. -/// 2. CALL DELEGATE directly — runs DELEGATE's code in its own context. -/// -/// Returns the `ResultAndState` for spec-specific assertions. -fn run_inspect_storage_pollution_scenario(spec: MegaSpecId) -> ResultAndState { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - - // DELEGATE: code does SSTORE(1, 0x77) then SLOAD(1) then RETURN. - // Has storage[1] = 99 which should never be confused with DELEGATOR's. - let delegate_code = BytecodeBuilder::default() - .sstore(U256::from(1), U256::from(0x77)) - .push_number(1u8) // slot 1 - .append(SLOAD) - .append(PUSH0) - .append(MSTORE) - .push_number(32u8) - .append(PUSH0) - .append(RETURN) - .build(); - db.set_account_code(DELEGATE, delegate_code); - db.set_account_storage(DELEGATE, U256::from(1), U256::from(99)); - db.set_account_balance(DELEGATE, U256::from(1_000_000u64)); - - // DELEGATOR: delegates to DELEGATE, storage[1] = 42 - set_eip7702_delegation(&mut db, DELEGATOR, DELEGATE); - db.set_account_storage(DELEGATOR, U256::from(1), U256::from(42)); - db.set_account_balance(DELEGATOR, U256::from(1_000_000u64)); - - // PARENT: calls DELEGATOR first (triggers inspect_storage), then DELEGATE directly - db.set_account_code(PARENT, build_two_calls_return_second(DELEGATOR, DELEGATE)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(spec, &mut db, tx).expect("transaction should succeed"); - assert!(result.result.is_success(), "execution should succeed: {:?}", result.result); - - let output = result.result.output().expect("should have output"); - let second_call_sload = U256::from_be_slice(output); - // After SSTORE(1, 0x77), SLOAD(1) should return 0x77 (the just-written value) - // regardless of spec — the pollution only affects original_value, not present_value. - assert_eq!( - second_call_sload, - U256::from(0x77), - "SLOAD after SSTORE should return the just-written value" - ); - - result -} - -/// REX4+: `inspect_storage` no longer follows EIP-7702 delegation, so the delegate's -/// journal is not polluted. -/// DELEGATE's slot 1 `original_value` should be 99 (its own DB value). -#[test] -fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { - let result = run_inspect_storage_pollution_scenario(MegaSpecId::REX4); - - let delegate_account = result.state.get(&DELEGATE).expect("DELEGATE should be in state"); - let slot = - delegate_account.storage.get(&U256::from(1)).expect("slot 1 should exist in DELEGATE"); - assert_eq!( - slot.original_value(), - U256::from(99), - "REX4: DELEGATE's slot 1 original_value should be 99 (its own), not 42 (DELEGATOR's)" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs b/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs deleted file mode 100644 index 7d66746ad..000000000 --- a/crates/mega-evm/tests/_pending/rex5/frame_target_updated_dedup.rs +++ /dev/null @@ -1,255 +0,0 @@ -//! Tests for Rex5's caller-account deduplication within a parent frame. -//! -//! Pre-Rex5, `DataSizeTracker::before_frame_init` and `KVUpdateTracker::before_frame_init` -//! checked the parent frame's `target_updated` flag to decide whether to charge the parent's -//! caller-account update for a value-transferring CALL / CALLCODE or CREATE, but never set -//! the flag to `true` after charging. As a result, every subsequent value-transferring call -//! or create from the same parent frame re-charged the caller account, overcounting data -//! size and KV updates. -//! -//! Rex5 marks the parent's flag after charging, so subsequent operations from the same -//! parent frame no longer double-charge the caller account. Per-target charges for distinct -//! callee / created addresses are unchanged. Pre-Rex5 specs keep their existing (frozen) -//! overcounting behavior for backward compatibility. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, -}; -use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, STOP}, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); - -/// Runs the given `tx` on `spec` with unlimited data/KV budgets and returns the -/// recorded data size and KV update counts. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let usage = ctx.additional_limit.borrow().get_usage(); - Ok((r, usage.data_size, usage.kv_updates)) -} - -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Appends `CALL(gas=GAS, target, value=1, args=[], ret=[])`, leaving the CALL -/// success flag on the stack. -fn append_value_call(builder: BytecodeBuilder, target: Address) -> BytecodeBuilder { - builder - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .append(PUSH1) - .append(1u8) // value - .push_address(target) - .append(GAS) - .append(CALL) -} - -/// Appends a CREATE with value=1 and an empty init code (immediately returns). -fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .append_many([PUSH0, PUSH0]) // initLen, initOff (empty init code) - .append(PUSH1) - .append(1u8) // value - .append(CREATE) -} - -/// Base intrinsic data size for a TX with no calldata / access-list / 7702 entries: -/// `BASE_TX_SIZE` + caller account write. -fn intrinsic_data_size() -> u64 { - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE -} - -// ============================================================================ -// Two consecutive value-transferring CALLs -// ============================================================================ - -/// CALLEE does two value-transferring CALLs to two distinct targets. -/// -/// Expected charges for the caller (= CALLEE parent frame) update: -/// - Rex5: charged once (deduplicated) -/// - Pre-Rex5 (Rex4): charged twice (overcounting bug) -/// -/// The two distinct target accounts are always charged separately. -fn two_value_calls_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); - builder = append_value_call(builder, CONTRACT2).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_two_value_calls_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_value_calls_code()); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE, counted once) + 1 (CONTRACT) + 1 (CONTRACT2) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate the CALLEE (parent) update across both calls"); - // Data size: intrinsic + 3 discardable account writes (CALLEE once, CONTRACT, CONTRACT2). - assert_eq!(data_size, intrinsic_data_size() + 3 * ACCOUNT_INFO_WRITE_SIZE); -} - -// ============================================================================ -// CREATE followed by value-transferring CALL -// ============================================================================ - -/// CALLEE does a CREATE followed by a value-transferring CALL, both from the same -/// parent frame. The parent update should only be charged once under Rex5. -fn create_then_call_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_create(builder).append(POP); - builder = append_value_call(builder, CONTRACT).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_create_then_call_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, create_then_call_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE parent, counted once) + 1 (created account) - // + 1 (CONTRACT) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE update across CREATE and CALL"); -} - -// ============================================================================ -// Two consecutive CREATEs from the same parent -// ============================================================================ - -/// CALLEE does two CREATEs from the same parent frame. The parent update should -/// only be charged once under Rex5 (created accounts still counted per-CREATE). -fn two_creates_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_create(builder).append(POP); - builder = append_value_create(builder).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_two_creates_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_creates_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE, once) + 2 (two distinct created accounts) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE across both CREATEs"); -} - -// ============================================================================ -// Reverted child still discards its accumulated charges -// ============================================================================ - -/// CALLEE CALLs CONTRACT with value. CONTRACT is an INVALID instruction that -/// halts, so the child frame's discardable usage must be dropped on revert, -/// regardless of spec. -fn call_that_reverts_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_reverted_child_drops_discardable_charges() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, call_that_reverts_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success(), "outer TX succeeds even though child reverts"); - - // The child's discardable charges (CALLEE parent update + CONTRACT target update) are - // dropped on revert. Only the persistent caller nonce survives. - assert_eq!(kv_updates, 1, "Reverted child's discardable KV updates must be dropped"); - assert_eq!(data_size, intrinsic_data_size(), "Reverted child's data size must be dropped"); -} - -// ============================================================================ -// Reverted first child followed by a successful second child (revert-then-retry) -// ============================================================================ - -/// CALLEE first CALLs CONTRACT with value (reverts), then CALLs CONTRACT2 with value (succeeds). -/// Under Rex5, the parent (CALLEE) account update should be charged exactly once — from the -/// second (successful) call, not zero times. Without the flag-reset-on-revert fix, Rex5 would -/// set `target_updated` on the first call, see it still set on the second, and charge 0 times. -fn revert_then_succeed_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); // CONTRACT reverts - builder = append_value_call(builder, CONTRACT2).append(POP); // CONTRACT2 succeeds - builder.append(STOP).build() -} - -#[test] -fn test_rex5_reverted_first_child_flag_reset_allows_second_charge() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, revert_then_succeed_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); // CONTRACT2 has no code → EOA - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE parent, charged on successful 2nd call) - // + 1 (CONTRACT2) = 3. - // The first call's charges (CALLEE + CONTRACT) are dropped on revert, and the - // target_updated flag is reset, so the second call correctly re-charges CALLEE. - assert_eq!( - kv_updates, 3, - "Rex5 must charge CALLEE once after revert-then-retry (not undercount to 0)" - ); - assert_eq!(data_size, intrinsic_data_size() + 2 * ACCOUNT_INFO_WRITE_SIZE); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 8d06f7f51..0716046c9 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -8,7 +8,6 @@ mod deposit_caller_accounting; mod deposit_create_storage_gas; mod eip7702_metering; mod eip7702_state_growth; -mod frame_target_updated_dedup; mod gas_validation; mod interceptor_selector_probe; mod keyless_deploy_dispatch_parity; diff --git a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs index 2d7958ecd..ab41bf66b 100644 --- a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs @@ -89,68 +89,6 @@ const OUTER_CREATOR: Address = Address::new([ 0xC0, 0xDE, 0x00, 0xFF, ]); -/// Bytecode: PUSH5 0x60006000fd; PUSH1 0; MSTORE; PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP; STOP. -/// The inner CREATE deploys init code [60 00 60 00 FD] = PUSH1 0; PUSH1 0; REVERT, which reverts, -/// so the nested CREATE frame reverts while this outer contract returns success. -fn outer_creator_code() -> Bytes { - Bytes::from_static(&[ - 0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, // PUSH5 - 0x60, 0x00, // PUSH1 0 (mem offset) - 0x52, // MSTORE - 0x60, 0x05, // PUSH1 5 (create length) - 0x60, 0x1b, // PUSH1 27 (create offset) - 0x60, 0x00, // PUSH1 0 (create value) - 0xf0, // CREATE - 0x50, // POP - 0x00, // STOP - ]) -} - -#[test] -fn test_rex6_nested_create_revert_charges_creator_nonce_bump_to_parent() { - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(OUTER_CREATOR, outer_creator_code()) - }; - let make_call = || { - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - kind: TxKind::Call(OUTER_CREATOR), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - tx - }; - let usage = |spec: MegaSpecId| { - let mut evm = make_evm(spec, build_db()); - let r = alloy_evm::Evm::transact_raw(&mut evm, make_call()); - assert!(r.expect("ok").result.is_success(), "outer call must succeed (spec {spec:?})"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage - }; - let rex5 = usage(MegaSpecId::REX5); - let rex6 = usage(MegaSpecId::REX6); - assert_eq!( - rex6.data_size.saturating_sub(rex5.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "REX6 must keep the creator nonce-bump account-info write (+{ACCOUNT_INFO_WRITE_SIZE}) on \ - the surviving parent (rex5={}, rex6={})", - rex5.data_size, - rex6.data_size, - ); - assert_eq!( - rex6.kv_updates.saturating_sub(rex5.kv_updates), - 1, - "REX6 must keep the creator nonce-bump KV write (+1) on the surviving parent \ - (rex5={}, rex6={})", - rex5.kv_updates, - rex6.kv_updates, - ); -} - /// Init code that returns `code_len` bytes of zeros from `memory[0..code_len]`. /// /// Layout: PUSH3 `code_len`; PUSH1 0; RETURN. @@ -227,73 +165,3 @@ fn test_rex6_create_net_new_inspect_db_error_surfaces() { assert!(res.is_err(), "DB error during REX6 CREATE net-new inspect must surface as Err"); } -/// Bytecode like [`outer_creator_code`] but with the reverting CREATE performed TWICE -/// (revert-then-retry). The creator's account-info write must be charged once, not once per -/// attempt: the first CREATE's parent-lane charge survives the child's revert (the nonce bump -/// does too), so the unwind must not re-arm the dedup flag. -fn outer_double_creator_code() -> Bytes { - Bytes::from_static(&[ - 0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, // PUSH5 - 0x60, 0x00, // PUSH1 0 (mem offset) - 0x52, // MSTORE - 0x60, 0x05, // PUSH1 5 (create length) - 0x60, 0x1b, // PUSH1 27 (create offset) - 0x60, 0x00, // PUSH1 0 (create value) - 0xf0, // CREATE (#1 — reverts) - 0x50, // POP - 0x60, 0x05, // PUSH1 5 - 0x60, 0x1b, // PUSH1 27 - 0x60, 0x00, // PUSH1 0 - 0xf0, // CREATE (#2 — reverts again) - 0x50, // POP - 0x00, // STOP - ]) -} - -/// REX6: a reverted-then-retried nested CREATE charges the creator's account-info write exactly -/// once. Before the unwind gate, `pop_frame_unwind_parent` reset the parent's dedup flag while -/// the parent-lane charge survived — the retry charged the same creator update again. -#[test] -fn test_rex6_nested_create_revert_then_retry_charges_creator_once() { - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(OUTER_CREATOR, outer_double_creator_code()) - }; - let make_call = || { - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - kind: TxKind::Call(OUTER_CREATOR), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - tx - }; - let usage = |spec: MegaSpecId| { - let mut evm = make_evm(spec, build_db()); - let r = alloy_evm::Evm::transact_raw(&mut evm, make_call()); - assert!(r.expect("ok").result.is_success(), "outer call must succeed (spec {spec:?})"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage - }; - let rex5 = usage(MegaSpecId::REX5); - let rex6 = usage(MegaSpecId::REX6); - assert_eq!( - rex6.data_size.saturating_sub(rex5.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "double reverted CREATE must charge the creator write ONCE under REX6 \ - (rex5={}, rex6={})", - rex5.data_size, - rex6.data_size, - ); - assert_eq!( - rex6.kv_updates.saturating_sub(rex5.kv_updates), - 1, - "double reverted CREATE must charge the creator KV update ONCE under REX6 \ - (rex5={}, rex6={})", - rex5.kv_updates, - rex6.kv_updates, - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs index ad50882a0..ce6adfd2b 100644 --- a/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs +++ b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs @@ -96,218 +96,23 @@ fn usage_of(spec: MegaSpecId, db: MemoryDatabase, tx: MegaTransaction) -> LimitU usage } -/// Returns `(data_size_delta, kv_delta)` between a `value=1` and a `value=0` top-level call to -/// `to`. The delta isolates the target-side account-info write. -fn value_transfer_delta(spec: MegaSpecId, to: Address) -> (u64, u64) { - let with_value = usage_of(spec, base_db(), call_tx(to, 1)); - let zero_value = usage_of(spec, base_db(), call_tx(to, 0)); - ( - with_value.data_size.saturating_sub(zero_value.data_size), - with_value.kv_updates.saturating_sub(zero_value.kv_updates), - ) -} - // ============================================================================ // Top-level self-transfer: A -> A // ============================================================================ -/// REX6: a top-level `A -> A` value transfer adds NO extra account-info write — A is already -/// recorded by `before_tx_start`, so the target-side write is suppressed. -#[test] -fn test_rex6_top_level_self_transfer_no_double_count() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX6, A); - assert_eq!( - data_delta, 0, - "REX6 A->A value transfer must not add a duplicate account-info write (data_size)", - ); - assert_eq!( - kv_delta, 0, - "REX6 A->A value transfer must not add a duplicate account-info write (kv_updates)", - ); -} - // ============================================================================ // Non-self transfer: A -> B (unchanged on every spec) // ============================================================================ -#[test] -fn test_rex6_non_self_transfer_counts_target() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX6, B); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX6 A->B value transfer must record the target write (data_size)", - ); - assert_eq!(kv_delta, 1, "REX6 A->B value transfer must record the target write (kv_updates)"); -} - // ============================================================================ // Nested self-call with value: A's code CALLs A with value // ============================================================================ -/// A contract at `SELF_CALLER` that self-calls **exactly once** with `value` wei. -/// -/// To bound the recursion the contract branches on `CALLDATASIZE`: the outer invocation (reached -/// from the EOA tx with 1 byte of calldata) takes the self-call branch and CALLs itself with an -/// EMPTY args buffer (`argsSize = 0`); the inner invocation therefore sees `CALLDATASIZE == 0` and -/// STOPs immediately. The result is a single `caller == target == SELF_CALLER` value frame. -fn self_calling_code(value: u64) -> Bytes { - // Layout (byte offsets matter for the JUMPDEST target): - // CALLDATASIZE ; cond - // PUSH1 ; dest - // JUMPI ; if calldatasize != 0 -> self-call branch - // STOP ; inner invocation (calldatasize == 0) returns here - // JUMPDEST ; <- self-call branch - // - // POP STOP - // - // Prefix bytes: CALLDATASIZE(1) PUSH1(2) JUMPI(1) STOP(1) = 5 bytes, so the JUMPDEST is at - // offset 5. - const JUMPDEST_OFFSET: u8 = 5; - BytecodeBuilder::default() - .append(CALLDATASIZE) - .push_number(JUMPDEST_OFFSET) // u8 -> single-byte PUSH1 - .append(JUMPI) - .append(STOP) - .append(JUMPDEST) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize (empty -> inner invocation sees CALLDATASIZE == 0) - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(SELF_CALLER) // target == self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .stop() - .build() -} - -/// A top-level no-value call `EOA -> SELF_CALLER` carrying 1 byte of calldata (so the outer -/// invocation takes the self-call branch). -fn nested_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: EOA, - kind: TxKind::Call(SELF_CALLER), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - value: U256::ZERO, - data: Bytes::from_static(&[0x01]), - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Reads `(data_size, kv_updates)` for a top-level no-value `EOA -> SELF_CALLER` call where the -/// contract frame CALLs itself once with `inner_value` wei. `SELF_CALLER` is pre-funded so the -/// inner value transfer always succeeds. -fn nested_usage(spec: MegaSpecId, inner_value: u64) -> (u64, u64) { - let db = base_db() - .account_balance(SELF_CALLER, U256::from(A_BALANCE)) - .account_code(SELF_CALLER, self_calling_code(inner_value)); - let u = usage_of(spec, db, nested_tx()); - (u.data_size, u.kv_updates) -} - -/// REX6: a nested `A -> A` value call records A only once — the caller-side write covers it, the -/// target-side write is suppressed. The delta over an inner `value=0` self-call is therefore one -/// account-info write (the caller-side write), not two. -#[test] -fn test_rex6_nested_self_call_with_value_counts_once() { - let (data_value, kv_value) = nested_usage(MegaSpecId::REX6, 1); - let (data_zero, kv_zero) = nested_usage(MegaSpecId::REX6, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - ACCOUNT_INFO_WRITE_SIZE, - "REX6 nested A->A value call must add exactly one account-info write (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 1, - "REX6 nested A->A value call must add exactly one account-info write (kv_updates)", - ); -} - // ============================================================================ // Nested self-call where the parent frame already did a value transfer // (`parent_needs_update == false` arm of the dedup predicate) // ============================================================================ -/// A contract at `SELF_CALLER` that, on its outer invocation, first CALLs `B` with `value` wei and -/// then CALLs **itself** with `value` wei. The first value-transferring call sets the frame's -/// `target_updated` flag, so the second (self) call has `parent_needs_update == false` — the -/// caller-side write is already skipped there, and the dedup predicate (`target == caller`) is what -/// suppresses the redundant target-side write under REX6. Recursion is bounded the same way as -/// [`self_calling_code`]: the self-call passes `argsSize = 0`, so the inner invocation sees -/// `CALLDATASIZE == 0` and STOPs. -fn self_calling_code_two(value: u64) -> Bytes { - const JUMPDEST_OFFSET: u8 = 5; - let mut b = BytecodeBuilder::default() - .append(CALLDATASIZE) - .push_number(JUMPDEST_OFFSET) - .append(JUMPI) - .append(STOP) - .append(JUMPDEST); - // CALL #1: SELF_CALLER -> B (distinct target), value. Sets `target_updated` on this frame. - b = b - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(B) // target != self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP); - // CALL #2: SELF_CALLER -> SELF_CALLER (self), value. `parent_needs_update == false` here. - b.push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize (empty -> inner invocation STOPs) - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(SELF_CALLER) // target == self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .stop() - .build() -} - -/// `(data_size, kv_updates)` for `EOA -> SELF_CALLER` where the contract frame CALLs `B` then -/// itself, each with `inner_value` wei. -fn nested_two_call_usage(spec: MegaSpecId, inner_value: u64) -> (u64, u64) { - let db = base_db() - .account_balance(SELF_CALLER, U256::from(A_BALANCE)) - .account_code(SELF_CALLER, self_calling_code_two(inner_value)); - let u = usage_of(spec, db, nested_tx()); - (u.data_size, u.kv_updates) -} - -/// REX6: the `parent_needs_update == false` self-transfer is still deduped. The value-transfer -/// delta is two account-info writes — `SELF_CALLER` (the first call's caller write) and `B` (its -/// target) — and the second, self-targeted call adds nothing. Crucially this is not an under-count: -/// the frame account is still recorded exactly once. -#[test] -fn test_rex6_nested_pnu_false_self_transfer_counts_once() { - let (data_value, kv_value) = nested_two_call_usage(MegaSpecId::REX6, 1); - let (data_zero, kv_zero) = nested_two_call_usage(MegaSpecId::REX6, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 2 * ACCOUNT_INFO_WRITE_SIZE, - "REX6 must record SELF_CALLER and B once each; the self-targeted second call adds nothing \ - (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 2, - "REX6 must record SELF_CALLER and B once each; the self-targeted second call adds nothing \ - (kv_updates)", - ); -} - // ============================================================================ // Zero-value call records no account-info write (unchanged) // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/src/evm/host.rs b/crates/mega-evm/tests/_pending/src/evm/host.rs index a092f529a..534e16b6b 100644 --- a/crates/mega-evm/tests/_pending/src/evm/host.rs +++ b/crates/mega-evm/tests/_pending/src/evm/host.rs @@ -78,147 +78,6 @@ mod tests { } } - /// `inspect_account(addr, false)` must not hydrate `info.code` on the vacant - /// branch — callers that need it pass `load_code = true`. - #[test] - fn test_inspect_account_vacant_path_does_not_hydrate_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); // PUSH1 1 PUSH1 1 ADD - let expected_hash = keccak256(&bytecode); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let account = - inspect_account(&mut journal, ADDR, false).expect("inspect_account must succeed"); - - assert_eq!( - account.info.code_hash, expected_hash, - "code_hash must propagate from the database's `basic()` result", - ); - assert!( - account.info.code.is_none(), - "`load_code = false` must leave `info.code` as-is on the vacant branch", - ); - } - - /// `inspect_account(addr, true)` hydrates `info.code` from `code_by_hash` on - /// first cold inspection against a lazy-code database. - #[test] - fn test_inspect_account_with_load_code_hydrates_lazy_bytecode_on_first_touch() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); - let mut journal = Journal::new(db); - - let account = inspect_account(&mut journal, ADDR, true) - .expect("inspect_account must succeed on first cold-touch"); - let hydrated = account - .info - .code - .as_ref() - .expect("`load_code = true` must populate `info.code` from code_by_hash"); - assert_eq!( - hydrated.original_bytes().as_ref(), - bytecode.as_ref(), - "hydrated bytecode must match what `code_by_hash` would return", - ); - } - - /// The occupied-branch hydration must keep firing — a second `inspect_account` - /// against the same lazy-DB address must observe hydrated `info.code` even with - /// `load_code = false`. - #[test] - fn test_inspect_account_occupied_branch_hydrates_on_second_inspection() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let first_code_hash = inspect_account(&mut journal, ADDR, false) - .expect("first inspection must succeed") - .info - .code_hash; - let second = - inspect_account(&mut journal, ADDR, false).expect("second inspection must succeed"); - - assert_eq!( - second.info.code_hash, first_code_hash, - "code_hash must be identical across cache miss and cache hit", - ); - assert!( - second.info.code.is_some(), - "second inspection must observe the hydrated code via the occupied-branch \ - `code_by_hash` load", - ); - } - - /// `inspect_account(addr, true)` must short-circuit on EOAs — the `code_hash != - /// KECCAK_EMPTY` guard keeps `code_by_hash` off the hot path. - #[test] - fn test_inspect_account_with_load_code_leaves_eoa_code_empty() { - const EOA: Address = address!("00000000000000000000000000000000000000cc"); - - let mut db = LazyCodeDatabase::default(); - db.accounts.insert( - EOA, - AccountInfo { - balance: U256::from(1_000_000u64), - nonce: 5, - code_hash: KECCAK_EMPTY, - code: None, - }, - ); - let mut journal = Journal::new(db); - - let account = inspect_account(&mut journal, EOA, true) - .expect("inspect_account must succeed and be a no-op on EOAs"); - assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); - assert!( - account.info.code.is_none(), - "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ - `code_by_hash` off the hot path for accounts without on-chain code", - ); - } - - /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate - /// `info.code` — on either branch. In particular the occupied branch must not fall through to - /// `code_by_hash` the way `inspect_account(.., false)` does (see - /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets the - /// REX6 keyless-deploy occupancy check decide on the hash alone, without demanding an - /// already-warmed occupied address's bytecode in a stateless witness carrying only its proof. - #[test] - fn test_inspect_account_code_hash_never_hydrates_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let expected_hash = keccak256(&bytecode); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - // Vacant cache-miss: returns the hash from `basic()` without hydrating code. - let vacant_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("vacant read must succeed"); - assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "vacant branch must not hydrate info.code", - ); - - // The address is now resident with `code == None`. `inspect_account` would hydrate on this - // occupied branch; `inspect_account_code_hash` must not. - let occupied_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("occupied read must succeed"); - assert_eq!( - occupied_hash, expected_hash, - "occupied branch must return the cached code_hash" - ); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "inspect_account_code_hash must NOT hydrate info.code on the occupied branch", - ); - } - /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the /// very first cold inspection against a lazy-code database. Regression guard: /// any refactor that re-introduces a code-None branch silently degrades the @@ -261,164 +120,4 @@ mod tests { the delegation was followed exactly one hop", ); } - - /// Pins the `LazyCodeDatabase` fixture's contract against the production - /// `revm::Database` shape it is modeling: `basic()` returns - /// `code: None` for known accounts, `None` for unknown addresses; - /// `code_by_hash()` falls back to empty bytecode for an unknown hash; - /// `storage()` and `block_hash()` are inert stubs (no tests exercise them via - /// `inspect_account`, but they must remain wired so the fixture is a complete - /// `revm::Database`). If the fixture ever drifts (e.g. someone "helpfully" - /// makes `basic()` eagerly populate `code` like `MemoryDatabase` does), the - /// inspect-account tests above silently lose their load-bearing property — - /// this test fails fast in that case. - #[test] - fn test_lazy_code_database_fixture_pins_reth_style_contract() { - const KNOWN: Address = address!("00000000000000000000000000000000000000ee"); - let bytecode = Bytes::from_static(&[0x00]); - let mut db = LazyCodeDatabase::default().with_account_code(KNOWN, bytecode); - - let known = db.basic(KNOWN).unwrap().expect("known account must resolve"); - assert!( - known.code.is_none(), - "LazyCodeDatabase::basic must NOT pre-populate code — that is the \ - behavior `inspect_account` is being tested against", - ); - assert!( - db.basic(Address::ZERO).unwrap().is_none(), - "unknown address must return None from basic()", - ); - - let unknown_hash = keccak256([0xffu8]); - assert_eq!( - db.code_by_hash(unknown_hash).unwrap().original_bytes().len(), - 0, - "unknown code_hash must fall back to empty bytecode", - ); - - assert_eq!(db.storage(KNOWN, U256::ZERO).unwrap(), U256::ZERO); - assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); - } - - // === inspect_storage coverage tests (PR #334) === - - #[test] - fn test_inspect_storage_rex4_slot_hit_returns_existing_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(3); - let expected_value = U256::from(42); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected_value, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let spec = MegaSpecId::REX4; - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on existing slot"); - - assert_eq!( - slot.present_value, expected_value, - "REX4 slot hit must return the pre-seeded value" - ); - assert!(slot.is_cold, "inspected slot must remain cold"); - } - - #[test] - fn test_inspect_storage_rex4_slot_miss_inserts_and_returns_db_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000cc"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(7); - let spec = MegaSpecId::REX4; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on absent slot"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "absent slot on non-created account must return ZERO from database" - ); - assert!(slot.is_cold, "newly inserted slot must be marked cold"); - - let calls_after_first = journal.database.storage_calls(); - let slot2 = - journal.inspect_storage(spec, ADDR, key).expect("second inspect_storage must succeed"); - - assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); - assert_eq!( - journal.database.storage_calls(), - calls_after_first, - "second inspect_storage on the same slot must hit the cache, not the DB", - ); - } - - #[test] - fn test_inspect_storage_rex4_newly_created_short_circuits_db() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - { - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - account.mark_created(); - } - - let key = U256::from(1); - let spec = MegaSpecId::REX4; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed on newly-created account"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "newly-created account must return ZERO without querying database" - ); - assert!(slot.is_cold, "slot must be marked cold"); - } - - #[test] - fn test_inspect_storage_rex4_ignores_eip7702_delegation() { - const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); - const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); - let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_code); - let mut journal = Journal::new(db); - - let key = U256::from(2); - let expected = U256::from(99); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, DELEGATOR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let spec = MegaSpecId::REX4; - let slot = journal - .inspect_storage(spec, DELEGATOR, key) - .expect("inspect_storage must succeed for REX4 delegator"); - - assert_eq!( - slot.present_value, expected, - "REX4 must read storage from delegator (original address), not delegate" - ); - } } diff --git a/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs b/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs deleted file mode 100644 index b9d899e16..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/frame_limit.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/frame_limit.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/frame_limit.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use alloy_primitives::address; - - use super::*; - - const ADDR: Address = address!("0000000000000000000000000000000000001234"); - - /// `set_created_address` on an empty frame stack must be a no-op. - #[test] - fn test_set_created_address_empty_stack_is_noop() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - // No frame on the stack — should not panic, just do nothing. - t.set_created_address(ADDR); - } - - /// `set_created_address` panics when called twice on the same CREATE frame - /// (invariant: `target_address` must be `None` when first filled in). - #[test] - #[should_panic(expected = "created account already recorded")] - fn test_set_created_address_duplicate_panics() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_create_frame(); - t.set_created_address(ADDR); - t.set_created_address(ADDR); // second call must panic - } - - /// Drives `FrameLimitTracker` through a representative sequence of pushes, mutations, - /// and pops (both success and revert) and asserts that the cached `net_usage()` stays - /// in sync with the uncached reference walk after every step. This is the load-bearing - /// guarantee of the cache-based refactor: any future change that introduces a new - /// mutation site without going through a helper will break this test. - #[test] - fn test_net_usage_cache_matches_uncached() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); - - // Pre-frame intrinsic usage goes to tx_entry. - t.add_tx_persistent(100); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // add_frame_persistent on empty stack must be a no-op and return false. - assert!(!t.add_frame_persistent(50)); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // add_frame_discardable / add_frame_refund are no-ops on empty stack. - t.add_frame_discardable(50); - t.add_frame_refund(50); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 100); - - // Push frame 1 and mix in persistent/discardable/refund. - t.push_frame(()); - assert!(t.add_frame_persistent(20)); - t.add_frame_discardable(30); - t.add_frame_refund(10); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 2 (nested) and mutate. - t.push_frame(()); - assert!(t.add_frame_persistent(7)); - t.add_frame_discardable(15); - t.add_frame_refund(3); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 3 (deeper) and revert it — discardable & refund must vanish from cache, - // persistent must merge into the parent (frame 2). - t.push_frame(()); - assert!(t.add_frame_persistent(5)); - t.add_frame_discardable(11); - t.add_frame_refund(2); - let before_revert = t.net_usage(); - let popped = t.pop_frame(false).expect("frame 3 popped"); - assert_eq!(popped.discardable_usage, 11); - assert_eq!(popped.refund, 2); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // After revert: cache should drop the child's discardable (11) and refund (2), - // so net_usage changes by -(11) + 2 = -9 vs before. - assert_eq!(t.net_usage(), before_revert - 9); - - // Push frame 3 again and pop it successfully — discardable/refund merge into parent, - // cache is unchanged by the pop itself (totals are invariant under transfer). - t.push_frame(()); - assert!(t.add_frame_persistent(4)); - t.add_frame_discardable(6); - t.add_frame_refund(1); - let before_success = t.net_usage(); - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), before_success); - - // Pop frame 2 with success → merge into frame 1. - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Pop the last frame (frame 1) with revert → discardable/refund vanish, persistent - // merges into tx_entry. - let before_last_revert = t.net_usage(); - let frame_1 = t.pop_frame(false).expect("frame 1 popped"); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // The popped frame's discardable/refund leave the cache. - assert_eq!(t.net_usage(), before_last_revert - frame_1.discardable_usage + frame_1.refund); - - // Reset returns the cache to zero in sync with the entries. - t.reset(); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); - } - - /// Verifies that a refund exceeding the cumulative usage clamps `net_usage()` to 0, - /// matching the saturating semantics of the uncached reference. This guards against - /// signed-style accounting bugs where refunds outrun used and an unsigned subtraction - /// would otherwise wrap. - #[test] - fn test_net_usage_saturates_when_refund_exceeds_used() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_frame(()); - t.add_frame_discardable(10); - t.add_frame_refund(100); - assert_eq!(t.net_usage(), 0); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - } -} diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs new file mode 100644 index 000000000..c94d91fbc --- /dev/null +++ b/crates/mega-evm/tests/satin/common.rs @@ -0,0 +1,59 @@ +//! Shared setup of the Satin tests. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{op_transaction, zero_fee_l1_block_info}, + LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, +}; +use revm::{ + context::{result::ResultAndState, BlockEnv, TxEnv}, + Database, +}; + +/// A block with room for any transaction the tests run. +pub(crate) fn block() -> BlockEnv { + BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, ..Default::default() } +} + +/// A Satin context over `db` with zero L1 fees. +pub(crate) fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +/// A call from `caller` to `to` with zero gas price. +pub(crate) fn call(caller: Address, to: Address, value: U256, gas_limit: u64) -> MegaTransaction { + tx(caller, TxKind::Call(to), Bytes::new(), value, gas_limit) +} + +/// A call from `caller` to `to` carrying `data`. +pub(crate) fn call_with_data( + caller: Address, + to: Address, + data: Bytes, + gas_limit: u64, +) -> MegaTransaction { + tx(caller, TxKind::Call(to), data, U256::ZERO, gas_limit) +} + +/// A creation from `caller` running `init_code`. +pub(crate) fn create(caller: Address, init_code: Bytes, gas_limit: u64) -> MegaTransaction { + tx(caller, TxKind::Create, init_code, U256::ZERO, gas_limit) +} + +fn tx(caller: Address, kind: TxKind, data: Bytes, value: U256, gas_limit: u64) -> MegaTransaction { + OpTx(op_transaction(TxEnv { caller, kind, data, value, gas_limit, ..Default::default() })) +} + +/// Runs `tx` on a fresh Satin EVM over `db` and returns its result and what the common execution +/// layer counted. +pub(crate) fn run( + db: DB, + tx: MegaTransaction, +) -> (ResultAndState, LimitUsage) { + let mut evm = MegaEvm::new(context(db)); + let result = evm.transact_raw(tx).expect("the transaction is valid"); + let usage = evm.ctx().additional_limit().usage(); + (result, usage) +} diff --git a/crates/mega-evm/tests/satin/db_error.rs b/crates/mega-evm/tests/satin/db_error.rs new file mode 100644 index 000000000..bfc5be1f2 --- /dev/null +++ b/crates/mega-evm/tests/satin/db_error.rs @@ -0,0 +1,101 @@ +//! A database error during execution fails the transaction with that error; it is never a halt +//! the transaction is included with. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CALL, STATICCALL}, + context::result::EVMError, +}; + +use crate::common::{call, context, create}; + +const CALLER: Address = address!("2000000000000000000000000000000000000002"); +const CALLEE: Address = address!("1000000000000000000000000000000000000001"); +const TARGET: Address = address!("3000000000000000000000000000000000000003"); + +fn transact( + db: ErrorInjectingDatabase, + tx: MegaTransaction, +) -> Result< + revm::context::result::ResultAndState, + EVMError, +> { + MegaEvm::new(context(db)).transact_raw(tx) +} + +fn assert_db_error( + result: Result>, + expected: &str, +) { + match result { + Err(EVMError::Database(error)) => { + assert!(format!("{error}").contains(expected), "got: {error}"); + } + other => panic!("expected a database error, got: {other:?}"), + } +} + +fn funded(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(100_000_000_000u64)) + .account_code(CALLEE, code) +} + +/// A failing storage read in `SSTORE` surfaces as the database error. +#[test] +fn test_sstore_db_error_on_inspect_storage() { + let key = U256::from(0x42); + let code = BytecodeBuilder::default().sstore(key, U256::from(1)).stop().build(); + let mut db = ErrorInjectingDatabase::new(funded(code)); + db.fail_on_storage = Some((CALLEE, key)); + assert_db_error( + transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), + "injected storage()", + ); +} + +fn call_target(opcode: u8) -> Bytes { + let code = BytecodeBuilder::default() + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64); + let code = if opcode == CALL { code.push_number(1_u64) } else { code }; + code.push_address(TARGET).push_number(100_000_u64).append(opcode).stop().build() +} + +/// A failing account read of a value transfer's recipient surfaces as the database error. +#[test] +fn test_call_with_transfer_db_error_on_inspect_account() { + let mut db = ErrorInjectingDatabase::new(funded(call_target(CALL))); + db.fail_on_account = Some(TARGET); + assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); +} + +/// A creation that writes storage never reads the created account's storage from the database: +/// it is empty, and a stateless witness has nothing for it. +#[test] +fn test_inspect_storage_skips_db_for_newly_created_account() { + let init_code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(0x42)).stop().build(); + let created = CALLER.create(0); + let inner = MemoryDatabase::default() + .account_balance(CALLER, U256::from(100_000_000_000u64)) + .account_balance(created, U256::from(1)); + let mut db = ErrorInjectingDatabase::new(inner); + db.fail_on_storage = Some((created, U256::ZERO)); + let result = transact(db, create(CALLER, init_code, 10_000_000)).expect("no database read"); + assert!(result.result.is_success(), "{:?}", result.result); +} + +/// A failing account read of a `STATICCALL` target surfaces as the database error. +#[test] +fn test_staticcall_db_error_on_inspect_account() { + let mut db = ErrorInjectingDatabase::new(funded(call_target(STATICCALL))); + db.fail_on_account = Some(TARGET); + assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 449988970..625602213 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -1,3 +1,7 @@ //! Tests of the Satin engine. +mod common; +mod db_error; mod equivalence; +mod state; +mod write_records; diff --git a/crates/mega-evm/tests/satin/state.rs b/crates/mega-evm/tests/satin/state.rs new file mode 100644 index 000000000..ffe8ef594 --- /dev/null +++ b/crates/mega-evm/tests/satin/state.rs @@ -0,0 +1,113 @@ +//! What a Satin transaction leaves in its returned state. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::test_utils::{BytecodeBuilder, MemoryDatabase}; +use revm::{ + bytecode::opcode::{CALL, GAS, INVALID, MSTORE, POP, PUSH0, RETURN, SLOAD}, + database::{AccountState, StateBuilder}, + state::Bytecode, +}; + +use crate::common::{call, run}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100001"); +const GAS_LIMIT: u64 = 1_000_000; + +/// A read of a slot that was never written still puts the slot in the returned state. +#[test] +fn test_evm_state_zero_storage() { + let db = MemoryDatabase::default().account_code(CONTRACT, Bytes::from_static(&[PUSH0, SLOAD])); + let (result, _) = run(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + let contract = &result.state[&CONTRACT]; + assert_eq!(contract.storage.len(), 1); + assert!(contract.storage.contains_key(&U256::ZERO)); +} + +/// A failed transaction's reads are in the returned state too. +#[test] +fn test_evm_state_include_failed_tx_reads() { + let db = MemoryDatabase::default() + .account_code(CONTRACT, Bytes::from_static(&[PUSH0, SLOAD, INVALID])); + let (result, _) = run(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + assert!(!result.result.is_success()); + assert!(result.state[&CONTRACT].storage.contains_key(&U256::ZERO)); +} + +/// A call to an existing empty account touches it, and EIP-161 clears it when the state is +/// applied. +#[test] +fn test_state_clear_with_noop_call() { + let empty_account = CONTRACT; + let mut db = MemoryDatabase::default().account_nonce(empty_account, 0); + let mut state = StateBuilder::::default() + .with_database(&mut db) + .with_bundle_update() + .build(); + let (result, _) = run(&mut state, call(CALLER, empty_account, U256::ZERO, GAS_LIMIT)); + assert!(result.state[&empty_account].is_touched()); + + let transitions = state.cache.apply_evm_state(result.state, |_, _| {}); + let (_, transition) = + transitions.iter().find(|(address, _)| *address == empty_account).unwrap(); + assert!(transition.storage_was_destroyed); +} + +const PARENT: Address = address!("0000000000000000000000000000000000500001"); +const DELEGATOR: Address = address!("0000000000000000000000000000000000500005"); +const DELEGATE: Address = address!("0000000000000000000000000000000000500006"); + +/// A contract that calls `first`, then `second`, and returns the 32 bytes `second` returned. +fn two_calls_returning_the_second(first: Address, second: Address) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(first) + .append(GAS) + .append(CALL) + .append(POP) + .push_number(32u8) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(second) + .append(GAS) + .append(CALL) + .append(POP) + .push_number(32u8) + .append(PUSH0) + .append(RETURN) + .build() +} + +/// A write through an EIP-7702 delegator goes to the delegator's storage: the delegate's own slot +/// keeps its original value when the delegate later runs in its own context. +#[test] +fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { + let delegate_code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(0x77)) + .push_number(1u8) + .append(SLOAD) + .append(PUSH0) + .append(MSTORE) + .push_number(32u8) + .append(PUSH0) + .append(RETURN) + .build(); + let mut db = MemoryDatabase::default() + .account_code(DELEGATE, delegate_code) + .account_storage(DELEGATE, U256::from(1), U256::from(99)) + .account_storage(DELEGATOR, U256::from(1), U256::from(42)) + .account_code(PARENT, two_calls_returning_the_second(DELEGATOR, DELEGATE)); + let delegation = Bytecode::new_eip7702(DELEGATE); + let account = db.load_account(DELEGATOR).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + account.account_state = AccountState::None; + + let (result, _) = run(db, call(CALLER, PARENT, U256::ZERO, 100_000_000)); + assert!(result.result.is_success(), "{:?}", result.result); + let second = U256::from_be_slice(result.result.output().unwrap()); + assert_eq!(second, U256::from(0x77), "the delegate reads its own write back"); + let slot = &result.state[&DELEGATE].storage[&U256::from(1)]; + assert_eq!(slot.original_value(), U256::from(99), "the delegate's own original value"); + let slot = &result.state[&DELEGATOR].storage[&U256::from(1)]; + assert_eq!(slot.original_value(), U256::from(42), "the delegator's own original value"); +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs new file mode 100644 index 000000000..9c0c3ec8e --- /dev/null +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -0,0 +1,514 @@ +//! The observe-stage-commit layer and the write records it counts. +//! +//! A write record is one account or storage write, 40 bytes of data size. The sites: the first +//! change of a slot in the transaction (taken back when the slot is written back), a value +//! transfer's sender and recipient, a creation's creator nonce and created account, a +//! `SELFDESTRUCT` that moves value to another account, an applied EIP-7702 authority, and the +//! transaction's own value recipient or created account. The sender's own account is part of the +//! transaction body and is not a record. Records are deduplicated per frame and discarded with the +//! frame that fails. + +use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, + SELFDESTRUCT, SSTORE, STOP, + }, + interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, + Database, Inspector, +}; + +use crate::common::{call, call_with_data, context, create, run}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0000000000000000000000000000000000100001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); +const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); +const GAS_LIMIT: u64 = 10_000_000; + +const fn records(n: u64) -> LimitUsage { + LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_000_000)) + .account_balance(CALLEE, U256::from(10_000_000)) +} + +/// Appends `CALL(gas=GAS, target, value, args=[], ret=[])`, leaving the success flag. +fn append_value_call(builder: BytecodeBuilder, target: Address, value: u8) -> BytecodeBuilder { + builder + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(value) + .push_address(target) + .append(GAS) + .append(CALL) +} + +/// Appends a `CREATE` with value 1 and empty init code. +fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { + builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) +} + +/* ---------- value transfers and creations, deduplicated per frame ---------- */ + +/// Two value transfers from one frame record the sender once and each recipient. +#[test] +fn test_two_value_calls_record_the_sender_once() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, CONTRACT, CONTRACT2"); +} + +/// A creation and a value transfer from one frame record the frame's account once. +#[test] +fn test_create_then_call_record_the_frame_account_once() { + let code = append_value_create(BytecodeBuilder::default()).append(POP); + let code = append_value_call(code, CONTRACT, 1).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, the created account, CONTRACT"); +} + +/// Two creations from one frame record the creator once and each created account. +#[test] +fn test_two_creates_record_the_creator_once() { + let code = append_value_create(BytecodeBuilder::default()).append(POP); + let code = append_value_create(code).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, two created accounts"); +} + +/// A value transfer into a child that fails is discarded with the child, sender included. +#[test] +fn test_failed_child_discards_its_transfer_records() { + let code = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "the outer call succeeds although the child halts"); + assert_eq!(usage, LimitUsage::ZERO); +} + +/// After a failed transfer the sender can be recorded again by the next one. +#[test] +fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(2), "CALLEE and CONTRACT2, from the second transfer"); +} + +const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); + +/// `PUSH5 ; PUSH1 0; MSTORE; (PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP) x +/// n`: `n` creations whose init code reverts. +fn reverting_creations(n: usize) -> Bytes { + let mut code = vec![0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, 0x60, 0x00, 0x52]; + for _ in 0..n { + code.extend_from_slice(&[0x60, 0x05, 0x60, 0x1b, 0x60, 0x00, 0xf0, 0x50]); + } + code.push(0x00); + code.into() +} + +/// A reverted creation keeps the creator's nonce record: the nonce bump survives the revert. +#[test] +fn test_reverted_nested_create_keeps_the_creator_nonce_record() { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(1)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1), "the creator's nonce; the created account is gone"); +} + +/// Two reverted creations record the creator once: the first record survives, so the second +/// finds the creator recorded. +#[test] +fn test_reverted_then_retried_create_records_the_creator_once() { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(2)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1)); +} + +/// A creation that fails before bumping the nonce (the creator cannot fund it) records nothing. +#[test] +fn test_creation_without_funds_records_nothing() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_000_000_000_000_u64) + .append(CREATE) + .append(POP) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); +} + +const A: Address = address!("00000000000000000000000000000000A0000001"); +const B: Address = address!("00000000000000000000000000000000B0000002"); +const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); + +fn value_delta(to: Address) -> LimitUsage { + let db = || MemoryDatabase::default().account_balance(A, U256::from(1_000_000)); + let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), GAS_LIMIT)); + let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, GAS_LIMIT)); + assert!(with_value.result.is_success() && zero_value.result.is_success()); + usage_value.saturating_sub(usage_zero) +} + +/// A top-level transfer to the sender itself writes no account the body does not already count. +#[test] +fn test_top_level_self_transfer_no_double_count() { + assert_eq!(value_delta(A), LimitUsage::ZERO); +} + +/// A top-level transfer to another account records the recipient. +#[test] +fn test_top_level_transfer_counts_the_recipient() { + assert_eq!(value_delta(B), records(1)); +} + +/// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty +/// calldata stops at once. +fn self_calling_code(targets: &[Address], value: u64) -> Bytes { + let mut code = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(5_u8) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST); + for target in targets { + code = code + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(*target) + .push_number(100_000_u64) + .append(CALL) + .append(POP); + } + code.stop().build() +} + +fn nested_delta(targets: &[Address]) -> LimitUsage { + let usage = |value| { + let db = MemoryDatabase::default() + .account_balance(A, U256::from(1_000_000)) + .account_balance(SELF_CALLER, U256::from(1_000_000)) + .account_code(SELF_CALLER, self_calling_code(targets, value)); + let (result, usage) = + run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), GAS_LIMIT)); + assert!(result.result.is_success()); + usage + }; + usage(1).saturating_sub(usage(0)) +} + +/// A nested transfer to the frame's own account is one account write. +#[test] +fn test_nested_self_call_with_value_counts_once() { + assert_eq!(nested_delta(&[SELF_CALLER]), records(1)); +} + +/// After a transfer to another account recorded the frame's account, a transfer to itself adds +/// nothing. +#[test] +fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { + assert_eq!(nested_delta(&[B, SELF_CALLER]), records(2)); +} + +/* ---------- storage, logs, selfdestruct ---------- */ + +/// A slot's first change is a record; writing it back to its original value takes it back. +#[test] +fn test_sstore_first_change_records_and_write_back_refunds() { + type Writes = &'static [(u64, u64)]; + let cases: [(Writes, u64, LimitUsage); 4] = [ + (&[(0, 1)], 0, records(1)), + (&[(0, 1), (0, 2)], 0, records(1)), + (&[(0, 1), (0, 0)], 0, LimitUsage::ZERO), + (&[(0, 0)], 5, records(1)), + ]; + for (writes, original, expected) in cases { + let mut code = BytecodeBuilder::default(); + for (slot, value) in writes { + code = code.sstore(U256::from(*slot), U256::from(*value)); + } + let db = MemoryDatabase::default() + .account_code(CALLEE, code.stop().build()) + .account_storage(CALLEE, U256::ZERO, U256::from(original)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected, "writes {writes:?} over original {original}"); + } +} + +/// A write-back in a child refunds the record its caller made, and the refund dies with a +/// failing child. +#[test] +fn test_write_back_in_a_child_refunds_the_caller_record() { + let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); + let failing_child = + BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).append(INVALID).build(); + for (code, expected) in [(child, LimitUsage::ZERO), (failing_child, records(1))] { + // CALLEE writes slot 0, then DELEGATECALLs CONTRACT, which writes it back in CALLEE's + // storage. + let parent = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build(); + let db = + MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected); + } +} + +/// A log counts 32 bytes for its address, 32 per topic and its data; no write record. +#[test] +fn test_log_counts_its_bytes() { + let code = BytecodeBuilder::default() + .push_number(0x22_u8) + .push_number(0x11_u8) + .push_number(10_u8) + .append(PUSH0) + .append(LOG2) + .stop() + .build(); + let (result, usage) = run( + MemoryDatabase::default().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + ); + assert!(result.result.is_success()); + assert_eq!(result.result.logs().len(), 1); + assert_eq!(usage, LimitUsage { data_size: 32 + 2 * 32 + 10, write_records: 0 }); +} + +/// `SELFDESTRUCT` records the beneficiary only when value moves to another account. +#[test] +fn test_selfdestruct_records_the_beneficiary_when_value_moves() { + let destruct_to = |beneficiary: Address| { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() + }; + let cases = [ + (U256::from(5), CONTRACT, records(1)), + (U256::from(5), CALLEE, LimitUsage::ZERO), + (U256::ZERO, CONTRACT, LimitUsage::ZERO), + ]; + for (balance, beneficiary, expected) in cases { + let db = MemoryDatabase::default() + .account_code(CALLEE, destruct_to(beneficiary)) + .account_balance(CALLEE, balance); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); + } +} + +/// A top-level creation records the created account, and nothing when it fails. +#[test] +fn test_top_level_create_records_the_created_account() { + let (result, usage) = + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1)); + + let (result, usage) = + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), GAS_LIMIT)); + assert!(!result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO); +} + +/* ---------- the commit happens after the opcode ---------- */ + +/// Records, after each opcode, what the layer holds. +#[derive(Default)] +struct LayerProbe { + /// `(opcode, staged record left, usage)` after each opcode. + steps: Vec<(u8, bool, LimitUsage)>, + opcode: u8, + /// Stages a log through the Host before every `SSTORE`, as a stale record. + stage_before_sstore: bool, +} + +impl Inspector, EthInterpreter> for LayerProbe { + fn step(&mut self, interp: &mut Interpreter, context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + if self.stage_before_sstore && self.opcode == SSTORE { + let log = Log { + address: CALLEE, + data: LogData::new(vec![B256::ZERO], Bytes::new()).unwrap(), + }; + revm::context_interface::Host::log(context, log); + assert!(matches!( + context.additional_limit().staged_record(), + Some(StagedRecord::Log { .. }) + )); + } + } + + fn step_end( + &mut self, + _interp: &mut Interpreter, + context: &mut MegaContext, + ) { + let layer = context.additional_limit(); + self.steps.push((self.opcode, layer.staged_record().is_some(), layer.usage())); + } +} + +fn probe( + db: MemoryDatabase, + gas_limit: u64, + stage_before_sstore: bool, +) -> Vec<(u8, bool, LimitUsage)> { + let mut evm = MegaEvm::new(context(db)) + .with_inspector(LayerProbe { stage_before_sstore, ..Default::default() }); + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); + evm.inspector().steps.clone() +} + +fn after_sstore(steps: &[(u8, bool, LimitUsage)]) -> (bool, LimitUsage) { + let (_, staged, usage) = steps.iter().find(|(op, ..)| *op == SSTORE).copied().unwrap(); + (staged, usage) +} + +/// A completed `SSTORE` commits its record: nothing is left staged and the record is counted by +/// the time the opcode ends. +#[test] +fn test_completed_sstore_commits_its_record() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, false); + let (staged, usage) = after_sstore(&steps); + assert!(!staged); + assert_eq!(usage, records(1)); +} + +/// An `SSTORE` that runs out of gas after its Host call wrote the slot discards the staged +/// record: the Host observed the write, the failure takes it back, and nothing is counted. +#[test] +fn test_sstore_out_of_gas_after_the_write_discards_the_record() { + // CALLEE calls CONTRACT with 5,000 gas: past the EIP-2200 stipend check, so the Host call + // writes the slot, but short of the 22,100 a cold first write charges after it. + let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .push_number(5_000_u64) + .append(CALL) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, child); + let steps = probe(db, GAS_LIMIT, false); + let (staged, usage) = after_sstore(&steps); + assert!(!staged, "the record is discarded, not left for the next opcode"); + assert_eq!(usage, LimitUsage::ZERO, "a failed opcode's write is not counted"); +} + +/// A record staged outside an opcode's wrapper is discarded when the next wrapper starts, so it +/// is never committed for that opcode. +#[test] +fn test_wrapper_discards_a_stale_record_on_entry() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, true); + let (staged, usage) = after_sstore(&steps); + assert!(!staged); + assert_eq!(usage, records(1), "the SSTORE's record, and not the stale log's bytes"); +} + +/* ---------- applied EIP-7702 authorities ---------- */ + +const DELEGATE: Address = address!("00000000000000000000000000000000DE1E0001"); +const AUTHORITY_1: Address = address!("00000000000000000000000000000000A0717001"); +const AUTHORITY_2: Address = address!("00000000000000000000000000000000A0717002"); + +/// A type-4 transaction from `CALLER` to `to` with value `value`, carrying authorizations +/// `(authority, nonce)` that delegate to `DELEGATE`. +fn authorizing_call( + to: Address, + value: u64, + authorizations: &[(Address, u64)], +) -> mega_evm::MegaTransaction { + use revm::{ + context::{transaction::TransactionType, TxEnv}, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + let authorization_list = authorizations + .iter() + .map(|(authority, nonce)| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: DELEGATE, nonce: *nonce }, + RecoveredAuthority::Valid(*authority), + )) + }) + .collect(); + alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: alloy_primitives::TxKind::Call(to), + value: U256::from(value), + gas_limit: GAS_LIMIT, + gas_priority_fee: Some(0), + authorization_list, + ..Default::default() + })) +} + +/// Each distinct applied authority is one record, however many of its authorizations applied; +/// an authorization that does not apply (a wrong nonce) records nothing. +#[test] +fn test_applied_authorities_record_once_each() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run( + db(), + authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0), (AUTHORITY_2, 0), (AUTHORITY_1, 1)]), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, records(2)); + + let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 7)])); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO, "a wrong nonce applies nothing"); + + let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(CALLER, 1)])); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO, "the sender's own account is part of the body"); +} + +/// A value transfer to an applied authority records the authority once, not again as the +/// recipient. +#[test] +fn test_value_to_an_applied_authority_records_it_once() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run(db, authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, records(1)); +} From 3bf74b3b2a8363fb0e9287f4f8cd1a81eea304c9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:36:29 +0800 Subject: [PATCH 058/201] feat: carry the inherited reservoir on synthetic frame results and guard the call depth --- crates/mega-evm/src/evm/execution.rs | 79 +++++- crates/mega-evm/src/evm/frame.rs | 248 ++++++++++++++++++ crates/mega-evm/src/evm/mod.rs | 2 + crates/mega-evm/tests/_pending/README.md | 11 +- .../_pending/rex5/call_too_deep_guard.rs | 130 --------- crates/mega-evm/tests/satin/main.rs | 1 + .../tests/satin/synthetic_frame_gas.rs | 125 +++++++++ 7 files changed, 453 insertions(+), 143 deletions(-) create mode 100644 crates/mega-evm/src/evm/frame.rs create mode 100644 crates/mega-evm/tests/satin/synthetic_frame_gas.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 30fb9ae5c..e25823ab8 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -29,13 +29,14 @@ use revm::{ InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, InitialAndFloorGas, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, + InitialAndFloorGas, InstructionResult, }, - primitives::Address, + primitives::{Address, Bytes, CALL_STACK_LIMIT}, Database, Inspector, Journal, }; -use crate::{ExternalEnvTypes, MegaContext, MegaEvm, MegaInstructions}; +use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext, MegaEvm, MegaInstructions}; /// The Satin handler. /// @@ -231,16 +232,29 @@ impl EvmTr for MegaEvm Result, ContextDbError> { + if let Some(result) = call_too_deep(&frame_init) { + self.inner.ctx.additional_limit.push_empty_frame(); + return Ok(ItemOrResult::Result(result)); + } + if let Some(result) = self.intercept(&frame_init) { + self.inner.ctx.additional_limit.push_empty_frame(); + return Ok(ItemOrResult::Result(result)); + } + let frame_init = self.rewrite_keyless(frame_init); let ctx = &mut self.inner.ctx; ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); // The creator of a nested creation, to tell afterwards whether revm bumped its nonce. @@ -341,6 +355,11 @@ where ) -> Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + // The inspector answered the frame. The depth guard still holds: an answer cannot + // reach past the call-stack limit. + if let Some(too_deep) = call_too_deep(&frame_init) { + output = too_deep; + } ctx.additional_limit.push_empty_frame(); frame_end(ctx, inspector, &frame_init.frame_input, &mut output); return Ok(ItemOrResult::Result(output)); @@ -374,6 +393,50 @@ where } } +impl MegaEvm { + /// System contract interception: a `CALL` or `STATICCALL` to a system contract answered by + /// `MegaETH` instead of the contract's code. + /// + /// The extension point of the system contract interceptors; nothing is intercepted yet. An + /// answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles like + /// a frame revm ran. + // Takes the EVM mutably: an interceptor reads and writes the context. + #[allow(clippy::needless_pass_by_ref_mut)] + #[inline] + const fn intercept(&mut self, _frame_init: &FrameInit) -> Option { + None + } + + /// The keyless deployment rewrite: a keyless deployment call turned into the native creation + /// it stands for. + /// + /// The extension point of native keyless deployment; nothing is rewritten yet. + // Takes the EVM mutably: the rewrite validates the deployment against the journal. + #[allow(clippy::needless_pass_by_ref_mut)] + #[inline] + const fn rewrite_keyless(&mut self, frame_init: FrameInit) -> FrameInit { + frame_init + } +} + +/// The depth guard: a `CALL` or `STATICCALL` past the call-stack limit, answered with +/// `CallTooDeep`, its gas untouched and its reservoir carried. +/// +/// revm checks the depth when it builds a frame; an interceptor or an inspector answers before +/// revm builds anything, so without the guard a system contract could be reached at any depth. +/// `CALLCODE` and `DELEGATECALL` never reach an interceptor and are left to revm's own check. +fn call_too_deep(frame_init: &FrameInit) -> Option { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; + let guarded = matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall); + (guarded && frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { + synthetic_frame_result( + &frame_init.frame_input, + InstructionResult::CallTooDeep, + Bytes::new(), + ) + }) +} + /// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. #[cold] #[inline(never)] diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs new file mode 100644 index 000000000..3cfc547a3 --- /dev/null +++ b/crates/mega-evm/src/evm/frame.rs @@ -0,0 +1,248 @@ +//! Frame results built without running a frame, and how they settle. +//! +//! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, and, +//! when they land, the system contract interceptors, precompile normalisation and native keyless +//! deployment. Such a result goes back to the caller like any frame's, and the caller settles it +//! the way revm settles a frame it ran: +//! +//! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) +//! is priced for refund when the frame failed; +//! 2. [`handle_reservoir_remaining_gas`] merges the frame's gas into the caller's: unused regular +//! gas back on success and revert, the frame's reservoir adopted as the caller's own; +//! 3. the refund is refilled into the caller's reservoir. +//! +//! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries +//! the reservoir the frame inherited ([`untouched_call_gas`], [`with_pools_of`]), never +//! `Gas::new(limit)`, which would carry none and bill the sender for the whole reservoir; and it +//! carries the calling opcode's upfront-charge flags, so step 1 refunds the charge. +//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is the settlement, for a +//! mechanism that settles a result into a running frame itself. + +use alloy_primitives::Bytes; +use revm::{ + context::{result::FromStringError, ContextTr}, + context_interface::{cfg::gas::GasTracker, context::take_error, Host}, + handler::{handle_reservoir_remaining_gas, FrameResult}, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, + InterpreterResult, + }, +}; + +/// The gas of a call result built without running the callee: the call's whole gas limit +/// unspent, and the reservoir the call inherited. +#[inline] +pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) +} + +/// The gas of a creation result built without running the init code: its whole gas limit +/// unspent, and the reservoir the creation inherited. +#[inline] +pub fn untouched_create_gas(inputs: &CreateInputs) -> Gas { + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) +} + +/// `gas_limit` of fresh regular gas carrying `source`'s EIP-8037 pools: its reservoir, the state +/// and history gas it charged, and the part of those charges that spilled onto regular gas. +/// +/// For a result whose regular gas is rebuilt (a precompile's output normalised to the gas limit +/// the caller forwarded): the caller keeps the frame's state and history charges on success and +/// rolls them back on failure, so a rebuilt `Gas` that dropped them would hand the caller an +/// empty reservoir and charges the frame never made. +#[inline] +pub const fn with_pools_of(gas_limit: u64, source: &Gas) -> Gas { + let mut gas = Gas::new(gas_limit); + gas.set_reservoir(source.reservoir()); + gas.set_state_gas_spent(source.state_gas_spent()); + gas.set_state_gas_spilled(source.state_gas_spilled()); + gas.set_history_gas_spent(source.history_gas_spent()); + gas +} + +/// A result for the frame `input` would start, built without running it: `result` with +/// `output`, the frame's gas untouched and the inherited reservoir carried, and the calling +/// opcode's upfront state-gas flags, as revm builds the results of the frames it answers itself. +pub fn synthetic_frame_result( + input: &FrameInput, + result: InstructionResult, + output: Bytes, +) -> FrameResult { + match input { + FrameInput::Call(inputs) => FrameResult::Call(CallOutcome { + result: InterpreterResult::new(result, output, untouched_call_gas(inputs)), + memory_offset: inputs.return_memory_offset.clone(), + was_precompile_called: false, + precompile_call_logs: Default::default(), + charged_new_account_state_gas: inputs.charged_new_account_state_gas, + charged_state_gas_address: inputs.target_address, + }), + FrameInput::Create(inputs) => FrameResult::Create(CreateOutcome { + result: InterpreterResult::new(result, output, untouched_create_gas(inputs)), + address: None, + charged_create_state_gas: inputs.charged_create_state_gas(), + charged_state_gas_address: inputs.charged_state_gas_address(), + }), + FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), + } +} + +/// Settles `result`'s gas into `caller_gas` exactly as revm's frame return does: the calling +/// opcode's upfront state-gas charge priced for refund, [`handle_reservoir_remaining_gas`], then +/// the refund refilled into the caller's reservoir. +/// +/// `ctx` prices the refund through the same hook the charge went through; a failed lookup is +/// the error the hook recorded. +pub fn settle_frame_result( + ctx: &mut CTX, + caller_gas: &mut GasTracker, + result: &mut FrameResult, +) -> Result<(), ERROR> +where + CTX: ContextTr + Host, + ERROR: From<::Error> + FromStringError, +{ + take_error::(ctx.error())?; + let refund = match result.refundable_state_gas_charge() { + Some(charge) => match ctx.state_gas_charge(charge) { + Some(refund) => Some(refund), + None => { + take_error::(ctx.error())?; + return Err(ERROR::from_string("state gas price lookup failed".into())); + } + }, + None => None, + }; + let instruction_result = result.instruction_result(); + handle_reservoir_remaining_gas(instruction_result, caller_gas, result.gas_mut().tracker_mut()); + if let Some(refund) = refund { + caller_gas.refill_reservoir(refund); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, Address, U256}; + use revm::interpreter::{CallInput, CallScheme, CallValue}; + + const TARGET: Address = address!("0000000000000000000000000000000000001234"); + + fn call_inputs(gas_limit: u64, reservoir: u64, charged: bool) -> CallInputs { + CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 3..7, + gas_limit, + bytecode_address: TARGET, + known_bytecode: Default::default(), + target_address: TARGET, + caller: Address::ZERO, + value: CallValue::Transfer(U256::from(1)), + scheme: CallScheme::Call, + is_static: false, + reservoir, + charged_new_account_state_gas: charged, + } + } + + /// The untouched gas is the gas limit unspent and the inherited reservoir, not a fresh + /// `Gas::new(limit)`. + #[test] + fn test_untouched_call_gas_carries_the_reservoir() { + let gas = untouched_call_gas(&call_inputs(50_000, 7_000, false)); + assert_eq!(gas.limit(), 50_000); + assert_eq!(gas.remaining(), 50_000); + assert_eq!(gas.reservoir(), 7_000); + assert_ne!(gas, Gas::new(50_000)); + } + + /// Rebuilding the regular gas keeps every EIP-8037 pool of the source. + #[test] + fn test_with_pools_of_keeps_the_pools() { + let mut source = Gas::new_with_regular_gas_and_reservoir(100, 1_000); + assert!(source.record_state_cost(1_050)); + assert!(source.record_history_cost(20)); + let rebuilt = with_pools_of(70, &source); + assert_eq!(rebuilt.limit(), 70); + assert_eq!(rebuilt.remaining(), 70); + assert_eq!(rebuilt.reservoir(), source.reservoir()); + assert_eq!(rebuilt.state_gas_spent(), 1_050); + assert_eq!(rebuilt.state_gas_spilled(), source.state_gas_spilled()); + assert_eq!(rebuilt.history_gas_spent(), 20); + } + + /// A synthetic call result carries the return range, the untouched gas and the upfront + /// charge flags of its inputs. + #[test] + fn test_synthetic_call_result_carries_the_inputs() { + let input = FrameInput::Call(Box::new(call_inputs(9_000, 11, true))); + let FrameResult::Call(outcome) = synthetic_frame_result( + &input, + InstructionResult::CallTooDeep, + Bytes::from_static(b"x"), + ) else { + panic!("a call input gives a call result"); + }; + assert_eq!(outcome.result.result, InstructionResult::CallTooDeep); + assert_eq!(outcome.result.output, Bytes::from_static(b"x")); + assert_eq!(outcome.result.gas, Gas::new_with_regular_gas_and_reservoir(9_000, 11)); + assert_eq!(outcome.memory_offset, 3..7); + assert!(outcome.charged_new_account_state_gas); + assert_eq!(outcome.charged_state_gas_address, TARGET); + assert!(!outcome.was_precompile_called); + } + + /// Settling a failed synthetic call into its caller returns the forwarded gas, keeps the + /// caller's reservoir, and refunds the new-account charge the calling opcode made, as revm's + /// frame return does. + #[test] + fn test_settle_frame_result_refunds_the_upfront_charge() { + use revm::{ + context::{CfgEnv, Context}, + context_interface::cfg::{GasId, GasParams}, + database::EmptyDB, + primitives::hardfork::SpecId, + MainContext, + }; + let mut cfg = CfgEnv::new_with_spec(SpecId::AMSTERDAM); + cfg.enable_amsterdam_eip8037 = true; + cfg.gas_params = GasParams::new_spec(SpecId::AMSTERDAM); + let new_account = cfg.gas_params.get(GasId::new_account_state_gas()); + assert!(new_account > 0); + let mut ctx = Context::mainnet().with_db(EmptyDB::default()).with_cfg(cfg); + + // The caller forwarded 9,000 gas and charged a new account from its 1M reservoir. + let reservoir = 1_000_000; + let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); + assert!(caller.record_state_cost(new_account)); + let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); + let mut result = + synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); + + settle_frame_result::<_, revm::context::result::EVMError>( + &mut ctx, + &mut caller, + &mut result, + ) + .unwrap(); + assert_eq!(caller.remaining(), 100_000, "the forwarded gas comes back"); + assert_eq!(caller.reservoir(), reservoir, "the charge is refunded to the reservoir"); + assert_eq!(caller.state_gas_spent(), 0); + + // A successful synthetic result keeps the charge: the account exists. + let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); + assert!(caller.record_state_cost(new_account)); + let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); + let mut result = synthetic_frame_result(&input, InstructionResult::Stop, Bytes::new()); + settle_frame_result::<_, revm::context::result::EVMError>( + &mut ctx, + &mut caller, + &mut result, + ) + .unwrap(); + assert_eq!(caller.remaining(), 100_000); + assert_eq!(caller.reservoir(), reservoir - new_account); + assert_eq!(caller.state_gas_spent(), new_account as i64); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 70e120d68..69255c5dc 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -8,6 +8,7 @@ mod context; mod execution; mod factory; +mod frame; mod host; mod instructions; mod result; @@ -16,6 +17,7 @@ mod spec; pub use context::*; pub use execution::*; pub use factory::*; +pub use frame::*; pub use host::*; pub use result::*; pub use spec::*; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 54d88b265..a38d37657 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -36,14 +36,14 @@ Do not add a `_pending/main.rs`. | the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | -| the system contract interceptors | 65 | 57 | 8 | 56 | 9 | 0 | +| the system contract interceptors | 62 | 54 | 8 | 53 | 9 | 0 | | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **731** | **607** | **124** | **410** | **293** | **28** | +| **Total** | **728** | **604** | **124** | **407** | **293** | **28** | ## Tests ported in place @@ -114,13 +114,14 @@ It becomes assertable with the common execution layer, which defines the frame o ## Tests ported by the common execution layer -These 40 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 43 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `equivalence/evm_state.rs` | the common execution layer (3) | 3 | `tests/satin/state.rs` | | `mini_rex/db_error.rs` | the common execution layer (4) | 4 | `tests/satin/db_error.rs` | | `rex4/eip7702_delegation_cycle.rs` | the common execution layer (1) | 1 | `tests/satin/state.rs` | +| `rex5/call_too_deep_guard.rs` | the system contract interceptors (3) | 3 | `tests/satin/synthetic_frame_gas.rs` | | `rex5/frame_target_updated_dedup.rs` | the common execution layer (5) | 5 | `tests/satin/write_records.rs` | | `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | | `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | @@ -128,7 +129,7 @@ These 40 rows run in a real test target now, adapted to the Satin API, so the co | `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | | `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | -| **Total** | | **40** | | +| **Total** | | **43** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -182,7 +183,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | -| `rex5/call_too_deep_guard.rs` | 4 | keep 4 (the system contract interceptors · the synthetic-result contract of the common execution layer) | +| `rex5/call_too_deep_guard.rs` | 1 | keep 1 (the system contract interceptors · the synthetic-result contract of the common execution layer) | | `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | | `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | diff --git a/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs b/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs index 009cf52f1..2fb6f2b2f 100644 --- a/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs +++ b/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs @@ -54,74 +54,6 @@ fn make_call_frame_init(target: Address, selector: [u8; 4], depth: usize) -> Fra } } -fn assert_call_too_deep(outcome_result: &FrameResult) { - let FrameResult::Call(outcome) = outcome_result else { - panic!("expected a Call frame result, got {:?}", outcome_result); - }; - assert_eq!( - outcome.result.result, - InstructionResult::CallTooDeep, - "depth guard should produce CallTooDeep" - ); - assert_eq!(outcome.result.gas.spent(), 0, "no gas should be spent on CallTooDeep"); - assert_eq!( - outcome.result.gas.remaining(), - GAS_LIMIT, - "all forwarded gas should be available for caller refund" - ); -} - -#[test] -fn test_rex5_depth_guard_returns_call_too_deep_for_system_contract() { - // REX5: a Call to a system contract at depth > CALL_STACK_LIMIT short-circuits with - // CallTooDeep before any interceptor runs. The selector targets a real system - // contract handler (AccessControlInterceptor::disableVolatileDataAccess) so the - // test would also detect a regression that lets the interceptor fire. - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(frame_result) = result else { - panic!("expected Result variant, got Item"); - }; - assert_call_too_deep(&frame_result); - - // Side-effect check: AccessControlInterceptor would have called disable_access(depth) - // on the volatile tracker if it had fired. Confirm it did not. - let ctx = evm.ctx_ref(); - assert!( - !ctx.volatile_data_tracker.borrow().volatile_access_disabled(CALL_STACK_LIMIT as usize), - "interceptor must not have fired", - ); -} - -#[test] -fn test_rex5_depth_boundary_allows_call_at_limit() { - // REX5: depth == CALL_STACK_LIMIT is the last permitted depth. The depth guard does - // not fire and the interceptor should run normally (matches revm's `depth > limit` - // boundary in `make_call_frame`). - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result from interceptor"); - }; - // At depth == CALL_STACK_LIMIT the interceptor still runs and returns its synthetic - // Return result; the depth guard's CallTooDeep would have aborted execution otherwise. - assert_eq!(outcome.result.result, InstructionResult::Return); -} - #[test] fn test_rex5_exceeded_tx_limit_wins_over_call_too_deep() { // Priority-ordering regression: when both a TX-level additional-limit exceed AND @@ -164,65 +96,3 @@ fn test_rex5_exceeded_tx_limit_wins_over_call_too_deep() { "exceeded-limit halt must take priority over CallTooDeep depth guard", ); } - -/// Inspector that unconditionally intercepts every CALL by returning a synthetic -/// success outcome from `call(...)`. Tracks how many times `call` and `call_end` -/// fire so the test can verify the inspector callback pairing is preserved. -#[derive(Default)] -struct AlwaysInterceptInspector { - call_count: usize, - call_end_count: usize, -} - -impl Inspector for AlwaysInterceptInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - self.call_count += 1; - Some(CallOutcome { - result: InterpreterResult { - result: InstructionResult::Stop, - output: Bytes::new(), - gas: Gas::new(inputs.gas_limit), - }, - memory_offset: inputs.return_memory_offset.clone(), - }) - } - - fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.call_end_count += 1; - } -} - -#[test] -fn test_rex5_inspect_frame_init_depth_guard_overrides_inspector() { - // REX5 inspect mirror: when an inspector returns Some(output) for a call past - // CALL_STACK_LIMIT, the depth guard must: - // 1. Override the inspector's success with CallTooDeep - // 2. Still call `call_end` so the inspector's start/end pairs balance - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let evm = MegaEvm::new(context); - let mut evm = evm.with_inspector(AlwaysInterceptInspector::default()); - - // Target a regular address (not a system contract). The inspector will intercept; - // without the depth guard, the inspector's synthetic Stop result would survive. - let target = address!("0000000000000000000000000000000000300001"); - let frame_init = make_call_frame_init(target, [0u8; 4], CALL_STACK_LIMIT as usize + 1); - - let result = InspectorEvmTr::inspect_frame_init(&mut evm, frame_init) - .expect("inspect_frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result"); - }; - // Depth guard wins over inspector synthetic Stop. - assert_eq!( - outcome.result.result, - InstructionResult::CallTooDeep, - "depth guard must override inspector's synthetic output", - ); - // call_end must have fired to keep the inspector start/end pair balanced. If a - // future refactor drops the `frame_end(...)` from the depth-guard early return, - // this asserts catches it. - let insp = evm.inspector(); - assert_eq!(insp.call_count, 1, "inspector should see exactly one call_start"); - assert_eq!(insp.call_end_count, 1, "inspector's call_end must be paired"); -} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 625602213..848851307 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,4 +4,5 @@ mod common; mod db_error; mod equivalence; mod state; +mod synthetic_frame_gas; mod write_records; diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs new file mode 100644 index 000000000..d5f0fed5e --- /dev/null +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -0,0 +1,125 @@ +//! Frame results `MegaETH` builds without running a frame carry the reservoir the frame +//! inherited and settle like revm's own. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{test_utils::MemoryDatabase, MegaEvm}; +use revm::{ + context::{ContextTr, JournalTr}, + handler::{EvmTr, FrameResult, ItemOrResult}, + inspector::InspectorEvmTr, + interpreter::{ + interpreter::SharedMemory, interpreter_action::FrameInit, + interpreter_types::InterpreterTypes, CallInput, CallInputs, CallOutcome, CallScheme, + CallValue, FrameInput, Gas, InstructionResult, InterpreterResult, + }, + primitives::CALL_STACK_LIMIT, + Inspector, +}; + +use crate::common::context; + +const CALLER: Address = address!("0000000000000000000000000000000000300010"); +const TARGET: Address = address!("0000000000000000000000000000000000300001"); +const GAS_LIMIT: u64 = 100_000; +const RESERVOIR: u64 = 7_000_000; + +fn call_frame_init(depth: usize) -> FrameInit { + FrameInit { + depth, + memory: SharedMemory::new(), + frame_input: FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: GAS_LIMIT, + bytecode_address: TARGET, + known_bytecode: Default::default(), + target_address: TARGET, + caller: CALLER, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + reservoir: RESERVOIR, + charged_new_account_state_gas: false, + })), + } +} + +fn assert_call_too_deep(result: &FrameResult) { + let FrameResult::Call(outcome) = result else { panic!("expected a call result: {result:?}") }; + assert_eq!(outcome.result.result, InstructionResult::CallTooDeep); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT, "the forwarded gas is untouched"); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR, "the inherited reservoir is carried"); + assert_eq!(outcome.result.gas.state_gas_spent(), 0); +} + +/// A call past the call-stack limit is answered with `CallTooDeep` before anything could +/// intercept it, with the forwarded gas untouched and the inherited reservoir carried. +#[test] +fn test_depth_guard_returns_call_too_deep_with_the_inherited_reservoir() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize + 1)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("no frame is built past the limit") }; + assert_call_too_deep(&result); +} + +/// `CALL_STACK_LIMIT` itself is the last permitted depth: the guard does not fire there. +#[test] +fn test_depth_boundary_allows_call_at_limit() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account(TARGET).unwrap(); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("a call to an account without code is answered at once"); + }; + assert_eq!(outcome.result.result, InstructionResult::Stop, "the call went through"); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR); +} + +/// Answers every call itself, and counts the calls and their ends. +#[derive(Default)] +struct AlwaysAnswers { + calls: usize, + call_ends: usize, +} + +impl Inspector for AlwaysAnswers { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + self.calls += 1; + Some(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + } + + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.call_ends += 1; + } +} + +/// An inspector's answer to a call past the limit gives way to `CallTooDeep`, and the inspector +/// still sees the call end. +#[test] +fn test_inspect_frame_init_depth_guard_overrides_inspector() { + let mut evm = + MegaEvm::new(context(MemoryDatabase::default())).with_inspector(AlwaysAnswers::default()); + let result = InspectorEvmTr::inspect_frame_init( + &mut evm, + call_frame_init(CALL_STACK_LIMIT as usize + 1), + ) + .expect("inspect_frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("the frame was answered") }; + assert_call_too_deep(&result); + assert_eq!( + (evm.inspector().calls, evm.inspector().call_ends), + (1, 1), + "call and call_end pair" + ); +} From ed7358cd6373d30dead611d5d01ba13b282063d6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:42:33 +0800 Subject: [PATCH 059/201] feat: stop transactions that cross a limit with a latched revert --- crates/mega-evm/src/evm/context.rs | 17 +- crates/mega-evm/src/evm/execution.rs | 123 +++++- crates/mega-evm/src/evm/instructions.rs | 42 +- crates/mega-evm/src/limit/frame_limit.rs | 12 +- crates/mega-evm/src/limit/limit.rs | 153 +++++++- crates/mega-evm/src/limit/mod.rs | 38 ++ crates/mega-evm/tests/_pending/README.md | 11 +- .../_pending/rex5/call_too_deep_guard.rs | 98 ----- crates/mega-evm/tests/_pending/rex5/main.rs | 1 - crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/strategic_stop.rs | 370 ++++++++++++++++++ .../tests/satin/synthetic_frame_gas.rs | 44 ++- 12 files changed, 756 insertions(+), 154 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs create mode 100644 crates/mega-evm/tests/satin/strategic_stop.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 4e334a65a..2df14b19c 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -9,8 +9,8 @@ use revm::{ }; use crate::{ - constants, AdditionalLimit, EmptyExternalEnv, ExternalEnvTypes, ExternalEnvs, MegaSpecId, - MegaTransaction, + constants, AdditionalLimit, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, + ExternalEnvs, MegaSpecId, MegaTransaction, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -109,11 +109,24 @@ impl MegaContext { &self.external_envs } + /// Enforces `limits` on every transaction from now on. + pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.additional_limit.set_limits(limits); + self + } + /// The common execution layer's state for the running (or last) transaction. pub const fn additional_limit(&self) -> &AdditionalLimit { &self.additional_limit } + /// The common execution layer's state, mutably. For tests and tools that drive the abort + /// protocol directly. + #[cfg(any(test, feature = "test-utils"))] + pub const fn additional_limit_mut(&mut self) -> &mut AdditionalLimit { + &mut self.additional_limit + } + /// Prepares the common execution layer for a new transaction or system call. pub(crate) fn on_new_tx(&mut self) { self.additional_limit.reset(); diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index e25823ab8..43b8579a9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -21,22 +21,25 @@ use revm::{ context_interface::{cfg::gas::GasTracker, journaled_state::entry::JournalEntry}, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, + instructions::InstructionProvider, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, }, inspector::{ - handler::{frame_end, frame_start}, + handler::{frame_end, frame_start, inspect_instructions}, InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, - InitialAndFloorGas, InstructionResult, + InitialAndFloorGas, InstructionResult, InterpreterAction, }, primitives::{Address, Bytes, CALL_STACK_LIMIT}, Database, Inspector, Journal, }; -use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext, MegaEvm, MegaInstructions}; +use crate::{ + synthetic_frame_result, ExternalEnvTypes, LimitCheck, MegaContext, MegaEvm, MegaInstructions, +}; /// The Satin handler. /// @@ -123,9 +126,11 @@ where self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } - /// Settles the outermost frame: pops its lane, then settles its gas into the transaction's as - /// op-revm does (op-revm replaces revm's settlement, so revm's never runs here), and keeps - /// the history gas the transaction spent. + /// Settles the outermost frame: pops its lane and, when the transaction is latched, turns its + /// result into the latched stop; then settles its gas into the transaction's as op-revm does + /// (op-revm replaces revm's settlement, so revm's never runs here): a stopped transaction + /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. + /// Keeps the history gas the transaction spent. fn last_frame_result( &mut self, evm: &mut Self::Evm, @@ -232,12 +237,14 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { + if let Some(latched) = self.inner.ctx.additional_limit.latched().copied() { + self.inner.ctx.additional_limit.push_empty_frame(); + return Ok(ItemOrResult::Result(stopped_frame_result(&frame_init, &latched))); + } if let Some(result) = call_too_deep(&frame_init) { self.inner.ctx.additional_limit.push_empty_frame(); return Ok(ItemOrResult::Result(result)); @@ -256,7 +267,10 @@ impl EvmTr for MegaEvm 0 => { @@ -285,21 +299,39 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - self.inner.frame_run() + let evm = &mut self.inner; + let frame = evm.frame_stack.get(); + let ctx = &mut evm.ctx; + let action = match before_frame_run(ctx, frame) { + Some(action) => action, + None => frame.interpreter.run_plain( + evm.instruction.instruction_table(), + evm.instruction.gas_table(), + ctx, + ), + }; + frame.process_next_action(ctx, action).inspect(|next| { + if next.is_result() { + frame.set_finished(true); + } + }) } - /// Pops the returning frame's lane (merged on success, discarded on failure), then returns the - /// result to the caller as revm does. + /// Pops the returning frame's lane (merged on success, discarded on failure; under a latch the + /// result is first rewritten to the stop), then returns the result to the caller as revm + /// does. #[inline] fn frame_return_result( &mut self, - result: FrameResult, + mut result: FrameResult, ) -> Result, ContextDbError> { - self.inner.ctx.additional_limit.on_frame_return(&result); + self.inner.ctx.additional_limit.on_frame_return(&mut result); self.inner.frame_return_result(result) } } @@ -355,9 +387,12 @@ where ) -> Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - // The inspector answered the frame. The depth guard still holds: an answer cannot + // The inspector answered the frame. The latch and the depth guard still hold, in + // `frame_init`'s order: an answer cannot start a frame of a stopped transaction, nor // reach past the call-stack limit. - if let Some(too_deep) = call_too_deep(&frame_init) { + if let Some(latched) = ctx.additional_limit.latched().copied() { + output = stopped_frame_result(&frame_init, &latched); + } else if let Some(too_deep) = call_too_deep(&frame_init) { output = too_deep; } ctx.additional_limit.push_empty_frame(); @@ -391,6 +426,56 @@ where inspector.initialize_interp(&mut frame.interpreter, ctx); Ok(ItemOrResult::Item(frame)) } + + /// revm's inspected frame run, with the latch short-circuit of [`EvmTr::frame_run`]: a frame + /// of a latched transaction returns the stop without a step, and the inspector sees it end. + #[inline] + fn inspect_frame_run( + &mut self, + ) -> Result, ContextDbError> { + let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); + let action = match before_frame_run(ctx, frame) { + Some(action) => action, + None => inspect_instructions( + ctx, + &mut frame.interpreter, + &mut *inspector, + instructions.instruction_table(), + instructions.gas_table(), + ), + }; + let mut next = frame.process_next_action(ctx, action); + if let Ok(ItemOrResult::Result(result)) = &mut next { + frame_end(ctx, inspector, &frame.input, result); + frame.set_finished(true); + } + next + } +} + +/// The action of a frame about to run: the latched stop, returned without running an +/// instruction, when the transaction is latched; `None` otherwise, and the frame runs. +/// +/// A frame runs here for the first time or after a child returned into it. Under a latch it is +/// the latter: the child that crossed the limit reverted, and its caller must not resume. +#[inline] +fn before_frame_run( + ctx: &MegaContext, + frame: &EthFrame, +) -> Option { + let latched = ctx.additional_limit.latched()?; + Some(InterpreterAction::new_return( + InstructionResult::Revert, + latched.revert_data(), + frame.interpreter.gas, + )) +} + +/// The result of a frame a limit stopped before it ran: a revert with the stop's +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a +/// [`synthetic_frame_result`] that settles like a frame revm ran. +fn stopped_frame_result(frame_init: &FrameInit, check: &LimitCheck) -> FrameResult { + synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, check.revert_data()) } impl MegaEvm { diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 8269e692b..acb82a35c 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -8,6 +8,10 @@ //! 2. run revm's instruction, whose Host call stages the record; //! 3. commit the record if the opcode completed, discard it if the opcode failed. //! +//! A commit that crosses a limit stops the opcode's frame with a revert whose output is +//! [`MegaLimitExceeded`](crate::MegaLimitExceeded) (see +//! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). +//! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. @@ -15,14 +19,15 @@ use revm::{ bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, handler::instructions::EthInstructions, interpreter::{ - instructions::host, interpreter::EthInterpreter, Instruction, InstructionContext, - InstructionExecResult, + instructions::host, interpreter::EthInterpreter, interpreter_types::LoopControl, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, + InterpreterAction, }, primitives::hardfork::SpecId, Database, }; -use crate::{ExternalEnvTypes, MegaContext}; +use crate::{ExternalEnvTypes, LimitCheck, MegaContext}; use super::MegaInstructions; @@ -71,11 +76,36 @@ fn commit_after( Ok(()) => true, Err(result) => result.is_ok(), }; - if completed { - host.additional_limit.commit_staged_record(); - } else { + if !completed { host.additional_limit.discard_staged_record(); + return result; + } + let check = host.additional_limit.commit_staged_record(); + if check.exceeded_limit() { + return Err(stop_frame(interpreter, &check)); + } + result +} + +/// Stops the running frame with the revert a crossed limit asks for: its output is +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) and its gas is the frame's, so the caller gets +/// the unspent part back. +#[cold] +#[inline(never)] +fn stop_frame( + interpreter: &mut Interpreter, + check: &LimitCheck, +) -> InstructionResult { + if interpreter.bytecode.action().is_some() { + // A `SELFDESTRUCT` or a return the opcode already set gives way to the stop. + let _ = interpreter.take_next_action(); } + let result = InstructionResult::Revert; + interpreter.bytecode.set_action(InterpreterAction::new_return( + result, + check.revert_data(), + interpreter.gas, + )); result } diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 1f1fa8ae5..5c8bfc750 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -58,6 +58,16 @@ impl Lane { pub(crate) const fn empty() -> Self { Self::new(None, false, u64::MAX) } + + /// What the frame keeps if it succeeds. + pub(crate) const fn net(&self) -> LimitUsage { + self.used.saturating_sub(self.refund) + } + + /// The data-size bytes the frame may still keep. + pub(crate) const fn remaining_budget(&self) -> u64 { + self.budget.saturating_sub(self.net().data_size) + } } /// The lanes of the running transaction. @@ -295,7 +305,7 @@ mod tests { let frame_1 = t.pop(false).expect("frame 1 popped"); assert_eq!(t.net(), t.net_uncached()); assert_eq!(t.net(), bytes(100), "only the transaction's own usage is left"); - assert_eq!(frame_1.used.saturating_sub(frame_1.refund), bytes(30 + 15 + 6 - 10 - 3 - 1)); + assert_eq!(frame_1.net(), bytes(30 + 15 + 6 - 10 - 3 - 1)); t.reset(); assert_eq!(t.net(), t.net_uncached()); diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 5c5f40463..48d8099cf 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,24 +1,43 @@ //! The per-transaction state of the common execution layer. use alloy_primitives::Address; -use revm::{handler::FrameResult, interpreter::FrameInput}; +use revm::{ + handler::FrameResult, + interpreter::{FrameInput, InstructionResult}, +}; use super::{ frame_limit::{FrameLimitTracker, Lane}, record::{RecordEffect, StagedRecord}, - LimitUsage, WRITE_RECORD, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, }; /// What the common execution layer tracks for the running transaction: the per-frame lanes of -/// data-size bytes and write records, and the record the Host staged for the running opcode. +/// data-size bytes and write records, the record the Host staged for the running opcode, and the +/// latch of a transaction a limit stopped. /// /// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and /// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) -/// and the frame lifecycle (lanes). +/// and the frame lifecycle (lanes, the latch). +/// +/// # The abort protocol +/// +/// A transaction-level limit stops the transaction with a revert, not a halt. The frame that +/// crosses the limit reverts with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output +/// and the transaction is latched ([`latch`](Self::latch)). From then on no frame runs another +/// instruction: a caller that gets the reverted result back returns the same revert instead of +/// resuming, a frame about to start is answered with it, and every result returned above is +/// rewritten to it. The outermost frame settles like any EIP-8037 revert: its unspent regular gas +/// and the reservoir go back to the sender, who pays only for what ran. A frame budget crossed +/// reverts that frame alone, without a latch, and its caller resumes. Exceptional halts (a real +/// out-of-gas, an invalid opcode) are not limit stops and still burn the frame's gas. #[derive(Clone, Debug, Default)] pub struct AdditionalLimit { pub(crate) tracker: FrameLimitTracker, staged: Option, + limits: EvmTxRuntimeLimits, + /// The transaction-level stop, once a limit latched one. + latched: Option, /// Whether the transaction's call target is an applied EIP-7702 authority, whose account /// write the transaction's lane already counts. target_is_authority: bool, @@ -27,14 +46,81 @@ pub struct AdditionalLimit { } impl AdditionalLimit { - /// Clears the state for a new transaction, keeping allocations. + /// A layer enforcing `limits`. + pub fn new(limits: EvmTxRuntimeLimits) -> Self { + Self { limits, ..Default::default() } + } + + /// The limits enforced. + pub const fn limits(&self) -> &EvmTxRuntimeLimits { + &self.limits + } + + /// Replaces the limits enforced from the next transaction on. + pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.limits = limits; + } + + /// Clears the state for a new transaction, keeping allocations and the limits. pub(crate) fn reset(&mut self) { self.tracker.reset(); self.staged = None; + self.latched = None; self.target_is_authority = false; self.history_gas_spent = 0; } + /* The latch */ + + /// The stop a transaction-level limit latched, if any. + pub const fn latched(&self) -> Option<&LimitCheck> { + self.latched.as_ref() + } + + /// Latches the transaction: `kind`'s transaction-level `limit` was crossed at `used`. The + /// running frame must stop with [`LimitCheck::revert_data`]; the frame lifecycle stops every + /// frame above it. A later latch does not replace the first. + pub fn latch(&mut self, kind: LimitKind, limit: u64, used: u64) -> LimitCheck { + *self.latched.get_or_insert(LimitCheck::ExceedsLimit { + kind, + limit, + used, + frame_local: false, + }) + } + + /// Checks the limits after the running frame counted something: the transaction's data size + /// against its limit (latching on a crossing), then the running frame's against its budget. + fn check(&mut self) -> LimitCheck { + let used = self.tracker.net().data_size; + if used > self.limits.tx_data_size_limit { + return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); + } + if let Some(lane) = self.tracker.current() { + let used = lane.net().data_size; + if used > lane.budget { + return LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: lane.budget, + used, + frame_local: true, + }; + } + } + LimitCheck::WithinLimit + } + + /// Rewrites `result` to the latched stop, when the transaction is latched: a success or a + /// revert becomes the latched revert. A halt stays what it is. + fn apply_latch(&self, result: &mut FrameResult) { + let Some(latched) = &self.latched else { return }; + let interpreter_result = result.interpreter_result_mut(); + if interpreter_result.result.is_ok_or_revert() { + interpreter_result.result = InstructionResult::Revert; + interpreter_result.output = latched.revert_data(); + } + } + /// What the transaction keeps so far: its data-size bytes and write records, with every /// running frame counted as if it succeeds. pub fn usage(&self) -> LimitUsage { @@ -65,14 +151,20 @@ impl AdditionalLimit { } /// Commits the staged record to the running frame's lane. Called by an opcode's wrapper once - /// the opcode completed. + /// the opcode completed; a crossed limit in the verdict stops the opcode's frame. #[inline] - pub(crate) fn commit_staged_record(&mut self) { - let Some(record) = self.staged.take() else { return }; + pub(crate) fn commit_staged_record(&mut self) -> LimitCheck { + let Some(record) = self.staged.take() else { return LimitCheck::WithinLimit }; match record.effect() { - RecordEffect::None => {} - RecordEffect::Record(usage) => self.tracker.record(usage), - RecordEffect::Refund(usage) => self.tracker.refund(usage), + RecordEffect::None => LimitCheck::WithinLimit, + RecordEffect::Record(usage) => { + self.tracker.record(usage); + self.check() + } + RecordEffect::Refund(usage) => { + self.tracker.refund(usage); + LimitCheck::WithinLimit + } } } @@ -102,6 +194,9 @@ impl AdditionalLimit { ) { self.target_is_authority = target_is_authority; self.tracker.record(WRITE_RECORD.times(authorities)); + // Crossing the limit here latches the transaction before its first frame, which is then + // answered with the stop without running. + self.check(); } /* Frame lanes */ @@ -113,7 +208,23 @@ impl AdditionalLimit { /// - a creation: the created account, and the creator's nonce (once per creator frame); /// - the transaction's own frame: the value recipient or the created account. The sender's /// account is part of the transaction body, not a record here. - pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) { + /// + /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. + /// So is every frame of a latched transaction, whose lane stays empty. + pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { + if let Some(latched) = self.latched { + self.push_empty_frame(); + return latched; + } + self.push_lane(input, depth); + self.check() + } + + fn push_lane(&mut self, input: &FrameInput, depth: usize) { + let budget = match self.tracker.current() { + Some(caller) => caller.remaining_budget().min(self.limits.frame_data_size_limit), + None => self.limits.frame_data_size_limit, + }; match input { FrameInput::Call(inputs) => { let target = inputs.target_address; @@ -123,7 +234,7 @@ impl AdditionalLimit { self.tracker.push(Lane::new( Some(target), written_outside || transfers_value, - u64::MAX, + budget, )); if transfers_value && !written_outside { self.tracker.record(WRITE_RECORD); @@ -133,7 +244,7 @@ impl AdditionalLimit { let inherited = self.tracker.current().is_some_and(|caller| { caller.address == Some(target) && caller.account_recorded }); - self.tracker.push(Lane::new(Some(target), inherited || transfers_value, u64::MAX)); + self.tracker.push(Lane::new(Some(target), inherited || transfers_value, budget)); if transfers_value { self.tracker.record_caller(false); if target != inputs.caller { @@ -142,7 +253,7 @@ impl AdditionalLimit { } } FrameInput::Create(_) => { - self.tracker.push(Lane::new(None, true, u64::MAX)); + self.tracker.push(Lane::new(None, true, budget)); self.tracker.record(WRITE_RECORD); if depth > 0 { self.tracker.record_caller(true); @@ -171,18 +282,22 @@ impl AdditionalLimit { } /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, - /// a failure discards it. - pub(crate) fn on_frame_return(&mut self, result: &FrameResult) { + /// a failure discards it. Under a latch the result is first rewritten to the latched stop, + /// whatever produced it (an interceptor, an inspector's rewrite), so no success passes it. + pub(crate) fn on_frame_return(&mut self, result: &mut FrameResult) { + self.apply_latch(result); self.tracker.pop(result.instruction_result().is_ok()); } /// Settles the transaction's outermost frame: pops its lane unless the frame already /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever - /// it ran. - pub(crate) fn on_last_frame_return(&mut self, result: &FrameResult) { + /// it ran, and rewrites the result to the latched stop. + pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); if self.tracker.depth() == 1 { self.on_frame_return(result); + } else { + self.apply_latch(result); } } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 32ed3cb92..669d256e5 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -41,6 +41,44 @@ pub struct LimitUsage { pub write_records: u64, } +/// Limits the common execution layer enforces on one transaction, for exercising the abort +/// protocol before the mechanisms that own the limits land. Both default to unlimited. +/// +/// The data-size limit replaces them with its own limit and per-frame budget rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EvmTxRuntimeLimits { + /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. + pub tx_data_size_limit: u64, + /// The most data-size bytes one frame may keep, children included, and never more than + /// what its caller has left. Crossing it reverts the frame alone. + pub frame_data_size_limit: u64, +} + +impl Default for EvmTxRuntimeLimits { + fn default() -> Self { + Self::no_limits() + } +} + +impl EvmTxRuntimeLimits { + /// No limit at all. + pub const fn no_limits() -> Self { + Self { tx_data_size_limit: u64::MAX, frame_data_size_limit: u64::MAX } + } + + /// Sets the transaction's data-size limit. + pub const fn with_tx_data_size_limit(mut self, limit: u64) -> Self { + self.tx_data_size_limit = limit; + self + } + + /// Sets the per-frame data-size budget. + pub const fn with_frame_data_size_limit(mut self, limit: u64) -> Self { + self.frame_data_size_limit = limit; + self + } +} + /// One write record. pub(crate) const WRITE_RECORD: LimitUsage = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index a38d37657..5d50342bc 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -36,14 +36,14 @@ Do not add a `_pending/main.rs`. | the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | -| the system contract interceptors | 62 | 54 | 8 | 53 | 9 | 0 | +| the system contract interceptors | 61 | 53 | 8 | 52 | 9 | 0 | | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **728** | **604** | **124** | **407** | **293** | **28** | +| **Total** | **727** | **603** | **124** | **406** | **293** | **28** | ## Tests ported in place @@ -114,14 +114,14 @@ It becomes assertable with the common execution layer, which defines the frame o ## Tests ported by the common execution layer -These 43 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 44 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `equivalence/evm_state.rs` | the common execution layer (3) | 3 | `tests/satin/state.rs` | | `mini_rex/db_error.rs` | the common execution layer (4) | 4 | `tests/satin/db_error.rs` | | `rex4/eip7702_delegation_cycle.rs` | the common execution layer (1) | 1 | `tests/satin/state.rs` | -| `rex5/call_too_deep_guard.rs` | the system contract interceptors (3) | 3 | `tests/satin/synthetic_frame_gas.rs` | +| `rex5/call_too_deep_guard.rs` | the system contract interceptors (4) | 4 | `tests/satin/synthetic_frame_gas.rs` | | `rex5/frame_target_updated_dedup.rs` | the common execution layer (5) | 5 | `tests/satin/write_records.rs` | | `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | | `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | @@ -129,7 +129,7 @@ These 43 rows run in a real test target now, adapted to the Satin API, so the co | `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | | `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | -| **Total** | | **43** | | +| **Total** | | **44** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -183,7 +183,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | -| `rex5/call_too_deep_guard.rs` | 1 | keep 1 (the system contract interceptors · the synthetic-result contract of the common execution layer) | | `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | | `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | diff --git a/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs b/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs deleted file mode 100644 index 2fb6f2b2f..000000000 --- a/crates/mega-evm/tests/_pending/rex5/call_too_deep_guard.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Tests for the REX5+ `CALL_STACK_LIMIT` depth guard before system contract -//! interceptor dispatch. -//! -//! Pre-REX5: an attacker who could already build the call stack to revm's `CALL_STACK_LIMIT` -//! could still invoke a system contract — the interceptor dispatch in `frame_init` ran -//! *before* revm's own depth check (which only fires inside `make_call_frame`), so the -//! synthetic interceptor result bypassed the depth boundary entirely. -//! -//! Under REX5: a `CALL_STACK_LIMIT` check is inserted between the TX-level -//! exceeded-limit guard and interceptor dispatch. Calls past the limit short-circuit -//! with `CallTooDeep` and never reach the interceptors. -//! -//! These tests drive `EvmTr::frame_init` directly with a synthetic [`FrameInit`] at the -//! depth boundary, since recursing 1025 deep through real bytecode is prohibitively -//! expensive. - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, IMegaAccessControl, MegaContext, MegaEvm, MegaSpecId, - ACCESS_CONTROL_ADDRESS, -}; -use revm::{ - context::ContextTr, - handler::{EvmTr, FrameResult, ItemOrResult}, - inspector::InspectorEvmTr, - interpreter::{ - interpreter::SharedMemory, interpreter_action::FrameInit, - interpreter_types::InterpreterTypes, CallInput, CallInputs, CallOutcome, CallScheme, - CallValue, FrameInput, Gas, InstructionResult, InterpreterResult, - }, - primitives::CALL_STACK_LIMIT, - Inspector, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000300010"); -const GAS_LIMIT: u64 = 100_000; - -fn make_call_frame_init(target: Address, selector: [u8; 4], depth: usize) -> FrameInit { - FrameInit { - depth, - memory: SharedMemory::new(), - frame_input: FrameInput::Call(Box::new(CallInputs { - input: CallInput::Bytes(Bytes::copy_from_slice(&selector)), - return_memory_offset: 0..0, - gas_limit: GAS_LIMIT, - bytecode_address: target, - target_address: target, - caller: CALLER, - value: CallValue::Transfer(U256::ZERO), - scheme: CallScheme::Call, - is_static: false, - })), - } -} - -#[test] -fn test_rex5_exceeded_tx_limit_wins_over_call_too_deep() { - // Priority-ordering regression: when both a TX-level additional-limit exceed AND - // a CALL_STACK_LIMIT overflow apply, the exceeded-limit path must win — it carries - // gas rescue semantics that CallTooDeep does not. `frame_init` and - // `inspect_frame_init` must run their existing exceeded-limit check BEFORE the - // new depth guard so the rescue path is preserved. - use mega_evm::{AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, LimitKind}; - use std::{cell::RefCell, rc::Rc}; - - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - // Construct an AdditionalLimit whose `has_exceeded_limit` is pre-set to a TX-level - // exceed. This mirrors the state produced by intrinsic-overflow detection in - // `before_tx_start` without depending on its internal API. - let mut additional = - AdditionalLimit::new(MegaSpecId::REX5, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX5)); - additional.set_has_exceeded_limit_for_test(LimitCheck::ExceedsLimit { - kind: LimitKind::KVUpdate, - limit: 0, - used: 1, - frame_local: false, - }); - context.additional_limit = Rc::new(RefCell::new(additional)); - - let mut evm = MegaEvm::new(context); - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result"); - }; - // TX-level exceed produces OutOfGas (halt path), not CallTooDeep. If the depth - // guard fires first, this assertion fails — CallTooDeep would skip gas rescue. - assert_eq!( - outcome.result.result, - InstructionResult::OutOfGas, - "exceeded-limit halt must take priority over CallTooDeep depth guard", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 0716046c9..a55b33de7 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -1,7 +1,6 @@ //! Tests for `Rex5` hardfork features. mod apply_pending_changes_gas_budget; -mod call_too_deep_guard; mod callcode_storage_gas; mod db_error; mod deposit_caller_accounting; diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 848851307..72714d7de 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,5 +4,6 @@ mod common; mod db_error; mod equivalence; mod state; +mod strategic_stop; mod synthetic_frame_gas; mod write_records; diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs new file mode 100644 index 000000000..f9cf1809b --- /dev/null +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -0,0 +1,370 @@ +//! The abort protocol: a transaction-level limit stops the transaction with a revert. +//! +//! The frame that crosses the limit reverts with `MegaLimitExceeded`, the transaction is latched, +//! no caller resumes, and the transaction settles like an EIP-8037 revert: the sender gets the +//! unspent regular gas and the whole reservoir back. A frame budget reverts only its frame. A real +//! out-of-gas still halts and burns. The limit here is the configurable data-size cap of +//! `EvmTxRuntimeLimits`; a write record is 40 bytes. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, + MegaLimitExceeded, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, SSTORE}, + context::result::{ExecutionResult, ResultAndState}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const A: Address = address!("00000000000000000000000000000000000000A0"); +const B: Address = address!("00000000000000000000000000000000000000B0"); +const C: Address = address!("00000000000000000000000000000000000000C0"); +const D: Address = address!("00000000000000000000000000000000000000D0"); +const GAS_LIMIT: u64 = 1_000_000; + +/// Writes slot 1, calls `next` with all its gas, then writes slot 2 and emits a log: the part +/// after the call is what a resumed caller would run. +fn relay(next: Address) -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP) + .sstore(U256::from(2), U256::from(1)) + .append_many([PUSH0, PUSH0]) + .append(LOG0) + .stop() + .build() +} + +/// Writes slots 1 to 3. +fn writer() -> Bytes { + (1..=3u64) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .stop() + .build() +} + +/// `A -> B -> C -> D`, each writing a slot before its call; `D`, at depth 3, writes three. +fn chain() -> MemoryDatabase { + MemoryDatabase::default() + .account_code(A, relay(B)) + .account_code(B, relay(C)) + .account_code(C, relay(D)) + .account_code(D, writer()) +} + +fn evm_with( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + inspector: INSP, +) -> MegaEvm { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(inspector) +} + +fn run( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + tx: MegaTransaction, +) -> (ResultAndState, Option) { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = evm.transact_raw(tx).unwrap(); + (result, evm.ctx().additional_limit().latched().copied()) +} + +fn cap(bytes: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) +} + +fn limit_exceeded(kind: LimitKind, limit: u64) -> Bytes { + MegaLimitExceeded { kind: kind.as_u8(), limit }.abi_encode().into() +} + +fn assert_stopped(result: &ExecutionResult, kind: LimitKind, limit: u64) { + match result { + ExecutionResult::Revert { output, .. } => { + assert_eq!(output, &limit_exceeded(kind, limit), "the stop's revert data") + } + other => panic!("expected a revert-class stop, got {other:?}"), + } +} + +/// Records every step, and every call result the inspector sees end. +#[derive(Default)] +struct Probe { + steps: Vec, + call_results: Vec<(Address, InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for Probe { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.steps.push(interp.bytecode.opcode()); + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + self.call_results.push(( + inputs.target_address, + outcome.result.result, + outcome.result.output.clone(), + )); + } +} + +/// Crossing the cap at depth 3 reverts the whole transaction with `MegaLimitExceeded`: nothing +/// it wrote or logged stays, no caller runs another instruction, and the transaction is latched. +#[test] +fn test_cap_crossed_at_depth_three_stops_the_transaction() { + // A, B, C and D's first write are four records (160 bytes); D's second crosses 180. + let limit = 180; + for inspect in [false, true] { + let mut evm = evm_with(chain(), cap(limit), Probe::default()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert_stopped(&result.result, LimitKind::DataSize, limit); + assert!(result.result.logs().is_empty()); + for account in [A, B, C, D] { + let storage = &result.state[&account].storage; + assert!(storage.values().all(|slot| !slot.is_changed()), "{account} kept a write"); + } + let latched = evm.ctx().additional_limit().latched().copied(); + assert_eq!( + latched, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: 200, + frame_local: false + }) + ); + if inspect { + let probe = evm.inspector(); + let sstores = probe.steps.iter().filter(|op| matches!(op, &&SSTORE)).count(); + assert_eq!(sstores, 5, "A, B, C and D's first two writes ran"); + assert_eq!(probe.steps.last(), Some(&SSTORE), "nothing ran after the crossing write"); + assert!(!probe.steps.contains(&LOG0), "no caller resumed"); + let stops = probe.call_results.iter().map(|(target, result, output)| { + assert_eq!(output, &limit_exceeded(LimitKind::DataSize, limit)); + (*target, *result) + }); + assert_eq!( + stops.collect::>(), + vec![ + (D, InstructionResult::Revert), + (C, InstructionResult::Revert), + (B, InstructionResult::Revert), + (A, InstructionResult::Revert) + ], + "every frame returned the stop, the deepest first" + ); + } + } +} + +/// With and without an inspector the stopped transaction spends the same gas, and the gas does +/// not depend on what the callers would have run after the call: they never resume. +#[test] +fn test_stop_bills_only_what_ran() { + let gas_of = |db: MemoryDatabase, inspect: bool| { + let mut evm = evm_with(db, cap(180), Probe::default()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 180); + result.result.gas().tx_gas_used() + }; + let plain = gas_of(chain(), false); + assert_eq!(gas_of(chain(), true), plain, "an observing inspector changes nothing"); + assert!(plain < GAS_LIMIT / 2, "the stop does not burn the gas: {plain}"); + + // Callers whose code after the call is far more expensive spend exactly as much. + let heavy = |next: Address| { + let mut code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP); + for slot in 10..30u64 { + code = code.sstore(U256::from(slot), U256::from(1)); + } + code.stop().build() + }; + let db = MemoryDatabase::default() + .account_code(A, heavy(B)) + .account_code(B, heavy(C)) + .account_code(C, heavy(D)) + .account_code(D, writer()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 80); + let light = |next: Address| { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build() + }; + let db = MemoryDatabase::default() + .account_code(A, light(B)) + .account_code(B, light(C)) + .account_code(C, light(D)) + .account_code(D, writer()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); + let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&light_result.result, LimitKind::DataSize, 80); + assert_eq!( + result.result.gas().tx_gas_used(), + light_result.result.gas().tx_gas_used(), + "the code after the calls never ran" + ); +} + +/// The stopped transaction gives the whole reservoir back, and spends the same gas whatever its +/// gas limit, so a limit above the execution cap changes nothing but the refund. +#[test] +fn test_stop_refills_the_reservoir_at_any_gas_limit() { + let at = |gas_limit: u64| { + let (result, _) = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); + assert_stopped(&result.result, LimitKind::DataSize, 180); + *result.result.gas() + }; + let small = at(100_000_000); + let large = at(1_000_000_000); + assert_eq!(small.reservoir_remaining(), 0, "a limit under the cap has no reservoir"); + assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP, "all of it back"); + assert_eq!(small.tx_gas_used(), large.tx_gas_used()); + assert_eq!(small.total_gas_spent(), large.total_gas_spent()); +} + +/// An `SSTORE` that runs out of gas after its Host call records nothing, so a cap of zero does +/// not stop the transaction: it halts out of gas and burns its gas. +#[test] +fn test_true_out_of_gas_still_halts_and_burns() { + let db = MemoryDatabase::default().account_code(A, writer()); + let gas_limit = 21_000 + 5_000; + let (result, latched) = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); + assert!( + matches!( + result.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(revm::context::result::HaltReason::OutOfGas(_)), + .. + } + ), + "{:?}", + result.result + ); + assert_eq!(result.result.gas().tx_gas_used(), gas_limit, "the halt burns the gas"); + assert_eq!(latched, None); +} + +/// A child that runs out of gas halts alone; its caller goes on and writes within the cap. +#[test] +fn test_child_out_of_gas_under_a_cap_does_not_latch() { + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(5_000_u64) + .append(CALL) + .append(POP) + .sstore(U256::from(9), U256::from(1)) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(A, parent).account_code(B, writer()); + let (result, latched) = run(db, cap(40), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&A].storage[&U256::from(9)].present_value(), U256::from(1)); + assert_eq!(latched, None); +} + +/// A cap crossed by the writes the first frame's start makes (a value transfer's recipient) +/// reverts the transaction before the frame runs: the recipient's code never runs, its balance +/// is untouched, and the transaction spends what an empty call does. +#[test] +fn test_cap_crossed_before_the_first_frame_reverts_without_running() { + let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); + let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); + let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 39); + assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); + assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); + + let (empty_call, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); + assert!(empty_call.result.is_success()); + assert_eq!(result.result.gas().tx_gas_used(), empty_call.result.gas().tx_gas_used()); +} + +/// A frame budget reverts the frame that crosses it and nothing else: the caller resumes and the +/// transaction is not latched. +#[test] +fn test_frame_budget_reverts_the_frame_without_a_latch() { + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append(GAS) + .append(CALL) + .append(POP) + .sstore(U256::from(9), U256::from(1)) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(A, parent).account_code(B, writer()); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let mut evm = evm_with(db, limits, Probe::default()); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + result.state[&A].storage[&U256::from(9)].present_value(), + U256::from(1), + "A resumed" + ); + assert!(result.state[&B].storage.values().all(|slot| !slot.is_changed()), "B reverted"); + assert_eq!(evm.ctx().additional_limit().latched(), None); + let (target, outcome, output) = evm.inspector().call_results[0].clone(); + assert_eq!((target, outcome), (B, InstructionResult::Revert)); + assert_eq!(output, limit_exceeded(LimitKind::DataSize, 100)); + assert!(evm.inspector().steps.contains(&SSTORE)); +} + +/// A frame budget crossed by the outermost frame reverts the transaction, still without a latch. +#[test] +fn test_frame_budget_of_the_outermost_frame_reverts_the_transaction() { + let db = MemoryDatabase::default().account_code(A, writer()); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let (result, latched) = run(db, limits, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert_stopped(&result.result, LimitKind::DataSize, 100); + assert_eq!(latched, None); +} + +/// A later latch does not replace the first. +#[test] +fn test_first_latch_wins() { + let mut layer = mega_evm::AdditionalLimit::default(); + let first = layer.latch(LimitKind::KVUpdate, 1, 2); + let second = layer.latch(LimitKind::DataSize, 3, 4); + assert_eq!(first, second); + assert_eq!(layer.latched(), Some(&first)); + assert!(first.exceeded_limit() && !first.is_frame_local()); +} diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index d5f0fed5e..75e7a212c 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -2,7 +2,9 @@ //! inherited and settle like revm's own. use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{test_utils::MemoryDatabase, MegaEvm}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaEvm, +}; use revm::{ context::{ContextTr, JournalTr}, handler::{EvmTr, FrameResult, ItemOrResult}, @@ -16,7 +18,7 @@ use revm::{ Inspector, }; -use crate::common::context; +use crate::common::{call, context}; const CALLER: Address = address!("0000000000000000000000000000000000300010"); const TARGET: Address = address!("0000000000000000000000000000000000300001"); @@ -123,3 +125,41 @@ fn test_inspect_frame_init_depth_guard_overrides_inspector() { "call and call_end pair" ); } + +/// A latched transaction's frame is answered with the stop, even past the call-stack limit: the +/// latch is checked first, and its answer carries the reservoir too. +#[test] +fn test_exceeded_tx_limit_wins_over_call_too_deep() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let stop = evm.ctx_mut().additional_limit_mut().latch(LimitKind::KVUpdate, 0, 1); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize + 1)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("a latched transaction's frame is answered"); + }; + assert_eq!(outcome.result.result, InstructionResult::Revert, "the stop, not CallTooDeep"); + assert_eq!(outcome.result.output, stop.revert_data()); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR); +} + +/// A first frame answered with the stop before it runs gives the whole reservoir back, and costs +/// the same at a gas limit under the execution cap and far above it. +#[test] +fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { + let at = |gas_limit: u64| { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, TARGET, U256::from(1), gas_limit)) + .unwrap(); + assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); + *result.result.gas() + }; + let (small, large) = (at(100_000_000), at(1_000_000_000)); + assert_eq!(small.reservoir_remaining(), 0); + assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); + assert_eq!(small.tx_gas_used(), large.tx_gas_used()); + assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); +} From 4f1ebda02f36fc1c5a490ac66a55442f1165bed6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:46:05 +0800 Subject: [PATCH 060/201] feat: gate block execution on declared observers and refuse creation revivals --- crates/mega-evm/src/evm/execution.rs | 11 +- crates/mega-evm/src/evm/inspector.rs | 292 ++++++++++++++++++ crates/mega-evm/src/evm/mod.rs | 42 ++- crates/mega-evm/tests/satin/inspector.rs | 366 +++++++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 1 + 5 files changed, 704 insertions(+), 8 deletions(-) create mode 100644 crates/mega-evm/src/evm/inspector.rs create mode 100644 crates/mega-evm/tests/satin/inspector.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 43b8579a9..3533f5a5b 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -26,7 +26,7 @@ use revm::{ PreExecutionOutput, }, inspector::{ - handler::{frame_end, frame_start, inspect_instructions}, + handler::{frame_start, inspect_instructions}, InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ @@ -38,7 +38,8 @@ use revm::{ }; use crate::{ - synthetic_frame_result, ExternalEnvTypes, LimitCheck, MegaContext, MegaEvm, MegaInstructions, + evm::inspector::frame_end_checked, synthetic_frame_result, ExternalEnvTypes, LimitCheck, + MegaContext, MegaEvm, MegaInstructions, }; /// The Satin handler. @@ -396,7 +397,7 @@ where output = too_deep; } ctx.additional_limit.push_empty_frame(); - frame_end(ctx, inspector, &frame_init.frame_input, &mut output); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } let frame_input = frame_init.frame_input.clone(); @@ -416,7 +417,7 @@ where } } } - frame_end(ctx, inspector, &frame_input, &mut output); + frame_end_checked(ctx, inspector, &frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } let (ctx, inspector, frame) = self.ctx_inspector_frame(); @@ -446,7 +447,7 @@ where }; let mut next = frame.process_next_action(ctx, action); if let Ok(ItemOrResult::Result(result)) = &mut next { - frame_end(ctx, inspector, &frame.input, result); + frame_end_checked(ctx, inspector, &frame.input, result); frame.set_finished(true); } next diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs new file mode 100644 index 000000000..f2d6088a7 --- /dev/null +++ b/crates/mega-evm/src/evm/inspector.rs @@ -0,0 +1,292 @@ +//! What an inspector may do to a Satin transaction, and the one thing it may not. +//! +//! An inspector is not a passive observer. A callback holding a live interpreter can write to its +//! gas and its pending action, a callback holding a frame's inputs can change them, and every +//! `*_end` callback can rewrite a result's classification, gas and output. Satin keeps no ledger +//! beside revm's `Gas` (compute is the regular gas spent), so an inspector that changes the gas +//! changes what the transaction owes, and a rewriting inspector gets exactly what it asked for. +//! Rewriting is a tool feature, supported and unmeasured. +//! +//! Two things bound it: +//! +//! - **The admission gate.** [`TrustedObserver`] is a declaration, made in source about one +//! inspector type, that none of its callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) +//! built with [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the +//! declaration, and [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what +//! block execution refuses a transaction on: a rewriting inspector has no route to a block. +//! [`DeclaredObserver`] carries the declaration for a tracer whose type cannot, and in debug +//! builds checks it at every callback. +//! - **The refusal.** A failed contract creation rewritten into a successful one is refused: the +//! transaction fails with [`FORBIDDEN_CREATE_REVIVAL`] as an `EVMError::Custom`. By the time +//! `create_end` runs, revm has reverted the frame and deposited no code, so the rewrite would +//! push an address for code that does not exist and merge the frame's state gas for state that +//! was rolled back. Every other rewrite is the tool's business. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{format, string::String}; + +use revm::{ + context::{ContextError, ContextTr}, + handler::FrameResult, + inspector::{handler::frame_end, NoOpInspector}, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, + Interpreter, InterpreterTypes, + }, + primitives::{Address, Log, U256}, + Inspector, +}; + +/// The message of the `EVMError::Custom` a refused creation revival fails the transaction with. +/// +/// Public so a tool driving rewriting inspectors can tell the refusal from an execution failure. +pub const FORBIDDEN_CREATE_REVIVAL: &str = + "inspector rewrote a failed contract creation into a successful one"; + +/// A declaration, made in source about one inspector type, that none of its callbacks writes +/// anything back to the EVM: nothing to an interpreter's gas or pending action, nothing to a +/// frame's inputs, nothing to a result's classification, gas or output, and no frame answered +/// itself. It may read anything and write its own state. +/// +/// The declaration is what block execution admits an inspected transaction on. +/// +/// - Implement it for one concrete type at a time, never as a blanket implementation, so each +/// declaration is a line someone wrote about a type they had read. +/// - Do not implement it for an inspector that answers a frame, edits inputs or rewrites a result, +/// however rarely. +/// - A foreign inspector type (a `revm-inspectors` tracer) is wrapped in [`DeclaredObserver`], +/// which is local here and carries the declaration. +/// - The test utilities' inspectors are not declared: they are not part of the gate. +pub trait TrustedObserver {} + +/// The inspector an EVM runs with when none was given observes nothing. +impl TrustedObserver for NoOpInspector {} + +/// A declared observer lent by reference stays declared: `&mut T` is declared exactly when `T` +/// is. +impl TrustedObserver for &mut T {} + +/// Carries a [`TrustedObserver`] declaration for an inspector whose type cannot carry one. +/// +/// It forwards every callback to the inspector inside and adds nothing. `DeclaredObserver(tracer)` +/// says "this tracer writes nothing back", moved from a type definition to the line that wraps +/// the value. Wrapping an inspector that writes is a false declaration, and a debug build panics +/// at the callback that breaks it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DeclaredObserver(pub I); + +impl DeclaredObserver { + /// Declares `inspector` a read-only observer. + pub const fn new(inspector: I) -> Self { + Self(inspector) + } + + /// The inspector inside. + pub fn into_inner(self) -> I { + self.0 + } +} + +impl TrustedObserver for DeclaredObserver {} + +impl Inspector for DeclaredObserver +where + I: Inspector, + INTR: InterpreterTypes, +{ + #[inline] + fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = gas_snapshot(interp); + self.0.initialize_interp(interp, context); + assert_gas_unwritten(before, interp, "initialize_interp"); + } + + #[inline] + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = gas_snapshot(interp); + self.0.step(interp, context); + assert_gas_unwritten(before, interp, "step"); + } + + #[inline] + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = gas_snapshot(interp); + self.0.step_end(interp, context); + assert_gas_unwritten(before, interp, "step_end"); + } + + #[inline] + fn log(&mut self, context: &mut CTX, log: Log) { + self.0.log(context, log); + } + + #[inline] + fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { + let before = gas_snapshot(interp); + self.0.log_full(interp, context, log); + assert_gas_unwritten(before, interp, "log_full"); + } + + #[inline] + fn frame_start( + &mut self, + context: &mut CTX, + frame_input: &mut FrameInput, + ) -> Option { + let answer = self.0.frame_start(context, frame_input); + debug_assert!(answer.is_none(), "a declared observer answered a frame in `frame_start`"); + answer + } + + #[inline] + fn frame_end( + &mut self, + context: &mut CTX, + frame_input: &FrameInput, + frame_result: &mut FrameResult, + ) { + let before = result_snapshot(frame_result); + self.0.frame_end(context, frame_input, frame_result); + assert_result_unwritten(before, frame_result, "frame_end"); + } + + #[inline] + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let answer = self.0.call(context, inputs); + debug_assert!(answer.is_none(), "a declared observer answered a call"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a declared observer rewrote a call's inputs"); + } + answer + } + + #[inline] + fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + self.0.call_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a declared observer rewrote a call result"); + } + } + + #[inline] + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let answer = self.0.create(context, inputs); + debug_assert!(answer.is_none(), "a declared observer answered a creation"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a declared observer rewrote a creation's inputs"); + } + answer + } + + #[inline] + fn create_end( + &mut self, + context: &mut CTX, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + self.0.create_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a declared observer rewrote a creation result"); + } + } + + #[inline] + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.0.selfdestruct(contract, target, value); + } +} + +/// An interpreter's gas and pending action, for the debug-build proof. `None` in release builds. +type GasSnapshot = Option<(revm::interpreter::Gas, bool)>; + +#[inline] +fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { + use revm::interpreter::interpreter_types::LoopControl; + cfg!(debug_assertions).then(|| (interp.gas, interp.bytecode.is_end())) +} + +#[inline] +fn assert_gas_unwritten( + before: GasSnapshot, + interp: &Interpreter, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + gas_snapshot(interp).expect("debug build"), + "a declared observer wrote to the interpreter in `{callback}`" + ); + } +} + +/// A frame result's classification, gas and output, and a creation's address, for the +/// debug-build proof. +type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; + +#[inline] +fn result_snapshot(result: &FrameResult) -> ResultSnapshot { + cfg!(debug_assertions).then(|| { + let address = match result { + FrameResult::Call(_) => None, + FrameResult::Create(outcome) => outcome.address, + }; + (result.interpreter_result().clone(), address) + }) +} + +#[inline] +fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { + if let Some(before) = before { + debug_assert!( + before == result_snapshot(result).expect("debug build"), + "a declared observer rewrote a frame result in `{callback}`" + ); + } +} + +/// Hands a frame's end to the inspector, then applies the one refusal: a creation that failed, +/// rewritten into a success, is put back and fails the transaction with +/// [`FORBIDDEN_CREATE_REVIVAL`]. +/// +/// Every place a frame result reaches the inspector goes through here, so the refusal covers a +/// result a frame ran to produce and one answered without running. A frame the inspector answered +/// with a success itself is no revival: nothing failed. +#[inline] +pub(crate) fn frame_end_checked( + context: &mut CTX, + inspector: &mut INSP, + frame_input: &FrameInput, + frame_result: &mut FrameResult, +) where + CTX: ContextTr, + INTR: InterpreterTypes, + INSP: Inspector, +{ + let before = frame_result.instruction_result(); + frame_end(context, inspector, frame_input, frame_result); + refuse_create_revival(context, before, frame_result); +} + +/// Puts a revived creation back to `before` and records the refusal as the context's error. +fn refuse_create_revival( + context: &mut CTX, + before: InstructionResult, + result: &mut FrameResult, +) { + let FrameResult::Create(outcome) = result else { return }; + if before.is_ok() || !outcome.result.result.is_ok() { + return; + } + outcome.result.result = before; + if context.error().is_ok() { + let message: String = format!("{FORBIDDEN_CREATE_REVIVAL}: {before:?}"); + *context.error() = Err(ContextError::Custom(message)); + } +} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 69255c5dc..238a3f82c 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -10,6 +10,7 @@ mod execution; mod factory; mod frame; mod host; +mod inspector; mod instructions; mod result; mod spec; @@ -19,6 +20,7 @@ pub use execution::*; pub use factory::*; pub use frame::*; pub use host::*; +pub use inspector::*; pub use result::*; pub use spec::*; @@ -71,6 +73,9 @@ pub struct MegaEvm, /// Whether [`alloy_evm::Evm::transact_raw`] runs the inspector. inspect: bool, + /// Whether the inspector's type carries a [`TrustedObserver`] declaration. Set only by the + /// constructors that require the declaration; true without an inspector. + trusted_inspector: bool, } impl MegaEvm { @@ -84,15 +89,46 @@ impl MegaEvm MegaEvm { - /// Replaces the inspector. The new inspector runs on every alloy-evm + /// Replaces the inspector with a tool's. The new inspector runs on every alloy-evm /// [`transact`](alloy_evm::Evm::transact) until it is disabled again. + /// + /// The inspector may rewrite what execution produces (see the `inspector` module), so the + /// EVM reports [`has_rewriting_inspector`](Self::has_rewriting_inspector) while it runs, and + /// block execution refuses it. pub fn with_inspector(self, inspector: I) -> MegaEvm { - MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true } + MegaEvm { + inner: self.inner.with_inspector(inspector), + inspect: true, + trusted_inspector: false, + } + } + + /// Replaces the inspector with one whose type is declared a [`TrustedObserver`]: it writes + /// nothing back, so the transactions it observes are the ones the chain executes, and block + /// execution admits them. + pub fn with_trusted_inspector( + self, + inspector: I, + ) -> MegaEvm { + MegaEvm { + inner: self.inner.with_inspector(inspector), + inspect: true, + trusted_inspector: true, + } + } + + /// Whether the EVM runs an inspector that may rewrite what execution produces: an enabled + /// inspector that did not arrive through + /// [`with_trusted_inspector`](Self::with_trusted_inspector). + /// + /// The admission gate block execution refuses a transaction on. + pub const fn has_rewriting_inspector(&self) -> bool { + self.inspect && !self.trusted_inspector } /// The execution context. diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs new file mode 100644 index 000000000..6d8ba7309 --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -0,0 +1,366 @@ +//! Inspectors on Satin: what a rewriting inspector gets, the one rewrite refused, and the +//! admission gate block execution keys on. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, + DeclaredObserver, MegaContext, MegaEvm, FORBIDDEN_CREATE_REVIVAL, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, + context::result::EVMError, + inspector::NoOpInspector, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, + }, + Database, Inspector, +}; +use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000400000"); +const A: Address = address!("00000000000000000000000000000000000000A1"); +const B: Address = address!("00000000000000000000000000000000000000B1"); +const FAKE: Address = address!("00000000000000000000000000000000000FA4E0"); +const GAS_LIMIT: u64 = 1_000_000; + +/// Calls `B` with `value` and stores the call's success flag in slot 0. +fn call_b_and_store_flag(value: u64) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(B) + .append(GAS) + .append(CALL) + .append(PUSH0) + .append(SSTORE) + .stop() + .build() +} + +/// Creates a contract from `init_code` (at most 32 bytes) and stores the address in slot 0. +fn create_and_store_address(init_code: &[u8]) -> Bytes { + let mut word = [0u8; 32]; + word[..init_code.len()].copy_from_slice(init_code); + BytecodeBuilder::default() + .mstore(0, word) + .push_number(init_code.len() as u64) + .append_many([PUSH0, PUSH0]) + .append(CREATE) + .append(PUSH0) + .append(SSTORE) + .stop() + .build() +} + +/// Rewrites what execution produces, one way per field. +#[derive(Default)] +struct Rewriter { + opcode: u8, + /// Gas charged after every `SSTORE`. + charge_after_sstore: u64, + /// Gas handed back after every `SSTORE`. + erase_after_sstore: u64, + /// Turns every call result into a success. + call_succeeds: bool, + /// Answers every call to `B` itself with a success. + answer_calls: bool, + /// Replaces every created address. + created_address: Option
, + /// Turns every creation result into a success. + create_succeeds: bool, +} + +impl Inspector, EthInterpreter> for Rewriter { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.opcode == SSTORE { + assert!(interp.gas.record_regular_cost(self.charge_after_sstore)); + interp.gas.erase_cost(self.erase_after_sstore); + } + } + + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + (self.answer_calls && inputs.target_address == B).then(|| { + CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if self.call_succeeds { + outcome.result.result = InstructionResult::Stop; + } + } + + fn create_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + if let Some(address) = self.created_address { + outcome.address = Some(address); + } + if self.create_succeeds { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(FAKE); + } + } +} + +fn run_with, EthInterpreter>>( + db: MemoryDatabase, + inspector: INSP, + value: u64, +) -> Result< + revm::context::result::ResultAndState, + EVMError, +> { + let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)) +} + +fn writes_two_slots() -> MemoryDatabase { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + MemoryDatabase::default().account_code(A, code) +} + +/// Gas an inspector charges or hands back in `step_end` lands on the receipt, exactly. +#[test] +fn test_step_end_charge_and_refund_land_on_the_receipt() { + let gas_used = |rewriter: Rewriter| { + let result = run_with(writes_two_slots(), rewriter, 0).unwrap(); + assert!(result.result.is_success()); + result.result.gas().tx_gas_used() + }; + let baseline = gas_used(Rewriter::default()); + assert_eq!( + gas_used(Rewriter { charge_after_sstore: 1_000, ..Default::default() }), + baseline + 2_000 + ); + assert_eq!( + gas_used(Rewriter { erase_after_sstore: 500, ..Default::default() }), + baseline - 1_000 + ); +} + +/// A call result rewritten in `call_end` is what the caller sees. +#[test] +fn test_call_end_rewrite_reaches_the_caller() { + let db = || { + MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + }; + let flag = |rewriter| { + run_with(db(), rewriter, 0).unwrap().state[&A].storage[&U256::ZERO].present_value() + }; + assert_eq!(flag(Rewriter::default()), U256::ZERO, "B reverts"); + assert_eq!(flag(Rewriter { call_succeeds: true, ..Default::default() }), U256::from(1)); +} + +/// A value call the inspector answers itself moves no value, and counts no write. +#[test] +fn test_short_circuited_value_call_moves_no_value() { + let db = MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(5)) + .account_balance(A, U256::from(100)); + let mut evm = MegaEvm::new(context(db)) + .with_inspector(Rewriter { answer_calls: true, ..Default::default() }); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(result.result.is_success()); + assert_eq!( + result.state[&A].storage[&U256::ZERO].present_value(), + U256::from(1), + "the answer is a success" + ); + assert_eq!(result.state[&A].info.balance, U256::from(100), "no value left A"); + assert!(result.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value reached B"); + assert_eq!(evm.ctx().additional_limit().usage().write_records, 1, "only A's slot 0"); +} + +/// An address rewritten in `create_end` is what the caller sees, but the code is where the +/// creation put it. +#[test] +fn test_create_end_address_rewrite_reaches_the_caller_not_the_code() { + // Init code returning one byte of runtime code (0x00). + let init_code = [0x60, 0x01, 0x60, 0x00, 0xf3]; + let db = MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); + let result = + run_with(db, Rewriter { created_address: Some(FAKE), ..Default::default() }, 0).unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + let stored = result.state[&A].storage[&U256::ZERO].present_value(); + assert_eq!(Address::from_word(stored.into()), FAKE, "the caller got the rewritten address"); + let created = A.create(0); + assert!(result.state[&created].info.code.as_ref().is_some_and(|code| !code.is_empty())); + assert!(result.state.get(&FAKE).is_none_or(|fake| fake.info.is_empty_code_hash())); +} + +/// A failed creation rewritten into a success is refused: the transaction fails with the +/// refusal. +#[test] +fn test_create_revival_is_refused() { + let db = MemoryDatabase::default() + .account_code(A, create_and_store_address(&[PUSH0, PUSH0, REVERT])); + let result = run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0); + match result { + Err(EVMError::Custom(message)) => { + assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") + } + other => panic!("expected the refusal, got {other:?}"), + } + + // A creation that succeeded may be rewritten freely; the refusal is for revivals only. + let db = MemoryDatabase::default() + .account_code(A, create_and_store_address(&[0x60, 0x01, 0x60, 0x00, 0xf3])); + assert!(run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0) + .unwrap() + .result + .is_success()); +} + +/// A declared observer that writes back fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer wrote to the interpreter in `step_end`")] +fn test_false_declaration_fails_in_debug() { + let rewriter = Rewriter { charge_after_sstore: 1, ..Default::default() }; + let mut evm = MegaEvm::new(context(writes_two_slots())) + .with_trusted_inspector(DeclaredObserver(rewriter)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared call rewrite fails too. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a call result")] +fn test_false_declaration_of_a_call_rewrite_fails_in_debug() { + let db = MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[INVALID])); + let rewriter = Rewriter { call_succeeds: true, ..Default::default() }; + let mut evm = MegaEvm::new(context(db)).with_trusted_inspector(DeclaredObserver(rewriter)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared observer that only reads produces the transaction no inspector produces. +#[test] +fn test_declared_tracer_changes_nothing() { + let db = || { + MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + }; + let plain = + MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); + let mut evm = MegaEvm::new(context(db())).with_trusted_inspector(DeclaredObserver(tracer)); + let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_eq!(plain.result, traced.result); + assert_eq!(plain.state, traced.state); + assert_eq!(evm.inspector().0.traces().nodes().len(), 2, "the tracer saw both frames"); +} + +/// The admission gate: only an enabled inspector that did not arrive declared is a rewriting one. +#[test] +fn test_has_rewriting_inspector_truth_table() { + let evm = || MegaEvm::new(context(MemoryDatabase::default())); + assert!(!evm().has_rewriting_inspector(), "no inspector"); + assert!(evm().with_inspector(NoOpInspector).has_rewriting_inspector(), "a tool's inspector"); + assert!( + evm().with_inspector(GasInspector::new()).has_rewriting_inspector(), + "test utilities are tools" + ); + assert!(!evm().with_trusted_inspector(NoOpInspector).has_rewriting_inspector()); + let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); + assert!(!evm().with_trusted_inspector(DeclaredObserver(tracer)).has_rewriting_inspector()); + + let mut disabled = evm().with_inspector(Rewriter::default()); + disabled.set_inspector_enabled(false); + assert!(!disabled.has_rewriting_inspector(), "a disabled inspector does not run"); + disabled.set_inspector_enabled(true); + assert!(disabled.has_rewriting_inspector()); +} + +/// Counts frame starts and ends. +#[derive(Default)] +struct Pairs { + calls: usize, + call_ends: usize, + creates: usize, + create_ends: usize, +} + +impl Inspector for Pairs { + fn call(&mut self, _context: &mut CTX, _inputs: &mut CallInputs) -> Option { + self.calls += 1; + None + } + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.call_ends += 1; + } + fn create(&mut self, _context: &mut CTX, _inputs: &mut CreateInputs) -> Option { + self.creates += 1; + None + } + fn create_end( + &mut self, + _context: &mut CTX, + _inputs: &CreateInputs, + _outcome: &mut CreateOutcome, + ) { + self.create_ends += 1; + } +} + +/// Every frame the inspector sees start, it sees end: a frame that ran, one answered before it +/// ran (a value transfer the sender cannot fund, a latched transaction's first frame), and a +/// creation. +#[test] +fn test_frame_start_and_end_stay_paired() { + let pairs = |db: MemoryDatabase, limits: mega_evm::EvmTxRuntimeLimits, value: u64| { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Pairs::default()); + let _ = evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)).unwrap(); + let pairs = evm.inspector(); + (pairs.calls, pairs.call_ends, pairs.creates, pairs.create_ends) + }; + let no_limits = mega_evm::EvmTxRuntimeLimits::no_limits(); + let unfunded = MemoryDatabase::default().account_code(A, call_b_and_store_flag(5)); + assert_eq!(pairs(unfunded, no_limits, 0), (2, 2, 0, 0)); + let creates = MemoryDatabase::default().account_code(A, create_and_store_address(&[0x00])); + assert_eq!(pairs(creates, no_limits, 0), (1, 1, 1, 1)); + let funded = MemoryDatabase::default().account_balance(CALLER, U256::from(10)); + let latched = no_limits.with_tx_data_size_limit(0); + assert_eq!(pairs(funded, latched, 1), (1, 1, 0, 0), "the stopped first frame ends too"); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 72714d7de..97393b1b7 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -3,6 +3,7 @@ mod common; mod db_error; mod equivalence; +mod inspector; mod state; mod strategic_stop; mod synthetic_frame_gas; From 65e508cc7000e07fa5c29274fcdb0c2fcda1222b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:47:20 +0800 Subject: [PATCH 061/201] feat: report the transaction outcome with its ledgers, usage and stop --- crates/mega-evm/src/evm/mod.rs | 30 ++++++ crates/mega-evm/src/evm/result.rs | 37 ++++++- crates/mega-evm/tests/_pending/README.md | 11 +- crates/mega-evm/tests/_pending/src/evm/mod.rs | 16 --- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/outcome.rs | 101 ++++++++++++++++++ 6 files changed, 173 insertions(+), 23 deletions(-) create mode 100644 crates/mega-evm/tests/satin/outcome.rs diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 238a3f82c..155a019a9 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -157,6 +157,36 @@ impl MegaEvm { } } +impl MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + /// Executes `tx`, through the inspector when one is enabled, and returns its outcome: the + /// result and state, the gas by ledger, the usage the common execution layer counted and the + /// limit that stopped the transaction, if any. Nothing is committed. + pub fn execute_transaction( + &mut self, + tx: MegaTransaction, + ) -> Result> { + let result_and_state = if self.inspect { + InspectEvm::inspect_tx(self, tx) + } else { + ExecuteEvm::transact(self, tx) + } + .map_err(map_op_err)?; + let layer = &self.inner.ctx.additional_limit; + let gas = MegaGasUsage::new(result_and_state.result.gas(), layer.history_gas_spent()); + Ok(MegaTransactionOutcome { + result_and_state, + gas, + usage: layer.usage(), + limit_exceeded: layer.latched().copied(), + }) + } +} + /// The error a [`MegaEvm`] reports through revm's execution traits. pub type MegaEvmError = EVMError; diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 9d9767abd..625def230 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -13,7 +13,42 @@ //! [`gas_used`](MegaGasUsage::gas_used), which is their sum less the refund, at least the EIP-7623 //! floor. -use revm::context::result::ResultGas; +use revm::context::result::{ResultAndState, ResultGas}; + +use crate::{LimitCheck, LimitUsage, MegaHaltReason}; + +/// What executing one transaction produced: revm's result and state, and what `MegaETH` counts +/// beside them. +/// +/// Derefs to the [`ResultAndState`], so `outcome.result` and `outcome.state` read through. +#[derive(Clone, Debug)] +pub struct MegaTransactionOutcome { + /// The execution result and the post-execution state. + pub result_and_state: ResultAndState, + /// The gas by ledger, and what the receipt reports. + pub gas: MegaGasUsage, + /// The data-size bytes and write records the transaction kept. The KV count a node reports + /// is [`LimitUsage::write_records`]. + pub usage: LimitUsage, + /// The transaction-level limit that stopped the transaction, if one did. The result is then a + /// revert whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the + /// output, tells a limit stop from a contract reverting with the same bytes. + pub limit_exceeded: Option, +} + +impl core::ops::Deref for MegaTransactionOutcome { + type Target = ResultAndState; + + fn deref(&self) -> &Self::Target { + &self.result_and_state + } +} + +impl core::ops::DerefMut for MegaTransactionOutcome { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.result_and_state + } +} /// The gas one transaction spent, by ledger, and what its receipt reports. /// diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5d50342bc..da629579b 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -26,7 +26,6 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| -| the common execution layer | 1 | 0 | 1 | 1 | 0 | 0 | | the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | @@ -43,7 +42,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **727** | **603** | **124** | **406** | **293** | **28** | +| **Total** | **726** | **603** | **123** | **405** | **293** | **28** | ## Tests ported in place @@ -114,7 +113,7 @@ It becomes assertable with the common execution layer, which defines the frame o ## Tests ported by the common execution layer -These 44 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 45 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -126,10 +125,11 @@ These 44 rows run in a real test target now, adapted to the Satin API, so the co | `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | | `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | | `src/evm/host.rs` | the common execution layer (10) | 10 | `src/evm/host.rs` | +| `src/evm/mod.rs` | the common execution layer (1) | 1 | `tests/satin/outcome.rs` | | `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | | `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | -| **Total** | | **44** | | +| **Total** | | **45** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -137,7 +137,6 @@ These 44 rows run in a real test target now, adapted to the Satin API, so the co |---|---|---|---| | `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | | `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | the Satin gas table | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | -| `src/evm/mod.rs` | `test_convenience_execution_methods_work` | the common execution layer | `execute_transaction` returns the transaction outcome type that the common execution layer defines | | `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | the block executor | reads the accessed-block-hash record, which returns with the block executor | ## Files @@ -225,7 +224,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | -| `src/evm/mod.rs` | 5 | keep 3 (the pre-block system calls); keep 1 (the block executor); keep 1 (the common execution layer) | +| `src/evm/mod.rs` | 4 | keep 3 (the pre-block system calls); keep 1 (the block executor) | | `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | | `src/evm/state.rs` | 1 | keep 1 (the block executor) | | `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs index 7cdc0d824..e0f5e2abd 100644 --- a/crates/mega-evm/tests/_pending/src/evm/mod.rs +++ b/crates/mega-evm/tests/_pending/src/evm/mod.rs @@ -108,20 +108,4 @@ mod tests { let evm = MegaEvm::new(configure_context(&mut state)); assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); } - - #[test] - fn test_convenience_execution_methods_work() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)).with_inspector(NoOpInspector); - - let executed = evm.execute_transaction(mega_tx()).unwrap(); - assert!(executed.result.is_success()); - - #[allow(deprecated)] - let inspected = evm.inspect_transaction(mega_tx()).unwrap(); - assert!(inspected.result.is_success()); - } - } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 97393b1b7..06bf21a58 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -4,6 +4,7 @@ mod common; mod db_error; mod equivalence; mod inspector; +mod outcome; mod state; mod strategic_stop; mod synthetic_frame_gas; diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs new file mode 100644 index 000000000..a578d127d --- /dev/null +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -0,0 +1,101 @@ +//! The transaction outcome: the result, the gas by ledger, the usage counted and the stop. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, + MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, +}; +use revm::inspector::NoOpInspector; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000600000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); + +fn writer() -> MemoryDatabase { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + MemoryDatabase::default().account_code(CONTRACT, code) +} + +fn execute( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + gas_limit: u64, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, gas_limit)) + .unwrap() +} + +/// The ledgers split the raw spend, the receipt reports revm's gas used, and the reservoir the +/// sender gets back is reported. +#[test] +fn test_outcome_reports_the_ledgers() { + let outcome = execute(writer(), EvmTxRuntimeLimits::no_limits(), 1_000_000_000); + assert!(outcome.result.is_success()); + let gas = outcome.gas; + let result_gas = outcome.result.gas(); + assert_eq!(gas.regular + gas.state + gas.history, result_gas.total_gas_spent()); + assert_eq!(gas.gas_used, result_gas.tx_gas_used()); + assert_eq!(gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP); + assert_eq!(gas.history, 0, "nothing prices history bytes yet"); + assert_eq!(outcome.usage, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); + assert_eq!(outcome.limit_exceeded, None); + + let mut block = BlockGasCounters::default(); + block.record(&gas); + block.record(&gas); + assert_eq!(block.execution, 2 * gas.block_execution_gas()); + assert_eq!(block.state, 2 * gas.state); +} + +/// A stopped transaction reports the stop. +#[test] +fn test_outcome_reports_the_stop() { + let outcome = + execute(writer(), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(40), 1_000_000); + assert!(!outcome.result.is_success()); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 40, + used: 80, + frame_local: false + }) + ); + assert_eq!(outcome.usage, LimitUsage::ZERO, "the stopped transaction keeps nothing"); +} + +/// A contract reverting with `MegaLimitExceeded`'s bytes on its own is not a stop. +#[test] +fn test_spoofed_revert_data_is_not_a_stop() { + let data: Bytes = MegaLimitExceeded { kind: 0, limit: 1 }.abi_encode().into(); + let code = BytecodeBuilder::default().revert_with_data(&data).build(); + let outcome = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + EvmTxRuntimeLimits::no_limits(), + 1_000_000, + ); + assert_eq!(outcome.result.output(), Some(&data)); + assert_eq!(outcome.limit_exceeded, None); +} + +/// `execute_transaction` runs the inspector when one is enabled, and not otherwise. +#[test] +fn test_convenience_execution_methods_work() { + let mut evm = MegaEvm::new(context(writer())).with_inspector(NoOpInspector); + let inspected = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + assert!(inspected.result.is_success()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, false); + let executed = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + assert!(executed.result.is_success()); + assert_eq!(inspected.gas, executed.gas); +} From 212f99e52f53c192598edd4d789720a3420ab65b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:48:29 +0800 Subject: [PATCH 062/201] test: assert the halt reason of a creation in a static callee --- crates/mega-evm/tests/_pending/README.md | 4 +- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/static_callee.rs | 123 +++++++++++++++++++ 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 crates/mega-evm/tests/satin/static_callee.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index da629579b..e4b56e283 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -108,8 +108,8 @@ A scenario keeps the transaction of its test; the assertions on compute gas (not | `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | `create2_missing_length` | | `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | `create2_missing_offset` | -The halt reason of a static callee is still owed, not discharged: 6 of these rows asserted it, and a scenario cannot, because the harness compares what the transaction reports and the inner frame's halt reason is not part of that. -It becomes assertable with the common execution layer, which defines the frame outcome, and inspector support, which reaches an inner frame as it ends; whichever lands first re-adds the assertions next to its own tests. +6 of these rows also asserted the halt reason of a static callee, which a scenario cannot compare: the harness compares what the transaction reports, and the inner frame's halt reason is not part of that. +The common execution layer re-added those assertions in `tests/satin/static_callee.rs`, where they read the halt reason off the callee's frame outcome as its caller receives it. ## Tests ported by the common execution layer diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 06bf21a58..6974ff689 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -6,6 +6,7 @@ mod equivalence; mod inspector; mod outcome; mod state; +mod static_callee; mod strategic_stop; mod synthetic_frame_gas; mod write_records; diff --git a/crates/mega-evm/tests/satin/static_callee.rs b/crates/mega-evm/tests/satin/static_callee.rs new file mode 100644 index 000000000..4c72ae26d --- /dev/null +++ b/crates/mega-evm/tests/satin/static_callee.rs @@ -0,0 +1,123 @@ +//! The halt reason of a creation inside a static call. +//! +//! A `CREATE` or `CREATE2` in a static frame halts with `StateChangeDuringStaticCall` before it +//! reads an operand, sizes its init code or charges anything, as in canonical revm. The +//! transaction does not expose an inner frame's halt reason, so these read it off the frame's +//! outcome as the caller receives it. The transactions are the differential corpus's +//! `create2_static_*` and `create_static_low_gas` scenarios. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::{CREATE, CREATE2, STATICCALL, STOP}, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult}, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000700000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000700001"); +const STATIC_CALLEE: Address = address!("0000000000000000000000000000000000700002"); + +/// The result of the static callee's frame, as its caller receives it. +#[derive(Default)] +struct CalleeResult(Option); + +impl Inspector, EthInterpreter> for CalleeResult { + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == STATIC_CALLEE { + self.0 = Some(outcome.result.result); + } + } +} + +/// Runs `CONTRACT`, which `STATICCALL`s `STATIC_CALLEE` running `callee` with `forward_gas`, and +/// returns the callee's result. +fn static_callee_result(callee: Bytes, forward_gas: u64) -> Option { + let caller_code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(STATIC_CALLEE) + .push_number(forward_gas) + .append(STATICCALL) + .append(STOP) + .build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, caller_code) + .account_code(STATIC_CALLEE, callee); + let mut evm = MegaEvm::new(context(db)).with_inspector(CalleeResult::default()); + let result = evm.transact_raw(call(CALLER, CONTRACT, U256::ZERO, 100_000_000)).unwrap(); + assert!(result.result.is_success(), "the static call's failure does not fail the caller"); + evm.inspector().0 +} + +/// `CREATE2(value 0, offset 0, size, salt 0)`. +fn create2(initcode_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(initcode_len) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .append(STOP) + .build() +} + +const STATIC_REJECTION: Option = + Some(InstructionResult::StateChangeDuringStaticCall); + +/// Oversized init code in a static frame reports the static rejection, not the size limit. +#[test] +fn test_create2_static_oversized_initcode_reports_static_rejection() { + assert_eq!(static_callee_result(create2(600_000), 50_000_000), STATIC_REJECTION); +} + +/// So does init code whose memory could never be paid for: nothing is sized. +#[test] +fn test_create2_static_hugely_oversized_initcode_halt_reason() { + assert_eq!(static_callee_result(create2(10 * 1024 * 1024), 50_000_000), STATIC_REJECTION); +} + +/// Empty init code in a static frame reports the static rejection. +#[test] +fn test_create2_static_zero_length_initcode_reports_static_rejection() { + assert_eq!(static_callee_result(create2(0), 50_000_000), STATIC_REJECTION); +} + +/// With little gas forwarded the static rejection still comes first: nothing is charged. +#[test] +fn test_create2_static_zero_length_low_gas_halt_reason() { + assert_eq!(static_callee_result(create2(0), 10_000), STATIC_REJECTION); +} + +/// Plain `CREATE` is rejected the same way. +#[test] +fn test_create_static_low_gas_halt_reason() { + let create = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(STOP) + .build(); + assert_eq!(static_callee_result(create, 10_000), STATIC_REJECTION); +} + +/// The rejection precedes the operand reads: a bare `CREATE2` reports it, not a stack underflow. +#[test] +fn test_create2_static_missing_operands_halt_reason() { + let bare = BytecodeBuilder::default().append(CREATE2).append(STOP).build(); + assert_eq!(static_callee_result(bare, 50_000_000), STATIC_REJECTION); +} From a758d8f956aaa153ca990315d53310988c0ddbcd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:51:59 +0800 Subject: [PATCH 063/201] bench: add deep calls, storage writes and logs to the transact bench --- crates/mega-evm/benches/transact.rs | 113 +++++++++++++++++++++++++--- 1 file changed, 103 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 1743906c9..ea24143ee 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -1,19 +1,29 @@ //! `ExecuteEvm::transact` on the Satin engine next to op-revm's `OpEvm` on the same `CfgEnv`. //! -//! A skeleton that keeps one benchmark target alive until the benchmark suite is rebuilt. Each -//! workload runs through `MegaEvm` (`satin`) and through `OpEvm` (`op_revm`), so the gap is the -//! wrapper's own cost. EVM construction is setup and is not measured. +//! Each workload runs through `MegaEvm` (`satin`) and through `OpEvm` (`op_revm`), so the gap is +//! the wrapper's own cost. EVM construction is setup and is not measured. +//! +//! - `empty_transaction`, `ether_transfer`: the per-transaction cost. +//! - `deep_calls`: a contract calling itself 64 deep, each frame writing a slot and logging, so +//! every frame pays the frame lifecycle's lanes and every `SSTORE` and `LOG` its commit wrapper. +//! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the +//! `SSTORE` wrapper's commit and refund. +//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit. #![allow(missing_docs)] use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ - test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, MegaContext, MegaEvm, MegaSpecId, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, PUSH0, + PUSH1, SSTORE, STOP, SUB, SWAP1, + }, context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, inspector::NoOpInspector, ExecuteEvm, Journal, @@ -21,6 +31,70 @@ use revm::{ const CALLER: Address = address!("0x0000000000000000000000000000000000100000"); const CALLEE: Address = address!("0x0000000000000000000000000000000000100001"); +const RECURSIVE: Address = address!("0x0000000000000000000000000000000000100002"); +const WRITER: Address = address!("0x0000000000000000000000000000000000100003"); +const LOGGER: Address = address!("0x0000000000000000000000000000000000100004"); + +/// Depth the recursive contract reaches. +const DEPTH: u8 = 64; +/// Slots written, then written back, by the storage workload; logs emitted by the log workload. +const REPEAT: u64 = 200; + +/// Offset of the `JUMPDEST` the recursion ends at. +const DONE: u8 = 0x1f; + +/// Reads `n` from calldata; while `n > 0` it writes slot `n`, logs, and calls itself with `n - 1`. +fn recursive_code() -> Bytes { + #[rustfmt::skip] + let body = [ + PUSH0, CALLDATALOAD, // n + DUP1, ISZERO, PUSH1, DONE, JUMPI, // n == 0: done + DUP1, PUSH1, 1, SWAP1, SSTORE, // storage[n] = 1 + PUSH0, PUSH0, LOG0, // an empty log + PUSH1, 1, SWAP1, SUB, PUSH0, MSTORE, // memory[0..32] = n - 1 + PUSH0, PUSH0, PUSH1, 0x20, PUSH0, PUSH0, ADDRESS, GAS, CALL, // call self with n - 1 + STOP, + JUMPDEST, STOP, // done + ]; + assert_eq!(body[DONE as usize], JUMPDEST); + Bytes::from(body.to_vec()) +} + +/// Writes `REPEAT` fresh slots, then writes each back to zero. +fn writer_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 0..REPEAT { + code = code.sstore(U256::from(slot), U256::from(1)); + } + for slot in 0..REPEAT { + code = code.sstore(U256::from(slot), U256::ZERO); + } + code.stop().build() +} + +/// Emits `REPEAT` two-topic logs of 32 bytes. +fn logger_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for topic in 0..REPEAT { + code = code + .push_number(topic) + .push_number(topic) + .push_number(32_u8) + .append(PUSH0) + .append(LOG2); + } + code.stop().build() +} + +fn call_tx(to: Address, data: Bytes, gas_limit: u64) -> OpTransaction { + op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data, + gas_limit, + ..Default::default() + }) +} type OpContext = Context< BlockEnv, @@ -48,16 +122,35 @@ fn mega_context(db: MemoryDatabase) -> MegaContext { fn bench_transact(c: &mut Criterion) { let db = MemoryDatabase::default() .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_balance(CALLEE, U256::from(1)); + .account_balance(CALLEE, U256::from(1)) + .account_code(RECURSIVE, recursive_code()) + .account_code(WRITER, writer_code()) + .account_code(LOGGER, logger_code()); let cfg = mega_context(db.clone()).cfg().clone(); + let mut depth = [0u8; 32]; + depth[31] = DEPTH; + let workloads = [ + ("empty_transaction", tx(U256::ZERO)), + ("ether_transfer", tx(U256::from(1))), + ("deep_calls", call_tx(RECURSIVE, Bytes::from(depth.to_vec()), 30_000_000)), + ("storage_writes", call_tx(WRITER, Bytes::new(), 30_000_000)), + ("logs", call_tx(LOGGER, Bytes::new(), 30_000_000)), + ]; + let mut group = c.benchmark_group("transact"); - for (workload, value) in [("empty_transaction", U256::ZERO), ("ether_transfer", U256::from(1))] - { + for (workload, tx) in workloads { + let satin = MegaEvm::new(mega_context(db.clone())).transact(OpTx(tx.clone())).unwrap(); + assert!(satin.result.is_success(), "{workload}: {:?}", satin.result); + if workload == "deep_calls" { + let written = + satin.state[&RECURSIVE].storage.values().filter(|s| s.is_changed()).count(); + assert_eq!(written, DEPTH as usize, "every frame of the recursion ran"); + } group.bench_function(format!("{workload}/satin"), |b| { b.iter_batched( || MegaEvm::new(mega_context(db.clone())), - |mut evm| evm.transact(OpTx(tx(value))).unwrap(), + |mut evm| evm.transact(OpTx(tx.clone())).unwrap(), BatchSize::SmallInput, ); }); @@ -69,7 +162,7 @@ fn bench_transact(c: &mut Criterion) { .with_chain(zero_fee_l1_block_info()); OpEvm::new(ctx, NoOpInspector) }, - |mut evm| evm.transact(tx(value)).unwrap(), + |mut evm| evm.transact(tx.clone()).unwrap(), BatchSize::SmallInput, ); }); From a87664d2c7fff203fa2a75d943815a51f66ce315 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:51:59 +0800 Subject: [PATCH 064/201] docs: write the common execution layer's contracts into AGENTS.md and the crate README --- AGENTS.md | 62 +++++++++++++++++++++++++++++---------- REVIEW.md | 2 +- crates/mega-evm/README.md | 18 ++++++++++-- 3 files changed, 64 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eb0aaae65..01db1f339 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,17 +89,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over op-revm's `OpEvm`; `MegaEvmFactory` (alloy-evm) | the common execution layer (frame lifecycle, result and gas types, inspector entry); the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM | -| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton | the block executor (Karst block rules), the pre-block system calls, the system contract deployments | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | -| `limit/` | nothing | the observe-stage-commit layer and abort protocol, the data-size limit, detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases | the common execution layer | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds now | Filled by | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton, `BlockGasCounters` (`result.rs`) | the block executor (Karst block rules, filling `BlockGasCounters`, refusing `has_rewriting_inspector`), the pre-block system calls, the system contract deployments | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -108,10 +108,42 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. Gas above the 200M execution cap goes to the EIP-8037 reservoir. The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. -- Every `Host` and context method delegates to op-revm's context, and `MegaEvm` delegates execution to `OpEvm`. - `tests/satin/equivalence.rs` pins that Satin currently equals op-revm on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. -- The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here. - The common execution layer defines Satin's frame, abort and write-record contracts; follow those once they land. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. + With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field, and the differential harness against revm 43; a later change that alters behavior on purpose updates that baseline. +- The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. +- The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. + +### Contracts of the common execution layer + +Every later mechanism plugs into these; a change to one comes back to this layer. + +- **The Host only observes.** + `sstore`, `log` and `selfdestruct` stage the facts revm hands them (`StagedRecord`) and record nothing. + Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop the transaction for a write that never happened. +- **Commit after the opcode.** + The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed. + Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's. +- **Write records.** + One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account. + The sender's own account is part of the transaction body. + Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped. + The KV count a node reports is the write-record count. +- **Lanes stay aligned with frames.** + `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the latch, the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran. +- **The latch.** + A transaction-level limit stops the transaction with a revert, never a halt: the frame that crosses it reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)`, the transaction is latched (`AdditionalLimit::latch`), no caller resumes (`before_frame_run`), no frame starts, every result returned above is rewritten to the stop, and the outermost frame settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. + A frame budget reverts its frame alone, without a latch. + A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn. + The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes. +- **Synthetic frame results carry the caller's pools.** + A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). +- **The admission gate.** + A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses, and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. + The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). + The test utilities' inspectors are not declared. +- **Three ledgers.** + `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. + `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. ## Test Organization (`crates/mega-evm/tests/`) diff --git a/REVIEW.md b/REVIEW.md index b7a613c3b..26a9729e9 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -98,7 +98,7 @@ These checks guard every change to the Satin engine. ### Instruction counts (CodSpeed) -- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`), `corpus` (a slice of the differential corpus through `MegaEvm`) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. +- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (a slice of the differential corpus through `MegaEvm`) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. - `codspeed.yml` runs them under instrumentation on every pull request that touches code and on every push to `satin`; the baseline a pull request is compared with is the latest `satin` push. - Read regressions from the CodSpeed report on the pull request (the CodSpeed comment and the `CodSpeed Performance Analysis` check). The regression threshold that fails that check is a setting of the repository's CodSpeed project; it is not recorded in this repository or in the reports CodSpeed posts, so this file does not state a number. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index d0b6f3dd7..9c14e8727 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -25,9 +25,14 @@ The legacy spec names do not parse: `"Rex6".parse::()` fails with `P ## Status Satin is under construction. -Today it runs transactions through op-revm with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. It still uses the Osaka gas table, which prices state gas at zero, so no transaction draws state gas yet. -SALT pricing, history gas, resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. + +The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the abort protocol that stops a transaction crossing a limit with a revert, and the inspector admission gate. +No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. +`MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. + +SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. ## Quick start @@ -47,6 +52,15 @@ let tx = OpTx(op_revm::OpTransaction { let result = evm.transact_raw(tx)?; ``` +A block executor admits an inspected transaction only from an EVM whose inspector is declared read-only: + +```rust,ignore +use mega_evm::DeclaredObserver; + +let evm = MegaEvm::new(context).with_trusted_inspector(DeclaredObserver(tracer)); +assert!(!evm.has_rewriting_inspector()); +``` + ## Documentation - [Specification](https://megaeth-labs.github.io/mega-evm/) (describes the legacy engine until the Satin pages land) From 3e5aba08fc9abc0bce0a9b7437115e1cbc464eba Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 18:55:49 +0800 Subject: [PATCH 065/201] fix: keep the sender's account and stopped creations out of the write records --- crates/mega-evm/src/evm/execution.rs | 2 + crates/mega-evm/src/limit/limit.rs | 27 +++++++--- crates/mega-evm/tests/satin/write_records.rs | 52 ++++++++++++++++++++ 3 files changed, 75 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 3533f5a5b..10ba515b7 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -270,6 +270,8 @@ impl EvmTr for MegaEvm { + FrameInput::Create(inputs) => { self.tracker.push(Lane::new(None, true, budget)); self.tracker.record(WRITE_RECORD); - if depth > 0 { + if depth == 0 { + self.sender = inputs.caller(); + } else { self.tracker.record_caller(true); } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 9c0c3ec8e..d4eec0478 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -512,3 +512,55 @@ fn test_value_to_an_applied_authority_records_it_once() { assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(usage, records(1)); } + +/// A creation a frame budget stops before it runs bumps no nonce, so it leaves no creator +/// record behind: the caller keeps only what it wrote itself. +#[test] +fn test_creation_stopped_at_init_leaves_no_creator_record() { + // CALLEE creates (two records: created account and creator), which a 60-byte budget stops, + // then writes a slot. + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0]) + .append(CREATE) + .append(POP) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(60); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CALLEE].info.nonce, 0, "the creation never started"); + assert_eq!(evm.ctx().additional_limit().usage(), records(1), "only CALLEE's slot"); +} + +/// A frame running as the transaction's sender (a delegated sender called back) records no +/// write to the sender's account: the transaction body counts it. +#[test] +fn test_frames_running_as_the_sender_do_not_record_it() { + // CALLER is delegated to CONTRACT, whose code sends value to CONTRACT2. CALLEE calls CALLER. + let relay = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CALLER) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let mut db = funded().account_code(CALLEE, relay).account_code(CONTRACT, sender_code); + let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); + let account = db.load_account(CALLER).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); + assert_eq!(usage, records(1), "CONTRACT2 only; the sender is part of the body"); +} From 2d6e06b09cffb40c9618d0f6ec14e1eb6d502dcb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:08:31 +0800 Subject: [PATCH 066/201] test: reach the creator-nonce check through an inspector and a collision --- crates/mega-evm/tests/satin/write_records.rs | 44 +++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index d4eec0478..14a1203cb 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -147,7 +147,8 @@ fn test_reverted_then_retried_create_records_the_creator_once() { assert_eq!(usage, records(1)); } -/// A creation that fails before bumping the nonce (the creator cannot fund it) records nothing. +/// A creation the creator cannot fund never starts (the opcode checks the endowment before it +/// builds a frame), so it records nothing. #[test] fn test_creation_without_funds_records_nothing() { let code = BytecodeBuilder::default() @@ -564,3 +565,44 @@ fn test_frames_running_as_the_sender_do_not_record_it() { assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); assert_eq!(usage, records(1), "CONTRACT2 only; the sender is part of the body"); } + +/// Raises the endowment of every creation past what the creator holds. +struct OverfundCreations; + +impl Inspector, EthInterpreter> for OverfundCreations { + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut revm::interpreter::CreateInputs, + ) -> Option { + inputs.set_value(U256::MAX); + None + } +} + +/// A creation that fails before bumping the creator's nonce (here, an endowment an inspector +/// raised past the creator's balance) takes its creator record back with it. +#[test] +fn test_creation_failing_before_the_nonce_bump_records_nothing() { + let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); + let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, code))) + .with_inspector(OverfundCreations); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); + assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO); +} + +/// A creation that collides with an existing account fails after bumping the creator's nonce, so +/// the creator record stays and the created account's goes. +#[test] +fn test_colliding_creation_keeps_the_creator_record() { + let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); + let db = funded().account_code(CALLEE, code).account_nonce(CALLEE.create(0), 1); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); + assert_eq!(usage, records(1), "the creator's nonce only"); +} From 1c4048ed6a924baa15bd19ea3573b151f4416063 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:09:07 +0800 Subject: [PATCH 067/201] refactor: reset the layer at the EVM's entry points and share the pre-frame answer --- crates/mega-evm/src/evm/context.rs | 3 +- crates/mega-evm/src/evm/execution.rs | 58 +++++++------------ crates/mega-evm/src/evm/mod.rs | 39 +++++++++---- crates/mega-evm/tests/satin/strategic_stop.rs | 39 +++++++++++++ 4 files changed, 88 insertions(+), 51 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 2df14b19c..309fccdca 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -127,7 +127,8 @@ impl MegaContext { &mut self.additional_limit } - /// Prepares the common execution layer for a new transaction or system call. + /// Prepares the common execution layer for a new transaction or system call. Every entry + /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. pub(crate) fn on_new_tx(&mut self) { self.additional_limit.reset(); } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 10ba515b7..8daca0b83 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -15,8 +15,8 @@ use std::vec::Vec; use op_revm::precompiles::OpPrecompiles; use revm::{ context::{ - result::FromStringError, transaction::TransactionType, Cfg, ContextError, ContextTr, - FrameStack, JournalTr, Transaction, + result::FromStringError, transaction::TransactionType, ContextError, ContextTr, FrameStack, + JournalTr, Transaction, }, context_interface::{cfg::gas::GasTracker, journaled_state::entry::JournalEntry}, handler::{ @@ -75,30 +75,6 @@ where type Error = ERROR; type HaltReason = OpHaltReason; - /// Resets the common execution layer, then validates as revm does. - fn validate(&self, evm: &mut Self::Evm) -> Result { - evm.ctx_mut().on_new_tx(); - self.validate_env(evm)?; - let mut init_and_floor_gas = self.validate_initial_tx_gas(evm)?; - self.validate_against_state_and_deduct_caller(evm, &mut init_and_floor_gas)?; - Ok(init_and_floor_gas) - } - - /// Resets the common execution layer for a system call, then builds its gas as revm does. - fn system_call_gas(&self, evm: &mut Self::Evm) -> GasTracker { - evm.ctx_mut().on_new_tx(); - let mut gas = self.tx_gas(evm, &InitialAndFloorGas::new(0, 0)); - let cfg = evm.ctx_ref().cfg(); - if cfg.system_call_state_gas_margin_in_reservoir() && cfg.is_amsterdam_eip8037_enabled() { - let margin = gas - .remaining() - .saturating_sub(revm::handler::system_call::SYSTEM_CALL_REGULAR_GAS_LIMIT); - gas.set_remaining(gas.remaining() - margin); - gas.set_reservoir(gas.reservoir() + margin); - } - gas - } - /// revm's pre-execution, then the write records of the EIP-7702 authorities it applied. fn pre_execution( &self, @@ -254,11 +230,7 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - if let Some(latched) = self.inner.ctx.additional_limit.latched().copied() { - self.inner.ctx.additional_limit.push_empty_frame(); - return Ok(ItemOrResult::Result(stopped_frame_result(&frame_init, &latched))); - } - if let Some(result) = call_too_deep(&frame_init) { + if let Some(result) = answer_before_building(&self.inner.ctx, &frame_init) { self.inner.ctx.additional_limit.push_empty_frame(); return Ok(ItemOrResult::Result(result)); } @@ -390,13 +362,11 @@ where ) -> Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - // The inspector answered the frame. The latch and the depth guard still hold, in - // `frame_init`'s order: an answer cannot start a frame of a stopped transaction, nor - // reach past the call-stack limit. - if let Some(latched) = ctx.additional_limit.latched().copied() { - output = stopped_frame_result(&frame_init, &latched); - } else if let Some(too_deep) = call_too_deep(&frame_init) { - output = too_deep; + // The inspector answered the frame. The latch and the depth guard still hold: an + // answer cannot start a frame of a stopped transaction, nor reach past the call-stack + // limit. + if let Some(answer) = answer_before_building(ctx, &frame_init) { + output = answer; } ctx.additional_limit.push_empty_frame(); frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); @@ -507,6 +477,18 @@ impl MegaEvm { } } +/// The answer a frame gets before anything builds or answers it otherwise, in this order: the +/// latched stop of a stopped transaction, then the depth guard's `CallTooDeep`. +fn answer_before_building( + ctx: &MegaContext, + frame_init: &FrameInit, +) -> Option { + if let Some(latched) = ctx.additional_limit.latched() { + return Some(stopped_frame_result(frame_init, latched)); + } + call_too_deep(frame_init) +} + /// The depth guard: a `CALL` or `STATICCALL` past the call-stack limit, answered with /// `CallTooDeep`, its gas untouched and its reservoir carried. /// diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 155a019a9..d545532ef 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -170,12 +170,7 @@ where &mut self, tx: MegaTransaction, ) -> Result> { - let result_and_state = if self.inspect { - InspectEvm::inspect_tx(self, tx) - } else { - ExecuteEvm::transact(self, tx) - } - .map_err(map_op_err)?; + let result_and_state = self.run_transaction(tx)?; let layer = &self.inner.ctx.additional_limit; let gas = MegaGasUsage::new(result_and_state.result.gas(), layer.history_gas_spent()); Ok(MegaTransactionOutcome { @@ -187,6 +182,26 @@ where } } +impl MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + /// Runs `tx` through the inspector when one is enabled, without committing. + fn run_transaction( + &mut self, + tx: MegaTransaction, + ) -> Result, EVMError> { + let result = if self.inspect { + InspectEvm::inspect_tx(self, tx) + } else { + ExecuteEvm::transact(self, tx) + }; + result.map_err(map_op_err) + } +} + /// The error a [`MegaEvm`] reports through revm's execution traits. pub type MegaEvmError = EVMError; @@ -203,6 +218,7 @@ impl ExecuteEvm for MegaEvm Result { self.inner.ctx.set_tx(tx); + self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().run(self) } @@ -213,6 +229,7 @@ impl ExecuteEvm for MegaEvm Result, Self::Error> { + self.inner.ctx.on_new_tx(); let result = MegaHandler::<_, Self::Error, _>::new().run(self)?; Ok(ExecResultAndState::new(result, self.finalize())) } @@ -240,6 +257,7 @@ where fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { self.inner.ctx.set_tx(tx); + self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().inspect_run(self) } } @@ -264,6 +282,7 @@ impl SystemCallEvm for MegaEvm::new().run_system_call(self) } } @@ -285,6 +304,7 @@ where system_contract_address, data, )); + self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().inspect_run_system_call(self) } } @@ -325,12 +345,7 @@ where &mut self, tx: Self::Tx, ) -> Result, Self::Error> { - let result = if self.inspect { - InspectEvm::inspect_tx(self, tx) - } else { - ExecuteEvm::transact(self, tx) - }; - result.map_err(map_op_err) + self.run_transaction(tx) } fn transact_system_call( diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index f9cf1809b..d63fc279a 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -368,3 +368,42 @@ fn test_first_latch_wins() { assert_eq!(layer.latched(), Some(&first)); assert!(first.exceeded_limit() && !first.is_frame_local()); } + +/// The layer's state belongs to one transaction: a latch and the usage counted do not reach the +/// next transaction or system call, through any entry point. +#[test] +fn test_the_latch_does_not_outlive_its_transaction() { + let db = chain().account_code(B, writer()); + let mut evm = + MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))).with_inspector(Probe::default()); + let stopped = + |evm: &MegaEvm| evm.ctx().additional_limit().latched().is_some(); + + // B writes three slots: 120 bytes cross the cap. + alloy_evm::Evm::set_inspector_enabled(&mut evm, false); + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + assert!(stopped(&evm)); + // An empty call runs clean, through the plain and the inspected path. + assert!(evm + .transact_raw(call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)) + .unwrap() + .result + .is_success()); + assert!(!stopped(&evm)); + assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO); + + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, true); + assert!(evm + .transact_raw(call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)) + .unwrap() + .result + .is_success()); + assert!(!stopped(&evm)); + + // So does a system call. + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + let system = evm.transact_system_call(CALLER, CALLER, Bytes::new()).unwrap(); + assert!(system.result.is_success()); + assert!(!stopped(&evm)); +} From 1ef1928de8fb3a1ae80b42d9f97bb10e65c3f6bb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:09:27 +0800 Subject: [PATCH 068/201] fix: keep a selfdestruct to the sender out of the write records --- crates/mega-evm/src/evm/host.rs | 1 + crates/mega-evm/src/limit/limit.rs | 2 +- crates/mega-evm/src/limit/record.rs | 48 ++++++++++++++------ crates/mega-evm/tests/satin/write_records.rs | 4 +- 4 files changed, 40 insertions(+), 15 deletions(-) diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 0af5854e4..5b9b9d4f7 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -124,6 +124,7 @@ impl revm::context_interface::Host had_value: load.data.had_value, target_exists: load.data.target_exists, to_other_account: target != address, + beneficiary: target, }); Ok(load) } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 976e2e54c..5a8e6afd0 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -159,7 +159,7 @@ impl AdditionalLimit { #[inline] pub(crate) fn commit_staged_record(&mut self) -> LimitCheck { let Some(record) = self.staged.take() else { return LimitCheck::WithinLimit }; - match record.effect() { + match record.effect(self.sender) { RecordEffect::None => LimitCheck::WithinLimit, RecordEffect::Record(usage) => { self.tracker.record(usage); diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 7bd927fce..93eb729e7 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -1,5 +1,6 @@ //! The facts the Host observes for the opcode that is running. +use alloy_primitives::Address; use revm::interpreter::SStoreResult; use super::{LimitUsage, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD}; @@ -30,6 +31,8 @@ pub enum StagedRecord { target_exists: bool, /// Whether the beneficiary is another account than the destructed one. to_other_account: bool, + /// The beneficiary. + beneficiary: Address, }, } @@ -50,8 +53,10 @@ impl StagedRecord { /// - `SSTORE`: the first change of a slot in the transaction is one write record; writing the /// slot back to its original value takes the record back. /// - `LOG`: its bytes, one base record for the address, one per topic and the data. - /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account. - pub(crate) fn effect(&self) -> RecordEffect { + /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account + /// than the destructed one and the transaction's `sender`, whose account the transaction body + /// counts. + pub(crate) fn effect(&self, sender: Address) -> RecordEffect { match self { Self::Sstore(slot) => { if slot.is_original_eq_present() { @@ -72,8 +77,8 @@ impl StagedRecord { .saturating_add(*data_len), write_records: 0, }), - Self::SelfDestruct { had_value, to_other_account, .. } => { - if *had_value && *to_other_account { + Self::SelfDestruct { had_value, to_other_account, beneficiary, .. } => { + if *had_value && *to_other_account && *beneficiary != sender { RecordEffect::Record(WRITE_RECORD) } else { RecordEffect::None @@ -86,7 +91,10 @@ impl StagedRecord { #[cfg(test)] mod tests { use super::*; - use alloy_primitives::U256; + use alloy_primitives::{address, U256}; + + const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); + const OTHER: Address = address!("0000000000000000000000000000000000000077"); fn sstore(original: u64, present: u64, new: u64) -> StagedRecord { StagedRecord::Sstore(SStoreResult { @@ -100,18 +108,18 @@ mod tests { /// original value takes the record back; every other write counts nothing. #[test] fn test_sstore_record_rules() { - assert_eq!(sstore(0, 0, 1).effect(), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(5, 5, 0).effect(), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 0).effect(), RecordEffect::Refund(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 2).effect(), RecordEffect::None); - assert_eq!(sstore(3, 3, 3).effect(), RecordEffect::None); - assert_eq!(sstore(3, 4, 4).effect(), RecordEffect::None); + assert_eq!(sstore(0, 0, 1).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(5, 5, 0).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 0).effect(SENDER), RecordEffect::Refund(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 2).effect(SENDER), RecordEffect::None); + assert_eq!(sstore(3, 3, 3).effect(SENDER), RecordEffect::None); + assert_eq!(sstore(3, 4, 4).effect(SENDER), RecordEffect::None); } /// A log is 32 bytes for its address, 32 per topic and its data. #[test] fn test_log_bytes() { - let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(); + let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(SENDER); assert_eq!(log(0, 0), RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 })); assert_eq!( log(4, 100), @@ -127,11 +135,25 @@ mod tests { #[test] fn test_selfdestruct_record_rules() { let sd = |had_value, to_other_account| { - StagedRecord::SelfDestruct { had_value, target_exists: true, to_other_account }.effect() + let beneficiary = OTHER; + StagedRecord::SelfDestruct { + had_value, + target_exists: true, + to_other_account, + beneficiary, + } + .effect(SENDER) }; assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); assert_eq!(sd(true, false), RecordEffect::None); assert_eq!(sd(false, true), RecordEffect::None); assert_eq!(sd(false, false), RecordEffect::None); + let to_sender = StagedRecord::SelfDestruct { + had_value: true, + target_exists: true, + to_other_account: true, + beneficiary: SENDER, + }; + assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 14a1203cb..cffe02c21 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -310,7 +310,8 @@ fn test_log_counts_its_bytes() { assert_eq!(usage, LimitUsage { data_size: 32 + 2 * 32 + 10, write_records: 0 }); } -/// `SELFDESTRUCT` records the beneficiary only when value moves to another account. +/// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the +/// destructed one and the sender, whose account the transaction body counts. #[test] fn test_selfdestruct_records_the_beneficiary_when_value_moves() { let destruct_to = |beneficiary: Address| { @@ -319,6 +320,7 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { let cases = [ (U256::from(5), CONTRACT, records(1)), (U256::from(5), CALLEE, LimitUsage::ZERO), + (U256::from(5), CALLER, LimitUsage::ZERO), (U256::ZERO, CONTRACT, LimitUsage::ZERO), ]; for (balance, beneficiary, expected) in cases { From c8501cb35ee04c16c380b8f543792c50e70f7f0a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:10:01 +0800 Subject: [PATCH 069/201] fix: enforce a limit stop before the writes it guards --- crates/mega-evm/src/evm/execution.rs | 61 ++++++++--- crates/mega-evm/src/limit/limit.rs | 36 +++++-- crates/mega-evm/tests/satin/strategic_stop.rs | 18 ++++ crates/mega-evm/tests/satin/write_records.rs | 100 +++++++++++++----- 4 files changed, 170 insertions(+), 45 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 8daca0b83..2adaa978c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -18,7 +18,10 @@ use revm::{ result::FromStringError, transaction::TransactionType, ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, - context_interface::{cfg::gas::GasTracker, journaled_state::entry::JournalEntry}, + context_interface::{ + cfg::gas::GasTracker, + journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, + }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, instructions::InstructionProvider, @@ -76,6 +79,10 @@ where type HaltReason = OpHaltReason; /// revm's pre-execution, then the write records of the EIP-7702 authorities it applied. + /// + /// When those records would cross a limit, the limit is enforced before the writes it + /// guards: the authorizations are taken back with the gas they charged, and the transaction, + /// latched, is stopped at its first frame. fn pre_execution( &self, evm: &mut Self::Evm, @@ -83,11 +90,17 @@ where ) -> Result, Self::Error> { self.load_accounts(evm)?; let checkpoint = evm.ctx().journal_mut().checkpoint(); + let gas_before = *gas; let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { evm.ctx().journal_mut().checkpoint_revert(checkpoint); return Ok(None); }; - record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + if record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i).exceeded_limit() { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + *gas = gas_before; + let checkpoint = evm.ctx().journal_mut().checkpoint(); + return Ok(Some(PreExecutionOutput { eip7702_refund: 0, checkpoint })); + } Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -230,7 +243,7 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = answer_before_building(&self.inner.ctx, &frame_init) { + if let Some(result) = answer_before_building(&mut self.inner.ctx, &frame_init)? { self.inner.ctx.additional_limit.push_empty_frame(); return Ok(ItemOrResult::Result(result)); } @@ -242,9 +255,7 @@ impl EvmTr for MegaEvm MegaEvm { /// The answer a frame gets before anything builds or answers it otherwise, in this order: the /// latched stop of a stopped transaction, then the depth guard's `CallTooDeep`. fn answer_before_building( - ctx: &MegaContext, + ctx: &mut MegaContext, + frame_init: &FrameInit, +) -> Result, ContextDbError>> { + if let Some(latched) = ctx.additional_limit.latched().copied() { + return stop_before_building(ctx, frame_init, &latched).map(Some); + } + Ok(call_too_deep(frame_init)) +} + +/// Answers a frame a limit stops before it is built with the stop. +/// +/// A creation still bumps its creator's nonce, as one that starts and reverts does: a nested +/// creation's caller sees an ordinary failed creation, and a creation transaction stopped before +/// its first frame cannot be replayed. +fn stop_before_building( + ctx: &mut MegaContext, frame_init: &FrameInit, -) -> Option { - if let Some(latched) = ctx.additional_limit.latched() { - return Some(stopped_frame_result(frame_init, latched)); + check: &LimitCheck, +) -> Result>> { + if let FrameInput::Create(inputs) = &frame_init.frame_input { + let _ = ctx.journal_mut().load_account_mut(inputs.caller())?.data.bump_nonce(); } - call_too_deep(frame_init) + Ok(stopped_frame_result(frame_init, check)) } /// The depth guard: a `CALL` or `STATICCALL` past the call-stack limit, answered with @@ -538,9 +565,9 @@ fn account_nonce( fn record_applied_authorities( ctx: &mut MegaContext, journal_i: usize, -) { +) -> LimitCheck { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return; + return LimitCheck::WithinLimit; } let caller = ctx.tx().caller(); let target = ctx.tx().kind().to().copied(); @@ -555,5 +582,9 @@ fn record_applied_authorities( authorities.dedup(); let target_is_authority = target.is_some_and(|target| authorities.binary_search(&target).is_ok()); - ctx.additional_limit.record_applied_authorities(authorities.len() as u64, target_is_authority); + ctx.additional_limit.record_applied_authorities( + caller, + authorities.len() as u64, + target_is_authority, + ) } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 5a8e6afd0..923572c74 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -44,6 +44,9 @@ pub struct AdditionalLimit { /// The transaction's sender, whose account write is part of the transaction body: a frame /// running as the sender never records it. sender: Address, + /// Whether the transaction's first frame reached frame init. When it did not, the runtime + /// phase before it ran out of gas and took back everything counted before it. + frame_began: bool, /// The history gas the settled transaction spent. history_gas_spent: u64, } @@ -71,6 +74,7 @@ impl AdditionalLimit { self.latched = None; self.target_is_authority = false; self.sender = Address::ZERO; + self.frame_began = false; self.history_gas_spent = 0; } @@ -190,17 +194,26 @@ impl AdditionalLimit { /// Records the account writes of the applied EIP-7702 authorities other than the sender: /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is - /// one of them. + /// one of them, from the transaction's `sender`. + /// + /// The limit is checked before the records are made: a crossing latches the transaction and + /// records nothing, and the caller takes the authorizations back, so the writes the limit + /// guards never happen. The first frame is then answered with the stop without running. pub(crate) fn record_applied_authorities( &mut self, + sender: Address, authorities: u64, target_is_authority: bool, - ) { + ) -> LimitCheck { + self.sender = sender; + let records = WRITE_RECORD.times(authorities); + let used = self.tracker.net().saturating_add(records).data_size; + if used > self.limits.tx_data_size_limit { + return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); + } self.target_is_authority = target_is_authority; - self.tracker.record(WRITE_RECORD.times(authorities)); - // Crossing the limit here latches the transaction before its first frame, which is then - // answered with the stop without running. - self.check(); + self.tracker.record(records); + LimitCheck::WithinLimit } /* Frame lanes */ @@ -219,6 +232,7 @@ impl AdditionalLimit { /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. /// So is every frame of a latched transaction, whose lane stays empty. pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { + self.frame_began = true; if let Some(latched) = self.latched { self.push_empty_frame(); return latched; @@ -293,6 +307,7 @@ impl AdditionalLimit { /// Pushes the lane of a frame answered without running: a result built without an /// interpreter keeps the lanes aligned with the frames revm returns. pub(crate) fn push_empty_frame(&mut self) { + self.frame_began = true; self.tracker.push(Lane::empty()); } @@ -307,7 +322,16 @@ impl AdditionalLimit { /// Settles the transaction's outermost frame: pops its lane unless the frame already /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever /// it ran, and rewrites the result to the latched stop. + /// + /// A transaction whose first frame never reached frame init ran out of gas in the runtime + /// phase before it: the out-of-gas took back the authorizations applied before it, so their + /// records and any latch they set go too, and the halt stays a halt. pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { + if !self.frame_began { + self.tracker.reset(); + self.latched = None; + return; + } debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); if self.tracker.depth() == 1 { self.on_frame_return(result); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index d63fc279a..d44cf03fd 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -407,3 +407,21 @@ fn test_the_latch_does_not_outlive_its_transaction() { assert!(system.result.is_success()); assert!(!stopped(&evm)); } + +/// A creation transaction stopped before its first frame still bumps the sender's nonce, like any +/// included creation transaction: it cannot be replayed. +#[test] +fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { + let tx = crate::common::create(CALLER, writer(), GAS_LIMIT); + let (result, latched) = run(MemoryDatabase::default(), cap(39), tx); + assert_stopped(&result.result, LimitKind::DataSize, 39); + assert!(latched.is_some()); + assert_eq!(result.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); + assert!(result.state.get(&CALLER.create(0)).is_none_or(|a| a.info.is_empty_code_hash())); + assert!(result.result.gas().tx_gas_used() < GAS_LIMIT / 2, "the stop burns nothing"); + + // The stopped creation's result carries the reservoir back. + let tx = crate::common::create(CALLER, writer(), 1_000_000_000); + let (result, _) = run(MemoryDatabase::default(), cap(39), tx); + assert_eq!(result.result.gas().reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index cffe02c21..97fac526a 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -516,30 +516,6 @@ fn test_value_to_an_applied_authority_records_it_once() { assert_eq!(usage, records(1)); } -/// A creation a frame budget stops before it runs bumps no nonce, so it leaves no creator -/// record behind: the caller keeps only what it wrote itself. -#[test] -fn test_creation_stopped_at_init_leaves_no_creator_record() { - // CALLEE creates (two records: created account and creator), which a 60-byte budget stops, - // then writes a slot. - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0]) - .append(CREATE) - .append(POP) - .sstore(U256::from(1), U256::from(1)) - .stop() - .build(); - let db = MemoryDatabase::default().account_code(CALLEE, code); - let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(60); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); - let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) - .unwrap(); - assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(result.state[&CALLEE].info.nonce, 0, "the creation never started"); - assert_eq!(evm.ctx().additional_limit().usage(), records(1), "only CALLEE's slot"); -} - /// A frame running as the transaction's sender (a delegated sender called back) records no /// write to the sender's account: the transaction body counts it. #[test] @@ -608,3 +584,79 @@ fn test_colliding_creation_keeps_the_creator_record() { assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); assert_eq!(usage, records(1), "the creator's nonce only"); } + +/// A creation a frame budget stops before it runs reverts like one that ran: the creator's nonce +/// is bumped and its record kept, the created account's record goes. +#[test] +fn test_creation_stopped_at_init_bumps_the_creator_nonce() { + // CALLEE writes a slot (40 bytes of its 100-byte budget), then creates: the creation's two + // records (80 bytes) exceed the 60 bytes left to it. CALLEE stores the created address. + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0]) + .append(CREATE) + .append(PUSH0) + .append(SSTORE) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CALLEE].info.nonce, 1, "the stopped creation bumped the nonce"); + assert_eq!(result.state[&CALLEE].storage[&U256::ZERO].present_value(), U256::ZERO, "it failed"); + assert_eq!(evm.ctx().additional_limit().usage(), records(2), "slot 1 and the creator's nonce"); +} + +/// Authorities whose records would cross the transaction's data-size limit are not applied: the +/// limit is enforced before the writes it guards, and the transaction is stopped before its first +/// frame. +#[test] +fn test_authorities_crossing_the_cap_are_not_applied() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(39); + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) + .unwrap(); + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_some()); + let authority = outcome.state.get(&AUTHORITY_1); + assert!( + authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "the delegation was not applied: {authority:?}" + ); + assert_eq!(outcome.usage, LimitUsage::ZERO); +} + +/// A transaction that runs out of gas after its authorities were applied, before its first frame, +/// keeps none of their records: the out-of-gas takes the delegations back. +#[test] +fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { + // The call target is an authority the transaction delegates: calling it pays for the + // delegation target's access after the authorities were applied. Find the gas limit one short + // of the whole runtime phase. + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000)); + let tx = |gas_limit| { + let mut tx = authorizing_call(AUTHORITY_1, 0, &[(AUTHORITY_1, 0)]); + tx.0.base.gas_limit = gas_limit; + tx + }; + let run_at = + |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)).unwrap(); + let mut gas_limit = 40_000; + while !run_at(gas_limit).result.is_success() { + gas_limit += 1; + assert!(gas_limit < 200_000, "the transaction never succeeds"); + } + let outcome = run_at(gas_limit - 1); + assert!(outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.usage, LimitUsage::ZERO); + assert_eq!(outcome.limit_exceeded, None); + assert!( + outcome.state.get(&AUTHORITY_1).is_none_or(|a| a.info.nonce == 0), + "the out-of-gas took the delegation back" + ); +} From b201251b8b68f5e023f2f4d91e6b223a74990ac9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:12:39 +0800 Subject: [PATCH 070/201] test: pin the limit verdicts, the Host's staging and the lane merge rule --- crates/mega-evm/src/block/result.rs | 2 +- crates/mega-evm/src/evm/host.rs | 54 ++++++++++++++++++++++++ crates/mega-evm/src/evm/result.rs | 8 +--- crates/mega-evm/src/limit/frame_limit.rs | 8 ++++ crates/mega-evm/src/limit/mod.rs | 12 ++++++ 5 files changed, 77 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index fb4868f8b..f3e2f378a 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -18,7 +18,7 @@ pub struct BlockGasCounters { impl BlockGasCounters { /// Adds one transaction's gas. - pub const fn record(&mut self, gas: &MegaGasUsage) { + pub fn record(&mut self, gas: &MegaGasUsage) { self.execution = self.execution.saturating_add(gas.block_execution_gas()); self.state = self.state.saturating_add(gas.state); self.history = self.history.saturating_add(gas.history); diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 5b9b9d4f7..c4d9cd34f 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -415,6 +415,8 @@ mod tests { "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ `code_by_hash` off the hot path for accounts without on-chain code", ); + let again = journal.inspect_account(EOA, false).expect("occupied read must succeed"); + assert!(again.info.code.is_none(), "the occupied branch keeps the guard too"); } /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate @@ -607,4 +609,56 @@ mod tests { "storage is read from the delegator (original address), not the delegate" ); } + + /// The Host stages what each state-writing call observed and counts nothing: counting is the + /// opcode wrapper's, after the opcode completed. + #[test] + fn test_host_stages_observations_and_counts_nothing() { + use crate::{test_utils::MemoryDatabase, MegaSpecId}; + use revm::{context_interface::Host, primitives::LogData}; + + const CONTRACT: Address = address!("00000000000000000000000000000000000000c1"); + const BENEFICIARY: Address = address!("00000000000000000000000000000000000000c2"); + let db = MemoryDatabase::default().account_balance(CONTRACT, U256::from(3)); + let mut ctx = MegaContext::new(db, MegaSpecId::SATIN); + ctx.inner.journaled_state.load_account(CONTRACT).unwrap(); + + let slot = Host::sstore(&mut ctx, CONTRACT, U256::from(1), U256::from(9)).unwrap(); + assert_eq!( + ctx.additional_limit.staged_record(), + Some(&StagedRecord::Sstore(slot.data.clone())), + "the non-Berlin entry point stages too" + ); + assert_eq!(slot.data.new_value, U256::from(9)); + let slot = + Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(1), U256::from(4), false) + .unwrap(); + assert_eq!(ctx.additional_limit.staged_record(), Some(&StagedRecord::Sstore(slot.data))); + + let log = Log { + address: CONTRACT, + data: LogData::new(vec![B256::ZERO, B256::ZERO], Bytes::from_static(b"abc")).unwrap(), + }; + Host::log(&mut ctx, log); + assert_eq!( + ctx.additional_limit.staged_record(), + Some(&StagedRecord::Log { topics: 2, data_len: 3 }) + ); + + Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); + assert_eq!( + ctx.additional_limit.staged_record(), + Some(&StagedRecord::SelfDestruct { + had_value: true, + target_exists: false, + to_other_account: true, + beneficiary: BENEFICIARY, + }) + ); + assert_eq!( + ctx.additional_limit.usage(), + crate::LimitUsage::ZERO, + "the Host counts nothing" + ); + } } diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 625def230..9211394b4 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -91,12 +91,8 @@ impl MegaGasUsage { /// The regular gas a block counts for the transaction: the regular ledger, at least the /// floor (EIP-8037 with EIP-7778). The refund does not lower it. - pub const fn block_execution_gas(&self) -> u64 { - if self.regular > self.floor { - self.regular - } else { - self.floor - } + pub fn block_execution_gas(&self) -> u64 { + self.regular.max(self.floor) } } diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 5c8bfc750..a0d6a54ca 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -381,5 +381,13 @@ mod tests { t.current_mut().unwrap().account_recorded = true; t.pop(false); assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); + + t.push(Lane::new(Some(ADDR), true, u64::MAX)); + assert_eq!(t.depth(), 3); + t.pop(true); + assert!(!t.current().unwrap().account_recorded, "another account's flag is its own"); + t.push(Lane::new(None, true, u64::MAX)); + t.pop(true); + assert!(!t.current().unwrap().account_recorded, "an unknown account is not the caller's"); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 669d256e5..4b15f1d45 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -264,6 +264,18 @@ mod tests { assert!(!exceeded.within_limit()); assert!(exceeded.exceeded_limit()); assert!(!exceeded.is_frame_local()); + assert!(!exceeded.is_exempt()); + assert!(!LimitCheck::WithinLimit.is_exempt()); + assert!(!LimitCheck::WithinLimit.exceeded_limit()); + assert!(LimitCheck::WithinLimit.revert_data().is_empty()); + let frame_local = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 150, + frame_local: true, + }; + assert!(frame_local.is_frame_local()); + assert!(frame_local.exceeded_limit()); } /// Every discriminant survives the round trip, and an unknown one maps to nothing. From e82e6c0ed148defeb92ab7b703cfad383f92eddc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:13:59 +0800 Subject: [PATCH 071/201] test: cover which frame's account counts as recorded and the limit boundary --- crates/mega-evm/tests/satin/strategic_stop.rs | 18 +++ crates/mega-evm/tests/satin/write_records.rs | 152 ++++++++++++++++++ 2 files changed, 170 insertions(+) diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index d44cf03fd..7ffa4f092 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -311,6 +311,8 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); + assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO, "nothing kept"); + let (empty_call, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); assert!(empty_call.result.is_success()); assert_eq!(result.result.gas().tx_gas_used(), empty_call.result.gas().tx_gas_used()); @@ -425,3 +427,19 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { let (result, _) = run(MemoryDatabase::default(), cap(39), tx); assert_eq!(result.result.gas().reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); } + +/// A limit is crossed by usage above it: usage equal to the limit does not stop a transaction or +/// a frame. +#[test] +fn test_usage_equal_to_the_limit_does_not_stop() { + // A writes three slots: 120 bytes. + let db = || MemoryDatabase::default().account_code(A, writer()); + let (result, latched) = run(db(), cap(120), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(latched, None); + let budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(120); + let (result, _) = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + let (result, _) = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert_stopped(&result.result, LimitKind::DataSize, 119); +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 97fac526a..d77ba2b5b 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -660,3 +660,155 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { "the out-of-gas took the delegation back" ); } + +/* ---------- which frame's account counts as recorded ---------- */ + +const D: Address = address!("00000000000000000000000000000000000000D1"); + +/// A child that received value records its own account then: its own value transfers do not +/// record it again. +#[test] +fn test_value_receiving_child_records_itself_once() { + let a = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(3), "CALLEE, CONTRACT once, CONTRACT2"); +} + +/// A child that received nothing starts with its own account unrecorded, whatever its caller's +/// state. +#[test] +fn test_zero_value_child_starts_unrecorded() { + let a = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded() + .account_code(CALLEE, a) + .account_code(CONTRACT, b) + .account_balance(CONTRACT, U256::from(5)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE as the recipient, CONTRACT, CONTRACT2"); +} + +/// Calls `D` with `DELEGATECALL`. +fn delegate_to_d() -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(D) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build() +} + +/// A `DELEGATECALL` runs as its caller's account, and inherits whether that account is recorded. +#[test] +fn test_delegatecall_child_inherits_the_frame_account_record() { + let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, delegate_to_d()).account_code(D, d); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); + assert_eq!(usage, records(2), "CALLEE as the recipient, CONTRACT2"); +} + +/// A created frame's account is recorded by the creation; a `DELEGATECALL` from its init code +/// inherits that. +#[test] +fn test_created_frame_delegatecall_inherits_the_created_account_record() { + let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(D, d); + let tx = { + let mut tx = create(CALLER, delegate_to_d(), GAS_LIMIT); + tx.0.base.value = U256::from(5); + tx + }; + let (result, usage) = run(db, tx); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(2), "the created account, CONTRACT2"); +} + +/// A transaction calling its own sender (delegated) counts the sender as recorded from the start. +#[test] +fn test_top_level_self_call_counts_the_sender_as_recorded() { + let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let mut db = funded().account_code(CONTRACT, sender_code); + let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); + let account = db.load_account(CALLER).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(1), "CONTRACT2 only"); +} + +/// Answers every call to `CONTRACT` itself. +struct AnswerContract; + +impl Inspector, EthInterpreter> for AnswerContract { + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut revm::interpreter::CallInputs, + ) -> Option { + (inputs.target_address == CONTRACT).then(|| { + revm::interpreter::CallOutcome::new( + revm::interpreter::InterpreterResult::new( + revm::interpreter::InstructionResult::Stop, + Bytes::new(), + revm::interpreter::Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// A call an inspector answers gets an empty lane of its own, so its caller's lane is intact for +/// what the caller does next. +#[test] +fn test_inspector_answered_call_keeps_the_caller_lane() { + let a = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(CALL) + .append(POP); + let a = append_value_call(a, CONTRACT2, 1).append(POP).append(STOP).build(); + let mut evm = + MegaEvm::new(context(funded().account_code(CALLEE, a))).with_inspector(AnswerContract); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().additional_limit().usage(), records(2), "CALLEE and CONTRACT2"); +} From e7e5d93366a59a1e4ff278cf13790985b00163ca Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:14:43 +0800 Subject: [PATCH 072/201] test: draw the reservoir before a stop, report history gas, and rewrite results under the latch --- crates/mega-evm/tests/satin/strategic_stop.rs | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 7ffa4f092..f6fd52460 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -443,3 +443,105 @@ fn test_usage_equal_to_the_limit_does_not_stop() { let (result, _) = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert_stopped(&result.result, LimitKind::DataSize, 119); } + +/// A tool's inspector that writes to the running frame's gas or results. +#[derive(Default)] +struct Charger { + opcode: u8, + /// State gas charged after the first `SSTORE` of the transaction. + state_gas: u64, + /// History gas charged after the first `SSTORE` of the transaction. + history_gas: u64, + charged: bool, + /// Turns every call result into a success. + calls_succeed: bool, +} + +impl Inspector, EthInterpreter> for Charger { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.opcode == SSTORE && !self.charged { + self.charged = true; + assert!(interp.gas.record_state_cost(self.state_gas)); + assert!(interp.gas.record_history_cost(self.history_gas)); + } + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if self.calls_succeed { + outcome.result.result = InstructionResult::Stop; + } + } +} + +fn execute_with( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + charger: Charger, + gas_limit: u64, +) -> mega_evm::MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(charger) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)) + .unwrap() +} + +/// State gas drawn from the reservoir before the stop is refilled by it: the stopped transaction +/// hands the whole reservoir back, where a transaction that kept the state keeps the charge. +#[test] +fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { + let gas_limit = 1_000_000_000; + let reservoir = gas_limit - TX_GAS_LIMIT_CAP; + let charger = || Charger { state_gas: 50_000, ..Default::default() }; + let kept = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), charger(), gas_limit); + assert!(kept.result.is_success()); + assert_eq!(kept.gas.reservoir_remaining, reservoir - 50_000, "the kept charge"); + assert_eq!(kept.gas.state, 50_000); + + let stopped = execute_with(chain(), cap(180), charger(), gas_limit); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); + assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); + assert_eq!(stopped.gas.state, 0); +} + +/// History gas a transaction spent is reported on its outcome, apart from regular gas; a stop +/// takes it back with the rest. +#[test] +fn test_outcome_reports_history_gas() { + let charger = || Charger { history_gas: 700, ..Default::default() }; + let kept = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), charger(), GAS_LIMIT); + let plain = + execute_with(chain(), EvmTxRuntimeLimits::no_limits(), Charger::default(), GAS_LIMIT); + assert!(kept.result.is_success()); + assert_eq!(kept.gas.history, 700); + assert_eq!(kept.gas.regular, plain.gas.regular, "history is not regular gas"); + assert_eq!(kept.gas.gas_used, plain.gas.gas_used + 700); + + let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); + assert_eq!(stopped.gas.history, 0); +} + +/// Under the latch every returned result is the stop, whatever an inspector made of it: rewriting +/// the calls' results into successes neither resumes a caller nor lets the transaction succeed. +#[test] +fn test_latch_overrides_a_rewritten_result() { + let charger = Charger { calls_succeed: true, ..Default::default() }; + let outcome = execute_with(chain(), cap(180), charger, GAS_LIMIT); + assert_stopped(&outcome.result, LimitKind::DataSize, 180); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(outcome.usage, mega_evm::LimitUsage::ZERO, "every lane failed"); + assert!(outcome.result.logs().is_empty()); +} From b8bcb43d40c2ba787940e648d6a92afc5303c18e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:16:41 +0800 Subject: [PATCH 073/201] fix: check a declared observer's inputs, stack, memory and journal writes in debug builds --- crates/mega-evm/src/evm/inspector.rs | 106 +++++++++++-- crates/mega-evm/tests/satin/inspector.rs | 189 ++++++++++++++++++++++- 2 files changed, 277 insertions(+), 18 deletions(-) diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index f2d6088a7..eb255511e 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -15,7 +15,7 @@ //! declaration, and [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what //! block execution refuses a transaction on: a rewriting inspector has no route to a block. //! [`DeclaredObserver`] carries the declaration for a tracer whose type cannot, and in debug -//! builds checks it at every callback. +//! builds checks it around every callback. //! - **The refusal.** A failed contract creation rewritten into a successful one is refused: the //! transaction fails with [`FORBIDDEN_CREATE_REVIVAL`] as an `EVMError::Custom`. By the time //! `create_end` runs, revm has reverted the frame and deposited no code, so the rewrite would @@ -27,9 +27,9 @@ use alloc as std; use std::{format, string::String}; use revm::{ - context::{ContextError, ContextTr}, + context::{ContextError, ContextTr, JournalTr}, handler::FrameResult, - inspector::{handler::frame_end, NoOpInspector}, + inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, Interpreter, InterpreterTypes, @@ -71,8 +71,13 @@ impl TrustedObserver for &mut T {} /// /// It forwards every callback to the inspector inside and adds nothing. `DeclaredObserver(tracer)` /// says "this tracer writes nothing back", moved from a type definition to the line that wraps -/// the value. Wrapping an inspector that writes is a false declaration, and a debug build panics -/// at the callback that breaks it. +/// the value. +/// +/// A debug build checks the declaration around every callback and panics at the one that breaks +/// it: the interpreter's gas, pending action, stack depth and memory size, the frame's inputs, +/// the frame result, and the journal's entries and logs must be as they were, and no frame may be +/// answered. Writes the check cannot see (a stack word replaced in place, a context field outside +/// the journal) are still false declarations; the check is a tripwire, not a proof. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct DeclaredObserver(pub I); @@ -93,39 +98,42 @@ impl TrustedObserver for DeclaredObserver {} impl Inspector for DeclaredObserver where I: Inspector, + CTX: ContextTr, INTR: InterpreterTypes, { #[inline] fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = gas_snapshot(interp); + let before = snapshot(interp, context); self.0.initialize_interp(interp, context); - assert_gas_unwritten(before, interp, "initialize_interp"); + assert_unwritten(before, interp, context, "initialize_interp"); } #[inline] fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = gas_snapshot(interp); + let before = snapshot(interp, context); self.0.step(interp, context); - assert_gas_unwritten(before, interp, "step"); + assert_unwritten(before, interp, context, "step"); } #[inline] fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = gas_snapshot(interp); + let before = snapshot(interp, context); self.0.step_end(interp, context); - assert_gas_unwritten(before, interp, "step_end"); + assert_unwritten(before, interp, context, "step_end"); } #[inline] fn log(&mut self, context: &mut CTX, log: Log) { + let before = journal_snapshot(context); self.0.log(context, log); + assert_journal_unwritten(before, context, "log"); } #[inline] fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let before = gas_snapshot(interp); + let before = snapshot(interp, context); self.0.log_full(interp, context, log); - assert_gas_unwritten(before, interp, "log_full"); + assert_unwritten(before, interp, context, "log_full"); } #[inline] @@ -134,8 +142,14 @@ where context: &mut CTX, frame_input: &mut FrameInput, ) -> Option { + let before = + cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); let answer = self.0.frame_start(context, frame_input); debug_assert!(answer.is_none(), "a declared observer answered a frame in `frame_start`"); + if let Some((input, journal)) = before { + debug_assert!(&input == frame_input, "a declared observer rewrote a frame's inputs"); + assert_journal_unwritten(journal, context, "frame_start"); + } answer } @@ -147,38 +161,46 @@ where frame_result: &mut FrameResult, ) { let before = result_snapshot(frame_result); + let journal = journal_snapshot(context); self.0.frame_end(context, frame_input, frame_result); assert_result_unwritten(before, frame_result, "frame_end"); + assert_journal_unwritten(journal, context, "frame_end"); } #[inline] fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); let answer = self.0.call(context, inputs); debug_assert!(answer.is_none(), "a declared observer answered a call"); if let Some(before) = before { debug_assert!(&before == inputs, "a declared observer rewrote a call's inputs"); } + assert_journal_unwritten(journal, context, "call"); answer } #[inline] fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); self.0.call_end(context, inputs, outcome); if let Some(before) = before { debug_assert!(&before == outcome, "a declared observer rewrote a call result"); } + assert_journal_unwritten(journal, context, "call_end"); } #[inline] fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); let answer = self.0.create(context, inputs); debug_assert!(answer.is_none(), "a declared observer answered a creation"); if let Some(before) = before { debug_assert!(&before == inputs, "a declared observer rewrote a creation's inputs"); } + assert_journal_unwritten(journal, context, "create"); answer } @@ -190,10 +212,12 @@ where outcome: &mut CreateOutcome, ) { let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); self.0.create_end(context, inputs, outcome); if let Some(before) = before { debug_assert!(&before == outcome, "a declared observer rewrote a creation result"); } + assert_journal_unwritten(journal, context, "create_end"); } #[inline] @@ -202,13 +226,61 @@ where } } -/// An interpreter's gas and pending action, for the debug-build proof. `None` in release builds. -type GasSnapshot = Option<(revm::interpreter::Gas, bool)>; +/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. +type JournalSnapshot = Option<(usize, usize)>; + +#[inline] +fn journal_snapshot>(context: &CTX) -> JournalSnapshot { + cfg!(debug_assertions) + .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) +} + +#[inline] +fn assert_journal_unwritten>( + before: JournalSnapshot, + context: &CTX, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + journal_snapshot(context).expect("debug build"), + "a declared observer wrote to the journal in `{callback}`" + ); + } +} + +/// An interpreter's and the journal's state, for the debug-build proof. +type Snapshot = (GasSnapshot, JournalSnapshot); + +#[inline] +fn snapshot>( + interp: &Interpreter, + context: &CTX, +) -> Snapshot { + (gas_snapshot(interp), journal_snapshot(context)) +} + +#[inline] +fn assert_unwritten>( + (gas, journal): Snapshot, + interp: &Interpreter, + context: &CTX, + callback: &str, +) { + assert_gas_unwritten(gas, interp, callback); + assert_journal_unwritten(journal, context, callback); +} + +/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. +/// `None` in release builds. +type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; #[inline] fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { - use revm::interpreter::interpreter_types::LoopControl; - cfg!(debug_assertions).then(|| (interp.gas, interp.bytecode.is_end())) + use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; + cfg!(debug_assertions) + .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) } #[inline] diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index 6d8ba7309..b80a5ad8c 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -2,7 +2,7 @@ //! admission gate block execution keys on. use alloy_evm::Evm; -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, DeclaredObserver, MegaContext, MegaEvm, FORBIDDEN_CREATE_REVIVAL, @@ -364,3 +364,190 @@ fn test_frame_start_and_end_stay_paired() { let latched = no_limits.with_tx_data_size_limit(0); assert_eq!(pairs(funded, latched, 1), (1, 1, 0, 0), "the stopped first frame ends too"); } + +/// Counts every callback it gets. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Recorder { + initialize_interp: usize, + step: usize, + step_end: usize, + log_full: usize, + frame_start: usize, + frame_end: usize, + call: usize, + call_end: usize, + create: usize, + create_end: usize, + selfdestruct: usize, +} + +impl Inspector, EthInterpreter> for Recorder { + fn initialize_interp(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.initialize_interp += 1; + } + fn step(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.step += 1; + } + fn step_end(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.step_end += 1; + } + fn log_full(&mut self, _: &mut Interpreter, _: &mut MegaContext, _: Log) { + self.log_full += 1; + } + fn frame_start( + &mut self, + _: &mut MegaContext, + _: &mut revm::interpreter::FrameInput, + ) -> Option { + self.frame_start += 1; + None + } + fn frame_end( + &mut self, + _: &mut MegaContext, + _: &revm::interpreter::FrameInput, + _: &mut revm::handler::FrameResult, + ) { + self.frame_end += 1; + } + fn call(&mut self, _: &mut MegaContext, _: &mut CallInputs) -> Option { + self.call += 1; + None + } + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, _: &mut CallOutcome) { + self.call_end += 1; + } + fn create(&mut self, _: &mut MegaContext, _: &mut CreateInputs) -> Option { + self.create += 1; + None + } + fn create_end(&mut self, _: &mut MegaContext, _: &CreateInputs, _: &mut CreateOutcome) { + self.create_end += 1; + } + fn selfdestruct(&mut self, _: Address, _: Address, _: U256) { + self.selfdestruct += 1; + } +} + +/// A contract that logs, creates a contract, calls `B` and self-destructs. +fn busy_contract() -> MemoryDatabase { + let init_code = [0x60, 0x01, 0x60, 0x00, 0xf3]; + let mut word = [0u8; 32]; + word[..init_code.len()].copy_from_slice(&init_code); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .append(revm::bytecode::opcode::LOG0) + .mstore(0, word) + .push_number(init_code.len() as u64) + .append_many([PUSH0, PUSH0]) + .append(CREATE) + .append(revm::bytecode::opcode::POP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append(GAS) + .append(CALL) + .append(revm::bytecode::opcode::POP) + .push_address(B) + .append(revm::bytecode::opcode::SELFDESTRUCT) + .build(); + MemoryDatabase::default().account_code(A, code).account_code(B, Bytes::from_static(&[0x00])) +} + +/// A declared observer forwards every callback to the inspector inside. +#[test] +fn test_declared_observer_forwards_every_callback() { + let mut plain = MegaEvm::new(context(busy_contract())).with_inspector(Recorder::default()); + plain.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let mut declared = MegaEvm::new(context(busy_contract())) + .with_trusted_inspector(DeclaredObserver::new(Recorder::default())); + declared.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + let seen = plain.inspector().clone(); + assert_eq!(declared.inspector().0, seen); + assert!( + seen.initialize_interp > 0 && + seen.step > 0 && + seen.step_end > 0 && + seen.log_full > 0 && + seen.frame_start > 0 && + seen.frame_end > 0 && + seen.call > 0 && + seen.call_end > 0 && + seen.create > 0 && + seen.create_end > 0 && + seen.selfdestruct > 0, + "every callback ran: {seen:?}" + ); + assert_eq!(DeclaredObserver::new(Recorder::default()).into_inner(), Recorder::default()); +} + +/// Edits a frame's inputs, writes to the journal, or rewrites a frame result, one per flag. +#[derive(Default)] +struct Writer { + edit_inputs: bool, + log_in_step: bool, + rewrite_frame_end: bool, +} + +impl Inspector, EthInterpreter> for Writer { + fn step(&mut self, _interp: &mut Interpreter, context: &mut MegaContext) { + if self.log_in_step { + let log = Log { address: A, data: Default::default() }; + revm::context::JournalTr::log(revm::context::ContextTr::journal_mut(context), log); + } + } + + fn frame_start( + &mut self, + _context: &mut MegaContext, + frame_input: &mut revm::interpreter::FrameInput, + ) -> Option { + if let (true, revm::interpreter::FrameInput::Call(inputs)) = (self.edit_inputs, frame_input) + { + inputs.gas_limit -= 1; + } + None + } + + fn frame_end( + &mut self, + _context: &mut MegaContext, + _frame_input: &revm::interpreter::FrameInput, + frame_result: &mut revm::handler::FrameResult, + ) { + if self.rewrite_frame_end { + frame_result.interpreter_result_mut().output = Bytes::from_static(b"rewritten"); + } + } +} + +fn run_declared(writer: Writer) { + let mut evm = + MegaEvm::new(context(writes_two_slots())).with_trusted_inspector(DeclaredObserver(writer)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared observer that edits a frame's inputs fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a frame's inputs")] +fn test_false_declaration_of_an_input_edit_fails_in_debug() { + run_declared(Writer { edit_inputs: true, ..Default::default() }); +} + +/// A declared observer that writes to the journal fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer wrote to the journal in `step`")] +fn test_false_declaration_of_a_journal_write_fails_in_debug() { + run_declared(Writer { log_in_step: true, ..Default::default() }); +} + +/// A declared observer that rewrites a frame result in `frame_end` fails its declaration in a +/// debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a frame result in `frame_end`")] +fn test_false_declaration_of_a_frame_end_rewrite_fails_in_debug() { + run_declared(Writer { rewrite_frame_end: true, ..Default::default() }); +} From 0137dafa57b8d289daa26bfda699aa5dd4a98ba4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:18:13 +0800 Subject: [PATCH 074/201] test: pin fees, refunds, system calls and rejections against op-revm --- crates/mega-evm/tests/satin/equivalence.rs | 127 +++++++++++++++++++-- 1 file changed, 118 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index fce269ed5..8817fca82 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -50,21 +50,35 @@ fn block() -> BlockEnv { /// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the /// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes and that `CfgEnv`. fn run_both(db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, CfgEnv) { + run_both_in(db, tx, block()) +} + +/// [`run_both`] in `block`. +fn run_both_in( + db: MemoryDatabase, + tx: TxEnv, + block: BlockEnv, +) -> (Outcome, Outcome, CfgEnv) { + let (mut mega, mut op, cfg) = both_evms(db, block); + let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap(); + let op_outcome = op.transact(op_transaction(tx)).unwrap(); + (mega_outcome, op_outcome, cfg) +} + +/// A `MegaEvm` and an `OpEvm` over `db` in `block`, on the same `CfgEnv`. +fn both_evms( + db: MemoryDatabase, + block: BlockEnv, +) -> (MegaEvm, OpEvm, CfgEnv) { let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) - .with_block(block()) + .with_block(block.clone()) .with_chain(zero_fee_l1_block_info()); let cfg = ctx.cfg().clone(); - let mut mega = MegaEvm::new(ctx); - let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap(); - let op_ctx = OpContext::new(db, OpSpecId::KARST) .with_cfg(cfg.clone()) - .with_block(block()) + .with_block(block) .with_chain(zero_fee_l1_block_info()); - let mut op = OpEvm::new(op_ctx, NoOpInspector); - let op_outcome = op.transact(op_transaction(tx)).unwrap(); - - (mega_outcome, op_outcome, cfg) + (MegaEvm::new(ctx), OpEvm::new(op_ctx, NoOpInspector), cfg) } /// Asserts the two outcomes agree field by field, then as a whole so a field added later is @@ -153,3 +167,98 @@ fn test_sstore_matches_op_revm() { assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); } + +const COINBASE: Address = address!("0x00000000000000000000000000000000000c0ffe"); + +/// A priced transaction pays its fee, gets its unused gas back and rewards the beneficiary and +/// the fee vaults exactly as op-revm has it. +#[test] +fn test_fees_match_op_revm() { + let db = + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))).account_code( + CALLEE, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + let block = BlockEnv { basefee: 7, beneficiary: COINBASE, ..block() }; + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value: U256::from(1_000), + gas_price: 10, + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, _) = run_both_in(db, tx, block); + assert!(mega.result.is_success()); + assert!(mega.state[&COINBASE].info.balance > U256::ZERO, "the beneficiary was paid"); + assert!( + mega.state[&CALLER].info.balance > U256::from(10u64.pow(18) - 10 * 1_000_000 - 1_000), + "the unused gas came back" + ); + assert_same(&mega, &op); +} + +/// A storage refund is applied exactly as op-revm has it. +#[test] +fn test_refund_matches_op_revm() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code).account_storage( + CALLEE, + U256::ZERO, + U256::from(5), + ); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, _) = run_both(db, tx); + assert!(mega.result.is_success()); + assert!(mega.result.gas().inner_refunded() > 0, "the clear is refunded"); + assert_same(&mega, &op); +} + +/// A system call runs exactly as op-revm runs it. +#[test] +fn test_system_call_matches_op_revm() { + use revm::handler::system_call::SystemCallEvm; + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(3)).stop().build(); + let (mut mega, mut op, _) = + both_evms(MemoryDatabase::default().account_code(CALLEE, code), block()); + let mega_outcome = mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let op_outcome = op.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + assert!(mega_outcome.result.is_success()); + assert_same(&mega_outcome, &op_outcome); +} + +/// A transaction op-revm rejects, Satin rejects with the same error. +#[test] +fn test_invalid_transaction_matches_op_revm() { + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mut mega, mut op, _) = both_evms(MemoryDatabase::default(), block()); + let unenveloped = OpTransaction { base: tx, enveloped_tx: None, ..Default::default() }; + let mega_error = mega.transact(OpTx(unenveloped.clone())).unwrap_err(); + let op_error = op.transact(unenveloped).unwrap_err(); + assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); + assert!(format!("{mega_error:?}").contains("MissingEnvelopedTx"), "{mega_error:?}"); + + // A gas limit above the block's is rejected before anything is charged. + let small_block = BlockEnv { gas_limit: 500_000, ..block() }; + let (mut mega, mut op, _) = both_evms(MemoryDatabase::default(), small_block); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let mega_error = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap_err(); + let op_error = op.transact(op_transaction(tx)).unwrap_err(); + assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); + assert!(format!("{mega_error:?}").contains("CallerGasLimitMoreThanBlock"), "{mega_error:?}"); +} From 4d092109aaa5e2949589e3a443a4b44e99f3c92c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:19:04 +0800 Subject: [PATCH 075/201] test: pin the synthetic-result settlement to revm's frame return --- .../tests/satin/synthetic_frame_gas.rs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 75e7a212c..4178bcb79 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -163,3 +163,59 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { assert_eq!(small.tx_gas_used(), large.tx_gas_used()); assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); } + +/// `settle_frame_result` settles a result into its caller's gas exactly as revm's frame return +/// does, for a success, a revert and a halt, with state gas drawn from the reservoir and spilled +/// onto regular gas. +#[test] +fn test_settle_frame_result_matches_revms_frame_return() { + use mega_evm::{settle_frame_result, synthetic_frame_result}; + use revm::context::result::EVMError; + + for result_kind in + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] + { + let code = Bytes::from_static(&[revm::bytecode::opcode::STOP]); + let mut evm = + MegaEvm::new(context(MemoryDatabase::default().account_code(TARGET, code.clone()))); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account(TARGET).unwrap(); + let mut caller_init = call_frame_init(1); + if let FrameInput::Call(inputs) = &mut caller_init.frame_input { + let bytecode = revm::state::Bytecode::new_raw(code.clone()); + inputs.known_bytecode = (bytecode.hash_slow(), bytecode); + } + let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, caller_init).unwrap() else { + panic!("the caller frame is built"); + }; + + // The child the caller starts: 30,000 gas of the caller's, and its reservoir. + let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); + let caller_frame = frames.get(); + assert!(caller_frame.interpreter.gas.record_regular_cost(30_000)); + let child_input = { + let FrameInput::Call(mut inputs) = call_frame_init(2).frame_input else { + unreachable!() + }; + inputs.gas_limit = 30_000; + inputs.reservoir = caller_frame.interpreter.gas.reservoir(); + FrameInput::Call(inputs) + }; + let mut result = synthetic_frame_result(&child_input, result_kind, Bytes::new()); + // The child spent regular gas, and state gas beyond the reservoir that spilled. + let child_gas = result.gas_mut(); + assert!(child_gas.record_regular_cost(1_000)); + assert!(child_gas.record_state_cost(RESERVOIR + 500)); + + let mut expected = *caller_frame.interpreter.gas.tracker(); + settle_frame_result::<_, EVMError>( + ctx, + &mut expected, + &mut result.clone(), + ) + .unwrap(); + caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); + assert_eq!(caller_frame.interpreter.gas.tracker(), &expected, "{result_kind:?}"); + } +} From 7515a9ae3d01f2b6dd6252840654c46f8928a835 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:19:36 +0800 Subject: [PATCH 076/201] test: name the ported tests after what they check --- crates/mega-evm/src/evm/result.rs | 4 ++-- crates/mega-evm/src/limit/frame_limit.rs | 4 ++-- crates/mega-evm/tests/satin/db_error.rs | 8 ++++---- crates/mega-evm/tests/satin/outcome.rs | 22 ++++++++++++++++++++-- crates/mega-evm/tests/satin/state.rs | 2 +- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 9211394b4..7e75c41b4 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -148,7 +148,7 @@ mod tests { /// A limit stop is not a halt: it is a revert whose output is `MegaLimitExceeded`, for every /// dimension. #[test] - fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { + fn test_limit_stops_are_reverts_with_mega_limit_exceeded() { for kind in [ LimitKind::DataSize, LimitKind::KVUpdate, @@ -171,7 +171,7 @@ mod tests { /// No halt reason of Satin's own exists: every one but the failed deposit is Ethereum's. #[test] - fn test_all_mega_specific_variants_fail_eth_conversion() { + fn test_only_the_failed_deposit_is_not_an_ethereum_halt() { let reasons = [ MegaHaltReason::Base(EthHaltReason::OutOfGas(OutOfGasError::Basic)), MegaHaltReason::Base(EthHaltReason::OpcodeNotFound), diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index a0d6a54ca..c324f3b7c 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -231,7 +231,7 @@ mod tests { /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. #[test] - fn test_set_created_address_empty_stack_is_noop() { + fn test_record_caller_without_a_caller_lane_is_noop() { let mut t = FrameLimitTracker::default(); t.record_caller(true); assert_eq!(t.net(), LimitUsage::ZERO); @@ -243,7 +243,7 @@ mod tests { /// A frame's caller is recorded once per caller frame: a second child finds it recorded. #[test] - fn test_set_created_address_duplicate_panics() { + fn test_record_caller_records_a_caller_once() { let mut t = FrameLimitTracker::default(); t.push(Lane::new(Some(ADDR), false, u64::MAX)); t.push(Lane::new(None, true, u64::MAX)); diff --git a/crates/mega-evm/tests/satin/db_error.rs b/crates/mega-evm/tests/satin/db_error.rs index bfc5be1f2..319dd3463 100644 --- a/crates/mega-evm/tests/satin/db_error.rs +++ b/crates/mega-evm/tests/satin/db_error.rs @@ -48,7 +48,7 @@ fn funded(code: Bytes) -> MemoryDatabase { /// A failing storage read in `SSTORE` surfaces as the database error. #[test] -fn test_sstore_db_error_on_inspect_storage() { +fn test_sstore_storage_read_error_fails_the_transaction() { let key = U256::from(0x42); let code = BytecodeBuilder::default().sstore(key, U256::from(1)).stop().build(); let mut db = ErrorInjectingDatabase::new(funded(code)); @@ -71,7 +71,7 @@ fn call_target(opcode: u8) -> Bytes { /// A failing account read of a value transfer's recipient surfaces as the database error. #[test] -fn test_call_with_transfer_db_error_on_inspect_account() { +fn test_value_call_account_read_error_fails_the_transaction() { let mut db = ErrorInjectingDatabase::new(funded(call_target(CALL))); db.fail_on_account = Some(TARGET); assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); @@ -80,7 +80,7 @@ fn test_call_with_transfer_db_error_on_inspect_account() { /// A creation that writes storage never reads the created account's storage from the database: /// it is empty, and a stateless witness has nothing for it. #[test] -fn test_inspect_storage_skips_db_for_newly_created_account() { +fn test_created_account_storage_is_never_read_from_the_database() { let init_code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(0x42)).stop().build(); let created = CALLER.create(0); let inner = MemoryDatabase::default() @@ -94,7 +94,7 @@ fn test_inspect_storage_skips_db_for_newly_created_account() { /// A failing account read of a `STATICCALL` target surfaces as the database error. #[test] -fn test_staticcall_db_error_on_inspect_account() { +fn test_staticcall_account_read_error_fails_the_transaction() { let mut db = ErrorInjectingDatabase::new(funded(call_target(STATICCALL))); db.fail_on_account = Some(TARGET); assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index a578d127d..e6a59ecd6 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -8,7 +8,6 @@ use mega_evm::{ BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, }; -use revm::inspector::NoOpInspector; use crate::common::{call, context}; @@ -88,14 +87,33 @@ fn test_spoofed_revert_data_is_not_a_stop() { assert_eq!(outcome.limit_exceeded, None); } +/// Counts the steps it sees. +#[derive(Default)] +struct Steps(usize); + +impl revm::Inspector for Steps { + fn step( + &mut self, + _interp: &mut revm::interpreter::Interpreter< + revm::interpreter::interpreter::EthInterpreter, + >, + _context: &mut CTX, + ) { + self.0 += 1; + } +} + /// `execute_transaction` runs the inspector when one is enabled, and not otherwise. #[test] fn test_convenience_execution_methods_work() { - let mut evm = MegaEvm::new(context(writer())).with_inspector(NoOpInspector); + let mut evm = MegaEvm::new(context(writer())).with_inspector(Steps::default()); let inspected = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); assert!(inspected.result.is_success()); + let steps = evm.inspector().0; + assert!(steps > 0, "the enabled inspector ran"); alloy_evm::Evm::set_inspector_enabled(&mut evm, false); let executed = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); assert!(executed.result.is_success()); + assert_eq!(evm.inspector().0, steps, "the disabled inspector did not run"); assert_eq!(inspected.gas, executed.gas); } diff --git a/crates/mega-evm/tests/satin/state.rs b/crates/mega-evm/tests/satin/state.rs index ffe8ef594..bec75ebc7 100644 --- a/crates/mega-evm/tests/satin/state.rs +++ b/crates/mega-evm/tests/satin/state.rs @@ -80,7 +80,7 @@ fn two_calls_returning_the_second(first: Address, second: Address) -> Bytes { /// A write through an EIP-7702 delegator goes to the delegator's storage: the delegate's own slot /// keeps its original value when the delegate later runs in its own context. #[test] -fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { +fn test_write_through_a_delegator_leaves_the_delegate_storage_alone() { let delegate_code = BytecodeBuilder::default() .sstore(U256::from(1), U256::from(0x77)) .push_number(1u8) From fe6ea74eef4db25df30c1fbd8f9543cc9607019b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:20:01 +0800 Subject: [PATCH 077/201] docs: record the review round's rules in AGENTS.md and the frame init order --- AGENTS.md | 6 ++++-- crates/mega-evm/src/evm/execution.rs | 8 +++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 01db1f339..909d5878e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -125,7 +125,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's. - **Write records.** One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account. - The sender's own account is part of the transaction body. + The sender's own account is part of the transaction body: it is never a record, and a frame running as the sender (through an EIP-7702 delegation) counts it as recorded. Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped. The KV count a node reports is the write-record count. - **Lanes stay aligned with frames.** @@ -133,7 +133,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **The latch.** A transaction-level limit stops the transaction with a revert, never a halt: the frame that crosses it reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)`, the transaction is latched (`AdditionalLimit::latch`), no caller resumes (`before_frame_run`), no frame starts, every result returned above is rewritten to the stop, and the outermost frame settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. A frame budget reverts its frame alone, without a latch. - A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn. + A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed), and EIP-7702 authorities whose records would cross it are taken back before the first frame. + A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted. + The layer's state belongs to one transaction: every entry point of `MegaEvm` resets it before it runs the handler. The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes. - **Synthetic frame results carry the caller's pools.** A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 2adaa978c..c285a153e 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -236,8 +236,14 @@ impl EvmTr for MegaEvm Date: Fri, 18 Sep 2026 19:23:13 +0800 Subject: [PATCH 078/201] style: drop the trailing blank line of a parked test file --- crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs index ab41bf66b..1f9e9d19c 100644 --- a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs @@ -164,4 +164,3 @@ fn test_rex6_create_net_new_inspect_db_error_surfaces() { let res = alloy_evm::Evm::transact_raw(&mut evm, tx); assert!(res.is_err(), "DB error during REX6 CREATE net-new inspect must surface as Err"); } - From f7c9738ef53cb656dfed1c62e11309bbe1ac2b60 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:33:00 +0800 Subject: [PATCH 079/201] test: pin the authority records at the data-size cap --- crates/mega-evm/tests/satin/write_records.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index d77ba2b5b..d0faaaff5 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -616,11 +616,18 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { /// frame. #[test] fn test_authorities_crossing_the_cap_are_not_applied() { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(39); - let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) - .unwrap(); + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let with_cap = |cap| { + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(cap); + MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) + .unwrap() + }; + let at_the_cap = with_cap(40); + assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); + assert_eq!(at_the_cap.usage, records(1)); + + let outcome = with_cap(39); assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); assert!(outcome.limit_exceeded.is_some()); let authority = outcome.state.get(&AUTHORITY_1); From 06303397cb639b3ce24da0a607e1988c7cc445bb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:33:00 +0800 Subject: [PATCH 080/201] refactor: check every creation's nonce bump, the outermost one included --- crates/mega-evm/src/evm/execution.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index c285a153e..7000aa11f 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -263,9 +263,11 @@ impl EvmTr for MegaEvm 0 => { + FrameInput::Create(inputs) => { Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) } _ => None, From 3955e66625f6b4f39b6784cfb9d5f938dc7da295 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 18 Sep 2026 19:33:00 +0800 Subject: [PATCH 081/201] test: suppress the equivalent and dead mutants of the common execution layer --- mutants/suppressions.toml | 53 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 9c3253769..592ecf856 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -233,3 +233,56 @@ file = "crates/mega-evm/src/test_utils/scenario.rs" mutant = "delete field gas_limit from struct BlockEnv expression in Scenario::block" justification = "Equivalent: the field writes u64::MAX and revm 40's BlockEnv::default() already has gas_limit: u64::MAX, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." reviewer = "RealiCZ" + +# ───────────────────────────────────────────────────────────────────────────── +# crates/mega-evm/src/ survivors of the common execution layer. + +# --- inspect_frame_init: logs journaled by frame init (dead while EIP-7708 is off) -------- +# `inspect_frame_init` mirrors revm's: after `frame_init`, the logs journaled since `logs_i` +# (EIP-7708 transfer logs, a precompile's logs) go to the inspector's `log` callback. Satin's +# spec configuration fixes EIP-7708 off (`MegaContext::with_cfg`), and op-revm's precompile set +# journals no log, so frame init never journals one: the length comparisons are always false +# and `inspect_logs` is never entered. Flipping `!=` to `==` would call `inspect_logs` over an +# empty range, a no-op; stubbing it changes nothing reachable. Live again when the Satin gas +# table switches EIP-7708 on, at which point a transfer-log test kills them. +[[suppress]] +kind = "line" +category = "dead" +file = "crates/mega-evm/src/evm/execution.rs" +mutant = "replace != with == in >::inspect_frame_init" +justification = "Dead in Satin: frame init journals no log (EIP-7708 is fixed off by the spec configuration, op-revm's precompiles journal none), so both `logs().len() != logs_i` comparisons are always false; with `==` the call hands the inspector an empty range, a no-op. Becomes live, and killable, when EIP-7708 is switched on." +reviewer = "RealiCZ" + +[[suppress]] +kind = "line" +category = "dead" +file = "crates/mega-evm/src/evm/execution.rs" +mutant = "replace inspect_logs with ()" +justification = "Dead in Satin: only called for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile). Becomes live, and killable, when EIP-7708 is switched on." +reviewer = "RealiCZ" + +# --- DeclaredObserver::log forwarding (dead while EIP-7708 is off) ---------------------- +# revm hands a log to `Inspector::log` (without an interpreter) only from the frame-init path +# above; every log an opcode emits goes to `log_full`, which the forwarding test covers. +[[suppress]] +kind = "line" +category = "dead" +file = "crates/mega-evm/src/evm/inspector.rs" +mutant = "replace for DeclaredObserver>::log with ()" +justification = "Dead in Satin: revm calls `Inspector::log` only for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile); opcode logs reach `log_full`, which test_declared_observer_forwards_every_callback covers. Becomes live when EIP-7708 is switched on." +reviewer = "RealiCZ" + +# --- AdditionalLimit::discard_stale_record (equivalent) --------------------------------- +# Every wrapper discards a record staged before its opcode on entry. The three wrapped opcodes +# each stage their own record through the Host whenever they complete (SSTORE through +# sstore_skip_cold_load, LOG through log, SELFDESTRUCT through selfdestruct), which overwrites a +# stale one, and a failing opcode's wrapper discards whatever is staged. So a stale record can +# never be committed with or without the entry discard; it is the contract's guard for a future +# wrapped opcode that completes without a Host call. +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/limit/limit.rs" +mutant = "replace AdditionalLimit::discard_stale_record with ()" +justification = "Equivalent: each wrapped opcode (SSTORE, LOG0-4, SELFDESTRUCT) stages its own record through the Host whenever it completes, overwriting a stale one, and a failing opcode's wrapper discards the staged record, so no stale record can be committed with or without the entry discard (test_wrapper_discards_a_stale_record_on_entry shows the stale log is not counted either way)." +reviewer = "RealiCZ" From 6074ef988d8a7fceb43c695be1b972b4d6b0c4f9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:38:12 +0800 Subject: [PATCH 082/201] bench: give the corpus bench its own scenario inputs --- AGENTS.md | 2 +- REVIEW.md | 2 +- crates/mega-evm/Cargo.toml | 7 +- crates/mega-evm/benches/corpus.rs | 44 +++++------ .../access_list_warm_slots_and_account.json | 43 +++++++++++ .../benches/scenarios/create_success.json | 28 +++++++ .../eip7702_delegate_new_authority.json | 34 +++++++++ .../scenarios/logs_all_topic_counts.json | 23 ++++++ .../nested_call_revert_with_spill.json | 34 +++++++++ .../scenarios/precompile_ecrecover.json | 31 ++++++++ .../benches/scenarios/precompile_modexp.json | 31 ++++++++ ...reated_in_same_tx_to_existing_account.json | 27 +++++++ .../benches/scenarios/sstore_set_spills.json | 28 +++++++ .../benches/scenarios/system_call.json | 26 +++++++ ...with_sstore_fork_Amsterdam_state_test.json | 27 +++++++ ...e_deepest_depth_10_sstore_restoration.json | 75 +++++++++++++++++++ .../benches/scenarios/two_txs_sequential.json | 36 +++++++++ 17 files changed, 471 insertions(+), 27 deletions(-) create mode 100644 crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json create mode 100644 crates/mega-evm/benches/scenarios/create_success.json create mode 100644 crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json create mode 100644 crates/mega-evm/benches/scenarios/logs_all_topic_counts.json create mode 100644 crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json create mode 100644 crates/mega-evm/benches/scenarios/precompile_ecrecover.json create mode 100644 crates/mega-evm/benches/scenarios/precompile_modexp.json create mode 100644 crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json create mode 100644 crates/mega-evm/benches/scenarios/sstore_set_spills.json create mode 100644 crates/mega-evm/benches/scenarios/system_call.json create mode 100644 crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json create mode 100644 crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json create mode 100644 crates/mega-evm/benches/scenarios/two_txs_sequential.json diff --git a/AGENTS.md b/AGENTS.md index 909d5878e..451381f9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (a slice of the differential corpus), `factory` (EVM construction) +# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (JSON scenarios, a bench input), `factory` (EVM construction) cargo bench -p mega-evm --bench # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) diff --git a/REVIEW.md b/REVIEW.md index 26a9729e9..836f5f84d 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -98,7 +98,7 @@ These checks guard every change to the Satin engine. ### Instruction counts (CodSpeed) -- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (a slice of the differential corpus through `MegaEvm`) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. +- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (the JSON scenarios under `benches/scenarios` through `MegaEvm`, a bench input rather than a conformance suite) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. - `codspeed.yml` runs them under instrumentation on every pull request that touches code and on every push to `satin`; the baseline a pull request is compared with is the latest `satin` push. - Read regressions from the CodSpeed report on the pull request (the CodSpeed comment and the `CodSpeed Performance Analysis` check). The regression threshold that fails that check is a setting of the repository's CodSpeed project; it is not recorded in this repository or in the reports CodSpeed posts, so this file does not state a number. diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 0918d6684..0989e6d51 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -56,9 +56,10 @@ std = [ ] test-utils = ["dep:derive_more"] -# The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (a slice of the differential -# corpus) and `factory` (EVM construction). The inputs under benches/data (revm_bench) and -# benches/fixtures (attack_replay) stay for the rebuild of the rest of the suite. +# The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (the JSON scenarios under +# benches/scenarios, a bench input) and `factory` (EVM construction). The inputs under +# benches/data (revm_bench) and benches/fixtures (attack_replay) stay for the rebuild of the rest +# of the suite. [[bench]] name = "corpus" harness = false diff --git a/crates/mega-evm/benches/corpus.rs b/crates/mega-evm/benches/corpus.rs index a79603acf..efccc8300 100644 --- a/crates/mega-evm/benches/corpus.rs +++ b/crates/mega-evm/benches/corpus.rs @@ -1,10 +1,11 @@ -//! A slice of the differential corpus through `MegaEvm`. +//! A set of JSON scenarios through `MegaEvm`. //! -//! The inputs are scenarios of `crates/mega-differential/scenarios`, the corpus the differential -//! harness compares against stock revm 43, so an instruction-count change here means the -//! execution or the pricing of those scenarios moved. Each scenario runs all its transactions, -//! one fresh `MegaEvm` per transaction as the harness does; building the pre-state is setup and -//! is not measured. +//! The inputs are the scenarios under `benches/scenarios` (the `test_utils::Scenario` format), +//! picked to spread over the mechanisms the engine runs. They are bench inputs, not a conformance +//! suite: nothing here compares their outcome with another engine, so an instruction-count change +//! means only that the execution or the pricing of those scenarios moved. Each scenario runs all +//! its transactions, one fresh `MegaEvm` per transaction; building the pre-state is setup and is +//! not measured. #![allow(missing_docs)] use std::path::Path; @@ -12,30 +13,29 @@ use std::path::Path; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::test_utils::Scenario; -/// `(bench id, scenario path under the corpus directory)`: a few scenarios of each origin, -/// spread over the mechanisms the corpus covers. +/// `(bench id, scenario name)`: the scenario is `benches/scenarios/.json`. const SLICE: &[(&str, &str)] = &[ - ("sstore_set", "handwritten/sstore_set_spills"), - ("create", "handwritten/create_success"), - ("nested_revert", "handwritten/nested_call_revert_with_spill"), - ("two_txs", "handwritten/two_txs_sequential"), - ("system_call", "handwritten/system_call"), - ("calldata_floor", "eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test"), + ("sstore_set", "sstore_set_spills"), + ("create", "create_success"), + ("nested_revert", "nested_call_revert_with_spill"), + ("two_txs", "two_txs_sequential"), + ("system_call", "system_call"), + ("calldata_floor", "test_calldata_floor_with_sstore_fork_Amsterdam_state_test"), ( "nested_refund_depth_10", - "eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", ), - ("eip7702_delegation", "harness/eip7702_delegate_new_authority"), - ("access_list", "harness/access_list_warm_slots_and_account"), - ("selfdestruct", "harness/selfdestruct_created_in_same_tx_to_existing_account"), - ("logs", "harness/logs_all_topic_counts"), - ("ecrecover", "harness/precompile_ecrecover"), - ("modexp", "harness/precompile_modexp"), + ("eip7702_delegation", "eip7702_delegate_new_authority"), + ("access_list", "access_list_warm_slots_and_account"), + ("selfdestruct", "selfdestruct_created_in_same_tx_to_existing_account"), + ("logs", "logs_all_topic_counts"), + ("ecrecover", "precompile_ecrecover"), + ("modexp", "precompile_modexp"), ]; fn load(path: &str) -> Scenario { let file = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../mega-differential/scenarios") + .join("benches/scenarios") .join(format!("{path}.json")); let text = std::fs::read_to_string(&file).unwrap_or_else(|err| panic!("{file:?}: {err}")); let scenario: Scenario = serde_json::from_str(&text).unwrap(); diff --git a/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json b/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json new file mode 100644 index 000000000..aacca0ab9 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json @@ -0,0 +1,43 @@ +{ + "name": "access_list_warm_slots_and_account", + "description": "The access list warms slot 0 and slot 2 of the reader and the account it reads the balance of; slot 1 stays cold.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0", + "0x2" + ] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/create_success.json b/crates/mega-evm/benches/scenarios/create_success.json new file mode 100644 index 000000000..e3f8cf5d0 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/create_success.json @@ -0,0 +1,28 @@ +{ + "name": "create_success", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json b/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json new file mode 100644 index 000000000..964eb05c3 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json @@ -0,0 +1,34 @@ +{ + "name": "eip7702_delegate_new_authority", + "description": "The authority does not exist: the authorization creates it with the delegation designator and nonce 1, and the call to it runs the delegate's code in its context.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json b/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json new file mode 100644 index 000000000..bb77d6ecd --- /dev/null +++ b/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json @@ -0,0 +1,23 @@ +{ + "name": "logs_all_topic_counts", + "description": "One LOG0 to LOG4 each, with data from memory.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000106": { + "code": "0x7f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2060005260206000a0600160206000a16002600160106000a260036002600160006000a3600460036002600160086018a400" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000106", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json b/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json new file mode 100644 index 000000000..f928b1289 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json @@ -0,0 +1,34 @@ +{ + "name": "nested_call_revert_with_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5ffd", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/precompile_ecrecover.json b/crates/mega-evm/benches/scenarios/precompile_ecrecover.json new file mode 100644 index 000000000..4f47989bf --- /dev/null +++ b/crates/mega-evm/benches/scenarios/precompile_ecrecover.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_ecrecover", + "description": "ecrecover on a valid signature, then on one with v = 29.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009901": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000015afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001c9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001d9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/precompile_modexp.json b/crates/mega-evm/benches/scenarios/precompile_modexp.json new file mode 100644 index 000000000..507d63dce --- /dev/null +++ b/crates/mega-evm/benches/scenarios/precompile_modexp.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_modexp", + "description": "modexp 3^5 mod 7 with one-byte operands, then with a 64-byte exponent (the Osaka pricing).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009905": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000055afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001030507", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000103ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json b/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json new file mode 100644 index 000000000..48f436af1 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json @@ -0,0 +1,27 @@ +{ + "name": "selfdestruct_created_in_same_tx_to_existing_account", + "description": "A contract created in the transaction self-destructs to an existing account from its init code: it is destroyed and the beneficiary gets its endowment.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000fac": { + "balance": "0x64", + "code": "0x3660006000373660006007f060005500" + }, + "0x0000000000000000000000000000000000000bee": { + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000fac", + "data": "0x730000000000000000000000000000000000000beeff", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/sstore_set_spills.json b/crates/mega-evm/benches/scenarios/sstore_set_spills.json new file mode 100644 index 000000000..5bd91f6b5 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/sstore_set_spills.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_set_spills", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/system_call.json b/crates/mega-evm/benches/scenarios/system_call.json new file mode 100644 index 000000000..4e82514d5 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/system_call.json @@ -0,0 +1,26 @@ +{ + "name": "system_call", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0xfffffffffffffffffffffffffffffffffffffffe", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "kind": "system_call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json b/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3a4b2393c --- /dev/null +++ b/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_with_sstore_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json b/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json new file mode 100644 index 000000000..7d4e6e671 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0551d99e64f665f96a535ea329b0b7730b256f84": { + "nonce": 1, + "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" + }, + "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { + "nonce": 1, + "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" + }, + "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { + "nonce": 1, + "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x440df445bc999c4a7ad434728514b18d49af1f76": { + "nonce": 1, + "code": "0x60006000600060006000737b9a4ebbbcaa3b5ed869adf6cb131a885347deb95af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x595ad51569abfc814f56e2025df8465bc7c96daa": { + "nonce": 1, + "code": "0x6000600060006000600073f840c69a775450661d3faa91f9dc8677eb0bf5425af15000" + }, + "0x768599d3d827a10afdd46c7ee74e043cb491b3bb": { + "nonce": 1, + "code": "0x6000600060006000600073440df445bc999c4a7ad434728514b18d49af1f765af15000" + }, + "0x7a3f53d68397cf003560f9713a2452974812fd5f": { + "nonce": 1, + "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" + }, + "0x7b9a4ebbbcaa3b5ed869adf6cb131a885347deb9": { + "nonce": 1, + "code": "0x6000600060006000600073595ad51569abfc814f56e2025df8465bc7c96daa5af15000" + }, + "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { + "nonce": 1, + "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" + }, + "0x84946fbc7842859adbd3644faa294e443c0232df": { + "nonce": 1, + "code": "0x60006000600060006000737a3f53d68397cf003560f9713a2452974812fd5f5af15000" + }, + "0xd6d787820fcc0f2b5b345d2b4026cc455431413b": { + "nonce": 1, + "code": "0x600060006000600060007384946fbc7842859adbd3644faa294e443c0232df5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf840c69a775450661d3faa91f9dc8677eb0bf542": { + "nonce": 1, + "code": "0x6000600060006000600073d6d787820fcc0f2b5b345d2b4026cc455431413b5af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x768599d3d827a10afdd46c7ee74e043cb491b3bb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/two_txs_sequential.json b/crates/mega-evm/benches/scenarios/two_txs_sequential.json new file mode 100644 index 000000000..9ab146327 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/two_txs_sequential.json @@ -0,0 +1,36 @@ +{ + "name": "two_txs_sequential", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} From 834c594596a089b2678cc67d110eb563fbc19d73 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:39:34 +0800 Subject: [PATCH 083/201] test: park the CREATE and CREATE2 tests again under the common execution layer --- crates/mega-evm/tests/_pending/README.md | 63 +- .../tests/_pending/rex4/create_safety.rs | 150 +++++ crates/mega-evm/tests/_pending/rex4/main.rs | 1 + .../_pending/rex5/create2_empty_initcode.rs | 168 ++++++ .../rex5/create2_resize_gas_metering.rs | 192 ++++++ crates/mega-evm/tests/_pending/rex5/main.rs | 2 + .../_pending/rex6/create2_metering_order.rs | 568 ++++++++++++++++++ .../tests/_pending/rex6/error_paths.rs | 50 +- crates/mega-evm/tests/_pending/rex6/main.rs | 1 + crates/mega-evm/tests/satin/static_callee.rs | 4 +- 10 files changed, 1164 insertions(+), 35 deletions(-) create mode 100644 crates/mega-evm/tests/_pending/rex4/create_safety.rs create mode 100644 crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs create mode 100644 crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs create mode 100644 crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index e4b56e283..da80c6b9a 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -26,6 +26,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| +| the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | | the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | @@ -42,7 +43,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **726** | **603** | **123** | **405** | **293** | **28** | +| **Total** | **747** | **624** | **123** | **426** | **293** | **28** | ## Tests ported in place @@ -79,37 +80,35 @@ What the retired `tests/mutation/` rows cited, for the mechanisms that own them. | the block executor | 17 | keep | the test gates regenerate | | the block executor | 5 | rewrite | single spec / Satin schedule | -## Tests ported into the differential harness +## Tests parked under the common execution layer -These 21 rows, owned by the test gates, pinned canonical CREATE and CREATE2 behavior; they are scenarios of `crates/mega-differential/scenarios/harness/` now, compared field by field against revm 43, so the counts above are lower than the inventory's by exactly these rows. -A scenario keeps the transaction of its test; the assertions on compute gas (not a Satin mechanism yet) and on the halt reason of a static callee (which the outer transaction does not expose) are not carried over. +These 21 rows belong to the test gates in the inventory and pin canonical CREATE and CREATE2 behavior. +The test gates had turned them into scenarios of a differential harness against revm 43; that harness is maintained outside this repository now, so the rows are parked here again, owed to the common execution layer, and counted under it above. +6 of them also assert the halt reason of a creation in a static callee: those assertions already run in `tests/satin/static_callee.rs`, under the same test names, and a port of one of those rows carries the rest of its assertions. -| Legacy file | Test | Scenarios | +| Legacy file | Test | Static-callee halt reason | |---|---|---| -| `rex4/create_safety.rs` | `test_create2_with_oversize_initcode_len_does_not_panic` | `create2_initcode_memory_oog` | -| `rex5/create2_empty_initcode.rs` | `test_create2_len_zero_offset_zero_succeeds_on_both_specs` | `create2_empty_initcode_offset_zero` | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_nonzero_offset_max_still_halts` | `create2_nonempty_initcode_offset_max` | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_large_offset_skips_memory_expansion` | `create2_empty_initcode_large_offset` | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_max_succeeds` | `create2_empty_initcode_offset_max` | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_zero_succeeds` | `create2_empty_initcode_offset_zero` | -| `rex5/create2_resize_gas_metering.rs` | `test_create2_missing_salt_halts_consistently_across_specs` | `create2_missing_salt` | -| `rex5/create2_resize_gas_metering.rs` | `test_rex5_create2_with_non_trivial_resize_succeeds` | `create2_initcode_32k` | -| `rex6/create2_metering_order.rs` | `test_create2_exact_boundary_initcode_length` | `create2_initcode_at_limit`, `create2_initcode_over_limit` | -| `rex6/create2_metering_order.rs` | `test_create2_missing_salt_consistent_rex5_rex6` | `create2_missing_salt` | -| `rex6/create2_metering_order.rs` | `test_create2_moderately_oversized_initcode_same_reason_both_specs` | `create2_initcode_600k` | -| `rex6/create2_metering_order.rs` | `test_create2_oversized_initcode_halts_before_prework_rex6` | `create2_initcode_10mib` | -| `rex6/create2_metering_order.rs` | `test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6` | `create2_oversized_initcode_unrepresentable_offset` | -| `rex6/create2_metering_order.rs` | `test_create2_static_hugely_oversized_initcode_halt_reason` | `create2_static_initcode_10mib` | -| `rex6/create2_metering_order.rs` | `test_create2_static_missing_operands_halt_reason` | `create2_static_missing_operands` | -| `rex6/create2_metering_order.rs` | `test_create2_static_oversized_initcode_reports_static_rejection` | `create2_static_initcode_600k` | -| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_initcode_reports_static_rejection` | `create2_static_empty_initcode` | -| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_low_gas_halt_reason` | `create2_static_empty_initcode_low_gas` | -| `rex6/create2_metering_order.rs` | `test_create_static_low_gas_halt_reason` | `create_static_low_gas` | -| `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | `create2_missing_length` | -| `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | `create2_missing_offset` | - -6 of these rows also asserted the halt reason of a static callee, which a scenario cannot compare: the harness compares what the transaction reports, and the inner frame's halt reason is not part of that. -The common execution layer re-added those assertions in `tests/satin/static_callee.rs`, where they read the halt reason off the callee's frame outcome as its caller receives it. +| `rex4/create_safety.rs` | `test_create2_with_oversize_initcode_len_does_not_panic` | — | +| `rex5/create2_empty_initcode.rs` | `test_create2_len_zero_offset_zero_succeeds_on_both_specs` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_nonzero_offset_max_still_halts` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_large_offset_skips_memory_expansion` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_max_succeeds` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_zero_succeeds` | — | +| `rex5/create2_resize_gas_metering.rs` | `test_create2_missing_salt_halts_consistently_across_specs` | — | +| `rex5/create2_resize_gas_metering.rs` | `test_rex5_create2_with_non_trivial_resize_succeeds` | — | +| `rex6/create2_metering_order.rs` | `test_create2_exact_boundary_initcode_length` | — | +| `rex6/create2_metering_order.rs` | `test_create2_missing_salt_consistent_rex5_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_moderately_oversized_initcode_same_reason_both_specs` | — | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_initcode_halts_before_prework_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_static_hugely_oversized_initcode_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_missing_operands_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_oversized_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_low_gas_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create_static_low_gas_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | — | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | — | ## Tests ported by the common execution layer @@ -173,6 +172,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | | `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | | `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | | `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | | `rex4/eip7702_delegation_cycle.rs` | 8 | keep 8 (SALT pricing · account inspection on the pricing path) | | `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | @@ -183,6 +183,8 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | | `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | +| `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | +| `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | | `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | @@ -204,9 +206,10 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | | `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | | `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | +| `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/create_frame_accounting.rs` | 1 | keep 1 (SALT pricing) | | `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | -| `rex6/error_paths.rs` | 2 | keep 2 (SALT pricing) | +| `rex6/error_paths.rs` | 4 | keep 2 (SALT pricing); keep 2 (the common execution layer · canonical) | | `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | | `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | | `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | diff --git a/crates/mega-evm/tests/_pending/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs new file mode 100644 index 000000000..363729117 --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex4/create_safety.rs @@ -0,0 +1,150 @@ +#![allow(clippy::doc_markdown)] +//! Regression tests for CREATE2 wrapper safety and compute-gas accounting. +//! +//! 1. CREATE2 with an out-of-bounds initcode slice must never trigger an interpreter panic. The +//! wrapper expands memory before reading the initcode slice; if memory expansion OOGs, the +//! canonical reject path runs without ever calling `slice_len` on unallocated memory. +//! 2. The expansion gas consumed by the wrapper's `resize_memory!` must be recorded into the +//! compute gas tracker. Otherwise the per-tx compute gas limit is undercounted by the initcode +//! memory-expansion cost, since the canonical CREATE2 path's own `resize_memory!` becomes a +//! no-op once memory is already sized. + +use std::convert::Infallible; + +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + TestExternalEnvs, +}; +use revm::{ + bytecode::opcode::*, + context::{result::ExecutionResult, TxEnv}, + handler::EvmTr, + state::{AccountInfo, Bytecode}, +}; + +const CALLER: Address = address!("1111111111111111111111111111111111111111"); +const CONTRACT_WITH_BAD_CREATE2: Address = address!("2222222222222222222222222222222222222222"); + +/// Runtime that performs CREATE2 with a length large enough to OOG the +/// canonical `resize_memory!` under a tight per-call gas budget, but +/// still under `MAX_INITCODE_SIZE` so the size check passes first. +/// +/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. +fn memory_oog_create2_runtime() -> Bytes { + BytecodeBuilder::default() + .push_number(0u8) // salt + .push_number(500_000u32) // length — large enough to OOG memory expansion + .push_number(0u8) // offset + .push_number(0u8) // value + .append(CREATE2) + .append(STOP) + .build() +} + +#[test] +fn test_create2_with_oversize_initcode_len_does_not_panic() { + let mut db = MemoryDatabase::default(); + db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); + let runtime = memory_oog_create2_runtime(); + let bytecode = Bytecode::new_raw(runtime); + db.insert_account_info( + CONTRACT_WITH_BAD_CREATE2, + AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, + ); + + let envs = TestExternalEnvs::::new(); + let limits = EvmTxRuntimeLimits::no_limits(); + let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) + .with_external_envs(envs.into()) + .with_tx_runtime_limits(limits); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + let tx_env = TxEnv { + caller: CALLER, + kind: TxKind::Call(CONTRACT_WITH_BAD_CREATE2), + gas_limit: 200_000, + gas_price: 0, + ..Default::default() + }; + let mut tx = MegaTransaction::new(tx_env); + tx.enveloped_tx = Some(Bytes::new()); + let res = + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError"); + + assert!( + matches!( + res.result, + ExecutionResult::Success { .. } | + ExecutionResult::Halt { .. } | + ExecutionResult::Revert { .. } + ), + "got: {:?}", + res.result + ); +} + +const COMPUTE_GAS_TEST_CONTRACT: Address = address!("3333333333333333333333333333333333333333"); + +/// Build runtime bytecode that issues a single CREATE2 over a memory window of +/// `initcode_len` bytes starting at offset 0, then STOPs. The initcode memory is left +/// zero-initialized; CREATE2 will deploy an empty contract, which is fine for measuring +/// gas accounting (we only care that the wrapper ran and metered the memory expansion). +/// +/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. +fn create2_bytecode(initcode_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) // salt + .push_number(initcode_len) // length + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build() +} + +/// EVM memory expansion gas: `3*words + words*words/512`. +fn memory_expansion_gas(len: u64) -> u64 { + let words = len.div_ceil(32); + 3 * words + words * words / 512 +} + +/// Run a single CREATE2 transaction at the REX4 spec and return the recorded compute gas. +fn run_create2_and_get_compute_gas( + initcode_len: u64, + gas_limit: u64, +) -> (ExecutionResult, u64) { + let mut db = MemoryDatabase::default(); + db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); + let bytecode = Bytecode::new_raw(create2_bytecode(initcode_len)); + db.insert_account_info( + COMPUTE_GAS_TEST_CONTRACT, + AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, + ); + + let envs = TestExternalEnvs::::new(); + let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) + .with_external_envs(envs.into()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + let tx_env = TxEnv { + caller: CALLER, + kind: TxKind::Call(COMPUTE_GAS_TEST_CONTRACT), + gas_limit, + gas_price: 0, + ..Default::default() + }; + let mut tx = MegaTransaction::new(tx_env); + tx.enveloped_tx = Some(Bytes::new()); + let res = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not fail"); + let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; + (res.result, compute_gas) +} diff --git a/crates/mega-evm/tests/_pending/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs index 5263b6fe0..b75668583 100644 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -2,6 +2,7 @@ mod access_control; mod beneficiary_detention; +mod create_safety; mod deployment; mod eip7702_delegation_cycle; mod frame_limits; diff --git a/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs new file mode 100644 index 000000000..01457e980 --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs @@ -0,0 +1,168 @@ +//! Regression suite for the REX5+ CREATE2 wrapper `len == 0` short-circuit. +//! +//! Canonical revm CREATE2 ignores the `offset` operand when `initcode_len == 0`: +//! no offset conversion, no memory expansion, no slice, no keccak. The initcode +//! hash is `KECCAK_EMPTY` and the deploy address is derived from +//! `creator.create2(salt, KECCAK_EMPTY)`. +//! +//! The Mega CREATE2 wrapper used to observe `offset` unconditionally, which +//! diverged from canonical revm in two ways: +//! +//! - A valid `CREATE2(value=0, offset=U256::MAX, len=0, salt=0)` halted inside +//! `as_usize_or_fail!(offset)` instead of succeeding with empty initcode. +//! - A `CREATE2(_, offset=large_finite, len=0, _)` over-charged memory-expansion EVM gas and (under +//! REX5+) recorded `resize_gas` into the `compute_gas` tracker even though canonical revm did +//! neither. +//! +//! REX5+ short-circuits `len == 0` before offset conversion / `resize_memory!` +//! / slice / `keccak256`, using the pre-computed `KECCAK_EMPTY`. Pre-REX5 keeps +//! the "observe offset, resize, slice, hash" sequence verbatim for replay +//! parity. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CREATE2, STOP}, + context::{result::ExecutionResult, tx::TxEnvBuilder}, + handler::EvmTr, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); + +/// Runs a tx that invokes a CREATE2 contract built from raw bytecode and returns +/// the execution result plus the post-tx `compute_gas` tracker reading. +fn transact_create2_with_code( + spec: MegaSpecId, + code: Bytes, +) -> (ExecutionResult, u64) { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) + .account_code(CONTRACT, code); + let mut context = + MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let tx = + TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let mut evm = MegaEvm::new(context); + let result = + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); + let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; + (result.result, compute) +} + +/// Builds bytecode that runs `CREATE2(value=0, offset, size=0, salt=0)`. +/// `offset` is pushed as a full 32-byte value so callers can exercise non-canonical +/// values such as `U256::MAX` or `1 << 30` that the short-circuit must tolerate. +fn build_create2_empty_initcode_at_offset(offset: U256) -> Bytes { + BytecodeBuilder::default() + .push_number(0_u64) // salt (depth 3) + .push_number(0_u64) // size = 0 (depth 2) + .push_u256(offset) // offset (depth 1) + .push_number(0_u64) // value (depth 0) + .append(CREATE2) + .append(STOP) + .build() +} + +/// REX5: `CREATE2(len=0, offset=U256::MAX)` MUST succeed. +/// +/// Pins that the wrapper short-circuits before offset conversion when +/// `len == 0` — without the short-circuit, `as_usize_or_fail!(U256::MAX)` +/// would halt with `InvalidOperandOOG`. Post-short-circuit the initcode hash +/// is `KECCAK_EMPTY` and the inner CREATE2 deploys empty code at the +/// deterministic address `creator.create2(0, KECCAK_EMPTY)`. +#[test] +fn test_rex5_create2_len_zero_offset_max_succeeds() { + let code = build_create2_empty_initcode_at_offset(U256::MAX); + let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); + assert!( + result.is_success(), + "REX5 CREATE2(len=0, offset=U256::MAX) must succeed; got {result:?}", + ); +} + +/// REX5: the `len == 0` short-circuit MUST NOT engage when `len > 0`. +/// `CREATE2(len=1, offset=U256::MAX, ...)` must halt inside +/// `as_usize_or_fail!(offset)`, not silently succeed with `KECCAK_EMPTY` as +/// the initcode hash. Pins the `initcode_len.is_zero()` guard against a +/// regression that broadens it (e.g. an accidental `<=` comparison). +#[test] +fn test_rex5_create2_len_nonzero_offset_max_still_halts() { + let code = BytecodeBuilder::default() + .push_number(0_u64) // salt (depth 3) + .push_number(1_u64) // size = 1 (NON-zero) + .push_u256(U256::MAX) // offset (depth 1) + .push_number(0_u64) // value (depth 0) + .append(CREATE2) + .append(STOP) + .build(); + let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); + assert!( + matches!(result, ExecutionResult::Halt { .. }), + "REX5 CREATE2(len=1, offset=U256::MAX) must halt — the len==0 short-circuit \ + must not engage for nonzero len; got {result:?}", + ); +} + +/// REX5: `CREATE2(len=0, offset=large_finite)` MUST succeed without paying for +/// memory expansion. Without the short-circuit, `resize_memory!(1<<30, 0)` +/// quadratically prices the implied range — pricing canonical revm explicitly +/// skips when `len == 0`. With the short-circuit the `compute_gas` reading +/// sits near the TX intrinsic baseline rather than balloon to MB-scale. +#[test] +fn test_rex5_create2_len_zero_large_offset_skips_memory_expansion() { + let offset = U256::from(1u64 << 30); + let code = build_create2_empty_initcode_at_offset(offset); + let (result, compute) = transact_create2_with_code(MegaSpecId::REX5, code); + assert!( + result.is_success(), + "REX5 CREATE2(len=0, offset={offset}) must succeed; got {result:?}", + ); + // The wrapper short-circuit means no `resize_gas` is recorded under REX5, + // so the compute_gas tracker only holds the TX intrinsic (~21k base + a + // handful of bytes of calldata) plus the CREATE2 frame setup (~32k storage + // gas drained from stipend on REX5 — does NOT count against compute_gas). + // A regression that observes the offset would push compute_gas into the + // millions on a `1 << 30` byte range. + assert!( + compute < 100_000, + "REX5 CREATE2(len=0) should not record memory-expansion compute_gas; got {compute}", + ); +} + +/// REX5: `CREATE2(len=0, offset=0)` happy path — the short-circuit must not +/// break the canonical "small offset, empty initcode" success case. +#[test] +fn test_rex5_create2_len_zero_offset_zero_succeeds() { + let code = build_create2_empty_initcode_at_offset(U256::ZERO); + let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); + assert!(result.is_success(), "REX5 CREATE2(len=0, offset=0) must succeed; got {result:?}",); +} + +/// REX5 vs REX4 deployed-address parity for `len=0, offset=0`. Both must derive +/// the same address `creator.create2(0, KECCAK_EMPTY)` — REX5 via the +/// short-circuit, REX4 via `keccak256(slice_len(0, 0))` which equals +/// `KECCAK_EMPTY`. Equality of `is_success` is a weaker form of address parity; +/// pinning the spec on it would require reading the deployed address out of the +/// execution result, which requires more plumbing. The success-only check is +/// sufficient for the wrapper-level invariant — if the REX5 short-circuit +/// produced a wrong hash, the inner CREATE2 would deploy to a different +/// address but `STOP` would still succeed at that other address. Direct +/// address-equality assertion is left as a follow-up. +#[test] +fn test_create2_len_zero_offset_zero_succeeds_on_both_specs() { + let code = build_create2_empty_initcode_at_offset(U256::ZERO); + let (result_rex5, _) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); + let (result_rex4, _) = transact_create2_with_code(MegaSpecId::REX4, code); + assert!(result_rex5.is_success(), "REX5 must succeed; got {result_rex5:?}"); + assert!(result_rex4.is_success(), "REX4 must succeed; got {result_rex4:?}"); +} diff --git a/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs new file mode 100644 index 000000000..ed1c754ee --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs @@ -0,0 +1,192 @@ +//! Regression suite for the REX5+ CREATE2 wrapper `resize_gas` recording rule. +//! +//! REX5+ validates the salt operand before `resize_memory!` / copy / keccak, +//! and records the memory-expansion gas (`resize_gas`) into the `compute_gas` +//! tracker immediately after `resize_memory!`. Pre-REX5 keeps the original +//! "resize first, salt last, record after inner CREATE2 returns" order +//! verbatim for replay parity. +//! +//! Coverage: +//! - Happy-path CREATE2 with measurable memory expansion succeeds under both specs. +//! - Cross-spec parity: the post-tx `compute_gas` tracker agrees within a small tolerance, pinning +//! that REX5 records `resize_gas` exactly once (no double-count from the trailing late-record +//! block, no miss-count from the early-record path being skipped). +//! - Stack-underflow consistency: a CREATE2 dispatched with only three operands halts with +//! `StackUnderflow` under both specs and leaks no `resize_gas` into the tracker. +//! +//! Failure-path verification (storage-gas OOG / inner CREATE2 halt under REX5 +//! retaining `resize_gas`, pre-REX5 skipping via the trailing block) is +//! delicate to engineer with stable gas tuning and is left to a follow-up. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CREATE2, STOP}, + context::{result::ExecutionResult, tx::TxEnvBuilder}, + handler::EvmTr, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); + +/// Builds bytecode that runs `CREATE2(value=0, offset=0, size=initcode_len, salt=0)`. +/// The initcode region is zero-initialized; the canonical CREATE2 keccak256-hashes +/// the bytes and runs the resulting `STOP`-only constructor, deploying empty code. +/// Memory expansion gas inside the wrapper is a function of `initcode_len`. +fn build_create2_contract(initcode_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(0_u64) // salt + .push_number(initcode_len) // size + .push_number(0_u64) // offset + .push_number(0_u64) // value + .append(CREATE2) + .append(STOP) + .build() +} + +/// Runs a tx that invokes the CREATE2 contract and returns the execution result and +/// the post-tx `compute_gas` tracker reading. +fn transact_create2(spec: MegaSpecId, initcode_len: u64) -> (ExecutionResult, u64) { + let code = build_create2_contract(initcode_len); + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) + .account_code(CONTRACT, code); + let mut context = + MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let tx = + TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let mut evm = MegaEvm::new(context); + let result = + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); + let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; + (result.result, compute) +} + +/// 32 KiB initcode: memory expansion gas inside the wrapper is in the ~5 K range, +/// large enough that a double-count or miss-count of `resize_gas` would be +/// visible against the cross-spec parity tolerance. +const INITCODE_LEN: u64 = 32 * 1024; + +/// REX5 happy path: CREATE2 with non-trivial memory expansion succeeds. The +/// `compute_gas` tracker registers usage that includes the `resize_gas` recorded +/// in the early-record path. +#[test] +fn test_rex5_create2_with_non_trivial_resize_succeeds() { + let (result, compute) = transact_create2(MegaSpecId::REX5, INITCODE_LEN); + assert!(result.is_success(), "REX5 CREATE2 happy path must succeed; got {result:?}"); + assert!( + compute > 0, + "REX5 compute_gas tracker must register usage including resize_gas; got {compute}", + ); +} + +/// Runs a CREATE2 contract built from raw bytecode (used to construct stack-underflow +/// scenarios that `build_create2_contract` cannot express). Mirrors `transact_create2`. +fn transact_create2_with_code( + spec: MegaSpecId, + code: Bytes, +) -> (ExecutionResult, u64) { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) + .account_code(CONTRACT, code); + let mut context = + MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let tx = + TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let mut evm = MegaEvm::new(context); + let result = + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); + let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; + (result.result, compute) +} + +/// CREATE2 dispatched with only three stack operands (value, offset, length; salt +/// absent) must halt with `StackUnderflow` under both specs, and neither spec may +/// leak `resize_gas` into the `compute_gas` tracker on the halt path: +/// +/// - REX5: the wrapper inspects salt at position 3 BEFORE `resize_memory!`, so the early-record +/// block is unreachable when salt is missing. +/// - REX4: the wrapper inspects salt AFTER `resize_memory!`, but the trailing `if resize_gas > 0 { +/// ... }` block is skipped on the `StackUnderflow` halt. +/// +/// Equality of the post-tx `compute_gas` reading across REX4 and REX5 pins this +/// invariant — a regression that records `resize_gas` on either halt path would +/// produce a spec-asymmetric reading. +#[test] +fn test_create2_missing_salt_halts_consistently_across_specs() { + // Three CREATE2 args, salt OMITTED. Stack order from top (depth 0) at the + // CREATE2 instruction: + // depth 0: value + // depth 1: offset + // depth 2: length + // depth 3: → wrapper's `stack.inspect::<3>()` fails → StackUnderflow. + let code = BytecodeBuilder::default() + .push_number(INITCODE_LEN) // length (depth 2) + .push_number(0_u64) // offset (depth 1) + .push_number(0_u64) // value (depth 0) + .append(CREATE2) + .append(STOP) + .build(); + + let (result_rex5, compute_rex5) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); + let (result_rex4, compute_rex4) = transact_create2_with_code(MegaSpecId::REX4, code); + + // Both specs must halt with StackUnderflow. (Compare via Debug to avoid pinning the + // exact OpHaltReason → EthHaltReason wrapper path.) + let is_stack_underflow = |r: &ExecutionResult| -> bool { + matches!(r, ExecutionResult::Halt { reason, .. } if format!("{reason:?}").contains("StackUnderflow")) + }; + assert!( + is_stack_underflow(&result_rex5), + "REX5 must halt with StackUnderflow; got {result_rex5:?}", + ); + assert!( + is_stack_underflow(&result_rex4), + "REX4 must halt with StackUnderflow; got {result_rex4:?}", + ); + + // Neither spec leaks `resize_gas` into the compute_gas tracker on the + // stack-underflow path. The expected baseline for both specs is the TX + // intrinsic recorded by `validate()` (`record_compute_gas(initial_gas)`) and + // nothing more: + // + // - REX5: salt inspect at position 3 halts BEFORE `resize_memory!`, so the early-record block + // (`if is_rex5_enabled && resize_gas > 0 { ... }`) is never reached. + // - REX4: `resize_memory!` runs and burns EVM gas, but the late-record block at the wrapper's + // tail is skipped when the frame halts on the position-3 salt inspect. + // + // Equality between the two specs pins this consistency: any regression that + // records `resize_gas` on a halted CREATE2 (whether by moving the REX5 early + // record ahead of the salt check, or by running the REX4 late-record despite + // the halt) would produce a spec-asymmetric compute_gas reading exceeding the + // shared intrinsic baseline. + assert_eq!( + compute_rex5, compute_rex4, + "compute_gas must be identical across REX4 ({compute_rex4}) and REX5 ({compute_rex5}) \ + when CREATE2 halts on salt underflow — any divergence indicates resize_gas leaked into \ + the tracker on the halt path", + ); + // Sanity check that what's recorded is just the TX intrinsic (≈21k base + ~9 calldata + // bytes for the CREATE2 contract code). A multi-KiB reading would indicate that the + // wrapper recorded `resize_gas` despite the halt. + assert!( + compute_rex5 < 25_000, + "compute_gas reading should be near the TX intrinsic (~21k) on the halt path, \ + not include the {INITCODE_LEN}-byte resize_gas; got {compute_rex5}", + ); +} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index a55b33de7..abf4efcd9 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -2,6 +2,8 @@ mod apply_pending_changes_gas_budget; mod callcode_storage_gas; +mod create2_empty_initcode; +mod create2_resize_gas_metering; mod db_error; mod deposit_caller_accounting; mod deposit_create_storage_gas; diff --git a/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs new file mode 100644 index 000000000..f411f4d41 --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs @@ -0,0 +1,568 @@ +//! REX6 CREATE2 gas-metering order. +//! +//! REX6 folds the CREATE2 memory-expansion (`resize_memory!`) gas into the single compute-gas +//! recording taken after the inner opcode completes, instead of the pre-REX6 split recording (REX5 +//! recorded it eagerly before the storage charge; pre-REX5 recorded it after the inner op). +//! +//! Coverage: +//! - **Happy path**: REX6 records the same total compute gas as REX5 (and identical `gas_used`), +//! proving the single recording equals the REX5 eager-resize + inner sum with no double/miss +//! count. +//! - **Missing salt**: a CREATE2 with the salt operand absent halts with `StackUnderflow` under +//! both specs without leaking any `resize_gas` into the compute tracker. +//! - **Failure-path divergence**: under a compute-gas limit tight enough that the memory-expansion +//! gas crosses it, REX5 halts at the eager resize record (before the inner opcode runs) while +//! REX6 defers recording until after the inner opcode has executed — so REX6 records strictly +//! more compute gas. This is the intended, spec-defined behavior change of the canonical order. + +use std::{cell::RefCell, convert::Infallible, rc::Rc}; + +use crate::common::{transact, transact_default, CALLER, CONTRACT, EMPTY_TARGET}; +use alloy_primitives::{Bytes, U256}; +use mega_evm::{ + constants::mini_rex::MAX_INITCODE_SIZE, + test_utils::{BytecodeBuilder, MemoryDatabase}, + BucketHasher, BucketId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + TestExternalEnvs, +}; +use revm::{ + bytecode::opcode::{CREATE, CREATE2, STATICCALL, STOP}, + context::{tx::TxEnvBuilder, ContextTr}, + inspector::Inspector, + interpreter::{ + interpreter_types::InterpreterTypes, CallInputs, CallOutcome, InstructionResult, + }, +}; + +/// Records the `InstructionResult` an inner call to [`EMPTY_TARGET`] halted with. Used to observe +/// the halt reason of a `CREATE2` executed inside a `STATICCALL` frame, which is otherwise not +/// visible in the outer transaction result. +#[derive(Clone, Default)] +struct InnerHaltCapture(Rc>>); + +impl Inspector for InnerHaltCapture { + fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address == EMPTY_TARGET { + *self.0.borrow_mut() = Some(outcome.result.result); + } + } +} + +/// Routes every SALT lookup to [`STATIC_TEST_BUCKET_ID`] so a raised capacity scales the +/// contract-creation storage charge inside the static callee. +#[derive(Debug, Clone, Copy)] +struct SingleBucketHasher; + +impl BucketHasher for SingleBucketHasher { + fn bucket_id(_key: &[u8]) -> BucketId { + STATIC_TEST_BUCKET_ID + } +} + +/// Bucket every SALT lookup is routed to under [`SingleBucketHasher`]. +const STATIC_TEST_BUCKET_ID: BucketId = 7; + +/// 2 × `MIN_BUCKET_SIZE` (256) → a 2× multiplier, so the REX-family contract-creation charge +/// `CONTRACT_CREATION_STORAGE_GAS_BASE × (multiplier − 1)` is 32,000 gas instead of the 0 a +/// minimum-capacity bucket yields. +const DOUBLED_BUCKET_CAPACITY: u64 = 512; + +/// Runs a tx to a contract that `STATICCALL`s [`EMPTY_TARGET`] (whose code is `inner_bytecode`) +/// with `forward_gas`, and returns the halt reason the static callee produced. A +/// `bucket_capacity` of `Some(DOUBLED_BUCKET_CAPACITY)` makes the contract-creation storage +/// charge nonzero (32,000 gas); `None` leaves every bucket at minimum capacity (charge = 0). +fn static_halt_reason_for_bytecode( + spec: MegaSpecId, + inner_bytecode: Bytes, + forward_gas: u64, + bucket_capacity: Option, +) -> Option { + let outer_staticcall = BytecodeBuilder::default() + .push_number(0u64) // retSize + .push_number(0u64) // retOffset + .push_number(0u64) // argsSize + .push_number(0u64) // argsOffset + .push_address(EMPTY_TARGET) // to + .push_number(forward_gas) // gas + .append(STATICCALL) + .append(STOP) + .build(); + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10 * ONE_ETH)) + .account_code(CONTRACT, outer_staticcall) + .account_code(EMPTY_TARGET, inner_bytecode); + + let mut external_envs = TestExternalEnvs::::new(); + if let Some(capacity) = bucket_capacity { + external_envs = external_envs.with_bucket_capacity(STATIC_TEST_BUCKET_ID, capacity); + } + + let capture = InnerHaltCapture::default(); + let mut context = MegaContext::new(&mut db, spec).with_external_envs(external_envs.into()); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let tx = + TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let mut evm = MegaEvm::new(context).with_inspector(capture.clone()); + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); + let reason = *capture.0.borrow(); + reason +} + +/// `CREATE2(value=0, offset=0, size=initcode_len, salt=0)` then `STOP`, as the static callee. +fn static_create2_bytecode(initcode_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) // salt + .push_number(initcode_len) // size + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build() +} + +/// Runs a static `CREATE2` with the given initcode length, ample forwarded gas, and +/// minimum-capacity buckets, returning its halt reason. +fn static_create2_halt_reason(spec: MegaSpecId, initcode_len: u64) -> Option { + static_halt_reason_for_bytecode(spec, static_create2_bytecode(initcode_len), 50_000_000, None) +} + +const ONE_ETH: u128 = 1_000_000_000_000_000_000; + +/// 32 KiB initcode: the wrapper-side memory expansion gas is in the multi-KiB range, large enough +/// that a double-count or miss-count of the resize gas is visible, yet under the configured +/// initcode size limit (548,864 bytes — see `constants::mini_rex::MAX_INITCODE_SIZE`, well above +/// the vanilla EIP-3860 default) so the inner CREATE2 sets up a child frame rather than erroring. +const INITCODE_LEN: u64 = 32 * 1024; + +/// `CREATE2(value=0, offset=0, size=INITCODE_LEN, salt=0)` then `STOP`. The zero-initialized +/// initcode region keccak-hashes to a `STOP`-only constructor that deploys empty code. +fn build_create2_contract() -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) // salt + .push_number(INITCODE_LEN) // size + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build() +} + +/// The same four operand pushes as [`build_create2_contract`] followed by `STOP` (no CREATE2). +/// Running this measures the compute-gas usage accumulated *before* the CREATE2 opcode, used to +/// place a compute-gas limit precisely inside the CREATE2 memory-expansion window. +fn build_pushes_only_contract() -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(INITCODE_LEN) + .push_number(0u64) + .push_number(0u64) + .stop() + .build() +} + +fn db_with(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10 * ONE_ETH)) + .account_code(CONTRACT, code) +} + +#[test] +fn test_create2_missing_salt_consistent_rex5_rex6() { + // Three CREATE2 operands, salt OMITTED: the wrapper's `stack.inspect::<3>()` fails, halting + // with `StackUnderflow` before any memory expansion under both specs. + let code = BytecodeBuilder::default() + .push_number(INITCODE_LEN) // length (depth 2) + .push_number(0u64) // offset (depth 1) + .push_number(0u64) // value (depth 0) + .append(CREATE2) + .append(STOP) + .build(); + + let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); + let r6 = transact_default(MegaSpecId::REX6, db_with(code)); + + let is_stack_underflow = |o: &crate::common::Outcome| { + matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("StackUnderflow")) + }; + assert!(is_stack_underflow(&r5), "REX5 must halt with StackUnderflow; got {:?}", r5.result); + assert!(is_stack_underflow(&r6), "REX6 must halt with StackUnderflow; got {:?}", r6.result); + + // Neither spec records any resize gas on the salt-underflow halt path: both readings equal the + // shared TX intrinsic baseline. + assert_eq!( + r5.compute_gas, r6.compute_gas, + "compute_gas must be identical on the salt-underflow halt path; REX5={} REX6={}", + r5.compute_gas, r6.compute_gas + ); +} + +/// An oversized CREATE2 initcode must halt with `CreateInitCodeSizeLimit` under REX6 +/// BEFORE any memory-expansion/copy/keccak256 prework runs, not after. +/// +/// A 10 MiB initcode is chosen so the memory-expansion gas would be enormous (quadratic word +/// cost, ~210M gas — far past the 100M tx gas limit) if `resize_memory!` ran. Without the fix, +/// `resize_memory!` itself would exhaust the gas limit first and halt with `MemoryOOG` — the +/// canonical EIP-3860 check inside the inner opcode is never reached. With the fix, the halt +/// fires immediately with `CreateInitCodeSizeLimit`, before `resize_memory!` is ever called. +/// `gas_used` is NOT a useful signal here: any non-revert exceptional halt (both `MemoryOOG` and +/// `CreateInitCodeSizeLimit`) consumes the full remaining gas regardless of when it fires — this +/// matches the finding's own claim that committed gas/state is identical under REX6 either way; +/// only the halt-reason label (and the avoided node CPU work) differ. +#[test] +fn test_create2_oversized_initcode_halts_before_prework_rex6() { + const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, far past the 548,864-byte cap + + let code = BytecodeBuilder::default() + .push_number(0u64) // salt + .push_number(HUGE_INITCODE_LEN) // size + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build(); + + let r6 = transact_default(MegaSpecId::REX6, db_with(code)); + + assert!( + matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), + "REX6 must halt with CreateInitCodeSizeLimit (not MemoryOOG) for a 10 MiB initcode — \ + the halt must fire before resize_memory! ever runs, got {:?}", + r6.result, + ); +} + +/// Halt-reason parity for a "moderately" oversized initcode (bigger than the 548,864-byte cap, +/// but small enough that `resize_memory!`'s own gas cost stays well within the 100M tx gas +/// limit). Both specs reach `CreateInitCodeSizeLimit` — REX5 via the slower prework-then-inner- +/// check path (frozen, unpatched), REX6 via the immediate early check. +/// +/// `gas_used` is deliberately NOT compared here: both specs consume the tx's full gas limit +/// regardless (any non-revert exceptional halt does), so equality there is a trivial artifact of +/// halt semantics, not a meaningful check. What genuinely differs — and is asserted below — is +/// the internal `compute_gas` tracker: REX5 still eagerly records the ~742,895-gas memory +/// expansion for this length before it ever reaches the inner opcode's check, while REX6's early +/// halt never reaches that recording at all. This divergence is pre-existing REX6 metering-order +/// behavior (`create_rex6`'s single post-body recording), not something this fix changes — it is +/// asserted here only to document that "same halt reason" does not imply "identical internal +/// accounting," and so a future change collapsing this gap doesn't silently look like a +/// regression. +#[test] +fn test_create2_moderately_oversized_initcode_same_reason_both_specs() { + const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost is negligible + + let code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(MODERATELY_OVERSIZED_LEN) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .append(STOP) + .build(); + + let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); + let r6 = transact_default(MegaSpecId::REX6, db_with(code)); + + let is_create_initcode_size_limit = |o: &crate::common::Outcome| { + matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("CreateInitCodeSizeLimit")) + }; + assert!( + is_create_initcode_size_limit(&r5), + "REX5 must reach CreateInitCodeSizeLimit via the slower prework-then-inner-check path: {:?}", + r5.result, + ); + assert!( + is_create_initcode_size_limit(&r6), + "REX6 must reach CreateInitCodeSizeLimit via the immediate early check: {:?}", + r6.result, + ); + assert!( + r5.compute_gas > r6.compute_gas + 500_000, + "REX5 must still eagerly record the memory-expansion compute gas that REX6's early halt \ + skips; REX5={} REX6={}", + r5.compute_gas, + r6.compute_gas, + ); +} + +/// Exact-boundary test: `initcode_len == max_initcode_size()` must NOT halt (the +/// comparator is strict `>`, matching revm's own canonical check), and +/// `max_initcode_size() + 1` MUST halt with `CreateInitCodeSizeLimit`. Pins the comparator +/// itself — a future `>` → `>=` regression would make the boundary length halt on REX6 while +/// still succeeding pre-REX6, a real spec divergence that the "moderately oversized" test above +/// (600,000 bytes, well clear of the boundary) cannot catch. +#[test] +fn test_create2_exact_boundary_initcode_length() { + let at_limit = BytecodeBuilder::default() + .push_number(0u64) + .push_number(MAX_INITCODE_SIZE as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .append(STOP) + .build(); + let r6_at_limit = transact_default(MegaSpecId::REX6, db_with(at_limit)); + assert!( + r6_at_limit.is_success(), + "an initcode exactly at max_initcode_size must succeed (strict `>`, not `>=`): {:?}", + r6_at_limit.result, + ); + + let over_limit = BytecodeBuilder::default() + .push_number(0u64) + .push_number(MAX_INITCODE_SIZE as u64 + 1) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .append(STOP) + .build(); + let r6_over_limit = transact_default(MegaSpecId::REX6, db_with(over_limit)); + assert!( + matches!(&r6_over_limit.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), + "one byte over max_initcode_size must halt with CreateInitCodeSizeLimit: {:?}", + r6_over_limit.result, + ); +} + +/// Operand-order test: an oversized `initcode_len` combined with an `initcode_offset` +/// that does not fit in a `usize` must still halt with `CreateInitCodeSizeLimit` on REX6 — the +/// size check runs before the offset is ever converted. +/// +/// The wrapper converts `initcode_len` first, then runs the REX6 size check, then converts +/// `initcode_offset`. If the conversion order were the reverse (offset first, as it was before +/// this fix), the unrepresentable offset would halt with `InvalidOperandOOG` +/// (`OutOfGas(InvalidOperand)`) and mask the intended EIP-3860 halt. Pre-REX6 has no early size +/// check, so it correctly halts on the offset overflow — the same `InvalidOperandOOG` reason both +/// operands share, which is why reordering their conversion is inert on sealed specs. +#[test] +fn test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6() { + // `len` is oversized but representable as `usize`; `offset` is > `usize::MAX`. + let code = BytecodeBuilder::default() + .push_number(0u64) // salt + .push_number(MAX_INITCODE_SIZE as u64 + 1) // size: oversized, but fits usize + .push_u256(U256::from(u128::MAX)) // offset: > usize::MAX (unrepresentable) + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build(); + + let r6 = transact_default(MegaSpecId::REX6, db_with(code.clone())); + assert!( + matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), + "REX6 must halt with CreateInitCodeSizeLimit even when the offset is unrepresentable — \ + the size check must run before the offset is converted; got {:?}", + r6.result, + ); + + // Pre-REX6 (sealed) has no early size check, so the unrepresentable offset is what halts, with + // OutOfGas(InvalidOperand). It must NOT surface CreateInitCodeSizeLimit — this pins that the + // reorder did not change sealed-spec behavior. + let r5 = transact_default(MegaSpecId::REX5, db_with(code)); + assert!( + matches!(&r5.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("InvalidOperand")), + "REX5 (sealed) must halt on the offset overflow (OutOfGas(InvalidOperand)), not the REX6 \ + size check; got {:?}", + r5.result, + ); +} + +/// Static-call precedence: a `CREATE2` inside a `STATICCALL` with oversized initcode must report +/// the static-context rejection (`StateChangeDuringStaticCall`), NOT `CreateInitCodeSizeLimit`. +/// REX6 halts with `StateChangeDuringStaticCall` at the top of the REX6 create handler, before +/// any operand read, the size check, or any resize/copy/keccak256 prework runs. REX5 (sealed) has +/// no such hoist, so it reaches the same halt reason only after running that prework and falling +/// through to the inner opcode's own static guard. A "moderately" oversized length (over the cap, +/// but cheap to resize) is used so REX5's prework-then-inner-guard path stays affordable rather +/// than running out of gas on the resize. +#[test] +fn test_create2_static_oversized_initcode_reports_static_rejection() { + const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost negligible vs. gas + + let is_static_reject = |r: Option| { + matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) + }; + + let r6 = static_create2_halt_reason(MegaSpecId::REX6, MODERATELY_OVERSIZED_LEN); + let r5 = static_create2_halt_reason(MegaSpecId::REX5, MODERATELY_OVERSIZED_LEN); + + assert!( + is_static_reject(r6), + "REX6 static oversized CREATE2 must halt with StateChangeDuringStaticCall, not \ + CreateInitCodeSizeLimit; got {r6:?}", + ); + assert!( + is_static_reject(r5), + "REX5 (sealed) static oversized CREATE2 halts with StateChangeDuringStaticCall; got {r5:?}", + ); + assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static-CREATE2 halt reason"); +} + +/// Static-call precedence at an unaffordable initcode length: a static `CREATE2` whose initcode +/// length would make `resize_memory!` prohibitively expensive must still halt with +/// `StateChangeDuringStaticCall` on REX6 — the hoisted guard fires before any operand conversion +/// or memory work is attempted, so the halt reason does not depend on whether the resize could +/// have been afforded. REX5 (sealed) has no such hoist: it attempts the resize, cannot afford it +/// out of the gas forwarded to the inner frame, and halts with a memory out-of-gas reason instead +/// — mirroring the non-static divergence pinned above, now shown to hold inside a static frame. +#[test] +fn test_create2_static_hugely_oversized_initcode_halt_reason() { + const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, resize cost far exceeds forwarded gas + + let r6 = static_create2_halt_reason(MegaSpecId::REX6, HUGE_INITCODE_LEN); + assert_eq!( + r6, + Some(InstructionResult::StateChangeDuringStaticCall), + "REX6 static CREATE2 with a hugely oversized initcode must halt with \ + StateChangeDuringStaticCall before resize_memory! is ever attempted; got {r6:?}", + ); + + let r5 = static_create2_halt_reason(MegaSpecId::REX5, HUGE_INITCODE_LEN); + assert_eq!( + r5, + Some(InstructionResult::MemoryOOG), + "REX5 (sealed) static CREATE2 must still attempt resize_memory! for a hugely oversized \ + initcode and halt with a memory out-of-gas reason, never reaching the static-call \ + rejection; got {r5:?}", + ); +} + +/// Zero-length boundary: a static `CREATE2` with `initcode_len == 0` reports the static rejection +/// on both specs. REX6 halts at the top of the create handler, before the zero-length shortcut +/// runs; REX5 (sealed) takes the shortcut, derives the address, attempts the contract-creation +/// storage charge, and only then reaches the inner opcode's static guard — same reason, different +/// path. The low-gas variant below distinguishes the two paths observably. +#[test] +fn test_create2_static_zero_length_initcode_reports_static_rejection() { + let is_static_reject = |r: Option| { + matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) + }; + + let r6 = static_create2_halt_reason(MegaSpecId::REX6, 0); + let r5 = static_create2_halt_reason(MegaSpecId::REX5, 0); + + assert!( + is_static_reject(r6), + "REX6 static zero-length CREATE2 must halt with StateChangeDuringStaticCall via the \ + inner opcode's static guard; got {r6:?}", + ); + assert!( + is_static_reject(r5), + "REX5 (sealed) static zero-length CREATE2 halts with StateChangeDuringStaticCall; \ + got {r5:?}", + ); + assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static zero-length CREATE2 halt reason"); +} + +/// Observable split on the zero-length path: with the contract-creation storage charge made +/// nonzero (2× bucket capacity → 32,000 gas) and forwarded gas below it, REX5 (sealed) attempts +/// the charge on its way to the inner opcode and halts out-of-gas — while REX6 halts +/// `StateChangeDuringStaticCall` at the top of the create handler, before the address is derived +/// or the charge is attempted. Pins that the static rejection covers the zero-length shortcut +/// path. +#[test] +fn test_create2_static_zero_length_low_gas_halt_reason() { + let r6 = static_halt_reason_for_bytecode( + MegaSpecId::REX6, + static_create2_bytecode(0), + 10_000, + Some(DOUBLED_BUCKET_CAPACITY), + ); + assert_eq!( + r6, + Some(InstructionResult::StateChangeDuringStaticCall), + "REX6 static zero-length CREATE2 must halt before the contract-creation storage charge; \ + got {r6:?}", + ); + + let r5 = static_halt_reason_for_bytecode( + MegaSpecId::REX5, + static_create2_bytecode(0), + 10_000, + Some(DOUBLED_BUCKET_CAPACITY), + ); + assert_eq!( + r5, + Some(InstructionResult::OutOfGas), + "REX5 (sealed) static zero-length CREATE2 must still attempt the contract-creation \ + storage charge first and halt out-of-gas when it cannot afford it; got {r5:?}", + ); +} + +/// The static rejection covers plain `CREATE`, not just `CREATE2`: same low-gas setup as the +/// zero-length test but with a `CREATE(value=0, offset=0, size=0)` callee. REX6 halts +/// `StateChangeDuringStaticCall` before the contract-creation storage charge; REX5 (sealed) +/// derives the address from the creator nonce, attempts the charge, and halts out-of-gas. +#[test] +fn test_create_static_low_gas_halt_reason() { + let create_bytecode = BytecodeBuilder::default() + .push_number(0u64) // size + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE) + .append(STOP) + .build(); + + let r6 = static_halt_reason_for_bytecode( + MegaSpecId::REX6, + create_bytecode.clone(), + 10_000, + Some(DOUBLED_BUCKET_CAPACITY), + ); + assert_eq!( + r6, + Some(InstructionResult::StateChangeDuringStaticCall), + "REX6 static CREATE must halt before the contract-creation storage charge; got {r6:?}", + ); + + let r5 = static_halt_reason_for_bytecode( + MegaSpecId::REX5, + create_bytecode, + 10_000, + Some(DOUBLED_BUCKET_CAPACITY), + ); + assert_eq!( + r5, + Some(InstructionResult::OutOfGas), + "REX5 (sealed) static CREATE must still attempt the contract-creation storage charge \ + first and halt out-of-gas when it cannot afford it; got {r5:?}", + ); +} + +/// The static rejection precedes operand inspection: a bare `CREATE2` on an empty stack halts +/// `StackUnderflow` on REX5 (sealed — operand inspection runs first) but +/// `StateChangeDuringStaticCall` on REX6, matching canonical revm, whose +/// `require_non_staticcall!` runs before the operand pops. +#[test] +fn test_create2_static_missing_operands_halt_reason() { + let bare_create2 = BytecodeBuilder::default().append(CREATE2).append(STOP).build(); + + let r6 = + static_halt_reason_for_bytecode(MegaSpecId::REX6, bare_create2.clone(), 50_000_000, None); + assert_eq!( + r6, + Some(InstructionResult::StateChangeDuringStaticCall), + "REX6 static CREATE2 with missing operands must halt with the static rejection, not \ + StackUnderflow; got {r6:?}", + ); + + let r5 = static_halt_reason_for_bytecode(MegaSpecId::REX5, bare_create2, 50_000_000, None); + assert_eq!( + r5, + Some(InstructionResult::StackUnderflow), + "REX5 (sealed) static CREATE2 with missing operands halts with StackUnderflow; got {r5:?}", + ); +} + +// Not covered: static + `initcode_len` unrepresentable in `usize`. `static_create2_halt_reason` +// takes a `u64` length, which always fits in `usize` on the 64-bit targets the tests run on, so +// the case cannot be expressed without a raw-`U256` variant of the shared helper. diff --git a/crates/mega-evm/tests/_pending/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs index 1dd596205..50ba6d9c9 100644 --- a/crates/mega-evm/tests/_pending/rex6/error_paths.rs +++ b/crates/mega-evm/tests/_pending/rex6/error_paths.rs @@ -1,4 +1,4 @@ -//! REX6 CREATE/SSTORE error-path coverage for the unified-metering refactor. +//! REX6 CREATE/CREATE2/SSTORE error-path coverage for the unified-metering refactor. //! //! The REX6 canonical-metering rewrite of `storage_gas_ext` moved the storage-gas charge of //! CREATE (`create_rex6`) and SSTORE behind fresh early-return guards, and split CREATE2 operand @@ -10,6 +10,9 @@ //! `EVMError::Custom`, not silently charge zero storage gas. //! - **SSTORE storage-gas DB error** (`sstore`): the zero→non-zero `sstore_set_storage_gas` failure //! must do the same. +//! - **CREATE2 operand underflow** (`compute_created_address`): a CREATE2 missing its `offset` or +//! `length` operand must halt with `StackUnderflow` from the wrapper's own `stack.inspect::<1>()` +//! / `inspect::<2>()`, before any memory expansion. use std::convert::Infallible; @@ -21,11 +24,11 @@ use mega_evm::{ MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, SaltEnv, }; use revm::{ - bytecode::opcode::{CREATE, SSTORE, STOP}, + bytecode::opcode::{CREATE, CREATE2, SSTORE, STOP}, context::TxEnv, }; -use crate::common::{CALLER, CONTRACT}; +use crate::common::{transact_default, CALLER, CONTRACT}; const ONE_ETH: u128 = 1_000_000_000_000_000_000; @@ -134,3 +137,44 @@ fn test_rex6_sstore_salt_error_on_sstore_set_storage_gas() { assert_injected_salt_custom_error(transact_with_failing_salt(MegaSpecId::REX6, code)); } + +fn is_stack_underflow(result: &crate::common::Outcome) -> bool { + matches!(&result.result, revm::context::result::ExecutionResult::Halt { reason, .. } + if format!("{reason:?}").contains("StackUnderflow")) +} + +/// CREATE2 with only the `value` operand on the stack must halt with `StackUnderflow` from the +/// wrapper's `stack.inspect::<1>()` (the `offset` operand) inside `compute_created_address`, +/// before any memory expansion. +#[test] +fn test_rex6_create2_missing_offset_stack_underflow() { + // One operand on the stack (value); `offset` is absent. + let code = BytecodeBuilder::default().push_number(0u64).append(CREATE2).append(STOP).build(); + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10 * ONE_ETH)) + .account_code(CONTRACT, code); + let outcome = transact_default(MegaSpecId::REX6, db); + + assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); +} + +/// CREATE2 with only `value` and `offset` on the stack must halt with `StackUnderflow` from the +/// wrapper's `stack.inspect::<2>()` (the `length` operand) inside `compute_created_address`. +#[test] +fn test_rex6_create2_missing_length_stack_underflow() { + // Two operands on the stack (offset, value); `length` is absent. + let code = BytecodeBuilder::default() + .push_number(0u64) // offset + .push_number(0u64) // value + .append(CREATE2) + .append(STOP) + .build(); + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10 * ONE_ETH)) + .account_code(CONTRACT, code); + let outcome = transact_default(MegaSpecId::REX6, db); + + assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); +} diff --git a/crates/mega-evm/tests/_pending/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs index a9c03a86b..a6e652c07 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -6,6 +6,7 @@ mod beneficiary_detention; mod common; +mod create2_metering_order; mod create_frame_accounting; mod eip7702_authority_accounting; mod error_paths; diff --git a/crates/mega-evm/tests/satin/static_callee.rs b/crates/mega-evm/tests/satin/static_callee.rs index 4c72ae26d..daa8b4379 100644 --- a/crates/mega-evm/tests/satin/static_callee.rs +++ b/crates/mega-evm/tests/satin/static_callee.rs @@ -3,8 +3,8 @@ //! A `CREATE` or `CREATE2` in a static frame halts with `StateChangeDuringStaticCall` before it //! reads an operand, sizes its init code or charges anything, as in canonical revm. The //! transaction does not expose an inner frame's halt reason, so these read it off the frame's -//! outcome as the caller receives it. The transactions are the differential corpus's -//! `create2_static_*` and `create_static_low_gas` scenarios. +//! outcome as the caller receives it. The transactions are those of the parked tests of the same +//! names (`tests/_pending/rex6/create2_metering_order.rs`). use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; From d38aacaf2c7016c4a29fb32fd64154e297593fdb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:47:19 +0800 Subject: [PATCH 084/201] test: pin the nonce and balance a scenario's database holds --- crates/mega-evm/src/test_utils/scenario.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index b3bc3f827..5e6cacbcb 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -467,6 +467,21 @@ mod tests { assert_eq!(db.storage(CALLEE, U256::ZERO).unwrap(), U256::from(7)); } + /// The database holds every field of every pre-state account. + #[test] + fn test_database_holds_the_pre_state() { + let mut scenario = scenario(vec![]); + scenario.pre.get_mut(&CALLEE).unwrap().storage.insert(U256::from(1), U256::from(9)); + let mut db = scenario.database(); + + let caller = db.basic(CALLER).unwrap().unwrap(); + assert_eq!((caller.nonce, caller.balance), (0, U256::from(10))); + let callee = db.basic(CALLEE).unwrap().unwrap(); + assert_eq!((callee.nonce, callee.balance), (1, U256::ZERO)); + assert_eq!(callee.code.unwrap().original_bytes(), scenario.pre[&CALLEE].code); + assert_eq!(db.storage(CALLEE, U256::from(1)).unwrap(), U256::from(9)); + } + /// A delegation designator in the pre-state is a delegation, not legacy code that starts /// with an invalid opcode. #[test] From f7ca8f28ad2368ea3a0a90b938667361915fd8a8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:53:40 +0800 Subject: [PATCH 085/201] test: mutate the scenario runner alone in the infrastructure scope --- .cargo/mutants-infra.toml | 14 +++++--------- .github/workflows/mutation.yml | 13 +++++-------- REVIEW.md | 8 +++----- mutants/README.md | 6 +++--- scripts/mutation_test.sh | 12 ++++-------- 5 files changed, 20 insertions(+), 33 deletions(-) diff --git a/.cargo/mutants-infra.toml b/.cargo/mutants-infra.toml index 302f97b29..66772a845 100644 --- a/.cargo/mutants-infra.toml +++ b/.cargo/mutants-infra.toml @@ -1,19 +1,15 @@ # cargo-mutants configuration for the test gates' own infrastructure. # # The canonical run (.cargo/mutants.toml) mutates mega-evm production code and excludes test -# helpers as noise. By that rule the code implementing the gates is helper code, but it is -# executable logic every later mechanism's verdict rests on: the scenario runner's transaction -# conversion and its execute/commit loop, and the differential harness's record, comparison and -# registry modules. This config mutates exactly those, with the differential tests among the -# killing tests; the production run keeps its exclusions unchanged. +# helpers as noise. By that rule the scenario runner (its transaction conversion and its +# execute/commit loop) is helper code, but it is executable logic the benches and later tests rest +# on. This config mutates exactly that; the production run keeps its exclusions unchanged. # # Selected by `scripts/mutation_test.sh infra`, which passes the file globs. See mutants/README.md. test_tool = "nextest" -# Both packages are tested: mega-evm's unit tests cover the scenario runner, and the differential -# crate's tests (the whole corpus through both arms) cover the record, comparison and registry -# modules. mega-differential is not a default member, so it has to be named here. -test_package = ["mega-evm", "mega-differential"] +# mega-evm's tests cover the scenario runner. +test_package = ["mega-evm"] # Same pinned feature set as the production run, so the two generate comparable mutants. additional_cargo_args = ["--all-features"] diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index f5e6ecc93..a74acc03f 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -129,11 +129,10 @@ jobs: # ── cargo-mutants: the test gates' own infrastructure ────────────────────── # The second mutation scope (.cargo/mutants-infra.toml): the scenario runner's - # transaction conversion and execute/commit loop, and the differential - # harness's record, comparison and registry modules. The production scope - # excludes test helpers as noise and tests only mega-evm, so this executable - # logic is never mutated there. 80 mutants today, so the whole set runs rather - # than a diff slice. Informational: it is not a required check. + # transaction conversion and execute/commit loop. The production scope + # excludes test helpers as noise, so this executable logic is never mutated + # there. 39 mutants today, so the whole set runs rather than a diff + # slice. Informational: it is not a required check. infra-mutants: name: cargo-mutants infrastructure needs: changes @@ -164,8 +163,7 @@ jobs: tool: cargo-mutants@27.1.0 - name: Warm build cache - # Both packages, since both are tested for every mutant of this scope. - run: cargo nextest run -p mega-evm -p mega-differential --all-features --no-run + run: cargo nextest run -p mega-evm --all-features --no-run - name: Run mutation testing env: @@ -341,7 +339,6 @@ jobs: - 'crates/mega-evm/src/**' infra: - '.cargo/mutants-infra.toml' - - 'crates/mega-differential/src/**' - 'crates/mega-evm/src/test_utils/scenario.rs' - 'scripts/mutation_gate.py' - 'scripts/mutation_test.sh' diff --git a/REVIEW.md b/REVIEW.md index 836f5f84d..55d09fd5f 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -115,14 +115,12 @@ These checks guard every change to the Satin engine. - The job is bounded to 330 minutes. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. -- The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) and the differential harness's `record`, `diff` and `registry` modules, with both packages' tests — so the whole corpus — among the killing tests. - The production scope excludes test helpers as noise and tests only `mega-evm`, so that code is otherwise never mutated, though every later mechanism's verdict rests on it. +- The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) against `mega-evm`'s tests. + The production scope excludes test helpers as noise, so that code is otherwise never mutated, though the benches and later tests rest on it. The two scopes are disjoint and the production one keeps its exclusions; a suppression may belong to either, and the suppression-hygiene job lists both scopes into its mutant universe. The `cargo-mutants infrastructure` job runs the scope on a pull request that touches those files, either configuration, the driver or the gate, and nightly; it is bounded to 90 minutes and is not a required check. - Reference point, its first run on the corpus this file describes: 80 mutants, 73 caught, 0 survived, 3 suppressed, 4 unviable, in 7m46s on a 15-core laptop with `JOBS=8`. + Reference point: 39 mutants, 34 caught, 0 survived, 3 suppressed, 2 unviable, in 5m45s on a 15-core laptop with `JOBS=8`. The three suppressed ones write a `BlockEnv` field that already holds that value by default, so no test can distinguish them; the test that pins those values kills them the moment a revm upgrade moves a default. -- `record.rs` builds a transaction record in a macro, and cargo-mutants does not mutate macro bodies, so four mutants cover that file. - Both arms build their records through that macro, so a fault in it moves both arms together and the comparison cannot see it; what covers it is the absolute values pinned in `crates/mega-differential/tests/claims.rs`, and any claim about a positive result belongs there for the same reason. - The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. It starts to bite with the first `is_enabled` gate of the spec after Satin. - The legacy mutant killers were retired with the legacy sources; a survivor in Satin code gets a new killer, next to the code or under `crates/mega-evm/tests/mutation/`. diff --git a/mutants/README.md b/mutants/README.md index 2363c49c1..776d89b47 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -7,8 +7,8 @@ Two scopes, mutated and gated separately: - **production** — `crates/mega-evm`'s engine code, with generated code and test helpers excluded as noise. (`mega-system-contracts` is excluded too — its `src/` is generated bytecode artifacts and produces zero mutants.) -- **infrastructure** — the code that implements the test gates, which the helper exclusion removes from the production scope: the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) and the differential harness's `record`, `diff` and `registry` modules. - Mutated against both packages' tests, so the whole differential corpus is among the killing tests. +- **infrastructure** — the code that implements the test gates, which the helper exclusion removes from the production scope: the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`). + Mutated against `mega-evm`'s tests. The two scopes are disjoint; a mutant belongs to exactly one of them. @@ -17,7 +17,7 @@ The two scopes are disjoint; a mutant belongs to exactly one of them. | Path | Purpose | |------|---------| | `.cargo/mutants.toml` | Canonical `cargo-mutants` config for the production scope (nextest, excludes, timeouts). | -| `.cargo/mutants-infra.toml` | Config for the infrastructure scope (no helper exclusion, both packages tested). | +| `.cargo/mutants-infra.toml` | Config for the infrastructure scope (no helper exclusion). | | `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating, in either scope. | | `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `, `infra`; `MUTANTS_SHARD=k/n` runs one shard. | | `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR. | diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 3b90bfbee..2be52d012 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -8,9 +8,9 @@ # infra Mutate the test gates' own infrastructure (see INFRA_FILES below). # # `diff`, `full` and `file` run the production scope of .cargo/mutants.toml, which excludes test -# helpers as noise. `infra` runs the second scope, .cargo/mutants-infra.toml: the code that -# implements the gates is helper code by that rule, but every later mechanism's verdict rests on -# it, so it is mutated against both packages' tests. +# helpers as noise. `infra` runs the second scope, .cargo/mutants-infra.toml: the scenario runner +# is helper code by that rule, but the benches and later tests rest on it, so it is mutated on its +# own. # # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # Run scripts/mutation_gate.py afterwards to score + gate the run. @@ -28,12 +28,9 @@ PKG_ARGS=(--package mega-evm) CONFIG_ARGS=() # The test gates' own executable logic: the scenario runner's transaction conversion and its -# execute/commit loop, and the differential harness's record, comparison and registry modules. +# execute/commit loop. INFRA_FILES=( crates/mega-evm/src/test_utils/scenario.rs - crates/mega-differential/src/record.rs - crates/mega-differential/src/diff.rs - crates/mega-differential/src/registry.rs ) cd "$ROOT_DIR" @@ -112,7 +109,6 @@ case "$cmd" in run_mutants -f "$glob" ;; infra) - PKG_ARGS=(--package mega-evm --package mega-differential) CONFIG_ARGS=(--config "$ROOT_DIR/.cargo/mutants-infra.toml") FILE_ARGS=() for file in "${INFRA_FILES[@]}"; do FILE_ARGS+=(-f "$file"); done From 520242ad9560ecd28566b34f741400a54ed8dd5f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:54:30 +0800 Subject: [PATCH 086/201] build: take the differential harness out of the repository --- .github/workflows/build-and-test.yml | 3 +- .github/workflows/differential.yml | 34 - .github/workflows/exec-spec.yml | 3 +- Cargo.lock | 629 +++--------------- Cargo.toml | 4 +- crates/mega-differential/Cargo.toml | 33 - crates/mega-differential/README.md | 130 ---- crates/mega-differential/deviations.json | 68 -- ...t_state_gas_fork_Amsterdam_state_test.json | 31 - ...s_reservoir_fork_Amsterdam_state_test.json | 31 - ...eation_cost_fork_Amsterdam_state_test.json | 28 - ...y_fork_Amsterdam_state_test_exact_fit.json | 28 - ...y_fork_Amsterdam_state_test_one_short.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_100M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_120M.json | 28 - ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 28 - ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_200M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_300M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_30M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_36M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_500M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_60M.json | 28 - ...n_detection_fork_Amsterdam_state_test.json | 35 - ..._forwarding_fork_Amsterdam_state_test.json | 35 - ...s_reservoir_fork_Amsterdam_state_test.json | 27 - ...test_reservoir_in_cap_target_kind_new.json | 28 - ...test_reservoir_in_cap_target_kind_pre.json | 28 - ...test_reservoir_over_cap_target_kind_n.json | 28 - ...test_reservoir_over_cap_target_kind_p.json | 28 - ...Amsterdam_state_test_reservoir_in_cap.json | 28 - ...sterdam_state_test_reservoir_over_cap.json | 28 - ...t_state_gas_fork_Amsterdam_state_test.json | 32 - ...ount_fork_Amsterdam_state_test_create.json | 28 - ...unt_fork_Amsterdam_state_test_create2.json | 28 - ...o_state_gas_fork_Amsterdam_state_test.json | 31 - ...new_account_fork_Amsterdam_state_test.json | 31 - ...t_state_gas_fork_Amsterdam_state_test.json | 28 - ...h_reservoir_fork_Amsterdam_state_test.json | 27 - ...d_block_gas_fork_Amsterdam_state_test.json | 27 - ...as_fork_Amsterdam_state_test_at_floor.json | 23 - ...fork_Amsterdam_state_test_below_floor.json | 23 - ..._cap_fork_Amsterdam_state_test_at_cap.json | 27 - ...fork_Amsterdam_state_test_exceeds_cap.json | 27 - ...h_state_ops_fork_Amsterdam_state_test.json | 27 - ...f_state_gas_fork_Amsterdam_state_test.json | 27 - ...y_state_gas_fork_Amsterdam_state_test.json | 27 - ...with_sstore_fork_Amsterdam_state_test.json | 27 - ...m_reservoir_fork_Amsterdam_state_test.json | 27 - ...y_fork_Amsterdam_state_test_exact_fit.json | 27 - ...y_fork_Amsterdam_state_test_one_short.json | 27 - ...to_gas_left_fork_Amsterdam_state_test.json | 27 - ...s_reservoir_fork_Amsterdam_state_test.json | 31 - ..._test_call_call_value_new_account_cha.json | 36 - ...sterdam_state_test_call_sstore_charge.json | 35 - ...state_test_delegatecall_sstore_charge.json | 35 - ...d_in_parent_fork_Amsterdam_state_test.json | 31 - ...t_reservoir_fork_Amsterdam_state_test.json | 31 - ...s_collision_fork_Amsterdam_state_test.json | 27 - ...ble_charged_fork_Amsterdam_state_test.json | 27 - ..._state_test_fail_mode_eip3541_slots_0.json | 27 - ..._state_test_fail_mode_eip3541_slots_1.json | 27 - ..._state_test_fail_mode_eip3541_slots_3.json | 27 - ...te_test_fail_mode_oog_deposit_slots_0.json | 27 - ...te_test_fail_mode_oog_deposit_slots_1.json | 27 - ...te_test_fail_mode_oog_deposit_slots_3.json | 27 - ...ATE2_state_test_charge_from_reservoir.json | 34 - ...tate_test_charge_spills_from_gas_left.json | 34 - ...EATE_state_test_charge_from_reservoir.json | 34 - ...tate_test_charge_spills_from_gas_left.json | 34 - ...e_CREATE2_state_test_existing_account.json | 30 - ...opcode_CREATE2_state_test_new_account.json | 27 - ...de_CREATE_state_test_existing_account.json | 30 - ..._opcode_CREATE_state_test_new_account.json | 27 - ...s_state_gas_fork_Amsterdam_state_test.json | 27 - ...code_CREATE2_state_test_initcode_halt.json | 31 - ...ode_CREATE2_state_test_invalid_prefix.json | 31 - ...pcode_CREATE_state_test_initcode_halt.json | 31 - ...code_CREATE_state_test_invalid_prefix.json | 31 - ...rdam_create_opcode_CREATE2_state_test.json | 31 - ...erdam_create_opcode_CREATE_state_test.json | 31 - ...rdam_create_opcode_CREATE2_state_test.json | 35 - ...erdam_create_opcode_CREATE_state_test.json | 35 - ...s_reservoir_fork_Amsterdam_state_test.json | 27 - ...t_state_gas_fork_Amsterdam_state_test.json | 27 - ...new_account_fork_Amsterdam_state_test.json | 31 - ...to_gas_left_fork_Amsterdam_state_test.json | 30 - ...rdam_create_opcode_CREATE2_state_test.json | 35 - ...erdam_create_opcode_CREATE_state_test.json | 35 - ...CREATE2_state_test_oog_on_create_base.json | 35 - ...state_test_oog_on_init_code_word_cost.json | 35 - ..._CREATE_state_test_oog_on_create_base.json | 35 - ...state_test_oog_on_init_code_word_cost.json | 35 - ...t_state_gas_fork_Amsterdam_state_test.json | 27 - ...as_consumed_fork_Amsterdam_state_test.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_100M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_120M.json | 27 - ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 27 - ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_200M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_300M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_30M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_36M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_500M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_60M.json | 27 - ...voir_fork_Amsterdam_state_test_create.json | 27 - ...oir_fork_Amsterdam_state_test_create2.json | 27 - ...sterdam_state_test_all_frames_succeed.json | 31 - ...state_test_middle_reverts_after_clear.json | 31 - ...msterdam_state_test_top_level_reverts.json | 31 - ...ble_charged_fork_Amsterdam_state_test.json | 31 - ...oir_passing_fork_Amsterdam_state_test.json | 31 - ...s_reservoir_fork_Amsterdam_state_test.json | 27 - ..._state_cost_fork_Amsterdam_state_test.json | 27 - ...exceeds_cap_fork_Amsterdam_state_test.json | 27 - ...r_below_cap_fork_Amsterdam_state_test.json | 27 - ...t_above_cap_fork_Amsterdam_state_test.json | 27 - ...e_opcode_CREATE2_state_test_exact_gas.json | 31 - ...code_CREATE2_state_test_short_one_gas.json | 31 - ...te_opcode_CREATE_state_test_exact_gas.json | 31 - ...pcode_CREATE_state_test_short_one_gas.json | 31 - ...oir_passing_fork_Amsterdam_state_test.json | 35 - ..._parent_gas_fork_Amsterdam_state_test.json | 27 - ...ume_deepest_depth_10_create_collision.json | 79 --- ...epest_depth_10_create_initcode_revert.json | 75 --- ...e_deepest_depth_10_sstore_restoration.json | 75 --- ...sume_deepest_depth_1_create_collision.json | 43 -- ...eepest_depth_1_create_initcode_revert.json | 39 -- ...me_deepest_depth_1_sstore_restoration.json | 39 -- ...sume_deepest_depth_3_create_collision.json | 51 -- ...eepest_depth_3_create_initcode_revert.json | 47 -- ...me_deepest_depth_3_sstore_restoration.json | 47 -- ...consume_top_depth_10_create_collision.json | 79 --- ...e_top_depth_10_create_initcode_revert.json | 75 --- ...nsume_top_depth_10_sstore_restoration.json | 75 --- ..._consume_top_depth_1_create_collision.json | 43 -- ...me_top_depth_1_create_initcode_revert.json | 39 -- ...onsume_top_depth_1_sstore_restoration.json | 39 -- ..._consume_top_depth_3_create_collision.json | 51 -- ...me_top_depth_3_create_initcode_revert.json | 47 -- ...onsume_top_depth_3_sstore_restoration.json | 47 -- ...e_CREATE2_state_test_insufficient_gas.json | 34 - ...ode_CREATE2_state_test_sufficient_gas.json | 34 - ...de_CREATE_state_test_insufficient_gas.json | 34 - ...code_CREATE_state_test_sufficient_gas.json | 34 - ...msterdam_state_test_no_reservoir_halt.json | 27 - ...terdam_state_test_no_reservoir_revert.json | 27 - ...terdam_state_test_with_reservoir_halt.json | 27 - ...rdam_state_test_with_reservoir_revert.json | 27 - ...ked_by_halt_fork_Amsterdam_state_test.json | 40 -- ...limits_fork_Amsterdam_state_test_100M.json | 27 - ...limits_fork_Amsterdam_state_test_120M.json | 27 - ...s_limits_fork_Amsterdam_state_test_1G.json | 27 - ...s_limits_fork_Amsterdam_state_test_1M.json | 27 - ...limits_fork_Amsterdam_state_test_200M.json | 27 - ...limits_fork_Amsterdam_state_test_300M.json | 27 - ..._limits_fork_Amsterdam_state_test_30M.json | 27 - ..._limits_fork_Amsterdam_state_test_36M.json | 27 - ...limits_fork_Amsterdam_state_test_500M.json | 27 - ..._limits_fork_Amsterdam_state_test_60M.json | 27 - ...s_state_gas_fork_Amsterdam_state_test.json | 27 - ...r_state_gas_fork_Amsterdam_state_test.json | 27 - ...ach_account_fork_Amsterdam_state_test.json | 27 - ...y_fork_Amsterdam_state_test_above_cap.json | 27 - ...dary_fork_Amsterdam_state_test_at_cap.json | 27 - ...y_fork_Amsterdam_state_test_below_cap.json | 27 - ..._and_revert_fork_Amsterdam_state_test.json | 31 - ...ll_and_halt_fork_Amsterdam_state_test.json | 31 - ..._and_revert_fork_Amsterdam_state_test.json | 31 - ...rned_on_oog_fork_Amsterdam_state_test.json | 31 - ...d_on_revert_fork_Amsterdam_state_test.json | 31 - ...pth_fork_Amsterdam_state_test_depth_1.json | 39 -- ...th_fork_Amsterdam_state_test_depth_10.json | 75 --- ...pth_fork_Amsterdam_state_test_depth_3.json | 47 -- ...epth_fork_Amsterdam_state_test_direct.json | 35 - ..._child_halt_fork_Amsterdam_state_test.json | 35 - ...o_state_gas_fork_Amsterdam_state_test.json | 28 - ..._write_cost_fork_Amsterdam_state_test.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_100M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_120M.json | 28 - ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 28 - ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_200M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_300M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_30M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_36M.json | 28 - ...h_cpsb_fork_Amsterdam_state_test_500M.json | 28 - ...th_cpsb_fork_Amsterdam_state_test_60M.json | 28 - ...msterdam_state_test_funding_reservoir.json | 28 - ...rk_Amsterdam_state_test_funding_spill.json | 28 - ...n_detection_fork_Amsterdam_state_test.json | 36 - ...stor_revert_fork_Amsterdam_state_test.json | 32 - ...n_create_tx_fork_Amsterdam_state_test.json | 28 - ...o_state_gas_fork_Amsterdam_state_test.json | 27 - ...een_reverts_fork_Amsterdam_state_test.json | 31 - ..._child_halt_fork_Amsterdam_state_test.json | 39 -- ...nd_reversal_fork_Amsterdam_state_test.json | 30 - ...me_contract_fork_Amsterdam_state_test.json | 27 - ..._fork_Amsterdam_state_test_five_slots.json | 27 - ...fork_Amsterdam_state_test_single_slot.json | 27 - ...s_fork_Amsterdam_state_test_ten_slots.json | 27 - ..._to_nonzero_fork_Amsterdam_state_test.json | 30 - ...ero_to_zero_fork_Amsterdam_state_test.json | 30 - ...n_fork_Amsterdam_state_test_exact_gas.json | 31 - ...rk_Amsterdam_state_test_short_one_gas.json | 31 - ...n_detection_fork_Amsterdam_state_test.json | 35 - ...h_cpsb_fork_Amsterdam_state_test_100M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_120M.json | 27 - ...ith_cpsb_fork_Amsterdam_state_test_1G.json | 27 - ...ith_cpsb_fork_Amsterdam_state_test_1M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_200M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_300M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_30M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_36M.json | 27 - ...h_cpsb_fork_Amsterdam_state_test_500M.json | 27 - ...th_cpsb_fork_Amsterdam_state_test_60M.json | 27 - ...erdam_call_opcode_CALLCODE_state_test.json | 39 -- ...Amsterdam_call_opcode_CALL_state_test.json | 39 -- ...m_call_opcode_DELEGATECALL_state_test.json | 39 -- ...opcode_CALLCODE_state_test_single_hop.json | 35 - ...l_opcode_CALLCODE_state_test_ten_hops.json | 71 -- ...opcode_CALLCODE_state_test_three_hops.json | 43 -- ...l_opcode_CALLCODE_state_test_two_hops.json | 39 -- ...de_DELEGATECALL_state_test_single_hop.json | 35 - ...code_DELEGATECALL_state_test_ten_hops.json | 71 -- ...de_DELEGATECALL_state_test_three_hops.json | 43 -- ...code_DELEGATECALL_state_test_two_hops.json | 39 -- ...erdam_call_opcode_CALLCODE_state_test.json | 39 -- ...m_call_opcode_DELEGATECALL_state_test.json | 39 -- ...rdam_create_opcode_CREATE2_state_test.json | 35 - ...erdam_create_opcode_CREATE_state_test.json | 35 - ...rdam_create_opcode_CREATE2_state_test.json | 27 - ...erdam_create_opcode_CREATE_state_test.json | 27 - ...tate_refund_fork_Amsterdam_state_test.json | 30 - ...e_test_depth_10_no_refund_create_oogs.json | 71 -- ...ate_test_depth_10_refund_funds_create.json | 71 -- ...te_test_depth_1_no_refund_create_oogs.json | 35 - ...tate_test_depth_1_refund_funds_create.json | 35 - ...te_test_depth_3_no_refund_create_oogs.json | 43 -- ...tate_test_depth_3_refund_funds_create.json | 43 -- ...tion_refund_fork_Amsterdam_state_test.json | 27 - ...erdam_call_opcode_CALLCODE_state_test.json | 35 - ...Amsterdam_call_opcode_CALL_state_test.json | 35 - ...m_call_opcode_DELEGATECALL_state_test.json | 35 - ...terdam_typed_transaction_0_state_test.json | 27 - ...terdam_typed_transaction_1_state_test.json | 27 - ...terdam_typed_transaction_2_state_test.json | 27 - ...m_reservoir_fork_Amsterdam_state_test.json | 27 - ...om_gas_left_fork_Amsterdam_state_test.json | 27 - ..._test_multiple_sstores_from_reservoir.json | 27 - ...st_multiple_sstores_spill_to_gas_left.json | 27 - ...ate_test_single_sstore_from_reservoir.json | 27 - ..._test_single_sstore_spill_to_gas_left.json | 27 - ..._fork_Amsterdam_state_test_at_stipend.json | 31 - ...rk_Amsterdam_state_test_below_stipend.json | 31 - ..._to_nonzero_fork_Amsterdam_state_test.json | 27 - ...ero_to_zero_fork_Amsterdam_state_test.json | 27 - ...s_reservoir_fork_Amsterdam_state_test.json | 31 - ...lear_credit_fork_Amsterdam_state_test.json | 35 - ...as_fork_Amsterdam_state_test_no_spill.json | 31 - ...e_gas_fork_Amsterdam_state_test_spill.json | 31 - ...te_gas_fork_Amsterdam_state_test_halt.json | 27 - ...ate_gas_fork_Amsterdam_state_test_oog.json | 27 - ..._gas_fork_Amsterdam_state_test_revert.json | 27 - ...te_test_halt_own_and_propagated_spill.json | 31 - ...k_Amsterdam_state_test_halt_own_spill.json | 27 - ...rdam_state_test_halt_propagated_spill.json | 31 - ..._test_revert_own_and_propagated_spill.json | 31 - ...Amsterdam_state_test_revert_own_spill.json | 27 - ...am_state_test_revert_propagated_spill.json | 31 - ...d_state_gas_fork_Amsterdam_state_test.json | 27 - .../scenarios/handwritten/code_deposit.json | 28 - .../code_deposit_large_spills.json | 28 - .../handwritten/create2_success.json | 28 - .../handwritten/create_address_collision.json | 34 - .../create_initcode_revert_after_spill.json | 28 - .../create_insufficient_endowment.json | 34 - .../create_revert_inside_reverting_call.json | 34 - .../scenarios/handwritten/create_success.json | 28 - .../handwritten/create_transaction.json | 21 - ...elegatecall_refill_of_a_parent_charge.json | 34 - .../handwritten/gas_limit_above_cap.json | 28 - .../handwritten/gas_limit_below_cap.json | 28 - .../nested_call_halt_with_spill.json | 34 - .../nested_call_revert_with_spill.json | 34 - .../selfdestruct_to_new_account.json | 34 - .../sstore_refill_after_spill.json | 28 - .../sstore_refill_no_prior_spill.json | 28 - .../handwritten/sstore_set_spills.json | 28 - .../sstore_set_within_reservoir.json | 28 - .../scenarios/handwritten/system_call.json | 26 - .../handwritten/two_txs_sequential.json | 36 - .../value_call_to_new_account.json | 28 - ...l_to_new_account_insufficient_balance.json | 28 - .../harness/access_list_duplicates.json | 53 -- .../harness/access_list_on_create.json | 27 - .../harness/access_list_unused_entries.json | 44 -- .../access_list_warm_slots_and_account.json | 43 -- .../create2_empty_initcode_large_offset.json | 23 - .../create2_empty_initcode_offset_max.json | 23 - .../create2_empty_initcode_offset_zero.json | 23 - .../harness/create2_initcode_10mib.json | 23 - .../harness/create2_initcode_32k.json | 23 - .../harness/create2_initcode_600k.json | 23 - .../harness/create2_initcode_at_limit.json | 23 - .../harness/create2_initcode_memory_oog.json | 23 - .../harness/create2_initcode_over_limit.json | 23 - .../harness/create2_missing_length.json | 23 - .../harness/create2_missing_offset.json | 23 - .../harness/create2_missing_salt.json | 23 - .../create2_nonempty_initcode_offset_max.json | 23 - ...sized_initcode_unrepresentable_offset.json | 23 - .../create2_static_empty_initcode.json | 29 - ...create2_static_empty_initcode_low_gas.json | 29 - .../create2_static_initcode_10mib.json | 29 - .../harness/create2_static_initcode_600k.json | 29 - .../create2_static_missing_operands.json | 29 - .../harness/create_static_low_gas.json | 29 - .../harness/eip7702_authority_with_code.json | 38 -- .../eip7702_call_into_delegated_account.json | 41 -- .../harness/eip7702_chain_id_mismatch.json | 40 -- .../eip7702_delegate_existing_authority.json | 38 -- .../eip7702_delegate_new_authority.json | 34 - .../eip7702_delegation_to_precompile.json | 34 - .../harness/eip7702_invalid_signature.json | 33 - .../harness/eip7702_nonce_mismatch.json | 38 -- .../harness/eip7702_redelegate_and_clear.json | 54 -- .../harness/eip7702_self_sponsored.json | 34 - ...702_two_authorizations_same_authority.json | 40 -- .../equivalence_empty_transaction.json | 16 - .../scenarios/harness/equivalence_sstore.json | 20 - .../harness/equivalence_value_transfer.json | 20 - .../scenarios/harness/fee_access_list.json | 44 -- .../harness/fee_balance_below_max_fee.json | 21 - .../scenarios/harness/fee_eip7702.json | 32 - .../harness/fee_reservoir_refund.json | 21 - .../scenarios/harness/fee_revert.json | 24 - .../harness/fee_sstore_clear_refund.json | 27 - .../scenarios/harness/fee_value_transfer.json | 21 - .../harness/logs_all_topic_counts.json | 23 - .../logs_discarded_by_reverted_subcall.json | 26 - .../scenarios/harness/precompile_blake2f.json | 31 - .../precompile_bls12_g1add_and_map.json | 34 - .../harness/precompile_bn254_add.json | 23 - .../precompile_bn254_mul_and_pairing.json | 34 - ...mpile_bn254_pairing_at_op_input_limit.json | 23 - ...ile_bn254_pairing_over_op_input_limit.json | 23 - .../harness/precompile_ecrecover.json | 31 - .../scenarios/harness/precompile_modexp.json | 31 - .../harness/precompile_p256verify.json | 31 - .../precompile_point_evaluation_invalid.json | 23 - .../precompile_point_evaluation_valid.json | 23 - ...ecompile_point_evaluation_wrong_proof.json | 23 - .../precompile_ripemd160_and_identity.json | 34 - .../scenarios/harness/precompile_sha256.json | 23 - ...reated_in_same_tx_to_existing_account.json | 27 - .../selfdestruct_in_static_context.json | 30 - .../selfdestruct_to_existing_account.json | 27 - .../selfdestruct_to_existing_contract.json | 30 - .../harness/selfdestruct_to_self.json | 24 - crates/mega-differential/src/diff.rs | 172 ----- crates/mega-differential/src/lib.rs | 279 -------- crates/mega-differential/src/mega.rs | 46 -- crates/mega-differential/src/oracle.rs | 331 --------- crates/mega-differential/src/record.rs | 195 ------ crates/mega-differential/src/registry.rs | 267 -------- crates/mega-differential/tests/claims.rs | 177 ----- crates/mega-differential/tests/corpus.rs | 14 - 368 files changed, 80 insertions(+), 13433 deletions(-) delete mode 100644 .github/workflows/differential.yml delete mode 100644 crates/mega-differential/Cargo.toml delete mode 100644 crates/mega-differential/README.md delete mode 100644 crates/mega-differential/deviations.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json delete mode 100644 crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json delete mode 100644 crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json delete mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json delete mode 100644 crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json delete mode 100644 crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json delete mode 100644 crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json delete mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json delete mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json delete mode 100644 crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json delete mode 100644 crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json delete mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json delete mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json delete mode 100644 crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json delete mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json delete mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json delete mode 100644 crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json delete mode 100644 crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json delete mode 100644 crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json delete mode 100644 crates/mega-differential/scenarios/handwritten/code_deposit.json delete mode 100644 crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create2_success.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_address_collision.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_success.json delete mode 100644 crates/mega-differential/scenarios/handwritten/create_transaction.json delete mode 100644 crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json delete mode 100644 crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json delete mode 100644 crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json delete mode 100644 crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json delete mode 100644 crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json delete mode 100644 crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json delete mode 100644 crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json delete mode 100644 crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json delete mode 100644 crates/mega-differential/scenarios/handwritten/sstore_set_spills.json delete mode 100644 crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json delete mode 100644 crates/mega-differential/scenarios/handwritten/system_call.json delete mode 100644 crates/mega-differential/scenarios/handwritten/two_txs_sequential.json delete mode 100644 crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json delete mode 100644 crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json delete mode 100644 crates/mega-differential/scenarios/harness/access_list_duplicates.json delete mode 100644 crates/mega-differential/scenarios/harness/access_list_on_create.json delete mode 100644 crates/mega-differential/scenarios/harness/access_list_unused_entries.json delete mode 100644 crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_10mib.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_32k.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_600k.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_missing_length.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_missing_offset.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_missing_salt.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json delete mode 100644 crates/mega-differential/scenarios/harness/create2_static_missing_operands.json delete mode 100644 crates/mega-differential/scenarios/harness/create_static_low_gas.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json delete mode 100644 crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json delete mode 100644 crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json delete mode 100644 crates/mega-differential/scenarios/harness/equivalence_sstore.json delete mode 100644 crates/mega-differential/scenarios/harness/equivalence_value_transfer.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_access_list.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_eip7702.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_reservoir_refund.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_revert.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json delete mode 100644 crates/mega-differential/scenarios/harness/fee_value_transfer.json delete mode 100644 crates/mega-differential/scenarios/harness/logs_all_topic_counts.json delete mode 100644 crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_blake2f.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_add.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_ecrecover.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_modexp.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_p256verify.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json delete mode 100644 crates/mega-differential/scenarios/harness/precompile_sha256.json delete mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json delete mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json delete mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json delete mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json delete mode 100644 crates/mega-differential/scenarios/harness/selfdestruct_to_self.json delete mode 100644 crates/mega-differential/src/diff.rs delete mode 100644 crates/mega-differential/src/lib.rs delete mode 100644 crates/mega-differential/src/mega.rs delete mode 100644 crates/mega-differential/src/oracle.rs delete mode 100644 crates/mega-differential/src/record.rs delete mode 100644 crates/mega-differential/src/registry.rs delete mode 100644 crates/mega-differential/tests/claims.rs delete mode 100644 crates/mega-differential/tests/corpus.rs diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 8dfc8a952..fb57502e8 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -46,8 +46,7 @@ jobs: - name: Build run: cargo build - name: Run Test - # The differential harness has its own job (differential.yml). - run: cargo test --workspace --exclude mega-differential + run: cargo test --workspace no-std: runs-on: ubuntu-24.04 diff --git a/.github/workflows/differential.yml b/.github/workflows/differential.yml deleted file mode 100644 index bcfeb2294..000000000 --- a/.github/workflows/differential.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Differential - -# Runs every scenario of the differential corpus through MegaEvm and through stock revm 43 and -# fails on any difference the deviation registry does not explain, or on a registry effect that -# explains nothing. See crates/mega-differential/README.md. - -on: - pull_request: - push: - branches: [satin] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - differential: - name: differential - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - - name: Install Rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - - name: Run the corpus - run: cargo test -p mega-differential --locked -- --nocapture diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index fd9ea2698..5493ccd01 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -6,8 +6,7 @@ name: Execution-spec tests # checks them against the numbers pinned below. # # An interim gate until the state-test tool is ported to Satin. It checks the fork MegaEvm runs -# on, not MegaEvm; MegaEvm meets execution-spec scenarios in the differential harness -# (crates/mega-differential/scenarios/eest). Not a required check. +# on, not MegaEvm. Not a required check. on: workflow_dispatch: diff --git a/Cargo.lock b/Cargo.lock index e5fb52b97..8c311d18f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,7 +156,7 @@ dependencies = [ "ethereum_ssz_derive", "serde", "serde_with", - "sha2 0.10.9", + "sha2", ] [[package]] @@ -174,7 +174,7 @@ dependencies = [ "alloy-sol-types", "auto_impl", "derive_more", - "revm 40.0.3", + "revm", "thiserror", "tracing", ] @@ -286,7 +286,7 @@ dependencies = [ "auto_impl", "op-alloy", "op-revm", - "revm 40.0.3", + "revm", "thiserror", ] @@ -312,7 +312,7 @@ dependencies = [ "cfg-if", "const-hex", "derive_more", - "foldhash 0.2.0", + "foldhash", "hashbrown 0.17.1", "indexmap 2.10.0", "itoa", @@ -709,48 +709,24 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" dependencies = [ - "ark-ec 0.5.0", + "ark-ec", "ark-ff 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", ] -[[package]] -name = "ark-bls12-381" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2ede2c0c96fa37d5d3484e8a59fec566c4a52b8c84bf993eaa6c67d7225a4c" -dependencies = [ - "ark-ec 0.6.0", - "ark-ff 0.6.0", - "ark-serialize 0.6.0", - "ark-std 0.6.0", -] - [[package]] name = "ark-bn254" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" dependencies = [ - "ark-ec 0.5.0", + "ark-ec", "ark-ff 0.5.0", - "ark-r1cs-std 0.5.0", + "ark-r1cs-std", "ark-std 0.5.0", ] -[[package]] -name = "ark-bn254" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" -dependencies = [ - "ark-ec 0.6.0", - "ark-ff 0.6.0", - "ark-r1cs-std 0.6.0", - "ark-std 0.6.0", -] - [[package]] name = "ark-ec" version = "0.5.0" @@ -759,7 +735,7 @@ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", "ark-ff 0.5.0", - "ark-poly 0.5.0", + "ark-poly", "ark-serialize 0.5.0", "ark-std 0.5.0", "educe", @@ -772,27 +748,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "ark-ec" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" -dependencies = [ - "ahash", - "ark-ff 0.6.0", - "ark-poly 0.6.0", - "ark-serialize 0.6.0", - "ark-std 0.6.0", - "educe", - "fnv", - "hashbrown 0.17.1", - "itertools 0.14.0", - "num-bigint", - "num-integer", - "num-traits", - "zeroize", -] - [[package]] name = "ark-ff" version = "0.3.0" @@ -851,23 +806,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "ark-ff" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7a806ac6c8307b929df4645776290a50ee2aac754ad09d8bdf73391309e43af" -dependencies = [ - "ark-ff-asm 0.6.0", - "ark-ff-macros 0.6.0", - "ark-serialize 0.6.0", - "ark-std 0.6.0", - "digest 0.10.7", - "educe", - "num-bigint", - "num-traits", - "zeroize", -] - [[package]] name = "ark-ff-asm" version = "0.3.0" @@ -898,16 +836,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "ark-ff-asm" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1479009684adc073dff49a1025d3a7065b317a9ead25aaaca38cdc70058ba8a2" -dependencies = [ - "quote", - "syn 2.0.104", -] - [[package]] name = "ark-ff-macros" version = "0.3.0" @@ -946,19 +874,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "ark-ff-macros" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8" -dependencies = [ - "num-bigint", - "num-traits", - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "ark-poly" version = "0.5.0" @@ -974,30 +889,15 @@ dependencies = [ "hashbrown 0.15.4", ] -[[package]] -name = "ark-poly" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" -dependencies = [ - "ahash", - "ark-ff 0.6.0", - "ark-serialize 0.6.0", - "ark-std 0.6.0", - "educe", - "fnv", - "hashbrown 0.17.1", -] - [[package]] name = "ark-r1cs-std" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" dependencies = [ - "ark-ec 0.5.0", + "ark-ec", "ark-ff 0.5.0", - "ark-relations 0.5.1", + "ark-relations", "ark-std 0.5.0", "educe", "num-bigint", @@ -1006,24 +906,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "ark-r1cs-std" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291f1c6628bfcac79b0dc2adbe401aa9100e2e96daa971645e0b18fc94de9a98" -dependencies = [ - "ark-ec 0.6.0", - "ark-ff 0.6.0", - "ark-relations 0.6.0", - "ark-std 0.6.0", - "educe", - "itertools 0.14.0", - "num-bigint", - "num-integer", - "num-traits", - "tracing", -] - [[package]] name = "ark-relations" version = "0.5.1" @@ -1033,23 +915,7 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber 0.2.25", -] - -[[package]] -name = "ark-relations" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe4c11c797a64b8a23e22bf4e77bf582ac27bb21395e3183a9a506ba2561e9f9" -dependencies = [ - "ark-ff 0.6.0", - "ark-poly 0.6.0", - "ark-serialize 0.6.0", - "ark-std 0.6.0", - "foldhash 0.1.5", - "indexmap 2.10.0", - "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -1079,26 +945,13 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" dependencies = [ - "ark-serialize-derive 0.5.0", + "ark-serialize-derive", "ark-std 0.5.0", "arrayvec", "digest 0.10.7", "num-bigint", ] -[[package]] -name = "ark-serialize" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b" -dependencies = [ - "ark-serialize-derive 0.6.0", - "ark-std 0.6.0", - "digest 0.10.7", - "num-bigint", - "serde_with", -] - [[package]] name = "ark-serialize-derive" version = "0.5.0" @@ -1110,17 +963,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "ark-serialize-derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f153690697a2b91e5e1251ff98411ee5371500a111a0fd317a70e588eb300f9" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "ark-std" version = "0.3.0" @@ -1151,16 +993,6 @@ dependencies = [ "rand 0.8.5", ] -[[package]] -name = "ark-std" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155" -dependencies = [ - "num-traits", - "rand 0.8.5", -] - [[package]] name = "arrayref" version = "0.3.9" @@ -2178,12 +2010,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" @@ -2400,7 +2226,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash 0.2.0", + "foldhash", "serde", "serde_core", ] @@ -2846,7 +2672,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2 0.10.9", + "sha2", ] [[package]] @@ -2934,17 +2760,6 @@ dependencies = [ "syn 2.0.104", ] -[[package]] -name = "mega-differential" -version = "2.0.0-alpha.1" -dependencies = [ - "alloy-primitives", - "mega-evm", - "revm 43.0.0", - "serde", - "serde_json", -] - [[package]] name = "mega-evm" version = "2.0.0-alpha.1" @@ -2963,7 +2778,7 @@ dependencies = [ "mega-system-contracts", "op-alloy-consensus", "op-revm", - "revm 40.0.3", + "revm", "revm-inspectors", "serde", "serde_json", @@ -3039,15 +2854,6 @@ dependencies = [ "serde", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num" version = "0.4.3" @@ -3284,7 +3090,7 @@ dependencies = [ "ethereum_ssz_derive", "op-alloy-consensus", "serde", - "sha2 0.10.9", + "sha2", "snap", "thiserror", ] @@ -3295,7 +3101,7 @@ version = "20.0.0" source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.2#260f65329f1f47b7412a1b2c1fda85453f66521c" dependencies = [ "auto_impl", - "revm 40.0.3", + "revm", "serde", ] @@ -3308,7 +3114,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2 0.10.9", + "sha2", ] [[package]] @@ -3392,7 +3198,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros 0.13.1", + "phf_macros", "phf_shared 0.13.1", "serde", ] @@ -3403,9 +3209,7 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros 0.14.0", "phf_shared 0.14.0", - "serde", ] [[package]] @@ -3418,42 +3222,19 @@ dependencies = [ "phf_shared 0.13.1", ] -[[package]] -name = "phf_generator" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" -dependencies = [ - "fastrand", - "phf_shared 0.14.0", -] - [[package]] name = "phf_macros" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator 0.13.1", + "phf_generator", "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.104", ] -[[package]] -name = "phf_macros" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" -dependencies = [ - "phf_generator 0.14.0", - "phf_shared 0.14.0", - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "phf_shared" version = "0.13.1" @@ -3915,9 +3696,9 @@ dependencies = [ "bytes", "derive_more", "once_cell", - "revm-bytecode 11.0.1", - "revm-primitives 24.0.1", - "revm-state 12.0.1", + "revm-bytecode", + "revm-primitives", + "revm-state", "secp256k1 0.30.0", "serde", "thiserror", @@ -3952,36 +3733,17 @@ name = "revm" version = "40.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode 11.0.1", - "revm-context 18.0.3", - "revm-context-interface 19.0.3", - "revm-database 15.0.2", - "revm-database-interface 12.1.1", - "revm-handler 20.0.3", - "revm-inspector 21.0.3", - "revm-interpreter 37.0.3", - "revm-precompile 36.0.3", - "revm-primitives 24.0.1", - "revm-state 12.0.1", -] - -[[package]] -name = "revm" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0d1681d52ee61171b838db4924827f63d659d4c3ad559aa3a57003f3dda3f7c" -dependencies = [ - "revm-bytecode 43.0.0", - "revm-context 43.0.2", - "revm-context-interface 43.0.1", - "revm-database 43.0.0", - "revm-database-interface 43.0.0", - "revm-handler 43.0.2", - "revm-inspector 43.0.2", - "revm-interpreter 43.0.1", - "revm-precompile 43.0.2", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "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]] @@ -3991,19 +3753,7 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "bitvec", "phf 0.13.1", - "revm-primitives 24.0.1", - "serde", -] - -[[package]] -name = "revm-bytecode" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d38e16b72ec1c836ec8490562bfb21003165ea8bc496086bf345680a6e6c41" -dependencies = [ - "bitvec", - "phf 0.14.0", - "revm-primitives 43.0.0", + "revm-primitives", "serde", ] @@ -4015,28 +3765,11 @@ dependencies = [ "bitvec", "cfg-if", "derive-where", - "revm-bytecode 11.0.1", - "revm-context-interface 19.0.3", - "revm-database-interface 12.1.1", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", -] - -[[package]] -name = "revm-context" -version = "43.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c16835bc2ead203219a18fcc84c2c71879ad6b890e8a71150cf7f10e4e355dc4" -dependencies = [ - "bitvec", - "cfg-if", - "derive-where", - "revm-bytecode 43.0.0", - "revm-context-interface 43.0.1", - "revm-database-interface 43.0.0", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-bytecode", + "revm-context-interface", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", ] @@ -4049,25 +3782,9 @@ dependencies = [ "alloy-eip7702", "auto_impl", "either", - "revm-database-interface 12.1.1", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", -] - -[[package]] -name = "revm-context-interface" -version = "43.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b4109bdceaca5ee6e27bf41f6b156f2b15892dc5bb47d3530bc4d3b3060077" -dependencies = [ - "alloy-eip2930", - "alloy-eip7702", - "auto_impl", - "either", - "revm-database-interface 43.0.0", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", ] @@ -4078,26 +3795,10 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "alloy-eips", "derive_more", - "revm-bytecode 11.0.1", - "revm-database-interface 12.1.1", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", -] - -[[package]] -name = "revm-database" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31d764afa9a1c9278c05d40461b07319d21ccb39c1bdf0e9dde7e5ea7d9be53d" -dependencies = [ - "alloy-eips", - "derive_more", - "either", - "revm-bytecode 43.0.0", - "revm-database-interface 43.0.0", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-bytecode", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", ] @@ -4108,22 +3809,8 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "either", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", - "thiserror", -] - -[[package]] -name = "revm-database-interface" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2a27e4440c2ef4932afdaa28a1d1ac8601504c7030c1a387b5e307d07d864d1" -dependencies = [ - "auto_impl", - "either", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-primitives", + "revm-state", "serde", "thiserror", ] @@ -4135,33 +3822,14 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "derive-where", - "revm-bytecode 11.0.1", - "revm-context 18.0.3", - "revm-context-interface 19.0.3", - "revm-database-interface 12.1.1", - "revm-interpreter 37.0.3", - "revm-precompile 36.0.3", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", -] - -[[package]] -name = "revm-handler" -version = "43.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73a7409031d87ec281b74efff65d7a4dbea9d80727a55dbc7e4b3fd77b5e03fb" -dependencies = [ - "auto_impl", - "derive-where", - "revm-bytecode 43.0.0", - "revm-context 43.0.2", - "revm-context-interface 43.0.1", - "revm-database-interface 43.0.0", - "revm-interpreter 43.0.1", - "revm-precompile 43.0.2", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-bytecode", + "revm-context", + "revm-context-interface", + "revm-database-interface", + "revm-interpreter", + "revm-precompile", + "revm-primitives", + "revm-state", "serde", ] @@ -4172,30 +3840,12 @@ source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de dependencies = [ "auto_impl", "either", - "revm-context 18.0.3", - "revm-database-interface 12.1.1", - "revm-handler 20.0.3", - "revm-interpreter 37.0.3", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", - "serde_json", -] - -[[package]] -name = "revm-inspector" -version = "43.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a56f37224afd628f7244aa6965609ada04b440ed8ab7a19f55e4291df5a0112" -dependencies = [ - "auto_impl", - "either", - "revm-context 43.0.2", - "revm-database-interface 43.0.0", - "revm-handler 43.0.2", - "revm-interpreter 43.0.1", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-context", + "revm-database-interface", + "revm-handler", + "revm-interpreter", + "revm-primitives", + "revm-state", "serde", "serde_json", ] @@ -4212,7 +3862,7 @@ dependencies = [ "alloy-sol-types", "anstyle", "colorchoice", - "revm 40.0.3", + "revm", "serde", "serde_json", "thiserror", @@ -4223,23 +3873,10 @@ name = "revm-interpreter" version = "37.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode 11.0.1", - "revm-context-interface 19.0.3", - "revm-primitives 24.0.1", - "revm-state 12.0.1", - "serde", -] - -[[package]] -name = "revm-interpreter" -version = "43.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "932f7fe05a2cdeb08195dd7e88a09a4da7c3660cdc6e62720839c77ba77f65aa" -dependencies = [ - "revm-bytecode 43.0.0", - "revm-context-interface 43.0.1", - "revm-primitives 43.0.0", - "revm-state 43.0.0", + "revm-bytecode", + "revm-context-interface", + "revm-primitives", + "revm-state", "serde", ] @@ -4248,9 +3885,9 @@ name = "revm-precompile" version = "36.0.3" source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "ark-bls12-381 0.5.0", - "ark-bn254 0.5.0", - "ark-ec 0.5.0", + "ark-bls12-381", + "ark-bn254", + "ark-ec", "ark-ff 0.5.0", "ark-serialize 0.5.0", "arrayref", @@ -4260,35 +3897,11 @@ dependencies = [ "cfg-if", "k256", "p256", - "revm-context-interface 19.0.3", - "revm-primitives 24.0.1", - "ripemd 0.1.3", + "revm-context-interface", + "revm-primitives", + "ripemd", "secp256k1 0.31.1", - "sha2 0.10.9", -] - -[[package]] -name = "revm-precompile" -version = "43.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac4dc0279f2a44770faa8c93d008df684440cf573c91b8e0e39d0d581abf7b3d" -dependencies = [ - "ark-bls12-381 0.6.0", - "ark-bn254 0.6.0", - "ark-ec 0.6.0", - "ark-ff 0.6.0", - "ark-serialize 0.6.0", - "arrayref", - "aurora-engine-modexp", - "c-kzg", - "cfg-if", - "k256", - "p256", - "revm-context-interface 43.0.1", - "revm-primitives 43.0.0", - "ripemd 0.2.0", - "secp256k1 0.31.1", - "sha2 0.11.0", + "sha2", ] [[package]] @@ -4301,17 +3914,6 @@ dependencies = [ "serde", ] -[[package]] -name = "revm-primitives" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f4ba1a5757fe4398262290422c371556fcebf236f762f7ed7ff2c56768a63c" -dependencies = [ - "alloy-primitives", - "once_cell", - "serde", -] - [[package]] name = "revm-state" version = "12.0.1" @@ -4320,22 +3922,8 @@ dependencies = [ "alloy-eip7928", "bitflags 2.11.1", "nonmax", - "revm-bytecode 11.0.1", - "revm-primitives 24.0.1", - "serde", -] - -[[package]] -name = "revm-state" -version = "43.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd02082cf1baca01e8bc17456c45136bdc66632395a98db1c1a2afe4c6ea87f" -dependencies = [ - "alloy-eip7928", - "bitflags 2.11.1", - "nonmax", - "revm-bytecode 43.0.0", - "revm-primitives 43.0.0", + "revm-bytecode", + "revm-primitives", "serde", ] @@ -4358,15 +3946,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "ripemd" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" -dependencies = [ - "digest 0.11.3", -] - [[package]] name = "rlp" version = "0.5.2" @@ -4692,17 +4271,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.3", -] - [[package]] name = "sha3" version = "0.11.0" @@ -4723,15 +4291,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -4954,15 +4513,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - [[package]] name = "threadpool" version = "1.8.1" @@ -5173,17 +4723,6 @@ dependencies = [ "valuable", ] -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - [[package]] name = "tracing-subscriber" version = "0.2.25" @@ -5193,20 +4732,6 @@ dependencies = [ "tracing-core", ] -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", -] - [[package]] name = "try-lock" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index de0f2e4d2..b4502668f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,9 +3,7 @@ # The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, # `crates/state-test`) still target the legacy engine; their sources are kept # untouched and each rejoins the workspace when it is ported to Satin. -# `crates/mega-differential` is a member but not a default member: it builds stock revm 43 as the -# oracle of the differential harness, so the commands run at the root stay on the engine's graph. -members = ["crates/mega-differential", "crates/mega-evm", "crates/system-contracts"] +members = ["crates/mega-evm", "crates/system-contracts"] default-members = ["crates/mega-evm"] exclude = [] diff --git a/crates/mega-differential/Cargo.toml b/crates/mega-differential/Cargo.toml deleted file mode 100644 index 55b8c27b9..000000000 --- a/crates/mega-differential/Cargo.toml +++ /dev/null @@ -1,33 +0,0 @@ -[package] -name = "mega-differential" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -description = "Differential harness: runs transaction scenarios through MegaEvm and through revm 43, field by field" -publish = false - -[lints] -workspace = true - -[dependencies] -# alloy -alloy-primitives = { workspace = true, features = ["serde"] } - -# revm -# The oracle: stock revm 43.0.0 from crates.io. The workspace's `[patch.crates-io] revm` points at -# the fork, whose version (40.0.3) does not satisfy `=43.0.0`, so this requirement resolves to the -# registry and the two revms sit side by side in this crate only. Default features stay off so the -# oracle adds no native precompile backend (c-kzg, blst, secp256k1) to the lockfile; it runs the -# pure-Rust ones. `dev` compiles the same optional configuration fields `mega-evm` compiles on the -# fork, so the oracle copies every one of them. -revm-oracle = { package = "revm", version = "=43.0.0", default-features = false, features = ["dev", "serde", "std"] } - -# megaeth -mega-evm = { workspace = true, features = ["default", "test-utils"] } - -# misc -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true, features = ["std"] } diff --git a/crates/mega-differential/README.md b/crates/mega-differential/README.md deleted file mode 100644 index 5cefaf0d4..000000000 --- a/crates/mega-differential/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# mega-differential - -The differential harness of the Satin engine. -It runs every scenario of a corpus through `MegaEvm` and through stock revm 43, and compares what the two report, field by field. -Every difference must be explained by the deviation registry, and every effect an active registry entry lists must explain at least one difference. - -```bash -cargo test -p mega-differential --locked -``` - -The corpus test prints one summary line, for example: - -```text -differential: 352 scenarios, 13296 fields compared, 1088 deviations matched (op-fee-vault-touch x1080, op-karst-bn254-pairing-input-bound x8), 0 unexplained, 0 stale registry effects -``` - -CI runs the same command as the `differential` job (`.github/workflows/differential.yml`), on every pull request and every push to `satin`. - -## The two arms - -**Left arm: `MegaEvm`.** -Each transaction runs on a fresh `MegaEvm` over a `MegaContext` for `MegaSpecId::SATIN`, through alloy-evm's `Evm::transact_raw` (system calls through `Evm::transact_system_call`). -The configuration is the one the spec fixes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 and EIP-2780 on, the 200,000,000 execution cap, EIP-7708 and the system-call reservoir margin off. -The L1 fees are zero (`test_utils::zero_fee_l1_block_info`), every transaction is a non-deposit one with an empty envelope, and the gas price is the transaction's own (zero unless the scenario sets one). -`mega-evm` is built with its default features, so the precompiles run on the same backends as in a node. - -**Right arm: the oracle.** -Stock `revm = "=43.0.0"` from crates.io, on its mainnet handler. -The requirement pins the `revm` crate itself; its sub-crates resolve to the 43.0.x patch releases the lockfile holds (`revm-context`, `revm-handler`, `revm-inspector` and `revm-precompile` 43.0.2, `revm-context-interface` and `revm-interpreter` 43.0.1, the others 43.0.0). -Its configuration is copied from the left arm's (`oracle::cfg`): the Ethereum spec the Satin spec runs on (Osaka), the gas table entry by entry, and every switch. -The fork numbers its gas ids as upstream does and adds its own at the top of the table (`tests/claims.rs` checks both, and that the fork-only prices are zero). -If `MegaEvm` switches on a mechanism revm 43 cannot run (EIP-7708 before Amsterdam, the system-call state-gas margin), `oracle::cfg` panics: the mechanism that switches it on has to model it or register the difference. -revm 43's `ResultGas` has no `reservoir_remaining`; the oracle reads the reservoir from the frame's gas at the point the fork records it (a handler that wraps revm 43's mainnet handler and only reads; a unit test checks it changes nothing else). - -Both arms share the scenario format and its loader, `mega_evm::test_utils::Scenario`. - -## How the two revms coexist - -The workspace redirects `revm` to the MegaETH fork with `[patch.crates-io]`. -A patch only replaces a crates.io dependency whose version requirement the patched crate satisfies: the fork is `revm 40.0.3`, and this crate asks for `=43.0.0`, which it does not satisfy, so the requirement resolves to the registry. -Both revms therefore sit in this crate's graph, and only here: the crate is a workspace member but not a default member, and nothing else depends on it. - -```bash -cargo tree -i revm --locked -p mega-evm # one revm, the fork -cargo tree -p mega-differential -i revm --locked # "ambiguous": revm@40.0.3 and revm@43.0.0 -cargo tree -p mega-differential -i revm@43.0.0 --locked -cargo tree -p mega-differential -i revm@40.0.3 --locked -``` - -The oracle is built without revm's default features, so it adds no native precompile backend (c-kzg, blst, secp256k1) to the build; it runs the pure-Rust ones. -A precompile scenario therefore compares two independent implementations: `harness/precompile_point_evaluation_valid` verifies the same KZG proof through the fork's c-kzg and through the oracle's arkworks, and `tests/claims.rs` pins what the left arm returns for it, so two calls that fail cannot stand in for a proof neither arm verified. -Its `dev` feature compiles the same optional configuration fields `mega-evm` compiles on the fork, so each of them is copied. - -The lockfile is shared. -Cargo writes the version requirements of revm 43's optional dependencies into it even though they are not built, so adding the oracle moved two crates of the core's graph to newer semver-compatible releases: `c-kzg` 2.1.7 → 2.1.8 and `tracing-core` 0.1.34 → 0.1.36. - -## The corpus - -`scenarios/` holds one JSON file per scenario; the file stem is the scenario name. -The format is `mega_evm::test_utils::Scenario`: an optional description, a coinbase, the pre-state accounts (nonce, balance, code, storage; code is legacy bytecode or an EIP-7702 delegation designator) and the transactions, run in order. -A transaction is a `call`, a `create` or a `system_call`; it may carry a `gas_price`, an EIP-2930 access list and an EIP-7702 authorization list with the signer already recovered (`authority`, absent for a signature that does not recover). -The block is fixed: number 1, timestamp 1, zero base fee, unlimited gas. - -| Directory | Scenarios | Origin | -| -------------- | --------: | ---------------------------------------------------------------------------------------------------------------------------------- | -| `handwritten/` | 23 | the hand-written scenarios of the reference differential of the fork: state-gas spill and refill, creates, nested reverts and halts | -| `eest/` | 263 | derived from the execution-spec-test Amsterdam state tests of EIP-8037 (state gas, its reservoir, and its interplay with the EIP-7623 calldata floor); the names keep the fixture test ids | -| `harness/` | 66 | written for this harness, for what the reference corpus lacks: EIP-7702 authorizations, access lists, SELFDESTRUCT to existing accounts, logs, precompiles, gas prices (`fee_*`: the fee debit, the coinbase's fee and the refunds show up in balances), the three cases of `crates/mega-evm/tests/satin/equivalence.rs`, and the CREATE and CREATE2 edge cases of the legacy suite (`create*`, listed in `crates/mega-evm/tests/_pending/README.md`) | - -The first two sets come from a reference harness that ran them at per-scenario state-gas prices and execution caps. -Satin fixes both, so the import dropped the `cap` and `prices` fields and moved every gas limit above the reference cap `C` to the Satin cap plus the same reservoir: `G' = 200,000,000 + (G − C)`. -Gas limits at or below the reference cap are unchanged, and the system call lost its gas limit, since a system call runs with the engine's own. -Under the Osaka gas table state gas is priced at zero, so today those scenarios exercise the reservoir, refunds and the regular-gas paths; their state-gas paths start to count when the Satin gas table prices state and the oracle takes the same table. - -Each scenario of `harness/` carries a `description` of what it exercises. -To add a scenario, drop a JSON file into the directory of its origin; the loader rejects unknown fields, a name that is not the file stem, and a duplicate name. - -## What is compared - -For every transaction: - -- the outcome: `success`, `revert`, `halt:` or `error:`, with op-revm's naming wrappers taken off; -- every gas figure: each field of `ResultGas` as it serializes (`gas_spent`, `state_gas_spent`, `gas_refunded`, `floor_gas`, `reservoir_remaining`), so a field the fork adds shows up as a difference, and the derived `tx_gas_used`, `block_regular_gas_used`, `block_state_gas_used` and `final_refunded`; - history gas has no field of its own in `ResultGas` and is part of `gas_spent` and `block_regular_gas_used`; -- the output bytes and the created address; -- the logs; -- every touched account: created and self-destructed flags, balance, nonce, code hash, and the value of every slot the transaction changed. - -The halt reason of an inner frame is not compared, only what it does to the gas, the state and its caller (a scenario that needs it records the call's success in storage). - -## The deviation registry - -`deviations.json` lists the accepted differences. -An entry names one mechanism and every effect it has on the compared fields: - -```json -{ - "id": "op-fee-vault-touch", - "status": "active", - "scenario": "*", - "mechanism": "op-revm fee distribution: the OP handler's reward_beneficiary", - "reason": "…", - "effects": [ - { - "field": "tx[*].state[0x4200000000000000000000000000000000000019]", - "left": "created=false selfdestructed=false balance=0x0 …", - "right": "" - } - ] -} -``` - -- `scenario` and each effect's `field`, `left` (the `MegaEvm` value) and `right` (the oracle's) are patterns in which `*` stands for any run of characters. - Keep them as narrow as the mechanism allows: exact values, and a scenario pattern that covers only the scenarios the mechanism reaches. -- `status` is `active` or `retired`; a retired entry keeps its history in `retired_reason` and explains nothing. -- The run fails on a difference no effect of an active entry explains, and on an effect of an active entry that explains nothing. - When a mechanism stops producing an effect, remove the effect, or retire the entry when none is left. -- The `version` field is the format version this crate reads. - -The active entries today: - -- `op-fee-vault-touch`: after every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to three vault predeploys, which touches them even at a zero amount. - `tests/claims.rs` checks that state clearing drops those empty accounts when the state is committed. -- `op-karst-bn254-pairing-input-bound`: op-revm's Karst precompile set rejects a BN254 pairing input over 57,600 bytes, which Ethereum's pairing accepts; `harness/precompile_bn254_pairing_over_op_input_limit` crosses the bound and `harness/precompile_bn254_pairing_at_op_input_limit` stays on it. - -## Relation to the equivalence tests - -`crates/mega-evm/tests/satin/equivalence.rs` compares `MegaEvm` with op-revm's `OpEvm` on the same fork, which pins that the Satin layer adds nothing to op-revm yet. -This harness compares `MegaEvm` with an independent implementation, which pins that the fork plus op-revm execute Ethereum semantics. -The three equivalence cases are also scenarios here (`harness/equivalence_*`); the equivalence tests stay as they are, since they check a different claim that later changes update on purpose. diff --git a/crates/mega-differential/deviations.json b/crates/mega-differential/deviations.json deleted file mode 100644 index cbf51eb52..000000000 --- a/crates/mega-differential/deviations.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "version": 1, - "deviations": [ - { - "id": "op-fee-vault-touch", - "status": "active", - "scenario": "*", - "mechanism": "op-revm fee distribution: the OP handler's reward_beneficiary", - "reason": "After every non-deposit transaction op-revm credits the base fee, the L1 data fee and the operator fee to the BaseFeeVault (0x…19), L1FeeVault (0x…1a) and OperatorFeeVault (0x…1b) predeploys with balance_incr, which touches each vault even when the amount is zero. The corpus runs with zero fees, so each vault is touched and stays empty; revm 43's mainnet handler has no vaults. EIP-161 state clearing drops a touched empty account when the state is committed (tests/claims.rs checks it), so the difference never reaches the state root. An effect stops matching once a transaction pays a non-zero fee of its kind: the vault then holds a balance and the difference must be attributed again.", - "effects": [ - { - "field": "tx[*].state[0x4200000000000000000000000000000000000019]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "" - }, - { - "field": "tx[*].state[0x420000000000000000000000000000000000001a]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "" - }, - { - "field": "tx[*].state[0x420000000000000000000000000000000000001b]", - "left": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}", - "right": "" - } - ] - }, - { - "id": "op-karst-bn254-pairing-input-bound", - "status": "active", - "scenario": "precompile_bn254_pairing_over_op_input_limit", - "mechanism": "op-revm's Karst precompile set: the BN254 pairing (0x08) rejects inputs over 57,600 bytes", - "reason": "op-revm bounds the BN254 pairing input on OP chains (57,600 bytes, 300 pairs, from Karst on); a longer input fails the precompile, which consumes the gas the call forwarded. Ethereum's pairing has no such bound, so revm 43 runs the 301 pairs and returns 1. The scenario's proxy records the failure: it stores no success flag and no return size, and the hash of empty return data. The failed call also leaves the precompile account untouched.", - "effects": [ - { - "field": "tx[0].gas.*", - "left": "29561930", - "right": "10608872" - }, - { - "field": "tx[0].output", - "left": "0x", - "right": "0x0000000000000000000000000000000000000000000000000000000000000001" - }, - { - "field": "tx[0].state[0x0000000000000000000000000000000000000008]", - "left": "", - "right": "created=false selfdestructed=false balance=0x0 nonce=0 code_hash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 storage={}" - }, - { - "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x0]", - "left": "", - "right": "0x1" - }, - { - "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x1]", - "left": "", - "right": "0x20" - }, - { - "field": "tx[0].state[0x0000000000000000000000000000000000009908].storage[0x2]", - "left": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", - "right": "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 1caa4520e..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_call_insufficient_balance_refunds_new_account_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x52046af6a4e2f4c607b63b582be53f06915040e3": { - "nonce": 1, - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x52046af6a4e2f4c607b63b582be53f06915040e3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 2dadfd539..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_call_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe02a60813fb94718ddd669258a39c113946a7a26": { - "nonce": 1, - "code": "0x600060006000600060017337f536464af59c8d7358cae965f92cbeadd58dcb620186a0f16000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe02a60813fb94718ddd669258a39c113946a7a26", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json deleted file mode 100644 index 5a8e07fab..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_no_execution_account_creation_cost_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xca1c9efd74f1a6b6f21a1ecf6a9f3334c87164dc": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f15000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xca1c9efd74f1a6b6f21a1ecf6a9f3334c87164dc", - "data": "0x", - "value": "0x00", - "gas_limit": 200058230, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json deleted file mode 100644 index 415128309..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_exact_fit", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f100" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8", - "data": "0x", - "value": "0x00", - "gas_limit": 200053230, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json deleted file mode 100644 index c6785c5f6..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_boundary_fork_Amsterdam_state_test_one_short", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f100" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd86f0b1d238a536b0b9f71c6ba85e54ecb4044a8", - "data": "0x", - "value": "0x00", - "gas_limit": 200053230, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json deleted file mode 100644 index 777cd31dd..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json deleted file mode 100644 index 654323465..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json deleted file mode 100644 index 7a2edfc74..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json deleted file mode 100644 index 1100c2936..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json deleted file mode 100644 index fb3e6cc2a..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json deleted file mode 100644 index b173de2da..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json deleted file mode 100644 index 601665d93..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json deleted file mode 100644 index 5aa23b895..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json deleted file mode 100644 index ac57b95da..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json deleted file mode 100644 index cd870fc0c..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_new_account_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8ed43eec7669b1c5749f3458455cbe39dfdefebd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json deleted file mode 100644 index 1c4e86ba4..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_call_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x3ef0adbd819089c276e7bac4d5c3844bbfc1b963": { - "nonce": 1, - "code": "0x6000600060006000600161dead6000f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x97d820929f41220187e4e5608702a49a70625fa5": { - "nonce": 1, - "code": "0x60006000600060006000733ef0adbd819089c276e7bac4d5c3844bbfc1b96362030520f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x97d820929f41220187e4e5608702a49a70625fa5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json deleted file mode 100644 index d94f7eddf..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_call_pre_charged_costs_excluded_from_forwarding_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x093685b223a8eb80d2365b02a2346b00b7ca4e83": { - "nonce": 1, - "code": "0x6000600060006000600073634cc1a10e5dec3daef49aa355d43ab81d3b07206147d7f150" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x634cc1a10e5dec3daef49aa355d43ab81d3b0720": { - "nonce": 1, - "code": "0x614000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef63fffffffff1" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x093685b223a8eb80d2365b02a2346b00b7ca4e83", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index fb0506c26..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_call_stack_depth_returns_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825": { - "nonce": 1, - "code": "0x60006000600060006000305af1506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json deleted file mode 100644 index a4ef59126..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_new", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f1fe" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json deleted file mode 100644 index 9d9d68ee8..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_in_cap_target_kind_pre", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600160086000f1fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json deleted file mode 100644 index 27bb4ba55..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_n", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f1fe" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf8bdf1c4bfaa8b56bb2c7845f42f74ba94b04fe3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json deleted file mode 100644 index 6dd42ff62..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_consumed_on_caller_halt_fork_Amsterdam_state_test_reservoir_over_cap_target_kind_p", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600160086000f1fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb208dc21515f8d7c1a87525e24dd3f521ad96c6a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json deleted file mode 100644 index 235701b63..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_in_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f160006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json b/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json deleted file mode 100644 index 71ca952af..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_new_account_state_gas_returned_on_caller_revert_fork_Amsterdam_state_test_reservoir_over_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b6000f160006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x12dabbf852dcbcf767ca632d63fd28d9f9d460be", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 4dc8e3b08..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "test_call_value_precompile_halt_refunds_new_account_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd1eb0fb525ff1409c4938cca3a03f31ba0f831f3": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600160086001f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd1eb0fb525ff1409c4938cca3a03f31ba0f831f3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json deleted file mode 100644 index ddcb3bb31..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x690da8229a8448e73cc9d03ef3f68f86cb9cd351": { - "nonce": 1, - "balance": "0x03", - "code": "0x7f30ff000000000000000000000000000000000000000000000000000000000000600052600260006001f08060205250600060006000600060016020515af1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x690da8229a8448e73cc9d03ef3f68f86cb9cd351", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json b/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json deleted file mode 100644 index 92502a31c..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_call_value_to_self_destructed_same_tx_account_fork_Amsterdam_state_test_create2", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0280b72062c43cbd14113e8ab12360868b5d7200": { - "nonce": 1, - "balance": "0x03", - "code": "0x7f30ff0000000000000000000000000000000000000000000000000000000000006000526000600260006001f58060205250600060006000600060016020515af1600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0280b72062c43cbd14113e8ab12360868b5d7200", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 9abd9478e..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_call_value_transfer_existing_account_no_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x32aa3856e9410279aa9c2933356e4cb403d68373": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173f36afef4dcb45e52f80cb039335952f77cec8960620186a0f1600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf36afef4dcb45e52f80cb039335952f77cec8960": { - "balance": "0x01" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x32aa3856e9410279aa9c2933356e4cb403d68373", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json deleted file mode 100644 index dba8f4a2d..000000000 --- a/crates/mega-differential/scenarios/eest/test_call_value_transfer_new_account_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_call_value_transfer_new_account_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xebb3ed1a3b7767fca5a4d4a82bdcd8f9be5da5bc": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b620186a0f1600055", - "storage": { - "0x00": "0x02" - } - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xebb3ed1a3b7767fca5a4d4a82bdcd8f9be5da5bc", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 77bc133f1..000000000 --- a/crates/mega-differential/scenarios/eest/test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_callcode_value_no_new_account_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x50a79fee82f1767e31cbef3d1c6761e3f338b869": { - "nonce": 1, - "balance": "0x0de0b6b3a7640000", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af2506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x50a79fee82f1767e31cbef3d1c6761e3f338b869", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index c7b8e5b33..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_binds_with_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 7bfae053a..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_counts_toward_block_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json deleted file mode 100644 index 7b0c06635..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_at_floor", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc0f6dc9e5836f54caadbf59cc69346c508e1992b", - "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200005350, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json deleted file mode 100644 index a9f8b0bde..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "test_calldata_floor_enforced_with_state_gas_fork_Amsterdam_state_test_below_floor", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc0f6dc9e5836f54caadbf59cc69346c508e1992b", - "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200004750, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json deleted file mode 100644 index ca0efd8cd..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_at_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0x010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json deleted file mode 100644 index 50921b181..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_exceeding_tx_gas_limit_cap_fork_Amsterdam_state_test_exceeds_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json deleted file mode 100644 index b3dee5aed..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_higher_than_execution_with_state_ops_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index bf30d27b1..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_independent_of_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index c30e9eb6e..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_not_discounted_by_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json deleted file mode 100644 index 3a4b2393c..000000000 --- a/crates/mega-differential/scenarios/eest/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_calldata_floor_with_sstore_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 3f5d35e46..000000000 --- a/crates/mega-differential/scenarios/eest/test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_charge_draws_entirely_from_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd7942304c419230163398d295036321e27e2e2fe": { - "nonce": 1, - "code": "0x60016000556000600101600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd7942304c419230163398d295036321e27e2e2fe", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json deleted file mode 100644 index 2a9117e16..000000000 --- a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_charge_spill_boundary_fork_Amsterdam_state_test_exact_fit", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200031256, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json b/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json deleted file mode 100644 index f9dc8af00..000000000 --- a/crates/mega-differential/scenarios/eest/test_charge_spill_boundary_fork_Amsterdam_state_test_one_short.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_charge_spill_boundary_fork_Amsterdam_state_test_one_short", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200031256, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json deleted file mode 100644 index 2902fa49b..000000000 --- a/crates/mega-differential/scenarios/eest/test_charge_spills_to_gas_left_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_charge_spills_to_gas_left_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 235f901b8..000000000 --- a/crates/mega-differential/scenarios/eest/test_child_call_uses_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_child_call_uses_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf0fe41d947da36ba18bb17012d4e33ba81d852ec": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf0fe41d947da36ba18bb17012d4e33ba81d852ec", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json deleted file mode 100644 index 47d82e640..000000000 --- a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_call_value_new_account_cha", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa61f3a41615e1900676200ed31c287ed5ad51f5f": { - "nonce": 1, - "code": "0x6000600060006000600073f207c059154dc6d35ff485a54cf0a466f0a06b115af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf207c059154dc6d35ff485a54cf0a466f0a06b11": { - "nonce": 1, - "balance": "0x01", - "code": "0x6000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af15060006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xa61f3a41615e1900676200ed31c287ed5ad51f5f", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json deleted file mode 100644 index 3403361a5..000000000 --- a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_call_sstore_charge", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x921019ef0dfa80a772ac96256fb64605d3bd68c0": { - "nonce": 1, - "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x921019ef0dfa80a772ac96256fb64605d3bd68c0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json b/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json deleted file mode 100644 index 136f78389..000000000 --- a/crates/mega-differential/scenarios/eest/test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_child_failure_refunds_state_gas_to_reservoir_not_gas_left_fork_Amsterdam_state_test_delegatecall_sstore_charge", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x3eaf0d84225675074f75f21322e538a2f32a7263": { - "nonce": 1, - "code": "0x600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af450600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af450" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x3eaf0d84225675074f75f21322e538a2f32a7263", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json deleted file mode 100644 index dba8e68e7..000000000 --- a/crates/mega-differential/scenarios/eest/test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_child_state_gas_tracked_in_parent_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x22d3d2785c604f63057c379f38cc9e3a758152f6": { - "nonce": 1, - "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f1600155" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x22d3d2785c604f63057c379f38cc9e3a758152f6", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 7eb999045..000000000 --- a/crates/mega-differential/scenarios/eest/test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_code_deposit_oog_preserves_parent_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x3279904096d6e2fb187b797bb27d79ef221bca59": { - "nonce": 1, - "code": "0x6000600060006000600073727cf77a2c6de3634297d278a2fda305010b1f2b6216e360f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x727cf77a2c6de3634297d278a2fda305010b1f2b": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000000000006110006000f36000526006601a6000f06000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x3279904096d6e2fb187b797bb27d79ef221bca59", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json deleted file mode 100644 index db1471914..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_address_collision_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_address_collision_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9f207d2415e91c7c19e3cd8aa806ce77db392bfe": { - "nonce": 1, - "code": "0x60006000526000600160006000f515156000556000600160006000f5600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x9f207d2415e91c7c19e3cd8aa806ce77db392bfe", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json deleted file mode 100644 index 58837e527..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_child_spill_not_double_charged_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc915407640e516d8e66e2774a4686ab6a3c7de67": { - "nonce": 1, - "code": "0x7f60016000556002600155600360025560046003556005600455600660055500006000526000601f60006000f550" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc915407640e516d8e66e2774a4686ab6a3c7de67", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json deleted file mode 100644 index 1376a92c6..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_0", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5f3204dd0805d0204f0bfdcdc7dbd7701da926b1": { - "nonce": 1, - "code": "0x7f60ef60005360016000f3000000000000000000000000000000000000000000006000526000600a60006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5f3204dd0805d0204f0bfdcdc7dbd7701da926b1", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json deleted file mode 100644 index a9b38512c..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_1", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x820b460b61ebed793495cfa83446666c71f3e3a5": { - "nonce": 1, - "code": "0x7f600160005560ef60005360016000f300000000000000000000000000000000006000526000600f60006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x820b460b61ebed793495cfa83446666c71f3e3a5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json deleted file mode 100644 index 06ba868f0..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_eip3541_slots_3", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x651ebfcb9681510a3a27dac0d6b74fc15c0678a5": { - "nonce": 1, - "code": "0x7f60016000556002600155600360025560ef60005360016000f3000000000000006000526000601960006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x651ebfcb9681510a3a27dac0d6b74fc15c0678a5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json deleted file mode 100644 index 6fd697d87..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_0", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x97e3e4e25bc5398b1a2fb5b1923eb7df47df940c": { - "nonce": 1, - "code": "0x7f620100006000f3000000000000000000000000000000000000000000000000006000526000600760006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x97e3e4e25bc5398b1a2fb5b1923eb7df47df940c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json deleted file mode 100644 index c347a794b..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_1", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xded801e9b63939db16c75751ca035243294ffb28": { - "nonce": 1, - "code": "0x7f6001600055620100006000f300000000000000000000000000000000000000006000526000600c60006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xded801e9b63939db16c75751ca035243294ffb28", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json b/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json deleted file mode 100644 index cd6d919e5..000000000 --- a/crates/mega-differential/scenarios/eest/test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create2_failed_deposit_refunds_storage_state_gas_fork_Amsterdam_state_test_fail_mode_oog_deposit_slots_3", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x7d9ccb76a7972109192aceb974da5bea7e4eb38f": { - "nonce": 1, - "code": "0x7f600160005560026001556003600255620100006000f3000000000000000000006000526000601660006000f5600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x7d9ccb76a7972109192aceb974da5bea7e4eb38f", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json deleted file mode 100644 index 7f33a9a01..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_from_reservoir", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x126f16ee09ef8508c23bc5dd7205236eefcd2317": { - "balance": "0x01" - }, - "0x4c162f0a55391f16b0d28bad275badc55f8b4882": { - "nonce": 1, - "code": "0x60006000600060006000738249de02b4017aec8639b3601fc73ca713d5c85162089685f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8249de02b4017aec8639b3601fc73ca713d5c851": { - "nonce": 1, - "code": "0x7f600062070f605260006000f3000000000000000000000000000000000000000060005260006000600c60006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4c162f0a55391f16b0d28bad275badc55f8b4882", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json deleted file mode 100644 index 9f324b6f9..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_charge_spills_from_gas_left", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x126f16ee09ef8508c23bc5dd7205236eefcd2317": { - "balance": "0x01" - }, - "0x4c162f0a55391f16b0d28bad275badc55f8b4882": { - "nonce": 1, - "code": "0x60006000600060006000738249de02b4017aec8639b3601fc73ca713d5c85162089685f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8249de02b4017aec8639b3601fc73ca713d5c851": { - "nonce": 1, - "code": "0x7f600062070f605260006000f3000000000000000000000000000000000000000060005260006000600c60006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4c162f0a55391f16b0d28bad275badc55f8b4882", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json deleted file mode 100644 index b8864f98c..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_from_reservoir", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4637a0e95b0259c6fdd8377b35caba897a9c43ed": { - "nonce": 1, - "code": "0x7f600062070f605260006000f300000000000000000000000000000000000000006000526000600c60006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x61cadd8e8bf6a11d86ef8ce44fab9396d1897134": { - "balance": "0x01" - }, - "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d": { - "nonce": 1, - "code": "0x60006000600060006000734637a0e95b0259c6fdd8377b35caba897a9c43ed62089682f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json b/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json deleted file mode 100644 index bae60e917..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_create_account_charge_reduces_child_gas_fork_Amsterdam_create_opcode_CREATE_state_test_charge_spills_from_gas_left", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4637a0e95b0259c6fdd8377b35caba897a9c43ed": { - "nonce": 1, - "code": "0x7f600062070f605260006000f300000000000000000000000000000000000000006000526000600c60006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x61cadd8e8bf6a11d86ef8ce44fab9396d1897134": { - "balance": "0x01" - }, - "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d": { - "nonce": 1, - "code": "0x60006000600060006000734637a0e95b0259c6fdd8377b35caba897a9c43ed62089682f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb14608bbbfbeebed302c359fee5af88ead9d3c8d", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json deleted file mode 100644 index b53abd84b..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_existing_account", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x27d27f776c2fa12c4500bc1cc2526c872253fa86": { - "balance": "0x01" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { - "nonce": 1, - "code": "0x600060005260006000600160006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json deleted file mode 100644 index e26661a73..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE2_state_test_new_account", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { - "nonce": 1, - "code": "0x600060005260006000600160006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json deleted file mode 100644 index 5d77984da..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_existing_account", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x08690f601113d9f3d72976b307ee0bc961d897c0": { - "nonce": 1, - "code": "0x60006000526000600160006000f011600055" - }, - "0x1ef7073e8d0ab897fbc7c049d64b3b7526690e16": { - "balance": "0x01" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json b/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json deleted file mode 100644 index 9bd7de95c..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_account_creation_charge_fork_Amsterdam_create_opcode_CREATE_state_test_new_account", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x08690f601113d9f3d72976b307ee0bc961d897c0": { - "nonce": 1, - "code": "0x60006000526000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 372ebe958..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_charges_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_charges_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x08690f601113d9f3d72976b307ee0bc961d897c0": { - "nonce": 1, - "code": "0x60006000526000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json deleted file mode 100644 index 84abf7121..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_initcode_halt", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6eda05b2a84f3df765d26677e5f704a8f971339d": { - "nonce": 1, - "code": "0x6000600060006000600073c62643632aeea6e7020f95f73cbb708dd2066893623bd177f1" - }, - "0xc62643632aeea6e7020f95f73cbb708dd2066893": { - "nonce": 1, - "code": "0x7ffe000000000000000000000000000000000000000000000000000000000000006000526000600160006000f5506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6eda05b2a84f3df765d26677e5f704a8f971339d", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json deleted file mode 100644 index d4dde5d77..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test_invalid_prefix", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x82e020d72434259dc21dc51591598ea7bf43319c": { - "nonce": 1, - "code": "0x7f60ef60005360016000f3000000000000000000000000000000000000000000006000526000600a60006000f5506001600055" - }, - "0xc08db6086f8b0f2e1c32e65ee46c4696cca5b299": { - "nonce": 1, - "code": "0x600060006000600060007382e020d72434259dc21dc51591598ea7bf43319c623bd177f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc08db6086f8b0f2e1c32e65ee46c4696cca5b299", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json deleted file mode 100644 index 18e108d5b..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_initcode_halt", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6e3653822cd4eb3e013593e9968d22d625125d48": { - "nonce": 1, - "code": "0x6000600060006000600073de840839cfd1cd4491421a12838f89414c01295d623bd174f1" - }, - "0xde840839cfd1cd4491421a12838f89414c01295d": { - "nonce": 1, - "code": "0x7ffe00000000000000000000000000000000000000000000000000000000000000600052600160006000f0506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6e3653822cd4eb3e013593e9968d22d625125d48", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json b/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json deleted file mode 100644 index a52e00477..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_child_halt_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test_invalid_prefix", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0992b6ed03a0ae71e10dcf76ea43ced6d28d4a88": { - "nonce": 1, - "code": "0x7f60ef60005360016000f300000000000000000000000000000000000000000000600052600a60006000f0506001600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe2888c6dd9f79a6f346c5ec4bf813bdbcef34053": { - "nonce": 1, - "code": "0x60006000600060006000730992b6ed03a0ae71e10dcf76ea43ced6d28d4a88623bd174f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe2888c6dd9f79a6f346c5ec4bf813bdbcef34053", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json deleted file mode 100644 index 002c87369..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5e2990598185fccd42e7e4568d91adc054a5f5c4": { - "nonce": 1, - "code": "0x6000600060006000600073f87b7124cc48c89c8922004bafdd9354b6ac2a13623bd177f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf87b7124cc48c89c8922004bafdd9354b6ac2a13": { - "nonce": 1, - "code": "0x7f620100016000f3000000000000000000000000000000000000000000000000006000526000600760006000f5506001600055" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5e2990598185fccd42e7e4568d91adc054a5f5c4", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json deleted file mode 100644 index 898662cbb..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_code_deposit_oog_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x13ae54b3ad54c77e91d57822730ac94f7e6ff1f2": { - "nonce": 1, - "code": "0x6000600060006000600073ade9e3ac1853995069340b550d3b394ef9deac29623bd174f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xade9e3ac1853995069340b550d3b394ef9deac29": { - "nonce": 1, - "code": "0x7f620100016000f300000000000000000000000000000000000000000000000000600052600760006000f0506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x13ae54b3ad54c77e91d57822730ac94f7e6ff1f2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json deleted file mode 100644 index 5d9962269..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x133bf0f549d849e7897b57aeb721f9157c7cd744": { - "nonce": 1, - "code": "0x60006000526000600160006000f5506001600055" - }, - "0x19f9a3c049a708223f7143e6c0a0b76069210762": { - "nonce": 1, - "code": "0x6000600060006000600073133bf0f549d849e7897b57aeb721f9157c7cd744623bd177f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe177168a6ff286ea8adfe3890c3e3d6cd090226f": { - "nonce": 1, - "code": "0x00" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x19f9a3c049a708223f7143e6c0a0b76069210762", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json deleted file mode 100644 index a2d4cf6c6..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_collision_refunds_state_gas_fork_Amsterdam_create_opcode_CREATE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x46ccd78896bdccd93808b71816d48c6a71337682": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa36ac1a9c6f2a860e9bb73511cbef95a03e2a066": { - "nonce": 1, - "code": "0x6000600052600160006000f0506001600055" - }, - "0xdf1b17863c9ef2d9e7a39f9e41b9ded103bedeb3": { - "nonce": 1, - "code": "0x6000600060006000600073a36ac1a9c6f2a860e9bb73511cbef95a03e2a066623bd174f1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xdf1b17863c9ef2d9e7a39f9e41b9ded103bedeb3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index a40a318cf..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_insufficient_balance_returns_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4d3af333455933fcf46214eb61dd4e57cca6ff1a": { - "nonce": 1, - "code": "0x6000600052600160006001f06000556001600155" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4d3af333455933fcf46214eb61dd4e57cca6ff1a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index c09605f20..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_insufficient_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_insufficient_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf4a71fe68af3cdf3bca2dd99c2ed0ff53d00cc11": { - "nonce": 1, - "code": "0x6000600052600160006000f0600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf4a71fe68af3cdf3bca2dd99c2ed0ff53d00cc11", - "data": "0x", - "value": "0x00", - "gas_limit": 200009252, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json deleted file mode 100644 index 75c81375d..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_no_double_charge_new_account_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_create_no_double_charge_new_account_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x1d52400515dacf7f589ae51dfdff002c4a871027": { - "nonce": 1, - "code": "0x600060006000f0600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xbe93aacae1d2d3fdd3b4904cf99769af5fa65658": { - "nonce": 1, - "code": "0x60006000600060006000731d52400515dacf7f589ae51dfdff002c4a8710276201dcb0f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xbe93aacae1d2d3fdd3b4904cf99769af5fa65658", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json deleted file mode 100644 index 3e5d44ad0..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_create_onto_alive_refunds_to_gas_left_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x22af32ea88308575e08326fe58f9af072821cff5": { - "nonce": 1, - "code": "0x6000600060006000f5506001600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x7415c7d4ba6a7ef22f6897b5cca5d378e2407f55": { - "balance": "0x01" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x22af32ea88308575e08326fe58f9af072821cff5", - "data": "0x", - "value": "0x00", - "gas_limit": 200052653, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json deleted file mode 100644 index d13e02c9b..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x968c4210528950e49d96feacc9d8f71ce9dd0cf7": { - "nonce": 1, - "code": "0x6000600060006000600073bad828646eb75618bdd15b07bae5f761e84fe919614e20f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0xbad828646eb75618bdd15b07bae5f761e84fe919": { - "nonce": 1, - "code": "0x600060005260006001601f6000f550" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x968c4210528950e49d96feacc9d8f71ce9dd0cf7", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json deleted file mode 100644 index e6da93a8d..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_during_state_gas_charge_fork_Amsterdam_create_opcode_CREATE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x3f48525deeff730b55641b8c167035de421e00e7": { - "nonce": 1, - "code": "0x6000600060006000600073f45668b615cda17f6291038243534145b19bac7a614e20f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af150" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf45668b615cda17f6291038243534145b19bac7a": { - "nonce": 1, - "code": "0x60006000526001601f6000f050" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x3f48525deeff730b55641b8c167035de421e00e7", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json deleted file mode 100644 index b76ba4a03..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_create_base", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x31a6b906c71e604f8cedfdc8ec34f21fab005a2c": { - "nonce": 1, - "code": "0x6000600060006000f5" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd2f0b0725f3abe88cc7b0f1e95bc1988642b3573": { - "nonce": 1, - "code": "0x600060006000600060007331a6b906c71e604f8cedfdc8ec34f21fab005a2c6202fc1bf1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd2f0b0725f3abe88cc7b0f1e95bc1988642b3573", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json deleted file mode 100644 index 892b30a08..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE2_state_test_oog_on_init_code_word_cost", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8d6e42cd3fc67c90728bd4a8947e5705cdbff1d7": { - "nonce": 1, - "code": "0x60006000600060006000739c4d33c33c1c2feea130a11f2cdfa1bee80056b16202fc2ff1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0x9c4d33c33c1c2feea130a11f2cdfa1bee80056b1": { - "nonce": 1, - "code": "0x60006000526000602060006000f5" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8d6e42cd3fc67c90728bd4a8947e5705cdbff1d7", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json deleted file mode 100644 index 662633f45..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_create_base", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x04b758daed4e31b9762bcc4f63266c1ddfd82804": { - "nonce": 1, - "code": "0x6000600060006000600073a01c1b31989a6fdf79d3059ea4b3300591b794d56202fc18f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa01c1b31989a6fdf79d3059ea4b3300591b794d5": { - "nonce": 1, - "code": "0x600060006000f0" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x04b758daed4e31b9762bcc4f63266c1ddfd82804", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json b/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json deleted file mode 100644 index 3754e8a06..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_create_oog_reservoir_inflation_detection_fork_Amsterdam_create_opcode_CREATE_state_test_oog_on_init_code_word_cost", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4007a2eaaef732f31a3ba0c270f10d747e338520": { - "nonce": 1, - "code": "0x6000600052602060006000f0" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8236ba8b4225119687d5e3318f1e15d3e4c11418": { - "nonce": 1, - "code": "0x60006000600060006000734007a2eaaef732f31a3ba0c270f10d747e3385206202fc26f1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8236ba8b4225119687d5e3318f1e15d3e4c11418", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 47ff02b97..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_revert_no_code_deposit_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x34be4080fa3a9e9ff22c2ec49e0b403dc385656c": { - "nonce": 1, - "code": "0x7f60006000fd000000000000000000000000000000000000000000000000000000600052600560006000f0600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x34be4080fa3a9e9ff22c2ec49e0b403dc385656c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json deleted file mode 100644 index bcd451c1f..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_stack_depth_state_gas_consumed_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825": { - "nonce": 1, - "code": "0x60006000600060006000305af1506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5f4ac33cc2e2741e10d3378840c7ee0cca5d4825", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json deleted file mode 100644 index b5c1e6325..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_100M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json deleted file mode 100644 index 93b3a583e..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_120M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json deleted file mode 100644 index 6885f9f03..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1G", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json deleted file mode 100644 index 74db00c08..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_1M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json deleted file mode 100644 index a449aac60..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_200M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json deleted file mode 100644 index cfa1015c5..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_300M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json deleted file mode 100644 index bbb9567f5..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_30M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json deleted file mode 100644 index 4b2e8d198..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_36M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json deleted file mode 100644 index 7576a4abd..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_500M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json deleted file mode 100644 index efa9b76a1..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_state_gas_scales_with_cpsb_fork_Amsterdam_state_test_60M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2ee362aadf03068c89e52f09623d640781d902c2": { - "nonce": 1, - "code": "0x6000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2ee362aadf03068c89e52f09623d640781d902c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json deleted file mode 100644 index efc258553..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_with_reservoir_fork_Amsterdam_state_test_create", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x08690f601113d9f3d72976b307ee0bc961d897c0": { - "nonce": 1, - "code": "0x60006000526000600160006000f011600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x08690f601113d9f3d72976b307ee0bc961d897c0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json b/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json deleted file mode 100644 index 50508c687..000000000 --- a/crates/mega-differential/scenarios/eest/test_create_with_reservoir_fork_Amsterdam_state_test_create2.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_create_with_reservoir_fork_Amsterdam_state_test_create2", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xccff01d1005d72551ee2b7b7cd66d52adafa6104": { - "nonce": 1, - "code": "0x600060005260006000600160006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xccff01d1005d72551ee2b7b7cd66d52adafa6104", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json deleted file mode 100644 index 32e0ca0dc..000000000 --- a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_all_frames_succeed", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x25da3158c44fd21895e84d8f3908acf61c089437": { - "nonce": 1, - "code": "0x60006000600160006000335af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xad110f9fa7b6b0f9a9c911e514c0616473e51e39": { - "nonce": 1, - "code": "0x36603758015760016000556001600155600060006000600060007325da3158c44fd21895e84d8f3908acf61c0894375af160025500600f5801565b60006000556000600155005b" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xad110f9fa7b6b0f9a9c911e514c0616473e51e39", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json deleted file mode 100644 index d9aeac58a..000000000 --- a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_middle_reverts_after_clear", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x01096b94dd617fe83942d88670785f010f6a98ba": { - "nonce": 1, - "code": "0x60006000600160006000335af15060006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe76309b881efcefeb092c92c812e5c6ace40764d": { - "nonce": 1, - "code": "0x36603758015760016000556001600155600060006000600060007301096b94dd617fe83942d88670785f010f6a98ba5af160025500600f5801565b60006000556000600155005b" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe76309b881efcefeb092c92c812e5c6ace40764d", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json b/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json deleted file mode 100644 index ffa5bff86..000000000 --- a/crates/mega-differential/scenarios/eest/test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_cross_frame_refund_advance_fork_Amsterdam_state_test_top_level_reverts", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x25da3158c44fd21895e84d8f3908acf61c089437": { - "nonce": 1, - "code": "0x60006000600160006000335af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6ed3b5f3632e4336b73347899b8b5b9da544be20": { - "nonce": 1, - "code": "0x36603b58015760016000556001600155600060006000600060007325da3158c44fd21895e84d8f3908acf61c0894375af160025560006000fd600f5801565b60006000556000600155005b" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6ed3b5f3632e4336b73347899b8b5b9da544be20", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json deleted file mode 100644 index 227f429e9..000000000 --- a/crates/mega-differential/scenarios/eest/test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_delegatecall_child_spill_not_double_charged_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x30f1585a288bca56a03a8e5cc2e12d2ef804b438": { - "nonce": 1, - "code": "0x60016000556002600155600360025560046003556005600455600660055500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfc9b6d6b58b8fe2bb98ab56d76071499dab8db27": { - "nonce": 1, - "code": "0x60006000600060007330f1585a288bca56a03a8e5cc2e12d2ef804b4385af450" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfc9b6d6b58b8fe2bb98ab56d76071499dab8db27", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json deleted file mode 100644 index ef1432512..000000000 --- a/crates/mega-differential/scenarios/eest/test_delegatecall_reservoir_passing_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_delegatecall_reservoir_passing_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x3fcbdf3601e9ce1a3c02ffcc0543e60c55d9548b": { - "nonce": 1, - "code": "0x600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef620186a0f4" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x3fcbdf3601e9ce1a3c02ffcc0543e60c55d9548b", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 4f786017c..000000000 --- a/crates/mega-differential/scenarios/eest/test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_gas_opcode_excludes_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x315988212a396700879340d79c907964ffaf2dd6": { - "nonce": 1, - "code": "0x5a6000556001600055" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x315988212a396700879340d79c907964ffaf2dd6", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json deleted file mode 100644 index 04bf5fcb5..000000000 --- a/crates/mega-differential/scenarios/eest/test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_insufficient_gas_for_sstore_state_cost_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200006776, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json deleted file mode 100644 index d6fd3bd66..000000000 --- a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_intrinsic_execution_gas_exceeds_cap_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json deleted file mode 100644 index 2a4de988f..000000000 --- a/crates/mega-differential/scenarios/eest/test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_intrinsic_execution_gas_exceeds_cap_with_floor_below_cap_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x37f536464af59c8d7358cae965f92cbeadd58dcb": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x37f536464af59c8d7358cae965f92cbeadd58dcb", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json deleted file mode 100644 index ed11d6d93..000000000 --- a/crates/mega-differential/scenarios/eest/test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_intrinsic_within_cap_gas_limit_above_cap_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json deleted file mode 100644 index 699273f03..000000000 --- a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_exact_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x20fcc0916f561c4de94b960c66095b0e3352c689": { - "nonce": 1, - "code": "0x36600060003760006000366000600073fa882ebef47fd1ada1c326c66f97cce6fdbbbffd6201be5bf100" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfa882ebef47fd1ada1c326c66f97cce6fdbbbffd": { - "nonce": 1, - "code": "0x36600060003762c0ffee3660006000f560005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x20fcc0916f561c4de94b960c66095b0e3352c689", - "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json deleted file mode 100644 index 7e46d4a8a..000000000 --- a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE2_state_test_short_one_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xafdada08181d5dbaacf18788b85122aa0d854554": { - "nonce": 1, - "code": "0x36600060003760006000366000600073fa882ebef47fd1ada1c326c66f97cce6fdbbbffd6201be5af100" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfa882ebef47fd1ada1c326c66f97cce6fdbbbffd": { - "nonce": 1, - "code": "0x36600060003762c0ffee3660006000f560005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xafdada08181d5dbaacf18788b85122aa0d854554", - "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json deleted file mode 100644 index 7c10a8b84..000000000 --- a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_exact_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x747c2e276047c0d2b7e6a4d8547efedcdb7f09b5": { - "nonce": 1, - "code": "0x36600060003760006000366000600073fd184434582c1cae53df720d5da5e5374c6c64b962015e58f100" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfd184434582c1cae53df720d5da5e5374c6c64b9": { - "nonce": 1, - "code": "0x3660006000373660006000f060005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x747c2e276047c0d2b7e6a4d8547efedcdb7f09b5", - "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json deleted file mode 100644 index 5982a48f0..000000000 --- a/crates/mega-differential/scenarios/eest/test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_max_initcode_size_gas_metering_via_create_fork_Amsterdam_create_opcode_CREATE_state_test_short_one_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf42013f94f3e0d49fd4ad3240ff668c0284ac29f": { - "nonce": 1, - "code": "0x36600060003760006000366000600073fd184434582c1cae53df720d5da5e5374c6c64b962015e57f100" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfd184434582c1cae53df720d5da5e5374c6c64b9": { - "nonce": 1, - "code": "0x3660006000373660006000f060005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf42013f94f3e0d49fd4ad3240ff668c0284ac29f", - "data": "0x610001600081600b8239f3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json deleted file mode 100644 index 695ea238d..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_calls_reservoir_passing_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_nested_calls_reservoir_passing_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0ecc504ac0640d87e828e30ed14b041bb6f1a48d": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef62030d40f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5829db418ba6428a4817553e0a237b3d88ae9424": { - "nonce": 1, - "code": "0x60006000600060006000730ecc504ac0640d87e828e30ed14b041bb6f1a48d620493e0f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5829db418ba6428a4817553e0a237b3d88ae9424", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 12603cdd7..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_nested_create_code_deposit_cannot_borrow_parent_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x981f21093384d81af297acec122f1e6758d1e1f4": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000000000000060016000f36000526005601b6000f050" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x981f21093384d81af297acec122f1e6758d1e1f4", - "data": "0x", - "value": "0x00", - "gas_limit": 200052851, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json deleted file mode 100644 index 47ee87c28..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x053cb57511a8f413073b9c1d4edef9d4debcd928": { - "nonce": 1, - "code": "0x6000600060006000600073c5ecec6304ce12928c6a67cabb08d256a006c5315af15000" - }, - "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21": { - "nonce": 1, - "code": "0x60006000600060006000737158469335c38bc1d1a236bc9f2ba5f3027bd6075af15000" - }, - "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5468c4cf3cebdc08565e2731b0678f8bdd0428e2": { - "nonce": 1, - "code": "0x60006000600060006000735e213dd0505c705179c3ca8f26174dc4c67f5da75af15000" - }, - "0x569044e2f76aae923eacb369c31afbe3358095b5": { - "nonce": 1, - "code": "0x6000600060006000600073053cb57511a8f413073b9c1d4edef9d4debcd9285af15000" - }, - "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { - "nonce": 1, - "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" - }, - "0x5e213dd0505c705179c3ca8f26174dc4c67f5da7": { - "nonce": 1, - "code": "0x6000600060006000600073e0e7ff869e4a073bf8b9a266cd40d5e5504176845af15000" - }, - "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { - "nonce": 1, - "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" - }, - "0x7158469335c38bc1d1a236bc9f2ba5f3027bd607": { - "nonce": 1, - "code": "0x60006000600060006000735f4eeb3c9c7db8445457a762ccaaf3924d0a40345af15000" - }, - "0x9fb2a61c28e965b67bad0f1a265da1d7beda1d62": { - "nonce": 1, - "code": "0x6000600060006000600073569044e2f76aae923eacb369c31afbe3358095b55af15000" - }, - "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { - "nonce": 1, - "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xc5ecec6304ce12928c6a67cabb08d256a006c531": { - "nonce": 1, - "code": "0x6000600060006000600073113cd9a7a08ad3edbb3dfab7696233f53cc98d215af15000" - }, - "0xe0e7ff869e4a073bf8b9a266cd40d5e550417684": { - "nonce": 1, - "code": "0x60006000600060006000739fb2a61c28e965b67bad0f1a265da1d7beda1d625af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5468c4cf3cebdc08565e2731b0678f8bdd0428e2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json deleted file mode 100644 index 221f5d924..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0003ba5491594ab7b42b572e036b869fef6719fb": { - "nonce": 1, - "code": "0x6000600060006000600073667731961164968220cf97f105947de66aa5bfd55af15000" - }, - "0x1af1a7588cff04d361cd1bcf9076594a60b983f8": { - "nonce": 1, - "code": "0x60006000600060006000734595d106902775aaf3c152ca65045b042cd0357d5af15000" - }, - "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { - "nonce": 1, - "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" - }, - "0x4066f1f675e6c984d91709c3dbf02b7b500b0ff5": { - "nonce": 1, - "code": "0x60006000600060006000737cb7da08ac424947a7b49f71861a41c7b5fd05765af15000" - }, - "0x4595d106902775aaf3c152ca65045b042cd0357d": { - "nonce": 1, - "code": "0x6000600060006000600073b3fcedac2ed3a5eb6849401ada6a49a573ddaa6a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x667731961164968220cf97f105947de66aa5bfd5": { - "nonce": 1, - "code": "0x6000600060006000600073e00a48bf2af4aee51c02c8e53c15de9a450db3e85af15000" - }, - "0x7cb7da08ac424947a7b49f71861a41c7b5fd0576": { - "nonce": 1, - "code": "0x60006000600060006000731af1a7588cff04d361cd1bcf9076594a60b983f85af15000" - }, - "0x9825e48625413478150ba42de46b5ae120c0ab7a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a": { - "nonce": 1, - "code": "0x6000600060006000600073e7b23f996831b470eb579585972f4608ddb46ff55af15000" - }, - "0xe00a48bf2af4aee51c02c8e53c15de9a450db3e8": { - "nonce": 1, - "code": "0x60006000600060006000734066f1f675e6c984d91709c3dbf02b7b500b0ff55af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xe7b23f996831b470eb579585972f4608ddb46ff5": { - "nonce": 1, - "code": "0x6000600060006000600073fc0a156d0f29a14b2d217623d0e7f13ab70eb2d15af15000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { - "nonce": 1, - "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0003ba5491594ab7b42b572e036b869fef6719fb", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json deleted file mode 100644 index 7d4e6e671..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0551d99e64f665f96a535ea329b0b7730b256f84": { - "nonce": 1, - "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" - }, - "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { - "nonce": 1, - "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" - }, - "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { - "nonce": 1, - "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x440df445bc999c4a7ad434728514b18d49af1f76": { - "nonce": 1, - "code": "0x60006000600060006000737b9a4ebbbcaa3b5ed869adf6cb131a885347deb95af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x595ad51569abfc814f56e2025df8465bc7c96daa": { - "nonce": 1, - "code": "0x6000600060006000600073f840c69a775450661d3faa91f9dc8677eb0bf5425af15000" - }, - "0x768599d3d827a10afdd46c7ee74e043cb491b3bb": { - "nonce": 1, - "code": "0x6000600060006000600073440df445bc999c4a7ad434728514b18d49af1f765af15000" - }, - "0x7a3f53d68397cf003560f9713a2452974812fd5f": { - "nonce": 1, - "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" - }, - "0x7b9a4ebbbcaa3b5ed869adf6cb131a885347deb9": { - "nonce": 1, - "code": "0x6000600060006000600073595ad51569abfc814f56e2025df8465bc7c96daa5af15000" - }, - "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { - "nonce": 1, - "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" - }, - "0x84946fbc7842859adbd3644faa294e443c0232df": { - "nonce": 1, - "code": "0x60006000600060006000737a3f53d68397cf003560f9713a2452974812fd5f5af15000" - }, - "0xd6d787820fcc0f2b5b345d2b4026cc455431413b": { - "nonce": 1, - "code": "0x600060006000600060007384946fbc7842859adbd3644faa294e443c0232df5af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf840c69a775450661d3faa91f9dc8677eb0bf542": { - "nonce": 1, - "code": "0x6000600060006000600073d6d787820fcc0f2b5b345d2b4026cc455431413b5af15000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x768599d3d827a10afdd46c7ee74e043cb491b3bb", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json deleted file mode 100644 index 7aa94188e..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { - "nonce": 1, - "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" - }, - "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { - "nonce": 1, - "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" - }, - "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { - "nonce": 1, - "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json deleted file mode 100644 index 4c0c6df5d..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { - "nonce": 1, - "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9825e48625413478150ba42de46b5ae120c0ab7a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { - "nonce": 1, - "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json deleted file mode 100644 index 344458457..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_1_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0551d99e64f665f96a535ea329b0b7730b256f84": { - "nonce": 1, - "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" - }, - "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { - "nonce": 1, - "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { - "nonce": 1, - "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json deleted file mode 100644 index ec5c26b55..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21": { - "nonce": 1, - "code": "0x60006000600060006000737158469335c38bc1d1a236bc9f2ba5f3027bd6075af15000" - }, - "0x275b427d93275ee67c7b0bf492b0aed6ed9ebed7": { - "nonce": 1, - "code": "0x00" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5df29f4015e6cd5f73601a6fba279a1ad6218264": { - "nonce": 1, - "code": "0x6000600060006000600073b7eeb232e05aa3e41916fac8497f5b739963f33f5af15000" - }, - "0x5f4eeb3c9c7db8445457a762ccaaf3924d0a4034": { - "nonce": 1, - "code": "0x60006000600060006000735df29f4015e6cd5f73601a6fba279a1ad62182645af15000" - }, - "0x7158469335c38bc1d1a236bc9f2ba5f3027bd607": { - "nonce": 1, - "code": "0x60006000600060006000735f4eeb3c9c7db8445457a762ccaaf3924d0a40345af15000" - }, - "0xb7eeb232e05aa3e41916fac8497f5b739963f33f": { - "nonce": 1, - "code": "0x600060006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x113cd9a7a08ad3edbb3dfab7696233f53cc98d21", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json deleted file mode 100644 index b6211e441..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2e238794726a102aa57b55c4feb5b129ceda4f88": { - "nonce": 1, - "code": "0x60006000600060006000739825e48625413478150ba42de46b5ae120c0ab7a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9825e48625413478150ba42de46b5ae120c0ab7a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f0506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a": { - "nonce": 1, - "code": "0x6000600060006000600073e7b23f996831b470eb579585972f4608ddb46ff55af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xe7b23f996831b470eb579585972f4608ddb46ff5": { - "nonce": 1, - "code": "0x6000600060006000600073fc0a156d0f29a14b2d217623d0e7f13ab70eb2d15af15000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfc0a156d0f29a14b2d217623d0e7f13ab70eb2d1": { - "nonce": 1, - "code": "0x60006000600060006000732e238794726a102aa57b55c4feb5b129ceda4f885af15000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb3fcedac2ed3a5eb6849401ada6a49a573ddaa6a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json deleted file mode 100644 index 2626d9016..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_3_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0551d99e64f665f96a535ea329b0b7730b256f84": { - "nonce": 1, - "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" - }, - "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { - "nonce": 1, - "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" - }, - "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { - "nonce": 1, - "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x7a3f53d68397cf003560f9713a2452974812fd5f": { - "nonce": 1, - "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" - }, - "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { - "nonce": 1, - "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x7a3f53d68397cf003560f9713a2452974812fd5f", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json deleted file mode 100644 index a9d8f43ce..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { - "nonce": 1, - "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" - }, - "0x125a27e3431a378dd32b805d1eb035ea603af917": { - "nonce": 1, - "code": "0x6000600060006000600073af98241cb31fccd9afe08ba6e94cf71d017875805af15000" - }, - "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { - "nonce": 1, - "code": "0x600060006000f05000" - }, - "0x2e4775e29f96e843a5f9ce77698ab8877763aefe": { - "nonce": 1, - "code": "0x600060006000600060007368cd2fbe38167708072637d53fb335f4d292ab2f5af15000" - }, - "0x340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce": { - "nonce": 1, - "code": "0x6000600060006000600073d8e4f3ab4a9131945355462a94714b714da61ca45af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x68cd2fbe38167708072637d53fb335f4d292ab2f": { - "nonce": 1, - "code": "0x6000600060006000600073ea276b22eb502fd9743053ec1e2a9fee96dc49175af15000" - }, - "0x86715d19d83c63b8f13ce14db52ed6bd140c723e": { - "nonce": 1, - "code": "0x6000600060006000600073125a27e3431a378dd32b805d1eb035ea603af9175af15000" - }, - "0xaa08db400382913932b5337b5b9f58083cdf9923": { - "nonce": 1, - "code": "0x00" - }, - "0xaf98241cb31fccd9afe08ba6e94cf71d01787580": { - "nonce": 1, - "code": "0x6000600060006000600073d95df29596ec5594256fd86c85bfcfecd8f9dd7e5af15000" - }, - "0xd8e4f3ab4a9131945355462a94714b714da61ca4": { - "nonce": 1, - "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af15000" - }, - "0xd95df29596ec5594256fd86c85bfcfecd8f9dd7e": { - "nonce": 1, - "code": "0x60006000600060006000732e4775e29f96e843a5f9ce77698ab8877763aefe5af15000" - }, - "0xd9e23acd2ad6cd9fab5c78ba1dc86f1796036070": { - "nonce": 1, - "code": "0x600060006000600060007386715d19d83c63b8f13ce14db52ed6bd140c723e5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xea276b22eb502fd9743053ec1e2a9fee96dc4917": { - "nonce": 1, - "code": "0x6000600060006000600073340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce5af15000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd9e23acd2ad6cd9fab5c78ba1dc86f1796036070", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json deleted file mode 100644 index 337f5576d..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { - "nonce": 1, - "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x517a726f8d693dc4aed7c032b5966211f5bd5e70": { - "nonce": 1, - "code": "0x6000600060006000600073744386689b43c80ac4d335c3783af4b06c46cf075af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x525b7c655228cb70c7fef4a7968323521a663f04": { - "nonce": 1, - "code": "0x6000600060006000600073bae123dc020b26f6257c336fa1f4e7f2a5a5fccf5af15000" - }, - "0x54041e3d292437d1643b29754e9e083f1768c00e": { - "nonce": 1, - "code": "0x6000600060006000600073c1854be81610463a79ca04b92ea63ba968f5af725af15000" - }, - "0x602994eb359e43b5bfc97fcf003be7d96bfd9691": { - "nonce": 1, - "code": "0x6000600060006000600073b6f864bf21a2bc9338850eb9af60d734287ea64d5af15000" - }, - "0x61e2c37aa43a458bc7458798179de42f1904d57a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" - }, - "0x744386689b43c80ac4d335c3783af4b06c46cf07": { - "nonce": 1, - "code": "0x600060006000600060007354041e3d292437d1643b29754e9e083f1768c00e5af15000" - }, - "0xb6f864bf21a2bc9338850eb9af60d734287ea64d": { - "nonce": 1, - "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af15000" - }, - "0xbae123dc020b26f6257c336fa1f4e7f2a5a5fccf": { - "nonce": 1, - "code": "0x6000600060006000600073dc3b4e24fbaa72dabbaf79304995970c83d952285af15000" - }, - "0xc1854be81610463a79ca04b92ea63ba968f5af72": { - "nonce": 1, - "code": "0x6000600060006000600073525b7c655228cb70c7fef4a7968323521a663f045af15000" - }, - "0xdc3b4e24fbaa72dabbaf79304995970c83d95228": { - "nonce": 1, - "code": "0x6000600060006000600073f039829f33edd9832f8c02f2c7bb8e7fa5b2a9bc5af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf039829f33edd9832f8c02f2c7bb8e7fa5b2a9bc": { - "nonce": 1, - "code": "0x6000600060006000600073602994eb359e43b5bfc97fcf003be7d96bfd96915af15000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x517a726f8d693dc4aed7c032b5966211f5bd5e70", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json deleted file mode 100644 index 7d8d5aad5..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_10_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2774ad7d5234681b2c0d65b2fca85ab39b9b91a1": { - "nonce": 1, - "code": "0x6000600060006000600073833905ba8cd7ad5c1c98476f86c0628be148ebea5af15000" - }, - "0x2b31bf922a1db1218ec41b676821bc34ae783281": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" - }, - "0x382dadf608e6ac15017cce80c1c608e96a8f3788": { - "nonce": 1, - "code": "0x6000600060006000600073d8ccf52b85eb2c7c59c1792ad1021d390120d79c5af15000" - }, - "0x4d92182b5a4d51e480cba616caa0a496f4efbda8": { - "nonce": 1, - "code": "0x6000600060006000600073c8790b08292677361b19ed416303aadfcfefc4db5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5d5da279fe0de991d67ada4beee9f3362bec2ead": { - "nonce": 1, - "code": "0x60006000600060006000734d92182b5a4d51e480cba616caa0a496f4efbda85af15000" - }, - "0x833905ba8cd7ad5c1c98476f86c0628be148ebea": { - "nonce": 1, - "code": "0x60006000600060006000735d5da279fe0de991d67ada4beee9f3362bec2ead5af15000" - }, - "0x8753f8aba8a5de40497bda3e9360642df4b6da98": { - "nonce": 1, - "code": "0x6000600060006000600073382dadf608e6ac15017cce80c1c608e96a8f37885af15000" - }, - "0xb1f4479dbaa6052a0991a02e1a0e970db0863cc9": { - "nonce": 1, - "code": "0x60006000600060006000732774ad7d5234681b2c0d65b2fca85ab39b9b91a15af15000" - }, - "0xc8790b08292677361b19ed416303aadfcfefc4db": { - "nonce": 1, - "code": "0x60006000600060006000738753f8aba8a5de40497bda3e9360642df4b6da985af15000" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xd8ccf52b85eb2c7c59c1792ad1021d390120d79c": { - "nonce": 1, - "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xff091f7082c73c848af84a40e617ae2eb9fa66c2": { - "nonce": 1, - "code": "0x6000600060006000600073b1f4479dbaa6052a0991a02e1a0e970db0863cc95af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xff091f7082c73c848af84a40e617ae2eb9fa66c2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json deleted file mode 100644 index 4d76e5faf..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { - "nonce": 1, - "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" - }, - "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { - "nonce": 1, - "code": "0x600060006000f05000" - }, - "0x4b3b27f06c23f88cdef683e65080aa2a6d5fa6bd": { - "nonce": 1, - "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xaa08db400382913932b5337b5b9f58083cdf9923": { - "nonce": 1, - "code": "0x00" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4b3b27f06c23f88cdef683e65080aa2a6d5fa6bd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json deleted file mode 100644 index 1afc1d141..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { - "nonce": 1, - "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x61e2c37aa43a458bc7458798179de42f1904d57a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" - }, - "0xd365ba83e1720b20c9fc0919ac037909751d59f9": { - "nonce": 1, - "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd365ba83e1720b20c9fc0919ac037909751d59f9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json deleted file mode 100644 index 4dd5f3780..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_1_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2b31bf922a1db1218ec41b676821bc34ae783281": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc31d99b57607343a1d2306a80999bdcd583ad294": { - "nonce": 1, - "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc31d99b57607343a1d2306a80999bdcd583ad294", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json deleted file mode 100644 index 84b73f1f4..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_collision", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d": { - "nonce": 1, - "code": "0x60006000600060006000731bee0f1a2245ddb9ae67719bf3028506dffa5f625af15000" - }, - "0x1bee0f1a2245ddb9ae67719bf3028506dffa5f62": { - "nonce": 1, - "code": "0x600060006000f05000" - }, - "0x310e21851b068ba17ba59a9c71215d510663114a": { - "nonce": 1, - "code": "0x6000600060006000600073340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x340d371051bfa2a2a07b2bc3fd29e8c7c7cc87ce": { - "nonce": 1, - "code": "0x6000600060006000600073d8e4f3ab4a9131945355462a94714b714da61ca45af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xaa08db400382913932b5337b5b9f58083cdf9923": { - "nonce": 1, - "code": "0x00" - }, - "0xd8e4f3ab4a9131945355462a94714b714da61ca4": { - "nonce": 1, - "code": "0x6000600060006000600073104aa8a37df8db94b6b29e7b5b2c781e4c4ae06d5af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x310e21851b068ba17ba59a9c71215d510663114a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json deleted file mode 100644 index 8b1d39793..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_create_initcode_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x135077524dfdfd4e903f978f63df5566a8e6f9fb": { - "nonce": 1, - "code": "0x600060006000600060007361e2c37aa43a458bc7458798179de42f1904d57a5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x602994eb359e43b5bfc97fcf003be7d96bfd9691": { - "nonce": 1, - "code": "0x6000600060006000600073b6f864bf21a2bc9338850eb9af60d734287ea64d5af15000" - }, - "0x61e2c37aa43a458bc7458798179de42f1904d57a": { - "nonce": 1, - "code": "0x6000517affffffffffffffffffffffffffffffffffffffffffffffffffffff167f60006000fd00000000000000000000000000000000000000000000000000000017600052600560006000f05000" - }, - "0xb16e09425098ead08d00ebaeb1ef519a2dc624be": { - "nonce": 1, - "code": "0x6000600060006000600073602994eb359e43b5bfc97fcf003be7d96bfd96915af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0xb6f864bf21a2bc9338850eb9af60d734287ea64d": { - "nonce": 1, - "code": "0x6000600060006000600073135077524dfdfd4e903f978f63df5566a8e6f9fb5af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb16e09425098ead08d00ebaeb1ef519a2dc624be", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json b/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json deleted file mode 100644 index b6ecfec03..000000000 --- a/crates/mega-differential/scenarios/eest/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_top_depth_3_sstore_restoration", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2b31bf922a1db1218ec41b676821bc34ae783281": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15000" - }, - "0x2bc9cd0edff891c3eb19c8c940ba4d1fb7189a0e": { - "nonce": 1, - "code": "0x6000600060006000600073382dadf608e6ac15017cce80c1c608e96a8f37885af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" - }, - "0x382dadf608e6ac15017cce80c1c608e96a8f3788": { - "nonce": 1, - "code": "0x6000600060006000600073d8ccf52b85eb2c7c59c1792ad1021d390120d79c5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xd8ccf52b85eb2c7c59c1792ad1021d390120d79c": { - "nonce": 1, - "code": "0x60006000600060006000732b31bf922a1db1218ec41b676821bc34ae7832815af15000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2bc9cd0edff891c3eb19c8c940ba4d1fb7189a0e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json deleted file mode 100644 index 8ff090e41..000000000 --- a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_insufficient_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xab5aee4f8102143b17e076232012c5ce8624e0da": { - "nonce": 1, - "code": "0x6000600060006000600073c3cd8b141c1d255b786f6686191e43f748413001612ef6f1" - }, - "0xc3cd8b141c1d255b786f6686191e43f748413001": { - "nonce": 1, - "code": "0x6000600160006000f5" - }, - "0xe7d8cee81bd8c1979af7d7812c78228065a8dee5": { - "balance": "0x01" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xab5aee4f8102143b17e076232012c5ce8624e0da", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json deleted file mode 100644 index 6b21d5a2c..000000000 --- a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE2_state_test_sufficient_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x7d9ec00f3eed8ede627e8e8da26bd607eaba841c": { - "nonce": 1, - "code": "0x6000600060006000600073c3cd8b141c1d255b786f6686191e43f748413001612ef7f1" - }, - "0xc3cd8b141c1d255b786f6686191e43f748413001": { - "nonce": 1, - "code": "0x6000600160006000f5" - }, - "0xe7d8cee81bd8c1979af7d7812c78228065a8dee5": { - "balance": "0x01" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x7d9ec00f3eed8ede627e8e8da26bd607eaba841c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json deleted file mode 100644 index 57d218626..000000000 --- a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_insufficient_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2a61375388141559b52e11dc3cece66a3e4a3cf6": { - "balance": "0x01" - }, - "0x45c43c77ccd9b82b494c776392e722ab2529b9b5": { - "nonce": 1, - "code": "0x6000600060006000600073853d5d321bb83315f6b3dafce43ec7e4157d4980612eedf1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x853d5d321bb83315f6b3dafce43ec7e4157d4980": { - "nonce": 1, - "code": "0x600160006000f0" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x45c43c77ccd9b82b494c776392e722ab2529b9b5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json b/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json deleted file mode 100644 index d8640fbdc..000000000 --- a/crates/mega-differential/scenarios/eest/test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "test_no_account_charge_on_existing_account_fork_Amsterdam_create_opcode_CREATE_state_test_sufficient_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2a61375388141559b52e11dc3cece66a3e4a3cf6": { - "balance": "0x01" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x853d5d321bb83315f6b3dafce43ec7e4157d4980": { - "nonce": 1, - "code": "0x600160006000f0" - }, - "0xed4eefcb238f28b838aba2f0f6a73e0b676464ba": { - "nonce": 1, - "code": "0x6000600060006000600073853d5d321bb83315f6b3dafce43ec7e4157d4980612eeef1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xed4eefcb238f28b838aba2f0f6a73e0b676464ba", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json deleted file mode 100644 index 6016c4c00..000000000 --- a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_halt", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xefb126b3e865f609c6dd9a82c52e119a60884446": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000000000006001600055fe6000526006601a6000f06000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xefb126b3e865f609c6dd9a82c52e119a60884446", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json deleted file mode 100644 index 0447b473a..000000000 --- a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_no_reservoir_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5b735edc5956f051f66b55cfb3e20b7899aa8043": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000600160005560006000fd600052600a60166000f06000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5b735edc5956f051f66b55cfb3e20b7899aa8043", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json deleted file mode 100644 index 918f72df1..000000000 --- a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_halt", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xefb126b3e865f609c6dd9a82c52e119a60884446": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000000000006001600055fe6000526006601a6000f06000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xefb126b3e865f609c6dd9a82c52e119a60884446", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json b/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json deleted file mode 100644 index 2df149851..000000000 --- a/crates/mega-differential/scenarios/eest/test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_parent_state_gas_after_child_failure_fork_Amsterdam_state_test_with_reservoir_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5b735edc5956f051f66b55cfb3e20b7899aa8043": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000600160005560006000fd600052600a60166000f06000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5b735edc5956f051f66b55cfb3e20b7899aa8043", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json deleted file mode 100644 index a5fe0bcc3..000000000 --- a/crates/mega-differential/scenarios/eest/test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "test_partially_discharged_advance_revoked_by_halt_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x53ba30867bbd50d8066077dd79b1dbad087115f0": { - "nonce": 1, - "code": "0x6000600060006000600073e5a5932a96a75fec7ac2d96786731376406feaca620927c0f16000556001600155" - }, - "0x96336043ed535f3143be4c5d61fa845747280bc0": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005560006000600060006001335af15000" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xe5a5932a96a75fec7ac2d96786731376406feaca": { - "nonce": 1, - "code": "0x34603558015760016000556001600155600060006000600060007396336043ed535f3143be4c5d61fa845747280bc05af150fe60315801565b6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af15060006000556000600155005b" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x53ba30867bbd50d8066077dd79b1dbad087115f0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json deleted file mode 100644 index 7430f4581..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_100M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json deleted file mode 100644 index b5a895c1c..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_120M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json deleted file mode 100644 index 2ae543aac..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1G", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json deleted file mode 100644 index 55741a171..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_1M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json deleted file mode 100644 index 1a07a8c2a..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_200M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json deleted file mode 100644 index b08727d50..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_300M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json deleted file mode 100644 index e171d934a..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_30M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json deleted file mode 100644 index fb9b4b668..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_36M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json deleted file mode 100644 index 3f7348d13..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_500M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json deleted file mode 100644 index cb8305265..000000000 --- a/crates/mega-differential/scenarios/eest/test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_pricing_at_various_gas_limits_fork_Amsterdam_state_test_60M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index d52971f37..000000000 --- a/crates/mega-differential/scenarios/eest/test_refund_cap_includes_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_refund_cap_includes_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 4feeb7e7e..000000000 --- a/crates/mega-differential/scenarios/eest/test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_refund_with_reservoir_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json deleted file mode 100644 index 3fcd3bb5c..000000000 --- a/crates/mega-differential/scenarios/eest/test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_repeated_create_same_code_charges_each_account_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xff5b195b5a743a15a4dd8bef51decbc40f020764": { - "nonce": 1, - "code": "0x7f00000000000000000000000000000000000000000000000000000060016000f36000525a6020526005601b6000f0505a6040526005601b6000f0505a60605260605160405103604051602051030360005500" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xff5b195b5a743a15a4dd8bef51decbc40f020764", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json deleted file mode 100644 index 46c270440..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_above_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json deleted file mode 100644 index ea9d22422..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_at_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json b/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json deleted file mode 100644 index f83d6ff7b..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_reservoir_allocation_boundary_fork_Amsterdam_state_test_below_cap", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json deleted file mode 100644 index 717a16fe6..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_reservoir_restored_after_child_full_drain_and_revert_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x97af882916b3473f0f8acdad4deb404d8e0b49e7": { - "nonce": 1, - "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506001600055" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x97af882916b3473f0f8acdad4deb404d8e0b49e7", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json deleted file mode 100644 index 0de2a0e71..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_reservoir_restored_after_child_spill_and_halt_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8307bcc4c9612d6d1875d2d97edd850986bd253c": { - "nonce": 1, - "code": "0x60016000556001600155fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfb680a2dc482b540884c4a1aed2a7c5ec920a603": { - "nonce": 1, - "code": "0x60006000600060006000738307bcc4c9612d6d1875d2d97edd850986bd253c6207a120f15060016000556001600155" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfb680a2dc482b540884c4a1aed2a7c5ec920a603", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json deleted file mode 100644 index 40f8b92a6..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_reservoir_restored_after_child_spill_and_revert_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9e6ec4eb938269f39fa7f791ef62859b45088d14": { - "nonce": 1, - "code": "0x6001600055600160015560006000fd" - }, - "0xd22f0bd65c9173af0826a2106e3fe6e9248e7b1b": { - "nonce": 1, - "code": "0x60006000600060006000739e6ec4eb938269f39fa7f791ef62859b45088d146207a120f15060016000556001600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd22f0bd65c9173af0826a2106e3fe6e9248e7b1b", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json deleted file mode 100644 index 255e7e38a..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_oog_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_reservoir_returned_on_oog_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9e39d16dc2ae00d8edff0816858346d089a62f19": { - "nonce": 1, - "code": "0x6000600060006000600073ec18af3fb3bbdc8967a4d68bf87b5a58053b4bf26064f1506001600055" - }, - "0xec18af3fb3bbdc8967a4d68bf87b5a58053b4bf2": { - "nonce": 1, - "code": "0xfe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x9e39d16dc2ae00d8edff0816858346d089a62f19", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json deleted file mode 100644 index c3a7c6f1e..000000000 --- a/crates/mega-differential/scenarios/eest/test_reservoir_returned_on_revert_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_reservoir_returned_on_revert_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4391c0c575a2677adfab1a4ddb038238f9dd01f0": { - "nonce": 1, - "code": "0x600060006000600060007343bbb24495f4107ab75aa339644d77b621ec0ee4620186a0f1506001600055" - }, - "0x43bbb24495f4107ab75aa339644d77b621ec0ee4": { - "nonce": 1, - "code": "0x60006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4391c0c575a2677adfab1a4ddb038238f9dd01f0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json deleted file mode 100644 index cb064f11a..000000000 --- a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_1", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { - "nonce": 1, - "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5104e8dfb400fa45528f1939767450df6969319e": { - "nonce": 1, - "code": "0x60006000556000600155600060025560006003556000600455" - }, - "0x7e8dd7bf50aad4bac65ba7009f3a28dc9b5095d6": { - "nonce": 1, - "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45060006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfe8fdcafa1baa1eeb585b46b2aff5d62b454acf0": { - "nonce": 1, - "code": "0x600160005560016001556001600255600160035560016004556000600060006000737e8dd7bf50aad4bac65ba7009f3a28dc9b5095d65af4506001600a556001600b556001600c556001600d556001600e55" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfe8fdcafa1baa1eeb585b46b2aff5d62b454acf0", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json deleted file mode 100644 index 4bf4b6af3..000000000 --- a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_10", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0d6dc1f2d223c764873a5e967ca4fcab4625474d": { - "nonce": 1, - "code": "0x600060006000600073c6ae4344e3c79e9b7300f6cb7cb4e1ea8b6279415af45000" - }, - "0x0e492b88ceca0e87c58a8a7731ec7e27a9f1bc6e": { - "nonce": 1, - "code": "0x6000600060006000730d6dc1f2d223c764873a5e967ca4fcab4625474d5af45000" - }, - "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { - "nonce": 1, - "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" - }, - "0x1df45fb03e8fc6903be1a92bcc784428050513fd": { - "nonce": 1, - "code": "0x60016000556001600155600160025560016003556001600455600060006000600073fa7629b29bab864c06d1ef65a74227e67b6667df5af4506001600a556001600b556001600c556001600d556001600e55" - }, - "0x20cd6b7ba966b9ea9889db4666188fd51ce420f0": { - "nonce": 1, - "code": "0x600060006000600073a6ef999b8ed332f940241c7f92fc3595e557e1eb5af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5104e8dfb400fa45528f1939767450df6969319e": { - "nonce": 1, - "code": "0x60006000556000600155600060025560006003556000600455" - }, - "0x6a01c38003a92aea11a96b08fa300a95f91bd3af": { - "nonce": 1, - "code": "0x6000600060006000738625a9441db50bd8d6e6161957087c2fecbdcdcf5af45000" - }, - "0x8625a9441db50bd8d6e6161957087c2fecbdcdcf": { - "nonce": 1, - "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45000" - }, - "0xa6ef999b8ed332f940241c7f92fc3595e557e1eb": { - "nonce": 1, - "code": "0x600060006000600073daa76ffe2f7b1a667cbfce190f46d90a5ae6dc015af45000" - }, - "0xc1a2f388d50af526c677f1f6a4ad26bc67dcab99": { - "nonce": 1, - "code": "0x6000600060006000730e492b88ceca0e87c58a8a7731ec7e27a9f1bc6e5af45000" - }, - "0xc6ae4344e3c79e9b7300f6cb7cb4e1ea8b627941": { - "nonce": 1, - "code": "0x60006000600060007320cd6b7ba966b9ea9889db4666188fd51ce420f05af45000" - }, - "0xdaa76ffe2f7b1a667cbfce190f46d90a5ae6dc01": { - "nonce": 1, - "code": "0x6000600060006000736a01c38003a92aea11a96b08fa300a95f91bd3af5af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfa7629b29bab864c06d1ef65a74227e67b6667df": { - "nonce": 1, - "code": "0x600060006000600073c1a2f388d50af526c677f1f6a4ad26bc67dcab995af45060006000fd" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x1df45fb03e8fc6903be1a92bcc784428050513fd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json deleted file mode 100644 index 338ceb360..000000000 --- a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_depth_3", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0e6ed2c96e984f585b89f968fdeab37cff439735": { - "nonce": 1, - "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5104e8dfb400fa45528f1939767450df6969319e": { - "nonce": 1, - "code": "0x60006000556000600155600060025560006003556000600455" - }, - "0x6a01c38003a92aea11a96b08fa300a95f91bd3af": { - "nonce": 1, - "code": "0x6000600060006000738625a9441db50bd8d6e6161957087c2fecbdcdcf5af45000" - }, - "0x79d2892fe6487ea2a9fba5e84de7ed71694ed6ec": { - "nonce": 1, - "code": "0x6000600060006000736a01c38003a92aea11a96b08fa300a95f91bd3af5af45060006000fd" - }, - "0x8625a9441db50bd8d6e6161957087c2fecbdcdcf": { - "nonce": 1, - "code": "0x6000600060006000730e6ed2c96e984f585b89f968fdeab37cff4397355af45000" - }, - "0xd7a970dca038fdb56ec2d0b7b36ff3c71eaa1784": { - "nonce": 1, - "code": "0x6001600055600160015560016002556001600355600160045560006000600060007379d2892fe6487ea2a9fba5e84de7ed71694ed6ec5af4506001600a556001600b556001600c556001600d556001600e55" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd7a970dca038fdb56ec2d0b7b36ff3c71eaa1784", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json b/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json deleted file mode 100644 index d057a518e..000000000 --- a/crates/mega-differential/scenarios/eest/test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_revert_discards_descendant_storage_clear_credit_through_depth_fork_Amsterdam_state_test_direct", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5104e8dfb400fa45528f1939767450df6969319e": { - "nonce": 1, - "code": "0x60006000556000600155600060025560006003556000600455" - }, - "0x6f54c4d99a08c1c7e6b8d65b4fd338996e587586": { - "nonce": 1, - "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45060006000fd" - }, - "0xb980ec1278699297a811e6a7f34d27d7cb686cda": { - "nonce": 1, - "code": "0x600160005560016001556001600255600160035560016004556000600060006000736f54c4d99a08c1c7e6b8d65b4fd338996e5875865af4506001600a556001600b556001600c556001600d556001600e55" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb980ec1278699297a811e6a7f34d27d7cb686cda", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json deleted file mode 100644 index fbe61bc53..000000000 --- a/crates/mega-differential/scenarios/eest/test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_reverted_grandchild_spill_through_child_halt_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6ab6b2485e767ba2f8f5c0526618184677377daa": { - "nonce": 1, - "code": "0x6000600060006000600073a2584bf1bb55ae3c006de0efdf56872a27544bf862061a80f16000556001600155" - }, - "0xa2584bf1bb55ae3c006de0efdf56872a27544bf8": { - "nonce": 1, - "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af150fe" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6ab6b2485e767ba2f8f5c0526618184677377daa", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 342e7ab27..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_existing_beneficiary_no_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1": { - "nonce": 1, - "balance": "0x01", - "code": "0x73c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json deleted file mode 100644 index f61a135aa..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_account_write_cost_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1": { - "nonce": 1, - "balance": "0x01", - "code": "0x73c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc79b96dbe44572a8e53fea80c9f73c99aded0fe1", - "data": "0x", - "value": "0x00", - "gas_limit": 200054900, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json deleted file mode 100644 index e11aa2705..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_100M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json deleted file mode 100644 index d0d779c9b..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_120M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json deleted file mode 100644 index b7ee26d42..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1G", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json deleted file mode 100644 index 1a31f2ef7..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_1M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json deleted file mode 100644 index 8d20d13c6..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_200M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json deleted file mode 100644 index 73ca1c26b..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_300M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json deleted file mode 100644 index 212e5aee6..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_30M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json deleted file mode 100644 index 5f5e08e0b..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_36M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json deleted file mode 100644 index 4232a5b90..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_500M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json deleted file mode 100644 index fb2fc7d06..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_scales_with_cpsb_fork_Amsterdam_state_test_60M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf98202f4ec103ee8ed7218d60753af742278537e": { - "nonce": 1, - "balance": "0x01", - "code": "0x600160005573c0f6dc9e5836f54caadbf59cc69346c508e1992bff" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf98202f4ec103ee8ed7218d60753af742278537e", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json deleted file mode 100644 index eb0cefdfe..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_reservoir", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { - "nonce": 1, - "balance": "0x01", - "code": "0x61deadff" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x895e76ae02c191381f7185dadef7dc9e0eae06b5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json deleted file mode 100644 index d1961d14b..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_new_beneficiary_state_gas_fork_Amsterdam_state_test_funding_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { - "nonce": 1, - "balance": "0x01", - "code": "0x61deadff" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x895e76ae02c191381f7185dadef7dc9e0eae06b5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json deleted file mode 100644 index 96ab1d9a2..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "test_selfdestruct_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9085a5d372760f4c4d295ef86317897367e479b3": { - "nonce": 1, - "code": "0x600060006000600060007396e10c7537ed10d01ff45bdb6c4740fb89ed5c1362030f9af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0x96e10c7537ed10d01ff45bdb6c4740fb89ed5c13": { - "nonce": 1, - "balance": "0x01", - "code": "0x61beefff" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x9085a5d372760f4c4d295ef86317897367e479b3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json deleted file mode 100644 index a0583ea61..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "test_selfdestruct_state_gas_refilled_on_ancestor_revert_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x895e76ae02c191381f7185dadef7dc9e0eae06b5": { - "nonce": 1, - "balance": "0x01", - "code": "0x61deadff" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfbb85e79c393dc0360ab6104bf657d70699d2540": { - "nonce": 1, - "code": "0x6000600060006000600073895e76ae02c191381f7185dadef7dc9e0eae06b55af15060006000fd" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfbb85e79c393dc0360ab6104bf657d70699d2540", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json deleted file mode 100644 index aa065d2c1..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test_selfdestruct_to_self_in_create_tx_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x892561f6d5f4204eb4892b936de9e93ef89b726a": { - "nonce": 1, - "balance": "0x01", - "code": "0x7f30ff000000000000000000000000000000000000000000000000000000000000600052600260006001f050" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x892561f6d5f4204eb4892b936de9e93ef89b726a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 99f7d83c4..000000000 --- a/crates/mega-differential/scenarios/eest/test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_selfdestruct_zero_balance_no_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4c644737fbd0f4c3ed81e7978ef771cffb2cd623": { - "nonce": 1, - "code": "0x61deadff" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x4c644737fbd0f4c3ed81e7978ef771cffb2cd623", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json deleted file mode 100644 index 66fffe05e..000000000 --- a/crates/mega-differential/scenarios/eest/test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_sequential_calls_reservoir_restored_between_reverts_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5ec2961b7c04481e954aac60dbe3db73647a27a5": { - "nonce": 1, - "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22426207a120f1506001600055" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5ec2961b7c04481e954aac60dbe3db73647a27a5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json deleted file mode 100644 index f67adbce1..000000000 --- a/crates/mega-differential/scenarios/eest/test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_soft_failed_value_call_refund_through_child_halt_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2a3649cfcbdab2b2df29f2179601e6bb016610f9": { - "nonce": 1, - "code": "0x6000600060006000600073e050ac2e4d9a47a60c134ed4b4973c975ab265cc620927c0f16000556001600155" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6a3af8fabbd77d2eb3816ad8db94d6dfc4a3aaa8": { - "nonce": 1, - "code": "0x6000600060006000600073b229c0dc861b48f5810722ac13332a9861fb22425af1506000600060006000600173c0f6dc9e5836f54caadbf59cc69346c508e1992b5af15000" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xe050ac2e4d9a47a60c134ed4b4973c975ab265cc": { - "nonce": 1, - "code": "0x600160005560006000600060006000736a3af8fabbd77d2eb3816ad8db94d6dfc4a3aaa85af150fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2a3649cfcbdab2b2df29f2179601e6bb016610f9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json deleted file mode 100644 index e9ffadb6d..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_clear_refund_reversal_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_sstore_clear_refund_reversal_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf05d9e96149e1e67cce4d42c4ee70ac95428020c": { - "nonce": 1, - "code": "0x60006000556002600055", - "storage": { - "0x00": "0x01" - } - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf05d9e96149e1e67cce4d42c4ee70ac95428020c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json deleted file mode 100644 index e8d476a40..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_direct_call_same_contract_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_direct_call_same_contract_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json deleted file mode 100644 index 01443d197..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_five_slots", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { - "nonce": 1, - "code": "0x60016000556001600155600160025560016003556001600455" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json deleted file mode 100644 index 20120753d..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_single_slot", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json b/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json deleted file mode 100644 index 736f154ba..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_multiple_slots_fork_Amsterdam_state_test_ten_slots", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x617bea927cf37c4412e3fce4f81e569abdc48455": { - "nonce": 1, - "code": "0x6001600055600160015560016002556001600355600160045560016005556001600655600160075560016008556001600955" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x617bea927cf37c4412e3fce4f81e569abdc48455", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json deleted file mode 100644 index 10cf9a8e4..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_sstore_nonzero_to_nonzero_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xeff502b1e5727e779185bcd40007a2016c533b4d": { - "nonce": 1, - "code": "0x6002600055", - "storage": { - "0x00": "0x01" - } - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xeff502b1e5727e779185bcd40007a2016c533b4d", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json deleted file mode 100644 index 6b90e12e6..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_nonzero_to_zero_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_sstore_nonzero_to_zero_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x22d339df985a054d335af73613545d6008566b37": { - "nonce": 1, - "code": "0x6000600055", - "storage": { - "0x00": "0x01" - } - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x22d339df985a054d335af73613545d6008566b37", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json deleted file mode 100644 index adbb7142b..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_exact_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { - "nonce": 1, - "code": "0x3660006000373660006000f0600055" - }, - "0xe6a324ee15bf48d590a092c37bff4e5c87cdd331": { - "nonce": 1, - "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b00af1" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe6a324ee15bf48d590a092c37bff4e5c87cdd331", - "data": "0x610001600081600b8239f300", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json deleted file mode 100644 index fdfbf95af..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_sstore_oog_no_reservoir_inflation_fork_Amsterdam_state_test_short_one_gas", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x40738b6435c17fe77e4996fa9c5ed1d8336ee81f": { - "nonce": 1, - "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b009f1" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { - "nonce": 1, - "code": "0x3660006000373660006000f0600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x40738b6435c17fe77e4996fa9c5ed1d8336ee81f", - "data": "0x610001600081600b8239f300", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json deleted file mode 100644 index aac03848a..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_oog_reservoir_inflation_detection_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9d87fef638b731e5aa691d2732b149eb2b6761b3": { - "nonce": 1, - "code": "0x3660006000373660006000f0600055" - }, - "0xb3142ba4ad58a0f6e68805f7f855b4f7b6142182": { - "nonce": 1, - "code": "0x6001600055600160015560016002556001600355" - }, - "0xf083cf5ff7e72c6cd483173256c7082088409f7d": { - "nonce": 1, - "code": "0x366000600037600060003660006000739d87fef638b731e5aa691d2732b149eb2b6761b36204b009f1506000600060006000600073b3142ba4ad58a0f6e68805f7f855b4f7b614218262025093f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf083cf5ff7e72c6cd483173256c7082088409f7d", - "data": "0x610001600081600b8239f300", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json deleted file mode 100644 index 17e21d5ec..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_100M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json deleted file mode 100644 index e6c2fe0a7..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_120M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json deleted file mode 100644 index 8793d8709..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1G", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json deleted file mode 100644 index b574e8c96..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_1M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json deleted file mode 100644 index 71297326d..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_200M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json deleted file mode 100644 index 00c58ae43..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_300M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json deleted file mode 100644 index 1ff4cc522..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_30M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json deleted file mode 100644 index 6f42e6f72..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_36M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json deleted file mode 100644 index 28b6d4cd4..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_500M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json b/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json deleted file mode 100644 index c47c82edb..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_refund_scales_with_cpsb_fork_Amsterdam_state_test_60M", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json deleted file mode 100644 index 7fd2c6c7c..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa0c52572fa5328e29f88edeec85dcb351e52b3d2": { - "nonce": 1, - "code": "0x6000600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xcd5508542374230140d5034f296cc69db8bf307b": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xa0c52572fa5328e29f88edeec85dcb351e52b3d2", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json deleted file mode 100644 index e5b63e5d0..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_CALL_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa8444717090cd23330d08d9e87bf42d227d1a203": { - "nonce": 1, - "code": "0x6000600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xcd5508542374230140d5034f296cc69db8bf307b": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xa8444717090cd23330d08d9e87bf42d227d1a203", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json deleted file mode 100644 index 1db173531..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_ancestor_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xcd5508542374230140d5034f296cc69db8bf307b": { - "nonce": 1, - "code": "0x6000600060006000600073d11563b17bd6259fe338a6974845ed64d4373b775af15060006000fd" - }, - "0xd11563b17bd6259fe338a6974845ed64d4373b77": { - "nonce": 1, - "code": "0x6001600055600060005500" - }, - "0xda705de478c87cceb6bc29ba16ed48a4be22a297": { - "nonce": 1, - "code": "0x600060006000600073cd5508542374230140d5034f296cc69db8bf307b5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xda705de478c87cceb6bc29ba16ed48a4be22a297", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json deleted file mode 100644 index 15cc5793c..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_single_hop", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x502d87dd8fc0a4b3389e1f3cf45b358ca65931bf": { - "nonce": 1, - "code": "0x600160005560006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x502d87dd8fc0a4b3389e1f3cf45b358ca65931bf", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json deleted file mode 100644 index 14d2cd1fa..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_ten_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x06a3a0082119a709a30e20f272a4f6acf1a4a188": { - "nonce": 1, - "code": "0x60006000600060006000730ecedbbade13d941b9a5a3cae25d460d37c071c25af25000" - }, - "0x0e32f98973de4965e5a94c046df0719cf287e4d3": { - "nonce": 1, - "code": "0x60006000600060006000731c574c3d836d61128c8700321f2d85c5e6027fae5af25000" - }, - "0x0ecedbbade13d941b9a5a3cae25d460d37c071c2": { - "nonce": 1, - "code": "0x60006000600060006000730e32f98973de4965e5a94c046df0719cf287e4d35af25000" - }, - "0x1c3d753788debf1c72853154110a4266671d5fb3": { - "nonce": 1, - "code": "0x600060006000600060007306a3a0082119a709a30e20f272a4f6acf1a4a1885af25000" - }, - "0x1c574c3d836d61128c8700321f2d85c5e6027fae": { - "nonce": 1, - "code": "0x6000600060006000600073200ccb62dcea9ceb6e6c5120fc41169ced10cade5af25000" - }, - "0x200ccb62dcea9ceb6e6c5120fc41169ced10cade": { - "nonce": 1, - "code": "0x6000600060006000600073c1a8eb07a893d6b77fb8dca17f0609fd544173715af25000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { - "nonce": 1, - "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" - }, - "0xc1a8eb07a893d6b77fb8dca17f0609fd54417371": { - "nonce": 1, - "code": "0x6000600060006000600073ce2b8b765a324df441554639c63f51041ecf41735af25000" - }, - "0xce2b8b765a324df441554639c63f51041ecf4173": { - "nonce": 1, - "code": "0x6000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af25000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfcd7bb271a3072c2f0829600a7220a4fd5a6c5fb": { - "nonce": 1, - "code": "0x600160005560006000600060006000731c3d753788debf1c72853154110a4266671d5fb35af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfcd7bb271a3072c2f0829600a7220a4fd5a6c5fb", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json deleted file mode 100644 index 9550912b8..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_three_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0x8a44f89da03e1ccdb1863429b2df1aa33551b45c": { - "nonce": 1, - "code": "0x60016000556000600060006000600073ce2b8b765a324df441554639c63f51041ecf41735af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { - "nonce": 1, - "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" - }, - "0xce2b8b765a324df441554639c63f51041ecf4173": { - "nonce": 1, - "code": "0x6000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af25000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x8a44f89da03e1ccdb1863429b2df1aa33551b45c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json deleted file mode 100644 index 41bac701a..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_CALLCODE_state_test_two_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x27c978b7268a99f80653ef0c370f2fb577fb8ec5": { - "nonce": 1, - "code": "0x60016000556000600060006000600073c00e4a73ec6ae626e63d408cffc7991f91dc3ba25af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xc00e4a73ec6ae626e63d408cffc7991f91dc3ba2": { - "nonce": 1, - "code": "0x60006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x27c978b7268a99f80653ef0c370f2fb577fb8ec5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json deleted file mode 100644 index 16480ccbf..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_single_hop", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xe5414887bddc564fa91e136f8ecd5d11c2967b33": { - "nonce": 1, - "code": "0x60016000556000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe5414887bddc564fa91e136f8ecd5d11c2967b33", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json deleted file mode 100644 index 400ff0e5c..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_ten_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { - "nonce": 1, - "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" - }, - "0x3b8acc4708b551d849131f41b9d960be2e7c905b": { - "nonce": 1, - "code": "0x600060006000600073dc81d7b2905163c6159329d5f16820fb6a554d885af45000" - }, - "0x499f3e9c99e571d817950d3d2cdf5a2df9791c84": { - "nonce": 1, - "code": "0x600060006000600073f4c687e3f29e0aa4f2b0d9b8420aa29b88f8dbdf5af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5b75b4547f441a232a390563dc9fae2ede7b7f88": { - "nonce": 1, - "code": "0x6000600060006000733b8acc4708b551d849131f41b9d960be2e7c905b5af45000" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0x806cf69271662bba0bac32ebd4e3f9e6d7c2b3a4": { - "nonce": 1, - "code": "0x6001600055600060006000600073ab2f92b511f6ed5cac4f1c8491ec3441019e1d9e5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xab2f92b511f6ed5cac4f1c8491ec3441019e1d9e": { - "nonce": 1, - "code": "0x600060006000600073f822f47c346ae7bed1440f68ab97a3e22b569e895af45000" - }, - "0xadea63edaf70d5cbbf53c24ce8b0cc22edc7e8fe": { - "nonce": 1, - "code": "0x600060006000600073499f3e9c99e571d817950d3d2cdf5a2df9791c845af45000" - }, - "0xdc81d7b2905163c6159329d5f16820fb6a554d88": { - "nonce": 1, - "code": "0x60006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af45000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf4c687e3f29e0aa4f2b0d9b8420aa29b88f8dbdf": { - "nonce": 1, - "code": "0x6000600060006000735b75b4547f441a232a390563dc9fae2ede7b7f885af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf822f47c346ae7bed1440f68ab97a3e22b569e89": { - "nonce": 1, - "code": "0x600060006000600073adea63edaf70d5cbbf53c24ce8b0cc22edc7e8fe5af45000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x806cf69271662bba0bac32ebd4e3f9e6d7c2b3a4", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json deleted file mode 100644 index 576b8e503..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_three_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { - "nonce": 1, - "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0x70f06bc3d6620b7e5b4bf63aff29043588afbf8c": { - "nonce": 1, - "code": "0x6001600055600060006000600073dc81d7b2905163c6159329d5f16820fb6a554d885af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xdc81d7b2905163c6159329d5f16820fb6a554d88": { - "nonce": 1, - "code": "0x60006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af45000" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x70f06bc3d6620b7e5b4bf63aff29043588afbf8c", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json deleted file mode 100644 index c4702f642..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_fork_Amsterdam_call_opcode_DELEGATECALL_state_test_two_hops", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x15e1618fbcac27dda0fa83b6fac2f735a5a40d60": { - "nonce": 1, - "code": "0x6000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0x7957016d354129b485e055f6ce731d9432924360": { - "nonce": 1, - "code": "0x600160005560006000600060007315e1618fbcac27dda0fa83b6fac2f735a5a40d605af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x7957016d354129b485e055f6ce731d9432924360", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json deleted file mode 100644 index 515ca4d09..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xc08d2c1a3c9ee34a8606ff5ca8b67dcf690ff371": { - "nonce": 1, - "code": "0x600160015560006000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af25060006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xe44db291e334fc5110232f4e5430de845b2890f5": { - "nonce": 1, - "code": "0x60016000556000600060006000600073c08d2c1a3c9ee34a8606ff5ca8b67dcf690ff3715af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe44db291e334fc5110232f4e5430de845b2890f5", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json deleted file mode 100644 index 01de9a929..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "test_sstore_restoration_charge_in_ancestor_intermediate_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5e20a1397258703e454f569126db7bd67b4744fc": { - "nonce": 1, - "code": "0x6001600055600060006000600073c8987c8935b45c813a6d4541aafc2ebfbe6533225af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600155" - }, - "0x6b79fec3b146aa3c1c869e589f1de9e26b0558f7": { - "nonce": 1, - "code": "0x600060005500" - }, - "0xc8987c8935b45c813a6d4541aafc2ebfbe653322": { - "nonce": 1, - "code": "0x60016001556000600060006000736b79fec3b146aa3c1c869e589f1de9e26b0558f75af45060006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5e20a1397258703e454f569126db7bd67b4744fc", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json deleted file mode 100644 index 815cc9916..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8b687a302685d3225dff99bf426ac71f33b2cc9c": { - "nonce": 1, - "code": "0x7f6001600055600060005560006000fd00000000000000000000000000000000006000526000600f60006000f55060006000fd" - }, - "0x9924456800f3de93b685f6bd8ba2ff52445d7032": { - "nonce": 1, - "code": "0x60006000600060006000738b687a302685d3225dff99bf426ac71f33b2cc9c5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x9924456800f3de93b685f6bd8ba2ff52445d7032", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json deleted file mode 100644 index 4d2118c22..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_create_init_revert_fork_Amsterdam_create_opcode_CREATE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xa6f584e4bf38391f364ba73cdfb5740dc7d989a4": { - "nonce": 1, - "code": "0x7f6001600055600060005560006000fd0000000000000000000000000000000000600052600f60006000f05060006000fd" - }, - "0xbbe7db18f80c7832998834d57dd751e52d92bdb9": { - "nonce": 1, - "code": "0x6000600060006000600073a6f584e4bf38391f364ba73cdfb5740dc7d989a45af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xbbe7db18f80c7832998834d57dd751e52d92bdb9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json deleted file mode 100644 index 209f32fb9..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5e85b8a9fe1249aa1a8e57406175f3873afa7811": { - "nonce": 1, - "code": "0x7f6001600055600060005560006000f3000000000000000000000000000000000060005260006000600f60006000f511600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5e85b8a9fe1249aa1a8e57406175f3873afa7811", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json deleted file mode 100644 index 7e31bff24..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_restoration_create_init_success_fork_Amsterdam_create_opcode_CREATE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x9be2be68c88060daffbb66e5bf419cf058feaaa7": { - "nonce": 1, - "code": "0x7f6001600055600060005560006000f300000000000000000000000000000000006000526000600f60006000f011600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x9be2be68c88060daffbb66e5bf419cf058feaaa7", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json deleted file mode 100644 index e2544522b..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "test_sstore_restoration_nonzero_no_state_refund_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x45077657f5c26405afcf543a09ff0536a5ec4532": { - "nonce": 1, - "code": "0x60026000556001600055", - "storage": { - "0x00": "0x01" - } - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x45077657f5c26405afcf543a09ff0536a5ec4532", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json deleted file mode 100644 index 01f4671fd..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_no_refund_create_oogs", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { - "nonce": 1, - "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" - }, - "0x3485e345790048eee08c9b61267d87478aaf5039": { - "nonce": 1, - "code": "0x600060006000600073903d585436c21b3f66864dcd14c9c72535450cb35af45000" - }, - "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { - "nonce": 1, - "code": "0x60026000556002600155600060006000f050600160025500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5f701c5c2cfcb03e8315498d1b92d293a0c15549": { - "nonce": 1, - "code": "0x6000600060006000738262901b8f40b64fcaf05340648089e28b8e4f3d5af45000" - }, - "0x7f91850cafc84dd9fab50531a01acc66694acdf8": { - "nonce": 1, - "code": "0x600060006000600073fa5847f72174944848d78a95f7df0705e29732a15af45000" - }, - "0x8262901b8f40b64fcaf05340648089e28b8e4f3d": { - "nonce": 1, - "code": "0x600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" - }, - "0x870405f91f7b6ff0ca990c059ee6715d1cf5dc0f": { - "nonce": 1, - "code": "0x6000600060006000733485e345790048eee08c9b61267d87478aaf50395af45000" - }, - "0x903d585436c21b3f66864dcd14c9c72535450cb3": { - "nonce": 1, - "code": "0x600060006000600073993e7bf6a7c0220c0a83d43de66539ac7c3b81d65af45000" - }, - "0x993e7bf6a7c0220c0a83d43de66539ac7c3b81d6": { - "nonce": 1, - "code": "0x600060006000600073f6ef97d4300d93bf2558c8d32c233b5422ab3e295af45000" - }, - "0xaa7690e523c2d3e068453fcbc5f7d9ef91bd1ea2": { - "nonce": 1, - "code": "0x600160005560016001556000600060006000737f91850cafc84dd9fab50531a01acc66694acdf85af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xf6ef97d4300d93bf2558c8d32c233b5422ab3e29": { - "nonce": 1, - "code": "0x6000600060006000735f701c5c2cfcb03e8315498d1b92d293a0c155495af45000" - }, - "0xfa5847f72174944848d78a95f7df0705e29732a1": { - "nonce": 1, - "code": "0x600060006000600073870405f91f7b6ff0ca990c059ee6715d1cf5dc0f5af45000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xaa7690e523c2d3e068453fcbc5f7d9ef91bd1ea2", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json deleted file mode 100644 index 045ef56e8..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_10_refund_funds_create", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x123351ba1d1b575788d5e7d422dd0d5991bae228": { - "nonce": 1, - "code": "0x600060006000600073fee8ae183d5743fcd9ca7bb2a818ac8c6222b6955af45000" - }, - "0x12d946c11d5ca6ca04ff5d4a9f42791f03469758": { - "nonce": 1, - "code": "0x6000600060006000736f802627f1da31fac729620e8749f3faead0d2535af45000" - }, - "0x2bff1dbc074f103d7f14a0838b3e05964be16825": { - "nonce": 1, - "code": "0x60006000600060007312d946c11d5ca6ca04ff5d4a9f42791f034697585af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x56508517ac549895c936f4ce69ea05801f2b10a9": { - "nonce": 1, - "code": "0x600160005560016001556000600060006000736724c7ff678d110c88703b6038f9f3e6e3e571685af45000" - }, - "0x6724c7ff678d110c88703b6038f9f3e6e3e57168": { - "nonce": 1, - "code": "0x6000600060006000736f969a7bd5f36d33848eeb3fbe25f3ab570f690b5af45000" - }, - "0x6f802627f1da31fac729620e8749f3faead0d253": { - "nonce": 1, - "code": "0x600060006000600073efeb46955494de7ec79826d87a9dabeed4f5fb635af45000" - }, - "0x6f969a7bd5f36d33848eeb3fbe25f3ab570f690b": { - "nonce": 1, - "code": "0x600060006000600073123351ba1d1b575788d5e7d422dd0d5991bae2285af45000" - }, - "0x8936a6da1a28684143533123025e622069901dc6": { - "nonce": 1, - "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" - }, - "0x9308b92176a11e055f973ce308e71afc2faec231": { - "nonce": 1, - "code": "0x6000600060006000738936a6da1a28684143533123025e622069901dc65af45000" - }, - "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { - "nonce": 1, - "code": "0x60006000556000600155600060006000f050600160025500" - }, - "0xefeb46955494de7ec79826d87a9dabeed4f5fb63": { - "nonce": 1, - "code": "0x6000600060006000739308b92176a11e055f973ce308e71afc2faec2315af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfee8ae183d5743fcd9ca7bb2a818ac8c6222b695": { - "nonce": 1, - "code": "0x6000600060006000732bff1dbc074f103d7f14a0838b3e05964be168255af45000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x56508517ac549895c936f4ce69ea05801f2b10a9", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json deleted file mode 100644 index 695b28e8b..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_no_refund_create_oogs", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { - "nonce": 1, - "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" - }, - "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { - "nonce": 1, - "code": "0x60026000556002600155600060006000f050600160025500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - }, - "0xfa20484013e64b1fd58c2f25bc42d386464cf2c1": { - "nonce": 1, - "code": "0x60016000556001600155600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xfa20484013e64b1fd58c2f25bc42d386464cf2c1", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json deleted file mode 100644 index 82f95c659..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_1_refund_funds_create", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x2c0ac31d364ca8a2321630f06ec491d424523fae": { - "nonce": 1, - "code": "0x600160005560016001556000600060006000738936a6da1a28684143533123025e622069901dc65af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8936a6da1a28684143533123025e622069901dc6": { - "nonce": 1, - "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" - }, - "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { - "nonce": 1, - "code": "0x60006000556000600155600060006000f050600160025500" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2c0ac31d364ca8a2321630f06ec491d424523fae", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json deleted file mode 100644 index dad7bbae8..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_no_refund_create_oogs", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x1ed438e9f55a47b766499a14b1e44155d5b60c9b": { - "nonce": 1, - "code": "0x600160005560016001556000600060006000735f701c5c2cfcb03e8315498d1b92d293a0c155495af45000" - }, - "0x310b67f924f29693de45cfcd7e2c97ade1b500d3": { - "nonce": 1, - "code": "0x6000600060006000733a003c9d9a2b48c4610623b5c025182026d6596b5af45000" - }, - "0x3a003c9d9a2b48c4610623b5c025182026d6596b": { - "nonce": 1, - "code": "0x60026000556002600155600060006000f050600160025500" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5f701c5c2cfcb03e8315498d1b92d293a0c15549": { - "nonce": 1, - "code": "0x6000600060006000738262901b8f40b64fcaf05340648089e28b8e4f3d5af45000" - }, - "0x8262901b8f40b64fcaf05340648089e28b8e4f3d": { - "nonce": 1, - "code": "0x600060006000600073310b67f924f29693de45cfcd7e2c97ade1b500d35af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x1ed438e9f55a47b766499a14b1e44155d5b60c9b", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json deleted file mode 100644 index 0b259a62f..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_credits_local_reservoir_fork_Amsterdam_state_test_depth_3_refund_funds_create", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0fbf9bd6a341fba0f8df9fd59308cc6108e49389": { - "nonce": 1, - "code": "0x60016000556001600155600060006000600073efeb46955494de7ec79826d87a9dabeed4f5fb635af45000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x8936a6da1a28684143533123025e622069901dc6": { - "nonce": 1, - "code": "0x600060006000600073c3886604bfe4b72b4f0189824b227a8549b1a0075af45000" - }, - "0x9308b92176a11e055f973ce308e71afc2faec231": { - "nonce": 1, - "code": "0x6000600060006000738936a6da1a28684143533123025e622069901dc65af45000" - }, - "0xc3886604bfe4b72b4f0189824b227a8549b1a007": { - "nonce": 1, - "code": "0x60006000556000600155600060006000f050600160025500" - }, - "0xefeb46955494de7ec79826d87a9dabeed4f5fb63": { - "nonce": 1, - "code": "0x6000600060006000739308b92176a11e055f973ce308e71afc2faec2315af45000" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0fbf9bd6a341fba0f8df9fd59308cc6108e49389", - "data": "0x", - "value": "0x00", - "gas_limit": 200121910, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json deleted file mode 100644 index 900d4182a..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_refund_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_restoration_refund_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8": { - "nonce": 1, - "code": "0x60016000556000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x5c81b4ea668898781e0c7d08c23f03b886fd76e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json deleted file mode 100644 index a5594cf1a..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALLCODE_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { - "nonce": 1, - "code": "0x6001600055600060005560006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6c3c798e2e8689bcfa1cd4118362859da59301a3": { - "nonce": 1, - "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af2506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6c3c798e2e8689bcfa1cd4118362859da59301a3", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json deleted file mode 100644 index c29ccaab5..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_CALL_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { - "nonce": 1, - "code": "0x6001600055600060005560006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc69c38a86504a4047bb75491f68f648750a22c85": { - "nonce": 1, - "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af1506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc69c38a86504a4047bb75491f68f648750a22c85", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json deleted file mode 100644 index bdda777d7..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_sstore_restoration_sub_frame_revert_fork_Amsterdam_call_opcode_DELEGATECALL_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { - "nonce": 1, - "code": "0x6001600055600060005560006000fd" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb20f9c60dd952ad73afb8445cc40daa0dd2c9f4b": { - "nonce": 1, - "code": "0x600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af4506000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb20f9c60dd952ad73afb8445cc40daa0dd2c9f4b", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json deleted file mode 100644 index 2f5d48809..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_0_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json deleted file mode 100644 index a8c31ac91..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_1_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json deleted file mode 100644 index 03ec80390..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_all_tx_types_fork_Amsterdam_typed_transaction_2_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 7fc30e647..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_drawn_from_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json deleted file mode 100644 index f6d97cb2e..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_entirely_from_gas_left_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json deleted file mode 100644 index 2aa1f9f4e..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_from_reservoir", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { - "nonce": 1, - "code": "0x60016000556001600155600160025560016003556001600455" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json deleted file mode 100644 index 409c557ad..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_multiple_sstores_spill_to_gas_left", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9": { - "nonce": 1, - "code": "0x60016000556001600155600160025560016003556001600455" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x0859dd7104c9a669ee8a0a15664f10b75f90a9f9", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json deleted file mode 100644 index 34d9178a3..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_from_reservoir", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json b/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json deleted file mode 100644 index 0b319c7a3..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_state_gas_source_fork_Amsterdam_state_test_single_sstore_spill_to_gas_left", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json deleted file mode 100644 index db2029e93..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_at_stipend", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x92db0d1541f6727ee66c97c69cd4e5c6c7d6c438": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef612f4af1600055" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x92db0d1541f6727ee66c97c69cd4e5c6c7d6c438", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json b/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json deleted file mode 100644 index 94bcdedc9..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_sstore_stipend_check_excludes_reservoir_fork_Amsterdam_state_test_below_stipend", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf69d5ad8ffdfcb5e33186a1618a4d1acb979a3ba": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef610902f1600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xf69d5ad8ffdfcb5e33186a1618a4d1acb979a3ba", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json deleted file mode 100644 index bd2d51c4e..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_nonzero_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_zero_to_nonzero_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json deleted file mode 100644 index f314f4e5c..000000000 --- a/crates/mega-differential/scenarios/eest/test_sstore_zero_to_zero_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_sstore_zero_to_zero_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe28ddc6f7f6ca2da37aeebaa7c6b0805b5949be6": { - "nonce": 1, - "code": "0x6000600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe28ddc6f7f6ca2da37aeebaa7c6b0805b5949be6", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json deleted file mode 100644 index 95bb01360..000000000 --- a/crates/mega-differential/scenarios/eest/test_staticcall_passes_reservoir_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_staticcall_passes_reservoir_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6057d1e55c120acb71ac66ba43c26283a7573589": { - "nonce": 1, - "code": "0x30600052" - }, - "0x84ca9599720705b6813be1acad6ff45a50fc6108": { - "nonce": 1, - "code": "0x6000600060006000736057d1e55c120acb71ac66ba43c26283a7573589620186a0fa506001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x84ca9599720705b6813be1acad6ff45a50fc6108", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json deleted file mode 100644 index 9fe8044e5..000000000 --- a/crates/mega-differential/scenarios/eest/test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "test_subcall_revert_does_not_leak_grandchild_storage_clear_credit_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x5104e8dfb400fa45528f1939767450df6969319e": { - "nonce": 1, - "code": "0x60006000556000600155600060025560006003556000600455" - }, - "0x6f54c4d99a08c1c7e6b8d65b4fd338996e587586": { - "nonce": 1, - "code": "0x6000600060006000735104e8dfb400fa45528f1939767450df6969319e5af45060006000fd" - }, - "0xb980ec1278699297a811e6a7f34d27d7cb686cda": { - "nonce": 1, - "code": "0x600160005560016001556001600255600160035560016004556000600060006000736f54c4d99a08c1c7e6b8d65b4fd338996e5875865af4506001600a556001600b556001600c556001600d556001600e55" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb980ec1278699297a811e6a7f34d27d7cb686cda", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json deleted file mode 100644 index 0e0dc6c13..000000000 --- a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_no_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { - "nonce": 1, - "code": "0x6001600055600060005560006000fd" - }, - "0x2bd72bd184d23ea3b68d41cd70854491f171997f": { - "nonce": 1, - "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2bd72bd184d23ea3b68d41cd70854491f171997f", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json b/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json deleted file mode 100644 index 91eab815d..000000000 --- a/crates/mega-differential/scenarios/eest/test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_subcall_set_clear_revert_pays_no_state_gas_fork_Amsterdam_state_test_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x033d0ae8aad38b912e80f5bfe7afc4c2122c929c": { - "nonce": 1, - "code": "0x6001600055600060005560006000fd" - }, - "0x2bd72bd184d23ea3b68d41cd70854491f171997f": { - "nonce": 1, - "code": "0x6000600060006000600073033d0ae8aad38b912e80f5bfe7afc4c2122c929c5af15000" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x2bd72bd184d23ea3b68d41cd70854491f171997f", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json deleted file mode 100644 index c01d6b1b1..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_halt", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6524df279f61e2ec1601dac01281b2d06a607772": { - "nonce": 1, - "code": "0x6001600055fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6524df279f61e2ec1601dac01281b2d06a607772", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json deleted file mode 100644 index bccdbf3a5..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_oog", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x1b6cf6d0ae353ff340e1f3951356d7dcec64b8e8": { - "nonce": 1, - "code": "0x600160005564174876e800600020" - }, - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x1b6cf6d0ae353ff340e1f3951356d7dcec64b8e8", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json deleted file mode 100644 index cebd1b292..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_failure_refunds_execution_state_gas_fork_Amsterdam_state_test_revert", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb229c0dc861b48f5810722ac13332a9861fb2242", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json deleted file mode 100644 index b48139755..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_and_propagated_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xd8da2dd52e320768f4e488cf4b9188268a0230dd": { - "nonce": 1, - "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af150fe" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xd8da2dd52e320768f4e488cf4b9188268a0230dd", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json deleted file mode 100644 index 1f9ebc84e..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_own_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x6524df279f61e2ec1601dac01281b2d06a607772": { - "nonce": 1, - "code": "0x6001600055fe" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x6524df279f61e2ec1601dac01281b2d06a607772", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json deleted file mode 100644 index 085566603..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_halt_propagated_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0x851bcae7cde3f214e0fc2a69fe8ba3251a0d5b56": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af150fe" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0x851bcae7cde3f214e0fc2a69fe8ba3251a0d5b56", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json deleted file mode 100644 index a6295e954..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_and_propagated_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xdf9bd1bc60f6cf9564c6053445b38b66c7b94fa6": { - "nonce": 1, - "code": "0x60016000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af15060006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xdf9bd1bc60f6cf9564c6053445b38b66c7b94fa6", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json deleted file mode 100644 index a5459a84b..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_own_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xb229c0dc861b48f5810722ac13332a9861fb2242": { - "nonce": 1, - "code": "0x600160005560006000fd" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xb229c0dc861b48f5810722ac13332a9861fb2242", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json b/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json deleted file mode 100644 index 7b588bb77..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "test_top_level_failure_spilled_state_gas_fork_Amsterdam_state_test_revert_propagated_spill", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xc1420b3ed565b52fd874b2aaf0cf7fac5b2d9d5a": { - "nonce": 1, - "code": "0x6000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef5af15060006000fd" - }, - "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { - "nonce": 1, - "code": "0x6001600055" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xc1420b3ed565b52fd874b2aaf0cf7fac5b2d9d5a", - "data": "0x", - "value": "0x00", - "gas_limit": 200250000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json b/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json deleted file mode 100644 index 4b399c55c..000000000 --- a/crates/mega-differential/scenarios/eest/test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test_top_level_opcode_oog_before_frame_end_does_not_refund_state_gas_fork_Amsterdam_state_test", - "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", - "pre": { - "0x4e59b44847b379578588920ca78fbf26c0b4956c": { - "nonce": 1, - "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" - }, - "0xe0312e9fddad3044789133bb09912bed5d8c1a00": { - "nonce": 1, - "code": "0x6001600055600160006110005e" - }, - "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { - "balance": "0x033b2e3c9fd0803ce8000000" - } - }, - "txs": [ - { - "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", - "to": "0xe0312e9fddad3044789133bb09912bed5d8c1a00", - "data": "0x", - "value": "0x00", - "gas_limit": 200006884, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/code_deposit.json b/crates/mega-differential/scenarios/handwritten/code_deposit.json deleted file mode 100644 index 3ead2c211..000000000 --- a/crates/mega-differential/scenarios/handwritten/code_deposit.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "code_deposit", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000000527f5b670000000000000000527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b670000000000000040527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000040670000000000000060527f52670000000000000060670000000000000000f3000000000000000000000000670000000000000080526700000000000000946700000000000000005ff0505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json b/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json deleted file mode 100644 index fbb3f4eb8..000000000 --- a/crates/mega-differential/scenarios/handwritten/code_deposit_large_spills.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "code_deposit_large_spills", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000000527f5b670000000000000000527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000020527f5b5b5b5b5b5b5b5b5b670000000000000040527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000040670000000000000060527f527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000080527f5b5b670000000000000060527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000000a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000080527f5b5b5b5b5b5b5b5b6700000000000000c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67000000000000006700000000000000e0527fa0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000100527f5b5b5b6700000000000000c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000120527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000000e0527f5b5b5b5b5b5b5b670000000000000140527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67000000000000670000000000000160527f0100527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000180527f5b5b5b5b670000000000000120527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000001a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000140527f5b5b5b5b5b5b6700000000000001c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000006700000000000001e0527f000160527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000200527f5b5b5b5b5b670000000000000180527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000220527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000001a0527f5b5b5b5b5b670000000000000240527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000670000000000000260527f000001c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000280527f5b5b5b5b5b5b6700000000000001e0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000002a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000200527f5b5b5b5b6700000000000002c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000006700000000000002e0527f0000000220527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000300527f5b5b5b5b5b5b5b670000000000000240527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000320527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000260527f5b5b5b670000000000000340527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000670000000000000360527f000000000280527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000380527f5b5b5b5b5b5b5b5b6700000000000002a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000003a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000002c0527f5b5b6700000000000003c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67006700000000000003e0527f000000000002e0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000400527f5b5b5b5b5b5b5b5b5b670000000000000300527f5b5b5b5b5b5b5b5b5b5b5b5b670000000000000420527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000320527f5b670000000000000440527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b67670000000000000460527f0000000000000340527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000480527f5b5b5b5b5b5b5b5b5b5b670000000000000360527f5b5b5b5b5b5b5b5b5b5b5b6700000000000004a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000380527f6700000000000004c0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000004e0527f6700000000000003a0527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b670000000000000500527f5b5b5b5b5b5b5b5b5b5b5b6700000000000003c0527f5b5b5b5b5b5b5b5b5b5b670000000000000520527f5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b5b6700000000000003e052670000000000000540527f670000000000000400670000000000000000f300000000000000000000000000670000000000000560526700000000000005736700000000000000005ff0505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create2_success.json b/crates/mega-differential/scenarios/handwritten/create2_success.json deleted file mode 100644 index 417a30118..000000000 --- a/crates/mega-differential/scenarios/handwritten/create2_success.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "create2_success", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005f670000000000000000f5505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_address_collision.json b/crates/mega-differential/scenarios/handwritten/create_address_collision.json deleted file mode 100644 index 102e4aa1d..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_address_collision.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "create_address_collision", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b000000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000002670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", - "storage": {} - }, - "0x4e4d52dd883900314328cde4a7050718ffd64bfc": { - "nonce": 1, - "balance": "0x0", - "code": "0x5b00", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json b/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json deleted file mode 100644 index 98dd8bf8e..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_initcode_revert_after_spill.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "create_initcode_revert_after_spill", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f5f5ffd0000000000000000000000000000000000000000000000000000000000670000000000000000526700000000000000036700000000000000005ff0505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json b/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json deleted file mode 100644 index c22845a62..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_insufficient_endowment.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "create_insufficient_endowment", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc6700000000000493e0f1505a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b000000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000002670000000000000000f300006700000000000000205267000000000000003e6700000000000000006700000000000003e8f05000", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json b/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json deleted file mode 100644 index 252ec3c09..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_revert_inside_reverting_call.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "create_revert_inside_reverting_call", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc670000000000061a80f1505a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f5f5ffd0000000000000000000000000000000000000000000000000000000000670000000000000000526700000000000000036700000000000000005ff0505f5ffd", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_success.json b/crates/mega-differential/scenarios/handwritten/create_success.json deleted file mode 100644 index e3f8cf5d0..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_success.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "create_success", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/create_transaction.json b/crates/mega-differential/scenarios/handwritten/create_transaction.json deleted file mode 100644 index 14cb8810e..000000000 --- a/crates/mega-differential/scenarios/handwritten/create_transaction.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "create_transaction", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "data": "0x7f5b5b00000000000000000000000000000000000000000000000000000000000067000000000000000052670000000000000003670000000000000000f3", - "value": "0x0", - "gas_limit": 200150000, - "kind": "create" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json b/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json deleted file mode 100644 index 4f007f6f3..000000000 --- a/crates/mega-differential/scenarios/handwritten/delegatecall_refill_of_a_parent_charge.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "delegatecall_refill_of_a_parent_charge", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5f5f5f730000000000000000000000000000000000000ccc67000000000002bf20f4505a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000015500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json b/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json deleted file mode 100644 index 16ad0ce49..000000000 --- a/crates/mega-differential/scenarios/handwritten/gas_limit_above_cap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "gas_limit_above_cap", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200500000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json b/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json deleted file mode 100644 index 1228af750..000000000 --- a/crates/mega-differential/scenarios/handwritten/gas_limit_below_cap.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "gas_limit_below_cap", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 650000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json b/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json deleted file mode 100644 index d8e6e0bde..000000000 --- a/crates/mega-differential/scenarios/handwritten/nested_call_halt_with_spill.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "nested_call_halt_with_spill", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1507f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000032557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000033555a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f000000000000000000000000000000000000000000000000000000000000000255fe", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json b/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json deleted file mode 100644 index f928b1289..000000000 --- a/crates/mega-differential/scenarios/handwritten/nested_call_revert_with_spill.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "nested_call_revert_with_spill", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5ffd", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json b/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json deleted file mode 100644 index bc70f9bf0..000000000 --- a/crates/mega-differential/scenarios/handwritten/selfdestruct_to_new_account.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "selfdestruct_to_new_account", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", - "storage": {} - }, - "0x0000000000000000000000000000000000000ccc": { - "nonce": 1, - "balance": "0x3e8", - "code": "0x730000000000000000000000000000000000000eeeff", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json b/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json deleted file mode 100644 index bc24628c2..000000000 --- a/crates/mega-differential/scenarios/handwritten/sstore_refill_after_spill.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "sstore_refill_after_spill", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002557f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json b/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json deleted file mode 100644 index 925423c53..000000000 --- a/crates/mega-differential/scenarios/handwritten/sstore_refill_no_prior_spill.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "sstore_refill_no_prior_spill", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json b/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json deleted file mode 100644 index 5bd91f6b5..000000000 --- a/crates/mega-differential/scenarios/handwritten/sstore_set_spills.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "sstore_set_spills", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json b/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json deleted file mode 100644 index cc8b8ef40..000000000 --- a/crates/mega-differential/scenarios/handwritten/sstore_set_within_reservoir.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "sstore_set_within_reservoir", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/system_call.json b/crates/mega-differential/scenarios/handwritten/system_call.json deleted file mode 100644 index 4e82514d5..000000000 --- a/crates/mega-differential/scenarios/handwritten/system_call.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "system_call", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0xfffffffffffffffffffffffffffffffffffffffe", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "kind": "system_call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json b/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json deleted file mode 100644 index 9ab146327..000000000 --- a/crates/mega-differential/scenarios/handwritten/two_txs_sequential.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "two_txs_sequential", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x0", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json deleted file mode 100644 index 3cd3608da..000000000 --- a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "value_call_to_new_account", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x3e8", - "code": "0x5f5f5f5f670000000000000001730000000000000000000000000000000000000eee67000000000002bf20f1505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json b/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json deleted file mode 100644 index ddfe0ec8c..000000000 --- a/crates/mega-differential/scenarios/handwritten/value_call_to_new_account_insufficient_balance.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "value_call_to_new_account_insufficient_balance", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "nonce": 0, - "balance": "0xe8d4a51000", - "code": "0x", - "storage": {} - }, - "0x0000000000000000000000000000000000000bbb": { - "nonce": 1, - "balance": "0x1", - "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5f5f5f6700000000000f4240730000000000000000000000000000000000000eee67000000000002bf20f1505a6700000000000000645500", - "storage": {} - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000bbb", - "data": "0x", - "value": "0x0", - "gas_limit": 200150000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/access_list_duplicates.json b/crates/mega-differential/scenarios/harness/access_list_duplicates.json deleted file mode 100644 index 9b7a478a3..000000000 --- a/crates/mega-differential/scenarios/harness/access_list_duplicates.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "access_list_duplicates", - "description": "The access list repeats an address and a storage key; each entry is charged.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000ead": { - "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", - "storage": { - "0x0": "0x1", - "0x1": "0x2" - } - }, - "0x00000000000000000000000000000000000000e4": { - "balance": "0x3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000ead", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "access_list": [ - { - "address": "0x0000000000000000000000000000000000000ead", - "storage_keys": [ - "0x0", - "0x0" - ] - }, - { - "address": "0x0000000000000000000000000000000000000ead", - "storage_keys": [ - "0x0" - ] - }, - { - "address": "0x00000000000000000000000000000000000000e4", - "storage_keys": [] - }, - { - "address": "0x00000000000000000000000000000000000000e4", - "storage_keys": [] - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/access_list_on_create.json b/crates/mega-differential/scenarios/harness/access_list_on_create.json deleted file mode 100644 index b24bf325e..000000000 --- a/crates/mega-differential/scenarios/harness/access_list_on_create.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "access_list_on_create", - "description": "A contract-creation transaction with an access list (EIP-2930 type).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "data": "0x600160005560006000f3", - "value": "0x0", - "gas_limit": 1000000, - "kind": "create", - "access_list": [ - { - "address": "0x0000000000000000000000000000000000000ead", - "storage_keys": [ - "0x0" - ] - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/access_list_unused_entries.json b/crates/mega-differential/scenarios/harness/access_list_unused_entries.json deleted file mode 100644 index 07542bcc4..000000000 --- a/crates/mega-differential/scenarios/harness/access_list_unused_entries.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "access_list_unused_entries", - "description": "The access list warms accounts and slots the call never touches.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000ead": { - "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", - "storage": { - "0x0": "0x1", - "0x1": "0x2" - } - }, - "0x00000000000000000000000000000000000000e4": { - "balance": "0x3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000ead", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "access_list": [ - { - "address": "0x0000000000000000000000000000000000000fee", - "storage_keys": [ - "0x1", - "0x2", - "0x3" - ] - }, - { - "address": "0x0000000000000000000000000000000000000fef", - "storage_keys": [] - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json b/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json deleted file mode 100644 index aacca0ab9..000000000 --- a/crates/mega-differential/scenarios/harness/access_list_warm_slots_and_account.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "access_list_warm_slots_and_account", - "description": "The access list warms slot 0 and slot 2 of the reader and the account it reads the balance of; slot 1 stays cold.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000ead": { - "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", - "storage": { - "0x0": "0x1", - "0x1": "0x2" - } - }, - "0x00000000000000000000000000000000000000e4": { - "balance": "0x3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000ead", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "access_list": [ - { - "address": "0x0000000000000000000000000000000000000ead", - "storage_keys": [ - "0x0", - "0x2" - ] - }, - { - "address": "0x00000000000000000000000000000000000000e4", - "storage_keys": [] - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json deleted file mode 100644 index c28b038ab..000000000 --- a/crates/mega-differential/scenarios/harness/create2_empty_initcode_large_offset.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_empty_initcode_large_offset", - "description": "CREATE2 with empty initcode at offset 2^30: no memory expansion is charged (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x6000600063400000006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json deleted file mode 100644 index 00a3cdc0e..000000000 --- a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_max.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_empty_initcode_offset_max", - "description": "CREATE2 with empty initcode at offset 2^256 - 1: the offset is ignored and the create succeeds (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json b/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json deleted file mode 100644 index 638c05391..000000000 --- a/crates/mega-differential/scenarios/harness/create2_empty_initcode_offset_zero.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_empty_initcode_offset_zero", - "description": "CREATE2 with empty initcode at offset 0 deploys empty code (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x6000600060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json b/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json deleted file mode 100644 index 96a3ee1ce..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_10mib.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_10mib", - "description": "CREATE2 of 10 MiB of initcode, far over the initcode size limit (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600062a0000060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_32k.json b/crates/mega-differential/scenarios/harness/create2_initcode_32k.json deleted file mode 100644 index dbdedf34a..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_32k.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_32k", - "description": "CREATE2 of 32 KiB of zero initcode: a non-trivial memory expansion, then a STOP constructor (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600061800060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_600k.json b/crates/mega-differential/scenarios/harness/create2_initcode_600k.json deleted file mode 100644 index 52edbb713..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_600k.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_600k", - "description": "CREATE2 of 600,000 bytes of initcode, over the initcode size limit with an affordable memory expansion (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x6000620927c060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json b/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json deleted file mode 100644 index 9d77a1369..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_at_limit.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_at_limit", - "description": "CREATE2 of exactly 49,152 bytes, the EIP-3860 initcode size limit the configuration carries today: it is accepted (ported from the legacy suite, whose bound was MegaETH's own).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600061c00060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json b/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json deleted file mode 100644 index c71485ad6..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_memory_oog.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_memory_oog", - "description": "CREATE2 of 500,000 bytes of initcode under a 200,000 gas limit. Over the 49,152-byte initcode size limit the configuration carries today, the size check halts the frame before memory expansion; under a limit above 500,000 bytes the memory expansion would run out of gas instead (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x60006207a12060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 200000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json b/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json deleted file mode 100644 index 8a955582b..000000000 --- a/crates/mega-differential/scenarios/harness/create2_initcode_over_limit.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_initcode_over_limit", - "description": "CREATE2 of 49,153 bytes, one over the EIP-3860 initcode size limit (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600061c00160006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_length.json b/crates/mega-differential/scenarios/harness/create2_missing_length.json deleted file mode 100644 index e37b7e871..000000000 --- a/crates/mega-differential/scenarios/harness/create2_missing_length.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_missing_length", - "description": "CREATE2 with two operands (no length) halts with a stack underflow (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x60006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_offset.json b/crates/mega-differential/scenarios/harness/create2_missing_offset.json deleted file mode 100644 index 85a8355f4..000000000 --- a/crates/mega-differential/scenarios/harness/create2_missing_offset.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_missing_offset", - "description": "CREATE2 with one operand (no offset) halts with a stack underflow (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x6000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_missing_salt.json b/crates/mega-differential/scenarios/harness/create2_missing_salt.json deleted file mode 100644 index c80bed8e2..000000000 --- a/crates/mega-differential/scenarios/harness/create2_missing_salt.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_missing_salt", - "description": "CREATE2 with three operands (no salt) halts with a stack underflow (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x61800060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json b/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json deleted file mode 100644 index cce13f177..000000000 --- a/crates/mega-differential/scenarios/harness/create2_nonempty_initcode_offset_max.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_nonempty_initcode_offset_max", - "description": "CREATE2 of one byte at offset 2^256 - 1: the offset does not fit and the frame halts (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600060017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json b/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json deleted file mode 100644 index e41a24b40..000000000 --- a/crates/mega-differential/scenarios/harness/create2_oversized_initcode_unrepresentable_offset.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "create2_oversized_initcode_unrepresentable_offset", - "description": "CREATE2 of 49,153 bytes at an offset of 2^128 - 1 (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x0000000000000000000000000000000000000c2e": { - "code": "0x600061c0017f00000000000000000000000000000000ffffffffffffffffffffffffffffffff6000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000c2e", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json deleted file mode 100644 index 726af8673..000000000 --- a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create2_static_empty_initcode", - "description": "CREATE2 with empty initcode inside a STATICCALL (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0x6000600060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json b/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json deleted file mode 100644 index 1bab6597f..000000000 --- a/crates/mega-differential/scenarios/harness/create2_static_empty_initcode_low_gas.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create2_static_empty_initcode_low_gas", - "description": "CREATE2 with empty initcode inside a STATICCALL that forwards 10,000 gas (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce612710fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0x6000600060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json b/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json deleted file mode 100644 index 6951c7797..000000000 --- a/crates/mega-differential/scenarios/harness/create2_static_initcode_10mib.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create2_static_initcode_10mib", - "description": "CREATE2 of 10 MiB inside a STATICCALL (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0x600062a0000060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json b/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json deleted file mode 100644 index d416c1c42..000000000 --- a/crates/mega-differential/scenarios/harness/create2_static_initcode_600k.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create2_static_initcode_600k", - "description": "CREATE2 of 600,000 bytes inside a STATICCALL; the caller records the failed call (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0x6000620927c060006000f500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json b/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json deleted file mode 100644 index de7830a73..000000000 --- a/crates/mega-differential/scenarios/harness/create2_static_missing_operands.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create2_static_missing_operands", - "description": "A bare CREATE2 on an empty stack inside a STATICCALL (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce6302faf080fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0xf500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/create_static_low_gas.json b/crates/mega-differential/scenarios/harness/create_static_low_gas.json deleted file mode 100644 index 365bb5d81..000000000 --- a/crates/mega-differential/scenarios/harness/create_static_low_gas.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "create_static_low_gas", - "description": "CREATE with empty initcode inside a STATICCALL that forwards 10,000 gas (ported from the legacy suite).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0x8ac7230489e80000" - }, - "0x00000000000000000000000000000000000005c2": { - "code": "0x60006000600060007300000000000000000000000000000000000005ce612710fa60005500", - "storage": { - "0x0": "0x7" - } - }, - "0x00000000000000000000000000000000000005ce": { - "code": "0x600060006000f000" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x00000000000000000000000000000000000005c2", - "data": "0x", - "value": "0x0", - "gas_limit": 100000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json b/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json deleted file mode 100644 index 4eade90e3..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_authority_with_code.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "eip7702_authority_with_code", - "description": "The authority is a contract with ordinary code: the authorization is skipped and the contract code runs.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - }, - "0x0000000000000000000000000000000000000a11": { - "nonce": 1, - "code": "0x600560055500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 1, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json b/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json deleted file mode 100644 index 2f4672d31..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_call_into_delegated_account.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "eip7702_call_into_delegated_account", - "description": "A legacy transaction calls a delegated account directly, then a contract calls it and reads its EXTCODESIZE and EXTCODEHASH (those of the designator).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - }, - "0x0000000000000000000000000000000000000a11": { - "nonce": 1, - "code": "0xef01000000000000000000000000000000000000000de1" - }, - "0x0000000000000000000000000000000000000b0b": { - "code": "0x60006000600060006000730000000000000000000000000000000000000a115af1600055730000000000000000000000000000000000000a113b600155730000000000000000000000000000000000000a113f60025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000b0b", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json b/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json deleted file mode 100644 index a04ebdad0..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_chain_id_mismatch.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "eip7702_chain_id_mismatch", - "description": "The authorization names another chain: it is skipped. A second authorization with chain id 0 (any chain) applies.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x7", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - }, - { - "chain_id": "0x0", - "address": "0x0000000000000000000000000000000000000de2", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json b/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json deleted file mode 100644 index dda065264..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_delegate_existing_authority.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "eip7702_delegate_existing_authority", - "description": "The authority exists with nonce 3 and a balance: the authorization applies with the existing-account refund.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - }, - "0x0000000000000000000000000000000000000a11": { - "nonce": 3, - "balance": "0x5" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 3, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json b/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json deleted file mode 100644 index 964eb05c3..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_delegate_new_authority.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "eip7702_delegate_new_authority", - "description": "The authority does not exist: the authorization creates it with the delegation designator and nonce 1, and the call to it runs the delegate's code in its context.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json b/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json deleted file mode 100644 index 1859817bb..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_delegation_to_precompile.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "eip7702_delegation_to_precompile", - "description": "The authority delegates to the identity precompile: calling it runs no code.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x0102", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000004", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json b/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json deleted file mode 100644 index 48c822a8b..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_invalid_signature.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "eip7702_invalid_signature", - "description": "The signature does not recover: the authorization is skipped and the call runs on an empty account.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 0 - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json b/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json deleted file mode 100644 index a9bb114d0..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_nonce_mismatch.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "eip7702_nonce_mismatch", - "description": "The authorization's nonce is not the authority's: it is skipped.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - }, - "0x0000000000000000000000000000000000000a11": { - "nonce": 2, - "balance": "0x5" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 5, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json b/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json deleted file mode 100644 index 4d3fd7974..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_redelegate_and_clear.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "eip7702_redelegate_and_clear", - "description": "The authority is delegated to one contract; the first transaction re-delegates it to another, the second clears the delegation with the zero address.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - }, - "0x0000000000000000000000000000000000000a11": { - "nonce": 1, - "code": "0xef01000000000000000000000000000000000000000de1" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de2", - "nonce": 1, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000000", - "nonce": 2, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json b/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json deleted file mode 100644 index a7da16880..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_self_sponsored.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "eip7702_self_sponsored", - "description": "The sender authorizes its own account: the sender's nonce is bumped before the authorization is checked, so the authorization carries nonce 1.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000aaa", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 1, - "authority": "0x0000000000000000000000000000000000000aaa" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json b/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json deleted file mode 100644 index 159ef174f..000000000 --- a/crates/mega-differential/scenarios/harness/eip7702_two_authorizations_same_authority.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "eip7702_two_authorizations_same_authority", - "description": "Two authorizations for one authority with consecutive nonces: both apply, the last one wins.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - }, - "0x0000000000000000000000000000000000000de2": { - "code": "0x600760025500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - }, - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de2", - "nonce": 1, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json b/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json deleted file mode 100644 index 4fae32668..000000000 --- a/crates/mega-differential/scenarios/harness/equivalence_empty_transaction.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "equivalence_empty_transaction", - "description": "An empty call whose gas limit exceeds the execution cap by 1,000,000: the excess goes to the EIP-8037 reservoir and, with no state gas drawn, is left over (equivalence.rs).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": {}, - "txs": [ - { - "caller": "0x4000000000000000000000000000000000000001", - "to": "0x5000000000000000000000000000000000000001", - "data": "0x", - "value": "0x0", - "gas_limit": 201000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/equivalence_sstore.json b/crates/mega-differential/scenarios/harness/equivalence_sstore.json deleted file mode 100644 index 20abeb11a..000000000 --- a/crates/mega-differential/scenarios/harness/equivalence_sstore.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "equivalence_sstore", - "description": "SSTORE(0, 42) into a fresh slot; the Osaka gas table prices no state gas (equivalence.rs).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x5000000000000000000000000000000000000001": { - "code": "0x602a60005500" - } - }, - "txs": [ - { - "caller": "0x4000000000000000000000000000000000000001", - "to": "0x5000000000000000000000000000000000000001", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json b/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json deleted file mode 100644 index 9939c02e3..000000000 --- a/crates/mega-differential/scenarios/harness/equivalence_value_transfer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "equivalence_value_transfer", - "description": "A 1,000 wei transfer to an account that does not exist (equivalence.rs).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x4000000000000000000000000000000000000001": { - "balance": "0xde0b6b3a7640000" - } - }, - "txs": [ - { - "caller": "0x4000000000000000000000000000000000000001", - "to": "0x5000000000000000000000000000000000000001", - "data": "0x", - "value": "0x3e8", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_access_list.json b/crates/mega-differential/scenarios/harness/fee_access_list.json deleted file mode 100644 index 25c14ffb5..000000000 --- a/crates/mega-differential/scenarios/harness/fee_access_list.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "fee_access_list", - "description": "An EIP-2930 transaction at 4 gwei.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000ead": { - "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", - "storage": { - "0x0": "0x1", - "0x1": "0x2" - } - }, - "0x00000000000000000000000000000000000000e4": { - "balance": "0x3" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x0000000000000000000000000000000000000ead", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 4000000000, - "access_list": [ - { - "address": "0x0000000000000000000000000000000000000ead", - "storage_keys": [ - "0x0", - "0x2" - ] - }, - { - "address": "0x00000000000000000000000000000000000000e4", - "storage_keys": [] - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json b/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json deleted file mode 100644 index 1547e5975..000000000 --- a/crates/mega-differential/scenarios/harness/fee_balance_below_max_fee.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "fee_balance_below_max_fee", - "description": "The sender holds less than gas limit times gas price: the transaction is rejected before execution.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0x38d7ea4c68000" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x0000000000000000000000000000000000000b0d", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 10000000000 - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_eip7702.json b/crates/mega-differential/scenarios/harness/fee_eip7702.json deleted file mode 100644 index f5bbded02..000000000 --- a/crates/mega-differential/scenarios/harness/fee_eip7702.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "fee_eip7702", - "description": "An EIP-7702 transaction at 2 gwei, max fee and priority fee equal.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000de1": { - "code": "0x602a6000553060015500" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x0000000000000000000000000000000000000a11", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 2000000000, - "authorization_list": [ - { - "chain_id": "0x1", - "address": "0x0000000000000000000000000000000000000de1", - "nonce": 0, - "authority": "0x0000000000000000000000000000000000000a11" - } - ] - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json b/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json deleted file mode 100644 index 8a9f3f407..000000000 --- a/crates/mega-differential/scenarios/harness/fee_reservoir_refund.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "fee_reservoir_refund", - "description": "An empty call at 1 gwei with a gas limit 1,000,000 over the execution cap: the unused reservoir and the unused regular gas are both refunded to the sender.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x0000000000000000000000000000000000000b0d", - "data": "0x", - "value": "0x0", - "gas_limit": 201000000, - "kind": "call", - "gas_price": 1000000000 - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_revert.json b/crates/mega-differential/scenarios/harness/fee_revert.json deleted file mode 100644 index 5b09b0ad4..000000000 --- a/crates/mega-differential/scenarios/harness/fee_revert.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "fee_revert", - "description": "A call that reverts at 2 gwei: the sender pays for the gas used, the value stays.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - }, - "0x00000000000000000000000000000000000008e7": { - "code": "0x600160005560006000fd" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x00000000000000000000000000000000000008e7", - "data": "0x", - "value": "0x9", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 2000000000 - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json b/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json deleted file mode 100644 index c4c74c3fa..000000000 --- a/crates/mega-differential/scenarios/harness/fee_sstore_clear_refund.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "fee_sstore_clear_refund", - "description": "Clearing a storage slot at 3 gwei: the clearing refund lowers what the sender pays.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - }, - "0x000000000000000000000000000000000000c1ea": { - "code": "0x600060005500", - "storage": { - "0x0": "0x5" - } - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x000000000000000000000000000000000000c1ea", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 3000000000 - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/fee_value_transfer.json b/crates/mega-differential/scenarios/harness/fee_value_transfer.json deleted file mode 100644 index 43cdf3f3c..000000000 --- a/crates/mega-differential/scenarios/harness/fee_value_transfer.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "fee_value_transfer", - "description": "A 1,000 wei transfer at 7 gwei: the sender pays value and gas, the coinbase gets the fee.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x000000000000000000000000000000000000fee0": { - "balance": "0xde0b6b3a7640000" - } - }, - "txs": [ - { - "caller": "0x000000000000000000000000000000000000fee0", - "to": "0x0000000000000000000000000000000000000b0d", - "data": "0x", - "value": "0x3e8", - "gas_limit": 1000000, - "kind": "call", - "gas_price": 7000000000 - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json b/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json deleted file mode 100644 index bb77d6ecd..000000000 --- a/crates/mega-differential/scenarios/harness/logs_all_topic_counts.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "logs_all_topic_counts", - "description": "One LOG0 to LOG4 each, with data from memory.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000106": { - "code": "0x7f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2060005260206000a0600160206000a16002600160106000a260036002600160006000a3600460036002600160086018a400" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000106", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json b/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json deleted file mode 100644 index ebd0cd5ce..000000000 --- a/crates/mega-differential/scenarios/harness/logs_discarded_by_reverted_subcall.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "logs_discarded_by_reverted_subcall", - "description": "A sub-call logs and reverts: its log is dropped, the caller's logs before and after stay.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000106": { - "code": "0x60cd60005360016000a0600060006000600060007300000000000000000000000000000000000001075af160005560ef600053600760016000a100" - }, - "0x0000000000000000000000000000000000000107": { - "code": "0x60ab60005360016000a060006000fd" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000106", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_blake2f.json b/crates/mega-differential/scenarios/harness/precompile_blake2f.json deleted file mode 100644 index 657ac87df..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_blake2f.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "precompile_blake2f", - "description": "BLAKE2 F with the EIP-152 test vector (12 rounds over \"abc\"), then with a bad final-block flag.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009909": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000095afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009909", - "data": "0x0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009909", - "data": "0x0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000002", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json b/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json deleted file mode 100644 index 19686c6bb..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_bls12_g1add_and_map.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "precompile_bls12_g1add_and_map", - "description": "BLS12-381 G1 addition of two points at infinity, and mapping the field element 0 to G1.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x000000000000000000000000000000000000990b": { - "code": "0x3660006000376000600036600073000000000000000000000000000000000000000b5afa6000553d6001553d600060003e3d6000206002553d6000f3" - }, - "0x0000000000000000000000000000000000009910": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000105afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x000000000000000000000000000000000000990b", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009910", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_add.json b/crates/mega-differential/scenarios/harness/precompile_bn254_add.json deleted file mode 100644 index c1695ae6b..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_bn254_add.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_bn254_add", - "description": "BN254 addition of the generator to itself.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009906": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000065afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009906", - "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json b/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json deleted file mode 100644 index 1e751f914..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_bn254_mul_and_pairing.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "precompile_bn254_mul_and_pairing", - "description": "BN254 multiplication of the generator by 2, and a pairing check of the empty input.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009907": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000075afa6000553d6001553d600060003e3d6000206002553d6000f3" - }, - "0x0000000000000000000000000000000000009908": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009907", - "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009908", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json deleted file mode 100644 index bd6a4064b..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_at_op_input_limit.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_bn254_pairing_at_op_input_limit", - "description": "A BN254 pairing of 300 pairs of points at infinity, 57,600 bytes: the most op-revm's Karst pairing accepts.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009908": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009908", - "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 30000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json b/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json deleted file mode 100644 index 247e4243c..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_bn254_pairing_over_op_input_limit.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_bn254_pairing_over_op_input_limit", - "description": "A BN254 pairing of 301 pairs of points at infinity, 57,792 bytes: over the input bound op-revm's Karst pairing enforces, which Ethereum's does not have.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009908": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000085afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009908", - "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 30000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_ecrecover.json b/crates/mega-differential/scenarios/harness/precompile_ecrecover.json deleted file mode 100644 index 4f47989bf..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_ecrecover.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "precompile_ecrecover", - "description": "ecrecover on a valid signature, then on one with v = 29.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009901": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000015afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009901", - "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001c9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009901", - "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001d9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_modexp.json b/crates/mega-differential/scenarios/harness/precompile_modexp.json deleted file mode 100644 index 507d63dce..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_modexp.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "precompile_modexp", - "description": "modexp 3^5 mod 7 with one-byte operands, then with a 64-byte exponent (the Osaka pricing).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009905": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000055afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009905", - "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001030507", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009905", - "data": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000103ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_p256verify.json b/crates/mega-differential/scenarios/harness/precompile_p256verify.json deleted file mode 100644 index 02f26260d..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_p256verify.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "precompile_p256verify", - "description": "P256VERIFY on 160 zero bytes (an invalid signature) and on a short input.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009a00": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000001005afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009a00", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009a00", - "data": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json deleted file mode 100644 index 53239dfbb..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_invalid.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_point_evaluation_invalid", - "description": "KZG point evaluation on 192 zero bytes: the versioned hash does not match, the call fails.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x000000000000000000000000000000000000990a": { - "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x000000000000000000000000000000000000990a", - "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json deleted file mode 100644 index 3a4c46728..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_valid.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_point_evaluation_valid", - "description": "KZG point evaluation on a valid proof: the versioned hash matches the commitment and verification succeeds, so the call returns FIELD_ELEMENTS_PER_BLOB and the BLS modulus.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x000000000000000000000000000000000000990a": { - "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x000000000000000000000000000000000000990a", - "data": "0x01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff000000001522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e98f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json b/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json deleted file mode 100644 index b71be9041..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_point_evaluation_wrong_proof.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_point_evaluation_wrong_proof", - "description": "KZG point evaluation with the versioned hash of the commitment but the commitment repeated in place of the proof: a well-formed curve point that is not the proof, so the call reaches verification and fails there.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x000000000000000000000000000000000000990a": { - "code": "0x3660006000376000600036600073000000000000000000000000000000000000000a5afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x000000000000000000000000000000000000990a", - "data": "0x01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff000000001522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e98f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b78f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json b/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json deleted file mode 100644 index c4d6165f5..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_ripemd160_and_identity.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "precompile_ripemd160_and_identity", - "description": "RIPEMD-160 and identity on 100 bytes, each through its own proxy.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009903": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000035afa6000553d6001553d600060003e3d6000206002553d6000f3" - }, - "0x0000000000000000000000000000000000009904": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000045afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009903", - "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - }, - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009904", - "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/precompile_sha256.json b/crates/mega-differential/scenarios/harness/precompile_sha256.json deleted file mode 100644 index c4b432deb..000000000 --- a/crates/mega-differential/scenarios/harness/precompile_sha256.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "precompile_sha256", - "description": "SHA-256 on 100 bytes.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000009902": { - "code": "0x366000600037600060003660007300000000000000000000000000000000000000025afa6000553d6001553d600060003e3d6000206002553d6000f3" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000009902", - "data": "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f60616263", - "value": "0x0", - "gas_limit": 5000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json b/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json deleted file mode 100644 index 48f436af1..000000000 --- a/crates/mega-differential/scenarios/harness/selfdestruct_created_in_same_tx_to_existing_account.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "selfdestruct_created_in_same_tx_to_existing_account", - "description": "A contract created in the transaction self-destructs to an existing account from its init code: it is destroyed and the beneficiary gets its endowment.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000fac": { - "balance": "0x64", - "code": "0x3660006000373660006007f060005500" - }, - "0x0000000000000000000000000000000000000bee": { - "balance": "0x5" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000fac", - "data": "0x730000000000000000000000000000000000000beeff", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json b/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json deleted file mode 100644 index d99cc30f0..000000000 --- a/crates/mega-differential/scenarios/harness/selfdestruct_in_static_context.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "selfdestruct_in_static_context", - "description": "SELFDESTRUCT under STATICCALL halts the callee; the caller records the failure.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000d35": { - "balance": "0x3e8", - "code": "0x730000000000000000000000000000000000000beeff" - }, - "0x0000000000000000000000000000000000000bee": { - "balance": "0x5" - }, - "0x000000000000000000000000000000000000057a": { - "code": "0x6000600060006000730000000000000000000000000000000000000d355afa60005500" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x000000000000000000000000000000000000057a", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json deleted file mode 100644 index 5839af49a..000000000 --- a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_account.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "selfdestruct_to_existing_account", - "description": "A contract that predates the transaction self-destructs to an existing funded account: its balance moves, the contract stays (EIP-6780).", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000d35": { - "balance": "0x3e8", - "code": "0x730000000000000000000000000000000000000beeff" - }, - "0x0000000000000000000000000000000000000bee": { - "balance": "0x5" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000d35", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json deleted file mode 100644 index f1f7b23a2..000000000 --- a/crates/mega-differential/scenarios/harness/selfdestruct_to_existing_contract.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "selfdestruct_to_existing_contract", - "description": "The beneficiary is a contract with code and storage; its code does not run.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000d35": { - "balance": "0x3e8", - "code": "0x730000000000000000000000000000000000000becff" - }, - "0x0000000000000000000000000000000000000bec": { - "code": "0x600160005500", - "storage": { - "0x3": "0x3" - } - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000d35", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json b/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json deleted file mode 100644 index 55a59a7d7..000000000 --- a/crates/mega-differential/scenarios/harness/selfdestruct_to_self.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "selfdestruct_to_self", - "description": "A contract that predates the transaction self-destructs to itself: the balance stays.", - "coinbase": "0x0000000000000000000000000000000000000c01", - "pre": { - "0x0000000000000000000000000000000000000aaa": { - "balance": "0xde0b6b3a7640000" - }, - "0x0000000000000000000000000000000000000d35": { - "balance": "0x3e8", - "code": "0x730000000000000000000000000000000000000d35ff" - } - }, - "txs": [ - { - "caller": "0x0000000000000000000000000000000000000aaa", - "to": "0x0000000000000000000000000000000000000d35", - "data": "0x", - "value": "0x0", - "gas_limit": 1000000, - "kind": "call" - } - ] -} diff --git a/crates/mega-differential/src/diff.rs b/crates/mega-differential/src/diff.rs deleted file mode 100644 index f1e9524fb..000000000 --- a/crates/mega-differential/src/diff.rs +++ /dev/null @@ -1,172 +0,0 @@ -//! Field-by-field comparison of two scenario records. - -use std::{collections::BTreeSet, fmt::Display}; - -use crate::record::{AccountRecord, ScenarioRecord, TxRecord, ABSENT}; - -/// One field on which the two arms disagree. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Difference { - /// Scenario name. - pub scenario: String, - /// Field path, e.g. `tx[0].gas.gas_spent` or `tx[1].state[0x…].storage[0x1]`. - pub field: String, - /// The value `MegaEvm` reported. - pub left: String, - /// The value the oracle reported. - pub right: String, -} - -/// The differences between two records of one scenario, and how many fields were compared. -#[derive(Debug, Default)] -pub struct Comparison { - /// Scenario name. - pub scenario: String, - /// Fields on which the arms disagree. - pub differences: Vec, - /// Number of fields compared. - pub compared: usize, -} - -impl Comparison { - fn field(&mut self, field: String, left: T, right: T) { - self.compared += 1; - if left != right { - self.differences.push(Difference { - scenario: self.scenario.clone(), - field, - left: left.to_string(), - right: right.to_string(), - }); - } - } -} - -/// Compares the record `MegaEvm` produced (`left`) with the oracle's (`right`). -pub fn compare(scenario: &str, left: &ScenarioRecord, right: &ScenarioRecord) -> Comparison { - let mut cmp = Comparison { scenario: scenario.to_string(), ..Default::default() }; - cmp.field("tx_count".into(), left.len(), right.len()); - for (i, (l, r)) in left.iter().zip(right).enumerate() { - compare_tx(&mut cmp, &format!("tx[{i}]"), l, r); - } - cmp -} - -fn compare_tx(cmp: &mut Comparison, at: &str, l: &TxRecord, r: &TxRecord) { - cmp.field(format!("{at}.outcome"), &l.outcome, &r.outcome); - for name in l.gas.keys().chain(r.gas.keys()).collect::>() { - cmp.field(format!("{at}.gas.{name}"), render(l.gas.get(name)), render(r.gas.get(name))); - } - cmp.field(format!("{at}.output"), &l.output, &r.output); - cmp.field( - format!("{at}.created"), - render(l.created.map(|address| format!("{address:#x}"))), - render(r.created.map(|address| format!("{address:#x}"))), - ); - cmp.field(format!("{at}.logs.len"), l.logs.len(), r.logs.len()); - for (j, (ll, rl)) in l.logs.iter().zip(&r.logs).enumerate() { - cmp.field(format!("{at}.logs[{j}]"), ll.render(), rl.render()); - } - for address in l.state.keys().chain(r.state.keys()).collect::>() { - let path = format!("{at}.state[{address:#x}]"); - match (l.state.get(address), r.state.get(address)) { - (Some(la), Some(ra)) => compare_account(cmp, &path, la, ra), - (la, ra) => cmp.field( - path, - la.map_or_else(|| ABSENT.to_string(), AccountRecord::render), - ra.map_or_else(|| ABSENT.to_string(), AccountRecord::render), - ), - } - } -} - -fn compare_account(cmp: &mut Comparison, at: &str, l: &AccountRecord, r: &AccountRecord) { - cmp.field(format!("{at}.created"), l.created, r.created); - cmp.field(format!("{at}.selfdestructed"), l.selfdestructed, r.selfdestructed); - cmp.field(format!("{at}.balance"), l.balance, r.balance); - cmp.field(format!("{at}.nonce"), l.nonce, r.nonce); - cmp.field(format!("{at}.code_hash"), l.code_hash, r.code_hash); - for slot in l.storage.keys().chain(r.storage.keys()).collect::>() { - cmp.field( - format!("{at}.storage[{slot:#x}]"), - render(l.storage.get(slot).map(|value| format!("{value:#x}"))), - render(r.storage.get(slot).map(|value| format!("{value:#x}"))), - ); - } -} - -/// Renders an optional value, with [`ABSENT`] for `None`. -fn render(value: Option) -> String { - value.map_or_else(|| ABSENT.to_string(), |value| value.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::record::LogRecord; - use alloy_primitives::{address, Address, Bytes, U256}; - use std::collections::BTreeMap; - - const A: Address = address!("0x0000000000000000000000000000000000000aaa"); - - fn tx() -> TxRecord { - TxRecord { - outcome: "success".into(), - gas: BTreeMap::from([("gas_spent".to_string(), 21_000)]), - state: BTreeMap::from([(A, AccountRecord { nonce: 1, ..Default::default() })]), - ..Default::default() - } - } - - #[test] - fn test_compare_equal_records_reports_nothing() { - let cmp = compare("s", &vec![tx()], &vec![tx()]); - assert!(cmp.differences.is_empty()); - // tx_count, outcome, one gas field, output, created, logs.len, five account fields. - assert_eq!(cmp.compared, 11); - } - - #[test] - fn test_compare_reports_each_differing_field() { - let mut right = tx(); - right.gas.insert("gas_spent".into(), 21_001); - right.gas.insert("reservoir_remaining".into(), 0); - right.state.get_mut(&A).unwrap().storage.insert(U256::from(1), U256::from(2)); - right.logs.push(LogRecord { address: A, topics: vec![], data: Bytes::new() }); - - let fields: Vec<(String, String, String)> = compare("s", &vec![tx()], &vec![right]) - .differences - .into_iter() - .map(|d| (d.field, d.left, d.right)) - .collect(); - - let at = format!("tx[0].state[{A:#x}]"); - assert_eq!( - fields, - vec![ - ("tx[0].gas.gas_spent".into(), "21000".into(), "21001".into()), - ("tx[0].gas.reservoir_remaining".into(), ABSENT.into(), "0".into()), - ("tx[0].logs.len".into(), "0".into(), "1".into()), - (format!("{at}.storage[0x1]"), ABSENT.into(), "0x2".into()), - ] - ); - } - - #[test] - fn test_compare_reports_an_account_only_one_arm_touched() { - let mut right = tx(); - right.state.clear(); - let differences = compare("s", &vec![tx()], &vec![right]).differences; - assert_eq!(differences.len(), 1); - assert_eq!(differences[0].field, "tx[0].state[0x0000000000000000000000000000000000000aaa]"); - assert!(differences[0].left.contains("nonce=1")); - assert_eq!(differences[0].right, ABSENT); - } - - #[test] - fn test_compare_reports_a_missing_transaction() { - let differences = compare("s", &vec![tx(), tx()], &vec![tx()]).differences; - assert_eq!(differences.len(), 1); - assert_eq!((differences[0].left.as_str(), differences[0].right.as_str()), ("2", "1")); - } -} diff --git a/crates/mega-differential/src/lib.rs b/crates/mega-differential/src/lib.rs deleted file mode 100644 index b50b608e2..000000000 --- a/crates/mega-differential/src/lib.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Differential harness of the Satin engine. -//! -//! Runs every scenario of a corpus through `MegaEvm` (the left arm) and through stock revm 43 on -//! its mainnet handler (the right arm, the oracle), and compares what they report field by -//! field: every gas figure, the outcome, the output, the logs and every touched account. Each -//! difference must be explained by an active entry of the deviation registry, and every effect -//! an active entry lists must explain at least one difference. -//! -//! See the crate README for the corpus, the registry and how the two revms coexist. - -use std::{ - collections::{BTreeMap, BTreeSet}, - fmt::Write as _, - fs, - path::{Path, PathBuf}, -}; - -use mega_evm::test_utils::Scenario; - -#[macro_use] -pub mod record; -pub mod diff; -pub mod mega; -pub mod oracle; -pub mod registry; - -use diff::Difference; -use registry::{EffectRef, Registry}; - -/// Directory of the corpus, one subdirectory per origin. -pub fn corpus_dir() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("scenarios") -} - -/// Path of the deviation registry. -pub fn registry_path() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("deviations.json") -} - -/// Loads every `*.json` scenario under `dir` (recursively), sorted by path. -/// -/// Every scenario must be valid, its name must be its file stem, and names must be unique. -pub fn load_corpus(dir: &Path) -> Result, String> { - let mut paths = Vec::new(); - collect_json(dir, &mut paths)?; - paths.sort(); - let mut names = BTreeMap::new(); - let mut scenarios = Vec::with_capacity(paths.len()); - for path in paths { - let text = fs::read_to_string(&path).map_err(|err| format!("{}: {err}", path.display()))?; - let scenario: Scenario = - serde_json::from_str(&text).map_err(|err| format!("{}: {err}", path.display()))?; - scenario.validate()?; - if path.file_stem().and_then(|stem| stem.to_str()) != Some(scenario.name.as_str()) { - return Err(format!("{}: the name must be the file stem", path.display())); - } - if let Some(other) = names.insert(scenario.name.clone(), path.clone()) { - return Err(format!("{}: name already used by {}", path.display(), other.display())); - } - scenarios.push(scenario); - } - Ok(scenarios) -} - -fn collect_json(dir: &Path, out: &mut Vec) -> Result<(), String> { - let entries = fs::read_dir(dir).map_err(|err| format!("{}: {err}", dir.display()))?; - for entry in entries { - let path = entry.map_err(|err| format!("{}: {err}", dir.display()))?.path(); - if path.is_dir() { - collect_json(&path, out)?; - } else if path.extension().is_some_and(|ext| ext == "json") { - out.push(path); - } - } - Ok(()) -} - -/// The outcome of a differential run. -#[derive(Debug, Default)] -pub struct Report { - /// Number of scenarios run. - pub scenarios: usize, - /// Number of fields compared. - pub compared: usize, - /// Differences an active registry entry explains, by entry id. - pub explained: BTreeMap>, - /// Differences no active entry explains, with the retired entry that would have, if any. - pub unexplained: Vec<(Difference, Option)>, - /// Effects of active entries that explained nothing, with their field pattern. - pub stale: Vec<(EffectRef, String)>, -} - -impl Report { - /// Whether every difference is explained and every effect of every active entry explained - /// one. - pub fn is_clean(&self) -> bool { - self.unexplained.is_empty() && self.stale.is_empty() - } - - /// The one-line summary printed at the end of a run. - pub fn summary(&self) -> String { - let matched: usize = self.explained.values().map(Vec::len).sum(); - let by_entry: Vec = - self.explained.iter().map(|(id, diffs)| format!("{id} x{}", diffs.len())).collect(); - format!( - "differential: {} scenarios, {} fields compared, {} deviations matched{}, {} unexplained, {} stale registry effects", - self.scenarios, - self.compared, - matched, - if by_entry.is_empty() { String::new() } else { format!(" ({})", by_entry.join(", ")) }, - self.unexplained.len(), - self.stale.len(), - ) - } - - /// Every unexplained difference and stale effect, one per line. - pub fn failures(&self) -> String { - let mut out = String::new(); - for (diff, retired) in &self.unexplained { - let _ = write!( - out, - "unexplained: {} {}: mega={} oracle={}", - diff.scenario, diff.field, diff.left, diff.right - ); - if let Some(id) = retired { - let _ = write!(out, " (matches retired entry {id})"); - } - out.push('\n'); - } - for ((id, i), field) in &self.stale { - let _ = - writeln!(out, "stale: effect {i} ({field}) of active entry {id} explained nothing"); - } - out - } -} - -/// Runs every scenario through both arms and checks the differences against `registry`. -pub fn run(scenarios: &[Scenario], registry: &Registry) -> Report { - let comparisons = parallel_map(scenarios, |scenario| { - diff::compare(&scenario.name, &mega::run(scenario), &oracle::run(scenario)) - }); - check(comparisons, registry) -} - -/// Checks the comparisons of a run against `registry`. -pub fn check(comparisons: Vec, registry: &Registry) -> Report { - let mut report = Report { scenarios: comparisons.len(), ..Default::default() }; - let mut hit = BTreeSet::new(); - for comparison in comparisons { - report.compared += comparison.compared; - for difference in comparison.differences { - match registry.explain(&difference) { - Some(effect) => { - report.explained.entry(effect.0.clone()).or_default().push(difference); - hit.insert(effect); - } - None => { - let retired = registry.retired_match(&difference).map(|(id, _)| id); - report.unexplained.push((difference, retired)); - } - } - } - } - report.stale = registry - .active_effects() - .filter(|(effect, _)| !hit.contains(effect)) - .map(|(effect, spec)| (effect, spec.field.clone())) - .collect(); - report -} - -/// Maps `f` over `items` on all available cores, keeping the order. -fn parallel_map(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec { - let threads = std::thread::available_parallelism().map_or(1, usize::from); - let chunk = items.len().div_ceil(threads).max(1); - std::thread::scope(|scope| { - let handles: Vec<_> = items - .chunks(chunk) - .map(|chunk| scope.spawn(|| chunk.iter().map(&f).collect::>())) - .collect(); - handles.into_iter().flat_map(|handle| handle.join().expect("scenario panicked")).collect() - }) -} - -/// The `u64` fields of `value` as it serializes to a JSON object, by serialized name. -/// -/// Both arms read `ResultGas` through this, so a field the fork adds shows up on the left arm -/// as a difference until the oracle reports the same figure or the registry explains it. -fn serialized_u64_fields(value: &impl serde::Serialize) -> BTreeMap { - let serde_json::Value::Object(fields) = serde_json::to_value(value).expect("serializable") - else { - panic!("expected a JSON object"); - }; - fields - .into_iter() - .map(|(name, value)| { - let value = value.as_u64().unwrap_or_else(|| panic!("{name} is not a u64: {value}")); - (name, value) - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use diff::Comparison; - - fn registry() -> Registry { - Registry::from_json( - r#"{"version": 1, "deviations": [ - {"id": "fee", "status": "active", "scenario": "*", "mechanism": "m", "reason": "r", - "effects": [ - {"field": "tx[*].gas.gas_spent", "left": "2", "right": "1"}, - {"field": "tx[*].output", "left": "0x", "right": "0x01"}]}, - {"id": "old", "status": "retired", "scenario": "*", "mechanism": "m", "reason": "r", - "retired_reason": "gone", - "effects": [{"field": "tx[*].logs.len", "left": "*", "right": "*"}]} - ]}"#, - ) - .unwrap() - } - - fn comparison(diffs: &[(&str, &str, &str)]) -> Comparison { - Comparison { - scenario: "s".into(), - differences: diffs - .iter() - .map(|(field, left, right)| Difference { - scenario: "s".into(), - field: (*field).into(), - left: (*left).into(), - right: (*right).into(), - }) - .collect(), - compared: 10, - } - } - - #[test] - fn test_check_is_clean_when_every_difference_and_effect_is_matched() { - let report = check( - vec![ - comparison(&[("tx[0].gas.gas_spent", "2", "1")]), - comparison(&[("tx[1].output", "0x", "0x01")]), - ], - ®istry(), - ); - assert!(report.is_clean(), "{}", report.failures()); - assert_eq!((report.scenarios, report.compared), (2, 20)); - assert_eq!(report.explained["fee"].len(), 2); - } - - #[test] - fn test_check_fails_on_an_unexplained_difference() { - let report = check( - vec![comparison(&[ - ("tx[0].gas.gas_spent", "2", "1"), - ("tx[0].output", "0x", "0x01"), - ("tx[0].gas.gas_spent", "3", "1"), - ("tx[0].logs.len", "1", "0"), - ])], - ®istry(), - ); - assert!(!report.is_clean()); - assert!(report.stale.is_empty()); - let failures = report.failures(); - assert!(failures.contains("unexplained: s tx[0].gas.gas_spent: mega=3 oracle=1\n")); - assert!(failures.contains("tx[0].logs.len: mega=1 oracle=0 (matches retired entry old)")); - } - - #[test] - fn test_check_fails_on_an_effect_that_explains_nothing() { - let report = check(vec![comparison(&[("tx[0].gas.gas_spent", "2", "1")])], ®istry()); - assert!(!report.is_clean()); - assert!(report.unexplained.is_empty()); - assert_eq!(report.stale, vec![(("fee".to_string(), 1), "tx[*].output".to_string())]); - } -} diff --git a/crates/mega-differential/src/mega.rs b/crates/mega-differential/src/mega.rs deleted file mode 100644 index 1646fa834..000000000 --- a/crates/mega-differential/src/mega.rs +++ /dev/null @@ -1,46 +0,0 @@ -//! The left arm: `MegaEvm`, configured as the Satin spec fixes it. - -use mega_evm::{ - alloy_op_evm::OpTxError, - op_revm::{OpHaltReason, OpTransactionError}, - revm::context::result::{EVMError, ExecutionResult}, - test_utils::{Scenario, ScenarioTxOutcome}, -}; - -use crate::record::{ScenarioRecord, TxRecord}; - -/// Runs `scenario` on `MegaEvm` and records every transaction. -pub fn run(scenario: &Scenario) -> ScenarioRecord { - let (outcomes, _db) = scenario.run(scenario.database()); - outcomes.iter().map(record).collect() -} - -fn record(outcome: &ScenarioTxOutcome) -> TxRecord { - match outcome { - // `ResultGas` serializes `reservoir_remaining` on the fork. - Ok(outcome) => tx_record!(ExecutionResult, &outcome.result, &outcome.state, halt, None), - Err(err) => TxRecord { outcome: format!("error:{}", error(err)), ..Default::default() }, - } -} - -/// The halt reason with the OP wrapper taken off: op-revm wraps every Ethereum halt reason in -/// `OpHaltReason::Base`, which is naming, not behavior. A halt reason of op-revm's own keeps an -/// `op:` prefix. -fn halt(reason: &OpHaltReason) -> String { - match reason { - OpHaltReason::Base(reason) => format!("{reason:?}"), - other => format!("op:{other:?}"), - } -} - -/// The error with the OP wrappers taken off, the same way as [`halt`]. -fn error(err: &EVMError) -> String { - match err { - EVMError::Transaction(OpTxError(OpTransactionError::Base(invalid))) => { - format!("invalid:{invalid:?}") - } - EVMError::Transaction(OpTxError(other)) => format!("op:{other:?}"), - EVMError::Header(header) => format!("header:{header:?}"), - other => format!("other:{other:?}"), - } -} diff --git a/crates/mega-differential/src/oracle.rs b/crates/mega-differential/src/oracle.rs deleted file mode 100644 index 963e35fcb..000000000 --- a/crates/mega-differential/src/oracle.rs +++ /dev/null @@ -1,331 +0,0 @@ -//! The right arm: stock revm 43 on its mainnet handler. -//! -//! The oracle takes its configuration from `MegaEvm`'s, field by field: the same Ethereum spec, -//! the same gas table (copied entry by entry), the same switches. It has no OP layer, so the -//! differences an OP-specific mechanism makes are the registry's to explain. - -use std::{cell::Cell, convert::Infallible, str::FromStr}; - -use mega_evm::{ - revm::context::{transaction::TransactionType as ScenarioTxType, CfgEnv as MegaCfgEnv}, - test_utils::{Scenario, ScenarioTxKind}, - MegaContext, MegaSpecId, -}; -use revm_oracle::{ - context::{ - result::{EVMError, ExecutionResult, HaltReason, ResultGas}, - transaction::{ - AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization, - }, - BlockEnv, CfgEnv, ContextSetters, ContextTr, JournalTr, TxEnv, - }, - context_interface::cfg::GasParams, - database::{CacheDB, EmptyDB}, - handler::{ - system_call::SystemCallTx, EthFrame, EvmTr, FrameResult, FrameTr, Handler, MainnetHandler, - }, - interpreter::interpreter::EthInterpreter, - primitives::{hardfork::SpecId, TxKind}, - state::{AccountInfo, Bytecode, EvmState}, - Context, Database, DatabaseCommit, MainBuilder, MainContext, MainnetEvm, -}; - -use crate::record::{ScenarioRecord, TxRecord}; - -type OracleDb = CacheDB; -type OracleEvm<'a> = MainnetEvm>; -type OracleError = EVMError; - -/// Runs `scenario` on revm 43 and records every transaction. -pub fn run(scenario: &Scenario) -> ScenarioRecord { - let cfg = cfg(); - let block = block(scenario); - let mut db = database(scenario); - let mut records = Vec::with_capacity(scenario.txs.len()); - for tx in &scenario.txs { - let mut evm = Context::mainnet() - .with_db(&mut db) - .with_cfg(cfg.clone()) - .with_block(block.clone()) - .build_mainnet(); - let mut probe = ReservoirProbe::default(); - let result = match tx.kind { - ScenarioTxKind::SystemCall => { - evm.ctx().set_tx(TxEnv::new_system_tx_with_caller( - tx.caller, - tx.to.expect("validated: a system call has a target"), - tx.data.clone(), - )); - probe.run_system_call(&mut evm) - } - ScenarioTxKind::Call | ScenarioTxKind::Create => { - let nonce = - evm.ctx().db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); - evm.ctx().set_tx(tx_env(tx, nonce)); - probe.run(&mut evm) - } - }; - let state = evm.ctx().journal_mut().finalize(); - drop(evm); - let record = match result { - Ok(result) => { - let record = record(&result, probe.reservoir.get(), &state); - db.commit(state); - record - } - Err(err) => { - TxRecord { outcome: format!("error:{}", error(&err)), ..Default::default() } - } - }; - records.push(record); - } - records -} - -/// The oracle's configuration: `MegaEvm`'s, field by field. -/// -/// # Panics -/// -/// If `MegaEvm` switches on a fork-only mechanism revm 43 cannot run: EIP-7708 transfer logs -/// before Amsterdam, or the system-call state-gas margin. The harness then needs a model of it or -/// a registry entry before it can compare. -pub fn cfg() -> CfgEnv { - let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); - let mega: &MegaCfgEnv = ctx.mega_cfg(); - let eth_spec: &'static str = mega.spec.into_eth_spec().into(); - let spec = SpecId::from_str(eth_spec).expect("revm 43 knows every spec the fork knows"); - assert!( - !mega.enable_amsterdam_eip7708 || spec.is_enabled_in(SpecId::AMSTERDAM), - "MegaEvm switches EIP-7708 on before Amsterdam, which revm 43 cannot do" - ); - assert!( - !mega.system_call_state_gas_margin_in_reservoir, - "MegaEvm reserves the system-call state-gas margin, which revm 43 does not have" - ); - - let mut cfg = CfgEnv::new_with_spec_and_gas_params(spec, gas_params(mega.gas_params.table())); - cfg.chain_id = mega.chain_id; - cfg.tx_chain_id_check = mega.tx_chain_id_check; - cfg.limit_contract_code_size = mega.limit_contract_code_size; - cfg.limit_contract_initcode_size = mega.limit_contract_initcode_size; - cfg.disable_nonce_check = mega.disable_nonce_check; - cfg.max_blobs_per_tx = mega.max_blobs_per_tx; - cfg.blob_base_fee_update_fraction = mega.blob_base_fee_update_fraction; - cfg.tx_gas_limit_cap = mega.tx_gas_limit_cap; - cfg.memory_limit = mega.memory_limit; - cfg.disable_balance_check = mega.disable_balance_check; - cfg.disable_block_gas_limit = mega.disable_block_gas_limit; - cfg.disable_eip3541 = mega.disable_eip3541; - cfg.disable_eip3607 = mega.disable_eip3607; - cfg.disable_eip7623 = mega.disable_eip7623; - cfg.disable_base_fee = mega.disable_base_fee; - cfg.enable_amsterdam_eip8037 = mega.enable_amsterdam_eip8037; - cfg.enable_amsterdam_eip2780 = mega.enable_amsterdam_eip2780; - cfg.amsterdam_eip7708_disabled = mega.amsterdam_eip7708_disabled; - cfg.amsterdam_eip8246_delayed_clear_disabled = mega.amsterdam_eip8246_delayed_clear_disabled; - cfg -} - -/// A revm 43 gas table holding `table` entry for entry. -/// -/// The fork numbers its gas ids as upstream does, so an index names the same price on both -/// sides; the fork's own ids sit at the top of the table, where upstream has none. -pub fn gas_params(table: &[u64; 256]) -> GasParams { - GasParams::new(std::sync::Arc::new(*table)) -} - -fn block(scenario: &Scenario) -> BlockEnv { - let mega = scenario.block(); - BlockEnv { - number: mega.number, - beneficiary: mega.beneficiary, - timestamp: mega.timestamp, - gas_limit: mega.gas_limit, - basefee: mega.basefee, - difficulty: mega.difficulty, - prevrandao: mega.prevrandao, - ..Default::default() - } -} - -fn database(scenario: &Scenario) -> OracleDb { - let mut db = OracleDb::default(); - for (address, account) in &scenario.pre { - let mut info = - AccountInfo { nonce: account.nonce, balance: account.balance, ..Default::default() }; - if !account.code.is_empty() { - let code = Bytecode::new_raw_checked(account.code.clone()) - .expect("validated: the pre-state code decodes"); - info.code_hash = code.hash_slow(); - info.code = Some(code); - } - db.insert_account_info(*address, info); - for (slot, value) in &account.storage { - db.insert_account_storage(*address, *slot, *value).expect("in-memory database"); - } - } - db -} - -fn tx_env(tx: &mega_evm::test_utils::ScenarioTx, nonce: u64) -> TxEnv { - let access_list = AccessList( - tx.access_list - .iter() - .map(|entry| AccessListItem { - address: entry.address, - storage_keys: entry.storage_keys.iter().map(|key| (*key).into()).collect(), - }) - .collect(), - ); - let authorizations = tx - .authorization_list - .iter() - .map(|entry| { - RecoveredAuthorization::new_unchecked( - Authorization { - chain_id: entry.chain_id, - address: entry.address, - nonce: entry.nonce, - }, - entry.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), - ) - }) - .collect(); - TxEnv::builder() - .tx_type(Some(tx.tx_type() as u8)) - .caller(tx.caller) - .kind(tx.to.map_or(TxKind::Create, TxKind::Call)) - .data(tx.data.clone()) - .value(tx.value) - .gas_limit(tx.gas_limit.expect("a call or a create has a gas limit")) - .gas_price(tx.gas_price) - .gas_priority_fee((tx.tx_type() == ScenarioTxType::Eip7702).then_some(tx.gas_price)) - .nonce(nonce) - .access_list(access_list) - .authorization_list_recovered(authorizations) - .build_fill() -} - -/// revm 43's mainnet handler, reading the reservoir left over at the point the fork records it. -/// -/// revm 43's `ResultGas` has no `reservoir_remaining`. The fork reads it from the frame's gas -/// right after the refund, before the EIP-7623 floor may absorb it; this handler reads the same -/// gas at the same point, in the floor check that runs right after (for a system call, which -/// has no floor check, in `execution_result`, which gets the same gas). -#[derive(Default)] -struct ReservoirProbe<'a> { - inner: MainnetHandler, OracleError, EthFrame>, - reservoir: Cell>, -} - -impl<'a> Handler for ReservoirProbe<'a> { - type Evm = OracleEvm<'a>; - type Error = OracleError; - type HaltReason = HaltReason; - - fn eip7623_check_gas_floor( - &self, - evm: &mut Self::Evm, - exec_result: &mut FrameResult, - init_and_floor_gas: revm_oracle::context_interface::cfg::gas::InitialAndFloorGas, - ) { - self.reservoir.set(Some(exec_result.gas().reservoir())); - self.inner.eip7623_check_gas_floor(evm, exec_result, init_and_floor_gas); - } - - fn execution_result( - &mut self, - evm: &mut Self::Evm, - result: <::Frame as FrameTr>::FrameResult, - result_gas: ResultGas, - ) -> Result, Self::Error> { - if self.reservoir.get().is_none() { - self.reservoir.set(Some(result.gas().reservoir())); - } - self.inner.execution_result(evm, result, result_gas) - } -} - -fn record(result: &ExecutionResult, reservoir: Option, state: &EvmState) -> TxRecord { - // revm 43's `ResultGas` has no `reservoir_remaining`; the probe supplies it. - tx_record!( - ExecutionResult, - result, - state, - |reason: &HaltReason| format!("{reason:?}"), - reservoir - ) -} - -fn error(err: &OracleError) -> String { - match err { - EVMError::Transaction(invalid) => format!("invalid:{invalid:?}"), - EVMError::Header(header) => format!("header:{header:?}"), - other => format!("other:{other:?}"), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use revm_oracle::{ExecuteEvm, SystemCallEvm}; - - /// Runs `scenario` with revm 43's own entry points instead of the probe. - fn run_stock(scenario: &Scenario) -> ScenarioRecord { - let mut db = database(scenario); - let mut records = Vec::new(); - for tx in &scenario.txs { - let mut evm = Context::mainnet() - .with_db(&mut db) - .with_cfg(cfg()) - .with_block(block(scenario)) - .build_mainnet(); - let outcome = match tx.kind { - ScenarioTxKind::SystemCall => { - evm.system_call_with_caller(tx.caller, tx.to.unwrap(), tx.data.clone()) - } - _ => { - let nonce = evm.ctx().db_mut().basic(tx.caller).unwrap().map_or(0, |i| i.nonce); - evm.transact(tx_env(tx, nonce)) - } - }; - drop(evm); - records.push(match outcome { - Ok(outcome) => { - let record = record(&outcome.result, None, &outcome.state); - db.commit(outcome.state); - record - } - Err(err) => { - TxRecord { outcome: format!("error:{}", error(&err)), ..Default::default() } - } - }); - } - records - } - - /// The probe only reads the reservoir: without that figure, every scenario records the same - /// as through revm 43's own `transact` and `system_call_with_caller`, rejected transactions - /// included. - #[test] - fn test_reservoir_probe_changes_nothing_else() { - let scenarios = crate::load_corpus(&crate::corpus_dir()).unwrap(); - let txs = || scenarios.iter().flat_map(|s| &s.txs); - assert!(txs().any(|tx| tx.kind == ScenarioTxKind::SystemCall)); - let mut rejected = 0; - for scenario in &scenarios { - let mut probed = run(scenario); - for record in &mut probed { - if record.outcome.starts_with("error:") { - rejected += 1; - assert!(record.gas.is_empty(), "{}", scenario.name); - } else { - let reservoir = record.gas.remove("reservoir_remaining"); - assert!(reservoir.is_some(), "{}", scenario.name); - } - } - assert_eq!(probed, run_stock(scenario), "{}", scenario.name); - } - assert!(rejected > 0, "the corpus has a rejected transaction"); - } -} diff --git a/crates/mega-differential/src/record.rs b/crates/mega-differential/src/record.rs deleted file mode 100644 index 5300c708d..000000000 --- a/crates/mega-differential/src/record.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! What an arm reports for a scenario, in a form both arms produce. -//! -//! Each arm turns its own result types into these records; the comparison only ever sees -//! records, so it cannot depend on which revm produced them. - -use std::collections::BTreeMap; - -use alloy_primitives::{Address, Bytes, B256, U256}; - -/// Marker for a value one arm has and the other does not. -pub const ABSENT: &str = ""; - -/// The records of every transaction of one scenario, in order. -pub type ScenarioRecord = Vec; - -/// What one transaction produced. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct TxRecord { - /// `success`, `revert`, `halt:` or `error:`. - pub outcome: String, - /// Every gas figure of the result, by name: the fields of `ResultGas` as it serializes - /// them, the reservoir left over, and the derived values a block builder reads. - pub gas: BTreeMap, - /// Return or revert data. - pub output: Bytes, - /// Address a create transaction deployed to. - pub created: Option
, - /// Logs, in emission order. - pub logs: Vec, - /// Every account the transaction touched. - pub state: BTreeMap, -} - -/// A log entry. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct LogRecord { - /// Emitting contract. - pub address: Address, - /// Topics. - pub topics: Vec, - /// Data. - pub data: Bytes, -} - -/// A touched account after the transaction. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct AccountRecord { - /// Created in this transaction (its storage starts empty). - pub created: bool, - /// Self-destructed in this transaction. - pub selfdestructed: bool, - /// Balance. - pub balance: U256, - /// Nonce. - pub nonce: u64, - /// Code hash. - pub code_hash: B256, - /// The slots whose value the transaction changed, with their new value. - pub storage: BTreeMap, -} - -impl LogRecord { - /// One-line rendering used in difference reports and the registry. - pub fn render(&self) -> String { - let topics: Vec = self.topics.iter().map(|topic| format!("{topic}")).collect(); - format!("{:#x} [{}] {}", self.address, topics.join(","), self.data) - } -} - -impl AccountRecord { - /// One-line rendering used when only one arm has the account. - pub fn render(&self) -> String { - let storage: Vec = - self.storage.iter().map(|(slot, value)| format!("{slot:#x}={value:#x}")).collect(); - format!( - "created={} selfdestructed={} balance={:#x} nonce={} code_hash={} storage={{{}}}", - self.created, - self.selfdestructed, - self.balance, - self.nonce, - self.code_hash, - storage.join(","), - ) - } -} - -/// Builds the [`TxRecord`] of an executed transaction, for either arm. -/// -/// Both revms expose the same accessors on their execution result, logs and state, but as -/// types of different crates, so one function cannot take both; this macro is that function, so -/// the two arms cannot drift apart in what they record. -/// -/// - `$exec`: the arm's `ExecutionResult` type, to match its variants; -/// - `$result`, `$state`: the result and the state the transaction produced; -/// - `$halt`: renders the arm's halt reason; -/// - `$reservoir`: the leftover reservoir when the arm's `ResultGas` does not serialize it. -macro_rules! tx_record { - ($exec:ident, $result:expr, $state:expr, $halt:expr, $reservoir:expr $(,)?) => {{ - let result = $result; - let gas = result.gas(); - let mut figures = $crate::serialized_u64_fields(gas); - if let Some(reservoir) = $reservoir { - figures.insert("reservoir_remaining".to_string(), reservoir); - } - figures.insert("tx_gas_used".to_string(), gas.tx_gas_used()); - figures.insert("block_regular_gas_used".to_string(), gas.block_regular_gas_used()); - figures.insert("block_state_gas_used".to_string(), gas.block_state_gas_used()); - figures.insert("final_refunded".to_string(), gas.final_refunded()); - $crate::record::TxRecord { - outcome: match result { - $exec::Success { .. } => "success".to_string(), - $exec::Revert { .. } => "revert".to_string(), - $exec::Halt { reason, .. } => format!("halt:{}", $halt(reason)), - }, - gas: figures, - output: result.output().cloned().unwrap_or_default(), - created: result.created_address(), - logs: result - .logs() - .iter() - .map(|log| $crate::record::LogRecord { - address: log.address, - topics: log.topics().to_vec(), - data: log.data.data.clone(), - }) - .collect(), - state: $state - .iter() - .filter(|(_, account)| account.is_touched()) - .map(|(address, account)| { - let record = $crate::record::AccountRecord { - created: account.is_created(), - selfdestructed: account.is_selfdestructed(), - balance: account.info.balance, - nonce: account.info.nonce, - code_hash: account.info.code_hash, - storage: account - .storage - .iter() - .filter(|(_, slot)| slot.is_changed()) - .map(|(key, slot)| (*key, slot.present_value)) - .collect(), - }; - (*address, record) - }) - .collect(), - } - }}; -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, b256, bytes}; - - const A: Address = address!("0x0000000000000000000000000000000000000aaa"); - - /// Two logs at the same index are compared as this one line, and a registry effect for a log - /// is a pattern over it, so the rendering carries every field of the log. - #[test] - fn test_log_record_renders_address_topics_and_data() { - let log = LogRecord { - address: A, - topics: vec![ - b256!("0x0000000000000000000000000000000000000000000000000000000000000001"), - b256!("0x0000000000000000000000000000000000000000000000000000000000000002"), - ], - data: bytes!("0xbeef"), - }; - assert_eq!(log.render(), format!("{A:#x} [{},{}] 0xbeef", log.topics[0], log.topics[1])); - let empty = LogRecord { topics: Vec::new(), data: Bytes::new(), ..log }; - assert_eq!(empty.render(), format!("{A:#x} [] 0x")); - } - - /// The same for an account only one arm touched, which is reported as its rendering. - #[test] - fn test_account_record_renders_every_field() { - let account = AccountRecord { - created: true, - selfdestructed: false, - balance: U256::from(7), - nonce: 3, - code_hash: B256::ZERO, - storage: BTreeMap::from([(U256::from(1), U256::from(2)), (U256::from(3), U256::ZERO)]), - }; - assert_eq!( - account.render(), - format!( - "created=true selfdestructed=false balance=0x7 nonce=3 code_hash={} \ - storage={{0x1=0x2,0x3=0x0}}", - B256::ZERO, - ), - ); - } -} diff --git a/crates/mega-differential/src/registry.rs b/crates/mega-differential/src/registry.rs deleted file mode 100644 index ab458733d..000000000 --- a/crates/mega-differential/src/registry.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! The registry of accepted differences. -//! -//! An entry names one mechanism and lists every effect it has on the compared fields, each as a -//! field and the two values. Every difference between the arms must be explained by an effect -//! of an active entry, and every effect of an active entry must explain at least one difference; -//! either failure fails the run. A mechanism that stops producing an effect therefore shows up as -//! a stale effect, to be removed or its entry retired, instead of lingering as a blanket excuse. - -use std::collections::BTreeSet; - -use serde::Deserialize; - -use crate::diff::Difference; - -/// Version of the registry format this crate reads. -pub const REGISTRY_VERSION: u64 = 1; - -/// The registry file. -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Registry { - /// Format version; must be [`REGISTRY_VERSION`]. - pub version: u64, - /// The entries. - pub deviations: Vec, -} - -/// An accepted difference between `MegaEvm` and the oracle: one mechanism and its effects. -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Deviation { - /// Stable identifier, used in reports. - pub id: String, - /// Whether the entry is in force. - pub status: Status, - /// Scenario names the entry covers (`*` matches any run of characters). - pub scenario: String, - /// The mechanism that makes the arms differ. - pub mechanism: String, - /// Why the difference is correct. - pub reason: String, - /// What the mechanism changes, field by field. - pub effects: Vec, - /// Why the entry was retired; required for a retired entry. - #[serde(default)] - pub retired_reason: Option, -} - -/// One field a mechanism changes, and the value on each arm. -/// -/// Each part is a pattern in which `*` matches any run of characters; every other character -/// stands for itself. -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Effect { - /// Field path. - pub field: String, - /// The value `MegaEvm` reports. - pub left: String, - /// The value the oracle reports. - pub right: String, -} - -/// Status of a registry entry. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Status { - /// In force: its effects explain differences, and each must explain at least one. - Active, - /// Kept for the record; it explains nothing. - Retired, -} - -/// An effect of an entry, by entry id and position in its `effects`. -pub type EffectRef = (String, usize); - -impl Registry { - /// Parses a registry and checks its entries are well formed. - pub fn from_json(json: &str) -> Result { - let registry: Self = serde_json::from_str(json).map_err(|err| err.to_string())?; - if registry.version != REGISTRY_VERSION { - return Err(format!( - "registry version {} (this harness reads {REGISTRY_VERSION})", - registry.version - )); - } - let mut ids = BTreeSet::new(); - for dev in ®istry.deviations { - if !ids.insert(dev.id.as_str()) { - return Err(format!("duplicate registry id {}", dev.id)); - } - if dev.mechanism.trim().is_empty() || dev.reason.trim().is_empty() { - return Err(format!("{}: an entry names its mechanism and its reason", dev.id)); - } - if dev.effects.is_empty() { - return Err(format!("{}: an entry lists at least one effect", dev.id)); - } - if (dev.status == Status::Retired) != dev.retired_reason.is_some() { - return Err(format!( - "{}: a retired entry, and only one, has retired_reason", - dev.id - )); - } - } - Ok(registry) - } - - /// The effect of an active entry that explains `diff`, if any. - pub fn explain(&self, diff: &Difference) -> Option { - self.find(Status::Active, diff) - } - - /// The effect of a retired entry that would have explained `diff`, to point at in a failure - /// report. - pub fn retired_match(&self, diff: &Difference) -> Option { - self.find(Status::Retired, diff) - } - - /// Every effect of every active entry. - pub fn active_effects(&self) -> impl Iterator { - self.deviations.iter().filter(|dev| dev.status == Status::Active).flat_map(|dev| { - dev.effects.iter().enumerate().map(|(i, effect)| ((dev.id.clone(), i), effect)) - }) - } - - fn find(&self, status: Status, diff: &Difference) -> Option { - self.deviations - .iter() - .filter(|dev| dev.status == status && glob(&dev.scenario, &diff.scenario)) - .find_map(|dev| { - let i = dev.effects.iter().position(|effect| effect.matches(diff))?; - Some((dev.id.clone(), i)) - }) - } -} - -impl Effect { - /// Whether this effect's patterns cover the field and values of `diff`. - pub fn matches(&self, diff: &Difference) -> bool { - glob(&self.field, &diff.field) && - glob(&self.left, &diff.left) && - glob(&self.right, &diff.right) - } -} - -/// Matches `text` against `pattern`, where `*` stands for any run of characters (including -/// none) and every other character stands for itself. -pub fn glob(pattern: &str, text: &str) -> bool { - let mut parts = pattern.split('*'); - let first = parts.next().unwrap_or_default(); - let Some(mut rest) = text.strip_prefix(first) else { return false }; - let parts: Vec<&str> = parts.collect(); - let Some((last, middle)) = parts.split_last() else { return rest.is_empty() }; - for part in middle { - match rest.find(part) { - Some(at) => rest = &rest[at + part.len()..], - None => return false, - } - } - rest.len() >= last.len() && rest.ends_with(last) -} - -#[cfg(test)] -mod tests { - use super::*; - - const GAS_EFFECT: &str = r#"{"field": "tx[*].gas.gas_spent", "left": "*", "right": "21000"}"#; - const OUTPUT_EFFECT: &str = r#"{"field": "tx[*].output", "left": "0x", "right": "0x01"}"#; - - fn entry(id: &str, status: &str, effects: &[&str], extra: &str) -> String { - format!( - r#"{{"id": "{id}", "status": "{status}", "scenario": "call_*", "mechanism": "m", - "reason": "r", "effects": [{}]{extra}}}"#, - effects.join(",") - ) - } - - fn registry(entries: &[String]) -> Result { - Registry::from_json(&format!(r#"{{"version": 1, "deviations": [{}]}}"#, entries.join(","))) - } - - fn diff(scenario: &str, field: &str, left: &str, right: &str) -> Difference { - Difference { - scenario: scenario.into(), - field: field.into(), - left: left.into(), - right: right.into(), - } - } - - #[test] - fn test_glob() { - assert!(glob("*", "")); - assert!(glob("abc", "abc")); - assert!(!glob("abc", "abcd")); - assert!(glob("a*c", "abbbc")); - assert!(glob("a*c", "ac")); - assert!(!glob("a*c", "ab")); - assert!(glob("*b*", "abc")); - assert!(glob("a*b*c", "aXbYc")); - assert!(!glob("a*b*c", "aXcYb")); - // The suffix may not reuse characters the prefix consumed. - assert!(!glob("ab*ba", "aba")); - // Nor may a middle segment: each one starts after the one before it ended. - assert!(glob("*b*b*", "abb")); - assert!(!glob("*b*b*", "ab")); - } - - #[test] - fn test_active_entry_explains_matching_differences_only() { - let registry = registry(&[entry("d", "active", &[GAS_EFFECT, OUTPUT_EFFECT], "")]).unwrap(); - let gas = |scenario, right| diff(scenario, "tx[0].gas.gas_spent", "21100", right); - - assert_eq!(registry.explain(&gas("call_1", "21000")), Some(("d".into(), 0))); - assert_eq!( - registry.explain(&diff("call_1", "tx[1].output", "0x", "0x01")), - Some(("d".into(), 1)) - ); - assert!(registry.explain(&gas("create_1", "21000")).is_none(), "scenario pattern"); - assert!(registry.explain(&gas("call_1", "21001")).is_none(), "right value"); - assert!(registry.explain(&diff("call_1", "tx[0].output", "0x", "0x02")).is_none()); - } - - #[test] - fn test_retired_entry_explains_nothing() { - let registry = - registry(&[entry("d", "retired", &[GAS_EFFECT], r#", "retired_reason": "gone""#)]) - .unwrap(); - let gas = diff("call_1", "tx[0].gas.gas_spent", "21100", "21000"); - assert!(registry.explain(&gas).is_none()); - assert_eq!(registry.retired_match(&gas), Some(("d".into(), 0))); - assert_eq!(registry.active_effects().count(), 0); - } - - #[test] - fn test_registry_rejects_malformed_entries() { - let reject = |entries: &[String]| registry(entries).unwrap_err(); - assert!(reject(&[entry("d", "retired", &[GAS_EFFECT], "")]).contains("retired_reason")); - assert!(reject(&[entry("d", "active", &[GAS_EFFECT], r#", "retired_reason": "x""#)]) - .contains("retired_reason")); - assert!(reject(&[entry("d", "active", &[], "")]).contains("effect")); - assert!(reject(&[ - entry("d", "active", &[GAS_EFFECT], ""), - entry("d", "active", &[GAS_EFFECT], "") - ]) - .contains("duplicate")); - assert!(Registry::from_json(r#"{"version": 2, "deviations": []}"#).is_err()); - assert!(registry(&[entry("d", "paused", &[GAS_EFFECT], "")]).is_err()); - } - - /// An entry names its mechanism and its reason; either one blank is rejected, so a blanket - /// excuse cannot be filed under a name that says nothing. - #[test] - fn test_registry_requires_both_a_mechanism_and_a_reason() { - let named = |mechanism: &str, reason: &str| { - Registry::from_json(&format!( - r#"{{"version": 1, "deviations": [{{"id": "d", "status": "active", - "scenario": "*", "mechanism": "{mechanism}", "reason": "{reason}", - "effects": [{GAS_EFFECT}]}}]}}"# - )) - }; - assert!(named("m", "r").is_ok()); - assert!(named("", "r").unwrap_err().contains("names its mechanism and its reason")); - assert!(named("m", "").unwrap_err().contains("names its mechanism and its reason")); - assert!(named(" ", " \t ").is_err(), "blank is not a name"); - } -} diff --git a/crates/mega-differential/tests/claims.rs b/crates/mega-differential/tests/claims.rs deleted file mode 100644 index 55f7ed57e..000000000 --- a/crates/mega-differential/tests/claims.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! Checks of what the harness and its registry claim about the two arms. - -use std::collections::BTreeMap; - -use mega_differential::{corpus_dir, mega, oracle}; -use mega_evm::{ - alloy_primitives::{address, hex, keccak256, Address, Bytes, U256}, - revm::{ - context_interface::cfg::gas_params::GasId as ForkGasId, - database::{states::bundle_state::BundleRetention, State}, - DatabaseCommit, - }, - test_utils::{PreAccount, Scenario, ScenarioTx, ScenarioTxKind}, - MegaContext, MegaSpecId, -}; -use revm_oracle::{ - context_interface::cfg::gas_params::GasId as OracleGasId, primitives::hardfork::SpecId, -}; - -const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); -const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); - -/// The proxy of the `precompile_point_evaluation_*` scenarios: it calls the precompile and -/// records the call's status in slot 0, the size of the return data in slot 1 and its hash in -/// slot 2. -const KZG_PROXY: Address = address!("0x000000000000000000000000000000000000990a"); - -/// What a successful point evaluation returns: `FIELD_ELEMENTS_PER_BLOB` and the BLS modulus, -/// each as a 32-byte big-endian value. -const POINT_EVALUATION_OUTPUT: [u8; 64] = hex!( - "0000000000000000000000000000000000000000000000000000000000001000" - "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001" -); - -/// The gas ids the fork adds on top of upstream's. revm 43 has no price at these indexes. -const FORK_ONLY_GAS_IDS: &[&str] = &["code_deposit_history_gas"]; - -/// The oracle copies `MegaEvm`'s gas table index by index, which is only sound if every index -/// names the same price on both sides. -#[test] -fn test_gas_table_indexes_name_the_same_prices() { - let mut fork_only = Vec::new(); - for id in 0..=u8::MAX { - let (fork, oracle) = (ForkGasId::new(id).name(), OracleGasId::new(id).name()); - if oracle == "unknown" && fork != "unknown" { - fork_only.push(fork); - } else { - assert_eq!(fork, oracle, "gas id {id}"); - } - } - assert_eq!(fork_only, FORK_ONLY_GAS_IDS); -} - -/// A price only the fork has is one the oracle cannot charge, so it must be zero while the -/// corpus is expected to match; the mechanism that prices it registers the difference. -#[test] -fn test_fork_only_gas_ids_are_priced_at_zero() { - let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); - for name in FORK_ONLY_GAS_IDS { - let id = ForkGasId::from_name(name).unwrap(); - assert_eq!(ctx.mega_cfg().gas_params.get(id), 0, "{name}"); - } -} - -#[test] -fn test_oracle_runs_the_satin_configuration() { - let cfg = oracle::cfg(); - assert_eq!(cfg.spec, SpecId::OSAKA); - let ctx = MegaContext::new(mega_evm::revm::database::EmptyDB::default(), MegaSpecId::SATIN); - assert_eq!(cfg.gas_params.table(), ctx.mega_cfg().gas_params.table()); - assert!(cfg.enable_amsterdam_eip8037); - assert!(cfg.enable_amsterdam_eip2780); - assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); - assert_eq!(cfg.chain_id, ctx.mega_cfg().chain_id); -} - -/// The registry's vault entries rest on this: a vault op-revm touches with a zero fee is -/// dropped by state clearing when the transaction's state is committed. -#[test] -fn test_zero_fee_vault_touch_leaves_no_committed_account() { - let vaults = [ - address!("0x4200000000000000000000000000000000000019"), - address!("0x420000000000000000000000000000000000001a"), - address!("0x420000000000000000000000000000000000001b"), - ]; - let scenario = Scenario { - name: "transfer".into(), - description: String::new(), - coinbase: Address::ZERO, - pre: BTreeMap::from([( - CALLER, - PreAccount { balance: U256::from(10), ..Default::default() }, - )]), - txs: vec![ScenarioTx { - caller: CALLER, - to: Some(CALLEE), - data: Bytes::new(), - value: U256::from(1), - gas_limit: Some(100_000), - gas_price: 0, - kind: ScenarioTxKind::Call, - access_list: Vec::new(), - authorization_list: Vec::new(), - }], - }; - let (outcomes, _) = scenario.run(scenario.database()); - let state = outcomes.into_iter().next().unwrap().unwrap().state; - for vault in vaults { - assert!(state[&vault].is_touched() && state[&vault].is_empty(), "{vault}"); - } - - let mut db = State::builder().with_database(scenario.database()).with_bundle_update().build(); - db.commit(state); - db.merge_transitions(BundleRetention::PlainState); - let bundle = db.take_bundle(); - - assert!(bundle.account(&CALLEE).is_some(), "the transfer itself is committed"); - for vault in vaults { - assert!(bundle.account(&vault).is_none(), "{vault}"); - } -} - -/// Reads a scenario of `scenarios/harness/` by name. -fn harness_scenario(name: &str) -> Scenario { - let path = corpus_dir().join("harness").join(format!("{name}.json")); - let scenario: Scenario = - serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); - scenario.validate().unwrap(); - scenario -} - -/// The corpus compares the two arms, and two calls that fail agree as readily as two that -/// succeed, so the positive KZG case needs a pinned value on the left arm: this is what -/// `MegaEvm`'s KZG backend returns for a valid proof, and it is only produced after -/// `verify_kzg_proof` accepts it. -#[test] -fn test_point_evaluation_on_a_valid_proof_returns_the_field_parameters() { - let scenario = harness_scenario("precompile_point_evaluation_valid"); - let record = mega::run(&scenario); - - assert_eq!(record.len(), 1); - assert_eq!(record[0].outcome, "success"); - assert_eq!(record[0].output, Bytes::from_static(&POINT_EVALUATION_OUTPUT)); - // The proxy's record of the inner call: status 1, 64 bytes of return data, its hash. - assert_eq!( - record[0].state[&KZG_PROXY].storage, - BTreeMap::from([ - (U256::ZERO, U256::from(1)), - (U256::from(1), U256::from(64)), - (U256::from(2), keccak256(POINT_EVALUATION_OUTPUT).into()), - ]), - ); -} - -/// The wrong-proof scenario differs from the valid one only in the proof, so its versioned hash -/// still matches its commitment: the call gets past that check and fails in verification, with -/// no status, no return data and the hash of an empty return. -#[test] -fn test_point_evaluation_on_a_wrong_proof_fails_in_verification() { - let valid = harness_scenario("precompile_point_evaluation_valid"); - let scenario = harness_scenario("precompile_point_evaluation_wrong_proof"); - let (input, valid_input) = (&scenario.txs[0].data, &valid.txs[0].data); - - // | versioned hash 32 | z 32 | y 32 | commitment 48 | proof 48 | - assert_eq!(input[..144], valid_input[..144], "same versioned hash, z, y and commitment"); - assert_ne!(input[144..192], valid_input[144..192], "a different proof"); - - let record = mega::run(&scenario); - assert_eq!(record.len(), 1); - assert_eq!(record[0].outcome, "success"); - assert_eq!(record[0].output, Bytes::new()); - assert_eq!( - record[0].state[&KZG_PROXY].storage, - BTreeMap::from([(U256::from(2), keccak256([]).into())]), - "storing zero into an empty slot is not a change, so only the hash slot is recorded", - ); -} diff --git a/crates/mega-differential/tests/corpus.rs b/crates/mega-differential/tests/corpus.rs deleted file mode 100644 index 2986b1342..000000000 --- a/crates/mega-differential/tests/corpus.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! Runs the whole corpus through both arms. - -use mega_differential::{corpus_dir, load_corpus, registry::Registry, registry_path, run}; - -#[test] -fn test_corpus_matches_the_oracle() { - let scenarios = load_corpus(&corpus_dir()).unwrap(); - let registry = Registry::from_json(&std::fs::read_to_string(registry_path()).unwrap()).unwrap(); - - let report = run(&scenarios, ®istry); - - println!("{}", report.summary()); - assert!(report.is_clean(), "{}\n{}", report.summary(), report.failures()); -} From 438783a8399b6cf254bde95d2a3c6c14f4ebdbfd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sat, 19 Sep 2026 21:55:22 +0800 Subject: [PATCH 087/201] docs: say the differential harness is maintained outside this repository --- AGENTS.md | 32 ++++++++-------------- REVIEW.md | 11 +++----- crates/mega-evm/src/test_utils/scenario.rs | 11 ++++---- 3 files changed, 20 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 451381f9a..0b5d356df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,9 +37,6 @@ cargo sort --check --workspace --grouped --order package,workspace,lints,profile cargo bench -p mega-evm --bench # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) -# Differential harness: MegaEvm against stock revm 43 over the scenario corpus -cargo test -p mega-differential --locked - # no_std check (run against riscv target) cargo check -p mega-evm --target riscv64imac-unknown-none-elf --no-default-features @@ -51,17 +48,15 @@ Git submodules are required — clone with `--recursive` or run `git submodule u ## Workspace Structure -| Crate | Path | Member | Purpose | -| ----------------------- | -------------------------- | ---------------- | ------------------------------------------------------------ | -| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | -| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-differential` | `crates/mega-differential` | yes, not default | Differential harness: `MegaEvm` against stock revm 43 | -| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | -| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | -| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | -| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | - -`mega-differential` builds stock revm 43 from crates.io next to the fork, as its oracle; it is not a default member, so the commands run at the root without `-p` or `--workspace` stay on the engine's graph. +| Crate | Path | Member | Purpose | +| ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | +| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | +| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | +| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | +| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | +| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | +| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | + The four tool crates still target the legacy engine. They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until they are ported to Satin. @@ -71,7 +66,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat `op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates (`alloy-op-evm`, `op-alloy-*`) come from the same monorepo revision. - Patch the twelve revm crates together, or the build resolves a second copy of revm. -- `cargo tree -i revm -p mega-evm` must show exactly one revm, from the fork; only `mega-differential`'s graph adds stock revm 43, as its oracle. +- `cargo tree -i revm` must show exactly one revm, from the fork. - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. ## Architecture @@ -109,7 +104,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Gas above the 200M execution cap goes to the EIP-8037 reservoir. The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. - `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. - With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field, and the differential harness against revm 43; a later change that alters behavior on purpose updates that baseline. + With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. @@ -154,8 +149,6 @@ Every later mechanism plugs into these; a change to one comes back to this layer It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. The change that ports a pending test deletes it from `_pending/` in the same commit. - Unit tests live next to the code in `#[cfg(test)] mod tests`. -- `crates/mega-differential/scenarios/` — the differential corpus: JSON scenarios (`test_utils::Scenario`) that run through `MegaEvm` and through stock revm 43 and are compared field by field. - A behavior that should equal Ethereum's is pinned best as a scenario there. ## Version Control @@ -218,9 +211,6 @@ When the agent is requested to implement a new feature or bug fix, it should con The agent should always consider accompanying tests or suggest to add additional tests. - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. -- **Keep the differential harness clean.** - `cargo test -p mega-differential --locked` must pass: every difference between `MegaEvm` and stock revm 43 is explained by an effect of `crates/mega-differential/deviations.json`, and every effect there explains one. - A change that makes `MegaEvm` differ on purpose registers each effect with its mechanism and reason, as narrow as the mechanism allows (or teaches the oracle to model it); a change that removes a difference removes its effect. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. This includes new or modified opcode behavior, gas mechanics, system contract interception, resource limit tracking, and block executor pipeline changes. diff --git a/REVIEW.md b/REVIEW.md index 55d09fd5f..d9f47b9ed 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -82,16 +82,13 @@ These checks guard every change to the Satin engine. ### Differential harness -- `crates/mega-differential` runs every scenario of its corpus (listed in its README) through `MegaEvm` and through stock revm 43, and compares every gas figure, the outcome, the output, the logs and every touched account. -- The `differential` check (`.github/workflows/differential.yml`) runs it on every pull request and every push to `satin`; it must pass with no unexplained difference and no stale registry effect. -- A change that makes `MegaEvm` differ from revm 43 on purpose adds the effects to `crates/mega-differential/deviations.json` (mechanism, reason, exact values), or configures the oracle to model the mechanism. - Review a registry change like a spec change: an effect wider than its mechanism (a `*` where an exact value fits, a scenario pattern of `*` for a mechanism a few scenarios reach) hides the next regression. -- A change that removes a difference removes its effect; the harness fails on an effect that explains nothing. +- The differential harness, which runs JSON scenarios through `MegaEvm` and through stock revm and compares them field by field, is maintained outside this repository. +- It is not a check on this repository's pull requests. +- The scenario format it reads (`test_utils::Scenario`) stays in `mega-evm`, where the `corpus` bench reads its own scenarios. ### Execution-spec tests -- Engine-level execution-spec coverage on `MegaEvm` is the 263 execution-spec-derived scenarios of the differential harness, until the state-test tool is ported to Satin. - They come from the EIP-8037 state tests; while the Osaka gas table prices state gas at zero they exercise the reservoir, refunds and regular gas, and their state-gas paths count once the Satin gas table prices state. +- No check in this repository runs execution-spec tests on `MegaEvm` itself until the state-test tool is ported to Satin. - `.github/workflows/exec-spec.yml` runs the fork's own runner on the execution-spec-test fixtures, at the fork tag `Cargo.lock` pins, and checks the Osaka and Amsterdam executed and skipped counts pinned in the workflow. It checks the fork `MegaEvm` runs on, not `MegaEvm`, and it is not a required check. - It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 5e6cacbcb..0739b5c01 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -1,9 +1,8 @@ //! Transaction scenarios: a pre-state and a sequence of transactions, read from JSON. //! -//! A [`Scenario`] is the input format of the differential harness (`crates/mega-differential`), -//! which runs every scenario through [`MegaEvm`] and through an independent EVM and compares the -//! two. The benches run slices of the same corpus, so their instruction counts move when the -//! semantics or the pricing of those scenarios move. +//! A [`Scenario`] describes a transaction sequence as data, so it can run through [`MegaEvm`] +//! and through another EVM alike. The `corpus` bench reads its inputs in this format, so its +//! instruction counts move when the semantics or the pricing of those scenarios move. //! //! The block, the configuration and the L1 fees are fixed, so a scenario is fully described by //! its accounts and transactions: @@ -439,8 +438,8 @@ mod tests { ); } - /// The block is the same for every scenario and for both arms of the differential harness, - /// except for the beneficiary, which the scenario sets. + /// The block is the same for every scenario, except for the beneficiary, which the scenario + /// sets. #[test] fn test_block_is_fixed_except_for_the_beneficiary() { let mut scenario = scenario(vec![]); From 3c25ededea6f6bd70774ef7a5d6cbefbbf2d2d16 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 09:48:39 +0800 Subject: [PATCH 088/201] feat(evm): build the Satin gas schedule from the two byte prices The schedule is Amsterdam's with the seventeen entries EIP-8038 repriced pressed back to their Osaka values and the EIP-8037 state-gas entries rebuilt from MegaETH's cost per state byte. The byte prices are an input, so a measurement build can run other ones through the std-only satin-price-override feature or the MEGA_SATIN_CPSB / MEGA_SATIN_CPHB environment variables; off by default. Nothing installs the schedule yet. --- crates/mega-evm/Cargo.toml | 4 + crates/mega-evm/src/evm/mod.rs | 4 + crates/mega-evm/src/evm/prices.rs | 387 ++++++++++++++++++++++++++++ crates/mega-evm/src/evm/schedule.rs | 270 +++++++++++++++++++ 4 files changed, 665 insertions(+) create mode 100644 crates/mega-evm/src/evm/prices.rs create mode 100644 crates/mega-evm/src/evm/schedule.rs diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 0989e6d51..675d000de 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -55,6 +55,10 @@ std = [ "revm/std", ] test-utils = ["dep:derive_more"] +# Measurement-only: lets a process fix other Satin byte prices than the constants, through +# `install_satin_prices` or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. +# Off by default, so a normal build prices with the constants and has no way to do otherwise. +satin-price-override = ["std"] # The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (the JSON scenarios under # benches/scenarios, a bench input) and `factory` (EVM construction). The inputs under diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index d545532ef..da7f5c387 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -12,7 +12,9 @@ mod frame; mod host; mod inspector; mod instructions; +mod prices; mod result; +mod schedule; mod spec; pub use context::*; @@ -21,7 +23,9 @@ pub use factory::*; pub use frame::*; pub use host::*; pub use inspector::*; +pub use prices::*; pub use result::*; +pub use schedule::*; pub use spec::*; use alloy_evm::EvmEnv; diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs new file mode 100644 index 000000000..c5a8fef10 --- /dev/null +++ b/crates/mega-evm/src/evm/prices.rs @@ -0,0 +1,387 @@ +//! The two byte prices the Satin gas table is built from, and a measurement-only way to build it +//! at prices other than the constants. +//! +//! Every Satin schedule entry that depends on a byte price reads it through +//! [`active_satin_prices`]: today the EIP-8037 state-gas entries, later the history entries. +//! +//! Without the `satin-price-override` feature [`active_satin_prices`] is a constant, so a build +//! that does not opt in prices with [`COST_PER_STATE_BYTE`] and [`COST_PER_HISTORY_BYTE`] and has +//! no way to do otherwise. With the feature, a process may fix other prices once, before it +//! executes anything, either with [`install_satin_prices`] or through the [`CPSB_ENV_VAR`] and +//! [`CPHB_ENV_VAR`] environment variables. Fixing nothing, or fixing the constants, leaves every +//! entry exactly where it was. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{fmt, str::FromStr}; +use std::string::String; + +use crate::constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}; + +/// Environment variable read for the cost per state byte when no price was installed. +pub const CPSB_ENV_VAR: &str = "MEGA_SATIN_CPSB"; + +/// Environment variable read for the cost per history byte when no price was installed. +pub const CPHB_ENV_VAR: &str = "MEGA_SATIN_CPHB"; + +/// Thousandths of a gas unit in one gas unit. +const MILLI_PER_GAS: u64 = 1_000; + +/// Decimal places a price may be written with: one per factor of ten in [`MILLI_PER_GAS`]. +const MAX_DECIMALS: usize = 3; + +/// The largest item a schedule entry prices, in bytes. A fixed-size charge is bounded by it, which +/// is what makes [`BytePrice::fixed_size_gas`] total. +const MAX_FIXED_SIZE_BYTES: u64 = MILLI_PER_GAS; + +/// A gas price per byte. +/// +/// Kept in thousandths of a gas unit, so a price such as 312.5 can be expressed. A charge is the +/// byte count times the price, rounded to the nearest whole gas unit with halves rounded up. A +/// whole-gas price never rounds: its charge is exactly `bytes * price` and overflows exactly where +/// that product does. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BytePrice { + milli_gas: u64, +} + +impl BytePrice { + /// A price of `gas` whole gas units per byte. + /// + /// # Panics + /// + /// If `gas` thousandths of a gas unit do not fit in a `u64`. + pub const fn from_gas(gas: u64) -> Self { + match gas.checked_mul(MILLI_PER_GAS) { + Some(milli_gas) => Self { milli_gas }, + None => panic!("byte price does not fit in thousandths of a gas unit"), + } + } + + /// A price of `milli_gas` thousandths of a gas unit per byte. + pub const fn from_milli_gas(milli_gas: u64) -> Self { + Self { milli_gas } + } + + /// The price in thousandths of a gas unit per byte. + pub const fn milli_gas(self) -> u64 { + self.milli_gas + } + + /// The gas `bytes` bytes cost at this price, or `None` if it does not fit in a `u64`. + #[inline] + pub const fn gas_for(self, bytes: u64) -> Option { + if self.milli_gas.is_multiple_of(MILLI_PER_GAS) { + return bytes.checked_mul(self.milli_gas / MILLI_PER_GAS); + } + let milli_gas = bytes as u128 * self.milli_gas as u128; + let gas = (milli_gas + MILLI_PER_GAS as u128 / 2) / MILLI_PER_GAS as u128; + if gas > u64::MAX as u128 { + None + } else { + Some(gas as u64) + } + } + + /// The gas a fixed-size item of `bytes` bytes costs at this price, for items of at most + /// [`MAX_FIXED_SIZE_BYTES`] bytes. + /// + /// Such a charge cannot overflow: a price is at most `u64::MAX` thousandths of a gas unit, so + /// a thousand bytes of it is at most `u64::MAX` gas. Schedule entries are priced through this, + /// which is why no price can make one fail. + /// + /// # Panics + /// + /// If `bytes` exceeds [`MAX_FIXED_SIZE_BYTES`]. + pub const fn fixed_size_gas(self, bytes: u64) -> u64 { + assert!(bytes <= MAX_FIXED_SIZE_BYTES, "a fixed-size item is at most a thousand bytes"); + match self.gas_for(bytes) { + Some(gas) => gas, + None => unreachable!(), + } + } +} + +impl fmt::Display for BytePrice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let whole = self.milli_gas / MILLI_PER_GAS; + let fraction = self.milli_gas % MILLI_PER_GAS; + if fraction == 0 { + return write!(f, "{whole}"); + } + let mut digits = [0u8; MAX_DECIMALS]; + let mut rest = fraction; + for digit in digits.iter_mut().rev() { + *digit = b'0' + (rest % 10) as u8; + rest /= 10; + } + let len = digits.iter().rposition(|d| *d != b'0').map_or(0, |last| last + 1); + let digits = core::str::from_utf8(&digits[..len]).expect("ASCII digits"); + write!(f, "{whole}.{digits}") + } +} + +impl FromStr for BytePrice { + type Err = String; + + /// Parses a non-negative decimal with at most three decimal places, such as `1530` or `312.5`. + fn from_str(s: &str) -> Result { + let (whole, fraction) = s.split_once('.').unwrap_or((s, "")); + let is_digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit()); + if whole.is_empty() || !is_digits(whole) || !is_digits(fraction) { + return Err(format!("`{s}` is not a non-negative decimal number")); + } + if s.contains('.') && fraction.is_empty() { + return Err(format!("`{s}` has no digits after the decimal point")); + } + if fraction.len() > MAX_DECIMALS { + return Err(format!("`{s}` has more than {MAX_DECIMALS} decimal places")); + } + let too_large = || format!("`{s}` is too large"); + let whole: u64 = whole.parse().map_err(|_| too_large())?; + let mut milli_fraction = 0u64; + for (place, digit) in fraction.bytes().enumerate() { + let scale = 10u64.pow((MAX_DECIMALS - 1 - place) as u32); + milli_fraction += u64::from(digit - b'0') * scale; + } + let milli_gas = whole + .checked_mul(MILLI_PER_GAS) + .and_then(|milli| milli.checked_add(milli_fraction)) + .ok_or_else(too_large)?; + Ok(Self { milli_gas }) + } +} + +/// The cost per state byte and the cost per history byte the Satin gas table is built from. +/// +/// `cphb` is carried and installable, but prices no schedule entry yet: history gas lands as its +/// own mechanism, and until then the schedule's history entry stays zero. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SatinPrices { + /// Cost per state byte: what one byte added to the world state costs. + pub cpsb: BytePrice, + /// Cost per history byte: what one byte appended to the chain's history costs. + pub cphb: BytePrice, +} + +/// Why a set of Satin prices was not accepted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SatinPriceError { + /// A price did not parse. + Invalid { + /// Where the price came from. + name: String, + /// What was wrong with it. + reason: String, + }, + /// The process had already fixed different prices. + AlreadyFixed { + /// The prices in effect. + installed: SatinPrices, + /// The prices that were asked for. + requested: SatinPrices, + }, +} + +impl fmt::Display for SatinPriceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Invalid { name, reason } => write!(f, "invalid {name}: {reason}"), + Self::AlreadyFixed { installed, requested } => write!( + f, + "Satin prices are already fixed at cpsb = {}, cphb = {}; cannot change them to \ + cpsb = {}, cphb = {}", + installed.cpsb, installed.cphb, requested.cpsb, requested.cphb + ), + } + } +} + +impl core::error::Error for SatinPriceError {} + +impl SatinPrices { + /// The prices the Satin spec defines: [`COST_PER_STATE_BYTE`] and [`COST_PER_HISTORY_BYTE`]. + pub const CONSTANTS: Self = Self { + cpsb: BytePrice::from_gas(COST_PER_STATE_BYTE), + cphb: BytePrice::from_gas(COST_PER_HISTORY_BYTE), + }; + + /// Whether these are the prices the Satin spec defines. + pub fn is_constants(&self) -> bool { + *self == Self::CONSTANTS + } + + /// Reads the prices from [`CPSB_ENV_VAR`] and [`CPHB_ENV_VAR`]; an unset variable keeps the + /// constant price. + #[cfg(feature = "std")] + pub fn from_env() -> Result { + let read = |name: &str, constant: BytePrice| match std::env::var(name) { + Ok(value) => value + .trim() + .parse() + .map_err(|reason| SatinPriceError::Invalid { name: name.to_string(), reason }), + Err(std::env::VarError::NotPresent) => Ok(constant), + Err(err) => { + Err(SatinPriceError::Invalid { name: name.to_string(), reason: err.to_string() }) + } + }; + Ok(Self { + cpsb: read(CPSB_ENV_VAR, Self::CONSTANTS.cpsb)?, + cphb: read(CPHB_ENV_VAR, Self::CONSTANTS.cphb)?, + }) + } +} + +#[cfg(feature = "satin-price-override")] +static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Fixes the prices the Satin gas table is built from for the rest of the process. +/// +/// Succeeds if nothing has fixed the prices yet, or if they are already fixed at `prices`. The +/// prices become fixed the first time a schedule is built, so this must run before anything is +/// executed. +#[cfg(feature = "satin-price-override")] +pub fn install_satin_prices(requested: SatinPrices) -> Result<(), SatinPriceError> { + let installed = *FIXED.get_or_init(|| requested); + if installed == requested { + Ok(()) + } else { + Err(SatinPriceError::AlreadyFixed { installed, requested }) + } +} + +/// The prices the Satin gas table is built from. +/// +/// Without the `satin-price-override` feature, always [`SatinPrices::CONSTANTS`]. +/// +/// # Panics +/// +/// With the feature, if nothing was installed and an environment variable holds an invalid price: +/// silently building at the constants would pass off one measurement as another. +#[inline] +pub fn active_satin_prices() -> SatinPrices { + #[cfg(feature = "satin-price-override")] + { + *FIXED.get_or_init(|| SatinPrices::from_env().unwrap_or_else(|err| panic!("{err}"))) + } + #[cfg(not(feature = "satin-price-override"))] + { + SatinPrices::CONSTANTS + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_prices_parse_as_decimals_with_up_to_three_places() { + let parse = |s: &str| s.parse::().map(BytePrice::milli_gas); + assert_eq!(parse("1530"), Ok(1_530_000)); + assert_eq!(parse("312.5"), Ok(312_500)); + assert_eq!(parse("0.125"), Ok(125)); + assert_eq!(parse("0"), Ok(0)); + assert_eq!(parse("007.050"), Ok(7_050)); + for bad in + ["", ".5", "5.", "-1", "+1", "1e3", "1.2345", "abc", "1 000", "18446744073709552"] + { + assert!(parse(bad).is_err(), "`{bad}` must be rejected"); + } + } + + #[test] + fn test_prices_print_as_they_parse() { + for s in ["1530", "312.5", "0.125", "0", "88", "1.05"] { + assert_eq!(s.parse::().unwrap().to_string(), s); + } + } + + /// A whole-gas price charges exactly `bytes * price`, overflowing exactly where the product + /// does, which is what makes the constants reproduce the unconditional arithmetic. + #[test] + fn test_a_whole_price_charges_the_plain_product() { + let bytes = [0, 1, 23, 64, 120, 524_288, u64::MAX / 1_530, u64::MAX / 1_530 + 1, u64::MAX]; + for gas in [0, 1, 88, 1_530, 40_000, u64::MAX / MILLI_PER_GAS] { + let price = BytePrice::from_gas(gas); + for &n in &bytes { + assert_eq!(price.gas_for(n), n.checked_mul(gas), "{n} bytes at {gas}"); + } + } + } + + #[test] + fn test_a_fractional_price_rounds_half_up() { + let price: BytePrice = "312.5".parse().unwrap(); + assert_eq!(price.gas_for(1), Some(313)); + assert_eq!(price.gas_for(2), Some(625)); + assert_eq!(price.gas_for(64), Some(20_000)); + assert_eq!(price.gas_for(23), Some(7_188)); + let price: BytePrice = "0.001".parse().unwrap(); + assert_eq!(price.gas_for(499), Some(0)); + assert_eq!(price.gas_for(500), Some(1)); + assert_eq!(price.gas_for(u64::MAX), Some(u64::MAX / 1000 + 1)); + let price: BytePrice = "1.5".parse().unwrap(); + assert_eq!(price.gas_for(u64::MAX), None); + } + + #[test] + fn test_the_constants_are_the_spec_prices() { + let constants = SatinPrices::CONSTANTS; + assert_eq!(constants.cpsb.gas_for(1), Some(COST_PER_STATE_BYTE)); + assert_eq!(constants.cphb.gas_for(1), Some(COST_PER_HISTORY_BYTE)); + assert!(constants.is_constants()); + assert!(!SatinPrices { cpsb: BytePrice::from_gas(1), ..constants }.is_constants()); + } + + /// No price can make a fixed-size charge overflow, which is why the schedule needs no + /// validation. + #[test] + fn test_a_thousand_bytes_of_any_price_fits() { + assert_eq!(BytePrice::from_milli_gas(u64::MAX).fixed_size_gas(1_000), u64::MAX); + let whole = BytePrice::from_gas(u64::MAX / MILLI_PER_GAS); + assert_eq!(whole.fixed_size_gas(1_000), u64::MAX / MILLI_PER_GAS * MILLI_PER_GAS); + } + + /// Without the override feature the active prices are the constants and nothing can change + /// them; with it, an unset environment leaves them at the constants too. + #[test] + fn test_the_active_prices_default_to_the_constants() { + assert_eq!(active_satin_prices(), SatinPrices::CONSTANTS); + } + + /// Installing the prices already in effect is accepted, so a measurement harness may install + /// unconditionally; installing different ones after that is refused, naming both. + #[cfg(feature = "satin-price-override")] + #[test] + fn test_installing_the_prices_in_effect_is_idempotent() { + assert_eq!(install_satin_prices(SatinPrices::CONSTANTS), Ok(())); + assert_eq!(install_satin_prices(SatinPrices::CONSTANTS), Ok(())); + + let requested = SatinPrices { cpsb: "312.5".parse().unwrap(), ..SatinPrices::CONSTANTS }; + assert_eq!( + install_satin_prices(requested), + Err(SatinPriceError::AlreadyFixed { installed: SatinPrices::CONSTANTS, requested }) + ); + assert_eq!(active_satin_prices(), SatinPrices::CONSTANTS); + } + + #[test] + fn test_price_errors_name_the_variable_and_the_installed_prices() { + let invalid = SatinPriceError::Invalid { + name: CPSB_ENV_VAR.to_string(), + reason: "`x` is not a non-negative decimal number".to_string(), + }; + assert_eq!( + invalid.to_string(), + "invalid MEGA_SATIN_CPSB: `x` is not a non-negative decimal number" + ); + let requested = SatinPrices { cpsb: "312.5".parse().unwrap(), ..SatinPrices::CONSTANTS }; + let already = + SatinPriceError::AlreadyFixed { installed: SatinPrices::CONSTANTS, requested }; + assert_eq!( + already.to_string(), + "Satin prices are already fixed at cpsb = 1530, cphb = 88; cannot change them to \ + cpsb = 312.5, cphb = 88" + ); + } +} diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs new file mode 100644 index 000000000..6022d0d1d --- /dev/null +++ b/crates/mega-evm/src/evm/schedule.rs @@ -0,0 +1,270 @@ +//! The Satin gas schedule. +//! +//! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, the EIP-2780 +//! intrinsic decomposition, the EIP-7976 calldata floor and EIP-7981 access-list data — and +//! changes exactly two things: +//! +//! 1. every entry EIP-8038 repriced goes back to its Osaka value ([`EIP8038_REPRICED`]), so state +//! *access* is priced as Osaka prices it and only state *creation* is repriced; +//! 2. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte +//! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than +//! Glamsterdam's. +//! +//! Every other entry is Amsterdam's, including the EIP-2780 decomposition entries +//! (`tx_account_write_cost`, `tx_create_access_cost`), the zero `code_deposit_cost` and the floor. +//! The history entry stays at zero: history gas is its own mechanism and switches it on. +//! +//! The schedule is built once per `CfgEnv` — [`MegaContext::with_cfg`](crate::MegaContext) — and +//! read per opcode out of the table revm already carries, so nothing here runs on the hot path. + +use revm::{ + context_interface::cfg::{GasId, GasParams}, + primitives::{eip8037, hardfork::SpecId}, +}; + +use crate::evm::prices::{active_satin_prices, SatinPrices}; + +/// The schedule entries EIP-8038 repriced, which Satin keeps at their pre-EIP-8038 values. +/// +/// EIP-8038 raises the price of *reaching* state — a cold account, a cold slot, a storage write, +/// an account write. Satin prices state creation on its own dimension instead (EIP-8037 state gas +/// at [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE)), so it does not adopt that +/// second increase: every entry EIP-8038 moved is pushed back to what the Osaka schedule has. +/// +/// Entries Amsterdam introduced for EIP-2780, EIP-7976 and EIP-7981 are not in this list and keep +/// their Amsterdam values, even where the number itself is derived from an EIP-8038 constant. +pub const EIP8038_REPRICED: &[fn() -> GasId] = &[ + GasId::warm_storage_read_cost, + GasId::cold_account_additional_cost, + GasId::cold_storage_additional_cost, + GasId::cold_storage_cost, + GasId::transfer_value_cost, + GasId::new_account_cost, + GasId::new_account_cost_for_selfdestruct, + GasId::sstore_static, + GasId::sstore_set_without_load_cost, + GasId::sstore_reset_without_cold_load_cost, + GasId::sstore_set_refund, + GasId::sstore_reset_refund, + GasId::sstore_clearing_slot_refund, + GasId::create, + GasId::tx_create_cost, + GasId::tx_access_list_address_cost, + GasId::tx_access_list_storage_key_cost, +]; + +/// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte +/// price. +type ScheduleEntry = (fn() -> GasId, u64); + +/// The EIP-8037 state-gas entries, rebuilt at `MegaETH`'s own cost per state byte. +/// +/// Each entry is a byte count times the cost per state byte. The byte counts are EIP-8037's — +/// what a leaf, a storage slot or a delegation indicator actually occupies — and `MegaETH` keeps +/// them; only the price of a byte is `MegaETH`'s, which is the whole of the divergence from the +/// Amsterdam schedule here. +pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ + (GasId::sstore_set_state_gas, eip8037::SSTORE_SET_BYTES), + (GasId::new_account_state_gas, eip8037::NEW_ACCOUNT_BYTES), + (GasId::create_state_gas, eip8037::NEW_ACCOUNT_BYTES), + (GasId::code_deposit_state_gas, eip8037::CODE_DEPOSIT_PER_BYTE), + (GasId::tx_eip7702_state_gas_bytecode, eip8037::AUTH_BASE_BYTES), +]; + +/// The Satin gas schedule at the prices in effect. +/// +/// See the module documentation for what it changes; [`satin_gas_params_at`] is the same schedule +/// with the byte prices taken as given rather than read from the process. +pub fn satin_gas_params() -> GasParams { + satin_gas_params_at(active_satin_prices()) +} + +/// The Satin gas schedule at `prices`. +pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { + let osaka = GasParams::new_spec(SpecId::OSAKA); + let mut params = GasParams::new_spec(SpecId::AMSTERDAM); + params.override_gas(EIP8038_REPRICED.iter().map(|id| { + let id = id(); + (id, osaka.get(id)) + })); + params.override_gas( + STATE_GAS_REPRICED.iter().map(|&(id, bytes)| (id(), prices.cpsb.fixed_size_gas(bytes))), + ); + params +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + constants::{ACCOUNT_STATE_GAS, COST_PER_STATE_BYTE, SLOT_STATE_GAS}, + evm::prices::BytePrice, + }; + + fn osaka() -> GasParams { + GasParams::new_spec(SpecId::OSAKA) + } + + fn amsterdam() -> GasParams { + GasParams::new_spec(SpecId::AMSTERDAM) + } + + /// The seventeen entries EIP-8038 repriced are back at their Osaka values, written out so a + /// change to the list is a visible diff. + #[test] + fn test_the_eip8038_repricing_is_pressed_back_to_osaka() { + let satin = satin_gas_params(); + let names = [ + "warm_storage_read_cost", + "cold_account_additional_cost", + "cold_storage_additional_cost", + "cold_storage_cost", + "transfer_value_cost", + "new_account_cost", + "new_account_cost_for_selfdestruct", + "sstore_static", + "sstore_set_without_load_cost", + "sstore_reset_without_cold_load_cost", + "sstore_set_refund", + "sstore_reset_refund", + "sstore_clearing_slot_refund", + "create", + "tx_create_cost", + "tx_access_list_address_cost", + "tx_access_list_storage_key_cost", + ]; + assert_eq!(EIP8038_REPRICED.len(), names.len(), "the list and its names agree"); + for (id, name) in EIP8038_REPRICED.iter().zip(names) { + assert_eq!(id().name(), name); + } + for id in EIP8038_REPRICED { + let id = id(); + assert_eq!(satin.get(id), osaka().get(id), "{} must be Osaka-priced", id.name()); + } + } + + /// The Osaka numbers those seventeen entries carry, so a change in the base schedule shows up + /// here rather than silently moving Satin. + #[test] + fn test_the_pressed_back_entries_carry_the_osaka_numbers() { + let satin = satin_gas_params(); + for (name, value) in [ + ("warm_storage_read_cost", 100), + ("cold_account_additional_cost", 2_500), + ("cold_storage_additional_cost", 2_000), + ("cold_storage_cost", 2_100), + ("transfer_value_cost", 9_000), + ("new_account_cost", 25_000), + ("new_account_cost_for_selfdestruct", 25_000), + ("sstore_static", 100), + ("sstore_set_without_load_cost", 19_900), + ("sstore_reset_without_cold_load_cost", 2_800), + ("sstore_set_refund", 19_900), + ("sstore_reset_refund", 2_800), + ("sstore_clearing_slot_refund", 4_800), + ("create", 32_000), + ("tx_create_cost", 32_000), + ("tx_access_list_address_cost", 2_400), + ("tx_access_list_storage_key_cost", 1_900), + ] { + let id = GasId::from_name(name).expect("a known gas id"); + assert_eq!(satin.get(id), value, "{name}"); + } + } + + /// Every entry outside the seventeen is Amsterdam's. The state-gas entries are rebuilt from + /// the cost per state byte rather than copied, so they are checked separately; at the + /// provisional price they land on Amsterdam's numbers too, which + /// [`test_other_prices_move_only_the_state_entries`] shows is a coincidence of the price and + /// not a copy. + #[test] + fn test_every_other_entry_is_amsterdam() { + let (satin, amsterdam) = (satin_gas_params(), amsterdam()); + for slot in 0..=u8::MAX { + let id = GasId::new(slot); + let rebuilt = EIP8038_REPRICED.iter().any(|entry| entry() == id) || + STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id); + if rebuilt { + continue; + } + assert_eq!(satin.get(id), amsterdam.get(id), "{} must be Amsterdam's", id.name()); + } + // The entries Amsterdam introduced whose value is derived from an EIP-8038 constant stay + // Amsterdam's all the same; spelled out because pressing them back would be plausible. + for (name, value) in [ + ("tx_account_write_cost", 9_000), + ("tx_create_access_cost", 12_000), + ("code_deposit_cost", 0), + ("tx_floor_cost_base_gas", 12_000), + ("tx_floor_cost_per_token", 16), + ("tx_floor_token_zero_byte_multiplier", 4), + ("tx_access_list_floor_byte_multiplier", 4), + ] { + let id = GasId::from_name(name).expect("a known gas id"); + assert_eq!(satin.get(id), value, "{name}"); + assert_eq!(amsterdam.get(id), value, "{name} is Amsterdam's"); + } + } + + /// History gas is a later mechanism; until it lands the schedule prices no history byte, the + /// way Osaka and Amsterdam do not. + #[test] + fn test_the_history_entry_is_not_priced_yet() { + let id = GasId::code_deposit_history_gas(); + assert_eq!(satin_gas_params().get(id), 0); + assert_eq!(osaka().get(id), 0); + assert_eq!(amsterdam().get(id), 0); + } + + /// The state entries are EIP-8037's byte counts at `MegaETH`'s price. Dividing an entry by + /// the price recovers the byte count the EIP names, which is the property that survives a + /// repricing. + #[test] + fn test_state_entries_recover_the_eip8037_byte_counts() { + let satin = satin_gas_params(); + for &(id, bytes) in STATE_GAS_REPRICED { + let id = id(); + assert_eq!(satin.get(id), bytes * COST_PER_STATE_BYTE, "{} at the price", id.name()); + assert_eq!(satin.get(id) / COST_PER_STATE_BYTE, bytes, "{} in bytes", id.name()); + } + assert_eq!(satin.get(GasId::sstore_set_state_gas()), SLOT_STATE_GAS); + assert_eq!(satin.get(GasId::sstore_set_state_gas()), 97_920); + assert_eq!(satin.get(GasId::new_account_state_gas()), ACCOUNT_STATE_GAS); + assert_eq!(satin.get(GasId::new_account_state_gas()), 183_600); + assert_eq!(satin.get(GasId::create_state_gas()), 183_600); + assert_eq!(satin.get(GasId::code_deposit_state_gas()), 1_530); + assert_eq!(satin.get(GasId::tx_eip7702_state_gas_bytecode()), 35_190); + } + + /// Other prices move the five state entries and nothing else, which is what makes a + /// measurement build a repricing rather than a different schedule. + #[test] + fn test_other_prices_move_only_the_state_entries() { + let constants = satin_gas_params_at(SatinPrices::CONSTANTS); + let prices = SatinPrices { cpsb: "312.5".parse().unwrap(), cphb: BytePrice::from_gas(400) }; + let repriced = satin_gas_params_at(prices); + let expected = [ + (GasId::sstore_set_state_gas(), 20_000), + (GasId::new_account_state_gas(), 37_500), + (GasId::create_state_gas(), 37_500), + (GasId::code_deposit_state_gas(), 313), + (GasId::tx_eip7702_state_gas_bytecode(), 7_188), + ]; + for slot in 0..=u8::MAX { + let id = GasId::new(slot); + match expected.iter().find(|(moved, _)| *moved == id) { + Some((_, value)) => assert_eq!(repriced.get(id), *value, "{}", id.name()), + None => { + assert_eq!(repriced.get(id), constants.get(id), "{} must not move", id.name()) + } + } + } + } + + /// The prices in effect are the constants, so the schedule the engine installs is the one + /// built at them. + #[test] + fn test_the_schedule_at_the_active_prices_is_the_schedule_at_the_constants() { + assert_eq!(satin_gas_params().table(), satin_gas_params_at(SatinPrices::CONSTANTS).table()); + } +} From 8ad894e4e9c03e2778ed22313c5af001f3b2e7cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:01:21 +0800 Subject: [PATCH 089/201] feat(block): read a chain's hardfork schedule Adds the schedule block execution reads a chain through: `MegaHardforks` over `OpHardforks`, the `MegaHardforkConfig` that carries the Ethereum, Optimism and MegaETH forks together, and `HardforkParams` for the values a fork needs from the chain configuration. A schedule is checked once, when it is loaded: `validate_schedule` refuses a fork registered on a block number or total difficulty, which the timestamp-scoped resolution would never activate, and `require_params` is the rule a fork registers so a schedule that activates it without its parameters fails at load rather than at the fork's first block. Satin requires no parameters yet, so the registration point is a named block in `validate_schedule`. `spec_id` answers `Option`: before the Satin activation a chain runs its pre-Satin engine, which this crate does not execute. The chain table now builds the schedules it describes, so the two cannot drift: `mainnet_hardforks`, `testnet_hardforks` and the unknown-chain fallback all come from `CHAIN_ACTIVATIONS`. Satin stays unscheduled on both known chains; an unknown chain runs `FALLBACK_RUNG` from genesis, pinned here rather than taken from `MegaSpecId::default`. Ports the 17 parked unit rows of the schedule and the chain table. --- Cargo.lock | 1 + crates/mega-evm/Cargo.toml | 1 + crates/mega-evm/src/block/chain.rs | 149 ++++- crates/mega-evm/src/block/hardfork.rs | 551 +++++++++++++++++- crates/mega-evm/tests/_pending/README.md | 16 +- .../tests/_pending/src/block/chain.rs | 100 ---- .../tests/_pending/src/block/hardfork.rs | 233 -------- 7 files changed, 705 insertions(+), 346 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/src/block/chain.rs delete mode 100644 crates/mega-evm/tests/_pending/src/block/hardfork.rs diff --git a/Cargo.lock b/Cargo.lock index 8c311d18f..1890f3100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2768,6 +2768,7 @@ dependencies = [ "alloy-evm", "alloy-hardforks", "alloy-op-evm", + "alloy-op-hardforks", "alloy-primitives", "alloy-sol-types", "auto_impl", diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 0989e6d51..cd6ee04fc 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -18,6 +18,7 @@ alloy-consensus = { workspace = true, features = ["k256"] } alloy-evm.workspace = true alloy-hardforks.workspace = true alloy-op-evm.workspace = true +alloy-op-hardforks.workspace = true alloy-primitives.workspace = true alloy-sol-types.workspace = true op-alloy-consensus.workspace = true diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 90edcbda0..ed3add095 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -1,27 +1,60 @@ //! Per-chain activation of the `MegaETH` hardforks of the Satin engine. //! -//! This is the single place that records when each [`MegaHardfork`](crate::MegaHardfork) -//! activates on the known `MegaETH` chains. The node chainspecs decide the schedule; this table -//! mirrors it for tools that replay a real chain. +//! This is the single place that records when each [`MegaHardfork`] activates on the known +//! `MegaETH` chains. The node chainspecs decide the schedule; this table mirrors it for tools +//! that replay a real chain, and [`hardfork_schedule`] turns a chain ID into the schedule block +//! execution reads. +use alloy_hardforks::ForkCondition; use alloy_primitives::BlockTimestamp; +use crate::{MegaHardfork, MegaHardforkConfig, MegaSpecId}; + /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; /// `MegaETH` testnet v2 chain ID. pub const TESTNET_CHAIN_ID: u64 = 6343; +/// The rung an unknown chain runs, from genesis. +/// +/// Pinned, not taken from [`MegaSpecId::default`]: an unknown chain runs this spec from block +/// zero with no fork boundary, so introducing a spec must leave it alone — registering a fork +/// above the pin would rewrite what history such a chain has already produced means. Raising the +/// pin is a decision of its own, made by editing this constant. +pub const FALLBACK_RUNG: MegaSpecId = MegaSpecId::SATIN; + /// Activation timestamps of the Satin-engine hardforks on one chain. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ChainActivation { /// The chain the timestamps belong to. pub chain_id: u64, - /// When [`MegaHardfork::Satin`](crate::MegaHardfork::Satin) activates; `None` while it is - /// not scheduled. + /// When [`MegaHardfork::Satin`] activates; `None` while it is not scheduled. pub satin: Option, } +impl ChainActivation { + /// The activation condition of `fork` on this chain. + pub const fn condition(&self, fork: MegaHardfork) -> ForkCondition { + let timestamp = match fork { + MegaHardfork::Satin => self.satin, + }; + match timestamp { + Some(timestamp) => ForkCondition::Timestamp(timestamp), + None => ForkCondition::Never, + } + } + + /// The hardfork schedule of this chain. + pub fn hardforks(&self) -> MegaHardforkConfig { + let mut config = MegaHardforkConfig::new(); + for fork in MegaHardfork::VARIANTS { + config.insert(*fork, self.condition(*fork)); + } + config + } +} + /// Activation table of the known `MegaETH` chains. pub const CHAIN_ACTIVATIONS: [ChainActivation; 2] = [ ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: None }, @@ -33,9 +66,39 @@ pub fn chain_activation(chain_id: u64) -> Option { CHAIN_ACTIVATIONS.iter().find(|activation| activation.chain_id == chain_id).copied() } +/// The hardfork schedule of `MegaETH` mainnet. +pub fn mainnet_hardforks() -> MegaHardforkConfig { + chain_activation(MAINNET_CHAIN_ID).expect("mainnet is in the activation table").hardforks() +} + +/// The hardfork schedule of `MegaETH` testnet. +pub fn testnet_hardforks() -> MegaHardforkConfig { + chain_activation(TESTNET_CHAIN_ID).expect("testnet is in the activation table").hardforks() +} + +/// The schedule an unknown chain runs: every fork up to [`FALLBACK_RUNG`], active at genesis. +pub fn all_activated_hardforks() -> MegaHardforkConfig { + let mut config = MegaHardforkConfig::new(); + for fork in MegaHardfork::VARIANTS { + let condition = if fork.spec_id() <= FALLBACK_RUNG { + ForkCondition::Timestamp(0) + } else { + ForkCondition::Never + }; + config.insert(*fork, condition); + } + config +} + +/// The hardfork schedule of `chain_id`: a known chain's table, or the unknown-chain fallback. +pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { + chain_activation(chain_id).map_or_else(all_activated_hardforks, |a| a.hardforks()) +} + #[cfg(test)] mod tests { use super::*; + use crate::MegaHardforks; #[test] fn test_known_chains_have_satin_unscheduled() { @@ -48,4 +111,80 @@ mod tests { } assert_eq!(chain_activation(1), None); } + + #[test] + fn test_mainnet_schedule_resolves_specs_by_timestamp() { + let hf = mainnet_hardforks(); + assert_eq!(hf.mega_fork_activation(MegaHardfork::Satin), ForkCondition::Never); + assert_eq!(hf.spec_id(0), None, "Satin is not scheduled on mainnet yet"); + assert_eq!(hf.spec_id(u64::MAX), None); + assert_eq!(hf.validate_schedule(), Ok(())); + } + + #[test] + fn test_testnet_schedule_resolves_specs_by_timestamp() { + let hf = testnet_hardforks(); + assert_eq!(hf.mega_fork_activation(MegaHardfork::Satin), ForkCondition::Never); + assert_eq!(hf.spec_id(0), None, "Satin is not scheduled on testnet yet"); + assert_eq!(hf.spec_id(u64::MAX), None); + assert_eq!(hf.validate_schedule(), Ok(())); + } + + /// A scheduled chain resolves the spec its table gives, at the timestamp the table gives. + #[test] + fn test_a_scheduled_activation_resolves_at_its_timestamp() { + let hf = + ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) }.hardforks(); + + assert_eq!(hf.spec_id(1_799_999_999), None); + assert_eq!(hf.spec_id(1_800_000_000), Some(MegaSpecId::SATIN)); + assert_eq!(hf.validate_schedule(), Ok(())); + } + + #[test] + fn test_schedule_dispatch_by_chain_id() { + assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(0), None); + assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(0), None); + // Unknown chain: every fork up to the pinned rung, active at genesis. + assert_eq!(hardfork_schedule(1).spec_id(0), Some(FALLBACK_RUNG)); + } + + /// The fallback schedule is one a chain can run: it needs no parameters that are not there, + /// so an unknown chain ID starts rather than failing at its first block. + #[test] + fn test_unknown_chain_fallback_is_a_runnable_schedule() { + let hf = hardfork_schedule(999_999); + + assert_eq!(hf.spec_id(0), Some(FALLBACK_RUNG)); + assert_eq!(hf.validate_schedule(), Ok(())); + } + + /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. + /// + /// Unknown chains run their rung from genesis, so it is their semantics from block zero with + /// no fork boundary. Introducing a spec must therefore leave them alone. What this pins is + /// drift: the fallback silently following `MegaSpecId::default` again, and the rung advancing + /// without [`FALLBACK_RUNG`] being edited in the same change. + #[test] + fn test_unknown_chain_fallback_pins_its_rung() { + let hf = all_activated_hardforks(); + const RUNG: MegaSpecId = MegaSpecId::SATIN; + + assert_eq!(FALLBACK_RUNG, RUNG, "the pin moves only by editing it here too"); + assert_eq!(hf.spec_id(0), Some(RUNG), "the rung applies from genesis"); + assert_eq!( + hf.spec_id(u64::MAX), + Some(RUNG), + "and is terminal — no later fork is registered" + ); + + for fork in MegaHardfork::VARIANTS { + let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; + assert_eq!( + registered, + fork.spec_id() <= RUNG, + "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" + ); + } + } } diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index aa364f4af..3a68f53f0 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -1,6 +1,20 @@ -//! `MegaETH` hardforks of the Satin engine. +//! `MegaETH` hardforks of the Satin engine, and the schedule a chain activates them on. +//! +//! [`MegaHardfork`] is the fork; [`MegaHardforkConfig`] is a schedule that mixes it with the +//! Ethereum and Optimism forks; [`MegaHardforks`] is what block execution reads a schedule +//! through. A schedule is checked once, when it is loaded +//! ([`validate_schedule`](MegaHardforks::validate_schedule)), so a malformed chain configuration +//! fails at load rather than at the fork's first block. -use alloy_hardforks::hardfork; +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{any::Any, fmt}; +use std::{boxed::Box, string::String, sync::Arc, vec, vec::Vec}; + +use alloy_hardforks::{hardfork, EthereumHardfork, EthereumHardforks, ForkCondition, Hardfork}; +use alloy_op_hardforks::{OpHardfork, OpHardforks}; +use alloy_primitives::{BlockTimestamp, U256}; +use auto_impl::auto_impl; use crate::MegaSpecId; @@ -26,13 +40,385 @@ impl MegaHardfork { } } +/// An invalid value of a [`HardforkParams`] type, as its +/// [`validate`](HardforkParams::validate) reports it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HardforkParamsError { + /// Which field or invariant is wrong. + pub message: String, +} + +impl fmt::Display for HardforkParamsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl core::error::Error for HardforkParamsError {} + +/// Parameters a fork needs from the chain configuration. +/// +/// A params type belongs to exactly one fork ([`FORK`](Self::FORK)), so +/// [`fork_params`](MegaHardforks::fork_params) returns it without the caller naming the fork +/// twice. [`validate`](Self::validate) states the invariants of the value itself; +/// [`MegaHardforkConfig::with_params`] runs it when the configuration is built, so a bad value +/// fails at load. A fork that cannot run without its parameters also registers the requirement in +/// [`validate_schedule`](MegaHardforks::validate_schedule). +pub trait HardforkParams: Any + fmt::Debug + Send + Sync { + /// The hardfork these parameters belong to. + const FORK: MegaHardfork; + + /// How [`ScheduleError::MissingParams`] names this type. + const NAME: &'static str; + + /// Checks the invariants of this value. The default accepts anything. + fn validate(&self) -> Result<(), HardforkParamsError> { + Ok(()) + } +} + +/// Extends [`OpHardforks`] with the `MegaETH` forks. +/// +/// Satin is the only `MegaETH` fork, so a schedule answers two questions: whether the chain has +/// reached it at a timestamp, and which spec it runs there. Before the Satin activation the chain +/// does not run this engine at all, which is why +/// [`spec_id`](Self::spec_id) answers `None` rather than an earlier spec. +#[auto_impl(&, Box, Arc)] +pub trait MegaHardforks: OpHardforks { + /// The activation condition of `fork`, or [`ForkCondition::Never`] if the schedule does not + /// carry it. + fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; + + /// The parameters attached to `fork`, type-erased. Forks without parameters answer `None`. + fn fork_params_any(&self, _fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { + None + } + + /// The parameters of the fork `P` belongs to, or `None` when the schedule carries none. + fn fork_params(&self) -> Option<&P> { + self.fork_params_any(P::FORK)?.downcast_ref::

() + } + + /// The latest `MegaETH` fork active at `timestamp`, or `None` before the first one. + /// + /// Resolution reads raw activation events and walks [`MegaHardfork::VARIANTS`] from the top, + /// so a fork declared later wins at an equal timestamp. + fn hardfork(&self, timestamp: BlockTimestamp) -> Option { + MegaHardfork::VARIANTS + .iter() + .rev() + .find(|fork| self.mega_fork_activation(**fork).active_at_timestamp(timestamp)) + .copied() + } + + /// The spec this engine executes at `timestamp`, or `None` when no `MegaETH` fork is active + /// there — the chain runs its pre-Satin engine, which this crate does not execute. + fn spec_id(&self, timestamp: BlockTimestamp) -> Option { + self.hardfork(timestamp).map(|fork| fork.spec_id()) + } + + /// Whether [`MegaHardfork::Satin`] has activated at `timestamp`. + fn is_satin_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { + self.mega_fork_activation(MegaHardfork::Satin).active_at_timestamp(timestamp) + } + + /// Refuses a schedule that activates `P::FORK` without attaching `P`. + /// + /// This is the rule [`validate_schedule`](Self::validate_schedule) applies to every params + /// type a fork requires; it is public so a params type can be checked on its own. + fn require_params(&self) -> Result<(), ScheduleError> { + if self.mega_fork_activation(P::FORK) != ForkCondition::Never && + self.fork_params::

().is_none() + { + return Err(ScheduleError::MissingParams { fork: P::FORK, params: P::NAME }); + } + Ok(()) + } + + /// Checks that this schedule is one a chain can run, so a configuration mistake is caught + /// when the chain configuration is loaded rather than at the fork's first block. + /// + /// Checked: + /// + /// - Every registered `MegaETH` fork activates by [`ForkCondition::Timestamp`] (or is + /// [`ForkCondition::Never`]). Resolution is timestamp-scoped, so a block-number or + /// total-difficulty condition would silently never activate the fork. + /// - The parameters every scheduled fork requires are attached + /// ([`require_params`](Self::require_params)). Satin requires none yet: a mechanism that + /// brings a [`HardforkParams`] type registers it here, in the block marked below, and the + /// requirement is enforced from that change on. + /// + /// There is no ordering or gap check: a single fork has nothing to be out of order with. The + /// spec that follows Satin brings the ladder back, and with it those checks. + fn validate_schedule(&self) -> Result<(), ScheduleError> { + for fork in MegaHardfork::VARIANTS { + match self.mega_fork_activation(*fork) { + ForkCondition::Never | ForkCondition::Timestamp(_) => {} + _ => return Err(ScheduleError::NonTimestampActivation { fork: *fork }), + } + } + + // Required parameters, one `self.require_params::

()?` per params type. Satin has none. + + Ok(()) + } +} + +/// A schedule a chain cannot run, as [`MegaHardforks::validate_schedule`] reports it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ScheduleError { + /// A `MegaETH` fork is registered with a block-number or total-difficulty condition, which + /// the timestamp-scoped resolution never reports as active. + NonTimestampActivation { + /// The fork with the wrong condition. + fork: MegaHardfork, + }, + /// A scheduled fork requires parameters that the schedule does not carry. + MissingParams { + /// The scheduled fork. + fork: MegaHardfork, + /// The required params type, as [`HardforkParams::NAME`] names it. + params: &'static str, + }, +} + +impl fmt::Display for ScheduleError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NonTimestampActivation { fork } => { + write!(f, "hardfork {fork:?} must activate by timestamp, not block number or TTD") + } + Self::MissingParams { fork, params } => { + write!( + f, + "hardfork {fork:?} is scheduled but its {params} params are not configured" + ) + } + } + } +} + +impl core::error::Error for ScheduleError {} + +/// One fork of a schedule: which fork, when it activates, and the parameters it carries. +#[derive(Debug)] +struct ForkEntry { + fork: Box, + condition: ForkCondition, + params: Option>, +} + +impl Clone for ForkEntry { + fn clone(&self) -> Self { + Self { fork: self.fork.clone(), condition: self.condition, params: self.params.clone() } + } +} + +/// A chain's hardfork schedule. +/// +/// [`new`](Self::new) activates every Ethereum and Optimism fork up to and including the base +/// Satin runs on (Osaka / Karst) at genesis, and no `MegaETH` fork: those the caller schedules, +/// with [`with`](Self::with) or [`with_all_activated`](Self::with_all_activated). +#[derive(Debug, Clone)] +pub struct MegaHardforkConfig { + entries: Vec, +} + +impl Default for MegaHardforkConfig { + fn default() -> Self { + Self::new() + } +} + +impl From for MegaHardforkConfig +where + I: Iterator, + H: Hardfork + 'static, +{ + fn from(iter: I) -> Self { + Self { + entries: iter + .map(|(fork, condition)| ForkEntry { + fork: Box::new(fork) as Box, + condition, + params: None, + }) + .collect(), + } + } +} + +impl MegaHardforkConfig { + /// A schedule with every Ethereum and Optimism fork up to Osaka / Karst active at genesis, + /// and no `MegaETH` fork. + /// + /// Karst is the base [`MegaSpecId::SATIN`] runs on, so a chain executing Satin has already + /// passed every fork below it; the schedule states that rather than leaving the node to + /// repeat it. + pub fn new() -> Self { + let forks: Vec<(Box, ForkCondition)> = vec![ + (EthereumHardfork::Frontier.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Homestead.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Dao.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Tangerine.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::SpuriousDragon.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Byzantium.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Constantinople.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Petersburg.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Istanbul.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::Berlin.boxed(), ForkCondition::Block(0)), + (EthereumHardfork::London.boxed(), ForkCondition::Block(0)), + ( + EthereumHardfork::Paris.boxed(), + ForkCondition::TTD { + activation_block_number: 0, + fork_block: None, + total_difficulty: U256::ZERO, + }, + ), + (OpHardfork::Bedrock.boxed(), ForkCondition::Block(0)), + (OpHardfork::Regolith.boxed(), ForkCondition::Timestamp(0)), + (EthereumHardfork::Shanghai.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Canyon.boxed(), ForkCondition::Timestamp(0)), + (EthereumHardfork::Cancun.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Ecotone.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Fjord.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Granite.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Holocene.boxed(), ForkCondition::Timestamp(0)), + (EthereumHardfork::Prague.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Isthmus.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Jovian.boxed(), ForkCondition::Timestamp(0)), + (EthereumHardfork::Osaka.boxed(), ForkCondition::Timestamp(0)), + (OpHardfork::Karst.boxed(), ForkCondition::Timestamp(0)), + ]; + Self { + entries: forks + .into_iter() + .map(|(fork, condition)| ForkEntry { fork, condition, params: None }) + .collect(), + } + } + + /// Activates every `MegaETH` fork at timestamp 0. + pub fn with_all_activated(mut self) -> Self { + for fork in MegaHardfork::VARIANTS { + self.insert(*fork, ForkCondition::Timestamp(0)); + } + self + } + + /// Attaches `params` to the fork they belong to. + /// + /// # Panics + /// + /// If the fork is not registered in this schedule, or if `params.validate()` refuses the + /// value — a chain configuration is built once, at load, and a bad one must not start. + pub fn with_params(mut self, params: P) -> Self { + if let Err(e) = params.validate() { + panic!("Invalid params for fork {:?}: {}", P::FORK, e.message); + } + let entry = self + .entries + .iter_mut() + .find(|entry| entry.fork.name() == P::FORK.name()) + .unwrap_or_else(|| { + panic!( + "Cannot attach params to fork {:?}: fork not registered in config. \ + Call .with({:?}, condition) first.", + P::FORK, + P::FORK, + ) + }); + entry.params = Some(Arc::new(params)); + self + } + + /// Removes a `MegaETH` fork, which is what [`ForkCondition::Never`] means. + pub fn without(mut self, hardfork: MegaHardfork) -> Self { + self.entries.retain(|entry| entry.fork.name() != hardfork.name()); + self + } + + /// Adds `hardfork` with `condition`, or replaces its condition if it is already there. + pub fn with(mut self, hardfork: impl Hardfork, condition: ForkCondition) -> Self { + self.insert(hardfork, condition); + self + } + + /// Adds `hardfork` with `condition`. An entry that is already there keeps its parameters and + /// takes the new condition. + pub fn insert(&mut self, hardfork: impl Hardfork, condition: ForkCondition) { + let index = self.entries.iter().position(|entry| entry.fork.name() == hardfork.name()); + if let Some(index) = index { + self.entries[index].condition = condition; + } else { + self.entries.push(ForkEntry { fork: Box::new(hardfork), condition, params: None }); + } + } + + /// The condition `hardfork` activates on, or `None` if the schedule does not carry it. + pub fn get(&self, hardfork: impl Hardfork) -> Option<&ForkCondition> { + self.entries + .iter() + .find(|entry| entry.fork.name() == hardfork.name()) + .map(|entry| &entry.condition) + } +} + +impl EthereumHardforks for MegaHardforkConfig { + fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { + self.get(fork).copied().unwrap_or(ForkCondition::Never) + } +} + +impl OpHardforks for MegaHardforkConfig { + fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { + self.get(fork).copied().unwrap_or(ForkCondition::Never) + } +} + +impl MegaHardforks for MegaHardforkConfig { + fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { + self.get(fork).copied().unwrap_or(ForkCondition::Never) + } + + fn fork_params_any(&self, fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { + self.entries + .iter() + .find(|entry| entry.fork.name() == fork.name()) + .and_then(|entry| entry.params.as_deref()) + } +} + #[cfg(test)] mod tests { use super::*; - use crate::MegaSpecId; - use alloy_hardforks::Hardfork; + use alloy_primitives::address; use core::str::FromStr; + /// A params type of this test module alone: the fork-requires-params rule is a mechanism + /// here, and Satin has no params type of its own yet. + #[derive(Clone, Debug, PartialEq, Eq)] + struct TestParams { + sequencer: alloy_primitives::Address, + } + + impl HardforkParams for TestParams { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "TestParams"; + + fn validate(&self) -> Result<(), HardforkParamsError> { + if self.sequencer.is_zero() { + return Err(HardforkParamsError { message: "sequencer must be set".into() }); + } + Ok(()) + } + } + + fn params() -> TestParams { + TestParams { sequencer: address!("0x2222222222222222222222222222222222222222") } + } + #[test] fn test_satin_fork_schedules_the_satin_spec() { assert_eq!(MegaHardfork::VARIANTS, &[MegaHardfork::Satin]); @@ -48,4 +434,161 @@ mod tests { assert!(MegaHardfork::from_str(legacy).is_err(), "{legacy} must not parse"); } } + + #[test] + fn test_default_config_contains_upstream_forks_and_no_mega_forks() { + let config = MegaHardforkConfig::default(); + + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Frontier), + ForkCondition::Block(0) + ); + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Prague), + ForkCondition::Timestamp(0) + ); + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Osaka), + ForkCondition::Timestamp(0) + ); + assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); + assert_eq!(config.op_fork_activation(OpHardfork::Karst), ForkCondition::Timestamp(0)); + assert_eq!(config.mega_fork_activation(MegaHardfork::Satin), ForkCondition::Never); + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_config_builder_helpers_override_and_remove_hardforks() { + let mut config = + MegaHardforkConfig::new().with(MegaHardfork::Satin, ForkCondition::Timestamp(10)); + + assert_eq!(config.get(MegaHardfork::Satin), Some(&ForkCondition::Timestamp(10))); + + config.insert(MegaHardfork::Satin, ForkCondition::Timestamp(20)); + assert_eq!(config.get(MegaHardfork::Satin), Some(&ForkCondition::Timestamp(20))); + + let config = config.without(MegaHardfork::Satin); + assert_eq!(config.get(MegaHardfork::Satin), None); + + let from_iter = MegaHardforkConfig::from( + [(MegaHardfork::Satin, ForkCondition::Timestamp(1))].into_iter(), + ); + assert_eq!(from_iter.get(MegaHardfork::Satin), Some(&ForkCondition::Timestamp(1))); + } + + #[test] + fn test_with_all_activated_enables_all_mega_hardforks() { + let config = MegaHardforkConfig::default().with_all_activated(); + + // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list + // that declares the enum. A second hand-written list here would assert only that the + // forks someone remembered to name are activated. + for hardfork in MegaHardfork::VARIANTS { + assert_eq!( + config.mega_fork_activation(*hardfork), + ForkCondition::Timestamp(0), + "{hardfork:?}" + ); + } + } + + #[test] + fn test_fork_params_typed_access() { + let config = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(0)) + .with_params(params()); + + let retrieved = config.fork_params::().expect("params were attached"); + assert_eq!(retrieved, ¶ms()); + } + + #[test] + fn test_fork_params_none_when_not_configured() { + let config = + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); + + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_default_validate_accepts_any_value() { + #[derive(Debug)] + struct NullParams; + + impl HardforkParams for NullParams { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "NullParams"; + } + + assert!(NullParams.validate().is_ok()); + } + + #[test] + fn test_hardfork_params_error_display() { + let e = HardforkParamsError { message: "something went wrong".into() }; + assert_eq!(e.to_string(), "something went wrong"); + } + + #[test] + #[should_panic(expected = "Invalid params for fork")] + fn test_with_params_panics_on_validation_error() { + MegaHardforkConfig::default() + .with_all_activated() + .with_params(TestParams { sequencer: alloy_primitives::Address::ZERO }); + } + + /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered by + /// block number never contributes its spec. `validate_schedule` rejects such a schedule at + /// load rather than leaving the fork silently inactive. + #[test] + fn test_resolution_ignores_block_numbered_forks() { + let hf = MegaHardforkConfig::new().with(MegaHardfork::Satin, ForkCondition::Block(0)); + + assert!( + !hf.mega_fork_activation(MegaHardfork::Satin).active_at_timestamp(0), + "block-numbered forks are not timestamped" + ); + assert_eq!(hf.spec_id(0), None); + assert!(!hf.is_satin_active_at_timestamp(0)); + assert_eq!( + hf.validate_schedule(), + Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::Satin }) + ); + } + + /// A scheduled fork whose required params are missing fails at validation time instead of at + /// the first block of the fork. + #[test] + fn test_validate_schedule_requires_scheduled_fork_params() { + let unscheduled = MegaHardforkConfig::default(); + assert_eq!(unscheduled.require_params::(), Ok(())); + + let no_params = MegaHardforkConfig::default().with_all_activated(); + assert_eq!( + no_params.require_params::(), + Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "TestParams" }) + ); + assert_eq!( + no_params.require_params::().unwrap_err().to_string(), + "hardfork Satin is scheduled but its TestParams params are not configured" + ); + + let with_params = no_params.with_params(params()); + assert_eq!(with_params.require_params::(), Ok(())); + assert_eq!(with_params.validate_schedule(), Ok(())); + } + + #[test] + fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { + let config = + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(100)); + + assert_eq!(config.hardfork(99), None); + assert_eq!(config.spec_id(99), None); + assert!(!config.is_satin_active_at_timestamp(99)); + assert_eq!(config.hardfork(100), Some(MegaHardfork::Satin)); + assert_eq!(config.spec_id(100), Some(MegaSpecId::SATIN)); + assert!(config.is_satin_active_at_timestamp(100)); + assert_eq!(config.spec_id(u64::MAX), Some(MegaSpecId::SATIN)); + } } diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index da80c6b9a..8eed5724e 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,10 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 53 | 23 | 30 | 39 | 14 | 0 | +| the block executor | 36 | 23 | 13 | 29 | 7 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **747** | **624** | **123** | **426** | **293** | **28** | +| **Total** | **730** | **624** | **106** | **416** | **286** | **28** | ## Tests ported in place @@ -130,6 +130,16 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | | **Total** | | **45** | | +## Tests ported by the block executor + +These 17 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | +| `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | +| **Total** | | **17** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | @@ -218,9 +228,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | -| `src/block/chain.rs` | 5 | rewrite 4 (the block executor · Satin activation timestamps; fallback pin = Satin); keep 1 (the block executor) | | `src/block/eips.rs` | 1 | keep 1 (the block executor) | -| `src/block/hardfork.rs` | 12 | rewrite 3 (the block executor · single fork); keep 9 (the block executor) | | `src/block/helpers.rs` | 3 | keep 3 (the block executor) | | `src/block/limit.rs` | 5 | keep 5 (the block executor) | | `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | diff --git a/crates/mega-evm/tests/_pending/src/block/chain.rs b/crates/mega-evm/tests/_pending/src/block/chain.rs deleted file mode 100644 index ff0d74c55..000000000 --- a/crates/mega-evm/tests/_pending/src/block/chain.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/chain.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/chain.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::{MegaHardfork, MegaHardforks, MegaSpecId}; - - #[test] - fn test_mainnet_schedule_resolves_specs_by_timestamp() { - let hf = mainnet_hardforks(); - assert_eq!(hf.spec_id(1764851940), MegaSpecId::REX); - assert_eq!(hf.spec_id(1776659200), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780631999), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780632000), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1787626799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1787626800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } - - #[test] - fn test_testnet_schedule_resolves_specs_by_timestamp() { - let hf = testnet_hardforks(); - assert_eq!(hf.spec_id(1776400000), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780459199), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780459200), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1786330799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1786330800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } - - #[test] - fn test_schedule_dispatch_by_chain_id() { - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1780632000), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1780459200), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1787626800), MegaSpecId::REX6); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1786330800), MegaSpecId::REX6); - // Unknown chain: every fork up to the pinned rung, active at genesis. - assert_eq!(hardfork_schedule(1).spec_id(0), MegaSpecId::REX7); - } - - #[test] - fn test_unknown_chain_fallback_carries_sequencer_registry_config() { - // Rex5 block execution fails pre-block without a SequencerRegistryConfig, - // so the all-activated fallback must attach placeholder roles. - let hf = hardfork_schedule(999_999); - assert_eq!(hf.spec_id(0), MegaSpecId::REX7); - let params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryConfig"); - assert_eq!(params.rex5_initial_sequencer, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.rex5_initial_admin, MEGA_SYSTEM_ADDRESS); - // Rex6 is also active at genesis in the fallback, and the v2.0.0 registry - // deploy fails pre-block without a SequencerRegistryRex6Config — without - // this, every unknown-chain block aborts before the registry can deploy. - let rex6_params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryRex6Config"); - assert!(rex6_params.rex6_min_rotation_delay > 0); - } - - /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. - /// - /// Unknown chains run their rung from genesis, so it is their semantics from block zero with - /// no fork boundary. Introducing a spec must therefore leave them alone: registering a fork - /// above the pinned rung would rewrite what history they have already produced means, and - /// `mega-evme replay` resolves an unknown chain ID through this same schedule. - /// - /// A newly introduced spec leaves this test green — the pin holding still is the safe - /// direction, so nothing fails to force a decision. What the test pins is drift: the - /// fallback silently following `MegaSpecId::default` again (it fails here once the default - /// advances past the rung), and the rung advancing without this `RUNG` constant being edited - /// in the same change. - #[test] - fn test_unknown_chain_fallback_pins_its_rung() { - let hf = all_activated_hardforks(); - const RUNG: MegaSpecId = MegaSpecId::REX7; - - assert_eq!(hf.spec_id(0), RUNG, "the rung applies from genesis"); - assert_eq!(hf.spec_id(u64::MAX), RUNG, "and is terminal — no later fork is registered"); - - for fork in MegaHardfork::VARIANTS { - let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; - assert_eq!( - registered, - RUNG.is_enabled(fork.spec_id()), - "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" - ); - } - } -} diff --git a/crates/mega-evm/tests/_pending/src/block/hardfork.rs b/crates/mega-evm/tests/_pending/src/block/hardfork.rs deleted file mode 100644 index 5094ee39b..000000000 --- a/crates/mega-evm/tests/_pending/src/block/hardfork.rs +++ /dev/null @@ -1,233 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/hardfork.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/hardfork.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::SequencerRegistryConfig; - - #[test] - fn test_mega_hardfork_spec_ids_match_expected_specs() { - // Note: MiniRex1 and MiniRex2 map to alias rungs whose behavior reverts to earlier specs. - let cases = [ - (MegaHardfork::MiniRex, MegaSpecId::MINI_REX), - (MegaHardfork::MiniRex1, MegaSpecId::MINI_REX_1), - (MegaHardfork::MiniRex2, MegaSpecId::MINI_REX_2), - (MegaHardfork::Rex, MegaSpecId::REX), - (MegaHardfork::Rex1, MegaSpecId::REX1), - (MegaHardfork::Rex2, MegaSpecId::REX2), - (MegaHardfork::Rex3, MegaSpecId::REX3), - (MegaHardfork::Rex4, MegaSpecId::REX4), - (MegaHardfork::Rex5, MegaSpecId::REX5), - (MegaHardfork::Rex6, MegaSpecId::REX6), - (MegaHardfork::Rex7, MegaSpecId::REX7), - ]; - - for (hardfork, expected_spec) in cases { - assert_eq!(hardfork.spec_id(), expected_spec); - } - } - - #[test] - fn test_default_config_contains_upstream_forks_and_no_mega_forks() { - let config = MegaHardforkConfig::default(); - - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Frontier), - ForkCondition::Block(0) - ); - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Prague), - ForkCondition::Timestamp(0) - ); - assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); - assert_eq!(config.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_config_builder_helpers_override_and_remove_hardforks() { - let mut config = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(10)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(80)); - - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(10))); - assert_eq!(config.get(MegaHardfork::Rex4), Some(&ForkCondition::Timestamp(80))); - - config.insert(MegaHardfork::MiniRex, ForkCondition::Timestamp(20)); - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(20))); - - let config = config.without(MegaHardfork::MiniRex); - assert_eq!(config.get(MegaHardfork::MiniRex), None); - - let from_iter = MegaHardforkConfig::from( - [ - (MegaHardfork::MiniRex, ForkCondition::Timestamp(1)), - (MegaHardfork::Rex2, ForkCondition::Timestamp(2)), - ] - .into_iter(), - ); - assert_eq!(from_iter.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(1))); - assert_eq!(from_iter.get(MegaHardfork::Rex2), Some(&ForkCondition::Timestamp(2))); - } - - #[test] - fn test_with_all_activated_enables_all_mega_hardforks() { - let config = MegaHardforkConfig::default().with_all_activated(); - - // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list - // that declares the enum. A second hand-written list here would assert only that the - // forks someone remembered to name are activated — a new fork missing from both the - // builder and the list would fail neither. - for hardfork in MegaHardfork::VARIANTS { - assert_eq!( - config.mega_fork_activation(*hardfork), - ForkCondition::Timestamp(0), - "{hardfork:?}" - ); - } - } - - #[test] - fn test_fork_params_typed_access() { - let params = SequencerRegistryConfig { - rex5_initial_sequencer: alloy_primitives::address!( - "0x2222222222222222222222222222222222222222" - ), - rex5_initial_admin: alloy_primitives::address!( - "0x3333333333333333333333333333333333333333" - ), - }; - - let config = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(params.clone()); - - let retrieved = config - .fork_params::() - .expect("should have SequencerRegistryConfig"); - assert_eq!(retrieved, ¶ms); - } - - #[test] - fn test_fork_params_none_when_not_configured() { - let config = - MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); - - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_default_validate_accepts_any_value() { - #[derive(Debug)] - struct NullParams; - - impl HardforkParams for NullParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - } - - assert!(NullParams.validate().is_ok()); - } - - #[test] - fn test_hardfork_params_error_display() { - let e = HardforkParamsError { message: "something went wrong".into() }; - assert_eq!(e.to_string(), "something went wrong"); - } - - #[test] - #[should_panic(expected = "Invalid params for fork")] - fn test_with_params_panics_on_validation_error() { - #[derive(Debug)] - struct AlwaysErrParams; - - impl HardforkParams for AlwaysErrParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - - fn validate(&self) -> Result<(), HardforkParamsError> { - Err(HardforkParamsError { message: "intentional test error".into() }) - } - } - - MegaHardforkConfig::default().with_all_activated().with_params(AlwaysErrParams); - } - - /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered - /// by block number never contributes its own spec to it. `spec_id`/`hardfork` share this - /// limitation; every canonical schedule uses `Timestamp` or `Never`, and - /// `validate_schedule` rejects anything else. - #[test] - fn test_resolution_ignores_block_numbered_forks() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(0)); - - assert!( - !hf.mega_fork_activation(MegaHardfork::MiniRex).active_at_timestamp(0), - "block-numbered forks are not timestamped" - ); - // The resolved spec comes from Rex alone; it still covers MINI_REX by ordinal - // inclusion, so the projected predicate reports active even though the MiniRex event - // itself never fires. - assert_eq!(hf.spec_id(0), MegaSpecId::REX); - assert!(hf.spec_id(0).is_enabled(MegaSpecId::MINI_REX)); - assert!(hf.is_mini_rex_active_at_timestamp(0)); - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::MiniRex }) - ); - } - - /// A scheduled fork whose required params are missing fails at validation time instead of at - /// the first block of the fork. - #[test] - fn test_validate_schedule_requires_scheduled_fork_params() { - let rex5_no_params = - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5); - assert_eq!( - rex5_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig" - }) - ); - - let rex6_no_params = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, - }); - assert_eq!( - rex6_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config" - }) - ); - } - - #[test] - fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { - let config = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(200)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(300)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(400)) - .with(MegaHardfork::Rex7, ForkCondition::Timestamp(500)); - - assert_eq!(config.hardfork(99), None); - assert_eq!(config.hardfork(100), Some(MegaHardfork::MiniRex)); - assert_eq!(config.hardfork(200), Some(MegaHardfork::Rex4)); - assert_eq!(config.hardfork(300), Some(MegaHardfork::Rex5)); - assert_eq!(config.hardfork(400), Some(MegaHardfork::Rex6)); - assert_eq!(config.hardfork(500), Some(MegaHardfork::Rex7)); - assert_eq!(config.spec_id(99), MegaSpecId::EQUIVALENCE); - assert_eq!(config.spec_id(100), MegaSpecId::MINI_REX); - assert_eq!(config.spec_id(200), MegaSpecId::REX4); - assert_eq!(config.spec_id(300), MegaSpecId::REX5); - assert_eq!(config.spec_id(400), MegaSpecId::REX6); - assert_eq!(config.spec_id(500), MegaSpecId::REX7); - } -} From b756f8bf5cfe9f9808d9855aeae5378ed571f4cc Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:03:19 +0800 Subject: [PATCH 090/201] feat(evm): read the block hashes execution accessed `BLOCKHASH` reads bypass the journal, so a witness built from a transaction's state alone misses them. `BlockHashes` reads the record revm's `State` already keeps, and `MegaEvm` exposes it, so block execution and the node's stateless witness share one source. Clearing the record attributes the next reads to one transaction; it is a cache, so clearing changes no execution result. Ports the two parked rows of the state wrapper. --- crates/mega-evm/src/evm/mod.rs | 42 ++++++++++- crates/mega-evm/src/evm/state.rs | 73 +++++++++++++++++++ crates/mega-evm/tests/_pending/README.md | 14 ++-- .../mega-evm/tests/_pending/src/evm/state.rs | 43 ----------- 4 files changed, 121 insertions(+), 51 deletions(-) create mode 100644 crates/mega-evm/src/evm/state.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/state.rs diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index d545532ef..6fc1798ac 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -14,6 +14,7 @@ mod inspector; mod instructions; mod result; mod spec; +mod state; pub use context::*; pub use execution::*; @@ -23,6 +24,11 @@ pub use host::*; pub use inspector::*; pub use result::*; pub use spec::*; +pub use state::*; + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::collections::BTreeMap; use alloy_evm::EvmEnv; use alloy_op_evm::map_op_err; @@ -40,7 +46,7 @@ use revm::{ NoOpInspector, }, interpreter::interpreter::EthInterpreter, - primitives::{Address, Bytes}, + primitives::{Address, Bytes, B256}, state::EvmState, Database, DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, }; @@ -157,6 +163,25 @@ impl MegaEvm { } } +impl MegaEvm +where + DB: Database + BlockHashes, + ExtEnvs: ExternalEnvTypes, +{ + /// The block hashes execution has read on this database so far. + /// + /// `BLOCKHASH` reads bypass the journal, so this is where a stateless witness learns of them. + pub fn get_accessed_block_hashes(&self) -> BTreeMap { + self.ctx().db().get_accessed_block_hashes() + } + + /// Forgets the block hashes read so far, so the next reads are attributable to one + /// transaction. The record is a cache, so clearing it changes no execution result. + pub fn clear_accessed_block_hashes(&mut self) { + self.ctx_mut().db_mut().clear_accessed_block_hashes(); + } +} + impl MegaEvm where DB: Database, @@ -513,6 +538,21 @@ mod tests { assert!(matches!(invalid, Some(InvalidTransaction::LackOfFundForMaxFee { .. })), "{err:?}"); } + /// The EVM reads the block hashes the wrapped `State` served, which is where a stateless + /// witness learns of a `BLOCKHASH` read. + #[test] + fn test_mega_evm_exposes_state_wrapper_block_hashes() { + let mut db = MemoryDatabase::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(7, B256::from([7_u8; 32])); + + let mut evm = MegaEvm::new(context(&mut state)); + assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); + + evm.clear_accessed_block_hashes(); + assert!(evm.get_accessed_block_hashes().is_empty()); + } + #[test] fn test_finish_returns_the_database() { let mut state = State::builder().with_database(funded_db()).build(); diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs new file mode 100644 index 000000000..aff17b70c --- /dev/null +++ b/crates/mega-evm/src/evm/state.rs @@ -0,0 +1,73 @@ +//! The block hashes execution read, which a node's stateless witness needs. +//! +//! `BLOCKHASH` reads the chain's history through the database, not through the journal, so a +//! witness built from a transaction's state alone would miss them. revm's [`State`] already +//! caches every hash it served in `block_hashes`; [`BlockHashes`] is the read of that cache the +//! block executor and the node share. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::collections::BTreeMap; + +use alloy_primitives::B256; +use auto_impl::auto_impl; +use revm::{ + database::{states::block_hash_cache::BlockHashCache, State}, + Database, +}; + +/// The block hashes execution has read so far. +/// +/// The record accumulates across every transaction executed on the same database, so a caller +/// that attributes reads to one transaction clears it first +/// ([`clear_accessed_block_hashes`](Self::clear_accessed_block_hashes)). It is a cache: a +/// cleared hash is fetched again on the next read, so clearing it changes no execution result. +#[auto_impl(&mut, Box)] +pub trait BlockHashes { + /// The block hashes read so far, by block number. + fn get_accessed_block_hashes(&self) -> BTreeMap; + + /// Forgets the hashes read so far. + fn clear_accessed_block_hashes(&mut self); +} + +impl BlockHashes for State { + fn get_accessed_block_hashes(&self) -> BTreeMap { + self.block_hashes.iter().collect() + } + + fn clear_accessed_block_hashes(&mut self) { + self.block_hashes = BlockHashCache::new(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use revm::database::InMemoryDB; + + #[test] + fn test_state_exposes_accessed_block_hashes() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(1, B256::ZERO); + state.block_hashes.insert(2, B256::from([2_u8; 32])); + + let hashes = state.get_accessed_block_hashes(); + assert_eq!(hashes.len(), 2); + assert_eq!(hashes.get(&1), Some(&B256::ZERO)); + assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); + } + + /// Clearing empties the record and leaves the database able to serve the hash again. + #[test] + fn test_clearing_forgets_the_hashes_read_so_far() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(7, B256::from([7_u8; 32])); + + state.clear_accessed_block_hashes(); + + assert!(state.get_accessed_block_hashes().is_empty()); + } +} diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 8eed5724e..4033b4e70 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,10 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 36 | 23 | 13 | 29 | 7 | 0 | +| the block executor | 34 | 23 | 11 | 27 | 7 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **730** | **624** | **106** | **416** | **286** | **28** | +| **Total** | **728** | **624** | **104** | **414** | **286** | **28** | ## Tests ported in place @@ -132,13 +132,15 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by the block executor -These 17 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 19 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | | `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | -| **Total** | | **17** | | +| `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | +| `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | +| **Total** | | **19** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -146,7 +148,6 @@ These 17 rows run in a real test target now, adapted to the Satin API, so the co |---|---|---|---| | `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | | `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | the Satin gas table | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | -| `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | the block executor | reads the accessed-block-hash record, which returns with the block executor | ## Files @@ -235,9 +236,8 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | -| `src/evm/mod.rs` | 4 | keep 3 (the pre-block system calls); keep 1 (the block executor) | +| `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | | `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | -| `src/evm/state.rs` | 1 | keep 1 (the block executor) | | `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | | `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | diff --git a/crates/mega-evm/tests/_pending/src/evm/state.rs b/crates/mega-evm/tests/_pending/src/evm/state.rs deleted file mode 100644 index 54b6172b8..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/state.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/state.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/state.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Address, B256, U256}; - use revm::{ - database::{InMemoryDB, State}, - state::{AccountInfo, EvmStorageSlot}, - }; - - const TEST_ADDRESS: Address = address!("1000000000000000000000000000000000000001"); - - fn account_with_status(status: AccountStatus) -> Account { - Account { - info: AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: B256::ZERO, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status, - } - } - - #[test] - fn test_state_exposes_accessed_block_hashes() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(1, B256::ZERO); - state.block_hashes.insert(2, B256::from([2_u8; 32])); - - let hashes = state.get_accessed_block_hashes(); - assert_eq!(hashes.len(), 2); - assert_eq!(hashes.get(&1), Some(&B256::ZERO)); - assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); - } - -} From 3612a25ac5084c2dd14b472c414a807bdbc576db Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:03:24 +0800 Subject: [PATCH 091/201] feat(evm): install the Satin gas schedule, its switches and its size limits MegaContext::with_cfg now writes the Satin schedule, the EIP-8037 and EIP-2780 switches, the 200M execution cap, the EIP-7708 and system-call-margin switches that stay off, and MegaETH's 512 KiB contract / 1 MiB initcode limits, whatever the caller passed. The instruction table activates the Amsterdam opcodes the base spec gates off, before the metering wrappers go in. The tests that were written against the Osaka schedule move with it: the op-revm baseline pins the Satin table on both engines, and the cases whose gas limits no longer cover the state gas a new slot or account draws are raised. --- crates/mega-evm/src/constants.rs | 19 +- crates/mega-evm/src/evm/context.rs | 194 ++++++++++++------ crates/mega-evm/src/evm/instructions.rs | 27 ++- crates/mega-evm/src/evm/mod.rs | 14 +- crates/mega-evm/src/evm/schedule.rs | 8 +- crates/mega-evm/src/test_utils/scenario.rs | 3 +- crates/mega-evm/tests/satin/equivalence.rs | 23 ++- crates/mega-evm/tests/satin/outcome.rs | 6 +- crates/mega-evm/tests/satin/strategic_stop.rs | 33 ++- crates/mega-evm/tests/satin/write_records.rs | 23 ++- 10 files changed, 241 insertions(+), 109 deletions(-) diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index f959e1633..7ef1c772d 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -6,14 +6,18 @@ //! //! | Constant | Value | Meaning | Read by | //! |---|---:|---|---| -//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas table (not yet) | -//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | the Satin gas table (not yet) | -//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | the Satin gas table (not yet) | +//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas schedule | +//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | the Satin gas schedule | +//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | the Satin gas schedule | //! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas (not yet) | //! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | the spec configuration | +//! | [`MAX_CONTRACT_SIZE`] | 524,288 | the most bytes a deployed contract may hold | the spec configuration | +//! | [`MAX_INITCODE_SIZE`] | 1,048,576 | the most bytes an initcode may hold | the spec configuration | //! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the data-size limit (not yet) | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the data-size limit (not yet) | //! +//! The Satin gas schedule reads the state-gas numbers through [`SatinPrices`](crate::SatinPrices), +//! so a measurement build can run other byte prices without touching this table. //! The storage call stipend and the per-transaction and per-block state-gas limits are further //! placeholders; history gas and the state-gas limits add them when they land. @@ -37,6 +41,13 @@ pub const COST_PER_HISTORY_BYTE: u64 = 88; /// the EIP-8037 state-gas reservoir. Provisional. pub const TX_GAS_LIMIT_CAP: u64 = 200_000_000; +/// The most bytes a deployed contract may hold, replacing the EIP-170 limit. Provisional. +pub const MAX_CONTRACT_SIZE: usize = 512 * 1024; + +/// The most bytes an initcode may hold: twice [`MAX_CONTRACT_SIZE`], the ratio EIP-3860 sets +/// between the two. Provisional. +pub const MAX_INITCODE_SIZE: usize = 2 * MAX_CONTRACT_SIZE; + /// The most data one transaction may produce, 12.5 MiB as in Rex6. Provisional. pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; @@ -55,6 +66,8 @@ mod tests { assert_eq!(ACCOUNT_STATE_GAS, 183_600); assert_eq!(COST_PER_HISTORY_BYTE, 88); assert_eq!(TX_GAS_LIMIT_CAP, 200_000_000); + assert_eq!(MAX_CONTRACT_SIZE, 524_288); + assert_eq!(MAX_INITCODE_SIZE, 1_048_576); assert_eq!(TX_DATA_LIMIT, 13_107_200); assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 309fccdca..f545731aa 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -4,13 +4,12 @@ use delegate::delegate; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, - context_interface::cfg::GasParams, Database, Journal, }; use crate::{ - constants, AdditionalLimit, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, - ExternalEnvs, MegaSpecId, MegaTransaction, + constants, evm::schedule::satin_gas_params, AdditionalLimit, EmptyExternalEnv, + EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -58,10 +57,10 @@ impl MegaContext { /// Replaces the configuration. /// - /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas table, the - /// EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and the system-call - /// state-gas margin. Every other field (chain id, limits, disabled checks) is taken from - /// `cfg`. + /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas schedule, + /// the EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch, the + /// system-call state-gas margin and the two code-size limits. Every other field (chain id, + /// disabled checks, blob schedule) is taken from `cfg`. pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { let cfg = spec_cfg(cfg); self.inner = self.inner.with_cfg(op_cfg(&cfg)); @@ -142,17 +141,23 @@ impl MegaContext { /// Sets the configuration fields the spec fixes. /// -/// Satin runs on the Osaka gas table of its Karst base, with EIP-8037 state gas and the EIP-2780 -/// intrinsic cost switched on and gas above the execution cap going to the state-gas reservoir. -/// The EIP-7708 transfer logs and the system-call reservoir margin stay off until the Satin gas -/// table and the system-call reservoir split switch them on. +/// Satin runs the Satin gas schedule (see [`satin_gas_params`]) on its Karst base, with EIP-8037 +/// state gas and the EIP-2780 intrinsic cost switched on and gas above the execution cap going to +/// the state-gas reservoir. It raises the code-size limits to `MegaETH`'s own. +/// +/// Two switches are set off rather than left alone, because the base spec would turn them on and +/// Satin does not take them: EIP-7708 mints a transfer log for every value movement, which +/// `MegaETH` meters through its own write records instead, and the system-call reservoir margin +/// belongs to the system-call reservoir split. fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { - cfg.gas_params = GasParams::new_spec(cfg.spec.into_eth_spec()); + cfg.gas_params = satin_gas_params(); cfg.enable_amsterdam_eip8037 = true; cfg.enable_amsterdam_eip2780 = true; cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); cfg.enable_amsterdam_eip7708 = false; cfg.system_call_state_gas_margin_in_reservoir = false; + cfg.limit_contract_code_size = Some(constants::MAX_CONTRACT_SIZE); + cfg.limit_contract_initcode_size = Some(constants::MAX_INITCODE_SIZE); cfg } @@ -213,84 +218,143 @@ mod tests { use crate::{EthSpecId, SaltEnv, TestExternalEnvs}; use alloy_primitives::U256; use core::convert::Infallible; - use revm::database::EmptyDB; + use revm::{context_interface::cfg::GasParams, database::EmptyDB}; - /// Asserts both configuration views carry the Satin switches. - fn assert_satin_switches(ctx: &MegaContext) { + /// Asserts both configuration views carry everything the spec fixes. + fn assert_satin_cfg(ctx: &MegaContext) { let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); assert_eq!(mega.spec, MegaSpecId::SATIN); assert_eq!(op.spec, OpSpecId::KARST); - for (eip8037, eip2780, cap, eip7708, margin) in [ - ( - mega.enable_amsterdam_eip8037, - mega.enable_amsterdam_eip2780, - mega.tx_gas_limit_cap, - mega.enable_amsterdam_eip7708, - mega.system_call_state_gas_margin_in_reservoir, - ), - ( - op.enable_amsterdam_eip8037, - op.enable_amsterdam_eip2780, - op.tx_gas_limit_cap, - op.enable_amsterdam_eip7708, - op.system_call_state_gas_margin_in_reservoir, - ), - ] { - assert!(eip8037, "EIP-8037 must be on"); - assert!(eip2780, "EIP-2780 must be on"); - assert_eq!(cap, Some(200_000_000), "execution cap"); - assert!(!eip7708, "EIP-7708 stays off until the Satin gas table"); - assert!( - !margin, - "the system-call reservoir margin stays off until the reservoir split" - ); + for cfg in [Fixed::of(mega), Fixed::of(op)] { + assert!(cfg.eip8037, "EIP-8037 must be on"); + assert!(cfg.eip2780, "EIP-2780 must be on"); + assert_eq!(cfg.cap, Some(constants::TX_GAS_LIMIT_CAP), "execution cap"); + assert!(!cfg.eip7708, "EIP-7708 stays off"); + assert!(!cfg.margin, "the system-call reservoir margin stays off"); + assert_eq!(cfg.code_size, Some(constants::MAX_CONTRACT_SIZE), "contract size"); + assert_eq!(cfg.initcode_size, Some(constants::MAX_INITCODE_SIZE), "initcode size"); + assert_eq!(cfg.gas_params.table(), satin_gas_params().table(), "gas schedule"); + } + } + + /// The configuration fields the spec fixes, read out of either view. + struct Fixed<'a> { + eip8037: bool, + eip2780: bool, + cap: Option, + eip7708: bool, + margin: bool, + code_size: Option, + initcode_size: Option, + gas_params: &'a GasParams, + } + + impl<'a> Fixed<'a> { + fn of(cfg: &'a CfgEnv) -> Self { + Self { + eip8037: cfg.enable_amsterdam_eip8037, + eip2780: cfg.enable_amsterdam_eip2780, + cap: cfg.tx_gas_limit_cap, + eip7708: cfg.enable_amsterdam_eip7708, + margin: cfg.system_call_state_gas_margin_in_reservoir, + code_size: cfg.limit_contract_code_size, + initcode_size: cfg.limit_contract_initcode_size, + gas_params: &cfg.gas_params, + } } - let osaka = GasParams::new_spec(EthSpecId::OSAKA); - assert_eq!(mega.gas_params.table(), osaka.table()); - assert_eq!(op.gas_params.table(), osaka.table()); + } + + /// A context built from a configuration `mutate` has set the other way. + fn context_with(mutate: impl FnOnce(&mut CfgEnv)) -> MegaContext { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + mutate(&mut cfg); + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg) } #[test] - fn test_new_context_carries_the_satin_switches() { + fn test_new_context_carries_the_satin_configuration() { let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); assert_eq!(ctx.spec(), MegaSpecId::SATIN); - assert_satin_switches(&ctx); + assert_satin_cfg(&ctx); } /// A caller's configuration cannot switch off what the spec fixes; every other field is /// taken from it. #[test] - fn test_with_cfg_keeps_the_spec_switches() { - let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); - cfg.chain_id = 4326; - cfg.enable_amsterdam_eip8037 = false; - cfg.enable_amsterdam_eip2780 = false; - cfg.tx_gas_limit_cap = Some(1 << 24); - cfg.enable_amsterdam_eip7708 = true; - cfg.system_call_state_gas_margin_in_reservoir = true; - cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); - - let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); - - assert_satin_switches(&ctx); + fn test_with_cfg_keeps_the_whole_spec_configuration() { + let ctx = context_with(|cfg| { + cfg.chain_id = 4326; + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.tx_gas_limit_cap = Some(1 << 24); + cfg.enable_amsterdam_eip7708 = true; + cfg.system_call_state_gas_margin_in_reservoir = true; + cfg.limit_contract_code_size = Some(24 * 1024); + cfg.limit_contract_initcode_size = Some(48 * 1024); + cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); + }); + + assert_satin_cfg(&ctx); assert_eq!(ctx.mega_cfg().chain_id, 4326); assert_eq!(ctx.cfg().chain_id, 4326); } + /// Each switch on its own: setting only that field the other way is overwritten, and the + /// rest of the configuration is untouched by the attempt. + #[test] + fn test_eip8037_stays_on() { + assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip8037 = false)); + } + + #[test] + fn test_eip2780_stays_on() { + assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip2780 = false)); + } + + #[test] + fn test_eip7708_stays_off() { + assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip7708 = true)); + } + + #[test] + fn test_the_system_call_reservoir_margin_stays_off() { + assert_satin_cfg(&context_with(|cfg| cfg.system_call_state_gas_margin_in_reservoir = true)); + } + + #[test] + fn test_the_execution_cap_is_the_spec_s() { + assert_satin_cfg(&context_with(|cfg| cfg.tx_gas_limit_cap = None)); + assert_satin_cfg(&context_with(|cfg| cfg.tx_gas_limit_cap = Some(u64::MAX))); + } + + #[test] + fn test_the_code_size_limits_are_the_spec_s() { + assert_satin_cfg(&context_with(|cfg| cfg.limit_contract_code_size = Some(24 * 1024))); + assert_satin_cfg(&context_with(|cfg| cfg.limit_contract_initcode_size = None)); + } + + /// The schedule is the Satin one whatever the caller passed, and it is the same table + /// object every time: it is built once, not per configuration. + #[test] + fn test_the_gas_schedule_is_the_satin_one() { + for spec in [EthSpecId::OSAKA, EthSpecId::AMSTERDAM, EthSpecId::PRAGUE] { + let ctx = context_with(|cfg| cfg.gas_params = GasParams::new_spec(spec)); + assert_satin_cfg(&ctx); + assert_ne!(ctx.mega_cfg().gas_params.table(), GasParams::new_spec(spec).table()); + } + } + /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. #[test] fn test_with_cfg_spec_consistency() { - let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); - cfg.chain_id = 6343; - cfg.limit_contract_code_size = Some(512 * 1024); - cfg.disable_nonce_check = true; - - let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); + let ctx = context_with(|cfg| { + cfg.chain_id = 6343; + cfg.disable_nonce_check = true; + }); let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); assert_eq!(op.spec, mega.spec.into_op_spec()); assert_eq!(op.chain_id, 6343); - assert_eq!(op.limit_contract_code_size, Some(512 * 1024)); assert!(op.disable_nonce_check); assert_eq!( mega.clone().with_spec_and_gas_params(op.spec, mega.gas_params.clone()), @@ -317,6 +381,6 @@ mod tests { assert_eq!(ctx.spec(), MegaSpecId::SATIN); assert_eq!(ctx.external_envs().salt_env.get_bucket_capacity(7).unwrap(), 1_024); - assert_satin_switches(&ctx); + assert_satin_cfg(&ctx); } } diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index acb82a35c..e3d5edc1e 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -14,12 +14,21 @@ //! //! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is //! unchanged. +//! +//! The table also carries the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), which +//! the base spec gates off: Satin takes the Amsterdam schedule, so it takes the opcodes with it. +//! They are installed before the wrappers go in, because installing them after would replace a +//! wrapped entry with an unwrapped one. `CLZ` needs no installation — its own gate is Osaka, so +//! the base spec already has it. use revm::{ bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, handler::instructions::EthInstructions, interpreter::{ - instructions::host, interpreter::EthInterpreter, interpreter_types::LoopControl, + enable_amsterdam_opcodes, instruction_table, + instructions::{gas_table_spec, host}, + interpreter::EthInterpreter, + interpreter_types::LoopControl, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, InterpreterAction, }, @@ -37,12 +46,14 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth /// An instruction of the Satin engine. type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; -/// The Satin instruction table: revm's for the base spec, with `SSTORE`, `LOG0`..`LOG4` and -/// `SELFDESTRUCT` wrapped. +/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated +/// and `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` wrapped. pub(crate) fn mega_instructions( spec: SpecId, ) -> MegaInstructions { - let mut instructions = EthInstructions::new_mainnet_with_spec(spec); + let mut table = instruction_table(); + enable_amsterdam_opcodes(&mut table); + let mut instructions = EthInstructions::new(table, gas_table_spec(spec), spec); let wrappers: [(u8, InstructionFn); 7] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), @@ -134,13 +145,19 @@ fn selfdestruct( mod tests { use super::*; use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use revm::interpreter::instructions::gas_table_spec; + use revm::bytecode::opcode::{CLZ, DUPN, EXCHANGE, SLOTNUM, SWAPN}; /// The wrappers keep the static gas revm charges for their opcodes: the whole table is revm's. + /// + /// Activating the Amsterdam opcodes does not touch it either — their static gas is the same + /// on every spec, which is why the activation is an instruction-table change alone. #[test] fn test_wrappers_keep_the_static_gas_table() { let mega = mega_instructions::(SpecId::OSAKA); assert_eq!(mega.gas_table(), &gas_table_spec(SpecId::OSAKA)); assert_eq!(mega.spec, SpecId::OSAKA); + for (opcode, gas) in [(DUPN, 3), (SWAPN, 3), (EXCHANGE, 3), (SLOTNUM, 2), (CLZ, 5)] { + assert_eq!(mega.gas_table()[opcode as usize], gas, "opcode {opcode:#04x}"); + } } } diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index da7f5c387..d398fa62f 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -402,10 +402,12 @@ mod tests { MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) } + /// A call to `CALLEE`, with room for the state gas a value transfer to it draws: `CALLEE` + /// holds nothing, so a transfer creates it and pays the new account's state gas. fn tx(value: U256) -> MegaTransaction { OpTx(op_transaction(TxEnv { caller: CALLER, - gas_limit: 100_000, + gas_limit: 300_000, kind: TxKind::Call(CALLEE), value, ..Default::default() @@ -436,12 +438,12 @@ mod tests { fn test_alloy_evm_interface_methods_execute_transactions() { let mut db = funded_db(); let mut evm = MegaEvm::new( - context(&mut db).with_block(BlockEnv { gas_limit: 222_222, ..Default::default() }), + context(&mut db).with_block(BlockEnv { gas_limit: 2_222_222, ..Default::default() }), ); assert_eq!(evm.chain_id(), evm.ctx().cfg().chain_id); assert_eq!(evm.cfg_env().spec, MegaSpecId::SATIN); - assert_eq!(evm.block().gas_limit, 222_222); + assert_eq!(evm.block().gas_limit, 2_222_222); evm.set_inspector_enabled(true); assert!(evm.is_inspecting()); @@ -456,15 +458,15 @@ mod tests { let (_db, evm_env) = evm.finish(); assert_eq!(evm_env.cfg_env.spec, MegaSpecId::SATIN); assert_eq!(evm_env.cfg_env.tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); - assert_eq!(evm_env.block_env.gas_limit, 222_222); + assert_eq!(evm_env.block_env.gas_limit, 2_222_222); } #[test] fn test_revm_execute_one_finalize_commit_works() { let mut db = funded_db(); let mut evm = MegaEvm::new(context(&mut db)); - ExecuteEvm::set_block(&mut evm, BlockEnv { gas_limit: 222_222, ..Default::default() }); - assert_eq!(evm.block().gas_limit, 222_222); + ExecuteEvm::set_block(&mut evm, BlockEnv { gas_limit: 2_222_222, ..Default::default() }); + assert_eq!(evm.block().gas_limit, 2_222_222); let result = ExecuteEvm::transact_one(&mut evm, tx(U256::from(7))).unwrap(); assert!(result.is_success()); diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 6022d0d1d..08db52a57 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -19,7 +19,7 @@ use revm::{ context_interface::cfg::{GasId, GasParams}, - primitives::{eip8037, hardfork::SpecId}, + primitives::{eip8037, hardfork::SpecId, OnceLock}, }; use crate::evm::prices::{active_satin_prices, SatinPrices}; @@ -75,8 +75,12 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ /// /// See the module documentation for what it changes; [`satin_gas_params_at`] is the same schedule /// with the byte prices taken as given rather than read from the process. +/// +/// Built once and handed out as a shared clone, the way revm hands out its own spec schedules: +/// the prices are fixed for the process, so every configuration gets the same table. pub fn satin_gas_params() -> GasParams { - satin_gas_params_at(active_satin_prices()) + static TABLE: OnceLock = OnceLock::new(); + TABLE.get_or_init(|| satin_gas_params_at(active_satin_prices())).clone() } /// The Satin gas schedule at `prices`. diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 0739b5c01..0aeb64f67 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -457,7 +457,8 @@ mod tests { /// current nonce. #[test] fn test_run_commits_each_transaction_before_the_next() { - let scenario = scenario(vec![call(Some(100_000)), call(Some(100_000))]); + // Room for the state gas the first transaction's new slot draws. + let scenario = scenario(vec![call(Some(200_000)), call(Some(200_000))]); let (outcomes, mut db) = scenario.run(scenario.database()); assert_eq!(outcomes.len(), 2); diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 8817fca82..688c5ad21 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -8,7 +8,8 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, TxKind, U256}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, + constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + satin_gas_params, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, }; @@ -18,9 +19,7 @@ use revm::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, - context_interface::cfg::GasParams, inspector::NoOpInspector, - primitives::hardfork::SpecId, state::EvmState, ExecuteEvm, Journal, }; @@ -97,15 +96,17 @@ fn assert_same(mega: &Outcome, op: &Outcome) { assert_eq!(mega.state, op.state, "state"); } -/// Both engines run on the Satin configuration: Karst on the Osaka gas table, EIP-8037 and -/// EIP-2780 switched on, the 200M execution cap, EIP-7708 and the system-call reservoir margin -/// off. +/// Both engines run on the Satin configuration: Karst on the Satin gas schedule, EIP-8037 and +/// EIP-2780 switched on, the 200M execution cap, `MegaETH`'s code-size limits, EIP-7708 and the +/// system-call reservoir margin off. fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); - assert_eq!(cfg.gas_params.table(), GasParams::new_spec(SpecId::OSAKA).table()); + assert_eq!(cfg.gas_params.table(), satin_gas_params().table()); assert!(cfg.enable_amsterdam_eip8037); assert!(cfg.enable_amsterdam_eip2780); - assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); + assert_eq!(cfg.tx_gas_limit_cap, Some(TX_GAS_LIMIT_CAP)); + assert_eq!(cfg.limit_contract_code_size, Some(MAX_CONTRACT_SIZE)); + assert_eq!(cfg.limit_contract_initcode_size, Some(MAX_INITCODE_SIZE)); assert!(!cfg.enable_amsterdam_eip7708); assert!(!cfg.system_call_state_gas_margin_in_reservoir); } @@ -162,9 +163,9 @@ fn test_sstore_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); assert_eq!(mega.state[&CALLEE].storage[&U256::ZERO].present_value, U256::from(42)); - // The Osaka gas table has no state-gas prices, so the new slot draws no state gas even with - // EIP-8037 on. The Satin gas table prices it; this assertion changes with it. - assert_eq!(mega.result.gas().state_gas_spent_final(), 0); + // The new slot draws the Satin schedule's state gas, which op-revm on the same schedule + // draws too: the schedule is configuration, not engine behavior. + assert_eq!(mega.result.gas().state_gas_spent_final(), SLOT_STATE_GAS); assert_same(&mega, &op); } diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index e6a59ecd6..feefe0da6 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -3,7 +3,7 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, + constants::{SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, @@ -43,7 +43,9 @@ fn test_outcome_reports_the_ledgers() { let result_gas = outcome.result.gas(); assert_eq!(gas.regular + gas.state + gas.history, result_gas.total_gas_spent()); assert_eq!(gas.gas_used, result_gas.tx_gas_used()); - assert_eq!(gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP); + // Both slots are new, so both draw state gas, and the reservoir is what pays it. + assert_eq!(gas.state, 2 * SLOT_STATE_GAS); + assert_eq!(gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * SLOT_STATE_GAS); assert_eq!(gas.history, 0, "nothing prices history bytes yet"); assert_eq!(outcome.usage, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); assert_eq!(outcome.limit_exceeded, None); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index f6fd52460..2e18b2daa 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -10,7 +10,7 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, + constants::{ACCOUNT_STATE_GAS, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransaction, @@ -32,7 +32,9 @@ const A: Address = address!("00000000000000000000000000000000000000A0"); const B: Address = address!("00000000000000000000000000000000000000B0"); const C: Address = address!("00000000000000000000000000000000000000C0"); const D: Address = address!("00000000000000000000000000000000000000D0"); -const GAS_LIMIT: u64 = 1_000_000; +/// Room for the state gas the chain's nine new slots draw, all of it out of regular gas: the +/// limit is below the execution cap, so the transaction has no reservoir. +const GAS_LIMIT: u64 = 10_000_000; /// Writes slot 1, calls `next` with all its gas, then writes slot 2 and emits a log: the part /// after the call is what a resumed caller would run. @@ -301,7 +303,8 @@ fn test_child_out_of_gas_under_a_cap_does_not_latch() { /// A cap crossed by the writes the first frame's start makes (a value transfer's recipient) /// reverts the transaction before the frame runs: the recipient's code never runs, its balance -/// is untouched, and the transaction spends what an empty call does. +/// is untouched, and the transaction spends the transfer's intrinsic gas alone — the recipient +/// is never created, so its state gas is never drawn. #[test] fn test_cap_crossed_before_the_first_frame_reverts_without_running() { let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); @@ -313,9 +316,14 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO, "nothing kept"); - let (empty_call, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); - assert!(empty_call.result.is_success()); - assert_eq!(result.result.gas().tx_gas_used(), empty_call.result.gas().tx_gas_used()); + let (transfer, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); + assert!(transfer.result.is_success()); + assert_eq!(result.result.gas().tx_gas_used(), 21_000, "the transfer's intrinsic gas"); + assert_eq!( + transfer.result.gas().tx_gas_used(), + result.result.gas().tx_gas_used() + ACCOUNT_STATE_GAS, + "the transfer that goes through also creates the recipient" + ); } /// A frame budget reverts the frame that crosses it and nothing else: the caller resumes and the @@ -505,10 +513,19 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { let gas_limit = 1_000_000_000; let reservoir = gas_limit - TX_GAS_LIMIT_CAP; let charger = || Charger { state_gas: 50_000, ..Default::default() }; + // The chain's own new slots draw state gas from the same reservoir, so the charger's 50,000 + // is measured against a run that charges nothing extra. + let plain = + execute_with(chain(), EvmTxRuntimeLimits::no_limits(), Charger::default(), gas_limit); let kept = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), charger(), gas_limit); assert!(kept.result.is_success()); - assert_eq!(kept.gas.reservoir_remaining, reservoir - 50_000, "the kept charge"); - assert_eq!(kept.gas.state, 50_000); + assert_eq!( + kept.gas.reservoir_remaining, + plain.gas.reservoir_remaining - 50_000, + "the kept charge" + ); + assert_eq!(kept.gas.state, plain.gas.state + 50_000); + assert!(plain.gas.state > 0, "the chain's slots are state gas of their own"); let stopped = execute_with(chain(), cap(180), charger(), gas_limit); assert_stopped(&stopped.result, LimitKind::DataSize, 180); diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index d0faaaff5..0367cedb4 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -28,7 +28,9 @@ const CALLER: Address = address!("0000000000000000000000000000000000100000"); const CALLEE: Address = address!("0000000000000000000000000000000000100001"); const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); -const GAS_LIMIT: u64 = 10_000_000; +/// Room for the state gas of several new accounts, including in a frame that resumes after a +/// child burned the 63/64 it was forwarded. +const GAS_LIMIT: u64 = 50_000_000; const fn records(n: u64) -> LimitUsage { LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } @@ -653,12 +655,21 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { }; let run_at = |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)).unwrap(); - let mut gas_limit = 40_000; - while !run_at(gas_limit).result.is_success() { - gas_limit += 1; - assert!(gas_limit < 200_000, "the transaction never succeeds"); + // Gas is monotone here: every limit above the smallest one that succeeds succeeds too. Search + // for that smallest limit rather than walking up to it, which the delegation's state gas puts + // several hundred thousand gas away. + let (mut fails, mut succeeds) = (40_000u64, 1_000_000u64); + assert!(!run_at(fails).result.is_success(), "the low bound must fail"); + assert!(run_at(succeeds).result.is_success(), "the high bound must succeed"); + while succeeds - fails > 1 { + let middle = fails + (succeeds - fails) / 2; + if run_at(middle).result.is_success() { + succeeds = middle; + } else { + fails = middle; + } } - let outcome = run_at(gas_limit - 1); + let outcome = run_at(succeeds - 1); assert!(outcome.result.is_halt(), "{:?}", outcome.result); assert_eq!(outcome.usage, LimitUsage::ZERO); assert_eq!(outcome.limit_exceeded, None); From 459748383d4e72641913c360f2f2a7632cc156eb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:06:09 +0800 Subject: [PATCH 092/201] feat(block): hold a block to its per-dimension limits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `BlockLimits` is what a node configures; `BlockLimiter` is what one block keeps while it runs. A limit known before execution — a transaction's gas limit, encoded size and data-availability size, and what each adds to the block — refuses the transaction before it runs. A limit only execution reveals is accumulated at commit and checked before the next transaction, so the transaction that crosses is still packed and the ones after it are refused. Of the three gas ledgers only execution has a block limit. History has none. The state ledger and the write-record count are accumulated with nowhere to be enforced yet: the state-gas block limit arrives with the state-gas limits, the write-record limit with the state-growth and KV limits. A deposit is exempt from both data-availability dimensions and adds nothing to the block's, since the chain cannot censor it. `MegaTxLimitExceededError` and `MegaBlockLimitExceededError` say which of the two happened: the transaction can never be included, or this block has no room for it. Ports the seven parked rows of the block limits and the limit errors. --- crates/mega-evm/src/block/limit.rs | 510 ++++++++++++++++++ crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/src/block/result.rs | 251 ++++++++- crates/mega-evm/tests/_pending/README.md | 12 +- .../tests/_pending/src/block/limit.rs | 97 ---- .../tests/_pending/src/block/result.rs | 65 --- 6 files changed, 768 insertions(+), 169 deletions(-) create mode 100644 crates/mega-evm/src/block/limit.rs delete mode 100644 crates/mega-evm/tests/_pending/src/block/limit.rs delete mode 100644 crates/mega-evm/tests/_pending/src/block/result.rs diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs new file mode 100644 index 000000000..37a8a5fb8 --- /dev/null +++ b/crates/mega-evm/src/block/limit.rs @@ -0,0 +1,510 @@ +//! What a block admits, and what it counts of the transactions it packed. +//! +//! [`BlockLimits`] is the configuration a node passes in the block execution context; +//! [`BlockLimiter`] is the state one block keeps while it executes. Every limit defaults to +//! unlimited, so a caller that configures nothing gets op-revm's block rules and nothing else. +//! +//! # When each limit is checked +//! +//! A limit known before execution is checked before the transaction runs, and refuses it: +//! its own gas limit, encoded size and data-availability size, and what each of those would add +//! to the block. +//! +//! A limit only known after execution — the execution ledger and the data-size bytes a +//! transaction kept — is accumulated when the transaction commits and checked before the *next* +//! transaction starts. The transaction that crosses such a limit is therefore still packed, and +//! the ones after it are refused; this is what keeps a block full rather than dropping the work +//! already done. A block whose counter has crossed refuses every later transaction, so the +//! overshoot is bounded by one transaction per dimension. +//! +//! # Which dimensions are enforced +//! +//! Of the three gas ledgers the block counts ([`BlockGasCounters`]), only execution has a block +//! limit. History has none by design. The state ledger and the write-record count are +//! accumulated here and enforced by nobody: the state-gas block limit arrives with the +//! state-gas limits, and the write-record limit with the state-growth and KV limits. + +use alloy_primitives::TxHash; + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::boxed::Box; + +use alloy_evm::block::{BlockExecutionError, BlockValidationError}; + +use crate::{ + BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, + MegaTxLimitExceededError, +}; + +/// The limits one block holds its transactions to. +/// +/// [`no_limits`](Self::no_limits) is the neutral value every field starts from; a node sets the +/// ones its chain configures, and the block executor always sets +/// [`block_gas_limit`](Self::block_gas_limit) from the block environment. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct BlockLimits { + /// The most gas a single transaction may declare. + pub tx_gas_limit: u64, + /// The block's gas limit: a transaction is admitted only if its declared gas limit fits in + /// what the block has left. Also the budget the data-availability footprint of the block's + /// transactions is held to. + pub block_gas_limit: u64, + /// The most bytes a single transaction's EIP-2718 encoding may take. + pub tx_encode_size_limit: u64, + /// The most bytes the block's transaction bodies may take together, uncompressed. + pub block_txs_encode_size_limit: u64, + /// The most data-availability bytes a single transaction may take. Deposits are exempt. + pub tx_da_size_limit: u64, + /// The most data-availability bytes the block's transactions may take together. Deposits are + /// exempt and do not count towards it. + pub block_da_size_limit: u64, + /// The most execution gas the block's transactions may spend together. + pub block_execution_gas_limit: u64, + /// The most data-size bytes the block's transactions may keep together. + pub block_txs_data_limit: u64, + /// The limits every transaction of the block runs under, which the executor installs on the + /// EVM. + pub tx_runtime_limits: EvmTxRuntimeLimits, +} + +impl Default for BlockLimits { + fn default() -> Self { + Self::no_limits() + } +} + +impl BlockLimits { + /// No limit at all. + pub const fn no_limits() -> Self { + Self { + tx_gas_limit: u64::MAX, + block_gas_limit: u64::MAX, + tx_encode_size_limit: u64::MAX, + block_txs_encode_size_limit: u64::MAX, + tx_da_size_limit: u64::MAX, + block_da_size_limit: u64::MAX, + block_execution_gas_limit: u64::MAX, + block_txs_data_limit: u64::MAX, + tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), + } + } + + /// Sets the per-transaction gas limit. + pub const fn with_tx_gas_limit(mut self, limit: u64) -> Self { + self.tx_gas_limit = limit; + self + } + + /// Sets the block's gas limit. + /// + /// The block executor overwrites it with the block environment's gas limit, which is the + /// number consensus holds the block to. + pub const fn with_block_gas_limit(mut self, limit: u64) -> Self { + self.block_gas_limit = limit; + self + } + + /// Sets the per-transaction encoded-size limit. + pub const fn with_tx_encode_size_limit(mut self, limit: u64) -> Self { + self.tx_encode_size_limit = limit; + self + } + + /// Sets the block's encoded-size limit. + pub const fn with_block_txs_encode_size_limit(mut self, limit: u64) -> Self { + self.block_txs_encode_size_limit = limit; + self + } + + /// Sets the per-transaction data-availability size limit. + pub const fn with_tx_da_size_limit(mut self, limit: u64) -> Self { + self.tx_da_size_limit = limit; + self + } + + /// Sets the block's data-availability size limit. + pub const fn with_block_da_size_limit(mut self, limit: u64) -> Self { + self.block_da_size_limit = limit; + self + } + + /// Sets the block's execution-gas limit. + pub const fn with_block_execution_gas_limit(mut self, limit: u64) -> Self { + self.block_execution_gas_limit = limit; + self + } + + /// Sets the block's data-size limit. + pub const fn with_block_txs_data_limit(mut self, limit: u64) -> Self { + self.block_txs_data_limit = limit; + self + } + + /// Sets the limits every transaction of the block runs under. + pub const fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.tx_runtime_limits = limits; + self + } + + /// The limits every transaction of the block runs under. + pub const fn to_evm_tx_runtime_limits(&self) -> EvmTxRuntimeLimits { + self.tx_runtime_limits + } + + /// A limiter that holds a block to these limits. + pub const fn to_block_limiter(self) -> BlockLimiter { + BlockLimiter::new(self) + } +} + +/// What one committed transaction adds to a block's counters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BlockUsage { + /// The gas the receipt reports. + pub gas_used: u64, + /// The gas by ledger. + pub gas: MegaGasUsage, + /// The data-size bytes and write records the transaction kept. + pub usage: LimitUsage, + /// The transaction's EIP-2718 encoded size, in bytes. + pub tx_size: u64, + /// The transaction's data-availability size, in bytes. + pub da_size: u64, + /// The transaction's data-availability footprint, in gas. + pub da_footprint: u64, + /// Whether the transaction is a deposit, which the data-availability dimensions exempt. + pub is_deposit: bool, +} + +/// What a block has used, and the limits it is held to. +/// +/// The counters are cumulative over the transactions the block committed; a transaction that was +/// executed and then discarded leaves them untouched. +#[derive(Clone, Debug)] +pub struct BlockLimiter { + /// The limits this block is held to. + pub limits: BlockLimits, + /// The gas the block's receipts report, which is the block header's gas used. + pub block_gas_used: u64, + /// The gas the block's transactions spent, by ledger. + pub gas: BlockGasCounters, + /// The data-size bytes and write records the block's transactions kept. + pub usage: LimitUsage, + /// The encoded size of the block's transaction bodies, in bytes. + pub block_tx_size_used: u64, + /// The data-availability size of the block's non-deposit transactions, in bytes. + pub block_da_size_used: u64, + /// The data-availability footprint of the block's non-deposit transactions, in gas. This is + /// what the block reports as its blob gas used. + pub block_da_footprint_used: u64, +} + +impl BlockLimiter { + /// A limiter with every counter at zero. + pub const fn new(limits: BlockLimits) -> Self { + Self { + limits, + block_gas_used: 0, + gas: BlockGasCounters { execution: 0, state: 0, history: 0 }, + usage: LimitUsage { data_size: 0, write_records: 0 }, + block_tx_size_used: 0, + block_da_size_used: 0, + block_da_footprint_used: 0, + } + } + + /// The gas the block still has for a transaction's declared gas limit. + pub const fn available_gas(&self) -> u64 { + self.limits.block_gas_limit.saturating_sub(self.block_gas_used) + } + + /// The data-availability footprint the block still has. The budget is the block's gas limit, + /// as the fork's rule states it. + pub const fn available_da_footprint(&self) -> u64 { + self.limits.block_gas_limit.saturating_sub(self.block_da_footprint_used) + } + + /// Whether `tx` may execute in this block. + /// + /// Checks the transaction against its own limits, and against what the block has left. It + /// reads the counters and changes nothing; + /// [`post_execution_update`](Self::post_execution_update) advances them once the + /// transaction commits. + /// + /// # Errors + /// + /// A [`MegaTxLimitExceededError`] when the transaction exceeds a limit of its own — it can + /// never be included, in this block or any other — and a [`MegaBlockLimitExceededError`] + /// when the block has no room left for it, which a builder answers by trying the next + /// transaction. + pub fn pre_execution_check( + &self, + tx_hash: TxHash, + gas_limit: u64, + tx_size: u64, + da_size: u64, + is_deposit: bool, + ) -> Result<(), BlockExecutionError> { + if gas_limit > self.limits.tx_gas_limit { + return Err(invalid_tx( + tx_hash, + MegaTxLimitExceededError::TransactionGasLimit { + tx_gas_limit: gas_limit, + limit: self.limits.tx_gas_limit, + }, + )); + } + + if self.block_gas_used.saturating_add(gas_limit) > self.limits.block_gas_limit { + return Err(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { + transaction_gas_limit: gas_limit, + block_available_gas: self.available_gas(), + } + .into()); + } + + if tx_size > self.limits.tx_encode_size_limit { + return Err(invalid_tx( + tx_hash, + MegaTxLimitExceededError::TransactionEncodeSizeLimit { + tx_size, + limit: self.limits.tx_encode_size_limit, + }, + )); + } + + if tx_size.saturating_add(self.block_tx_size_used) > self.limits.block_txs_encode_size_limit + { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::TransactionEncodeSizeLimit { + block_used: self.block_tx_size_used, + tx_used: tx_size, + limit: self.limits.block_txs_encode_size_limit, + }, + )); + } + + // A deposit is an L1 message the chain cannot censor, so it is exempt from both + // data-availability limits and does not count towards the block's. + if !is_deposit { + if da_size > self.limits.tx_da_size_limit { + return Err(invalid_tx( + tx_hash, + MegaTxLimitExceededError::DataAvailabilitySizeLimit { + da_size, + limit: self.limits.tx_da_size_limit, + }, + )); + } + + if da_size.saturating_add(self.block_da_size_used) > self.limits.block_da_size_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::DataAvailabilitySizeLimit { + block_used: self.block_da_size_used, + tx_used: da_size, + limit: self.limits.block_da_size_limit, + }, + )); + } + } + + // The dimensions a transaction's own execution reveals: the transaction that crossed one + // is already packed, so what is refused here is the next one. + if self.gas.execution >= self.limits.block_execution_gas_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::ExecutionGasLimit { + block_used: self.gas.execution, + limit: self.limits.block_execution_gas_limit, + }, + )); + } + + if self.usage.data_size >= self.limits.block_txs_data_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::TransactionDataLimit { + block_used: self.usage.data_size, + limit: self.limits.block_txs_data_limit, + }, + )); + } + + // `self.gas.state`, `self.gas.history` and `self.usage.write_records` are accumulated and + // not checked: history has no block limit, the state-gas block limit arrives with the + // state-gas limits, and the write-record limit with the state-growth and KV limits. + + Ok(()) + } + + /// Adds what one committed transaction used. + /// + /// Every counter saturates: a block that has already crossed a limit stays crossed, and the + /// check before the next transaction sees it. + pub fn post_execution_update(&mut self, usage: &BlockUsage) { + self.block_gas_used = self.block_gas_used.saturating_add(usage.gas_used); + self.gas.record(&usage.gas); + self.usage.data_size = self.usage.data_size.saturating_add(usage.usage.data_size); + self.usage.write_records = + self.usage.write_records.saturating_add(usage.usage.write_records); + self.block_tx_size_used = self.block_tx_size_used.saturating_add(usage.tx_size); + if !usage.is_deposit { + self.block_da_size_used = self.block_da_size_used.saturating_add(usage.da_size); + self.block_da_footprint_used = + self.block_da_footprint_used.saturating_add(usage.da_footprint); + } + } +} + +/// Wraps a limit error as the rejection of one transaction. +fn invalid_tx( + hash: TxHash, + error: impl alloy_evm::InvalidTxError + 'static, +) -> BlockExecutionError { + BlockValidationError::InvalidTx { hash, error: Box::new(error) }.into() +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::B256; + + fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { + BlockLimits::no_limits().with_block_gas_limit(block_gas_limit).with_tx_gas_limit(u64::MAX) + } + + fn saturated_usage() -> BlockUsage { + BlockUsage { + gas_used: u64::MAX, + gas: MegaGasUsage { + regular: u64::MAX, + state: u64::MAX, + history: u64::MAX, + ..Default::default() + }, + usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX }, + tx_size: u64::MAX, + da_size: u64::MAX, + da_footprint: u64::MAX, + is_deposit: false, + } + } + + #[test] + fn test_pre_execution_check_block_gas_addition_saturates() { + // Block has very high accumulated usage and a transaction with a near-`u64::MAX` + // gas limit; unchecked addition would wrap and accidentally pass the limit check. + let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); + limiter.block_gas_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); + assert!(result.is_err(), "saturating_add must keep the rejection in place"); + } + + #[test] + fn test_pre_execution_check_block_tx_size_addition_saturates() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_txs_encode_size_limit(1_000_000)); + limiter.block_tx_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); + assert!(result.is_err()); + } + + #[test] + fn test_pre_execution_check_block_da_size_addition_saturates() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_da_size_limit(1_000_000)); + limiter.block_da_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); + assert!(result.is_err()); + } + + #[test] + fn test_post_execution_update_saturates_all_counters() { + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_gas_used = u64::MAX - 1; + limiter.gas = BlockGasCounters { + execution: u64::MAX - 1, + state: u64::MAX - 1, + history: u64::MAX - 1, + }; + limiter.usage = LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1 }; + limiter.block_tx_size_used = u64::MAX - 1; + limiter.block_da_size_used = u64::MAX - 1; + limiter.block_da_footprint_used = u64::MAX - 1; + + limiter.post_execution_update(&saturated_usage()); + + assert_eq!(limiter.block_gas_used, u64::MAX); + assert_eq!( + limiter.gas, + BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX } + ); + assert_eq!(limiter.usage, LimitUsage { data_size: u64::MAX, write_records: u64::MAX }); + assert_eq!(limiter.block_tx_size_used, u64::MAX); + assert_eq!(limiter.block_da_size_used, u64::MAX); + assert_eq!(limiter.block_da_footprint_used, u64::MAX); + } + + #[test] + fn test_post_execution_update_skips_da_for_deposits() { + // Deposit transactions should not advance the data-availability counters, even when the + // value would otherwise saturate. + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_da_size_used = 100; + limiter.block_da_footprint_used = 200; + + limiter.post_execution_update(&BlockUsage { + is_deposit: true, + tx_size: 7, + ..saturated_usage() + }); + + assert_eq!(limiter.block_da_size_used, 100); + assert_eq!(limiter.block_da_footprint_used, 200); + assert_eq!(limiter.block_tx_size_used, 7, "a deposit still counts as a transaction body"); + } + + /// The execution ledger is the one gas dimension with a block limit: the transaction that + /// crosses it is already packed, and the next one is refused. + #[test] + fn test_execution_gas_limit_refuses_the_transaction_after_the_crossing() { + let mut limiter = + BlockLimiter::new(BlockLimits::no_limits().with_block_execution_gas_limit(1_000)); + + limiter.post_execution_update(&BlockUsage { + gas: MegaGasUsage { regular: 999, ..Default::default() }, + ..Default::default() + }); + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); + + limiter.post_execution_update(&BlockUsage { + gas: MegaGasUsage { regular: 1, ..Default::default() }, + ..Default::default() + }); + let err = limiter + .pre_execution_check(B256::ZERO, 0, 0, 0, false) + .expect_err("the block's execution gas has reached its limit"); + assert!(std::format!("{err}").contains("Block execution gas limit reached"), "{err}"); + } + + /// The state and history ledgers and the write-record count are accumulated, and no check + /// refuses a transaction on them. + #[test] + fn test_state_history_and_write_records_are_counted_but_not_enforced() { + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + + limiter.post_execution_update(&BlockUsage { + gas: MegaGasUsage { state: 10_000, history: 20_000, ..Default::default() }, + usage: LimitUsage { data_size: 0, write_records: 30 }, + ..Default::default() + }); + + assert_eq!(limiter.gas.state, 10_000); + assert_eq!(limiter.gas.history, 20_000); + assert_eq!(limiter.usage.write_records, 30); + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); + } +} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 9141ade89..30c55a4f5 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -3,9 +3,11 @@ mod chain; mod executor; mod hardfork; +mod limit; mod result; pub use chain::*; pub use executor::*; pub use hardfork::*; +pub use limit::*; pub use result::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index f3e2f378a..429c28032 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -1,4 +1,9 @@ -//! What a block counts of its transactions' gas. +//! What a block counts of its transactions, and how it refuses one. + +use core::fmt; + +use alloy_evm::InvalidTxError; +use revm::context::result::InvalidTransaction; use crate::MegaGasUsage; @@ -25,6 +30,191 @@ impl BlockGasCounters { } } +/// A transaction that exceeds a limit of its own. +/// +/// It can never be included — in this block or any other — so a builder drops it rather than +/// trying it again later. Every variant reports what the transaction +/// [used](Self::usage) and the [limit](Self::limit) it exceeded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MegaTxLimitExceededError { + /// The transaction declares more gas than one transaction may. + TransactionGasLimit { + /// The gas limit the transaction declares. + tx_gas_limit: u64, + /// The most gas a transaction may declare. + limit: u64, + }, + /// The transaction's encoding is larger than one transaction's may be. + TransactionEncodeSizeLimit { + /// The transaction's encoded size, in bytes. + tx_size: u64, + /// The most bytes a transaction's encoding may take. + limit: u64, + }, + /// The transaction's data-availability size is larger than one transaction's may be. + DataAvailabilitySizeLimit { + /// The transaction's data-availability size, in bytes. + da_size: u64, + /// The most data-availability bytes a transaction may take. + limit: u64, + }, +} + +impl MegaTxLimitExceededError { + /// What the transaction used of the resource. + pub const fn usage(&self) -> u64 { + match self { + Self::TransactionGasLimit { tx_gas_limit, .. } => *tx_gas_limit, + Self::TransactionEncodeSizeLimit { tx_size, .. } => *tx_size, + Self::DataAvailabilitySizeLimit { da_size, .. } => *da_size, + } + } + + /// The limit of the resource. + pub const fn limit(&self) -> u64 { + match self { + Self::TransactionGasLimit { limit, .. } | + Self::TransactionEncodeSizeLimit { limit, .. } | + Self::DataAvailabilitySizeLimit { limit, .. } => *limit, + } + } +} + +impl fmt::Display for MegaTxLimitExceededError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TransactionGasLimit { tx_gas_limit, limit } => { + write!( + f, + "Transaction gas limit exceeded: tx_gas_limit={tx_gas_limit} > limit={limit}" + ) + } + Self::TransactionEncodeSizeLimit { tx_size, limit } => { + write!( + f, + "Transaction encode size limit exceeded: tx_size={tx_size} > limit={limit}" + ) + } + Self::DataAvailabilitySizeLimit { da_size, limit } => { + write!( + f, + "Transaction data availability size limit exceeded: da_size={da_size} > limit={limit}" + ) + } + } + } +} + +impl core::error::Error for MegaTxLimitExceededError {} + +impl InvalidTxError for MegaTxLimitExceededError { + fn is_nonce_too_low(&self) -> bool { + false + } + + fn as_invalid_tx_err(&self) -> Option<&InvalidTransaction> { + // A `MegaETH` resource limit has no upstream `InvalidTransaction` counterpart. + None + } +} + +/// A block with no room left for one more transaction. +/// +/// Unlike [`MegaTxLimitExceededError`] this says nothing about the transaction: a builder tries +/// the next one, and the same transaction may well fit in the next block. Every variant reports +/// what the block [used](Self::block_used) and the [limit](Self::limit) it is held to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MegaBlockLimitExceededError { + /// The block's transactions have spent their execution gas. + ExecutionGasLimit { + /// The execution gas the block has spent. + block_used: u64, + /// The block's execution-gas limit. + limit: u64, + }, + /// The block's transactions have kept their data-size bytes. + TransactionDataLimit { + /// The data-size bytes the block has kept. + block_used: u64, + /// The block's data-size limit. + limit: u64, + }, + /// The transaction's body does not fit in what the block has left. + TransactionEncodeSizeLimit { + /// The bytes the block's transaction bodies already take. + block_used: u64, + /// The bytes this transaction's body would add. + tx_used: u64, + /// The block's encoded-size limit. + limit: u64, + }, + /// The transaction's data-availability size does not fit in what the block has left. + DataAvailabilitySizeLimit { + /// The data-availability bytes the block already takes. + block_used: u64, + /// The data-availability bytes this transaction would add. + tx_used: u64, + /// The block's data-availability size limit. + limit: u64, + }, +} + +impl MegaBlockLimitExceededError { + /// What the block used of the resource. + pub const fn block_used(&self) -> u64 { + match self { + Self::ExecutionGasLimit { block_used, .. } | + Self::TransactionDataLimit { block_used, .. } | + Self::TransactionEncodeSizeLimit { block_used, .. } | + Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, + } + } + + /// The limit of the resource. + pub const fn limit(&self) -> u64 { + match self { + Self::ExecutionGasLimit { limit, .. } | + Self::TransactionDataLimit { limit, .. } | + Self::TransactionEncodeSizeLimit { limit, .. } | + Self::DataAvailabilitySizeLimit { limit, .. } => *limit, + } + } +} + +impl fmt::Display for MegaBlockLimitExceededError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ExecutionGasLimit { block_used, limit } => { + write!(f, "Block execution gas limit reached: block_used={block_used} >= limit={limit}") + } + Self::TransactionDataLimit { block_used, limit } => { + write!(f, "Block transactions data limit reached: block_used={block_used} >= limit={limit}") + } + Self::TransactionEncodeSizeLimit { block_used, tx_used, limit } => write!( + f, + "Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" + ), + Self::DataAvailabilitySizeLimit { block_used, tx_used, limit } => write!( + f, + "Block data availability size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" + ), + } + } +} + +impl core::error::Error for MegaBlockLimitExceededError {} + +impl InvalidTxError for MegaBlockLimitExceededError { + fn is_nonce_too_low(&self) -> bool { + false + } + + fn as_invalid_tx_err(&self) -> Option<&InvalidTransaction> { + // A full block has no upstream `InvalidTransaction` counterpart. + None + } +} + #[cfg(test)] mod tests { use super::*; @@ -41,6 +231,65 @@ mod tests { assert_eq!(block, BlockGasCounters { execution: 60, state: 21, history: 32 }); } + #[test] + fn test_transaction_limit_error_reports_usage_and_limit() { + let cases = [ + (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), + ( + MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, + 101, + 100, + ), + ( + MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, + 11, + 10, + ), + ]; + + for (error, expected_usage, expected_limit) in cases { + assert_eq!(error.usage(), expected_usage); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + // A resource limit of this engine has no upstream counterpart, so classification + // downstream reads "drop this transaction", not "abort the payload". + assert!(error.as_invalid_tx_err().is_none(), "no counterpart for {error}"); + } + } + + #[test] + fn test_block_limit_error_reports_block_usage_and_limit() { + let cases = [ + (MegaBlockLimitExceededError::ExecutionGasLimit { block_used: 3, limit: 12 }, 3, 12), + (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + ( + MegaBlockLimitExceededError::TransactionEncodeSizeLimit { + block_used: 4, + tx_used: 1, + limit: 13, + }, + 4, + 13, + ), + ( + MegaBlockLimitExceededError::DataAvailabilitySizeLimit { + block_used: 5, + tx_used: 1, + limit: 14, + }, + 5, + 14, + ), + ]; + + for (error, expected_block_used, expected_limit) in cases { + assert_eq!(error.block_used(), expected_block_used); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + assert!(error.as_invalid_tx_err().is_none(), "no counterpart for {error}"); + } + } + #[test] fn test_block_counters_saturate() { let mut block = diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 4033b4e70..5c30a8c8a 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,10 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 34 | 23 | 11 | 27 | 7 | 0 | +| the block executor | 27 | 23 | 4 | 22 | 5 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **728** | **624** | **104** | **414** | **286** | **28** | +| **Total** | **721** | **624** | **97** | **409** | **284** | **28** | ## Tests ported in place @@ -132,15 +132,17 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by the block executor -These 19 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 26 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | | `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | +| `src/block/limit.rs` | the block executor (5) | 5 | `src/block/limit.rs` | +| `src/block/result.rs` | the block executor (2) | 2 | `src/block/result.rs` | | `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | -| **Total** | | **19** | | +| **Total** | | **26** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -231,8 +233,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/block/eips.rs` | 1 | keep 1 (the block executor) | | `src/block/helpers.rs` | 3 | keep 3 (the block executor) | -| `src/block/limit.rs` | 5 | keep 5 (the block executor) | -| `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | diff --git a/crates/mega-evm/tests/_pending/src/block/limit.rs b/crates/mega-evm/tests/_pending/src/block/limit.rs deleted file mode 100644 index ebe3786ae..000000000 --- a/crates/mega-evm/tests/_pending/src/block/limit.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/limit.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/limit.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::B256; - - fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = block_gas_limit; - limits.tx_gas_limit = u64::MAX; - limits - } - - fn limits_with_block_tx_size(block_txs_encode_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_txs_encode_size_limit = block_txs_encode_size_limit; - limits - } - - fn limits_with_block_da_size(block_da_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_da_size_limit = block_da_size_limit; - limits - } - - #[test] - fn test_pre_execution_check_block_gas_addition_saturates() { - // Block has very high accumulated usage and a transaction with a near-`u64::MAX` - // gas limit; unchecked addition would wrap and accidentally pass the limit check. - let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); - limiter.block_gas_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); - assert!(result.is_err(), "saturating_add must keep the rejection in place"); - } - - #[test] - fn test_pre_execution_check_block_tx_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_tx_size(1_000_000)); - limiter.block_tx_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); - assert!(result.is_err()); - } - - #[test] - fn test_pre_execution_check_block_da_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_da_size(1_000_000)); - limiter.block_da_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); - assert!(result.is_err()); - } - - #[test] - fn test_post_execution_update_raw_saturates_all_counters() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_gas_used = u64::MAX - 1; - limiter.block_tx_size_used = u64::MAX - 1; - limiter.block_da_size_used = u64::MAX - 1; - limiter.block_data_used = u64::MAX - 1; - limiter.block_kv_updates_used = u64::MAX - 1; - limiter.block_compute_gas_used = u64::MAX - 1; - limiter.block_state_growth_used = u64::MAX - 1; - - limiter.post_execution_update_raw( - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - false, - ); - - assert_eq!(limiter.block_gas_used, u64::MAX); - assert_eq!(limiter.block_tx_size_used, u64::MAX); - assert_eq!(limiter.block_da_size_used, u64::MAX); - assert_eq!(limiter.block_data_used, u64::MAX); - assert_eq!(limiter.block_kv_updates_used, u64::MAX); - assert_eq!(limiter.block_compute_gas_used, u64::MAX); - assert_eq!(limiter.block_state_growth_used, u64::MAX); - } - - #[test] - fn test_post_execution_update_raw_skips_da_for_deposits() { - // Deposit transactions should not advance `block_da_size_used`, even when the value - // would otherwise saturate. - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_da_size_used = 100; - - limiter.post_execution_update_raw(0, 0, u64::MAX, 0, 0, 0, 0, true); - - assert_eq!(limiter.block_da_size_used, 100); - } -} diff --git a/crates/mega-evm/tests/_pending/src/block/result.rs b/crates/mega-evm/tests/_pending/src/block/result.rs deleted file mode 100644 index a0c55ca24..000000000 --- a/crates/mega-evm/tests/_pending/src/block/result.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/result.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/result.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_transaction_limit_error_reports_usage_and_limit() { - let cases = [ - (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), - ( - MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, - 101, - 100, - ), - ( - MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, - 11, - 10, - ), - ]; - - for (error, expected_usage, expected_limit) in cases { - assert_eq!(error.usage(), expected_usage); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } - } - - #[test] - fn test_block_limit_error_reports_block_usage_and_limit() { - let cases = [ - (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), - (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 2, limit: 11 }, 2, 11), - (MegaBlockLimitExceededError::ComputeGasLimit { block_used: 3, limit: 12 }, 3, 12), - ( - MegaBlockLimitExceededError::TransactionEncodeSizeLimit { - block_used: 4, - tx_used: 1, - limit: 13, - }, - 4, - 13, - ), - ( - MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: 5, - tx_used: 1, - limit: 14, - }, - 5, - 14, - ), - (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 6, limit: 15 }, 6, 15), - ]; - - for (error, expected_block_used, expected_limit) in cases { - assert_eq!(error.block_used(), expected_block_used); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } - } -} From 0eb3a257f9115ceef3a625b1b41795c1a8c79de2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:08:43 +0800 Subject: [PATCH 093/201] feat(block): read a transaction's hash and sizes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The block-level limits are stated over a transaction's hash, its encoded size and its data-availability size, none of which is part of the transaction environment. `MegaTransactionExt` is where block execution reads them, with defaults that recompute both sizes from the encoding. `EnrichedMegaTx` carries them already computed, for a caller that has them — a sequencer's own mempool. The values are trusted as they are and never checked against the encoding, so an understated one would pass a limit it should have been refused by; the type documents that and `new_slow` is the answer anywhere else. The data-availability estimate is the fork's own, read through op-revm, so the engine and the node agree on the figure by construction. Ports the three parked rows of the transaction helpers. --- Cargo.lock | 1 + crates/mega-evm/Cargo.toml | 1 + crates/mega-evm/src/block/helpers.rs | 450 ++++++++++++++++++ crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/tests/_pending/README.md | 10 +- .../tests/_pending/src/block/helpers.rs | 205 -------- 6 files changed, 459 insertions(+), 210 deletions(-) create mode 100644 crates/mega-evm/src/block/helpers.rs delete mode 100644 crates/mega-evm/tests/_pending/src/block/helpers.rs diff --git a/Cargo.lock b/Cargo.lock index 1890f3100..a61460fa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2765,6 +2765,7 @@ name = "mega-evm" version = "2.0.0-alpha.1" dependencies = [ "alloy-consensus", + "alloy-eips", "alloy-evm", "alloy-hardforks", "alloy-op-evm", diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index cd6ee04fc..79cc1b469 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -15,6 +15,7 @@ workspace = true [dependencies] # alloy alloy-consensus = { workspace = true, features = ["k256"] } +alloy-eips.workspace = true alloy-evm.workspace = true alloy-hardforks.workspace = true alloy-op-evm.workspace = true diff --git a/crates/mega-evm/src/block/helpers.rs b/crates/mega-evm/src/block/helpers.rs new file mode 100644 index 000000000..e5dd807c1 --- /dev/null +++ b/crates/mega-evm/src/block/helpers.rs @@ -0,0 +1,450 @@ +//! What block execution needs of a transaction besides its environment. +//! +//! The block-level limits are stated over a transaction's hash and its two sizes, and none of +//! them is part of revm's transaction environment. [`MegaTransactionExt`] is where block +//! execution reads them; [`EnrichedMegaTx`] is a transaction that carries them already computed, +//! for a caller that has them. + +use alloy_consensus::{transaction::Recovered, Transaction}; +use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization, Encodable2718, Typed2718}; +use alloy_evm::{RecoveredTx, ToTxEnv}; +use alloy_primitives::{Address, Bytes, ChainId, Selector, TxHash, TxKind, B256, U256}; +use auto_impl::auto_impl; +use delegate::delegate; + +use crate::MegaTxEnvelope; + +/// Scale [`op_revm::estimate_tx_compressed_size`] is returned in. +const COMPRESSED_SIZE_SCALE: u64 = 1_000_000; + +/// The estimated size `bytes` take on data availability, in bytes. +/// +/// The estimate is the fork's own: op-revm scales it by [`COMPRESSED_SIZE_SCALE`], and the +/// per-transaction figure the limits are stated in is that estimate in bytes. +pub fn estimated_da_size(bytes: &[u8]) -> u64 { + op_revm::estimate_tx_compressed_size(bytes) / COMPRESSED_SIZE_SCALE +} + +/// What block execution reads off a transaction beside its environment. +/// +/// The two sizes have defaults that compute them from the transaction's encoding. A type that +/// already knows them (see [`EnrichedMegaTx`]) answers with what it carries, and the choice is +/// made at compile time — no caller picks a variant. +#[auto_impl(&)] +pub trait MegaTransactionExt { + /// The size the transaction takes on data availability, in bytes. + /// + /// The default recomputes it from the encoding on every call. + fn estimated_da_size(&self) -> u64 + where + Self: Encodable2718, + { + estimated_da_size(self.encoded_2718().as_slice()) + } + + /// The transaction's EIP-2718 encoded size, in bytes. + fn tx_size(&self) -> u64 + where + Self: Encodable2718, + { + self.encode_2718_len() as u64 + } + + /// The transaction's hash. + fn tx_hash(&self) -> TxHash; +} + +impl MegaTransactionExt for Recovered { + fn tx_hash(&self) -> TxHash { + self.inner().tx_hash() + } +} + +impl MegaTransactionExt for Recovered<&MegaTxEnvelope> { + fn tx_hash(&self) -> TxHash { + self.inner().tx_hash() + } +} + +impl MegaTransactionExt for MegaTxEnvelope { + fn tx_hash(&self) -> TxHash { + self.tx_hash() + } +} + +/// A transaction that carries its hash and its two sizes already computed. +/// +/// # Correctness +/// +/// The carried values are trusted as they are and never checked against the transaction's real +/// encoding. They feed the per-transaction and block-level size limits, so an understated value +/// lets a transaction through a limit it should have been refused by. Pass only values computed +/// from this very transaction by a party that is trusted to have done so — a sequencer's own +/// mempool at insertion time — and use [`new_slow`](Self::new_slow) anywhere else. +#[derive(Clone, Debug)] +pub struct EnrichedMegaTx { + inner: T, + /// The transaction's hash. + pub tx_hash: TxHash, + /// The size the transaction takes on data availability, in bytes. + pub da_size: u64, + /// The transaction's EIP-2718 encoded size, in bytes. + pub tx_size: u64, +} + +impl EnrichedMegaTx { + /// A transaction carrying values the caller computed. See the type's correctness note. + pub const fn new(inner: T, tx_hash: TxHash, da_size: u64, tx_size: u64) -> Self { + Self { inner, tx_hash, da_size, tx_size } + } + + /// The transaction inside. + pub const fn inner(&self) -> &T { + &self.inner + } + + /// Consumes the wrapper and returns the transaction inside. + pub fn into_inner(self) -> T { + self.inner + } +} + +impl EnrichedMegaTx { + /// A transaction whose hash and sizes are computed here, from its own encoding. + pub fn new_slow(inner: T) -> Self { + Self { + tx_hash: inner.trie_hash(), + da_size: estimated_da_size(inner.encoded_2718().as_slice()), + tx_size: inner.encode_2718_len() as u64, + inner, + } + } +} + +impl core::ops::Deref for EnrichedMegaTx { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl core::ops::DerefMut for EnrichedMegaTx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} + +impl AsRef for EnrichedMegaTx { + fn as_ref(&self) -> &T { + &self.inner + } +} + +impl AsMut for EnrichedMegaTx { + fn as_mut(&mut self) -> &mut T { + &mut self.inner + } +} + +impl Encodable2718 for EnrichedMegaTx { + delegate! { + to self.inner { + fn type_flag(&self) -> Option; + fn encode_2718_len(&self) -> usize; + fn encode_2718(&self, out: &mut dyn alloy_primitives::bytes::BufMut); + } + } +} + +impl MegaTransactionExt for EnrichedMegaTx { + fn estimated_da_size(&self) -> u64 { + self.da_size + } + + fn tx_size(&self) -> u64 { + self.tx_size + } + + fn tx_hash(&self) -> TxHash { + self.tx_hash + } +} + +impl Typed2718 for EnrichedMegaTx { + delegate! { + to self.inner { + fn ty(&self) -> u8; + fn is_type(&self, ty: u8) -> bool; + fn is_legacy(&self) -> bool; + fn is_eip2930(&self) -> bool; + fn is_eip1559(&self) -> bool; + fn is_eip4844(&self) -> bool; + fn is_eip7702(&self) -> bool; + } + } +} + +impl Transaction for EnrichedMegaTx { + delegate! { + to self.inner { + fn chain_id(&self) -> Option; + fn nonce(&self) -> u64; + fn gas_limit(&self) -> u64; + fn gas_price(&self) -> Option; + fn max_fee_per_gas(&self) -> u128; + fn max_priority_fee_per_gas(&self) -> Option; + fn max_fee_per_blob_gas(&self) -> Option; + fn priority_fee_or_price(&self) -> u128; + fn effective_gas_price(&self, base_fee: Option) -> u128; + fn is_dynamic_fee(&self) -> bool; + fn kind(&self) -> TxKind; + fn is_create(&self) -> bool; + fn value(&self) -> U256; + fn input(&self) -> &Bytes; + fn access_list(&self) -> Option<&AccessList>; + fn blob_versioned_hashes(&self) -> Option<&[B256]>; + fn authorization_list(&self) -> Option<&[SignedAuthorization]>; + fn authorization_count(&self) -> Option; + fn effective_tip_per_gas(&self, base_fee: u64) -> Option; + fn to(&self) -> Option

; + fn function_selector(&self) -> Option<&Selector>; + fn blob_count(&self) -> Option; + fn blob_gas_used(&self) -> Option; + } + } +} + +impl> RecoveredTx for EnrichedMegaTx { + delegate! { + to self.inner { + fn tx(&self) -> &Tx; + fn signer(&self) -> &Address; + } + } +} + +/// Being both this and a [`RecoveredTx`] is what makes a reference to the wrapper an +/// executable transaction of a block. +impl> ToTxEnv for EnrichedMegaTx { + delegate! { + to self.inner { + fn to_tx_env(&self) -> Tx; + } + } +} + +impl Copy for EnrichedMegaTx {} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_consensus::{Signed, TxLegacy}; + use alloy_primitives::{address, bytes::BufMut, Signature}; + use revm::context::TxEnv; + + const CALLER: Address = address!("0x2000000000000000000000000000000000000001"); + const CONTRACT: Address = address!("0x3000000000000000000000000000000000000001"); + + #[derive(Debug, Clone)] + struct MockTx { + nonce: u64, + gas_limit: u64, + value: U256, + input: Bytes, + } + + impl Typed2718 for MockTx { + fn ty(&self) -> u8 { + 0 + } + } + + impl Encodable2718 for MockTx { + fn encode_2718_len(&self) -> usize { + self.input.len() + } + + fn encode_2718(&self, out: &mut dyn BufMut) { + out.put_slice(&self.input); + } + } + + impl Transaction for MockTx { + fn chain_id(&self) -> Option { + Some(1) + } + + fn nonce(&self) -> u64 { + self.nonce + } + + fn gas_limit(&self) -> u64 { + self.gas_limit + } + + fn gas_price(&self) -> Option { + Some(9) + } + + fn max_fee_per_gas(&self) -> u128 { + 9 + } + + fn max_priority_fee_per_gas(&self) -> Option { + None + } + + fn max_fee_per_blob_gas(&self) -> Option { + None + } + + fn priority_fee_or_price(&self) -> u128 { + 9 + } + + fn effective_gas_price(&self, _base_fee: Option) -> u128 { + 9 + } + + fn is_dynamic_fee(&self) -> bool { + false + } + + fn kind(&self) -> TxKind { + TxKind::Call(CONTRACT) + } + + fn is_create(&self) -> bool { + false + } + + fn value(&self) -> U256 { + self.value + } + + fn input(&self) -> &Bytes { + &self.input + } + + fn access_list(&self) -> Option<&AccessList> { + None + } + + fn blob_versioned_hashes(&self) -> Option<&[B256]> { + None + } + + fn authorization_list(&self) -> Option<&[SignedAuthorization]> { + None + } + } + + #[derive(Debug, Clone)] + struct MockRecoveredTx { + tx: TxEnv, + signer: Address, + } + + impl RecoveredTx for MockRecoveredTx { + fn tx(&self) -> &TxEnv { + &self.tx + } + + fn signer(&self) -> &Address { + &self.signer + } + } + + impl ToTxEnv for MockRecoveredTx { + fn to_tx_env(&self) -> TxEnv { + self.tx.clone() + } + } + + fn legacy_tx() -> TxLegacy { + TxLegacy { + chain_id: Some(1), + nonce: 7, + gas_price: 9, + gas_limit: 21_000, + to: TxKind::Call(CONTRACT), + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + } + } + + fn legacy_envelope() -> MegaTxEnvelope { + MegaTxEnvelope::Legacy(Signed::new_unchecked( + legacy_tx(), + Signature::test_signature(), + B256::repeat_byte(9), + )) + } + + #[test] + fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { + let tx = legacy_envelope(); + let recovered = Recovered::new_unchecked(tx.clone(), CALLER); + + assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); + assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); + assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); + assert!(MegaTransactionExt::tx_size(&tx) > 0); + } + + #[test] + fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { + let tx = MockTx { + nonce: 7, + gas_limit: 21_000, + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + }; + let expected_hash = tx.trie_hash(); + let expected_da_size = estimated_da_size(tx.encoded_2718().as_slice()); + let expected_tx_size = tx.encode_2718_len() as u64; + + let enriched = EnrichedMegaTx::new_slow(tx); + + assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); + assert_eq!(enriched.da_size, expected_da_size); + assert_eq!(enriched.tx_size, expected_tx_size); + assert_eq!(enriched.nonce(), 7); + assert_eq!(enriched.gas_limit(), 21_000); + assert_eq!(enriched.value(), U256::from(11)); + assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); + } + + #[test] + fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { + let tx_env = TxEnv { + caller: CALLER, + gas_limit: 21_000, + kind: TxKind::Call(CONTRACT), + value: U256::from(11), + data: Bytes::from_static(&[0xaa, 0xbb]), + ..Default::default() + }; + let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; + let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); + + assert_eq!(enriched.tx(), &tx_env); + assert_eq!(*enriched.signer(), CALLER); + + let converted: TxEnv = alloy_evm::IntoTxEnv::into_tx_env(enriched); + assert_eq!(converted, tx_env); + } + + /// The carried figures are what block execution reads, even when they disagree with the + /// encoding — which is the whole point of the type, and its risk. + #[test] + fn test_enriched_mega_tx_reports_the_values_it_carries() { + let enriched = EnrichedMegaTx::new(legacy_envelope(), TxHash::ZERO, 1, 2); + + assert_eq!(MegaTransactionExt::tx_hash(&enriched), TxHash::ZERO); + assert_eq!(MegaTransactionExt::estimated_da_size(&enriched), 1); + assert_eq!(MegaTransactionExt::tx_size(&enriched), 2); + assert_ne!(enriched.inner().tx_hash(), TxHash::ZERO, "the transaction's own hash differs"); + } +} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 30c55a4f5..3e4be9204 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -3,11 +3,13 @@ mod chain; mod executor; mod hardfork; +mod helpers; mod limit; mod result; pub use chain::*; pub use executor::*; pub use hardfork::*; +pub use helpers::*; pub use limit::*; pub use result::*; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 5c30a8c8a..d6ad5750e 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,10 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 27 | 23 | 4 | 22 | 5 | 0 | +| the block executor | 24 | 23 | 1 | 19 | 5 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **721** | **624** | **97** | **409** | **284** | **28** | +| **Total** | **718** | **624** | **94** | **406** | **284** | **28** | ## Tests ported in place @@ -132,17 +132,18 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by the block executor -These 26 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 29 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | | `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | +| `src/block/helpers.rs` | the block executor (3) | 3 | `src/block/helpers.rs` | | `src/block/limit.rs` | the block executor (5) | 5 | `src/block/limit.rs` | | `src/block/result.rs` | the block executor (2) | 2 | `src/block/result.rs` | | `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | -| **Total** | | **26** | | +| **Total** | | **29** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -232,7 +233,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/block/eips.rs` | 1 | keep 1 (the block executor) | -| `src/block/helpers.rs` | 3 | keep 3 (the block executor) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | diff --git a/crates/mega-evm/tests/_pending/src/block/helpers.rs b/crates/mega-evm/tests/_pending/src/block/helpers.rs deleted file mode 100644 index 9a45b97fd..000000000 --- a/crates/mega-evm/tests/_pending/src/block/helpers.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/helpers.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/helpers.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; - use alloy_primitives::{address, bytes::BufMut, Signature}; - use revm::context::TxEnv; - - const CALLER: Address = address!("2000000000000000000000000000000000000001"); - const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - - #[derive(Debug, Clone)] - struct MockTx { - nonce: u64, - gas_limit: u64, - value: U256, - input: Bytes, - } - - impl Typed2718 for MockTx { - fn ty(&self) -> u8 { - 0 - } - } - - impl Encodable2718 for MockTx { - fn encode_2718_len(&self) -> usize { - self.input.len() - } - - fn encode_2718(&self, out: &mut dyn BufMut) { - out.put_slice(&self.input); - } - } - - impl Transaction for MockTx { - fn chain_id(&self) -> Option { - Some(1) - } - - fn nonce(&self) -> u64 { - self.nonce - } - - fn gas_limit(&self) -> u64 { - self.gas_limit - } - - fn gas_price(&self) -> Option { - Some(9) - } - - fn max_fee_per_gas(&self) -> u128 { - 9 - } - - fn max_priority_fee_per_gas(&self) -> Option { - None - } - - fn max_fee_per_blob_gas(&self) -> Option { - None - } - - fn priority_fee_or_price(&self) -> u128 { - 9 - } - - fn effective_gas_price(&self, _base_fee: Option) -> u128 { - 9 - } - - fn is_dynamic_fee(&self) -> bool { - false - } - - fn kind(&self) -> TxKind { - TxKind::Call(CONTRACT) - } - - fn is_create(&self) -> bool { - false - } - - fn value(&self) -> U256 { - self.value - } - - fn input(&self) -> &Bytes { - &self.input - } - - fn access_list(&self) -> Option<&AccessList> { - None - } - - fn blob_versioned_hashes(&self) -> Option<&[B256]> { - None - } - - fn authorization_list(&self) -> Option<&[SignedAuthorization]> { - None - } - } - - #[derive(Debug, Clone)] - struct MockRecoveredTx { - tx: TxEnv, - signer: Address, - } - - impl RecoveredTx for MockRecoveredTx { - fn tx(&self) -> &TxEnv { - &self.tx - } - - fn signer(&self) -> &Address { - &self.signer - } - } - - impl IntoTxEnv for MockRecoveredTx { - fn into_tx_env(self) -> TxEnv { - self.tx - } - } - - fn legacy_tx() -> TxLegacy { - TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - } - } - - fn legacy_envelope() -> MegaTxEnvelope { - MegaTxEnvelope::Legacy(Signed::new_unchecked( - legacy_tx(), - Signature::test_signature(), - Default::default(), - )) - } - - #[test] - fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx.clone(), CALLER); - - assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); - assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); - assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); - assert!(MegaTransactionExt::tx_size(&tx) > 0); - } - - #[test] - fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { - let tx = MockTx { - nonce: 7, - gas_limit: 21_000, - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - }; - let expected_hash = tx.trie_hash(); - let expected_da_size = - op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()); - let expected_tx_size = tx.encode_2718_len() as u64; - - let enriched = EnrichedMegaTx::new_slow(tx); - - assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); - assert_eq!(enriched.da_size, expected_da_size); - assert_eq!(enriched.tx_size, expected_tx_size); - assert_eq!(enriched.nonce(), 7); - assert_eq!(enriched.gas_limit(), 21_000); - assert_eq!(enriched.value(), U256::from(11)); - assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); - } - - #[test] - fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { - let tx_env = TxEnv { - caller: CALLER, - gas_limit: 21_000, - kind: TxKind::Call(CONTRACT), - value: U256::from(11), - data: Bytes::from_static(&[0xaa, 0xbb]), - ..Default::default() - }; - let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; - let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); - - assert_eq!(enriched.tx(), &tx_env); - assert_eq!(*enriched.signer(), CALLER); - - let converted: TxEnv = enriched.into_tx_env(); - assert_eq!(converted, tx_env); - } -} From 7c47fdfad80456f4c5b9ba855542145f3d6d8f09 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:09:27 +0800 Subject: [PATCH 094/201] feat(evm): run the Satin precompile set behind a dynamic map The set is op-revm's Karst set with KZG point evaluation repriced to 100,000. It is carried as an alloy-evm PrecompilesMap, so a node's RPC can add or replace an address through MegaEvmFactory::with_dyn_precompiles_builder. Public surface: MegaEvm's and MegaEvmFactory's Precompiles associated type is PrecompilesMap instead of OpPrecompiles, and the trait impls on MegaEvm take alloy-evm's Database bound, which the map's provider requires. --- crates/mega-evm/src/evm/execution.rs | 6 +- crates/mega-evm/src/evm/factory.rs | 164 ++++++++++++-- crates/mega-evm/src/evm/mod.rs | 44 ++-- crates/mega-evm/src/evm/precompiles.rs | 285 +++++++++++++++++++++++++ crates/mega-evm/src/evm/prices.rs | 2 +- 5 files changed, 462 insertions(+), 39 deletions(-) create mode 100644 crates/mega-evm/src/evm/precompiles.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 7000aa11f..223eac2dd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -12,7 +12,7 @@ use op_revm::{ }; use std::vec::Vec; -use op_revm::precompiles::OpPrecompiles; +use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::{ result::FromStringError, transaction::TransactionType, ContextError, ContextTr, FrameStack, @@ -37,7 +37,7 @@ use revm::{ InitialAndFloorGas, InstructionResult, InterpreterAction, }, primitives::{Address, Bytes, CALL_STACK_LIMIT}, - Database, Inspector, Journal, + Inspector, Journal, }; use crate::{ @@ -203,7 +203,7 @@ where impl EvmTr for MegaEvm { type Context = MegaContext; type Instructions = MegaInstructions; - type Precompiles = OpPrecompiles; + type Precompiles = PrecompilesMap; type Frame = EthFrame; #[inline] diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index e8c4bf204..d7d4a9650 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -1,7 +1,8 @@ //! Factory of Satin EVMs for alloy-evm consumers. -use alloy_evm::{Database, EvmEnv}; -use op_revm::{precompiles::OpPrecompiles, OpHaltReason}; +use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; +use core::fmt; +use op_revm::OpHaltReason; use revm::{ context::{result::EVMError, BlockEnv, DBErrorMarker}, inspector::NoOpInspector, @@ -9,23 +10,34 @@ use revm::{ }; use crate::{ - EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - MegaTransactionError, + DynPrecompilesBuilder, EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, + MegaTransaction, MegaTransactionError, }; /// Creates [`MegaEvm`]s for alloy-evm consumers such as a node's block executor. /// /// The factory holds the [`ExternalEnvFactory`] that supplies each EVM with the SALT and oracle -/// environments of the block it executes. -#[derive(Clone, Debug, Default)] +/// environments of the block it executes, and the optional builder of the dynamic precompiles a +/// node adds on top of the Satin set. +#[derive(Clone, Default)] pub struct MegaEvmFactory { external_env_factory: ExtEnvFactory, + dyn_precompiles_builder: Option, +} + +impl fmt::Debug for MegaEvmFactory { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MegaEvmFactory") + .field("external_env_factory", &self.external_env_factory) + .field("dyn_precompiles_builder", &self.dyn_precompiles_builder.is_some()) + .finish() + } } impl MegaEvmFactory { /// Creates a factory whose EVMs have no external environments. pub const fn new() -> Self { - Self { external_env_factory: EmptyExternalEnv } + Self { external_env_factory: EmptyExternalEnv, dyn_precompiles_builder: None } } } @@ -40,7 +52,17 @@ impl MegaEvmFactory { self, external_env_factory: F, ) -> MegaEvmFactory { - MegaEvmFactory { external_env_factory } + MegaEvmFactory { + external_env_factory, + dyn_precompiles_builder: self.dyn_precompiles_builder, + } + } + + /// Adds a builder of dynamic precompiles. Every EVM the factory creates runs the Satin set + /// with what the builder returns applied on top. + pub fn with_dyn_precompiles_builder(mut self, builder: DynPrecompilesBuilder) -> Self { + self.dyn_precompiles_builder = Some(builder); + self } } @@ -53,12 +75,8 @@ impl alloy_evm::EvmFactory for MegaEvmFactory type HaltReason = OpHaltReason; type Spec = MegaSpecId; type BlockEnv = BlockEnv; - /// op-revm's precompile set for the base spec. - /// - /// Provisional: the Satin precompile provider replaces this type when it lands, and code that - /// names `OpPrecompiles` through this associated type has no source-compatibility promise - /// across that change. - type Precompiles = OpPrecompiles; + /// The Satin precompile set, with whatever the factory's builder added to it. + type Precompiles = PrecompilesMap; /// Creates an EVM for the block in `evm_env`, with the external environments of that block. /// @@ -72,10 +90,15 @@ impl alloy_evm::EvmFactory for MegaEvmFactory let EvmEnv { cfg_env, block_env } = evm_env; let external_envs = self.external_env_factory.external_envs(block_env.number.saturating_to()); - let ctx = MegaContext::new_with_external_envs(db, cfg_env.spec, external_envs) + let spec = cfg_env.spec; + let ctx = MegaContext::new_with_external_envs(db, spec, external_envs) .with_cfg(cfg_env) .with_block(block_env); - MegaEvm::new(ctx) + let evm = MegaEvm::new(ctx); + match &self.dyn_precompiles_builder { + Some(builder) => evm.with_dyn_precompiles(builder(spec)), + None => evm, + } } fn create_evm_with_inspector>>( @@ -90,12 +113,28 @@ impl alloy_evm::EvmFactory for MegaEvmFactory #[cfg(test)] mod tests { + #[cfg(not(feature = "std"))] + use alloc as std; + use std::sync::Arc; + use super::*; - use crate::{test_utils::MemoryDatabase, ExternalEnvs, SaltEnv, TestExternalEnvs}; - use alloy_evm::{Evm, EvmFactory}; - use alloy_primitives::{BlockNumber, U256}; - use core::cell::Cell; - use revm::context::CfgEnv; + use crate::{ + satin_precompiles, + test_utils::{op_transaction, MemoryDatabase}, + ExternalEnvs, SaltEnv, TestExternalEnvs, + }; + use alloy_evm::{precompiles::DynPrecompile, Evm, EvmFactory}; + use alloy_op_evm::OpTx; + use alloy_primitives::{address, Address, BlockNumber, Bytes, TxKind, U256}; + use core::{ + cell::Cell, + sync::atomic::{AtomicUsize, Ordering}, + }; + use revm::{ + context::{CfgEnv, TxEnv}, + precompile::{PrecompileId, PrecompileOutput}, + primitives::HashMap, + }; #[test] fn test_external_env_factory_getter() { @@ -138,6 +177,89 @@ mod tests { } } + const CUSTOM: Address = address!("0x00000000000000000000000000000000000c0de0"); + const CALLER: Address = address!("0x00000000000000000000000000000000000ca11e"); + + /// A dynamic precompile that returns its own name for a flat price. + fn custom_precompile() -> DynPrecompile { + DynPrecompile::new(PrecompileId::Custom("custom".into()), |input| { + Ok(PrecompileOutput::new(1_234, Bytes::from_static(b"custom"), input.reservoir)) + }) + } + + fn evm_env() -> EvmEnv { + EvmEnv { + cfg_env: CfgEnv::new_with_spec(MegaSpecId::SATIN), + block_env: BlockEnv { gas_limit: 10_000_000, ..Default::default() }, + } + } + + /// A call from `CALLER` to `to`. + fn call(to: Address) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + gas_limit: 1_000_000, + ..Default::default() + })) + } + + /// The builder runs once per EVM, is handed the spec the EVM executes, and what it returns + /// answers a call to its address. + #[test] + fn test_dyn_precompiles_builder_receives_the_spec() { + static CALLS: AtomicUsize = AtomicUsize::new(0); + let factory = MegaEvmFactory::new().with_dyn_precompiles_builder(Arc::new(|spec| { + CALLS.fetch_add(1, Ordering::SeqCst); + assert_eq!(spec, MegaSpecId::SATIN, "the builder is handed the EVM's spec"); + HashMap::from_iter([(CUSTOM, custom_precompile())]) + })); + + let mut evm = factory.create_evm(MemoryDatabase::default(), evm_env()); + + assert_eq!(CALLS.load(Ordering::SeqCst), 1, "built once"); + let result = evm.transact_raw(call(CUSTOM)).unwrap().result; + assert_eq!(result.output().map(Bytes::as_ref), Some(b"custom".as_slice())); + + let (_db, _inspector, precompiles) = evm.components(); + assert!(precompiles.get(&CUSTOM).is_some(), "the builder's entry is in the set"); + for address in satin_precompiles().addresses() { + assert!(precompiles.get(address).is_some(), "{address} survived the addition"); + } + } + + /// Without a builder the EVM runs the Satin set and nothing else: the address answers as an + /// empty account. + #[test] + fn test_without_a_builder_the_set_is_the_satin_one() { + let mut evm = MegaEvmFactory::new().create_evm(MemoryDatabase::default(), evm_env()); + + let result = evm.transact_raw(call(CUSTOM)).unwrap().result; + assert!(result.is_success()); + assert_eq!(result.output().map(Bytes::as_ref), Some(b"".as_slice())); + + let (_db, _inspector, precompiles) = evm.components(); + assert!(precompiles.get(&CUSTOM).is_none()); + for address in satin_precompiles().addresses() { + assert!(precompiles.get(address).is_some(), "{address} is in the set"); + } + } + + /// A dynamic entry at an address the Satin set already holds replaces it. + #[test] + fn test_a_dyn_precompile_replaces_a_satin_entry() { + let kzg = crate::kzg_point_evaluation::ADDRESS; + let factory = MegaEvmFactory::new().with_dyn_precompiles_builder(Arc::new(move |_| { + HashMap::from_iter([(kzg, custom_precompile())]) + })); + + let mut evm = factory.create_evm(MemoryDatabase::default(), evm_env()); + + // Upstream's KZG refuses an empty input; the replacement answers it. + let result = evm.transact_raw(call(kzg)).unwrap().result; + assert_eq!(result.output().map(Bytes::as_ref), Some(b"custom".as_slice())); + } + #[test] fn test_create_evm_takes_the_external_envs_of_the_block() { let factory = MegaEvmFactory::new().with_external_env_factory(RecordingFactory::default()); diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index d398fa62f..e31f80d60 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -12,6 +12,7 @@ mod frame; mod host; mod inspector; mod instructions; +mod precompiles; mod prices; mod result; mod schedule; @@ -23,14 +24,18 @@ pub use factory::*; pub use frame::*; pub use host::*; pub use inspector::*; +pub use precompiles::*; pub use prices::*; pub use result::*; pub use schedule::*; pub use spec::*; -use alloy_evm::EvmEnv; +use alloy_evm::{ + precompiles::{DynPrecompile, PrecompilesMap}, + Database, EvmEnv, +}; use alloy_op_evm::map_op_err; -use op_revm::{precompiles::OpPrecompiles, OpHaltReason, OpTransactionError}; +use op_revm::{OpHaltReason, OpTransactionError}; use revm::{ context::{ result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, @@ -44,9 +49,9 @@ use revm::{ NoOpInspector, }, interpreter::interpreter::EthInterpreter, - primitives::{Address, Bytes}, + primitives::{Address, Bytes, HashMap}, state::EvmState, - Database, DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, + DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, }; use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; @@ -57,12 +62,13 @@ pub(crate) type MegaInstructions = /// The revm EVM a [`MegaEvm`] wraps. /// -/// It runs op-revm's precompile set for the base spec until the Satin precompile set lands. +/// It runs the Satin precompile set, carried as an alloy-evm map so a node can add its own +/// entries (see the `precompiles` module). pub(crate) type MegaInnerEvm = revm::context::Evm< MegaContext, INSP, MegaInstructions, - OpPrecompiles, + PrecompilesMap, EthFrame, >; @@ -90,7 +96,7 @@ impl MegaEvm MegaEvm { self.inspect } + /// Adds `dyn_precompiles` on top of the Satin set, replacing an entry whose address is + /// already taken. + /// + /// A node's RPC builds these; the chain's own set is the one [`MegaEvm::new`] installs. + pub fn with_dyn_precompiles( + mut self, + dyn_precompiles: HashMap, + ) -> Self { + for (address, dyn_precompile) in dyn_precompiles { + self.inner.precompiles.apply_precompile(&address, move |_| Some(dyn_precompile)); + } + self + } + /// Consumes the EVM and returns the revm EVM it wraps. pub(crate) fn into_inner(self) -> MegaInnerEvm { self.inner @@ -315,7 +335,7 @@ where impl alloy_evm::Evm for MegaEvm where - DB: alloy_evm::Database, + DB: Database, INSP: Inspector, EthInterpreter>, ExtEnvs: ExternalEnvTypes, { @@ -325,12 +345,8 @@ where type HaltReason = OpHaltReason; type Spec = MegaSpecId; type BlockEnv = BlockEnv; - /// op-revm's precompile set for the base spec. - /// - /// Provisional: the Satin precompile provider replaces this type when it lands, and code that - /// names `OpPrecompiles` through this associated type has no source-compatibility promise - /// across that change. - type Precompiles = OpPrecompiles; + /// The Satin precompile set, with whatever a node added to it. + type Precompiles = PrecompilesMap; type Inspector = INSP; fn block(&self) -> &BlockEnv { diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs new file mode 100644 index 000000000..55dbfb382 --- /dev/null +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -0,0 +1,285 @@ +//! The precompile set of the Satin engine. +//! +//! Satin runs op-revm's Karst set — the Osaka `ModExp` schedule, `P256VERIFY` at 6,900, the BN254 +//! pairing bounded at 57,600 bytes of input — with one entry replaced: KZG point evaluation costs +//! [`kzg_point_evaluation::GAS_COST`] instead of upstream's 50,000, because verifying a proof is +//! far more work than that price buys on a `MegaETH` sequencer. +//! +//! The set is handed to the EVM as an alloy-evm [`PrecompilesMap`], so a node can add or replace +//! an address at runtime ([`DynPrecompilesBuilder`]). A map built from the static set looks the +//! address up in the same table op-revm would, so carrying it costs no allocation per call. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{string::String, sync::Arc}; + +use alloy_evm::{ + precompiles::{DynPrecompile, PrecompilesMap}, + Database, +}; +use revm::{ + handler::PrecompileProvider, + interpreter::{CallInputs, InterpreterResult}, + precompile::Precompiles, + primitives::{Address, AddressSet, HashMap, OnceLock}, +}; + +use crate::{ExternalEnvTypes, MegaContext, MegaInnerContext, MegaSpecId}; + +/// The Satin precompile set: op-revm's Karst set with `MegaETH`'s KZG price. +pub fn satin_precompiles() -> &'static Precompiles { + static INSTANCE: OnceLock = OnceLock::new(); + INSTANCE.get_or_init(|| { + let mut precompiles = op_revm::precompiles::karst().clone(); + precompiles.extend([kzg_point_evaluation::KZG_POINT_EVALUATION]); + precompiles + }) +} + +/// A precompile map carrying the Satin set, ready for a node to add its own entries to. +pub fn satin_precompiles_map() -> PrecompilesMap { + PrecompilesMap::from_static(satin_precompiles()) +} + +/// Builds the dynamic precompiles an EVM runs on top of the Satin set. +/// +/// The spec is passed so a builder can key on it; Satin is a single spec, so it is always +/// [`MegaSpecId::SATIN`] today. +pub type DynPrecompilesBuilder = + Arc HashMap + Send + Sync>; + +/// KZG point evaluation at `MegaETH`'s price. +pub mod kzg_point_evaluation { + use revm::{ + precompile::{ + Precompile, PrecompileHalt, PrecompileId, PrecompileOutput, PrecompileResult, + }, + primitives::Address, + }; + + /// Address of the KZG point evaluation precompile, as upstream has it. + pub const ADDRESS: Address = revm::precompile::kzg_point_evaluation::ADDRESS; + + /// What a KZG point evaluation costs on `MegaETH`: a flat price, as upstream's is, twice + /// upstream's 50,000. + pub const GAS_COST: u64 = 100_000; + + /// Runs upstream's KZG point evaluation and reports [`GAS_COST`] for it. + /// + /// The gas check comes first, so a call that cannot pay the `MegaETH` price is out of gas + /// before any verification runs, exactly as upstream is out of gas below its own price. + fn run_with_fixed_cost(input: &[u8], gas_limit: u64, reservoir: u64) -> PrecompileResult { + if gas_limit < GAS_COST { + return Ok(PrecompileOutput::halt(PrecompileHalt::OutOfGas, reservoir)); + } + Ok(match revm::precompile::kzg_point_evaluation::run(input, gas_limit) { + Ok(output) => PrecompileOutput::new(GAS_COST, output.bytes, reservoir), + Err(halt) => PrecompileOutput::halt(halt, reservoir), + }) + } + + /// KZG point evaluation, priced at [`GAS_COST`]. + pub const KZG_POINT_EVALUATION: Precompile = + Precompile::new(PrecompileId::KzgPointEvaluation, ADDRESS, run_with_fixed_cost); +} + +/// Runs the Satin precompile set on a [`MegaContext`]. +/// +/// alloy-evm implements the provider for revm's plain context; every method here hands it the +/// context [`MegaContext`] wraps, which is that context. +impl PrecompileProvider> + for PrecompilesMap +{ + type Output = InterpreterResult; + + /// The table is already the Satin one; the engine has a single spec, so nothing can change + /// it. Rebuilding from the base spec would drop the `MegaETH` entries and a node's own. + #[inline] + fn set_spec(&mut self, _spec: op_revm::OpSpecId) -> bool { + false + } + + #[inline] + fn run( + &mut self, + context: &mut MegaContext, + inputs: &CallInputs, + ) -> Result, String> { + PrecompileProvider::>::run(self, &mut context.inner, inputs) + } + + #[inline] + fn warm_addresses(&self) -> &AddressSet { + PrecompileProvider::>::warm_addresses(self) + } + + #[inline] + fn contains(&self, address: &Address) -> bool { + PrecompileProvider::>::contains(self, address) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::MemoryDatabase; + use alloy_primitives::{hex, Bytes}; + use op_revm::precompiles::bn254_pair::KARST_MAX_INPUT_SIZE; + use revm::{ + interpreter::{CallInput, CallScheme, CallValue, InstructionResult}, + precompile::secp256r1, + primitives::U256, + }; + + /// The c-kzg test vector `verify_kzg_proof_case_correct_proof_4_4`, as the precompile takes + /// it: `versioned_hash ++ z ++ y ++ commitment ++ proof`. + fn kzg_input() -> Bytes { + let commitment = hex!( + "8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca2\ + 5f26936857bc3a7c2539ea8ec3a952b7" + ); + let mut versioned_hash = + revm::precompile::kzg_point_evaluation::kzg_to_versioned_hash(commitment.as_slice()) + .to_vec(); + let z = hex!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000").to_vec(); + let y = hex!("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9").to_vec(); + let proof = hex!( + "a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc216074\ + 4faf0070725e00b60ad9a026a15b1a8c" + ); + versioned_hash.extend_from_slice(&z); + versioned_hash.extend_from_slice(&y); + versioned_hash.extend_from_slice(&commitment); + versioned_hash.extend_from_slice(&proof); + Bytes::from(versioned_hash) + } + + /// What upstream returns from a successful evaluation: the field parameters. + const KZG_RETURN_VALUE: &[u8; 64] = revm::precompile::kzg_point_evaluation::RETURN_VALUE; + + fn inputs(to: Address, input: Bytes, gas_limit: u64) -> CallInputs { + CallInputs { + input: CallInput::Bytes(input), + return_memory_offset: 0..0, + gas_limit, + reservoir: 0, + bytecode_address: to, + known_bytecode: Default::default(), + target_address: to, + caller: Address::ZERO, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: false, + } + } + + /// Runs `input` against the precompile at `to` and returns its result. + fn run(to: Address, input: Bytes, gas_limit: u64) -> InterpreterResult { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::SATIN); + satin_precompiles_map() + .run(&mut context, &inputs(to, input, gas_limit)) + .expect("the precompile does not fail fatally") + .expect("the address is a precompile") + } + + /// A valid proof costs the `MegaETH` price and returns the field parameters. + #[test] + fn test_kzg_precompile_sufficient_gas() { + let result = run(kzg_point_evaluation::ADDRESS, kzg_input(), 200_000); + assert_eq!(result.result, InstructionResult::Return); + assert_eq!(result.gas.total_gas_spent(), kzg_point_evaluation::GAS_COST); + assert_eq!(result.output.as_ref(), KZG_RETURN_VALUE.as_slice()); + } + + /// The price is exactly payable at the price itself. + #[test] + fn test_kzg_precompile_exact_gas_limit() { + let result = + run(kzg_point_evaluation::ADDRESS, kzg_input(), kzg_point_evaluation::GAS_COST); + assert_eq!(result.result, InstructionResult::Return); + assert_eq!(result.gas.total_gas_spent(), kzg_point_evaluation::GAS_COST); + assert_eq!(result.output.as_ref(), KZG_RETURN_VALUE.as_slice()); + } + + /// Below the `MegaETH` price the call is out of gas, including at upstream's price, which + /// would have been enough before the override. + #[test] + fn test_kzg_precompile_insufficient_gas() { + for gas_limit in [0, 50_000, kzg_point_evaluation::GAS_COST - 1] { + let result = run(kzg_point_evaluation::ADDRESS, kzg_input(), gas_limit); + assert_eq!(result.result, InstructionResult::PrecompileOOG, "at {gas_limit} gas"); + } + } + + /// The `MegaETH` entry replaces upstream's rather than sitting beside it: the set holds one + /// KZG precompile, at the same address, and the price it charges is `MegaETH`'s. + #[test] + fn test_the_kzg_entry_replaces_upstreams() { + let satin = satin_precompiles(); + let karst = op_revm::precompiles::karst(); + assert_eq!(satin.len(), karst.len(), "no address was added"); + assert!(satin.contains(&kzg_point_evaluation::ADDRESS)); + assert_ne!( + kzg_point_evaluation::GAS_COST, + revm::precompile::kzg_point_evaluation::GAS_COST, + "the price is not upstream's" + ); + } + + /// Every other Karst entry is op-revm's, at the address op-revm has it. + #[test] + fn test_every_other_entry_is_the_karst_one() { + let satin = satin_precompiles(); + for address in op_revm::precompiles::karst().addresses() { + assert!(satin.contains(address), "{address} is missing"); + } + } + + /// `P256VERIFY` is priced at the Osaka fee, which is what Karst put in the set. + #[test] + fn test_p256_verify_is_priced_at_the_osaka_fee() { + assert_eq!(secp256r1::P256VERIFY_BASE_GAS_FEE_OSAKA, 6_900); + let address = *secp256r1::P256VERIFY_OSAKA.address(); + // An all-zero input is a well-formed 160-byte call whose signature does not verify: it + // returns empty output and still pays the base fee. + let result = run(address, Bytes::from(std::vec![0u8; 160]), 100_000); + assert_eq!(result.result, InstructionResult::Return); + assert_eq!(result.gas.total_gas_spent(), 6_900); + assert!(result.output.is_empty(), "the signature does not verify"); + } + + /// The BN254 pairing takes input up to the Karst bound and refuses one byte more, without + /// charging for the work it did not do. + #[test] + fn test_bn254_pairing_is_bounded_at_the_karst_size() { + assert_eq!(KARST_MAX_INPUT_SIZE, 57_600); + let address = *op_revm::precompiles::bn254_pair::KARST.address(); + // At the bound the input is a whole number of pair elements of zeros, which pair to the + // identity: the call succeeds and pays the Istanbul pairing price. + let at_bound = run(address, Bytes::from(std::vec![0u8; KARST_MAX_INPUT_SIZE]), 50_000_000); + assert_eq!(at_bound.result, InstructionResult::Return); + assert!(at_bound.gas.total_gas_spent() > 0); + + let over = run(address, Bytes::from(std::vec![0u8; KARST_MAX_INPUT_SIZE + 1]), 50_000_000); + assert_eq!(over.result, InstructionResult::PrecompileError); + } + + /// `ModExp` runs on the Osaka formula, which prices a small exponentiation well above the + /// 200-gas Berlin minimum the earlier entry charged. + #[test] + fn test_modexp_is_priced_on_the_osaka_formula() { + let address = *revm::precompile::modexp::OSAKA.address(); + // base = 3 (1 byte), exponent = 2 (1 byte), modulus = 5 (1 byte): 3^2 mod 5 = 4. + let mut input = std::vec![0u8; 96]; + input[31] = 1; + input[63] = 1; + input[95] = 1; + input.extend_from_slice(&[3, 2, 5]); + let result = run(address, Bytes::from(input), 100_000); + assert_eq!(result.result, InstructionResult::Return); + assert_eq!(result.output.as_ref(), &[4]); + assert_eq!(result.gas.total_gas_spent(), 500, "the Osaka minimum"); + } +} diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index c5a8fef10..6f94ee927 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -14,7 +14,7 @@ #[cfg(not(feature = "std"))] use alloc as std; use core::{fmt, str::FromStr}; -use std::string::String; +use std::{format, string::String}; use crate::constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}; From 289f9f17854f10287415f403fe2b017b04618b58 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:09:55 +0800 Subject: [PATCH 095/201] feat(block): run the pre-block and post-block calls as state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the calls a block makes around its transactions: the EIP-2935 block hashes call, the EIP-4788 beacon root call, and the post-block balance increments. Each helper runs its call and hands back the state it produced, and none of them commits — the node's witness generator has to see the read and write set of every step, which a helper committing straight to the database would hide. Ports the parked row of the pre-block call helpers. --- crates/mega-evm/src/block/eips.rs | 210 ++++++++++++++++++ crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/tests/_pending/README.md | 10 +- .../mega-evm/tests/_pending/src/block/eips.rs | 92 -------- 4 files changed, 217 insertions(+), 97 deletions(-) create mode 100644 crates/mega-evm/src/block/eips.rs delete mode 100644 crates/mega-evm/tests/_pending/src/block/eips.rs diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs new file mode 100644 index 000000000..8b3a2ef09 --- /dev/null +++ b/crates/mega-evm/src/block/eips.rs @@ -0,0 +1,210 @@ +//! The pre-block and post-block calls a block makes before and after its transactions. +//! +//! Each helper runs the call and hands back the state it produced; none of them commits. A +//! node's witness generator needs to see the read and write set of every step of block +//! execution, and a helper that committed straight to the database would hide its own. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{boxed::Box, string::ToString}; + +use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; +use alloy_evm::{ + block::{BlockExecutionError, BlockValidationError}, + Evm, +}; +use alloy_hardforks::EthereumHardforks; +use alloy_primitives::{Address, B256, U256}; +use revm::{ + context::{result::ResultAndState, Block}, + database::State, + state::{Account, EvmState}, + Database, +}; + +/// The caller every pre-block system call runs as. +pub use alloy_eips::eip4788::SYSTEM_ADDRESS; + +/// Runs the pre-block call to the [EIP-2935] block hashes contract. +/// +/// Answers `None`, having run nothing, when Prague is not active or the block is the genesis +/// block, where EIP-2935 makes no call. The state is not committed. +/// +/// [EIP-2935]: https://eips.ethereum.org/EIPS/eip-2935 +pub fn transact_blockhashes_contract_call( + hardforks: H, + parent_block_hash: B256, + evm: &mut E, +) -> Result>, BlockExecutionError> { + if !hardforks.is_prague_active_at_timestamp(evm.block().timestamp().saturating_to()) { + return Ok(None); + } + + // The genesis block has no parent to record. + if evm.block().number().is_zero() { + return Ok(None); + } + + evm.transact_system_call(SYSTEM_ADDRESS, HISTORY_STORAGE_ADDRESS, parent_block_hash.0.into()) + .map(Some) + .map_err(|e| BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) +} + +/// Runs the pre-block call to the [EIP-4788] beacon block root contract. +/// +/// Answers `None`, having run nothing, when Cancun is not active or the block is the genesis +/// block, where EIP-4788 makes no call and requires a zero root. The state is not committed. +/// +/// [EIP-4788]: https://eips.ethereum.org/EIPS/eip-4788 +pub fn transact_beacon_root_contract_call( + hardforks: H, + parent_beacon_block_root: Option, + evm: &mut E, +) -> Result>, BlockExecutionError> { + if !hardforks.is_cancun_active_at_timestamp(evm.block().timestamp().saturating_to()) { + return Ok(None); + } + + let parent_beacon_block_root = + parent_beacon_block_root.ok_or(BlockValidationError::MissingParentBeaconBlockRoot)?; + + if evm.block().number().is_zero() { + if !parent_beacon_block_root.is_zero() { + return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { + parent_beacon_block_root, + } + .into()); + } + return Ok(None); + } + + evm.transact_system_call( + SYSTEM_ADDRESS, + BEACON_ROOTS_ADDRESS, + parent_beacon_block_root.0.into(), + ) + .map(Some) + .map_err(|e| { + BlockValidationError::BeaconRootContractCall { + parent_beacon_block_root: Box::new(parent_beacon_block_root), + message: e.to_string(), + } + .into() + }) +} + +/// The state that applying `balances` to `db` would produce. Nothing is committed. +/// +/// Equivalent to revm's own `increment_balances`, in state rather than in place: committing what +/// this returns leaves the same accounts, balances and account statuses behind, and a witness +/// generator gets to see the delta in between. +pub fn transact_balance_increments( + balances: impl IntoIterator, + db: &mut State, +) -> Result, DB::Error> { + let mut state = EvmState::default(); + + for (address, balance_increment) in balances { + if balance_increment == 0 { + continue; + } + let cache_account = db.load_cache_account(address)?; + let account_info = cache_account.account_info().unwrap_or_default(); + let mut account = Account::default().with_info(account_info); + account.info.balance += U256::from(balance_increment); + account.mark_touch(); + state.insert(address, account); + } + + Ok(Some(state)) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::address; + use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; + use std::vec; + + #[test] + fn test_balance_increment_commit_equivalence() { + // The property that matters: this is equivalent to revm's `increment_balances`, which + // the block executor would otherwise call in place. + + let addr1 = address!("0x1000000000000000000000000000000000000001"); + let addr2 = address!("0x2000000000000000000000000000000000000002"); + let addr3 = address!("0x3000000000000000000000000000000000000003"); + + // Fund only addr1 and addr2, but leave addr3 empty (non-existent) + let setup_db = |db: &mut InMemoryDB| { + for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { + db.insert_account_info( + addr, + AccountInfo { balance: U256::from(balance), nonce, ..Default::default() }, + ); + } + }; + + let mut db1 = InMemoryDB::default(); + setup_db(&mut db1); + let mut state1 = State::builder().with_database(&mut db1).build(); + + let mut db2 = InMemoryDB::default(); + setup_db(&mut db2); + let mut state2 = State::builder().with_database(&mut db2).build(); + + let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; + + // In place, as revm does it. + revm::database_interface::DatabaseCommitExt::increment_balances( + &mut state1, + balance_increments.clone(), + ) + .expect("increment_balances should succeed"); + + // As state, then committed: the commit is what applies the status transitions, so the + // two paths must land on the same accounts. + let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) + .expect("transact_balance_increments should succeed") + .expect("Should return state"); + state2.commit(result_state); + + for (addr, _expected_increment) in balance_increments { + let account1 = state1.load_cache_account(addr).expect("Should load from state1"); + let account2 = state2.load_cache_account(addr).expect("Should load from state2"); + + let info1 = account1.account_info().expect("Should have account info"); + let info2 = account2.account_info().expect("Should have account info"); + + assert_eq!( + info1.balance, info2.balance, + "Balance for {addr:?} should be identical after both methods" + ); + assert_eq!(info1.nonce, info2.nonce, "Nonce for {addr:?} should be identical"); + assert_eq!( + info1.code_hash, info2.code_hash, + "Code hash for {addr:?} should be identical" + ); + assert_eq!( + account1.status, account2.status, + "Account status for {addr:?} should be identical after both methods" + ); + } + } + + /// A zero increment is not a touch: it leaves no account in the state at all. + #[test] + fn test_zero_increments_leave_no_account_behind() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let produced = transact_balance_increments( + [(address!("0x1000000000000000000000000000000000000001"), 0u128)], + &mut state, + ) + .expect("no database error") + .expect("Should return state"); + + assert!(produced.is_empty()); + } +} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 3e4be9204..4016c9a56 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -1,6 +1,7 @@ //! Block-level pieces of the Satin engine. mod chain; +mod eips; mod executor; mod hardfork; mod helpers; @@ -8,6 +9,7 @@ mod limit; mod result; pub use chain::*; +pub use eips::*; pub use executor::*; pub use hardfork::*; pub use helpers::*; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index d6ad5750e..f076a18f2 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,10 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 24 | 23 | 1 | 19 | 5 | 0 | +| the block executor | 23 | 23 | 0 | 18 | 5 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **718** | **624** | **94** | **406** | **284** | **28** | +| **Total** | **717** | **624** | **93** | **405** | **284** | **28** | ## Tests ported in place @@ -132,18 +132,19 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by the block executor -These 29 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 30 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| | `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | +| `src/block/eips.rs` | the block executor (1) | 1 | `src/block/eips.rs` | | `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | | `src/block/helpers.rs` | the block executor (3) | 3 | `src/block/helpers.rs` | | `src/block/limit.rs` | the block executor (5) | 5 | `src/block/limit.rs` | | `src/block/result.rs` | the block executor (2) | 2 | `src/block/result.rs` | | `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | -| **Total** | | **29** | | +| **Total** | | **30** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -232,7 +233,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | -| `src/block/eips.rs` | 1 | keep 1 (the block executor) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | diff --git a/crates/mega-evm/tests/_pending/src/block/eips.rs b/crates/mega-evm/tests/_pending/src/block/eips.rs deleted file mode 100644 index 0bba32f6f..000000000 --- a/crates/mega-evm/tests/_pending/src/block/eips.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/block/eips.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/eips.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; - - #[test] - fn test_balance_increment_commit_equivalence() { - // This is the most important test: verify that our approach is equivalent - // to the original increment_balances + balance_increment_state approach - - // Setup: create two identical database states - let addr1 = address!("0x1000000000000000000000000000000000000001"); - let addr2 = address!("0x2000000000000000000000000000000000000002"); - let addr3 = address!("0x3000000000000000000000000000000000000003"); - - // Fund only addr1 and addr2, but leave addr3 empty (non-existent) - let setup_db = |db: &mut InMemoryDB| { - for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { - db.insert_account_info( - addr, - AccountInfo { - balance: U256::from(balance), - nonce, - code_hash: alloy_primitives::B256::ZERO, - code: None, - }, - ); - } - }; - - // Setup database 1: will use original approach (increment_balances) - let mut db1 = InMemoryDB::default(); - setup_db(&mut db1); - let mut state1 = State::builder().with_database(&mut db1).build(); - - // Setup database 2: will use our approach (transact_balance_increments + commit) - let mut db2 = InMemoryDB::default(); - setup_db(&mut db2); - let mut state2 = State::builder().with_database(&mut db2).build(); - - // Apply balance increments - let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; - - // Method 1: Original approach - state1 - .increment_balances(balance_increments.clone()) - .expect("increment_balances should succeed"); - - // Method 2: Refactored approach (transact + commit, matching the actual usage pattern) - // The refactoring separates increment_balances into two steps: - // 1. transact_balance_increments() - produces EvmState delta - // 2. commit() - integrates the delta and fixes status transitions - // This allows extracting the intermediate state for system_caller.on_state() hooks - let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) - .expect("transact_balance_increments should succeed") - .expect("Should return state"); - - // Commit the state changes (this applies proper status transitions via apply_evm_state) - state2.commit(result_state); - - // Verify final states match after both approaches - for (addr, _expected_increment) in balance_increments { - let account1 = state1.load_cache_account(addr).expect("Should load from state1"); - let account2 = state2.load_cache_account(addr).expect("Should load from state2"); - - let info1 = account1.account_info().expect("Should have account info"); - let info2 = account2.account_info().expect("Should have account info"); - - assert_eq!( - info1.balance, info2.balance, - "Balance for {:?} should be identical after both methods", - addr - ); - assert_eq!(info1.nonce, info2.nonce, "Nonce for {:?} should be identical", addr); - assert_eq!( - info1.code_hash, info2.code_hash, - "Code hash for {:?} should be identical", - addr - ); - assert_eq!( - account1.status, account2.status, - "Account status for {:?} should be identical after both methods", - addr - ); - } - } -} From 6dc3c7bf70751716c707fd7f2900e4cc06b4978a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:16:52 +0800 Subject: [PATCH 096/201] feat(block): execute a block on the Satin engine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, and `MegaBlockExecutorFactory` is what a node builds one from. Both mirror alloy-op-evm's shape for an OP chain, with the rules the Karst base brings and the counters the common execution layer defines. The three block rules: - A block in which a fork activates admits only deposit transactions. The caller sets the flag from the chain's schedule (`admits_only_deposits`), and a user transaction in such a block is refused before it executes. - A non-deposit transaction's data-availability footprint is its compressed size times the footprint gas scalar the L1 block contract holds, accumulated against the block's gas limit and reported as the block's blob gas used. The scalar is read per transaction, as the fork states the rule: the block's own L1 info transaction may set it. With no scalar in state it is zero and the rule costs nothing. - The L1 block info is read once, at the start of the block. An empty L1 block contract reads as zeroes rather than as an error, and a caller that placed its own info for this block keeps it — the read is conditioned exactly as op-revm's handler conditions its own, so the two never disagree. The executor fills the block's three gas ledgers from every transaction, and `finish_with_counters` reports them beside the receipts; the header's gas used keeps its meaning as the sum of the receipts. A rewriting inspector cannot reach a block: `apply_pre_execution_changes` refuses one, and the factory's trusted-inspector constructor is the only way an inspected transaction is executed in a block. `apply_pre_execution_changes` names two hook points that are empty today: system contract deployment and the pre-block system calls. --- crates/mega-evm/src/block/executor.rs | 543 +++++++++++++++++++++++++- crates/mega-evm/src/block/factory.rs | 122 ++++++ crates/mega-evm/src/block/hardfork.rs | 28 ++ crates/mega-evm/src/block/mod.rs | 2 + crates/mega-evm/src/block/result.rs | 126 +++++- crates/mega-evm/src/evm/mod.rs | 20 + crates/mega-evm/src/lib.rs | 4 +- 7 files changed, 827 insertions(+), 18 deletions(-) create mode 100644 crates/mega-evm/src/block/factory.rs diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index cd65aa3bc..5a9e8c8c9 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -1,23 +1,184 @@ //! Block executor of the Satin engine. //! -//! Block execution lands here with the block executor: alloy-evm's `BlockExecutor` over a -//! [`MegaEvm`](crate::MegaEvm), the Karst block rules, the pre-block system calls and -//! system contract deployments, and the block-level limits. +//! [`MegaBlockExecutor`] is alloy-evm's [`BlockExecutor`] over a [`MegaEvm`]: it runs the block's +//! transactions, holds them to the block's limits, builds their receipts and counts what the +//! block spent on each of the three gas ledgers. +//! +//! # The block rules of the Karst base +//! +//! - **An activation block admits only deposits.** The caller sets +//! [`no_user_tx_activation_block`](MegaBlockExecutionCtx::no_user_tx_activation_block) from the +//! chain's schedule ([`MegaHardforks::admits_only_deposits`]), and a user transaction in such a +//! block is refused before it executes. This mirrors alloy-op-evm's flag of the same name. +//! - **The data-availability footprint is a block limit.** Each non-deposit transaction's footprint +//! is its compressed size times the footprint gas scalar the L1 block contract holds, accumulated +//! against the block's gas limit and reported as the block's blob gas used. With no scalar in +//! state the scalar is zero and the rule costs nothing. This mirrors alloy-op-evm's Jovian DA +//! footprint block limit. +//! - **The L1 block info is read once, at the start of the block.** An empty L1 block contract +//! reads as zeroes, not as an error, and a caller that placed its own info for this block keeps +//! it. This mirrors alloy-op-evm's `l1_block_info`. +//! +//! # What later mechanisms fill in +//! +//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) names two hook +//! points that are empty today: system contract deployment, and the pre-block system calls. -/// Executes the transactions of one block on a Satin EVM. +#[cfg(not(feature = "std"))] +use alloc as std; +use core::fmt; +use std::{boxed::Box, vec::Vec}; + +use alloy_consensus::{Eip658Value, Header, Transaction, TransactionEnvelope, TxReceipt}; +use alloy_eips::{eip7685::Requests, Encodable2718, Typed2718}; +use alloy_evm::{ + block::{ + state_changes::post_block_balance_increments, BlockExecutionError, BlockExecutionResult, + BlockExecutor, CommitChanges, ExecutableTx, GasOutput, StateDB, + }, + eth::receipt_builder::ReceiptBuilderCtx, + Database, Evm, FromRecoveredTx, FromTxWithEncoded, RecoveredTx, +}; +use alloy_op_evm::block::{receipt_builder::OpReceiptBuilder, OpTxEnv}; +use alloy_primitives::{Bytes, B256}; +use op_alloy_consensus::OpDepositReceipt; +use op_revm::{ + constants::L1_BLOCK_CONTRACT, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, +}; +use revm::{ + context::{result::ResultAndState, Block, ContextTr}, + database::DatabaseCommitExt, + state::EvmState, + DatabaseCommit, Inspector, +}; + +/// What [`MegaBlockExecutor::finish_with_counters`] hands back: the EVM the block ran on, and +/// what the block produced and counted. +pub type MegaFinishedBlock = + (MegaEvm, MegaBlockExecutionResult<::Receipt>); + +use crate::{ + block::eips, estimated_da_size, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, + MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, + MegaTransaction, +}; + +/// What the node hands block execution beside the EVM. /// -/// A skeleton for now: it owns the EVM and hands it back. -#[derive(Debug)] -pub struct MegaBlockExecutor { - evm: E, +/// It carries what the pre-block calls need (the parent hash and the parent beacon block root, as +/// alloy-op-evm does), the block's own extra data, the activation-block flag and the limits the +/// block holds its transactions to. +#[derive(Clone, Debug, Default)] +pub struct MegaBlockExecutionCtx { + /// The parent block's hash, which the EIP-2935 pre-block call records. + pub parent_hash: B256, + /// The parent block's beacon block root, which the EIP-4788 pre-block call records. + pub parent_beacon_block_root: Option, + /// The block's extra data. + pub extra_data: Bytes, + /// Whether this block admits only deposit transactions because a fork activates in it. + /// + /// The caller sets it from the chain's schedule with + /// [`MegaHardforks::admits_only_deposits`], which needs the parent block's timestamp; `false` + /// skips the rule. + pub no_user_tx_activation_block: bool, + /// The limits this block holds its transactions to. + pub block_limits: BlockLimits, +} + +impl MegaBlockExecutionCtx { + /// A context for a block that activates no fork. + pub const fn new( + parent_hash: B256, + parent_beacon_block_root: Option, + extra_data: Bytes, + block_limits: BlockLimits, + ) -> Self { + Self { + parent_hash, + parent_beacon_block_root, + extra_data, + no_user_tx_activation_block: false, + block_limits, + } + } + + /// Marks this block one that admits only deposit transactions. + pub const fn with_no_user_tx_activation_block(mut self, activation_block: bool) -> Self { + self.no_user_tx_activation_block = activation_block; + self + } +} + +/// A block this engine refuses to execute. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MegaBlockExecutionError { + /// A block that activates a fork carries a transaction that is not a deposit. + UnexpectedNonDepositTxInActivationBlock, + /// A transaction's data-availability footprint does not fit in what the block has left. + TransactionDaFootprintAboveGasLimit { + /// The footprint of the transaction that does not fit. + transaction_da_footprint: u64, + /// The footprint the block has left. + available_block_da_footprint: u64, + }, + /// The EVM runs an inspector that may rewrite what execution produces, which block execution + /// does not admit. + RewritingInspector, } -impl MegaBlockExecutor { - /// Creates an executor that runs the block on `evm`. - pub const fn new(evm: E) -> Self { - Self { evm } +impl fmt::Display for MegaBlockExecutionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnexpectedNonDepositTxInActivationBlock => { + f.write_str("unexpected non-deposit transaction in fork activation block") + } + Self::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint, + available_block_da_footprint, + } => write!( + f, + "transaction DA footprint exceeds available block DA footprint. \ + transaction_da_footprint: {transaction_da_footprint}, \ + available_block_da_footprint: {available_block_da_footprint}" + ), + Self::RewritingInspector => f.write_str( + "block execution does not admit an inspector that may rewrite execution", + ), + } } +} + +impl core::error::Error for MegaBlockExecutionError {} + +impl From for BlockExecutionError { + fn from(error: MegaBlockExecutionError) -> Self { + Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) + } +} +/// Executes the transactions of one block on a Satin EVM. +#[derive(Debug)] +pub struct MegaBlockExecutor { + /// The chain's hardfork schedule. + pub spec: Spec, + /// The receipt builder. + pub receipt_builder: R, + /// What the node handed this block. + pub ctx: MegaBlockExecutionCtx, + /// The EVM the block runs on. + pub evm: E, + /// The receipts of the transactions committed so far. + pub receipts: Vec, + /// What the block has used, and the limits it is held to. + pub limiter: BlockLimiter, + /// Whether Canyon is active, which decides whether a deposit receipt carries a version. + is_canyon: bool, + /// Whether Regolith is active, which decides whether a deposit receipt carries a nonce. + is_regolith: bool, +} + +impl MegaBlockExecutor { /// The EVM the block runs on. pub const fn evm(&self) -> &E { &self.evm @@ -32,12 +193,360 @@ impl MegaBlockExecutor { pub fn into_evm(self) -> E { self.evm } + + /// What the block has used, and the limits it is held to. + pub const fn limiter(&self) -> &BlockLimiter { + &self.limiter + } + + /// The gas the block's transactions have spent so far, by ledger. + pub const fn gas(&self) -> &BlockGasCounters { + &self.limiter.gas + } +} + +impl MegaBlockExecutor { + /// Creates an executor that runs `ctx`'s block on `evm`. + /// + /// The block's gas limit comes from the block environment, whatever `ctx` carries: it is the + /// number consensus holds the block to, and it is also the budget the data-availability + /// footprint of the block's transactions is held to. + pub fn new(evm: E, ctx: MegaBlockExecutionCtx, spec: Spec, receipt_builder: R) -> Self { + let timestamp = evm.block().timestamp().saturating_to(); + let limits = ctx.block_limits.with_block_gas_limit(evm.block().gas_limit()); + Self { + is_canyon: spec.is_canyon_active_at_timestamp(timestamp), + is_regolith: spec.is_regolith_active_at_timestamp(timestamp), + spec, + receipt_builder, + ctx, + evm, + receipts: Vec::new(), + limiter: limits.to_block_limiter(), + } + } +} + +impl MegaBlockExecutor, R, Spec> +where + DB: Database + DatabaseCommit, + INSP: Inspector>, + ExtEnvs: ExternalEnvTypes, + R: OpReceiptBuilder, + Spec: MegaHardforks, +{ + /// The inspector the EVM runs. + pub const fn inspector(&self) -> &INSP { + self.evm.inspector() + } + + /// Reads the L1 block info of this block from state, unless the EVM already carries the info + /// of this very block. + /// + /// An empty L1 block contract reads as zeroes — no fee scalars, no data-availability + /// footprint scalar — which is a chain that has not set them, not an error. A caller that + /// placed its own info for this block number keeps it: this is the same condition op-revm's + /// handler reloads on, so the two never disagree about which info the block runs with. + fn load_l1_block_info(&mut self) -> Result<(), BlockExecutionError> { + let block_number = self.evm.block().number(); + if self.evm.ctx().chain().l2_block == Some(block_number) { + return Ok(()); + } + let spec = self.evm.ctx().cfg().spec; + let info = L1BlockInfo::try_fetch(self.evm.ctx_mut().db_mut(), block_number, spec) + .map_err(BlockExecutionError::other)?; + self.evm.ctx_mut().modify_chain(|chain| *chain = info); + Ok(()) + } + + /// The data-availability footprint gas scalar the L1 block contract holds. + /// + /// Read per transaction, as the fork's rule is stated: the block's own L1 info transaction + /// may set it, and the transactions after it are held to the value it set. + fn da_footprint_gas_scalar(&mut self) -> Result { + // Load the L1 block account into the cache first; a database that has never seen it + // cannot serve its storage. + let db = self.evm.ctx_mut().db_mut(); + db.basic(L1_BLOCK_CONTRACT).map_err(BlockExecutionError::other)?; + L1BlockInfo::fetch_da_footprint_gas_scalar(db) + .map(u64::from) + .map_err(BlockExecutionError::other) + } + + /// Commits `state` to the database. + fn commit(&mut self, state: EvmState) { + self.evm.ctx_mut().db_mut().commit(state); + } +} + +impl BlockExecutor + for MegaBlockExecutor, R, Spec> +where + DB: Database + StateDB, + INSP: Inspector>, + ExtEnvs: ExternalEnvTypes, + R: OpReceiptBuilder, + Spec: MegaHardforks, + MegaTransaction: FromRecoveredTx + FromTxWithEncoded, +{ + type Transaction = R::Transaction; + type Receipt = R::Receipt; + type Evm = MegaEvm; + type Result = MegaBlockTxResult<::TxType>; + + /// Runs what a block does before its transactions. + /// + /// In order: the admission gate, the EIP-2935 and EIP-4788 pre-block calls, and the read of + /// the L1 block info. Each call's state is committed here rather than inside its helper, so + /// a witness generator sees every step's read and write set. + /// + /// Two hook points are empty: system contract deployment, which deploys the chain's system + /// contracts at the Satin activation, and the pre-block system calls, which apply the + /// pending changes the sequencer registry holds. Both arrive with the mechanisms of those + /// names, between the pre-block calls and the L1 block info read. + fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { + if self.evm.has_rewriting_inspector() { + return Err(MegaBlockExecutionError::RewritingInspector.into()); + } + + let state = eips::transact_blockhashes_contract_call( + &self.spec, + self.ctx.parent_hash, + &mut self.evm, + )?; + if let Some(ResultAndState { state, .. }) = state { + self.commit(state); + } + + let state = eips::transact_beacon_root_contract_call( + &self.spec, + self.ctx.parent_beacon_block_root, + &mut self.evm, + )?; + if let Some(ResultAndState { state, .. }) = state { + self.commit(state); + } + + // Hook point: system contract deployment. + // Hook point: the pre-block system calls. + + self.load_l1_block_info()?; + + Ok(()) + } + + fn execute_transaction_without_commit( + &mut self, + tx: impl ExecutableTx, + ) -> Result { + let (tx_env, tx) = tx.into_parts(); + let inner = tx.tx(); + let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE; + + // A block that activates a fork carries the chain's own transactions only, so a user + // transaction in it is refused before anything runs. + if self.ctx.no_user_tx_activation_block && !is_deposit { + return Err(MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock.into()); + } + + // The encoding, once: the transaction environment carries it when the node passes an + // encoded transaction, and it is encoded here when it does not. + let da_size = tx_env.encoded_bytes().map_or_else( + || estimated_da_size(inner.encoded_2718().as_ref()), + |encoded| estimated_da_size(encoded), + ); + let tx_size = inner.encode_2718_len() as u64; + let gas_limit = inner.gas_limit(); + let tx_hash = inner.trie_hash(); + + self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; + + // A deposit is exempt from the data-availability footprint of the block, as it is from + // its data-availability size. + let da_footprint = if is_deposit { + 0 + } else { + let footprint = da_size.saturating_mul(self.da_footprint_gas_scalar()?); + let available = self.limiter.available_da_footprint(); + if footprint > available { + return Err(MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint: footprint, + available_block_da_footprint: available, + } + .into()); + } + footprint + }; + + // Read before execution, so committing the transaction cannot fail. + let depositor_nonce = if is_deposit && self.is_regolith { + let sender = *tx.signer(); + Some( + self.evm + .ctx_mut() + .db_mut() + .basic(sender) + .map_err(BlockExecutionError::other)? + .unwrap_or_default() + .nonce, + ) + } else { + None + }; + + let outcome = self + .evm + .execute_transaction(tx_env) + .map_err(|err| BlockExecutionError::evm(err, tx_hash))?; + + Ok(MegaBlockTxResult { + tx_type: inner.tx_type(), + tx_hash, + gas_limit, + tx_size, + da_size, + da_footprint, + is_deposit, + depositor_nonce, + inner: outcome, + }) + } + + /// Executes `tx` and commits it if `f` says so. + /// + /// The block's counters may have moved between the transaction executing and its commit — a + /// builder that executes candidates and then picks among them — so what the transaction adds + /// is checked against the block once more before it is committed. + fn execute_transaction_with_commit_condition( + &mut self, + tx: impl ExecutableTx, + f: impl FnOnce(&Self::Result) -> CommitChanges, + ) -> Result, BlockExecutionError> { + let output = self.execute_transaction_without_commit(tx)?; + + if !f(&output).should_commit() { + return Ok(None); + } + + self.limiter.pre_execution_check( + output.tx_hash, + output.gas_limit, + output.tx_size, + output.da_size, + output.is_deposit, + )?; + + Ok(Some(self.commit_transaction(output))) + } + + fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { + self.limiter.post_execution_update(&output.block_usage()); + + let MegaBlockTxResult { tx_type, is_deposit, depositor_nonce, inner, .. } = output; + let gas = inner.gas; + let cumulative_gas_used = self.limiter.block_gas_used; + let ResultAndState { result, state } = inner.result_and_state; + + self.receipts.push( + match self.receipt_builder.build_receipt(ReceiptBuilderCtx { + tx_type, + result, + cumulative_gas_used, + evm: &self.evm, + state: &state, + }) { + Ok(receipt) => receipt, + Err(ctx) => { + let receipt = alloy_consensus::Receipt { + // EIP-658 put the status code in the receipt. + status: Eip658Value::Eip658(ctx.result.is_success()), + cumulative_gas_used, + logs: ctx.result.into_logs(), + }; + + self.receipt_builder.build_deposit_receipt(OpDepositReceipt { + inner: receipt, + deposit_nonce: depositor_nonce, + // Canyon introduced the deposit receipt version, which says how the + // receipt hash is computed. + deposit_receipt_version: (is_deposit && self.is_canyon).then_some(1), + }) + } + }, + ); + + self.commit(state); + + GasOutput::with_state_gas(gas.gas_used, gas.state) + } + + fn finish( + self, + ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { + let (evm, result) = self.finish_with_counters()?; + Ok((evm, result.inner)) + } + + fn evm_mut(&mut self) -> &mut Self::Evm { + &mut self.evm + } + + fn evm(&self) -> &Self::Evm { + &self.evm + } + + fn receipts(&self) -> &[Self::Receipt] { + &self.receipts + } +} + +impl MegaBlockExecutor, R, Spec> +where + DB: Database + StateDB, + INSP: Inspector>, + ExtEnvs: ExternalEnvTypes, + R: OpReceiptBuilder, + Spec: MegaHardforks, + MegaTransaction: FromRecoveredTx + FromTxWithEncoded, +{ + /// Finishes the block and reports what it counted, on top of what + /// [`finish`](BlockExecutor::finish) returns. + /// + /// The block's gas used is the sum of its receipts, as it has always been; the three ledgers + /// and the data-size and write-record counts ride beside it, where no upstream type has a + /// place for them. The blob gas used is the block's data-availability footprint. + pub fn finish_with_counters( + mut self, + ) -> Result, BlockExecutionError> { + let balance_increments = + post_block_balance_increments::
(&self.spec, self.evm.block(), &[], None); + self.evm + .ctx_mut() + .db_mut() + .increment_balances(balance_increments) + .map_err(|_| alloy_evm::block::BlockValidationError::IncrementBalanceFailed)?; + + let BlockLimiter { gas, usage, block_gas_used, block_da_footprint_used, .. } = self.limiter; + Ok(( + self.evm, + MegaBlockExecutionResult { + inner: BlockExecutionResult { + receipts: self.receipts, + requests: Requests::default(), + gas_used: block_gas_used, + blob_gas_used: block_da_footprint_used, + }, + gas, + usage, + }, + )) + } } #[cfg(test)] mod tests { use super::*; - use crate::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId}; + use crate::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaHardforkConfig, MegaSpecId}; use alloy_evm::Evm; use revm::context::BlockEnv; @@ -45,9 +554,15 @@ mod tests { fn test_executor_hands_back_its_evm() { let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) .with_block(BlockEnv { gas_limit: 30_000_000, ..Default::default() }); - let mut executor = MegaBlockExecutor::new(MegaEvm::new(ctx)); + let mut executor = MegaBlockExecutor::new( + MegaEvm::new(ctx), + MegaBlockExecutionCtx::default(), + MegaHardforkConfig::default().with_all_activated(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ); assert_eq!(executor.evm().block().gas_limit, 30_000_000); + assert_eq!(executor.limiter().limits.block_gas_limit, 30_000_000); executor.evm_mut().set_inspector_enabled(true); assert!(executor.into_evm().is_inspecting()); } diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs new file mode 100644 index 000000000..169a607c5 --- /dev/null +++ b/crates/mega-evm/src/block/factory.rs @@ -0,0 +1,122 @@ +//! Factory of block executors for alloy-evm consumers. + +use alloy_consensus::{Transaction, TxReceipt}; +use alloy_eips::Encodable2718; +use alloy_evm::{ + block::{BlockExecutorFactory, StateDB}, + EvmEnv, EvmFactory, FromRecoveredTx, FromTxWithEncoded, +}; +use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; +use revm::Inspector; + +use crate::{ + ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockTxResult, MegaContext, + MegaEvm, MegaEvmFactory, MegaHardforks, MegaSpecId, MegaTransaction, TrustedObserver, +}; + +/// Creates the block executors a node drives. +/// +/// It holds what every block of the chain shares — the hardfork schedule, the EVM factory and +/// the receipt builder — and each block adds its own [`MegaBlockExecutionCtx`]. +#[derive(Clone, Debug, Default)] +pub struct MegaBlockExecutorFactory { + receipt_builder: R, + spec: Spec, + evm_factory: EvmF, +} + +impl MegaBlockExecutorFactory { + /// Creates a factory over a receipt builder, a hardfork schedule and an EVM factory. + pub const fn new(receipt_builder: R, spec: Spec, evm_factory: EvmF) -> Self { + Self { receipt_builder, spec, evm_factory } + } + + /// The receipt builder. + pub const fn receipt_builder(&self) -> &R { + &self.receipt_builder + } + + /// The chain's hardfork schedule. + pub const fn spec(&self) -> &Spec { + &self.spec + } + + /// The EVM factory. + pub const fn evm_factory_ref(&self) -> &EvmF { + &self.evm_factory + } +} + +impl MegaBlockExecutorFactory> +where + ExtEnvFactory: ExternalEnvFactory, + Spec: MegaHardforks, + R: OpReceiptBuilder, +{ + /// Creates an executor over an EVM that runs a declared observer. + /// + /// This is the one way an inspected transaction reaches a block: the inspector's type + /// declares that it writes nothing back ([`TrustedObserver`]), so what the block executes is + /// what the chain executes. An inspector without that declaration is refused by + /// [`apply_pre_execution_changes`](alloy_evm::block::BlockExecutor::apply_pre_execution_changes). + pub fn create_executor_with_trusted_inspector( + &self, + db: DB, + evm_env: EvmEnv, + ctx: MegaBlockExecutionCtx, + inspector: I, + ) -> MegaBlockExecutor, &R, &Spec> + where + DB: StateDB, + I: TrustedObserver + Inspector>, + { + let evm = self + .evm_factory + .create_evm(db, evm_env) + .with_trusted_inspector(inspector) + .with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) + } +} + +impl BlockExecutorFactory + for MegaBlockExecutorFactory> +where + R: OpReceiptBuilder + 'static, + Spec: MegaHardforks + 'static, + ExtEnvFactory: ExternalEnvFactory + 'static, + MegaTransaction: FromRecoveredTx + FromTxWithEncoded, + Self: 'static, +{ + type EvmFactory = MegaEvmFactory; + type ExecutionCtx<'a> = MegaBlockExecutionCtx; + type Transaction = R::Transaction; + type Receipt = R::Receipt; + type TxExecutionResult = + MegaBlockTxResult<::TxType>; + type Executor<'a, DB: StateDB, I: Inspector>> = + MegaBlockExecutor, &'a R, &'a Spec>; + + fn evm_factory(&self) -> &Self::EvmFactory { + &self.evm_factory + } + + /// Creates an executor over an EVM the caller built. + /// + /// The block's transaction-level limits are installed here, so the two ways to reach an + /// executor — this one and + /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) — + /// run every transaction under the same limits, whatever the caller did or did not apply. + fn create_executor<'a, DB, I>( + &'a self, + evm: MegaEvm, + ctx: Self::ExecutionCtx<'a>, + ) -> Self::Executor<'a, DB, I> + where + DB: StateDB, + I: Inspector>, + { + let evm = evm.with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) + } +} diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 3a68f53f0..a9623d389 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -122,6 +122,21 @@ pub trait MegaHardforks: OpHardforks { self.mega_fork_activation(MegaHardfork::Satin).active_at_timestamp(timestamp) } + /// Whether the block at `block_timestamp`, whose parent is at `parent_timestamp`, admits + /// only deposit transactions. + /// + /// A block in which a fork activates carries the chain's own transactions only. This is true + /// of a `MegaETH` fork and of an Optimism fork at or after Jovian, which + /// [`OpHardforks::is_no_user_tx_activation_block`] answers for; block execution reads one + /// flag, so the two are asked together here. + fn admits_only_deposits(&self, parent_timestamp: u64, block_timestamp: u64) -> bool { + MegaHardfork::VARIANTS.iter().any(|fork| { + let activation = self.mega_fork_activation(*fork); + activation.active_at_timestamp(block_timestamp) && + !activation.active_at_timestamp(parent_timestamp) + }) || self.is_no_user_tx_activation_block(parent_timestamp, block_timestamp) + } + /// Refuses a schedule that activates `P::FORK` without attaching `P`. /// /// This is the rule [`validate_schedule`](Self::validate_schedule) applies to every params @@ -578,6 +593,19 @@ mod tests { assert_eq!(with_params.validate_schedule(), Ok(())); } + /// The block a fork activates in carries the chain's own transactions only, and only that + /// block: the one before it and the ones after it are ordinary. + #[test] + fn test_activation_block_admits_only_deposits() { + let config = + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(100)); + + assert!(config.admits_only_deposits(99, 100), "the first block at the activation"); + assert!(config.admits_only_deposits(99, 101), "and the first block after a gap"); + assert!(!config.admits_only_deposits(98, 99), "not before the activation"); + assert!(!config.admits_only_deposits(100, 101), "and not once the parent had it too"); + } + #[test] fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { let config = diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 4016c9a56..7e06545d8 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -3,6 +3,7 @@ mod chain; mod eips; mod executor; +mod factory; mod hardfork; mod helpers; mod limit; @@ -11,6 +12,7 @@ mod result; pub use chain::*; pub use eips::*; pub use executor::*; +pub use factory::*; pub use hardfork::*; pub use helpers::*; pub use limit::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 429c28032..ff18a0936 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -1,11 +1,18 @@ //! What a block counts of its transactions, and how it refuses one. +#[cfg(not(feature = "std"))] +use alloc as std; use core::fmt; +use std::vec::Vec; -use alloy_evm::InvalidTxError; -use revm::context::result::InvalidTransaction; +use alloy_evm::{ + block::{BlockExecutionResult, TxResult}, + InvalidTxError, +}; +use alloy_primitives::TxHash; +use revm::context::result::{InvalidTransaction, ResultAndState}; -use crate::MegaGasUsage; +use crate::{BlockUsage, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome}; /// A block's gas, on the three ledgers its transactions spend on. /// @@ -215,6 +222,119 @@ impl InvalidTxError for MegaBlockLimitExceededError { } } +/// What executing one transaction of a block produced. +/// +/// This is the shape [`BlockExecutor::Result`](alloy_evm::block::BlockExecutor) is instantiated +/// with, and an associated type cannot carry the transaction: a transaction enters +/// `execute_transaction_without_commit` as a method-level type parameter, which an associated +/// type — fixed once per implementation — cannot name. So this carries what the commit path +/// needs of it instead: the type byte the receipt builder reads, and the hash, gas limit and +/// sizes the block-level admission re-reads at commit. +/// +/// Everything execution itself produced travels as the embedded [`MegaTransactionOutcome`], so a +/// dimension added there flows through without being declared again here. +#[derive(Clone, Debug)] +pub struct MegaBlockTxResult { + /// The transaction's type, which is what the receipt builder needs of it. + pub tx_type: T, + /// The transaction's hash, which names it if block admission refuses it at commit. + pub tx_hash: TxHash, + /// The gas the transaction declared. + pub gas_limit: u64, + /// The transaction's EIP-2718 encoded size, in bytes. + pub tx_size: u64, + /// The transaction's data-availability size, in bytes. + pub da_size: u64, + /// The transaction's data-availability footprint, in gas. + pub da_footprint: u64, + /// Whether the transaction is a deposit. + pub is_deposit: bool, + /// The nonce the depositor had before execution, which the deposit receipt reports. `Some` + /// only for a deposit. + pub depositor_nonce: Option, + /// The execution result, the post-state and what `MegaETH` counted, as execution produced + /// them. + pub inner: MegaTransactionOutcome, +} + +impl MegaBlockTxResult { + /// What this transaction adds to the block's counters. + pub const fn block_usage(&self) -> BlockUsage { + BlockUsage { + gas_used: self.inner.gas.gas_used, + gas: self.inner.gas, + usage: self.inner.usage, + tx_size: self.tx_size, + da_size: self.da_size, + da_footprint: self.da_footprint, + is_deposit: self.is_deposit, + } + } +} + +impl core::ops::Deref for MegaBlockTxResult { + type Target = MegaTransactionOutcome; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl core::ops::DerefMut for MegaBlockTxResult { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} + +impl TxResult for MegaBlockTxResult { + type HaltReason = MegaHaltReason; + + fn result(&self) -> &ResultAndState { + &self.inner.result_and_state + } + + fn into_result(self) -> ResultAndState { + self.inner.result_and_state + } +} + +/// What executing a whole block produced. +/// +/// The receipts, requests and the two header figures are alloy-evm's +/// [`BlockExecutionResult`], which the node consumes as it does for any chain; the block's three +/// gas ledgers and the data-size and write-record counts are `MegaETH`'s own, and no upstream +/// type has a place for them. +#[derive(Clone, Debug)] +pub struct MegaBlockExecutionResult { + /// The receipts, the requests, the gas used and the blob gas used. + pub inner: BlockExecutionResult, + /// The gas the block's transactions spent, by ledger. + pub gas: BlockGasCounters, + /// The data-size bytes and write records the block's transactions kept. The KV count a node + /// reports is [`LimitUsage::write_records`]. + pub usage: LimitUsage, +} + +impl MegaBlockExecutionResult { + /// The receipts of the block's transactions. + pub fn receipts(&self) -> &[R] { + &self.inner.receipts + } + + /// Consumes the result and returns the receipts. + pub fn into_receipts(self) -> Vec { + self.inner.receipts + } +} + +impl core::ops::Deref for MegaBlockExecutionResult { + type Target = BlockExecutionResult; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 6fc1798ac..a29c9b155 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -157,6 +157,26 @@ impl MegaEvm { self.inspect } + /// Enforces `limits` on every transaction this EVM runs from now on. + /// + /// Block execution installs the block's limits this way, so a transaction runs under them + /// whatever the caller configured when it built the EVM. + #[must_use] + pub fn with_tx_runtime_limits(mut self, limits: crate::EvmTxRuntimeLimits) -> Self { + self.set_tx_runtime_limits(limits); + self + } + + /// Enforces `limits` on every transaction this EVM runs from now on. + pub const fn set_tx_runtime_limits(&mut self, limits: crate::EvmTxRuntimeLimits) { + self.inner.ctx.additional_limit.set_limits(limits); + } + + /// The limits every transaction this EVM runs is held to. + pub const fn tx_runtime_limits(&self) -> &crate::EvmTxRuntimeLimits { + self.inner.ctx.additional_limit().limits() + } + /// Consumes the EVM and returns the revm EVM it wraps. pub(crate) fn into_inner(self) -> MegaInnerEvm { self.inner diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 9b6f76cfc..0e8b96e4d 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -56,4 +56,6 @@ pub type EvmFactory = MegaEvmFactory; /// Alias for [`MegaContext`] pub type Context = MegaContext; /// Alias for [`MegaBlockExecutor`] -pub type BlockExecutor = MegaBlockExecutor; +pub type BlockExecutor = MegaBlockExecutor; +/// Alias for [`MegaBlockExecutorFactory`] +pub type BlockExecutorFactory = MegaBlockExecutorFactory; From 86bb1f6cdff5a51128600d077f9d72878fe0c43f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:17:05 +0800 Subject: [PATCH 097/201] test(satin): measure the schedule, the floor and the KZG price on real transactions Four test targets under tests/satin: the intrinsic numbers and the state gas a new slot, a new account and deployed code draw; the code-size limits on a creation transaction and on a CREATE; the EIP-7976 calldata floor, the EIP-7981 access-list bytes and the calldata the execution cap admits; and what a KZG evaluation costs, including every way its verification can fail. The Amsterdam opcodes are covered by running them: without the table-level activation the same bytecode halts. --- crates/mega-evm/tests/satin/contract_size.rs | 200 +++++++++++++ crates/mega-evm/tests/satin/intrinsic.rs | 281 ++++++++++++++++++ crates/mega-evm/tests/satin/main.rs | 4 + crates/mega-evm/tests/satin/precompile_gas.rs | 167 +++++++++++ crates/mega-evm/tests/satin/schedule.rs | 184 ++++++++++++ 5 files changed, 836 insertions(+) create mode 100644 crates/mega-evm/tests/satin/contract_size.rs create mode 100644 crates/mega-evm/tests/satin/intrinsic.rs create mode 100644 crates/mega-evm/tests/satin/precompile_gas.rs create mode 100644 crates/mega-evm/tests/satin/schedule.rs diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs new file mode 100644 index 000000000..c8e9c136c --- /dev/null +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -0,0 +1,200 @@ +//! The code-size limits the Satin configuration raises. +//! +//! A deployed contract may hold 512 KiB, eight times more than EIP-7954's bound and twenty-one +//! times EIP-170's; an initcode may hold twice that, the ratio EIP-3860 sets between the two. +//! Both bounds are `CfgEnv` limits the spec fixes, so they apply to a creation transaction and to +//! a `CREATE` alike. + +use alloy_evm::{Evm, EvmError, InvalidTxError}; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE}, + test_utils::{right_pad_bytes, BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaHaltReason, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, + context::result::{ExecutionResult, HaltReason, InvalidTransaction}, + primitives::{eip170, eip3860}, +}; + +use crate::common::{call, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const FACTORY: Address = address!("0000000000000000000000000000000000100001"); + +/// Room for the state gas a megabyte of deployed code draws, all of it above the execution cap so +/// it comes out of the reservoir. +const GAS_LIMIT: u64 = 4_000_000_000; + +/// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. +fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { + let mut evm = MegaEvm::new(context(db)); + match evm.transact_raw(tx) { + Ok(outcome) => Ok(outcome.result), + Err(err) => { + let invalid = err + .as_invalid_tx_err() + .and_then(InvalidTxError::as_invalid_tx_err) + .unwrap_or_else(|| panic!("unexpected error {err:?}")); + Err(format!("{invalid:?}")) + } + } +} + +/// Runs `init_code` as a creation transaction from `CALLER`. +fn deploy(init_code: Bytes) -> Result, String> { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + run(create(CALLER, init_code, GAS_LIMIT), db) +} + +/// Init code of `size` bytes that does nothing. +fn initcode_of(size: usize) -> Bytes { + Bytes::from(vec![STOP; size]) +} + +/// Init code that returns `size` bytes of zeros as the deployed code. +fn constructor_returning(size: usize) -> Bytes { + let code = BytecodeBuilder::default() + .push_number(size as u64) + .append_many([PUSH1, 0x00]) + .append(RETURN) + .build_vec(); + right_pad_bytes(code, 32).into() +} + +fn assert_initcode_limit(result: Result, String>) { + let expected = format!("{:?}", InvalidTransaction::CreateInitCodeSizeLimit); + assert_eq!(result.expect_err("the transaction is rejected"), expected); +} + +fn assert_code_size_limit(result: Result, String>) { + let halt = result.expect("the transaction is valid"); + assert!( + matches!( + halt, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::CreateContractSizeLimit), + .. + } + ), + "{halt:?}" + ); +} + +/* ---------- the initcode bound ---------- */ + +/// An initcode of EIP-3860's size is far below the Satin bound and goes through. +#[test] +fn test_the_eip3860_initcode_size_is_accepted() { + assert!(deploy(initcode_of(eip3860::MAX_INITCODE_SIZE)).unwrap().is_success()); +} + +/// The Satin bound itself is accepted. +#[test] +fn test_the_satin_initcode_size_is_accepted() { + assert!(deploy(initcode_of(MAX_INITCODE_SIZE)).unwrap().is_success()); +} + +/// One byte past it is rejected before the transaction runs. +#[test] +fn test_one_byte_past_the_satin_initcode_size_is_rejected() { + assert_initcode_limit(deploy(initcode_of(MAX_INITCODE_SIZE + 1))); +} + +/// So is twice it. +#[test] +fn test_double_the_satin_initcode_size_is_rejected() { + assert_initcode_limit(deploy(initcode_of(2 * MAX_INITCODE_SIZE))); +} + +/// The initcode bound is twice the contract bound, which is the ratio EIP-3860 sets. +#[test] +fn test_the_initcode_bound_is_twice_the_contract_bound() { + assert_eq!(MAX_INITCODE_SIZE, 2 * MAX_CONTRACT_SIZE); + assert_eq!(MAX_CONTRACT_SIZE, 512 * 1024); +} + +/* ---------- the deployed-code bound, from a creation transaction ---------- */ + +/// Code of EIP-170's size deploys. +#[test] +fn test_the_eip170_code_size_deploys() { + assert!(deploy(constructor_returning(eip170::MAX_CODE_SIZE)).unwrap().is_success()); +} + +/// Code of the Satin size deploys. +#[test] +fn test_the_satin_code_size_deploys() { + assert!(deploy(constructor_returning(MAX_CONTRACT_SIZE)).unwrap().is_success()); +} + +/// One byte past it halts the creation. +#[test] +fn test_one_byte_past_the_satin_code_size_halts() { + assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); +} + +/// So does twice it. +#[test] +fn test_double_the_satin_code_size_halts() { + assert_code_size_limit(deploy(constructor_returning(2 * MAX_CONTRACT_SIZE))); +} + +/* ---------- the deployed-code bound, from a CREATE ---------- */ + +/// A contract that `CREATE`s a contract of `size` bytes and runs `INVALID` if the creation failed, +/// so a rejected creation shows up as a halt of the outer frame. +fn factory_creating(size: usize) -> Bytes { + let init_code = constructor_returning(size); + let code = BytecodeBuilder::default() + .mstore(0, &init_code) + .push_number(init_code.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(ISZERO); + let len = code.len(); + code.push_number(len as u8 + 4) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST) + .append(INVALID) + .build() +} + +/// Runs a factory that creates `size` bytes of code and returns whether the creation succeeded. +fn create_through_factory(size: usize) -> bool { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(FACTORY, factory_creating(size)); + let result = + run(call(CALLER, FACTORY, U256::ZERO, GAS_LIMIT), db).expect("the transaction is valid"); + match result { + ExecutionResult::Success { .. } => true, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::InvalidFEOpcode), .. + } => false, + other => panic!("unexpected result {other:?}"), + } +} + +/// A `CREATE` of EIP-170's size succeeds, and so does one byte past it: EIP-170 is not the bound +/// here. +#[test] +fn test_create_of_the_eip170_code_size_succeeds() { + assert!(create_through_factory(eip170::MAX_CODE_SIZE)); + assert!(create_through_factory(eip170::MAX_CODE_SIZE + 1)); +} + +/// A `CREATE` of the Satin size succeeds. +#[test] +fn test_create_of_the_satin_code_size_succeeds() { + assert!(create_through_factory(MAX_CONTRACT_SIZE)); +} + +/// One byte past it fails the creation, which the factory turns into a halt. +#[test] +fn test_create_one_byte_past_the_satin_code_size_fails() { + assert!(!create_through_factory(MAX_CONTRACT_SIZE + 1)); +} diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs new file mode 100644 index 000000000..1c7b05a2c --- /dev/null +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -0,0 +1,281 @@ +//! The intrinsic phase: the EIP-7976 calldata floor, the EIP-7981 access-list data charge, and +//! what the execution cap admits. +//! +//! Satin keeps Amsterdam's floor: a base of 12,000 with the recipient and value charges on top, +//! and every calldata byte at 64 gas whether it is zero or not. EIP-7981 puts the access list's +//! own bytes in the floor at the same rate, while the per-item intrinsic charge stays at its +//! pre-EIP-8038 value. A transaction whose floor is above the 200M execution cap is rejected +//! before it runs, which is what bounds the calldata a transaction may carry. + +use alloy_evm::{Evm, EvmError, InvalidTxError}; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + constants::{ACCOUNT_STATE_GAS, TX_GAS_LIMIT_CAP}, + test_utils::{op_transaction, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::{ + context::{ + result::{ExecutionResult, InvalidTransaction}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + primitives::B256, + Database, +}; + +use crate::common::{call, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000800000"); +const CALLEE: Address = address!("0000000000000000000000000000000000800001"); + +/// The intrinsic gas of a plain call to an account that is not the sender: the EIP-2780 sender +/// base plus the recipient's cold account access. +const EMPTY_CALL: u64 = 15_000; + +/// What one byte of anything a transaction carries costs in the EIP-7976 / EIP-7981 floor: four +/// floor tokens at 16 gas each. +const FLOOR_PER_BYTE: u64 = 64; + +/// A database where the sender can pay and `CALLEE` exists. +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(1)) +} + +/// Runs `tx` and returns the gas it used, or the validation error that rejected it. +fn gas_used(db: MemoryDatabase, tx: MegaTransaction) -> Result { + let mut evm = MegaEvm::new(context(db)); + match evm.transact_raw(tx) { + Ok(outcome) => { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + Ok(outcome.result.gas().tx_gas_used()) + } + Err(err) => { + let invalid = err + .as_invalid_tx_err() + .and_then(InvalidTxError::as_invalid_tx_err) + .unwrap_or_else(|| panic!("unexpected error {err:?}")); + Err(format!("{invalid:?}")) + } + } +} + +/* ---------- the EIP-7976 calldata floor ---------- */ + +/// A call carrying `len` bytes of `byte`. +fn with_calldata(len: usize, byte: u8) -> MegaTransaction { + crate::common::call_with_data(CALLER, CALLEE, Bytes::from(vec![byte; len]), 10_000_000) +} + +/// Empty calldata pays the intrinsic gas alone: the floor is the same number, so neither is the +/// binding one. +#[test] +fn test_the_floor_of_empty_calldata_is_the_intrinsic_gas() { + assert_eq!(gas_used(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL)); +} + +/// One byte of calldata costs 64 gas in the floor, which is above what the intrinsic phase +/// charges for it, so the floor is what the transaction pays. +#[test] +fn test_one_calldata_byte_costs_sixty_four_gas() { + assert_eq!(gas_used(funded(), with_calldata(1, 0x42)), Ok(EMPTY_CALL + FLOOR_PER_BYTE)); +} + +/// A hundred bytes, and a kilobyte: the floor is linear in the byte count at the same rate. +#[test] +fn test_the_floor_is_sixty_four_gas_for_every_calldata_byte() { + for len in [100u64, 1_024, 4_096] { + assert_eq!( + gas_used(funded(), with_calldata(len as usize, 0x42)), + Ok(EMPTY_CALL + FLOOR_PER_BYTE * len), + "{len} bytes" + ); + } +} + +/// A zero byte costs the same as a non-zero one in the floor: EIP-7976 prices the space a byte +/// takes in a block, not its value. +#[test] +fn test_a_zero_calldata_byte_costs_the_same_as_a_non_zero_one() { + let zeros = gas_used(funded(), with_calldata(1_024, 0x00)); + let non_zeros = gas_used(funded(), with_calldata(1_024, 0xff)); + assert_eq!(zeros, non_zeros); + assert_eq!(zeros, Ok(EMPTY_CALL + FLOOR_PER_BYTE * 1_024)); +} + +/* ---------- the EIP-7981 access-list data charge ---------- */ + +/// A call whose access list names `CALLEE` with `keys` storage keys. +fn with_access_list(keys: usize) -> MegaTransaction { + let access_list = AccessList(vec![AccessListItem { + address: CALLEE, + storage_keys: (0..keys).map(|i| B256::with_last_byte(i as u8)).collect(), + }]); + OpTx(op_transaction(TxEnv { + // Legacy transactions carry no access list, so the type has to say EIP-2930. + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 10_000_000, + access_list, + ..Default::default() + })) +} + +/// An access-list address costs 2,400 in the intrinsic phase — its pre-EIP-8038 price — and its +/// twenty bytes cost 64 each in the floor. With one address alone the intrinsic charge is the +/// larger of the two, so that is what the transaction pays. +#[test] +fn test_an_access_list_address_is_priced_at_the_pre_eip8038_rate() { + assert_eq!(gas_used(funded(), with_access_list(0)), Ok(EMPTY_CALL + 2_400)); +} + +/// A storage key costs 1,900 in the intrinsic phase and its thirty-two bytes cost 2,048 in the +/// floor, so every key pushes the floor further above the intrinsic sum. Past the address's +/// 1,120-gas head start the floor takes over, and from there the transaction pays the bytes. +#[test] +fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { + let address_bytes = 20 * FLOOR_PER_BYTE; + let key_bytes = 32 * FLOOR_PER_BYTE; + for keys in [0u64, 1, 7] { + assert_eq!( + gas_used(funded(), with_access_list(keys as usize)), + Ok(EMPTY_CALL + 2_400 + 1_900 * keys), + "{keys} keys: the intrinsic charge is still the larger" + ); + } + for keys in [8u64, 16, 64] { + assert_eq!( + gas_used(funded(), with_access_list(keys as usize)), + Ok(EMPTY_CALL + address_bytes + key_bytes * keys), + "{keys} keys: the floor is the larger" + ); + } +} + +/* ---------- the execution cap ---------- */ + +/// The largest calldata the execution cap admits: its floor is the cap's own number rounded down +/// to a whole byte. +const LARGEST_CALLDATA: u64 = 3_124_765; + +/// A call carrying `len` calldata bytes with a gas limit above the execution cap, so the cap is +/// what the floor is measured against. +fn with_calldata_over_the_cap(len: u64) -> MegaTransaction { + crate::common::call_with_data( + CALLER, + CALLEE, + Bytes::from(vec![0u8; len as usize]), + TX_GAS_LIMIT_CAP + 1_000_000, + ) +} + +/// At the bound the transaction is admitted and pays its floor; one byte more and the floor is +/// above the execution cap, which rejects it before it runs. +#[test] +fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { + let floor = EMPTY_CALL + FLOOR_PER_BYTE * LARGEST_CALLDATA; + assert!(floor <= TX_GAS_LIMIT_CAP, "{floor} is within the cap"); + assert!( + floor + FLOOR_PER_BYTE > TX_GAS_LIMIT_CAP, + "one byte more is over it, so the bound is the largest" + ); + + let db = funded().account_balance(CALLER, U256::from(10u128.pow(24))); + assert_eq!(gas_used(db.clone(), with_calldata_over_the_cap(LARGEST_CALLDATA)), Ok(floor)); + + let expected = format!( + "{:?}", + InvalidTransaction::GasFloorMoreThanGasLimit { + gas_floor: floor + FLOOR_PER_BYTE, + gas_limit: TX_GAS_LIMIT_CAP, + } + ); + assert_eq!(gas_used(db, with_calldata_over_the_cap(LARGEST_CALLDATA + 1)), Err(expected)); +} + +/// A floor above the transaction's own gas limit is rejected too, below the cap: the floor is +/// measured against whichever of the two is smaller. +#[test] +fn test_a_floor_above_the_gas_limit_is_rejected() { + let gas_limit = 100_000; + let len = (gas_limit - EMPTY_CALL) / FLOOR_PER_BYTE + 1; + let tx = crate::common::call_with_data( + CALLER, + CALLEE, + Bytes::from(vec![0u8; len as usize]), + gas_limit, + ); + let expected = format!( + "{:?}", + InvalidTransaction::GasFloorMoreThanGasLimit { + gas_floor: EMPTY_CALL + FLOOR_PER_BYTE * len, + gas_limit, + } + ); + assert_eq!(gas_used(funded(), tx), Err(expected)); + assert_sender_untouched(); +} + +/// The sender's nonce and balance are untouched by a transaction validation rejected. +fn assert_sender_untouched() { + let mut db = funded(); + let info = db.basic(CALLER).unwrap().unwrap(); + assert_eq!(info.nonce, 0); + assert_eq!(info.balance, U256::from(10u64.pow(18))); +} + +/* ---------- the state component is charged where it happens ---------- */ + +/// A transfer whose recipient must be created needs the account's state gas on top of the +/// intrinsic charge. The state gas is not part of the intrinsic phase, so a gas limit that covers +/// the intrinsic charge alone is accepted and then runs out of gas, charging the sender. +#[test] +fn test_a_transfer_that_cannot_pay_the_new_account_runs_out_of_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let mut evm = MegaEvm::new(context(db)); + let outcome = evm + .transact_raw(call(CALLER, CALLEE, U256::from(1), 21_000 + ACCOUNT_STATE_GAS - 1)) + .expect("the transaction is admitted"); + + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_eq!(outcome.state[&CALLER].info.nonce, 1, "the sender paid for the attempt"); +} + +/// The same for a creation: the created account's state gas is charged as the frame starts, not +/// at validation. +#[test] +fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let mut evm = MegaEvm::new(context(db)); + let outcome = evm + .transact_raw(create(CALLER, Bytes::new(), 24_000 + ACCOUNT_STATE_GAS - 1)) + .expect("the transaction is admitted"); + + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_eq!(outcome.state[&CALLER].info.nonce, 1, "the sender paid for the attempt"); +} + +/// A gas limit below the intrinsic charge itself is a validation rejection, which leaves the +/// sender untouched. +#[test] +fn test_a_gas_limit_below_the_intrinsic_charge_is_rejected() { + let expected = format!( + "{:?}", + InvalidTransaction::CallGasCostMoreThanGasLimit { + gas_limit: EMPTY_CALL - 1, + initial_gas: EMPTY_CALL, + } + ); + assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, EMPTY_CALL - 1)), Err(expected)); + assert_sender_untouched(); +} + +/// A plain call within its limits still goes through, so the checks above are not too eager. +#[test] +fn test_a_valid_call_still_passes() { + assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, 1_000_000)), Ok(EMPTY_CALL)); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6974ff689..44eba54de 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -1,10 +1,14 @@ //! Tests of the Satin engine. mod common; +mod contract_size; mod db_error; mod equivalence; mod inspector; +mod intrinsic; mod outcome; +mod precompile_gas; +mod schedule; mod state; mod static_callee; mod strategic_stop; diff --git a/crates/mega-evm/tests/satin/precompile_gas.rs b/crates/mega-evm/tests/satin/precompile_gas.rs new file mode 100644 index 000000000..f7a0f5f83 --- /dev/null +++ b/crates/mega-evm/tests/satin/precompile_gas.rs @@ -0,0 +1,167 @@ +//! What a call to the repriced KZG precompile costs, measured through the gas a transaction used. +//! +//! A successful evaluation costs a flat 100,000 whatever the caller forwarded. A call that +//! reaches verification and fails there — a wrong proof, a versioned hash that does not match the +//! commitment, an input of the wrong length — burns everything the caller forwarded, as a failing +//! precompile does. A caller that forwards less than the price is out of gas before verification +//! runs. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + kzg_point_evaluation::{ADDRESS as KZG, GAS_COST as KZG_GAS_COST}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaEvm, +}; +use revm::{ + bytecode::opcode::{MSTORE, PUSH0, RETURN, STATICCALL}, + precompile::kzg_point_evaluation::kzg_to_versioned_hash, + primitives::hex, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000a00000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000a00001"); + +const GAS_LIMIT: u64 = 10_000_000; + +/// The c-kzg test vector `verify_kzg_proof_case_correct_proof_4_4`. +const COMMITMENT: [u8; 48] = hex!( + "8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca2\ + 5f26936857bc3a7c2539ea8ec3a952b7" +); +const Z: [u8; 32] = hex!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"); +const Y: [u8; 32] = hex!("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9"); +const PROOF: [u8; 48] = hex!( + "a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc216074\ + 4faf0070725e00b60ad9a026a15b1a8c" +); + +/// The precompile's input: `versioned_hash ++ z ++ y ++ commitment ++ proof`. +fn kzg_input() -> Vec { + let mut input = kzg_to_versioned_hash(&COMMITMENT).to_vec(); + input.extend_from_slice(&Z); + input.extend_from_slice(&Y); + input.extend_from_slice(&COMMITMENT); + input.extend_from_slice(&PROOF); + input +} + +/// The same input with the last byte of the proof flipped: well formed, but the proof does not +/// verify. +fn invalid_proof() -> Vec { + let mut input = kzg_input(); + let last = input.len() - 1; + input[last] ^= 0x01; + input +} + +/// The same input with a versioned hash the commitment does not hash to. +fn mismatched_version() -> Vec { + let mut input = kzg_input(); + input[0] = 0x02; + input +} + +/// A contract that `STATICCALL`s the KZG precompile with `forwarded` gas and `input`, and returns +/// the call's success flag. +fn caller_of(input: &[u8], forwarded: u64, args_len: u64) -> Bytes { + BytecodeBuilder::default() + .mstore(0, input) + .push_number(0u64) // retLength + .push_number(0u64) // retOffset + .push_number(args_len) + .push_number(0u64) // argsOffset + .push_address(KZG) + .push_number(forwarded) + .append(STATICCALL) + .append_many([PUSH0, MSTORE]) + .push_number(32u64) + .push_number(0u64) + .append(RETURN) + .build() +} + +/// The gas the transaction used, and whether the `STATICCALL` reported success. +struct Call { + gas_used: u64, + succeeded: bool, +} + +fn run(input: &[u8], forwarded: u64, args_len: u64) -> Call { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, caller_of(input, forwarded, args_len)); + let mut evm = MegaEvm::new(context(db)); + let result = evm + .transact_raw(call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid") + .result; + assert!(result.is_success(), "{result:?}"); + let output = result.output().expect("the caller returns the flag").clone(); + Call { gas_used: result.gas().tx_gas_used(), succeeded: output.iter().any(|byte| *byte != 0) } +} + +/// A successful evaluation costs the same whatever the caller forwarded: the price is flat. +#[test] +fn test_a_valid_kzg_evaluation_costs_a_flat_price() { + let at = |forwarded| run(&kzg_input(), forwarded, 192); + let base = at(KZG_GAS_COST); + assert!(base.succeeded); + for forwarded in [KZG_GAS_COST + 1, 2 * KZG_GAS_COST, 10 * KZG_GAS_COST] { + let call = at(forwarded); + assert!(call.succeeded, "at {forwarded} forwarded"); + assert_eq!(call.gas_used, base.gas_used, "at {forwarded} forwarded"); + } +} + +/// The flat price is 100,000: a verification that fails keeps the whole forwarded amount, and the +/// difference from a success is what the success did not spend. +#[test] +fn test_the_flat_price_is_one_hundred_thousand() { + for forwarded in [2 * KZG_GAS_COST, 5 * KZG_GAS_COST] { + let success = run(&kzg_input(), forwarded, 192); + let failure = run(&invalid_proof(), forwarded, 192); + assert!(success.succeeded); + assert!(!failure.succeeded, "a wrong proof does not verify"); + assert_eq!( + failure.gas_used - success.gas_used, + forwarded - KZG_GAS_COST, + "at {forwarded} forwarded" + ); + } + assert_eq!(KZG_GAS_COST, 100_000); +} + +/// Each way verification can fail burns the forwarded gas the same way: a wrong proof, a +/// versioned hash that does not match, and an input of the wrong length. +#[test] +fn test_every_verification_failure_burns_the_forwarded_gas() { + let forwarded = 5 * KZG_GAS_COST; + let success = run(&kzg_input(), forwarded, 192); + for (name, input, args_len) in [ + ("a wrong proof", invalid_proof(), 192), + ("a mismatched versioned hash", mismatched_version(), 192), + ("an input one byte short", kzg_input(), 191), + ] { + let failure = run(&input, forwarded, args_len); + assert!(!failure.succeeded, "{name}"); + assert_eq!( + failure.gas_used - success.gas_used, + forwarded - KZG_GAS_COST, + "{name} burns what was forwarded" + ); + } +} + +/// A caller that forwards less than the price is out of gas before verification runs, so the +/// price is a floor on what a call must carry, not only on what it pays. +#[test] +fn test_forwarding_less_than_the_price_is_out_of_gas() { + let short = run(&kzg_input(), KZG_GAS_COST - 1, 192); + assert!(!short.succeeded); + // Upstream's own price would have been enough; the `MegaETH` price is not. + let at_upstreams_price = run(&kzg_input(), 50_000, 192); + assert!(!at_upstreams_price.succeeded); +} diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs new file mode 100644 index 000000000..350429316 --- /dev/null +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -0,0 +1,184 @@ +//! What the Satin gas schedule charges, measured on real transactions. +//! +//! The intrinsic numbers, the state gas a new slot and a new account draw, and the Amsterdam +//! opcodes the schedule brings with it. Each number is read off a transaction the engine ran, not +//! computed from the schedule, so a change to either side shows up here. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{ACCOUNT_STATE_GAS, SLOT_STATE_GAS}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaEvm, +}; +use revm::{ + bytecode::opcode::{CLZ, DUPN, EXCHANGE, MSTORE, PUSH0, PUSH1, RETURN, SLOTNUM, SWAPN}, + context::result::ExecutionResult, +}; + +use crate::common::{call, call_with_data, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000900000"); +const CALLEE: Address = address!("0000000000000000000000000000000000900001"); + +const GAS_LIMIT: u64 = 1_000_000; + +/// The gas a transaction used and the state gas inside it. +struct Spend { + gas_used: u64, + state: u64, +} + +/// Runs `tx` on `db` and returns what it spent. The transaction must succeed. +fn spend(db: MemoryDatabase, tx: mega_evm::MegaTransaction) -> Spend { + let mut evm = MegaEvm::new(context(db)); + let result = evm.transact_raw(tx).expect("the transaction is valid").result; + assert!(result.is_success(), "{result:?}"); + Spend { gas_used: result.gas().tx_gas_used(), state: result.gas().state_gas_spent_final() } +} + +/// A database where `CALLEE` exists and runs `code`. +fn with_code(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CALLEE, code) +} + +/* ---------- the intrinsic numbers ---------- */ + +/// A call that reaches an existing account and does nothing pays the sender base plus the +/// recipient's cold access, and draws no state gas. +#[test] +fn test_an_empty_call_costs_fifteen_thousand() { + let spent = spend(with_code(Bytes::new()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert_eq!(spent.gas_used, 15_000); + assert_eq!(spent.state, 0); +} + +/// A value transfer to an account that already exists adds the value charge, and still draws no +/// state gas: nothing is created. +#[test] +fn test_a_value_transfer_to_an_existing_account_costs_twenty_one_thousand() { + let db = with_code(Bytes::new()).account_balance(CALLEE, U256::from(1)); + let spent = spend(db, call(CALLER, CALLEE, U256::from(7), GAS_LIMIT)); + assert_eq!(spent.gas_used, 21_000); + assert_eq!(spent.state, 0); +} + +/// A transfer to an account that does not exist creates it, which is the account's state gas on +/// top of the transfer's own cost. +#[test] +fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let spent = spend(db, call(CALLER, CALLEE, U256::from(7), GAS_LIMIT)); + assert_eq!(spent.state, ACCOUNT_STATE_GAS); + assert_eq!(spent.gas_used, 21_000 + ACCOUNT_STATE_GAS); +} + +/// A transfer to the sender itself pays the sender base alone: neither the recipient charge nor +/// the value charge applies, because the recipient is the sender. +#[test] +fn test_a_self_transfer_costs_twelve_thousand() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let spent = spend(db, call(CALLER, CALLER, U256::from(7), GAS_LIMIT)); + assert_eq!(spent.gas_used, 12_000); + assert_eq!(spent.state, 0); +} + +/// A creation transaction pays the sender base plus the creation access charge, and the created +/// account's state gas on top. With empty init code nothing else is charged, so the fixed part is +/// what is left when the state gas is taken out. +#[test] +fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let spent = spend(db, create(CALLER, Bytes::new(), GAS_LIMIT)); + assert_eq!(spent.state, ACCOUNT_STATE_GAS, "the created account"); + assert_eq!(spent.gas_used - spent.state, 24_000, "the fixed part"); +} + +/* ---------- the state entries ---------- */ + +/// A slot's first write to a non-zero value draws the slot's state gas; writing it again does +/// not, because the slot is no longer new. +#[test] +fn test_a_new_slot_draws_the_slot_state_gas() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let new = spend(with_code(code.clone()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert_eq!(new.state, SLOT_STATE_GAS); + + let db = with_code(code).account_storage(CALLEE, U256::ZERO, U256::from(1)); + let again = spend(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert_eq!(again.state, 0, "the slot already holds the value"); +} + +/// Deployed code is priced by the byte on the state dimension, on top of the created account. +#[test] +fn test_deployed_code_draws_state_gas_by_the_byte() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let empty = spend(db(), create(CALLER, Bytes::new(), GAS_LIMIT)); + let thirty_two = spend(db(), create(CALLER, deploying(32), GAS_LIMIT)); + + assert_eq!(empty.state, ACCOUNT_STATE_GAS); + assert_eq!(thirty_two.state - empty.state, 32 * 1_530, "32 bytes at the state byte price"); +} + +/// Init code that returns `len` bytes of zeros as the deployed code. +fn deploying(len: u64) -> Bytes { + BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() +} + +/* ---------- the Amsterdam opcodes ---------- */ + +/// Runs `code` in `CALLEE` and returns the result, so a gated opcode shows up as a halt. +fn run_code(code: Vec) -> ExecutionResult { + let mut evm = MegaEvm::new(context(with_code(Bytes::from(code)))); + evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid") + .result +} + +/// `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` are gated on the Amsterdam spec upstream; the Satin +/// table activates them on the Karst base, so each one runs instead of halting. +#[test] +fn test_the_amsterdam_opcodes_run() { + // Two pushes and fifteen `DUP1`s, then `DUPN 0x80`: a stack deep enough for the immediate. + let mut deep = vec![PUSH1, 0x01, PUSH1, 0x00]; + deep.extend([0x80u8; 15]); // DUP1 + for opcode in [ + vec![SLOTNUM, PUSH0, MSTORE], + [deep.clone(), vec![DUPN, 0x80]].concat(), + [deep.clone(), vec![PUSH1, 0x02, SWAPN, 0x80]].concat(), + vec![PUSH1, 0x00, PUSH1, 0x01, PUSH1, 0x02, EXCHANGE, 0x8E], + ] { + let result = run_code(opcode.clone()); + assert!(result.is_success(), "{:#04x} halted: {result:?}", opcode[opcode.len() - 2]); + } +} + +/// `CLZ` is gated on Osaka, which the Karst base already is, so it needs no activation; it is +/// listed here so the whole Amsterdam opcode set is covered in one place. +#[test] +fn test_clz_runs_on_the_base_spec() { + let result = run_code(vec![PUSH1, 0x01, CLZ, PUSH0, MSTORE]); + assert!(result.is_success(), "{result:?}"); +} + +/// `SLOTNUM` pushes what the host reports, which is zero until the block executor sets it. +#[test] +fn test_slotnum_pushes_the_host_slot_number() { + let code = BytecodeBuilder::default() + .append(SLOTNUM) + .push_number(0u64) + .append(MSTORE) + .push_number(32u64) + .push_number(0u64) + .append(RETURN) + .build(); + let mut evm = MegaEvm::new(context(with_code(code))); + let result = evm + .transact_raw(call_with_data(CALLER, CALLEE, Bytes::new(), GAS_LIMIT)) + .expect("the transaction is valid") + .result; + assert!(result.is_success(), "{result:?}"); + assert_eq!(result.output().map(Bytes::as_ref), Some([0u8; 32].as_slice())); +} From 54d5a3f29fe118a87e2f8da9f6989dd136d48303 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:20:18 +0800 Subject: [PATCH 098/201] feat(block): execute a transaction with the sizes it reports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `run_transaction` is the entry point for a caller that already knows a transaction's hash and sizes — a sequencer whose mempool computed them at insertion — and it skips the compression estimate the size limits are stated over. The figures are used as they are, so an understated one would pass a limit it should have been refused by; a debug build cross-checks them against a fresh recompute and trips there instead. `commit_transaction_outcome` re-checks the block's admission before committing, which is what a builder that executes candidates and then picks among them needs; the trait's commit-condition path goes through it. `MegaTransactionExt` drops the `Encodable2718` bound its two size methods carried, so the trait alone is what the executor reads a transaction through. --- crates/mega-evm/src/block/executor.rs | 245 +++++++++++++++++--------- crates/mega-evm/src/block/helpers.rs | 67 ++++--- 2 files changed, 204 insertions(+), 108 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 5a9e8c8c9..7306654d6 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -60,7 +60,7 @@ pub type MegaFinishedBlock = use crate::{ block::eips, estimated_da_size, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, - MegaTransaction, + MegaTransaction, MegaTransactionExt, }; /// What the node hands block execution beside the EVM. @@ -339,77 +339,7 @@ where &mut self, tx: impl ExecutableTx, ) -> Result { - let (tx_env, tx) = tx.into_parts(); - let inner = tx.tx(); - let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE; - - // A block that activates a fork carries the chain's own transactions only, so a user - // transaction in it is refused before anything runs. - if self.ctx.no_user_tx_activation_block && !is_deposit { - return Err(MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock.into()); - } - - // The encoding, once: the transaction environment carries it when the node passes an - // encoded transaction, and it is encoded here when it does not. - let da_size = tx_env.encoded_bytes().map_or_else( - || estimated_da_size(inner.encoded_2718().as_ref()), - |encoded| estimated_da_size(encoded), - ); - let tx_size = inner.encode_2718_len() as u64; - let gas_limit = inner.gas_limit(); - let tx_hash = inner.trie_hash(); - - self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; - - // A deposit is exempt from the data-availability footprint of the block, as it is from - // its data-availability size. - let da_footprint = if is_deposit { - 0 - } else { - let footprint = da_size.saturating_mul(self.da_footprint_gas_scalar()?); - let available = self.limiter.available_da_footprint(); - if footprint > available { - return Err(MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { - transaction_da_footprint: footprint, - available_block_da_footprint: available, - } - .into()); - } - footprint - }; - - // Read before execution, so committing the transaction cannot fail. - let depositor_nonce = if is_deposit && self.is_regolith { - let sender = *tx.signer(); - Some( - self.evm - .ctx_mut() - .db_mut() - .basic(sender) - .map_err(BlockExecutionError::other)? - .unwrap_or_default() - .nonce, - ) - } else { - None - }; - - let outcome = self - .evm - .execute_transaction(tx_env) - .map_err(|err| BlockExecutionError::evm(err, tx_hash))?; - - Ok(MegaBlockTxResult { - tx_type: inner.tx_type(), - tx_hash, - gas_limit, - tx_size, - da_size, - da_footprint, - is_deposit, - depositor_nonce, - inner: outcome, - }) + self.execute(tx, None) } /// Executes `tx` and commits it if `f` says so. @@ -428,15 +358,7 @@ where return Ok(None); } - self.limiter.pre_execution_check( - output.tx_hash, - output.gas_limit, - output.tx_size, - output.da_size, - output.is_deposit, - )?; - - Ok(Some(self.commit_transaction(output))) + self.commit_transaction_outcome(output).map(Some) } fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { @@ -509,6 +431,167 @@ where Spec: MegaHardforks, MegaTransaction: FromRecoveredTx + FromTxWithEncoded, { + /// Executes `tx`, reading its hash and sizes from the transaction rather than computing + /// them. + /// + /// This is the entry point for a caller that already has those figures — a sequencer whose + /// mempool computed them at insertion. They feed the transaction-level and block-level size + /// limits directly and are not checked against the encoding in release builds, so an + /// understated value would pass a limit it should have been refused by; a debug build + /// cross-checks them against a fresh recompute and trips there instead. A transaction that + /// computes them from its own encoding is unconditionally safe. + /// + /// Nothing is committed. Hand the result to + /// [`commit_transaction`](BlockExecutor::commit_transaction), or to + /// [`commit_transaction_outcome`](Self::commit_transaction_outcome) to have the block's + /// admission re-checked first. + pub fn run_transaction( + &mut self, + tx: Tx, + ) -> Result< + MegaBlockTxResult<::TxType>, + BlockExecutionError, + > + where + Tx: ExecutableTx + MegaTransactionExt, + { + let reported = (tx.tx_hash(), tx.tx_size(), tx.estimated_da_size()); + self.execute(tx, Some(reported)) + } + + /// Alias of [`run_transaction`](Self::run_transaction). + pub fn execute_mega_transaction( + &mut self, + tx: Tx, + ) -> Result< + MegaBlockTxResult<::TxType>, + BlockExecutionError, + > + where + Tx: ExecutableTx + MegaTransactionExt, + { + self.run_transaction(tx) + } + + /// Re-checks the block's admission and commits `output`. + /// + /// The block's counters may have moved between the transaction executing and its commit — a + /// builder that executes candidates and then picks among them — so what the transaction adds + /// is checked against the block once more. + pub fn commit_transaction_outcome( + &mut self, + output: MegaBlockTxResult<::TxType>, + ) -> Result { + self.limiter.pre_execution_check( + output.tx_hash, + output.gas_limit, + output.tx_size, + output.da_size, + output.is_deposit, + )?; + Ok(self.commit_transaction(output)) + } + + /// Runs one transaction of the block, with the hash and sizes the caller reported or + /// computed from the transaction itself. + fn execute( + &mut self, + tx: impl ExecutableTx, + reported: Option<(alloy_primitives::TxHash, u64, u64)>, + ) -> Result< + MegaBlockTxResult<::TxType>, + BlockExecutionError, + > { + let (tx_env, tx) = tx.into_parts(); + let inner = tx.tx(); + let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE; + + // A block that activates a fork carries the chain's own transactions only, so a user + // transaction in it is refused before anything runs. + if self.ctx.no_user_tx_activation_block && !is_deposit { + return Err(MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock.into()); + } + + let (tx_hash, tx_size, da_size) = reported.map_or_else( + || { + // The compressed size is estimated from the encoding, which the transaction + // environment carries when the node passes an encoded transaction and which is + // produced here when it does not. + let da_size = tx_env.encoded_bytes().map_or_else( + || estimated_da_size(inner.encoded_2718().as_ref()), + |encoded| estimated_da_size(encoded), + ); + (inner.trie_hash(), inner.encode_2718_len() as u64, da_size) + }, + |reported| { + debug_assert_eq!( + reported, + ( + inner.trie_hash(), + inner.encode_2718_len() as u64, + estimated_da_size(inner.encoded_2718().as_ref()), + ), + "the transaction's reported hash and sizes do not match a fresh recompute \ + from the encoded transaction" + ); + reported + }, + ); + let gas_limit = inner.gas_limit(); + + self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; + + // A deposit is exempt from the data-availability footprint of the block, as it is from + // its data-availability size. + let da_footprint = if is_deposit { + 0 + } else { + let footprint = da_size.saturating_mul(self.da_footprint_gas_scalar()?); + let available = self.limiter.available_da_footprint(); + if footprint > available { + return Err(MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint: footprint, + available_block_da_footprint: available, + } + .into()); + } + footprint + }; + + // Read before execution, so committing the transaction cannot fail. + let depositor_nonce = if is_deposit && self.is_regolith { + let sender = *tx.signer(); + Some( + self.evm + .ctx_mut() + .db_mut() + .basic(sender) + .map_err(BlockExecutionError::other)? + .unwrap_or_default() + .nonce, + ) + } else { + None + }; + + let outcome = self + .evm + .execute_transaction(tx_env) + .map_err(|err| BlockExecutionError::evm(err, tx_hash))?; + + Ok(MegaBlockTxResult { + tx_type: inner.tx_type(), + tx_hash, + gas_limit, + tx_size, + da_size, + da_footprint, + is_deposit, + depositor_nonce, + inner: outcome, + }) + } + /// Finishes the block and reports what it counted, on top of what /// [`finish`](BlockExecutor::finish) returns. /// diff --git a/crates/mega-evm/src/block/helpers.rs b/crates/mega-evm/src/block/helpers.rs index e5dd807c1..a12fc12a3 100644 --- a/crates/mega-evm/src/block/helpers.rs +++ b/crates/mega-evm/src/block/helpers.rs @@ -27,48 +27,61 @@ pub fn estimated_da_size(bytes: &[u8]) -> u64 { /// What block execution reads off a transaction beside its environment. /// -/// The two sizes have defaults that compute them from the transaction's encoding. A type that -/// already knows them (see [`EnrichedMegaTx`]) answers with what it carries, and the choice is -/// made at compile time — no caller picks a variant. +/// A type that computes the two sizes from its own encoding and one that carries them already +/// computed (see [`EnrichedMegaTx`]) answer the same three questions, so the executor's +/// transaction path is written once and the choice is made at compile time — no caller picks a +/// variant. #[auto_impl(&)] pub trait MegaTransactionExt { + /// The transaction's hash. + fn tx_hash(&self) -> TxHash; + + /// The transaction's EIP-2718 encoded size, in bytes. + fn tx_size(&self) -> u64; + /// The size the transaction takes on data availability, in bytes. - /// - /// The default recomputes it from the encoding on every call. - fn estimated_da_size(&self) -> u64 - where - Self: Encodable2718, - { - estimated_da_size(self.encoded_2718().as_slice()) + fn estimated_da_size(&self) -> u64; +} + +impl MegaTransactionExt for MegaTxEnvelope { + fn tx_hash(&self) -> TxHash { + self.tx_hash() } - /// The transaction's EIP-2718 encoded size, in bytes. - fn tx_size(&self) -> u64 - where - Self: Encodable2718, - { + fn tx_size(&self) -> u64 { self.encode_2718_len() as u64 } - /// The transaction's hash. - fn tx_hash(&self) -> TxHash; + fn estimated_da_size(&self) -> u64 { + estimated_da_size(self.encoded_2718().as_slice()) + } } impl MegaTransactionExt for Recovered { fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() + MegaTransactionExt::tx_hash(self.inner()) + } + + fn tx_size(&self) -> u64 { + MegaTransactionExt::tx_size(self.inner()) + } + + fn estimated_da_size(&self) -> u64 { + MegaTransactionExt::estimated_da_size(self.inner()) } } impl MegaTransactionExt for Recovered<&MegaTxEnvelope> { fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() + MegaTransactionExt::tx_hash(*self.inner()) } -} -impl MegaTransactionExt for MegaTxEnvelope { - fn tx_hash(&self) -> TxHash { - self.tx_hash() + fn tx_size(&self) -> u64 { + MegaTransactionExt::tx_size(*self.inner()) + } + + fn estimated_da_size(&self) -> u64 { + MegaTransactionExt::estimated_da_size(*self.inner()) } } @@ -158,16 +171,16 @@ impl Encodable2718 for EnrichedMegaTx { } impl MegaTransactionExt for EnrichedMegaTx { - fn estimated_da_size(&self) -> u64 { - self.da_size + fn tx_hash(&self) -> TxHash { + self.tx_hash } fn tx_size(&self) -> u64 { self.tx_size } - fn tx_hash(&self) -> TxHash { - self.tx_hash + fn estimated_da_size(&self) -> u64 { + self.da_size } } From 884d2407602cbda3a921c1393a1c414cacca83af Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:21:28 +0800 Subject: [PATCH 099/201] test(satin): render the pricing table and port the parked gas rows pricing-table.md lists every named schedule entry at the Osaka, the Amsterdam and the Satin price, and nine probe transactions with what each spent by ledger; the test renders it and compares it to the checked-in file. The 34 rows the pending ledger owes the Satin gas table run in real test targets now and are deleted from _pending: the code-size limits, the calldata floor and the validation boundaries, the KZG price and the dynamic precompile builder. --- crates/mega-evm/src/evm/precompiles.rs | 22 ++ crates/mega-evm/tests/_pending/README.md | 28 +- .../tests/_pending/compute_gas/claims.rs | 214 -------------- .../_pending/mini_rex/contract_size_limit.rs | 253 ---------------- .../mega-evm/tests/_pending/mini_rex/gas.rs | 25 -- .../mega-evm/tests/_pending/mini_rex/main.rs | 1 - .../tests/_pending/rex5/gas_validation.rs | 230 --------------- crates/mega-evm/tests/_pending/rex5/main.rs | 2 - .../_pending/rex5/precompile_compute_gas.rs | 275 ------------------ .../tests/_pending/src/evm/factory.rs | 31 -- .../tests/_pending/src/evm/precompiles.rs | 211 -------------- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/pricing-table.md | 80 +++++ crates/mega-evm/tests/satin/pricing_table.rs | 253 ++++++++++++++++ crates/mega-evm/tests/satin/schedule.rs | 26 ++ 15 files changed, 400 insertions(+), 1252 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/gas_validation.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/factory.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/precompiles.rs create mode 100644 crates/mega-evm/tests/satin/pricing-table.md create mode 100644 crates/mega-evm/tests/satin/pricing_table.rs diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 55dbfb382..c60400e7d 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -213,6 +213,28 @@ mod tests { } } + /// Nothing can put upstream's KZG price back: the engine has one spec, so `set_spec` has + /// nothing to switch to and leaves the table — and a node's own entries — alone. + #[test] + fn test_set_spec_keeps_the_mega_kzg_override() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::SATIN); + let mut map = satin_precompiles_map(); + + for spec in [op_revm::OpSpecId::ISTHMUS, op_revm::OpSpecId::KARST] { + let changed = + PrecompileProvider::>::set_spec(&mut map, spec); + assert!(!changed, "the table must stay the Satin one"); + } + + let result = map + .run(&mut context, &inputs(kzg_point_evaluation::ADDRESS, kzg_input(), 200_000)) + .unwrap() + .unwrap(); + assert_eq!(result.result, InstructionResult::Return); + assert_eq!(result.gas.total_gas_spent(), kzg_point_evaluation::GAS_COST); + } + /// The `MegaETH` entry replaces upstream's rather than sitting beside it: the set holds one /// KZG precompile, at the same address, and the price it charges is `MegaETH`'s. #[test] diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index da80c6b9a..7a1e0a53c 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -27,7 +27,6 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | | SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | @@ -43,7 +42,7 @@ Do not add a `_pending/main.rs`. | the block executor | 53 | 23 | 30 | 39 | 14 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **747** | **624** | **123** | **426** | **293** | **28** | +| **Total** | **713** | **597** | **116** | **419** | **266** | **28** | ## Tests ported in place @@ -130,12 +129,26 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co | `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | | **Total** | | **45** | | +## Tests ported by the Satin gas table + +These 34 rows run in a real test target now, adapted to the Satin API and to the schedule the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `compute_gas/claims.rs` | the Satin gas table (4) | 4 | `tests/satin/precompile_gas.rs`, `tests/satin/schedule.rs` | +| `mini_rex/contract_size_limit.rs` | the Satin gas table (12) | 12 | `tests/satin/contract_size.rs` | +| `mini_rex/gas.rs` | the Satin gas table (4) | 4 | `tests/satin/intrinsic.rs` | +| `rex5/gas_validation.rs` | the Satin gas table (4) | 4 | `tests/satin/intrinsic.rs` | +| `rex5/precompile_compute_gas.rs` | the Satin gas table (3) | 3 | `tests/satin/precompile_gas.rs` | +| `src/evm/factory.rs` | the Satin gas table (1) | 1 | `src/evm/factory.rs` | +| `src/evm/precompiles.rs` | the Satin gas table (6) | 6 | `src/evm/precompiles.rs` | +| **Total** | | **34** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | |---|---|---|---| | `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | -| `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | the Satin gas table | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | | `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | the block executor | reads the accessed-block-hash record, which returns with the block executor | ## Files @@ -151,14 +164,13 @@ Each cell lists `disposition count (mechanism · decision)`. | `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | | `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | | `block_executor/trait_factory_runtime_limits.rs` | 4 | rewrite 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | -| `compute_gas/claims.rs` | 14 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); keep 1 (the Satin gas table · D04 (KZG 100k)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 2 (the Satin gas table · D13); rewrite 1 (the Satin gas table · D11); rewrite 1 (the data-size limit · D33/D48) | +| `compute_gas/claims.rs` | 10 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 1 (the data-size limit · D33/D48) | | `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | | `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | | `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | -| `mini_rex/contract_size_limit.rs` | 12 | rewrite 12 (the Satin gas table · D04 (512 KiB kept; the decision table does not pin the initcode bound under Osaka/EIP-3860)) | -| `mini_rex/gas.rs` | 26 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)); rewrite 4 (the Satin gas table · D11/D55 (7976 floor)) | +| `mini_rex/gas.rs` | 22 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | | `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | | `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | | `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | @@ -190,7 +202,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | | `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | | `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/gas_validation.rs` | 4 | rewrite 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | | `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | | `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | | `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | @@ -199,7 +210,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/keyless_replay_barrier.rs` | 3 | rewrite 3 (native keyless deployment · D36 (real nonce increment)) | | `rex5/oracle_hint_metering.rs` | 9 | keep 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); rewrite 1 (the oracle and control contracts · D11 intrinsic number); rewrite 1 (revert-class aborts · D48) | | `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | -| `rex5/precompile_compute_gas.rs` | 3 | rewrite 3 (the Satin gas table · D04/D40 (assert via gas_used)) | | `rex5/sandbox_accounting.rs` | 9 | rewrite 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | | `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | | `rex5/sstore_storage_gas_error.rs` | 1 | keep 1 (SALT pricing · pricing-failure path) | @@ -225,10 +235,8 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/block/limit.rs` | 5 | keep 5 (the block executor) | | `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | -| `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | | `src/evm/mod.rs` | 4 | keep 3 (the pre-block system calls); keep 1 (the block executor) | -| `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | | `src/evm/state.rs` | 1 | keep 1 (the block executor) | | `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | diff --git a/crates/mega-evm/tests/_pending/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs index 6539fd31e..cd19ee4b2 100644 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -202,49 +202,6 @@ fn test_refunds_do_not_reduce_compute_gas() { } } -/// Spec: [Precompiles], the KZG branch — "`KZG_POINT_EVALUATION_GAS_COST`, when the invocation -/// targeted the KZG point-evaluation precompile and its effective gas limit was at least -/// `KZG_POINT_EVALUATION_GAS_COST`". -/// -/// The constant is a **`MegaETH` override** (100,000), not the inherited EVM value (50,000). This -/// test pins the number itself rather than merely its presence: on the KZG non-out-of-gas error -/// path, Rex4 records the spent amount (zero, because the precompile never charged) while Rex5 -/// records the fixed cost. The difference between the two specs is therefore exactly the -/// constant, and a recording that fell back to the inherited value would miss by half. -#[test] -fn test_kzg_error_path_records_the_megaeth_fixed_cost() { - /// `MegaETH`'s override, defined in `crates/mega-evm/src/evm/precompiles.rs`. - /// Deliberately NOT imported from the crate: hard-coding it here means a change to the - /// implementation constant fails this test instead of silently following it. - const KZG_POINT_EVALUATION_GAS_COST: u64 = 100_000; - - let program = crate::corpus() - .into_iter() - .find(|p| p.name == "precompile_kzg_invalid_input") - .expect("corpus must contain precompile_kzg_invalid_input"); - - let rex4 = transact(MegaSpecId::REX4, (program.build_db)()); - let rex5 = transact(MegaSpecId::REX5, (program.build_db)()); - let rex6 = transact(MegaSpecId::REX6, (program.build_db)()); - - assert_eq!( - rex5.compute_gas.checked_sub(rex4.compute_gas).unwrap_or_else(|| panic!( - "Rex5 must not record less compute gas than Rex4 (Rex4={} Rex5={})", - rex4.compute_gas, rex5.compute_gas - )), - KZG_POINT_EVALUATION_GAS_COST, - "Rex5 must record MegaETH's fixed KZG cost where Rex4 recorded the spent amount \ - (Rex4={} Rex5={})", - rex4.compute_gas, - rex5.compute_gas - ); - assert_eq!( - rex6.compute_gas, rex5.compute_gas, - "Rex6 inherits the Rex5 KZG recording rule unchanged (Rex5={} Rex6={})", - rex5.compute_gas, rex6.compute_gas - ); -} - /// Spec: [Storage Gas Exclusion], at the one surcharge site the snapshot corpus cannot reach. /// /// Rex5 charges dynamic new-account storage gas when `SELFDESTRUCT` materializes an empty @@ -601,177 +558,6 @@ fn test_first_call_to_the_beneficiary_is_charged_cold_from_minirex() { } } -/// Pins "Code Deposit": the deposit's compute gas is recorded exactly once when the deposit -/// occurs, and nothing is recorded when it does not. -/// -/// The two initcodes have identical length and opcode sequence and differ only in the byte they -/// store, so every other cost in the transaction cancels and the difference between the two -/// recorded totals is the code-deposit charge alone. `0xEF` makes EIP-3541 reject the runtime -/// code, so the deposit never happens. -/// -/// Two different mechanisms produce this number — `MiniRex` through Rex4 measure it over the -/// frame-action window, Rex5+ pre-charge the canonical amount before the checkpoint commits — so -/// the assertion runs on every tracked spec to keep them agreeing. -#[test] -fn test_code_deposit_recorded_only_when_deposit_occurs() { - /// `PUSH1 , PUSH0, MSTORE8, PUSH1 32, PUSH0, RETURN` — returns 32 bytes of runtime - /// code whose first byte is `first`. - fn initcode(first: u8) -> [u8; 8] { - [0x60, first, 0x5f, 0x53, 0x60, 0x20, 0x5f, 0xf3] - } - - fn creator(first: u8) -> MemoryDatabase { - let code = initcode(first); - base_db( - BytecodeBuilder::default() - .mstore(0, code) - .push_number(code.len() as u64) // length - .push_number(0_u64) // offset - .push_number(0_u64) // value - .append(CREATE) - .stop() - .build(), - ) - } - - /// 32 bytes of deployed runtime code at the inherited `CODEDEPOSIT` rate of 200 gas per byte. - const EXPECTED_DEPOSIT_GAS: u64 = 32 * 200; - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; // Equivalence records no compute gas at all. - } - let deposited = transact(spec, creator(0x00)); - let skipped = transact(spec, creator(0xef)); - // Both transactions succeed: the EIP-3541 rejection fails the CREATE (it pushes zero), - // not the transaction. A non-success outcome means the fixture itself drifted. - assert_eq!(deposited.outcome, "success", "{spec_name}: depositing run should succeed"); - assert_eq!(skipped.outcome, "success", "{spec_name}: skipped-deposit run should succeed"); - let (deposited, skipped) = (deposited.compute_gas, skipped.compute_gas); - - let delta = deposited.checked_sub(skipped).unwrap_or_else(|| { - panic!( - "{spec_name}: depositing run must record at least as much compute gas as the \ - skipped run (deposited={deposited} skipped={skipped})" - ) - }); - assert_eq!( - delta, EXPECTED_DEPOSIT_GAS, - "{spec_name}: the only compute gas separating a deposit from an EIP-3541 rejection \ - must be the code-deposit charge (deposited={deposited} skipped={skipped})" - ); - } -} - -/// Pins "Transaction Intrinsic Gas" for a creation transaction, which no other test here sends — -/// every other helper dispatches a call transaction, so the creation surcharge and the EIP-3860 -/// per-initcode-word charge are otherwise unreachable. -/// -/// The recorded intrinsic is asserted as a closed formula over the initcode length rather than as -/// a handful of magic numbers, so the test states which components are in the amount: -/// base cost, the creation surcharge, the calldata token cost, and the per-initcode-word charge. -/// Lengths straddle a word boundary (64 and 65) so a missing or mis-rounded word charge shows up. -/// -/// Because the initcode is all zero bytes it executes as `STOP`, depositing no runtime code, so -/// the amount is the intrinsic alone with no opcode or code-deposit contribution mixed in. The -/// code-deposit charge a creation transaction records when it does deploy runtime code is pinned -/// separately by [`test_creation_transaction_records_code_deposit_compute_gas`]. -#[test] -fn test_creation_transaction_intrinsic_compute_gas() { - /// Inherited base cost of any transaction. - const TX_BASE_GAS: u64 = 21_000; - /// Inherited surcharge that only a contract-creation transaction pays. - const TX_CREATE_SURCHARGE: u64 = 32_000; - /// Gas per calldata token; a zero byte is one token. - const STANDARD_TOKEN_COST: u64 = 4; - /// EIP-3860 charge per 32-byte word of initcode. - const INITCODE_WORD_COST: u64 = 2; - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; // Equivalence records no compute gas at all. - } - for len in [0_u64, 32, 64, 65] { - let words = len.div_ceil(32); - let expected = TX_BASE_GAS + - TX_CREATE_SURCHARGE + - STANDARD_TOKEN_COST * len + - INITCODE_WORD_COST * words; - - let outcome = crate::transact_create(spec, vec![0_u8; len as usize].into()); - assert_eq!( - outcome.outcome, "success", - "{spec_name}: creation transaction with {len} initcode bytes should succeed" - ); - assert_eq!( - outcome.compute_gas, expected, - "{spec_name}: a creation transaction with {len} initcode bytes must record base \ - cost + creation surcharge + calldata tokens + {words} initcode word(s) as \ - compute gas, and nothing else" - ); - } - } -} - -/// Spec: [Contract Creation Code Deposit], the contract-creation-transaction leg — the deposit's -/// `code_length × CODEDEPOSIT` compute gas is recorded for a creation *transaction*, not only for -/// the `CREATE` / `CREATE2` opcodes the snapshot corpus exercises. -/// -/// Two creation transactions carry byte-identical initcode except for the RETURN size operand: -/// one deploys 32 bytes of zeroed runtime code, the other 64. Both initcodes first MSTORE a zero -/// word at offset 32, expanding memory to 64 bytes, so neither RETURN expands memory further; and -/// both size operands are non-zero bytes, so the calldata token cost is identical too. The only -/// cost separating the two transactions is 32 extra deposited bytes, so the recorded compute gas -/// must differ by exactly 32 × 200 = 6,400 on every metering spec. -#[test] -fn test_creation_transaction_records_code_deposit_compute_gas() { - /// The inherited EVM's per-byte code deposit rate. - const CODEDEPOSIT: u64 = 200; - /// The number of deployed bytes separating the two transactions. - const EXTRA_RUNTIME_BYTES: u64 = 32; - - /// `PUSH0; PUSH1 0x20; MSTORE; PUSH1 ; PUSH0; RETURN` — stores a zero word at offset 32 - /// (expanding memory to 64 bytes) and returns the first `len` bytes of memory, all zero, as - /// the deployed runtime code. - fn initcode(runtime_len: u8) -> Bytes { - Bytes::from(vec![0x5f, 0x60, 0x20, 0x52, 0x60, runtime_len, 0x5f, 0xf3]) - } - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; // Equivalence records no compute gas at all. - } - let deploys_32 = crate::transact_create(spec, initcode(32)); - let deploys_64 = crate::transact_create(spec, initcode(64)); - assert_eq!( - deploys_32.outcome, "success", - "{spec_name}: the 32-byte deployment should succeed" - ); - assert_eq!( - deploys_64.outcome, "success", - "{spec_name}: the 64-byte deployment should succeed" - ); - - let delta = - deploys_64.compute_gas.checked_sub(deploys_32.compute_gas).unwrap_or_else(|| { - panic!( - "{spec_name}: deploying more runtime code must not record less compute gas \ - (32B={} 64B={})", - deploys_32.compute_gas, deploys_64.compute_gas - ) - }); - assert_eq!( - delta, - EXTRA_RUNTIME_BYTES * CODEDEPOSIT, - "{spec_name}: the only compute gas separating the two creation transactions must be \ - the code-deposit charge for the {EXTRA_RUNTIME_BYTES} extra deployed bytes \ - (32B={} 64B={})", - deploys_32.compute_gas, - deploys_64.compute_gas - ); - } -} - /// Spec: [Opcode Metering Classes], the `SelfDestruct` class — "When that check finds more than one /// dimension over its limit, the reported dimension follows the fixed priority" (data size, /// key-value updates, compute gas, state growth). diff --git a/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs deleted file mode 100644 index fb6da8fc2..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs +++ /dev/null @@ -1,253 +0,0 @@ -//! Tests for the increased contract size limit and initcode size limit. - -use alloy_primitives::{address, Bytes, U256}; -use core::convert::Infallible; -use mega_evm::{ - revm::{ - bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, - context::result::{EVMError, ExecutionResult, InvalidTransaction, ResultAndState}, - }, - test_utils::{right_pad_bytes, transact, BytecodeBuilder, MemoryDatabase}, - *, -}; - -fn deploy_contract( - db: &mut MemoryDatabase, - bytecode: Bytes, - spec: MegaSpecId, -) -> Result, EVMError> { - transact( - spec, - db, - address!("0000000000000000000000000000000000100000"), - None, - bytecode, - U256::ZERO, - ) -} - -fn initcode_size_limit_test_case(spec: MegaSpecId, initcode_size: usize, success: bool) { - let large_bytecode = vec![STOP; initcode_size]; - let bytecode: Bytes = large_bytecode.into(); - let mut db = MemoryDatabase::default(); - let result = deploy_contract(&mut db, bytecode, spec); - if success { - assert!(result.is_ok()); - } else { - assert!(matches!( - result, - Err(EVMError::Transaction(MegaTransactionError::Base( - InvalidTransaction::CreateInitCodeSizeLimit - ))) - )); - } -} - -/// Test that verifies `MINI_REX` spec allows deployment with EIP-3860 max initcode size. -#[test] -fn test_minirex_eip3860_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::MINI_REX, - revm::primitives::eip3860::MAX_INITCODE_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec allows deployment with `MiniRex` max initcode size. -#[test] -fn test_minirex_minirex_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_INITCODE_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec rejects deployment with `MiniRex` max initcode size + 1. -#[test] -fn test_minirex_minirex_max_initcode_size_plus_one() { - initcode_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_INITCODE_SIZE + 1, - false, - ); -} - -/// Test that verifies `MINI_REX` spec rejects deployment with double `MiniRex` max initcode size. -#[test] -fn test_minirex_double_minirex_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::MINI_REX, - 2 * constants::mini_rex::MAX_INITCODE_SIZE, - false, - ); -} - -fn constructor_code(contract_size: usize) -> Bytes { - let mut init_code = BytecodeBuilder::default() - .push_number(contract_size as u64) - .append_many(vec![PUSH1, 0x00]) - .append(RETURN) - .build_vec(); - - init_code = right_pad_bytes(init_code, 32); - init_code.into() -} - -fn contract_size_limit_test_case(spec: MegaSpecId, contract_size: usize, success: bool) { - // Use the simplest method to return a contract code - let init_code = constructor_code(contract_size); - let mut db = MemoryDatabase::default(); - let result = deploy_contract(&mut db, init_code, spec); - if success { - assert!(result.is_ok()); - } else { - assert!(matches!( - result, - Ok(ResultAndState { - result: ExecutionResult::Halt { - reason: MegaHaltReason::Base(OpHaltReason::Base( - EthHaltReason::CreateContractSizeLimit - ),), - .. - }, - .. - }) - )); - } -} - -/// Test that verifies `MINI_REX` spec allows deployment with EIP-170 max code size. -#[test] -fn test_minirex_eip170_max_code_size() { - contract_size_limit_test_case( - MegaSpecId::MINI_REX, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec allows deployment with `MiniRex` max contract size. -#[test] -fn test_minirex_minirex_max_contract_size() { - contract_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_CONTRACT_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec rejects deployment with `MiniRex` max contract size + 1. -#[test] -fn test_minirex_minirex_max_contract_size_plus_one() { - contract_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_CONTRACT_SIZE + 1, - false, - ); -} - -/// Test that verifies `MINI_REX` spec rejects deployment with double `MiniRex` max contract size. -#[test] -fn test_minirex_double_minirex_max_contract_size() { - contract_size_limit_test_case( - MegaSpecId::MINI_REX, - 2 * constants::mini_rex::MAX_CONTRACT_SIZE, - false, - ); -} - -fn contract_factory_code_size_limit_test_case( - spec: MegaSpecId, - contract_size: usize, - success: bool, -) { - // 1. Create a "factory" contract that uses the CREATE opcode to create another large contract - // 2. Since the sub-contract exceeds the EIP-170 limit, the CREATE operation should fail - - let init_code = constructor_code(contract_size); - let factory_code = BytecodeBuilder::default() - // 1. put contract constructor code in memory - .mstore(0, &init_code) - // 2. create contract - .push_number(init_code.len() as u64) - .push_number(0u64) - .push_number(0u64) - .append(CREATE); - // 3. check if the create is successful, if not, jump to INVALID - let factory_code = factory_code.append(ISZERO); - let factory_code_len = factory_code.len(); - let factory_code = factory_code - .push_number(factory_code_len as u8 + 4) - .append(JUMPI) - .append(STOP) - .append(JUMPDEST) - .append(INVALID) - .build_vec(); - - let caller = address!("0000000000000000000000000000000000100000"); - let mut db = MemoryDatabase::default(); - let factory_address = address!("0000000000000000000000000000000000100001"); - db.set_account_code(factory_address, factory_code.into()); - let result = - transact(spec, &mut db, caller, Some(factory_address), Bytes::default(), U256::ZERO); - if success { - assert!(matches!( - result, - Ok(ResultAndState { result: ExecutionResult::Success { .. }, .. }) - )); - } else { - assert!(matches!( - result, - Ok(ResultAndState { - result: ExecutionResult::Halt { - reason: MegaHaltReason::Base(OpHaltReason::Base( - EthHaltReason::InvalidFEOpcode - )), - .. - }, - .. - }) - )); - } -} - -/// Test that verifies `MINI_REX` spec allows CREATE opcode with EIP-170 max code size. -#[test] -fn test_minirex_create_eip170_max_code_size() { - contract_factory_code_size_limit_test_case( - MegaSpecId::MINI_REX, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec allows CREATE opcode with EIP-170 max code size + 1. -#[test] -fn test_minirex_create_eip170_max_code_size_plus_one() { - contract_factory_code_size_limit_test_case( - MegaSpecId::MINI_REX, - revm::primitives::eip170::MAX_CODE_SIZE + 1, - true, - ); -} - -/// Test that verifies `MINI_REX` spec allows CREATE opcode with `MiniRex` max contract size. -#[test] -fn test_minirex_create_minirex_max_contract_size() { - contract_factory_code_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_CONTRACT_SIZE, - true, - ); -} - -/// Test that verifies `MINI_REX` spec rejects CREATE opcode with `MiniRex` max contract size + 1. -#[test] -fn test_minirex_create_minirex_max_contract_size_plus_one() { - contract_factory_code_size_limit_test_case( - MegaSpecId::MINI_REX, - constants::mini_rex::MAX_CONTRACT_SIZE + 1, - false, - ); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs index c131f5235..3c7ccda23 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -796,28 +796,3 @@ fn floor_gas_test_case(spec: MegaSpecId, calldata_size: usize, expected_gas_used assert_eq!(gas_used, expected_gas_used); } -/// Tests floor gas charges additional cost for calldata in `MINI_REX` spec. -#[test] -fn test_floor_gas_calldata_mini_rex() { - // Test with 100 bytes of calldata - floor_gas_test_case(MegaSpecId::MINI_REX, 100, 65_000); -} - -/// Tests floor gas charges additional cost for large calldata in `MINI_REX` spec. -#[test] -fn test_floor_gas_large_calldata_mini_rex() { - // Test with 1024 bytes of calldata - floor_gas_test_case(MegaSpecId::MINI_REX, 1024, 471_560); -} - -/// Tests floor gas with empty calldata (edge case). -#[test] -fn test_floor_gas_empty_calldata() { - floor_gas_test_case(MegaSpecId::MINI_REX, 0, 21_000); -} - -/// Tests floor gas with minimal calldata (1 byte). -#[test] -fn test_floor_gas_minimal_calldata() { - floor_gas_test_case(MegaSpecId::MINI_REX, 1, 21_440); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs index c94d58cc7..f3079b45c 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -4,7 +4,6 @@ mod access_beneficiary_balance; mod block_env_access_tracking; mod block_env_gas_limit; mod compute_gas_limit; -mod contract_size_limit; mod gas; mod mega_system_transaction; mod oracle; diff --git a/crates/mega-evm/tests/_pending/rex5/gas_validation.rs b/crates/mega-evm/tests/_pending/rex5/gas_validation.rs deleted file mode 100644 index f6d7752c7..000000000 --- a/crates/mega-evm/tests/_pending/rex5/gas_validation.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! REX5 final-Mega-gas validation regression tests. -//! -//! Pin the invariant that, before `pre_execution()` runs, `MegaHandler::validate()` -//! has accounted for every Mega-side intrinsic and dynamic storage gas contribution -//! and rejected the transaction as a canonical validation error if either bound is -//! exceeded. -//! -//! Pre-REX5 specs intentionally produce a different shape (synthetic OOG with -//! `gas_used == gas_limit`); the legacy stable-spec tests in -//! `tests/mini_rex/gas.rs::test_mini_rex_insufficient_storage_gas_*_oog` lock that -//! shape in. This module locks down the new REX5 shape and adds a REX4 mirror of -//! the legacy stable-spec test so the gating is exercised in two pre-REX5 specs -//! that follow different code paths into Mega-step-D. - -use std::convert::Infallible; - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, EVMError, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - MegaTransactionError, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{ - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -use revm::context::result::InvalidTransaction; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const NEW_ACCOUNT: Address = address!("9000000000000000000000000000000000000009"); - -/// Build a context wired to the given spec and salt environment. -fn build_evm( - db: &mut MemoryDatabase, - spec: MegaSpecId, - external_envs: TestExternalEnvs, -) -> MegaEvm<&mut MemoryDatabase, revm::inspector::NoOpInspector, TestExternalEnvs> { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - MegaEvm::new(context) -} - -fn run_tx( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - tx: TxEnv, -) -> Result, EVMError> { - let mut evm = build_evm(db, spec, external_envs); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -fn external_envs_with_hot_account( - account: Address, - multiplier: u64, -) -> TestExternalEnvs { - let bucket_id = TestExternalEnvs::::bucket_id_for_account(account); - TestExternalEnvs::::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * multiplier) -} - -fn assert_call_gas_cost_more_than_gas_limit(err: &EVMError) { - let dbg = format!("{err:?}"); - assert!( - dbg.contains("CallGasCostMoreThanGasLimit"), - "expected CallGasCostMoreThanGasLimit, got {dbg}", - ); -} - -fn assert_gas_floor_more_than_gas_limit(err: &EVMError) { - let dbg = format!("{err:?}"); - assert!( - dbg.contains("GasFloorMoreThanGasLimit"), - "expected GasFloorMoreThanGasLimit, got {dbg}", - ); -} - -/// Sender state must be untouched when `validate()` rejects: balance unchanged AND nonce unchanged. -fn assert_sender_untouched(db: &mut MemoryDatabase, expected_balance: U256, expected_nonce: u64) { - use revm::Database as _; - let info = db.basic(CALLER).expect("db read should succeed").unwrap_or_default(); - assert_eq!( - info.balance, expected_balance, - "sender balance must not change on validation reject" - ); - assert_eq!(info.nonce, expected_nonce, "sender nonce must not change on validation reject"); -} - -// ================================================================================== -// REX5 validation-rejection tests -// ================================================================================== - -/// REX5: a top-level CALL with non-zero value to an empty callee whose bucket is hot -/// must be rejected by `validate()` once Mega-side new-account storage gas is added. -/// The sender's balance and nonce must not move. -#[test] -fn test_rex5_initial_gas_includes_new_callee_storage_gas_before_validation_rejection() { - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(10_000_000u64); - db.set_account_balance(CALLER, initial_balance); - - let multiplier = 10u64; // Rex-tier new_account storage gas: 2_000_000 * 10 = 20_000_000 - let external_envs = external_envs_with_hot_account(NEW_ACCOUNT, multiplier); - - // Intrinsic ≈ 21k, REX intrinsic storage gas 39k → ~60k. Storage gas is 20M. - // Choose 80_000 so initial_gas after Mega-step-D blows past gas_limit. - let insufficient_gas_limit = 80_000; - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(NEW_ACCOUNT), - data: Bytes::new(), - value: U256::from(1), - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - - let err = run_tx(MegaSpecId::REX5, &mut db, external_envs, tx) - .expect_err("REX5 must reject Mega-final-gas overrun as a validation error"); - assert_call_gas_cost_more_than_gas_limit(&err); - assert_sender_untouched(&mut db, initial_balance, 0); -} - -/// REX5: a top-level CREATE whose final Mega-side initial gas exceeds the tx gas limit -/// must be rejected by `validate()` rather than synthesizing an OOG after fee debit. -#[test] -fn test_rex5_initial_gas_includes_create_storage_gas_before_validation_rejection() { - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(10_000_000u64); - db.set_account_balance(CALLER, initial_balance); - - let created_address = CALLER.create(0); - let multiplier = 10u64; // Rex-tier contract creation storage gas dominates the budget. - let external_envs = external_envs_with_hot_account(created_address, multiplier); - - // Intrinsic + CREATE base ≈ 53k, REX intrinsic 39k → ~92k. Storage gas is in the millions. - let insufficient_gas_limit = 120_000; - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Create, - data: Bytes::new(), - value: U256::ZERO, - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - - let err = run_tx(MegaSpecId::REX5, &mut db, external_envs, tx) - .expect_err("REX5 must reject Mega-final-gas overrun as a validation error"); - assert_call_gas_cost_more_than_gas_limit(&err); - assert_sender_untouched(&mut db, initial_balance, 0); -} - -/// REX5: a tx whose floor gas exceeds the gas limit (driven by Mega calldata-floor scaling) -/// must be rejected with `GasFloorMoreThanGasLimit`. The sender state must not move. -#[test] -fn test_rex5_floor_gas_above_gas_limit_is_validation_rejection() { - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(1_000_000_000u64); - db.set_account_balance(CALLER, initial_balance); - - // For a top-level CALL with non-zero value to the existing sender (no new-account storage): - // initial_gas = 21_000 (base) + 4*T (canonical zero-byte token cost) + 40*T (mega calldata - // storage) + 39_000 (REX intrinsic) = 60_000 + 44*T - // floor_gas = 21_000 + 10*T (EIP-7623 floor) + 100*T (mega floor storage) = 21_000 + 110*T - // - // For a gas_limit that bands `initial_gas <= gas_limit < floor_gas` we need - // 60_000 + 44*T <= gas_limit < 21_000 + 110*T, - // i.e. T > 590. Use T = 700 zero bytes: - // initial_gas = 90_800 - // floor_gas = 98_000 - let calldata = Bytes::from(vec![0u8; 700]); - let gas_limit = 95_000; - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(NEW_ACCOUNT), - data: calldata, - value: U256::ZERO, - gas_limit, - ..Default::default() - }; - - let err = run_tx(MegaSpecId::REX5, &mut db, TestExternalEnvs::::new(), tx) - .expect_err("REX5 must reject floor_gas > gas_limit as a validation error"); - assert_gas_floor_more_than_gas_limit(&err); - assert_sender_untouched(&mut db, initial_balance, 0); -} - -/// REX5: a normal valid CALL still goes through. Sanity that the new check is not too aggressive. -#[test] -fn test_rex5_valid_tx_still_passes() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10u64).pow(U256::from(20u64))); // 100 ETH - - let callee: Address = address!("1000000000000000000000000000000000000001"); - db.set_account_balance(callee, U256::from(1u64)); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(callee), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 1_000_000, - ..Default::default() - }; - - let res = run_tx(MegaSpecId::REX5, &mut db, TestExternalEnvs::::new(), tx) - .expect("plain transfer to existing account must succeed under REX5"); - assert!(res.result.is_success(), "got {:?}", res.result); -} - -// ================================================================================== -// Stable-spec preservation tests (pre-REX5 specs keep the bug-shape OOG behavior) -// ================================================================================== -// -// MINI_REX coverage already lives in -// `tests/mini_rex/gas.rs::test_mini_rex_insufficient_storage_gas_*_oog` (intentional bug-shape -// pin). The block below mirrors the same scenario at REX4 so the gating is exercised against the -// second pre-REX5 code path (REX adds `TX_INTRINSIC_STORAGE_GAS`, so MINI_REX and REX..REX4 walk -// Mega-step-D differently). - -// `_` to prove `InvalidTransaction` from `revm::context::result` is reachable via the -// public re-export and to catch a future revm bump that drops the variant. -const _: fn() = || { - let _ = InvalidTransaction::CallGasCostMoreThanGasLimit { initial_gas: 0, gas_limit: 0 }; - let _ = InvalidTransaction::GasFloorMoreThanGasLimit { gas_floor: 0, gas_limit: 0 }; -}; diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index abf4efcd9..439aad933 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -9,7 +9,6 @@ mod deposit_caller_accounting; mod deposit_create_storage_gas; mod eip7702_metering; mod eip7702_state_growth; -mod gas_validation; mod interceptor_selector_probe; mod keyless_deploy_dispatch_parity; mod keyless_empty_code_logs; @@ -18,7 +17,6 @@ mod keyless_gas_cap_postcap_recheck; mod keyless_replay_barrier; mod oracle_hint_metering; mod pre_block_system_calls; -mod precompile_compute_gas; mod sandbox_accounting; mod selfdestruct_beneficiary; mod sstore_storage_gas_error; diff --git a/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs deleted file mode 100644 index 59a154f95..000000000 --- a/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs +++ /dev/null @@ -1,275 +0,0 @@ -//! Tests for precompile error path compute gas. -//! -//! REX5 fixes compute gas accounting for failing precompile calls. When a precompile -//! fails with `PrecompileOOG` (e.g., ecrecover called with insufficient gas), the full -//! forwarded gas amount is permanently lost by the parent. REX5 records this lost gas -//! as compute gas via `gas.limit()`. Pre-REX5 specs record only `gas.spent()` which -//! is 0 on error paths because revm does not call `record_cost()` for failed precompiles. -//! -//! REX5 also refines the error-path accounting for Mega's fixed-cost KZG precompile -//! (`0x0a`). When the KZG wrapper's `gas_limit < GAS_COST` pre-check has passed and -//! upstream verification then returned a non-OOG error (invalid proof / mismatched -//! version / wrong input length), the recorded compute-gas is exactly `GAS_COST` -//! (= 100 000) instead of the full forwarded amount. The cap-induced OOG path -//! (`effective_gas_limit < GAS_COST`, wrapper itself OOGs before verification) is -//! unaffected and still records the capped budget. -//! -//! Pre-REX5 KZG verification-failure behaviour is intentionally preserved as the -//! original `spent() == 0` recording — replay determinism requires that stable specs -//! produce byte-identical receipts. The `test_rex4_kzg_*` test below is a -//! stable-spec replay-preservation guard. - -use alloy_primitives::{address, Address, Bytes, U256}; -use core::cell::RefCell; -use mega_evm::{ - kzg_point_evaluation, - test_utils::{BytecodeBuilder, MemoryDatabase}, - AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ResultAndState, tx::TxEnvBuilder, TxEnv}, - handler::EvmTr, -}; -use sha2::{Digest, Sha256}; -use std::rc::Rc; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000600000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); -const ECRECOVER: Address = address!("0000000000000000000000000000000000000001"); -/// Blake2f precompile (EIP-152). Requires exactly 213 bytes of input. -/// Wrong-length input triggers `PrecompileError::Other` (not OOG). -const BLAKE2F: Address = address!("0000000000000000000000000000000000000009"); -// KZG point evaluation precompile (EIP-4844, address `0x0a`) and its Mega-overridden -// fixed cost. These are local `const` aliases of the production constants in -// `mega_evm::kzg_point_evaluation`, kept here only because Rust's -// named-format-arg substitution (`{KZG_GAS_COST}` in `assert!` messages) requires -// the identifier to be in lexical scope. If the production constant is ever -// re-tuned (e.g., a future Mega spec changes the fixed cost), these aliases -// inherit the new value automatically; no manual sync required. -const KZG: Address = kzg_point_evaluation::ADDRESS; -const KZG_GAS_COST: u64 = kzg_point_evaluation::GAS_COST; - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> (ResultAndState, u64) { - transact_with_compute_limit(spec, db, tx, None) -} - -/// Like `transact`, but optionally overrides the transaction's compute-gas budget -/// via a custom `AdditionalLimit` tracker. Used by KZG cap-induced tests that need -/// `tx_compute_gas_limit < KZG_GAS_COST` to exercise the wrapper's pre-check OOG. -fn transact_with_compute_limit( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, - tx_compute_gas_limit_override: Option, -) -> (ResultAndState, u64) { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - if let Some(limit) = tx_compute_gas_limit_override { - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: limit, - ..EvmTxRuntimeLimits::from_spec(spec) - }; - context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); - } - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (r, compute_gas) -} - -/// Build a KZG-precompile payload from the four 48/32-byte fields. -/// Layout: `versioned_hash[32] || z[32] || y[32] || commitment[48] || proof[48]` = 192 bytes. -/// The `versioned_hash` is the SHA-256 of `commitment` with byte 0 forced to -/// `VERSIONED_HASH_VERSION_KZG = 0x01` unless `version_byte_override` is set -/// (used by `mismatched_version` tests). -fn build_kzg_input(version_byte_override: Option) -> Vec { - let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); - let z = - hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000").unwrap(); - let y = - hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9").unwrap(); - let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); - let mut versioned_hash = Sha256::digest(&commitment).to_vec(); - versioned_hash[0] = version_byte_override.unwrap_or(0x01); - - let mut input = Vec::with_capacity(192); - input.extend_from_slice(&versioned_hash); - input.extend_from_slice(&z); - input.extend_from_slice(&y); - input.extend_from_slice(&commitment); - input.extend_from_slice(&proof); - debug_assert_eq!(input.len(), 192); - input -} - -/// Valid KZG payload (verification succeeds upstream). -fn valid_kzg_input() -> Vec { - build_kzg_input(None) -} - -/// KZG payload with the proof's last byte flipped — structurally valid (192 bytes, -/// matching versioned hash) but upstream verification returns -/// `PrecompileError::BlobVerifyKzgProofFailed`. -fn invalid_proof_kzg_input() -> Vec { - let mut input = valid_kzg_input(); - let last = input.len() - 1; - input[last] ^= 0x01; - input -} - -/// KZG payload with `versioned_hash[0] = 0x02` so the version-byte check fails → -/// upstream returns `PrecompileError::BlobMismatchedVersion`. -fn mismatched_version_kzg_input() -> Vec { - build_kzg_input(Some(0x02)) -} - -/// KZG payload truncated to 191 bytes — upstream returns -/// `PrecompileError::BlobInvalidInputLength` (requires exactly 192 bytes). -fn wrong_length_kzg_input() -> Vec { - let mut input = valid_kzg_input(); - input.pop(); - input -} - -/// Build a wrapper-contract bytecode that stores `input` at memory offset 0, then -/// CALLs `precompile` with `(gas, value=0, argsOffset=0, argsSize=input.len(), -/// retOffset=input.len(), retSize=0)`, pops the CALL result, and STOPs. -/// -/// Modelled on the existing ecrecover / blake2f tests so the outer tx always -/// succeeds (the contract swallows the precompile failure via POP). -fn kzg_wrapper_bytecode(input: &[u8], forwarded_gas: u64) -> Bytes { - let args_size = input.len() as u64; - BytecodeBuilder::default() - .mstore(0, input) - .push_number(0_u64) // retSize - .push_number(args_size) // retOffset (place return data after the input) - .push_number(args_size) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(KZG) - .push_number(forwarded_gas) // gas - .append(CALL) - .append(POP) - .stop() - .build() -} - -// ============================================================================ -// TESTS -// ============================================================================ - -// ============================================================================ -// KZG fixed-cost compute-gas accounting (REX5) -// ============================================================================ -// -// The three `test_rex5_kzg_*_records_exact_gas_cost` tests pin the invariant -// that on REX5, when the KZG wrapper reaches past its `gas_limit < GAS_COST` -// pre-check and upstream verification then fails (invalid proof / mismatched -// version / wrong length), the recorded compute-gas equals exactly -// `KZG_GAS_COST`. The cap-induced OOG test pins that the -// wrapper-pre-check-OOG case does NOT take the fixed-cost arm. -// -// The `test_rex4_kzg_*` test is a stable-spec replay-preservation guard: REX4 -// records `0` on the same path. Changing that under REX4 would break -// byte-for-byte replay of historical blocks. - -/// Differential helper: run the same KZG-via-wrapper bytecode under REX4 and REX5 -/// and return both `(compute_gas_rex4, compute_gas_rex5)`. Both outer txs are -/// expected to succeed (the contract swallows the precompile failure). -fn run_kzg_wrapper_under_both_specs(input: Vec, forwarded_gas: u64) -> (u64, u64) { - let code = kzg_wrapper_bytecode(&input, forwarded_gas); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, compute_gas_rex5) = transact(MegaSpecId::REX5, &mut db, tx.clone()); - assert!( - result_rex5.result.is_success(), - "REX5 outer tx should succeed (KZG failure caught by CALL)" - ); - - let (result_rex4, compute_gas_rex4) = transact(MegaSpecId::REX4, &mut db, tx); - assert!( - result_rex4.result.is_success(), - "REX4 outer tx should succeed (KZG failure caught by CALL)" - ); - - (compute_gas_rex4, compute_gas_rex5) -} - -/// Verification failure with `BlobVerifyKzgProofFailed`: structurally valid -/// 192-byte input with the proof's last byte flipped. Wrapper's pre-check -/// passes, upstream verification rejects the proof. REX5 records exactly -/// `KZG_GAS_COST`; REX4 records 0. -#[test] -fn test_rex5_kzg_invalid_proof_records_exact_gas_cost() { - let forwarded_gas: u64 = 500_000; - let (compute_gas_rex4, compute_gas_rex5) = - run_kzg_wrapper_under_both_specs(invalid_proof_kzg_input(), forwarded_gas); - - let diff = compute_gas_rex5 - compute_gas_rex4; - assert_eq!( - diff, KZG_GAS_COST, - "REX5 must record exactly KZG_GAS_COST ({KZG_GAS_COST}) more compute gas than REX4 \ - on a failed-proof KZG call (REX5={compute_gas_rex5}, REX4={compute_gas_rex4}). \ - A diff > KZG_GAS_COST means the fixed-cost arm fell through to `limit()`; a \ - diff < KZG_GAS_COST means the fixed-cost arm did not fire." - ); -} - -/// Verification failure with `BlobMismatchedVersion`: versioned hash's first -/// byte forced to 0x02 so it disagrees with `VERSIONED_HASH_VERSION_KZG = 0x01`. -/// Wrapper's pre-check passes; upstream rejects on the version comparison -/// before the cryptographic verify runs. -#[test] -fn test_rex5_kzg_mismatched_version_records_exact_gas_cost() { - let forwarded_gas: u64 = 500_000; - let (compute_gas_rex4, compute_gas_rex5) = - run_kzg_wrapper_under_both_specs(mismatched_version_kzg_input(), forwarded_gas); - - let diff = compute_gas_rex5 - compute_gas_rex4; - assert_eq!( - diff, KZG_GAS_COST, - "REX5 must record exactly KZG_GAS_COST ({KZG_GAS_COST}) more compute gas than REX4 \ - on a mismatched-version KZG call (REX5={compute_gas_rex5}, REX4={compute_gas_rex4})." - ); -} - -/// Verification failure with `BlobInvalidInputLength`: 191-byte payload (one -/// byte short). Wrapper's pre-check passes; upstream rejects on the -/// `input.len() != 192` check. -#[test] -fn test_rex5_kzg_invalid_input_length_records_exact_gas_cost() { - let forwarded_gas: u64 = 500_000; - let (compute_gas_rex4, compute_gas_rex5) = - run_kzg_wrapper_under_both_specs(wrong_length_kzg_input(), forwarded_gas); - - let diff = compute_gas_rex5 - compute_gas_rex4; - assert_eq!( - diff, KZG_GAS_COST, - "REX5 must record exactly KZG_GAS_COST ({KZG_GAS_COST}) more compute gas than REX4 \ - on a wrong-length KZG call (REX5={compute_gas_rex5}, REX4={compute_gas_rex4})." - ); -} diff --git a/crates/mega-evm/tests/_pending/src/evm/factory.rs b/crates/mega-evm/tests/_pending/src/evm/factory.rs deleted file mode 100644 index 6e3a8b9da..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/factory.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/factory.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/factory.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_dyn_precompiles_builder_receives_the_behavior_spec() { - use alloy_evm::EvmFactory as _; - use core::sync::atomic::{AtomicU8, Ordering}; - - // The builder must see the behavior projection, never an alias rung: an external - // builder keyed on exact specs would otherwise install a different precompile set - // during a rollback window. - static SEEN_SPEC: AtomicU8 = AtomicU8::new(u8::MAX); - - let factory = - MegaEvmFactory::new().with_dyn_precompiles_builder(std::sync::Arc::new(|spec| { - SEEN_SPEC.store(spec as u8, Ordering::SeqCst); - revm::primitives::HashMap::default() - })); - - let mut evm_env = EvmEnv::::default(); - evm_env.cfg_env.spec = MegaSpecId::MINI_REX_1; - let _evm = factory.create_evm(crate::test_utils::MemoryDatabase::default(), evm_env); - - assert_eq!(SEEN_SPEC.load(Ordering::SeqCst), MegaSpecId::EQUIVALENCE as u8); - } -} diff --git a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs deleted file mode 100644 index 8f5e776b3..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs +++ /dev/null @@ -1,211 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/precompiles.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/precompiles.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - #[cfg(not(feature = "std"))] - use alloc as std; - use std::{rc::Rc, vec::Vec}; - - use super::{kzg_point_evaluation::GAS_COST, mini_rex, rex, MegaPrecompiles}; - use crate::{ - test_utils::MemoryDatabase, AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaSpecId, - }; - use alloy_evm::precompiles::PrecompilesMap; - use alloy_primitives::Bytes; - use core::cell::RefCell; - use revm::{ - handler::PrecompileProvider, - interpreter::{InputsImpl, InstructionResult}, - }; - use sha2::{Digest, Sha256}; - - /// Generate valid KZG Point Evaluation test data from EIP-4844 test vectors. - fn generate_kzg_test_input() -> InputsImpl { - let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); - let mut versioned_hash = Sha256::digest(&commitment).to_vec(); - versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG - let z = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000") - .unwrap(); - let y = hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9") - .unwrap(); - let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); - - let mut input = Vec::new(); - input.extend_from_slice(&versioned_hash); - input.extend_from_slice(&z); - input.extend_from_slice(&y); - input.extend_from_slice(&commitment); - input.extend_from_slice(&proof); - - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - InputsImpl { - target_address: address, - bytecode_address: Some(address), - caller_address: address, - input: revm::interpreter::CallInput::Bytes(Bytes::from(input)), - call_value: Default::default(), - } - } - - /// Mirror of `generate_kzg_test_input()` but with the last byte of the proof - /// flipped — structurally valid (192 bytes, matching versioned hash) but - /// upstream verification returns `PrecompileError::BlobVerifyKzgProofFailed`. - fn generate_invalid_proof_kzg_test_input() -> InputsImpl { - let mut inputs = generate_kzg_test_input(); - let bytes = match inputs.input { - revm::interpreter::CallInput::Bytes(b) => b, - _ => panic!("expected Bytes"), - }; - let mut buf = bytes.to_vec(); - let last = buf.len() - 1; - buf[last] ^= 0x01; - inputs.input = revm::interpreter::CallInput::Bytes(Bytes::from(buf)); - inputs - } - - fn set_spec_for_context( - precompiles_map: &mut PrecompilesMap, - _context: &MegaContext, - spec: op_revm::OpSpecId, - ) -> bool { - >>::set_spec( - precompiles_map, - spec, - ) - } - - #[test] - fn test_kzg_precompile_sufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - assert!(result.is_ok(), "Precompile should succeed with sufficient gas"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_exact_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST); - assert!(result.is_ok(), "Precompile should succeed with exact GAS_COST"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_set_spec_preserves_mega_kzg_override() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - - let changed = - set_spec_for_context(&mut precompiles_map, &context, op_revm::OpSpecId::ISTHMUS); - assert!(!changed, "Mega precompile table must remain unchanged"); - - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_insufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 50_000); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_one_below_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST - 1); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_zero_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 0); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - /// Replaces the context's `additional_limit` with one whose `tx_compute_gas_limit` - /// is set to `limit`, so tests can exercise the REX5 compute-gas cap path with a - /// small remaining budget without having to pre-record large gas amounts. - fn set_tx_compute_gas_limit( - context: &mut MegaContext, - spec: MegaSpecId, - limit: u64, - ) { - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: limit, - ..EvmTxRuntimeLimits::from_spec(spec) - }; - context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); - } - -} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 44eba54de..e4b10281d 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -8,6 +8,7 @@ mod inspector; mod intrinsic; mod outcome; mod precompile_gas; +mod pricing_table; mod schedule; mod state; mod static_callee; diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md new file mode 100644 index 000000000..70eb328a8 --- /dev/null +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -0,0 +1,80 @@ +# The Satin gas table + +Generated by `cargo test -p mega-evm --test satin`; the test compares this file to what it renders, so every number here is one the engine produced. + +## Schedule entries + +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8038 repricing pressed back to Osaka and the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those two applies. + +| Gas id | Osaka | Amsterdam | Satin | +|---|---:|---:|---:| +| exp_byte_gas | 50 | 50 | 50 | +| extcodecopy_per_word | 3 | 3 | 3 | +| copy_per_word | 3 | 3 | 3 | +| logdata | 8 | 8 | 8 | +| logtopic | 375 | 375 | 375 | +| mcopy_per_word | 3 | 3 | 3 | +| keccak256_per_word | 6 | 6 | 6 | +| memory_linear_cost | 3 | 3 | 3 | +| memory_quadratic_reduction | 512 | 512 | 512 | +| initcode_per_word | 2 | 2 | 2 | +| create | 32000 | 12000 | 32000 | +| call_stipend_reduction | 64 | 64 | 64 | +| transfer_value_cost | 9000 | 11300 | 9000 | +| cold_account_additional_cost | 2500 | 2900 | 2500 | +| new_account_cost | 25000 | 0 | 25000 | +| warm_storage_read_cost | 100 | 100 | 100 | +| sstore_static | 100 | 100 | 100 | +| sstore_set_without_load_cost | 19900 | 10000 | 19900 | +| sstore_reset_without_cold_load_cost | 2800 | 10000 | 2800 | +| sstore_clearing_slot_refund | 4800 | 11616 | 4800 | +| selfdestruct_refund | 0 | 0 | 0 | +| call_stipend | 2300 | 2300 | 2300 | +| cold_storage_additional_cost | 2000 | 2000 | 2000 | +| cold_storage_cost | 2100 | 2000 | 2100 | +| new_account_cost_for_selfdestruct | 25000 | 9000 | 25000 | +| code_deposit_cost | 200 | 0 | 0 | +| tx_eip7702_regular_gas | 25000 | 7816 | 7816 | +| tx_token_non_zero_byte_multiplier | 4 | 4 | 4 | +| tx_token_cost | 4 | 4 | 4 | +| tx_floor_cost_per_token | 10 | 16 | 16 | +| tx_floor_cost_base_gas | 21000 | 12000 | 12000 | +| tx_access_list_address_cost | 2400 | 4180 | 2400 | +| tx_access_list_storage_key_cost | 1900 | 4048 | 1900 | +| tx_base_stipend | 21000 | 21000 | 21000 | +| tx_create_cost | 32000 | 12000 | 32000 | +| tx_initcode_cost | 2 | 2 | 2 | +| sstore_set_refund | 19900 | 10000 | 19900 | +| sstore_reset_refund | 2800 | 10000 | 2800 | +| tx_eip7702_regular_refund | 12500 | 0 | 0 | +| sstore_set_state_gas | 0 | 97920 | 97920 | +| new_account_state_gas | 0 | 183600 | 183600 | +| code_deposit_state_gas | 0 | 1530 | 1530 | +| create_state_gas | 0 | 183600 | 183600 | +| tx_eip7702_state_gas_bytecode | 0 | 35190 | 35190 | +| tx_floor_token_zero_byte_multiplier | 1 | 4 | 4 | +| tx_access_list_floor_byte_multiplier | 0 | 4 | 4 | +| max_refund_quotient | 5 | 5 | 5 | +| tx_account_write_cost | 0 | 9000 | 9000 | +| tx_create_access_cost | 0 | 12000 | 12000 | +| code_deposit_history_gas | 0 | 0 | 0 | + +## Measured transactions + +One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's figure; the three ledgers below it are the raw spend split by what the gas paid for. + +| Probe | gas used | regular | state | history | +|---|---:|---:|---:|---:| +| empty call | 15000 | 15000 | 0 | 0 | +| value transfer to an existing account | 21000 | 21000 | 0 | 0 | +| self-transfer | 12000 | 12000 | 0 | 0 | +| SSTORE 0 -> 1 | 135026 | 37106 | 97920 | 0 | +| SSTORE 0 -> 1 -> 0 | 29770 | 37212 | 0 | 0 | +| value CALL to an empty account | 232921 | 49321 | 183600 | 0 | +| LOG1 with 32 data bytes | 16018 | 16018 | 0 | 0 | +| create transaction deploying 0 bytes | 207687 | 24087 | 183600 | 0 | +| create transaction deploying 32 bytes | 256668 | 24108 | 232560 | 0 | + +## The execution cap + +Satin pins `tx_gas_limit_cap` at 200000000, so a transaction's EIP-8037 reservoir is `max(0, gas_limit - intrinsic gas)` above it. Every probe above runs well below the cap, so its reservoir is empty and each state charge comes out of the regular budget. diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs new file mode 100644 index 000000000..794cd6bdd --- /dev/null +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -0,0 +1,253 @@ +//! The Satin schedule and what it charges, rendered into `pricing-table.md` next to this file. +//! +//! Two kinds of row. A *schedule* row reads one entry out of the Osaka, the Amsterdam and the +//! Satin schedules, so the two changes Satin makes are visible side by side. A *measured* row +//! runs one probe transaction and reports what it cost, split across the ledgers — every number +//! there comes from a transaction the engine ran, not from arithmetic on the schedule. +//! +//! The test renders the table and compares it to the checked-in file, so a change to either the +//! schedule or the engine that moves a number fails here. Regenerate it after an intentional +//! change: +//! +//! ```text +//! UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin +//! ``` + +use std::{fmt::Write as _, fs, path::Path}; + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + satin_gas_params, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaGasUsage, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CALL, LOG1, PUSH0, RETURN}, + context_interface::cfg::{GasId, GasParams}, + primitives::hardfork::SpecId, +}; + +use crate::common::{call, context, create}; + +const CALLER: Address = address!("0000000000000000000000000000000000b00000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000b00001"); +const FUNDED: Address = address!("0000000000000000000000000000000000b00002"); +const EMPTY: Address = address!("0000000000000000000000000000000000b00003"); + +/// Below the execution cap, so every probe's reservoir is empty and each state charge spills onto +/// the regular budget — which is why a probe's total includes its state column. +const GAS_LIMIT: u64 = 5_000_000; + +/// Where the rendered table lives. +fn table_path() -> &'static Path { + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/satin/pricing-table.md")) +} + +/// A database the probes run on: a funded sender, a funded account to transfer to, and a +/// contract running `code` with a balance of its own, so a probe's inner `CALL` can carry value. +fn db(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(FUNDED, U256::from(1)) + .account_balance(CONTRACT, U256::from(10u64.pow(9))) + .account_code(CONTRACT, code) +} + +/// One measured row. +struct Measured { + probe: &'static str, + gas: MegaGasUsage, +} + +/// Runs `tx` on `db` and reports what it spent by ledger. The probe must succeed. +fn measure(probe: &'static str, db: MemoryDatabase, tx: MegaTransaction) -> Measured { + let mut evm = MegaEvm::new(context(db)); + let outcome = evm.execute_transaction(tx).expect("the probe is valid"); + assert!(outcome.result.is_success(), "{probe}: {:?}", outcome.result); + Measured { probe, gas: outcome.gas } +} + +/// Runs `code` in `CONTRACT` as a plain call from `CALLER`. +fn measure_call(probe: &'static str, code: BytecodeBuilder) -> Measured { + let code = code.stop().build(); + measure(probe, db(code), call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)) +} + +/// Runs a creation transaction whose init code deploys `len` bytes of zeros. +fn measure_create(probe: &'static str, len: u64) -> Measured { + let init_code = + BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build(); + measure(probe, db(Bytes::new()), create(CALLER, init_code, GAS_LIMIT)) +} + +/// `CALL(gas, target, value, 0, 0, 0, 0)`. +fn value_call(target: Address) -> BytecodeBuilder { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(target) + .push_number(1_000_000u64) + .append(CALL) +} + +fn sstore(slot: u64, value: u64) -> BytecodeBuilder { + BytecodeBuilder::default().sstore(U256::from(slot), U256::from(value)) +} + +fn render() -> String { + let osaka = GasParams::new_spec(SpecId::OSAKA); + let amsterdam = GasParams::new_spec(SpecId::AMSTERDAM); + let satin = satin_gas_params(); + + let mut out = String::new(); + out.push_str("# The Satin gas table\n\n"); + out.push_str( + "Generated by `cargo test -p mega-evm --test satin`; the test compares this file to what \ + it renders, so every number here is one the engine produced.\n\n", + ); + + out.push_str("## Schedule entries\n\n"); + out.push_str( + "Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam \ + devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8038 repricing \ + pressed back to Osaka and the EIP-8037 state entries rebuilt at `MegaETH`'s cost per \ + state byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one \ + of those two applies.\n\n", + ); + out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); + for slot in 0..=u8::MAX { + let id = GasId::new(slot); + let name = id.name(); + if name == "unknown" { + continue; + } + let _ = writeln!( + out, + "| {name} | {} | {} | {} |", + osaka.get(id), + amsterdam.get(id), + satin.get(id) + ); + } + + out.push_str("\n## Measured transactions\n\n"); + let _ = writeln!( + out, + "One probe transaction each, at a {GAS_LIMIT} gas limit. `gas used` is the receipt's \ + figure; the three ledgers below it are the raw spend split by what the gas paid for.\n" + ); + out.push_str("| Probe | gas used | regular | state | history |\n|---|---:|---:|---:|---:|\n"); + for row in measured() { + let _ = writeln!( + out, + "| {} | {} | {} | {} | {} |", + row.probe, row.gas.gas_used, row.gas.regular, row.gas.state, row.gas.history + ); + } + + out.push_str("\n## The execution cap\n\n"); + let _ = writeln!( + out, + "Satin pins `tx_gas_limit_cap` at {TX_GAS_LIMIT_CAP}, so a transaction's EIP-8037 \ + reservoir is `max(0, gas_limit - intrinsic gas)` above it. Every probe above runs well \ + below the cap, so its reservoir is empty and each state charge comes out of the regular \ + budget." + ); + out +} + +/// The probes, in the order the table lists them. +fn measured() -> Vec { + vec![ + measure("empty call", db(Bytes::new()), call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)), + measure( + "value transfer to an existing account", + db(Bytes::new()), + call(CALLER, FUNDED, U256::from(1), GAS_LIMIT), + ), + measure("self-transfer", db(Bytes::new()), call(CALLER, CALLER, U256::from(1), GAS_LIMIT)), + measure_call("SSTORE 0 -> 1", sstore(0, 1)), + measure_call( + "SSTORE 0 -> 1 -> 0", + BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO), + ), + measure_call("value CALL to an empty account", value_call(EMPTY)), + measure_call( + "LOG1 with 32 data bytes", + BytecodeBuilder::default() + .push_number(0u64) + .push_number(32u64) + .push_number(0u64) + .append(LOG1), + ), + measure_create("create transaction deploying 0 bytes", 0), + measure_create("create transaction deploying 32 bytes", 32), + ] +} + +/// The rendered table is the one checked in. `UPDATE_SATIN_PRICING_TABLE=1` writes it instead. +#[test] +fn test_the_pricing_table_is_up_to_date() { + let rendered = render(); + let path = table_path(); + if std::env::var_os("UPDATE_SATIN_PRICING_TABLE").is_some() { + fs::write(path, &rendered).expect("the table is writable"); + return; + } + let checked_in = fs::read_to_string(path).expect("the table is checked in"); + assert_eq!( + checked_in, rendered, + "pricing-table.md is out of date; regenerate it with \ + UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin" + ); +} + +/// The schedule section covers every entry, and the entries Satin moves are the ones the two +/// rules name and no others — read off the rendered table rather than the schedule, so the table +/// cannot drift from what it claims. +#[test] +fn test_the_table_shows_where_satin_differs_from_amsterdam() { + let rendered = render(); + let differing: Vec<&str> = rendered + .lines() + .filter(|line| line.starts_with("| ") && line.matches('|').count() == 5) + .filter_map(|line| { + let mut cells = line.split('|').map(str::trim).skip(1); + let name = cells.next()?; + let (_osaka, amsterdam, satin) = (cells.next()?, cells.next()?, cells.next()?); + (name != "Gas id" && amsterdam != satin).then_some(name) + }) + .collect(); + + // The pressed-back entries whose Osaka and Amsterdam prices are not the same number. The + // other three of the seventeen — `warm_storage_read_cost`, `sstore_static` and + // `cold_storage_additional_cost` — EIP-8038 left where they were, so pressing them back + // moves nothing. The state entries are rebuilt rather than copied, and land on Amsterdam's + // numbers because the provisional cost per state byte is the one Glamsterdam uses. + assert_eq!( + differing, + [ + "create", + "transfer_value_cost", + "cold_account_additional_cost", + "new_account_cost", + "sstore_set_without_load_cost", + "sstore_reset_without_cold_load_cost", + "sstore_clearing_slot_refund", + "cold_storage_cost", + "new_account_cost_for_selfdestruct", + "tx_access_list_address_cost", + "tx_access_list_storage_key_cost", + "tx_create_cost", + "sstore_set_refund", + "sstore_reset_refund", + ], + "the entries Satin prices differently from Amsterdam" + ); +} diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 350429316..040a1e533 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -127,6 +127,32 @@ fn deploying(len: u64) -> Bytes { BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() } +/// A creation that reverts deposits nothing, so it draws no state gas at all: neither the +/// created account's nor the code's. The state gas a creation draws is charged on the deposit, +/// not on the attempt. +#[test] +fn test_a_reverted_creation_draws_no_state_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let mut evm = MegaEvm::new(context(db)); + let init_code = BytecodeBuilder::default().mstore(0, [0u8; 32]).revert().build(); + let result = evm + .transact_raw(create(CALLER, init_code, GAS_LIMIT)) + .expect("the transaction is valid") + .result; + + assert!(!result.is_success(), "{result:?}"); + assert_eq!(result.gas().state_gas_spent_final(), 0); +} + +/// A creation that deposits nothing — empty runtime code — still pays for the account it +/// created, and nothing for code. +#[test] +fn test_a_creation_depositing_no_code_pays_for_the_account_alone() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let spent = spend(db, create(CALLER, deploying(0), GAS_LIMIT)); + assert_eq!(spent.state, ACCOUNT_STATE_GAS); +} + /* ---------- the Amsterdam opcodes ---------- */ /// Runs `code` in `CALLEE` and returns the result, so a gated opcode shows up as a halt. From 08b29d3adc070a5884de5e32f07a3179663ec4a1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:25:24 +0800 Subject: [PATCH 100/201] docs: describe the Satin gas schedule, its prices and the precompile set The module table gains the schedule, the byte prices and the precompile set; the execution notes say what the schedule changes, which Amsterdam opcodes the table activates and how a measurement build reprices; the constants table names the schedule as their reader. Prettier reflowed the module table's column widths. REVIEW.md gains the rule that the pricing table is generated, not hand-edited. --- AGENTS.md | 36 +++++++++++++++++++++++------------- REVIEW.md | 2 ++ crates/mega-evm/README.md | 10 +++++++++- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b5d356df..612006204 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,12 @@ cargo test # all tests cargo test -p mega-evm # core crate only cargo test -p mega-evm -- test_name # single test +# The gas schedule's byte prices are an input; this feature lets a measurement build change them +cargo test -p mega-evm --features satin-price-override,test-utils + +# Regenerate the checked-in pricing table after an intentional schedule or engine change +UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin + # Check compiler errors (preferred over clippy for quick checks) cargo check cargo check -p mega-evm @@ -84,25 +90,29 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton, `BlockGasCounters` (`result.rs`) | the block executor (Karst block rules, filling `BlockGasCounters`, refusing `has_rewriting_inspector`), the pre-block system calls, the system contract deployments | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | -| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds now | Filled by | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton, `BlockGasCounters` (`result.rs`) | the block executor (Karst block rules, filling `BlockGasCounters`, refusing `has_rewriting_inspector`), the pre-block system calls, the system contract deployments | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today - `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. -- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off, the contract size limit at 512 KiB and the initcode size limit at 1 MiB. Gas above the 200M execution cap goes to the EIP-8037 reservoir. - The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. +- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the seventeen entries EIP-8038 repriced go back to their Osaka values, and the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte. + It is built once per process and installed on every configuration; the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. + `crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, and what nine probe transactions spent; a test renders it and compares it to the file. +- The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the metering wrappers go in; `CLZ` is gated on Osaka and needs no activation. +- The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000, carried as an alloy-evm `PrecompilesMap` so a node can add or replace an address (`MegaEvmFactory::with_dyn_precompiles_builder`). - `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. diff --git a/REVIEW.md b/REVIEW.md index d9f47b9ed..d024042d7 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -59,6 +59,8 @@ This is the single most important correctness concern in mega-evm. Their comments — especially the `file:line:col` mutation-location references — must be kept up to date when the referenced source moves. Flag any PR that shifts lines in a mutated source file but leaves a now-stale location reference (or an orphaned/renamed test) in `tests/mutation/`; a reference that no longer points at its mutant defeats the purpose of the linkage. These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. +- `crates/mega-evm/tests/satin/pricing-table.md` is generated by its own test, not written by hand. + A change that moves a number in it must regenerate the file (`UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin`) and explain the movement; a hand-edited row hides the change it was meant to surface. - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. Missing the required explicit hardfork pin can silently bench the wrong fork when a shared bench subject defaults to a different one. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 9c14e8727..42127bb61 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -26,13 +26,21 @@ The legacy spec names do not parse: `"Rex6".parse::()` fails with `P Satin is under construction. Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. -It still uses the Osaka gas table, which prices state gas at zero, so no transaction draws state gas yet. + +The gas schedule is Amsterdam's with two changes: the entries EIP-8038 repriced go back to their Osaka values, and the EIP-8037 state-gas entries are rebuilt from MegaETH's own cost per state byte, so a new storage slot draws 97,920 state gas and a new account 183,600. +The schedule also brings the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`) and raises the code-size limits to 512 KiB of contract and 1 MiB of initcode. +Its byte prices are an input: the `satin-price-override` feature, off by default, lets a measurement build install other ones. +`tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, with what a handful of probe transactions spent. + +The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000. +It is carried as an alloy-evm `PrecompilesMap`, so a node can add or replace an address through `MegaEvmFactory::with_dyn_precompiles_builder`. The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the abort protocol that stops a transaction crossing a limit with a revert, and the inspector admission gate. No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. `MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. +Until history gas lands, nothing prices a history byte and the schedule's history entry stays at zero. ## Quick start From 82fdd6890078453d19c0ec747559099b052686a8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:26:47 +0800 Subject: [PATCH 101/201] style: drop the trailing blank line the gas file kept after its port --- crates/mega-evm/tests/_pending/mini_rex/gas.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/mega-evm/tests/_pending/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs index 3c7ccda23..f4f6d2ab3 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -795,4 +795,3 @@ fn floor_gas_test_case(spec: MegaSpecId, calldata_size: usize, expected_gas_used let gas_used = res.result.gas_used(); assert_eq!(gas_used, expected_gas_used); } - From b8d876832ca31af820b47532a4d73f39a65dd36f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:32:01 +0800 Subject: [PATCH 102/201] test(block): pin the block rules, the counters and the admission gate A test target of its own for block execution, with the three rules each on its own fixture: an activation block that refuses a user transaction and executes a deposit; a data-availability footprint that is inert without a scalar, is reported as the block's blob gas with one, and refuses a transaction that does not fit the block's budget; an L1 block info read that answers zeroes on an empty contract and leaves a caller's own info for this block alone. The operator fee pins the Karst formula, which multiplies where the earlier one divides to zero. The counters: a block sums each ledger of its transactions, the result carries the three of them next to the footprint, the execution dimension packs the transaction that crosses its limit and refuses the next, and the state and history ledgers refuse nothing. The admission gate: a declared observer reaches a block, an undeclared inspector is refused before the block's first call, and a disabled one is admitted because it rewrites nothing. Ports the 23 parked rows of block execution: the block limits, the deposit data-availability exemption, the accessed block hashes, the factory's runtime limits, the canonical schedules and the params validation at load. The two rows whose KV limit semantics are undecided stay parked. --- crates/mega-evm/src/block/executor.rs | 41 +- crates/mega-evm/tests/_pending/README.md | 21 +- .../block_executor/accessed_block_hashes.rs | 110 --- .../_pending/block_executor/block_limits.rs | 919 +----------------- .../block_executor/canonical_schedule.rs | 150 --- .../block_executor/deposit_da_exemption.rs | 342 ------- .../tests/_pending/block_executor/main.rs | 4 - .../trait_factory_runtime_limits.rs | 227 ----- .../rex6/sequencer_registry_rotation.rs | 21 - crates/mega-evm/tests/block/block_hashes.rs | 62 ++ crates/mega-evm/tests/block/common.rs | 211 ++++ crates/mega-evm/tests/block/counters.rs | 139 +++ crates/mega-evm/tests/block/factory.rs | 101 ++ crates/mega-evm/tests/block/inspector.rs | 84 ++ crates/mega-evm/tests/block/limits.rs | 460 +++++++++ crates/mega-evm/tests/block/main.rs | 10 + crates/mega-evm/tests/block/rules.rs | 218 +++++ crates/mega-evm/tests/block/schedule.rs | 93 ++ 18 files changed, 1422 insertions(+), 1791 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs create mode 100644 crates/mega-evm/tests/block/block_hashes.rs create mode 100644 crates/mega-evm/tests/block/common.rs create mode 100644 crates/mega-evm/tests/block/counters.rs create mode 100644 crates/mega-evm/tests/block/factory.rs create mode 100644 crates/mega-evm/tests/block/inspector.rs create mode 100644 crates/mega-evm/tests/block/limits.rs create mode 100644 crates/mega-evm/tests/block/main.rs create mode 100644 crates/mega-evm/tests/block/rules.rs create mode 100644 crates/mega-evm/tests/block/schedule.rs diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 7306654d6..b0c2b660a 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -27,7 +27,7 @@ #[cfg(not(feature = "std"))] use alloc as std; use core::fmt; -use std::{boxed::Box, vec::Vec}; +use std::{boxed::Box, collections::BTreeMap, vec::Vec}; use alloy_consensus::{Eip658Value, Header, Transaction, TransactionEnvelope, TxReceipt}; use alloy_eips::{eip7685::Requests, Encodable2718, Typed2718}; @@ -58,9 +58,9 @@ pub type MegaFinishedBlock = (MegaEvm, MegaBlockExecutionResult<::Receipt>); use crate::{ - block::eips, estimated_da_size, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, - MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, - MegaTransaction, MegaTransactionExt, + block::eips, estimated_da_size, BlockGasCounters, BlockHashes, BlockLimiter, BlockLimits, + ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, + MegaHardforks, MegaTransaction, MegaTransactionExt, }; /// What the node hands block execution beside the EVM. @@ -279,6 +279,26 @@ where } } +impl MegaBlockExecutor, R, Spec> +where + DB: Database + BlockHashes, + ExtEnvs: ExternalEnvTypes, + R: OpReceiptBuilder, +{ + /// The block hashes the block's transactions have read so far. + /// + /// `BLOCKHASH` reads bypass the journal, so this is where a stateless witness learns of them. + pub fn get_accessed_block_hashes(&self) -> BTreeMap { + self.evm.get_accessed_block_hashes() + } + + /// Forgets the block hashes read so far, so the next reads are attributable to one + /// transaction. The record is a cache, so clearing it changes no execution result. + pub fn clear_accessed_block_hashes(&mut self) { + self.evm.clear_accessed_block_hashes(); + } +} + impl BlockExecutor for MegaBlockExecutor, R, Spec> where @@ -523,18 +543,19 @@ where ); (inner.trie_hash(), inner.encode_2718_len() as u64, da_size) }, - |reported| { + |(tx_hash, tx_size, da_size)| { + // Only the sizes are cross-checked: they are what the limits are stated over. + // The hash names the transaction in an error and decides nothing. debug_assert_eq!( - reported, + (tx_size, da_size), ( - inner.trie_hash(), inner.encode_2718_len() as u64, estimated_da_size(inner.encoded_2718().as_ref()), ), - "the transaction's reported hash and sizes do not match a fresh recompute \ - from the encoded transaction" + "the transaction's reported sizes do not match a fresh recompute from the \ + encoded transaction" ); - reported + (tx_hash, tx_size, da_size) }, ); let gas_limit = inner.gas_limit(); diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index f076a18f2..384752abc 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -40,10 +40,9 @@ Do not add a `_pending/main.rs`. | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| the block executor | 23 | 23 | 0 | 18 | 5 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **717** | **624** | **93** | **405** | **284** | **28** | +| **Total** | **694** | **601** | **93** | **387** | **279** | **28** | ## Tests ported in place @@ -132,10 +131,16 @@ These 45 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by the block executor -These 30 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. +These 53 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| +| `block_executor/accessed_block_hashes.rs` | the block executor (1) | 1 | `tests/block/block_hashes.rs` | +| `block_executor/block_limits.rs` | the block executor (12) | 12 | `tests/block/limits.rs` | +| `block_executor/canonical_schedule.rs` | the block executor (1) | 1 | `tests/block/schedule.rs` | +| `block_executor/deposit_da_exemption.rs` | the block executor (4) | 4 | `tests/block/limits.rs` | +| `block_executor/trait_factory_runtime_limits.rs` | the block executor (4) | 4 | `tests/block/factory.rs` | +| `rex6/sequencer_registry_rotation.rs` | the block executor (1) | 1 | `tests/block/schedule.rs` | | `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | | `src/block/eips.rs` | the block executor (1) | 1 | `src/block/eips.rs` | | `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | @@ -144,7 +149,7 @@ These 30 rows run in a real test target now, adapted to the Satin API, so the co | `src/block/result.rs` | the block executor (2) | 2 | `src/block/result.rs` | | `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | -| **Total** | | **30** | | +| **Total** | | **53** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -159,13 +164,9 @@ Each cell lists `disposition count (mechanism · decision)`. | File | Tests | Owners | |---|---:|---| -| `block_executor/accessed_block_hashes.rs` | 1 | keep 1 (the block executor) | -| `block_executor/block_limits.rs` | 14 | keep 12 (the block executor · D47); undecided 2 (the state-growth and KV limits · D46) | -| `block_executor/canonical_schedule.rs` | 1 | rewrite 1 (the block executor · single Satin fork; the specification pages own the doc side) | -| `block_executor/deposit_da_exemption.rs` | 4 | keep 4 (the block executor · D23) | +| `block_executor/block_limits.rs` | 2 | undecided 2 (the state-growth and KV limits · D46) | | `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | | `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | -| `block_executor/trait_factory_runtime_limits.rs` | 4 | rewrite 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | | `compute_gas/claims.rs` | 14 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); keep 1 (the Satin gas table · D04 (KZG 100k)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 2 (the Satin gas table · D13); rewrite 1 (the Satin gas table · D11); rewrite 1 (the data-size limit · D33/D48) | | `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | | `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | @@ -230,7 +231,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | | `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | -| `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | +| `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | diff --git a/crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs b/crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs deleted file mode 100644 index a1be5fcd7..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Tests for block hash access tracking on `MegaBlockExecutor`. -//! -//! `get_accessed_block_hashes` exposes the executor database's block hash record, -//! which accumulates across every transaction executed so far. -//! `clear_accessed_block_hashes` resets it so callers can attribute BLOCKHASH -//! reads to a single transaction (the replay fixture dump relies on this). - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{BLOCKHASH, POP}, - context::BlockEnv, - database::State, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const BLOCKHASH_CONTRACT: Address = address!("1000000000000000000000000000000000000001"); -const PLAIN_CONTRACT: Address = address!("1000000000000000000000000000000000000002"); - -fn create_transaction( - nonce: u64, - to: Address, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit: 1_000_000, - to: TxKind::Call(to), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Contract that reads `BLOCKHASH(999)` (one below the block number used in the -/// test) and discards it. -fn create_blockhash_contract() -> Bytes { - BytecodeBuilder::default().push_number(999u16).append(BLOCKHASH).append(POP).stop().build() -} - -#[test] -fn test_accessed_block_hashes_track_and_clear_per_transaction() { - let mut db = MemoryDatabase::default(); - db.set_account_code(BLOCKHASH_CONTRACT, create_blockhash_contract()); - db.set_account_code(PLAIN_CONTRACT, BytecodeBuilder::default().stop().build()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm = evm_factory.create_evm(&mut state, EvmEnv::new(cfg_env, block_env)); - - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let mut executor = - MegaBlockExecutor::new(evm, block_ctx, chain_spec, OpAlloyReceiptBuilder::default()); - - // A transaction that reads BLOCKHASH leaves its access in the record. - executor - .execute_transaction(&create_transaction(0, BLOCKHASH_CONTRACT)) - .expect("blockhash tx should succeed"); - let accessed = executor.get_accessed_block_hashes(); - assert_eq!(accessed.len(), 1, "BLOCKHASH read should be recorded"); - assert!(accessed.contains_key(&999), "the queried block number should be recorded"); - - // Clearing resets the record without affecting subsequent execution. - executor.clear_accessed_block_hashes(); - assert!(executor.get_accessed_block_hashes().is_empty(), "record should be empty after clear"); - - // A transaction that never reads BLOCKHASH leaves the cleared record empty, - // even though an earlier transaction in the same block read one. - executor - .execute_transaction(&create_transaction(1, PLAIN_CONTRACT)) - .expect("plain tx should succeed"); - assert!( - executor.get_accessed_block_hashes().is_empty(), - "a transaction without BLOCKHASH reads must not repopulate the record" - ); - - // A fresh BLOCKHASH read after the clear is attributed to that transaction. - executor - .execute_transaction(&create_transaction(2, BLOCKHASH_CONTRACT)) - .expect("second blockhash tx should succeed"); - assert_eq!(executor.get_accessed_block_hashes().len(), 1); -} diff --git a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs index 7b22aef97..d2daaedcd 100644 --- a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs +++ b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs @@ -43,22 +43,6 @@ fn create_transaction( alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) } -/// Like [`create_transaction`], but returns the bare envelope so callers can build a -/// `Recovered<&MegaTxEnvelope>` (needed for `EnrichedMegaTx: Copy`, which requires `T: Copy`). -fn create_envelope(nonce: u64, gas_limit: u64) -> MegaTxEnvelope { - let tx_legacy = TxLegacy { - chain_id: Some(8453), // Base mainnet - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - MegaTxEnvelope::Legacy(signed) -} - /// Creates a contract that generates a log with specified data size. /// /// The contract will emit LOG0 with the specified number of zero bytes. @@ -124,209 +108,6 @@ fn create_sstore_contract(num_writes: usize) -> Bytes { builder.stop().build() } -#[test] -fn test_block_custom_data_limit() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(2000); // 2 KB log - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with VERY LOW custom data limit - // New behavior: The first transaction that exceeds the limit is allowed, - // but subsequent transactions are rejected in pre-execution - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_data_limit(2_500), - ); // 2.5 KB data limit - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute first transaction (should succeed and likely exceed the limit) - let tx1 = create_transaction(0, 1_000_000); - let result1 = executor.execute_transaction(&tx1); - assert!(result1.is_ok(), "First transaction should succeed"); - assert!(result1.unwrap() < tx1.gas_limit(), "Gas used should be less than gas limit"); - - // Execute second transaction (should succeed, causing block to exceed limit) - let tx2 = create_transaction(1, 1_000_000); - let result2 = executor.execute_transaction(&tx2); - assert!(result2.is_ok(), "Second transaction should succeed (last tx can exceed limit)"); - assert!(result2.unwrap() < tx2.gas_limit(), "Gas used should be less than gas limit"); - - // Execute third transaction (should fail due to block data limit already exceeded) - let tx3 = create_transaction(2, 1_000_000); - let result3 = executor.execute_transaction(&tx3); - assert!(result3.is_err(), "Third transaction should fail due to block data limit"); - let err_msg = format!("{:?}", result3.unwrap_err()); - assert!( - err_msg.contains("TransactionDataLimit"), - "Error should mention TransactionDataLimit, got: {}", - err_msg - ); -} - -/// `MegaBlockExecutor::run_transaction` resolves `tx_size`/`da_size` through `MegaTransactionExt`, -/// so an `EnrichedMegaTx` feeds its cached values into the pre-execution limit check instead of a -/// fresh recompute (see the method's "Correctness" doc section). Its `debug_assert` cross-checks -/// the resolved values against a fresh recompute, so a caller bug — here a deliberately understated -/// stored `da_size` — is caught immediately in debug/test builds instead of silently letting a -/// transaction bypass a limit it should have been rejected by. -/// -/// A freshly recomputed DA size for any legacy tx is always >= 100 bytes (the `op_alloy_flz` -/// minimum-size floor), so a `tx_da_size_limit` of 80 rejects a bare `Recovered<&MegaTxEnvelope>` -/// (which uses the recomputing default). An `EnrichedMegaTx` carrying a deliberately understated -/// stored `da_size` of 50 would pass that same limit using the cached value, but the `debug_assert` -/// trips on the mismatch first. -/// -/// `#[cfg(debug_assertions)]`: this test exercises the `debug_assert` itself, which is compiled -/// out in release builds — under `cargo test --release` the same call would not panic and would -/// instead silently succeed using the understated cached value. That is the documented, -/// deliberate trade-off on `run_transaction` (see its "Correctness" doc section): the cache -/// contract is enforced in debug/test builds only, at zero cost in release. -#[cfg(debug_assertions)] -#[test] -#[should_panic(expected = "does not match a fresh recompute")] -fn test_run_transaction_rejects_understated_cached_da_size() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - let evm = evm_factory.create_evm(&mut state, evm_env); - - const TX_DA_SIZE_LIMIT: u64 = 80; - const STORED_DA_SIZE: u64 = 50; - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_tx_da_size_limit(TX_DA_SIZE_LIMIT), - ); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - let envelope = create_envelope(0, 100_000); - let real_da_size = MegaTransactionExt::estimated_da_size(&envelope); - assert!( - real_da_size > TX_DA_SIZE_LIMIT, - "test setup requires the freshly recomputed da_size ({real_da_size}) to exceed the limit" - ); - const { assert!(STORED_DA_SIZE < TX_DA_SIZE_LIMIT, "stored da_size must pass the limit") }; - - let recovered = alloy_consensus::transaction::Recovered::new_unchecked(&envelope, CALLER); - - // A bare (non-enriched) transaction uses the recomputing default and is rejected. - let plain_result = executor.run_transaction(&recovered); - assert!( - plain_result.is_err(), - "bare transaction should be rejected: real da_size exceeds the limit" - ); - - // An `EnrichedMegaTx` with an understated stored `da_size` would pass the limit using the - // cached value, but `run_transaction`'s debug_assert catches the mismatch and panics instead - // of silently letting it through. `tx_size` is stored accurately here so the assert trips on - // `da_size` alone. - let real_tx_size = MegaTransactionExt::tx_size(&envelope); - let enriched = - EnrichedMegaTx::new(recovered, envelope.trie_hash(), STORED_DA_SIZE, real_tx_size); - let _ = executor.run_transaction(enriched); -} - -/// `MegaBlockExecutor::execute_mega_transaction` (the alias for -/// [`MegaBlockExecutor::run_transaction`]) must succeed and produce an outcome carrying the cached -/// fields when they accurately reflect the wrapped transaction — the intended, common-case usage, -/// as opposed to the deliberately mismatched cache exercised above. -#[test] -fn test_execute_mega_transaction_succeeds_with_accurate_cache() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - let evm = evm_factory.create_evm(&mut state, evm_env); - - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - let envelope = create_envelope(0, 1_000_000); - let expected_da_size = MegaTransactionExt::estimated_da_size(&envelope); - let expected_tx_size = MegaTransactionExt::tx_size(&envelope); - let recovered = alloy_consensus::transaction::Recovered::new_unchecked(&envelope, CALLER); - let enriched = EnrichedMegaTx::new_slow(recovered); - - let outcome = executor - .execute_mega_transaction(enriched) - .expect("accurate cached values must satisfy the debug_assert and succeed normally"); - assert_eq!(outcome.da_size, expected_da_size, "outcome da_size must match the accurate cache"); - assert_eq!(outcome.tx_size, expected_tx_size, "outcome tx_size must match the accurate cache"); -} - #[test] fn test_block_custom_kv_update_limit() { // Create database and deploy contract @@ -390,142 +171,6 @@ fn test_block_custom_kv_update_limit() { ); } -#[test] -fn test_block_multiple_transactions_within_limits() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); // 100 bytes per tx - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with reasonable limits - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits() - .with_block_txs_data_limit(10_000) - .with_block_kv_update_limit(1_000), - ); // 10 KB data limit and 1000 KV update limit - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute 5 transactions, all should succeed - for nonce in 0..5 { - let tx = create_transaction(nonce, 1_000_000); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction {} should succeed", nonce); - assert!(result.unwrap() < tx.gas_limit(), "Gas used should be less than gas limit"); - } - - // Finish the block and get receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 5, "Should have 5 receipts"); -} - -#[test] -fn test_block_data_limit_exceeded_mid_block() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(2000); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with ~6 KB limit - // The transaction that causes the block to exceed the limit is allowed, - // but the next transaction is rejected - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_data_limit(6_000), - ); // 6 KB data limit - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute first transaction (should succeed) - let result1 = executor.execute_transaction(&create_transaction(0, 1_000_000)); - assert!(result1.is_ok(), "First transaction should succeed"); - - // Execute second transaction (should succeed) - let result2 = executor.execute_transaction(&create_transaction(1, 1_000_000)); - assert!(result2.is_ok(), "Second transaction should succeed"); - - // Execute third transaction (should succeed, likely causing block to exceed limit) - let result3 = executor.execute_transaction(&create_transaction(2, 1_000_000)); - assert!(result3.is_ok(), "Third transaction should succeed (last tx can exceed limit)"); - - // Execute fourth transaction (should fail due to block data limit already exceeded) - let result4 = executor.execute_transaction(&create_transaction(3, 1_000_000)); - assert!(result4.is_err(), "Fourth transaction should fail due to block data limit"); - - // Finish the block - should have 3 receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 3, "Should have 3 receipts (4th tx failed)"); -} - #[test] fn test_block_kv_limit_exceeded_mid_block() { // Create database and deploy contract with minimal SSTORE operations @@ -594,566 +239,6 @@ fn test_block_kv_limit_exceeded_mid_block() { assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt (2nd tx failed)"); } -#[test] -fn test_block_no_state_commit_on_limit_exceeded() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(42u8) // value - .append(PUSH0) // key (slot 0) - .append(SSTORE) // SSTORE - .stop() - .build(); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); +const CALLER2: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); +const CALLER3: alloy_primitives::Address = address!("4000000000000000000000000000000000000004"); - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with VERY low KV update limit - // With new behavior, we need to set limit to 0 to ensure no transactions can be added - // Setting to 0 means block_kv_updates_used (0) >= limit (0) is true from the start - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_kv_update_limit(0), - ); // Zero limit - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute transaction (should fail due to KV limit of 0) - let result = executor.execute_transaction(&create_transaction(0, 10_000_000)); - assert!(result.is_err(), "Transaction should fail due to block KV update limit of 0"); - - // Verify storage slot 0 is NOT set in the database - let db_state = executor.evm_mut().db_mut(); - let _ = db_state.load_cache_account(CONTRACT); - let value = db_state.storage(CONTRACT, U256::ZERO).expect("Storage access should not fail"); - - // The storage should be zero (not 42) since the transaction was not committed - assert_eq!(value, U256::ZERO, "Storage should not be committed"); - - // Finish the block - should have 0 receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 0, "Should have 0 receipts (tx rejected in pre-execution)"); -} - -#[test] -fn test_block_tx_size_limit_default_unlimited() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with default limits (tx size should be u64::MAX) - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - assert_eq!( - block_ctx.block_limits.block_txs_encode_size_limit, - u64::MAX, - "Default tx size limit should be u64::MAX" - ); - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute multiple transactions - should all succeed with unlimited size - for nonce in 0..10 { - let tx = create_transaction(nonce, 1_000_000); - let result = executor.execute_transaction(&tx); - assert!( - result.is_ok(), - "Transaction {} should succeed with unlimited tx size limit", - nonce - ); - } - - // Finish the block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 10, "Should have 10 receipts"); -} - -#[test] -fn test_block_tx_size_limit_allows_multiple_transactions() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create a transaction to measure its size - let sample_tx = create_transaction(0, 1_000_000); - let tx_size = sample_tx.encode_2718_len() as u64; - - // Set limit to allow exactly 5 transactions - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_encode_size_limit(tx_size * 5), - ); - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute 5 transactions - should all succeed - for nonce in 0..5 { - let tx = create_transaction(nonce, 1_000_000); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction {} should succeed", nonce); - } - - // Finish the block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 5, "Should have 5 receipts"); -} - -#[test] -fn test_block_tx_size_limit_exceeded_first_transaction() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Set a very small tx size limit that won't fit even one transaction - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_encode_size_limit(10), - ); // Very small limit - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute transaction (should fail immediately due to tx size limit) - let result = executor.execute_transaction(&create_transaction(0, 1_000_000)); - assert!(result.is_err(), "Transaction should fail due to tx size limit"); - - let err_msg = format!("{:?}", result.unwrap_err()); - assert!( - err_msg.contains("TransactionEncodeSizeLimit"), - "Error should mention TransactionEncodeSizeLimit, got: {}", - err_msg - ); - - // Finish the block - should have 0 receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 0, "Should have 0 receipts (tx failed)"); -} - -#[test] -fn test_block_tx_size_limit_exceeded_mid_block() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create a transaction to measure its size - let sample_tx = create_transaction(0, 1_000_000); - let tx_size = sample_tx.encode_2718_len() as u64; - - // Set limit to allow exactly 3 transactions - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_encode_size_limit(tx_size * 3), - ); - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute first 3 transactions (should all succeed) - for nonce in 0..3 { - let tx = create_transaction(nonce, 1_000_000); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction {} should succeed", nonce); - } - - // Execute 4th transaction (should fail due to tx size limit) - let result = executor.execute_transaction(&create_transaction(3, 1_000_000)); - assert!(result.is_err(), "Fourth transaction should fail due to tx size limit"); - - let err_msg = format!("{:?}", result.unwrap_err()); - assert!( - err_msg.contains("TransactionEncodeSizeLimit"), - "Error should mention TransactionEncodeSizeLimit, got: {}", - err_msg - ); - - // Finish the block - should have 3 receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 3, "Should have 3 receipts (4th tx failed)"); -} - -const CALLER2: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); -const CALLER3: alloy_primitives::Address = address!("4000000000000000000000000000000000000004"); - -/// Helper function to create a recovered transaction with a specific caller. -fn create_transaction_with_caller( - caller: alloy_primitives::Address, - nonce: u64, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), // Base mainnet - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, caller) -} - -/// Tests that the commit-time `pre_execution_check` catches parallel execution race conditions. -/// -/// This test simulates the following scenario: -/// 1. TX A: `run_transaction()` → passes (block has capacity for one more tx) -/// 2. TX B: `run_transaction()` → passes (block still has capacity - checked before A committed) -/// 3. TX B: `commit_transaction_outcome()` → succeeds, updates block counters (now at limit) -/// 4. TX A: `commit_transaction_outcome()` → should FAIL due to commit-time `pre_execution_check` -#[test] -fn test_commit_time_pre_execution_check_parallel_simulation() { - // Create database and deploy a simple contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund multiple caller accounts (simulating parallel execution from different senders) - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(CALLER3, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Determine gas needed per transaction - // We'll use gas_limit of 100_000 per transaction - let tx_gas_limit = 100_000u64; - - // Create EVM environment with block gas limit that allows exactly 2 transactions - // The pre_execution_check uses: block_gas_used + gas_limit > block_gas_limit - // Actual gas used per tx is ~30_000 (simple contract call) - // After 2 txs commit: block_gas_used ≈ 60_000 - // For 3rd tx to fail: 60_000 + 100_000 = 160_000 > block_gas_limit - // So we set block_gas_limit = 150_000 (allows 2 txs, rejects 3rd) - let block_gas_limit = 150_000u64; - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: block_gas_limit, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with block_gas_limit set (this is what pre_execution_check uses) - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_gas_limit(block_gas_limit), - ); - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Create 3 transactions from different callers (nonce 0 for each) - // This simulates parallel execution where each transaction is independent - let tx1 = create_transaction_with_caller(CALLER, 0, tx_gas_limit); - let tx2 = create_transaction_with_caller(CALLER2, 0, tx_gas_limit); - let tx3 = create_transaction_with_caller(CALLER3, 0, tx_gas_limit); - - // Step 1: Run tx1 (should pass - block has capacity) - let outcome1 = executor.run_transaction(&tx1); - assert!(outcome1.is_ok(), "run_transaction(tx1) should succeed"); - let outcome1 = outcome1.unwrap(); - - // Step 2: Run tx2 (should pass - block still has capacity, tx1 not committed yet) - let outcome2 = executor.run_transaction(&tx2); - assert!(outcome2.is_ok(), "run_transaction(tx2) should succeed (tx1 not committed yet)"); - let outcome2 = outcome2.unwrap(); - - // Step 3: Run tx3 (should pass - block still has capacity, neither tx1 nor tx2 committed) - let outcome3 = executor.run_transaction(&tx3); - assert!(outcome3.is_ok(), "run_transaction(tx3) should succeed (no tx committed yet)"); - let outcome3 = outcome3.unwrap(); - - // Step 4: Commit tx2 first (out of order - simulating parallel execution) - let commit2 = executor.commit_transaction_outcome(outcome2); - assert!(commit2.is_ok(), "commit_transaction_outcome(tx2) should succeed"); - - // Step 5: Commit tx3 (should succeed, filling up the block) - let commit3 = executor.commit_transaction_outcome(outcome3); - assert!(commit3.is_ok(), "commit_transaction_outcome(tx3) should succeed"); - - // Step 6: Commit tx1 (should FAIL - block is now at capacity) - // This tests the commit-time pre_execution_check that catches the race condition. - // Even though tx1 passed run_transaction() initially (before tx2/tx3 committed), - // the commit-time check re-validates and catches that block_gas_used + gas_limit - // now exceeds block_gas_limit. - let commit1 = executor.commit_transaction_outcome(outcome1); - assert!(commit1.is_err(), "commit_transaction_outcome(tx1) should fail - block at capacity"); - - let err_msg = format!("{:?}", commit1.unwrap_err()); - assert!( - err_msg.contains("TransactionGasLimitMoreThanAvailableBlockGas"), - "Error should mention TransactionGasLimitMoreThanAvailableBlockGas, got: {}", - err_msg - ); - - // Finish the block - should have 2 receipts (tx2 and tx3, tx1 was rejected at commit time) - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!( - receipts.receipts.len(), - 2, - "Should have 2 receipts (tx1 failed at commit time due to race condition)" - ); -} - -#[test] -fn test_block_tx_size_limit_with_varying_sizes() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_log_generating_contract(100); - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Measure transaction sizes with different gas limits - let small_tx = create_transaction(0, 100_000); - let large_tx = create_transaction(0, 10_000_000); - let small_size = small_tx.encode_2718_len() as u64; - let large_size = large_tx.encode_2718_len() as u64; - - // Set limit to allow 2 small + 1 large transaction - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_txs_encode_size_limit(small_size * 2 + large_size), - ); - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute 2 small transactions - let result1 = executor.execute_transaction(&create_transaction(0, 100_000)); - assert!(result1.is_ok(), "First small transaction should succeed"); - - let result2 = executor.execute_transaction(&create_transaction(1, 100_000)); - assert!(result2.is_ok(), "Second small transaction should succeed"); - - // Execute 1 large transaction - let result3 = executor.execute_transaction(&create_transaction(2, 10_000_000)); - assert!(result3.is_ok(), "Large transaction should succeed"); - - // Try to execute one more small transaction (should fail) - let result4 = executor.execute_transaction(&create_transaction(3, 100_000)); - assert!(result4.is_err(), "Fourth transaction should fail due to tx size limit"); - - // Finish the block - should have 3 receipts - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 3, "Should have 3 receipts (4th tx failed)"); -} diff --git a/crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs b/crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs deleted file mode 100644 index ada644d84..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Pins the canonical per-chain schedules (`block/chain.rs`) to the activation timestamps -//! published in `docs/spec/upgrades/overview.md`. -//! -//! The two are separate copies of the same numbers: the overview is what operators and -//! integrators read, the schedule is what `mega-evme replay` executes. A digit mistyped in -//! either is self-consistent with its own tests, so this test reads the published table and -//! compares every fork on both networks — a backticked timestamp in the overview must be the -//! schedule entry, and a fork the overview marks as not activated (`N/A`, `Not yet scheduled`) -//! must be [`ForkCondition::Never`]. - -use std::{ - collections::BTreeMap, - fs, - path::{Path, PathBuf}, -}; - -use alloy_hardforks::ForkCondition; -use mega_evm::{mainnet_hardforks, testnet_hardforks, MegaHardfork, MegaHardforks}; - -/// Every fork heading in the published upgrade overview and the hardfork it documents. A new -/// fork page must be added here to be pinned; the test fails if the two sets differ. -const FORK_PAGES: &[(&str, MegaHardfork)] = &[ - ("MiniRex", MegaHardfork::MiniRex), - ("MiniRex1", MegaHardfork::MiniRex1), - ("MiniRex2", MegaHardfork::MiniRex2), - ("Rex", MegaHardfork::Rex), - ("Rex1", MegaHardfork::Rex1), - ("Rex2", MegaHardfork::Rex2), - ("Rex3", MegaHardfork::Rex3), - ("Rex4", MegaHardfork::Rex4), - ("Rex5", MegaHardfork::Rex5), - ("Rex6", MegaHardfork::Rex6), - ("Rex7", MegaHardfork::Rex7), -]; - -/// Published activation per network as written in the overview: `Some(ts)` for a backticked -/// timestamp, `None` for the prose that marks a fork as not activated on that network. -#[derive(Debug, Default)] -struct Published { - testnet: Option, - mainnet: Option, -} - -#[derive(Clone, Copy)] -enum Network { - Testnet, - Mainnet, -} - -/// The overview lives outside the crate root, so it is not part of the published package. -/// Returns `None` when this crate is not laid out as a repository checkout (a crates.io tarball -/// or a vendored copy), where the pin has nothing to compare against; in a checkout the file is -/// mandatory and its absence fails the test. -fn overview() -> Option { - let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); - if !workspace_root.join("crates/mega-evm/Cargo.toml").is_file() { - eprintln!( - "skipping: not a repository checkout, docs/spec/upgrades/overview.md is not packaged" - ); - return None; - } - let path: PathBuf = workspace_root.join("docs/spec/upgrades/overview.md"); - Some( - fs::read_to_string(&path) - .unwrap_or_else(|e| panic!("{} is part of the repository: {e}", path.display())), - ) -} - -/// Parses the `## Hardfork History` section. Each `### ` heading (linked or bare) opens an -/// entry; the line after `{% tab title="Testnet" %}` / `{% tab title="Mainnet" %}` carries either -/// a backticked timestamp or a not-activated marker. -fn parse_published(overview: &str) -> BTreeMap { - let mut out: BTreeMap = BTreeMap::new(); - let mut current: Option = None; - let mut in_history = false; - let mut lines = overview.lines(); - while let Some(line) = lines.next() { - if let Some(heading) = line.strip_prefix("## ") { - in_history = heading.trim() == "Hardfork History"; - current = None; - continue; - } - if !in_history { - continue; - } - if let Some(heading) = line.strip_prefix("### ") { - let heading = heading.trim(); - // `### [Rex6](rex6.md)` and `### MiniRex1` both name the fork. - let label = heading - .strip_prefix('[') - .and_then(|rest| rest.split(']').next()) - .unwrap_or(heading); - out.entry(label.to_string()).or_default(); - current = Some(label.to_string()); - continue; - } - let network = match line.trim() { - "{% tab title=\"Testnet\" %}" => Network::Testnet, - "{% tab title=\"Mainnet\" %}" => Network::Mainnet, - _ => continue, - }; - let body = lines.next().expect("a tab has a body line").trim(); - let timestamp = body.strip_prefix('`').map(|rest| { - let digits = rest.split('`').next().expect("closing backtick"); - digits.parse::().unwrap_or_else(|e| panic!("bad timestamp {digits:?}: {e}")) - }); - let label = current.as_ref().expect("a tab outside any fork heading"); - let entry = out.get_mut(label).expect("entry created at the heading"); - match network { - Network::Testnet => entry.testnet = timestamp, - Network::Mainnet => entry.mainnet = timestamp, - } - } - out -} - -fn expected(published: Option) -> ForkCondition { - published.map_or(ForkCondition::Never, ForkCondition::Timestamp) -} - -#[test] -fn test_canonical_schedules_match_published_activation_timestamps() { - let Some(overview) = overview() else { return }; - let published = parse_published(&overview); - - // Every documented fork is pinned, and every pinned fork is documented. - let documented: Vec<&str> = published.keys().map(String::as_str).collect(); - let mut pinned: Vec<&str> = FORK_PAGES.iter().map(|(label, _)| *label).collect(); - pinned.sort_unstable(); - assert_eq!( - documented, pinned, - "overview.md fork pages and FORK_PAGES differ — extend the pin when a fork page is added" - ); - - let mainnet = mainnet_hardforks(); - let testnet = testnet_hardforks(); - for (label, fork) in FORK_PAGES { - let doc = &published[*label]; - assert_eq!( - testnet.mega_fork_activation(*fork), - expected(doc.testnet), - "{label}: testnet schedule in block/chain.rs disagrees with overview.md" - ); - assert_eq!( - mainnet.mega_fork_activation(*fork), - expected(doc.mainnet), - "{label}: mainnet schedule in block/chain.rs disagrees with overview.md" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs b/crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs deleted file mode 100644 index b29ae566e..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs +++ /dev/null @@ -1,342 +0,0 @@ -//! Tests for deposit transaction DA size limit exemption. -//! -//! These tests verify that deposit transactions are exempt from DA size limit checks -//! while regular transactions are still subject to DA size limits. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, - MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTransactionExt, MegaTxEnvelope, - TestExternalEnvs, -}; -use op_alloy_consensus::TxDeposit; -use revm::{context::BlockEnv, database::State}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); -const DA_SIZE_LIMIT: u64 = 100; // Small DA limit for testing - -/// Helper function to create a regular (non-deposit) transaction with large calldata. -fn create_regular_transaction_with_large_calldata( - nonce: u64, -) -> alloy_consensus::transaction::Recovered { - // Create calldata with non-compressible data (sequential bytes) to ensure it exceeds - // DA_SIZE_LIMIT - let large_calldata = - Bytes::from((0..(DA_SIZE_LIMIT * 1000)).map(|_| rand::random::()).collect::>()); - - let tx_legacy = TxLegacy { - chain_id: Some(8453), // Base mainnet - nonce, - gas_price: 1_000_000, - gas_limit: 1_000_000, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: large_calldata, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Helper function to create a deposit transaction with large calldata. -fn create_deposit_transaction_with_large_calldata( -) -> alloy_consensus::transaction::Recovered { - // Create calldata with non-compressible data (sequential bytes) to ensure it exceeds - // DA_SIZE_LIMIT - let large_calldata = - Bytes::from((0..(DA_SIZE_LIMIT * 1000)).map(|_| rand::random::()).collect::>()); - - let deposit_tx = TxDeposit { - source_hash: B256::ZERO, - from: CALLER, - to: TxKind::Call(CONTRACT), - mint: 0, - value: U256::ZERO, - gas_limit: 1_000_000, - is_system_transaction: false, - input: large_calldata, - }; - let tx = - MegaTxEnvelope::Deposit(alloy_consensus::Sealed::new_unchecked(deposit_tx, B256::ZERO)); - // Deposit transactions don't have a recoverable signature, so we use CALLER as the signer - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Helper function to create a small regular transaction. -fn create_small_regular_transaction( - nonce: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit: 100_000, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -#[test] -fn test_deposit_transaction_exempt_from_single_tx_da_limit() { - // Create database with empty contract - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, Bytes::new()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with strict DA size limits - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits() - .with_block_gas_limit(30_000_000) - .with_tx_da_size_limit(DA_SIZE_LIMIT) - .with_block_da_size_limit(DA_SIZE_LIMIT * 10), - ); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute deposit transaction with large calldata - should succeed - let deposit_tx = create_deposit_transaction_with_large_calldata(); - assert!(deposit_tx.estimated_da_size() > DA_SIZE_LIMIT * 10); - - let result = executor.execute_transaction(&deposit_tx); - assert!( - result.is_ok(), - "Deposit transaction should succeed despite exceeding tx_da_size_limit, got error: {:?}", - result.err() - ); - - // Finish block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt for deposit transaction"); -} - -#[test] -fn test_regular_transaction_rejected_by_single_tx_da_limit() { - // Create database with empty contract - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, Bytes::new()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with strict DA size limits - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits() - .with_block_gas_limit(30_000_000) - .with_tx_da_size_limit(DA_SIZE_LIMIT) - .with_block_da_size_limit(DA_SIZE_LIMIT * 10), - ); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute regular transaction with large calldata - should fail - let regular_tx = create_regular_transaction_with_large_calldata(0); - assert!(regular_tx.estimated_da_size() > DA_SIZE_LIMIT); - - let result = executor.execute_transaction(®ular_tx); - assert!( - result.is_err(), - "Regular transaction should be rejected for exceeding tx_da_size_limit" - ); - - let err_msg = format!("{:?}", result.unwrap_err()); - assert!( - err_msg.contains("DataAvailabilitySizeLimit"), - "Error should mention DataAvailabilitySizeLimit, got: {}", - err_msg - ); -} - -#[test] -fn test_deposit_exempt_from_block_da_limit() { - // Create database with empty contract - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, Bytes::new()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with strict block DA size limit - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits() - .with_block_gas_limit(30_000_000) - .with_tx_da_size_limit(DA_SIZE_LIMIT * 10) // High single tx limit - .with_block_da_size_limit(DA_SIZE_LIMIT), // Low block limit - ); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute deposit transaction with large calldata - should succeed even if block DA is exceeded - let deposit_tx = create_deposit_transaction_with_large_calldata(); - assert!(deposit_tx.estimated_da_size() > DA_SIZE_LIMIT); - - let result = executor.execute_transaction(&deposit_tx); - assert!( - result.is_ok(), - "Deposit transaction should succeed despite exceeding block_da_size_limit, got error: {:?}", - result.err() - ); - - // Finish block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt for deposit transaction"); -} - -#[test] -fn test_mixed_deposit_and_regular_transactions() { - // Create database with empty contract - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, Bytes::new()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with moderate DA size limits - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits() - .with_block_gas_limit(30_000_000) - .with_tx_da_size_limit(DA_SIZE_LIMIT) - .with_block_da_size_limit(DA_SIZE_LIMIT * 10), - ); - - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // 1. Execute small regular transaction - should succeed - let small_tx = create_small_regular_transaction(0); - let result1 = executor.execute_transaction(&small_tx); - assert!(result1.is_ok(), "Small regular transaction should succeed"); - - // 2. Execute large deposit transaction - should succeed (exempt from DA limits) - let deposit_tx = create_deposit_transaction_with_large_calldata(); - let result2 = executor.execute_transaction(&deposit_tx); - assert!(result2.is_ok(), "Deposit transaction should succeed despite large DA size"); - - // 3. Execute large regular transaction - should fail (exceeds tx DA limit) - let large_tx = create_regular_transaction_with_large_calldata(1); - let result3 = executor.execute_transaction(&large_tx); - assert!(result3.is_err(), "Large regular transaction should fail due to DA size limit"); - - // Finish block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 2, "Should have 2 receipts (small regular + deposit)"); -} diff --git a/crates/mega-evm/tests/_pending/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs index 1d7f9b265..693e3735f 100644 --- a/crates/mega-evm/tests/_pending/block_executor/main.rs +++ b/crates/mega-evm/tests/_pending/block_executor/main.rs @@ -1,9 +1,5 @@ //! Tests for block executor functionality. -mod accessed_block_hashes; mod block_limits; -mod canonical_schedule; -mod deposit_da_exemption; mod inspector; mod sequencer_registry; -mod trait_factory_runtime_limits; diff --git a/crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs b/crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs deleted file mode 100644 index ff775c36e..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs +++ /dev/null @@ -1,227 +0,0 @@ -//! Tests for the `alloy_evm::block::BlockExecutorFactory` trait impl on -//! `MegaBlockExecutorFactory`. -//! -//! The factory exposes two paths that produce a `MegaBlockExecutor`: -//! -//! 1. The inherent `create_executor` / `create_executor_with_inspector` methods, which build the -//! EVM internally and apply `block_ctx.block_limits.to_evm_tx_runtime_limits()` before -//! constructing the executor. -//! -//! 2. The trait method `::create_executor` which receives a prebuilt EVM and -//! is what downstream block-builder / reorg paths in `mega-reth` call into. -//! -//! Historically only path (1) synchronized the EVM tx runtime limits with the -//! block-context limits, so callers of (2) that forgot to chain -//! `.with_tx_runtime_limits(...)` on the EVM ran against whatever default -//! limits the EVM was constructed with. These tests pin the invariant that the -//! trait impl now applies the same synchronization unconditionally, on every -//! spec, so the two construction routes are observationally equivalent. - -use std::convert::Infallible; - -use alloy_evm::{ - block::{BlockExecutor, BlockExecutorFactory}, - EvmEnv, EvmFactory, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{Bytes, B256, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, - MegaBlockExecutorFactory, MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, - TestExternalEnvs, -}; -use revm::{context::BlockEnv, database::State, handler::EvmTr}; - -/// A deliberately non-default per-tx compute-gas cap. Chosen well below any -/// spec default and any saturation boundary so that all four tests use the -/// same recognizable value across specs. -const NON_DEFAULT_TX_COMPUTE_GAS_LIMIT: u64 = 1_234_567; - -fn evm_env_for_spec(spec: MegaSpecId) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - cfg_env.chain_id = 8453; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn chain_spec_at(hardfork: MegaHardfork) -> MegaHardforkConfig { - MegaHardforkConfig::default().with(hardfork, ForkCondition::Timestamp(0)) -} - -fn block_ctx_with_compute_gas_limit(limit: u64) -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_tx_compute_gas_limit(limit), - ) -} - -/// The trait factory must apply `block_ctx.block_limits.to_evm_tx_runtime_limits()` -/// to the prebuilt EVM under REX5. -#[test] -fn test_trait_path_applies_block_context_compute_gas_limit_rex5() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = chain_spec_at(MegaHardfork::Rex5); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let factory = MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - // Build the EVM without any caller-side .with_tx_runtime_limits(...) chain. - // This is exactly the trigger condition of the original bug: a caller of - // the trait factory that forgot to pre-apply the block-context limits. - let evm = factory.evm_factory().create_evm(&mut state, evm_env_for_spec(MegaSpecId::REX5)); - - let ctx = block_ctx_with_compute_gas_limit(NON_DEFAULT_TX_COMPUTE_GAS_LIMIT); - - // Route via the trait method. Fully-qualified syntax disambiguates from the - // inherent `create_executor(db, ctx, evm_env)` method that takes three args. - let executor = as BlockExecutorFactory>::create_executor( - &factory, evm, ctx, - ); - - assert_eq!( - executor.evm().ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, - NON_DEFAULT_TX_COMPUTE_GAS_LIMIT, - "trait factory must propagate block_ctx.block_limits.tx_compute_gas_limit \ - to the prebuilt EVM's runtime limits under REX5", - ); -} - -/// The same invariant must hold on a spec other than REX5. This is the -/// load-bearing assertion that the trait/inherent asymmetry has been -/// eliminated on every spec, not just on the latest one. -#[test] -fn test_trait_path_applies_block_context_compute_gas_limit_rex4() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = chain_spec_at(MegaHardfork::Rex4); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let factory = MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let evm = factory.evm_factory().create_evm(&mut state, evm_env_for_spec(MegaSpecId::REX4)); - - let ctx = block_ctx_with_compute_gas_limit(NON_DEFAULT_TX_COMPUTE_GAS_LIMIT); - - let executor = as BlockExecutorFactory>::create_executor( - &factory, evm, ctx, - ); - - assert_eq!( - executor.evm().ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, - NON_DEFAULT_TX_COMPUTE_GAS_LIMIT, - "trait factory must propagate block_ctx.block_limits.tx_compute_gas_limit \ - to the prebuilt EVM's runtime limits under REX4", - ); -} - -/// Inherent and trait construction routes must produce executors with the same -/// configured runtime limits for the same `BlockLimits`. This directly pins the -/// no-asymmetry invariant: there must be no observable difference between -/// `factory.create_executor(db, ctx, evm_env)` and -/// `<_ as BlockExecutorFactory>::create_executor(&factory, evm, ctx)` for -/// equivalent inputs. -#[test] -fn test_inherent_and_trait_paths_apply_same_runtime_limits() { - let chain_spec = chain_spec_at(MegaHardfork::Rex5); - let receipt_builder = OpAlloyReceiptBuilder::default(); - - let inherent_limit: u64 = { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let factory = - MegaBlockExecutorFactory::new(chain_spec.clone(), evm_factory, receipt_builder); - - let ctx = block_ctx_with_compute_gas_limit(NON_DEFAULT_TX_COMPUTE_GAS_LIMIT); - let executor = factory.create_executor(&mut state, ctx, evm_env_for_spec(MegaSpecId::REX5)); - let limit = executor.evm().ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit; - limit - }; - - let trait_limit: u64 = { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let factory = MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let evm = factory.evm_factory().create_evm(&mut state, evm_env_for_spec(MegaSpecId::REX5)); - let ctx = block_ctx_with_compute_gas_limit(NON_DEFAULT_TX_COMPUTE_GAS_LIMIT); - let executor = as BlockExecutorFactory>::create_executor( - &factory, evm, ctx, - ); - let limit = executor.evm().ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit; - limit - }; - - assert_eq!( - inherent_limit, NON_DEFAULT_TX_COMPUTE_GAS_LIMIT, - "inherent factory must apply the configured tx_compute_gas_limit", - ); - assert_eq!( - trait_limit, NON_DEFAULT_TX_COMPUTE_GAS_LIMIT, - "trait factory must apply the configured tx_compute_gas_limit", - ); - assert_eq!( - inherent_limit, trait_limit, - "inherent and trait construction routes must produce identical \ - tx_compute_gas_limit values for the same BlockLimits", - ); -} - -/// If the caller has already chained `with_tx_runtime_limits(...)` on the EVM -/// before invoking the trait factory, the factory's own synchronization step -/// must be a semantic no-op: the configured limit (derived from the same -/// `block_ctx.block_limits`) is just re-applied at the same value. This pins -/// the idempotence property the unconditional-sync rationale relies on. -#[test] -fn test_trait_path_idempotent_when_caller_pre_applied_runtime_limits() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = chain_spec_at(MegaHardfork::Rex5); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let factory = MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_limits = - BlockLimits::no_limits().with_tx_compute_gas_limit(NON_DEFAULT_TX_COMPUTE_GAS_LIMIT); - let pre_applied: EvmTxRuntimeLimits = block_limits.to_evm_tx_runtime_limits(); - - // Caller pre-applies the same limits derived from block_limits — the - // canonical pattern used today by mega-reth's RPC paths. - let evm = factory - .evm_factory() - .create_evm(&mut state, evm_env_for_spec(MegaSpecId::REX5)) - .with_tx_runtime_limits(pre_applied); - - let ctx = MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), block_limits); - - let executor = as BlockExecutorFactory>::create_executor( - &factory, evm, ctx, - ); - - assert_eq!( - executor.evm().ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, - NON_DEFAULT_TX_COMPUTE_GAS_LIMIT, - "trait factory's runtime-limit synchronization must be idempotent for \ - callers that already applied the same limits via with_tx_runtime_limits", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs index 97664c952..4a437b901 100644 --- a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs +++ b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs @@ -397,24 +397,3 @@ fn test_rex6_eip4788_pre_block_call_failure_aborts_block() { ); } -/// Fail-closed guard: with Rex5 active but no [`SequencerRegistryConfig`] on the chain's -/// hardfork configuration, the pre-block pipeline must abort rather than deploy the registry -/// with unseeded roles. -#[test] -fn test_rex5_active_without_sequencer_registry_config_aborts_block() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = executor_factory_with(rex6_chain_spec_missing_registry_config()) - .create_executor(&mut state, block_ctx(), evm_env_at_block(1000)); - let err = executor - .apply_pre_execution_changes() - .expect_err("Rex5 active without SequencerRegistryConfig must fail closed"); - - let msg = std::format!("{err}"); - assert!( - msg.contains("SequencerRegistryConfig not configured"), - "expected a missing-config failure, got: {msg}" - ); -} diff --git a/crates/mega-evm/tests/block/block_hashes.rs b/crates/mega-evm/tests/block/block_hashes.rs new file mode 100644 index 000000000..5fb4c084f --- /dev/null +++ b/crates/mega-evm/tests/block/block_hashes.rs @@ -0,0 +1,62 @@ +//! The block hashes a block's transactions read, which a stateless witness needs. + +use alloy_evm::block::BlockExecutor; +use alloy_primitives::Bytes; +use mega_evm::test_utils::BytecodeBuilder; +use revm::{ + bytecode::opcode::{BLOCKHASH, POP}, + database::State, +}; + +use crate::common::{self, executor, recovered, user_tx, BLOCK_NUMBER, CONTRACT}; + +/// The block number the contract below reads, one below the block being executed. +const READ_BLOCK: u64 = BLOCK_NUMBER - 1; + +/// An account with no code, so a call to it reads no block hash. +const PLAIN: alloy_primitives::Address = + alloy_primitives::address!("0x1000000000000000000000000000000000000002"); + +/// Code that reads `BLOCKHASH(READ_BLOCK)` and discards it. +fn blockhash_contract() -> Bytes { + BytecodeBuilder::default() + .push_number(READ_BLOCK as u32) + .append(BLOCKHASH) + .append(POP) + .stop() + .build() +} + +/// The record accumulates over the block's transactions and can be cleared, so a caller can +/// attribute the reads to one transaction. Clearing changes no execution result. +#[test] +fn test_accessed_block_hashes_track_and_clear_per_transaction() { + let mut db = common::database(); + db.set_account_code(CONTRACT, blockhash_contract()); + db.set_account_code(PLAIN, Bytes::new()); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.clear_accessed_block_hashes(); + + // A transaction that reads a block hash leaves it in the record. + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + let accessed = executor.get_accessed_block_hashes(); + assert_eq!(accessed.len(), 1, "the read is recorded"); + assert!(accessed.contains_key(&READ_BLOCK), "under the block number it asked for"); + + // Clearing empties the record. + executor.clear_accessed_block_hashes(); + assert!(executor.get_accessed_block_hashes().is_empty()); + + // A transaction that reads none leaves the cleared record empty, even though an earlier + // transaction of the same block read one. + executor + .execute_transaction(&recovered(common::tx(1, PLAIN, Bytes::new(), 1_000_000))) + .expect("the transaction executes"); + assert!(executor.get_accessed_block_hashes().is_empty()); + + // And a read after the clear is attributed to the transaction that made it. + executor.execute_transaction(&user_tx(2, 1_000_000)).expect("the transaction executes"); + assert_eq!(executor.get_accessed_block_hashes().len(), 1); +} diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs new file mode 100644 index 000000000..32e966c86 --- /dev/null +++ b/crates/mega-evm/tests/block/common.rs @@ -0,0 +1,211 @@ +//! Shared setup of the block-executor tests. +//! +//! A block on a chain whose schedule activates Satin at genesis, over an in-memory database with +//! an empty L1 block contract — so the L1 fees, the operator fee and the data-availability +//! footprint scalar all read as zero unless a test writes them. + +use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxLegacy}; +use alloy_evm::{EvmEnv, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, + MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, +}; +use op_alloy_consensus::TxDeposit; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::State, + inspector::NoOpInspector, +}; + +/// The sender every test transaction comes from. +pub(crate) const CALLER: Address = address!("0x2000000000000000000000000000000000000002"); + +/// The account every test transaction calls. +pub(crate) const CONTRACT: Address = address!("0x1000000000000000000000000000000000000001"); + +/// The block the tests execute. +pub(crate) const BLOCK_NUMBER: u64 = 1_000; + +/// The timestamp of the block the tests execute. +pub(crate) const BLOCK_TIMESTAMP: u64 = 1_800_000_000; + +/// The gas limit of the block the tests execute. +pub(crate) const BLOCK_GAS_LIMIT: u64 = 30_000_000; + +/// The chain id the test transactions carry. +pub(crate) const CHAIN_ID: u64 = 4_326; + +/// The database a block runs on: the caller is funded and the callee has empty code. +pub(crate) fn database() -> MemoryDatabase { + let mut db = MemoryDatabase::default(); + db.set_account_code(CONTRACT, Bytes::new()); + db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000_u64)); + db +} + +/// The state a block runs on. +pub(crate) fn state() -> State { + State::builder().with_database(database()).build() +} + +/// The environment of the block the tests execute. +pub(crate) fn evm_env() -> EvmEnv { + let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg_env.chain_id = CHAIN_ID; + let block_env = BlockEnv { + number: U256::from(BLOCK_NUMBER), + timestamp: U256::from(BLOCK_TIMESTAMP), + gas_limit: BLOCK_GAS_LIMIT, + ..Default::default() + }; + EvmEnv::new(cfg_env, block_env) +} + +/// A schedule that activates Satin at genesis. +pub(crate) fn chain_spec() -> MegaHardforkConfig { + MegaHardforkConfig::default().with_all_activated() +} + +/// The context of a block held to `limits`. +/// +/// Cancun is active, so the block carries a parent beacon block root; without one the EIP-4788 +/// pre-block call refuses the block. +pub(crate) fn block_ctx(limits: BlockLimits) -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), limits) +} + +/// The context of a block with no limits at all. +pub(crate) fn unlimited_ctx() -> MegaBlockExecutionCtx { + block_ctx(BlockLimits::no_limits()) +} + +/// The EVM the tests run a block on. +pub(crate) type TestEvm<'a> = + MegaEvm<&'a mut State, NoOpInspector, EmptyExternalEnv>; + +/// The executor the tests drive. +pub(crate) type TestExecutor<'a> = + MegaBlockExecutor, OpAlloyReceiptBuilder, MegaHardforkConfig>; + +/// The factory the tests build executors from. +pub(crate) fn factory() -> MegaBlockExecutorFactory< + OpAlloyReceiptBuilder, + MegaHardforkConfig, + MegaEvmFactory, +> { + MegaBlockExecutorFactory::new( + OpAlloyReceiptBuilder::default(), + chain_spec(), + MegaEvmFactory::new(), + ) +} + +/// An executor over `state`, for a block held to `ctx`. +pub(crate) fn executor( + state: &mut State, + ctx: MegaBlockExecutionCtx, +) -> TestExecutor<'_> { + executor_with_env(state, ctx, evm_env()) +} + +/// An executor over `state`, for a block held to `ctx` in the environment `env`. +pub(crate) fn executor_with_env( + state: &mut State, + ctx: MegaBlockExecutionCtx, + env: EvmEnv, +) -> TestExecutor<'_> { + build(state, ctx, env, chain_spec()) +} + +/// An executor over `state`, for a block on the chain `spec` describes. +pub(crate) fn executor_with_spec( + state: &mut State, + ctx: MegaBlockExecutionCtx, + spec: MegaHardforkConfig, +) -> TestExecutor<'_> { + build(state, ctx, evm_env(), spec) +} + +fn build( + state: &mut State, + ctx: MegaBlockExecutionCtx, + env: EvmEnv, + spec: MegaHardforkConfig, +) -> TestExecutor<'_> { + let evm = MegaEvmFactory::new() + .create_evm(state, env) + .with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) +} + +/// A legacy transaction from [`CALLER`]. +pub(crate) fn tx(nonce: u64, to: Address, input: Bytes, gas_limit: u64) -> MegaTxEnvelope { + let tx_legacy = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 1_000_000, + gas_limit, + to: TxKind::Call(to), + value: U256::ZERO, + input, + }; + MegaTxEnvelope::Legacy(Signed::new_unchecked( + tx_legacy, + Signature::test_signature(), + B256::repeat_byte(nonce as u8 + 1), + )) +} + +/// A legacy transaction from [`CALLER`], with its sender recovered. +pub(crate) fn user_tx(nonce: u64, gas_limit: u64) -> Recovered { + recovered(tx(nonce, CONTRACT, Bytes::new(), gas_limit)) +} + +/// A legacy transaction carrying `input`. +pub(crate) fn user_tx_with_input( + nonce: u64, + input: Bytes, + gas_limit: u64, +) -> Recovered { + recovered(tx(nonce, CONTRACT, input, gas_limit)) +} + +/// A deposit transaction carrying `input`. +pub(crate) fn deposit_tx(input: Bytes, gas_limit: u64) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::ZERO, + from: CALLER, + to: TxKind::Call(CONTRACT), + mint: 0, + value: U256::ZERO, + gas_limit, + is_system_transaction: false, + input, + }; + recovered(MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0xde)))) +} + +/// A transaction with its sender recovered. Deposits carry no recoverable signature, so every +/// test transaction names [`CALLER`] as its sender. +pub(crate) fn recovered(tx: MegaTxEnvelope) -> Recovered { + Recovered::new_unchecked(tx, CALLER) +} + +/// `len` bytes that barely compress, so a transaction carrying them has a large +/// data-availability size. Deterministic, so every run estimates the same size. +pub(crate) fn incompressible(len: usize) -> Bytes { + let mut state = 0x2545_F491_4F6C_DD1D_u64; + Bytes::from( + (0..len) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 32) as u8 + }) + .collect::>(), + ) +} diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs new file mode 100644 index 000000000..d7289ca13 --- /dev/null +++ b/crates/mega-evm/tests/block/counters.rs @@ -0,0 +1,139 @@ +//! What a block counts of the transactions it packed. + +use alloy_consensus::transaction::Recovered; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{test_utils::BytecodeBuilder, BlockGasCounters, BlockLimits, MegaTxEnvelope}; +use revm::{bytecode::opcode::LOG0, database::State}; + +use crate::common::{self, executor, user_tx, CONTRACT}; + +/// An account with no code, to transfer to. +const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); + +/// Code that writes a slot and emits a log, so a transaction touching it spends on more than +/// plain execution once the mechanisms that price those land. +fn writing_contract() -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(7)) + .push_number(64_u32) + .push_number(0_u8) + .append(LOG0) + .stop() + .build() +} + +fn state_with_writer() -> State { + let mut db = common::database(); + db.set_account_code(CONTRACT, writing_contract()); + State::builder().with_database(db).build() +} + +/// A transfer to an account with no code. +fn transfer(nonce: u64) -> Recovered { + common::recovered(common::tx(nonce, RECIPIENT, Bytes::new(), 100_000)) +} + +/// The block's three ledgers are the sum of its transactions', each on its own ledger, and the +/// block's gas used stays the sum of its receipts. +#[test] +fn test_a_block_sums_each_ledger_of_its_transactions() { + let mut state = state_with_writer(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let mut expected = BlockGasCounters::default(); + let mut expected_gas_used = 0; + for tx in [transfer(0), user_tx(1, 1_000_000), transfer(2)] { + let outcome = executor.run_transaction(&tx).expect("the transaction executes"); + expected.record(&outcome.gas); + expected_gas_used += outcome.gas.gas_used; + executor.commit_transaction_outcome(outcome).expect("the block has room"); + } + // A deposit counts on the same ledgers as any other transaction. + let deposit = common::deposit_tx(Bytes::new(), 100_000); + let outcome = executor.run_transaction(&deposit).expect("the deposit executes"); + expected.record(&outcome.gas); + expected_gas_used += outcome.gas.gas_used; + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + assert_eq!(*executor.gas(), expected); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.gas, expected); + assert_eq!(result.gas_used, expected_gas_used, "the header's gas used is its receipts' sum"); + assert!(result.gas.execution > 0, "execution gas is what these transactions spend"); +} + +/// The counters and the footprint ride on the block's result, where the node reads them. +#[test] +fn test_the_result_carries_the_counters_and_the_footprint() { + let mut state = state_with_writer(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + + let usage = executor.limiter().usage; + let gas = *executor.gas(); + let footprint = executor.limiter().block_da_footprint_used; + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + + assert_eq!(result.gas, gas); + assert_eq!(result.usage, usage); + assert_eq!(result.blob_gas_used, footprint); + assert_eq!(result.receipts().len(), 1); + assert!(result.usage.write_records > 0, "the transaction wrote to state"); +} + +/// The execution-gas dimension of the block: the transaction that crosses the limit is packed, +/// and the next one is refused before it runs. +#[test] +fn test_the_execution_limit_packs_the_crossing_transaction_and_skips_the_next() { + let mut state = state_with_writer(); + + // What one of these transactions spends on the execution ledger, so the block below has room + // for exactly one of them. + let spent = { + let mut probe_state = state_with_writer(); + let mut probe = executor(&mut probe_state, common::unlimited_ctx()); + probe.apply_pre_execution_changes().expect("the block starts"); + probe.execute_transaction(&user_tx(0, 1_000_000)).expect("the probe executes"); + probe.gas().execution + }; + assert!(spent > 0); + + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_execution_gas_limit(spent - 1)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, 1_000_000)) + .expect("the transaction that crosses the limit is still packed"); + assert!(executor.gas().execution > spent - 1, "the block has crossed its limit"); + + let err = executor + .execute_transaction(&user_tx(1, 1_000_000)) + .expect_err("the block has no execution gas left"); + assert!(format!("{err}").contains("Block execution gas limit reached"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// The state and history ledgers are counted, and nothing refuses a transaction on them: their +/// block limits belong to the mechanisms that bring those ledgers. +#[test] +fn test_the_state_and_history_ledgers_refuse_nothing() { + let mut state = state_with_writer(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + for nonce in 0..3 { + executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("nothing refuses these"); + } + + let counters = *executor.gas(); + assert_eq!(counters.state, 0, "the Osaka gas table prices state gas at zero"); + assert_eq!(counters.history, 0, "history gas arrives with the mechanism that meters it"); +} diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs new file mode 100644 index 000000000..5650f55c0 --- /dev/null +++ b/crates/mega-evm/tests/block/factory.rs @@ -0,0 +1,101 @@ +//! The two ways to reach a block executor, and the limits both install. +//! +//! A block's transaction-level limits live in its execution context, and the EVM is what +//! enforces them. Whichever route builds the executor — the factory trait a node's block-building +//! and reorg paths call with an EVM they built, or the trusted-inspector constructor — must +//! install them, so a caller that did not pre-apply them does not run a block under whatever +//! limits the EVM happened to carry. + +use alloy_evm::{block::BlockExecutorFactory, EvmFactory}; +use mega_evm::{test_utils::GasInspector, BlockLimits, DeclaredObserver, EvmTxRuntimeLimits}; + +use crate::common; + +/// A limit no default carries, so seeing it proves it travelled from the block context. +const TX_DATA_SIZE_LIMIT: u64 = 1_234_567; + +/// A second one, so a route that installs only the first is caught. +const FRAME_DATA_SIZE_LIMIT: u64 = 7_654_321; + +fn limits() -> BlockLimits { + BlockLimits::no_limits().with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(TX_DATA_SIZE_LIMIT) + .with_frame_data_size_limit(FRAME_DATA_SIZE_LIMIT), + ) +} + +/// The factory trait installs the block context's limits on an EVM the caller built without +/// them. +#[test] +fn test_trait_path_applies_block_context_runtime_limits() { + let mut state = common::state(); + let factory = common::factory(); + // Built without any caller-side limits: the case a caller that forgot them produces. + let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); + + let executor = factory.create_executor(evm, common::block_ctx(limits())); + + assert_eq!(executor.evm().tx_runtime_limits().tx_data_size_limit, TX_DATA_SIZE_LIMIT); +} + +/// Every field travels, not just the one a test happens to look at. +#[test] +fn test_trait_path_applies_every_runtime_limit_field() { + let mut state = common::state(); + let factory = common::factory(); + let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + + let executor = factory.create_executor(evm, common::block_ctx(limits())); + + assert_eq!( + *executor.evm().tx_runtime_limits(), + limits().to_evm_tx_runtime_limits(), + "the EVM runs under exactly the block's limits" + ); +} + +/// The two routes to an executor install the same limits, so neither is a way around them. +#[test] +fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { + let trait_path = { + let mut state = common::state(); + let factory = common::factory(); + let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + let executor = factory.create_executor(evm, common::block_ctx(limits())); + *executor.evm().tx_runtime_limits() + }; + + let inspector_path = { + let mut state = common::state(); + let factory = common::factory(); + let executor = factory.create_executor_with_trusted_inspector( + &mut state, + common::evm_env(), + common::block_ctx(limits()), + DeclaredObserver::new(GasInspector::new()), + ); + *executor.evm().tx_runtime_limits() + }; + + assert_eq!(trait_path, limits().to_evm_tx_runtime_limits()); + assert_eq!(inspector_path, limits().to_evm_tx_runtime_limits()); + assert_eq!(trait_path, inspector_path); +} + +/// Installing them again over the same values changes nothing, so a caller that did pre-apply +/// them is not penalised for it. +#[test] +fn test_trait_path_idempotent_when_caller_pre_applied_runtime_limits() { + let mut state = common::state(); + let factory = common::factory(); + let evm = factory + .evm_factory() + .create_evm(&mut state, common::evm_env()) + .with_tx_runtime_limits(limits().to_evm_tx_runtime_limits()); + + let executor = factory.create_executor(evm, common::block_ctx(limits())); + + assert_eq!(*executor.evm().tx_runtime_limits(), limits().to_evm_tx_runtime_limits()); +} diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs new file mode 100644 index 000000000..0c5d53a06 --- /dev/null +++ b/crates/mega-evm/tests/block/inspector.rs @@ -0,0 +1,84 @@ +//! The admission gate: which inspectors reach block execution. + +use alloy_evm::{ + block::{BlockExecutor, BlockExecutorFactory}, + Evm, EvmFactory, +}; +use mega_evm::{test_utils::GasInspector, DeclaredObserver, MegaEvmFactory}; +use revm::inspector::NoOpInspector; + +use crate::common::{self, user_tx}; + +/// A declared observer reaches a block: its type says it writes nothing back, so what the block +/// executes is what the chain executes. +#[test] +fn test_a_declared_observer_reaches_block_execution() { + let mut state = common::state(); + let factory = common::factory(); + + let mut executor = factory.create_executor_with_trusted_inspector( + &mut state, + common::evm_env(), + common::unlimited_ctx(), + DeclaredObserver::new(GasInspector::new()), + ); + + assert!(executor.evm().is_inspecting(), "the inspector runs"); + assert!(!executor.evm().has_rewriting_inspector(), "and is admitted"); + executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// An inspector that arrived without the declaration does not: block execution refuses it before +/// the block's first call. +#[test] +fn test_a_rewriting_inspector_cannot_reach_block_execution() { + let mut state = common::state(); + let factory = common::factory(); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(GasInspector::new()); + assert!(evm.has_rewriting_inspector()); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + + let err = executor + .apply_pre_execution_changes() + .expect_err("an undeclared inspector has no route to a block"); + assert!( + format!("{err}").contains("does not admit an inspector that may rewrite execution"), + "{err}" + ); +} + +/// An EVM with no inspector at all is admitted, which is the ordinary case. +#[test] +fn test_a_block_without_an_inspector_is_admitted() { + let mut state = common::state(); + let factory = common::factory(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + + assert!(!executor.evm().is_inspecting()); + executor.apply_pre_execution_changes().expect("nothing to refuse"); +} + +/// The gate keys on what runs, not on what is held: an inspector that is disabled does not +/// rewrite anything, and the block is admitted. +#[test] +fn test_a_disabled_inspector_is_admitted() { + let mut state = common::state(); + let factory = common::factory(); + let mut evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(NoOpInspector); + evm.set_inspector_enabled(false); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + + executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); +} diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs new file mode 100644 index 000000000..6a73be376 --- /dev/null +++ b/crates/mega-evm/tests/block/limits.rs @@ -0,0 +1,460 @@ +//! What a block admits, and what it does with a transaction it does not. + +use alloy_consensus::{transaction::Recovered, Transaction}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, MegaTransactionExt, MegaTxEnvelope, +}; +use revm::{ + bytecode::opcode::LOG0, + context::{BlockEnv, ContextTr}, + Database as _, +}; + +use crate::common::{self, executor, incompressible, user_tx, CALLER, CONTRACT}; + +const CALLER2: Address = address!("0x2000000000000000000000000000000000000003"); +const CALLER3: Address = address!("0x2000000000000000000000000000000000000004"); + +/// Code that emits one log of `data_size` zero bytes, so every call to it keeps data-size bytes. +fn log_generating_contract(data_size: usize) -> Bytes { + BytecodeBuilder::default() + .push_number(data_size as u32) + .push_number(0_u8) + .append(LOG0) + .stop() + .build() +} + +/// A state whose callee emits a log of `data_size` bytes on every call. +fn state_with_log_contract( + data_size: usize, +) -> revm::database::State { + let mut db = common::database(); + db.set_account_code(CONTRACT, log_generating_contract(data_size)); + revm::database::State::builder().with_database(db).build() +} + +/// A transaction from `caller`, so transactions of one block can come from different senders. +fn tx_from(caller: Address, nonce: u64, gas_limit: u64) -> Recovered { + Recovered::new_unchecked(common::tx(nonce, CONTRACT, Bytes::new(), gas_limit), caller) +} + +/// The block's data-size limit: the transaction that crosses it is packed, and the next one is +/// refused before it runs. +#[test] +fn test_block_custom_data_limit() { + let mut state = state_with_log_contract(2_000); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(2_500)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = user_tx(0, 1_000_000); + let gas = executor.execute_transaction(&first).expect("the first transaction is packed"); + assert!(gas.tx_gas_used() < first.gas_limit()); + + let second = user_tx(1, 1_000_000); + let gas = executor + .execute_transaction(&second) + .expect("the transaction that crosses the limit is packed too"); + assert!(gas.tx_gas_used() < second.gas_limit()); + assert!(executor.limiter().usage.data_size >= 2_500, "the block has crossed its limit"); + + let err = executor + .execute_transaction(&user_tx(2, 1_000_000)) + .expect_err("the block has no data-size left"); + assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); +} + +/// Transactions that stay inside the block's limits are all packed. +#[test] +fn test_block_multiple_transactions_within_limits() { + let mut state = state_with_log_contract(100); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(10_000)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + for nonce in 0..5 { + let tx = user_tx(nonce, 1_000_000); + let gas = executor.execute_transaction(&tx).expect("the transaction is packed"); + assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); + } + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 5); +} + +/// The same limit mid-block: the transactions before the crossing are packed, the crossing one +/// is packed, and the block ends there. +#[test] +fn test_block_data_limit_exceeded_mid_block() { + let mut state = state_with_log_contract(2_000); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(6_000)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + for nonce in 0..3 { + executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("packed"); + } + assert!( + executor.execute_transaction(&user_tx(3, 1_000_000)).is_err(), + "the block has no data-size left" + ); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3, "the fourth transaction never ran"); +} + +/// A transaction refused before it runs changes nothing: no receipt, and no state. +#[test] +fn test_block_no_state_commit_on_limit_exceeded() { + let mut db = common::database(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(), + ); + let mut state = revm::database::State::builder().with_database(db).build(); + // A limit of zero is crossed before the block starts, so nothing is admitted. + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(0)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, 10_000_000)) + .expect_err("a block with no data-size admits nothing"); + + let stored = executor + .evm_mut() + .ctx_mut() + .db_mut() + .storage(CONTRACT, U256::ZERO) + .expect("the slot is readable"); + assert_eq!(stored, U256::ZERO, "the transaction's write was never committed"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert!(result.receipts().is_empty()); +} + +/// With no size limit configured, a transaction of any size is admitted. +#[test] +fn test_block_tx_size_limit_default_unlimited() { + let mut state = state_with_log_contract(100); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let big = common::user_tx_with_input(0, incompressible(20_000), 3_000_000); + assert!(MegaTransactionExt::tx_size(&big) > 20_000); + + executor.execute_transaction(&big).expect("no limit, no refusal"); +} + +/// Several transactions fit while their bodies together stay under the block's limit. +#[test] +fn test_block_tx_size_limit_allows_multiple_transactions() { + let mut state = state_with_log_contract(100); + let one = MegaTransactionExt::tx_size(&user_tx(0, 1_000_000)); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_encode_size_limit(one * 3)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + for nonce in 0..3 { + executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("the body fits"); + } + assert_eq!(executor.limiter().block_tx_size_used, one * 3); +} + +/// A first transaction whose body is larger than the block's limit is refused, and the block +/// stays empty. +#[test] +fn test_block_tx_size_limit_exceeded_first_transaction() { + let mut state = state_with_log_contract(100); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_encode_size_limit(10)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let err = executor + .execute_transaction(&user_tx(0, 1_000_000)) + .expect_err("the body does not fit in the block"); + assert!(format!("{err}").contains("Block transactions encode size limit exceeded"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert!(result.receipts().is_empty()); +} + +/// The same limit mid-block: the transaction that would cross it is refused before it runs, so +/// unlike a post-execution dimension the block never crosses this one. +#[test] +fn test_block_tx_size_limit_exceeded_mid_block() { + let mut state = state_with_log_contract(100); + let one = MegaTransactionExt::tx_size(&user_tx(0, 1_000_000)); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_encode_size_limit(one * 2 + 1)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the first body fits"); + executor.execute_transaction(&user_tx(1, 1_000_000)).expect("the second body fits"); + executor.execute_transaction(&user_tx(2, 1_000_000)).expect_err("the third body does not"); + + assert!(executor.limiter().block_tx_size_used <= one * 2 + 1, "the limit was never crossed"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); +} + +/// Transactions of different sizes accumulate by their own sizes, and the one that does not fit +/// is the one refused. +#[test] +fn test_block_tx_size_limit_with_varying_sizes() { + let mut state = state_with_log_contract(100); + let small = user_tx(0, 1_000_000); + let large = common::user_tx_with_input(1, incompressible(4_096), 3_000_000); + let (small_size, large_size) = + (MegaTransactionExt::tx_size(&small), MegaTransactionExt::tx_size(&large)); + assert!(large_size > small_size); + + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits().with_block_txs_encode_size_limit(small_size + large_size), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&small).expect("the small body fits"); + assert_eq!(executor.limiter().block_tx_size_used, small_size); + executor.execute_transaction(&large).expect("the large body fits exactly"); + assert_eq!(executor.limiter().block_tx_size_used, small_size + large_size); + + executor.execute_transaction(&user_tx(2, 1_000_000)).expect_err("nothing fits any more"); +} + +/// The block's counters may move between a transaction executing and its commit, so what it +/// adds is checked against the block once more before it is committed. +/// +/// Three transactions are executed while none has committed, so each passes admission; two +/// commit and fill the block, and the third is refused at commit. +#[test] +fn test_commit_time_pre_execution_check_parallel_simulation() { + const TX_GAS_LIMIT: u64 = 100_000; + + let db = || { + let mut db = common::database(); + db.set_account_code(CONTRACT, log_generating_contract(100)); + db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); + db.set_account_balance(CALLER3, U256::from(1_000_000_000_000_000_u64)); + revm::database::State::builder().with_database(db).build() + }; + + // What one of these transactions actually spends, so the block below has room for exactly + // two of them and the third finds it full. + let spent = { + let mut state = db(); + let mut probe = executor(&mut state, common::unlimited_ctx()); + probe.apply_pre_execution_changes().expect("the block starts"); + probe + .execute_transaction(&tx_from(CALLER, 0, TX_GAS_LIMIT)) + .expect("the probe transaction executes") + .tx_gas_used() + }; + let block_gas_limit = spent + TX_GAS_LIMIT; + + let mut state = db(); + let mut env = common::evm_env(); + env.block_env = BlockEnv { gas_limit: block_gas_limit, ..env.block_env }; + let mut executor = common::executor_with_env(&mut state, common::unlimited_ctx(), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = tx_from(CALLER, 0, TX_GAS_LIMIT); + let second = tx_from(CALLER2, 0, TX_GAS_LIMIT); + let third = tx_from(CALLER3, 0, TX_GAS_LIMIT); + + let first = executor.run_transaction(&first).expect("the block has room"); + let second = executor.run_transaction(&second).expect("nothing has committed yet"); + let third = executor.run_transaction(&third).expect("nothing has committed yet"); + + executor.commit_transaction_outcome(second).expect("the block has room"); + executor.commit_transaction_outcome(third).expect("the block is full now"); + + let err = executor + .commit_transaction_outcome(first) + .expect_err("the block filled up while this transaction waited"); + assert!(format!("{err}").contains("more than blocks available gas"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); +} + +/// A transaction that reports its own sizes is executed on the figures it reports. A debug build +/// cross-checks them against a fresh recompute, so an understated one trips here instead of +/// passing a limit it should have been refused by. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "do not match a fresh recompute")] +fn test_run_transaction_rejects_understated_cached_da_size() { + const TX_DA_SIZE_LIMIT: u64 = 80; + const REPORTED_DA_SIZE: u64 = 50; + + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_tx_da_size_limit(TX_DA_SIZE_LIMIT)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let envelope = common::tx(0, CONTRACT, Bytes::new(), 100_000); + let real_da_size = MegaTransactionExt::estimated_da_size(&envelope); + assert!( + real_da_size > TX_DA_SIZE_LIMIT, + "the test needs a recomputed size ({real_da_size}) above the limit" + ); + const { assert!(REPORTED_DA_SIZE < TX_DA_SIZE_LIMIT, "the reported size must pass the limit") }; + + let recovered = Recovered::new_unchecked(&envelope, CALLER); + executor + .run_transaction(&recovered) + .expect_err("a transaction that recomputes its sizes is refused by the limit"); + + let enriched = EnrichedMegaTx::new( + recovered, + MegaTransactionExt::tx_hash(&envelope), + REPORTED_DA_SIZE, + MegaTransactionExt::tx_size(&envelope), + ); + let _ = executor.run_transaction(&enriched); +} + +/// The common case of the same path: figures that agree with the transaction are used as they +/// are, and the outcome carries them. +#[test] +fn test_execute_mega_transaction_succeeds_with_accurate_cache() { + let mut state = common::state(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let envelope = common::tx(0, CONTRACT, Bytes::new(), 1_000_000); + let expected_da_size = MegaTransactionExt::estimated_da_size(&envelope); + let expected_tx_size = MegaTransactionExt::tx_size(&envelope); + let enriched = EnrichedMegaTx::new_slow(Recovered::new_unchecked(&envelope, CALLER)); + + let outcome = executor + .execute_mega_transaction(&enriched) + .expect("figures that agree with the transaction are used as they are"); + + assert_eq!(outcome.da_size, expected_da_size); + assert_eq!(outcome.tx_size, expected_tx_size); +} + +/// A deposit is exempt from its own data-availability size limit: the chain cannot censor it. +#[test] +fn test_deposit_transaction_exempt_from_single_tx_da_limit() { + const DA_SIZE_LIMIT: u64 = 100; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits() + .with_tx_da_size_limit(DA_SIZE_LIMIT) + .with_block_da_size_limit(DA_SIZE_LIMIT * 10), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let deposit = common::deposit_tx(incompressible(100_000), 3_000_000); + assert!(MegaTransactionExt::estimated_da_size(&deposit) > DA_SIZE_LIMIT * 10); + + executor.execute_transaction(&deposit).expect("a deposit is exempt"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// A user transaction is not exempt from the same limit. +#[test] +fn test_regular_transaction_rejected_by_single_tx_da_limit() { + const DA_SIZE_LIMIT: u64 = 100; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits() + .with_tx_da_size_limit(DA_SIZE_LIMIT) + .with_block_da_size_limit(DA_SIZE_LIMIT * 10), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let tx = common::user_tx_with_input(0, incompressible(100_000), 3_000_000); + assert!(MegaTransactionExt::estimated_da_size(&tx) > DA_SIZE_LIMIT); + + let err = executor.execute_transaction(&tx).expect_err("the limit binds a user transaction"); + assert!( + format!("{err}").contains("Transaction data availability size limit exceeded"), + "{err}" + ); +} + +/// A deposit is exempt from the block's data-availability size too, and adds nothing to it. +#[test] +fn test_deposit_exempt_from_block_da_limit() { + const DA_SIZE_LIMIT: u64 = 100; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits() + .with_tx_da_size_limit(DA_SIZE_LIMIT * 10_000) + .with_block_da_size_limit(DA_SIZE_LIMIT), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&common::deposit_tx(incompressible(100_000), 3_000_000)) + .expect("a deposit is exempt"); + + assert_eq!(executor.limiter().block_da_size_used, 0, "and adds nothing to the block's"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// The three cases in one block: a small user transaction, a large deposit, a large user +/// transaction. +#[test] +fn test_mixed_deposit_and_regular_transactions() { + const DA_SIZE_LIMIT: u64 = 100; + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx( + BlockLimits::no_limits() + .with_tx_da_size_limit(DA_SIZE_LIMIT) + .with_block_da_size_limit(DA_SIZE_LIMIT * 10), + ), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&user_tx(0, 100_000)).expect("a small user transaction fits"); + executor + .execute_transaction(&common::deposit_tx(incompressible(100_000), 3_000_000)) + .expect("a deposit is exempt"); + executor + .execute_transaction(&common::user_tx_with_input(1, incompressible(100_000), 3_000_000)) + .expect_err("a large user transaction is not"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); +} diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs new file mode 100644 index 000000000..f92cff133 --- /dev/null +++ b/crates/mega-evm/tests/block/main.rs @@ -0,0 +1,10 @@ +//! Tests of the block executor. + +mod block_hashes; +mod common; +mod counters; +mod factory; +mod inspector; +mod limits; +mod rules; +mod schedule; diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs new file mode 100644 index 000000000..dc5d5d223 --- /dev/null +++ b/crates/mega-evm/tests/block/rules.rs @@ -0,0 +1,218 @@ +//! The block rules the Karst base brings, each on its own. + +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{Bytes, U256}; +use mega_evm::BlockLimits; +use op_revm::{ + constants::{ + DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, + OPERATOR_FEE_CONSTANT_OFFSET, OPERATOR_FEE_RECIPIENT, OPERATOR_FEE_SCALAR_OFFSET, + }, + L1BlockInfo, +}; +use revm::{context::ContextTr, database::State, Database}; + +use crate::common::{ + self, deposit_tx, executor, unlimited_ctx, user_tx, BLOCK_GAS_LIMIT, BLOCK_NUMBER, +}; + +/// The word the L1 block contract holds at its scalars slot: the data-availability footprint +/// gas scalar, the operator fee scalar and the operator fee constant, at the offsets the fork +/// reads them from. +fn scalars_word(da_footprint: u16, operator_fee_scalar: u32, operator_fee_constant: u64) -> U256 { + let mut word = [0_u8; 32]; + word[DA_FOOTPRINT_GAS_SCALAR_OFFSET..DA_FOOTPRINT_GAS_SCALAR_OFFSET + 2] + .copy_from_slice(&da_footprint.to_be_bytes()); + word[OPERATOR_FEE_SCALAR_OFFSET..OPERATOR_FEE_SCALAR_OFFSET + 4] + .copy_from_slice(&operator_fee_scalar.to_be_bytes()); + word[OPERATOR_FEE_CONSTANT_OFFSET..OPERATOR_FEE_CONSTANT_OFFSET + 8] + .copy_from_slice(&operator_fee_constant.to_be_bytes()); + U256::from_be_bytes(word) +} + +/// A state whose L1 block contract holds `word` at its scalars slot. +fn state_with_scalars(word: U256) -> State { + let mut db = common::database(); + db.set_account_storage(L1_BLOCK_CONTRACT, DA_FOOTPRINT_GAS_SCALAR_SLOT, word); + State::builder().with_database(db).build() +} + +/// Rule 1, alloy-op-evm's `no_user_tx_activation_block`: the block a fork activates in carries +/// the chain's own transactions only, and a user transaction in it is refused before it runs. +#[test] +fn test_activation_block_rejects_a_user_transaction() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx().with_no_user_tx_activation_block(true)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let err = executor + .execute_transaction(&user_tx(0, 100_000)) + .expect_err("a user transaction has no place in an activation block"); + + assert!(format!("{err}").contains("non-deposit transaction in fork activation block"), "{err}"); + assert!(executor.receipts().is_empty(), "nothing was packed"); +} + +/// Rule 1, the other half: the same block executes deposits. +#[test] +fn test_activation_block_executes_deposits() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx().with_no_user_tx_activation_block(true)); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&deposit_tx(Bytes::new(), 100_000)) + .expect("a deposit is what an activation block is for"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// Rule 2, alloy-op-evm's Jovian DA footprint block limit: with no scalar in state the rule +/// costs nothing and the block reports no blob gas. +#[test] +fn test_da_footprint_is_inert_without_a_scalar() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.blob_gas_used, 0, "no scalar, no footprint"); +} + +/// Rule 2: a non-zero scalar makes every non-deposit transaction cost footprint, and the block +/// reports the accumulated footprint as its blob gas used. +#[test] +fn test_da_footprint_within_the_block_budget_is_reported_as_blob_gas() { + const SCALAR: u16 = 3; + let mut state = state_with_scalars(scalars_word(SCALAR, 0, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = user_tx(0, 100_000); + let second = user_tx(1, 100_000); + let expected = (mega_evm::MegaTransactionExt::estimated_da_size(&first) + + mega_evm::MegaTransactionExt::estimated_da_size(&second)) * + u64::from(SCALAR); + + executor.execute_transaction(&first).expect("the first transaction executes"); + executor.execute_transaction(&second).expect("the second transaction executes"); + + assert_eq!(executor.limiter().block_da_footprint_used, expected); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.blob_gas_used, expected, "the block reports its footprint as blob gas"); +} + +/// Rule 2: a transaction whose footprint does not fit in the block's budget — the block's gas +/// limit — is refused, and the block keeps the footprint it had. +#[test] +fn test_da_footprint_over_the_block_budget_refuses_the_transaction() { + let mut state = state_with_scalars(scalars_word(u16::MAX, 0, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let big = common::user_tx_with_input(0, common::incompressible(100_000), 3_000_000); + let footprint = mega_evm::MegaTransactionExt::estimated_da_size(&big) * u64::from(u16::MAX); + assert!(footprint > BLOCK_GAS_LIMIT, "the test needs a footprint the block cannot hold"); + + let err = + executor.execute_transaction(&big).expect_err("the footprint does not fit in the block"); + + assert!( + format!("{err}").contains("DA footprint exceeds available block DA footprint"), + "{err}" + ); + assert_eq!(executor.limiter().block_da_footprint_used, 0); +} + +/// Rule 2: a deposit is exempt from the footprint, as it is from the data-availability size. +#[test] +fn test_deposits_do_not_count_towards_the_da_footprint() { + let mut state = state_with_scalars(scalars_word(u16::MAX, 0, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&deposit_tx(common::incompressible(100_000), 3_000_000)) + .expect("a deposit is exempt from the footprint rule"); + + assert_eq!(executor.limiter().block_da_footprint_used, 0); +} + +/// Rule 3, alloy-op-evm's `l1_block_info`: the read at the start of the block is failable, and +/// an empty L1 block contract answers with zeroes rather than an error. +#[test] +fn test_l1_block_info_reads_an_empty_contract_as_zero() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx()); + + executor.apply_pre_execution_changes().expect("an empty L1 block contract is not an error"); + + let chain = executor.evm().ctx().chain(); + assert_eq!(chain.l2_block, Some(U256::from(BLOCK_NUMBER))); + assert_eq!(chain.da_footprint_gas_scalar, Some(0)); + assert_eq!(chain.operator_fee_scalar, Some(U256::ZERO)); + assert_eq!(chain.l1_base_fee, U256::ZERO); +} + +/// Rule 3: the read is conditioned on the block the info is for, so info a caller placed for +/// this very block is not overwritten by what state holds. +#[test] +fn test_l1_block_info_of_this_block_is_not_overwritten() { + let mut state = state_with_scalars(scalars_word(7, 0, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.evm_mut().ctx_mut().modify_chain(|chain| { + *chain = L1BlockInfo { + l2_block: Some(U256::from(BLOCK_NUMBER)), + operator_fee_scalar: Some(U256::from(11)), + operator_fee_constant: Some(U256::ZERO), + da_footprint_gas_scalar: Some(5), + ..Default::default() + }; + }); + + executor.apply_pre_execution_changes().expect("the block starts"); + + let chain = executor.evm().ctx().chain(); + assert_eq!(chain.operator_fee_scalar, Some(U256::from(11)), "the caller's info stands"); + assert_eq!(chain.da_footprint_gas_scalar, Some(5)); +} + +/// Rule 3: the operator fee the reward path pays is the one op-revm computes for the Karst +/// spec — gas x scalar x 100 — and not the pre-Jovian formula, which would divide it to zero. +#[test] +fn test_operator_fee_is_charged_on_the_karst_formula() { + const OPERATOR_FEE_SCALAR: u32 = 1; + let mut state = state_with_scalars(scalars_word(0, OPERATOR_FEE_SCALAR, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let gas = executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + let (evm, _) = executor.finish_with_counters().expect("the block finishes"); + + let (db, _) = alloy_evm::Evm::finish(evm); + let paid = db + .basic(OPERATOR_FEE_RECIPIENT) + .expect("the recipient is readable") + .expect("the operator fee created the recipient") + .balance; + assert_eq!( + paid, + U256::from(gas.tx_gas_used()) * U256::from(OPERATOR_FEE_SCALAR) * U256::from(100), + "the Karst formula multiplies by 100 where the pre-Jovian one divides by 1e6" + ); +} + +/// The block's gas limit is the block environment's, whatever the context carries: it is the +/// number consensus holds the block to, and the budget the footprint is held to. +#[test] +fn test_block_gas_limit_comes_from_the_block_environment() { + let mut state = common::state(); + let ctx = common::block_ctx(BlockLimits::no_limits().with_block_gas_limit(1)); + let executor = executor(&mut state, ctx); + + assert_eq!(executor.limiter().limits.block_gas_limit, BLOCK_GAS_LIMIT); + assert_eq!(executor.limiter().available_da_footprint(), BLOCK_GAS_LIMIT); +} diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs new file mode 100644 index 000000000..fd5c72154 --- /dev/null +++ b/crates/mega-evm/tests/block/schedule.rs @@ -0,0 +1,93 @@ +//! The schedule a block runs on, and what is checked of it before the block starts. + +use alloy_evm::block::BlockExecutor; +use alloy_hardforks::ForkCondition; +use alloy_primitives::{address, Address}; +use mega_evm::{ + chain_activation, mainnet_hardforks, testnet_hardforks, HardforkParams, HardforkParamsError, + MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError, MAINNET_CHAIN_ID, + TESTNET_CHAIN_ID, +}; + +use crate::common::{self, user_tx}; + +/// Parameters a fork requires from the chain configuration. Satin requires none yet, so this +/// stands in for the ones the mechanisms that bring the system contracts will register. +#[derive(Debug, Clone, PartialEq, Eq)] +struct RegistryParams { + sequencer: Address, +} + +impl HardforkParams for RegistryParams { + const FORK: MegaHardfork = MegaHardfork::Satin; + const NAME: &'static str = "RegistryParams"; + + fn validate(&self) -> Result<(), HardforkParamsError> { + if self.sequencer.is_zero() { + return Err(HardforkParamsError { message: "sequencer must be set".into() }); + } + Ok(()) + } +} + +fn params() -> RegistryParams { + RegistryParams { sequencer: address!("0x4444444444444444444444444444444444444444") } +} + +/// The canonical schedules are the chain activation table: the two are one source, so a +/// timestamp cannot be right in one and wrong in the other. What the published upgrade pages +/// say about them is the specification's side, not this crate's. +#[test] +fn test_canonical_schedules_match_the_chain_activation_table() { + for (chain_id, schedule) in + [(MAINNET_CHAIN_ID, mainnet_hardforks()), (TESTNET_CHAIN_ID, testnet_hardforks())] + { + let activation = chain_activation(chain_id).expect("a known chain"); + for fork in MegaHardfork::VARIANTS { + assert_eq!( + schedule.mega_fork_activation(*fork), + activation.condition(*fork), + "{fork:?} on chain {chain_id}" + ); + } + assert_eq!(schedule.validate_schedule(), Ok(()), "chain {chain_id} loads"); + } + + // Satin is not scheduled on either chain yet, so neither runs this engine. + assert_eq!(mainnet_hardforks().spec_id(u64::MAX), None); + assert_eq!(testnet_hardforks().spec_id(u64::MAX), None); +} + +/// A schedule that activates a fork without the parameters it requires fails when the chain +/// configuration is loaded, not at the fork's first block: the block executor is never built +/// from one. +#[test] +fn test_a_schedule_missing_its_fork_params_is_refused_at_load() { + let missing = + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); + assert_eq!( + missing.require_params::(), + Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "RegistryParams" }), + "the load refuses it" + ); + + // With the parameters attached the schedule loads, and a block runs on it. + let loaded = missing.with_params(params()); + assert_eq!(loaded.require_params::(), Ok(())); + assert_eq!(loaded.validate_schedule(), Ok(())); + assert_eq!(loaded.fork_params::(), Some(¶ms())); + + let mut state = common::state(); + let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), loaded); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); +} + +/// A fork the schedule does not activate needs no parameters. +#[test] +fn test_an_unscheduled_fork_needs_no_params() { + let unscheduled = MegaHardforkConfig::default(); + + assert_eq!(unscheduled.require_params::(), Ok(())); + assert_eq!(unscheduled.validate_schedule(), Ok(())); +} From 60ea808ccd25bd6cb5a11fdbcfffb558954cd7e5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:33:09 +0800 Subject: [PATCH 103/201] docs: say the schedule is built once for the process, not once per configuration --- crates/mega-evm/src/evm/schedule.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 08db52a57..50e612870 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -14,8 +14,9 @@ //! (`tx_account_write_cost`, `tx_create_access_cost`), the zero `code_deposit_cost` and the floor. //! The history entry stays at zero: history gas is its own mechanism and switches it on. //! -//! The schedule is built once per `CfgEnv` — [`MegaContext::with_cfg`](crate::MegaContext) — and -//! read per opcode out of the table revm already carries, so nothing here runs on the hot path. +//! The schedule is built once for the process and handed to every configuration as a shared +//! clone ([`MegaContext::with_cfg`](crate::MegaContext)); an opcode reads its price out of the +//! table revm already carries. Nothing here runs on the hot path. use revm::{ context_interface::cfg::{GasId, GasParams}, From 940b5efd78b1823df7668a6ac492df567a4cb4c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:34:30 +0800 Subject: [PATCH 104/201] bench(block): measure a block through the executor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two workloads of 64 transactions each — value transfers and storage writes — run through `MegaBlockExecutor` with the block's limits unset, so what the numbers carry is the executor's own per-transaction work: the admission checks, the size estimates, the counters, the receipt and the commit. The measurement covers the whole block a node executes, from the pre-block calls to the finish. Each workload also runs once outside the measurement, so a block that does not execute fails the bench rather than being timed. --- .github/workflows/benchmark.yml | 9 +- crates/mega-evm/Cargo.toml | 10 +- crates/mega-evm/benches/block.rs | 153 +++++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 7 deletions(-) create mode 100644 crates/mega-evm/benches/block.rs diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index a7051b726..b6ab9e728 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -199,10 +199,11 @@ jobs: strategy: fail-fast: false matrix: - # The Satin bench set: `transact`, `corpus` and `factory`, until the - # suite is rebuilt on Satin, which restores the full list. Scheduled and - # comment-triggered runs use the default branch's copy of this file. - target: [corpus, factory, transact] + # The Satin bench set: `block`, `transact`, `corpus` and `factory`, + # until the suite is rebuilt on Satin, which restores the full list. + # Scheduled and comment-triggered runs use the default branch's copy of + # this file. + target: [block, corpus, factory, transact] steps: - uses: actions/checkout@v4 with: diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index 79cc1b469..0b09d29d0 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -59,9 +59,13 @@ std = [ test-utils = ["dep:derive_more"] # The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (the JSON scenarios under -# benches/scenarios, a bench input) and `factory` (EVM construction). The inputs under -# benches/data (revm_bench) and benches/fixtures (attack_replay) stay for the rebuild of the rest -# of the suite. +# benches/scenarios, a bench input), `factory` (EVM construction) and `block` (a block through +# MegaBlockExecutor). The inputs under benches/data (revm_bench) and benches/fixtures +# (attack_replay) stay for the rebuild of the rest of the suite. +[[bench]] +name = "block" +harness = false + [[bench]] name = "corpus" harness = false diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs new file mode 100644 index 000000000..256734203 --- /dev/null +++ b/crates/mega-evm/benches/block.rs @@ -0,0 +1,153 @@ +//! A block through `MegaBlockExecutor`: what block execution costs per transaction on top of +//! what the transaction itself costs. +//! +//! Two workloads of `N` transactions each, both with the block's limits unset so the +//! per-transaction work is the executor's own: the admission checks, the size estimates, the +//! counters, the receipt and the commit. +//! +//! - `transfers`: value transfers to accounts with no code — the cheapest transaction there is, so +//! the executor's own cost is most of what is measured. +//! - `storage_writes`: calls to a contract that writes a slot, so every transaction also carries a +//! write record through the counters and a log-free receipt. +//! +//! The pre-block calls and the state the block is built on are setup, and the measurement runs +//! `apply_pre_execution_changes`, the transactions and `finish` — the whole block a node +//! executes. +#![allow(missing_docs)] + +use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, +}; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::State, +}; +use std::hint::black_box; + +/// Transactions in the block. +const N: u64 = 64; + +/// The chain the block belongs to. +const CHAIN_ID: u64 = 4_326; + +/// The block the bench executes. +const BLOCK_NUMBER: u64 = 1_000; + +/// The timestamp of the block the bench executes. +const BLOCK_TIMESTAMP: u64 = 1_800_000_000; + +const SENDER: Address = address!("0x2000000000000000000000000000000000000002"); +const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); +const WRITER: Address = address!("0x1000000000000000000000000000000000000001"); + +/// Code that writes one slot, so a call to it leaves a write record behind. +fn writer_code() -> Bytes { + BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).stop().build() +} + +/// The database every iteration starts from. +fn database() -> MemoryDatabase { + let mut db = MemoryDatabase::default(); + db.set_account_code(WRITER, writer_code()); + db.set_account_code(RECIPIENT, Bytes::new()); + db.set_account_balance(SENDER, U256::from(1_000_000_000_000_000_u64)); + db +} + +fn evm_env() -> EvmEnv { + let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg_env.chain_id = CHAIN_ID; + EvmEnv { + cfg_env, + block_env: BlockEnv { + number: U256::from(BLOCK_NUMBER), + timestamp: U256::from(BLOCK_TIMESTAMP), + gas_limit: 1_000_000_000, + ..Default::default() + }, + } +} + +/// A block whose limits are all unset, so what is measured is the executor's own work. +fn block_ctx() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits()) +} + +/// `N` transactions to `to`, one per nonce. +fn transactions(to: Address, value: u64, gas_limit: u64) -> Vec> { + (0..N) + .map(|nonce| { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 0, + gas_limit, + to: TxKind::Call(to), + value: U256::from(value), + input: Bytes::new(), + }; + let signed = + Signed::new_unchecked(tx, Signature::test_signature(), B256::repeat_byte(1)); + Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), SENDER) + }) + .collect() +} + +fn bench_block(c: &mut Criterion) { + let spec = MegaHardforkConfig::default().with_all_activated(); + let workloads = [ + ("transfers", transactions(RECIPIENT, 1, 100_000)), + ("storage_writes", transactions(WRITER, 0, 200_000)), + ]; + + let mut group = c.benchmark_group("block"); + for (name, txs) in &workloads { + // The workload runs once outside the measurement, so a block that does not execute is + // caught here rather than being measured. + { + let mut state = State::builder().with_database(database()).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); + let mut executor = + MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); + executor.apply_pre_execution_changes().expect("the block starts"); + for tx in txs { + executor.execute_transaction(tx).expect("the transaction executes"); + } + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), N as usize); + assert!(result.gas.execution > 0); + } + + group.bench_function(*name, |b| { + b.iter_batched( + || State::builder().with_database(database()).build(), + |mut state| { + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + block_ctx(), + &spec, + OpAlloyReceiptBuilder::default(), + ); + executor.apply_pre_execution_changes().unwrap(); + for tx in txs { + black_box(executor.execute_transaction(tx).unwrap()); + } + black_box(executor.finish_with_counters().unwrap().1) + }, + BatchSize::SmallInput, + ); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_block); +criterion_main!(benches); From 771290c142a0f2b169bfe33ea54b542a5e340509 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:34:35 +0800 Subject: [PATCH 105/201] test(evm): price a modexp above the minimum on the EIP-7883 formula MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The one-byte vector lands on the Osaka 500-gas minimum, which distinguishes the entry from Berlin's 200 but not the formula from the floor. A 32-byte vector with a full 32-byte exponent costs 4,080 — the multiplication complexity times the iteration count, with the divisor EIP-7883 removes. --- crates/mega-evm/src/evm/precompiles.rs | 48 +++++++++++++++++++------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index c60400e7d..2a59f08fe 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -288,20 +288,44 @@ mod tests { assert_eq!(over.result, InstructionResult::PrecompileError); } - /// `ModExp` runs on the Osaka formula, which prices a small exponentiation well above the - /// 200-gas Berlin minimum the earlier entry charged. + /// A `ModExp` header of `base_len`, `exp_len` and `mod_len`, followed by the operands. + fn modexp_input(base: &[u8], exponent: &[u8], modulus: &[u8]) -> Bytes { + let mut input = std::vec![0u8; 96]; + input[31] = base.len() as u8; + input[63] = exponent.len() as u8; + input[95] = modulus.len() as u8; + input.extend_from_slice(base); + input.extend_from_slice(exponent); + input.extend_from_slice(modulus); + Bytes::from(input) + } + + /// `ModExp` is the Osaka entry: a one-byte exponentiation costs the Osaka 500-gas minimum, + /// not the 200 of the Berlin entry Karst removed, and an exponentiation large enough for the + /// EIP-7883 formula to bite is priced by the formula rather than by the minimum. #[test] fn test_modexp_is_priced_on_the_osaka_formula() { let address = *revm::precompile::modexp::OSAKA.address(); - // base = 3 (1 byte), exponent = 2 (1 byte), modulus = 5 (1 byte): 3^2 mod 5 = 4. - let mut input = std::vec![0u8; 96]; - input[31] = 1; - input[63] = 1; - input[95] = 1; - input.extend_from_slice(&[3, 2, 5]); - let result = run(address, Bytes::from(input), 100_000); - assert_eq!(result.result, InstructionResult::Return); - assert_eq!(result.output.as_ref(), &[4]); - assert_eq!(result.gas.total_gas_spent(), 500, "the Osaka minimum"); + + // base = 3, exponent = 2, modulus = 5, one byte each: 3^2 mod 5 = 4. + let small = run(address, modexp_input(&[3], &[2], &[5]), 100_000); + assert_eq!(small.result, InstructionResult::Return); + assert_eq!(small.output.as_ref(), &[4]); + assert_eq!(small.gas.total_gas_spent(), 500, "the Osaka minimum"); + + // 32-byte operands with a 32-byte exponent: the formula's cost is above the minimum. + let thirty_two = |last: u8| { + let mut operand = [0u8; 32]; + operand[31] = last; + operand + }; + let large = + run(address, modexp_input(&thirty_two(3), &[0xffu8; 32], &thirty_two(7)), 1_000_000); + assert_eq!(large.result, InstructionResult::Return); + // EIP-7883 prices this as multiplication complexity (16, for operands of 32 bytes or + // fewer) times the iteration count (255, one below the exponent's 256 bits), with no + // divisor: 4,080. The Berlin entry Karst removed divided that by three. + assert_eq!(large.gas.total_gas_spent(), 16 * 255); + assert_eq!(large.gas.total_gas_spent(), 4_080); } } From 59f6393417fcd081c906073c129834cab56b63ed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:37:43 +0800 Subject: [PATCH 106/201] docs: say what block execution does today The module table's `block/` row, the bench list and the test targets name what is there now; the executor's three block rules and its two empty hook points are stated where the engine's behavior is described. The per-fork parameter rule and the pre-block helper rule are no longer conditional: both have code to point at. --- AGENTS.md | 15 ++++++++++----- REVIEW.md | 2 +- crates/mega-evm/README.md | 23 ++++++++++++++++++++++- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b5d356df..60b2b26c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (JSON scenarios, a bench input), `factory` (EVM construction) +# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (JSON scenarios, a bench input), `factory` (EVM construction), `block` (a block through MegaBlockExecutor) cargo bench -p mega-evm --bench # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) @@ -87,7 +87,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | Module | Holds now | Filled by | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton, `BlockGasCounters` (`result.rs`) | the block executor (Karst block rules, filling `BlockGasCounters`, refusing `has_rewriting_inspector`), the pre-block system calls, the system contract deployments | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | | `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | | `access/` | nothing | volatile-data access tracking (detention) | @@ -106,6 +106,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. +- `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. + It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read once at the start of the block — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. + `apply_pre_execution_changes` refuses a rewriting inspector and names two hook points that are empty today: system contract deployment and the pre-block system calls. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. ### Contracts of the common execution layer @@ -145,6 +148,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer ## Test Organization (`crates/mega-evm/tests/`) - `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). +- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters, the factory and the admission gate. - `_pending/` — the legacy tests the test inventory keeps, parked until the mechanism they test lands. It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. The change that ports a pending test deletes it from `_pending/` in the same commit. @@ -229,11 +233,12 @@ When the agent is requested to implement a new feature or bug fix, it should con Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. Only `CALL` and `STATICCALL` reach interceptor dispatch; `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard before any interceptor is consulted. Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. -- **Validate per-fork parameters at load time (once the block executor lands).** +- **Validate per-fork parameters at load time.** A hardfork parameters type overrides `HardforkParams::validate()` with field-level invariant checks, so a bad chain config fails when it is loaded rather than at the fork's first block. - The fork-requires-params rule is registered in the schedule validation too, so a schedule that activates the fork without its params is rejected at load time. -- **Pre-block helpers must return state, not commit directly (pre-block system calls, system contract deployment).** + The fork-requires-params rule is registered in `MegaHardforks::validate_schedule` too — one `require_params::

()` per params type — so a schedule that activates the fork without its params is rejected at load time. +- **Pre-block helpers must return state, not commit directly.** Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. + `block/eips.rs` holds the ones that exist — the EIP-2935 and EIP-4788 calls and the post-block balance increments — and the block executor is what commits them. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. diff --git a/REVIEW.md b/REVIEW.md index d9f47b9ed..9b2a08d4a 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,7 +24,7 @@ This is the single most important correctness concern in mega-evm. - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. - Pre-block helpers (system contract deploys, pre-exec system calls, etc.) must return `Option` for the block executor to commit — never call `db.commit(...)` directly. Even idempotent "no change" paths must return `Some(EvmState)` with a read-only account entry; silently returning `None` drops the account from the stateless witness read set and produces an incomplete proof. - On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the pre-block helpers arrive with the pre-block system calls and the system contract deployments. + On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the helpers that exist live in `crates/mega-evm/src/block/eips.rs` and the block executor is what commits them, and the rest arrive with the pre-block system calls and the system contract deployments. The same applies inside execution: read through the journal (`inspect_account`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state — and an early halt placed before the sandbox state merge drops that read set entirely. - Per-frame gas mechanisms (stipends, adjustments) must handle all frame termination paths: system contract interception, gas rescue on limit exceed, and frame return. Missing any path causes gas leakage. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 9c14e8727..6ab74ea8a 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -32,6 +32,10 @@ The common execution layer is in place: the frame lifecycle the later mechanisms No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. `MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. +Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read once at the start of the block. +Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers. +`apply_pre_execution_changes` leaves two hook points empty: system contract deployment and the pre-block system calls. + SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. ## Quick start @@ -52,7 +56,24 @@ let tx = OpTx(op_revm::OpTransaction { let result = evm.transact_raw(tx)?; ``` -A block executor admits an inspected transaction only from an EVM whose inspector is declared read-only: +A node executes a block through the factory, which installs the block's limits on the EVM: + +```rust,ignore +use alloy_evm::block::{BlockExecutor as _, BlockExecutorFactory as _}; +use mega_evm::{BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory}; + +let factory = MegaBlockExecutorFactory::new(receipt_builder, chain_spec, MegaEvmFactory::new()); +let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_block_root, extra_data, BlockLimits::no_limits()); + +let mut executor = factory.create_executor(evm, ctx); +executor.apply_pre_execution_changes()?; +for tx in transactions { + executor.execute_transaction(tx)?; +} +let (evm, result) = executor.finish_with_counters()?; +``` + +Block execution admits an inspected transaction only from an EVM whose inspector is declared read-only: ```rust,ignore use mega_evm::DeclaredObserver; From 414f8a89f35d3d4709703af100f9ba406d01e7b0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:41:56 +0800 Subject: [PATCH 107/201] test(evm): cover the precompile provider's warm set and membership answer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two mutation survivors of the provider: warm_addresses returning an empty set, and contains answering the same for every address. The first is observable in gas — a call to a precompile pays no cold-account surcharge where a call to a plain address does; the second has no caller inside revm's execution path, so a direct test covers what a node's RPC asks. --- crates/mega-evm/src/evm/precompiles.rs | 18 ++++++++ crates/mega-evm/tests/satin/precompile_gas.rs | 43 ++++++++++++++++++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 2a59f08fe..712f504e2 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -250,6 +250,24 @@ mod tests { ); } + /// `contains` answers for the set the provider carries: every Satin address is a precompile + /// and an address outside the set is not. Nothing in revm's execution path asks, so only a + /// direct call covers it; a node's RPC is the caller that does. + #[test] + fn test_contains_answers_for_the_satin_set() { + let map = satin_precompiles_map(); + let contains = |address: &Address| { + PrecompileProvider::>::contains(&map, address) + }; + for address in satin_precompiles().addresses() { + assert!(contains(address), "{address} is a precompile"); + } + assert!(contains(&kzg_point_evaluation::ADDRESS)); + for address in [Address::ZERO, Address::repeat_byte(0xee), Address::with_last_byte(0x7f)] { + assert!(!contains(&address), "{address} is not a precompile"); + } + } + /// Every other Karst entry is op-revm's, at the address op-revm has it. #[test] fn test_every_other_entry_is_the_karst_one() { diff --git a/crates/mega-evm/tests/satin/precompile_gas.rs b/crates/mega-evm/tests/satin/precompile_gas.rs index f7a0f5f83..7510c138b 100644 --- a/crates/mega-evm/tests/satin/precompile_gas.rs +++ b/crates/mega-evm/tests/satin/precompile_gas.rs @@ -14,7 +14,7 @@ use mega_evm::{ MegaEvm, }; use revm::{ - bytecode::opcode::{MSTORE, PUSH0, RETURN, STATICCALL}, + bytecode::opcode::{MSTORE, POP, PUSH0, RETURN, STATICCALL}, precompile::kzg_point_evaluation::kzg_to_versioned_hash, primitives::hex, }; @@ -155,6 +155,47 @@ fn test_every_verification_failure_burns_the_forwarded_gas() { } } +/// The precompile addresses are warm from the start of a transaction, so a call to one pays no +/// cold-account surcharge where a call to a plain address of the same shape does. +#[test] +fn test_the_precompile_addresses_are_warm() { + /// The identity precompile: 15 gas for an empty input. + const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); + /// A plain address that holds nothing, so a call to it is a cold account access. + const PLAIN: Address = address!("00000000000000000000000000000000000000ee"); + + // `STATICCALL(50_000, target, 0, 0, 0, 0)` and stop: the call itself is the only difference. + let caller_of = |target: Address| { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(target) + .push_number(50_000u64) + .append(STATICCALL) + .append(POP) + .stop() + .build() + }; + let gas_of = |target: Address| { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, caller_of(target)); + let mut evm = MegaEvm::new(context(db)); + let result = evm + .transact_raw(call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid") + .result; + assert!(result.is_success(), "{result:?}"); + result.gas().tx_gas_used() + }; + + // The cold surcharge the plain address pays and the precompile does not, less the 15 gas the + // identity precompile charges for an empty input. + assert_eq!(gas_of(PLAIN) - gas_of(IDENTITY), 2_500 - 15); +} + /// A caller that forwards less than the price is out of gas before verification runs, so the /// price is a floor on what a call must carry, not only on what it pays. #[test] From b2dc7c29ec9b6e027e22750f23fec26b6b48c4af Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:42:39 +0800 Subject: [PATCH 108/201] test: drop the blank line the ported rows left at the end of two parked files The rows ported out of these two files took their trailing content with them and left the files ending in a blank line, which `git diff --check` reports. Both files keep the rows that stay parked. --- crates/mega-evm/tests/_pending/block_executor/block_limits.rs | 1 - .../mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs index d2daaedcd..824d84eb1 100644 --- a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs +++ b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs @@ -241,4 +241,3 @@ fn test_block_kv_limit_exceeded_mid_block() { const CALLER2: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); const CALLER3: alloy_primitives::Address = address!("4000000000000000000000000000000000000004"); - diff --git a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs index 4a437b901..46277678c 100644 --- a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs +++ b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs @@ -396,4 +396,3 @@ fn test_rex6_eip4788_pre_block_call_failure_aborts_block() { "expected an EIP-4788 pre-block failure, got: {msg}" ); } - From a1da0ec5981cf2dbed4e9a38610e113ad0c27bed Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:45:57 +0800 Subject: [PATCH 109/201] test(evm): pin what the factory's Debug prints The precompile builder is a closure with no Debug, so the impl reports it as a flag; nothing asserted the output, which left the impl's body unexercised. --- crates/mega-evm/src/evm/factory.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index d7d4a9650..74106362f 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -204,6 +204,26 @@ mod tests { })) } + /// The factory prints its external environment factory and whether a precompile builder is + /// installed. A closure has no `Debug`, so the builder is reported as a flag rather than + /// dropped: a reader of a node's log can tell the two configurations apart. + #[test] + fn test_debug_reports_whether_a_precompile_builder_is_installed() { + let factory = MegaEvmFactory::new(); + assert_eq!( + format!("{factory:?}"), + "MegaEvmFactory { external_env_factory: EmptyExternalEnv, \ + dyn_precompiles_builder: false }" + ); + + let with_builder = factory.with_dyn_precompiles_builder(Arc::new(|_| HashMap::default())); + assert_eq!( + format!("{with_builder:?}"), + "MegaEvmFactory { external_env_factory: EmptyExternalEnv, \ + dyn_precompiles_builder: true }" + ); + } + /// The builder runs once per EVM, is handed the spec the EVM executes, and what it returns /// answers a call to its address. #[test] From a1caa9bd621293a55fd6b50fa9b1a5c68ef923a7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 10:58:42 +0800 Subject: [PATCH 110/201] test(block): close the mutation survivors of block execution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The diff-scoped mutation gate reported 25 survivors on this series, every one of them a property no test read: - The pre-block calls. Neither the EIP-2935 nor the EIP-4788 call was observed by a test: the two contracts have no code in the test database, so a call that ran and a call that did not left the same state behind. A new test target plants a recorder at both addresses and pins what each call records, that a chain before Prague or before Cancun makes the call it has not reached, that the genesis block makes neither, and the two refusals of EIP-4788 — a genesis block with a non-zero root, and a Cancun block with none. - The receipts. A deposit's nonce and receipt version follow the chain's schedule, which a test now reads on a chain past Regolith and Canyon and on one past neither, and a block's receipts are read while it is built and again from its result. - The limits. Every dimension of the pre-execution check is an inclusive bound, one case per dimension: what exactly fills the limit — or what the block has left of it — is admitted and one unit more is refused. The block's available gas is what its refusal reports. The data-availability footprint gets the same boundary through the executor: a footprint that exactly fills the block's budget is admitted and leaves the block with none. - The schedules. The canonical chain schedules register every fork, including the ones the chain has not scheduled, which is what attaching a fork's parameters needs; removing one fork leaves the rest of the schedule alone. - The transaction helpers. A recovered borrow of an envelope reports the same hash and sizes as the envelope and as a recovered envelope. --- crates/mega-evm/src/block/hardfork.rs | 7 + crates/mega-evm/src/block/helpers.rs | 34 ++++- crates/mega-evm/src/block/limit.rs | 96 ++++++++++++ crates/mega-evm/tests/block/common.rs | 11 ++ crates/mega-evm/tests/block/eips.rs | 193 ++++++++++++++++++++++++ crates/mega-evm/tests/block/main.rs | 2 + crates/mega-evm/tests/block/receipts.rs | 69 +++++++++ crates/mega-evm/tests/block/rules.rs | 26 ++++ crates/mega-evm/tests/block/schedule.rs | 7 + 9 files changed, 440 insertions(+), 5 deletions(-) create mode 100644 crates/mega-evm/tests/block/eips.rs create mode 100644 crates/mega-evm/tests/block/receipts.rs diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index a9623d389..bc9f8acd0 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -482,8 +482,15 @@ mod tests { config.insert(MegaHardfork::Satin, ForkCondition::Timestamp(20)); assert_eq!(config.get(MegaHardfork::Satin), Some(&ForkCondition::Timestamp(20))); + // Removing one fork leaves the rest of the schedule as it was. + config.insert(EthereumHardfork::Prague, ForkCondition::Timestamp(30)); let config = config.without(MegaHardfork::Satin); assert_eq!(config.get(MegaHardfork::Satin), None); + assert_eq!( + config.get(EthereumHardfork::Prague), + Some(&ForkCondition::Timestamp(30)), + "the other entries are untouched" + ); let from_iter = MegaHardforkConfig::from( [(MegaHardfork::Satin, ForkCondition::Timestamp(1))].into_iter(), diff --git a/crates/mega-evm/src/block/helpers.rs b/crates/mega-evm/src/block/helpers.rs index a12fc12a3..aee098e2f 100644 --- a/crates/mega-evm/src/block/helpers.rs +++ b/crates/mega-evm/src/block/helpers.rs @@ -399,11 +399,35 @@ mod tests { fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { let tx = legacy_envelope(); let recovered = Recovered::new_unchecked(tx.clone(), CALLER); - - assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); - assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); - assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); - assert!(MegaTransactionExt::tx_size(&tx) > 0); + // A recovered borrow is what a node passes when it keeps the envelope itself. + let borrowed = Recovered::new_unchecked(&tx, CALLER); + + let hash = tx.tx_hash(); + let da_size = MegaTransactionExt::estimated_da_size(&tx); + let tx_size = MegaTransactionExt::tx_size(&tx); + assert!(da_size > 0); + assert!(tx_size > 0); + + // The three forms are the same transaction, so they report the same figures. + for reported in [ + ( + MegaTransactionExt::tx_hash(&tx), + MegaTransactionExt::estimated_da_size(&tx), + MegaTransactionExt::tx_size(&tx), + ), + ( + MegaTransactionExt::tx_hash(&recovered), + MegaTransactionExt::estimated_da_size(&recovered), + MegaTransactionExt::tx_size(&recovered), + ), + ( + MegaTransactionExt::tx_hash(&borrowed), + MegaTransactionExt::estimated_da_size(&borrowed), + MegaTransactionExt::tx_size(&borrowed), + ), + ] { + assert_eq!(reported, (hash, da_size, tx_size)); + } } #[test] diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 37a8a5fb8..f7459adad 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -490,6 +490,102 @@ mod tests { assert!(std::format!("{err}").contains("Block execution gas limit reached"), "{err}"); } + /// Every limit is an inclusive bound: a transaction that exactly fills what the limit — or + /// what the block has left of it — is admitted, and one unit more is refused. + #[test] + fn test_pre_execution_check_admits_what_exactly_fills_a_limit() { + const LIMIT: u64 = 1_000; + const USED: u64 = 400; + + // Each case names the dimension, the limiter it is checked on, what the limit leaves for + // one transaction, and how that figure reaches `pre_execution_check`. + type Check = fn(&BlockLimiter, u64) -> Result<(), BlockExecutionError>; + let cases: [(&str, BlockLimiter, u64, Check); 6] = [ + ( + "a transaction's own gas limit", + BlockLimiter::new(BlockLimits::no_limits().with_tx_gas_limit(LIMIT)), + LIMIT, + |limiter, gas_limit| { + limiter.pre_execution_check(B256::ZERO, gas_limit, 0, 0, false) + }, + ), + ( + "the block's gas limit", + BlockLimiter { + block_gas_used: USED, + ..BlockLimiter::new(BlockLimits::no_limits().with_block_gas_limit(LIMIT)) + }, + LIMIT - USED, + |limiter, gas_limit| { + limiter.pre_execution_check(B256::ZERO, gas_limit, 0, 0, false) + }, + ), + ( + "a transaction's own encoded size", + BlockLimiter::new(BlockLimits::no_limits().with_tx_encode_size_limit(LIMIT)), + LIMIT, + |limiter, tx_size| limiter.pre_execution_check(B256::ZERO, 0, tx_size, 0, false), + ), + ( + "the block's encoded size", + BlockLimiter { + block_tx_size_used: USED, + ..BlockLimiter::new( + BlockLimits::no_limits().with_block_txs_encode_size_limit(LIMIT), + ) + }, + LIMIT - USED, + |limiter, tx_size| limiter.pre_execution_check(B256::ZERO, 0, tx_size, 0, false), + ), + ( + "a transaction's own data-availability size", + BlockLimiter::new(BlockLimits::no_limits().with_tx_da_size_limit(LIMIT)), + LIMIT, + |limiter, da_size| limiter.pre_execution_check(B256::ZERO, 0, 0, da_size, false), + ), + ( + "the block's data-availability size", + BlockLimiter { + block_da_size_used: USED, + ..BlockLimiter::new(BlockLimits::no_limits().with_block_da_size_limit(LIMIT)) + }, + LIMIT - USED, + |limiter, da_size| limiter.pre_execution_check(B256::ZERO, 0, 0, da_size, false), + ), + ]; + + for (name, limiter, bound, check) in cases { + assert!( + check(&limiter, bound).is_ok(), + "{name}: {bound} exactly fills what is left and is admitted" + ); + assert!(check(&limiter, bound + 1).is_err(), "{name}: one unit more is refused"); + } + } + + /// What the block has left is what its refusal reports, and it is the limit minus what the + /// block used. + #[test] + fn test_available_gas_is_the_limit_less_what_the_block_used() { + let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000)); + assert_eq!(limiter.available_gas(), 1_000, "an empty block has all of it"); + + limiter.post_execution_update(&BlockUsage { gas_used: 400, ..Default::default() }); + assert_eq!(limiter.available_gas(), 600); + + let err = limiter + .pre_execution_check(B256::ZERO, 601, 0, 0, false) + .expect_err("601 does not fit in 600"); + assert!( + std::format!("{err}").contains("blocks available gas 600"), + "the refusal reports what the block has left: {err}" + ); + + // The block cannot owe gas: a counter past the limit reports nothing left. + limiter.post_execution_update(&BlockUsage { gas_used: u64::MAX, ..Default::default() }); + assert_eq!(limiter.available_gas(), 0); + } + /// The state and history ledgers and the write-record count are accumulated, and no check /// refuses a transaction on them. #[test] diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 32e966c86..91cbb242a 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -129,6 +129,17 @@ pub(crate) fn executor_with_spec( build(state, ctx, evm_env(), spec) } +/// An executor over `state`, for a block held to `ctx` in the environment `env`, on the chain +/// `spec` describes. +pub(crate) fn executor_with_env_and_spec( + state: &mut State, + ctx: MegaBlockExecutionCtx, + env: EvmEnv, + spec: MegaHardforkConfig, +) -> TestExecutor<'_> { + build(state, ctx, env, spec) +} + fn build( state: &mut State, ctx: MegaBlockExecutionCtx, diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs new file mode 100644 index 000000000..1cf9fda80 --- /dev/null +++ b/crates/mega-evm/tests/block/eips.rs @@ -0,0 +1,193 @@ +//! The pre-block calls a block makes before its transactions, and what each of them records. +//! +//! Every helper hands its state back rather than committing it, and the executor is what commits: +//! a call the fork makes is in the state the block's transactions run on, and a call it does not +//! make leaves that state alone. + +use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor, BlockValidationError}, + EvmEnv, +}; +use alloy_hardforks::{EthereumHardfork, ForkCondition}; +use alloy_primitives::{Bytes, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockLimits, MegaBlockExecutionCtx, MegaHardforkConfig, MegaSpecId, +}; +use revm::{ + bytecode::opcode::{CALLDATALOAD, SSTORE}, + database::State, + Database, +}; + +use crate::common::{self, executor_with_env, executor_with_env_and_spec, BLOCK_NUMBER}; + +/// The parent hash the EIP-2935 call records. +const PARENT_HASH: B256 = B256::repeat_byte(0xab); + +/// The parent beacon block root the EIP-4788 call records. +const PARENT_BEACON_ROOT: B256 = B256::repeat_byte(0xcd); + +/// Code that stores the word it was called with in slot zero, so a pre-block call to it leaves +/// what it was given behind. +fn recorder() -> Bytes { + BytecodeBuilder::default() + .push_number(0_u32) + .append(CALLDATALOAD) + .push_number(0_u32) + .append(SSTORE) + .stop() + .build() +} + +/// A state whose two pre-block system contracts record what they are called with. +fn state_with_recorders() -> State { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, recorder()); + db.set_account_code(BEACON_ROOTS_ADDRESS, recorder()); + State::builder().with_database(db).build() +} + +/// The context of a block whose parent hash and parent beacon block root are the two above. +fn ctx() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(PARENT_BEACON_ROOT), + Bytes::new(), + BlockLimits::no_limits(), + ) +} + +/// The context of a block that carries no parent beacon block root. +fn ctx_without_beacon_root() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new(PARENT_HASH, None, Bytes::new(), BlockLimits::no_limits()) +} + +/// The environment of a block at `number`. +fn env_at_block(number: u64) -> EvmEnv { + let mut env = common::evm_env(); + env.block_env.number = U256::from(number); + env +} + +/// What the two contracts hold in slot zero: the parent hash and the parent beacon block root, +/// as far as the pre-block calls recorded them. +fn recorded(state: &mut State) -> (B256, B256) { + let parent_hash = state.storage(HISTORY_STORAGE_ADDRESS, U256::ZERO).expect("readable"); + let beacon_root = state.storage(BEACON_ROOTS_ADDRESS, U256::ZERO).expect("readable"); + (B256::from(parent_hash.to_be_bytes()), B256::from(beacon_root.to_be_bytes())) +} + +/// Runs the pre-block calls of a block at `number` on the chain `spec` describes, and reports +/// what the two contracts recorded. +fn pre_block_calls( + spec: MegaHardforkConfig, + number: u64, + ctx: MegaBlockExecutionCtx, +) -> (B256, B256) { + let mut state = state_with_recorders(); + { + let mut executor = executor_with_env_and_spec(&mut state, ctx, env_at_block(number), spec); + executor.apply_pre_execution_changes().expect("the block starts"); + } + recorded(&mut state) +} + +/// Both calls run on a block of a chain past Prague and Cancun, and the executor commits what +/// they produced: the block's transactions see the parent hash and the parent beacon root. +#[test] +fn test_the_pre_block_calls_record_the_parent_hash_and_the_beacon_root() { + assert_eq!( + pre_block_calls(common::chain_spec(), BLOCK_NUMBER, ctx()), + (PARENT_HASH, PARENT_BEACON_ROOT) + ); +} + +/// A chain that has not reached Prague makes no block hashes call; the beacon root call is +/// unaffected. +#[test] +fn test_the_block_hashes_call_waits_for_prague() { + let before_prague = common::chain_spec().with(EthereumHardfork::Prague, ForkCondition::Never); + + assert_eq!( + pre_block_calls(before_prague, BLOCK_NUMBER, ctx()), + (B256::ZERO, PARENT_BEACON_ROOT), + "nothing was recorded for the parent hash" + ); +} + +/// A chain that has not reached Cancun makes no beacon root call, and needs no root; the block +/// hashes call is unaffected. +#[test] +fn test_the_beacon_root_call_waits_for_cancun() { + let before_cancun = common::chain_spec().with(EthereumHardfork::Cancun, ForkCondition::Never); + + assert_eq!( + pre_block_calls(before_cancun, BLOCK_NUMBER, ctx_without_beacon_root()), + (PARENT_HASH, B256::ZERO), + "nothing was recorded for the beacon root" + ); +} + +/// The genesis block makes neither call: it has no parent to record. Its parent beacon root is +/// zero, which is what EIP-4788 requires of it, and that is not an error. +#[test] +fn test_the_genesis_block_makes_no_pre_block_call() { + let genesis = MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + + assert_eq!( + pre_block_calls(common::chain_spec(), 0, genesis), + (B256::ZERO, B256::ZERO), + "neither contract was called" + ); +} + +/// A genesis block carrying a non-zero parent beacon block root is refused, as EIP-4788 +/// requires. +#[test] +fn test_the_genesis_block_refuses_a_non_zero_beacon_root() { + let mut state = state_with_recorders(); + let mut executor = executor_with_env(&mut state, ctx(), env_at_block(0)); + + let err = executor + .apply_pre_execution_changes() + .expect_err("the genesis block's parent beacon block root must be zero"); + + assert!( + matches!( + err, + BlockExecutionError::Validation( + BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { + parent_beacon_block_root, + }, + ) if parent_beacon_block_root == PARENT_BEACON_ROOT + ), + "{err}" + ); +} + +/// A block of a chain past Cancun that carries no parent beacon block root is refused. +#[test] +fn test_a_block_without_a_parent_beacon_root_is_refused() { + let mut state = state_with_recorders(); + let mut executor = + executor_with_env(&mut state, ctx_without_beacon_root(), env_at_block(BLOCK_NUMBER)); + + let err = executor + .apply_pre_execution_changes() + .expect_err("a Cancun block carries a parent beacon block root"); + + assert!( + matches!( + err, + BlockExecutionError::Validation(BlockValidationError::MissingParentBeaconBlockRoot) + ), + "{err}" + ); +} diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index f92cff133..3158182ca 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -3,8 +3,10 @@ mod block_hashes; mod common; mod counters; +mod eips; mod factory; mod inspector; mod limits; +mod receipts; mod rules; mod schedule; diff --git a/crates/mega-evm/tests/block/receipts.rs b/crates/mega-evm/tests/block/receipts.rs new file mode 100644 index 000000000..868dd4f40 --- /dev/null +++ b/crates/mega-evm/tests/block/receipts.rs @@ -0,0 +1,69 @@ +//! The receipts a block builds, which go through an OP receipt builder. + +use alloy_evm::block::BlockExecutor; +use alloy_hardforks::ForkCondition; +use alloy_op_hardforks::OpHardfork; +use alloy_primitives::Bytes; +use op_alloy_consensus::OpReceiptEnvelope; + +use crate::common::{self, deposit_tx, executor, executor_with_spec, unlimited_ctx, user_tx}; + +/// The deposit receipt of the block's only transaction. +fn deposit_receipt(receipts: &[OpReceiptEnvelope]) -> &op_alloy_consensus::OpDepositReceipt { + match receipts { + [OpReceiptEnvelope::Deposit(deposit)] => &deposit.receipt, + other => panic!("one deposit receipt, got {other:?}"), + } +} + +/// A block's receipts are readable while it is still being built, and they leave with its +/// result. +#[test] +fn test_the_receipts_are_readable_during_the_block_and_leave_with_its_result() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + assert!(executor.receipts().is_empty(), "nothing is packed yet"); + executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + assert_eq!(executor.receipts().len(), 1, "the committed transaction has its receipt"); + + executor.execute_transaction(&user_tx(1, 100_000)).expect("the transaction executes"); + assert_eq!(executor.receipts().len(), 2); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); + assert_eq!(result.into_receipts().len(), 2, "the receipts leave with the result"); +} + +/// A deposit's receipt carries the depositor's nonce and the receipt version, each from the fork +/// that introduced it: Regolith for the nonce, Canyon for the version. +#[test] +fn test_a_deposit_receipt_reports_the_nonce_and_the_version_the_schedule_activated() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&deposit_tx(Bytes::new(), 100_000)).expect("the deposit executes"); + + let receipt = deposit_receipt(executor.receipts()); + assert_eq!(receipt.deposit_nonce, Some(0), "the depositor's nonce before the deposit ran"); + assert_eq!(receipt.deposit_receipt_version, Some(1), "Canyon's receipt version"); +} + +/// The same deposit on a chain that has reached neither fork: no nonce and no version. The two +/// fields follow the chain's schedule, not the transaction. +#[test] +fn test_a_deposit_receipt_omits_what_the_schedule_has_not_activated() { + let before_both = common::chain_spec() + .with(OpHardfork::Regolith, ForkCondition::Never) + .with(OpHardfork::Canyon, ForkCondition::Never); + + let mut state = common::state(); + let mut executor = executor_with_spec(&mut state, unlimited_ctx(), before_both); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&deposit_tx(Bytes::new(), 100_000)).expect("the deposit executes"); + + let receipt = deposit_receipt(executor.receipts()); + assert_eq!(receipt.deposit_nonce, None, "Regolith brought the nonce"); + assert_eq!(receipt.deposit_receipt_version, None, "Canyon brought the version"); +} diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index dc5d5d223..340d80d0e 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -127,6 +127,32 @@ fn test_da_footprint_over_the_block_budget_refuses_the_transaction() { assert_eq!(executor.limiter().block_da_footprint_used, 0); } +/// Rule 2: the budget is an inclusive bound — a footprint that exactly fills what the block has +/// is admitted, and the block has nothing left for the next transaction. +#[test] +fn test_da_footprint_that_exactly_fills_the_block_budget_is_admitted() { + const SCALAR: u16 = 64; + const GAS_LIMIT: u64 = 900_000; + + let tx = common::user_tx_with_input(0, common::incompressible(20_000), GAS_LIMIT); + let footprint = mega_evm::MegaTransactionExt::estimated_da_size(&tx) * u64::from(SCALAR); + assert!(footprint >= GAS_LIMIT, "the block's gas limit must also fit the transaction's gas"); + + // The block's gas limit is the footprint's budget, so a block with exactly this gas limit + // has exactly this transaction's footprint. + let mut env = common::evm_env(); + env.block_env.gas_limit = footprint; + + let mut state = state_with_scalars(scalars_word(SCALAR, 0, 0)); + let mut executor = common::executor_with_env(&mut state, unlimited_ctx(), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor.execute_transaction(&tx).expect("a footprint that exactly fills the budget fits"); + + assert_eq!(executor.limiter().block_da_footprint_used, footprint); + assert_eq!(executor.limiter().available_da_footprint(), 0, "the block has no footprint left"); +} + /// Rule 2: a deposit is exempt from the footprint, as it is from the data-availability size. #[test] fn test_deposits_do_not_count_towards_the_da_footprint() { diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index fd5c72154..c7644301f 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -49,6 +49,13 @@ fn test_canonical_schedules_match_the_chain_activation_table() { activation.condition(*fork), "{fork:?} on chain {chain_id}" ); + // The schedule carries an entry for every fork, including the ones the chain has not + // scheduled: attaching a fork's parameters needs its entry to be there. + assert_eq!( + schedule.get(*fork), + Some(&activation.condition(*fork)), + "{fork:?} is registered on chain {chain_id}" + ); } assert_eq!(schedule.validate_schedule(), Ok(()), "chain {chain_id} loads"); } From 76b329d07a6904b20744bb4eec9fc3a6e02323c9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:02:42 +0800 Subject: [PATCH 111/201] test: name the constants test after what it asserts --- crates/mega-evm/src/constants.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 7ef1c772d..462663bab 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -60,7 +60,7 @@ mod tests { /// The placeholder values, written out so a change to one is a visible diff. #[test] - fn test_provisional_values_match_the_work_order() { + fn test_the_provisional_values_are_written_out() { assert_eq!(COST_PER_STATE_BYTE, 1_530); assert_eq!(SLOT_STATE_GAS, 97_920); assert_eq!(ACCOUNT_STATE_GAS, 183_600); From d7f4115561d3f466804959b09a966c8b8920105f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:30:11 +0800 Subject: [PATCH 112/201] fix(block): price a block's transactions with its own L1 info Block execution fetched the L1 block info at the end of `apply_pre_execution_changes`, from the parent block's state, and stamped it as the info of this block. op-revm's handler reloads only when the info is for another block, and returns early for deposits before that check, so every user transaction of the block was priced with the values from before the block's own L1 info deposit. alloy-op-evm's executor pre-loads no info: op-revm fetches it when it deducts the caller of the first non-deposit transaction, which is after the L1 info deposit has committed. Do the same and fetch nothing before the block's transactions. A caller that placed its own info for this block still keeps it, which is op-revm's own condition. The data-availability footprint reads the scalar from storage per transaction and is unchanged, so the two paths now read the same block's values. --- AGENTS.md | 2 +- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/block/executor.rs | 43 +++----- crates/mega-evm/tests/block/common.rs | 11 +- crates/mega-evm/tests/block/rules.rs | 140 ++++++++++++++++++++++---- 5 files changed, 146 insertions(+), 52 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 60b2b26c5..745e2ed79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,7 +107,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. - It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read once at the start of the block — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. + It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. `apply_pre_execution_changes` refuses a rewriting inspector and names two hook points that are empty today: system contract deployment and the pre-block system calls. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 6ab74ea8a..71a77c651 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -32,7 +32,7 @@ The common execution layer is in place: the frame lifecycle the later mechanisms No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. `MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. -Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read once at the start of the block. +Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read by the first transaction that prices against it, so the block's own L1 info deposit is what the transactions after it are priced with. Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers. `apply_pre_execution_changes` leaves two hook points empty: system contract deployment and the pre-block system calls. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index b0c2b660a..cdb0f01fc 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -15,9 +15,12 @@ //! against the block's gas limit and reported as the block's blob gas used. With no scalar in //! state the scalar is zero and the rule costs nothing. This mirrors alloy-op-evm's Jovian DA //! footprint block limit. -//! - **The L1 block info is read once, at the start of the block.** An empty L1 block contract -//! reads as zeroes, not as an error, and a caller that placed its own info for this block keeps -//! it. This mirrors alloy-op-evm's `l1_block_info`. +//! - **The L1 block info is read lazily, by the transaction that prices against it.** Block +//! execution fetches nothing: op-revm's handler reads the L1 block contract when it deducts the +//! caller of the first non-deposit transaction, which is after the block's own L1 info deposit +//! has committed, so every transaction prices against the values that deposit set. An empty L1 +//! block contract reads as zeroes, not as an error, and a caller that placed its own info for +//! this block keeps it. alloy-op-evm's executor pre-loads no info either. //! //! # What later mechanisms fill in //! @@ -240,25 +243,6 @@ where self.evm.inspector() } - /// Reads the L1 block info of this block from state, unless the EVM already carries the info - /// of this very block. - /// - /// An empty L1 block contract reads as zeroes — no fee scalars, no data-availability - /// footprint scalar — which is a chain that has not set them, not an error. A caller that - /// placed its own info for this block number keeps it: this is the same condition op-revm's - /// handler reloads on, so the two never disagree about which info the block runs with. - fn load_l1_block_info(&mut self) -> Result<(), BlockExecutionError> { - let block_number = self.evm.block().number(); - if self.evm.ctx().chain().l2_block == Some(block_number) { - return Ok(()); - } - let spec = self.evm.ctx().cfg().spec; - let info = L1BlockInfo::try_fetch(self.evm.ctx_mut().db_mut(), block_number, spec) - .map_err(BlockExecutionError::other)?; - self.evm.ctx_mut().modify_chain(|chain| *chain = info); - Ok(()) - } - /// The data-availability footprint gas scalar the L1 block contract holds. /// /// Read per transaction, as the fork's rule is stated: the block's own L1 info transaction @@ -316,14 +300,19 @@ where /// Runs what a block does before its transactions. /// - /// In order: the admission gate, the EIP-2935 and EIP-4788 pre-block calls, and the read of - /// the L1 block info. Each call's state is committed here rather than inside its helper, so - /// a witness generator sees every step's read and write set. + /// In order: the admission gate and the EIP-2935 and EIP-4788 pre-block calls. Each call's + /// state is committed here rather than inside its helper, so a witness generator sees every + /// step's read and write set. + /// + /// The L1 block info is not read here. op-revm's handler reads it when it deducts the caller + /// of the first non-deposit transaction, which is after the block's own L1 info deposit has + /// committed; reading it here would price every transaction of the block against the parent + /// block's values. /// /// Two hook points are empty: system contract deployment, which deploys the chain's system /// contracts at the Satin activation, and the pre-block system calls, which apply the /// pending changes the sequencer registry holds. Both arrive with the mechanisms of those - /// names, between the pre-block calls and the L1 block info read. + /// names, after the pre-block calls. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { if self.evm.has_rewriting_inspector() { return Err(MegaBlockExecutionError::RewritingInspector.into()); @@ -350,8 +339,6 @@ where // Hook point: system contract deployment. // Hook point: the pre-block system calls. - self.load_l1_block_info()?; - Ok(()) } diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 91cbb242a..88c95e403 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -186,10 +186,19 @@ pub(crate) fn user_tx_with_input( /// A deposit transaction carrying `input`. pub(crate) fn deposit_tx(input: Bytes, gas_limit: u64) -> Recovered { + deposit_tx_to(CONTRACT, input, gas_limit) +} + +/// A deposit transaction to `to`, carrying `input`. +pub(crate) fn deposit_tx_to( + to: Address, + input: Bytes, + gas_limit: u64, +) -> Recovered { let deposit = TxDeposit { source_hash: B256::ZERO, from: CALLER, - to: TxKind::Call(CONTRACT), + to: TxKind::Call(to), mint: 0, value: U256::ZERO, gas_limit, diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index 340d80d0e..8044a7896 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -2,7 +2,7 @@ use alloy_evm::block::BlockExecutor; use alloy_primitives::{Bytes, U256}; -use mega_evm::BlockLimits; +use mega_evm::{test_utils::BytecodeBuilder, BlockLimits}; use op_revm::{ constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, @@ -10,10 +10,15 @@ use op_revm::{ }, L1BlockInfo, }; -use revm::{context::ContextTr, database::State, Database}; +use revm::{ + bytecode::opcode::{CALLDATALOAD, SSTORE}, + context::ContextTr, + database::State, + Database, +}; use crate::common::{ - self, deposit_tx, executor, unlimited_ctx, user_tx, BLOCK_GAS_LIMIT, BLOCK_NUMBER, + self, deposit_tx, executor, unlimited_ctx, user_tx, TestExecutor, BLOCK_GAS_LIMIT, BLOCK_NUMBER, }; /// The word the L1 block contract holds at its scalars slot: the data-availability footprint @@ -37,6 +42,43 @@ fn state_with_scalars(word: U256) -> State State::builder().with_database(db).build() } +/// Code that writes its 32 bytes of calldata to the scalars slot, which is what the L1 info +/// deposit's setter does for the fields this test reads. +fn l1_block_setter() -> Bytes { + BytecodeBuilder::default() + .push_number(0_u64) + .append(CALLDATALOAD) + .push_u256(DA_FOOTPRINT_GAS_SCALAR_SLOT) + .append(SSTORE) + .stop() + .build() +} + +/// The scalars word the L1 block contract holds in the state the block runs on. +fn state_scalars(executor: &mut TestExecutor<'_>) -> U256 { + executor + .evm_mut() + .ctx_mut() + .db_mut() + .storage(L1_BLOCK_CONTRACT, DA_FOOTPRINT_GAS_SCALAR_SLOT) + .expect("the slot is readable") +} + +/// The operator fee op-revm charges on the Karst formula: gas x scalar x 100. +fn karst_operator_fee(gas_used: u64, scalar: u32) -> U256 { + U256::from(gas_used) * U256::from(scalar) * U256::from(100) +} + +/// What the block paid the operator fee recipient, read once the block has finished. +fn operator_fee_paid(executor: TestExecutor<'_>) -> U256 { + let (evm, _) = executor.finish_with_counters().expect("the block finishes"); + let (db, _) = alloy_evm::Evm::finish(evm); + db.basic(OPERATOR_FEE_RECIPIENT) + .expect("the recipient is readable") + .map(|account| account.balance) + .unwrap_or_default() +} + /// Rule 1, alloy-op-evm's `no_user_tx_activation_block`: the block a fork activates in carries /// the chain's own transactions only, and a user transaction in it is refused before it runs. #[test] @@ -167,32 +209,39 @@ fn test_deposits_do_not_count_towards_the_da_footprint() { assert_eq!(executor.limiter().block_da_footprint_used, 0); } -/// Rule 3, alloy-op-evm's `l1_block_info`: the read at the start of the block is failable, and -/// an empty L1 block contract answers with zeroes rather than an error. +/// Rule 3, alloy-op-evm's `l1_block_info`: block execution fetches nothing, and the first +/// transaction that prices against the info is what reads it. An empty L1 block contract answers +/// with zeroes rather than an error. #[test] -fn test_l1_block_info_reads_an_empty_contract_as_zero() { +fn test_l1_block_info_is_read_by_the_first_transaction_that_prices_against_it() { let mut state = common::state(); let mut executor = executor(&mut state, unlimited_ctx()); - executor.apply_pre_execution_changes().expect("an empty L1 block contract is not an error"); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(executor.evm().ctx().chain().l2_block, None, "the block starts with no info"); + + executor + .execute_transaction(&user_tx(0, 100_000)) + .expect("an empty L1 block contract is not an error"); let chain = executor.evm().ctx().chain(); - assert_eq!(chain.l2_block, Some(U256::from(BLOCK_NUMBER))); + assert_eq!(chain.l2_block, Some(U256::from(BLOCK_NUMBER)), "read for this block"); assert_eq!(chain.da_footprint_gas_scalar, Some(0)); assert_eq!(chain.operator_fee_scalar, Some(U256::ZERO)); assert_eq!(chain.l1_base_fee, U256::ZERO); } /// Rule 3: the read is conditioned on the block the info is for, so info a caller placed for -/// this very block is not overwritten by what state holds. +/// this very block is what its transactions are priced with, not what state holds. #[test] fn test_l1_block_info_of_this_block_is_not_overwritten() { - let mut state = state_with_scalars(scalars_word(7, 0, 0)); + const CALLER_SCALAR: u32 = 11; + let mut state = state_with_scalars(scalars_word(7, 3, 0)); let mut executor = executor(&mut state, unlimited_ctx()); executor.evm_mut().ctx_mut().modify_chain(|chain| { *chain = L1BlockInfo { l2_block: Some(U256::from(BLOCK_NUMBER)), - operator_fee_scalar: Some(U256::from(11)), + operator_fee_scalar: Some(U256::from(CALLER_SCALAR)), operator_fee_constant: Some(U256::ZERO), da_footprint_gas_scalar: Some(5), ..Default::default() @@ -200,10 +249,66 @@ fn test_l1_block_info_of_this_block_is_not_overwritten() { }); executor.apply_pre_execution_changes().expect("the block starts"); + let gas = executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); let chain = executor.evm().ctx().chain(); - assert_eq!(chain.operator_fee_scalar, Some(U256::from(11)), "the caller's info stands"); + assert_eq!( + chain.operator_fee_scalar, + Some(U256::from(CALLER_SCALAR)), + "the caller's info stands" + ); assert_eq!(chain.da_footprint_gas_scalar, Some(5)); + assert_eq!( + operator_fee_paid(executor), + karst_operator_fee(gas.tx_gas_used(), CALLER_SCALAR), + "and is what the transaction was charged" + ); +} + +/// Rule 3: the block's own L1 info deposit is what the transactions after it are priced with. +/// Reading the info before the block's first transaction would hold every user transaction of +/// the block to the parent block's values. +#[test] +fn test_the_l1_info_deposit_prices_the_transactions_after_it() { + const PARENT_SCALAR: u32 = 1; + const BLOCK_SCALAR: u32 = 9; + + let mut db = common::database(); + db.set_account_code(L1_BLOCK_CONTRACT, l1_block_setter()); + db.set_account_storage( + L1_BLOCK_CONTRACT, + DA_FOOTPRINT_GAS_SCALAR_SLOT, + scalars_word(0, PARENT_SCALAR, 0), + ); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + // The chain's own first transaction writes the block's scalars, as the L1 info deposit does. + let word = scalars_word(0, BLOCK_SCALAR, 0); + executor + .execute_transaction(&common::deposit_tx_to( + L1_BLOCK_CONTRACT, + Bytes::from(word.to_be_bytes::<32>()), + 200_000, + )) + .expect("the deposit executes"); + assert_eq!(state_scalars(&mut executor), word, "the deposit wrote the block's scalars"); + + // The deposit bumped the sender's nonce, so the user transaction after it carries nonce 1. + let gas = executor.execute_transaction(&user_tx(1, 100_000)).expect("the transaction executes"); + + let paid = operator_fee_paid(executor); + assert_eq!( + paid, + karst_operator_fee(gas.tx_gas_used(), BLOCK_SCALAR), + "the transaction pays what the block's own deposit set" + ); + assert_ne!( + paid, + karst_operator_fee(gas.tx_gas_used(), PARENT_SCALAR), + "and not what the parent block held" + ); } /// Rule 3: the operator fee the reward path pays is the one op-revm computes for the Karst @@ -216,17 +321,10 @@ fn test_operator_fee_is_charged_on_the_karst_formula() { executor.apply_pre_execution_changes().expect("the block starts"); let gas = executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); - let (evm, _) = executor.finish_with_counters().expect("the block finishes"); - let (db, _) = alloy_evm::Evm::finish(evm); - let paid = db - .basic(OPERATOR_FEE_RECIPIENT) - .expect("the recipient is readable") - .expect("the operator fee created the recipient") - .balance; assert_eq!( - paid, - U256::from(gas.tx_gas_used()) * U256::from(OPERATOR_FEE_SCALAR) * U256::from(100), + operator_fee_paid(executor), + karst_operator_fee(gas.tx_gas_used(), OPERATOR_FEE_SCALAR), "the Karst formula multiplies by 100 where the pre-Jovian one divides by 1e6" ); } From 60850e8a1ce43674413d564b408e7fa4be2d3cd5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:31:47 +0800 Subject: [PATCH 113/201] fix(block): refuse a rewriting inspector at every entry point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gate was checked once, in `apply_pre_execution_changes`. A disabled rewriting inspector passed that check and could then be enabled through `set_inspector_enabled` on the EVM the `BlockExecutor` trait hands out, and a caller that never ran the pre-execution changes was never checked at all. alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type. Check it at every entry point instead — the pre-block changes, the execution of a transaction, the commit of an outcome and the end of the block — before anything changes. The trusted constructor stays the compile-time proof that an inspector writes nothing back; the generic one is checked at every call. --- AGENTS.md | 4 +- crates/mega-evm/src/block/executor.rs | 34 +++++++++++++-- crates/mega-evm/src/block/factory.rs | 14 +++--- crates/mega-evm/tests/block/inspector.rs | 55 ++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 745e2ed79..c9c585434 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,7 +108,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. - `apply_pre_execution_changes` refuses a rewriting inspector and names two hook points that are empty today: system contract deployment and the pre-block system calls. + It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` names two hook points that are empty today: system contract deployment and the pre-block system calls. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. ### Contracts of the common execution layer @@ -139,6 +139,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). - **The admission gate.** A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses, and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. + alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type: block execution checks it at every entry point — the pre-block changes, a transaction, a commit and the end of the block — because an inspector can be enabled after the block was set up and a caller can run transactions without setting it up. + `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route. The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). The test utilities' inspectors are not declared. - **Three ledgers.** diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index cdb0f01fc..d0846c564 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -22,6 +22,18 @@ //! block contract reads as zeroes, not as an error, and a caller that placed its own info for //! this block keeps it. alloy-op-evm's executor pre-loads no info either. //! +//! # The admission gate +//! +//! Block execution refuses an inspector that may rewrite what execution produces +//! ([`MegaEvm::has_rewriting_inspector`]). alloy-evm's `BlockExecutorFactory` asks for an executor +//! for every `I: Inspector`, so the refusal cannot be a bound on the type: it is checked at every +//! entry point that runs code or moves the block on — the pre-block changes, the execution of a +//! transaction, the commit of an outcome and the end of the block — before anything changes. The +//! trusted route +//! ([`create_executor_with_trusted_inspector`](crate::MegaBlockExecutorFactory::create_executor_with_trusted_inspector)) +//! is the compile-time proof that an inspector observes and writes nothing back; the generic route +//! is the checked one. +//! //! # What later mechanisms fill in //! //! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) names two hook @@ -261,6 +273,19 @@ where fn commit(&mut self, state: EvmState) { self.evm.ctx_mut().db_mut().commit(state); } + + /// Refuses an EVM that runs an inspector which may rewrite what execution produces. + /// + /// Checked at every entry point rather than once, because the inspector can be enabled after + /// the block was set up ([`Evm::set_inspector_enabled`] through + /// [`evm_mut`](BlockExecutor::evm_mut)) and because a caller may run transactions without + /// calling [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) at all. + fn check_admission(&self) -> Result<(), BlockExecutionError> { + if self.evm.has_rewriting_inspector() { + return Err(MegaBlockExecutionError::RewritingInspector.into()); + } + Ok(()) + } } impl MegaBlockExecutor, R, Spec> @@ -314,9 +339,7 @@ where /// pending changes the sequencer registry holds. Both arrive with the mechanisms of those /// names, after the pre-block calls. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { - if self.evm.has_rewriting_inspector() { - return Err(MegaBlockExecutionError::RewritingInspector.into()); - } + self.check_admission()?; let state = eips::transact_blockhashes_contract_call( &self.spec, @@ -489,6 +512,7 @@ where &mut self, output: MegaBlockTxResult<::TxType>, ) -> Result { + self.check_admission()?; self.limiter.pre_execution_check( output.tx_hash, output.gas_limit, @@ -509,6 +533,8 @@ where MegaBlockTxResult<::TxType>, BlockExecutionError, > { + self.check_admission()?; + let (tx_env, tx) = tx.into_parts(); let inner = tx.tx(); let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE; @@ -609,6 +635,8 @@ where pub fn finish_with_counters( mut self, ) -> Result, BlockExecutionError> { + self.check_admission()?; + let balance_increments = post_block_balance_increments::

(&self.spec, self.evm.block(), &[], None); self.evm diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index 169a607c5..a5e40bb9b 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -57,8 +57,10 @@ where /// /// This is the one way an inspected transaction reaches a block: the inspector's type /// declares that it writes nothing back ([`TrustedObserver`]), so what the block executes is - /// what the chain executes. An inspector without that declaration is refused by - /// [`apply_pre_execution_changes`](alloy_evm::block::BlockExecutor::apply_pre_execution_changes). + /// what the chain executes, and this bound is the compile-time proof of it. An inspector + /// that arrives through [`create_executor`](BlockExecutorFactory::create_executor) carries no + /// such proof, so block execution checks it at every entry point instead and refuses it with + /// `RewritingInspector`. pub fn create_executor_with_trusted_inspector( &self, db: DB, @@ -103,10 +105,10 @@ where /// Creates an executor over an EVM the caller built. /// - /// The block's transaction-level limits are installed here, so the two ways to reach an - /// executor — this one and - /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) — - /// run every transaction under the same limits, whatever the caller did or did not apply. + /// alloy-evm asks for an executor for every `I: Inspector`, so this route cannot refuse a + /// rewriting inspector by its type; the executor checks the EVM at every entry point instead. + /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) is + /// the route whose bound proves the inspector observes only. fn create_executor<'a, DB, I>( &'a self, evm: MegaEvm, diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 0c5d53a06..bf94da4ce 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -82,3 +82,58 @@ fn test_a_disabled_inspector_is_admitted() { executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); } + +/// The gate is checked at every entry point, not once: an inspector enabled after the block was +/// set up is refused by the transaction that would run under it, by a commit and by the end of +/// the block. +#[test] +fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { + let mut state = common::state(); + let factory = common::factory(); + let mut evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(GasInspector::new()); + evm.set_inspector_enabled(false); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); + + // The one transaction that ran before the inspector was enabled is admitted. + let outcome = executor + .execute_transaction_without_commit(&user_tx(0, 100_000)) + .expect("the block is still clean"); + + executor.evm_mut().set_inspector_enabled(true); + + assert!(is_refused(executor.execute_transaction(&user_tx(1, 100_000))), "no transaction runs"); + assert!(is_refused(executor.commit_transaction_outcome(outcome)), "nothing commits"); + assert!(executor.receipts().is_empty(), "the block packed nothing"); + assert!(is_refused(executor.finish_with_counters()), "and the block does not finish"); +} + +/// The gate holds for a caller that never runs the block's pre-execution changes: the check is on +/// the path that runs code, not only on the block's setup. +#[test] +fn test_a_rewriting_inspector_is_refused_without_the_pre_execution_changes() { + let mut state = common::state(); + let factory = common::factory(); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(GasInspector::new()); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + + assert!( + is_refused(executor.execute_transaction_without_commit(&user_tx(0, 100_000))), + "skipping the setup is not a way past the gate" + ); + assert!(is_refused(executor.finish_with_counters()), "and neither is finishing the block"); +} + +/// Whether block execution refused the call because of the inspector. +fn is_refused(result: Result) -> bool { + match result { + Ok(_) => false, + Err(err) => format!("{err}").contains("does not admit an inspector that may rewrite"), + } +} From 8f9ab2eb8dfc2095a65680ba3af7c1c3c9f3422a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:33:48 +0800 Subject: [PATCH 114/201] fix(block): install the block's transaction limits in the constructor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `MegaBlockExecutor::new` set up the block limiter but left the EVM's transaction-level limits alone, so a node that used the documented constructor ran the block's transactions under whatever limits the EVM it built happened to carry — unlimited, for an EVM straight from the factory — while the two factory routes installed them. Install them in the constructor, which every route goes through, and drop the two installs the factory made. --- crates/mega-evm/src/block/executor.rs | 27 ++++++- crates/mega-evm/src/block/factory.rs | 11 ++- crates/mega-evm/tests/block/common.rs | 4 +- crates/mega-evm/tests/block/factory.rs | 100 ++++++++++++++++++++++--- 4 files changed, 120 insertions(+), 22 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index d0846c564..a90579c2c 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -220,15 +220,34 @@ impl MegaBlockExecutor { } } -impl MegaBlockExecutor { +impl MegaBlockExecutor, R, Spec> +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + R: OpReceiptBuilder, + Spec: MegaHardforks, +{ /// Creates an executor that runs `ctx`'s block on `evm`. /// + /// The block's transaction-level limits are installed on the EVM here, so every route to an + /// executor — this one and both factory constructors — runs the block's transactions under + /// the limits `ctx` carries, whatever the caller did or did not apply. + /// /// The block's gas limit comes from the block environment, whatever `ctx` carries: it is the /// number consensus holds the block to, and it is also the budget the data-availability /// footprint of the block's transactions is held to. - pub fn new(evm: E, ctx: MegaBlockExecutionCtx, spec: Spec, receipt_builder: R) -> Self { - let timestamp = evm.block().timestamp().saturating_to(); - let limits = ctx.block_limits.with_block_gas_limit(evm.block().gas_limit()); + pub fn new( + mut evm: MegaEvm, + ctx: MegaBlockExecutionCtx, + spec: Spec, + receipt_builder: R, + ) -> Self { + evm.set_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + let (timestamp, block_gas_limit) = { + let block = evm.ctx().block(); + (block.timestamp().saturating_to(), block.gas_limit()) + }; + let limits = ctx.block_limits.with_block_gas_limit(block_gas_limit); Self { is_canyon: spec.is_canyon_active_at_timestamp(timestamp), is_regolith: spec.is_regolith_active_at_timestamp(timestamp), diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index a5e40bb9b..2862938d6 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -72,11 +72,7 @@ where DB: StateDB, I: TrustedObserver + Inspector>, { - let evm = self - .evm_factory - .create_evm(db, evm_env) - .with_trusted_inspector(inspector) - .with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + let evm = self.evm_factory.create_evm(db, evm_env).with_trusted_inspector(inspector); MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) } } @@ -105,6 +101,10 @@ where /// Creates an executor over an EVM the caller built. /// + /// The block's transaction-level limits are installed by + /// [`MegaBlockExecutor::new`], so an EVM the caller built without them still runs the block's + /// transactions under them. + /// /// alloy-evm asks for an executor for every `I: Inspector`, so this route cannot refuse a /// rewriting inspector by its type; the executor checks the EVM at every entry point instead. /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) is @@ -118,7 +118,6 @@ where DB: StateDB, I: Inspector>, { - let evm = evm.with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) } } diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index 88c95e403..e882d2115 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -146,9 +146,7 @@ fn build( env: EvmEnv, spec: MegaHardforkConfig, ) -> TestExecutor<'_> { - let evm = MegaEvmFactory::new() - .create_evm(state, env) - .with_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); + let evm = MegaEvmFactory::new().create_evm(state, env); MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 5650f55c0..807119ce3 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -1,15 +1,26 @@ //! The two ways to reach a block executor, and the limits both install. //! //! A block's transaction-level limits live in its execution context, and the EVM is what -//! enforces them. Whichever route builds the executor — the factory trait a node's block-building -//! and reorg paths call with an EVM they built, or the trusted-inspector constructor — must -//! install them, so a caller that did not pre-apply them does not run a block under whatever -//! limits the EVM happened to carry. - -use alloy_evm::{block::BlockExecutorFactory, EvmFactory}; -use mega_evm::{test_utils::GasInspector, BlockLimits, DeclaredObserver, EvmTxRuntimeLimits}; - -use crate::common; +//! enforces them. Whichever route builds the executor — the constructor a node calls directly, +//! the factory trait its block-building and reorg paths call with an EVM they built, or the +//! trusted-inspector constructor — installs them, so a caller that did not pre-apply them does +//! not run a block under whatever limits the EVM happened to carry. + +use alloy_evm::{ + block::{BlockExecutor, BlockExecutorFactory}, + EvmFactory, +}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::U256; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::{BytecodeBuilder, GasInspector}, + BlockLimits, DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, + MegaEvmFactory, MegaLimitExceeded, +}; +use revm::{context::result::ExecutionResult, database::State}; + +use crate::common::{self, user_tx}; /// A limit no default carries, so seeing it proves it travelled from the block context. const TX_DATA_SIZE_LIMIT: u64 = 1_234_567; @@ -99,3 +110,74 @@ fn test_trait_path_idempotent_when_caller_pre_applied_runtime_limits() { assert_eq!(*executor.evm().tx_runtime_limits(), limits().to_evm_tx_runtime_limits()); } + +/// The constructor a node calls directly installs the block's limits, so it and the factory +/// routes agree. +#[test] +fn test_direct_construction_applies_block_context_runtime_limits() { + let mut state = common::state(); + // Built without any caller-side limits: the case a caller that forgot them produces. + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); + + let executor = MegaBlockExecutor::new( + evm, + common::block_ctx(limits()), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ); + + assert_eq!( + *executor.evm().tx_runtime_limits(), + limits().to_evm_tx_runtime_limits(), + "the EVM runs under exactly the block's limits" + ); +} + +/// And they are enforced, not only carried: a transaction that keeps more data-size bytes than +/// the block allows is stopped with `MegaLimitExceeded`. +#[test] +fn test_direct_construction_stops_a_transaction_over_the_block_data_size_limit() { + const DATA_SIZE_LIMIT: u64 = 40; + + let mut db = common::database(); + db.set_account_code( + common::CONTRACT, + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(), + ); + let mut state = State::builder().with_database(db).build(); + let block_limits = BlockLimits::no_limits().with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(DATA_SIZE_LIMIT), + ); + // `common::executor` builds the executor with `MegaBlockExecutor::new` and an EVM that + // carries no limits of its own. + let mut executor = common::executor(&mut state, common::block_ctx(block_limits)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let outcome = executor + .execute_transaction_without_commit(&user_tx(0, 1_000_000)) + .expect("the transaction runs"); + + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: DATA_SIZE_LIMIT, + used: 2 * DATA_SIZE_LIMIT, + frame_local: false, + }) + ); + match &outcome.result { + ExecutionResult::Revert { output, .. } => assert_eq!( + output.as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } + .abi_encode(), + "the stop's revert data" + ), + other => panic!("expected a revert-class stop, got {other:?}"), + } +} From 99ccad21ba3627bd5c3aa64026edb2f76ce174bb Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:35:47 +0800 Subject: [PATCH 115/201] fix(block): re-check the footprint when a transaction commits late `commit_transaction_outcome` re-ran the block's ordinary admission check but never looked at the outcome's data-availability footprint, so two candidates that each fit the block's footprint budget when they were simulated could both commit and carry the block's blob gas used past the budget. Check the footprint against what the block has left, before any counter, receipt or state moves, and share the check with the one the execution path already made. --- crates/mega-evm/src/block/executor.rs | 30 +++++++++----- crates/mega-evm/tests/block/limits.rs | 58 +++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index a90579c2c..64e7cc59c 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -293,6 +293,21 @@ where self.evm.ctx_mut().db_mut().commit(state); } + /// Refuses a data-availability footprint the block has no room left for. + /// + /// The budget is the block's gas limit, as the fork's rule states it. + fn check_da_footprint(&self, footprint: u64) -> Result<(), BlockExecutionError> { + let available = self.limiter.available_da_footprint(); + if footprint > available { + return Err(MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint: footprint, + available_block_da_footprint: available, + } + .into()); + } + Ok(()) + } + /// Refuses an EVM that runs an inspector which may rewrite what execution produces. /// /// Checked at every entry point rather than once, because the inspector can be enabled after @@ -525,8 +540,9 @@ where /// Re-checks the block's admission and commits `output`. /// /// The block's counters may have moved between the transaction executing and its commit — a - /// builder that executes candidates and then picks among them — so what the transaction adds - /// is checked against the block once more. + /// builder that executes candidates and then picks among them — so everything the block + /// holds a transaction to is checked once more, its data-availability footprint included, and + /// nothing changes before the check passes. pub fn commit_transaction_outcome( &mut self, output: MegaBlockTxResult<::TxType>, @@ -539,6 +555,7 @@ where output.da_size, output.is_deposit, )?; + self.check_da_footprint(output.da_footprint)?; Ok(self.commit_transaction(output)) } @@ -600,14 +617,7 @@ where 0 } else { let footprint = da_size.saturating_mul(self.da_footprint_gas_scalar()?); - let available = self.limiter.available_da_footprint(); - if footprint > available { - return Err(MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { - transaction_da_footprint: footprint, - available_block_da_footprint: available, - } - .into()); - } + self.check_da_footprint(footprint)?; footprint }; diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 6a73be376..3df9fa232 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -6,6 +6,9 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ test_utils::BytecodeBuilder, BlockLimits, EnrichedMegaTx, MegaTransactionExt, MegaTxEnvelope, }; +use op_revm::constants::{ + DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, +}; use revm::{ bytecode::opcode::LOG0, context::{BlockEnv, ContextTr}, @@ -41,6 +44,11 @@ fn tx_from(caller: Address, nonce: u64, gas_limit: u64) -> Recovered Recovered { + Recovered::new_unchecked(common::tx(0, CONTRACT, input, gas_limit), caller) +} + /// The block's data-size limit: the transaction that crosses it is packed, and the next one is /// refused before it runs. #[test] @@ -458,3 +466,53 @@ fn test_mixed_deposit_and_regular_transactions() { let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 2); } + +/// The data-availability footprint is re-checked at commit too: two candidates that each fit the +/// block's footprint budget on their own do not both commit. +/// +/// A builder simulates candidates against the same pre-state and then picks among them, so both +/// are executed before either commits. The first fills the budget; the second is refused before +/// the block's counters, receipts or state move. +#[test] +fn test_commit_time_da_footprint_check_parallel_simulation() { + const SCALAR: u16 = u16::MAX; + const TX_GAS_LIMIT: u64 = 200_000; + + let first = tx_with_input(CALLER, incompressible(2_000), TX_GAS_LIMIT); + let second = tx_with_input(CALLER2, incompressible(1_999), TX_GAS_LIMIT); + let footprint = |tx: &Recovered| { + MegaTransactionExt::estimated_da_size(tx) * u64::from(SCALAR) + }; + // The block holds exactly the larger of the two, so each fits alone and the two do not. + let budget = footprint(&first).max(footprint(&second)); + assert!(budget >= TX_GAS_LIMIT, "the budget is the block's gas limit, which must fit a tx"); + + let mut db = common::database(); + db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); + db.set_account_storage( + L1_BLOCK_CONTRACT, + DA_FOOTPRINT_GAS_SCALAR_SLOT, + U256::from(SCALAR) << (8 * (32 - DA_FOOTPRINT_GAS_SCALAR_OFFSET - 2)), + ); + let mut state = revm::database::State::builder().with_database(db).build(); + let mut env = common::evm_env(); + env.block_env = BlockEnv { gas_limit: budget, ..env.block_env }; + let mut executor = common::executor_with_env(&mut state, common::unlimited_ctx(), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = executor.run_transaction(&first).expect("the block's footprint budget is free"); + let second = executor.run_transaction(&second).expect("nothing has committed yet"); + + executor.commit_transaction_outcome(first).expect("the block has the footprint for it"); + let err = executor + .commit_transaction_outcome(second) + .expect_err("the block's footprint was spent while this transaction waited"); + + assert!( + format!("{err}").contains("DA footprint exceeds available block DA footprint"), + "{err}" + ); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "only the transaction that fit was packed"); + assert!(result.blob_gas_used <= budget, "the block stays within its footprint budget"); +} From e69da600d88d3f5e35906f156fc14c1fc916f6e2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:40:30 +0800 Subject: [PATCH 116/201] fix(evm): make the block-hash record a per-block read set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The record was revm's `State` cache read back out. The cache outlives one block, so a database reused over a range of blocks, or one whose cache was filled in advance, reported hashes the block being executed never asked for — and nothing emptied it when a block started. Record the reads where they happen instead: the Host keeps a `BlockHashRecord` in the context, block execution empties it when the block starts, and the getters read that. The record cannot be reset through the `BlockExecutor` trait's database bound, which alloy-evm fixes at `StateDB`, so keeping it beside the cache is also what makes the reset expressible. The cache keeps serving what it holds, so nothing is fetched twice. --- AGENTS.md | 24 ++--- crates/mega-evm/src/block/executor.rs | 26 ++++-- crates/mega-evm/src/evm/context.rs | 26 +++++- crates/mega-evm/src/evm/host.rs | 15 +++- crates/mega-evm/src/evm/mod.rs | 27 +++--- crates/mega-evm/src/evm/state.rs | 98 ++++++++++++--------- crates/mega-evm/tests/block/block_hashes.rs | 88 +++++++++++++++++- 7 files changed, 223 insertions(+), 81 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c9c585434..e043e82a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,17 +84,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | -| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds now | Filled by | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -103,7 +103,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. Gas above the 200M execution cap goes to the EIP-8037 reservoir. The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. -- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did and the block-hash read the Host records. With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 64e7cc59c..40f887fa8 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -73,9 +73,9 @@ pub type MegaFinishedBlock = (MegaEvm, MegaBlockExecutionResult<::Receipt>); use crate::{ - block::eips, estimated_da_size, BlockGasCounters, BlockHashes, BlockLimiter, BlockLimits, - ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, - MegaHardforks, MegaTransaction, MegaTransactionExt, + block::eips, estimated_da_size, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, + MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, + MegaTransaction, MegaTransactionExt, }; /// What the node hands block execution beside the EVM. @@ -324,19 +324,23 @@ where impl MegaBlockExecutor, R, Spec> where - DB: Database + BlockHashes, + DB: Database, ExtEnvs: ExternalEnvTypes, R: OpReceiptBuilder, { - /// The block hashes the block's transactions have read so far. + /// The block hashes this block's transactions have read so far. /// /// `BLOCKHASH` reads bypass the journal, so this is where a stateless witness learns of them. + /// The record covers this executor's block: + /// [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) empties it + /// when the block starts, so a database reused over a range of blocks does not report the + /// reads of an earlier one. pub fn get_accessed_block_hashes(&self) -> BTreeMap { self.evm.get_accessed_block_hashes() } /// Forgets the block hashes read so far, so the next reads are attributable to one - /// transaction. The record is a cache, so clearing it changes no execution result. + /// transaction. The record decides nothing, so clearing it changes no execution result. pub fn clear_accessed_block_hashes(&mut self) { self.evm.clear_accessed_block_hashes(); } @@ -359,9 +363,9 @@ where /// Runs what a block does before its transactions. /// - /// In order: the admission gate and the EIP-2935 and EIP-4788 pre-block calls. Each call's - /// state is committed here rather than inside its helper, so a witness generator sees every - /// step's read and write set. + /// In order: the admission gate, the reset of the block-hash record, and the EIP-2935 and + /// EIP-4788 pre-block calls. Each call's state is committed here rather than inside its + /// helper, so a witness generator sees every step's read and write set. /// /// The L1 block info is not read here. op-revm's handler reads it when it deducts the caller /// of the first non-deposit transaction, which is after the block's own L1 info deposit has @@ -375,6 +379,10 @@ where fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; + // The block starts with an empty block-hash record, so what it holds at the end is what + // this block read. + self.evm.clear_accessed_block_hashes(); + let state = eips::transact_blockhashes_contract_call( &self.spec, self.ctx.parent_hash, diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 309fccdca..860befb87 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -9,8 +9,8 @@ use revm::{ }; use crate::{ - constants, AdditionalLimit, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, - ExternalEnvs, MegaSpecId, MegaTransaction, + constants, AdditionalLimit, BlockHashRecord, EmptyExternalEnv, EvmTxRuntimeLimits, + ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -35,6 +35,7 @@ pub struct MegaContext, external_envs: ExternalEnvs, pub(crate) additional_limit: AdditionalLimit, + pub(crate) block_hash_record: BlockHashRecord, } impl MegaContext { @@ -53,7 +54,13 @@ impl MegaContext { ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); - Self { inner, cfg, external_envs, additional_limit: AdditionalLimit::default() } + Self { + inner, + cfg, + external_envs, + additional_limit: AdditionalLimit::default(), + block_hash_record: BlockHashRecord::default(), + } } /// Replaces the configuration. @@ -115,6 +122,19 @@ impl MegaContext { self } + /// The block hashes execution has read on this context. + /// + /// The record belongs to one block: block execution empties it when the block starts, so it + /// never carries a hash an earlier block read. + pub const fn block_hash_record(&self) -> &BlockHashRecord { + &self.block_hash_record + } + + /// Forgets the block hashes read so far. + pub fn clear_block_hash_record(&mut self) { + self.block_hash_record.clear(); + } + /// The common execution layer's state for the running (or last) transaction. pub const fn additional_limit(&self) -> &AdditionalLimit { &self.additional_limit diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index c4d9cd34f..227211ea9 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -10,7 +10,8 @@ //! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the //! frame with the record already counted. //! -//! Every other Host method delegates to op-revm's context. +//! `block_hash` serves the read and records it, so a stateless witness learns of a `BLOCKHASH` +//! that bypassed the journal. Every other Host method delegates to op-revm's context. use alloy_primitives::map::Entry; use delegate::delegate; @@ -51,7 +52,6 @@ impl revm::context_interface::Host fn is_amsterdam_eip8037_enabled(&self) -> bool; fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; - fn block_hash(&mut self, number: u64) -> Option; fn sload_skip_cold_load( &mut self, address: Address, @@ -74,6 +74,17 @@ impl revm::context_interface::Host } } + /// Serves the hash and records that this block read it. + /// + /// `BLOCKHASH` reads the chain's history through the database, so a witness built from the + /// journal alone would miss it; the record is where a node learns of the read. + #[inline] + fn block_hash(&mut self, number: u64) -> Option { + let hash = self.inner.block_hash(number)?; + self.block_hash_record.record(number, hash); + Some(hash) + } + /// Writes the slot and stages the write's values. #[inline] fn sstore_skip_cold_load( diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index a29c9b155..6b2e7ee05 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -185,20 +185,22 @@ impl MegaEvm { impl MegaEvm where - DB: Database + BlockHashes, + DB: Database, ExtEnvs: ExternalEnvTypes, { - /// The block hashes execution has read on this database so far. + /// The block hashes execution has read on this EVM so far. /// /// `BLOCKHASH` reads bypass the journal, so this is where a stateless witness learns of them. + /// The record starts empty and is emptied again when block execution starts a block, so it + /// holds what this EVM read and not what its database cached earlier. pub fn get_accessed_block_hashes(&self) -> BTreeMap { - self.ctx().db().get_accessed_block_hashes() + self.ctx().block_hash_record().hashes().clone() } /// Forgets the block hashes read so far, so the next reads are attributable to one - /// transaction. The record is a cache, so clearing it changes no execution result. + /// transaction. The record decides nothing, so clearing it changes no execution result. pub fn clear_accessed_block_hashes(&mut self) { - self.ctx_mut().db_mut().clear_accessed_block_hashes(); + self.ctx_mut().clear_block_hash_record(); } } @@ -558,16 +560,21 @@ mod tests { assert!(matches!(invalid, Some(InvalidTransaction::LackOfFundForMaxFee { .. })), "{err:?}"); } - /// The EVM reads the block hashes the wrapped `State` served, which is where a stateless - /// witness learns of a `BLOCKHASH` read. + /// The EVM reports the block hashes its Host served, which is where a stateless witness + /// learns of a `BLOCKHASH` read. What the database cached before is not a read of this EVM. #[test] - fn test_mega_evm_exposes_state_wrapper_block_hashes() { + fn test_mega_evm_exposes_the_block_hashes_it_read() { let mut db = MemoryDatabase::default(); let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(7, B256::from([7_u8; 32])); + state.block_hashes.insert(1, B256::from([1_u8; 32])); let mut evm = MegaEvm::new(context(&mut state)); - assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); + assert!(evm.get_accessed_block_hashes().is_empty(), "the cache is not a read"); + + let served = revm::context_interface::Host::block_hash(evm.ctx_mut(), 7) + .expect("the database serves the hash"); + assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&served)); + assert_eq!(evm.get_accessed_block_hashes().len(), 1, "and only the read"); evm.clear_accessed_block_hashes(); assert!(evm.get_accessed_block_hashes().is_empty()); diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs index aff17b70c..c61e0533f 100644 --- a/crates/mega-evm/src/evm/state.rs +++ b/crates/mega-evm/src/evm/state.rs @@ -1,73 +1,87 @@ //! The block hashes execution read, which a node's stateless witness needs. //! //! `BLOCKHASH` reads the chain's history through the database, not through the journal, so a -//! witness built from a transaction's state alone would miss them. revm's [`State`] already -//! caches every hash it served in `block_hashes`; [`BlockHashes`] is the read of that cache the -//! block executor and the node share. +//! witness built from a transaction's state alone would miss them. The Host records every hash it +//! serves in the [`BlockHashRecord`] the context keeps, and block execution empties the record +//! when the block starts, so what the record holds is what this block read. +//! +//! The record is kept beside revm's `State`, not read out of it: `State` caches every hash it ever +//! served, across every block it was used for, so a database reused over a range of blocks — or +//! one whose cache was filled in advance — would report hashes this block never asked for. #[cfg(not(feature = "std"))] use alloc as std; use std::collections::BTreeMap; use alloy_primitives::B256; -use auto_impl::auto_impl; -use revm::{ - database::{states::block_hash_cache::BlockHashCache, State}, - Database, -}; -/// The block hashes execution has read so far. +/// The block hashes execution has read, by block number. /// -/// The record accumulates across every transaction executed on the same database, so a caller -/// that attributes reads to one transaction clears it first -/// ([`clear_accessed_block_hashes`](Self::clear_accessed_block_hashes)). It is a cache: a -/// cleared hash is fetched again on the next read, so clearing it changes no execution result. -#[auto_impl(&mut, Box)] -pub trait BlockHashes { - /// The block hashes read so far, by block number. - fn get_accessed_block_hashes(&self) -> BTreeMap; +/// The record accumulates over the transactions of one block; block execution empties it at the +/// start of the block, and a caller that attributes reads to one transaction empties it between +/// transactions ([`MegaEvm::clear_accessed_block_hashes`](crate::MegaEvm)). It records what was +/// read and decides nothing, so emptying it changes no execution result. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct BlockHashRecord(BTreeMap); - /// Forgets the hashes read so far. - fn clear_accessed_block_hashes(&mut self); -} +impl BlockHashRecord { + /// Records that `number`'s hash was read, and what it was. + pub fn record(&mut self, number: u64, hash: B256) { + self.0.insert(number, hash); + } -impl BlockHashes for State { - fn get_accessed_block_hashes(&self) -> BTreeMap { - self.block_hashes.iter().collect() + /// The hashes read so far, by block number. + pub const fn hashes(&self) -> &BTreeMap { + &self.0 } - fn clear_accessed_block_hashes(&mut self) { - self.block_hashes = BlockHashCache::new(); + /// Whether nothing has been read. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Forgets the hashes read so far. + pub fn clear(&mut self) { + self.0.clear(); } } #[cfg(test)] mod tests { use super::*; - use revm::database::InMemoryDB; #[test] - fn test_state_exposes_accessed_block_hashes() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(1, B256::ZERO); - state.block_hashes.insert(2, B256::from([2_u8; 32])); - - let hashes = state.get_accessed_block_hashes(); - assert_eq!(hashes.len(), 2); - assert_eq!(hashes.get(&1), Some(&B256::ZERO)); - assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); + fn test_the_record_holds_what_was_read() { + let mut record = BlockHashRecord::default(); + assert!(record.is_empty()); + + record.record(1, B256::ZERO); + record.record(2, B256::from([2_u8; 32])); + + assert_eq!(record.hashes().len(), 2); + assert_eq!(record.hashes().get(&1), Some(&B256::ZERO)); + assert_eq!(record.hashes().get(&2), Some(&B256::from([2_u8; 32]))); + } + + /// Reading the same block twice records it once, with the hash it was served with. + #[test] + fn test_the_record_keeps_one_entry_per_block() { + let mut record = BlockHashRecord::default(); + record.record(7, B256::from([7_u8; 32])); + record.record(7, B256::from([7_u8; 32])); + + assert_eq!(record.hashes().len(), 1); } - /// Clearing empties the record and leaves the database able to serve the hash again. + /// Clearing empties the record. #[test] fn test_clearing_forgets_the_hashes_read_so_far() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(7, B256::from([7_u8; 32])); + let mut record = BlockHashRecord::default(); + record.record(7, B256::from([7_u8; 32])); - state.clear_accessed_block_hashes(); + record.clear(); - assert!(state.get_accessed_block_hashes().is_empty()); + assert!(record.is_empty()); + assert!(record.hashes().is_empty()); } } diff --git a/crates/mega-evm/tests/block/block_hashes.rs b/crates/mega-evm/tests/block/block_hashes.rs index 5fb4c084f..1622a945e 100644 --- a/crates/mega-evm/tests/block/block_hashes.rs +++ b/crates/mega-evm/tests/block/block_hashes.rs @@ -1,8 +1,9 @@ //! The block hashes a block's transactions read, which a stateless witness needs. use alloy_evm::block::BlockExecutor; -use alloy_primitives::Bytes; -use mega_evm::test_utils::BytecodeBuilder; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{Bytes, B256}; +use mega_evm::{test_utils::BytecodeBuilder, MegaBlockExecutor}; use revm::{ bytecode::opcode::{BLOCKHASH, POP}, database::State, @@ -13,20 +14,37 @@ use crate::common::{self, executor, recovered, user_tx, BLOCK_NUMBER, CONTRACT}; /// The block number the contract below reads, one below the block being executed. const READ_BLOCK: u64 = BLOCK_NUMBER - 1; +/// A second block number, read by a second contract. +const OTHER_READ_BLOCK: u64 = BLOCK_NUMBER - 2; + /// An account with no code, so a call to it reads no block hash. const PLAIN: alloy_primitives::Address = alloy_primitives::address!("0x1000000000000000000000000000000000000002"); +/// A second contract, which reads a different block number. +const OTHER: alloy_primitives::Address = + alloy_primitives::address!("0x1000000000000000000000000000000000000003"); + /// Code that reads `BLOCKHASH(READ_BLOCK)` and discards it. fn blockhash_contract() -> Bytes { + blockhash_reader(READ_BLOCK) +} + +/// Code that reads `BLOCKHASH(number)` and discards it. +fn blockhash_reader(number: u64) -> Bytes { BytecodeBuilder::default() - .push_number(READ_BLOCK as u32) + .push_number(number as u32) .append(BLOCKHASH) .append(POP) .stop() .build() } +/// The block numbers the record holds. +fn read_numbers(executor: &crate::common::TestExecutor<'_>) -> Vec { + executor.get_accessed_block_hashes().into_keys().collect() +} + /// The record accumulates over the block's transactions and can be cleared, so a caller can /// attribute the reads to one transaction. Clearing changes no execution result. #[test] @@ -60,3 +78,67 @@ fn test_accessed_block_hashes_track_and_clear_per_transaction() { executor.execute_transaction(&user_tx(2, 1_000_000)).expect("the transaction executes"); assert_eq!(executor.get_accessed_block_hashes().len(), 1); } + +/// The record covers one block: an EVM and a `State` carried over to the next block report that +/// block's reads and not the ones before it. +#[test] +fn test_two_blocks_over_the_same_evm_report_only_their_own_reads() { + let mut db = common::database(); + db.set_account_code(CONTRACT, blockhash_reader(READ_BLOCK)); + db.set_account_code(OTHER, blockhash_reader(OTHER_READ_BLOCK)); + let mut state = State::builder().with_database(db).build(); + + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + assert_eq!(read_numbers(&executor), vec![READ_BLOCK]); + + // The next block runs on the EVM the first handed back, so both its record and its database + // carry what the first block read. + let (evm, _) = executor.finish_with_counters().expect("the block finishes"); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ); + executor.apply_pre_execution_changes().expect("the next block starts"); + executor + .execute_transaction(&recovered(common::tx(1, OTHER, Bytes::new(), 1_000_000))) + .expect("the transaction executes"); + + assert_eq!( + read_numbers(&executor), + vec![OTHER_READ_BLOCK], + "what the block before read is not this block's read set" + ); +} + +/// A hash the database already cached is not a read of this block — and the cache keeps it, so +/// nothing has to be fetched twice. +#[test] +fn test_a_cached_hash_the_block_never_read_is_not_reported() { + const CACHED: u64 = BLOCK_NUMBER - 3; + + let mut db = common::database(); + db.set_account_code(CONTRACT, blockhash_contract()); + let mut state = State::builder().with_database(db).build(); + state.block_hashes.insert(CACHED, B256::repeat_byte(0xaa)); + + { + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + + assert_eq!( + read_numbers(&executor), + vec![READ_BLOCK], + "the cached hash was never asked for in this block" + ); + } + + assert!( + state.block_hashes.iter().any(|(number, _)| number == CACHED), + "and the cache still holds it" + ); +} From 91dcd100eb38dc24652bde287a8501dfbd8007e5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:43:11 +0800 Subject: [PATCH 117/201] bench(block): give every storage write a slot of its own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The workload stored the same value in the same slot 64 times, so only the first transaction changed storage: the other 63 wrote back the value the slot already held, the write record was taken back, and what the bench measured was an unchanged-value SSTORE. Each transaction now names its own slot in its calldata, and the run outside the measurement asserts that every transaction of both workloads succeeded and kept a write record — which the old workload fails. --- crates/mega-evm/benches/block.rs | 52 ++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 256734203..84cc92254 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -7,8 +7,9 @@ //! //! - `transfers`: value transfers to accounts with no code — the cheapest transaction there is, so //! the executor's own cost is most of what is measured. -//! - `storage_writes`: calls to a contract that writes a slot, so every transaction also carries a -//! write record through the counters and a log-free receipt. +//! - `storage_writes`: calls to a contract that writes the slot the transaction names in its +//! calldata, so every transaction changes storage and carries a write record through the +//! counters, with a log-free receipt. //! //! The pre-block calls and the state the block is built on are setup, and the measurement runs //! `apply_pre_execution_changes`, the transactions and `finish` — the whole block a node @@ -26,6 +27,7 @@ use mega_evm::{ MegaSpecId, MegaTxEnvelope, }; use revm::{ + bytecode::opcode::{CALLDATALOAD, SSTORE}, context::{BlockEnv, CfgEnv}, database::State, }; @@ -47,9 +49,22 @@ const SENDER: Address = address!("0x2000000000000000000000000000000000000002"); const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); const WRITER: Address = address!("0x1000000000000000000000000000000000000001"); -/// Code that writes one slot, so a call to it leaves a write record behind. +/// Code that writes 1 to the slot its first calldata word names, so every call that names a slot +/// of its own changes storage and leaves a write record behind. fn writer_code() -> Bytes { - BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).stop().build() + BytecodeBuilder::default() + .push_number(1_u64) + .push_number(0_u64) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build() +} + +/// The slot the transaction with this nonce writes: one per transaction, so none of them writes +/// a value the slot already holds. +fn slot_calldata(nonce: u64) -> Bytes { + Bytes::from(U256::from(nonce + 1).to_be_bytes::<32>()) } /// The database every iteration starts from. @@ -80,8 +95,13 @@ fn block_ctx() -> MegaBlockExecutionCtx { MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits()) } -/// `N` transactions to `to`, one per nonce. -fn transactions(to: Address, value: u64, gas_limit: u64) -> Vec> { +/// `N` transactions to `to`, one per nonce, each carrying the input `input` builds for it. +fn transactions( + to: Address, + value: u64, + gas_limit: u64, + input: impl Fn(u64) -> Bytes, +) -> Vec> { (0..N) .map(|nonce| { let tx = TxLegacy { @@ -91,7 +111,7 @@ fn transactions(to: Address, value: u64, gas_limit: u64) -> Vec Vec 0, + "every transaction of the workload keeps a write record" + ); + executor.commit_transaction(outcome); } let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), N as usize); assert!(result.gas.execution > 0); + assert_eq!(result.usage.write_records, N, "one record per transaction, at least"); } group.bench_function(*name, |b| { From af926f78cb51cf867e43b2bb68d485377cd239e5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:43:39 +0800 Subject: [PATCH 118/201] docs(evm): say what the pressed-back entries do to state creation The list was documented as EIP-8038's access repricing. Three of its seventeen entries are ones EIP-8037 moved onto the state dimension, so pressing them back charges state creation on both dimensions: a value CALL that creates its recipient pays 25,000 regular and 183,600 state, a CREATE opcode 32,000 and 183,600, a slot's first write 22,100 and 97,920. The docs now say that, with the numbers, and name tx_create_cost as the one entry the list prices and nothing reads: under EIP-2780 the intrinsic phase charges a creation through tx_create_access_cost. --- crates/mega-evm/src/evm/schedule.rs | 37 +++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 50e612870..05c737c20 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -4,12 +4,20 @@ //! intrinsic decomposition, the EIP-7976 calldata floor and EIP-7981 access-list data — and //! changes exactly two things: //! -//! 1. every entry EIP-8038 repriced goes back to its Osaka value ([`EIP8038_REPRICED`]), so state -//! *access* is priced as Osaka prices it and only state *creation* is repriced; +//! 1. every regular-gas entry the Amsterdam table changed for EIP-8037 or EIP-8038 goes back to its +//! Osaka value ([`EIP8038_REPRICED`]) — every one but the state-gas, EIP-2780, floor and +//! EIP-7702 entries, which stay Amsterdam's; //! 2. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than //! Glamsterdam's. //! +//! The first group includes the three entries EIP-8037 moved onto the state dimension, so at these +//! prices state creation is charged on both dimensions: a value `CALL` that creates its recipient +//! pays 25,000 regular and 183,600 state, a `CREATE` opcode 32,000 and 183,600, a slot's first +//! write 22,100 and 97,920, where the Amsterdam schedule charges 0, 12,000 and 12,100 regular +//! against the same state charge. Whether creation keeps its Osaka regular price is an open +//! pricing question; the schedule states the prices, it does not settle them. +//! //! Every other entry is Amsterdam's, including the EIP-2780 decomposition entries //! (`tx_account_write_cost`, `tx_create_access_cost`), the zero `code_deposit_cost` and the floor. //! The history entry stays at zero: history gas is its own mechanism and switches it on. @@ -25,15 +33,24 @@ use revm::{ use crate::evm::prices::{active_satin_prices, SatinPrices}; -/// The schedule entries EIP-8038 repriced, which Satin keeps at their pre-EIP-8038 values. +/// The regular-gas entries Amsterdam repriced for EIP-8037 and EIP-8038, which Satin keeps at +/// their Osaka values. +/// +/// Amsterdam moves them for two reasons. EIP-8038 raises the price of *reaching* state — a cold +/// account, a cold slot, a storage write. EIP-8037 lowers the regular price of *creating* state, +/// having moved that charge onto the state dimension: `new_account_cost`, `create` and +/// `sstore_set_without_load_cost` are that group. Satin takes neither move, so state creation +/// keeps its Osaka regular price on top of the state charge at +/// [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE); the module documentation puts +/// numbers on what that costs. The list is named for EIP-8038 because that is the repricing it +/// was drawn up against. /// -/// EIP-8038 raises the price of *reaching* state — a cold account, a cold slot, a storage write, -/// an account write. Satin prices state creation on its own dimension instead (EIP-8037 state gas -/// at [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE)), so it does not adopt that -/// second increase: every entry EIP-8038 moved is pushed back to what the Osaka schedule has. +/// `tx_create_cost` is priced here and read nowhere: under EIP-2780 the intrinsic phase charges a +/// creation through `tx_create_access_cost`, so pressing this entry back moves no transaction. /// -/// Entries Amsterdam introduced for EIP-2780, EIP-7976 and EIP-7981 are not in this list and keep -/// their Amsterdam values, even where the number itself is derived from an EIP-8038 constant. +/// The entries Amsterdam introduced for EIP-8037's state gas, EIP-2780, EIP-7976, EIP-7981 and +/// EIP-7702 are not in this list and keep their Amsterdam values, even where the number itself is +/// derived from an EIP-8038 constant. pub const EIP8038_REPRICED: &[fn() -> GasId] = &[ GasId::warm_storage_read_cost, GasId::cold_account_additional_cost, @@ -114,7 +131,7 @@ mod tests { GasParams::new_spec(SpecId::AMSTERDAM) } - /// The seventeen entries EIP-8038 repriced are back at their Osaka values, written out so a + /// The seventeen entries Amsterdam repriced are back at their Osaka values, written out so a /// change to the list is a visible diff. #[test] fn test_the_eip8038_repricing_is_pressed_back_to_osaka() { From beb3db79ee4a392e7ea6b8635ae83908a87df75a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:43:46 +0800 Subject: [PATCH 119/201] docs(satin): name the intrinsic recipient charge as EIP-2780's own The tests called the 3,000 a recipient's cold account access. The schedule prices a cold account access at 2,600 inside execution; the intrinsic phase adds EIP-2780's own fixed 3,000, so a reader deriving one from the other lands 400 short, and repricing the schedule entry would not move the intrinsic number. --- crates/mega-evm/tests/satin/intrinsic.rs | 6 +++++- crates/mega-evm/tests/satin/schedule.rs | 7 +++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 1c7b05a2c..5f187c743 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -31,7 +31,11 @@ const CALLER: Address = address!("0000000000000000000000000000000000800000"); const CALLEE: Address = address!("0000000000000000000000000000000000800001"); /// The intrinsic gas of a plain call to an account that is not the sender: the EIP-2780 sender -/// base plus the recipient's cold account access. +/// base of 12,000 plus 3,000 for reaching the recipient. +/// +/// The 3,000 is EIP-2780's own fixed charge, not the schedule's cold-account entry: inside +/// execution the schedule prices a cold account access at 2,600 — 100 for the read and 2,500 for +/// the cold surcharge — so repricing that entry would leave this number where it is. const EMPTY_CALL: u64 = 15_000; /// What one byte of anything a transaction carries costs in the EIP-7976 / EIP-7981 floor: four diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 040a1e533..8c0a0813e 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -46,8 +46,11 @@ fn with_code(code: Bytes) -> MemoryDatabase { /* ---------- the intrinsic numbers ---------- */ -/// A call that reaches an existing account and does nothing pays the sender base plus the -/// recipient's cold access, and draws no state gas. +/// A call that reaches an existing account and does nothing pays the EIP-2780 sender base of +/// 12,000 plus 3,000 for reaching the recipient, and draws no state gas. +/// +/// The 3,000 is EIP-2780's own fixed charge and not the schedule's cold-account entry, which +/// prices an access inside execution at 2,600. #[test] fn test_an_empty_call_costs_fifteen_thousand() { let spent = spend(with_code(Bytes::new()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); From 45b100198d7e774cbb188eccc0c5077200a70969 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:43:46 +0800 Subject: [PATCH 120/201] docs: say the tests read the two state-gas constants The constants table named the gas schedule as their reader. The schedule derives its state entries from the EIP-8037 byte counts at the cost per state byte, so changing either constant moves a test, not a price. --- crates/mega-evm/src/constants.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 462663bab..9db7e0493 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -7,8 +7,8 @@ //! | Constant | Value | Meaning | Read by | //! |---|---:|---|---| //! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas schedule | -//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | the Satin gas schedule | -//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | the Satin gas schedule | +//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | tests of the Satin gas schedule | +//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | tests of the Satin gas schedule | //! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas (not yet) | //! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | the spec configuration | //! | [`MAX_CONTRACT_SIZE`] | 524,288 | the most bytes a deployed contract may hold | the spec configuration | @@ -16,8 +16,11 @@ //! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the data-size limit (not yet) | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the data-size limit (not yet) | //! -//! The Satin gas schedule reads the state-gas numbers through [`SatinPrices`](crate::SatinPrices), -//! so a measurement build can run other byte prices without touching this table. +//! The Satin gas schedule builds its state-gas entries from the EIP-8037 byte counts at +//! [`COST_PER_STATE_BYTE`], read through [`SatinPrices`](crate::SatinPrices) so a measurement +//! build can run other byte prices without touching this table. [`SLOT_STATE_GAS`] and +//! [`ACCOUNT_STATE_GAS`] are two of those products written out: the tests assert the schedule +//! against them, and changing one of the two moves a test rather than a price. //! The storage call stipend and the per-transaction and per-block state-gas limits are further //! placeholders; history gas and the state-gas limits add them when they land. From ea5bd8cc7b756a0f62fb8b863e554acb729b6837 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:47:14 +0800 Subject: [PATCH 121/201] test: skip the tests that assert the spec's byte prices at other prices A measurement build that exported MEGA_SATIN_CPSB or MEGA_SATIN_CPHB got sixteen failures whose cause was the price it had asked for. Those tests now return early and the process says so once, on stderr, where the harness does not capture it. The one that recovers the EIP-8037 byte counts builds at the constants instead, so it holds either way; that the process runs that schedule is its own test, which is one of the skippers. AGENTS.md says the suite wants the two variables unset. --- AGENTS.md | 2 ++ crates/mega-evm/src/evm/prices.rs | 35 +++++++++++++++++++ crates/mega-evm/src/evm/schedule.rs | 13 +++++-- crates/mega-evm/tests/satin/common.rs | 27 ++++++++++++++ crates/mega-evm/tests/satin/equivalence.rs | 5 +++ crates/mega-evm/tests/satin/intrinsic.rs | 8 ++++- crates/mega-evm/tests/satin/outcome.rs | 5 ++- crates/mega-evm/tests/satin/pricing_table.rs | 8 ++++- crates/mega-evm/tests/satin/schedule.rs | 17 ++++++++- crates/mega-evm/tests/satin/strategic_stop.rs | 5 ++- 10 files changed, 117 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 612006204..1501562e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,8 @@ cargo test -p mega-evm -- test_name # single test # The gas schedule's byte prices are an input; this feature lets a measurement build change them cargo test -p mega-evm --features satin-price-override,test-utils +# Run the suite with MEGA_SATIN_CPSB and MEGA_SATIN_CPHB unset: with either of them set the tests +# that assert the spec's own byte prices skip, and the suite checks less than it looks like it does # Regenerate the checked-in pricing table after an intentional schedule or engine change UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index 6f94ee927..a72b15823 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -270,6 +270,35 @@ pub fn active_satin_prices() -> SatinPrices { } } +/// Whether this process prices bytes at something other than the constants. +/// +/// Only a measurement build can arrange that — the `satin-price-override` feature, through +/// [`install_satin_prices`] or the two environment variables — and it moves every state-gas +/// number in the schedule. A test that asserts one of those numbers returns early instead of +/// failing on a price the developer asked for. +/// +/// The notice goes straight to stderr and only once: the harness captures the print macros of a +/// test that passes, so a message written with them would never be read. +#[cfg(test)] +pub(crate) fn runs_at_measurement_prices() -> bool { + if active_satin_prices().is_constants() { + return false; + } + #[cfg(feature = "satin-price-override")] + { + use std::io::Write; + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the tests that assert the spec's byte prices, because \ + {CPSB_ENV_VAR} or {CPHB_ENV_VAR} fixed other ones; unset them to run those tests" + ); + }); + } + true +} + #[cfg(test)] mod tests { use super::*; @@ -346,6 +375,9 @@ mod tests { /// them; with it, an unset environment leaves them at the constants too. #[test] fn test_the_active_prices_default_to_the_constants() { + if runs_at_measurement_prices() { + return; + } assert_eq!(active_satin_prices(), SatinPrices::CONSTANTS); } @@ -354,6 +386,9 @@ mod tests { #[cfg(feature = "satin-price-override")] #[test] fn test_installing_the_prices_in_effect_is_idempotent() { + if runs_at_measurement_prices() { + return; + } assert_eq!(install_satin_prices(SatinPrices::CONSTANTS), Ok(())); assert_eq!(install_satin_prices(SatinPrices::CONSTANTS), Ok(())); diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 05c737c20..254c0909c 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -120,7 +120,7 @@ mod tests { use super::*; use crate::{ constants::{ACCOUNT_STATE_GAS, COST_PER_STATE_BYTE, SLOT_STATE_GAS}, - evm::prices::BytePrice, + evm::prices::{runs_at_measurement_prices, BytePrice}, }; fn osaka() -> GasParams { @@ -241,9 +241,13 @@ mod tests { /// The state entries are EIP-8037's byte counts at `MegaETH`'s price. Dividing an entry by /// the price recovers the byte count the EIP names, which is the property that survives a /// repricing. + /// + /// Built at the constants rather than read off the process, so the numbers below hold in a + /// measurement build too; that the process runs this schedule is + /// [`test_the_schedule_at_the_active_prices_is_the_schedule_at_the_constants`]. #[test] fn test_state_entries_recover_the_eip8037_byte_counts() { - let satin = satin_gas_params(); + let satin = satin_gas_params_at(SatinPrices::CONSTANTS); for &(id, bytes) in STATE_GAS_REPRICED { let id = id(); assert_eq!(satin.get(id), bytes * COST_PER_STATE_BYTE, "{} at the price", id.name()); @@ -284,9 +288,12 @@ mod tests { } /// The prices in effect are the constants, so the schedule the engine installs is the one - /// built at them. + /// built at them. A measurement build is the one case where they part, and it skips. #[test] fn test_the_schedule_at_the_active_prices_is_the_schedule_at_the_constants() { + if runs_at_measurement_prices() { + return; + } assert_eq!(satin_gas_params().table(), satin_gas_params_at(SatinPrices::CONSTANTS).table()); } } diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index c94d91fbc..054d77f6e 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -4,6 +4,7 @@ use alloy_evm::Evm; use alloy_op_evm::OpTx; use alloy_primitives::{Address, Bytes, TxKind, U256}; use mega_evm::{ + active_satin_prices, test_utils::{op_transaction, zero_fee_l1_block_info}, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, }; @@ -57,3 +58,29 @@ pub(crate) fn run( let usage = evm.ctx().additional_limit().usage(); (result, usage) } + +/// Whether this process prices bytes at something other than the constants the spec fixes. +/// +/// Only a measurement build can arrange that — the `satin-price-override` feature, through +/// `install_satin_prices` or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` variables — and it moves +/// every state-gas number. A test that asserts one of those numbers returns early instead of +/// failing on a price the developer asked for. +/// +/// The notice goes straight to stderr and only once: the harness captures the print macros of a +/// test that passes, so a message written with them would never be read. +pub(crate) fn runs_at_measurement_prices() -> bool { + use std::io::Write; + + if active_satin_prices().is_constants() { + return false; + } + static NOTICE: std::sync::Once = std::sync::Once::new(); + NOTICE.call_once(|| { + let _ = writeln!( + std::io::stderr(), + "note: skipping the tests that assert the spec's byte prices, because \ + MEGA_SATIN_CPSB or MEGA_SATIN_CPHB fixed other ones; unset them to run those tests" + ); + }); + true +} diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 688c5ad21..fa6cb1966 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -24,6 +24,8 @@ use revm::{ ExecuteEvm, Journal, }; +use crate::common::runs_at_measurement_prices; + const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); @@ -150,6 +152,9 @@ fn test_value_transfer_matches_op_revm() { #[test] fn test_sstore_matches_op_revm() { + if runs_at_measurement_prices() { + return; + } let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(); let db = MemoryDatabase::default().account_code(CALLEE, code); let tx = TxEnv { diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 5f187c743..4b9d75581 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -25,7 +25,7 @@ use revm::{ Database, }; -use crate::common::{call, context, create}; +use crate::common::{call, context, create, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000800000"); const CALLEE: Address = address!("0000000000000000000000000000000000800001"); @@ -239,6 +239,9 @@ fn assert_sender_untouched() { /// the intrinsic charge alone is accepted and then runs out of gas, charging the sender. #[test] fn test_a_transfer_that_cannot_pay_the_new_account_runs_out_of_gas() { + if runs_at_measurement_prices() { + return; + } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let mut evm = MegaEvm::new(context(db)); let outcome = evm @@ -253,6 +256,9 @@ fn test_a_transfer_that_cannot_pay_the_new_account_runs_out_of_gas() { /// at validation. #[test] fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { + if runs_at_measurement_prices() { + return; + } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let mut evm = MegaEvm::new(context(db)); let outcome = evm diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index feefe0da6..95fd050d9 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -9,7 +9,7 @@ use mega_evm::{ MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, }; -use crate::common::{call, context}; +use crate::common::{call, context, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000600000"); const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); @@ -37,6 +37,9 @@ fn execute( /// sender gets back is reported. #[test] fn test_outcome_reports_the_ledgers() { + if runs_at_measurement_prices() { + return; + } let outcome = execute(writer(), EvmTxRuntimeLimits::no_limits(), 1_000_000_000); assert!(outcome.result.is_success()); let gas = outcome.gas; diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 794cd6bdd..bc08f1115 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -28,7 +28,7 @@ use revm::{ primitives::hardfork::SpecId, }; -use crate::common::{call, context, create}; +use crate::common::{call, context, create, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000b00000"); const CONTRACT: Address = address!("0000000000000000000000000000000000b00001"); @@ -194,6 +194,9 @@ fn measured() -> Vec { /// The rendered table is the one checked in. `UPDATE_SATIN_PRICING_TABLE=1` writes it instead. #[test] fn test_the_pricing_table_is_up_to_date() { + if runs_at_measurement_prices() { + return; + } let rendered = render(); let path = table_path(); if std::env::var_os("UPDATE_SATIN_PRICING_TABLE").is_some() { @@ -213,6 +216,9 @@ fn test_the_pricing_table_is_up_to_date() { /// cannot drift from what it claims. #[test] fn test_the_table_shows_where_satin_differs_from_amsterdam() { + if runs_at_measurement_prices() { + return; + } let rendered = render(); let differing: Vec<&str> = rendered .lines() diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 8c0a0813e..a51bf3417 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -16,7 +16,7 @@ use revm::{ context::result::ExecutionResult, }; -use crate::common::{call, call_with_data, context, create}; +use crate::common::{call, call_with_data, context, create, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000900000"); const CALLEE: Address = address!("0000000000000000000000000000000000900001"); @@ -72,6 +72,9 @@ fn test_a_value_transfer_to_an_existing_account_costs_twenty_one_thousand() { /// top of the transfer's own cost. #[test] fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas() { + if runs_at_measurement_prices() { + return; + } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let spent = spend(db, call(CALLER, CALLEE, U256::from(7), GAS_LIMIT)); assert_eq!(spent.state, ACCOUNT_STATE_GAS); @@ -93,6 +96,9 @@ fn test_a_self_transfer_costs_twelve_thousand() { /// what is left when the state gas is taken out. #[test] fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_gas() { + if runs_at_measurement_prices() { + return; + } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let spent = spend(db, create(CALLER, Bytes::new(), GAS_LIMIT)); assert_eq!(spent.state, ACCOUNT_STATE_GAS, "the created account"); @@ -105,6 +111,9 @@ fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_g /// not, because the slot is no longer new. #[test] fn test_a_new_slot_draws_the_slot_state_gas() { + if runs_at_measurement_prices() { + return; + } let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); let new = spend(with_code(code.clone()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); assert_eq!(new.state, SLOT_STATE_GAS); @@ -117,6 +126,9 @@ fn test_a_new_slot_draws_the_slot_state_gas() { /// Deployed code is priced by the byte on the state dimension, on top of the created account. #[test] fn test_deployed_code_draws_state_gas_by_the_byte() { + if runs_at_measurement_prices() { + return; + } let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let empty = spend(db(), create(CALLER, Bytes::new(), GAS_LIMIT)); let thirty_two = spend(db(), create(CALLER, deploying(32), GAS_LIMIT)); @@ -151,6 +163,9 @@ fn test_a_reverted_creation_draws_no_state_gas() { /// created, and nothing for code. #[test] fn test_a_creation_depositing_no_code_pays_for_the_account_alone() { + if runs_at_measurement_prices() { + return; + } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let spent = spend(db, create(CALLER, deploying(0), GAS_LIMIT)); assert_eq!(spent.state, ACCOUNT_STATE_GAS); diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 2e18b2daa..50bc64773 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -25,7 +25,7 @@ use revm::{ Database, Inspector, }; -use crate::common::{call, context}; +use crate::common::{call, context, runs_at_measurement_prices}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const A: Address = address!("00000000000000000000000000000000000000A0"); @@ -307,6 +307,9 @@ fn test_child_out_of_gas_under_a_cap_does_not_latch() { /// is never created, so its state gas is never drawn. #[test] fn test_cap_crossed_before_the_first_frame_reverts_without_running() { + if runs_at_measurement_prices() { + return; + } let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); From 3b011ab2f1445c0ec9e52a814bba1ce20a1927d8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:48:41 +0800 Subject: [PATCH 122/201] test(evm): run the byte-price override through a child test process Nothing exercised the environment path: a build with the override feature read MEGA_SATIN_CPSB only if a developer set it by hand. A test now re-executes the test binary with both variables set and an ignored probe selected, and reads the probe's measurement off its output, so a run that selected nothing fails rather than passing empty. It has to be a child process because a process fixes its prices the first time anything builds a schedule. --- crates/mega-evm/src/evm/prices.rs | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index a72b15823..b81338be9 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -400,6 +400,53 @@ mod tests { assert_eq!(active_satin_prices(), SatinPrices::CONSTANTS); } + /// The name the probe below answers to, spelled out because the parent filters on it. A name + /// that drifts from the function filters nothing, which the parent catches: a run that + /// selected no test prints no measurement. + #[cfg(feature = "satin-price-override")] + const PROBE: &str = "evm::prices::tests::test_the_environment_prices_build_the_schedule"; + + /// The environment path end to end: a child process of this test binary, started with both + /// variables set, builds its schedule at the prices they name. + /// + /// It has to be a child. The prices of a process are fixed the first time anything builds a + /// schedule, and this process has built several, so the only way to watch a variable reach + /// the table is to start a process that has not. + #[cfg(feature = "satin-price-override")] + #[test] + fn test_the_environment_prices_reach_a_fresh_process() { + let binary = std::env::current_exe().expect("the running test binary"); + let run = std::process::Command::new(binary) + .args([PROBE, "--exact", "--ignored", "--nocapture"]) + .env(CPSB_ENV_VAR, "312.5") + .env(CPHB_ENV_VAR, "400") + .output() + .expect("the test binary runs"); + let stdout = String::from_utf8_lossy(&run.stdout); + assert!(run.status.success(), "the probe failed:\n{stdout}"); + assert!( + stdout.contains("sstore_set_state_gas = 20000"), + "the probe must report the repriced entry; a run that selected no test reports \ + nothing:\n{stdout}" + ); + } + + /// What [`test_the_environment_prices_reach_a_fresh_process`] runs in its child, and nothing + /// else runs: with the variables unset there is no override to observe, so it is ignored. + #[cfg(feature = "satin-price-override")] + #[test] + #[ignore = "runs in the child process of test_the_environment_prices_reach_a_fresh_process"] + fn test_the_environment_prices_build_the_schedule() { + use revm::context_interface::cfg::GasId; + + let state_gas = crate::satin_gas_params().get(GasId::sstore_set_state_gas()); + std::println!("sstore_set_state_gas = {state_gas}"); + + assert_eq!(active_satin_prices().cpsb, "312.5".parse().unwrap(), "the state byte price"); + assert_eq!(active_satin_prices().cphb, BytePrice::from_gas(400), "the history byte price"); + assert_eq!(state_gas, 20_000, "a slot's 64 bytes at 312.5 gas each"); + } + #[test] fn test_price_errors_name_the_variable_and_the_installed_prices() { let invalid = SatinPriceError::Invalid { From 4cf4b0045d2f5ee04fa3c11ef5fc8135c9cfd7b9 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:51:07 +0800 Subject: [PATCH 123/201] test(satin): cover the EIP-3541 rejection of a deployed 0xEF byte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The row that carried this scenario was ported to a creation that reverts and one that deposits empty code, which leaves the first-byte rejection untested: nothing showed that it lands before the deposit is charged. Two tests now deposit a single 0xEF byte, one from a creation transaction — which halts with the rejection and draws no state gas — and one from a CREATE frame, where the frame returns the zero address and the state gas it took upfront comes back. --- crates/mega-evm/tests/satin/schedule.rs | 61 +++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index a51bf3417..0ea0f152d 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -9,11 +9,11 @@ use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ constants::{ACCOUNT_STATE_GAS, SLOT_STATE_GAS}, test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaEvm, + MegaEvm, MegaHaltReason, }; use revm::{ - bytecode::opcode::{CLZ, DUPN, EXCHANGE, MSTORE, PUSH0, PUSH1, RETURN, SLOTNUM, SWAPN}, - context::result::ExecutionResult, + bytecode::opcode::{CLZ, CREATE, DUPN, EXCHANGE, MSTORE, PUSH0, PUSH1, RETURN, SLOTNUM, SWAPN}, + context::result::{ExecutionResult, HaltReason}, }; use crate::common::{call, call_with_data, context, create, runs_at_measurement_prices}; @@ -159,6 +159,61 @@ fn test_a_reverted_creation_draws_no_state_gas() { assert_eq!(result.gas().state_gas_spent_final(), 0); } +/// Init code that returns a single `0xEF` byte as the deployed code, which EIP-3541 rejects. +fn depositing_an_ef_byte() -> Bytes { + BytecodeBuilder::default() + .mstore(0, [0xEF]) + .push_number(1u64) + .append_many([PUSH0, RETURN]) + .build() +} + +/// EIP-3541 rejects deployed code whose first byte is `0xEF`, and the rejection lands before the +/// deposit is charged: the creation halts and draws no state gas, neither the account's nor the +/// byte's. +#[test] +fn test_a_creation_rejected_for_its_first_byte_draws_no_state_gas() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let mut evm = MegaEvm::new(context(db)); + let result = evm + .transact_raw(create(CALLER, depositing_an_ef_byte(), GAS_LIMIT)) + .expect("the transaction is valid") + .result; + + assert!( + matches!( + result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::CreateContractStartingWithEF), + .. + } + ), + "{result:?}" + ); + assert_eq!(result.gas().state_gas_spent_final(), 0); +} + +/// The same from a `CREATE` frame: the frame fails and returns the zero address, the transaction +/// around it goes through, and the state gas the frame took upfront is back. +#[test] +fn test_a_create_frame_rejected_for_its_first_byte_draws_no_state_gas() { + let init_code = depositing_an_ef_byte(); + // `CREATE` pops value, offset and length in that order, so they are pushed the other way + // round; the assertion that follows halts the frame unless the created address is zero. + let factory = BytecodeBuilder::default() + .mstore(0, &init_code) + .push_number(init_code.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .assert_stack_value(0, U256::ZERO) + .stop() + .build(); + let spent = spend(with_code(factory), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + + assert_eq!(spent.state, 0, "the created account and its byte are both taken back"); +} + /// A creation that deposits nothing — empty runtime code — still pays for the account it /// created, and nothing for code. #[test] From c456c533503ba1d887e09834e031dd80720a5335 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:51:31 +0800 Subject: [PATCH 124/201] test(satin): measure the EIP-3860 word step on a create transaction The ported row straddled an initcode word at 64 and 65 bytes; it landed as a create with empty init code, which leaves the two-gas word charge pinned as a schedule entry and never as a step a transaction pays. The pair is back: sixty-four bytes is two words, sixty-five is three, and the two lengths also separate the word charge from the calldata token each byte costs. --- crates/mega-evm/tests/satin/schedule.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 0ea0f152d..3a2e1c780 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -105,6 +105,26 @@ fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_g assert_eq!(spent.gas_used - spent.state, 24_000, "the fixed part"); } +/// Init code is transaction data twice over: every byte is a calldata token, and EIP-3860 charges +/// two gas for each 32-byte word of it. Sixty-four bytes of zeros is two words; sixty-five is +/// three, so the word charge steps by two where the token charge steps by four. +#[test] +fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { + let fixed = 24_000; + let token = 4; + let word = 2; + for (len, words) in [(64u64, 2u64), (65, 3)] { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + // Every byte is `STOP`, so the init code deposits nothing and costs nothing to run. + let spent = spend(db, create(CALLER, Bytes::from(vec![0u8; len as usize]), GAS_LIMIT)); + assert_eq!( + spent.gas_used - spent.state, + fixed + token * len + word * words, + "{len} bytes of init code" + ); + } +} + /* ---------- the state entries ---------- */ /// A slot's first write to a non-zero value draws the slot's state gas; writing it again does From bbca057900f3fd322ec235ef6ea0ccaf424c2cd0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:53:53 +0800 Subject: [PATCH 125/201] docs(evm): count tx_create_cost among the creation entries EIP-8037 moved four entries onto the state dimension, not three: the earlier wording left tx_create_cost out of the group and named it only afterwards, as though it belonged to the access repricing. --- crates/mega-evm/src/evm/schedule.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 254c0909c..877b51960 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -11,7 +11,7 @@ //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than //! Glamsterdam's. //! -//! The first group includes the three entries EIP-8037 moved onto the state dimension, so at these +//! The first group includes the four entries EIP-8037 moved onto the state dimension, so at these //! prices state creation is charged on both dimensions: a value `CALL` that creates its recipient //! pays 25,000 regular and 183,600 state, a `CREATE` opcode 32,000 and 183,600, a slot's first //! write 22,100 and 97,920, where the Amsterdam schedule charges 0, 12,000 and 12,100 regular @@ -38,15 +38,15 @@ use crate::evm::prices::{active_satin_prices, SatinPrices}; /// /// Amsterdam moves them for two reasons. EIP-8038 raises the price of *reaching* state — a cold /// account, a cold slot, a storage write. EIP-8037 lowers the regular price of *creating* state, -/// having moved that charge onto the state dimension: `new_account_cost`, `create` and -/// `sstore_set_without_load_cost` are that group. Satin takes neither move, so state creation -/// keeps its Osaka regular price on top of the state charge at -/// [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE); the module documentation puts -/// numbers on what that costs. The list is named for EIP-8038 because that is the repricing it -/// was drawn up against. +/// having moved that charge onto the state dimension; `new_account_cost`, `create`, +/// `tx_create_cost` and `sstore_set_without_load_cost` are that second group. Satin takes neither +/// move, so state creation keeps its Osaka regular price on top of the state charge at +/// [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE). The list is named for EIP-8038 +/// because that is the repricing it was drawn up against. /// -/// `tx_create_cost` is priced here and read nowhere: under EIP-2780 the intrinsic phase charges a -/// creation through `tx_create_access_cost`, so pressing this entry back moves no transaction. +/// `tx_create_cost` is the one of those four that prices nothing: under EIP-2780 the intrinsic +/// phase charges a creation through `tx_create_access_cost`, so pressing it back moves no +/// transaction. What the other three cost is in the module documentation. /// /// The entries Amsterdam introduced for EIP-8037's state gas, EIP-2780, EIP-7976, EIP-7981 and /// EIP-7702 are not in this list and keep their Amsterdam values, even where the number itself is From b4d3cb6185f95318d65f2d8841298243f70af4a2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:56:49 +0800 Subject: [PATCH 126/201] docs: make the byte-price guard a review rule A state-gas assertion without it passes every run but the measurement one, which is the run nobody watches. --- REVIEW.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/REVIEW.md b/REVIEW.md index d024042d7..71cb5e3e5 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -61,6 +61,9 @@ This is the single most important correctness concern in mega-evm. These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. - `crates/mega-evm/tests/satin/pricing-table.md` is generated by its own test, not written by hand. A change that moves a number in it must regenerate the file (`UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin`) and explain the movement; a hand-edited row hides the change it was meant to surface. +- A test that asserts one of the spec's own byte-price numbers must return early when the process runs at other prices (`runs_at_measurement_prices`). + A measurement build fixes other prices through the `satin-price-override` feature, and a test without the guard fails there on a price the developer asked for. + Flag a new state-gas assertion that lacks it: the failure only shows in the configuration nobody watches. - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. Missing the required explicit hardfork pin can silently bench the wrong fork when a shared bench subject defaults to a different one. From f753e24ce2582eee295874f05ed26dced0a7e912 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:56:52 +0800 Subject: [PATCH 127/201] test(evm): pin that a block-hash record with a read is not empty The diff-scoped mutation gate found one survivor: every assertion on the record's `is_empty` expected `true`, so a version that always answers `true` passed them all. --- crates/mega-evm/src/evm/state.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs index c61e0533f..fed6d1b4c 100644 --- a/crates/mega-evm/src/evm/state.rs +++ b/crates/mega-evm/src/evm/state.rs @@ -58,6 +58,7 @@ mod tests { record.record(1, B256::ZERO); record.record(2, B256::from([2_u8; 32])); + assert!(!record.is_empty(), "a record that holds a read is not empty"); assert_eq!(record.hashes().len(), 2); assert_eq!(record.hashes().get(&1), Some(&B256::ZERO)); assert_eq!(record.hashes().get(&2), Some(&B256::from([2_u8; 32]))); From b1926a8047cdf4fb2a535fd873c63b83edef5959 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 11:59:18 +0800 Subject: [PATCH 128/201] test(evm): report the child probe's stderr when it fails The probe runs with --nocapture, so its panic message goes to stderr and the parent was printing stdout alone. --- crates/mega-evm/src/evm/prices.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index b81338be9..eff2c8ce1 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -423,7 +423,9 @@ mod tests { .output() .expect("the test binary runs"); let stdout = String::from_utf8_lossy(&run.stdout); - assert!(run.status.success(), "the probe failed:\n{stdout}"); + // The probe runs with `--nocapture`, so its panic message is on stderr and nowhere else. + let stderr = String::from_utf8_lossy(&run.stderr); + assert!(run.status.success(), "the probe failed:\n{stdout}\n{stderr}"); assert!( stdout.contains("sstore_set_state_gas = 20000"), "the probe must report the repriced entry; a run that selected no test reports \ From 70578fe1c25201dd0e75435daf8c1857d10b8c06 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:07:58 +0800 Subject: [PATCH 129/201] feat(system): carry the six system contracts' addresses, code and code hashes Each system contract gets a module with the address, the code and the code hash the mega-system-contracts crate ships, and its ABI. A test hashes every contract's code and compares it to the pinned hash, so a Solidity change that moves a hash is visible here. --- crates/mega-evm/src/system/control.rs | 30 +++++++ crates/mega-evm/src/system/keyless/mod.rs | 28 +++++-- crates/mega-evm/src/system/limit_control.rs | 19 +++++ crates/mega-evm/src/system/mod.rs | 78 ++++++++++++++++++- crates/mega-evm/src/system/oracle.rs | 19 +++++ .../mega-evm/src/system/sequencer_registry.rs | 23 ++++++ crates/mega-evm/src/system/timestamp.rs | 19 +++++ 7 files changed, 207 insertions(+), 9 deletions(-) create mode 100644 crates/mega-evm/src/system/control.rs create mode 100644 crates/mega-evm/src/system/limit_control.rs create mode 100644 crates/mega-evm/src/system/oracle.rs create mode 100644 crates/mega-evm/src/system/sequencer_registry.rs create mode 100644 crates/mega-evm/src/system/timestamp.rs diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs new file mode 100644 index 000000000..3aee4575f --- /dev/null +++ b/crates/mega-evm/src/system/control.rs @@ -0,0 +1,30 @@ +//! The `MegaAccessControl` system contract. +//! +//! It switches volatile-data access off and on for the calling frame and the frames below it, +//! and reports whether it is off. Its methods are intercepted: the deployed bytecode only +//! carries the ABI and reverts with `NotIntercepted()`. Its Solidity source is +//! `crates/system-contracts/contracts/MegaAccessControl.sol`. + +use alloy_primitives::{address, Address}; +use alloy_sol_types::SolError; + +/// The address of the `MegaAccessControl` system contract. +pub const ACCESS_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000004"); + +/// The code of the `MegaAccessControl` contract. +pub use mega_system_contracts::access_control::LATEST_CODE as ACCESS_CONTROL_CODE; + +/// The code hash of the `MegaAccessControl` contract. +pub use mega_system_contracts::access_control::LATEST_CODE_HASH as ACCESS_CONTROL_CODE_HASH; + +pub use mega_system_contracts::access_control::IMegaAccessControl; +pub use IMegaAccessControl::VolatileDataAccessType; + +/// The revert data of `DisabledByParent()`: the answer to a frame that tries to switch +/// volatile-data access back on after a frame above it switched it off. +pub const DISABLED_BY_PARENT_REVERT_DATA: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; + +/// The selector of `VolatileDataAccessDisabled(uint8)`, the error a volatile read reverts with +/// while access is off. +pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = + IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 875ba7aa7..22f445e92 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -1,13 +1,29 @@ -//! Keyless deployment (Nick's Method): the transaction format, its validation rules and the -//! error ABI. +//! The `KeylessDeploy` system contract, and keyless deployment (Nick's Method): the transaction +//! format, its validation rules and the error ABI. //! -//! These are data-only helpers: decoding the pre-EIP-155 transaction, recovering its signer, -//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. The -//! interceptor that dispatches `keylessDeploy` calls and the deployment as a native CREATE -//! sub-frame are not here yet. +//! `keylessDeploy(bytes,uint64)` is intercepted; every other selector falls through to the +//! deployed bytecode, which reverts with `NotIntercepted()`. What the interceptor does today is +//! the dispatch and the fixed compute charge; turning the deployment into a native creation +//! belongs to native keyless deployment. +//! +//! The rest of the module is data-only: decoding the pre-EIP-155 transaction, recovering its +//! signer, deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. mod error; mod tx; pub use error::*; pub use tx::*; + +use alloy_primitives::{address, Address}; + +/// The address of the `KeylessDeploy` system contract. +pub const KEYLESS_DEPLOY_ADDRESS: Address = address!("0x6342000000000000000000000000000000000003"); + +/// The code of the `KeylessDeploy` contract. +pub use mega_system_contracts::keyless_deploy::LATEST_CODE as KEYLESS_DEPLOY_CODE; + +/// The code hash of the `KeylessDeploy` contract. +pub use mega_system_contracts::keyless_deploy::LATEST_CODE_HASH as KEYLESS_DEPLOY_CODE_HASH; + +pub use mega_system_contracts::keyless_deploy::IKeylessDeploy; diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs new file mode 100644 index 000000000..aa81e4271 --- /dev/null +++ b/crates/mega-evm/src/system/limit_control.rs @@ -0,0 +1,19 @@ +//! The `MegaLimitControl` system contract. +//! +//! It answers what the running call has left of the resources `MegaETH` meters; today that is +//! `remainingComputeGas()`. Its methods are intercepted: the deployed bytecode only carries the +//! ABI and reverts with `NotIntercepted()`. Its Solidity source is +//! `crates/system-contracts/contracts/MegaLimitControl.sol`. + +use alloy_primitives::{address, Address}; + +/// The address of the `MegaLimitControl` system contract. +pub const LIMIT_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000005"); + +/// The code of the `MegaLimitControl` contract. +pub use mega_system_contracts::limit_control::LATEST_CODE as LIMIT_CONTROL_CODE; + +/// The code hash of the `MegaLimitControl` contract. +pub use mega_system_contracts::limit_control::LATEST_CODE_HASH as LIMIT_CONTROL_CODE_HASH; + +pub use mega_system_contracts::limit_control::IMegaLimitControl; diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index e046b0c6a..85be4143e 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -1,6 +1,78 @@ -//! System contracts of the Satin engine. +//! The system contracts of the Satin engine. //! -//! Filled when the interceptor dispatch, the deployment at activation and the oracle and control -//! contracts land. For now it holds only the keyless-deployment data helpers. +//! Six contracts live at fixed addresses under `0x6342…`: the [`Oracle`](oracle), +//! the [`High-Precision Timestamp`](timestamp) wrapper, [`KeylessDeploy`](keyless), +//! [`MegaAccessControl`](control), [`MegaLimitControl`](limit_control) and the +//! [`SequencerRegistry`](sequencer_registry). Each module carries its address, the code and code +//! hash the `mega-system-contracts` crate ships, and its ABI. +//! +//! Four of them have an interceptor: a `CALL` or `STATICCALL` to one of their intercepted +//! selectors is answered by the engine instead of by the contract's code. The timestamp wrapper +//! and the `SequencerRegistry` run their bytecode. +//! +//! Deploying the contracts at the fork that activates them belongs to system contract +//! deployment; it is not here. pub mod keyless; + +mod control; +mod limit_control; +mod oracle; +mod sequencer_registry; +mod timestamp; + +pub use control::*; +pub use limit_control::*; +pub use oracle::*; +pub use sequencer_registry::*; +pub use timestamp::*; + +#[cfg(test)] +mod tests { + use super::{keyless::*, *}; + use alloy_primitives::{keccak256, Address, Bytes, B256}; + + /// Every system contract, as `(address, code, code hash)`. + fn system_contracts() -> [(Address, Bytes, B256); 6] { + [ + (ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, ORACLE_CONTRACT_CODE_HASH), + ( + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + ), + (KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH), + (ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ACCESS_CONTROL_CODE_HASH), + (LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, LIMIT_CONTROL_CODE_HASH), + (SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_HASH), + ] + } + + /// The code hash of every contract is the hash of the code it ships with: Satin deploys the + /// contracts as they are, so a Solidity change that moved a hash shows up here. + #[test] + fn test_every_system_contract_code_hashes_to_its_pinned_hash() { + for (address, code, hash) in system_contracts() { + assert!(!code.is_empty(), "{address} has no code"); + assert_eq!(keccak256(&code), hash, "the code hash of {address} moved"); + } + } + + /// The six addresses are the six of the `0x6342…` range, each used once. + #[test] + fn test_the_system_contract_addresses_are_the_pinned_ones() { + let addresses: [Address; 6] = core::array::from_fn(|i| system_contracts()[i].0); + assert_eq!( + addresses.map(|address| address.to_string()), + [ + "0x6342000000000000000000000000000000000001", + "0x6342000000000000000000000000000000000002", + "0x6342000000000000000000000000000000000003", + "0x6342000000000000000000000000000000000004", + "0x6342000000000000000000000000000000000005", + "0x6342000000000000000000000000000000000006", + ] + .map(str::to_string), + ); + } +} diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs new file mode 100644 index 000000000..2e52355f7 --- /dev/null +++ b/crates/mega-evm/src/system/oracle.rs @@ -0,0 +1,19 @@ +//! The Oracle system contract. +//! +//! The Oracle holds the protocol's key-value storage (`getSlot` / `setSlot`) and is the surface +//! through which a contract reaches the node's oracle service: `sendHint` carries a message to +//! the service backend. Its Solidity source is +//! `crates/system-contracts/contracts/Oracle.sol`. + +use alloy_primitives::{address, Address}; + +/// The address of the Oracle system contract. +pub const ORACLE_CONTRACT_ADDRESS: Address = address!("0x6342000000000000000000000000000000000001"); + +/// The code of the Oracle contract. +pub use mega_system_contracts::oracle::LATEST_CODE as ORACLE_CONTRACT_CODE; + +/// The code hash of the Oracle contract. +pub use mega_system_contracts::oracle::LATEST_CODE_HASH as ORACLE_CONTRACT_CODE_HASH; + +pub use mega_system_contracts::oracle::IOracle; diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs new file mode 100644 index 000000000..83dfa20a6 --- /dev/null +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -0,0 +1,23 @@ +//! The `SequencerRegistry` system contract. +//! +//! It holds the two rotating roles of the chain — the system address and the sequencer — and +//! their change schedules. It runs its own bytecode: no method of it is intercepted, so a call +//! to it is an ordinary call. Its Solidity source is +//! `crates/system-contracts/contracts/SequencerRegistry.sol`. +//! +//! Reading the rotated system address out of its storage, and the pre-block call that applies a +//! due change, belong to system contract deployment and the pre-block system calls. + +use alloy_primitives::{address, Address}; + +/// The address of the `SequencerRegistry` system contract. +pub const SEQUENCER_REGISTRY_ADDRESS: Address = + address!("0x6342000000000000000000000000000000000006"); + +/// The code of the `SequencerRegistry` contract. +pub use mega_system_contracts::sequencer_registry::LATEST_CODE as SEQUENCER_REGISTRY_CODE; + +/// The code hash of the `SequencerRegistry` contract. +pub use mega_system_contracts::sequencer_registry::LATEST_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH; + +pub use mega_system_contracts::sequencer_registry::ISequencerRegistry; diff --git a/crates/mega-evm/src/system/timestamp.rs b/crates/mega-evm/src/system/timestamp.rs new file mode 100644 index 000000000..ed1949b02 --- /dev/null +++ b/crates/mega-evm/src/system/timestamp.rs @@ -0,0 +1,19 @@ +//! The High-Precision Timestamp system contract. +//! +//! A thin wrapper that reads a microsecond-resolution timestamp out of the Oracle's storage. +//! It runs its own bytecode: no method of it is intercepted, so a call to it is an ordinary +//! call. The Oracle's address is baked into the code, which is why the code is carried here +//! rather than built from the `mega-system-contracts` sources. + +use alloy_primitives::{address, b256, bytes, Address, Bytes, B256}; + +/// The address of the High-Precision Timestamp system contract. +pub const HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS: Address = + address!("0x6342000000000000000000000000000000000002"); + +/// The code hash of the High-Precision Timestamp contract. +pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH: B256 = + b256!("0x1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2"); + +/// The code of the High-Precision Timestamp contract, with the Oracle's address embedded. +pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE: Bytes = bytes!("0x608060405234801561000f575f5ffd5b5060043610610064575f3560e01c806382ab890a1161004d57806382ab890a146100f55780638582b7bc1461010a578063b80777ea1461013f575f5ffd5b806328af7f3c146100685780633e6890fb146100a9575b5f5ffd5b61008f7f000000000000000000000000000000000000000000000000000000000000000881565b60405163ffffffff90911681526020015b60405180910390f35b6100d07f000000000000000000000000634200000000000000000000000000000000000181565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100a0565b6101086101033660046103b6565b610147565b005b6101317f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016100a0565b610131610154565b6101515f82610165565b50565b5f5f61015f5f610245565b92915050565b8161016f8161031a565b73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000063420000000000000000000000000000000000011663fbc0d0356101d5857f00000000000000000000000000000000000000000000000000000000000000006103cd565b60405160e083901b7fffffffff000000000000000000000000000000000000000000000000000000001681526004810191909152602481018590526044015f604051808303815f87803b15801561022a575f5ffd5b505af115801561023c573d5f5f3e3d5ffd5b50505050505050565b5f816102508161031a565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000634200000000000000000000000000000000000116637eba7ba66102b6857f00000000000000000000000000000000000000000000000000000000000000006103cd565b6040518263ffffffff1660e01b81526004016102d491815260200190565b602060405180830381865afa1580156102ef573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103139190610405565b9392505050565b63ffffffff7f00000000000000000000000000000000000000000000000000000000000000081661034c8260016103cd565b10610151576040517fef94d8420000000000000000000000000000000000000000000000000000000081526004810182905263ffffffff7f000000000000000000000000000000000000000000000000000000000000000816602482015260440160405180910390fd5b5f602082840312156103c6575f5ffd5b5035919050565b8082018082111561015f577f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f60208284031215610415575f5ffd5b505191905056fea2646970667358221220290614c973d24b9016b73a6b3fa98b2485a5c324199ceeb767818495dbe785e864736f6c634300081e0033"); From 3b8da830ed905960350a8e3fb9d4bf83f51318c2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:09:09 +0800 Subject: [PATCH 130/201] feat(external): cache the SALT bucket multipliers of a transaction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Accounts and storage slots live in SALT buckets, and a bucket's capacity in minimum buckets is the multiplier every EIP-8037 state gas charge on it is scaled by. BucketMultipliers turns a capacity into that multiplier and caches it, so a bucket is read from the SALT environment once per transaction and every later charge on it is answered without touching the database. The cache lives on MegaContext next to the common execution layer's state and is cleared with it at every entry point, so a transaction never prices against a capacity an earlier one read. account_bucket_multiplier and slot_bucket_multiplier are what the pricing hook will ask. A capacity below the minimum — which a bucket cannot have — prices at one rather than at zero, so no environment can make state gas free. The test environment grows two knobs the pricing tests need: a bucket whose capacity query fails, and a count of the queries each bucket received. --- crates/mega-evm/src/evm/context.rs | 70 ++++++- crates/mega-evm/src/external/gas.rs | 224 +++++++++++++++++++++ crates/mega-evm/src/external/mod.rs | 6 + crates/mega-evm/src/external/test_utils.rs | 44 +++- 4 files changed, 339 insertions(+), 5 deletions(-) create mode 100644 crates/mega-evm/src/external/gas.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index d842b5ec6..afd1a3294 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -4,12 +4,14 @@ use delegate::delegate; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, + primitives::{Address, StorageKey}, Database, Journal, }; use crate::{ - constants, evm::schedule::satin_gas_params, AdditionalLimit, BlockHashRecord, EmptyExternalEnv, - EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, + constants, evm::schedule::satin_gas_params, AdditionalLimit, BlockHashRecord, + BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, + MegaSpecId, MegaTransaction, SaltEnv, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -27,7 +29,8 @@ pub(crate) type MegaInnerContext = /// Every context accessor delegates to the wrapped context, and so does every /// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing /// opcode did (see the `host` module). It also carries the common execution layer's state for the -/// running transaction ([`AdditionalLimit`]). +/// running transaction ([`AdditionalLimit`]) and the SALT bucket multipliers that transaction has +/// priced state gas with ([`BucketMultipliers`]). #[derive(Debug)] pub struct MegaContext { pub(crate) inner: MegaInnerContext, @@ -35,6 +38,8 @@ pub struct MegaContext, pub(crate) additional_limit: AdditionalLimit, pub(crate) block_hash_record: BlockHashRecord, + /// The SALT bucket multipliers the running transaction has read. + bucket_multipliers: BucketMultipliers, } impl MegaContext { @@ -59,6 +64,7 @@ impl MegaContext { external_envs, additional_limit: AdditionalLimit::default(), block_hash_record: BlockHashRecord::default(), + bucket_multipliers: BucketMultipliers::default(), } } @@ -146,10 +152,43 @@ impl MegaContext { &mut self.additional_limit } + /// The SALT bucket multiplier of the account `address`'s own state lives in: the capacity of + /// its bucket in minimum buckets, never below one. + /// + /// Every account-scoped EIP-8037 state gas charge on `address` is scaled by it. The bucket is + /// read from the transaction's [`SaltEnv`] the first time the transaction asks for it and + /// from [`BucketMultipliers`] afterwards. + pub fn account_bucket_multiplier( + &mut self, + address: Address, + ) -> Result::Error> { + self.bucket_multipliers.account(&self.external_envs.salt_env, address) + } + + /// The SALT bucket multiplier of the slot `key` of `address`, which scales every slot-scoped + /// EIP-8037 state gas charge on it. See + /// [`account_bucket_multiplier`](Self::account_bucket_multiplier). + pub fn slot_bucket_multiplier( + &mut self, + address: Address, + key: StorageKey, + ) -> Result::Error> { + self.bucket_multipliers.slot(&self.external_envs.salt_env, address, key) + } + + /// The SALT bucket multipliers the running (or last) transaction read. + pub const fn bucket_multipliers(&self) -> &BucketMultipliers { + &self.bucket_multipliers + } + /// Prepares the common execution layer for a new transaction or system call. Every entry /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. + /// + /// The SALT bucket multipliers go with it: they are what one transaction read, so the next + /// one reads its own. pub(crate) fn on_new_tx(&mut self) { self.additional_limit.reset(); + self.bucket_multipliers.reset(); } /// Consumes the context and returns the database, the configuration and the block. @@ -389,6 +428,31 @@ mod tests { assert_eq!(ctx.chain().l2_block, Some(U256::from(42))); } + /// The multipliers a transaction read belong to it: the next transaction reads the capacity + /// again, so a bucket that grew between two transactions is priced at what it holds now. + #[test] + fn test_the_bucket_multipliers_are_forgotten_between_transactions() { + const ACCOUNT: alloy_primitives::Address = + alloy_primitives::address!("00000000000000000000000000000000000000a1"); + let bucket = ::bucket_id_for_account(ACCOUNT); + let env = TestExternalEnvs::::new() + .with_bucket_capacity(bucket, crate::MIN_BUCKET_SIZE as u64 * 4); + let mut ctx = MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs::from(env.clone()), + ); + + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); + assert_eq!(env.bucket_queries(bucket), 1, "the second charge came from the cache"); + + ctx.on_new_tx(); + assert_eq!(ctx.bucket_multipliers().cached_buckets().len(), 0); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); + assert_eq!(env.bucket_queries(bucket), 2, "the next transaction read it again"); + } + /// The external environments given at construction are the ones the context exposes. #[test] fn test_new_with_ext_envs_builds_over_configurable_env() { diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs new file mode 100644 index 000000000..564f15900 --- /dev/null +++ b/crates/mega-evm/src/external/gas.rs @@ -0,0 +1,224 @@ +//! The SALT bucket multipliers one transaction prices with. +//! +//! `MegaETH` keeps accounts and storage slots in SALT buckets. A bucket holds at least +//! [`MIN_BUCKET_SIZE`] entries and grows as the region fills up; the ratio between what it holds +//! and that minimum is the *multiplier* every EIP-8037 state gas charge on an account or slot of +//! that bucket is scaled by. A charge in a minimum-capacity bucket pays the schedule price, and +//! one in a bucket eight times as large pays eight times as much. +//! +//! Capacities are read through the transaction's [`SaltEnv`], which is a database read. The hook +//! that prices state gas runs on every state charge and every refill of one, so the reads are +//! cached here: [`BucketMultipliers`] queries a bucket once per transaction and answers every +//! later charge on that bucket from the cache. + +use alloy_primitives::{map::Entry, Address}; +use revm::primitives::{HashMap, StorageKey}; + +use crate::{BucketId, SaltEnv, MIN_BUCKET_SIZE}; + +/// The SALT bucket multipliers the running transaction has looked up. +/// +/// One entry per bucket the transaction has priced a charge in. It is cleared with the rest of +/// the per-transaction state at every entry point of [`MegaEvm`](crate::MegaEvm), so a +/// transaction never prices against a capacity an earlier transaction read. +/// +/// The environment is passed in rather than held, so the cache adds no second copy of it and +/// puts no `Clone` bound on the engine's external environment types. +#[derive(Clone, Debug, Default)] +pub struct BucketMultipliers { + /// Bucket id to its multiplier, for the buckets this transaction has read. + cached: HashMap, +} + +impl BucketMultipliers { + /// Forgets what the last transaction read, keeping the allocation. + #[inline] + pub(crate) fn reset(&mut self) { + self.cached.clear(); + } + + /// The multiplier a bucket of `capacity` entries prices with: `capacity / MIN_BUCKET_SIZE`, + /// never below one. + /// + /// A bucket cannot hold fewer entries than the minimum, so the floor only guards against an + /// environment that reports one that does: without it such a report would price every state + /// charge in that bucket at zero, which is the one answer that must not be reachable from + /// outside the engine. + #[inline] + pub const fn for_capacity(capacity: u64) -> u64 { + let multiplier = capacity / MIN_BUCKET_SIZE as u64; + if multiplier == 0 { + 1 + } else { + multiplier + } + } + + /// The multiplier of the bucket `account`'s own state lives in. + #[inline] + pub fn account(&mut self, salt_env: &S, account: Address) -> Result { + self.of_bucket(salt_env, S::bucket_id_for_account(account)) + } + + /// The multiplier of the bucket the slot `key` of `address` lives in. + #[inline] + pub fn slot( + &mut self, + salt_env: &S, + address: Address, + key: StorageKey, + ) -> Result { + self.of_bucket(salt_env, S::bucket_id_for_slot(address, key)) + } + + /// The multiplier of `bucket`, read from `salt_env` the first time this transaction asks for + /// it and from the cache afterwards. + #[inline] + fn of_bucket(&mut self, salt_env: &S, bucket: BucketId) -> Result { + match self.cached.entry(bucket) { + Entry::Occupied(entry) => Ok(*entry.get()), + Entry::Vacant(entry) => { + let multiplier = Self::for_capacity(salt_env.get_bucket_capacity(bucket)?); + Ok(*entry.insert(multiplier)) + } + } + } + + /// The buckets this transaction has read, for tests and tools that check the read set. + #[cfg(any(test, feature = "test-utils"))] + pub fn cached_buckets(&self) -> impl ExactSizeIterator + '_ { + self.cached.keys().copied() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{TestExternalEnvs, MIN_BUCKET_SIZE}; + use alloy_primitives::{address, U256}; + + const ACCOUNT: Address = address!("00000000000000000000000000000000000000a1"); + const OTHER: Address = address!("00000000000000000000000000000000000000a2"); + + type Env = TestExternalEnvs; + + fn account_bucket(account: Address) -> BucketId { + ::bucket_id_for_account(account) + } + + fn slot_bucket(address: Address, key: StorageKey) -> BucketId { + ::bucket_id_for_slot(address, key) + } + + /// A bucket at the minimum capacity multiplies by one, so the schedule's own price stands. + #[test] + fn test_the_minimum_bucket_multiplies_by_one() { + let env = Env::new(); + let mut cache = BucketMultipliers::default(); + + assert_eq!(cache.account(&env, ACCOUNT), Ok(1)); + assert_eq!(cache.slot(&env, ACCOUNT, U256::ZERO), Ok(1)); + } + + /// The multiplier is the capacity in minimum buckets, over the range a capacity can take. + #[test] + fn test_the_multiplier_is_the_capacity_in_minimum_buckets() { + let min = MIN_BUCKET_SIZE as u64; + for factor in [1, 2, 8, 1_000, u32::MAX as u64] { + assert_eq!(BucketMultipliers::for_capacity(min * factor), factor, "{factor}x"); + } + // A capacity between two whole multiples rounds down to the lower one: a bucket pays for + // the minimum buckets it has filled, not for the one it has started. + assert_eq!(BucketMultipliers::for_capacity(min * 2 + min / 2), 2); + assert_eq!(BucketMultipliers::for_capacity(u64::MAX), u64::MAX / min); + } + + /// A capacity below the minimum — which a bucket cannot have — still prices at one rather + /// than at zero, so no environment can make state gas free. + #[test] + fn test_a_capacity_below_the_minimum_still_multiplies_by_one() { + for capacity in [0, 1, MIN_BUCKET_SIZE as u64 - 1] { + assert_eq!(BucketMultipliers::for_capacity(capacity), 1, "capacity {capacity}"); + } + + let bucket = account_bucket(ACCOUNT); + let env = Env::new().with_bucket_capacity(bucket, 0); + assert_eq!(BucketMultipliers::default().account(&env, ACCOUNT), Ok(1)); + } + + /// A crowded bucket scales every charge on it, and an account and a slot are read through + /// their own buckets. + #[test] + fn test_a_crowded_bucket_scales_the_account_and_the_slot_separately() { + let min = MIN_BUCKET_SIZE as u64; + let env = Env::new() + .with_bucket_capacity(account_bucket(ACCOUNT), min * 8) + .with_bucket_capacity(slot_bucket(ACCOUNT, U256::ZERO), min * 2); + let mut cache = BucketMultipliers::default(); + + assert_eq!(cache.account(&env, ACCOUNT), Ok(8)); + assert_eq!(cache.slot(&env, ACCOUNT, U256::ZERO), Ok(2)); + // A slot of the same account in another bucket is untouched by either. + assert_eq!(cache.slot(&env, ACCOUNT, U256::from(1)), Ok(1)); + // So is another account. + assert_eq!(cache.account(&env, OTHER), Ok(1)); + } + + /// A bucket is read from the environment once; every later charge on it is answered from the + /// cache. This is what keeps the pricing hook off the database on the hot path. + #[test] + fn test_a_bucket_is_read_once_and_cached() { + let bucket = account_bucket(ACCOUNT); + let env = Env::new().with_bucket_capacity(bucket, MIN_BUCKET_SIZE as u64 * 4); + let mut cache = BucketMultipliers::default(); + + for _ in 0..8 { + assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); + } + assert_eq!(env.bucket_queries(bucket), 1, "one capacity query for eight charges"); + assert_eq!(cache.cached_buckets().collect::>(), vec![bucket]); + } + + /// The cache belongs to one transaction: a reset forgets it, and the next transaction reads + /// the capacity again. + #[test] + fn test_a_reset_forgets_what_the_transaction_read() { + let bucket = account_bucket(ACCOUNT); + let env = Env::new().with_bucket_capacity(bucket, MIN_BUCKET_SIZE as u64 * 4); + let mut cache = BucketMultipliers::default(); + + assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); + cache.reset(); + assert_eq!(cache.cached_buckets().len(), 0, "the reset emptied the cache"); + assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); + assert_eq!(env.bucket_queries(bucket), 2, "one query per transaction"); + } + + /// A failed capacity query is reported, not swallowed: the caller must fail the transaction + /// rather than price the charge at some other number. + #[test] + fn test_a_failed_capacity_query_is_reported() { + let bucket = account_bucket(ACCOUNT); + let env = TestExternalEnvs::::new() + .with_failing_bucket(bucket, "salt backend unreachable".into()); + let mut cache = BucketMultipliers::default(); + + assert_eq!(cache.account(&env, ACCOUNT), Err("salt backend unreachable".into())); + assert_eq!(cache.cached_buckets().len(), 0, "a failed lookup caches nothing"); + // It is not cached either, so the next charge asks again. + assert!(cache.account(&env, ACCOUNT).is_err()); + assert_eq!(env.bucket_queries(bucket), 2); + } + + /// One bucket failing does not stop another from being priced. + #[test] + fn test_only_the_failing_bucket_fails() { + let env = TestExternalEnvs::::new() + .with_bucket_capacity(account_bucket(OTHER), MIN_BUCKET_SIZE as u64 * 2) + .with_failing_bucket(account_bucket(ACCOUNT), "unreachable".into()); + let mut cache = BucketMultipliers::default(); + + assert!(cache.account(&env, ACCOUNT).is_err()); + assert_eq!(cache.account(&env, OTHER), Ok(2)); + } +} diff --git a/crates/mega-evm/src/external/mod.rs b/crates/mega-evm/src/external/mod.rs index e0b6c4277..3094575ea 100644 --- a/crates/mega-evm/src/external/mod.rs +++ b/crates/mega-evm/src/external/mod.rs @@ -4,6 +4,10 @@ //! - **SALT**: Bucket capacity information for dynamic gas pricing //! - **Oracle**: Storage from the `MegaETH` oracle contract //! +//! [`BucketMultipliers`] is what execution reads the SALT side through: it turns the capacities +//! [`SaltEnv`] reports into the multipliers EIP-8037 state gas is scaled by, and caches them for +//! the running transaction. +//! //! # Architecture //! //! External environments follow a factory pattern: @@ -19,6 +23,7 @@ use auto_impl::auto_impl; use core::fmt::Debug; mod factory; +mod gas; #[cfg(any(test, feature = "test-utils"))] mod hasher; mod oracle; @@ -27,6 +32,7 @@ mod salt; mod test_utils; pub use factory::*; +pub use gas::*; #[cfg(any(test, feature = "test-utils"))] pub use hasher::*; pub use oracle::*; diff --git a/crates/mega-evm/src/external/test_utils.rs b/crates/mega-evm/src/external/test_utils.rs index 04da5bb0d..53b02f404 100644 --- a/crates/mega-evm/src/external/test_utils.rs +++ b/crates/mega-evm/src/external/test_utils.rs @@ -107,6 +107,13 @@ pub struct TestExternalEnvs { /// Fallback capacity for buckets not in `bucket_capacity`. /// When `None`, falls back to [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). default_bucket_capacity: Rc>>, + /// Buckets whose capacity query fails, with the error it fails with. Lets a test drive the + /// pricing hook's failure path, where a state gas charge cannot be priced at all. + #[debug(ignore)] + failing_buckets: Rc>>, + /// How many times [`SaltEnv::get_bucket_capacity`] was called per bucket, so a test can + /// assert the engine reads a bucket once and answers later charges from its own cache. + bucket_queries: Rc>>, /// Recorded hints from `on_hint` calls. Used for testing the hint mechanism. recorded_hints: Rc>>, } @@ -143,6 +150,8 @@ impl oracle_storage: Rc::new(RefCell::new(HashMap::default())), bucket_capacity: Rc::new(RefCell::new(HashMap::default())), default_bucket_capacity: Rc::new(RefCell::new(None)), + failing_buckets: Rc::new(RefCell::new(HashMap::default())), + bucket_queries: Rc::new(RefCell::new(HashMap::default())), recorded_hints: Rc::new(RefCell::new(Vec::new())), } } @@ -193,6 +202,31 @@ impl self.bucket_capacity.borrow_mut().clear(); } + /// Makes the capacity query of `bucket_id` fail with `error`, whatever capacity it carries. + /// + /// This is what an unreachable SALT backend looks like to the engine: the state gas charge + /// on an account or slot of that bucket cannot be priced, so the transaction fails instead + /// of falling back to a price nobody chose. + pub fn with_failing_bucket(self, bucket_id: BucketId, error: Error) -> Self { + self.failing_buckets.borrow_mut().insert(bucket_id, error); + self + } + + /// How many capacity queries `bucket_id` has received. + pub fn bucket_queries(&self, bucket_id: BucketId) -> u32 { + self.bucket_queries.borrow().get(&bucket_id).copied().unwrap_or_default() + } + + /// How many capacity queries every bucket has received together. + pub fn total_bucket_queries(&self) -> u32 { + self.bucket_queries.borrow().values().sum() + } + + /// Forgets the capacity queries counted so far. + pub fn clear_bucket_queries(&self) { + self.bucket_queries.borrow_mut().clear(); + } + /// Configures a storage slot in the oracle contract to have a specific value. /// /// # Arguments @@ -242,7 +276,7 @@ impl ExternalEnvFactory } } -impl ExternalEnvTypes +impl ExternalEnvTypes for TestExternalEnvs { type SaltEnv = Self; @@ -258,10 +292,16 @@ const PLAIN_ACCOUNT_KEY_LEN: usize = Address::len_bytes(); const PLAIN_STORAGE_KEY_LEN: usize = PLAIN_ACCOUNT_KEY_LEN + SLOT_KEY_LEN; /// SALT environment implementation with configurable bucket ID hashing. -impl SaltEnv for TestExternalEnvs { +impl SaltEnv + for TestExternalEnvs +{ type Error = Error; fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result { + *self.bucket_queries.borrow_mut().entry(bucket_id).or_default() += 1; + if let Some(error) = self.failing_buckets.borrow().get(&bucket_id) { + return Err(error.clone()); + } Ok(self.bucket_capacity.borrow().get(&bucket_id).copied().unwrap_or_else(|| { self.default_bucket_capacity.borrow().unwrap_or(crate::MIN_BUCKET_SIZE as u64) })) From 5637b682bda901f87a7c221be267c14dad515c5d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:16:07 +0800 Subject: [PATCH 131/201] feat(evm): intercept the two control contracts' calls The interceptor dispatch answers a CALL or STATICCALL to a system contract instead of running its code: the scheme guard refuses CALLCODE and DELEGATECALL, one comparison against the 0x6342 range decides whether an interceptor can be concerned, and the contract's own dispatch peeks the first four bytes of the input without materialising the rest. A selector a contract does not intercept falls through to its bytecode, which reverts with NotIntercepted(). MegaAccessControl and MegaLimitControl answer through it. Both refuse a call that carries value with NonZeroTransfer(), after the selector matched. What the three access-control methods do, and the compute ledger remainingComputeGas will read, belong to detention and to compute gas; until then the interceptors answer what the common execution layer knows. Every answer is a synthetic call result, so it carries the caller's reservoir and settles like a frame revm ran. --- crates/mega-evm/src/evm/execution.rs | 20 +- crates/mega-evm/src/evm/frame.rs | 27 ++- crates/mega-evm/src/system/control.rs | 51 ++++- crates/mega-evm/src/system/intercept.rs | 200 ++++++++++++++++++ crates/mega-evm/src/system/limit_control.rs | 42 +++- crates/mega-evm/src/system/mod.rs | 9 +- crates/mega-evm/tests/system/common.rs | 136 ++++++++++++ crates/mega-evm/tests/system/control.rs | 149 +++++++++++++ crates/mega-evm/tests/system/limit_control.rs | 136 ++++++++++++ crates/mega-evm/tests/system/main.rs | 6 + 10 files changed, 756 insertions(+), 20 deletions(-) create mode 100644 crates/mega-evm/src/system/intercept.rs create mode 100644 crates/mega-evm/tests/system/common.rs create mode 100644 crates/mega-evm/tests/system/control.rs create mode 100644 crates/mega-evm/tests/system/limit_control.rs create mode 100644 crates/mega-evm/tests/system/main.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 223eac2dd..5fddc6332 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -474,14 +474,20 @@ impl MegaEvm { /// System contract interception: a `CALL` or `STATICCALL` to a system contract answered by /// `MegaETH` instead of the contract's code. /// - /// The extension point of the system contract interceptors; nothing is intercepted yet. An - /// answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles like - /// a frame revm ran. - // Takes the EVM mutably: an interceptor reads and writes the context. - #[allow(clippy::needless_pass_by_ref_mut)] + /// The scheme guard is here: `CALLCODE` and `DELEGATECALL` run the callee's code in the + /// caller's context, where a system contract's semantics would apply to the wrong account, + /// so they never reach an interceptor and revm builds their frame as it does for any other + /// contract. A creation reaches no interceptor either. + /// + /// An answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles + /// like a frame revm ran. What each contract answers is in the `system` module. #[inline] - const fn intercept(&mut self, _frame_init: &FrameInit) -> Option { - None + fn intercept(&mut self, frame_init: &FrameInit) -> Option { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; + if !matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { + return None; + } + crate::system::intercept(&mut self.inner.ctx, inputs) } /// The keyless deployment rewrite: a keyless deployment call turned into the native creation diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 3cfc547a3..09d08538d 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -69,14 +69,7 @@ pub fn synthetic_frame_result( output: Bytes, ) -> FrameResult { match input { - FrameInput::Call(inputs) => FrameResult::Call(CallOutcome { - result: InterpreterResult::new(result, output, untouched_call_gas(inputs)), - memory_offset: inputs.return_memory_offset.clone(), - was_precompile_called: false, - precompile_call_logs: Default::default(), - charged_new_account_state_gas: inputs.charged_new_account_state_gas, - charged_state_gas_address: inputs.target_address, - }), + FrameInput::Call(inputs) => synthetic_call_result(inputs, result, output), FrameInput::Create(inputs) => FrameResult::Create(CreateOutcome { result: InterpreterResult::new(result, output, untouched_create_gas(inputs)), address: None, @@ -87,6 +80,24 @@ pub fn synthetic_frame_result( } } +/// A result for the call `inputs` would start, built without running it, as +/// [`synthetic_frame_result`] builds one: for a mechanism that already holds the call's inputs +/// (a system contract interceptor). +pub fn synthetic_call_result( + inputs: &CallInputs, + result: InstructionResult, + output: Bytes, +) -> FrameResult { + FrameResult::Call(CallOutcome { + result: InterpreterResult::new(result, output, untouched_call_gas(inputs)), + memory_offset: inputs.return_memory_offset.clone(), + was_precompile_called: false, + precompile_call_logs: Default::default(), + charged_new_account_state_gas: inputs.charged_new_account_state_gas, + charged_state_gas_address: inputs.target_address, + }) +} + /// Settles `result`'s gas into `caller_gas` exactly as revm's frame return does: the calling /// opcode's upfront state-gas charge priced for refund, [`handle_reservoir_remaining_gas`], then /// the refund refilled into the caller's reservoir. diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 3aee4575f..21043b806 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -5,8 +5,19 @@ //! carries the ABI and reverts with `NotIntercepted()`. Its Solidity source is //! `crates/system-contracts/contracts/MegaAccessControl.sol`. -use alloy_primitives::{address, Address}; -use alloy_sol_types::SolError; +use alloy_evm::Database; +use alloy_primitives::{address, Address, Bytes}; +use alloy_sol_types::{SolCall, SolError}; +use revm::{ + handler::FrameResult, + interpreter::{CallInputs, InstructionResult}, +}; + +use crate::{ + synthetic_call_result, + system::intercept::{peek_selector, reject_non_zero_transfer}, + ExternalEnvTypes, MegaContext, +}; /// The address of the `MegaAccessControl` system contract. pub const ACCESS_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000004"); @@ -28,3 +39,39 @@ pub const DISABLED_BY_PARENT_REVERT_DATA: [u8; 4] = IMegaAccessControl::Disabled /// while access is off. pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; + +/// Answers a call to `MegaAccessControl`, or `None` when the selector is not one of its three +/// and the deployed bytecode runs. +/// +/// # What the three methods do today +/// +/// The switch itself belongs to detention, which brings the tracker that remembers a frame's +/// answer and the volatile reads that consult it. Until then the interceptor is the dispatch +/// and the value policy: `disableVolatileDataAccess` and `enableVolatileDataAccess` succeed and +/// change nothing, and `isVolatileDataAccessDisabled` answers `false`, which is what the common +/// execution layer knows — no frame has ever switched access off. `DisabledByParent()`, the +/// answer to a frame that re-enables what a frame above it disabled, is the tracker's to give. +/// +/// All three take no value: they read or steer execution, and the contract holds no balance. +pub(crate) fn intercept( + ctx: &MegaContext, + inputs: &CallInputs, +) -> Option { + let selector = peek_selector(&inputs.input, ctx)?; + // Selector-only admission: the four bytes decide, whatever follows them. + let output = if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR || + selector == IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR + { + Bytes::new() + } else if selector == IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR { + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false, + )) + } else { + return None; + }; + if let Some(rejected) = reject_non_zero_transfer(inputs) { + return Some(rejected); + } + Some(synthetic_call_result(inputs, InstructionResult::Return, output)) +} diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs new file mode 100644 index 000000000..92df99ae6 --- /dev/null +++ b/crates/mega-evm/src/system/intercept.rs @@ -0,0 +1,200 @@ +//! The interceptor dispatch: which system contract answers a call, and how its answer is built. +//! +//! A `CALL` or `STATICCALL` whose target is a system contract with an interceptor and whose +//! first four bytes name one of that contract's intercepted methods is answered by the engine, +//! before revm builds a frame for it. Everything else runs the contract's own bytecode. +//! +//! # The dispatch order +//! +//! 1. **The scheme guard.** Only `CALL` and `STATICCALL` reach the dispatch; `CALLCODE` and +//! `DELEGATECALL` run the callee's code in the caller's context, where a system contract's +//! semantics would apply to the wrong account, so they are refused before any interceptor (see +//! [`MegaEvm::intercept`](crate::MegaEvm)). +//! 2. **The address.** One comparison against the `0x6342…` range decides whether any interceptor +//! can be concerned, before a byte of calldata is read ([`intercepted_contract`]). +//! 3. **The selector.** The contract's own dispatch peeks the first four bytes of the input +//! ([`peek_selector`]) without materialising the rest. A selector the contract does not +//! intercept is *not* intercepted: the call falls through to the deployed bytecode, which +//! reverts with `NotIntercepted()`. A selector matches on its own four bytes, whatever follows +//! them. +//! 4. **The value policy.** A method that takes no value answers a value-bearing call with +//! `NonZeroTransfer()` ([`reject_non_zero_transfer`]). The policy is per method, after the +//! selector matched, so a value-bearing call to an unknown selector still falls through. +//! +//! # The answer +//! +//! An answer is a [`synthetic_call_result`]: the forwarded gas untouched, the caller's reservoir +//! carried, and the calling opcode's upfront state-gas flags, so the caller settles it exactly +//! like a frame revm ran. + +use alloy_evm::Database; +use alloy_primitives::{Address, Bytes}; +use alloy_sol_types::SolError; +use revm::{ + context::{ContextTr, LocalContextTr}, + handler::FrameResult, + interpreter::{CallInput, CallInputs, InstructionResult}, +}; + +use crate::{ + synthetic_call_result, + system::{IMegaAccessControl, ORACLE_CONTRACT_ADDRESS}, + ExternalEnvTypes, MegaContext, +}; + +/// The revert data of `NonZeroTransfer()`: the answer to a call that carries value to a method +/// that takes none. Both control contracts declare the error, with the same selector. +pub const NON_ZERO_TRANSFER_REVERT_DATA: [u8; 4] = IMegaAccessControl::NonZeroTransfer::SELECTOR; + +/// The first 19 bytes every system contract address shares; only the last byte tells the six +/// apart. The dispatch compares them in one go, so a call to any other address leaves the +/// dispatch after a single comparison. +const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { + let mut prefix = [0_u8; 19]; + let address = ORACLE_CONTRACT_ADDRESS.0 .0; + let mut i = 0; + while i < prefix.len() { + prefix[i] = address[i]; + i += 1; + } + prefix +}; + +/// A system contract whose calls an interceptor answers. +/// +/// The High-Precision Timestamp wrapper and the `SequencerRegistry` are not here: they have no +/// interceptor and run their bytecode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum InterceptedContract { + /// `MegaAccessControl`: the volatile-data access switch. + AccessControl, + /// `MegaLimitControl`: what the running call has left. + LimitControl, +} + +/// The system contract with an interceptor `address` names, if any. +/// +/// The hot path of the dispatch: every call a transaction makes runs through it, so it is one +/// comparison against the shared prefix and one match on the last byte. +#[inline] +pub(crate) fn intercepted_contract(address: &Address) -> Option { + let bytes = address.0 .0; + if bytes[..SYSTEM_CONTRACT_PREFIX.len()] != SYSTEM_CONTRACT_PREFIX { + return None; + } + match bytes[SYSTEM_CONTRACT_PREFIX.len()] { + 4 => Some(InterceptedContract::AccessControl), + 5 => Some(InterceptedContract::LimitControl), + _ => None, + } +} + +/// Answers a call to a system contract, or `None` when nothing intercepts it and the contract's +/// own bytecode runs. +/// +/// The caller has already applied the scheme guard. +// Takes the context mutably: an interceptor whose answer is a side effect writes it. +#[allow(clippy::needless_pass_by_ref_mut)] +#[inline] +pub(crate) fn intercept( + ctx: &mut MegaContext, + inputs: &CallInputs, +) -> Option { + match intercepted_contract(&inputs.target_address)? { + InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs), + InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), + } +} + +/// The first four bytes of a call input, without materialising the rest of it. +/// +/// `None` when the input is shorter than four bytes: no selector, so nothing is intercepted. +/// For an input that lives in shared memory only the four-byte head is borrowed. +#[inline] +pub(crate) fn peek_selector(input: &CallInput, ctx: &CTX) -> Option<[u8; 4]> { + let mut selector = [0_u8; 4]; + match input { + CallInput::Bytes(bytes) => { + selector.copy_from_slice(bytes.get(..4)?); + } + CallInput::SharedBuffer(range) => { + if range.len() < 4 { + return None; + } + let head = ctx.local().shared_memory_buffer_slice(range.start..range.start + 4)?; + selector.copy_from_slice(&head); + } + } + Some(selector) +} + +/// The answer to a call that carries value to a method that takes none: a revert with +/// `NonZeroTransfer()`. `None` when the call carries no value and the method may run. +/// +/// Every intercepted method of the two control contracts and of `KeylessDeploy` reads state or +/// steers execution and takes no value. A method that takes value on purpose states why, in its +/// own interceptor, instead of calling this. +#[inline] +pub(crate) fn reject_non_zero_transfer(inputs: &CallInputs) -> Option { + inputs.transfer_value().is_some_and(|value| !value.is_zero()).then(|| { + synthetic_call_result( + inputs, + InstructionResult::Revert, + Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA), + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::system::{ + keyless::KEYLESS_DEPLOY_ADDRESS, IMegaLimitControl, ACCESS_CONTROL_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + }; + use alloy_primitives::{address, keccak256}; + + /// Every system contract with an interceptor is the one the dispatch names, and the ones + /// without an interceptor are not intercepted. + #[test] + fn test_every_system_address_maps_to_its_interceptor() { + assert_eq!( + intercepted_contract(&ACCESS_CONTROL_ADDRESS), + Some(InterceptedContract::AccessControl) + ); + assert_eq!( + intercepted_contract(&LIMIT_CONTROL_ADDRESS), + Some(InterceptedContract::LimitControl) + ); + assert_eq!(intercepted_contract(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), None); + assert_eq!(intercepted_contract(&SEQUENCER_REGISTRY_ADDRESS), None); + // The Oracle's and KeylessDeploy's interceptors follow; their addresses are in the + // range the dispatch tests, so they reach it as soon as they land. + assert_eq!(intercepted_contract(&ORACLE_CONTRACT_ADDRESS), None); + assert_eq!(intercepted_contract(&KEYLESS_DEPLOY_ADDRESS), None); + } + + /// An address next to the range, and one that shares the last byte but not the prefix, are + /// not intercepted: the prefix comparison is the whole address but its last byte. + #[test] + fn test_an_address_outside_the_range_is_not_intercepted() { + for address in [ + address!("0x6342000000000000000000000000000000000000"), + address!("0x6342000000000000000000000000000000000007"), + address!("0x6342000000000000000000000000000000010004"), + address!("0x6343000000000000000000000000000000000004"), + address!("0x0000000000000000000000000000000000000004"), + Address::ZERO, + ] { + assert_eq!(intercepted_contract(&address), None, "{address}"); + } + } + + /// The `NonZeroTransfer()` revert data is the error both control contracts declare. + #[test] + fn test_non_zero_transfer_revert_data_is_the_abi_error() { + let expected: [u8; 4] = keccak256("NonZeroTransfer()")[..4].try_into().unwrap(); + assert_eq!(NON_ZERO_TRANSFER_REVERT_DATA, expected); + assert_eq!(NON_ZERO_TRANSFER_REVERT_DATA, IMegaLimitControl::NonZeroTransfer::SELECTOR); + } +} diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index aa81e4271..608185a75 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -5,7 +5,19 @@ //! ABI and reverts with `NotIntercepted()`. Its Solidity source is //! `crates/system-contracts/contracts/MegaLimitControl.sol`. -use alloy_primitives::{address, Address}; +use alloy_evm::Database; +use alloy_primitives::{address, Address, Bytes}; +use alloy_sol_types::SolCall; +use revm::{ + handler::FrameResult, + interpreter::{CallInputs, InstructionResult}, +}; + +use crate::{ + synthetic_call_result, + system::intercept::{peek_selector, reject_non_zero_transfer}, + ExternalEnvTypes, MegaContext, +}; /// The address of the `MegaLimitControl` system contract. pub const LIMIT_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000005"); @@ -17,3 +29,31 @@ pub use mega_system_contracts::limit_control::LATEST_CODE as LIMIT_CONTROL_CODE; pub use mega_system_contracts::limit_control::LATEST_CODE_HASH as LIMIT_CONTROL_CODE_HASH; pub use mega_system_contracts::limit_control::IMegaLimitControl; + +/// Answers a call to `MegaLimitControl`, or `None` when the selector is not `remainingComputeGas` +/// and the deployed bytecode runs. +/// +/// # What `remainingComputeGas` answers today +/// +/// The compute ledger belongs to compute gas, which is what will make this the compute gas the +/// transaction has left. Until then the interceptor answers what the common execution layer +/// knows: the regular gas the intercepted call was forwarded, which is the regular gas its frame +/// could still spend. Regular gas is capped at the execution cap, so the answer never counts the +/// state-gas reservoir. +/// +/// The method reads and takes no value. +pub(crate) fn intercept( + ctx: &MegaContext, + inputs: &CallInputs, +) -> Option { + let selector = peek_selector(&inputs.input, ctx)?; + // Selector-only admission: the four bytes decide, whatever follows them. + if selector != IMegaLimitControl::remainingComputeGasCall::SELECTOR { + return None; + } + if let Some(rejected) = reject_non_zero_transfer(inputs) { + return Some(rejected); + } + let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&inputs.gas_limit); + Some(synthetic_call_result(inputs, InstructionResult::Return, Bytes::from(output))) +} diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index 85be4143e..8db1d122d 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -7,8 +7,9 @@ //! hash the `mega-system-contracts` crate ships, and its ABI. //! //! Four of them have an interceptor: a `CALL` or `STATICCALL` to one of their intercepted -//! selectors is answered by the engine instead of by the contract's code. The timestamp wrapper -//! and the `SequencerRegistry` run their bytecode. +//! selectors is answered by the engine instead of by the contract's code (see the `intercept` +//! module for the dispatch order and the shape of an answer). The timestamp wrapper and the +//! `SequencerRegistry` run their bytecode. //! //! Deploying the contracts at the fork that activates them belongs to system contract //! deployment; it is not here. @@ -16,17 +17,21 @@ pub mod keyless; mod control; +mod intercept; mod limit_control; mod oracle; mod sequencer_registry; mod timestamp; pub use control::*; +pub use intercept::NON_ZERO_TRANSFER_REVERT_DATA; pub use limit_control::*; pub use oracle::*; pub use sequencer_registry::*; pub use timestamp::*; +pub(crate) use intercept::intercept; + #[cfg(test)] mod tests { use super::{keyless::*, *}; diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs new file mode 100644 index 000000000..1e734d540 --- /dev/null +++ b/crates/mega-evm/tests/system/common.rs @@ -0,0 +1,136 @@ +//! Shared setup of the system contract tests. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + system::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE}, + ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE, + }, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{ADD, MSTORE, RETURN, RETURNDATACOPY, RETURNDATASIZE}, + context::{result::ResultAndState, BlockEnv, TxEnv}, + Database, +}; + +/// The sender of every transaction the tests run. +pub(crate) const CALLER: Address = address!("0x0000000000000000000000000000000000300000"); + +/// The contract the tests deploy when a call has to come from code. +pub(crate) const CONTRACT: Address = address!("0x0000000000000000000000000000000000300001"); + +/// A gas limit below the execution cap, so a transaction has no state-gas reservoir. +pub(crate) const GAS_LIMIT: u64 = 100_000_000; + +/// A database holding the code of every system contract, as the chain holds it once the fork +/// that deploys them has activated. +pub(crate) fn system_db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .account_code(HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE) + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE) +} + +/// A database as [`system_db`], with `code` deployed at [`CONTRACT`] and a balance to send +/// from, so a test that makes a value-bearing call fails on the policy and not on the funds. +pub(crate) fn with_contract(code: Bytes) -> MemoryDatabase { + system_db().account_code(CONTRACT, code).account_balance(CONTRACT, U256::from(1_000_000)) +} + +/// A block with room for any transaction the tests run. +pub(crate) fn block() -> BlockEnv { + BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, ..Default::default() } +} + +/// A Satin context over `db` with zero L1 fees. +pub(crate) fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +/// A transaction from [`CALLER`] calling `to` with `data` and `value`. +pub(crate) fn call_tx(to: Address, data: impl AsRef<[u8]>, value: U256) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::copy_from_slice(data.as_ref()), + value, + gas_limit: GAS_LIMIT, + ..Default::default() + })) +} + +/// Runs `tx` on a fresh Satin EVM over `db`, without committing. +pub(crate) fn run( + db: DB, + tx: MegaTransaction, +) -> ResultAndState { + MegaEvm::new(context(db)).transact_raw(tx).expect("the transaction is valid") +} + +/// Code that calls `target` with `data` through the `scheme` opcode, forwarding all the gas it +/// has, and returns the call's status followed by the callee's return data. +/// +/// `value` is passed by the two schemes that carry one (`CALL`, `CALLCODE`) and ignored by the +/// two that do not. +pub(crate) fn calls_with(scheme: u8, target: Address, data: &[u8], value: u64) -> Bytes { + use revm::bytecode::opcode::{CALL, CALLCODE, GAS}; + + let mut code = BytecodeBuilder::default().mstore(0x0, data); + code = code + .push_number(0_u64) // retSize: the return data is read with RETURNDATACOPY + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64); // argsOffset + if scheme == CALL || scheme == CALLCODE { + code = code.push_number(value); + } + code.push_address(target) + .append(GAS) + .append(scheme) + // memory[0..32] = the call's status + .push_number(0_u64) + .append(MSTORE) + // memory[32..32 + returndatasize] = the callee's return data + .append(RETURNDATASIZE) + .push_number(0_u64) + .push_number(32_u64) + .append(RETURNDATACOPY) + // return both + .append(RETURNDATASIZE) + .push_number(32_u64) + .append(ADD) + .push_number(0_u64) + .append(RETURN) + .build() +} + +/// Splits what [`calls_with`] returns into the inner call's status and its return data. +pub(crate) fn split_outcome(output: &[u8]) -> (bool, &[u8]) { + let (status, data) = output.split_at(32); + (U256::from_be_slice(status) == U256::ONE, data) +} + +/// The output of a successful transaction. +pub(crate) fn output(result: &ResultAndState) -> Bytes { + assert!(result.result.is_success(), "the transaction failed: {:?}", result.result); + result.result.output().cloned().unwrap_or_default() +} + +/// The revert data of a transaction that reverted. +pub(crate) fn revert_data(result: &ResultAndState) -> Bytes { + match &result.result { + revm::context::result::ExecutionResult::Revert { output, .. } => output.clone(), + other => panic!("the transaction did not revert: {other:?}"), + } +} diff --git a/crates/mega-evm/tests/system/control.rs b/crates/mega-evm/tests/system/control.rs new file mode 100644 index 000000000..afddd5ce8 --- /dev/null +++ b/crates/mega-evm/tests/system/control.rs @@ -0,0 +1,149 @@ +//! The `MegaAccessControl` interceptor: the three intercepted methods, the value policy, the +//! unknown selector and the call schemes. + +use alloy_primitives::{Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}, + test_utils::MemoryDatabase, +}; +use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; + +use crate::common::{ + call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, + CONTRACT, +}; + +const DISABLE: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; +const ENABLE: [u8; 4] = IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; +const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; +const NOT_INTERCEPTED: [u8; 4] = IMegaAccessControl::NotIntercepted::SELECTOR; + +/// A call from a contract to the access control contract, run as a transaction. +fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { + let code = calls_with(scheme, ACCESS_CONTROL_ADDRESS, data, value); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, data) = split_outcome(&outcome); + (status, Bytes::copy_from_slice(data)) +} + +/// The three methods are intercepted: the two switches return nothing and the query answers +/// `false`, which is what the common execution layer knows while detention is not here. +#[test] +fn test_the_three_methods_are_intercepted() { + let disabled = IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&false); + for (selector, expected) in + [(DISABLE, Bytes::new()), (ENABLE, Bytes::new()), (IS_DISABLED, Bytes::from(disabled))] + { + let (status, data) = through_contract(CALL, &selector, 0); + assert!(status, "the call to the intercepted method failed"); + assert_eq!(data, expected); + } +} + +/// A transaction that calls the contract directly is intercepted too: no opcode has to start +/// the call. +#[test] +fn test_a_direct_transaction_is_intercepted() { + let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, IS_DISABLED, U256::ZERO)); + assert_eq!( + output(&result), + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false + )), + ); +} + +/// A `STATICCALL` reaches the interceptor: the three methods write nothing. +#[test] +fn test_a_static_call_is_intercepted() { + let (status, data) = through_contract(STATICCALL, &IS_DISABLED, 0); + assert!(status); + assert_eq!( + data, + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false + )), + ); + let (status, data) = through_contract(STATICCALL, &DISABLE, 0); + assert!(status, "the switch does not write state, so a static caller may set it"); + assert!(data.is_empty()); +} + +/// A call that carries value to one of the three methods is refused with `NonZeroTransfer()`: +/// they read or steer execution and take no value. +#[test] +fn test_a_value_bearing_call_is_refused() { + for selector in [DISABLE, ENABLE, IS_DISABLED] { + let (status, data) = through_contract(CALL, &selector, 1); + assert!(!status, "a value-bearing call must not succeed"); + assert_eq!(data, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA)); + } +} + +/// The value policy is per method, after the selector matched: a value-bearing call to a +/// selector the contract does not intercept still falls through to the bytecode. +#[test] +fn test_a_value_bearing_call_to_an_unknown_selector_falls_through() { + let (status, data) = through_contract(CALL, &[0xde, 0xad, 0xbe, 0xef], 1); + assert!(!status); + assert_eq!(data, Bytes::from_static(&NOT_INTERCEPTED)); +} + +/// A selector the contract does not intercept, and an input too short to hold one, fall through +/// to the deployed bytecode, which reverts with `NotIntercepted()`. +#[test] +fn test_an_unknown_selector_falls_through_to_not_intercepted() { + for data in [vec![0xde, 0xad, 0xbe, 0xef], vec![], vec![0x00; 3], DISABLE[..3].to_vec()] { + let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); + assert_eq!( + revert_data(&result), + Bytes::from_static(&NOT_INTERCEPTED), + "input {data:?} must run the bytecode", + ); + } +} + +/// A selector followed by trailing bytes is intercepted: admission is the four bytes alone. +#[test] +fn test_a_selector_with_trailing_bytes_is_intercepted() { + for tail in [vec![0xff], vec![0x00; 32], vec![0xab; 100]] { + let data: Vec = IS_DISABLED.iter().copied().chain(tail).collect(); + let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); + assert_eq!( + output(&result), + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false + )), + ); + } +} + +/// `CALLCODE` and `DELEGATECALL` never reach an interceptor: the scheme guard refuses them, and +/// the contract's own bytecode runs, which reverts with `NotIntercepted()`. +#[test] +fn test_callcode_and_delegatecall_are_not_intercepted() { + for scheme in [CALLCODE, DELEGATECALL] { + for selector in [DISABLE, ENABLE, IS_DISABLED] { + let (status, data) = through_contract(scheme, &selector, 0); + assert!(!status, "scheme {scheme:#x} must not be intercepted"); + assert_eq!(data, Bytes::from_static(&NOT_INTERCEPTED)); + } + } +} + +/// An account without the contract's code at the address is not the access control contract: +/// the interceptor answers whatever the account holds, because the address is what it matches. +#[test] +fn test_the_address_is_what_the_interceptor_matches() { + let db = MemoryDatabase::default().account_balance(crate::common::CALLER, U256::from(1_000)); + let result = run(db, call_tx(ACCESS_CONTROL_ADDRESS, IS_DISABLED, U256::ZERO)); + assert_eq!( + output(&result), + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false + )), + "the interceptor answers before the code of the account is looked at", + ); +} diff --git a/crates/mega-evm/tests/system/limit_control.rs b/crates/mega-evm/tests/system/limit_control.rs new file mode 100644 index 000000000..a252b7002 --- /dev/null +++ b/crates/mega-evm/tests/system/limit_control.rs @@ -0,0 +1,136 @@ +//! The `MegaLimitControl` interceptor: `remainingComputeGas`, the value policy, the unknown +//! selector and the call schemes. + +use alloy_primitives::{Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}; +use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; + +use crate::common::{ + call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, + CONTRACT, GAS_LIMIT, +}; + +const REMAINING_COMPUTE_GAS: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; +const NOT_INTERCEPTED: [u8; 4] = IMegaLimitControl::NotIntercepted::SELECTOR; + +/// A call from a contract to the limit control contract, run as a transaction. +fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { + let code = calls_with(scheme, LIMIT_CONTROL_ADDRESS, data, value); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, data) = split_outcome(&outcome); + (status, Bytes::copy_from_slice(data)) +} + +/// Decodes what `remainingComputeGas()` answered. +fn remaining(data: &Bytes) -> u64 { + IMegaLimitControl::remainingComputeGasCall::abi_decode_returns(data) + .expect("the answer is a uint64") +} + +/// `remainingComputeGas()` is intercepted and answers the regular gas the call was forwarded, +/// which is below the execution cap and below what the caller had. +#[test] +fn test_remaining_compute_gas_is_intercepted() { + let (status, data) = through_contract(CALL, &REMAINING_COMPUTE_GAS, 0); + assert!(status); + let remaining = remaining(&data); + assert!(remaining > 0, "the call was forwarded gas"); + assert!(remaining < GAS_LIMIT, "the caller spent gas before the call"); + assert!( + remaining <= mega_evm::constants::TX_GAS_LIMIT_CAP, + "regular gas never exceeds the execution cap", + ); +} + +/// A transaction calling the contract directly is intercepted, and answers a figure below the +/// transaction's own gas limit. +#[test] +fn test_a_direct_transaction_is_intercepted() { + let result = + run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::ZERO)); + let answer = remaining(&output(&result)); + assert!( + answer > 0 && answer < GAS_LIMIT, + "{answer} is not between the intrinsic cost and the limit" + ); +} + +/// A `STATICCALL` reaches the interceptor: the method only reads. +#[test] +fn test_a_static_call_is_intercepted() { + let (status, data) = through_contract(STATICCALL, &REMAINING_COMPUTE_GAS, 0); + assert!(status); + assert!(remaining(&data) > 0); +} + +/// The answer falls as the caller spends: a second query further along the same frame reports +/// less than the first. +#[test] +fn test_the_answer_falls_as_the_caller_spends() { + use mega_evm::test_utils::BytecodeBuilder; + use revm::bytecode::opcode::{GAS, POP, RETURN}; + + // Two queries in a row, both written into memory and returned. + let mut code = BytecodeBuilder::default().mstore(0x0, REMAINING_COMPUTE_GAS); + for slot in [0x20_u64, 0x40] { + code = code + .push_number(32_u64) // retSize + .push_number(slot) // retOffset + .push_number(4_u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(LIMIT_CONTROL_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP); + } + let code = code.push_number(64_u64).push_number(0x20_u64).append(RETURN).build(); + + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let first = U256::from_be_slice(&outcome[..32]); + let second = U256::from_be_slice(&outcome[32..64]); + assert!(second < first, "{second} is not below {first}"); +} + +/// A call that carries value is refused with `NonZeroTransfer()`: the method reads and takes no +/// value. +#[test] +fn test_a_value_bearing_call_is_refused() { + let (status, data) = through_contract(CALL, &REMAINING_COMPUTE_GAS, 1); + assert!(!status); + assert_eq!(data, Bytes::from_static(&NON_ZERO_TRANSFER_REVERT_DATA)); +} + +/// A selector the contract does not intercept, and an input too short to hold one, fall through +/// to the deployed bytecode, which reverts with `NotIntercepted()`. +#[test] +fn test_an_unknown_selector_falls_through_to_not_intercepted() { + for data in [vec![0xde, 0xad, 0xbe, 0xef], vec![], REMAINING_COMPUTE_GAS[..3].to_vec()] { + let result = run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, &data, U256::ZERO)); + assert_eq!(revert_data(&result), Bytes::from_static(&NOT_INTERCEPTED), "input {data:?}"); + } +} + +/// A selector followed by trailing bytes is intercepted: admission is the four bytes alone. +#[test] +fn test_a_selector_with_trailing_bytes_is_intercepted() { + for tail in [vec![0xff], vec![0x00; 32]] { + let data: Vec = REMAINING_COMPUTE_GAS.iter().copied().chain(tail).collect(); + let result = run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, &data, U256::ZERO)); + assert!(remaining(&output(&result)) > 0); + } +} + +/// `CALLCODE` and `DELEGATECALL` never reach an interceptor: the scheme guard refuses them, and +/// the contract's own bytecode runs, which reverts with `NotIntercepted()`. +#[test] +fn test_callcode_and_delegatecall_are_not_intercepted() { + for scheme in [CALLCODE, DELEGATECALL] { + let (status, data) = through_contract(scheme, &REMAINING_COMPUTE_GAS, 0); + assert!(!status, "scheme {scheme:#x} must not be intercepted"); + assert_eq!(data, Bytes::from_static(&NOT_INTERCEPTED)); + } +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs new file mode 100644 index 000000000..f58e54b17 --- /dev/null +++ b/crates/mega-evm/tests/system/main.rs @@ -0,0 +1,6 @@ +//! Tests of the system contracts: the interceptor dispatch, what each contract answers, and the +//! system-address transaction. + +mod common; +mod control; +mod limit_control; From dfaa5a0cc6b7888c43722a82c864438e91b906bd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:17:42 +0800 Subject: [PATCH 132/201] feat(evm): price state gas by the SALT bucket the charge lands in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MegaContext overrides the Host's pricing hook: an EIP-8037 state gas charge costs the schedule's entry times the capacity of the SALT bucket of the account, or of the storage slot, it is attributed to, counted in minimum buckets. State that crowds a region of the trie costs what it makes everyone else pay to carry it; regular gas is never touched by the multiplier. The hook is the only place a charge is priced, so every site that gives a charge back re-prices the same (id, site) pair and cancels it exactly — the per-transaction multiplier cache is what guarantees the two agree. A system-originated transaction prices at the minimum bucket and never reads SALT at all: a state change the protocol mandates cannot be priced out by the growth of a region it does not control. Today that is the transaction whose caller is the EIP-4788 system address and every transaction run through a system-call entry point. A user's deposit is deliberately not covered — a deposit is a shape a user can produce. A failed capacity lookup reports nothing and records its cause in the context error the way a failed sload does; the charge site turns that into a bail-out the transaction surfaces as an error, so a price the engine could not look up is never replaced by one nobody chose. With every bucket at the minimum the engine charges what it charged before: the op-revm baseline and the pricing table do not move. --- crates/mega-evm/src/evm/context.rs | 47 ++- crates/mega-evm/src/evm/host.rs | 63 +++- crates/mega-evm/src/evm/mod.rs | 4 +- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/salt.rs | 535 ++++++++++++++++++++++++++++ 5 files changed, 642 insertions(+), 8 deletions(-) create mode 100644 crates/mega-evm/tests/satin/salt.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index afd1a3294..8226eec27 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,9 +1,13 @@ //! The execution context of the Satin engine. +use alloy_eips::eip4788::SYSTEM_ADDRESS; use delegate::delegate; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ - context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, + context::{ + BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, + Transaction, + }, primitives::{Address, StorageKey}, Database, Journal, }; @@ -40,6 +44,9 @@ pub struct MegaContext MegaContext { @@ -65,6 +72,7 @@ impl MegaContext { additional_limit: AdditionalLimit::default(), block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), + system_originated: false, } } @@ -181,6 +189,12 @@ impl MegaContext { &self.bucket_multipliers } + /// Whether the running (or last) transaction is system-originated, and so prices every + /// EIP-8037 state gas charge at the minimum bucket. See [`is_system_originated`]. + pub const fn is_system_originated(&self) -> bool { + self.system_originated + } + /// Prepares the common execution layer for a new transaction or system call. Every entry /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. /// @@ -189,6 +203,17 @@ impl MegaContext { pub(crate) fn on_new_tx(&mut self) { self.additional_limit.reset(); self.bucket_multipliers.reset(); + self.system_originated = is_system_originated(&self.inner.tx); + } + + /// Prepares the context for a system call. Every system-call entry point of + /// [`MegaEvm`](crate::MegaEvm) calls it instead of [`on_new_tx`](Self::on_new_tx). + /// + /// A system call is system-originated whatever caller it names: it is the protocol running, + /// not a transaction anybody sent. + pub(crate) fn on_new_system_call(&mut self) { + self.on_new_tx(); + self.system_originated = true; } /// Consumes the context and returns the database, the configuration and the block. @@ -198,6 +223,26 @@ impl MegaContext { } } +/// Whether `tx` is system-originated: produced by the protocol itself rather than sent by a user. +/// +/// A system-originated transaction prices EIP-8037 state gas at the minimum bucket (`m = 1`), so +/// a state change the protocol mandates costs the same however full the SALT bucket it lands in +/// happens to be, and can never be priced out of a block by the growth of a region it does not +/// control. +/// +/// What it matches today is the transaction whose caller is the EIP-4788 / EIP-2935 system +/// address, which is how the pre-block system calls are issued; every transaction run through a +/// system-call entry point is system-originated whatever caller it names +/// ([`MegaContext::on_new_system_call`]). The sequencer's own system transaction joins this rule +/// when the system contract mechanisms land, which are what define its caller and the deposit +/// source hash it is promoted with. +/// +/// A user's deposit transaction is deliberately not system-originated. A deposit is a shape a +/// user can produce, so matching it here would be a way around the scaling. +fn is_system_originated(tx: &MegaTransaction) -> bool { + tx.caller() == SYSTEM_ADDRESS +} + /// Sets the configuration fields the spec fixes. /// /// Satin runs the Satin gas schedule (see [`satin_gas_params`]) on its Karst base, with EIP-8037 diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 227211ea9..fa7f6754b 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -11,14 +11,29 @@ //! frame with the record already counted. //! //! `block_hash` serves the read and records it, so a stateless witness learns of a `BLOCKHASH` -//! that bypassed the journal. Every other Host method delegates to op-revm's context. +//! that bypassed the journal. +//! +//! # One hook prices every state charge +//! +//! [`state_gas_price`](revm::context_interface::Host::state_gas_price) is the one place an +//! EIP-8037 state gas charge is priced. Every charge site of the engine asks it, and so does +//! every site that gives a charge back — the same `(id, site)` pair, so a refill cancels the +//! charge it undoes exactly, whatever the price was. That is what lets SALT scale the charge by +//! the capacity of the bucket it lands in without a second table of what to give back. +//! +//! Every other Host method delegates to op-revm's context. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::format; use alloy_primitives::map::Entry; use delegate::delegate; use revm::{ + context::ContextTr, context_interface::{ - cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, - context::{SStoreResult, SelfDestructResult, StateLoad}, + cfg::{GasId, GasParams, StateGasSite}, + context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, host::LoadError, journaled_state::{AccountInfoLoad, AccountLoad}, }, @@ -50,8 +65,6 @@ impl revm::context_interface::Host fn max_initcode_size(&self) -> usize; fn gas_params(&self) -> &GasParams; fn is_amsterdam_eip8037_enabled(&self) -> bool; - fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; - fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; fn sload_skip_cold_load( &mut self, address: Address, @@ -74,6 +87,46 @@ impl revm::context_interface::Host } } + /// Prices one EIP-8037 state gas unit, scaling the schedule's entry by the SALT bucket + /// capacity of the account — or, for a slot-scoped entry, of the storage slot — the charge + /// lands on. + /// + /// `state gas = schedule entry x m`, where `m` is the bucket's capacity in minimum buckets. + /// A charge in a minimum-capacity bucket pays the schedule's own number, and a charge in a + /// bucket eight times as large pays eight times as much: state that crowds a region of the + /// trie costs what it makes everyone else pay to carry it. Only the state dimension scales; + /// regular gas is never touched by `m`. + /// + /// Two charges are priced without reading SALT at all: an entry the schedule prices at zero, + /// which `m` cannot move off zero, and every charge of a system-originated transaction, + /// which prices at the minimum bucket by rule (see + /// [`is_system_originated`](crate::MegaContext::is_system_originated)). + /// + /// Reporting nothing is how a failed capacity lookup travels: the cause is recorded in the + /// context error the way [`Host::sload`](revm::context_interface::Host::sload) records a + /// database failure, and the charge site turns it into a bail-out that the transaction + /// surfaces as an error. A price the engine could not look up is never replaced by one + /// nobody chose. + #[inline] + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { + let base = self.inner.cfg.gas_params.get(id); + if base == 0 || self.is_system_originated() { + return Some(base); + } + let multiplier = match site.slot { + Some(slot) => self.slot_bucket_multiplier(site.address, slot), + None => self.account_bucket_multiplier(site.address), + }; + match multiplier { + Ok(multiplier) => Some(base.saturating_mul(multiplier)), + Err(error) => { + *self.error() = + Err(ContextError::Custom(format!("SALT bucket lookup failed: {error}"))); + None + } + } + } + /// Serves the hash and records that this block read it. /// /// `BLOCKHASH` reads the chain's history through the database, so a witness built from the diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 5871436ce..45dd80c3f 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -353,7 +353,7 @@ impl SystemCallEvm for MegaEvm::new().run_system_call(self) } } @@ -375,7 +375,7 @@ where system_contract_address, data, )); - self.inner.ctx.on_new_tx(); + self.inner.ctx.on_new_system_call(); MegaHandler::<_, Self::Error, _>::new().inspect_run_system_call(self) } } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index e4b10281d..0f8b00a0e 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -9,6 +9,7 @@ mod intrinsic; mod outcome; mod precompile_gas; mod pricing_table; +mod salt; mod schedule; mod state; mod static_callee; diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs new file mode 100644 index 000000000..7ecd8e239 --- /dev/null +++ b/crates/mega-evm/tests/satin/salt.rs @@ -0,0 +1,535 @@ +//! SALT pricing: the shared setup of the SALT tests, and what one state gas charge costs. +//! +//! Every EIP-8037 state gas charge is priced `schedule entry x m`, where `m` is the capacity of +//! the SALT bucket the charge lands in, counted in minimum buckets. This module pins that on +//! each of the sites a charge is made at, by running the same probe over three environments — +//! one where the bucket is at the minimum, one twice as large, one eight times as large — and +//! reading the ledgers the transaction reports: +//! +//! - the state ledger is the schedule's entry times `m`, and +//! - the regular ledger does not move: `m` scales the state dimension and nothing else. +//! +//! The refund side is in `salt_refund`, the failed-lookup side in `salt_failure`. + +use alloy_eips::{ + eip4788::SYSTEM_ADDRESS, + eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}, +}; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + satin_gas_params, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + BucketId, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, PUSH0, RETURN}, + context::{result::EVMError, tx::TxEnvBuilder, TxEnv}, + context_interface::cfg::GasId, +}; + +use crate::common::{block, runs_at_measurement_prices}; + +/// The sender of every probe. +pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000c00000"); +/// The contract a probe's code runs in. +pub(crate) const CONTRACT: Address = address!("0000000000000000000000000000000000c00001"); +/// An account that does not exist, so reaching it with value creates it. +pub(crate) const EMPTY: Address = address!("0000000000000000000000000000000000c00002"); +/// An authority that does not exist, so an authorization on it creates it. +pub(crate) const AUTHORITY: Address = address!("0000000000000000000000000000000000c00003"); +/// The contract an authorization delegates to. +pub(crate) const DELEGATE: Address = address!("0000000000000000000000000000000000c00004"); + +/// Plenty for every probe, and below the execution cap, so the reservoir is empty and each state +/// charge spills onto the regular budget rather than being absorbed. +pub(crate) const GAS_LIMIT: u64 = 30_000_000; + +/// The external environments of a SALT test. The error type is a string so a test can name the +/// failure a broken SALT backend reports. +pub(crate) type SaltEnvs = TestExternalEnvs; + +/// Every bucket at the minimum capacity, which is `m = 1` everywhere. +pub(crate) fn minimal_envs() -> SaltEnvs { + TestExternalEnvs::new() +} + +/// The bucket an account's own state lives in. +pub(crate) fn account_bucket(account: Address) -> BucketId { + ::bucket_id_for_account(account) +} + +/// The bucket a storage slot lives in. +pub(crate) fn slot_bucket(address: Address, key: U256) -> BucketId { + ::bucket_id_for_slot(address, key) +} + +/// The capacity a bucket has at multiplier `m`. +pub(crate) fn capacity(m: u64) -> u64 { + MIN_BUCKET_SIZE as u64 * m +} + +/// `envs` with the bucket of `account`'s own state at multiplier `m`. +pub(crate) fn crowded_account(envs: SaltEnvs, account: Address, m: u64) -> SaltEnvs { + envs.with_bucket_capacity(account_bucket(account), capacity(m)) +} + +/// `envs` with the bucket of the slot `key` of `address` at multiplier `m`. +pub(crate) fn crowded_slot(envs: SaltEnvs, address: Address, key: U256, m: u64) -> SaltEnvs { + envs.with_bucket_capacity(slot_bucket(address, key), capacity(m)) +} + +/// A Satin context over `db` reading `envs`, with zero L1 fees. +pub(crate) fn salt_context( + db: MemoryDatabase, + envs: SaltEnvs, +) -> MegaContext { + MegaContext::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, + ) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()) +} + +/// The error a SALT test's transaction can fail with. +pub(crate) type SaltError = EVMError; + +/// Runs `tx` on a fresh EVM over `db` reading `envs`, without committing. +pub(crate) fn try_run( + db: MemoryDatabase, + envs: SaltEnvs, + tx: MegaTransaction, +) -> Result { + MegaEvm::new(salt_context(db, envs)).execute_transaction(tx) +} + +/// Runs `tx` and requires it to succeed. +pub(crate) fn run( + db: MemoryDatabase, + envs: SaltEnvs, + tx: MegaTransaction, +) -> MegaTransactionOutcome { + let outcome = try_run(db, envs, tx).expect("the probe is a valid transaction"); + assert!(outcome.result.is_success(), "the probe must succeed: {:?}", outcome.result); + outcome +} + +/// A funded sender and a contract running `code` with a balance of its own, so a probe's inner +/// `CALL` can carry value. +pub(crate) fn db(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CONTRACT, U256::from(10u64.pow(9))) + .account_code(CONTRACT, code) +} + +/// A zero-value call from `CALLER` to `CONTRACT`. +pub(crate) fn call_contract() -> MegaTransaction { + tx(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO) +} + +/// A transaction from `CALLER`. +pub(crate) fn tx(kind: TxKind, data: Bytes, value: U256) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind, + data, + value, + gas_limit: GAS_LIMIT, + ..Default::default() + })) +} + +/// A type-4 transaction from `CALLER` to `to`, delegating `AUTHORITY` to `DELEGATE`. +pub(crate) fn authorization_tx(to: Address) -> MegaTransaction { + OpTx(op_transaction( + TxEnvBuilder::default() + .caller(CALLER) + .call(to) + .chain_id(Some(1)) + .gas_limit(GAS_LIMIT) + .authorization_list_recovered(vec![RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: DELEGATE, nonce: 0 }, + RecoveredAuthority::Valid(AUTHORITY), + )]) + .build_fill(), + )) +} + +/// `CALL(gas, target, value, 0, 0, 0, 0)`. +pub(crate) fn value_call(target: Address) -> BytecodeBuilder { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(target) + .push_number(1_000_000u64) + .append(CALL) +} + +/// `CREATE(0, 0, len)` of an init code already in memory at offset 0. +pub(crate) fn create_empty_contract() -> BytecodeBuilder { + // Init code `PUSH0 PUSH0 RETURN`: deploys zero bytes of runtime code. + let init: [u8; 3] = [PUSH0, PUSH0, RETURN]; + BytecodeBuilder::default() + .mstore(0, init) + .push_number(init.len() as u64) + .push_number(32u64 - init.len() as u64) + .push_number(0u64) + .append(CREATE) +} + +/// One state gas entry of the Satin schedule. +pub(crate) fn entry(id: GasId) -> u64 { + satin_gas_params().get(id) +} + +/// What a probe spent on state gas at each of the three multipliers, with the regular ledger +/// checked to be the same at all three: `m` scales the state dimension and nothing else. +/// +/// `probe` builds the transaction and the database; `crowd` puts the bucket the probe charges in +/// at multiplier `m`. +pub(crate) fn state_gas_at( + m: u64, + crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs, + probe: impl Fn() -> (MemoryDatabase, MegaTransaction), +) -> (u64, u64) { + let (db, tx) = probe(); + let outcome = run(db, crowd(minimal_envs(), m), tx); + (outcome.gas.state, outcome.gas.regular) +} + +/// Pins one charge site: the state ledger is `unit_price x units x m` at every multiplier, and +/// the regular ledger does not move. +pub(crate) fn assert_scales( + site: &str, + unscaled: u64, + crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs + Copy, + probe: impl Fn() -> (MemoryDatabase, MegaTransaction) + Copy, +) { + let (state_at_one, regular_at_one) = state_gas_at(1, crowd, probe); + assert_eq!(state_at_one, unscaled, "{site}: the minimum bucket pays the schedule's entry"); + for m in [2, 8] { + let (state, regular) = state_gas_at(m, crowd, probe); + assert_eq!(state, unscaled * m, "{site}: state gas at m = {m}"); + assert_eq!(regular, regular_at_one, "{site}: regular gas must not scale with m"); + } +} + +/* The six sites a state gas charge is made at. */ + +/// `SSTORE` onto a slot that was zero: the slot's own bucket prices it. +#[test] +fn test_the_sstore_set_charge_scales_with_the_slot_s_bucket() { + const SLOT: u64 = 7; + assert_scales( + "SSTORE set", + entry(GasId::sstore_set_state_gas()), + |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m), + || { + let code = + BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + (db(code), call_contract()) + }, + ); +} + +/// A `CALL` carrying value to an account that does not exist: the account's bucket prices it. +#[test] +fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { + assert_scales( + "CALL to a new account", + entry(GasId::new_account_state_gas()), + |envs, m| crowded_account(envs, EMPTY, m), + || (db(value_call(EMPTY).stop().build()), call_contract()), + ); +} + +/// `CREATE`: the bucket of the address it deploys to prices the account it adds. +#[test] +fn test_the_create_charge_scales_with_the_created_address_s_bucket() { + let created = CONTRACT.create(0); + assert_scales( + "CREATE", + entry(GasId::create_state_gas()), + move |envs, m| crowded_account(envs, created, m), + || (db(create_empty_contract().stop().build()), call_contract()), + ); +} + +/// The EIP-2780 runtime phase charges the transaction's own recipient before the first frame, +/// and reads the recipient's bucket to price it. +#[test] +fn test_the_top_level_recipient_charge_scales_with_the_recipient_s_bucket() { + assert_scales( + "the transaction's recipient", + entry(GasId::new_account_state_gas()), + |envs, m| crowded_account(envs, EMPTY, m), + || (db(Bytes::new()), tx(TxKind::Call(EMPTY), Bytes::new(), U256::from(1))), + ); +} + +/// The same phase charges a creation transaction's target, in the target's own bucket. +#[test] +fn test_the_create_transaction_target_charge_scales_with_its_bucket() { + let created = CALLER.create(0); + assert_scales( + "a creation transaction's target", + entry(GasId::create_state_gas()), + move |envs, m| crowded_account(envs, created, m), + || { + let init = Bytes::from_static(&[PUSH0, PUSH0, RETURN]); + (db(Bytes::new()), tx(TxKind::Create, init, U256::ZERO)) + }, + ); +} + +/// An EIP-7702 authorization on an authority that does not exist pays for the account leaf it +/// adds and for the delegation bytes it writes, both in the authority's bucket. +#[test] +fn test_the_eip7702_authority_charges_scale_with_the_authority_s_bucket() { + assert_scales( + "an EIP-7702 authority", + entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()), + |envs, m| crowded_account(envs, AUTHORITY, m), + || (db(Bytes::new()), authorization_tx(CONTRACT)), + ); +} + +/// Deployed code is charged per byte, in the bucket of the address it is deployed to — the same +/// bucket that priced the creation itself. +#[test] +fn test_the_code_deposit_charge_scales_with_the_deployed_address_s_bucket() { + const DEPLOYED: u64 = 32; + let created = CALLER.create(0); + assert_scales( + "a code deposit", + entry(GasId::create_state_gas()) + entry(GasId::code_deposit_state_gas()) * DEPLOYED, + move |envs, m| crowded_account(envs, created, m), + || { + let init = BytecodeBuilder::default() + .push_number(DEPLOYED) + .append_many([PUSH0, RETURN]) + .build(); + (db(Bytes::new()), tx(TxKind::Create, init, U256::ZERO)) + }, + ); +} + +/// The numbers the sites above pay at the minimum bucket, written out: the schedule's state +/// entries at `MegaETH`'s cost per state byte. +#[test] +fn test_the_minimum_bucket_pays_the_spec_s_own_state_gas() { + if runs_at_measurement_prices() { + return; + } + assert_eq!(entry(GasId::sstore_set_state_gas()), 97_920); + assert_eq!(entry(GasId::new_account_state_gas()), 183_600); + assert_eq!(entry(GasId::create_state_gas()), 183_600); + assert_eq!(entry(GasId::code_deposit_state_gas()), 1_530); + assert_eq!(entry(GasId::tx_eip7702_state_gas_bytecode()), 35_190); +} + +/* What the multiplier does not touch. */ + +/// A crowded bucket somewhere else changes nothing: the charge reads the bucket of the account +/// or slot it lands on, and no other. +#[test] +fn test_a_crowded_bucket_elsewhere_does_not_change_the_price() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let unscaled = run(db(code.clone()), minimal_envs(), call_contract()).gas; + + // Crowd the contract's own account bucket, another slot of the same contract, and an + // unrelated account — none of them is the site this charge lands on. + let envs = crowded_account(minimal_envs(), CONTRACT, 64); + let envs = crowded_slot(envs, CONTRACT, U256::from(SLOT + 1), 64); + let envs = crowded_account(envs, EMPTY, 64); + let elsewhere = run(db(code), envs, call_contract()).gas; + + assert_eq!(elsewhere, unscaled, "only the charge's own bucket prices it"); +} + +/// The engine reads a bucket once per transaction: a program writing many slots of one bucket +/// asks the SALT environment for its capacity a single time. +#[test] +fn test_a_bucket_is_read_once_per_transaction() { + const SLOTS: u64 = 16; + // Put every slot this program writes in one bucket, so one capacity query serves them all. + let mut code = BytecodeBuilder::default(); + let mut envs = minimal_envs(); + for slot in 0..SLOTS { + code = code.sstore(U256::from(slot), U256::from(1)); + envs = envs.with_bucket_capacity(slot_bucket(CONTRACT, U256::from(slot)), capacity(4)); + } + let buckets: Vec = + (0..SLOTS).map(|slot| slot_bucket(CONTRACT, U256::from(slot))).collect(); + + let mut evm = MegaEvm::new(salt_context(db(code.stop().build()), envs.clone())); + let outcome = evm.execute_transaction(call_contract()).expect("the probe is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + assert_eq!( + outcome.gas.state, + entry(GasId::sstore_set_state_gas()) * 4 * SLOTS, + "every slot paid the crowded price", + ); + for bucket in &buckets { + assert_eq!(envs.bucket_queries(*bucket), 1, "bucket {bucket} was read more than once"); + } + assert_eq!( + envs.total_bucket_queries(), + buckets.iter().copied().collect::>().len() as u32, + "one query per distinct bucket, whatever the number of charges", + ); +} + +/// A multiplier large enough to overflow the product saturates instead of wrapping: an absurd +/// capacity makes a charge unaffordable, never free. +#[test] +fn test_an_absurd_capacity_saturates_rather_than_wrapping() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = + minimal_envs().with_bucket_capacity(slot_bucket(CONTRACT, U256::from(SLOT)), u64::MAX); + + let outcome = try_run(db(code), envs, call_contract()).expect("the transaction is valid"); + assert!( + matches!(outcome.result, revm::context::result::ExecutionResult::Halt { .. }), + "an unaffordable charge halts: {:?}", + outcome.result, + ); +} + +/* The system-origin rule. */ + +/// The pre-block system calls and every other system call price at the minimum bucket, whatever +/// the bucket they write into actually holds: a state change the protocol mandates cannot be +/// priced out by the growth of a region it does not control. +#[test] +fn test_a_system_call_prices_at_the_minimum_bucket() { + use alloy_evm::Evm; + + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + + let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); + let result = evm + .transact_system_call(SYSTEM_ADDRESS, CONTRACT, Bytes::new()) + .expect("the system call is valid"); + assert!(result.result.is_success(), "{:?}", result.result); + + assert_eq!( + result.result.gas().state_gas_spent_final(), + entry(GasId::sstore_set_state_gas()), + "a system call pays the schedule's own entry", + ); + assert_eq!(envs.total_bucket_queries(), 0, "and never reads the SALT environment"); + assert!(evm.ctx().is_system_originated()); +} + +/// A system call is system-originated whatever caller it names: it is the protocol running, not +/// a transaction anybody sent. +#[test] +fn test_a_system_call_with_another_caller_is_still_system_originated() { + use alloy_evm::Evm; + + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + + let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); + let result = + evm.transact_system_call(CALLER, CONTRACT, Bytes::new()).expect("the system call is valid"); + assert!(result.result.is_success(), "{:?}", result.result); + + assert_eq!(result.result.gas().state_gas_spent_final(), entry(GasId::sstore_set_state_gas())); + assert_eq!(envs.total_bucket_queries(), 0); +} + +/// A transaction the system address sends prices at the minimum bucket too: that address has no +/// key, so only the protocol's own pre-block helpers ever set it as caller. +#[test] +fn test_a_transaction_from_the_system_address_prices_at_the_minimum_bucket() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + let tx = OpTx(op_transaction(TxEnv { + caller: SYSTEM_ADDRESS, + kind: TxKind::Call(CONTRACT), + gas_limit: GAS_LIMIT, + ..Default::default() + })); + + let outcome = run(db(code), envs.clone(), tx); + assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas())); + assert_eq!(envs.total_bucket_queries(), 0); +} + +/// The control arm of the rule: the very same write, sent by a user, pays the crowded price. +/// Without this the exemption above could be passing for the wrong reason. +#[test] +fn test_a_user_transaction_into_the_same_bucket_pays_the_crowded_price() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + + let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); + let outcome = evm.execute_transaction(call_contract()).expect("the probe is valid"); + + assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas()) * 8); + assert_eq!(envs.total_bucket_queries(), 1); + assert!(!evm.ctx().is_system_originated()); +} + +/// The exemption belongs to one transaction: a user transaction run on the same EVM right after +/// a system call is priced by its own bucket again. +#[test] +fn test_the_system_exemption_does_not_leak_into_the_next_transaction() { + use alloy_evm::Evm; + + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + let mut evm = MegaEvm::new(salt_context(db(code), envs)); + + let system = evm + .transact_system_call(SYSTEM_ADDRESS, CONTRACT, Bytes::new()) + .expect("the system call is valid"); + assert_eq!(system.result.gas().state_gas_spent_final(), entry(GasId::sstore_set_state_gas())); + assert!(evm.ctx().is_system_originated()); + + let user = evm.execute_transaction(call_contract()).expect("the probe is valid"); + assert!(!evm.ctx().is_system_originated(), "the next transaction is nobody's system call"); + assert_eq!(user.gas.state, entry(GasId::sstore_set_state_gas()) * 8); +} + +/// With every bucket at the minimum the engine charges exactly what it charges without a SALT +/// environment at all, so turning SALT pricing on moves nothing until a bucket grows. +#[test] +fn test_the_minimum_bucket_matches_the_engine_without_a_salt_environment() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .append_many(value_call(EMPTY).build_vec()) + .stop() + .build(); + + let with_salt = run(db(code.clone()), minimal_envs(), call_contract()).gas; + let without_salt = MegaEvm::new( + MegaContext::new(db(code), MegaSpecId::SATIN) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()), + ) + .execute_transaction(call_contract()) + .expect("the probe is valid") + .gas; + + assert_eq!(with_salt, without_salt); +} From 49dae5d2ff7ff7ab3e6c6701f23f526532d61546 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:18:59 +0800 Subject: [PATCH 133/201] test(satin): pin what an unpriceable state gas charge does Every site a state gas charge is made at surfaces a failed SALT capacity lookup as the cause the environment reported, not as the out-of-gas halt the EIP-2780 runtime phase uses for a real shortfall and not as a silent fall back to the schedule's own price. The code-deposit arm deploys to an address that already holds a balance, so the creation charge is skipped and the per-byte deposit is the only charge in that bucket; a control run pins that it really is drawn. Two arms say where the hook is not consulted: a program that charges no state gas never asks for a price, and a system call prices at the minimum bucket without reading SALT at all. --- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/salt_failure.rs | 200 ++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 crates/mega-evm/tests/satin/salt_failure.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 0f8b00a0e..c4c084835 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -10,6 +10,7 @@ mod outcome; mod precompile_gas; mod pricing_table; mod salt; +mod salt_failure; mod schedule; mod state; mod static_callee; diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs new file mode 100644 index 000000000..5b9c75a86 --- /dev/null +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -0,0 +1,200 @@ +//! SALT pricing: what happens when a state gas charge cannot be priced at all. +//! +//! The pricing hook reports a failed capacity lookup the way `Host::sload` reports a failed +//! database read: it returns nothing and records the cause in the context error. Every charge +//! site turns that into a bail-out, and the transaction surfaces the recorded cause as an error +//! rather than as a halt — a transaction that could not afford its state gas and one whose price +//! could not be looked up must not look alike, and neither may be settled at a price nobody +//! chose. + +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{PUSH0, RETURN}, + context::result::EVMError, + context_interface::cfg::GasId, +}; + +use crate::salt::{ + account_bucket, authorization_tx, call_contract, create_empty_contract, crowded_account, db, + entry, minimal_envs, run, salt_context, slot_bucket, try_run, tx, value_call, SaltEnvs, + AUTHORITY, CALLER, CONTRACT, EMPTY, +}; + +/// What a broken SALT backend reports. +const UNREACHABLE: &str = "salt backend unreachable"; + +/// A slot every probe that writes storage uses. +const SLOT: u64 = 7; + +/// `envs` with the capacity query of `account`'s own bucket failing. +fn failing_account(envs: SaltEnvs, account: Address) -> SaltEnvs { + envs.with_failing_bucket(account_bucket(account), UNREACHABLE.into()) +} + +/// `envs` with the capacity query of the slot `key` of `address` failing. +fn failing_slot(envs: SaltEnvs, address: Address, key: U256) -> SaltEnvs { + envs.with_failing_bucket(slot_bucket(address, key), UNREACHABLE.into()) +} + +/// Runs the probe and requires it to fail with the cause the SALT environment reported. +fn assert_fails(site: &str, db: MemoryDatabase, envs: SaltEnvs, tx: MegaTransaction) { + match try_run(db, envs, tx) { + Err(EVMError::Custom(message)) => assert!( + message.contains(UNREACHABLE), + "{site}: the recorded cause must reach the caller, got {message:?}", + ), + Err(other) => panic!("{site}: expected the recorded cause, got {other:?}"), + Ok(outcome) => panic!("{site}: expected an error, got {:?}", outcome.result), + } +} + +/// An `SSTORE` onto a slot whose bucket cannot be read fails the transaction. +#[test] +fn test_an_unpriceable_sstore_set_fails_the_transaction() { + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + assert_fails( + "SSTORE set", + db(code), + failing_slot(minimal_envs(), CONTRACT, U256::from(SLOT)), + call_contract(), + ); +} + +/// So does a `CALL` carrying value to an account whose bucket cannot be read. +#[test] +fn test_an_unpriceable_new_account_call_fails_the_transaction() { + assert_fails( + "CALL to a new account", + db(value_call(EMPTY).stop().build()), + failing_account(minimal_envs(), EMPTY), + call_contract(), + ); +} + +/// And a `CREATE` whose deployment address falls in a bucket that cannot be read. +#[test] +fn test_an_unpriceable_create_fails_the_transaction() { + assert_fails( + "CREATE", + db(create_empty_contract().stop().build()), + failing_account(minimal_envs(), CONTRACT.create(0)), + call_contract(), + ); +} + +/// A charge the EIP-2780 runtime phase makes before the first frame fails the transaction too: +/// that phase reports a real shortfall as an out-of-gas halt, and an unpriceable charge must not +/// be dressed up as one. +#[test] +fn test_an_unpriceable_top_level_recipient_fails_the_transaction() { + assert_fails( + "the transaction's recipient", + db(Bytes::new()), + failing_account(minimal_envs(), EMPTY), + tx(TxKind::Call(EMPTY), Bytes::new(), U256::from(1)), + ); +} + +/// The create target of a creation transaction is charged in the same phase. +#[test] +fn test_an_unpriceable_create_transaction_target_fails_the_transaction() { + assert_fails( + "a creation transaction's target", + db(Bytes::new()), + failing_account(minimal_envs(), CALLER.create(0)), + tx(TxKind::Create, Bytes::from_static(&[PUSH0, PUSH0, RETURN]), U256::ZERO), + ); +} + +/// An EIP-7702 authorization is applied before any frame runs, and its charges go through the +/// same hook. +#[test] +fn test_an_unpriceable_eip7702_authority_fails_the_transaction() { + assert_fails( + "an EIP-7702 authority", + db(Bytes::new()), + failing_account(minimal_envs(), AUTHORITY), + authorization_tx(CONTRACT), + ); +} + +/// The code deposit is priced through the hook as well. The creation itself pays nothing here — +/// the deployment address already holds a balance, so it is not a new account leaf — which +/// leaves the deposit as the only charge in that bucket. +#[test] +fn test_an_unpriceable_code_deposit_fails_the_transaction() { + let created = CALLER.create(0); + let db = db(Bytes::new()).account_balance(created, U256::from(1)); + let init = BytecodeBuilder::default().push_number(32u64).append_many([PUSH0, RETURN]).build(); + + // The creation charge is skipped for an address that already exists, so a run with the + // bucket readable must still draw the per-byte deposit charge — otherwise the failure below + // would be pinning nothing. + let deposited = run( + db.clone(), + crowded_account(minimal_envs(), created, 1), + tx(TxKind::Create, init.clone(), U256::ZERO), + ); + assert_eq!( + deposited.gas.state, + entry(GasId::code_deposit_state_gas()) * 32, + "the deposit is the only state charge of this probe", + ); + + assert_fails( + "a code deposit", + db, + failing_account(minimal_envs(), created), + tx(TxKind::Create, init, U256::ZERO), + ); +} + +/// A program that never charges state gas never asks for a price, so a SALT environment that +/// cannot answer does not fail it. +#[test] +fn test_a_program_that_charges_no_state_gas_is_unaffected() { + let envs = failing_slot(minimal_envs(), CONTRACT, U256::from(SLOT)); + let envs = failing_account(envs, CONTRACT); + let envs = failing_account(envs, CALLER); + let code = BytecodeBuilder::default().stop().build(); + + let outcome = try_run(db(code), envs, call_contract()).expect("nothing was priced"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0); +} + +/// A failed lookup inside a frame that goes on to revert still fails the transaction: the cause +/// is recorded on the context, which the frame's own rollback does not undo. +#[test] +fn test_an_unpriceable_charge_in_a_reverting_frame_still_fails_the_transaction() { + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .revert_with_data([0xaa]) + .build(); + assert_fails( + "a reverting frame", + db(code), + failing_slot(minimal_envs(), CONTRACT, U256::from(SLOT)), + call_contract(), + ); +} + +/// A system-originated transaction is priced at the minimum bucket without reading SALT, so a +/// SALT environment that cannot answer does not stop the protocol's own work. +#[test] +fn test_a_system_call_is_unaffected_by_an_unreadable_bucket() { + use alloy_eips::eip4788::SYSTEM_ADDRESS; + use alloy_evm::Evm; + + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = failing_slot(minimal_envs(), CONTRACT, U256::from(SLOT)); + + let result = MegaEvm::new(salt_context(db(code), envs)) + .transact_system_call(SYSTEM_ADDRESS, CONTRACT, Bytes::new()) + .expect("a system call does not read SALT"); + assert!(result.result.is_success(), "{:?}", result.result); +} From 9cfb565e832e969ad440d6741b52d072b86229ce Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:19:29 +0800 Subject: [PATCH 134/201] feat(system): forward the Oracle's hints to the oracle service A sendHint(bytes32,bytes) call reaches OracleEnv::on_hint before the frame runs, and the Oracle's own bytecode runs after it: the interceptor is a side effect, not an answer. A call that carries value or was forwarded no gas cannot deliver a hint, because it reverts in the bytecode, so it forwards none. A STATICCALL does: sendHint is a view method. The payload the node materialises is counted on the transaction's data size before it is decoded, so bytes an ABI decoder ignores are paid for; the bytes are the transaction's, not the frame's, because the hint has left the machine by the time a frame could fail. --- crates/mega-evm/src/limit/frame_limit.rs | 7 + crates/mega-evm/src/limit/limit.rs | 13 ++ crates/mega-evm/src/system/intercept.rs | 15 +- crates/mega-evm/src/system/oracle.rs | 47 ++++++ crates/mega-evm/tests/system/main.rs | 1 + crates/mega-evm/tests/system/oracle.rs | 191 +++++++++++++++++++++++ 6 files changed, 269 insertions(+), 5 deletions(-) create mode 100644 crates/mega-evm/tests/system/oracle.rs diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index c324f3b7c..14103a4bc 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -131,6 +131,13 @@ impl FrameLimitTracker { self.total_used = self.total_used.saturating_add(usage); } + /// Counts `usage` on the transaction's own lane, whatever frame is running: what it stands + /// for is outside the state, so no frame's failure takes it back. + pub(crate) fn record_tx(&mut self, usage: LimitUsage) { + self.tx_used = self.tx_used.saturating_add(usage); + self.total_used = self.total_used.saturating_add(usage); + } + /// Takes `usage` back on the running frame's lane. Outside any frame nothing is taken back. pub(crate) fn refund(&mut self, usage: LimitUsage) { if let Some(lane) = self.lanes.last_mut() { diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 923572c74..d6622c6ff 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -192,6 +192,19 @@ impl AdditionalLimit { /* Transaction-level records */ + /// Counts the `bytes` of an Oracle hint, the payload a `sendHint` call hands to the node's + /// oracle service. + /// + /// The bytes are counted before the payload is decoded, so a caller cannot make the node + /// materialise a payload for free by appending bytes an ABI decoder ignores. They are the + /// transaction's, not the calling frame's: the hint has left the machine by the time the + /// frame could fail, so nothing takes it back. A crossing latches the transaction, and the + /// hint is not forwarded. + pub(crate) fn record_hint_bytes(&mut self, bytes: u64) -> LimitCheck { + self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); + self.check() + } + /// Records the account writes of the applied EIP-7702 authorities other than the sender: /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is /// one of them, from the transaction's `sender`. diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 92df99ae6..0e0f55abf 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -66,6 +66,8 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { /// interceptor and run their bytecode. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum InterceptedContract { + /// The Oracle: `sendHint` reaches the node's oracle service. + Oracle, /// `MegaAccessControl`: the volatile-data access switch. AccessControl, /// `MegaLimitControl`: what the running call has left. @@ -83,6 +85,7 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option Some(InterceptedContract::Oracle), 4 => Some(InterceptedContract::AccessControl), 5 => Some(InterceptedContract::LimitControl), _ => None, @@ -93,14 +96,13 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option( ctx: &mut MegaContext, inputs: &CallInputs, ) -> Option { match intercepted_contract(&inputs.target_address)? { + InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs), InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs), InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), } @@ -166,11 +168,14 @@ mod tests { intercepted_contract(&LIMIT_CONTROL_ADDRESS), Some(InterceptedContract::LimitControl) ); + assert_eq!( + intercepted_contract(&ORACLE_CONTRACT_ADDRESS), + Some(InterceptedContract::Oracle) + ); assert_eq!(intercepted_contract(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), None); assert_eq!(intercepted_contract(&SEQUENCER_REGISTRY_ADDRESS), None); - // The Oracle's and KeylessDeploy's interceptors follow; their addresses are in the - // range the dispatch tests, so they reach it as soon as they land. - assert_eq!(intercepted_contract(&ORACLE_CONTRACT_ADDRESS), None); + // KeylessDeploy's interceptor follows; its address is in the range the dispatch tests, + // so it reaches it as soon as it lands. assert_eq!(intercepted_contract(&KEYLESS_DEPLOY_ADDRESS), None); } diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 2e52355f7..853ce89d1 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -5,7 +5,12 @@ //! the service backend. Its Solidity source is //! `crates/system-contracts/contracts/Oracle.sol`. +use alloy_evm::Database; use alloy_primitives::{address, Address}; +use alloy_sol_types::SolCall; +use revm::{handler::FrameResult, interpreter::CallInputs}; + +use crate::{system::intercept::peek_selector, ExternalEnvTypes, MegaContext, OracleEnv}; /// The address of the Oracle system contract. pub const ORACLE_CONTRACT_ADDRESS: Address = address!("0x6342000000000000000000000000000000000001"); @@ -17,3 +22,45 @@ pub use mega_system_contracts::oracle::LATEST_CODE as ORACLE_CONTRACT_CODE; pub use mega_system_contracts::oracle::LATEST_CODE_HASH as ORACLE_CONTRACT_CODE_HASH; pub use mega_system_contracts::oracle::IOracle; + +/// Forwards the hint of a `sendHint(bytes32,bytes)` call to the node's oracle service, and +/// never answers the call: the deployed bytecode runs, whatever the interceptor did. +/// +/// `sendHint` is the one intercepted selector of the Oracle, and the only one that is a side +/// effect rather than an answer. The Oracle's storage methods are ordinary code, and reading +/// its storage through the node's oracle service is the Host's business. +/// +/// The hint is forwarded only by a call that can deliver it: +/// +/// - the call carries no value: `sendHint` is not payable, so a value-bearing call reverts in the +/// bytecode and its hint would be one the caller never sent; +/// - the call was forwarded gas: a call with none cannot run the dispatcher of the bytecode, so it +/// reverts, and its hint would be a free message to the service. +/// +/// A `STATICCALL` does forward: `sendHint` is a view method and writes nothing. +/// +/// The payload is counted toward the transaction's data size before it is decoded +/// ([`AdditionalLimit::record_hint_bytes`](crate::AdditionalLimit)), so trailing bytes an ABI +/// decoder ignores are paid for; a payload that crosses the transaction's limit is not +/// forwarded, and the limit stops the transaction at the frame the call would have started. +pub(crate) fn intercept( + ctx: &mut MegaContext, + inputs: &CallInputs, +) -> Option { + let selector = peek_selector(&inputs.input, ctx)?; + if selector != IOracle::sendHintCall::SELECTOR || + inputs.transfers_value() || + inputs.gas_limit == 0 + { + return None; + } + let payload = inputs.input.bytes(&*ctx); + if ctx.additional_limit.record_hint_bytes(payload.len() as u64).exceeded_limit() { + return None; + } + // Trailing bytes after a valid envelope are dropped by the decoder and a malformed envelope + // is refused; either way the payload is paid for above. + let call = IOracle::sendHintCall::abi_decode(&payload).ok()?; + ctx.external_envs().oracle_env.on_hint(inputs.caller, call.topic, call.data); + None +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index f58e54b17..589e59409 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -4,3 +4,4 @@ mod common; mod control; mod limit_control; +mod oracle; diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs new file mode 100644 index 000000000..cbe7db35b --- /dev/null +++ b/crates/mega-evm/tests/system/oracle.rs @@ -0,0 +1,191 @@ +//! The Oracle's hint path: which calls reach `OracleEnv::on_hint`, what they cost the +//! transaction's data size, and which do not reach it at all. + +use core::convert::Infallible; + +use alloy_evm::Evm; +use alloy_primitives::{Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, ORACLE_CONTRACT_ADDRESS}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + ExternalEnvs, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + RecordedHint, TestExternalEnvs, +}; +use revm::{ + bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, + context::result::ResultAndState, +}; + +use crate::common::{block, call_tx, calls_with, run, system_db, with_contract, CALLER, CONTRACT}; + +/// A topic and payload the tests send. +const TOPIC: B256 = B256::repeat_byte(0x7a); + +/// The calldata of `sendHint(TOPIC, data)`. +fn send_hint(data: &[u8]) -> Bytes { + Bytes::from( + IOracle::sendHintCall { topic: TOPIC, data: Bytes::copy_from_slice(data) }.abi_encode(), + ) +} + +/// Runs `tx` against an oracle environment that records the hints it receives, and returns what +/// the transaction produced, the hints and what the common execution layer counted. +fn run_with_oracle( + db: MemoryDatabase, + tx: MegaTransaction, +) -> (ResultAndState, Vec, LimitUsage) { + let envs = TestExternalEnvs::::new(); + let ctx = MegaContext::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs::from(envs.clone()), + ) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + let result = evm.transact_raw(tx).expect("the transaction is valid"); + let usage = evm.ctx().additional_limit().usage(); + (result, envs.recorded_hints(), usage) +} + +/// A `sendHint` transaction reaches the oracle service with the caller, the topic and the +/// payload, and the call itself succeeds through the contract's own bytecode. +#[test] +fn test_send_hint_reaches_the_oracle_service() { + let payload = b"a hint".to_vec(); + let (result, hints, _) = run_with_oracle( + system_db(), + call_tx(ORACLE_CONTRACT_ADDRESS, send_hint(&payload), U256::ZERO), + ); + + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + hints, + vec![RecordedHint { from: CALLER, topic: TOPIC, data: Bytes::from(payload) }], + ); +} + +/// The bytes the node materialised for the hint are counted on the transaction's data size, +/// trailing bytes the decoder ignores included. +#[test] +fn test_the_hint_payload_is_counted_on_the_transaction() { + let data = send_hint(b"a hint"); + let (_, hints, usage) = + run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO)); + assert_eq!(hints.len(), 1); + assert_eq!(usage.data_size, data.len() as u64); + + // The same call with bytes the ABI decoder drops pays for them too. + let padded: Vec = data.iter().copied().chain([0_u8; 64]).collect(); + let (_, hints, padded_usage) = + run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &padded, U256::ZERO)); + assert_eq!(hints.len(), 1, "the trailing bytes do not stop the decoding"); + assert_eq!(padded_usage.data_size, padded.len() as u64); +} + +/// A payload that does not decode is paid for and forwards nothing. +#[test] +fn test_a_malformed_payload_is_paid_for_and_not_forwarded() { + let data: Vec = + IOracle::sendHintCall::SELECTOR.iter().copied().chain([0xff_u8; 8]).collect(); + let (_, hints, usage) = + run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); + assert!(hints.is_empty(), "a payload that does not decode carries no hint"); + assert_eq!(usage.data_size, data.len() as u64); +} + +/// A `STATICCALL` forwards the hint: `sendHint` is a view method. +#[test] +fn test_a_static_call_forwards_the_hint() { + let data = send_hint(b"static"); + let code = calls_with(STATICCALL, ORACLE_CONTRACT_ADDRESS, &data, 0); + let (result, hints, _) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert!(result.result.is_success()); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].from, CONTRACT, "the frame that called is the sender of the hint"); +} + +/// A call that carries value forwards nothing: `sendHint` is not payable, so the call reverts +/// in the bytecode and the hint would be one the caller never sent. +#[test] +fn test_a_value_bearing_call_forwards_nothing() { + let data = send_hint(b"paid"); + let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &data, 1); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + let outcome = result.result.output().cloned().unwrap_or_default(); + let (status, _) = crate::common::split_outcome(&outcome); + assert!(!status, "the bytecode refuses the value"); + assert!(hints.is_empty()); + assert_eq!(usage.data_size, 0, "nothing was materialised for a hint that is not forwarded"); +} + +/// A call forwarded no gas forwards nothing: it cannot run the contract either, so its hint +/// would be a free message to the service. +#[test] +fn test_a_call_without_gas_forwards_nothing() { + use revm::bytecode::opcode::{POP, STOP}; + + let data = send_hint(b"free"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(0_u64) // gas + .append(CALL) + .append(POP) + .append(STOP) + .build(); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(result.result.is_success(), "the caller survives the failed call"); + assert!(hints.is_empty()); + assert_eq!(usage.data_size, 0); +} + +/// `CALLCODE` and `DELEGATECALL` never reach the interceptor, so they forward nothing. +#[test] +fn test_callcode_and_delegatecall_forward_nothing() { + let data = send_hint(b"scheme"); + for scheme in [CALLCODE, DELEGATECALL] { + let code = calls_with(scheme, ORACLE_CONTRACT_ADDRESS, &data, 0); + let (_, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert!(hints.is_empty(), "scheme {scheme:#x} must not reach the interceptor"); + assert_eq!(usage.data_size, 0); + } +} + +/// A selector the Oracle's interceptor does not know is not intercepted: the call runs the +/// contract's bytecode, which reverts on an unknown selector. +#[test] +fn test_an_unknown_selector_runs_the_bytecode() { + let (result, hints, usage) = run_with_oracle( + system_db(), + call_tx(ORACLE_CONTRACT_ADDRESS, [0xde, 0xad, 0xbe, 0xef], U256::ZERO), + ); + assert!(!result.result.is_success(), "the Oracle has no such method"); + assert!(hints.is_empty()); + assert_eq!(usage.data_size, 0); +} + +/// Reading the Oracle's storage is not intercepted: `getSlot` runs the contract's code. +#[test] +fn test_reading_a_slot_runs_the_bytecode() { + let db = system_db().account_storage(ORACLE_CONTRACT_ADDRESS, U256::from(3), U256::from(42)); + let data = IOracle::getSlotCall { slot: U256::from(3) }.abi_encode(); + let result = run(db, call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(result.result.output().unwrap()).unwrap(), + B256::from(U256::from(42)), + ); +} From 5ff137aabe8f8c643d19c61353b2d21b73af8b15 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:21:54 +0800 Subject: [PATCH 135/201] test(satin): pin the three ways a state gas charge is given back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A charge is undone at three kinds of moment, and the tests separate them: a rollback gives the charge back, an applied EIP-7702 authorization keeps it because the delegation it wrote survives the frame that reverted, and a price that could not be looked up charges nothing at all. Because every refill re-prices the charge that was made through the one hook, and a bucket's capacity is read once per transaction, the refill is the charge: what is fully undone nets zero at every multiplier, what is kept scales, and a transaction that writes a slot and restores it twice reads the capacity once. Two control arms keep the zeroes honest — the same programs with the frame surviving pay the crowded price. The CREATE probes build their init code at memory offset zero; reading it from the tail of the word left the earlier probe creating from three zero bytes rather than from the init code it names. --- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/salt.rs | 20 +- crates/mega-evm/tests/satin/salt_refund.rs | 375 +++++++++++++++++++++ 3 files changed, 389 insertions(+), 7 deletions(-) create mode 100644 crates/mega-evm/tests/satin/salt_refund.rs diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index c4c084835..d6fdcbc0e 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -11,6 +11,7 @@ mod precompile_gas; mod pricing_table; mod salt; mod salt_failure; +mod salt_refund; mod schedule; mod state; mod static_callee; diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 7ecd8e239..1b6235de8 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -172,18 +172,24 @@ pub(crate) fn value_call(target: Address) -> BytecodeBuilder { .append(CALL) } -/// `CREATE(0, 0, len)` of an init code already in memory at offset 0. -pub(crate) fn create_empty_contract() -> BytecodeBuilder { - // Init code `PUSH0 PUSH0 RETURN`: deploys zero bytes of runtime code. - let init: [u8; 3] = [PUSH0, PUSH0, RETURN]; +/// `CREATE(value = 0, offset = 0, size)` of `init_code`, written to memory first. +/// +/// `mstore` right-pads to a whole word, so the init code sits at offset 0 and the `CREATE` +/// reads it from there. +pub(crate) fn create_with(init_code: &[u8]) -> BytecodeBuilder { BytecodeBuilder::default() - .mstore(0, init) - .push_number(init.len() as u64) - .push_number(32u64 - init.len() as u64) + .mstore(0, init_code) + .push_number(init_code.len() as u64) + .push_number(0u64) .push_number(0u64) .append(CREATE) } +/// A `CREATE` whose init code `PUSH0 PUSH0 RETURN` deploys zero bytes of runtime code. +pub(crate) fn create_empty_contract() -> BytecodeBuilder { + create_with(&[PUSH0, PUSH0, RETURN]) +} + /// One state gas entry of the Satin schedule. pub(crate) fn entry(id: GasId) -> u64 { satin_gas_params().get(id) diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs new file mode 100644 index 000000000..4ab9fa91d --- /dev/null +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -0,0 +1,375 @@ +//! SALT pricing: giving a state gas charge back at the price it was made at. +//! +//! A state charge is undone at three kinds of moment, and all three re-price the charge that was +//! made rather than looking the number up again from somewhere else: +//! +//! - the same opcode takes its own write back (`SSTORE` 0 -> x -> 0), +//! - a frame that made a charge, or a frame whose child did not create the leaf the charge paid +//! for, does not survive, and +//! - the transaction itself reverts. +//! +//! Because the site is re-priced through the one hook, and because the multiplier of a bucket is +//! read once per transaction, the refill is the charge — a bucket cannot be read at one capacity +//! for the charge and another for the refill. These tests pin that: what is fully undone nets +//! zero at every multiplier, what is kept scales, and the environment is asked once. +//! +//! Against that, an applied EIP-7702 authorization is *not* undone by a frame that reverts +//! later: the delegation it wrote survives the revert, so the state gas it paid must survive it +//! too. + +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaEvm, MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, + context_interface::cfg::GasId, +}; + +use crate::salt::{ + authorization_tx, call_contract, capacity, create_with, crowded_account, crowded_slot, db, + entry, minimal_envs, run, salt_context, slot_bucket, try_run, tx, SaltEnvs, AUTHORITY, CALLER, + CONTRACT, EMPTY, GAS_LIMIT, +}; + +/// The contract a probe's inner frame runs in. +const SUB: Address = alloy_primitives::address!("0000000000000000000000000000000000c00005"); + +/// The slot every probe that writes storage uses. +const SLOT: u64 = 7; + +/// Runs `probe` at each multiplier and returns the state gas it netted, requiring the regular +/// ledger to be the same at all of them. +fn net_state_at( + ms: [u64; 3], + crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs, + probe: impl Fn() -> (MemoryDatabase, MegaTransaction), +) -> [u64; 3] { + let mut states = [0; 3]; + let mut regular = None; + for (i, m) in ms.into_iter().enumerate() { + let (db, tx) = probe(); + let outcome = try_run(db, crowd(minimal_envs(), m), tx).expect("the probe is valid"); + states[i] = outcome.gas.state; + let previous = *regular.get_or_insert(outcome.gas.regular); + assert_eq!(outcome.gas.regular, previous, "regular gas must not move with m"); + } + states +} + +/// `SSTORE` onto a fresh slot and straight back to zero: the restore refills exactly what the +/// set charged, so the transaction nets nothing on the state ledger however crowded the bucket +/// is — and the bucket is read once for both. +#[test] +fn test_a_slot_written_and_restored_nets_nothing_at_every_multiplier() { + let code = || { + BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .sstore(U256::from(SLOT), U256::ZERO) + .stop() + .build() + }; + let crowd = |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m); + + assert_eq!( + net_state_at([1, 2, 8], crowd, || (db(code()), call_contract())), + [0, 0, 0], + "the restore gives back what the set charged", + ); + + let envs = crowd(minimal_envs(), 8); + let outcome = run(db(code()), envs.clone(), call_contract()); + assert_eq!(outcome.gas.state, 0); + assert_eq!( + envs.bucket_queries(slot_bucket(CONTRACT, U256::from(SLOT))), + 1, + "one capacity read priced both the charge and the refill", + ); +} + +/// A creation whose init code reverts: the `CREATE` opcode charged its caller for the account +/// leaf upfront, and the frame that did not create it gives the charge back at the same price. +#[test] +fn test_a_reverting_creation_gives_its_upfront_charge_back() { + let created = CONTRACT.create(0); + let probe = || { + // Init code `PUSH0 PUSH0 REVERT`: the creation fails, so no account leaf is added. + let code = create_with(&[PUSH0, PUSH0, REVERT]).stop().build(); + (db(code), call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], move |envs, m| crowded_account(envs, created, m), probe), + [0, 0, 0], + "a creation that deployed nothing pays no state gas", + ); +} + +/// A `CALL` that charged for a new account leaf and then failed gives the charge back: the +/// caller cannot afford the transfer, so no account is created. +#[test] +fn test_a_failed_value_call_gives_its_new_account_charge_back() { + let probe = || { + let code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(EMPTY) + .push_number(1_000_000u64) + .append(CALL) + .stop() + .build(); + // The contract holds nothing, so the transfer the CALL attempts cannot be made. + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, code); + (db, call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_account(envs, EMPTY, m), probe), + [0, 0, 0], + "no account was created, so the upfront charge comes back", + ); +} + +/// A charge made two frames deep and rolled back with its frame comes back whole: the inner +/// frame wrote a slot in a crowded bucket and reverted. +#[test] +fn test_a_charge_in_a_reverting_inner_frame_comes_back_whole() { + let probe = || { + let sub = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .revert_with_data([0xaa]) + .build(); + let code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(SUB) + .push_number(2_000_000u64) + .append(CALL) + .stop() + .build(); + (db(code).account_code(SUB, sub), call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, SUB, U256::from(SLOT), m), probe), + [0, 0, 0], + "the frame's rollback takes its state charge with it", + ); +} + +/// What an inner frame keeps still scales: the same program with the inner frame succeeding +/// pays the crowded price, so the arms above are not passing because nothing was charged. +#[test] +fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { + let probe = || { + let sub = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(SUB) + .push_number(2_000_000u64) + .append(CALL) + .stop() + .build(); + (db(code).account_code(SUB, sub), call_contract()) + }; + + let set = entry(GasId::sstore_set_state_gas()); + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, SUB, U256::from(SLOT), m), probe), + [set, set * 2, set * 8], + ); +} + +/// The whole transaction reverting is the same story one level up: the outermost frame's charge +/// goes back with it. +#[test] +fn test_a_transaction_that_reverts_pays_no_state_gas() { + let probe = || { + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .revert_with_data([0xaa]) + .build(); + (db(code), call_contract()) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m), probe), + [0, 0, 0], + ); +} + +/// An applied EIP-7702 authorization is not a frame's doing: the delegation it wrote outlives a +/// frame that reverts afterwards, and so does the state gas it paid. +#[test] +fn test_an_applied_authorization_keeps_its_charge_through_a_revert() { + let authority_charges = + entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()); + let probe = || { + let code = BytecodeBuilder::default().revert_with_data([0xaa]).build(); + (db(code), authorization_tx(CONTRACT)) + }; + + assert_eq!( + net_state_at([1, 2, 8], |envs, m| crowded_account(envs, AUTHORITY, m), probe), + [authority_charges, authority_charges * 2, authority_charges * 8], + "the authority's leaf and its delegation bytes are still there after the revert", + ); + + // And the delegation really did survive: the authority carries the designation. + let outcome = try_run( + db(BytecodeBuilder::default().revert_with_data([0xaa]).build()), + crowded_account(minimal_envs(), AUTHORITY, 8), + authorization_tx(CONTRACT), + ) + .expect("the transaction is valid"); + assert!( + outcome.state.get(&AUTHORITY).is_some_and(|account| account + .info + .code + .as_ref() + .is_some_and(|code| !code.is_empty())), + "the authority kept its delegation", + ); +} + +/// A creation whose deposit is refused gives back everything it charged: the account leaf it +/// paid for upfront and the bytes it never deposited. +#[test] +fn test_a_refused_code_deposit_pays_no_state_gas() { + let created = CALLER.create(0); + let probe = || { + // Init code returning a single `0xEF` byte, which EIP-3541 refuses to deploy. + let init = BytecodeBuilder::default() + .mstore(0, [0xefu8]) + .push_number(1u64) + .push_number(0u64) + .append(RETURN) + .build(); + (db(Bytes::new()), tx(TxKind::Create, init, U256::ZERO)) + }; + + assert_eq!( + net_state_at([1, 2, 8], move |envs, m| crowded_account(envs, created, m), probe), + [0, 0, 0], + "nothing was deployed, so nothing is owed", + ); +} + +/// A charge kept beside one given back: the kept one scales, the other nets out, and the +/// transaction pays exactly the difference. +#[test] +fn test_a_kept_charge_and_a_restored_one_settle_independently() { + const KEPT: u64 = 3; + let probe = || { + let code = BytecodeBuilder::default() + .sstore(U256::from(KEPT), U256::from(1)) + .sstore(U256::from(SLOT), U256::from(1)) + .sstore(U256::from(SLOT), U256::ZERO) + .stop() + .build(); + (db(code), call_contract()) + }; + let crowd = |envs: SaltEnvs, m: u64| { + let envs = crowded_slot(envs, CONTRACT, U256::from(KEPT), m); + crowded_slot(envs, CONTRACT, U256::from(SLOT), m) + }; + + let set = entry(GasId::sstore_set_state_gas()); + assert_eq!(net_state_at([1, 2, 8], crowd, probe), [set, set * 2, set * 8]); +} + +/// A crowded bucket cannot make a transaction owe more than it charged: the refill of a charge +/// is the charge, so a restore never leaves the state ledger negative or the reservoir richer +/// than the sender's budget. +#[test] +fn test_a_restore_never_gives_back_more_than_it_charged() { + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .sstore(U256::from(SLOT), U256::ZERO) + .stop() + .build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + + let outcome: MegaTransactionOutcome = + MegaEvm::new(salt_context(db(code), envs)).execute_transaction(call_contract()).unwrap(); + + assert_eq!(outcome.gas.state, 0, "the state ledger nets to zero, not below it"); + assert!( + outcome.gas.reservoir_remaining <= GAS_LIMIT, + "a refill cannot put more in the reservoir than the transaction brought", + ); + assert!(outcome.gas.gas_used > 0 && outcome.gas.gas_used <= GAS_LIMIT); +} + +/// The whole matrix at one multiplier, side by side, so the three refund classes are readable in +/// one place: a rollback gives the charge back, an authorization keeps it, and a bucket is read +/// once whatever happens to the charge afterwards. +#[test] +fn test_the_refund_classes_side_by_side() { + let set = entry(GasId::sstore_set_state_gas()); + let authority_charges = + entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()); + + let kept = run( + db(BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build()), + crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8), + call_contract(), + ); + assert_eq!(kept.gas.state, set * 8, "a write that stays pays the crowded price"); + + let rolled_back = try_run( + db(BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .revert_with_data([0xaa]) + .build()), + crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8), + call_contract(), + ) + .expect("the transaction is valid"); + assert_eq!(rolled_back.gas.state, 0, "a write that is rolled back pays nothing"); + + let authorized = try_run( + db(BytecodeBuilder::default().revert_with_data([0xaa]).build()), + crowded_account(minimal_envs(), AUTHORITY, 8), + authorization_tx(CONTRACT), + ) + .expect("the transaction is valid"); + assert_eq!( + authorized.gas.state, + authority_charges * 8, + "an applied authorization pays even though the frame reverted", + ); +} + +/// The capacity a bucket is read at is fixed for the transaction: one read serves the charge and +/// the refill, so the two cannot disagree even if the environment's answer would. +#[test] +fn test_the_capacity_behind_a_charge_and_its_refill_is_read_once() { + let bucket = slot_bucket(CONTRACT, U256::from(SLOT)); + let envs = minimal_envs().with_bucket_capacity(bucket, capacity(8)); + let code = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .sstore(U256::from(SLOT), U256::ZERO) + .sstore(U256::from(SLOT), U256::from(2)) + .sstore(U256::from(SLOT), U256::ZERO) + .stop() + .build(); + + let outcome = run(db(code), envs.clone(), call_contract()); + + assert_eq!(outcome.gas.state, 0, "every set was restored"); + assert_eq!(envs.bucket_queries(bucket), 1, "two charges and two refills, one capacity read"); +} From cb669ea289fbef9af883a78ce6cd0087de741f3b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:22:54 +0800 Subject: [PATCH 136/201] test(satin): add the SALT scaling rows to the pricing table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One slot-scoped probe and one account-scoped probe, each at the minimum bucket and at two larger ones, so what the multiplier does to a transaction is in the same units as the measured rows above it — and the minimum-bucket row of each is the measured row, which is where the reader sees that turning SALT pricing on moved nothing. A second test reads the section back and checks it says what it claims: the regular ledger is the same at every multiplier and the state ledger is the minimum bucket's times the multiplier. --- crates/mega-evm/tests/satin/pricing-table.md | 13 ++ crates/mega-evm/tests/satin/pricing_table.rs | 120 ++++++++++++++++++- 2 files changed, 130 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index 70eb328a8..ff4f1592b 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -75,6 +75,19 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | create transaction deploying 0 bytes | 207687 | 24087 | 183600 | 0 | | create transaction deploying 32 bytes | 256668 | 24108 | 232560 | 0 | +## SALT scaling + +The same probes again, with the SALT bucket the state charge lands in at `m` times the minimum capacity. `m` multiplies the state ledger and nothing else: the regular column is the same on all three rows of a probe, and `gas used` grows by exactly the state column's growth, because these probes run below the execution cap and every state charge spills onto the regular budget. + +| Probe | m | gas used | regular | state | history | +|---|---:|---:|---:|---:|---:| +| SSTORE 0 -> 1 | 1 | 135026 | 37106 | 97920 | 0 | +| SSTORE 0 -> 1 | 2 | 232946 | 37106 | 195840 | 0 | +| SSTORE 0 -> 1 | 8 | 820466 | 37106 | 783360 | 0 | +| value CALL to an empty account | 1 | 232921 | 49321 | 183600 | 0 | +| value CALL to an empty account | 2 | 416521 | 49321 | 367200 | 0 | +| value CALL to an empty account | 8 | 1518121 | 49321 | 1468800 | 0 | + ## The execution cap Satin pins `tx_gas_limit_cap` at 200000000, so a transaction's EIP-8037 reservoir is `max(0, gas_limit - intrinsic gas)` above it. Every probe above runs well below the cap, so its reservoir is empty and each state charge comes out of the regular budget. diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index bc08f1115..9389ff4ba 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -1,9 +1,11 @@ //! The Satin schedule and what it charges, rendered into `pricing-table.md` next to this file. //! -//! Two kinds of row. A *schedule* row reads one entry out of the Osaka, the Amsterdam and the +//! Three kinds of row. A *schedule* row reads one entry out of the Osaka, the Amsterdam and the //! Satin schedules, so the two changes Satin makes are visible side by side. A *measured* row //! runs one probe transaction and reports what it cost, split across the ledgers — every number -//! there comes from a transaction the engine ran, not from arithmetic on the schedule. +//! there comes from a transaction the engine ran, not from arithmetic on the schedule. A *SALT +//! scaling* row runs one of those probes again with the bucket its state charge lands in at a +//! larger capacity, so what the multiplier does to each ledger is visible in the same units. //! //! The test renders the table and compares it to the checked-in file, so a change to either the //! schedule or the engine that moves a number fails here. Regenerate it after an intentional @@ -28,7 +30,10 @@ use revm::{ primitives::hardfork::SpecId, }; -use crate::common::{call, context, create, runs_at_measurement_prices}; +use crate::{ + common::{call, context, create, runs_at_measurement_prices}, + salt::{crowded_account, crowded_slot, minimal_envs, salt_context, SaltEnvs}, +}; const CALLER: Address = address!("0000000000000000000000000000000000b00000"); const CONTRACT: Address = address!("0000000000000000000000000000000000b00001"); @@ -60,6 +65,14 @@ struct Measured { gas: MegaGasUsage, } +/// One SALT scaling row: a probe run with the bucket its state charge lands in at multiplier +/// `m`. +struct Scaled { + probe: &'static str, + m: u64, + gas: MegaGasUsage, +} + /// Runs `tx` on `db` and reports what it spent by ledger. The probe must succeed. fn measure(probe: &'static str, db: MemoryDatabase, tx: MegaTransaction) -> Measured { let mut evm = MegaEvm::new(context(db)); @@ -68,6 +81,20 @@ fn measure(probe: &'static str, db: MemoryDatabase, tx: MegaTransaction) -> Meas Measured { probe, gas: outcome.gas } } +/// Runs `tx` on `db` with `envs` as the SALT environment and reports what it spent. +fn measure_scaled( + probe: &'static str, + m: u64, + db: MemoryDatabase, + tx: MegaTransaction, + envs: SaltEnvs, +) -> Scaled { + let mut evm = MegaEvm::new(salt_context(db, envs)); + let outcome = evm.execute_transaction(tx).expect("the probe is valid"); + assert!(outcome.result.is_success(), "{probe} at m = {m}: {:?}", outcome.result); + Scaled { probe, m, gas: outcome.gas } +} + /// Runs `code` in `CONTRACT` as a plain call from `CALLER`. fn measure_call(probe: &'static str, code: BytecodeBuilder) -> Measured { let code = code.stop().build(); @@ -149,6 +176,25 @@ fn render() -> String { ); } + out.push_str("\n## SALT scaling\n\n"); + out.push_str( + "The same probes again, with the SALT bucket the state charge lands in at `m` times the \ + minimum capacity. `m` multiplies the state ledger and nothing else: the regular column \ + is the same on all three rows of a probe, and `gas used` grows by exactly the state \ + column's growth, because these probes run below the execution cap and every state \ + charge spills onto the regular budget.\n\n", + ); + out.push_str( + "| Probe | m | gas used | regular | state | history |\n|---|---:|---:|---:|---:|---:|\n", + ); + for row in scaled() { + let _ = writeln!( + out, + "| {} | {} | {} | {} | {} | {} |", + row.probe, row.m, row.gas.gas_used, row.gas.regular, row.gas.state, row.gas.history + ); + } + out.push_str("\n## The execution cap\n\n"); let _ = writeln!( out, @@ -191,6 +237,34 @@ fn measured() -> Vec { ] } +/// The SALT scaling rows, in the order the table lists them. +/// +/// One slot-scoped charge and one account-scoped charge, each at the minimum bucket and at two +/// larger ones. The `m = 1` row of each is the same number as the measured row above it. +fn scaled() -> Vec { + const SLOT: u64 = 0; + let mut rows = Vec::new(); + for m in [1, 2, 8] { + rows.push(measure_scaled( + "SSTORE 0 -> 1", + m, + db(sstore(SLOT, 1).stop().build()), + call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT), + crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), m), + )); + } + for m in [1, 2, 8] { + rows.push(measure_scaled( + "value CALL to an empty account", + m, + db(value_call(EMPTY).stop().build()), + call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT), + crowded_account(minimal_envs(), EMPTY, m), + )); + } + rows +} + /// The rendered table is the one checked in. `UPDATE_SATIN_PRICING_TABLE=1` writes it instead. #[test] fn test_the_pricing_table_is_up_to_date() { @@ -257,3 +331,43 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { "the entries Satin prices differently from Amsterdam" ); } + +/// The SALT scaling section says what it claims: on each probe the regular ledger is the same at +/// every multiplier and the state ledger is the minimum bucket's times the multiplier. Read off +/// the rendered table rather than the engine, so the table cannot drift from the claim above it. +#[test] +fn test_the_table_shows_the_multiplier_on_the_state_ledger_alone() { + if runs_at_measurement_prices() { + return; + } + let rendered = render(); + let section = rendered.split("## SALT scaling").nth(1).expect("the scaling section"); + let section = section.split("\n## ").next().expect("the section ends at the next heading"); + + let mut baselines: Vec<(String, u64, u64)> = Vec::new(); + for line in section.lines().filter(|l| l.starts_with("| ") && l.matches('|').count() == 7) { + let mut cells = line.split('|').map(str::trim).skip(1); + let probe = cells.next().expect("probe").to_string(); + let m = cells.next().expect("m"); + if m == "m" { + continue; + } + let m: u64 = m.parse().expect("m is a number"); + let _gas_used = cells.next(); + let regular: u64 = cells.next().expect("regular").parse().expect("a number"); + let state: u64 = cells.next().expect("state").parse().expect("a number"); + + match baselines.iter().find(|(name, ..)| *name == probe) { + None => { + assert_eq!(m, 1, "{probe}: the first row of a probe is the minimum bucket"); + baselines.push((probe, regular, state)); + } + Some((_, base_regular, base_state)) => { + assert_eq!(regular, *base_regular, "{probe} at m = {m}: regular gas moved"); + assert_eq!(state, base_state * m, "{probe} at m = {m}: state gas"); + } + } + } + assert_eq!(baselines.len(), 2, "one slot-scoped probe and one account-scoped probe"); + assert!(baselines.iter().all(|(_, _, state)| *state > 0), "a probe must charge state gas"); +} From db42781ee8a8cd960480046663d652fbc9762711 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:24:45 +0800 Subject: [PATCH 137/201] feat(system): dispatch KeylessDeploy calls and charge their overhead A keylessDeploy(bytes,uint256) transaction is recognised at depth 0, charged the fixed 100,000 regular gas the decoding, the signer recovery and the preparation cost, and handed on to the keyless rewrite hook. The hook is native keyless deployment's and is a pass-through today, so the charged call runs the deployed bytecode and reverts with NotIntercepted(). A call a contract makes is not dispatched, so a deployment's answer is never something an inner caller reads off its return data; a call that carries value is refused with the ABI's NoEtherTransfer(); a call that was not forwarded the overhead is answered out of gas. An interceptor can now charge the frame it hands on, which is why MegaEvm::intercept takes the frame mutably. --- crates/mega-evm/src/evm/execution.rs | 13 +- crates/mega-evm/src/system/intercept.rs | 26 ++- .../mega-evm/src/system/keyless/dispatch.rs | 73 ++++++++ crates/mega-evm/src/system/keyless/mod.rs | 8 + crates/mega-evm/tests/system/keyless.rs | 160 ++++++++++++++++++ crates/mega-evm/tests/system/main.rs | 1 + 6 files changed, 269 insertions(+), 12 deletions(-) create mode 100644 crates/mega-evm/src/system/keyless/dispatch.rs create mode 100644 crates/mega-evm/tests/system/keyless.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 5fddc6332..867869f91 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -253,7 +253,8 @@ impl EvmTr for MegaEvm MegaEvm { /// contract. A creation reaches no interceptor either. /// /// An answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles - /// like a frame revm ran. What each contract answers is in the `system` module. + /// like a frame revm ran. An interceptor that lets the frame run may charge it instead of + /// answering it, which is why the frame is taken mutably. What each contract answers is in + /// the `system` module. #[inline] - fn intercept(&mut self, frame_init: &FrameInit) -> Option { - let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; + fn intercept(&mut self, frame_init: &mut FrameInit) -> Option { + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return None }; if !matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { return None; } - crate::system::intercept(&mut self.inner.ctx, inputs) + crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth) } /// The keyless deployment rewrite: a keyless deployment call turned into the native creation diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 0e0f55abf..8e7fdcf90 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -18,8 +18,9 @@ //! reverts with `NotIntercepted()`. A selector matches on its own four bytes, whatever follows //! them. //! 4. **The value policy.** A method that takes no value answers a value-bearing call with -//! `NonZeroTransfer()` ([`reject_non_zero_transfer`]). The policy is per method, after the -//! selector matched, so a value-bearing call to an unknown selector still falls through. +//! `NonZeroTransfer()` ([`reject_non_zero_transfer`]), or with the error its own ABI names. The +//! policy is per method, after the selector matched, so a value-bearing call to an unknown +//! selector still falls through. //! //! # The answer //! @@ -68,6 +69,8 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { pub(crate) enum InterceptedContract { /// The Oracle: `sendHint` reaches the node's oracle service. Oracle, + /// `KeylessDeploy`: `keylessDeploy` deploys a pre-EIP-155 transaction. + KeylessDeploy, /// `MegaAccessControl`: the volatile-data access switch. AccessControl, /// `MegaLimitControl`: what the running call has left. @@ -86,6 +89,7 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option Some(InterceptedContract::Oracle), + 3 => Some(InterceptedContract::KeylessDeploy), 4 => Some(InterceptedContract::AccessControl), 5 => Some(InterceptedContract::LimitControl), _ => None, @@ -95,14 +99,21 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option( ctx: &mut MegaContext, - inputs: &CallInputs, + inputs: &mut CallInputs, + depth: usize, ) -> Option { match intercepted_contract(&inputs.target_address)? { InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs), + InterceptedContract::KeylessDeploy => crate::system::keyless::intercept(ctx, inputs, depth), InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs), InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), } @@ -172,11 +183,12 @@ mod tests { intercepted_contract(&ORACLE_CONTRACT_ADDRESS), Some(InterceptedContract::Oracle) ); + assert_eq!( + intercepted_contract(&KEYLESS_DEPLOY_ADDRESS), + Some(InterceptedContract::KeylessDeploy) + ); assert_eq!(intercepted_contract(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), None); assert_eq!(intercepted_contract(&SEQUENCER_REGISTRY_ADDRESS), None); - // KeylessDeploy's interceptor follows; its address is in the range the dispatch tests, - // so it reaches it as soon as it lands. - assert_eq!(intercepted_contract(&KEYLESS_DEPLOY_ADDRESS), None); } /// An address next to the range, and one that shares the last byte but not the prefix, are diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs new file mode 100644 index 000000000..4360ec4b9 --- /dev/null +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -0,0 +1,73 @@ +//! The dispatch of `KeylessDeploy` calls. +//! +//! A `keylessDeploy(bytes,uint256)` call is recognised here, charged the fixed overhead, and +//! handed to the keyless rewrite hook, which turns it into the creation it stands for. The +//! rewrite is native keyless deployment's; until it lands the recognised call runs the deployed +//! bytecode, which reverts with `NotIntercepted()`, and the overhead is charged all the same. + +use alloy_evm::Database; +use alloy_primitives::Bytes; +use alloy_sol_types::{SolCall, SolError}; +use revm::{ + handler::FrameResult, + interpreter::{CallInputs, InstructionResult}, +}; + +use crate::{ + synthetic_call_result, + system::{ + intercept::peek_selector, + keyless::{IKeylessDeploy, KEYLESS_DEPLOY_OVERHEAD_GAS}, + }, + ExternalEnvTypes, MegaContext, +}; + +/// Recognises a `keylessDeploy` call and charges it, or answers it when it cannot go on. +/// +/// # What is dispatched +/// +/// Only a transaction reaches the deployment: `depth` is the depth of the frame the call would +/// start, and a call a contract makes (`depth > 0`) is not dispatched, so the deployment's +/// answer is never something an inner caller can read off its own return data. A call whose +/// selector is not `keylessDeploy` is not dispatched either; both run the deployed bytecode, +/// which reverts with `NotIntercepted()`. +/// +/// # What it charges +/// +/// A dispatched call pays [`KEYLESS_DEPLOY_OVERHEAD_GAS`] of regular gas before anything else: +/// the frame is handed that much less gas, so the caller pays it whatever the deployment does. +/// A call that was not forwarded enough gas to pay it is answered out of gas, as a frame that +/// ran out is. +/// +/// # What it refuses +/// +/// A `keylessDeploy` call carries no value: the deployment is made by the transaction's signer, +/// not by the caller, and the contract holds no balance. A call that carries one is answered +/// with the ABI's own `NoEtherTransfer()`, after the overhead was charged. +pub(crate) fn intercept( + ctx: &MegaContext, + inputs: &mut CallInputs, + depth: usize, +) -> Option { + if depth != 0 { + return None; + } + let selector = peek_selector(&inputs.input, ctx)?; + if selector != IKeylessDeploy::keylessDeployCall::SELECTOR { + return None; + } + let Some(charged) = inputs.gas_limit.checked_sub(KEYLESS_DEPLOY_OVERHEAD_GAS) else { + let mut result = synthetic_call_result(inputs, InstructionResult::OutOfGas, Bytes::new()); + result.gas_mut().spend_all(); + return Some(result); + }; + inputs.gas_limit = charged; + if !inputs.call_value().is_zero() { + return Some(synthetic_call_result( + inputs, + InstructionResult::Revert, + Bytes::from_static(&IKeylessDeploy::NoEtherTransfer::SELECTOR), + )); + } + None +} diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 22f445e92..1fdb4f4b2 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -9,12 +9,15 @@ //! The rest of the module is data-only: decoding the pre-EIP-155 transaction, recovering its //! signer, deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. +mod dispatch; mod error; mod tx; pub use error::*; pub use tx::*; +pub(crate) use dispatch::intercept; + use alloy_primitives::{address, Address}; /// The address of the `KeylessDeploy` system contract. @@ -27,3 +30,8 @@ pub use mega_system_contracts::keyless_deploy::LATEST_CODE as KEYLESS_DEPLOY_COD pub use mega_system_contracts::keyless_deploy::LATEST_CODE_HASH as KEYLESS_DEPLOY_CODE_HASH; pub use mega_system_contracts::keyless_deploy::IKeylessDeploy; + +/// The regular gas a `keylessDeploy` call pays before the deployment runs: the fixed cost of +/// decoding the transaction, recovering its signer and preparing the deployment. Provisional, +/// as the rest of the engine's numbers are. +pub const KEYLESS_DEPLOY_OVERHEAD_GAS: u64 = 100_000; diff --git a/crates/mega-evm/tests/system/keyless.rs b/crates/mega-evm/tests/system/keyless.rs new file mode 100644 index 000000000..2ae63e188 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless.rs @@ -0,0 +1,160 @@ +//! The `KeylessDeploy` dispatch: which calls are recognised, what they are charged, and which +//! run the deployed bytecode instead. + +use alloy_primitives::{Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::system::keyless::{ + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, +}; +use revm::{ + bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, + context::result::ExecutionResult, +}; + +use crate::common::{ + call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, + CONTRACT, GAS_LIMIT, +}; + +const KEYLESS_DEPLOY: [u8; 4] = IKeylessDeploy::keylessDeployCall::SELECTOR; +const NOT_INTERCEPTED: [u8; 4] = IKeylessDeploy::NotIntercepted::SELECTOR; +const NO_ETHER_TRANSFER: [u8; 4] = IKeylessDeploy::NoEtherTransfer::SELECTOR; + +/// The calldata of a `keylessDeploy` call carrying `transaction` bytes. +fn keyless_deploy(transaction: &[u8]) -> Bytes { + Bytes::from( + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::copy_from_slice(transaction), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode(), + ) +} + +/// The same calldata with a selector the contract does not know, so the call is not dispatched +/// and pays no overhead. +fn unknown_selector(data: &Bytes) -> Bytes { + let mut data = data.to_vec(); + data[0] ^= 0xff; + Bytes::from(data) +} + +/// A dispatched `keylessDeploy` transaction pays the fixed overhead, and then runs the deployed +/// bytecode, because the rewrite that turns it into a deployment is not here yet. +#[test] +fn test_a_keyless_deploy_transaction_pays_the_overhead() { + let data = keyless_deploy(b"a transaction"); + let dispatched = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO)); + let plain = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&data), U256::ZERO)); + + assert_eq!( + revert_data(&dispatched), + Bytes::from_static(&NOT_INTERCEPTED), + "the deployed bytecode runs after the charge", + ); + // What each transaction spent, not what its receipt reports: the calldata floor of + // EIP-7623 lifts the receipt of the cheaper one above what it spent. + let charged = dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent(); + assert!( + (KEYLESS_DEPLOY_OVERHEAD_GAS..KEYLESS_DEPLOY_OVERHEAD_GAS + 1_000).contains(&charged), + "{charged} is not the fixed overhead plus what the two paths differ by in the bytecode", + ); +} + +/// A call that carries value is refused with the ABI's own `NoEtherTransfer()`, and the +/// overhead is charged all the same. +#[test] +fn test_a_value_bearing_call_is_refused() { + let data = keyless_deploy(b"a transaction"); + let code = calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &data, 1); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, returned) = split_outcome(&outcome); + + // A call from a contract is at depth 1, where nothing is dispatched: the bytecode runs and + // refuses the value itself, with the empty revert data of a non-payable method. + assert!(!status); + assert!(returned.is_empty(), "the bytecode refuses the value before it reaches the method"); + + // The transaction itself is at depth 0, where the dispatch refuses it. + let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::from(1))); + assert_eq!(revert_data(&result), Bytes::from_static(&NO_ETHER_TRANSFER)); + assert!( + result.result.gas().total_gas_spent() > KEYLESS_DEPLOY_OVERHEAD_GAS, + "the refusal keeps the overhead", + ); +} + +/// A call a contract makes is not dispatched, whatever its selector: only a transaction +/// deploys. The deployed bytecode runs and reverts with `NotIntercepted()`, and no overhead is +/// charged. +#[test] +fn test_a_call_from_a_contract_is_not_dispatched() { + let data = keyless_deploy(b"a transaction"); + for scheme in [CALL, STATICCALL, CALLCODE, DELEGATECALL] { + let code = calls_with(scheme, KEYLESS_DEPLOY_ADDRESS, &data, 0); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, returned) = split_outcome(&outcome); + assert!(!status, "scheme {scheme:#x}"); + assert_eq!(returned, NOT_INTERCEPTED, "scheme {scheme:#x}"); + assert!( + result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS, + "scheme {scheme:#x} paid the overhead of a dispatch that did not happen", + ); + } +} + +/// A selector the contract does not know, and an input too short to hold one, are not +/// dispatched: the bytecode runs and reverts on its own. +#[test] +fn test_an_unknown_selector_is_not_dispatched() { + let data = keyless_deploy(b"a transaction"); + for input in [unknown_selector(&data), Bytes::new(), Bytes::from(KEYLESS_DEPLOY[..3].to_vec())] + { + let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, &input, U256::ZERO)); + assert!(!result.result.is_success()); + assert!( + result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS, + "an input of {} bytes paid an overhead it does not owe", + input.len(), + ); + } +} + +/// A `keylessDeploy` call the caller did not forward the overhead to is answered out of gas, +/// as a frame that ran out of gas is: the gas it was forwarded is spent. +#[test] +fn test_a_call_that_cannot_pay_the_overhead_runs_out_of_gas() { + let data = keyless_deploy(b"a transaction"); + let gas_limit = 60_000; + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.gas_limit = gas_limit; + + let result = run(system_db(), tx); + assert!( + matches!(result.result, ExecutionResult::Halt { .. }), + "{:?} is not an out-of-gas halt", + result.result, + ); + assert_eq!(result.result.tx_gas_used(), gas_limit, "an out-of-gas frame spends what it had",); +} + +/// The overhead is fixed: an empty deployment transaction is charged the same as one with a +/// payload. +#[test] +fn test_the_overhead_does_not_depend_on_the_payload() { + let charge_of = |payload: &[u8]| { + let data = keyless_deploy(payload); + let dispatched = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO)); + let plain = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&data), U256::ZERO)); + assert!(dispatched.result.gas().total_gas_spent() < GAS_LIMIT); + dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent() + }; + let (empty, payload) = (charge_of(b""), charge_of(&[0xab; 512])); + assert!(empty >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{empty} is below the fixed overhead"); + assert!(payload >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{payload} is below the fixed overhead"); +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index 589e59409..6d4d2ec6e 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -3,5 +3,6 @@ mod common; mod control; +mod keyless; mod limit_control; mod oracle; From d4c42f7fd7f966f85eb4873d30f85eaafaaeb7c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:25:17 +0800 Subject: [PATCH 138/201] bench(evm): price a transaction against a crowded SALT environment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two workloads draw one EIP-8037 state gas charge per slot or per account, and each is benchmarked twice: against the default environment, where every bucket is minimal, and against one holding every bucket at eight times the minimum capacity. The gap is what the pricing hook costs on the hot path — one environment read per bucket and a cache hit per charge after it. Both arms run the same transaction at the same gas limit, and a check before the measurement pins that the crowded arm really pays eight times the state gas, so the pair cannot quietly become two runs of the same thing. --- crates/mega-evm/benches/transact.rs | 108 ++++++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index ea24143ee..a7b56016d 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -9,20 +9,27 @@ //! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the //! `SSTORE` wrapper's commit and refund. //! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit. +//! +//! Two more run through `MegaEvm` alone, because they price something op-revm has no equivalent +//! of: `salt_storage_writes` and `salt_new_accounts` each draw one EIP-8037 state gas charge per +//! slot or per account, and are benchmarked twice — once against the default environment, where +//! every bucket is minimal, and once (`/crowded`) against a SALT environment holding every bucket +//! at eight times the minimum capacity. The gap is what the pricing hook costs on the hot path: +//! one environment read per bucket and a cache hit per charge after it. #![allow(missing_docs)] use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U160, U256}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaSpecId, + ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, MIN_BUCKET_SIZE, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, PUSH0, - PUSH1, SSTORE, STOP, SUB, SWAP1, + ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, POP, + PUSH0, PUSH1, SSTORE, STOP, SUB, SWAP1, }, context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, inspector::NoOpInspector, @@ -34,6 +41,8 @@ const CALLEE: Address = address!("0x0000000000000000000000000000000000100001"); const RECURSIVE: Address = address!("0x0000000000000000000000000000000000100002"); const WRITER: Address = address!("0x0000000000000000000000000000000000100003"); const LOGGER: Address = address!("0x0000000000000000000000000000000000100004"); +const SALT_WRITER: Address = address!("0x0000000000000000000000000000000000100005"); +const SALT_CALLER: Address = address!("0x0000000000000000000000000000000000100006"); /// Depth the recursive contract reaches. const DEPTH: u8 = 64; @@ -43,6 +52,16 @@ const REPEAT: u64 = 200; /// Offset of the `JUMPDEST` the recursion ends at. const DONE: u8 = 0x1f; +/// Slots written, and accounts created, by the two SALT workloads. Small enough that the whole +/// transaction fits in [`SALT_GAS_LIMIT`] at the crowded multiplier. +const SALT_REPEAT: u64 = 16; +/// How many minimum buckets a crowded bucket holds in the `/crowded` arms. +const SALT_MULTIPLIER: u64 = 8; +/// Room for `SALT_REPEAT` state charges at `SALT_MULTIPLIER`, on both arms alike. +const SALT_GAS_LIMIT: u64 = 60_000_000; +/// The first of `SALT_REPEAT` consecutive addresses the value calls create. +const SALT_ACCOUNT_BASE: u64 = 0x200000; + /// Reads `n` from calldata; while `n > 0` it writes slot `n`, logs, and calls itself with `n - 1`. fn recursive_code() -> Bytes { #[rustfmt::skip] @@ -86,6 +105,48 @@ fn logger_code() -> Bytes { code.stop().build() } +/// Writes `SALT_REPEAT` fresh slots, each drawing one state gas charge the pricing hook prices. +fn salt_writer_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 0..SALT_REPEAT { + code = code.sstore(U256::from(slot), U256::from(1)); + } + code.stop().build() +} + +/// Sends one wei to each of `SALT_REPEAT` accounts that do not exist, each drawing one +/// new-account state gas charge. +fn salt_caller_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for i in 0..SALT_REPEAT { + code = code + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(1_u64) + .push_address(Address::from(U160::from(SALT_ACCOUNT_BASE + i))) + .push_number(1_000_000_u64) + .append(CALL) + .append(POP); + } + code.stop().build() +} + +/// A SALT environment holding every bucket at `m` times the minimum capacity. +fn salt_envs(m: u64) -> TestExternalEnvs { + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * m) +} + +/// A context over `db` reading `envs`. +fn salt_context( + db: MemoryDatabase, + envs: TestExternalEnvs, +) -> MegaContext { + MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, ExternalEnvs::from(envs)) + .with_chain(zero_fee_l1_block_info()) +} + fn call_tx(to: Address, data: Bytes, gas_limit: u64) -> OpTransaction { op_transaction(TxEnv { caller: CALLER, @@ -125,7 +186,10 @@ fn bench_transact(c: &mut Criterion) { .account_balance(CALLEE, U256::from(1)) .account_code(RECURSIVE, recursive_code()) .account_code(WRITER, writer_code()) - .account_code(LOGGER, logger_code()); + .account_code(LOGGER, logger_code()) + .account_code(SALT_WRITER, salt_writer_code()) + .account_balance(SALT_CALLER, U256::from(10u64.pow(9))) + .account_code(SALT_CALLER, salt_caller_code()); let cfg = mega_context(db.clone()).cfg().clone(); let mut depth = [0u8; 32]; @@ -167,6 +231,40 @@ fn bench_transact(c: &mut Criterion) { ); }); } + + // The SALT arms: the same transaction against a minimal environment and against one where + // every bucket is crowded, both through `MegaEvm` — op-revm has nothing to compare to. + let salt_workloads = [ + ("salt_storage_writes", call_tx(SALT_WRITER, Bytes::new(), SALT_GAS_LIMIT)), + ("salt_new_accounts", call_tx(SALT_CALLER, Bytes::new(), SALT_GAS_LIMIT)), + ]; + for (workload, tx) in salt_workloads { + let minimal = salt_envs(1); + let crowded = salt_envs(SALT_MULTIPLIER); + let at_minimum = MegaEvm::new(salt_context(db.clone(), minimal.clone())) + .execute_transaction(OpTx(tx.clone())) + .unwrap(); + let at_crowded = MegaEvm::new(salt_context(db.clone(), crowded.clone())) + .execute_transaction(OpTx(tx.clone())) + .unwrap(); + assert!(at_minimum.result.is_success(), "{workload}: {:?}", at_minimum.result); + assert!(at_crowded.result.is_success(), "{workload}: {:?}", at_crowded.result); + assert_eq!( + at_crowded.gas.state, + at_minimum.gas.state * SALT_MULTIPLIER, + "{workload}: the crowded arm must actually pay the crowded price", + ); + + for (arm, envs) in [("satin", minimal), ("crowded", crowded)] { + group.bench_function(format!("{workload}/{arm}"), |b| { + b.iter_batched( + || MegaEvm::new(salt_context(db.clone(), envs.clone())), + |mut evm| evm.transact(OpTx(tx.clone())).unwrap(), + BatchSize::SmallInput, + ); + }); + } + } group.finish(); } From c30ccdece8d0a37a979fa9e3f0aa79724c67c4a6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:33:35 +0800 Subject: [PATCH 139/201] test(satin): port the parked rows SALT pricing owns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 61 of the 75 rows the test inventory parks under SALT pricing run again, adapted to the Satin API and to the pricing hook: the state gas a charge pays is the schedule's entry times the bucket multiplier, where the legacy engine charged a base times the multiplier less one, so the minimum bucket now pays the entry rather than nothing. What they add beyond the sites already covered: the writes the multiplier has nothing to scale (a reset, a clear, a slot written twice, value reaching an account that exists), CREATE2, a creation that also writes a slot, the multiplier over a wide range, and — in a file of their own — what a delegation designator means for the price. A designator can point at itself or two can point at each other; deciding whether the target exists must follow it the one hop EIP-7702 allows and no further, and the probes reach such a chain through every call-family opcode and both creation opcodes. CALLCODE sits there too: it sends value to the caller's own account, so it adds no leaf and asks for no price at all. The 14 rows left parked need something that is not here: four pin a spec gate a single-spec engine has none of, three inspect accounts while pricing, which this hook does not do, four belong to the deposit creation path and the pre-block system calls, and three are undecided. --- crates/mega-evm/src/evm/context.rs | 31 + crates/mega-evm/tests/_pending/README.md | 40 +- .../mega-evm/tests/_pending/mini_rex/gas.rs | 261 ------ .../tests/_pending/rex/storage_gas.rs | 746 ------------------ .../_pending/rex4/eip7702_delegation_cycle.rs | 364 --------- .../_pending/rex5/callcode_storage_gas.rs | 97 --- .../tests/_pending/rex5/eip7702_metering.rs | 338 -------- .../_pending/rex5/sstore_storage_gas_error.rs | 103 --- .../_pending/rex6/create_frame_accounting.rs | 166 ---- .../tests/_pending/rex6/error_paths.rs | 33 - .../rex6/system_tx_metering_exemption.rs | 52 -- .../tests/_pending/src/evm/context.rs | 50 -- .../tests/_pending/src/external/gas.rs | 58 -- crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/salt.rs | 203 ++++- .../mega-evm/tests/satin/salt_delegation.rs | 289 +++++++ crates/mega-evm/tests/satin/salt_failure.rs | 25 + 17 files changed, 569 insertions(+), 2288 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex/storage_gas.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/context.rs create mode 100644 crates/mega-evm/tests/satin/salt_delegation.rs diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 8226eec27..e83953942 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -498,6 +498,37 @@ mod tests { assert_eq!(env.bucket_queries(bucket), 2, "the next transaction read it again"); } + /// Two contexts may read one SALT environment — a node builds an EVM per transaction over + /// the block's environments — and each keeps the multipliers it read to itself. + #[test] + fn test_contexts_sharing_a_salt_environment_keep_their_own_multipliers() { + const ONE: alloy_primitives::Address = + alloy_primitives::address!("0000000000000000000000000000000000000b01"); + const OTHER: alloy_primitives::Address = + alloy_primitives::address!("0000000000000000000000000000000000000b02"); + let env = TestExternalEnvs::::new(); + let context = || { + MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs::from(env.clone()), + ) + }; + let (mut first, mut second) = (context(), context()); + + first.account_bucket_multiplier(ONE).unwrap(); + second.account_bucket_multiplier(OTHER).unwrap(); + + assert_eq!( + first.bucket_multipliers().cached_buckets().collect::>(), + vec![::bucket_id_for_account(ONE)], + ); + assert_eq!( + second.bucket_multipliers().cached_buckets().collect::>(), + vec![::bucket_id_for_account(OTHER)], + ); + } + /// The external environments given at construction are the ones the context exposes. #[test] fn test_new_with_ext_envs_builds_over_configurable_env() { diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index b7ac4e67b..f3c5f31d4 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -27,7 +27,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | +| SALT pricing | 14 | 9 | 5 | 4 | 10 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +41,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **660** | **574** | **86** | **380** | **252** | **28** | +| **Total** | **599** | **519** | **80** | **367** | **204** | **28** | ## Tests ported in place @@ -165,11 +165,29 @@ These 53 rows run in a real test target now, adapted to the Satin API, so the co | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | | **Total** | | **53** | | +## Tests ported by SALT pricing + +These 61 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `mini_rex/gas.rs` | SALT pricing (20) | 20 | `tests/satin/salt.rs` | +| `rex/storage_gas.rs` | SALT pricing (15) | 15 | `tests/satin/salt.rs` | +| `rex4/eip7702_delegation_cycle.rs` | SALT pricing (8) | 8 | `tests/satin/salt_delegation.rs` | +| `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | `tests/satin/salt_delegation.rs` | +| `rex5/eip7702_metering.rs` | SALT pricing (4) | 4 | `tests/satin/salt_delegation.rs` | +| `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | +| `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | +| `rex6/error_paths.rs` | SALT pricing (2) | 2 | `tests/satin/salt_failure.rs` | +| `rex6/system_tx_metering_exemption.rs` | SALT pricing (1) | 1 | `tests/satin/salt.rs` | +| `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | +| `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | +| **Total** | | **61** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | |---|---|---|---| -| `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | ## Files @@ -186,13 +204,12 @@ Each cell lists `disposition count (mechanism · decision)`. | `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | | `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | -| `mini_rex/gas.rs` | 22 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | +| `mini_rex/gas.rs` | 2 | undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | | `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | | `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | | `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | | `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex/storage_gas.rs` | 15 | rewrite 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | | `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | | `rex3/keyless_deploy.rs` | 2 | rewrite 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | @@ -202,7 +219,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | | `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | -| `rex4/eip7702_delegation_cycle.rs` | 8 | keep 8 (SALT pricing · account inspection on the pricing path) | | `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | | `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | @@ -210,13 +226,12 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | -| `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | +| `rex5/callcode_storage_gas.rs` | 3 | keep 3 (SALT pricing · pricing-failure propagation) | | `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | | `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | -| `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | | `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | | `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | | `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | @@ -228,26 +243,23 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | | `rex5/sandbox_accounting.rs` | 9 | rewrite 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | | `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | -| `rex5/sstore_storage_gas_error.rs` | 1 | keep 1 (SALT pricing · pricing-failure path) | | `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | | `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | | `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/create_frame_accounting.rs` | 1 | keep 1 (SALT pricing) | | `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | -| `rex6/error_paths.rs` | 4 | keep 2 (SALT pricing); keep 2 (the common execution layer · canonical) | +| `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | | `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | | `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | | `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | | `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | +| `rex6/system_tx_metering_exemption.rs` | 2 | rewrite 2 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | -| `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | -| `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | +| `src/external/gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | | `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | | `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | diff --git a/crates/mega-evm/tests/_pending/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs index f4f6d2ab3..9b93e3158 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -117,129 +117,6 @@ fn sstore_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests SSTORE setting a zero slot to non-zero value without bucket expansion, expecting 2M+ gas -/// due to high `SSTORE_SET_GAS` cost plus EIP-2929 cold access penalty. -#[test] -fn test_sstore_no_bucket_expansion() { - sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Set, 0, 43_106 + SSTORE_SET_STORAGE_GAS); -} - -/// Tests SSTORE with single bucket expansion, expecting doubled gas cost (4M+ gas) due to bucket -/// capacity doubling, plus EIP-2929 cold access penalty. -#[test] -fn test_sstore_with_bucket_expansion_once() { - sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Set, 1, 43_106 + SSTORE_SET_STORAGE_GAS * 2); -} - -/// Tests SSTORE with 10x bucket expansion, expecting 10x gas cost (20M+ gas) due to linear scaling -/// with bucket capacity, plus EIP-2929 cold access penalty. -#[test] -fn test_sstore_with_bucket_expansion_ten_times() { - sstore_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Set, - 9, - 43_106 + SSTORE_SET_STORAGE_GAS * 10, - ); -} - -/// Tests SSTORE resetting non-zero to different non-zero value, expecting standard gas cost (base + -/// `WARM_SSTORE_RESET`) plus EIP-2929 cold access penalty. -#[test] -fn test_sstore_reset() { - sstore_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Reset, - 0, - 23_906 + constants::equivalence::COLD_SLOAD_COST, - ); -} - -/// Tests SSTORE reset with bucket expansion, expecting same gas cost as without expansion since no -/// new storage allocation, plus EIP-2929 cold access penalty. -#[test] -fn test_sstore_reset_with_bucket_expansion() { - sstore_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Reset, - 1, - 23_906 + constants::equivalence::COLD_SLOAD_COST, - ); -} - -/// Tests SSTORE clearing non-zero to zero value. -/// -/// Gas calculation with EIP-2929 (cold access) and EIP-3529 (refund): -/// 1. Base tx: 21,000 -/// 2. SSTORE cost: `WARM_SSTORE_RESET` (2900) + `COLD_SLOAD_COST` (2100) = 5,000 -/// 3. Bytecode overhead: ~6 gas (PUSH, STOP, etc.) -/// 4. Total charged: 26,006 -/// 5. Refund (EIP-3529): min(4800, 26006/5) = 4,800 -/// - `sstore_clears_schedule` = `SSTORE_RESET` - `COLD_SLOAD_COST` + `ACCESS_LIST_STORAGE_KEY` -/// - = 5000 - 2100 + 1900 = 4,800 -/// 6. Final gas used: 26,006 - 4,800 = 21,206 -#[test] -fn test_sstore_clear() { - sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Clear, 0, 21_206); -} - -/// Tests SSTORE clear with bucket expansion. Bucket expansion doesn't affect clearing operations -/// since no new storage is allocated. Same gas cost as `test_sstore_clear` (21,206) due to: -/// - SSTORE charges: `WARM_SSTORE_RESET` + `COLD_SLOAD_COST` = 5,000 -/// - EIP-3529 refund: 4,800 -/// - Net SSTORE cost: 200 gas (plus ~6 overhead) -#[test] -fn test_sstore_clear_with_bucket_expansion() { - sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Clear, 1, 21_206); -} - -/// Tests EIP-2929: First SSTORE to a slot charges cold access penalty (2100 gas), subsequent -/// SSTOREs to the same slot in the same transaction use warm pricing. -#[test] -fn test_sstore_cold_then_warm_access() { - let mut db = MemoryDatabase::default(); - - let storage_key = U256::from(0); - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64); - - // Contract that performs two SSTOREs to the same slot: - // 1. First SSTORE (cold): should charge SSTORE_SET_GAS + COLD_SLOAD_COST - // 2. Second SSTORE (warm): should only charge WARM_STORAGE_READ_COST (no cold penalty) - let bytecode = BytecodeBuilder::default() - .sstore(storage_key, U256::from(100)) // Cold access - .sstore(storage_key, U256::from(200)) // Warm access - .stop() - .build(); - db.set_account_code(CALLEE, bytecode); - - let res = transact( - MegaSpecId::MINI_REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Default::default(), - U256::ZERO, - ) - .unwrap(); - assert!(res.result.is_success()); - - // Expected gas breakdown: - // - Base: 21_000 - // - Bytecode execution overhead: ~12 gas (PUSH opcodes, STOP, etc.) - // - First SSTORE (cold): SSTORE_SET_GAS + COLD_SLOAD_COST - // - Second SSTORE (warm, overwriting non-zero with non-zero): WARM_STORAGE_READ_COST - let expected_gas = 21_000 - + 12 // bytecode overhead - + SSTORE_SET_STORAGE_GAS - + constants::equivalence::SSTORE_SET - + constants::equivalence::COLD_SLOAD_COST - + constants::equivalence::WARM_STORAGE_READ_COST; - assert_eq!(res.result.gas_used(), expected_gas); -} - /// Executes an ether transfer test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -293,34 +170,6 @@ fn ether_transfer_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests ether transfer to new account charges increased `NEW_ACCOUNT_GAS` in `MegaETH`. -#[test] -fn test_ether_transfer_to_non_existent_account() { - ether_transfer_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Set, - 0, - 21_000 + constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS, - ); -} - -/// Tests ether transfer with bucket expansion doubles the `NEW_ACCOUNT_GAS` cost. -#[test] -fn test_ether_transfer_to_non_existent_account_with_bucket_expansion() { - ether_transfer_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Set, - 1, - 21_000 + constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS * 2, - ); -} - -/// Tests ether transfer to existing account only charges base transaction gas. -#[test] -fn test_ether_transfer_to_existent_account() { - ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 21_000); -} - /// Executes a nested ether transfer test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -384,34 +233,6 @@ fn nested_ether_transfer_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests nested ether transfer (via CALL) to new account charges increased `NEW_ACCOUNT_GAS`. -#[test] -fn test_nested_ether_transfer_to_non_existent_account() { - nested_ether_transfer_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Set, - 0, - 55_316 + constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS, - ); -} - -/// Tests nested ether transfer with bucket expansion doubles the `NEW_ACCOUNT_GAS` cost. -#[test] -fn test_nested_ether_transfer_to_non_existent_account_with_bucket_expansion() { - nested_ether_transfer_test_case( - MegaSpecId::MINI_REX, - UpdateMode::Set, - 1, - 55_316 + constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS * 2, - ); -} - -/// Tests nested ether transfer to existing account only charges base CALL gas. -#[test] -fn test_nested_ether_transfer_to_existent_account() { - nested_ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 30_316); -} - /// Executes a create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -447,32 +268,6 @@ fn create_contract_test_case(spec: MegaSpecId, expansion_times: u64, expected_ga assert_eq!(gas_used, expected_gas_used); } -/// Tests CREATE contract charges increased `NEW_ACCOUNT_GAS` and additional code deposit gas. -#[test] -fn test_create_contract_to_non_existent_account() { - create_contract_test_case( - MegaSpecId::MINI_REX, - 0, - 53_554 + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS + - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_GAS * 83, - ); -} - -/// Tests CREATE with bucket expansion doubles the `NEW_ACCOUNT_GAS` cost. -#[test] -fn test_create_contract_to_non_existent_account_with_bucket_expansion() { - create_contract_test_case( - MegaSpecId::MINI_REX, - 1, - 53_554 + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS * 2 + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS + - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_GAS * 83, - ); -} - /// Executes a nested create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -540,62 +335,6 @@ fn nested_create_contract_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests nested CREATE (via CALL) charges `CREATE_GAS` plus `NEW_ACCOUNT_GAS`. -#[test] -fn test_nested_create_contract_to_non_existent_account() { - nested_create_contract_test_case( - MegaSpecId::MINI_REX, - false, - 0, - 21_255 + - constants::equivalence::CREATE + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS, - ); -} - -/// Tests nested CREATE with bucket expansion doubles the `NEW_ACCOUNT_GAS` cost. -#[test] -fn test_nested_create_contract_to_non_existent_account_with_bucket_expansion() { - nested_create_contract_test_case( - MegaSpecId::MINI_REX, - false, - 1, - 21_255 + - constants::equivalence::CREATE + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS * 2 + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS, - ); -} - -/// Tests nested CREATE2 charges `CREATE_GAS` plu`NEW_ACCOUNT_GAS`AS plus KECCAK256 cost. -#[test] -fn test_nested_create2_contract_to_non_existent_account() { - nested_create_contract_test_case( - MegaSpecId::MINI_REX, - true, - 0, - 21_270 + - constants::equivalence::CREATE + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS, - ); -} - -/// Tests nested CREATE2 with bucket expansion doubles the `NEW_ACCOUNT_GAS` cost. -#[test] -fn test_nested_create2_contract_to_non_existent_account_with_bucket_expansion() { - nested_create_contract_test_case( - MegaSpecId::MINI_REX, - true, - 1, - 21_270 + - constants::equivalence::CREATE + - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS * 2 + - constants::mini_rex::CODEDEPOSIT_STORAGE_GAS, - ); -} - /// Executes a calldata test case, verifying gas usage for calldata scenarios. /// /// # Arguments diff --git a/crates/mega-evm/tests/_pending/rex/storage_gas.rs b/crates/mega-evm/tests/_pending/rex/storage_gas.rs deleted file mode 100644 index a9455333d..000000000 --- a/crates/mega-evm/tests/_pending/rex/storage_gas.rs +++ /dev/null @@ -1,746 +0,0 @@ -//! Tests for REX hardfork storage gas costs. - -use std::convert::Infallible; - -use alloy_primitives::{address, keccak256, Bytes, TxKind, U256}; -use mega_evm::{ - constants::{self, rex::*}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EVMError, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::{CALL, CREATE, CREATE2}, - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); -const NEW_ACCOUNT: Address = address!("3000000000000000000000000000000000000003"); - -/// Base intrinsic gas cost for all transactions -const BASE_INTRINSIC_GAS: u64 = 21_000; -const BASE_CREATE_GAS: u64 = 32_000; - -/// Executes a transaction on the EVM. -#[allow(clippy::too_many_arguments)] -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -#[test] -fn test_sstore_minimum_bucket_zero_gas() { - // With multiplier = 1 (minimum bucket), REX should charge 0 gas for SSTORE - // Formula: 20,000 × (1 - 1) = 0 - let mut db = MemoryDatabase::default(); - - let storage_key = U256::ZERO; - let storage_value = U256::from(0x42); - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - - // Deploy contract with SSTORE operation - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - db.set_account_code(CALLEE, bytecode); - - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 100_000, - ) - .expect("Transaction should succeed"); - - // Gas breakdown: - // - 21,000 (base intrinsic) - // - 39,000 (TX_INTRINSIC_STORAGE_GAS) - // - 22,100 (SSTORE cold access + first-time set in EVM) - // - 0 (REX storage gas with multiplier = 1) - // Total: ~82,200 - - let gas_used = result.result.gas_used(); - assert_eq!( - gas_used, - BASE_INTRINSIC_GAS + - constants::rex::TX_INTRINSIC_STORAGE_GAS + - constants::equivalence::SSTORE_SET + - constants::equivalence::COLD_SLOAD_COST + - 6, // bytecode overhead - ); -} - -#[test] -fn test_sstore_with_multiplier_charges_storage_gas() { - // With multiplier > 1, REX should charge storage gas - // Formula: 20,000 × (multiplier - 1) - let mut db = MemoryDatabase::default(); - - let storage_key = U256::ZERO; - let storage_value = U256::from(0x42); - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - db.set_account_code(CALLEE, bytecode); - - // Test with multiplier = 2 (bucket_capacity = 2 * MIN_BUCKET_SIZE) - let bucket_capacity = MIN_BUCKET_SIZE as u64 * 2; - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 200_000, - ) - .expect("Transaction should succeed"); - - // Expected storage gas: 20,000 × (2 - 1) = 20,000 - let gas_used = result.result.gas_used(); - let expected_storage_gas = SSTORE_SET_STORAGE_GAS_BASE; - - assert_eq!( - gas_used, - BASE_INTRINSIC_GAS - + constants::rex::TX_INTRINSIC_STORAGE_GAS - + constants::equivalence::SSTORE_SET - + constants::equivalence::COLD_SLOAD_COST - + 6 // bytecode overhead - + expected_storage_gas, - ); -} - -#[test] -fn test_sstore_multiplier_scaling() { - // Test that storage gas scales linearly with multiplier - let multipliers = vec![1u64, 2, 5, 10]; - let mut previous_gas = 0u64; - - for multiplier in multipliers { - let mut db = MemoryDatabase::default(); - - let storage_key = U256::ZERO; - let storage_value = U256::from(0x42); - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - db.set_account_code(CALLEE, bytecode); - - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - let gas_used = result.result.gas_used(); - let expected_storage_gas = SSTORE_SET_STORAGE_GAS_BASE * (multiplier - 1); - let expected_total = BASE_INTRINSIC_GAS - + constants::rex::TX_INTRINSIC_STORAGE_GAS - + constants::equivalence::SSTORE_SET - + constants::equivalence::COLD_SLOAD_COST - + 6 // bytecode overhead - + expected_storage_gas; - - assert_eq!(gas_used, expected_total); - - if previous_gas > 0 { - // Verify gas increased from previous - assert!(gas_used > previous_gas, "Gas should increase with higher multiplier"); - } - - previous_gas = gas_used; - } -} - -#[test] -fn test_sstore_reset_no_storage_gas() { - // SSTORE reset (non-zero → non-zero) should not charge REX storage gas - let mut db = MemoryDatabase::default(); - - let storage_key = U256::ZERO; - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - - // Bytecode that sets a value then resets it to different non-zero value - let bytecode = BytecodeBuilder::default() - // First SSTORE: 0 → 0x42 - .sstore(storage_key, U256::from(0x42)) - // Second SSTORE: 0x42 → 0x99 (reset, not initial set) - .sstore(storage_key, U256::from(0x99)) - .stop() - .build(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - db.set_account_code(CALLEE, bytecode); - - let bucket_capacity = MIN_BUCKET_SIZE as u64 * 10; // High multiplier - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - // Should only charge storage gas for the first SSTORE (0 → non-zero) - // Expected: 20,000 × (10 - 1) = 180,000 for first SSTORE only - let expected_single_sstore_gas = SSTORE_SET_STORAGE_GAS_BASE * (10 - 1); - - // Gas breakdown: - // - Base intrinsic + TX_INTRINSIC_STORAGE_GAS - // - First SSTORE: EVM gas + storage gas - // - Second SSTORE: warm storage read (no storage gas, no reset cost) - let gas_used = result.result.gas_used(); - let expected_total = BASE_INTRINSIC_GAS - + constants::rex::TX_INTRINSIC_STORAGE_GAS - + constants::equivalence::SSTORE_SET - + constants::equivalence::COLD_SLOAD_COST - + 12 // bytecode overhead (two SSTOREs) - + expected_single_sstore_gas - + constants::equivalence::WARM_STORAGE_READ_COST; - - assert_eq!(gas_used, expected_total, "Should only charge storage gas once for first SSTORE"); -} - -#[test] -fn test_new_account_minimum_bucket_zero_gas() { - // With multiplier = 1, account creation should charge 0 storage gas - // Formula: 25,000 × (1 - 1) = 0 - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), // Send value to create new account - 100_000, - ) - .expect("Transaction should succeed"); - - // Gas breakdown: - // - 21,000 (base intrinsic) - // - 39,000 (TX_INTRINSIC_STORAGE_GAS) - // - 0 (REX account creation with multiplier = 1) - // Total: 60,000 - - assert_eq!(result.result.gas_used(), 60_000); -} - -#[test] -fn test_new_account_with_multiplier() { - // Test account creation with various multipliers - // Formula: 25,000 × (multiplier - 1) - let multipliers = vec![1u64, 2, 5, 10]; - - for multiplier in multipliers { - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 10_000_000, - ) - .expect("Transaction should succeed"); - - let expected_storage_gas = NEW_ACCOUNT_STORAGE_GAS_BASE * (multiplier - 1); - let expected_total = 21_000 + TX_INTRINSIC_STORAGE_GAS + expected_storage_gas; - - assert_eq!(result.result.gas_used(), expected_total); - } -} - -#[test] -fn test_existing_account_no_storage_gas() { - // Transfer to existing account should not charge storage gas - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - // Pre-create the account - db.set_account_balance(NEW_ACCOUNT, U256::from(1_000)); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let bucket_capacity = MIN_BUCKET_SIZE as u64 * 10; // High multiplier - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000, - ) - .expect("Transaction should succeed"); - - // Should only charge intrinsic gas, no storage gas for existing account - let expected_total = 21_000 + TX_INTRINSIC_STORAGE_GAS; - - assert_eq!(result.result.gas_used(), expected_total); -} - -#[test] -fn test_contract_creation_minimum_bucket() { - // Contract creation with multiplier = 1 should charge 0 storage gas - // Formula: 32,000 × (1 - 1) = 0 - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - - let deployed_bytecode = BytecodeBuilder::default().stop().build(); - - // For CREATE transactions, we need to know the address that will be created - // The created address is deterministic based on caller + nonce - // For this test, we'll use a simplified approach and set a wide bucket capacity - let external_envs = TestExternalEnvs::default(); - - // CREATE transaction - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - None, // None = CREATE - deployed_bytecode, - U256::ZERO, - 200_000, - ) - .expect("Transaction should succeed"); - - // Should not charge REX contract creation storage gas with minimum bucket (default env has - // MIN_BUCKET_SIZE) - let expected_gas = - BASE_INTRINSIC_GAS + BASE_CREATE_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS + 46; // bytecode overhead - assert_eq!(result.result.gas_used(), expected_gas); -} - -#[test] -fn test_contract_creation_with_multiplier() { - // Test contract creation with various multipliers - // Formula: 32,000 × (multiplier - 1) - let multipliers = vec![2u64, 5, 10]; - - for multiplier in multipliers { - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - let deployed_bytecode = BytecodeBuilder::default().stop().build(); - - // Calculate the deterministic contract address (RLP(sender, nonce)) - // For nonce=0: keccak256(rlp([sender, 0]))[12:] - let created_address = CALLER.create(0); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(created_address); - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - let external_envs = - TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - None, - deployed_bytecode, - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - let expected_storage_gas = CONTRACT_CREATION_STORAGE_GAS_BASE * (multiplier - 1); - let gas_used = result.result.gas_used(); - - // Gas breakdown for CREATE: - // Base overhead (including intrinsic, CREATE opcode, code deposit, etc.) = 92,046 - // REX contract creation storage gas = 32,000 × (multiplier - 1) - let base_create_gas = 92_046; - let expected_total = base_create_gas + expected_storage_gas; - - assert_eq!(gas_used, expected_total); - } -} - -#[test] -fn test_contract_creation_costs_more_than_account() { - // REX distinguishes contract creation (32k base) from account creation (25k base) - // Mini-Rex used same 2M base for both - let mut db_contract = MemoryDatabase::default(); - let mut db_account = MemoryDatabase::default(); - - db_contract.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - db_account.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - let multiplier = 10u64; - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - // Contract creation - let created_address = CALLER.create(0); - let contract_bucket_id = TestExternalEnvs::::bucket_id_for_account(created_address); - let contract_external_envs = - TestExternalEnvs::new().with_bucket_capacity(contract_bucket_id, bucket_capacity); - - let deployed_bytecode = BytecodeBuilder::default().stop().build(); - let contract_result = transact( - MegaSpecId::REX, - &mut db_contract, - &contract_external_envs, - CALLER, - None, - deployed_bytecode, - U256::ZERO, - 10_000_000, - ) - .expect("Contract creation should succeed"); - - // Account creation - let account_bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let account_external_envs = - TestExternalEnvs::new().with_bucket_capacity(account_bucket_id, bucket_capacity); - - let account_result = transact( - MegaSpecId::REX, - &mut db_account, - &account_external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 10_000_000, - ) - .expect("Account creation should succeed"); - - let contract_gas = contract_result.result.gas_used(); - let account_gas = account_result.result.gas_used(); - - // Expected difference in storage gas: (32,000 - 25,000) × (10 - 1) = 63,000 - let _expected_difference = - (CONTRACT_CREATION_STORAGE_GAS_BASE - NEW_ACCOUNT_STORAGE_GAS_BASE) * (multiplier - 1); - - assert!( - contract_gas > account_gas, - "Contract creation should cost more than account creation in REX" - ); -} - -#[test] -fn test_combined_contract_creation_and_sstore() { - // Test that contract creation + SSTORE both charge storage gas - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - // Constructor that does SSTORE - let storage_key = U256::ZERO; - let storage_value = U256::from(0x42); - let deployed_bytecode = - BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - let multiplier = 5u64; - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - // Get both bucket IDs - let created_address = CALLER.create(0); - let contract_bucket_id = TestExternalEnvs::::bucket_id_for_account(created_address); - let storage_bucket_id = - TestExternalEnvs::::bucket_id_for_slot(created_address, storage_key); - - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(contract_bucket_id, bucket_capacity) - .with_bucket_capacity(storage_bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - None, - deployed_bytecode, - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - // Expected storage gas: - // - Contract creation: 32,000 × (5 - 1) = 128,000 - // - SSTORE: 20,000 × (5 - 1) = 80,000 - // Total storage gas: 208,000 - let expected_storage_gas = CONTRACT_CREATION_STORAGE_GAS_BASE * (multiplier - 1) + - SSTORE_SET_STORAGE_GAS_BASE * (multiplier - 1); - - let gas_used = result.result.gas_used(); - - // Gas breakdown for CREATE with SSTORE: - // Base overhead (including intrinsic, CREATE, SSTORE, code deposit, etc.) = 117,632 - // REX storage gas = 32,000 × (mult - 1) + 20,000 × (mult - 1) = 208,000 - let base_create_sstore_gas = 117_632; - let expected_total = base_create_sstore_gas + expected_storage_gas; - - assert_eq!(gas_used, expected_total); -} - -#[test] -fn test_large_multiplier_linear_scaling() { - // Verify storage gas scales linearly even with large multipliers - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(100_000_000_000_000u64)); - - let multiplier = 100u64; - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000_000, - ) - .expect("Transaction should succeed"); - - // Expected: 21k + 39k + 25k×(100-1) = 21k + 39k + 2,475k = 2,535k - let expected_storage_gas = NEW_ACCOUNT_STORAGE_GAS_BASE * (multiplier - 1); - let expected_total = 21_000 + TX_INTRINSIC_STORAGE_GAS + expected_storage_gas; - - assert_eq!(result.result.gas_used(), expected_total); -} - -// ======================================================================================== -// Opcode-level tests for CREATE, CREATE2, and CALL -// ======================================================================================== - -#[test] -fn test_create_opcode() { - // Test CREATE opcode is executed correctly in REX mode - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - // Create a contract that uses CREATE opcode to deploy another contract - let deployed_contract = BytecodeBuilder::default().stop().build(); - - let code_len = deployed_contract.len(); - let creator_bytecode = BytecodeBuilder::default() - .mstore(0x00, deployed_contract.as_ref()) - .push_number(code_len as u64) - .push_number(0x00_u64) - .push_number(0x00_u64) - .append(CREATE) - .stop() - .build(); - - db.set_account_code(CALLEE, creator_bytecode); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(CALLEE.create(0)); - let external_envs = - TestExternalEnvs::default().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * 10); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - assert!(result.result.is_success()); - assert_eq!( - result.result.gas_used(), - BASE_INTRINSIC_GAS + - constants::rex::TX_INTRINSIC_STORAGE_GAS + - constants::equivalence::CREATE + - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE * 9 + - 23, /* bytecode overhead */ - ); -} - -#[test] -fn test_create2_opcode() { - // Test CREATE2 opcode is executed correctly in REX mode - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - - let deployed_contract = BytecodeBuilder::default().stop().build(); - - let code_len = deployed_contract.len(); - let salt = U256::from(0x42); - let creator_bytecode = BytecodeBuilder::default() - .mstore(0x00, deployed_contract.as_ref()) - .push_u256(salt) - .push_number(code_len as u64) - .push_number(0x00_u64) - .push_number(0x00_u64) - .append(CREATE2) - .stop() - .build(); - - db.set_account_code(CALLEE, creator_bytecode); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account( - CALLEE.create2(salt.to_be_bytes(), keccak256(&deployed_contract)), - ); - let external_envs = - TestExternalEnvs::default().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * 10); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - assert!(result.result.is_success()); - assert_eq!( - result.result.gas_used(), - BASE_INTRINSIC_GAS + - constants::rex::TX_INTRINSIC_STORAGE_GAS + - constants::equivalence::CREATE + - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE * 9 + - 32, /* bytecode overhead */ - ); -} - -#[test] -fn test_call_opcode_creates_account() { - // Test CALL opcode creating a new account by sending value - let mut db = MemoryDatabase::default(); - - db.set_account_balance(CALLER, U256::from(1_000_000_000_000u64)); - db.set_account_balance(CALLEE, U256::from(1_000_000u64)); - - // Contract that uses CALL opcode to send value to NEW_ACCOUNT - let caller_bytecode = BytecodeBuilder::default() - .push_number(0x00_u64) // retSize - .push_number(0x00_u64) // retOffset - .push_number(0x00_u64) // argsSize - .push_number(0x00_u64) // argsOffset - .push_number(1000_u64) // value to send - .push_address(NEW_ACCOUNT) // address - .push_number(100_000_u64) // gas - .append(CALL) - .stop() - .build(); - - db.set_account_code(CALLEE, caller_bytecode); - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let external_envs = - TestExternalEnvs::default().with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * 10); - - let result = transact( - MegaSpecId::REX, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 10_000_000, - ) - .expect("Transaction should succeed"); - - assert!(result.result.is_success()); - assert_eq!( - result.result.gas_used(), - BASE_INTRINSIC_GAS + - constants::rex::TX_INTRINSIC_STORAGE_GAS + - constants::equivalence::CALLVALUE + - constants::equivalence::NEWACCOUNT + - constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE * 9 + - 321, /* bytecode overhead */ - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs deleted file mode 100644 index 91f504a0c..000000000 --- a/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs +++ /dev/null @@ -1,364 +0,0 @@ -//! Tests for EIP-7702 delegation handling. -//! -//! ## Delegation cycle tests -//! -//! `Journal::inspect_account_delegated` (host.rs) follows EIP-7702 delegation to resolve -//! the delegate. -//! If an account self-delegates (A→A) or forms a cycle (A→B→A), unbounded recursion would -//! cause a stack overflow (SIGABRT, not a catchable Rust panic). -//! -//! The function is called from `wrap_call_with_storage_gas!` (CALL, CALLCODE, -//! DELEGATECALL, STATICCALL), `create` (CREATE/CREATE2), and -//! `StateGrowthTracker::before_frame_init`. -//! -//! Direct top-level transactions are unaffected because revm's own `load_account_delegated` -//! resolves exactly one hop. -//! The issue only manifests when a *contract* performs a CALL-family opcode targeting the -//! poisoned address. -//! -//! ## EIP-7702 spec note -//! -//! EIP-7702 specifies that clients must resolve at most one level of delegation. -//! Recursive resolution is itself a spec violation, independent of the crash. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - database::AccountState, - state::Bytecode, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); -const PARENT: Address = address!("0000000000000000000000000000000000500001"); -const SELF_DELEGATING: Address = address!("0000000000000000000000000000000000500002"); -const CYCLE_A: Address = address!("0000000000000000000000000000000000500003"); -const CYCLE_B: Address = address!("0000000000000000000000000000000000500004"); -const DELEGATOR: Address = address!("0000000000000000000000000000000000500005"); -const DELEGATE: Address = address!("0000000000000000000000000000000000500006"); - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = - MegaContext::new(db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Sets EIP-7702 delegation bytecode on an account, making it delegate to `delegate_to`. -/// -/// This produces the same `0xef0100 || address` designator that revm's -/// `apply_eip7702_auth_list` writes during Type 4 transaction processing. -fn set_eip7702_delegation(db: &mut MemoryDatabase, address: Address, delegate_to: Address) { - let bytecode = Bytecode::new_eip7702(delegate_to); - let code_hash = bytecode.hash_slow(); - let account = db.load_account(address).unwrap(); - account.info.code = Some(bytecode); - account.info.code_hash = code_hash; - account.account_state = AccountState::None; -} - -/// Builds a contract that CALLs `target` with zero value and empty calldata. -fn build_call_contract(target: Address) -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(target) - .append(GAS) - .append(CALL) - .append(STOP) - .build() -} - -/// Builds a contract that STATICCALLs `target` with empty calldata. -fn build_staticcall_contract(target: Address) -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .push_address(target) - .append(GAS) - .append(STATICCALL) - .append(STOP) - .build() -} - -/// Builds a contract that DELEGATECALLs `target` with empty calldata. -fn build_delegatecall_contract(target: Address) -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .push_address(target) - .append(GAS) - .append(DELEGATECALL) - .append(STOP) - .build() -} - -/// Builds a contract that CALLCODEs `target` with zero value and empty calldata. -fn build_callcode_contract(target: Address) -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(target) - .append(GAS) - .append(CALLCODE) - .append(STOP) - .build() -} - -/// Self-delegation (A→A) via CALL causes unbounded recursion in `inspect_account_delegated`. -/// -/// The `wrap_call_with_storage_gas!` macro calls `inspect_account_delegated` on the CALL -/// target to determine `is_empty` for storage gas charging. -/// With self-delegation, the function sees `Bytecode::Eip7702(self)` on every iteration -/// and recurses indefinitely. -#[test] -fn test_self_delegation_via_call() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_call_contract(SELF_DELEGATING)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, SELF_DELEGATING, SELF_DELEGATING); - db.set_account_balance(SELF_DELEGATING, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Should complete without stack overflow"); -} - -/// Two-address cycle (A→B→A) via CALL. -/// -/// A delegates to B, B delegates back to A. -/// `inspect_account_delegated` follows A→B→A→B→... until the stack overflows. -#[test] -fn test_two_address_cycle_via_call() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_call_contract(CYCLE_A)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, CYCLE_A, CYCLE_B); - set_eip7702_delegation(&mut db, CYCLE_B, CYCLE_A); - db.set_account_balance(CYCLE_A, U256::from(1_000_000u64)); - db.set_account_balance(CYCLE_B, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Should complete without stack overflow"); -} - -/// Self-delegation (A→A) via STATICCALL exercises the same `wrap_call_with_storage_gas!` -/// path through the STATICCALL variant. -#[test] -fn test_self_delegation_via_staticcall() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_staticcall_contract(SELF_DELEGATING)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, SELF_DELEGATING, SELF_DELEGATING); - db.set_account_balance(SELF_DELEGATING, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Should complete without stack overflow"); -} - -/// Two-address cycle (A→B→A) via DELEGATECALL exercises the same wrapped call path as CALL, -/// but through the DELEGATECALL variant. -#[test] -fn test_two_address_cycle_via_delegatecall() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_delegatecall_contract(CYCLE_A)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, CYCLE_A, CYCLE_B); - set_eip7702_delegation(&mut db, CYCLE_B, CYCLE_A); - db.set_account_balance(CYCLE_A, U256::from(1_000_000u64)); - db.set_account_balance(CYCLE_B, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Should complete without stack overflow"); -} - -/// Self-delegation (A→A) via CALLCODE exercises the transfer-aware wrapped call path used by -/// CALLCODE. -#[test] -fn test_self_delegation_via_callcode() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_callcode_contract(SELF_DELEGATING)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, SELF_DELEGATING, SELF_DELEGATING); - db.set_account_balance(SELF_DELEGATING, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Should complete without stack overflow"); -} - -/// Direct transaction to a self-delegating address (control case). -/// -/// Top-level transaction target resolution uses revm's `load_account_delegated`, which -/// resolves exactly one hop — not our recursive `inspect_account_delegated`. -/// This test should pass regardless of whether the bug is fixed. -#[test] -fn test_direct_tx_to_self_delegating() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - - set_eip7702_delegation(&mut db, SELF_DELEGATING, SELF_DELEGATING); - db.set_account_balance(SELF_DELEGATING, U256::from(1_000_000u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(SELF_DELEGATING) - .gas_limit(100_000_000) - .build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "Direct TX should use safe single-hop resolution"); -} - -// --------------------------------------------------------------------------- -// CREATE / CREATE2 tests — `inspect_account_delegated` is called on the creator -// --------------------------------------------------------------------------- - -/// Builds a contract whose code executes CREATE with a minimal initcode (STOP). -/// -/// The CREATE opcode triggers `inspect_account_delegated(creator_address)` to load the -/// creator's nonce for address derivation and storage gas charging. -fn build_create_contract() -> Bytes { - // initcode: just STOP (1 byte) - // PUSH1 0x00 PUSH1 0x00 MSTORE8 — store STOP (0x00) at memory[0] - // PUSH1 0x01 PUSH1 0x00 PUSH1 0x00 CREATE - BytecodeBuilder::default() - .append(PUSH0) // value = 0x00 - .append(PUSH0) // offset = 0 - .append(MSTORE8) // memory[0] = 0x00 (STOP opcode) - .push_number(1u8) // size = 1 - .append(PUSH0) // offset = 0 - .append(PUSH0) // value = 0 wei - .append(CREATE) - .append(POP) // discard created address - .append(STOP) - .build() -} - -/// Builds a contract whose code executes CREATE2 with a minimal initcode (STOP) and salt=0. -fn build_create2_contract() -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // value = 0x00 - .append(PUSH0) // offset = 0 - .append(MSTORE8) // memory[0] = 0x00 (STOP opcode) - .append(PUSH0) // salt = 0 - .push_number(1u8) // size = 1 - .append(PUSH0) // offset = 0 - .append(PUSH0) // value = 0 wei - .append(CREATE2) - .append(POP) // discard created address - .append(STOP) - .build() -} - -/// Delegation via `CREATE`: `PARENT` calls `CYCLE_A` (delegates to `CYCLE_B`). -/// `CYCLE_B`'s code runs in `CYCLE_A`'s context and executes `CREATE`. -/// `CREATE` calls `inspect_account_delegated(CYCLE_A)` to load the creator's nonce. -/// `CYCLE_A` delegates to `CYCLE_B`, so the one-hop resolution follows to `CYCLE_B`. -/// Before the fix, this would recurse if `CYCLE_B` also delegated back. -#[test] -fn test_self_delegation_via_create() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - - // CYCLE_A delegates to CYCLE_B, CYCLE_B has CREATE code - set_eip7702_delegation(&mut db, CYCLE_A, CYCLE_B); - db.set_account_balance(CYCLE_A, U256::from(1_000_000_000u64)); - db.set_account_code(CYCLE_B, build_create_contract()); - db.set_account_balance(CYCLE_B, U256::from(1_000_000_000u64)); - - // PARENT calls CYCLE_A - db.set_account_code(PARENT, build_call_contract(CYCLE_A)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.is_ok(), "CREATE with delegated creator should complete without stack overflow"); -} - -/// Two-address delegation cycle (A→B→A) via `CREATE2`. -/// -/// Same setup as `CREATE` test but uses `CREATE2` opcode. -/// `PARENT` calls `CYCLE_A` (delegates to `CYCLE_B`). `CYCLE_B`'s code runs `CREATE2` in -/// `CYCLE_A`'s context. `CREATE2` calls `inspect_account_delegated(CYCLE_A)` for nonce/gas. -#[test] -fn test_delegation_cycle_via_create2() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - - // CYCLE_A delegates to CYCLE_B (which has CREATE2 code). - // CYCLE_B also delegates back to CYCLE_A to form the cycle. - set_eip7702_delegation(&mut db, CYCLE_A, CYCLE_B); - db.set_account_balance(CYCLE_A, U256::from(1_000_000_000u64)); - db.set_account_code(CYCLE_B, build_create2_contract()); - set_eip7702_delegation(&mut db, CYCLE_B, CYCLE_A); - db.set_account_balance(CYCLE_B, U256::from(1_000_000_000u64)); - - db.set_account_code(PARENT, build_call_contract(CYCLE_A)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(MegaSpecId::REX4, &mut db, tx); - assert!( - result.is_ok(), - "CREATE2 with cyclic delegation should complete without stack overflow" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs index 6193eaf91..6edaa0749 100644 --- a/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs @@ -139,90 +139,10 @@ fn run_with_target_multiplier(spec: MegaSpecId, bytecode: Bytes, target_multipli // CALLCODE: Rex5 fix — no new-account storage gas charged // ============================================================================ -/// Under Rex5, a value-transferring `CALLCODE` to an empty code-source must NOT -/// charge new-account storage gas, because the storage context is the (non-empty) -/// caller contract. -#[test] -fn test_rex5_callcode_to_empty_no_new_account_storage_gas() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX5, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX5, bytecode, 10); - - assert_eq!( - gas_mult10, gas_mult1, - "Rex5 CALLCODE must not charge new-account storage gas based on the code-source bucket", - ); -} - // ============================================================================ // CALLCODE: Rex5 fix combined with EIP-7702 non-delegating inspection // ============================================================================ -/// Regression test for the combined Rex5 fix surface where CALLCODE meters -/// new-account storage gas against the **caller** (current frame) using -/// non-delegating account inspection. -/// -/// Setup: the transaction targets `CALLEE`, which carries an EIP-7702 designator -/// pointing at `DELEGATE`. Revm follows the designator and runs `DELEGATE`'s -/// CALLCODE-emitting bytecode inside `CALLEE`'s frame, so the in-frame CALLCODE -/// sees `current = CALLEE` (an authority that holds designator code, hence -/// non-empty) and `to = EMPTY_TARGET` (empty). -/// -/// Under the merged Rex5 path: -/// - `storage_address = current = CALLEE` (per `storage_addr_for_callcode`) -/// - `inspect_account(CALLEE, false)` returns the authority's own record (designator code, -/// non-empty), so the new-account premium never fires. -/// -/// Gas usage must therefore be invariant under both the authority's bucket -/// multiplier and the code-source's bucket multiplier. The test catches: -/// - the CALLCODE selector regressing to `storage_addr_from_to` (the code-source multiplier would -/// start affecting gas), and -/// - the Rex5 gate being removed (Rex4's frozen behavior would charge against the code-source). -#[test] -fn test_rex5_callcode_from_eip7702_authority_no_storage_gas() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - - let run = |authority_multiplier: u64, target_multiplier: u64| -> u64 { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1_000_000_000u64)) - .account_code(DELEGATE, bytecode.clone()); - set_eip7702_delegation(&mut db, CALLEE, DELEGATE); - - let authority_bucket = TestExternalEnvs::::bucket_id_for_account(CALLEE); - let target_bucket = TestExternalEnvs::::bucket_id_for_account(EMPTY_TARGET); - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(authority_bucket, MIN_BUCKET_SIZE as u64 * authority_multiplier) - .with_bucket_capacity(target_bucket, MIN_BUCKET_SIZE as u64 * target_multiplier); - - let result = transact( - MegaSpecId::REX5, - &mut db, - &external_envs, - CALLER, - CALLEE, - U256::ZERO, - 10_000_000, - ) - .expect("transaction must succeed"); - assert!(result.result.is_success(), "execution must succeed: {:?}", result.result); - result.result.gas_used() - }; - - let gas_baseline = run(1, 1); - let gas_high_authority = run(10, 1); - let gas_high_target = run(1, 10); - - assert_eq!( - gas_high_authority, gas_baseline, - "authority bucket multiplier must not affect gas — no new-account charge fires against the authority", - ); - assert_eq!( - gas_high_target, gas_baseline, - "code-source bucket multiplier must not affect gas — Rex5 CALLCODE meters against the caller, not the code-source", - ); -} - // ============================================================================ // CALLCODE: Pre-Rex5 frozen behavior — bug preserved // ============================================================================ @@ -231,23 +151,6 @@ fn test_rex5_callcode_from_eip7702_authority_no_storage_gas() { // CALL: behavior unchanged — value-transferring CALL to empty target still charges // ============================================================================ -/// Under Rex5, a value-transferring `CALL` to an empty target still charges -/// new-account storage gas based on the target's bucket. The fix is scoped to -/// `CALLCODE` only; `CALL` semantics are unchanged. -#[test] -fn test_rex5_call_to_empty_still_charges_new_account_storage_gas() { - let bytecode = call_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX5, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX5, bytecode, 10); - - let expected_extra = NEW_ACCOUNT_STORAGE_GAS_BASE * 9; - assert_eq!( - gas_mult10 - gas_mult1, - expected_extra, - "Rex5 CALL must continue to charge new-account storage gas against the target bucket", - ); -} - // ============================================================================ // Error-path tests — coverage for FatalExternalError branches in call_code // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs deleted file mode 100644 index 8f1ed766f..000000000 --- a/crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! Tests for non-delegating CALL/CREATE metering. -//! -//! REX5 changes the CALL and CREATE storage-gas wrappers to use `inspect_account` -//! (non-delegating) instead of `inspect_account_delegated`. -//! `StateGrowthTracker::before_frame_init` also uses non-delegating inspection. -//! -//! This matters when the CALL target is an EIP-7702 authority whose delegate is an -//! empty (non-existent) address: -//! -//! - **Pre-REX5** (`inspect_account_delegated`): follows delegation, sees the empty delegate, and -//! treats the target as empty. This causes overcharging: new-account storage gas premium is -//! applied even though the authority itself already exists, and state growth is incorrectly -//! recorded. -//! -//! - **REX5** (`inspect_account`): inspects the authority directly, sees it has EIP-7702 delegation -//! bytecode (non-empty), and correctly skips the premium. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, - TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ResultAndState, tx::TxEnvBuilder, TxEnv}, - database::AccountState, - handler::EvmTr, - state::Bytecode, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000810000"); -const PARENT: Address = address!("0000000000000000000000000000000000810001"); -/// An EIP-7702 authority that delegates to `EMPTY_DELEGATE`. -const AUTHORITY: Address = address!("0000000000000000000000000000000000810002"); -/// A non-existent address that AUTHORITY delegates to. -const EMPTY_DELEGATE: Address = address!("0000000000000000000000000000000000810099"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> (ResultAndState, LimitUsage) { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (r, usage) -} - -/// Sets EIP-7702 delegation bytecode on an account, making it delegate to `delegate_to`. -/// -/// This produces the same `0xef0100 || address` designator that revm's -/// `apply_eip7702_auth_list` writes during Type 4 transaction processing. -fn set_eip7702_delegation(db: &mut MemoryDatabase, address: Address, delegate_to: Address) { - let bytecode = Bytecode::new_eip7702(delegate_to); - let code_hash = bytecode.hash_slow(); - let account = db.load_account(address).unwrap(); - account.info.code = Some(bytecode); - account.info.code_hash = code_hash; - account.account_state = AccountState::None; -} - -/// Builds a contract that CALLs `target` with 1 wei value and empty calldata. -/// -/// The value transfer is necessary to trigger the new-account storage gas logic in -/// `wrap_call_with_storage_gas!` — only CALLs with value to empty accounts are -/// charged the new-account premium. -fn build_call_with_value_contract(target: Address) -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .push_number(1u8) // value = 1 wei - .push_address(target) - .append(GAS) - .append(CALL) - .append(STOP) - .build() -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// CALL with value to an EIP-7702 authority (whose delegate is empty) should -/// record LESS state growth in REX5 than REX4. -/// -/// - REX4: `inspect_account_delegated` follows delegation to the empty delegate, treating the -/// target as empty. This records state growth for a "new account" even though the authority -/// itself exists. -/// - REX5: `inspect_account` sees the authority itself with EIP-7702 code (non-empty). No -/// new-account state growth is recorded. -/// -/// Note: the new-account *storage gas* premium is also affected, but with the test's -/// `EmptyExternalEnv` (min bucket, multiplier=1), the premium formula yields zero. -/// The observable difference is in the state growth tracker. -#[test] -fn test_call_with_value_to_eip7702_authority_rex5_vs_rex4() { - let build_db = || { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(PARENT, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_call_with_value_contract(AUTHORITY)); - // Set up authority: delegates to EMPTY_DELEGATE (which does not exist). - // Give authority some balance so it is a "real" account in the DB. - set_eip7702_delegation(&mut db, AUTHORITY, EMPTY_DELEGATE); - db.set_account_balance(AUTHORITY, U256::from(1_000u64)); - db - }; - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let (result_rex5, usage_rex5) = transact(MegaSpecId::REX5, &mut build_db(), tx.clone()); - assert!(result_rex5.result.is_success(), "REX5 should succeed: {result_rex5:?}"); - - let (result_rex4, usage_rex4) = transact(MegaSpecId::REX4, &mut build_db(), tx); - assert!(result_rex4.result.is_success(), "REX4 should succeed: {result_rex4:?}"); - - // REX4 should record state growth for the "new account" (via delegation to empty). - // REX5 should NOT record state growth because the authority itself is non-empty. - assert!( - usage_rex4.state_growth > usage_rex5.state_growth, - "REX4 state growth ({}) should exceed REX5 ({}) — \ - REX4 incorrectly counts authority as new account via delegation", - usage_rex4.state_growth, - usage_rex5.state_growth, - ); - - // REX5 should have zero state growth from the CALL target. - assert_eq!( - usage_rex5.state_growth, 0, - "REX5 should not record state growth for CALL to existing EIP-7702 authority: {}", - usage_rex5.state_growth - ); - - // REX4 should have non-zero state growth because it follows delegation to the empty - // delegate and treats the target as a new account. - assert!( - usage_rex4.state_growth > 0, - "REX4 should record state growth (treats delegated-to-empty as new account): {}", - usage_rex4.state_growth - ); -} - -/// CALL with value to an EIP-7702 authority whose delegate is empty should NOT -/// record state growth in REX5. -/// -/// The authority itself has delegation bytecode so `inspect_account` sees it as -/// non-empty. -/// No new-account creation occurs, so state growth should be zero from this path. -#[test] -fn test_rex5_call_to_eip7702_authority_no_state_growth() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(PARENT, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_call_with_value_contract(AUTHORITY)); - set_eip7702_delegation(&mut db, AUTHORITY, EMPTY_DELEGATE); - db.set_account_balance(AUTHORITY, U256::from(1_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // The authority is non-empty (has EIP-7702 code), so no new account is created. - assert_eq!( - usage.state_growth, 0, - "REX5 should not record state growth for CALL to existing EIP-7702 authority: {}", - usage.state_growth - ); -} - -/// CREATE inside an EIP-7702 delegated frame: REX5 uses the authority's nonce -/// for SALT bucket lookup, REX4 uses the delegate's nonce (wrong). -/// -/// To make the difference observable, we set up divergent SALT bucket capacities: -/// - The address computed from authority nonce gets a LOW bucket (1x multiplier). -/// - The address computed from delegate nonce gets a HIGH bucket (2x multiplier). -/// -/// REX4 follows delegation, uses the delegate's nonce → queries the high-capacity -/// bucket → charges more storage gas. -/// REX5 inspects the authority directly → queries the low-capacity bucket → charges less. -#[test] -fn test_rex5_create_inside_delegated_frame_uses_authority_nonce() { - // Init code: returns 1 byte of runtime code. - let init_code_bytes: &[u8] = &[ - PUSH1, 1, // size = 1 - PUSH1, 0, // offset = 0 - PUSH1, 0, // destOffset = 0 - CODECOPY, PUSH1, 1, // size = 1 - PUSH1, 0, // offset = 0 - RETURN, STOP, - ]; - - // Delegate bytecode: stores init code in memory, then CREATE. - let delegate_code = BytecodeBuilder::default() - .mstore(0, init_code_bytes) - .push_number(0u64) // value = 0 - .push_number(init_code_bytes.len() as u64) // size - .push_number((32 - init_code_bytes.len()) as u64) // offset (right-aligned in 32-byte word) - .append(CREATE) - .append(POP) - .stop() - .build(); - - let delegate_addr = address!("0000000000000000000000000000000000810050"); - let authority_nonce: u64 = 5; - let delegate_nonce: u64 = 0; // delegate contract has nonce 0 in DB - - // Compute the two candidate created addresses. - // Revm always creates at AUTHORITY.create(authority_nonce) regardless of metering bug. - // The metering code queries create_contract_storage_gas for one of these addresses: - let addr_from_authority_nonce = AUTHORITY.create(authority_nonce); - let addr_from_delegate_nonce = AUTHORITY.create(delegate_nonce); - assert_ne!( - addr_from_authority_nonce, addr_from_delegate_nonce, - "Divergent nonces must produce different addresses" - ); - - // Set up SALT buckets: high capacity for the wrong address (delegate nonce path). - let high_capacity = (MIN_BUCKET_SIZE as u64) * 3; - let wrong_bucket = - as SaltEnv>::bucket_id_for_account( - addr_from_delegate_nonce, - ); - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(wrong_bucket, high_capacity); - - let build_db = || { - let mut db = - MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(delegate_addr, delegate_code.clone()); - set_eip7702_delegation(&mut db, AUTHORITY, delegate_addr); - db.set_account_balance(AUTHORITY, U256::from(1_000_000u64)); - db.set_account_nonce(AUTHORITY, authority_nonce); - - // CALL the authority → code executes from delegate, target_address = AUTHORITY. - let caller_code = BytecodeBuilder::default() - .append(PUSH0) - .append(PUSH0) - .append(PUSH0) - .append(PUSH0) - .append(PUSH0) - .push_address(AUTHORITY) - .append(GAS) - .append(CALL) - .append(STOP) - .build(); - db.set_account_code(PARENT, caller_code); - db - }; - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - // REX5: uses authority's nonce → correct bucket (low capacity, 1x multiplier). - let mut db_rex5 = build_db(); - let mut ctx_rex5 = MegaContext::new(&mut db_rex5, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()); - ctx_rex5.modify_chain(|c| { - c.operator_fee_scalar = Some(U256::from(0)); - c.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm_rex5 = MegaEvm::new(ctx_rex5); - let mut tx_rex5 = MegaTransaction::new(tx.clone()); - tx_rex5.enveloped_tx = Some(Bytes::new()); - let r5 = alloy_evm::Evm::transact_raw(&mut evm_rex5, tx_rex5).unwrap(); - assert!(r5.result.is_success(), "REX5 should succeed: {:?}", r5.result); - let gas_rex5 = r5.result.gas_used(); - - // REX4: uses delegate's nonce → wrong bucket (high capacity, 3x multiplier). - let mut db_rex4 = build_db(); - let mut ctx_rex4 = MegaContext::new(&mut db_rex4, MegaSpecId::REX4) - .with_external_envs((&external_envs).into()); - ctx_rex4.modify_chain(|c| { - c.operator_fee_scalar = Some(U256::from(0)); - c.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm_rex4 = MegaEvm::new(ctx_rex4); - let mut tx_rex4 = MegaTransaction::new(tx); - tx_rex4.enveloped_tx = Some(Bytes::new()); - let r4 = alloy_evm::Evm::transact_raw(&mut evm_rex4, tx_rex4).unwrap(); - assert!(r4.result.is_success(), "REX4 should succeed: {:?}", r4.result); - let gas_rex4 = r4.result.gas_used(); - - // REX4 queries the high-capacity bucket (3x multiplier) → more gas. - // REX5 queries the correct bucket (1x multiplier) → less gas. - assert!( - gas_rex4 > gas_rex5, - "REX4 should use more gas ({gas_rex4}) than REX5 ({gas_rex5}) because \ - REX4 uses delegate's nonce for SALT lookup (hitting high-capacity bucket)" - ); -} - -/// CALL with value to a genuinely empty address should STILL charge the -/// new-account premium in REX5. -/// -/// This is the control case: `inspect_account` on a truly empty address correctly -/// sees it as empty and charges accordingly. -#[test] -fn test_rex5_call_to_truly_empty_address_charges_premium() { - let empty_target = address!("0000000000000000000000000000000000819999"); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(PARENT, U256::from(1_000_000_000u64)); - db.set_account_code(PARENT, build_call_with_value_contract(empty_target)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // A genuinely empty address should still incur new-account state growth. - assert!( - usage.state_growth > 0, - "CALL with value to truly empty address should record state growth: {}", - usage.state_growth - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs b/crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs deleted file mode 100644 index 0e2d71db7..000000000 --- a/crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! SSTORE storage-gas pricing error path. -//! -//! The dynamically-scaled storage gas for a first-time non-zero write is charged in -//! `storage_gas_ext::sstore`, before the inner SSTORE executes. When the SALT environment -//! fails to price the slot (`sstore_set_storage_gas` returns `None`), the instruction must -//! halt with `FatalExternalError`, which surfaces as `EVMError::Custom`. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BucketId, EVMError, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, SaltEnv, -}; -use revm::{ - bytecode::opcode::{SSTORE, STOP}, - context::{result::ResultAndState, TxEnv}, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000011"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000011"); - -/// A SALT environment that always fails `get_bucket_capacity`, triggering the -/// `sstore_set_storage_gas` → `None` → `FatalExternalError` path in the SSTORE wrapper. -#[derive(Debug)] -struct FailingSaltEnv; - -impl SaltEnv for FailingSaltEnv { - type Error = String; - - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err("injected salt error".into()) - } - - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } -} - -/// SSTORE(key=0, value=1): a first-time non-zero write to an originally-zero slot, -/// the only shape that triggers the dynamic storage-gas charge. -fn sstore_fresh_slot_bytecode() -> Bytes { - BytecodeBuilder::default() - .push_number(1u64) // value - .push_number(0u64) // key (top of stack) - .append(SSTORE) - .append(STOP) - .build() -} - -fn transact_with_failing_salt( - spec: MegaSpecId, - db: &mut MemoryDatabase, -) -> Result, EVMError> { - let envs: ExternalEnvs<(FailingSaltEnv, EmptyExternalEnv)> = - ExternalEnvs { salt_env: FailingSaltEnv, oracle_env: EmptyExternalEnv }; - let mut context = MegaContext::new(db, spec) - .with_external_envs(envs) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 1_000_000, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// A failing SALT pricing on a first-time SSTORE write must halt the instruction with -/// `FatalExternalError` before the inner SSTORE executes, surfacing as `EVMError::Custom`. -#[test] -fn test_rex5_sstore_salt_error_halts_with_fatal_external_error() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_code(CONTRACT, sstore_fresh_slot_bytecode()); - - let result = transact_with_failing_salt(MegaSpecId::REX5, &mut db); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected salt error"), - "error message should contain salt error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} diff --git a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs deleted file mode 100644 index 1f9e9d19c..000000000 --- a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs +++ /dev/null @@ -1,166 +0,0 @@ -//! REX6 CREATE-frame resource-accounting tests. -//! -//! Under REX6, `StateGrowthTracker` records +1 state growth for a `CREATE` only when the -//! deployment address is a net-new account; a pre-funded balance-only target already exists -//! and is not counted. Pre-REX6 records +1 unconditionally. -//! -//! This file also pins that a child-CREATE's creator nonce-bump account-info write is charged -//! to the parent frame's discardable lane under REX6, so the charge survives the child's revert -//! and is correctly attributed to the frame that owns the on-chain effect. - -use alloy_primitives::{Address, Bytes, U256}; -use mega_evm::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, ACCOUNT_INFO_WRITE_SIZE, -}; -use revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - BlockEnv, ContextSetters, TxEnv, - }, - handler::EvmTr, - primitives::TxKind, -}; - -const CALLER: Address = Address::new([ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0xDE, 0x00, 0x01, -]); -const CALLER_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH -const TX_GAS_LIMIT: u64 = 5_000_000; // generous headroom for a trivial CREATE; not a bound under test - -type TestEvm = MegaEvm; -type TestResult = ResultAndState; - -/// Builds a configured `MegaEvm` for `spec` with the given `limits` and operator fees zeroed -/// (so only the accounting under test moves). Single source of truth for block/chain setup. -fn make_evm_with_limits( - spec: MegaSpecId, - db: MemoryDatabase, - limits: EvmTxRuntimeLimits, -) -> TestEvm { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -/// Builds a configured `MegaEvm` for `spec` with no tx runtime limits and operator fees zeroed. -/// Shared by every test in this file that doesn't need custom limits. -fn make_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { - make_evm_with_limits(spec, db, EvmTxRuntimeLimits::no_limits()) -} - -/// Init code that immediately STOPs (deploys empty runtime) — a trivial successful CREATE. -fn stop_init_code() -> Bytes { - Bytes::from_static(&[0x00]) // STOP -} - -fn run(spec: MegaSpecId, db: MemoryDatabase, init_code: Bytes) -> (TestResult, TestEvm) { - let mut evm = make_evm(spec, db); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - data: init_code, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - (r, evm) -} - -/// The address a top-level CREATE from CALLER (nonce 0) deploys to. -fn first_create_address() -> Address { - CALLER.create(0) -} - -const OUTER_CREATOR: Address = Address::new([ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0xDE, 0x00, 0xFF, -]); - -/// Init code that returns `code_len` bytes of zeros from `memory[0..code_len]`. -/// -/// Layout: PUSH3 `code_len`; PUSH1 0; RETURN. -fn return_zeros_initcode(code_len: u32) -> Bytes { - let bytes = code_len.to_be_bytes(); - let mut code = Vec::with_capacity(7); - code.push(0x62); // PUSH3 - code.extend_from_slice(&bytes[1..]); // 3-byte big-endian length - code.push(0x60); // PUSH1 - code.push(0x00); - code.push(0xf3); // RETURN - Bytes::from(code) -} - -/// Runs a top-level CREATE under `spec` with `data_size_limit` as the tx data-size budget and a -/// constructor that RETURNs `code_len` runtime bytes, with `tx_gas_limit` available to the frame. -fn run_create_with_limits( - spec: MegaSpecId, - data_size_limit: u64, - code_len: u32, - tx_gas_limit: u64, -) -> TestResult { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data_size_limit); - let mut evm = make_evm_with_limits(spec, db, limits); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: tx_gas_limit, - gas_price: 0, - data: return_zeros_initcode(code_len), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError") -} - -/// REX6: a DB failure while inspecting the CREATE target for the net-new state-growth check must -/// surface as an error, not be silently swallowed. A normal `MemoryDatabase` is infallible, so the -/// `inspect_account(created_address, ..)?` error branch is only exercised by injecting a DB read -/// failure here. The created-address read happens after the caller-nonce read, so failing on -/// `first_create_address()` lets the caller read succeed and trips exactly the created-address -/// inspect. -#[test] -fn test_rex6_create_net_new_inspect_db_error_surfaces() { - let inner = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(first_create_address()); - - let mut context = MegaContext::new(db, MegaSpecId::REX6); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - data: stop_init_code(), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - let res = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(res.is_err(), "DB error during REX6 CREATE net-new inspect must surface as Err"); -} diff --git a/crates/mega-evm/tests/_pending/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs index 50ba6d9c9..deb3192f6 100644 --- a/crates/mega-evm/tests/_pending/rex6/error_paths.rs +++ b/crates/mega-evm/tests/_pending/rex6/error_paths.rs @@ -105,39 +105,6 @@ fn assert_injected_salt_custom_error( } } -/// `create_rex6` must surface a SALT-env failure on `create_contract_storage_gas` as a fatal -/// external error rather than charging zero storage gas for the new contract. -#[test] -fn test_rex6_create_salt_error_on_create_contract_storage_gas() { - // CREATE(value=0, offset=0, length=0): empty initcode, so the address is computed and the - // contract-creation storage-gas charge is reached without needing any memory contents. - let code = BytecodeBuilder::default() - .push_number(0u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .append(STOP) - .build(); - - assert_injected_salt_custom_error(transact_with_failing_salt(MegaSpecId::REX6, code)); -} - -/// REX6 SSTORE of a zero→non-zero slot must surface a SALT-env failure on `sstore_set_storage_gas` -/// as a fatal external error rather than charging zero storage gas for the set. -#[test] -fn test_rex6_sstore_salt_error_on_sstore_set_storage_gas() { - // SSTORE(key=0, value=1) into a fresh slot: original == present == 0, new != 0, so the - // dynamic `sstore_set_storage_gas` charge fires. - let code = BytecodeBuilder::default() - .push_number(1u64) // value - .push_number(0u64) // key - .append(SSTORE) - .append(STOP) - .build(); - - assert_injected_salt_custom_error(transact_with_failing_salt(MegaSpecId::REX6, code)); -} - fn is_stack_underflow(result: &crate::common::Outcome) -> bool { matches!(&result.result, revm::context::result::ExecutionResult::Halt { reason, .. } if format!("{reason:?}").contains("StackUnderflow")) diff --git a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs index 6362475fd..7218fd08d 100644 --- a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs +++ b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs @@ -279,55 +279,3 @@ fn test_rex6_sequencer_oracle_tx_succeeds_under_heavy_salt() { // 3. Determinism: system tx cost/state independent of bucket capacity // ============================================================================ -/// Runs the identical oracle system tx under light (1×) and heavy (100,000×) SALT, both REX6, and -/// asserts identical `gas_used` and identical resulting oracle state. This pins the core property: -/// a system-originated transaction's cost no longer depends on SALT bucket capacity. (Under REX5 -/// the heavy case would instead OOG.) -#[test] -fn test_rex6_system_tx_storage_gas_independent_of_bucket_capacity() { - fn run_oracle_tx(envs: TestExternalEnvs) -> (u64, U256) { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(envs); - let executor_factory = MegaBlockExecutorFactory::new( - rex6_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = - executor_factory.create_executor(&mut state, block_ctx, rex6_evm_env(BLOCK_GAS_LIMIT)); - executor.evm.ctx.chain_mut().operator_fee_scalar = Some(U256::ZERO); - executor.evm.ctx.chain_mut().operator_fee_constant = Some(U256::ZERO); - executor.apply_pre_execution_changes().expect("pre-execution"); - - let value = B256::with_last_byte(0xCD); - let tx = oracle_system_tx(0, ORACLE_SLOT, value); - let outcome = executor.run_transaction(&tx).expect("oracle system tx must execute"); - assert!(outcome.result.is_success(), "must succeed: {:?}", outcome.result); - let gas_used = outcome.result.gas_used(); - executor.commit_transaction_outcome(outcome).expect("commit"); - let slot = executor - .evm - .db_mut() - .storage(ORACLE_CONTRACT_ADDRESS, ORACLE_SLOT) - .expect("oracle storage read"); - (gas_used, slot) - } - - let (gas_light, slot_light) = run_oracle_tx(light_external_envs()); - let (gas_heavy, slot_heavy) = run_oracle_tx(heavy_external_envs()); - - assert_eq!( - gas_light, gas_heavy, - "exempt system tx gas must be independent of SALT bucket capacity (light={gas_light}, heavy={gas_heavy})", - ); - assert_eq!( - slot_light, slot_heavy, - "resulting oracle state must be identical regardless of bucket capacity" - ); -} diff --git a/crates/mega-evm/tests/_pending/src/evm/context.rs b/crates/mega-evm/tests/_pending/src/evm/context.rs deleted file mode 100644 index de57bad9d..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/context.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/context.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/context.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - use alloy_primitives::address; - use revm::{context::CfgEnv, database::EmptyDB}; - - use crate::TestExternalEnvs; - - /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. - #[test] - fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { - let external_envs = TestExternalEnvs::new(); - let parent = MegaContext::new(EmptyDB::default(), MegaSpecId::REX4) - .with_external_envs(external_envs.into()); - let parent_address = address!("0000000000000000000000000000000000100001"); - let sandbox_address = address!("0000000000000000000000000000000000100002"); - - parent - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(parent_address) - .expect("parent bucket lookup should succeed"); - let parent_bucket_ids = parent.accessed_bucket_ids(); - - let sandbox = - MegaContext::<_, TestExternalEnvs>::new_with_shared_ext_envs( - EmptyDB::default(), - MegaSpecId::REX4, - Rc::clone(&parent.salt_env), - Rc::clone(&parent.oracle_env), - ) - .with_block(parent.block().clone()) - .with_chain(parent.chain().clone()) - .with_inside_sandbox(true); - sandbox - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(sandbox_address) - .expect("sandbox bucket lookup should succeed"); - - assert_eq!(parent.accessed_bucket_ids(), parent_bucket_ids); - assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); - } - -} diff --git a/crates/mega-evm/tests/_pending/src/external/gas.rs b/crates/mega-evm/tests/_pending/src/external/gas.rs index 271776c5d..2957676b1 100644 --- a/crates/mega-evm/tests/_pending/src/external/gas.rs +++ b/crates/mega-evm/tests/_pending/src/external/gas.rs @@ -20,54 +20,6 @@ mod tests { DynamicGasCost::new(spec, env, 0) } - /// `MIN_BUCKET_SIZE * u64::MAX` cannot be represented in `u64`; verify the hardened - /// arithmetic does not panic and saturates instead of wrapping. - #[test] - fn test_sstore_set_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_new_account_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_create_contract_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - /// REX6 system-exempt path: the unscaled cost (`multiplier = 1`) is `0` for the REX-family - /// formula `base × (multiplier − 1)`, and is independent of the actual bucket capacity. This - /// is what makes a system call's storage cost immune to SALT bucket scaling. - #[test] - fn test_unscaled_gas_is_zero_for_rex_and_independent_of_capacity() { - for capacity in [MIN_BUCKET_SIZE as u64, 1_280_000, u64::MAX] { - let cost = cost_with_capacity(MegaSpecId::REX6, capacity); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - } - /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a /// tightened gate (e.g. REX1) fails here. @@ -107,14 +59,4 @@ mod tests { .create_contract_gas_unscaled(); } - /// The unscaled result equals the SALT-driven result evaluated at the minimum bucket - /// capacity, confirming the shared formula helper produces consistent values across both paths. - #[test] - fn test_unscaled_matches_salt_path_at_min_capacity() { - let mut cost = cost_with_capacity(MegaSpecId::REX6, MIN_BUCKET_SIZE as u64); - assert_eq!( - cost.sstore_set_gas_unscaled(), - cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(), - ); - } } diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index d6fdcbc0e..2c5f7e862 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -10,6 +10,7 @@ mod outcome; mod precompile_gas; mod pricing_table; mod salt; +mod salt_delegation; mod salt_failure; mod salt_refund; mod schedule; diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 1b6235de8..0668b7e2c 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -24,7 +24,7 @@ use mega_evm::{ MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, PUSH0, RETURN}, + bytecode::opcode::{CALL, CREATE, CREATE2, PUSH0, RETURN}, context::{result::EVMError, tx::TxEnvBuilder, TxEnv}, context_interface::cfg::GasId, }; @@ -81,10 +81,10 @@ pub(crate) fn crowded_slot(envs: SaltEnvs, address: Address, key: U256, m: u64) } /// A Satin context over `db` reading `envs`, with zero L1 fees. -pub(crate) fn salt_context( - db: MemoryDatabase, +pub(crate) fn salt_context( + db: DB, envs: SaltEnvs, -) -> MegaContext { +) -> MegaContext { MegaContext::new_with_external_envs( db, MegaSpecId::SATIN, @@ -131,14 +131,25 @@ pub(crate) fn call_contract() -> MegaTransaction { tx(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO) } -/// A transaction from `CALLER`. +/// A transaction from `CALLER`, at [`GAS_LIMIT`]. pub(crate) fn tx(kind: TxKind, data: Bytes, value: U256) -> MegaTransaction { + tx_with_gas(kind, data, value, GAS_LIMIT) +} + +/// A transaction from `CALLER` at a gas limit of its own, for a probe whose charge does not fit +/// in [`GAS_LIMIT`]. +pub(crate) fn tx_with_gas( + kind: TxKind, + data: Bytes, + value: U256, + gas_limit: u64, +) -> MegaTransaction { OpTx(op_transaction(TxEnv { caller: CALLER, kind, data, value, - gas_limit: GAS_LIMIT, + gas_limit, ..Default::default() })) } @@ -539,3 +550,183 @@ fn test_the_minimum_bucket_matches_the_engine_without_a_salt_environment() { assert_eq!(with_salt, without_salt); } + +/* What the multiplier has nothing to scale: the writes that add no state. */ + +/// Runs `probe` at the minimum bucket and at a crowded one and requires both to charge nothing +/// on the state ledger — a write that adds no state has nothing for `m` to multiply. +fn assert_charges_no_state_gas( + site: &str, + crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs, + probe: impl Fn() -> (MemoryDatabase, MegaTransaction) + Copy, +) { + for m in [1, 8] { + let (db, tx) = probe(); + let outcome = run(db, crowd(minimal_envs(), m), tx); + assert_eq!(outcome.gas.state, 0, "{site} at m = {m}"); + } +} + +/// Writing over a slot that already held a value adds no state, so it pays no state gas +/// however crowded its bucket is. +#[test] +fn test_writing_over_a_slot_charges_no_state_gas() { + assert_charges_no_state_gas( + "a reset", + |envs, m| crowded_slot(envs, CONTRACT, U256::ZERO, m), + || { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(2)).stop().build(); + (db(code).account_storage(CONTRACT, U256::ZERO, U256::from(1)), call_contract()) + }, + ); +} + +/// Clearing a slot removes state rather than adding it, so it pays no state gas either. +#[test] +fn test_clearing_a_slot_charges_no_state_gas() { + assert_charges_no_state_gas( + "a clear", + |envs, m| crowded_slot(envs, CONTRACT, U256::ZERO, m), + || { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); + (db(code).account_storage(CONTRACT, U256::ZERO, U256::from(1)), call_contract()) + }, + ); +} + +/// A slot is one leaf however many times the transaction writes it: the first write off zero +/// pays, the rest pay nothing. +#[test] +fn test_a_slot_written_twice_pays_for_one_leaf() { + let set = entry(GasId::sstore_set_state_gas()); + assert_scales( + "a slot written twice", + set, + |envs, m| crowded_slot(envs, CONTRACT, U256::ZERO, m), + || { + let code = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::from(2)) + .stop() + .build(); + (db(code), call_contract()) + }, + ); +} + +/// Value reaching an account that already exists adds no leaf, at the top level and from a +/// frame alike. +#[test] +fn test_a_transfer_to_an_account_that_exists_charges_no_state_gas() { + const FUNDED: Address = address!("0000000000000000000000000000000000c00006"); + + assert_charges_no_state_gas( + "a top-level transfer to an existing account", + |envs, m| crowded_account(envs, FUNDED, m), + || { + let db = db(Bytes::new()).account_balance(FUNDED, U256::from(1)); + (db, tx(TxKind::Call(FUNDED), Bytes::new(), U256::from(1))) + }, + ); + + assert_charges_no_state_gas( + "a transfer from a frame to an existing account", + |envs, m| crowded_account(envs, FUNDED, m), + || { + let db = db(value_call(FUNDED).stop().build()).account_balance(FUNDED, U256::from(1)); + (db, call_contract()) + }, + ); +} + +/* The remaining creation sites. */ + +/// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in +/// that address's bucket just as `CREATE` is. +#[test] +fn test_the_create2_charge_scales_with_the_created_address_s_bucket() { + const SALT: U256 = U256::ZERO; + let init: [u8; 3] = [PUSH0, PUSH0, RETURN]; + let created = CONTRACT.create2_from_code(SALT.to_be_bytes::<32>(), init); + + assert_scales( + "CREATE2", + entry(GasId::create_state_gas()), + move |envs, m| crowded_account(envs, created, m), + move || { + let code = BytecodeBuilder::default() + .mstore(0, init) + .push_u256(SALT) + .push_number(init.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .stop() + .build(); + (db(code), call_contract()) + }, + ); +} + +/// An account leaf costs the same however it comes about: the entry a creation pays and the one +/// a value transfer pays are the same number, because they buy the same leaf. +#[test] +fn test_an_account_leaf_costs_the_same_however_it_is_added() { + assert_eq!(entry(GasId::create_state_gas()), entry(GasId::new_account_state_gas())); + + let created = CONTRACT.create(0); + let creation = run( + db(create_empty_contract().stop().build()), + crowded_account(minimal_envs(), created, 8), + call_contract(), + ); + let transfer = run( + db(value_call(EMPTY).stop().build()), + crowded_account(minimal_envs(), EMPTY, 8), + call_contract(), + ); + + assert_eq!(creation.gas.state, transfer.gas.state); +} + +/// A creation that also writes a slot pays for both leaves, each in the bucket it lands in: the +/// account in the created address's, the slot in its own. +#[test] +fn test_a_creation_that_writes_a_slot_pays_both_in_their_own_buckets() { + const ACCOUNT_M: u64 = 2; + const SLOT_M: u64 = 4; + let created = CALLER.create(0); + // Init code writing slot 0 of the contract being created, then deploying nothing. + let init = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, RETURN]) + .build(); + + let envs = crowded_account(minimal_envs(), created, ACCOUNT_M); + let envs = crowded_slot(envs, created, U256::ZERO, SLOT_M); + let outcome = run(db(Bytes::new()), envs, tx(TxKind::Create, init, U256::ZERO)); + + assert_eq!( + outcome.gas.state, + entry(GasId::create_state_gas()) * ACCOUNT_M + + entry(GasId::sstore_set_state_gas()) * SLOT_M, + ); +} + +/// The multiplier is linear over the whole range a bucket can grow through, not just the small +/// ones the other probes use. The largest of these charges more than the execution cap allows +/// in regular gas, so the probe brings a budget that puts the excess in the state reservoir — +/// which is where a charge this size is meant to be paid from. +#[test] +fn test_the_multiplier_is_linear_over_a_wide_range() { + const WIDE_GAS_LIMIT: u64 = 400_000_000; + let set = entry(GasId::sstore_set_state_gas()); + let code = || BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + + for m in [1, 2, 10, 1_000] { + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::ZERO, m); + let probe = tx_with_gas(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO, WIDE_GAS_LIMIT); + let outcome = run(db(code()), envs, probe); + assert_eq!(outcome.gas.state, set * m, "at m = {m}"); + } +} diff --git a/crates/mega-evm/tests/satin/salt_delegation.rs b/crates/mega-evm/tests/satin/salt_delegation.rs new file mode 100644 index 000000000..b427c098c --- /dev/null +++ b/crates/mega-evm/tests/satin/salt_delegation.rs @@ -0,0 +1,289 @@ +//! SALT pricing across an EIP-7702 delegation, and across the call kinds that do not add state. +//! +//! Two things a state gas charge must get right when the target of a call carries a delegation +//! designator: +//! +//! - the target is an account that *exists*, so reaching it with value adds no leaf and costs no +//! state gas, however crowded its bucket is; and +//! - deciding that must not follow the designator further than the one hop EIP-7702 allows. A +//! designator can point at itself, or two of them at each other; resolving such a chain to a +//! fixed point does not terminate. These probes reach a cycle through each call-family opcode and +//! through both creation opcodes, and require the transaction to settle. +//! +//! `CALLCODE` is here for the same reason from the other side: it runs the callee's code in the +//! caller's own account and sends value to that account, so it adds no leaf either, whatever the +//! callee looks like. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, PUSH0, RETURN, STATICCALL, STOP, + }, + context_interface::cfg::GasId, + database::AccountState, + state::Bytecode, +}; + +use crate::salt::{ + account_bucket, call_contract, crowded_account, db, entry, minimal_envs, run, try_run, + SaltEnvs, CONTRACT, EMPTY, +}; + +/// An account whose code is a delegation designator pointing at itself. +const SELF_DELEGATING: Address = address!("0000000000000000000000000000000000c00010"); +/// One half of a two-address delegation cycle. +const CYCLE_A: Address = address!("0000000000000000000000000000000000c00011"); +/// The other half. +const CYCLE_B: Address = address!("0000000000000000000000000000000000c00012"); + +/// Writes the `0xef0100 || address` designator an applied EIP-7702 authorization leaves behind. +fn with_delegation(mut db: MemoryDatabase, address: Address, to: Address) -> MemoryDatabase { + let bytecode = Bytecode::new_eip7702(to); + let code_hash = bytecode.hash_slow(); + let account = db.load_account(address).expect("the account is in memory"); + account.info.code = Some(bytecode); + account.info.code_hash = code_hash; + account.account_state = AccountState::None; + db +} + +/// `CALL(gas, target, 0, 0, 0, 0, 0)` followed by `STOP`. +fn calls(target: Address) -> Bytes { + BytecodeBuilder::default() + .append(PUSH0) + .append(PUSH0) + .append(PUSH0) + .append(PUSH0) + .append(PUSH0) + .push_address(target) + .append(GAS) + .append(CALL) + .append(STOP) + .build() +} + +/// The three call kinds that take no value operand, plus `CALLCODE`, against `target`. +fn calls_with(opcode: u8, target: Address) -> Bytes { + let mut code = + BytecodeBuilder::default().append(PUSH0).append(PUSH0).append(PUSH0).append(PUSH0); + if opcode == CALLCODE { + code = code.append(PUSH0); + } + code.push_address(target).append(GAS).append(opcode).append(STOP).build() +} + +/// `CREATE`, or `CREATE2` with salt zero, of an init code that deploys nothing. +fn creates(opcode: u8) -> Bytes { + let init: [u8; 3] = [PUSH0, PUSH0, RETURN]; + let mut code = BytecodeBuilder::default().mstore(0, init); + if opcode == CREATE2 { + code = code.push_number(0u64); + } + code.push_number(init.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(opcode) + .append(STOP) + .build() +} + +/// Requires the probe to settle into a receipt at all. A delegation chain resolved to a fixed +/// point would not return here — the test would not fail, it would never finish — so what this +/// asserts is that the engine followed the designator the one hop EIP-7702 allows and no further. +fn assert_settles(what: &str, db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + let outcome = try_run(db, minimal_envs(), tx).unwrap_or_else(|e| panic!("{what}: {e:?}")); + assert!(outcome.gas.gas_used > 0, "{what}: the transaction produced no receipt"); + outcome +} + +/// The outer frame of a probe stops after the call it makes, so the transaction succeeds +/// whatever the frame it called did. +fn assert_outer_frame_succeeds(what: &str, db: MemoryDatabase, tx: MegaTransaction) { + let outcome = assert_settles(what, db, tx); + assert!(outcome.result.is_success(), "{what}: {:?}", outcome.result); +} + +/* Delegation cycles reached through each opcode that prices a state charge. */ + +#[test] +fn test_a_call_to_a_self_delegating_account_settles() { + let db = with_delegation(db(calls(SELF_DELEGATING)), SELF_DELEGATING, SELF_DELEGATING); + assert_outer_frame_succeeds("CALL", db, call_contract()); +} + +#[test] +fn test_a_call_into_a_two_address_delegation_cycle_settles() { + let db = with_delegation(db(calls(CYCLE_A)), CYCLE_A, CYCLE_B); + let db = with_delegation(db, CYCLE_B, CYCLE_A); + assert_outer_frame_succeeds("CALL into a cycle", db, call_contract()); +} + +#[test] +fn test_a_staticcall_to_a_self_delegating_account_settles() { + let db = with_delegation( + db(calls_with(STATICCALL, SELF_DELEGATING)), + SELF_DELEGATING, + SELF_DELEGATING, + ); + assert_outer_frame_succeeds("STATICCALL", db, call_contract()); +} + +#[test] +fn test_a_delegatecall_into_a_two_address_delegation_cycle_settles() { + let db = with_delegation(db(calls_with(DELEGATECALL, CYCLE_A)), CYCLE_A, CYCLE_B); + let db = with_delegation(db, CYCLE_B, CYCLE_A); + assert_outer_frame_succeeds("DELEGATECALL into a cycle", db, call_contract()); +} + +#[test] +fn test_a_callcode_to_a_self_delegating_account_settles() { + let db = with_delegation( + db(calls_with(CALLCODE, SELF_DELEGATING)), + SELF_DELEGATING, + SELF_DELEGATING, + ); + assert_outer_frame_succeeds("CALLCODE", db, call_contract()); +} + +/// The top level resolves a delegation with the same one-hop rule, so a transaction sent +/// straight at a self-delegating address is the control arm of the five above. One hop lands +/// back on the designator, whose own bytes are then what runs — which is not a program, so the +/// transaction settles without succeeding. +#[test] +fn test_a_transaction_to_a_self_delegating_account_settles() { + let db = with_delegation(db(Bytes::new()), SELF_DELEGATING, SELF_DELEGATING); + let outcome = assert_settles( + "a direct transaction", + db, + crate::salt::tx(revm::primitives::TxKind::Call(SELF_DELEGATING), Bytes::new(), U256::ZERO), + ); + assert!(!outcome.result.is_success(), "the designator's own bytes are not a program"); +} + +/// A `CREATE` runs inside a delegated frame: the creator whose nonce derives the address, and +/// whose bucket prices the charge, is the delegating account, reached through the designator. +#[test] +fn test_a_create_from_a_delegated_frame_settles() { + let db = db(calls(CYCLE_A)).account_code(CYCLE_B, creates(CREATE)); + let db = with_delegation(db, CYCLE_A, CYCLE_B); + assert_outer_frame_succeeds("CREATE", db, call_contract()); +} + +/// The same through `CREATE2`, which derives its address by hashing rather than by nonce. +#[test] +fn test_a_create2_from_a_delegated_frame_settles() { + let db = db(calls(CYCLE_A)).account_code(CYCLE_B, creates(CREATE2)); + let db = with_delegation(db, CYCLE_A, CYCLE_B); + assert_outer_frame_succeeds("CREATE2", db, call_contract()); +} + +/* What a delegation designator means for the price. */ + +/// An account carrying a delegation designator exists, so value reaching it adds no leaf and +/// costs no state gas however crowded its bucket is. +#[test] +fn test_a_value_call_to_a_delegated_account_charges_no_state_gas() { + let target = SELF_DELEGATING; + for m in [1, 8] { + let db = with_delegation(db(crate::salt::value_call(target).stop().build()), target, EMPTY); + let envs = crowded_account(minimal_envs(), target, m); + assert_eq!(run(db, envs, call_contract()).gas.state, 0, "at m = {m}"); + } +} + +/// The control arm: the same call to an address that really is empty pays for the leaf it adds, +/// at the crowded price. +#[test] +fn test_a_value_call_to_a_truly_empty_address_pays_the_crowded_price() { + let envs = crowded_account(minimal_envs(), EMPTY, 8); + let outcome = run(db(crate::salt::value_call(EMPTY).stop().build()), envs, call_contract()); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas()) * 8); +} + +/// A `CREATE` executed inside a delegated frame deploys from the delegating account, so the +/// charge lands in the bucket of the address *that* account's nonce derives — not the delegate's. +#[test] +fn test_a_create_inside_a_delegated_frame_is_priced_at_the_authority_s_address() { + const AUTHORITY: Address = address!("0000000000000000000000000000000000c00013"); + const CODE: Address = address!("0000000000000000000000000000000000c00014"); + let created = AUTHORITY.create(0); + let delegate_created = CODE.create(0); + + let db = db(calls(AUTHORITY)).account_code(CODE, creates(CREATE)); + let db = with_delegation(db, AUTHORITY, CODE); + + let envs = crowded_account(minimal_envs(), created, 8); + let outcome = run(db.clone(), envs.clone(), call_contract()); + assert_eq!( + outcome.gas.state, + entry(GasId::create_state_gas()) * 8, + "the authority's own address is what was priced", + ); + assert_eq!(envs.bucket_queries(account_bucket(created)), 1); + + // Crowding the address the delegate's own nonce would derive changes nothing. + let envs = crowded_account(minimal_envs(), delegate_created, 8); + let outcome = run(db, envs, call_contract()); + assert_eq!(outcome.gas.state, entry(GasId::create_state_gas())); +} + +/* CALLCODE: value that never leaves the caller's account. */ + +/// `CALLCODE` sends value to the caller's own account, which exists, so it adds no leaf — even +/// when the code it borrows lives at an address that does not exist. +#[test] +fn test_a_callcode_to_an_empty_account_charges_no_state_gas() { + for m in [1, 8] { + let code = callcode_with_value(EMPTY); + let envs = crowded_account(minimal_envs(), EMPTY, m); + assert_eq!(run(db(code), envs, call_contract()).gas.state, 0, "at m = {m}"); + } +} + +/// The same, with the borrowed code at an account carrying a delegation designator. +#[test] +fn test_a_callcode_to_a_delegated_account_charges_no_state_gas() { + let db = with_delegation(db(callcode_with_value(SELF_DELEGATING)), SELF_DELEGATING, EMPTY); + let envs = crowded_account(minimal_envs(), SELF_DELEGATING, 8); + assert_eq!(run(db, envs, call_contract()).gas.state, 0); +} + +/// And the control arm again: a `CALL` to the same empty address does add a leaf, and pays for +/// it. Without this the two above could be passing because nothing was charged anywhere. +#[test] +fn test_a_call_to_the_same_empty_account_still_pays() { + let envs = crowded_account(minimal_envs(), EMPTY, 8); + let outcome = run(db(crate::salt::value_call(EMPTY).stop().build()), envs, call_contract()); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas()) * 8); +} + +/// `CALLCODE(gas, target, 1, 0, 0, 0, 0)` followed by `STOP`. +fn callcode_with_value(target: Address) -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(target) + .push_number(1_000_000u64) + .append(CALLCODE) + .append(STOP) + .build() +} + +/// A broken SALT environment does not fail a program built only of calls that add no state: +/// nothing on that path asks the pricing hook for a number. +#[test] +fn test_a_callcode_does_not_consult_the_pricing_hook() { + let envs: SaltEnvs = + minimal_envs().with_failing_bucket(account_bucket(EMPTY), "unreachable".into()); + let outcome = + try_run(db(callcode_with_value(EMPTY)), envs, call_contract()).expect("nothing was priced"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0); +} diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs index 5b9c75a86..988e5aed2 100644 --- a/crates/mega-evm/tests/satin/salt_failure.rs +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -198,3 +198,28 @@ fn test_a_system_call_is_unaffected_by_an_unreadable_bucket() { .expect("a system call does not read SALT"); assert!(result.result.is_success(), "{:?}", result.result); } + +/// The read that decides whether a creation adds an account leaf can fail on its own, without +/// the SALT environment being involved at all. Its failure is the database's, and it surfaces as +/// such — the pricing hook is never reached, so nothing is charged at a price nobody chose. +#[test] +fn test_a_database_error_on_the_create_target_read_fails_the_transaction() { + use mega_evm::test_utils::{ErrorInjectingDatabase, InjectedDbError}; + + let created = CALLER.create(0); + let mut db = ErrorInjectingDatabase::new(db(Bytes::new())); + db.fail_on_account = Some(created); + + let result = MegaEvm::new(salt_context(db, minimal_envs())).execute_transaction(tx( + TxKind::Create, + Bytes::from_static(&[PUSH0, PUSH0, RETURN]), + U256::ZERO, + )); + + match result { + Err(EVMError::Database(InjectedDbError(message))) => { + assert!(message.contains("injected basic()"), "got {message}"); + } + other => panic!("expected a database error, got {other:?}"), + } +} From 2a05c8fb878f6d1973f8acb55d999d9067625203 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:35:04 +0800 Subject: [PATCH 140/201] feat(system): run the system-address transaction as a deposit A legacy transaction from the system address is validated and promoted to a deposit before op-revm validates it: it may only call a contract on the whitelist and never create one, it carries the chain's id, its nonce is the system address's, and the system address carries no code. The deposit path then drops the signature, the nonce check and every fee, and the gas price goes to zero with the promotion, so no fee is paid and none is rewarded. The checks a caller switches off for user transactions are switched off here too. The account a deposit-like transaction creates for its caller is charged the account-creation state gas, where EIP-2780 charges a recipient's and before it, so a transaction that creates both pays for both and one whose recipient is its own caller pays once. The system address's account is read without warming it, so validation does not make the transaction's first touch of it cheaper than anyone else's. --- crates/mega-evm/src/evm/execution.rs | 76 ++- crates/mega-evm/src/system/mod.rs | 6 + crates/mega-evm/src/system/tx.rs | 289 ++++++++++++ crates/mega-evm/tests/system/main.rs | 1 + crates/mega-evm/tests/system/system_tx.rs | 550 ++++++++++++++++++++++ 5 files changed, 917 insertions(+), 5 deletions(-) create mode 100644 crates/mega-evm/src/system/tx.rs create mode 100644 crates/mega-evm/tests/system/system_tx.rs diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 867869f91..b53bb4fdd 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -6,6 +6,8 @@ #[cfg(not(feature = "std"))] use alloc as std; +use core::cell::Cell; + use op_revm::{ handler::{IsTxError, OpHandler}, OpHaltReason, OpTransactionError, @@ -19,8 +21,9 @@ use revm::{ JournalTr, Transaction, }, context_interface::{ - cfg::gas::GasTracker, + cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, + Host, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, @@ -41,22 +44,30 @@ use revm::{ }; use crate::{ - evm::inspector::frame_end_checked, synthetic_frame_result, ExternalEnvTypes, LimitCheck, - MegaContext, MegaEvm, MegaInstructions, + evm::inspector::frame_end_checked, + synthetic_frame_result, + system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, + ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, MegaInstructions, }; /// The Satin handler. /// /// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. +/// One handler runs one transaction, so what a phase learns about it is kept here. #[derive(Debug)] pub struct MegaHandler { op: OpHandler, + /// Whether validation found the caller of a deposit-like transaction empty, so executing it + /// creates that account. Read by the pre-execution phase, which charges for the account + /// before the transaction runs; by then the caller has been materialised and the fact is no + /// longer visible in the state. + deposit_creates_caller: Cell, } impl MegaHandler { /// Creates a handler. pub fn new() -> Self { - Self { op: OpHandler::new() } + Self { op: OpHandler::new(), deposit_creates_caller: Cell::new(false) } } } @@ -78,7 +89,13 @@ where type Error = ERROR; type HaltReason = OpHaltReason; - /// revm's pre-execution, then the write records of the EIP-7702 authorities it applied. + /// revm's pre-execution, with the account a deposit-like transaction creates for its caller + /// charged first, then the write records of the EIP-7702 authorities it applied. + /// + /// The caller's account is charged where EIP-2780 charges the recipient's, and before it: + /// a transaction that creates both pays for both, and a transaction whose recipient is its + /// own caller pays once, because by the time EIP-2780 looks at the recipient the account + /// exists. /// /// When those records would cross a limit, the limit is enforced before the writes it /// guards: the authorizations are taken back with the gas they charged, and the transaction, @@ -90,6 +107,10 @@ where ) -> Result, Self::Error> { self.load_accounts(evm)?; let checkpoint = evm.ctx().journal_mut().checkpoint(); + if self.deposit_creates_caller.get() && !charge_created_caller(evm.ctx_mut(), gas) { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + return Ok(None); + } let gas_before = *gas; let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { evm.ctx().journal_mut().checkpoint_revert(checkpoint); @@ -104,15 +125,28 @@ where Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } + /// Validates a transaction sent from the system address and promotes it to a deposit, then + /// validates the transaction as op-revm does — as a deposit, when it was promoted. fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { + crate::system::validate_and_promote::<_, _, Self::Error>( + evm.ctx_mut(), + MEGA_SYSTEM_ADDRESS, + )?; self.op.validate_env(evm) } + /// Notes whether this transaction's caller is an account executing it creates, then deducts + /// the caller as op-revm does, which is what creates it. + /// + /// Only a deposit-like transaction can have one: every other transaction pays a fee, which + /// an empty account cannot. The account is charged for in + /// [`pre_execution`](Handler::pre_execution). fn validate_against_state_and_deduct_caller( &self, evm: &mut Self::Evm, init_and_floor_gas: &mut InitialAndFloorGas, ) -> Result<(), Self::Error> { + self.deposit_creates_caller.set(deposit_creates_caller(evm.ctx_mut())?); self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } @@ -567,6 +601,38 @@ fn inspect_logs( } } +/// Whether executing this transaction creates its caller's account: a deposit-like transaction +/// whose caller is empty, which the deposit path materialises by bumping its nonce or by minting +/// to it. +/// +/// Read before op-revm deducts the caller, which is what materialises the account. Every other +/// transaction pays a fee its caller must hold, so it has an account already. +/// +/// The read does not warm the account: the transaction's own touches of it pay what they would +/// have paid without the check. +fn deposit_creates_caller( + ctx: &mut MegaContext, +) -> Result { + if !is_deposit_like_transaction(ctx.tx(), MEGA_SYSTEM_ADDRESS) { + return Ok(false); + } + let caller = ctx.tx().caller(); + Ok(ctx.journal_mut().inspect_account(caller, false)?.info.is_empty()) +} + +/// Charges the state gas of the account a deposit-like transaction creates for its caller, as +/// EIP-2780 charges the account a value transfer creates for its recipient. `false` when the +/// transaction cannot pay it, which is an out-of-gas before it runs. +fn charge_created_caller( + ctx: &mut MegaContext, + gas: &mut GasTracker, +) -> bool { + let caller = ctx.tx().caller(); + let charge = StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(caller)); + let Some(state_gas) = ctx.state_gas_charge(charge) else { return false }; + gas.record_state_cost(state_gas) +} + /// The nonce of an account the journal holds; zero for one it does not. fn account_nonce( ctx: &MegaContext, diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index 8db1d122d..d72eec85f 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -11,6 +11,9 @@ //! module for the dispatch order and the shape of an answer). The timestamp wrapper and the //! `SequencerRegistry` run their bytecode. //! +//! [`tx`](tx) holds the system-address transaction: the deposit-like transaction the sequencer +//! maintains the protocol's own state with. +//! //! Deploying the contracts at the fork that activates them belongs to system contract //! deployment; it is not here. @@ -22,6 +25,7 @@ mod limit_control; mod oracle; mod sequencer_registry; mod timestamp; +mod tx; pub use control::*; pub use intercept::NON_ZERO_TRANSFER_REVERT_DATA; @@ -29,8 +33,10 @@ pub use limit_control::*; pub use oracle::*; pub use sequencer_registry::*; pub use timestamp::*; +pub use tx::*; pub(crate) use intercept::intercept; +pub(crate) use tx::validate_and_promote; #[cfg(test)] mod tests { diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs new file mode 100644 index 000000000..8c75cf119 --- /dev/null +++ b/crates/mega-evm/src/system/tx.rs @@ -0,0 +1,289 @@ +//! The system-address transaction: how the protocol maintains its own state. +//! +//! The sequencer writes what the protocol owes the chain — the oracle values it served, for one +//! — through transactions sent from [`MEGA_SYSTEM_ADDRESS`]. They carry no signature and pay no +//! fee, so they are executed as deposit transactions: the engine stamps +//! [`MEGA_SYSTEM_TRANSACTION_SOURCE_HASH`] on one before it validates it, and op-revm's deposit +//! path takes it from there. +//! +//! A deposit is unvalidated by construction, so the engine validates what still matters itself +//! before promoting the transaction ([`validate_and_promote`]): +//! +//! - it may only call a contract on [`MEGA_SYSTEM_TX_WHITELIST`], never create one; +//! - its chain id must be the chain's, so a transaction cannot be replayed on another chain; +//! - its nonce must be the system address's, so it cannot be replayed on this one; +//! - the system address must have no code of its own (EIP-3607). +//! +//! The configuration switches that turn those checks off for a user transaction +//! (`tx_chain_id_check`, `disable_nonce_check`, `disable_eip3607`) turn them off here too: a +//! caller simulating a transaction sees one shape of validation, not two. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::string::ToString; + +use alloy_evm::Database; +use alloy_primitives::{address, b256, Address, TxKind, B256}; +use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; +use revm::{ + context::{result::FromStringError, ContextTr, Transaction}, + context_interface::{cfg::Cfg, result::InvalidTransaction}, + handler::pre_execution::validate_account_nonce_and_code, +}; + +use crate::{ + system::ORACLE_CONTRACT_ADDRESS, types::MegaTransaction, ExternalEnvTypes, JournalInspectTr, + MegaContext, +}; + +/// The address the sequencer sends the protocol's own transactions from. +/// +/// A transaction from it is executed as a deposit: no signature, no nonce check of op-revm's own +/// and no fee. Which address it is can be rotated through the `SequencerRegistry`; reading the +/// rotated one out of the registry's storage belongs to system contract deployment, and until +/// then this is the address. +pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); + +/// The contracts a system-address transaction may call. It may call nothing else and create +/// nothing. +pub const MEGA_SYSTEM_TX_WHITELIST: &[Address] = &[ORACLE_CONTRACT_ADDRESS]; + +/// The `source_hash` of a promoted system-address transaction, +/// `keccak256("MEGA_SYSTEM_TRANSACTION")`. +/// +/// It marks the transaction as the protocol's own: op-revm sees a deposit, and the engine can +/// tell a promoted system transaction from a user's deposit by the hash alone. +pub const MEGA_SYSTEM_TRANSACTION_SOURCE_HASH: B256 = + b256!("852c082c0faff590c6300c2c34815d1f79882552fa95ba413cd5aeb1dba84957"); + +/// Whether `tx` was sent from `system_address`. +pub fn sent_from_system_address(tx: &MegaTransaction, system_address: Address) -> bool { + tx.caller() == system_address +} + +/// Whether `tx` is a system-address transaction: a legacy transaction from `system_address` to a +/// contract on [`MEGA_SYSTEM_TX_WHITELIST`]. +pub fn is_mega_system_transaction_with(tx: &MegaTransaction, system_address: Address) -> bool { + check_if_mega_system_transaction(tx.caller(), tx.tx_type(), tx.kind(), system_address) +} + +/// Whether a transaction with these fields is a system-address transaction. +/// +/// It is one when it was sent from `system_address` as a legacy transaction (type `0x0`, the +/// shape the sequencer builds) and calls a contract on [`MEGA_SYSTEM_TX_WHITELIST`]. A creation +/// is never one: the protocol maintains the contracts it deployed, it does not deploy new ones +/// this way. +pub fn check_if_mega_system_transaction( + tx_signer: Address, + tx_type: u8, + tx_kind: TxKind, + system_address: Address, +) -> bool { + if tx_type != 0x0 || tx_signer != system_address { + return false; + } + match tx_kind { + TxKind::Create => false, + TxKind::Call(address) => MEGA_SYSTEM_TX_WHITELIST.contains(&address), + } +} + +/// Whether `tx` is executed on the deposit path: a deposit transaction, or a system-address +/// transaction, which is promoted to one. +pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address) -> bool { + tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || is_mega_system_transaction_with(tx, system_address) +} + +/// Whether `tx` was produced by the protocol itself rather than by a user. +/// +/// That is the case for a call the engine makes on the chain's behalf (the EIP-2935 and EIP-4788 +/// pre-block calls, whose caller is the EIP-4788 system address) and for a system-address +/// transaction, before or after it was promoted. A user's deposit transaction is not +/// system-originated, however deposit-like it is: it carries another source hash and another +/// caller. +/// +/// It is what exempts the protocol's own work from the metering `MegaETH` holds users to — the +/// history gas of a system transaction is not charged, so the protocol's maintenance cannot fail +/// on a resource limit. The mechanisms that meter read it as they land. +pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bool { + tx.caller() == alloy_eips::eip4788::SYSTEM_ADDRESS || + tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH || + is_mega_system_transaction_with(tx, system_address) +} + +/// Validates a transaction sent from the system address and promotes it to a deposit; does +/// nothing to any other transaction. +/// +/// Runs before op-revm validates the transaction, so op-revm sees the promoted shape: a deposit, +/// whose signature, nonce and fee it does not check. The checks the deposit path drops and this +/// chain still wants are made here (see the module documentation), each under the configuration +/// switch a user transaction obeys. +/// +/// A transaction from the system address that is not a system transaction — it creates a +/// contract, or calls a contract that is not whitelisted — is rejected outright: the sequencer +/// has no business sending it, and promoting it would give it the deposit path's exemptions. +pub(crate) fn validate_and_promote( + ctx: &mut MegaContext, + system_address: Address, +) -> Result<(), ERROR> +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + ERROR: From + From + FromStringError, +{ + if !sent_from_system_address(ctx.tx(), system_address) { + return Ok(()); + } + if !is_mega_system_transaction_with(ctx.tx(), system_address) { + return Err(ERROR::from_string( + "the callee of a system transaction is not on the whitelist".to_string(), + )); + } + + let cfg = ctx.cfg(); + let (chain_id, chain_id_check) = (cfg.chain_id(), cfg.tx_chain_id_check); + let (eip3607_disabled, nonce_check_disabled) = + (cfg.is_eip3607_disabled(), cfg.is_nonce_check_disabled()); + if chain_id_check { + match ctx.tx().chain_id() { + None => return Err(InvalidTransaction::MissingChainId.into()), + Some(id) if id != chain_id => return Err(InvalidTransaction::InvalidChainId.into()), + Some(_) => {} + } + } + + // Read the system address without warming it: validation must not leave the account in the + // EIP-2929 access list, which would make the transaction's first touch of it cheaper than + // the same transaction from anyone else. Its code is loaded, so EIP-3607 sees a lazy + // database's code too. + let tx_nonce = ctx.tx().nonce(); + let account = ctx.journal_mut().inspect_account(system_address, true)?; + validate_account_nonce_and_code( + &account.info, + tx_nonce, + eip3607_disabled, + nonce_check_disabled, + )?; + + // The deposit shape: op-revm skips the signature, the nonce and every fee for it. The gas + // price goes to zero with it, so the fee accounting of the block degenerates to nothing. + let tx = &mut ctx.inner.tx; + tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + tx.base.gas_price = 0; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::TxKind; + + const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; + const USER: Address = address!("0x0000000000000000000000000000000000009999"); + const NOT_WHITELISTED: Address = address!("0x00000000000000000000000000000000000000ab"); + + /// A legacy call transaction from `caller` to `to`. + fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { + let mut tx = MegaTransaction::default(); + tx.base.tx_type = 0; + tx.base.caller = caller; + tx.base.kind = TxKind::Call(to); + tx + } + + /// The pre-block calls the engine makes are system-originated whatever the system address + /// is: their caller is the EIP-4788 system address, which no key can sign for. + #[test] + fn test_is_system_originated_matches_eip_system_address_caller() { + let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(is_system_originated(&tx, USER)); + } + + #[test] + fn test_is_system_originated_matches_mega_system_tx() { + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NOT_WHITELISTED); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + /// The promotion stamps the source hash and flips the transaction's type to a deposit; the + /// promoted shape is still system-originated, through the source hash. + #[test] + fn test_is_system_originated_matches_promoted_mega_system_tx() { + let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "the promotion makes it a deposit"); + assert!( + !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), + "the legacy-typed check no longer matches after the promotion", + ); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "the source hash does"); + } + + #[test] + fn test_is_system_originated_rejects_user_tx() { + let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + /// A user's deposit transaction is deposit-like but not system-originated: otherwise a user + /// could buy the protocol's exemptions by sending one. + #[test] + fn test_is_system_originated_rejects_user_deposit_tx() { + let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + tx.deposit.source_hash = B256::repeat_byte(0x11); + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); + assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + /// A system transaction is a legacy call to a whitelisted contract, and nothing else. + #[test] + fn test_only_a_whitelisted_legacy_call_is_a_system_transaction() { + assert!(is_mega_system_transaction_with( + &legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS), + MEGA_SYSTEM_ADDRESS, + )); + assert!(!is_mega_system_transaction_with( + &legacy_call_tx(MEGA_SYSTEM_ADDRESS, NOT_WHITELISTED), + MEGA_SYSTEM_ADDRESS, + )); + assert!(!is_mega_system_transaction_with( + &legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS), + MEGA_SYSTEM_ADDRESS, + )); + assert!( + !check_if_mega_system_transaction( + MEGA_SYSTEM_ADDRESS, + 0, + TxKind::Create, + MEGA_SYSTEM_ADDRESS, + ), + "the protocol creates no contract this way", + ); + assert!( + !check_if_mega_system_transaction( + MEGA_SYSTEM_ADDRESS, + 2, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + MEGA_SYSTEM_ADDRESS, + ), + "the sequencer builds a legacy transaction", + ); + } + + /// The source hash is the hash of the name it stands for. + #[test] + fn test_the_source_hash_is_the_hash_of_its_name() { + assert_eq!( + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, + alloy_primitives::keccak256("MEGA_SYSTEM_TRANSACTION"), + ); + } +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index 6d4d2ec6e..a8e8e5415 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -6,3 +6,4 @@ mod control; mod keyless; mod limit_control; mod oracle; +mod system_tx; diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs new file mode 100644 index 000000000..f623bc35d --- /dev/null +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -0,0 +1,550 @@ +//! The system-address transaction: what it may do, what it pays, and what still validates it. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{ + is_deposit_like_transaction, is_mega_system_transaction_with, IOracle, ISequencerRegistry, + MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + }, + test_utils::{op_transaction, MemoryDatabase}, + MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, +}; +use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; +use revm::{ + context::{result::ExecutionResult, CfgEnv, TxEnv}, + database::State, + DatabaseCommit, +}; + +use crate::common::{block, context, system_db, CALLER, GAS_LIMIT}; + +/// The chain the tests run on. +const CHAIN_ID: u64 = 4326; + +/// A contract that is not on the whitelist. +const OFF_WHITELIST: Address = address!("0x00000000000000000000000000000000000dead1"); + +/// The Oracle's slot the system transactions write. +const ORACLE_SLOT: U256 = U256::ZERO; + +/// A database with the system contracts in place and the registry naming +/// [`MEGA_SYSTEM_ADDRESS`] the current system address, which is what lets an Oracle write from +/// it through. +fn chain_db() -> MemoryDatabase { + system_db().account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + U256::from_be_slice(MEGA_SYSTEM_ADDRESS.as_slice()), + ) +} + +/// A legacy transaction from `caller`, as the sequencer builds one. +fn legacy_tx(caller: Address, kind: TxKind, data: Bytes, nonce: u64) -> MegaTransaction { + legacy_tx_with_chain_id(caller, kind, data, nonce, Some(CHAIN_ID)) +} + +fn legacy_tx_with_chain_id( + caller: Address, + kind: TxKind, + data: Bytes, + nonce: u64, + chain_id: Option, +) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind, + data, + nonce, + chain_id, + gas_limit: GAS_LIMIT, + gas_price: 1_000, + ..Default::default() + })) +} + +/// A deposit transaction from `caller`, which pays no fee, minting `mint` to its caller. +fn deposit_tx(caller: Address, kind: TxKind, value: U256, mint: u128) -> MegaTransaction { + let mut tx = legacy_tx(caller, kind, Bytes::new(), 0); + tx.0.base.gas_price = 0; + tx.0.base.value = value; + tx.0.deposit.source_hash = B256::repeat_byte(0x22); + tx.0.deposit.mint = Some(mint); + tx +} + +/// The calldata of `setSlots([slot], [value])`. +fn set_slot(slot: U256, value: B256) -> Bytes { + IOracle::setSlotsCall { slots: vec![slot], values: vec![value] }.abi_encode().into() +} + +/// A system transaction writing `value` to the Oracle's slot. +fn system_tx(nonce: u64, value: B256) -> MegaTransaction { + legacy_tx( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, value), + nonce, + ) +} + +/// A Satin context over `db` with the chain id the tests use. +fn chain_context(db: DB) -> MegaContext { + let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + context(db).with_cfg(cfg) +} + +/// Runs `tx` and returns everything the engine reports about it. +fn run_outcome(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + MegaEvm::new(chain_context(db)).execute_transaction(tx).expect("the transaction is valid") +} + +/// Runs `tx` and returns the error it was rejected with, as a string. +fn rejection(db: MemoryDatabase, tx: MegaTransaction) -> String { + let error = MegaEvm::new(chain_context(db)) + .execute_transaction(tx) + .expect_err("the transaction must be rejected"); + format!("{error:?}") +} + +/// The Oracle's slot as the database holds it. +fn oracle_slot(db: &mut DB, slot: U256) -> U256 +where + DB::Error: core::fmt::Debug, +{ + db.storage(ORACLE_CONTRACT_ADDRESS, slot).expect("the read succeeds") +} + +/// The nonce of `address` as the database holds it. +fn nonce_of(db: &mut DB, address: Address) -> u64 +where + DB::Error: core::fmt::Debug, +{ + db.basic(address).expect("the read succeeds").map_or(0, |info| info.nonce) +} + +/// A system transaction executes with the system address as its caller and writes what it came +/// to write. +#[test] +fn test_a_system_transaction_writes_through_the_oracle() { + let value = B256::with_last_byte(0x55); + let outcome = run_outcome(chain_db(), system_tx(0, value)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.state[&ORACLE_CONTRACT_ADDRESS].storage[&ORACLE_SLOT].present_value, + U256::from_be_bytes(value.0), + ); +} + +/// The transaction the engine executed is a deposit: the promotion stamped the source hash on +/// it, which is what op-revm's deposit path keys on. +#[test] +fn test_a_system_transaction_is_promoted_to_a_deposit() { + let mut evm = MegaEvm::new(chain_context(chain_db())); + let tx = system_tx(0, B256::with_last_byte(0x11)); + assert!(is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + + assert!(evm.transact_raw(tx).expect("the transaction is valid").result.is_success()); + assert_eq!( + revm::context::ContextTr::tx(evm.ctx()).deposit.source_hash, + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, + ); +} + +/// A system transaction pays no fee: neither the sequencer's balance nor the block's +/// beneficiary changes, whatever the L1 and operator fees are. +#[test] +fn test_a_system_transaction_pays_no_fee() { + let balance = U256::from(1_000_000); + let db = chain_db().account_balance(MEGA_SYSTEM_ADDRESS, balance); + let mut context = chain_context(db); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(1_000_000)); + chain.operator_fee_constant = Some(U256::from(10_000)); + }); + let mut evm = MegaEvm::new(context); + + let result = evm + .transact_raw(system_tx(0, B256::with_last_byte(0x22))) + .expect("the transaction is valid"); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + result.state[&MEGA_SYSTEM_ADDRESS].info.balance, balance, + "no fee, no L1 fee and no operator fee comes out of the system address", + ); + let beneficiary = block().beneficiary; + assert!( + result.state.get(&beneficiary).is_none_or(|account| account.info.balance.is_zero()), + "the beneficiary is paid nothing", + ); +} + +/// A system transaction needs no balance at all: nothing is deducted from its caller. +#[test] +fn test_a_system_transaction_needs_no_balance() { + let outcome = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x33))); + assert!(outcome.result.is_success(), "{:?}", outcome.result); +} + +/// A system transaction that carries value moves exactly that value, and no fee with it. +#[test] +fn test_a_system_transaction_moves_only_its_value() { + let balance = U256::from(1_000_000); + let transferred = U256::from(50_000); + // The Oracle's methods are not payable, so the value goes to a whitelisted address running + // code that takes it. + let db = chain_db() + .account_balance(MEGA_SYSTEM_ADDRESS, balance) + .account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[revm::bytecode::opcode::STOP])); + + let mut tx = + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), Bytes::new(), 0); + tx.0.base.value = transferred; + let outcome = run_outcome(db, tx); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&MEGA_SYSTEM_ADDRESS].info.balance, balance - transferred); + assert_eq!(outcome.state[&ORACLE_CONTRACT_ADDRESS].info.balance, transferred); +} + +/// A transaction from the system address to a contract that is not on the whitelist is +/// rejected, and so is one that creates a contract. +#[test] +fn test_the_whitelist_is_what_the_system_address_may_call() { + let off_whitelist = + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); + let refused = rejection(chain_db(), off_whitelist); + assert!(refused.contains("whitelist"), "{refused}"); + + let creation = legacy_tx( + MEGA_SYSTEM_ADDRESS, + TxKind::Create, + Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]), + 0, + ); + let refused = rejection(chain_db(), creation); + assert!(refused.contains("whitelist"), "{refused}"); +} + +/// The whitelist holds for the system address alone: anyone else may call anything, and pays +/// for it. +#[test] +fn test_a_user_transaction_is_not_held_to_the_whitelist() { + let db = chain_db() + .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) + .account_code(OFF_WHITELIST, Bytes::from_static(&[revm::bytecode::opcode::STOP])); + let tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); + let outcome = run_outcome(db, tx); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!( + outcome.state[&CALLER].info.balance < U256::from(1_000_000_000_000_u64), + "a user transaction pays its fee", + ); +} + +/// A user's deposit transaction is not a system transaction: it is executed as the deposit it +/// is, and the system-address checks do not touch it. +#[test] +fn test_a_user_deposit_is_not_a_system_transaction() { + let db = chain_db().account_balance(CALLER, U256::from(1_000_000)); + let mut tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + + assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(!is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS)); + let outcome = run_outcome(db, tx); + assert!(outcome.result.is_success(), "{:?}", outcome.result); +} + +/// A deposit transaction whose caller is not the system address goes through untouched, even +/// when it carries the system transaction's own source hash. +#[test] +fn test_a_deposit_from_another_caller_is_untouched() { + let db = chain_db().account_balance(CALLER, U256::from(1_000_000)); + let mut tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); + tx.0.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert!(run_outcome(db, tx).result.is_success()); +} + +/// The nonce of a system transaction is checked against the system address's own, so a +/// transaction cannot be replayed: a stale one is refused and changes nothing. +#[test] +fn test_a_replayed_system_transaction_is_refused() { + let mut state = State::builder().with_database(chain_db()).build(); + let mut evm = MegaEvm::new(chain_context(&mut state)); + + let first = B256::with_last_byte(0x11); + let second = B256::with_last_byte(0x22); + for (nonce, value) in [(0, first), (1, second)] { + let result = evm.transact_commit(system_tx(nonce, value)).expect("the transaction runs"); + assert!(result.is_success(), "nonce {nonce}: {result:?}"); + } + + let replay = rejection_in(&mut evm, system_tx(0, first)); + assert!(replay.contains("NonceTooLow"), "{replay}"); + let ahead = rejection_in(&mut evm, system_tx(5, first)); + assert!(ahead.contains("NonceTooHigh"), "{ahead}"); + + drop(evm); + assert_eq!( + oracle_slot(&mut state, ORACLE_SLOT), + U256::from_be_bytes(second.0), + "the refused replay did not write the old value back", + ); + assert_eq!( + nonce_of(&mut state, MEGA_SYSTEM_ADDRESS), + 2, + "a refused transaction does not bump the nonce", + ); +} + +/// Two system transactions in the same block both go through: the second sees the nonce the +/// first bumped. +#[test] +fn test_two_system_transactions_in_a_block_both_go_through() { + let mut state = State::builder().with_database(chain_db()).build(); + let mut evm = MegaEvm::new(chain_context(&mut state)); + for (nonce, value) in [(0, B256::with_last_byte(0xaa)), (1, B256::with_last_byte(0xbb))] { + assert!(evm.transact_commit(system_tx(nonce, value)).expect("it runs").is_success()); + } + drop(evm); + assert_eq!( + oracle_slot(&mut state, ORACLE_SLOT), + U256::from_be_bytes(B256::with_last_byte(0xbb).0), + ); + assert_eq!(nonce_of(&mut state, MEGA_SYSTEM_ADDRESS), 2); +} + +/// A system transaction carries the chain's id, so it cannot be replayed on another chain; one +/// without an id at all is refused too. +#[test] +fn test_a_system_transaction_is_bound_to_the_chain() { + let foreign = legacy_tx_with_chain_id( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(0xcc)), + 0, + Some(31_337), + ); + let rejected = rejection(chain_db(), foreign); + assert!(rejected.contains("InvalidChainId"), "{rejected}"); + + let no_chain_id = legacy_tx_with_chain_id( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(0xdd)), + 0, + None, + ); + let rejected = rejection(chain_db(), no_chain_id); + assert!(rejected.contains("MissingChainId"), "{rejected}"); +} + +/// The system address may not carry code (EIP-3607), as no sender may. +#[test] +fn test_a_system_address_with_code_is_refused() { + let db = chain_db().account_code(MEGA_SYSTEM_ADDRESS, Bytes::from_static(&[0x00])); + let rejected = rejection(db, system_tx(0, B256::with_last_byte(0xce))); + assert!(rejected.contains("RejectCallerWithCode"), "{rejected}"); +} + +/// The checks a caller switches off for user transactions are switched off here too: one shape +/// of validation, not two. +#[test] +fn test_the_configuration_switches_hold_for_system_transactions() { + let run_with = |mutate: fn(&mut CfgEnv), db: MemoryDatabase, tx| { + let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + mutate(&mut cfg); + MegaEvm::new(context(db).with_cfg(cfg)).execute_transaction(tx) + }; + + // A foreign chain id goes through when the chain-id check is off. + let foreign = legacy_tx_with_chain_id( + MEGA_SYSTEM_ADDRESS, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(0xee)), + 0, + Some(31_337), + ); + let outcome = run_with(|cfg| cfg.tx_chain_id_check = false, chain_db(), foreign) + .expect("the chain-id check is off"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + // A stale nonce goes through when the nonce check is off. + let db = chain_db().account_nonce(MEGA_SYSTEM_ADDRESS, 7); + let outcome = run_with(|cfg| cfg.disable_nonce_check = true, db, system_tx(0, B256::ZERO)) + .expect("the nonce check is off"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + // A system address with code goes through when EIP-3607 is off. + let db = chain_db().account_code(MEGA_SYSTEM_ADDRESS, Bytes::from_static(&[0x00])); + let outcome = + run_with(|cfg| cfg.disable_eip3607 = true, db, system_tx(0, B256::with_last_byte(0xcf))) + .expect("EIP-3607 is off"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); +} + +/// Validating a system transaction does not warm the system address: the transaction pays the +/// cold access its first touch of any account would. +#[test] +fn test_validating_a_system_transaction_does_not_warm_the_system_address() { + // `getSlot` reads one slot and writes nothing, so what the two transactions differ by is + // the access to the caller's own account. + let read = Bytes::from(IOracle::getSlotCall { slot: ORACLE_SLOT }.abi_encode()); + let system = run_outcome( + chain_db(), + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), read.clone(), 0), + ); + let user = run_outcome( + chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), + legacy_tx(CALLER, TxKind::Call(ORACLE_CONTRACT_ADDRESS), read, 0), + ); + assert!(system.result.is_success() && user.result.is_success()); + assert_eq!( + system.gas.regular, user.gas.regular, + "the system transaction pays what any other transaction pays", + ); +} + +/// A system transaction spends nothing on the history ledger: the protocol's own maintenance is +/// exempt from history gas. +#[test] +fn test_a_system_transaction_spends_no_history_gas() { + let outcome = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x66))); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history gas"); +} + +/// A deposit-like transaction whose caller does not exist yet creates that account, and pays +/// the account-creation charge for it exactly once: the same charge a value transfer to a +/// fresh account pays. +#[test] +fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { + // The reference charge: a user transaction that creates one account by sending value to it. + let fresh = address!("0x00000000000000000000000000000000000f0001"); + let reference = + run_outcome(chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), { + let mut tx = legacy_tx(CALLER, TxKind::Call(fresh), Bytes::new(), 0); + tx.0.base.value = U256::from(1); + tx + }); + let one_account = reference.gas.state; + assert!(one_account > 0, "a fresh recipient costs state gas"); + + // A system transaction whose sender does not exist yet creates it, for the same charge. + let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); + assert!(created.result.is_success(), "{:?}", created.result); + let slot_charge = run_outcome( + chain_db() + .account_nonce(MEGA_SYSTEM_ADDRESS, 0) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), + system_tx(0, B256::with_last_byte(0x77)), + ) + .gas + .state; + assert_eq!( + created.gas.state - slot_charge, + one_account, + "the caller's account costs one account creation, and the slot the same either way", + ); +} + +/// A deposit-like transaction whose caller already exists pays no account-creation charge for +/// it. +#[test] +fn test_a_deposit_with_an_existing_caller_pays_nothing_extra() { + let existing = chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)); + let fresh = chain_db(); + let (existing, fresh) = ( + run_outcome(existing, system_tx(0, B256::with_last_byte(0x88))).gas.state, + run_outcome(fresh, system_tx(0, B256::with_last_byte(0x88))).gas.state, + ); + assert!(fresh > existing, "{fresh} is not above {existing}"); +} + +/// A deposit whose recipient is its own caller pays for that one account once: by the time the +/// recipient is looked at, the caller's materialisation has created it. +#[test] +fn test_a_deposit_to_its_own_caller_pays_once() { + let fresh = address!("0x00000000000000000000000000000000000f0002"); + let outcome = + run_outcome(chain_db(), deposit_tx(fresh, TxKind::Call(fresh), U256::from(100), 1_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + let reference = + run_outcome(chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), { + let recipient = address!("0x00000000000000000000000000000000000f0003"); + let mut tx = legacy_tx(CALLER, TxKind::Call(recipient), Bytes::new(), 0); + tx.0.base.value = U256::from(1); + tx + }); + assert_eq!( + outcome.gas.state, reference.gas.state, + "one account was created, so one account-creation charge was paid", + ); +} + +/// A deposit that creates its caller and sends value to another account that does not exist +/// pays for both. +#[test] +fn test_a_deposit_that_creates_two_accounts_pays_for_both() { + let sender = address!("0x00000000000000000000000000000000000f0004"); + let recipient = address!("0x00000000000000000000000000000000000f0005"); + let deposit = || deposit_tx(sender, TxKind::Call(recipient), U256::from(100), 1_000); + let two = run_outcome(chain_db(), deposit()).gas.state; + let one = run_outcome(chain_db().account_balance(sender, U256::from(1)), deposit()).gas.state; + + assert_eq!(two, one * 2, "two accounts created, two charges"); +} + +/// A deposit that cannot pay for the account it creates for its caller is an out-of-gas halt, +/// as a transaction that runs out in its runtime phase is. +#[test] +fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { + let sender = address!("0x00000000000000000000000000000000000f0006"); + let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); + tx.0.base.gas_limit = 30_000; + + let outcome = run_outcome(chain_db(), tx); + assert!( + matches!(outcome.result, ExecutionResult::Halt { .. }), + "{:?} is not a halt", + outcome.result, + ); +} + +/// The registry the Oracle reads the current system address from is seeded as the chain seeds +/// it, so a write from the system address is the one the Oracle accepts. +#[test] +fn test_the_oracle_accepts_the_system_address_the_registry_names() { + let current = ISequencerRegistry::currentSystemAddressCall {}.abi_encode(); + let outcome = run_outcome( + chain_db().account_balance(CALLER, U256::from(1_000_000_000_000_u64)), + legacy_tx(CALLER, TxKind::Call(SEQUENCER_REGISTRY_ADDRESS), current.into(), 0), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + Address::from_word(B256::from_slice(outcome.result.output().unwrap())), + MEGA_SYSTEM_ADDRESS, + ); +} + +/// Runs `tx` on `evm` and returns the error it was rejected with. +fn rejection_in( + evm: &mut MegaEvm, + tx: MegaTransaction, +) -> String +where + DB: alloy_evm::Database + DatabaseCommit, +{ + let error = evm.execute_transaction(tx).expect_err("the transaction must be rejected"); + format!("{error:?}") +} From 73dab1eae1050bc1221391900217445443f9ebb1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:35:35 +0800 Subject: [PATCH 141/201] docs: say how SALT prices a state gas charge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The module table moves SALT pricing from what fills `external/` and `evm/` to what they hold, the engine notes gain the formula, where the capacities come from, the system-origin rule and the failure path, and the execution layer's contracts gain the one this series is built on: a state charge is priced in exactly one place, and every site that gives a charge back re-prices the same pair rather than reading a second table. The schedule's own header says what its state entries now are — the price at the minimum bucket, the number the scaling starts from. Prettier reflowed the module table's column widths. --- AGENTS.md | 36 ++++++++++++------- crates/mega-evm/README.md | 8 ++++- crates/mega-evm/src/evm/schedule.rs | 4 +++ crates/mega-evm/src/external/AGENTS.md | 6 +++- .../mega-evm/tests/satin/salt_delegation.rs | 2 +- 5 files changed, 40 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0a63ee8b6..3b3e258a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,17 +92,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | -| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds now | Filled by | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the SALT pricing hook, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -112,11 +112,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Gas above the 200M execution cap goes to the EIP-8037 reservoir. - The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the seventeen entries EIP-8038 repriced go back to their Osaka values, and the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte. It is built once per process and installed on every configuration; the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. - `crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, and what nine probe transactions spent; a test renders it and compares it to the file. + `crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, what nine probe transactions spent, and what two of those probes spend with the bucket they write into crowded; a test renders it and compares it to the file. - The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the metering wrappers go in; `CLZ` is gated on Osaka and needs no activation. - The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000, carried as an alloy-evm `PrecompilesMap` so a node can add or replace an address (`MegaEvmFactory::with_dyn_precompiles_builder`). -- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did and the block-hash read the Host records. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did, the block-hash read the Host records and the state-gas price the Host scales. With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. +- SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`). + A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. + The capacities come from the transaction's `SaltEnv` through `BucketMultipliers` (`external/gas.rs`), which reads a bucket once per transaction; the cache is cleared with the rest of the per-transaction state. + A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; today that is a transaction whose caller is the EIP-4788 system address and every transaction run through a system-call entry point, and the mega system transaction joins it with the system contract mechanisms. + A failed capacity lookup reports nothing and records its cause the way a failed `sload` does; the transaction fails with that cause rather than settling at a price nobody chose. + At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. @@ -155,6 +161,10 @@ Every later mechanism plugs into these; a change to one comes back to this layer `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route. The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). The test utilities' inspectors are not declared. +- **One hook prices every state charge.** + `Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced, and every site that gives a charge back re-prices the same `(id, site)` pair rather than reading a second table, so a refill cancels the charge it undoes exactly whatever the price was. + Because a bucket's multiplier is read once per transaction, the two cannot disagree even if the environment's answer would. + A mechanism that adds a state charge adds a `StateGasCharge` at the site the state lands on; it must not price the charge itself. - **Three ledgers.** `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index bf2f79917..134fe38c7 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -43,7 +43,13 @@ Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecut Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers. `apply_pre_execution_changes` leaves two hook points empty: system contract deployment and the pre-block system calls. -SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. +SALT pricing is in place: every EIP-8037 state gas charge costs the schedule's entry times the capacity of the SALT bucket it lands in, counted in minimum buckets, so a slot written into a region eight times as crowded as the minimum costs eight times as much. +The multiplier applies to the state dimension only; regular gas never scales. +Capacities come from the transaction's `SaltEnv`, read once per bucket per transaction, and a transaction the protocol itself produced prices at the minimum bucket whatever the bucket holds. +Without a SALT environment every bucket is minimal, so the numbers above are what a transaction pays. +`tests/satin/pricing-table.md` shows two probes at three multipliers. + +History gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. Until history gas lands, nothing prices a history byte and the schedule's history entry stays at zero. ## Quick start diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 877b51960..85edbf934 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -18,6 +18,10 @@ //! against the same state charge. Whether creation keeps its Osaka regular price is an open //! pricing question; the schedule states the prices, it does not settle them. //! +//! The state-gas entries are the price at the *minimum* SALT bucket. A charge is scaled from +//! there by the capacity of the bucket it lands in, which the pricing hook does +//! (`Host::state_gas_price`); the schedule holds the number that scaling starts from. +//! //! Every other entry is Amsterdam's, including the EIP-2780 decomposition entries //! (`tx_account_write_cost`, `tx_create_access_cost`), the zero `code_deposit_cost` and the floor. //! The history entry stays at zero: history gas is its own mechanism and switches it on. diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 29f2abe16..21b2540db 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -8,7 +8,7 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - `factory.rs`: `ExternalEnvFactory` trait for block-scoped environment creation. - `salt.rs`: SALT trait and bucket-id derivation rules. - `oracle.rs`: oracle trait for storage reads and hint side effects. -- SALT pricing (the state-gas price hook that consumes `SaltEnv`) is not here yet. +- `gas.rs`: `BucketMultipliers`, the per-transaction cache of bucket multipliers the state-gas price hook reads `SaltEnv` through. - `hasher/`: hashing utilities used for deterministic bucket-id computation. ## KEY PATTERNS @@ -16,6 +16,9 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - SALT and oracle are independent traits but consumed together via `ExternalEnvs` bundle. - External errors are propagated to host and then stashed in EVM context error channel. - `EmptyExternalEnv` must stay deterministic and side-effect free. +- A bucket's capacity is read once per transaction and answered from `BucketMultipliers` afterwards, so a state gas charge and the refill that undoes it are priced at the same capacity by construction. +- `BucketMultipliers` does not hold the environment; it takes a `&SaltEnv` per call, so there is no second copy of it and no `Clone` bound on the engine's environment types. +- A capacity below `MIN_BUCKET_SIZE` — which a bucket cannot have — prices at `m = 1`, never at `m = 0`: no environment can make state gas free. ## ANTI-PATTERNS - Do not query live chain state directly from opcode handlers. @@ -27,3 +30,4 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. - Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration is not here yet). - Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. +- Change how a bucket capacity becomes a gas multiplier: `gas.rs`. What that multiplier is applied to is the pricing hook in `evm/host.rs`. diff --git a/crates/mega-evm/tests/satin/salt_delegation.rs b/crates/mega-evm/tests/satin/salt_delegation.rs index b427c098c..e3705a63e 100644 --- a/crates/mega-evm/tests/satin/salt_delegation.rs +++ b/crates/mega-evm/tests/satin/salt_delegation.rs @@ -30,7 +30,7 @@ use revm::{ use crate::salt::{ account_bucket, call_contract, crowded_account, db, entry, minimal_envs, run, try_run, - SaltEnvs, CONTRACT, EMPTY, + SaltEnvs, EMPTY, }; /// An account whose code is a delegation designator pointing at itself. From 51a1435100607f4a163f7847c01c83050040346d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:36:18 +0800 Subject: [PATCH 142/201] test(satin): pin the reservoir on every interceptor path An answer built without running a frame carries the caller's reservoir, so the transaction that made the call costs the same with a state-gas pool and without one. The cases are an intercepted answer, an intercepted refusal of a value-bearing call, and the dispatched keylessDeploy call whose overhead comes out of regular gas. --- .../tests/satin/synthetic_frame_gas.rs | 99 ++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 4178bcb79..e70b09ae7 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -2,8 +2,16 @@ //! inherited and settle like revm's own. use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaEvm, + constants::TX_GAS_LIMIT_CAP, + system::{ + keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE}, + IMegaAccessControl, IMegaLimitControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + }, + test_utils::MemoryDatabase, + EvmTxRuntimeLimits, LimitKind, MegaEvm, }; use revm::{ context::{ContextTr, JournalTr}, @@ -219,3 +227,92 @@ fn test_settle_frame_result_matches_revms_frame_return() { assert_eq!(caller_frame.interpreter.gas.tracker(), &expected, "{result_kind:?}"); } } + +/// A gas limit below the execution cap: the transaction has no state-gas reservoir. +const NARROW: u64 = 100_000_000; + +/// A gas limit far above the execution cap: everything above the cap is the reservoir. +const WIDE: u64 = 1_000_000_000; + +/// Runs the same call to `to` at both gas limits and requires the reservoir to come back whole +/// and the two to cost the same: an answer that carried no reservoir would hand the caller an +/// empty pool and bill the sender for all of it. +fn assert_the_reservoir_survives(db: impl Fn() -> MemoryDatabase, to: Address, data: Bytes) { + let at = |gas_limit: u64| { + let tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); + let (result, _) = crate::common::run(db(), tx); + *result.result.gas() + }; + let (narrow, wide) = (at(NARROW), at(WIDE)); + + assert_eq!(narrow.reservoir_remaining(), 0, "there is no pool below the cap"); + assert_eq!( + wide.reservoir_remaining(), + WIDE - TX_GAS_LIMIT_CAP, + "the call spends no state gas, so the whole pool comes back", + ); + assert_eq!( + narrow.tx_gas_used(), + wide.tx_gas_used(), + "the call costs the same with a pool and without one", + ); +} + +/// A database holding what a call to a system contract needs: the contracts' code, and a +/// balance for the sender. +fn system_db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) + .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE) +} + +/// Every answer a system contract interceptor gives carries the reservoir the frame inherited. +#[test] +fn test_an_intercepted_answer_keeps_the_reservoir() { + for (to, selector) in [ + (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR), + (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR), + (LIMIT_CONTROL_ADDRESS, IMegaLimitControl::remainingComputeGasCall::SELECTOR), + ] { + assert_the_reservoir_survives(system_db, to, Bytes::copy_from_slice(&selector)); + } +} + +/// So does the refusal of a call that carries value to a method that takes none. +#[test] +fn test_an_intercepted_refusal_keeps_the_reservoir() { + let selector = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; + let at = |gas_limit: u64| { + let mut tx = crate::common::call_with_data( + CALLER, + ACCESS_CONTROL_ADDRESS, + Bytes::copy_from_slice(&selector), + gas_limit, + ); + tx.0.base.value = U256::from(1); + let (result, _) = crate::common::run(system_db(), tx); + assert!(!result.result.is_success(), "the value is refused"); + *result.result.gas() + }; + let (narrow, wide) = (at(NARROW), at(WIDE)); + assert_eq!(narrow.reservoir_remaining(), 0); + assert_eq!(wide.reservoir_remaining(), WIDE - TX_GAS_LIMIT_CAP); + assert_eq!(narrow.tx_gas_used(), wide.tx_gas_used()); +} + +/// A dispatched `keylessDeploy` call is charged its overhead out of regular gas, so it costs +/// the same whether there is a pool or not, and the pool comes back whole. +#[test] +fn test_the_keyless_overhead_comes_out_of_regular_gas() { + let data = Bytes::from( + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode(), + ); + assert_the_reservoir_survives(system_db, KEYLESS_DEPLOY_ADDRESS, data); +} From 4c6a184e3f68af52a1463c0ab10fcf12f9923a0a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:41:59 +0800 Subject: [PATCH 143/201] test(system): port the parked rows of the system contract interceptors The 61 rows run in the new system test target and in the unit tests of system/tx.rs: the system-address transaction and its replay protection, the deposit caller's account, the selector probes, the KeylessDeploy dispatch and what an intercepted call costs. Eight parked files held nothing else and are gone. Two rows change what they expect, because the Satin dispatch admits a call on its four selector bytes alone: a keylessDeploy payload too short to hold the arguments the ABI names is dispatched and charged, and the deployment is what refuses it. One more changes shape: a database error while the system address is read is the database error, not a custom string. --- crates/mega-evm/tests/_pending/README.md | 36 +- .../tests/_pending/compute_gas/claims.rs | 92 --- .../mega-evm/tests/_pending/mini_rex/main.rs | 1 - .../mini_rex/mega_system_transaction.rs | 739 ------------------ .../tests/_pending/rex3/keyless_deploy.rs | 138 ---- crates/mega-evm/tests/_pending/rex3/main.rs | 1 - .../tests/_pending/rex4/limit_control.rs | 155 ---- .../mega-evm/tests/_pending/rex5/db_error.rs | 56 -- .../rex5/deposit_caller_accounting.rs | 458 ----------- .../rex5/interceptor_selector_probe.rs | 301 ------- .../rex5/keyless_deploy_dispatch_parity.rs | 91 --- crates/mega-evm/tests/_pending/rex5/main.rs | 4 - .../tests/_pending/rex5/system_tx_replay.rs | 640 --------------- .../tests/_pending/src/system/intercept.rs | 114 --- .../mega-evm/tests/_pending/src/system/tx.rs | 79 -- crates/mega-evm/tests/system/dispatch.rs | 248 ++++++ crates/mega-evm/tests/system/keyless.rs | 19 + crates/mega-evm/tests/system/main.rs | 1 + crates/mega-evm/tests/system/system_tx.rs | 68 ++ 19 files changed, 359 insertions(+), 2882 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/intercept.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/tx.rs create mode 100644 crates/mega-evm/tests/system/dispatch.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index b7ac4e67b..cc775e736 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -35,13 +35,12 @@ Do not add a `_pending/main.rs`. | the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | | revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | | the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | -| the system contract interceptors | 61 | 53 | 8 | 52 | 9 | 0 | | system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | | the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **660** | **574** | **86** | **380** | **252** | **28** | +| **Total** | **599** | **521** | **78** | **328** | **243** | **28** | ## Tests ported in place @@ -165,6 +164,25 @@ These 53 rows run in a real test target now, adapted to the Satin API, so the co | `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | | **Total** | | **53** | | +## Tests ported by the system contract interceptors + +These 61 rows run in a real test target now, adapted to the Satin API and to the dispatch the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `compute_gas/claims.rs` | the system contract interceptors (2) | 2 | `tests/system/dispatch.rs` | +| `mini_rex/mega_system_transaction.rs` | the system contract interceptors (15) | 15 | `src/system/tx.rs`, `tests/system/system_tx.rs` | +| `rex3/keyless_deploy.rs` | the system contract interceptors (2) | 2 | `tests/system/keyless.rs` | +| `rex4/limit_control.rs` | the system contract interceptors (5) | 5 | `tests/system/dispatch.rs`, `tests/system/limit_control.rs` | +| `rex5/db_error.rs` | the system contract interceptors (1) | 1 | `tests/system/dispatch.rs` | +| `rex5/deposit_caller_accounting.rs` | the system contract interceptors (7) | 7 | `tests/system/system_tx.rs` | +| `rex5/interceptor_selector_probe.rs` | the system contract interceptors (6) | 6 | `tests/system/dispatch.rs`, `tests/system/oracle.rs` | +| `rex5/keyless_deploy_dispatch_parity.rs` | the system contract interceptors (3) | 3 | `tests/system/keyless.rs` | +| `rex5/system_tx_replay.rs` | the system contract interceptors (12) | 12 | `tests/system/system_tx.rs` | +| `src/system/intercept.rs` | the system contract interceptors (2) | 2 | `tests/system/dispatch.rs`, `tests/system/limit_control.rs` | +| `src/system/tx.rs` | the system contract interceptors (6) | 6 | `src/system/tx.rs` | +| **Total** | | **61** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | @@ -180,14 +198,13 @@ Each cell lists `disposition count (mechanism · decision)`. | `block_executor/block_limits.rs` | 2 | undecided 2 (the state-growth and KV limits · D46) | | `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | | `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | -| `compute_gas/claims.rs` | 10 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 1 (the data-size limit · D33/D48) | +| `compute_gas/claims.rs` | 8 | rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 1 (the data-size limit · D33/D48) | | `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | | `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | | `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | | `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | | `mini_rex/gas.rs` | 22 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | -| `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | | `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | | `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | | `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | @@ -195,7 +212,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex/storage_gas.rs` | 15 | rewrite 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | | `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | | `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | -| `rex3/keyless_deploy.rs` | 2 | rewrite 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | | `rex3/oracle_gas_limit.rs` | 8 | keep 7 (detention · D08); rewrite 1 (revert-class aborts · D48) | | `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | | `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | @@ -207,19 +223,16 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | | `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | | `rex4/keyless_deploy.rs` | 2 | keep 2 (native keyless deployment · native sub-frame inherits env) | -| `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | +| `rex4/limit_control.rs` | 9 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)) | | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | | `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | | `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | -| `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | -| `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | +| `rex5/db_error.rs` | 3 | rewrite 3 (native keyless deployment · native path surfaces DB errors) | | `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | | `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | | `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | -| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | | `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | | `rex5/keyless_fee_free.rs` | 12 | rewrite 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); keep 4 (native keyless deployment · rules unchanged) | | `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | rewrite 3 (native keyless deployment · native sub-frame gas handling) | @@ -230,7 +243,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | | `rex5/sstore_storage_gas_error.rs` | 1 | keep 1 (SALT pricing · pricing-failure path) | | `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | -| `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | | `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | | `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | | `rex6/create_frame_accounting.rs` | 1 | keep 1 (SALT pricing) | @@ -255,9 +267,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | | `src/system/control.rs` | 8 | keep 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | | `src/system/deploy.rs` | 4 | keep 3 (system contract deployment); rewrite 1 (system contract deployment · single version) | -| `src/system/intercept.rs` | 2 | keep 2 (the system contract interceptors) | | `src/system/keyless_deploy.rs` | 2 | keep 2 (system contract deployment) | | `src/system/limit_control.rs` | 5 | keep 5 (system contract deployment) | | `src/system/oracle.rs` | 7 | keep 7 (system contract deployment · v2.0.0 only) | | `src/system/sequencer_registry.rs` | 24 | keep 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | -| `src/system/tx.rs` | 6 | keep 6 (the system contract interceptors · D51) | diff --git a/crates/mega-evm/tests/_pending/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs index cd19ee4b2..79285d884 100644 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -54,98 +54,6 @@ fn intercepted_call(forwarded_gas: u64) -> Bytes { .build() } -/// Spec: [System Contract Interception] — "Where an interceptor performs no metering of its own, a -/// node MUST NOT record compute gas for the interception: the forwarded gas is returned to the -/// caller in full." `MegaLimitControl` is such an interceptor. -/// -/// If the interception consumed or recorded any portion of the forwarded gas, changing how much is -/// forwarded would change the transaction's compute gas. Both operands are three bytes wide, so the -/// two programs are byte-identical in length and differ only in the forwarded amount. -#[test] -fn test_interception_records_no_compute_gas() { - const LOW: u64 = 1_000_000; // 0x0F4240 — PUSH3 - const HIGH: u64 = 9_000_000; // 0x895440 — PUSH3 - assert_eq!( - intercepted_call(LOW).len(), - intercepted_call(HIGH).len(), - "the two programs must differ only in the forwarded-gas operand value" - ); - - // MegaLimitControl is deployed from Rex4 onward. - for spec in [MegaSpecId::REX4, MegaSpecId::REX5, MegaSpecId::REX6] { - let low = transact(spec, base_db(intercepted_call(LOW))); - let high = transact(spec, base_db(intercepted_call(HIGH))); - - assert_eq!( - low.outcome, "success", - "{spec:?}: intercepted call should succeed, got {}", - low.outcome - ); - assert_eq!( - low.compute_gas, high.compute_gas, - "{spec:?}: forwarding {HIGH} instead of {LOW} gas to an interceptor must not change \ - compute gas — interception records none of it ({} vs {})", - low.compute_gas, high.compute_gas - ); - assert_eq!( - low.gas_used, high.gas_used, - "{spec:?}: forwarded gas must be returned to the caller in full ({} vs {})", - low.gas_used, high.gas_used - ); - } -} - -/// Spec: [System Contract Interception] — the *absolute* half of the same rule. -/// -/// [`test_interception_records_no_compute_gas`] only shows the recorded amount is independent of -/// how much gas is forwarded. A fixed per-interception charge would satisfy that and still violate -/// the rule. This test pins the absolute cost by differencing against a structurally identical -/// CALL whose only difference is the callee: a plain account instead of the system contract. -/// -/// Both targets are cold, both take the same operand encoding, both return immediately with no -/// return data. Any compute gas the interception records itself would show up as a difference. -#[test] -fn test_interception_costs_the_same_as_a_plain_call() { - /// Same shape as [`intercepted_call`] but targeting an arbitrary address instead of the - /// system contract, so the CALL is not intercepted. - fn plain_call(to: alloy_primitives::Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(0_u64) - .push_number(0_u64) - .push_number(4_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(to) - .push_number(forwarded_gas) - .append(CALL) - .append(POP) - .stop() - .build() - } - - const FORWARDED_GAS: u64 = 1_000_000; - assert_eq!( - intercepted_call(FORWARDED_GAS).len(), - plain_call(EXISTING_TARGET, FORWARDED_GAS).len(), - "the intercepted and plain programs must be byte-identical apart from the target address" - ); - - for spec in [MegaSpecId::REX4, MegaSpecId::REX5, MegaSpecId::REX6] { - let intercepted = transact(spec, base_db(intercepted_call(FORWARDED_GAS))); - let plain = transact(spec, base_db(plain_call(EXISTING_TARGET, FORWARDED_GAS))); - - assert_eq!(intercepted.outcome, "success", "{spec:?}: intercepted call should succeed"); - assert_eq!(plain.outcome, "success", "{spec:?}: plain call should succeed"); - assert_eq!( - intercepted.compute_gas, plain.compute_gas, - "{spec:?}: an intercepted call must cost exactly what the CALL opcode alone costs — \ - the interception itself records no compute gas (intercepted={} plain={})", - intercepted.compute_gas, plain.compute_gas - ); - } -} - /// Spec: [Refund Exclusion] — "A node MUST NOT subtract EVM gas refunds from compute gas usage. /// Refunds affect final gas settlement but do not reduce the compute gas recorded during /// execution." diff --git a/crates/mega-evm/tests/_pending/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs index f3079b45c..0a4e5ed7c 100644 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -5,7 +5,6 @@ mod block_env_access_tracking; mod block_env_gas_limit; mod compute_gas_limit; mod gas; -mod mega_system_transaction; mod oracle; mod state_growth_limit; mod tx_data_and_kv_update_limit; diff --git a/crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs b/crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs deleted file mode 100644 index 52f313e65..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs +++ /dev/null @@ -1,739 +0,0 @@ -//! Tests for mega system transaction functionality. -//! -//! This test suite verifies that transactions from the `MEGA_SYSTEM_ADDRESS` are processed -//! as deposit-like transactions, bypassing signature validation, nonce verification, -//! and fee deduction while maintaining normal execution behavior. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - is_deposit_like_transaction, is_mega_system_transaction_with, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EmptyExternalEnv, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, -}; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; -use revm::{ - bytecode::opcode::{CALLER, MSTORE, RETURN}, - context::{result::ResultAndState, BlockEnv, ContextSetters, ContextTr, Transaction, TxEnv}, - handler::EvmTr, - inspector::NoOpInspector, - primitives::TxKind, - Database, -}; - -const REGULAR_CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT_ADDR: Address = address!("0000000000000000000000000000000000100001"); -const BENEFICIARY: Address = address!("0000000000000000000000000000000000BEEF01"); -const NON_WHITELISTED_ADDR: Address = address!("0000000000000000000000000000000000DEAD01"); - -// Whitelisted address from MEGA_SYSTEM_TX_WHITELIST -const WHITELISTED_ADDR: Address = ORACLE_CONTRACT_ADDRESS; - -/// Creates a test EVM instance with the provided database. -fn create_evm(db: MemoryDatabase) -> MegaEvm { - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - - let block_env = BlockEnv { - beneficiary: BENEFICIARY, - number: U256::from(10), - basefee: 1000, - ..Default::default() - }; - context.set_block(block_env); - - // Set operator fees to zero for cleaner testing (except for the fee deduction test) - // Note: Some tests need fees enabled to test fee deduction behavior - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - - MegaEvm::new(context) -} - -/// Creates a simple contract that returns the caller address. -fn create_simple_contract() -> Bytes { - // CALLER PUSH1 0 MSTORE PUSH1 32 PUSH1 0 RETURN - BytecodeBuilder::default() - .append(CALLER) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0x00u8) - .append(RETURN) - .build() -} - -/// Executes a transaction and returns the result. -fn execute_transaction( - evm: &mut MegaEvm, - caller: Address, - to: Address, - value: U256, - data: Bytes, -) -> ResultAndState { - let tx = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(to), - value, - data, - gas_limit: 1_000_000, - gas_price: 1000, - ..Default::default() - }, - ..Default::default() - }; - - alloy_evm::Evm::transact_raw(evm, tx).expect("Transaction should execute") -} - -/// Tests the utility functions for detecting mega system address transactions and deposit-like -/// transactions. -/// -/// This test verifies that: -/// - `is_mega_system_address_transaction` correctly identifies transactions from -/// `MEGA_SYSTEM_ADDRESS` -/// - `is_deposit_like_transaction` correctly identifies both actual deposit transactions and mega -/// system transactions -#[test] -fn test_utility_functions() { - // Test is_mega_system_address_transaction - let mega_system_tx = MegaTransaction { - base: TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(WHITELISTED_ADDR), - ..Default::default() - }, - ..Default::default() - }; - - let regular_tx = MegaTransaction { - base: TxEnv { - caller: REGULAR_CALLER, - kind: TxKind::Call(CONTRACT_ADDR), - ..Default::default() - }, - ..Default::default() - }; - - assert!(is_mega_system_transaction_with(&mega_system_tx, MEGA_SYSTEM_ADDRESS)); - assert!(!is_mega_system_transaction_with(®ular_tx, MEGA_SYSTEM_ADDRESS)); - - // Test is_deposit_like_transaction - assert!(is_deposit_like_transaction(&mega_system_tx, MEGA_SYSTEM_ADDRESS)); - assert!(!is_deposit_like_transaction(®ular_tx, MEGA_SYSTEM_ADDRESS)); -} - -/// Tests that mega system transactions execute successfully and behave as deposit-like -/// transactions. -/// -/// This test verifies that: -/// - Transactions from `MEGA_SYSTEM_ADDRESS` to whitelisted addresses execute successfully -/// - The contract receives `MEGA_SYSTEM_ADDRESS` as the caller (no address manipulation) -/// - The transaction follows deposit-like execution path -#[test] -fn test_mega_system_transaction_execution() { - // Create database and set up contract - let mut db = MemoryDatabase::default(); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Execute transaction from mega system address - let result = execute_transaction( - &mut evm, - MEGA_SYSTEM_ADDRESS, - WHITELISTED_ADDR, - U256::ZERO, - Bytes::new(), - ); - - // Transaction should succeed - assert!(result.result.is_success(), "Mega system transaction should succeed"); - - // The contract should return the caller address (MEGA_SYSTEM_ADDRESS) - if let Some(output) = result.result.output() { - // The output should contain the MEGA_SYSTEM_ADDRESS padded to 32 bytes - let expected_caller = MEGA_SYSTEM_ADDRESS; - let mut expected_output = [0u8; 32]; - expected_output[12..].copy_from_slice(expected_caller.as_slice()); - - assert_eq!( - output.as_ref(), - &expected_output, - "Contract should receive MEGA_SYSTEM_ADDRESS as caller" - ); - } else { - panic!("Expected output from contract"); - } -} - -/// Tests that regular transactions continue to work normally and are not affected by mega system -/// transaction handling. -/// -/// This test verifies that: -/// - Regular transactions to whitelisted addresses execute successfully -/// - Regular transactions follow normal execution path (not deposit-like) -/// - The contract receives the actual caller address -/// - Regular transactions are not processed as system transactions -#[test] -fn test_regular_transaction_still_works() { - // Create database and set up accounts and contract - let mut db = MemoryDatabase::default(); - db.set_account_balance(REGULAR_CALLER, U256::from(1_000_000_000u64)); // Give it some balance - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Execute transaction from regular address - let result = - execute_transaction(&mut evm, REGULAR_CALLER, WHITELISTED_ADDR, U256::ZERO, Bytes::new()); - - // Transaction should succeed - assert!(result.result.is_success(), "Regular transaction should succeed"); - - // The contract should return the caller address (REGULAR_CALLER) - if let Some(output) = result.result.output() { - let expected_caller = REGULAR_CALLER; - let mut expected_output = [0u8; 32]; - expected_output[12..].copy_from_slice(expected_caller.as_slice()); - - assert_eq!( - output.as_ref(), - &expected_output, - "Contract should receive REGULAR_CALLER as caller" - ); - } else { - panic!("Expected output from contract"); - } -} - -/// Tests that mega system transactions bypass balance checks and execute without sufficient -/// balance. -/// -/// This test verifies that: -/// - `MEGA_SYSTEM_ADDRESS` transactions execute successfully even without any balance -/// - The transaction bypasses normal balance validation for gas fees -/// - This demonstrates deposit-like behavior where balance checks are skipped -/// - The contract execution proceeds normally despite insufficient balance -#[test] -fn test_mega_system_transaction_bypasses_balance_check() { - // Create database and set up contract - // Note: We don't set any balance for MEGA_SYSTEM_ADDRESS - let mut db = MemoryDatabase::default(); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Regular transactions would fail without sufficient balance for gas, - // but mega system transactions should succeed - - // Execute transaction from mega system address (no value transfer, just gas bypass test) - let result = execute_transaction( - &mut evm, - MEGA_SYSTEM_ADDRESS, - WHITELISTED_ADDR, - U256::ZERO, // No value transfer to avoid deposit validation complexities - Bytes::new(), - ); - - // Transaction should succeed even without balance (deposit-like behavior) - assert!( - result.result.is_success(), - "Mega system transaction should succeed even without balance: {:?}", - result.result - ); -} - -/// Tests that mega system transactions correctly set the deposit source hash. -/// -/// This test verifies that: -/// - Mega system transactions automatically set the `MEGA_SYSTEM_TRANSACTION_SOURCE_HASH` -/// - The source hash is properly configured in the transaction's deposit info -/// - This enables the transaction to be processed as a deposit-like transaction -/// - The source hash matches the expected constant value -#[test] -fn test_mega_system_transaction_sets_source_hash() { - let db = MemoryDatabase::default(); - let mut evm = create_evm(db); - - // Create a mega system transaction - let tx = MegaTransaction { - base: TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(WHITELISTED_ADDR), - gas_limit: 1_000_000, - gas_price: 1000, - ..Default::default() - }, - ..Default::default() - }; - - // The transaction should be detected as from mega system address - assert!(is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS)); - - // Set the transaction in the context - evm.ctx().set_tx(tx); - - // Execute the transaction which will trigger pre_execution and set the source hash - let tx_clone = evm.ctx().tx().clone(); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx_clone); - assert!(result.is_ok(), "Transaction should execute successfully"); - - // Check that the source hash was set - assert_eq!( - evm.ctx().tx().deposit.source_hash, - MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, - "Source hash should be set for mega system transactions" - ); -} - -/// Tests that existing deposit transaction behavior is preserved and not affected by mega system -/// transaction logic. -/// -/// This test verifies that: -/// - Actual deposit transactions (with `DEPOSIT_TRANSACTION_TYPE`) still work correctly -/// - Deposit transactions are detected as deposit-like but not as mega system transactions -/// - The mega system transaction detection doesn't interfere with existing deposit logic -/// - Both transaction types can coexist without conflicts -#[test] -fn test_deposit_transaction_behavior_preserved() { - // Create a transaction that looks like a deposit transaction - let mut deposit_tx = MegaTransaction { - base: TxEnv { - caller: REGULAR_CALLER, - kind: TxKind::Call(WHITELISTED_ADDR), - ..Default::default() - }, - ..Default::default() - }; - - // Manually set it as a deposit transaction type - deposit_tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; // Any non-zero hash makes it a deposit - - // Should be detected as deposit-like - assert!(deposit_tx.tx_type() == DEPOSIT_TRANSACTION_TYPE); - assert!(is_deposit_like_transaction(&deposit_tx, MEGA_SYSTEM_ADDRESS)); - - // But should NOT be detected as mega system address transaction - assert!(!is_mega_system_transaction_with(&deposit_tx, MEGA_SYSTEM_ADDRESS)); -} - -/// Tests that mega system transactions do not deduct gas fees from the system address balance. -/// -/// This test verifies that: -/// - `MEGA_SYSTEM_ADDRESS` balance remains unchanged after transaction execution -/// - Gas fees are not deducted from the system address (deposit-like behavior) -/// - The transaction executes successfully despite gas costs -/// - This demonstrates the fee bypass mechanism for system transactions -#[test] -fn test_mega_system_transaction_no_fee_deduction() { - // Create database and set up contract with an initial balance for the mega system address - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(1_000_000u64); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, initial_balance); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Get the initial balance before transaction - let balance_before = evm.ctx().db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().balance; - assert_eq!(balance_before, initial_balance, "Initial balance should be set correctly"); - - // Execute transaction from mega system address with high gas price - let result = execute_transaction( - &mut evm, - MEGA_SYSTEM_ADDRESS, - WHITELISTED_ADDR, - U256::ZERO, - Bytes::new(), - ); - - // Transaction should succeed - assert!(result.result.is_success(), "Mega system transaction should succeed"); - - // Check balance after transaction - should be unchanged (no fee deducted) - let balance_after = evm.ctx().db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().balance; - assert_eq!( - balance_after, initial_balance, - "Balance should remain unchanged - no gas fee should be deducted from mega system address" - ); -} - -/// Tests that regular transactions correctly deduct gas fees from the caller's balance. -/// -/// This test verifies that: -/// - Regular transactions deduct gas fees from the caller's balance -/// - The balance reduction reflects the actual gas cost of the transaction -/// - This confirms normal transaction processing is unaffected -/// - Provides a contrast to mega system transactions which bypass fee deduction -#[test] -fn test_regular_transaction_fee_deduction() { - // Create database and set up contract with an initial balance for the regular caller - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(1_000_000_000_000u64); - db.set_account_balance(REGULAR_CALLER, initial_balance); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Get the initial balance before transaction - let balance_before = evm.ctx().db_mut().basic(REGULAR_CALLER).unwrap().unwrap().balance; - assert_eq!(balance_before, initial_balance, "Initial balance should be set correctly"); - - // Execute transaction from regular caller - let result = - execute_transaction(&mut evm, REGULAR_CALLER, WHITELISTED_ADDR, U256::ZERO, Bytes::new()); - - // Transaction should succeed - assert!(result.result.is_success(), "Regular transaction should succeed"); - - // Check balance after transaction - should be reduced by gas fees - // Get the updated balance from the transaction result state - let balance_after = result.state.get(®ULAR_CALLER).unwrap().info.balance; - assert!( - balance_after < initial_balance, - "Balance should be reduced by gas fees for regular transactions. Before: {}, After: {}", - initial_balance, - balance_after - ); - - // Calculate the fee deducted - let fee_deducted = initial_balance - balance_after; - assert!( - fee_deducted > U256::ZERO, - "Gas fee should be deducted from regular caller. Fee deducted: {}", - fee_deducted - ); -} - -/// Tests that mega system transactions do not pay operator fees even when fees are enabled. -/// -/// This test verifies that: -/// - `MEGA_SYSTEM_ADDRESS` balance remains unchanged even with operator fees enabled -/// - Operator fees are not deducted from the system address (deposit-like behavior) -/// - L1 data fees are not charged to system transactions -/// - This demonstrates complete fee bypass including L1 and operator fees -#[test] -fn test_mega_system_transaction_no_operator_fees() { - // Create database and set up contract with an initial balance for the mega system address - let mut db = MemoryDatabase::default(); - let initial_balance = U256::from(1_000_000u64); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, initial_balance); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - // Create EVM with operator fees enabled - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - - let block_env = BlockEnv { - beneficiary: BENEFICIARY, - number: U256::from(10), - basefee: 1000, - ..Default::default() - }; - context.set_block(block_env); - - // Enable operator fees (instead of setting to zero) - context.chain_mut().operator_fee_scalar = Some(U256::from(1_000_000)); - context.chain_mut().operator_fee_constant = Some(U256::from(10_000)); - - let mut evm = MegaEvm::new(context); - - // Get the initial balance before transaction - let balance_before = evm.ctx().db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().balance; - assert_eq!(balance_before, initial_balance, "Initial balance should be set correctly"); - - // Execute transaction from mega system address with some calldata (to trigger L1 data fee) - let call_data = Bytes::from_static(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); - let result = - execute_transaction(&mut evm, MEGA_SYSTEM_ADDRESS, WHITELISTED_ADDR, U256::ZERO, call_data); - - // Transaction should succeed - assert!(result.result.is_success(), "Mega system transaction should succeed"); - - // Check balance after transaction - should be unchanged (no operator or L1 data fee deducted) - let balance_after = evm.ctx().db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().balance; - assert_eq!( - balance_after, initial_balance, - "Balance should remain unchanged - no operator fee or L1 data fee should be deducted from mega system address" - ); -} - -/// Tests that mega system transactions with value transfer only deduct the transferred value. -/// -/// This test verifies that: -/// - When a mega system transaction transfers value, balance changes by exactly that amount -/// - No gas fees, operator fees, or L1 data fees are added to the value transfer -/// - The recipient receives the exact transferred amount -/// - This demonstrates that fee bypass applies even when value is transferred -#[test] -fn test_mega_system_transaction_value_transfer_no_fees() { - // Create database and set up accounts - let mut db = MemoryDatabase::default(); - let initial_sender_balance = U256::from(1_000_000_000_000u64); - let transfer_value = U256::from(50_000u64); - - // Allocate balance to sender BEFORE creating EVM - db.set_account_balance(MEGA_SYSTEM_ADDRESS, initial_sender_balance); - // Set initial balance for recipient to ensure account exists - db.set_account_balance(WHITELISTED_ADDR, U256::ZERO); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - // Create EVM with operator fees enabled to ensure they're bypassed - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - - let block_env = BlockEnv { - beneficiary: BENEFICIARY, - number: U256::from(10), - basefee: 1000, - ..Default::default() - }; - context.set_block(block_env); - - // Enable operator fees - context.chain_mut().operator_fee_scalar = Some(U256::from(1_000_000)); - context.chain_mut().operator_fee_constant = Some(U256::from(10_000)); - - let mut evm = MegaEvm::new(context); - - // Verify initial balances are set correctly - let sender_balance_before = - evm.ctx().db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().balance; - let recipient_balance_before = - evm.ctx().db_mut().basic(WHITELISTED_ADDR).unwrap().unwrap().balance; - - assert_eq!( - sender_balance_before, initial_sender_balance, - "Initial sender balance should be set correctly" - ); - assert_eq!(recipient_balance_before, U256::ZERO, "Initial recipient balance should be zero"); - - // Execute transaction with value transfer - let result = execute_transaction( - &mut evm, - MEGA_SYSTEM_ADDRESS, - WHITELISTED_ADDR, - transfer_value, - Bytes::new(), - ); - - // Transaction should succeed - assert!( - result.result.is_success(), - "Mega system transaction with value should succeed: {:?}", - result.result - ); - - // Check sender balance - should be reduced by exactly the transfer value (no fees) - let sender_balance_after = result.state.get(&MEGA_SYSTEM_ADDRESS).unwrap().info.balance; - assert_eq!( - sender_balance_after, - initial_sender_balance - transfer_value, - "Sender balance should be reduced by exactly the transfer value with no additional fees. Expected: {}, Got: {}", - initial_sender_balance - transfer_value, - sender_balance_after - ); - - // Check recipient balance - should be increased by exactly the transfer value - let recipient_balance_after = result.state.get(&WHITELISTED_ADDR).unwrap().info.balance; - assert_eq!( - recipient_balance_after, - recipient_balance_before + transfer_value, - "Recipient balance should be increased by exactly the transfer value. Expected: {}, Got: {}", - recipient_balance_before + transfer_value, - recipient_balance_after - ); -} - -/// Tests that mega system transactions to whitelisted addresses execute successfully. -/// -/// This test verifies that: -/// - Transactions from `MEGA_SYSTEM_ADDRESS` to whitelisted addresses are allowed -/// - The transaction executes successfully and returns expected results -/// - The contract receives `MEGA_SYSTEM_ADDRESS` as the caller -/// - Whitelist enforcement allows legitimate system transactions -#[test] -fn test_mega_system_transaction_to_whitelisted_address_succeeds() { - // Create database and set up the whitelisted contract - let mut db = MemoryDatabase::default(); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Execute transaction from mega system address to whitelisted address - let result = execute_transaction( - &mut evm, - MEGA_SYSTEM_ADDRESS, - WHITELISTED_ADDR, - U256::ZERO, - Bytes::new(), - ); - - // Transaction should succeed since the address is whitelisted - assert!( - result.result.is_success(), - "Mega system transaction to whitelisted address should succeed" - ); - - // The contract should return the caller address (MEGA_SYSTEM_ADDRESS) - if let Some(output) = result.result.output() { - let expected_caller = MEGA_SYSTEM_ADDRESS; - let mut expected_output = [0u8; 32]; - expected_output[12..].copy_from_slice(expected_caller.as_slice()); - - assert_eq!( - output.as_ref(), - &expected_output, - "Whitelisted contract should receive MEGA_SYSTEM_ADDRESS as caller" - ); - } else { - panic!("Expected output from whitelisted contract"); - } -} - -/// Tests that mega system transactions to non-whitelisted addresses are rejected. -/// -/// This test verifies that: -/// - Transactions from `MEGA_SYSTEM_ADDRESS` to non-whitelisted addresses fail -/// - The error message indicates whitelist violation -/// - Whitelist enforcement prevents unauthorized system transactions -/// - Security mechanism correctly blocks non-approved destinations -#[test] -fn test_mega_system_transaction_to_non_whitelisted_address_fails() { - // Create database and set up the non-whitelisted contract - let mut db = MemoryDatabase::default(); - db.set_account_code(NON_WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Attempt to execute transaction from mega system address to non-whitelisted address - let tx = MegaTransaction { - base: TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(NON_WHITELISTED_ADDR), - value: U256::ZERO, - data: Bytes::new(), - gas_limit: 1_000_000, - gas_price: 1000, - ..Default::default() - }, - ..Default::default() - }; - - // Transaction should fail due to whitelist check - let result = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(result.is_err(), "Mega system transaction to non-whitelisted address should fail"); - - // Check that the error message contains whitelist-related text - let error_msg = format!("{:?}", result.unwrap_err()); - assert!( - error_msg.contains("whitelist") || error_msg.contains("Whitelist"), - "Error should mention whitelist: {}", - error_msg - ); -} - -/// Tests that mega system transactions with CREATE operations are rejected. -/// -/// This test verifies that: -/// - CREATE transactions from `MEGA_SYSTEM_ADDRESS` are not supported -/// - The error message indicates CREATE is not allowed for system transactions -/// - Security measure prevents system transactions from deploying arbitrary contracts -/// - Only CALL operations are supported for system transactions -#[test] -fn test_mega_system_transaction_create_fails() { - // Create database - let db = MemoryDatabase::default(); - let mut evm = create_evm(db); - - // Attempt to execute CREATE transaction from mega system address - let tx = MegaTransaction { - base: TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Create, - value: U256::ZERO, - data: Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]), // Simple contract bytecode - gas_limit: 10_000_000, - gas_price: 1000, - ..Default::default() - }, - ..Default::default() - }; - - // Transaction should fail since CREATE is not supported for system transactions - let result = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(result.is_err(), "Mega system CREATE transaction should fail"); -} - -/// Tests that regular transactions to non-whitelisted addresses work normally. -/// -/// This test verifies that: -/// - Regular transactions (non-system) can call any address regardless of whitelist -/// - Whitelist restrictions only apply to mega system transactions -/// - Normal transaction processing is unaffected by whitelist implementation -/// - Backward compatibility is maintained for existing transactions -#[test] -fn test_regular_transaction_to_non_whitelisted_address_succeeds() { - // Create database and set up accounts and contract - let mut db = MemoryDatabase::default(); - db.set_account_balance(REGULAR_CALLER, U256::from(1_000_000_000u64)); - db.set_account_code(NON_WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Execute transaction from regular address to non-whitelisted address - let result = execute_transaction( - &mut evm, - REGULAR_CALLER, - NON_WHITELISTED_ADDR, - U256::ZERO, - Bytes::new(), - ); - - // Transaction should succeed since whitelist only applies to system transactions - assert!( - result.result.is_success(), - "Regular transaction to non-whitelisted address should succeed" - ); - - // The contract should return the caller address (REGULAR_CALLER) - if let Some(output) = result.result.output() { - let expected_caller = REGULAR_CALLER; - let mut expected_output = [0u8; 32]; - expected_output[12..].copy_from_slice(expected_caller.as_slice()); - - assert_eq!( - output.as_ref(), - &expected_output, - "Contract should receive REGULAR_CALLER as caller" - ); - } else { - panic!("Expected output from contract"); - } -} - -/// Tests that mega system transactions to whitelisted addresses work with call data. -/// -/// This test verifies that: -/// - System transactions can include arbitrary call data -/// - Whitelisted addresses can receive complex function calls from system transactions -/// - Call data does not affect whitelist validation -/// - Full contract interaction is supported for whitelisted addresses -#[test] -fn test_mega_system_transaction_whitelist_with_data() { - // Create database and set up the whitelisted contract - let mut db = MemoryDatabase::default(); - db.set_account_code(WHITELISTED_ADDR, create_simple_contract()); - - let mut evm = create_evm(db); - - // Execute transaction from mega system address to whitelisted address with data - let call_data = Bytes::from_static(&[0x01, 0x02, 0x03, 0x04]); - let result = - execute_transaction(&mut evm, MEGA_SYSTEM_ADDRESS, WHITELISTED_ADDR, U256::ZERO, call_data); - - // Transaction should succeed even with call data - assert!( - result.result.is_success(), - "Mega system transaction with data to whitelisted address should succeed" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs deleted file mode 100644 index 7c75ed261..000000000 --- a/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! Tests for keyless deploy compute gas tracking in Rex3. -//! -//! Rex3 adds compute gas recording for the keyless deploy overhead (100K gas). -//! Before Rex3, keyless deploy bypassed compute gas tracking entirely. - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - constants, - revm::context::result::ExecutionResult, - sandbox::tests::{CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX}, - test_utils::MemoryDatabase, - EvmTxRuntimeLimits, IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, -}; -use revm::{context::TxEnv, handler::EvmTr, inspector::NoOpInspector}; - -/// Standard test caller address. -const TEST_CALLER: Address = address!("0000000000000000000000000000000000100000"); - -/// Large gas limit override for tests (10 billion gas). -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -/// Helper function to execute a keyless deploy transaction and return the result -/// along with the compute gas used. -fn execute_keyless_deploy( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx_bytes: Bytes, - gas_limit_override: u64, -) -> (ExecutionResult, u64) { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: TEST_CALLER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - let compute_gas_used = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - - (result, compute_gas_used) -} - -/// Test that keyless deploy overhead gas counts toward compute gas in Rex3. -#[test] -fn test_rex3_keyless_deploy_records_compute_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let (result, compute_gas_used) = execute_keyless_deploy( - MegaSpecId::REX3, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - - // Compute gas should include the keyless deploy overhead (100K) - assert!( - compute_gas_used >= constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - "Rex3 compute gas ({}) should include keyless deploy overhead ({})", - compute_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - -/// Test that keyless deploy halts when compute gas limit is set below the 100K overhead. -/// In Rex3, the 100K overhead is recorded as compute gas, so if the compute gas limit -/// is lower than 100K, the transaction should fail. -#[test] -fn test_rex3_keyless_deploy_exceeds_compute_gas_limit() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), - gasLimitOverride: U256::from(LARGE_GAS_LIMIT_OVERRIDE), - } - .abi_encode(); - - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX3).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: TEST_CALLER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - // Set compute gas limit to 50K, which is below the 100K keyless deploy overhead - let runtime_limits = - EvmTxRuntimeLimits::from_spec(MegaSpecId::REX3).with_tx_compute_gas_limit(50_000); - let mut evm = - MegaEvm::new(context).with_tx_runtime_limits(runtime_limits).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - - // The transaction should fail because 100K overhead exceeds the 50K compute gas limit - assert!( - !result.is_success(), - "Keyless deploy should fail when compute gas limit ({}) is below overhead ({})", - 50_000, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} diff --git a/crates/mega-evm/tests/_pending/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs index 175592c89..e197703b0 100644 --- a/crates/mega-evm/tests/_pending/rex3/main.rs +++ b/crates/mega-evm/tests/_pending/rex3/main.rs @@ -1,5 +1,4 @@ //! Tests for Rex3 hardfork features. -mod keyless_deploy; mod oracle_gas_limit; mod system_address; diff --git a/crates/mega-evm/tests/_pending/rex4/limit_control.rs b/crates/mega-evm/tests/_pending/rex4/limit_control.rs index fa5d1cb1c..4acfb1133 100644 --- a/crates/mega-evm/tests/_pending/rex4/limit_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/limit_control.rs @@ -223,64 +223,6 @@ fn test_direct_tx_remaining_compute_gas() { assert!(remaining > 0, "remaining compute gas should be positive"); } -/// Unknown selector should not be intercepted and should fall through to contract fallback revert. -#[test] -fn test_direct_tx_unknown_selector_falls_through_and_reverts_not_intercepted() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let result = transact( - MegaSpecId::REX4, - &mut db, - direct_tx_with_data(LIMIT_CONTROL_ADDRESS, &[0xde, 0xad, 0xbe, 0xef]), - ) - .unwrap(); - assert!( - !result.result.is_success(), - "unknown selector should fall through and revert, got: {:?}", - result.result - ); - - let output = result.result.output().expect("revert should include output"); - assert_eq!( - output.len(), - 4, - "fallback should return only NotIntercepted selector, got {} bytes", - output.len() - ); - assert_eq!( - &output[..4], - &NOT_INTERCEPTED_SELECTOR, - "unknown selector should revert with NotIntercepted()" - ); -} - -/// Direct transaction query with non-zero value should revert. -#[test] -fn test_direct_tx_remaining_compute_gas_with_value_reverts() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = transact( - MegaSpecId::REX4, - &mut db, - direct_query_tx_with_value(LIMIT_CONTROL_ADDRESS, U256::from(1_u64)), - ) - .unwrap(); - assert!( - !result.result.is_success(), - "Direct TX query with non-zero value should revert, got: {:?}", - result.result - ); - let output = result.result.output().expect("revert should include output"); - assert_eq!(output.len(), 4, "non-zero transfer revert should return selector only"); - assert_eq!( - &output[..4], - &NON_ZERO_TRANSFER_SELECTOR, - "non-zero transfer should revert with NonZeroTransfer()" - ); -} - /// STATICCALL query should also return a positive remaining value. #[test] fn test_remaining_compute_gas_staticcall() { @@ -628,107 +570,10 @@ impl Inspector for CallTracki } } -/// System contract interception should still be visible to inspectors. -#[test] -fn test_inspector_sees_remaining_compute_gas_system_call() { - let contract_code = call_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, contract_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut inspector = CallTrackingInspector::default(); - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(default_tx(CONTRACT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(result.result.is_success(), "transaction should succeed"); - - assert_eq!(inspector.calls.len(), 2, "inspector should see two call hooks"); - assert_eq!(inspector.calls[0], CONTRACT, "first call should be top-level contract"); - assert_eq!( - inspector.calls[1], LIMIT_CONTROL_ADDRESS, - "second call should target remaining compute gas system contract" - ); - - assert_eq!(inspector.call_ends.len(), 2, "inspector should see two call_end hooks"); - assert_eq!( - inspector.call_ends[0], LIMIT_CONTROL_ADDRESS, - "first call_end should be remaining compute gas system contract" - ); - assert_eq!(inspector.call_ends[1], CONTRACT, "second call_end should be top-level contract"); -} - // ============================================================================ // 5. CALL VARIANTS // ============================================================================ -/// DELEGATECALL to the contract should NOT be intercepted. -/// The scheme guard in `frame_init` rejects `DELEGATECALL` and `CALLCODE` before any -/// interceptor sees the call; the unit-level coverage lives in `src/system/intercept.rs`. -#[test] -fn test_delegatecall_not_intercepted() { - // Parent: DELEGATECALL to LIMIT_CONTROL_ADDRESS with selector, - // then return success flag as 32-byte word. - let parent_code = BytecodeBuilder::default().mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR); - let parent_code = append_delegatecall(parent_code, LIMIT_CONTROL_ADDRESS, 100_000_u64) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, parent_code) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - assert!(result.result.is_success(), "parent tx should succeed"); - - let output = result.result.output().expect("should have output"); - let success_flag = U256::from_be_slice(output); - assert_eq!( - success_flag, - U256::from(0), - "DELEGATECALL should fail because it is not intercepted" - ); -} - -/// CALLCODE to the contract should NOT be intercepted. -/// Same scheme-guard policy as `DELEGATECALL` above. -#[test] -fn test_callcode_not_intercepted() { - // Parent: CALLCODE to LIMIT_CONTROL_ADDRESS with selector, - // then return success flag as 32-byte word. - let parent_code = BytecodeBuilder::default().mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR); - let parent_code = append_callcode(parent_code, LIMIT_CONTROL_ADDRESS, 100_000_u64) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, parent_code) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - assert!(result.result.is_success(), "parent tx should succeed"); - - let output = result.result.output().expect("should have output"); - let success_flag = U256::from_be_slice(output); - assert_eq!(success_flag, U256::from(0), "CALLCODE should fail because it is not intercepted"); -} - // ============================================================================ // 6. BACKWARD COMPATIBILITY // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex5/db_error.rs b/crates/mega-evm/tests/_pending/rex5/db_error.rs index aea0d693e..ec195d2a4 100644 --- a/crates/mega-evm/tests/_pending/rex5/db_error.rs +++ b/crates/mega-evm/tests/_pending/rex5/db_error.rs @@ -234,59 +234,3 @@ fn test_keyless_signer_nonce_db_error_maps_to_internal_error_revert() { "DB error before sandbox must not bump signer nonce (no replay barrier)", ); } - -/// REX5+ system-tx validate must surface a DB failure as `EVMError::Custom`. The -/// `inspect_account` call on `MEGA_SYSTEM_ADDRESS` happens *before* the deposit -/// promotion, so a DB blip there must NOT silently let the tx through as a deposit. -#[test] -fn test_system_tx_validate_inspect_account_db_error_surfaces_as_custom() { - let mut inner = MemoryDatabase::default(); - // Give system address a balance so the test doesn't trip on InsufficientBalance - // before reaching the inspect_account check. - inner.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(10u128.pow(18))); - - let mut db = ErrorInjectingDatabase::new(inner); - // Fail when `validate_tx_against_state` calls `inspect_account(MEGA_SYSTEM_ADDRESS)`. - db.fail_on_account = Some(MEGA_SYSTEM_ADDRESS); - - let mut context = MegaContext::new(db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - // `CfgEnv::default().chain_id` is 1; `MegaContext::new` does not override it. - let chain_id = revm::context::ContextTr::cfg(&context).chain_id; - - // Whitelisted callee — required for the system-tx path to even consider the - // chain-id / nonce / inspect_account checks. With a non-whitelisted callee the - // request gets rejected up-front as "callee not in the whitelist" before our - // injected DB error has a chance to fire. - let tx = TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 1_000_000, - gas_price: 0, - chain_id: Some(chain_id), - nonce: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx); - - match res { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("Mega system transaction state read failed"), - "expected wrapped DB error, got: {msg}", - ); - } - other => panic!( - "expected EVMError::Custom for system-tx inspect_account DB error, got {other:?}" - ), - } -} diff --git a/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs b/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs deleted file mode 100644 index 91767300f..000000000 --- a/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs +++ /dev/null @@ -1,458 +0,0 @@ -//! Tests for the REX5+ deposit-caller account-creation accounting rule. -//! -//! Pre-REX5: `OpHandler::pre_execution` materialises an empty deposit caller via mint -//! balance increment and/or nonce bump without `MegaHandler::validate` charging any -//! `new_account_storage_gas` for the caller side. `state_growth_used` is also not -//! incremented, so the materialisation is effectively a free new L2 account. -//! -//! Under REX5: `validate()` detects deposit-like txs whose caller is empty at the -//! pre-`pre_execution` snapshot and: -//! 1. Adds `new_account_storage_gas(caller)` to `initial_gas`. -//! 2. Records `+1` on `state_growth.tx_entry.persistent_usage` via -//! `AdditionalLimit::record_deposit_caller_creation`. -//! -//! `data_size` and `kv_update` are intentionally NOT touched on this path — -//! `before_tx_start` already records the caller's account-info write unconditionally. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BucketHasher, BucketId, EmptyExternalEnv, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, - MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - BlockEnv, ContextSetters, TxEnv, - }, - handler::EvmTr, - primitives::TxKind, -}; - -/// A fresh L1 caller address — has no L2 account before the tx. -const EMPTY_CALLER: Address = address!("00000000000000000000000000000000000C0DE0"); -/// A caller that we pre-fund so it's already non-empty. -const FUNDED_CALLER: Address = address!("00000000000000000000000000000000000C0DE1"); -/// Whitelisted address from `MEGA_SYSTEM_TX_WHITELIST` for mega system deposit txs. -const WHITELISTED_CALLEE: Address = ORACLE_CONTRACT_ADDRESS; -/// A simple callee contract that just RETURNs. -const TARGET_CONTRACT: Address = address!("00000000000000000000000000000000000FEED1"); - -fn simple_return_contract() -> Bytes { - BytecodeBuilder::default().push_number(0u64).push_number(0u64).append(RETURN).build() -} - -/// Builds an OP deposit transaction (`tx_type` == `DEPOSIT_TRANSACTION_TYPE`) with the -/// specified caller, mint amount, and callee. -fn make_op_deposit_tx(caller: Address, mint: u128, callee: Address) -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(callee), - gas_limit: 100_000_000, - gas_price: 0, - ..Default::default() - }, - ..Default::default() - }; - // Setting a non-zero source_hash flips the tx_type to DEPOSIT_TRANSACTION_TYPE. - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.deposit.mint = Some(mint); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Builds an OP deposit Create transaction with the specified caller and mint. -/// The created contract address is derived from the caller's nonce at execution -/// time (pre-execution will set the caller's nonce to 1 for `Call` deposits, but -/// for `Create` deposits the nonce bump is deferred to `make_create_frame`). -fn make_op_deposit_create_tx(caller: Address, mint: u128) -> MegaTransaction { - // Minimal init code: STOP (deploys to a zero-byte runtime). - let init_code = Bytes::from_static(&[0x00]); - let mut tx = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Create, - data: init_code, - gas_limit: 100_000_000, - gas_price: 0, - ..Default::default() - }, - ..Default::default() - }; - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.deposit.mint = Some(mint); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Builds a mega system deposit-marked legacy tx. -fn make_mega_system_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(WHITELISTED_CALLEE), - gas_limit: 100_000_000, - gas_price: 0, - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -fn build_evm( - spec: MegaSpecId, - db: MemoryDatabase, -) -> MegaEvm { - let mut context = MegaContext::new(db, spec); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -type TestEvm = MegaEvm; -type TestEvmResult = - Result, EVMError>; - -fn transact_with( - spec: MegaSpecId, - db: MemoryDatabase, - tx: MegaTransaction, -) -> (TestEvmResult, TestEvm) { - let mut evm = build_evm(spec, db); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx); - (r, evm) -} - -/// REX5: the deposit-caller creation event increments `state_growth` by exactly 1. -#[test] -fn test_rex5_deposit_caller_creation_records_state_growth_plus_one() { - let db_empty = - MemoryDatabase::default().account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_empty = make_op_deposit_tx(EMPTY_CALLER, 1u128, TARGET_CONTRACT); - let (res_empty, evm_empty) = transact_with(MegaSpecId::REX5, db_empty, tx_empty); - assert!(res_empty.expect("ok").result.is_success()); - let growth_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - let db_funded = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_funded = make_op_deposit_tx(FUNDED_CALLER, 1u128, TARGET_CONTRACT); - let (res_funded, evm_funded) = transact_with(MegaSpecId::REX5, db_funded, tx_funded); - assert!(res_funded.expect("ok").result.is_success()); - let growth_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - assert_eq!( - growth_empty.saturating_sub(growth_funded), - 1, - "empty-caller deposit must record exactly +1 state_growth vs funded baseline (empty={}, funded={})", - growth_empty, growth_funded, - ); -} - -/// REX5: `data_size` and `kv_updates` are NOT incremented by the deposit-caller branch — the -/// caller's account-info write is already recorded by `before_tx_start` for every -/// transaction. The deposit-caller materialisation is a new account event, not a -/// new account-info write event. -#[test] -fn test_rex5_does_not_double_count_data_size_or_kv_updates() { - // Run an empty-caller deposit and a funded-caller deposit; compare data_size and - // kv_updates. They must match (the deposit-caller branch must NOT add a second account-info - // write on the empty-caller path). - let db_empty = - MemoryDatabase::default().account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_empty = make_op_deposit_tx(EMPTY_CALLER, 1u128, TARGET_CONTRACT); - let (_, evm_empty) = transact_with(MegaSpecId::REX5, db_empty, tx_empty); - let usage_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - let db_funded = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_funded = make_op_deposit_tx(FUNDED_CALLER, 1u128, TARGET_CONTRACT); - let (_, evm_funded) = transact_with(MegaSpecId::REX5, db_funded, tx_funded); - let usage_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - assert_eq!( - usage_empty.data_size, usage_funded.data_size, - "data_size must match between empty and funded caller (no second account-info write)", - ); - assert_eq!( - usage_empty.kv_updates, usage_funded.kv_updates, - "kv_updates must match between empty and funded caller (no second account-info write)", - ); -} - -/// REX5: a deposit-like tx whose caller is already non-empty does NOT incur an -/// extra caller-side storage gas charge. Complementary to the empty-caller test -/// above — pinned independently because regressions could land an unconditional -/// caller charge. -#[test] -fn test_rex5_non_empty_caller_no_extra_charge() { - // Non-deposit baseline: same caller/callee shape but as a normal (non-deposit) tx. - let db_normal = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1_000_000u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_normal = MegaTransaction { - base: TxEnv { - caller: FUNDED_CALLER, - kind: TxKind::Call(TARGET_CONTRACT), - gas_limit: 100_000_000, - gas_price: 0, - ..Default::default() - }, - ..Default::default() - }; - let (res_normal, _) = transact_with(MegaSpecId::REX5, db_normal, tx_normal); - let gas_normal = res_normal.expect("ok").result.gas_used(); - - // Deposit variant with the same already-non-empty caller. - let db_deposit = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1_000_000u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_deposit = make_op_deposit_tx(FUNDED_CALLER, 1u128, TARGET_CONTRACT); - let (res_deposit, evm_deposit) = transact_with(MegaSpecId::REX5, db_deposit, tx_deposit); - let _ = res_deposit.expect("ok"); - // No extra state-growth event for the caller. - let growth = evm_deposit.ctx_ref().additional_limit.borrow().get_usage().state_growth; - assert_eq!( - growth, 0, - "non-empty caller must not record a deposit-caller-creation state-growth event", - ); - - // Sanity: the deposit tx is at most the normal tx's gas (no extra caller charge). - // gas_used semantics for deposit can differ slightly (e.g., gas_price handling), so we - // only assert no significant inflation. - let _ = gas_normal; // referenced for clarity; precise inequality is implicit via growth check. -} - -/// Routes every account to a single high-capacity bucket so the new-account -/// storage gas charge under REX5 (`25_000 × (multiplier - 1)`) is non-zero. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - 7 - } -} - -/// REX5: pinpointed test for the storage gas charge specifically. -/// -/// The other state-growth-based tests prove the `if caller_is_empty` block was -/// entered, but they cannot directly verify the `initial_gas += storage_gas` line -/// (the `EmptyExternalEnv` multiplier is 1, so the charge is `25_000 × 0 = 0`). -/// -/// Strategy: use `TestExternalEnvs` with `bucket_capacity = 512` so multiplier = 2 -/// and the storage gas charge is `25_000 × 1 = 25_000` gas. Set `tx.gas_limit` -/// just below `intrinsic + 25_000` so the empty-caller deposit OOGs in -/// `before_execution` (where `init_gas > tx.gas_limit` is re-checked AFTER the -/// callee + deposit-caller charges are added), while the funded-caller deposit succeeds. -#[test] -fn test_rex5_storage_gas_charge_blocks_undergassed_empty_caller() { - use std::convert::Infallible; - const HEAVY_BUCKET: BucketId = 7; - const HEAVY_CAPACITY: u64 = 512; // 2 × MIN_BUCKET_SIZE → multiplier = 2 → charge = 25_000 - - // Gas-limit sized so the deposit's intrinsic (base tx + REX TX_INTRINSIC_STORAGE_GAS) - // alone fits but `+25_000` deposit-caller charge pushes it over. Base intrinsic for a simple - // REX5 Call is ~21k + ~39k (REX intrinsic storage) ≈ 60k; budget 75k so funded fits - // but empty (+25k) overflows. - const TIGHT_GAS_LIMIT: u64 = 75_000; - - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET, HEAVY_CAPACITY); - - // Empty-caller variant under tight gas — should OOG because of the deposit-caller charge. - let mut db_empty = - MemoryDatabase::default().account_code(TARGET_CONTRACT, simple_return_contract()); - let mut context_empty = MegaContext::new(&mut db_empty, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()); - context_empty.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut tx_empty = make_op_deposit_tx(EMPTY_CALLER, 1u128, TARGET_CONTRACT); - tx_empty.base.gas_limit = TIGHT_GAS_LIMIT; - let mut evm_empty = MegaEvm::new(context_empty); - let res_empty = alloy_evm::Evm::transact_raw(&mut evm_empty, tx_empty); - - // Funded-caller variant under same tight gas — the deposit-caller branch doesn't fire, so the - // intrinsic alone fits and execution proceeds (may or may not succeed depending - // on the exact intrinsic cost, but it must NOT halt with the same OutOfGas the - // empty-caller variant produces from `initial_gas > tx.gas_limit`). - let mut db_funded = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let mut context_funded = MegaContext::new(&mut db_funded, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()); - context_funded.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut tx_funded = make_op_deposit_tx(FUNDED_CALLER, 1u128, TARGET_CONTRACT); - tx_funded.base.gas_limit = TIGHT_GAS_LIMIT; - let mut evm_funded = MegaEvm::new(context_funded); - let res_funded = alloy_evm::Evm::transact_raw(&mut evm_funded, tx_funded); - - // Expected failure class: `validate()` adds the deposit-caller charge AFTER its - // `initial_gas > tx.gas_limit` early-check (which sees only intrinsic + calldata - // storage gas), so validation does NOT reject. The overflow is caught later by - // `before_execution` (`init_gas > tx.gas_limit` re-check), which synthesizes an - // OOG halt frame result. Net: empty-caller returns `Ok` with a halted result; - // funded-caller returns `Ok` with success. Pin both halves precisely so that a - // future intrinsic-gas tweak that changes which check fires would surface here - // as a test failure rather than be silently absorbed. - let res_empty = res_empty.expect("empty-caller deposit must not produce a validation Err"); - let res_funded = res_funded.expect("funded-caller deposit must not produce a validation Err"); - assert!( - !res_empty.result.is_success(), - "Deposit-caller storage gas must push the empty-caller deposit over TIGHT_GAS_LIMIT, \ - producing an OOG halt (got {:?})", - res_empty.result, - ); - assert!( - res_funded.result.is_success(), - "funded-caller deposit must succeed under the same gas budget (the deposit-caller branch must not fire \ - when the caller is already non-empty); got {:?}", - res_funded.result, - ); -} - -/// REX5: a deposit `TxKind::Create` whose caller is empty at validation time has -/// two distinct accounts that need accounting: -/// -/// 1. The created contract — charged by the existing callee branch in `validate()` via -/// `create_contract_storage_gas(created_address)`. -/// 2. The caller account (materialized by `pre_execution`'s nonce-bump path for `Create` -/// deposits) — charged by the deposit-caller branch via `new_account_storage_gas(caller)`. -/// -/// The self-call short-circuit does not fire for `Create` (it only matches -/// `TxKind::Call(addr) if addr == caller`), so both charges legitimately apply. -/// The deposit-caller branch additionally records `+1` state-growth for the caller -/// materialization (the existing `Create` branch records state-growth later in -/// `state_growth.before_frame_init` when the `Create` frame is pushed — a separate -/// `+1` for the created contract). -#[test] -fn test_rex5_deposit_create_with_empty_caller_records_caller_state_growth() { - let db_empty = MemoryDatabase::default(); - let tx_empty = make_op_deposit_create_tx(EMPTY_CALLER, 1u128); - let (res_empty, evm_empty) = transact_with(MegaSpecId::REX5, db_empty, tx_empty); - assert!(res_empty.expect("ok").result.is_success(), "Create deposit must succeed"); - let usage_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - // Funded-caller baseline: same Create shape but caller already non-empty, so the - // deposit-caller branch does NOT fire and the caller-side state-growth +1 is - // absent. The created contract's +1 state-growth still happens in both cases - // (frame_init records it for `Create`). - let db_funded = MemoryDatabase::default().account_balance(FUNDED_CALLER, U256::from(1u64)); - let tx_funded = make_op_deposit_create_tx(FUNDED_CALLER, 1u128); - let (res_funded, evm_funded) = transact_with(MegaSpecId::REX5, db_funded, tx_funded); - assert!(res_funded.expect("ok").result.is_success(), "Create deposit must succeed"); - let usage_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - assert_eq!( - usage_empty.state_growth.saturating_sub(usage_funded.state_growth), - 1, - "Create deposit with empty caller must record exactly +1 state_growth for the caller \ - materialization (in addition to the +1 the Create frame records for the created \ - contract, which is present in both runs); empty={}, funded={}", - usage_empty.state_growth, - usage_funded.state_growth, - ); - - // `data_size` / `kv_updates` must be identical between empty and funded — the - // deposit-caller branch only touches state_growth and intrinsic gas. - assert_eq!( - usage_empty.data_size, usage_funded.data_size, - "Create deposit must not add a second account-info write to data_size for the caller", - ); - assert_eq!( - usage_empty.kv_updates, usage_funded.kv_updates, - "Create deposit must not add a second kv_update for the caller", - ); -} - -/// REX5 corner case: `deposit TxKind::Call(caller)` with `value > 0` and an -/// empty caller. The existing callee branch in `validate()` already charges -/// `new_account_storage_gas(caller_as_callee)` for this exact account, so the -/// deposit-caller branch must NOT double-charge. We pin both halves of the invariant: -/// 1. Gas charge is single-shot — comparing a self-call deposit's intrinsic against a -/// non-self-call deposit (with the same other parameters) must not show a 2× difference vs the -/// non-deposit baseline. -/// 2. State-growth is still recorded exactly once — the +1 must land even though the gas charge -/// is suppressed. -#[test] -fn test_rex5_self_call_caller_eq_callee_does_not_double_charge() { - use std::convert::Infallible; - const HEAVY_BUCKET: BucketId = 99; - const HEAVY_CAPACITY: u64 = 512; // multiplier = 2 → 25_000 gas per new account - - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET, HEAVY_CAPACITY); - - // Self-call: caller == callee == EMPTY_CALLER, value > 0. - let mut db_self = MemoryDatabase::default(); - let mut context_self = MegaContext::new(&mut db_self, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()); - context_self.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut tx_self = make_op_deposit_tx(EMPTY_CALLER, 10_000_000u128, EMPTY_CALLER); - tx_self.base.value = U256::from(1u64); - // Set gas_limit just barely enough for intrinsic + ONE new_account_storage_gas charge. - // If the deposit-caller branch double-charged, this would push initial_gas above gas_limit and - // the tx would halt with OOG via `before_execution`. - tx_self.base.gas_limit = 90_000; - let mut evm_self = MegaEvm::new(context_self); - let r_self = alloy_evm::Evm::transact_raw(&mut evm_self, tx_self).expect("transact ok"); - assert!( - r_self.result.is_success(), - "self-call deposit must succeed under single-charge gas budget — \ - a halt here indicates the deposit-caller branch double-charged on top of the callee branch", - ); - - // State_growth must still record exactly +1 (the materialisation event). - let growth = evm_self.ctx_ref().additional_limit.borrow().get_usage().state_growth; - assert_eq!( - growth, 1, - "self-call deposit must still record +1 state_growth even when gas is single-charged", - ); -} - -/// Routes every account to a single bucket so the test above can drive the SALT -/// multiplier above 1 without depending on `EMPTY_CALLER`'s natural bucket id. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasherSelf; - -impl BucketHasher for SingleBucketHasherSelf { - fn bucket_id(_key: &[u8]) -> BucketId { - 99 - } -} - -/// REX5: a mega-system-deposit-marked legacy tx with an empty system address -/// follows the same deposit-caller branch (test-only construction — in production the -/// system address has been seeded by the bootstrap). -#[test] -fn test_rex5_mega_system_deposit_marked_legacy_tx_branch() { - // Note: this is a test-only construction. In production the mega system address - // is non-empty by the time blocks execute. - let db = MemoryDatabase::default().account_code(WHITELISTED_CALLEE, simple_return_contract()); - let tx = make_mega_system_tx(); - let (res, evm) = transact_with(MegaSpecId::REX5, db, tx); - let res = res.expect("ok"); - assert!(res.result.is_success(), "mega system deposit tx must succeed"); - - let growth = evm.ctx_ref().additional_limit.borrow().get_usage().state_growth; - assert_eq!(growth, 1, "mega-system-marked tx with empty caller must record +1 state_growth",); -} diff --git a/crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs b/crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs deleted file mode 100644 index 2556f5312..000000000 --- a/crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs +++ /dev/null @@ -1,301 +0,0 @@ -//! Tests for the REX5+ zero-copy selector probing in system-contract -//! interceptor dispatch. -//! -//! Pre-REX5: each interceptor began with `call_inputs.input.bytes(ctx)` which -//! materializes the entire calldata. For `CallInput::SharedBuffer`, this copies the -//! full `argsSize` range out of shared memory on every dispatch attempt — even when -//! the selector ultimately does not match — producing a memory-bandwidth / -//! allocator `DoS` vector. -//! -//! Under REX5: REX5+ uses `peek_selector` which only reads four bytes from the input -//! head. Trailing bytes are never copied. Pre-REX5 keeps the original -//! `input.bytes(ctx)` + `abi_decode` path so historical replay is unaffected. -//! -//! These tests prove byte-for-byte equivalence of the admission decision across -//! REX4 and REX5 for the consensus-visible inputs (exact selector, selector + -//! trailing junk, truncated input below 4 bytes, unknown 4-byte selector). The -//! plan's `..._no_full_copy` performance assertion would require instrumenting -//! `LocalContext` to count `shared_memory_buffer_slice` calls and is intentionally -//! left out of this regression suite — behavior equivalence is the -//! consensus-critical invariant. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, IOracle, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, TestExternalEnvs, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000400000"); -const PROBE_CONTRACT: Address = address!("0000000000000000000000000000000000400001"); - -const DISABLE_SELECTOR: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Builds bytecode that: -/// 1. Writes a 4-byte selector at memory[0..4]. -/// 2. Writes `tail_size` zero bytes after the selector (no-op MSTORE pad to grow memory). -/// 3. Calls `ACCESS_CONTROL` with `argsSize = 4 + tail_size`, `argsOffset = 0`. -/// 4. Returns the CALL's success flag (32-byte big-endian) as the outer-tx output. -fn build_probe_bytecode(selector: [u8; 4], tail_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default().mstore(0x0, selector); - if tail_size > 0 { - // Grow memory by writing one byte at offset `4 + tail_size - 1`. MSTORE writes 32 bytes, - // so this expands memory to cover the full 4 + tail_size span. The bytes beyond the - // selector are whatever the EVM zero-initialized — that's the "trailing junk" the - // peek_selector path must skip reading from shared memory. - let last_byte_offset = 4 + tail_size - 1; - builder = builder.push_number(0u64).push_number(last_byte_offset as u64).append(MSTORE8); - } - let args_size = 4u64 + tail_size as u64; - builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(args_size) - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(1_000_000u64) // gas forwarded to system contract - .append(CALL) // success flag on stack - .push_number(0u64) - .append(MSTORE) // store success flag at memory[0..32] - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build() -} - -fn run_probe( - spec: MegaSpecId, - selector: [u8; 4], - tail_size: usize, -) -> ResultAndState { - let code = build_probe_bytecode(selector, tail_size); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(PROBE_CONTRACT, code) - // The on-chain ACCESS_CONTROL_CODE is needed so non-intercepted calls fall through - // to actual bytecode (which reverts NotIntercepted()) instead of being treated as - // a call to an empty account (which would return success=1 and obscure the test). - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(PROBE_CONTRACT) - .gas_limit(100_000_000) - .build_fill(); - transact(spec, &mut db, tx).expect("transact should succeed") -} - -fn extract_success_flag(result: &ResultAndState) -> U256 { - let ExecutionResult::Success { output, .. } = &result.result else { - panic!("expected outer tx success, got {:?}", result.result); - }; - let bytes = output.data(); - assert_eq!(bytes.len(), 32, "outer return must be a 32-byte success flag"); - U256::from_be_slice(bytes) -} - -/// Pinned admission rule across REX4 and REX5: -/// An exact 4-byte selector to `ACCESS_CONTROL` is intercepted in both specs. -#[test] -fn test_exact_selector_intercepts_under_both_specs() { - for spec in [MegaSpecId::REX4, MegaSpecId::REX5] { - let result = run_probe(spec, DISABLE_SELECTOR, 0); - let flag = extract_success_flag(&result); - assert_eq!( - flag, - U256::from(1), - "{:?}: exact 4-byte selector must intercept (CALL success)", - spec, - ); - } -} - -/// Pinned admission rule across REX4 and REX5: -/// A 4-byte selector followed by 1 KiB of trailing junk to `ACCESS_CONTROL` is -/// intercepted in both specs. Under REX5 the trailing bytes are never read from -/// shared memory; behavior equivalence is what this test pins, the perf -/// invariant is documented in the plan. -#[test] -fn test_selector_plus_junk_intercepts_under_both_specs() { - for spec in [MegaSpecId::REX4, MegaSpecId::REX5] { - let result = run_probe(spec, DISABLE_SELECTOR, 1024); - let flag = extract_success_flag(&result); - assert_eq!(flag, U256::from(1), "{:?}: selector + 1KiB junk must still intercept", spec,); - } -} - -/// Pinned fall-through rule across REX4 and REX5: -/// A 2-byte input (below the 4-byte selector size) cannot match any selector and -/// must fall through to the on-chain bytecode (which reverts `NotIntercepted`, so -/// the CALL returns success=0). -#[test] -fn test_truncated_calldata_falls_through_under_both_specs() { - // 2-byte input by reusing build_probe_bytecode with tail_size 0 but custom selector - // ... actually we need argsSize = 2. Build manually: - let code = BytecodeBuilder::default() - .mstore(0x0, DISABLE_SELECTOR) // 32-byte word - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(2u64) // argsSize = 2 bytes (truncated) - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - for spec in [MegaSpecId::REX4, MegaSpecId::REX5] { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(PROBE_CONTRACT, code.clone()) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(PROBE_CONTRACT) - .gas_limit(100_000_000) - .build_fill(); - let result = transact(spec, &mut db, tx).expect("transact ok"); - let flag = extract_success_flag(&result); - assert_eq!( - flag, - U256::from(0), - "{:?}: 2-byte input must fall through (CALL returns failure)", - spec, - ); - } -} - -/// Pinned fall-through rule across REX4 and REX5: -/// An unknown 4-byte selector to `ACCESS_CONTROL` falls through to on-chain -/// bytecode (`NotIntercepted` revert). -#[test] -fn test_unknown_selector_falls_through_under_both_specs() { - let unknown = [0xde, 0xad, 0xbe, 0xef]; - for spec in [MegaSpecId::REX4, MegaSpecId::REX5] { - let result = run_probe(spec, unknown, 0); - let flag = extract_success_flag(&result); - assert_eq!(flag, U256::from(0), "{:?}: unknown 4-byte selector must fall through", spec,); - } -} - -/// Selector-match-plus-malformed-args parity for the `OracleHint` interceptor. -/// -/// This is the only interceptor where the REX5+ branch still calls -/// `input.bytes(ctx)` and `abi_decode` after the selector probe matches (because -/// `sendHint` carries args). The risk being pinned: if a refactor ever drops the -/// inner `abi_decode` retry under REX5+, `on_hint` would fire with garbage data. -/// -/// We send `sendHint`'s selector followed by truncated args (4 + 64 bytes — not -/// enough to satisfy the `(bytes32, bytes)` encoding) and assert no hint is -/// recorded under either spec. -#[test] -fn test_oracle_hint_malformed_args_does_not_record_under_both_specs() { - let send_hint_selector: [u8; 4] = IOracle::sendHintCall::SELECTOR; - // Bytecode: write `selector || 16 zero bytes` at memory[0..20], then CALL with argsSize=20. - // sendHint requires `(bytes32 topic, bytes data)` = at minimum 64 bytes (32 topic + 32 offset). - // 16 bytes of args is far short of even a single ABI word; abi_decode MUST fail. - let code = BytecodeBuilder::default() - .mstore(0x0, send_hint_selector) - // Grow memory to 20 bytes via MSTORE8 at offset 19. - .push_number(0u64) - .push_number(19u64) - .append(MSTORE8) - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(20u64) // argsSize (selector + 16 zero bytes — too short for topic) - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - - for spec in [MegaSpecId::REX4, MegaSpecId::REX5] { - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(PROBE_CONTRACT, code.clone()) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - let mut context = - MegaContext::new(&mut db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(PROBE_CONTRACT) - .gas_limit(100_000_000) - .build_fill(); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let _ = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - - assert!( - external_envs.recorded_hints().is_empty(), - "{:?}: malformed sendHint args must NOT trigger on_hint", - spec, - ); - } -} - -/// Cross-spec parity: every input shape produces the same CALL success flag in -/// REX4 and REX5. This is the consensus-critical invariant — a divergence here -/// would break replay of a REX4 block under a REX5+ node or vice versa. -#[test] -fn test_admission_decision_parity_across_specs() { - let shapes: &[(_, usize, &str)] = &[ - (DISABLE_SELECTOR, 0, "exact selector"), - (DISABLE_SELECTOR, 1, "selector + 1B junk"), - (DISABLE_SELECTOR, 1024, "selector + 1KiB junk"), - ([0xde, 0xad, 0xbe, 0xef], 0, "unknown 4-byte selector"), - ([0xde, 0xad, 0xbe, 0xef], 1024, "unknown selector + 1KiB junk"), - ]; - for (sel, tail, label) in shapes { - let rex4 = extract_success_flag(&run_probe(MegaSpecId::REX4, *sel, *tail)); - let rex5 = extract_success_flag(&run_probe(MegaSpecId::REX5, *sel, *tail)); - assert_eq!( - rex4, rex5, - "admission decision must match across REX4 and REX5 for shape: {}", - label, - ); - } -} diff --git a/crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs b/crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs deleted file mode 100644 index 75a9c4f22..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Cross-spec admission parity for `KeylessDeployInterceptor`. -//! -//! Every input shape below must produce the same outer-transaction outcome on -//! REX4 and REX5. A spec-gated divergence in the interceptor's admission path -//! would fail one of these tests. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - revm::context::result::ExecutionResult, test_utils::MemoryDatabase, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, - KEYLESS_DEPLOY_CODE, -}; -use revm::context::{result::ResultAndState, tx::TxEnvBuilder}; - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); - -const KEYLESS_DEPLOY_SELECTOR: [u8; 4] = mega_evm::IKeylessDeploy::keylessDeployCall::SELECTOR; - -fn run_dispatch(spec: MegaSpecId, calldata: Bytes) -> ResultAndState { - // KEYLESS_DEPLOY_CODE is installed so non-intercepted calls fall through to - // canonical on-chain bytecode (which reverts NotIntercepted()). - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000u64)) - .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); - - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(&mut db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx_env = TxEnvBuilder::default() - .caller(CALLER) - .kind(TxKind::Call(KEYLESS_DEPLOY_ADDRESS)) - .gas_limit(30_000_000) - .gas_price(0) - .data(calldata) - .build_fill(); - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact must not surface a fatal EVMError") -} - -// Result tag + payload bytes only — gas counters are excluded so the parity -// check is admission-shaped, not gas-accounting-shaped. -fn outcome_fingerprint(res: &ResultAndState) -> (&'static str, Vec) { - match &res.result { - ExecutionResult::Success { output, .. } => ("Success", output.data().to_vec()), - ExecutionResult::Revert { output, .. } => ("Revert", output.to_vec()), - ExecutionResult::Halt { reason, .. } => ("Halt", format!("{reason:?}").into_bytes()), - } -} - -#[test] -fn test_keyless_deploy_unknown_selector_falls_through_across_specs() { - let calldata = Bytes::from(vec![0xde, 0xad, 0xbe, 0xef]); - let rex4 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX4, calldata.clone())); - let rex5 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX5, calldata)); - assert_eq!(rex4.0, "Revert"); - assert_eq!(rex4, rex5); -} - -#[test] -fn test_keyless_deploy_short_input_falls_through_across_specs() { - for tail in [&[][..], &[0xab][..], &[0xab, 0xcd][..], &[0xab, 0xcd, 0xef][..]] { - let calldata = Bytes::from(tail.to_vec()); - let rex4 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX4, calldata.clone())); - let rex5 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX5, calldata)); - assert_eq!(rex4.0, "Revert", "len={}", tail.len()); - assert_eq!(rex4, rex5, "len={}", tail.len()); - } -} - -#[test] -fn test_keyless_deploy_truncated_args_falls_through_across_specs() { - let mut calldata = Vec::with_capacity(5); - calldata.extend_from_slice(&KEYLESS_DEPLOY_SELECTOR); - calldata.push(0xff); - let calldata = Bytes::from(calldata); - - let rex4 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX4, calldata.clone())); - let rex5 = outcome_fingerprint(&run_dispatch(MegaSpecId::REX5, calldata)); - assert_eq!(rex4.0, "Revert"); - assert_eq!(rex4, rex5); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 439aad933..1e50e1579 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -5,12 +5,9 @@ mod callcode_storage_gas; mod create2_empty_initcode; mod create2_resize_gas_metering; mod db_error; -mod deposit_caller_accounting; mod deposit_create_storage_gas; mod eip7702_metering; mod eip7702_state_growth; -mod interceptor_selector_probe; -mod keyless_deploy_dispatch_parity; mod keyless_empty_code_logs; mod keyless_fee_free; mod keyless_gas_cap_postcap_recheck; @@ -21,4 +18,3 @@ mod sandbox_accounting; mod selfdestruct_beneficiary; mod sstore_storage_gas_error; mod stipend_accounting; -mod system_tx_replay; diff --git a/crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs b/crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs deleted file mode 100644 index 9413a69c5..000000000 --- a/crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs +++ /dev/null @@ -1,640 +0,0 @@ -//! REX5 replay protection for `MEGA_SYSTEM_ADDRESS` legacy transactions. -//! -//! A legacy transaction whose caller is the runtime `system_address` is otherwise -//! normalized into a deposit-style transaction by `MegaHandler::before_run`, which -//! bypasses signature validation, nonce verification, and chain-id binding. REX5+ -//! restores nonce and chain-id checks and uses canonical `InvalidTransaction` variants -//! so the rejections are classified as tx-validation errors by `IsTxError`. -//! -//! The restored checks honor the same `CfgEnv` toggles the canonical revm validate -//! path honors (`tx_chain_id_check`, `disable_nonce_check`, `disable_eip3607`). In -//! production these all default to "checks enabled"; debug / state-test / replay tools -//! that legitimately toggle them see consistent behavior across ordinary user txs and -//! system txs. -//! -//! Test layout: -//! -//! - Stale nonce, in-block double-tx, and happy path use the real block-executor flow -//! (`MegaBlockExecutor::run_transaction` → `commit_transaction_outcome`) so the journal cache / -//! DB commit boundary is exercised exactly as in production. -//! - Wrong chain id, missing chain id, and the cfg-toggle pin use the simpler `transact_raw` flow -//! on a fresh EVM — those rejections (or acceptances) fire on the very first tx so a -//! block-executor wrapping is unnecessary. - -use std::convert::Infallible; - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, Evm as _, EvmEnv}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, EVMError, IOracle, MegaBlockExecutionCtx, - MegaBlockExecutor, MegaBlockExecutorFactory, MegaContext, MegaEvm, MegaEvmFactory, - MegaHardfork, MegaHardforkConfig, MegaSpecId, MegaTransaction, MegaTransactionError, - MegaTxEnvelope, SequencerRegistryConfig, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - context::{result::InvalidTransaction, BlockEnv, CfgEnv, ContextTr as _, TxEnv}, - database::State, - Database as _, -}; - -const REGULAR_CALLER: Address = address!("0000000000000000000000000000000000100000"); -const FOREIGN_CHAIN_ID: u64 = 31337; -const MEGA_CHAIN_ID: u64 = 4326; -const SYSTEM_TX_GAS_LIMIT: u64 = 4_020_000; -const BLOCK_GAS_LIMIT: u64 = 100_000_000; -const ORACLE_SLOT: U256 = U256::ZERO; - -const BOOTSTRAP_SEQUENCER: Address = address!("4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("5000000000000000000000000000000000000005"); - -type PocExecutor<'a> = MegaBlockExecutor< - MegaHardforkConfig, - MegaEvm< - &'a mut State, - revm::inspector::NoOpInspector, - TestExternalEnvs, - >, - OpAlloyReceiptBuilder, ->; - -/// A chain running Rex5, matching the `CfgEnv.spec = REX5` these tests set. -fn rex5_hardforks() -> MegaHardforkConfig { - // Rex6+ is excluded: this suite pins Rex5 semantics (v1.0.0 registry, REX5 spec). - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5).with_params( - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - }, - ) -} - -/// Per-test cfg toggles that affect the REX5 system-tx guards. Defaults match the -/// production-equivalent `CfgEnv` shape (chain-id check on, nonce check on, EIP-3607 -/// on), so most tests can call `Rex5Cfg::default()`; tests that pin the cfg-toggle -/// escape hatch override one field via struct-update syntax. -#[derive(Copy, Clone)] -struct Rex5Cfg { - /// Mirrors `CfgEnv::tx_chain_id_check` — production default `true`. - tx_chain_id_check: bool, - /// Mirrors `CfgEnv::disable_nonce_check` — production default `false`. - disable_nonce_check: bool, - /// Mirrors `CfgEnv::disable_eip3607` — production default `false`. - disable_eip3607: bool, -} - -impl Default for Rex5Cfg { - fn default() -> Self { - Self { tx_chain_id_check: true, disable_nonce_check: false, disable_eip3607: false } - } -} - -fn rex5_evm_env(cfg: Rex5Cfg) -> EvmEnv { - let mut cfg_env = CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX5; - cfg_env.chain_id = MEGA_CHAIN_ID; - cfg_env.tx_chain_id_check = cfg.tx_chain_id_check; - cfg_env.disable_nonce_check = cfg.disable_nonce_check; - cfg_env.disable_eip3607 = cfg.disable_eip3607; - - let block_env = BlockEnv { - number: U256::from(10), - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - basefee: 0, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn create_rex5_block_executor<'a>( - state: &'a mut State, - cfg: Rex5Cfg, -) -> PocExecutor<'a> { - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let executor_factory = MegaBlockExecutorFactory::new( - rex5_hardforks(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let block_limits = - BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex5, BLOCK_GAS_LIMIT); - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), block_limits); - let mut executor = executor_factory.create_executor(state, block_ctx, rex5_evm_env(cfg)); - executor.evm.ctx.chain_mut().operator_fee_scalar = Some(U256::ZERO); - executor.evm.ctx.chain_mut().operator_fee_constant = Some(U256::ZERO); - executor -} - -fn oracle_set_slots_calldata(slot: U256, value: B256) -> Bytes { - IOracle::setSlotsCall { slots: vec![slot], values: vec![value] }.abi_encode().into() -} - -fn recovered_legacy_tx( - signer: Address, - nonce: u64, - chain_id: Option, - to: Address, - data: Bytes, - gas_limit: u64, - gas_price: u128, -) -> Recovered { - let tx = TxLegacy { - chain_id, - nonce, - gas_price, - gas_limit, - to: TxKind::Call(to), - value: U256::ZERO, - input: data, - }; - let signed = Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::with_last_byte(nonce.saturating_add(1) as u8), - ); - Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), signer) -} - -fn system_tx_with( - nonce: u64, - chain_id: Option, - slot: U256, - value: B256, -) -> Recovered { - recovered_legacy_tx( - MEGA_SYSTEM_ADDRESS, - nonce, - chain_id, - ORACLE_CONTRACT_ADDRESS, - oracle_set_slots_calldata(slot, value), - SYSTEM_TX_GAS_LIMIT, - 0, - ) -} - -fn assert_invalid_tx_contains(err: &E, marker: &str) { - let dbg = format!("{err:?}"); - assert!(dbg.contains(marker), "expected error containing {marker}, got {dbg}"); -} - -fn oracle_storage_at(db: &mut DB, slot: U256) -> U256 -where - ::Error: core::fmt::Debug, -{ - db.storage(ORACLE_CONTRACT_ADDRESS, slot).expect("oracle storage read should succeed") -} - -// ============================================================================ -// 1. Stale-nonce replay rejected (block executor flow) -// ============================================================================ - -/// REX5: a legacy `MEGA_SYSTEM_ADDRESS` tx with `tx.nonce < state.nonce` is rejected -/// at `before_run` with `InvalidTransaction::NonceTooLow`. Pre-fix, the deposit -/// promotion would skip the canonical nonce check and let the stale tx commit again, -/// rolling oracle state back. Post-fix, replay is blocked before any state mutation. -#[test] -fn test_legacy_system_address_tx_with_stale_nonce_is_rejected() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor - .apply_pre_execution_changes() - .expect("REX5 pre-execution should deploy the oracle and seed the registry"); - - // tx0: nonce=0 → succeeds, oracle slot = 0x1111 - let old_value = B256::with_last_byte(0x11); - let tx0 = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, old_value); - let outcome0 = executor - .run_transaction(&tx0) - .expect("nonce=0 system tx must succeed under REX5 happy path"); - assert!(outcome0.result.is_success()); - executor.commit_transaction_outcome(outcome0).expect("commit nonce=0"); - - // tx1: nonce=1 → succeeds, oracle slot = 0x2222 - let new_value = B256::with_last_byte(0x22); - let tx1 = system_tx_with(1, Some(MEGA_CHAIN_ID), ORACLE_SLOT, new_value); - let outcome1 = executor.run_transaction(&tx1).expect("nonce=1 system tx must succeed"); - assert!(outcome1.result.is_success()); - executor.commit_transaction_outcome(outcome1).expect("commit nonce=1"); - - // Replay tx0 (nonce=0) — must be rejected with NonceTooLow now that state.nonce == 2. - let replay_err = executor - .run_transaction(&tx0) - .expect_err("stale nonce=0 replay must be rejected at validation"); - assert_invalid_tx_contains(&replay_err, "NonceTooLow"); - - // Oracle slot must still hold the new_value — replay did NOT roll the value back. - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!( - oracle_after, - U256::from_be_bytes(new_value.0), - "stale replay must not overwrite the latest oracle value", - ); - // Sender nonce must stay at 2 (not bumped by the rejected replay). - let nonce_after = executor.evm.db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().nonce; - assert_eq!(nonce_after, 2, "rejected replay must not bump the system address nonce"); -} - -/// REX5: a legacy `MEGA_SYSTEM_ADDRESS` tx with `tx.nonce > state.nonce` is rejected -/// at `before_run` with `InvalidTransaction::NonceTooHigh`. Pins the second branch of -/// the canonical nonce comparison so a regression in either direction is caught. -#[test] -fn test_legacy_system_address_tx_with_future_nonce_is_rejected() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - // state.nonce starts at 0; submit tx with nonce=5 (large gap). - let value = B256::with_last_byte(0x77); - let future_tx = system_tx_with(5, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value); - - let err = executor - .run_transaction(&future_tx) - .expect_err("future-nonce system tx must be rejected at validation"); - assert_invalid_tx_contains(&err, "NonceTooHigh"); - - // No state mutation: oracle slot untouched, system nonce still at 0. - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!(oracle_after, U256::ZERO); - let nonce_after = executor - .evm - .db_mut() - .basic(MEGA_SYSTEM_ADDRESS) - .expect("db read should succeed") - .map(|info| info.nonce) - .unwrap_or(0); - assert_eq!(nonce_after, 0); -} - -// ============================================================================ -// 2. In-block double-tx happy path (journal-cache correctness) -// ============================================================================ - -/// REX5: two legitimate sequencer system transactions in the same block must both -/// succeed, with `state.nonce` advancing 0 → 1 → 2. The nonce read uses -/// `journal.inspect_account` (cache → DB fallback, no access-list warming), so the -/// second tx in the same block sees the first tx's committed nonce bump even though -/// no DB-level flush has happened yet. -#[test] -fn test_two_legitimate_system_txs_in_same_block_both_succeed() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value0 = B256::with_last_byte(0xAA); - let value1 = B256::with_last_byte(0xBB); - - let tx0 = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value0); - let tx1 = system_tx_with(1, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value1); - - let outcome0 = executor.run_transaction(&tx0).expect("first in-block system tx must succeed"); - assert!(outcome0.result.is_success()); - executor.commit_transaction_outcome(outcome0).expect("commit tx0"); - - let outcome1 = executor.run_transaction(&tx1).expect( - "second in-block system tx must succeed; journal cache must reflect tx0's nonce bump", - ); - assert!(outcome1.result.is_success()); - executor.commit_transaction_outcome(outcome1).expect("commit tx1"); - - // Final state: oracle slot reflects the second update; sender nonce = 2. - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!(oracle_after, U256::from_be_bytes(value1.0)); - let nonce_after = executor.evm.db_mut().basic(MEGA_SYSTEM_ADDRESS).unwrap().unwrap().nonce; - assert_eq!(nonce_after, 2); -} - -// ============================================================================ -// 3. Wrong chain id rejected (block executor) -// ============================================================================ - -/// REX5: a legacy system-address tx with a foreign chain id is rejected with -/// `InvalidTransaction::InvalidChainId`. Pre-fix, the deposit promotion would skip -/// the chain-id check and let the foreign envelope commit. -#[test] -fn test_legacy_system_address_tx_with_wrong_chain_id_is_rejected() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0xCC); - let foreign_tx = system_tx_with(0, Some(FOREIGN_CHAIN_ID), ORACLE_SLOT, value); - - let err = executor - .run_transaction(&foreign_tx) - .expect_err("foreign-chain-id system tx must be rejected at validation"); - assert_invalid_tx_contains(&err, "InvalidChainId"); - - // Sender nonce unchanged at 0 — no state mutation. The system address may not even - // exist in the DB after a pre-promotion rejection, so default to 0. - let nonce_after = executor - .evm - .db_mut() - .basic(MEGA_SYSTEM_ADDRESS) - .expect("db read should succeed") - .map(|info| info.nonce) - .unwrap_or(0); - assert_eq!(nonce_after, 0); -} - -// ============================================================================ -// 4. chain_id = None rejected (block executor) -// ============================================================================ - -/// REX5: a legacy system-address tx with `chain_id = None` (pre-EIP-155 shape) is -/// rejected with `InvalidTransaction::MissingChainId`. Production sequencer -/// transactions must carry a chain id on REX5+; this test pins that requirement. -#[test] -fn test_legacy_system_address_tx_with_chain_id_none_is_rejected() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0xDD); - let no_chain_id_tx = system_tx_with(0, None, ORACLE_SLOT, value); - - let err = executor - .run_transaction(&no_chain_id_tx) - .expect_err("system tx with chain_id=None must be rejected at validation"); - assert_invalid_tx_contains(&err, "MissingChainId"); - - let nonce_after = executor - .evm - .db_mut() - .basic(MEGA_SYSTEM_ADDRESS) - .expect("db read should succeed") - .map(|info| info.nonce) - .unwrap_or(0); - assert_eq!(nonce_after, 0); -} - -// ============================================================================ -// 5. cfg.tx_chain_id_check = false skips the system-tx chain-id guard (block executor) -// ============================================================================ - -/// REX5: when the operator disables `cfg.tx_chain_id_check`, the system-address -/// chain-id guard is skipped — system txs follow the same cfg-honoring policy as -/// ordinary user txs. Production defaults `tx_chain_id_check = true` so the canonical -/// chain-id binding remains in force; this test pins the cfg-toggle escape hatch for -/// debug / state-test / replay tooling. -#[test] -fn test_cfg_tx_chain_id_check_disabled_skips_system_tx_chain_id_guard() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor( - &mut state, - Rex5Cfg { tx_chain_id_check: false, ..Default::default() }, - ); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0xEE); - let foreign_tx = system_tx_with(0, Some(FOREIGN_CHAIN_ID), ORACLE_SLOT, value); - - let outcome = executor - .run_transaction(&foreign_tx) - .expect("system tx with foreign chain id must succeed when cfg.tx_chain_id_check = false"); - assert!( - outcome.result.is_success(), - "system tx must commit when cfg.tx_chain_id_check = false; got {:?}", - outcome.result, - ); - executor.commit_transaction_outcome(outcome).expect("commit cfg-disabled system tx"); - - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!( - oracle_after, - U256::from_be_bytes(value.0), - "oracle storage must reflect the system tx write when cfg.tx_chain_id_check is off", - ); -} - -// ============================================================================ -// 5b. cfg.disable_nonce_check = true skips the system-tx nonce guard -// ============================================================================ - -/// REX5: when the operator sets `cfg.disable_nonce_check = true`, the system-address -/// nonce guard is skipped — same input that would be rejected as `NonceTooLow` under -/// the default cfg now commits. Mirrors -/// `test_legacy_system_address_tx_with_stale_nonce_is_rejected` to keep the cfg-toggle contract -/// symmetric. -#[test] -fn test_cfg_disable_nonce_check_skips_system_tx_nonce_guard() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor( - &mut state, - Rex5Cfg { disable_nonce_check: true, ..Default::default() }, - ); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - // tx0: nonce=0 → state.nonce advances to 1. - let v0 = B256::with_last_byte(0x11); - let tx0 = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, v0); - let outcome0 = executor.run_transaction(&tx0).expect("nonce=0 system tx must succeed"); - assert!(outcome0.result.is_success()); - executor.commit_transaction_outcome(outcome0).expect("commit nonce=0"); - - // tx_stale: nonce=0 again. Under prod cfg this is rejected (`NonceTooLow`); with - // `disable_nonce_check = true` it must commit and overwrite the oracle slot. - let v_stale = B256::with_last_byte(0x99); - let tx_stale = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, v_stale); - let outcome_stale = executor - .run_transaction(&tx_stale) - .expect("stale-nonce system tx must succeed when cfg.disable_nonce_check = true"); - assert!( - outcome_stale.result.is_success(), - "system tx must commit when cfg.disable_nonce_check = true; got {:?}", - outcome_stale.result, - ); - executor.commit_transaction_outcome(outcome_stale).expect("commit stale-nonce tx"); - - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!( - oracle_after, - U256::from_be_bytes(v_stale.0), - "stale-nonce tx must overwrite oracle slot when nonce check is off", - ); -} - -// ============================================================================ -// 5c. cfg.disable_eip3607 honoring for the system address -// ============================================================================ - -/// REX5: with the production-default `cfg.disable_eip3607 = false`, a system tx must be -/// rejected (`RejectCallerWithCode`) when `MEGA_SYSTEM_ADDRESS` has bytecode — the -/// canonical EIP-3607 contract. This is defense-in-depth: prod never deploys code at -/// the system address, but if some future code path or misconfiguration does, the -/// system-tx path hard-fails instead of silently executing against a code-bearing -/// caller. -#[test] -fn test_cfg_disable_eip3607_false_rejects_system_tx_when_system_address_has_code() { - let mut db = MemoryDatabase::default(); - // Plant arbitrary bytecode at MEGA_SYSTEM_ADDRESS so the EIP-3607 check fires. - db.set_account_code(MEGA_SYSTEM_ADDRESS, Bytes::from_static(&[0x00])); - let mut state = State::builder().with_database(db).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0xCD); - let tx = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value); - - let err = executor.run_transaction(&tx).expect_err( - "system tx must be rejected by EIP-3607 when MEGA_SYSTEM_ADDRESS has code and cfg.disable_eip3607 = false", - ); - assert_invalid_tx_contains(&err, "RejectCallerWithCode"); -} - -/// REX5: with `cfg.disable_eip3607 = true`, the same code-bearing-system-address input -/// commits — the cfg-toggle escape hatch lets debug / state-test / replay tooling -/// proceed even if the system address happens to carry bytecode in their fixture. -#[test] -fn test_cfg_disable_eip3607_true_accepts_system_tx_when_system_address_has_code() { - let mut db = MemoryDatabase::default(); - db.set_account_code(MEGA_SYSTEM_ADDRESS, Bytes::from_static(&[0x00])); - let mut state = State::builder().with_database(db).build(); - let mut executor = create_rex5_block_executor( - &mut state, - Rex5Cfg { disable_eip3607: true, ..Default::default() }, - ); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0xCE); - let tx = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value); - let outcome = executor.run_transaction(&tx).expect( - "system tx must succeed when cfg.disable_eip3607 = true even with code at system address", - ); - assert!(outcome.result.is_success()); - executor.commit_transaction_outcome(outcome).expect("commit cfg-disabled-eip3607 tx"); - - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!(oracle_after, U256::from_be_bytes(value.0)); -} - -// ============================================================================ -// 6. Happy path (block executor) -// ============================================================================ - -/// REX5: the canonical happy path — single legitimate system tx commits and updates -/// oracle state. -#[test] -fn test_legacy_system_address_tx_with_correct_nonce_and_chain_id_succeeds() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let mut executor = create_rex5_block_executor(&mut state, Rex5Cfg::default()); - executor.apply_pre_execution_changes().expect("apply pre-execution"); - - let value = B256::with_last_byte(0x55); - let tx = system_tx_with(0, Some(MEGA_CHAIN_ID), ORACLE_SLOT, value); - let outcome = - executor.run_transaction(&tx).expect("happy-path system tx must succeed under REX5"); - assert!(outcome.result.is_success()); - executor.commit_transaction_outcome(outcome).expect("commit happy-path tx"); - - let oracle_after = oracle_storage_at(executor.evm.db_mut(), ORACLE_SLOT); - assert_eq!(oracle_after, U256::from_be_bytes(value.0)); -} - -// ============================================================================ -// 7. Normal user legacy tx is unaffected -// ============================================================================ - -/// Sanity: REX5+ guards apply only to txs whose caller is the system address. A -/// regular EOA legacy tx still goes through the canonical validate path, with normal -/// nonce + chain-id behavior. We test this via `transact_raw` because there's no -/// system-tx interaction to verify here. -#[test] -fn test_normal_user_legacy_tx_is_unaffected() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(REGULAR_CALLER, U256::from(10u64).pow(U256::from(20u64))); // 100 ETH - let recipient = address!("1000000000000000000000000000000000000001"); - db.set_account_balance(recipient, U256::from(1u64)); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::new(context); - - let tx = TxEnv { - caller: REGULAR_CALLER, - kind: TxKind::Call(recipient), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 100_000, - gas_price: 0, - chain_id: Some(MEGA_CHAIN_ID), /* canonical chain id; not validated here because cfg - * defaults */ - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result: Result<_, EVMError> = - alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(result.is_ok(), "normal user legacy tx must still execute successfully under REX5"); - assert!(result.unwrap().result.is_success()); -} - -// ============================================================================ -// 8. Actual OP deposit transaction is unaffected by the REX5 guards -// ============================================================================ - -/// Boundary pin: a genuine `DEPOSIT_TRANSACTION_TYPE` transaction (one that already -/// arrives stamped with a non-zero `source_hash`, not a legacy tx promoted by the Mega -/// pre-handler) must not be intercepted by the REX5 system-address chain-id / nonce -/// guards. The guards key off `sent_from_system_address` (= `caller == system_address`), -/// so a deposit tx whose caller is anyone else passes through `before_run` untouched. -/// This test pins that structural boundary so a future change extending the guards can't -/// silently break OP deposit semantics. -#[test] -fn test_actual_op_deposit_tx_is_unaffected() { - use mega_evm::MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(REGULAR_CALLER, U256::from(10u64).pow(U256::from(20u64))); // 100 ETH - let recipient = address!("1000000000000000000000000000000000000001"); - db.set_account_balance(recipient, U256::from(1u64)); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::new(context); - - // Build a tx that op-revm classifies as deposit-typed via a non-zero source_hash but - // whose caller is NOT the system address — the REX5 system-tx guards must not fire. - let tx_inner = TxEnv { - caller: REGULAR_CALLER, - kind: TxKind::Call(recipient), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 100_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_inner); - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.enveloped_tx = Some(Bytes::new()); - - let result: Result<_, EVMError> = - alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!( - result.is_ok(), - "deposit-typed tx with non-system caller must execute successfully under REX5", - ); - assert!(result.unwrap().result.is_success()); -} - -// ============================================================================ -// Compile-time guard: pin the canonical InvalidTransaction variant set used here. -// ============================================================================ -const _: fn() = || { - let _ = InvalidTransaction::NonceTooLow { tx: 0, state: 0 }; - let _ = InvalidTransaction::NonceTooHigh { tx: 0, state: 0 }; - let _ = InvalidTransaction::InvalidChainId; - let _ = InvalidTransaction::MissingChainId; -}; diff --git a/crates/mega-evm/tests/_pending/src/system/intercept.rs b/crates/mega-evm/tests/_pending/src/system/intercept.rs deleted file mode 100644 index e6fb0a3e0..000000000 --- a/crates/mega-evm/tests/_pending/src/system/intercept.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/intercept.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/intercept.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use alloy_primitives::{Bytes, U256}; - use alloy_sol_types::SolCall; - use revm::{ - bytecode::opcode::{CALLCODE, MSTORE, RETURN}, - context::tx::TxEnvBuilder, - }; - - use crate::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, - }; - - const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; - - /// Pins the `abi_decode`-accepts-trailing-junk behaviour of `alloy-sol-types`'s - /// `decode_sequence::<()>` for parameterless system-contract methods. The - /// interceptor dispatch's selector-only admission relies on this: if a future - /// alloy upgrade rejects trailing bytes, historical replays would diverge from - /// the original `abi_decode` admission and break replay determinism on stable - /// specs. - #[test] - fn test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls() { - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let exact = selector; - let with_junk: Vec = selector.iter().copied().chain(core::iter::once(0xff)).collect(); - let with_pad: Vec = selector.iter().copied().chain([0u8; 32]).collect(); - - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&exact).is_ok(), - "exact 4-byte selector must decode", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_junk).is_ok(), - "current alloy-sol-types accepts selector+1B junk for empty-tuple decode; if this \ - fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_pad).is_ok(), - "current alloy-sol-types accepts selector+32B padding for empty-tuple decode; if \ - this fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - } - - /// Unit test for the explicit call-scheme guard in `frame_init`. - /// - /// A `CALLCODE` to a system contract address with a recognized selector must NOT be - /// intercepted. - /// The scheme guard rejects it before any interceptor sees the call. - /// The call falls through to on-chain bytecode, which reverts with `NotIntercepted()`, - /// leaving the `CALLCODE` success flag as 0. - #[test] - fn test_callcode_scheme_guard_skips_interception() { - let code = BytecodeBuilder::default() - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize (selector length) - .push_number(0_u64) // argsOffset (selector at memory[0]) - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALLCODE) // success flag (0=fail, 1=success) on stack - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let caller = alloy_primitives::address!("0000000000000000000000000000000000300000"); - let contract = alloy_primitives::address!("0000000000000000000000000000000000300001"); - - let mut db = MemoryDatabase::default() - .account_balance(caller, U256::from(1_000_000)) - .account_code(contract, code) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default() - .caller(caller) - .call(contract) - .gas_limit(100_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "outer tx should succeed"); - - let output = result.result.output().expect("should have output"); - let success_flag = U256::from_be_slice(output); - assert_eq!( - success_flag, - U256::ZERO, - "CALLCODE to system contract must not be intercepted — scheme guard must reject it" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/tx.rs b/crates/mega-evm/tests/_pending/src/system/tx.rs deleted file mode 100644 index 4314fa100..000000000 --- a/crates/mega-evm/tests/_pending/src/system/tx.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/tx.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/tx.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::TxKind; - - const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; - const USER: Address = address!("0000000000000000000000000000000000009999"); - const NON_WHITELIST: Address = address!("00000000000000000000000000000000000000ab"); - - /// Builds a legacy (type 0x0) call transaction with the given caller and callee. - fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { - let mut tx = MegaTransaction::default(); - tx.base.tx_type = 0; - tx.base.caller = caller; - tx.base.kind = TxKind::Call(to); - tx - } - - #[test] - fn test_is_system_originated_matches_eip_system_address_caller() { - // The protocol's own pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) - // use `0xff..fe` as caller; it matches regardless of the resolved system address or target. - let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(is_system_originated(&tx, USER)); - } - - #[test] - fn test_is_system_originated_matches_mega_system_tx() { - // Sequencer mega system tx: legacy tx from the system address to a whitelisted contract. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { - // System address calling a non-whitelisted contract is not a mega system tx. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NON_WHITELIST); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_matches_promoted_mega_system_tx() { - // `before_run` promotes a mega system tx to a deposit (stamping the source hash and - // flipping `tx_type()`) *before* `on_new_tx` evaluates the exemption. The promoted shape - // must still be recognized as system-originated. - let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "promotion flips tx_type to deposit"); - assert!( - !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), - "the legacy-typed check no longer matches after promotion", - ); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "but the source-hash branch does"); - } - - #[test] - fn test_is_system_originated_rejects_user_tx() { - let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_user_deposit_tx() { - // Anti-bypass: a user deposit transaction (non-system caller) must NOT be treated as - // system-originated, even though `is_deposit_like_transaction` classifies any deposit as - // deposit-like. Otherwise a user could craft a deposit to escape SALT-scaled storage gas. - let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - // A non-zero deposit source hash makes `tx_type()` report `DEPOSIT_TRANSACTION_TYPE`. - tx.deposit.source_hash = B256::repeat_byte(0x11); - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } -} diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs new file mode 100644 index 000000000..e6349bd93 --- /dev/null +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -0,0 +1,248 @@ +//! The dispatch itself: what admits a call, what an admitted call costs, and what an observer +//! sees of it. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::{ + IMegaAccessControl, IMegaLimitControl, IOracle, ACCESS_CONTROL_ADDRESS, + LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, + MegaEvm, MegaTransactionError, +}; +use revm::{ + bytecode::opcode::{CALL, POP, STOP}, + context::{result::EVMError, ContextTr}, + inspector::Inspector, + interpreter::{interpreter_types::InterpreterTypes, CallInputs, CallOutcome}, +}; + +use crate::common::{call_tx, context, output, run, system_db, with_contract, CONTRACT}; + +const REMAINING_COMPUTE_GAS: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; +const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; + +/// An account that exists and runs no code, so a call to it costs what the `CALL` opcode costs +/// and nothing more. +const PLAIN_TARGET: Address = address!("0x0000000000000000000000000000000000c0ffee"); + +/// Code that calls `to` with `data`, forwarding `gas`, and stops. +fn call_with_gas(to: Address, data: &[u8], gas: u64) -> Bytes { + BytecodeBuilder::default() + .mstore(0x0, data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(to) + .push_number(gas) + .append(CALL) + .append(POP) + .append(STOP) + .build() +} + +/// What a transaction running `code` spends. +fn spent(code: Bytes) -> u64 { + let db = with_contract(code).account_code(PLAIN_TARGET, Bytes::new()); + let result = run(db, call_tx(CONTRACT, [], U256::ZERO)); + assert!(result.result.is_success(), "{:?}", result.result); + result.result.gas().total_gas_spent() +} + +/// An intercepted call costs what the `CALL` opcode that made it costs: the dispatch itself +/// records nothing. +#[test] +fn test_an_intercepted_call_costs_what_a_plain_call_costs() { + let intercepted = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 1_000_000); + let plain = call_with_gas(PLAIN_TARGET, &REMAINING_COMPUTE_GAS, 1_000_000); + assert_eq!( + intercepted.len(), + plain.len(), + "the two programs differ only in the address they call", + ); + assert_eq!(spent(intercepted), spent(plain)); +} + +/// How much gas the caller forwards to an intercepted call does not change what it costs: the +/// forwarded gas comes back in full. +#[test] +fn test_the_forwarded_gas_of_an_intercepted_call_comes_back() { + let low = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 1_000_000); + let high = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 9_000_000); + assert_eq!(low.len(), high.len(), "the two programs differ only in the gas they forward"); + assert_eq!(spent(low), spent(high)); +} + +/// Admission is the four selector bytes: the exact selector and the selector followed by +/// anything are both intercepted, and an input too short to hold one is not. +#[test] +fn test_admission_is_the_selector_alone() { + let intercepted = |data: Vec| { + let result = run(system_db(), call_tx(ACCESS_CONTROL_ADDRESS, &data, U256::ZERO)); + // The interceptor answers `false`; the deployed bytecode reverts. + result.result.is_success() + }; + assert!(intercepted(IS_DISABLED.to_vec()), "the exact selector"); + assert!(intercepted(IS_DISABLED.iter().copied().chain([0xff]).collect()), "one byte after it"); + assert!( + intercepted(IS_DISABLED.iter().copied().chain([0_u8; 32]).collect()), + "a padded argument after it", + ); + assert!(!intercepted(IS_DISABLED[..3].to_vec()), "three bytes are not a selector"); + assert!(!intercepted(Vec::new()), "no input is not a selector"); + assert!(!intercepted(vec![0xde, 0xad, 0xbe, 0xef]), "another selector"); +} + +/// The dispatch reaches a system contract only at its own address: the same selectors sent +/// anywhere else run whatever code is there. +#[test] +fn test_the_address_admits_the_dispatch() { + let db = system_db().account_code(PLAIN_TARGET, Bytes::new()); + let result = run(db, call_tx(PLAIN_TARGET, IS_DISABLED, U256::ZERO)); + assert!(result.result.is_success()); + assert!( + result.result.output().is_none_or(|output| output.is_empty()), + "an account without code answers nothing, so nothing was intercepted", + ); +} + +/// Records which addresses an inspector sees called, and in which order they end. +#[derive(Default)] +struct CallTracker { + calls: Vec
, + call_ends: Vec
, +} + +impl Inspector for CallTracker { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + self.calls.push(inputs.target_address); + None + } + + fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.call_ends.push(inputs.target_address); + } +} + +/// An intercepted call is a call like any other to an observer: the inspector sees it start and +/// end, paired with the frame that made it. +#[test] +fn test_an_inspector_sees_an_intercepted_call() { + let code = call_with_gas(LIMIT_CONTROL_ADDRESS, &REMAINING_COMPUTE_GAS, 1_000_000); + let mut evm = MegaEvm::new(context(with_contract(code))).with_inspector(CallTracker::default()); + let result = + evm.transact_raw(call_tx(CONTRACT, [], U256::ZERO)).expect("the transaction is valid"); + + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(evm.inspector().calls, vec![CONTRACT, LIMIT_CONTROL_ADDRESS]); + assert_eq!(evm.inspector().call_ends, vec![LIMIT_CONTROL_ADDRESS, CONTRACT]); +} + +/// A database error while the system address is read during validation fails the transaction +/// with that error: a database blip must not let the transaction through as a deposit. +#[test] +fn test_a_database_error_reading_the_system_address_fails_the_transaction() { + let mut db = ErrorInjectingDatabase::new(system_db()); + db.fail_on_account = Some(MEGA_SYSTEM_ADDRESS); + + let tx = { + let mut tx = call_tx( + ORACLE_CONTRACT_ADDRESS, + IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(), + U256::ZERO, + ); + tx.0.base.caller = MEGA_SYSTEM_ADDRESS; + tx.0.base.chain_id = + Some(revm::context::CfgEnv::::default().chain_id); + tx + }; + let result: Result<_, EVMError> = + MegaEvm::new(context(db)).transact_raw(tx); + + match result { + Err(EVMError::Database(error)) => { + assert!(format!("{error}").contains(&MEGA_SYSTEM_ADDRESS.to_string()), "{error}"); + } + other => panic!("expected a database error, got: {other:?}"), + } +} + +/// The value policy is the interceptor's, not the account's: a value-bearing transaction to a +/// control contract is refused with `NonZeroTransfer()` before any value moves. +#[test] +fn test_a_value_bearing_transaction_is_refused_before_the_value_moves() { + let db = system_db(); + let mut tx = call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::from(1)); + tx.0.base.caller = crate::common::CALLER; + let result = run(db, tx); + + let revm::context::result::ExecutionResult::Revert { output, .. } = &result.result else { + panic!("the transaction did not revert: {:?}", result.result); + }; + assert_eq!(output[..], IMegaLimitControl::NonZeroTransfer::SELECTOR); + assert!( + result + .state + .get(&LIMIT_CONTROL_ADDRESS) + .is_none_or(|account| account.info.balance.is_zero()), + "the refused value stayed with its sender", + ); +} + +/// A `STATICCALL` to a system contract from inside a static frame is intercepted too: nothing +/// about the answer writes state. +#[test] +fn test_a_nested_static_call_is_intercepted() { + use revm::bytecode::opcode::STATICCALL; + + // An outer contract that STATICCALLs an inner one, which STATICCALLs the system contract. + let inner_code = BytecodeBuilder::default() + .mstore(0x0, IS_DISABLED) + .push_number(32_u64) + .push_number(0x20_u64) + .push_number(4_u64) + .push_number(0_u64) + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u64) + .append(STATICCALL) + .append(POP) + .push_number(32_u64) + .push_number(0x20_u64) + .append(revm::bytecode::opcode::RETURN) + .build(); + let inner = address!("0x0000000000000000000000000000000000300002"); + let outer_code = BytecodeBuilder::default() + .push_number(32_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(inner) + .push_number(1_000_000_u64) + .append(STATICCALL) + .append(POP) + .push_number(32_u64) + .push_number(0_u64) + .append(revm::bytecode::opcode::RETURN) + .build(); + + let db = with_contract(outer_code).account_code(inner, inner_code); + let result = run(db, call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!( + output(&result), + Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( + &false + )), + ); +} + +/// A transaction that reaches no system contract is untouched by the dispatch. +#[test] +fn test_a_transaction_that_touches_no_system_contract_is_untouched() { + let code = BytecodeBuilder::default().append(STOP).build(); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert!(result.result.is_success()); +} diff --git a/crates/mega-evm/tests/system/keyless.rs b/crates/mega-evm/tests/system/keyless.rs index 2ae63e188..5836f4246 100644 --- a/crates/mega-evm/tests/system/keyless.rs +++ b/crates/mega-evm/tests/system/keyless.rs @@ -158,3 +158,22 @@ fn test_the_overhead_does_not_depend_on_the_payload() { assert!(empty >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{empty} is below the fixed overhead"); assert!(payload >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{payload} is below the fixed overhead"); } + +/// Admission is the selector alone here too: a payload too short to hold the arguments the ABI +/// names is still dispatched and charged. What the deployment makes of it is the deployment's +/// to decide — it rejects a transaction it cannot decode. +#[test] +fn test_a_truncated_payload_is_still_dispatched() { + let truncated: Bytes = + KEYLESS_DEPLOY.iter().copied().chain([0_u8; 16]).collect::>().into(); + let dispatched = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated.clone(), U256::ZERO)); + let plain = + run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&truncated), U256::ZERO)); + + let charged = dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent(); + assert!( + charged >= KEYLESS_DEPLOY_OVERHEAD_GAS, + "{charged} is below the overhead a dispatched call pays", + ); +} diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index a8e8e5415..8ff049f36 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -3,6 +3,7 @@ mod common; mod control; +mod dispatch; mod keyless; mod limit_control; mod oracle; diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index f623bc35d..5147d3cf4 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -548,3 +548,71 @@ where let error = evm.execute_transaction(tx).expect_err("the transaction must be rejected"); format!("{error:?}") } + +/// The contract a system transaction calls sees the system address as its caller: the promotion +/// does not put another address in its place. +#[test] +fn test_the_callee_sees_the_system_address_as_its_caller() { + use mega_evm::test_utils::BytecodeBuilder; + use revm::bytecode::opcode::{CALLER as CALLER_OP, MSTORE, RETURN}; + + let returns_caller = BytecodeBuilder::default() + .append(CALLER_OP) + .push_number(0_u64) + .append(MSTORE) + .push_number(32_u64) + .push_number(0_u64) + .append(RETURN) + .build(); + let db = chain_db().account_code(ORACLE_CONTRACT_ADDRESS, returns_caller); + let outcome = run_outcome( + db, + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), Bytes::new(), 0), + ); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + Address::from_word(B256::from_slice(outcome.result.output().unwrap())), + MEGA_SYSTEM_ADDRESS, + ); +} + +/// The account a deposit-like transaction creates for its caller is the transaction's own +/// account: it is part of the transaction body, so it is not a write record of its own. +#[test] +fn test_the_created_caller_is_not_a_write_record() { + let fresh = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x99))); + let existing = run_outcome( + chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), + system_tx(0, B256::with_last_byte(0x99)), + ); + assert!(fresh.result.is_success() && existing.result.is_success()); + assert_eq!( + fresh.usage, existing.usage, + "creating the sender's own account records nothing a transaction with an existing sender \ + does not record", + ); +} + +/// A deposit-like transaction that creates a contract pays for the account it creates for its +/// caller as well as for the contract. +#[test] +fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { + let creator = address!("0x00000000000000000000000000000000000f0007"); + let init_code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); // returns empty code + let deposit = |db: MemoryDatabase| { + let mut tx = legacy_tx(creator, TxKind::Create, init_code.clone(), 0); + tx.0.base.gas_price = 0; + tx.0.deposit.source_hash = B256::repeat_byte(0x55); + run_outcome(db, tx) + }; + let fresh = deposit(chain_db()); + let existing = deposit(chain_db().account_balance(creator, U256::from(1))); + + assert!(fresh.result.is_success(), "{:?}", fresh.result); + assert!(existing.result.is_success(), "{:?}", existing.result); + assert!( + fresh.gas.state > existing.gas.state, + "the created caller costs state gas on top of the created contract", + ); +} From 525f9aa42808f7e0148d59468a6ff3bac43cce76 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:44:02 +0800 Subject: [PATCH 144/201] style: drop the trailing blank line the parked file kept after its port --- .../mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs index 7218fd08d..7d4b1e343 100644 --- a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs +++ b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs @@ -278,4 +278,3 @@ fn test_rex6_sequencer_oracle_tx_succeeds_under_heavy_salt() { // ============================================================================ // 3. Determinism: system tx cost/state independent of bucket capacity // ============================================================================ - From 522814f4bc6d8b8ab093089f4010526ea0602d63 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:44:29 +0800 Subject: [PATCH 145/201] bench(transact): measure the dispatch on the hot path Two workloads, 200 STATICCALLs each: one to a selector MegaAccessControl intercepts, which measures the dispatch and the synthetic answer, and one to a selector it does not, which measures what a call to a system address pays for the address match and the selector peek before the bytecode runs. --- crates/mega-evm/benches/transact.rs | 41 ++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index ea24143ee..e411cb630 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -9,20 +9,27 @@ //! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the //! `SSTORE` wrapper's commit and refund. //! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit. +//! - `intercepted_calls`: 200 `STATICCALL`s to `MegaAccessControl`'s +//! `isVolatileDataAccessDisabled`, which the interceptor answers: the dispatch and the synthetic +//! result, 200 times. +//! - `system_address_misses`: the same 200 calls with a selector the contract does not intercept, +//! so each pays the dispatch's address match and selector peek and then runs the bytecode. #![allow(missing_docs)] use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, MegaContext, MegaEvm, MegaSpecId, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, PUSH0, - PUSH1, SSTORE, STOP, SUB, SWAP1, + ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, POP, + PUSH0, PUSH1, SSTORE, STATICCALL, STOP, SUB, SWAP1, }, context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, inspector::NoOpInspector, @@ -34,6 +41,12 @@ const CALLEE: Address = address!("0x0000000000000000000000000000000000100001"); const RECURSIVE: Address = address!("0x0000000000000000000000000000000000100002"); const WRITER: Address = address!("0x0000000000000000000000000000000000100003"); const LOGGER: Address = address!("0x0000000000000000000000000000000000100004"); +const INTERCEPTED: Address = address!("0x0000000000000000000000000000000000100005"); +const MISSING: Address = address!("0x0000000000000000000000000000000000100006"); + +/// A selector `MegaAccessControl` intercepts, and one it does not. +const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; +const UNKNOWN_SELECTOR: [u8; 4] = [0xde, 0xad, 0xbe, 0xef]; /// Depth the recursive contract reaches. const DEPTH: u8 = 64; @@ -86,6 +99,23 @@ fn logger_code() -> Bytes { code.stop().build() } +/// `STATICCALL`s `MegaAccessControl` with `selector` `REPEAT` times, discarding the answers. +fn system_caller_code(selector: [u8; 4]) -> Bytes { + let mut code = BytecodeBuilder::default().mstore(0x0, selector); + for _ in 0..REPEAT { + code = code + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(4_u64) // argsSize + .push_number(0_u64) // argsOffset + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u64) + .append(STATICCALL) + .append(POP); + } + code.stop().build() +} + fn call_tx(to: Address, data: Bytes, gas_limit: u64) -> OpTransaction { op_transaction(TxEnv { caller: CALLER, @@ -125,7 +155,10 @@ fn bench_transact(c: &mut Criterion) { .account_balance(CALLEE, U256::from(1)) .account_code(RECURSIVE, recursive_code()) .account_code(WRITER, writer_code()) - .account_code(LOGGER, logger_code()); + .account_code(LOGGER, logger_code()) + .account_code(INTERCEPTED, system_caller_code(IS_DISABLED)) + .account_code(MISSING, system_caller_code(UNKNOWN_SELECTOR)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); let cfg = mega_context(db.clone()).cfg().clone(); let mut depth = [0u8; 32]; @@ -136,6 +169,8 @@ fn bench_transact(c: &mut Criterion) { ("deep_calls", call_tx(RECURSIVE, Bytes::from(depth.to_vec()), 30_000_000)), ("storage_writes", call_tx(WRITER, Bytes::new(), 30_000_000)), ("logs", call_tx(LOGGER, Bytes::new(), 30_000_000)), + ("intercepted_calls", call_tx(INTERCEPTED, Bytes::new(), 30_000_000)), + ("system_address_misses", call_tx(MISSING, Bytes::new(), 30_000_000)), ]; let mut group = c.benchmark_group("transact"); From b29eefb71a84b7ea7289e5795e943a458f9be0dd Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:46:48 +0800 Subject: [PATCH 146/201] docs: describe the interceptor dispatch and the system-address transaction The module table's system row, the dispatch order and its four rules as a contract of the common execution layer, a module guide next to the code, and what the crate README says the engine does today. --- AGENTS.md | 31 ++++++++++++-------- crates/mega-evm/README.md | 13 +++++++-- crates/mega-evm/src/system/AGENTS.md | 42 ++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 13 deletions(-) create mode 100644 crates/mega-evm/src/system/AGENTS.md diff --git a/AGENTS.md b/AGENTS.md index 0a63ee8b6..6d1e6686f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,17 +92,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | -| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds now | Filled by | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle, the interceptor scheme guard and the system-transaction promotion in `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` and `MegaLimitControl` interceptors (`control.rs`, `limit_control.rs`); the Oracle's hint path (`oracle.rs`); the `KeylessDeploy` dispatch and its fixed overhead (`keyless/dispatch.rs`) next to the Nick's Method transaction format, validation helpers and error ABI (data only); the system-address transaction and its whitelist (`tx.rs`) | system contract deployment; the oracle and control contracts (the detention and compute-ledger semantics the two control contracts answer with, and the Host's oracle reads); keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | ### How Satin executes today @@ -121,6 +121,10 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` names two hook points that are empty today: system contract deployment and the pre-block system calls. +- Four of the six system contracts answer calls through their interceptors (`system/`). + A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input; an unknown selector is not intercepted and runs the contract's own bytecode. + `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until detention and compute gas fill them in, the Oracle forwards a `sendHint` payload to the node's oracle service, and a `keylessDeploy` transaction is charged its fixed overhead and handed to the keyless rewrite hook. +- The system address may send transactions the protocol pays nothing for (`system/tx.rs`): a legacy transaction from it to a whitelisted contract is validated — the whitelist, the chain id, the nonce, EIP-3607 — and promoted to a deposit, and the account a deposit-like transaction creates for its caller is charged the account-creation state gas once. - The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. ### Contracts of the common execution layer @@ -155,6 +159,11 @@ Every later mechanism plugs into these; a change to one comes back to this layer `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route. The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). The test utilities' inspectors are not declared. +- **The interceptor dispatch.** + Its order is the scheme guard, the address, the selector, then the method's value policy, each step cheaper than the next: `CALLCODE` and `DELEGATECALL` never reach an interceptor, because they run the callee's code in the caller's context; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes; the selector is peeked without materialising the calldata behind it, and is admitted on its four bytes alone, trailing bytes and all. + A selector a contract does not intercept is not intercepted: the call falls through to the deployed bytecode, which reverts with `NotIntercepted()` on the contracts that carry that error, so an unrecognised call cannot succeed silently. + A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names, after the selector matched — so a value-bearing call to an unknown selector still falls through. + An answer is a synthetic frame result and carries the reservoir; an interceptor that lets the frame run may charge it instead, by taking gas off the frame's limit. - **Three ledgers.** `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index bf2f79917..e1d65831c 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -43,8 +43,17 @@ Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecut Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers. `apply_pre_execution_changes` leaves two hook points empty: system contract deployment and the pre-block system calls. -SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. -Until history gas lands, nothing prices a history byte and the schedule's history entry stays at zero. +The six system contracts live at their fixed `0x6342…` addresses, and four of them answer calls through an interceptor instead of running their bytecode. +A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input: `CALLCODE` and `DELEGATECALL` never reach an interceptor, and a selector a contract does not intercept falls through to the deployed bytecode, which reverts with `NotIntercepted()`. +A method that takes no value answers a value-bearing call with `NonZeroTransfer()`. +`MegaAccessControl` and `MegaLimitControl` answer with what the engine knows so far — nothing has switched volatile-data access off, and `remainingComputeGas()` reports the regular gas the call was forwarded — until detention and compute gas fill them in. +The Oracle forwards a `sendHint` payload to the node's oracle service, and a `keylessDeploy` transaction is charged its fixed 100,000 gas and handed to the keyless rewrite hook that native keyless deployment fills in. + +The system address (`MEGA_SYSTEM_ADDRESS`) sends the protocol's own transactions: a legacy transaction from it to a whitelisted contract is validated — the whitelist, the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. +The account such a transaction creates for its caller is charged the account-creation state gas exactly once. + +SALT pricing, history gas, the resource limits, gas detention, system contract deployment and keyless deployment arrive in later changes. +Until history gas lands, nothing prices a history byte and the schedule's history entry stays at zero, and a system transaction's history ledger is zero with it. ## Quick start diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md new file mode 100644 index 000000000..d0a947d94 --- /dev/null +++ b/crates/mega-evm/src/system/AGENTS.md @@ -0,0 +1,42 @@ +# AGENTS.md + +## OVERVIEW +The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, and the system-address transaction. + +## STRUCTURE +- `oracle.rs`: the Oracle's address, code and ABI, and the `sendHint` side effect. +- `timestamp.rs`: the High-Precision Timestamp wrapper's address and code. No interceptor. +- `keyless/`: the `KeylessDeploy` address, code and ABI (`mod.rs`), the dispatch of `keylessDeploy` (`dispatch.rs`), and the data-only helpers of the pre-EIP-155 transaction (`tx.rs`, `error.rs`). +- `control.rs`: `MegaAccessControl`'s address, code, ABI and revert payloads, and its interceptor. +- `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI. No interceptor. +- `intercept.rs`: the dispatch — the address test, the selector peek, the value policy and the shape of an answer. +- `tx.rs`: the system-address transaction, its whitelist and the validation that precedes its promotion to a deposit. + +## KEY PATTERNS +- The dispatch order is: the scheme guard (`MegaEvm::intercept`), the address, the selector, then the method's value policy. Each step is cheaper than the next; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes. +- A selector is admitted on its four bytes alone. Trailing bytes are accepted; an input shorter than four bytes is not a selector and is not admitted. +- An unknown selector is never intercepted: the call falls through to the deployed bytecode, which reverts with `NotIntercepted()` on the contracts that carry that error. +- `CALL` and `STATICCALL` reach the dispatch. `CALLCODE` and `DELEGATECALL` run the callee's code in the caller's context, so they are refused by the scheme guard before any interceptor. +- A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names (`KeylessDeploy` answers `NoEtherTransfer()`). The policy is per method and is applied after the selector matched, so a value-bearing call to an unknown selector still falls through. +- An answer is a `synthetic_call_result`: the forwarded gas untouched, the caller's reservoir carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. +- An interceptor that lets the frame run may charge it instead of answering it, by taking gas off the frame's limit (`KeylessDeploy`'s fixed overhead). That is why the dispatch takes the call inputs mutably. +- The Oracle's `sendHint` is a side effect, not an answer: it forwards the hint and returns `None`, so the contract's own bytecode runs. It forwards only for a call that could deliver it — no value, some gas — and the payload is counted on the transaction's data size before it is decoded. +- The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The whitelist, the chain id, the nonce and EIP-3607 are checked there, each under the configuration switch a user transaction obeys. +- Accounts read during validation are read without warming them, so the transaction pays what any other transaction would pay for its first touch. + +## ANTI-PATTERNS +- Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and a contract's stable error is what a caller decodes. +- Do not materialise calldata before the address and the selector matched. `peek_selector` borrows four bytes; `CallInput::bytes` copies the whole payload. +- Do not build an answer from a bare gas limit. Use `synthetic_call_result`, which carries the reservoir and the upfront-charge flags. +- Do not add a length check to a selector match. Admission is the four bytes. +- Do not accept value on a read-only or control method without saying why in the interceptor and pinning it with a test. +- Do not deploy system bytecode from a literal in this crate; the `mega-system-contracts` crate ships the code and its hash. The timestamp wrapper is the one exception, because the Oracle's address is baked into its code. +- Do not read the system address from a constant in new code once the `SequencerRegistry` is read: the address can be rotated. + +## WHERE TO LOOK +- Add a method to an intercepted contract: the contract's own module, next to the selectors it already answers, and a boundary test per `tests/system/`. +- Change what a call to a system contract costs: `intercept.rs` for the dispatch, the contract's module for what its own method charges. +- Change the system transaction's validation: `tx.rs::validate_and_promote`, which `MegaHandler::validate_env` calls. +- Change what a deposit-like transaction pays for the account it creates: `evm/execution.rs`, where the charge is made in the pre-execution phase. +- Deploy the contracts at a fork, read the rotated system address, or run the pre-block calls: not here yet — system contract deployment and the pre-block system calls own those. From 13abee56143a9d6e0864471df633167f4cd52525 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:53:01 +0800 Subject: [PATCH 147/201] test(satin): pin where a crowded bucket takes Satin away from op-revm The op-revm baseline holds case by case because every case runs without a SALT environment, where every bucket is minimal and the multiplier is one. This is the case that crowds one bucket: the same transaction on the same configuration, and the only thing that moves is the state ledger, by exactly the multiplier. The logs, the output and the resulting state are identical. --- crates/mega-evm/tests/satin/equivalence.rs | 64 +++++++++++++++++++++- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index fa6cb1966..3917e4115 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -1,9 +1,14 @@ -//! `MegaEvm` on Satin adds nothing to op-revm yet. +//! What `MegaEvm` on Satin adds to op-revm, and where it adds nothing. //! //! The same transaction on the same `CfgEnv`, block and L1 info must produce the same result //! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and -//! the resulting state. Once later changes add `MegaETH` behavior (SALT pricing, history gas, -//! limits), these cases stay the baseline that shows where the two diverge on purpose. +//! the resulting state. Once later changes add `MegaETH` behavior (history gas, limits), these +//! cases stay the baseline that shows where the two diverge on purpose. +//! +//! One difference is here already: SALT pricing multiplies a state gas charge by the capacity of +//! the bucket it lands in, and op-revm has no SALT to read. Every case above runs without a SALT +//! environment, where every bucket is minimal and the multiplier is one, so the baseline holds; +//! the last case crowds one bucket and pins what the difference is and how large. use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, TxKind, U256}; @@ -268,3 +273,56 @@ fn test_invalid_transaction_matches_op_revm() { assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); assert!(format!("{mega_error:?}").contains("CallerGasLimitMoreThanBlock"), "{mega_error:?}"); } + +/// Where Satin leaves op-revm on purpose: a state gas charge in a crowded SALT bucket. +/// +/// The transaction, the configuration, the block and the database are the ones +/// [`test_sstore_matches_op_revm`] uses, and every field of the outcome still agrees — except the +/// state ledger, which Satin multiplies by the bucket's capacity in minimum buckets. op-revm has +/// no SALT to read, so it charges the schedule's entry, which is Satin's own answer at the +/// minimum bucket. +#[test] +fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { + use crate::salt::{crowded_slot, minimal_envs, salt_context}; + + const MULTIPLIER: u64 = 8; + if runs_at_measurement_prices() { + return; + } + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + + let envs = crowded_slot(minimal_envs(), CALLEE, U256::ZERO, MULTIPLIER); + let ctx = salt_context(db.clone(), envs).with_block(block()); + let cfg = ctx.cfg().clone(); + let mega = MegaEvm::new(ctx).transact(OpTx(op_transaction(tx.clone()))).unwrap(); + let op_ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let op = OpEvm::new(op_ctx, NoOpInspector).transact(op_transaction(tx)).unwrap(); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success() && op.result.is_success()); + + // The one difference, and its exact size. + assert_eq!(op.result.gas().state_gas_spent_final(), SLOT_STATE_GAS); + assert_eq!(mega.result.gas().state_gas_spent_final(), SLOT_STATE_GAS * MULTIPLIER); + assert_eq!( + mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(), + SLOT_STATE_GAS * (MULTIPLIER - 1), + "the extra state gas is the whole of the extra spend", + ); + + // Everything the transaction did is the same: the fees are zero here, so the multiplier + // moves the gas ledgers and nothing else. + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result.output(), op.result.output(), "output"); + assert_eq!(mega.state, op.state, "state"); +} From 257e2d6dfb0231709354e80de74fde2567ce4b8a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:55:04 +0800 Subject: [PATCH 148/201] test(system): pin that a promoted transaction is not promoted twice A transaction that already carries the system source hash has skipped the validation the promotion runs, so the engine refuses it. A block's transactions are decoded from their legacy encoding, which carries no source hash, so the shape only reaches the engine from a caller that built it. --- crates/mega-evm/tests/system/system_tx.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 5147d3cf4..b318c41af 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -616,3 +616,17 @@ fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { "the created caller costs state gas on top of the created contract", ); } + +/// A transaction that already carries the system source hash is not executed as one: the +/// promotion is the engine's own, made once per execution, and a transaction that arrives +/// promoted has skipped the validation that precedes it. +/// +/// A block's transactions are decoded from their legacy encoding, which carries no source hash, +/// so this is the shape a caller hands the engine directly, not one a block holds. +#[test] +fn test_a_transaction_that_arrives_promoted_is_refused() { + let mut tx = system_tx(0, B256::with_last_byte(0xaf)); + tx.0.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + let refused = rejection(chain_db(), tx); + assert!(refused.contains("whitelist"), "{refused}"); +} From 6900963263c4618cc4131c0a42d0180f71a26872 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:58:02 +0800 Subject: [PATCH 149/201] test(system): pin that the two contracts without an interceptor run their code A call to the timestamp wrapper or to the SequencerRegistry reaches no interceptor, whatever its selector, its value or its call scheme: their dispatchers refuse an unknown selector, where a call to an account without code would succeed. --- crates/mega-evm/tests/system/dispatch.rs | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index e6349bd93..300b043fd 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -246,3 +246,36 @@ fn test_a_transaction_that_touches_no_system_contract_is_untouched() { let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); assert!(result.result.is_success()); } + +/// The two system contracts without an interceptor run their bytecode, whatever the call +/// carries and whichever scheme makes it: an unknown selector reverts in their dispatcher, where +/// a call to an account without code would succeed. +#[test] +fn test_the_contracts_without_an_interceptor_run_their_bytecode() { + use mega_evm::system::{HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}; + use revm::bytecode::opcode::{CALLCODE, DELEGATECALL, STATICCALL}; + + for address in [HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, SEQUENCER_REGISTRY_ADDRESS] { + // As a transaction, with a selector neither contract knows and with none at all. + for data in [vec![0xde, 0xad, 0xbe, 0xef], Vec::new()] { + let result = run(system_db(), call_tx(address, &data, U256::ZERO)); + assert!(!result.result.is_success(), "{address} answered {data:?} without its code"); + } + + // Through every call scheme, including the two the scheme guard refuses. + for scheme in [CALL, STATICCALL, CALLCODE, DELEGATECALL] { + let code = crate::common::calls_with(scheme, address, &[0xde, 0xad, 0xbe, 0xef], 0); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, _) = crate::common::split_outcome(&outcome); + assert!(!status, "{address} answered scheme {scheme:#x} without its code"); + } + + // A call that carries value is the bytecode's to refuse. + let code = crate::common::calls_with(CALL, address, &[0xde, 0xad, 0xbe, 0xef], 1); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, _) = crate::common::split_outcome(&outcome); + assert!(!status, "{address} took value without its code"); + } +} From e38c99e6e9c437d749f09c0470abce17ea6a2b24 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 13:59:24 +0800 Subject: [PATCH 150/201] style(evm): take the frame init mutably in the signature --- crates/mega-evm/src/evm/execution.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index b53bb4fdd..441be53ff 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -264,7 +264,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { if let Some(result) = answer_before_building(&mut self.inner.ctx, &frame_init)? { self.inner.ctx.additional_limit.push_empty_frame(); return Ok(ItemOrResult::Result(result)); } - let mut frame_init = frame_init; if let Some(result) = self.intercept(&mut frame_init) { self.inner.ctx.additional_limit.push_empty_frame(); return Ok(ItemOrResult::Result(result)); From 0f4ce2be6893fe191eee18e2419f7559af856eb0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:00:37 +0800 Subject: [PATCH 151/201] test(system): say what the second run of the caller-charge test measures --- crates/mega-evm/tests/system/system_tx.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index b318c41af..f1fa05d43 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -442,10 +442,10 @@ fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { // A system transaction whose sender does not exist yet creates it, for the same charge. let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); assert!(created.result.is_success(), "{:?}", created.result); + // The same transaction from a sender that already exists: what it pays is the slot it + // writes, and nothing for its own account. let slot_charge = run_outcome( - chain_db() - .account_nonce(MEGA_SYSTEM_ADDRESS, 0) - .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), + chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)), system_tx(0, B256::with_last_byte(0x77)), ) .gas From 711c9206f85b1b81d2209bdddb86893020a74f7e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:02:44 +0800 Subject: [PATCH 152/201] test(satin): pin where the engine now diverges from op-revm Three cases join the baseline: a call a system contract interceptor answers, where op-revm runs the contract's bytecode; a legacy transaction from the system address, which Satin runs as a fee-free deposit and op-revm refuses for want of a balance; and a deposit whose sender does not exist yet, whose account Satin charges for and op-revm does not. --- crates/mega-evm/tests/satin/equivalence.rs | 116 ++++++++++++++++++++- 1 file changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index fa6cb1966..f2f8b8b1a 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -1,9 +1,11 @@ -//! `MegaEvm` on Satin adds nothing to op-revm yet. +//! What `MegaEvm` on Satin adds to op-revm, and what it does not. //! -//! The same transaction on the same `CfgEnv`, block and L1 info must produce the same result +//! An ordinary transaction on the same `CfgEnv`, block and L1 info must produce the same result //! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and -//! the resulting state. Once later changes add `MegaETH` behavior (SALT pricing, history gas, -//! limits), these cases stay the baseline that shows where the two diverge on purpose. +//! the resulting state. The cases at the end are the ones that diverge on purpose — the system +//! contract interceptors and the system-address transaction — and they pin both sides, so a +//! divergence is never silently absorbed. Later changes (SALT pricing, history gas, limits) add +//! their own. use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, TxKind, U256}; @@ -268,3 +270,109 @@ fn test_invalid_transaction_matches_op_revm() { assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); assert!(format!("{mega_error:?}").contains("CallerGasLimitMoreThanBlock"), "{mega_error:?}"); } + +/* Where the two diverge on purpose */ + +/// A call to a system contract is answered by the engine, where op-revm runs the contract's +/// bytecode and gets its `NotIntercepted()` revert. +#[test] +fn test_an_intercepted_call_diverges_from_op_revm() { + use alloy_sol_types::{SolCall, SolError}; + use mega_evm::system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}; + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(ACCESS_CONTROL_ADDRESS), + data: IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR.into(), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert_eq!( + mega.result.output().cloned().unwrap_or_default(), + IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&false), + "the interceptor answers", + ); + assert!(!op.result.is_success(), "op-revm runs the bytecode"); + assert_eq!( + op.result.output().cloned().unwrap_or_default()[..], + IMegaAccessControl::NotIntercepted::SELECTOR, + ); +} + +/// A legacy transaction from the system address is a fee-free deposit on Satin, where op-revm +/// sees an ordinary transaction and refuses it for want of a balance to pay with. +#[test] +fn test_a_system_address_transaction_diverges_from_op_revm() { + use mega_evm::system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}; + + let db = MemoryDatabase::default() + .account_code(ORACLE_CONTRACT_ADDRESS, mega_evm::system::ORACLE_CONTRACT_CODE); + let tx = TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + data: alloy_sol_types::SolCall::abi_encode(&IOracle::getSlotCall { slot: U256::ZERO }) + .into(), + gas_limit: 1_000_000, + gas_price: 1_000, + chain_id: Some(1), + ..Default::default() + }; + let (mut mega, mut op, cfg) = both_evms(db, block()); + assert_satin_cfg(&cfg); + + let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).expect("Satin accepts it"); + assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); + assert!( + mega_outcome + .state + .get(&MEGA_SYSTEM_ADDRESS) + .is_none_or(|account| account.info.balance.is_zero()), + "the sender pays no fee and needed no balance", + ); + + let error = op.transact(op_transaction(tx)).expect_err("op-revm wants a fee"); + assert!(format!("{error:?}").contains("LackOfFundForMaxFee"), "{error:?}"); +} + +/// A deposit-like transaction whose sender does not exist yet pays the state gas of the account +/// it creates for it; op-revm creates the same account and charges nothing for it. +#[test] +fn test_the_created_deposit_caller_diverges_from_op_revm() { + use alloy_primitives::B256; + + let sender = address!("0x00000000000000000000000000000000000f0001"); + let tx = TxEnv { + caller: sender, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + gas_price: 0, + ..Default::default() + }; + let deposit = |tx: TxEnv| { + let mut tx = op_transaction(tx); + tx.deposit.source_hash = B256::repeat_byte(0x11); + tx + }; + let (mut mega, mut op, cfg) = both_evms(MemoryDatabase::default(), block()); + assert_satin_cfg(&cfg); + + let mega_outcome = mega.transact(OpTx(deposit(tx.clone()))).unwrap(); + let op_outcome = op.transact(deposit(tx)).unwrap(); + + assert!(mega_outcome.result.is_success() && op_outcome.result.is_success()); + assert!( + mega_outcome.result.gas().state_gas_spent_final() > 0, + "Satin charges the account the deposit creates for its sender", + ); + assert_eq!( + op_outcome.result.gas().state_gas_spent_final(), + 0, + "op-revm charges nothing for it", + ); +} From 6b20b2341cd2621d0cdc4d6a81287f46d3623bee Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:04:12 +0800 Subject: [PATCH 153/201] test(system): pin that a revert does not take the hint bytes back The hint has left the machine by the time the frame that sent it fails, so the bytes it cost are the transaction's and stay counted. --- crates/mega-evm/tests/system/oracle.rs | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index cbe7db35b..fb08d92cd 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -189,3 +189,36 @@ fn test_reading_a_slot_runs_the_bytecode() { B256::from(U256::from(42)), ); } + +/// A hint cannot be un-sent, so the bytes it cost stay counted even when the frame that sent it +/// reverts and takes its writes back. +#[test] +fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { + use revm::bytecode::opcode::{POP, PUSH0, REVERT}; + + let data = send_hint(b"a hint that was sent"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(200_000_u64) + .append(CALL) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(!result.result.is_success(), "the frame that sent the hint reverted"); + assert_eq!(hints.len(), 1, "the hint reached the service before the revert"); + assert_eq!( + usage.data_size, + data.len() as u64, + "the bytes stay counted: a revert cannot take the hint back", + ); +} From dae3c4f0c758ed8ef57b692f0444e15ebb4ce45c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:40:46 +0800 Subject: [PATCH 154/201] docs(system): name the keylessDeploy ABI the contract declares --- crates/mega-evm/src/system/keyless/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index 1fdb4f4b2..e0b33e70b 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -1,7 +1,7 @@ //! The `KeylessDeploy` system contract, and keyless deployment (Nick's Method): the transaction //! format, its validation rules and the error ABI. //! -//! `keylessDeploy(bytes,uint64)` is intercepted; every other selector falls through to the +//! `keylessDeploy(bytes,uint256)` is intercepted; every other selector falls through to the //! deployed bytecode, which reverts with `NotIntercepted()`. What the interceptor does today is //! the dispatch and the fixed compute charge; turning the deployment into a native creation //! belongs to native keyless deployment. From 472852299b24215c301046fc2fd4ceffe0daef95 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:42:42 +0800 Subject: [PATCH 155/201] fix(system): word the system-address refusal as the rule it states --- crates/mega-evm/src/system/tx.rs | 12 ++++++++---- crates/mega-evm/tests/system/system_tx.rs | 24 ++++++++++++++++++++--- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index 8c75cf119..d6e620440 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -119,9 +119,11 @@ pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bo /// chain still wants are made here (see the module documentation), each under the configuration /// switch a user transaction obeys. /// -/// A transaction from the system address that is not a system transaction — it creates a -/// contract, or calls a contract that is not whitelisted — is rejected outright: the sequencer -/// has no business sending it, and promoting it would give it the deposit path's exemptions. +/// A transaction from the system address that is not a system transaction is rejected outright: +/// the sequencer has no business sending it, and promoting it would give it the deposit path's +/// exemptions. That covers a creation, a call to a contract that is not on the whitelist, and +/// any shape that is not a legacy transaction — an EIP-1559 one, or one that already carries a +/// source hash, which has skipped the validation the promotion runs. pub(crate) fn validate_and_promote( ctx: &mut MegaContext, system_address: Address, @@ -136,7 +138,9 @@ where } if !is_mega_system_transaction_with(ctx.tx(), system_address) { return Err(ERROR::from_string( - "the callee of a system transaction is not on the whitelist".to_string(), + "a transaction from the system address must be a legacy call to a whitelisted \ + contract" + .to_string(), )); } diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index f1fa05d43..2d7a1409f 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -28,6 +28,11 @@ const CHAIN_ID: u64 = 4326; /// A contract that is not on the whitelist. const OFF_WHITELIST: Address = address!("0x00000000000000000000000000000000000dead1"); +/// The refusal every transaction from the system address that is not a system transaction gets: +/// the rule it broke, whichever way it broke it. +const NOT_A_SYSTEM_TRANSACTION: &str = + "a transaction from the system address must be a legacy call to a whitelisted contract"; + /// The Oracle's slot the system transactions write. const ORACLE_SLOT: U256 = U256::ZERO; @@ -220,7 +225,7 @@ fn test_the_whitelist_is_what_the_system_address_may_call() { let off_whitelist = legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); let refused = rejection(chain_db(), off_whitelist); - assert!(refused.contains("whitelist"), "{refused}"); + assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); let creation = legacy_tx( MEGA_SYSTEM_ADDRESS, @@ -229,7 +234,17 @@ fn test_the_whitelist_is_what_the_system_address_may_call() { 0, ); let refused = rejection(chain_db(), creation); - assert!(refused.contains("whitelist"), "{refused}"); + assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); +} + +/// A transaction from the system address that is not a legacy one is refused whatever it calls: +/// the sequencer builds the legacy shape, and the promotion is what turns it into a deposit. +#[test] +fn test_a_non_legacy_transaction_from_the_system_address_is_refused() { + let mut tx = system_tx(0, B256::with_last_byte(0xaf)); + tx.0.base.tx_type = 2; // EIP-1559 + let refused = rejection(chain_db(), tx); + assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); } /// The whitelist holds for the system address alone: anyone else may call anything, and pays @@ -628,5 +643,8 @@ fn test_a_transaction_that_arrives_promoted_is_refused() { let mut tx = system_tx(0, B256::with_last_byte(0xaf)); tx.0.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; let refused = rejection(chain_db(), tx); - assert!(refused.contains("whitelist"), "{refused}"); + assert!( + refused.contains(NOT_A_SYSTEM_TRANSACTION), + "the refusal names the rule, not the whitelist alone: {refused}", + ); } From 17f9656439f301c1fd0fd9a7dc6fe8cdd0135453 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:43:55 +0800 Subject: [PATCH 156/201] test(system): pin the hint that crosses the transaction's data-size limit --- crates/mega-evm/tests/system/oracle.rs | 80 +++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index fb08d92cd..92be42a8e 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -5,11 +5,12 @@ use core::convert::Infallible; use alloy_evm::Evm; use alloy_primitives::{Bytes, B256, U256}; -use alloy_sol_types::SolCall; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ system::{IOracle, ORACLE_CONTRACT_ADDRESS}, test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - ExternalEnvs, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, + MegaHaltReason, MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, RecordedHint, TestExternalEnvs, }; use revm::{ @@ -35,6 +36,17 @@ fn run_with_oracle( db: MemoryDatabase, tx: MegaTransaction, ) -> (ResultAndState, Vec, LimitUsage) { + let (outcome, hints) = run_with_oracle_under(db, tx, EvmTxRuntimeLimits::no_limits()); + (outcome.result_and_state, hints, outcome.usage) +} + +/// [`run_with_oracle`] under `limits`, returning the whole outcome: the stop a crossed limit +/// latched is what the outcome reports, not the output alone. +fn run_with_oracle_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> (MegaTransactionOutcome, Vec) { let envs = TestExternalEnvs::::new(); let ctx = MegaContext::new_with_external_envs( db, @@ -42,11 +54,10 @@ fn run_with_oracle( ExternalEnvs::from(envs.clone()), ) .with_block(block()) - .with_chain(zero_fee_l1_block_info()); - let mut evm = MegaEvm::new(ctx); - let result = evm.transact_raw(tx).expect("the transaction is valid"); - let usage = evm.ctx().additional_limit().usage(); - (result, envs.recorded_hints(), usage) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(limits); + let outcome = MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is valid"); + (outcome, envs.recorded_hints()) } /// A `sendHint` transaction reaches the oracle service with the caller, the topic and the @@ -222,3 +233,58 @@ fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { "the bytes stay counted: a revert cannot take the hint back", ); } + +/// A payload that does not fit in what is left of the transaction's data-size limit is not +/// forwarded, and the crossing stops the transaction: the hint's bytes are counted before the +/// payload is decoded, so the limit is crossed before the frame the call would have started. +/// +/// The bytes stay counted — the crossing is what the transaction is stopped for, and the usage +/// is what shows it — and the transaction settles as a revert carrying the stop's own data. +#[test] +fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { + let data = send_hint(b"a hint one byte too long"); + let limit = data.len() as u64 - 1; + let (outcome, hints) = run_with_oracle_under( + system_db(), + call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + + assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); + assert_eq!( + outcome.usage.data_size, + data.len() as u64, + "the whole payload is counted: the count is what crossed the limit", + ); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: data.len() as u64, + frame_local: false, + }), + ); + assert_eq!( + outcome.result.output().cloned().unwrap_or_default(), + Bytes::from(MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.abi_encode()), + "the transaction settles as the stop's revert", + ); +} + +/// The same payload at exactly the transaction's limit is forwarded: the limit is crossed only +/// above it. +#[test] +fn test_a_hint_at_the_data_size_limit_is_forwarded() { + let data = send_hint(b"a hint one byte too long"); + let (outcome, hints) = run_with_oracle_under( + system_db(), + call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data.len() as u64), + ); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(hints.len(), 1); + assert_eq!(outcome.usage.data_size, data.len() as u64); + assert_eq!(outcome.limit_exceeded, None); +} From ada7b23fdd0f0de485075f540dce1062c9deee3c Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:44:13 +0800 Subject: [PATCH 157/201] style(system): drop the import the oracle tests no longer use --- crates/mega-evm/tests/system/oracle.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 92be42a8e..5a7a635b7 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -3,7 +3,6 @@ use core::convert::Infallible; -use alloy_evm::Evm; use alloy_primitives::{Bytes, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ From 680ebf5702fa63f17b6fec2aaa8f6baa9c09dc95 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:44:32 +0800 Subject: [PATCH 158/201] fix(external): fail a capacity below the minimum bucket closed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A SALT bucket holds at least `MIN_BUCKET_SIZE` entries, so a backend reporting less is a broken backend rather than a cheap bucket. The multiplier rounded such a report up to one, which handed a misreporting backend the cheapest price there is; it is now a failed lookup of its own (`BucketError::BelowMinimum`) and fails the transaction the way an unanswerable query does. `BucketMultipliers` reports the two apart — the environment could not answer, or it answered something a bucket cannot hold — and caches neither. The minimum capacity itself is still a bucket and still prices at one. --- crates/mega-evm/src/evm/context.rs | 10 +- crates/mega-evm/src/external/AGENTS.md | 3 +- crates/mega-evm/src/external/gas.rs | 123 ++++++++++++++++---- crates/mega-evm/src/external/salt.rs | 6 + crates/mega-evm/tests/satin/salt_failure.rs | 47 +++++++- 5 files changed, 158 insertions(+), 31 deletions(-) diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index e83953942..644e49c5f 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -13,7 +13,7 @@ use revm::{ }; use crate::{ - constants, evm::schedule::satin_gas_params, AdditionalLimit, BlockHashRecord, + constants, evm::schedule::satin_gas_params, AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, }; @@ -165,11 +165,13 @@ impl MegaContext { /// /// Every account-scoped EIP-8037 state gas charge on `address` is scaled by it. The bucket is /// read from the transaction's [`SaltEnv`] the first time the transaction asks for it and - /// from [`BucketMultipliers`] afterwards. + /// from [`BucketMultipliers`] afterwards. A bucket the environment could not report, and one + /// it reported below the minimum capacity a bucket can hold, both fail + /// ([`BucketError`](crate::BucketError)). pub fn account_bucket_multiplier( &mut self, address: Address, - ) -> Result::Error> { + ) -> Result::Error>> { self.bucket_multipliers.account(&self.external_envs.salt_env, address) } @@ -180,7 +182,7 @@ impl MegaContext { &mut self, address: Address, key: StorageKey, - ) -> Result::Error> { + ) -> Result::Error>> { self.bucket_multipliers.slot(&self.external_envs.salt_env, address, key) } diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 21b2540db..761ee3097 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -18,7 +18,8 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - `EmptyExternalEnv` must stay deterministic and side-effect free. - A bucket's capacity is read once per transaction and answered from `BucketMultipliers` afterwards, so a state gas charge and the refill that undoes it are priced at the same capacity by construction. - `BucketMultipliers` does not hold the environment; it takes a `&SaltEnv` per call, so there is no second copy of it and no `Clone` bound on the engine's environment types. -- A capacity below `MIN_BUCKET_SIZE` — which a bucket cannot have — prices at `m = 1`, never at `m = 0`: no environment can make state gas free. +- `MIN_BUCKET_SIZE` is the smallest capacity a backend may report. + A report below it is a broken backend, not a cheap bucket: it is a failed lookup (`BucketError::BelowMinimum`) and fails the transaction, rather than being rounded up to `m = 1` or priced at `m = 0`. ## ANTI-PATTERNS - Do not query live chain state directly from opcode handlers. diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs index 564f15900..f09362e17 100644 --- a/crates/mega-evm/src/external/gas.rs +++ b/crates/mega-evm/src/external/gas.rs @@ -10,12 +10,52 @@ //! that prices state gas runs on every state charge and every refill of one, so the reads are //! cached here: [`BucketMultipliers`] queries a bucket once per transaction and answers every //! later charge on that bucket from the cache. +//! +//! [`MIN_BUCKET_SIZE`] is the smallest capacity a backend may report. A capacity below it is a +//! broken backend rather than a cheap bucket, and is treated as a failed lookup +//! ([`BucketError::BelowMinimum`]) rather than rounded up to the minimum: a report the engine +//! cannot make sense of must not become a price nobody chose. + +use core::fmt; use alloy_primitives::{map::Entry, Address}; use revm::primitives::{HashMap, StorageKey}; use crate::{BucketId, SaltEnv, MIN_BUCKET_SIZE}; +/// Why a SALT bucket's multiplier could not be established. +/// +/// Both variants fail the transaction the same way: the pricing hook reports nothing and records +/// the cause, and the charge site bails out. They are kept apart because they say different +/// things about the backend — one could not answer, the other answered something a bucket cannot +/// hold. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BucketError { + /// The SALT environment could not report the bucket's capacity. + Env(E), + /// The SALT environment reported a capacity below [`MIN_BUCKET_SIZE`], which is the smallest + /// a bucket can hold. + BelowMinimum { + /// The bucket that was asked for. + bucket: BucketId, + /// The capacity the environment reported for it. + capacity: u64, + }, +} + +impl fmt::Display for BucketError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Env(error) => write!(f, "{error}"), + Self::BelowMinimum { bucket, capacity } => write!( + f, + "bucket {bucket} reports capacity {capacity}, below the minimum bucket of \ + {MIN_BUCKET_SIZE}", + ), + } + } +} + /// The SALT bucket multipliers the running transaction has looked up. /// /// One entry per bucket the transaction has priced a charge in. It is cleared with the rest of @@ -38,25 +78,28 @@ impl BucketMultipliers { } /// The multiplier a bucket of `capacity` entries prices with: `capacity / MIN_BUCKET_SIZE`, - /// never below one. + /// or nothing when that capacity is below the minimum a bucket can hold. /// - /// A bucket cannot hold fewer entries than the minimum, so the floor only guards against an - /// environment that reports one that does: without it such a report would price every state - /// charge in that bucket at zero, which is the one answer that must not be reachable from - /// outside the engine. + /// A bucket cannot hold fewer entries than the minimum, so a report that one does is a broken + /// backend. Rounding it up to the minimum would let a misreport pass as the cheapest price + /// there is; reporting nothing fails the transaction instead, the way any other unanswerable + /// lookup does. The one answer that must not be reachable from outside the engine — + /// `m = 0`, which prices every state charge in the bucket at zero — is neither. #[inline] - pub const fn for_capacity(capacity: u64) -> u64 { - let multiplier = capacity / MIN_BUCKET_SIZE as u64; - if multiplier == 0 { - 1 - } else { - multiplier + pub const fn for_capacity(capacity: u64) -> Option { + match capacity / MIN_BUCKET_SIZE as u64 { + 0 => None, + multiplier => Some(multiplier), } } /// The multiplier of the bucket `account`'s own state lives in. #[inline] - pub fn account(&mut self, salt_env: &S, account: Address) -> Result { + pub fn account( + &mut self, + salt_env: &S, + account: Address, + ) -> Result> { self.of_bucket(salt_env, S::bucket_id_for_account(account)) } @@ -67,18 +110,27 @@ impl BucketMultipliers { salt_env: &S, address: Address, key: StorageKey, - ) -> Result { + ) -> Result> { self.of_bucket(salt_env, S::bucket_id_for_slot(address, key)) } /// The multiplier of `bucket`, read from `salt_env` the first time this transaction asks for /// it and from the cache afterwards. + /// + /// Only a multiplier is cached, so a bucket whose capacity could not be turned into one is + /// asked for again rather than remembered as anything. #[inline] - fn of_bucket(&mut self, salt_env: &S, bucket: BucketId) -> Result { + fn of_bucket( + &mut self, + salt_env: &S, + bucket: BucketId, + ) -> Result> { match self.cached.entry(bucket) { Entry::Occupied(entry) => Ok(*entry.get()), Entry::Vacant(entry) => { - let multiplier = Self::for_capacity(salt_env.get_bucket_capacity(bucket)?); + let capacity = salt_env.get_bucket_capacity(bucket).map_err(BucketError::Env)?; + let multiplier = Self::for_capacity(capacity) + .ok_or(BucketError::BelowMinimum { bucket, capacity })?; Ok(*entry.insert(multiplier)) } } @@ -125,25 +177,45 @@ mod tests { fn test_the_multiplier_is_the_capacity_in_minimum_buckets() { let min = MIN_BUCKET_SIZE as u64; for factor in [1, 2, 8, 1_000, u32::MAX as u64] { - assert_eq!(BucketMultipliers::for_capacity(min * factor), factor, "{factor}x"); + assert_eq!(BucketMultipliers::for_capacity(min * factor), Some(factor), "{factor}x"); } // A capacity between two whole multiples rounds down to the lower one: a bucket pays for // the minimum buckets it has filled, not for the one it has started. - assert_eq!(BucketMultipliers::for_capacity(min * 2 + min / 2), 2); - assert_eq!(BucketMultipliers::for_capacity(u64::MAX), u64::MAX / min); + assert_eq!(BucketMultipliers::for_capacity(min * 2 + min / 2), Some(2)); + assert_eq!(BucketMultipliers::for_capacity(u64::MAX), Some(u64::MAX / min)); } - /// A capacity below the minimum — which a bucket cannot have — still prices at one rather - /// than at zero, so no environment can make state gas free. + /// A capacity below the minimum is a capacity no bucket can have, so it is reported as a + /// failed lookup rather than rounded up to the minimum: a backend that misreports must fail + /// the transaction, not hand it the cheapest price there is. #[test] - fn test_a_capacity_below_the_minimum_still_multiplies_by_one() { + fn test_a_capacity_below_the_minimum_is_a_failed_lookup() { for capacity in [0, 1, MIN_BUCKET_SIZE as u64 - 1] { - assert_eq!(BucketMultipliers::for_capacity(capacity), 1, "capacity {capacity}"); + assert_eq!(BucketMultipliers::for_capacity(capacity), None, "capacity {capacity}"); } let bucket = account_bucket(ACCOUNT); let env = Env::new().with_bucket_capacity(bucket, 0); - assert_eq!(BucketMultipliers::default().account(&env, ACCOUNT), Ok(1)); + let mut cache = BucketMultipliers::default(); + assert_eq!( + cache.account(&env, ACCOUNT), + Err(BucketError::BelowMinimum { bucket, capacity: 0 }), + ); + assert_eq!(cache.cached_buckets().len(), 0, "nothing was cached for it"); + } + + /// The two failures read differently, so a node can tell a backend that could not answer from + /// one that answered something impossible. + #[test] + fn test_the_two_bucket_failures_say_what_went_wrong() { + let unreachable: BucketError = BucketError::Env("salt backend unreachable".into()); + assert_eq!(unreachable.to_string(), "salt backend unreachable"); + + let below: BucketError = BucketError::BelowMinimum { bucket: 7, capacity: 3 }; + assert_eq!( + below.to_string(), + format!("bucket 7 reports capacity 3, below the minimum bucket of {MIN_BUCKET_SIZE}"), + ); } /// A crowded bucket scales every charge on it, and an account and a slot are read through @@ -203,7 +275,10 @@ mod tests { .with_failing_bucket(bucket, "salt backend unreachable".into()); let mut cache = BucketMultipliers::default(); - assert_eq!(cache.account(&env, ACCOUNT), Err("salt backend unreachable".into())); + assert_eq!( + cache.account(&env, ACCOUNT), + Err(BucketError::Env("salt backend unreachable".into())), + ); assert_eq!(cache.cached_buckets().len(), 0, "a failed lookup caches nothing"); // It is not cached either, so the next charge asks again. assert!(cache.account(&env, ACCOUNT).is_err()); diff --git a/crates/mega-evm/src/external/salt.rs b/crates/mega-evm/src/external/salt.rs index 77dc611df..b90621a7e 100644 --- a/crates/mega-evm/src/external/salt.rs +++ b/crates/mega-evm/src/external/salt.rs @@ -24,6 +24,9 @@ pub const MIN_BUCKET_SIZE_BITS: usize = 8; /// Buckets hold accounts or storage slots and can grow beyond this size. The gas cost /// multiplier is calculated as `capacity / MIN_BUCKET_SIZE`, so a bucket at minimum /// capacity has a 1x multiplier. +/// +/// This is also the smallest capacity a [`SaltEnv`] may report: a smaller answer is one no bucket +/// can have, and is treated as a failed lookup rather than as the cheapest bucket there is. pub const MIN_BUCKET_SIZE: usize = 1 << MIN_BUCKET_SIZE_BITS; /// Interface for SALT bucket capacity information. @@ -58,6 +61,9 @@ pub trait SaltEnv: Debug + Unpin { /// This multiplier scales the base storage gas costs, making operations more expensive /// as buckets grow. /// + /// [`MIN_BUCKET_SIZE`] is the smallest capacity an implementation may report. Reporting less + /// fails the transaction the way an error here does; it is not rounded up to the minimum. + /// /// # Arguments /// /// * `bucket_id` - The bucket to query diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs index 988e5aed2..6e3317e81 100644 --- a/crates/mega-evm/tests/satin/salt_failure.rs +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -10,7 +10,7 @@ use alloy_primitives::{Address, Bytes, TxKind, U256}; use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaEvm, MegaTransaction, + MegaEvm, MegaTransaction, MIN_BUCKET_SIZE, }; use revm::{ bytecode::opcode::{PUSH0, RETURN}, @@ -42,9 +42,20 @@ fn failing_slot(envs: SaltEnvs, address: Address, key: U256) -> SaltEnvs { /// Runs the probe and requires it to fail with the cause the SALT environment reported. fn assert_fails(site: &str, db: MemoryDatabase, envs: SaltEnvs, tx: MegaTransaction) { + assert_fails_with(site, UNREACHABLE, db, envs, tx); +} + +/// Runs the probe and requires it to fail with a cause naming `cause`. +fn assert_fails_with( + site: &str, + cause: &str, + db: MemoryDatabase, + envs: SaltEnvs, + tx: MegaTransaction, +) { match try_run(db, envs, tx) { Err(EVMError::Custom(message)) => assert!( - message.contains(UNREACHABLE), + message.contains(cause), "{site}: the recorded cause must reach the caller, got {message:?}", ), Err(other) => panic!("{site}: expected the recorded cause, got {other:?}"), @@ -183,6 +194,38 @@ fn test_an_unpriceable_charge_in_a_reverting_frame_still_fails_the_transaction() ); } +/// A bucket reported below the minimum capacity is a broken backend, not a cheap bucket: it fails +/// the transaction with a cause of its own rather than being rounded up to the minimum. A bucket +/// holds at least `MIN_BUCKET_SIZE` entries by construction, so a smaller answer is one the engine +/// cannot price against, and the one price it must never become is the free one. +#[test] +fn test_a_capacity_below_the_minimum_bucket_fails_the_transaction() { + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + + for capacity in [0, 1, MIN_BUCKET_SIZE as u64 - 1] { + let envs = + minimal_envs().with_bucket_capacity(slot_bucket(CONTRACT, U256::from(SLOT)), capacity); + assert_fails_with( + "a sub-minimum capacity", + "below the minimum bucket", + db(code.clone()), + envs, + call_contract(), + ); + } +} + +/// The same report at the minimum itself is a bucket, not a misreport: it prices at `m = 1`. +#[test] +fn test_the_minimum_capacity_itself_is_priced_not_refused() { + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = minimal_envs() + .with_bucket_capacity(slot_bucket(CONTRACT, U256::from(SLOT)), MIN_BUCKET_SIZE as u64); + + let outcome = run(db(code), envs, call_contract()); + assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas())); +} + /// A system-originated transaction is priced at the minimum bucket without reading SALT, so a /// SALT environment that cannot answer does not stop the protocol's own work. #[test] From 7923b9ea1a4f18b4c9b8e367af8f691523e2a224 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:45:46 +0800 Subject: [PATCH 159/201] test(satin): pin the keyless overhead against op-revm --- crates/mega-evm/tests/satin/equivalence.rs | 57 ++++++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index f2f8b8b1a..048b9147e 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -2,10 +2,10 @@ //! //! An ordinary transaction on the same `CfgEnv`, block and L1 info must produce the same result //! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and -//! the resulting state. The cases at the end are the ones that diverge on purpose — the system -//! contract interceptors and the system-address transaction — and they pin both sides, so a -//! divergence is never silently absorbed. Later changes (SALT pricing, history gas, limits) add -//! their own. +//! the resulting state. The four cases at the end are the ones that diverge on purpose — the +//! system contract interceptors, the `KeylessDeploy` overhead and the system-address transaction +//! — and they pin both sides, so a divergence is never silently absorbed. Later changes (SALT +//! pricing, history gas, limits) add their own. use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, TxKind, U256}; @@ -376,3 +376,52 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { "op-revm charges nothing for it", ); } + +/// A `keylessDeploy` transaction is charged the fixed overhead before its frame runs, where +/// op-revm charges nothing for it. Both engines then run the contract's bytecode and get its +/// `NotIntercepted()` revert, because the rewrite that turns the call into a deployment is not +/// here yet; the whole divergence is the overhead. +#[test] +fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { + use alloy_primitives::Bytes; + use alloy_sol_types::{SolCall, SolError}; + use mega_evm::system::keyless::{ + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_OVERHEAD_GAS, + }; + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), + data: IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode() + .into(), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + let revert_data = Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR); + assert_eq!( + mega.result.output().cloned().unwrap_or_default(), + revert_data, + "the bytecode runs after the charge", + ); + assert_eq!(op.result.output().cloned().unwrap_or_default(), revert_data); + + // What each transaction spent, not what its receipt reports: op-revm spends less than the + // EIP-7623 calldata floor here, so its receipt is lifted to the floor and Satin's is not. + // The two run the same bytecode on the same input, so the whole difference is the charge. + let charged = mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(); + assert_eq!(charged, KEYLESS_DEPLOY_OVERHEAD_GAS, "the divergence is the overhead, exactly"); + assert!( + mega.result.gas_used() - op.result.gas_used() < charged, + "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", + ); +} From f88e01e4a29e7ec7926d182b6142aab59a39b13d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:46:05 +0800 Subject: [PATCH 160/201] test(satin): pin the SELFDESTRUCT beneficiary as a state gas charge site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `SELFDESTRUCT` that moves a balance to an account that does not exist adds that account's leaf and is charged for it at the beneficiary's own site, so the hook prices it by the beneficiary's bucket. Nothing read that: the scaling arms, the failed-lookup arms and the refund matrix each covered six sites and this is the seventh. The arms are the ones the other sites have: the charge scales with the beneficiary's bucket and the regular ledger does not move; a bucket that cannot be read fails the transaction; a caller that reverts gives the charge back, with the surviving caller as the control. Two arms pin the condition from the other side — a contract with nothing to move, and a beneficiary that already exists, add no state and are charged nothing however crowded the bucket is. --- AGENTS.md | 1 + crates/mega-evm/tests/satin/salt.rs | 53 ++++++++++++++++++++- crates/mega-evm/tests/satin/salt_failure.rs | 15 +++++- crates/mega-evm/tests/satin/salt_refund.rs | 45 ++++++++++++++++- 4 files changed, 108 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3b3e258a0..84f95630f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,6 +119,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`). A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. + A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or create target, by an applied EIP-7702 authority, and by the beneficiary a `SELFDESTRUCT` moves a balance to; the bytes a creation deposits are charged in the deployed address's bucket. The capacities come from the transaction's `SaltEnv` through `BucketMultipliers` (`external/gas.rs`), which reads a bucket once per transaction; the cache is cleared with the rest of the per-transaction state. A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; today that is a transaction whose caller is the EIP-4788 system address and every transaction run through a system-call entry point, and the mega system transaction joins it with the system contract mechanisms. A failed capacity lookup reports nothing and records its cause the way a failed `sload` does; the transaction fails with that cause rather than settling at a price nobody chose. diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 0668b7e2c..f95bcaa0d 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -24,7 +24,7 @@ use mega_evm::{ MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, CREATE2, PUSH0, RETURN}, + bytecode::opcode::{CALL, CREATE, CREATE2, PUSH0, RETURN, SELFDESTRUCT}, context::{result::EVMError, tx::TxEnvBuilder, TxEnv}, context_interface::cfg::GasId, }; @@ -183,6 +183,12 @@ pub(crate) fn value_call(target: Address) -> BytecodeBuilder { .append(CALL) } +/// `SELFDESTRUCT(beneficiary)`: the running contract sends its balance to `beneficiary` and ends +/// its frame. +pub(crate) fn selfdestruct_to(beneficiary: Address) -> BytecodeBuilder { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT) +} + /// `CREATE(value = 0, offset = 0, size)` of `init_code`, written to memory first. /// /// `mstore` right-pads to a whole word, so the init code sits at offset 0 and the `CREATE` @@ -238,7 +244,7 @@ pub(crate) fn assert_scales( } } -/* The six sites a state gas charge is made at. */ +/* The seven sites a state gas charge is made at. */ /// `SSTORE` onto a slot that was zero: the slot's own bucket prices it. #[test] @@ -267,6 +273,19 @@ fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { ); } +/// A `SELFDESTRUCT` moving a balance to an account that does not exist adds that account's leaf, +/// and the beneficiary's own bucket prices it — the same entry and the same site a value `CALL` +/// pays, reached from the opcode that empties an account rather than the one that funds it. +#[test] +fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket() { + assert_scales( + "SELFDESTRUCT to a new account", + entry(GasId::new_account_state_gas()), + |envs, m| crowded_account(envs, EMPTY, m), + || (db(selfdestruct_to(EMPTY).build()), call_contract()), + ); +} + /// `CREATE`: the bucket of the address it deploys to prices the account it adds. #[test] fn test_the_create_charge_scales_with_the_created_address_s_bucket() { @@ -639,6 +658,36 @@ fn test_a_transfer_to_an_account_that_exists_charges_no_state_gas() { ); } +/// A `SELFDESTRUCT` pays for a beneficiary's leaf only when it has a balance to move and the +/// beneficiary does not exist yet. Neither half alone adds state, so neither is charged, however +/// crowded the beneficiary's bucket is. +#[test] +fn test_a_selfdestruct_that_adds_no_account_charges_no_state_gas() { + const FUNDED: Address = address!("0000000000000000000000000000000000c00007"); + + assert_charges_no_state_gas( + "a SELFDESTRUCT with nothing to move", + |envs, m| crowded_account(envs, EMPTY, m), + || { + // The contract holds no balance, so the beneficiary receives nothing and is not + // created. + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, selfdestruct_to(EMPTY).build()); + (db, call_contract()) + }, + ); + + assert_charges_no_state_gas( + "a SELFDESTRUCT to an account that exists", + |envs, m| crowded_account(envs, FUNDED, m), + || { + let db = db(selfdestruct_to(FUNDED).build()).account_balance(FUNDED, U256::from(1)); + (db, call_contract()) + }, + ); +} + /* The remaining creation sites. */ /// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs index 6e3317e81..96d39da90 100644 --- a/crates/mega-evm/tests/satin/salt_failure.rs +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -20,8 +20,8 @@ use revm::{ use crate::salt::{ account_bucket, authorization_tx, call_contract, create_empty_contract, crowded_account, db, - entry, minimal_envs, run, salt_context, slot_bucket, try_run, tx, value_call, SaltEnvs, - AUTHORITY, CALLER, CONTRACT, EMPTY, + entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, try_run, tx, value_call, + SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, }; /// What a broken SALT backend reports. @@ -86,6 +86,17 @@ fn test_an_unpriceable_new_account_call_fails_the_transaction() { ); } +/// And a `SELFDESTRUCT` whose beneficiary does not exist and whose bucket cannot be read. +#[test] +fn test_an_unpriceable_selfdestruct_beneficiary_fails_the_transaction() { + assert_fails( + "a SELFDESTRUCT beneficiary", + db(selfdestruct_to(EMPTY).build()), + failing_account(minimal_envs(), EMPTY), + call_contract(), + ); +} + /// And a `CREATE` whose deployment address falls in a bucket that cannot be read. #[test] fn test_an_unpriceable_create_fails_the_transaction() { diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 4ab9fa91d..3ea6a87e1 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -29,8 +29,8 @@ use revm::{ use crate::salt::{ authorization_tx, call_contract, capacity, create_with, crowded_account, crowded_slot, db, - entry, minimal_envs, run, salt_context, slot_bucket, try_run, tx, SaltEnvs, AUTHORITY, CALLER, - CONTRACT, EMPTY, GAS_LIMIT, + entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, try_run, tx, SaltEnvs, + AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, }; /// The contract a probe's inner frame runs in. @@ -193,6 +193,47 @@ fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { ); } +/// A `SELFDESTRUCT` charges for the beneficiary's leaf inside the frame that runs it, and a frame +/// whose caller does not survive gives the charge back: the inner frame self-destructed, the outer +/// one reverted, and the beneficiary was never created after all. +#[test] +fn test_a_selfdestruct_whose_caller_reverts_gives_its_charge_back() { + let probe = |outer_reverts: bool| { + move || { + let sub = selfdestruct_to(EMPTY).build(); + let mut code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(SUB) + .push_number(2_000_000u64) + .append(CALL); + code = if outer_reverts { code.revert_with_data([0xaa]) } else { code.stop() }; + let db = db(code.build()) + .account_code(SUB, sub) + .account_balance(SUB, U256::from(1_000_000u64)); + (db, call_contract()) + } + }; + let crowd = |envs, m| crowded_account(envs, EMPTY, m); + + assert_eq!( + net_state_at([1, 2, 8], crowd, probe(true)), + [0, 0, 0], + "the reverting caller takes the beneficiary's leaf back with it", + ); + + // The control: the same program whose outer frame survives keeps the charge, scaled. Without + // it the zeroes above could be passing because nothing was ever charged. + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!( + net_state_at([1, 2, 8], crowd, probe(false)), + [new_account, new_account * 2, new_account * 8], + ); +} + /// The whole transaction reverting is the same story one level up: the outermost frame's charge /// goes back with it. #[test] From 684cc5cead5b9383e3523e80f6c43ddfa8427cf1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:46:35 +0800 Subject: [PATCH 161/201] style(satin): read the receipt through the accessor that is not deprecated --- crates/mega-evm/tests/satin/equivalence.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 048b9147e..58e9a7182 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -421,7 +421,7 @@ fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { let charged = mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(); assert_eq!(charged, KEYLESS_DEPLOY_OVERHEAD_GAS, "the divergence is the overhead, exactly"); assert!( - mega.result.gas_used() - op.result.gas_used() < charged, + mega.result.gas().tx_gas_used() - op.result.gas().tx_gas_used() < charged, "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", ); } From 24f6b59875bc1af11b17d3807451ef4b5d0440d8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:46:51 +0800 Subject: [PATCH 162/201] test(satin): pin that a deposit transaction is not system-originated The system-origin rule exempts what the protocol produces, and a deposit is a shape a user can produce, so it is deliberately not exempt. Nothing in the tree read that: the rule's arms covered the system address and the system-call entry points, and the control arm was a plain call. Two arms now: a deposit with a non-zero source hash and no system flag pays the crowded price and reads the bucket it writes into, and one whose bucket cannot be read fails like any other transaction. --- crates/mega-evm/tests/satin/salt.rs | 58 ++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index f95bcaa0d..7120d6575 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -16,7 +16,7 @@ use alloy_eips::{ eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}, }; use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use mega_evm::{ satin_gas_params, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, @@ -154,6 +154,23 @@ pub(crate) fn tx_with_gas( })) } +/// A deposit transaction from `CALLER` to `to`, at [`GAS_LIMIT`]. +/// +/// A non-zero source hash is what makes op-revm classify a transaction as a deposit, and +/// `is_system_transaction` is left off: this is the deposit shape a user can produce, not the +/// sequencer's own system transaction. +pub(crate) fn deposit_tx(to: Address) -> MegaTransaction { + let mut tx = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + gas_limit: GAS_LIMIT, + ..Default::default() + }); + tx.deposit.source_hash = B256::from([0x42; 32]); + tx.deposit.is_system_transaction = false; + OpTx(tx) +} + /// A type-4 transaction from `CALLER` to `to`, delegating `AUTHORITY` to `DELEGATE`. pub(crate) fn authorization_tx(to: Address) -> MegaTransaction { OpTx(op_transaction( @@ -524,6 +541,45 @@ fn test_a_user_transaction_into_the_same_bucket_pays_the_crowded_price() { assert!(!evm.ctx().is_system_originated()); } +/// A deposit transaction is deliberately not system-originated, and pays the crowded price like +/// any other transaction a user sends. A deposit is a shape a user can produce, so matching it +/// here would be a way around the scaling. +#[test] +fn test_a_deposit_transaction_pays_the_crowded_price() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); + + let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); + let tx = deposit_tx(CONTRACT); + assert_ne!(tx.0.deposit.source_hash, B256::ZERO, "the probe must be a deposit"); + assert!(!tx.0.deposit.is_system_transaction, "and not a system deposit"); + + let outcome = evm.execute_transaction(tx).expect("the probe is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas()) * 8); + assert_eq!(envs.total_bucket_queries(), 1, "the deposit read the bucket it writes into"); + assert!(!evm.ctx().is_system_originated()); +} + +/// And a deposit whose bucket cannot be read fails, exactly as a plain transaction does: not +/// being system-originated cuts both ways. +#[test] +fn test_an_unpriceable_deposit_transaction_fails() { + const SLOT: u64 = 7; + let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); + let envs = minimal_envs() + .with_failing_bucket(slot_bucket(CONTRACT, U256::from(SLOT)), "salt backend down".into()); + + match try_run(db(code), envs, deposit_tx(CONTRACT)) { + Err(EVMError::Custom(message)) => { + assert!(message.contains("salt backend down"), "got {message:?}"); + } + other => panic!("expected the recorded cause, got {other:?}"), + } +} + /// The exemption belongs to one transaction: a user transaction run on the same EVM right after /// a system call is priced by its own bucket again. #[test] From e3058753edb5cdb20a27ff3a1a6cd7d40f1369f5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:47:39 +0800 Subject: [PATCH 163/201] docs: separate the two ways a state gas charge comes back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The invariant said every site that gives a charge back re-prices it through the pricing hook. Four do — `SSTORE`'s own restore, a caller's upfront charge for a call or creation that did not add the leaf, the transaction-level refund and the settlement of a synthetic frame result. A frame that fails does not: it rolls its own charges back by the amounts it recorded while running, without asking for a price. Both cancel the charge exactly, for different reasons, and only the first reason was written down. The mechanism that puts history gas on the same hook needs the shape it actually has. --- AGENTS.md | 5 +++-- crates/mega-evm/src/evm/host.rs | 14 +++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 84f95630f..e38fbe13f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,8 +163,9 @@ Every later mechanism plugs into these; a change to one comes back to this layer The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). The test utilities' inspectors are not declared. - **One hook prices every state charge.** - `Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced, and every site that gives a charge back re-prices the same `(id, site)` pair rather than reading a second table, so a refill cancels the charge it undoes exactly whatever the price was. - Because a bucket's multiplier is read once per transaction, the two cannot disagree even if the environment's answer would. + `Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced. + A charge is given back two ways, and neither reads a second table: `SSTORE`'s own restore, a caller's upfront charge for a call or creation that did not add the leaf, the transaction-level refund and the settlement of a synthetic frame result re-price the same `(id, site)` pair through the hook; a frame that fails rolls its own charges back by the amounts it recorded while running, without asking for a price at all. + Both cancel the charge exactly whatever the price was — the re-priced sites because a bucket's multiplier is read once per transaction, so the two cannot disagree even if the environment's answer would, and the rolled-back amounts because nothing but the hook priced them. A mechanism that adds a state charge adds a `StateGasCharge` at the site the state lands on; it must not price the charge itself. - **Three ledgers.** `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index fa7f6754b..f3259d784 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -17,9 +17,17 @@ //! //! [`state_gas_price`](revm::context_interface::Host::state_gas_price) is the one place an //! EIP-8037 state gas charge is priced. Every charge site of the engine asks it, and so does -//! every site that gives a charge back — the same `(id, site)` pair, so a refill cancels the -//! charge it undoes exactly, whatever the price was. That is what lets SALT scale the charge by -//! the capacity of the bucket it lands in without a second table of what to give back. +//! every site that names a charge to give back — the same `(id, site)` pair, so the refill +//! cancels the charge it undoes exactly, whatever the price was. That is what lets SALT scale the +//! charge by the capacity of the bucket it lands in without a second table of what to give back. +//! +//! A charge comes back two ways, and neither reads a second table. `SSTORE`'s own restore, a +//! caller's upfront charge for a call or creation that did not add the leaf, the transaction-level +//! refund and the settlement of a synthetic frame result re-price the recorded `(id, site)` +//! through this hook. A frame that fails instead rolls its own charges back by the amounts it +//! recorded while running, without asking for a price at all. Both cancel exactly, for different +//! reasons: the re-priced sites because the multiplier of a bucket is read once per transaction, +//! the rolled-back amounts because nothing but this hook priced them in the first place. //! //! Every other Host method delegates to op-revm's context. From 07e354ba11cf10967c136214443bc7fdbc83fda0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:48:14 +0800 Subject: [PATCH 164/201] test(satin): park the system transaction exemption row again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ledger recorded the row that runs the sequencer's deposit-promoted system transaction under two SALT capacities as ported into the system-address arm of the SALT tests. It is not that scenario: the arm runs a plain transaction whose caller is the system address, and the mega system transaction is not system-originated yet — the system contract mechanisms are what define its caller and the source hash it is promoted with. The row goes back to the parked file, so the ledger reports the gap as the three rows it is rather than two, and a successor does not read the exemption as pinned. --- crates/mega-evm/tests/_pending/README.md | 11 ++-- .../rex6/system_tx_metering_exemption.rs | 53 +++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index f3c5f31d4..b3139f7d7 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -27,7 +27,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 14 | 9 | 5 | 4 | 10 | 0 | +| SALT pricing | 15 | 10 | 5 | 4 | 11 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +41,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **599** | **519** | **80** | **367** | **204** | **28** | +| **Total** | **600** | **520** | **80** | **367** | **205** | **28** | ## Tests ported in place @@ -167,7 +167,7 @@ These 53 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by SALT pricing -These 61 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. +These 60 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -179,10 +179,9 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the | `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/error_paths.rs` | SALT pricing (2) | 2 | `tests/satin/salt_failure.rs` | -| `rex6/system_tx_metering_exemption.rs` | SALT pricing (1) | 1 | `tests/satin/salt.rs` | | `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | | `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | -| **Total** | | **61** | | +| **Total** | | **60** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -255,7 +254,7 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | | `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `rex6/system_tx_metering_exemption.rs` | 2 | rewrite 2 (SALT pricing · D51 (m = 1 for system source; history exempt)) | +| `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | diff --git a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs index 7d4b1e343..6362475fd 100644 --- a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs +++ b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs @@ -278,3 +278,56 @@ fn test_rex6_sequencer_oracle_tx_succeeds_under_heavy_salt() { // ============================================================================ // 3. Determinism: system tx cost/state independent of bucket capacity // ============================================================================ + +/// Runs the identical oracle system tx under light (1×) and heavy (100,000×) SALT, both REX6, and +/// asserts identical `gas_used` and identical resulting oracle state. This pins the core property: +/// a system-originated transaction's cost no longer depends on SALT bucket capacity. (Under REX5 +/// the heavy case would instead OOG.) +#[test] +fn test_rex6_system_tx_storage_gas_independent_of_bucket_capacity() { + fn run_oracle_tx(envs: TestExternalEnvs) -> (u64, U256) { + let mut state = State::builder().with_database(MemoryDatabase::default()).build(); + let evm_factory = MegaEvmFactory::new().with_external_env_factory(envs); + let executor_factory = MegaBlockExecutorFactory::new( + rex6_chain_spec(), + evm_factory, + OpAlloyReceiptBuilder::default(), + ); + let block_ctx = MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + let mut executor = + executor_factory.create_executor(&mut state, block_ctx, rex6_evm_env(BLOCK_GAS_LIMIT)); + executor.evm.ctx.chain_mut().operator_fee_scalar = Some(U256::ZERO); + executor.evm.ctx.chain_mut().operator_fee_constant = Some(U256::ZERO); + executor.apply_pre_execution_changes().expect("pre-execution"); + + let value = B256::with_last_byte(0xCD); + let tx = oracle_system_tx(0, ORACLE_SLOT, value); + let outcome = executor.run_transaction(&tx).expect("oracle system tx must execute"); + assert!(outcome.result.is_success(), "must succeed: {:?}", outcome.result); + let gas_used = outcome.result.gas_used(); + executor.commit_transaction_outcome(outcome).expect("commit"); + let slot = executor + .evm + .db_mut() + .storage(ORACLE_CONTRACT_ADDRESS, ORACLE_SLOT) + .expect("oracle storage read"); + (gas_used, slot) + } + + let (gas_light, slot_light) = run_oracle_tx(light_external_envs()); + let (gas_heavy, slot_heavy) = run_oracle_tx(heavy_external_envs()); + + assert_eq!( + gas_light, gas_heavy, + "exempt system tx gas must be independent of SALT bucket capacity (light={gas_light}, heavy={gas_heavy})", + ); + assert_eq!( + slot_light, slot_heavy, + "resulting oracle state must be identical regardless of bucket capacity" + ); +} From 4932314a31d23bd8c85d538742ff5f36c0fd656b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:49:30 +0800 Subject: [PATCH 165/201] test(satin): retire the rows the pricing hook leaves nothing to pin Four parked rows guarded a pricing path that does not exist in Satin. Three ran `CALLCODE` into an account inspection while pricing a new account leaf; `CALLCODE` sends value to the frame's own account, which exists, so it adds no leaf and asks for no price at all. The fourth guarded a recursive delegation walk on that same path; the fork decides whether a target exists and the hook only prices what it is told to. No later mechanism will port them, so they are retired rather than left parked waiting for one. The pending ledger gains the disposition, with the reason and the mechanism that owns each row, and the two files that held nothing else are gone. --- crates/mega-evm/tests/_pending/README.md | 18 +- .../_pending/rex5/callcode_storage_gas.rs | 319 ------------------ .../mega-evm/tests/_pending/src/evm/host.rs | 123 ------- 3 files changed, 14 insertions(+), 446 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/host.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index b3139f7d7..6ac469adb 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -16,6 +16,7 @@ Do not add a `_pending/main.rs`. - Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. - `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. - Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. +- A row whose owning mechanism has landed and left it nothing to pin is retired rather than kept parked: it moves to "Tests retired after the inventory" with the reason, and its row is deleted from the file here in the same commit. - The 44 legacy mutant killers the inventory kept (`tests/mutation/`) are not here: each was keyed to a surviving mutant of the legacy sources, and the test gates found no survivor in the Satin sources to regenerate one for. A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`; what the retired rows cited is kept in "Retired mutant killers" below. - Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. @@ -27,7 +28,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 15 | 10 | 5 | 4 | 11 | 0 | +| SALT pricing | 11 | 7 | 4 | 0 | 11 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +42,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **600** | **520** | **80** | **367** | **205** | **28** | +| **Total** | **596** | **517** | **79** | **363** | **205** | **28** | ## Tests ported in place @@ -183,6 +184,17 @@ These 60 rows run in a real test target now, adapted to the Satin API and to the | `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | | **Total** | | **60** | | +## Tests retired after the inventory + +These 4 rows were parked when the inventory was applied and have since been retired: the mechanism that owns them landed and left them nothing to pin, so no later mechanism will port them. +They are not counted above. + +| Legacy file | Owner in the inventory | Tests | Why | +|---|---|---:|---| +| `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | Satin's `CALLCODE` cannot reach a state gas pricing site: it sends value to the frame's own account, which exists, so it adds no account leaf and asks for no price. There is no pricing-path account inspection left to fail | +| `src/evm/host.rs` | SALT pricing (1) | 1 | the pricing hook inspects no account: the fork decides whether a target exists and the hook only prices what it is told to, so there is no delegation walk on the pricing path to guard | +| **Total** | | **4** | | + ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism | File | Test | Parked under | Reason | @@ -225,7 +237,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | | `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | | `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | -| `rex5/callcode_storage_gas.rs` | 3 | keep 3 (SALT pricing · pricing-failure propagation) | | `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | @@ -256,7 +267,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | -| `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | | `src/external/gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | diff --git a/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs deleted file mode 100644 index 6edaa0749..000000000 --- a/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs +++ /dev/null @@ -1,319 +0,0 @@ -//! Tests for Rex5's fix to `CALLCODE` new-account storage gas metering. -//! -//! Pre-Rex5, the storage-gas wrapper for `CALLCODE` checked emptiness and charged -//! `new_account_storage_gas` against the stack `to` address — the code-source. For -//! `CALLCODE`, however, execution happens in the caller's account context, so the -//! storage account being potentially "created" is the caller's, not the code-source. -//! Charging against the code-source can charge new-account storage gas spuriously -//! when the code-source happens to be empty. -//! -//! Rex5 changes the wrapper to meter new-account storage gas against -//! `interpreter.input.target_address()` (the caller / current frame). The stack -//! `to` is still used as the code-source for the underlying `CALLCODE` instruction. -//! Pre-Rex5 specs preserve their (frozen) prior behavior. -//! -//! `CALL` behavior is unchanged across all specs: the stack `to` is the value -//! recipient and is the correct address for emptiness / new-account metering. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE, - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, - BucketId, EVMError, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, SaltEnv, TestExternalEnvs, - MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::{CALL, CALLCODE, STOP}, - context::{result::ResultAndState, TxEnv}, - database::AccountState, - state::Bytecode, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000001"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); -/// An address that is not present in the database — i.e. an empty account. -const EMPTY_TARGET: Address = address!("3000000000000000000000000000000000000001"); -/// Address that `CALLEE` 7702-delegates to in the combined-fix regression test; -/// holds the actual CALLCODE-emitting runtime bytecode. -const DELEGATE: Address = address!("4000000000000000000000000000000000000001"); - -/// Writes an EIP-7702 designator (`0xef0100 || delegate_to`) into `address`, -/// mirroring what revm's `apply_eip7702_auth_list` does for Type 4 transactions. -fn set_eip7702_delegation(db: &mut MemoryDatabase, address: Address, delegate_to: Address) { - let bytecode = Bytecode::new_eip7702(delegate_to); - let code_hash = bytecode.hash_slow(); - let account = db.load_account(address).unwrap(); - account.info.code = Some(bytecode); - account.info.code_hash = code_hash; - account.account_state = AccountState::None; -} - -/// Builds bytecode that performs `CALLCODE(gas=GAS, target, value=1, args=[], ret=[])` -/// followed by `STOP`. The CALL stipend covers gas inside the (empty-code) callee. -fn callcode_bytecode(target: Address) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(target) - .push_number(100_000_u64) // gas - .append(CALLCODE) - .append(STOP) - .build() -} - -/// Builds bytecode that performs `CALL(gas=GAS, target, value=1, args=[], ret=[])` -/// followed by `STOP`. -fn call_bytecode(target: Address) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(target) - .push_number(100_000_u64) // gas - .append(CALL) - .append(STOP) - .build() -} - -#[allow(clippy::too_many_arguments)] -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - caller: Address, - callee: Address, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = - MegaContext::new(db, spec).with_external_envs(external_envs.into()).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: TxKind::Call(callee), - data: Bytes::new(), - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Runs the given bytecode on `spec` with a configurable bucket multiplier for the -/// empty target. Returns the transaction's `gas_used`. -fn run_with_target_multiplier(spec: MegaSpecId, bytecode: Bytes, target_multiplier: u64) -> u64 { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1_000_000_000u64)) - .account_code(CALLEE, bytecode); - - let target_bucket = TestExternalEnvs::::bucket_id_for_account(EMPTY_TARGET); - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(target_bucket, MIN_BUCKET_SIZE as u64 * target_multiplier); - - let result = transact(spec, &mut db, &external_envs, CALLER, CALLEE, U256::ZERO, 10_000_000) - .expect("transaction must succeed"); - assert!(result.result.is_success(), "execution must succeed: {:?}", result.result); - result.result.gas_used() -} - -// ============================================================================ -// CALLCODE: Rex5 fix — no new-account storage gas charged -// ============================================================================ - -// ============================================================================ -// CALLCODE: Rex5 fix combined with EIP-7702 non-delegating inspection -// ============================================================================ - -// ============================================================================ -// CALLCODE: Pre-Rex5 frozen behavior — bug preserved -// ============================================================================ - -// ============================================================================ -// CALL: behavior unchanged — value-transferring CALL to empty target still charges -// ============================================================================ - -// ============================================================================ -// Error-path tests — coverage for FatalExternalError branches in call_code -// ============================================================================ - -/// A SALT environment that always fails `get_bucket_capacity`, triggering the -/// `new_account_storage_gas` → `None` → `FatalExternalError` path in `call_code`. -#[derive(Debug)] -struct FailingSaltEnv; - -impl SaltEnv for FailingSaltEnv { - type Error = String; - - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err("injected salt error".into()) - } - - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } -} - -fn transact_with_error_db( - spec: MegaSpecId, - db: ErrorInjectingDatabase, - caller: Address, - callee: Address, - gas_limit: u64, -) -> Result, EVMError> { - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(db, spec).with_external_envs(external_envs.into()).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: TxKind::Call(callee), - data: Bytes::new(), - value: U256::ZERO, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -fn transact_with_failing_salt( - spec: MegaSpecId, - db: &mut MemoryDatabase, - caller: Address, - callee: Address, - gas_limit: u64, -) -> Result, EVMError> { - let envs: ExternalEnvs<(FailingSaltEnv, EmptyExternalEnv)> = - ExternalEnvs { salt_env: FailingSaltEnv, oracle_env: EmptyExternalEnv }; - let mut context = MegaContext::new(db, spec).with_external_envs(envs).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: TxKind::Call(callee), - data: Bytes::new(), - value: U256::ZERO, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// When `inspect_account_delegated` fails during CALLCODE (in `storage_gas_ext::call_code`), -/// the EVM should halt with `FatalExternalError` and return `EVMError::Custom`. -/// Under Rex4, the storage address is the code-source (stack `to` = `EMPTY_TARGET`). -#[test] -fn test_callcode_db_error_on_inspect_account() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let inner_db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1_000_000_000u64)) - .account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - db.fail_on_account = Some(EMPTY_TARGET); - - let result = transact_with_error_db(MegaSpecId::REX4, db, CALLER, CALLEE, 1_000_000); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected basic()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -/// Under Rex5, CALLCODE storage metering inspects the current frame target (`CALLEE`), -/// not the code-source. This injected database failure is triggered while loading -/// `CALLEE` during transaction setup, so it surfaces as `EVMError::Database`. -#[test] -fn test_rex5_callcode_db_error_on_inspect_account() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let inner_db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1_000_000_000u64)) - .account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - db.fail_on_account = Some(CALLEE); - - let result = transact_with_error_db(MegaSpecId::REX5, db, CALLER, CALLEE, 1_000_000); - - match result { - Err(EVMError::Database(err)) => { - assert!( - err.to_string().contains("injected basic()"), - "error message should contain injected error, got: {err}" - ); - } - Err(other) => panic!("expected EVMError::Database, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -#[test] -fn test_callcode_salt_error_on_new_account_storage_gas() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1_000_000_000u64)) - .account_code(CALLEE, bytecode); - - let result = transact_with_failing_salt(MegaSpecId::REX4, &mut db, CALLER, CALLEE, 1_000_000); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected salt error"), - "error message should contain salt error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} diff --git a/crates/mega-evm/tests/_pending/src/evm/host.rs b/crates/mega-evm/tests/_pending/src/evm/host.rs deleted file mode 100644 index 534e16b6b..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/host.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/host.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/host.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256}; - use core::cell::Cell; - use revm::{ - primitives::HashMap, - state::{AccountInfo, Bytecode}, - Database, - }; - - /// Minimal `revm::Database` implementation that mimics the production - /// `reth`-style `StateProviderDatabase` contract: `basic()` returns - /// `AccountInfo { code: None, code_hash: }` for accounts with - /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via - /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — - /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache - /// miss against it would always see the code already hydrated. - #[derive(Default)] - struct LazyCodeDatabase { - accounts: HashMap, - codes: HashMap, - storage_calls: Cell, - } - - impl LazyCodeDatabase { - fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { - let code = Bytecode::new_raw(bytecode); - let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); - self.codes.insert(code_hash, code); - self - } - - fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { - let code = Bytecode::new_eip7702(delegate); - let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); - self.codes.insert(code_hash, code); - self - } - - fn storage_calls(&self) -> usize { - self.storage_calls.get() - } - } - - impl revm::Database for LazyCodeDatabase { - type Error = core::convert::Infallible; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without - // populating `code`, even when the account has on-chain bytecode. - Ok(self.accounts.get(&address).cloned()) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) - } - - fn storage(&mut self, _address: Address, _index: U256) -> Result { - self.storage_calls.set(self.storage_calls.get() + 1); - Ok(U256::ZERO) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } - } - - /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the - /// very first cold inspection against a lazy-code database. Regression guard: - /// any refactor that re-introduces a code-None branch silently degrades the - /// walk to "treat the delegator as a regular EOA". - #[test] - fn test_inspect_account_delegated_follows_eip7702_on_cold_first_touch() { - use revm::context::JournalTr; - - const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); - let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); // PUSH1 0x42 PUSH1 0 SSTORE - - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_bytecode.clone()); - - let mut journal = Journal::new(db); - - let resolved = journal - .inspect_account_delegated(MegaSpecId::REX5, DELEGATOR) - .expect("inspect_account_delegated must succeed on a cold-cache first touch"); - - // The resolved account must be the delegate, not the delegator. The only way - // to distinguish them is the code: the delegator's code is the EIP-7702 - // designation pointing at DELEGATE; the delegate's code is the raw bytecode. - let hydrated = resolved.info.code.as_ref().expect( - "delegate's bytecode must be hydrated by the inner inspect_account call — \ - without the vacant-path hydration, the cold-touch on DELEGATE would leave \ - code as None and any subsequent EIP-7702 walk would see a wrongly-empty target", - ); - assert!( - !matches!(hydrated, Bytecode::Eip7702(_)), - "resolved account must NOT be the delegator (whose code is the EIP-7702 \ - designation); got: {hydrated:?}", - ); - assert_eq!( - hydrated.original_bytes().as_ref(), - delegate_bytecode.as_ref(), - "resolved account's code must match the delegate's raw bytecode — confirms \ - the delegation was followed exactly one hop", - ); - } -} From e051a824bd9f9df7ae5a6b1dcf546ecc846d70c3 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 14:50:36 +0800 Subject: [PATCH 166/201] test(system): send the same hint from both data-size cases --- crates/mega-evm/tests/system/oracle.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 5a7a635b7..d7af5f0bc 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -22,6 +22,9 @@ use crate::common::{block, call_tx, calls_with, run, system_db, with_contract, C /// A topic and payload the tests send. const TOPIC: B256 = B256::repeat_byte(0x7a); +/// The hint the two data-size cases send, so the limit they set is the same number. +const METERED_HINT: &[u8] = b"a hint the transaction is metered for"; + /// The calldata of `sendHint(TOPIC, data)`. fn send_hint(data: &[u8]) -> Bytes { Bytes::from( @@ -241,7 +244,7 @@ fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { /// is what shows it — and the transaction settles as a revert carrying the stop's own data. #[test] fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { - let data = send_hint(b"a hint one byte too long"); + let data = send_hint(METERED_HINT); let limit = data.len() as u64 - 1; let (outcome, hints) = run_with_oracle_under( system_db(), @@ -275,7 +278,7 @@ fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { /// above it. #[test] fn test_a_hint_at_the_data_size_limit_is_forwarded() { - let data = send_hint(b"a hint one byte too long"); + let data = send_hint(METERED_HINT); let (outcome, hints) = run_with_oracle_under( system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), From 16b575a111a6da8787b60b64d80d10f0ec459305 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 15:37:35 +0800 Subject: [PATCH 167/201] feat(evm): price the sequencer's system transaction at the minimum bucket The context decided system origin on its own, matching only the EIP-4788 system-address caller, because the system transaction had no definition yet when SALT pricing landed. It has one now, so the context consults it: the predicate is `system::is_system_originated` with the address execution.rs promotes with, which matches the system-address caller, the promoted source hash and the whitelisted system-address call before promotion. The system-call flag stays the other arm, and the private duplicate goes. Ports the three rows the pending ledger parks under SALT pricing: the promoted system transaction pays the same state gas across two capacities and reads no capacity at all, the pre-block system calls likewise, and a user transaction in the same block still pays the crowded price. --- AGENTS.md | 2 +- crates/mega-evm/src/evm/context.rs | 40 +-- crates/mega-evm/tests/_pending/README.md | 10 +- crates/mega-evm/tests/_pending/rex6/main.rs | 1 - .../rex6/system_tx_metering_exemption.rs | 333 ------------------ crates/mega-evm/tests/satin/salt.rs | 138 ++++++++ 6 files changed, 153 insertions(+), 371 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs diff --git a/AGENTS.md b/AGENTS.md index c491f9bbe..a01cb6ece 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -121,7 +121,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or create target, by an applied EIP-7702 authority, and by the beneficiary a `SELFDESTRUCT` moves a balance to; the bytes a creation deposits are charged in the deployed address's bucket. The capacities come from the transaction's `SaltEnv` through `BucketMultipliers` (`external/gas.rs`), which reads a bucket once per transaction; the cache is cleared with the rest of the per-transaction state. - A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; today that is a transaction whose caller is the EIP-4788 system address and every transaction run through a system-call entry point, and the mega system transaction joins it with the system contract mechanisms. + A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; that is a transaction whose caller is the EIP-4788 system address, the sequencer's own system transaction — before or after the engine promotes it to a deposit — and every transaction run through a system-call entry point. A failed capacity lookup reports nothing and records its cause the way a failed `sload` does; the transaction fails with that cause rather than settling at a price nobody chose. At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. - The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 644e49c5f..79edf4446 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,21 +1,19 @@ //! The execution context of the Satin engine. -use alloy_eips::eip4788::SYSTEM_ADDRESS; use delegate::delegate; use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ - context::{ - BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, - Transaction, - }, + context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, primitives::{Address, StorageKey}, Database, Journal, }; use crate::{ - constants, evm::schedule::satin_gas_params, AdditionalLimit, BlockHashRecord, BucketError, - BucketMultipliers, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - MegaSpecId, MegaTransaction, SaltEnv, + constants, + evm::schedule::satin_gas_params, + system::{self, MEGA_SYSTEM_ADDRESS}, + AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, + EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -45,7 +43,7 @@ pub struct MegaContext MegaContext { } /// Whether the running (or last) transaction is system-originated, and so prices every - /// EIP-8037 state gas charge at the minimum bucket. See [`is_system_originated`]. + /// EIP-8037 state gas charge at the minimum bucket. See [`system::is_system_originated`]. pub const fn is_system_originated(&self) -> bool { self.system_originated } @@ -205,7 +203,7 @@ impl MegaContext { pub(crate) fn on_new_tx(&mut self) { self.additional_limit.reset(); self.bucket_multipliers.reset(); - self.system_originated = is_system_originated(&self.inner.tx); + self.system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); } /// Prepares the context for a system call. Every system-call entry point of @@ -225,26 +223,6 @@ impl MegaContext { } } -/// Whether `tx` is system-originated: produced by the protocol itself rather than sent by a user. -/// -/// A system-originated transaction prices EIP-8037 state gas at the minimum bucket (`m = 1`), so -/// a state change the protocol mandates costs the same however full the SALT bucket it lands in -/// happens to be, and can never be priced out of a block by the growth of a region it does not -/// control. -/// -/// What it matches today is the transaction whose caller is the EIP-4788 / EIP-2935 system -/// address, which is how the pre-block system calls are issued; every transaction run through a -/// system-call entry point is system-originated whatever caller it names -/// ([`MegaContext::on_new_system_call`]). The sequencer's own system transaction joins this rule -/// when the system contract mechanisms land, which are what define its caller and the deposit -/// source hash it is promoted with. -/// -/// A user's deposit transaction is deliberately not system-originated. A deposit is a shape a -/// user can produce, so matching it here would be a way around the scaling. -fn is_system_originated(tx: &MegaTransaction) -> bool { - tx.caller() == SYSTEM_ADDRESS -} - /// Sets the configuration fields the spec fixes. /// /// Satin runs the Satin gas schedule (see [`satin_gas_params`]) on its Karst base, with EIP-8037 diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index fc2049f94..a65491af7 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,7 +28,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 11 | 7 | 4 | 0 | 11 | 0 | +| SALT pricing | 8 | 4 | 4 | 0 | 8 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +41,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **535** | **464** | **71** | **311** | **196** | **28** | +| **Total** | **532** | **461** | **71** | **311** | **193** | **28** | ## Tests ported in place @@ -167,7 +167,7 @@ These 53 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by SALT pricing -These 60 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. +These 63 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -179,9 +179,10 @@ These 60 rows run in a real test target now, adapted to the Satin API and to the | `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/error_paths.rs` | SALT pricing (2) | 2 | `tests/satin/salt_failure.rs` | +| `rex6/system_tx_metering_exemption.rs` | SALT pricing (3) | 3 | `tests/satin/salt.rs` | | `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | | `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | -| **Total** | | **60** | | +| **Total** | | **63** | | ## Tests ported by the system contract interceptors @@ -277,7 +278,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | | `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | | `src/external/gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D51) | diff --git a/crates/mega-evm/tests/_pending/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs index a6e652c07..54d1f6c42 100644 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -16,4 +16,3 @@ mod keyless_sandbox_hardening; mod oracle_hint_volatile_access; mod self_transfer_account_dedup; mod sequencer_registry_rotation; -mod system_tx_metering_exemption; diff --git a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs deleted file mode 100644 index 6362475fd..000000000 --- a/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs +++ /dev/null @@ -1,333 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! End-to-end tests for the REX6 system-originated metering exemption. -//! -//! REX6 exempts system-originated transactions (the protocol's pre-block system calls and -//! sequencer mega system transactions — see `mega_evm::is_system_originated`) from MegaETH's -//! per-transaction resource metering: SALT-scaled storage gas is charged at the minimum bucket -//! capacity (so it never grows with the bucket), and the four `AdditionalLimit` dimensions plus -//! gas detention are bypassed. Only the standard EVM `gas_limit` still bounds the work. -//! -//! The heavy-SALT scenario uses a 100,000× bucket multiplier, which makes each zero→nonzero -//! `SSTORE` cost ≈ 2G of dynamic storage gas. Two paired tests pin the parity claim end-to-end: -//! the REX6 case accepts the block; the REX5 case (same setup, only `cfg.spec` differs) rejects -//! it on the EIP-2935 pre-block `SSTORE`. - -use std::convert::Infallible; - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_evm::{ - block::{ - BlockExecutor, BlockValidationError, OnStateHook, StateChangePreBlockSource, - StateChangeSource, - }, - Evm as _, EvmEnv, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, BucketHasher, BucketId, IOracle, - MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, MegaHardfork, - MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, SequencerRegistryConfig, - SequencerRegistryRex6Config, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - context::{BlockEnv, CfgEnv, ContextTr as _}, - database::State, - state::{AccountInfo, Bytecode, EvmState}, - Database as _, -}; -use std::sync::{Arc, Mutex}; - -const ACTIVATION_BLOCK: u64 = 1000; -const MEGA_CHAIN_ID: u64 = 4326; -const BLOCK_GAS_LIMIT: u64 = 250_000_000; -const SYSTEM_TX_GAS_LIMIT: u64 = 4_020_000; -const ORACLE_SLOT: U256 = U256::ZERO; - -/// Bucket that every SALT lookup is routed to under [`SingleBucketHasher`]. -const HEAVY_BUCKET_ID: BucketId = 100_000; -/// Capacity = 100,000 × `MIN_BUCKET_SIZE` (256) → a 100,000× multiplier, so each zero→nonzero -/// `SSTORE` would cost ≈ 2G of dynamic storage gas without the exemption (far beyond any -/// reasonable gas limit). This is the capacity that rejects the block under REX5. -const HEAVY_BUCKET_CAPACITY: u64 = 25_600_000; - -const BOOTSTRAP_SEQUENCER: Address = address!("4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("5000000000000000000000000000000000000005"); - -/// Routes every account / slot to a single bucket so the heavy capacity bites every `SSTORE`, -/// regardless of which contract/slot performs it. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - HEAVY_BUCKET_ID - } -} - -fn rex6_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - }) - .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 100 }) -} - -/// REX5-only chain spec (REX6 stays at `ForkCondition::Never`). Used by the negative parity test -/// to confirm the heavy-SALT pre-block-call scenario is rejected pre-REX6. -fn rex5_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)).with_params( - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - }, - ) -} - -fn evm_env(spec: MegaSpecId, gas_limit: u64) -> EvmEnv { - let mut cfg_env = CfgEnv::default(); - cfg_env.spec = spec; - cfg_env.chain_id = MEGA_CHAIN_ID; - let block_env = BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit, - basefee: 0, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn rex6_evm_env(gas_limit: u64) -> EvmEnv { - evm_env(MegaSpecId::REX6, gas_limit) -} - -fn heavy_external_envs() -> TestExternalEnvs { - TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET_ID, HEAVY_BUCKET_CAPACITY) -} - -/// Default capacity (`MIN_BUCKET_SIZE`) for the heavy bucket → 1× multiplier, normal gas cost. -fn light_external_envs() -> TestExternalEnvs { - TestExternalEnvs::::new() -} - -fn install_eip2935_history_storage(db: &mut MemoryDatabase) { - let bytecode = Bytecode::new_raw(alloy_eips::eip2935::HISTORY_STORAGE_CODE.clone()); - db.insert_account_info( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -fn install_eip4788_beacon_roots(db: &mut MemoryDatabase) { - let bytecode = Bytecode::new_raw(alloy_eips::eip4788::BEACON_ROOTS_CODE.clone()); - db.insert_account_info( - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -/// Recording state hook capturing every reported `StateChangeSource`, so a test can assert that a -/// pre-block call's state delta reached the witness path (i.e., the call succeeded and committed). -#[derive(Debug, Default, Clone)] -struct RecordingStateHook { - events: Arc>>, -} - -impl OnStateHook for RecordingStateHook { - fn on_state(&mut self, source: StateChangeSource, _state: &EvmState) { - self.events.lock().unwrap().push(source); - } -} - -fn oracle_set_slots_calldata(slot: U256, value: B256) -> Bytes { - IOracle::setSlotsCall { slots: vec![slot], values: vec![value] }.abi_encode().into() -} - -/// A sequencer mega system tx: legacy tx from `MEGA_SYSTEM_ADDRESS` to the whitelisted oracle. -fn oracle_system_tx(nonce: u64, slot: U256, value: B256) -> Recovered { - let tx = TxLegacy { - chain_id: Some(MEGA_CHAIN_ID), - nonce, - gas_price: 0, - gas_limit: SYSTEM_TX_GAS_LIMIT, - to: TxKind::Call(ORACLE_CONTRACT_ADDRESS), - value: U256::ZERO, - input: oracle_set_slots_calldata(slot, value), - }; - let signed = Signed::new_unchecked( - tx, - Signature::test_signature(), - B256::with_last_byte(nonce.saturating_add(1) as u8), - ); - Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), MEGA_SYSTEM_ADDRESS) -} - -// ============================================================================ -// 1. Pre-block system calls (EIP-2935 / EIP-4788) accepted under heavy SALT -// ============================================================================ - -/// Under heavy SALT, the EIP-2935 history-storage and EIP-4788 beacon-root pre-block `SSTORE`s -/// would each cost ≈ 2G of dynamic storage gas — which rejects the block under REX5. REX6 exempts -/// these system-originated calls (`0xff..fe` caller), so both succeed and their state deltas reach -/// the on-state witness path. -#[test] -fn test_rex6_pre_block_calls_accepted_under_heavy_salt() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex6_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - // Non-zero parent hash / beacon root so both pre-block calls perform a real zero→nonzero - // SSTORE. - let block_ctx = MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx, - rex6_evm_env(BLOCK_GAS_LIMIT), - ); - - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - executor - .apply_pre_execution_changes() - .expect("REX6 must accept pre-block system calls even under heavy SALT"); - - let recorded = events.lock().unwrap(); - let saw_block_hashes = recorded.iter().any(|s| { - matches!(s, StateChangeSource::PreBlock(StateChangePreBlockSource::BlockHashesContract)) - }); - let saw_beacon_root = recorded.iter().any(|s| { - matches!(s, StateChangeSource::PreBlock(StateChangePreBlockSource::BeaconRootContract)) - }); - assert!(saw_block_hashes, "EIP-2935 pre-block call must succeed and commit under REX6"); - assert!(saw_beacon_root, "EIP-4788 pre-block call must succeed and commit under REX6"); -} - -// ============================================================================ -// 2. Sequencer mega system tx (oracle write) succeeds under heavy SALT -// ============================================================================ - -/// A sequencer oracle `setSlots` mega system tx performs a real (non-intercepted) zero→nonzero -/// `SSTORE`. Under heavy SALT this would OOG without the exemption; REX6 charges it at the minimum -/// bucket capacity, so it succeeds and the oracle slot is updated. -#[test] -fn test_rex6_sequencer_oracle_tx_succeeds_under_heavy_salt() { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let executor_factory = MegaBlockExecutorFactory::new( - rex6_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - // Zero parent hash/beacon → pre-block calls write zero (no SSTORE_SET), isolating the SALT - // exposure to the oracle write under test. - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = - executor_factory.create_executor(&mut state, block_ctx, rex6_evm_env(BLOCK_GAS_LIMIT)); - executor.evm.ctx.chain_mut().operator_fee_scalar = Some(U256::ZERO); - executor.evm.ctx.chain_mut().operator_fee_constant = Some(U256::ZERO); - - executor - .apply_pre_execution_changes() - .expect("REX6 pre-execution must deploy oracle + registry"); - - let value = B256::with_last_byte(0xAB); - let tx = oracle_system_tx(0, ORACLE_SLOT, value); - let outcome = - executor.run_transaction(&tx).expect("oracle system tx must execute under REX6 heavy SALT"); - assert!(outcome.result.is_success(), "oracle system tx must succeed: {:?}", outcome.result); - executor.commit_transaction_outcome(outcome).expect("commit oracle system tx"); - - let oracle_after = executor - .evm - .db_mut() - .storage(ORACLE_CONTRACT_ADDRESS, ORACLE_SLOT) - .expect("oracle storage read"); - assert_eq!( - oracle_after, - U256::from_be_bytes(value.0), - "oracle slot must hold the written value after the exempt system tx", - ); -} - -// ============================================================================ -// 3. Determinism: system tx cost/state independent of bucket capacity -// ============================================================================ - -/// Runs the identical oracle system tx under light (1×) and heavy (100,000×) SALT, both REX6, and -/// asserts identical `gas_used` and identical resulting oracle state. This pins the core property: -/// a system-originated transaction's cost no longer depends on SALT bucket capacity. (Under REX5 -/// the heavy case would instead OOG.) -#[test] -fn test_rex6_system_tx_storage_gas_independent_of_bucket_capacity() { - fn run_oracle_tx(envs: TestExternalEnvs) -> (u64, U256) { - let mut state = State::builder().with_database(MemoryDatabase::default()).build(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(envs); - let executor_factory = MegaBlockExecutorFactory::new( - rex6_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = - executor_factory.create_executor(&mut state, block_ctx, rex6_evm_env(BLOCK_GAS_LIMIT)); - executor.evm.ctx.chain_mut().operator_fee_scalar = Some(U256::ZERO); - executor.evm.ctx.chain_mut().operator_fee_constant = Some(U256::ZERO); - executor.apply_pre_execution_changes().expect("pre-execution"); - - let value = B256::with_last_byte(0xCD); - let tx = oracle_system_tx(0, ORACLE_SLOT, value); - let outcome = executor.run_transaction(&tx).expect("oracle system tx must execute"); - assert!(outcome.result.is_success(), "must succeed: {:?}", outcome.result); - let gas_used = outcome.result.gas_used(); - executor.commit_transaction_outcome(outcome).expect("commit"); - let slot = executor - .evm - .db_mut() - .storage(ORACLE_CONTRACT_ADDRESS, ORACLE_SLOT) - .expect("oracle storage read"); - (gas_used, slot) - } - - let (gas_light, slot_light) = run_oracle_tx(light_external_envs()); - let (gas_heavy, slot_heavy) = run_oracle_tx(heavy_external_envs()); - - assert_eq!( - gas_light, gas_heavy, - "exempt system tx gas must be independent of SALT bucket capacity (light={gas_light}, heavy={gas_heavy})", - ); - assert_eq!( - slot_light, slot_heavy, - "resulting oracle state must be identical regardless of bucket capacity" - ); -} diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 7120d6575..3648942ce 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -17,12 +17,18 @@ use alloy_eips::{ }; use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ satin_gas_params, + system::{ + IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + }, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, BucketId, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, }; +use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; use revm::{ bytecode::opcode::{CALL, CREATE, CREATE2, PUSH0, RETURN, SELFDESTRUCT}, context::{result::EVMError, tx::TxEnvBuilder, TxEnv}, @@ -541,6 +547,138 @@ fn test_a_user_transaction_into_the_same_bucket_pays_the_crowded_price() { assert!(!evm.ctx().is_system_originated()); } +/* The sequencer's own system transaction. */ + +/// The Oracle slot the system transactions write. `setSlot` writes the raw slot number, so the +/// bucket a test crowds is the bucket the write lands in. +const ORACLE_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); + +/// The capacity the system-transaction arms crowd the Oracle's slot to. +const SYSTEM_TX_MULTIPLIER: u64 = 8; + +/// A database holding the Oracle, the registry naming [`MEGA_SYSTEM_ADDRESS`] the current system +/// address — which is what lets an Oracle write from it through — and a user contract to send +/// the control arm's transaction to. +fn system_tx_db() -> MemoryDatabase { + let user_code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, user_code) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE) + .account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + U256::from_be_slice(MEGA_SYSTEM_ADDRESS.as_slice()), + ) +} + +/// The sequencer's own system transaction: a legacy call from the system address to the +/// whitelisted Oracle, writing `ORACLE_SLOT`, which the engine promotes to a deposit. +fn oracle_system_tx() -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + data: IOracle::setSlotCall { slot: ORACLE_SLOT, value: B256::with_last_byte(0xAB) } + .abi_encode() + .into(), + chain_id: Some(1), + gas_limit: GAS_LIMIT, + ..Default::default() + })) +} + +/// `envs` with the Oracle's slot at multiplier `m`. +fn crowded_oracle_slot(m: u64) -> SaltEnvs { + crowded_slot(minimal_envs(), ORACLE_CONTRACT_ADDRESS, ORACLE_SLOT, m) +} + +/// The sequencer's system transaction prices at the minimum bucket: it pays the same state gas +/// whatever the capacity of the bucket it writes into, and never reads the SALT environment. +/// +/// This is the arm the system-origin predicate gained when the system transaction's definition +/// landed: the engine promotes it to a deposit, and a promoted system transaction is the +/// protocol running, so the growth of the Oracle's region cannot price the protocol out of +/// maintaining it. +#[test] +fn test_the_promoted_system_transaction_prices_at_the_minimum_bucket() { + let set = entry(GasId::sstore_set_state_gas()); + let mut spends = Vec::new(); + for m in [1, SYSTEM_TX_MULTIPLIER] { + let envs = crowded_oracle_slot(m); + let mut evm = MegaEvm::new(salt_context(system_tx_db(), envs.clone())); + let outcome = evm.execute_transaction(oracle_system_tx()).expect("the probe is valid"); + assert!(outcome.result.is_success(), "at m = {m}: {:?}", outcome.result); + + assert!(evm.ctx().is_system_originated(), "at m = {m}"); + assert_eq!(envs.total_bucket_queries(), 0, "at m = {m}: it reads no capacity at all"); + spends.push(outcome.gas.state); + } + + assert_eq!(spends[0], spends[1], "the two capacities cost the same"); + assert_eq!( + spends[0], + set + entry(GasId::new_account_state_gas()), + "and both charges are the schedule's own entries: the Oracle's write, and the account \ + the promoted deposit creates for the system address", + ); +} + +/// The pre-block system calls likewise: the same call priced across the same two capacities +/// costs the same, so a protocol-mandated write cannot be priced out either. +#[test] +fn test_a_pre_block_system_call_prices_the_same_at_any_capacity() { + use alloy_evm::Evm; + + let mut spends = Vec::new(); + for m in [1, SYSTEM_TX_MULTIPLIER] { + let envs = crowded_oracle_slot(m); + let data = IOracle::setSlotCall { slot: ORACLE_SLOT, value: B256::with_last_byte(0xCD) } + .abi_encode() + .into(); + let result = MegaEvm::new(salt_context(system_tx_db(), envs.clone())) + .transact_system_call(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, data) + .expect("the system call is valid"); + assert!(result.result.is_success(), "at m = {m}: {:?}", result.result); + + assert_eq!(envs.total_bucket_queries(), 0, "at m = {m}"); + spends.push(result.result.gas().state_gas_spent_final()); + } + + assert_eq!(spends[0], spends[1], "the two capacities cost the same"); + assert_eq!(spends[0], entry(GasId::sstore_set_state_gas())); +} + +/// The control arm: a user transaction in the same block, into a bucket crowded the same way, +/// still pays the crowded price. The exemption belongs to the protocol's own transactions, not +/// to the block they run in. +#[test] +fn test_a_user_transaction_in_the_same_block_still_pays_the_crowded_price() { + let set = entry(GasId::sstore_set_state_gas()); + let envs = crowded_slot( + crowded_oracle_slot(SYSTEM_TX_MULTIPLIER), + CONTRACT, + U256::ZERO, + SYSTEM_TX_MULTIPLIER, + ); + let mut evm = MegaEvm::new(salt_context(system_tx_db(), envs.clone())); + + let system = evm.execute_transaction(oracle_system_tx()).expect("the system probe is valid"); + assert!(system.result.is_success(), "{:?}", system.result); + assert_eq!( + system.gas.state, + set + entry(GasId::new_account_state_gas()), + "the system transaction is exempt", + ); + assert!(evm.ctx().is_system_originated()); + + let user = evm.execute_transaction(call_contract()).expect("the user probe is valid"); + assert!(user.result.is_success(), "{:?}", user.result); + assert_eq!(user.gas.state, set * SYSTEM_TX_MULTIPLIER, "the user transaction pays the crowd"); + assert!(!evm.ctx().is_system_originated()); + assert_eq!(envs.total_bucket_queries(), 1, "only the user transaction read a capacity"); +} + /// A deposit transaction is deliberately not system-originated, and pays the crowded price like /// any other transaction a user sends. A deposit is a shape a user can produce, so matching it /// here would be a way around the scaling. From fced20669bfca2e0d8a7dd629871bded14c91039 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 16:33:40 +0800 Subject: [PATCH 168/201] test(satin): assert what every interceptor path answers at both gas limits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pool matrix compared gas alone, so a fall-through into a contract's deployed bytecode satisfied a row meant to pin an interceptor's answer. Every row now says what the call must end as and asserts it at both limits, and the matrix covers every method the four contracts intercept, every value refusal, and the `keylessDeploy` call that cannot pay its overhead — the one branch a transaction cannot reach with a reservoir, reached through `frame_init` instead. --- .../tests/satin/synthetic_frame_gas.rs | 295 +++++++++++++++--- 1 file changed, 248 insertions(+), 47 deletions(-) diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index e70b09ae7..8e9752edc 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -1,20 +1,32 @@ //! Frame results `MegaETH` builds without running a frame carry the reservoir the frame //! inherited and settle like revm's own. +//! +//! The matrix at the end runs every method a system contract interceptor answers at a gas limit +//! under the execution cap, where a transaction has no reservoir, and at one far above it, where +//! the reservoir is the whole difference. One branch is not reachable that way: a `keylessDeploy` +//! call forwarded less regular gas than the fixed overhead. A transaction carries a reservoir only +//! when its gas limit is above the execution cap, and then its own frame is forwarded the cap +//! itself, which is far above the overhead — so that branch is reached through `frame_init` +//! instead. -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, system::{ - keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE}, - IMegaAccessControl, IMegaLimitControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + keyless::{ + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + IMegaAccessControl, IMegaLimitControl, IOracle, ACCESS_CONTROL_ADDRESS, + ACCESS_CONTROL_CODE, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, + ORACLE_CONTRACT_CODE, }, test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaEvm, }; use revm::{ - context::{ContextTr, JournalTr}, + context::{result::ExecutionResult, ContextTr, JournalTr}, handler::{EvmTr, FrameResult, ItemOrResult}, inspector::InspectorEvmTr, interpreter::{ @@ -54,6 +66,18 @@ fn call_frame_init(depth: usize) -> FrameInit { } } +/// [`call_frame_init`] carrying `data` to `to`, with `gas_limit` of regular gas. +fn call_frame_init_to(depth: usize, to: Address, data: Bytes, gas_limit: u64) -> FrameInit { + let mut init = call_frame_init(depth); + if let FrameInput::Call(inputs) = &mut init.frame_input { + inputs.target_address = to; + inputs.bytecode_address = to; + inputs.input = CallInput::Bytes(data); + inputs.gas_limit = gas_limit; + } + init +} + fn assert_call_too_deep(result: &FrameResult) { let FrameResult::Call(outcome) = result else { panic!("expected a call result: {result:?}") }; assert_eq!(outcome.result.result, InstructionResult::CallTooDeep); @@ -234,17 +258,65 @@ const NARROW: u64 = 100_000_000; /// A gas limit far above the execution cap: everything above the cap is the reservoir. const WIDE: u64 = 1_000_000_000; -/// Runs the same call to `to` at both gas limits and requires the reservoir to come back whole -/// and the two to cost the same: an answer that carried no reservoir would hand the caller an -/// empty pool and bill the sender for all of it. -fn assert_the_reservoir_survives(db: impl Fn() -> MemoryDatabase, to: Address, data: Bytes) { +/// What a call to a system contract must end as. +/// +/// The gas comparison alone cannot tell an interceptor's answer from a fall-through into the +/// contract's own bytecode — both cost the same at both gas limits — so every row of the matrix +/// says which of the two it expects, and says it at both limits. +#[derive(Clone, Debug)] +enum Expected { + /// The call succeeded with exactly these bytes. + Answer(Bytes), + /// The call reverted with exactly this data. + Revert(Bytes), + /// `remainingComputeGas` answers the regular gas its own frame was forwarded, the one answer + /// of the matrix that depends on the transaction's gas limit: under the execution cap it is + /// the transaction's limit less what pre-execution took, above the cap it is the cap's. So + /// the two answers differ by exactly what the cap holds back at the wider limit. + ForwardedRegularGas, +} + +/// Runs the same call to `to` at both gas limits and requires `expected` at both, the reservoir +/// to come back whole and the two to cost the same: an answer that carried no reservoir would +/// hand the caller an empty pool and bill the sender for all of it. +fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected: Expected) { let at = |gas_limit: u64| { - let tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); - let (result, _) = crate::common::run(db(), tx); - *result.result.gas() + let mut tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); + tx.0.base.value = value; + let (result, _) = crate::common::run(system_db(), tx); + let output = result.result.output().cloned().unwrap_or_default(); + match &expected { + Expected::Answer(answer) => { + assert!(result.result.is_success(), "at {gas_limit}: {:?}", result.result); + assert_eq!(&output, answer, "at a gas limit of {gas_limit}"); + } + Expected::Revert(revert_data) => { + assert!( + matches!(result.result, ExecutionResult::Revert { .. }), + "at {gas_limit}: {:?}", + result.result, + ); + assert_eq!(&output, revert_data, "at a gas limit of {gas_limit}"); + } + Expected::ForwardedRegularGas => { + assert!(result.result.is_success(), "at {gas_limit}: {:?}", result.result); + } + } + (*result.result.gas(), output) }; - let (narrow, wide) = (at(NARROW), at(WIDE)); + let ((narrow, narrow_answer), (wide, wide_answer)) = (at(NARROW), at(WIDE)); + if matches!(expected, Expected::ForwardedRegularGas) { + let forwarded = |answer: &Bytes| { + IMegaLimitControl::remainingComputeGasCall::abi_decode_returns(answer) + .expect("the answer is the method's own return type") + }; + assert_eq!( + forwarded(&wide_answer) - forwarded(&narrow_answer), + TX_GAS_LIMIT_CAP - NARROW, + "the answer is the forwarded regular gas, which the execution cap holds back", + ); + } assert_eq!(narrow.reservoir_remaining(), 0, "there is no pool below the cap"); assert_eq!( wide.reservoir_remaining(), @@ -258,61 +330,190 @@ fn assert_the_reservoir_survives(db: impl Fn() -> MemoryDatabase, to: Address, d ); } -/// A database holding what a call to a system contract needs: the contracts' code, and a -/// balance for the sender. +/// A database holding what a call to a system contract needs: the contracts' code, a balance for +/// the sender, and an account without code, which a transaction reaches for its intrinsic cost +/// alone. fn system_db() -> MemoryDatabase { MemoryDatabase::default() .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) + .account_balance(TARGET, U256::from(1)) .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE) .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) +} + +/// The calldata of a `keylessDeploy` call the dispatch recognises. +fn keyless_deploy_call() -> Bytes { + Bytes::from( + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode(), + ) } -/// Every answer a system contract interceptor gives carries the reservoir the frame inherited. +/// Every method a system contract interceptor answers carries the reservoir the frame inherited, +/// and answers what its own ABI names rather than falling through to the contract's bytecode. #[test] fn test_an_intercepted_answer_keeps_the_reservoir() { - for (to, selector) in [ - (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR), - (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR), - (LIMIT_CONTROL_ADDRESS, IMegaLimitControl::remainingComputeGasCall::SELECTOR), + let answers_nothing = Expected::Answer(Bytes::new()); + for (to, selector, expected) in [ + ( + ACCESS_CONTROL_ADDRESS, + IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR, + answers_nothing.clone(), + ), + ( + ACCESS_CONTROL_ADDRESS, + IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR, + answers_nothing, + ), + ( + ACCESS_CONTROL_ADDRESS, + IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR, + Expected::Answer(Bytes::from( + IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&false), + )), + ), + ( + LIMIT_CONTROL_ADDRESS, + IMegaLimitControl::remainingComputeGasCall::SELECTOR, + Expected::ForwardedRegularGas, + ), ] { - assert_the_reservoir_survives(system_db, to, Bytes::copy_from_slice(&selector)); + assert_the_reservoir_survives(to, Bytes::copy_from_slice(&selector), U256::ZERO, expected); } } -/// So does the refusal of a call that carries value to a method that takes none. +/// So does the refusal of a call that carries value to a method that takes none, on every method +/// of the two control contracts. #[test] fn test_an_intercepted_refusal_keeps_the_reservoir() { - let selector = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; - let at = |gas_limit: u64| { - let mut tx = crate::common::call_with_data( - CALLER, - ACCESS_CONTROL_ADDRESS, + let refused = + Expected::Revert(Bytes::from_static(&IMegaAccessControl::NonZeroTransfer::SELECTOR)); + for (to, selector) in [ + (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR), + (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR), + (ACCESS_CONTROL_ADDRESS, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR), + (LIMIT_CONTROL_ADDRESS, IMegaLimitControl::remainingComputeGasCall::SELECTOR), + ] { + assert_the_reservoir_survives( + to, Bytes::copy_from_slice(&selector), - gas_limit, + U256::from(1), + refused.clone(), ); - tx.0.base.value = U256::from(1); - let (result, _) = crate::common::run(system_db(), tx); - assert!(!result.result.is_success(), "the value is refused"); - *result.result.gas() - }; - let (narrow, wide) = (at(NARROW), at(WIDE)); - assert_eq!(narrow.reservoir_remaining(), 0); - assert_eq!(wide.reservoir_remaining(), WIDE - TX_GAS_LIMIT_CAP); - assert_eq!(narrow.tx_gas_used(), wide.tx_gas_used()); + } } -/// A dispatched `keylessDeploy` call is charged its overhead out of regular gas, so it costs -/// the same whether there is a pool or not, and the pool comes back whole. +/// The Oracle's hint is the one dispatch that answers nothing: it forwards the payload and lets +/// the contract's own bytecode run. What the matrix pins for it is that the pools reach that +/// bytecode untouched. #[test] -fn test_the_keyless_overhead_comes_out_of_regular_gas() { +fn test_a_forwarded_hint_keeps_the_reservoir() { let data = Bytes::from( - IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), - gasLimitOverride: U256::from(1_000_000), - } - .abi_encode(), + IOracle::sendHintCall { topic: B256::ZERO, data: Bytes::from_static(b"a hint") } + .abi_encode(), + ); + assert_the_reservoir_survives( + ORACLE_CONTRACT_ADDRESS, + data, + U256::ZERO, + Expected::Answer(Bytes::new()), ); - assert_the_reservoir_survives(system_db, KEYLESS_DEPLOY_ADDRESS, data); +} + +/// A dispatched `keylessDeploy` call is charged its overhead out of regular gas, so it costs the +/// same whether there is a pool or not and the pool comes back whole. The charge is not an +/// answer: the deployed bytecode runs after it and reverts with `NotIntercepted()`, because the +/// rewrite that turns the call into a deployment is not here yet. +#[test] +fn test_the_keyless_overhead_comes_out_of_regular_gas() { + assert_the_reservoir_survives( + KEYLESS_DEPLOY_ADDRESS, + keyless_deploy_call(), + U256::ZERO, + Expected::Revert(Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR)), + ); +} + +/// A `keylessDeploy` call that carries value is answered by the dispatch itself, with the ABI's +/// own `NoEtherTransfer()` and after the overhead was charged: the answer carries the reservoir, +/// and the overhead is charged once, at either gas limit. +#[test] +fn test_the_keyless_value_refusal_keeps_the_reservoir() { + let data = keyless_deploy_call(); + assert_the_reservoir_survives( + KEYLESS_DEPLOY_ADDRESS, + data.clone(), + U256::from(1), + Expected::Revert(Bytes::from_static(&IKeylessDeploy::NoEtherTransfer::SELECTOR)), + ); + + // The same transaction to an account without code spends its intrinsic cost and nothing + // else, and the refusal is answered before a frame runs, so what the dispatched call spends + // beyond it is the overhead — once. + let spent = |to: Address, gas_limit: u64| { + let mut tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); + tx.0.base.value = U256::from(1); + crate::common::run(system_db(), tx).0.result.gas().total_gas_spent() + }; + for gas_limit in [NARROW, WIDE] { + assert_eq!( + spent(KEYLESS_DEPLOY_ADDRESS, gas_limit) - spent(TARGET, gas_limit), + KEYLESS_DEPLOY_OVERHEAD_GAS, + "at a gas limit of {gas_limit}", + ); + } +} + +/// A `keylessDeploy` call forwarded less regular gas than the overhead is answered out of gas, +/// with the reservoir it inherited carried, and that answer settles into a caller exactly as +/// revm's own frame return settles a frame that ran out. +#[test] +fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { + use core::convert::Infallible; + + use mega_evm::settle_frame_result; + use revm::context::result::EVMError; + + let forwarded = KEYLESS_DEPLOY_OVERHEAD_GAS - 1; + let mut evm = MegaEvm::new(context(system_db())); + let init = call_frame_init_to(0, KEYLESS_DEPLOY_ADDRESS, keyless_deploy_call(), forwarded); + let ItemOrResult::Result(result) = + EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail") + else { + panic!("a call that cannot pay the overhead starts no frame"); + }; + let FrameResult::Call(outcome) = &result else { panic!("expected a call result: {result:?}") }; + assert_eq!(outcome.result.result, InstructionResult::OutOfGas); + assert!(outcome.result.output.is_empty()); + assert_eq!(outcome.result.gas.remaining(), 0, "an out-of-gas answer spends what it had"); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR, "the inherited reservoir is carried"); + + // The caller the answer goes back to, built as the settlement test above builds one. + let code = Bytes::from_static(&[revm::bytecode::opcode::STOP]); + let mut evm = MegaEvm::new(context(system_db().account_code(TARGET, code.clone()))); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account(TARGET).unwrap(); + let mut caller_init = call_frame_init(1); + if let FrameInput::Call(inputs) = &mut caller_init.frame_input { + let bytecode = revm::state::Bytecode::new_raw(code); + inputs.known_bytecode = (bytecode.hash_slow(), bytecode); + } + let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, caller_init).unwrap() else { + panic!("the caller frame is built"); + }; + + let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); + let caller_frame = frames.get(); + let mut expected = *caller_frame.interpreter.gas.tracker(); + settle_frame_result::<_, EVMError>(ctx, &mut expected, &mut result.clone()) + .unwrap(); + caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); + assert_eq!(caller_frame.interpreter.gas.tracker(), &expected); } From 825457ca8fda2791f8bf6c37d021c45800aef54d Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 16:39:13 +0800 Subject: [PATCH 169/201] docs(system): say what a selector that is not intercepted actually runs into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dispatch documented the fall-through as a revert with `NotIntercepted()`, which is the two control contracts' fallback and not a rule the other two keep: `KeylessDeploy` and the Oracle carry no fallback, so a selector they do not declare reverts with empty data, while a `keylessDeploy` call reaches the method body's own `NotIntercepted()`. The fall-through is now described as what it is — the deployed bytecode running — with the per-contract outcomes named, and the two empty-data answers are pinned. --- AGENTS.md | 3 ++- crates/mega-evm/README.md | 2 +- crates/mega-evm/src/system/AGENTS.md | 4 ++-- crates/mega-evm/src/system/intercept.rs | 15 ++++++++++++--- crates/mega-evm/src/system/keyless/dispatch.rs | 6 ++++-- crates/mega-evm/src/system/keyless/mod.rs | 7 ++++--- crates/mega-evm/tests/system/keyless.rs | 11 ++++++++++- crates/mega-evm/tests/system/oracle.rs | 8 +++++++- 8 files changed, 42 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a01cb6ece..2e2989884 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,7 +168,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer The test utilities' inspectors are not declared. - **The interceptor dispatch.** Its order is the scheme guard, the address, the selector, then the method's value policy, each step cheaper than the next: `CALLCODE` and `DELEGATECALL` never reach an interceptor, because they run the callee's code in the caller's context; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes; the selector is peeked without materialising the calldata behind it, and is admitted on its four bytes alone, trailing bytes and all. - A selector a contract does not intercept is not intercepted: the call falls through to the deployed bytecode, which reverts with `NotIntercepted()` on the contracts that carry that error, so an unrecognised call cannot succeed silently. + A selector a contract does not intercept is not intercepted: the call falls through, which is to say the deployed bytecode runs, and what it answers is that contract's own. + The two control contracts have a fallback that reverts with `NotIntercepted()`; `KeylessDeploy` has none, so a selector it does not declare reverts with empty data while a `keylessDeploy` call reaches the method body's `NotIntercepted()`; the Oracle's other selectors are methods it runs, and one it does not declare reverts with empty data. A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names, after the selector matched — so a value-bearing call to an unknown selector still falls through. An answer is a synthetic frame result and carries the reservoir; an interceptor that lets the frame run may charge it instead, by taking gas off the frame's limit. - **One hook prices every state charge.** diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 81d736319..d63deff5a 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -50,7 +50,7 @@ Without a SALT environment every bucket is minimal, so the numbers above are wha `tests/satin/pricing-table.md` shows two probes at three multipliers. The six system contracts live at their fixed `0x6342…` addresses, and four of them answer calls through an interceptor instead of running their bytecode. -A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input: `CALLCODE` and `DELEGATECALL` never reach an interceptor, and a selector a contract does not intercept falls through to the deployed bytecode, which reverts with `NotIntercepted()`. +A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input: `CALLCODE` and `DELEGATECALL` never reach an interceptor, and a selector a contract does not intercept falls through to the deployed bytecode, whose answer is that contract's own — the two control contracts revert with `NotIntercepted()` from their fallback, and `KeylessDeploy` and the Oracle, which have none, revert with empty data on a selector they do not declare. A method that takes no value answers a value-bearing call with `NonZeroTransfer()`. `MegaAccessControl` and `MegaLimitControl` answer with what the engine knows so far — nothing has switched volatile-data access off, and `remainingComputeGas()` reports the regular gas the call was forwarded — until detention and compute gas fill them in. The Oracle forwards a `sendHint` payload to the node's oracle service, and a `keylessDeploy` transaction is charged its fixed 100,000 gas and handed to the keyless rewrite hook that native keyless deployment fills in. diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index d0a947d94..59c78556f 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -16,7 +16,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch ## KEY PATTERNS - The dispatch order is: the scheme guard (`MegaEvm::intercept`), the address, the selector, then the method's value policy. Each step is cheaper than the next; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes. - A selector is admitted on its four bytes alone. Trailing bytes are accepted; an input shorter than four bytes is not a selector and is not admitted. -- An unknown selector is never intercepted: the call falls through to the deployed bytecode, which reverts with `NotIntercepted()` on the contracts that carry that error. +- An unknown selector is never intercepted: the call falls through to the deployed bytecode, and what that bytecode answers is the contract's own. The two control contracts revert with `NotIntercepted()` from their fallback; `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data while a `keylessDeploy` call reaches the method body's `NotIntercepted()`; the Oracle runs its other methods, and reverts with empty data on a selector it does not declare. - `CALL` and `STATICCALL` reach the dispatch. `CALLCODE` and `DELEGATECALL` run the callee's code in the caller's context, so they are refused by the scheme guard before any interceptor. - A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names (`KeylessDeploy` answers `NoEtherTransfer()`). The policy is per method and is applied after the selector matched, so a value-bearing call to an unknown selector still falls through. - An answer is a `synthetic_call_result`: the forwarded gas untouched, the caller's reservoir carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. @@ -26,7 +26,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - Accounts read during validation are read without warming them, so the transaction pays what any other transaction would pay for its first touch. ## ANTI-PATTERNS -- Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and a contract's stable error is what a caller decodes. +- Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and what it answers is the contract's own business. - Do not materialise calldata before the address and the selector matched. `peek_selector` borrows four bytes; `CallInput::bytes` copies the whole payload. - Do not build an answer from a bare gas limit. Use `synthetic_call_result`, which carries the reservoir and the upfront-charge flags. - Do not add a length check to a selector match. Admission is the four bytes. diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index 8e7fdcf90..a2b5c40d6 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -14,9 +14,18 @@ //! can be concerned, before a byte of calldata is read ([`intercepted_contract`]). //! 3. **The selector.** The contract's own dispatch peeks the first four bytes of the input //! ([`peek_selector`]) without materialising the rest. A selector the contract does not -//! intercept is *not* intercepted: the call falls through to the deployed bytecode, which -//! reverts with `NotIntercepted()`. A selector matches on its own four bytes, whatever follows -//! them. +//! intercept is *not* intercepted: the call falls through, which is to say the deployed bytecode +//! runs, and what that bytecode answers is the contract's own: +//! +//! - the two control contracts have a fallback that reverts with `NotIntercepted()`, so every +//! selector they do not intercept ends there; +//! - `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data; +//! a `keylessDeploy` call the dispatch did not take — one a contract makes — reaches the +//! method body and its own `NotIntercepted()`, as a dispatched one does after its charge; +//! - the Oracle's other selectors are methods it runs (`getSlot`, `version`), and one it does +//! not declare reverts with empty data. +//! +//! A selector matches on its own four bytes, whatever follows them. //! 4. **The value policy.** A method that takes no value answers a value-bearing call with //! `NonZeroTransfer()` ([`reject_non_zero_transfer`]), or with the error its own ABI names. The //! policy is per method, after the selector matched, so a value-bearing call to an unknown diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 4360ec4b9..133643156 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -29,8 +29,10 @@ use crate::{ /// Only a transaction reaches the deployment: `depth` is the depth of the frame the call would /// start, and a call a contract makes (`depth > 0`) is not dispatched, so the deployment's /// answer is never something an inner caller can read off its own return data. A call whose -/// selector is not `keylessDeploy` is not dispatched either; both run the deployed bytecode, -/// which reverts with `NotIntercepted()`. +/// selector is not `keylessDeploy` is not dispatched either. Both run the deployed bytecode, +/// which answers them differently: a `keylessDeploy` call reaches the method body and its +/// `NotIntercepted()`, while a selector the contract does not declare finds no function and no +/// fallback, so it reverts with empty data. /// /// # What it charges /// diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index e0b33e70b..ce8237db0 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -2,9 +2,10 @@ //! format, its validation rules and the error ABI. //! //! `keylessDeploy(bytes,uint256)` is intercepted; every other selector falls through to the -//! deployed bytecode, which reverts with `NotIntercepted()`. What the interceptor does today is -//! the dispatch and the fixed compute charge; turning the deployment into a native creation -//! belongs to native keyless deployment. +//! deployed bytecode, which carries no fallback and reverts with empty data. What the interceptor +//! does today is the dispatch and the fixed compute charge; turning the deployment into a native +//! creation belongs to native keyless deployment, so a dispatched call still runs the method body +//! and its `NotIntercepted()`. //! //! The rest of the module is data-only: decoding the pre-EIP-155 transaction, recovering its //! signer, deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. diff --git a/crates/mega-evm/tests/system/keyless.rs b/crates/mega-evm/tests/system/keyless.rs index 5836f4246..fa846c82e 100644 --- a/crates/mega-evm/tests/system/keyless.rs +++ b/crates/mega-evm/tests/system/keyless.rs @@ -107,7 +107,11 @@ fn test_a_call_from_a_contract_is_not_dispatched() { } /// A selector the contract does not know, and an input too short to hold one, are not -/// dispatched: the bytecode runs and reverts on its own. +/// dispatched: the bytecode runs and reverts on its own, with empty data. +/// +/// `KeylessDeploy` carries no fallback, so a selector it does not declare finds no function to +/// run; `NotIntercepted()` is what its `keylessDeploy` body reverts with, which is a call the +/// contract does declare. #[test] fn test_an_unknown_selector_is_not_dispatched() { let data = keyless_deploy(b"a transaction"); @@ -115,6 +119,11 @@ fn test_an_unknown_selector_is_not_dispatched() { { let result = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, &input, U256::ZERO)); assert!(!result.result.is_success()); + assert!( + revert_data(&result).is_empty(), + "an input of {} bytes reverted with data the contract has no code to return", + input.len(), + ); assert!( result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS, "an input of {} bytes paid an overhead it does not owe", diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index d7af5f0bc..d602e6127 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -178,7 +178,8 @@ fn test_callcode_and_delegatecall_forward_nothing() { } /// A selector the Oracle's interceptor does not know is not intercepted: the call runs the -/// contract's bytecode, which reverts on an unknown selector. +/// contract's bytecode, which reverts with empty data on a selector it does not declare — the +/// Oracle carries no fallback of its own. #[test] fn test_an_unknown_selector_runs_the_bytecode() { let (result, hints, usage) = run_with_oracle( @@ -186,6 +187,11 @@ fn test_an_unknown_selector_runs_the_bytecode() { call_tx(ORACLE_CONTRACT_ADDRESS, [0xde, 0xad, 0xbe, 0xef], U256::ZERO), ); assert!(!result.result.is_success(), "the Oracle has no such method"); + assert_eq!( + result.result.output().cloned().unwrap_or_default(), + Bytes::new(), + "the contract has no code to answer a selector it does not declare", + ); assert!(hints.is_empty()); assert_eq!(usage.data_size, 0); } From b085833ed7ba9a5bca61be8a7870f5b6b5296d1a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 16:43:03 +0800 Subject: [PATCH 170/201] docs(system): separate the hint rule carried over from the one this engine adds The zero-gas suppression is the legacy engine's own and is kept; the value suppression is what is new. Positive gas is not a promise that the bytecode runs either: a hint forwarded with one gas reaches the service and the frame then runs out of gas, which a test now pins. An admitted hint is a synchronous, irreversible side effect whatever the frame does afterwards. --- crates/mega-evm/src/system/oracle.rs | 18 +++++++++---- crates/mega-evm/tests/system/oracle.rs | 36 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index 853ce89d1..c7fd6f4e6 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -30,12 +30,20 @@ pub use mega_system_contracts::oracle::IOracle; /// effect rather than an answer. The Oracle's storage methods are ordinary code, and reading /// its storage through the node's oracle service is the Host's business. /// -/// The hint is forwarded only by a call that can deliver it: +/// Two conditions admit a hint, and neither is a statement about the frame that runs afterwards: /// -/// - the call carries no value: `sendHint` is not payable, so a value-bearing call reverts in the -/// bytecode and its hint would be one the caller never sent; -/// - the call was forwarded gas: a call with none cannot run the dispatcher of the bytecode, so it -/// reverts, and its hint would be a free message to the service. +/// - the call was forwarded gas. A call with none cannot run the dispatcher of the bytecode at all, +/// so its hint would be a free message to the service; +/// - the call carries no value. `sendHint` is not payable, so a value-bearing call reverts in the +/// bytecode and its hint would be one the caller never sent. +/// +/// The gas condition is the legacy engine's, carried over; the value condition is new. +/// +/// Gas above zero does not promise that the bytecode succeeds: a hint forwarded with one gas +/// reaches the service and the frame it was sent from then runs out of gas. An admitted hint is a +/// synchronous, irreversible side effect — the service holds it whatever the frame, or the +/// transaction, does next. That is also why its bytes are counted on the transaction rather than +/// on the frame. /// /// A `STATICCALL` does forward: `sendHint` is a view method and writes nothing. /// diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index d602e6127..4563c06b0 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -164,6 +164,42 @@ fn test_a_call_without_gas_forwards_nothing() { assert_eq!(usage.data_size, 0); } +/// A call forwarded one gas does forward its hint, and the frame it was sent from then runs out +/// of gas: positive gas is what admits a hint, not a promise that the bytecode can run. The hint +/// is a synchronous side effect, so the service holds it whatever the frame does next. +#[test] +fn test_a_call_with_one_gas_forwards_the_hint_it_cannot_deliver() { + use revm::bytecode::opcode::{MSTORE, RETURN}; + + let data = send_hint(b"one gas"); + let code = BytecodeBuilder::default() + .mstore(0x0, &data) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(1_u64) // gas: enough to admit the hint, not to run the bytecode + .append(CALL) + // memory[0..32] = the call's status, and return it + .push_number(0_u64) + .append(MSTORE) + .push_number(32_u64) + .push_number(0_u64) + .append(RETURN) + .build(); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + assert!(result.result.is_success(), "the caller survives the failed call"); + let outcome = result.result.output().cloned().unwrap_or_default(); + let (status, _) = crate::common::split_outcome(&outcome); + assert!(!status, "one gas does not run the contract's dispatcher"); + assert_eq!(hints.len(), 1, "the hint reached the service before the frame ran out of gas"); + assert_eq!(usage.data_size, data.len() as u64, "and its bytes stay counted"); +} + /// `CALLCODE` and `DELEGATECALL` never reach the interceptor, so they forward nothing. #[test] fn test_callcode_and_delegatecall_forward_nothing() { From 5ba718985e80a0c065e5b4d9824c075ab2b47ea5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 16:46:44 +0800 Subject: [PATCH 171/201] test(satin): name the floor the keyless receipts are measured against The case asserted that the two receipts differ by less than the charge without saying why. It now pins the floor itself, computed by revm from the schedule both engines run on: Satin's receipt is its own raw spend, and op-revm's is the transaction's EIP-7623 floor. --- crates/mega-evm/tests/satin/equivalence.rs | 39 ++++++++++++++++++---- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 7ead03790..69debde23 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -27,6 +27,7 @@ use revm::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, + context_interface::cfg::gas_params::Eip2780TxInfo, inspector::NoOpInspector, state::EvmState, ExecuteEvm, Journal, @@ -398,15 +399,16 @@ fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { let db = MemoryDatabase::default() .account_balance(CALLER, U256::from(10u64.pow(18))) .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); + let data: Bytes = IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode() + .into(); let tx = TxEnv { caller: CALLER, kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), - gasLimitOverride: U256::from(1_000_000), - } - .abi_encode() - .into(), + data: data.clone(), gas_limit: 1_000_000, ..Default::default() }; @@ -426,6 +428,31 @@ fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { // The two run the same bytecode on the same input, so the whole difference is the charge. let charged = mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(); assert_eq!(charged, KEYLESS_DEPLOY_OVERHEAD_GAS, "the divergence is the overhead, exactly"); + + // Which floor, exactly: the one this transaction's own calldata buys, computed by revm from + // the schedule both engines run on. Satin is above it and reports what it spent; op-revm is + // below it and reports the floor, so the receipts differ by less than the charge. + let floor = cfg + .gas_params + .initial_tx_gas( + &data, + false, + 0, + 0, + 0, + Some(Eip2780TxInfo { value: U256::ZERO, is_self_transfer: false }), + ) + .floor_gas(); + assert_eq!( + mega.result.gas().tx_gas_used(), + mega.result.gas().total_gas_spent(), + "Satin spends past the floor, so its receipt is its own spend", + ); + assert_eq!( + op.result.gas().tx_gas_used(), + floor, + "op-revm spends below the floor, so its receipt is the floor", + ); assert!( mega.result.gas().tx_gas_used() - op.result.gas().tx_gas_used() < charged, "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", From 07d36b2d62c31b6155fafc8f545195ac1174f25b Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:39:14 +0800 Subject: [PATCH 172/201] test(satin): tell the authority's nonce from the delegate's in a delegated creation The port left both nonces at zero, where the address the authority's own nonce derives and the address the delegate's nonce derives from the authority are the same address, so the arm could not see a creation priced at the delegate's nonce. Give the two accounts different nonces and crowd the three candidate addresses in turn: the authority's own, the one the delegate's nonce would derive from it, and the one the delegate's own address derives. Only the first is read, and it is where the frame deploys. --- .../mega-evm/tests/satin/salt_delegation.rs | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt_delegation.rs b/crates/mega-evm/tests/satin/salt_delegation.rs index e3705a63e..7684a4b87 100644 --- a/crates/mega-evm/tests/satin/salt_delegation.rs +++ b/crates/mega-evm/tests/satin/salt_delegation.rs @@ -206,29 +206,62 @@ fn test_a_value_call_to_a_truly_empty_address_pays_the_crowded_price() { /// A `CREATE` executed inside a delegated frame deploys from the delegating account, so the /// charge lands in the bucket of the address *that* account's nonce derives — not the delegate's. +/// +/// The two accounts carry different nonces, which is what tells the three candidate addresses +/// apart: the authority's address with its own nonce is where the frame deploys and what the +/// charge must be priced at; the authority's address with the delegate's nonce, and the +/// delegate's address with its own nonce, are the two ways of reading the designator too far. +/// With both nonces at zero the first two collapse into one address and the regression this +/// guards — the delegate's nonce used with the authority's address — cannot be seen. #[test] fn test_a_create_inside_a_delegated_frame_is_priced_at_the_authority_s_address() { const AUTHORITY: Address = address!("0000000000000000000000000000000000c00013"); const CODE: Address = address!("0000000000000000000000000000000000c00014"); - let created = AUTHORITY.create(0); - let delegate_created = CODE.create(0); + /// The nonce the authority carries, which derives the address the frame deploys at. + const AUTHORITY_NONCE: u64 = 5; + /// The nonce the delegate carries, which derives nothing here. + const DELEGATE_NONCE: u64 = 0; - let db = db(calls(AUTHORITY)).account_code(CODE, creates(CREATE)); - let db = with_delegation(db, AUTHORITY, CODE); + let created = AUTHORITY.create(AUTHORITY_NONCE); + let from_delegate_nonce = AUTHORITY.create(DELEGATE_NONCE); + let from_delegate_address = CODE.create(DELEGATE_NONCE); + assert_ne!(created, from_delegate_nonce, "the two nonces must derive different addresses"); + assert_ne!(created, from_delegate_address); + + let build = || { + let db = db(calls(AUTHORITY)) + .account_code(CODE, creates(CREATE)) + .account_nonce(CODE, DELEGATE_NONCE) + .account_balance(AUTHORITY, U256::from(1_000_000u64)) + .account_nonce(AUTHORITY, AUTHORITY_NONCE); + with_delegation(db, AUTHORITY, CODE) + }; let envs = crowded_account(minimal_envs(), created, 8); - let outcome = run(db.clone(), envs.clone(), call_contract()); + let outcome = run(build(), envs.clone(), call_contract()); assert_eq!( outcome.gas.state, entry(GasId::create_state_gas()) * 8, "the authority's own address is what was priced", ); assert_eq!(envs.bucket_queries(account_bucket(created)), 1); + assert!( + outcome.state.contains_key(&created), + "and the authority's own address is where the frame deployed", + ); + + // Crowding the address the delegate's nonce would derive from the authority changes + // nothing, and that bucket is never read. + let envs = crowded_account(minimal_envs(), from_delegate_nonce, 8); + let outcome = run(build(), envs.clone(), call_contract()); + assert_eq!(outcome.gas.state, entry(GasId::create_state_gas())); + assert_eq!(envs.bucket_queries(account_bucket(from_delegate_nonce)), 0); - // Crowding the address the delegate's own nonce would derive changes nothing. - let envs = crowded_account(minimal_envs(), delegate_created, 8); - let outcome = run(db, envs, call_contract()); + // Nor does crowding the address the delegate's own address and nonce derive. + let envs = crowded_account(minimal_envs(), from_delegate_address, 8); + let outcome = run(build(), envs.clone(), call_contract()); assert_eq!(outcome.gas.state, entry(GasId::create_state_gas())); + assert_eq!(envs.bucket_queries(account_bucket(from_delegate_address)), 0); } /* CALLCODE: value that never leaves the caller's account. */ From a1c90bf926f25b6226f666086e17864b9a1cd695 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:42:31 +0800 Subject: [PATCH 173/201] test(satin): settle a crowded upfront charge through the synthetic helper The refund matrix left two routes unpinned at a non-minimum capacity. The public settlement helper was only exercised over a plain context on the flat schedule, so nothing proved it gives a SALT-priced upfront charge back; and the one deposit arm returns 0xEF, which validation refuses before a deposit charge is ever made, so no rolled-back deposit charge was covered either. Charge a call and a creation through the pricing hook at eight times the minimum bucket, carry the site and the upfront flags into a synthetic failure and settle it: both pools land where they started, the state ledger nets zero and one capacity read priced charge and refund alike, whether the reservoir covered the charge or it spilled onto regular gas. Beside it, a creation whose init code writes a crowded slot and then cannot pay for the bytes it returns: both charges are made, priced and then rolled back, with a control whose deposit fits and keeps all three. The 0xEF arm says what it actually covers. --- crates/mega-evm/tests/satin/salt_refund.rs | 237 ++++++++++++++++++++- 1 file changed, 230 insertions(+), 7 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 3ea6a87e1..28a5a294b 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -17,20 +17,28 @@ //! later: the delegation it wrote survives the revert, so the state gas it paid must survive it //! too. -use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ + settle_frame_result, synthetic_frame_result, test_utils::{BytecodeBuilder, MemoryDatabase}, MegaEvm, MegaTransaction, MegaTransactionOutcome, }; use revm::{ bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, - context_interface::cfg::GasId, + context_interface::{ + cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, + Host, + }, + interpreter::{ + CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, + InstructionResult, + }, }; use crate::salt::{ - authorization_tx, call_contract, capacity, create_with, crowded_account, crowded_slot, db, - entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, try_run, tx, SaltEnvs, - AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, + account_bucket, authorization_tx, call_contract, capacity, create_with, crowded_account, + crowded_slot, db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, + try_run, tx, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, }; /// The contract a probe's inner frame runs in. @@ -286,8 +294,10 @@ fn test_an_applied_authorization_keeps_its_charge_through_a_revert() { ); } -/// A creation whose deposit is refused gives back everything it charged: the account leaf it -/// paid for upfront and the bytes it never deposited. +/// A creation whose deployed code is refused before any deposit charge is made: EIP-3541 turns +/// down a runtime code starting `0xEF` at validation, so the only state gas in play is the +/// account leaf the transaction's own create target was charged for upfront, which comes back. +/// The arm below it is the one where a deposit charge really is made and then rolled back. #[test] fn test_a_refused_code_deposit_pays_no_state_gas() { let created = CALLER.create(0); @@ -414,3 +424,216 @@ fn test_the_capacity_behind_a_charge_and_its_refill_is_read_once() { assert_eq!(outcome.gas.state, 0, "every set was restored"); assert_eq!(envs.bucket_queries(bucket), 1, "two charges and two refills, one capacity read"); } + +/* The refund route that runs without a frame. */ + +/// The address a synthetic frame would have added a leaf at. +const SYNTHETIC_TARGET: Address = address!("0000000000000000000000000000000000c00008"); + +/// The regular gas a caller forwards to the frame the probes below answer without running it. +const FORWARDED: u64 = 9_000; + +/// The caller's own regular gas limit in those probes, wide enough for a crowded charge to spill +/// onto it in full. +const CALLER_LIMIT: u64 = 5_000_000; + +/// The capacity the synthetic-settlement probes crowd their site to. +const SYNTHETIC_MULTIPLIER: u64 = 8; + +/// What one synthetic settlement did: the caller's tracker afterwards, the price the charge was +/// made at, and how much of that charge spilled onto regular gas when it was made. +struct Settled { + caller: GasTracker, + price: u64, + spilled: u64, +} + +/// Charges `charge` through the pricing hook of a context reading `envs`, hands the frame the +/// reservoir the caller has left, and settles a synthetic failure for it through the public +/// helper — the route a mechanism takes when it answers a frame rather than running it. +fn settle_a_synthetic_failure( + envs: &SaltEnvs, + reservoir: u64, + charge: StateGasCharge, + input: impl FnOnce(u64) -> FrameInput, +) -> Settled { + let mut ctx = salt_context(db(Bytes::new()), envs.clone()); + let price = ctx.state_gas_charge(charge).expect("the bucket is readable"); + + let mut caller = GasTracker::new(CALLER_LIMIT, CALLER_LIMIT - FORWARDED, reservoir); + assert!(caller.record_state_cost(price), "the caller can pay the crowded charge"); + let spilled = caller.state_gas_spilled(); + + let mut result = + synthetic_frame_result(&input(caller.reservoir()), InstructionResult::Revert, Bytes::new()); + settle_frame_result::<_, revm::context::result::EVMError>( + &mut ctx, + &mut caller, + &mut result, + ) + .expect("the refund is priced through the same hook"); + + Settled { caller, price, spilled } +} + +/// The inputs of a `CALL` whose calling opcode charged the caller for the account it would add. +fn charged_call_input(reservoir: u64) -> FrameInput { + FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: FORWARDED, + bytecode_address: SYNTHETIC_TARGET, + known_bytecode: Default::default(), + target_address: SYNTHETIC_TARGET, + caller: CALLER, + value: CallValue::Transfer(U256::from(1)), + scheme: CallScheme::Call, + is_static: false, + reservoir, + charged_new_account_state_gas: true, + })) +} + +/// The inputs of a `CREATE` whose calling opcode charged the caller for the account it would +/// deploy. +fn charged_create_input(reservoir: u64) -> FrameInput { + let mut inputs = CreateInputs::new( + CALLER, + CreateScheme::Create, + U256::ZERO, + Bytes::new(), + FORWARDED, + reservoir, + ); + inputs.set_charged_create_state_gas(true); + inputs.set_charged_state_gas_address(SYNTHETIC_TARGET); + FrameInput::Create(Box::new(inputs)) +} + +/// Requires a settlement to have put both pools back exactly where they were before the charge, +/// with the state ledger net zero and one capacity read behind the charge and the refill alike. +fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settled: &Settled) { + let caller = &settled.caller; + assert_eq!(caller.remaining(), CALLER_LIMIT, "{site}: the regular pool comes back whole"); + assert_eq!(caller.reservoir(), reservoir, "{site}: and so does the reservoir"); + assert_eq!(caller.state_gas_spent(), 0, "{site}: the state ledger nets zero"); + assert_eq!(caller.state_gas_spilled(), 0, "{site}: nothing is left spilled"); + assert_eq!( + envs.bucket_queries(account_bucket(SYNTHETIC_TARGET)), + 1, + "{site}: one capacity read priced the charge and the refund", + ); +} + +/// A synthetic `CALL` failure settled through the public helper gives back a SALT-priced upfront +/// charge, both when the reservoir paid for it and when it spilled onto regular gas. +#[test] +fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { + let crowded = entry(GasId::new_account_state_gas()) * SYNTHETIC_MULTIPLIER; + let charge = StateGasCharge::one( + GasId::new_account_state_gas(), + StateGasSite::account(SYNTHETIC_TARGET), + ); + + // The reservoir covers the whole charge. + let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); + let settled = settle_a_synthetic_failure(&envs, CALLER_LIMIT, charge, charged_call_input); + assert_eq!(settled.price, crowded, "the charge was priced at the crowded bucket"); + assert_eq!(settled.spilled, 0, "and the reservoir paid for all of it"); + assert_restores_both_pools("a call from the reservoir", &envs, CALLER_LIMIT, &settled); + + // The reservoir covers part of it and the rest spills onto regular gas. + let reservoir = crowded / 4; + let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); + let settled = settle_a_synthetic_failure(&envs, reservoir, charge, charged_call_input); + assert_eq!(settled.price, crowded); + assert_eq!(settled.spilled, crowded - reservoir, "the rest of the charge spilled"); + assert_restores_both_pools("a call that spilled", &envs, reservoir, &settled); +} + +/// The same for a synthetic `CREATE` failure, whose upfront charge is the creation entry at the +/// address the frame would have deployed to. +#[test] +fn test_a_synthetic_creation_failure_refunds_the_crowded_upfront_charge() { + let crowded = entry(GasId::create_state_gas()) * SYNTHETIC_MULTIPLIER; + let charge = + StateGasCharge::one(GasId::create_state_gas(), StateGasSite::account(SYNTHETIC_TARGET)); + + let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); + let settled = settle_a_synthetic_failure(&envs, CALLER_LIMIT, charge, charged_create_input); + assert_eq!(settled.price, crowded, "the charge was priced at the crowded bucket"); + assert_eq!(settled.spilled, 0); + assert_restores_both_pools("a creation from the reservoir", &envs, CALLER_LIMIT, &settled); + + let reservoir = crowded / 4; + let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); + let settled = settle_a_synthetic_failure(&envs, reservoir, charge, charged_create_input); + assert_eq!(settled.price, crowded); + assert_eq!(settled.spilled, crowded - reservoir); + assert_restores_both_pools("a creation that spilled", &envs, reservoir, &settled); +} + +/* A deposit charge that is made and then rolled back. */ + +/// How many bytes of runtime code the creation below deploys when its deposit is meant to fail. +/// At the crowded price a byte costs `code_deposit_state_gas x 8`, so this many bytes is far +/// beyond what the transaction brought. +const UNAFFORDABLE_CODE: u64 = 20_000; + +/// How many it deploys when the deposit is meant to go through. +const AFFORDABLE_CODE: u64 = 32; + +/// A creation whose init code writes a slot in a crowded bucket and then returns `deployed` +/// bytes of runtime code, run from [`CONTRACT`] so the transaction outlives the creation. +fn creation_depositing(deployed: u64) -> MemoryDatabase { + let init = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .push_number(deployed) + .append(PUSH0) + .append(RETURN) + .build(); + db(create_with(&init).stop().build()) +} + +/// A creation that runs out of gas paying for its code deposit takes back both of the charges it +/// made: the slot its init code wrote in a crowded bucket, and the account leaf the `CREATE` +/// opcode charged its caller for upfront. The outer frame stops after the failed creation, so +/// the transaction settles and reports what it kept. +#[test] +fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { + let created = CONTRACT.create(0); + let crowd = |envs| { + let envs = crowded_account(envs, created, SYNTHETIC_MULTIPLIER); + crowded_slot(envs, created, U256::from(SLOT), SYNTHETIC_MULTIPLIER) + }; + + let envs = crowd(minimal_envs()); + let outcome = run(creation_depositing(UNAFFORDABLE_CODE), envs.clone(), call_contract()); + assert_eq!(outcome.gas.state, 0, "the failed creation kept neither charge"); + assert_eq!( + envs.bucket_queries(slot_bucket(created, U256::from(SLOT))), + 1, + "the init code did write the slot, and it was priced before the deposit failed", + ); + assert_eq!(envs.bucket_queries(account_bucket(created)), 1, "and so was the account leaf"); + assert!( + outcome.state.get(&created).is_none_or(|account| account + .info + .code + .as_ref() + .is_none_or(|code| code.is_empty())), + "and nothing was deployed", + ); + + // The control: the same program with a deposit it can pay keeps all three charges, scaled. + let envs = crowd(minimal_envs()); + let outcome = run(creation_depositing(AFFORDABLE_CODE), envs, call_contract()); + assert_eq!( + outcome.gas.state, + (entry(GasId::create_state_gas()) + + entry(GasId::sstore_set_state_gas()) + + entry(GasId::code_deposit_state_gas()) * AFFORDABLE_CODE) * + SYNTHETIC_MULTIPLIER, + "the creation, the slot its init code wrote and the bytes it deposited", + ); +} From 5992b0e5c7967403ad4cc387d08dad99c4c37af0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:42:45 +0800 Subject: [PATCH 174/201] docs(satin): say which refunds re-price and which roll back by amount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The refund tests' header still described all three refund moments as re-pricing the charge through the hook. Four sites do — the restore, a caller's upfront charge, the transaction-level refund and a synthetic settlement — while a frame that fails rolls its own charges back by the amounts it recorded, asking for no price at all. Both cancel exactly, for different reasons; the header now says which is which. --- crates/mega-evm/tests/satin/salt_refund.rs | 24 +++++++++++++--------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 28a5a294b..cd77ab9ed 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -1,17 +1,21 @@ //! SALT pricing: giving a state gas charge back at the price it was made at. //! -//! A state charge is undone at three kinds of moment, and all three re-price the charge that was -//! made rather than looking the number up again from somewhere else: +//! A state charge is undone in two shapes, and neither of them reads a second table. //! -//! - the same opcode takes its own write back (`SSTORE` 0 -> x -> 0), -//! - a frame that made a charge, or a frame whose child did not create the leaf the charge paid -//! for, does not survive, and -//! - the transaction itself reverts. +//! One shape names the charge and asks the hook for its price again: the same opcode taking its +//! own write back (`SSTORE` 0 -> x -> 0), the upfront charge a caller made for a call or a +//! creation that did not add the leaf after all, the transaction-level refund, and the +//! settlement of a frame result built without running a frame. Because the site is re-priced +//! through the one hook, and because the multiplier of a bucket is read once per transaction, +//! the refill is the charge — a bucket cannot be read at one capacity for the charge and another +//! for the refill. //! -//! Because the site is re-priced through the one hook, and because the multiplier of a bucket is -//! read once per transaction, the refill is the charge — a bucket cannot be read at one capacity -//! for the charge and another for the refill. These tests pin that: what is fully undone nets -//! zero at every multiplier, what is kept scales, and the environment is asked once. +//! The other shape asks for no price at all: a frame that fails rolls its own charges back by +//! the amounts it recorded while running. Nothing but the hook priced those amounts, so they +//! cancel exactly whatever the price was. +//! +//! These tests pin both: what is fully undone nets zero at every multiplier, what is kept +//! scales, and the environment is asked once. //! //! Against that, an applied EIP-7702 authorization is *not* undone by a frame that reverts //! later: the delegation it wrote survives the revert, so the state gas it paid must survive it From 0fd2fbacf7fa3050ace86b90e2803d1d3876a61e Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:43:36 +0800 Subject: [PATCH 175/201] test(satin): retire the rows a single-spec engine leaves no gate to pin Four parked rows pin a helper at a legacy spec boundary: it is served from one rung and asserts below it, so a tightened or loosened gate fails them. Satin is a single spec and has no gate of its own, so no later mechanism can port them. They move to the retired table with that reason and leave the parked file, which then holds nothing and goes with them. --- crates/mega-evm/tests/_pending/README.md | 10 +-- .../tests/_pending/src/external/gas.rs | 62 ------------------- 2 files changed, 5 insertions(+), 67 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/src/external/gas.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index a65491af7..90dd1bfb9 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,7 +28,7 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 8 | 4 | 4 | 0 | 8 | 0 | +| SALT pricing | 4 | 4 | 0 | 0 | 4 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +41,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **532** | **461** | **71** | **311** | **193** | **28** | +| **Total** | **528** | **461** | **67** | **311** | **189** | **28** | ## Tests ported in place @@ -205,14 +205,15 @@ These 61 rows run in a real test target now, adapted to the Satin API and to the ## Tests retired after the inventory -These 4 rows were parked when the inventory was applied and have since been retired: the mechanism that owns them landed and left them nothing to pin, so no later mechanism will port them. +These 8 rows were parked when the inventory was applied and have since been retired: the mechanism that owns them landed and left them nothing to pin, so no later mechanism will port them. They are not counted above. | Legacy file | Owner in the inventory | Tests | Why | |---|---|---:|---| | `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | Satin's `CALLCODE` cannot reach a state gas pricing site: it sends value to the frame's own account, which exists, so it adds no account leaf and asks for no price. There is no pricing-path account inspection left to fail | | `src/evm/host.rs` | SALT pricing (1) | 1 | the pricing hook inspects no account: the fork decides whether a target exists and the hook only prices what it is told to, so there is no delegation walk on the pricing path to guard | -| **Total** | | **4** | | +| `src/external/gas.rs` | SALT pricing (4) | 4 | these pin a helper at a legacy spec boundary: it is served from one rung and asserts below it. Satin is a single spec and has no gate of its own, so there is no boundary left for them to pin | +| **Total** | | **8** | | ## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism @@ -280,7 +281,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | | `src/access/volatile.rs` | 4 | keep 4 (detention) | | `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | -| `src/external/gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D51) | | `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | | `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | | `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | diff --git a/crates/mega-evm/tests/_pending/src/external/gas.rs b/crates/mega-evm/tests/_pending/src/external/gas.rs deleted file mode 100644 index 2957676b1..000000000 --- a/crates/mega-evm/tests/_pending/src/external/gas.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/external/gas.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/gas.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::external::test_utils::TestExternalEnvs; - - fn cost_with_capacity(spec: MegaSpecId, capacity: u64) -> DynamicGasCost { - // Map the bucket id that the simple bucket hasher will produce for the zero address / - // zero slot to the requested capacity. - let bucket_for_account = - ::bucket_id_for_account(Address::ZERO); - let bucket_for_slot = - ::bucket_id_for_slot(Address::ZERO, U256::ZERO); - let env = TestExternalEnvs::new() - .with_bucket_capacity(bucket_for_account, capacity) - .with_bucket_capacity(bucket_for_slot, capacity); - DynamicGasCost::new(spec, env, 0) - } - - /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX - /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a - /// tightened gate (e.g. REX1) fails here. - #[test] - fn test_unscaled_gas_is_available_from_rex_exactly() { - let cost = cost_with_capacity(MegaSpecId::REX, MIN_BUCKET_SIZE as u64); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - - /// Pre-REX callers must trip the debug assert — a loosened gate (e.g. `MiniRex`) would - /// silently serve the REX-family formula to a spec that prices storage differently. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_sstore_set_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .sstore_set_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_new_account_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .new_account_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_create_contract_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .create_contract_gas_unscaled(); - } - -} From 86cf1d09e74438cf637d7985521f3c97f7982d50 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:46:17 +0800 Subject: [PATCH 176/201] test(satin): check what the promoted system transaction left behind The arm compared only the state ledger and the capacity reads across the two bucket sizes, so it could have passed on a transaction that priced correctly and wrote nothing. Read the Oracle slot back out of the state the transaction produced, and compare the whole receipt rather than its state ledger alone. --- crates/mega-evm/tests/satin/salt.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 3648942ce..0416efeef 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -604,6 +604,7 @@ fn crowded_oracle_slot(m: u64) -> SaltEnvs { fn test_the_promoted_system_transaction_prices_at_the_minimum_bucket() { let set = entry(GasId::sstore_set_state_gas()); let mut spends = Vec::new(); + let mut receipts = Vec::new(); for m in [1, SYSTEM_TX_MULTIPLIER] { let envs = crowded_oracle_slot(m); let mut evm = MegaEvm::new(salt_context(system_tx_db(), envs.clone())); @@ -612,10 +613,20 @@ fn test_the_promoted_system_transaction_prices_at_the_minimum_bucket() { assert!(evm.ctx().is_system_originated(), "at m = {m}"); assert_eq!(envs.total_bucket_queries(), 0, "at m = {m}: it reads no capacity at all"); + assert_eq!( + written_oracle_slot(&outcome), + U256::from_be_bytes(B256::with_last_byte(0xAB).0), + "at m = {m}: the Oracle slot holds what the transaction wrote", + ); spends.push(outcome.gas.state); + receipts.push(outcome.gas.gas_used); } assert_eq!(spends[0], spends[1], "the two capacities cost the same"); + assert_eq!( + receipts[0], receipts[1], + "and so does the whole receipt, not only its state ledger", + ); assert_eq!( spends[0], set + entry(GasId::new_account_state_gas()), @@ -624,6 +635,18 @@ fn test_the_promoted_system_transaction_prices_at_the_minimum_bucket() { ); } +/// What [`ORACLE_SLOT`] holds in the state a probe produced. +fn written_oracle_slot(outcome: &MegaTransactionOutcome) -> U256 { + outcome + .state + .get(&ORACLE_CONTRACT_ADDRESS) + .expect("the Oracle is in the transaction's state") + .storage + .get(&ORACLE_SLOT) + .expect("the write reached the slot") + .present_value +} + /// The pre-block system calls likewise: the same call priced across the same two capacities /// costs the same, so a protocol-mandated write cannot be priced out either. #[test] From 3ac797f67f8060fcdc04d97602e01e2a285636d0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 17:46:27 +0800 Subject: [PATCH 177/201] test(block): run the pre-block calls against a crowded SALT region The ported row drove the system-call entry point directly, which the two arms beside it already pin; what its original pinned was the block's own pre-block phase surviving a crowded region, through the executor and the two contracts' own code. Drive it there: the EIP-2935 and EIP-4788 calls run at the minimum bucket and at a hundred thousand times it, their ring-buffer slots hold the parent hash and the beacon root either way, the block's ledgers agree and no capacity is read at all. A user transaction in the same block is the control: it reads a capacity and cannot afford the one slot it writes. The entry-point arm keeps its scenario under a name that says what it drives. --- crates/mega-evm/tests/_pending/README.md | 2 +- crates/mega-evm/tests/block/main.rs | 1 + crates/mega-evm/tests/block/salt.rs | 182 +++++++++++++++++++++++ crates/mega-evm/tests/satin/salt.rs | 8 +- 4 files changed, 189 insertions(+), 4 deletions(-) create mode 100644 crates/mega-evm/tests/block/salt.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 90dd1bfb9..463eb3f63 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -179,7 +179,7 @@ These 63 rows run in a real test target now, adapted to the Satin API and to the | `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/error_paths.rs` | SALT pricing (2) | 2 | `tests/satin/salt_failure.rs` | -| `rex6/system_tx_metering_exemption.rs` | SALT pricing (3) | 3 | `tests/satin/salt.rs` | +| `rex6/system_tx_metering_exemption.rs` | SALT pricing (3) | 3 | `tests/block/salt.rs`, `tests/satin/salt.rs` | | `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | | `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | | **Total** | | **63** | | diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 3158182ca..8e51e26b1 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -9,4 +9,5 @@ mod inspector; mod limits; mod receipts; mod rules; +mod salt; mod schedule; diff --git a/crates/mega-evm/tests/block/salt.rs b/crates/mega-evm/tests/block/salt.rs new file mode 100644 index 000000000..f0eef5620 --- /dev/null +++ b/crates/mega-evm/tests/block/salt.rs @@ -0,0 +1,182 @@ +//! A block whose own bookkeeping lands in a crowded SALT region. +//! +//! The two pre-block calls write into whatever part of the trie the EIP-2935 and EIP-4788 +//! contracts live in, and the protocol has no say in how crowded that part is. Both calls are +//! system-originated, so they price at the minimum bucket and read no capacity at all: a block +//! cannot fail to start because the region its own history buffers live in grew. +//! +//! The control arm is a user transaction in the same block: it pays the crowded price, and at +//! the capacity these tests use it cannot afford it — so the environment the two calls ran +//! against really is crowded. + +use alloy_eips::{ + eip2935::{HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, +}; +use alloy_evm::{block::BlockExecutor, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{Bytes, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockGasCounters, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, + MegaEvmFactory, MegaHardforkConfig, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{database::State, inspector::NoOpInspector, Database}; + +use crate::common::{self, BLOCK_NUMBER, BLOCK_TIMESTAMP, CONTRACT}; + +/// The parent hash the EIP-2935 call records. Non-zero, so the call really writes a fresh slot. +const PARENT_HASH: B256 = B256::repeat_byte(0x29); + +/// The parent beacon block root the EIP-4788 call records, non-zero for the same reason. +const PARENT_BEACON_ROOT: B256 = B256::repeat_byte(0x47); + +/// The ring buffer the EIP-4788 contract keeps its two arrays in, as its own bytecode counts it. +/// The timestamp lands at `timestamp % LENGTH` and the root one whole buffer further on. +const BEACON_ROOTS_BUFFER_LENGTH: u64 = 8191; + +/// The capacity the crowded arm puts every bucket at. A slot's first write would cost this many +/// times the schedule's own entry, far beyond what any transaction of this block brought. +const HEAVY: u64 = 100_000; + +/// The gas limit the control arm's user transaction carries: plenty at the minimum bucket, and +/// nowhere near enough at [`HEAVY`]. +const USER_GAS_LIMIT: u64 = 1_000_000; + +/// The external environments of these tests: every bucket at `m` times the minimum, so the +/// capacity bites wherever a charge lands. +type SaltEnvs = TestExternalEnvs; + +/// The EVM a crowded block runs on. +type SaltEvm<'a> = MegaEvm<&'a mut State, NoOpInspector, SaltEnvs>; + +/// The executor these tests drive. +type SaltExecutor<'a> = MegaBlockExecutor, OpAlloyReceiptBuilder, MegaHardforkConfig>; + +/// Every bucket at `m` times the minimum capacity. +fn envs_at(m: u64) -> SaltEnvs { + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * m) +} + +/// A state holding the two pre-block contracts' own code and a contract a user transaction can +/// write a slot in. +fn state_with_contracts() -> State { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + State::builder().with_database(db).build() +} + +/// The context of a block whose parent hash and parent beacon block root are the two above. +fn ctx() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(PARENT_BEACON_ROOT), + Bytes::new(), + BlockLimits::no_limits(), + ) +} + +/// An executor over `state` reading `envs`. +fn executor(state: &mut State, envs: SaltEnvs) -> SaltExecutor<'_> { + let evm = + MegaEvmFactory::new().with_external_env_factory(envs).create_evm(state, common::evm_env()); + MegaBlockExecutor::new(evm, ctx(), common::chain_spec(), OpAlloyReceiptBuilder::default()) +} + +/// The ring-buffer slot the EIP-2935 call writes the parent hash into. +fn history_slot() -> U256 { + U256::from(BLOCK_NUMBER - 1) % U256::from(HISTORY_SERVE_WINDOW) +} + +/// The ring-buffer slot the EIP-4788 call writes the beacon root into. +fn beacon_root_slot() -> U256 { + U256::from(BLOCK_TIMESTAMP) % U256::from(BEACON_ROOTS_BUFFER_LENGTH) + + U256::from(BEACON_ROOTS_BUFFER_LENGTH) +} + +/// What one crowded block's pre-block phase left behind. +struct PreBlock { + /// The parent hash the EIP-2935 contract holds, as committed. + parent_hash: B256, + /// The beacon root the EIP-4788 contract holds, as committed. + beacon_root: B256, + /// The block's three ledgers after the pre-block phase. + counters: BlockGasCounters, + /// How many bucket capacities the phase read. + queries: u32, +} + +/// Runs the pre-block phase of a block against an environment at `m` and reports what it left. +fn pre_block_at(m: u64) -> PreBlock { + let envs = envs_at(m); + let mut state = state_with_contracts(); + let counters = { + let mut executor = executor(&mut state, envs.clone()); + executor.apply_pre_execution_changes().expect("the block starts"); + *executor.gas() + }; + let mut read = |address, slot| { + B256::from(state.storage(address, slot).expect("the slot is readable").to_be_bytes()) + }; + PreBlock { + parent_hash: read(HISTORY_STORAGE_ADDRESS, history_slot()), + beacon_root: read(BEACON_ROOTS_ADDRESS, beacon_root_slot()), + counters, + queries: envs.total_bucket_queries(), + } +} + +/// Both pre-block calls run and commit whatever the capacity of the region they write into, and +/// neither of them reads that capacity. +#[test] +fn test_the_pre_block_calls_commit_at_any_capacity() { + let minimum = pre_block_at(1); + let crowded = pre_block_at(HEAVY); + + for (m, block) in [(1, &minimum), (HEAVY, &crowded)] { + assert_eq!(block.parent_hash, PARENT_HASH, "at m = {m}: the EIP-2935 write committed"); + assert_eq!(block.beacon_root, PARENT_BEACON_ROOT, "at m = {m}: and the EIP-4788 write"); + assert_eq!(block.queries, 0, "at m = {m}: a pre-block call reads no capacity at all"); + } + assert_eq!( + minimum.counters, crowded.counters, + "the block's ledgers are the same at both capacities", + ); +} + +/// The control: the very same block's first user transaction does pay the crowded price, and at +/// this capacity cannot afford the one slot it writes. Without this the arms above could be +/// passing because the environment was never crowded. +#[test] +fn test_a_user_transaction_in_the_crowded_block_pays_the_crowded_price() { + let affordable = { + let mut state = state_with_contracts(); + let mut executor = executor(&mut state, envs_at(1)); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.run_transaction(&common::user_tx(0, USER_GAS_LIMIT)).expect("it executes") + }; + assert!(affordable.result.is_success(), "{:?}", affordable.result); + assert!(affordable.gas.state > 0, "the write is charged state gas"); + + let envs = envs_at(HEAVY); + let crowded = { + let mut state = state_with_contracts(); + let mut executor = executor(&mut state, envs.clone()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.run_transaction(&common::user_tx(0, USER_GAS_LIMIT)).expect("it executes") + }; + assert!( + crowded.result.is_halt(), + "a user transaction cannot afford the crowded write: {:?}", + crowded.result, + ); + assert!( + envs.total_bucket_queries() > 0, + "and it is the user transaction, not the pre-block phase, that reads a capacity", + ); +} diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 0416efeef..86c64fc14 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -647,10 +647,12 @@ fn written_oracle_slot(outcome: &MegaTransactionOutcome) -> U256 { .present_value } -/// The pre-block system calls likewise: the same call priced across the same two capacities -/// costs the same, so a protocol-mandated write cannot be priced out either. +/// The system-call entry point likewise: the same call priced across the same two capacities +/// costs the same, so a protocol-mandated write cannot be priced out either. This is the entry +/// point a block issues its pre-block calls through; driving a real block through it is a +/// block-execution test. #[test] -fn test_a_pre_block_system_call_prices_the_same_at_any_capacity() { +fn test_the_system_call_entry_point_prices_the_same_at_any_capacity() { use alloy_evm::Evm; let mut spends = Vec::new(); From 37943b4fc2327097c77259beb6787acb68ba23a2 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Sun, 20 Sep 2026 18:03:45 +0800 Subject: [PATCH 178/201] docs(satin): say what a synthetic settlement actually restores The helper's doc comment said both pools come back to where they were before the charge. The reservoir does; the regular pool comes back higher, because the frame's own forwarded gas returns with the spill. Say which is which. --- crates/mega-evm/tests/satin/salt_refund.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index cd77ab9ed..98a6a8e58 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -514,12 +514,14 @@ fn charged_create_input(reservoir: u64) -> FrameInput { FrameInput::Create(Box::new(inputs)) } -/// Requires a settlement to have put both pools back exactly where they were before the charge, -/// with the state ledger net zero and one capacity read behind the charge and the refill alike. +/// Requires a settlement to have left the caller whole: the forwarded gas back on the regular +/// pool with whatever the charge spilled onto it, the reservoir at the value it held before the +/// charge, the state ledger net zero, and one capacity read behind the charge and the refill +/// alike. fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settled: &Settled) { let caller = &settled.caller; assert_eq!(caller.remaining(), CALLER_LIMIT, "{site}: the regular pool comes back whole"); - assert_eq!(caller.reservoir(), reservoir, "{site}: and so does the reservoir"); + assert_eq!(caller.reservoir(), reservoir, "{site}: and the reservoir is where it started"); assert_eq!(caller.state_gas_spent(), 0, "{site}: the state ledger nets zero"); assert_eq!(caller.state_gas_spilled(), 0, "{site}: nothing is left spilled"); assert_eq!( From e7799156ed9e5bc1608c591f9678c30203bf0279 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 11:08:14 +0800 Subject: [PATCH 179/201] chore(deps): move the revm fork to the tag that fixes first-frame CREATE The pinned tag derived a creation transaction's pricing site from the envelope nonce, while frame creation derives the deployed address from the caller's journal nonce. The two agree for an ordinary transaction, whose nonce is validated against the account's, and part for a deposit, whose nonce is not: the charge then landed in the bucket of an address the transaction never deploys at, priced by a capacity nothing it wrote lives under. The new tag reads the same journal nonce both phases use and keeps that address for the refund. All twelve patch entries move together, or the build resolves a second revm; the lockfile moves with exactly those twelve. The op-revm pin stays where it is: it takes revm through this patch block and overrides nothing on this path. --- Cargo.lock | 24 ++++++++++++------------ Cargo.toml | 24 ++++++++++++------------ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a61460fa9..d267e10ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3733,7 +3733,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "revm-bytecode", "revm-context", @@ -3751,7 +3751,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "bitvec", "phf 0.13.1", @@ -3762,7 +3762,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "bitvec", "cfg-if", @@ -3778,7 +3778,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3793,7 +3793,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "alloy-eips", "derive_more", @@ -3807,7 +3807,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "auto_impl", "either", @@ -3820,7 +3820,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "auto_impl", "derive-where", @@ -3838,7 +3838,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "auto_impl", "either", @@ -3873,7 +3873,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3885,7 +3885,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3909,7 +3909,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "alloy-primitives", "once_cell", @@ -3919,7 +3919,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" dependencies = [ "alloy-eip7928", "bitflags 2.11.1", diff --git a/Cargo.toml b/Cargo.toml index b4502668f..ead272edc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -228,18 +228,18 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built From f2aaf6e3ffeb357c79459a8f33aaab69e5806755 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 11:16:55 +0800 Subject: [PATCH 180/201] test(satin): price a deposit creation where it deploys, not where its envelope says Four rows were parked on a fork that derived a creation transaction's pricing site from the envelope nonce. The nonce a deposit carries is never compared to the sender's account, so the charge could land in the bucket of an address the transaction does not deploy at: the leaf it really adds was priced by a region it does not live in, and a region it does live in went unread. The rows come back in this engine's shape, with the sender at nonce 5 and the envelope at 0. The deployed address's bucket prices the leaf and is read once; the envelope's address is never priced, never read and never written; a capacity only the deployed address's bucket cannot report fails the transaction, and the same failure at the envelope's address is never asked for; a reverting creation gives the charge back in the bucket it was made in. The control runs both envelope shapes at equal nonces, where there is one address to derive and the two agree. The old fork passes only that control. --- crates/mega-evm/tests/_pending/README.md | 9 +- .../rex5/deposit_create_storage_gas.rs | 205 ---------------- crates/mega-evm/tests/_pending/rex5/main.rs | 1 - crates/mega-evm/tests/satin/main.rs | 1 + crates/mega-evm/tests/satin/salt_deposit.rs | 220 ++++++++++++++++++ 5 files changed, 225 insertions(+), 211 deletions(-) delete mode 100644 crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs create mode 100644 crates/mega-evm/tests/satin/salt_deposit.rs diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md index 463eb3f63..4c4ea6455 100644 --- a/crates/mega-evm/tests/_pending/README.md +++ b/crates/mega-evm/tests/_pending/README.md @@ -28,7 +28,6 @@ Do not add a `_pending/main.rs`. | Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | |---|---:|---:|---:|---:|---:|---:| | the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| SALT pricing | 4 | 4 | 0 | 0 | 4 | 0 | | history gas | 28 | 24 | 4 | 4 | 24 | 0 | | compute gas | 26 | 26 | 0 | 0 | 26 | 0 | | the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | @@ -41,7 +40,7 @@ Do not add a `_pending/main.rs`. | native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | | inspector support | 4 | 4 | 0 | 1 | 3 | 0 | | — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **528** | **461** | **67** | **311** | **189** | **28** | +| **Total** | **524** | **457** | **67** | **311** | **185** | **28** | ## Tests ported in place @@ -167,7 +166,7 @@ These 53 rows run in a real test target now, adapted to the Satin API, so the co ## Tests ported by SALT pricing -These 63 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. +These 67 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. | Legacy file | Owner in the inventory | Tests | Now in | |---|---|---:|---| @@ -175,6 +174,7 @@ These 63 rows run in a real test target now, adapted to the Satin API and to the | `rex/storage_gas.rs` | SALT pricing (15) | 15 | `tests/satin/salt.rs` | | `rex4/eip7702_delegation_cycle.rs` | SALT pricing (8) | 8 | `tests/satin/salt_delegation.rs` | | `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | `tests/satin/salt_delegation.rs` | +| `rex5/deposit_create_storage_gas.rs` | SALT pricing (4) | 4 | `tests/satin/salt_deposit.rs` | | `rex5/eip7702_metering.rs` | SALT pricing (4) | 4 | `tests/satin/salt_delegation.rs` | | `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | | `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | @@ -182,7 +182,7 @@ These 63 rows run in a real test target now, adapted to the Satin API and to the | `rex6/system_tx_metering_exemption.rs` | SALT pricing (3) | 3 | `tests/block/salt.rs`, `tests/satin/salt.rs` | | `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | | `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | -| **Total** | | **63** | | +| **Total** | | **67** | | ## Tests ported by the system contract interceptors @@ -258,7 +258,6 @@ Each cell lists `disposition count (mechanism · decision)`. | `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | | `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | | `rex5/db_error.rs` | 3 | rewrite 3 (native keyless deployment · native path surfaces DB errors) | -| `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | | `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | | `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | | `rex5/keyless_fee_free.rs` | 12 | rewrite 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); keep 4 (native keyless deployment · rules unchanged) | diff --git a/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs deleted file mode 100644 index c70520043..000000000 --- a/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs +++ /dev/null @@ -1,205 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! Tests for top-level CREATE storage-gas pricing. -//! -//! Under `MegaSpecId::REX5`, `MegaHandler::validate` derives the CREATE -//! address from the caller's state nonce (read via non-destructive -//! `journal.inspect_account`), matching `make_create_frame`. Pre-REX5 keeps -//! the `tx.nonce()`-based pricing for replay determinism. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; -use mega_evm::{ - constants, test_utils::MemoryDatabase, BucketHasher, EvmTxRuntimeLimits, MegaContext, MegaEvm, - MegaSpecId, MegaTransaction, SimpleBucketHasher, TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{context::TxEnv, database::Database as _}; - -const CALLER: Address = address!("1111111111111111111111111111111111111111"); - -/// Caller's actual on-chain nonce. The contract WILL deploy at -/// `CALLER.create(STATE_NONCE)`. -const STATE_NONCE: u64 = 5; - -/// Nonce field carried by the deposit envelope. Different from STATE_NONCE, -/// which is the whole point: under op-revm a deposit's `tx.nonce` is not -/// validated against state. -const TX_NONCE: u64 = 0; - -/// Multiplier 100 → storage gas = `CONTRACT_CREATION_STORAGE_GAS_BASE * (100 - 1)` -/// = 32_000 * 99 = 3_168_000 gas. The cheap (default) bucket has multiplier 1 -/// → storage gas = 0. The 3.17M-gas spread is what the test observes. -const HEAVY_MULTIPLIER: u64 = 100; -const HEAVY_CAPACITY: u64 = (MIN_BUCKET_SIZE as u64) * HEAVY_MULTIPLIER; -const EXPECTED_HEAVY_STORAGE_GAS: u64 = - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE * (HEAVY_MULTIPLIER - 1); - -/// Builds external envs where the bucket containing the address derived -/// from `nonce_for_heavy_bucket` is configured for the heavy multiplier. -/// Every other bucket falls through to the default (multiplier = 1). -fn envs_with_heavy_bucket_at( - nonce_for_heavy_bucket: u64, -) -> TestExternalEnvs { - let heavy_address = CALLER.create(nonce_for_heavy_bucket); - let heavy_bucket = SimpleBucketHasher::bucket_id(heavy_address.as_slice()); - TestExternalEnvs::new().with_bucket_capacity(heavy_bucket, HEAVY_CAPACITY) -} - -/// Builds a deposit-style top-level CREATE transaction. -/// -/// `tx.nonce` is the envelope nonce (does not need to match state). The -/// `deposit.source_hash != ZERO` field is what makes op-revm classify this -/// as a deposit and skip nonce validation. -fn deposit_create_tx(tx_nonce: u64, gas_limit: u64) -> MegaTransaction { - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - nonce: tx_nonce, - gas_limit, - gas_price: 0, // deposits don't pay gas - data: Bytes::new(), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.deposit.source_hash = B256::from([0x42; 32]); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Builds a normal (non-deposit) top-level CREATE transaction. `tx.nonce` -/// must match `state.nonce` for `validate_against_state` to pass. -fn normal_create_tx(state_nonce: u64, gas_limit: u64) -> MegaTransaction { - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - nonce: state_nonce, - gas_limit, - gas_price: 0, - data: Bytes::new(), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -fn run( - spec: MegaSpecId, - db: &mut MemoryDatabase, - envs: &TestExternalEnvs, - tx: MegaTransaction, -) -> revm::context::result::ResultAndState { - let mut context = MegaContext::new(db, spec) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError") -} - -/// Pre-state with caller account at the chosen state nonce. -fn seed_caller(state_nonce: u64) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - db.set_account_nonce(CALLER, state_nonce); - db -} - -/// Deposit CREATE storage gas is priced at `caller.create(state_nonce)`, -/// not `caller.create(tx.nonce)`. Heavy SALT on the state-nonce bucket -/// makes the gas charge observable. -#[test] -fn test_deposit_create_storage_gas_uses_state_nonce() { - let mut db = seed_caller(STATE_NONCE); - let envs = envs_with_heavy_bucket_at(STATE_NONCE); - let gas_limit = 50_000_000; - let tx = deposit_create_tx(TX_NONCE, gas_limit); - - let res = run(MegaSpecId::REX5, &mut db, &envs, tx); - - assert!( - res.result.is_success(), - "Deposit CREATE must succeed under REX5 with sufficient gas; got: {:?}", - res.result - ); - - // Sanity: the deployed address comes from the state nonce. - let deployed_address = match &res.result { - revm::context::result::ExecutionResult::Success { output, .. } => match output { - revm::context::result::Output::Create(_, Some(addr)) => *addr, - other => panic!("Expected Create output with address, got: {other:?}"), - }, - _ => panic!("not Success"), - }; - assert_eq!(deployed_address, CALLER.create(STATE_NONCE)); - assert_ne!(deployed_address, CALLER.create(TX_NONCE)); - - let gas_used = res.result.gas_used(); - assert!( - gas_used >= EXPECTED_HEAVY_STORAGE_GAS, - "expected gas_used ≥ {EXPECTED_HEAVY_STORAGE_GAS} (heavy-bucket storage gas), got \ - {gas_used}", - ); -} - -/// Non-deposit CREATE under REX5: `tx.nonce == state.nonce`, so the -/// state-nonce read returns the same value as `tx.nonce()` did. -#[test] -fn test_non_deposit_create_storage_gas_unchanged_under_rex5() { - let mut db = seed_caller(STATE_NONCE); - let envs = envs_with_heavy_bucket_at(STATE_NONCE); - let gas_limit = 50_000_000; - let tx = normal_create_tx(STATE_NONCE, gas_limit); - - let res = run(MegaSpecId::REX5, &mut db, &envs, tx); - - assert!(res.result.is_success(), "CREATE must succeed: {:?}", res.result); - let gas_used = res.result.gas_used(); - assert!(gas_used >= EXPECTED_HEAVY_STORAGE_GAS, "got gas_used={gas_used}"); -} - -/// When `state_nonce == tx_nonce == 0`, the state-nonce read produces -/// the same address as `tx.nonce()`; REX4 and REX5 must agree on the -/// receipt. -#[test] -fn test_deposit_create_with_state_nonce_zero_unchanged() { - let envs = envs_with_heavy_bucket_at(0); - let gas_limit = 50_000_000; - - let mut db_rex4 = seed_caller(0); - let res_rex4 = run(MegaSpecId::REX4, &mut db_rex4, &envs, deposit_create_tx(0, gas_limit)); - - let mut db_rex5 = seed_caller(0); - let res_rex5 = run(MegaSpecId::REX5, &mut db_rex5, &envs, deposit_create_tx(0, gas_limit)); - - assert_eq!(res_rex4.result.is_success(), res_rex5.result.is_success()); - assert_eq!(res_rex4.result.gas_used(), res_rex5.result.gas_used()); -} - -/// Confirms `validate()` reads the caller through the canonical pipeline: -/// the state delta carries a bumped caller nonce and the deployed -/// contract account. -#[test] -fn test_deposit_create_caller_state_nonce_is_bumped_after_create() { - let mut db = seed_caller(STATE_NONCE); - let envs = envs_with_heavy_bucket_at(STATE_NONCE); - let gas_limit = 50_000_000; - let tx = deposit_create_tx(TX_NONCE, gas_limit); - - let res = run(MegaSpecId::REX5, &mut db, &envs, tx); - assert!(res.result.is_success(), "deposit CREATE should succeed: {:?}", res.result); - - let caller_account = res.state.get(&CALLER).expect("caller account must be in state delta"); - assert_eq!(caller_account.info.nonce, STATE_NONCE + 1); - let deployed = CALLER.create(STATE_NONCE); - assert!(res.state.contains_key(&deployed), "deployed contract must be in state delta"); - assert!( - db.basic(deployed).unwrap().is_none_or(|info| info.is_empty()), - "db should be untouched; assertions read only the in-memory delta", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs index 1e50e1579..7db9edbf5 100644 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -5,7 +5,6 @@ mod callcode_storage_gas; mod create2_empty_initcode; mod create2_resize_gas_metering; mod db_error; -mod deposit_create_storage_gas; mod eip7702_metering; mod eip7702_state_growth; mod keyless_empty_code_logs; diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 2c5f7e862..6c6ddbe74 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -11,6 +11,7 @@ mod precompile_gas; mod pricing_table; mod salt; mod salt_delegation; +mod salt_deposit; mod salt_failure; mod salt_refund; mod schedule; diff --git a/crates/mega-evm/tests/satin/salt_deposit.rs b/crates/mega-evm/tests/satin/salt_deposit.rs new file mode 100644 index 000000000..c2cc87c0e --- /dev/null +++ b/crates/mega-evm/tests/satin/salt_deposit.rs @@ -0,0 +1,220 @@ +//! SALT pricing: where a creation transaction's charge lands when the envelope nonce and the +//! sender's own nonce disagree. +//! +//! A creation transaction pays for the account leaf it adds before its first frame runs, and the +//! bucket that leaf lands in prices the charge. The leaf lands at the address frame creation +//! derives from the sender's account nonce, which is not in general the nonce the envelope +//! carries. An ordinary transaction cannot tell the two apart: its nonce is validated against +//! the account's, so the two numbers are one. A deposit can — op-revm returns from the account +//! load before the nonce check when the transaction is a deposit — so its envelope may say +//! anything while the contract still deploys at `sender.create(account nonce)`. +//! +//! Every test below runs that shape, and an engine pricing the charge at the envelope nonce's +//! address fails all of them but the last: it pays the base price where the leaf actually lands +//! and eight times the price where nothing is written, asks whether the wrong bucket can be +//! priced at all, and settles a reverted creation in a bucket the transaction never deploys +//! into. The last one is the control the two agree on, because equal nonces leave one address +//! to derive. + +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, B256}; +use mega_evm::{ + test_utils::{op_transaction, MemoryDatabase}, + MegaTransaction, +}; +use revm::{ + bytecode::opcode::{PUSH0, RETURN, REVERT}, + context::{result::ExecutionResult, TxEnv}, + context_interface::cfg::GasId, +}; + +use crate::salt::{ + account_bucket, crowded_account, db, entry, minimal_envs, run, try_run, SaltEnvs, CALLER, + GAS_LIMIT, +}; + +/// The sender's own nonce. The contract deploys at `CALLER.create(STATE_NONCE)`. +const STATE_NONCE: u64 = 5; + +/// The nonce the deposit's envelope carries, which op-revm never compares to the account's. +const ENVELOPE_NONCE: u64 = 0; + +/// The capacity, in minimum buckets, every crowded arm puts its bucket at. +const M: u64 = 8; + +/// Init code deploying zero bytes of runtime code, so the creation's only state charge is the +/// account leaf itself. +const EMPTY_INIT: &[u8] = &[PUSH0, PUSH0, RETURN]; + +/// Init code that reverts, so the creation adds no leaf and its upfront charge comes back. +const REVERTING_INIT: &[u8] = &[PUSH0, PUSH0, REVERT]; + +/// The address the transaction deploys at, and the one its envelope nonce derives, with the +/// guard the tests rest on: the two fall in different buckets, so crowding one says nothing +/// about the other. +fn candidates() -> (Address, Address) { + let deployed = CALLER.create(STATE_NONCE); + let envelope = CALLER.create(ENVELOPE_NONCE); + assert_ne!( + account_bucket(deployed), + account_bucket(envelope), + "the probes tell the two sites apart by the bucket each reads", + ); + (deployed, envelope) +} + +/// A sender whose account nonce is `nonce`. +fn sender_at(nonce: u64) -> MemoryDatabase { + db(Bytes::new()).account_nonce(CALLER, nonce) +} + +/// A creation transaction from `CALLER` carrying `nonce` in its envelope, deploying `init_code`. +/// +/// `deposit` gives the transaction a source hash, which is what makes op-revm classify it as a +/// deposit and skip the nonce check; it is not the sequencer's own system transaction, so it is +/// priced like any transaction a user sends. +fn create_tx(nonce: u64, init_code: &[u8], deposit: bool) -> MegaTransaction { + let mut tx = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + nonce, + data: Bytes::copy_from_slice(init_code), + gas_limit: GAS_LIMIT, + ..Default::default() + }); + if deposit { + tx.deposit.source_hash = B256::from([0x42; 32]); + tx.deposit.is_system_transaction = false; + } + OpTx(tx) +} + +/// What one account leaf costs at the minimum bucket. +fn leaf() -> u64 { + entry(GasId::create_state_gas()) +} + +/// `envs` with the capacity query of `account`'s own bucket failing. +fn failing_account(envs: SaltEnvs, account: Address) -> SaltEnvs { + envs.with_failing_bucket(account_bucket(account), "salt backend unreachable".into()) +} + +/// A deposit creation is charged in the bucket of the address it deploys at, and the address its +/// envelope nonce derives is never priced, never written and never read. +#[test] +fn test_a_deposit_creation_is_priced_where_it_deploys() { + let (deployed, envelope) = candidates(); + let envs = crowded_account(minimal_envs(), deployed, M); + + let outcome = + run(sender_at(STATE_NONCE), envs.clone(), create_tx(ENVELOPE_NONCE, EMPTY_INIT, true)); + + assert_eq!(outcome.gas.state, leaf() * M, "the deployed address's bucket prices the leaf"); + assert_eq!(envs.bucket_queries(account_bucket(deployed)), 1, "read once, for that charge"); + assert_eq!( + envs.bucket_queries(account_bucket(envelope)), + 0, + "the envelope nonce's address is nobody's charge site", + ); + + // The state says the same thing the price does: the leaf is at the deployed address, the + // sender's nonce moved off the value that derived it, and the envelope's address is absent. + assert!(outcome.state.contains_key(&deployed), "the created account is at {deployed}"); + assert!(!outcome.state.contains_key(&envelope), "nothing was written at {envelope}"); + let sender = outcome.state.get(&CALLER).expect("the sender is in the state"); + assert_eq!(sender.info.nonce, STATE_NONCE + 1, "the creation bumped the account's own nonce"); +} + +/// Crowding the address the envelope nonce derives changes nothing: the transaction pays the +/// base price, and that bucket's capacity is never asked for. +#[test] +fn test_crowding_the_envelope_nonce_s_address_changes_no_price() { + let (deployed, envelope) = candidates(); + let envs = crowded_account(minimal_envs(), envelope, M); + + let outcome = + run(sender_at(STATE_NONCE), envs.clone(), create_tx(ENVELOPE_NONCE, EMPTY_INIT, true)); + + assert_eq!(outcome.gas.state, leaf(), "the crowd sits where the transaction writes nothing"); + assert_eq!(envs.bucket_queries(account_bucket(envelope)), 0, "so it is never read"); + assert_eq!(envs.bucket_queries(account_bucket(deployed)), 1, "the leaf's own bucket is"); +} + +/// A capacity the deployed address's bucket cannot report fails the transaction with the cause +/// the SALT environment gave, like any other charge that cannot be priced. +#[test] +fn test_an_unpriceable_deposit_creation_fails_with_its_cause() { + let (deployed, _) = candidates(); + let envs = failing_account(minimal_envs(), deployed); + + match try_run(sender_at(STATE_NONCE), envs, create_tx(ENVELOPE_NONCE, EMPTY_INIT, true)) { + Err(revm::context::result::EVMError::Custom(message)) => { + assert!(message.contains("salt backend unreachable"), "got {message:?}"); + } + other => panic!("expected the recorded cause, got {other:?}"), + } +} + +/// The same failure at the envelope nonce's address does not reach the transaction at all: a +/// bucket nothing is charged in is a bucket nothing asks about. +#[test] +fn test_a_failure_at_the_envelope_nonce_s_address_is_never_asked_for() { + let (deployed, envelope) = candidates(); + let envs = failing_account(minimal_envs(), envelope); + + let outcome = + run(sender_at(STATE_NONCE), envs.clone(), create_tx(ENVELOPE_NONCE, EMPTY_INIT, true)); + + assert_eq!(outcome.gas.state, leaf(), "the transaction is priced by its own site"); + assert_eq!(envs.bucket_queries(account_bucket(envelope)), 0); + assert_eq!(envs.bucket_queries(account_bucket(deployed)), 1); +} + +/// A deposit creation whose init code reverts adds no leaf, and the refund is made at the site +/// the charge was: the transaction nets nothing on the state ledger even where that site is +/// eight times the minimum, and one capacity read priced both halves. +#[test] +fn test_a_reverting_deposit_creation_gives_the_charge_back_where_it_was_made() { + let (deployed, envelope) = candidates(); + let envs = crowded_account(minimal_envs(), deployed, M); + + let outcome = try_run( + sender_at(STATE_NONCE), + envs.clone(), + create_tx(ENVELOPE_NONCE, REVERTING_INIT, true), + ) + .expect("the probe is a valid transaction"); + + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "the init code reverts: {:?}", + outcome.result, + ); + assert_eq!(outcome.gas.state, 0, "a creation that deployed nothing pays no state gas"); + assert_eq!(envs.bucket_queries(account_bucket(deployed)), 1, "charge and refill, one read"); + assert_eq!(envs.bucket_queries(account_bucket(envelope)), 0); + assert!(!outcome.state.contains_key(&envelope), "nothing was written at {envelope}"); +} + +/// The control: with the two nonces equal there is one address to derive, and a deposit and an +/// ordinary transaction are priced alike there. This is every other creation transaction in the +/// suite, and the site it is charged at did not move. +#[test] +fn test_at_equal_nonces_a_deposit_and_an_ordinary_creation_agree() { + // Both nonces are `STATE_NONCE` here, so the two candidate addresses of the tests above + // are this one address, and no arrangement of buckets can tell them apart. + let deployed = CALLER.create(STATE_NONCE); + + let mut ledgers = Vec::new(); + for deposit in [false, true] { + let envs = crowded_account(minimal_envs(), deployed, M); + let outcome = + run(sender_at(STATE_NONCE), envs.clone(), create_tx(STATE_NONCE, EMPTY_INIT, deposit)); + + assert_eq!(outcome.gas.state, leaf() * M, "deposit = {deposit}: the crowded leaf"); + assert_eq!(envs.bucket_queries(account_bucket(deployed)), 1, "deposit = {deposit}"); + assert!(outcome.state.contains_key(&deployed), "deposit = {deposit}: the leaf is here"); + ledgers.push(outcome.gas.state); + } + assert_eq!(ledgers[0], ledgers[1], "the envelope's shape prices nothing on its own"); +} From b16d1b36b382e4d3726e347b2222ed02d593bc02 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Mon, 21 Sep 2026 11:24:10 +0800 Subject: [PATCH 181/201] docs(satin): name the address a creation transaction is charged at "Create target" reads either way now that the two candidate addresses are pinned apart: say the one the transaction deploys at. --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 2e2989884..0b691789b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,7 +119,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. - SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`). A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. - A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or create target, by an applied EIP-7702 authority, and by the beneficiary a `SELFDESTRUCT` moves a balance to; the bytes a creation deposits are charged in the deployed address's bucket. + A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or the address a creation transaction deploys at, by an applied EIP-7702 authority, and by the beneficiary a `SELFDESTRUCT` moves a balance to; the bytes a creation deposits are charged in the deployed address's bucket. The capacities come from the transaction's `SaltEnv` through `BucketMultipliers` (`external/gas.rs`), which reads a bucket once per transaction; the cache is cleared with the rest of the per-transaction state. A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; that is a transaction whose caller is the EIP-4788 system address, the sequencer's own system transaction — before or after the engine promotes it to a deposit — and every transaction run through a system-call entry point. A failed capacity lookup reports nothing and records its cause the way a failed `sload` does; the transaction fails with that cause rather than settling at a price nobody chose. From 17fb2b14ce81bfa7f4180d29954fdf748f6e2bf1 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 14:47:15 +0800 Subject: [PATCH 182/201] feat!: restart mega-evm as the Satin skeleton on the revm 40 forks (#385) --- .cargo/mutants-infra.toml | 22 + .cargo/mutants.toml | 11 +- .github/workflows/benchmark.yml | 5 +- .github/workflows/exec-spec.yml | 165 + .github/workflows/mutation.yml | 94 +- .github/workflows/replay-bench.yml | 5 + AGENTS.md | 349 +-- Cargo.lock | 2672 ++++++----------- Cargo.toml | 97 +- REVIEW.md | 60 +- clippy.toml | 2 +- crates/mega-evm/Cargo.toml | 59 +- crates/mega-evm/README.md | 140 +- crates/mega-evm/benches/attack_replay.rs | 436 --- crates/mega-evm/benches/block_bench.rs | 484 --- crates/mega-evm/benches/common/mod.rs | 156 - crates/mega-evm/benches/common/subject.rs | 443 --- crates/mega-evm/benches/common/workload.rs | 116 - crates/mega-evm/benches/comp_cost.rs | 1130 ------- crates/mega-evm/benches/corpus.rs | 63 + crates/mega-evm/benches/ctt.rs | 170 -- crates/mega-evm/benches/enriched_tx.rs | 103 - crates/mega-evm/benches/factory.rs | 41 + crates/mega-evm/benches/mega_bench.rs | 971 ------ crates/mega-evm/benches/revm_bench.rs | 279 -- .../access_list_warm_slots_and_account.json | 43 + .../benches/scenarios/create_success.json | 28 + .../eip7702_delegate_new_authority.json | 34 + .../scenarios/logs_all_topic_counts.json | 23 + .../nested_call_revert_with_spill.json | 34 + .../scenarios/precompile_ecrecover.json | 31 + .../benches/scenarios/precompile_modexp.json | 31 + ...reated_in_same_tx_to_existing_account.json | 27 + .../benches/scenarios/sstore_set_spills.json | 28 + .../benches/scenarios/system_call.json | 26 + ...with_sstore_fork_Amsterdam_state_test.json | 27 + ...e_deepest_depth_10_sstore_restoration.json | 75 + .../benches/scenarios/two_txs_sequential.json | 36 + crates/mega-evm/benches/transact.rs | 228 +- .../examples/beneficiary_access_tracking.rs | 205 -- .../mega-evm/examples/block_env_tracking.rs | 184 -- crates/mega-evm/src/AGENTS.md | 33 - crates/mega-evm/src/access/AGENTS.md | 32 - crates/mega-evm/src/access/mod.rs | 13 +- crates/mega-evm/src/access/tracker.rs | 305 -- crates/mega-evm/src/access/volatile.rs | 186 -- crates/mega-evm/src/block/AGENTS.md | 70 - crates/mega-evm/src/block/chain.rs | 263 +- crates/mega-evm/src/block/eips.rs | 272 -- crates/mega-evm/src/block/executor.rs | 775 +---- crates/mega-evm/src/block/factory.rs | 205 -- crates/mega-evm/src/block/hardfork.rs | 1164 +------ crates/mega-evm/src/block/helpers.rs | 390 --- crates/mega-evm/src/block/limit.rs | 1147 ------- crates/mega-evm/src/block/mod.rs | 100 +- crates/mega-evm/src/block/result.rs | 258 +- crates/mega-evm/src/constants.rs | 267 +- crates/mega-evm/src/evm/AGENTS.md | 30 - crates/mega-evm/src/evm/context.rs | 994 ++---- crates/mega-evm/src/evm/execution.rs | 1821 +++-------- crates/mega-evm/src/evm/factory.rs | 267 +- crates/mega-evm/src/evm/frame.rs | 248 ++ crates/mega-evm/src/evm/host.rs | 1126 ++----- crates/mega-evm/src/evm/inspector.rs | 364 +++ crates/mega-evm/src/evm/instructions.rs | 2475 +-------------- crates/mega-evm/src/evm/interfaces.rs | 236 -- crates/mega-evm/src/evm/limit.rs | 185 -- crates/mega-evm/src/evm/mod.rs | 883 +++--- crates/mega-evm/src/evm/precompiles.rs | 758 ----- crates/mega-evm/src/evm/result.rs | 308 +- crates/mega-evm/src/evm/spec.rs | 559 +--- crates/mega-evm/src/evm/state.rs | 396 --- crates/mega-evm/src/external/AGENTS.md | 7 +- crates/mega-evm/src/external/gas.rs | 300 -- crates/mega-evm/src/external/mod.rs | 2 - crates/mega-evm/src/lib.rs | 40 +- crates/mega-evm/src/limit/AGENTS.md | 36 - crates/mega-evm/src/limit/compute_gas.rs | 270 -- crates/mega-evm/src/limit/data_size.rs | 406 --- crates/mega-evm/src/limit/frame_limit.rs | 895 ++---- crates/mega-evm/src/limit/kv_update.rs | 298 -- crates/mega-evm/src/limit/limit.rs | 1327 ++------ crates/mega-evm/src/limit/mod.rs | 279 +- crates/mega-evm/src/limit/record.rs | 159 + crates/mega-evm/src/limit/state_growth.rs | 380 --- .../src/limit/storage_call_stipend.rs | 215 -- crates/mega-evm/src/sandbox/execution.rs | 1616 ---------- crates/mega-evm/src/sandbox/mod.rs | 105 - crates/mega-evm/src/sandbox/state.rs | 516 ---- crates/mega-evm/src/sandbox/state_merge.rs | 910 ------ crates/mega-evm/src/system/AGENTS.md | 57 - crates/mega-evm/src/system/deploy.rs | 386 --- crates/mega-evm/src/system/intercept.rs | 619 ---- .../src/{sandbox => system/keyless}/error.rs | 44 +- crates/mega-evm/src/system/keyless/mod.rs | 13 + .../src/{sandbox => system/keyless}/tx.rs | 58 +- crates/mega-evm/src/system/keyless_deploy.rs | 141 - crates/mega-evm/src/system/mod.rs | 42 +- crates/mega-evm/src/system/oracle.rs | 605 ---- .../mega-evm/src/system/sequencer_registry.rs | 1494 --------- crates/mega-evm/src/system/tx.rs | 213 -- crates/mega-evm/src/test_utils/database.rs | 8 +- crates/mega-evm/src/test_utils/evm.rs | 61 +- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/opcode_gen.rs | 29 +- crates/mega-evm/src/test_utils/scenario.rs | 536 ++++ crates/mega-evm/src/types.rs | 33 +- crates/mega-evm/tests/_pending/README.md | 246 ++ .../block_executor/accessed_block_hashes.rs | 0 .../block_executor/block_limits.rs | 0 .../block_executor/canonical_schedule.rs | 0 .../block_executor/deposit_da_exemption.rs | 0 .../block_executor/inspector.rs | 0 .../{ => _pending}/block_executor/main.rs | 1 - .../block_executor/sequencer_registry.rs | 0 .../trait_factory_runtime_limits.rs | 0 .../{ => _pending}/compute_gas/claims.rs | 215 -- .../tests/{ => _pending}/compute_gas/main.rs | 80 - .../mini_rex/access_beneficiary_balance.rs | 0 .../mini_rex/block_env_access_tracking.rs | 0 .../mini_rex/block_env_gas_limit.rs | 0 .../mini_rex/compute_gas_limit.rs | 162 - .../mini_rex/contract_size_limit.rs | 60 - .../tests/{ => _pending}/mini_rex/gas.rs | 196 -- .../tests/{ => _pending}/mini_rex/main.rs | 2 - .../mini_rex/mega_system_transaction.rs | 0 .../tests/{ => _pending}/mini_rex/oracle.rs | 230 -- .../_pending/mini_rex/state_growth_limit.rs | 220 ++ .../mini_rex/tx_data_and_kv_update_limit.rs | 282 -- .../mega-evm/tests/{ => _pending}/rex/main.rs | 2 - .../tests/{ => _pending}/rex/oracle.rs | 0 .../tests/{ => _pending}/rex/storage_gas.rs | 52 - .../{ => _pending}/rex2/keyless_deploy.rs | 91 - .../tests/{ => _pending}/rex2/main.rs | 1 - .../tests/{ => _pending}/rex2/oracle_hint.rs | 25 - .../{ => _pending}/rex3/keyless_deploy.rs | 25 - .../tests/{ => _pending}/rex3/main.rs | 0 .../{ => _pending}/rex3/oracle_gas_limit.rs | 68 - .../{ => _pending}/rex3/system_address.rs | 0 .../{ => _pending}/rex4/access_control.rs | 80 - .../rex4/beneficiary_detention.rs | 56 - .../{ => _pending}/rex4/create_safety.rs | 110 - .../tests/{ => _pending}/rex4/deployment.rs | 11 - .../rex4/eip7702_delegation_cycle.rs | 138 - .../tests/{ => _pending}/rex4/frame_limits.rs | 248 -- .../{ => _pending}/rex4/gas_detention.rs | 28 - .../rex4/intrinsic_limit_bypass.rs | 0 .../{ => _pending}/rex4/keyless_deploy.rs | 78 - .../{ => _pending}/rex4/limit_control.rs | 13 - .../tests/{ => _pending}/rex4/main.rs | 2 - .../rex4/storage_call_stipend.rs | 273 -- .../rex5/apply_pending_changes_gas_budget.rs | 0 .../rex5/callcode_storage_gas.rs | 34 - .../rex5/create2_empty_initcode.rs | 25 - .../rex5/create2_resize_gas_metering.rs | 31 - .../tests/{ => _pending}/rex5/db_error.rs | 0 .../rex5/deposit_caller_accounting.rs | 36 - .../rex5/deposit_create_storage_gas.rs | 19 - .../{ => _pending}/rex5/eip7702_metering.rs | 0 .../rex5/eip7702_state_growth.rs | 33 - .../{ => _pending}/rex5/gas_validation.rs | 35 - .../rex5/interceptor_selector_probe.rs | 0 .../rex5/keyless_deploy_dispatch_parity.rs | 0 .../rex5/keyless_empty_code_logs.rs | 40 - .../{ => _pending}/rex5/keyless_fee_free.rs | 35 - .../rex5/keyless_gas_cap_postcap_recheck.rs | 36 - .../rex5/keyless_replay_barrier.rs | 45 - .../tests/{ => _pending}/rex5/main.rs | 3 - .../rex5/oracle_hint_metering.rs | 59 - .../rex5/pre_block_system_calls.rs | 103 - .../rex5/precompile_compute_gas.rs | 205 -- .../{ => _pending}/rex5/sandbox_accounting.rs | 549 ---- .../rex5/selfdestruct_beneficiary.rs | 34 - .../rex5/sstore_storage_gas_error.rs | 0 .../{ => _pending}/rex5/stipend_accounting.rs | 356 --- .../{ => _pending}/rex5/system_tx_replay.rs | 0 .../rex6/beneficiary_detention.rs | 90 - .../tests/{ => _pending}/rex6/common.rs | 0 .../rex6/create2_metering_order.rs | 141 - .../_pending/rex6/create_frame_accounting.rs | 166 + .../rex6/eip7702_authority_accounting.rs | 0 .../tests/{ => _pending}/rex6/error_paths.rs | 0 .../rex6/fee_reward_accounting.rs | 57 - .../rex6/frame_local_accounting.rs | 89 - .../rex6/keyless_sandbox_hardening.rs | 68 - .../tests/{ => _pending}/rex6/main.rs | 1 - .../rex6/oracle_hint_volatile_access.rs | 17 - .../rex6/self_transfer_account_dedup.rs | 136 + .../rex6/sequencer_registry_rotation.rs | 104 - .../rex6/system_tx_metering_exemption.rs | 42 - .../tests/_pending/src/access/volatile.rs | 85 + .../tests/_pending/src/block/chain.rs | 100 + .../mega-evm/tests/_pending/src/block/eips.rs | 92 + .../tests/_pending/src/block/hardfork.rs | 233 ++ .../tests/_pending/src/block/helpers.rs | 205 ++ .../tests/_pending/src/block/limit.rs | 97 + .../tests/_pending/src/block/result.rs | 65 + .../tests/_pending/src/evm/context.rs | 50 + .../tests/_pending/src/evm/factory.rs | 31 + .../mega-evm/tests/_pending/src/evm/host.rs | 123 + crates/mega-evm/tests/_pending/src/evm/mod.rs | 111 + .../tests/_pending/src/evm/precompiles.rs | 211 ++ .../mega-evm/tests/_pending/src/evm/state.rs | 43 + .../tests/_pending/src/external/gas.rs | 120 + .../tests/_pending/src/limit/compute_gas.rs | 28 + .../tests/_pending/src/limit/data_size.rs | 26 + .../tests/_pending/src/limit/kv_update.rs | 19 + .../tests/_pending/src/limit/limit.rs | 98 + .../tests/_pending/src/sandbox/execution.rs | 159 + .../_pending}/src/system/control.rs | 85 +- .../tests/_pending/src/system/deploy.rs | 150 + .../tests/_pending/src/system/intercept.rs | 114 + .../_pending/src/system/keyless_deploy.rs | 64 + .../_pending}/src/system/limit_control.rs | 60 +- .../tests/_pending/src/system/oracle.rs | 257 ++ .../_pending/src/system/sequencer_registry.rs | 778 +++++ .../mega-evm/tests/_pending/src/system/tx.rs | 79 + .../tests/block_executor/partial_ladder.rs | 404 --- .../mega-evm/tests/compute_gas/snapshot.txt | 429 --- .../mega-evm/tests/equivalence/evm_state.rs | 92 - crates/mega-evm/tests/equivalence/main.rs | 3 - crates/mega-evm/tests/mini_rex/db_error.rs | 222 -- .../tests/mini_rex/disallow_selfdestruct.rs | 55 - .../tests/mini_rex/state_growth_limit.rs | 807 ----- crates/mega-evm/tests/mutation/access_evm.rs | 479 --- crates/mega-evm/tests/mutation/block.rs | 618 ---- crates/mega-evm/tests/mutation/constants.rs | 78 - .../mega-evm/tests/mutation/external_exec.rs | 347 --- crates/mega-evm/tests/mutation/limit.rs | 115 - crates/mega-evm/tests/mutation/main.rs | 49 - crates/mega-evm/tests/rex/intrinsic_gas.rs | 317 -- crates/mega-evm/tests/rex2/selfdestruct.rs | 25 - .../mega-evm/tests/rex4/frame_state_growth.rs | 962 ------ .../tests/rex4/selfdestruct_state_growth.rs | 609 ---- .../tests/rex5/call_too_deep_guard.rs | 253 -- .../mega-evm/tests/rex5/create_atomicity.rs | 281 -- .../tests/rex5/frame_target_updated_dedup.rs | 341 --- .../tests/rex6/create_frame_accounting.rs | 395 --- .../tests/rex6/metering_order_parity.rs | 240 -- .../tests/rex6/self_transfer_account_dedup.rs | 391 --- crates/mega-evm/tests/satin/common.rs | 59 + crates/mega-evm/tests/satin/db_error.rs | 101 + crates/mega-evm/tests/satin/equivalence.rs | 264 ++ crates/mega-evm/tests/satin/inspector.rs | 553 ++++ crates/mega-evm/tests/satin/main.rs | 12 + crates/mega-evm/tests/satin/outcome.rs | 119 + crates/mega-evm/tests/satin/state.rs | 113 + crates/mega-evm/tests/satin/static_callee.rs | 123 + crates/mega-evm/tests/satin/strategic_stop.rs | 547 ++++ .../tests/satin/synthetic_frame_gas.rs | 221 ++ crates/mega-evm/tests/satin/write_records.rs | 821 +++++ mutants/README.md | 30 +- mutants/suppressions.toml | 196 +- scripts/mutation_test.sh | 34 +- 254 files changed, 13549 insertions(+), 43588 deletions(-) create mode 100644 .cargo/mutants-infra.toml create mode 100644 .github/workflows/exec-spec.yml delete mode 100644 crates/mega-evm/benches/attack_replay.rs delete mode 100644 crates/mega-evm/benches/block_bench.rs delete mode 100644 crates/mega-evm/benches/common/mod.rs delete mode 100644 crates/mega-evm/benches/common/subject.rs delete mode 100644 crates/mega-evm/benches/common/workload.rs delete mode 100644 crates/mega-evm/benches/comp_cost.rs create mode 100644 crates/mega-evm/benches/corpus.rs delete mode 100644 crates/mega-evm/benches/ctt.rs delete mode 100644 crates/mega-evm/benches/enriched_tx.rs create mode 100644 crates/mega-evm/benches/factory.rs delete mode 100644 crates/mega-evm/benches/mega_bench.rs delete mode 100644 crates/mega-evm/benches/revm_bench.rs create mode 100644 crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json create mode 100644 crates/mega-evm/benches/scenarios/create_success.json create mode 100644 crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json create mode 100644 crates/mega-evm/benches/scenarios/logs_all_topic_counts.json create mode 100644 crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json create mode 100644 crates/mega-evm/benches/scenarios/precompile_ecrecover.json create mode 100644 crates/mega-evm/benches/scenarios/precompile_modexp.json create mode 100644 crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json create mode 100644 crates/mega-evm/benches/scenarios/sstore_set_spills.json create mode 100644 crates/mega-evm/benches/scenarios/system_call.json create mode 100644 crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json create mode 100644 crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json create mode 100644 crates/mega-evm/benches/scenarios/two_txs_sequential.json delete mode 100644 crates/mega-evm/examples/beneficiary_access_tracking.rs delete mode 100644 crates/mega-evm/examples/block_env_tracking.rs delete mode 100644 crates/mega-evm/src/AGENTS.md delete mode 100644 crates/mega-evm/src/access/AGENTS.md delete mode 100644 crates/mega-evm/src/access/tracker.rs delete mode 100644 crates/mega-evm/src/access/volatile.rs delete mode 100644 crates/mega-evm/src/block/AGENTS.md delete mode 100644 crates/mega-evm/src/block/eips.rs delete mode 100644 crates/mega-evm/src/block/factory.rs delete mode 100644 crates/mega-evm/src/block/helpers.rs delete mode 100644 crates/mega-evm/src/block/limit.rs delete mode 100644 crates/mega-evm/src/evm/AGENTS.md create mode 100644 crates/mega-evm/src/evm/frame.rs create mode 100644 crates/mega-evm/src/evm/inspector.rs delete mode 100644 crates/mega-evm/src/evm/interfaces.rs delete mode 100644 crates/mega-evm/src/evm/limit.rs delete mode 100644 crates/mega-evm/src/evm/precompiles.rs delete mode 100644 crates/mega-evm/src/evm/state.rs delete mode 100644 crates/mega-evm/src/external/gas.rs delete mode 100644 crates/mega-evm/src/limit/AGENTS.md delete mode 100644 crates/mega-evm/src/limit/compute_gas.rs delete mode 100644 crates/mega-evm/src/limit/data_size.rs delete mode 100644 crates/mega-evm/src/limit/kv_update.rs create mode 100644 crates/mega-evm/src/limit/record.rs delete mode 100644 crates/mega-evm/src/limit/state_growth.rs delete mode 100644 crates/mega-evm/src/limit/storage_call_stipend.rs delete mode 100644 crates/mega-evm/src/sandbox/execution.rs delete mode 100644 crates/mega-evm/src/sandbox/mod.rs delete mode 100644 crates/mega-evm/src/sandbox/state.rs delete mode 100644 crates/mega-evm/src/sandbox/state_merge.rs delete mode 100644 crates/mega-evm/src/system/AGENTS.md delete mode 100644 crates/mega-evm/src/system/deploy.rs delete mode 100644 crates/mega-evm/src/system/intercept.rs rename crates/mega-evm/src/{sandbox => system/keyless}/error.rs (91%) create mode 100644 crates/mega-evm/src/system/keyless/mod.rs rename crates/mega-evm/src/{sandbox => system/keyless}/tx.rs (88%) delete mode 100644 crates/mega-evm/src/system/keyless_deploy.rs delete mode 100644 crates/mega-evm/src/system/oracle.rs delete mode 100644 crates/mega-evm/src/system/sequencer_registry.rs delete mode 100644 crates/mega-evm/src/system/tx.rs create mode 100644 crates/mega-evm/src/test_utils/scenario.rs create mode 100644 crates/mega-evm/tests/_pending/README.md rename crates/mega-evm/tests/{ => _pending}/block_executor/accessed_block_hashes.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/block_limits.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/canonical_schedule.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/deposit_da_exemption.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/inspector.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/main.rs (91%) rename crates/mega-evm/tests/{ => _pending}/block_executor/sequencer_registry.rs (100%) rename crates/mega-evm/tests/{ => _pending}/block_executor/trait_factory_runtime_limits.rs (100%) rename crates/mega-evm/tests/{ => _pending}/compute_gas/claims.rs (79%) rename crates/mega-evm/tests/{ => _pending}/compute_gas/main.rs (91%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/access_beneficiary_balance.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/block_env_access_tracking.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/block_env_gas_limit.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/compute_gas_limit.rs (87%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/contract_size_limit.rs (81%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/gas.rs (80%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/main.rs (87%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/mega_system_transaction.rs (100%) rename crates/mega-evm/tests/{ => _pending}/mini_rex/oracle.rs (78%) create mode 100644 crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs rename crates/mega-evm/tests/{ => _pending}/mini_rex/tx_data_and_kv_update_limit.rs (82%) rename crates/mega-evm/tests/{ => _pending}/rex/main.rs (76%) rename crates/mega-evm/tests/{ => _pending}/rex/oracle.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex/storage_gas.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex2/keyless_deploy.rs (94%) rename crates/mega-evm/tests/{ => _pending}/rex2/main.rs (80%) rename crates/mega-evm/tests/{ => _pending}/rex2/oracle_hint.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex3/keyless_deploy.rs (84%) rename crates/mega-evm/tests/{ => _pending}/rex3/main.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex3/oracle_gas_limit.rs (83%) rename crates/mega-evm/tests/{ => _pending}/rex3/system_address.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex4/access_control.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex4/beneficiary_detention.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex4/create_safety.rs (52%) rename crates/mega-evm/tests/{ => _pending}/rex4/deployment.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex4/eip7702_delegation_cycle.rs (71%) rename crates/mega-evm/tests/{ => _pending}/rex4/frame_limits.rs (73%) rename crates/mega-evm/tests/{ => _pending}/rex4/gas_detention.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex4/intrinsic_limit_bypass.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex4/keyless_deploy.rs (76%) rename crates/mega-evm/tests/{ => _pending}/rex4/limit_control.rs (98%) rename crates/mega-evm/tests/{ => _pending}/rex4/main.rs (83%) rename crates/mega-evm/tests/{ => _pending}/rex4/storage_call_stipend.rs (69%) rename crates/mega-evm/tests/{ => _pending}/rex5/apply_pending_changes_gas_budget.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/callcode_storage_gas.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/create2_empty_initcode.rs (87%) rename crates/mega-evm/tests/{ => _pending}/rex5/create2_resize_gas_metering.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/db_error.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/deposit_caller_accounting.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/deposit_create_storage_gas.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex5/eip7702_metering.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/eip7702_state_growth.rs (92%) rename crates/mega-evm/tests/{ => _pending}/rex5/gas_validation.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/interceptor_selector_probe.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_deploy_dispatch_parity.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_empty_code_logs.rs (85%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_fee_free.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_gas_cap_postcap_recheck.rs (89%) rename crates/mega-evm/tests/{ => _pending}/rex5/keyless_replay_barrier.rs (87%) rename crates/mega-evm/tests/{ => _pending}/rex5/main.rs (89%) rename crates/mega-evm/tests/{ => _pending}/rex5/oracle_hint_metering.rs (89%) rename crates/mega-evm/tests/{ => _pending}/rex5/pre_block_system_calls.rs (86%) rename crates/mega-evm/tests/{ => _pending}/rex5/precompile_compute_gas.rs (57%) rename crates/mega-evm/tests/{ => _pending}/rex5/sandbox_accounting.rs (57%) rename crates/mega-evm/tests/{ => _pending}/rex5/selfdestruct_beneficiary.rs (93%) rename crates/mega-evm/tests/{ => _pending}/rex5/sstore_storage_gas_error.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex5/stipend_accounting.rs (60%) rename crates/mega-evm/tests/{ => _pending}/rex5/system_tx_replay.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/beneficiary_detention.rs (91%) rename crates/mega-evm/tests/{ => _pending}/rex6/common.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/create2_metering_order.rs (79%) create mode 100644 crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs rename crates/mega-evm/tests/{ => _pending}/rex6/eip7702_authority_accounting.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/error_paths.rs (100%) rename crates/mega-evm/tests/{ => _pending}/rex6/fee_reward_accounting.rs (90%) rename crates/mega-evm/tests/{ => _pending}/rex6/frame_local_accounting.rs (67%) rename crates/mega-evm/tests/{ => _pending}/rex6/keyless_sandbox_hardening.rs (85%) rename crates/mega-evm/tests/{ => _pending}/rex6/main.rs (96%) rename crates/mega-evm/tests/{ => _pending}/rex6/oracle_hint_volatile_access.rs (93%) create mode 100644 crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs rename crates/mega-evm/tests/{ => _pending}/rex6/sequencer_registry_rotation.rs (79%) rename crates/mega-evm/tests/{ => _pending}/rex6/system_tx_metering_exemption.rs (89%) create mode 100644 crates/mega-evm/tests/_pending/src/access/volatile.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/chain.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/eips.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/hardfork.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/helpers.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/limit.rs create mode 100644 crates/mega-evm/tests/_pending/src/block/result.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/context.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/factory.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/host.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/mod.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/precompiles.rs create mode 100644 crates/mega-evm/tests/_pending/src/evm/state.rs create mode 100644 crates/mega-evm/tests/_pending/src/external/gas.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/compute_gas.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/data_size.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/kv_update.rs create mode 100644 crates/mega-evm/tests/_pending/src/limit/limit.rs create mode 100644 crates/mega-evm/tests/_pending/src/sandbox/execution.rs rename crates/mega-evm/{ => tests/_pending}/src/system/control.rs (60%) create mode 100644 crates/mega-evm/tests/_pending/src/system/deploy.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/intercept.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs rename crates/mega-evm/{ => tests/_pending}/src/system/limit_control.rs (63%) create mode 100644 crates/mega-evm/tests/_pending/src/system/oracle.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs create mode 100644 crates/mega-evm/tests/_pending/src/system/tx.rs delete mode 100644 crates/mega-evm/tests/block_executor/partial_ladder.rs delete mode 100644 crates/mega-evm/tests/compute_gas/snapshot.txt delete mode 100644 crates/mega-evm/tests/equivalence/evm_state.rs delete mode 100644 crates/mega-evm/tests/equivalence/main.rs delete mode 100644 crates/mega-evm/tests/mini_rex/db_error.rs delete mode 100644 crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs delete mode 100644 crates/mega-evm/tests/mini_rex/state_growth_limit.rs delete mode 100644 crates/mega-evm/tests/mutation/access_evm.rs delete mode 100644 crates/mega-evm/tests/mutation/block.rs delete mode 100644 crates/mega-evm/tests/mutation/constants.rs delete mode 100644 crates/mega-evm/tests/mutation/external_exec.rs delete mode 100644 crates/mega-evm/tests/mutation/limit.rs delete mode 100644 crates/mega-evm/tests/mutation/main.rs delete mode 100644 crates/mega-evm/tests/rex/intrinsic_gas.rs delete mode 100644 crates/mega-evm/tests/rex2/selfdestruct.rs delete mode 100644 crates/mega-evm/tests/rex4/frame_state_growth.rs delete mode 100644 crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs delete mode 100644 crates/mega-evm/tests/rex5/call_too_deep_guard.rs delete mode 100644 crates/mega-evm/tests/rex5/create_atomicity.rs delete mode 100644 crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs delete mode 100644 crates/mega-evm/tests/rex6/create_frame_accounting.rs delete mode 100644 crates/mega-evm/tests/rex6/metering_order_parity.rs delete mode 100644 crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs create mode 100644 crates/mega-evm/tests/satin/common.rs create mode 100644 crates/mega-evm/tests/satin/db_error.rs create mode 100644 crates/mega-evm/tests/satin/equivalence.rs create mode 100644 crates/mega-evm/tests/satin/inspector.rs create mode 100644 crates/mega-evm/tests/satin/main.rs create mode 100644 crates/mega-evm/tests/satin/outcome.rs create mode 100644 crates/mega-evm/tests/satin/state.rs create mode 100644 crates/mega-evm/tests/satin/static_callee.rs create mode 100644 crates/mega-evm/tests/satin/strategic_stop.rs create mode 100644 crates/mega-evm/tests/satin/synthetic_frame_gas.rs create mode 100644 crates/mega-evm/tests/satin/write_records.rs diff --git a/.cargo/mutants-infra.toml b/.cargo/mutants-infra.toml new file mode 100644 index 000000000..66772a845 --- /dev/null +++ b/.cargo/mutants-infra.toml @@ -0,0 +1,22 @@ +# cargo-mutants configuration for the test gates' own infrastructure. +# +# The canonical run (.cargo/mutants.toml) mutates mega-evm production code and excludes test +# helpers as noise. By that rule the scenario runner (its transaction conversion and its +# execute/commit loop) is helper code, but it is executable logic the benches and later tests rest +# on. This config mutates exactly that; the production run keeps its exclusions unchanged. +# +# Selected by `scripts/mutation_test.sh infra`, which passes the file globs. See mutants/README.md. + +test_tool = "nextest" +# mega-evm's tests cover the scenario runner. +test_package = ["mega-evm"] + +# Same pinned feature set as the production run, so the two generate comparable mutants. +additional_cargo_args = ["--all-features"] + +# No `**/test_utils/**` exclusion here: the scenario runner living under it is the subject. +exclude_globs = ["**/generated/**"] + +minimum_test_timeout = 120 +timeout_multiplier = 3.0 +copy_target = true diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index eb9f37b75..840fddfda 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -4,8 +4,15 @@ # (scripts/mutation_test.sh + scripts/mutation_gate.py) layers diff-scoping, # suppression metadata, and PR gating on top of it. See mutants/README.md. # -# Scope: only `mega-evm` is mutated. `mega-system-contracts` produces 0 mutants -# (its src/ is generated bytecode artifacts), so it is intentionally absent. +# Scope: only `mega-evm` production code is mutated. `mega-system-contracts` +# produces 0 mutants (its src/ is generated bytecode artifacts), so it is +# intentionally absent. +# +# There is a second scope, .cargo/mutants-infra.toml (`scripts/mutation_test.sh +# infra`): the code that implements the test gates themselves, which the +# `**/test_utils/**` exclusion below and the single `test_package` would +# otherwise leave unmutated. The two scopes are disjoint and are gated +# separately; this one keeps its exclusions. # Run tests with nextest (the project's standard runner) and restrict the test # command to the mutated package for speed. diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 485b160b7..a7051b726 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -199,7 +199,10 @@ jobs: strategy: fail-fast: false matrix: - target: [revm_bench, mega_bench, block_bench, transact, comp_cost, ctt, attack_replay] + # The Satin bench set: `transact`, `corpus` and `factory`, until the + # suite is rebuilt on Satin, which restores the full list. Scheduled and + # comment-triggered runs use the default branch's copy of this file. + target: [corpus, factory, transact] steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml new file mode 100644 index 000000000..5493ccd01 --- /dev/null +++ b/.github/workflows/exec-spec.yml @@ -0,0 +1,165 @@ +name: Execution-spec tests + +# Runs the execution-spec-test fixtures with the revm fork's own runner (`scripts/run-tests.sh`, +# release mode) at the fork tag Cargo.lock pins, then counts the state tests the runner executes +# and skips for Osaka (the main fixtures) and Amsterdam (the glamsterdam devnet fixtures) and +# checks them against the numbers pinned below. +# +# An interim gate until the state-test tool is ported to Satin. It checks the fork MegaEvm runs +# on, not MegaEvm. Not a required check. + +on: + workflow_dispatch: + # GitHub fires a schedule only from the default branch's copy of a workflow: this one runs + # weekly once `satin` is the default branch. Until then, dispatch it by hand on `satin`. + schedule: + - cron: "0 4 * * 1" # Weekly, Monday 4:00 UTC + pull_request: + paths: + - Cargo.lock + - Cargo.toml + - .github/workflows/exec-spec.yml + push: + branches: [satin] + paths: + - Cargo.lock + - Cargo.toml + - .github/workflows/exec-spec.yml + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + exec-spec: + name: execution-spec tests + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + # State tests the runner executes and skips, per fork, on the fixture releases + # `scripts/run-tests.sh` downloads at the pinned tag (main v5.4.0 develop fixtures, + # glamsterdam devnet v8.1.0). The skipped ones are the create-collision fixtures with + # storage the runner skips by name, and expected-exception transactions it cannot build + # (bad signatures, blob-hash creates). A change that moves the fork pin, and with it the + # runner or the fixtures, updates them. + OSAKA_EXECUTED: "19465" + OSAKA_SKIPPED: "52" + AMSTERDAM_EXECUTED: "15754" + AMSTERDAM_SKIPPED: "72" + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Read the fork pin from Cargo.lock + id: pin + run: | + sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) + if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then + printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2 + exit 1 + fi + tag=${sources#*tag=} + tag=${tag%%#*} + commit=${sources##*#} + echo "fork tag $tag at $commit" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "commit=$commit" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v4 + with: + repository: megaeth-labs/revm + ref: ${{ steps.pin.outputs.tag }} + path: revm-fork + persist-credentials: false + + - name: Check the tag names the locked revision + working-directory: revm-fork + env: + COMMIT: ${{ steps.pin.outputs.commit }} + run: test "$(git rev-parse HEAD)" = "$COMMIT" + + - name: Read the fork's toolchain + id: rust + working-directory: revm-fork + run: echo "channel=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)" >> "$GITHUB_OUTPUT" + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ steps.rust.outputs.channel }} + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: revm-fork + cache-on-failure: true + + - name: Run the fork's execution-spec suites + working-directory: revm-fork + run: ./scripts/run-tests.sh clean cargo release + + - name: Count the Osaka and Amsterdam state tests + working-directory: revm-fork + run: | + set -euo pipefail + # State tests a fixture tree defines for a fork: one per post-state entry, keyed by the + # fixtures' fork name (`Osaka`). `$fork` in the jq program is a jq variable. + # shellcheck disable=SC2016 + defined() { + find "$1" -name '*.json' -print0 \ + | xargs -0 jq -r --arg fork "$2" '[.[] | .post[$fork] // [] | length] | add // 0' \ + | awk '{ n += $1 } END { print n + 0 }' + } + # The script's run prints no counts, so the two state-test trees run once more with the + # runner's per-test JSON outcome on stderr (about a minute of the job). The build is + # the one the script made. + outcomes() { + cargo run --release -p revme -- statetest --json-outcome --omit-progress "$1" \ + 2> outcomes.jsonl > /dev/null + } + # State tests the runner executed for a fork, keyed by revm's spec id (`OSAKA`). Other + # stderr lines are not JSON and are dropped. `$spec` in the jq program is a jq variable. + # shellcheck disable=SC2016 + executed() { + jq -Rr --arg spec "$1" 'fromjson? | select(type == "object" and .fork == $spec) | .test' \ + outcomes.jsonl | wc -l | tr -d ' ' + } + check() { + local label=$1 dir=$2 fork=$3 spec=$4 want_executed=$5 want_skipped=$6 + local total ran skipped + # `check` runs under `||`, where errexit is off, so every step is guarded here: a + # counting pipeline that prints the expected number and then fails would otherwise + # pass the comparison below. Each command substitution is assigned on its own so the + # assignment carries the command's status (`local total=$(...)` would mask it). + if ! total=$(defined "$dir" "$fork"); then + echo "::error::$label: counting the state tests $dir defines failed" + return 1 + fi + if ! outcomes "$dir"; then + echo "::error::$label: the runner failed on $dir" + return 1 + fi + if ! ran=$(executed "$spec"); then + echo "::error::$label: counting the state tests the runner executed for $spec failed" + return 1 + fi + skipped=$((total - ran)) + echo "$label: $ran executed, $skipped skipped of $total defined ($dir)" + echo "| $label | $ran | $skipped | $total |" >> "$GITHUB_STEP_SUMMARY" + if [ "$ran" != "$want_executed" ] || [ "$skipped" != "$want_skipped" ]; then + echo "::error::$label: expected $want_executed executed and $want_skipped skipped, got $ran and $skipped" + return 1 + fi + } + { + echo "| Fixtures | Executed | Skipped | Defined |" + echo "|---|---:|---:|---:|" + } >> "$GITHUB_STEP_SUMMARY" + status=0 + check Osaka test-fixtures/main/develop/state_tests Osaka OSAKA \ + "$OSAKA_EXECUTED" "$OSAKA_SKIPPED" || status=1 + check Amsterdam test-fixtures/devnet/state_tests Amsterdam AMSTERDAM \ + "$AMSTERDAM_EXECUTED" "$AMSTERDAM_SKIPPED" || status=1 + exit "$status" diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 0452f28e7..a74acc03f 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -1,11 +1,13 @@ name: Mutation Testing -# All mutation-testing CI lives here. Three concerns, one file: +# All mutation-testing CI lives here. Four concerns, one file: # * cargo-mutants gate — generic operators (diff-scoped on PRs, full nightly) +# * infrastructure gate — the same operators on the code that implements the +# test gates, which the production scope excludes # * spec-gate — universalmutator + comby custom operators for # backward-compat spec gates (diff PR + nightly sweep) # * suppression hygiene — flag suppressions that no longer match a live mutant -# All three share the scorer scripts/mutation_gate.py. See mutants/README.md. +# All four share the scorer scripts/mutation_gate.py. See mutants/README.md. on: workflow_dispatch: @@ -125,6 +127,64 @@ jobs: mutation-report.md if-no-files-found: ignore + # ── cargo-mutants: the test gates' own infrastructure ────────────────────── + # The second mutation scope (.cargo/mutants-infra.toml): the scenario runner's + # transaction conversion and execute/commit loop. The production scope + # excludes test helpers as noise, so this executable logic is never mutated + # there. 39 mutants today, so the whole set runs rather than a diff + # slice. Informational: it is not a required check. + infra-mutants: + name: cargo-mutants infrastructure + needs: changes + # Always on nightly/dispatch; on PRs only when the mutated code, its + # configuration or the driver changed. + if: | + always() && + (github.event_name != 'pull_request' || needs.changes.outputs.infra == 'true') + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Install cargo-nextest + uses: taiki-e/install-action@nextest + + - name: Install cargo-mutants + uses: taiki-e/install-action@v2 + with: + tool: cargo-mutants@27.1.0 + + - name: Warm build cache + run: cargo nextest run -p mega-evm --all-features --no-run + + - name: Run mutation testing + env: + OUT_DIR: target/mutants-infra + run: scripts/mutation_test.sh infra + + - name: Score and gate + run: | + python3 scripts/mutation_gate.py report \ + --results target/mutants-infra/mutants.out \ + --suppressions mutants/suppressions.toml \ + --summary "$GITHUB_STEP_SUMMARY" + + - name: Upload mutation artifacts + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutation-results-infra + path: target/mutants-infra/mutants.out + if-no-files-found: ignore + # ── spec-gate: diff-scoped blocking gate on PRs ──────────────────────────── # Only files+lines the PR changed are mutated, so most PRs generate zero # spec-gate mutants and this is near-instant. @@ -260,12 +320,14 @@ jobs: # ── suppression hygiene: gate on relevant PR changes, plus nightly ───────── # `changes` scopes the hygiene job to PRs that could orphan a suppression - # (suppressions, operators, or src edits); nightly/dispatch always run it. + # (suppressions, operators, or src edits) and the infrastructure job to PRs + # that touch its scope; nightly/dispatch always run both. changes: if: github.event_name == 'pull_request' runs-on: ubuntu-24.04 outputs: hygiene: ${{ steps.filter.outputs.hygiene }} + infra: ${{ steps.filter.outputs.infra }} steps: - uses: dorny/paths-filter@v3 id: filter @@ -275,6 +337,11 @@ jobs: - 'mutants/suppressions.toml' - 'mutants/operators/**' - 'crates/mega-evm/src/**' + infra: + - '.cargo/mutants-infra.toml' + - 'crates/mega-evm/src/test_utils/scenario.rs' + - 'scripts/mutation_gate.py' + - 'scripts/mutation_test.sh' orphan-suppressions: name: suppression hygiene @@ -306,10 +373,10 @@ jobs: sudo curl -fsSL https://github.com/comby-tools/comby/releases/download/1.8.1/comby-1.8.1-x86_64-linux -o /usr/local/bin/comby sudo chmod +x /usr/local/bin/comby comby -version - - name: Build the full mutant universe (both engines) + - name: Build the full mutant universe (both engines, both scopes) run: | - # --package mega-evm: match the driver's scope (otherwise --list also - # covers the CLI bins in the virtual workspace's default-members, so a + # --package mega-evm: match the driver's production scope (otherwise --list + # also covers the CLI bins in the virtual workspace's default-members, so a # stale mega-evm suppression could be kept alive by a same-named mutant # in another crate). # No --exclude-re here, so function-suppressed mutants are included — @@ -317,8 +384,19 @@ jobs: # --colors never: CI forces CARGO_TERM_COLOR=always, which would otherwise # embed ANSI codes and break exact suppression matching. cargo mutants --list --package mega-evm --colors never > universe.txt - python3 scripts/umutate.py plan --packs spec-gate \ - | grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' >> universe.txt + # The infrastructure scope is a second mutant population and a suppression may live in + # it, so it joins the universe. Listed through the driver, so its file list stays in + # one place, with SUPPRESS=/dev/null so the driver emits no --exclude-re and function- + # suppressed mutants stay in the universe here too. The grep drops the driver's + # trailing progress lines and fails the step if the scope lists nothing. + SUPPRESS=/dev/null scripts/mutation_test.sh infra --list --colors never \ + | grep -oE 'crates/[^:]+:[0-9]+:[0-9]+: .*' >> universe.txt + # The plan runs on its own so a planner failure still fails the step. + # Its mutant lines are grepped separately: a single-spec engine (the + # satin branch) has no spec gates and the pack finds nothing. grep's + # "no match" (exit 1) is accepted; a grep error (exit 2) still fails. + python3 scripts/umutate.py plan --packs spec-gate > spec-gate-plan.txt + grep -oE 'crates/mega-evm/[^:]+:[0-9]+:[0-9]+: spec-gate .*' spec-gate-plan.txt >> universe.txt || [ $? -eq 1 ] echo "universe: $(wc -l < universe.txt) mutants" - name: Check for orphan suppressions run: | diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml index b371d8737..808da589e 100644 --- a/.github/workflows/replay-bench.yml +++ b/.github/workflows/replay-bench.yml @@ -104,6 +104,11 @@ jobs: bench: name: Replay throughput needs: prepare + # Disabled on the satin branch: this job builds `state-test`, which is not a + # workspace member until it is ported to the Satin engine; the port removes + # this line. (`compare` needs this job, so it is skipped with it.) Scheduled + # and comment-triggered runs use the default branch's copy of this file. + if: false runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 90 permissions: diff --git a/AGENTS.md b/AGENTS.md index 6f4e03b8d..0b5d356df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,14 +4,20 @@ This file provides guidance to AI agents (e.g., claude code, codex, cursor, etc. ## Project Overview -MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on **revm** and **op-revm** by customizing several hooks exposed by trait of revm. +MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on **revm** and **op-revm** by customizing the hooks revm exposes through its traits. + +This branch (`satin`) builds **Satin**, the new engine: a single spec on the MegaETH fork of revm 40.0.3 and the MegaETH fork of op-revm 20.0.0. +Today's `main` is the legacy engine; Satin is the only active spec. +The legacy engine (specs `Equivalence` through `Rex7`, the 1.x crate line on crates.io revm 27) is frozen and is not edited here. + +Satin is being built mechanism by mechanism from an empty skeleton. +The module table below says what exists and which mechanisms fill the rest. ## Build & Development Commands ```bash # Build cargo build -cargo build --release -p mega-evme # CLI tool # Test cargo test # all tests @@ -27,8 +33,8 @@ cargo fmt --all --check cargo clippy --workspace --lib --examples --tests --benches --all-features --locked cargo sort --check --workspace --grouped --order package,workspace,lints,profile,bin,benches,dependencies,dev-dependencies,features -# Benchmarks -cargo bench -p mega-evm --bench transact # wall-clock + HTML report +# Benchmarks: `transact` (MegaEvm next to op-revm), `corpus` (JSON scenarios, a bench input), `factory` (EVM construction) +cargo bench -p mega-evm --bench # wall-clock + HTML report cargo codspeed build -p mega-evm --bench && cargo codspeed run # instruction counts (Linux only) # no_std check (run against riscv target) @@ -42,214 +48,113 @@ Git submodules are required — clone with `--recursive` or run `git submodule u ## Workspace Structure -| Crate | Path | Purpose | -| ----------------------- | ------------------------- | ------------------------------------------------------------------------------------------- | -| `mega-evm` | `crates/mega-evm` | Core EVM implementation | -| `mega-system-contracts` | `crates/system-contracts` | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-state-test` | `crates/mega-state-test` | State-test fixtures + runner library (EEST-compatible, published; imported as `state_test`) | -| `state-test` | `crates/state-test` | Thin CLI front-end over `mega-state-test` (not published) | -| `mega-evme` | `bin/mega-evme` | CLI tool for EVM execution (`run`, `tx`, `replay`) | -| `mega-t8n` | `bin/mega-t8n` | Standalone state transition (t8n) tool | - -## Architecture - -### Spec System (`MegaSpecId`) - -Progression: `EQUIVALENCE` → `MINI_REX` → `MINI_REX_1` → `MINI_REX_2` → `REX` → `REX1` → `REX2` → `REX3` → `REX4` → `REX5` → `REX6` → `REX7` (`MINI_REX_1`/`MINI_REX_2` are alias rungs executing `EQUIVALENCE` and `MINI_REX` behavior respectively) - -- **Spec** defines EVM behavior (what the EVM does). - Defined in `crates/mega-evm/src/evm/spec.rs`. - The code base **MUST** maintain **backward-compatibility**, which means the semantics (i.e., EVM behaviors) must remain the same for existing specs. - The only exception for this is the **unstable** spec that is under active development (if exists, must be the latest one). - - _`REX7` is the current unstable spec under active development._ - When a new spec is introduced, this line should be updated to indicate the unstable spec. - - Frozen and activated are separate properties. - `REX6` is frozen and activated on both networks (see `block/chain.rs`); `REX7` has no activation timestamp yet. - Freezing forbids further semantic change; scheduling is a later, separate decision made in the node chainspecs and mirrored here in `block/chain.rs` for replay tooling. - - Specifications of each behavior-introducing spec can be found in the upgrade pages under `docs/spec/upgrades/`; alias rungs have no page of their own and are recorded in the upgrade overview and `docs/spec/hardfork-spec.md`. -- **Hardfork** (`MegaHardfork`) defines network upgrade events (when specs activate). - Every hardfork schedules a spec rung of its own — the fork→spec mapping is 1:1. - `MiniRex1` and `MiniRex2` schedule the alias specs `MINI_REX_1` and `MINI_REX_2`, whose `behavior()` projects to `EQUIVALENCE` and `MINI_REX` respectively. - Defined in `crates/mega-evm/src/block/hardfork.rs`. -- All specs use `OpSpecId::ISTHMUS` as the Optimism base layer. - But this is subject to change in the future. - -### Core Source Layout (`crates/mega-evm/src/`) - -- **`evm/`** — Core mega-evm logic: spec definitions, context, factory, execution pipeline, modified opcodes (LOG, SELFDESTRUCT), host hooks, precompiles. - This module collects all our modifications and customizations of EVM's behavior for mega-evm based on the revm. -- **`block/`** — Block execution: executor, factory, hardfork-to-spec mapping, limit enforcement, and the canonical per-chain hardfork schedules. - This module defines how a block in MegaETH block should be executed. - `block/chain.rs` is the single source of truth for the mainnet/testnet chain IDs and activation-timestamp schedules (`hardfork_schedule(chain_id)`, `MAINNET_CHAIN_ID`, `TESTNET_CHAIN_ID`, `mainnet_hardforks()`, `testnet_hardforks()`); look there to find or change when a fork activates on a given chain. - Its unknown-chain fallback pins a named spec rather than following the latest one, so introducing a spec does not move chains that run from genesis; advancing that pin is a deliberate edit made when a spec is sealed. - Forks map 1:1 onto an ascending spec ladder, so the resolved `spec_id` is monotone; rollbacks are alias specs (`MINI_REX_1`, `MINI_REX_2`) whose `behavior()` projects to an earlier spec. - One value, two projections that must not be confused: `is_enabled` compares behavior and gates EVM semantics (rolls back in alias windows); `reaches` compares ladder position and gates one-way chain setup such as predeploys and pre-block rules (never rolls back). - The `is__active_at_timestamp` predicates are position projections for behavior-introducing forks and raw event queries for alias forks, and `MegaHardforks::validate_schedule` is the load-time check that a published schedule climbs the ladder without gaps. -- **`limit/`** — Resource limit tracking: compute gas, data size, KV updates, state growth (each in its own module). - MegaETH introduces additional resource metering mechanism and this module implements their logic as utility structs to be used by mega-evm. -- **`access/`** — Block env access tracking and volatile data detection for parallel execution. - MegaETH incorporates parallel EVM, so it is essential to reduce the conflicts between transactions by restricting the access to some "hot" resources. - This module collects the logic of tracking the access to such hot resources during transaction execution. -- **`external/`** — External environmental context depended by mega-evm. - The execution of mega-evm relies on some external environment information, in addition to revm's normal BlockEnv and CfgEnv. -- **`system/`** — System contract integration. - MegaETH provides several system contracts that are predeployed on the chain. - Any modification of such system contract must induce a new Spec to ensure backward compatibility. -- **`sandbox/`** — Isolated EVM execution -- **`constants.rs`** — All numeric constants organized by spec -- **`types.rs`** — Shared type definitions - -### Key Concepts - -#### Backward Compatibility of Specs - -The spec system (`MegaSpecId`) forms a linear progression where each newer behavior-introducing spec includes all previous behaviors; the alias rungs are the exception, re-executing an earlier spec's behavior instead. -The codebase **MUST** maintain backward-compatibility: EVM semantics must never change for existing (stable) specs. -The only exception is the latest spec if explicitly marked as **unstable**. -Consequently: - -- Adding/modifying a system contract requires introducing a new spec. -- Changing gas costs, opcode behavior, or resource limits requires a new spec. -- Code should use `spec.is_enabled(MegaSpecId::X)` to gate spec-specific behavior. -- Modified opcodes (e.g., SELFDESTRUCT behavior varies by spec) are wired per-spec in the instruction table (`evm/instructions.rs`). - -#### Dual Gas Model (Compute Gas vs Storage Gas) - -MegaETH separates EVM gas into two independent dimensions tracked during execution: - -- **Compute gas**: Measures pure computational cost. - Every opcode's gas consumption is recorded via wrapped instructions in `evm/instructions.rs` — `compute_gas_ext::*` for plain opcodes and `storage_gas_ext::*` for storage-affecting opcodes (SSTORE, LOG, CALL-family, CREATE/CREATE2, SELFDESTRUCT) — both invoking the shared `record_storage_compute_gas!` primitive after the opcode body completes. - Subject to a per-spec compute gas limit and further restricted by gas detention (see below). -- **Storage gas**: Charges for persistent state modifications (SSTORE, account creation, contract deployment). - These costs scale dynamically with SALT bucket capacity (see External Environment Dependencies below). - LOG opcodes are charged in both dimensions: standard compute gas rates plus a storage gas multiplier on topic and data costs. - -Both dimensions are enforced independently. -A transaction can be halted by exceeding either limit. - -#### Multidimensional Resource Limits - -Beyond the dual gas model, mega-evm enforces **four independent per-transaction resource limits** via `AdditionalLimit` (`limit/limit.rs`): - -- **Compute gas** — Computational opcode cost -- **Data size** — Calldata + logs + storage writes + code deploy + account updates -- **KV updates** — Storage writes + account modifications (net, with refunds) -- **State growth** — Net new accounts + net new storage slots (not all specs enable this) - -Each dimension has its own per-spec limit defined in `constants.rs`. -All trackers are **frame-aware**: reverted inner calls discard their tracked usage, successful calls merge into the parent frame. -When any limit is exceeded, execution halts with `OutOfGas` and remaining gas is preserved for refund. - -#### Gas Detention (Volatile Data Access Restriction) - -MegaETH's parallel EVM needs to minimize conflicts between concurrent transactions. -"Volatile" data — block environment fields (NUMBER, TIMESTAMP, COINBASE, etc.), the beneficiary's account state, and the oracle contract — is frequently read by many transactions and thus a major source of conflicts. - -**Gas detention** restricts computation after volatile data is accessed by capping the remaining compute gas: - -- Different volatile data categories (block env/beneficiary, oracle) have different cap levels defined in `constants.rs`. -- The **most restrictive cap wins** when multiple volatile sources are accessed. -- Caps are applied via host hooks (`evm/host.rs`) that mark access in a `VolatileDataAccessTracker` (`access/tracker.rs`), then enforced after each volatile opcode via `wrap_op_detain_gas!` in `evm/instructions.rs`. +| Crate | Path | Member | Purpose | +| ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | +| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | +| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | +| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | +| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | +| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | +| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | -This forces transactions that touch volatile data to terminate quickly, reducing parallel execution conflicts without banning the access outright. -Detained gas is effectively refunded — users only pay for actual computation performed. +The four tool crates still target the legacy engine. +They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until they are ported to Satin. -#### Storage Gas Stipend (Rex4+) +### Dependencies on the forks -MegaETH's 10× storage gas multiplier on LOG opcodes causes even `LOG1` to cost 4,500 gas, exceeding the EVM's `CALL_STIPEND` of 2,300. -Rex4 introduced `STORAGE_CALL_STIPEND` (23,000 gas) for internal (`depth > 0`) value-transferring `CALL`/`CALLCODE`; Rex5 reworked it into a separated allowance, so the tracker is dual-mode. -Under Rex5 the stipend is a per-frame allowance that does NOT inflate the child's `gas_limit`: it is drawn only at MegaETH's storage-gas surcharge sites (LOG topic/data, new-account materialization, first-time-write SSTORE, contract-creation storage, SELFDESTRUCT beneficiary creation), is structurally unspendable on compute, and is neither returned to the caller nor rescued for the sender — nothing is burned because nothing ever enters the frame's gas limit. -Under Rex4 (legacy mode) the stipend instead inflates the child's `gas_limit`, a per-frame compute gas cap keeps the extra gas usable only for storage-gas-heavy operations, and unused stipend is burned on return. +The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crates to the MegaETH fork with `[patch.crates-io]`. +`op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates (`alloy-op-evm`, `op-alloy-*`) come from the same monorepo revision. -The stipend lifecycle is managed by `StorageCallStipendTracker` (`limit/storage_call_stipend.rs`), which maintains a per-frame stack aligned with the EVM call stack. -The tracker's `before_frame_init` method is called inside `AdditionalLimit::before_frame_init`, after all four sub-trackers push their frames (so the compute gas frame exists for the Rex4 legacy-mode per-frame cap). +- Patch the twelve revm crates together, or the build resolves a second copy of revm. +- `cargo tree -i revm` must show exactly one revm, from the fork. +- The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. -The storage gas stipend is subject to the general gas leakage pitfalls described below. - -#### System Contracts - -MegaETH pre-deploys system contracts at well-known addresses (`0x634200...0001`, `0002`, `0003`, etc.). -They are deployed idempotently during `pre_execution_changes()` in `block/executor.rs`, gated by hardfork activation: - -| Contract | Address suffix | Purpose | -| ------------------------ | -------------- | --------------------------------------------------- | -| Oracle | `...0001` | External key-value storage with hint support | -| High-Precision Timestamp | `...0002` | Sub-second block timestamp | -| Keyless Deploy | `...0003` | Deterministic contract deployment via Nick's Method | -| MegaAccessControl | `...0004` | Access control (disableVolatileDataAccess) | -| MegaLimitControl | `...0005` | Limit query/control (currently remainingComputeGas) | -| SequencerRegistry | `...0006` | System address and sequencer role registry | - -Key design aspects: - -- Solidity sources in `crates/system-contracts/contracts/`, compiled by Foundry, with Rust ABI bindings generated via `alloy-sol-types`. -- Bytecode is versioned and hash-verified at build time (`crates/system-contracts/build.rs`). -- The **MEGA_SYSTEM_ADDRESS** can call whitelisted system contracts as deposit-like transactions — no signature or fee required. - This is how the sequencer updates oracle storage. -- **Any system contract modification requires a new spec** to preserve backward compatibility. - -#### External Environment Dependencies - -mega-evm requires external context beyond revm's standard `BlockEnv`/`CfgEnv`, provided via the `ExternalEnvFactory` trait (`external/factory.rs`): - -- **SALT environment** (`external/salt.rs`): Provides bucket capacity data for dynamic gas pricing. - Each account and storage slot maps to a SALT bucket; gas cost = base cost × (bucket_capacity / MIN_BUCKET_SIZE). - This makes storage operations more expensive in crowded state regions, preventing state bloat. - Implementation: `DynamicGasCost` struct (`external/gas.rs`) lazily caches bucket multipliers. -- **Oracle environment** (`external/oracle.rs`): Supplies storage values for the oracle contract via `get_oracle_storage(slot)`. - Oracle reads in `sload` are **always forced cold** for deterministic replay. - The `on_hint(from, topic, data)` callback enables synchronous oracle hints during execution. -- An `EmptyExternalEnv` implementation disables both features (returns minimum bucket size, no oracle data) for testing or standalone use. - -### Gas Leakage Pitfalls - -Any mechanism that grants, inflates, or adjusts gas on a per-frame basis (e.g., `STORAGE_CALL_STIPEND`, and any future per-frame gas adjustment) must account for all frame termination paths. -Failing to do so can cause system-granted gas to leak back to the parent call frame or the transaction sender. -The following paths are common sources of leakage: - -1. **System contract interception** (`system/intercept.rs`): Interceptors short-circuit `frame_init` before `AdditionalLimit::before_frame_init` runs, producing a synthetic `FrameResult` without a real child EVM frame. - Any per-frame gas adjustment applied in `before_frame_init` is skipped on this path. - The `push_empty_frame()` call maintains stack alignment but does not apply adjustments. - Synthetic results must not assume any per-frame gas mechanism was applied. -2. **Gas rescue on TX-level limit exceed** (`limit/limit.rs`): When a transaction-level resource limit is exceeded, `rescue_gas` captures remaining gas for sender refund. - If a frame's gas was inflated by a per-frame mechanism, the rescued amount must exclude the inflated portion — otherwise the sender recovers system-granted gas that should have been burned. -3. **Frame return** (`limit/limit.rs`): `before_frame_return_result` is the final hook before gas is returned to the parent. - Any per-frame gas adjustment must be unwound here (e.g., burning unused granted gas). - The unwinding must apply identically on success and revert — conditional unwinding can leak gas on one path. - -When adding a new per-frame gas mechanism, verify that all three paths handle it correctly and add tests for each. - -### Resource-Limit Check Protocol +## Architecture -The per-opcode hot path records and checks only the compute-gas dimension (`AdditionalLimit::record_compute_gas`). -Correctness of the other three dimensions (data size, KV updates, state growth) rests on a protocol instead of a per-opcode fan-out across all four trackers: +### Spec System (`MegaSpecId`) -1. **Every non-compute mutation site must latch.** - Any code that records data-size/KV/state-growth usage during execution (`on_sstore`, `on_log`, `record_oracle_hint_bytes`, the frame-lifecycle hooks) must run `check_limit()` itself, latching any exceed into `has_exceeded_limit`. - The latch is surfaced by the leading short-circuit of the next `record_compute_gas` call, so the halt lands on the same opcode as the pre-protocol fan-out did. -2. **Pre-inner recorders must NOT latch.** - A site that records usage _before_ its inner instruction executes (currently SELFDESTRUCT's two beneficiary recorders: empty-beneficiary creation and the REX6+ existing-beneficiary credit) must record without latching: the inner instruction can still fail, the frame then discards the usage, and an early latch would stick and rewrite the frame's real result. - Such opcodes use a trailing all-dimension check (`record_compute_gas_all_dims`) that runs only after the inner instruction succeeds. -3. **Compute gas is always recorded.** - `record_compute_gas` must record before surfacing any latched exceed — the recorded total feeds the transaction outcome and block-level compute accounting even for transactions halted on another dimension. +`MegaSpecId` has a single rung, `SATIN`, running on `OpSpecId::KARST` (Ethereum `OSAKA`). +`MegaHardfork` has the single fork `Satin`, which activates `SATIN`. -The protocol governs mutation sites that run during execution; the REX6+ post-execution fee-reward accounting is deliberately outside it. -That accounting merges usage into the transaction's reported totals and the block-level cumulative counters after the execution result is final, without latching, and never retroactively fails the transaction. +- `SATIN` is the unstable spec under active development: it has no activation timestamp yet (`block/chain.rs` lists the two chains with the Satin timestamp unset), and its behavior may change until it is sealed. +- Display and `FromStr` use `"Satin"`; serde uses the variant name `"SATIN"`. +- The legacy spec names (`Equivalence` … `Rex7`) parse to `ParseMegaSpecError::Legacy`; they are never mapped to Satin. +- There are no spec gates: a single-spec engine has nothing to gate. + The spec that follows Satin introduces the first `is_enabled`-style gate. -Rule 1 is backed by a `debug_assert!` in `record_compute_gas`: if a non-compute dimension is over its limit but not yet latched, the assert trips at the exact opcode whose mutation site forgot to call `check_limit()`. -The sub-tracker checks are non-mutating, so the guard compiles out of release builds. +### Core Source Layout (`crates/mega-evm/src/`) -When adding an opcode or mutation site that touches a non-compute dimension, decide whether it records after or before its inner instruction, follow the matching case above, and add a test asserting the exceed halts at that opcode. +| Module | Holds now | Filled by | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle and `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host and the non-warming journal reads (`host.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers (`instructions.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` (alloy-evm) | the Satin gas table, SALT pricing, history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; the system contract interceptors (`MegaEvm::intercept`), native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | +| `block/` | `MegaHardfork`, the chain activation table, a `MegaBlockExecutor` skeleton, `BlockGasCounters` (`result.rs`) | the block executor (Karst block rules, filling `BlockGasCounters`, refusing `has_rewriting_inspector`), the pre-block system calls, the system contract deployments | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs` | SALT pricing, the oracle | +| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | +| `access/` | nothing | volatile-data access tracking (detention) | +| `system/` | `keyless`: the Nick's Method transaction format, validation helpers and error ABI (data only) | the system contract interceptors, deployment and oracle and control contracts; keyless deployment as a native CREATE sub-frame | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, data-size limits) | read by the gas and limit mechanisms; the numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | +| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | + +### How Satin executes today + +- `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. + It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Osaka gas table, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off. + Gas above the 200M execution cap goes to the EIP-8037 reservoir. + The Osaka gas table prices state gas at zero, so no transaction draws state gas until the Satin gas table is installed. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did. + With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. +- The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. +- The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. + +### Contracts of the common execution layer + +Every later mechanism plugs into these; a change to one comes back to this layer. + +- **The Host only observes.** + `sstore`, `log` and `selfdestruct` stage the facts revm hands them (`StagedRecord`) and record nothing. + Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop the transaction for a write that never happened. +- **Commit after the opcode.** + The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed. + Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's. +- **Write records.** + One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account. + The sender's own account is part of the transaction body: it is never a record, and a frame running as the sender (through an EIP-7702 delegation) counts it as recorded. + Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped. + The KV count a node reports is the write-record count. +- **Lanes stay aligned with frames.** + `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the latch, the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran. +- **The latch.** + A transaction-level limit stops the transaction with a revert, never a halt: the frame that crosses it reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)`, the transaction is latched (`AdditionalLimit::latch`), no caller resumes (`before_frame_run`), no frame starts, every result returned above is rewritten to the stop, and the outermost frame settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. + A frame budget reverts its frame alone, without a latch. + A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed), and EIP-7702 authorities whose records would cross it are taken back before the first frame. + A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted. + The layer's state belongs to one transaction: every entry point of `MegaEvm` resets it before it runs the handler. + The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes. +- **Synthetic frame results carry the caller's pools.** + A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). +- **The admission gate.** + A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses, and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. + The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). + The test utilities' inspectors are not declared. +- **Three ledgers.** + `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. + `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. ## Test Organization (`crates/mega-evm/tests/`) -Tests are organized by spec: `equivalence/`, `mini_rex/` (12 modules), `rex/`, `rex2/`, `rex3/`, `rex4/`, `rex5/`, `rex6/`, and `block_executor/`. -Each module tests specific features of that spec. +- `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). +- `_pending/` — the legacy tests the test inventory keeps, parked until the mechanism they test lands. + It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. + The change that ports a pending test deletes it from `_pending/` in the same commit. +- Unit tests live next to the code in `#[cfg(test)] mod tests`. ## Version Control -The main branch is `main`, but it's protected. -All change should be made via PRs on GitHub. +`satin` is the integration branch of the new engine; pull requests for Satin target `satin`. +`main` carries the legacy engine and is not touched from Satin work. +Both are protected: all changes go through PRs on GitHub. ### Branch naming convention @@ -274,14 +179,14 @@ The commit message should be short and exclude any information of the agent itse When a PR creation is requested, the agent should: -1. Check if the repo is current on a different branch other than `main`. +1. Check if the repo is current on a different branch other than `satin` or `main`. If not, create and checkout to a new branch. Make sure to inform the user about this branch creation. 2. Commit the changes in the worktree before fix linting issues. 3. Run lint check, and fix any lint warnings, and then commit if there are any changes. 4. Format the code and commit if there are any changes. 5. Push to the remote. -6. Use `gh` CLI tool to create a PR. +6. Use `gh` CLI tool to create a PR against `satin`. When generating the PR title and description, consider the overall changes in this branch across commits. In the PR description, make sure a `Summary` section is put on the top. The PR will be merged with `Squash and Merge` operation, whose commit description should include the summary. @@ -295,9 +200,17 @@ When the agent is requested to implement a new feature or bug fix, it should con ## Caveats for Agents +- **Satin is the only active spec; the legacy engine is frozen.** + Do not add legacy specs, alias rungs or spec gates to this crate, and do not port a legacy mechanism the legacy test inventory retired. + Behavior of the legacy specs is changed only on the legacy line, never here. +- **Build from the skeleton, one mechanism at a time.** + Each module is filled by the mechanisms named in the module table; do not implement another mechanism to make yours work. + If a change needs an interface that belongs to another mechanism, stub the smallest interface and name the mechanism that owns it. - **Always test logic changes.** Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. +- **Keep the op-revm baseline honest.** + A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. This includes new or modified opcode behavior, gas mechanics, system contract interception, resource limit tracking, and block executor pipeline changes. @@ -309,30 +222,18 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Use `test_` prefix for Rust test function names.** New `#[test]` functions should be named with a `test_` prefix for consistency with this repository and upstream revm style. If editing nearby tests in the same module, align names to the same `test_` style when reasonable. -- **Do NOT modify behavior for existing stable specs.** - All specs through `REX6` are frozen; `REX7` is the unstable spec under active development. - A spec being frozen is independent of whether any network has scheduled it — a frozen spec is off-limits to behavior changes whether or not a timestamp has been published. - New EVM behavior, gas cost changes, or opcode modifications for stable specs **must** introduce a new spec and be gated with `spec.is_enabled(MegaSpecId::NEW_SPEC)`. - Never change what an existing stable spec does. -- **System contract changes require a new spec.** - Do not modify system contract Solidity sources or their Rust integration without also introducing a new spec for backward compatibility. -- **Override `HardforkParams::validate()` for every new params type.** - The default implementation accepts any value silently. - Override it with field-level invariant checks (e.g., non-zero addresses) so that `with_params()` panics loudly at chain-config load time rather than allowing the error to surface at the first block where the fork activates. - Also register the fork-requires-params rule in `MegaHardforks::validate_schedule` so a schedule that activates the fork without its params fails validation, not the fork's first block. -- **Pre-block helpers must return state, not commit directly.** - Any helper participating in `pre_execution_changes` (system contract deploys, pre-block system calls, etc.) MUST return `Option` and never call `db.commit(...)` directly. - Full convention: `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`. -- **Define value-transfer policy explicitly for system contract interceptors.** - For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor. - If a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. -- **Do not intercept unknown selectors for system contracts.** - Unknown selectors should fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. -- **Only `CALL` and `STATICCALL` reach interceptor dispatch.** - `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard in `frame_init` before any interceptor is consulted. - Do not expect these schemes to trigger system contract interception. -- **System contract interceptor tests must cover boundary behaviors.** - Include tests for normal intercepted path, non-zero value behavior, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE interception boundaries. +- **System contracts carry over as they are.** + Satin reuses the Solidity sources and bindings in `crates/system-contracts`; changing a contract needs a decision of its own, not a side effect of an engine change. +- **Rules for system contract interceptors (once the interceptors land).** + For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor; if a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. + Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. + Only `CALL` and `STATICCALL` reach interceptor dispatch; `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard before any interceptor is consulted. + Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. +- **Validate per-fork parameters at load time (once the block executor lands).** + A hardfork parameters type overrides `HardforkParams::validate()` with field-level invariant checks, so a bad chain config fails when it is loaded rather than at the fork's first block. + The fork-requires-params rule is registered in the schedule validation too, so a schedule that activates the fork without its params is rejected at load time. +- **Pre-block helpers must return state, not commit directly (pre-block system calls, system contract deployment).** + Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. @@ -353,9 +254,9 @@ When the agent is requested to implement a new feature or bug fix, it should con Run `cargo fmt --all --check` before completion. - **Keep documentation up to date.** When making changes, always check whether related documentation needs updating. - The primary documentation is in `docs/`. + The primary documentation is in `docs/`; it still describes the legacy engine until the Satin specification pages are written. The spec documentation is under `docs/spec/`, and the mega-evme documentation is under `docs/mega-evme/`. - Also update this `AGENTS.md` when relevant (e.g., unstable spec marker, spec progression list, system contract table). + Also update this `AGENTS.md` when relevant (e.g., the module table, the unstable-spec marker). - **One sentence, one line.** When writing markdown or similar format files, put each sentence in a separate line. - **Run Prettier on docs before committing.** diff --git a/Cargo.lock b/Cargo.lock index 2b72f2d86..8c311d18f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,17 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addchain" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2e69442aa5628ea6951fa33e24efe8313f4321a91bd729fc2f75bdfc858570" -dependencies = [ - "num-bigint 0.3.3", - "num-integer", - "num-traits", -] - [[package]] name = "ahash" version = "0.8.12" @@ -42,20 +31,20 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "alloy-chains" -version = "0.2.6" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4195a29a4b87137b2bb02105e746102873bc03561805cf45c0e510c961f160e6" +checksum = "c1c4f6f6f020f38a4ef079428b5c7009e913bf8102e4d65a90c6cb2cf93800eb" dependencies = [ "alloy-primitives", "num_enum", - "strum", + "phf 0.14.0", ] [[package]] name = "alloy-consensus" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90d103d3e440ad6f703dd71a5b58a6abd24834563bde8a5fabe706e00242f810" +checksum = "0b836b372d3b742b7c083d2617d6e68563cd5dadbd8752c461a935a756551e69" dependencies = [ "alloy-eips", "alloy-primitives", @@ -64,6 +53,7 @@ dependencies = [ "alloy-trie", "alloy-tx-macros", "auto_impl", + "borsh", "c-kzg", "derive_more", "either", @@ -79,9 +69,9 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48ead76c8c84ab3a50c31c56bc2c748c2d64357ad2131c32f9b10ab790a25e1a" +checksum = "b1befb37485ea71e8599e32ffd76c98af7c3720a34741d30abd87f41c3148407" dependencies = [ "alloy-consensus", "alloy-eips", @@ -132,9 +122,9 @@ dependencies = [ [[package]] name = "alloy-eip7928" -version = "0.3.7" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b827a6d7784fe3eb3489d40699407a4cdcce74271421a01bdffe60cf573bb16" +checksum = "6a12e1dc70236cfb8e79b96dd8544aed47c39e2f45dc6b51c3703e969e052faa" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -146,9 +136,9 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "1.8.3" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6ef28c9fdad22d4eec52d894f5f2673a0895f1e5ef196734568e68c0f6caca8" +checksum = "ca3e76d47e8de277cb55e7e77fa38adde835162fc01cddbe1b258b5e0a86035b" dependencies = [ "alloy-eip2124", "alloy-eip2930", @@ -162,35 +152,53 @@ dependencies = [ "c-kzg", "derive_more", "either", + "ethereum_ssz", + "ethereum_ssz_derive", "serde", "serde_with", - "sha2 0.10.9", + "sha2", ] [[package]] name = "alloy-evm" -version = "0.15.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28de0dd1bbb0634ef7c3715e8e60176b77b82f8b6b15b2e35fe64cf6640f6550" +checksum = "a6e494529570a4d25eb4d1a7456d8f969c3202aceaf703e4006cec5f730aee96" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-hardforks", "alloy-primitives", + "alloy-rpc-types-engine", + "alloy-rpc-types-eth", "alloy-sol-types", "auto_impl", "derive_more", - "op-alloy-consensus", - "op-revm 8.1.0", - "revm 27.1.0", + "revm", "thiserror", + "tracing", +] + +[[package]] +name = "alloy-genesis" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0680a2f7d4bbc6f48c0cb43368fa544918a1fa291e772bdb47c834ade338f363" +dependencies = [ + "alloy-eips", + "alloy-primitives", + "alloy-serde", + "alloy-trie", + "borsh", + "serde", + "serde_with", ] [[package]] name = "alloy-hardforks" -version = "0.2.13" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165210652f71dfc094b051602bafd691f506c54050a174b1cba18fb5ef706a3" +checksum = "865371fb677c005f7cb0ea9c2847a1ba4fdb042caf6428b1769fee20368bbfc7" dependencies = [ "alloy-chains", "alloy-eip2124", @@ -201,9 +209,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5513d5e6bd1cba6bdcf5373470f559f320c05c8c59493b6e98912fbe6733943f" +checksum = "7c36c9d7f9021601b04bfef14a4b64849f6d73116a4e91e071d7fbfe10247901" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -213,9 +221,9 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003f46c54f22854a32b9cc7972660a476968008ad505427eabab49225309ec40" +checksum = "2a523ca087dda941e53f6ecde5bf5df78b9dbe760f3f77488e13dbf355de4a84" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -228,9 +236,9 @@ dependencies = [ [[package]] name = "alloy-network" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612296e6b723470bb1101420a73c63dfd535aa9bf738ce09951aedbd4ab7292e" +checksum = "f263c8d752b15e19b7c2d3cbad00338ec2d7cc923a46cd1ff98aea2fa333166b" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -254,9 +262,9 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0e7918396eecd69d9c907046ec8a93fb09b89e2f325d5e7ea9c4e3929aa0dd2" +checksum = "8795eecf50374a0dd942caff57922c59333c9991ead9eccbbc1709f55d73c7c2" dependencies = [ "alloy-consensus", "alloy-eips", @@ -267,9 +275,8 @@ dependencies = [ [[package]] name = "alloy-op-evm" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0afe768962308a08b42fddef8a4296324f140b5a8dd0d4360038229885ce9434" +version = "0.32.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-consensus", "alloy-eips", @@ -277,19 +284,20 @@ dependencies = [ "alloy-op-hardforks", "alloy-primitives", "auto_impl", - "op-alloy-consensus", - "op-revm 8.1.0", - "revm 27.1.0", + "op-alloy", + "op-revm", + "revm", + "thiserror", ] [[package]] name = "alloy-op-hardforks" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3417f4187eaf7f7fb0d7556f0197bca26f0b23c4bb3aca0c9d566dc1c5d727a2" +version = "0.5.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-chains", "alloy-hardforks", + "alloy-primitives", "auto_impl", ] @@ -304,7 +312,7 @@ dependencies = [ "cfg-if", "const-hex", "derive_more", - "foldhash 0.2.0", + "foldhash", "hashbrown 0.17.1", "indexmap 2.10.0", "itoa", @@ -323,9 +331,9 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55c1313a527a2e464d067c031f3c2ec073754ef615cc0eabca702fd0fe35729c" +checksum = "ef487e44dfae9c87cb732989d3f43682f65aefb11a0f56045b26be357f671fcf" dependencies = [ "alloy-chains", "alloy-consensus", @@ -335,7 +343,9 @@ dependencies = [ "alloy-network-primitives", "alloy-primitives", "alloy-rpc-client", + "alloy-rpc-types-debug", "alloy-rpc-types-eth", + "alloy-rpc-types-trace", "alloy-signer", "alloy-sol-types", "alloy-transport", @@ -347,6 +357,7 @@ dependencies = [ "either", "futures", "futures-utils-wasm", + "http", "lru", "parking_lot", "pin-project", @@ -362,9 +373,9 @@ dependencies = [ [[package]] name = "alloy-rlp" -version = "0.3.12" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f70d83b765fdc080dbcd4f4db70d8d23fe4761f2f02ebfa9146b833900634b4" +checksum = "24671b1f62edcf0f9b62994c7bf72cd621a04a4b99f5020ece1a647b40e2f103" dependencies = [ "alloy-rlp-derive", "arrayvec", @@ -373,9 +384,9 @@ dependencies = [ [[package]] name = "alloy-rlp-derive" -version = "0.3.12" +version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64b728d511962dda67c1bc7ea7c03736ec275ed2cf4c35d9585298ac9ccf3b73" +checksum = "9d4311c03125e8a18296504560b9de3d75ecbd0dcda7f71e6cf2a196d57e6fba" dependencies = [ "proc-macro2", "quote", @@ -384,9 +395,9 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c89883fe6b7381744cbe80fef638ac488ead4f1956a4278956a1362c71cd2e" +checksum = "98267c2d47f9c185b575bac3f772a8ca66bcbd712693535e50980c12eab80a42" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -407,20 +418,56 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdbf6d1766ca41e90ac21c4bc5cbc5e9e965978a25873c3f90b3992d905db4cb" +checksum = "1176430031ba27abfb51b95516cf71e8ce3ff4172c72f3136627f0f89813a739" dependencies = [ "alloy-consensus-any", + "alloy-network-primitives", + "alloy-primitives", "alloy-rpc-types-eth", "alloy-serde", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-rpc-types-debug" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a97960aa11b9984a18580b8dfbfc3eacfce1befa0d588b03ccc0bc5563d01f8" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "derive_more", + "serde", + "serde_with", +] + +[[package]] +name = "alloy-rpc-types-engine" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a43d7b6b86be4885c7a76f1dfcde9651af2d419ff571e8ee7257de47101203b" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-serde", + "derive_more", + "ethereum_ssz", + "ethereum_ssz_derive", + "rand 0.8.5", + "serde", + "strum", ] [[package]] name = "alloy-rpc-types-eth" -version = "1.1.0" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15e4831b71eea9d20126a411c1c09facf1d01d5cac84fd51d532d3c429cfc26" +checksum = "756eb5803e70985be4066b636194ccb5f6629e5d141817c1f0c50cea8350bf5c" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -439,9 +486,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "1.0.24" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6a854af3fe8fce1cfe319fcf84ee8ba8cda352b14d3dd4221405b5fc6cce9e1" +checksum = "1933d60c2f51b8906103484ea2ca2218357264dbf16f948f7c2dd4ac5818e1d8" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -453,9 +500,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "1.8.3" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ece63b89294b8614ab3f483560c08d016930f842bf36da56bf0b764a15c11e" +checksum = "cc142e40df0c3eb5983b1637a68ab33471d8d22b8f402c9ed8260411a4e89d86" dependencies = [ "alloy-primitives", "serde", @@ -464,9 +511,9 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc39ad2c0a3d2da8891f4081565780703a593f090f768f884049aa3aa929cbc" +checksum = "b4c84f88f8a29d2607f98993687ed55a5943ba06819bc2126bb078dca54be943" dependencies = [ "alloy-primitives", "async-trait", @@ -479,9 +526,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3ce480400051b5217f19d6e9a82d9010cdde20f1ae9c00d53591e4a1afbb312" +checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", @@ -493,9 +540,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro-expander" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d792e205ed3b72f795a8044c52877d2e6b6e9b1d13f431478121d8d4eaa9028" +checksum = "63ec265e5d65d725175f6ca7711c970824c90ef9c0d1f1973711d4150ee612dd" dependencies = [ "alloy-sol-macro-input", "const-hex", @@ -504,16 +551,16 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", + "sha3", "syn 2.0.104", "syn-solidity", - "tiny-keccak", ] [[package]] name = "alloy-sol-macro-input" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd1247a8f90b465ef3f1207627547ec16940c35597875cdc09c49d58b19693c" +checksum = "89bf01077f18650876cfa682eb1f949967b5cde03f1a51c955c469d2c9b4aa67" dependencies = [ "const-hex", "dunce", @@ -527,19 +574,19 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "954d1b2533b9b2c7959652df3076954ecb1122a28cc740aa84e7b0a49f6ac0a9" +checksum = "857b470ecdd2ed38beaf82ad1a38c516a8ff75266750f38b9eeed001d575241b" dependencies = [ "serde", - "winnow", + "winnow 1.0.4", ] [[package]] name = "alloy-sol-types" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70319350969a3af119da6fb3e9bddb1bce66c9ea933600cb297c8b1850ad2a3c" +checksum = "384cf252de0db2dec52821eac037a7f57e2aa33fe5b900ce6fe39973402341f1" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -549,13 +596,13 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cae82426d98f8bc18f53c5223862907cac30ab8fc5e4cd2bb50808e6d3ab43d8" +checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" dependencies = [ "alloy-json-rpc", "auto_impl", - "base64", + "base64 0.22.1", "derive_more", "futures", "futures-utils-wasm", @@ -572,12 +619,13 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90aa6825760905898c106aba9c804b131816a15041523e80b6d4fe7af6380ada" +checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" dependencies = [ "alloy-json-rpc", "alloy-transport", + "itertools 0.14.0", "reqwest", "serde_json", "tower", @@ -587,27 +635,27 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.0" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bada1fc392a33665de0dc50d401a3701b62583c655e3522a323490a5da016962" +checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" dependencies = [ "alloy-primitives", "alloy-rlp", - "arrayvec", "derive_more", "nybbles", "serde", "smallvec", + "thiserror", "tracing", ] [[package]] name = "alloy-tx-macros" -version = "1.1.2" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae109e33814b49fc0a62f2528993aa8a2dd346c26959b151f05441dc0b9da292" +checksum = "25484345e4d89c259235e200d4f895eba33e70f125f4e8bb37a7aa69a97bd656" dependencies = [ - "darling", + "darling 0.23.0", "proc-macro2", "quote", "syn 2.0.104", @@ -634,56 +682,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - [[package]] name = "anstyle" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.103" @@ -738,7 +742,7 @@ dependencies = [ "fnv", "hashbrown 0.15.4", "itertools 0.13.0", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "zeroize", @@ -755,7 +759,7 @@ dependencies = [ "ark-serialize 0.3.0", "ark-std 0.3.0", "derivative", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "rustc_version 0.3.3", @@ -775,7 +779,7 @@ dependencies = [ "derivative", "digest 0.10.7", "itertools 0.10.5", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "rustc_version 0.4.1", @@ -796,7 +800,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint 0.4.6", + "num-bigint", "num-traits", "paste", "zeroize", @@ -838,7 +842,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "quote", "syn 1.0.109", @@ -850,7 +854,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "proc-macro2", "quote", @@ -863,7 +867,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09be120733ee33f7693ceaa202ca41accd5653b779563608f1234f78ae07c4b3" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-traits", "proc-macro2", "quote", @@ -896,7 +900,7 @@ dependencies = [ "ark-relations", "ark-std 0.5.0", "educe", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "tracing", @@ -911,7 +915,7 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber 0.2.25", + "tracing-subscriber", ] [[package]] @@ -932,7 +936,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint 0.4.6", + "num-bigint", ] [[package]] @@ -945,7 +949,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint 0.4.6", + "num-bigint", ] [[package]] @@ -1000,19 +1004,6 @@ name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" -dependencies = [ - "serde", -] - -[[package]] -name = "assert-json-diff" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" -dependencies = [ - "serde", - "serde_json", -] [[package]] name = "async-stream" @@ -1038,13 +1029,13 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.89" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] @@ -1080,12 +1071,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" -[[package]] -name = "az" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b7e4c2464d97fe331d41de9d5db0def0a96f4d823b8b32a2efd503578988973" - [[package]] name = "base16ct" version = "0.2.0" @@ -1099,19 +1084,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] -name = "base64ct" -version = "1.8.0" +name = "base64" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] -name = "bincode" -version = "1.3.3" +name = "base64ct" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] +checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" [[package]] name = "bit-set" @@ -1144,6 +1126,12 @@ dependencies = [ "hex-conservative", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.11.1" @@ -1166,28 +1154,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "blake3" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if", - "constant_time_eq", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -1242,6 +1208,15 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -1271,9 +1246,9 @@ dependencies = [ [[package]] name = "c-kzg" -version = "2.1.7" +version = "2.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6648ed1e4ea8e8a1a4a2c78e1cda29a3fd500bc622899c340d8525ea9a76b24a" +checksum = "38d04308254695569fdb9bfe3bacc1c91837a670d0806605eb82d63748fbd3a6" dependencies = [ "blst", "cc", @@ -1297,6 +1272,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1312,17 +1289,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" -[[package]] -name = "chacha20" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "rand_core 0.10.1", -] - [[package]] name = "chrono" version = "0.4.41" @@ -1370,7 +1336,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", - "clap_derive", ] [[package]] @@ -1379,22 +1344,8 @@ version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" dependencies = [ - "anstream", "anstyle", "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.5.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.104", ] [[package]] @@ -1475,18 +1426,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "console" -version = "0.15.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" -dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "windows-sys 0.59.0", -] - [[package]] name = "const-hex" version = "1.14.1" @@ -1526,31 +1465,15 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "constant_time_eq" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" - [[package]] name = "convert_case" -version = "0.7.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" 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-sys" version = "0.8.7" @@ -1600,11 +1523,17 @@ dependencies = [ "itertools 0.10.5", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crunchy" @@ -1645,21 +1574,30 @@ dependencies = [ [[package]] name = "darling" -version = "0.21.3" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] name = "darling_core" -version = "0.21.3" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" dependencies = [ - "fnv", "ident_case", "proc-macro2", "quote", @@ -1668,17 +1606,41 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.6", +] + [[package]] name = "darling_macro" -version = "0.21.3" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ - "darling_core", + "darling_core 0.23.0", "quote", "syn 2.0.104", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.6", +] + [[package]] name = "dashmap" version = "6.1.0" @@ -1694,41 +1656,54 @@ dependencies = [ ] [[package]] -name = "deadpool" -version = "0.12.3" +name = "defmt" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" dependencies = [ - "deadpool-runtime", - "lazy_static", - "num_cpus", - "tokio", + "bitflags 1.3.2", + "defmt-macros", ] [[package]] -name = "deadpool-runtime" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" - -[[package]] -name = "delegate" -version = "0.13.4" +name = "defmt-macros" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6178a82cf56c836a3ba61a7935cdb1c49bfaa6fa4327cd5bf554a503087de26b" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" dependencies = [ + "defmt-parser", "proc-macro2", "quote", "syn 2.0.104", ] [[package]] -name = "der" -version = "0.7.10" +name = "defmt-parser" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" dependencies = [ - "const-oid", + "thiserror", +] + +[[package]] +name = "delegate" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6178a82cf56c836a3ba61a7935cdb1c49bfaa6fa4327cd5bf554a503087de26b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", "zeroize", ] @@ -1766,22 +1741,23 @@ dependencies = [ [[package]] name = "derive_more" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ "convert_case", "proc-macro2", "quote", + "rustc_version 0.4.1", "syn 2.0.104", "unicode-xid", ] @@ -1817,36 +1793,15 @@ dependencies = [ "crypto-common 0.2.2", ] -[[package]] -name = "dirs" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.61.2", -] - [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] @@ -1917,21 +1872,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "encode_unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" - -[[package]] -name = "encoding_rs" -version = "0.8.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" -dependencies = [ - "cfg-if", -] - [[package]] name = "enum-ordinalize" version = "4.3.0" @@ -1968,6 +1908,46 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "ethereum_serde_utils" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38df44a7a271ab43835678f9215b53cc2523e4714a215da6643d83dc110245da" +dependencies = [ + "alloy-primitives", + "hex", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "ethereum_ssz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e462875ad8693755ea8913d6e905715c76ea4836e2254e18c9cf0f7a8f8c2a13" +dependencies = [ + "alloy-primitives", + "ethereum_serde_utils", + "itertools 0.14.0", + "serde", + "serde_derive", + "smallvec", + "typenum", +] + +[[package]] +name = "ethereum_ssz_derive" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf022360bdbe9456eda5f35718a50476d5b2a0d51a97ed4eae27420737a6fba" +dependencies = [ + "darling 0.23.0", + "proc-macro2", + "quote", + "syn 2.0.104", +] + [[package]] name = "fastrand" version = "2.3.0" @@ -2002,27 +1982,10 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "byteorder", - "ff_derive", "rand_core 0.6.4", "subtle", ] -[[package]] -name = "ff_derive" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f10d12652036b0e99197587c6ba87a8fc3031986499973c030d8b44fcc151b60" -dependencies = [ - "addchain", - "num-bigint 0.3.3", - "num-integer", - "num-traits", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -2047,33 +2010,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -2091,9 +2033,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -2106,9 +2048,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -2116,15 +2058,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -2133,38 +2075,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] name = "futures-sink" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -2174,7 +2116,6 @@ dependencies = [ "futures-task", "memchr", "pin-project-lite", - "pin-utils", "slab", ] @@ -2184,12 +2125,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" -[[package]] -name = "gcd" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d758ba1b47b00caf47f24925c0074ecb20d6dfcffe7f6d53395c0465674841a" - [[package]] name = "generic-array" version = "0.14.7" @@ -2233,7 +2168,6 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", - "rand_core 0.10.1", ] [[package]] @@ -2242,16 +2176,6 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" -[[package]] -name = "gmp-mpfr-sys" -version = "1.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66d61197a68f6323b9afa616cf83d55d69191e1bf364d4eb7d35ae18defe776" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - [[package]] name = "group" version = "0.13.0" @@ -2263,25 +2187,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "h2" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap 2.10.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "half" version = "2.6.0" @@ -2292,12 +2197,6 @@ dependencies = [ "crunchy", ] -[[package]] -name = "hash-db" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" - [[package]] name = "hashbrown" version = "0.12.3" @@ -2317,8 +2216,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" dependencies = [ "allocator-api2", - "equivalent", - "foldhash 0.1.5", ] [[package]] @@ -2327,7 +2224,9 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "foldhash 0.2.0", + "allocator-api2", + "equivalent", + "foldhash", "serde", "serde_core", ] @@ -2373,20 +2272,19 @@ dependencies = [ [[package]] name = "http" -version = "1.3.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", - "fnv", "itoa", ] [[package]] name = "http-body" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", "http", @@ -2394,9 +2292,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -2411,12 +2309,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.12" @@ -2428,69 +2320,33 @@ dependencies = [ [[package]] name = "hyper" -version = "1.8.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1744436df46f0bde35af3eda22aeaba453aada65d8f1c171cd8a5f59030bd69f" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" dependencies = [ "atomic-waker", "bytes", "futures-channel", "futures-core", - "h2", "http", "http-body", "httparse", - "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", ] -[[package]] -name = "hyper-rustls" -version = "0.27.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" -version = "0.1.17" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-channel", - "futures-core", "futures-util", "http", "http-body", @@ -2500,11 +2356,9 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", - "system-configuration", "tokio", "tower-service", "tracing", - "windows-registry", ] [[package]] @@ -2533,12 +2387,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -2546,9 +2401,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", @@ -2559,9 +2414,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2573,16 +2428,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" [[package]] name = "icu_properties" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -2593,15 +2449,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", @@ -2631,9 +2487,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -2681,33 +2537,11 @@ dependencies = [ "serde", ] -[[package]] -name = "indicatif" -version = "0.17.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" -dependencies = [ - "console", - "number_prefix", - "portable-atomic", - "web-time", -] - [[package]] name = "ipnet" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.9" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f867b9d1d896b67beb18518eda36fdb77a32ea590de864f1325b294a6d14397" -dependencies = [ - "memchr", - "serde", -] +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "is-terminal" @@ -2720,12 +2554,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itertools" version = "0.10.5" @@ -2735,15 +2563,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.13.0" @@ -2769,135 +2588,130 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] -name = "js-sys" -version = "0.3.77" +name = "jiff" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" dependencies = [ - "once_cell", - "wasm-bindgen", + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link 0.2.1", ] [[package]] -name = "k256" -version = "0.13.4" +name = "jiff-core" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" dependencies = [ - "cfg-if", - "ecdsa", - "elliptic-curve", - "once_cell", - "serdect", - "sha2 0.10.9", + "defmt", + "log", ] [[package]] -name = "keccak" -version = "0.2.0" +name = "jiff-static" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e24a010dd405bd7ed803e5253182815b41bf2e6a80cc3bfc066658e03a198aa" +checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.104", ] [[package]] -name = "keccak-asm" -version = "0.1.7" +name = "jiff-tzdb" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1766b89733097006f3a1388a02849865d6bc98c89273cb622e29fdd209922183" -dependencies = [ - "digest 0.10.7", - "sha3-asm", -] +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" [[package]] -name = "kzg-rs" -version = "0.2.7" +name = "jiff-tzdb-platform" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9201effeea3fcc93b587904ae2df9ce97e433184b9d6d299e9ebc9830a546636" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" dependencies = [ - "ff", - "hex", - "serde_arrays", - "sha2 0.10.9", - "sp1_bls12_381", - "spin", + "jiff-tzdb", ] [[package]] -name = "lazy_static" -version = "1.5.0" +name = "jobserver" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] [[package]] -name = "libc" -version = "0.2.186" +name = "js-sys" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +dependencies = [ + "once_cell", + "wasm-bindgen", +] [[package]] -name = "libm" -version = "0.2.15" +name = "k256" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "once_cell", + "serdect", + "sha2", +] [[package]] -name = "libredox" -version = "0.1.15" +name = "keccak" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" +checksum = "9e24a010dd405bd7ed803e5253182815b41bf2e6a80cc3bfc066658e03a198aa" dependencies = [ - "libc", + "cfg-if", + "cpufeatures 0.3.0", ] [[package]] -name = "libsecp256k1" -version = "0.7.2" +name = "keccak-asm" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79019718125edc905a079a70cfa5f3820bc76139fc91d6f9abc27ea2a887139" +checksum = "1766b89733097006f3a1388a02849865d6bc98c89273cb622e29fdd209922183" dependencies = [ - "arrayref", - "base64", - "digest 0.9.0", - "libsecp256k1-core", - "libsecp256k1-gen-ecmult", - "libsecp256k1-gen-genmult", - "rand 0.8.5", - "serde", - "sha2 0.9.9", + "digest 0.10.7", + "sha3-asm", ] [[package]] -name = "libsecp256k1-core" -version = "0.3.0" +name = "lazy_static" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" -dependencies = [ - "crunchy", - "digest 0.9.0", - "subtle", -] +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] -name = "libsecp256k1-gen-ecmult" -version = "0.3.0" +name = "libc" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809" -dependencies = [ - "libsecp256k1-core", -] +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] -name = "libsecp256k1-gen-genmult" -version = "0.3.0" +name = "libm" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c" -dependencies = [ - "libsecp256k1-core", -] +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "linux-raw-sys" @@ -2907,9 +2721,9 @@ checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "lock_api" @@ -2928,131 +2742,51 @@ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "lru" -version = "0.13.0" +version = "0.18.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "227748d55f2f0ab4735d87fd623798cb6b664512fe979705f829c9f81c934465" +checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25" dependencies = [ - "hashbrown 0.15.4", + "hashbrown 0.17.1", ] [[package]] name = "macro-string" -version = "0.1.4" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b27834086c65ec3f9387b096d66e99f221cf081c2b738042aa252bcd41204e3" +checksum = "59a9dbbfc75d2688ed057456ce8a3ee3f48d12eec09229f560f3643b9f275653" dependencies = [ "proc-macro2", "quote", "syn 2.0.104", ] -[[package]] -name = "matchers" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" -dependencies = [ - "regex-automata", -] - [[package]] name = "mega-evm" -version = "1.7.1" +version = "2.0.0-alpha.1" dependencies = [ "alloy-consensus", - "alloy-eips", "alloy-evm", "alloy-hardforks", "alloy-op-evm", - "alloy-op-hardforks", "alloy-primitives", "alloy-sol-types", "auto_impl", - "bitflags", "codspeed-criterion-compat", "delegate", "derive_more", - "hex", "mega-evm", "mega-system-contracts", - "once_cell", "op-alloy-consensus", - "op-alloy-flz", - "op-revm 20.0.0", - "op-revm 8.1.0", - "rand 0.10.2", - "revm 27.1.0", - "revm 38.0.0", + "op-revm", + "revm", "revm-inspectors", "serde", "serde_json", - "sha2 0.10.9", - "thiserror", - "tracing", -] - -[[package]] -name = "mega-evme" -version = "1.7.1" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-json-rpc", - "alloy-network", - "alloy-primitives", - "alloy-provider", - "alloy-rpc-client", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", - "alloy-serde", - "alloy-sol-types", - "alloy-transport", - "alloy-transport-http", - "clap", - "dirs", - "mega-evm", - "mega-evme", - "mega-state-test", - "op-alloy-consensus", - "op-alloy-network", - "op-alloy-rpc-types", - "reqwest", - "revm-inspectors", - "rstest", - "serde", - "serde_json", - "tempfile", - "thiserror", - "tokio", - "tower", - "tracing", - "tracing-subscriber 0.3.20", - "wiremock", -] - -[[package]] -name = "mega-state-test" -version = "1.7.1" -dependencies = [ - "alloy-eips", - "alloy-primitives", - "alloy-rlp", - "alloy-serde", - "hash-db", - "indicatif", - "k256", - "mega-evm", - "plain_hasher", - "serde", - "serde_json", - "thiserror", - "triehash", - "walkdir", ] [[package]] name = "mega-system-contracts" -version = "1.7.1" +version = "2.0.0-alpha.1" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -3061,38 +2795,17 @@ dependencies = [ "serde_json", ] -[[package]] -name = "mega-t8n" -version = "1.7.1" -dependencies = [ - "alloy-consensus", - "alloy-primitives", - "alloy-serde", - "clap", - "mega-evm", - "mega-state-test", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "memchr" version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - [[package]] name = "mio" -version = "1.1.0" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -3100,20 +2813,24 @@ dependencies = [ ] [[package]] -name = "native-tls" -version = "0.2.14" +name = "modular-bitfield" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +checksum = "2956e537fc68236d2aa048f55704f231cc93f1c4de42fe1ecb5bd7938061fc4a" dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", + "modular-bitfield-impl", + "static_assertions", +] + +[[package]] +name = "modular-bitfield-impl" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b43b4fd69e3437618106f7754f34021b831a514f9e1a98ae863cabcd8d8dad" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", ] [[package]] @@ -3122,19 +2839,19 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.11.1", "cfg-if", "cfg_aliases", "libc", ] [[package]] -name = "nu-ansi-term" -version = "0.50.3" +name = "nonmax" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" dependencies = [ - "windows-sys 0.61.2", + "serde", ] [[package]] @@ -3143,7 +2860,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-complex", "num-integer", "num-iter", @@ -3151,17 +2868,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-bigint" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6f7833f2cbf2360a6cfd58cd41a53aa7a90bd4c202f5b1c7dd2ed73c57b2c3" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - [[package]] name = "num-bigint" version = "0.4.6" @@ -3213,7 +2919,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", ] @@ -3254,18 +2960,11 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77e878c846a8abae00dd069496dbe8751b16ac1c3d6bd2a7283a938e8228f90d" dependencies = [ - "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.104", ] -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - [[package]] name = "nybbles" version = "0.4.3" @@ -3285,12 +2984,10 @@ name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +dependencies = [ + "critical-section", + "portable-atomic", +] [[package]] name = "oorandom" @@ -3298,11 +2995,22 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "op-alloy" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "op-alloy-consensus", + "op-alloy-network", + "op-alloy-provider", + "op-alloy-rpc-types", + "op-alloy-rpc-types-engine", +] + [[package]] name = "op-alloy-consensus" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c88d2940558fd69f8f07b3cbd7bb3c02fc7d31159c1a7ba9deede50e7881024" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-consensus", "alloy-eips", @@ -3311,130 +3019,92 @@ dependencies = [ "alloy-rlp", "alloy-rpc-types-eth", "alloy-serde", + "bytes", "derive_more", + "reth-codecs", + "reth-zstd-compressors", "serde", + "serde_with", "thiserror", ] -[[package]] -name = "op-alloy-flz" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79f352fc3893dcd670172e615afef993a41798a1d3fc0db88a3e60ef2e70ecc" - [[package]] name = "op-alloy-network" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7071d7c3457d02aa0d35799cb8fbd93eabd51a21d100dcf411f4fcab6fdd2ea5" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-consensus", "alloy-network", - "alloy-primitives", "alloy-provider", "alloy-rpc-types-eth", - "alloy-signer", "op-alloy-consensus", "op-alloy-rpc-types", ] +[[package]] +name = "op-alloy-provider" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" +dependencies = [ + "alloy-network", + "alloy-primitives", + "alloy-provider", + "alloy-rpc-types-engine", + "alloy-transport", + "async-trait", + "op-alloy-rpc-types-engine", +] + [[package]] name = "op-alloy-rpc-types" -version = "0.18.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f22201e53e8cbb67a053e88b534b4e7f02265c5406994bf35978482a9ad0ae26" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-consensus", "alloy-eips", + "alloy-network", "alloy-network-primitives", "alloy-primitives", "alloy-rpc-types-eth", "alloy-serde", "derive_more", "op-alloy-consensus", + "reth-rpc-traits", "serde", "serde_json", "thiserror", ] [[package]] -name = "op-revm" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce1dc7533f4e5716c55cd3d62488c6200cb4dfda96e0c75a7e484652464343b" +name = "op-alloy-rpc-types-engine" +version = "2.0.0" +source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "auto_impl", - "once_cell", - "revm 27.1.0", + "alloy-consensus", + "alloy-eips", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-engine", + "alloy-serde", + "ethereum_ssz", + "ethereum_ssz_derive", + "op-alloy-consensus", "serde", + "sha2", + "snap", + "thiserror", ] [[package]] name = "op-revm" version = "20.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cfe618e3426e7a65b74f105aa706cfc92cd100ade8a6588a15c6ac3002e467" +source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.2#260f65329f1f47b7412a1b2c1fda85453f66521c" dependencies = [ "auto_impl", - "revm 38.0.0", + "revm", "serde", ] -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "openssl" -version = "0.10.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.104", -] - -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - -[[package]] -name = "openssl-sys" -version = "0.9.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "p256" version = "0.13.2" @@ -3444,128 +3114,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2 0.10.9", -] - -[[package]] -name = "p3-baby-bear" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7521838ecab2ddf4f7bc4ceebad06ec02414729598485c1ada516c39900820e8" -dependencies = [ - "num-bigint 0.4.6", - "p3-field", - "p3-mds", - "p3-poseidon2", - "p3-symmetric", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-dft" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46414daedd796f1eefcdc1811c0484e4bced5729486b6eaba9521c572c76761a" -dependencies = [ - "p3-field", - "p3-matrix", - "p3-maybe-rayon", - "p3-util", - "tracing", -] - -[[package]] -name = "p3-field" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48948a0516b349e9d1cdb95e7236a6ee010c44e68c5cc78b4b92bf1c4022a0d9" -dependencies = [ - "itertools 0.12.1", - "num-bigint 0.4.6", - "num-traits", - "p3-util", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-matrix" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4de3f373589477cb735ea58e125898ed20935e03664b4614c7fac258b3c42f" -dependencies = [ - "itertools 0.12.1", - "p3-field", - "p3-maybe-rayon", - "p3-util", - "rand 0.8.5", - "serde", - "tracing", -] - -[[package]] -name = "p3-maybe-rayon" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3968ad1160310296eb04f91a5f4edfa38fe1d6b2b8cd6b5c64e6f9b7370979e" - -[[package]] -name = "p3-mds" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2356b1ed0add6d5dfbf7a338ce534a6fde827374394a52cec16a0840af6e97c9" -dependencies = [ - "itertools 0.12.1", - "p3-dft", - "p3-field", - "p3-matrix", - "p3-symmetric", - "p3-util", - "rand 0.8.5", -] - -[[package]] -name = "p3-poseidon2" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da1eec7e1b6900581bedd95e76e1ef4975608dd55be9872c9d257a8a9651c3a" -dependencies = [ - "gcd", - "p3-field", - "p3-mds", - "p3-symmetric", - "rand 0.8.5", - "serde", -] - -[[package]] -name = "p3-symmetric" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edb439bea1d822623b41ff4b51e3309e80d13cadf8b86d16ffd5e6efb9fdc360" -dependencies = [ - "itertools 0.12.1", - "p3-field", - "serde", -] - -[[package]] -name = "p3-util" -version = "0.2.3-succinct" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c2c2010678b9332b563eaa38364915b585c1a94b5ca61e2c7541c087ddda5c" -dependencies = [ - "serde", -] - -[[package]] -name = "pairing" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" -dependencies = [ - "group", + "sha2", ] [[package]] @@ -3577,6 +3126,7 @@ dependencies = [ "arrayvec", "bitvec", "byte-slice-cast", + "bytes", "const_format", "impl-trait-for-tuples", "parity-scale-codec-derive", @@ -3642,36 +3192,24 @@ dependencies = [ "ucd-trie", ] -[[package]] -name = "phf" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" -dependencies = [ - "phf_macros 0.11.3", - "phf_shared 0.11.3", - "serde", -] - [[package]] name = "phf" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros 0.13.1", + "phf_macros", "phf_shared 0.13.1", "serde", ] [[package]] -name = "phf_generator" -version = "0.11.3" +name = "phf" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_shared 0.11.3", - "rand 0.8.5", + "phf_shared 0.14.0", ] [[package]] @@ -3684,26 +3222,13 @@ dependencies = [ "phf_shared 0.13.1", ] -[[package]] -name = "phf_macros" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" -dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", - "proc-macro2", - "quote", - "syn 2.0.104", -] - [[package]] name = "phf_macros" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator 0.13.1", + "phf_generator", "phf_shared 0.13.1", "proc-macro2", "quote", @@ -3712,36 +3237,36 @@ dependencies = [ [[package]] name = "phf_shared" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" dependencies = [ "siphasher", ] [[package]] name = "phf_shared" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" dependencies = [ "siphasher", ] [[package]] name = "pin-project" -version = "1.1.10" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.10" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2", "quote", @@ -3772,18 +3297,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" - -[[package]] -name = "plain_hasher" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e19e6491bdde87c2c43d70f4c194bc8a758f2eb732df00f61e43f7362e3b4cc" -dependencies = [ - "crunchy", -] +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plotters" @@ -3815,15 +3331,24 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.11.1" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "zerovec", ] @@ -3911,7 +3436,7 @@ checksum = "6fcdab19deb5195a31cf7726a210015ff1496ba1464fd42cb4f537b8b01b471f" dependencies = [ "bit-set", "bit-vec", - "bitflags", + "bitflags 2.11.1", "lazy_static", "num-traits", "rand 0.9.4", @@ -3931,9 +3456,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" -version = "1.0.40" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -3979,17 +3504,6 @@ dependencies = [ "serde", ] -[[package]] -name = "rand" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - [[package]] name = "rand_chacha" version = "0.3.1" @@ -4029,12 +3543,6 @@ dependencies = [ "serde", ] -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - [[package]] name = "rand_xorshift" version = "0.4.0" @@ -4059,18 +3567,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", -] - -[[package]] -name = "redox_users" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" -dependencies = [ - "getrandom 0.2.16", - "libredox", - "thiserror", + "bitflags 2.11.1", ] [[package]] @@ -4122,43 +3619,28 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" -[[package]] -name = "relative-path" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" - [[package]] name = "reqwest" -version = "0.12.24" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64", + "base64 0.23.1", "bytes", - "encoding_rs", "futures-core", - "h2", "http", "http-body", "http-body-util", "hyper", - "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", - "mime", - "native-tls", "percent-encoding", "pin-project-lite", - "rustls-pki-types", "serde", "serde_json", - "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", "tower", "tower-http", "tower-service", @@ -4169,270 +3651,210 @@ dependencies = [ ] [[package]] -name = "revm" -version = "27.1.0" +name = "reth-codecs" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6bf82101a1ad8a2b637363a37aef27f88b4efc8a6e24c72bf5f64923dc5532" +checksum = "f9c37bb4d1bac98661bf9128e1141b969034640d68697b22f70377e492fd332c" dependencies = [ - "revm-bytecode 6.2.1", - "revm-context 8.0.4", - "revm-context-interface 9.0.0", - "revm-database 7.0.4", - "revm-database-interface 7.0.4", - "revm-handler 8.1.0", - "revm-inspector 8.1.0", - "revm-interpreter 24.0.0", - "revm-precompile 25.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-trie", + "bytes", + "modular-bitfield", + "parity-scale-codec", + "reth-codecs-derive", + "reth-zstd-compressors", + "serde", ] [[package]] -name = "revm" -version = "38.0.0" +name = "reth-codecs-derive" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91202d39dbe8e8d10e9e8f2b76c30da68ecd1d25be69ba6d853ad0d03a3a398a" +checksum = "ceeb8dab90194305d3f7e3f043a22d2db1fb54b6dcf5d8e75c5a4fa8540e1f57" dependencies = [ - "revm-bytecode 10.0.0", - "revm-context 16.0.1", - "revm-context-interface 17.0.1", - "revm-database 13.0.1", - "revm-database-interface 11.0.1", - "revm-handler 18.1.0", - "revm-inspector 19.0.0", - "revm-interpreter 35.0.1", - "revm-precompile 34.0.0", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "proc-macro2", + "quote", + "syn 2.0.104", ] [[package]] -name = "revm-bytecode" -version = "6.2.1" +name = "reth-primitives-traits" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d800e6c2119457ded5b0af71634eb2468040bf97de468eee5a730272a106da0" +checksum = "9102518f0bbf99bc8f0e656a56fb2a7513248630275b608d3706076a82fde42b" dependencies = [ - "bitvec", - "phf 0.11.3", - "revm-primitives 20.2.1", + "alloy-consensus", + "alloy-eips", + "alloy-genesis", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-eth", + "alloy-trie", + "bytes", + "derive_more", + "once_cell", + "revm-bytecode", + "revm-primitives", + "revm-state", + "secp256k1 0.30.0", "serde", + "thiserror", ] [[package]] -name = "revm-bytecode" -version = "10.0.0" +name = "reth-rpc-traits" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdbb3a3d735efa94c91f2ef6bf20a35f99a77bc78f3e25bd758336901bdf9661" +checksum = "9fa03a2c9681c385ae1c72b169ac9c3525163b71db0b3362f16e8929e19e45fd" dependencies = [ - "bitvec", - "phf 0.13.1", - "revm-primitives 23.0.0", - "serde", + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-rpc-types-eth", + "alloy-signer", + "reth-primitives-traits", + "thiserror", ] [[package]] -name = "revm-context" -version = "8.0.4" +name = "reth-zstd-compressors" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd508416a35a4d8a9feaf5ccd06ac6d6661cd31ee2dc0252f9f7316455d71f9" +checksum = "dc0e86cf594718932d42cebce1fa48292fb7b92721f7c914631add1ca970e814" dependencies = [ - "cfg-if", - "derive-where", - "revm-bytecode 6.2.1", - "revm-context-interface 9.0.0", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", - "serde", + "zstd", ] [[package]] -name = "revm-context" -version = "16.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f68d928d8b228e0faeb1c6ed75c4fde7d124f1ddf9119b67e7a0ad4041237d" +name = "revm" +version = "40.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" +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 = "11.0.1" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "bitvec", - "cfg-if", - "derive-where", - "revm-bytecode 10.0.0", - "revm-context-interface 17.0.1", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "phf 0.13.1", + "revm-primitives", "serde", ] [[package]] -name = "revm-context-interface" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc90302642d21c8f93e0876e201f3c5f7913c4fcb66fb465b0fd7b707dfe1c79" +name = "revm-context" +version = "18.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "alloy-eip2930", - "alloy-eip7702", - "auto_impl", - "either", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "bitvec", + "cfg-if", + "derive-where", + "revm-bytecode", + "revm-context-interface", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", ] [[package]] name = "revm-context-interface" -version = "17.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3758e6167c4ba7a59a689c519a047edaefcd4c37d74f279b93ed87bc8aece4" +version = "19.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip2930", "alloy-eip7702", "auto_impl", "either", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-database" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40000c7d917c865f6c232a78581b78e70c43f52db17282bd1b52d4f0565bc8a2" -dependencies = [ - "alloy-eips", - "alloy-provider", - "alloy-transport", - "revm-bytecode 6.2.1", - "revm-database-interface 7.0.4", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", - "tokio", ] [[package]] name = "revm-database" -version = "13.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c281a1f11d3bcb8c0bba1199ed6bcb001d1aeb3d4fb366819e14f88723989a4e" +version = "15.0.2" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eips", - "revm-bytecode 10.0.0", - "revm-database-interface 11.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-database-interface" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4ccea7a168cba1196b1e57dd3e22c36047208c135f600f8e58cbe7d49957dba" -dependencies = [ - "auto_impl", - "either", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "derive_more", + "revm-bytecode", + "revm-database-interface", + "revm-primitives", + "revm-state", "serde", - "tokio", ] [[package]] name = "revm-database-interface" -version = "11.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89efb9832a4e3742bb4ded5f7fe5bf905e8860e69427d4dfec153484fc6d304" +version = "12.1.1" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-primitives", + "revm-state", "serde", "thiserror", ] [[package]] name = "revm-handler" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1529c8050e663be64010e80ec92bf480315d21b1f2dbf65540028653a621b27d" -dependencies = [ - "auto_impl", - "derive-where", - "revm-bytecode 6.2.1", - "revm-context 8.0.4", - "revm-context-interface 9.0.0", - "revm-database-interface 7.0.4", - "revm-interpreter 24.0.0", - "revm-precompile 25.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", - "serde", -] - -[[package]] -name = "revm-handler" -version = "18.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "783e903d6922b7f5f9a940d1bb229530502d2924b1aed9d5ca5a94ebf065d460" +version = "20.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "derive-where", - "revm-bytecode 10.0.0", - "revm-context 16.0.1", - "revm-context-interface 17.0.1", - "revm-database-interface 11.0.1", - "revm-interpreter 35.0.1", - "revm-precompile 34.0.0", - "revm-primitives 23.0.0", - "revm-state 11.0.1", - "serde", -] - -[[package]] -name = "revm-inspector" -version = "8.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78db140e332489094ef314eaeb0bd1849d6d01172c113ab0eb6ea8ab9372926" -dependencies = [ - "auto_impl", - "either", - "revm-context 8.0.4", - "revm-database-interface 7.0.4", - "revm-handler 8.1.0", - "revm-interpreter 24.0.0", - "revm-primitives 20.2.1", - "revm-state 7.0.4", + "revm-bytecode", + "revm-context", + "revm-context-interface", + "revm-database-interface", + "revm-interpreter", + "revm-precompile", + "revm-primitives", + "revm-state", "serde", - "serde_json", ] [[package]] name = "revm-inspector" -version = "19.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8216ad58422090d0daa9eb430e0a081f7ad07e7fd30681dee71f8420c99624e0" +version = "21.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "auto_impl", "either", - "revm-context 16.0.1", - "revm-database-interface 11.0.1", - "revm-handler 18.1.0", - "revm-interpreter 35.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-context", + "revm-database-interface", + "revm-handler", + "revm-interpreter", + "revm-primitives", + "revm-state", "serde", "serde_json", ] [[package]] name = "revm-inspectors" -version = "0.27.3" +version = "0.40.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2483827fec2c31db4ada14e0b5523c377d1084337d1dbe135faaf14c218ab1af" +checksum = "e93b96ddc470322a7294b8aecad862480625a9f1346d42fea51b1cce54afdb05" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -4440,7 +3862,7 @@ dependencies = [ "alloy-sol-types", "anstyle", "colorchoice", - "revm 27.1.0", + "revm", "serde", "serde_json", "thiserror", @@ -4448,34 +3870,20 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "24.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff9d7d9d71e8a33740b277b602165b6e3d25fff091ba3d7b5a8d373bf55f28a7" -dependencies = [ - "revm-bytecode 6.2.1", - "revm-context-interface 9.0.0", - "revm-primitives 20.2.1", - "serde", -] - -[[package]] -name = "revm-interpreter" -version = "35.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ece9f41b69658c15d748288a4dbdfc06a63f3ce93d983af440de3f1631dce6a" +version = "37.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ - "revm-bytecode 10.0.0", - "revm-context-interface 17.0.1", - "revm-primitives 23.0.0", - "revm-state 11.0.1", + "revm-bytecode", + "revm-context-interface", + "revm-primitives", + "revm-state", "serde", ] [[package]] name = "revm-precompile" -version = "25.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cee3f336b83621294b4cfe84d817e3eef6f3d0fce00951973364cc7f860424d" +version = "36.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -4488,87 +3896,34 @@ dependencies = [ "c-kzg", "cfg-if", "k256", - "kzg-rs", - "libsecp256k1", - "once_cell", - "p256", - "revm-primitives 20.2.1", - "ripemd", - "rug", - "secp256k1 0.31.1", - "sha2 0.10.9", -] - -[[package]] -name = "revm-precompile" -version = "34.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a346a8cc6c8c39bd65306641c692191299c0a7b63d38810e39e8fe9b92378660" -dependencies = [ - "ark-bls12-381", - "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", - "arrayref", - "aurora-engine-modexp", - "c-kzg", - "cfg-if", - "k256", "p256", - "revm-context-interface 17.0.1", - "revm-primitives 23.0.0", + "revm-context-interface", + "revm-primitives", "ripemd", "secp256k1 0.31.1", - "sha2 0.10.9", -] - -[[package]] -name = "revm-primitives" -version = "20.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa29d9da06fe03b249b6419b33968ecdf92ad6428e2f012dc57bcd619b5d94e" -dependencies = [ - "alloy-primitives", - "num_enum", - "once_cell", - "serde", + "sha2", ] [[package]] name = "revm-primitives" -version = "23.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c99bda77d9661521ba0b4bc04558c6692074f01e65dd420fa3b893033d9b8a2" +version = "24.0.1" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-primitives", - "num_enum", "once_cell", "serde", ] [[package]] name = "revm-state" -version = "7.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d7f39ea56df3bfbb3c81c99b1f028d26f205b6004156baffbf1a4f84b46cfa" -dependencies = [ - "bitflags", - "revm-bytecode 6.2.1", - "revm-primitives 20.2.1", - "serde", -] - -[[package]] -name = "revm-state" -version = "11.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c32490ed687dba31c3c882beb8c20408bdd30ef96690d8f145b0ee9a87040bfe" +version = "12.0.1" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.1#43485bf7de73b6ad92e9b5de4318eb96e2de2182" dependencies = [ "alloy-eip7928", - "bitflags", - "revm-bytecode 10.0.0", - "revm-primitives 23.0.0", + "bitflags 2.11.1", + "nonmax", + "revm-bytecode", + "revm-primitives", "serde", ] @@ -4582,20 +3937,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.16", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - [[package]] name = "ripemd" version = "0.1.3" @@ -4615,45 +3956,6 @@ dependencies = [ "rustc-hex", ] -[[package]] -name = "rstest" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" -dependencies = [ - "rstest_macros", - "rustc_version 0.4.1", -] - -[[package]] -name = "rstest_macros" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f168d99749d307be9de54d23fd226628d99768225ef08f6ffb52e0182a27746" -dependencies = [ - "cfg-if", - "glob", - "proc-macro2", - "quote", - "regex", - "relative-path", - "rustc_version 0.4.1", - "syn 2.0.104", - "unicode-ident", -] - -[[package]] -name = "rug" -version = "1.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4207e8d668e5b8eb574bda8322088ccd0d7782d3d03c7e8d562e82ed82bdcbc3" -dependencies = [ - "az", - "gmp-mpfr-sys", - "libc", - "libm", -] - [[package]] name = "ruint" version = "1.17.2" @@ -4667,7 +3969,7 @@ dependencies = [ "bytes", "fastrlp 0.3.1", "fastrlp 0.4.0", - "num-bigint 0.4.6", + "num-bigint", "num-integer", "num-traits", "parity-scale-codec", @@ -4724,46 +4026,13 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ - "bitflags", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys", "windows-sys 0.60.2", ] -[[package]] -name = "rustls" -version = "0.23.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" -dependencies = [ - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rustversion" version = "1.0.21" @@ -4782,12 +4051,6 @@ dependencies = [ "wait-timeout", ] -[[package]] -name = "ryu" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" - [[package]] name = "same-file" version = "1.0.6" @@ -4797,15 +4060,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "schannel" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "schemars" version = "0.9.0" @@ -4875,44 +4129,21 @@ dependencies = [ ] [[package]] -name = "secp256k1-sys" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" -dependencies = [ - "cc", -] - -[[package]] -name = "secp256k1-sys" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcb913707158fadaf0d8702c2db0e857de66eb003ccfdda5924b5f5ac98efb38" -dependencies = [ - "cc", -] - -[[package]] -name = "security-framework" -version = "2.11.1" +name = "secp256k1-sys" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", + "cc", ] [[package]] -name = "security-framework-sys" -version = "2.15.0" +name = "secp256k1-sys" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" +checksum = "dcb913707158fadaf0d8702c2db0e857de66eb003ccfdda5924b5f5ac98efb38" dependencies = [ - "core-foundation-sys", - "libc", + "cc", ] [[package]] @@ -4952,15 +4183,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde_arrays" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a16b99c5ea4fe3daccd14853ad260ec00ea043b2708d1fd1da3106dcd8d9df" -dependencies = [ - "serde", -] - [[package]] name = "serde_core" version = "1.0.228" @@ -4983,44 +4205,34 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.141" +version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ "indexmap 2.10.0", "itoa", "memchr", - "ryu", - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", "serde", + "serde_core", + "zmij", ] [[package]] name = "serde_with" -version = "3.14.1" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c522100790450cf78eeac1507263d0a350d4d5b30df0c8e1fe051a10c22b376e" +checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" dependencies = [ - "base64", + "base64 0.23.1", + "bs58", "chrono", "hex", "indexmap 1.9.3", "indexmap 2.10.0", + "jiff", "schemars 0.9.0", "schemars 1.0.4", - "serde", - "serde_derive", + "serde_core", "serde_json", "serde_with_macros", "time", @@ -5028,14 +4240,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.14.1" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327ada00f7d64abaac1e55a6911e90cf665aa051b9a561c7006c157f4633135e" +checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" dependencies = [ - "darling", + "darling 0.24.1", "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", ] [[package]] @@ -5048,19 +4260,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.9.0", - "opaque-debug", -] - [[package]] name = "sha2" version = "0.10.9" @@ -5092,15 +4291,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -5125,9 +4315,9 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" [[package]] name = "slab" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" @@ -5139,67 +4329,21 @@ dependencies = [ ] [[package]] -name = "socket2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" -dependencies = [ - "libc", - "windows-sys 0.60.2", -] - -[[package]] -name = "sp1-lib" -version = "5.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fbb6e3d8741c0fcdaa37e74d2dd9a2bdcbf958d192e438eec59e8071e08124c" -dependencies = [ - "bincode", - "serde", - "sp1-primitives", -] - -[[package]] -name = "sp1-primitives" -version = "5.0.8" +name = "snap" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4d2be9803acce74985f8861b6d5eb375ad1c5f176a68c2c735755937248f25e" -dependencies = [ - "bincode", - "blake3", - "cfg-if", - "hex", - "lazy_static", - "num-bigint 0.4.6", - "p3-baby-bear", - "p3-field", - "p3-poseidon2", - "p3-symmetric", - "serde", - "sha2 0.10.9", -] +checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" [[package]] -name = "sp1_bls12_381" -version = "0.8.0-sp1-5.0.0" +name = "socket2" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac255e1704ebcdeec5e02f6a0ebc4d2e9e6b802161938330b6810c13a610c583" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ - "cfg-if", - "ff", - "group", - "pairing", - "rand_core 0.6.4", - "sp1-lib", - "subtle", + "libc", + "windows-sys 0.61.2", ] -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - [[package]] name = "spki" version = "0.7.3" @@ -5216,16 +4360,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" -[[package]] -name = "state-test" -version = "1.7.1" -dependencies = [ - "clap", - "mega-evm", - "mega-state-test", - "serde_json", -] - [[package]] name = "static_assertions" version = "1.1.0" @@ -5297,11 +4431,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn-solidity" -version = "1.4.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff790eb176cc81bb8936aed0f7b9f14fc4670069a2d371b3e3b0ecce908b2cb3" +checksum = "ec005042c7d952febc1a3ef5b0f6674e9054aa836877a31c90b20e25b3d31744" dependencies = [ "paste", "proc-macro2", @@ -5320,34 +4465,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", -] - -[[package]] -name = "system-configuration" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" -dependencies = [ - "bitflags", - "core-foundation", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", + "syn 3.0.6", ] [[package]] @@ -5371,31 +4495,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.12" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.12" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", -] - -[[package]] -name = "thread_local" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" -dependencies = [ - "cfg-if", + "syn 3.0.6", ] [[package]] @@ -5438,20 +4553,11 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", "zerovec", @@ -5467,13 +4573,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" -version = "1.48.0" +version = "1.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" dependencies = [ - "bytes", "libc", "mio", "pin-project-lite", @@ -5484,40 +4595,20 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", -] - -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", + "syn 3.0.6", ] [[package]] name = "tokio-stream" -version = "0.1.17" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" dependencies = [ "futures-core", "pin-project-lite", @@ -5527,9 +4618,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.17" +version = "0.7.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" dependencies = [ "bytes", "futures-core", @@ -5552,14 +4643,14 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap 2.10.0", "toml_datetime", - "winnow", + "winnow 0.7.12", ] [[package]] name = "tower" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", @@ -5572,20 +4663,20 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.6" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.11.1", "bytes", "futures-util", "http", "http-body", - "iri-string", "pin-project-lite", "tower", "tower-layer", "tower-service", + "url", ] [[package]] @@ -5624,9 +4715,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.34" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", "valuable", @@ -5641,32 +4732,6 @@ dependencies = [ "tracing-core", ] -[[package]] -name = "tracing-subscriber" -version = "0.3.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex-automata", - "sharded-slab", - "thread_local", - "tracing", - "tracing-core", -] - -[[package]] -name = "triehash" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1631b201eb031b563d2e85ca18ec8092508e262a3196ce9bd10a67ec87b9f5c" -dependencies = [ - "hash-db", - "rlp", -] - [[package]] name = "try-lock" version = "0.2.5" @@ -5721,22 +4786,17 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - [[package]] name = "url" -version = "2.5.7" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -5745,24 +4805,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "version_check" version = "0.9.5" @@ -5907,16 +4955,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "winapi-util" version = "0.1.11" @@ -5973,17 +5011,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-registry" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" -dependencies = [ - "windows-link 0.1.3", - "windows-result", - "windows-strings", -] - [[package]] name = "windows-result" version = "0.3.4" @@ -6002,15 +5029,6 @@ dependencies = [ "windows-link 0.1.3", ] -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.59.0" @@ -6176,26 +5194,12 @@ dependencies = [ ] [[package]] -name = "wiremock" -version = "0.6.5" +name = "winnow" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" dependencies = [ - "assert-json-diff", - "base64", - "deadpool", - "futures", - "http", - "http-body-util", - "hyper", - "hyper-util", - "log", - "once_cell", - "regex", - "serde", - "serde_json", - "tokio", - "url", + "memchr", ] [[package]] @@ -6204,14 +5208,14 @@ version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "wyz" @@ -6224,9 +5228,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -6235,13 +5239,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", "synstructure", ] @@ -6267,22 +5271,22 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", "synstructure", ] @@ -6308,9 +5312,9 @@ dependencies = [ [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -6319,9 +5323,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ "yoke", "zerofrom", @@ -6330,11 +5334,45 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.104", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", ] diff --git a/Cargo.toml b/Cargo.toml index d76c60501..b4502668f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,23 +1,19 @@ [workspace] -members = [ - "bin/mega-evme", - "bin/mega-t8n", - "crates/mega-evm", - "crates/mega-state-test", - "crates/state-test", - "crates/system-contracts", -] -default-members = ["crates/mega-evm", "bin/mega-evme", "bin/mega-t8n"] +# The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, +# `crates/state-test`) still target the legacy engine; their sources are kept +# untouched and each rejoins the workspace when it is ported to Satin. +members = ["crates/mega-evm", "crates/system-contracts"] +default-members = ["crates/mega-evm"] exclude = [] # Explicitly set the resolver to version 2, which is the default for packages with edition >= 2021 # https://doc.rust-lang.org/edition-guide/rust-2021/default-cargo-resolver.html resolver = "2" [workspace.package] -version = "1.7.1" +version = "2.0.0-alpha.1" edition = "2021" -rust-version = "1.91" +rust-version = "1.94.1" license = "MIT OR Apache-2.0" homepage = "https://github.com/megaeth-labs/mega-evm" repository = "https://github.com/megaeth-labs/mega-evm" @@ -122,38 +118,42 @@ too_long_first_doc_paragraph = "allow" [workspace.dependencies] # megaeth -mega-evm = { path = "./crates/mega-evm", version = "1.7.1", default-features = false } -mega-state-test = { path = "./crates/mega-state-test", version = "1.7.1", default-features = false } -mega-system-contracts = { path = "./crates/system-contracts", version = "1.7.1", default-features = false } +mega-evm = { path = "./crates/mega-evm", version = "2.0.0-alpha.1", default-features = false } +mega-state-test = { path = "./crates/mega-state-test", version = "2.0.0-alpha.1", default-features = false } +mega-system-contracts = { path = "./crates/system-contracts", version = "2.0.0-alpha.1", default-features = false } # revm -op-revm = { version = "8.1.0", default-features = false } -revm = { version = "27.1.0", default-features = false } -revm-inspectors = { version = "0.27.3", default-features = false } +# revm stays pinned to the crates.io version the megaeth fork is based on; `[patch.crates-io]` +# below redirects all twelve revm crates to the fork. op-revm and the OP alloy crates have no +# crates.io release for revm 40: they come from the OP monorepo revision the node locks, and +# op-revm is redirected to the megaeth fork of it by the second patch block. +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +revm = { version = "=40.0.3", default-features = false } +revm-inspectors = { version = "0.40.1", default-features = false } # alloy -alloy-consensus = { version = "1.0.23", default-features = false } -alloy-eips = { version = "1.0.23", default-features = false } -alloy-evm = { version = "0.15.0", default-features = false } -alloy-hardforks = { version = "0.2.7", default-features = false } -alloy-json-rpc = { version = "1.0.41", default-features = false } -alloy-network = { version = "1.0.41", default-features = false } -alloy-op-evm = { version = "0.15.0", default-features = false } -alloy-op-hardforks = { version = "0.2.2", default-features = false } -alloy-primitives = { version = "1.3.0", default-features = false, features = ["map-foldhash"] } -alloy-provider = { version = "1.0.41", default-features = false } -alloy-rlp = { version = "0.3.12", default-features = false } -alloy-rpc-client = { version = "1.0.41", default-features = false } -alloy-rpc-types-eth = { version = "1.0.24", default-features = false, features = ["serde"] } -alloy-rpc-types-trace = { version = "1.0.22", default-features = false } -alloy-serde = { version = "1.0.23", default-features = false } -alloy-sol-types = { version = "1.0.23", default-features = false } -alloy-transport = { version = "1.0.41", default-features = false } -alloy-transport-http = { version = "1.0.41", default-features = false } -op-alloy-consensus = { version = "0.18.12", default-features = false, features = ["k256"] } +alloy-consensus = { version = "2.0.5", default-features = false } +alloy-eips = { version = "2.0.5", default-features = false } +alloy-evm = { version = "0.36.0", default-features = false } +alloy-hardforks = { version = "0.4.7", default-features = false } +alloy-json-rpc = { version = "2.1.1", default-features = false } +alloy-network = { version = "2.0.5", default-features = false } +alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +alloy-op-hardforks = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +alloy-primitives = { version = "1.6.0", default-features = false, features = ["map-foldhash"] } +alloy-provider = { version = "2.0.5", default-features = false } +alloy-rlp = { version = "0.3.16", default-features = false } +alloy-rpc-client = { version = "2.1.1", default-features = false } +alloy-rpc-types-eth = { version = "2.0.5", default-features = false, features = ["serde"] } +alloy-rpc-types-trace = { version = "2.0.5", default-features = false } +alloy-serde = { version = "2.1.1", default-features = false } +alloy-sol-types = { version = "1.6.0", default-features = false } +alloy-transport = { version = "2.1.1", default-features = false } +alloy-transport-http = { version = "2.1.1", default-features = false } +op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false, features = ["k256"] } op-alloy-flz = { version = "0.13.1", default-features = false } -op-alloy-network = { version = "0.18.12", default-features = false } -op-alloy-rpc-types = { version = "0.18.12", default-features = false } +op-alloy-network = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } +op-alloy-rpc-types = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } # misc auto_impl = { version = "1.3", default-features = false } @@ -224,3 +224,24 @@ strip = "none" inherits = "release" lto = "fat" codegen-units = 1 + +[patch.crates-io] +# megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). +# All twelve crates move together, otherwise the build resolves a second copy of revm. +revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.1" } + +[patch."https://github.com/ethereum-optimism/optimism"] +# megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built +# against the revm tag above. +op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.2" } diff --git a/REVIEW.md b/REVIEW.md index 259701ddf..d9f47b9ed 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,7 +24,7 @@ This is the single most important correctness concern in mega-evm. - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. - Pre-block helpers (system contract deploys, pre-exec system calls, etc.) must return `Option` for the block executor to commit — never call `db.commit(...)` directly. Even idempotent "no change" paths must return `Some(EvmState)` with a read-only account entry; silently returning `None` drops the account from the stateless witness read set and produces an incomplete proof. - See `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`. + On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the pre-block helpers arrive with the pre-block system calls and the system contract deployments. The same applies inside execution: read through the journal (`inspect_account`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state — and an early halt placed before the sandbox state merge drops that read set entirely. - Per-frame gas mechanisms (stipends, adjustments) must handle all frame termination paths: system contract interception, gas rescue on limit exceed, and frame return. Missing any path causes gas leakage. @@ -55,6 +55,7 @@ This is the single most important correctness concern in mega-evm. - If a change affects cross-component behavior that cannot be covered by unit tests, suggest e2e tests in the review comment (these may live in the `test-client` repo). - For stateful systems (resource-limit trackers, gas-stipend lifecycle), assert state-machine invariants after each transition, not just at the end. - Tests under `crates/mega-evm/tests/mutation/` are generated mutation-killing system tests, each keyed to a specific surviving mutant. + On the `satin` branch the directory does not exist yet: the legacy killers were keyed to mutants of the legacy sources and were retired, and the Satin sources leave no survivor; the first mechanism whose survivor needs a system-level killer creates it, with the conventions of `main`'s `crates/mega-evm/tests/mutation/main.rs`. Their comments — especially the `file:line:col` mutation-location references — must be kept up to date when the referenced source moves. Flag any PR that shifts lines in a mutated source file but leaves a now-stale location reference (or an orphaned/renamed test) in `tests/mutation/`; a reference that no longer points at its mutant defeats the purpose of the linkage. These tests should not be hand-edited otherwise — see `crates/mega-evm/tests/mutation/main.rs`. @@ -74,6 +75,63 @@ This is the single most important correctness concern in mega-evm. The fixture runners have failed this repeatedly: an exception assertion accepting any `Err`, a setup failure skipping execution, a `zip` letting missing output pass, a duplicate test name silently overwriting, an `unwrap_or(default)` rewriting a contradictory fixture into a valid one, a filename-based skip, an unconditional prune before state-root validation. Benchmarks fail it the same way — an unfunded inner call, zero-byte initcode, a discarded inner-call result or an undeployed address means the measured path never runs, and a mock database that cannot fail a lookup cannot test its error path. +## Test gates + +These checks guard every change to the Satin engine. +`lint`, `test`, `no-std` and `require-label` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. + +### Differential harness + +- The differential harness, which runs JSON scenarios through `MegaEvm` and through stock revm and compares them field by field, is maintained outside this repository. +- It is not a check on this repository's pull requests. +- The scenario format it reads (`test_utils::Scenario`) stays in `mega-evm`, where the `corpus` bench reads its own scenarios. + +### Execution-spec tests + +- No check in this repository runs execution-spec tests on `MegaEvm` itself until the state-test tool is ported to Satin. +- `.github/workflows/exec-spec.yml` runs the fork's own runner on the execution-spec-test fixtures, at the fork tag `Cargo.lock` pins, and checks the Osaka and Amsterdam executed and skipped counts pinned in the workflow. + It checks the fork `MegaEvm` runs on, not `MegaEvm`, and it is not a required check. +- It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. + +### Instruction counts (CodSpeed) + +- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (the JSON scenarios under `benches/scenarios` through `MegaEvm`, a bench input rather than a conformance suite) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. +- `codspeed.yml` runs them under instrumentation on every pull request that touches code and on every push to `satin`; the baseline a pull request is compared with is the latest `satin` push. +- Read regressions from the CodSpeed report on the pull request (the CodSpeed comment and the `CodSpeed Performance Analysis` check). + The regression threshold that fails that check is a setting of the repository's CodSpeed project; it is not recorded in this repository or in the reports CodSpeed posts, so this file does not state a number. + The check is not required: a flagged regression is fixed, or acknowledged in CodSpeed with the reason stated on the pull request. +- `corpus` moves when the semantics or the pricing of its scenarios move; a pricing change that moves it says so on the pull request. +- Locally, `cargo bench -p mega-evm --bench ` proves a bench runs to completion; its wall-clock numbers are not evidence. + +### Mutation testing + +- The `cargo-mutants gate` job mutates the lines a pull request changes and fails on a surviving mutant that no reviewed suppression covers. + Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. + That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --suppressions mutants/suppressions.toml`. + Take the numbers from that pair, not from `cargo mutants` on its own: the driver turns the function-scoped suppressions into `--exclude-re` before generation, and the gate filters the line-scoped ones after the run, so the bare command reports a different population and a different survivor count. +- The job is bounded to 330 minutes. + Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. + Run shard `k` of `n` with `MUTANTS_SHARD=k/n OUT_DIR=target/mutants-k scripts/mutation_test.sh diff ` and gate each shard with `scripts/mutation_gate.py report`; the pull request that first needs it adds a shard matrix to the job, and every shard must pass. +- The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) against `mega-evm`'s tests. + The production scope excludes test helpers as noise, so that code is otherwise never mutated, though the benches and later tests rest on it. + The two scopes are disjoint and the production one keeps its exclusions; a suppression may belong to either, and the suppression-hygiene job lists both scopes into its mutant universe. + The `cargo-mutants infrastructure` job runs the scope on a pull request that touches those files, either configuration, the driver or the gate, and nightly; it is bounded to 90 minutes and is not a required check. + Reference point: 39 mutants, 34 caught, 0 survived, 3 suppressed, 2 unviable, in 5m45s on a 15-core laptop with `JOBS=8`. + The three suppressed ones write a `BlockEnv` field that already holds that value by default, so no test can distinguish them; the test that pins those values kills them the moment a revm upgrade moves a default. +- The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. + It starts to bite with the first `is_enabled` gate of the spec after Satin. +- The legacy mutant killers were retired with the legacy sources; a survivor in Satin code gets a new killer, next to the code or under `crates/mega-evm/tests/mutation/`. + +### Scheduled workflows + +- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, weekly benchmark, replay-bench, doc-audit, the weekly execution-spec run) stay inert until `satin` is the default branch. +- Run them on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. + - `mutation.yml`: the whole-crate cargo-mutants run, the spec-gate sweep and suppression hygiene. + - `benchmark.yml`: the Satin bench set on `satin`'s head, without a baseline (`-f aa_check=true` measures the noise floor). + - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. + - `doc-audit.yml`: the documentation audit of `satin`'s docs. + - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the state-test tool is ported. + ## Dev tools and test infrastructure Applies to `bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, `crates/state-test`, test utilities and benches — not consensus code, but `mega-state-test` is a published library and tool output feeds fixtures and indexers. Default severity cap `[Minor]`; raise only when the defect reaches that published API or corrupts a downstream fixture. diff --git a/clippy.toml b/clippy.toml index bdc50bb3f..392025ce4 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,4 +1,4 @@ -msrv = "1.86" +msrv = "1.94.1" too-large-for-stack = 128 doc-valid-idents = [ "P2P", diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index dccf6eaf6..0989e6d51 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -15,32 +15,25 @@ workspace = true [dependencies] # alloy alloy-consensus = { workspace = true, features = ["k256"] } -alloy-eips.workspace = true alloy-evm.workspace = true alloy-hardforks.workspace = true alloy-op-evm.workspace = true -alloy-op-hardforks.workspace = true alloy-primitives.workspace = true alloy-sol-types.workspace = true op-alloy-consensus.workspace = true -op-alloy-flz.workspace = true -op-revm = { workspace = true, features = ["dev", "serde", "kzg-rs"] } +op-revm = { workspace = true, features = ["dev", "serde"] } # revm -revm = { workspace = true, features = ["dev", "serde", "kzg-rs"] } +revm = { workspace = true, features = ["dev", "serde"] } # megaeth mega-system-contracts = { workspace = true, default-features = false } # misc auto_impl.workspace = true -bitflags.workspace = true delegate.workspace = true -derive_more.workspace = true -once_cell.workspace = true +derive_more = { workspace = true, optional = true, features = ["debug", "deref", "deref_mut", "display", "error"] } serde = { workspace = true, features = ["derive"] } -thiserror.workspace = true -tracing.workspace = true [dev-dependencies] # CodSpeed drop-in: `codspeed-criterion-compat` re-exports criterion's API, so @@ -48,47 +41,31 @@ tracing.workspace = true # it behaves exactly like criterion; under `cargo codspeed` it runs each bench # once under valgrind and reports layout-insensitive instruction counts. criterion = { package = "codspeed-criterion-compat", version = "5.0.1", default-features = false, features = ["cargo_bench_support", "html_reports", "plotters"] } -hex.workspace = true mega-evm = { path = ".", features = ["test-utils"] } -op-revm-latest = { package = "op-revm", version = "20.0.0", default-features = false, features = ["dev", "serde", "std"] } -rand = { workspace = true, features = ["thread_rng"] } revm-inspectors = { workspace = true, features = ["std"] } -# Pin to the revm version `op-revm-latest` depends on so both `_latest` baselines share one revm tree. -revm-latest = { package = "revm", version = "38.0.0", default-features = false, features = ["dev", "serde", "std"] } -serde_json.workspace = true -sha2.workspace = true +serde_json = { workspace = true, features = ["std"] } [features] default = ["std", "revm/default", "op-revm/default"] -std = ["revm/std", "op-revm/std", "revm/alloydb", "mega-system-contracts/std"] -test-utils = [] +std = [ + "alloy-evm/std", + "alloy-op-evm/std", + "mega-system-contracts/std", + "op-revm/std", + "revm/std", +] +test-utils = ["dep:derive_more"] +# The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (the JSON scenarios under +# benches/scenarios, a bench input) and `factory` (EVM construction). The inputs under +# benches/data (revm_bench) and benches/fixtures (attack_replay) stay for the rebuild of the rest +# of the suite. [[bench]] -name = "attack_replay" +name = "corpus" harness = false [[bench]] -name = "block_bench" -harness = false - -[[bench]] -name = "comp_cost" -harness = false - -[[bench]] -name = "ctt" -harness = false - -[[bench]] -name = "enriched_tx" -harness = false - -[[bench]] -name = "mega_bench" -harness = false - -[[bench]] -name = "revm_bench" +name = "factory" harness = false [[bench]] diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index aaefbe1e4..9c14e8727 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -1,123 +1,67 @@ # mega-evm -A specialized Ethereum Virtual Machine (EVM) implementation tailored for MegaETH, built on top of [revm](https://github.com/bluealloy/revm) and [op-revm](https://github.com/bluealloy/op-revm). +The EVM of MegaETH, built on [revm](https://github.com/bluealloy/revm) and [op-revm](https://github.com/ethereum-optimism/optimism/tree/develop/rust/op-revm). -## EVM Version +This is the 2.x line: the **Satin** engine. +The legacy engine (specs `Equivalence` through `Rex7`) is the 1.x line. -- **Base EVM**: [revm v27.1.0 (v83)](https://github.com/bluealloy/revm) -- **Optimism EVM**: [op-revm v8.1.0 (v83)](https://github.com/bluealloy/op-revm) -- **Alloy EVM**: [alloy-evm v0.15.0](https://github.com/alloy-rs/alloy-evm) +## Base -## Terminology: Spec vs Hardfork +- **revm**: 40.0.3, from the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) (the revm 43 gas core with EIP-8037 and EIP-2780, plus MegaETH hooks) +- **op-revm**: 20.0.0, from the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) +- **alloy-evm**: 0.36; **alloy-op-evm**: 0.32 -This codebase distinguishes between two related concepts: +A consumer redirects all twelve revm crates and `op-revm` to the forks with `[patch]` entries; see this repository's root `Cargo.toml`. -- **Spec (`MegaSpecId`)**: Defines EVM behavior - what the EVM does. Values: `EQUIVALENCE`, `MINI_REX`, `MINI_REX_1`, `MINI_REX_2`, `REX`, `REX1`, `REX2`, `REX3`, `REX4`, `REX5`, `REX6`, `REX7` -- **Hardfork (`MegaHardfork`)**: Defines network upgrade events - when specs are activated. Values: `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` +## Spec and hardfork -The mapping between hardforks and specs is one-to-one: every hardfork schedules a spec rung of its own. -Rollbacks are expressed by alias specs whose behavior projects to an earlier spec: `MiniRex1` schedules `MINI_REX_1` (behavior: `EQUIVALENCE`) and `MiniRex2` schedules `MINI_REX_2` (behavior: `MINI_REX`). +- **Spec (`MegaSpecId`)** defines EVM behavior. + Satin has a single spec, `SATIN`, running on Optimism Karst (Ethereum Osaka). +- **Hardfork (`MegaHardfork`)** defines when a spec activates. + The single fork `Satin` activates `SATIN`; its timestamps are not scheduled yet. -## Key Features +The legacy spec names do not parse: `"Rex6".parse::()` fails with `ParseMegaSpecError::Legacy`. -### EQUIVALENCE Spec +## Status -- **Optimism Compatibility**: Maintains full compatibility with Optimism Isthmus EVM -- **Parallel Execution Support**: Block environment access tracking for conflict detection +Satin is under construction. +Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +It still uses the Osaka gas table, which prices state gas at zero, so no transaction draws state gas yet. -### MINI_REX Spec +The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the abort protocol that stops a transaction crossing a limit with a revert, and the inspector admission gate. +No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. +`MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. -- **Multidimensional Gas Model**: Independent tracking for compute gas (1B), data size (3.125 MB), and KV updates (125K) -- **Compute Gas Tracking**: Separate limit for computational work with gas detention for volatile data access -- **Dynamic Gas Costs**: SALT bucket-based scaling preventing state bloat -- **Split LOG Costs**: Compute gas (standard) + storage gas (10x multiplier) for independent resource pricing -- **SELFDESTRUCT Prohibition**: Complete disabling for contract integrity -- **Large Contract Support**: 512 KB contracts (21x increase from 24 KB) -- **Gas Detention**: Volatile data access (block env, beneficiary, oracle) triggers gas limiting with refunds -- **Enhanced Security**: Comprehensive limit enforcement preserving remaining gas on limit violations +SALT pricing, history gas, the resource limits, gas detention, the system contracts and keyless deployment arrive in later changes. -For complete MiniRex specification, see the [MiniRex upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/minirex.html). +## Quick start -### REX Spec +```rust,ignore +use alloy_evm::Evm as _; +use mega_evm::{alloy_op_evm::OpTx, MegaContext, MegaEvm, MegaSpecId}; +use revm::{context::TxEnv, database::{CacheDB, EmptyDB}, primitives::TxKind}; -- **Refined Storage Gas Economics**: Optimized storage gas formulas with gradual scaling (20K-32K base costs vs. MiniRex's 2M) -- **Transaction Intrinsic Storage Gas**: 39,000 storage gas baseline for all transactions (total 60K with compute gas) -- **Zero Cost Fresh Storage**: Storage operations in minimum-sized SALT buckets charge 0 storage gas -- **Separate Contract Creation Cost**: Distinct storage gas for contract creation (32K base) vs. account creation (25K base) -- **Critical Security Fixes**: DELEGATECALL, STATICCALL, and CALLCODE now properly enforce 98/100 gas forwarding and oracle access detection -- **MiniRex Foundation**: Inherits all MiniRex features including multidimensional gas model, compute gas detention, and enhanced security +let context = MegaContext::new(CacheDB::::default(), MegaSpecId::SATIN); +let mut evm = MegaEvm::new(context); -For complete Rex specification, see the [Rex upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex.html). - -### REX1 Spec - -- **Limit Reset Fix**: Resets compute gas limits at the start of each transaction -- **No Other Behavioral Changes**: Inherits Rex semantics fully - -For complete Rex1 specification, see the [Rex1 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex1.html). - -### REX2 Spec - -- **SELFDESTRUCT Restored**: Re-enabled with EIP-6780 semantics -- **KeylessDeploy System Contract**: Enables keyless deployment (Nick's Method) with custom gas limits -- **Rex1 Baseline**: Inherits Rex1 behavior for all other features - -For complete Rex2 specification, see the [Rex2 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex2.html). - -### REX3 Spec - -- **Increased Oracle Access Gas Limit**: Oracle access compute gas limit raised from 1M to 20M, allowing more post-oracle computation -- **SLOAD-based Oracle Detention**: Oracle gas detention triggers on SLOAD from oracle storage instead of CALL to oracle contract -- **Keyless Deploy Compute Gas Tracking**: Records the 100K keyless deploy overhead as compute gas -- **Rex2 Baseline**: Inherits all Rex2 behavior - -For complete Rex3 specification, see the [Rex3 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex3.html). - -### REX4 Spec - -- **Per-Call-Frame Resource Budgets**: All four resource dimensions (compute gas, data size, KV updates, state growth) are bounded per call frame with 98/100 forwarding -- **Relative Gas Detention**: Effective detained limit is `current_usage + cap` instead of an absolute cap -- **Storage Gas Stipend**: Value-transferring CALL/CALLCODE receives an additional 23,000 gas for storage gas operations -- **MegaAccessControl System Contract**: Allows contracts to proactively disable volatile data access for a call subtree -- **MegaLimitControl System Contract**: Allows querying effective remaining compute gas under detention and call frame limits -- **Rex3 Baseline**: Inherits all Rex3 behavior - -For complete Rex4 specification, see the [Rex4 upgrade page](https://megaeth-labs.github.io/mega-evm/upgrades/rex4.html). - -## Quick Start - -```rust -use mega_evm::{Context, Evm, SpecId, Transaction}; -use revm::{ - context::TxEnv, - database::{CacheDB, EmptyDB}, - inspector::NoOpInspector, - primitives::TxKind, -}; +let tx = OpTx(op_revm::OpTransaction { + base: TxEnv { caller, kind: TxKind::Call(target), gas_limit: 1_000_000, ..Default::default() }, + enveloped_tx: Some(Default::default()), + ..Default::default() +}); +let result = evm.transact_raw(tx)?; +``` -// Create EVM instance with MINI_REX spec -let mut db = CacheDB::::default(); -let spec = SpecId::MINI_REX; -let mut context = Context::new(db, spec); -let mut evm = Evm::new(context, NoOpInspector); +A block executor admits an inspected transaction only from an EVM whose inspector is declared read-only: -// Execute transaction -let tx = Transaction { - base: TxEnv { - caller: address!("..."), - kind: TxKind::Call(target_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - ..Default::default() - }, - ..Default::default() -}; +```rust,ignore +use mega_evm::DeclaredObserver; -let result = alloy_evm::Evm::transact_raw(&mut evm, tx)?; +let evm = MegaEvm::new(context).with_trusted_inspector(DeclaredObserver(tracer)); +assert!(!evm.has_rewriting_inspector()); ``` ## Documentation -- [Full specification](https://megaeth-labs.github.io/mega-evm/) +- [Specification](https://megaeth-labs.github.io/mega-evm/) (describes the legacy engine until the Satin pages land) - [Architecture](../../ARCH.md) diff --git a/crates/mega-evm/benches/attack_replay.rs b/crates/mega-evm/benches/attack_replay.rs deleted file mode 100644 index 60a7d4cdc..000000000 --- a/crates/mega-evm/benches/attack_replay.rs +++ /dev/null @@ -1,436 +0,0 @@ -//! Benchmark replay of a real mainnet attack contract deployment. -//! -//! Loads a saved prestate snapshot (captured via `debug_traceCall` + -//! `prestateTracer` on `MegaETH` mainnet at a fixed block) and replays the -//! deploy through `MegaEvm` for both supported specs, alongside a vanilla -//! revm baseline executing the same CREATE on the same in-memory state. -//! -//! ## Motivation -//! -//! Production sequencer-monitor measurements on this exact transaction: -//! -//! | path | wall time | -//! |-------------------------------------|-----------| -//! | `mega-evm` + Tracer + `RocksDB` state | ~33 ms | -//! | vanilla revm + `RocksDB` state | ~1.4 ms | -//! -//! The bench reproduces the same ratio in a hermetic, `RocksDB`-free -//! environment: -//! -//! | arm | wall time | -//! |--------------------------------------|-----------| -//! | `mega-evm` `EQUIVALENCE` spec | ~1.15 ms | -//! | `mega-evm` `MINI_REX` spec | ~35.9 ms | -//! | vanilla revm | ~1.10 ms | -//! -//! Both specs execute the same 205,951 opcodes and deploy the same 582-byte -//! runtime; the 30× gap between `EQUIVALENCE` and `MINI_REX` comes entirely -//! from the multi-dimensional `AdditionalLimit` accounting (quadratic LOG / -//! compute / storage / data / KV buckets) that `MINI_REX` enables. -//! -//! Pairing the `mega-evm` and `pure_revm` arms gives a hermetic regression -//! target for any limit-tracker / hot-path optimization (e.g. caching -//! `net_usage` in `FrameLimitTracker`). -//! -//! ## Run -//! -//! ```bash -//! cargo bench --bench attack_replay -//! ``` - -#![allow(missing_docs)] - -use std::{ - collections::HashMap, - str::FromStr, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, - }, -}; - -use alloy_primitives::{hex, Address, Bytes, B256, U256}; -use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; -use mega_evm::{ - test_utils::MemoryDatabase, EmptyExternalEnv, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, -}; -use revm::{ - context::{ - result::{ExecResultAndState, ExecutionResult, Output}, - tx::TxEnvBuilder, - TxEnv, - }, - interpreter::{interpreter::EthInterpreter, Interpreter}, - primitives::TxKind, - Context, ExecuteEvm, InspectEvm, Inspector, MainBuilder, MainContext, -}; -use serde_json::Value; - -/// Captured fixture; see `fixtures/known_attack_deploy.json` for provenance. -const FIXTURE_JSON: &str = include_str!("fixtures/known_attack_deploy.json"); - -/// Parsed transaction fields. Kept simple — manual extraction so the fixture -/// can stay free-form JSON without requiring serde feature flags on alloy. -struct TxFixture { - caller: Address, - nonce: u64, - gas_limit: u64, - max_fee_per_gas: u128, - max_priority_fee_per_gas: u128, - value: U256, - chain_id: u64, - input: Bytes, -} - -/// Per-account snapshot entry from `prestateTracer`. -struct AccountFixture { - balance: U256, - nonce: u64, - code: Bytes, - storage: Vec<(B256, U256)>, -} - -/// Block environment captured at the same block as `prestate`. -struct BlockFixture { - number: u64, - timestamp: u64, - base_fee_per_gas: u64, - gas_limit: u64, - beneficiary: Address, - mix_hash: B256, -} - -fn parse_u256(v: &Value) -> U256 { - let s = v.as_str().unwrap(); - if let Some(stripped) = s.strip_prefix("0x") { - U256::from_str_radix(stripped, 16).unwrap() - } else { - U256::from_str_radix(s, 10).unwrap() - } -} - -fn parse_bytes(v: &Value) -> Bytes { - let s = v.as_str().unwrap(); - Bytes::from(hex::decode(s.trim_start_matches("0x")).unwrap()) -} - -fn parse_address(v: &Value) -> Address { - let s = v.as_str().unwrap(); - Address::from_str(s).unwrap() -} - -fn load_fixture() -> (TxFixture, HashMap, BlockFixture) { - let json: Value = serde_json::from_str(FIXTURE_JSON).expect("fixture json parses"); - - let tx_obj = &json["tx"]; - let tx = TxFixture { - caller: parse_address(&tx_obj["caller"]), - nonce: tx_obj["nonce"].as_u64().unwrap(), - gas_limit: tx_obj["gas_limit"].as_u64().unwrap(), - max_fee_per_gas: tx_obj["max_fee_per_gas"].as_u64().unwrap() as u128, - max_priority_fee_per_gas: tx_obj["max_priority_fee_per_gas"].as_u64().unwrap() as u128, - value: parse_u256(&tx_obj["value"]), - chain_id: tx_obj["chain_id"].as_u64().unwrap(), - input: parse_bytes(&tx_obj["input"]), - }; - - let mut prestate = HashMap::new(); - for (addr_str, acc) in json["prestate"].as_object().unwrap() { - let addr = Address::from_str(addr_str).unwrap(); - let balance = acc.get("balance").map(parse_u256).unwrap_or_default(); - let nonce = acc.get("nonce").and_then(|v| v.as_u64()).unwrap_or(0); - let code = acc.get("code").map(parse_bytes).unwrap_or_default(); - let storage: Vec<(B256, U256)> = acc - .get("storage") - .and_then(|s| s.as_object()) - .map(|m| m.iter().map(|(k, v)| (B256::from_str(k).unwrap(), parse_u256(v))).collect()) - .unwrap_or_default(); - prestate.insert(addr, AccountFixture { balance, nonce, code, storage }); - } - - let blk = &json["block"]; - let block = BlockFixture { - number: blk["number"].as_u64().unwrap(), - timestamp: blk["timestamp"].as_u64().unwrap(), - base_fee_per_gas: blk["base_fee_per_gas"].as_u64().unwrap(), - gas_limit: blk["gas_limit"].as_u64().unwrap(), - beneficiary: parse_address(&blk["beneficiary"]), - mix_hash: B256::from_str(blk["mix_hash"].as_str().unwrap()).unwrap(), - }; - - (tx, prestate, block) -} - -/// Build a fresh `MemoryDatabase` populated with the captured prestate. -/// Called inside the per-iteration setup so each measurement starts from -/// the same on-chain state. -fn build_db(prestate: &HashMap) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - for (addr, acc) in prestate { - db.set_account_balance(*addr, acc.balance); - if acc.nonce > 0 { - db.set_account_nonce(*addr, acc.nonce); - } - if !acc.code.is_empty() { - db.set_account_code(*addr, acc.code.clone()); - } - for (slot, value) in &acc.storage { - db.set_account_storage(*addr, (*slot).into(), *value); - } - } - db -} - -/// Build a `MegaContext` from the captured fixture for the given spec. -/// -/// **`chain_id` matters**: leaving the default (1) silently sends `mega-evm` -/// down a short-circuit path that skips most of the limit-tracker work, -/// producing artificially-fast bench numbers (~80 µs vs ~36 ms). The -/// fixture's `chain_id` (4326 = `MegaETH` mainnet) must be threaded through. -fn build_mega_context( - spec: MegaSpecId, - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) -> MegaContext { - let db = build_db(prestate); - let mut ctx = MegaContext::new(db, spec); - ctx.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - // MegaContext derefs to OpContext — cfg lives on the inner context. - ctx.cfg.chain_id = tx_fixture.chain_id; - ctx.modify_block(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }); - ctx -} - -/// Build the `MegaTransaction` for the captured deploy. -fn build_mega_tx(tx: &TxFixture) -> MegaTransaction { - let inner = TxEnvBuilder::new() - .caller(tx.caller) - .create() - .data(tx.input.clone()) - .gas_limit(tx.gas_limit) - .gas_price(tx.max_fee_per_gas) - .gas_priority_fee(Some(tx.max_priority_fee_per_gas)) - .nonce(tx.nonce) - .value(tx.value) - .chain_id(Some(tx.chain_id)) - .build_fill(); - let mut mega_tx = MegaTransaction::new(inner); - // The handler expects `enveloped_tx` to be set for EIP-2718 typed txns, - // but the value isn't consumed by the limit-check / EVM path. Use empty. - mega_tx.enveloped_tx = Some(Bytes::new()); - mega_tx -} - -/// Build a vanilla revm `TxEnv` mirroring the captured fixture. -fn build_revm_tx(tx_fixture: &TxFixture) -> TxEnv { - TxEnv { - caller: tx_fixture.caller, - gas_limit: tx_fixture.gas_limit, - gas_price: tx_fixture.max_fee_per_gas, - gas_priority_fee: Some(tx_fixture.max_priority_fee_per_gas), - kind: TxKind::Create, - value: tx_fixture.value, - data: tx_fixture.input.clone(), - nonce: tx_fixture.nonce, - chain_id: Some(tx_fixture.chain_id), - ..Default::default() - } -} - -/// Minimal `Inspector` that just counts how many opcodes the interpreter -/// executed. Used as a sanity check that the bench is not silently -/// short-circuiting. The count is exposed via a shared atomic so it can be -/// read back after the EVM consumes the inspector by value. -#[derive(Clone, Default)] -struct OpcodeCounter { - steps: Arc, -} - -impl Inspector for OpcodeCounter { - fn step(&mut self, _interp: &mut Interpreter, _ctx: &mut CTX) { - self.steps.fetch_add(1, Ordering::Relaxed); - } -} - -/// Minimum opcode count we expect the deploy to execute. If the bench -/// silently short-circuits (e.g. wrong `chain_id` in setup, validation -/// reject wrapped as `Ok`), step count drops to single digits — assert -/// catches that before users mistake an early-exit for a "fast" bench. -const MIN_EXPECTED_OPCODE_STEPS: u64 = 100_000; - -fn sanity_check_mega( - name: &str, - spec: MegaSpecId, - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) { - // First run: confirm Success variant + inspect deployed output / state. - let ctx = build_mega_context(spec, prestate, block, tx_fixture); - let mut evm = MegaEvm::new(ctx); - let ExecResultAndState { result, state } = - evm.transact(build_mega_tx(tx_fixture)).expect("mega evm.transact ok"); - - let variant = match &result { - ExecutionResult::Success { reason, output, .. } => match output { - Output::Create(code, addr) => format!( - "Success(Create, reason={reason:?}, deployed_code_len={}, addr={:?})", - code.len(), - addr, - ), - Output::Call(data) => { - format!("Success(Call, reason={reason:?}, output_len={})", data.len()) - } - }, - ExecutionResult::Revert { output, .. } => format!("Revert(output_len={})", output.len()), - ExecutionResult::Halt { reason, .. } => format!("Halt({reason:?})"), - }; - let slot_count: usize = state.values().map(|a| a.storage.len()).sum(); - eprintln!( - "sanity[{name}]: gas_used={} variant={} accounts={} storage_slots={}", - result.gas_used(), - variant, - state.len(), - slot_count, - ); - assert!( - result.is_success(), - "deploy did not succeed on {name} — prestate / block env / spec config incomplete: {variant}", - ); - - // Second run: count opcode steps actually executed. Without this, a - // short-circuit (e.g. tx rejected in validation but wrapped as Ok) - // would look like a fast benchmark instead of failing loudly. - let ctx = build_mega_context(spec, prestate, block, tx_fixture); - let counter = OpcodeCounter::default(); - let counter_handle = counter.clone(); - let mut evm = MegaEvm::new(ctx).with_inspector(counter); - let _ = evm.inspect_one_tx(build_mega_tx(tx_fixture)).expect("inspect_one_tx ok"); - let steps = counter_handle.steps.load(Ordering::Relaxed); - eprintln!("sanity[{name}]: opcode_steps={}", steps); - assert!( - steps >= MIN_EXPECTED_OPCODE_STEPS, - "bench appears to short-circuit on {name}: only {steps} opcode steps \ - executed (expected ≥ {MIN_EXPECTED_OPCODE_STEPS}). Check that \ - chain_id and block env are wired correctly.", - ); -} - -fn sanity_check_pure_revm( - prestate: &HashMap, - block: &BlockFixture, - tx_fixture: &TxFixture, -) { - let mut evm = Context::mainnet() - .modify_cfg_chained(|cfg| { - cfg.chain_id = tx_fixture.chain_id; - cfg.disable_balance_check = true; - cfg.disable_base_fee = true; - }) - .modify_block_chained(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }) - .with_db(build_db(prestate)) - .build_mainnet(); - let res = evm.transact_one(build_revm_tx(tx_fixture)).expect("revm transact_one ok"); - let variant = match &res { - ExecutionResult::Success { output: Output::Create(code, _), .. } => { - format!("Success(Create, deployed_code_len={})", code.len()) - } - ExecutionResult::Success { .. } => "Success(non-Create)".to_string(), - ExecutionResult::Revert { output, .. } => format!("Revert(output_len={})", output.len()), - ExecutionResult::Halt { reason, .. } => format!("Halt({reason:?})"), - }; - eprintln!("sanity[pure_revm]: gas_used={} variant={}", res.gas_used(), variant); - assert!( - variant.starts_with("Success(Create"), - "pure revm did not deploy successfully: {variant}", - ); -} - -fn bench_attack_replay(c: &mut Criterion) { - let (tx_fixture, prestate, block) = load_fixture(); - - // Run all sanity checks first so failures abort before criterion warms up. - for (name, spec) in - [("equivalence", MegaSpecId::EQUIVALENCE), ("mini_rex", MegaSpecId::MINI_REX)] - { - sanity_check_mega(name, spec, &prestate, &block, &tx_fixture); - } - sanity_check_pure_revm(&prestate, &block, &tx_fixture); - - let mut group = c.benchmark_group("attack_replay"); - - for (name, spec) in - [("equivalence", MegaSpecId::EQUIVALENCE), ("mini_rex", MegaSpecId::MINI_REX)] - { - group.bench_function(name, |b| { - b.iter_batched( - || { - let ctx = build_mega_context(spec, &prestate, &block, &tx_fixture); - (MegaEvm::new(ctx), build_mega_tx(&tx_fixture)) - }, - |(mut evm, mega_tx)| black_box(evm.transact(black_box(mega_tx))), - BatchSize::SmallInput, - ) - }); - } - - // Apples-to-apples comparison arm: vanilla revm running the same CREATE - // on the same in-memory state. With the bench setup correct, this comes - // back at ~1.1 ms — very close to the `equivalence` arm — which is what - // we expect: same opcodes, similar interpreter overhead. The interesting - // delta is `mini_rex` vs both at ~36 ms, isolating the cost of the - // multi-dimensional `AdditionalLimit` accounting. - // - // Note: vanilla revm doesn't enforce OP-stack rules (L1 data fee, etc.) - // and uses its own SpecId set, but for a self-contained CREATE that - // doesn't touch L1Block / OP-specific precompiles, the opcode-level - // work is the same. - group.bench_function("pure_revm", |b| { - b.iter_batched( - || { - let evm = Context::mainnet() - .modify_cfg_chained(|cfg| { - cfg.chain_id = tx_fixture.chain_id; - cfg.disable_balance_check = true; - cfg.disable_base_fee = true; - }) - .modify_block_chained(|b| { - b.number = U256::from(block.number); - b.timestamp = U256::from(block.timestamp); - b.basefee = block.base_fee_per_gas; - b.gas_limit = block.gas_limit; - b.beneficiary = block.beneficiary; - b.prevrandao = Some(block.mix_hash); - }) - .with_db(build_db(&prestate)) - .build_mainnet(); - (evm, build_revm_tx(&tx_fixture)) - }, - |(mut evm, tx)| black_box(evm.transact_one(black_box(tx))), - BatchSize::SmallInput, - ) - }); - - group.finish(); -} - -criterion_group!(benches, bench_attack_replay); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/block_bench.rs b/crates/mega-evm/benches/block_bench.rs deleted file mode 100644 index d2b019743..000000000 --- a/crates/mega-evm/benches/block_bench.rs +++ /dev/null @@ -1,484 +0,0 @@ -//! Benchmarks for the block executor pipeline. -//! -//! Measures the full production path: `pre_execution_changes` (system contract -//! deployment), transaction execution, and `post_execution_changes`. - -#![allow(missing_docs)] - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, SequencerRegistryConfig, TestExternalEnvs, ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, - ORACLE_CONTRACT_CODE_REX5, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, -}; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, - INITIAL_SYSTEM_ADDRESS, -}; -use revm::{ - bytecode::opcode::{ADD, LOG1, POP, SSTORE}, - context::BlockEnv, - database::State, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); - -/// Create a recovered legacy transaction for block execution. -fn create_call_tx( - nonce: u64, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Create a contract deployment transaction. -fn create_deploy_tx( - nonce: u64, - gas_limit: u64, - init_code: Bytes, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Hardfork schedule coherent with `spec`: everything through the spec's rung is active from -/// genesis, with the params Rex5+ pre-block setup needs. Each benchmark row therefore measures -/// one complete per-spec world — pre-block setup included — matching the executor's rule that -/// setup follows the executing spec. (A REX6+ row would additionally need -/// `SequencerRegistryRex6Config` attached here.) -fn hardforks_for(spec: MegaSpecId) -> MegaHardforkConfig { - let mut config = MegaHardforkConfig::default().with_all_activated_through(spec); - if spec.reaches(MegaSpecId::REX5) { - config = config.with_params(SequencerRegistryConfig { - rex5_initial_sequencer: MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: MEGA_SYSTEM_ADDRESS, - }); - } - config -} - -/// Create block EVM environment. -fn block_evm_env(spec: MegaSpecId) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn rex5_steady_state_db(contract_code: &Bytes) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Predeploy all REX5 system contracts so this benchmark measures the steady-state - // pre-block path instead of repeatedly paying first-deploy cost. - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX5); - db.set_account_code( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - ); - db.set_account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); - db.set_account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); - db.set_account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE); - - // Seed the bootstrap SequencerRegistry slots exactly once so deploy stays idempotent - // and resolve_system_address reads committed steady-state data. - let initial_address = U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, ADMIN, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SYSTEM_ADDRESS, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_SEQUENCER, initial_address); - db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, INITIAL_FROM_BLOCK, U256::from(1000)); - - db -} - -/// Simple contract: just STOPs. -fn empty_contract() -> Bytes { - BytecodeBuilder::default().stop().build() -} - -/// Contract that does 10 SSTOREs + 5 LOG1s + 50 ADDs. -fn mixed_contract() -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..10u64 { - builder = builder.push_number(i + 1).push_number(i).append(SSTORE); - } - for _ in 0..5 { - builder = builder.push_number(0xbeef_u64).push_number(32u64).push_number(0u64).append(LOG1); - } - for _ in 0..50 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.stop().build() -} - -// -// ============================================================================ -// Block Executor Pipeline Benchmarks -// ============================================================================ -// - -/// Benchmark a complete block with N empty transactions. -fn bench_block_empty_txs(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_empty_txs"); - group.sample_size(10); - - let contract_code = empty_contract(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - for n_txs in [1, 10, 50] { - group.bench_function(format!("{spec_name}/{n_txs}_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..n_txs { - let tx = create_call_tx(i, 1_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - } - group.finish(); -} - -/// Benchmark a complete block with N mixed workload transactions. -fn bench_block_mixed_txs(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_mixed_txs"); - group.sample_size(10); - - let contract_code = mixed_contract(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - for n_txs in [1, 10] { - group.bench_function(format!("{spec_name}/{n_txs}_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..n_txs { - let tx = create_call_tx(i, 10_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - } - group.finish(); -} - -/// Benchmark contract deployment through the block executor. -fn bench_block_deploy(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_deploy"); - group.sample_size(10); - - // Init code that deploys a small runtime: PUSH1 0x00 PUSH1 0x00 RETURN - let init_code: Bytes = vec![0x60, 0x00, 0x60, 0x00, 0xf3].into(); - let specs: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - for &(spec_name, spec) in specs { - group.bench_function(format!("{spec_name}/deploy_1"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - let nonce = 0u64; - let tx = create_deploy_tx(nonce, 10_000_000, init_code.clone()); - let gas = executor.execute_transaction(&tx).expect("deploy should succeed"); - black_box(gas); - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - group.finish(); -} - -/// Benchmark spec comparison for block execution. -/// -/// NOTE: Each spec runs against its own coherent world (`hardforks_for(spec)`), pre-block -/// setup included: `EQUIVALENCE` deploys nothing while `REX5` bootstraps its predeploys and -/// registry inside every iteration. Rows therefore compare whole-block costs per spec, not -/// isolated EVM execution deltas — for the latter, the cross-spec compute-gas snapshot -/// (`tests/compute_gas/`) is the tool. -fn bench_block_spec_comparison(c: &mut Criterion) { - let mut group = c.benchmark_group("block_executor_spec_comparison"); - group.sample_size(10); - - let contract_code = mixed_contract(); - let specs: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - ]; - - for &(spec_name, spec) in specs { - group.bench_function(format!("{spec_name}/5_mixed_txs"), |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor - .apply_pre_execution_changes() - .expect("pre-execution changes should succeed"); - - for i in 0..5u64 { - let tx = create_call_tx(i, 10_000_000); - let gas = executor.execute_transaction(&tx).expect("should succeed"); - black_box(gas); - } - - let (_evm, block_result) = executor.finish().expect("finish should succeed"); - black_box(block_result); - }) - }); - } - group.finish(); -} - -/// Benchmark the full REX5 pre-block path. -/// -/// `bootstrap` starts from an empty DB and pays first-deploy cost for the REX5 system contracts. -/// `no_change` starts from a steady-state DB where all deploy-only contracts already exist and -/// the `SequencerRegistry` has no pending changes. -fn bench_rex5_pre_block(c: &mut Criterion) { - let mut group = c.benchmark_group("rex5_pre_block"); - group.sample_size(10); - - let contract_code = empty_contract(); - let spec = MegaSpecId::REX5; - - // Bootstrap block: first REX5 pre-block on an empty state. - group.bench_function("bootstrap", |b| { - b.iter(|| { - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, contract_code.clone()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - black_box(()); - }) - }); - - // Steady-state block: all deploy-only system contracts already exist and the registry has no - // pending changes. - group.bench_function("no_change", |b| { - let baseline_db = rex5_steady_state_db(&contract_code); - - b.iter(|| { - let mut db = baseline_db.clone(); - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let evm = evm_factory.create_evm(&mut state, block_evm_env(spec)); - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = MegaBlockExecutor::new( - evm, - block_ctx, - hardforks_for(spec), - OpAlloyReceiptBuilder::default(), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - black_box(()); - }) - }); - - group.finish(); -} - -/// Benchmark hardfork-config resolution on the real mainnet schedule. -/// -/// The position-projected predicates (`is_rex_5_active_at_timestamp`) are what downstream node -/// components call once per block; `spec_id` is the executor's per-block resolution; -/// `validate_schedule` is a once-per-config-load cost. Resolution's descending early-exit scan -/// keeps the per-query cost at one or two activation lookups for chains near the top of the -/// ladder, which this benchmark pins. -fn bench_hardfork_resolution(c: &mut Criterion) { - use mega_evm::MegaHardforks; - - let mut group = c.benchmark_group("hardfork_resolution"); - let schedule = mega_evm::mainnet_hardforks(); - // A timestamp after the last scheduled fork: every real query happens here. - let ts = 1_800_000_000u64; - - group.bench_function("is_rex_5_active_at_timestamp", |b| { - b.iter(|| black_box(schedule.is_rex_5_active_at_timestamp(black_box(ts)))) - }); - group.bench_function("spec_id", |b| b.iter(|| black_box(schedule.spec_id(black_box(ts))))); - group.bench_function("validate_schedule", |b| { - b.iter(|| black_box(schedule.validate_schedule())) - }); - - group.finish(); -} - -criterion_group!( - benches, - bench_block_empty_txs, - bench_block_mixed_txs, - bench_block_deploy, - bench_block_spec_comparison, - bench_rex5_pre_block, - bench_hardfork_resolution, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/common/mod.rs b/crates/mega-evm/benches/common/mod.rs deleted file mode 100644 index 0d75c1c70..000000000 --- a/crates/mega-evm/benches/common/mod.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Shared bench harness comparing mega-evm against vanilla revm and op-revm. -//! -//! A bench declares a backend-agnostic [`Workload`] (accounts + transactions) -//! and registers it across a fixed set of [`Subject`](subject::Subject) rows: -//! the four vanilla baselines (`revm_pinned`, `revm_latest`, `op_revm_pinned`, -//! `op_revm_latest`) and the mega specs. Every row runs the same scenario, so a -//! single criterion group yields a comparable gap table. -//! -//! Bench files pull this in with a plain `mod common;` (resolved via the -//! standard `common/mod.rs` sibling-folder lookup). Each criterion bench target -//! compiles as its own binary, so this module is compiled once per target. - -#![allow(dead_code)] // each bench target uses a subset of the harness -#![allow(unreachable_pub)] // included as a shared bench module, so `pub` items appear unreachable in lint terms - -pub mod subject; -pub mod workload; - -use core::convert::Infallible; - -use mega_evm::{MegaSpecId, TestExternalEnvs}; -pub use subject::MegaWithEnv; -use subject::{Mega, OpRevmLatest, OpRevmPinned, RevmLatest, RevmPinned, Subject}; -pub use workload::{Account, TxSpec, Workload}; - -/// Mega specs registered by [`register_all`] and [`register_mega`]. Shared so -/// every bench file emits the same mega rows. Benches needing a different set -/// (single spec, SELFDESTRUCT-relevant specs, …) pass their own list to -/// [`register_mega_specs`]. -pub const SPEC_IDS: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - // REX5 vs REX6 isolates the cost of the unified gas-metering order: REX6 routes the - // storage-affecting opcodes (SSTORE, CALL, etc.) through the canonical - // charge-storage / run-body / record-compute-once path. - ("rex6", MegaSpecId::REX6), - // Rex7 delegates to Rex6 entirely, so the pair reads as a no-op today. It is registered from - // the spec's first day anyway: this is the frozen baseline every later Rex7 measurement is - // compared against, and a row added only once Rex7 has behavior would arrive with nothing to - // compare to. - ("rex7", MegaSpecId::REX7), -]; - -type Group<'a> = criterion::BenchmarkGroup<'a, criterion::measurement::WallTime>; - -fn baseline_subjects() -> Vec> { - vec![Box::new(RevmPinned), Box::new(RevmLatest), Box::new(OpRevmPinned), Box::new(OpRevmLatest)] -} - -fn mega_subjects(specs: &[(&'static str, MegaSpecId)]) -> Vec> { - specs.iter().map(|&(name, spec)| Box::new(Mega { name, spec }) as Box).collect() -} - -/// Run each subject as one row of `group`, named `` or, when `variant` -/// is non-empty, `/` (e.g. `revm_pinned/log0_32b`) so every -/// row shares a single variant axis. -fn run_subjects(group: &mut Group<'_>, variant: &str, w: &Workload, subjects: &[Box]) { - for subject in subjects { - let row = if variant.is_empty() { - subject.name().to_string() - } else { - format!("{}/{variant}", subject.name()) - }; - group.bench_function(row, |b| b.iter(|| subject.run(w))); - } -} - -/// Register the four baselines plus the [`SPEC_IDS`] mega rows. -pub fn register_all(group: &mut Group<'_>, w: &Workload) { - register_all_suffixed(group, "", w); -} - -/// [`register_all`] with a `/variant` suffix on every row. -pub fn register_all_suffixed(group: &mut Group<'_>, variant: &str, w: &Workload) { - let mut subjects = baseline_subjects(); - subjects.extend(mega_subjects(SPEC_IDS)); - run_subjects(group, variant, w, &subjects); -} - -/// Register only the [`SPEC_IDS`] mega rows (no vanilla baselines). -pub fn register_mega(group: &mut Group<'_>, w: &Workload) { - register_mega_suffixed(group, "", w); -} - -/// [`register_mega`] with a `/variant` suffix on every row. -pub fn register_mega_suffixed(group: &mut Group<'_>, variant: &str, w: &Workload) { - run_subjects(group, variant, w, &mega_subjects(SPEC_IDS)); -} - -/// Register mega rows for a caller-supplied spec list (e.g. a single spec, or -/// the SELFDESTRUCT-relevant specs). -pub fn register_mega_specs( - group: &mut Group<'_>, - specs: &[(&'static str, MegaSpecId)], - w: &Workload, -) { - register_mega_specs_suffixed(group, specs, "", w); -} - -/// [`register_mega_specs`] with a `/variant` suffix on every row. -pub fn register_mega_specs_suffixed( - group: &mut Group<'_>, - specs: &[(&'static str, MegaSpecId)], - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &mega_subjects(specs)); -} - -/// Register three isolation rows for one spec + workload under a `/variant` -/// suffix, in order: -/// -/// 1. `revm_pinned` — the env-agnostic absolute floor (no mega overhead). -/// 2. `baseline_name` — `Mega` over `EmptyExternalEnv`, where the external-env path (SALT / oracle) -/// short-circuits to constants (no hash, no map lookup). -/// 3. `active_name` — `MegaWithEnv` over the supplied `env`, exercising the real external-env path -/// (e.g. crowded SALT buckets or oracle storage). -/// -/// The `active_name` − `baseline_name` gap isolates the external-env path cost -/// while holding spec and workload fixed. Shared by the SALT and oracle benches. -pub fn register_env_isolation( - group: &mut Group<'_>, - spec: MegaSpecId, - baseline_name: &'static str, - active_name: &'static str, - env: TestExternalEnvs, - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &[Box::new(RevmPinned)]); - run_subjects(group, variant, w, &[Box::new(Mega { name: baseline_name, spec })]); - run_subjects(group, variant, w, &[Box::new(MegaWithEnv { name: active_name, spec, env })]); -} - -/// Like [`register_env_isolation`] but omits the `revm_pinned` floor row. -/// -/// Use this to register more than one spec's env-isolation rows in the SAME -/// group: call [`register_env_isolation`] for the first spec (registering the -/// shared `revm_pinned` floor plus that spec's baseline + active env rows), -/// then call this floor-less variant for each additional spec. The -/// `revm_pinned` row must appear only once per group — registering it twice -/// panics with a duplicate benchmark-id error. -pub fn register_env_isolation_mega_only( - group: &mut Group<'_>, - spec: MegaSpecId, - baseline_name: &'static str, - active_name: &'static str, - env: TestExternalEnvs, - variant: &str, - w: &Workload, -) { - run_subjects(group, variant, w, &[Box::new(Mega { name: baseline_name, spec })]); - run_subjects(group, variant, w, &[Box::new(MegaWithEnv { name: active_name, spec, env })]); -} diff --git a/crates/mega-evm/benches/common/subject.rs b/crates/mega-evm/benches/common/subject.rs deleted file mode 100644 index d3dc946a9..000000000 --- a/crates/mega-evm/benches/common/subject.rs +++ /dev/null @@ -1,443 +0,0 @@ -//! Benchmark subjects: one per EVM stack being compared. -//! -//! A [`Subject`] turns a backend-agnostic [`Workload`] into a concrete run on -//! its own stack. The shared loop/assert/measure skeleton lives once in -//! [`run_workload`]; each subject only supplies how to *build* its EVM and how -//! to *execute* one tx, so the success assertion can never drift between stacks. -//! -//! What makes the vanilla rows comparable — the target hardfork and the -//! operator-fee zero-out — is defined once in the "Comparability baseline" -//! section below, not repeated per stack. -//! -//! `_latest` types come from a cargo `package` rename in `Cargo.toml`. Both -//! `_latest` subjects share one revm tree because the chosen `op-revm` version -//! already pulls the chosen `revm` version transitively. - -use alloy_primitives::{Address, Bytes, U256}; -use core::convert::Infallible; -use criterion::black_box; -use mega_evm::{ - revm::inspector::NoOpInspector, test_utils::MemoryDatabase, EmptyExternalEnv, MegaContext, - MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, -}; -use op_revm::{ - DefaultOp as _, OpBuilder as _, OpContext as OpContextPinned, OpSpecId as OpSpecIdPinned, - OpTransaction as OpTransactionPinned, -}; -use op_revm_latest::{ - DefaultOp as _, OpBuilder as _, OpContext as OpContextLatest, OpSpecId as OpSpecIdLatest, - OpTransaction as OpTransactionLatest, -}; -use revm::{ - context::{tx::TxEnvBuilder, TxEnv}, - database::EmptyDB as EmptyDBPinned, - primitives::hardfork::SpecId as SpecIdPinned, - Context as ContextPinned, ExecuteEvm, MainBuilder as _, MainContext as _, -}; -use revm_latest::{ - bytecode::Bytecode as BytecodeLatest, - context::{tx::TxEnvBuilder as TxEnvBuilderLatest, TxEnv as TxEnvLatest}, - database::{CacheDB as CacheDBLatest, EmptyDB as EmptyDBLatest}, - primitives::hardfork::SpecId as SpecIdLatest, - Context as ContextLatest, ExecuteEvm as _, MainBuilder as _, MainContext as _, -}; -use std::{cell::RefCell, rc::Rc}; - -use super::workload::{Account, TxSpec, Workload}; - -// -// ============================================================================ -// Comparability baseline — single source of truth for what makes the vanilla -// rows comparable. Change a value here and every baseline moves together; CI's -// baseline-gap table assumes the rows all sit on one fork. -// ============================================================================ -// - -/// Target hardfork for the vanilla `revm` rows. Cancun keeps every baseline on -/// one fork and predates EIP-7825's `tx_gas_limit_cap` (2^24), so the -/// multi-gigagas `gas_limit` workloads are not truncated. (`revm_latest`'s -/// `MainContext::mainnet()` would otherwise default to Osaka and trip the cap.) -const REVM_FORK: SpecIdPinned = SpecIdPinned::CANCUN; -const REVM_FORK_LATEST: SpecIdLatest = SpecIdLatest::CANCUN; - -/// Target hardfork for the op rows. Holocene maps to eth Cancun, matching the -/// `revm` rows above. Needed because `DefaultOp::op()` hard-codes `BEDROCK` -/// (eth Merge) regardless of the enum default — without this the op rows would -/// sit on a different fork and the op-vs-revm gap would reflect a hardfork -/// difference rather than a version one. -const OP_FORK: OpSpecIdPinned = OpSpecIdPinned::HOLOCENE; -const OP_FORK_LATEST: OpSpecIdLatest = OpSpecIdLatest::HOLOCENE; - -/// Zero the operator fee so the op and mega rows are comparable to the revm -/// rows, which carry no such fee. A macro rather than a fn: the three `chain` -/// types come from distinct crates (op-revm pinned/latest, mega-evm) and share -/// no common trait — only the field names line up. -macro_rules! zero_operator_fee { - ($chain:expr) => {{ - $chain.operator_fee_scalar = Some(U256::ZERO); - $chain.operator_fee_constant = Some(U256::ZERO); - }}; -} - -// -// ============================================================================ -// Subject trait + shared run skeleton. -// ============================================================================ -// - -/// One row of a criterion group — a specific EVM stack at a specific config. -pub trait Subject { - /// Row name as it appears in the criterion group (e.g. `revm_pinned`). - fn name(&self) -> &str; - /// Build a fresh DB + EVM from the workload, run every tx on that one - /// reused instance, and (unless the workload opts out) assert each - /// succeeds. Implementations delegate to [`run_workload`]. - fn run(&self, workload: &Workload); -} - -/// The one place the per-tx loop, success assertion, and `black_box` live. -/// -/// `build` constructs the (stack-specific) EVM once; `exec` runs a single tx -/// and returns its `is_success()`. Keeping the skeleton here means the success -/// check can never drift or be forgotten on one stack — the bug that the old -/// per-stack `run` bodies were prone to. The generic `E` is inferred from -/// `build`, so no stack has to spell out its verbose revm `Evm<…>` type. -/// -/// On failure the panic names the row and tx index; the concrete result is not -/// surfaced because `exec` has already abstracted away the stack's distinct -/// `ExecutionResult` type (it `black_box`es the result for the optimizer). -fn run_workload( - name: &str, - workload: &Workload, - build: impl FnOnce() -> E, - exec: impl Fn(&mut E, &TxSpec) -> bool, -) { - let mut evm = build(); - for (i, tx) in workload.txs.iter().enumerate() { - let success = exec(&mut evm, tx); - if workload.assert_success { - assert!(success, "{name} tx #{i} should succeed"); - } - } -} - -// -// ============================================================================ -// Database builders — written once, fed to every subject of each stack. -// ============================================================================ -// - -/// Seed a pinned-revm `MemoryDatabase` from the workload accounts. Shared by -/// the `*_pinned` baselines and every `mega_*` subject. -fn build_pinned_db(accounts: &[Account]) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - for account in accounts { - db = db.account_balance(account.address, account.balance); - if let Some(code) = &account.code { - db = db.account_code(account.address, code.clone()); - } - for (slot, value) in &account.storage { - db = db.account_storage(account.address, *slot, *value); - } - } - db -} - -/// Seed a latest-revm `CacheDB` from the workload accounts. Shared by both -/// `*_latest` baselines. -fn build_latest_db(accounts: &[Account]) -> CacheDBLatest { - let mut builder = LatestDbBuilder::new(); - for account in accounts { - builder = builder.account_balance(account.address, account.balance); - if let Some(code) = &account.code { - builder = builder.account_code(account.address, code.clone()); - } - for (slot, value) in &account.storage { - builder = builder.account_storage(account.address, *slot, *value); - } - } - builder.build() -} - -/// Translate a [`TxSpec`] into a pinned-revm `TxEnv`, used by the `revm_pinned`, -/// `op_revm_pinned`, and `mega_*` subjects (mega-evm re-exports the same pinned -/// revm crate). -fn pinned_tx_env(tx: &TxSpec) -> TxEnv { - TxEnvBuilder::new() - .caller(tx.caller) - .call(tx.target) - .gas_limit(tx.gas_limit) - .value(tx.value) - .data(tx.data.clone()) - .build_fill() -} - -/// Translate a [`TxSpec`] into a latest-revm `TxEnv`. -fn latest_tx_env(tx: &TxSpec) -> TxEnvLatest { - TxEnvBuilderLatest::new() - .caller(tx.caller) - .call(tx.target) - .gas_limit(tx.gas_limit) - .value(tx.value) - .data(tx.data.clone()) - .build_fill() -} - -// -// ============================================================================ -// Mega subject. -// ============================================================================ -// - -/// `MegaEvm` at a single spec. One instance per benchmarked spec. -pub struct Mega { - pub name: &'static str, - pub spec: MegaSpecId, -} - -impl Subject for Mega { - fn name(&self) -> &str { - self.name - } - - fn run(&self, workload: &Workload) { - let spec = self.spec; - run_workload( - self.name, - workload, - || { - let mut context = MegaContext::new(build_pinned_db(&workload.accounts), spec); - context.modify_chain(|chain| zero_operator_fee!(chain)); - MegaEvm::<_, NoOpInspector, EmptyExternalEnv>::new(context) - }, - |evm, tx| { - // Wrap into a `MegaTransaction` with an empty envelope, matching - // what the production tx-pool would attach. - let mut mega_tx = MegaTransaction::new(pinned_tx_env(tx)); - mega_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(mega_tx).expect("mega transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// MegaWithEnv subject. -// ============================================================================ -// - -/// `MegaEvm` at a single spec over a configurable `TestExternalEnvs` (crowded -/// SALT buckets and/or oracle storage). Used by the SALT and oracle benches. -/// The `env` is cloned per build so each iteration starts from the same config. -pub struct MegaWithEnv { - pub name: &'static str, - pub spec: MegaSpecId, - pub env: TestExternalEnvs, -} - -impl Subject for MegaWithEnv { - fn name(&self) -> &str { - self.name - } - - fn run(&self, workload: &Workload) { - let spec = self.spec; - let env = self.env.clone(); - run_workload( - self.name, - workload, - || { - let db = build_pinned_db(&workload.accounts); - let salt = Rc::new(env.clone()); - let oracle = Rc::new(RefCell::new(env.clone())); - let mut context = MegaContext::new_with_ext_envs(db, spec, salt, oracle); - context.modify_chain(|chain| zero_operator_fee!(chain)); - MegaEvm::<_, NoOpInspector, TestExternalEnvs>::new(context) - }, - |evm, tx| { - let mut mega_tx = MegaTransaction::new(pinned_tx_env(tx)); - mega_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(mega_tx).expect("mega transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// Baseline subjects. Fork pins and the operator-fee zero-out come from the -// Comparability baseline section above. -// ============================================================================ -// - -/// Vanilla `revm` at the version mega-evm currently pins (fork: [`REVM_FORK`]). -pub struct RevmPinned; - -impl Subject for RevmPinned { - fn name(&self) -> &str { - "revm_pinned" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - ContextPinned::mainnet() - .modify_cfg_chained(|cfg| cfg.spec = REVM_FORK) - .with_db(build_pinned_db(&workload.accounts)) - .build_mainnet() - }, - |evm, tx| { - let r = evm.transact(pinned_tx_env(tx)).expect("revm_pinned transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// Vanilla `revm` at the latest crates.io release (fork: [`REVM_FORK_LATEST`]). -pub struct RevmLatest; - -impl Subject for RevmLatest { - fn name(&self) -> &str { - "revm_latest" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - ContextLatest::mainnet() - .modify_cfg_chained(|cfg| cfg.set_spec_and_mainnet_gas_params(REVM_FORK_LATEST)) - .with_db(build_latest_db(&workload.accounts)) - .build_mainnet() - }, - |evm, tx| { - let r = evm.transact(latest_tx_env(tx)).expect("revm_latest transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// `op-revm` at the version mega-evm currently pins (fork: [`OP_FORK`], -/// operator fee = 0). -pub struct OpRevmPinned; - -impl Subject for OpRevmPinned { - fn name(&self) -> &str { - "op_revm_pinned" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - let mut ctx = >::op() - .with_db(build_pinned_db(&workload.accounts)); - ctx.modify_cfg(|cfg| cfg.spec = OP_FORK); - ctx.modify_chain(|chain| zero_operator_fee!(chain)); - ctx.build_op() - }, - |evm, tx| { - let mut op_tx = OpTransactionPinned::new(pinned_tx_env(tx)); - op_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(op_tx).expect("op_revm_pinned transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -/// `op-revm` at the latest crates.io release (fork: [`OP_FORK_LATEST`], -/// operator fee = 0). -pub struct OpRevmLatest; - -impl Subject for OpRevmLatest { - fn name(&self) -> &str { - "op_revm_latest" - } - - fn run(&self, workload: &Workload) { - run_workload( - self.name(), - workload, - || { - let mut ctx = >::op() - .with_db(build_latest_db(&workload.accounts)); - ctx.modify_cfg(|cfg| cfg.spec = OP_FORK_LATEST); - ctx.modify_chain(|chain| zero_operator_fee!(chain)); - ctx.build_op() - }, - |evm, tx| { - let mut op_tx = OpTransactionLatest::new(latest_tx_env(tx)); - op_tx.enveloped_tx = Some(Bytes::new()); - let r = evm.transact(op_tx).expect("op_revm_latest transact"); - let success = r.result.is_success(); - black_box(r); - success - }, - ); - } -} - -// -// ============================================================================ -// CacheDB builder for the latest revm stack. -// ============================================================================ -// - -/// Fluent builder for a `CacheDB` from the latest revm stack, mirroring -/// `MemoryDatabase`'s API so [`build_latest_db`] can seed it the same way -/// [`build_pinned_db`] seeds the pinned database. -#[derive(Default)] -struct LatestDbBuilder { - db: CacheDBLatest, -} - -impl LatestDbBuilder { - fn new() -> Self { - Self { db: CacheDBLatest::new(EmptyDBLatest::default()) } - } - - fn account_code(mut self, address: Address, code: Bytes) -> Self { - let bytecode = BytecodeLatest::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.info.code = Some(bytecode); - entry.info.code_hash = code_hash; - self - } - - fn account_balance(mut self, address: Address, balance: U256) -> Self { - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.info.balance = balance; - self - } - - fn account_storage(mut self, address: Address, slot: U256, value: U256) -> Self { - let entry = self.db.cache.accounts.entry(address).or_default(); - entry.storage.insert(slot, value); - self - } - - fn build(self) -> CacheDBLatest { - self.db - } -} diff --git a/crates/mega-evm/benches/common/workload.rs b/crates/mega-evm/benches/common/workload.rs deleted file mode 100644 index 0d234bd78..000000000 --- a/crates/mega-evm/benches/common/workload.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Backend-agnostic description of a bench scenario. -//! -//! A [`Workload`] names the accounts to seed and the transactions to run, -//! without referring to any particular revm version or EVM type. Each -//! [`Subject`](crate::common::subject::Subject) translates the same `Workload` -//! into its own stack, so a scenario is written once and compared across every -//! row of a criterion group. - -use alloy_primitives::{Address, Bytes, U256}; - -/// A single account to seed into the database before a workload runs. -/// -/// Built fluently: `Account::new(addr).balance(b).code(c).storage(slot, v)`. -/// Omitted fields default to zero balance, no code, and no storage — an -/// `Account` with all defaults still forces the account to exist, which differs -/// from leaving it out of the workload entirely. -#[derive(Clone)] -pub struct Account { - pub address: Address, - pub balance: U256, - pub code: Option, - pub storage: Vec<(U256, U256)>, -} - -impl Account { - pub fn new(address: Address) -> Self { - Self { address, balance: U256::ZERO, code: None, storage: Vec::new() } - } - - pub fn balance(mut self, balance: U256) -> Self { - self.balance = balance; - self - } - - pub fn code(mut self, code: Bytes) -> Self { - self.code = Some(code); - self - } - - pub fn storage(mut self, slot: U256, value: U256) -> Self { - self.storage.push((slot, value)); - self - } -} - -/// A single `transact()` call, backend-agnostic. Mirrors the minimal set of -/// fields every adapter needs; kept deliberately small so it does not tie the -/// abstraction to one revm version's `TxEnv` (the pinned and latest stacks are -/// separate crates and each translates this into its own envelope). -#[derive(Clone)] -pub struct TxSpec { - pub caller: Address, - pub target: Address, - pub gas_limit: u64, - pub value: U256, - pub data: Bytes, -} - -impl TxSpec { - /// A call from `caller` to `target` with a 30M gas limit, no value, no data. - pub fn call(caller: Address, target: Address) -> Self { - Self { caller, target, gas_limit: 30_000_000, value: U256::ZERO, data: Bytes::new() } - } - - pub fn gas_limit(mut self, gas_limit: u64) -> Self { - self.gas_limit = gas_limit; - self - } - - pub fn value(mut self, value: U256) -> Self { - self.value = value; - self - } - - pub fn data(mut self, data: Bytes) -> Self { - self.data = data; - self - } -} - -/// A complete bench scenario: the accounts to seed and the transactions to run. -/// -/// Single-shot benches pass one tx via [`Workload::single`]; `transfer_multi` -/// passes the whole batch and a subject loops over it on one reused EVM. -#[derive(Clone)] -pub struct Workload { - pub accounts: Vec, - pub txs: Vec, - /// When `true` (the default) every subject asserts each tx returns a - /// successful result. Set to `false` via [`Workload::allow_halt`] for - /// scenarios that legitimately halt under some specs (e.g. SELFDESTRUCT - /// disabled, or DELEGATECALL falling through to absent bytecode). - pub assert_success: bool, -} - -impl Workload { - pub fn new(accounts: Vec, txs: Vec) -> Self { - Self { accounts, txs, assert_success: true } - } - - /// A workload running a single transaction. - pub fn single(accounts: Vec, tx: TxSpec) -> Self { - Self::new(accounts, vec![tx]) - } - - /// Opt out of the per-tx `is_success()` assertion. Use for scenarios where - /// halting is the expected outcome under at least one benchmarked spec. - /// - /// The relaxed check accepts *any* non-success result — a revert as well as - /// a halt — not only halts; the name reflects the intended use rather than a - /// revert-vs-halt distinction. - pub fn allow_halt(mut self) -> Self { - self.assert_success = false; - self - } -} diff --git a/crates/mega-evm/benches/comp_cost.rs b/crates/mega-evm/benches/comp_cost.rs deleted file mode 100644 index 141332c71..000000000 --- a/crates/mega-evm/benches/comp_cost.rs +++ /dev/null @@ -1,1130 +0,0 @@ -//! Benchmarks for CPU-intensive EVM opcodes and precompiles. -//! -//! This benchmark suite measures the computational cost of various EVM operations -//! to understand their real-world performance characteristics across different -//! EVM specifications (`EQUIVALENCE` vs `MINI_REX`). -//! -//! The benchmarks are organized into several categories: -//! - Cryptographic hash operations (KECCAK256, SHA256, BLAKE2F) -//! - Arithmetic operations (EXP, ADDMOD, MULMOD, DIV, etc.) -//! - Elliptic curve precompiles (ECRECOVER, ECADD, ECMUL, ECPAIRING) -//! - Modular exponentiation (MODEXP) - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{ADD, ADDRESS, EXP, GAS, KECCAK256, POP, STATICCALL}, - context::{ - result::{ExecResultAndState, ExecutionResult}, - tx::TxEnvBuilder, - }, - precompile::{ - blake2, bls12_381, bn128, - hash::{RIPEMD160, SHA256}, - kzg_point_evaluation, modexp, - secp256k1::ECRECOVER, - }, - primitives::hardfork::SpecId, - Context as RevmContext, ExecuteEvm, MainBuilder as _, MainContext as _, -}; -use sha2::{Digest, Sha256 as Sha256Hash}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -/// Specification IDs to benchmark against. REX5 is included so the precompile -/// hot path (compute-gas cap + Gas normalization in `PrecompilesMap::run`) is -/// measured against the pre-REX5 baseline. -const SPEC_IDS: &[(&str, MegaSpecId)] = &[ - // ("equivalence", MegaSpecId::EQUIVALENCE), - ("mini_rex", MegaSpecId::MINI_REX), - ("rex5", MegaSpecId::REX5), -]; - -// -// ============================================================================ -// Common Utility Functions -// ============================================================================ -// - -/// Execute bytecode with the given spec and return the transaction execution result. -fn execute_bytecode( - bytecode: &Bytes, - spec: MegaSpecId, -) -> ExecResultAndState> { - let db = MemoryDatabase::default() - .account_code(CONTRACT, bytecode.clone()) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(10_000_000_000u64).build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let r = evm.transact(mega_tx).expect("transaction should succeed"); - assert!(r.result.is_success(), "transaction should succeed: {:?}", r.result); - assert!(r.result.gas_used() > 21000, "transaction should spend more than 21000 gas"); - r -} - -/// Execute bytecode with the given spec and return gas used. -fn execute_and_get_gas(bytecode: &Bytes, spec: MegaSpecId) -> u64 { - execute_bytecode(bytecode, spec).result.gas_used() -} - -/// Run `bytecode` on vanilla revm at PRAGUE (has all precompiles incl. BLS12-381, -/// no EIP-7825 tx-gas cap). The no-mega floor for precompile benchmarks. -/// -/// Mirrors `execute_bytecode`'s measurement boundary: the full execution result is -/// kept alive through `black_box` before being dropped, so the optimizer cannot -/// elide result construction for the revm row while keeping it for the mega rows — -/// an asymmetry that would underestimate the revm floor and inflate the gap. -fn execute_bytecode_revm(bytecode: &Bytes) -> bool { - let db = MemoryDatabase::default() - .account_code(CONTRACT, bytecode.clone()) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - let mut evm = RevmContext::mainnet() - .modify_cfg_chained(|cfg| cfg.spec = SpecId::PRAGUE) - .with_db(db) - .build_mainnet(); - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(10_000_000_000u64).build_fill(); - let r = evm.transact(tx).expect("revm transact"); - assert!(r.result.is_success(), "revm precompile bench tx should succeed: {:?}", r.result); - let success = r.result.is_success(); - black_box(r); - success -} - -/// Print gas for each spec, then bench a `revm_pinned` row and one row per spec. -/// -/// The `revm_pinned` row runs vanilla revm at PRAGUE — the no-mega floor. -/// One row per `SPEC_IDS` entry follows so the mega-vs-revm gap is visible. -fn bench_precompile_group(c: &mut Criterion, group_name: &str, bytecode: Bytes) { - let mut group = c.benchmark_group(group_name); - println!("\n=== Gas consumption for {group_name} ==="); - for &(spec_name, spec) in SPEC_IDS { - println!(" {spec_name} spec: {} gas", execute_and_get_gas(&bytecode, spec)); - } - println!(); - group.bench_function("revm_pinned", |b| { - b.iter(|| black_box(execute_bytecode_revm(black_box(&bytecode)))) - }); - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - group.finish(); -} - -// -// ============================================================================ -// Simple Opcodes -// ============================================================================ -// - -fn generate_add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(1_u64); - builder = builder.push_number(2_u64); - builder = builder.append(ADD); - builder = builder.append(POP); - } - builder.build() -} - -/// Benchmark ADD opcode. -fn bench_add_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - let mut group = c.benchmark_group("add"); - let bytecode = generate_add_bytecode(ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for add ({}x iterations) ===", ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - group.finish(); -} - -fn generate_address_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(ADDRESS); - builder = builder.append(POP); - } - builder.build() -} - -/// Benchmark ADDRESS opcode. -fn bench_address_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - let mut group = c.benchmark_group("address"); - let bytecode = generate_address_bytecode(ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for address ({}x iterations) ===", ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); -} - -// -// ============================================================================ -// KECCAK256 Benchmarks -// ============================================================================ -// - -/// Generate bytecode that benchmarks KECCAK256 opcode with specified data size. -fn generate_keccak256_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - // Call KECCAK256 multiple times - for _ in 0..iterations { - builder = builder.push_number(data_size as u64); // size - builder = builder.push_number(0_u64); // offset - builder = builder.append(KECCAK256); - builder = builder.append(POP); // remove hash result from stack - } - - builder.build() -} - -/// Benchmark KECCAK256 opcode with varying data sizes. -fn bench_keccak256_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - let mut group = c.benchmark_group(format!("keccak256_{}", size_name)); - let bytecode = generate_keccak256_bytecode(data_size, ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!( - "\n=== Gas consumption for keccak256_{} ({}x iterations) ===", - size_name, ITERATIONS - ); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); - } -} - -// -// ============================================================================ -// EXP (Exponentiation) Benchmarks -// ============================================================================ -// - -/// Generate bytecode that benchmarks EXP opcode with specified exponent size. -fn generate_exp_bytecode(exponent_bits: u32, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Create an exponent with the specified number of bits set - let exponent = if exponent_bits == 256 { - U256::MAX - } else if exponent_bits == 0 { - U256::ZERO - } else { - (U256::from(1) << exponent_bits) - U256::from(1) - }; - - let base = U256::from(3); // Use 3 as base for exponentiation - - // Call EXP multiple times - for _ in 0..iterations { - builder = builder.push_u256(exponent); - builder = builder.push_u256(base); - builder = builder.append(EXP); - builder = builder.append(POP); // remove result from stack - } - - builder.build() -} - -/// Benchmark EXP opcode with varying exponent sizes. -fn bench_exp_opcode(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("256bit", 256)]; - - for (size_name, exponent_bits) in test_cases { - let mut group = c.benchmark_group(format!("exp_{}", size_name)); - let bytecode = generate_exp_bytecode(exponent_bits, ITERATIONS); - - // Run once to collect gas consumption before benchmarking - println!("\n=== Gas consumption for exp_{} ({}x iterations) ===", size_name, ITERATIONS); - for &(spec_name, spec) in SPEC_IDS { - let gas_used = execute_and_get_gas(&bytecode, spec); - println!(" {} spec: {} gas", spec_name, gas_used); - } - println!(); - - for &(spec_name, spec) in SPEC_IDS { - group.bench_function(spec_name, |b| { - b.iter(|| black_box(execute_bytecode(&bytecode, black_box(spec)))) - }); - } - - group.finish(); - } -} - -// -// ============================================================================ -// ECRECOVER Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECRECOVER precompile. -fn generate_ecrecover_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECRECOVER input (hash, v, r, s) - let r = bytes!("0x9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac8038825608"); - let s = bytes!("0x4f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada"); - let v = U256::from(28); - let hash = bytes!("0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3"); - let _signer = address!("0x7156526fbd7a3c72969b54f64e42c10fbb768c8a"); - - // Store input data in memory - builder = builder.mstore(0, hash); // hash at offset 0 - builder = builder.mstore(32, v.to_be_bytes_vec()); // v at offset 32 - builder = builder.mstore(64, &r); // r at offset 64 - builder = builder.mstore(96, &s); // s at offset 96 - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (hash + v + r + s = 128 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*ECRECOVER.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); // remove success flag - } - - builder.build() -} - -/// Benchmark ECRECOVER precompile. -fn bench_ecrecover_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecrecover", generate_ecrecover_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// SHA256 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls SHA256 precompile. -fn generate_sha256_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (SHA256 outputs 32 bytes) - builder = builder.push_number(data_size as u64 + 32); // retOffset - builder = builder.push_number(data_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*SHA256.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark SHA256 precompile with varying input sizes. -fn bench_sha256_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_sha256_{}", size_name), - generate_sha256_bytecode(data_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// RIPEMD160 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls RIPEMD160 precompile. -fn generate_ripemd160_bytecode(data_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Fill memory with data - let data = vec![0xFF; data_size]; - builder = builder.mstore(0, data); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (RIPEMD160 outputs 32 bytes, padded) - builder = builder.push_number(data_size as u64 + 32); // retOffset - builder = builder.push_number(data_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*RIPEMD160.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark RIPEMD160 precompile with varying input sizes. -fn bench_ripemd160_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32), ("1KB", 1024)]; - - for (size_name, data_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_ripemd160_{}", size_name), - generate_ripemd160_bytecode(data_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// MODEXP Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls MODEXP precompile with specified modulus size. -fn generate_modexp_bytecode(modulus_size: usize, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MODEXP input format: - // - let base_len = modulus_size; - let exp_len = modulus_size; - let mod_len = modulus_size; - - // Create sample values (using simple patterns for testing) - let base = vec![0x03u8; base_len]; - let exponent = vec![0xFFu8; exp_len]; - let modulus = vec![0x05u8; mod_len]; - - // Store lengths (each 32 bytes) - builder = builder.mstore(0, U256::from(base_len).to_be_bytes_vec()); - builder = builder.mstore(32, U256::from(exp_len).to_be_bytes_vec()); - builder = builder.mstore(64, U256::from(mod_len).to_be_bytes_vec()); - - // Store base, exponent, and modulus - builder = builder.mstore(96, base); - builder = builder.mstore(96 + base_len, exponent); - builder = builder.mstore(96 + base_len + exp_len, modulus); - - let input_size = 96 + base_len + exp_len + mod_len; - - for _ in 0..iterations { - builder = builder.push_number(mod_len as u64); // retSize (output size = modulus size) - builder = builder.push_number(input_size as u64 + 32); // retOffset - builder = builder.push_number(input_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*modexp::BYZANTIUM.address()); - builder = builder.append(GAS); // gas (modexp can be expensive) - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark MODEXP precompile with varying modulus sizes. -fn bench_modexp_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("32B", 32)]; - - for (size_name, modulus_size) in test_cases { - bench_precompile_group( - c, - &format!("precompile_modexp_{}", size_name), - generate_modexp_bytecode(modulus_size, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// ECADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECADD precompile. -fn generate_ecadd_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECADD input: two points on alt_bn128 curve - // Point 1: (1, 2) - let x1 = U256::from(1); - let y1 = U256::from(2); - // Point 2: (1, 2) - doubling the point - let x2 = U256::from(1); - let y2 = U256::from(2); - - // Store input data in memory - builder = builder.mstore(0, x1.to_be_bytes_vec()); - builder = builder.mstore(32, y1.to_be_bytes_vec()); - builder = builder.mstore(64, x2.to_be_bytes_vec()); - builder = builder.mstore(96, y2.to_be_bytes_vec()); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (x, y = 64 bytes) - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (two points = 128 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::add::ADDRESS); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECADD precompile. -fn bench_ecadd_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecadd", generate_ecadd_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// ECMUL Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECMUL precompile. -fn generate_ecmul_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECMUL input: point and scalar - // Point: (1, 2) - let x = U256::from(1); - let y = U256::from(2); - // Scalar - let scalar = U256::from(2); - - // Store input data in memory - builder = builder.mstore(0, x.to_be_bytes_vec()); - builder = builder.mstore(32, y.to_be_bytes_vec()); - builder = builder.mstore(64, scalar.to_be_bytes_vec()); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (x, y = 64 bytes) - builder = builder.push_number(96_u64); // retOffset - builder = builder.push_number(96_u64); // argsSize (point + scalar = 96 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::mul::ADDRESS); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECMUL precompile. -fn bench_ecmul_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecmul", generate_ecmul_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// ECPAIRING Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls ECPAIRING precompile with specified number of pairing points. -fn generate_ecpairing_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Sample ECPAIRING input: pairs of (G1 point, G2 point) - // For simplicity, we'll use the identity elements which are valid points - // G1 point (x, y) - using generator point (1, 2) - let g1_x1 = bytes!("0x2cf44499d5d27bb186308b7af7af02ac5bc9eeb6a3d147c186b21fb1b76e18da"); - let g1_y1 = bytes!("0x2c0f001f52110ccfe69108924926e45f0b0c868df0e7bde1fe16d3242dc715f6"); - let g1_x2 = bytes!("0x1fb19bb476f6b9e44e2a32234da8212f61cd63919354bc06aef31e3cfaff3ebc"); - let g1_y2 = bytes!("0x22606845ff186793914e03e21df544c34ffe2f2f3504de8a79d9159eca2d98d9"); - let g1_x3 = bytes!("0x2bd368e28381e8eccb5fa81fc26cf3f048eea9abfdd85d7ed3ab3698d63e4f90"); - let g1_y3 = bytes!("0x2fe02e47887507adf0ff1743cbac6ba291e66f59be6bd763950bb16041a0a85e"); - - let g2_x1 = bytes!("0x0000000000000000000000000000000000000000000000000000000000000001"); - let g2_y1 = bytes!("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"); - let g2_x2 = bytes!("0x1971ff0471b09fa93caaf13cbf443c1aede09cc4328f5a62aad45f40ec133eb4"); - let g2_y2 = bytes!("0x091058a3141822985733cbdddfed0fd8d6c104e9e9eff40bf5abfef9ab163bc7"); - let g2_x3 = bytes!("0x2a23af9a5ce2ba2796c1f4e453a370eb0af8c212d9dc9acd8fc02c2e907baea2"); - let g2_y3 = bytes!("0x23a8eb0b0996252cb548a4487da97b02422ebc0e834613f954de6c7e0afdc1fc"); - - // Store pairing input data in memory - builder = builder.mstore(0, &g1_x1); - builder = builder.mstore(32, &g1_y1); - builder = builder.mstore(64, &g1_x2); - builder = builder.mstore(96, &g1_y2); - builder = builder.mstore(128, &g1_x3); - builder = builder.mstore(160, &g1_y3); - - // G2 point (128 bytes) - builder = builder.mstore(192, &g2_x1); - builder = builder.mstore(224, &g2_y1); - builder = builder.mstore(256, &g2_x2); - builder = builder.mstore(288, &g2_y2); - builder = builder.mstore(320, &g2_x3); - builder = builder.mstore(352, &g2_y3); - - let input_size = 384; - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (returns 32 bytes: 0 or 1) - builder = builder.push_number(input_size as u64 + 32); // retOffset - builder = builder.push_number(input_size as u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(bn128::pair::ADDRESS); - builder = builder.append(GAS); // gas (pairing needs more gas) - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark ECPAIRING precompile with varying number of pairing points. -fn bench_ecpairing_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group(c, "precompile_ecpairing", generate_ecpairing_bytecode(ITERATIONS)); -} - -// -// ============================================================================ -// BLAKE2F Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLAKE2F precompile with specified number of rounds. -fn generate_blake2f_bytecode(rounds: u32, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // BLAKE2F input format (213 bytes total): - // - rounds (4 bytes, big-endian) - // - h (64 bytes, state vector) - // - m (128 bytes, message block) - // - t (16 bytes, offset counters) - // - f (1 byte, final block indicator) - - let rounds_bytes = rounds.to_be_bytes(); - let h = [0x08u8; 64]; // Initial state vector - let m = [0xFFu8; 128]; // Message block - let t = [0x00u8; 16]; // Offset counters - let f = [0x00u8]; // Final block indicator (0 = not final) - - // Store BLAKE2F input in memory - builder = builder.mstore(0, rounds_bytes); - builder = builder.mstore(4, h); - builder = builder.mstore(68, m); - builder = builder.mstore(196, t); - builder = builder.mstore(212, f); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (BLAKE2F returns 64 bytes) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(213_u64); // argsSize - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*blake2::FUN.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLAKE2F precompile with varying number of rounds. -fn bench_blake2f_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - - let test_cases = [("1round", 1)]; - - for (rounds_name, rounds) in test_cases { - bench_precompile_group( - c, - &format!("precompile_blake2f_{}", rounds_name), - generate_blake2f_bytecode(rounds, ITERATIONS), - ); - } -} - -// -// ============================================================================ -// KZG Point Evaluation Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls KZG Point Evaluation precompile. -fn generate_kzg_point_evaluation_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // KZG Point Evaluation input (192 bytes total): - // - versioned_hash (32 bytes) - // - z (32 bytes) - // - y (32 bytes) - // - commitment (48 bytes) - // - proof (48 bytes) - - // Sample data from EIP-4844 test vectors - let commitment = bytes!("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7"); - let mut versioned_hash = Sha256Hash::digest(&commitment).to_vec(); - versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG - let z = bytes!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"); - let y = bytes!("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9"); - let proof = bytes!("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c"); - - // Store KZG input in memory - builder = builder.mstore(0, versioned_hash); - builder = builder.mstore(32, &z); - builder = builder.mstore(64, &y); - builder = builder.mstore(96, &commitment); - builder = builder.mstore(144, &proof); - - for _ in 0..iterations { - builder = builder.push_number(64_u64); // retSize (returns 64 bytes) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(192_u64); // argsSize (total input size) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*kzg_point_evaluation::POINT_EVALUATION.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark KZG Point Evaluation precompile. -fn bench_kzg_point_evaluation_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_kzg_point_evaluation", - generate_kzg_point_evaluation_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G1ADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G1ADD precompile. -fn generate_bls12_381_g1add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G1ADD input: two G1 points (128 bytes each = 256 bytes total) - // Official EIP-2537 test vector - let g1_add_input = bytes!("0000000000000000000000000000000012196c5a43d69224d8713389285f26b98f86ee910ab3dd668e413738282003cc5b7357af9a7af54bb713d62255e80f560000000000000000000000000000000006ba8102bfbeea4416b710c73e8cce3032c31c6269c44906f8ac4f7874ce99fb17559992486528963884ce429a992fee000000000000000000000000000000000001101098f5c39893765766af4512a0c74e1bb89bc7e6fdf14e3e7337d257cc0f94658179d83320b99f31ff94cd2bac0000000000000000000000000000000003e1a9f9f44ca2cdab4f43a1a3ee3470fdf90b2fc228eb3b709fcd72f014838ac82a6d797aeefed9a0804b22ed1ce8f7"); - - // Store the input - builder = builder.mstore(0, &g1_add_input); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(256_u64); // retOffset - builder = builder.push_number(256_u64); // argsSize (two G1 points) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g1_add::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G1ADD precompile. -fn bench_bls12_381_g1add_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g1add", - generate_bls12_381_g1add_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G1MSM Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G1MSM precompile. -fn generate_bls12_381_g1msm_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G1MSM input: G1 point (128 bytes) + scalar (32 bytes) = 160 bytes per pair - // Official EIP-2537 test vector (double-and-add worst case) - let g1_msm_input = bytes!("0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - - // Store the input - builder = builder.mstore(0, &g1_msm_input); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(160_u64); // retOffset - builder = builder.push_number(160_u64); // argsSize (one G1 point + scalar) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g1_msm::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G1MSM precompile. -fn bench_bls12_381_g1msm_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g1msm", - generate_bls12_381_g1msm_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G2ADD Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G2ADD precompile. -fn generate_bls12_381_g2add_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G2ADD input: two G2 points (256 bytes each = 512 bytes total) - // Official EIP-2537 test vector - let g2_add_input = bytes!("0000000000000000000000000000000018c0ada6351b70661f053365deae56910798bd2ace6e2bf6ba4192d1a229967f6af6ca1c9a8a11ebc0a232344ee0f6d6000000000000000000000000000000000cc70a587f4652039d8117b6103858adcd9728f6aebe230578389a62da0042b7623b1c0436734f463cfdd187d20903240000000000000000000000000000000009f50bd7beedb23328818f9ffdafdb6da6a4dd80c5a9048ab8b154df3cad938ccede829f1156f769d9e149791e8e0cd900000000000000000000000000000000079ba50d2511631b20b6d6f3841e616e9d11b68ec3368cd60129d9d4787ab56c4e9145a38927e51c9cd6271d493d938800000000000000000000000000000000192fa5d8732ff9f38e0b1cf12eadfd2608f0c7a39aced7746837833ae253bb57ef9c0d98a4b69eeb2950901917e99d1e0000000000000000000000000000000009aeb10c372b5ef1010675c6a4762fda33636489c23b581c75220589afbc0cc46249f921eea02dd1b761e036ffdbae220000000000000000000000000000000002d225447600d49f932b9dd3ca1e6959697aa603e74d8666681a2dca8160c3857668ae074440366619eb8920256c4e4a00000000000000000000000000000000174882cdd3551e0ce6178861ff83e195fecbcffd53a67b6f10b4431e423e28a480327febe70276036f60bb9c99cf7633"); - - // Store the input - builder = builder.mstore(0, &g2_add_input); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(512_u64); // retOffset - builder = builder.push_number(512_u64); // argsSize (two G2 points) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g2_add::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G2ADD precompile. -fn bench_bls12_381_g2add_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g2add", - generate_bls12_381_g2add_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 G2MSM Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 G2MSM precompile. -fn generate_bls12_381_g2msm_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // G2MSM input: G2 point (256 bytes) + scalar (32 bytes) = 288 bytes per pair - // Official EIP-2537 test vector (double-and-add worst case) - let g2_msm_input = bytes!("00000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79beffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - - // Store the input - builder = builder.mstore(0, &g2_msm_input); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(288_u64); // retOffset - builder = builder.push_number(288_u64); // argsSize (one G2 point + scalar) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::g2_msm::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 G2MSM precompile. -fn bench_bls12_381_g2msm_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_g2msm", - generate_bls12_381_g2msm_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 PAIRING Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 PAIRING precompile. -fn generate_bls12_381_pairing_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // PAIRING input: 2 pairs (G1 point + G2 point) * 2 = 768 bytes - // Official EIP-2537 test vector for 2 pairs - let pairing_input = bytes!("0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0000000000000000000000000000000017f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb0000000000000000000000000000000008b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e100000000000000000000000000000000024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80000000000000000000000000000000013e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e000000000000000000000000000000000ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801000000000000000000000000000000000606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be"); - - // Store the input - builder = builder.mstore(0, &pairing_input); - - for _ in 0..iterations { - builder = builder.push_number(32_u64); // retSize (returns 32 bytes: 0 or 1) - builder = builder.push_number(768_u64); // retOffset - builder = builder.push_number(768_u64); // argsSize (2 pairs = 768 bytes) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::pairing::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 PAIRING precompile. -fn bench_bls12_381_pairing_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_pairing", - generate_bls12_381_pairing_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 MAP_FP_TO_G1 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 `MAP_FP_TO_G1` precompile. -fn generate_bls12_381_map_fp_to_g1_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MAP_FP_TO_G1 input: field element (64 bytes padded) - // Using value 1 with proper padding (16 bytes padding + 48 bytes data) - let mut fp_element = vec![0u8; 64]; - fp_element[63] = 1; // Set to 1 - - // Store field element - builder = builder.mstore(0, &fp_element); - - for _ in 0..iterations { - builder = builder.push_number(128_u64); // retSize (one G1 point) - builder = builder.push_number(64_u64); // retOffset - builder = builder.push_number(64_u64); // argsSize (one field element) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::map_fp_to_g1::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 `MAP_FP_TO_G1` precompile. -fn bench_bls12_381_map_fp_to_g1_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_map_fp_to_g1", - generate_bls12_381_map_fp_to_g1_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// BLS12-381 MAP_FP2_TO_G2 Precompile Benchmark -// ============================================================================ -// - -/// Generate bytecode that calls BLS12-381 `MAP_FP2_TO_G2` precompile. -fn generate_bls12_381_map_fp2_to_g2_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // MAP_FP2_TO_G2 input: Fp2 element (128 bytes padded = 2 * 64 bytes) - // Using a simple valid Fp2 element: (1, 0) with proper padding - // Each component is 64 bytes: 16 bytes padding + 48 bytes data - let mut fp2_element = vec![0u8; 128]; - // Set first component to 1 (at byte 63, the last byte of first 64-byte chunk) - fp2_element[63] = 1; - - // Store Fp2 element - builder = builder.mstore(0, &fp2_element); - - for _ in 0..iterations { - builder = builder.push_number(256_u64); // retSize (one G2 point) - builder = builder.push_number(128_u64); // retOffset - builder = builder.push_number(128_u64); // argsSize (one Fp2 element) - builder = builder.push_number(0_u64); // argsOffset - builder = builder.push_address(*bls12_381::map_fp2_to_g2::PRECOMPILE.address()); - builder = builder.append(GAS); // gas - builder = builder.append(STATICCALL); - // assert call success - builder = builder.assert_stack_value(0, U256::from(1)); - builder = builder.append(POP); - } - - builder.build() -} - -/// Benchmark BLS12-381 `MAP_FP2_TO_G2` precompile. -fn bench_bls12_381_map_fp2_to_g2_precompile(c: &mut Criterion) { - const ITERATIONS: usize = 100; - bench_precompile_group( - c, - "precompile_bls12_381_map_fp2_to_g2", - generate_bls12_381_map_fp2_to_g2_bytecode(ITERATIONS), - ); -} - -// -// ============================================================================ -// Criterion Configuration -// ============================================================================ -// - -criterion_group!( - benches, - bench_add_opcode, - bench_address_opcode, - bench_keccak256_opcode, - bench_exp_opcode, - bench_ecrecover_precompile, - bench_sha256_precompile, - bench_ripemd160_precompile, - bench_modexp_precompile, - bench_ecadd_precompile, - bench_ecmul_precompile, - bench_ecpairing_precompile, - bench_blake2f_precompile, - bench_kzg_point_evaluation_precompile, - bench_bls12_381_g1add_precompile, - bench_bls12_381_g1msm_precompile, - bench_bls12_381_g2add_precompile, - bench_bls12_381_g2msm_precompile, - bench_bls12_381_pairing_precompile, - bench_bls12_381_map_fp_to_g1_precompile, - bench_bls12_381_map_fp2_to_g2_precompile, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/corpus.rs b/crates/mega-evm/benches/corpus.rs new file mode 100644 index 000000000..efccc8300 --- /dev/null +++ b/crates/mega-evm/benches/corpus.rs @@ -0,0 +1,63 @@ +//! A set of JSON scenarios through `MegaEvm`. +//! +//! The inputs are the scenarios under `benches/scenarios` (the `test_utils::Scenario` format), +//! picked to spread over the mechanisms the engine runs. They are bench inputs, not a conformance +//! suite: nothing here compares their outcome with another engine, so an instruction-count change +//! means only that the execution or the pricing of those scenarios moved. Each scenario runs all +//! its transactions, one fresh `MegaEvm` per transaction; building the pre-state is setup and is +//! not measured. +#![allow(missing_docs)] + +use std::path::Path; + +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use mega_evm::test_utils::Scenario; + +/// `(bench id, scenario name)`: the scenario is `benches/scenarios/.json`. +const SLICE: &[(&str, &str)] = &[ + ("sstore_set", "sstore_set_spills"), + ("create", "create_success"), + ("nested_revert", "nested_call_revert_with_spill"), + ("two_txs", "two_txs_sequential"), + ("system_call", "system_call"), + ("calldata_floor", "test_calldata_floor_with_sstore_fork_Amsterdam_state_test"), + ( + "nested_refund_depth_10", + "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + ), + ("eip7702_delegation", "eip7702_delegate_new_authority"), + ("access_list", "access_list_warm_slots_and_account"), + ("selfdestruct", "selfdestruct_created_in_same_tx_to_existing_account"), + ("logs", "logs_all_topic_counts"), + ("ecrecover", "precompile_ecrecover"), + ("modexp", "precompile_modexp"), +]; + +fn load(path: &str) -> Scenario { + let file = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("benches/scenarios") + .join(format!("{path}.json")); + let text = std::fs::read_to_string(&file).unwrap_or_else(|err| panic!("{file:?}: {err}")); + let scenario: Scenario = serde_json::from_str(&text).unwrap(); + scenario.validate().unwrap(); + scenario +} + +fn bench_corpus(c: &mut Criterion) { + let mut group = c.benchmark_group("corpus"); + for (id, path) in SLICE { + let scenario = load(path); + // The measured path must be the scenario's execution, not a rejected transaction. + let (outcomes, _) = scenario.run(scenario.database()); + for (i, outcome) in outcomes.iter().enumerate() { + assert!(outcome.is_ok(), "{path}: tx[{i}] is rejected: {outcome:?}"); + } + group.bench_function(*id, |b| { + b.iter_batched(|| scenario.database(), |db| scenario.run(db), BatchSize::SmallInput); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_corpus); +criterion_main!(benches); diff --git a/crates/mega-evm/benches/ctt.rs b/crates/mega-evm/benches/ctt.rs deleted file mode 100644 index 3bc2ea830..000000000 --- a/crates/mega-evm/benches/ctt.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Benchmarks for the `ConcurrencyTortureTest` batchTransfer operation. -//! -//! This benchmark suite measures the performance of the `batchTransfer` function -//! from the `ConcurrencyTortureTest` (CTT) contract, comparing performance across -//! different EVM specifications (`EQUIVALENCE` vs `MINI_REX`). - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId, MegaTransaction}; -use revm::{context::tx::TxEnvBuilder, primitives::KECCAK_EMPTY, ExecuteCommitEvm, ExecuteEvm}; - -const DEPLOYER: Address = address!("0000000000000000000000000000000000100000"); -const CALLER: Address = address!("0000000000000000000000000000000000100001"); - -/// CTT deployment bytecode. Compiled at commit 0bcd874ab95f1300d1796888cd2ce087e1773b55 of -/// git@github.com:megaeth-labs/concurrency-torture-test.git -const CTT_DEPLOY_CODE: Bytes = bytes!("0x6101406040523461033557604051601f611f4b38819003918201601f19168301916001600160401b038311848410176102165780849260809460405283398101031261033557805190602081015191606060408301519201516001831180610328575b156102ce5760648211610275578260805260a05260c052801561026157808083049206820180831161024d57610096610339565b9081525f808052602052517fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb55560015b81811061022a5760405161077d8082016001600160401b03811183821017610216578291611365833903905ff0801561020b576001600160a01b031660e0526040516101008082016001600160401b03811183821017610216578291611ae2833903905ff0801561020b576001600160a01b0316610100526040516103698082016001600160401b03811183821017610216578291611be2833903905ff0801561020b576001600160a01b03166101205260405161100c908161035982396080518181816102f90152818161081e015281816108d60152610bb1015260a051818181610369015281816108fc01528181610e3f0152610ebf015260c0518181816102bf0152818161089c0152610b88015260e05181818161016c01526109340152610100518181816103a10152610570015261012051818181610279015261069f0152f35b6040513d5f823e3d90fd5b634e487b7160e01b5f52604160045260245ffd5b600190610235610339565b848152815f525f60205260405f2090519055016100c6565b634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f52601260045260245ffd5b60405162461bcd60e51b815260206004820152602b60248201527f4354543a20626c6f636b496e666f5265616450657263656e74616765206d757360448201526a074206265203c3d203130360ac1b6064820152608490fd5b60405162461bcd60e51b815260206004820152602c60248201527f4354543a2063656c6c436f756e74206d757374206265206265747765656e203260448201526b020616e64203130302c3030360a41b6064820152608490fd5b50620186a0831115610062565b5f80fd5b60405190602082016001600160401b038111838210176102165760405256fe60806040526004361015610011575f80fd5b5f3560e01c806305d48b21146101145780630d3eadda1461010f5780631941fd141461010a5780635a5173b314610105578063660844f01461010057806374eee84c146100fb5780637b49b4ae146100f657806382106275146100f157806396e17e4d146100ec5780639f366f67146100e7578063a8ae91cd146100e2578063b1444901146100dd578063c77e41dd146100d8578063dd70c8ec146100d3578063fd433182146100ce5763fd65f099146100c9575f80fd5b610429565b61040c565b6103f2565b6103d0565b61038c565b610352565b61031c565b6102e2565b6102a8565b610264565b61021f565b6101e0565b6101c4565b61019b565b610157565b61013b565b60809060031901126101375760043590602435906044359060643590565b5f80fd5b346101375761015561014c36610119565b9291909161051e565b005b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137576020366003190112610137576004355f525f602052602060405f2054604051908152f35b34610137575f3660031901126101375760206040516127108152f35b346101375760206101fc6101f336610119565b929190916105d6565b6040516001600160a01b039091168152f35b6001600160a01b0381160361013757565b346101375760203660031901126101375760043561023c8161020e565b60018060a01b03165f526001602052602067ffffffffffffffff60405f205416604051908152f35b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346101375760a0366003190112610137576004356004811015610137576101fc602091602435604435606435916084359361072f565b34610137575f3660031901126101375760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610137575f366003190112610137576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610137575f3660031901126101375760206103ea610812565b604051908152f35b346101375761015561040336610119565b92919091610870565b34610137575f366003190112610137576020600254604051908152f35b346101375761015561043a36610119565b92919091610ad9565b1561044a57565b60405162461bcd60e51b815260206004820152602c60248201527f4354543a206e756d53656e6465727320616e64206e756d52656365697665727360448201526b0206d757374206265203e20360a41b6064820152608490fd5b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff8211176104da57604052565b6104a4565b3d15610519573d9067ffffffffffffffff82116104da576040519161050e601f8201601f1916602001846104b8565b82523d5f602084013e565b606090565b905f938493831515806105aa575b61053590610443565b604051926020840194630d02bd9760e31b865260248501526044840152606483015260848201526084815261056b60a4826104b8565b5190827f00000000000000000000000000000000000000000000000000000000000000005af16105996104df565b90156105a25750565b602081519101fd5b5082151561052c565b9081602091031261013757516105c88161020e565b90565b6040513d5f823e3d90fd5b90929161069a60209383151580610708575b6105f190610443565b325f908152600160205260409020610653908290610618905b5467ffffffffffffffff1690565b6040519061064e826106408b8201600d906c10d4915055114c97d0d2125311609a1b81520190565b03601f1981018452836104b8565b610eaa565b60405163318600cf60e01b8152600481019190915230602482015260448101949094526064840195909552608483019190915260a4820193909352918290819060c4820190565b03815f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1908115610703575f916106da575090565b6105c8915060203d6020116106fc575b6106f481836104b8565b8101906105b3565b503d6106ea565b6105cb565b508515156105e8565b6004111561071b57565b634e487b7160e01b5f52602160045260245ffd5b939291909361073d81610711565b80610750575061074c93610ad9565b5f90565b61075981610711565b6001810361076b575061074c93610870565b61077481610711565b60028103610786575061074c9361051e565b80610792600392610711565b036107a0576105c8936105d6565b60405162461bcd60e51b81526020600482015260166024820152754354543a20496e76616c69642063616c6c207479706560501b6044820152606490fd5b634e487b7160e01b5f52601160045260245ffd5b600101908160011161080057565b6107de565b9190820180921161080057565b5f9060025461086a575f7f00000000000000000000000000000000000000000000000000000000000000005b808210610849575050565b9092835f525f60205260405f2054810180911161080057926001019061083e565b5f199150565b905f9384938315158061095d575b61088790610443565b6040519260208401946317f613d160e31b86527f0000000000000000000000000000000000000000000000000000000000000000602486015260448501526064840152608483015260a48201527f000000000000000000000000000000000000000000000000000000000000000060c48201527f000000000000000000000000000000000000000000000000000000000000000060e482015260e48152610930610104826104b8565b51907f00000000000000000000000000000000000000000000000000000000000000005af46105996104df565b5082151561087e565b1561096d57565b60405162461bcd60e51b815260206004820152602660248201527f4354543a20726561644f6e6c7950657263656e74616765206d7573742062652060448201526503c3d203130360d41b6064820152608490fd5b67ffffffffffffffff60019116019067ffffffffffffffff821161080057565b81156109eb570690565b634e487b7160e01b5f52601260045260245ffd5b15610a0657565b60405162461bcd60e51b815260206004820152602860248201527f4354543a20696e73756666696369656e742062616c616e636520696e2073656e60448201526719195c8818d95b1b60c21b6064820152608490fd5b15610a6357565b60405162461bcd60e51b815260206004820152602d60248201527f4354543a207472616e7366657220776f756c64206f766572666c6f772072656360448201526c65697665722062616c616e636560981b6064820152608490fd5b9190820391821161080057565b5f1981146108005760010190565b9081151580610e20575b610aec90610443565b610af96064841115610966565b325f908152600160205260409020610b1990610b149061060a565b6109c1565b325f908152600160205260409020805467ffffffffffffffff191667ffffffffffffffff83161790555f935f95610b82604051610b7c81610b6e60208201600a9069424c4f434b5f494e464f60b01b81520190565b03601f1981018352826104b8565b84610e29565b606481067f000000000000000000000000000000000000000000000000000000000000000011610df7575b505f7f00000000000000000000000000000000000000000000000000000000000000009083151593612711915b888110610c0f57505050505050505050610bf390610f63565b03610bfa57565b610c0d610c08600254610acb565b600255565b565b868b8487610c3e88610c3983604051610c3381610b6e8c6020830160209181520190565b88610eaa565b6109e1565b92868b610c52865f525f60205260405f2090565b54968791610dac575b505050610c869291610b6e610c80610c39936040519283916020830160209181520190565b8d610eaa565b5f5b8b8110610c9d57505050506001905b01610bda565b808b610cd18a610c398d600196610ccb8c610b6e604051938492602084019091604092825260208201520190565b85610eaa565b808614610da55780610d4186610d3b81610d137f77a84327eb5534e95fa55d5a8a7ccc7e19c6cee0e9777fd78e8dda84b2275fac965f525f60205260405f2090565b549b610d21828210156109ff565b610d368d610d2f8482610805565b1015610a5c565b610abe565b99610805565b9088610d54895f525f60205260405f2090565b5581610d67825f525f60205260405f2090565b556040805167ffffffffffffffff95909516855260208501889052840188905260608401899052608084015260a0830152329160c090a25b01610c88565b5050610d9f565b84610ddd92610dd69261064e8c610640604051948592602084019091604092825260208201520190565b6064900690565b10610dea5786858d610c5b565b5050505050600190610c97565b610e0a919750610e0f9296506009900690565b6107f2565b93610e1985610f63565b955f610bad565b50801515610ae3565b6020610e9f605c600194604051938491818301967f000000000000000000000000000000000000000000000000000000000000000088523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f1981018352826104b8565b519020906105c85790565b90610f1f605c602092604051938491818301967f000000000000000000000000000000000000000000000000000000000000000088523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f1981018352826104b8565b519020905f905b808210610f3257505090565b9091600190604051610f5881610b6e876020830195869091604092825260208201520190565b519020920190610f26565b60018103610f7057504890565b60028103610f7d57504a90565b60038103610f8a57504690565b60048103610f9757504190565b60058103610fa457504490565b60068103610fb157504590565b60078103610fbe57504390565b60088103610fcb57504490565b60090361074c57429056fea26469706673582212205cf443ae3ff796f483da8f3136046f6f42b4741de464846b1af03f977336b13864736f6c634300081e003360808060405234601557610763908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c63bfb09e8814610024575f80fd5b346103385760e03660031901126103385760043560843560243560443560a43560643560c4358415158061032f575b61005c9061033c565b6100686001841161039d565b61007560648311156103e9565b610087325f52600160205260405f2090565b926100a261009d855467ffffffffffffffff1690565b610458565b8094555f965f986100e66040516100df816100d160208201600a9069424c4f434b5f494e464f60b01b81520190565b03601f19810183528261047d565b87866105b8565b906064820610610306575b506127115f5b88811061011a578a6101088b6106b6565b0361010f57005b600280546001019055005b610197858c84868b6101508a61014b846100d16101448c6040519283916020830160209181520190565b858a61061d565b6104b3565b938c6101a361019c858b8661016c8b5f525f60205260405f2090565b805460408051602081019590955284018190529d909c9083606081015b03601f19810185528461047d565b61061d565b6064900690565b106102f757916101cb61014b926101d96101df96956040519384916020830160209181520190565b03601f19810184528361047d565b8d61061d565b8b8b89898c5f945b8510610200575050505050505050506001905b016100f7565b61022c9291858561014b936101978e610189604051958692602084019091604092825260208201520190565b8085146102ed57907f77a84327eb5534e95fa55d5a8a7ccc7e19c6cee0e9777fd78e8dda84b2275fac61029897836102a38761029d8161027660019a995f525f60205260405f2090565b9586549e8f610287848410156104ec565b61029184826104df565b1015610549565b6105ab565b9b6104df565b8a8a55918290556040805167ffffffffffffffff959095168552602085018890528401889052606084018a9052608084015260a0830152329160c090a25b018b89898f8d906101e7565b50506001906102e1565b505050505050506001906101fa565b61031991995061031e9298506009900690565b6104d1565b95610328876106b6565b975f6100f1565b50831515610053565b5f80fd5b1561034357565b60405162461bcd60e51b815260206004820152602c60248201527f4354543a206e756d53656e6465727320616e64206e756d52656365697665727360448201526b0206d757374206265203e20360a41b6064820152608490fd5b156103a457565b60405162461bcd60e51b815260206004820152601960248201527f4354543a206e756d43656c6c73206d757374206265203e2031000000000000006044820152606490fd5b156103f057565b60405162461bcd60e51b815260206004820152602660248201527f4354543a20726561644f6e6c7950657263656e74616765206d7573742062652060448201526503c3d203130360d41b6064820152608490fd5b634e487b7160e01b5f52601160045260245ffd5b67ffffffffffffffff60019116019067ffffffffffffffff821161047857565b610444565b90601f8019910116810190811067ffffffffffffffff82111761049f57604052565b634e487b7160e01b5f52604160045260245ffd5b81156104bd570690565b634e487b7160e01b5f52601260045260245ffd5b600101908160011161047857565b9190820180921161047857565b156104f357565b60405162461bcd60e51b815260206004820152602860248201527f4354543a20696e73756666696369656e742062616c616e636520696e2073656e60448201526719195c8818d95b1b60c21b6064820152608490fd5b1561055057565b60405162461bcd60e51b815260206004820152602d60248201527f4354543a207472616e7366657220776f756c64206f766572666c6f772072656360448201526c65697665722062616c616e636560981b6064820152608490fd5b9190820391821161047857565b909161060f605c60019460206040519485928284019788523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f19810183528261047d565b5190209061061a5790565b90565b9190605c6106729160206040519485928284019788523260601b604085015267ffffffffffffffff60c01b9060c01b1660548401528051918291018484015e81015f838201520301601f19810183528261047d565b519020905f905b80821061068557505090565b90916001906040516106ab816100d1876020830195869091604092825260208201520190565b519020920190610679565b600181036106c357504890565b600281036106d057504a90565b600381036106dd57504690565b600481036106ea57504190565b600581036106f757504490565b6006810361070457504590565b6007810361071157504390565b6008810361071e57504490565b600903610729574290565b5f9056fea2646970667358221220a4bcc3777bb41dc90dbc866c57aa4c6ea571d71031195916664ccb5fd8163e4764736f6c634300081e00336080806040523460145760e790816100198239f35b5f80fdfe60808060405260043610156011575f80fd5b5f905f3560e01c636815ecb8146025575f80fd5b3460ad57608036600319011260ad57333b1560ad5763fd65f09960e01b815260043560048201526024356024820152604435604482015260643560648201525f8160848183335af1801560a2576079575080f35b905067ffffffffffffffff8111608e57604052005b634e487b7160e01b5f52604160045260245ffd5b6040513d5f823e3d90fd5b5f80fdfea2646970667358221220f175208873a77bf072379c6ff131eeaae1326bd45c2f48995824ed2c602ed5a664736f6c634300081e00336080806040523460155761034f908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c63318600cf14610024575f80fd5b346100895760c0366003190112610089576024356001600160a01b03811681036100895761006b6100859161005860443590565b6064356084359160a43593600435610121565b6040516001600160a01b0390911681529081906020820190565b0390f35b5f80fd5b90601f8019910116810190811067ffffffffffffffff8211176100af57604052565b634e487b7160e01b5f52604160045260245ffd5b805191908290602001825e015f815290565b156100dc57565b60405162461bcd60e51b815260206004820152601e60248201527f4354543a2043524541544532206465706c6f796d656e74206661696c656400006044820152606490fd5b946101a79294610199946101229660405197610140602082018a61008d565b8089526101f860208a01396040519460018060a01b0316602086015260408501526060840152608083015260a082015260a0815261017f60c08261008d565b6040519283916101936020840180976100c3565b906100c3565b03601f19810183528261008d565b51905ff5906101c06001600160a01b03831615156100d5565b6040516001600160a01b03831681527f916f35ba24f3be9802a8b5ffca961b5cd764d08fcfd24c270bc1c58b948e886290602090a156fe60808060405260a08161012280380380916018828560b2565b83398101031260ae5780516001600160a01b0381169081900360ae576020820151906040830151906080606085015194015192813b1560ae575f6084928195604051978896879563fd65f09960e01b875260048701526024860152604485015260648401525af1801560a3576096575b604051603990816100e98239f35b5f609e9160b2565b5f6088565b6040513d5f823e3d90fd5b5f80fd5b601f909101601f19168101906001600160401b0382119082101760d457604052565b634e487b7160e01b5f52604160045260245ffdfe5f80fdfea2646970667358221220c1b785695bcc466bc621dad0960a0d161ccc9db357b5516454f683de2fc4397264736f6c634300081e0033a26469706673582212200de4490c305b2997f987b3670cef90af77fd7a480fffe15b04ab7ea8bda349b964736f6c634300081e0033"); -const TOTAL_SUPPLY: u64 = 1_000_000_000; -const CELL_COUNT: u64 = 100; -const BLOCK_INFO_READ_PERCENTAGE: u64 = 20; -const SEED: [u8; 32] = *b"test-seed-for-ctt-benchmarking!!"; - -/// Deploy CTT contract and return the deployed address and post-deployment database -fn deploy_ctt(spec: MegaSpecId) -> (Address, MemoryDatabase) { - let creation_code = CTT_DEPLOY_CODE; - - // Encode constructor parameters: (blockInfoReadPercentage, totalSupply, cellCount, seed) - let mut constructor_args = Vec::new(); - constructor_args.extend_from_slice(&U256::from(BLOCK_INFO_READ_PERCENTAGE).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&U256::from(TOTAL_SUPPLY).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&U256::from(CELL_COUNT).to_be_bytes::<32>()); - constructor_args.extend_from_slice(&SEED); - - let mut deploy_data = creation_code.to_vec(); - deploy_data.extend_from_slice(&constructor_args); - - // Set up database with deployer and caller balances - let mut db = MemoryDatabase::default() - .account_balance(DEPLOYER, U256::from(10).pow(U256::from(18))) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - - let mut context = MegaContext::new(&mut db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - // Deploy contract (CREATE transaction with no 'to' address) - let tx = TxEnvBuilder::new() - .gas_limit(1_000_000_000) - .caller(DEPLOYER) - .create() - .data(Bytes::from(deploy_data)) - .build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.transact_commit(mega_tx).expect("deployment should succeed"); - assert!(result.is_success(), "CTT deployment failed"); - - // Calculate the deployed contract address: keccak256(rlp([sender, nonce]))[12:] - // For the first transaction from DEPLOYER, nonce is 0 - let deployed_address = DEPLOYER.create(0); - - // check if the deployment is successful - let deployed_info = &db.load_account(deployed_address).unwrap().info; - deployed_info.code.as_ref().expect("code should be present"); - assert_ne!(deployed_info.code_hash, KECCAK_EMPTY); - - (deployed_address, db) -} - -/// Encode a call to batchTransfer(uint256,uint256,uint256,uint256) -/// Function selector: 0xfd65f099 -fn encode_batch_transfer_call( - num_senders: u64, - num_receivers: u64, - read_only_percentage: u64, - complexity: u64, -) -> Bytes { - let mut calldata = Vec::with_capacity(4 + 32 * 4); - - // Function selector: batchTransfer(uint256,uint256,uint256,uint256) - calldata.extend_from_slice(&[0xfd, 0x65, 0xf0, 0x99]); - - // Encode parameters (all uint256) - calldata.extend_from_slice(&U256::from(num_senders).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(num_receivers).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(read_only_percentage).to_be_bytes::<32>()); - calldata.extend_from_slice(&U256::from(complexity).to_be_bytes::<32>()); - - Bytes::from(calldata) -} - -/// Helper function to execute a single benchmark iteration -fn execute_batch_transfer( - spec: MegaSpecId, - db: MemoryDatabase, - contract_addr: Address, - calldata: &Bytes, -) { - let mut context = MegaContext::new(black_box(db), black_box(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(contract_addr).data(calldata.clone()).build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - - let result = evm.transact(mega_tx).expect("transaction should succeed"); - assert!(result.result.is_success()); - black_box(result); -} - -/// Benchmark batchTransfer with different contention patterns -fn bench_ctt_batch_transfer(c: &mut Criterion) { - // Deploy CTT once per spec to get the initial state - let (ctt_addr_eq, initial_db_eq) = deploy_ctt(MegaSpecId::EQUIVALENCE); - let (ctt_addr_mr, initial_db_mr) = deploy_ctt(MegaSpecId::MINI_REX); - - // Test cases: (name, numSenders, numReceivers, complexity) - let test_cases = [ - ("low_contention_1x1", 1, 1, 0), - ("medium_contention_5x5", 5, 5, 0), - ("high_contention_10x10", 10, 10, 0), - ("little_complexity_1x1", 1, 1, 5), - ("medium_complexity_1x1", 1, 1, 50), - ("high_complexity_1x1", 1, 1, 100), - ("some_complexity_5x5", 5, 5, 25), - ]; - - for (test_name, num_senders, num_receivers, complexity) in test_cases { - let mut group = c.benchmark_group(format!("batch_transfer_{}", test_name)); - let calldata = encode_batch_transfer_call(num_senders, num_receivers, 0, complexity); - - group.bench_function("equivalence", |b| { - b.iter(|| { - execute_batch_transfer( - MegaSpecId::EQUIVALENCE, - initial_db_eq.clone(), - ctt_addr_eq, - &calldata, - ) - }) - }); - - group.bench_function("mini_rex", |b| { - b.iter(|| { - execute_batch_transfer( - MegaSpecId::MINI_REX, - initial_db_mr.clone(), - ctt_addr_mr, - &calldata, - ) - }) - }); - - group.finish(); - } -} - -criterion_group!(benches, bench_ctt_batch_transfer); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/enriched_tx.rs b/crates/mega-evm/benches/enriched_tx.rs deleted file mode 100644 index 65eb8954c..000000000 --- a/crates/mega-evm/benches/enriched_tx.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Benchmarks the cost of `MegaTransactionExt::{tx_size, estimated_da_size}` recompute vs the -//! `EnrichedMegaTx` cached fields. -//! -//! `EnrichedMegaTx` exists to precompute `tx_size`/`da_size` once (e.g. via `new_slow` from a -//! mempool-cached value) so block-execution callers can reuse them instead of recomputing on -//! every access. Three rows: -//! - `recompute_via_tx_unwrap` mirrors the `alloy_evm` block-execution path's call pattern -//! (`tx.tx().estimated_da_size()` / `tx.tx().tx_size()`), which unwraps `EnrichedMegaTx` down to -//! the raw inner transaction and always hits the recomputing default impl. -//! - `via_trait_dispatch` mirrors `MegaBlockExecutor::run_transaction`'s call pattern -//! (`tx.estimated_da_size()` / `tx.tx_size()` on the outer wrapper), which dispatches to the -//! stored fields for an `EnrichedMegaTx`. -//! - `cached_fields` reads the wrapper's precomputed fields directly, the floor -//! `via_trait_dispatch` should match. - -#![allow(missing_docs)] - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_evm::RecoveredTx; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, U256}; -use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; -use mega_evm::{EnrichedMegaTx, MegaTransactionExt, MegaTxEnvelope}; - -const CALLER: Address = address!("2000000000000000000000000000000000000001"); -const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - -/// Calldata sizes spanning a plain transfer up to a large multicall-style payload. -const CALLDATA_SIZES: &[usize] = &[0, 68, 180, 1000]; - -fn enriched_tx(calldata_len: usize) -> EnrichedMegaTx> { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from(vec![0xabu8; calldata_len]), - }; - let envelope = MegaTxEnvelope::Legacy(Signed::new_unchecked( - tx, - Signature::test_signature(), - Default::default(), - )); - let recovered = Recovered::new_unchecked(envelope, CALLER); - EnrichedMegaTx::new_slow(recovered) -} - -/// The `alloy_evm` block-execution path's pattern: `tx.tx().()` unwraps `EnrichedMegaTx` -/// down to the raw inner transaction, so `tx_size`/`estimated_da_size` always hit the recomputing -/// default impl even when the wrapper carries precomputed fields. -fn bench_recompute_via_tx_unwrap(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/recompute_via_tx_unwrap"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx.tx()).estimated_da_size()) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx.tx()).tx_size()) - }); - } - group.finish(); -} - -/// `MegaBlockExecutor::run_transaction`'s call pattern: `tx.()` called directly on the -/// outer `EnrichedMegaTx`, dispatching to the stored fields via `MegaTransactionExt`. -fn bench_via_trait_dispatch(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/via_trait_dispatch"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).estimated_da_size()) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).tx_size()) - }); - } - group.finish(); -} - -/// Reading `EnrichedMegaTx`'s precomputed fields directly. -fn bench_cached_fields(c: &mut Criterion) { - let mut group = c.benchmark_group("tx_size_da_size/cached_fields"); - for &len in CALLDATA_SIZES { - let tx = enriched_tx(len); - group.bench_with_input(BenchmarkId::new("estimated_da_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).da_size) - }); - group.bench_with_input(BenchmarkId::new("tx_size", len), &tx, |b, tx| { - b.iter(|| black_box(tx).tx_size) - }); - } - group.finish(); -} - -criterion_group!( - benches, - bench_recompute_via_tx_unwrap, - bench_via_trait_dispatch, - bench_cached_fields -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/factory.rs b/crates/mega-evm/benches/factory.rs new file mode 100644 index 000000000..4d7832237 --- /dev/null +++ b/crates/mega-evm/benches/factory.rs @@ -0,0 +1,41 @@ +//! Construction of a `MegaEvm` through `MegaEvmFactory`, as a node's block executor makes one +//! per block. +//! +//! `create_evm` builds the context and applies the configuration the spec fixes; the EVM is +//! dropped inside the measurement, so its teardown counts too. +#![allow(missing_docs)] + +use alloy_evm::{EvmEnv, EvmFactory}; +use criterion::{criterion_group, criterion_main, Criterion}; +use mega_evm::{MegaEvmFactory, MegaSpecId}; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::EmptyDB, + inspector::NoOpInspector, +}; +use std::hint::black_box; + +fn evm_env() -> EvmEnv { + EvmEnv { cfg_env: CfgEnv::new_with_spec(MegaSpecId::SATIN), block_env: BlockEnv::default() } +} + +fn bench_factory(c: &mut Criterion) { + let factory = MegaEvmFactory::new(); + let mut group = c.benchmark_group("factory"); + group.bench_function("create_evm", |b| { + b.iter(|| drop(black_box(factory.create_evm(EmptyDB::default(), black_box(evm_env()))))); + }); + group.bench_function("create_evm_with_inspector", |b| { + b.iter(|| { + drop(black_box(factory.create_evm_with_inspector( + EmptyDB::default(), + black_box(evm_env()), + NoOpInspector, + ))) + }); + }); + group.finish(); +} + +criterion_group!(benches, bench_factory); +criterion_main!(benches); diff --git a/crates/mega-evm/benches/mega_bench.rs b/crates/mega-evm/benches/mega_bench.rs deleted file mode 100644 index a29a3b282..000000000 --- a/crates/mega-evm/benches/mega_bench.rs +++ /dev/null @@ -1,971 +0,0 @@ -//! Benchmarks for mega-evm specific features. -//! -//! These benchmarks exercise code paths unique to mega-evm: -//! - **`volatile_data`**: Gas detention from block env opcodes (COINBASE, TIMESTAMP, etc.) -//! - **`gas_detention_computation`**: Impact of gas detention on subsequent heavy computation -//! - **`log_opcodes`**: LOG0-LOG4 with dual gas model (compute + storage gas) -//! - **`sstore_heavy`**: SSTORE-intensive workloads triggering resource limit tracking -//! - **`system_contract_single` / `system_contract_100x`**: System contract call interception -//! overhead -//! - **`delegatecall_system_contract`**: DELEGATECALL vs CALL to system contracts -//! - **`oracle_sload`**: Oracle forced-cold SLOAD vs regular SLOAD -//! - **`create_deploy`**: CREATE/CREATE2 contract deployment with resource tracking -//! - **`selfdestruct`**: SELFDESTRUCT behavior across specs -//! - **`call_value_empty_account`**: CALL with value to empty accounts (dynamic gas) -//! - **`mixed_workload`**: Realistic combined workload -//! - **`eip7702_authlist`**: REX5 pre-execution authority-list scan scaling with list size -//! - **`staticcall_selfdestruct`**: SELFDESTRUCT inside a STATICCALL frame vs a STOP control - -#![allow(missing_docs)] - -use alloy_eips::eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}; -use alloy_primitives::{address, Address, Bytes, U256}; -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use mega_evm::{ - revm::inspector::NoOpInspector, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EmptyExternalEnv, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{ - ADD, CALL, COINBASE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, LOG1, LOG2, LOG4, NUMBER, - POP, PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STATICCALL, STOP, TIMESTAMP, - }, - context::tx::TxEnvBuilder, - ExecuteEvm as _, -}; - -mod common; -use common::{ - register_all, register_all_suffixed, register_mega_specs, register_mega_specs_suffixed, - register_mega_suffixed, Account, TxSpec, Workload, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const SECONDARY: Address = address!("0000000000000000000000000000000000100003"); - -/// Gas limit shared by every mega-feature workload — high enough that the -/// bench never halts on the EVM gas limit, leaving mega's own resource limits -/// as the only relevant ceiling. -const FEATURE_GAS_LIMIT: u64 = 10_000_000_000; - -/// A funded `CALLER` calling a contract at `CONTRACT` holding `code`, under the -/// shared feature gas limit with empty calldata. Covers most mega benches; the -/// few with extra accounts or a different target build their `Workload` inline. -fn mega_contract_workload(code: Bytes) -> Workload { - Workload::single( - vec![ - Account::new(CONTRACT).code(code), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) -} - -// -// ============================================================================ -// Volatile Data Access Benchmarks -// ============================================================================ -// - -const VOLATILE_ITERATIONS: usize = 100; - -fn generate_baseline_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() -} - -fn generate_coinbase_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(COINBASE).append(POP); - } - builder.build() -} - -fn generate_timestamp_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(TIMESTAMP).append(POP); - } - builder.build() -} - -fn generate_number_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.append(NUMBER).append(POP); - } - builder.build() -} - -fn bench_volatile_data(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("baseline_add", generate_baseline_bytecode(VOLATILE_ITERATIONS)), - ("coinbase", generate_coinbase_bytecode(VOLATILE_ITERATIONS)), - ("timestamp", generate_timestamp_bytecode(VOLATILE_ITERATIONS)), - ("number", generate_number_bytecode(VOLATILE_ITERATIONS)), - ]; - - let mut group = c.benchmark_group("volatile_data"); - for (variant, bytecode) in variants { - register_mega_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// Gas Detention + Computation Benchmark -// ============================================================================ -// -// Measures the impact of gas detention on subsequent heavy computation. -// After accessing volatile data, every subsequent opcode must check the -// detained compute gas limit. This benchmark isolates that overhead. -// - -fn bench_gas_detention_computation(c: &mut Criterion) { - // Heavy computation only (500 ADD ops) — no volatile access - let computation_only = { - let mut builder = BytecodeBuilder::default(); - for _ in 0..500 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() - }; - - // Volatile access THEN heavy computation (COINBASE + 500 ADD ops) - // Every ADD after COINBASE must check the detained gas cap. - let volatile_then_compute = { - let mut builder = BytecodeBuilder::default(); - builder = builder.append(COINBASE).append(POP); - for _ in 0..500 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() - }; - - let mut group = c.benchmark_group("gas_detention_computation"); - register_mega_suffixed( - &mut group, - "compute_only_500", - &mega_contract_workload(computation_only), - ); - register_mega_suffixed( - &mut group, - "volatile_then_compute_500", - &mega_contract_workload(volatile_then_compute), - ); - group.finish(); -} - -// -// ============================================================================ -// LOG Opcode Benchmarks -// ============================================================================ -// - -const LOG_ITERATIONS: usize = 50; - -fn generate_log0_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder.push_number(data_size as u64).push_number(0u64).append(LOG0); - } - builder.build() -} - -fn generate_log2_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0xdead_beef_u64) - .push_number(0xcafe_babe_u64) - .push_number(data_size as u64) - .push_number(0u64) - .append(LOG2); - } - builder.build() -} - -fn generate_log4_bytecode(iterations: usize, data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0x1111_u64) - .push_number(0x2222_u64) - .push_number(0x3333_u64) - .push_number(0x4444_u64) - .push_number(data_size as u64) - .push_number(0u64) - .append(LOG4); - } - builder.build() -} - -fn bench_log_opcodes(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("log0_32b", generate_log0_bytecode(LOG_ITERATIONS, 32)), - ("log0_256b", generate_log0_bytecode(LOG_ITERATIONS, 256)), - ("log2_32b", generate_log2_bytecode(LOG_ITERATIONS, 32)), - ("log4_32b", generate_log4_bytecode(LOG_ITERATIONS, 32)), - ("log4_256b", generate_log4_bytecode(LOG_ITERATIONS, 256)), - ]; - - let mut group = c.benchmark_group("log_opcodes"); - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// SSTORE Heavy Benchmarks -// ============================================================================ -// - -const SSTORE_ITERATIONS: usize = 100; - -fn generate_sstore_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder.push_number(i as u64 + 1).push_number(i as u64).append(SSTORE); - } - builder.build() -} - -fn generate_sload_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder.push_number(i as u64).append(SLOAD).append(POP); - } - builder.build() -} - -fn generate_sstore_sload_bytecode(iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for i in 0..iterations { - builder = builder - .push_number(i as u64 + 1) - .push_number(i as u64) - .append(SSTORE) - .push_number(i as u64) - .append(SLOAD) - .append(POP); - } - builder.build() -} - -fn bench_sstore(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = &[ - ("sstore_100", generate_sstore_bytecode(SSTORE_ITERATIONS)), - ("sload_100", generate_sload_bytecode(SSTORE_ITERATIONS)), - ("sstore_sload_100", generate_sstore_sload_bytecode(SSTORE_ITERATIONS)), - ]; - - let mut group = c.benchmark_group("sstore_heavy"); - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// CREATE / CREATE2 Contract Deployment Benchmarks -// ============================================================================ -// -// Exercises: -// - forward_gas_ext (98/100 gas forwarding rule) -// - storage_gas_ext (SALT dynamic gas for new account/contract) -// - State growth tracking -// - Data size tracking (deployed code size) -// - -/// Build bytecode that deploys a minimal contract via CREATE. -/// The init code stores a small runtime bytecode and returns it. -fn make_create_bytecode(n_deploys: usize) -> Bytes { - // Init code that deploys an empty contract: PUSH1 0x00 PUSH1 0x00 RETURN. - let init_code: [u8; 5] = [0x60, 0x00, 0x60, 0x00, 0xf3]; - - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, init_code); - - for _ in 0..n_deploys { - builder = builder - .push_number(5u64) // size of init code - .push_number(0u64) // memory offset - .push_number(0u64) // value - .append(CREATE) - .append(POP); // discard deployed address - } - builder.build() -} - -/// Build bytecode that deploys a minimal contract via CREATE2 with varying salts. -fn make_create2_bytecode(n_deploys: usize) -> Bytes { - let init_code: [u8; 5] = [0x60, 0x00, 0x60, 0x00, 0xf3]; - - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, init_code); - - for i in 0..n_deploys { - builder = builder - .push_number(i as u64) // salt (different each time) - .push_number(5u64) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(POP); - } - builder.build() -} - -fn bench_create_deploy(c: &mut Criterion) { - let variants: &[(&str, Bytes)] = - &[("create_10", make_create_bytecode(10)), ("create2_10", make_create2_bytecode(10))]; - - let mut group = c.benchmark_group("create_deploy"); - group.sample_size(10); - - for (variant, bytecode) in variants { - register_all_suffixed(&mut group, variant, &mega_contract_workload(bytecode.clone())); - } - group.finish(); -} - -// -// ============================================================================ -// SELFDESTRUCT Benchmark -// ============================================================================ -// -// SELFDESTRUCT behavior varies by spec: -// - EQUIVALENCE: Standard EIP-6780 behavior -// - MINI_REX ~ REX1: Disabled (halts execution) -// - REX2+: Re-enabled with EIP-6780 semantics -// - REX4+: Also marks beneficiary balance access for gas detention -// - -fn bench_selfdestruct(c: &mut Criterion) { - // SELFDESTRUCT(target) — send remaining balance to target - let selfdestruct_code: Bytes = vec![PUSH0, SELFDESTRUCT].into(); - - // Specs where SELFDESTRUCT is allowed - let selfdestruct_specs: &[(&str, MegaSpecId)] = &[ - ("equivalence", MegaSpecId::EQUIVALENCE), - ("rex2", MegaSpecId::REX2), - ("rex4", MegaSpecId::REX4), - ("rex5", MegaSpecId::REX5), - ]; - - let mut group = c.benchmark_group("selfdestruct"); - // A subject rebuilds the DB from the workload each iteration (SELFDESTRUCT - // modifies state), and `allow_halt` covers the specs where it is disabled. - let workload = mega_contract_workload(selfdestruct_code).allow_halt(); - register_mega_specs(&mut group, selfdestruct_specs, &workload); - group.finish(); -} - -// -// ============================================================================ -// CALL with Value to Empty Account Benchmark -// ============================================================================ -// -// When CALL transfers value to an empty (non-existent) account, mega-evm -// charges dynamic account creation gas via SALT bucket pricing. -// This benchmark compares: -// - CALL with value to existing account (no creation cost) -// - CALL with value to empty account (triggers account creation gas) -// - -fn bench_call_value_empty_account(c: &mut Criterion) { - let existing_target: Address = address!("cccccccccccccccccccccccccccccccccccccccc"); - let empty_target: Address = address!("dddddddddddddddddddddddddddddddddddddddd"); - - // Build bytecode: CALL(gas, target, value=1wei, argsOff=0, argsLen=0, retOff=0, retLen=0) - let make_call_with_value = |target: Address, n: usize| -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..n { - builder = builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value = 1 wei - .push_address(target) - .append(GAS) - .append(CALL) - .append(POP); - } - builder.build() - }; - - let call_existing = make_call_with_value(existing_target, 50); - let call_empty = make_call_with_value(empty_target, 50); - - let mut group = c.benchmark_group("call_value_empty_account"); - - // Variant: existing target has a balance; CALL hits an existing account. - let existing = Workload::single( - vec![ - Account::new(CONTRACT).code(call_existing), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - Account::new(existing_target).balance(U256::from(1)), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ); - register_all_suffixed(&mut group, "existing_account_50", &existing); - - // Variant: empty target — CALL with value triggers account creation gas. - register_all_suffixed(&mut group, "empty_account_50", &mega_contract_workload(call_empty)); - - group.finish(); -} - -// -// ============================================================================ -// System Contract Interception Benchmarks -// ============================================================================ -// - -/// Oracle contract address. -const ORACLE_ADDRESS: Address = address!("6342000000000000000000000000000000000001"); - -fn make_staticcall_bytecode(target: Address, selector: [u8; 4]) -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, selector); - builder = builder - .push_number(32u64) - .push_number(32u64) - .push_number(4u64) - .push_number(0u64) - .push_address(target) - .append(GAS) - .append(STATICCALL) - .append(POP); - builder.build() -} - -fn make_repeated_staticcall_bytecode( - target: Address, - selector: [u8; 4], - iterations: usize, -) -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, selector); - for _ in 0..iterations { - builder = builder - .push_number(32u64) - .push_number(32u64) - .push_number(4u64) - .push_number(0u64) - .push_address(target) - .append(GAS) - .append(STATICCALL) - .append(POP); - } - builder.build() -} - -fn bench_system_contract(c: &mut Criterion) { - let access_control_addr: Address = address!("6342000000000000000000000000000000000004"); - let is_disabled_selector: [u8; 4] = [0x9e, 0x8e, 0x7b, 0xc0]; - let limit_control_addr: Address = address!("6342000000000000000000000000000000000005"); - let remaining_gas_selector: [u8; 4] = [0xde, 0x85, 0xee, 0xf5]; - let empty_contract_code = Bytes::from_static(&[STOP]); - - // A `CONTRACT` that STATICCALLs `SECONDARY` (a regular contract), used as - // the non-system-contract baseline for the interception comparison. - let regular_workload = |code: Bytes| { - Workload::single( - vec![ - Account::new(CONTRACT).code(code), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - Account::new(SECONDARY).code(empty_contract_code.clone()), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) - }; - - // REX5 is included so the `frame_init` hot path additions (CALL_STACK_LIMIT - // depth guard + zero-copy `peek_selector`) are measured against REX4 as the - // pre-fix baseline. Both specs go through the same interceptor dispatch on - // CALL/STATICCALL to a system contract, so the delta isolates the new logic. - const SYSTEM_CONTRACT_SPECS: &[(&str, MegaSpecId)] = - &[("rex4", MegaSpecId::REX4), ("rex5", MegaSpecId::REX5)]; - - // Single call benchmarks - { - let mut group = c.benchmark_group("system_contract_single"); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "access_control", - &mega_contract_workload(make_staticcall_bytecode( - access_control_addr, - is_disabled_selector, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "limit_control", - &mega_contract_workload(make_staticcall_bytecode( - limit_control_addr, - remaining_gas_selector, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "regular_contract", - ®ular_workload(make_staticcall_bytecode(SECONDARY, [0x00, 0x00, 0x00, 0x00])), - ); - group.finish(); - } - - // Repeated calls (100 iterations) - { - let n = 100; - let mut group = c.benchmark_group("system_contract_100x"); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "access_control", - &mega_contract_workload(make_repeated_staticcall_bytecode( - access_control_addr, - is_disabled_selector, - n, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "limit_control", - &mega_contract_workload(make_repeated_staticcall_bytecode( - limit_control_addr, - remaining_gas_selector, - n, - )), - ); - register_mega_specs_suffixed( - &mut group, - SYSTEM_CONTRACT_SPECS, - "regular_contract", - ®ular_workload(make_repeated_staticcall_bytecode( - SECONDARY, - [0x00, 0x00, 0x00, 0x00], - n, - )), - ); - group.finish(); - } -} - -// -// ============================================================================ -// DELEGATECALL to System Contract Benchmark -// ============================================================================ -// -// System contracts are intercepted on CALL but NOT on DELEGATECALL. -// DELEGATECALL falls through to on-chain bytecode (or reverts if no code). -// This is a security-relevant boundary. -// - -fn bench_delegatecall_system_contract(c: &mut Criterion) { - let access_control_addr: Address = address!("6342000000000000000000000000000000000004"); - let is_disabled_selector: [u8; 4] = [0x9e, 0x8e, 0x7b, 0xc0]; - let rex4: &[(&str, MegaSpecId)] = &[("rex4", MegaSpecId::REX4)]; - - // STATICCALL to system contract — intercepted, returns result - let staticcall_code = make_staticcall_bytecode(access_control_addr, is_disabled_selector); - - // DELEGATECALL to system contract — NOT intercepted, falls through - let delegatecall_code = { - let mut builder = BytecodeBuilder::default(); - builder = builder.mstore(0, is_disabled_selector); - // DELEGATECALL(gas, target, argsOffset, argsSize, retOffset, retSize) - builder = builder - .push_number(32u64) // retSize - .push_number(32u64) // retOffset - .push_number(4u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(access_control_addr) - .append(GAS) - .append(DELEGATECALL) - .append(POP); - builder.build() - }; - - let mut group = c.benchmark_group("delegatecall_system_contract"); - register_mega_specs_suffixed( - &mut group, - rex4, - "staticcall_intercepted", - &mega_contract_workload(staticcall_code), - ); - // DELEGATECALL falls through to absent bytecode and may halt, so allow it. - register_mega_specs_suffixed( - &mut group, - rex4, - "delegatecall_not_intercepted", - &mega_contract_workload(delegatecall_code).allow_halt(), - ); - group.finish(); -} - -// -// ============================================================================ -// Oracle SLOAD Benchmark -// ============================================================================ -// - -fn bench_oracle_sload(c: &mut Criterion) { - let sload_bytecode = generate_sload_bytecode(50); - - let mut group = c.benchmark_group("oracle_sload"); - // Regular SLOAD against a normal contract. - register_mega_suffixed( - &mut group, - "regular_sload_50", - &mega_contract_workload(sload_bytecode.clone()), - ); - // Oracle SLOAD: the same bytecode runs at the oracle address, where reads - // are forced cold. - let oracle = Workload::single( - vec![ - Account::new(ORACLE_ADDRESS).code(sload_bytecode), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, ORACLE_ADDRESS).gas_limit(FEATURE_GAS_LIMIT), - ); - register_mega_suffixed(&mut group, "oracle_sload_50", &oracle); - group.finish(); -} - -// -// ============================================================================ -// Mixed Workload Benchmark -// ============================================================================ -// - -fn generate_mixed_workload_bytecode() -> Bytes { - let mut builder = BytecodeBuilder::default(); - // Volatile data access - builder = builder.append(TIMESTAMP).append(POP).append(COINBASE).append(POP); - // Storage writes - for i in 0..20u64 { - builder = builder.push_number(i + 1).push_number(i).append(SSTORE); - } - // Log emissions - for _ in 0..10 { - builder = - builder.push_number(0xdead_beef_u64).push_number(32u64).push_number(0u64).append(LOG1); - } - // Computation - for _ in 0..50 { - builder = builder.push_number(1u64).push_number(2u64).append(ADD).append(POP); - } - builder.build() -} - -fn bench_mixed_workload(c: &mut Criterion) { - let mut group = c.benchmark_group("mixed_workload"); - register_all(&mut group, &mega_contract_workload(generate_mixed_workload_bytecode())); - group.finish(); -} - -// -// ============================================================================ -// EIP-7702 Authorization-List Scaling Benchmark -// ============================================================================ -// -// REX5 records state growth for EIP-7702 authority accounts during -// pre-execution (`record_eip7702_authority_state_growth`). For each -// authorization it consults a transaction-local collection of already-seen -// authorities; with a `Vec` that lookup is O(N) per authorization, hence O(N²) -// over the list — a node-CPU amplification an attacker can drive with ~1200 -// unique authorities in one 30M-gas type-4 tx. The `BTreeMap`-based -// implementation bounds the pass at O(N log N). -// -// The benchmark sweeps the authority count so a quadratic term shows up as -// super-linear growth (a map-based implementation grows linearly). Authorities -// are pre-recovered (`RecoveredAuthority::Valid`) so no ecrecover cost dilutes -// the measured scan; each is distinct and absent from state, so every one -// passes validation and exercises the full lookup. -// -// This bench builds the mega EVM directly instead of going through the -// `Workload` harness: `TxSpec` is deliberately backend-agnostic and carries no -// authorization list, and only mega rows are meaningful for this REX5-only -// pre-execution path. -// - -const AUTH_DELEGATE: Address = address!("0000000000000000000000000000000000900001"); - -fn make_recovered_auth_list(n: usize) -> Vec { - (0..n) - .map(|i| { - let mut bytes = [0u8; 20]; - bytes[12..20].copy_from_slice(&((i as u64) + 0x0010_0000).to_be_bytes()); - RecoveredAuthorization::new_unchecked( - // chain_id 0 = chain-agnostic, always valid regardless of cfg - Authorization { chain_id: U256::ZERO, address: AUTH_DELEGATE, nonce: 0 }, - RecoveredAuthority::Valid(Address::from(bytes)), - ) - }) - .collect() -} - -fn bench_eip7702_authlist(c: &mut Criterion) { - let mut group = c.benchmark_group("eip7702_authlist"); - for &n in &[150usize, 400, 800, 1200] { - let auth_list = make_recovered_auth_list(n); - let db = - MemoryDatabase::default().account_balance(CALLER, U256::from(10).pow(U256::from(24))); - group.bench_function(format!("rex5/{n}"), |b| { - b.iter(|| { - let mut context = MegaContext::new(db.clone(), MegaSpecId::REX5); - // Match the harness's Mega subject: the op-revm base panics on - // unset operator-fee fields, so zero them explicitly. - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::<_, NoOpInspector, EmptyExternalEnv>::new(context); - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(100_000_000) - .authorization_list_recovered(auth_list.clone()) - .build_fill(); - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(Bytes::new()); - black_box(evm.transact(mega_tx)) - }) - }); - } - group.finish(); -} - -// -// ============================================================================ -// STATICCALL → SELFDESTRUCT Unmetered-Work Benchmark -// ============================================================================ -// -// Without the `is_static` early-exit guard, the REX5 SELFDESTRUCT wrapper -// (`storage_gas_ext::selfdestruct`) inspects the beneficiary and caller -// accounts and runs SALT account-creation pricing BEFORE the inner interpreter -// reaches revm's static-context check and halts. Inside a STATICCALL frame -// that host work is always wasted: the frame reverts. An attacker repeats it -// via STATICCALL → selfdestruct in a loop. -// -// The parent loops fixed-gas STATICCALLs to a SELFDESTRUCT child; a STOP-child -// row is the control the early-exit guard must NOT change, so the wasted host -// work is the difference between the two rows. -// - -const SD_CHILD: Address = address!("00000000000000000000000000000000000a0001"); - -/// Parent that performs `iterations` STATICCALLs to `target`, each forwarding a -/// fixed `gas_each` (not all remaining gas, so one reverting child cannot drain -/// the parent), then STOPs. -fn make_repeated_staticcall_fixedgas(target: Address, gas_each: u64, iterations: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - for _ in 0..iterations { - builder = builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(target) - .push_number(gas_each) // forwarded gas (fixed) - .append(STATICCALL) - .append(POP); - } - builder.append(STOP).build() -} - -fn bench_staticcall_selfdestruct(c: &mut Criterion) { - const ITERS: usize = 500; - const GAS_EACH: u64 = 200_000; - let parent_code = make_repeated_staticcall_fixedgas(SD_CHILD, GAS_EACH, ITERS); - // SELFDESTRUCT(beneficiary=0): halts on the static-context check inside revm. - let sd_child: Bytes = vec![PUSH0, SELFDESTRUCT].into(); - // control: pure STOP — same STATICCALL frame cost, no SELFDESTRUCT host work. - let stop_child: Bytes = vec![STOP].into(); - - let workload = |child_code: Bytes| { - Workload::single( - vec![ - Account::new(CONTRACT).code(parent_code.clone()), - // fund the child so the SELFDESTRUCT `has_value` branch (SALT - // pricing) triggers - Account::new(SD_CHILD).code(child_code).balance(U256::from(1u64)), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, CONTRACT).gas_limit(FEATURE_GAS_LIMIT), - ) - }; - - const REX5_ONLY: &[(&str, MegaSpecId)] = &[("rex5", MegaSpecId::REX5)]; - let mut group = c.benchmark_group("staticcall_selfdestruct"); - register_mega_specs_suffixed( - &mut group, - REX5_ONLY, - &format!("selfdestruct_child/{ITERS}"), - &workload(sd_child), - ); - register_mega_specs_suffixed( - &mut group, - REX5_ONLY, - &format!("stop_child/{ITERS}"), - &workload(stop_child), - ); - group.finish(); -} - -// -// ============================================================================ -// SALT Dynamic-Gas Benchmarks -// ============================================================================ -// -// Isolates the SALT dynamic-gas path cost. For each storage-write workload, -// three rows run the SAME spec + workload: -// - `revm_pinned`: the env-agnostic absolute floor (no mega overhead). -// - `rex5`: mega over `EmptyExternalEnv`, where the SALT path short-circuits to a constant -// `MIN_BUCKET_SIZE` (no hash, no map lookup). -// - `rex5_salt`: mega over a crowded `TestExternalEnvs` (FNV hash + HashMap lookup + multiply -// per touched bucket). -// The `rex5_salt` − `rex5` gap is the isolated SALT-path cost. -// -// There is NO multiplier sweep: the bucket-capacity multiplier changes the gas -// AMOUNT charged, not the compute performed, so it does not move wall-clock time -// (verified empirically — x1 ≈ x32). A single crowded capacity -// (32 × MIN_BUCKET_SIZE) keeps the multiply operand non-trivial; what exercises -// the path is the number of distinct buckets touched, which `sstore_100` already -// drives to ~100. -// -// Only SSTORE / new-account / CREATE consult the SALT bucket multiplier; LOG -// storage gas uses a FIXED 10× multiplier (compile-time constants charged in -// `storage_gas_ext::log` without calling `load_bucket_cost_multiplier`), so a -// LOG workload would show ~0 gap — the crowded `TestExternalEnvs` is inert for -// LOG. The workloads below are therefore limited to `sstore_100` and `create_10`, -// both of which genuinely drive `load_bucket_cost_multiplier`. - -fn bench_salt_dynamic_gas(c: &mut Criterion) { - use mega_evm::MIN_BUCKET_SIZE; - - let workloads: &[(&str, Bytes)] = &[ - ("sstore_100", generate_sstore_bytecode(SSTORE_ITERATIONS)), - ("create_10", make_create_bytecode(10)), - ]; - - let mut group = c.benchmark_group("salt_dynamic_gas"); - for (wl_name, bytecode) in workloads { - let workload = mega_contract_workload(bytecode.clone()); - let crowded = mega_evm::TestExternalEnvs::::new() - .with_default_bucket_capacity(32 * MIN_BUCKET_SIZE as u64); - common::register_env_isolation( - &mut group, - MegaSpecId::REX5, - "rex5", - "rex5_salt", - crowded, - wl_name, - &workload, - ); - } - group.finish(); -} - -// -// ============================================================================ -// Oracle Real-Data Benchmark -// ============================================================================ -// -// Characterizes the real oracle SLOAD path (`host.rs::sload`), which no prior -// bench drove with populated oracle storage. At the oracle address `sload` -// forks on `get_oracle_storage(key)`: `Some(value)` early-returns and bypasses -// the journal entirely (oracle HIT); `None` falls through to the full journal -// SLOAD (`inner.sload`) for each slot (oracle MISS). -// -// Three rows, same shape as bench_salt_dynamic_gas: -// - `revm_pinned`: raw SLOAD floor — no oracle machinery at all. -// - ``: oracle SLOAD MISS — Mega over EmptyExternalEnv, where `get_oracle_storage` -// returns `None` and each slot falls through to the journal SLOAD. -// - `_oracle`: oracle SLOAD HIT — MegaWithEnv over populated TestExternalEnvs, where -// `get_oracle_storage` serves real data and early-returns past the journal. -// -// The `_oracle` − `` gap is the HIT-vs-MISS *structural* cost of the -// oracle SLOAD path (early-return vs journal traversal), NOT an isolated -// `get_oracle_storage` lookup microcost. The path forks structurally on hit vs -// miss, so — unlike the SALT bucket-multiply — the lookup cost cannot be isolated -// further; this bench characterizes the hit / miss / floor costs of the real -// oracle path. Address-based oracle gas detention fires identically on both mega -// rows, so it does not enter the gap. -// - -fn bench_oracle_real_data(c: &mut Criterion) { - let sload_bytecode = generate_sload_bytecode(50); - let workload = Workload::single( - vec![ - Account::new(ORACLE_ADDRESS).code(sload_bytecode), - Account::new(CALLER).balance(U256::from(10).pow(U256::from(18))), - ], - TxSpec::call(CALLER, ORACLE_ADDRESS).gas_limit(FEATURE_GAS_LIMIT), - ); - - // Populate the first 50 oracle slots with non-zero values. - let mut env = mega_evm::TestExternalEnvs::::new(); - for slot in 0u64..50 { - env = env.with_oracle_storage(U256::from(slot), U256::from(slot + 1)); - } - - let mut group = c.benchmark_group("oracle_real_data"); - // REX4: includes the revm_pinned floor row (registered only once per group). - common::register_env_isolation( - &mut group, - MegaSpecId::REX4, - "rex4", - "rex4_oracle", - env.clone(), - "oracle_sload_50", - &workload, - ); - // REX5: omit revm_pinned (already registered above — duplicate IDs panic). - common::register_env_isolation_mega_only( - &mut group, - MegaSpecId::REX5, - "rex5", - "rex5_oracle", - env, - "oracle_sload_50", - &workload, - ); - group.finish(); -} - -criterion_group!( - benches, - bench_volatile_data, - bench_gas_detention_computation, - bench_log_opcodes, - bench_sstore, - bench_create_deploy, - bench_selfdestruct, - bench_call_value_empty_account, - bench_system_contract, - bench_delegatecall_system_contract, - bench_oracle_sload, - bench_oracle_real_data, - bench_mixed_workload, - bench_eip7702_authlist, - bench_staticcall_selfdestruct, - bench_salt_dynamic_gas, -); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/revm_bench.rs b/crates/mega-evm/benches/revm_bench.rs deleted file mode 100644 index 47cefe542..000000000 --- a/crates/mega-evm/benches/revm_bench.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Benchmarks ported from upstream revm. -//! -//! These benchmarks are adapted from revm's revme bench suite to measure equivalent -//! workloads through mega-evm's execution pipeline, enabling performance comparison -//! between vanilla revm, op-revm, and mega-evm. -//! -//! Each workload runs against five layers so a single `cargo bench` produces a -//! comparable table: -//! -//! 1. `revm_pinned` — vanilla `revm::Evm` at the version mega-evm currently pins. -//! 2. `revm_latest` — vanilla `revm::Evm` at the latest crates.io release. -//! 3. `op_revm_pinned` — `op_revm::OpEvm` at the version mega-evm currently pins (operator fee = -//! 0). -//! 4. `op_revm_latest` — `op_revm::OpEvm` at the latest crates.io release (operator fee = 0). -//! 5. `mega_` — `MegaEvm` at `EQUIVALENCE` / `MINI_REX` / `REX4` / `REX5`. -//! -//! Ported workloads: -//! - **snailtracer**: CPU-intensive ray tracer exercising many opcodes -//! - **analysis**: ERC20-like contract bytecode execution -//! - **subcall**: Multi-level contract call performance (1000 iterations) -//! - **`transfer_multi`**: Batch transaction execution (1000 transfers) -//! -//! New workloads must avoid touching mega-evm's per-tx resource limits -//! (compute gas / data size / KV updates / state growth) under any spec, or the -//! `mega_*` row would halt early and skew the baseline comparison. -//! Likewise, every vanilla baseline is pinned to a Cancun-equivalent fork -//! (`revm` rows to Cancun, `op-revm` rows to Holocene) in `common::subject`, so -//! a new workload must execute successfully under Cancun semantics on every row. - -#![allow(missing_docs)] - -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{criterion_group, criterion_main, Criterion}; -use revm::bytecode::opcode; - -mod common; -use common::{register_all, Account, TxSpec, Workload}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -const SUBCALL_TARGET_A: Address = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); -const SUBCALL_TARGET_B: Address = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - -// -// ============================================================================ -// Snailtracer Benchmark -// ============================================================================ -// -// A CPU-intensive ray tracer that exercises many opcodes. -// This is the standard EVM performance benchmark from upstream revm. -// - -const SNAILTRACER_BYTES: &str = include_str!("data/snailtracer.hex"); - -fn bench_snailtracer(c: &mut Criterion) { - let bytecode = Bytes::from(hex::decode(SNAILTRACER_BYTES).unwrap()); - let calldata = bytes!("30627b7c"); - let caller_balance = U256::from(10).pow(U256::from(18)); - - let mut group = c.benchmark_group("snailtracer"); - group.sample_size(10); - - let workload = Workload::single( - vec![Account::new(CONTRACT).code(bytecode), Account::new(CALLER).balance(caller_balance)], - TxSpec::call(CALLER, CONTRACT).gas_limit(1_000_000_000).data(calldata), - ); - register_all(&mut group, &workload); - group.finish(); -} - -// -// ============================================================================ -// Analysis Benchmark -// ============================================================================ -// -// Exercises ERC20-like contract bytecode execution. -// Measures bytecode analysis and execution performance. -// - -const ANALYSIS_BYTES: &str = include_str!("data/analysis.hex"); - -fn bench_analysis(c: &mut Criterion) { - let bytecode = Bytes::from(hex::decode(ANALYSIS_BYTES).unwrap()); - let calldata = bytes!("8035F0CE"); - let caller_balance = U256::from(10).pow(U256::from(18)); - - let mut group = c.benchmark_group("analysis"); - - let workload = Workload::single( - vec![Account::new(CONTRACT).code(bytecode), Account::new(CALLER).balance(caller_balance)], - TxSpec::call(CALLER, CONTRACT).gas_limit(10_000_000_000).data(calldata), - ); - register_all(&mut group, &workload); - group.finish(); -} - -// -// ============================================================================ -// Subcall Benchmarks -// ============================================================================ -// -// Measures contract CALL overhead with three variants: -// - 1000 subcalls with 1 wei value transfer -// - 1000 subcalls with no value (same account) -// - 1000 nested subcalls (each target does another subcall) -// - -/// Constructs bytecode that loops 1000 times, each iteration doing a CALL to `target` -/// with the given `value` (0 or 1 wei). -fn make_loop_call_bytecode(target: Address, value: u8) -> Bytes { - let mut code = vec![ - opcode::PUSH2, - 0x03, - 0xE8, // PUSH2 1000 — loop counter - opcode::JUMPDEST, // loop_start at offset 3 - opcode::PUSH1, - 0x00, // retSize - opcode::PUSH1, - 0x00, // retOffset - opcode::PUSH1, - 0x00, // argsSize - opcode::PUSH1, - 0x00, // argsOffset - opcode::PUSH1, - value, // value - opcode::PUSH20, // target address - ]; - code.extend_from_slice(target.as_slice()); - code.extend_from_slice(&[ - opcode::GAS, // forward all remaining gas - opcode::CALL, - opcode::POP, // discard success/failure - opcode::PUSH1, - 0x01, // decrement counter - opcode::SWAP1, - opcode::SUB, - opcode::DUP1, // duplicate counter for JUMPI check - opcode::PUSH1, - 0x03, // jump target (JUMPDEST offset) - opcode::JUMPI, // jump back if counter != 0 - opcode::POP, // clean up remaining counter (0) - opcode::STOP, - ]); - code.into() -} - -/// Minimal contract that just STOPs. -fn make_stop_bytecode() -> Bytes { - Bytes::from_static(&[opcode::STOP]) -} - -/// Constructs bytecode that does a single CALL (no value) to `target`, then STOPs. -fn make_subcall_bytecode(target: Address) -> Bytes { - let mut code = vec![ - opcode::PUSH1, - 0x00, // retSize - opcode::PUSH1, - 0x00, // retOffset - opcode::PUSH1, - 0x00, // argsSize - opcode::PUSH1, - 0x00, // argsOffset - opcode::PUSH1, - 0x00, // value (no transfer) - opcode::PUSH20, // target address - ]; - code.extend_from_slice(target.as_slice()); - code.extend_from_slice(&[opcode::GAS, opcode::CALL, opcode::POP, opcode::STOP]); - Bytes::from(code) -} - -/// Benchmark one subcall variant across the 4 baselines and mega specs. The -/// contract at `CONTRACT` drives the loop, so the tx itself just calls it with -/// a high gas limit and no value. -fn bench_subcall_variant( - group: &mut criterion::BenchmarkGroup<'_, criterion::measurement::WallTime>, - accounts: Vec, -) { - const SUBCALL_GAS_LIMIT: u64 = 10_000_000_000; - let workload = - Workload::single(accounts, TxSpec::call(CALLER, CONTRACT).gas_limit(SUBCALL_GAS_LIMIT)); - register_all(group, &workload); -} - -fn bench_subcall(c: &mut Criterion) { - let caller_balance = U256::from(u128::MAX); - - // Variant 1: 1000 subcalls each transferring 1 wei - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 1); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_transfer_1wei"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(stop_code), - ], - ); - group.finish(); - } - - // Variant 2: 1000 subcalls with no value transfer - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 0); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_no_value"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(stop_code), - ], - ); - group.finish(); - } - - // Variant 3: 1000 nested subcalls (each target does another subcall) - { - let loop_code = make_loop_call_bytecode(SUBCALL_TARGET_A, 0); - let subcall_code = make_subcall_bytecode(SUBCALL_TARGET_B); - let stop_code = make_stop_bytecode(); - - let mut group = c.benchmark_group("subcall_1000_nested"); - group.sample_size(10); - bench_subcall_variant( - &mut group, - vec![ - Account::new(CALLER).balance(caller_balance), - Account::new(CONTRACT).code(loop_code), - Account::new(SUBCALL_TARGET_A).code(subcall_code), - Account::new(SUBCALL_TARGET_B).code(stop_code), - ], - ); - group.finish(); - } -} - -// -// ============================================================================ -// Transfer Multi Benchmark -// ============================================================================ -// -// Measures batch transaction execution: 1000 sequential ether transfers run on -// one reused EVM (a subject loops the workload's tx list internally). -// - -fn bench_transfer_multi(c: &mut Criterion) { - let mut group = c.benchmark_group("transfer_multi_1000"); - group.sample_size(10); - - let base = U256::from(10_000); - let targets: Vec
= - (0..1000u64).map(|i| Address::from_word((base + U256::from(i)).into())).collect(); - let caller_balance = U256::from(3_000_000_000u64); - let target_balance = U256::from(3_000_000_000u64); - - let mut accounts = vec![Account::new(CALLER).balance(caller_balance)]; - accounts.extend(targets.iter().map(|t| Account::new(*t).balance(target_balance))); - - let txs: Vec = targets - .iter() - .map(|t| TxSpec::call(CALLER, *t).value(U256::from(1)).gas_limit(100_000)) - .collect(); - - let workload = Workload::new(accounts, txs); - register_all(&mut group, &workload); - group.finish(); -} - -criterion_group!(benches, bench_snailtracer, bench_analysis, bench_subcall, bench_transfer_multi,); -criterion_main!(benches); diff --git a/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json b/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json new file mode 100644 index 000000000..aacca0ab9 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/access_list_warm_slots_and_account.json @@ -0,0 +1,43 @@ +{ + "name": "access_list_warm_slots_and_account", + "description": "The access list warms slot 0 and slot 2 of the reader and the account it reads the balance of; slot 1 stays cold.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000ead": { + "code": "0x60005450600154507300000000000000000000000000000000000000e43150600960025500", + "storage": { + "0x0": "0x1", + "0x1": "0x2" + } + }, + "0x00000000000000000000000000000000000000e4": { + "balance": "0x3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000ead", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "access_list": [ + { + "address": "0x0000000000000000000000000000000000000ead", + "storage_keys": [ + "0x0", + "0x2" + ] + }, + { + "address": "0x00000000000000000000000000000000000000e4", + "storage_keys": [] + } + ] + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/create_success.json b/crates/mega-evm/benches/scenarios/create_success.json new file mode 100644 index 000000000..e3f8cf5d0 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/create_success.json @@ -0,0 +1,28 @@ +{ + "name": "create_success", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f7f5b5b0000000000000000000000000000000000000000000000000000000000670000000000000000527f0067000000000000000052670000000000000003670000000000000000f300006700000000000000205267000000000000003e6700000000000000005ff0505a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json b/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json new file mode 100644 index 000000000..964eb05c3 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/eip7702_delegate_new_authority.json @@ -0,0 +1,34 @@ +{ + "name": "eip7702_delegate_new_authority", + "description": "The authority does not exist: the authorization creates it with the delegation designator and nonce 1, and the call to it runs the delegate's code in its context.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000de1": { + "code": "0x602a6000553060015500" + }, + "0x0000000000000000000000000000000000000de2": { + "code": "0x600760025500" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000a11", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call", + "authorization_list": [ + { + "chain_id": "0x1", + "address": "0x0000000000000000000000000000000000000de1", + "nonce": 0, + "authority": "0x0000000000000000000000000000000000000a11" + } + ] + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json b/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json new file mode 100644 index 000000000..bb77d6ecd --- /dev/null +++ b/crates/mega-evm/benches/scenarios/logs_all_topic_counts.json @@ -0,0 +1,23 @@ +{ + "name": "logs_all_topic_counts", + "description": "One LOG0 to LOG4 each, with data from memory.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000106": { + "code": "0x7f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2060005260206000a0600160206000a16002600160106000a260036002600160006000a3600460036002600160086018a400" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000106", + "data": "0x", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json b/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json new file mode 100644 index 000000000..f928b1289 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/nested_call_revert_with_spill.json @@ -0,0 +1,34 @@ +{ + "name": "nested_call_revert_with_spill", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x5f5f5f5f670000000000000000730000000000000000000000000000000000000ccc67000000000002bf20f1505a6700000000000000645500", + "storage": {} + }, + "0x0000000000000000000000000000000000000ccc": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555f5ffd", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/precompile_ecrecover.json b/crates/mega-evm/benches/scenarios/precompile_ecrecover.json new file mode 100644 index 000000000..4f47989bf --- /dev/null +++ b/crates/mega-evm/benches/scenarios/precompile_ecrecover.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_ecrecover", + "description": "ecrecover on a valid signature, then on one with v = 29.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009901": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000015afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001c9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009901", + "data": "0x456e9aea5e197a1f1af7a3e85a3212fa4049a3ba34c2289b4c860fc0b0c64ef3000000000000000000000000000000000000000000000000000000000000001d9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/precompile_modexp.json b/crates/mega-evm/benches/scenarios/precompile_modexp.json new file mode 100644 index 000000000..507d63dce --- /dev/null +++ b/crates/mega-evm/benches/scenarios/precompile_modexp.json @@ -0,0 +1,31 @@ +{ + "name": "precompile_modexp", + "description": "modexp 3^5 mod 7 with one-byte operands, then with a 64-byte exponent (the Osaka pricing).", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000009905": { + "code": "0x366000600037600060003660007300000000000000000000000000000000000000055afa6000553d6001553d600060003e3d6000206002553d6000f3" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001030507", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000009905", + "data": "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000103ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07", + "value": "0x0", + "gas_limit": 5000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json b/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json new file mode 100644 index 000000000..48f436af1 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/selfdestruct_created_in_same_tx_to_existing_account.json @@ -0,0 +1,27 @@ +{ + "name": "selfdestruct_created_in_same_tx_to_existing_account", + "description": "A contract created in the transaction self-destructs to an existing account from its init code: it is destroyed and the beneficiary gets its endowment.", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "balance": "0xde0b6b3a7640000" + }, + "0x0000000000000000000000000000000000000fac": { + "balance": "0x64", + "code": "0x3660006000373660006007f060005500" + }, + "0x0000000000000000000000000000000000000bee": { + "balance": "0x5" + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000fac", + "data": "0x730000000000000000000000000000000000000beeff", + "value": "0x0", + "gas_limit": 1000000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/sstore_set_spills.json b/crates/mega-evm/benches/scenarios/sstore_set_spills.json new file mode 100644 index 000000000..5bd91f6b5 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/sstore_set_spills.json @@ -0,0 +1,28 @@ +{ + "name": "sstore_set_spills", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/system_call.json b/crates/mega-evm/benches/scenarios/system_call.json new file mode 100644 index 000000000..4e82514d5 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/system_call.json @@ -0,0 +1,26 @@ +{ + "name": "system_call", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0xfffffffffffffffffffffffffffffffffffffffe", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "kind": "system_call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json b/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json new file mode 100644 index 000000000..3a4b2393c --- /dev/null +++ b/crates/mega-evm/benches/scenarios/test_calldata_floor_with_sstore_fork_Amsterdam_state_test.json @@ -0,0 +1,27 @@ +{ + "name": "test_calldata_floor_with_sstore_fork_Amsterdam_state_test", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0xe4492b6021e10a7b66a358972a0a67e0668817ef", + "data": "0x01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json b/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json new file mode 100644 index 000000000..7d4e6e671 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration.json @@ -0,0 +1,75 @@ +{ + "name": "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "pre": { + "0x0551d99e64f665f96a535ea329b0b7730b256f84": { + "nonce": 1, + "code": "0x60006000600060006000732dc8e42e99708c21567c90a3377341210ae12bb75af15000" + }, + "0x1ab6c3f64002a64fc6ab14a6d936b616d67ff2a3": { + "nonce": 1, + "code": "0x600060006000600060007380747c26d21e8b6196b92e05b0fd5b44bfda3eb95af15000" + }, + "0x2dc8e42e99708c21567c90a3377341210ae12bb7": { + "nonce": 1, + "code": "0x600160005560006000556000600060006000600073e4492b6021e10a7b66a358972a0a67e0668817ef6201adc9f160005500" + }, + "0x440df445bc999c4a7ad434728514b18d49af1f76": { + "nonce": 1, + "code": "0x60006000600060006000737b9a4ebbbcaa3b5ed869adf6cb131a885347deb95af15000" + }, + "0x4e59b44847b379578588920ca78fbf26c0b4956c": { + "nonce": 1, + "code": "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3" + }, + "0x595ad51569abfc814f56e2025df8465bc7c96daa": { + "nonce": 1, + "code": "0x6000600060006000600073f840c69a775450661d3faa91f9dc8677eb0bf5425af15000" + }, + "0x768599d3d827a10afdd46c7ee74e043cb491b3bb": { + "nonce": 1, + "code": "0x6000600060006000600073440df445bc999c4a7ad434728514b18d49af1f765af15000" + }, + "0x7a3f53d68397cf003560f9713a2452974812fd5f": { + "nonce": 1, + "code": "0x60006000600060006000731ab6c3f64002a64fc6ab14a6d936b616d67ff2a35af15000" + }, + "0x7b9a4ebbbcaa3b5ed869adf6cb131a885347deb9": { + "nonce": 1, + "code": "0x6000600060006000600073595ad51569abfc814f56e2025df8465bc7c96daa5af15000" + }, + "0x80747c26d21e8b6196b92e05b0fd5b44bfda3eb9": { + "nonce": 1, + "code": "0x60006000600060006000730551d99e64f665f96a535ea329b0b7730b256f845af15000" + }, + "0x84946fbc7842859adbd3644faa294e443c0232df": { + "nonce": 1, + "code": "0x60006000600060006000737a3f53d68397cf003560f9713a2452974812fd5f5af15000" + }, + "0xd6d787820fcc0f2b5b345d2b4026cc455431413b": { + "nonce": 1, + "code": "0x600060006000600060007384946fbc7842859adbd3644faa294e443c0232df5af15000" + }, + "0xe4492b6021e10a7b66a358972a0a67e0668817ef": { + "nonce": 1, + "code": "0x6001600055" + }, + "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff": { + "balance": "0x033b2e3c9fd0803ce8000000" + }, + "0xf840c69a775450661d3faa91f9dc8677eb0bf542": { + "nonce": 1, + "code": "0x6000600060006000600073d6d787820fcc0f2b5b345d2b4026cc455431413b5af15000" + } + }, + "txs": [ + { + "caller": "0xf6c3a9edc1afa0ad5b720e4d42e1437c43d3b3ff", + "to": "0x768599d3d827a10afdd46c7ee74e043cb491b3bb", + "data": "0x", + "value": "0x00", + "gas_limit": 200250000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/scenarios/two_txs_sequential.json b/crates/mega-evm/benches/scenarios/two_txs_sequential.json new file mode 100644 index 000000000..9ab146327 --- /dev/null +++ b/crates/mega-evm/benches/scenarios/two_txs_sequential.json @@ -0,0 +1,36 @@ +{ + "name": "two_txs_sequential", + "coinbase": "0x0000000000000000000000000000000000000c01", + "pre": { + "0x0000000000000000000000000000000000000aaa": { + "nonce": 0, + "balance": "0xe8d4a51000", + "code": "0x", + "storage": {} + }, + "0x0000000000000000000000000000000000000bbb": { + "nonce": 1, + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000001557f00000000000000000000000000000000000000000000000000000000000000017f0000000000000000000000000000000000000000000000000000000000000002555a6700000000000000645500", + "storage": {} + } + }, + "txs": [ + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + }, + { + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "data": "0x", + "value": "0x0", + "gas_limit": 200150000, + "kind": "call" + } + ] +} diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 6636c3322..ea24143ee 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -1,96 +1,174 @@ -//! Benchmarks for the `ExecuteEvm::transact()` interface. +//! `ExecuteEvm::transact` on the Satin engine next to op-revm's `OpEvm` on the same `CfgEnv`. //! -//! Each workload runs against four vanilla baselines (`revm_pinned`, -//! `revm_latest`, `op_revm_pinned`, `op_revm_latest`) and four mega specs -//! (`EQUIVALENCE`, `MINI_REX`, `REX4`, `REX5`) so a single bench produces a -//! cross-row gap table. +//! Each workload runs through `MegaEvm` (`satin`) and through `OpEvm` (`op_revm`), so the gap is +//! the wrapper's own cost. EVM construction is setup and is not measured. +//! +//! - `empty_transaction`, `ether_transfer`: the per-transaction cost. +//! - `deep_calls`: a contract calling itself 64 deep, each frame writing a slot and logging, so +//! every frame pays the frame lifecycle's lanes and every `SSTORE` and `LOG` its commit wrapper. +//! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the +//! `SSTORE` wrapper's commit and refund. +//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit. #![allow(missing_docs)] -use alloy_primitives::{address, bytes, Address, Bytes, U256}; -use criterion::{criterion_group, criterion_main, Criterion}; -use revm::primitives::{keccak256, B256}; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use mega_evm::{ + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaSpecId, +}; +use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, PUSH0, + PUSH1, SSTORE, STOP, SUB, SWAP1, + }, + context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, + inspector::NoOpInspector, + ExecuteEvm, Journal, +}; -mod common; -use common::{register_all, Account, TxSpec, Workload}; +const CALLER: Address = address!("0x0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0x0000000000000000000000000000000000100001"); +const RECURSIVE: Address = address!("0x0000000000000000000000000000000000100002"); +const WRITER: Address = address!("0x0000000000000000000000000000000000100003"); +const LOGGER: Address = address!("0x0000000000000000000000000000000000100004"); -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const WETH9_ADDRESS: Address = address!("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); +/// Depth the recursive contract reaches. +const DEPTH: u8 = 64; +/// Slots written, then written back, by the storage workload; logs emitted by the log workload. +const REPEAT: u64 = 200; -/// WETH9 deployed runtime bytecode. -const WETH9_RUNTIME_CODE: Bytes = bytes!("6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b9578063095ea7b31461014757806318160ddd146101a157806323b872dd146101ca5780632e1a7d4d14610243578063313ce5671461026657806370a082311461029557806395d89b41146102e2578063a9059cbb14610370578063d0e30db0146103ca578063dd62ed3e146103d4575b6100b7610440565b005b34156100c457600080fd5b6100cc6104dd565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561010c5780820151818401526020810190506100f1565b50505050905090810190601f1680156101395780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561015257600080fd5b610187600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061057b565b604051808215151515815260200191505060405180910390f35b34156101ac57600080fd5b6101b461066d565b6040518082815260200191505060405180910390f35b34156101d557600080fd5b610229600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061068c565b604051808215151515815260200191505060405180910390f35b341561024e57600080fd5b61026460048080359060200190919050506109d9565b005b341561027157600080fd5b610279610b05565b604051808260ff1660ff16815260200191505060405180910390f35b34156102a057600080fd5b6102cc600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b18565b6040518082815260200191505060405180910390f35b34156102ed57600080fd5b6102f5610b30565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561033557808201518184015260208101905061031a565b50505050905090810190601f1680156103625780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561037b57600080fd5b6103b0600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610bce565b604051808215151515815260200191505060405180910390f35b6103d2610440565b005b34156103df57600080fd5b61042a600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610be3565b6040518082815260200191505060405180910390f35b34600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055503373ffffffffffffffffffffffffffffffffffffffff167fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c346040518082815260200191505060405180910390a2565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105735780601f1061054857610100808354040283529160200191610573565b820191906000526020600020905b81548152906001019060200180831161055657829003601f168201915b505050505081565b600081600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60003073ffffffffffffffffffffffffffffffffffffffff1631905090565b600081600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101515156106dc57600080fd5b3373ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16141580156107b457507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205414155b156108cf5781600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015151561084457600080fd5b81600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b81600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a2757600080fd5b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f193505050501515610ab457600080fd5b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65826040518082815260200191505060405180910390a250565b600260009054906101000a900460ff1681565b60036020528060005260406000206000915090505481565b60018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610bc65780601f10610b9b57610100808354040283529160200191610bc6565b820191906000526020600020905b815481529060010190602001808311610ba957829003601f168201915b505050505081565b6000610bdb33848461068c565b905092915050565b60046020528160005260406000206020528060005260406000206000915091505054815600a165627a7a72305820deb4c2ccab3c2fdca32ab3f46728389c2fe2c165d5fafa07661e4e004f6c344a0029"); +/// Offset of the `JUMPDEST` the recursion ends at. +const DONE: u8 = 0x1f; -/// Calculate the storage slot for an ERC20 balance mapping. -/// Solidity mapping storage slot = keccak256(abi.encode(key, slot)) -fn erc20_balance_slot(address: Address, mapping_slot: u8) -> B256 { - let mut data = [0u8; 64]; - // Encode address (left-padded to 32 bytes) - data[12..32].copy_from_slice(address.as_slice()); - // Encode mapping slot - data[63] = mapping_slot; - keccak256(data) +/// Reads `n` from calldata; while `n > 0` it writes slot `n`, logs, and calls itself with `n - 1`. +fn recursive_code() -> Bytes { + #[rustfmt::skip] + let body = [ + PUSH0, CALLDATALOAD, // n + DUP1, ISZERO, PUSH1, DONE, JUMPI, // n == 0: done + DUP1, PUSH1, 1, SWAP1, SSTORE, // storage[n] = 1 + PUSH0, PUSH0, LOG0, // an empty log + PUSH1, 1, SWAP1, SUB, PUSH0, MSTORE, // memory[0..32] = n - 1 + PUSH0, PUSH0, PUSH1, 0x20, PUSH0, PUSH0, ADDRESS, GAS, CALL, // call self with n - 1 + STOP, + JUMPDEST, STOP, // done + ]; + assert_eq!(body[DONE as usize], JUMPDEST); + Bytes::from(body.to_vec()) } -/// Benchmark empty transaction (call with no value or data). -fn bench_empty_transaction(c: &mut Criterion) { - let mut group = c.benchmark_group("empty_transaction"); - // No accounts seeded — caller and callee don't exist (gas price is zero, so - // the caller needs no balance), matching the original workload. - let workload = Workload::single(vec![], TxSpec::call(CALLER, CALLEE)); - register_all(&mut group, &workload); - group.finish(); +/// Writes `REPEAT` fresh slots, then writes each back to zero. +fn writer_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 0..REPEAT { + code = code.sstore(U256::from(slot), U256::from(1)); + } + for slot in 0..REPEAT { + code = code.sstore(U256::from(slot), U256::ZERO); + } + code.stop().build() } -/// Benchmark simple ether transfer between existing accounts. -fn bench_simple_ether_transfer(c: &mut Criterion) { - let mut group = c.benchmark_group("simple_ether_transfer"); - let workload = Workload::single( - vec![ - Account::new(CALLER).balance(U256::from(1000)), - Account::new(CALLEE).balance(U256::from(100)), - ], - TxSpec::call(CALLER, CALLEE), - ); - register_all(&mut group, &workload); - group.finish(); +/// Emits `REPEAT` two-topic logs of 32 bytes. +fn logger_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for topic in 0..REPEAT { + code = code + .push_number(topic) + .push_number(topic) + .push_number(32_u8) + .append(PUSH0) + .append(LOG2); + } + code.stop().build() +} + +fn call_tx(to: Address, data: Bytes, gas_limit: u64) -> OpTransaction { + op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data, + gas_limit, + ..Default::default() + }) } -/// Benchmark WETH9 ERC20 transfer. -fn bench_weth9_transfer(c: &mut Criterion) { - let mut group = c.benchmark_group("weth9_transfer"); +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +fn tx(value: U256) -> OpTransaction { + op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value, + gas_limit: 1_000_000, + ..Default::default() + }) +} - // Transfer amount: 100 WETH - let transfer_amount = U256::from(100) * U256::from(10).pow(U256::from(18)); +fn mega_context(db: MemoryDatabase) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) +} - // Encode transfer(address,uint256) call. Function selector: 0xa9059cbb. - let mut calldata = Vec::with_capacity(68); - calldata.extend_from_slice(&[0xa9, 0x05, 0x9c, 0xbb]); - calldata.extend_from_slice(&[0u8; 12]); - calldata.extend_from_slice(CALLEE.as_slice()); - calldata.extend_from_slice(&transfer_amount.to_be_bytes::<32>()); - let calldata = Bytes::from(calldata); +fn bench_transact(c: &mut Criterion) { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(1)) + .account_code(RECURSIVE, recursive_code()) + .account_code(WRITER, writer_code()) + .account_code(LOGGER, logger_code()); + let cfg = mega_context(db.clone()).cfg().clone(); - let caller_weth_balance = U256::from(1000) * U256::from(10).pow(U256::from(18)); - let caller_gas_balance = U256::from(10).pow(U256::from(18)); - let balance_slot: U256 = erc20_balance_slot(CALLER, 3).into(); + let mut depth = [0u8; 32]; + depth[31] = DEPTH; + let workloads = [ + ("empty_transaction", tx(U256::ZERO)), + ("ether_transfer", tx(U256::from(1))), + ("deep_calls", call_tx(RECURSIVE, Bytes::from(depth.to_vec()), 30_000_000)), + ("storage_writes", call_tx(WRITER, Bytes::new(), 30_000_000)), + ("logs", call_tx(LOGGER, Bytes::new(), 30_000_000)), + ]; - let workload = Workload::single( - vec![ - Account::new(WETH9_ADDRESS) - .code(WETH9_RUNTIME_CODE) - .storage(balance_slot, caller_weth_balance), - Account::new(CALLER).balance(caller_gas_balance), - ], - TxSpec::call(CALLER, WETH9_ADDRESS).data(calldata), - ); - register_all(&mut group, &workload); + let mut group = c.benchmark_group("transact"); + for (workload, tx) in workloads { + let satin = MegaEvm::new(mega_context(db.clone())).transact(OpTx(tx.clone())).unwrap(); + assert!(satin.result.is_success(), "{workload}: {:?}", satin.result); + if workload == "deep_calls" { + let written = + satin.state[&RECURSIVE].storage.values().filter(|s| s.is_changed()).count(); + assert_eq!(written, DEPTH as usize, "every frame of the recursion ran"); + } + group.bench_function(format!("{workload}/satin"), |b| { + b.iter_batched( + || MegaEvm::new(mega_context(db.clone())), + |mut evm| evm.transact(OpTx(tx.clone())).unwrap(), + BatchSize::SmallInput, + ); + }); + group.bench_function(format!("{workload}/op_revm"), |b| { + b.iter_batched( + || { + let ctx = OpContext::new(db.clone(), OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_chain(zero_fee_l1_block_info()); + OpEvm::new(ctx, NoOpInspector) + }, + |mut evm| evm.transact(tx.clone()).unwrap(), + BatchSize::SmallInput, + ); + }); + } group.finish(); } -criterion_group!( - benches, - bench_empty_transaction, - bench_simple_ether_transfer, - bench_weth9_transfer -); +criterion_group!(benches, bench_transact); criterion_main!(benches); diff --git a/crates/mega-evm/examples/beneficiary_access_tracking.rs b/crates/mega-evm/examples/beneficiary_access_tracking.rs deleted file mode 100644 index ddf76e290..000000000 --- a/crates/mega-evm/examples/beneficiary_access_tracking.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! This example demonstrates the beneficiary access detection feature. -//! It creates contracts that access beneficiary account data and shows how -//! the system can detect when such access occurs during execution. -//! -//! The contracts tested are: -//! 1. Contract 1: Reads beneficiary balance (should trigger access detection) -//! 2. Contract 2: Does NOT access beneficiary data (should not trigger detection) -//! 3. Contract 3: Accesses beneficiary via different operations (should trigger detection) - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{MegaContext, MegaEvm, MegaSpecId, MegaTransaction}; -use revm::{ - bytecode::opcode::{BALANCE, CALLER, POP, PUSH20, STOP}, - context::{BlockEnv, ContextSetters, ContextTr, TxEnv}, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - primitives::TxKind, - state::{AccountInfo, Bytecode}, -}; - -fn main() -> Result<(), Box> { - println!("=== Beneficiary Access Tracking Demo ===\n"); - - // Create database and EVM context - let mut db = CacheDB::::default(); - let spec = MegaSpecId::MINI_REX; - let beneficiary = address!("0000000000000000000000000000000000000001"); - - // Contract 1: Reads beneficiary balance - let contract1_address = address!("0000000000000000000000000000000000100001"); - let mut contract1_code = vec![]; - // Push beneficiary address onto stack - contract1_code.push(PUSH20); - contract1_code.extend(beneficiary.as_slice()); - // Get balance of beneficiary - contract1_code.push(BALANCE); - contract1_code.push(POP); // Remove result from stack - contract1_code.push(STOP); - set_account_code(&mut db, contract1_address, contract1_code.into()); - - // Contract 2: Does NOT access beneficiary (uses CALLER) - let contract2_address = address!("0000000000000000000000000000000000100002"); - let contract2_code = vec![CALLER, POP, STOP]; - set_account_code(&mut db, contract2_address, contract2_code.into()); - - // Contract 3: Accesses beneficiary balance (same as contract 1, but separate test) - let contract3_address = address!("0000000000000000000000000000000000100003"); - let mut contract3_code = vec![]; - // Push beneficiary address onto stack - contract3_code.push(PUSH20); - contract3_code.extend(beneficiary.as_slice()); - // Get balance of beneficiary - contract3_code.push(BALANCE); - contract3_code.push(POP); - contract3_code.push(STOP); - set_account_code(&mut db, contract3_address, contract3_code.into()); - - // Create EVM instance with properly configured context - let mut context = MegaContext::new(db, spec); - - // Set the beneficiary in the block environment - let block_env = BlockEnv { beneficiary, ..Default::default() }; - context.set_block(block_env); - - // Set operator fee fields to zero to avoid panic in MINI_REX spec - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - - let mut evm = MegaEvm::new(context); - - let caller = address!("0000000000000000000000000000000000100000"); - - // Test Contract 1 (reads beneficiary balance) - println!("Testing Contract 1 (reads beneficiary balance):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx1 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract1_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, // Use reasonable gas limit - ..Default::default() - }, - ..Default::default() - }; - - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1)?; - println!(" Transaction successful: {}", result1.result.is_success()); - println!(" Gas used: {}", result1.result.gas_used()); - - // Verify that beneficiary access was detected - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!( - beneficiary_accessed, - "Contract 1 should have detected beneficiary access (balance read)!" - ); - assert!(result1.result.is_success(), "Contract 1 transaction should succeed"); - - // Reset for next transaction - evm.ctx_mut().reset_volatile_data_access(); - println!(" After reset: no beneficiary access detected\n"); - - // Test Contract 2 (does NOT access beneficiary) - println!("Testing Contract 2 (does NOT access beneficiary):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx2 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract2_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, - ..Default::default() - }, - ..Default::default() - }; - - let result2 = alloy_evm::Evm::transact_raw(&mut evm, tx2)?; - println!(" Transaction successful: {}", result2.result.is_success()); - println!(" Gas used: {}", result2.result.gas_used()); - - // Verify that beneficiary was NOT accessed - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!(!beneficiary_accessed, "Contract 2 should NOT have detected beneficiary access!"); - assert!(result2.result.is_success(), "Contract 2 transaction should succeed"); - - // Reset for next transaction - evm.ctx_mut().reset_volatile_data_access(); - println!(" After reset: no beneficiary access detected\n"); - - // Test Contract 3 (accesses beneficiary balance) - println!("Testing Contract 3 (accesses beneficiary balance):"); - - assert!( - !evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(), - "Should start with no beneficiary access" - ); - println!(" Initial state: no beneficiary access detected"); - - let tx3 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract3_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 100000, - ..Default::default() - }, - ..Default::default() - }; - - let result3 = alloy_evm::Evm::transact_raw(&mut evm, tx3)?; - println!(" Transaction successful: {}", result3.result.is_success()); - println!(" Gas used: {}", result3.result.gas_used()); - - // Verify that beneficiary access was detected - let beneficiary_accessed = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - println!(" Beneficiary access detected: {}", beneficiary_accessed); - assert!( - beneficiary_accessed, - "Contract 3 should have detected beneficiary access (balance read)!" - ); - assert!(result3.result.is_success(), "Contract 3 transaction should succeed"); - - println!("\n=== Tracking Summary ==="); - println!("✅ Beneficiary access tracking is working correctly!"); - println!("✅ Contract 1 (balance read): Access tracked = true"); - println!("✅ Contract 2 (no access): Access tracked = false"); - println!("✅ Contract 3 (balance read): Access tracked = true"); - println!("✅ All tracking tests passed!"); - println!( - "\nThe system can accurately track when transactions access beneficiary account data." - ); - println!( - "This detection mechanism can be used for monitoring, analytics, or enforcement purposes." - ); - - Ok(()) -} - -/// Helper function to set account code -fn set_account_code(db: &mut CacheDB, address: alloy_primitives::Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = AccountInfo { code: Some(bytecode), code_hash, ..Default::default() }; - db.insert_account_info(address, account_info); -} diff --git a/crates/mega-evm/examples/block_env_tracking.rs b/crates/mega-evm/examples/block_env_tracking.rs deleted file mode 100644 index d42d02c22..000000000 --- a/crates/mega-evm/examples/block_env_tracking.rs +++ /dev/null @@ -1,184 +0,0 @@ -//! This example demonstrates the block environment access tracking in the EVM. -//! It creates three contracts that use different block environment accesses and -//! tests the tracking functionality. -//! -//! The contracts are: -//! 1. Contract 1: Uses single block environment access (NUMBER opcode) -//! 2. Contract 2: Uses multiple block environment accesses (NUMBER, TIMESTAMP, BASEFEE opcodes) -//! 3. Contract 3: Does NOT use block environment (CALLER opcode) - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{MegaContext, MegaEvm, MegaSpecId, MegaTransaction, VolatileDataAccess}; -use revm::{ - bytecode::opcode::{BASEFEE, CALLER, NUMBER, POP, STOP, TIMESTAMP}, - context::{ContextTr, TxEnv}, - database::{CacheDB, EmptyDB}, - primitives::TxKind, - state::{AccountInfo, Bytecode}, -}; - -fn main() -> Result<(), Box> { - // Create database and EVM context - let mut db = CacheDB::::default(); - let spec = MegaSpecId::MINI_REX; - - // Contract 1: Uses single block environment access (NUMBER opcode) - let contract1_address = address!("0000000000000000000000000000000000100001"); - let contract1_code = vec![NUMBER, STOP]; // Read block number then stop - set_account_code(&mut db, contract1_address, contract1_code.into()); - - // Contract 2: Uses multiple block environment accesses - let contract2_address = address!("0000000000000000000000000000000000100002"); - let contract2_code = vec![ - NUMBER, POP, // Read block number - TIMESTAMP, POP, // Read timestamp - BASEFEE, POP, // Read base fee - STOP, - ]; - set_account_code(&mut db, contract2_address, contract2_code.into()); - - // Contract 3: Does NOT use block environment (CALLER opcode) - let contract3_address = address!("0000000000000000000000000000000000100003"); - let contract3_code = vec![CALLER, STOP]; // Read caller then stop - set_account_code(&mut db, contract3_address, contract3_code.into()); - - // Create EVM instance with properly configured L1BlockInfo - let mut context = MegaContext::new(db, spec); - // Set operator fee fields to zero to avoid panic in MINI_REX (ISTHMUS) spec - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - let mut evm = MegaEvm::new(context); - - let caller = address!("0000000000000000000000000000000000100000"); - - println!("=== Block Environment Access Tracking Demo ===\n"); - - // Test Contract 1 (single block env access) - println!("Testing Contract 1 (uses NUMBER opcode):"); - - // Ensure clean state - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 1 - let tx1 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract1_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - ..Default::default() - }, - ..Default::default() - }; - - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1)?; - println!(" Transaction result: {:?}", result1.result.is_success()); - - let accesses1 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses1.is_empty()); - - // Show detailed access information - println!(" Access count: {}", accesses1.count_block_env_accessed()); - println!( - " Has accessed BlockNumber: {}", - accesses1.contains(VolatileDataAccess::BLOCK_NUMBER) - ); - - assert_eq!(accesses1.count_block_env_accessed(), 1); - assert!(accesses1.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(!accesses1.is_empty(), "Contract 1 should have accessed block env"); - - // Reset for next transaction - evm.reset_volatile_data_access(); - println!(" After reset: {}\n", evm.get_block_env_accesses().is_empty()); - - // Test Contract 2 (multiple block env accesses) - println!("Testing Contract 2 (uses NUMBER, TIMESTAMP, BASEFEE opcodes):"); - - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 2 - let tx2 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract2_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - nonce: 0, // Reset nonce for new transaction - ..Default::default() - }, - ..Default::default() - }; - - let result2 = alloy_evm::Evm::transact_raw(&mut evm, tx2)?; - println!(" Transaction result: {:?}", result2.result.is_success()); - - let accesses2 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses2.is_empty()); - - // Show detailed access information - println!(" Access count: {}", accesses2.count_block_env_accessed()); - println!( - " Has accessed BlockNumber: {}", - accesses2.contains(VolatileDataAccess::BLOCK_NUMBER) - ); - println!(" Has accessed Timestamp: {}", accesses2.contains(VolatileDataAccess::TIMESTAMP)); - println!(" Has accessed BaseFee: {}", accesses2.contains(VolatileDataAccess::BASE_FEE)); - - assert_eq!(accesses2.count_block_env_accessed(), 3); - assert!(accesses2.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(accesses2.contains(VolatileDataAccess::TIMESTAMP)); - assert!(accesses2.contains(VolatileDataAccess::BASE_FEE)); - assert!(!accesses2.is_empty(), "Contract 2 should have accessed block env"); - - // Reset for next transaction - evm.reset_volatile_data_access(); - println!(" After reset: {}\n", evm.get_block_env_accesses().is_empty()); - - // Test Contract 3 (does NOT access block env) - println!("Testing Contract 3 (uses CALLER opcode):"); - - assert!(evm.get_block_env_accesses().is_empty(), "Should start with no block env access"); - println!(" Initial state: no block env access"); - - // Create and execute transaction for contract 3 - let tx3 = MegaTransaction { - base: TxEnv { - caller, - kind: TxKind::Call(contract3_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000, - nonce: 0, // Reset nonce for new transaction - ..Default::default() - }, - ..Default::default() - }; - - let result3 = alloy_evm::Evm::transact_raw(&mut evm, tx3)?; - println!(" Transaction result: {:?}", result3.result.is_success()); - - let accesses3 = evm.get_block_env_accesses(); - println!(" Block env accessed: {}", !accesses3.is_empty()); - - println!(" Access count: {}", accesses3.count_block_env_accessed()); - - assert_eq!(accesses3.count_block_env_accessed(), 0); - assert!(accesses3.is_empty(), "Contract 3 should NOT have accessed block env"); - - println!(" Demo finished"); - - Ok(()) -} - -/// Helper function to set account code -fn set_account_code(db: &mut CacheDB, address: alloy_primitives::Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = AccountInfo { code: Some(bytecode), code_hash, ..Default::default() }; - db.insert_account_info(address, account_info); -} diff --git a/crates/mega-evm/src/AGENTS.md b/crates/mega-evm/src/AGENTS.md deleted file mode 100644 index 0eab71d1c..000000000 --- a/crates/mega-evm/src/AGENTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Core MegaEVM crate implementation layer that composes execution, block processing, limits, system contracts, and external environments. - -## STRUCTURE -- `lib.rs`: crate module wiring, public re-exports, type aliases. -- `evm/`: transaction execution engine, instruction table, host hooks, context and factory. -- `block/`: block executor, hardfork mapping, block-level limit pipeline. -- `limit/`: per-tx and per-frame resource trackers plus exceed handling. -- `system/`: system contract addresses, deployment helpers, frame interceptors. -- `access/`: volatile-data access bitmaps and disable/enable depth tracking. -- `external/`: SALT and oracle external environment contracts and factories. -- `sandbox/`: isolated execution paths used by special flows. -- `constants.rs`: per-spec limits and gas constants used across modules. - -## KEY PATTERNS -- `no_std` discipline is active for this crate. -- Use `#[cfg(not(feature = "std"))] use alloc as std;` when std collections are required. -- Spec progression is additive for behavior-introducing specs; alias rungs (`MINI_REX_1`, `MINI_REX_2`) re-execute an earlier behavior instead. -- Keep behavior gates explicit via `spec.is_enabled(...)` at call sites. -- Per-frame trackers must stay stack-aligned with EVM frame lifecycle hooks. -- Intercepted synthetic frame results must keep tracker alignment via empty-frame pushes. -- Keep aliases in `lib.rs` aligned with canonical `Mega*` types. - -## WHERE TO LOOK -- Add or modify opcode semantics: `evm/instructions.rs` and `evm/host.rs`. -- Add transaction-level runtime constraints: `limit/limit.rs` and tracker submodules. -- Add block inclusion or accounting rules: `block/limit.rs` and `block/executor.rs`. -- Add/adjust hardfork activation logic: `block/hardfork.rs`. -- Add system contract deployment or interception behavior: `system/*.rs` plus block pre-execution deployment calls. -- Add external dependency plumbing: `external/factory.rs`, `external/gas.rs`, `external/oracle.rs`, `external/salt.rs`. -- Add reusable constants: `constants.rs`. diff --git a/crates/mega-evm/src/access/AGENTS.md b/crates/mega-evm/src/access/AGENTS.md deleted file mode 100644 index aca629b6e..000000000 --- a/crates/mega-evm/src/access/AGENTS.md +++ /dev/null @@ -1,32 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Volatile-data access tracking primitives used to enforce compute-gas detention and Rex4 subtree-level volatile access disable. - -## STRUCTURE -- `mod.rs`: public module exports. -- `tracker.rs`: mutable tracker state, cap merge logic, and depth-scoped disable semantics. -- `volatile.rs`: bitflags and typed conversions for volatile access categories. - -## KEY PATTERNS -- Tracker stores both a bitmap of accessed categories and the most restrictive raw detention cap. -- Cap aggregation is order-independent via min-cap merge. -- Disable scope is depth-based. -- `disable_access(depth)` keeps the shallower depth if already active. -- `enable_access(caller_depth)` only succeeds when caller is at or above activation depth. -- `enable_access_if_returning(current_depth)` prevents disable leakage into sibling frames. -- Reset clears access state and disable depth, but preserves configured cap parameters. - -## ANTI-PATTERNS -- Do not store spec-dependent effective detained limits in this module. -- This module stores raw caps only. -- Do not clear `disable_depth` on every frame return. -- Only clear when returning above the activation depth. -- Do not mutate bitmap bits from unrelated subsystems. -- Access marks should come from host/instruction touch points only. - -## WHERE TO LOOK -- Adjust volatile category mapping bits: `volatile.rs`. -- Change detention cap merge policy: `tracker.rs::apply_or_create_limit`. -- Change disable/enable call-tree semantics: `tracker.rs::{disable_access,enable_access,enable_access_if_returning}`. -- Change beneficiary/oracle detection helpers: `tracker.rs` and host call sites in `../evm/host.rs`. diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 6fe86ff36..0a46ba7f8 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -1,12 +1,3 @@ -//! Volatile data access tracking for the `MegaETH` EVM. +//! Volatile-data access tracking (block environment, beneficiary, oracle) behind gas detention. //! -//! Volatile data means those data that may be modified by the system (e.g., sequencer, oracle, or -//! payload builder). Once a transaction accesses volatile data, the system will immediate limit -//! the remaining gas in all message calls to a small amount of gas, forcing the transaction to -//! finish execution soon. These restrictions are necessary to prevent `DoS` attacks on EVM. - -mod tracker; -mod volatile; - -pub use tracker::*; -pub use volatile::*; +//! Empty until gas detention lands. diff --git a/crates/mega-evm/src/access/tracker.rs b/crates/mega-evm/src/access/tracker.rs deleted file mode 100644 index 8ea5e3437..000000000 --- a/crates/mega-evm/src/access/tracker.rs +++ /dev/null @@ -1,305 +0,0 @@ -use crate::{VolatileDataAccess, VolatileDataAccessType, ORACLE_CONTRACT_ADDRESS}; -use alloy_primitives::Address; - -/// A tracker for volatile data access with compute gas limit enforcement. -/// -/// This tracker manages volatile data access detection (block environment, beneficiary, oracle) -/// and tracks the compute gas detention cap to prevent `DoS` attacks. -/// -/// # Compute Gas Limit Enforcement -/// -/// When volatile data is first accessed in a transaction, this tracker records the cap value: -/// - `BLOCK_ENV_ACCESS_COMPUTE_GAS` (20M) for block environment or beneficiary -/// - `ORACLE_ACCESS_COMPUTE_GAS` (configurable: 1M pre-Rex3, 20M Rex3+) for oracle contract -/// -/// The cap value stored here is the **raw** per-access-type cap. How it is applied depends on -/// the spec: -/// - **Pre-REX4**: The cap is an **absolute** compute gas limit for the transaction. -/// - **REX4+**: The cap is **relative** — `ComputeGasTracker::set_detained_limit()` adds current -/// usage to produce the effective limit (`usage_at_access + cap`). -/// -/// If additional volatile data is accessed with a different cap, the **most restrictive** -/// (minimum) raw cap is stored. -/// The caller is responsible for applying this cap to the `AdditionalLimit`. -/// -/// # Key Properties -/// -/// - **Type-Specific Caps**: Block env/beneficiary access → 20M compute gas, Oracle access → -/// configurable (1M pre-Rex3, 20M Rex3+) -/// - **Most Restrictive Wins**: Multiple accesses with different caps → minimum cap applied -/// - **Order Independent**: Oracle→BlockEnv or BlockEnv→Oracle both result in same final cap -/// - **Compute Gas Only**: Only limits compute gas costs, not storage gas cost -/// -/// # Example Flows -/// -/// ## Example 1: Block env then oracle (pre-Rex3, oracle limit = 1M) -/// ```ignore -/// // Transaction starts with compute gas limit of 30M -/// TIMESTAMP opcode: -/// - Marks block_env_accessed -/// - Compute gas limit tracked as 20M -/// -/// CALL(oracle) opcode: -/// - Marks oracle_accessed -/// - Compute gas limit lowered to min(20M, 1M) = 1M -/// -/// // Caller applies 1M compute gas limit to AdditionalLimit -/// ``` -/// -/// ## Example 2: Oracle then block env (pre-Rex3, order independent) -/// ```ignore -/// // Transaction starts with compute gas limit of 30M -/// CALL(oracle) opcode: -/// - Marks oracle_accessed -/// - Compute gas limit tracked as 1M -/// -/// TIMESTAMP opcode: -/// - Marks block_env_accessed -/// - Compute gas limit remains min(1M, 20M) = 1M -/// -/// // Caller applies 1M compute gas limit to AdditionalLimit -/// ``` -/// -/// In Rex3+, the oracle access limit is also 20M, so both limits are equal. -#[derive(Debug, Clone)] -pub struct VolatileDataAccessTracker { - /// Unified bitmap tracking all types of volatile data access. - /// Includes block environment fields, beneficiary balance, and oracle access. - volatile_data_accessed: VolatileDataAccess, - /// The compute gas limit to enforce when volatile data is accessed. - compute_gas_limit: Option, - /// Compute gas limit when accessing block environment data. - block_env_access_limit: u64, - /// Compute gas limit when accessing oracle data. - oracle_access_limit: u64, - - /// The journal depth at which `disableVolatileDataAccess()` was activated (Rex4+). - /// `None` means inactive. `Some(depth)` means calls with - /// `journal.depth() >= depth` are restricted. - disable_depth: Option, -} - -impl VolatileDataAccessTracker { - /// Creates a new tracker with no accesses recorded and configurable limits. - pub fn new(block_env_access_limit: u64, oracle_access_limit: u64) -> Self { - Self { - volatile_data_accessed: VolatileDataAccess::empty(), - compute_gas_limit: None, - block_env_access_limit, - oracle_access_limit, - disable_depth: None, - } - } - - /// Checks if any volatile data has been accessed. - /// If so, the remaining gas in all message calls will be limited to a small amount of gas, - /// forcing the transaction to finish execution soon. - pub fn accessed(&self) -> bool { - !self.volatile_data_accessed.is_empty() - } - - /// Returns the bitmap of volatile data accessed during transaction execution. - /// Returns None if no volatile data has been accessed. - pub fn get_volatile_data_info(&self) -> Option { - self.accessed().then_some(self.volatile_data_accessed) - } - - /// Returns the compute gas limit for the accessed volatile data. - /// Returns None if no volatile data has been accessed. - pub fn get_compute_gas_limit(&self) -> Option { - self.compute_gas_limit - } - - /// Returns the bitmap of block environment data accessed during transaction execution. - pub fn get_block_env_accesses(&self) -> VolatileDataAccess { - self.volatile_data_accessed.block_env_only() - } - - /// Returns the bitmap of all volatile data accessed during transaction execution. - pub fn get_volatile_data_accessed(&self) -> VolatileDataAccess { - self.volatile_data_accessed - } - - /// Marks that a specific type of block environment has been accessed. - pub fn mark_block_env_accessed(&mut self, access_type: VolatileDataAccessType) { - self.volatile_data_accessed.insert(access_type.into()); - self.apply_or_create_limit(self.block_env_access_limit); - } - - /// Checks if beneficiary balance has been accessed. - pub fn has_accessed_beneficiary_balance(&self) -> bool { - self.volatile_data_accessed.has_beneficiary_balance_access() - } - - /// Marks that beneficiary balance has been accessed. - pub fn mark_beneficiary_balance_accessed(&mut self) { - self.volatile_data_accessed.insert(VolatileDataAccess::BENEFICIARY_BALANCE); - self.apply_or_create_limit(self.block_env_access_limit); - } - - /// Checks if the oracle contract has been accessed. - pub fn has_accessed_oracle(&self) -> bool { - self.volatile_data_accessed.has_oracle_access() - } - - /// Checks if the given address is the oracle contract address and marks it as accessed. - /// Applies the oracle access gas limit, which may further restrict gas if a less - /// restrictive limit was already in place. - pub fn check_and_mark_oracle_access(&mut self, address: &Address) -> bool { - if address == &ORACLE_CONTRACT_ADDRESS { - self.volatile_data_accessed.insert(VolatileDataAccess::ORACLE); - self.apply_or_create_limit(self.oracle_access_limit); - true - } else { - false - } - } - - /// Applies a compute gas limit or creates a new one if none exists. - /// If a limit already exists, applies the more restrictive limit (minimum of current and new). - fn apply_or_create_limit(&mut self, limit: u64) { - if let Some(current_limit) = self.compute_gas_limit { - // A limit already exists - apply the more restrictive one - self.compute_gas_limit = Some(current_limit.min(limit)); - } else { - // First volatile data access - set the initial limit - self.compute_gas_limit = Some(limit); - } - } - - /// Activates the volatile data access disable at the given depth. - /// - /// When active, `volatile_access_disabled(depth)` returns `true` for any - /// `depth` greater than or equal to `disable_depth`, causing the caller and - /// inner calls that access volatile data to revert with - /// `VolatileDataAccessDisabled()`. - /// - /// If already active, keeps the shallower (more restrictive) depth. - pub fn disable_access(&mut self, depth: usize) { - match self.disable_depth { - Some(current) if depth >= current => {} - _ => self.disable_depth = Some(depth), - } - } - - /// Checks if volatile data access is disabled at the given journal depth. - /// Returns `true` if `disable_depth` is set and `current_depth >= disable_depth`. - pub fn volatile_access_disabled(&self, current_depth: usize) -> bool { - self.disable_depth.is_some_and(|d| current_depth >= d) - } - - /// Re-enables volatile data access. - /// - /// Succeeds (returns `true`) if access is not disabled, or the caller is at the same - /// depth or shallower than the disabling frame (`caller_depth <= disable_depth`). - /// Fails (returns `false`) if a parent frame disabled access (`caller_depth > disable_depth`). - pub fn enable_access(&mut self, caller_depth: usize) -> bool { - match self.disable_depth { - None => true, - Some(d) if caller_depth <= d => { - self.disable_depth = None; - true - } - Some(_) => false, - } - } - - /// Deactivates the disable if the current depth has dropped below the disable depth. - /// - /// Called on frame return to ensure the disable only applies to the activating frame's - /// subtree and does not leak to sibling calls. - /// When the journal depth drops strictly below the disable depth, the frame that called - /// `disableVolatileDataAccess()` has returned and the restriction is no longer in scope. - pub fn enable_access_if_returning(&mut self, current_depth: usize) { - if self.disable_depth.is_some_and(|d| current_depth < d) { - self.disable_depth = None; - } - } - - /// Resets all access tracking for a new transaction. - /// Preserves the configured limits (only resets access state). - pub fn reset(&mut self) { - self.volatile_data_accessed = VolatileDataAccess::empty(); - self.compute_gas_limit = None; - self.disable_depth = None; - } - - /// Unions a volatile-access bitmap snapshot into this tracker. - /// Footprint only — the parameter type intentionally excludes detention state - /// (`compute_gas_limit`, `disable_depth`), which is frame-local. - pub fn merge_accesses_from_bitmap(&mut self, other_bitmap: VolatileDataAccess) { - self.volatile_data_accessed |= other_bitmap; - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::VolatileDataAccessType; - - #[test] - fn test_merge_accesses_from_bitmap_unions_bitmap_and_preserves_other_state() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - - parent.mark_block_env_accessed(VolatileDataAccessType::Timestamp); - let parent_cap_before = parent.get_compute_gas_limit(); - assert_eq!(parent_cap_before, Some(20_000_000)); - assert!(parent.get_volatile_data_accessed().contains(VolatileDataAccess::TIMESTAMP)); - - let snapshot = VolatileDataAccess::BLOCK_NUMBER | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - - let merged = parent.get_volatile_data_accessed(); - assert!(merged.contains(VolatileDataAccess::TIMESTAMP)); - assert!(merged.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(merged.contains(VolatileDataAccess::ORACLE)); - assert!(!merged.contains(VolatileDataAccess::BENEFICIARY_BALANCE)); - - assert_eq!(parent.get_compute_gas_limit(), parent_cap_before); - assert!(!parent.volatile_access_disabled(0)); - assert!(!parent.volatile_access_disabled(10)); - } - - #[test] - fn test_merge_accesses_from_bitmap_empty_snapshot_is_noop() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - parent.mark_beneficiary_balance_accessed(); - let before_bitmap = parent.get_volatile_data_accessed(); - let before_cap = parent.get_compute_gas_limit(); - - parent.merge_accesses_from_bitmap(VolatileDataAccess::empty()); - - assert_eq!(parent.get_volatile_data_accessed(), before_bitmap); - assert_eq!(parent.get_compute_gas_limit(), before_cap); - } - - #[test] - fn test_merge_accesses_from_bitmap_into_empty_parent_copies_bitmap_only() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - let snapshot = VolatileDataAccess::COINBASE | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - - let merged = parent.get_volatile_data_accessed(); - assert!(merged.contains(VolatileDataAccess::COINBASE)); - assert!(merged.contains(VolatileDataAccess::ORACLE)); - assert_eq!(parent.get_compute_gas_limit(), None); - assert!(!parent.volatile_access_disabled(0)); - assert!(!parent.volatile_access_disabled(3)); - } - - #[test] - fn test_merge_accesses_from_bitmap_is_idempotent() { - let mut parent = VolatileDataAccessTracker::new(20_000_000, 20_000_000); - let snapshot = VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE; - - parent.merge_accesses_from_bitmap(snapshot); - let after_first = parent.get_volatile_data_accessed(); - let cap_after_first = parent.get_compute_gas_limit(); - - parent.merge_accesses_from_bitmap(snapshot); - assert_eq!(parent.get_volatile_data_accessed(), after_first); - assert_eq!(parent.get_compute_gas_limit(), cap_after_first); - } -} diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs deleted file mode 100644 index 7d403357f..000000000 --- a/crates/mega-evm/src/access/volatile.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Volatile data access bitflags. - -use bitflags::bitflags; -use serde::{Deserialize, Serialize}; - -bitflags! { - /// Unified bitmap for tracking all types of volatile data access. - /// - /// This combines both fine-grained block environment tracking and coarse-grained - /// tracking of beneficiary balance and oracle contract access. - /// - /// Bits 0-9: Specific block environment fields (10 bits) - /// Bit 10: Beneficiary balance access - /// Bit 11: Oracle contract access - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] - pub struct VolatileDataAccess: u16 { - // Block environment fields (bits 0-9) - /// Block number (NUMBER opcode) - const BLOCK_NUMBER = 1 << 0; - /// Block timestamp (TIMESTAMP opcode) - const TIMESTAMP = 1 << 1; - /// Block coinbase/beneficiary (COINBASE opcode) - const COINBASE = 1 << 2; - /// Block difficulty (DIFFICULTY opcode) - const DIFFICULTY = 1 << 3; - /// Block gas limit (GASLIMIT opcode) - const GAS_LIMIT = 1 << 4; - /// Base fee per gas (BASEFEE opcode) - const BASE_FEE = 1 << 5; - /// Previous block randomness (PREVRANDAO opcode) - const PREV_RANDAO = 1 << 6; - /// Block hash lookup (BLOCKHASH opcode) - const BLOCK_HASH = 1 << 7; - /// Blob base fee per gas (BLOBBASEFEE opcode) - const BLOB_BASE_FEE = 1 << 8; - /// Blob hash lookup (BLOBHASH opcode) - const BLOB_HASH = 1 << 9; - - // Other volatile data types (bits 10-11) - /// Beneficiary balance was accessed - const BENEFICIARY_BALANCE = 1 << 10; - /// Oracle contract was accessed - const ORACLE = 1 << 11; - } -} - -impl VolatileDataAccess { - /// Mask for all block environment access flags (bits 0-9). - const BLOCK_ENV_MASK: u16 = 0b0000_0011_1111_1111; - - /// Checks if any block environment data has been accessed. - pub fn has_block_env_access(self) -> bool { - (self.bits() & Self::BLOCK_ENV_MASK) != 0 - } - - /// Checks if beneficiary balance has been accessed. - pub fn has_beneficiary_balance_access(self) -> bool { - self.contains(Self::BENEFICIARY_BALANCE) - } - - /// Checks if oracle contract has been accessed. - pub fn has_oracle_access(self) -> bool { - self.contains(Self::ORACLE) - } - - /// Counts the number of distinct block environment fields accessed. - pub fn count_block_env_accessed(self) -> usize { - (self.bits() & Self::BLOCK_ENV_MASK).count_ones() as usize - } - - /// Counts the number of distinct block environment fields accessed. - /// This is an alias for `count_block_env_accessed` for backward compatibility. - pub fn count_accessed(self) -> usize { - self.count_block_env_accessed() - } - - /// Gets the raw bitmap value. - pub const fn raw(self) -> u16 { - self.bits() - } - - /// Converts a single-bit flag to its bit position as a `u8`. - /// This matches the `VolatileDataAccessType` Solidity enum discriminant. - /// - /// # Panics - /// - /// Panics if `self` is empty (no bits set). - pub fn as_u8(self) -> u8 { - debug_assert!(!self.is_empty(), "cannot convert empty VolatileDataAccess to u8"); - self.bits().trailing_zeros() as u8 - } - - /// Returns only the block environment access portion as a separate bitflag. - /// This is useful for compatibility with code that expects only block env flags. - pub fn block_env_only(self) -> Self { - Self::from_bits_truncate(self.bits() & Self::BLOCK_ENV_MASK) - } -} - -impl From for VolatileDataAccess { - fn from(ty: crate::VolatileDataAccessType) -> Self { - Self::from_bits_truncate(1 << (ty as u8)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::VolatileDataAccessType; - - #[test] - fn test_empty_access_has_no_flags() { - let access = VolatileDataAccess::empty(); - - assert!(!access.has_block_env_access()); - assert!(!access.has_beneficiary_balance_access()); - assert!(!access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 0); - assert_eq!(access.count_accessed(), 0); - assert_eq!(access.block_env_only(), VolatileDataAccess::empty()); - assert_eq!(access.raw(), 0); - } - - #[test] - fn test_block_env_helpers_ignore_non_block_flags() { - let access = VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::BLOB_HASH | - VolatileDataAccess::BENEFICIARY_BALANCE | - VolatileDataAccess::ORACLE; - - assert!(access.has_block_env_access()); - assert!(access.has_beneficiary_balance_access()); - assert!(access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 2); - assert_eq!(access.count_accessed(), 2); - assert_eq!( - access.block_env_only(), - VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH - ); - assert_eq!(access.raw(), access.bits()); - } - - #[test] - fn test_from_volatile_data_access_type_covers_all_variants() { - let expected: &[(VolatileDataAccessType, VolatileDataAccess)] = &[ - (VolatileDataAccessType::BlockNumber, VolatileDataAccess::BLOCK_NUMBER), - (VolatileDataAccessType::Timestamp, VolatileDataAccess::TIMESTAMP), - (VolatileDataAccessType::Coinbase, VolatileDataAccess::COINBASE), - (VolatileDataAccessType::Difficulty, VolatileDataAccess::DIFFICULTY), - (VolatileDataAccessType::GasLimit, VolatileDataAccess::GAS_LIMIT), - (VolatileDataAccessType::BaseFee, VolatileDataAccess::BASE_FEE), - (VolatileDataAccessType::PrevRandao, VolatileDataAccess::PREV_RANDAO), - (VolatileDataAccessType::BlockHash, VolatileDataAccess::BLOCK_HASH), - (VolatileDataAccessType::BlobBaseFee, VolatileDataAccess::BLOB_BASE_FEE), - (VolatileDataAccessType::BlobHash, VolatileDataAccess::BLOB_HASH), - (VolatileDataAccessType::Beneficiary, VolatileDataAccess::BENEFICIARY_BALANCE), - (VolatileDataAccessType::Oracle, VolatileDataAccess::ORACLE), - ]; - - for &(access_type, expected_flag) in expected { - let converted = VolatileDataAccess::from(access_type); - assert_eq!(converted, expected_flag); - assert_eq!(converted.as_u8(), expected_flag.as_u8()); - } - } - - #[test] - fn test_all_block_env_flags_counted_correctly() { - let all_block_env = VolatileDataAccess::BLOCK_NUMBER | - VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::COINBASE | - VolatileDataAccess::DIFFICULTY | - VolatileDataAccess::GAS_LIMIT | - VolatileDataAccess::BASE_FEE | - VolatileDataAccess::PREV_RANDAO | - VolatileDataAccess::BLOCK_HASH | - VolatileDataAccess::BLOB_BASE_FEE | - VolatileDataAccess::BLOB_HASH; - - assert_eq!(all_block_env.count_block_env_accessed(), 10); - assert!(all_block_env.has_block_env_access()); - assert!(!all_block_env.has_beneficiary_balance_access()); - assert!(!all_block_env.has_oracle_access()); - assert_eq!(all_block_env.block_env_only(), all_block_env); - } -} diff --git a/crates/mega-evm/src/block/AGENTS.md b/crates/mega-evm/src/block/AGENTS.md deleted file mode 100644 index 090883e3c..000000000 --- a/crates/mega-evm/src/block/AGENTS.md +++ /dev/null @@ -1,70 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Block execution orchestration for MegaETH, including hardfork-to-spec resolution, system pre/post calls, and block-level resource admission. - -## STRUCTURE -- `executor.rs`: `MegaBlockExecutor` lifecycle, pre/post execution changes, tx commit policy. -- `factory.rs`: executor factory wiring from hardfork config and EVM factory. -- `hardfork.rs`: `MegaHardfork` definitions, activation checks, spec mapping. -- `chain.rs`: canonical chain IDs and per-chain hardfork activation schedules (mainnet, testnet, all-activated fallback for unknown chains). -- `limit.rs`: `BlockLimits` config and `BlockLimiter` pre/post checks. -- `eips.rs`: EIP system calls (blockhashes, beacon root, balance increments). -- `helpers.rs`: utility helpers for block execution. -- `result.rs`: block execution result types. - -## KEY PATTERNS -- Pre-execution and post-execution limits are intentionally separated. -- Pre-checks reject/skip before execution. -- Post-checks can drop outcomes before commit. -- System contract deployments are idempotent state patches, position-gated on the resolved spec. -- Executor constructor asserts hardfork/spec coherence for non-test builds. -- Block limiter state is cumulative and must be updated only on committed outcomes. -- `pre_execution_changes` collects `Option` outcomes from each helper into a vector; `commit_system_call_outcomes` walks them and calls `system_caller.on_state(source, &state)` **before** `db.commit(state)` for every entry. The `on_state` hook feeds the stateless witness generator with the complete read/write set. Helpers must therefore return all accounts and slots they touched (including reads). See `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT` for the helper-side contract. - -## INVARIANT MAP -The structural invariants of the spec ladder and fork schedule, indexed by where each is enforced and when it fires. -Guards live next to the tables they guard; this map is the index, not the home. - -Compile time (const assertions and exhaustive matches; a violation fails `cargo build`): -- `MegaSpecId::ALL` lists every spec in ladder order without gaps: `is_ladder_prefix` assertion in `evm/spec.rs`. -- The `behavior()` projection is flat — no alias chains or cycles, no upward targets: `is_flat_projection` assertion in `evm/spec.rs`. -- The fork→spec map is strictly ascending and therefore 1:1: `climbs_the_spec_ladder` assertion in `hardfork.rs`. -- Every new spec must be placed everywhere it matters: exhaustive matches in `ladder_index` (`evm/spec.rs`), the instruction table (`evm/instructions.rs`), precompiles (`evm/precompiles.rs`), and runtime limits (`evm/limit.rs`) fail compilation until the variant is wired; its fork is forced the same way by the matches on the fork enum in `MegaHardfork::spec_id` (`hardfork.rs`) and block limits (`limit.rs`). - -Chain-config load time: -- A published schedule climbs the ladder in activation order with required params attached: `MegaHardforks::validate_schedule` (`hardfork.rs`); `hardfork_schedule` (`chain.rs`) debug-asserts it, and node startup should call it. -- Per-fork params invariants hold: `HardforkParams::validate` runs inside `with_params` and panics at load time, not at the fork's first block. - -Block execution time: -- The cfg spec equals the schedule's resolution: executor constructor assert (compiled out under `test`/`test-utils`; pre-block setup reads the same cfg spec as `resolve_system_address`, so a tool overriding the cfg spec gets a coherent what-if rather than a hybrid block). -- A scheduled fork whose params are missing fails closed at its first block: registry checks in `executor.rs` and `system/sequencer_registry.rs`. - -Test time (`cargo test`): -- Alias dispatch grouping agrees with `behavior()`: reconciliation tests in `evm/instructions.rs`, `evm/precompiles.rs`, `evm/limit.rs`, and `limit.rs`. -- The resolved spec equals the maximum over activated forks on every schedule shape: `test_resolved_spec_is_the_maximum_over_activated_forks` (`hardfork.rs`). -- Position projections coincide with raw activation events: parity tests on every canonical schedule (`hardfork.rs`) and on a fully staged synthetic ladder (`tests/mutation/block.rs`). -- The const checkers themselves reject malformed inputs (the real tables can never exercise the negative path): `test_is_ladder_prefix_rejects_malformed_lists`, `test_is_flat_projection_rejects_malformed_tables`, `test_climbs_the_spec_ladder_rejects_malformed_lists`. -- Golden tables pin what derivation cannot: spec names and discriminant positions (`ALL_SPECS` in `evm/spec.rs`), the exact fork→spec pairs (`hardfork.rs`), and the pairing of load-time and pre-block params rules (`tests/block_executor/partial_ladder.rs`). - -CI: -- Spec-gate mutation testing probes boundary shifts and dispatch misroutes: `mutants/operators/spec-gate/` (behavior-introducing specs only; alias rungs are not on the behavior axis). - -## ANTI-PATTERNS -- Do not apply post-execution limit counters before a tx outcome is commit-eligible. -- Do not bypass `pre_execution_changes` in replay or simulation paths that aim for chain equivalence. -- Do not infer spec from tx fields. -- Gate on the one resolved spec through the right projection: `spec.is_enabled(MegaSpecId::X)` compares BEHAVIOR (both sides project through `behavior()`, so alias windows roll semantics back), `spec.reaches(MegaSpecId::X)` compares POSITION (one-way setup; alias windows do not retract it). The `is__active_at_timestamp` predicates are position projections for behavior-introducing forks and raw event queries for alias forks (`is_mini_rex_1/2_active_at_timestamp`), whose occurrence is not recoverable from the ladder; `mega_fork_activation` answers raw scheduling for any fork. -- A published chain schedule must pass `MegaHardforks::validate_schedule` (rung gaps, activation ordering, required per-fork params). The execution layer stays tolerant of malformed schedules — position-compared setup stays additive — but that tolerance is the fail-safe, not permission to publish one; `hardfork_schedule` debug-asserts it and node startup should check it. A new `HardforkParams` type must be registered in `validate_schedule`. -- One spec, two projections. `spec_id` is monotone (forks map 1:1 onto an ascending ladder; rollbacks are alias rungs like `MINI_REX_1`). Behavior (`is_enabled`) gates execution semantics: EVM behavior, block limits, transaction classification — it rolls back inside an alias window. Position (`reaches`) gates one-way chain setup: system-contract predeploys, pre-block rules, expected installed bytecode versions — retracting it during a rollback window would drop the Oracle predeploys' read-only witness entries that the on-state hook feeds to stateless proofs and the state-sync transition shard. -- Do not express "a chain running spec N" as `with_all_activated().without(fork)`. Removing a middle rung leaves later forks active, so the resolved spec stays at the top of the ladder. Use `with_all_activated_through(MegaSpecId::N)`. -- Do not hardcode gas-limit assumptions outside `BlockLimits` plumbing. -- Do not commit outcomes without first firing `on_state`. The two-step `on_state` → `commit` ordering is the witness-recorder contract; swapping or skipping it corrupts stateless proofs. - -## WHERE TO LOOK -- Add a new hardfork activation condition: `hardfork.rs` and `MegaHardforkConfig` wiring. -- Change when a fork activates on mainnet/testnet (or the unknown-chain fallback): `chain.rs`. -- Change tx inclusion behavior under block pressure: `limit.rs` and `executor.rs::run_transaction`/commit methods. -- Add pre-block or post-block system call: `eips.rs` and `executor.rs::{pre_execution_changes,post_execution_changes}`. -- Change block-level default limits for a hardfork: `limit.rs::from_hardfork_and_block_gas_limit`. -- Surface new block execution metadata: `result.rs`. diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index 885542a6f..90edcbda0 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -1,21 +1,10 @@ -//! Canonical per-chain `MegaETH` hardfork schedules. +//! Per-chain activation of the `MegaETH` hardforks of the Satin engine. //! -//! This is the single source of truth for when each [`MegaHardfork`] activates on -//! the known `MegaETH` chains. Tools that need a real chain schedule (the -//! `mega-evme` replay command, Foundry-based tooling, integration tests) should -//! use [`hardfork_schedule`] rather than re-declaring timestamps locally. -//! -//! Per-fork parameters that are chain-specific data — the -//! [`SequencerRegistryConfig`] seeded at Rex5 activation and the -//! [`SequencerRegistryRex6Config`] seeded at Rex6 activation — are attached here too. - -use alloy_hardforks::ForkCondition; -use alloy_primitives::address; +//! This is the single place that records when each [`MegaHardfork`](crate::MegaHardfork) +//! activates on the known `MegaETH` chains. The node chainspecs decide the schedule; this table +//! mirrors it for tools that replay a real chain. -use crate::{ - MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaSpecId, SequencerRegistryConfig, - SequencerRegistryRex6Config, MEGA_SYSTEM_ADDRESS, -}; +use alloy_primitives::BlockTimestamp; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -23,234 +12,40 @@ pub const MAINNET_CHAIN_ID: u64 = 4326; /// `MegaETH` testnet v2 chain ID. pub const TESTNET_CHAIN_ID: u64 = 6343; -/// Governance parameter seeded into the v2.0.0 `SequencerRegistry` at Rex6 init on both -/// live networks: the minimum scheduling-to-activation delay (`_minRotationDelay`), in -/// blocks. Must equal the `rex6MinRotationDelay` the operator genesis attaches; the live -/// value is readable via `minRotationDelay()` on `0x6342…0006`. One constant for both -/// schedules, so a network diverging from the other is a deliberate edit rather than a -/// silent difference. -const REX6_MIN_ROTATION_DELAY: u64 = 21_600; - -/// Canonical hardfork schedule for `MegaETH` mainnet (chain `4326`). -pub fn mainnet_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(1764845637)) - .with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(1764849932)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(1764851940)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(1766282400)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(1770246000)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(1771639200)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(1776659200)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(1780632000)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1787626800)) - // Seeded values read from the on-chain SequencerRegistry (0x6342…0006) at - // Rex5 init: INITIAL_SEQUENCER (slot 5) and the admin (slot 2). At replay - // time these only satisfy the activation guard — the live system address - // is read from forked registry storage. - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: address!("0x7a49197dd1ebb8d38c67e4eb7626af6ade432445"), - rex5_initial_admin: address!("0x92e0e0b15e3e99b32c9ed9ad284f939553c7b7d6"), - }) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: REX6_MIN_ROTATION_DELAY, - }) +/// Activation timestamps of the Satin-engine hardforks on one chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChainActivation { + /// The chain the timestamps belong to. + pub chain_id: u64, + /// When [`MegaHardfork::Satin`](crate::MegaHardfork::Satin) activates; `None` while it is + /// not scheduled. + pub satin: Option, } -/// Canonical hardfork schedule for `MegaETH` testnet v2 (chain `6343`). -pub fn testnet_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::MiniRex1, ForkCondition::Never) - .with(MegaHardfork::MiniRex2, ForkCondition::Never) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(1764694618)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(1766147599)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(1770116400)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(1771380000)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(1776400000)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(1780459200)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1786330800)) - // Seeded values read from the on-chain SequencerRegistry (0x6342…0006) at - // Rex5 init on testnet: INITIAL_SEQUENCER (slot 5) and the admin (slot 2). - // At replay time these only satisfy the activation guard — the live system - // address is read from forked registry storage. - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: address!("0xB8DB54eBA7Ae650d14F362de461516a4FF1551FC"), - rex5_initial_admin: address!("0x1d9BD232C44B39341e670B735c7F423c40426b34"), - }) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: REX6_MIN_ROTATION_DELAY, - }) -} - -/// All `MegaETH` hardforks activated at genesis. -/// -/// Used for unknown chains and local/standalone execution where the chain has no -/// published schedule. Rex5 requires a [`SequencerRegistryConfig`] (block -/// execution fails pre-block without one), and an unknown chain has no published -/// roles, so both roles are seeded with [`MEGA_SYSTEM_ADDRESS`] as a -/// placeholder. The placeholder only matters when bootstrapping a fresh -/// registry: on a chain whose registry is already deployed, the live roles are -/// read from the registry's storage. -/// -/// Rex6 (active at genesis here too) likewise requires a -/// [`SequencerRegistryRex6Config`] for the v2.0.0 registry deploy. The fallback -/// seeds the smallest valid rotation delay (1 block) so local and dev chains can -/// exercise rotations without friction; a real network must attach a -/// governance-approved value in its published schedule when it schedules Rex6. -/// -/// The rung is named explicitly rather than inherited from [`MegaSpecId::default`]. -/// These chains run at genesis, so the rung *is* their semantics from block zero, -/// with no fork boundary to separate an old rule from a new one. Introducing a spec -/// must therefore not move them: a devnet that produced history under this fallback -/// would otherwise replay differently — through [`hardfork_schedule`], which is what -/// `mega-evme replay` resolves an unknown chain ID with — against the same binary -/// that produced it. Advancing this rung is a deliberate edit; it currently names -/// `REX7`, the unstable development head, which carries no behavior of its own yet, -/// so dev chains track the newest semantics at no cost. -pub fn all_activated_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with_all_activated_through(MegaSpecId::REX7) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: MEGA_SYSTEM_ADDRESS, - }) - .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }) -} +/// Activation table of the known `MegaETH` chains. +pub const CHAIN_ACTIVATIONS: [ChainActivation; 2] = [ + ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: None }, + ChainActivation { chain_id: TESTNET_CHAIN_ID, satin: None }, +]; -/// Returns the canonical hardfork schedule for a chain ID. -/// -/// Mainnet (`4326`) and testnet v2 (`6343`) use their published schedules; any -/// other chain gets [`all_activated_hardforks`]. -pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { - let schedule = match chain_id { - MAINNET_CHAIN_ID => mainnet_hardforks(), - TESTNET_CHAIN_ID => testnet_hardforks(), - _ => all_activated_hardforks(), - }; - // The canonical schedules are edited by hand; a malformed edit must fail at the first - // resolution, not at the first block that happens to expose it. - debug_assert_eq!(schedule.validate_schedule(), Ok(())); - schedule +/// The activation table of a known chain, or `None` for any other chain. +pub fn chain_activation(chain_id: u64) -> Option { + CHAIN_ACTIVATIONS.iter().find(|activation| activation.chain_id == chain_id).copied() } #[cfg(test)] mod tests { use super::*; - use crate::{MegaHardfork, MegaHardforks, MegaSpecId}; - - #[test] - fn test_mainnet_schedule_resolves_specs_by_timestamp() { - let hf = mainnet_hardforks(); - assert_eq!(hf.spec_id(1764851940), MegaSpecId::REX); - assert_eq!(hf.spec_id(1776659200), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780631999), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780632000), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1787626799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1787626800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } - - #[test] - fn test_testnet_schedule_resolves_specs_by_timestamp() { - let hf = testnet_hardforks(); - assert_eq!(hf.spec_id(1776400000), MegaSpecId::REX4); - // Just before Rex5, still Rex4; at/after Rex5, Rex5. - assert_eq!(hf.spec_id(1780459199), MegaSpecId::REX4); - assert_eq!(hf.spec_id(1780459200), MegaSpecId::REX5); - // Just before Rex6, still Rex5; at/after Rex6, Rex6. - assert_eq!(hf.spec_id(1786330799), MegaSpecId::REX5); - assert_eq!(hf.spec_id(1786330800), MegaSpecId::REX6); - // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. - assert!(hf.fork_params::().is_some()); - assert!(hf.fork_params::().is_some()); - } #[test] - fn test_schedule_dispatch_by_chain_id() { - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1780632000), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1780459200), MegaSpecId::REX5); - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1787626800), MegaSpecId::REX6); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1786330800), MegaSpecId::REX6); - // Unknown chain: every fork up to the pinned rung, active at genesis. - assert_eq!(hardfork_schedule(1).spec_id(0), MegaSpecId::REX7); - } - - #[test] - fn test_canonical_schedules_activate_rex6_and_pin_rex7_never() { - // Rex6 is scheduled on both networks at the published timestamps (testnet - // 2026-08-10, mainnet 2026-08-25) and carries the governance-seeded rotation - // delay. Rex7 is still unstable and must not appear in a canonical schedule - // until governance publishes a timestamp: an accidental entry here would - // fork the live chains at that timestamp. - for (hf, rex6_activation) in - [(mainnet_hardforks(), 1787626800), (testnet_hardforks(), 1786330800)] - { - assert_eq!( - hf.mega_fork_activation(MegaHardfork::Rex6), - ForkCondition::Timestamp(rex6_activation) - ); - assert_eq!(hf.mega_fork_activation(MegaHardfork::Rex7), ForkCondition::Never); - // Rex6 is therefore the terminal spec on both chains, at any later timestamp. - assert_eq!(hf.spec_id(u64::MAX), MegaSpecId::REX6); - let params = hf - .fork_params::() - .expect("canonical schedules must carry a SequencerRegistryRex6Config"); - assert_eq!(params.rex6_min_rotation_delay, 21600); - } - } - - #[test] - fn test_unknown_chain_fallback_carries_sequencer_registry_config() { - // Rex5 block execution fails pre-block without a SequencerRegistryConfig, - // so the all-activated fallback must attach placeholder roles. - let hf = hardfork_schedule(999_999); - assert_eq!(hf.spec_id(0), MegaSpecId::REX7); - let params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryConfig"); - assert_eq!(params.rex5_initial_sequencer, MEGA_SYSTEM_ADDRESS); - assert_eq!(params.rex5_initial_admin, MEGA_SYSTEM_ADDRESS); - // Rex6 is also active at genesis in the fallback, and the v2.0.0 registry - // deploy fails pre-block without a SequencerRegistryRex6Config — without - // this, every unknown-chain block aborts before the registry can deploy. - let rex6_params = hf - .fork_params::() - .expect("fallback schedule must carry a SequencerRegistryRex6Config"); - assert!(rex6_params.rex6_min_rotation_delay > 0); - } - - /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. - /// - /// Unknown chains run their rung from genesis, so it is their semantics from block zero with - /// no fork boundary. Introducing a spec must therefore leave them alone: registering a fork - /// above the pinned rung would rewrite what history they have already produced means, and - /// `mega-evme replay` resolves an unknown chain ID through this same schedule. - /// - /// A newly introduced spec leaves this test green — the pin holding still is the safe - /// direction, so nothing fails to force a decision. What the test pins is drift: the - /// fallback silently following `MegaSpecId::default` again (it fails here once the default - /// advances past the rung), and the rung advancing without this `RUNG` constant being edited - /// in the same change. - #[test] - fn test_unknown_chain_fallback_pins_its_rung() { - let hf = all_activated_hardforks(); - const RUNG: MegaSpecId = MegaSpecId::REX7; - - assert_eq!(hf.spec_id(0), RUNG, "the rung applies from genesis"); - assert_eq!(hf.spec_id(u64::MAX), RUNG, "and is terminal — no later fork is registered"); - - for fork in MegaHardfork::VARIANTS { - let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; - assert_eq!( - registered, - RUNG.is_enabled(fork.spec_id()), - "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" - ); + fn test_known_chains_have_satin_unscheduled() { + assert_eq!(MAINNET_CHAIN_ID, 4326); + assert_eq!(TESTNET_CHAIN_ID, 6343); + for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID] { + let activation = chain_activation(chain_id).expect("known chain"); + assert_eq!(activation.chain_id, chain_id); + assert_eq!(activation.satin, None, "Satin has no activation timestamp yet"); } + assert_eq!(chain_activation(1), None); } } diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs deleted file mode 100644 index 13056deb6..000000000 --- a/crates/mega-evm/src/block/eips.rs +++ /dev/null @@ -1,272 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, string::ToString}; - -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - Evm, -}; -use alloy_primitives::{Address, B256, U256}; -use revm::{ - context_interface::result::ResultAndState, - database::State, - state::{Account, EvmState}, - Database, Inspector, -}; - -use crate::{ - block::hardfork::MegaHardforks, ExternalEnvTypes, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, -}; - -/// Applies the pre-block call to the [EIP-2935] blockhashes contract, using the given block, -/// chain specification, and EVM. -/// -/// If Prague is not activated, or the block is the genesis block, then this is a no-op, and no -/// state changes are made. -/// -/// Note: this does not commit the state changes to the database, it only transact the call. -/// -/// Returns `None` if Prague is not active or the block is the genesis block, otherwise returns the -/// result of the call. -/// -/// Rex5+: the system call is issued with `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` -/// (matching `SequencerRegistry` pre-block helpers) instead of revm's upstream-fixed 30M -/// default. The EIP-2935 history-storage write cost depends on Rex5 dynamic storage gas, so -/// the 30M default is no longer guaranteed to be enough on high-SALT-bucket blocks. -/// Pre-Rex5 keeps the original `transact_system_call` (30M) path for replay parity. -/// -/// [EIP-2935]: https://eips.ethereum.org/EIPS/eip-2935 -#[inline] -pub(crate) fn transact_blockhashes_contract_call( - hardforks: H, - setup_spec: MegaSpecId, - parent_block_hash: B256, - evm: &mut MegaEvm, -) -> Result>, BlockExecutionError> -where - H: MegaHardforks, - DB: alloy_evm::Database, - ExtEnvs: ExternalEnvTypes, - INSP: Inspector>, -{ - let block_timestamp: u64 = evm.block().timestamp.saturating_to(); - if !hardforks.is_prague_active_at_timestamp(block_timestamp) { - return Ok(None); - } - - // if the block number is zero (genesis block) then no system transaction may occur as per - // EIP-2935 - if evm.block().number.is_zero() { - return Ok(None); - } - - let res = if setup_spec.reaches(MegaSpecId::REX5) { - let gas_limit = - evm.block().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - parent_block_hash.0.into(), - gas_limit, - ) - } else { - evm.transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - parent_block_hash.0.into(), - ) - }; - - match res { - Ok(res) => Ok(Some(res)), - Err(e) => { - Err(BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) - } - } -} - -/// Applies the pre-block call to the [EIP-4788] beacon block root contract, using the given block, -/// chain spec, EVM. -/// -/// Note: this does not commit the state changes to the database, it only transact the call. -/// -/// Returns `None` if Cancun is not active or the block is the genesis block, otherwise returns the -/// result of the call. -/// -/// Rex5+: see [`transact_blockhashes_contract_call`] for the gas-limit override rationale — -/// the beacon-root SSTORE shares the same dynamic-storage-gas exposure. -/// -/// [EIP-4788]: https://eips.ethereum.org/EIPS/eip-4788 -#[inline] -pub(crate) fn transact_beacon_root_contract_call( - hardforks: H, - setup_spec: MegaSpecId, - parent_beacon_block_root: Option, - evm: &mut MegaEvm, -) -> Result>, BlockExecutionError> -where - H: MegaHardforks, - DB: alloy_evm::Database, - ExtEnvs: ExternalEnvTypes, - INSP: Inspector>, -{ - let block_timestamp: u64 = evm.block().timestamp.saturating_to(); - if !hardforks.is_cancun_active_at_timestamp(block_timestamp) { - return Ok(None); - } - - let parent_beacon_block_root = - parent_beacon_block_root.ok_or(BlockValidationError::MissingParentBeaconBlockRoot)?; - - // if the block number is zero (genesis block) then the parent beacon block root must - // be 0x0 and no system transaction may occur as per EIP-4788 - if evm.block().number.is_zero() { - if !parent_beacon_block_root.is_zero() { - return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { - parent_beacon_block_root, - } - .into()); - } - return Ok(None); - } - - let res = if setup_spec.reaches(MegaSpecId::REX5) { - let gas_limit = - evm.block().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - gas_limit, - ) - } else { - evm.transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - ) - }; - - match res { - Ok(res) => Ok(Some(res)), - Err(e) => Err(BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: e.to_string(), - } - .into()), - } -} - -/// Transacts the balance increments and returns the post evm state. Note that the changes are not -/// committed to the given db. -pub(crate) fn transact_balance_increments( - balances: impl IntoIterator, - db: &mut State, -) -> Result, DB::Error> { - let balances = balances.into_iter(); - let mut state = EvmState::default(); - - for (address, balance_increment) in balances { - if balance_increment == 0 { - continue; - } - let cache_account = db.load_cache_account(address)?; - let account_info = cache_account.account_info().unwrap_or_default(); - let mut account = Account::default().with_info(account_info); - account.info.balance += U256::from(balance_increment); - account.mark_touch(); - state.insert(address, account); - } - - Ok(Some(state)) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; - - #[test] - fn test_balance_increment_commit_equivalence() { - // This is the most important test: verify that our approach is equivalent - // to the original increment_balances + balance_increment_state approach - - // Setup: create two identical database states - let addr1 = address!("0x1000000000000000000000000000000000000001"); - let addr2 = address!("0x2000000000000000000000000000000000000002"); - let addr3 = address!("0x3000000000000000000000000000000000000003"); - - // Fund only addr1 and addr2, but leave addr3 empty (non-existent) - let setup_db = |db: &mut InMemoryDB| { - for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { - db.insert_account_info( - addr, - AccountInfo { - balance: U256::from(balance), - nonce, - code_hash: alloy_primitives::B256::ZERO, - code: None, - }, - ); - } - }; - - // Setup database 1: will use original approach (increment_balances) - let mut db1 = InMemoryDB::default(); - setup_db(&mut db1); - let mut state1 = State::builder().with_database(&mut db1).build(); - - // Setup database 2: will use our approach (transact_balance_increments + commit) - let mut db2 = InMemoryDB::default(); - setup_db(&mut db2); - let mut state2 = State::builder().with_database(&mut db2).build(); - - // Apply balance increments - let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; - - // Method 1: Original approach - state1 - .increment_balances(balance_increments.clone()) - .expect("increment_balances should succeed"); - - // Method 2: Refactored approach (transact + commit, matching the actual usage pattern) - // The refactoring separates increment_balances into two steps: - // 1. transact_balance_increments() - produces EvmState delta - // 2. commit() - integrates the delta and fixes status transitions - // This allows extracting the intermediate state for system_caller.on_state() hooks - let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) - .expect("transact_balance_increments should succeed") - .expect("Should return state"); - - // Commit the state changes (this applies proper status transitions via apply_evm_state) - state2.commit(result_state); - - // Verify final states match after both approaches - for (addr, _expected_increment) in balance_increments { - let account1 = state1.load_cache_account(addr).expect("Should load from state1"); - let account2 = state2.load_cache_account(addr).expect("Should load from state2"); - - let info1 = account1.account_info().expect("Should have account info"); - let info2 = account2.account_info().expect("Should have account info"); - - assert_eq!( - info1.balance, info2.balance, - "Balance for {:?} should be identical after both methods", - addr - ); - assert_eq!(info1.nonce, info2.nonce, "Nonce for {:?} should be identical", addr); - assert_eq!( - info1.code_hash, info2.code_hash, - "Code hash for {:?} should be identical", - addr - ); - assert_eq!( - account1.status, account2.status, - "Account status for {:?} should be identical after both methods", - addr - ); - } - } -} diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index c4ddfea54..cd65aa3bc 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -1,751 +1,54 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, collections::BTreeMap, vec::Vec}; +//! Block executor of the Satin engine. +//! +//! Block execution lands here with the block executor: alloy-evm's `BlockExecutor` over a +//! [`MegaEvm`](crate::MegaEvm), the Karst block rules, the pre-block system calls and +//! system contract deployments, and the block-level limits. -use alloy_consensus::{Eip658Value, Header, Transaction, TxReceipt}; -use alloy_eips::{Encodable2718, Typed2718}; -pub use alloy_evm::block::CommitChanges; -use alloy_evm::{ - block::{ - state_changes::post_block_balance_increments, BlockExecutionError, BlockExecutionResult, - BlockValidationError, ExecutableTx, OnStateHook, StateChangePostBlockSource, - StateChangePreBlockSource, StateChangeSource, SystemCaller, - }, - eth::receipt_builder::ReceiptBuilderCtx, - Database, Evm as _, FromRecoveredTx, FromTxWithEncoded, IntoTxEnv, RecoveredTx, -}; -use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; -use alloy_primitives::B256; -use op_alloy_consensus::OpDepositReceipt; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; -use revm::{ - context::result::{ExecResultAndState, ExecutionResult}, - database::State, - handler::EvmTr, - DatabaseCommit, Inspector, -}; - -use crate::{ - block::eips, flat_system_contract_specs_for, is_apply_pending_changes_due, - resolve_system_address, transact_apply_pending_changes, transact_deploy, - transact_deploy_sequencer_registry_for, BlockLimiter, BlockMegaTransactionOutcome, BucketId, - MegaBlockExecutionCtx, MegaHardforks, MegaSpecId, MegaSystemCallOutcome, MegaTransaction, - MegaTransactionExt, MegaTransactionOutcome, SequencerRegistryConfig, - SequencerRegistryRex6Config, -}; - -/// Block executor for the `MegaETH` chain. -/// -/// A block executor that processes transactions within a block using `MegaETH`-specific -/// EVM specifications and optimizations. This executor wraps the Optimism block executor -/// and provides access to `MegaETH` features such as enhanced security measures, increased -/// contract size limits, and block environment access tracking for parallel execution. -/// -/// # Generic Parameters -/// -/// - `H`: The hardfork configuration implementing `MegaHardforks` -/// - `E`: The EVM type implementing `alloy_evm::Evm` -/// - `R`: The receipt builder implementing `OpReceiptBuilder` -/// -/// # Implementation Strategy +/// Executes the transactions of one block on a Satin EVM. /// -/// This executor uses the delegation pattern to efficiently wrap the underlying Optimism -/// block executor (`OpBlockExecutor`) while providing MegaETH-specific customizations. -/// The delegation ensures minimal overhead while maintaining full compatibility with -/// the Optimism EVM infrastructure. -pub struct MegaBlockExecutor { - hardforks: H, - receipt_builder: R, - ctx: MegaBlockExecutionCtx, - system_caller: SystemCaller, - /// The inner evm instance. - pub evm: E, - /// The block limiter for tracking the limit usage. - pub block_limiter: BlockLimiter, - /// The receipts for the transactions in the block. - pub receipts: Vec, +/// A skeleton for now: it owns the EVM and hands it back. +#[derive(Debug)] +pub struct MegaBlockExecutor { + evm: E, } -impl core::fmt::Debug for MegaBlockExecutor { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethBlockExecutor").finish_non_exhaustive() - } -} - -impl<'db, DB, H, R, INSP, ExtEnvs> - MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - H: MegaHardforks + Clone, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder, -{ - /// Create a new block executor. - /// - /// # Parameters - /// - /// - `evm`: The EVM instance to use for transaction execution - /// - `ctx`: The block execution context for tracking access patterns - /// - `hardforks`: The hardforks configuration implementing [`MegaHardforks`] - /// - `receipt_builder`: The receipt builder for processing transaction receipts - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn new( - evm: crate::MegaEvm<&'db mut State, INSP, ExtEnvs>, - ctx: MegaBlockExecutionCtx, - hardforks: H, - receipt_builder: R, - ) -> Self { - // Sanity check: spec id must match hardfork - let block_timestamp = evm.block().timestamp.saturating_to(); - #[cfg(not(any(test, feature = "test-utils")))] - { - use crate::HostExt; - let spec_id = evm.spec_id(); - let expected_spec_id = hardforks.spec_id(block_timestamp); - assert_eq!( - spec_id, expected_spec_id, - "The spec id {} in cfg env must match the expected spec id {} for timestamp {}", - spec_id, expected_spec_id, block_timestamp - ); - } - assert!( - hardforks.is_regolith_active_at_timestamp(block_timestamp), - "mega-evm assumes Regolith hardfork is always active" - ); - assert!( - hardforks.is_canyon_active_at_timestamp(block_timestamp), - "mega-evm assumes Canyon hardfork is always active" - ); - assert!( - hardforks.is_isthmus_active_at_timestamp(block_timestamp), - "mega-evm assumes Isthmus hardfork is always active" - ); - - #[cfg(not(any(test, feature = "test-utils")))] - assert!( - ctx.block_limits.block_gas_limit == evm.block().gas_limit, - "block gas limit must be set to the block env gas limit" - ); - - Self { - hardforks: hardforks.clone(), - receipt_builder, - receipts: Vec::new(), - block_limiter: ctx.block_limits.to_block_limiter(), - ctx, - evm, - system_caller: SystemCaller::new(hardforks), - } - } - - /// Gets a mutable reference to the inspector in the `MegaEVM`. - pub fn inspector_mut(&mut self) -> &mut INSP { - self.evm.inspector_mut() - } - - /// Gets a reference to the inspector in the `MegaEVM`. - pub fn inspector(&self) -> &INSP { - self.evm.inspector() - } -} - -impl<'db, DB, C, R, INSP, ExtEnvs> - MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - C: MegaHardforks, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder< - Transaction: Transaction + Encodable2718 + MegaTransactionExt, - Receipt: TxReceipt, - >, -{ - /// Make pre-execution changes on the state. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn pre_execution_changes( - &mut self, - ) -> Result, BlockExecutionError> { - let mut outcomes = Vec::new(); - - // In MegaETH, the Spurious Dragon hardfork is always active, so we can safely set the state - // clear flag to true. - self.evm.db_mut().set_state_clear_flag(true); - - // Every pre-block gate below derives from the executing spec in the EVM's cfg — the - // same source `resolve_system_address` reads — compared by POSITION (`reaches`): setup - // stays additive by construction — a config that schedules only a later fork still gets - // every earlier fork's predeploys and fail-closed checks, and an alias window - // (`MINI_REX_1`, live on mainnet) rolls back behavior without dropping the Oracle - // predeploys or their read-only witness entries. On node paths the constructor asserts - // this spec equals the schedule's resolution; tools that override the cfg spec get a - // coherent what-if (setup and execution move together) instead of a hybrid block. - let setup_spec = self.evm.ctx().mega_spec(); - let is_rex_5 = setup_spec.reaches(MegaSpecId::REX5); - - // EIP-2935 - let result_and_state = eips::transact_blockhashes_contract_call( - &self.hardforks, - setup_spec, - self.ctx.parent_hash, - &mut self.evm, - )?; - if let Some(ExecResultAndState { result, state }) = result_and_state { - if is_rex_5 && !result.is_success() { - return Err(BlockValidationError::BlockHashContractCall { - message: std::format!( - "EIP-2935 pre-block system call did not succeed: {result:?}" - ), - } - .into()); - } - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PreBlock(StateChangePreBlockSource::BlockHashesContract), - state, - }); - } - - // EIP-4788 - let result_and_state = eips::transact_beacon_root_contract_call( - &self.hardforks, - setup_spec, - self.ctx.parent_beacon_block_root, - &mut self.evm, - )?; - if let Some(ExecResultAndState { result, state }) = result_and_state { - if is_rex_5 && !result.is_success() { - let parent_beacon_block_root = - self.ctx.parent_beacon_block_root.unwrap_or_default(); - return Err(BlockValidationError::BeaconRootContractCall { - parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: std::format!( - "EIP-4788 pre-block system call did not succeed: {result:?}" - ), - } - .into()); - } - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PreBlock(StateChangePreBlockSource::BeaconRootContract), - state, - }); - } - - // In MegaETH, the Isthmus hardfork is always active, which means the Canyon hardfork has - // already activated and the create2 deployer is already deployed, so we can safely assume - // that `ensure_create2_deployer` function will never be called. - - // Flat system contracts (Oracle, high-precision timestamp Oracle, KeylessDeploy, - // MegaAccessControl, MegaLimitControl) share one deploy path via the canonical - // registry. We tentatively use `StateChangeSource::Transaction(0)` as the state - // change source, as alloy defines no specific source for these predeploys. - for spec in flat_system_contract_specs_for(setup_spec) { - let state = - transact_deploy(self.evm.db_mut(), &spec).map_err(BlockExecutionError::other)?; - outcomes - .push(MegaSystemCallOutcome { source: StateChangeSource::Transaction(0), state }); - } - - // Rex5 hardfork: deploy SequencerRegistry (first block only) and apply pending - // role changes if any are due. - let block_number = self.evm.block().number.to::(); - if is_rex_5 { - // Deploy: seeds system address, sequencer, admin, and initialFromBlock - // into storage on first deploy. - // Cloned so the helper below can take `&mut self`; a few words, once per block. - let params = self - .hardforks - .fork_params::() - .ok_or_else(|| BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistryConfig not configured".into(), - })? - .clone(); - let rex6_params = self.hardforks.fork_params::().cloned(); - - // The deploy and apply-pending-changes outcomes commit in push order, while the - // apply system call always executes against the not-yet-committed state and thus - // carries the pre-deploy account info in its result. Pre-Rex6 both record the - // same v1.0.0 code, so the order is irrelevant; at the Rex6 activation block the - // deploy performs the in-place v1 → v2 bytecode upgrade (when a v1 registry - // exists), and an apply outcome committed after it would overwrite the upgraded - // account info with the stale pre-upgrade code. From Rex6 the apply call - // therefore runs BEFORE the deploy so the upgrade outcome commits last; the - // `applyPendingChanges()` logic is identical in v1/v2 (v2 changes only rotation - // scheduling), so its semantics do not depend on which side of the deploy it - // executes. Pre-Rex6 blocks keep the original deploy-then-apply order untouched. - let is_rex_6 = setup_spec.reaches(MegaSpecId::REX6); - - if !is_rex_6 { - self.push_deploy_sequencer_registry_outcome( - setup_spec, - rex6_params.as_ref(), - block_number, - ¶ms, - &mut outcomes, - )?; - } - - // Apply pending role changes if any are due. - // NOTE: The pre-check reads from the DB *before* the deploy outcome is committed. - // On the bootstrap block, the registry account does not yet exist in the DB, - // so the pre-check returns false. This is correct because deploy does not seed - // any pending slots. - let (due, witness_state) = - is_apply_pending_changes_due(self.evm.db_mut(), block_number)?; - // Always push the witness state (read-only account + slot records). - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::Transaction(0), - state: witness_state, - }); - if due { - let ExecResultAndState { state, .. } = - transact_apply_pending_changes(&mut self.evm)?; - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::Transaction(0), - state, - }); - } - - if is_rex_6 { - self.push_deploy_sequencer_registry_outcome( - setup_spec, - rex6_params.as_ref(), - block_number, - ¶ms, - &mut outcomes, - )?; - } - } - - Ok(outcomes) - } - - /// Runs the `SequencerRegistry` deploy (bootstrap, in-place upgrade, or idempotent no-op) - /// and pushes its outcome. - fn push_deploy_sequencer_registry_outcome( - &mut self, - setup_spec: MegaSpecId, - rex6_params: Option<&SequencerRegistryRex6Config>, - block_number: u64, - params: &SequencerRegistryConfig, - outcomes: &mut Vec, - ) -> Result<(), BlockExecutionError> { - let result_and_state = transact_deploy_sequencer_registry_for( - setup_spec, - rex6_params, - block_number, - self.evm.db_mut(), - params, - )?; - if let Some(state) = result_and_state { - outcomes - .push(MegaSystemCallOutcome { source: StateChangeSource::Transaction(0), state }); - } - Ok(()) - } - - /// Make post-execution changes on the state. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn post_execution_changes( - &mut self, - ) -> Result, BlockExecutionError> { - let mut outcomes = Vec::new(); - - // post block balance increments - let balance_increments = - post_block_balance_increments::
(&self.hardforks, self.evm.block(), &[], None); - // self.evm - // .db_mut() - // .increment_balances(balance_increments.clone()) - // .map_err(|_| BlockValidationError::IncrementBalanceFailed)?; - // let state = balance_increment_state(&balance_increments, self.evm.db_mut())?; - let state = eips::transact_balance_increments(balance_increments, self.evm.db_mut()) - .map_err(BlockExecutionError::other)?; - if let Some(state) = state { - outcomes.push(MegaSystemCallOutcome { - source: StateChangeSource::PostBlock(StateChangePostBlockSource::BalanceIncrements), - state, - }); - } - - Ok(outcomes) - } - - /// Commit the system call outcomes to the internal state of the block executor. - pub fn commit_system_call_outcomes( - &mut self, - outcomes: Vec, - ) -> Result<(), BlockExecutionError> { - for outcome in outcomes { - self.system_caller.on_state(outcome.source, &outcome.state); - self.evm.db_mut().commit(outcome.state); - } - - Ok(()) - } - - /// Alias to [`MegaBlockExecutor::run_transaction`]. - pub fn execute_mega_transaction( - &mut self, - tx: Tx, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv - + RecoveredTx - + MegaTransactionExt - + Encodable2718 - + Copy, - { - self.run_transaction(tx) +impl MegaBlockExecutor { + /// Creates an executor that runs the block on `evm`. + pub const fn new(evm: E) -> Self { + Self { evm } } - /// Execute a transaction with a commit condition function without committing the execution - /// result to the block executor's inner state. - /// - /// `tx_size`/`da_size` are resolved from `Tx` through [`MegaTransactionExt`]: a `Tx` that - /// carries precomputed values (e.g. [`crate::EnrichedMegaTx`]) reuses them, while any other - /// `Tx` falls back to the trait's default, which recomputes them from the EIP-2718 encoding. - /// The choice is resolved at compile time by trait dispatch, so callers do not pick a - /// variant — this is the single execution entry point regardless of whether the transaction - /// carries a size cache. - /// - /// The `alloy_evm` block-execution path - /// ([`alloy_evm::block::BlockExecutor::execute_transaction_with_commit_condition`]) does not - /// route through this method: its `tx: impl ExecutableTx` parameter cannot be required - /// to implement [`MegaTransactionExt`], so it recomputes the sizes itself and calls - /// [`MegaBlockExecutor::run_transaction_with_sizes`] directly. - /// - /// # Correctness - /// - /// `tx_size`/`da_size` feed directly into [`BlockLimiter::pre_execution_check`]'s - /// `tx_encode_size_limit`/`tx_da_size_limit`/block cumulative-size checks. When `Tx` - /// overrides the defaults with cached values, those values are trusted with no validation - /// against the real encoded transaction: callers MUST ensure `Tx::tx_size()`/ - /// `Tx::estimated_da_size()` accurately reflect `tx`'s actual EIP-2718 encoding — an - /// understated value lets a transaction bypass a limit it should have been rejected by. - /// This is safe for the sequencer's own block-building path (the cache is computed by the - /// same trusted process, e.g. at mempool insertion), but a `Tx` whose cached sizes could - /// come from an untrusted or stale source (e.g. block validation of another party's block) - /// must not be fed here without first re-establishing that invariant. A `Tx` that uses the - /// recomputing default (e.g. a bare `Recovered<...>`) is unconditionally safe. - /// - /// A `debug_assert` cross-checks the resolved values against a fresh recompute, so a caller - /// bug is caught in tests/CI; it is compiled out in release builds. For the recomputing - /// default it is a no-op; for a cached override it is the real safety net. - /// - /// # Parameters - /// - /// - `tx`: The transaction to execute. - /// - /// # Returns - /// - /// Returns the execution outcome of the transaction. Note that the execution result is not - /// committed to the block executor's inner state. - pub fn run_transaction( - &mut self, - tx: Tx, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv - + RecoveredTx - + MegaTransactionExt - + Encodable2718 - + Copy, - { - let tx_size = tx.tx_size(); - let da_size = tx.estimated_da_size(); - debug_assert_eq!( - tx_size, - tx.encode_2718_len() as u64, - "run_transaction: Tx-reported tx_size does not match a fresh recompute from the \ - encoded transaction" - ); - debug_assert_eq!( - da_size, - op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()), - "run_transaction: Tx-reported da_size does not match a fresh recompute from the \ - encoded transaction" - ); - self.run_transaction_with_sizes(tx, tx_size, da_size) - } - - /// Shared body of [`MegaBlockExecutor::run_transaction`] and the `alloy_evm` - /// block-execution path: `tx_size`/`da_size` are resolved by the caller (recomputed or read - /// from a cache), this only consumes them. - /// - /// This is the escape hatch for callers whose `Tx` cannot implement [`MegaTransactionExt`] - /// (e.g. the `alloy_evm` `ExecutableTx`-constrained path): they resolve the sizes themselves - /// and pass them in. Prefer [`MegaBlockExecutor::run_transaction`] otherwise, which resolves - /// the sizes for you and cross-checks any cached values. - pub fn run_transaction_with_sizes( - &mut self, - tx: Tx, - tx_size: u64, - da_size: u64, - ) -> Result, BlockExecutionError> - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - let is_deposit = tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE; - - // Check transaction-level and block-level limits before transaction execution - self.block_limiter.pre_execution_check( - tx.tx().tx_hash(), - tx.tx().gas_limit(), - tx_size, - da_size, - is_deposit, - )?; - - // Cache the depositor account prior to the state transition for the deposit nonce. - // - // Note that in MegaETH, the Regolith hardfork is always active, so we always have deposit - // nonces. In addition, regular transactions don't have deposit - // nonces, so we don't need to touch the DB for those. - let depositor = is_deposit - .then(|| { - self.evm - .db_mut() - .load_cache_account(*tx.signer()) - .map(|acc| acc.account_info().unwrap_or_default()) - }) - .transpose() - .map_err(BlockExecutionError::other)?; - - let hash = tx.tx().trie_hash(); - - // Execute transaction. - let outcome = self - .evm - .execute_transaction(tx.into_tx_env()) - .map_err(move |err| BlockExecutionError::evm(err, hash))?; - - Ok(BlockMegaTransactionOutcome { tx, tx_size, da_size, depositor, inner: outcome }) - } - - /// Alias to [`MegaBlockExecutor::commit_transaction_outcome`]. - pub fn commit_execution_outcome( - &mut self, - outcome: BlockMegaTransactionOutcome, - ) -> Result - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - self.commit_transaction_outcome(outcome) - } - - /// Commit the execution outcome of a transaction. - /// - /// This method commits the execution outcome of a transaction to the block executor's inner - /// state. - /// - /// # Parameters - /// - /// - `outcome`: The execution outcome of the transaction. - /// - /// # Returns - /// - /// Returns the gas used by the transaction. - pub fn commit_transaction_outcome( - &mut self, - outcome: BlockMegaTransactionOutcome, - ) -> Result - where - Tx: IntoTxEnv + RecoveredTx + Copy, - { - // Re-validate limits at commit time to handle parallel execution race conditions. - // Between run_transaction() and commit_transaction_outcome(), other transactions - // may have been committed, potentially exceeding block limits. - self.block_limiter.pre_execution_check( - outcome.tx.tx().tx_hash(), - outcome.tx.tx().gas_limit(), - outcome.tx_size, - outcome.da_size, - outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE, - )?; - - // Accumulate post-execution resource usage into block-level counters. - // This does not validate limits; over-limit enforcement happens in - // `pre_execution_check` before the next transaction. - self.block_limiter.post_execution_update(&outcome)?; - - let BlockMegaTransactionOutcome { tx, depositor, inner, .. } = outcome; - let MegaTransactionOutcome { result, state, .. } = inner; - let gas_used = result.gas_used(); - - self.system_caller.on_state(StateChangeSource::Transaction(self.receipts.len()), &state); - - let block_gas_used = self.block_limiter.block_gas_used; - self.receipts.push( - match self.receipt_builder.build_receipt(ReceiptBuilderCtx { - tx: tx.tx(), - result, - cumulative_gas_used: block_gas_used, - evm: &self.evm, - state: &state, - }) { - Ok(receipt) => receipt, - Err(ctx) => { - let receipt = alloy_consensus::Receipt { - // Success flag was added in `EIP-658: Embedding transaction status code - // in receipts`. - status: Eip658Value::Eip658(ctx.result.is_success()), - cumulative_gas_used: block_gas_used, - logs: ctx.result.into_logs(), - }; - - self.receipt_builder.build_deposit_receipt(OpDepositReceipt { - inner: receipt, - // The deposit receipt version was introduced in Canyon to indicate an - // update to how receipt hashes should be computed - // when set. The state transition process ensures - // this is only set for post-Canyon deposit - // transactions. In MegaETH, Canyon is always active. - deposit_receipt_version: depositor.is_some().then_some(1), - deposit_nonce: depositor.map(|account| account.nonce), - }) - } - }, - ); - - self.evm.db_mut().commit(state); - - Ok(gas_used) - } - - /// Get the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn get_accessed_bucket_ids(&self) -> Vec { - self.evm.ctx_ref().dynamic_storage_gas_cost.borrow().get_bucket_ids() + /// The EVM the block runs on. + pub const fn evm(&self) -> &E { + &self.evm } - /// Get the block hashes used during transaction execution. - /// - /// # Returns - /// - /// Returns the block hashes used during transaction execution. - pub fn get_accessed_block_hashes(&self) -> BTreeMap { - self.evm.db().block_hashes.clone() + /// The EVM the block runs on, mutably. + pub const fn evm_mut(&mut self) -> &mut E { + &mut self.evm } - /// Clears the recorded block hash accesses. - /// - /// Block hash reads accumulate in the executor's database across every - /// transaction executed so far. Callers that need to attribute BLOCKHASH - /// reads to a single transaction (e.g. replay fixture dumping) clear the - /// record before executing it. The record is a cache: a cleared hash is - /// simply re-fetched from the underlying database on the next access, so - /// execution results are unaffected. - pub fn clear_accessed_block_hashes(&mut self) { - self.evm.db_mut().block_hashes.clear(); + /// Consumes the executor and returns its EVM. + pub fn into_evm(self) -> E { + self.evm } } -/// Implementation of `alloy_evm::block::BlockExecutor` for `MegaETH` block executor. -/// -/// This implementation delegates all block execution operations to the underlying -/// Optimism block executor while providing MegaETH-specific customizations through -/// the configured chain specification and EVM factory. -impl<'db, DB, C, R, INSP, ExtEnvs> alloy_evm::block::BlockExecutor - for MegaBlockExecutor, INSP, ExtEnvs>, R> -where - DB: Database + 'db, - C: MegaHardforks, - ExtEnvs: crate::ExternalEnvTypes, - INSP: Inspector, ExtEnvs>>, - R: OpReceiptBuilder< - Transaction: Transaction + Encodable2718 + MegaTransactionExt, - Receipt: TxReceipt, - >, - crate::MegaTransaction: FromRecoveredTx + FromTxWithEncoded, -{ - type Transaction = R::Transaction; - - type Receipt = R::Receipt; - - type Evm = crate::MegaEvm<&'db mut State, INSP, ExtEnvs>; - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::apply_pre_execution_changes`. Changes there should be - /// synced. - fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { - let outcomes = self.pre_execution_changes()?; - self.commit_system_call_outcomes(outcomes)?; - - // After all pre-block outcomes are committed, resolve the system address for this block. - // This reads _currentSystemAddress from the now-committed SequencerRegistry storage. - // The returned EvmState captures the read as a witness record. Inside the resolver the - // behavior projection gates whether dynamic resolution applies, and the position - // projection selects the expected registry bytecode version. - let spec = self.evm.ctx().mega_spec(); - let (system_address, read_state) = - resolve_system_address(&self.hardforks, spec, self.evm.db_mut())?; - if let Some(state) = read_state { - self.system_caller.on_state(StateChangeSource::Transaction(0), &state); - self.evm.db_mut().commit(state); - } - self.evm.ctx_mut().set_system_address(system_address); - - Ok(()) - } - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::execute_transaction_with_commit_condition`. Changes there - /// should be synced. - fn execute_transaction_with_commit_condition( - &mut self, - tx: impl ExecutableTx, - f: impl FnOnce(&ExecutionResult<::HaltReason>) -> CommitChanges, - ) -> Result, BlockExecutionError> { - // `tx: impl ExecutableTx` cannot be required to implement `MegaTransactionExt`, so - // this path recomputes the sizes from the raw inner transaction and bypasses - // `run_transaction` (which reads them via the trait). See `run_transaction`'s docs. - let tx_size = tx.tx().encode_2718_len() as u64; - let da_size = tx.tx().estimated_da_size(); - let outcome = self.run_transaction_with_sizes(tx, tx_size, da_size)?; - if f(&outcome.result).should_commit() { - let gas_used = self.commit_execution_outcome(outcome)?; - Ok(Some(gas_used)) - } else { - Ok(None) - } - } - - /// NOTE: this function resembles the one in - /// `alloy_op_evm::OpBlockExecutor::finish`. Changes there should be - /// synced. - fn finish( - mut self, - ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { - let outcomes = self.post_execution_changes()?; - self.commit_system_call_outcomes(outcomes)?; - - let gas_used = self.receipts.last().map(|r| r.cumulative_gas_used()).unwrap_or_default(); - Ok(( - self.evm, - BlockExecutionResult { - receipts: self.receipts, - requests: Default::default(), - gas_used, - }, - )) - } - - fn set_state_hook(&mut self, hook: Option>) { - self.system_caller.with_state_hook(hook); - } - - fn evm_mut(&mut self) -> &mut Self::Evm { - &mut self.evm - } - - fn evm(&self) -> &Self::Evm { - &self.evm +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaSpecId}; + use alloy_evm::Evm; + use revm::context::BlockEnv; + + #[test] + fn test_executor_hands_back_its_evm() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) + .with_block(BlockEnv { gas_limit: 30_000_000, ..Default::default() }); + let mut executor = MegaBlockExecutor::new(MegaEvm::new(ctx)); + + assert_eq!(executor.evm().block().gas_limit, 30_000_000); + executor.evm_mut().set_inspector_enabled(true); + assert!(executor.into_evm().is_inspecting()); } } diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs deleted file mode 100644 index 096640c86..000000000 --- a/crates/mega-evm/src/block/factory.rs +++ /dev/null @@ -1,205 +0,0 @@ -use alloy_consensus::{Transaction, TxReceipt}; -use alloy_eips::Encodable2718; -use alloy_evm::{ - block::BlockExecutorFor, Database, EvmEnv, EvmFactory, FromRecoveredTx, FromTxWithEncoded, -}; -use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; -use alloy_primitives::{Bytes, B256}; -use revm::{database::State, inspector::NoOpInspector, Inspector}; - -use crate::{BlockLimits, MegaBlockExecutor, MegaEvm, MegaHardforks, MegaSpecId, MegaTxEnvelope}; - -/// `MegaETH` block executor factory. -/// -/// A factory for creating block executors configured with MegaETH-specific specifications -/// and optimizations. This factory encapsulates the chain specification, EVM factory, -/// and receipt builder needed to create block executors that support `MegaETH` features -/// such as enhanced security measures and increased contract size limits. -/// -/// # Generic Parameters -/// -/// - `Hardforks`: The hardforks implementing [`MegaHardforks`] -/// - `EvmF`: The EVM factory type implementing [`alloy_evm::EvmFactory`] -/// - `ReceiptBuilder`: The receipt builder implementing [`OpReceiptBuilder`] to build op-stack -/// receipts -/// -/// # Implementation Details -/// -/// The factory implements `alloy_evm::block::BlockExecutorFactory` and delegates -/// to the underlying Optimism EVM implementation while providing MegaETH-specific -/// customizations through the configured chain specification and EVM factory. -#[derive(Debug, Clone)] -pub struct MegaBlockExecutorFactory { - receipt_builder: ReceiptBuilder, - hardforks: Hardforks, - evm_factory: EvmF, -} - -impl MegaBlockExecutorFactory -where - ReceiptBuilder: OpReceiptBuilder, -{ - /// Create a new block executor factory. - /// - /// # Parameters - /// - /// - `spec`: The chain specification (e.g., `SpecId::MINI_REX` or `SpecId::EQUIVALENCE`) - /// - `evm_factory`: The EVM factory for creating EVM instances - /// - `receipt_builder`: The receipt builder for processing transaction receipts - /// - /// # Returns - /// - /// A new `BlockExecutorFactory` instance configured with the provided parameters. - pub fn new(hardforks: Hardforks, evm_factory: EvmF, receipt_builder: ReceiptBuilder) -> Self { - Self { receipt_builder, hardforks, evm_factory } - } - - /// Returns a reference to the EVM factory. - pub fn evm_factory_ref(&self) -> &EvmF { - &self.evm_factory - } - - /// Returns a mutable reference to the EVM factory. - pub fn evm_factory_mut(&mut self) -> &mut EvmF { - &mut self.evm_factory - } -} - -impl - MegaBlockExecutorFactory, ReceiptBuilder> -where - Hardforks: MegaHardforks + Clone, - ReceiptBuilder: OpReceiptBuilder + Clone, - crate::MegaTransaction: FromRecoveredTx, - ExtEnvFactory: crate::ExternalEnvFactory + Clone, -{ - /// Create a new block executor. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. - /// - `block_ctx`: The block execution context for tracking access patterns. - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn create_executor<'a, DB>( - &self, - db: &'a mut State, - block_ctx: MegaBlockExecutionCtx, - evm_env: EvmEnv, - ) -> MegaBlockExecutor< - Hardforks, - MegaEvm<&'a mut State, NoOpInspector, ExtEnvFactory::EnvTypes>, - ReceiptBuilder, - > - where - DB: Database + 'a, - { - let runtime_limits = block_ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = self.evm_factory.create_evm(db, evm_env).with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, block_ctx, self.hardforks.clone(), self.receipt_builder.clone()) - } - - /// Create a new block executor with an inspector. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. - /// - `block_ctx`: The block execution context for tracking access patterns. - /// - `inspector`: The inspector to use for debugging and monitoring. - /// - /// # Returns - /// - /// A new `BlockExecutor` instance configured with the provided parameters. - pub fn create_executor_with_inspector<'a, DB, I>( - &self, - db: &'a mut State, - block_ctx: MegaBlockExecutionCtx, - evm_env: EvmEnv, - inspector: I, - ) -> MegaBlockExecutor< - Hardforks, - MegaEvm<&'a mut State, I, ExtEnvFactory::EnvTypes>, - ReceiptBuilder, - > - where - DB: Database + 'a, - I: Inspector, ExtEnvFactory::EnvTypes>> + 'a, - { - let runtime_limits = block_ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = self - .evm_factory - .create_evm_with_inspector(db, evm_env, inspector) - .with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, block_ctx, self.hardforks.clone(), self.receipt_builder.clone()) - } -} - -impl alloy_evm::block::BlockExecutorFactory - for MegaBlockExecutorFactory, ReceiptBuilder> -where - ReceiptBuilder: OpReceiptBuilder, - Hardforks: MegaHardforks + Clone, - ExtEnvFactory: crate::ExternalEnvFactory + Clone, - crate::MegaTransaction: FromRecoveredTx - + FromTxWithEncoded, - Self: 'static, -{ - type EvmFactory = crate::MegaEvmFactory; - type ExecutionCtx<'a> = MegaBlockExecutionCtx; - type Transaction = ReceiptBuilder::Transaction; - type Receipt = ReceiptBuilder::Receipt; - - fn evm_factory(&self) -> &Self::EvmFactory { - self.evm_factory_ref() - } - - fn create_executor<'a, DB, I>( - &'a self, - evm: ::Evm<&'a mut State, I>, - ctx: Self::ExecutionCtx<'a>, - ) -> impl BlockExecutorFor<'a, Self, DB, I> - where - DB: Database + 'a, - I: Inspector<::Context<&'a mut State>> + 'a, - { - // Synchronize EVM tx runtime limits with the block context's BlockLimits. - // This mirrors the inherent factory paths above which apply this - // unconditionally on every spec since introduction. Without this, the - // trait impl path silently ran against whatever limits the caller did - // or did not pre-apply via with_tx_runtime_limits, leaving an asymmetry - // between the inherent and trait construction routes. - let runtime_limits = ctx.block_limits.to_evm_tx_runtime_limits(); - let evm = evm.with_tx_runtime_limits(runtime_limits); - MegaBlockExecutor::new(evm, ctx, &self.hardforks, &self.receipt_builder) - } -} - -/// Block execution context for the `MegaETH` chain. -#[derive(Debug, Clone)] -pub struct MegaBlockExecutionCtx { - /// Parent block hash. - pub parent_hash: B256, - /// Parent beacon block root. - pub parent_beacon_block_root: Option, - /// The block's extra data. - pub extra_data: Bytes, - - /// The block limits. - pub block_limits: BlockLimits, -} - -impl MegaBlockExecutionCtx { - /// Create a new block execution context with default limits. - pub fn new( - parent_hash: B256, - parent_beacon_block_root: Option, - extra_data: Bytes, - block_limits: BlockLimits, - ) -> Self { - Self { parent_hash, parent_beacon_block_root, extra_data, block_limits } - } -} diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index 82e02404e..aa364f4af 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -1,1167 +1,51 @@ -#[cfg(not(feature = "std"))] -use alloc as std; +//! `MegaETH` hardforks of the Satin engine. -use alloy_hardforks::{hardfork, EthereumHardfork, EthereumHardforks, ForkCondition, Hardfork}; -use alloy_op_hardforks::{OpHardfork, OpHardforks}; -use alloy_primitives::{BlockTimestamp, U256}; -use auto_impl::auto_impl; -use core::any::Any; -use std::{boxed::Box, sync::Arc, vec::Vec}; +use alloy_hardforks::hardfork; -use crate::{MegaSpecId, SequencerRegistryConfig, SequencerRegistryRex6Config}; +use crate::MegaSpecId; hardfork! { - /// The name of MegaETH hardforks. It is expected to mix with [`EthereumHardfork`] and - /// [`OpHardfork`]. + /// `MegaETH` network upgrades that schedule a Satin-engine spec. It is expected to mix with + /// `EthereumHardfork` and `OpHardfork`. + /// + /// The forks of the legacy engine (`MiniRex` through `Rex7`) are not variants here; a chain + /// runs them on the legacy engine up to the Satin activation. #[derive(serde::Serialize, serde::Deserialize)] MegaHardfork { - /// The first hardfork. - MiniRex, - /// The first alias hardfork: rolls behavior back to Equivalence on its own rung. - MiniRex1, - /// The second alias hardfork: restores MiniRex behavior on its own rung. - MiniRex2, - /// The fourth hardfork. - Rex, - /// The fifth hardfork (first patch to Rex). - Rex1, - /// The sixth hardfork (second patch to Rex). - Rex2, - /// The seventh hardfork (third patch to Rex). - Rex3, - /// The eighth hardfork (fourth patch to Rex). - Rex4, - /// The ninth hardfork (fifth patch to Rex). - Rex5, - /// The tenth hardfork (sixth patch to Rex). - Rex6, - /// The eleventh hardfork (seventh patch to Rex). - Rex7, + /// Activates [`MegaSpecId::SATIN`]. + Satin, } } impl MegaHardfork { - /// Whether this fork introduces new behavior — its spec is not an alias. Alias forks - /// (`MiniRex1`, `MiniRex2`) schedule a rung whose behavior belongs to an earlier spec. - pub(crate) fn introduces_behavior(self) -> bool { - !self.spec_id().is_alias() - } - - /// Gets the `MegaSpecId` associated with this hardfork. - #[allow(clippy::match_same_arms)] + /// The spec this hardfork activates. pub const fn spec_id(&self) -> MegaSpecId { - // Note: MiniRex1 and MiniRex2 map to alias specs: rungs of their own whose - // behavior projects to previously released specs. match self { - Self::MiniRex => MegaSpecId::MINI_REX, - Self::MiniRex1 => MegaSpecId::MINI_REX_1, - Self::MiniRex2 => MegaSpecId::MINI_REX_2, - Self::Rex => MegaSpecId::REX, - Self::Rex1 => MegaSpecId::REX1, - Self::Rex2 => MegaSpecId::REX2, - Self::Rex3 => MegaSpecId::REX3, - Self::Rex4 => MegaSpecId::REX4, - Self::Rex5 => MegaSpecId::REX5, - Self::Rex6 => MegaSpecId::REX6, - Self::Rex7 => MegaSpecId::REX7, - } - } -} - -/// Whether each fork in `forks` maps to a strictly higher spec rung than the fork before it. -/// -/// This is the invariant the fork→spec map rests on: the reverse scan in -/// [`MegaHardforks::hardfork`] and the skipped-rung rule in -/// [`MegaHardforks::validate_schedule`] assume declaration order climbs the ladder, and -/// strictness pins injectivity — no two forks share a rung, so the map stays 1:1 and the -/// resolved spec is monotone on any ordered schedule. -/// -/// Shared by the compile-time assertion below and by the test that feeds it malformed lists, -/// so the checker itself is exercised — the real `VARIANTS` always satisfies the property it -/// checks. -const fn climbs_the_spec_ladder(forks: &[MegaHardfork]) -> bool { - let mut i = 1; - while i < forks.len() { - if forks[i - 1].spec_id() as u8 >= forks[i].spec_id() as u8 { - return false; - } - i += 1; - } - true -} - -const _: () = assert!( - climbs_the_spec_ladder(MegaHardfork::VARIANTS), - "every hardfork must map to a strictly higher spec rung than the fork declared before it — \ - express a rollback as a new alias rung, not by reusing an earlier spec" -); - -/// Validation error returned by [`HardforkParams::validate`]. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] -#[display("{message}")] -pub struct HardforkParamsError { - /// Human-readable description of the invalid field or invariant. - pub message: std::string::String, -} - -/// Marker trait for per-fork parameters. -/// -/// Each params type is pinned to exactly one [`MegaHardfork`] variant via `FORK`. -/// This lets [`MegaHardforks::fork_params`] return a typed reference without -/// requiring the caller to specify the fork separately. -pub trait HardforkParams: Any + core::fmt::Debug + Send + Sync { - /// The hardfork this params type belongs to. - const FORK: MegaHardfork; - - /// Validates construction-time invariants (no cross-fork context required). - /// - /// Called by [`MegaHardforkConfig::with_params`] so misconfiguration is caught - /// at chain-config load time rather than at the first block where the fork activates. - /// The default implementation accepts any value. - fn validate(&self) -> Result<(), HardforkParamsError> { - Ok(()) - } -} - -/// Extends [`OpHardforks`] with `MegaETH` helper methods. -/// -/// Forks map 1:1 onto specs, so [`spec_id`](Self::spec_id) — the latest activated fork's spec — -/// is monotone: it only ever climbs. Rollbacks are expressed by *alias specs* (`MINI_REX_1`, -/// `MINI_REX_2`): rungs of their own whose behavior projects to an earlier spec. One resolved -/// value is therefore read through two projections: -/// -/// - `spec.is_enabled(X)` — the BEHAVIOR gate: both sides project through [`MegaSpecId::behavior`], -/// so execution semantics roll back inside an alias window. -/// - `spec.reaches(X)` — the POSITION gate: raw rung comparison for one-way chain setup -/// (predeploys, bytecode versions, pre-block rules), which a rollback does not retract. -/// -/// The `is__active_at_timestamp` predicates are position projections for -/// behavior-introducing forks (additive on schedules that omit a predecessor) and raw event -/// queries for alias forks, whose occurrence is not recoverable from the ladder. To ask about -/// the raw scheduling event of any fork, use `mega_fork_activation` directly. To check a -/// schedule for well-formedness (rung gaps, ordering, required params), use -/// [`validate_schedule`](Self::validate_schedule). -#[auto_impl(&, Box, Arc)] -pub trait MegaHardforks: OpHardforks { - /// Retrieves [`ForkCondition`] by a [`MegaHardfork`]. If `fork` is not present, returns - /// [`ForkCondition::Never`]. - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; - - /// Returns a type-erased reference to per-fork parameters, if configured. - /// - /// Most forks carry no parameters and the default implementation returns `None`. - fn fork_params_any(&self, _fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - None - } - - /// Returns a typed reference to per-fork parameters. - /// - /// `P::FORK` identifies the fork. Returns `None` if the fork has no params configured. - fn fork_params(&self) -> Option<&P> { - self.fork_params_any(P::FORK)?.downcast_ref::

() - } - - /// Returns the current `MegaHardfork` active at the given timestamp. - /// - /// Resolution walks the declaration ladder from the top: the latest-declared fork whose - /// activation event has occurred wins. Declaration order is chronological, so at equal - /// activation timestamps the later-declared fork prevails. Driven off - /// [`MegaHardfork::VARIANTS`] so a newly declared fork joins resolution without a second - /// hand-written ladder here. - /// - /// Resolution reads raw activation events - /// ([`mega_fork_activation`](Self::mega_fork_activation)); with the 1:1 ascending fork->spec - /// map, the resolved spec is monotone in time on any ordered schedule. - fn hardfork(&self, timestamp: BlockTimestamp) -> Option { - MegaHardfork::VARIANTS - .iter() - .rev() - .find(|fork| self.mega_fork_activation(**fork).active_at_timestamp(timestamp)) - .copied() - } - - /// Returns the current `MegaSpecId` for the given block timestamp. - fn spec_id(&self, timestamp: BlockTimestamp) -> MegaSpecId { - self.hardfork(timestamp).map_or(MegaSpecId::EQUIVALENCE, |h| h.spec_id()) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::MINI_REX`], the - /// spec introduced by [`MegaHardfork::MiniRex`]. Position-projected (`reaches`) — see the trait - /// docs; for the raw activation event use - /// [`mega_fork_activation`](Self::mega_fork_activation). - fn is_mini_rex_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::MINI_REX) - } - - /// Returns `true` if the [`MegaHardfork::MiniRex1`] activation event has occurred at the - /// given block timestamp. - /// - /// `MiniRex1` schedules the alias rung [`MegaSpecId::MINI_REX_1`], whose occurrence is not - /// recoverable from the ladder position (later rungs stand above it whether or not it was - /// ever scheduled), so this predicate stays a raw event query, unlike the - /// position-projected predicates of behavior-introducing forks. - fn is_mini_rex_1_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.mega_fork_activation(MegaHardfork::MiniRex1).active_at_timestamp(timestamp) - } - - /// Returns `true` if the [`MegaHardfork::MiniRex2`] activation event has occurred at the - /// given block timestamp. - /// - /// `MiniRex2` schedules the alias rung [`MegaSpecId::MINI_REX_2`], whose occurrence is not - /// recoverable from the ladder position, so this predicate stays a raw event query, unlike - /// the position-projected predicates of behavior-introducing forks. - fn is_mini_rex_2_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.mega_fork_activation(MegaHardfork::MiniRex2).active_at_timestamp(timestamp) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX`], the rung - /// introduced by [`MegaHardfork::Rex`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX1`], the rung - /// introduced by [`MegaHardfork::Rex1`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_1_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX1) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX2`], the rung - /// introduced by [`MegaHardfork::Rex2`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_2_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX2) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX3`], the rung - /// introduced by [`MegaHardfork::Rex3`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_3_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX3) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX4`], the rung - /// introduced by [`MegaHardfork::Rex4`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_4_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX4) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX5`], the rung - /// introduced by [`MegaHardfork::Rex5`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_5_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX5) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX6`], the rung - /// introduced by [`MegaHardfork::Rex6`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_6_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX6) - } - - /// Returns `true` once the scheduled spec has reached [`MegaSpecId::REX7`], the rung - /// introduced by [`MegaHardfork::Rex7`]. Position-projected (`reaches`) — see the trait docs; - /// for the raw activation event use [`mega_fork_activation`](Self::mega_fork_activation). - fn is_rex_7_active_at_timestamp(&self, timestamp: BlockTimestamp) -> bool { - self.spec_id(timestamp).reaches(MegaSpecId::REX7) - } - - /// Checks the schedule for well-formedness, i.e., that it describes a chain climbing the - /// spec ladder rung by rung. - /// - /// This is the fail-fast complement to the fail-safe execution layer: block execution - /// tolerates a malformed schedule (setup gates compare rung positions, so a skipped rung's - /// setup still runs), but a real chain's published schedule with a skipped rung is almost - /// certainly a configuration mistake. Chain-config authors and node startup - /// paths should call this and refuse a schedule that does not validate. - /// - /// Checked, in order: - /// - /// - Every registered `MegaHardfork` activates by [`ForkCondition::Timestamp`] (or is - /// [`ForkCondition::Never`]). Block-number and TTD conditions never report active to the - /// timestamp-scoped resolution here and would silently deactivate the fork. - /// - Scheduled forks activate in declaration order: a later-declared fork must not activate - /// strictly before an earlier-declared one. - /// - No skipped rungs: a behavior-introducing fork may be unscheduled only if no scheduled fork - /// maps to an equal-or-higher rung. Alias forks are exempt as the *missing* side — testnet - /// legitimately never schedules `MiniRex1`/`MiniRex2` — but an alias scheduled without its - /// base is itself a skipped rung (the alias's rung sits above the base's). - /// - Per-fork parameters required by a scheduled fork are present (`Rex5` requires - /// [`SequencerRegistryConfig`](crate::SequencerRegistryConfig), `Rex6` requires - /// [`SequencerRegistryRex6Config`](crate::SequencerRegistryRex6Config)). This surfaces a - /// missing config at load time rather than at the first block of the fork. A new - /// [`HardforkParams`] type must be registered here. - fn validate_schedule(&self) -> Result<(), ScheduleError> { - let scheduled = - |fork: MegaHardfork| self.mega_fork_activation(fork) != ForkCondition::Never; - - let mut prev: Option<(MegaHardfork, u64)> = None; - for fork in MegaHardfork::VARIANTS { - match self.mega_fork_activation(*fork) { - ForkCondition::Never => {} - ForkCondition::Timestamp(timestamp) => { - if let Some((earlier, earlier_timestamp)) = prev { - if timestamp < earlier_timestamp { - return Err(ScheduleError::UnorderedForks { - earlier, - earlier_timestamp, - later: *fork, - later_timestamp: timestamp, - }); - } - } - prev = Some((*fork, timestamp)); - } - _ => return Err(ScheduleError::NonTimestampActivation { fork: *fork }), - } - } - - for fork in MegaHardfork::VARIANTS { - if !fork.introduces_behavior() || scheduled(*fork) { - continue; - } - if let Some(above) = MegaHardfork::VARIANTS - .iter() - .find(|g| scheduled(**g) && g.spec_id() >= fork.spec_id()) - { - return Err(ScheduleError::SkippedRung { missing: *fork, scheduled: *above }); - } - } - - if scheduled(MegaHardfork::Rex5) && self.fork_params::().is_none() - { - return Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig", - }); - } - if scheduled(MegaHardfork::Rex6) && - self.fork_params::().is_none() - { - return Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config", - }); - } - - Ok(()) - } -} - -/// A malformed hardfork schedule, as reported by [`MegaHardforks::validate_schedule`]. -#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display, derive_more::Error)] -pub enum ScheduleError { - /// A later-declared fork activates strictly before an earlier-declared one. - #[display( - "hardfork {later:?} (t={later_timestamp}) activates before {earlier:?} (t={earlier_timestamp})" - )] - UnorderedForks { - /// The earlier-declared fork. - earlier: MegaHardfork, - /// Activation timestamp of the earlier-declared fork. - earlier_timestamp: u64, - /// The later-declared fork that activates too early. - later: MegaHardfork, - /// Activation timestamp of the later-declared fork. - later_timestamp: u64, - }, - /// A spec-introducing fork is unscheduled while a fork of an equal-or-higher spec is - /// scheduled — the ladder skips a rung. - #[display("hardfork {missing:?} is unscheduled but {scheduled:?} is scheduled above it")] - SkippedRung { - /// The unscheduled spec-introducing fork. - missing: MegaHardfork, - /// A scheduled fork whose spec is equal or higher. - scheduled: MegaHardfork, - }, - /// A `MegaHardfork` is registered with a block-number or TTD condition, which the - /// timestamp-scoped resolution never reports as active. - #[display("hardfork {fork:?} must activate by timestamp, not block number or TTD")] - NonTimestampActivation { - /// The fork with a non-timestamp activation condition. - fork: MegaHardfork, - }, - /// A scheduled fork requires per-fork parameters that are not attached. - #[display("hardfork {fork:?} is scheduled but its {params} params are not configured")] - MissingParams { - /// The scheduled fork whose params are missing. - fork: MegaHardfork, - /// The required params type. - params: &'static str, - }, -} - -/// A single fork entry: identity, activation condition, and optional per-fork parameters. -#[derive(Debug)] -struct ForkEntry { - fork: Box, - condition: ForkCondition, - params: Option>, -} - -impl Clone for ForkEntry { - fn clone(&self) -> Self { - Self { fork: self.fork.clone(), condition: self.condition, params: self.params.clone() } - } -} - -/// Configuration of the hardforks for `MegaETH`. It by default includes no `MegaHardfork` but -/// includes all hardforks before and including Optimism Isthmus. Optimism Isthmus is the hardfork -/// where `MegaETH` is established. -/// -/// Per-fork parameters (e.g., [`SequencerRegistryConfig`](crate::SequencerRegistryConfig)) are -/// embedded in the corresponding fork entry via [`with_params`](Self::with_params). -#[derive(Debug, Clone)] -pub struct MegaHardforkConfig { - entries: Vec, -} - -impl Default for MegaHardforkConfig { - fn default() -> Self { - Self::new() - } -} - -impl From for MegaHardforkConfig -where - I: Iterator, - H: Hardfork + 'static, -{ - fn from(iter: I) -> Self { - Self { - entries: iter - .map(|(h, c)| ForkEntry { - fork: Box::new(h) as Box, - condition: c, - params: None, - }) - .collect(), - } - } -} - -impl MegaHardforkConfig { - /// Creates a new hardfork configuration with the default hardforks, i.e., all hardforks before - /// and including Optimism Isthmus are enabled. Optimism Isthmus is the hardfork where - /// `MegaETH` is established. - pub fn new() -> Self { - let forks: Vec<(Box, ForkCondition)> = vec![ - (EthereumHardfork::Frontier.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Homestead.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Dao.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Tangerine.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::SpuriousDragon.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Byzantium.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Constantinople.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Petersburg.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Istanbul.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::Berlin.boxed(), ForkCondition::Block(0)), - (EthereumHardfork::London.boxed(), ForkCondition::Block(0)), - ( - EthereumHardfork::Paris.boxed(), - ForkCondition::TTD { - activation_block_number: 0, - fork_block: None, - total_difficulty: U256::ZERO, - }, - ), - (OpHardfork::Bedrock.boxed(), ForkCondition::Block(0)), - (OpHardfork::Regolith.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Shanghai.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Canyon.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Cancun.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Ecotone.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Fjord.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Granite.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Holocene.boxed(), ForkCondition::Timestamp(0)), - (EthereumHardfork::Prague.boxed(), ForkCondition::Timestamp(0)), - (OpHardfork::Isthmus.boxed(), ForkCondition::Timestamp(0)), - ]; - Self { - entries: forks - .into_iter() - .map(|(fork, condition)| ForkEntry { fork, condition, params: None }) - .collect(), - } - } - - /// Sets all `MegaHardfork` to be activated at timestamp 0. - pub fn with_all_activated(self) -> Self { - self.with_all_activated_through(MegaSpecId::default()) - } - - /// Activates every `MegaHardfork` whose spec is enabled under `spec` at timestamp 0, and - /// leaves every later fork unregistered. - /// - /// This is how to express "a chain running spec N": the resulting config resolves to `spec` - /// at any timestamp. Removing only the next fork up is not equivalent — the ladder runs past - /// it, so the config would resolve to the newest fork still registered rather than to `spec`, - /// and it would silently drift again the next time a spec is introduced. On top of the wrong - /// resolved spec, the leftover later forks also keep the scheduled spec high, so every - /// pre-block setup gate below them stays open. - /// - /// The *activations* in the result are a function of `spec` alone, not of what the config - /// held before: a later fork already registered is removed rather than left in place, so the - /// resolved spec does not depend on builder call order. Per-fork params are the exception: - /// params on a kept fork are preserved, while params on a removed fork are dropped with its - /// entry and are not restored by a later climb back up — re-attach them with - /// [`with_params`](Self::with_params). - /// - /// Alias forks sit on their own rungs above their base (`MINI_REX_1`/`MINI_REX_2` above - /// `MINI_REX`), so climbing through a rung includes everything below it — aliases and - /// bases alike — with no special casing. - pub fn with_all_activated_through(mut self, spec: MegaSpecId) -> Self { - for fork in MegaHardfork::VARIANTS { - if spec.reaches(fork.spec_id()) { - self.insert(*fork, ForkCondition::Timestamp(0)); - } else { - self = self.without(*fork); - } - } - self - } - - /// Attaches per-fork parameters to the entry identified by `P::FORK`. - /// - /// The fork must already exist in the config (via [`with`](Self::with) or default). - /// Panics if the fork is not found or if `params.validate()` returns an error. - pub fn with_params(mut self, params: P) -> Self { - if let Err(e) = params.validate() { - panic!("Invalid params for fork {:?}: {}", P::FORK, e.message,); - } - let entry = - self.entries.iter_mut().find(|e| e.fork.name() == P::FORK.name()).unwrap_or_else( - || { - panic!( - "Cannot attach params to fork {:?}: fork not registered in config. \ - Call .with({:?}, condition) first.", - P::FORK, - P::FORK, - ) - }, - ); - entry.params = Some(Arc::new(params)); - self - } - - /// Removes a `MegaHardfork` from the configuration, i.e., equivalent to setting the fork - /// condition to [`ForkCondition::Never`]. - /// - /// Deliberately private: `with_all_activated().without(fork)` reads as "a chain running the - /// spec below `fork`" but does not express it — the forks above `fork` stay registered, so - /// the config resolves above the intended rung and silently climbs again with the next spec. - /// Say it with [`with_all_activated_through`](Self::with_all_activated_through) instead. - /// - /// This narrows an idiom, not a capability: [`with`](Self::with) with - /// [`ForkCondition::Never`] produces the same unregistered fork, and must stay public because - /// the canonical schedules use it for exactly that (testnet's `MiniRex1` / `MiniRex2` never - /// activate). Writing a gap that way is at least visibly deliberate, and it keeps the entry - /// so [`with_params`](Self::with_params) can still attach to it. - fn without(mut self, hardfork: MegaHardfork) -> Self { - self.entries.retain(|e| e.fork.name() != hardfork.name()); - self - } - - /// Creates a new hardfork configuration with the given hardfork and condition. - pub fn with(mut self, hardfork: impl Hardfork, condition: ForkCondition) -> Self { - self.insert(hardfork, condition); - self - } - - /// Inserts a new hardfork into the configuration. If the hardfork is already present, it will - /// be overwritten (condition updated, params preserved). - pub fn insert(&mut self, hardfork: impl Hardfork, condition: ForkCondition) { - let index = self.entries.iter().position(|e| e.fork.name() == hardfork.name()); - if let Some(index) = index { - self.entries[index].condition = condition; - } else { - self.entries.push(ForkEntry { fork: Box::new(hardfork), condition, params: None }); - } - } - - /// Gets `ForkCondition` by a [`Hardfork`]. If the hardfork is not present, returns `None`. - pub fn get(&self, hardfork: impl Hardfork) -> Option<&ForkCondition> { - self.entries.iter().find(|e| e.fork.name() == hardfork.name()).map(|e| &e.condition) - } -} - -impl EthereumHardforks for MegaHardforkConfig { - fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, - } - } -} - -impl OpHardforks for MegaHardforkConfig { - fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, + Self::Satin => MegaSpecId::SATIN, } } } -impl MegaHardforks for MegaHardforkConfig { - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { - match self.get(fork) { - Some(condition) => *condition, - None => ForkCondition::Never, - } - } - - fn fork_params_any(&self, fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - self.entries.iter().find(|e| e.fork.name() == fork.name()).and_then(|e| e.params.as_deref()) - } -} - #[cfg(test)] mod tests { use super::*; - use crate::SequencerRegistryConfig; - - #[test] - fn test_climbs_the_spec_ladder_rejects_malformed_lists() { - // The real `VARIANTS` is checked at compile time by the const assertion; only - // rejection cases can detect a weakened guard inside the checker. - assert!(climbs_the_spec_ladder(MegaHardfork::VARIANTS)); - assert!(climbs_the_spec_ladder(&[]), "the empty list climbs trivially"); - assert!(climbs_the_spec_ladder(&[MegaHardfork::Rex]), "a single fork climbs trivially"); - assert!( - climbs_the_spec_ladder(&[MegaHardfork::MiniRex, MegaHardfork::Rex5]), - "gaps are fine — strictly ascending is the property, contiguity is not" - ); - - assert!( - !climbs_the_spec_ladder(&[MegaHardfork::Rex, MegaHardfork::MiniRex]), - "a fork mapping below its predecessor must be rejected" - ); - assert!( - !climbs_the_spec_ladder(&[MegaHardfork::Rex, MegaHardfork::Rex]), - "two forks sharing a rung must be rejected — the map must stay 1:1" - ); - } - - #[test] - fn test_mega_hardfork_spec_ids_match_expected_specs() { - // Note: MiniRex1 and MiniRex2 map to alias rungs whose behavior reverts to earlier specs. - let cases = [ - (MegaHardfork::MiniRex, MegaSpecId::MINI_REX), - (MegaHardfork::MiniRex1, MegaSpecId::MINI_REX_1), - (MegaHardfork::MiniRex2, MegaSpecId::MINI_REX_2), - (MegaHardfork::Rex, MegaSpecId::REX), - (MegaHardfork::Rex1, MegaSpecId::REX1), - (MegaHardfork::Rex2, MegaSpecId::REX2), - (MegaHardfork::Rex3, MegaSpecId::REX3), - (MegaHardfork::Rex4, MegaSpecId::REX4), - (MegaHardfork::Rex5, MegaSpecId::REX5), - (MegaHardfork::Rex6, MegaSpecId::REX6), - (MegaHardfork::Rex7, MegaSpecId::REX7), - ]; - - for (hardfork, expected_spec) in cases { - assert_eq!(hardfork.spec_id(), expected_spec); - } - } + use crate::MegaSpecId; + use alloy_hardforks::Hardfork; + use core::str::FromStr; #[test] - fn test_default_config_contains_upstream_forks_and_no_mega_forks() { - let config = MegaHardforkConfig::default(); - - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Frontier), - ForkCondition::Block(0) - ); - assert_eq!( - config.ethereum_fork_activation(EthereumHardfork::Prague), - ForkCondition::Timestamp(0) - ); - assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); - assert_eq!(config.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_config_builder_helpers_override_and_remove_hardforks() { - let mut config = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(10)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(80)); - - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(10))); - assert_eq!(config.get(MegaHardfork::Rex4), Some(&ForkCondition::Timestamp(80))); - - config.insert(MegaHardfork::MiniRex, ForkCondition::Timestamp(20)); - assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(20))); - - let config = config.without(MegaHardfork::MiniRex); - assert_eq!(config.get(MegaHardfork::MiniRex), None); - - let from_iter = MegaHardforkConfig::from( - [ - (MegaHardfork::MiniRex, ForkCondition::Timestamp(1)), - (MegaHardfork::Rex2, ForkCondition::Timestamp(2)), - ] - .into_iter(), - ); - assert_eq!(from_iter.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(1))); - assert_eq!(from_iter.get(MegaHardfork::Rex2), Some(&ForkCondition::Timestamp(2))); + fn test_satin_fork_schedules_the_satin_spec() { + assert_eq!(MegaHardfork::VARIANTS, &[MegaHardfork::Satin]); + assert_eq!(MegaHardfork::Satin.spec_id(), MegaSpecId::SATIN); + assert_eq!(Hardfork::name(&MegaHardfork::Satin), "Satin"); + assert_eq!(MegaHardfork::Satin.to_string(), "Satin"); } #[test] - fn test_with_all_activated_enables_all_mega_hardforks() { - let config = MegaHardforkConfig::default().with_all_activated(); - - // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list - // that declares the enum. A second hand-written list here would assert only that the - // forks someone remembered to name are activated — a new fork missing from both the - // builder and the list would fail neither. - for hardfork in MegaHardfork::VARIANTS { - assert_eq!( - config.mega_fork_activation(*hardfork), - ForkCondition::Timestamp(0), - "{hardfork:?}" - ); + fn test_legacy_fork_names_do_not_parse() { + assert_eq!(MegaHardfork::from_str("Satin").unwrap(), MegaHardfork::Satin); + for legacy in ["MiniRex", "MiniRex1", "MiniRex2", "Rex", "Rex1", "Rex6", "Rex7"] { + assert!(MegaHardfork::from_str(legacy).is_err(), "{legacy} must not parse"); } } - - #[test] - fn test_fork_params_typed_access() { - let params = SequencerRegistryConfig { - rex5_initial_sequencer: alloy_primitives::address!( - "0x2222222222222222222222222222222222222222" - ), - rex5_initial_admin: alloy_primitives::address!( - "0x3333333333333333333333333333333333333333" - ), - }; - - let config = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(params.clone()); - - let retrieved = config - .fork_params::() - .expect("should have SequencerRegistryConfig"); - assert_eq!(retrieved, ¶ms); - } - - #[test] - fn test_fork_params_none_when_not_configured() { - let config = - MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); - - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_default_validate_accepts_any_value() { - #[derive(Debug)] - struct NullParams; - - impl HardforkParams for NullParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - } - - assert!(NullParams.validate().is_ok()); - } - - #[test] - fn test_hardfork_params_error_display() { - let e = HardforkParamsError { message: "something went wrong".into() }; - assert_eq!(e.to_string(), "something went wrong"); - } - - #[test] - #[should_panic(expected = "Invalid params for fork")] - fn test_with_params_panics_on_validation_error() { - #[derive(Debug)] - struct AlwaysErrParams; - - impl HardforkParams for AlwaysErrParams { - const FORK: MegaHardfork = MegaHardfork::Rex4; - - fn validate(&self) -> Result<(), HardforkParamsError> { - Err(HardforkParamsError { message: "intentional test error".into() }) - } - } - - MegaHardforkConfig::default().with_all_activated().with_params(AlwaysErrParams); - } - - /// Mainnet runs a real behavior rollback: inside the `MiniRex1` window the scheduled spec - /// is the alias rung `MINI_REX_1` — behavior projects to `EQUIVALENCE` while position keeps - /// one-way setup (the Oracle predeploys) enabled. - #[test] - fn test_mainnet_rollback_window_behavior_rolls_back_setup_stays() { - let hf = crate::mainnet_hardforks(); - let ForkCondition::Timestamp(rollback_start) = - hf.mega_fork_activation(MegaHardfork::MiniRex1) - else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - let ForkCondition::Timestamp(rollback_end) = - hf.mega_fork_activation(MegaHardfork::MiniRex2) - else { - panic!("mainnet must schedule MiniRex2 by timestamp"); - }; - assert!(rollback_start < rollback_end, "the rollback window must be non-empty"); - - for ts in [rollback_start, rollback_start + 1, rollback_end - 1] { - let spec = hf.spec_id(ts); - assert_eq!(spec, MegaSpecId::MINI_REX_1, "the scheduled spec is monotone"); - assert_eq!(spec.behavior(), MegaSpecId::EQUIVALENCE, "behavior rolls back"); - // Behavior gates turn MiniRex features off; position gates keep its setup. - assert!(!spec.is_enabled(MegaSpecId::MINI_REX)); - assert!(spec.reaches(MegaSpecId::MINI_REX)); - assert!(hf.is_mini_rex_active_at_timestamp(ts)); - } - } - - /// The scheduled spec's position reproduces every per-fork activation event exactly, for - /// every behavior-introducing fork, on every canonical schedule. This is what makes the - /// position-projected predicates a no-op switch on well-formed ladders. - /// - /// Forks that introduce no new behavior — `MiniRex1` (rollback to `EQUIVALENCE`) and - /// `MiniRex2` (restoration to `MINI_REX`) — may be omitted from a schedule whose ladder - /// climbs past their rungs, so their activation events are not recoverable from position and - /// nothing may gate on them this way. The predicate is derived rather than hardcoded so a - /// future rollback fork is classified automatically. - #[test] - fn test_position_matches_per_fork_activation_for_behavior_introducing_forks() { - for hf in [ - crate::mainnet_hardforks(), - crate::testnet_hardforks(), - crate::all_activated_hardforks(), - ] { - let mut stamps = std::vec![0u64, u64::MAX]; - for fork in MegaHardfork::VARIANTS { - if let ForkCondition::Timestamp(t) = hf.mega_fork_activation(*fork) { - stamps.extend([t.saturating_sub(1), t, t.saturating_add(1)]); - } - } - - for ts in stamps { - let resolved = hf.spec_id(ts); - for fork in MegaHardfork::VARIANTS { - if !fork.introduces_behavior() { - continue; - } - assert_eq!( - resolved.reaches(fork.spec_id()), - hf.mega_fork_activation(*fork).active_at_timestamp(ts), - "position disagrees with per-fork activation for {fork:?} at ts={ts}" - ); - } - } - } - } - - /// On a partial ladder — a config that schedules a later fork without its predecessors — the - /// resolved spec still enables every lower spec, and the spec-introducing predicates, being - /// position projections, report active for forks that were never scheduled. Gating on either - /// can therefore not silently skip a predecessor's behavior; only the raw activation events - /// distinguish the missing rungs. - #[test] - fn test_partial_ladder_resolved_spec_enables_unscheduled_predecessors() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)); - - assert_eq!(hf.mega_fork_activation(MegaHardfork::Rex5), ForkCondition::Never); - assert_eq!(hf.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - - let resolved = hf.spec_id(0); - assert_eq!(resolved, MegaSpecId::REX6); - for spec in [MegaSpecId::MINI_REX, MegaSpecId::REX2, MegaSpecId::REX4, MegaSpecId::REX5] { - assert!(resolved.is_enabled(spec), "{spec:?} must be enabled on a partial ladder"); - } - // The predicates project the position: unscheduled predecessors still report active. - assert!(hf.is_rex_5_active_at_timestamp(0), "Rex5 predicate projects the position"); - assert!(hf.is_mini_rex_active_at_timestamp(0), "MiniRex predicate projects the position"); - } - - /// `with_all_activated_through` is the well-formed way to express "a chain running spec N": - /// the resolved spec is exactly `N` at any timestamp. The specs under test come from - /// [`MegaSpecId::ALL`], so a newly introduced spec is covered here automatically instead of - /// depending on a hand-written list. - #[test] - fn test_with_all_activated_through_resolves_to_that_spec() { - for spec in MegaSpecId::ALL.iter().copied() { - let config = MegaHardforkConfig::default().with_all_activated_through(spec); - assert_eq!(config.spec_id(0), spec, "{spec:?} at genesis"); - assert_eq!(config.spec_id(u64::MAX), spec, "{spec:?} must be terminal"); - - // The same contract must hold when the config already carries later forks: the - // builder states the whole ladder, so it removes what it does not activate. Without - // that, the resolved spec would depend on which builder ran last. - let downgraded = - MegaHardforkConfig::default().with_all_activated().with_all_activated_through(spec); - assert_eq!(downgraded.spec_id(u64::MAX), spec, "{spec:?} from an activated config"); - } - } - - /// Removing a middle rung does NOT express "a chain running spec N". It is the partial-ladder - /// shape: the resolved spec follows the newest fork still registered, and — with the - /// predicate projected from its position — keeps every lower gate open. - #[test] - fn test_removing_a_middle_rung_does_not_lower_the_spec() { - let partial = - MegaHardforkConfig::default().with_all_activated().without(MegaHardfork::Rex4); - - assert_eq!( - partial.mega_fork_activation(MegaHardfork::Rex4), - ForkCondition::Never, - "Rex4 itself is unregistered" - ); - assert_ne!(partial.spec_id(0), MegaSpecId::REX4, "the resolved spec is not lowered"); - assert!( - partial.spec_id(0).is_enabled(MegaSpecId::REX4), - "the resolved spec still enables the removed fork's spec" - ); - assert!(partial.is_rex_4_active_at_timestamp(0), "the projected predicate stays open"); - } - - /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered - /// by block number never contributes its own spec to it. `spec_id`/`hardfork` share this - /// limitation; every canonical schedule uses `Timestamp` or `Never`, and - /// `validate_schedule` rejects anything else. - #[test] - fn test_resolution_ignores_block_numbered_forks() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(0)); - - assert!( - !hf.mega_fork_activation(MegaHardfork::MiniRex).active_at_timestamp(0), - "block-numbered forks are not timestamped" - ); - // The resolved spec comes from Rex alone; it still covers MINI_REX by ordinal - // inclusion, so the projected predicate reports active even though the MiniRex event - // itself never fires. - assert_eq!(hf.spec_id(0), MegaSpecId::REX); - assert!(hf.spec_id(0).is_enabled(MegaSpecId::MINI_REX)); - assert!(hf.is_mini_rex_active_at_timestamp(0)); - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::MiniRex }) - ); - } - - /// The resolved spec must equal the naive maximum over all activated forks, on every - /// schedule shape: canonical ladders, rollback windows, partial ladders, block-numbered - /// conditions, and the empty config. Under the 1:1 ascending fork→spec map the latest - /// activated fork IS the maximum; the const assertion on `climbs_the_spec_ladder` pins that - /// statically for declaration order, and this pins it dynamically across schedule shapes. - #[test] - fn test_resolved_spec_is_the_maximum_over_activated_forks() { - let configs = [ - crate::mainnet_hardforks(), - crate::testnet_hardforks(), - crate::all_activated_hardforks(), - MegaHardforkConfig::new(), - // Partial ladders: a lone top rung, and a lone alias fork. - MegaHardforkConfig::new().with(MegaHardfork::Rex6, ForkCondition::Timestamp(7)), - MegaHardforkConfig::new().with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(7)), - // Non-timestamp conditions never contribute. - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(7)), - ]; - let rungs: Vec = MegaSpecId::ALL - .iter() - .map(|spec| MegaHardforkConfig::default().with_all_activated_through(*spec)) - .collect(); - - for hf in configs.iter().chain(rungs.iter()) { - let mut stamps = std::vec![0u64, u64::MAX]; - for fork in MegaHardfork::VARIANTS { - if let ForkCondition::Timestamp(t) = hf.mega_fork_activation(*fork) { - stamps.extend([t.saturating_sub(1), t, t.saturating_add(1)]); - } - } - for ts in stamps { - let naive = MegaHardfork::VARIANTS - .iter() - .filter(|fork| hf.mega_fork_activation(**fork).active_at_timestamp(ts)) - .map(|fork| fork.spec_id()) - .max() - .unwrap_or(MegaSpecId::EQUIVALENCE); - assert_eq!(hf.spec_id(ts), naive, "resolved spec diverges at ts={ts}"); - } - } - } - - /// Alias-fork predicates stay raw event queries: they are not recoverable from a spec - /// ordinal, so they must not be projected from the resolved spec. Testnet is the live case - /// — its resolved spec climbs the whole ladder while `MiniRex1`/`MiniRex2` are never - /// scheduled. - #[test] - fn test_alias_fork_predicates_stay_event_scoped() { - let hf = crate::testnet_hardforks(); - let ts = u64::MAX; - assert!(hf.spec_id(ts).is_enabled(MegaSpecId::REX5), "the resolved spec is high"); - assert!(!hf.is_mini_rex_1_active_at_timestamp(ts), "MiniRex1 never happened on testnet"); - assert!(!hf.is_mini_rex_2_active_at_timestamp(ts), "MiniRex2 never happened on testnet"); - - // On mainnet both events did happen, and the predicates report them. - let hf = crate::mainnet_hardforks(); - assert!(hf.is_mini_rex_1_active_at_timestamp(ts)); - assert!(hf.is_mini_rex_2_active_at_timestamp(ts)); - } - - /// Every canonical schedule and every `with_all_activated_through` rung is well-formed. - /// `with_all_activated_through(EQUIVALENCE)` is the edge worth pinning: it registers no - /// fork at all (a patch without its base would be an orphan) and resolves to - /// `EQUIVALENCE` by default. - #[test] - fn test_validate_schedule_accepts_well_formed_ladders() { - assert_eq!(crate::mainnet_hardforks().validate_schedule(), Ok(())); - assert_eq!(crate::testnet_hardforks().validate_schedule(), Ok(())); - assert_eq!(crate::all_activated_hardforks().validate_schedule(), Ok(())); - assert_eq!(MegaHardforkConfig::new().validate_schedule(), Ok(()), "no mega forks is fine"); - - for spec in MegaSpecId::ALL.iter().copied() { - let mut config = MegaHardforkConfig::default().with_all_activated_through(spec); - if spec.is_enabled(MegaSpecId::REX5) { - config = config.with_params(SequencerRegistryConfig { - rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, - }); - } - if spec.is_enabled(MegaSpecId::REX6) { - config = - config.with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }); - } - assert_eq!(config.validate_schedule(), Ok(()), "{spec:?} rung must validate"); - } - } - - /// A partial ladder is executable (position-gated setup stays additive) but not a valid - /// published schedule: `validate_schedule` is the fail-fast side of that split. - #[test] - fn test_validate_schedule_rejects_skipped_rungs() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { rex6_min_rotation_delay: 1 }); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::MiniRex, - scheduled: MegaHardfork::Rex6 - }) - ); - } - - /// A gap in the middle of the ladder is flagged too, naming the first missing rung. Unlike - /// the lowest rung (whose empty prefix makes it trivially spec-introducing), this exercises - /// the prefix classification for real: `Rex` counts as a rung only because every - /// earlier-declared fork maps strictly below it. - #[test] - fn test_validate_schedule_rejects_skipped_middle_rung() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::Rex, - scheduled: MegaHardfork::Rex2 - }) - ); - } - - /// Scheduling an alias fork without its base is the rollback of a fork that never - /// happened. Under the ascending 1:1 map this is just a skipped rung — the alias's spec - /// sits above its base's — so the general rung check catches it without a dedicated rule. - #[test] - fn test_validate_schedule_rejects_alias_without_base() { - let hf = - MegaHardforkConfig::new().with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(0)); - - assert_eq!(hf.spec_id(0), MegaSpecId::MINI_REX_1); - assert_eq!(hf.spec_id(0).behavior(), MegaSpecId::EQUIVALENCE, "execution unaffected"); - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::SkippedRung { - missing: MegaHardfork::MiniRex, - scheduled: MegaHardfork::MiniRex1 - }) - ); - } - - #[test] - fn test_validate_schedule_rejects_unordered_forks() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(50)); - - assert_eq!( - hf.validate_schedule(), - Err(ScheduleError::UnorderedForks { - earlier: MegaHardfork::MiniRex, - earlier_timestamp: 100, - later: MegaHardfork::Rex, - later_timestamp: 50, - }) - ); - } - - /// A scheduled fork whose required params are missing fails at validation time instead of at - /// the first block of the fork. - #[test] - fn test_validate_schedule_requires_scheduled_fork_params() { - let rex5_no_params = - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5); - assert_eq!( - rex5_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig" - }) - ); - - let rex6_no_params = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(SequencerRegistryConfig { - rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, - rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, - }); - assert_eq!( - rex6_no_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config" - }) - ); - } - - #[test] - fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { - let config = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(200)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(300)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(400)) - .with(MegaHardfork::Rex7, ForkCondition::Timestamp(500)); - - assert_eq!(config.hardfork(99), None); - assert_eq!(config.hardfork(100), Some(MegaHardfork::MiniRex)); - assert_eq!(config.hardfork(200), Some(MegaHardfork::Rex4)); - assert_eq!(config.hardfork(300), Some(MegaHardfork::Rex5)); - assert_eq!(config.hardfork(400), Some(MegaHardfork::Rex6)); - assert_eq!(config.hardfork(500), Some(MegaHardfork::Rex7)); - assert_eq!(config.spec_id(99), MegaSpecId::EQUIVALENCE); - assert_eq!(config.spec_id(100), MegaSpecId::MINI_REX); - assert_eq!(config.spec_id(200), MegaSpecId::REX4); - assert_eq!(config.spec_id(300), MegaSpecId::REX5); - assert_eq!(config.spec_id(400), MegaSpecId::REX6); - assert_eq!(config.spec_id(500), MegaSpecId::REX7); - } } diff --git a/crates/mega-evm/src/block/helpers.rs b/crates/mega-evm/src/block/helpers.rs deleted file mode 100644 index d612e3519..000000000 --- a/crates/mega-evm/src/block/helpers.rs +++ /dev/null @@ -1,390 +0,0 @@ -use alloy_consensus::{transaction::Recovered, Transaction}; -use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization, Encodable2718, Typed2718}; -use alloy_evm::{IntoTxEnv, RecoveredTx}; -use alloy_primitives::{Address, Bytes, ChainId, Selector, TxHash, TxKind, B256, U256}; -use auto_impl::auto_impl; -use delegate::delegate; - -use crate::MegaTxEnvelope; - -/// Helper trait that allows attaching extra information to a transaction. -#[auto_impl(&)] -pub trait MegaTransactionExt { - /// Get the estimated data availability size of the transaction. - /// - /// Note: the default implementation is not efficient since it does not cache the `da_size` and - /// always recalculates it. - fn estimated_da_size(&self) -> u64 - where - Self: Encodable2718, - { - op_alloy_flz::tx_estimated_size_fjord_bytes(self.encoded_2718().as_slice()) - } - - /// Get the EIP-2718 encoded size of the transaction in bytes. - fn tx_size(&self) -> u64 - where - Self: Encodable2718, - { - self.encode_2718_len() as u64 - } - - /// Get the transaction hash. - fn tx_hash(&self) -> TxHash; -} - -impl MegaTransactionExt for Recovered { - fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() - } -} - -impl MegaTransactionExt for Recovered<&MegaTxEnvelope> { - fn tx_hash(&self) -> TxHash { - self.inner().tx_hash() - } -} - -impl MegaTransactionExt for MegaTxEnvelope { - fn tx_hash(&self) -> TxHash { - self.tx_hash() - } -} - -/// A wrapper that allows attaching additional information to a transaction. -#[derive( - Debug, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::AsRef, derive_more::AsMut, -)] -pub struct EnrichedMegaTx { - #[deref] - #[deref_mut] - #[as_ref] - #[as_mut] - inner: T, - - /// The transaction hash. - pub tx_hash: TxHash, - - /// The estimated data availability size of the transaction. - pub da_size: u64, - - /// The EIP-2718 encoded size of the transaction in bytes. - pub tx_size: u64, -} - -impl EnrichedMegaTx { - /// Create a new `WithDASize` wrapper with a known data availability size. - /// - /// `da_size`/`tx_size` are trusted as-is and not validated against `inner`'s actual - /// encoding. When this wrapper reaches [`crate::MegaBlockExecutor::run_transaction`], these - /// values are read via [`MegaTransactionExt`] and used directly for - /// `tx_da_size_limit`/`tx_encode_size_limit`/block cumulative-size enforcement, so an - /// inaccurate value can let a transaction bypass a limit it should have been rejected by. - /// Only pass values computed from `inner` itself (e.g. by a trusted mempool at insertion - /// time); prefer [`EnrichedMegaTx::new_slow`] when in doubt. - pub fn new(inner: T, tx_hash: TxHash, da_size: u64, tx_size: u64) -> Self { - Self { inner, tx_hash, da_size, tx_size } - } -} - -impl EnrichedMegaTx { - /// Create a new `WithDASize` wrapper and do the computation to estimate the data availability - /// size. - pub fn new_slow(inner: T) -> Self { - Self { - tx_hash: inner.trie_hash(), - da_size: op_alloy_flz::tx_estimated_size_fjord_bytes(inner.encoded_2718().as_slice()), - tx_size: inner.encode_2718_len() as u64, - inner, - } - } -} - -impl Encodable2718 for EnrichedMegaTx { - delegate! { - to self.inner { - fn type_flag(&self) -> Option; - fn encode_2718_len(&self) -> usize; - fn encode_2718(&self, out: &mut dyn alloy_primitives::bytes::BufMut); - } - } -} - -impl MegaTransactionExt for EnrichedMegaTx { - fn estimated_da_size(&self) -> u64 { - self.da_size - } - - fn tx_size(&self) -> u64 { - self.tx_size - } - - fn tx_hash(&self) -> TxHash { - self.tx_hash - } -} - -impl Typed2718 for EnrichedMegaTx { - delegate! { - to self.inner { - fn ty(&self) -> u8; - fn is_type(&self, ty: u8) -> bool; - fn is_legacy(&self) -> bool; - fn is_eip2930(&self) -> bool; - fn is_eip1559(&self) -> bool; - fn is_eip4844(&self) -> bool; - fn is_eip7702(&self) -> bool; - } - } -} - -impl Transaction for EnrichedMegaTx { - delegate! { - to self.inner { - fn chain_id(&self) -> Option; - fn nonce(&self) -> u64; - fn gas_limit(&self) -> u64; - fn gas_price(&self) -> Option; - fn max_fee_per_gas(&self) -> u128; - fn max_priority_fee_per_gas(&self) -> Option; - fn max_fee_per_blob_gas(&self) -> Option; - fn priority_fee_or_price(&self) -> u128; - fn effective_gas_price(&self, base_fee: Option) -> u128; - fn is_dynamic_fee(&self) -> bool; - fn kind(&self) -> TxKind; - fn is_create(&self) -> bool; - fn value(&self) -> U256; - fn input(&self) -> &Bytes; - fn access_list(&self) -> Option<&AccessList>; - fn blob_versioned_hashes(&self) -> Option<&[B256]>; - fn authorization_list(&self) -> Option<&[SignedAuthorization]>; - fn authorization_count(&self) -> Option; - fn effective_tip_per_gas(&self, base_fee: u64) -> Option; - fn to(&self) -> Option

; - fn function_selector(&self) -> Option<&Selector>; - fn blob_count(&self) -> Option; - fn blob_gas_used(&self) -> Option; - } - } -} - -impl> RecoveredTx for EnrichedMegaTx { - delegate! { - to self.inner { - fn tx(&self) -> &Tx; - fn signer(&self) -> &Address; - } - } -} - -impl> IntoTxEnv for EnrichedMegaTx { - delegate! { - to self.inner { - fn into_tx_env(self) -> Tx; - } - } -} - -impl Copy for EnrichedMegaTx {} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; - use alloy_primitives::{address, bytes::BufMut, Signature}; - use revm::context::TxEnv; - - const CALLER: Address = address!("2000000000000000000000000000000000000001"); - const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - - #[derive(Debug, Clone)] - struct MockTx { - nonce: u64, - gas_limit: u64, - value: U256, - input: Bytes, - } - - impl Typed2718 for MockTx { - fn ty(&self) -> u8 { - 0 - } - } - - impl Encodable2718 for MockTx { - fn encode_2718_len(&self) -> usize { - self.input.len() - } - - fn encode_2718(&self, out: &mut dyn BufMut) { - out.put_slice(&self.input); - } - } - - impl Transaction for MockTx { - fn chain_id(&self) -> Option { - Some(1) - } - - fn nonce(&self) -> u64 { - self.nonce - } - - fn gas_limit(&self) -> u64 { - self.gas_limit - } - - fn gas_price(&self) -> Option { - Some(9) - } - - fn max_fee_per_gas(&self) -> u128 { - 9 - } - - fn max_priority_fee_per_gas(&self) -> Option { - None - } - - fn max_fee_per_blob_gas(&self) -> Option { - None - } - - fn priority_fee_or_price(&self) -> u128 { - 9 - } - - fn effective_gas_price(&self, _base_fee: Option) -> u128 { - 9 - } - - fn is_dynamic_fee(&self) -> bool { - false - } - - fn kind(&self) -> TxKind { - TxKind::Call(CONTRACT) - } - - fn is_create(&self) -> bool { - false - } - - fn value(&self) -> U256 { - self.value - } - - fn input(&self) -> &Bytes { - &self.input - } - - fn access_list(&self) -> Option<&AccessList> { - None - } - - fn blob_versioned_hashes(&self) -> Option<&[B256]> { - None - } - - fn authorization_list(&self) -> Option<&[SignedAuthorization]> { - None - } - } - - #[derive(Debug, Clone)] - struct MockRecoveredTx { - tx: TxEnv, - signer: Address, - } - - impl RecoveredTx for MockRecoveredTx { - fn tx(&self) -> &TxEnv { - &self.tx - } - - fn signer(&self) -> &Address { - &self.signer - } - } - - impl IntoTxEnv for MockRecoveredTx { - fn into_tx_env(self) -> TxEnv { - self.tx - } - } - - fn legacy_tx() -> TxLegacy { - TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - } - } - - fn legacy_envelope() -> MegaTxEnvelope { - MegaTxEnvelope::Legacy(Signed::new_unchecked( - legacy_tx(), - Signature::test_signature(), - Default::default(), - )) - } - - #[test] - fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx.clone(), CALLER); - - assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); - assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); - assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); - assert!(MegaTransactionExt::tx_size(&tx) > 0); - } - - #[test] - fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { - let tx = MockTx { - nonce: 7, - gas_limit: 21_000, - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - }; - let expected_hash = tx.trie_hash(); - let expected_da_size = - op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()); - let expected_tx_size = tx.encode_2718_len() as u64; - - let enriched = EnrichedMegaTx::new_slow(tx); - - assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); - assert_eq!(enriched.da_size, expected_da_size); - assert_eq!(enriched.tx_size, expected_tx_size); - assert_eq!(enriched.nonce(), 7); - assert_eq!(enriched.gas_limit(), 21_000); - assert_eq!(enriched.value(), U256::from(11)); - assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); - } - - #[test] - fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { - let tx_env = TxEnv { - caller: CALLER, - gas_limit: 21_000, - kind: TxKind::Call(CONTRACT), - value: U256::from(11), - data: Bytes::from_static(&[0xaa, 0xbb]), - ..Default::default() - }; - let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; - let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); - - assert_eq!(enriched.tx(), &tx_env); - assert_eq!(*enriched.signer(), CALLER); - - let converted: TxEnv = enriched.into_tx_env(); - assert_eq!(converted, tx_env); - } -} diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs deleted file mode 100644 index bdf5fd3b8..000000000 --- a/crates/mega-evm/src/block/limit.rs +++ /dev/null @@ -1,1147 +0,0 @@ -//! Block-level resource limit enforcement for `MegaETH`. -//! -//! This module provides comprehensive limit tracking and enforcement for block-level resources -//! in the `MegaETH` EVM. It implements a two-phase checking system to optimize block construction -//! while preventing spam attacks and ensuring fair resource allocation. -//! -//! # Overview -//! -//! `MegaEVM` enforces **6 types of limits**, each with both **transaction-level** and -//! **block-level** variants: -//! -//! 1. **Gas Limit** - Traditional EVM gas consumption -//! 2. **Transaction Size Limit** - EIP-2718 encoded transaction size -//! 3. **Data Availability (DA) Size Limit** - Compressed DA size -//! 4. **Compute Gas Limit** - Actual computational cost (separate from standard gas) -//! 5. **Data Size Limit** - Total execution data generated -//! 6. **KV Update Limit** - Storage operations count -//! -//! # Two-Phase Checking Strategy -//! -//! ## Phase 1: Pre-execution Checks (Limits 1-3) -//! -//! **When**: Before transaction execution -//! **What**: Validates gas limit, transaction size, and DA size -//! **Purpose**: Fast rejection of oversized transactions without expensive execution -//! -//! ### Transaction-level Violations -//! - **Error**: [`MegaTxLimitExceededError`] -//! - **Action**: Transaction is **rejected permanently** (invalid transaction) -//! - **Reason**: Transaction exceeds individual limit (e.g., gas > `tx_gas_limit`) -//! - **Example**: A transaction declares 50M gas when limit is 30M gas -//! -//! ### Block-level Violations -//! - **Error**: [`MegaBlockLimitExceededError`] or -//! [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`] -//! - **Action**: Transaction is **skipped**, try next transaction -//! - **Reason**: Including this transaction would exceed block capacity -//! - **Example**: Block has 5M gas remaining, transaction needs 10M gas -//! -//! ## Phase 2: Post-execution Checks (Limits 4-6) -//! -//! **When**: After transaction execution, before state commitment -//! **What**: Validates compute gas, data size, and KV updates -//! **Purpose**: Enforce limits based on actual execution results -//! -//! ### Transaction-level Enforcement (During Execution) -//! - **Location**: Enforced in [`crate::evm::limit::AdditionalLimit`] -//! - **Behavior**: Transaction halts with `OutOfGas`, remaining gas preserved -//! - **Result**: Transaction fails (status=0) but is **still included in block** -//! - **Reason**: Failed transactions consume resources and must be recorded on-chain -//! -//! ### Block-level Enforcement (Before Next Transaction) -//! - The first transaction that causes the block to exceed limits is **allowed to execute and be -//! included** -//! - **Pre-execution check**: Before executing the next transaction, check if block limit has -//! already been exceeded -//! - **Action**: If limit already exceeded, reject transaction before execution -//! - **Reason**: Maximize block utilization by not wasting valid transaction execution -//! - **Example**: Block has 10MB data limit. TX1 uses 6MB (included), TX2 uses 8MB (included, total -//! 14MB exceeds limit), TX3 is rejected before execution -//! -//! # Architecture -//! -//! The module consists of two main types: -//! -//! - [`BlockLimits`]: Configuration struct defining all limit thresholds -//! - [`BlockLimiter`]: Stateful tracker that enforces limits and accumulates resource usage -//! -//! # Limit Types -//! -//! ## Pre-execution Limits (Checked before execution) -//! -//! 1. **Gas Limit** -//! - Tx-level: `tx_gas_limit` - Maximum gas per transaction -//! - Block-level: `block_gas_limit` - Total gas available in block -//! -//! 2. **Transaction Size Limit** -//! - Tx-level: `tx_encode_size_limit` - Maximum encoded transaction size -//! - Block-level: `block_txs_encode_size_limit` - Total uncompressed transaction size in block -//! -//! 3. **Data Availability Size Limit** -//! - Tx-level: `tx_da_size_limit` - Maximum DA size per transaction -//! - Block-level: `block_da_size_limit` - Total compressed DA size in block -//! - **Note**: Deposit transactions are exempt from DA size limit checks -//! -//! ## Post-execution Limits (Checked during/after execution) -//! -//! 4. **Compute Gas Limit** -//! - Tx-level: `tx_compute_gas_limit` - Maximum compute gas per transaction -//! - Block-level: `block_compute_gas_limit` - Total compute gas in block -//! -//! 5. **Data Size Limit** -//! - Tx-level: `tx_data_limit` - Maximum data per transaction -//! - Block-level: `block_txs_data_limit` - Total execution data in block -//! - Includes: tx data, logs, storage writes, account updates, contract code -//! -//! 6. **KV Update Limit** -//! - Tx-level: `tx_kv_update_limit` - Maximum storage updates per transaction -//! - Block-level: `block_kv_update_limit` - Total storage updates in block -//! - Tracks: SSTORE operations and account updates -//! -//! # Deposit Transaction Exemptions -//! -//! Deposit transactions (Optimism Layer 1 to Layer 2 deposits) receive special treatment: -//! -//! - **DA Size Limit Exemption**: Deposit transactions are exempt from both transaction-level and -//! block-level Data Availability size limit checks during pre-execution validation -//! - **Rationale**: Deposit transactions are trustless L1→L2 messages that cannot be censored. They -//! must be included in blocks regardless of their DA size to maintain bridge integrity -//! - **Tracking**: Deposit DA sizes are **not** accumulated into the block DA usage counter -//! (`post_execution_update` skips them), so `block_da_size_used` reflects non-deposit -//! transactions only -//! - **Other Limits**: Deposit transactions are still subject to all other limits (gas, tx size, -//! compute gas, data size, KV updates) -//! -//! # Block Building Workflow -//! -//! For each transaction in the mempool: -//! -//! 1. **Pre-execution check** - [`BlockLimiter::pre_execution_check`] -//! - If tx-level violation → Reject permanently -//! - If block-level violation → Skip, try next transaction -//! -//! 2. **Execute transaction** - [`crate::MegaBlockExecutor::execute_mega_transaction`] -//! - During execution, tx-level limits (4-6) are enforced in EVM -//! - If exceeded → Transaction fails but continues to step 3 -//! -//! 3. **Post-execution update** - [`BlockLimiter::post_execution_update`] -//! - Accumulates resource usage from the executed transaction into block-level counters -//! - Does not validate post-execution limits; over-limit enforcement happens before admitting -//! the next transaction in [`BlockLimiter::pre_execution_check`] -//! -//! 4. **Commit transaction** - [`crate::MegaBlockExecutor::commit_execution_outcome`] -//! - Include in block (with success or failed receipt) -//! - Update block usage counters -//! -//! # Configuration -//! -//! ## For EQUIVALENCE Specification (Optimism Isthmus Compatible) -//! -//! ```rust,ignore -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .fit_equivalence(); -//! ``` -//! -//! ## For `MINI_REX` Specification (Enhanced with Additional Limits) -//! -//! ```rust,ignore -//! use mega_evm::constants::mini_rex; -//! -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .fit_mini_rex(); // Sets all MINI_REX limits automatically -//! ``` -//! -//! Or configure manually: -//! -//! ```rust,ignore -//! let limits = BlockLimits::no_limits() -//! .with_block_gas_limit(block_env.gas_limit) -//! .with_tx_compute_gas_limit(mini_rex::TX_COMPUTE_GAS_LIMIT) -//! .with_block_txs_data_limit(mini_rex::BLOCK_DATA_LIMIT) -//! .with_block_kv_update_limit(mini_rex::BLOCK_KV_UPDATE_LIMIT); -//! ``` -//! -//! # Error Handling -//! -//! ## Transaction-level Errors (Permanent Rejection) -//! - [`MegaTxLimitExceededError::TransactionGasLimit`] - Gas limit too high -//! - [`MegaTxLimitExceededError::TransactionEncodeSizeLimit`] - Transaction too large -//! - [`MegaTxLimitExceededError::DataAvailabilitySizeLimit`] - DA size too large -//! -//! ## Block-level Errors (Skip and Try Next) -//! - [`MegaBlockLimitExceededError::ComputeGasLimit`] - Would exceed block compute gas -//! - [`MegaBlockLimitExceededError::TransactionDataLimit`] - Would exceed block data limit -//! - [`MegaBlockLimitExceededError::KVUpdateLimit`] - Would exceed block KV updates -//! - [`MegaBlockLimitExceededError::TransactionEncodeSizeLimit`] - Would exceed block tx size -//! - [`MegaBlockLimitExceededError::DataAvailabilitySizeLimit`] - Would exceed block DA size -//! - [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`] - Insufficient gas -//! -//! # See Also -//! -//! - [`crate::evm::limit`] - Transaction-level limit enforcement during execution -//! - [`crate::MegaBlockExecutor`] - Block executor that orchestrates limit checks - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::boxed::Box; - -use alloy_consensus::Transaction; -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - RecoveredTx, -}; -use alloy_primitives::TxHash; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; - -use crate::{ - BlockMegaTransactionOutcome, EvmTxRuntimeLimits, MegaBlockLimitExceededError, MegaHardfork, - MegaTransactionExt, MegaTxLimitExceededError, -}; - -/// Configuration for block-level resource limits. The block-level resource limits are associated -/// with a specific `MegaHardfork` instead of a `MegaSpecId`. In constrast, `EvmTxRuntimeLimits` is -/// associated with a `MegaSpecId`. -/// -/// This struct defines the thresholds for various resource limits that govern transaction -/// inclusion and block construction. Limits are categorized into two groups: -/// -/// 1. **Pre-execution limits**: Checked before transaction execution (gas, size, DA size) -/// 2. **Post-execution limits**: Checked after execution (data size, KV updates) -/// -/// # Default Behavior -/// -/// By default, most limits are set to `u64::MAX` (effectively unlimited) except for: -/// - `block_txs_data_limit`: Set to [`crate::constants::mini_rex::BLOCK_DATA_LIMIT`] -/// - `block_kv_update_limit`: Set to [`crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT`] -/// - `block_gas_limit`: Auto-set from the EVM block environment (cannot be manually configured) -/// -/// # Builder Pattern -/// -/// Use builder methods to configure specific limits: -/// -/// ```rust,ignore -/// let limits = BlockLimits::default() -/// .with_tx_gas_limit(15_000_000) -/// .with_block_txs_encode_size_limit(1_000_000) -/// .with_block_txs_data_limit(5_000); -/// ``` -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct BlockLimits { - /// Maximum gas limit for a single transaction. - /// - /// Transactions with gas limits exceeding this value will be rejected with - /// [`MegaTxLimitExceededError::TransactionGasLimit`]. - pub tx_gas_limit: u64, - - /// Total gas limit for the block. - /// - /// Transactions that would cause the cumulative block gas to exceed this limit are rejected - /// with [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`]. - pub block_gas_limit: u64, - - /// Maximum encoded size (in bytes) for a single transaction. - /// - /// This limit applies to the transaction's EIP-2718 encoded size. Transactions exceeding - /// this size will be rejected with [`MegaTxLimitExceededError::TransactionEncodeSizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub tx_encode_size_limit: u64, - - /// Maximum cumulative size (in bytes) of all transaction bodies in a block. - /// - /// This limit applies to the **uncompressed** transaction size. For compressed data - /// availability limits, see [`block_da_size_limit`](Self::block_da_size_limit). - /// - /// Transactions that would cause the cumulative block transaction size to exceed this - /// limit are rejected with [`MegaBlockLimitExceededError::TransactionEncodeSizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub block_txs_encode_size_limit: u64, - - /// Maximum data availability size (in bytes) for a single transaction. - /// - /// This represents the compressed size for data availability purposes. Transactions - /// exceeding this size will be rejected with - /// [`MegaTxLimitExceededError::DataAvailabilitySizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub tx_da_size_limit: u64, - - /// Maximum cumulative data availability size (in bytes) for all transactions in a block. - /// - /// This applies to the **compressed** transaction size for data availability. For - /// uncompressed transaction body limits, see - /// [`block_txs_encode_size_limit`](Self::block_txs_encode_size_limit). - /// - /// Transactions that would cause the cumulative block DA size to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::DataAvailabilitySizeLimit`]. - /// - /// Default: `u64::MAX` (effectively unlimited) - pub block_da_size_limit: u64, - - /// Maximum data size of a single transaction's execution outcome, i.e., encoded transaction - /// object, encoded state changes, logs, etc. The data will need to be saved and transmitted - /// over network. - pub tx_data_limit: u64, - - /// Maximum cumulative data size (in bytes) of all transactions' execution outcomes from block - /// execution. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total data produced by all transactions in the block, including - /// logs, return data, and other execution artifacts. - /// - /// Transactions that would cause the cumulative block data to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::TransactionDataLimit`], and their state - /// changes are **not committed**. - /// - /// Note: Transaction-level data limits are enforced separately in the `MegaEVM`. - /// Transactions exceeding transaction-level limits may still be included but marked - /// as failed. - pub block_txs_data_limit: u64, - - /// Maximum key-value updates for a single transaction. - pub tx_kv_update_limit: u64, - - /// Maximum cumulative key-value updates allowed in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total number of storage slot updates (SSTORE operations) across - /// all transactions in the block. - /// - /// Transactions that would cause the cumulative KV updates to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::KVUpdateLimit`], and their state changes - /// are **not committed**. - /// - /// Note: Transaction-level KV update limits are enforced separately in the `MegaEVM`. - /// Transactions exceeding transaction-level limits may still be included but marked - /// as failed. - pub block_kv_update_limit: u64, - - /// Maximum compute gas limit for a single transaction. - pub tx_compute_gas_limit: u64, - - /// Maximum cumulative compute gas limit for all transactions in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total compute gas consumed by all transactions in the block. - /// - /// Transactions that would cause the cumulative block compute gas to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::ComputeGasLimit`], and their state changes - /// are **not committed**. - pub block_compute_gas_limit: u64, - - /// Maximum state growth limit for a single transaction. - pub tx_state_growth_limit: u64, - - /// Maximum cumulative state growth limit for all transactions in a block. - /// - /// This limit is checked **after** transaction execution but **before** committing state - /// changes. It tracks the total state growth consumed by all transactions in the block. - /// - /// Transactions that would cause the cumulative block state growth to exceed this limit are - /// rejected with [`MegaBlockLimitExceededError::StateGrowthLimit`], and their state changes - /// are **not committed**. - pub block_state_growth_limit: u64, - - /// Compute gas limit when accessing block environment data. - /// - /// When a transaction accesses volatile block environment data (e.g., TIMESTAMP, COINBASE), - /// the compute gas is capped to this limit to prevent `DoS` attacks. - pub block_env_access_compute_gas_limit: u64, - - /// Compute gas limit when accessing oracle data. - /// - /// When a transaction accesses the oracle contract, the compute gas is capped to this - /// limit to prevent `DoS` attacks. - pub oracle_access_compute_gas_limit: u64, -} - -impl BlockLimits { - /// Creates a new block limits instance with no limits. - pub fn no_limits() -> Self { - Self { - tx_gas_limit: u64::MAX, - block_gas_limit: u64::MAX, - tx_encode_size_limit: u64::MAX, - block_txs_encode_size_limit: u64::MAX, - tx_da_size_limit: u64::MAX, - block_da_size_limit: u64::MAX, - tx_data_limit: u64::MAX, - block_txs_data_limit: u64::MAX, - tx_kv_update_limit: u64::MAX, - block_kv_update_limit: u64::MAX, - tx_compute_gas_limit: u64::MAX, - block_compute_gas_limit: u64::MAX, - tx_state_growth_limit: u64::MAX, - block_state_growth_limit: u64::MAX, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - /// Creates a new block limits instance from a hardfork and a block gas limit. - pub fn from_hardfork_and_block_gas_limit(hardfork: MegaHardfork, block_gas_limit: u64) -> Self { - let spec = hardfork.spec_id(); - let tx_runtime_limits = EvmTxRuntimeLimits::from_spec(spec); - let limits = Self::no_limits() - .with_tx_runtime_limits(tx_runtime_limits) - .with_block_gas_limit(block_gas_limit); - match hardfork { - MegaHardfork::Rex | - MegaHardfork::Rex1 | - MegaHardfork::Rex2 | - MegaHardfork::Rex3 | - MegaHardfork::Rex4 | - MegaHardfork::Rex5 | - MegaHardfork::Rex6 | - MegaHardfork::Rex7 => Self { - block_txs_data_limit: crate::constants::mini_rex::BLOCK_DATA_LIMIT, - block_kv_update_limit: crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - block_state_growth_limit: crate::constants::rex::BLOCK_STATE_GROWTH_LIMIT, - ..limits - }, - MegaHardfork::MiniRex | MegaHardfork::MiniRex2 => Self { - block_txs_data_limit: crate::constants::mini_rex::BLOCK_DATA_LIMIT, - block_kv_update_limit: crate::constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - ..limits - }, - MegaHardfork::MiniRex1 => limits, - } - } -} - -impl BlockLimits { - /// Sets the related fields - pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { - self.tx_data_limit = limits.tx_data_size_limit; - self.tx_kv_update_limit = limits.tx_kv_updates_limit; - self.tx_compute_gas_limit = limits.tx_compute_gas_limit; - self.tx_state_growth_limit = limits.tx_state_growth_limit; - self.block_env_access_compute_gas_limit = limits.block_env_access_compute_gas_limit; - self.oracle_access_compute_gas_limit = limits.oracle_access_compute_gas_limit; - self - } - - /// Set a custom transaction gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction gas limit. Transactions with gas limits - /// exceeding this value will be rejected. - /// - /// # Parameters - /// - /// - `limit`: Maximum gas limit for a single transaction - /// - /// # Example - /// - /// ```rust,ignore - /// let limits = BlockLimits::default() - /// .with_tx_gas_limit(15_000_000); - /// ``` - pub fn with_tx_gas_limit(mut self, limit: u64) -> Self { - self.tx_gas_limit = limit; - self - } - - /// Set a custom block gas limit. - /// - /// **Warning**: This setting is **overridden** during block executor initialization. - /// The block gas limit is automatically set from the EVM block environment's gas limit. - /// This method exists for testing purposes only. - /// - /// # Parameters - /// - /// - `limit`: Block gas limit (will be overridden at runtime) - pub fn with_block_gas_limit(mut self, limit: u64) -> Self { - self.block_gas_limit = limit; - self - } - - /// Set a custom transaction encode size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction encode size limit. - pub fn with_tx_encode_size_limit(mut self, limit: u64) -> Self { - self.tx_encode_size_limit = limit; - self - } - - /// Set a custom block transactions encode size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block transactions encode size limit. - pub fn with_block_txs_encode_size_limit(mut self, limit: u64) -> Self { - self.block_txs_encode_size_limit = limit; - self - } - - /// Set a custom transaction data availability size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction data availability size limit. - pub fn with_tx_da_size_limit(mut self, limit: u64) -> Self { - self.tx_da_size_limit = limit; - self - } - - /// Set a custom block data availability size limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified data availability size limit. - pub fn with_block_da_size_limit(mut self, limit: u64) -> Self { - self.block_da_size_limit = limit; - self - } - - /// Set a custom transaction data limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction data limit. - pub fn with_tx_data_limit(mut self, limit: u64) -> Self { - self.tx_data_limit = limit; - self - } - - /// Set a custom block transactions data limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block transactions data limit. - pub fn with_block_txs_data_limit(mut self, limit: u64) -> Self { - self.block_txs_data_limit = limit; - self - } - - /// Set a custom transaction KV update limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction KV update limit. - pub fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { - self.tx_kv_update_limit = limit; - self - } - - /// Set a custom block KV update limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified KV update limit. - pub fn with_block_kv_update_limit(mut self, limit: u64) -> Self { - self.block_kv_update_limit = limit; - self - } - - /// Set a custom transaction compute gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction compute gas limit. - pub fn with_tx_compute_gas_limit(mut self, limit: u64) -> Self { - self.tx_compute_gas_limit = limit; - self - } - - /// Set a custom block compute gas limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block compute gas limit. - pub fn with_block_compute_gas_limit(mut self, limit: u64) -> Self { - self.block_compute_gas_limit = limit; - self - } - - /// Set a custom transaction state growth limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified transaction state growth limit. - pub fn with_tx_state_growth_limit(mut self, limit: u64) -> Self { - self.tx_state_growth_limit = limit; - self - } - - /// Set a custom block state growth limit. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block state growth limit. - pub fn with_block_state_growth_limit(mut self, limit: u64) -> Self { - self.block_state_growth_limit = limit; - self - } - - /// Set a custom compute gas limit when accessing block environment data. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified block environment access compute gas limit. - pub fn with_block_env_access_compute_gas_limit(mut self, limit: u64) -> Self { - self.block_env_access_compute_gas_limit = limit; - self - } - - /// Set a custom compute gas limit when accessing oracle data. - /// - /// This is a builder method that consumes self and returns a new instance - /// with the specified oracle access compute gas limit. - pub fn with_oracle_access_compute_gas_limit(mut self, limit: u64) -> Self { - self.oracle_access_compute_gas_limit = limit; - self - } - - /// Create a new block limiter from these limits. - /// - /// This converts the limit configuration into a stateful [`BlockLimiter`] that tracks - /// resource usage and enforces the configured limits throughout block execution. - /// - /// # Returns - /// - /// A new [`BlockLimiter`] initialized with zero usage for all tracked resources. - /// - /// # Example - /// - /// ```rust,ignore - /// let limits = BlockLimits::default().with_block_txs_data_limit(5_000); - /// let limiter = limits.to_block_limiter(); - /// ``` - pub fn to_block_limiter(self) -> BlockLimiter { - BlockLimiter { - limits: self, - block_gas_used: 0, - block_data_used: 0, - block_kv_updates_used: 0, - block_tx_size_used: 0, - block_da_size_used: 0, - block_compute_gas_used: 0, - block_state_growth_used: 0, - } - } - - /// Convert the block limits to the runtime limits for a single transaction. - pub fn to_evm_tx_runtime_limits(&self) -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: self.tx_data_limit, - tx_kv_updates_limit: self.tx_kv_update_limit, - tx_compute_gas_limit: self.tx_compute_gas_limit, - tx_state_growth_limit: self.tx_state_growth_limit, - block_env_access_compute_gas_limit: self.block_env_access_compute_gas_limit, - oracle_access_compute_gas_limit: self.oracle_access_compute_gas_limit, - } - } -} - -/// Stateful block resource limiter that tracks usage and enforces limits. -/// -/// This struct maintains cumulative resource usage throughout block execution and validates -/// that each transaction stays within both transaction-level and block-level limits. It -/// provides a two-phase checking mechanism: -/// -/// 1. **Pre-execution**: Validates limits that can be determined before execution (gas limit, -/// transaction size, DA size) -/// 2. **Post-execution**: Validates limits based on execution results (data size, KV updates) and -/// updates the usage accumulators -/// -/// # Resource Tracking -/// -/// The limiter tracks five cumulative metrics: -/// - Gas consumed by all transactions -/// - Total transaction body size -/// - Total data availability size -/// - Total execution data generated -/// - Total key-value storage updates -/// -/// # Usage Pattern -/// -/// ```rust,ignore -/// let mut limiter = BlockLimits::default().to_block_limiter(); -/// -/// for tx in transactions { -/// // Pre-execution check -/// limiter.pre_execution_check(tx.hash(), tx.gas_limit(), tx.size(), tx.da_size(), is_deposit)?; -/// -/// let outcome = execute_transaction(tx); -/// -/// // Post-execution update -/// limiter.post_execution_update(&outcome)?; -/// } -/// ``` -#[derive(Debug, Clone)] -pub struct BlockLimiter { - /// The configured resource limits. - pub limits: BlockLimits, - - /// Cumulative gas consumed by all committed transactions in the block. - pub block_gas_used: u64, - - /// Cumulative encoded size of all transaction bodies in the block (uncompressed). - pub block_tx_size_used: u64, - - /// Cumulative data availability size for all transactions in the block (compressed). - pub block_da_size_used: u64, - - /// Cumulative execution data generated by all transactions in the block. - /// - /// This includes the encoded transaction object, logs, return data, and other execution - /// artifacts. - pub block_data_used: u64, - - /// Cumulative key-value storage updates performed by all transactions in the block. - /// - /// This tracks the total number of SSTORE operations across all transactions. - pub block_kv_updates_used: u64, - - /// Cumulative compute gas consumed by all transactions in the block. - pub block_compute_gas_used: u64, - - /// Cumulative state growth consumed by all transactions in the block. - pub block_state_growth_used: u64, -} - -impl BlockLimiter { - /// Create a new block limiter with the specified limits. - /// - /// Initializes a limiter with all resource usage counters set to zero. - /// - /// # Parameters - /// - /// - `limits`: The resource limit configuration - /// - /// # Returns - /// - /// A new limiter ready to track resource usage - pub fn new(limits: BlockLimits) -> Self { - Self { - limits, - block_gas_used: 0, - block_data_used: 0, - block_kv_updates_used: 0, - block_tx_size_used: 0, - block_da_size_used: 0, - block_compute_gas_used: 0, - block_state_growth_used: 0, - } - } - - /// Validate transaction against pre-execution limits. - /// - /// This method validates that a transaction can be included in the block by checking - /// limits that are known before execution: - /// - Single transaction gas limit - /// - Remaining block gas capacity - /// - Single transaction size limit - /// - Remaining block transaction size capacity - /// - Single transaction DA size limit - /// - Remaining block DA size capacity - /// - /// **Important**: This method does **not** modify any state. It only performs validation. - /// Call [`post_execution_update`](Self::post_execution_update) after execution to update - /// usage counters. - /// - /// # Parameters - /// - /// - `tx_hash`: Transaction hash for error reporting - /// - `gas_limit`: Transaction's declared gas limit - /// - `tx_size`: Transaction's encoded size in bytes (EIP-2718 encoding) - /// - `da_size`: Transaction's compressed data availability size in bytes - /// - `is_deposit`: Whether the transaction is an L1-to-L2 deposit (exempt from DA size limits) - /// - /// # Returns - /// - /// - `Ok(())`: Transaction passes all pre-execution checks - /// - `Err(BlockExecutionError)`: Transaction violates one or more limits - /// - /// # Errors - /// - /// Returns [`BlockExecutionError::Validation`] containing either: - /// - [`MegaTxLimitExceededError`]: Transaction exceeds its own limits (invalid transaction) - /// - [`MegaBlockLimitExceededError`]: Transaction would exceed block capacity - /// - [`BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas`][] - Insufficient - /// remaining gas in block - /// - /// # Example - /// - /// ```rust,ignore - /// let mut limiter = BlockLimits::default().to_block_limiter(); - /// - /// limiter.pre_execution_check( - /// tx.hash(), - /// tx.gas_limit(), - /// tx.encode_2718_len() as u64, - /// tx.estimated_da_size(), - /// tx.is_deposit(), - /// )?; - /// ``` - pub fn pre_execution_check( - &self, - tx_hash: TxHash, - gas_limit: u64, - tx_size: u64, - da_size: u64, - is_deposit: bool, - ) -> Result<(), BlockExecutionError> { - // Check single transaction gas limit - if gas_limit > self.limits.tx_gas_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::TransactionGasLimit { - tx_gas_limit: gas_limit, - limit: self.limits.tx_gas_limit, - }), - })); - } - - // Check block gas limit - if self.block_gas_used.saturating_add(gas_limit) > self.limits.block_gas_limit { - return Err(BlockExecutionError::Validation( - BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { - transaction_gas_limit: gas_limit, - block_available_gas: self - .limits - .block_gas_limit - .saturating_sub(self.block_gas_used), - }, - )); - } - - // Check single transaction size limit - if tx_size > self.limits.tx_encode_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::TransactionEncodeSizeLimit { - tx_size, - limit: self.limits.tx_encode_size_limit, - }), - })); - } - - // Check block transaction size limit - if tx_size.saturating_add(self.block_tx_size_used) > self.limits.block_txs_encode_size_limit - { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::TransactionEncodeSizeLimit { - block_used: self.block_tx_size_used, - tx_used: tx_size, - limit: self.limits.block_txs_encode_size_limit, - }), - })); - } - - // Deposit transactions are exempt from data availability size limits - if !is_deposit { - // Check single transaction data availability size limit - if da_size > self.limits.tx_da_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaTxLimitExceededError::DataAvailabilitySizeLimit { - da_size, - limit: self.limits.tx_da_size_limit, - }), - })); - } - - // Check block data availability size limit - if da_size.saturating_add(self.block_da_size_used) > self.limits.block_da_size_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: self.block_da_size_used, - tx_used: da_size, - limit: self.limits.block_da_size_limit, - }), - })); - } - } - - // Check block-level data limit - if self.block_data_used >= self.limits.block_txs_data_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::TransactionDataLimit { - block_used: self.block_data_used, - limit: self.limits.block_txs_data_limit, - }), - })); - } - - // Check block-level kv update limit - if self.block_kv_updates_used >= self.limits.block_kv_update_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::KVUpdateLimit { - block_used: self.block_kv_updates_used, - limit: self.limits.block_kv_update_limit, - }), - })); - } - - // Check block-level compute gas limit - if self.block_compute_gas_used >= self.limits.block_compute_gas_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::ComputeGasLimit { - block_used: self.block_compute_gas_used, - limit: self.limits.block_compute_gas_limit, - }), - })); - } - - // Check block-level state growth limit - if self.block_state_growth_used >= self.limits.block_state_growth_limit { - return Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { - hash: tx_hash, - error: Box::new(MegaBlockLimitExceededError::StateGrowthLimit { - block_used: self.block_state_growth_used, - limit: self.limits.block_state_growth_limit, - }), - })); - } - - Ok(()) - } - - /// Update usage counters after transaction execution. - /// - /// This method is called **after** transaction execution to accumulate the executed - /// transaction's resource usage into the limiter's block-level counters. It does **not** - /// validate post-execution limits — over-limit enforcement happens in - /// [`pre_execution_check`](Self::pre_execution_check) before admitting the next transaction. - /// The transaction may cause the block to exceed limits, which is intentional to maximize - /// block utilization. - /// - /// The return type remains `Result` to leave room for future fallible post-execution logic; - /// the current implementation always returns `Ok(())`. - /// - /// # Parameters - /// - /// - `outcome`: The transaction execution outcome containing resource usage information - /// - /// # Returns - /// - /// - `Ok(())`: Usage counters updated successfully - /// - /// # State Modification - /// - /// This method updates all cumulative usage counters: - /// - `block_gas_used += gas_used` - /// - `block_tx_size_used += tx_size_used` - /// - `block_da_size_used += da_size_used` (only for non-deposit transactions) - /// - `block_data_used += data_size_used` - /// - `block_kv_updates_used += kv_updates_used` - /// - `block_compute_gas_used += compute_gas_used` - /// - `block_state_growth_used += state_growth_used` - /// - /// **Note**: The block may exceed limits after this update. This is intentional - the first - /// transaction that causes the block to exceed is allowed to be included. - /// - /// # Example - /// - /// ```rust,ignore - /// let outcome = executor.execute_mega_transaction(tx)?; - /// - /// // Accumulates usage; may cause block-level counters to exceed limits. - /// limiter.post_execution_update(&outcome)?; - /// - /// // Commit the transaction state - /// executor.commit_execution_outcome(outcome)?; - /// ``` - pub fn post_execution_update( - &mut self, - outcome: &BlockMegaTransactionOutcome>, - ) -> Result<(), BlockExecutionError> { - let is_deposit = outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE; - - self.post_execution_update_raw( - outcome.result.gas_used(), - outcome.tx_size, - outcome.da_size, - outcome.data_size, - outcome.kv_updates, - outcome.compute_gas_used, - outcome.state_growth_used, - is_deposit, - ); - - Ok(()) - } - - /// Update usage counters after transaction execution using raw values. - /// - /// This mirrors [`post_execution_update`](Self::post_execution_update) but takes precomputed - /// resource usage values instead of a full execution outcome. - #[allow(clippy::too_many_arguments)] - pub fn post_execution_update_raw( - &mut self, - gas_used: u64, - tx_size: u64, - da_size: u64, - tx_data: u64, - kv_updates: u64, - compute_gas_used: u64, - state_growth_used: u64, - is_deposit: bool, - ) { - // Block gas limit. No need to check here since it's checked before transaction execution. - self.block_gas_used = self.block_gas_used.saturating_add(gas_used); - - // Block tx size limit, no need to check here since it's checked before transaction - // execution. - self.block_tx_size_used = self.block_tx_size_used.saturating_add(tx_size); - - // Block da size limit, no need to check here since it's checked before transaction - // execution. Only appliable for non-deposit transactions. - if !is_deposit { - self.block_da_size_used = self.block_da_size_used.saturating_add(da_size); - } - - // Block data limit, no need to check here since we allow the last transaction to exceed the - // limit. - self.block_data_used = self.block_data_used.saturating_add(tx_data); - - // Block kv updates limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_kv_updates_used = self.block_kv_updates_used.saturating_add(kv_updates); - - // Block compute gas limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_compute_gas_used = self.block_compute_gas_used.saturating_add(compute_gas_used); - - // Block state growth limit, no need to check here since we allow the last transaction to - // exceed the limit. - self.block_state_growth_used = - self.block_state_growth_used.saturating_add(state_growth_used); - } - - /// Returns true if any block-level limit has been reached or exceeded. - pub fn is_block_limit_reached(&self) -> bool { - self.block_gas_used >= self.limits.block_gas_limit || - self.block_tx_size_used >= self.limits.block_txs_encode_size_limit || - self.block_da_size_used >= self.limits.block_da_size_limit || - self.block_data_used >= self.limits.block_txs_data_limit || - self.block_kv_updates_used >= self.limits.block_kv_update_limit || - self.block_compute_gas_used >= self.limits.block_compute_gas_limit || - self.block_state_growth_used >= self.limits.block_state_growth_limit - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::B256; - - /// Alias forks must configure exactly their behavior target's block limits: the - /// hand-written arm grouping in `from_hardfork_and_block_gas_limit` is reconciled with - /// `behavior()`, mirroring the instruction-table/precompile/runtime-limit reconciliation - /// tests. Driven off `VARIANTS` and `is_alias`, so a future alias fork joins automatically. - #[test] - fn test_alias_forks_use_their_behavior_targets_block_limits() { - const GAS: u64 = 1_000_000; - let alias_forks = - MegaHardfork::VARIANTS.iter().copied().filter(|fork| fork.spec_id().is_alias()); - let mut seen = 0; - for fork in alias_forks { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(fork, GAS); - let target = fork.spec_id().behavior(); - let expected = match MegaHardfork::VARIANTS - .iter() - .copied() - .find(|base| base.spec_id() as u8 == target as u8) - { - Some(base_fork) => BlockLimits::from_hardfork_and_block_gas_limit(base_fork, GAS), - // The target predates every fork (EQUIVALENCE): no block-level limits apply. - None => BlockLimits::no_limits() - .with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(fork.spec_id())) - .with_block_gas_limit(GAS), - }; - assert_eq!(limits, expected, "{fork:?} must mirror its behavior target {target:?}"); - seen += 1; - } - assert_eq!(seen, 2, "MiniRex1 and MiniRex2 are the alias forks under reconciliation"); - } - - fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = block_gas_limit; - limits.tx_gas_limit = u64::MAX; - limits - } - - fn limits_with_block_tx_size(block_txs_encode_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_txs_encode_size_limit = block_txs_encode_size_limit; - limits - } - - fn limits_with_block_da_size(block_da_size_limit: u64) -> BlockLimits { - let mut limits = BlockLimits::no_limits(); - limits.block_da_size_limit = block_da_size_limit; - limits - } - - #[test] - fn test_pre_execution_check_block_gas_addition_saturates() { - // Block has very high accumulated usage and a transaction with a near-`u64::MAX` - // gas limit; unchecked addition would wrap and accidentally pass the limit check. - let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); - limiter.block_gas_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); - assert!(result.is_err(), "saturating_add must keep the rejection in place"); - } - - #[test] - fn test_pre_execution_check_block_tx_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_tx_size(1_000_000)); - limiter.block_tx_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); - assert!(result.is_err()); - } - - #[test] - fn test_pre_execution_check_block_da_size_addition_saturates() { - let mut limiter = BlockLimiter::new(limits_with_block_da_size(1_000_000)); - limiter.block_da_size_used = u64::MAX - 10; - let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); - assert!(result.is_err()); - } - - #[test] - fn test_post_execution_update_raw_saturates_all_counters() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_gas_used = u64::MAX - 1; - limiter.block_tx_size_used = u64::MAX - 1; - limiter.block_da_size_used = u64::MAX - 1; - limiter.block_data_used = u64::MAX - 1; - limiter.block_kv_updates_used = u64::MAX - 1; - limiter.block_compute_gas_used = u64::MAX - 1; - limiter.block_state_growth_used = u64::MAX - 1; - - limiter.post_execution_update_raw( - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - u64::MAX, - false, - ); - - assert_eq!(limiter.block_gas_used, u64::MAX); - assert_eq!(limiter.block_tx_size_used, u64::MAX); - assert_eq!(limiter.block_da_size_used, u64::MAX); - assert_eq!(limiter.block_data_used, u64::MAX); - assert_eq!(limiter.block_kv_updates_used, u64::MAX); - assert_eq!(limiter.block_compute_gas_used, u64::MAX); - assert_eq!(limiter.block_state_growth_used, u64::MAX); - } - - #[test] - fn test_post_execution_update_raw_skips_da_for_deposits() { - // Deposit transactions should not advance `block_da_size_used`, even when the value - // would otherwise saturate. - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - limiter.block_da_size_used = 100; - - limiter.post_execution_update_raw(0, 0, u64::MAX, 0, 0, 0, 0, true); - - assert_eq!(limiter.block_da_size_used, 100); - } -} diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 0340cd82c..9141ade89 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -1,109 +1,11 @@ -//! Block execution abstraction for the `MegaETH` EVM. -//! -//! This module provides comprehensive block execution functionality specifically tailored for -//! the `MegaETH` chain, built on top of the Optimism EVM (`op-revm`) with MegaETH-specific -//! customizations and optimizations. -//! -//! # Architecture -//! -//! The block execution system consists of five main components: -//! -//! 1. **[`MegaBlockExecutorFactory`]**: Factory for creating block executors with `MegaETH` -//! specifications -//! 2. **[`MegaBlockExecutor`]**: The actual executor that processes transactions within a block -//! 3. **[`BlockLimits`]**: Configuration for block-level resource limits -//! 4. **[`BlockLimiter`]**: Stateful tracker that enforces limits and accumulates resource usage -//! 5. **[`MegaBlockExecutionCtx`]**: Context for block execution including parent hash and limits -//! -//! # Pre-Block State Changes and Witness Recording -//! -//! [`MegaBlockExecutor::pre_execution_changes`] collects `Option` outcomes from each -//! pre-block helper, and [`MegaBlockExecutor::commit_system_call_outcomes`] walks them calling -//! `system_caller.on_state(source, &state)` **before** `db.commit(state)` for every entry. The -//! `on_state` hook feeds the stateless witness generator with the complete read/write set, so -//! helpers must return all accounts and slots they touched — including pure reads on -//! idempotent no-change paths. See `crates/mega-evm/src/system/AGENTS.md` → -//! `PRE-BLOCK STATE CHANGE CONTRACT` for the helper-side contract. -//! -//! # Resource Limit Enforcement -//! -//! `MegaETH` implements a comprehensive resource limiting system to prevent `DoS` attacks and -//! ensure fair resource allocation. The system enforces limits at two levels: -//! -//! ## Transaction-level Limits -//! -//! Individual transactions are validated against: -//! - Gas limit per transaction -//! - Transaction body size -//! - Data availability (DA) size -//! -//! ## Block-level Limits -//! -//! Cumulative resource usage across all transactions in a block is validated against: -//! - Total gas consumption -//! - Total transaction size -//! - Total DA size -//! - Total execution data (logs, return data) -//! - Total key-value storage updates -//! -//! Limits are checked in two phases: -//! - **Pre-execution**: Gas, transaction size, and DA size (fast, no execution needed) -//! - **Post-execution**: Data size and KV updates (after execution, before commit) -//! -//! # EVM Specifications -//! -//! `MegaETH` supports two EVM specifications: -//! -//! - **`EQUIVALENCE`**: Maintains equivalence with Optimism Isthmus EVM (default) -//! - **`MINI_REX`**: Enhanced version with additional resource limits and modified gas costs -//! -//! # Usage Example -//! -//! ```rust,ignore -//! use mega_evm::{MegaBlockExecutorFactory, MegaBlockExecutionCtx, BlockLimits}; -//! -//! // Configure block limits -//! let limits = BlockLimits::default() -//! .with_block_txs_encode_size_limit(1_000_000) -//! .with_block_txs_data_limit(10_000); -//! -//! // Create execution context -//! let ctx = MegaBlockExecutionCtx::new(parent_hash, parent_beacon_root, extra_data) -//! .with_block_limits(limits); -//! -//! // Create executor factory -//! let factory = MegaBlockExecutorFactory::new(spec, evm_factory, receipt_builder); -//! -//! // Create and use executor -//! let mut executor = factory.create_executor_with_config(&mut state, ctx, evm_config); -//! executor.apply_pre_execution_changes()?; -//! executor.execute_transaction(tx)?; -//! let (evm, result) = executor.finish()?; -//! ``` -//! -//! # Performance Considerations -//! -//! The `MegaETH` block executor is optimized for high-performance blockchain operations: -//! -//! - Efficient delegation to the underlying Optimism EVM implementation -//! - Minimal overhead for MegaETH-specific features -//! - Two-phase limit checking minimizes unnecessary execution -//! - Support for parallel execution through access tracking -//! - Optimized gas calculations for modified opcodes +//! Block-level pieces of the Satin engine. mod chain; -mod eips; mod executor; -mod factory; mod hardfork; -mod helpers; -mod limit; mod result; pub use chain::*; pub use executor::*; -pub use factory::*; pub use hardfork::*; -pub use helpers::*; -pub use limit::*; pub use result::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index beb5ee2c0..f3e2f378a 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -1,179 +1,27 @@ -use alloy_evm::InvalidTxError; -use revm::state::AccountInfo; +//! What a block counts of its transactions' gas. -use crate::MegaTransactionOutcome; +use crate::MegaGasUsage; -/// The execution outcome of a transaction in `MegaETH`. +/// A block's gas, on the three ledgers its transactions spend on. /// -/// This struct contains additional information about the transaction execution on top of the -/// standard EVM's execution result and state. -#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)] -pub struct BlockMegaTransactionOutcome { - /// The transaction. - pub tx: T, - /// The transaction size in bytes. - pub tx_size: u64, - /// The transaction data availability size in bytes. - pub da_size: u64, - /// The depositor account info. - pub depositor: Option, - /// The transaction execution outcome. - #[deref] - #[deref_mut] - pub inner: MegaTransactionOutcome, +/// The block executor fills it transaction by transaction with [`record`](Self::record) and +/// holds each counter to its own block limit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BlockGasCounters { + /// Regular gas: each transaction's regular ledger, at least its EIP-7623 floor. + pub execution: u64, + /// State gas. + pub state: u64, + /// History gas. + pub history: u64, } -/// Error type for additional reasons of an invalid transaction. If one transaction is invalid, it -/// will never be able to be included in a block and should be discarded. -#[derive(Debug, Clone, thiserror::Error)] -pub enum MegaTxLimitExceededError { - /// Transaction gas limit exceeded. - #[error("Transaction gas limit exceeded: tx_gas_limit={tx_gas_limit} > limit={limit}")] - TransactionGasLimit { - /// Transaction gas limit used by current transaction - tx_gas_limit: u64, - /// Transaction gas limit limit - limit: u64, - }, - /// Transaction encode size limit exceeded. - #[error("Transaction encode size limit exceeded: tx_size={tx_size} > limit={limit}")] - TransactionEncodeSizeLimit { - /// Transaction encode size used by current transaction - tx_size: u64, - /// Transaction encode size limit - limit: u64, - }, - - /// Transaction data availability size limit exceeded. - #[error( - "Transaction data availability size limit exceeded: da_size={da_size} > limit={limit}" - )] - DataAvailabilitySizeLimit { - /// Data availability size used by current transaction - da_size: u64, - /// Data availability size limit - limit: u64, - }, -} - -impl MegaTxLimitExceededError { - /// The amount of the resource used by the current transaction. - pub fn usage(&self) -> u64 { - match self { - Self::TransactionGasLimit { tx_gas_limit, .. } => *tx_gas_limit, - Self::TransactionEncodeSizeLimit { tx_size, .. } => *tx_size, - Self::DataAvailabilitySizeLimit { da_size, .. } => *da_size, - } - } - - /// The limit of the resource. - pub fn limit(&self) -> u64 { - match self { - Self::TransactionGasLimit { limit, .. } | - Self::TransactionEncodeSizeLimit { limit, .. } | - Self::DataAvailabilitySizeLimit { limit, .. } => *limit, - } - } -} - -impl InvalidTxError for MegaTxLimitExceededError { - fn is_nonce_too_low(&self) -> bool { - false - } -} - -/// Error type for block-level limit exceeded. These errors are thrown when the block has already -/// exceeded its limit (from a previous transaction) and no more transactions can be added. -#[derive(Debug, Clone, thiserror::Error)] -pub enum MegaBlockLimitExceededError { - /// Block transactions data limit reached. - #[error("Block transactions data limit reached: block_used={block_used} >= limit={limit}")] - TransactionDataLimit { - /// Transaction data used by block so far - block_used: u64, - /// Block transactions data limit - limit: u64, - }, - - /// Block KV update limit reached. - #[error("Block KV update limit reached: block_used={block_used} >= limit={limit}")] - KVUpdateLimit { - /// KV updates used by block so far - block_used: u64, - /// Block KV update limit - limit: u64, - }, - - /// Block compute gas limit reached. - #[error("Block compute gas limit reached: block_used={block_used} >= limit={limit}")] - ComputeGasLimit { - /// Compute gas used by block so far - block_used: u64, - /// Block compute gas limit - limit: u64, - }, - - /// Block transactions encode size limit exceeded. - #[error("Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}")] - TransactionEncodeSizeLimit { - /// Transaction encode size used by block so far - block_used: u64, - /// Transaction encode size used by current transaction - tx_used: u64, - /// Block transactions encode size limit - limit: u64, - }, - - /// Block data availability size limit exceeded. - #[error("Block data availability size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}")] - DataAvailabilitySizeLimit { - /// Data availability size used by block so far - block_used: u64, - /// Data availability size used by current transaction - tx_used: u64, - /// Block data availability size limit - limit: u64, - }, - - /// Block state growth limit reached. - #[error("Block state growth limit reached: block_used={block_used} >= limit={limit}")] - StateGrowthLimit { - /// State growth used by block so far - block_used: u64, - /// Block state growth limit - limit: u64, - }, -} - -impl MegaBlockLimitExceededError { - /// The total amount of the resource used by the block so far. - pub fn block_used(&self) -> u64 { - match self { - Self::TransactionDataLimit { block_used, .. } | - Self::KVUpdateLimit { block_used, .. } | - Self::ComputeGasLimit { block_used, .. } | - Self::TransactionEncodeSizeLimit { block_used, .. } | - Self::DataAvailabilitySizeLimit { block_used, .. } | - Self::StateGrowthLimit { block_used, .. } => *block_used, - } - } - - /// The limit of the resource. - pub fn limit(&self) -> u64 { - match self { - Self::TransactionDataLimit { limit, .. } | - Self::KVUpdateLimit { limit, .. } | - Self::ComputeGasLimit { limit, .. } | - Self::TransactionEncodeSizeLimit { limit, .. } | - Self::DataAvailabilitySizeLimit { limit, .. } | - Self::StateGrowthLimit { limit, .. } => *limit, - } - } -} - -impl InvalidTxError for MegaBlockLimitExceededError { - fn is_nonce_too_low(&self) -> bool { - false +impl BlockGasCounters { + /// Adds one transaction's gas. + pub fn record(&mut self, gas: &MegaGasUsage) { + self.execution = self.execution.saturating_add(gas.block_execution_gas()); + self.state = self.state.saturating_add(gas.state); + self.history = self.history.saturating_add(gas.history); } } @@ -182,59 +30,25 @@ mod tests { use super::*; #[test] - fn test_transaction_limit_error_reports_usage_and_limit() { - let cases = [ - (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), - ( - MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, - 101, - 100, - ), - ( - MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, - 11, - 10, - ), - ]; - - for (error, expected_usage, expected_limit) in cases { - assert_eq!(error.usage(), expected_usage); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } + fn test_block_counters_add_each_ledger() { + let mut block = BlockGasCounters::default(); + let first = + MegaGasUsage { regular: 10, state: 20, history: 30, floor: 0, ..Default::default() }; + let floored = + MegaGasUsage { regular: 5, state: 1, history: 2, floor: 50, ..Default::default() }; + block.record(&first); + block.record(&floored); + assert_eq!(block, BlockGasCounters { execution: 60, state: 21, history: 32 }); } #[test] - fn test_block_limit_error_reports_block_usage_and_limit() { - let cases = [ - (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), - (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 2, limit: 11 }, 2, 11), - (MegaBlockLimitExceededError::ComputeGasLimit { block_used: 3, limit: 12 }, 3, 12), - ( - MegaBlockLimitExceededError::TransactionEncodeSizeLimit { - block_used: 4, - tx_used: 1, - limit: 13, - }, - 4, - 13, - ), - ( - MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: 5, - tx_used: 1, - limit: 14, - }, - 5, - 14, - ), - (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 6, limit: 15 }, 6, 15), - ]; - - for (error, expected_block_used, expected_limit) in cases { - assert_eq!(error.block_used(), expected_block_used); - assert_eq!(error.limit(), expected_limit); - assert!(!error.is_nonce_too_low()); - } + fn test_block_counters_saturate() { + let mut block = + BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX }; + block.record(&MegaGasUsage { regular: 1, state: 1, history: 1, ..Default::default() }); + assert_eq!( + block, + BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX } + ); } } diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 8afafdfd6..f959e1633 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -1,210 +1,61 @@ -//! Constants for the `MegaETH` EVM. +//! Numeric constants of the Satin engine. //! -//! It groups the constants for different EVM specs as sub-modules. - -/// Constants for the `EQUIVALENCE` spec. -pub mod equivalence { - use revm::interpreter::gas; - - /// Constants inherited from `revm`. - pub use gas::{ - BASE, BLOCKHASH, CALLVALUE, CALL_STIPEND, CODEDEPOSIT, COLD_ACCOUNT_ACCESS_COST, - COLD_SLOAD_COST, CREATE, KECCAK256WORD, LOG, LOGDATA, LOGTOPIC, NEWACCOUNT, SSTORE_RESET, - SSTORE_SET, STANDARD_TOKEN_COST, TOTAL_COST_FLOOR_PER_TOKEN, VERYLOW, WARM_SSTORE_RESET, - WARM_STORAGE_READ_COST, - }; - pub use revm::primitives::STACK_LIMIT; -} - -/// Constants for the `MINI_REX` spec. -pub mod mini_rex { - /// The maximum contract size for the `MINI_REX` spec. - pub const MAX_CONTRACT_SIZE: usize = 512 * 1024; - /// The additional initcode size for the `MINI_REX` spec. The initcode size is limited to - /// `MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE`. - pub const ADDITIONAL_INITCODE_SIZE: usize = 24 * 1024; - /// The maximum initcode size for the `MINI_REX` spec. - pub const MAX_INITCODE_SIZE: usize = MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE; - - /// The maximum compute gas allowed per transaction for the `MINI_REX` spec. - pub const TX_COMPUTE_GAS_LIMIT: u64 = 1_000_000_000; - - /// The base storage gas cost for setting a storage slot to a non-zero value for the `MINI_REX` - /// spec. Actual cost is dynamically scaled by SALT bucket capacity: `SSTORE_SET_GAS × - /// (bucket_capacity / MIN_BUCKET_SIZE)`. - pub const SSTORE_SET_STORAGE_GAS: u64 = 2_000_000; - /// The base storage gas cost for creating a new account for the `MINI_REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `NEW_ACCOUNT_GAS × - /// (bucket_capacity / MIN_BUCKET_SIZE)`. Applied when transaction targets new account, CALL - /// with transfer to empty account, or CREATE operations. - pub const NEW_ACCOUNT_STORAGE_GAS: u64 = 2_000_000; - /// Storage gas cost per byte for code deposit during contract creation in `MINI_REX` spec. - pub const CODEDEPOSIT_STORAGE_GAS: u64 = 10_000; - /// The storage gas cost for `LOGDATA` for the `MINI_REX` spec, i.e., gas cost per byte for log - /// data. - pub const LOG_DATA_STORAGE_GAS: u64 = super::equivalence::LOGDATA * 10; - /// The storage gas cost for `LOGTOPIC` for the `MINI_REX` spec, i.e., gas cost per topic for - /// log. - pub const LOG_TOPIC_STORAGE_GAS: u64 = super::equivalence::LOGTOPIC * 10; - /// The additional gas cost for `CALLDATA` for the `MINI_REX` spec, i.e., gas cost per token - /// (one byte) for call data. This is charged on top of the calldata cost of standard EVM. - pub const CALLDATA_STANDARD_TOKEN_STORAGE_GAS: u64 = - super::equivalence::STANDARD_TOKEN_COST * 10; - /// The additional gas cost for EIP-7623 floor gas cost, i.e., gas cost per token (one byte) - /// for call data. This is charged on top of the floor cost of standard EVM. - pub const CALLDATA_STANDARD_TOKEN_STORAGE_FLOOR_GAS: u64 = - super::equivalence::TOTAL_COST_FLOOR_PER_TOKEN * 10; - - /// The maximum amount of data allowed to generate from a block for the `MINI_REX` spec. - pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; // 12.5 MB - /// The maximum data size allowed per transaction for the `MINI_REX` spec. - /// Transactions exceeding this limit halt with `OutOfGas`, preserving remaining gas. - pub const TX_DATA_LIMIT: u64 = BLOCK_DATA_LIMIT * 25 / 100; // 25% of the block limit - /// The maximum amount of key-value updates allowed to generate from a block for the `MINI_REX` - /// spec. - pub const BLOCK_KV_UPDATE_LIMIT: u64 = 500_000; - /// The maximum amount of key-value updates allowed to generate from a transaction for the - /// `MINI_REX` spec. - pub const TX_KV_UPDATE_LIMIT: u64 = BLOCK_KV_UPDATE_LIMIT * 25 / 100; // 25% of the block limit - - /// Gas limit after block environment or beneficiary data access. - /// When block environment data or beneficiary account data is accessed, the compute gas - /// is limited to force the transaction to complete quickly and prevent `DoS` attacks. - /// - /// - **Pre-REX4**: This is an **absolute** cap on the transaction's total compute gas. - /// - **REX4+**: This is a **relative** cap — it limits post-access compute gas. The effective - /// limit becomes `current_usage + BLOCK_ENV_ACCESS_COMPUTE_GAS` at the point of access. - pub const BLOCK_ENV_ACCESS_COMPUTE_GAS: u64 = 20_000_000; - - /// Gas limit after oracle contract access. - /// When oracle contract is accessed, the compute gas is limited to force the transaction - /// to complete quickly and prevent `DoS` attacks. - /// - /// - **Pre-REX4**: This is an **absolute** cap on the transaction's total compute gas. - /// - **REX4+**: This is a **relative** cap — it limits post-access compute gas. The effective - /// limit becomes `current_usage + ORACLE_ACCESS_COMPUTE_GAS` at the point of access. - /// - /// Note: If block environment was accessed first (20M compute gas limit), then oracle is - /// accessed, the compute gas will be further restricted to this lower limit (1M compute - /// gas). - pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 1_000_000; -} - -/// Constants for the `REX2` spec. -pub mod rex2 { - /// Fixed overhead gas for the keylessDeploy operation. - /// This covers the cost of RLP decoding, signature recovery, and state filtering. - pub const KEYLESS_DEPLOY_OVERHEAD_GAS: u64 = 100_000; -} - -/// Constants for the `REX3` spec. -pub mod rex3 { - /// Gas limit after oracle contract access for the `REX3` spec. - /// Increased from 1M (used in `MINI_REX` through `REX2`) to 20M, giving oracle-accessing - /// transactions more room for post-oracle computation. - pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; -} - -/// Constants for the `REX4` spec. -pub mod rex4 { - /// Numerator of the fraction of parent's remaining resource budget forwarded to a child - /// frame. Applies to all four resource dimensions (data size, KV updates, compute gas, - /// state growth). - /// Child budget = `parent_remaining` * NUMERATOR / DENOMINATOR. - pub const FRAME_LIMIT_NUMERATOR: u64 = 98; - /// Denominator of the per-frame resource budget forwarding fraction. - pub const FRAME_LIMIT_DENOMINATOR: u64 = 100; - - /// Additional call stipend for storage operations in CALL/CALLCODE with value transfer. - /// - /// `MegaETH`'s 10x storage gas multiplier on LOG opcodes causes even a simple `LOG1` to cost - /// 4,500 gas (750 compute + 3,750 storage), exceeding the EVM's `CALL_STIPEND` of 2,300. - /// This breaks `transfer()` / `send()` to contracts that emit events in `receive()`. - /// - /// When an internal CALL or CALLCODE transfers value (value > 0), the callee receives this - /// extra gas on top of the standard `CALL_STIPEND`. - /// The callee's compute gas limit remains at the original level (`forwarded_gas + - /// CALL_STIPEND`), so the extra gas can only be consumed by storage gas operations (e.g., - /// the 10x LOG topic/data costs). - /// On return, unused `STORAGE_CALL_STIPEND` is burned — it is never returned to the caller. - pub const STORAGE_CALL_STIPEND: u64 = 23_000; -} - -/// Constants for the `REX5` spec. -pub mod rex5 { - /// Floor for the gas limit assigned to REX5 pre-block system calls that opt - /// into the live block gas budget via - /// [`crate::MegaEvm::transact_system_call_with_gas_limit`] — currently the - /// `SequencerRegistry.applyPendingChanges()`, EIP-2935 history-storage, and - /// EIP-4788 beacon-roots pre-block calls. - /// - /// The value (30M) matches the historical revm system-call default at the - /// time REX5 was specified — see the `gas_limit(30_000_000)` literal in - /// [`revm::handler::SystemCallTx::new_system_tx_with_caller`]'s `TxEnv` impl - /// (`revm-handler/src/system_call.rs`). - /// revm does not export this as a `pub const`, so we mirror the literal here - /// instead of aliasing it. Do NOT raise this value to follow upstream - /// changes — the floor must remain at the historical 30M to preserve - /// backward compatibility for REX5 chains whose block gas limit is smaller - /// than any new upstream default. Lifting it would silently increase the - /// minimum guaranteed budget and become observable via the `GAS` opcode - /// inside `applyPendingChanges()`. - /// - /// Keeping the floor at the historical default ensures test harnesses or - /// chains configured with a sub-30M block gas limit still receive the - /// budget that pre-REX5 / EIP-2935 / EIP-4788 system calls have always - /// gotten. - pub const SYSTEM_CALL_GAS_LIMIT_FLOOR: u64 = 30_000_000; -} - -/// Constants for the `REX6` spec. -pub mod rex6 {} - -/// Constants for the `REX7` spec. -pub mod rex7 {} - -/// Constants for the `REX` spec. -pub mod rex { - /// Additional storage gas cost added to transaction intrinsic gas for the `REX` spec. - /// This is charged on top of the base 21,000 intrinsic gas for all transactions. - pub const TX_INTRINSIC_STORAGE_GAS: u64 = 39_000; - - /// The base storage gas cost for setting a storage slot to a non-zero value for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `SSTORE_SET_STORAGE_GAS_BASE × - /// (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const SSTORE_SET_STORAGE_GAS_BASE: u64 = 20_000; - - /// The base storage gas cost for creating a new account for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: `NEW_ACCOUNT_STORAGE_GAS_BASE × - /// (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const NEW_ACCOUNT_STORAGE_GAS_BASE: u64 = 25_000; - - /// The base storage gas cost for creating a new contract for the `REX` spec. - /// Actual cost is dynamically scaled by SALT bucket capacity: - /// `CONTRACT_CREATION_STORAGE_GAS_BASE × (bucket_capacity / MIN_BUCKET_SIZE - 1)`. - pub const CONTRACT_CREATION_STORAGE_GAS_BASE: u64 = 32_000; - - /// The maximum compute gas limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit fail on the compute-gas limit path. - /// The exact surface result depends on the current spec's top-level/frame-local semantics. - pub const TX_COMPUTE_GAS_LIMIT: u64 = 200_000_000; - - /// The maximum data size limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `DataLimitExceeded`, preserving remaining gas. - pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; // Same with the block data limit - - /// The maximum key-value updates limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `KVUpdateLimitExceeded`, preserving remaining - /// gas. - pub const TX_KV_UPDATE_LIMIT: u64 = 500_000; // Same with the block kv update limit - - /// The maximum state growth limit for a single transaction for the `REX` spec. - /// Transactions exceeding this limit halt with `StateGrowthLimitExceeded`, preserving remaining - /// gas. - pub const TX_STATE_GROWTH_LIMIT: u64 = 1000; - - /// The maximum state growth limit for a block for the `REX` spec. - /// Blocks exceeding this limit halt with `StateGrowthLimitExceeded`, preserving remaining - /// gas. - pub const BLOCK_STATE_GROWTH_LIMIT: u64 = 1000; +//! Every value is *provisional*: a placeholder until the economics sign-off fixes the numbers. +//! A constant that no code reads yet is here so the whole placeholder set can be reviewed in +//! one place. +//! +//! | Constant | Value | Meaning | Read by | +//! |---|---:|---|---| +//! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas table (not yet) | +//! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | the Satin gas table (not yet) | +//! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | the Satin gas table (not yet) | +//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas (not yet) | +//! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | the spec configuration | +//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the data-size limit (not yet) | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the data-size limit (not yet) | +//! +//! The storage call stipend and the per-transaction and per-block state-gas limits are further +//! placeholders; history gas and the state-gas limits add them when they land. + +use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; + +/// Gas per byte of new state, the EIP-8037 `COST_PER_STATE_BYTE`. Provisional. +pub const COST_PER_STATE_BYTE: u64 = 1_530; + +/// State gas of one new storage slot: the EIP-8037 slot size times +/// [`COST_PER_STATE_BYTE`]. Provisional. +pub const SLOT_STATE_GAS: u64 = SSTORE_SET_BYTES * COST_PER_STATE_BYTE; + +/// State gas of one new account: the EIP-8037 account size times +/// [`COST_PER_STATE_BYTE`]. Provisional. +pub const ACCOUNT_STATE_GAS: u64 = NEW_ACCOUNT_BYTES * COST_PER_STATE_BYTE; + +/// Gas per history byte (logs, deployed code, write records, transaction body). Provisional. +pub const COST_PER_HISTORY_BYTE: u64 = 88; + +/// The execution cap: the most regular gas one transaction may spend. Gas above it goes to +/// the EIP-8037 state-gas reservoir. Provisional. +pub const TX_GAS_LIMIT_CAP: u64 = 200_000_000; + +/// The most data one transaction may produce, 12.5 MiB as in Rex6. Provisional. +pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; + +/// The most data one block may produce, 12.5 MiB as in Rex6. Provisional. +pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; + +#[cfg(test)] +mod tests { + use super::*; + + /// The placeholder values, written out so a change to one is a visible diff. + #[test] + fn test_provisional_values_match_the_work_order() { + assert_eq!(COST_PER_STATE_BYTE, 1_530); + assert_eq!(SLOT_STATE_GAS, 97_920); + assert_eq!(ACCOUNT_STATE_GAS, 183_600); + assert_eq!(COST_PER_HISTORY_BYTE, 88); + assert_eq!(TX_GAS_LIMIT_CAP, 200_000_000); + assert_eq!(TX_DATA_LIMIT, 13_107_200); + assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); + } } diff --git a/crates/mega-evm/src/evm/AGENTS.md b/crates/mega-evm/src/evm/AGENTS.md deleted file mode 100644 index 0245c104b..000000000 --- a/crates/mega-evm/src/evm/AGENTS.md +++ /dev/null @@ -1,30 +0,0 @@ -# AGENTS.md - -## OVERVIEW -MegaEVM execution core that wraps revm/op-revm with MegaETH instruction tables, host behavior, and execution interfaces. - -## STRUCTURE -- `mod.rs`: `MegaEvm` wrapper, inspector toggling, execution convenience APIs. -- `context.rs`: execution context composition and state wiring. -- `execution.rs`: transaction execution flow and result shaping. -- `factory.rs`: `MegaEvmFactory` builder for context and external env wiring. -- `instructions.rs`: spec-layered opcode table and extension wrappers. -- `host.rs`: host overrides for volatile tracking, oracle reads, SALT gas hooks. -- `limit.rs`: EVM-facing limit helpers and runtime-limit adaptation. -- `spec.rs`: `MegaSpecId` parsing/ordering utilities. - -## KEY PATTERNS -- Instruction semantics are layered wrappers, not ad-hoc per-opcode mutations. -- Preserve wrapper ordering when changing opcode stacks. -- Spec upgrades extend prior tables by overriding changed opcodes only. -- Host methods mark volatile accesses before delegating to inner host behavior. -- Oracle `sload` handling forces cold semantics for deterministic replay. -- `MegaEvm` methods read aggregate resource usage from `additional_limit` after execution. -- Keep inspector and non-inspector paths behaviorally aligned. - -## WHERE TO LOOK -- New spec opcode delta: `instructions.rs` (`mini_rex`, `rex`, `rex2`, `rex3`, `rex4`, `rex5`, `rex6`, `rex7` tables; `rex6` and `rex7` currently alias their predecessor, expressing their deltas as `is_enabled` dispatch inside the shared handlers). -- Volatile access detention trigger changes: `host.rs` and volatile wrappers in `instructions.rs`. -- Call forwarding and stipend interplay: `instructions.rs` + `../limit/storage_call_stipend.rs`. -- New external gas pricing path: `host.rs` gas helper methods. -- Execution result fields exposed to callers: `execution.rs` and `mod.rs::execute_transaction`. diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 886022cff..309fccdca 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,638 +1,169 @@ -//! # `MegaETH` EVM Context -//! -//! This module provides the core context implementation for the `MegaETH` EVM. -//! The [`Context`] struct wraps the underlying `OpStack` context and provides -//! additional MegaETH-specific functionality including gas cost oracles, -//! additional limits, and block environment access tracking. -//! -//! ## Key Features -//! -//! - **Gas Cost Oracle**: Tracks and manages gas costs during transaction execution -//! - **Additional Limits**: Enforces data and KV update limits beyond standard EVM limits -//! - **Block Environment Access Tracking**: Monitors which block environment data is accessed -//! - **Spec Management**: Handles different `MegaETH` specification versions - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{rc::Rc, vec::Vec}; - -use alloy_evm::Database; -use alloy_primitives::Address; -use core::cell::RefCell; +//! The execution context of the Satin engine. + use delegate::delegate; -use op_revm::{DefaultOp, L1BlockInfo, OpContext, OpSpecId}; +use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ - context::{BlockEnv, CfgEnv, ContextSetters, ContextTr, LocalContext}, - context_interface::context::ContextError, - database::EmptyDB, - Journal, + context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, + context_interface::cfg::GasParams, + Database, Journal, }; use crate::{ - constants, is_system_originated, AdditionalLimit, BucketId, DynamicGasCost, EmptyExternalEnv, - EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, TxRuntimeLimit, - VolatileDataAccess, VolatileDataAccessTracker, VolatileDataAccessType, + constants, AdditionalLimit, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvTypes, + ExternalEnvs, MegaSpecId, MegaTransaction, }; -/// `MegaETH` EVM context type. This struct wraps [`OpContext`] and implements the [`ContextTr`] -/// trait to be used as the context for the [`crate::Evm`]. -#[derive(Debug, derive_more::Deref, derive_more::DerefMut)] -pub struct MegaContext { - /// The inner context. - #[deref] - #[deref_mut] - pub(crate) inner: OpContext, - /// The `MegaETH` spec id. The inner context contains the `OpSpecId`. - /// The `OpSpec` in the `inner` context should be the corresponding [`OpSpecId`] for the - /// [`SpecId`]. - pub(crate) spec: MegaSpecId, - - /// Whether to disable the post-transaction reward to beneficiary. - pub(crate) disable_beneficiary: bool, - - /// Additional limits for the EVM. - pub additional_limit: Rc>, - - /// Shared SALT environment handle. - pub(crate) salt_env: Rc, - - /// Calculator for dynamic gas costs during transaction execution. - pub dynamic_storage_gas_cost: Rc>>>, - - /// The oracle environment. - pub oracle_env: Rc>, +/// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` +/// transaction type. +pub(crate) type MegaInnerContext = + Context, DB, Journal, L1BlockInfo>; - /* Internal state variables */ - /// Tracker for volatile data access (block environment, beneficiary, oracle) - /// and volatile data access disable (`MegaAccessControl` system contract). - pub volatile_data_tracker: Rc>, - - /// Set to `true` when this context is itself a sandbox execution. - /// - /// Suppresses sandbox interception (preventing recursive sandboxing) and signals other - /// Mega hooks to defer to outer-frame accounting (e.g., the Rex5+ deposit-caller - /// materialization charge in `validate`, which is paid by the outer keyless-deploy call - /// before the sandbox runs). - pub(crate) inside_sandbox: Rc>, - - /// The system address for the current block. - /// Pre-REX5: always `MEGA_SYSTEM_ADDRESS` (the legacy hardcoded constant). - /// REX5+: resolved from `SequencerRegistry` storage in `apply_pre_execution_changes`. - pub(crate) system_address: Address, -} - -impl Default for MegaContext { - fn default() -> Self { - Self::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE) - } +/// Execution context of the Satin engine. +/// +/// It wraps op-revm's context and adds what `MegaETH` execution needs on top: the `MegaETH` +/// spec and the external environments (SALT, oracle). The configuration is kept twice: the +/// [`MegaSpecId`] view that callers see and the [`OpSpecId`] view op-revm executes on. Both are +/// written together, only through [`MegaContext::with_cfg`], so they cannot drift apart. +/// +/// Every context accessor delegates to the wrapped context, and so does every +/// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing +/// opcode did (see the `host` module). It also carries the common execution layer's state for the +/// running transaction ([`AdditionalLimit`]). +#[derive(Debug)] +pub struct MegaContext { + pub(crate) inner: MegaInnerContext, + cfg: CfgEnv, + external_envs: ExternalEnvs, + pub(crate) additional_limit: AdditionalLimit, } -/* Constructors */ impl MegaContext { - /// Creates a new `MegaContext` with [`EmptyExternalEnv`]. - /// - /// This constructor initializes a new `MegaETH` EVM context with default settings. - /// For the `MINI_REX` specification, it automatically configures appropriate - /// contract size and initcode size limits. - /// - /// # Arguments - /// - /// * `db` - The database implementation to use for state storage - /// * `spec` - The `MegaETH` specification version to use - /// - /// # Returns - /// - /// Returns a new `MegaContext` instance with default configuration. + /// Creates a context over `db` that executes `spec`, without external environments. pub fn new(db: DB, spec: MegaSpecId) -> Self { - // `OpContext::default()` starts with block number 0, so the parent block number is also 0. - let salt_env = Rc::new(EmptyExternalEnv); - Self::new_with_shared_ext_envs(db, spec, salt_env, Rc::new(RefCell::new(EmptyExternalEnv))) - } -} - -#[cfg(any(test, feature = "test-utils"))] -impl MegaContext { - /// Test/bench-only public wrapper over [`new_with_shared_ext_envs`] so a - /// bench can build a context over a configurable external environment - /// (e.g. `TestExternalEnvs` with crowded buckets or oracle storage). - pub fn new_with_ext_envs( - db: DB, - spec: MegaSpecId, - salt_env: Rc, - oracle_env: Rc>, - ) -> Self { - Self::new_with_shared_ext_envs(db, spec, salt_env, oracle_env) + Self::new_with_external_envs(db, spec, ExternalEnvs::default()) } } impl MegaContext { - /// Creates a new `MegaContext` with shared external environment references. - /// - /// Unlike [`MegaContext::new`] which uses [`EmptyExternalEnv`], this constructor accepts - /// existing `Rc` references to share a parent context's salt env and oracle env. - /// This ensures the sandbox uses the same dynamic gas pricing as the parent. - /// - /// # Arguments - /// - /// * `db` - The database implementation to use for state storage - /// * `spec` - The `MegaETH` specification version to use - /// * `salt_env` - Shared salt environment from the parent context - /// * `oracle_env` - Shared oracle environment from the parent context - /// - /// # Returns - /// - /// Returns a new `MegaContext` instance sharing the parent's external environments while - /// keeping a fresh dynamic gas cost cache local to the new context. - pub(crate) fn new_with_shared_ext_envs( + /// Creates a context over `db` that executes `spec` with the given external environments. + pub fn new_with_external_envs( db: DB, spec: MegaSpecId, - salt_env: Rc, - oracle_env: Rc>, - ) -> Self { - let mut inner = - revm::Context::op().with_db(db).with_cfg(CfgEnv::new_with_spec(spec.into_op_spec())); - - if spec.is_enabled(MegaSpecId::MINI_REX) { - inner.cfg.limit_contract_code_size = Some(constants::mini_rex::MAX_CONTRACT_SIZE); - inner.cfg.limit_contract_initcode_size = Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - - let tx_limits = EvmTxRuntimeLimits::from_spec(spec); - Self { - spec, - disable_beneficiary: false, - additional_limit: Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))), - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - inner.block.number.to::().saturating_sub(1), - ))), - oracle_env, - volatile_data_tracker: Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))), - inside_sandbox: Rc::new(RefCell::new(false)), - system_address: crate::MEGA_SYSTEM_ADDRESS, - inner, - } - } -} - -impl MegaContext { - /// Creates a new `Context` from an existing `OpContext`. - /// - /// This constructor is useful when you already have a configured `OpContext` - /// and want to wrap it with MegaETH-specific functionality. The specification - /// in the provided context must match the `spec` parameter. - /// - /// # Arguments - /// - /// * `context` - The existing `OpStack` context to wrap - /// * `spec` - The `MegaETH` specification version (must match context spec) - /// * `external_envs` - The external environments for gas cost calculations - /// - /// # Returns - /// - /// Returns a new `Context` instance wrapping the provided context. - #[deprecated(note = "Use `MegaContext::new` instead")] - pub fn new_with_context( - context: OpContext, - spec: MegaSpecId, - external_envs: ExternalEnvs, + external_envs: ExternalEnvs, ) -> Self { - let mut inner = context; - - // spec in context must keep the same with parameter `spec` - inner.cfg.spec = spec.into_op_spec(); - - // For the `MINI_REX` spec, we override the contract size and initcode size limits if they - // not set in the given `OpContext`. - if spec.is_enabled(MegaSpecId::MINI_REX) { - if inner.cfg.limit_contract_code_size.is_none() { - inner.cfg.limit_contract_code_size = Some(constants::mini_rex::MAX_CONTRACT_SIZE); - } - if inner.cfg.limit_contract_initcode_size.is_none() { - inner.cfg.limit_contract_initcode_size = - Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - } - - let tx_limits = EvmTxRuntimeLimits::from_spec(spec); - let salt_env = Rc::new(external_envs.salt_env); - Self { - spec, - disable_beneficiary: false, - additional_limit: Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))), - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - inner.block.number.to::().saturating_sub(1), - ))), - oracle_env: Rc::new(RefCell::new(external_envs.oracle_env)), - volatile_data_tracker: Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))), - inside_sandbox: Rc::new(RefCell::new(false)), - system_address: crate::MEGA_SYSTEM_ADDRESS, - inner, - } - } - - /// Sets the [`Database`] used by the EVM. - /// - /// This method allows changing the underlying database implementation - /// while preserving all other context configuration. - /// - /// # Arguments - /// - /// * `db` - The new database implementation - /// - /// # Returns - /// - /// Returns a new `Context` with the updated database type. - pub fn with_db(self, db: ODB) -> MegaContext { - MegaContext { - inner: self.inner.with_db(db), - spec: self.spec, - disable_beneficiary: self.disable_beneficiary, - additional_limit: self.additional_limit, - salt_env: self.salt_env, - dynamic_storage_gas_cost: self.dynamic_storage_gas_cost, - oracle_env: self.oracle_env, - volatile_data_tracker: self.volatile_data_tracker, - inside_sandbox: self.inside_sandbox, - system_address: self.system_address, - } + let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); + let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); + Self { inner, cfg, external_envs, additional_limit: AdditionalLimit::default() } } - /// Sets the [`Transaction`] to be executed by the EVM. - /// - /// This method configures the transaction to be executed and automatically - /// resets internal state for the new transaction. - /// - /// # Arguments + /// Replaces the configuration. /// - /// * `tx` - The transaction to execute - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_tx(mut self, tx: crate::MegaTransaction) -> Self { - self.inner = self.inner.with_tx(tx); + /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas table, the + /// EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and the system-call + /// state-gas margin. Every other field (chain id, limits, disabled checks) is taken from + /// `cfg`. + pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { + let cfg = spec_cfg(cfg); + self.inner = self.inner.with_cfg(op_cfg(&cfg)); + self.cfg = cfg; self } - /// Sets the [`BlockEnv`] for the EVM. - /// - /// This method configures the block environment and automatically - /// resets internal state for the new block. - /// - /// # Arguments - /// - /// * `block` - The block environment configuration - /// - /// # Returns - /// - /// Returns `self` for method chaining. + /// Replaces the block environment. pub fn with_block(mut self, block: BlockEnv) -> Self { - self.inner = self.inner.with_block(block); - // Reset internal state for new block - self.on_new_block(); + self.inner.block = block; self } - /// Sets the [`CfgEnv`] for the EVM. - /// - /// This method configures the EVM environment settings. For the `MINI_REX` - /// specification, it automatically applies appropriate contract size limits - /// if they are not already set in the configuration. - /// - /// # Arguments - /// - /// * `cfg` - The configuration environment - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { - self.spec = cfg.spec; - self.inner = self.inner.with_cfg(cfg.into_op_cfg()); - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - if self.inner.cfg.limit_contract_code_size.is_none() { - self.inner.cfg.limit_contract_code_size = - Some(constants::mini_rex::MAX_CONTRACT_SIZE); - } - if self.inner.cfg.limit_contract_initcode_size.is_none() { - self.inner.cfg.limit_contract_initcode_size = - Some(constants::mini_rex::MAX_INITCODE_SIZE); - } - } + /// Replaces the transaction. + pub fn with_tx(mut self, tx: MegaTransaction) -> Self { + self.inner.tx = tx; self } - /// Sets the external environments for the EVM. - /// - /// This method updates the external environments used for gas cost calculations, - /// including the salt environment and oracle environment. When setting new - /// external environments, the dynamic gas cost calculator and oracle environment - /// are reinitialized with the new configurations. - /// - /// # Arguments - /// - /// * `external_envs` - The new external environments configuration - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_external_envs( - self, - external_envs: ExternalEnvs, - ) -> MegaContext { - let parent_block_number = self.inner.block.number.to::().saturating_sub(1); - let spec = self.spec; - let salt_env = Rc::new(external_envs.salt_env); - MegaContext { - inner: self.inner, - spec, - disable_beneficiary: self.disable_beneficiary, - additional_limit: self.additional_limit, - salt_env: Rc::clone(&salt_env), - dynamic_storage_gas_cost: Rc::new(RefCell::new(DynamicGasCost::new( - spec, - salt_env, - parent_block_number, - ))), - oracle_env: Rc::new(RefCell::new(external_envs.oracle_env)), - volatile_data_tracker: self.volatile_data_tracker, - inside_sandbox: self.inside_sandbox, - system_address: self.system_address, - } - } - - /// Sets the Op Stack's [`L1BlockInfo`] for the EVM. - /// - /// This method configures the L1 block information used by the `OpStack` - /// for cross-layer communication and state management. - /// - /// # Arguments - /// - /// * `chain` - The L1 block information - /// - /// # Returns - /// - /// Returns `self` for method chaining. + /// Replaces the L1 block info. pub fn with_chain(mut self, chain: L1BlockInfo) -> Self { - self.inner = self.inner.with_chain(chain); - self - } - - /// Sets the transaction limits for the EVM. - pub fn with_tx_runtime_limits(mut self, tx_limits: EvmTxRuntimeLimits) -> Self { - self.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(self.spec, tx_limits))); - self.volatile_data_tracker = Rc::new(RefCell::new(VolatileDataAccessTracker::new( - tx_limits.block_env_access_compute_gas_limit, - tx_limits.oracle_access_compute_gas_limit, - ))); + self.inner.chain = chain; self } -} - -/* Getters */ -impl MegaContext { - /// Gets the `MegaETH` specification ID. - /// - /// Returns the specification version currently configured for this context. - /// - /// # Returns - /// - /// Returns the [`SpecId`] representing the current `MegaETH` specification. - pub fn mega_spec(&self) -> MegaSpecId { - self.spec - } - /// Gets the system address for the current block. - /// - /// Pre-REX5: always `MEGA_SYSTEM_ADDRESS`. - /// REX5+: resolved from `SequencerRegistry` storage in `apply_pre_execution_changes`. - pub fn system_address(&self) -> Address { - self.system_address + /// Modifies the L1 block info in place. + pub fn modify_chain(&mut self, f: impl FnOnce(&mut L1BlockInfo)) { + f(&mut self.inner.chain); } - /// Sets the system address for the current block. - pub(crate) fn set_system_address(&mut self, address: Address) { - self.system_address = address; + /// The spec this context executes. + pub const fn spec(&self) -> MegaSpecId { + self.cfg.spec } - /// Returns whether this context is itself a sandbox execution. + /// The configuration as callers see it, keyed by [`MegaSpecId`]. /// - /// When `true`, sandbox interception (e.g., keyless deploy) is suppressed to prevent - /// recursive sandboxing, and Mega hooks defer to outer-frame accounting (e.g., the - /// Rex5+ deposit-caller materialization charge in `validate`). - #[inline] - pub fn is_inside_sandbox(&self) -> bool { - *self.inside_sandbox.borrow() + /// [`ContextTr::cfg`] returns the [`OpSpecId`] view op-revm executes on. + pub const fn mega_cfg(&self) -> &CfgEnv { + &self.cfg } - /// Sets whether this context is itself a sandbox execution. - #[inline] - pub(crate) fn set_inside_sandbox(&self, value: bool) { - *self.inside_sandbox.borrow_mut() = value; + /// The external environments (SALT, oracle) of this context. + pub const fn external_envs(&self) -> &ExternalEnvs { + &self.external_envs } - /// Builder method to mark this context as itself a sandbox execution. - /// - /// Used when constructing a sandbox's own context to prevent recursive interception. - #[inline] - pub fn with_inside_sandbox(self, value: bool) -> Self { - self.set_inside_sandbox(value); + /// Enforces `limits` on every transaction from now on. + pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.additional_limit.set_limits(limits); self } - /// Gets the current total data size generated from transaction execution. - /// - /// # Returns - /// - /// Returns the current total data size in bytes generated so far. The data size is reset at the - /// beginning of each transaction. - pub fn generated_data_size(&self) -> u64 { - self.additional_limit.borrow().data_size.tx_usage() - } - - /// Gets the current total number of key-value updates performed during transaction execution. - /// - /// # Returns - /// - /// Returns the current total number of KV operations performed so far. The count is reset at - /// the beginning of each transaction. - pub fn kv_update_count(&self) -> u64 { - self.additional_limit.borrow().kv_update.tx_usage() - } - - /// Gets the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn accessed_bucket_ids(&self) -> Vec { - self.dynamic_storage_gas_cost.borrow().get_bucket_ids() - } - - /// Consumes the context and converts it into the inner `OpContext`. - /// - /// This method extracts the underlying `OpStack` context, discarding - /// all MegaETH-specific state and configuration. - /// - /// # Returns - /// - /// Returns the inner `OpContext`. - pub fn into_inner(self) -> OpContext { - self.inner + /// The common execution layer's state for the running (or last) transaction. + pub const fn additional_limit(&self) -> &AdditionalLimit { + &self.additional_limit } -} -/* Block Environment Access Tracking */ -impl MegaContext { - /// Returns the bitmap of block environment data accessed during transaction execution. - /// - /// This method provides information about which block environment fields - /// have been accessed during the current transaction, which is useful for - /// optimization and analysis purposes. - /// - /// # Returns - /// - /// Returns a [`VolatileDataAccess`] bitmap indicating accessed fields. - pub fn get_block_env_accesses(&self) -> VolatileDataAccess { - self.volatile_data_tracker.borrow().get_block_env_accesses() + /// The common execution layer's state, mutably. For tests and tools that drive the abort + /// protocol directly. + #[cfg(any(test, feature = "test-utils"))] + pub const fn additional_limit_mut(&mut self) -> &mut AdditionalLimit { + &mut self.additional_limit } - /// Resets the volatile data access tracker for new transactions. - /// - /// This method clears the volatile data access tracker, preparing the context for a new - /// transaction. - pub fn reset_volatile_data_access(&mut self) { - self.volatile_data_tracker.borrow_mut().reset(); + /// Prepares the common execution layer for a new transaction or system call. Every entry + /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. + pub(crate) fn on_new_tx(&mut self) { + self.additional_limit.reset(); } - /// Marks that a specific type of block environment has been accessed. - /// - /// This internal method is used to track which block environment fields - /// are being accessed during transaction execution. - /// - /// # Arguments - /// - /// * `access_type` - The type of block environment access to record - pub(crate) fn mark_block_env_accessed(&self, access_type: VolatileDataAccessType) { - self.volatile_data_tracker.borrow_mut().mark_block_env_accessed(access_type); + /// Consumes the context and returns the database, the configuration and the block. + pub fn into_parts(self) -> (DB, CfgEnv, BlockEnv) { + let Context { block, journaled_state, .. } = self.inner; + (journaled_state.database, self.cfg, block) } } -/* Beneficiary Access Tracking */ -impl MegaContext { - /// Disables the beneficiary reward. - pub fn disable_beneficiary(&mut self) { - self.disable_beneficiary = true; - } - - /// Check if address is beneficiary and mark access if so. - /// Returns true if beneficiary was accessed. - pub(crate) fn check_and_mark_beneficiary_balance_access(&self, address: &Address) -> bool { - if self.inner.block.beneficiary == *address { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - true - } else { - false - } - } - - /// Check if the transaction caller or recipient is the beneficiary - pub(crate) fn check_tx_beneficiary_access(&self) { - let tx = &self.inner.tx; - let beneficiary = self.inner.block.beneficiary; - - // Check if caller is beneficiary - if tx.base.caller == beneficiary { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - } - - // Check if recipient is beneficiary (for calls) - if let revm::primitives::TxKind::Call(recipient) = tx.base.kind { - if recipient == beneficiary { - self.volatile_data_tracker.borrow_mut().mark_beneficiary_balance_accessed(); - } - } - } +/// Sets the configuration fields the spec fixes. +/// +/// Satin runs on the Osaka gas table of its Karst base, with EIP-8037 state gas and the EIP-2780 +/// intrinsic cost switched on and gas above the execution cap going to the state-gas reservoir. +/// The EIP-7708 transfer logs and the system-call reservoir margin stay off until the Satin gas +/// table and the system-call reservoir split switch them on. +fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { + cfg.gas_params = GasParams::new_spec(cfg.spec.into_eth_spec()); + cfg.enable_amsterdam_eip8037 = true; + cfg.enable_amsterdam_eip2780 = true; + cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); + cfg.enable_amsterdam_eip7708 = false; + cfg.system_call_state_gas_margin_in_reservoir = false; + cfg } -/* Hooks */ -impl MegaContext { - /// Resets the internal state for a new block. - /// - /// This method is called when transitioning to a new block and updates - /// the dynamic gas cost calculator and additional limits accordingly. - pub(crate) fn on_new_block(&self) { - // The dynamic gas cost calculator is only enabled when the `MINI_REX` spec is enabled. - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - self.dynamic_storage_gas_cost.borrow_mut().on_new_block(&self.inner.block); - } - } - - /// Resets the internal state for a new transaction. - /// - /// This method is called when starting a new transaction and resets - /// block environment access tracking and additional limits. - /// - /// If transaction-only intrinsic resource usage exceeds a configured limit, - /// `before_tx_start()` sets `has_exceeded_limit` so that the subsequent - /// `frame_result_if_exceeding_limit()` or `before_frame_init()` call produces a normal - /// execution failure on the standard additional-limit path. - /// - /// DB-dependent pre-frame usage may still be recorded later during pre-execution. - pub(crate) fn on_new_tx(&mut self) { - self.reset_volatile_data_access(); - - // The additional-limit lifecycle (reset → intrinsic accounting) exists only for MINI_REX+. - if self.spec.is_enabled(MegaSpecId::MINI_REX) { - self.additional_limit.borrow_mut().reset(); - self.additional_limit.borrow_mut().before_tx_start(&self.inner.tx); - } - - // REX6+: exempt system-originated transactions (see `crate::is_system_originated`) from - // MegaETH per-tx resource metering. - if self.spec.is_enabled(MegaSpecId::REX6) && - is_system_originated(&self.inner.tx, self.system_address) - { - self.additional_limit.borrow_mut().mark_exempt(); - } - - // Mark beneficiary access AFTER additional_limit.reset() so that the volatile - // tracker marking from check_tx_beneficiary_access can be synchronized into - // additional_limit below, rather than being cleared by the reset. - // - // Gated to REX4: pre-REX4 specs never had eager beneficiary detention at TX start. - // Changing pre-REX4 behavior would alter historical replay results. - self.check_tx_beneficiary_access(); - if self.spec.is_enabled(MegaSpecId::REX4) { - let compute_gas_limit = self.volatile_data_tracker.borrow().get_compute_gas_limit(); - if let Some(limit) = compute_gas_limit { - self.additional_limit.borrow_mut().set_compute_gas_limit(limit); - } - } - } +/// The op-revm view of `cfg`: the same fields, keyed by the Optimism spec. +fn op_cfg(cfg: &CfgEnv) -> CfgEnv { + cfg.clone().with_spec_and_gas_params(cfg.spec.into_op_spec(), cfg.gas_params.clone()) } -/// Implementation of the `ContextTr` trait for `Context`. -/// -/// This implementation delegates most methods to the inner `OpContext` while -/// maintaining the MegaETH-specific functionality. The trait provides access -/// to the core EVM context components like transaction, block, configuration, -/// database, journal, and chain information. impl ContextTr for MegaContext { type Block = BlockEnv; - type Tx = crate::MegaTransaction; + type Tx = MegaTransaction; type Cfg = CfgEnv; type Db = DB; type Journal = Journal; @@ -641,242 +172,151 @@ impl ContextTr for MegaContext &Self::Tx; - fn block(&self) -> &Self::Block; - fn cfg(&self) -> &Self::Cfg; - fn journal(&self) -> &Self::Journal; - fn journal_mut(&mut self) -> &mut Self::Journal; - fn journal_ref(&self) -> &Self::Journal; - fn db(&self) -> &Self::Db; - fn db_mut(&mut self) -> &mut Self::Db; - fn chain(&self) -> &Self::Chain; - fn chain_mut(&mut self) -> &mut Self::Chain; - fn local(&self) -> &Self::Local; - fn local_mut(&mut self) -> &mut Self::Local; - fn error(&mut self) -> &mut Result<(), ContextError<::Error>>; - fn tx_journal_mut(&mut self) -> (&Self::Tx, &mut Self::Journal); - fn tx_local_mut(&mut self) -> (&Self::Tx, &mut Self::Local); + fn all( + &self, + ) -> ( + &BlockEnv, + &MegaTransaction, + &CfgEnv, + &DB, + &Journal, + &L1BlockInfo, + &LocalContext, + ); + fn all_mut( + &mut self, + ) -> ( + &BlockEnv, + &MegaTransaction, + &CfgEnv, + &mut Journal, + &mut L1BlockInfo, + &mut LocalContext, + ); + fn error(&mut self) -> &mut Result<(), ContextError>; } } } -/// Implementation of the `ContextSetters` trait for `Context`. -/// -/// This implementation provides methods to update the context state, with -/// special handling for transaction updates to reset internal state. impl ContextSetters for MegaContext { delegate! { to self.inner { - fn set_block(&mut self, block: Self::Block); - fn set_tx(&mut self, tx: Self::Tx); + fn set_tx(&mut self, tx: MegaTransaction); + fn set_block(&mut self, block: BlockEnv); } } } -/// A convenient trait to convert a `CfgEnv` into a `CfgEnv`. -/// -/// This trait provides a conversion method for `OpStack` configuration environments -/// to `MegaETH` configuration environments, preserving all configuration fields -/// while changing the specification type. -pub trait IntoMegaethCfgEnv { - /// Converts to `CfgEnv`. - fn into_megaeth_cfg(self, spec: MegaSpecId) -> CfgEnv; -} - -/// A convenient trait to convert a `CfgEnv` into a `CfgEnv`. -/// -/// This trait provides a conversion method for `MegaETH` configuration environments -/// to `OpStack` configuration environments, preserving all configuration fields -/// while changing the specification type. -pub trait IntoOpCfgEnv { - /// Converts to `CfgEnv`. - fn into_op_cfg(self) -> CfgEnv; -} - -/// Implementation of `IntoOpCfgEnv` for `CfgEnv`. -/// -/// This implementation converts a `MegaETH` configuration environment to an -/// `OpStack` configuration environment by copying all relevant fields. -impl IntoOpCfgEnv for CfgEnv { - /// Converts to `CfgEnv`. - /// - /// This method creates a new `OpStack` configuration environment with the - /// same settings as the `MegaETH` configuration, converting the specification ID. - /// - /// # Returns - /// - /// Returns a new `CfgEnv` with all fields copied from `self`. - /// - /// # Note - /// - /// When the fields of [`CfgEnv`] change, this function needs to be updated - /// to include the new fields. - fn into_op_cfg(self) -> CfgEnv { - let mut op_cfg = CfgEnv::new_with_spec(OpSpecId::from(self.spec)); - op_cfg.chain_id = self.chain_id; - op_cfg.tx_chain_id_check = self.tx_chain_id_check; - op_cfg.limit_contract_code_size = self.limit_contract_code_size; - op_cfg.limit_contract_initcode_size = self.limit_contract_initcode_size; - op_cfg.disable_nonce_check = self.disable_nonce_check; - op_cfg.max_blobs_per_tx = self.max_blobs_per_tx; - op_cfg.blob_base_fee_update_fraction = self.blob_base_fee_update_fraction; - op_cfg.tx_gas_limit_cap = self.tx_gas_limit_cap; - op_cfg.memory_limit = self.memory_limit; - op_cfg.disable_balance_check = self.disable_balance_check; - op_cfg.disable_block_gas_limit = self.disable_block_gas_limit; - op_cfg.disable_eip3541 = self.disable_eip3541; - op_cfg.disable_eip3607 = self.disable_eip3607; - op_cfg.disable_base_fee = self.disable_base_fee; - op_cfg - } -} - -/// Implementation of `IntoMegaethCfgEnv` for `CfgEnv`. -/// -/// This implementation converts an `OpStack` configuration environment to a -/// `MegaETH` configuration environment by copying all relevant fields. -impl IntoMegaethCfgEnv for CfgEnv { - /// Converts to `CfgEnv`. - /// - /// This method creates a new `MegaETH` configuration environment with the - /// same settings as the `OpStack` configuration, using the provided specification ID. - /// - /// # Arguments - /// - /// * `spec` - The `MegaETH` specification ID to use in the new configuration - /// - /// # Returns - /// - /// Returns a new `CfgEnv` with all fields copied from `self`. - /// - /// # Note - /// - /// When the fields of [`CfgEnv`] change, this function needs to be updated - /// to include the new fields. - fn into_megaeth_cfg(self, spec: MegaSpecId) -> CfgEnv { - let mut cfg = CfgEnv::new_with_spec(spec); - cfg.chain_id = self.chain_id; - cfg.tx_chain_id_check = self.tx_chain_id_check; - cfg.limit_contract_code_size = self.limit_contract_code_size; - cfg.limit_contract_initcode_size = self.limit_contract_initcode_size; - cfg.disable_nonce_check = self.disable_nonce_check; - cfg.max_blobs_per_tx = self.max_blobs_per_tx; - cfg.blob_base_fee_update_fraction = self.blob_base_fee_update_fraction; - cfg.tx_gas_limit_cap = self.tx_gas_limit_cap; - cfg.memory_limit = self.memory_limit; - cfg.disable_balance_check = self.disable_balance_check; - cfg.disable_block_gas_limit = self.disable_block_gas_limit; - cfg.disable_eip3541 = self.disable_eip3541; - cfg.disable_eip3607 = self.disable_eip3607; - cfg.disable_base_fee = self.disable_base_fee; - cfg - } -} - #[cfg(test)] mod tests { use super::*; - - use alloy_primitives::address; - use revm::{context::CfgEnv, database::EmptyDB}; - - use crate::TestExternalEnvs; + use crate::{EthSpecId, SaltEnv, TestExternalEnvs}; + use alloy_primitives::U256; + use core::convert::Infallible; + use revm::database::EmptyDB; + + /// Asserts both configuration views carry the Satin switches. + fn assert_satin_switches(ctx: &MegaContext) { + let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); + assert_eq!(mega.spec, MegaSpecId::SATIN); + assert_eq!(op.spec, OpSpecId::KARST); + for (eip8037, eip2780, cap, eip7708, margin) in [ + ( + mega.enable_amsterdam_eip8037, + mega.enable_amsterdam_eip2780, + mega.tx_gas_limit_cap, + mega.enable_amsterdam_eip7708, + mega.system_call_state_gas_margin_in_reservoir, + ), + ( + op.enable_amsterdam_eip8037, + op.enable_amsterdam_eip2780, + op.tx_gas_limit_cap, + op.enable_amsterdam_eip7708, + op.system_call_state_gas_margin_in_reservoir, + ), + ] { + assert!(eip8037, "EIP-8037 must be on"); + assert!(eip2780, "EIP-2780 must be on"); + assert_eq!(cap, Some(200_000_000), "execution cap"); + assert!(!eip7708, "EIP-7708 stays off until the Satin gas table"); + assert!( + !margin, + "the system-call reservoir margin stays off until the reservoir split" + ); + } + let osaka = GasParams::new_spec(EthSpecId::OSAKA); + assert_eq!(mega.gas_params.table(), osaka.table()); + assert_eq!(op.gas_params.table(), osaka.table()); + } #[test] - fn test_with_cfg_updates_spec() { - // Create context with initial spec - let mut context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Verify initial state - assert_eq!(context.mega_spec(), MegaSpecId::EQUIVALENCE); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::EQUIVALENCE)); + fn test_new_context_carries_the_satin_switches() { + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert_satin_switches(&ctx); + } - // Create new config with different spec - let new_cfg = CfgEnv::new_with_spec(MegaSpecId::MINI_REX); + /// A caller's configuration cannot switch off what the spec fixes; every other field is + /// taken from it. + #[test] + fn test_with_cfg_keeps_the_spec_switches() { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = 4326; + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.tx_gas_limit_cap = Some(1 << 24); + cfg.enable_amsterdam_eip7708 = true; + cfg.system_call_state_gas_margin_in_reservoir = true; + cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); - // Apply new config using with_cfg - context = context.with_cfg(new_cfg); + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); - // Verify that both the context's spec and inner config's spec are updated - assert_eq!(context.mega_spec(), MegaSpecId::MINI_REX); - assert_eq!(context.inner.cfg.spec, OpSpecId::from(MegaSpecId::MINI_REX)); + assert_satin_switches(&ctx); + assert_eq!(ctx.mega_cfg().chain_id, 4326); + assert_eq!(ctx.cfg().chain_id, 4326); } + /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. #[test] fn test_with_cfg_spec_consistency() { - let context = MegaContext::new(EmptyDB::default(), MegaSpecId::EQUIVALENCE); - - // Test multiple spec transitions - let specs_to_test = [MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]; + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = 6343; + cfg.limit_contract_code_size = Some(512 * 1024); + cfg.disable_nonce_check = true; - let mut current_context = context; - for spec in specs_to_test { - let cfg = CfgEnv::new_with_spec(spec); - current_context = current_context.with_cfg(cfg); + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_cfg(cfg); + let (mega, op) = (ctx.mega_cfg(), ctx.cfg()); - // Verify consistency between context spec and inner config spec - assert_eq!(current_context.mega_spec(), spec); - assert_eq!(current_context.inner.cfg.spec, OpSpecId::from(spec)); - } + assert_eq!(op.spec, mega.spec.into_op_spec()); + assert_eq!(op.chain_id, 6343); + assert_eq!(op.limit_contract_code_size, Some(512 * 1024)); + assert!(op.disable_nonce_check); + assert_eq!( + mega.clone().with_spec_and_gas_params(op.spec, mega.gas_params.clone()), + op.clone() + ); } - /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. #[test] - fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { - let external_envs = TestExternalEnvs::new(); - let parent = MegaContext::new(EmptyDB::default(), MegaSpecId::REX4) - .with_external_envs(external_envs.into()); - let parent_address = address!("0000000000000000000000000000000000100001"); - let sandbox_address = address!("0000000000000000000000000000000000100002"); - - parent - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(parent_address) - .expect("parent bucket lookup should succeed"); - let parent_bucket_ids = parent.accessed_bucket_ids(); - - let sandbox = - MegaContext::<_, TestExternalEnvs>::new_with_shared_ext_envs( - EmptyDB::default(), - MegaSpecId::REX4, - Rc::clone(&parent.salt_env), - Rc::clone(&parent.oracle_env), - ) - .with_block(parent.block().clone()) - .with_chain(parent.chain().clone()) - .with_inside_sandbox(true); - sandbox - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(sandbox_address) - .expect("sandbox bucket lookup should succeed"); - - assert_eq!(parent.accessed_bucket_ids(), parent_bucket_ids); - assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); + fn test_modify_chain_edits_the_l1_block_info() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + ctx.modify_chain(|chain| chain.l2_block = Some(U256::from(42))); + assert_eq!(ctx.chain().l2_block, Some(U256::from(42))); } - /// The test/bench-only `new_with_ext_envs` wrapper builds a `MegaContext` - /// over a caller-supplied external environment (`TestExternalEnvs`), at the - /// requested spec and wired to the given SALT/oracle handles. + /// The external environments given at construction are the ones the context exposes. #[test] fn test_new_with_ext_envs_builds_over_configurable_env() { - let env = TestExternalEnvs::::new(); - let context = - MegaContext::<_, TestExternalEnvs>::new_with_ext_envs( - EmptyDB::default(), - MegaSpecId::REX5, - Rc::new(env.clone()), - Rc::new(RefCell::new(env)), - ); - - assert_eq!(context.mega_spec(), MegaSpecId::REX5); - // The supplied SALT env is wired through: a bucket lookup against the - // dynamic-gas cache succeeds. - context - .dynamic_storage_gas_cost - .borrow_mut() - .new_account_gas(address!("0000000000000000000000000000000000100003")) - .expect("bucket lookup against the supplied env should succeed"); + let env = TestExternalEnvs::::new().with_bucket_capacity(7, 1_024); + let ctx = MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs::from(env), + ); + + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert_eq!(ctx.external_envs().salt_env.get_bucket_capacity(7).unwrap(), 1_024); + assert_satin_switches(&ctx); } } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index a34c6ea8a..7000aa11f 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1,59 +1,60 @@ +//! The Satin handler and the frame lifecycle of [`MegaEvm`]. +//! +//! [`MegaHandler`] runs a transaction through op-revm's [`OpHandler`] and overrides the phases +//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] and [`InspectorEvmTr`] itself, so the +//! frame lifecycle (`frame_init`, `frame_run`, `frame_return_result`) is `MegaETH`'s own. + #[cfg(not(feature = "std"))] use alloc as std; -use std::{collections::BTreeMap, string::ToString, vec::Vec}; - -use alloy_evm::{precompiles::PrecompilesMap, Database}; -use alloy_primitives::{Address, Bytes, TxKind, U256}; -use delegate::delegate; use op_revm::{ - constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, handler::{IsTxError, OpHandler}, - transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; +use std::vec::Vec; + +use op_revm::precompiles::OpPrecompiles; use revm::{ context::{ - result::{ExecutionResult, FromStringError, InvalidTransaction}, - transaction::{AuthorizationTr, TransactionType}, - Block, Cfg, ContextError, ContextTr, FrameStack, JournalTr, LocalContextTr, Transaction, + result::FromStringError, transaction::TransactionType, ContextError, ContextTr, FrameStack, + JournalTr, Transaction, + }, + context_interface::{ + cfg::gas::GasTracker, + journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, }, handler::{ - evm::{ContextDbError, FrameInitResult}, + evm::{ContextDbError, FrameInitResult, FrameTr}, instructions::InstructionProvider, - post_execution::output as post_execution_output, - pre_execution::validate_account_nonce_and_code, - EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, FrameTr, Handler, - ItemOrResult, + EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, + PreExecutionOutput, }, inspector::{ - handler::{frame_end, frame_start}, - inspect_instructions, InspectorEvmTr, InspectorFrame, InspectorHandler, + handler::{frame_start, inspect_instructions}, + InspectorEvmTr, InspectorHandler, JournalExt, }, interpreter::{ - gas::get_tokens_in_calldata, interpreter::EthInterpreter, interpreter_action::FrameInit, - CallOutcome, CallScheme, CreateOutcome, FrameInput, Gas, InitialAndFloorGas, - InstructionResult, InterpreterAction, InterpreterResult, + interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, + InitialAndFloorGas, InstructionResult, InterpreterAction, }, - primitives::CALL_STACK_LIMIT, - Inspector, Journal, + primitives::{Address, Bytes, CALL_STACK_LIMIT}, + Database, Inspector, Journal, }; use crate::{ - constants, dispatch_system_contract_interceptors, is_deposit_like_transaction, - is_mega_system_transaction_with, limit::ACCOUNT_INFO_WRITE_SIZE, sent_from_system_address, - ExternalEnvTypes, HostExt, JournalInspectTr, MegaContext, MegaEvm, MegaHaltReason, - MegaInstructions, MegaSpecId, MegaTransactionError, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, + evm::inspector::frame_end_checked, synthetic_frame_result, ExternalEnvTypes, LimitCheck, + MegaContext, MegaEvm, MegaInstructions, }; -/// Revm handler for `MegaETH`. It internally wraps the [`op_revm::handler::OpHandler`] and inherits -/// most functionalities from Optimism. -#[allow(missing_debug_implementations)] +/// The Satin handler. +/// +/// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. +#[derive(Debug)] pub struct MegaHandler { op: OpHandler, } impl MegaHandler { - /// Create a new `MegaethHandler`. + /// Creates a handler. pub fn new() -> Self { Self { op: OpHandler::new() } } @@ -65,1527 +66,533 @@ impl Default for MegaHandler { } } -impl MegaHandler -where - DB: Database, - ExtEnvs: ExternalEnvTypes, - EVM: EvmTr>, - ERROR: FromStringError + From, -{ - /// The hook to be called in `revm::handler::Handler::run_without_catch_error` and - /// `revm::handler::InspectorHandler::inspect_run_without_catch_error`. - /// - /// Promotes a legacy `system_address` transaction into the OP deposit-style path so it - /// bypasses signature, nonce, and fee validation. REX5+ restores nonce and chain-id - /// checks before the promotion (the deposit path otherwise drops them, leaving the - /// transaction replayable). Pre-REX5 specs preserve the original behavior so existing - /// chain replay is unaffected. - #[inline] - fn before_run(&self, evm: &mut EVM) -> Result<(), ERROR> { - let ctx = evm.ctx_mut(); - let spec = ctx.spec; - if spec.is_enabled(MegaSpecId::MINI_REX) { - let system_address = ctx.system_address; - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - // Honor the same `CfgEnv` toggles as the canonical revm validate path. - // Ordinary txs are already filtered by the upstream validate path before - // reaching this promotion logic, so keeping system txs aligned here does - // not introduce a separate replay-only escape hatch. - let cfg = ctx.cfg(); - let cfg_chain_id = cfg.chain_id; - let tx_chain_id_check = cfg.tx_chain_id_check; - let disable_nonce_check = cfg.disable_nonce_check; - let disable_eip3607 = cfg.disable_eip3607; - let tx = ctx.tx(); - - if sent_from_system_address(tx, system_address) { - // Whitelist rejection has no canonical `InvalidTransaction` variant; keep the - // existing string-error shape pre-REX5 callers already expect. - if !is_mega_system_transaction_with(tx, system_address) { - return Err(FromStringError::from_string( - "Mega system transaction callee is not in the whitelist".to_string(), - )); - } - - if is_rex5_enabled { - if tx_chain_id_check { - match tx.chain_id() { - None => return Err(InvalidTransaction::MissingChainId.into()), - Some(cid) if cid != cfg_chain_id => { - return Err(InvalidTransaction::InvalidChainId.into()); - } - Some(_) => {} - } - } - - // Inspect without warming so validation does not mutate the EIP-2929 - // access list. The journal cache still lets consecutive in-block system - // txs observe committed nonce bumps. - let tx_nonce = tx.nonce(); - // EIP-3607 reads `info.code`; pass `load_code = true` so the - // `code_by_hash` is paid here rather than silently bypassing the - // guard against a lazy-code DB. - let state_account = ctx - .journal_mut() - .inspect_account(system_address, true) - .map_err(|e| -> ERROR { - FromStringError::from_string(format!( - "Mega system transaction state read failed: {e:?}" - )) - })?; - validate_account_nonce_and_code( - &mut state_account.info, - tx_nonce, - disable_eip3607, - disable_nonce_check, - )?; - } - - // Mark the tx as deposit-style for `OpHandler` and force gas_price to 0 - // so fee / L1 / operator / beneficiary accounting all degenerate to no-ops. - let tx = &mut ctx.inner.tx; - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.base.gas_price = 0; - } - } - - ctx.on_new_tx(); - Ok(()) - } - - /// The hook to be called in `revm::handler::Handler::execution` and - /// `revm::inspector::InspectorHandler::inspect_execution` to check if the initial gas exceeds - /// the tx gas limit, if so, we halt with out of gas. - #[inline] - fn before_execution( - &self, - evm: &mut EVM, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result, ERROR> { - // Check if the initial gas exceeds the tx gas limit, if so, we halt with out of gas - let ctx = evm.ctx(); - let tx = ctx.tx(); - if tx.gas_limit() < init_and_floor_gas.initial_gas { - // If not sufficient gas, we halt with out of gas - let oog_frame_result = gen_oog_frame_result(tx.kind(), tx.gas_limit()); - return Ok(Some(oog_frame_result)); - } - Ok(None) - } -} - -/// A fee recipient's pre-reward state, captured before delegating to op-revm so the -/// post-reward diff can tell whether the credit changed or materialised the account. -struct FeeRecipientSnapshot { - address: Address, - balance: U256, - was_empty: bool, -} - -/// One EIP-7702 authorization that would actually apply, as determined by the read-only -/// pre-application scan in [`MegaHandler::scan_applied_eip7702_authorizations`]. -struct AppliedAuthorization { - /// The recovered authority account the authorization delegates. - authority: Address, - /// `true` if applying the authorization materializes an account that does not yet exist. - creates_authority: bool, -} - -impl MegaHandler +impl Handler for MegaHandler where DB: Database, ExtEnvs: ExternalEnvTypes, - EVM: EvmTr>, - ERROR: From + FromStringError, -{ - /// Read-only scan of a transaction's EIP-7702 authorization list, mirroring revm's auth-list - /// application order: the chain-id / `u64::MAX`-nonce / non-empty-non-7702-code gates, the - /// per-authority account-nonce match, and the sequential simulated-nonce tracking for repeated - /// authorities. Returns the authorizations that would actually apply; it does not mutate - /// delegation bytecode (revm's `apply_eip7702_auth_list` does that later). This is the single - /// shared source of the gating logic for the REX5 state-growth pass and the REX6 consolidated - /// accounting, so the two cannot drift. - /// - /// `caller_nonce_already_bumped` selects the caller-nonce baseline: for a call tx, - /// `validate_against_state_and_deduct_caller` bumps the caller's nonce by 1 before - /// `apply_eip7702_auth_list` checks it. A scan running after that bump (REX5, in - /// `pre_execution`) passes `true`; one running before it (REX6, in `validate`) passes `false`, - /// so a self-authorization (`authority == caller`) is compared against `caller.nonce + 1` and - /// matches the real application. Each net-new authority appears at most once (the simulated - /// nonce dedupes repeats), so callers may treat the `creates_authority` entries as a set. - fn scan_applied_eip7702_authorizations( - &self, - evm: &mut EVM, - caller_nonce_already_bumped: bool, - ) -> Result, ERROR> { - let ctx = evm.ctx_mut(); - let chain_id = ctx.cfg().chain_id; - let (tx, journal) = ctx.tx_journal_mut(); - let caller = tx.caller(); - // Transaction-local simulated auth-list state, mirroring revm's sequential processing - // when the same authority appears multiple times in one tx. A `BTreeMap` keeps - // per-authorization lookup/update at O(log N) instead of the O(N) linear scan a `Vec` - // would need, bounding the whole pass at O(N log N) (an attacker could otherwise drive - // O(N²) node CPU with many unique authorities in one tx). The map is only ever keyed, - // never iterated for output, so the produced `applied` list is unchanged. - let mut simulated_authorities = BTreeMap::::new(); - let mut applied = Vec::new(); - for authorization in tx.authorization_list() { - let auth_chain_id = authorization.chain_id(); - if !auth_chain_id.is_zero() && auth_chain_id != U256::from(chain_id) { - continue; - } - if authorization.nonce() == u64::MAX { - continue; - } - let Some(authority) = authorization.authority() else { - continue; - }; - - let (authority_nonce, creates_authority) = if let Some(nonce) = - simulated_authorities.get(&authority).copied() - { - (nonce, false) - } else { - // No-warm read: this scan is a pre-flight count and must not change the - // access list. Authority warming is owned by revm's authorization application; - // `inspect_account` keeps that boundary clean. - let authority_acc = journal.inspect_account(authority, true)?; - if let Some(bytecode) = &authority_acc.info.code { - if !bytecode.is_empty() && !bytecode.is_eip7702() { - continue; - } - } - // Mirror the call tx caller's own nonce bump for a self-authorization, unless this - // scan already runs after that bump. Type-4 txs are always calls (a missing `to` - // is rejected at validation as `Eip7702CannotBeCreate`), so no `is_call` guard is - // needed — the authorization list is non-empty only for calls. - let effective_nonce = if !caller_nonce_already_bumped && authority == caller { - authority_acc.info.nonce.saturating_add(1) - } else { - authority_acc.info.nonce - }; - ( - effective_nonce, - authority_acc.is_empty() && - authority_acc.is_loaded_as_not_existing_not_touched(), - ) - }; - - if authorization.nonce() != authority_nonce { - continue; - } - - applied.push(AppliedAuthorization { authority, creates_authority }); - let next_nonce = authority_nonce.saturating_add(1); - // insert overwrites an existing entry and inserts a new one otherwise, - // matching the prior find-or-push. - simulated_authorities.insert(authority, next_nonce); - } - Ok(applied) - } - - /// Records REX5 state growth for EIP-7702 authorizations that create authority accounts. - /// - /// Runs in `pre_execution` (after the caller nonce bump) and charges only the state-growth - /// dimension; overflow is latched into `AdditionalLimit::has_exceeded_limit` and surfaced as - /// the normal execution failure at the first frame. The caller gates this to the REX5-only - /// path (REX5 on, REX6 off, type-4 tx); REX6+ accounts for every per-authorization effect in - /// the consolidated `validate`-time scan (`record_rex6_eip7702_authority_accounting`) instead. - #[inline] - fn record_rex5_eip7702_authority_state_growth(&self, evm: &mut EVM) -> Result<(), ERROR> { - // Pre-execution pass runs after the caller nonce bump. - let applied = self.scan_applied_eip7702_authorizations(evm, true)?; - let authority_creations = - applied.iter().filter(|auth| auth.creates_authority).count() as u64; - if authority_creations > 0 { - evm.ctx_mut() - .additional_limit - .borrow_mut() - .on_rex5_eip7702_authority_creations(authority_creations); - } - - Ok(()) - } - - /// Side-effect-free read of a fee recipient's balance and emptiness. - /// - /// Uses `inspect_account` (no warming) so reading the recipients to account the - /// post-execution reward does not perturb gas or the access list. - fn fee_recipient_balance_and_emptiness( - evm: &mut EVM, - address: Address, - ) -> Result<(U256, bool), ERROR> { - let info = &evm - .ctx_mut() - .journal_mut() - .inspect_account(address, false) - .map_err(|e| { - ERROR::from_string(format!( - "Failed to inspect fee recipient {address} for REX6 reward accounting: {e:?}", - )) - })? - .info; - Ok((info.balance, info.is_empty())) - } - - /// Snapshots the distinct accounts op-revm credits in the post-execution reward path, - /// each with its pre-reward balance and emptiness. - /// - /// The set is the block beneficiary plus the L1 / base-fee / operator fee vaults. - /// It is deduplicated because the block beneficiary may coincide with a fee vault, and - /// op-revm would otherwise issue two `balance_incr`s to the same on-chain account — which - /// is still a single account write. - fn snapshot_fee_recipients(evm: &mut EVM) -> Result, ERROR> { - let recipients = [ - evm.ctx().block().beneficiary(), - L1_FEE_RECIPIENT, - BASE_FEE_RECIPIENT, - OPERATOR_FEE_RECIPIENT, - ]; - let mut snapshots: Vec = Vec::with_capacity(recipients.len()); - for address in recipients { - if snapshots.iter().any(|snapshot| snapshot.address == address) { - continue; - } - let (balance, was_empty) = Self::fee_recipient_balance_and_emptiness(evm, address)?; - snapshots.push(FeeRecipientSnapshot { address, balance, was_empty }); - } - Ok(snapshots) - } - - /// REX6 consolidated EIP-7702 authorization accounting. - /// - /// Runs in `validate`, before the gas-limit check and fee affordability, and is the single - /// source of truth for per-authorization effects — replacing the pre-REX6 split between the - /// ungated `before_tx_start` DataSize/KV charges and the pre-execution state-growth scan: - /// - charges data size +40 / KV +1 for every *applied* authority (one that passed the chain-id - /// / nonce / code gates), not every recoverable one; - /// - charges state growth +1 for each *net-new* authority and returns its address so the caller - /// can add the dynamic SALT account-creation gas to `initial_gas`; - /// - marks beneficiary detention when an applied authority is the block beneficiary. - /// - /// Returns the net-new authority addresses; the caller uses them both to charge SALT gas and - /// to avoid double-charging an auth-materialized value-transfer recipient. The caller gates - /// this to REX6 type-4 transactions; pre-REX6 keeps the old split frozen. - #[inline] - fn record_rex6_eip7702_authority_accounting( - &self, - evm: &mut EVM, - ) -> Result, ERROR> { - // Runs in validate, before the caller nonce bump. - let applied = self.scan_applied_eip7702_authorizations(evm, false)?; - - // Record per-applied-authority resources + beneficiary detention. Dynamic SALT gas is - // charged by the caller from `materialized` (the net-new authorities). - let ctx = evm.ctx_mut(); - let beneficiary = ctx.inner.block.beneficiary; - let mut materialized = Vec::new(); - let mut beneficiary_applied = false; - for auth in applied { - ctx.additional_limit - .borrow_mut() - .on_rex6_eip7702_authority_applied(auth.creates_authority); - if auth.creates_authority { - // The scanner yields each net-new authority once, so `materialized` stays a set. - debug_assert!(!materialized.contains(&auth.authority)); - materialized.push(auth.authority); - } - if auth.authority == beneficiary { - beneficiary_applied = true; - } - } - - // An applied authority that is the block beneficiary mutates beneficiary state, so mark - // it and re-derive the REX4 beneficiary detention cap — the cap set at `on_new_tx` - // predates this scan and would otherwise miss the authority-side access. - if beneficiary_applied { - ctx.check_and_mark_beneficiary_balance_access(&beneficiary); - if let Some(limit) = ctx.volatile_data_tracker.borrow().get_compute_gas_limit() { - ctx.additional_limit.borrow_mut().set_compute_gas_limit(limit); - } - } - - Ok(materialized) - } -} - -impl MegaEvm { - /// This is the hook to be called in the beginning of the `frame_run` and `inspect_frame_run` - /// functions. This function checks if the additional limit is already exceeded, if so, we - /// should immediately stop and synthesize an interpreter action and return it. - #[inline] - fn before_frame_run( - ctx: &MegaContext, - frame: &EthFrame, - ) -> Result, ContextDbError>> { - // Check if the additional limit is already exceeded, if so, we should immediately stop - // and synthesize an interpreter action. - if ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - if let Some(interpreter_result) = - ctx.additional_limit.borrow_mut().before_frame_run(frame) - { - return Ok(Some(InterpreterAction::Return(interpreter_result))); - } - } - Ok(None) - } - - /// This is the hook to be called in the `frame_run` and `inspect_frame_run` - /// functions after the instructions are executed. Apply `MiniRex` additional limits after - /// running instructions. - /// - /// This handles: - /// - Charging `CODEDEPOSIT_STORAGE_GAS` for successful create operations - /// - Updating additional limits via `after_create_frame_run` - /// - Recording gas remaining for later compute gas tracking - /// - /// Returns `Some(gas_remaining)` if `MiniRex` is enabled and action is a Return, - /// for use in `after_frame_run`. - #[inline] - fn after_frame_run_instructions( - ctx: &MegaContext, - frame: &EthFrame, - action: &mut InterpreterAction, - ) -> Result<(), ContextDbError>> { - if !ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - return Ok(()); - } - let is_rex5 = ctx.spec.is_enabled(MegaSpecId::REX5); - - if let InterpreterAction::Return(interpreter_result) = action { - // Charge storage gas cost for the number of bytes - if frame.data.is_create() && interpreter_result.is_ok() { - let code_deposit_storage_gas = constants::mini_rex::CODEDEPOSIT_STORAGE_GAS * - interpreter_result.output.len() as u64; - if !interpreter_result.gas.record_cost(code_deposit_storage_gas) { - interpreter_result.result = InstructionResult::OutOfGas; - } - } - - // REX5+: pre-charge canonical code-deposit compute gas before - // process_next_action commits the CREATE checkpoint. Skip when - // revm's return_create would not charge it; the existing - // limit-side hook below owns the result-marking on exceed. - if is_rex5 && frame.data.is_create() { - let cfg = ctx.cfg(); - if will_return_create_charge_code_deposit( - interpreter_result, - cfg.max_code_size(), - cfg.spec().into(), - cfg.is_eip3541_disabled(), - ) { - let code_len = interpreter_result.output.len() as u64; - let canonical_code_deposit_gas = - code_len.saturating_mul(revm::interpreter::gas::CODEDEPOSIT); - let _ = ctx - .additional_limit - .borrow_mut() - .record_compute_gas(canonical_code_deposit_gas); - } - } - } - - // Update additional limits. MiniRex is guaranteed to be enabled here. - ctx.additional_limit.borrow_mut().after_frame_run_instructions(frame, action); - - Ok(()) - } - - /// Apply `MiniRex` additional limits after frame action processing. - /// - /// Under REX5+ for CREATE results, the code-deposit compute gas was - /// already pre-charged in [`after_frame_run_instructions`]; pass - /// `None` here so the post-action hook does not double-record. - #[inline] - fn after_frame_run( - ctx: &MegaContext, - frame_output: &mut ItemOrResult, - gas_remaining_before_process_action: Option, - ) -> Result<(), ContextDbError>> { - if !ctx.spec.is_enabled(MegaSpecId::MINI_REX) { - return Ok(()); - } - let is_rex5 = ctx.spec.is_enabled(MegaSpecId::REX5); - - if let ItemOrResult::Result(frame_result) = frame_output { - // REX5+: code-deposit compute gas for CREATE results was already - // pre-charged. Skip post-action recording so we don't double-count. - let pass_through = if is_rex5 && matches!(frame_result, FrameResult::Create(_)) { - None - } else { - gas_remaining_before_process_action - }; - ctx.additional_limit.borrow_mut().after_frame_run(frame_result, pass_through); - } - - Ok(()) - } -} - -/// Mirrors `revm_handler::frame::return_create`'s pre-commit predicate. -/// Returns `true` iff `return_create` would charge `code_len * CODEDEPOSIT` -/// from the interpreter gas and commit the checkpoint. -/// -/// REVIEW ON UPSTREAM BUMP: keep in lockstep with -/// `revm-handler::frame::return_create`. Any revm bump that touches the -/// predicate inputs (`is_ok`, EIP-3541 gate, EIP-170 gate, code-deposit -/// gas availability) requires re-auditing this helper. -fn will_return_create_charge_code_deposit( - interpreter_result: &InterpreterResult, - max_code_size: usize, - runtime_spec_id: revm::primitives::hardfork::SpecId, - is_eip3541_disabled: bool, -) -> bool { - use revm::primitives::hardfork::SpecId; - - if !interpreter_result.result.is_ok() { - return false; - } - if !is_eip3541_disabled && - runtime_spec_id.is_enabled_in(SpecId::LONDON) && - interpreter_result.output.first() == Some(&0xEF) - { - return false; - } - if runtime_spec_id.is_enabled_in(SpecId::SPURIOUS_DRAGON) && - interpreter_result.output.len() > max_code_size - { - return false; - } - let code_deposit_gas = (interpreter_result.output.len() as u64) - .saturating_mul(revm::interpreter::gas::CODEDEPOSIT); - interpreter_result.gas.remaining() >= code_deposit_gas -} - -impl Handler - for MegaHandler -where EVM: EvmTr, Frame = FRAME>, - ERROR: EvmTrError - + From - + From - + FromStringError - + IsTxError - + core::fmt::Debug, + ERROR: EvmTrError + From + FromStringError + IsTxError, FRAME: FrameTr, { type Evm = EVM; - type Error = ERROR; + type HaltReason = OpHaltReason; - type HaltReason = MegaHaltReason; - - delegate! { - to self.op { - fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error>; - fn validate_against_state_and_deduct_caller( - &self, - evm: &mut Self::Evm, - ) -> Result<(), Self::Error>; - fn reimburse_caller(&self, evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult) -> Result<(), Self::Error>; - fn refund(&self, evm: &mut Self::Evm, exec_result: &mut <::Frame as FrameTr>::FrameResult, eip7702_refund: i64); - } - } - - fn pre_execution(&self, evm: &mut Self::Evm) -> Result { - self.validate_against_state_and_deduct_caller(evm)?; + /// revm's pre-execution, then the write records of the EIP-7702 authorities it applied. + /// + /// When those records would cross a limit, the limit is enforced before the writes it + /// guards: the authorizations are taken back with the gas they charged, and the transaction, + /// latched, is stopped at its first frame. + fn pre_execution( + &self, + evm: &mut Self::Evm, + gas: &mut GasTracker, + ) -> Result, Self::Error> { self.load_accounts(evm)?; - // EIP-7702 authority state-growth handling, split by spec era. Only type-4 txs reach - // either branch, and no exempt (system-originated) tx is type-4 here — system txs are - // legacy-typed pre-promotion / deposit-typed post-promotion, and a type-4 system caller is - // rejected earlier in `before_run` — so neither branch consults `is_exempt()`. - if evm.ctx().tx().tx_type() == TransactionType::Eip7702 { - if evm.ctx().spec.is_enabled(MegaSpecId::REX6) { - // `validate()` (`record_rex6_eip7702_authority_accounting`) already charged every - // applied authority against the pre-frame resource dimensions it touches (a - // persistent account write on `data_size` + `kv_update`; `state_growth` for net-new - // authorities; and — when an applied authority is the block beneficiary — a lowered - // detention cap that the intrinsic `compute_gas` can then exceed). If any of those - // pushed the tx over a per-tx limit, the first frame halts anyway — but - // `apply_eip7702_auth_list` `mark_touch`es every authority in pre-execution, and a - // HALT (unlike an `Err`) does not roll those pre-frame writes back. Skip the whole - // list so the halt discards them. - // - // Gate on `AdditionalLimit::limit_exceeded()`: that is the exact condition - // `frame_result_if_exceeding_limit` halts on, so skipping here covers every - // pre-frame dimension (`DataSize`/`KVUpdate`/`ComputeGas`/`StateGrowth`) that could - // trigger that halt — including compute overflows and any dimension added later — - // with no risk of the check and the halt disagreeing. (It is false for both - // `WithinLimit` and `Exempt`, matching the halt path.) `Ok(0)` forgoes the - // existing-authority EIP-7702 refund (`post_execution::refund` records it - // unconditionally) — the intended all-or-nothing consequence of skipping the whole - // list (see `test_rex6_authority_state_growth_overflow_forgoes_refund`). - if evm.ctx().additional_limit.borrow().limit_exceeded() { - return Ok(0); - } - } else if evm.ctx().spec.is_enabled(MegaSpecId::REX5) { - // REX5 runs the authority state-growth scan here in pre-execution; REX6 folds it - // into `validate()`'s accounting above instead. - self.record_rex5_eip7702_authority_state_growth(evm)?; - } + let checkpoint = evm.ctx().journal_mut().checkpoint(); + let gas_before = *gas; + let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + return Ok(None); + }; + if record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i).exceeded_limit() { + evm.ctx().journal_mut().checkpoint_revert(checkpoint); + *gas = gas_before; + let checkpoint = evm.ctx().journal_mut().checkpoint(); + return Ok(Some(PreExecutionOutput { eip7702_refund: 0, checkpoint })); } + Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) + } - self.apply_eip7702_auth_list(evm) + fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { + self.op.validate_env(evm) } - fn run_system_call( - &mut self, + fn validate_against_state_and_deduct_caller( + &self, evm: &mut Self::Evm, - ) -> Result, Self::Error> { - // system call does not call `pre_execution` and `post_execution`, so we need to extract - // some logic from them. - let ctx = evm.ctx_mut(); - ctx.on_new_tx(); - - // dummy values that are not used. - let init_and_floor_gas = InitialAndFloorGas::new(0, 0); - // call execution and than output. - match self - .execution(evm, &init_and_floor_gas) - .and_then(|exec_result| self.execution_result(evm, exec_result)) - { - out @ Ok(_) => out, - Err(e) => self.catch_error(evm, e), - } + init_and_floor_gas: &mut InitialAndFloorGas, + ) -> Result<(), Self::Error> { + self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } - fn run_without_catch_error( + /// Settles the outermost frame: pops its lane and, when the transaction is latched, turns its + /// result into the latched stop; then settles its gas into the transaction's as op-revm does + /// (op-revm replaces revm's settlement, so revm's never runs here): a stopped transaction + /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. + /// Keeps the history gas the transaction spent. + fn last_frame_result( &mut self, evm: &mut Self::Evm, - ) -> Result, Self::Error> { - self.before_run(evm)?; - - let init_and_floor_gas = self.validate(evm)?; - let eip7702_refund = self.pre_execution(evm)? as i64; - let mut exec_result = self.execution(evm, &init_and_floor_gas)?; - self.post_execution(evm, &mut exec_result, init_and_floor_gas, eip7702_refund)?; - - // Prepare the output - self.execution_result(evm, exec_result) - } - - /// This function copies the logic from `revm::handler::Handler::validate` to and - /// add additional storage gas cost for calldata. - /// - /// REX5+ adds a final initial+floor gas validation after all Mega-side dynamic storage gas - /// has been accounted for. Pre-REX5 specs keep the historical mid-sequence check exactly - /// where it was so byte-for-byte replay is preserved. - fn validate(&self, evm: &mut Self::Evm) -> Result { - self.validate_env(evm)?; - let mut initial_and_floor_gas = self.validate_initial_tx_gas(evm)?; - - // REX6 only (gated on type-4 tx + REX6 spec): consolidated EIP-7702 authorization - // accounting. Records the per-applied-authority DataSize/KV/StateGrowth + beneficiary - // detention, and returns the net-new authority addresses so the caller folds the dynamic - // SALT account-creation gas into `initial_gas` before the gas-limit / fee-affordability - // check. Pre-REX6 / non-EIP-7702 produces `Vec::new()` and the SALT-gas loop is a no-op. - let record_rex6_accounting = { - let ctx = evm.ctx(); - ctx.spec.is_enabled(MegaSpecId::REX6) && ctx.tx().tx_type() == TransactionType::Eip7702 - }; - let materialized_authorities = if record_rex6_accounting { - self.record_rex6_eip7702_authority_accounting(evm)? - } else { - Vec::new() - }; - - let ctx = evm.ctx_mut(); - let is_mini_rex_enabled = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex_enabled = ctx.spec.is_enabled(MegaSpecId::REX); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - if is_mini_rex_enabled { - // record the initial gas cost as compute gas cost, limit exceeding will be captured in - // `frame_init` function. - ctx.additional_limit() - .borrow_mut() - .record_compute_gas(initial_and_floor_gas.initial_gas); - - // MegaETH MiniRex modification: calldata storage gas costs (10x the standard EVM rates) - // - Standard tokens: 40 gas per token (vs 4) - // - EIP-7623 floor: 100 gas per token (vs 10) - let tokens_in_calldata = get_tokens_in_calldata(ctx.tx().input(), true); - let calldata_storage_gas = - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_GAS * tokens_in_calldata; - initial_and_floor_gas.initial_gas += calldata_storage_gas; - let floor_calldata_storage_gas = - constants::mini_rex::CALLDATA_STANDARD_TOKEN_STORAGE_FLOOR_GAS * tokens_in_calldata; - initial_and_floor_gas.floor_gas += floor_calldata_storage_gas; - - // MegaETH Rex modification: additional intrinsic storage gas cost - // Add 39,000 gas on top of base intrinsic gas for all transactions - if is_rex_enabled { - initial_and_floor_gas.initial_gas += constants::rex::TX_INTRINSIC_STORAGE_GAS; - } - - // Pre-REX5: keep the historical mid-sequence initial-gas check here so existing - // stable-spec replays produce exactly the same OOG-after-fee-charge result on - // transactions whose final Mega-adjusted initial_gas exceeds gas_limit only after - // CREATE/new-account storage gas is added below. - // - // REX5+: this mid-sequence check is deferred to the final check below, which runs - // after CREATE/new-account storage gas has also been added so a transaction that - // cannot fit its final Mega-side intrinsic+storage gas is rejected as a validation - // error before pre_execution() debits the sender or bumps the nonce. - if !is_rex5_enabled && initial_and_floor_gas.initial_gas > ctx.tx().gas_limit() { - return Err(InvalidTransaction::CallGasCostMoreThanGasLimit { - gas_limit: ctx.tx().gas_limit(), - initial_gas: initial_and_floor_gas.initial_gas, - } - .into()); - } - - // MegaETH modification: additional storage gas cost for creating account - let kind = ctx.tx().kind(); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - let (callee_address, storage_gas) = match kind { - TxKind::Create => { - let caller = ctx.tx().caller(); - // REX5+: derive the created address from the caller's - // state nonce — the same value `make_create_frame` uses - // for the actual deployment. Pre-REX5 keeps `tx.nonce()`. - let nonce = if is_rex5_enabled { - ctx.journal_mut() - .inspect_account(caller, false) - .map_err(|e| { - Self::Error::from_string(format!( - "Failed to inspect caller account for CREATE storage gas: {e:?}", - )) - })? - .info - .nonce - } else { - ctx.tx().nonce() - }; - let created_address = caller.create(nonce); - - let storage_gas = if is_rex_enabled { - // Rex spec distinguishes between contract creation and account creation. - ctx.create_contract_storage_gas(created_address) - } else { - // Mini-Rex spec does not distinguish between contract creation and account - // creation. - ctx.new_account_storage_gas(created_address) - }; - (created_address, storage_gas) - } - TxKind::Call(address) => { - // Reading emptiness through the journal (instead of the raw DB) is - // observationally equivalent on every spec, relying on two invariants: - // pre-REX6 the journal holds no entries when `validate` runs (each - // transaction's journal is drained at finalize, and access-list warming / - // `deduct_caller` only run in `pre_execution`, after `validate`), so the - // read observes exactly the DB value; and the cold entry the read inserts - // is the call target, which frame init loads for every call transaction - // anyway, so the transaction's returned state gains no new account. - // Under REX6 the authority scan above may have journaled applied - // authorities already; for those the read observes the applied - // delegation, which is the intended REX6 semantics. - let new_account = !ctx.tx().value().is_zero() && - ctx.journal_mut().inspect_account(address, false)?.info.is_empty() && - // If an applied EIP-7702 authorization materializes this recipient, its - // creation gas is charged via the authority SALT gas below — don't - // double-charge the value-transfer new-account gas for the same account. - !materialized_authorities.contains(&address); - let storage_gas = - if new_account { ctx.new_account_storage_gas(address) } else { Some(0) }; - (address, storage_gas) - } - }; - initial_and_floor_gas.initial_gas += storage_gas.ok_or_else(|| { - let err_str = - format!("Failed to get storage gas for callee address: {callee_address}",); - Self::Error::from_string(err_str) - })?; - - // REX6: dynamic SALT account-creation gas for each net-new EIP-7702 authority, - // folded into initial_gas so it is enforced against gas_limit / fee affordability. - // `materialized_authorities` is empty pre-REX6, so this is a no-op on stable specs. - for authority in &materialized_authorities { - let authority_storage_gas = - ctx.new_account_storage_gas(*authority).ok_or_else(|| { - Self::Error::from_string(format!( - "Failed to get storage gas for EIP-7702 authority: {authority}", - )) - })?; - initial_and_floor_gas.initial_gas += authority_storage_gas; - } - - // REX5+: charge dynamic new-account storage gas for a deposit-driven caller - // materialisation (either `tx.mint() > 0` balance increment or pre-execution - // nonce bump). Mirrors the `TxKind::Call(address) with value` branch above, - // but for the caller side. Detection runs here so we observe the pre- - // pre-execution state — `OpHandler::pre_execution` (run after `validate`) is - // what actually materialises the caller account. - // - // `data_size` / `kv_update` are intentionally NOT touched: their - // `before_tx_start` hooks already record the caller's account-info write - // unconditionally for every transaction. Only `state_growth` (which has no - // pre-existing caller-side accounting) and intrinsic gas need the charge. - // Skip this branch inside sandbox contexts: the sandbox view of `caller`'s nonce - // is overridden to 0 by `SandboxDb`, which would mis-classify a previously - // materialised signer as empty on retry. The keyless-deploy outer flow charges - // caller materialisation explicitly via `charge_caller_materialization_pre_sandbox` - // before constructing the sandbox tx, based on the parent journal-visible state. - if is_rex5_enabled && !ctx.is_inside_sandbox() { - let caller = ctx.tx().caller(); - let system_address = ctx.system_address; - if is_deposit_like_transaction(&ctx.inner.tx, system_address) { - // Journal read equivalence: as for the recipient emptiness check above, - // the journal is empty at `validate` time on frozen specs (drained at the - // previous transaction's finalize, warmed only in `pre_execution`), so - // this observes the raw DB value, and the inserted cold entry is the - // caller, which `deduct_caller` loads for every transaction anyway. - let caller_is_empty = - ctx.journal_mut().inspect_account(caller, false)?.info.is_empty(); - if caller_is_empty { - // Self-call corner: if the deposit is a `TxKind::Call(caller)` with - // non-zero `value` AND the same empty caller as callee, the existing - // callee branch above has already charged `new_account_storage_gas(caller)` - // for the same account materialisation. Don't charge the gas a second - // time — but still record the state-growth event (the existing branch - // never records state_growth; the +1 here reflects the single account - // materialisation that pre_execution will perform). - let already_charged_as_callee = matches!( - ctx.tx().kind(), - TxKind::Call(addr) if addr == caller, - ) && !ctx.tx().value().is_zero(); - if !already_charged_as_callee { - let storage_gas = - ctx.new_account_storage_gas(caller).ok_or_else(|| { - let err_str = format!( - "Failed to get storage gas for deposit caller: {caller}", - ); - Self::Error::from_string(err_str) - })?; - initial_and_floor_gas.initial_gas += storage_gas; - } - ctx.additional_limit.borrow_mut().record_deposit_caller_creation(); - } - } - } - - // REX5+: final initial+floor gas validation, after every Mega-side storage gas - // contribution has been added. A transaction that fails either bound is rejected - // here as a canonical validation error so callers see Err(...) rather than an - // ExecutionResult::Halt with full gas spent — i.e. fees and nonce stay untouched - // when the tx cannot fit its final intrinsic+storage gas requirement. - if is_rex5_enabled { - let gas_limit = ctx.tx().gas_limit(); - if initial_and_floor_gas.initial_gas > gas_limit { - return Err(InvalidTransaction::CallGasCostMoreThanGasLimit { - gas_limit, - initial_gas: initial_and_floor_gas.initial_gas, - } - .into()); - } - if initial_and_floor_gas.floor_gas > gas_limit { - return Err(InvalidTransaction::GasFloorMoreThanGasLimit { - gas_limit, - gas_floor: initial_and_floor_gas.floor_gas, - } - .into()); - } - } - } - - Ok(initial_and_floor_gas) + frame_result: &mut FrameResult, + parent_gas: &mut GasTracker, + ) -> Result<(), Self::Error> { + evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); + self.op.last_frame_result(evm, frame_result, parent_gas)?; + let history = frame_result.gas().history_gas_spent().max(0) as u64; + evm.ctx_mut().additional_limit.set_history_gas_spent(history); + Ok(()) } - /// This function copies the logic from `revm::handler::Handler::execution` to and - /// add new account storage gas - #[inline] - fn execution( - &mut self, + fn reimburse_caller( + &self, evm: &mut Self::Evm, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result { - if let Some(oog_frame_result) = self.before_execution(evm, init_and_floor_gas)? { - return Ok(oog_frame_result); - } - - let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas; - // Create first frame action - let first_frame_input = self.first_frame_input(evm, gas_limit)?; - - // Run execution loop - let mut frame_result = self.run_exec_loop(evm, first_frame_input)?; - - // Handle last frame result - self.last_frame_result(evm, &mut frame_result)?; - Ok(frame_result) + exec_result: &mut FrameResult, + ) -> Result<(), Self::Error> { + self.op.reimburse_caller(evm, exec_result) } - fn reward_beneficiary( + fn refund( &self, evm: &mut Self::Evm, - exec_result: &mut <::Frame as FrameTr>::FrameResult, + exec_result: &mut FrameResult, + eip7702_refund: i64, ) -> Result<(), Self::Error> { - if evm.ctx().disable_beneficiary { - return Ok(()); - } - - // Pre-REX6: frozen. Delegate unchanged so stable-spec replay is byte-for-byte — - // the post-execution fee-reward materialisations remain unaccounted exactly as - // historical REX5-and-earlier blocks recorded them. - if !evm.ctx().spec.is_enabled(MegaSpecId::REX6) { - return self.op.reward_beneficiary(evm, exec_result); - } - - // REX6: op-revm credits the beneficiary + fee vaults HERE, after `last_frame_result` - // finalised the trackers — so these writes escape DataSize / KV / StateGrowth unless - // accounted now. Deposit / keyless-sandbox txs credit nothing (op-revm early-returns), - // so the diff naturally records nothing for them. - let snapshots = Self::snapshot_fee_recipients(evm)?; - - self.op.reward_beneficiary(evm, exec_result)?; - - for snapshot in snapshots { - let (balance, now_empty) = - Self::fee_recipient_balance_and_emptiness(evm, snapshot.address)?; - if balance == snapshot.balance { - continue; - } - // One account-info write = 40 bytes DataSize + 1 KV update; a newly materialised - // account also counts as +1 StateGrowth. TX-persistent lane (frames are gone). - let mut limit = evm.ctx().additional_limit.borrow_mut(); - limit.data_size.merge_persistent_usage(ACCOUNT_INFO_WRITE_SIZE); - limit.kv_update.merge_persistent_usage(1); - if snapshot.was_empty && !now_empty { - limit.state_growth.merge_persistent_usage(1); - } - } - - Ok(()) + self.op.refund(evm, exec_result, eip7702_refund) } - fn last_frame_result( - &mut self, + fn reward_beneficiary( + &self, evm: &mut Self::Evm, - frame_result: &mut <::Frame as FrameTr>::FrameResult, + exec_result: &mut FrameResult, ) -> Result<(), Self::Error> { - let is_mini_rex = evm.ctx().spec.is_enabled(MegaSpecId::MINI_REX); - if is_mini_rex { - // Update the additional limit before returning the frame result - evm.ctx().additional_limit.borrow_mut().before_frame_return_result::(frame_result) - } - - // Call the inner last_frame_result function first - // This will finalize gas accounting according to REVM's rules: - // - Spends all gas_limit - // - Only refunds remaining gas if is_ok_or_revert() - self.op.last_frame_result(evm, frame_result)?; - - // After REVM's gas accounting, we need to return the rescued gas from additional limits. - if is_mini_rex { - let ctx = evm.ctx_mut(); - - let additional_limit = ctx.additional_limit.borrow(); - let gas = frame_result.gas_mut(); - gas.erase_cost(additional_limit.rescued_gas); - } - - Ok(()) + self.op.reward_beneficiary(evm, exec_result) } fn execution_result( &mut self, evm: &mut Self::Evm, - result: <::Frame as FrameTr>::FrameResult, - ) -> Result, Self::Error> { - // Capture volatile data info for error reporting - let volatile_info = evm - .ctx() - .spec - .is_enabled(MegaSpecId::MINI_REX) - .then(|| { - let volatile_data_tracker = evm.ctx().volatile_data_tracker.borrow(); - volatile_data_tracker.get_volatile_data_info() - }) - .flatten(); - - // Deposit-style sandbox txs: bypass op-revm's HaltedDepositPostRegolith conversion so - // that a runtime halt surfaces as `Ok(Halt(actual_reason, actual_gas_used))` instead of - // being squashed into `FailedDeposit(gas_limit)`. The keyless-deploy outer flow needs - // the real halt reason to distinguish runtime halts (which must merge sandbox state and - // charge `sandbox_gas_used` against the outer gas counter) from validation-rejects - // (which still flow through `catch_error` and produce `FailedDeposit`). - let result = if evm.ctx().is_inside_sandbox() && - evm.ctx().tx().tx_type() == DEPOSIT_TRANSACTION_TYPE - { - match core::mem::replace(evm.ctx().error(), Ok(())) { - Err(ContextError::Db(e)) => return Err(e.into()), - Err(ContextError::Custom(e)) => return Err(Self::Error::from_string(e)), - Ok(_) => (), - } - let exec_result = - post_execution_output(evm.ctx(), result).map_haltreason(OpHaltReason::Base); - evm.ctx().journal_mut().commit_tx(); - evm.ctx().chain_mut().clear_tx_l1_cost(); - evm.ctx().local_mut().clear(); - evm.frame_stack().clear(); - exec_result - } else { - self.op.execution_result(evm, result)? - }; - Ok(result.map_haltreason(|reason| { - let mut additional_limit = evm.ctx().additional_limit.borrow_mut(); - if additional_limit.is_exceeding_limit_halt(&reason) { - if let Some(access_type) = volatile_info { - if let Some(halt) = - additional_limit.detained_compute_gas_halt_reason(access_type) - { - return halt; - } - } - // normal additional limit exceeded (no volatile data access, or detention - // was not more restrictive than the per-tx compute gas limit) - additional_limit - .check_limit() - .maybe_halt_reason() - .expect("should have a halt reason") - } else { - // not due to additional limit exceeded - MegaHaltReason::Base(reason) - } - })) + result: FrameResult, + result_gas: revm::context::result::ResultGas, + ) -> Result, Self::Error> { + self.op.execution_result(evm, result, result_gas) } fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, - ) -> Result, Self::Error> { - let result = self.op.catch_error(evm, error)?; - Ok(result.map_haltreason(MegaHaltReason::Base)) + ) -> Result, Self::Error> { + self.op.catch_error(evm, error) } } -impl InspectorHandler - for MegaHandler> +impl InspectorHandler for MegaHandler> where DB: Database, + ExtEnvs: ExternalEnvTypes, MegaContext: ContextTr>, - Journal: revm::inspector::JournalExt, + Journal: JournalExt, EVM: InspectorEvmTr< Context = MegaContext, Frame = EthFrame, - Inspector: Inspector< - <::Evm as EvmTr>::Context, - EthInterpreter, - >, + Inspector: Inspector, EthInterpreter>, >, + // Implied by `EvmTrError`, but the `ContextTr>` bound above stops + // the compiler from normalizing the context's database type down to `DB`. ERROR: EvmTrError + + From + + From> + From - + From + FromStringError - + IsTxError - + core::fmt::Debug, + + IsTxError, { type IT = EthInterpreter; - - fn inspect_run_without_catch_error( - &mut self, - evm: &mut Self::Evm, - ) -> Result, Self::Error> { - self.before_run(evm)?; - - let init_and_floor_gas = self.validate(evm)?; - let eip7702_refund = self.pre_execution(evm)? as i64; - let mut frame_result = self.inspect_execution(evm, &init_and_floor_gas)?; - self.post_execution(evm, &mut frame_result, init_and_floor_gas, eip7702_refund)?; - self.execution_result(evm, frame_result) - } - - /// This function copies the logic from `Handler::execution` to add - /// new account storage gas and early OOG check with inspector support. - #[inline] - fn inspect_execution( - &mut self, - evm: &mut Self::Evm, - init_and_floor_gas: &InitialAndFloorGas, - ) -> Result { - if let Some(oog_frame_result) = self.before_execution(evm, init_and_floor_gas)? { - return Ok(oog_frame_result); - } - - let gas_limit = evm.ctx().tx().gas_limit() - init_and_floor_gas.initial_gas; - // Create first frame action - let first_frame_input = self.first_frame_input(evm, gas_limit)?; - - // Run execution loop with inspector - let mut frame_result = self.inspect_run_exec_loop(evm, first_frame_input)?; - - // Handle last frame result - self.last_frame_result(evm, &mut frame_result)?; - Ok(frame_result) - } } -impl revm::handler::EvmTr for MegaEvm -where - DB: Database, -{ +impl EvmTr for MegaEvm { type Context = MegaContext; - type Instructions = MegaInstructions; - - type Precompiles = PrecompilesMap; - + type Precompiles = OpPrecompiles; type Frame = EthFrame; #[inline] - fn ctx(&mut self) -> &mut Self::Context { - &mut self.inner.ctx - } - - #[inline] - fn ctx_ref(&self) -> &Self::Context { - &self.inner.ctx + fn all( + &self, + ) -> (&Self::Context, &Self::Instructions, &Self::Precompiles, &FrameStack) { + self.inner.all() } #[inline] - fn ctx_instructions(&mut self) -> (&mut Self::Context, &mut Self::Instructions) { - (&mut self.inner.ctx, &mut self.inner.instruction) + fn all_mut( + &mut self, + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack, + ) { + self.inner.all_mut() } + /// Starts a frame, in this order: + /// + /// 1. the latch: a latched transaction's frame is answered with the stop; + /// 2. the depth guard: a `CALL` or `STATICCALL` past the call-stack limit is answered with + /// `CallTooDeep` before anything could intercept it; + /// 3. system contract interception ([`MegaEvm::intercept`]); + /// 4. the keyless deployment rewrite ([`MegaEvm::rewrite_keyless`]); + /// 5. the frame's lane is pushed and the writes its start makes are counted; a limit they cross + /// answers the frame with the stop before it runs; + /// 6. revm builds the frame. + /// + /// Steps 1 and 2 are the pre-frame check: they answer a frame nothing may start. The frame's + /// own writes are counted after the interceptor and the rewrite, because the rewrite decides + /// which frame starts (a keyless deployment becomes a creation) and an intercepted frame's + /// writes are the interceptor's to count. + /// + /// A frame answered before revm builds it gets an empty lane, so the lanes stay aligned with + /// the results [`frame_return_result`](EvmTr::frame_return_result) pops. A creation answered + /// with a stop still bumps its creator's nonce, as one that starts and reverts does. #[inline] - fn ctx_precompiles(&mut self) -> (&mut Self::Context, &mut Self::Precompiles) { - (&mut self.inner.ctx, &mut self.inner.precompiles) - } - - fn frame_stack(&mut self) -> &mut FrameStack { - &mut self.inner.frame_stack - } - fn frame_init( &mut self, - mut frame_init: ::FrameInit, + frame_init: FrameInit, ) -> Result, ContextDbError> { - let is_mini_rex_enabled = self.ctx().spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX); - let is_rex3_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX3); - let is_rex4_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX4); - let is_rex5_enabled = self.ctx().spec.is_enabled(MegaSpecId::REX5); - let additional_limit = self.ctx().additional_limit.clone(); - - // Check if this is a call to the oracle contract and mark it as accessed. - // This handles both direct transaction calls and internal CALL operations. - // Rex3+: Oracle access gas detention is triggered by SLOAD (not CALL), so skip this - // CALL-based check for Rex3 and later specs. - // - // The check uses `target_address` which equals the oracle address for CALL and - // STATICCALL, but equals the caller's address for CALLCODE and DELEGATECALL (since - // those execute in the caller's state context). CALLCODE and DELEGATECALL are therefore - // never detected here by design — they do not access oracle state. - // - // MiniRex: Only CALL triggers oracle access detection. STATICCALL, CALLCODE, and - // DELEGATECALL bypass it. - // Rex: STATICCALL is added to oracle access detection (unifying CALL-like behavior). - if is_mini_rex_enabled && !is_rex3_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - let detect_oracle = match call_inputs.scheme { - CallScheme::Call => true, - // Rex fixes the bug in MiniRex where STATICCALL bypasses oracle access - // detection. - CallScheme::StaticCall => is_rex_enabled, - // CALLCODE and DELEGATECALL have target_address = caller (not oracle), - // so check_and_mark_oracle_access would never match anyway. - CallScheme::CallCode | CallScheme::DelegateCall => false, - }; - // Mega system address is exempted from volatile data access enforcement. - if detect_oracle && call_inputs.caller != self.ctx().system_address { - let volatile_data_tracker = self.ctx().volatile_data_tracker.clone(); - let mut tracker = volatile_data_tracker.borrow_mut(); - if tracker.check_and_mark_oracle_access(&call_inputs.target_address) { - if let Some(compute_gas_limit) = tracker.get_compute_gas_limit() { - additional_limit.borrow_mut().set_compute_gas_limit(compute_gas_limit); - } - } - } - } - } - - // REX4+: If a TX-level limit is already exceeded (e.g., intrinsic DataSize/KVUpdate - // overflow from before_tx_start), abort before interceptor dispatch. Interceptors - // return synthetic results that skip before_frame_init(), which would otherwise - // catch the exceeded limit. - // - // Gated to REX4 only: pre-REX4 specs use TX-global check_limit() which catches - // intrinsic overflow during execution. Changing pre-REX4 behavior would break replay. - if is_rex4_enabled { - // Separate borrow scope: the RefMut must be dropped before push_empty_frame - // borrows again. - let exceeded = additional_limit - .borrow_mut() - .frame_result_if_exceeding_limit(&frame_init.frame_input); - if let Some(frame_result) = exceeded { - additional_limit.borrow_mut().push_empty_frame(); - return Ok(FrameInitResult::Result(frame_result)); + if let Some(result) = answer_before_building(&mut self.inner.ctx, &frame_init)? { + self.inner.ctx.additional_limit.push_empty_frame(); + return Ok(ItemOrResult::Result(result)); + } + if let Some(result) = self.intercept(&frame_init) { + self.inner.ctx.additional_limit.push_empty_frame(); + return Ok(ItemOrResult::Result(result)); + } + let frame_init = self.rewrite_keyless(frame_init); + let ctx = &mut self.inner.ctx; + let check = ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); + if check.exceeded_limit() { + return Ok(ItemOrResult::Result(stop_before_building(ctx, &frame_init, &check)?)); + } + // The creator of a creation, to tell afterwards whether revm bumped its nonce. The + // transaction's own creation has no creator record to take back, so the check is a + // no-op there. + let creator = match &frame_init.frame_input { + FrameInput::Create(inputs) => { + Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) } - } - - // REX5+: enforce `CALL_STACK_LIMIT` before interceptor dispatch. Interceptors - // short-circuit before revm's `make_call_frame` runs its own depth check, so - // without this guard a system contract could be invoked at unbounded depth. - // Scope mirrors interceptor dispatch (Call/StaticCall only); other schemes still - // flow into revm where its own depth check applies. - if is_rex5_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) && - frame_init.depth > CALL_STACK_LIMIT as usize - { - let frame_result = gen_call_too_deep_result(call_inputs); - additional_limit.borrow_mut().push_empty_frame(); - return Ok(FrameInitResult::Result(frame_result)); - } + _ => None, + }; + let outcome = match self.inner.frame_init(frame_init)? { + ItemOrResult::Item(frame) => Ok(frame.interpreter.input.target_address), + ItemOrResult::Result(result) => Err(result), + }; + let ctx = &mut self.inner.ctx; + match outcome { + Ok(address) => { + ctx.additional_limit.set_frame_address(address); + Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } - } - - // System contract interception dispatch. - // Each interceptor checks target address and ABI-decodes function selectors. - // Side-effect interceptors (oracle hint) usually return None. - // Short-circuiting paths return Some(FrameResult). - // These synthetic results skip `AdditionalLimit::before_frame_init`; we only push an - // empty tracking frame to keep the additional-limit stacks aligned. - // - // Only `CALL` and `STATICCALL` enter interceptor dispatch. `CALLCODE` and - // `DELEGATECALL` execute in the caller's state context, so intercepting them - // would apply system-contract logic in the wrong state context — the scheme - // guard enforces this policy explicitly rather than relying on upstream - // call-frame semantics to keep `target_address` distinct. - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { - if let Some(result) = - dispatch_system_contract_interceptors(self.ctx(), call_inputs, frame_init.depth) - { - // Push an empty frame to keep the limit tracker stack balanced: - // `frame_return_result` / `last_frame_result` will pop a frame, but - // `after_frame_init` (which normally pushes) was skipped. - if is_mini_rex_enabled { - additional_limit.borrow_mut().push_empty_frame(); + Err(result) => { + if let Some((creator, nonce)) = creator { + if account_nonce(ctx, creator) == nonce { + ctx.additional_limit.creation_did_not_bump_nonce(); } - return Ok(FrameInitResult::Result(result)); } + Ok(ItemOrResult::Result(result)) } } - - if is_mini_rex_enabled { - if let Some(frame_result) = additional_limit - .borrow_mut() - .before_frame_init(&mut frame_init, self.ctx().journal_mut())? - { - return Ok(FrameInitResult::Result(frame_result)); - } - } - - // call the inner frame_init function to initialize the frame - let init_result = self.inner.frame_init(frame_init)?; - - // Apply the additional limits only when the `MINI_REX` spec is enabled. - if is_mini_rex_enabled { - additional_limit.borrow_mut().after_frame_init(&init_result); - } - - Ok(init_result) } - /// This method copies the logic from `revm::handler::EvmTr::frame_run` to and add additional - /// logic before `process_next_action` to handle the additional limit. + /// Runs the frame on top of the stack, unless the transaction is latched: then the frame + /// returns the stop without running another instruction (see [`before_frame_run`]). #[inline] fn frame_run( &mut self, ) -> Result, ContextDbError> { - let frame = self.inner.frame_stack.get(); - let context = &mut self.inner.ctx; - let instructions = &mut self.inner.instruction; - - // Before frame_run Hook - let mut action = if let Some(action) = Self::before_frame_run(context, frame)? { - action - } else { - frame.interpreter.run_plain(instructions.instruction_table(), context) + let evm = &mut self.inner; + let frame = evm.frame_stack.get(); + let ctx = &mut evm.ctx; + let action = match before_frame_run(ctx, frame) { + Some(action) => action, + None => frame.interpreter.run_plain( + evm.instruction.instruction_table(), + evm.instruction.gas_table(), + ctx, + ), }; - - // After frame_run instructions Hook - Self::after_frame_run_instructions(context, frame, &mut action)?; - - // Record gas remaining before frame action processing - let gas_remaining_before = match (&action, context.spec.is_enabled(MegaSpecId::MINI_REX)) { - (InterpreterAction::Return(interpreter_result), true) => { - Some(interpreter_result.gas.remaining()) + frame.process_next_action(ctx, action).inspect(|next| { + if next.is_result() { + frame.set_finished(true); } - _ => None, - }; - - // Process the frame action, it may need to create a new frame or return the current frame - // result. - let mut frame_output = frame - .process_next_action::<_, ContextDbError>(context, action) - .inspect(|i| { - if i.is_result() { - frame.set_finished(true); - } - })?; - - // After frame_run Hook - Self::after_frame_run(context, &mut frame_output, gas_remaining_before)?; - - Ok(frame_output) + }) } + /// Pops the returning frame's lane (merged on success, discarded on failure; under a latch the + /// result is first rewritten to the stop), then returns the result to the caller as revm + /// does. + #[inline] fn frame_return_result( &mut self, - mut result: ::FrameResult, - ) -> Result< - Option<::FrameResult>, - ContextDbError, - > { - let ctx = self.ctx_ref(); - let is_mini_rex = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - // Apply the additional limits only when the `MINI_REX` spec is enabled. - if is_mini_rex { - // call the `on_frame_return` function to update the `AdditionalLimit` if the limit is - // exceeded, return the error frame result - ctx.additional_limit.borrow_mut().before_frame_return_result::(&mut result); - } - - // Call the inner frame_return_result function to return the frame result. - let ret = self.inner.frame_return_result(result)?; - - // Rex4+: Re-enable volatile data access when the disabling frame has returned. - // The inner handler has already popped the frame and committed/reverted the journal, - // so journal depth is decremented at this point. If it dropped below disable_depth, - // the frame that invoked disableVolatileDataAccess() has returned and the disable - // should no longer restrict sibling calls. - if self.ctx_ref().spec.is_enabled(MegaSpecId::REX4) { - let depth = self.ctx_ref().journal_ref().depth(); - self.ctx_ref().volatile_data_tracker.borrow_mut().enable_access_if_returning(depth); - } - - Ok(ret) + mut result: FrameResult, + ) -> Result, ContextDbError> { + self.inner.ctx.additional_limit.on_frame_return(&mut result); + self.inner.frame_return_result(result) } } -impl revm::inspector::InspectorEvmTr - for MegaEvm +impl InspectorEvmTr for MegaEvm where DB: Database, - INSP: Inspector>, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, { type Inspector = INSP; - fn inspector(&mut self) -> &mut Self::Inspector { - &mut self.inner.inspector - } - - fn ctx_inspector(&mut self) -> (&mut Self::Context, &mut Self::Inspector) { - (&mut self.inner.ctx, &mut self.inner.inspector) - } - - fn ctx_inspector_frame( - &mut self, - ) -> (&mut Self::Context, &mut Self::Inspector, &mut Self::Frame) { - (&mut self.inner.ctx, &mut self.inner.inspector, self.inner.frame_stack.get()) + #[inline] + fn all_inspector( + &self, + ) -> ( + &Self::Context, + &Self::Instructions, + &Self::Precompiles, + &FrameStack, + &Self::Inspector, + ) { + let evm = &self.inner; + (&evm.ctx, &evm.instruction, &evm.precompiles, &evm.frame_stack, &evm.inspector) } - fn ctx_inspector_frame_instructions( + #[inline] + fn all_mut_inspector( &mut self, - ) -> (&mut Self::Context, &mut Self::Inspector, &mut Self::Frame, &mut Self::Instructions) { + ) -> ( + &mut Self::Context, + &mut Self::Instructions, + &mut Self::Precompiles, + &mut FrameStack, + &mut Self::Inspector, + ) { + let evm = &mut self.inner; ( - &mut self.inner.ctx, - &mut self.inner.inspector, - self.inner.frame_stack.get(), - &mut self.inner.instruction, + &mut evm.ctx, + &mut evm.instruction, + &mut evm.precompiles, + &mut evm.frame_stack, + &mut evm.inspector, ) } - /// Override `inspect_frame_init` to handle the case when inspector returns early. - /// - /// When an inspector's `call` or `create` hook returns `Some(outcome)`, the default - /// implementation returns early without calling `frame_init`. This means no frame is - /// pushed to the additional limit trackers. However, `frame_return_result` will still - /// be called and expect to pop a frame. - /// - /// To keep the frame stacks aligned, we push a dummy frame when inspector returns early. + /// revm's inspected frame start, with the lanes kept aligned: a frame the inspector answers + /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it. #[inline] fn inspect_frame_init( &mut self, - mut frame_init: ::FrameInit, + mut frame_init: FrameInit, ) -> Result, ContextDbError> { let (ctx, inspector) = self.ctx_inspector(); - let is_mini_rex_enabled = ctx.spec.is_enabled(MegaSpecId::MINI_REX); - let is_rex4_enabled = ctx.spec.is_enabled(MegaSpecId::REX4); - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - - // Check if inspector wants to skip this call/create if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - // Inspector intercepted — `frame_init()` is skipped entirely, so neither - // `frame_result_if_exceeding_limit` nor `before_frame_init` would run. - // - // The priority order below mirrors `frame_init`'s exact order so that a - // TX-level additional-limit exceed is reported instead of being shadowed by - // a CallTooDeep guard: - // 1. TX-level limit exceed (REX4+) - // 2. CALL_STACK_LIMIT depth guard (REX5+) - // 3. Deliver the inspector's synthetic output - // Each early-return path calls `frame_end` to keep inspector callbacks paired. - - // (1) REX4+: if a TX-level limit is already exceeded (e.g., intrinsic - // overflow), abort to ensure correct gas rescue before inspector callbacks. - // Gated to REX4 to avoid changing stable spec behavior. - if is_rex4_enabled { - let exceeded = ctx - .additional_limit - .borrow_mut() - .frame_result_if_exceeding_limit(&frame_init.frame_input); - if let Some(mut frame_result) = exceeded { - ctx.additional_limit.borrow_mut().push_empty_frame(); - frame_end(ctx, inspector, &frame_init.frame_input, &mut frame_result); - return Ok(ItemOrResult::Result(frame_result)); - } - } - // (2) REX5+: enforce CALL_STACK_LIMIT for Call/StaticCall so an inspector - // cannot deliver a synthetic call result at unbounded depth, mirroring the - // protection added to `frame_init` before interceptor dispatch. - if is_rex5_enabled { - if let FrameInput::Call(call_inputs) = &frame_init.frame_input { - if matches!(call_inputs.scheme, CallScheme::Call | CallScheme::StaticCall) && - frame_init.depth > CALL_STACK_LIMIT as usize - { - let mut frame_result = gen_call_too_deep_result(call_inputs); - ctx.additional_limit.borrow_mut().push_empty_frame(); - frame_end(ctx, inspector, &frame_init.frame_input, &mut frame_result); - return Ok(ItemOrResult::Result(frame_result)); - } - } - } - // (3) MINI_REX+: push empty frame to keep the limit tracker stack balanced - // (`before_frame_return_result` will pop). - if is_mini_rex_enabled { - ctx.additional_limit.borrow_mut().push_empty_frame(); + // The inspector answered the frame. The latch and the depth guard still hold: an + // answer cannot start a frame of a stopped transaction, nor reach past the call-stack + // limit. + if let Some(answer) = answer_before_building(ctx, &frame_init)? { + output = answer; } - frame_end(ctx, inspector, &frame_init.frame_input, &mut output); + ctx.additional_limit.push_empty_frame(); + frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } - - // Normal path - delegate to frame_init (which pushes a real frame) let frame_input = frame_init.frame_input.clone(); + let logs_i = ctx.journal().logs().len(); if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { let (ctx, inspector) = self.ctx_inspector(); - frame_end(ctx, inspector, &frame_input, &mut output); + // Logs the frame journaled without running: the EIP-7708 transfer log, and the logs + // of a precompile. + if ctx.journal().logs().len() != logs_i { + inspect_logs(ctx, inspector, logs_i); + } + // Custom precompiles gather their logs outside the journal. + if let FrameResult::Call(outcome) = &output { + if outcome.was_precompile_called { + for log in outcome.precompile_call_logs.clone() { + inspector.log(ctx, log); + } + } + } + frame_end_checked(ctx, inspector, &frame_input, &mut output); return Ok(ItemOrResult::Result(output)); } - - // Frame created successfully - initialize the interpreter let (ctx, inspector, frame) = self.ctx_inspector_frame(); - inspector.initialize_interp(frame.interpreter(), ctx); + if ctx.journal().logs().len() != logs_i { + inspect_logs(ctx, inspector, logs_i); + } + inspector.initialize_interp(&mut frame.interpreter, ctx); Ok(ItemOrResult::Item(frame)) } - /// This method copies the logic from `MegaEvm::frame_run` with inspector support. - /// It adds the same additional limit checks while using `inspect_instructions` instead of - /// `run_plain`. + /// revm's inspected frame run, with the latch short-circuit of [`EvmTr::frame_run`]: a frame + /// of a latched transaction returns the stop without a step, and the inspector sees it end. #[inline] fn inspect_frame_run( &mut self, ) -> Result, ContextDbError> { let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); - - let mut action = if let Some(action) = Self::before_frame_run(ctx, frame)? { - action - } else { - inspect_instructions( + let action = match before_frame_run(ctx, frame) { + Some(action) => action, + None => inspect_instructions( ctx, - frame.interpreter(), - inspector, + &mut frame.interpreter, + &mut *inspector, instructions.instruction_table(), - ) + instructions.gas_table(), + ), }; + let mut next = frame.process_next_action(ctx, action); + if let Ok(ItemOrResult::Result(result)) = &mut next { + frame_end_checked(ctx, inspector, &frame.input, result); + frame.set_finished(true); + } + next + } +} - // Apply additional limits and storage gas cost - Self::after_frame_run_instructions(ctx, frame, &mut action)?; - - // Record gas remaining before frame action processing - let gas_remaining_before = match (&action, ctx.spec.is_enabled(MegaSpecId::MINI_REX)) { - (InterpreterAction::Return(interpreter_result), true) => { - Some(interpreter_result.gas.remaining()) - } - _ => None, - }; +/// The action of a frame about to run: the latched stop, returned without running an +/// instruction, when the transaction is latched; `None` otherwise, and the frame runs. +/// +/// A frame runs here for the first time or after a child returned into it. Under a latch it is +/// the latter: the child that crossed the limit reverted, and its caller must not resume. +#[inline] +fn before_frame_run( + ctx: &MegaContext, + frame: &EthFrame, +) -> Option { + let latched = ctx.additional_limit.latched()?; + Some(InterpreterAction::new_return( + InstructionResult::Revert, + latched.revert_data(), + frame.interpreter.gas, + )) +} - // Process the frame action, it may need to create a new frame or return the current frame - // result. - let mut frame_output = frame - .process_next_action::<_, ContextDbError>(ctx, action) - .inspect(|i| { - if i.is_result() { - frame.set_finished(true); - } - })?; +/// The result of a frame a limit stopped before it ran: a revert with the stop's +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a +/// [`synthetic_frame_result`] that settles like a frame revm ran. +fn stopped_frame_result(frame_init: &FrameInit, check: &LimitCheck) -> FrameResult { + synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, check.revert_data()) +} - // After frame_run Hook - Self::after_frame_run(ctx, &mut frame_output, gas_remaining_before)?; +impl MegaEvm { + /// System contract interception: a `CALL` or `STATICCALL` to a system contract answered by + /// `MegaETH` instead of the contract's code. + /// + /// The extension point of the system contract interceptors; nothing is intercepted yet. An + /// answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles like + /// a frame revm ran. + // Takes the EVM mutably: an interceptor reads and writes the context. + #[allow(clippy::needless_pass_by_ref_mut)] + #[inline] + const fn intercept(&mut self, _frame_init: &FrameInit) -> Option { + None + } - // Call frame_end for inspector callback - if let ItemOrResult::Result(frame_result) = &mut frame_output { - let (ctx, inspector, frame) = self.ctx_inspector_frame(); - frame_end(ctx, inspector, frame.frame_input(), frame_result); - } + /// The keyless deployment rewrite: a keyless deployment call turned into the native creation + /// it stands for. + /// + /// The extension point of native keyless deployment; nothing is rewritten yet. + // Takes the EVM mutably: the rewrite validates the deployment against the journal. + #[allow(clippy::needless_pass_by_ref_mut)] + #[inline] + const fn rewrite_keyless(&mut self, frame_init: FrameInit) -> FrameInit { + frame_init + } +} - Ok(frame_output) +/// The answer a frame gets before anything builds or answers it otherwise, in this order: the +/// latched stop of a stopped transaction, then the depth guard's `CallTooDeep`. +fn answer_before_building( + ctx: &mut MegaContext, + frame_init: &FrameInit, +) -> Result, ContextDbError>> { + if let Some(latched) = ctx.additional_limit.latched().copied() { + return stop_before_building(ctx, frame_init, &latched).map(Some); } + Ok(call_too_deep(frame_init)) } -/// Builds a `FrameResult` matching revm's `make_call_frame` `CallTooDeep` return: -/// `Gas::new(gas_limit)` (no spend, fully refundable to caller via `erase_cost`), -/// empty output, and the caller's `return_memory_offset`. +/// Answers a frame a limit stops before it is built with the stop. /// -/// Used by the REX5+ depth guard that runs before system-contract interceptor dispatch. -/// Interceptors short-circuit before revm's own depth check, so without this guard a -/// system contract could be invoked at any call-stack depth. -fn gen_call_too_deep_result(call_inputs: &revm::interpreter::CallInputs) -> FrameResult { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( +/// A creation still bumps its creator's nonce, as one that starts and reverts does: a nested +/// creation's caller sees an ordinary failed creation, and a creation transaction stopped before +/// its first frame cannot be replayed. +fn stop_before_building( + ctx: &mut MegaContext, + frame_init: &FrameInit, + check: &LimitCheck, +) -> Result>> { + if let FrameInput::Create(inputs) = &frame_init.frame_input { + let _ = ctx.journal_mut().load_account_mut(inputs.caller())?.data.bump_nonce(); + } + Ok(stopped_frame_result(frame_init, check)) +} + +/// The depth guard: a `CALL` or `STATICCALL` past the call-stack limit, answered with +/// `CallTooDeep`, its gas untouched and its reservoir carried. +/// +/// revm checks the depth when it builds a frame; an interceptor or an inspector answers before +/// revm builds anything, so without the guard a system contract could be reached at any depth. +/// `CALLCODE` and `DELEGATECALL` never reach an interceptor and are left to revm's own check. +fn call_too_deep(frame_init: &FrameInit) -> Option { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; + let guarded = matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall); + (guarded && frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { + synthetic_frame_result( + &frame_init.frame_input, InstructionResult::CallTooDeep, Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) + ) + }) } -/// Builds a top-level `FrameResult` for the case where `validate()` returned an -/// `initial_gas` that exceeds the transaction's `gas_limit` by the time -/// `before_execution` re-checks it. -/// -/// The frame result carries `InstructionResult::OutOfGas` with `Gas::new_spent(gas_limit)` -/// (entire tx budget burnt, no remaining), matching how an EVM-level OOG halt is -/// represented for top-level transactions. The `FrameResult` variant (`Call` vs `Create`) -/// is chosen by `tx_kind` so the downstream output helper can extract the right -/// fields without re-matching on transaction kind. -/// -/// Called from `MegaHandler::before_execution` when `tx.gas_limit() < init_gas`, -/// which can happen after `MegaHandler::validate` has added any MegaETH-specific -/// intrinsic gas (calldata storage gas, REX intrinsic storage gas, callee-side -/// new-account storage gas, or the REX5+ deposit-caller storage gas). -fn gen_oog_frame_result(tx_kind: TxKind, gas_limit: u64) -> FrameResult { - match tx_kind { - TxKind::Call(_address) => FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - Default::default(), - )), - TxKind::Create => FrameResult::Create(CreateOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - None, - )), +/// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. +#[cold] +#[inline(never)] +fn inspect_logs( + ctx: &mut MegaContext, + inspector: &mut INSP, + logs_i: usize, +) where + INSP: Inspector, EthInterpreter>, +{ + let logs = ctx.journal().logs()[logs_i..].to_vec(); + for log in logs { + inspector.log(ctx, log); } } + +/// The nonce of an account the journal holds; zero for one it does not. +fn account_nonce( + ctx: &MegaContext, + address: Address, +) -> u64 { + ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// Records the account writes of the EIP-7702 authorities applied since journal entry +/// `journal_i`: each applied authorization bumps its authority's nonce once, so the distinct +/// authorities other than the sender are the accounts written. The sender's write is part of the +/// transaction body. +fn record_applied_authorities( + ctx: &mut MegaContext, + journal_i: usize, +) -> LimitCheck { + if ctx.tx().tx_type() != TransactionType::Eip7702 { + return LimitCheck::WithinLimit; + } + let caller = ctx.tx().caller(); + let target = ctx.tx().kind().to().copied(); + let mut authorities: Vec
= ctx.journal_ref().journal()[journal_i..] + .iter() + .filter_map(|entry| match entry { + JournalEntry::NonceBump { address } if *address != caller => Some(*address), + _ => None, + }) + .collect(); + authorities.sort_unstable(); + authorities.dedup(); + let target_is_authority = + target.is_some_and(|target| authorities.binary_search(&target).is_ok()); + ctx.additional_limit.record_applied_authorities( + caller, + authorities.len() as u64, + target_is_authority, + ) +} diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index bc2d8927f..e8c4bf204 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -1,218 +1,155 @@ -use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; -use op_revm::L1BlockInfo; -use revm::{context::result::EVMError, Inspector}; +//! Factory of Satin EVMs for alloy-evm consumers. + +use alloy_evm::{Database, EvmEnv}; +use op_revm::{precompiles::OpPrecompiles, OpHaltReason}; +use revm::{ + context::{result::EVMError, BlockEnv, DBErrorMarker}, + inspector::NoOpInspector, + Inspector, +}; use crate::{ - DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, MegaContext, - MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, + EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionError, }; -/// Factory for creating `MegaETH` EVM instances. -/// -/// The `EvmFactory` is responsible for creating EVM instances configured with `MegaETH`-specific -/// specifications and optimizations. It encapsulates the `external_envs` service and provides -/// methods to create EVM instances with different configurations. -/// -/// # Type Parameters -/// -/// - `Oracle`: The `external_envs` service to provide deterministic external information during EVM -/// execution. Must implement [`ExternalEnvs`] and [`Clone`] traits. -/// -/// # Usage +/// Creates [`MegaEvm`]s for alloy-evm consumers such as a node's block executor. /// -/// ```rust -/// use alloy_evm::{EvmEnv, EvmFactory}; -/// use mega_evm::{MegaEvmFactory, MegaSpecId}; -/// use revm::database::{CacheDB, EmptyDB}; -/// -/// // Create a factory with default external_envs -/// let factory = MegaEvmFactory::default(); -/// -/// // Create EVM instance -/// let db = CacheDB::::default(); -/// let evm_env = EvmEnv::default(); -/// let evm = factory.create_evm(db, evm_env); -/// ``` -/// -/// # Implementation Details -/// -/// The factory implements [`alloy_evm::EvmFactory`] and provides `MegaETH`-specific -/// customizations through the configured `external_envs` service and chain specifications. -#[derive(derive_more::Debug, Clone)] -#[non_exhaustive] -pub struct MegaEvmFactory { - /// The `external_envs` service to provide deterministic external information during EVM - /// execution. +/// The factory holds the [`ExternalEnvFactory`] that supplies each EVM with the SALT and oracle +/// environments of the block it executes. +#[derive(Clone, Debug, Default)] +pub struct MegaEvmFactory { external_env_factory: ExtEnvFactory, - - /// A builder function to build dynamic precompiles for the EVM. - #[debug(ignore)] - dyn_precompiles_builder: Option, -} - -impl Default for MegaEvmFactory { - /// Creates a new [`EvmFactory`] instance with the default [`DefaultExternalEnvs`]. - /// - /// This is the recommended way to create a factory when no custom `external_envs` is needed. - /// The `DefaultExternalEnvs` provides a no-operation implementation that doesn't perform - /// any external environment queries. - fn default() -> Self { - Self::new() - } } impl MegaEvmFactory { - /// Creates a new [`EvmFactory`] instance with the given `external_envs`. - /// - /// # Parameters - /// - /// - `external_envs`: The `external_envs` service to provide deterministic external information - /// during EVM execution - /// - /// # Returns - /// - /// A new `EvmFactory` instance configured with the provided `external_envs`. - pub fn new() -> Self { - Self { external_env_factory: EmptyExternalEnv, dyn_precompiles_builder: None } + /// Creates a factory whose EVMs have no external environments. + pub const fn new() -> Self { + Self { external_env_factory: EmptyExternalEnv } } } impl MegaEvmFactory { - /// Sets the builder function to build dynamic precompiles for the EVM. - pub fn with_dyn_precompiles_builder( - mut self, - dyn_precompiles_builder: DynPrecompilesBuilder, - ) -> Self { - self.dyn_precompiles_builder = Some(dyn_precompiles_builder); - self - } - - /// Returns a reference to the external environment factory. - /// - /// This is useful for inspecting or cloning the factory after construction, - /// since the field is private and the struct is `#[non_exhaustive]`. - pub fn external_env_factory(&self) -> &ExtEnvFactory { + /// The external environment factory. + pub const fn external_env_factory(&self) -> &ExtEnvFactory { &self.external_env_factory } - /// Sets the external environment factory for the EVM. - /// - /// # Parameters - /// - /// - `external_env_factory`: The external environment factory to use for the EVM. - /// - /// # Returns - /// - /// Returns `self` for method chaining. - pub fn with_external_env_factory( + /// Replaces the external environment factory. + pub fn with_external_env_factory( self, - external_env_factory: NewExtEnvFactory, - ) -> MegaEvmFactory { - MegaEvmFactory { - external_env_factory, - dyn_precompiles_builder: self.dyn_precompiles_builder, - } + external_env_factory: F, + ) -> MegaEvmFactory { + MegaEvmFactory { external_env_factory } } } -impl alloy_evm::EvmFactory - for MegaEvmFactory -{ +impl alloy_evm::EvmFactory for MegaEvmFactory { type Evm>> = MegaEvm; type Context = MegaContext; type Tx = MegaTransaction; - type Error = - EVMError; - type HaltReason = MegaHaltReason; + type Error = EVMError; + type HaltReason = OpHaltReason; type Spec = MegaSpecId; - type Precompiles = PrecompilesMap; - - /// Creates a new `Evm` instance with the provided database and EVM environment. - /// - /// This method constructs a new `Context` using the given database, the specification from the - /// EVM environment, and the factory's `external_envs`. It then sets up the transaction, block, - /// config, and chain environment for the context, and finally returns a new `Evm` instance - /// using the [`NoOpInspector`] as the default inspector. - /// - /// # Parameters - /// - /// - `db`: The database to use for EVM state. - /// - `evm_env`: The EVM environment, including block and config environments. + type BlockEnv = BlockEnv; + /// op-revm's precompile set for the base spec. /// - /// # Returns + /// Provisional: the Satin precompile provider replaces this type when it lands, and code that + /// names `OpPrecompiles` through this associated type has no source-compatibility promise + /// across that change. + type Precompiles = OpPrecompiles; + + /// Creates an EVM for the block in `evm_env`, with the external environments of that block. /// - /// A new [`Evm`] instance configured with the provided database and environment. + /// The configuration fields the spec fixes are set from the spec (see + /// [`MegaContext::with_cfg`]). fn create_evm( &self, db: DB, - evm_env: EvmEnv, - ) -> Self::Evm { - let spec_id = *evm_env.spec_id(); - let block_number = evm_env.block_env.number.to(); - let runtime_limits = EvmTxRuntimeLimits::from_spec(spec_id); - let ctx = MegaContext::new(db, spec_id) - .with_external_envs(self.external_env_factory.external_envs(block_number)) - .with_tx(MegaTransaction::default()) - .with_block(evm_env.block_env) - .with_cfg(evm_env.cfg_env) - .with_chain(L1BlockInfo::default()) - .with_tx_runtime_limits(runtime_limits); - // The builder is an external closure with no exhaustive match over `MegaSpecId`, so it - // receives the behavior projection: dynamic precompiles are execution semantics, and a - // builder keyed on exact specs must not see an alias rung during a rollback window. The - // context above keeps the raw rung. - MegaEvm::new(ctx).with_dyn_precompiles( - self.dyn_precompiles_builder - .as_ref() - .map_or_else(Default::default, |builder| builder(spec_id.behavior())), - ) + evm_env: EvmEnv, + ) -> Self::Evm { + let EvmEnv { cfg_env, block_env } = evm_env; + let external_envs = + self.external_env_factory.external_envs(block_env.number.saturating_to()); + let ctx = MegaContext::new_with_external_envs(db, cfg_env.spec, external_envs) + .with_cfg(cfg_env) + .with_block(block_env); + MegaEvm::new(ctx) } fn create_evm_with_inspector>>( &self, db: DB, - input: EvmEnv, + input: EvmEnv, inspector: I, ) -> Self::Evm { - Self::create_evm(self, db, input).with_inspector(inspector) + self.create_evm(db, input).with_inspector(inspector) } } #[cfg(test)] mod tests { use super::*; + use crate::{test_utils::MemoryDatabase, ExternalEnvs, SaltEnv, TestExternalEnvs}; + use alloy_evm::{Evm, EvmFactory}; + use alloy_primitives::{BlockNumber, U256}; + use core::cell::Cell; + use revm::context::CfgEnv; #[test] fn test_external_env_factory_getter() { - let factory = MegaEvmFactory::new().with_external_env_factory(EmptyExternalEnv); + let factory = MegaEvmFactory::new() + .with_external_env_factory(TestExternalEnvs::new().with_bucket_capacity(7, 1_024)); + + let got: &TestExternalEnvs = factory.external_env_factory(); - let got: &EmptyExternalEnv = factory.external_env_factory(); + assert_eq!(got.get_bucket_capacity(7).unwrap(), 1_024); + } - // Verify the getter returns a stable reference to the same field. - assert!(core::ptr::eq(got, factory.external_env_factory())); + /// Whatever configuration the caller passes, the EVM runs with the switches the spec fixes. + #[test] + fn test_create_evm_applies_the_spec_switches() { + let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg_env.chain_id = 4326; + cfg_env.tx_gas_limit_cap = Some(1 << 24); + cfg_env.enable_amsterdam_eip8037 = false; + let block_env = BlockEnv { number: U256::from(5), ..Default::default() }; + + let evm = MegaEvmFactory::new() + .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env, block_env }); + + assert_eq!(evm.chain_id(), 4326); + assert_eq!(evm.cfg_env().tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); + assert!(evm.cfg_env().enable_amsterdam_eip8037); + assert_eq!(evm.block().number, U256::from(5)); + } + + /// Records the block number each EVM's external environments are created for. + #[derive(Debug, Default)] + struct RecordingFactory(Cell>); + + impl ExternalEnvFactory for RecordingFactory { + type EnvTypes = EmptyExternalEnv; + + fn external_envs(&self, block: BlockNumber) -> ExternalEnvs { + self.0.set(Some(block)); + ExternalEnvs::default() + } } #[test] - fn test_dyn_precompiles_builder_receives_the_behavior_spec() { - use alloy_evm::EvmFactory as _; - use core::sync::atomic::{AtomicU8, Ordering}; - - // The builder must see the behavior projection, never an alias rung: an external - // builder keyed on exact specs would otherwise install a different precompile set - // during a rollback window. - static SEEN_SPEC: AtomicU8 = AtomicU8::new(u8::MAX); - - let factory = - MegaEvmFactory::new().with_dyn_precompiles_builder(std::sync::Arc::new(|spec| { - SEEN_SPEC.store(spec as u8, Ordering::SeqCst); - revm::primitives::HashMap::default() - })); - - let mut evm_env = EvmEnv::::default(); - evm_env.cfg_env.spec = MegaSpecId::MINI_REX_1; - let _evm = factory.create_evm(crate::test_utils::MemoryDatabase::default(), evm_env); - - assert_eq!(SEEN_SPEC.load(Ordering::SeqCst), MegaSpecId::EQUIVALENCE as u8); + fn test_create_evm_takes_the_external_envs_of_the_block() { + let factory = MegaEvmFactory::new().with_external_env_factory(RecordingFactory::default()); + let block_env = BlockEnv { number: U256::from(1_234), ..Default::default() }; + + let evm = factory.create_evm_with_inspector( + MemoryDatabase::default(), + EvmEnv { cfg_env: CfgEnv::new_with_spec(MegaSpecId::SATIN), block_env }, + NoOpInspector, + ); + + assert_eq!(factory.external_env_factory().0.get(), Some(1_234)); + assert!(evm.is_inspecting()); } } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs new file mode 100644 index 000000000..3cfc547a3 --- /dev/null +++ b/crates/mega-evm/src/evm/frame.rs @@ -0,0 +1,248 @@ +//! Frame results built without running a frame, and how they settle. +//! +//! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, and, +//! when they land, the system contract interceptors, precompile normalisation and native keyless +//! deployment. Such a result goes back to the caller like any frame's, and the caller settles it +//! the way revm settles a frame it ran: +//! +//! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) +//! is priced for refund when the frame failed; +//! 2. [`handle_reservoir_remaining_gas`] merges the frame's gas into the caller's: unused regular +//! gas back on success and revert, the frame's reservoir adopted as the caller's own; +//! 3. the refund is refilled into the caller's reservoir. +//! +//! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries +//! the reservoir the frame inherited ([`untouched_call_gas`], [`with_pools_of`]), never +//! `Gas::new(limit)`, which would carry none and bill the sender for the whole reservoir; and it +//! carries the calling opcode's upfront-charge flags, so step 1 refunds the charge. +//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is the settlement, for a +//! mechanism that settles a result into a running frame itself. + +use alloy_primitives::Bytes; +use revm::{ + context::{result::FromStringError, ContextTr}, + context_interface::{cfg::gas::GasTracker, context::take_error, Host}, + handler::{handle_reservoir_remaining_gas, FrameResult}, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, + InterpreterResult, + }, +}; + +/// The gas of a call result built without running the callee: the call's whole gas limit +/// unspent, and the reservoir the call inherited. +#[inline] +pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) +} + +/// The gas of a creation result built without running the init code: its whole gas limit +/// unspent, and the reservoir the creation inherited. +#[inline] +pub fn untouched_create_gas(inputs: &CreateInputs) -> Gas { + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) +} + +/// `gas_limit` of fresh regular gas carrying `source`'s EIP-8037 pools: its reservoir, the state +/// and history gas it charged, and the part of those charges that spilled onto regular gas. +/// +/// For a result whose regular gas is rebuilt (a precompile's output normalised to the gas limit +/// the caller forwarded): the caller keeps the frame's state and history charges on success and +/// rolls them back on failure, so a rebuilt `Gas` that dropped them would hand the caller an +/// empty reservoir and charges the frame never made. +#[inline] +pub const fn with_pools_of(gas_limit: u64, source: &Gas) -> Gas { + let mut gas = Gas::new(gas_limit); + gas.set_reservoir(source.reservoir()); + gas.set_state_gas_spent(source.state_gas_spent()); + gas.set_state_gas_spilled(source.state_gas_spilled()); + gas.set_history_gas_spent(source.history_gas_spent()); + gas +} + +/// A result for the frame `input` would start, built without running it: `result` with +/// `output`, the frame's gas untouched and the inherited reservoir carried, and the calling +/// opcode's upfront state-gas flags, as revm builds the results of the frames it answers itself. +pub fn synthetic_frame_result( + input: &FrameInput, + result: InstructionResult, + output: Bytes, +) -> FrameResult { + match input { + FrameInput::Call(inputs) => FrameResult::Call(CallOutcome { + result: InterpreterResult::new(result, output, untouched_call_gas(inputs)), + memory_offset: inputs.return_memory_offset.clone(), + was_precompile_called: false, + precompile_call_logs: Default::default(), + charged_new_account_state_gas: inputs.charged_new_account_state_gas, + charged_state_gas_address: inputs.target_address, + }), + FrameInput::Create(inputs) => FrameResult::Create(CreateOutcome { + result: InterpreterResult::new(result, output, untouched_create_gas(inputs)), + address: None, + charged_create_state_gas: inputs.charged_create_state_gas(), + charged_state_gas_address: inputs.charged_state_gas_address(), + }), + FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), + } +} + +/// Settles `result`'s gas into `caller_gas` exactly as revm's frame return does: the calling +/// opcode's upfront state-gas charge priced for refund, [`handle_reservoir_remaining_gas`], then +/// the refund refilled into the caller's reservoir. +/// +/// `ctx` prices the refund through the same hook the charge went through; a failed lookup is +/// the error the hook recorded. +pub fn settle_frame_result( + ctx: &mut CTX, + caller_gas: &mut GasTracker, + result: &mut FrameResult, +) -> Result<(), ERROR> +where + CTX: ContextTr + Host, + ERROR: From<::Error> + FromStringError, +{ + take_error::(ctx.error())?; + let refund = match result.refundable_state_gas_charge() { + Some(charge) => match ctx.state_gas_charge(charge) { + Some(refund) => Some(refund), + None => { + take_error::(ctx.error())?; + return Err(ERROR::from_string("state gas price lookup failed".into())); + } + }, + None => None, + }; + let instruction_result = result.instruction_result(); + handle_reservoir_remaining_gas(instruction_result, caller_gas, result.gas_mut().tracker_mut()); + if let Some(refund) = refund { + caller_gas.refill_reservoir(refund); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, Address, U256}; + use revm::interpreter::{CallInput, CallScheme, CallValue}; + + const TARGET: Address = address!("0000000000000000000000000000000000001234"); + + fn call_inputs(gas_limit: u64, reservoir: u64, charged: bool) -> CallInputs { + CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 3..7, + gas_limit, + bytecode_address: TARGET, + known_bytecode: Default::default(), + target_address: TARGET, + caller: Address::ZERO, + value: CallValue::Transfer(U256::from(1)), + scheme: CallScheme::Call, + is_static: false, + reservoir, + charged_new_account_state_gas: charged, + } + } + + /// The untouched gas is the gas limit unspent and the inherited reservoir, not a fresh + /// `Gas::new(limit)`. + #[test] + fn test_untouched_call_gas_carries_the_reservoir() { + let gas = untouched_call_gas(&call_inputs(50_000, 7_000, false)); + assert_eq!(gas.limit(), 50_000); + assert_eq!(gas.remaining(), 50_000); + assert_eq!(gas.reservoir(), 7_000); + assert_ne!(gas, Gas::new(50_000)); + } + + /// Rebuilding the regular gas keeps every EIP-8037 pool of the source. + #[test] + fn test_with_pools_of_keeps_the_pools() { + let mut source = Gas::new_with_regular_gas_and_reservoir(100, 1_000); + assert!(source.record_state_cost(1_050)); + assert!(source.record_history_cost(20)); + let rebuilt = with_pools_of(70, &source); + assert_eq!(rebuilt.limit(), 70); + assert_eq!(rebuilt.remaining(), 70); + assert_eq!(rebuilt.reservoir(), source.reservoir()); + assert_eq!(rebuilt.state_gas_spent(), 1_050); + assert_eq!(rebuilt.state_gas_spilled(), source.state_gas_spilled()); + assert_eq!(rebuilt.history_gas_spent(), 20); + } + + /// A synthetic call result carries the return range, the untouched gas and the upfront + /// charge flags of its inputs. + #[test] + fn test_synthetic_call_result_carries_the_inputs() { + let input = FrameInput::Call(Box::new(call_inputs(9_000, 11, true))); + let FrameResult::Call(outcome) = synthetic_frame_result( + &input, + InstructionResult::CallTooDeep, + Bytes::from_static(b"x"), + ) else { + panic!("a call input gives a call result"); + }; + assert_eq!(outcome.result.result, InstructionResult::CallTooDeep); + assert_eq!(outcome.result.output, Bytes::from_static(b"x")); + assert_eq!(outcome.result.gas, Gas::new_with_regular_gas_and_reservoir(9_000, 11)); + assert_eq!(outcome.memory_offset, 3..7); + assert!(outcome.charged_new_account_state_gas); + assert_eq!(outcome.charged_state_gas_address, TARGET); + assert!(!outcome.was_precompile_called); + } + + /// Settling a failed synthetic call into its caller returns the forwarded gas, keeps the + /// caller's reservoir, and refunds the new-account charge the calling opcode made, as revm's + /// frame return does. + #[test] + fn test_settle_frame_result_refunds_the_upfront_charge() { + use revm::{ + context::{CfgEnv, Context}, + context_interface::cfg::{GasId, GasParams}, + database::EmptyDB, + primitives::hardfork::SpecId, + MainContext, + }; + let mut cfg = CfgEnv::new_with_spec(SpecId::AMSTERDAM); + cfg.enable_amsterdam_eip8037 = true; + cfg.gas_params = GasParams::new_spec(SpecId::AMSTERDAM); + let new_account = cfg.gas_params.get(GasId::new_account_state_gas()); + assert!(new_account > 0); + let mut ctx = Context::mainnet().with_db(EmptyDB::default()).with_cfg(cfg); + + // The caller forwarded 9,000 gas and charged a new account from its 1M reservoir. + let reservoir = 1_000_000; + let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); + assert!(caller.record_state_cost(new_account)); + let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); + let mut result = + synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); + + settle_frame_result::<_, revm::context::result::EVMError>( + &mut ctx, + &mut caller, + &mut result, + ) + .unwrap(); + assert_eq!(caller.remaining(), 100_000, "the forwarded gas comes back"); + assert_eq!(caller.reservoir(), reservoir, "the charge is refunded to the reservoir"); + assert_eq!(caller.state_gas_spent(), 0); + + // A successful synthetic result keeps the charge: the account exists. + let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); + assert!(caller.record_state_cost(new_account)); + let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); + let mut result = synthetic_frame_result(&input, InstructionResult::Stop, Bytes::new()); + settle_frame_result::<_, revm::context::result::EVMError>( + &mut ctx, + &mut caller, + &mut result, + ) + .unwrap(); + assert_eq!(caller.remaining(), 100_000); + assert_eq!(caller.reservoir(), reservoir - new_account); + assert_eq!(caller.state_gas_spent(), new_account as i64); + } +} diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index 2cc8ee2bc..c4d9cd34f 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -1,726 +1,241 @@ -use core::cell::RefCell; - -#[cfg(not(feature = "std"))] -use alloc as std; -use mega_system_contracts::access_control::IMegaAccessControl::VolatileDataAccessType; -use std::{format, rc::Rc}; - -use crate::{ - AdditionalLimit, ExternalEnvTypes, MegaContext, MegaSpecId, OracleEnv, - VolatileDataAccessTracker, ORACLE_CONTRACT_ADDRESS, -}; -use alloy_evm::Database; -use alloy_primitives::{Address, Bytes, Log, B256, U256}; +//! The Host of the Satin engine, and the journal reads that observe without warming. +//! +//! # The Host only observes +//! +//! revm hands the Host the facts of every state-writing opcode: an `SSTORE`'s original, present and +//! new values, a log's topics and data, a `SELFDESTRUCT`'s balance and beneficiary. The Host +//! stages them ([`AdditionalLimit::stage_record`](crate::AdditionalLimit)) and records nothing. +//! The opcode's wrapper commits the staged record after the opcode completed, and discards it when +//! the opcode failed. Recording in the Host would count a write the opcode's own failure then takes +//! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the +//! frame with the record already counted. +//! +//! Every other Host method delegates to op-revm's context. + +use alloy_primitives::map::Entry; use delegate::delegate; use revm::{ - context::{ContextTr, JournalTr}, - context_interface::{context::ContextError, journaled_state::AccountLoad}, - interpreter::{Host, SStoreResult, SelfDestructResult, StateLoad}, - primitives::{hash_map::Entry, StorageKey, KECCAK_EMPTY}, - state::{Account, Bytecode, EvmStorageSlot}, - Journal, + context_interface::{ + cfg::{GasId, GasParams, StateGasCharge, StateGasSite}, + context::{SStoreResult, SelfDestructResult, StateLoad}, + host::LoadError, + journaled_state::{AccountInfoLoad, AccountLoad}, + }, + primitives::{Address, Bytes, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256}, + state::{Account, EvmStorageSlot}, + Database, Journal, }; -impl Host for MegaContext { - // Block environment related methods - with tracking - fn basefee(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BaseFee); - self.inner.basefee() - } - - fn gas_limit(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::GasLimit); - self.inner.gas_limit() - } - - fn difficulty(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::Difficulty); - self.inner.difficulty() - } - - fn prevrandao(&self) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::PrevRandao); - self.inner.prevrandao() - } - - fn block_number(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BlockNumber); - self.inner.block_number() - } - - fn timestamp(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::Timestamp); - self.inner.timestamp() - } - - fn beneficiary(&self) -> Address { - self.mark_block_env_accessed(VolatileDataAccessType::Coinbase); - self.inner.beneficiary() - } - - fn block_hash(&mut self, number: u64) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::BlockHash); - self.inner.block_hash(number) - } - - // Blob-related block environment methods - with tracking - fn blob_gasprice(&self) -> U256 { - self.mark_block_env_accessed(VolatileDataAccessType::BlobBaseFee); - self.inner.blob_gasprice() - } - - fn blob_hash(&self, number: usize) -> Option { - self.mark_block_env_accessed(VolatileDataAccessType::BlobHash); - self.inner.blob_hash(number) - } +use crate::{ExternalEnvTypes, MegaContext, StagedRecord}; +impl revm::context_interface::Host + for MegaContext +{ delegate! { to self.inner { + fn basefee(&self) -> U256; + fn blob_gasprice(&self) -> U256; + fn gas_limit(&self) -> U256; + fn difficulty(&self) -> U256; + fn prevrandao(&self) -> Option; + fn block_number(&self) -> U256; + fn timestamp(&self) -> U256; + fn beneficiary(&self) -> Address; + fn slot_num(&self) -> U256; fn chain_id(&self) -> U256; fn effective_gas_price(&self) -> U256; - fn log(&mut self, log: Log); fn caller(&self) -> Address; + fn blob_hash(&self, number: usize) -> Option; fn max_initcode_size(&self) -> usize; - fn sstore( + fn gas_params(&self) -> &GasParams; + fn is_amsterdam_eip8037_enabled(&self) -> bool; + fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option; + fn state_gas_charge(&mut self, charge: StateGasCharge) -> Option; + fn block_hash(&mut self, number: u64) -> Option; + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn sload(&mut self, address: Address, key: StorageKey) -> Option>; + fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); + fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + fn load_account_info_skip_cold_load( &mut self, address: Address, - key: U256, - value: U256, - ) -> Option>; - fn tstore(&mut self, address: Address, key: U256, value: U256); - fn tload(&mut self, address: Address, key: U256) -> U256; + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn balance(&mut self, address: Address) -> Option>; + fn load_account_delegated(&mut self, address: Address) -> Option>; + fn load_account_code(&mut self, address: Address) -> Option>; + fn load_account_code_hash(&mut self, address: Address) -> Option>; } } - fn selfdestruct( + /// Writes the slot and stages the write's values. + #[inline] + fn sstore_skip_cold_load( &mut self, address: Address, - target: Address, - ) -> Option> { - // Rex4+: Mark beneficiary balance access when SELFDESTRUCT targets the beneficiary. - // This enables gas detention and the disableVolatileDataAccess check in the instruction - // wrapper. - if self.spec.is_enabled(MegaSpecId::REX4) { - self.check_and_mark_beneficiary_balance_access(&target); - } - - // Rex4+: Before inner selfdestruct mutates account status, inspect the account - // to compute state growth refund for same-TX-created accounts (EIP-6780). - // Uses non-delegating inspect_account to ensure we enumerate storage on the - // actual selfdestructed address, not a delegation target. - let selfdestruct_refund = if self.spec.is_enabled(MegaSpecId::REX4) { - let journal = &mut self.inner.journaled_state; - // inspect_account may fail if DB errors; treat as no refund. - inspect_account(journal, address, false).ok().and_then(|account| { - // Only refund if the account was created in this transaction (EIP-6780: - // only same-TX-created accounts are actually destroyed by SELFDESTRUCT). - // Use CreatedLocal flag which matches revm's is_created_locally() check. - if !account.status.contains(revm::state::AccountStatus::CreatedLocal) { - return None; - } - // Count new storage slots: original was zero, current is non-zero. - let slot_count = account - .storage - .values() - .filter(|slot| { - slot.original_value().is_zero() && !slot.present_value().is_zero() - }) - .count() as u64; - // +1 for the account itself (counted in before_frame_init) + slot count. - Some(1 + slot_count) - }) - } else { - None - }; - - let result = self.inner.selfdestruct(address, target); - - // Record state growth refund only on the first effective destruction. - // Repeated SELFDESTRUCT on the same account still returns a result but with - // `previously_destroyed == true` — refunding again would double-count. - if let Some(refund) = selfdestruct_refund { - if let Some(ref state_load) = result { - if !state_load.data.previously_destroyed { - self.additional_limit.borrow_mut().on_selfdestruct(refund); - } - } - } - - result - } - - fn sload(&mut self, address: Address, key: U256) -> Option> { - if self.spec.is_enabled(MegaSpecId::MINI_REX) && address == ORACLE_CONTRACT_ADDRESS { - // Rex3+: Mark oracle access for gas detention on SLOAD rather than CALL. - // The actual gas limit enforcement happens in the SLOAD instruction wrapper - // (detain_gas_ext::sload in instructions.rs). - // Mega system address transactions are exempted from oracle gas detention. - // Note: This checks the transaction sender (from TxEnv) via Host::caller(), - // unlike the pre-Rex3 CALL-based path which checked the frame-level caller. - if self.spec.is_enabled(MegaSpecId::REX3) && self.caller() != self.system_address { - self.volatile_data_tracker.borrow_mut().check_and_mark_oracle_access(&address); - } - - // if the oracle env provides a value, return it. Otherwise, fallback to the inner - // context. - if let Some(value) = self.oracle_env.borrow().get_oracle_storage(key) { - // Accessing oracle contract storage is forced to be cold access, since it always - // reads from the outside world (oracle_env). - return Some(StateLoad::new(value, true)); - } - } - let state_load = self.inner.sload(address, key); - state_load.map(|mut state_load| { - if self.spec.is_enabled(MegaSpecId::MINI_REX) && address == ORACLE_CONTRACT_ADDRESS { - // It is indistinguishable to tell whether a storage access of oracle contract is - // warm or not even if it is loaded from the inner journal state. This is because - // the current execution may be a replay of existing blocks and we cannot know - // whether the payload builder read from the oracle_env or not. So we force such - // sload always to be cold access to ensure consistent gas cost. - state_load.is_cold = true; - } - state_load - }) - } - - fn balance(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.balance(address) - } - - fn load_account_delegated(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - // Rex6+: also mark the EIP-7702 delegate of `address` if any, so a CALL whose - // target delegates to the beneficiary triggers detention even though the raw stack - // operand doesn't match. The Rex4 path only marked the raw input. A resolve DB error - // falls back to the raw address (no delegate mark) — the `load_account_delegated` below - // remains responsible for surfacing the failure. - if self.spec.is_enabled(MegaSpecId::REX6) { - let resolved = self.best_effort_resolve_eip7702_delegate_address(address); - if resolved != address { - self.check_and_mark_beneficiary_balance_access(&resolved); - } - } - self.inner.load_account_delegated(address) - } - - fn load_account_code(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.load_account_code(address) - } - - fn load_account_code_hash(&mut self, address: Address) -> Option> { - self.check_and_mark_beneficiary_balance_access(&address); - self.inner.load_account_code_hash(address) - } -} - -/// Extension trait for the `Host` trait that provides additional functionality for `MegaETH`. -/// -/// Gas cost methods (`sstore_set_storage_gas`, `new_account_storage_gas`, -/// `create_contract_storage_gas`) follow the same error-handling pattern as revm's `Host` trait: -/// on error, stash the error in `self.error()` and return `None`. -/// This ensures that `FatalExternalError` always has a stashed error for revm to drain. -pub trait HostExt: Host { - /// Gets the `MegaSpecId` of the current execution context. - fn spec_id(&self) -> MegaSpecId; - - /// Gets the `AdditionalLimit` instance. Only used when the `MINI_REX` spec is enabled. - fn additional_limit(&self) -> &Rc>; - - /// Gets the gas cost for setting a storage slot to a non-zero value. Only used when the - /// `MINI_REX` spec is enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn sstore_set_storage_gas(&mut self, address: Address, key: U256) -> Option; - - /// Gets the gas cost for creating a new account. Only used when the `MINI_REX` spec is enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn new_account_storage_gas(&mut self, address: Address) -> Option; - - /// Gets the gas cost for creating a new contract. Only used when the `REX` spec is - /// enabled. - /// - /// Returns `None` if the underlying SALT environment returns an error (the error is stashed - /// in `self.error()`). - fn create_contract_storage_gas(&mut self, address: Address) -> Option; - - /// Gets the volatile data tracker. Only used when the `MINI_REX` spec is enabled. - fn volatile_data_tracker(&self) -> &Rc>; - - /// Checks if volatile data access should cause a revert at the current call depth. - /// Returns `true` if `disableVolatileDataAccess()` was called and the current - /// journal depth is deeper than the activation depth. - fn volatile_access_disabled(&self) -> bool; - - /// Returns the block beneficiary address without triggering volatile data tracking. - /// Used by instruction handlers to pre-check whether an opcode targets the beneficiary. - fn beneficiary_address(&self) -> Address; - - /// Resolves the EIP-7702 delegate of `address` one hop on a best-effort basis, returning - /// `address` itself when there is no delegate or when the resolve hits a DB error. - /// - /// Unlike [`JournalInspectTr::resolve_eip7702_delegate_address`], a DB failure here is NOT - /// stashed in `self.error()`. This is for prechecks and side-marks (the beneficiary-volatile - /// guard, the detention side-mark) that compare the delegate against a known address and must - /// never turn a transaction into an error on their own — e.g. a malformed CALL that underflows - /// before it ever runs the target must keep its `StackUnderflow`, not a spurious DB error from - /// eagerly loading a delegate's code it never needs. The opcode's real execution path reads the - /// account again and owns surfacing any genuine DB error. - fn best_effort_resolve_eip7702_delegate_address(&mut self, address: Address) -> Address; -} - -impl HostExt for MegaContext { - #[inline] - fn spec_id(&self) -> MegaSpecId { - self.spec - } - - #[inline] - fn additional_limit(&self) -> &Rc> { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - &self.additional_limit - } - - #[inline] - fn sstore_set_storage_gas(&mut self, address: Address, key: U256) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - // System-tx exemption (REX6+ `LimitCheck::Exempt` stamp): charge un-scaled (min-bucket) - // storage gas so the write never depends on SALT bucket capacity and can never OOG as - // buckets grow. This path also avoids querying the SALT env. - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().sstore_set_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().sstore_set_gas(address, key); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn new_account_storage_gas(&mut self, address: Address) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::MINI_REX)); - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().new_account_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().new_account_gas(address); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn create_contract_storage_gas(&mut self, address: Address) -> Option { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - if self.additional_limit.borrow().has_exceeded_limit.is_exempt() { - return Some(self.dynamic_storage_gas_cost.borrow().create_contract_gas_unscaled()); - } - let result = self.dynamic_storage_gas_cost.borrow_mut().create_contract_gas(address); - result - .map_err(|e| { - *self.error() = Err(ContextError::Custom(format!("{e}"))); - }) - .ok() - } - - #[inline] - fn volatile_data_tracker(&self) -> &Rc> { - &self.volatile_data_tracker + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError> { + let load = self.inner.sstore_skip_cold_load(address, key, value, skip_cold_load)?; + self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); + Ok(load) } + /// Writes the slot and stages the write's values. #[inline] - fn volatile_access_disabled(&self) -> bool { - let current_depth = self.journal_ref().depth(); - self.volatile_data_tracker.borrow().volatile_access_disabled(current_depth) + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Option> { + let load = self.inner.sstore(address, key, value)?; + self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); + Some(load) } + /// Stages the log's topic count and data length, then appends it. #[inline] - fn beneficiary_address(&self) -> Address { - self.inner.block.beneficiary + fn log(&mut self, log: Log) { + self.additional_limit.stage_record(StagedRecord::Log { + topics: log.topics().len() as u8, + data_len: log.data.data.len() as u64, + }); + self.inner.log(log); } + /// Destructs the account and stages whether value moved and where to. #[inline] - fn best_effort_resolve_eip7702_delegate_address(&mut self, address: Address) -> Address { - // Resolve through the journal directly so a DB error propagates as `Err` here (and is - // discarded) rather than being stashed into `self.error()` by - // `MegaContext::inspect_account`. - let spec = self.spec; - self.inner - .journaled_state - .resolve_eip7702_delegate_address(spec, address) - .unwrap_or(address) + fn selfdestruct( + &mut self, + address: Address, + target: Address, + skip_cold_load: bool, + ) -> Result, LoadError> { + let load = self.inner.selfdestruct(address, target, skip_cold_load)?; + self.additional_limit.stage_record(StagedRecord::SelfDestruct { + had_value: load.data.had_value, + target_exists: load.data.target_exists, + to_other_account: target != address, + beneficiary: target, + }); + Ok(load) } } -/// Trait to inspect the journal's internal state without marking any accounts or storage slots as -/// warm. -/// -/// # EIP-7702 address semantics -/// -/// Address handling is intentionally split by call-site purpose. The guiding rule: follow the -/// delegate ONLY to (1) execute the delegate's code and (2) decide whether an operand observes the -/// block beneficiary's state. Everything that *attributes* balance / nonce / storage / state-growth -/// / data-size uses the ORIGINAL address — a delegated account's state is its own, not the -/// delegate's. Before adding a new 7702-touching call site, find its row in this table and use the -/// listed address; do not re-derive the raw-vs-delegate decision ad-hoc. -/// -/// | Purpose | Address | Mechanism | Spec gate | -/// | --- | --- | --- | --- | -/// | Code / execution target | delegate | revm's `load_account_delegated` (not these primitives) | revm-owned | -/// | Storage / SALT / state-growth / account-write accounting | original | `inspect_account` | REX5+ original; pre-REX5 followed the delegate (frozen) | -/// | CALL-family beneficiary / volatile-access check | delegate | `resolve_eip7702_delegate_address` | REX6+ only; `<=` REX5 compares the raw operand (frozen) | -/// | Validate-time authorization accounting | original authority | `inspect_account` with `load_code = true` (EIP-7702 / EIP-3607 detection) | scan-wide | +/// Journal reads that observe an account or a slot without warming it. /// -/// `inspect_account_delegated` follows the delegate; it backs the frozen pre-REX5 accounting path -/// and any caller that genuinely needs the delegate's account. New accounting call sites should use -/// `inspect_account` (original address), not this. -/// -/// To improve performance, when journal does not have the account or storage slot, it will be -/// loaded from the database and cached in the journal. -/// However, since we explicitly mark the account or storage slot as cold, this pre-loading before -/// executing the original instruction will make no difference on gas cost. -/// -/// Both `Journal` and `MegaContext` implement this trait: -/// - `Journal`: `DBError = DB::Error` — returns DB errors for propagation. -/// - `MegaContext`: `DBError = ()` — stashes errors in `self.error()` and returns `Err(())`. +/// A read loads what the journal does not hold yet into it, so the returned state and a +/// stateless witness carry it, and marks it cold, so it neither enters the EIP-2929 access list +/// nor leaves a journal entry. Execution that later touches the same account or slot pays for it +/// as if the read never happened. pub trait JournalInspectTr { - /// The error type returned on DB failures. - type DBError: core::fmt::Debug; + /// The database error. + type DBError; - /// Inspect the account at the given address without marking it as warm and without - /// following EIP-7702 delegation. + /// The account at `address`, without following an EIP-7702 delegation. /// - /// Loads the account from the database into the journal cache (so subsequent - /// in-block reads see this committed state), then explicitly marks it cold so the - /// inspection does not show up in EIP-2929's access list and produces no - /// `account_warmed` journal entry. Use this for metering inspections where the - /// authority's own state matters (e.g., new-account storage-gas premium, SALT - /// bucket lookup, state-growth emptiness check) rather than the delegate's state, - /// and for validate-path reads (nonce, code) that must not participate in the - /// access-list accounting the execution path will perform later. - /// - /// When `load_code` is `true`, additionally invokes `code_by_hash` if the database - /// left `info.code` lazy (production reth-style `StateProviderDatabase::basic` - /// returns `code: None` for accounts with on-chain bytecode, deferring code load). - /// Set this only on call sites that read `info.code` (EIP-7702 detection, EIP-3607 - /// check) — the cheaper `false` path skips `code_by_hash` for every other cold - /// first-touch. Parallels revm's `JournalTr::load_account_optional(.., load_code, - /// ..)` shape. + /// With `load_code`, the code of an account the database served without it is loaded. An + /// account the journal already holds always has its code loaded. fn inspect_account( &mut self, address: Address, load_code: bool, ) -> Result<&mut Account, Self::DBError>; - /// Inspect the account at the given address without marking it as warm. - /// If the account is EIP-7702 type, follows delegation. - /// - /// Starting from REX4, resolves exactly one hop (matching upstream revm behavior). - /// Pre-REX4, follows delegation recursively but detects cycles to prevent stack overflow. - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, Self::DBError>; + /// The code hash of the account at `address`. Never loads the code, so an occupancy check + /// needs only the account in a witness, not its bytecode. + fn inspect_account_code_hash(&mut self, address: Address) -> Result; - /// Inspect the storage at the given address and key without marking it as warm. - /// - /// Starting from REX4, storage is always loaded from the original address without following - /// EIP-7702 delegation (matching upstream revm's sload behavior). - /// Pre-REX4 specs retain the original behavior that follows delegation. + /// The slot `key` of the account at `address`, which is always the account's own storage (an + /// EIP-7702 delegation does not move it). A slot of an account created in this transaction + /// is zero without a database read. fn inspect_storage( &mut self, - spec: MegaSpecId, address: Address, key: StorageKey, ) -> Result<&EvmStorageSlot, Self::DBError>; - - /// Resolve the EIP-7702 delegate of `address` one hop and return the target address. - /// - /// Returns `address` itself when the account is not EIP-7702-delegated. Hydrates `info.code` - /// on REX5+ so EIP-7702 detection works against lazy-code databases (mirrors - /// `inspect_account_delegated`'s rule for stable-spec freeze). - /// - /// Callers gate this on REX6 (the only place it is used). EIP-7702 does not exist on earlier - /// specs, so an account there simply has no delegate code and resolves to `address` — no - /// pre-REX4 special case is needed. - /// - /// Useful for instruction-wrapper checks that need to compare the effective code-running - /// address against a known target (e.g., the block beneficiary) before delegating to revm. - fn resolve_eip7702_delegate_address( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result { - let load_code = spec.is_enabled(MegaSpecId::REX5); - let account = self.inspect_account(address, load_code)?; - let delegate = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(c) => Some(c.address()), - _ => None, - }); - Ok(delegate.unwrap_or(address)) - } -} - -/// Load an account into the journal cache without following EIP-7702 delegation -/// and mark it cold. When `load_code` is `true`, additionally invokes -/// `code_by_hash` if the database left `info.code` lazy. -/// -/// The occupied branch's `code_by_hash` hydration is load-bearing and must -/// stay: removing it would shift observable behavior on stable specs (a second -/// `inspect_account` against the same lazy-code DB would no longer see hydrated -/// code). -fn inspect_account( - journal: &mut Journal, - address: Address, - load_code: bool, -) -> Result<&mut Account, ::Error> { - let transaction_id = journal.transaction_id; - match journal.inner.state.entry(address) { - Entry::Occupied(entry) => { - let account = entry.into_mut(); - if account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { - // Load code if not loaded before - account.info.code = Some(journal.database.code_by_hash(account.info.code_hash)?); - } - Ok(account) - } - Entry::Vacant(entry) => { - let mut account = journal - .database - .basic(address)? - .map(|info| info.into()) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - if load_code && account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { - account.info.code = Some(journal.database.code_by_hash(account.info.code_hash)?); - } - // deliberately mark the account as cold since we are only inspecting it, not warming - // it. - account.mark_cold(); - Ok(entry.insert(account)) - } - } } -/// Cold occupancy read that returns an account's `code_hash` and loads it into the journal (so it -/// appears in the returned `EvmState` / witness) but — unlike [`inspect_account`] — never hydrates -/// `info.code`, even when the account is already resident (`inspect_account`'s already-loaded -/// branch force-loads code via `code_by_hash` regardless of its `load_code` argument). An occupancy -/// check needs only the hash; forcing `code_by_hash` on an already-warmed occupied address would -/// require its bytecode in a stateless witness that need only carry the account proof, turning the -/// expected revert into a spurious DB error on replay. -/// -/// Only [`Journal`] needs this (the REX6 keyless-deploy occupancy check calls it on -/// `ctx.journal_mut()`), so it is a free function rather than a `JournalInspectTr` method. -pub(crate) fn inspect_account_code_hash( - journal: &mut Journal, - address: Address, -) -> Result::Error> { - let transaction_id = journal.transaction_id; - match journal.inner.state.entry(address) { - Entry::Occupied(entry) => Ok(entry.get().info.code_hash), - Entry::Vacant(entry) => { - let mut account = journal - .database - .basic(address)? - .map(|info| info.into()) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - account.mark_cold(); - Ok(entry.insert(account).info.code_hash) - } - } -} - -impl JournalInspectTr for Journal { - type DBError = ::Error; +impl JournalInspectTr for Journal { + type DBError = DB::Error; fn inspect_account( &mut self, address: Address, load_code: bool, - ) -> Result<&mut Account, Self::DBError> { - inspect_account(self, address, load_code) - } - - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, Self::DBError> { - // REX5+ hydrates code before the 7702 detection below; pre-REX5 must not — - // stable specs preserve the latent lazy-DB EIP-7702 detection gap. - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - - let account = inspect_account(self, address, is_rex5_enabled)?; - - let delegated_address = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(code) => Some(code.address()), - _ => None, - }); - let Some(delegated_address) = delegated_address else { - // Not delegated — reload to satisfy borrow checker and return. - let account = self.inner.state.get_mut(&address).unwrap(); - return Ok(account); - }; - - if spec.is_enabled(MegaSpecId::REX4) { - // REX4+: resolve exactly one hop (matching upstream revm behavior). - return inspect_account(self, delegated_address, is_rex5_enabled); - } - - // Pre-REX4: follow delegation recursively with cycle detection. - // Stays on non-hydrating `inspect_account` (load_code = false) deliberately — - // pre-REX4 is pre-REX5, so the lazy-DB EIP-7702 detection gap is the frozen - // behavior on these specs. - let mut current = delegated_address; - let mut visited = std::vec![address]; - loop { - let account = inspect_account(self, current, false)?; - let next = account.info.code.as_ref().and_then(|code| match code { - Bytecode::Eip7702(code) => Some(code.address()), - _ => None, - }); - let Some(next) = next else { - // End of chain — reload and return. - let account = self.inner.state.get_mut(¤t).unwrap(); - return Ok(account); - }; - if visited.contains(&next) { - // Cycle detected — stop here. - let account = self.inner.state.get_mut(¤t).unwrap(); - return Ok(account); + ) -> Result<&mut Account, DB::Error> { + let transaction_id = self.transaction_id; + match self.inner.state.entry(address) { + Entry::Occupied(entry) => { + let account = entry.into_mut(); + if account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { + account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); + } + Ok(account) + } + Entry::Vacant(entry) => { + let mut account = self + .database + .basic(address)? + .map(Account::from) + .unwrap_or_else(|| Account::new_not_existing(transaction_id)); + if load_code && + account.info.code_hash != KECCAK_EMPTY && + account.info.code.is_none() + { + account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); + } + account.mark_cold(); + Ok(entry.insert(account)) } - visited.push(current); - current = next; } } - fn inspect_storage( - &mut self, - spec: MegaSpecId, - address: Address, - key: StorageKey, - ) -> Result<&EvmStorageSlot, Self::DBError> { + fn inspect_account_code_hash(&mut self, address: Address) -> Result { let transaction_id = self.transaction_id; - let is_rex4_enabled = spec.is_enabled(MegaSpecId::REX4); - // EIP-7702 storage semantics: storage belongs to the original address (delegator), - // not the delegate. So `is_created` must be checked on the original address — an - // EOA delegating via 7702 is never CREATEd, so its flag is always false. Checking - // the delegate's flag instead would mistakenly short-circuit storage reads when the - // delegate happens to be a freshly-CREATEd contract in the same tx, corrupting - // SSTORE accounting (gas / kv_updates / data_size) on the delegator's slots. - // Fold two inspect_account calls into one hydrating load on REX4 path. - // inspect_account's occupied branch hydrates lazy code unconditionally, - // so the old second (always-occupied) pass hydrated the same code that - // load_code=true hydrates inline here — identical final account state, - // identical DB-call sequence and error position, one fewer state.entry lookup. - // Newly-created accounts must short-circuit storage misses to ZERO before any DB call. - // Querying here would otherwise trigger a witness lookup for a slot with no meaningful - // pre-state value, which breaks stateless replay when CREATE lands on a pre-funded - // address: its `Loaded` cache status bypasses revm's `State::storage` short-circuit and - // exposes the call to the witness backend. - let is_newly_created; - let account = if is_rex4_enabled { - let account = inspect_account(self, address, true)?; - is_newly_created = account.is_created(); - debug_assert!(account.info.code_hash == KECCAK_EMPTY || account.info.code.is_some()); - account - } else { - // Non-REX4: is_created must be read on the original address (an EOA delegating - // via 7702 is never CREATEd), but the storage account follows delegation — - // genuinely two different accounts, so the two loads cannot be folded. - is_newly_created = inspect_account(self, address, false)?.is_created(); - self.inspect_account_delegated(spec, address)? - }; - // REX4/REX5 hot path: use entry() API for a single HashMap probe. - // The prologue guarantees the account is in inner.state; reload via get_mut - // to narrow the borrow from &mut self to &mut inner.state, keeping - // self.database reachable for the miss path. - if is_rex4_enabled { - let account = self.inner.state.get_mut(&address).unwrap(); - return match account.storage.entry(key) { - Entry::Occupied(entry) => Ok(entry.into_mut()), - Entry::Vacant(entry) => { - let slot_value = if is_newly_created { - U256::ZERO - } else { - self.database.storage(address, key)? - }; - let mut slot = EvmStorageSlot::new(slot_value, transaction_id); - slot.mark_cold(); - Ok(entry.insert(slot)) - } - }; - } - - // Pre-REX4: original contains_key + reload pattern (genuinely two different accounts). - if account.storage.contains_key(&key) { - // Need to reload account to satisfy borrow checker. - let account = self.inspect_account_delegated(spec, address)?; - return Ok(account.storage.get(&key).unwrap()); + match self.inner.state.entry(address) { + Entry::Occupied(entry) => Ok(entry.get().info.code_hash), + Entry::Vacant(entry) => { + let mut account = self + .database + .basic(address)? + .map(Account::from) + .unwrap_or_else(|| Account::new_not_existing(transaction_id)); + account.mark_cold(); + Ok(entry.insert(account).info.code_hash) + } } - // Slot doesn't exist. For newly-created accounts, post-CREATE storage is - // guaranteed empty (EIP-161 / EIP-6780), so return ZERO without touching the DB. - let slot_value = - if is_newly_created { U256::ZERO } else { self.database.storage(address, key)? }; - let mut slot = EvmStorageSlot::new(slot_value, transaction_id); - // deliberately mark the slot as cold since we are only inspecting it, not warming it - slot.mark_cold(); - // Load account again to bypass the borrow checker and insert the slot - let account = self.inspect_account_delegated(spec, address)?; - account.storage.insert(key, slot); - // Return reference to the newly inserted slot - Ok(account.storage.get(&key).expect("slot should exist")) - } -} - -/// `MegaContext` delegates to `Journal` and stashes DB errors via `self.error()`. -/// -/// On DB error, the real error is stashed as `ContextError::Custom` and `Err(())` is returned. -/// Callers should halt with `FatalExternalError` when receiving `Err`. -impl JournalInspectTr for MegaContext { - type DBError = (); - - fn inspect_account(&mut self, address: Address, load_code: bool) -> Result<&mut Account, ()> { - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_account(address, load_code).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) - } - - fn inspect_account_delegated( - &mut self, - spec: MegaSpecId, - address: Address, - ) -> Result<&mut Account, ()> { - // Split borrow: `journaled_state` and `error` are sibling fields on the inner context, - // so we can borrow them independently to avoid the double-call workaround. - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_account_delegated(spec, address).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) } fn inspect_storage( &mut self, - spec: MegaSpecId, address: Address, key: StorageKey, - ) -> Result<&EvmStorageSlot, ()> { - let journal = &mut self.inner.journaled_state; - let error = &mut self.inner.error; - journal.inspect_storage(spec, address, key).map_err(|e| { - *error = Err(ContextError::Custom(format!("{e}"))); - }) + ) -> Result<&EvmStorageSlot, DB::Error> { + let transaction_id = self.transaction_id; + let is_newly_created = self.inspect_account(address, true)?.is_created(); + let account = self.inner.state.get_mut(&address).expect("inspected above"); + match account.storage.entry(key) { + Entry::Occupied(entry) => Ok(entry.into_mut()), + Entry::Vacant(entry) => { + let value = if is_newly_created { + U256::ZERO + } else { + self.database.storage(address, key)? + }; + let mut slot = EvmStorageSlot::new(value, transaction_id); + slot.mark_cold(); + Ok(entry.insert(slot)) + } + } } } @@ -730,9 +245,9 @@ mod tests { use alloy_primitives::{address, keccak256}; use core::cell::Cell; use revm::{ + context::JournalTr, primitives::HashMap, state::{AccountInfo, Bytecode}, - Database, }; /// Minimal `revm::Database` implementation that mimics the production @@ -753,10 +268,8 @@ mod tests { fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { let code = Bytecode::new_raw(bytecode); let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); + self.accounts + .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); self.codes.insert(code_hash, code); self } @@ -764,10 +277,8 @@ mod tests { fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { let code = Bytecode::new_eip7702(delegate); let code_hash = code.hash_slow(); - self.accounts.insert( - address, - AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, - ); + self.accounts + .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); self.codes.insert(code_hash, code); self } @@ -811,8 +322,7 @@ mod tests { let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); let mut journal = Journal::new(db); - let account = - inspect_account(&mut journal, ADDR, false).expect("inspect_account must succeed"); + let account = journal.inspect_account(ADDR, false).expect("inspect_account must succeed"); assert_eq!( account.info.code_hash, expected_hash, @@ -834,7 +344,8 @@ mod tests { let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); let mut journal = Journal::new(db); - let account = inspect_account(&mut journal, ADDR, true) + let account = journal + .inspect_account(ADDR, true) .expect("inspect_account must succeed on first cold-touch"); let hydrated = account .info @@ -858,12 +369,12 @@ mod tests { let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); let mut journal = Journal::new(db); - let first_code_hash = inspect_account(&mut journal, ADDR, false) + let first_code_hash = journal + .inspect_account(ADDR, false) .expect("first inspection must succeed") .info .code_hash; - let second = - inspect_account(&mut journal, ADDR, false).expect("second inspection must succeed"); + let second = journal.inspect_account(ADDR, false).expect("second inspection must succeed"); assert_eq!( second.info.code_hash, first_code_hash, @@ -890,11 +401,13 @@ mod tests { nonce: 5, code_hash: KECCAK_EMPTY, code: None, + ..Default::default() }, ); let mut journal = Journal::new(db); - let account = inspect_account(&mut journal, EOA, true) + let account = journal + .inspect_account(EOA, true) .expect("inspect_account must succeed and be a no-op on EOAs"); assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); assert!( @@ -902,14 +415,16 @@ mod tests { "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ `code_by_hash` off the hot path for accounts without on-chain code", ); + let again = journal.inspect_account(EOA, false).expect("occupied read must succeed"); + assert!(again.info.code.is_none(), "the occupied branch keeps the guard too"); } /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate /// `info.code` — on either branch. In particular the occupied branch must not fall through to /// `code_by_hash` the way `inspect_account(.., false)` does (see - /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets the - /// REX6 keyless-deploy occupancy check decide on the hash alone, without demanding an - /// already-warmed occupied address's bytecode in a stateless witness carrying only its proof. + /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets an + /// occupancy check decide on the hash alone, without demanding an already-warmed occupied + /// address's bytecode in a stateless witness carrying only its proof. #[test] fn test_inspect_account_code_hash_never_hydrates_code() { const ADDR: Address = address!("00000000000000000000000000000000000000dd"); @@ -920,7 +435,7 @@ mod tests { // Vacant cache-miss: returns the hash from `basic()` without hydrating code. let vacant_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("vacant read must succeed"); + journal.inspect_account_code_hash(ADDR).expect("vacant read must succeed"); assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); assert!( journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), @@ -930,7 +445,7 @@ mod tests { // The address is now resident with `code == None`. `inspect_account` would hydrate on this // occupied branch; `inspect_account_code_hash` must not. let occupied_hash = - inspect_account_code_hash(&mut journal, ADDR).expect("occupied read must succeed"); + journal.inspect_account_code_hash(ADDR).expect("occupied read must succeed"); assert_eq!( occupied_hash, expected_hash, "occupied branch must return the cached code_hash" @@ -941,112 +456,6 @@ mod tests { ); } - /// `resolve_eip7702_delegate_address` hydrates lazy delegation bytecode only from REX5: - /// pin both sides of the boundary so a shifted gate (e.g. REX4) fails here. At REX4 a - /// lazy-code delegator resolves to itself (its `0xef0100…` code is never loaded); at REX5 - /// the same first cold touch loads the code and follows the hop. - #[test] - fn test_resolve_eip7702_delegate_loads_code_from_rex5_exactly() { - const DELEGATOR: Address = address!("00000000000000000000000000000000000000e1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000e2"); - - // REX4: no hydration — the delegation is invisible and resolution degrades to identity. - let db = LazyCodeDatabase::default().with_eip7702_delegation(DELEGATOR, DELEGATE); - let mut journal = Journal::new(db); - let resolved = journal - .resolve_eip7702_delegate_address(MegaSpecId::REX4, DELEGATOR) - .expect("resolve must succeed"); - assert_eq!(resolved, DELEGATOR, "REX4 must not load code, so the hop is not followed"); - assert!( - journal.inner.state.get(&DELEGATOR).is_some_and(|a| a.info.code.is_none()), - "REX4 resolution must leave the delegator's code lazy", - ); - - // REX5: the first cold touch hydrates the delegation bytecode and follows the hop. - let db = LazyCodeDatabase::default().with_eip7702_delegation(DELEGATOR, DELEGATE); - let mut journal = Journal::new(db); - let resolved = journal - .resolve_eip7702_delegate_address(MegaSpecId::REX5, DELEGATOR) - .expect("resolve must succeed"); - assert_eq!(resolved, DELEGATE, "REX5 must hydrate the code and follow the hop"); - } - - /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the - /// very first cold inspection against a lazy-code database. Regression guard: - /// any refactor that re-introduces a code-None branch silently degrades the - /// walk to "treat the delegator as a regular EOA". - #[test] - fn test_inspect_account_delegated_follows_eip7702_on_cold_first_touch() { - use revm::context::JournalTr; - - const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); - let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); // PUSH1 0x42 PUSH1 0 SSTORE - - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_bytecode.clone()); - - let mut journal = Journal::new(db); - - let resolved = journal - .inspect_account_delegated(MegaSpecId::REX5, DELEGATOR) - .expect("inspect_account_delegated must succeed on a cold-cache first touch"); - - // The resolved account must be the delegate, not the delegator. The only way - // to distinguish them is the code: the delegator's code is the EIP-7702 - // designation pointing at DELEGATE; the delegate's code is the raw bytecode. - let hydrated = resolved.info.code.as_ref().expect( - "delegate's bytecode must be hydrated by the inner inspect_account call — \ - without the vacant-path hydration, the cold-touch on DELEGATE would leave \ - code as None and any subsequent EIP-7702 walk would see a wrongly-empty target", - ); - assert!( - !matches!(hydrated, Bytecode::Eip7702(_)), - "resolved account must NOT be the delegator (whose code is the EIP-7702 \ - designation); got: {hydrated:?}", - ); - assert_eq!( - hydrated.original_bytes().as_ref(), - delegate_bytecode.as_ref(), - "resolved account's code must match the delegate's raw bytecode — confirms \ - the delegation was followed exactly one hop", - ); - } - - /// Pre-REX5 `inspect_account_delegated` must NOT hydrate `info.code` — the - /// latent EIP-7702 lazy-DB detection gap is the frozen observable behavior of - /// stable specs (hydrating would flip `state_clear_aware_is_empty` and the - /// SALT-bucket nonce in CALL/CREATE/state-growth, breaking spec immutability). - #[test] - fn test_inspect_account_delegated_does_not_hydrate_pre_rex5() { - use revm::context::JournalTr; - - const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); - let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); - - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_bytecode); - - let mut journal = Journal::new(db); - - // REX4 (pre-REX5): the one-hop walk runs but `code = None` against the - // lazy DB hides the 7702 designation, so the walk returns the delegator. - let resolved = journal - .inspect_account_delegated(MegaSpecId::REX4, DELEGATOR) - .expect("inspect_account_delegated must succeed on pre-REX5"); - - assert!( - resolved.info.code.is_none(), - "pre-REX5: `inspect_account_delegated` must NOT hydrate `info.code` — the \ - latent lazy-DB EIP-7702 detection gap on stable specs is intentionally \ - preserved. Resolved account's code: {:?}", - resolved.info.code, - ); - } - /// Pins the `LazyCodeDatabase` fixture's contract against the production /// `revm::Database` shape it is modeling: `basic()` returns /// `code: None` for known accounts, `None` for unknown addresses; @@ -1085,10 +494,8 @@ mod tests { assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); } - // === inspect_storage coverage tests (PR #334) === - #[test] - fn test_inspect_storage_rex4_slot_hit_returns_existing_value() { + fn test_inspect_storage_slot_hit_returns_existing_value() { const ADDR: Address = address!("00000000000000000000000000000000000000bb"); let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); @@ -1098,36 +505,34 @@ mod tests { let expected_value = U256::from(42); { let tid = journal.transaction_id; - let account = inspect_account(&mut journal, ADDR, false).unwrap(); + let account = journal.inspect_account(ADDR, false).unwrap(); let mut slot = EvmStorageSlot::new(expected_value, tid); slot.mark_cold(); account.storage.insert(key, slot); } - let spec = MegaSpecId::REX4; let slot = journal - .inspect_storage(spec, ADDR, key) + .inspect_storage(ADDR, key) .expect("inspect_storage must succeed on existing slot"); assert_eq!( slot.present_value, expected_value, - "REX4 slot hit must return the pre-seeded value" + "a slot hit must return the pre-seeded value" ); assert!(slot.is_cold, "inspected slot must remain cold"); } #[test] - fn test_inspect_storage_rex4_slot_miss_inserts_and_returns_db_value() { + fn test_inspect_storage_slot_miss_inserts_and_returns_db_value() { const ADDR: Address = address!("00000000000000000000000000000000000000cc"); let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); let mut journal = Journal::new(db); let key = U256::from(7); - let spec = MegaSpecId::REX4; let slot = journal - .inspect_storage(spec, ADDR, key) + .inspect_storage(ADDR, key) .expect("inspect_storage must succeed on absent slot"); assert_eq!( @@ -1139,7 +544,7 @@ mod tests { let calls_after_first = journal.database.storage_calls(); let slot2 = - journal.inspect_storage(spec, ADDR, key).expect("second inspect_storage must succeed"); + journal.inspect_storage(ADDR, key).expect("second inspect_storage must succeed"); assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); assert_eq!( @@ -1150,22 +555,21 @@ mod tests { } #[test] - fn test_inspect_storage_rex4_newly_created_short_circuits_db() { + fn test_inspect_storage_newly_created_short_circuits_db() { const ADDR: Address = address!("00000000000000000000000000000000000000dd"); let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); let mut journal = Journal::new(db); { - let account = inspect_account(&mut journal, ADDR, false).unwrap(); + let account = journal.inspect_account(ADDR, false).unwrap(); account.mark_created(); } let key = U256::from(1); - let spec = MegaSpecId::REX4; let slot = journal - .inspect_storage(spec, ADDR, key) + .inspect_storage(ADDR, key) .expect("inspect_storage must succeed on newly-created account"); assert_eq!( @@ -1177,106 +581,84 @@ mod tests { } #[test] - fn test_inspect_storage_pre_rex4_uses_delegation_path() { - const ADDR: Address = address!("00000000000000000000000000000000000000ee"); - const DELEGATE: Address = address!("00000000000000000000000000000000000000ed"); + fn test_inspect_storage_ignores_eip7702_delegation() { + const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); + const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); let db = LazyCodeDatabase::default() - .with_eip7702_delegation(ADDR, DELEGATE) + .with_eip7702_delegation(DELEGATOR, DELEGATE) .with_account_code(DELEGATE, delegate_code); let mut journal = Journal::new(db); - let key = U256::from(5); - let expected = U256::from(123); - let spec = MegaSpecId::MINI_REX; - - // Preload the delegator so the subsequent occupied-branch inspection hydrates the - // EIP-7702 designation and the pre-REX4 delegated walk can follow it. - let _ = inspect_account(&mut journal, ADDR, false).unwrap(); + let key = U256::from(2); + let expected = U256::from(99); { let tid = journal.transaction_id; - let account = inspect_account(&mut journal, DELEGATE, false).unwrap(); + let account = journal.inspect_account(DELEGATOR, false).unwrap(); let mut slot = EvmStorageSlot::new(expected, tid); slot.mark_cold(); account.storage.insert(key, slot); } let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed pre-REX4"); + .inspect_storage(DELEGATOR, key) + .expect("inspect_storage must succeed for a delegator"); assert_eq!( slot.present_value, expected, - "pre-REX4 storage inspection must follow the delegator to the delegate's slot", - ); - assert!(slot.is_cold, "slot must be marked cold"); - assert_eq!( - journal.database.storage_calls(), - 0, - "delegate slot pre-seeded in the cache must be returned without hitting the DB", + "storage is read from the delegator (original address), not the delegate" ); } + /// The Host stages what each state-writing call observed and counts nothing: counting is the + /// opcode wrapper's, after the opcode completed. #[test] - fn test_inspect_storage_pre_rex4_newly_created_short_circuits_db() { - const ADDR: Address = address!("00000000000000000000000000000000000000ef"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - { - let account = inspect_account(&mut journal, ADDR, false).unwrap(); - account.mark_created(); - } + fn test_host_stages_observations_and_counts_nothing() { + use crate::{test_utils::MemoryDatabase, MegaSpecId}; + use revm::{context_interface::Host, primitives::LogData}; - let key = U256::from(6); - let spec = MegaSpecId::MINI_REX; - - let slot = journal - .inspect_storage(spec, ADDR, key) - .expect("inspect_storage must succeed pre-REX4 on newly-created account"); + const CONTRACT: Address = address!("00000000000000000000000000000000000000c1"); + const BENEFICIARY: Address = address!("00000000000000000000000000000000000000c2"); + let db = MemoryDatabase::default().account_balance(CONTRACT, U256::from(3)); + let mut ctx = MegaContext::new(db, MegaSpecId::SATIN); + ctx.inner.journaled_state.load_account(CONTRACT).unwrap(); + let slot = Host::sstore(&mut ctx, CONTRACT, U256::from(1), U256::from(9)).unwrap(); assert_eq!( - slot.present_value, - U256::ZERO, - "pre-REX4 newly-created account must return ZERO without querying database" + ctx.additional_limit.staged_record(), + Some(&StagedRecord::Sstore(slot.data.clone())), + "the non-Berlin entry point stages too" ); - assert!(slot.is_cold, "slot must be marked cold"); + assert_eq!(slot.data.new_value, U256::from(9)); + let slot = + Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(1), U256::from(4), false) + .unwrap(); + assert_eq!(ctx.additional_limit.staged_record(), Some(&StagedRecord::Sstore(slot.data))); + + let log = Log { + address: CONTRACT, + data: LogData::new(vec![B256::ZERO, B256::ZERO], Bytes::from_static(b"abc")).unwrap(), + }; + Host::log(&mut ctx, log); assert_eq!( - journal.database.storage_calls(), - 0, - "newly-created pre-REX4 path must not hit the database storage lookup", + ctx.additional_limit.staged_record(), + Some(&StagedRecord::Log { topics: 2, data_len: 3 }) ); - } - - #[test] - fn test_inspect_storage_rex4_ignores_eip7702_delegation() { - const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); - const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); - let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_code); - let mut journal = Journal::new(db); - - let key = U256::from(2); - let expected = U256::from(99); - { - let tid = journal.transaction_id; - let account = inspect_account(&mut journal, DELEGATOR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let spec = MegaSpecId::REX4; - let slot = journal - .inspect_storage(spec, DELEGATOR, key) - .expect("inspect_storage must succeed for REX4 delegator"); + Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); assert_eq!( - slot.present_value, expected, - "REX4 must read storage from delegator (original address), not delegate" + ctx.additional_limit.staged_record(), + Some(&StagedRecord::SelfDestruct { + had_value: true, + target_exists: false, + to_other_account: true, + beneficiary: BENEFICIARY, + }) + ); + assert_eq!( + ctx.additional_limit.usage(), + crate::LimitUsage::ZERO, + "the Host counts nothing" ); } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs new file mode 100644 index 000000000..eb255511e --- /dev/null +++ b/crates/mega-evm/src/evm/inspector.rs @@ -0,0 +1,364 @@ +//! What an inspector may do to a Satin transaction, and the one thing it may not. +//! +//! An inspector is not a passive observer. A callback holding a live interpreter can write to its +//! gas and its pending action, a callback holding a frame's inputs can change them, and every +//! `*_end` callback can rewrite a result's classification, gas and output. Satin keeps no ledger +//! beside revm's `Gas` (compute is the regular gas spent), so an inspector that changes the gas +//! changes what the transaction owes, and a rewriting inspector gets exactly what it asked for. +//! Rewriting is a tool feature, supported and unmeasured. +//! +//! Two things bound it: +//! +//! - **The admission gate.** [`TrustedObserver`] is a declaration, made in source about one +//! inspector type, that none of its callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) +//! built with [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the +//! declaration, and [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what +//! block execution refuses a transaction on: a rewriting inspector has no route to a block. +//! [`DeclaredObserver`] carries the declaration for a tracer whose type cannot, and in debug +//! builds checks it around every callback. +//! - **The refusal.** A failed contract creation rewritten into a successful one is refused: the +//! transaction fails with [`FORBIDDEN_CREATE_REVIVAL`] as an `EVMError::Custom`. By the time +//! `create_end` runs, revm has reverted the frame and deposited no code, so the rewrite would +//! push an address for code that does not exist and merge the frame's state gas for state that +//! was rolled back. Every other rewrite is the tool's business. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{format, string::String}; + +use revm::{ + context::{ContextError, ContextTr, JournalTr}, + handler::FrameResult, + inspector::{handler::frame_end, JournalExt, NoOpInspector}, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, + Interpreter, InterpreterTypes, + }, + primitives::{Address, Log, U256}, + Inspector, +}; + +/// The message of the `EVMError::Custom` a refused creation revival fails the transaction with. +/// +/// Public so a tool driving rewriting inspectors can tell the refusal from an execution failure. +pub const FORBIDDEN_CREATE_REVIVAL: &str = + "inspector rewrote a failed contract creation into a successful one"; + +/// A declaration, made in source about one inspector type, that none of its callbacks writes +/// anything back to the EVM: nothing to an interpreter's gas or pending action, nothing to a +/// frame's inputs, nothing to a result's classification, gas or output, and no frame answered +/// itself. It may read anything and write its own state. +/// +/// The declaration is what block execution admits an inspected transaction on. +/// +/// - Implement it for one concrete type at a time, never as a blanket implementation, so each +/// declaration is a line someone wrote about a type they had read. +/// - Do not implement it for an inspector that answers a frame, edits inputs or rewrites a result, +/// however rarely. +/// - A foreign inspector type (a `revm-inspectors` tracer) is wrapped in [`DeclaredObserver`], +/// which is local here and carries the declaration. +/// - The test utilities' inspectors are not declared: they are not part of the gate. +pub trait TrustedObserver {} + +/// The inspector an EVM runs with when none was given observes nothing. +impl TrustedObserver for NoOpInspector {} + +/// A declared observer lent by reference stays declared: `&mut T` is declared exactly when `T` +/// is. +impl TrustedObserver for &mut T {} + +/// Carries a [`TrustedObserver`] declaration for an inspector whose type cannot carry one. +/// +/// It forwards every callback to the inspector inside and adds nothing. `DeclaredObserver(tracer)` +/// says "this tracer writes nothing back", moved from a type definition to the line that wraps +/// the value. +/// +/// A debug build checks the declaration around every callback and panics at the one that breaks +/// it: the interpreter's gas, pending action, stack depth and memory size, the frame's inputs, +/// the frame result, and the journal's entries and logs must be as they were, and no frame may be +/// answered. Writes the check cannot see (a stack word replaced in place, a context field outside +/// the journal) are still false declarations; the check is a tripwire, not a proof. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DeclaredObserver(pub I); + +impl DeclaredObserver { + /// Declares `inspector` a read-only observer. + pub const fn new(inspector: I) -> Self { + Self(inspector) + } + + /// The inspector inside. + pub fn into_inner(self) -> I { + self.0 + } +} + +impl TrustedObserver for DeclaredObserver {} + +impl Inspector for DeclaredObserver +where + I: Inspector, + CTX: ContextTr, + INTR: InterpreterTypes, +{ + #[inline] + fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.initialize_interp(interp, context); + assert_unwritten(before, interp, context, "initialize_interp"); + } + + #[inline] + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step(interp, context); + assert_unwritten(before, interp, context, "step"); + } + + #[inline] + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step_end(interp, context); + assert_unwritten(before, interp, context, "step_end"); + } + + #[inline] + fn log(&mut self, context: &mut CTX, log: Log) { + let before = journal_snapshot(context); + self.0.log(context, log); + assert_journal_unwritten(before, context, "log"); + } + + #[inline] + fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { + let before = snapshot(interp, context); + self.0.log_full(interp, context, log); + assert_unwritten(before, interp, context, "log_full"); + } + + #[inline] + fn frame_start( + &mut self, + context: &mut CTX, + frame_input: &mut FrameInput, + ) -> Option { + let before = + cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); + let answer = self.0.frame_start(context, frame_input); + debug_assert!(answer.is_none(), "a declared observer answered a frame in `frame_start`"); + if let Some((input, journal)) = before { + debug_assert!(&input == frame_input, "a declared observer rewrote a frame's inputs"); + assert_journal_unwritten(journal, context, "frame_start"); + } + answer + } + + #[inline] + fn frame_end( + &mut self, + context: &mut CTX, + frame_input: &FrameInput, + frame_result: &mut FrameResult, + ) { + let before = result_snapshot(frame_result); + let journal = journal_snapshot(context); + self.0.frame_end(context, frame_input, frame_result); + assert_result_unwritten(before, frame_result, "frame_end"); + assert_journal_unwritten(journal, context, "frame_end"); + } + + #[inline] + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.call(context, inputs); + debug_assert!(answer.is_none(), "a declared observer answered a call"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a declared observer rewrote a call's inputs"); + } + assert_journal_unwritten(journal, context, "call"); + answer + } + + #[inline] + fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.call_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a declared observer rewrote a call result"); + } + assert_journal_unwritten(journal, context, "call_end"); + } + + #[inline] + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.create(context, inputs); + debug_assert!(answer.is_none(), "a declared observer answered a creation"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a declared observer rewrote a creation's inputs"); + } + assert_journal_unwritten(journal, context, "create"); + answer + } + + #[inline] + fn create_end( + &mut self, + context: &mut CTX, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.create_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a declared observer rewrote a creation result"); + } + assert_journal_unwritten(journal, context, "create_end"); + } + + #[inline] + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.0.selfdestruct(contract, target, value); + } +} + +/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. +type JournalSnapshot = Option<(usize, usize)>; + +#[inline] +fn journal_snapshot>(context: &CTX) -> JournalSnapshot { + cfg!(debug_assertions) + .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) +} + +#[inline] +fn assert_journal_unwritten>( + before: JournalSnapshot, + context: &CTX, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + journal_snapshot(context).expect("debug build"), + "a declared observer wrote to the journal in `{callback}`" + ); + } +} + +/// An interpreter's and the journal's state, for the debug-build proof. +type Snapshot = (GasSnapshot, JournalSnapshot); + +#[inline] +fn snapshot>( + interp: &Interpreter, + context: &CTX, +) -> Snapshot { + (gas_snapshot(interp), journal_snapshot(context)) +} + +#[inline] +fn assert_unwritten>( + (gas, journal): Snapshot, + interp: &Interpreter, + context: &CTX, + callback: &str, +) { + assert_gas_unwritten(gas, interp, callback); + assert_journal_unwritten(journal, context, callback); +} + +/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. +/// `None` in release builds. +type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; + +#[inline] +fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { + use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; + cfg!(debug_assertions) + .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) +} + +#[inline] +fn assert_gas_unwritten( + before: GasSnapshot, + interp: &Interpreter, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + gas_snapshot(interp).expect("debug build"), + "a declared observer wrote to the interpreter in `{callback}`" + ); + } +} + +/// A frame result's classification, gas and output, and a creation's address, for the +/// debug-build proof. +type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; + +#[inline] +fn result_snapshot(result: &FrameResult) -> ResultSnapshot { + cfg!(debug_assertions).then(|| { + let address = match result { + FrameResult::Call(_) => None, + FrameResult::Create(outcome) => outcome.address, + }; + (result.interpreter_result().clone(), address) + }) +} + +#[inline] +fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { + if let Some(before) = before { + debug_assert!( + before == result_snapshot(result).expect("debug build"), + "a declared observer rewrote a frame result in `{callback}`" + ); + } +} + +/// Hands a frame's end to the inspector, then applies the one refusal: a creation that failed, +/// rewritten into a success, is put back and fails the transaction with +/// [`FORBIDDEN_CREATE_REVIVAL`]. +/// +/// Every place a frame result reaches the inspector goes through here, so the refusal covers a +/// result a frame ran to produce and one answered without running. A frame the inspector answered +/// with a success itself is no revival: nothing failed. +#[inline] +pub(crate) fn frame_end_checked( + context: &mut CTX, + inspector: &mut INSP, + frame_input: &FrameInput, + frame_result: &mut FrameResult, +) where + CTX: ContextTr, + INTR: InterpreterTypes, + INSP: Inspector, +{ + let before = frame_result.instruction_result(); + frame_end(context, inspector, frame_input, frame_result); + refuse_create_revival(context, before, frame_result); +} + +/// Puts a revived creation back to `before` and records the refusal as the context's error. +fn refuse_create_revival( + context: &mut CTX, + before: InstructionResult, + result: &mut FrameResult, +) { + let FrameResult::Create(outcome) = result else { return }; + if before.is_ok() || !outcome.result.result.is_ok() { + return; + } + outcome.result.result = before; + if context.error().is_ok() { + let message: String = format!("{FORBIDDEN_CREATE_REVIVAL}: {before:?}"); + *context.error() = Err(ContextError::Custom(message)); + } +} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index f92675325..acb82a35c 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,2385 +1,146 @@ -use core::cmp::min; +//! The instruction table of the Satin engine. +//! +//! Every opcode runs revm's own instruction, except the three that write state the resource +//! limits count: `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT`. Each of those runs in a wrapper +//! that commits what the Host staged for it after the opcode completed: +//! +//! 1. discard any record staged before the opcode (nothing may commit it for this one); +//! 2. run revm's instruction, whose Host call stages the record; +//! 3. commit the record if the opcode completed, discard it if the opcode failed. +//! +//! A commit that crosses a limit stops the opcode's frame with a revert whose output is +//! [`MegaLimitExceeded`](crate::MegaLimitExceeded) (see +//! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). +//! +//! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is +//! unchanged. -use crate::{ - constants::{self}, - ExternalEnvTypes, HostExt, JournalInspectTr, MegaContext, MegaSpecId, -}; -use alloy_evm::Database; -use alloy_primitives::{keccak256, Bytes, U256}; use revm::{ - context::ContextTr, - handler::instructions::{EthInstructions, InstructionProvider}, + bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, + handler::instructions::EthInstructions, interpreter::{ - as_usize_or_fail, as_usize_or_fail_ret, gas, gas_or_fail, - instructions::{self, control, utility::IntoAddress}, - interpreter::EthInterpreter, - interpreter_types::{InputsTr, LoopControl, MemoryTr, RuntimeFlag}, - resize_memory, CallScheme, FrameInput, Instruction, InstructionContext, InstructionResult, - InstructionTable, InterpreterAction, InterpreterTypes, SStoreResult, Stack, + instructions::host, interpreter::EthInterpreter, interpreter_types::LoopControl, + Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, + InterpreterAction, }, - primitives::KECCAK_EMPTY, + primitives::hardfork::SpecId, + Database, }; -/// `MegaInstructions` is the instruction table for `MegaETH`. -/// -/// This instruction table implements a multi-dimensional gas model and customizes certain opcodes -/// for `MegaETH` specifications: -/// -/// # Multi-Dimensional Gas Model -/// -/// All instructions track gas usage across multiple dimensions: -/// - **Compute Gas**: Standard EVM operation costs (arithmetic, control flow, memory, etc.) -/// - **Storage Gas**: Dynamic costs for persistent storage operations (SSTORE, CREATE, CALL with -/// transfer) -/// - **Log Storage Gas**: Additional costs for persisting event logs (10x standard costs) -/// -/// This separation allows for independent pricing and limiting of different resource types. -/// -/// # Customized Opcodes -/// -/// ## LOG Opcodes (LOG0-LOG4) -/// - Compute gas: Standard EVM costs (375 + 375×topics + `8×data_bytes`) -/// - Storage gas: 10x multiplier (3,750×topics + `80×data_bytes`) -/// - Data limit enforcement: Halts when total transaction data exceeds 3.125 MB -/// -/// ## SELFDESTRUCT Opcode -/// - Disabled in Mini-Rex, Rex, and Rex1 specs -/// - Re-enabled in Rex2 with EIP-6780 semantics -/// - When disabled, halts with `InvalidFEOpcode` to prevent contract destruction -/// -/// ## SSTORE Opcode -/// - Compute gas: Standard EIP-2200/EIP-2929 costs -/// - Storage gas: Dynamic bucket-based costs only when setting zero → non-zero -/// - Data/KV limit enforcement: Tracks 40 bytes + 1 KV update per storage slot modification -/// -/// ## CREATE/CREATE2 Opcodes -/// - Compute gas: Standard costs (32,000 for CREATE, 6 gas/word for CREATE2 hashing) -/// - Storage gas: Dynamic bucket-based costs for new account creation -/// - Gas forwarding: 98/100 rule (2% withheld vs. standard 1.5%) -/// - Data/KV tracking: 40 bytes + 1 KV update per account creation -/// -/// ## CALL-like Opcode -/// - Compute gas: Standard call costs -/// - Storage gas: Dynamic bucket-based costs for new account creation (when transferring to empty -/// account) -/// - REX4+: Value-transferring `CALL`/`CALLCODE` receives additional `STORAGE_CALL_STIPEND` for -/// storage-gas-heavy operations such as `LOG` -/// - REX4+: Compute gas remains capped at the original `forwarded_gas + CALL_STIPEND`, so the extra -/// stipend cannot be used for pure computation -/// - Gas forwarding: 98/100 rule (2% withheld vs. standard 1.5%) -/// - Oracle detection: Handled at frame level (in `frame_init`), applies gas detention for both -/// direct transaction calls and internal CALL operations -/// - Data/KV tracking: 40 bytes + 2 KV updates when transferring to empty account -/// -/// ## Volatile Data Access Opcodes -/// Block environment opcodes (TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE, -/// BLOCKHASH, BLOBBASEFEE, BLOBHASH) and beneficiary-accessing opcodes (BALANCE, EXTCODESIZE, -/// EXTCODECOPY, EXTCODEHASH) implement immediate gas detention to prevent `DoS` attacks. -/// -/// # Gas Detention Mechanism -/// -/// When volatile data (block environment, beneficiary, or oracle) is accessed, the system -/// implements a gas detention mechanism: -/// 1. The compute gas limit is lowered based on the type of volatile data: -/// - Block environment or beneficiary: `BLOCK_ENV_ACCESS_COMPUTE_GAS` (20M gas) -/// - Oracle contract: `ORACLE_ACCESS_COMPUTE_GAS` (1M gas pre-Rex3, 20M gas Rex3+) -/// -/// In pre-REX4, this is an **absolute** cap on total compute gas. -/// In REX4+, this is a **relative** cap: `usage_at_access + cap`. -/// 2. Most restrictive limit wins: If multiple volatile data types are accessed, the minimum (most -/// restrictive) effective limit applies, regardless of access order -/// 3. Detained gas is tracked and refunded at transaction end -/// 4. Users only pay for actual work performed, not for enforcement gas -/// 5. This prevents `DoS` attacks while maintaining fair gas accounting -/// -/// # Instruction Layering Architecture -/// -/// ## Extension Modules (Inner → Outer) -/// -/// Each opcode handler is composed of one or more extension module wrappers, applied from -/// innermost (closest to revm) to outermost: -/// -/// 1. **`compute_gas_ext`** — Tracks compute gas usage for every opcode. Wraps the raw revm -/// instruction and records how much gas was consumed. -/// 2. **`storage_gas_ext`** — Adds dynamic storage gas costs (SSTORE, CALL with value transfer, -/// CREATE, LOG). Wraps `compute_gas_ext` handlers. -/// 3. **`additional_limit_ext`** — Enforces multidimensional resource limits (data size, KV -/// updates). Wraps `storage_gas_ext` handlers. -/// 4. **`forward_gas_ext`** — Enforces the 98/100 gas forwarding rule for CALL-like and CREATE -/// opcodes. Wraps `storage_gas_ext` handlers. -/// 5. **`volatile_data_ext`** — Applies gas detention on volatile data access (block env, -/// beneficiary, oracle) and pre-execution disable checks (Rex4+). Wraps `compute_gas_ext` or -/// `forward_gas_ext` handlers depending on the opcode. -/// -/// ## Spec Progression and Opcode Overrides -/// -/// Each behavior-introducing spec builds on the previous one; the alias specs have no table of -/// their own and select their behavior target's (see [`MegaInstructions::new`]). Only the -/// opcodes that change are listed: -/// -/// - **EQUIVALENCE**: Standard revm mainnet instruction table (no custom wrappers). -/// - **`MINI_REX`** (base custom table): All 256 opcodes initialized from scratch. -/// - Most opcodes: `compute_gas_ext::*` -/// - Block env opcodes (TIMESTAMP, NUMBER, etc.): `volatile_data_ext::*` -/// - BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH: `volatile_data_ext::*` -/// - SLOAD: `compute_gas_ext::sload` -/// - SSTORE: `additional_limit_ext` → `storage_gas_ext` -/// - LOG0–LOG4: `additional_limit_ext` → `storage_gas_ext` -/// - CALL: `forward_gas_ext` → `storage_gas_ext` -/// - CREATE, CREATE2: `forward_gas_ext` → `storage_gas_ext` -/// - CALLCODE, DELEGATECALL, STATICCALL: `compute_gas_ext::*` (bug: missing `forward_gas_ext`) -/// - SELFDESTRUCT: disabled (`control::invalid`) -/// - **REX / REX1** (extends `MINI_REX)`: -/// - CALLCODE: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - DELEGATECALL: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - STATICCALL: `forward_gas_ext` → `storage_gas_ext` (bugfix) -/// - **REX2** (extends REX): -/// - SELFDESTRUCT: `compute_gas_ext::selfdestruct` (re-enabled with EIP-6780) -/// - **REX3** (extends REX2): -/// - SLOAD: `volatile_data_ext::sload` → `compute_gas_ext::sload` (oracle gas detention) -/// - **REX4** (extends REX3): -/// - CALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - STATICCALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - DELEGATECALL: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - CALLCODE: `volatile_data_ext` → `forward_gas_ext` → `storage_gas_ext` -/// - **REX5** (extends REX4): -/// - SELFDESTRUCT: `volatile_data_ext::selfdestruct_with_beneficiary_guard` → -/// `storage_gas_ext::selfdestruct` (new-account storage gas, beneficiary-volatile guard -/// outermost) -/// - **REX6** (extends REX5): unifies the per-opcode gas-metering order. The table wiring is -/// unchanged. Storage-affecting handlers (SSTORE, LOG, CALL-family, CREATE/CREATE2) all follow a -/// canonical order: charge storage gas → run the raw opcode body → record compute gas exactly -/// once via `record_storage_compute_gas!` after the body completes, excluding the storage gas. -/// For SSTORE / LOG / CALL-family this is byte-equivalent to the pre-REX6 layering (nothing -/// between `gas_before` and the storage charge debits EVM gas), so `storage_gas_ext::*` records -/// compute inline on every spec — no `if REX6` branch is needed. SELFDESTRUCT keeps its -/// delegation to `compute_gas_ext::selfdestruct`, whose trailing `record_compute_gas_all_dims` -/// check records the same single compute window while latching the pre-recorded data/KV/state -/// usage. CREATE2 is the one real behavior change: REX6+ short-circuits to `create_rex6`, which -/// folds the memory-expansion gas into the single post-body recording instead of recording it as -/// a separate eager entry as REX5 did. -/// -/// Note: chains terminating at `storage_gas_ext` (rather than `compute_gas_ext`) reflect the -/// canonical metering order above — `storage_gas_ext::*` records compute gas internally via -/// `record_storage_compute_gas!`, so there is no separate `compute_gas_ext` layer below it. -/// -/// # Assumptions -/// -/// This instruction table is only used when the `MINI_REX` spec (or later) is enabled, so we can -/// safely assume that all features before and including Mini-Rex are enabled. -#[derive(Clone)] -pub struct MegaInstructions { - spec: MegaSpecId, - inner: EthInstructions>, -} - -impl core::fmt::Debug for MegaInstructions { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethInstructions").field("spec", &self.spec).finish_non_exhaustive() - } -} - -impl MegaInstructions { - /// Create a new `MegaethInstructions` with the given spec id. - pub fn new(spec: MegaSpecId) -> Self { - // An alias spec is grouped with its `behavior()` target so it executes exactly the - // target's table; the grouping must agree with `behavior()`, pinned by - // `test_alias_specs_use_their_behavior_targets_table`. - let instruction_table = match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => EthInstructions::new_mainnet(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => { - EthInstructions::new(mini_rex::instruction_table::< - EthInterpreter, - MegaContext, - >()) - } - MegaSpecId::REX | MegaSpecId::REX1 => EthInstructions::new(rex::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX2 => EthInstructions::new(rex2::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX3 => EthInstructions::new(rex3::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX4 => EthInstructions::new(rex4::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX5 => EthInstructions::new(rex5::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX6 => EthInstructions::new(rex6::instruction_table::< - EthInterpreter, - MegaContext, - >()), - MegaSpecId::REX7 => EthInstructions::new(rex7::instruction_table::< - EthInterpreter, - MegaContext, - >()), - }; - Self { spec, inner: instruction_table } - } -} - -impl InstructionProvider - for MegaInstructions -{ - type Context = MegaContext; - type InterpreterTypes = EthInterpreter; - - fn instruction_table(&self) -> &InstructionTable { - self.inner.instruction_table() - } -} - -mod rex { - use super::*; - - /// Returns the instruction table for the `REX` and `REX1` specs. - /// - /// Changes from Mini-Rex (bugfix — adds missing `forward_gas_ext` wrapping): - /// - CALLCODE: `forward_gas_ext` → `storage_gas_ext` - /// - DELEGATECALL: `forward_gas_ext` → `storage_gas_ext` - /// - STATICCALL: `forward_gas_ext` → `storage_gas_ext` - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = mini_rex::instruction_table::(); - - // Mini-Rex mistakenly not modifying these three call-like opcodes. They are fixed in Rex - table[CALLCODE as usize] = forward_gas_ext::call_code; - table[DELEGATECALL as usize] = forward_gas_ext::delegate_call; - table[STATICCALL as usize] = forward_gas_ext::static_call; - - table - } -} - -mod rex2 { - use super::*; - - /// Returns the instruction table for the `REX2` spec. - /// - /// Changes from Rex: - /// - SELFDESTRUCT: `compute_gas_ext::selfdestruct` (re-enabled with EIP-6780 semantics) - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex::instruction_table::(); - - table[SELFDESTRUCT as usize] = compute_gas_ext::selfdestruct; - - table - } -} - -mod rex3 { - use super::*; - - /// Returns the instruction table for the `REX3` spec. - /// - /// Changes from Rex2: - /// - SLOAD: `volatile_data_ext::sload` → `compute_gas_ext::sload` (oracle gas detention). This - /// replaces the CALL-based oracle access detection used in earlier specs. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex2::instruction_table::(); - - // Rex3: SLOAD triggers gas detention for oracle contract access. - // The host's sload() method marks oracle access in the volatile data tracker, - // then the detain_gas_ext wrapper applies the compute gas limit. - table[SLOAD as usize] = volatile_data_ext::sload; - - table - } -} - -mod rex4 { - use super::*; - - /// Returns the instruction table for the `REX4` spec. - /// - /// Changes from Rex3: - /// - CALL: `volatile_data_ext::call` → `forward_gas_ext` → `storage_gas_ext` - /// - STATICCALL: `volatile_data_ext::static_call` → `forward_gas_ext` → `storage_gas_ext` - /// - DELEGATECALL: `volatile_data_ext::delegate_call` → `forward_gas_ext` → `storage_gas_ext` - /// - CALLCODE: `volatile_data_ext::call_code` → `forward_gas_ext` → `storage_gas_ext` - /// - SELFDESTRUCT: `volatile_data_ext::selfdestruct` → `compute_gas_ext::selfdestruct` - /// - SELFBALANCE: `volatile_data_ext::selfbalance` → `compute_gas_ext::selfbalance` - /// - /// The `volatile_data_ext` wrapper checks if the target address is the beneficiary and - /// volatile data access is disabled — if so, reverts before executing. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex3::instruction_table::(); - - // Rex4: CALL-like opcodes check for beneficiary volatile access disabled. - table[CALL as usize] = volatile_data_ext::call; - table[STATICCALL as usize] = volatile_data_ext::static_call; - table[DELEGATECALL as usize] = volatile_data_ext::delegate_call; - table[CALLCODE as usize] = volatile_data_ext::call_code; - - // Rex4: SELFDESTRUCT checks for beneficiary volatile access. - table[SELFDESTRUCT as usize] = volatile_data_ext::selfdestruct; - - // Rex4: SELFBALANCE checks for beneficiary volatile access (when the executing - // contract is the beneficiary, SELFBALANCE triggers gas detention). - table[SELFBALANCE as usize] = volatile_data_ext::selfbalance; - - table - } -} - -mod rex5 { - use super::*; - - /// Returns the instruction table for the `REX5` spec. - /// - /// Changes from Rex4: - /// - SELFDESTRUCT: `volatile_data_ext::selfdestruct_with_beneficiary_guard` → - /// `storage_gas_ext::selfdestruct`. The outer wrapper keeps the beneficiary-volatile guard - /// outermost (matching the SSTORE / LOG layering) and slots the new-account storage-gas - /// charge between the guard and the inner opcode, so disabled-volatile frames short-circuit - /// ahead of any storage-layer side effects (account inspection, dynamic gas charge, - /// `on_selfdestruct_new_account` record). - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - use revm::bytecode::opcode::*; - let mut table = rex4::instruction_table::(); - - // REX5: SELFDESTRUCT charges storage gas for new beneficiary accounts, - // gated behind the beneficiary-volatile guard. - table[SELFDESTRUCT as usize] = volatile_data_ext::selfdestruct_with_beneficiary_guard; - - table - } -} - -mod rex6 { - use super::*; - - /// Returns the instruction table for the `REX6` spec. - /// - /// Changes from Rex5: the instruction *table* is unchanged (same handler functions as Rex5). - /// Every Rex6 behavior difference is expressed as internal `spec.is_enabled(MegaSpecId::REX6)` - /// dispatch inside the shared handlers, never as a swapped table entry: - /// - the storage-affecting handlers (SSTORE, LOG, CALL-family, CREATE/CREATE2) charge storage - /// gas, run their body, then record compute gas exactly once (via - /// [`record_storage_compute_gas!`]) with the storage gas excluded; SELFDESTRUCT keeps its - /// delegation to `compute_gas_ext::selfdestruct`, whose trailing all-dimension check records - /// the same single compute window while latching the pre-recorded data/KV/state usage; - /// - `storage_gas_ext::selfdestruct` additionally records existing-target balance-update - /// accounting, and its outer volatile wrapper - /// (`volatile_data_ext::selfdestruct_with_beneficiary_guard`) additionally guards the - /// executing contract (source) against the beneficiary; - /// - the CALL-family volatile wrappers, on the `disableVolatileDataAccess` path, resolve the - /// stack target's one-hop EIP-7702 delegate before the beneficiary comparison. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - rex5::instruction_table::() - } -} - -mod rex7 { - use super::*; - - /// Returns the instruction table for the `REX7` spec. - /// - /// Changes from Rex6: none yet. - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] - where - WIRE::Stack: StackInspectTr, - { - rex6::instruction_table::() - } -} - -/// Macro to record compute gas and check if the limit has been exceeded. If the limit is exceeded, -/// the interpreter halts and returns. -macro_rules! compute_gas { - ($interpreter:expr, $additional_limit:expr, $gas_used:expr $(,$ret:expr)?) => { - if !$additional_limit.record_compute_gas($gas_used) { - $interpreter.halt($additional_limit.exceeding_instruction_result()); - return $($ret)?; - } - }; -} - -/// Macro to run the inner instruction and abort if the instruction result is an error. -macro_rules! run_inner_instruction_or_abort { - ($inner_fn:path, $context:expr) => { - let ctx = InstructionContext::<'_, H, WIRE> { - interpreter: &mut *$context.interpreter, - host: &mut *$context.host, - }; - $inner_fn(ctx); - if $context - .interpreter - .bytecode - .instruction_result() - .is_some_and(|result| result.is_error()) - { - return; - } +use crate::{ExternalEnvTypes, LimitCheck, MegaContext}; + +use super::MegaInstructions; + +/// The context an instruction of the Satin engine runs with. +type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; + +/// An instruction of the Satin engine. +type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; + +/// The Satin instruction table: revm's for the base spec, with `SSTORE`, `LOG0`..`LOG4` and +/// `SELFDESTRUCT` wrapped. +pub(crate) fn mega_instructions( + spec: SpecId, +) -> MegaInstructions { + let mut instructions = EthInstructions::new_mainnet_with_spec(spec); + let wrappers: [(u8, InstructionFn); 7] = [ + (SSTORE, sstore::), + (LOG0, log::<0, DB, ExtEnvs>), + (LOG1, log::<1, DB, ExtEnvs>), + (LOG2, log::<2, DB, ExtEnvs>), + (LOG3, log::<3, DB, ExtEnvs>), + (LOG4, log::<4, DB, ExtEnvs>), + (SELFDESTRUCT, selfdestruct::), + ]; + for (opcode, wrapper) in wrappers { + let static_gas = instructions.gas_table()[opcode as usize]; + instructions.insert_instruction(opcode, Instruction::new(wrapper), static_gas); + } + instructions +} + +/// Runs `inner` and commits the record its Host call staged once it completed. +/// +/// An opcode completes when it returns `Ok` or stops the frame successfully (`SELFDESTRUCT` +/// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the +/// staged write back with it. +#[inline(always)] +fn commit_after( + context: Ctx<'_, DB, ExtEnvs>, + inner: InstructionFn, +) -> InstructionExecResult { + let InstructionContext { interpreter, host } = context; + host.additional_limit.discard_stale_record(); + let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + let completed = match result { + Ok(()) => true, + Err(result) => result.is_ok(), }; -} - -/// Records an opcode's compute gas in a single measurement window and enforces the compute-gas -/// limit. The REX6 storage-affecting handlers invoke it directly with the storage gas they -/// charged; plain opcodes use the leaner inline recording in -/// `compute_gas_ext::wrap_op_compute_gas`, which implements the same forwarded-gas exclusion -/// without the REX6 abort-path handling (unreachable from those wrappers). -/// -/// `$gas_before` MUST be the interpreter gas remaining captured at the very top of the handler, -/// before any storage-gas charge or wrapper-side EVM-gas work (e.g. CREATE2 memory expansion), so -/// the single measurement window covers all of the opcode's compute work. The recorded amount is -/// `($gas_before − gas_after) − $storage_charged − forwarded_child_gas`: the storage gas charged -/// inside the window is subtracted back out, and gas forwarded to a child frame is excluded (the -/// child records its own compute gas). The forwarded-gas exclusion is spec-aware — REX5+ excludes -/// the revm-side `CALL_STIPEND`, pre-REX5 does not — so the result is identical to the pre-existing -/// inline recording on every spec. -/// -/// Because nothing consumes EVM gas before the storage charge for the non-CREATE2 opcodes, the REX6 -/// storage handlers record the same compute gas, at the same point, as the pre-REX6 layering; -/// CREATE2 differs only by folding its memory-expansion gas into this single window instead of -/// recording it separately. -/// -/// On exceeding the compute-gas limit, halts the interpreter and returns from the enclosing -/// instruction handler. The early return mirrors [`compute_gas!`] so a trailing statement after -/// this macro (e.g. the pre-REX5 `resize_gas` late-record in `storage_gas_ext::create`) is only -/// reached on the non-halt path; without the return, a halt here would let a later `compute_gas!` -/// add gas to the tracker after the OOG was already set. -macro_rules! record_storage_compute_gas { - ($context:expr, $gas_before:expr, $storage_charged:expr) => {{ - let gas_after = $context.interpreter.gas.remaining(); - let mut gas_used = $gas_before.saturating_sub(gas_after).saturating_sub($storage_charged); - // Exclude gas forwarded to a child frame. REX5+ excludes the revm-side `CALL_STIPEND` - // (added by value-transferring CALL/CALLCODE without deducting from the parent) so the - // parent's compute gas is not under-counted; pre-REX5 subtracts the full child gas limit - // for replay parity. `forwarded_child_gas` records that deducted amount so the abort path - // below can return it to the parent. - let mut forwarded_child_gas: u64 = 0; - match $context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - let stipend_from_revm = if $context.host.spec_id().is_enabled(MegaSpecId::REX5) && - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode) && - call_inputs.transfers_value() - { - gas::CALL_STIPEND - } else { - 0 - }; - let parent_contributed = call_inputs.gas_limit.saturating_sub(stipend_from_revm); - forwarded_child_gas = parent_contributed; - gas_used = gas_used.saturating_sub(parent_contributed); - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - forwarded_child_gas = create_inputs.gas_limit; - gas_used = gas_used.saturating_sub(create_inputs.gas_limit); - } - _ => {} - } - // On a compute-limit halt the pending child `NewFrame` is discarded (the child never runs), - // but revm already deducted the forwarded gas and the outer `forward_gas_ext` erase is - // skipped on this abort path. REX6+: return that gas to the parent before halting. - let is_rex6 = $context.host.spec_id().is_enabled(MegaSpecId::REX6); - let exceeding_result = { - let mut additional_limit = $context.host.additional_limit().borrow_mut(); - if additional_limit.record_compute_gas(gas_used) { - None - } else { - Some(additional_limit.exceeding_instruction_result()) - } - }; - if let Some(result) = exceeding_result { - if is_rex6 { - $context.interpreter.gas.erase_cost(forwarded_child_gas); - } - $context.interpreter.halt(result); - return; - } - }}; -} - -mod mini_rex { - use super::*; - - /// Returns the instruction table for the `MINI_REX` spec. - /// - /// This is the base custom table — all 256 opcodes are initialized from scratch with - /// compute gas tracking. Key opcode layering: - /// - Most opcodes: `compute_gas_ext::*` (compute gas tracking only) - /// - Block env opcodes: `volatile_data_ext::*` (gas detention) - /// - BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH: `volatile_data_ext::*` (conditional) - /// - SSTORE: `additional_limit_ext` → `storage_gas_ext` - /// - LOG0–LOG4: `additional_limit_ext` → `storage_gas_ext` - /// - CALL: `forward_gas_ext` → `storage_gas_ext` - /// - CREATE, CREATE2: `forward_gas_ext` → `storage_gas_ext` - /// - CALLCODE, DELEGATECALL, STATICCALL: `compute_gas_ext::*` (bug: missing `forward_gas_ext`) - /// - SELFDESTRUCT: disabled (`control::invalid`) - pub(super) const fn instruction_table< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >() -> [Instruction; 256] { - use revm::bytecode::opcode::*; - let mut table = [control::unknown as Instruction; 256]; - - table[STOP as usize] = compute_gas_ext::stop; - table[ADD as usize] = compute_gas_ext::add; - table[MUL as usize] = compute_gas_ext::mul; - table[SUB as usize] = compute_gas_ext::sub; - table[DIV as usize] = compute_gas_ext::div; - table[SDIV as usize] = compute_gas_ext::sdiv; - table[MOD as usize] = compute_gas_ext::rem; - table[SMOD as usize] = compute_gas_ext::smod; - table[ADDMOD as usize] = compute_gas_ext::addmod; - table[MULMOD as usize] = compute_gas_ext::mulmod; - table[EXP as usize] = compute_gas_ext::exp; - table[SIGNEXTEND as usize] = compute_gas_ext::signextend; - - table[LT as usize] = compute_gas_ext::lt; - table[GT as usize] = compute_gas_ext::gt; - table[SLT as usize] = compute_gas_ext::slt; - table[SGT as usize] = compute_gas_ext::sgt; - table[EQ as usize] = compute_gas_ext::eq; - table[ISZERO as usize] = compute_gas_ext::iszero; - table[AND as usize] = compute_gas_ext::bitand; - table[OR as usize] = compute_gas_ext::bitor; - table[XOR as usize] = compute_gas_ext::bitxor; - table[NOT as usize] = compute_gas_ext::not; - table[BYTE as usize] = compute_gas_ext::byte; - table[SHL as usize] = compute_gas_ext::shl; - table[SHR as usize] = compute_gas_ext::shr; - table[SAR as usize] = compute_gas_ext::sar; - table[CLZ as usize] = compute_gas_ext::clz; - - table[KECCAK256 as usize] = compute_gas_ext::keccak256; - - table[ADDRESS as usize] = compute_gas_ext::address; - table[BALANCE as usize] = volatile_data_ext::balance; - table[ORIGIN as usize] = compute_gas_ext::origin; - table[CALLER as usize] = compute_gas_ext::caller; - table[CALLVALUE as usize] = compute_gas_ext::callvalue; - table[CALLDATALOAD as usize] = compute_gas_ext::calldataload; - table[CALLDATASIZE as usize] = compute_gas_ext::calldatasize; - table[CALLDATACOPY as usize] = compute_gas_ext::calldatacopy; - table[CODESIZE as usize] = compute_gas_ext::codesize; - table[CODECOPY as usize] = compute_gas_ext::codecopy; - - table[GASPRICE as usize] = compute_gas_ext::gasprice; - table[EXTCODESIZE as usize] = volatile_data_ext::extcodesize; - table[EXTCODECOPY as usize] = volatile_data_ext::extcodecopy; - table[EXTCODEHASH as usize] = volatile_data_ext::extcodehash; - table[RETURNDATASIZE as usize] = compute_gas_ext::returndatasize; - table[RETURNDATACOPY as usize] = compute_gas_ext::returndatacopy; - table[BLOCKHASH as usize] = volatile_data_ext::blockhash; - table[COINBASE as usize] = volatile_data_ext::coinbase; - table[TIMESTAMP as usize] = volatile_data_ext::timestamp; - table[NUMBER as usize] = volatile_data_ext::block_number; - table[DIFFICULTY as usize] = volatile_data_ext::difficulty; - table[GASLIMIT as usize] = volatile_data_ext::gas_limit_opcode; - table[CHAINID as usize] = compute_gas_ext::chainid; - table[SELFBALANCE as usize] = compute_gas_ext::selfbalance; - table[BASEFEE as usize] = volatile_data_ext::basefee; - table[BLOBBASEFEE as usize] = volatile_data_ext::blobbasefee; - table[BLOBHASH as usize] = volatile_data_ext::blobhash; - - table[POP as usize] = compute_gas_ext::pop; - table[MLOAD as usize] = compute_gas_ext::mload; - table[MSTORE as usize] = compute_gas_ext::mstore; - table[MSTORE8 as usize] = compute_gas_ext::mstore8; - table[SLOAD as usize] = compute_gas_ext::sload; - table[SSTORE as usize] = additional_limit_ext::sstore; - table[JUMP as usize] = compute_gas_ext::jump; - table[JUMPI as usize] = compute_gas_ext::jumpi; - table[PC as usize] = compute_gas_ext::pc; - table[MSIZE as usize] = compute_gas_ext::msize; - table[GAS as usize] = compute_gas_ext::gas; - table[JUMPDEST as usize] = compute_gas_ext::jumpdest; - table[TLOAD as usize] = compute_gas_ext::tload; - table[TSTORE as usize] = compute_gas_ext::tstore; - table[MCOPY as usize] = compute_gas_ext::mcopy; - - table[PUSH0 as usize] = compute_gas_ext::push0; - table[PUSH1 as usize] = compute_gas_ext::push1; - table[PUSH2 as usize] = compute_gas_ext::push2; - table[PUSH3 as usize] = compute_gas_ext::push3; - table[PUSH4 as usize] = compute_gas_ext::push4; - table[PUSH5 as usize] = compute_gas_ext::push5; - table[PUSH6 as usize] = compute_gas_ext::push6; - table[PUSH7 as usize] = compute_gas_ext::push7; - table[PUSH8 as usize] = compute_gas_ext::push8; - table[PUSH9 as usize] = compute_gas_ext::push9; - table[PUSH10 as usize] = compute_gas_ext::push10; - table[PUSH11 as usize] = compute_gas_ext::push11; - table[PUSH12 as usize] = compute_gas_ext::push12; - table[PUSH13 as usize] = compute_gas_ext::push13; - table[PUSH14 as usize] = compute_gas_ext::push14; - table[PUSH15 as usize] = compute_gas_ext::push15; - table[PUSH16 as usize] = compute_gas_ext::push16; - table[PUSH17 as usize] = compute_gas_ext::push17; - table[PUSH18 as usize] = compute_gas_ext::push18; - table[PUSH19 as usize] = compute_gas_ext::push19; - table[PUSH20 as usize] = compute_gas_ext::push20; - table[PUSH21 as usize] = compute_gas_ext::push21; - table[PUSH22 as usize] = compute_gas_ext::push22; - table[PUSH23 as usize] = compute_gas_ext::push23; - table[PUSH24 as usize] = compute_gas_ext::push24; - table[PUSH25 as usize] = compute_gas_ext::push25; - table[PUSH26 as usize] = compute_gas_ext::push26; - table[PUSH27 as usize] = compute_gas_ext::push27; - table[PUSH28 as usize] = compute_gas_ext::push28; - table[PUSH29 as usize] = compute_gas_ext::push29; - table[PUSH30 as usize] = compute_gas_ext::push30; - table[PUSH31 as usize] = compute_gas_ext::push31; - table[PUSH32 as usize] = compute_gas_ext::push32; - - table[DUP1 as usize] = compute_gas_ext::dup1; - table[DUP2 as usize] = compute_gas_ext::dup2; - table[DUP3 as usize] = compute_gas_ext::dup3; - table[DUP4 as usize] = compute_gas_ext::dup4; - table[DUP5 as usize] = compute_gas_ext::dup5; - table[DUP6 as usize] = compute_gas_ext::dup6; - table[DUP7 as usize] = compute_gas_ext::dup7; - table[DUP8 as usize] = compute_gas_ext::dup8; - table[DUP9 as usize] = compute_gas_ext::dup9; - table[DUP10 as usize] = compute_gas_ext::dup10; - table[DUP11 as usize] = compute_gas_ext::dup11; - table[DUP12 as usize] = compute_gas_ext::dup12; - table[DUP13 as usize] = compute_gas_ext::dup13; - table[DUP14 as usize] = compute_gas_ext::dup14; - table[DUP15 as usize] = compute_gas_ext::dup15; - table[DUP16 as usize] = compute_gas_ext::dup16; - - table[SWAP1 as usize] = compute_gas_ext::swap1; - table[SWAP2 as usize] = compute_gas_ext::swap2; - table[SWAP3 as usize] = compute_gas_ext::swap3; - table[SWAP4 as usize] = compute_gas_ext::swap4; - table[SWAP5 as usize] = compute_gas_ext::swap5; - table[SWAP6 as usize] = compute_gas_ext::swap6; - table[SWAP7 as usize] = compute_gas_ext::swap7; - table[SWAP8 as usize] = compute_gas_ext::swap8; - table[SWAP9 as usize] = compute_gas_ext::swap9; - table[SWAP10 as usize] = compute_gas_ext::swap10; - table[SWAP11 as usize] = compute_gas_ext::swap11; - table[SWAP12 as usize] = compute_gas_ext::swap12; - table[SWAP13 as usize] = compute_gas_ext::swap13; - table[SWAP14 as usize] = compute_gas_ext::swap14; - table[SWAP15 as usize] = compute_gas_ext::swap15; - table[SWAP16 as usize] = compute_gas_ext::swap16; - - table[LOG0 as usize] = additional_limit_ext::log::<0, _, _>; - table[LOG1 as usize] = additional_limit_ext::log::<1, _, _>; - table[LOG2 as usize] = additional_limit_ext::log::<2, _, _>; - table[LOG3 as usize] = additional_limit_ext::log::<3, _, _>; - table[LOG4 as usize] = additional_limit_ext::log::<4, _, _>; - - table[CREATE as usize] = forward_gas_ext::create; - table[CREATE2 as usize] = forward_gas_ext::create2; - table[CALL as usize] = forward_gas_ext::call; - table[CALLCODE as usize] = compute_gas_ext::call_code; - table[DELEGATECALL as usize] = compute_gas_ext::delegate_call; - table[STATICCALL as usize] = compute_gas_ext::static_call; - - table[INVALID as usize] = compute_gas_ext::invalid; - table[RETURN as usize] = compute_gas_ext::ret; - table[REVERT as usize] = compute_gas_ext::revert; - table[SELFDESTRUCT as usize] = control::invalid; - - table - } -} - -/// Call-like and create-like opcode handlers with 98/100 gas forwarding rule. -/// -/// This module provides wrapper implementations for CALL, CALLCODE, DELEGATECALL, STATICCALL, -/// CREATE, and CREATE2 opcodes that enforce the 98/100 gas forwarding rule (retaining 2% of -/// remaining gas in the parent call instead of the standard 1/64). -/// -/// The wrappers: -/// 1. Check for value transfer (CALL and CALLCODE only) to account for call stipend -/// 2. Call the underlying opcode implementation -/// 3. Cap the forwarded gas to 98% of the parent's remaining gas -/// 4. Preserve the call stipend (2300 gas) when value is transferred (CALL/CALLCODE only) -/// 5. Support both Call and Create frame types -pub mod forward_gas_ext { - use super::*; - - /// Macro to wrap call-like and create-like opcodes with 98/100 gas forwarding rule. - /// - /// This macro generates a wrapper function that: - /// 1. Optionally checks for value transfer (`has_transfer`) for CALL opcode - /// 2. Calls the wrapped opcode handler - /// 3. Caps the forwarded gas to 98/100 of the remaining gas - /// 4. Adjusts for call stipend if value is being transferred - /// 5. Supports both Call and Create frame types - /// - /// # Parameters - /// - `$fn_name`: Name of the generated function - /// - `$opcode_name`: String name of the opcode (for documentation) - /// - `$wrapped_fn`: Path to the wrapped instruction implementation - /// - `$has_transfer_logic`: Expression to determine if value is being transferred (e.g., - /// `has_transfer` or `false`) - macro_rules! wrap_gas_cap { - ($fn_name:ident, $opcode_name:expr, $wrapped_fn:path, $has_transfer_logic:expr) => { - #[doc = concat!("`", $opcode_name, "` opcode with 98/100 gas forwarding rule.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Determine if there's a value transfer (only applies to CALL opcode). - let has_transfer = $has_transfer_logic(&context); - - // Call the wrapped opcode handler. - run_inner_instruction_or_abort!($wrapped_fn, context); - - // Cap the forwarded gas to the child call/create to the 98/100 of the remaining - // gas. - match context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - // The forwarded gas to the child call should be further restricted to the - // 98/100 of the remaining gas. Here, we first recover the total - // gas left in the parent call and then cap the child call gas - // limit if necessary. - - // We recover the forwarded gas to the child call from the parent call. - let child_gas = call_inputs.gas_limit as u128; - // There may be a call stipend if there is value to be transferred. - let transfer_gas_stipend = - if has_transfer { gas::CALL_STIPEND as u128 } else { 0 }; - let forwarded_gas = child_gas - transfer_gas_stipend; // Safe from underflow - - // Recover the remaining gas in the parent call before forwarding to the - // child call. - let parent_original_gas_left = - context.interpreter.gas.remaining() as u128 + forwarded_gas; - - // Calculate the amount of gas that should be returned to the parent call - // under the 98/100 rule. - let forwarded_gas_cap = - parent_original_gas_left - parent_original_gas_left * 2 / 100; - let capped_forwarded_gas = min(forwarded_gas, forwarded_gas_cap); - let gas_to_return = forwarded_gas - capped_forwarded_gas; // Safe from underflow - - // Recalculate the child gas - let new_child_gas = capped_forwarded_gas + transfer_gas_stipend; - - // Return the gas to the parent call. - context.interpreter.gas.erase_cost(gas_to_return as u64); - - // Set the child call gas limit to the capped value. - // Note: REX4+ STORAGE_CALL_STIPEND is applied later in - // AdditionalLimit::before_frame_init, which owns the full - // stipend lifecycle (grant → compute cap → burn on return). - call_inputs.gas_limit = new_child_gas as u64; - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - // The forwarded gas to the child create should be further restricted to the - // 98/100 of the remaining gas. CREATE opcodes don't have a call - // stipend, so the logic is simpler. - - // We recover the forwarded gas from the parent call. - let child_gas = create_inputs.gas_limit as u128; - let forwarded_gas = child_gas; // No stipend for CREATE - - // Recover the remaining gas in the parent call before forwarding to the - // child create. - let parent_original_gas_left = - context.interpreter.gas.remaining() as u128 + forwarded_gas; - - // Calculate the amount of gas that should be returned to the parent call - // under the 98/100 rule. - let forwarded_gas_cap = - parent_original_gas_left - parent_original_gas_left * 2 / 100; - let capped_forwarded_gas = min(forwarded_gas, forwarded_gas_cap); - let gas_to_return = forwarded_gas - capped_forwarded_gas; // Safe from underflow - - // Return the gas to the parent call. - context.interpreter.gas.erase_cost(gas_to_return as u64); - - // Set the child create gas limit to the capped value. - create_inputs.gas_limit = capped_forwarded_gas as u64; - } - _ => {} - } - } - }; + if !completed { + host.additional_limit.discard_staged_record(); + return result; } - - // Helper function to check if CALL has value transfer - #[inline] - fn check_call_has_transfer< - WIRE: InterpreterTypes, - H: HostExt + ?Sized, - >( - context: &InstructionContext<'_, H, WIRE>, - ) -> bool { - if let Some(value) = context.interpreter.stack.inspect::<2>() { - !value.is_zero() - } else { - false - } + let check = host.additional_limit.commit_staged_record(); + if check.exceeded_limit() { + return Err(stop_frame(interpreter, &check)); } - - // Helper function for opcodes without value transfer - #[inline] - fn no_transfer, H: HostExt + ?Sized>( - _context: &InstructionContext<'_, H, WIRE>, - ) -> bool { - false - } - - wrap_gas_cap!(call, "CALL", storage_gas_ext::call, check_call_has_transfer); - wrap_gas_cap!(call_code, "CALLCODE", storage_gas_ext::call_code, check_call_has_transfer); - wrap_gas_cap!(delegate_call, "DELEGATECALL", storage_gas_ext::delegate_call, no_transfer); - wrap_gas_cap!(static_call, "STATICCALL", storage_gas_ext::static_call, no_transfer); - wrap_gas_cap!(create, "CREATE", storage_gas_ext::create::, no_transfer); - wrap_gas_cap!(create2, "CREATE2", storage_gas_ext::create::, no_transfer); + result } -/** Volatile data access opcode handlers with compute gas limit enforcement. - -These custom instruction handlers override opcodes that access volatile data (block environment, -beneficiary account data, oracle contract) to lower the compute gas limit. -This prevents `DoS` attacks while allowing storage operations to continue with full transaction gas. - -# Compute Gas Limit Enforcement - -When volatile data is accessed: -1. The opcode executes normally (calls host method, processes data) -2. If this is the first volatile data access in the transaction: - - The compute gas limit is lowered based on the type: - * Block environment or beneficiary: `BLOCK_ENV_ACCESS_REMAINING_GAS` (20M compute gas) - * Oracle contract: `ORACLE_ACCESS_REMAINING_GAS` (1M compute gas) -3. Most restrictive limit wins: If additional volatile data with different limit is accessed, - the minimum (most restrictive) limit is applied, regardless of access order -4. All subsequent compute operations are limited by this compute gas limit -5. Storage operations (SSTORE, account creation) continue with full transaction gas - -# Volatile Data Access Disable (Rex4+) - -When `disableVolatileDataAccess()` is active, the handlers check **before** executing the -opcode and revert immediately if the access would be volatile. -This ensures that disabled volatile accesses do not pollute the tracker's `volatile_data_accessed` -bitmap or lower the `compute_gas_limit`. - -# Two Categories of Opcodes - -## Block Environment Opcodes (Always Volatile) -These opcodes ALWAYS access volatile data and apply 20M compute gas limit: -- TIMESTAMP, NUMBER, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE, BLOCKHASH, BLOBBASEFEE, BLOBHASH - -## Account-Accessing Opcodes (Conditionally Volatile) -These opcodes only SOMETIMES access volatile data (20M compute gas limit when volatile): -- `BALANCE(beneficiary_address)` → volatile, applies 20M compute gas limit -- `BALANCE(other_address)` → not volatile, no limit -- EXTCODESIZE/EXTCODECOPY/EXTCODEHASH → same conditional behavior - -For conditional opcodes, the instruction handler peeks the target address from the stack before -executing the opcode to determine if the access would be volatile. - -## Oracle SLOAD (Rex3+) -SLOAD targeting the oracle contract is volatile and applies the oracle compute gas limit. -The target address comes from `interpreter.input.target_address()` (not from the stack). -*/ -pub mod volatile_data_ext { - use super::*; - - use alloy_primitives::Address; - - use crate::{ - volatile_data_access_disabled_revert_data, VolatileDataAccessType, ORACLE_CONTRACT_ADDRESS, - }; - - /// Applies the compute gas limit from the volatile data tracker to the additional limit. - /// - /// This is safe to call unconditionally after any instruction: `get_compute_gas_limit()` - /// returns `None` if no volatile data has been accessed in this transaction, and if a - /// prior instruction already set the limit, re-applying the same value is idempotent. - macro_rules! apply_compute_gas_limit { - ($context:expr) => { - let compute_gas_limit = - $context.host.volatile_data_tracker().borrow().get_compute_gas_limit(); - if let Some(limit) = compute_gas_limit { - $context.host.additional_limit().borrow_mut().set_compute_gas_limit(limit); - } - }; - } - - /// Macro to create opcode handlers for **unconditionally volatile** opcodes. - /// - /// These opcodes (TIMESTAMP, NUMBER, etc.) always access volatile data. - /// The handler: - /// 1. Checks if volatile data access is disabled (Rex4+) — if so, reverts immediately - /// **before** executing the opcode, avoiding any side effects on the tracker. - /// 2. Executes the original instruction. - /// 3. Applies the compute gas limit via `apply_compute_gas_limit!`. - macro_rules! wrap_op_detain_gas_unconditional { - ($fn_name:ident, $opcode_name:expr, $original_fn:path, $access_type:expr) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas limit enforcement on volatile data access.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: revert before executing if volatile data access is disabled. - if context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data($access_type), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!($original_fn, context); - apply_compute_gas_limit!(context); - } - }; - } - - /// Macro to create opcode handlers for **conditionally volatile** opcodes. - /// - /// These opcodes (BALANCE, EXTCODESIZE, EXTCODECOPY, EXTCODEHASH) are volatile only when - /// targeting the block beneficiary address. - /// The handler: - /// 1. Peeks the target address from the stack (position 0) without consuming it. - /// 2. If the target is the beneficiary and volatile access is disabled, reverts immediately - /// **before** executing the opcode. - /// 3. Otherwise executes the instruction normally and applies gas detention if volatile data - /// was accessed. - macro_rules! wrap_op_detain_gas_conditional { - ($fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas limit enforcement on volatile data access.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Peek the target address from the stack to check if it's the beneficiary. - // Rex4+: If targeting the beneficiary while volatile access is disabled, revert - // before executing the opcode to avoid polluting the tracker. - if let Some(addr_word) = context.interpreter.stack.inspect::<0>() { - let target: Address = addr_word.into_address(); - let beneficiary = context.host.beneficiary_address(); - if target == beneficiary && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - - run_inner_instruction_or_abort!($original_fn, context); - apply_compute_gas_limit!(context); - } - }; - } - - // Unconditional volatile opcodes — always access volatile data, no stack inspection needed. - wrap_op_detain_gas_unconditional!( - timestamp, - "TIMESTAMP", - compute_gas_ext::timestamp, - VolatileDataAccessType::Timestamp - ); - wrap_op_detain_gas_unconditional!( - block_number, - "NUMBER", - compute_gas_ext::number, - VolatileDataAccessType::BlockNumber - ); - wrap_op_detain_gas_unconditional!( - difficulty, - "DIFFICULTY", - compute_gas_ext::difficulty, - VolatileDataAccessType::Difficulty - ); - wrap_op_detain_gas_unconditional!( - gas_limit_opcode, - "GASLIMIT", - compute_gas_ext::gaslimit, - VolatileDataAccessType::GasLimit - ); - wrap_op_detain_gas_unconditional!( - basefee, - "BASEFEE", - compute_gas_ext::basefee, - VolatileDataAccessType::BaseFee - ); - wrap_op_detain_gas_unconditional!( - coinbase, - "COINBASE", - compute_gas_ext::coinbase, - VolatileDataAccessType::Coinbase - ); - wrap_op_detain_gas_unconditional!( - blockhash, - "BLOCKHASH", - compute_gas_ext::blockhash, - VolatileDataAccessType::BlockHash - ); - wrap_op_detain_gas_unconditional!( - blobbasefee, - "BLOBBASEFEE", - compute_gas_ext::blobbasefee, - VolatileDataAccessType::BlobBaseFee - ); - wrap_op_detain_gas_unconditional!( - blobhash, - "BLOBHASH", - compute_gas_ext::blobhash, - VolatileDataAccessType::BlobHash - ); - - // Conditional volatile opcodes — volatile only when targeting the block beneficiary. - wrap_op_detain_gas_conditional!(balance, "BALANCE", compute_gas_ext::balance); - wrap_op_detain_gas_conditional!(extcodesize, "EXTCODESIZE", compute_gas_ext::extcodesize); - wrap_op_detain_gas_conditional!(extcodecopy, "EXTCODECOPY", compute_gas_ext::extcodecopy); - wrap_op_detain_gas_conditional!(extcodehash, "EXTCODEHASH", compute_gas_ext::extcodehash); - wrap_op_detain_gas_conditional!(selfdestruct, "SELFDESTRUCT", compute_gas_ext::selfdestruct); - - /// REX5+ SELFDESTRUCT outer wrapper: beneficiary volatile-access guard ahead of the - /// `storage_gas_ext::selfdestruct` layer (which under REX6 also records the existing-target - /// balance-update accounting), then the compute-gas-limit application. - /// - /// This is the conditional-volatile shape of [`wrap_op_detain_gas_conditional`] (it cannot be - /// macro-generated because of the extra REX6 source check below): when volatile access is - /// disabled and the stack target is the beneficiary, revert before any storage-layer side - /// effect. REX6 additionally guards the executing contract (the *source*, whose balance is read - /// and zeroed): REX5 inspected only the stack target, so when the source itself was the - /// beneficiary its state was still observed without `disableVolatileDataAccess` rejecting. - /// The source check is REX6-gated, leaving REX5 byte-for-byte frozen. When volatile access is - /// *enabled*, the beneficiary is already balance-marked before its own code runs (it is reached - /// as the tx recipient or a CALL target, both of which mark it), so detention engages without a - /// SELFDESTRUCT-specific hook. - #[inline] - pub fn selfdestruct_with_beneficiary_guard< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - if context.host.volatile_access_disabled() { - let beneficiary = context.host.beneficiary_address(); - // Confirm the SELFDESTRUCT has a target operand first: a stack-underflow SELFDESTRUCT - // must keep revm's `StackUnderflow` halt and not be pre-empted by a beneficiary revert. - // The guards apply only once the opcode actually acts on a target. - if let Some(addr_word) = context.interpreter.stack.inspect::<0>() { - let target: Address = addr_word.into_address(); - // REX6: the executing contract (source) reading and zeroing its own balance is - // itself a beneficiary observation. Frozen off pre-REX6, where only the stack - // target below was guarded. - if context.host.spec_id().is_enabled(MegaSpecId::REX6) && - context.interpreter.input.target_address() == beneficiary - { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - // All specs: the stack target (the value-transfer destination). - if target == beneficiary { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - } - - run_inner_instruction_or_abort!(super::storage_gas_ext::selfdestruct, context); - apply_compute_gas_limit!(context); - } - - /// `SELFBALANCE` opcode with compute gas limit enforcement on volatile data access. - /// - /// SELFBALANCE is conditionally volatile when the current contract is the beneficiary. - /// Unlike the other beneficiary-conditional opcodes (BALANCE, EXTCODESIZE, etc.), - /// the target comes from `interpreter.input.target_address()` (the executing contract), - /// not from a stack operand, so `wrap_op_detain_gas_conditional` cannot be reused. - #[inline] - pub fn selfbalance( - context: InstructionContext<'_, H, WIRE>, - ) { - let target = context.interpreter.input.target_address(); - let beneficiary = context.host.beneficiary_address(); - if target == beneficiary && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data(VolatileDataAccessType::Beneficiary), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!(compute_gas_ext::selfbalance, context); - apply_compute_gas_limit!(context); - } - - /// `SLOAD` opcode with compute gas limit enforcement on volatile data access. - /// - /// SLOAD is conditionally volatile when targeting the oracle contract. - /// Unlike the beneficiary-conditional opcodes, the target address comes from - /// `interpreter.input.target_address()` (the current contract), not from the stack. - /// - /// The handler checks if the SLOAD targets the oracle contract and volatile access is - /// disabled — if so, reverts before executing the instruction. - #[inline] - pub fn sload( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: If SLOAD targets the oracle contract and volatile access is disabled, - // revert before executing to avoid polluting the tracker. - let target = context.interpreter.input.target_address(); - if target == ORACLE_CONTRACT_ADDRESS && context.host.volatile_access_disabled() { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data(VolatileDataAccessType::Oracle), - context.interpreter.gas, - )); - return; - } - - run_inner_instruction_or_abort!(compute_gas_ext::sload, context); - apply_compute_gas_limit!(context); - } - - /// Macro to create opcode handlers for **conditionally volatile CALL-like** opcodes. - /// - /// These opcodes (CALL, STATICCALL, DELEGATECALL, CALLCODE) are volatile only when - /// targeting the block beneficiary address. - /// - /// When volatile access is disabled, the handler peeks the stack target (position 1) and - /// reverts **before** executing the opcode if the target is the beneficiary — avoiding tracker - /// pollution via `load_account_delegated`. Under REX6 it compares the target's one-hop EIP-7702 - /// delegate so a call to a delegator pointing at the beneficiary is also caught; that - /// resolution (a DB read) is gated behind the disabled check so it stays off the enabled - /// path, where the raw call proceeds and `load_account_delegated` marks the resolved - /// delegate instead. `<=` REX5 compares the raw stack operand (frozen). Otherwise it - /// delegates to the existing `forward_gas_ext` handler. - macro_rules! wrap_call_volatile_check { - ($fn_name:ident, $opcode_name:expr, $inner_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with volatile data access disabled check for beneficiary.")] - #[inline] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Rex4+: If targeting the beneficiary while volatile access is disabled, revert before - // executing the opcode to avoid polluting the tracker. Only this disabled path can - // revert and only it needs the EIP-7702 delegate resolved, so the resolve (a DB read) - // is gated behind the disabled check to keep it off the common (enabled) hot path — - // enabled-access detention is marked by `load_account_delegated` during the CALL on the - // resolved delegate. - if context.host.volatile_access_disabled() { - // Peek the target address from the stack (position 1 for CALL-like opcodes: - // stack layout is [gas_limit, to, ...]). - if let Some(addr_word) = context.interpreter.stack.inspect::<1>() { - let target: Address = addr_word.into_address(); - let beneficiary = context.host.beneficiary_address(); - let spec = context.host.spec_id(); - // The raw target already being the beneficiary observes beneficiary state - // regardless of where it itself delegates, so check it first — `||` short-circuits - // so no EIP-7702 delegate is resolved (and no DB read happens) in that case. - // REX6 otherwise resolves the delegate one hop so a CALL to a delegator `A` whose - // code points at `B == beneficiary` is also caught; <= REX5 compares the raw - // operand (frozen). The resolve is best-effort: a DB error (e.g. the delegate's - // code failing to load) falls back to the raw target WITHOUT stashing a - // `ctx.error`, so a malformed CALL that underflows before it ever runs the target - // keeps its `StackUnderflow` rather than surfacing a spurious DB error from this - // precheck. The opcode's real execution path reads the account again and owns - // surfacing any genuine failure. - if target == beneficiary || - (spec.is_enabled(MegaSpecId::REX6) && - context.host.best_effort_resolve_eip7702_delegate_address(target) == - beneficiary) - { - context.interpreter.bytecode.set_action(InterpreterAction::new_return( - InstructionResult::Revert, - volatile_data_access_disabled_revert_data( - VolatileDataAccessType::Beneficiary, - ), - context.interpreter.gas, - )); - return; - } - } - } - - // Delegate to the existing forward_gas_ext handler via reborrow so that - // `context` remains usable for `apply_compute_gas_limit!` afterward. - { - let ctx = InstructionContext::<'_, H, WIRE> { - interpreter: &mut *context.interpreter, - host: &mut *context.host, - }; - $inner_fn(ctx); - } - - // Propagate the detained compute gas limit if the CALL triggered beneficiary - // access (via `host.load_account_delegated()` inside the CALL handler). - // `apply_compute_gas_limit!` only touches the tracker and `AdditionalLimit`, - // not interpreter state, so it is safe in any interpreter state (including - // `NewFrame` after a successful CALL). - apply_compute_gas_limit!(context); - } - }; - } - - // Conditionally volatile CALL-like opcodes — volatile only when targeting the block - // beneficiary. These wrap forward_gas_ext handlers with a pre-execution beneficiary check. - wrap_call_volatile_check!(call, "CALL", forward_gas_ext::call); - wrap_call_volatile_check!(static_call, "STATICCALL", forward_gas_ext::static_call); - wrap_call_volatile_check!(delegate_call, "DELEGATECALL", forward_gas_ext::delegate_call); - wrap_call_volatile_check!(call_code, "CALLCODE", forward_gas_ext::call_code); -} - -/// Extends opcodes with additional limit (kv update limit, data limit, etc.) enforcement. -pub mod additional_limit_ext { - use super::*; - - /// `SSTORE` opcode implementation with data size and KV update limit enforcement. - /// - /// This wrapper adds limit tracking on top of [`storage_gas_ext::sstore`], which handles - /// compute gas tracking and storage gas costs. - /// - /// # Data Size and KV Update Tracking - /// - /// When first writing non-zero value to originally-zero slot: - /// - Adds 40 bytes to transaction data size - /// - Adds 1 KV update count - /// - /// # Limit Enforcement - /// - /// Halts with `OutOfGas` when data (3.125 MB) or KV (1,000) limits exceeded. - /// - /// # Refund Logic - /// - /// Refunds data/KV when slot reset to original value. - pub fn sstore< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Load storage slot values before executing the instruction - let target_address = context.interpreter.input.target_address(); - let Some(index) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let mega_spec = context.host.spec_id(); - let Ok(slot) = context.host.inspect_storage(mega_spec, target_address, index) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let (original_value, present_value) = (slot.original_value(), slot.present_value()); - let Some(new_value) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let loaded_data = SStoreResult { original_value, present_value, new_value }; - - // Execute the original SSTORE instruction - run_inner_instruction_or_abort!(storage_gas_ext::sstore, context); - - // KV update bomb and data bomb (only when first writing non-zero value to originally zero - // slot): check if the number of key-value updates or the total data size will exceed the - // limit, if so, halt. - let additional_limit = context.host.additional_limit(); - let mut additional_limit = additional_limit.borrow_mut(); - if !additional_limit.on_sstore(target_address, index, &loaded_data) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } - - /// `LOG` opcode implementation with data size limit enforcement. - /// - /// This wrapper adds data limit tracking on top of [`storage_gas_ext::log`], which handles - /// compute gas tracking and storage gas costs. - /// - /// # Data Size Limit Enforcement - /// - /// After log emission, checks if total transaction data size exceeds `TX_DATA_LIMIT` (3.125 - /// MB). Halts when data limit exceeded. - pub fn log< - const N: usize, - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Get the log data length before executing the instruction - let Some(len) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let len = as_usize_or_fail!(context.interpreter, len); - - // Execute the original LOG instruction - run_inner_instruction_or_abort!(storage_gas_ext::log::, context); - - // Record the size of the log topics and data. If the total data size exceeds the limit, we - // halt. - let additional_limit = context.host.additional_limit(); - let mut additional_limit = additional_limit.borrow_mut(); - if !additional_limit.on_log(N as u64, len as u64) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } -} - -/// Extends opcodes with storage gas cost on top of `compute_gas_ext`. -pub mod storage_gas_ext { - use super::*; - use alloy_primitives::Address; - - /// Address-selector for opcodes where the storage account is the stack `to` address (e.g. - /// CALL). - fn storage_addr_from_to(_mega_spec: MegaSpecId, _current: Address, to: Address) -> Address { - to - } - - /// Address-selector for CALLCODE: Rex5+ uses the current frame's address because CALLCODE - /// executes borrowed code in the caller's own storage context; pre-Rex5 preserves the frozen - /// behavior of metering against the code-source (stack `to`). - fn storage_addr_for_callcode(mega_spec: MegaSpecId, current: Address, to: Address) -> Address { - if mega_spec.is_enabled(MegaSpecId::REX5) { - current - } else { - to - } - } - - /// Macro to charge storage gas for new account creation before calling the wrapped instruction. - /// - /// This macro generates a wrapper function that: - /// 1. Inspects the target address (stack position 1) and value (stack position 2) - /// 2. Resolves the storage account address via `$select_addr` - /// 3. Checks if the storage account is empty and value transfer is non-zero - /// 4. Charges storage gas for new account creation if applicable - /// 5. Calls the wrapped instruction implementation - /// - /// # Call Opcode Behavior - /// - /// The generated `CALL` and `CALLCODE` implementations add: - /// - /// **Dynamic New Account Gas**: When calling empty account with value transfer: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - /// # Parameters - /// - `$fn_name`: Name of the generated function - /// - `$opcode_name`: String name of the opcode (for documentation) - /// - `$raw_fn`: Path to the raw inner opcode implementation (no compute-gas wrapper) - /// - `$has_transfer_logic`: `true` if the opcode can transfer value (inspects stack position 2) - /// - `$select_addr` (optional): Path to a `fn(MegaSpecId, current: Address, to: Address) -> - /// Address` function that returns the address to check for emptiness and charge - /// `new_account_storage_gas` against. `current` is the current frame's address; `to` is the - /// stack position-1 address. Defaults to [`storage_addr_from_to`]. - /// - /// # Metering order - /// - /// Runs `$raw_fn` directly and records compute gas exactly once after the body completes via - /// [`record_storage_compute_gas!`], excluding the storage gas charged above. Nothing consumes - /// EVM gas between the `gas_before` capture and the storage-gas charge (only stack inspects, - /// host account reads, and additional-limit operations), so this single-window form records - /// the same compute gas as the pre-REX6 "wrap the inner with `compute_gas_ext`" layering on - /// every spec — the recorded amount is `body_gas` either way. - macro_rules! wrap_call_with_storage_gas { - ($fn_name:ident, $opcode_name:expr, $raw_fn:path, $has_transfer_logic:expr) => { - wrap_call_with_storage_gas!( - $fn_name, - $opcode_name, - $raw_fn, - $has_transfer_logic, - storage_addr_from_to - ); - }; - ($fn_name:ident, $opcode_name:expr, $raw_fn:path, $has_transfer_logic:expr, $select_addr:path) => { - #[doc = concat!("`", $opcode_name, "` opcode implementation modified from `revm` with compute gas tracking and dynamically-scaled storage gas costs.")] - pub fn $fn_name< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers all of the - // opcode's compute work. - let gas_before = context.interpreter.gas.remaining(); - let spec = context.interpreter.runtime_flag.spec_id(); - let Some(to) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let to = to.into_address(); - let mega_spec = context.host.spec_id(); - let current_address = context.interpreter.input.target_address(); - let storage_address = $select_addr(mega_spec, current_address, to); - let Ok(storage_account) = (if mega_spec.is_enabled(MegaSpecId::REX5) { - context.host.inspect_account(storage_address, false) - } else { - context.host.inspect_account_delegated(mega_spec, storage_address) - }) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let is_empty = storage_account.state_clear_aware_is_empty(spec); - let has_transfer = if $has_transfer_logic { - let Some(value) = context.interpreter.stack.inspect::<2>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - !value.is_zero() - } else { - false - }; - // Charge additional storage gas cost for creating a new account. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - // `storage_charged` is the EVM gas actually debited for storage gas, so the REX6 - // single compute recording below can exclude it from the measured window. - let storage_charged = if is_empty && has_transfer { - let Some(new_account_storage_gas) = - context.host.new_account_storage_gas(storage_address) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(new_account_storage_gas); - let charged = new_account_storage_gas - drained; - gas!(context.interpreter, charged); - charged - } else { - 0 - }; - - // Run the raw opcode and record compute gas once after the body completes - // (canonical metering order). Byte-equivalent to the pre-REX6 layering on every - // spec because nothing between the `gas_before` capture and the storage charge - // above consumes EVM gas. - run_inner_instruction_or_abort!($raw_fn, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - }; - } - - wrap_call_with_storage_gas!(call, "CALL", instructions::contract::call, true); - wrap_call_with_storage_gas!( - delegate_call, - "DELEGATECALL", - instructions::contract::delegate_call, - false - ); - wrap_call_with_storage_gas!( - static_call, - "STATICCALL", - instructions::contract::static_call, - false - ); - wrap_call_with_storage_gas!( - call_code, - "CALLCODE", - instructions::contract::call_code, - true, - storage_addr_for_callcode - ); - - /// Inspects the creator account and computes the address a `CREATE`/`CREATE2` would deploy to. - /// - /// Shared by the pre-REX6 [`create`] and the REX6 [`create_rex6`] handlers so the address - /// computation lives in one place. For CREATE2 this expands memory to hash the initcode, which - /// debits EVM gas: - /// - /// - When `record_resize_eagerly` is `true` (pre-REX6 with REX5 enabled), the memory-expansion - /// gas is recorded into the compute-gas tracker immediately — the same position and timing as - /// the original inline code — and the returned `resize_gas` is `0`. - /// - When `record_resize_eagerly` is `false`, the gas is left unrecorded and returned, so the - /// caller decides when to record it: the pre-REX5 late-record path, or the REX6 single-window - /// folding in [`record_storage_compute_gas!`]. - /// - /// Returns `None` if a precondition failed (stack underflow, oversized operand, a REX6 - /// oversized-initcode halt, memory OOG, external DB error, or an eager compute-gas-limit - /// exceed) and the interpreter was halted. - fn compute_created_address< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: &mut InstructionContext<'_, H, WIRE>, - spec: MegaSpecId, - record_resize_eagerly: bool, - ) -> Option<(Address, u64)> { - // The current execution contract (the caller). Load it without marking it warm (it is - // already warm since the current frame began). REX5+ uses non-delegating inspection to get - // the authority's own state. - let creator_address = context.interpreter.input.target_address(); - let Ok(creator) = (if spec.is_enabled(MegaSpecId::REX5) { - context.host.inspect_account(creator_address, false) - } else { - context.host.inspect_account_delegated(spec, creator_address) - }) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return None; - }; - - let mut resize_gas: u64 = 0; - let is_rex5_enabled = spec.is_enabled(MegaSpecId::REX5); - let created_address = if IS_CREATE2 { - let Some(initcode_offset) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - let Some(initcode_len) = context.interpreter.stack.inspect::<2>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - // REX5+: validate the salt operand before running `resize_memory!` and the copy / - // keccak block, so a missing salt halts with `StackUnderflow` without - // performing the expensive memory work. Pre-REX5 keeps the original "resize - // first, salt last" order. - let rex5_salt = if is_rex5_enabled { - let Some(salt) = context.interpreter.stack.inspect::<3>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - Some(salt) - } else { - None - }; - - // REX5+: when `initcode_len == 0`, mirror canonical revm CREATE2 — ignore the offset - // entirely (no conversion, no memory expansion, no slice, no keccak) and use - // `KECCAK_EMPTY`. Pre-REX5 keeps the "observe offset, resize, slice, hash" sequence. - let initcode_hash = if is_rex5_enabled && initcode_len.is_zero() { - KECCAK_EMPTY - } else { - // Convert `initcode_len` before `initcode_offset` (matching canonical revm's - // `create`, which pops/converts `len` first): both operands halt with the same - // `InstructionResult::InvalidOperandOOG` reason when they don't fit in a - // `usize` (see `as_usize_or_fail_ret!`'s default reason), so this reordering - // does not change pre-REX6 behavior — but it matters for the REX6 size check - // below, which must run before `initcode_offset` is ever touched so that an - // oversized `initcode_len` halts with `CreateInitCodeSizeLimit` even when - // `initcode_offset` does not fit in a `usize` either. - let initcode_len = as_usize_or_fail_ret!(context.interpreter, initcode_len, None); - - // REX6: EIP-3860 initcode-size halt, matching revm's canonical - // ordering intent (`revm::interpreter::instructions::contract::create`) — halt - // BEFORE `initcode_offset` conversion, `resize_memory!`/copy/keccak256/address- - // derivation, not after. Pre-REX6 performs that prework before the halt - // eventually fires inside the inner opcode call below; that ordering is - // non-consensus under REX6 when the halt fires before the inner opcode - // completes (committed gas/state is identical either way — - // `record_resize_eagerly=false` means the resize gas is not yet recorded at - // this point, so skipping it here charges nothing that a later, slower path - // would have charged — only the halt timing / node CPU differ), but changing - // pre-REX6 timing would perturb sealed-spec replay, so this is gated to REX6 - // only. A REX6 static frame never reaches this check: [`create_rex6`] rejects - // static frames before entering this helper. - if spec.is_enabled(MegaSpecId::REX6) && - initcode_len > context.host.max_initcode_size() - { - context.interpreter.halt(InstructionResult::CreateInitCodeSizeLimit); - return None; - } - - let initcode_offset = - as_usize_or_fail_ret!(context.interpreter, initcode_offset, None); - - // Expand memory before slicing so the read can never go out of bounds. The inner - // CREATE2 also calls `resize_memory!`, which is a no-op once memory already fits. - let gas_before_resize = context.interpreter.gas.remaining(); - resize_memory!(context.interpreter, initcode_offset, initcode_len, None); - resize_gas = gas_before_resize.saturating_sub(context.interpreter.gas.remaining()); - - // Eager recording (pre-REX6 / REX5): record the expansion gas immediately to align - // its timing with revm's EVM-gas debit, then zero `resize_gas` so the caller's - // late-record path does not double-count. - if record_resize_eagerly && resize_gas > 0 { - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, resize_gas, None); - resize_gas = 0; - } - - let code = Bytes::copy_from_slice( - context.interpreter.memory.slice_len(initcode_offset, initcode_len).as_ref(), - ); - keccak256(&code) - }; - - let salt = if let Some(s) = rex5_salt { - s - } else { - let Some(salt) = context.interpreter.stack.inspect::<3>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return None; - }; - salt - }; - - creator_address.create2(salt.to_be_bytes(), initcode_hash) - } else { - creator_address.create(creator.info.nonce) - }; - - Some((created_address, resize_gas)) - } - - /// `CREATE`/`CREATE2` opcode implementation modified from `revm` with compute gas tracking and - /// dynamically-scaled storage gas costs. - /// - /// # Differences from the standard EVM - /// - /// 1. **Dynamic New Account Gas**: Additional storage gas for new account creation: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - /// # Assumptions - /// - /// This is the entry point for `CREATE`/`CREATE2` from `MINI_REX` onward. REX6+ short- - /// circuits to [`create_rex6`] at the top; the body below is the pre-REX6 path, which can - /// assume all features up to and including `MINI_REX` are enabled. - pub fn create< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - mut context: InstructionContext<'_, H, WIRE>, - ) { - let spec = context.host.spec_id(); - - // REX6+: canonical metering order — fold the CREATE2 memory-expansion gas into a single - // compute-gas recording taken after the body completes (see `create_rex6`), instead of - // the pre-REX6 split `resize_gas` recording handled below. - if spec.is_enabled(MegaSpecId::REX6) { - create_rex6::(context); - return; - } - - // Inspect the creator and compute the created address. REX5+ records the CREATE2 - // memory-expansion gas eagerly inside the helper (the same position and timing as the - // original inline code); pre-REX5 leaves it in `resize_gas` for the late-record path below. - let Some((created_address, resize_gas)) = compute_created_address::( - &mut context, - spec, - spec.is_enabled(MegaSpecId::REX5), - ) else { - return; - }; - - // Charge storage gas cost for creating a new contract - let create_contract_storage_gas = if spec.is_enabled(MegaSpecId::REX) { - // Rex spec distinguishes between contract creation and account creation. - context.host.create_contract_storage_gas(created_address) - } else { - // Mini-Rex spec does not distinguish between contract creation and account creation. - context.host.new_account_storage_gas(created_address) - }; - let Some(create_contract_storage_gas) = create_contract_storage_gas else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(create_contract_storage_gas); - gas!(context.interpreter, create_contract_storage_gas - drained); - - // Capture, run raw, record — `gas_before` here is captured after the storage debit and - // after `compute_created_address`'s eager `resize_gas` record (REX5+), so the recorded - // amount equals the inner opcode's body gas. Byte-equivalent to the old per-`IS_CREATE2` - // dispatch through `compute_gas_ext::{create, create2}`, which captured at the same - // point. - let gas_before = context.interpreter.gas.remaining(); - run_inner_instruction_or_abort!( - instructions::contract::create::<_, IS_CREATE2, _>, - context - ); - record_storage_compute_gas!(context, gas_before, 0); - - // Pre-REX5 late-record path for the CREATE2 initcode memory-expansion gas. - // Preserved verbatim for replay parity: pre-REX5 keeps the original "skip on inner - // error" semantics where storage-gas OOG and inner-CREATE2 failure both skip this - // recording. REX5+ already recorded `resize_gas` above (and zeroed it), so this - // branch is a no-op under REX5. - if resize_gas > 0 { - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, resize_gas); - } - } - - /// `CREATE`/`CREATE2` under the REX6+ canonical metering order. - /// - /// Records the opcode's compute gas exactly once, after the inner opcode completes, via - /// [`record_storage_compute_gas!`]. This folds the CREATE2 memory-expansion (`resize_memory!`) - /// gas into the single compute window instead of the pre-REX6 split recording (REX5 recorded it - /// eagerly before the storage charge; pre-REX5 recorded it after the inner op). The storage gas - /// charged for contract creation is excluded from the recorded compute gas. - /// - /// On the straight-line success path the total compute gas equals the pre-REX6 amount. The two - /// differ only when a compute-limit or storage-gas-OOG halt occurs between the memory expansion - /// and inner-op completion: REX6 records compute gas only once the body has fully executed, so - /// a partial memory expansion that never reaches the inner opcode is not recorded against - /// the compute-gas limit (its EVM gas is still debited). - /// - /// REX6 implies REX5 (and REX), so the REX5 operand validation and the contract-creation - /// storage-gas path are taken unconditionally here. - fn create_rex6< - WIRE: InterpreterTypes, - const IS_CREATE2: bool, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - mut context: InstructionContext<'_, H, WIRE>, - ) { - // Canonical revm's `create` runs `require_non_staticcall!` before any operand read, - // memory work, address derivation, or storage-gas charge, so a static-frame - // `CREATE`/`CREATE2` halts here first. This unifies the halt reasons the prework below - // would otherwise produce in a static frame — stack underflow from operand inspection, - // memory OOG from an unaffordable resize, storage-gas OOG from the creation charge, or - // a fatal external error from the storage-pricing lookup — into the canonical - // `StateChangeDuringStaticCall`. No spec gate: [`create`] dispatches here exactly when - // REX6 is enabled. Pre-REX6 keeps the prework-first order (changing sealed-spec halt - // reasons would perturb replay). Every reachable path is an all-gas-consuming halt, so - // committed gas and state are identical either way. - if context.interpreter.runtime_flag.is_static() { - context.interpreter.halt(InstructionResult::StateChangeDuringStaticCall); - return; - } - - // Captured before any gas movement so the single compute window covers the wrapper-side - // CREATE2 memory expansion as well as the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - let spec = context.host.spec_id(); - - // Inspect the creator and compute the created address. `record_resize_eagerly = false`: - // the CREATE2 memory-expansion gas is left unrecorded so it folds into the single compute - // window closed by `record_storage_compute_gas!` below. - let Some((created_address, _resize_gas)) = - compute_created_address::(&mut context, spec, false) - else { - return; - }; - - // Charge storage gas cost for creating a new contract. REX6 implies REX, so the - // contract-creation cost path applies. `storage_charged` is excluded from the compute - // recording below. - let Some(create_contract_storage_gas) = - context.host.create_contract_storage_gas(created_address) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - // REX6 implies REX5: drain the storage stipend allowance first. - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(create_contract_storage_gas); - let storage_charged = create_contract_storage_gas - drained; - gas!(context.interpreter, storage_charged); - - // Run the raw inner create opcode (no `compute_gas_ext` wrapper — REX6 records compute gas - // once below). - if IS_CREATE2 { - run_inner_instruction_or_abort!(instructions::contract::create::<_, true, _>, context); - } else { - run_inner_instruction_or_abort!(instructions::contract::create::<_, false, _>, context); - } - - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `LOG` opcode implementation modified from `revm` with compute gas tracking, increased - /// storage gas costs, and data size limit enforcement. - /// - /// # Differences from the standard EVM - /// - /// 1. **Storage Gas Costs**: Additional storage gas charged for log storage: - /// - Topic storage: 3,750 gas per topic (10x standard topic cost) - /// - Data storage: 80 gas per byte (10x standard data cost) - /// - /// # Assumptions - /// - /// This alternative implementation of `LOG` is only used when the `MINI_REX` spec is enabled. - pub fn log< - const N: usize, - WIRE: InterpreterTypes, - H: HostExt + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - let Some(len) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let len = as_usize_or_fail!(context.interpreter, len); - - // Charge storage gas cost for log topics and data before instruction execution. - // REX5 drains the allowance on the `Some(amount)` arm; the `None` (overflow) arm - // is passed through unchanged to preserve the OOG halt. - let log_storage_cost = { - let topic_cost = constants::mini_rex::LOG_TOPIC_STORAGE_GAS.checked_mul(N as u64); - let data_cost = constants::mini_rex::LOG_DATA_STORAGE_GAS.checked_mul(len as u64); - topic_cost.and_then(|topic| data_cost.and_then(|cost| cost.checked_add(topic))) - }; - let log_storage_cost = log_storage_cost.map(|amount| { - let drained = - context.host.additional_limit().borrow_mut().try_consume_storage_stipend(amount); - amount - drained - }); - gas_or_fail!(context.interpreter, log_storage_cost); - // `gas_or_fail!` halts and returns on the `None` (overflow) arm, so reaching here means the - // cost was `Some`; this is the storage gas actually charged, excluded from the compute - // recording below. Assert the invariant with `expect` rather than `unwrap_or(0)`: a silent - // `0` here would make `record_storage_compute_gas!` over-count compute gas by the full LOG - // storage cost. - let storage_charged = - log_storage_cost.expect("gas_or_fail! above halts and returns on None"); - - // Run the raw opcode and record compute gas once after the body completes (canonical - // metering order). Byte-equivalent to the pre-REX6 per-`N` `compute_gas_ext::logK` - // dispatch on every spec because nothing between `gas_before` and the `gas_or_fail!` above - // consumes EVM gas. The wrapper is only ever instantiated for `N` in `0..=4`, so the - // generic `instructions::host::log::` covers every valid call site. - run_inner_instruction_or_abort!(instructions::host::log::, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `SSTORE` opcode implementation modified from `revm` with compute gas tracking and - /// dynamically-scaled storage gas costs. - /// - /// # Differences from the standard EVM - /// - /// 1. **Dynamic Storage Gas**: Additional storage gas ONLY when setting originally-zero slot to - /// non-zero: - /// - Base cost 2,000,000 gas, multiplied by `bucket_capacity / MIN_BUCKET_SIZE` - /// - Not charged for updating already-non-zero slots or resetting to zero - /// - /// # Assumptions - /// - /// This alternative implementation of `SSTORE` is only used when the `MINI_REX` spec is - /// enabled, so we can safely assume that all features before and including Mini-Rex are - /// enabled. - pub fn sstore< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured at the very top so the single compute window covers the inner opcode. - let gas_before = context.interpreter.gas.remaining(); - // The address to the underlying execution contract state - let target_address = context.interpreter.input.target_address(); - // The storage slot to write - let Some(index) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - // The storage slot values - let mega_spec = context.host.spec_id(); - let Ok(slot) = context.host.inspect_storage(mega_spec, target_address, index) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let (original_value, present_value) = (slot.original_value(), slot.present_value()); - let Some(new_value) = context.interpreter.stack.inspect::<1>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - - // Charge storage gas cost before the instruction is executed. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - // `storage_charged` is the EVM gas actually debited for storage gas, excluded from the - // single compute recording below. - let storage_charged = - if original_value.is_zero() && present_value.is_zero() && !new_value.is_zero() { - let Some(sstore_set_storage_gas) = - context.host.sstore_set_storage_gas(target_address, index) - else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = context - .host - .additional_limit() - .borrow_mut() - .try_consume_storage_stipend(sstore_set_storage_gas); - let charged = sstore_set_storage_gas - drained; - gas!(context.interpreter, charged); - charged - } else { - 0 - }; - - // Run the raw opcode and record compute gas once after the body completes (canonical - // metering order). Byte-equivalent to the pre-REX6 `compute_gas_ext::sstore` layering on - // every spec because nothing between `gas_before` and the storage charge above consumes - // EVM gas. - run_inner_instruction_or_abort!(instructions::host::sstore, context); - record_storage_compute_gas!(context, gas_before, storage_charged); - } - - /// `SELFDESTRUCT` opcode implementation with storage gas metering for - /// new beneficiary account creation (REX5+). - /// - /// When SELFDESTRUCT sends remaining balance to an empty beneficiary, charges: - /// - Storage gas for new account creation (dynamic bucket-based cost) - /// - Data size (+40 for account info write) - /// - KV update (+1) - /// - State growth (+1) - /// - /// This wrapper sits between `volatile_data_ext` and `compute_gas_ext` in the - /// REX5 SELFDESTRUCT dispatch chain - /// (`volatile_data_ext::selfdestruct_with_beneficiary_guard` → `storage_gas_ext::selfdestruct` - /// → `compute_gas_ext::selfdestruct`), matching the layering used by SSTORE - /// and LOG. The beneficiary-volatile guard runs in the outer - /// `volatile_data_ext::selfdestruct_with_beneficiary_guard` ahead of any side effects below. - /// - /// REX6 additionally records the `DataSize` +40 / KV +1 of a balance credit to an existing - /// *distinct* beneficiary — the account-info write the frame-init / `target_updated` path never - /// sees — via the REX6-gated arm below; pre-REX6 records nothing for an existing target. The - /// rest of the body, and all ≤REX5 behavior, is unchanged. - pub fn selfdestruct< - WIRE: InterpreterTypes, - H: HostExt + ContextTr + JournalInspectTr + ?Sized, - >( - context: InstructionContext<'_, H, WIRE>, - ) { - // Inside a static frame, revm's inner SELFDESTRUCT halts on the - // static-context check without changing state. Skip the mega host work below - // (two account inspections, SALT account-creation pricing, the storage-gas - // stipend draw and tracker write) — the frame reverts and discards all of it - // anyway — and let the inner instruction produce the identical halt. This is - // behavior-neutral: the static halt is exceptional, so the frame's gas and - // tracked usage are the same whether or not the host work ran first. The table - // installs this wrapper only for REX5+, so pre-REX5 specs never reach here. - if context.interpreter.runtime_flag.is_static() { - run_inner_instruction_or_abort!(compute_gas_ext::selfdestruct, context); - // Defensive: unreachable in practice — a static SELFDESTRUCT always halts - // inside the inner instruction, so the macro returns early above. - return; - } - - let eth_spec = context.interpreter.runtime_flag.spec_id(); - - // Peek beneficiary address from stack (SELFDESTRUCT uses stack position 0) - let Some(target) = context.interpreter.stack.inspect::<0>() else { - context.interpreter.halt(InstructionResult::StackUnderflow); - return; - }; - let target = target.into_address(); - - // Use non-delegating inspection (REX5+) - let Ok(target_account) = context.host.inspect_account(target, false) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let is_empty = target_account.state_clear_aware_is_empty(eth_spec); - - // Check if caller has balance (value will be transferred to beneficiary) - let caller = context.interpreter.input.target_address(); - let Ok(caller_account) = context.host.inspect_account(caller, false) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let has_value = !caller_account.info.balance.is_zero(); - - if is_empty && has_value { - // Charge storage gas for creating a new account. - // REX5 drains the storage stipend allowance first; pre-REX5 returns 0. - let Some(cost) = context.host.new_account_storage_gas(target) else { - context.interpreter.halt(InstructionResult::FatalExternalError); - return; - }; - let drained = - context.host.additional_limit().borrow_mut().try_consume_storage_stipend(cost); - gas!(context.interpreter, cost - drained); - - // Record resource usage for new beneficiary account - context.host.additional_limit().borrow_mut().on_selfdestruct_new_account(); - } else if context.host.spec_id().is_enabled(MegaSpecId::REX6) && - has_value && - caller != target - { - // REX6: a balance credit to an existing *distinct* beneficiary performs an account-info - // write the frame-init / `target_updated` path never sees — record DataSize +40 / KV +1 - // (no `StateGrowth`, the account already exists; no storage gas, the bucket is paid). - // SELFDESTRUCT to self (`caller == target`) is an EIP-6780 balance no-op on a - // non-same-tx-created account (and a burn-to-self on a same-tx-created one) — neither - // is a distinct-target credit, so record nothing. Pre-REX6 records nothing - // for any existing target. - context.host.additional_limit().borrow_mut().on_selfdestruct_existing_account(); - } - - // Delegate to compute_gas_ext::selfdestruct (the volatile-disabled guard - // ran in the outer `volatile_data_ext::selfdestruct_with_beneficiary_guard` wrapper). - run_inner_instruction_or_abort!(compute_gas_ext::selfdestruct, context); +/// Stops the running frame with the revert a crossed limit asks for: its output is +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) and its gas is the frame's, so the caller gets +/// the unspent part back. +#[cold] +#[inline(never)] +fn stop_frame( + interpreter: &mut Interpreter, + check: &LimitCheck, +) -> InstructionResult { + if interpreter.bytecode.action().is_some() { + // A `SELFDESTRUCT` or a return the opcode already set gives way to the stop. + let _ = interpreter.take_next_action(); } + let result = InstructionResult::Revert; + interpreter.bytecode.set_action(InterpreterAction::new_return( + result, + check.revert_data(), + interpreter.gas, + )); + result } -/// Compute gas recording implementation. TODO: add more doc -pub mod compute_gas_ext { - use super::*; - - /// Macro to wrap the original instruction implementation with compute gas tracking. - /// - /// Two variants: - /// - default: "simple" opcodes that can never spawn a child frame. The compute gas used is - /// simply `gas_before - gas_after`. These opcodes never set an `InterpreterAction::NewFrame`, - /// so the child-gas-subtraction match (below) would always fall through to `_` — it is - /// omitted entirely to keep the per-opcode hot path lean. - /// - `@frame`: the call/create family (`CALL`/`CALLCODE`/`DELEGATECALL`/`STATICCALL`/ - /// `CREATE`/`CREATE2`), the only opcodes that set `NewFrame`. These must subtract the gas - /// forwarded to the child frame so the parent's compute gas is not over-counted. - macro_rules! wrap_op_compute_gas { - ($fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas tracking.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - // Captured before the inner opcode runs. Plain opcodes charge no storage gas, so - // the measurement window starting here covers exactly the opcode's compute work. - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!($original_fn, context); - - let gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, gas_used); - } - }; - (@frame $fn_name:ident, $opcode_name:expr, $original_fn:path) => { - #[doc = concat!("`", $opcode_name, "` opcode with compute gas tracking.")] - #[inline] - pub fn $fn_name( - context: InstructionContext<'_, H, WIRE>, - ) { - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!($original_fn, context); - - let mut gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - // Subtract the gas forwarded to the child. REX5 excludes the revm-side - // `CALL_STIPEND` (added by value-transferring CALL/CALLCODE without - // deducting from the parent) so parent compute-gas is not under-counted. - // Pre-REX5 keeps the legacy raw-`gas_limit` subtraction for replay parity. - match context.interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(FrameInput::Call(call_inputs))) => { - let stipend_from_revm = if context - .host - .spec_id() - .is_enabled(MegaSpecId::REX5) && - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode) && - call_inputs.transfers_value() - { - gas::CALL_STIPEND - } else { - 0 - }; - let parent_contributed = - call_inputs.gas_limit.saturating_sub(stipend_from_revm); - gas_used = gas_used.saturating_sub(parent_contributed); - } - Some(InterpreterAction::NewFrame(FrameInput::Create(create_inputs))) => { - gas_used = gas_used.saturating_sub(create_inputs.gas_limit); - } - _ => {} - } - let mut additional_limit = context.host.additional_limit().borrow_mut(); - compute_gas!(context.interpreter, additional_limit, gas_used); - } - }; - } - - wrap_op_compute_gas!(stop, "STOP", instructions::control::stop); - wrap_op_compute_gas!(add, "ADD", instructions::arithmetic::add); - wrap_op_compute_gas!(mul, "MUL", instructions::arithmetic::mul); - wrap_op_compute_gas!(sub, "SUB", instructions::arithmetic::sub); - wrap_op_compute_gas!(div, "DIV", instructions::arithmetic::div); - wrap_op_compute_gas!(sdiv, "SDIV", instructions::arithmetic::sdiv); - wrap_op_compute_gas!(rem, "MOD", instructions::arithmetic::rem); - wrap_op_compute_gas!(smod, "SMOD", instructions::arithmetic::smod); - wrap_op_compute_gas!(addmod, "ADDMOD", instructions::arithmetic::addmod); - wrap_op_compute_gas!(mulmod, "MULMOD", instructions::arithmetic::mulmod); - wrap_op_compute_gas!(exp, "EXP", instructions::arithmetic::exp); - wrap_op_compute_gas!(signextend, "SIGNEXTEND", instructions::arithmetic::signextend); - - wrap_op_compute_gas!(lt, "LT", instructions::bitwise::lt); - wrap_op_compute_gas!(gt, "GT", instructions::bitwise::gt); - wrap_op_compute_gas!(slt, "SLT", instructions::bitwise::slt); - wrap_op_compute_gas!(sgt, "SGT", instructions::bitwise::sgt); - wrap_op_compute_gas!(eq, "EQ", instructions::bitwise::eq); - wrap_op_compute_gas!(iszero, "ISZERO", instructions::bitwise::iszero); - wrap_op_compute_gas!(bitand, "AND", instructions::bitwise::bitand); - wrap_op_compute_gas!(bitor, "OR", instructions::bitwise::bitor); - wrap_op_compute_gas!(bitxor, "XOR", instructions::bitwise::bitxor); - wrap_op_compute_gas!(not, "NOT", instructions::bitwise::not); - wrap_op_compute_gas!(byte, "BYTE", instructions::bitwise::byte); - wrap_op_compute_gas!(shl, "SHL", instructions::bitwise::shl); - wrap_op_compute_gas!(shr, "SHR", instructions::bitwise::shr); - wrap_op_compute_gas!(sar, "SAR", instructions::bitwise::sar); - wrap_op_compute_gas!(clz, "CLZ", instructions::bitwise::clz); - - wrap_op_compute_gas!(keccak256, "KECCAK256", instructions::system::keccak256); - - wrap_op_compute_gas!(address, "ADDRESS", instructions::system::address); - wrap_op_compute_gas!(balance, "BALANCE", instructions::host::balance); - wrap_op_compute_gas!(origin, "ORIGIN", instructions::tx_info::origin); - wrap_op_compute_gas!(caller, "CALLER", instructions::system::caller); - wrap_op_compute_gas!(callvalue, "CALLVALUE", instructions::system::callvalue); - wrap_op_compute_gas!(calldataload, "CALLDATALOAD", instructions::system::calldataload); - wrap_op_compute_gas!(calldatasize, "CALLDATASIZE", instructions::system::calldatasize); - wrap_op_compute_gas!(calldatacopy, "CALLDATACOPY", instructions::system::calldatacopy); - wrap_op_compute_gas!(codesize, "CODESIZE", instructions::system::codesize); - wrap_op_compute_gas!(codecopy, "CODECOPY", instructions::system::codecopy); - - wrap_op_compute_gas!(gasprice, "GASPRICE", instructions::tx_info::gasprice); - wrap_op_compute_gas!(extcodesize, "EXTCODESIZE", instructions::host::extcodesize); - wrap_op_compute_gas!(extcodecopy, "EXTCODECOPY", instructions::host::extcodecopy); - wrap_op_compute_gas!(returndatasize, "RETURNDATASIZE", instructions::system::returndatasize); - wrap_op_compute_gas!(returndatacopy, "RETURNDATACOPY", instructions::system::returndatacopy); - wrap_op_compute_gas!(extcodehash, "EXTCODEHASH", instructions::host::extcodehash); - wrap_op_compute_gas!(blockhash, "BLOCKHASH", instructions::host::blockhash); - wrap_op_compute_gas!(coinbase, "COINBASE", instructions::block_info::coinbase); - wrap_op_compute_gas!(timestamp, "TIMESTAMP", instructions::block_info::timestamp); - wrap_op_compute_gas!(number, "NUMBER", instructions::block_info::block_number); - wrap_op_compute_gas!(difficulty, "DIFFICULTY", instructions::block_info::difficulty); - wrap_op_compute_gas!(gaslimit, "GASLIMIT", instructions::block_info::gaslimit); - wrap_op_compute_gas!(chainid, "CHAINID", instructions::block_info::chainid); - wrap_op_compute_gas!(selfbalance, "SELFBALANCE", instructions::host::selfbalance); - wrap_op_compute_gas!(basefee, "BASEFEE", instructions::block_info::basefee); - wrap_op_compute_gas!(blobhash, "BLOBHASH", instructions::tx_info::blob_hash); - wrap_op_compute_gas!(blobbasefee, "BLOBBASEFEE", instructions::block_info::blob_basefee); - - wrap_op_compute_gas!(pop, "POP", instructions::stack::pop); - wrap_op_compute_gas!(mload, "MLOAD", instructions::memory::mload); - wrap_op_compute_gas!(mstore, "MSTORE", instructions::memory::mstore); - wrap_op_compute_gas!(mstore8, "MSTORE8", instructions::memory::mstore8); - wrap_op_compute_gas!(sload, "SLOAD", instructions::host::sload); - wrap_op_compute_gas!(jump, "JUMP", instructions::control::jump); - wrap_op_compute_gas!(jumpi, "JUMPI", instructions::control::jumpi); - wrap_op_compute_gas!(pc, "PC", instructions::control::pc); - wrap_op_compute_gas!(msize, "MSIZE", instructions::memory::msize); - wrap_op_compute_gas!(gas, "GAS", instructions::system::gas); - wrap_op_compute_gas!(jumpdest, "JUMPDEST", instructions::control::jumpdest); - wrap_op_compute_gas!(tload, "TLOAD", instructions::host::tload); - wrap_op_compute_gas!(tstore, "TSTORE", instructions::host::tstore); - wrap_op_compute_gas!(mcopy, "MCOPY", instructions::memory::mcopy); - - wrap_op_compute_gas!(push0, "PUSH0", instructions::stack::push0); - wrap_op_compute_gas!(push1, "PUSH1", instructions::stack::push::<1, _, _>); - wrap_op_compute_gas!(push2, "PUSH2", instructions::stack::push::<2, _, _>); - wrap_op_compute_gas!(push3, "PUSH3", instructions::stack::push::<3, _, _>); - wrap_op_compute_gas!(push4, "PUSH4", instructions::stack::push::<4, _, _>); - wrap_op_compute_gas!(push5, "PUSH5", instructions::stack::push::<5, _, _>); - wrap_op_compute_gas!(push6, "PUSH6", instructions::stack::push::<6, _, _>); - wrap_op_compute_gas!(push7, "PUSH7", instructions::stack::push::<7, _, _>); - wrap_op_compute_gas!(push8, "PUSH8", instructions::stack::push::<8, _, _>); - wrap_op_compute_gas!(push9, "PUSH9", instructions::stack::push::<9, _, _>); - wrap_op_compute_gas!(push10, "PUSH10", instructions::stack::push::<10, _, _>); - wrap_op_compute_gas!(push11, "PUSH11", instructions::stack::push::<11, _, _>); - wrap_op_compute_gas!(push12, "PUSH12", instructions::stack::push::<12, _, _>); - wrap_op_compute_gas!(push13, "PUSH13", instructions::stack::push::<13, _, _>); - wrap_op_compute_gas!(push14, "PUSH14", instructions::stack::push::<14, _, _>); - wrap_op_compute_gas!(push15, "PUSH15", instructions::stack::push::<15, _, _>); - wrap_op_compute_gas!(push16, "PUSH16", instructions::stack::push::<16, _, _>); - wrap_op_compute_gas!(push17, "PUSH17", instructions::stack::push::<17, _, _>); - wrap_op_compute_gas!(push18, "PUSH18", instructions::stack::push::<18, _, _>); - wrap_op_compute_gas!(push19, "PUSH19", instructions::stack::push::<19, _, _>); - wrap_op_compute_gas!(push20, "PUSH20", instructions::stack::push::<20, _, _>); - wrap_op_compute_gas!(push21, "PUSH21", instructions::stack::push::<21, _, _>); - wrap_op_compute_gas!(push22, "PUSH22", instructions::stack::push::<22, _, _>); - wrap_op_compute_gas!(push23, "PUSH23", instructions::stack::push::<23, _, _>); - wrap_op_compute_gas!(push24, "PUSH24", instructions::stack::push::<24, _, _>); - wrap_op_compute_gas!(push25, "PUSH25", instructions::stack::push::<25, _, _>); - wrap_op_compute_gas!(push26, "PUSH26", instructions::stack::push::<26, _, _>); - wrap_op_compute_gas!(push27, "PUSH27", instructions::stack::push::<27, _, _>); - wrap_op_compute_gas!(push28, "PUSH28", instructions::stack::push::<28, _, _>); - wrap_op_compute_gas!(push29, "PUSH29", instructions::stack::push::<29, _, _>); - wrap_op_compute_gas!(push30, "PUSH30", instructions::stack::push::<30, _, _>); - wrap_op_compute_gas!(push31, "PUSH31", instructions::stack::push::<31, _, _>); - wrap_op_compute_gas!(push32, "PUSH32", instructions::stack::push::<32, _, _>); - - wrap_op_compute_gas!(dup1, "DUP1", instructions::stack::dup::<1, _, _>); - wrap_op_compute_gas!(dup2, "DUP2", instructions::stack::dup::<2, _, _>); - wrap_op_compute_gas!(dup3, "DUP3", instructions::stack::dup::<3, _, _>); - wrap_op_compute_gas!(dup4, "DUP4", instructions::stack::dup::<4, _, _>); - wrap_op_compute_gas!(dup5, "DUP5", instructions::stack::dup::<5, _, _>); - wrap_op_compute_gas!(dup6, "DUP6", instructions::stack::dup::<6, _, _>); - wrap_op_compute_gas!(dup7, "DUP7", instructions::stack::dup::<7, _, _>); - wrap_op_compute_gas!(dup8, "DUP8", instructions::stack::dup::<8, _, _>); - wrap_op_compute_gas!(dup9, "DUP9", instructions::stack::dup::<9, _, _>); - wrap_op_compute_gas!(dup10, "DUP10", instructions::stack::dup::<10, _, _>); - wrap_op_compute_gas!(dup11, "DUP11", instructions::stack::dup::<11, _, _>); - wrap_op_compute_gas!(dup12, "DUP12", instructions::stack::dup::<12, _, _>); - wrap_op_compute_gas!(dup13, "DUP13", instructions::stack::dup::<13, _, _>); - wrap_op_compute_gas!(dup14, "DUP14", instructions::stack::dup::<14, _, _>); - wrap_op_compute_gas!(dup15, "DUP15", instructions::stack::dup::<15, _, _>); - wrap_op_compute_gas!(dup16, "DUP16", instructions::stack::dup::<16, _, _>); - - wrap_op_compute_gas!(swap1, "SWAP1", instructions::stack::swap::<1, _, _>); - wrap_op_compute_gas!(swap2, "SWAP2", instructions::stack::swap::<2, _, _>); - wrap_op_compute_gas!(swap3, "SWAP3", instructions::stack::swap::<3, _, _>); - wrap_op_compute_gas!(swap4, "SWAP4", instructions::stack::swap::<4, _, _>); - wrap_op_compute_gas!(swap5, "SWAP5", instructions::stack::swap::<5, _, _>); - wrap_op_compute_gas!(swap6, "SWAP6", instructions::stack::swap::<6, _, _>); - wrap_op_compute_gas!(swap7, "SWAP7", instructions::stack::swap::<7, _, _>); - wrap_op_compute_gas!(swap8, "SWAP8", instructions::stack::swap::<8, _, _>); - wrap_op_compute_gas!(swap9, "SWAP9", instructions::stack::swap::<9, _, _>); - wrap_op_compute_gas!(swap10, "SWAP10", instructions::stack::swap::<10, _, _>); - wrap_op_compute_gas!(swap11, "SWAP11", instructions::stack::swap::<11, _, _>); - wrap_op_compute_gas!(swap12, "SWAP12", instructions::stack::swap::<12, _, _>); - wrap_op_compute_gas!(swap13, "SWAP13", instructions::stack::swap::<13, _, _>); - wrap_op_compute_gas!(swap14, "SWAP14", instructions::stack::swap::<14, _, _>); - wrap_op_compute_gas!(swap15, "SWAP15", instructions::stack::swap::<15, _, _>); - wrap_op_compute_gas!(swap16, "SWAP16", instructions::stack::swap::<16, _, _>); - - wrap_op_compute_gas!(@frame call_code, "CALLCODE", instructions::contract::call_code); - wrap_op_compute_gas!(ret, "RETURN", instructions::control::ret); - wrap_op_compute_gas!(@frame delegate_call, "DELEGATECALL", instructions::contract::delegate_call); - wrap_op_compute_gas!(@frame static_call, "STATICCALL", instructions::contract::static_call); - - wrap_op_compute_gas!(revert, "REVERT", instructions::control::revert); - wrap_op_compute_gas!(invalid, "INVALID", instructions::control::invalid); - - /// `SELFDESTRUCT` opcode with compute gas tracking. - /// - /// Unlike the default wrapper, the trailing check fans out across all four limit - /// dimensions (`record_compute_gas_all_dims`): the REX5 storage wrapper records - /// beneficiary data/KV/state usage *before* the inner instruction runs, without - /// latching, and those dimensions must latch (and halt) here — only once the inner - /// instruction has succeeded. Latching at the recording site instead would stick - /// even when the inner instruction subsequently fails and the frame's discardable - /// usage is rolled back. - pub fn selfdestruct( - context: InstructionContext<'_, H, WIRE>, - ) { - let gas_before = context.interpreter.gas.remaining(); - - // Call the original instruction - run_inner_instruction_or_abort!(instructions::host::selfdestruct, context); - - let gas_used = gas_before.saturating_sub(context.interpreter.gas.remaining()); - let mut additional_limit = context.host.additional_limit().borrow_mut(); - if !additional_limit.record_compute_gas_all_dims(gas_used) { - context.interpreter.halt(additional_limit.exceeding_instruction_result()); - } - } +/// `SSTORE`, committing the slot's write record. +fn sstore( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::sstore) } -/// Trait to inspect the stack elements. -pub trait StackInspectTr { - /// Inspect the N-th element of the stack. The top of the stack is the 0-th element. - /// If the stack is too short, return None. - fn inspect(&self) -> Option; +/// `LOG0`..`LOG4`, committing the log's bytes. +fn log( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::log::>) } -impl StackInspectTr for Stack { - fn inspect(&self) -> Option { - if N >= self.len() { - return None; - } - let index = self.len() - 1 - N; - // SAFETY: the index must be within the bounds of the stack - Some(unsafe { *self.data().get_unchecked(index) }) - } +/// `SELFDESTRUCT`, committing the beneficiary's write record. +fn selfdestruct( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + commit_after(context, host::selfdestruct) } #[cfg(test)] mod tests { use super::*; use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use revm::interpreter::instructions::gas_table_spec; - /// Every alias spec must select exactly its `behavior()` target's instruction - /// table — the match in `MegaInstructions::new` states the alias→target mapping a - /// second time, and this test is the reconciliation between the two. Both tables - /// come from the same monomorphization, so identical arms produce identical fn - /// pointers and `fn_addr_eq` compares them reliably. + /// The wrappers keep the static gas revm charges for their opcodes: the whole table is revm's. #[test] - fn test_alias_specs_use_their_behavior_targets_table() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - let alias = MegaInstructions::::new(*spec); - let target = MegaInstructions::::new(spec.behavior()); - let (alias_table, target_table) = - (alias.instruction_table(), target.instruction_table()); - for opcode in 0..=0xff_usize { - assert!( - core::ptr::fn_addr_eq(alias_table[opcode], target_table[opcode]), - "{spec:?} table diverges from its behavior target {:?} at opcode {opcode:#04x}", - spec.behavior(), - ); - } - } + fn test_wrappers_keep_the_static_gas_table() { + let mega = mega_instructions::(SpecId::OSAKA); + assert_eq!(mega.gas_table(), &gas_table_spec(SpecId::OSAKA)); + assert_eq!(mega.spec, SpecId::OSAKA); } } diff --git a/crates/mega-evm/src/evm/interfaces.rs b/crates/mega-evm/src/evm/interfaces.rs deleted file mode 100644 index 4f46cb05f..000000000 --- a/crates/mega-evm/src/evm/interfaces.rs +++ /dev/null @@ -1,236 +0,0 @@ -use alloy_evm::{precompiles::PrecompilesMap, Database, EvmEnv}; -use alloy_primitives::{Address, Bytes}; -use revm::{ - context::{ - result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, - BlockEnv, ContextSetters, ContextTr, - }, - handler::{EthFrame, EvmTr, SystemCallTx}, - interpreter::interpreter::EthInterpreter, - state::EvmState, - DatabaseCommit, InspectEvm, Inspector, SystemCallEvm, -}; - -use crate::{ - ExternalEnvTypes, IntoMegaethCfgEnv, MegaContext, MegaEvm, MegaHaltReason, MegaHandler, - MegaSpecId, MegaTransaction, MegaTransactionError, -}; - -/// Implementation of [`alloy_evm::Evm`] for `MegaETH` EVM. -/// -/// This implementation provides the core EVM interface required by the Alloy EVM framework, -/// enabling seamless integration with Alloy-based applications while providing `MegaETH`-specific -/// customizations and optimizations. -impl alloy_evm::Evm for MegaEvm -where - DB: Database, - INSP: Inspector>, -{ - type DB = DB; - type Tx = MegaTransaction; - type Error = EVMError; - type HaltReason = MegaHaltReason; - type Spec = MegaSpecId; - type Precompiles = PrecompilesMap; - type Inspector = INSP; - - fn block(&self) -> &BlockEnv { - self.block_env_ref() - } - - fn chain_id(&self) -> u64 { - self.ctx_ref().cfg.chain_id - } - - fn transact_raw( - &mut self, - tx: Self::Tx, - ) -> Result, Self::Error> { - if self.inspect { - InspectEvm::inspect_tx(self, tx) - } else { - revm::ExecuteEvm::transact(self, tx) - } - } - - /// Transact a system call. - /// - /// This method enables system calls within the `MegaETH` EVM, following the same - /// pattern as the Optimism EVM. System calls are special transactions that can - /// interact with the underlying system without going through the normal transaction - /// validation process. - /// - /// # Parameters - /// - /// - `caller`: The address making the system call - /// - `contract`: The target contract address - /// - `data`: The call data to execute - /// - /// # Returns - /// - /// The execution result and state changes from the system call. - /// - /// # Note - /// - /// This function copies the logic from `alloy_op_evm::OpEvm::transact_system_call` - /// to maintain compatibility with the Optimism EVM system call interface. The - /// transaction's gas limit follows revm's upstream-fixed 30M default. Callers that - /// need to use the live block gas budget — e.g. REX5 pre-block helpers whose cost is - /// sensitive to dynamic storage gas — should use - /// [`MegaEvm::transact_system_call_with_gas_limit`] instead. - fn transact_system_call( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - ) -> Result, Self::Error> { - self.transact_system_call_with_caller_finalize(caller, contract, data) - } - - fn finish(self) -> (Self::DB, EvmEnv) - where - Self: Sized, - { - let spec = self.inner.ctx.mega_spec(); - let revm::Context { block: block_env, cfg: cfg_env, journaled_state, .. } = - self.inner.ctx.into_inner(); - let cfg_env = cfg_env.into_megaeth_cfg(spec); - (journaled_state.database, EvmEnv { block_env, cfg_env }) - } - - fn set_inspector_enabled(&mut self, enabled: bool) { - self.inspect = enabled; - } - - fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { - (&self.inner.ctx.journaled_state.database, &self.inner.inspector, &self.inner.precompiles) - } - - fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { - ( - &mut self.inner.ctx.journaled_state.database, - &mut self.inner.inspector, - &mut self.inner.precompiles, - ) - } -} - -impl revm::ExecuteEvm for MegaEvm -where - DB: Database, -{ - type Tx = MegaTransaction; - type Block = BlockEnv; - 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.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run(&mut h, self) - } - - fn finalize(&mut self) -> Self::State { - self.inner.ctx.journal_mut().finalize() - } - - fn replay( - &mut self, - ) -> Result, Self::Error> { - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run(&mut h, self).map(|result| { - let state = self.finalize(); - ExecResultAndState::new(result, state) - }) - } -} - -impl revm::ExecuteCommitEvm for MegaEvm -where - DB: Database + DatabaseCommit, -{ - fn commit(&mut self, state: Self::State) { - self.ctx().db_mut().commit(state); - } -} - -impl revm::InspectEvm for MegaEvm -where - DB: Database, - INSP: Inspector>, -{ - type Inspector = INSP; - - fn set_inspector(&mut self, inspector: Self::Inspector) { - self.inner.inspector = inspector; - } - - fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { - self.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::inspector::InspectorHandler::inspect_run(&mut h, self) - } -} - -impl revm::InspectCommitEvm for MegaEvm -where - DB: Database + DatabaseCommit, - INSP: Inspector>, -{ -} - -impl revm::SystemCallEvm for MegaEvm -where - DB: Database, -{ - fn transact_system_call_with_caller( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - ) -> Result { - self.ctx().set_tx(::new_system_tx_with_caller( - caller, contract, data, - )); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run_system_call(&mut h, self) - } -} - -impl MegaEvm -where - DB: Database, -{ - /// Transact a system call with an explicit gas limit and finalize. - /// - /// Behaves like [`alloy_evm::Evm::transact_system_call`] but lets the caller specify - /// the gas limit instead of relying on revm's upstream-fixed 30M default. This is - /// intended for REX5+ pre-block helpers (e.g. `transact_apply_pending_changes` in - /// `system::sequencer_registry`) whose real cost is sensitive to dynamic storage gas - /// and is no longer guaranteed to fit within 30M on activation blocks. - /// - /// The recommended argument is - /// `block.gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR)`. - pub fn transact_system_call_with_gas_limit( - &mut self, - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, - ) -> Result, EVMError> { - let mut tx = - ::new_system_tx_with_caller(caller, contract, data); - tx.base.gas_limit = gas_limit; - self.ctx().set_tx(tx); - let mut h = MegaHandler::<_, _, EthFrame>::new(); - revm::handler::Handler::run_system_call(&mut h, self).map(|result| { - let state = self.inner.ctx.journal_mut().finalize(); - ResultAndState { result, state } - }) - } -} diff --git a/crates/mega-evm/src/evm/limit.rs b/crates/mega-evm/src/evm/limit.rs deleted file mode 100644 index b9111abb8..000000000 --- a/crates/mega-evm/src/evm/limit.rs +++ /dev/null @@ -1,185 +0,0 @@ -use crate::MegaSpecId; - -/// Runtime limits for a single transaction. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct EvmTxRuntimeLimits { - // ====== Limits enforced during transaction execution ====== - /// Maximum data size for a single transaction. - pub tx_data_size_limit: u64, - /// Maximum key-value updates for a single transaction. - pub tx_kv_updates_limit: u64, - /// Maximum compute gas limit for a single transaction. - pub tx_compute_gas_limit: u64, - /// Maximum state growth limit for a single transaction. - pub tx_state_growth_limit: u64, - /// Compute gas limit when accessing block environment data. - pub block_env_access_compute_gas_limit: u64, - /// Compute gas limit when accessing oracle data. - pub oracle_access_compute_gas_limit: u64, -} - -impl EvmTxRuntimeLimits { - /// Creates a new `TxLimits` instance from the given `MegaSpecId`. - pub fn from_spec(spec: MegaSpecId) -> Self { - // An alias spec is grouped with its `behavior()` target so it runs under exactly the - // target's limits; the grouping must agree with `behavior()`, pinned by - // `test_alias_specs_use_their_behavior_targets_limits`. - match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => Self::equivalence(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => Self::mini_rex(), - MegaSpecId::REX | MegaSpecId::REX1 | MegaSpecId::REX2 => Self::rex(), - MegaSpecId::REX3 => Self::rex3(), - MegaSpecId::REX4 => Self::rex4(), - MegaSpecId::REX5 => Self::rex5(), - MegaSpecId::REX6 => Self::rex6(), - MegaSpecId::REX7 => Self::rex7(), - } - } - - /// No limits. - pub fn no_limits() -> Self { - Self { - tx_data_size_limit: u64::MAX, - tx_kv_updates_limit: u64::MAX, - tx_compute_gas_limit: u64::MAX, - tx_state_growth_limit: u64::MAX, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - /// Limits for the `EQUIVALENCE` spec. - pub fn equivalence() -> Self { - Self::no_limits() - } - - /// Limits for the `MINI_REX` spec. - pub fn mini_rex() -> Self { - Self { - tx_data_size_limit: crate::constants::mini_rex::TX_DATA_LIMIT, - tx_kv_updates_limit: crate::constants::mini_rex::TX_KV_UPDATE_LIMIT, - tx_compute_gas_limit: crate::constants::mini_rex::TX_COMPUTE_GAS_LIMIT, - block_env_access_compute_gas_limit: - crate::constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - oracle_access_compute_gas_limit: crate::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - ..Self::equivalence() - } - } - - /// Limits for the `REX` spec. - pub fn rex() -> Self { - Self { - tx_data_size_limit: crate::constants::rex::TX_DATA_LIMIT, - tx_kv_updates_limit: crate::constants::rex::TX_KV_UPDATE_LIMIT, - tx_compute_gas_limit: crate::constants::rex::TX_COMPUTE_GAS_LIMIT, - tx_state_growth_limit: crate::constants::rex::TX_STATE_GROWTH_LIMIT, - block_env_access_compute_gas_limit: - crate::constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - oracle_access_compute_gas_limit: crate::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - } - } - - /// Limits for the `REX3` spec. - fn rex3() -> Self { - Self { - oracle_access_compute_gas_limit: crate::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - ..Self::rex() - } - } - - /// Limits for the `REX4` spec. - /// - /// Currently identical to Rex3 limits. - /// Per-frame state growth budgets are handled by `FrameLimitTracker`. - fn rex4() -> Self { - Self::rex3() - } - - /// Limits for the `REX5` spec. - /// - /// Currently identical to Rex4 limits. - fn rex5() -> Self { - Self::rex4() - } - - /// Limits for the `REX6` spec. - /// - /// Currently identical to Rex5 limits. - fn rex6() -> Self { - Self::rex5() - } - - /// Limits for the `REX7` spec. - /// - /// Currently identical to Rex6 limits. - fn rex7() -> Self { - Self::rex6() - } -} - -impl EvmTxRuntimeLimits { - /// Sets the maximum data size for a single transaction. - pub fn with_tx_data_size_limit(mut self, tx_data_size_limit: u64) -> Self { - self.tx_data_size_limit = tx_data_size_limit; - self - } - - /// Sets the maximum key-value updates for a single transaction. - pub fn with_tx_kv_updates_limit(mut self, tx_kv_updates_limit: u64) -> Self { - self.tx_kv_updates_limit = tx_kv_updates_limit; - self - } - - /// Sets the maximum compute gas limit for a single transaction. - pub fn with_tx_compute_gas_limit(mut self, tx_compute_gas_limit: u64) -> Self { - self.tx_compute_gas_limit = tx_compute_gas_limit; - self - } - - /// Sets the maximum state growth limit for a single transaction. - pub fn with_tx_state_growth_limit(mut self, tx_state_growth_limit: u64) -> Self { - self.tx_state_growth_limit = tx_state_growth_limit; - self - } - - /// Sets the compute gas limit when accessing block environment data. - pub fn with_block_env_access_compute_gas_limit( - mut self, - block_env_access_compute_gas_limit: u64, - ) -> Self { - self.block_env_access_compute_gas_limit = block_env_access_compute_gas_limit; - self - } - - /// Sets the compute gas limit when accessing oracle data. - pub fn with_oracle_access_compute_gas_limit( - mut self, - oracle_access_compute_gas_limit: u64, - ) -> Self { - self.oracle_access_compute_gas_limit = oracle_access_compute_gas_limit; - self - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Every alias spec must run under exactly its `behavior()` target's limits — the - /// match in `from_spec` states the alias→target mapping a second time, and this - /// test is the reconciliation between the two. - #[test] - fn test_alias_specs_use_their_behavior_targets_limits() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - assert_eq!( - EvmTxRuntimeLimits::from_spec(*spec), - EvmTxRuntimeLimits::from_spec(spec.behavior()), - "{spec:?} limits diverge from its behavior target {:?}", - spec.behavior(), - ); - } - } -} diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 5ddf94f2f..d545532ef 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,299 +1,158 @@ -//! EVM implementation for the `MegaETH` chain. +//! The Satin EVM. //! -//! This module provides the core EVM implementation specifically tailored for the `MegaETH` -//! chain, built on top of the Optimism EVM (`op-revm`) with MegaETH-specific customizations -//! and optimizations. -//! -//! # Architecture -//! -//! The EVM implementation consists of two main components: -//! -//! 1. **`EvmFactory`**: Factory for creating EVM instances with `MegaETH` specifications -//! 2. **`Evm`**: The main EVM instance that wraps the Optimism EVM with `MegaETH` customizations -//! -//! # EVM Specifications -//! -//! `MegaETH` supports multiple EVM specifications: -//! -//! - **`EQUIVALENCE`**: Maintains equivalence with Optimism Isthmus EVM -//! - **`MINI_REX`**: Enhanced version with quadratic LOG costs and disabled SELFDESTRUCT -//! - **`REX`**: Fixes `MiniRex` call opcode inconsistencies and refines storage gas -//! - **`REX1`**: Resets compute gas limits between transactions -//! - **`REX2`**: Re-enables SELFDESTRUCT with EIP-6780 semantics -//! - **`REX3`**: Increases oracle gas limit to 20M, moves oracle detention to SLOAD-based, tracks -//! keyless deploy compute gas -//! - **`REX4`**: Per-call-frame resource budgets, relative gas detention, storage gas stipend, -//! `MegaAccessControl` and `MegaLimitControl` system contracts +//! [`MegaEvm`] runs transactions on a [`MegaContext`] configured for the Satin spec through +//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame lifecycle +//! itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level mechanisms +//! plug in. mod context; mod execution; mod factory; +mod frame; mod host; +mod inspector; mod instructions; -mod interfaces; -mod limit; -mod precompiles; mod result; mod spec; -mod state; - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{collections::BTreeMap, vec::Vec}; -use alloy_primitives::{Address, B256}; pub use context::*; pub use execution::*; pub use factory::*; +pub use frame::*; pub use host::*; -pub use instructions::*; -#[allow(unused_imports, unreachable_pub)] -pub use interfaces::*; -pub use limit::*; -pub use precompiles::*; +pub use inspector::*; pub use result::*; pub use spec::*; -pub use state::*; -use alloy_evm::{ - precompiles::{DynPrecompile, PrecompilesMap}, - Database, -}; +use alloy_evm::EvmEnv; +use alloy_op_evm::map_op_err; +use op_revm::{precompiles::OpPrecompiles, OpHaltReason, OpTransactionError}; use revm::{ - context::{result::ResultAndState, BlockEnv, ContextTr}, - handler::{EthFrame, EvmTr}, - inspector::NoOpInspector, + context::{ + result::{EVMError, ExecResultAndState, ExecutionResult, ResultAndState}, + BlockEnv, CfgEnv, ContextSetters, ContextTr, FrameStack, JournalTr, + }, + handler::{ + instructions::EthInstructions, system_call::SystemCallEvm, EthFrame, Handler, SystemCallTx, + }, + inspector::{ + InspectCommitEvm, InspectEvm, InspectSystemCallEvm, Inspector, InspectorHandler, + NoOpInspector, + }, interpreter::interpreter::EthInterpreter, - primitives::HashMap, - ExecuteEvm, InspectEvm, Inspector, Journal, + primitives::{Address, Bytes}, + state::EvmState, + Database, DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, }; -use crate::{BucketId, ExternalEnvTypes, LimitUsage, MegaTransaction}; +use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; -/// The main EVM implementation for the `MegaETH` chain. -/// -/// This struct wraps the underlying Optimism EVM (`OpEvm`) with `MegaETH`-specific customizations -/// and optimizations. It provides access to enhanced security features, increased limits, and -/// block environment access tracking capabilities. -/// -/// # Type Parameters -/// -/// - `DB`: The database type implementing [`Database`] -/// - `INSP`: The inspector type implementing [`Inspector`] -/// - `Oracle`: The `external_envs` type implementing [`ExternalEnvs`] +/// The instruction table of the Satin engine. +pub(crate) type MegaInstructions = + EthInstructions>; + +/// The revm EVM a [`MegaEvm`] wraps. /// -/// # Implementation Details +/// It runs op-revm's precompile set for the base spec until the Satin precompile set lands. +pub(crate) type MegaInnerEvm = revm::context::Evm< + MegaContext, + INSP, + MegaInstructions, + OpPrecompiles, + EthFrame, +>; + +/// The Satin EVM. /// -/// The EVM uses delegation to efficiently wrap the underlying Optimism EVM while providing -/// `MegaETH`-specific customizations through the configured context, instructions, and precompiles. +/// Executes transactions through [`MegaHandler`] on a [`MegaContext`]. It implements revm's +/// execution traits ([`ExecuteEvm`], [`InspectEvm`], [`SystemCallEvm`] and their commit +/// variants) and alloy-evm's [`Evm`](alloy_evm::Evm), which is what a node's block executor +/// drives. #[allow(missing_debug_implementations)] -#[allow(clippy::type_complexity)] -pub struct MegaEvm { - inner: revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - >, - /// Whether to enable the inspector at runtime. +pub struct MegaEvm { + inner: MegaInnerEvm, + /// Whether [`alloy_evm::Evm::transact_raw`] runs the inspector. inspect: bool, -} - -impl core::fmt::Debug - for MegaEvm -{ - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("MegaethEvm").field("inspect", &self.inspect).finish_non_exhaustive() - } -} - -impl core::ops::Deref - for MegaEvm -{ - type Target = revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - >; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl core::ops::DerefMut - for MegaEvm -{ - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.inner - } + /// Whether the inspector's type carries a [`TrustedObserver`] declaration. Set only by the + /// constructors that require the declaration; true without an inspector. + trusted_inspector: bool, } impl MegaEvm { - /// Creates a new `MegaETH` EVM instance. - /// - /// # Parameters - /// - /// - `context`: The `MegaETH` context containing database, configuration, and `external_envs` - /// - `inspect`: The inspector to use for debugging and monitoring - /// - /// # Returns - /// - /// A new `Evm` instance configured with the provided context and inspector. - pub fn new(context: MegaContext) -> Self { - let spec = context.mega_spec(); - Self { - inner: revm::context::Evm::new_with_inspector( - context, - NoOpInspector, - MegaInstructions::new(spec), - PrecompilesMap::from_static(MegaPrecompiles::new_with_spec(spec).precompiles()), - ), - inspect: false, - } + /// Creates an EVM over `ctx`, without an inspector. + pub fn new(ctx: MegaContext) -> Self { + let spec = ctx.cfg().spec; + let inner = revm::context::Evm { + ctx, + inspector: NoOpInspector, + instruction: instructions::mega_instructions(spec.into()), + precompiles: OpPrecompiles::new_with_spec(spec), + frame_stack: FrameStack::new_prealloc(8), + }; + Self { inner, inspect: false, trusted_inspector: true } } } impl MegaEvm { - /// Creates a new `MegaETH` EVM instance with the given inspector enabled at runtime. - /// - /// # Parameters - /// - /// - `inspector`: The new inspector to use for debugging and monitoring + /// Replaces the inspector with a tool's. The new inspector runs on every alloy-evm + /// [`transact`](alloy_evm::Evm::transact) until it is disabled again. /// - /// # Returns - /// - /// A new `Evm` instance with the specified inspector enabled. + /// The inspector may rewrite what execution produces (see the `inspector` module), so the + /// EVM reports [`has_rewriting_inspector`](Self::has_rewriting_inspector) while it runs, and + /// block execution refuses it. pub fn with_inspector(self, inspector: I) -> MegaEvm { - let inner = revm::context::Evm::new_with_inspector( - self.inner.ctx, - inspector, - self.inner.instruction, - self.inner.precompiles, - ); - MegaEvm { inner, inspect: true } - } - - /// Creates a new `MegaETH` EVM instance with the inspector disabled at runtime. - /// - /// # Returns - /// - /// A new `Evm` instance with the inspector disabled. - pub fn without_inspector(self) -> MegaEvm { - let inner = revm::context::Evm::new_with_inspector( - self.inner.ctx, - NoOpInspector, - self.inner.instruction, - self.inner.precompiles, - ); - MegaEvm { inner, inspect: false } - } - - /// Sets the transaction runtime limits for the EVM. - pub fn with_tx_runtime_limits(self, tx_limits: EvmTxRuntimeLimits) -> Self { - let inner = revm::context::Evm { - ctx: self.inner.ctx.with_tx_runtime_limits(tx_limits), - inspector: self.inner.inspector, - instruction: self.inner.instruction, - precompiles: self.inner.precompiles, - frame_stack: self.inner.frame_stack, - }; - Self { inner, inspect: self.inspect } + MegaEvm { + inner: self.inner.with_inspector(inspector), + inspect: true, + trusted_inspector: false, + } } - /// Adds or overrides dynamic precompiles in the EVM. - /// - /// # Parameters - /// - /// - `dyn_precompiles`: The dynamic precompiles to add to the EVM, overriding the existing - /// precompiles if they already exist. - /// - /// # Returns - /// - /// A new `Evm` instance with the dynamic precompiles added. - fn with_dyn_precompiles(self, dyn_precompiles: HashMap) -> Self { - let mut precompiles = self.inner.precompiles; - // Apply the dynamic precompiles to the precompiles map. If the precompile already exists, - // it will be overridden with the dynamic precompile. - for (address, dyn_precompile) in dyn_precompiles { - precompiles.apply_precompile(&address, move |_| Some(dyn_precompile)); + /// Replaces the inspector with one whose type is declared a [`TrustedObserver`]: it writes + /// nothing back, so the transactions it observes are the ones the chain executes, and block + /// execution admits them. + pub fn with_trusted_inspector( + self, + inspector: I, + ) -> MegaEvm { + MegaEvm { + inner: self.inner.with_inspector(inspector), + inspect: true, + trusted_inspector: true, } - let inner = revm::context::Evm { - ctx: self.inner.ctx, - inspector: self.inner.inspector, - instruction: self.inner.instruction, - precompiles, - frame_stack: self.inner.frame_stack, - }; - Self { inner, inspect: self.inspect } } -} -impl MegaEvm { - /// Provides a reference to the block environment. + /// Whether the EVM runs an inspector that may rewrite what execution produces: an enabled + /// inspector that did not arrive through + /// [`with_trusted_inspector`](Self::with_trusted_inspector). /// - /// The block environment contains information about the current block being processed, - /// including block number, timestamp, gas limit, and other block-specific data. - #[inline] - pub fn block_env_ref(&self) -> &BlockEnv { - &self.ctx_ref().block + /// The admission gate block execution refuses a transaction on. + pub const fn has_rewriting_inspector(&self) -> bool { + self.inspect && !self.trusted_inspector } - /// Provides a mutable reference to the block environment. - /// - /// This allows modification of block environment data during EVM execution, - /// which is useful for testing and simulation scenarios. - #[inline] - pub fn block_env_mut(&mut self) -> &mut BlockEnv { - &mut self.ctx().block + /// The execution context. + pub const fn ctx(&self) -> &MegaContext { + &self.inner.ctx } - /// Provides a reference to the journaled state. - /// - /// The journaled state tracks all state changes during transaction execution, - /// enabling rollback capabilities and state management. - #[inline] - pub fn journaled_state(&self) -> &Journal { - &self.ctx_ref().journaled_state + /// The execution context, mutably. + pub const fn ctx_mut(&mut self) -> &mut MegaContext { + &mut self.inner.ctx } - /// Provides a mutable reference to the journaled state. - /// - /// This allows direct manipulation of the journaled state for advanced - /// use cases and testing scenarios. - #[inline] - pub fn journaled_state_mut(&mut self) -> &mut Journal { - &mut self.ctx().journaled_state + /// The inspector. + pub const fn inspector(&self) -> &INSP { + &self.inner.inspector } - /// Consumes self and returns the journaled state. - /// - /// This is useful when you need to extract the final state after EVM execution - /// and no longer need the EVM instance. - #[inline] - #[deprecated(note = "Use `into_inner` instead")] - pub fn into_journaled_state(self) -> Journal { - self.inner.ctx.inner.journaled_state + /// Whether alloy-evm's [`transact`](alloy_evm::Evm::transact) runs the inspector. + pub const fn is_inspecting(&self) -> bool { + self.inspect } - /// Consumes the `MegaEvm` instance and returns the inner EVM. - /// - /// This method is typically used after EVM execution when you need to access - /// the underlying EVM components and no longer require the `MegaEvm` wrapper. - #[inline] - #[allow(clippy::type_complexity)] - pub fn into_inner( - self, - ) -> revm::context::Evm< - MegaContext, - INSP, - MegaInstructions, - PrecompilesMap, - EthFrame, - > { + /// Consumes the EVM and returns the revm EVM it wraps. + pub(crate) fn into_inner(self) -> MegaInnerEvm { self.inner } } @@ -301,322 +160,368 @@ impl MegaEvm { impl MegaEvm where DB: Database, - INSP: Inspector>, + INSP: Inspector, EthInterpreter>, ExtEnvs: ExternalEnvTypes, { - /// Execute a transaction and return the outcome. If the inspector is set, it will be used to - /// inspect the transaction. - /// Users can use [`MegaEvm::with_inspector`] to set up a custom inspector. - /// Users can use [`MegaEvm::without_inspector`] to disable the inspector. - /// - /// # Parameters - /// - /// - `tx`: The transaction to execute - /// - /// # Returns - /// - /// The outcome of the transaction. + /// Executes `tx`, through the inspector when one is enabled, and returns its outcome: the + /// result and state, the gas by ledger, the usage the common execution layer counted and the + /// limit that stopped the transaction, if any. Nothing is committed. pub fn execute_transaction( &mut self, tx: MegaTransaction, ) -> Result> { - let ResultAndState { result, state } = if self.inspect { - InspectEvm::inspect_tx(self, tx)? - } else { - ExecuteEvm::transact(self, tx)? - }; - let additional_limit = self.ctx().additional_limit.borrow(); - let LimitUsage { data_size, kv_updates, compute_gas, state_growth } = - additional_limit.get_usage(); + let result_and_state = self.run_transaction(tx)?; + let layer = &self.inner.ctx.additional_limit; + let gas = MegaGasUsage::new(result_and_state.result.gas(), layer.history_gas_spent()); Ok(MegaTransactionOutcome { - result, - state, - data_size, - kv_updates, - compute_gas_used: compute_gas, - state_growth_used: state_growth, + result_and_state, + gas, + usage: layer.usage(), + limit_exceeded: layer.latched().copied(), }) } +} - /// Inspect a transaction and return the outcome. The inspector used is the one set up already - /// in the EVM. Use [`MegaEvm::with_inspector`] to set up a custom inspector. - /// - /// # Parameters - /// - /// - `tx`: The transaction to inspect - /// - /// # Returns - /// - /// The outcome of the transaction. - #[deprecated( - since = "1.0.2", - note = "Use `MegaEvm::execute_transaction` instead, which will automatically use the inspector if it is set up" - )] - pub fn inspect_transaction( +impl MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + /// Runs `tx` through the inspector when one is enabled, without committing. + fn run_transaction( &mut self, tx: MegaTransaction, - ) -> Result> { - let ResultAndState { result, state } = InspectEvm::inspect_tx(self, tx)?; - let additional_limit = self.ctx().additional_limit.borrow(); - let LimitUsage { data_size, kv_updates, compute_gas, state_growth } = - additional_limit.get_usage(); - Ok(MegaTransactionOutcome { - result, - state, - data_size, - kv_updates, - compute_gas_used: compute_gas, - state_growth_used: state_growth, - }) + ) -> Result, EVMError> { + let result = if self.inspect { + InspectEvm::inspect_tx(self, tx) + } else { + ExecuteEvm::transact(self, tx) + }; + result.map_err(map_op_err) } +} - /// Get the bucket IDs used during transaction execution. - /// - /// # Returns - /// - /// Returns the bucket IDs used during transaction execution. - pub fn get_accessed_bucket_ids(&self) -> Vec { - self.ctx_ref().dynamic_storage_gas_cost.borrow().get_bucket_ids() +/// The error a [`MegaEvm`] reports through revm's execution traits. +pub type MegaEvmError = EVMError; + +impl ExecuteEvm for MegaEvm { + type ExecutionResult = ExecutionResult; + type State = EvmState; + type Error = MegaEvmError; + type Tx = MegaTransaction; + type Block = BlockEnv; + + 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); + self.inner.ctx.on_new_tx(); + MegaHandler::<_, Self::Error, _>::new().run(self) + } + + fn finalize(&mut self) -> Self::State { + self.inner.ctx.journal_mut().finalize() + } + + fn replay( + &mut self, + ) -> Result, Self::Error> { + self.inner.ctx.on_new_tx(); + let result = MegaHandler::<_, Self::Error, _>::new().run(self)?; + Ok(ExecResultAndState::new(result, self.finalize())) } } -impl MegaEvm { - /// Get the block hashes used during transaction execution. - /// - /// # Returns +impl ExecuteCommitEvm + for MegaEvm +{ + fn commit(&mut self, state: Self::State) { + self.inner.ctx.db_mut().commit(state); + } +} + +impl InspectEvm for MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + type Inspector = INSP; + + 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); + self.inner.ctx.on_new_tx(); + MegaHandler::<_, Self::Error, _>::new().inspect_run(self) + } +} + +impl InspectCommitEvm for MegaEvm +where + DB: Database + DatabaseCommit, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ +} + +impl SystemCallEvm for MegaEvm { + fn system_call_one_with_caller( + &mut self, + caller: Address, + system_contract_address: Address, + data: Bytes, + ) -> Result { + self.inner.ctx.set_tx(MegaTransaction::new_system_tx_with_caller( + caller, + system_contract_address, + data, + )); + self.inner.ctx.on_new_tx(); + MegaHandler::<_, Self::Error, _>::new().run_system_call(self) + } +} + +impl InspectSystemCallEvm for MegaEvm +where + DB: Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + fn inspect_one_system_call_with_caller( + &mut self, + caller: Address, + system_contract_address: Address, + data: Bytes, + ) -> Result { + self.inner.ctx.set_tx(MegaTransaction::new_system_tx_with_caller( + caller, + system_contract_address, + data, + )); + self.inner.ctx.on_new_tx(); + MegaHandler::<_, Self::Error, _>::new().inspect_run_system_call(self) + } +} + +impl alloy_evm::Evm for MegaEvm +where + DB: alloy_evm::Database, + INSP: Inspector, EthInterpreter>, + ExtEnvs: ExternalEnvTypes, +{ + type DB = DB; + type Tx = MegaTransaction; + type Error = EVMError; + type HaltReason = OpHaltReason; + type Spec = MegaSpecId; + type BlockEnv = BlockEnv; + /// op-revm's precompile set for the base spec. /// - /// Returns the block hashes used during transaction execution. - pub fn get_accessed_block_hashes(&self) -> BTreeMap { - self.db_ref().get_accessed_block_hashes() + /// Provisional: the Satin precompile provider replaces this type when it lands, and code that + /// names `OpPrecompiles` through this associated type has no source-compatibility promise + /// across that change. + type Precompiles = OpPrecompiles; + type Inspector = INSP; + + fn block(&self) -> &BlockEnv { + self.ctx().block() + } + + fn cfg_env(&self) -> &CfgEnv { + self.ctx().mega_cfg() + } + + fn chain_id(&self) -> u64 { + self.ctx().mega_cfg().chain_id + } + + fn transact_raw( + &mut self, + tx: Self::Tx, + ) -> Result, Self::Error> { + self.run_transaction(tx) + } + + fn transact_system_call( + &mut self, + caller: Address, + contract: Address, + data: Bytes, + ) -> Result, Self::Error> { + SystemCallEvm::system_call_with_caller(self, caller, contract, data).map_err(map_op_err) + } + + fn finish(self) -> (Self::DB, EvmEnv) { + let (db, cfg_env, block_env) = self.into_inner().ctx.into_parts(); + (db, EvmEnv { cfg_env, block_env }) + } + + fn set_inspector_enabled(&mut self, enabled: bool) { + self.inspect = enabled; + } + + fn components(&self) -> (&Self::DB, &Self::Inspector, &Self::Precompiles) { + let evm = &self.inner; + (evm.ctx.db(), &evm.inspector, &evm.precompiles) + } + + fn components_mut(&mut self) -> (&mut Self::DB, &mut Self::Inspector, &mut Self::Precompiles) { + let evm = &mut self.inner; + (evm.ctx.db_mut(), &mut evm.inspector, &mut evm.precompiles) } } #[cfg(test)] mod tests { use super::*; - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use alloy_primitives::{address, Bytes, U256}; + use crate::test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}; + use alloy_evm::{Evm, EvmError}; + use alloy_op_evm::OpTx; + use alloy_primitives::{address, TxKind, U256}; use revm::{ - context::{ - result::{ExecResultAndState, ExecutionResult}, - ContextSetters, TxEnv, - }, + context::{result::InvalidTransaction, ContextSetters, TxEnv}, database::State, - inspector::NoOpInspector, - state::EvmState, - ExecuteCommitEvm, ExecuteEvm, InspectEvm, SystemCallEvm, + DatabaseRef, }; + use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; - const CALLER: Address = address!("4000000000000000000000000000000000000001"); - const CALLEE: Address = address!("5000000000000000000000000000000000000001"); + const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); + const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); - fn configure_context(db: DB) -> MegaContext { - let mut context = MegaContext::new(db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context + fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) } - fn tx_env() -> TxEnv { - TxEnv { + fn tx(value: U256) -> MegaTransaction { + OpTx(op_transaction(TxEnv { caller: CALLER, gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::ZERO, - data: Bytes::new(), + kind: TxKind::Call(CALLEE), + value, ..Default::default() - } + })) } - fn mega_tx() -> MegaTransaction { - let mut tx = MegaTransaction::new(tx_env()); - tx.enveloped_tx = Some(Bytes::new()); - tx + fn funded_db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()) } #[test] fn test_mega_evm_builder_chain_produces_working_evm() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let context = configure_context(&mut db); - let evm = MegaEvm::new(context); + let mut db = funded_db(); + let evm = MegaEvm::new(context(&mut db)); + assert!(!evm.is_inspecting()); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(777); - let evm = evm.with_tx_runtime_limits(limits); - assert_eq!(evm.ctx_ref().additional_limit.borrow().limits.tx_compute_gas_limit, 777); - - let evm = evm.with_dyn_precompiles(HashMap::default()); - let evm = evm.with_inspector(NoOpInspector); - let evm = evm.without_inspector(); + let mut evm = evm.with_inspector(NoOpInspector); + assert!(evm.is_inspecting()); + assert!(evm.transact_raw(tx(U256::ZERO)).unwrap().result.is_success()); let inner = evm.into_inner(); - assert_eq!(inner.ctx.block.gas_limit, u64::MAX); + assert_eq!(inner.ctx.spec(), MegaSpecId::SATIN); } #[test] fn test_alloy_evm_interface_methods_execute_transactions() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - assert_eq!(alloy_evm::Evm::chain_id(&evm), evm.ctx_ref().cfg.chain_id); - assert_eq!(alloy_evm::Evm::block(&evm).gas_limit, evm.ctx_ref().block.gas_limit); + let mut db = funded_db(); + let mut evm = MegaEvm::new( + context(&mut db).with_block(BlockEnv { gas_limit: 222_222, ..Default::default() }), + ); - alloy_evm::Evm::set_inspector_enabled(&mut evm, true); - assert!(evm.inspect); - let (_db_ref, _inspector, _precompiles) = alloy_evm::Evm::components(&evm); - let (_db_ref_mut, _inspector_mut, _precompiles_mut) = - alloy_evm::Evm::components_mut(&mut evm); + assert_eq!(evm.chain_id(), evm.ctx().cfg().chain_id); + assert_eq!(evm.cfg_env().spec, MegaSpecId::SATIN); + assert_eq!(evm.block().gas_limit, 222_222); - let result = alloy_evm::Evm::transact_raw(&mut evm, mega_tx()).unwrap(); - assert!(result.result.is_success()); + evm.set_inspector_enabled(true); + assert!(evm.is_inspecting()); + evm.set_inspector_enabled(false); + let (_db, _inspector, _precompiles) = evm.components(); + let (_db, _inspector, _precompiles) = evm.components_mut(); - let system_call = - alloy_evm::Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()).unwrap(); - assert!(system_call.result.is_success()); + assert!(evm.transact_raw(tx(U256::ZERO)).unwrap().result.is_success()); + let system_call = Evm::transact_system_call(&mut evm, CALLER, CALLEE, Bytes::new()); + assert!(system_call.unwrap().result.is_success()); - let (_db_back, evm_env) = alloy_evm::Evm::finish(evm); - assert_eq!(evm_env.cfg_env.spec, MegaSpecId::REX4); + let (_db, evm_env) = evm.finish(); + assert_eq!(evm_env.cfg_env.spec, MegaSpecId::SATIN); + assert_eq!(evm_env.cfg_env.tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); + assert_eq!(evm_env.block_env.gas_limit, 222_222); } #[test] fn test_revm_execute_one_finalize_commit_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let block = revm::context::BlockEnv { gas_limit: 222_222, ..Default::default() }; - ExecuteEvm::set_block(&mut evm, block); - assert_eq!(evm.block_env_ref().gas_limit, 222_222); - - let one: ExecutionResult = - ExecuteEvm::transact_one(&mut evm, mega_tx()).unwrap(); - assert!(one.is_success()); + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + ExecuteEvm::set_block(&mut evm, BlockEnv { gas_limit: 222_222, ..Default::default() }); + assert_eq!(evm.block().gas_limit, 222_222); + + let result = ExecuteEvm::transact_one(&mut evm, tx(U256::from(7))).unwrap(); + assert!(result.is_success()); let state = ExecuteEvm::finalize(&mut evm); ExecuteCommitEvm::commit(&mut evm, state); + drop(evm); + + assert_eq!(db.basic_ref(CALLEE).unwrap().unwrap().balance, U256::from(7)); } #[test] fn test_revm_replay_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - evm.ctx().set_tx(mega_tx()); - let replay: ExecResultAndState, EvmState> = - ExecuteEvm::replay(&mut evm).unwrap(); + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + evm.ctx_mut().set_tx(tx(U256::ZERO)); + let replay = ExecuteEvm::replay(&mut evm).unwrap(); assert!(replay.result.is_success()); + assert!(replay.state.contains_key(&CALLER)); } #[test] fn test_revm_inspect_one_tx_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - InspectEvm::set_inspector(&mut evm, NoOpInspector); - let inspected: ExecutionResult = - InspectEvm::inspect_one_tx(&mut evm, mega_tx()).unwrap(); - assert!(inspected.is_success()); - } - - #[test] - fn test_revm_system_call_with_caller_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let system_call: ExecutionResult = - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - assert!(system_call.is_success()); - } - - #[test] - fn test_transact_system_call_with_gas_limit_uses_passed_value() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) - .unwrap(); - assert!(result.result.is_success()); - // The custom gas limit must be applied to the underlying tx. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 123_456_789); - } - - #[test] - fn test_default_system_call_keeps_upstream_30m_gas_limit() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context.block.gas_limit = 100_000_000; - let mut evm = MegaEvm::new(context); - - // The default system-call entry point must NOT be widened by REX5 — only the - // explicit `transact_system_call_with_gas_limit` path should pick up the live - // block budget. This preserves byte-level behavior of EIP-2935 / EIP-4788 - // pre-block calls across all specs. - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - // Literal, not `SYSTEM_CALL_GAS_LIMIT_FLOOR`: this assertion verifies revm's - // upstream hardcoded default. If upstream ever drifts from our floor, this - // test should fail loudly rather than be auto-aligned by our constant. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 30_000_000); - } - - #[test] - fn test_mega_evm_exposes_state_wrapper_block_hashes() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(7, B256::from([7_u8; 32])); - - let evm = MegaEvm::new(configure_context(&mut state)); - assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); - } - - #[test] - fn test_convenience_execution_methods_work() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)).with_inspector(NoOpInspector); - - let executed = evm.execute_transaction(mega_tx()).unwrap(); - assert!(executed.result.is_success()); - - #[allow(deprecated)] - let inspected = evm.inspect_transaction(mega_tx()).unwrap(); - assert!(inspected.result.is_success()); + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)) + .with_inspector(TracingInspector::new(TracingInspectorConfig::default_parity())); + let result = InspectEvm::inspect_one_tx(&mut evm, tx(U256::ZERO)).unwrap(); + assert!(result.is_success()); + + // The arena starts with one placeholder root node; the call fills it in. + let traces = evm.inspector().traces(); + assert_eq!(traces.nodes().len(), 1, "one call frame"); + assert_eq!(traces.nodes()[0].trace.address, CALLEE); + + // A fresh inspector replaces the one that recorded the call. + InspectEvm::set_inspector( + &mut evm, + TracingInspector::new(TracingInspectorConfig::default_parity()), + ); + assert_eq!(evm.inspector().traces().nodes()[0].trace.address, Address::ZERO); } #[test] fn test_execute_transaction_fails_with_insufficient_balance() { let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); + let mut evm = MegaEvm::new(context(&mut db)); - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::from(1_000_000), - data: Bytes::new(), - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); + let err = evm.transact_raw(tx(U256::from(1_000_000))).unwrap_err(); + let invalid = + err.as_invalid_tx_err().and_then(alloy_evm::InvalidTxError::as_invalid_tx_err); + assert!(matches!(invalid, Some(InvalidTransaction::LackOfFundForMaxFee { .. })), "{err:?}"); + } - let result = evm.execute_transaction(tx); - assert!(result.is_err()); + #[test] + fn test_finish_returns_the_database() { + let mut state = State::builder().with_database(funded_db()).build(); + let mut evm = MegaEvm::new(context(&mut state)); + assert!(Evm::transact_commit(&mut evm, tx(U256::from(5))).unwrap().is_success()); + let (db, _) = evm.finish(); + assert_eq!( + db.cache.accounts[&CALLEE].account.as_ref().unwrap().info.balance, + U256::from(5) + ); } } diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs deleted file mode 100644 index d1bc95e43..000000000 --- a/crates/mega-evm/src/evm/precompiles.rs +++ /dev/null @@ -1,758 +0,0 @@ -//! Custom precompiles for `MegaETH` EVM. -//! -//! This module provides custom precompile implementations with `MegaETH`-specific -//! gas cost overrides. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{boxed::Box, string::String, sync::Arc}; - -use crate::{ExternalEnvTypes, MegaContext, MegaSpecId}; -use alloy_evm::{ - precompiles::{DynPrecompile, PrecompilesMap}, - Database, -}; -use delegate::delegate; -use once_cell::race::OnceBox; -use op_revm::{OpContext, OpSpecId}; -use revm::{ - context::Cfg, - context_interface::ContextTr, - handler::{EthPrecompiles, PrecompileProvider}, - interpreter::{Gas, InputsImpl, InterpreterResult}, - precompile::Precompiles, - primitives::{Address, HashMap}, -}; - -/// `MegaETH` precompile provider with custom gas cost overrides. -#[derive(Debug, Clone)] -pub struct MegaPrecompiles { - /// Inner precompile provider from op-revm. - inner: EthPrecompiles, - /// The `MegaETH` specification ID. - spec: MegaSpecId, -} - -impl MegaPrecompiles { - /// Create a new precompile provider with the given `MegaETH` spec. - #[inline] - pub fn new_with_spec(spec: MegaSpecId) -> Self { - // Get base precompiles from op-revm. An alias spec is grouped with its `behavior()` - // target so it gets exactly the target's precompiles; the grouping must agree with - // `behavior()`, pinned by `test_alias_specs_use_their_behavior_targets_precompiles`. - let inner = match spec { - MegaSpecId::EQUIVALENCE | MegaSpecId::MINI_REX_1 => op_revm::precompiles::isthmus(), - MegaSpecId::MINI_REX | MegaSpecId::MINI_REX_2 => mini_rex(), - MegaSpecId::REX | - MegaSpecId::REX1 | - MegaSpecId::REX2 | - MegaSpecId::REX3 | - MegaSpecId::REX4 | - MegaSpecId::REX5 | - MegaSpecId::REX6 | - MegaSpecId::REX7 => rex(), - }; - - Self { inner: EthPrecompiles { precompiles: inner, spec: spec.into_eth_spec() }, spec } - } - - /// Get the precompiles for the current spec. - /// - /// This method returns precompiles with custom gas cost overrides for `MINI_REX` spec. - #[inline] - pub fn precompiles(&self) -> &'static Precompiles { - // For now, just use the inner precompiles - // Custom gas costs will be applied in the run() method - self.inner.precompiles - } -} - -/// Precompiles for the `REX` spec. -pub fn rex() -> &'static Precompiles { - static INSTANCE: OnceBox = OnceBox::new(); - INSTANCE.get_or_init(|| Box::new(mini_rex().clone())) -} - -/// Precompiles for the `MINI_REX` spec. -pub fn mini_rex() -> &'static Precompiles { - static INSTANCE: OnceBox = OnceBox::new(); - INSTANCE.get_or_init(|| { - let mut precompiles = op_revm::precompiles::isthmus().clone(); - // Use the OSAKA modexp precompile for MINI_REX - precompiles - .extend([revm::precompile::modexp::OSAKA, kzg_point_evaluation::KZG_POINT_EVALUATION]); - Box::new(precompiles) - }) -} - -/// Customized KZG point evaluation precompile module. -pub mod kzg_point_evaluation { - use revm::{ - precompile::{PrecompileError, PrecompileWithAddress}, - primitives::Address, - }; - - /// Address of the KZG point evaluation precompile (re-export of the upstream - /// constant). Local re-export so call-sites can refer to `GAS_COST` and - /// `ADDRESS` through the same module path. - pub const ADDRESS: Address = revm::precompile::kzg_point_evaluation::ADDRESS; - - /// Gas cost for the KZG point evaluation precompile. - pub const GAS_COST: u64 = 100_000; - - /// KZG point evaluation precompile. This is the modified version of the original precompile - /// with a custom gas cost. - pub const KZG_POINT_EVALUATION: PrecompileWithAddress = - PrecompileWithAddress(ADDRESS, |input, gas_limit| { - if gas_limit < GAS_COST { - return Err(PrecompileError::OutOfGas); - } - let mut output = revm::precompile::kzg_point_evaluation::run(input, gas_limit)?; - output.gas_used = GAS_COST; - Ok(output) - }); -} - -impl PrecompileProvider for MegaPrecompiles -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 - } - - delegate! { - to self.inner { - fn run( - &mut self, - context: &mut CTX, - address: &Address, - inputs: &InputsImpl, - is_static: bool, - gas_limit: u64, - ) -> Result, String>; - fn warm_addresses(&self) -> Box>; - fn contains(&self, address: &Address) -> bool; - } - } -} - -impl Default for MegaPrecompiles { - fn default() -> Self { - Self::new_with_spec(MegaSpecId::EQUIVALENCE) - } -} - -impl PrecompileProvider> - for PrecompilesMap -{ - type Output = InterpreterResult; - - #[inline] - fn set_spec(&mut self, _spec: OpSpecId) -> bool { - // The table is already correct and unchanged: MegaEvm bakes it at construction - // from MegaSpecId. Rebuilding from OpSpecId would lose Mega-specific overrides - // because all current Mega specs map to the same OpSpecId. - false - } - - #[inline] - fn run( - &mut self, - context: &mut MegaContext, - address: &Address, - inputs: &InputsImpl, - is_static: bool, - gas_limit: u64, - ) -> Result, String> { - // REX5+: cap forwarded gas at the current compute-gas remaining so a precompile - // cannot spend more compute gas than the per-frame / TX-level budget permits. - // Pre-REX5 keeps the original forwarding semantics for backward compatibility. - let is_rex5_enabled = context.spec.is_enabled(MegaSpecId::REX5); - let effective_gas_limit = if is_rex5_enabled { - let remaining = context.additional_limit.borrow().current_call_remaining_compute_gas(); - gas_limit.min(remaining) - } else { - gas_limit - }; - - let maybe_output = PrecompileProvider::>::run( - self, - context, - address, - inputs, - is_static, - effective_gas_limit, - )?; - - Ok(maybe_output.map(|mut output| { - // Normalize the returned Gas back to the caller's original `gas_limit` budget - // ONLY on `is_ok_or_revert` paths — those are the paths where the caller's - // refund logic (`EthFrame::return_result` and `Handler::last_frame_result`, - // both gated on `is_ok_or_revert()`) actually consumes `gas.remaining()`. - // - // Halt paths (`PrecompileOOG`, `PrecompileError`) skip the refund entirely: - // the parent burns the full forwarded `gas_limit` regardless of the Gas - // object's reported `remaining`. Leaving revm's vanilla `Gas::new(effective)` - // on those paths keeps the post-cap halt result semantically identical to - // an uncapped precompile OOG, matches what tracers / inspectors expect, and - // makes the "cap forced an OOG" behavior locally indistinguishable from - // "user just forwarded too little gas". - // - // The normalize preserves the precompile's `refunded()` value (today every - // standard revm precompile leaves refunded == 0, but custom precompiles - // injected via `PrecompilesMap` may set a refund, and a future EIP - // precompile could also). Memory expansion gas is not preserved because - // precompiles do not allocate from `Gas::memory` — memory expansion is - // the caller-interpreter's responsibility and is settled before the - // precompile is invoked. - if is_rex5_enabled && output.result.is_ok_or_revert() { - let spent = output.gas.spent(); - let refunded = output.gas.refunded(); - let mut normalized = Gas::new(gas_limit); - normalized.set_spent(spent); - normalized.record_refund(refunded); - output.gas = normalized; - } - // Compute-gas recording on REX5+: - // - // * Success / revert: revm called `record_cost`, so `spent()` already reflects the - // actually-consumed amount. Use it. - // * Fixed-cost precompile that reached past its wrapper gas pre-check (today: KZG with - // `limit() >= GAS_COST`): record the declared fixed cost. revm's `PrecompileError` - // halt still consumes the parent's forwarded `gas_limit` from the EVM-gas meter, so - // compute-gas here is intentionally a separate number from the EVM-gas burn. - // * All other error paths (non-KZG, or KZG with `limit() < GAS_COST` meaning the - // wrapper's pre-check itself OOG'd before verification could run): revm did not call - // `record_cost`, so `spent() == 0`. The parent still permanently loses the forwarded - // amount, so record `limit()` to match the EVM-gas burn. - if is_rex5_enabled { - let compute_gas = if output.result.is_ok_or_revert() { - output.gas.spent() - } else if address == &kzg_point_evaluation::ADDRESS && - output.gas.limit() >= kzg_point_evaluation::GAS_COST - { - // KZG with the wrapper's `gas_limit < GAS_COST` pre-check passed: upstream - // verification ran and returned a non-OOG error - // (`BlobInvalidInputLength` / `BlobMismatchedVersion` / - // `BlobVerifyKzgProofFailed`). Charge the fixed cost regardless of which - // error variant fired. Using the structural predicate - // (`limit() >= GAS_COST`) instead of an error-variant match keeps this arm - // robust against upstream KZG adding new non-OOG variants. - kzg_point_evaluation::GAS_COST - } else { - output.gas.limit() - }; - context.additional_limit.borrow_mut().record_compute_gas(compute_gas); - } else if context.spec.is_enabled(MegaSpecId::MINI_REX) { - context.additional_limit.borrow_mut().record_compute_gas(output.gas.spent()); - } - output - })) - } - - #[inline] - fn warm_addresses(&self) -> Box> { - PrecompileProvider::>::warm_addresses(self) - } - - #[inline] - fn contains(&self, address: &Address) -> bool { - PrecompileProvider::>::contains(self, address) - } -} - -/// A builder function to build dynamic precompiles for a given [`MegaSpecId`]. -/// -/// The spec passed to the builder is the behavior projection and is never an alias spec: -/// dynamic precompiles are execution semantics, so during an alias window the builder is -/// invoked with the alias's behavior target (e.g. `EQUIVALENCE` while `MINI_REX_1` is the -/// resolved spec). -pub type DynPrecompilesBuilder = - Arc HashMap + Send + Sync>; - -#[cfg(test)] -mod tests { - #[cfg(not(feature = "std"))] - use alloc as std; - use std::{rc::Rc, vec::Vec}; - - use super::{kzg_point_evaluation::GAS_COST, mini_rex, rex, MegaPrecompiles}; - use crate::{ - test_utils::MemoryDatabase, AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaSpecId, - }; - use alloy_evm::precompiles::PrecompilesMap; - use alloy_primitives::Bytes; - use core::cell::RefCell; - use revm::{ - handler::PrecompileProvider, - interpreter::{InputsImpl, InstructionResult}, - }; - use sha2::{Digest, Sha256}; - - /// Every alias spec must get exactly its `behavior()` target's precompile set — the - /// match in `new_with_spec` states the alias→target mapping a second time, and this - /// test is the reconciliation between the two. The sets are `&'static`, so pointer - /// identity is the exact form of "same set". - #[test] - fn test_alias_specs_use_their_behavior_targets_precompiles() { - for spec in MegaSpecId::ALL { - if !spec.is_alias() { - continue; - } - let alias = MegaPrecompiles::new_with_spec(*spec); - let target = MegaPrecompiles::new_with_spec(spec.behavior()); - assert!( - core::ptr::eq(alias.precompiles(), target.precompiles()), - "{spec:?} precompiles diverge from its behavior target {:?}", - spec.behavior(), - ); - } - } - - /// Generate valid KZG Point Evaluation test data from EIP-4844 test vectors. - fn generate_kzg_test_input() -> InputsImpl { - let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); - let mut versioned_hash = Sha256::digest(&commitment).to_vec(); - versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG - let z = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000") - .unwrap(); - let y = hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9") - .unwrap(); - let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); - - let mut input = Vec::new(); - input.extend_from_slice(&versioned_hash); - input.extend_from_slice(&z); - input.extend_from_slice(&y); - input.extend_from_slice(&commitment); - input.extend_from_slice(&proof); - - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - InputsImpl { - target_address: address, - bytecode_address: Some(address), - caller_address: address, - input: revm::interpreter::CallInput::Bytes(Bytes::from(input)), - call_value: Default::default(), - } - } - - /// Mirror of `generate_kzg_test_input()` but with the last byte of the proof - /// flipped — structurally valid (192 bytes, matching versioned hash) but - /// upstream verification returns `PrecompileError::BlobVerifyKzgProofFailed`. - fn generate_invalid_proof_kzg_test_input() -> InputsImpl { - let mut inputs = generate_kzg_test_input(); - let bytes = match inputs.input { - revm::interpreter::CallInput::Bytes(b) => b, - _ => panic!("expected Bytes"), - }; - let mut buf = bytes.to_vec(); - let last = buf.len() - 1; - buf[last] ^= 0x01; - inputs.input = revm::interpreter::CallInput::Bytes(Bytes::from(buf)); - inputs - } - - fn set_spec_for_context( - precompiles_map: &mut PrecompilesMap, - _context: &MegaContext, - spec: op_revm::OpSpecId, - ) -> bool { - >>::set_spec( - precompiles_map, - spec, - ) - } - - #[test] - fn test_rex_and_mini_rex_precompiles_have_distinct_statics() { - assert!(!core::ptr::eq(rex(), mini_rex())); - } - - #[test] - fn test_kzg_precompile_sufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - assert!(result.is_ok(), "Precompile should succeed with sufficient gas"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_exact_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST); - assert!(result.is_ok(), "Precompile should succeed with exact GAS_COST"); - let output = result.unwrap().unwrap(); - assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_set_spec_preserves_mega_kzg_override() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - - let changed = - set_spec_for_context(&mut precompiles_map, &context, op_revm::OpSpecId::ISTHMUS); - assert!(!changed, "Mega precompile table must remain unchanged"); - - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - } - - #[test] - fn test_kzg_precompile_insufficient_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 50_000); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_one_below_gas_limit() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST - 1); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - #[test] - fn test_kzg_precompile_zero_gas() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 0); - assert!(result.is_ok(), "Should not panic"); - let output = result.unwrap(); - assert!(output.is_some(), "Precompile should return Some(result)"); - let interpreter_result = output.unwrap(); - assert!( - matches!(interpreter_result.result, InstructionResult::PrecompileOOG), - "Result should be PrecompileOOG" - ); - } - - /// Replaces the context's `additional_limit` with one whose `tx_compute_gas_limit` - /// is set to `limit`, so tests can exercise the REX5 compute-gas cap path with a - /// small remaining budget without having to pre-record large gas amounts. - fn set_tx_compute_gas_limit( - context: &mut MegaContext, - spec: MegaSpecId, - limit: u64, - ) { - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: limit, - ..EvmTxRuntimeLimits::from_spec(spec) - }; - context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); - } - - #[test] - fn test_kzg_precompile_rex5_compute_gas_cap_succeeds() { - // REX5: forward gas_limit > GAS_COST > remaining compute. Cap should engage but - // the precompile still fits within the remaining compute budget, so it succeeds. - // Caller-visible Gas must be normalized back to the original gas_limit. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST + 1_000); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - // Spent reflects the precompile's actual cost. - assert_eq!(output.gas.spent(), GAS_COST); - // Limit was normalized back to the caller's forwarded gas so the caller sees the - // correct refund (forwarded_gas - GAS_COST) instead of (effective_gas_limit - GAS_COST). - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - // The compute-gas tracker records the actual spent. - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, GAS_COST,); - } - - #[test] - fn test_kzg_precompile_rex5_compute_gas_cap_oogs() { - // Cap forces PrecompileOOG. Compute is charged `output.gas.limit()` - // (= remaining budget under the cap), exactly exhausting the meter. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - let compute_gas_limit = GAS_COST - 1; - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, compute_gas_limit); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, 1_000_000); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::PrecompileOOG)); - assert_eq!(output.gas.spent(), 0); - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, compute_gas_limit); - } - - #[test] - fn test_kzg_precompile_rex5_no_cap_when_remaining_sufficient() { - // REX5: when remaining compute already exceeds the forwarded gas_limit, the cap - // is a no-op and the path behaves identically to pre-REX5. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 200_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - } - - #[test] - fn test_kzg_precompile_rex5_cap_at_exact_gas_cost() { - // REX5 boundary: remaining compute equals exactly GAS_COST. The precompile must - // succeed (cost == effective_gas_limit), spending GAS_COST, with normalization - // yielding remaining = gas_limit - GAS_COST. - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - assert_eq!(output.gas.remaining(), forwarded_gas - GAS_COST); - assert_eq!(context.additional_limit.borrow().get_usage().compute_gas, GAS_COST); - } - - /// REX5 boundary mirror of `test_kzg_precompile_rex5_cap_at_exact_gas_cost`, - /// but with an invalid-proof input so upstream returns - /// `BlobVerifyKzgProofFailed`. `tx_compute_gas_limit == GAS_COST` forces the - /// outer cap to `effective_gas_limit == GAS_COST`, so the wrapper's - /// `gas_limit < GAS_COST` pre-check passes by exactly one, upstream KZG runs - /// verification, fails on the flipped proof, and revm constructs the failure - /// `Gas` with `Gas::new(effective_gas_limit)` — leaving `output.gas.limit() == - /// GAS_COST` because halt paths skip the success-side normalization to the - /// caller's original `gas_limit`. Recorded compute-gas must equal `GAS_COST`. - /// - /// Lives in the inline unit-test module rather than - /// `tests/rex5/precompile_compute_gas.rs` because the integration helper - /// cannot reliably hit `remaining == GAS_COST` at the precompile call site: - /// opcode-level compute-gas consumed by a wrapper contract's MSTORE / PUSH / - /// CALL sequence shifts the actual `remaining` below `tx_compute_gas_limit` - /// by a brittle amount. Direct `precompiles_map.run()` bypasses that - /// pre-work and gives an exact boundary. - #[test] - fn test_kzg_precompile_rex5_cap_at_exact_gas_cost_fail() { - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX5, GAS_COST); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX5).precompiles(), - ); - let inputs = generate_invalid_proof_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - // Upstream rejects the invalid proof with `BlobVerifyKzgProofFailed` → - // `InstructionResult::PrecompileError` (NOT `PrecompileOOG`). - assert!( - matches!(output.result, InstructionResult::PrecompileError), - "expected PrecompileError on invalid-proof at the cap boundary; got {:?}", - output.result - ); - // Halt paths skip the success-side normalization, so output.gas keeps revm's - // vanilla `Gas::new(effective_gas_limit)`. effective_gas_limit was capped to - // exactly GAS_COST, so limit() == GAS_COST. spent() is 0 because revm did not - // call record_cost on the error path. - assert_eq!(output.gas.limit(), GAS_COST); - assert_eq!(output.gas.spent(), 0); - // Joint invariant pinned here: result variant (PrecompileError) + limit value - // (GAS_COST) + recorded compute-gas (GAS_COST) at the exact boundary where the - // fixed-cost arm's `limit() >= GAS_COST` predicate transitions. - assert_eq!( - context.additional_limit.borrow().get_usage().compute_gas, - GAS_COST, - "at the exact-cap boundary on a verification failure, the recorded \ - compute-gas must equal GAS_COST" - ); - } - - /// End-to-end verification that the REX5+ `Gas` normalization on `PrecompileOOG` does NOT - /// affect caller gas accounting. - /// - /// Context: the REX5+ precompile wrapper re-wraps the returned `Gas` to use the - /// caller's original `gas_limit` on success and revert paths so the caller-side - /// `erase_cost(remaining)` refund accounts for the full forwarded budget minus - /// actual spent. The OOG path leaves revm's vanilla `Gas::new(effective_gas_limit)` - /// in place — `PrecompileOOG` is a halt (`return_error!`, not `return_revert!`), - /// so neither `EthFrame::return_result` (parent CALL) nor `Handler::last_frame_result` - /// (top-level TX) calls `erase_cost` for it. The caller is meant to burn the - /// forwarded gas regardless of the Gas object's reported remaining. - /// - /// This test pins that behavior: a top-level TX directly invoking KZG with the cap - /// forcing OOG must consume the full `tx.gas_limit`, NOT refund the user. - #[test] - fn test_kzg_precompile_rex5_oog_via_cap_burns_full_tx_gas() { - use crate::{MegaEvm, MegaTransaction}; - use alloy_primitives::{address, Bytes as BytesT, U256}; - use revm::context::{tx::TxEnvBuilder, BlockEnv, ContextSetters}; - - let caller = address!("0000000000000000000000000000000000600000"); - - let mut db = MemoryDatabase::default().account_balance(caller, U256::from(10_000_000)); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - // Tight TX-level compute-gas budget that's smaller than KZG's GAS_COST. - let tx_limits = EvmTxRuntimeLimits { - tx_compute_gas_limit: GAS_COST - 1, - ..EvmTxRuntimeLimits::from_spec(MegaSpecId::REX5) - }; - context.additional_limit = - Rc::new(RefCell::new(AdditionalLimit::new(MegaSpecId::REX5, tx_limits))); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - // Build a valid KZG-input calldata so the precompile would proceed up to its - // gas-cost check (which is the OOG trigger under the cap). - let valid_kzg_input = match generate_kzg_test_input().input { - revm::interpreter::CallInput::Bytes(b) => b, - _ => panic!("expected Bytes"), - }; - - let tx_gas_limit = 1_000_000u64; - let tx = TxEnvBuilder::default() - .caller(caller) - .call(revm::precompile::kzg_point_evaluation::ADDRESS) - .gas_limit(tx_gas_limit) - .gas_price(1) - .data(valid_kzg_input) - .build_fill(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(BytesT::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - - // The TX must halt (precompile OOG'd because cap forced effective_gas_limit < GAS_COST). - assert!(!result.result.is_success(), "tx must halt: cap forced precompile OOG",); - // Critical invariant: the receipt's gas_used reports the FULL tx.gas_limit. If - // the Gas-normalization breaks refund accounting on the OOG path, gas_used would - // be far smaller (sender refunded most of tx.gas_limit despite the halt). - assert_eq!( - result.result.gas_used(), - tx_gas_limit, - "OOG'd precompile call must burn the full tx.gas_limit (normalization must NOT \ - leak a refund through the halt path)", - ); - } - - #[test] - fn test_kzg_precompile_pre_rex5_does_not_cap() { - // Pre-REX5 (REX4): the cap is intentionally disabled for backward compatibility. - // Even with a very small tx_compute_gas_limit, the precompile is invoked with - // the original forwarded gas; compute-gas overshoot is detected only after the - // fact (the existing behavior). - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - set_tx_compute_gas_limit(&mut context, MegaSpecId::REX4, GAS_COST - 1); - let mut precompiles_map = PrecompilesMap::from_static( - MegaPrecompiles::new_with_spec(MegaSpecId::REX4).precompiles(), - ); - let inputs = generate_kzg_test_input(); - let address = revm::precompile::kzg_point_evaluation::ADDRESS; - let forwarded_gas = 500_000u64; - - let result = precompiles_map.run(&mut context, &address, &inputs, true, forwarded_gas); - let output = result.expect("run ok").expect("Some output"); - // Precompile runs with full forwarded gas and succeeds, spending GAS_COST. - // The post-hoc record_compute_gas call pushes the tracker over the limit, but - // that detection happens via check_limit elsewhere, not in this path. - assert!(matches!(output.result, InstructionResult::Return)); - assert_eq!(output.gas.spent(), GAS_COST); - assert_eq!(output.gas.limit(), forwarded_gas); - } -} diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index bbe6cf129..7e75c41b4 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -1,195 +1,185 @@ -use alloy_evm::block::StateChangeSource; -pub use alloy_evm::InvalidTxError; -use alloy_primitives::Address; -pub use op_revm::{OpHaltReason, OpTransactionError}; -use revm::{context::result::ExecutionResult, state::EvmState}; -pub use revm::{ - context::result::{EVMError, InvalidTransaction}, - context_interface::{ - result::HaltReason as EthHaltReason, transaction::TransactionError as TransactionErrorTr, - }, -}; -use serde::{Deserialize, Serialize}; - -use crate::VolatileDataAccess; - -/// The execution outcome of a transaction in `MegaETH`. +//! What a Satin transaction reports: its gas by ledger. +//! +//! A transaction pays from the EIP-8037 pools (the reservoir first, then regular gas) on three +//! ledgers, counted apart: +//! +//! - **regular**: execution. It is the compute gas the resource limits meter. +//! - **state**: bytes added to the world state (EIP-8037 state gas). +//! - **history**: bytes appended to the chain's history (logs, deployed code, write records, the +//! transaction body). +//! +//! State or history gas that spilled from the reservoir onto regular gas stays on its own ledger, +//! so it is not compute. The ledgers are raw spend, before the refund; the receipt reports +//! [`gas_used`](MegaGasUsage::gas_used), which is their sum less the refund, at least the EIP-7623 +//! floor. + +use revm::context::result::{ResultAndState, ResultGas}; + +use crate::{LimitCheck, LimitUsage, MegaHaltReason}; + +/// What executing one transaction produced: revm's result and state, and what `MegaETH` counts +/// beside them. /// -/// This struct contains additional information about the transaction execution on top of the -/// standard EVM's execution result and state. -#[derive(Debug, Clone)] +/// Derefs to the [`ResultAndState`], so `outcome.result` and `outcome.state` read through. +#[derive(Clone, Debug)] pub struct MegaTransactionOutcome { - /// The transaction execution result. - pub result: ExecutionResult, - /// The post-execution evm state. - pub state: EvmState, - /// The data size usage in bytes. - pub data_size: u64, - /// The number of KV updates. - pub kv_updates: u64, - /// The compute gas used. - pub compute_gas_used: u64, - /// The state growth used. - pub state_growth_used: u64, + /// The execution result and the post-execution state. + pub result_and_state: ResultAndState, + /// The gas by ledger, and what the receipt reports. + pub gas: MegaGasUsage, + /// The data-size bytes and write records the transaction kept. The KV count a node reports + /// is [`LimitUsage::write_records`]. + pub usage: LimitUsage, + /// The transaction-level limit that stopped the transaction, if one did. The result is then a + /// revert whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the + /// output, tells a limit stop from a contract reverting with the same bytes. + pub limit_exceeded: Option, } -/// The execution outcome of system call in `MegaETH`. -#[derive(Debug, Clone)] -pub struct MegaSystemCallOutcome { - /// Source of the state change - pub source: StateChangeSource, - /// The post-call evm state - pub state: EvmState, -} +impl core::ops::Deref for MegaTransactionOutcome { + type Target = ResultAndState; -/// `MegaETH` transaction validation error type. -/// -/// TODO: This is currently a type alias due to constraints from `op_revm::OpHandler`. -/// `OpHandler` requires `ERROR: From`, but we cannot satisfy this -/// for `EVMError` due to Rust's orphan rules. -/// -/// To add custom transaction error variants, we need to: -/// 1. Stop using `OpHandler` directly -/// 2. Implement all handler methods manually without delegating to `OpHandler` -/// 3. Then we can use a custom enum like: ``` pub enum MegaTransactionError { -/// Base(OpTransactionError), CustomVariant, } ``` -pub type MegaTransactionError = OpTransactionError; - -/// `MegaETH` halt reason type, with additional MegaETH-specific halt reasons. -/// -/// It is a wrapper around `OpHaltReason`, which internally wraps `EthHaltReason`. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum MegaHaltReason { - /// Base [`OpHaltReason`] - Base(OpHaltReason), - /// Data limit exceeded - DataLimitExceeded { - /// The configured data limit - limit: u64, - /// The actual data generated - actual: u64, - }, - /// KV update limit exceeded - KVUpdateLimitExceeded { - /// The configured KV update limit - limit: u64, - /// The actual KV update count - actual: u64, - }, - /// Compute gas limit exceeded - ComputeGasLimitExceeded { - /// The configured compute gas limit - limit: u64, - /// The actual compute gas usage - actual: u64, - }, - /// State growth limit exceeded - StateGrowthLimitExceeded { - /// The configured state growth limit - limit: u64, - /// The actual state growth usage - actual: u64, - }, - /// System transaction's callee is not in the whitelist - SystemTxInvalidCallee { - /// address called - callee: Address, - }, - /// Out of gas due to volatile data access limit enforcement. - /// The transaction exceeded the compute gas limit imposed after accessing volatile data - /// (block environment, beneficiary, or oracle contract). - VolatileDataAccessOutOfGas { - /// Bitflags indicating which volatile data was accessed. - /// Can check specific accesses using `has_block_env_access()`, - /// `has_beneficiary_balance_access()`, `has_oracle_access()` - access_type: VolatileDataAccess, - /// The effective detained compute gas limit that was exceeded. - /// In REX4+ this is `usage_at_access + cap` (relative); pre-REX4 it equals the raw cap - /// (absolute). Always satisfies `actual > limit`. - limit: u64, - /// The actual compute gas usage - actual: u64, - }, + fn deref(&self) -> &Self::Target { + &self.result_and_state + } } -impl From for MegaHaltReason { - fn from(value: EthHaltReason) -> Self { - Self::Base(OpHaltReason::Base(value)) +impl core::ops::DerefMut for MegaTransactionOutcome { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.result_and_state } } -impl From for MegaHaltReason { - fn from(value: OpHaltReason) -> Self { - Self::Base(value) - } +/// The gas one transaction spent, by ledger, and what its receipt reports. +/// +/// `regular + state + history` is the transaction's raw spend, +/// [`ResultGas::total_gas_spent`]; [`gas_used`](Self::gas_used) is +/// [`ResultGas::tx_gas_used`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MegaGasUsage { + /// Regular gas spent: everything that is neither state nor history gas, before the refund. + pub regular: u64, + /// State gas spent, net of refills. + pub state: u64, + /// History gas spent, net of refills. + pub history: u64, + /// The EIP-8037 reservoir left unspent, which the sender gets back. + pub reservoir_remaining: u64, + /// The EIP-7623 floor the receipt's gas used cannot fall below. + pub floor: u64, + /// The gas used the receipt reports: the raw spend less the refund, at least the floor. + pub gas_used: u64, } -impl TryFrom for EthHaltReason { - type Error = MegaHaltReason; - - fn try_from(value: MegaHaltReason) -> Result { - match value { - MegaHaltReason::Base(reason) => Ok(reason.try_into()?), - MegaHaltReason::DataLimitExceeded { .. } | - MegaHaltReason::KVUpdateLimitExceeded { .. } | - MegaHaltReason::ComputeGasLimitExceeded { .. } | - MegaHaltReason::StateGrowthLimitExceeded { .. } | - MegaHaltReason::SystemTxInvalidCallee { .. } | - MegaHaltReason::VolatileDataAccessOutOfGas { .. } => Err(value), +impl MegaGasUsage { + /// The ledgers of a transaction that settled into `result_gas` and spent `history` gas on + /// history. + /// + /// [`ResultGas`] has no history field; its total includes history gas, which is taken back + /// out of regular here. + pub const fn new(result_gas: &ResultGas, history: u64) -> Self { + let state = result_gas.state_gas_spent_final(); + Self { + regular: result_gas.total_gas_spent().saturating_sub(state).saturating_sub(history), + state, + history, + reservoir_remaining: result_gas.reservoir_remaining(), + floor: result_gas.floor_gas(), + gas_used: result_gas.tx_gas_used(), } } + + /// The regular gas a block counts for the transaction: the regular ledger, at least the + /// floor (EIP-8037 with EIP-7778). The refund does not lower it. + pub fn block_execution_gas(&self) -> u64 { + self.regular.max(self.floor) + } } #[cfg(test)] mod tests { use super::*; - use revm::context::result::OutOfGasError; + use crate::{LimitCheck, LimitKind, MegaHaltReason, MegaLimitExceeded}; + use alloy_sol_types::SolError; + use op_revm::OpHaltReason; + use revm::context::result::{HaltReason as EthHaltReason, OutOfGasError}; + + fn result_gas(total: u64, state: u64, refunded: u64, floor: u64) -> ResultGas { + ResultGas::default() + .with_total_gas_spent(total) + .with_state_gas_spent(state) + .with_refunded(refunded) + .with_floor_gas(floor) + .with_reservoir_remaining(5_000) + } + /// The three ledgers add up to the raw spend; the receipt figure is the spend less the refund. + #[test] + fn test_ledgers_split_the_raw_spend() { + let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000); + assert_eq!(gas.regular, 60_000); + assert_eq!(gas.state, 30_000); + assert_eq!(gas.history, 10_000); + assert_eq!(gas.regular + gas.state + gas.history, 100_000); + assert_eq!(gas.reservoir_remaining, 5_000); + assert_eq!(gas.gas_used, 96_000); + assert_eq!(gas.block_execution_gas(), 60_000); + } + + /// The floor binds the receipt figure and the block's execution gas, not the ledgers. + #[test] + fn test_floor_binds_receipt_and_block_execution_gas() { + let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000); + assert_eq!(gas.regular, 25_000); + assert_eq!(gas.floor, 45_000); + assert_eq!(gas.gas_used, 45_000); + assert_eq!(gas.block_execution_gas(), 45_000); + } + + /// Satin's halt set is op-revm's: an Ethereum halt converts in and back out. #[test] fn test_base_halt_reasons_convert_roundtrip() { let eth_reason = EthHaltReason::OutOfGas(OutOfGasError::Basic); - let mega_from_eth = MegaHaltReason::from(eth_reason); - let mega_from_op = MegaHaltReason::from(OpHaltReason::Base(eth_reason)); - - assert_eq!(mega_from_eth, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(mega_from_op, MegaHaltReason::Base(OpHaltReason::Base(eth_reason))); - assert_eq!(EthHaltReason::try_from(mega_from_eth).unwrap(), eth_reason); - assert_eq!(EthHaltReason::try_from(mega_from_op).unwrap(), eth_reason); + let mega = MegaHaltReason::from(eth_reason.clone()); + assert_eq!(mega, OpHaltReason::Base(eth_reason.clone())); + assert_eq!(EthHaltReason::try_from(mega).unwrap(), eth_reason); } + /// A limit stop is not a halt: it is a revert whose output is `MegaLimitExceeded`, for every + /// dimension. #[test] - fn test_mega_specific_halt_reasons_do_not_convert_to_eth() { - let reason = MegaHaltReason::VolatileDataAccessOutOfGas { - access_type: VolatileDataAccess::ORACLE, - limit: 100, - actual: 101, - }; - - assert_eq!(EthHaltReason::try_from(reason.clone()), Err(reason)); + fn test_limit_stops_are_reverts_with_mega_limit_exceeded() { + for kind in [ + LimitKind::DataSize, + LimitKind::KVUpdate, + LimitKind::ComputeGas, + LimitKind::StateGrowth, + ] { + let stop = LimitCheck::ExceedsLimit { kind, limit: 100, used: 101, frame_local: false }; + let decoded = MegaLimitExceeded::abi_decode(&stop.revert_data()).unwrap(); + assert_eq!(LimitKind::from_u8(decoded.kind), Some(kind)); + assert_eq!(decoded.limit, 100); + } } + /// The one halt reason op-revm adds, a failed deposit, has no Ethereum counterpart. #[test] fn test_op_specific_halt_reason_does_not_convert_to_eth() { - let op_reason = OpHaltReason::FailedDeposit; - let mega = MegaHaltReason::from(op_reason.clone()); - assert_eq!(mega, MegaHaltReason::Base(op_reason)); - assert!(EthHaltReason::try_from(mega).is_err()); + let mega = MegaHaltReason::FailedDeposit; + assert_eq!(EthHaltReason::try_from(mega.clone()), Err(mega)); } + /// No halt reason of Satin's own exists: every one but the failed deposit is Ethereum's. #[test] - fn test_all_mega_specific_variants_fail_eth_conversion() { - let variants: Vec = vec![ - MegaHaltReason::DataLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::KVUpdateLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::ComputeGasLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::StateGrowthLimitExceeded { limit: 1, actual: 2 }, - MegaHaltReason::SystemTxInvalidCallee { callee: Address::ZERO }, + fn test_only_the_failed_deposit_is_not_an_ethereum_halt() { + let reasons = [ + MegaHaltReason::Base(EthHaltReason::OutOfGas(OutOfGasError::Basic)), + MegaHaltReason::Base(EthHaltReason::OpcodeNotFound), + MegaHaltReason::Base(EthHaltReason::CallTooDeep), + MegaHaltReason::FailedDeposit, ]; - for variant in variants { - assert!( - EthHaltReason::try_from(variant).is_err(), - "mega-specific variant should not convert to EthHaltReason" - ); - } + let converted = + reasons.iter().filter(|r| EthHaltReason::try_from((*r).clone()).is_ok()).count(); + assert_eq!(converted, reasons.len() - 1, "only the failed deposit is OP-specific"); } } diff --git a/crates/mega-evm/src/evm/spec.rs b/crates/mega-evm/src/evm/spec.rs index 925804225..8f17d59bb 100644 --- a/crates/mega-evm/src/evm/spec.rs +++ b/crates/mega-evm/src/evm/spec.rs @@ -1,506 +1,235 @@ -//! Definitions of the `MegaETH` EVM versions (`SpecId`). +//! The `MegaETH` EVM spec of the Satin engine (`MegaSpecId`). +#[cfg(not(feature = "std"))] +use alloc as std; use core::{ fmt::{self, Display}, str::FromStr, }; +use std::string::String; + pub use op_revm::OpSpecId; -pub use revm::primitives::hardfork::{SpecId as EthSpecId, UnknownHardfork}; +pub use revm::primitives::hardfork::SpecId as EthSpecId; use serde::{Deserialize, Serialize}; -/// `MegaETH` spec id, defining different versions of the `MegaETH` EVM. +/// `MegaETH` spec id: the EVM behavior the Satin engine executes. +/// +/// Satin is a single-spec engine. The specs of the legacy engine (`Equivalence` through `Rex7`) +/// are not variants here and never parse to one; they are executed by the legacy engine. /// -/// Each `MegaETH` EVM version corresponds to a version of the Optimism EVM, which means the -/// behavior of the `MegaETH` EVM inherits and is customized on top of that version of the Optimism -/// EVM. Similarly, each Optimism EVM version also corresponds to a Ethereum EVM version. The -/// corresponding relations are as follows: -/// - [`SpecId::EQUIVALENCE`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX_1`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::MINI_REX_2`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX1`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX2`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX3`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX4`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX5`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX6`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] -/// - [`SpecId::REX7`] -> [`OpSpecId::ISTHMUS`] -> [`EthSpecId::PRAGUE`] +/// Each spec runs on top of an Optimism spec, which in turn runs on top of an Ethereum spec: +/// - [`MegaSpecId::SATIN`] -> [`OpSpecId::KARST`] -> [`EthSpecId::OSAKA`] /// -/// The `Default` variant tracks the latest spec, which may still be unstable; -/// callers that need a stable spec must select it explicitly instead of -/// relying on `Default::default()`. +/// The discriminants continue after the legacy ladder (`EQUIVALENCE` = 0 through `REX7` = 11), +/// so a raw `as u8` of a Satin spec never aliases a legacy one. #[repr(u8)] #[derive( Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize, )] -#[allow(non_camel_case_types, clippy::upper_case_acronyms, missing_docs)] +#[allow(non_camel_case_types, clippy::upper_case_acronyms)] #[non_exhaustive] pub enum MegaSpecId { - /// The EVM version when no `MegaETH` harfork is enabled. The behavior of the EVM - /// should be equivalent to the [`OpSpecId::ISTHMUS`] of the Optimism EVM. - EQUIVALENCE, - /// The EVM version for the *Mini-Rex* hardfork of `MegaETH`. - MINI_REX, - /// Alias spec for the `MiniRex1` hardfork: scheduled as its own rung, executes - /// [`MegaSpecId::EQUIVALENCE`] behavior (`behavior()` projects there). - MINI_REX_1, - /// Alias spec for the `MiniRex2` hardfork: scheduled as its own rung, executes - /// [`MegaSpecId::MINI_REX`] behavior (`behavior()` projects there). - MINI_REX_2, - /// The EVM version for the *Rex* hardfork of `MegaETH`. - REX, - /// The EVM version for the *Rex1* hardfork of `MegaETH`. - REX1, - /// The EVM version for the *Rex2* hardfork of `MegaETH`. - REX2, - /// The EVM version for the *Rex3* hardfork of `MegaETH`. - REX3, - /// The EVM version for the *Rex4* hardfork of `MegaETH`. - REX4, - /// The EVM version for the *Rex5* hardfork of `MegaETH`. - REX5, - /// The EVM version for the *Rex6* hardfork of `MegaETH`. - REX6, - /// The EVM version for the *Rex7* hardfork of `MegaETH`. + /// The Satin spec: Karst / Osaka base with EIP-8037 state gas and the EIP-2780 intrinsic + /// cost, under a 200M execution cap. #[default] - REX7, + SATIN = 12, } -/// String identifiers for `MegaETH` EVM versions. -#[allow(missing_docs)] +/// String identifiers of the `MegaETH` specs. pub mod name { - /// The string identifier for the *Equivalence* version of the `MegaETH` EVM. - pub const EQUIVALENCE: &str = "Equivalence"; - /// The string identifier for the *Mini-Rex* version of the `MegaETH` EVM. - pub const MINI_REX: &str = "MiniRex"; - /// The string identifier for the `MiniRex1` alias spec. - pub const MINI_REX_1: &str = "MiniRex1"; - /// The string identifier for the `MiniRex2` alias spec. - pub const MINI_REX_2: &str = "MiniRex2"; - /// The string identifier for the *Rex* version of the `MegaETH` EVM. - pub const REX: &str = "Rex"; - /// The string identifier for the *Rex1* version of the `MegaETH` EVM. - pub const REX1: &str = "Rex1"; - /// The string identifier for the *Rex2* version of the `MegaETH` EVM. - pub const REX2: &str = "Rex2"; - /// The string identifier for the *Rex3* version of the `MegaETH` EVM. - pub const REX3: &str = "Rex3"; - /// The string identifier for the *Rex4* version of the `MegaETH` EVM. - pub const REX4: &str = "Rex4"; - /// The string identifier for the *Rex5* version of the `MegaETH` EVM. - pub const REX5: &str = "Rex5"; - /// The string identifier for the *Rex6* version of the `MegaETH` EVM. - pub const REX6: &str = "Rex6"; - /// The string identifier for the *Rex7* version of the `MegaETH` EVM. - pub const REX7: &str = "Rex7"; + /// The string identifier of [`MegaSpecId::SATIN`](super::MegaSpecId::SATIN). + pub const SATIN: &str = "Satin"; } -impl MegaSpecId { - /// Every spec in the progression, oldest first. - /// - /// The single point to enumerate specs from: sweeps and tables that list specs by hand - /// drift silently when a variant is added. Completeness is enforced in two steps — - /// introducing a variant is a compile error in `ladder_index`'s exhaustive match (and the - /// `is_ladder_prefix` const assertion ties each entry here to its ladder position), and - /// `test_all_ends_at_the_latest_spec` fails until the new spec is appended here. - pub const ALL: &'static [Self] = &[ - Self::EQUIVALENCE, - Self::MINI_REX, - Self::MINI_REX_1, - Self::MINI_REX_2, - Self::REX, - Self::REX1, - Self::REX2, - Self::REX3, - Self::REX4, - Self::REX5, - Self::REX6, - Self::REX7, - ]; +/// The string identifiers of the legacy engine's specs. +/// +/// Parsing one of them fails with [`ParseMegaSpecError::Legacy`]: the Satin engine does not +/// execute legacy specs, and a legacy name is never mapped to a Satin spec. +pub const LEGACY_SPEC_NAMES: &[&str] = &[ + "Equivalence", + "MiniRex", + "MiniRex1", + "MiniRex2", + "Rex", + "Rex1", + "Rex2", + "Rex3", + "Rex4", + "Rex5", + "Rex6", + "Rex7", +]; - /// Converts the [`SpecId`] into its corresponding [`EthSpecId`]. - pub const fn into_eth_spec(self) -> EthSpecId { - self.into_op_spec().into_eth_spec() - } +impl MegaSpecId { + /// Every spec, oldest first. + pub const ALL: &'static [Self] = &[Self::SATIN]; - /// Converts the [`SpecId`] into its corresponding [`OpSpecId`]. + /// The Optimism spec this spec runs on. pub const fn into_op_spec(self) -> OpSpecId { match self { - Self::MINI_REX | - Self::MINI_REX_1 | - Self::MINI_REX_2 | - Self::EQUIVALENCE | - Self::REX | - Self::REX1 | - Self::REX2 | - Self::REX3 | - Self::REX4 | - Self::REX5 | - Self::REX6 | - Self::REX7 => OpSpecId::ISTHMUS, + Self::SATIN => OpSpecId::KARST, } } - /// The behavior this spec executes: alias specs project to the spec whose behavior they - /// reuse; every other spec is its own behavior. - /// - /// The projection must stay flat — every target is a concrete spec at or below the - /// projecting rung, never another alias — which the `is_flat_projection` const assertion - /// below pins at compile time. - pub const fn behavior(self) -> Self { - match self { - Self::MINI_REX_1 => Self::EQUIVALENCE, - Self::MINI_REX_2 => Self::MINI_REX, - other => other, - } - } - - /// Whether this spec is an alias — a rung whose behavior belongs to another spec. - /// Derived from [`behavior`](Self::behavior), so a future alias needs only its projection - /// arm; there is no second list to extend. - pub const fn is_alias(self) -> bool { - self.behavior() as u8 != self as u8 - } - - /// Returns `true` if `other`'s BEHAVIOR is enabled under `self` — the gate for execution - /// semantics. Both sides project through [`behavior`](Self::behavior) first, so an alias - /// spec enables exactly what its behavior target enables (`MINI_REX_1` does NOT enable - /// `MINI_REX`). - pub const fn is_enabled(self, other: Self) -> bool { - other.behavior() as u8 <= self.behavior() as u8 - } - - /// Returns `true` if the ladder has REACHED `other`'s rung — the gate for one-way chain - /// setup. Position comparison, no behavior projection: during an alias window the ladder - /// stands above the specs it rolled back from, so their setup stays in place. - pub const fn reaches(self, other: Self) -> bool { - other as u8 <= self as u8 - } -} - -/// Position on the spec progression, 0 = `EQUIVALENCE`. -/// -/// Not an API — the `u8` discriminant already carries the ordinal. This exists to be an -/// exhaustive match: introducing a spec fails compilation here until the variant is placed, -/// and the const assertion below fails until [`MegaSpecId::ALL`] lists it at that position. -const fn ladder_index(spec: MegaSpecId) -> usize { - match spec { - MegaSpecId::EQUIVALENCE => 0, - MegaSpecId::MINI_REX => 1, - MegaSpecId::MINI_REX_1 => 2, - MegaSpecId::MINI_REX_2 => 3, - MegaSpecId::REX => 4, - MegaSpecId::REX1 => 5, - MegaSpecId::REX2 => 6, - MegaSpecId::REX3 => 7, - MegaSpecId::REX4 => 8, - MegaSpecId::REX5 => 9, - MegaSpecId::REX6 => 10, - MegaSpecId::REX7 => 11, + /// The Ethereum spec this spec runs on. + pub const fn into_eth_spec(self) -> EthSpecId { + self.into_op_spec().into_eth_spec() } -} -/// Whether `list` is a prefix of the spec ladder: entry `i` is exactly the spec at ladder -/// position `i` — in order, without gaps, starting from `EQUIVALENCE`. -/// -/// Shared by the compile-time assertion on [`MegaSpecId::ALL`] below and by the test that -/// feeds it malformed lists, so the checker itself is exercised — a weakened guard here would -/// otherwise pass silently, since the real `ALL` always satisfies the property it checks. -const fn is_ladder_prefix(list: &[MegaSpecId]) -> bool { - let mut i = 0; - while i < list.len() { - if ladder_index(list[i]) != i { - return false; + /// The string identifier of this spec. + pub const fn name(self) -> &'static str { + match self { + Self::SATIN => name::SATIN, } - i += 1; } - true } -const _: () = assert!( - is_ladder_prefix(MegaSpecId::ALL), - "MegaSpecId::ALL must list every spec in ladder order, without gaps" -); - -/// The target `spec` projects to under a behavior `table` of `(spec, target)` pairs; a spec -/// absent from the table is its own target, mirroring [`MegaSpecId::behavior`]'s identity arm. -const fn project(table: &[(MegaSpecId, MegaSpecId)], spec: MegaSpecId) -> MegaSpecId { - let mut i = 0; - while i < table.len() { - if table[i].0 as u8 == spec as u8 { - return table[i].1; - } - i += 1; - } - spec +/// Error returned when a string does not name a Satin spec. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ParseMegaSpecError { + /// The string names a spec of the legacy engine. + Legacy(String), + /// The string names no known spec. + Unknown, } -/// Whether a behavior table is flat: every target is a fixed point of the table and sits at -/// or below the spec projecting onto it. -/// -/// The fixed-point check rejects chains and cycles in one property — a chain `A→B→C` fails -/// because `B`'s own target is `C`, a cycle `A→B→A` because `B` projects back to `A` — either -/// way [`MegaSpecId::behavior`]'s single-step lookup would silently resolve half-way. The -/// downward check rejects an alias projecting upward, which would execute semantics whose -/// one-way setup (gated by [`MegaSpecId::reaches`], a position below the target's rung) never -/// ran. -/// -/// The table is passed as data so the checker can be fed malformed shapes: the compile-time -/// assertion below checks the real projection, and the test exercises the rejection cases the -/// real table can never produce — a weakened guard here would otherwise pass silently. -const fn is_flat_projection(table: &[(MegaSpecId, MegaSpecId)]) -> bool { - let mut i = 0; - while i < table.len() { - let (spec, target) = table[i]; - if project(table, target) as u8 != target as u8 { - return false; - } - if target as u8 > spec as u8 { - return false; - } - // A key that appears twice would make `project` ambiguous (first match wins); - // reject the table outright rather than trusting the lookup order. - let mut j = 0; - while j < i { - if table[j].0 as u8 == spec as u8 { - return false; +impl Display for ParseMegaSpecError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Legacy(name) => { + write!(f, "{name} is a spec of the legacy engine; Satin does not execute it") } - j += 1; + Self::Unknown => f.write_str("unknown MegaETH spec name"), } - i += 1; - } - true -} - -/// [`MegaSpecId::behavior`] as data: every spec in [`MegaSpecId::ALL`] paired with its -/// projection target. -const fn behavior_table() -> [(MegaSpecId, MegaSpecId); MegaSpecId::ALL.len()] { - let mut table = [(MegaSpecId::EQUIVALENCE, MegaSpecId::EQUIVALENCE); MegaSpecId::ALL.len()]; - let mut i = 0; - while i < table.len() { - table[i] = (MegaSpecId::ALL[i], MegaSpecId::ALL[i].behavior()); - i += 1; } - table } -const _: () = { - let table = behavior_table(); - assert!( - is_flat_projection(&table), - "behavior() targets must be concrete specs at or below the projecting rung" - ); -}; - -impl From for &'static str { - /// Converts the [`SpecId`] into its corresponding string identifier. - fn from(spec_id: MegaSpecId) -> Self { - match spec_id { - MegaSpecId::EQUIVALENCE => name::EQUIVALENCE, - MegaSpecId::MINI_REX => name::MINI_REX, - MegaSpecId::MINI_REX_1 => name::MINI_REX_1, - MegaSpecId::MINI_REX_2 => name::MINI_REX_2, - MegaSpecId::REX => name::REX, - MegaSpecId::REX1 => name::REX1, - MegaSpecId::REX2 => name::REX2, - MegaSpecId::REX3 => name::REX3, - MegaSpecId::REX4 => name::REX4, - MegaSpecId::REX5 => name::REX5, - MegaSpecId::REX6 => name::REX6, - MegaSpecId::REX7 => name::REX7, - } - } -} +impl core::error::Error for ParseMegaSpecError {} impl FromStr for MegaSpecId { - type Err = UnknownHardfork; + type Err = ParseMegaSpecError; - /// Converts the string identifier into its corresponding [`SpecId`]. fn from_str(s: &str) -> Result { match s { - name::EQUIVALENCE => Ok(Self::EQUIVALENCE), - name::MINI_REX => Ok(Self::MINI_REX), - name::MINI_REX_1 => Ok(Self::MINI_REX_1), - name::MINI_REX_2 => Ok(Self::MINI_REX_2), - name::REX => Ok(Self::REX), - name::REX1 => Ok(Self::REX1), - name::REX2 => Ok(Self::REX2), - name::REX3 => Ok(Self::REX3), - name::REX4 => Ok(Self::REX4), - name::REX5 => Ok(Self::REX5), - name::REX6 => Ok(Self::REX6), - name::REX7 => Ok(Self::REX7), - _ => Err(UnknownHardfork), + name::SATIN => Ok(Self::SATIN), + legacy if LEGACY_SPEC_NAMES.contains(&legacy) => { + Err(ParseMegaSpecError::Legacy(legacy.into())) + } + _ => Err(ParseMegaSpecError::Unknown), } } } -impl From for revm::primitives::hardfork::SpecId { - /// Converts the [`SpecId`] into its corresponding [`EthSpecId`]. - fn from(spec_id: MegaSpecId) -> Self { - spec_id.into_eth_spec() +impl From for &'static str { + fn from(spec: MegaSpecId) -> Self { + spec.name() } } impl From for OpSpecId { - /// Converts the [`SpecId`] into its corresponding [`OpSpecId`]. - fn from(spec_id: MegaSpecId) -> Self { - spec_id.into_op_spec() + fn from(spec: MegaSpecId) -> Self { + spec.into_op_spec() + } +} + +impl From for EthSpecId { + fn from(spec: MegaSpecId) -> Self { + spec.into_eth_spec() } } impl Display for MegaSpecId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s: &'static str = (*self).into(); - write!(f, "{}", s) + f.write_str(self.name()) } } #[cfg(test)] mod tests { use super::*; - - /// The one golden spec table: every spec with its string identifier and its pinned ladder - /// position. The spec column must be exactly [`MegaSpecId::ALL`] (asserted in the - /// round-trip test); the name and position columns stay hand-written — deriving either - /// from the code under test would make its check vacuous. - const ALL_SPECS: [(MegaSpecId, &str, u8); 12] = [ - (MegaSpecId::EQUIVALENCE, name::EQUIVALENCE, 0), - (MegaSpecId::MINI_REX, name::MINI_REX, 1), - (MegaSpecId::MINI_REX_1, name::MINI_REX_1, 2), - (MegaSpecId::MINI_REX_2, name::MINI_REX_2, 3), - (MegaSpecId::REX, name::REX, 4), - (MegaSpecId::REX1, name::REX1, 5), - (MegaSpecId::REX2, name::REX2, 6), - (MegaSpecId::REX3, name::REX3, 7), - (MegaSpecId::REX4, name::REX4, 8), - (MegaSpecId::REX5, name::REX5, 9), - (MegaSpecId::REX6, name::REX6, 10), - (MegaSpecId::REX7, name::REX7, 11), + use core::str::FromStr; + + /// Every spec name of the legacy engine, written out by hand so the rejection check does + /// not read the list it is checking. + const LEGACY_NAMES: [&str; 12] = [ + "Equivalence", + "MiniRex", + "MiniRex1", + "MiniRex2", + "Rex", + "Rex1", + "Rex2", + "Rex3", + "Rex4", + "Rex5", + "Rex6", + "Rex7", ]; #[test] fn test_spec_names_roundtrip_and_display() { - // The spec column must be exactly `MegaSpecId::ALL`, so a newly introduced spec cannot - // be forgotten here. - assert!(ALL_SPECS.iter().map(|(spec, _, _)| *spec).eq(MegaSpecId::ALL.iter().copied())); - - for (spec, expected_name, _) in ALL_SPECS { - assert_eq!(<&'static str>::from(spec), expected_name); - assert_eq!(MegaSpecId::from_str(expected_name).unwrap(), spec); - assert_eq!(spec.to_string(), expected_name); - } - - assert_eq!(MegaSpecId::default(), MegaSpecId::REX7); - assert_eq!(MegaSpecId::from_str("unknown"), Err(UnknownHardfork)); - } - - /// The completeness anchor for [`MegaSpecId::ALL`]: `Default` tracks the latest spec (its - /// own assertion above pins which), so a variant added without extending `ALL` fails here - /// once the default advances. The const assertion on `ladder_index` covers order and gaps; - /// this covers the tail. - #[test] - fn test_all_ends_at_the_latest_spec() { - assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); + assert_eq!(MegaSpecId::SATIN.to_string(), "Satin"); + assert_eq!(<&'static str>::from(MegaSpecId::SATIN), "Satin"); + assert_eq!(MegaSpecId::from_str("Satin"), Ok(MegaSpecId::SATIN)); + assert_eq!(MegaSpecId::from_str("satin"), Err(ParseMegaSpecError::Unknown)); + assert_eq!(MegaSpecId::from_str(""), Err(ParseMegaSpecError::Unknown)); } #[test] - fn test_ladder_positions_are_pinned() { - // A downstream variant-index codec (bincode-style) of `MegaSpecId` — or of a - // container holding it — silently misreads old data if discriminants renumber. - // Pinning every position turns any future renumbering into a loud diff on the - // golden table, where the review attention is. - assert_eq!(ALL_SPECS.len(), MegaSpecId::ALL.len()); - for (spec, _, position) in ALL_SPECS { - assert_eq!(spec as u8, position, "{spec:?} moved on the ladder"); + fn test_legacy_spec_names_are_rejected_not_mapped() { + for name in LEGACY_NAMES { + assert_eq!( + MegaSpecId::from_str(name), + Err(ParseMegaSpecError::Legacy(name.into())), + "{name} must not parse to a Satin spec" + ); } + assert_eq!(LEGACY_SPEC_NAMES, LEGACY_NAMES.as_slice()); } #[test] - fn test_is_ladder_prefix_rejects_malformed_lists() { - assert!(is_ladder_prefix(MegaSpecId::ALL)); - assert!(is_ladder_prefix(&[]), "the empty prefix is a ladder prefix"); - assert!(is_ladder_prefix(&[MegaSpecId::EQUIVALENCE, MegaSpecId::MINI_REX])); - - assert!( - !is_ladder_prefix(&[MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE]), - "reordered entries must be rejected" + fn test_parse_error_names_the_legacy_engine() { + let err = MegaSpecId::from_str("Rex6").unwrap_err(); + assert_eq!( + err.to_string(), + "Rex6 is a spec of the legacy engine; Satin does not execute it" ); - assert!( - !is_ladder_prefix(&[MegaSpecId::MINI_REX]), - "a list not starting at the ladder base must be rejected" - ); - assert!( - !is_ladder_prefix(&[MegaSpecId::EQUIVALENCE, MegaSpecId::REX]), - "a skipped rung must be rejected" + assert_eq!( + MegaSpecId::from_str("Rex8").unwrap_err().to_string(), + "unknown MegaETH spec name" ); } #[test] - fn test_is_flat_projection_rejects_malformed_tables() { - assert!(is_flat_projection(&behavior_table())); - assert!(is_flat_projection(&[]), "the empty table is flat"); - assert!( - is_flat_projection(&[(MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE)]), - "a target absent from the table projects to itself" - ); - - assert!( - !is_flat_projection(&[ - (MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE), - (MegaSpecId::MINI_REX_2, MegaSpecId::MINI_REX_1), - ]), - "a chain — an alias targeting another alias — must be rejected" - ); - assert!( - !is_flat_projection(&[ - (MegaSpecId::EQUIVALENCE, MegaSpecId::MINI_REX), - (MegaSpecId::MINI_REX, MegaSpecId::EQUIVALENCE), - ]), - "a projection cycle must be rejected" - ); - assert!( - !is_flat_projection(&[(MegaSpecId::MINI_REX, MegaSpecId::REX)]), - "an alias projecting to a higher rung must be rejected" - ); - assert!( - !is_flat_projection(&[ - (MegaSpecId::MINI_REX_1, MegaSpecId::EQUIVALENCE), - (MegaSpecId::MINI_REX_1, MegaSpecId::MINI_REX), - ]), - "a duplicate key must be rejected — it would make the projection ambiguous" - ); + fn test_serde_uses_the_variant_name() { + assert_eq!(serde_json::to_string(&MegaSpecId::SATIN).unwrap(), "\"SATIN\""); + assert_eq!(serde_json::from_str::("\"SATIN\"").unwrap(), MegaSpecId::SATIN); + for legacy in ["\"REX6\"", "\"REX7\"", "\"EQUIVALENCE\"", "\"Satin\""] { + assert!( + serde_json::from_str::(legacy).is_err(), + "{legacy} must not deserialize" + ); + } } #[test] - fn test_all_specs_map_to_isthmus_and_prague() { - for spec in MegaSpecId::ALL.iter().copied() { - assert_eq!(spec.into_op_spec(), OpSpecId::ISTHMUS); - assert_eq!(spec.into_eth_spec(), EthSpecId::PRAGUE); - assert_eq!(revm::primitives::hardfork::SpecId::from(spec), EthSpecId::PRAGUE); - assert_eq!(OpSpecId::from(spec), OpSpecId::ISTHMUS); - } + fn test_all_ends_at_the_latest_spec() { + assert_eq!(MegaSpecId::ALL, &[MegaSpecId::SATIN]); + assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); } + /// A raw `as u8` of a Satin spec never aliases a legacy rung (`EQUIVALENCE` = 0 through + /// `REX7` = 11). #[test] - fn test_spec_order_is_backward_compatible() { - assert!(MegaSpecId::REX4.is_enabled(MegaSpecId::REX3)); - assert!(MegaSpecId::REX4.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::MINI_REX.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX2.is_enabled(MegaSpecId::REX1)); - assert!(MegaSpecId::REX5.is_enabled(MegaSpecId::REX4)); - assert!(MegaSpecId::REX5.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX6.is_enabled(MegaSpecId::REX5)); - assert!(MegaSpecId::REX6.is_enabled(MegaSpecId::EQUIVALENCE)); - assert!(MegaSpecId::REX7.is_enabled(MegaSpecId::REX6)); - assert!(MegaSpecId::REX7.is_enabled(MegaSpecId::EQUIVALENCE)); + fn test_discriminant_continues_after_the_legacy_ladder() { + assert_eq!(MegaSpecId::SATIN as u8, 12); + } - assert!(!MegaSpecId::EQUIVALENCE.is_enabled(MegaSpecId::MINI_REX)); - assert!(!MegaSpecId::REX1.is_enabled(MegaSpecId::REX2)); - assert!(!MegaSpecId::REX3.is_enabled(MegaSpecId::REX4)); - assert!(!MegaSpecId::REX4.is_enabled(MegaSpecId::REX5)); - assert!(!MegaSpecId::REX5.is_enabled(MegaSpecId::REX6)); - assert!(!MegaSpecId::REX6.is_enabled(MegaSpecId::REX7)); + #[test] + fn test_all_specs_map_to_karst_and_osaka() { + assert_eq!(MegaSpecId::SATIN.into_op_spec(), OpSpecId::KARST); + assert_eq!(MegaSpecId::SATIN.into_eth_spec(), EthSpecId::OSAKA); + assert_eq!(OpSpecId::from(MegaSpecId::SATIN), OpSpecId::KARST); + assert_eq!(EthSpecId::from(MegaSpecId::SATIN), EthSpecId::OSAKA); } } diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs deleted file mode 100644 index 4c5681c59..000000000 --- a/crates/mega-evm/src/evm/state.rs +++ /dev/null @@ -1,396 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::collections::BTreeMap; - -use alloy_primitives::{map::hash_map::Entry, B256}; -use revm::state::{Account, AccountStatus, EvmState, EvmStorage}; - -use auto_impl::auto_impl; -use revm::{database::State, Database}; - -/// A helper trait to get the block hashes used during transaction execution. -#[auto_impl(&, &mut, Box, Rc, Arc)] -pub trait BlockHashes { - /// Get the block hashes used during transaction execution. - fn get_accessed_block_hashes(&self) -> BTreeMap; -} - -impl BlockHashes for State { - fn get_accessed_block_hashes(&self) -> BTreeMap { - self.block_hashes.clone() - } -} - -/// Merges the other [`EvmState`] into the current one with account status also merged. -/// See more details in the [`merge_evm_state_optional_status`] function. -pub fn merge_evm_state(this: &mut EvmState, other: &EvmState) { - merge_evm_state_optional_status(this, other, true); -} - -/// Merges the other [`EvmState`] into the current one. The account status may or may not be merged -/// according to the `merge_status` parameter. -/// -/// # Assumption -/// -/// - The `other` `EvmState` is the result of the execution of a single transaction, or the merged -/// result of another [`merge_evm_state`] call. It must not be a partial `EvmState` in the middle -/// of a transaction execution. -/// - This function assumes that Cancun hardfork (EIP-6780) is activated. -/// - This function only works correctly post Cancun. -/// -/// # Algorithm -/// -/// Post Cancun (with EIP-6780), the account status is `SelfDestructed` only when the account is -/// created in the same transaction, i.e., if `SelfDestructed` flag is set, it must be "created -> -/// selfdestructed" in the same transaction and `Created` flag is also set. When merging `EvmState`s -/// (base `EvmState` <- new `EvmState`), we are doing this for each account: -/// - If the `SelfDestructed` (and `Created`) flag is set in the account status of the new -/// `EvmState`, override the account with an empty, touched account. -/// - Otherwise, we override the corresponding account and storage slots in the base `EvmState`. -/// -/// # Coldness -/// -/// When merging the state, if an account or storage slot exists in `this`, its coldness is -/// preserved; if an account or storage slot does not exist in `this`, it is marked as cold. -/// -/// # Account Status -/// -/// Optionally: -/// - `CreatedLocal` and `SelfDestructedLocal` on the `other` `EvmState` is cleared since they only -/// matter in the execution of the same transaction, while this merging between transactions. -/// - The `Cold` flag in the `this` `EvmState` is preserved. -/// - For other flags, they are merged from `other` into `this`. -/// -/// We merge the state even if the account is not marked as `Touched`. This is because we may need -/// to know which account is read but not written to obtain `ReadSet` for witness generation. -pub fn merge_evm_state_optional_status(this: &mut EvmState, other: &EvmState, merge_status: bool) { - for (address, account) in other { - if account.is_selfdestructed() { - // if the account is selfdestructed, we assert that the account is also created and do - // nothing. - assert!( - account.is_created(), - "Account is selfdestructed but not created. EIP-6780 must be applied." - ); - // we will put an empty (equivalent to non-existent) account in the base state. - // NOTE: we want to avoid marking an account as `SelfDestructed` since this may result - // in a `BundleAccount` with `wipe_storage = true`. The underlying database in fact - // cannot process such wiping storage action. Here, we do an early interpretation of - // `SelfDestruct` by overriding the account with a default (empty) one and marking it as - // `Touched`. The rationale is: - // 1. The account is effectively selfdestructed, so its result state is equivalent to an - // empty account. - // 2. There is no need to wipe storage in the database since this account is just - // created and destructed, there must be no storage data in the database. - // 3. The account needs to be marked as `Touched` in case it pre-exists in the database - // and needs to be deleted. - let mut empty_account = Account::default().with_touched_mark(); - match this.entry(*address) { - Entry::Occupied(mut occupied_entry) => { - if occupied_entry.get().status.contains(AccountStatus::Cold) { - // if the account was cold, we need to preserve the coldness - empty_account.mark_cold(); - } - occupied_entry.insert(empty_account); - } - Entry::Vacant(vacant_entry) => { - // if the account didn't exist, we mark it as cold - vacant_entry.insert(empty_account.with_cold_mark()); - } - } - continue; - } - - // merge regardless of whether the account is touched or not - match this.entry(*address) { - Entry::Vacant(v) => { - // if the account didn't exist, we mark it as cold - let mut merged_account = account.clone().with_cold_mark(); - // all storage slots should be marked as cold - for slot in merged_account.storage.values_mut() { - slot.mark_cold(); - } - // `CreatedLocal` and `SelfDestructedLocal` are cleared since they only matter in - // the execution of the same transaction, while this merging between transactions. - merged_account.unmark_created_locally(); - merged_account.unmark_selfdestructed_locally(); - v.insert(merged_account); - } - Entry::Occupied(mut v) => { - let this_account = v.get_mut(); - merge_account_state(this_account, account, merge_status); - } - } - } -} - -/// Merges the other [`Account`] into the current one. -/// -/// # Assumption -/// -/// The other account to merge is not flagged as `SelfDestructed`. See more details in -/// the [`merge_evm_state`] function. -fn merge_account_state(this: &mut Account, other: &Account, merge_status: bool) { - this.info = other.info.clone(); - merge_evm_storage(&mut this.storage, &other.storage); - if merge_status { - merge_account_status(&mut this.status, other.status); - } -} - -/// Merges the other [`AccountStatus`] into the current one. -/// -/// # Assumption -/// -/// The other [`AccountStatus`] to merge is not flagged as `SelfDestructed`. See more details in -/// the [`merge_evm_state`] function. -fn merge_account_status(this: &mut AccountStatus, mut other: AccountStatus) { - assert!( - !other.contains(AccountStatus::SelfDestructed), - "Account is selfdestructed and should not be merged." - ); - // The coldness of `this` account should be preserved. - // Remove the flags that only matter in the execution of the same transaction, while this - // merging between transactions. - other -= AccountStatus::Cold | AccountStatus::CreatedLocal | AccountStatus::SelfDestructedLocal; - - if this.contains(AccountStatus::SelfDestructed) && other.contains(AccountStatus::Created) { - // if `this` account is selfdestructed, and `other` account is created, - // we should no longer mark `this` as selfdestructed. - *this -= AccountStatus::SelfDestructed; - } - - // Other status flags are simply merged into `this`. - *this |= other; -} - -/// Merges the other [`EvmStorage`] into the current one. -/// -/// See more details in the [`merge_evm_state`] function. -fn merge_evm_storage(this: &mut EvmStorage, other: &EvmStorage) { - for (slot, slot_value) in other { - match this.entry(*slot) { - Entry::Vacant(v) => { - let mut slot = slot_value.clone(); - // If this slot is not loaded, we mark it as cold. - slot.mark_cold(); - v.insert(slot); - } - Entry::Occupied(mut v) => { - let this_slot = v.get_mut(); - this_slot.present_value = slot_value.present_value; - // The coldness of the slot is preserved. - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Address, B256, U256}; - use revm::{ - database::{InMemoryDB, State}, - state::{AccountInfo, EvmStorageSlot}, - }; - - const TEST_ADDRESS: Address = address!("1000000000000000000000000000000000000001"); - - fn account_with_status(status: AccountStatus) -> Account { - Account { - info: AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: B256::ZERO, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status, - } - } - - #[test] - fn test_state_exposes_accessed_block_hashes() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(1, B256::ZERO); - state.block_hashes.insert(2, B256::from([2_u8; 32])); - - let hashes = state.get_accessed_block_hashes(); - assert_eq!(hashes.len(), 2); - assert_eq!(hashes.get(&1), Some(&B256::ZERO)); - assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); - } - - #[test] - fn test_merge_evm_state_replaces_created_selfdestructed_accounts_with_empty_touched_accounts() { - let mut this = EvmState::default(); - this.insert(TEST_ADDRESS, Account::default().with_cold_mark()); - - let mut other_account = account_with_status(AccountStatus::Created); - other_account.mark_selfdestruct(); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - merge_evm_state(&mut this, &other); - - let merged = this.get_mut(&TEST_ADDRESS).unwrap(); - assert!(merged.is_touched()); - assert!(!merged.is_selfdestructed()); - assert_eq!(merged.info, AccountInfo::default()); - assert!(merged.storage.is_empty()); - assert!(merged.mark_warm_with_transaction_id(0), "coldness should be preserved"); - } - - #[test] - fn test_merge_evm_state_marks_new_accounts_and_storage_as_cold_and_clears_local_flags() { - let mut other_account = - account_with_status(AccountStatus::Created | AccountStatus::CreatedLocal); - other_account.status |= AccountStatus::SelfDestructedLocal; - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(5), 0)); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert!(merged.status.contains(AccountStatus::Cold)); - assert!(merged.status.contains(AccountStatus::Created)); - assert!(!merged.status.contains(AccountStatus::CreatedLocal)); - assert!(!merged.status.contains(AccountStatus::SelfDestructedLocal)); - - let mut slot = merged.storage.get(&U256::from(1)).unwrap().clone(); - assert_eq!(slot.present_value(), U256::from(5)); - assert!(slot.mark_warm_with_transaction_id(0), "new slots should be marked cold"); - } - - #[test] - fn test_merge_evm_state_optional_status_can_skip_or_merge_status_flags() { - let mut base_account = - account_with_status(AccountStatus::SelfDestructed | AccountStatus::Cold); - let mut base_slot = EvmStorageSlot::new(U256::from(1), 0); - base_slot.mark_cold(); - base_account.storage.insert(U256::from(1), base_slot); - let base_state = EvmState::from_iter([(TEST_ADDRESS, base_account)]); - - let mut other_account = - account_with_status(AccountStatus::Created | AccountStatus::CreatedLocal); - other_account.info.balance = U256::from(9); - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(9), 0)); - let other_state = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut without_status_merge = base_state.clone(); - merge_evm_state_optional_status(&mut without_status_merge, &other_state, false); - let without_status_merge_account = without_status_merge.get(&TEST_ADDRESS).unwrap(); - assert!(without_status_merge_account.status.contains(AccountStatus::SelfDestructed)); - assert!(without_status_merge_account.status.contains(AccountStatus::Cold)); - assert!(!without_status_merge_account.status.contains(AccountStatus::Created)); - assert_eq!( - without_status_merge_account.storage.get(&U256::from(1)).unwrap().present_value(), - U256::from(9) - ); - let mut preserved_slot = - without_status_merge_account.storage.get(&U256::from(1)).unwrap().clone(); - assert!(preserved_slot.mark_warm_with_transaction_id(0)); - - let mut with_status_merge = base_state; - merge_evm_state(&mut with_status_merge, &other_state); - let with_status_merge_account = with_status_merge.get(&TEST_ADDRESS).unwrap(); - assert!(!with_status_merge_account.is_selfdestructed()); - assert!(with_status_merge_account.status.contains(AccountStatus::Created)); - assert!(with_status_merge_account.status.contains(AccountStatus::Cold)); - } - - #[test] - fn test_merge_empty_other_state_is_noop() { - let mut this = - EvmState::from_iter([(TEST_ADDRESS, account_with_status(AccountStatus::Cold))]); - let other = EvmState::default(); - - merge_evm_state(&mut this, &other); - - assert_eq!(this.len(), 1); - let account = this.get(&TEST_ADDRESS).unwrap(); - assert_eq!(account.info.balance, U256::from(1)); - } - - #[test] - fn test_merge_evm_state_overwrites_existing_account_storage_and_preserves_slot_coldness() { - let addr2 = address!("2000000000000000000000000000000000000001"); - - let mut base_account = account_with_status(AccountStatus::Touched | AccountStatus::Cold); - let mut base_slot = EvmStorageSlot::new(U256::from(10), 0); - base_slot.mark_cold(); - base_account.storage.insert(U256::from(1), base_slot); - base_account.storage.insert(U256::from(2), EvmStorageSlot::new(U256::from(20), 0)); - let mut this = EvmState::from_iter([(TEST_ADDRESS, base_account)]); - - let mut other_account = account_with_status(AccountStatus::Touched); - other_account.info.balance = U256::from(99); - other_account - .storage - .insert(U256::from(1), EvmStorageSlot::new_changed(U256::from(10), U256::from(42), 0)); - other_account - .storage - .insert(U256::from(3), EvmStorageSlot::new_changed(U256::ZERO, U256::from(77), 0)); - let other = EvmState::from_iter([ - (TEST_ADDRESS, other_account), - (addr2, account_with_status(AccountStatus::Touched)), - ]); - - merge_evm_state(&mut this, &other); - - assert_eq!(this.len(), 2); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert_eq!(merged.info.balance, U256::from(99)); - assert_eq!(merged.storage.get(&U256::from(1)).unwrap().present_value(), U256::from(42),); - { - let mut existing_slot = merged.storage.get(&U256::from(1)).unwrap().clone(); - assert!( - existing_slot.mark_warm_with_transaction_id(0), - "existing slot should have preserved original coldness" - ); - } - assert_eq!(merged.storage.get(&U256::from(2)).unwrap().present_value(), U256::from(20),); - let mut new_slot = merged.storage.get(&U256::from(3)).unwrap().clone(); - assert_eq!(new_slot.present_value(), U256::from(77)); - assert!(new_slot.mark_warm_with_transaction_id(0), "new slot from other should be cold"); - - let new_account = this.get(&addr2).unwrap(); - assert!(new_account.status.contains(AccountStatus::Cold)); - } - - #[test] - fn test_merge_selfdestructed_account_not_in_base_is_inserted_as_cold_empty() { - let mut other_account = account_with_status(AccountStatus::Created); - other_account.mark_selfdestruct(); - other_account.info.balance = U256::from(999); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - - let merged = this.get(&TEST_ADDRESS).unwrap(); - assert!(merged.is_touched()); - assert!(!merged.is_selfdestructed()); - assert_eq!(merged.info, AccountInfo::default()); - assert!(merged.status.contains(AccountStatus::Cold)); - } - - #[test] - #[should_panic(expected = "EIP-6780 must be applied")] - fn test_merge_evm_state_panics_for_selfdestructed_account_without_created_flag() { - let mut other_account = account_with_status(AccountStatus::Touched); - other_account.mark_selfdestruct(); - other_account.status.remove(AccountStatus::Created); - let other = EvmState::from_iter([(TEST_ADDRESS, other_account)]); - - let mut this = EvmState::default(); - merge_evm_state(&mut this, &other); - } -} diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 7a8370421..29f2abe16 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -8,25 +8,22 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - `factory.rs`: `ExternalEnvFactory` trait for block-scoped environment creation. - `salt.rs`: SALT trait and bucket-id derivation rules. - `oracle.rs`: oracle trait for storage reads and hint side effects. -- `gas.rs`: dynamic storage gas calculator with per-bucket multiplier cache. +- SALT pricing (the state-gas price hook that consumes `SaltEnv`) is not here yet. - `hasher/`: hashing utilities used for deterministic bucket-id computation. ## KEY PATTERNS - Block context is captured at environment creation time, not passed per query. - SALT and oracle are independent traits but consumed together via `ExternalEnvs` bundle. -- Dynamic gas multipliers are cached by bucket id and reset on new parent block. - External errors are propagated to host and then stashed in EVM context error channel. - `EmptyExternalEnv` must stay deterministic and side-effect free. ## ANTI-PATTERNS - Do not query live chain state directly from opcode handlers. - All external reads should route through trait objects created by `ExternalEnvFactory`. -- Do not bypass bucket multiplier cache for repeated bucket ids in one block. - Do not couple oracle hint side effects to SALT behavior. - Keep SALT and oracle traits independently testable. ## WHERE TO LOOK - Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. -- Change bucket multiplier formula: `gas.rs`. -- Change oracle storage retrieval behavior: `oracle.rs` trait impls and `evm/host.rs` integration. +- Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration is not here yet). - Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs deleted file mode 100644 index 2fe08f173..000000000 --- a/crates/mega-evm/src/external/gas.rs +++ /dev/null @@ -1,300 +0,0 @@ -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use core::fmt::Debug; -use revm::primitives::hash_map::Entry; - -use alloy_primitives::{Address, BlockNumber, U256}; -use revm::{context::BlockEnv, primitives::HashMap}; - -use crate::{constants, BucketId, MegaSpecId, SaltEnv, MIN_BUCKET_SIZE}; - -/// Calculator for dynamic gas costs based on bucket capacity. -#[derive(Debug)] -pub struct DynamicGasCost { - /// The spec id. - spec: MegaSpecId, - /// The parent block number. - parent_block: BlockNumber, - /// The external environment for SALT bucket information. - salt_env: SaltEnvImpl, - /// Cache of the bucket cost multiplier for each bucket Id. The multiplier will be used to - /// multiply [`SSTORE_SET_GAS`] to get the actual gas cost for setting a storage slot. - bucket_cost_mulitipers: HashMap, -} - -impl DynamicGasCost { - /// Creates a new [`DynamicGasCost`]. - pub fn new(spec: MegaSpecId, salt_env: SaltEnvImpl, parent_block: BlockNumber) -> Self { - Self { spec, parent_block, salt_env, bucket_cost_mulitipers: HashMap::default() } - } - - /// Resets the cache of the bucket cost multiplier. - pub fn reset(&mut self, parent_block: BlockNumber) { - self.bucket_cost_mulitipers.clear(); - self.parent_block = parent_block; - } - - /// Gets the bucket IDs used during transaction execution. - pub fn get_bucket_ids(&self) -> Vec { - self.bucket_cost_mulitipers.keys().copied().collect() - } - - /// `SSTORE_SET` storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - /// - /// Single source of the per-spec `SSTORE_SET` dynamic storage-gas formula, shared by the - /// SALT-driven path ([`sstore_set_gas`](Self::sstore_set_gas)) and the REX6 system-exempt - /// unscaled path ([`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled)). - fn sstore_set_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::SSTORE_SET_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::SSTORE_SET_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// `NEW_ACCOUNT` storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - fn new_account_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// CREATE storage gas for an explicit bucket-capacity `multiplier` (always ≥ 1). - fn create_contract_gas_for_multiplier(&self, multiplier: u64) -> u64 { - if self.spec.is_enabled(MegaSpecId::REX) { - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE.saturating_mul(multiplier - 1) - } else { - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(multiplier) - } - } - - /// Calculates the gas cost for setting a storage slot to a non-zero value. This overrides the - /// [`SSTORE_SET`](revm::interpreter::gas::SSTORE_SET) gas cost in the original EVM. - pub fn sstore_set_gas( - &mut self, - address: Address, - key: U256, - ) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_slot(address, key); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.sstore_set_gas_for_multiplier(multiplier)) - } - - /// Calculates the gas cost for creating a new account. This overrides the - /// [`NEWACCOUNT`](revm::interpreter::gas::NEWACCOUNT) gas cost in the original EVM. - pub fn new_account_gas(&mut self, address: Address) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_account(address); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.new_account_gas_for_multiplier(multiplier)) - } - - /// Calculates the gas cost for creating a new contract. This overrides the - /// [`CREATE`](revm::interpreter::gas::CREATE) gas cost in the original EVM. - pub fn create_contract_gas(&mut self, address: Address) -> Result { - // increase the gas cost according to the bucket capacity - let bucket_id = SaltEnvImpl::bucket_id_for_account(address); - let multiplier = self.load_bucket_cost_multiplier(bucket_id)?; - - Ok(self.create_contract_gas_for_multiplier(multiplier)) - } - - /// SALT-unscaled `SSTORE_SET` storage gas: the cost a write would pay if the target bucket - /// were at its minimum capacity, equivalent to taking the REX-family formula - /// `base × (multiplier − 1)` to `0`. REX6+ charges system-originated transactions this so - /// their storage cost is independent of how full SALT buckets actually are. Unlike - /// [`sstore_set_gas`](Self::sstore_set_gas) this does not query the SALT env or record bucket - /// access. - /// - /// REX-family only: the production caller (`HostExt::sstore_set_storage_gas` under the - /// REX6-gated `LimitCheck::Exempt` stamp) is unreachable pre-REX, and the "0 additional - /// storage gas" property holds only for the REX-family `base × (multiplier − 1)` formula. - pub fn sstore_set_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - // `multiplier = 1` ≡ bucket at minimum capacity, no excess to charge for — - // REX-family `base × (multiplier − 1)` evaluates to `0`. - self.sstore_set_gas_for_multiplier(1) - } - - /// SALT-unscaled `NEW_ACCOUNT` storage gas. - /// See [`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled). - pub fn new_account_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - self.new_account_gas_for_multiplier(1) - } - - /// SALT-unscaled CREATE storage gas. - /// See [`sstore_set_gas_unscaled`](Self::sstore_set_gas_unscaled). - pub fn create_contract_gas_unscaled(&self) -> u64 { - debug_assert!(self.spec.is_enabled(MegaSpecId::REX)); - self.create_contract_gas_for_multiplier(1) - } - - /// Loads the bucket cost multiplier for a given bucket Id. - fn load_bucket_cost_multiplier( - &mut self, - bucket_id: BucketId, - ) -> Result { - match self.bucket_cost_mulitipers.entry(bucket_id) { - Entry::Occupied(occupied_entry) => Ok(*occupied_entry.get()), - Entry::Vacant(vacant_entry) => { - let capacity = self.salt_env.get_bucket_capacity(bucket_id)?; - assert!( - capacity >= MIN_BUCKET_SIZE as u64, - "SaltEnv returned bucket_capacity={capacity} below MIN_BUCKET_SIZE ({})", - MIN_BUCKET_SIZE, - ); - let multiplier = capacity / MIN_BUCKET_SIZE as u64; - vacant_entry.insert(multiplier); - Ok(multiplier) - } - } - } -} - -impl DynamicGasCost { - pub(crate) fn on_new_block(&mut self, block: &BlockEnv) { - self.reset(block.number.to::().saturating_sub(1)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::external::test_utils::TestExternalEnvs; - - fn cost_with_capacity(spec: MegaSpecId, capacity: u64) -> DynamicGasCost { - // Map the bucket id that the simple bucket hasher will produce for the zero address / - // zero slot to the requested capacity. - let bucket_for_account = - ::bucket_id_for_account(Address::ZERO); - let bucket_for_slot = - ::bucket_id_for_slot(Address::ZERO, U256::ZERO); - let env = TestExternalEnvs::new() - .with_bucket_capacity(bucket_for_account, capacity) - .with_bucket_capacity(bucket_for_slot, capacity); - DynamicGasCost::new(spec, env, 0) - } - - /// `MIN_BUCKET_SIZE * u64::MAX` cannot be represented in `u64`; verify the hardened - /// arithmetic does not panic and saturates instead of wrapping. - #[test] - fn test_sstore_set_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_new_account_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.new_account_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - #[test] - fn test_create_contract_gas_saturates_on_huge_multiplier() { - let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - - let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); - let gas = cost.create_contract_gas(Address::ZERO).unwrap(); - assert_eq!(gas, u64::MAX); - } - - /// REX6 system-exempt path: the unscaled cost (`multiplier = 1`) is `0` for the REX-family - /// formula `base × (multiplier − 1)`, and is independent of the actual bucket capacity. This - /// is what makes a system call's storage cost immune to SALT bucket scaling. - #[test] - fn test_unscaled_gas_is_zero_for_rex_and_independent_of_capacity() { - for capacity in [MIN_BUCKET_SIZE as u64, 1_280_000, u64::MAX] { - let cost = cost_with_capacity(MegaSpecId::REX6, capacity); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - } - - /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX - /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a - /// tightened gate (e.g. REX1) fails here. - #[test] - fn test_unscaled_gas_is_available_from_rex_exactly() { - let cost = cost_with_capacity(MegaSpecId::REX, MIN_BUCKET_SIZE as u64); - assert_eq!(cost.sstore_set_gas_unscaled(), 0); - assert_eq!(cost.new_account_gas_unscaled(), 0); - assert_eq!(cost.create_contract_gas_unscaled(), 0); - } - - /// Pre-REX callers must trip the debug assert — a loosened gate (e.g. `MiniRex`) would - /// silently serve the REX-family formula to a spec that prices storage differently. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_sstore_set_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .sstore_set_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_new_account_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .new_account_gas_unscaled(); - } - - /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "assertion failed")] - fn test_create_contract_gas_unscaled_asserts_pre_rex() { - let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) - .create_contract_gas_unscaled(); - } - - /// `MiniRex` prices contract creation with the flat `NEW_ACCOUNT_STORAGE_GAS × multiplier` - /// formula; REX switches to `CONTRACT_CREATION_STORAGE_GAS_BASE × (multiplier − 1)`. Pin - /// the boundary from the `MiniRex` side so a loosened REX gate fails here. - #[test] - fn test_create_contract_gas_uses_mini_rex_formula_before_rex() { - let cost = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64); - assert_eq!( - cost.create_contract_gas_for_multiplier(3), - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(3), - ); - assert_ne!( - constants::mini_rex::NEW_ACCOUNT_STORAGE_GAS.saturating_mul(3), - constants::rex::CONTRACT_CREATION_STORAGE_GAS_BASE.saturating_mul(2), - "the two formulas must disagree for this pin to mean anything", - ); - } - - /// The unscaled result equals the SALT-driven result evaluated at the minimum bucket - /// capacity, confirming the shared formula helper produces consistent values across both paths. - #[test] - fn test_unscaled_matches_salt_path_at_min_capacity() { - let mut cost = cost_with_capacity(MegaSpecId::REX6, MIN_BUCKET_SIZE as u64); - assert_eq!( - cost.sstore_set_gas_unscaled(), - cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(), - ); - } -} diff --git a/crates/mega-evm/src/external/mod.rs b/crates/mega-evm/src/external/mod.rs index feb0fb4a0..e0b6c4277 100644 --- a/crates/mega-evm/src/external/mod.rs +++ b/crates/mega-evm/src/external/mod.rs @@ -19,7 +19,6 @@ use auto_impl::auto_impl; use core::fmt::Debug; mod factory; -mod gas; #[cfg(any(test, feature = "test-utils"))] mod hasher; mod oracle; @@ -28,7 +27,6 @@ mod salt; mod test_utils; pub use factory::*; -pub use gas::*; #[cfg(any(test, feature = "test-utils"))] pub use hasher::*; pub use oracle::*; diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index ce129a5af..9b6f76cfc 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -1,9 +1,12 @@ -//! The EVM implementation for the `MegaETH`. +//! The EVM implementation for the `MegaETH` Satin engine. +//! +//! Satin runs a single spec, [`MegaSpecId::SATIN`], on op-revm's Karst handler with EIP-8037 +//! state gas and the EIP-2780 intrinsic cost. The legacy engine (specs `Equivalence` through +//! `Rex7`) is a separate crate line; nothing here executes a legacy spec. #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] -#[cfg_attr(not(feature = "std"), macro_use)] #[cfg(not(feature = "std"))] extern crate alloc; @@ -13,59 +16,44 @@ pub mod constants; mod evm; mod external; mod limit; -pub mod sandbox; -mod system; +pub mod system; #[cfg(any(test, feature = "test-utils"))] pub mod test_utils; mod types; -pub use access::*; pub use block::*; pub use evm::*; pub use external::*; pub use limit::*; -pub use system::*; pub use types::*; -/* Re-export of upstream types */ +/* Re-export of upstream crates, so consumers build against the exact versions used here */ pub use alloy_consensus; -pub use alloy_eips; pub use alloy_evm; pub use alloy_hardforks; pub use alloy_op_evm; -pub use alloy_op_hardforks; pub use alloy_primitives; pub use alloy_sol_types; pub use op_alloy_consensus; -pub use op_alloy_flz; pub use op_revm; -pub use revm::{self, context::either::Either, primitives::HashMap}; +pub use revm; -/* Alias of the mega-evm types */ -/// Alias for [`MegaTransaction`] -pub type Transaction = MegaTransaction; +/* Short aliases of the mega-evm types */ /// Alias for [`MegaSpecId`] pub type SpecId = MegaSpecId; +/// Alias for [`MegaTransaction`] +pub type Transaction = MegaTransaction; /// Alias for [`MegaHaltReason`] pub type HaltReason = MegaHaltReason; /// Alias for [`MegaTransactionError`] pub type TransactionError = MegaTransactionError; -/// Alias for [`MegaPrecompiles`] -pub type Precompiles = MegaPrecompiles; /// Alias for [`MegaTxType`] pub type TxType = MegaTxType; -/// Alias for [`MegaInstructions`] -pub type Instructions = MegaInstructions; -/// Alias for [`MegaHandler`] -pub type Handler = MegaHandler; /// Alias for [`MegaEvm`] -pub type Evm = MegaEvm; +pub type Evm = MegaEvm; /// Alias for [`MegaEvmFactory`] pub type EvmFactory = MegaEvmFactory; /// Alias for [`MegaContext`] -pub type Context = MegaContext; +pub type Context = MegaContext; /// Alias for [`MegaBlockExecutor`] -pub type BlockExecutor = MegaBlockExecutor; -/// Alias for [`MegaBlockExecutorFactory`] -pub type BlockExecutorFactory = - MegaBlockExecutorFactory; +pub type BlockExecutor = MegaBlockExecutor; diff --git a/crates/mega-evm/src/limit/AGENTS.md b/crates/mega-evm/src/limit/AGENTS.md deleted file mode 100644 index c4799024d..000000000 --- a/crates/mega-evm/src/limit/AGENTS.md +++ /dev/null @@ -1,36 +0,0 @@ -# AGENTS.md - -## OVERVIEW -Resource metering subsystem for transaction and frame limits across compute gas, data size, KV updates, and state growth. - -## STRUCTURE -- `limit.rs`: `AdditionalLimit` coordinator and frame/tx lifecycle hooks. -- `compute_gas.rs`: compute gas tracking, detention limits, frame budgets. -- `data_size.rs`: tx/frame data accounting with revert-aware discard paths. -- `kv_update.rs`: tx/frame KV accounting with revert-aware discard paths. -- `state_growth.rs`: net-new account/slot growth accounting. -- `frame_limit.rs`: generic 98/100 frame-limit tracker utilities. -- `storage_call_stipend.rs`: dual-mode stipend — REX5+ separated allowance drained at `storage_gas_ext` sites; REX4 legacy inflation with compute cap and burn-on-return. -- `mod.rs`: `LimitKind`, `LimitCheck`, revert-data ABI surface. - -## KEY PATTERNS -- Limit-check order is deterministic and shared by all opcode paths. -- Distinguish TX-level exceed (halt/OutOfGas) from frame-local exceed (revert). -- All trackers push/pop per-frame in lockstep with EVM frame lifecycle hooks. -- Synthetic frame results still require empty-frame pushes for stack alignment. -- Gas rescue must exclude any system-granted stipend gas. -- Revert paths must roll back discardable usage for data/KV/state growth trackers. - -## ANTI-PATTERNS -- Do not introduce per-frame gas grants without explicit unwind-on-return behavior. -- Do not encode frame-local exceeds as halts. -- They must be reverts with bounded payload. -- Do not read tracker totals after an exceeded-limit revert path unless using tracker-owned finalized APIs. -- Avoid duplicating limit checks inside opcode handlers when the tracker already enforces the same dimension. - -## WHERE TO LOOK -- New limit dimension: add tracker module, wire into `AdditionalLimit`, extend `LimitKind`/`LimitCheck`. -- Change exceed semantics or revert data: `mod.rs` and `limit.rs` helper builders. -- Change compute detention behavior: `compute_gas.rs` and detention callers in `evm` module. -- Change frame budget forwarding logic: `frame_limit.rs` and each tracker’s frame hooks. -- Change storage call stipend semantics: `storage_call_stipend.rs` and `limit.rs` integration points. diff --git a/crates/mega-evm/src/limit/compute_gas.rs b/crates/mega-evm/src/limit/compute_gas.rs deleted file mode 100644 index d37e27cac..000000000 --- a/crates/mega-evm/src/limit/compute_gas.rs +++ /dev/null @@ -1,270 +0,0 @@ -use revm::{handler::FrameResult, interpreter::interpreter_action::FrameInit}; - -use super::{ - frame_limit::{FrameLimitTracker, TxRuntimeLimit}, - LimitCheck, LimitKind, -}; -use crate::{JournalInspectTr, MegaSpecId}; - -/// A frame-limit-based compute gas tracker using `FrameLimitTracker`. -/// -/// Unlike the other trackers (`DataSizeTracker`, `KVUpdateTracker`, `StateGrowthTracker`), compute -/// gas is **always persistent**: CPU cycles cannot be undone, so even if a child frame reverts, -/// its compute gas still counts toward the parent's total. All gas is recorded as -/// `persistent_usage`, never as `discardable_usage` or `refund`. -/// -/// In Rex4+, compute gas is enforced at **both** per-frame and TX level: -/// - **Per-frame**: Each inner call frame receives `remaining * 98 / 100` of the parent's remaining -/// compute gas budget. When a frame exceeds its budget, it reverts (not halts). However, since -/// gas is always persistent, the parent's total gas still increases by the child's actual gas -/// used — per-frame limits act as "early termination guardrails", not budget protection. -/// - **TX-level (detained)**: The effective TX limit may be dynamically lowered by gas detention -/// (volatile data access). In Rex4+ the cap is **relative** to current usage at the access point -/// (`current_usage + cap`), while pre-Rex4 it is absolute. This remains a TX-level halt for all -/// specs including Rex4+. -/// -/// In pre-Rex4, compute gas is enforced at the TX level only. -/// -/// Compute gas is NOT recorded via `TxRuntimeLimit` lifecycle hooks. Instead it is -/// recorded externally via `record_gas_used()` called from: -/// - `compute_gas!` macro in `instructions.rs` (per-opcode) -/// - `execution.rs` frame completion (code deposit cost + initial gas) -/// - `precompiles.rs` (precompile gas) -/// - `sandbox/execution.rs` (sandbox gas) -#[derive(Debug, Clone)] -pub(crate) struct ComputeGasTracker { - rex1_enabled: bool, - rex4_enabled: bool, - /// The effective compute gas limit, which may be dynamically lowered by gas detention - /// (volatile data access). Always <= `frame_tracker.tx_limit()`. - detained_limit: u64, - frame_tracker: FrameLimitTracker<()>, -} - -impl ComputeGasTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - detained_limit: tx_limit, - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - rex1_enabled: spec.is_enabled(MegaSpecId::REX1), - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - } - } - - /// Pushes a new frame onto the tracker. - /// - /// - **Rex4+ top-level**: budget = `tx_entry.remaining()` (accounts for intrinsic compute gas - /// already recorded before the first frame is pushed). - /// - **Rex4+ nested**: budget = parent's remaining × 98/100 (generic behavior). - /// - **Pre-Rex4**: `u64::MAX` (TX-level enforcement only). - fn push_frame(&mut self) { - if self.rex4_enabled { - self.frame_tracker.push_frame(()); - } else { - self.frame_tracker.push_frame_with_limit(u64::MAX, ()); - } - } - - /// Sets the detained compute gas limit (takes the minimum of current and new effective limit). - /// This is used to dynamically lower the compute gas limit when volatile data is accessed. - /// - /// - **REX4+**: The cap is **relative** to current usage — allows `cap` more compute gas after - /// the access point. Effective limit = `current_usage + cap`. - /// - **Pre-REX4**: The cap is **absolute** — effective limit = `cap`. - pub(crate) fn set_detained_limit(&mut self, cap: u64) { - let new_limit = if self.rex4_enabled { - // REX4+: cap is relative to current usage (limits post-access computation) - self.tx_usage().saturating_add(cap) - } else { - // Pre-REX4: cap is absolute - cap - }; - self.detained_limit = self.detained_limit.min(new_limit); - } - - /// Returns the remaining compute gas of the current call. - /// - /// In Rex4+, returns the minimum of the caller's per-frame remaining compute gas - /// and the TX-level detained remaining. This ensures the returned value reflects - /// the actual compute gas available before execution halts, whether due to - /// per-frame budget exhaustion or TX-level gas detention (e.g., after volatile - /// data access like TIMESTAMP). - /// If no frame exists yet (direct TX → system contract), returns the TX-level - /// remaining which accounts for intrinsic compute gas. - /// In pre-Rex4, falls back to TX-level remaining compute gas. - /// - /// Called during system contract interception, before the callee's frame is pushed. - /// At that point `frame_stack.last()` is the caller's frame, so - /// `current_frame_remaining()` gives the caller's remaining compute gas. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = self.tx_limit().saturating_sub(self.tx_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } - - /// Returns the current detained compute gas limit. - pub(crate) fn detained_limit(&self) -> u64 { - self.detained_limit - } - - /// Returns `true` when gas detention is the binding TX-level constraint, i.e., the detained - /// limit is tighter than the base TX limit AND actual usage exceeds it. - pub(crate) fn is_detained_exceed(&self) -> bool { - let used = self.tx_usage(); - used > self.detained_limit && self.detained_limit < self.frame_tracker.tx_limit() - } - - /// Caps the current (top) frame's compute gas budget. - /// - /// Used by the **REX4 legacy** `STORAGE_CALL_STIPEND` path: the child's total gas - /// (`gas_limit`) is inflated by `STORAGE_CALL_STIPEND`, but compute gas must remain - /// bounded at the original `forwarded_gas + CALL_STIPEND` so the extra storage stipend - /// cannot be spent on compute opcodes. This method tightens the per-frame compute gas - /// limit to enforce that cap. - /// - /// REX5+ does not call this method: under the separated-allowance model the child's - /// `gas.limit()` is never inflated, so the per-frame compute budget already equals the - /// pre-inflation amount naturally. - pub(crate) fn cap_current_frame_limit(&mut self, cap: u64) { - if let Some(frame) = self.frame_tracker.frame_mut() { - frame.limit = frame.limit.min(cap); - } - } - - /// Records compute gas as persistent usage in the current frame. - /// If no frame exists (before `frame_init` or after last frame pop), - /// records to the `tx_entry`. - /// - /// Compute gas is always persistent because CPU cycles cannot be undone. - #[inline] - pub(crate) fn record_gas_used(&mut self, gas: u64) { - if !self.frame_tracker.add_frame_persistent(gas) { - self.frame_tracker.add_tx_persistent(gas); - } - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox compute gas consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } -} - -impl TxRuntimeLimit for ComputeGasTracker { - /// Returns the current effective compute gas limit for the entire transaction (may be - /// detained/lowered by volatile data access). - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit().min(self.detained_limit) - } - - /// Returns the current total compute gas used across all frames. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - // Rex1+: reset detained limit to original TX limit between transactions. - // Pre-Rex1: the detained limit persists across transactions. - if self.rex1_enabled { - self.detained_limit = self.frame_tracker.tx_limit(); - } - } - - /// Returns whether the compute gas limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first (`frame_local`: true on exceed), then falls - /// through to the TX-level detained check. Gas detention is always TX-level (`frame_local`: - /// false) across all specs — accessing volatile data caps the whole transaction. - /// - /// Note: unlike state growth in Rex4+, we intentionally do NOT return early on - /// frame-within-limit. Compute gas has TX-scope components (e.g., pre-frame intrinsic compute - /// gas recorded in `tx_entry`) and TX-level detention (`detained_limit`) that can exceed even - /// when the current frame budget is still within limit. - #[inline] - fn check_limit(&self) -> LimitCheck { - if self.rex4_enabled { - let frame_check = self.frame_tracker.exceeds_current_frame_limit(LimitKind::ComputeGas); - if frame_check.exceeded_limit() { - return frame_check; - } - // Do not early-return on frame WithinLimit: - // 1) pre-frame intrinsic compute gas is recorded in `tx_entry`, outside current frame - // budget; - // 2) `detained_limit` can be lowered at runtime by volatile-data access. - // So TX-level detained check must still run even when frame check is within limit. - } - // TX-level detained check (all specs): total usage vs effective limit (min of tx/detained). - let limit = self.tx_limit(); - let used = self.tx_usage(); - if used > limit { - LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - frame_local: false, - limit, - used, - } - } else { - LimitCheck::WithinLimit - } - } - - #[inline] - fn push_empty_frame(&mut self) { - self.push_frame(); - } - - /// Push a new frame when a child call/create starts. - /// Compute gas does not need any data from the `frame_init` input. - #[inline] - fn before_frame_init>( - &mut self, - _frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - self.push_frame(); - Ok(()) - } - - /// Pop frame when returning. Since all gas is recorded as `persistent_usage`, - /// the SUCCESS flag has no effect (only `discardable_usage` and `refund` differ, - /// both are always 0 for compute gas). We use the actual result for convention. - #[inline] - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - self.frame_tracker.pop_frame(result.instruction_result().is_ok()); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Usage exactly equal to the detained limit must NOT count as a detained exceed: - /// the predicate is strictly-greater-than (`used > detained_limit`), not `>=`. - #[test] - fn test_is_detained_exceed_is_strict_at_boundary() { - // tx_limit = 100, detained lowered to 50 (< tx_limit, so detention is binding). - let mut tracker = ComputeGasTracker::new(MegaSpecId::MINI_REX, 100); - tracker.set_detained_limit(50); - - // Usage exactly at the detained limit: not exceeded. - tracker.record_gas_used(50); - assert!( - !tracker.is_detained_exceed(), - "usage == detained_limit must not be a detained exceed" - ); - - // One unit over the limit: exceeded. - tracker.record_gas_used(1); - assert!(tracker.is_detained_exceed(), "usage > detained_limit must be a detained exceed"); - } -} diff --git a/crates/mega-evm/src/limit/data_size.rs b/crates/mega-evm/src/limit/data_size.rs deleted file mode 100644 index ab3840004..000000000 --- a/crates/mega-evm/src/limit/data_size.rs +++ /dev/null @@ -1,406 +0,0 @@ -use alloy_primitives::{Address, U256}; -use revm::{ - context::{transaction::AuthorizationTr, Transaction}, - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, InterpreterAction, - SStoreResult, - }, -}; - -use super::frame_limit::CallFrameInfo; -use crate::{FrameLimitTracker, MegaSpecId, TxRuntimeLimit}; - -/// The number of bytes for the base transaction data. -pub const BASE_TX_SIZE: u64 = 110; -/// The number of bytes for the each EIP-7702 authorization. -pub const AUTHORIZATION_SIZE: u64 = 101; -/// The number of bytes for the each log topic. -pub const LOG_TOPIC_SIZE: u64 = 32; -/// The number of bytes for the salt key. -pub const SALT_KEY_SIZE: u64 = 8; -/// The number of bytes for the salt value delta of the account info. We assume the XOR delta -/// of address, nonce, and code hash is very small, so we can ignore them. The only significant -/// delta is the balance. We over-estimate it to 32 bytes. -pub const SALT_VALUE_DELTA_ACCOUNT_INFO_SIZE: u64 = 32; -/// The number of bytes for the salt value XOR delta of the storage slot. We over-estimate it to -/// 32 bytes. -pub const SALT_VALUE_DELTA_STORAGE_SLOT_SIZE: u64 = 32; -/// The originated data size for reading an account info. -pub const ACCOUNT_INFO_WRITE_SIZE: u64 = SALT_KEY_SIZE + SALT_VALUE_DELTA_ACCOUNT_INFO_SIZE; -/// The originated data size for writing a storage slot. -pub const STORAGE_SLOT_WRITE_SIZE: u64 = SALT_KEY_SIZE + SALT_VALUE_DELTA_STORAGE_SLOT_SIZE; -/// REX6+ per-log base overhead: one value unit (`LOG_TOPIC_SIZE`) for the address every receipt log -/// carries, so an empty `LOG0` is not free in the `data_size` lane. -pub const LOG_BASE_SIZE: u64 = 32; - -/// A tracker for the total data size (in bytes) generated from transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware tracking with per-frame budgets (Rex4+). -/// -/// In Rex4+, data size is enforced at the per-frame level: each inner call frame receives -/// `remaining * 98 / 100` of the parent's remaining data size budget. -/// When a frame exceeds its budget, it reverts (not halts) and its discardable data is dropped, -/// protecting the parent's budget. -/// In pre-Rex4, data size is enforced at the TX level only. -/// -/// ## Tracked Data Types -/// -/// **Non-discardable (permanent):** -/// - Transaction base data: 110 bytes -/// - Calldata: actual byte length -/// - Access lists: sum of access entry sizes -/// - EIP-7702 authorizations: 101 bytes per authorization -/// - Transaction caller account update: 40 bytes -/// - EIP-7702 authority account updates: 40 bytes each -/// -/// **Discardable (reverted on frame revert):** -/// - Log data: 32 bytes per topic + data length -/// - Storage writes: 40 bytes (only when original ≠ new value, refunded when reset to original) -/// - Account updates from calls/creates: 40 bytes each -/// - Contract code: actual deployed bytecode size -#[derive(Debug, Clone)] -pub(crate) struct DataSizeTracker { - rex4_enabled: bool, - rex5_enabled: bool, - rex6_enabled: bool, - frame_tracker: FrameLimitTracker, -} - -impl DataSizeTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - } - } - - /// Returns whether there is at least one active frame on the stack. - pub(crate) fn has_active_frame(&self) -> bool { - self.frame_tracker.has_active_frame() - } - - /// Records discardable data in the current frame. - fn record_discardable(&mut self, size: u64) { - self.frame_tracker.add_frame_discardable(size); - } - - /// Records discardable usage into the PARENT frame (one below the top). Used for a - /// child-CREATE's creator-side account-info write, whose on-chain effect (the creator - /// nonce bump) is undone only by the parent's revert, not the child's. - fn record_parent_discardable(&mut self, size: u64) { - self.frame_tracker.add_parent_discardable(size); - } - - /// Records a refund (negative data) in the current frame. - fn record_refund(&mut self, size: u64) { - self.frame_tracker.add_frame_refund(size); - } - - /// REX5+: meter an oracle-hint payload against the TX intrinsic data-size lane. - /// - /// Hints are a TX-scoped side-channel into the off-chain oracle backend. They do not - /// belong to any call frame (the inner Oracle frame may revert, but the hint has already - /// flowed out), so we record into `tx_entry.persistent_usage` — the same lane as calldata - /// — rather than the current frame's discardable usage. - pub(crate) fn record_oracle_hint_bytes(&mut self, len: u64) { - self.frame_tracker.add_tx_persistent(len); - } - - /// Records an account info write (40 bytes) as discardable data in the current frame. - /// - /// Used by SELFDESTRUCT beneficiary metering (REX5+) to charge data size for - /// creating a new beneficiary account. - pub(crate) fn record_account_write(&mut self) { - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Records an account info write (40 bytes) as TX-level persistent (non-discardable) data. - /// - /// Used by the REX6 EIP-7702 authorization scan, which runs in `validate` before any frame - /// exists, so the charge cannot go through the frame-scoped `record_account_write`. - pub(crate) fn record_persistent_account_write(&mut self) { - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox data size consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining data size budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for DataSizeTracker { - /// Returns the current effective data size limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current total data size across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the data size limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic overflow when no frame exists yet - /// (intrinsic usage is recorded in `tx_entry` before the first frame is pushed). - /// In pre-Rex4, checks total data size across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.rex4_enabled { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::DataSize); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: defense-in-depth safety net. - // In Rex4+ during execution, per-frame budgets are derived from remaining TX - // budget, so this should only exceed when no frame exists (intrinsic overflow). - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - // Defense-in-depth: pre-REX5, the only mid-execution writer to `tx_entry` is - // `before_tx_start` (which runs before any frame is pushed), so a TX-level - // exceed with an active frame indicates a budget-accounting bug. REX5+ adds - // `record_oracle_hint_bytes` which legitimately writes to `tx_entry` mid- - // execution to meter oracle-hint payloads as TX-scoped side-channel cost, so - // the invariant is only asserted on pre-REX5 specs. - debug_assert!( - !self.rex4_enabled || self.rex5_enabled || !self.frame_tracker.has_active_frame(), - "DataSize TX-level exceeded with active frame — budget invariant violated" - ); - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::DataSize, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// Records the data size of a transaction at the start of execution. - /// - /// This includes: - /// - 110 bytes base transaction data - /// - Calldata byte length - /// - Access list sizes - /// - EIP-7702 authorizations (101 bytes each) + authority account updates (40 bytes each) - /// - Caller account update (40 bytes) - /// - /// All recorded as pre-frame (non-discardable) since no frame exists yet. - fn before_tx_start(&mut self, tx: &crate::MegaTransaction) { - // TX intrinsic data (non-discardable, recorded before any frame is pushed) - let mut size = BASE_TX_SIZE; - size += tx.input().len() as u64; - size += tx - .access_list() - .map(|item| item.map(|access| access.size() as u64).sum::()) - .unwrap_or_default(); - size += tx.authorization_list_len() as u64 * AUTHORIZATION_SIZE; - self.frame_tracker.add_tx_persistent(size); - - // EIP-7702 authority account updates (non-discardable). - // - // Pre-REX6: charged here for every authorization with a recoverable authority, even ones - // that fail the chain-id / nonce / code application gates and never write the account. - // REX6+ moves this charge into the journal-aware authorization scan in `validate` so only - // *applied* authorities are charged; skip it here. - if !self.rex6_enabled { - for authorization in tx.authorization_list() { - if authorization.authority().is_some() { - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - - // Caller account update (non-discardable) - self.frame_tracker.add_tx_persistent(ACCOUNT_INFO_WRITE_SIZE); - } - - /// Called when inspector intercepts and skips a call/create. - /// - /// Pushes an empty frame so `before_frame_return_result` can pop it to keep - /// the frame stack aligned with the EVM's call stack. - #[inline] - fn push_empty_frame(&mut self) { - self.frame_tracker.push_dummy_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Pushes a new frame and records account info updates: - /// - **Call with value transfer**: Updates parent's account info if not yet marked, then - /// records target account info update (40 bytes each). - /// - **Create**: Updates parent's account info if not yet marked (caller nonce increment). - /// Created address is set later in `after_frame_init_on_frame`. - /// - **Call without transfer**: No account info updates. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - let has_transfer = call_inputs.transfers_value(); - let parent_needs_update = - self.frame_tracker.push_call_frame(call_inputs.target_address, has_transfer); - if has_transfer { - if parent_needs_update { - // Parent's account info update goes to child's discardable. - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - // A value transfer to the caller itself touches a single account, already - // accounted by the caller-side write above (or, at the top level, by the - // `before_tx_start` caller record). Recording the target side again would - // double-count that one account, so skip it under REX6. - if !(self.rex6_enabled && call_inputs.target_address == call_inputs.caller) { - // Record target account info update in child's discardable. - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - FrameInput::Create(_) => { - let parent_needs_update = self.frame_tracker.push_create_frame(); - if parent_needs_update { - if self.rex6_enabled { - // The creator's nonce bump survives the child's revert (revm bumps it - // before the create checkpoint), so charge it to the parent frame — - // see `FrameLimitTracker::add_parent_discardable`. - self.record_parent_discardable(ACCOUNT_INFO_WRITE_SIZE); - } else { - // Pre-REX6: the creator nonce-bump charge is bundled into the child frame's - // discardable lane (frozen behavior). - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a new execution frame is successfully initialized. - /// - /// For CREATE frames, records the created address and its account info update (40 bytes). - fn after_frame_init_on_frame(&mut self, frame: &EthFrame) { - if frame.data.is_create() { - let created_address = - frame.data.created_address().expect("created address is none for create frame"); - self.frame_tracker.set_created_address(created_address); - // Record account info update for created address - self.record_discardable(ACCOUNT_INFO_WRITE_SIZE); - } - } - - /// Hook called after a frame finishes running. - /// - /// For CREATE frames, records the deployed contract bytecode size as discardable data. - fn after_frame_run<'a>( - &mut self, - frame: &'a EthFrame, - action: &'a mut InterpreterAction, - ) { - if let InterpreterAction::Return(interpreter_result) = action { - if frame.data.is_create() { - let code_size = interpreter_result.output.len() as u64; - self.record_discardable(code_size); - } - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Pops the current frame from the tracker: - /// - **On success**: merges the frame's data into the parent frame. - /// - **On revert/failure**: discards the frame's discardable data. - /// - /// Rex5+: if the reverting child had set the parent's account-update flag, the flag - /// is reset so the next successful call from the same parent still charges the parent - /// account (avoiding undercounting after a revert-then-retry pattern). The unwind is - /// owned by `FrameLimitTracker::pop_frame_unwind_parent`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - let is_success = result.instruction_result().is_ok(); - self.frame_tracker.pop_frame_unwind_parent(is_success); - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// Records SSTORE data based on the storage slot's state transition: - /// - /// | Original == Present | Original == New | Effect | Reason | - /// |---------------------|-----------------|------------------------|-------------------------| - /// | yes | yes | — | No change | - /// | yes | no | +40 bytes (discardable)| First write to slot | - /// | no | yes | -40 bytes (refund) | Reset to original value | - /// | no | no | — | Rewrite, no new data | - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - if store_result.is_original_eq_present() { - if !store_result.is_original_eq_new() { - // First write to slot: original == present, but new differs - self.record_discardable(STORAGE_SLOT_WRITE_SIZE); - } - } else if store_result.is_original_eq_new() { - // Reset to original: refund - self.record_refund(STORAGE_SLOT_WRITE_SIZE); - } - } - - /// Hook called when a log is emitted. - /// - /// Records `LOG_BASE_SIZE` (REX6+ only) + `num_topics * 32` + `data_size` as discardable. - fn after_log(&mut self, num_topics: u64, data_size: u64) { - let base = if self.rex6_enabled { LOG_BASE_SIZE } else { 0 }; - let size = base + num_topics * LOG_TOPIC_SIZE + data_size; - self.record_discardable(size); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The originated data-size constants are *sums* of their salt key/value components, - /// not products. Pin the values against independent literals so an arithmetic slip - /// (e.g. `+` -> `*`) is caught (8 + 32 = 40, not 8 * 32 = 256). - #[test] - fn test_originated_data_size_constants() { - assert_eq!(STORAGE_SLOT_WRITE_SIZE, 40); - assert_eq!(ACCOUNT_INFO_WRITE_SIZE, 40); - } - - /// `has_active_frame` must reflect the underlying frame stack, not a constant. - #[test] - fn test_has_active_frame_reflects_frame_stack() { - let mut tracker = DataSizeTracker::new(MegaSpecId::MINI_REX, u64::MAX); - assert!(!tracker.has_active_frame(), "no frame pushed yet"); - tracker.push_empty_frame(); - assert!(tracker.has_active_frame(), "a frame is on the stack"); - } -} diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 6ff0b5df1..c324f3b7c 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -1,648 +1,393 @@ +//! The per-frame tracker of data-size bytes and write records. +//! +//! Every frame on the call stack has a lane. What a frame writes is counted on its lane; when the +//! frame returns, a success merges the lane into its caller's and a failure discards it, the way +//! the journal keeps or reverts the writes themselves. What is counted outside any frame (the +//! records of applied EIP-7702 authorities) and what the outermost frame kept sit on the +//! transaction's own lane. +//! +//! Every operation is O(1): the totals are cached and kept in step with each change. + #[cfg(not(feature = "std"))] use alloc as std; -use alloy_primitives::{Address, U256}; -use revm::{ - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, InterpreterAction, SStoreResult, - }, -}; use std::vec::Vec; -use crate::{constants, JournalInspectTr, MegaSpecId, MegaTransaction}; - -use super::{LimitCheck, LimitKind}; - -/// Per-frame metadata for trackers that need account update deduplication -/// (data size and KV update trackers). -/// -/// All fields are private to this module: the -/// `push_call_frame` / `push_create_frame` / `pop_frame_unwind_parent` methods on -/// `FrameLimitTracker` own the invariant that wires `target_updated` and -/// `charged_parent_update` together. Callers should not touch these fields directly. -#[derive(Debug, Clone, Default)] -pub(crate) struct CallFrameInfo { - /// The target address of the frame. `None` during CREATE until the address is known. - target_address: Option
, - /// Whether this frame's target address has been marked as updated. - target_updated: bool, - /// True when this frame caused the parent's `target_updated` to be flipped to `true` - /// (Rex5+ only). Used by `pop_frame_unwind_parent` to undo the parent flag on revert, - /// so a subsequent successful call from the same parent still charges the parent account. - charged_parent_update: bool, -} - -#[derive(Debug, Clone)] -pub(crate) struct FrameLimitTracker { - /// Top-level (TX-scope) entry. Holds the TX limit and accumulates usage - /// from pre-frame data and from the last frame pop. - tx_entry: FrameLimitEntry<()>, - /// Stack of child frame entries. - frame_stack: Vec>, - /// Whether Rex4 (per-frame budgeting) is active. Used by the `CallFrameInfo` - /// specialization to choose between `push_frame` (Rex4+) and `push_frame_with_limit` - /// (`u64::MAX` for pre-Rex4) when constructing call/create/intercept frames. - /// Other instantiations (`FrameLimitTracker<()>`) currently do not consult this flag. - rex4_enabled: bool, - /// Whether Rex5 (parent account update dedup) is active. Used by the `CallFrameInfo` - /// specialization to gate the `target_updated` mutation in `push_call_frame` / - /// `push_create_frame` and the matching unwind in `pop_frame_unwind_parent`. - /// Other instantiations do not consult this flag. - rex5_enabled: bool, - /// Whether Rex6 is active. Used by the `CallFrameInfo` specialization: a CREATE's - /// creator-side charge survives the child's revert (revm bumps the creator nonce before the - /// create checkpoint), so under Rex6 `push_create_frame` does not arm the - /// `charged_parent_update` unwind — a reverted-then-retried CREATE must not charge the - /// creator account update twice. Rex5 keeps the (over-unwinding) frozen behavior. - rex6_enabled: bool, - - /// Cached `Σ(persistent_usage + discardable_usage)` across `tx_entry` and every entry on - /// `frame_stack`. Maintained incrementally so `net_usage()` is O(1) instead of O(depth) - /// per opcode. See `net_usage()` for the invariant and `pop_frame` for the revert delta. - cached_total_used: u64, - /// Cached `Σ refund` across `tx_entry` and every entry on `frame_stack`. Maintained - /// together with `cached_total_used` so `net_usage = saturating_sub(used, refund)` is - /// a single subtraction. - cached_total_refund: u64, -} - -/// Per-frame budget entry on the frame stack. -#[derive(Debug, Clone)] -pub(crate) struct FrameLimitEntry { - /// Maximum usage allowed in this frame. - pub(crate) limit: u64, - - // The three budget fields below MUST only be mutated through `FrameLimitTracker`'s - // cache-aware helpers (`add_tx_persistent`, `add_frame_persistent`, - // `add_frame_discardable`, `add_frame_refund`) or through `pop_frame`'s explicit - // cache deltas. Writing them directly desyncs `cached_total_used` / - // `cached_total_refund` and silently corrupts every subsequent `net_usage()` result. - /// Persistent usage in this frame even if it is reverted. - persistent_usage: u64, - /// Discardable usage if this frame is reverted. - discardable_usage: u64, - /// Refund usage in this frame. - refund: u64, - - /// Additional information about the frame. - #[allow(dead_code)] - pub(crate) info: I, -} - -impl FrameLimitEntry { - pub(crate) fn new(limit: u64, info: I) -> Self { - Self { limit, persistent_usage: 0, discardable_usage: 0, refund: 0, info } - } - - /// Returns the remaining budget for this frame. - /// - /// Computed as `limit - (used - refund)`, clamped to `[0, limit]`. - /// The net usage (`used - refund`) is computed first to stay consistent with - /// the exceed check in `exceeds_current_frame_limit`. - #[inline] - pub(crate) fn remaining(&self) -> u64 { - self.limit.saturating_sub(self.used().saturating_sub(self.refund)) - } - - /// Returns usage for this frame. - #[inline] - pub(crate) fn used(&self) -> u64 { - self.persistent_usage.checked_add(self.discardable_usage).expect("overflow") - } +use alloy_primitives::Address; + +use super::{LimitUsage, WRITE_RECORD}; + +/// One frame's lane. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Lane { + /// What the frame, and the children it kept, counted. + pub(crate) used: LimitUsage, + /// What the frame, and the children it kept, took back: a slot written back to its original + /// value. + pub(crate) refund: LimitUsage, + /// The account the frame runs as. `None` until known (a creation learns it at frame init). + pub(crate) address: Option
, + /// Whether a write to the frame's own account is already counted, so a value transfer or a + /// creation from the frame does not count it again. + pub(crate) account_recorded: bool, + /// Whether this lane holds the record of its caller's account, made when the frame started + /// (a value transfer's sender, a creation's creator). Its failure discards that record, so the + /// caller's account is no longer recorded either. + pub(crate) holds_caller_record: bool, + /// Whether the caller's record on this lane is a creator's nonce, which survives the + /// creation's failure once the nonce was bumped. + pub(crate) creator_record: bool, + /// The most data-size bytes the frame may keep; `u64::MAX` when it has no budget. + pub(crate) budget: u64, } -impl FrameLimitTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { +impl Lane { + /// A lane for a frame running as `address`. + pub(crate) const fn new(address: Option
, account_recorded: bool, budget: u64) -> Self { Self { - tx_entry: FrameLimitEntry::new(tx_limit, ()), - frame_stack: Vec::new(), - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - cached_total_used: 0, - cached_total_refund: 0, + used: LimitUsage::ZERO, + refund: LimitUsage::ZERO, + address, + account_recorded, + holds_caller_record: false, + creator_record: false, + budget, } } - /// Returns the TX-level limit. - pub(crate) fn tx_limit(&self) -> u64 { - self.tx_entry.limit + /// A lane for a frame that does not run: a result built without an interpreter. + pub(crate) const fn empty() -> Self { + Self::new(None, false, u64::MAX) } - /// Resets the tracker for a new transaction. - pub(crate) fn reset(&mut self) { - self.tx_entry.persistent_usage = 0; - self.tx_entry.discardable_usage = 0; - self.tx_entry.refund = 0; - self.frame_stack.clear(); - self.cached_total_used = 0; - self.cached_total_refund = 0; + /// What the frame keeps if it succeeds. + pub(crate) const fn net(&self) -> LimitUsage { + self.used.saturating_sub(self.refund) } - /// Returns the remaining budget of the current frame. - /// - /// If the frame stack is non-empty, returns the top frame's remaining budget. - /// If the frame stack is empty (before the first frame is pushed), returns - /// the TX-level remaining which accounts for pre-frame usage (e.g. intrinsic charges). - pub(crate) fn current_frame_remaining(&self) -> u64 { - match self.frame_stack.last() { - Some(entry) => entry.remaining(), - None => self.tx_entry.remaining(), - } - } - - /// Returns the maximum limit that can be forwarded to the next frame. - /// - /// - **Nested frame**: parent's remaining × 98/100. - /// - **Top-level frame** (empty stack): `tx_entry.remaining()`, which accounts for pre-frame - /// intrinsic usage (e.g., calldata size, access lists) already charged into `tx_entry`. - /// - /// Individual trackers that need a different top-level budget should use - /// `push_frame_with_limit()` instead of `push_frame()`. - fn max_forward_limit(&self) -> u64 { - match self.frame_stack.last() { - Some(entry) => { - let remaining = u128::from(entry.remaining()); - let numerator = u128::from(constants::rex4::FRAME_LIMIT_NUMERATOR); - let denominator = u128::from(constants::rex4::FRAME_LIMIT_DENOMINATOR); - ((remaining * numerator) / denominator) as u64 - } - None => self.tx_entry.remaining(), - } - } - - pub(crate) fn push_frame(&mut self, info: I) { - self.frame_stack.push(FrameLimitEntry::new(self.max_forward_limit(), info)); - } - - /// Pops the current frame from the stack and merges its usage into the parent. - /// - /// On success: `persistent_usage`, `discardable_usage`, and `refund` are all merged. - /// On failure: only `persistent_usage` is merged; `discardable_usage` and `refund` are dropped. - /// - /// Cache invariant: every mutation to `persistent_usage` / `discardable_usage` / `refund` - /// — whether via the public helpers or via this pop — keeps `cached_total_used` and - /// `cached_total_refund` in sync. On revert the child's `discardable_usage` and `refund` - /// are subtracted from the cache because they vanish (they are neither kept on the child - /// nor merged into the parent). - pub(crate) fn pop_frame(&mut self, success: bool) -> Option> { - let child = self.frame_stack.pop(); - if let Some(child) = &child { - if let Some(parent) = self.frame_stack.last_mut() { - // Persistent usage is always preserved: move from child slot to parent slot. - // The cache already counts it once, so no cache update is needed here. - parent.persistent_usage += child.persistent_usage; - if success { - // Discardable & refund are preserved on success — same total, just relocated - // from child entry to parent entry. Cache stays the same. - parent.discardable_usage += child.discardable_usage; - parent.refund += child.refund; - } else { - // Revert: child's discardable_usage and refund vanish entirely. Subtract them - // from the cache to maintain the `Σ(persistent + discardable) - Σ refund` - // invariant. - self.cached_total_used -= child.discardable_usage; - self.cached_total_refund -= child.refund; - } - } else { - // Last frame popped — merge into tx_entry. Same cache reasoning as the parent - // branch above. - self.tx_entry.persistent_usage += child.persistent_usage; - if success { - self.tx_entry.discardable_usage += child.discardable_usage; - self.tx_entry.refund += child.refund; - } else { - self.cached_total_used -= child.discardable_usage; - self.cached_total_refund -= child.refund; - } - } - } - child - } - - /// Returns whether the current frame has exceeded its frame-local limit. - /// If exceeded, `frame_local` is always `true` since this checks per-frame budgets. - pub(crate) fn exceeds_current_frame_limit(&self, kind: LimitKind) -> LimitCheck { - match self.frame_stack.last() { - Some(entry) if entry.used().saturating_sub(entry.refund) > entry.limit => { - LimitCheck::ExceedsLimit { - kind, - limit: entry.limit, - used: entry.used(), - frame_local: true, - } - } - _ => LimitCheck::WithinLimit, - } + /// The data-size bytes the frame may still keep. + pub(crate) const fn remaining_budget(&self) -> u64 { + self.budget.saturating_sub(self.net().data_size) } +} - /// Returns a mutable reference to the current (top) frame entry. - pub(crate) fn frame_mut(&mut self) -> Option<&mut FrameLimitEntry> { - self.frame_stack.last_mut() - } +/// The lanes of the running transaction. +#[derive(Clone, Debug, Default)] +pub(crate) struct FrameLimitTracker { + /// What the transaction counted outside any running frame, and what the outermost frame kept. + tx_used: LimitUsage, + /// What the outermost frame kept of its refunds. + tx_refund: LimitUsage, + /// One lane per frame on the call stack, the running frame last. + lanes: Vec, + /// `tx_used` plus every lane's `used`. + total_used: LimitUsage, + /// `tx_refund` plus every lane's `refund`. + total_refund: LimitUsage, +} - /// Returns whether there is at least one active frame on the stack. - pub(crate) fn has_active_frame(&self) -> bool { - !self.frame_stack.is_empty() +impl FrameLimitTracker { + /// Clears the tracker for a new transaction, keeping its allocation. + pub(crate) fn reset(&mut self) { + self.tx_used = LimitUsage::ZERO; + self.tx_refund = LimitUsage::ZERO; + self.lanes.clear(); + self.total_used = LimitUsage::ZERO; + self.total_refund = LimitUsage::ZERO; } - /// Pushes a new frame with a custom limit, bypassing `max_forward_limit()`. - /// - /// Used by pre-Rex4 specs (`u64::MAX`, per-frame limits not enforced) and by any tracker that - /// intentionally wants to bypass the default `max_forward_limit()` behavior. - pub(crate) fn push_frame_with_limit(&mut self, limit: u64, info: I) { - self.frame_stack.push(FrameLimitEntry::new(limit, info)); + /// The number of lanes, which is the number of frames on the call stack. + pub(crate) fn depth(&self) -> usize { + self.lanes.len() } - /// Returns the total net usage across `tx_entry` and all frames on the stack. - /// Net usage = Σ(`persistent_usage` + `discardable_usage`) - Σ(refund), clamped to 0. - /// - /// O(1): served from `cached_total_used` / `cached_total_refund`, which are maintained - /// incrementally by `add_tx_persistent`, `add_frame_persistent`, `add_frame_discardable`, - /// `add_frame_refund`, and `pop_frame`. - #[inline] - pub(crate) fn net_usage(&self) -> u64 { - let net_usage = self.cached_total_used.saturating_sub(self.cached_total_refund); - #[cfg(debug_assertions)] - assert_eq!( - net_usage, - self.net_usage_uncached(), - "cached net_usage must match uncached reference" - ); - net_usage + /// What the transaction keeps if every running frame succeeds. + pub(crate) const fn net(&self) -> LimitUsage { + self.total_used.saturating_sub(self.total_refund) } - /// Reference implementation of `net_usage` that walks `tx_entry + frame_stack` directly. - /// Active only in debug builds (gated by `cfg(debug_assertions)`), where it backs the - /// per-call assertion inside `net_usage()` so the incremental cache is verified against - /// the slow O(depth) walk on every opcode in tests and dev runs. Release builds - /// (including `cargo bench` and production) compile this out entirely. - #[cfg(any(debug_assertions, test))] - fn net_usage_uncached(&self) -> u64 { - let mut total_used: u64 = self.tx_entry.used(); - let mut total_refund: u64 = self.tx_entry.refund; - for entry in &self.frame_stack { - total_used += entry.used(); - total_refund += entry.refund; - } - total_used.saturating_sub(total_refund) + /// The running frame's lane. + pub(crate) fn current(&self) -> Option<&Lane> { + self.lanes.last() } - /// Adds `n` to `tx_entry.persistent_usage` and keeps the cache in sync. - /// - /// Used by trackers to record intrinsic / pre-frame usage (e.g. base TX size, - /// EIP-7702 authority updates, caller account update). The current frame stack - /// may be empty (pre-`frame_init`) or non-empty (`compute_gas`'s fallback when no - /// frame exists). - #[inline] - pub(crate) fn add_tx_persistent(&mut self, n: u64) { - self.tx_entry.persistent_usage += n; - self.cached_total_used += n; + /// The running frame's lane, mutably. + pub(crate) fn current_mut(&mut self) -> Option<&mut Lane> { + self.lanes.last_mut() } - /// Adds `n` to the current top frame's `persistent_usage` and keeps the cache in sync. - /// Returns `false` (and does nothing) when the frame stack is empty — callers that - /// need a tx-level fallback must check the return value. - #[inline] - pub(crate) fn add_frame_persistent(&mut self, n: u64) -> bool { - match self.frame_stack.last_mut() { - Some(entry) => { - entry.persistent_usage += n; - self.cached_total_used += n; - true - } - None => false, - } + /// Pushes the lane of a frame that starts. + pub(crate) fn push(&mut self, lane: Lane) { + self.total_used = self.total_used.saturating_add(lane.used); + self.total_refund = self.total_refund.saturating_add(lane.refund); + self.lanes.push(lane); } - /// Adds `n` to the current top frame's `discardable_usage` and keeps the cache in sync. - /// No-op when the frame stack is empty (discardable usage requires a frame to be - /// discardable into; pre-frame usage is always persistent). - #[inline] - pub(crate) fn add_frame_discardable(&mut self, n: u64) { - if let Some(entry) = self.frame_stack.last_mut() { - entry.discardable_usage += n; - self.cached_total_used += n; + /// Counts `usage` on the running frame's lane, or on the transaction's outside any frame. + pub(crate) fn record(&mut self, usage: LimitUsage) { + match self.lanes.last_mut() { + Some(lane) => lane.used = lane.used.saturating_add(usage), + None => self.tx_used = self.tx_used.saturating_add(usage), } + self.total_used = self.total_used.saturating_add(usage); } - /// Adds `n` to the current top frame's `refund` and keeps the cache in sync. - /// No-op when the frame stack is empty. - #[inline] - pub(crate) fn add_frame_refund(&mut self, n: u64) { - if let Some(entry) = self.frame_stack.last_mut() { - entry.refund += n; - self.cached_total_refund += n; + /// Takes `usage` back on the running frame's lane. Outside any frame nothing is taken back. + pub(crate) fn refund(&mut self, usage: LimitUsage) { + if let Some(lane) = self.lanes.last_mut() { + lane.refund = lane.refund.saturating_add(usage); + self.total_refund = self.total_refund.saturating_add(usage); } } - /// Adds `n` to the parent frame's `discardable_usage` (the frame directly beneath the - /// current top) and keeps the cache in sync. No-op when the current frame is top-level. + /// Records the running frame's caller's account on the running frame's lane, unless the + /// caller's lane already counts it. A `creator` record is a creation's nonce. /// - /// Used by REX6 CREATE accounting to charge the creator's nonce-bump account-info write to - /// the parent (creator) frame instead of the child (created) frame. revm increments the - /// creator's nonce *before* it takes the create checkpoint, so the nonce bump survives the - /// created contract's revert and is undone only if the creator's own frame reverts. - /// Recording the charge on the parent's discardable lane matches that lifetime: it is kept - /// when the child reverts and dropped only with the parent. - /// - /// This is the opposite of a value-transferring CALL, whose balance moves *are* rolled back - /// when the callee reverts — those are correctly charged to the child's discardable lane. - #[inline] - pub(crate) fn add_parent_discardable(&mut self, n: u64) { - if let Some((_current, below)) = self.frame_stack.split_last_mut() { - if let Some(parent) = below.last_mut() { - parent.discardable_usage += n; - self.cached_total_used += n; - } + /// Must run right after the running frame's lane was pushed, with the caller's lane below it. + pub(crate) fn record_caller(&mut self, creator: bool) { + let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; + if caller.account_recorded { + return; } - } -} - -impl FrameLimitTracker { - /// Pushes a new `CallFrameInfo` frame using the per-spec budget choice: - /// - **Rex4+**: `max_forward_limit()` (parent × 98/100, or `tx_entry.remaining()` at top - /// level). - /// - **Pre-Rex4**: `u64::MAX` since per-frame limits are not enforced. - fn push_call_frame_info(&mut self, info: CallFrameInfo) { - if self.rex4_enabled { - self.push_frame(info); - } else { - self.push_frame_with_limit(u64::MAX, info); + caller.account_recorded = true; + lane.holds_caller_record = true; + lane.creator_record = creator; + lane.used = lane.used.saturating_add(WRITE_RECORD); + self.total_used = self.total_used.saturating_add(WRITE_RECORD); + } + + /// Drops the caller's record from the running frame's lane: the frame failed before the + /// write it stands for happened (a creation that did not bump the creator's nonce). + pub(crate) fn drop_caller_record(&mut self) { + let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; + if !lane.holds_caller_record { + return; } + caller.account_recorded = false; + lane.holds_caller_record = false; + lane.creator_record = false; + lane.used = lane.used.saturating_sub(WRITE_RECORD); + self.total_used = self.total_used.saturating_sub(WRITE_RECORD); } - /// Pushes a synthetic frame for inspector / access-control interception paths. - /// - /// No parent-flag mutation: an intercepted call is short-circuited before any - /// state-modifying account update is recorded, so the parent does not need to be marked. - /// The frame exists only to keep the per-tracker frame stack aligned with the EVM's call - /// stack so that the matching `pop_frame_unwind_parent` finds an entry to pop. - pub(crate) fn push_dummy_frame(&mut self) { - self.push_call_frame_info(CallFrameInfo::default()); - } - - /// Pushes a CALL frame and updates the parent's dedup flag. + /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or + /// the transaction's), a failure discards it. /// - /// Returns `true` when the parent's account info should be charged by the caller - /// (i.e., the parent has not been marked updated yet *and* this call transfers value). - /// Rex5+: the parent's `target_updated` flag is set so subsequent value-transferring - /// calls from the same parent frame don't double-charge the caller account; the - /// `charged_parent_update` flag is recorded on the new child so a revert can unwind it. - /// Pre-Rex5: the parent flag is left untouched, preserving pre-Rex5 semantics. - pub(crate) fn push_call_frame(&mut self, target: Address, has_transfer: bool) -> bool { - let rex5_enabled = self.rex5_enabled; - let parent_needs_update = has_transfer && - match self.frame_mut() { - Some(entry) if !entry.info.target_updated => { - if rex5_enabled { - entry.info.target_updated = true; + /// A creator's record outlives the creation's failure; any other record of the caller dies + /// with it, and the caller's account stops counting as recorded. + pub(crate) fn pop(&mut self, success: bool) -> Option { + let lane = self.lanes.pop()?; + if success { + match self.lanes.last_mut() { + Some(caller) => { + caller.used = caller.used.saturating_add(lane.used); + caller.refund = caller.refund.saturating_add(lane.refund); + if lane.address.is_some() && lane.address == caller.address { + caller.account_recorded |= lane.account_recorded; } - true } - _ => false, - }; - let charged_parent_update = rex5_enabled && parent_needs_update; - self.push_call_frame_info(CallFrameInfo { - target_address: Some(target), - target_updated: has_transfer, - charged_parent_update, - }); - parent_needs_update - } - - /// Pushes a CREATE frame and updates the parent's dedup flag. - /// - /// Returns `true` when the parent's account info should be charged by the caller - /// (i.e., the parent has not been marked updated yet — CREATE always increments the - /// caller's nonce, so there is no `has_transfer` gate). - /// The created address is unknown at push time; callers should fill it in via - /// `set_created_address` once `frame_init` completes. - /// Rex5+ deduplication semantics match `push_call_frame`. - pub(crate) fn push_create_frame(&mut self) -> bool { - let rex5_enabled = self.rex5_enabled; - let parent_needs_update = match self.frame_mut() { - Some(entry) if !entry.info.target_updated => { - if rex5_enabled { - entry.info.target_updated = true; + None => { + self.tx_used = self.tx_used.saturating_add(lane.used); + self.tx_refund = self.tx_refund.saturating_add(lane.refund); } - true } - _ => false, - }; - // Rex6: the creator's nonce bump survives the child CREATE's revert, and its charge - // lives on the parent's discardable lane — do not arm the unwind, or a - // revert-then-retry CREATE re-charges the same creator account update. Rex5 keeps the - // frozen unwind (its charge lived on the child lane and was dropped with it). - let charged_parent_update = rex5_enabled && parent_needs_update && !self.rex6_enabled; - self.push_call_frame_info(CallFrameInfo { - target_address: None, - target_updated: true, - charged_parent_update, - }); - parent_needs_update - } - - /// Records the created address on the current CREATE frame. - /// - /// Asserts that the current frame's `target_address` has not already been set, - /// matching the previous inline behavior. Does nothing if the frame stack is empty. - pub(crate) fn set_created_address(&mut self, addr: Address) { - if let Some(entry) = self.frame_mut() { - assert!(entry.info.target_address.is_none(), "created account already recorded"); - entry.info.target_address = Some(addr); + return Some(lane); } - } - - /// Pops the current frame and, on revert, unwinds the parent's `target_updated` flag - /// if this child set it. - /// - /// Rex5+ only: when the reverting child had `charged_parent_update` set, the parent's - /// `target_updated` is reset so the next successful call from the same parent still - /// charges the parent account (avoiding undercounting after a revert-then-retry pattern). - /// Pre-Rex5 child frames have `charged_parent_update = false`, so this method behaves - /// identically to `pop_frame` for older specs. - pub(crate) fn pop_frame_unwind_parent(&mut self, success: bool) { - let child = self.pop_frame(success); - if !success { - if let Some(child_entry) = child { - if child_entry.info.charged_parent_update { - // charged_parent_update=true implies a parent frame exists - // (the flag is only set when frame_mut() returned Some). - self.frame_mut() - .expect("parent frame must exist when charged_parent_update is true") - .info - .target_updated = false; - } + self.total_used = self.total_used.saturating_sub(lane.used); + self.total_refund = self.total_refund.saturating_sub(lane.refund); + if let Some(caller) = self.lanes.last_mut() { + if lane.creator_record { + caller.used = caller.used.saturating_add(WRITE_RECORD); + self.total_used = self.total_used.saturating_add(WRITE_RECORD); + } else if lane.holds_caller_record { + caller.account_recorded = false; } } + Some(lane) } -} -pub(crate) trait TxRuntimeLimit { - fn tx_limit(&self) -> u64; - fn tx_usage(&self) -> u64; - fn reset(&mut self); - fn check_limit(&self) -> LimitCheck; - - #[inline] - fn before_tx_start(&mut self, _tx: &MegaTransaction) {} - #[inline] - fn push_empty_frame(&mut self) {} - #[inline] - fn before_frame_init>( - &mut self, - _frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - Ok(()) - } - #[inline] - fn after_frame_init_on_frame(&mut self, _frame: &EthFrame) {} - #[inline] - fn before_frame_run(&mut self, _frame: &EthFrame) {} - #[inline] - fn after_frame_run<'a>( - &mut self, - _frame: &'a EthFrame, - _action: &'a mut InterpreterAction, - ) { - } - #[inline] - fn before_frame_return_result(&mut self, _result: &FrameResult) {} - #[inline] - fn after_sstore( - &mut self, - _target_address: Address, - _slot: U256, - _store_result: &SStoreResult, - ) { + /// [`net`](Self::net) recomputed from the lanes, for checking the cache. + #[cfg(test)] + pub(crate) fn net_uncached(&self) -> LimitUsage { + let mut used = self.tx_used; + let mut refund = self.tx_refund; + for lane in &self.lanes { + used = used.saturating_add(lane.used); + refund = refund.saturating_add(lane.refund); + } + used.saturating_sub(refund) } - fn after_log(&mut self, _num_topics: u64, _data_size: u64) {} - #[inline] - fn after_selfdestruct(&mut self, _refund: u64) {} } #[cfg(test)] mod tests { - use alloy_primitives::address; - use super::*; + use alloy_primitives::address; const ADDR: Address = address!("0000000000000000000000000000000000001234"); - /// `set_created_address` on an empty frame stack must be a no-op. - #[test] - fn test_set_created_address_empty_stack_is_noop() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - // No frame on the stack — should not panic, just do nothing. - t.set_created_address(ADDR); + const fn bytes(data_size: u64) -> LimitUsage { + LimitUsage { data_size, write_records: 0 } } - /// `set_created_address` panics when called twice on the same CREATE frame - /// (invariant: `target_address` must be `None` when first filled in). + /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. #[test] - #[should_panic(expected = "created account already recorded")] - fn test_set_created_address_duplicate_panics() { - let mut t = FrameLimitTracker::::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_create_frame(); - t.set_created_address(ADDR); - t.set_created_address(ADDR); // second call must panic + fn test_record_caller_without_a_caller_lane_is_noop() { + let mut t = FrameLimitTracker::default(); + t.record_caller(true); + assert_eq!(t.net(), LimitUsage::ZERO); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.record_caller(true); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.current().unwrap().holds_caller_record); } - /// Drives `FrameLimitTracker` through a representative sequence of pushes, mutations, - /// and pops (both success and revert) and asserts that the cached `net_usage()` stays - /// in sync with the uncached reference walk after every step. This is the load-bearing - /// guarantee of the cache-based refactor: any future change that introduces a new - /// mutation site without going through a helper will break this test. + /// A frame's caller is recorded once per caller frame: a second child finds it recorded. + #[test] + fn test_record_caller_records_a_caller_once() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + assert!(t.pop(true).is_some()); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); + assert_eq!(t.net(), WRITE_RECORD); + } + + /// The cached totals match the lanes after every push, record, refund and pop. #[test] fn test_net_usage_cache_matches_uncached() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); - - // Pre-frame intrinsic usage goes to tx_entry. - t.add_tx_persistent(100); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // add_frame_persistent on empty stack must be a no-op and return false. - assert!(!t.add_frame_persistent(50)); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // add_frame_discardable / add_frame_refund are no-ops on empty stack. - t.add_frame_discardable(50); - t.add_frame_refund(50); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 100); - - // Push frame 1 and mix in persistent/discardable/refund. - t.push_frame(()); - assert!(t.add_frame_persistent(20)); - t.add_frame_discardable(30); - t.add_frame_refund(10); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 2 (nested) and mutate. - t.push_frame(()); - assert!(t.add_frame_persistent(7)); - t.add_frame_discardable(15); - t.add_frame_refund(3); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Push frame 3 (deeper) and revert it — discardable & refund must vanish from cache, - // persistent must merge into the parent (frame 2). - t.push_frame(()); - assert!(t.add_frame_persistent(5)); - t.add_frame_discardable(11); - t.add_frame_refund(2); - let before_revert = t.net_usage(); - let popped = t.pop_frame(false).expect("frame 3 popped"); - assert_eq!(popped.discardable_usage, 11); - assert_eq!(popped.refund, 2); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // After revert: cache should drop the child's discardable (11) and refund (2), - // so net_usage changes by -(11) + 2 = -9 vs before. - assert_eq!(t.net_usage(), before_revert - 9); - - // Push frame 3 again and pop it successfully — discardable/refund merge into parent, - // cache is unchanged by the pop itself (totals are invariant under transfer). - t.push_frame(()); - assert!(t.add_frame_persistent(4)); - t.add_frame_discardable(6); - t.add_frame_refund(1); - let before_success = t.net_usage(); - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), before_success); - - // Pop frame 2 with success → merge into frame 1. - t.pop_frame(true); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - - // Pop the last frame (frame 1) with revert → discardable/refund vanish, persistent - // merges into tx_entry. - let before_last_revert = t.net_usage(); - let frame_1 = t.pop_frame(false).expect("frame 1 popped"); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - // The popped frame's discardable/refund leave the cache. - assert_eq!(t.net_usage(), before_last_revert - frame_1.discardable_usage + frame_1.refund); - - // Reset returns the cache to zero in sync with the entries. + let mut t = FrameLimitTracker::default(); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), LimitUsage::ZERO); + + // Outside any frame, usage goes to the transaction and nothing is taken back. + t.record(bytes(100)); + t.refund(bytes(50)); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(100)); + + // Frame 1. + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.record(bytes(30)); + t.refund(bytes(10)); + assert_eq!(t.net(), t.net_uncached()); + + // Frame 2, nested. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(15)); + t.refund(bytes(3)); + assert_eq!(t.net(), t.net_uncached()); + + // Frame 3 fails: its usage and refund leave the totals. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(11)); + t.refund(bytes(2)); + let before_revert = t.net(); + let popped = t.pop(false).expect("frame 3 popped"); + assert_eq!((popped.used, popped.refund), (bytes(11), bytes(2))); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(before_revert.data_size - 9)); + + // Frame 3 again, succeeding: merging moves usage, the totals do not change. + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(6)); + t.refund(bytes(1)); + let before_success = t.net(); + t.pop(true); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), before_success); + + // Frame 2 succeeds into frame 1; frame 1 fails. + t.pop(true); + assert_eq!(t.net(), t.net_uncached()); + let frame_1 = t.pop(false).expect("frame 1 popped"); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), bytes(100), "only the transaction's own usage is left"); + assert_eq!(frame_1.net(), bytes(30 + 15 + 6 - 10 - 3 - 1)); + t.reset(); - assert_eq!(t.net_usage(), t.net_usage_uncached()); - assert_eq!(t.net_usage(), 0); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.depth(), 0); } - /// Verifies that a refund exceeding the cumulative usage clamps `net_usage()` to 0, - /// matching the saturating semantics of the uncached reference. This guards against - /// signed-style accounting bugs where refunds outrun used and an unsigned subtraction - /// would otherwise wrap. + /// A refund larger than the usage clamps the net at zero. #[test] fn test_net_usage_saturates_when_refund_exceeds_used() { - let mut t = FrameLimitTracker::<()>::new(MegaSpecId::EQUIVALENCE, u64::MAX); - t.push_frame(()); - t.add_frame_discardable(10); - t.add_frame_refund(100); - assert_eq!(t.net_usage(), 0); - assert_eq!(t.net_usage(), t.net_usage_uncached()); + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(None, false, u64::MAX)); + t.record(bytes(10)); + t.refund(bytes(100)); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + t.pop(true); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A value transfer's sender record dies with the child that failed, and the caller can be + /// recorded again; a creator's record survives the creation's failure. + #[test] + fn test_failed_child_discards_sender_record_but_keeps_creator_record() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(false); + t.record(WRITE_RECORD); + t.pop(false); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.current().unwrap().account_recorded, "the sender record died with the child"); + + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + t.record(WRITE_RECORD); + t.pop(false); + assert_eq!(t.net(), WRITE_RECORD, "the creator's nonce outlives the creation"); + assert!(t.current().unwrap().account_recorded); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A creation that fails before bumping the nonce takes the creator record back. + #[test] + fn test_drop_caller_record_rearms_the_caller() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(None, true, u64::MAX)); + t.record_caller(true); + t.drop_caller_record(); + t.drop_caller_record(); + assert_eq!(t.net(), LimitUsage::ZERO); + assert!(!t.lanes[0].account_recorded); + t.pop(false); + assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), t.net_uncached()); + } + + /// A child running as its caller's account hands its record flag back on success. + #[test] + fn test_same_account_child_merges_the_recorded_flag() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(Some(ADDR), true, u64::MAX)); + t.pop(true); + assert!(t.current().unwrap().account_recorded); + + let other = address!("0000000000000000000000000000000000005678"); + t.push(Lane::new(Some(other), false, u64::MAX)); + t.push(Lane::new(Some(other), false, u64::MAX)); + t.current_mut().unwrap().account_recorded = true; + t.pop(false); + assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); + + t.push(Lane::new(Some(ADDR), true, u64::MAX)); + assert_eq!(t.depth(), 3); + t.pop(true); + assert!(!t.current().unwrap().account_recorded, "another account's flag is its own"); + t.push(Lane::new(None, true, u64::MAX)); + t.pop(true); + assert!(!t.current().unwrap().account_recorded, "an unknown account is not the caller's"); } } diff --git a/crates/mega-evm/src/limit/kv_update.rs b/crates/mega-evm/src/limit/kv_update.rs deleted file mode 100644 index 6b2615cdb..000000000 --- a/crates/mega-evm/src/limit/kv_update.rs +++ /dev/null @@ -1,298 +0,0 @@ -use alloy_primitives::{Address, U256}; -use revm::{ - context::{transaction::AuthorizationTr, Transaction}, - handler::{EthFrame, FrameResult}, - interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, FrameInput, SStoreResult, - }, -}; - -use super::frame_limit::{CallFrameInfo, FrameLimitTracker, TxRuntimeLimit}; -use crate::{MegaSpecId, MegaTransaction}; - -/// A counter for tracking key-value storage operations during transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware counting. -/// -/// In Rex4+, KV updates are enforced at the per-frame level: each inner call frame receives -/// `remaining * 98 / 100` of the parent's remaining KV update budget. -/// When a frame exceeds its budget, it reverts (not halts) and its discardable KV updates are -/// dropped, protecting the parent's budget. -/// In pre-Rex4, KV updates are enforced at the TX level only. -/// Units are 1 per KV operation (not bytes). -/// -/// ## Tracked Operations -/// -/// **Non-discardable (permanent):** -/// - Transaction caller account update: 1 KV update -/// - EIP-7702 authority account updates: 1 KV update each -/// -/// **Discardable (reverted on frame revert):** -/// - Storage writes: 1 KV update (only when original ≠ new value, refunded when reset to original) -/// - Account updates from CREATE: 1 KV update for created account -/// - Account updates from CALL with transfer: 2 KV updates (caller + callee) -#[derive(Debug, Clone)] -pub(crate) struct KVUpdateTracker { - rex4_enabled: bool, - rex6_enabled: bool, - frame_tracker: FrameLimitTracker, -} - -impl KVUpdateTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { - rex4_enabled: spec.is_enabled(MegaSpecId::REX4), - rex6_enabled: spec.is_enabled(MegaSpecId::REX6), - frame_tracker: FrameLimitTracker::new(spec, tx_limit), - } - } - - /// Records a discardable KV update in the current frame. - fn record_discardable(&mut self, n: u64) { - self.frame_tracker.add_frame_discardable(n); - } - - /// Records discardable usage into the PARENT frame (one below the top). Used for a - /// child-CREATE's creator-side account-info write, whose on-chain effect (the creator - /// nonce bump) is undone only by the parent's revert, not the child's. - fn record_parent_discardable(&mut self, n: u64) { - self.frame_tracker.add_parent_discardable(n); - } - - /// Records a KV update refund in the current frame. - fn record_refund(&mut self, n: u64) { - self.frame_tracker.add_frame_refund(n); - } - - /// Records a single account update as discardable KV update in the current frame. - /// - /// Used by SELFDESTRUCT beneficiary metering (REX5+) to charge a KV update for - /// creating a new beneficiary account. - pub(crate) fn record_account_update(&mut self) { - self.record_discardable(1); - } - - /// Records a single account update as TX-level persistent (non-discardable) KV usage. - /// - /// Used by the REX6 EIP-7702 authorization scan, which runs in `validate` before any frame - /// exists, so the charge cannot go through the frame-scoped `record_account_update`. - pub(crate) fn record_persistent_account_update(&mut self) { - self.frame_tracker.add_tx_persistent(1); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox KV update consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining KV update budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.rex4_enabled { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for KVUpdateTracker { - /// Returns the current effective KV update limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current total KV update count across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the KV update limit has been exceeded. - /// - /// In Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic overflow when no frame exists yet - /// (intrinsic usage is recorded in `tx_entry` before the first frame is pushed). - /// In pre-Rex4, checks total KV updates across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.rex4_enabled { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::KVUpdate); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: defense-in-depth safety net. - // In Rex4+ during execution, per-frame budgets are derived from remaining TX - // budget, so this should only exceed when no frame exists (intrinsic overflow). - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - debug_assert!( - !self.rex4_enabled || !self.frame_tracker.has_active_frame(), - "KVUpdate TX-level exceeded with active frame — budget invariant violated" - ); - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::KVUpdate, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// Records the KV updates at the start of a transaction. - /// - /// This includes: - /// - EIP-7702 authority account updates (1 each) - /// - Caller account update (1) - /// - /// All recorded as pre-frame (non-discardable) since no frame exists yet. - fn before_tx_start(&mut self, tx: &MegaTransaction) { - // EIP-7702 authority account updates (non-discardable). - // - // Pre-REX6: charged here for every recoverable authority, including ones that fail the - // application gates. REX6+ moves this into the journal-aware authorization scan in - // `validate` so only *applied* authorities are charged; skip here. - if !self.rex6_enabled { - for authorization in tx.authorization_list() { - if authorization.authority().is_some() { - self.frame_tracker.add_tx_persistent(1); - } - } - } - - // Caller account update (non-discardable) - self.frame_tracker.add_tx_persistent(1); - } - - #[inline] - fn push_empty_frame(&mut self) { - self.frame_tracker.push_dummy_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Records KV updates for account info changes: - /// - **Call with value transfer**: Parent account update (1, if not yet marked) + target - /// account update (1). - /// - **Create**: Parent account update (1, if not yet marked). Created address is set later in - /// `after_frame_init_on_frame`. - /// - **Call without transfer**: No KV updates. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - _journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - let has_transfer = call_inputs.transfers_value(); - let parent_needs_update = - self.frame_tracker.push_call_frame(call_inputs.target_address, has_transfer); - if has_transfer { - if parent_needs_update { - // Parent's account info update goes to child's discardable. - self.record_discardable(1); - } - // A value transfer to the caller itself touches a single account, already - // accounted by the caller-side write above (or, at the top level, by the - // transaction-start caller record). Recording the target side again would - // double-count that one account, so skip it under REX6. - if !(self.rex6_enabled && call_inputs.target_address == call_inputs.caller) { - // Record target account info update in child's discardable. - self.record_discardable(1); - } - } - } - FrameInput::Create(_) => { - let parent_needs_update = self.frame_tracker.push_create_frame(); - if parent_needs_update { - if self.rex6_enabled { - // The creator's nonce bump survives the child's revert (revm bumps it - // before the create checkpoint), so charge it to the parent frame — - // see `FrameLimitTracker::add_parent_discardable`. - self.record_parent_discardable(1); - } else { - // Pre-REX6: the creator nonce-bump charge is bundled into the child frame's - // discardable lane (frozen behavior). - self.record_discardable(1); - } - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a new execution frame is successfully initialized. - /// - /// For CREATE frames, records the created address and its account info update (1 KV). - fn after_frame_init_on_frame(&mut self, frame: &EthFrame) { - if frame.data.is_create() { - let created_address = - frame.data.created_address().expect("created address is none for create frame"); - self.frame_tracker.set_created_address(created_address); - // Record account info update for created address - self.record_discardable(1); - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Rex5+: if the reverting child had set the parent's account-update flag, the flag - /// is reset so the next successful call from the same parent still charges the parent - /// account (avoiding undercounting after a revert-then-retry pattern). The unwind is - /// owned by `FrameLimitTracker::pop_frame_unwind_parent`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - let is_success = result.instruction_result().is_ok(); - self.frame_tracker.pop_frame_unwind_parent(is_success); - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// | Original == Present | Original == New | Effect | Reason | - /// |---------------------|-----------------|------------|-------------------------| - /// | yes | yes | — | No change | - /// | yes | no | +1 (disc.) | First write to slot | - /// | no | yes | +1 (refund)| Reset to original value | - /// | no | no | — | Rewrite, no new KV | - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - if store_result.is_original_eq_present() { - if !store_result.is_original_eq_new() { - self.record_discardable(1); - } - } else if store_result.is_original_eq_new() { - self.record_refund(1); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `record_account_update` must charge exactly one KV update against the current frame - /// (used by REX5+ SELFDESTRUCT-beneficiary metering); it must not be a no-op. - #[test] - fn test_record_account_update_charges_one_kv() { - let mut tracker = KVUpdateTracker::new(MegaSpecId::MINI_REX, u64::MAX); - tracker.push_empty_frame(); - assert_eq!(tracker.tx_usage(), 0); - tracker.record_account_update(); - assert_eq!(tracker.tx_usage(), 1, "record_account_update must add exactly 1 KV update"); - } -} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 2bcec8b8b..923572c74 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,1153 +1,342 @@ -use core::ops::Range; +//! The per-transaction state of the common execution layer. -use alloy_primitives::{Address, Bytes, U256}; -use op_revm::OpHaltReason; +use alloy_primitives::Address; use revm::{ - context::result::{HaltReason, OutOfGasError}, - handler::{EthFrame, FrameResult, ItemOrResult}, - interpreter::{ - gas::calculate_initial_tx_gas_for_tx, interpreter::EthInterpreter, - interpreter_action::FrameInit, CallOutcome, CreateOutcome, FrameInput, Gas, - InstructionResult, InterpreterAction, InterpreterResult, SStoreResult, - }, + handler::FrameResult, + interpreter::{FrameInput, InstructionResult}, }; use super::{ - compute_gas, data_size, frame_limit::TxRuntimeLimit, kv_update, state_growth, - storage_call_stipend, + frame_limit::{FrameLimitTracker, Lane}, + record::{RecordEffect, StagedRecord}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, }; -use crate::{ - EvmTxRuntimeLimits, JournalInspectTr, MegaHaltReason, MegaSpecId, MegaTransaction, - VolatileDataAccess, -}; - -use super::LimitCheck; -/// Additional limits for the `MegaETH` EVM beyond standard EVM limits. -/// -/// This struct coordinates four independent resource limits: compute gas, data size, -/// key-value updates, and state growth. Each limit is tracked separately and enforced during -/// transaction execution. -/// -/// ## TX-Level Halt Enforcement +/// What the common execution layer tracks for the running transaction: the per-frame lanes of +/// data-size bytes and write records, the record the Host staged for the running opcode, and the +/// latch of a transaction a limit stopped. /// -/// TX-level exceed is represented as `InstructionResult::OutOfGas`. -/// Remaining gas is rescued and later refunded to the sender. -/// - **Compute gas**: TX-level check is always active (`min(tx_limit, detained_limit)`). -/// - **Data size / KV update**: TX-level fallthrough is active in all specs. In Rex4+ it catches -/// intrinsic overflow (when the frame stack is empty) and serves as a safety net behind the -/// per-frame check. -/// - **State growth**: TX-level fallthrough catches Rex5 pre-frame authority usage and serves as a -/// safety net behind the per-frame check. +/// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and +/// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) +/// and the frame lifecycle (lanes, the latch). /// -/// ## Per-Frame Enforcement (Rex4+) +/// # The abort protocol /// -/// In Rex4+, all four limits use per-frame budgets. -/// Each inner call frame receives `remaining * 98 / 100` of the parent's remaining budget. -/// When a frame exceeds its per-frame budget, it **reverts** (not halts) and gas returns to -/// the parent frame, which can continue executing: -/// - **State growth**: Reverted child's growth is discarded (`discardable_usage` dropped). -/// - **Data size**: Reverted child's discardable data is dropped, protecting parent's budget. -/// - **KV updates**: Reverted child's discardable KV ops are dropped, protecting parent's budget. -/// - **Compute gas**: Reverted child's gas still counts toward parent (gas is always persistent). -/// Per-frame limits act as "early termination guardrails" only, not budget protection. Compute -/// gas still retains TX-level detained checking in all specs. -/// -/// # Tracking Details -/// -/// - **Compute Gas**: Tracks gas consumption from EVM instructions during execution, monitoring the -/// computational cost separate from the standard gas limit -/// - **Data Size**: Tracks transaction data (110 bytes base + calldata + access lists + -/// authorizations), caller/authority account updates (40 bytes each), log data, storage writes -/// (40 bytes when original ≠ new), account updates from calls/creates (40 bytes), and contract -/// code size -/// - **KV Updates**: Tracks transaction caller + authority updates, storage writes (when original ≠ -/// new), and account updates from value transfers and creates -/// - **State Growth**: Tracks net new accounts + net new storage slots -/// -/// Additionally, this struct manages the `STORAGE_CALL_STIPEND` (Rex4+): extra gas granted to -/// value-transferring `CALL`/`CALLCODE` for storage operations. REX5+ tracks the stipend as a -/// separated internal allowance drained at the `storage_gas_ext` charging sites; REX4 retains -/// the legacy `gas.limit()` inflation with a per-frame compute gas cap and burn-on-return. -#[derive(Debug)] +/// A transaction-level limit stops the transaction with a revert, not a halt. The frame that +/// crosses the limit reverts with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output +/// and the transaction is latched ([`latch`](Self::latch)). From then on no frame runs another +/// instruction: a caller that gets the reverted result back returns the same revert instead of +/// resuming, a frame about to start is answered with it, and every result returned above is +/// rewritten to it. The outermost frame settles like any EIP-8037 revert: its unspent regular gas +/// and the reservoir go back to the sender, who pays only for what ran. A frame budget crossed +/// reverts that frame alone, without a latch, and its caller resumes. Exceptional halts (a real +/// out-of-gas, an invalid opcode) are not limit stops and still burn the frame's gas. +#[derive(Clone, Debug, Default)] pub struct AdditionalLimit { - /// Carries the tx's current limit-check verdict. - /// - /// Once stamped to a non-[`LimitCheck::WithinLimit`] value, the sub-tracker pass in - /// [`check_limit`](Self::check_limit) is bypassed and individual tracker usage values may - /// no longer be reliable (subsequent frames revert and their discardable usage is dropped). - /// Legitimate writers: [`check_limit`](Self::check_limit) (latches `ExceedsLimit`), - /// [`mark_exempt`](Self::mark_exempt) (stamps `Exempt`), - /// [`reset`](Self::reset) (clears to `WithinLimit`), and - /// [`before_frame_return_result`](Self::before_frame_return_result) (absorbs a frame-local - /// `ExceedsLimit` back to `WithinLimit`). Everything else reads via - /// [`check_limit`](Self::check_limit) or - /// [`exceeded_limit`](LimitCheck::exceeded_limit) / [`is_exempt`](LimitCheck::is_exempt). - pub(crate) has_exceeded_limit: LimitCheck, - - /// The total remaining gas after the limit exceeds. - pub rescued_gas: u64, - - /// The original limits set by the EVM. Some of the limits may be overridden (such as the - /// compute gas limit) during transaction execution. We keep the original limits to be able to - /// reset the limits before each transaction. - pub limits: EvmTxRuntimeLimits, - - /// A tracker for the state growth during transaction execution. - pub(crate) state_growth: state_growth::StateGrowthTracker, - - /// A tracker for the total data size (in bytes) generated from a transaction execution. - pub(crate) data_size: data_size::DataSizeTracker, - - /// A tracker for the total KV updates during transaction execution. - pub(crate) kv_update: kv_update::KVUpdateTracker, - - /// A tracker for the total compute gas consumed during transaction execution. - pub(crate) compute_gas: compute_gas::ComputeGasTracker, - - /// A tracker for the `STORAGE_CALL_STIPEND` granted to value-transferring calls (REX4+). - pub(crate) storage_call_stipend: storage_call_stipend::StorageCallStipendTracker, -} - -/// The usage of the additional limits. -#[derive(Clone, Copy, Debug, Default)] -pub struct LimitUsage { - /// The data size usage in bytes. - pub data_size: u64, - /// The number of KV updates. - pub kv_updates: u64, - /// The compute gas usage. - pub compute_gas: u64, - /// The state growth. - pub state_growth: u64, + pub(crate) tracker: FrameLimitTracker, + staged: Option, + limits: EvmTxRuntimeLimits, + /// The transaction-level stop, once a limit latched one. + latched: Option, + /// Whether the transaction's call target is an applied EIP-7702 authority, whose account + /// write the transaction's lane already counts. + target_is_authority: bool, + /// The transaction's sender, whose account write is part of the transaction body: a frame + /// running as the sender never records it. + sender: Address, + /// Whether the transaction's first frame reached frame init. When it did not, the runtime + /// phase before it ran out of gas and took back everything counted before it. + frame_began: bool, + /// The history gas the settled transaction spent. + history_gas_spent: u64, } impl AdditionalLimit { - /// Creates a new `AdditionalLimit` instance from the given `MegaSpecId`. - pub fn new(spec: MegaSpecId, limits: EvmTxRuntimeLimits) -> Self { - Self { - has_exceeded_limit: LimitCheck::WithinLimit, - rescued_gas: 0, - limits, - state_growth: state_growth::StateGrowthTracker::new(spec, limits.tx_state_growth_limit), - data_size: data_size::DataSizeTracker::new(spec, limits.tx_data_size_limit), - kv_update: kv_update::KVUpdateTracker::new(spec, limits.tx_kv_updates_limit), - compute_gas: compute_gas::ComputeGasTracker::new(spec, limits.tx_compute_gas_limit), - storage_call_stipend: storage_call_stipend::StorageCallStipendTracker::new(spec), - } + /// A layer enforcing `limits`. + pub fn new(limits: EvmTxRuntimeLimits) -> Self { + Self { limits, ..Default::default() } } -} - -impl AdditionalLimit { - /// The [`InstructionResult`] to indicate that the limit is exceeded (TX-level). - /// - /// This constant is used for TX-level additional-limit exceeds. - /// For TX-level exceeds, this is `OutOfGas` (halt path, with rescued gas refund). - /// For frame-local exceeds (Rex4+), use - /// `exceeding_instruction_result()` which returns `Revert` instead. - pub const EXCEEDING_LIMIT_INSTRUCTION_RESULT: InstructionResult = InstructionResult::OutOfGas; - /// Returns the appropriate [`InstructionResult`] for the current limit exceed. - /// - /// - **Frame-local (Rex4+)**: `Revert` — gas returns to the parent frame naturally. - /// - **TX-level**: `OutOfGas` — halt, gas consumed (rescued via `rescued_gas`). - #[inline] - pub(crate) fn exceeding_instruction_result(&self) -> InstructionResult { - if self.has_exceeded_limit.is_frame_local() { - InstructionResult::Revert - } else { - Self::EXCEEDING_LIMIT_INSTRUCTION_RESULT - } + /// The limits enforced. + pub const fn limits(&self) -> &EvmTxRuntimeLimits { + &self.limits } - /// Resets the internal state for a new transaction or block. - /// - /// This method clears both the data size tracker and KV update counter, - /// preparing the limit system for a new execution context. - /// - /// Each tracker internally handles spec-gated behavior (e.g., `ComputeGasTracker` - /// resets the detained limit only for Rex1+). - pub fn reset(&mut self) { - self.has_exceeded_limit = LimitCheck::WithinLimit; - self.rescued_gas = 0; - self.compute_gas.reset(); - self.state_growth.reset(); - self.data_size.reset(); - self.kv_update.reset(); - self.storage_call_stipend.reset(); + /// Replaces the limits enforced from the next transaction on. + pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.limits = limits; } - /// Test-only setter for [`has_exceeded_limit`](Self::has_exceeded_limit). Bypasses every - /// invariant maintained by the normal write paths (sticky `Exempt`, sub-tracker latching, - /// frame-local absorb). Integration tests use this to construct specific pre-latched states - /// — production code must not. - #[cfg(any(test, feature = "test-utils"))] - #[doc(hidden)] - pub fn set_has_exceeded_limit_for_test(&mut self, state: LimitCheck) { - self.has_exceeded_limit = state; + /// Clears the state for a new transaction, keeping allocations and the limits. + pub(crate) fn reset(&mut self) { + self.tracker.reset(); + self.staged = None; + self.latched = None; + self.target_is_authority = false; + self.sender = Address::ZERO; + self.frame_began = false; + self.history_gas_spent = 0; } - /// Marks the current transaction as exempt from `MegaETH` per-tx resource metering by stamping - /// `has_exceeded_limit = LimitCheck::Exempt`. REX6+ uses this for system-originated - /// transactions (see [`crate::is_system_originated`]); cleared by [`reset`](Self::reset). - /// - /// `Exempt` is sticky: [`check_limit`](Self::check_limit) short-circuits on it, so no later - /// sub-tracker overflow can latch over it, and every direct read of `has_exceeded_limit` - /// observes the exemption as "not exceeded" via - /// [`exceeded_limit`](LimitCheck::exceeded_limit). The host storage-gas charging sites - /// additionally consult [`is_exempt`](LimitCheck::is_exempt) to charge the SALT-unscaled - /// cost, since SALT-scaled storage gas is charged to interpreter gas and is not tracked here. - /// - /// `current_call_remaining_*` queries (compute gas, data size, KV updates, state growth) still - /// report `limit − usage` against the configured limit while exempt, but the limit is not - /// enforced — so a caller that uses these values to make admission or sizing decisions for an - /// exempt tx will get a number that is not load-bearing. Today's consumers - /// (`MegaLimitControl.remainingComputeGas`, the `KeylessDeploy` sandbox sub-limits, oracle - /// hint precompile) are unreachable from a system-originated tx; revisit this if a future - /// system contract joins the mega whitelist and would consult them. - #[inline] - pub(crate) fn mark_exempt(&mut self) { - self.has_exceeded_limit = LimitCheck::Exempt; - } + /* The latch */ - /// Gets the usage of the additional limits. - #[inline] - pub fn get_usage(&self) -> LimitUsage { - LimitUsage { - data_size: self.data_size.tx_usage(), - kv_updates: self.kv_update.tx_usage(), - compute_gas: self.compute_gas.tx_usage(), - state_growth: self.state_growth.tx_usage(), - } + /// The stop a transaction-level limit latched, if any. + pub const fn latched(&self) -> Option<&LimitCheck> { + self.latched.as_ref() } - /// Checks whether the Rex5 sandbox's TX-level pre-frame intrinsic usage fits inside - /// `limits`. - /// - /// Runs a trial `AdditionalLimit` through the same entry points production uses — - /// `before_tx_start` (data size / KV updates) and `record_compute_gas(initial_gas)` - /// (intrinsic compute gas, via `MegaHandler::validate`) — then returns its `check_limit()` - /// result. Reusing production logic keeps tracker changes and dimension-priority ordering - /// in sync automatically. Consumed by the `KeylessDeploy` preflight. - /// - /// Any future TX-level persistent usage recorded before the first frame through a different - /// path MUST be added here too when it can be computed from the transaction alone. DB-dependent - /// contributions, such as REX5 EIP-7702 net-new authority state growth, are recorded during - /// pre-execution once the journal is available. Missing additions do not fail open — the - /// `KeylessDeploy` post-merge overflow check still catches residual overflow — but the failure - /// mode degrades from the preflight fast-path (pre-sandbox revert with `ParentBudgetExceeded`) - /// to an outer `OutOfGas` halt after sandbox setup has already run. - pub(crate) fn intrinsic_check_for_tx( - spec: MegaSpecId, - tx: &MegaTransaction, - limits: EvmTxRuntimeLimits, - ) -> LimitCheck { - debug_assert!(spec.is_enabled(MegaSpecId::REX5)); - let mut trial = Self::new(spec, limits); - trial.before_tx_start(tx); - - let initial_and_floor_gas = calculate_initial_tx_gas_for_tx(tx, spec.into_eth_spec()); - trial.record_compute_gas(initial_and_floor_gas.initial_gas); - - trial.check_limit() + /// Latches the transaction: `kind`'s transaction-level `limit` was crossed at `used`. The + /// running frame must stop with [`LimitCheck::revert_data`]; the frame lifecycle stops every + /// frame above it. A later latch does not replace the first. + pub fn latch(&mut self, kind: LimitKind, limit: u64, used: u64) -> LimitCheck { + *self.latched.get_or_insert(LimitCheck::ExceedsLimit { + kind, + limit, + used, + frame_local: false, + }) } - /// Pushes an empty frame to all trackers so `before_frame_return_result` can pop - /// them to keep stacks aligned with the EVM's call stack. - /// - /// Used when `frame_init` returns an early `Result` (e.g., inspector interception, - /// access control interception) without going through `after_frame_init`. - #[inline] - pub(crate) fn push_empty_frame(&mut self) { - self.state_growth.push_empty_frame(); - self.data_size.push_empty_frame(); - self.kv_update.push_empty_frame(); - self.compute_gas.push_empty_frame(); - self.storage_call_stipend.push_empty_frame(); + /// Checks the limits after the running frame counted something: the transaction's data size + /// against its limit (latching on a crossing), then the running frame's against its budget. + fn check(&mut self) -> LimitCheck { + let used = self.tracker.net().data_size; + if used > self.limits.tx_data_size_limit { + return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); + } + if let Some(lane) = self.tracker.current() { + let used = lane.net().data_size; + if used > lane.budget { + return LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: lane.budget, + used, + frame_local: true, + }; + } + } + LimitCheck::WithinLimit } - /// Returns the current effective compute gas limit (may be detained/lowered by volatile - /// data access). - #[inline] - pub fn compute_gas_limit(&self) -> u64 { - self.compute_gas.tx_limit() + /// Rewrites `result` to the latched stop, when the transaction is latched: a success or a + /// revert becomes the latched revert. A halt stays what it is. + fn apply_latch(&self, result: &mut FrameResult) { + let Some(latched) = &self.latched else { return }; + let interpreter_result = result.interpreter_result_mut(); + if interpreter_result.result.is_ok_or_revert() { + interpreter_result.result = InstructionResult::Revert; + interpreter_result.output = latched.revert_data(); + } } - /// Returns the remaining compute gas of the current call. - /// - /// In Rex4+, returns the minimum of the caller's per-frame remaining compute gas - /// and the TX-level detained remaining, reflecting the actual gas available before - /// execution halts (whether due to frame budget or gas detention). - /// If no frame exists yet (direct TX → system contract), returns the TX-level - /// remaining which accounts for intrinsic compute gas. - /// In pre-Rex4, falls back to TX-level remaining compute gas. - #[inline] - pub fn current_call_remaining_compute_gas(&self) -> u64 { - self.compute_gas.current_call_remaining() + /// What the transaction keeps so far: its data-size bytes and write records, with every + /// running frame counted as if it succeeds. + pub fn usage(&self) -> LimitUsage { + self.tracker.net() } - /// Returns the remaining data size budget for the current call frame. - #[inline] - pub fn current_call_remaining_data_size(&self) -> u64 { - self.data_size.current_call_remaining() + /// The history gas the last settled transaction spent. + pub const fn history_gas_spent(&self) -> u64 { + self.history_gas_spent } - /// Returns the remaining KV update budget for the current call frame. - #[inline] - pub fn current_call_remaining_kv_updates(&self) -> u64 { - self.kv_update.current_call_remaining() + /// Records the history gas the settled transaction spent. + pub(crate) const fn set_history_gas_spent(&mut self, history_gas_spent: u64) { + self.history_gas_spent = history_gas_spent; } - /// Returns the remaining state growth budget for the current call frame. - #[inline] - pub fn current_call_remaining_state_growth(&self) -> u64 { - self.state_growth.current_call_remaining() - } + /* Observe, stage, commit */ - /// Returns the detained compute gas limit (independent of the natural TX limit). - /// This is the limit set by volatile data access gas detention. - #[inline] - pub fn detained_compute_gas_limit(&self) -> u64 { - self.compute_gas.detained_limit() + /// The record the Host staged for the running opcode, if any. + pub const fn staged_record(&self) -> Option<&StagedRecord> { + self.staged.as_ref() } - /// Returns the halt reason when gas detention is the binding compute gas constraint. - /// Otherwise (detention was not more restrictive than the base TX limit), returns `None`. + /// Stages the facts the Host observed. Called by the Host, which records nothing itself. #[inline] - pub(crate) fn detained_compute_gas_halt_reason( - &self, - access_type: VolatileDataAccess, - ) -> Option { - self.compute_gas.is_detained_exceed().then(|| MegaHaltReason::VolatileDataAccessOutOfGas { - access_type, - limit: self.compute_gas.detained_limit(), - actual: self.compute_gas.tx_usage(), - }) + pub(crate) fn stage_record(&mut self, record: StagedRecord) { + self.staged = Some(record); } - /// Sets the compute gas limit to a new value. - /// This is used to dynamically lower the compute gas limit when volatile data is accessed. - /// The new limit must be lower than the current limit. + /// Commits the staged record to the running frame's lane. Called by an opcode's wrapper once + /// the opcode completed; a crossed limit in the verdict stops the opcode's frame. #[inline] - pub fn set_compute_gas_limit(&mut self, new_limit: u64) { - self.compute_gas.set_detained_limit(new_limit); - } - - /// Checks if any of the configured limits have been exceeded. - /// - /// This method examines data size, KV update, compute gas, and state growth in fixed order - /// and returns the first exceeded limit. - /// - /// # Returns - /// - /// Returns a [`LimitCheck`] indicating whether limits have been exceeded - /// and which specific limit was exceeded if any. - #[inline] - pub fn check_limit(&mut self) -> LimitCheck { - // Sticky short-circuit: `Exempt` (REX6+ system-originated tx; usage is still accumulated - // by individual trackers for `get_usage` and block-level accounting, only the halt - // decision is suppressed) and already-latched `ExceedsLimit` both bypass the sub-tracker - // pass. For `Exempt` this also neutralizes gas detention (which runs through - // `compute_gas.check_limit()` below), so protocol-mandated execution can never halt on - // metering — e.g. when SALT buckets grow. The standard EVM `gas_limit` remains the - // runaway guard. - if !self.has_exceeded_limit.within_limit() { - return self.has_exceeded_limit; - } - - let data_size_check = self.data_size.check_limit(); - if data_size_check.exceeded_limit() { - self.has_exceeded_limit = data_size_check; - return self.has_exceeded_limit; - } - - let kv_update_check = self.kv_update.check_limit(); - if kv_update_check.exceeded_limit() { - self.has_exceeded_limit = kv_update_check; - return self.has_exceeded_limit; - } - - // Per-frame compute gas check (Rex4+) and TX-level detained check (all specs). - let compute_gas_check = self.compute_gas.check_limit(); - if compute_gas_check.exceeded_limit() { - self.has_exceeded_limit = compute_gas_check; - return self.has_exceeded_limit; - } - - // State growth check: - // - Rex4+: frame-local budget check. - // - pre-Rex4: TX-level check inside `state_growth.check_limit()`. - let state_growth_check = self.state_growth.check_limit(); - if state_growth_check.exceeded_limit() { - self.has_exceeded_limit = state_growth_check; - return self.has_exceeded_limit; + pub(crate) fn commit_staged_record(&mut self) -> LimitCheck { + let Some(record) = self.staged.take() else { return LimitCheck::WithinLimit }; + match record.effect(self.sender) { + RecordEffect::None => LimitCheck::WithinLimit, + RecordEffect::Record(usage) => { + self.tracker.record(usage); + self.check() + } + RecordEffect::Refund(usage) => { + self.tracker.refund(usage); + LimitCheck::WithinLimit + } } - - self.has_exceeded_limit - } - - /// `true` when a per-tx resource limit has already been latched as exceeded — the exact - /// condition [`frame_result_if_exceeding_limit`](Self::frame_result_if_exceeding_limit) halts - /// the transaction on. `WithinLimit` and `Exempt` both return `false`. Reads the latched - /// aggregate; call [`check_limit`](Self::check_limit) first if a fresh evaluation is needed. - #[inline] - pub(crate) fn limit_exceeded(&self) -> bool { - self.has_exceeded_limit.exceeded_limit() - } - - /// Checks if the halt reason indicates that the limit has been exceeded. - /// - /// # Arguments - /// - /// * `halt_reason` - The halt reason to check - /// - /// # Returns - /// - /// Returns `true` if the halt reason indicates that the limit has been exceeded, `false` - /// otherwise. - pub fn is_exceeding_limit_halt(&mut self, halt_reason: &OpHaltReason) -> bool { - matches!(halt_reason, &OpHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic))) && - self.check_limit().exceeded_limit() } -} -/* Hooks for transaction execution lifecycle. */ -impl AdditionalLimit { - /// Records the compute gas used and returns `false` if the limit has been exceeded. - /// - /// This runs on every metered opcode, so it is the hottest hook in the whole tracker. - /// `#[inline]` lets the record + within-limit check fold directly into the per-opcode - /// wrapper, removing a call across the `RefMut` boundary. + /// Discards the staged record. Called by an opcode's wrapper when the opcode failed, which + /// takes the observed write back with it. #[inline] - pub(crate) fn record_compute_gas(&mut self, compute_gas_used: u64) -> bool { - // Record unconditionally, even when another dimension has already latched an exceed: - // the compute work was performed, and the recorded total feeds the transaction outcome - // and block-level compute accounting. Skipping the record would under-report compute - // usage for transactions halted on a non-compute dimension (e.g. intrinsic data size - // latched in `before_tx_start` before `validate` records the initial gas). - self.compute_gas.record_gas_used(compute_gas_used); - // Sticky short-circuit, mirroring `check_limit`: an already-latched `ExceedsLimit` is - // surfaced immediately, and `Exempt` (REX6+ system-originated tx) suppresses the halt - // decision — including the compute-gas / detained check below — while the recording - // above still feeds `get_usage` and block-level accounting. - if !self.has_exceeded_limit.within_limit() { - return !self.has_exceeded_limit.exceeded_limit(); - } - // Debug-only guard for the latch protocol: the compute-only fast path below is sound - // only if every non-compute mutation site already latched its own exceed. If a - // non-compute dimension is over limit but not yet latched, some mutation site is missing - // its `check_limit()` — catch it here in tests, not in production. The sub-tracker - // `check_limit()` calls are non-mutating, so this compiles out of release builds. (The - // one pre-inner recorder, SELFDESTRUCT, routes through `record_compute_gas_all_dims`, not - // this method, so it never trips this.) - debug_assert!( - !self.data_size.check_limit().exceeded_limit() && - !self.kv_update.check_limit().exceeded_limit() && - !self.state_growth.check_limit().exceeded_limit(), - "non-compute limit exceeded without latching: a mutation site is missing check_limit()", - ); - // Recording compute gas can only change the compute-gas dimension, so check just that one - // (`compute_gas.check_limit()` covers both the Rex4+ per-frame budget and the TX-level - // detained limit) instead of fanning out to all four sub-trackers. The other three - // dimensions only change at their own mutation sites (`on_sstore`, `on_log`, - // `record_oracle_hint_bytes`, the frame-lifecycle hooks), each of which runs - // `check_limit()` itself and latches any exceed into `has_exceeded_limit` — which the - // short-circuit above then surfaces here. The one exception is SELFDESTRUCT's pre-inner - // `on_selfdestruct_new_account` / `on_selfdestruct_existing_account`, which deliberately - // do not latch; their dimensions latch in the trailing `record_compute_gas_all_dims`. - let check = self.compute_gas.check_limit(); - if check.exceeded_limit() { - self.has_exceeded_limit = check; - return false; - } - true + pub(crate) fn discard_staged_record(&mut self) { + self.staged = None; } - /// Records the compute gas used and checks ALL four limit dimensions (the - /// pre-optimization fan-out), returning `false` if any has been exceeded. - /// - /// Retained for SELFDESTRUCT: its REX5 storage wrapper records beneficiary - /// data/KV/state usage *before* the inner instruction runs, without latching - /// (the inner instruction may still fail, in which case the frame pops that - /// discardable usage). The fan-out here latches those dimensions only after the - /// inner instruction has succeeded, with `check_limit`'s dimension priority. - /// Hot-path opcodes use [`Self::record_compute_gas`] instead. + /// Discards a record staged outside an opcode's wrapper. Called by each wrapper on entry, so + /// a record nobody committed cannot be committed for the wrong opcode. #[inline] - pub(crate) fn record_compute_gas_all_dims(&mut self, compute_gas_used: u64) -> bool { - self.compute_gas.record_gas_used(compute_gas_used); - !self.check_limit().exceeded_limit() - } - - /// Records the current frame's remaining gas on a TX-level limit exceed so it can be - /// refunded to the sender. The storage-stipend tracker decides how `gas.remaining()` - /// maps to the refundable balance — see - /// `StorageCallStipendTracker::effective_remaining_for_rescue`. - pub(crate) fn rescue_gas(&mut self, gas: &Gas) { - self.rescued_gas += self.storage_call_stipend.effective_remaining_for_rescue(gas); - } - - /// Drains up to `amount` from the current frame's storage stipend allowance and - /// returns the portion drained. Caller charges the residual via the original site's - /// gas-charging macro. Returns 0 pre-REX5 (the legacy path covers storage via - /// `gas.limit()` inflation). - pub(crate) fn try_consume_storage_stipend(&mut self, amount: u64) -> u64 { - self.storage_call_stipend.try_consume(amount) - } - - /// Rescue remaining gas from a frame result if a TX-level additional limit has been - /// exceeded. - /// - /// This must be called before any inspector callback (`frame_end`) that might modify the - /// gas via `spend_all()`, so the correct `gas.remaining()` value is captured. - /// The rescued gas is later refunded to the transaction sender in `last_frame_result`. - pub(crate) fn try_rescue_gas(&mut self, gas: &Gas) { - let limit_check = self.check_limit(); - if limit_check.exceeded_limit() && !limit_check.is_frame_local() { - self.rescue_gas(gas); - } - } - - /// Hook called when a new transaction starts. - /// - /// Records transaction-only intrinsic resource usage that can be computed from the - /// transaction itself (calldata size, access lists, EIP-7702 authority account update - /// footprint, caller account update, etc.) and checks TX-level limits. - /// - /// DB-dependent pre-frame usage is recorded later once the journal is available. - /// In particular, REX5 EIP-7702 net-new authority state growth is accounted during - /// pre-execution rather than here because `before_tx_start()` cannot tell whether an - /// authority account already exists. - /// - /// If the recorded usage already exceeds a configured limit, sets `has_exceeded_limit` - /// so that the subsequent `frame_result_if_exceeding_limit()` or `before_frame_init()` - /// call produces a normal execution failure (Halt), keeping the failure on the standard - /// additional-limit path. - /// - /// Intrinsic overflow detection works through each tracker's own `check_limit()`, which - /// includes a TX-level fallthrough that catches `tx_usage > tx_limit` even when the frame - /// stack is empty (before the first frame is pushed). - pub(crate) fn before_tx_start(&mut self, tx: &MegaTransaction) { - self.state_growth.before_tx_start(tx); - self.data_size.before_tx_start(tx); - self.kv_update.before_tx_start(tx); - self.check_limit(); - } - - /// Records REX5 EIP-7702 authority accounts that are net-new state entries — the state-growth - /// dimension only. Data size and KV updates for REX5 are charged upfront in `before_tx_start` - /// for every authorization with a recoverable authority, independent of application. - /// - /// Runs in pre-execution after the authorization scan identifies net-new authorities and - /// before revm writes the delegation bytecode; the net-new check needs DB / journal state, - /// so this cannot live in `before_tx_start`. - /// - /// REX6+ replaces this with the per-applied-authority hook - /// [`AdditionalLimit::on_rex6_eip7702_authority_applied`], which records all three resource - /// dimensions in a single call. - /// - /// Latches any TX-level overflow into `has_exceeded_limit` via `check_limit`; the next frame - /// boundary surfaces it as the normal execution failure. - pub(crate) fn on_rex5_eip7702_authority_creations(&mut self, amount: u64) { - self.state_growth.record_authority_creations(amount); - self.check_limit(); + pub(crate) fn discard_stale_record(&mut self) { + self.staged = None; } - /// Records the resource footprint of a single *applied* EIP-7702 authorization — one that - /// passed the chain-id / `u64::MAX`-nonce / recoverable-authority / code gates and therefore - /// writes the authority account — as TX-level persistent usage across all three dimensions. - /// - /// Every applied authorization writes the authority account (delegation code + nonce bump), - /// so it always costs data size (+40) and a KV update (+1). A net-new authority account - /// additionally counts as state growth (+1) — the caller passes `creates_authority` for that. - /// The matching dynamic SALT account-creation gas is folded into `initial_gas` by the caller. - /// - /// REX5 splits the same accounting into two paths: data size / KV charged unconditionally in - /// `before_tx_start` (covers skipped authorizations too), and state growth via - /// [`AdditionalLimit::on_rex5_eip7702_authority_creations`]. REX6 consolidates them so only - /// applied authorizations pay. - pub(crate) fn on_rex6_eip7702_authority_applied(&mut self, creates_authority: bool) { - self.data_size.record_persistent_account_write(); - self.kv_update.record_persistent_account_update(); - if creates_authority { - self.state_growth.record_authority_creations(1); - } - self.check_limit(); - } + /* Transaction-level records */ - /// Hook called before a new execution frame is initialized. Returns `Some(FrameResult)` if the - /// limit is exceeded and the frame should terminate early with the returned `FrameResult`. + /// Records the account writes of the applied EIP-7702 authorities other than the sender: + /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is + /// one of them, from the transaction's `sender`. /// - /// For REX4+ value-transferring internal `CALL`/`CALLCODE`, this method also applies the - /// `STORAGE_CALL_STIPEND`: it inflates `gas_limit`, caps the per-frame compute gas budget - /// at the original gas limit, and pushes the stipend amount to the burn stack. - pub(crate) fn before_frame_init>( + /// The limit is checked before the records are made: a crossing latches the transaction and + /// records nothing, and the caller takes the authorizations back, so the writes the limit + /// guards never happen. The first frame is then answered with the stop without running. + pub(crate) fn record_applied_authorities( &mut self, - frame_init: &mut FrameInit, - journal: &mut JOURNAL, - ) -> Result, JOURNAL::DBError> { - // Push new frame in frame limit trackers. - self.state_growth.before_frame_init(frame_init, journal)?; - self.data_size.before_frame_init(frame_init, journal)?; - self.kv_update.before_frame_init(frame_init, journal)?; - self.compute_gas.before_frame_init(frame_init, journal)?; - - // REX4+: detect value-transferring CALL/CALLCODE, inflate gas_limit, push stipend - // to stack, and cap per-frame compute gas budget. - self.storage_call_stipend.before_frame_init(frame_init, &mut self.compute_gas); - - if self.check_limit().exceeded_limit() { - return Ok(self.create_exceeded_limit_result(&frame_init.frame_input)); + sender: Address, + authorities: u64, + target_is_authority: bool, + ) -> LimitCheck { + self.sender = sender; + let records = WRITE_RECORD.times(authorities); + let used = self.tracker.net().saturating_add(records).data_size; + if used > self.limits.tx_data_size_limit { + return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); } - - Ok(None) + self.target_is_authority = target_is_authority; + self.tracker.record(records); + LimitCheck::WithinLimit } - /// Checks whether a TX-level limit was already exceeded before the first frame starts - /// (e.g., intrinsic `DataSize` or `KVUpdate` overflow from `before_tx_start()`). + /* Frame lanes */ + + /// Pushes the lane of a frame about to start and counts the writes its start makes: /// - /// Called from two sites that would otherwise skip `before_frame_init()`: - /// - `frame_init()` before system contract interceptor dispatch (REX4+). - /// - `inspect_frame_init()` before inspector early-return (REX4+). + /// - a call that transfers value: the sender's account (once per sender frame) and the + /// recipient's, one record when they are the same account; + /// - a creation: the created account, and the creator's nonce (once per creator frame); + /// - the transaction's own frame: the value recipient or the created account. /// - /// Without this check, an intrinsic overflow would never be converted into a real - /// failure and gas rescue would be missed. + /// The sender's account is part of the transaction body and never a record here: a frame + /// running as the sender (reached through an EIP-7702 delegation) counts it as recorded, and + /// a value transfer to the sender records no recipient. /// - /// Returns `Some(FrameResult)` if a TX-level limit is already exceeded. - pub(crate) fn frame_result_if_exceeding_limit( - &mut self, - frame_input: &FrameInput, - ) -> Option { - if !self.limit_exceeded() { - return None; + /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. + /// So is every frame of a latched transaction, whose lane stays empty. + pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { + self.frame_began = true; + if let Some(latched) = self.latched { + self.push_empty_frame(); + return latched; } - self.create_exceeded_limit_result(frame_input) + self.push_lane(input, depth); + self.check() } - /// Creates a `FrameResult` for an exceeded limit and rescues remaining gas. - /// - /// Shared by `before_frame_init` (limit exceeded after pushing sub-tracker frames) - /// and `frame_result_if_exceeding_limit` (intrinsic overflow before frame push). - fn create_exceeded_limit_result(&mut self, frame_input: &FrameInput) -> Option { - let (gas_limit, return_memory_offset) = match frame_input { - FrameInput::Call(inputs) => { - (inputs.gas_limit, Some(inputs.return_memory_offset.clone())) - } - FrameInput::Create(inputs) => (inputs.gas_limit, None), - FrameInput::Empty => unreachable!(), + fn push_lane(&mut self, input: &FrameInput, depth: usize) { + let budget = match self.tracker.current() { + Some(caller) => caller.remaining_budget().min(self.limits.frame_data_size_limit), + None => self.limits.frame_data_size_limit, }; - let output = self.has_exceeded_limit.revert_data(); - let result = create_exceeding_limit_frame_result( - self.exceeding_instruction_result(), - Gas::new(gas_limit), - return_memory_offset, - output, - ); - self.try_rescue_gas(result.gas()); - Some(result) - } - - /// Hook called when a new execution frame is successfully initialized in `frame_init` and needs - /// to be run (i.e., target address has code). - pub(crate) fn after_frame_init( - &mut self, - init_result: &ItemOrResult<&mut EthFrame, FrameResult>, - ) { - if let ItemOrResult::Item(frame) = &init_result { - self.state_growth.after_frame_init_on_frame(frame); - self.data_size.after_frame_init_on_frame(frame); - self.kv_update.after_frame_init_on_frame(frame); - self.compute_gas.after_frame_init_on_frame(frame); - } else if let ItemOrResult::Result(result) = init_result { - // Rescue gas if a TX-level limit was exceeded. This covers the - // before_frame_init early-return path and any other Result from frame_init. - self.try_rescue_gas(result.gas()); - } - } - - /// Hook called before a frame run. If the limit is exceeded, return an interpreter result - /// indicating that the limit is exceeded. - pub(crate) fn before_frame_run( - &mut self, - frame: &EthFrame, - ) -> Option { - self.state_growth.before_frame_run(frame); - self.data_size.before_frame_run(frame); - self.kv_update.before_frame_run(frame); - self.compute_gas.before_frame_run(frame); - - if self.check_limit().exceeded_limit() { - let output = self.has_exceeded_limit.revert_data(); - return Some(create_exceeding_interpreter_result( - self.exceeding_instruction_result(), - frame.interpreter.gas, - output, - )); - } - None - } - - /// Hook called after frame action processing in `frame_run`. - /// - /// Records compute gas cost induced in frame action processing (e.g., code deposit cost), - /// marks the frame result as exceeding limit if needed, and rescues gas if a TX-level limit - /// was exceeded (before any inspector callback that might modify gas). - pub(crate) fn after_frame_run( - &mut self, - result: &mut FrameResult, - gas_remaining_before_process_action: Option, - ) { - if let Some(gas_remaining_before) = gas_remaining_before_process_action { - let compute_gas_cost = gas_remaining_before.saturating_sub(result.gas().remaining()); - if !self.record_compute_gas(compute_gas_cost) { - mark_frame_result_as_exceeding_limit( - result, - self.exceeding_instruction_result(), - Default::default(), - ); - } - } - // Rescue gas if a TX-level additional limit has been exceeded. - // This must happen before any inspector callback (`frame_end`) that might modify - // the gas via `spend_all()`, so the correct `gas.remaining()` value is captured. - self.try_rescue_gas(result.gas()); - } - - /// Hook called when a frame finishes running in `frame_run`. If the limit is exceeded, mark - /// in place the interpreter result as exceeding the limit. - pub(crate) fn after_frame_run_instructions<'a>( - &mut self, - frame: &'a EthFrame, - action: &'a mut InterpreterAction, - ) { - self.state_growth.after_frame_run(frame, action); - self.data_size.after_frame_run(frame, action); - self.kv_update.after_frame_run(frame, action); - self.compute_gas.after_frame_run(frame, action); - - if let InterpreterAction::Return(interpreter_result) = action { - if frame.data.is_create() { - // Fast-path: a TX-level limit was latched earlier; pick it up without re-running - // sub-tracker checks. Under `Exempt`, the predicate is false, so the exemption - // passes through unchanged. - if self.limit_exceeded() { - let output = self.has_exceeded_limit.revert_data(); - mark_interpreter_result_as_exceeding_limit( - interpreter_result, - self.exceeding_instruction_result(), - output, - ); + match input { + FrameInput::Call(inputs) => { + let target = inputs.target_address; + let transfers_value = inputs.transfers_value(); + if depth == 0 { + self.sender = inputs.caller; + let written_outside = target == inputs.caller || self.target_is_authority; + self.tracker.push(Lane::new( + Some(target), + written_outside || transfers_value, + budget, + )); + if transfers_value && !written_outside { + self.tracker.record(WRITE_RECORD); + } return; } - - // The sub-tracker `after_frame_run` calls above may have recorded new usage; run - // a fresh check to catch overflow first detected at this frame end. - if self.check_limit().exceeded_limit() { - let output = self.has_exceeded_limit.revert_data(); - mark_interpreter_result_as_exceeding_limit( - interpreter_result, - self.exceeding_instruction_result(), - output, - ); + let inherited = self.tracker.current().is_some_and(|caller| { + caller.address == Some(target) && caller.account_recorded + }); + let is_sender = target == self.sender; + self.tracker.push(Lane::new( + Some(target), + inherited || is_sender || transfers_value, + budget, + )); + if transfers_value { + self.tracker.record_caller(false); + if target != inputs.caller && !is_sender { + self.tracker.record(WRITE_RECORD); + } } } - } - } - - /// Hook called when returning a frame result to parent frame in `frame_return_result` or - /// `last_frame_result`. May modify the frame result in place if the limit is exceeded. - pub(crate) fn before_frame_return_result( - &mut self, - result: &mut FrameResult, - ) { - // TRUE if the current function is called twice for the top-level frame. If the top-level - // frame has child frames, the top-level frame's result will be handled twice (one via - // `EvmTr::frame_return_result`, the other via `Handler::last_frame_result`). This flag is - // used to distinguish these two cases. - let duplicate_return_frame_result = LAST_FRAME && !self.data_size.has_active_frame(); - - // Pop frame from the frame limit trackers. - self.state_growth.before_frame_return_result::(result); - self.data_size.before_frame_return_result::(result); - self.kv_update.before_frame_return_result::(result); - self.compute_gas.before_frame_return_result::(result); - - // Pop stipend from stack and burn unused stipend (Rex4+). - self.storage_call_stipend.before_frame_return_result::(result); - - // Frame-level limit handling (Rex4+): check if the child frame exceeded its - // frame-local budget. The detection may not have happened during execution, so - // we call check_limit() here to ensure it's caught. - // If frame-local, absorb it — clear the exceed flag and change to Revert so - // remaining gas returns to the caller. State changes are reverted by revm's - // Revert handling. This works at any depth including the top-level frame. - let limit_check = self.check_limit(); - if limit_check.exceeded_limit() && !duplicate_return_frame_result { - if limit_check.is_frame_local() { - let output = limit_check.revert_data(); - self.has_exceeded_limit = LimitCheck::WithinLimit; - match result { - FrameResult::Call(o) => { - o.result.result = InstructionResult::Revert; - o.result.output = output; - } - FrameResult::Create(o) => { - o.result.result = InstructionResult::Revert; - o.result.output = output; - } + FrameInput::Create(inputs) => { + self.tracker.push(Lane::new(None, true, budget)); + self.tracker.record(WRITE_RECORD); + if depth == 0 { + self.sender = inputs.caller(); + } else { + self.tracker.record_caller(true); } - } else { - // Gas should already have been rescued at the point where the limit was - // exceeded (frame_result_if_exceeding_limit, before_frame_init, - // after_frame_init, or after_frame_run). - // Just mark the result as exceeding the limit. - mark_frame_result_as_exceeding_limit( - result, - Self::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); } + FrameInput::Empty => self.push_empty_frame(), } } - /// Merges resource usage from a sandbox execution into this tracker. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox resource consumption - /// back to the parent transaction. - pub(crate) fn merge_usage(&mut self, usage: LimitUsage) { - self.compute_gas.merge_persistent_usage(usage.compute_gas); - self.data_size.merge_persistent_usage(usage.data_size); - self.kv_update.merge_persistent_usage(usage.kv_updates); - self.state_growth.merge_persistent_usage(usage.state_growth); - } - - /// Hook called when an orginally zero storage slot is written non-zero value for the first time - /// in the transaction. Returns `false` if the limit has been exceeded. - pub(crate) fn on_sstore( - &mut self, - target_address: Address, - slot: U256, - store_result: &SStoreResult, - ) -> bool { - self.state_growth.after_sstore(target_address, slot, store_result); - self.data_size.after_sstore(target_address, slot, store_result); - self.kv_update.after_sstore(target_address, slot, store_result); - - !self.check_limit().exceeded_limit() - } - - /// REX5+: record that the current transaction's caller account is being materialised - /// by deposit pre-execution (mint balance increment, nonce bump, or both). - /// - /// Routes a `+1` to `state_growth`'s TX intrinsic lane only. Does **not** touch - /// `data_size` or `kv_update`: their `before_tx_start` hooks already record the - /// caller's account-info write unconditionally for every transaction (protocol-level - /// definition: one caller account-info write per tx). Adding a second record here - /// would double-count. - /// - /// Must be called exactly once per deposit-like transaction, only when the caller - /// account is empty at validation time (before `OpHandler::pre_execution` runs). - pub(crate) fn record_deposit_caller_creation(&mut self) { - self.state_growth.record_deposit_caller_creation(); - let _ = self.check_limit(); - } - - /// REX5+: meter an oracle-hint payload against the TX data-size budget. - /// - /// Records `len` bytes into the TX intrinsic data-size lane (same lane as calldata) and - /// runs `check_limit()` so `has_exceeded_limit` is flipped to a TX-level exceed if the - /// recording overflows. - /// - /// Returns `true` if the recording stayed within the limit, `false` otherwise. - /// - /// **Caller contract**: on `false`, do NOT synthesize a result. Return `None` from the - /// interceptor and let the next `frame_init` step (`before_frame_init` → - /// `create_exceeded_limit_result`) produce the canonical TX-level `OutOfGas` halt with - /// rescued gas. This keeps the failure shape identical to any other data-size overflow. - pub(crate) fn record_oracle_hint_bytes(&mut self, len: u64) -> bool { - self.data_size.record_oracle_hint_bytes(len); - !self.check_limit().exceeded_limit() - } - - /// Hook called when a log is written. Returns `false` if the limit has been exceeded. - pub(crate) fn on_log(&mut self, num_topics: u64, data_size: u64) -> bool { - self.state_growth.after_log(num_topics, data_size); - self.data_size.after_log(num_topics, data_size); - - !self.check_limit().exceeded_limit() - } - - /// Hook called after a SELFDESTRUCT on a same-TX-created account (REX4+). - /// - /// Records state growth refund for the destroyed account and its new storage slots. - /// The caller is responsible for computing the total refund before calling this. - pub(crate) fn on_selfdestruct(&mut self, refund: u64) { - self.state_growth.after_selfdestruct(refund); - } - - /// Records resource usage when SELFDESTRUCT creates a new beneficiary account (REX5+). - /// - /// Charges data size (+40 for account info write), KV update (+1), and state growth (+1). - pub(crate) fn on_selfdestruct_new_account(&mut self) { - // Account info write: same as DataSizeTracker's ACCOUNT_INFO_WRITE_SIZE (40 bytes) - self.data_size.record_account_write(); - self.kv_update.record_account_update(); - self.state_growth.record_growth(1); - } - - /// Records resource usage when SELFDESTRUCT transfers balance to an existing - /// beneficiary account (REX6+). - /// - /// Charges data size (+40 for account info write) and KV update (+1). The target - /// already exists, so no `StateGrowth` is recorded. SELFDESTRUCT does not push a call - /// frame, so the `target_updated` dedup path in `FrameLimitTracker` never sees the - /// balance write to an existing target — hence this dedicated hook. - pub(crate) fn on_selfdestruct_existing_account(&mut self) { - self.data_size.record_account_write(); - self.kv_update.record_account_update(); - } -} - -/// Creates a `FrameResult` indicating that the limit is exceeded. -/// -/// This utility function creates a frame result that signals limit exceeded. -/// -/// # Arguments -/// -/// * `gas_limit` - The gas limit of the transaction -/// * `return_memory_offset` - The memory offset of the return value if the frame is a call frame. -/// `None` if the frame is a create frame -/// -/// # Returns -/// -/// A `FrameResult` indicating that the limit is exceeded with the given instruction result. -fn create_exceeding_limit_frame_result( - instruction_result: InstructionResult, - gas: Gas, - return_memory_offset: Option>, - output: Bytes, -) -> FrameResult { - match return_memory_offset { - None => FrameResult::Create(CreateOutcome::new( - create_exceeding_interpreter_result(instruction_result, gas, output), - None, - )), - Some(return_memory_offset) => FrameResult::Call(CallOutcome::new( - create_exceeding_interpreter_result(instruction_result, gas, output), - return_memory_offset, - )), - } -} - -/// Creates an interpreter result indicating that the limit is exceeded. -fn create_exceeding_interpreter_result( - instruction_result: InstructionResult, - gas: Gas, - output: Bytes, -) -> InterpreterResult { - InterpreterResult::new(instruction_result, output, gas) -} - -/// Marks an existing interpreter result as exceeding the limit. -fn mark_interpreter_result_as_exceeding_limit( - result: &mut InterpreterResult, - instruction_result: InstructionResult, - output: Bytes, -) { - result.result = instruction_result; - result.output = output; -} - -/// Marks a frame result as exceeding the limit. -pub(crate) fn mark_frame_result_as_exceeding_limit( - result: &mut FrameResult, - instruction_result: InstructionResult, - output: Bytes, -) { - match result { - FrameResult::Call(call_outcome) => { - mark_interpreter_result_as_exceeding_limit( - &mut call_outcome.result, - instruction_result, - output, - ); - } - FrameResult::Create(create_outcome) => { - mark_interpreter_result_as_exceeding_limit( - &mut create_outcome.result, - instruction_result, - output, - ); - } - } -} - -#[cfg(test)] -mod metering_exemption_tests { - use super::*; - - /// Tiny per-dimension limits so a single recording trivially exceeds them. - fn tiny_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 1, - tx_kv_updates_limit: 1, - tx_compute_gas_limit: 1, - tx_state_growth_limit: 1, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, + /// Sets the account the running frame runs as, once known (a creation's address). + pub(crate) fn set_frame_address(&mut self, address: Address) { + if let Some(lane) = self.tracker.current_mut() { + lane.address = Some(address); } } - #[test] - fn test_metering_enforced_when_not_exempt() { - // Default (non-exempt): halted once compute gas exceeds the (tiny) limit. The REX6 × - // system-origin gate that would stamp `Exempt` lives in `MegaContext::on_new_tx`; here we - // exercise the tracker directly. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - assert!(!al.record_compute_gas(1_000_000), "non-exempt tx must report exceeded limit"); - assert!(al.check_limit().exceeded_limit()); - } - - #[test] - fn test_metering_bypassed_when_exempt() { - // When the system-tx exemption is stamped, `check_limit` short-circuits on the sticky - // `Exempt` state, covering the four dimensions *and* gas detention, so the same - // over-limit usage never halts. Usage is still recorded (only the halt decision is - // suppressed). - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.record_compute_gas(1_000_000), "exempt tx must not report exceeded limit"); - assert!(!al.check_limit().exceeded_limit()); - assert!(al.check_limit().is_exempt(), "check_limit must surface the sticky Exempt state"); - assert!(al.get_usage().compute_gas >= 1_000_000, "usage is still accumulated while exempt"); - } - - #[test] - fn test_detained_compute_gas_does_not_halt_when_exempt() { - // Gas detention lowers the detained compute-gas limit; enforcement runs through the same - // `check_limit` chokepoint, so the exemption neutralizes detention too. - let mut al = - AdditionalLimit::new(MegaSpecId::REX6, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX6)); - al.mark_exempt(); - al.set_compute_gas_limit(1); // detain hard - assert!(al.record_compute_gas(10_000_000), "exempt tx must ignore gas detention"); - assert!(!al.check_limit().exceeded_limit()); - } - - #[test] - fn test_reset_clears_exempt() { - // The sticky `Exempt` state must not leak to the next transaction reusing the same tracker. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.has_exceeded_limit.is_exempt()); - al.reset(); - assert!(!al.has_exceeded_limit.is_exempt(), "reset must clear the sticky Exempt state"); - assert!( - al.has_exceeded_limit.within_limit(), - "reset must restore the WithinLimit baseline" - ); - assert!(!al.record_compute_gas(1_000_000), "after reset, metering is enforced again"); + /// Takes a creation's creator record back: the creation failed before bumping the nonce. + pub(crate) fn creation_did_not_bump_nonce(&mut self) { + self.tracker.drop_caller_record(); } -} - -#[cfg(test)] -mod tests { - use revm::context::tx::TxEnvBuilder; - - use super::{super::LimitKind, *}; - fn test_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 100, - tx_kv_updates_limit: 1_000, - tx_compute_gas_limit: 1_000_000, - tx_state_growth_limit: 1_000, - block_env_access_compute_gas_limit: 1_000_000, - oracle_access_compute_gas_limit: 1_000_000, + /// Pushes the lane of a frame answered without running: a result built without an + /// interpreter keeps the lanes aligned with the frames revm returns. + pub(crate) fn push_empty_frame(&mut self) { + self.frame_began = true; + self.tracker.push(Lane::empty()); + } + + /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, + /// a failure discards it. Under a latch the result is first rewritten to the latched stop, + /// whatever produced it (an interceptor, an inspector's rewrite), so no success passes it. + pub(crate) fn on_frame_return(&mut self, result: &mut FrameResult) { + self.apply_latch(result); + self.tracker.pop(result.instruction_result().is_ok()); + } + + /// Settles the transaction's outermost frame: pops its lane unless the frame already + /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever + /// it ran, and rewrites the result to the latched stop. + /// + /// A transaction whose first frame never reached frame init ran out of gas in the runtime + /// phase before it: the out-of-gas took back the authorizations applied before it, so their + /// records and any latch they set go too, and the halt stays a halt. + pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { + if !self.frame_began { + self.tracker.reset(); + self.latched = None; + return; } - } - - /// Returns the latched limit kind, or `None` when within limit. - fn latched_kind(limit: &AdditionalLimit) -> Option { - match limit.has_exceeded_limit { - LimitCheck::ExceedsLimit { kind, .. } => Some(kind), - LimitCheck::WithinLimit | LimitCheck::Exempt => None, + debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); + if self.tracker.depth() == 1 { + self.on_frame_return(result); + } else { + self.apply_latch(result); } } - - /// Compute gas must be recorded even when another dimension has already latched an - /// exceed: the work was performed, and the recorded total feeds the transaction outcome - /// and block-level compute accounting. A skipped record would under-report compute usage - /// for transactions halted on a non-compute dimension. - /// - /// This pins the `validate()` path: `before_tx_start` latches intrinsic data-size - /// overflow before any frame exists, then the initial gas is recorded. - #[test] - fn test_record_compute_gas_records_after_other_dimension_latched() { - let mut limit = AdditionalLimit::new(MegaSpecId::REX5, test_limits()); - - // Latch the data-size dimension at its mutation site: intrinsic transaction data - // (110-byte base + 200 bytes of calldata) exceeds the 100-byte limit. - let tx = MegaTransaction::new( - TxEnvBuilder::new() - .caller(Address::ZERO) - .call(Address::ZERO) - .data(vec![0u8; 200].into()) - .build_fill(), - ); - limit.before_tx_start(&tx); - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - - // The trailing compute-gas record of the same opcode must still surface the latched - // exceed AND record the gas. - assert!(!limit.record_compute_gas(5_000), "latched exceed must surface as false"); - assert_eq!( - limit.get_usage().compute_gas, - 5_000, - "compute gas must be recorded even after another dimension latched", - ); - - // The latched kind is preserved (not overwritten by the compute-gas check). - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - } - - /// SELFDESTRUCT's beneficiary usage is recorded *before* the inner instruction runs and - /// must NOT latch at the recording site: the inner instruction can still fail (out of - /// gas, DB error), in which case the frame pops the discardable usage and a latch taken - /// at recording time would stick and misattribute the failure. The latch belongs to the - /// trailing all-dimension check, which only runs after the inner instruction succeeds. - #[test] - fn test_selfdestruct_usage_latches_only_at_trailing_check() { - let mut limits = test_limits(); - // Below the 40-byte account-info write, so the beneficiary creation exceeds it. - limits.tx_data_size_limit = 10; - let mut limit = AdditionalLimit::new(MegaSpecId::REX5, limits); - // Simulate an active call frame (SELFDESTRUCT always runs inside one). - limit.push_empty_frame(); - - // Recording site: usage recorded, but no latch yet (inner instruction may still fail). - limit.on_selfdestruct_new_account(); - assert_eq!(latched_kind(&limit), None, "recording site must not latch"); - - // Trailing all-dimension check (runs only after inner success): latches and halts. - assert!(!limit.record_compute_gas_all_dims(100), "trailing check must surface exceed"); - assert_eq!(latched_kind(&limit), Some(LimitKind::DataSize)); - } - - /// `intrinsic_check_for_tx` is a REX5-only preflight (EIP-7702 authority growth); - /// its `debug_assert!(spec.is_enabled(REX5))` precondition must reject a pre-REX5 - /// spec. Calling it at REX4 must trip the assert. - /// - /// Kills the spec-gate mutant `is_enabled(MegaSpecId::REX5) -> is_enabled(REX4)` at - /// limit.rs:203: under the mutant the precondition would silently accept REX4 and the - /// call would return a `LimitCheck` instead of panicking. - #[test] - #[should_panic(expected = "REX5")] - #[cfg(debug_assertions)] - fn test_intrinsic_check_for_tx_requires_rex5_spec() { - let tx = MegaTransaction::new( - TxEnvBuilder::new().caller(Address::ZERO).call(Address::ZERO).build_fill(), - ); - // REX4 < REX5: the precondition assert must fire. - let _ = AdditionalLimit::intrinsic_check_for_tx(MegaSpecId::REX4, &tx, test_limits()); - } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index a536565af..4b15f1d45 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -1,42 +1,145 @@ -use alloy_primitives::Bytes; -use alloy_sol_types::SolError; +//! Resource limits of the Satin engine. +//! +//! The common execution layer defines what a limit reports when it is crossed: the dimension +//! ([`LimitKind`]), the verdict of a check ([`LimitCheck`]) and the revert data a stopped frame +//! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension (the data-size limit, +//! detention, the state-growth and KV limits) fill these in. +//! +//! It also counts what those limits meter at the sites the data-size limit counts: data-size +//! bytes and write records, on a lane per frame ([`AdditionalLimit`]). The Host stages what it +//! observes ([`StagedRecord`]) and the opcode commits it once it completed. -mod compute_gas; -mod data_size; mod frame_limit; -mod kv_update; #[allow(clippy::module_inception)] mod limit; -mod state_growth; -mod storage_call_stipend; +mod record; + +pub use limit::AdditionalLimit; +pub use record::StagedRecord; + +use alloy_primitives::Bytes; +use alloy_sol_types::SolError; + +/// Bytes of one write record: the key and value delta one account or storage write leaves in +/// the state diff. +pub const WRITE_RECORD_SIZE: u64 = 40; + +/// Bytes every log counts for the address it carries. +pub const LOG_BASE_SIZE: u64 = 32; + +/// Bytes every log topic counts. +pub const LOG_TOPIC_SIZE: u64 = 32; + +/// What a transaction or a frame counts: data-size bytes and write records. +/// +/// The KV count a node reports is the write-record count; it has no tracker of its own. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct LimitUsage { + /// Data-size bytes. + pub data_size: u64, + /// Account and storage write records. + pub write_records: u64, +} + +/// Limits the common execution layer enforces on one transaction, for exercising the abort +/// protocol before the mechanisms that own the limits land. Both default to unlimited. +/// +/// The data-size limit replaces them with its own limit and per-frame budget rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EvmTxRuntimeLimits { + /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. + pub tx_data_size_limit: u64, + /// The most data-size bytes one frame may keep, children included, and never more than + /// what its caller has left. Crossing it reverts the frame alone. + pub frame_data_size_limit: u64, +} + +impl Default for EvmTxRuntimeLimits { + fn default() -> Self { + Self::no_limits() + } +} + +impl EvmTxRuntimeLimits { + /// No limit at all. + pub const fn no_limits() -> Self { + Self { tx_data_size_limit: u64::MAX, frame_data_size_limit: u64::MAX } + } + + /// Sets the transaction's data-size limit. + pub const fn with_tx_data_size_limit(mut self, limit: u64) -> Self { + self.tx_data_size_limit = limit; + self + } + + /// Sets the per-frame data-size budget. + pub const fn with_frame_data_size_limit(mut self, limit: u64) -> Self { + self.frame_data_size_limit = limit; + self + } +} + +/// One write record. +pub(crate) const WRITE_RECORD: LimitUsage = + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; + +impl LimitUsage { + /// Nothing counted. + pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + + /// Both counters added, saturating. + pub const fn saturating_add(self, other: Self) -> Self { + Self { + data_size: self.data_size.saturating_add(other.data_size), + write_records: self.write_records.saturating_add(other.write_records), + } + } -pub use data_size::*; -pub(crate) use frame_limit::{FrameLimitTracker, TxRuntimeLimit}; -pub use limit::*; + /// Both counters subtracted, saturating at zero. + pub const fn saturating_sub(self, other: Self) -> Self { + Self { + data_size: self.data_size.saturating_sub(other.data_size), + write_records: self.write_records.saturating_sub(other.write_records), + } + } -use crate::MegaHaltReason; + /// Both counters multiplied by `n`, saturating. + pub const fn times(self, n: u64) -> Self { + Self { + data_size: self.data_size.saturating_mul(n), + write_records: self.write_records.saturating_mul(n), + } + } +} alloy_sol_types::sol! { - /// ABI-encoded error emitted as revert data when a frame-local resource limit is exceeded. + /// The revert data of a frame a resource limit stopped. + /// + /// `kind` is the [`LimitKind`] discriminant and `limit` the limit that was crossed. A frame + /// can revert with the same bytes on its own; whether a limit stopped the transaction is + /// reported by the transaction outcome, not read off the output. #[derive(Debug, PartialEq, Eq)] error MegaLimitExceeded(uint8 kind, uint64 limit); } -/// Identifies which resource limit was exceeded. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +/// A resource dimension a limit meters. +/// +/// The discriminants are the `kind` of [`MegaLimitExceeded`] and keep the values the legacy engine +/// encoded, so a contract that decodes the legacy revert data decodes Satin's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LimitKind { - /// Data size limit (bytes of data transmitted and stored). + /// Bytes of data a transaction produces; metered by the data-size limit. DataSize, - /// Key-value update limit (number of state-modifying operations). + /// Key-value updates; metered by the state-growth and KV limits. KVUpdate, - /// Compute gas limit (cumulative EVM instruction gas). + /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, - /// State growth limit (net new accounts and storage slots). + /// Net new state; metered by the state-growth and KV limits. StateGrowth, } impl LimitKind { - /// Returns the discriminant value used in ABI-encoded revert data. + /// The `kind` of [`MegaLimitExceeded`]. pub const fn as_u8(&self) -> u8 { match self { Self::DataSize => 0, @@ -46,7 +149,7 @@ impl LimitKind { } } - /// Converts a discriminant value back to a `LimitKind`. + /// The dimension a `kind` of [`MegaLimitExceeded`] names, if any. pub const fn from_u8(kind: u8) -> Option { match kind { 0 => Some(Self::DataSize), @@ -58,73 +161,58 @@ impl LimitKind { } } -/// Result of a limit check. +/// The verdict of a limit check. /// -/// Carries three semantically distinct states: limits passed; a limit was exceeded (with -/// metadata for the halt path); or per-tx metering is exempt (REX6+ system-originated tx — -/// see [`crate::is_system_originated`]). The `Exempt` state is **sticky**: once `AdditionalLimit` -/// stores it in `has_exceeded_limit`, `check_limit` short-circuits and the sub-tracker checks -/// are skipped, so no later overflow can overwrite it. -#[derive(Debug, Default, Clone, Copy)] +/// A transaction-level exceed stops the transaction: the frame that crosses it reverts, the +/// transaction is latched and every frame above reverts in turn. A frame-local exceed (a frame +/// budget) reverts the frame alone and its caller resumes. `Exempt` is sticky for the +/// transaction: nothing it does is stopped by a limit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum LimitCheck { - /// All limits are within their configured thresholds. + /// Every limit holds. #[default] WithinLimit, - /// A limit has been exceeded. + /// A limit was crossed. ExceedsLimit { - /// Which resource limit was exceeded. + /// The dimension crossed. kind: LimitKind, - /// The configured limit. + /// The limit crossed. limit: u64, - /// The current usage. + /// The usage that crossed it. used: u64, - /// Whether this exceed is from a frame-local budget (absorbable at frame boundary) - /// vs a TX-level limit (must propagate to halt the transaction). + /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, }, - /// Per-tx metering is exempt: REX6+ system-originated tx (see - /// [`crate::is_system_originated`]). Behaves as not-exceeded for halt decisions; sticky as - /// described on the enum. Sub-tracker `check_limit` impls never produce this variant — - /// only `AdditionalLimit::has_exceeded_limit` carries it, set via - /// [`AdditionalLimit::mark_exempt`](super::AdditionalLimit::mark_exempt). + /// The transaction is exempt from metering. Exempt, } impl LimitCheck { - /// Returns `true` if a resource limit has been exceeded. - /// - /// `Exempt` returns `false`: per-tx metering is suppressed, so the halt path must not fire. + /// Whether a limit was crossed. `Exempt` is not. #[inline] pub const fn exceeded_limit(&self) -> bool { matches!(self, Self::ExceedsLimit { .. }) } - /// Returns `true` strictly when no limit check has been performed yet or the last check passed. - /// - /// `Exempt` returns `false`: it is a distinct sticky state, not a "passed" result. Callers - /// that just want to gate the halt path should use [`exceeded_limit`](Self::exceeded_limit) - /// (its negation), not this predicate. + /// Whether the check passed. `Exempt` is a state of its own, not a pass. #[inline] pub const fn within_limit(&self) -> bool { matches!(self, Self::WithinLimit) } - /// Returns `true` when per-tx metering is suppressed for the current transaction. + /// Whether the transaction is exempt from metering. #[inline] pub const fn is_exempt(&self) -> bool { matches!(self, Self::Exempt) } - /// Returns whether this is a frame-local exceed. + /// Whether a frame budget, rather than a transaction-level limit, was crossed. #[inline] pub const fn is_frame_local(&self) -> bool { matches!(self, Self::ExceedsLimit { frame_local: true, .. }) } - /// Returns ABI-encoded revert data for a frame-local limit exceed. - /// - /// Encodes as `MegaLimitExceeded(uint8 kind, uint64 limit)`. Returns empty bytes for - /// `WithinLimit` and `Exempt` (neither produces a frame-local revert). + /// The [`MegaLimitExceeded`] revert data of a crossed limit; empty otherwise. pub fn revert_data(&self) -> Bytes { match self { Self::ExceedsLimit { kind, limit, .. } => { @@ -133,36 +221,26 @@ impl LimitCheck { Self::WithinLimit | Self::Exempt => Bytes::new(), } } - - /// Returns the [`MegaHaltReason`] if a limit has been exceeded. - /// - /// `WithinLimit` and `Exempt` both return `None`: neither halts the transaction. - pub fn maybe_halt_reason(&self) -> Option { - match self { - Self::ExceedsLimit { kind: LimitKind::DataSize, limit, used, .. } => { - Some(MegaHaltReason::DataLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::KVUpdate, limit, used, .. } => { - Some(MegaHaltReason::KVUpdateLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::ComputeGas, limit, used, .. } => { - Some(MegaHaltReason::ComputeGasLimitExceeded { limit: *limit, actual: *used }) - } - Self::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used, .. } => { - Some(MegaHaltReason::StateGrowthLimitExceeded { limit: *limit, actual: *used }) - } - Self::WithinLimit | Self::Exempt => None, - } - } } #[cfg(test)] mod tests { use super::*; - /// Pins the predicate truth-table for the `Exempt` variant so a future change that flips one - /// predicate (e.g., reverting `exceeded_limit` to `!matches!(WithinLimit)`) is caught here - /// rather than silently re-enabling halts for exempt txs. + #[test] + fn test_limit_usage_arithmetic_saturates() { + let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; + assert_eq!(max.saturating_add(WRITE_RECORD), max); + assert_eq!(LimitUsage::ZERO.saturating_sub(WRITE_RECORD), LimitUsage::ZERO); + assert_eq!(WRITE_RECORD.times(3), LimitUsage { data_size: 120, write_records: 3 }); + assert_eq!(WRITE_RECORD.times(u64::MAX).data_size, u64::MAX); + assert_eq!( + WRITE_RECORD.saturating_add(WRITE_RECORD).saturating_sub(WRITE_RECORD), + WRITE_RECORD + ); + } + + /// `Exempt` passes no predicate that would stop a frame, and has no revert data. #[test] fn test_limit_check_exempt_predicate_truth_table() { let exempt = LimitCheck::Exempt; @@ -171,10 +249,9 @@ mod tests { assert!(exempt.is_exempt()); assert!(!exempt.is_frame_local()); assert!(exempt.revert_data().is_empty()); - assert!(exempt.maybe_halt_reason().is_none()); } - /// `within_limit` must mirror the enum variant exactly, not return a constant. + /// `within_limit` follows the variant. #[test] fn test_within_limit_reflects_variant() { assert!(LimitCheck::WithinLimit.within_limit()); @@ -185,18 +262,32 @@ mod tests { frame_local: false, }; assert!(!exceeded.within_limit()); + assert!(exceeded.exceeded_limit()); + assert!(!exceeded.is_frame_local()); + assert!(!exceeded.is_exempt()); + assert!(!LimitCheck::WithinLimit.is_exempt()); + assert!(!LimitCheck::WithinLimit.exceeded_limit()); + assert!(LimitCheck::WithinLimit.revert_data().is_empty()); + let frame_local = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 150, + frame_local: true, + }; + assert!(frame_local.is_frame_local()); + assert!(frame_local.exceeded_limit()); } - /// Every `LimitKind` discriminant must survive an `as_u8` -> `from_u8` round-trip, - /// and unknown discriminants must map to `None`. + /// Every discriminant survives the round trip, and an unknown one maps to nothing. #[test] fn test_limit_kind_u8_roundtrip() { - for kind in [ - LimitKind::DataSize, - LimitKind::KVUpdate, - LimitKind::ComputeGas, - LimitKind::StateGrowth, + for (kind, expected) in [ + (LimitKind::DataSize, 0), + (LimitKind::KVUpdate, 1), + (LimitKind::ComputeGas, 2), + (LimitKind::StateGrowth, 3), ] { + assert_eq!(kind.as_u8(), expected, "{kind:?}"); assert_eq!( LimitKind::from_u8(kind.as_u8()), Some(kind), @@ -205,4 +296,20 @@ mod tests { } assert_eq!(LimitKind::from_u8(4), None); } + + /// The revert data is the ABI encoding of `MegaLimitExceeded(uint8,uint64)`. + #[test] + fn test_revert_data_encodes_mega_limit_exceeded() { + let check = LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 7, + used: 9, + frame_local: true, + }; + let data = check.revert_data(); + assert_eq!(&data[..4], MegaLimitExceeded::SELECTOR.as_slice()); + let decoded = MegaLimitExceeded::abi_decode(&data).unwrap(); + assert_eq!(decoded, MegaLimitExceeded { kind: 3, limit: 7 }); + assert_eq!(MegaLimitExceeded::SIGNATURE, "MegaLimitExceeded(uint8,uint64)"); + } } diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs new file mode 100644 index 000000000..93eb729e7 --- /dev/null +++ b/crates/mega-evm/src/limit/record.rs @@ -0,0 +1,159 @@ +//! The facts the Host observes for the opcode that is running. + +use alloy_primitives::Address; +use revm::interpreter::SStoreResult; + +use super::{LimitUsage, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD}; + +/// What the Host saw an opcode do, staged until the opcode completes. +/// +/// The Host only observes: it stages the facts revm hands it and records nothing. The opcode's +/// wrapper commits the staged record once the opcode completed, or discards it when the opcode +/// failed after the Host call (an out-of-gas on the gas charged after the write, say), because the +/// failure takes the write back with it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StagedRecord { + /// An `SSTORE`: the slot's value at the start of the transaction, before the write, and + /// after it. + Sstore(SStoreResult), + /// A `LOG`: its topic count and data length. + Log { + /// Number of topics. + topics: u8, + /// Length of the data, in bytes. + data_len: u64, + }, + /// A `SELFDESTRUCT`. + SelfDestruct { + /// Whether the destructed account had a balance to move. + had_value: bool, + /// Whether the beneficiary existed before. + target_exists: bool, + /// Whether the beneficiary is another account than the destructed one. + to_other_account: bool, + /// The beneficiary. + beneficiary: Address, + }, +} + +/// How a committed record changes the running frame's usage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RecordEffect { + /// Nothing to count. + None, + /// Count this usage. + Record(LimitUsage), + /// Take this usage back. + Refund(LimitUsage), +} + +impl StagedRecord { + /// What committing the record counts, per site: + /// + /// - `SSTORE`: the first change of a slot in the transaction is one write record; writing the + /// slot back to its original value takes the record back. + /// - `LOG`: its bytes, one base record for the address, one per topic and the data. + /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account + /// than the destructed one and the transaction's `sender`, whose account the transaction body + /// counts. + pub(crate) fn effect(&self, sender: Address) -> RecordEffect { + match self { + Self::Sstore(slot) => { + if slot.is_original_eq_present() { + if slot.is_original_eq_new() { + RecordEffect::None + } else { + RecordEffect::Record(WRITE_RECORD) + } + } else if slot.is_original_eq_new() { + RecordEffect::Refund(WRITE_RECORD) + } else { + RecordEffect::None + } + } + Self::Log { topics, data_len } => RecordEffect::Record(LimitUsage { + data_size: LOG_BASE_SIZE + .saturating_add(LOG_TOPIC_SIZE.saturating_mul(*topics as u64)) + .saturating_add(*data_len), + write_records: 0, + }), + Self::SelfDestruct { had_value, to_other_account, beneficiary, .. } => { + if *had_value && *to_other_account && *beneficiary != sender { + RecordEffect::Record(WRITE_RECORD) + } else { + RecordEffect::None + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, U256}; + + const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); + const OTHER: Address = address!("0000000000000000000000000000000000000077"); + + fn sstore(original: u64, present: u64, new: u64) -> StagedRecord { + StagedRecord::Sstore(SStoreResult { + original_value: U256::from(original), + present_value: U256::from(present), + new_value: U256::from(new), + }) + } + + /// A slot counts once, on its first change in the transaction; writing it back to its + /// original value takes the record back; every other write counts nothing. + #[test] + fn test_sstore_record_rules() { + assert_eq!(sstore(0, 0, 1).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(5, 5, 0).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 0).effect(SENDER), RecordEffect::Refund(WRITE_RECORD)); + assert_eq!(sstore(0, 1, 2).effect(SENDER), RecordEffect::None); + assert_eq!(sstore(3, 3, 3).effect(SENDER), RecordEffect::None); + assert_eq!(sstore(3, 4, 4).effect(SENDER), RecordEffect::None); + } + + /// A log is 32 bytes for its address, 32 per topic and its data. + #[test] + fn test_log_bytes() { + let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(SENDER); + assert_eq!(log(0, 0), RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 })); + assert_eq!( + log(4, 100), + RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) + ); + assert_eq!( + log(1, u64::MAX), + RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) + ); + } + + /// Only value that moves to another account is a beneficiary write. + #[test] + fn test_selfdestruct_record_rules() { + let sd = |had_value, to_other_account| { + let beneficiary = OTHER; + StagedRecord::SelfDestruct { + had_value, + target_exists: true, + to_other_account, + beneficiary, + } + .effect(SENDER) + }; + assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); + assert_eq!(sd(true, false), RecordEffect::None); + assert_eq!(sd(false, true), RecordEffect::None); + assert_eq!(sd(false, false), RecordEffect::None); + let to_sender = StagedRecord::SelfDestruct { + had_value: true, + target_exists: true, + to_other_account: true, + beneficiary: SENDER, + }; + assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); + } +} diff --git a/crates/mega-evm/src/limit/state_growth.rs b/crates/mega-evm/src/limit/state_growth.rs deleted file mode 100644 index 758eafbc6..000000000 --- a/crates/mega-evm/src/limit/state_growth.rs +++ /dev/null @@ -1,380 +0,0 @@ -//! # State Growth Tracking -//! -//! This module implements tracking of **net state growth** during transaction execution. -//! State growth measures the expansion of blockchain state by counting new accounts and -//! storage slots created, offset by any that are cleared. -//! -//! ## What Counts as State Growth -//! -//! State growth is measured in discrete units, where each unit represents: -//! -//! - **+1** for creating a new account via `CREATE` / `CREATE2` (net-new address under REX6+; -//! unconditional under pre-REX6) or via `CALL` with value transfer to an empty account -//! - **+1** for each valid EIP-7702 authorization that creates a previously non-existent authority -//! account (Rex5+) -//! - **+1** for writing a storage slot from zero to non-zero for the first time -//! - **-1** for clearing a storage slot back to zero (only when the slot was empty at transaction -//! start) -//! -//! ## Net Growth Model -//! -//! This implementation uses a **net growth** model, meaning: -//! - The counter increases when state is created -//! - The counter decreases when state is cleared -//! - The internal `total_growth` can temporarily become negative during execution -//! - The externally reported growth is clamped to a minimum of zero -//! -//! ### Example: Net Growth Calculation -//! -//! ```text -//! Transaction creates 3 new storage slots: total_growth = +3 -//! Transaction clears 1 slot back to zero: total_growth = +2 -//! Transaction clears 2 more slots: total_growth = 0 -//! ``` -//! -//! ## Frame-Based Tracking -//! -//! State growth is tracked using a frame stack that mirrors the EVM's call frame stack. -//! This ensures proper handling of reverts: -//! -//! - Each `CALL`/`CREATE` pushes a new frame -//! - Growth within a frame is tracked as "discardable" (can be reverted) -//! - On successful frame exit, growth is merged into the parent frame -//! - On failed frame exit (revert), growth is discarded -//! -//! ### Example: Frame Revert Behavior -//! -//! ```text -//! Main transaction starts: Frame 0: discardable = 0 -//! Main creates 2 storage slots: Frame 0: discardable = 2, total = 2 -//! Main calls contract A: Frame 1: discardable = 0 -//! Contract A creates 3 storage slots: Frame 1: discardable = 3, total = 5 -//! Contract A calls contract B: Frame 2: discardable = 0 -//! Contract B creates 1 storage slot: Frame 2: discardable = 1, total = 6 -//! Contract B reverts: Frame 2 discarded, total = 5 -//! Contract A completes successfully: Frame 1 merged to Frame 0, total = 5 -//! Transaction completes: Final growth = 5 -//! ``` -//! -//! ## EIP-161 Compliance -//! -//! The tracker implements EIP-161 account clearing rules: -//! - Only `CALL`-like opcodes with value transfer to empty accounts count as creating an account -//! - `CALL` without value transfer to empty accounts does not count (empty account remains empty) -//! -//! ## Storage Slot Tracking -//! -//! Storage slot state transitions are tracked based on three values: -//! - `original_value`: Value at the start of the transaction -//! - `present_value`: Current value before the SSTORE -//! - `new_value`: Value being written -//! -//! Only transitions that affect the **transaction-level** state growth are counted: -//! - `(zero, zero, non-zero)`: First write to empty slot → **+1** -//! - `(zero, non-zero, zero)`: Clear a slot that was empty at transaction start → **-1** -//! - Other transitions: No change (slot was already non-zero at transaction start) - -use alloy_primitives::{Address, U256}; -use revm::{ - handler::FrameResult, - interpreter::{interpreter_action::FrameInit, FrameInput, SStoreResult}, - primitives::hardfork::SpecId, -}; - -use crate::{FrameLimitTracker, JournalInspectTr, MegaSpecId, TxRuntimeLimit}; - -/// A tracker for net state growth during transaction execution. -/// -/// Uses `FrameLimitTracker` for frame-aware tracking with per-frame budgets (Rex4+). -/// -/// State growth measures the expansion of blockchain state by counting new accounts and -/// storage slots created, offset by any that are cleared: -/// -/// - **+1** for creating a new account via `CREATE` / `CREATE2` (net-new address under REX6+; -/// unconditional under pre-REX6) or via `CALL` with value transfer to an empty account (EIP-161) -/// - **+1** for each valid EIP-7702 authorization that creates a previously non-existent authority -/// account (Rex5+) -/// - **+1** for writing a storage slot from zero to non-zero for the first time -/// - **-1** for clearing a storage slot back to zero (only when the slot was empty at transaction -/// start) -/// -/// See module-level documentation for details on the net growth model and frame-based tracking. -#[derive(Debug, Clone)] -pub(crate) struct StateGrowthTracker { - spec: MegaSpecId, - frame_tracker: FrameLimitTracker<()>, -} - -impl StateGrowthTracker { - pub(crate) fn new(spec: MegaSpecId, tx_limit: u64) -> Self { - Self { spec, frame_tracker: FrameLimitTracker::new(spec, tx_limit) } - } - - /// Pushes a new frame onto the tracker. - /// - /// For Rex4+, delegates to `FrameLimitTracker::push_frame()` which uses - /// `tx_entry.remaining()` for the top-level frame and parent's remaining × 98/100 - /// for nested frames. - /// For pre-Rex4, pushes with `u64::MAX` since per-frame limits are not enforced - /// (the TX-level check in `check_limit()` uses `net_usage()` instead). - fn push_frame(&mut self) { - if self.spec.is_enabled(MegaSpecId::REX4) { - self.frame_tracker.push_frame(()); - } else { - self.frame_tracker.push_frame_with_limit(u64::MAX, ()); - } - } - - /// Records positive state growth in the current frame. - pub(crate) fn record_growth(&mut self, n: u64) { - // For state growth, all growth in the current transaction is discardable on revert. - self.frame_tracker.add_frame_discardable(n); - } - - /// Records a refund (negative growth) in the current frame. - fn record_refund(&mut self, n: u64) { - self.frame_tracker.add_frame_refund(n); - } - - /// REX5+: record +1 net state growth for the materialisation of an empty deposit - /// caller during `OpHandler::pre_execution` (mint balance increment and/or nonce - /// bump). This event does not correspond to any EVM frame, so the +1 is written - /// directly to the TX intrinsic lane (`tx_entry.persistent_usage`) — same lane - /// `before_tx_start` uses for other intrinsic accounting. - pub(crate) fn record_deposit_caller_creation(&mut self) { - self.frame_tracker.add_tx_persistent(1); - } - - /// Merges external persistent usage into the TX-level entry. - /// - /// Used by `KeylessDeploy` (REX5+) to propagate sandbox state growth consumption - /// back to the parent transaction. - pub(crate) fn merge_persistent_usage(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Records EIP-7702 authority accounts that were created by pre-execution auth processing. - /// - /// This is TX-level persistent usage because authorization-list changes are applied before the - /// first EVM frame and are not discarded by frame revert. - pub(crate) fn record_authority_creations(&mut self, amount: u64) { - self.frame_tracker.add_tx_persistent(amount); - } - - /// Returns the remaining state growth budget for the current call frame, capped by - /// the TX-level remaining. - pub(crate) fn current_call_remaining(&self) -> u64 { - let tx_remaining = - self.frame_tracker.tx_limit().saturating_sub(self.frame_tracker.net_usage()); - if self.spec.is_enabled(MegaSpecId::REX4) { - self.frame_tracker.current_frame_remaining().min(tx_remaining) - } else { - tx_remaining - } - } -} - -impl TxRuntimeLimit for StateGrowthTracker { - /// Returns the current effective state growth limit for the entire transaction. - #[inline] - fn tx_limit(&self) -> u64 { - self.frame_tracker.tx_limit() - } - - /// Returns the current net state growth across all frames, clamped to zero. - #[inline] - fn tx_usage(&self) -> u64 { - self.frame_tracker.net_usage() - } - - /// Resets the tracker to its initial state. - /// - /// This clears the frame stack, preparing the tracker for a new transaction. - #[inline] - fn reset(&mut self) { - self.frame_tracker.reset(); - } - - /// Returns whether the state growth limit has been exceeded. - /// - /// For Rex4+, checks the per-frame budget first, then falls through to a TX-level check. - /// The TX-level fallthrough catches intrinsic usage written directly to `tx_entry` — - /// notably the REX5+ deposit-caller-creation record and Rex5 pre-frame authority - /// usage — and any frame-level overflow that has already been popped into `tx_entry`. - /// For pre-Rex4, checks total net growth across all frames against the TX limit. - fn check_limit(&self) -> super::LimitCheck { - if self.spec.is_enabled(MegaSpecId::REX4) { - let frame_check = - self.frame_tracker.exceeds_current_frame_limit(super::LimitKind::StateGrowth); - if frame_check.exceeded_limit() { - return frame_check; - } - // TX-level fallthrough: catches Rex5 pre-frame authority usage and any - // future TX-level state-growth contribution. - } - let used = self.tx_usage(); - let limit = self.frame_tracker.tx_limit(); - if used > limit { - super::LimitCheck::ExceedsLimit { - kind: super::LimitKind::StateGrowth, - limit, - used, - frame_local: false, - } - } else { - super::LimitCheck::WithinLimit - } - } - - /// No-op. - /// - /// REX5 EIP-7702 authority state growth is journal-dependent, so it is recorded later during - /// pre-execution via `record_authority_creations()` rather than from transaction-only data. - fn before_tx_start(&mut self, _tx: &crate::MegaTransaction) {} - - /// Called when inspector intercepts and skips a call/create. - /// - /// Pushes an empty frame so `before_frame_return_result` can pop it to keep - /// the frame stack aligned with the EVM's call stack. - #[inline] - fn push_empty_frame(&mut self) { - self.push_frame(); - } - - /// Hook called before a new execution frame is initialized. - /// - /// Pushes a new frame onto the tracker and records any state growth caused by - /// the frame initialization itself: - /// - /// - **Call with value transfer to empty account**: +1 growth (EIP-161 compliant). Only - /// `CALL`-like opcodes with value transfer to empty accounts count as creating an account. - /// `CALL` without value transfer does not count (empty account remains empty). - /// - **Create** (`CREATE` / `CREATE2`): +1 growth when deploying to a net-new address (REX6+); - /// unconditional +1 for pre-REX6 specs. - /// - **Call without value transfer** or **call to non-empty account**: no growth. - fn before_frame_init>( - &mut self, - frame_init: &FrameInit, - journal: &mut JOURNAL, - ) -> Result<(), JOURNAL::DBError> { - self.push_frame(); - - match &frame_init.frame_input { - FrameInput::Call(call_inputs) => { - // EIP-161: only value transfers to empty accounts count as creating an account. - if call_inputs.transfers_value() { - // REX5+: use non-delegating inspection to get the authority's own state. - let to_account = if self.spec.is_enabled(MegaSpecId::REX5) { - journal.inspect_account(call_inputs.target_address, false)? - } else { - journal.inspect_account_delegated(self.spec, call_inputs.target_address)? - }; - let is_empty = to_account.state_clear_aware_is_empty(SpecId::PRAGUE); - if is_empty { - self.record_growth(1); - } - } - } - FrameInput::Create(create_inputs) => { - if self.spec.is_enabled(MegaSpecId::REX6) { - // REX6: count only net-new accounts. `before_frame_init` runs before revm bumps - // the caller nonce, so the caller's current state nonce is the `old_nonce` the - // deployment uses; derive the target and skip the +1 when it already exists - // (e.g. a pre-funded balance-only account). - let caller_nonce = - journal.inspect_account(create_inputs.caller, false)?.info.nonce; - let created_address = create_inputs.created_address(caller_nonce); - let to_account = journal.inspect_account(created_address, false)?; - if to_account.state_clear_aware_is_empty(SpecId::PRAGUE) { - self.record_growth(1); - } - } else { - self.record_growth(1); - } - } - FrameInput::Empty => unreachable!(), - } - Ok(()) - } - - /// Hook called when a storage slot is written via `SSTORE`. - /// - /// Updates the frame's growth and refund counters based on the storage slot's state - /// transition. - /// Only transitions that affect **transaction-level** state growth are counted: - /// - /// | Original | Present | New | Effect | Reason | - /// |----------|---------|-------|------------|---------------------------------------------| - /// | zero | zero | non-0 | +1 growth | First write to empty slot | - /// | zero | non-0 | zero | +1 refund | Clear slot that was empty at tx start | - /// | zero | non-0 | non-0 | — | Already counted when first written | - /// | non-0 | * | * | — | Slot existed at tx start, no growth change | - /// - /// # Examples - /// - /// ```text - /// Slot starts at 0, write 5: +1 (new storage) - /// Slot starts at 0, write 5, write 10: +1 (only counted once) - /// Slot starts at 0, write 5, write 0: 0 (created then cleared via refund) - /// Slot starts at 5, write 10: 0 (already existed) - /// ``` - fn after_sstore(&mut self, _target_address: Address, _slot: U256, store_result: &SStoreResult) { - match ( - store_result.original_value.is_zero(), - store_result.present_value.is_zero(), - store_result.new_value.is_zero(), - ) { - (true, true, false) => { - // First write to empty slot: slot goes from zero to non-zero → +1 - self.record_growth(1); - } - (true, false, true) => { - // Clear slot: was zero at tx start, became non-zero, now back to zero → -1 - self.record_refund(1); - } - _ => { - // No state growth change: - // - (zero, non-zero, non-zero): Already counted when first written - // - (non-zero, _, _): Slot existed at tx start, modifications don't count - } - } - } - - /// Hook called when a frame returns its result to the parent frame. - /// - /// Pops the current frame from the tracker and handles its accumulated state growth: - /// - **On success**: merges the frame's growth and refunds into the parent frame via - /// `pop_frame::()`. - /// - **On revert/failure**: discards the frame's discardable growth (refunds and persistent - /// usage are still propagated) via `pop_frame::()`. - fn before_frame_return_result(&mut self, result: &FrameResult) { - assert!(LAST_FRAME || self.frame_tracker.has_active_frame(), "frame stack is empty"); - self.frame_tracker.pop_frame(result.instruction_result().is_ok()); - } - - /// Hook called after a SELFDESTRUCT on a same-TX-created account (REX4+). - /// - /// Records a refund for the account and its new storage slots that were - /// previously counted as state growth. This is frame-aware: if the frame reverts, - /// both the SELFDESTRUCT and the refund are discarded together. - fn after_selfdestruct(&mut self, refund: u64) { - self.record_refund(refund); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// `reset` must clear accumulated TX-level state-growth usage so a tracker reused - /// across transactions does not leak growth from the previous one. - #[test] - fn test_reset_clears_accumulated_usage() { - let mut tracker = StateGrowthTracker::new(MegaSpecId::MINI_REX, 100); - tracker.record_deposit_caller_creation(); - assert_eq!(tracker.tx_usage(), 1, "recorded growth should be reflected in tx_usage"); - - tracker.reset(); - assert_eq!(tracker.tx_usage(), 0, "reset must clear accumulated state growth"); - } -} diff --git a/crates/mega-evm/src/limit/storage_call_stipend.rs b/crates/mega-evm/src/limit/storage_call_stipend.rs deleted file mode 100644 index 93a99bbc7..000000000 --- a/crates/mega-evm/src/limit/storage_call_stipend.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Tracks the `STORAGE_CALL_STIPEND` granted to value-transferring `CALL` / `CALLCODE` -//! frames. Two spec-gated models share this tracker. -//! -//! REX5+ uses a separated allowance: `call_inputs.gas_limit` is not inflated, and the -//! five `storage_gas_ext` charging sites (CALL/CALLCODE new-account, CREATE/CREATE2, -//! SSTORE first-time-write, LOG, SELFDESTRUCT) drain `try_consume` before charging the -//! residual against EVM `Gas`. `additional_limit_ext::{sstore, log}` are not consumers — -//! they check non-gas dimensions only. -//! -//! REX4 uses the legacy inflation: `call_inputs.gas_limit` is inflated by -//! `STORAGE_CALL_STIPEND`, the per-frame compute budget is capped at the pre-inflation -//! limit, and unused stipend is burned on return by clamping `gas.remaining()`. Preserved -//! byte-for-byte for replay parity. -//! -//! Pre-REX4 specs do not grant a stipend; both models collapse to a zero-allowance no-op. -//! Synthetic system-contract interception results that short-circuit `frame_init` push a -//! zero-allowance entry for stack alignment. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use revm::{ - handler::FrameResult, - interpreter::{interpreter_action::FrameInit, CallScheme, FrameInput, Gas}, -}; - -use super::compute_gas; -use crate::{constants, MegaSpecId}; - -/// Tracks per-frame `STORAGE_CALL_STIPEND` grants. -/// -/// See the module-level doc for the dual-mode (REX5+ separated allowance vs REX4 -/// legacy inflation) design and its rationale. -#[derive(Debug, Clone)] -pub(crate) struct StorageCallStipendTracker { - /// Per-spec stipend grant amount. 0 for pre-REX4 (disabled). - stipend_amount: u64, - /// `true` for REX5+ (separated-allowance model); `false` for REX4 and pre-REX4 - /// (legacy inflation model, including the no-stipend case where - /// `stipend_amount == 0`). - rex5_enabled: bool, - /// Per-frame stipend state. Pushed in `before_frame_init` / `push_empty_frame`, - /// popped in `before_frame_return_result`. - stack: Vec, -} - -/// Per-frame stipend state. -/// -/// `remaining` is the REX5+ separated-allowance balance. `legacy_inflated` is `true` -/// iff this frame was granted a REX4 `gas.limit()` inflation and must burn unused -/// stipend on return; `false` for REX5+ grants, empty frames, and pre-REX4. -#[derive(Debug, Clone, Copy, Default)] -struct StipendFrame { - remaining: u64, - legacy_inflated: bool, -} - -impl StorageCallStipendTracker { - pub(crate) fn new(spec: MegaSpecId) -> Self { - Self { - stipend_amount: Self::stipend_for_spec(spec), - rex5_enabled: spec.is_enabled(MegaSpecId::REX5), - stack: Vec::new(), - } - } - - /// Returns the stipend amount for the given spec. Zero for pre-REX4. - fn stipend_for_spec(spec: MegaSpecId) -> u64 { - if spec.is_enabled(MegaSpecId::REX4) { - constants::rex4::STORAGE_CALL_STIPEND - } else { - 0 - } - } - - pub(crate) fn reset(&mut self) { - self.stack.clear(); - } - - /// Pushes a zero-allowance entry for an empty frame (synthetic system-contract - /// interception result or inspector early-return). Keeps the stack aligned with - /// the EVM frame stack so subsequent pops match. - pub(crate) fn push_empty_frame(&mut self) { - self.stack.push(StipendFrame::default()); - } - - /// Drains up to `amount` from the current frame's allowance and returns the - /// portion drained. The caller charges the residual via the original site's - /// gas-charging macro (`gas!` or `gas_or_fail!`). Returns 0 pre-REX5; REX4 covers - /// storage via `gas.limit()` inflation and does not draw from this allowance. - pub(crate) fn try_consume(&mut self, amount: u64) -> u64 { - if !self.rex5_enabled { - return 0; - } - let Some(frame) = self.stack.last_mut() else { - return 0; - }; - let drained = frame.remaining.min(amount); - frame.remaining -= drained; - drained - } - - /// Pushes a per-frame entry. REX5+ records the grant as an internal allowance. - /// REX4 inflates `call_inputs.gas_limit`, caps the per-frame compute budget, and - /// records the pre-inflation limit for the return-time burn clamp. - /// - /// Must be called **after** `compute_gas.before_frame_init()` so the compute frame - /// exists for the REX4 cap-tightening. - pub(crate) fn before_frame_init( - &mut self, - frame_init: &mut FrameInit, - compute_gas: &mut compute_gas::ComputeGasTracker, - ) { - if !self.detect_grant(frame_init) { - self.stack.push(StipendFrame::default()); - return; - } - - if self.rex5_enabled { - // REX5+ separated-allowance model: no gas_limit mutation, no compute cap. - self.stack - .push(StipendFrame { remaining: self.stipend_amount, legacy_inflated: false }); - return; - } - - // REX4 legacy inflation model. - let FrameInput::Call(call_inputs) = &mut frame_init.frame_input else { - // `detect_grant` only returns true for Call frames, so this branch is - // unreachable. Defend against future divergence. - self.stack.push(StipendFrame::default()); - return; - }; - let pre_inflation_limit = call_inputs.gas_limit; - call_inputs.gas_limit = call_inputs.gas_limit.saturating_add(self.stipend_amount); - compute_gas.cap_current_frame_limit(pre_inflation_limit); - // REX4 stores the full grant in `remaining` so `current_frame_stipend()` can - // surface it to `effective_remaining_for_rescue`. `try_consume` is a no-op on - // REX4, so the value stays static. - self.stack.push(StipendFrame { remaining: self.stipend_amount, legacy_inflated: true }); - } - - /// Pops the per-frame entry. REX4 also burns unused stipend by clamping - /// `gas.remaining()` to `gas.limit().saturating_sub(stipend_amount)` so the caller - /// never recovers more than the pre-stipend limit. Deriving the cap from - /// post-inflation `gas.limit()` matches the saturating-add at inflation time. - /// REX5 has nothing to burn (the allowance never entered `gas.limit()`). - /// - /// `LAST_FRAME` matches the other trackers' hook signature so the top-level - /// duplicate `last_frame_result` call can safely no-op on an empty stack. - pub(crate) fn before_frame_return_result( - &mut self, - result: &mut FrameResult, - ) { - assert!(LAST_FRAME || !self.stack.is_empty(), "frame stack is empty"); - let frame = self.stack.pop().unwrap_or_default(); - if self.rex5_enabled { - // REX5+: nothing to burn — `gas.limit()` never held stipend. - return; - } - if frame.legacy_inflated { - let gas = result.gas_mut(); - // Derive the burn cap from post-inflation `gas.limit()` so the saturating - // arithmetic mirrors the inflation site exactly. - let original_limit = gas.limit().saturating_sub(self.stipend_amount); - let burn = gas.remaining().saturating_sub(original_limit); - if burn > 0 { - let _ = gas.record_cost(burn); - } - } - } - - /// Current frame's stipend balance. REX5: remaining (un-drained) allowance. REX4: - /// the original grant amount (static; used by `effective_remaining_for_rescue` to - /// exclude the inflated portion from the rescued-gas refund). Pre-REX4: 0. - pub(crate) fn current_frame_stipend(&self) -> u64 { - self.stack.last().map(|frame| frame.remaining).unwrap_or(0) - } - - /// Portion of `gas.remaining()` to add to `rescued_gas` on a TX-level limit exceed. - /// REX5 returns `gas.remaining()` directly (allowance never entered `gas.limit()`). - /// REX4 excludes the current frame's stipend so system-granted gas is not refunded - /// to the sender. - pub(crate) fn effective_remaining_for_rescue(&self, gas: &Gas) -> u64 { - if self.rex5_enabled { - return gas.remaining(); - } - let stipend = self.current_frame_stipend(); - if stipend > 0 { - let original_limit = gas.limit().saturating_sub(stipend); - gas.remaining().min(original_limit) - } else { - gas.remaining() - } - } - - /// Returns `true` if the given `frame_init` qualifies for a stipend grant. - /// - /// The stipend is granted to value-transferring internal `CALL`/`CALLCODE` - /// frames (depth > 0). Top-level transaction frames, non-value-transfer - /// CALL/CALLCODE, DELEGATECALL/STATICCALL, and CREATE/CREATE2 do not qualify. - fn detect_grant(&self, frame_init: &FrameInit) -> bool { - if self.stipend_amount == 0 { - return false; - } - let FrameInput::Call(call_inputs) = &frame_init.frame_input else { - return false; - }; - let is_internal_call = frame_init.depth != 0; - let is_value_transfer = call_inputs.transfers_value(); - let is_call_or_callcode = - matches!(call_inputs.scheme, CallScheme::Call | CallScheme::CallCode); - is_internal_call && is_value_transfer && is_call_or_callcode - } -} diff --git a/crates/mega-evm/src/sandbox/execution.rs b/crates/mega-evm/src/sandbox/execution.rs deleted file mode 100644 index 2782bbf72..000000000 --- a/crates/mega-evm/src/sandbox/execution.rs +++ /dev/null @@ -1,1616 +0,0 @@ -//! Keyless deploy sandbox execution. -//! -//! Implements Nick's Method deterministic deployment via an isolated sandbox. See the -//! module-level `Spam Protection` section in `sandbox/mod.rs` for the invariants that -//! govern when each path is taken (normal completion / Rex5 preflight reject / Rex5 -//! residual-overflow reject / Rex5 sandbox-`validate()` reject). -//! -//! The Rex5 defense layers are implemented here as: `sandbox_runtime_limits` (upfront -//! cap), `sandbox_intrinsic_overflow_error` (preflight), and `reject_if_tx_limit_overflow` -//! (post-merge safety net). -//! -//! Rex5+ runs the sandbox transaction as an OP deposit-like transaction -//! (`gas_price = 0` plus `deposit.source_hash` set, via -//! `build_fee_free_sandbox_deposit_tx`). The deposit-style sandbox tx never debits -//! the inner signer for gas, never credits coinbase or any OP fee vault, and is -//! covered by the outer transaction's own fee model: `gas_limit_override` is -//! pre-debited from the outer `Gas` counter before the sandbox runs and -//! `refund_unused_sandbox_gas` returns the unused portion on exit, mirroring revm's -//! standard message-call accounting. The signer's only state change is the -//! `make_create_frame` nonce bump that serves as the replay barrier. -//! -//! A Rex5 sandbox-`validate()` rejection — the final Mega-side intrinsic / floor -//! gas check inside `MegaHandler::validate` — surfaces in two distinct ways: -//! op-revm's deposit `catch_error` converts tx-validation errors into -//! `Ok(Halt(FailedDeposit, gas_used = gas_limit))`; `process_sandbox_transact_result` -//! maps that back to `KeylessDeployError::InvalidTransaction` so the outer -//! keyless-deploy call surfaces as `Revert`, the sandbox state (including the -//! deposit-`catch_error` nonce bump) is dropped, and `apply_sandbox_post_accounting` -//! is never invoked. Pre-Rex5 specs run the sandbox as a non-deposit transaction: -//! sandbox `pre_execution` debits the signer at the signed gas price, and -//! validation errors propagate as standard `Err(InvalidTransaction)`. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{rc::Rc, vec::Vec}; - -use alloy_consensus::{Signed, Transaction as AlloyTransaction, TxLegacy}; -use alloy_evm::{Database as AlloyDatabase, Evm}; -use alloy_primitives::{Address, Bytes, Log, TxKind, U256}; -use alloy_sol_types::SolCall; -use mega_system_contracts::keyless_deploy::IKeylessDeploy; -use op_revm::{handler::IsTxError, L1BlockInfo}; -use revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - BlockEnv, Cfg, ContextTr, TxEnv, - }, - context_interface::Transaction, - handler::FrameResult, - interpreter::{CallOutcome, Gas, Host, InstructionResult, InterpreterResult}, - primitives::KECCAK_EMPTY, - state::{AccountInfo, EvmState}, - Database as RevmDatabase, -}; -use tracing::{error, warn}; - -use crate::{ - constants, inspect_account_code_hash, mark_frame_result_as_exceeding_limit, AdditionalLimit, - EvmTxRuntimeLimits, ExternalEnvTypes, JournalInspectTr, LimitCheck, LimitUsage, MegaContext, - MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, TxRuntimeLimit, VolatileDataAccess, - SANDBOX_TX_SOURCE_HASH, -}; - -use super::{ - state_merge::apply_sandbox_state, - tx::{calculate_keyless_deploy_address, decode_keyless_tx, recover_signer}, -}; - -use super::{ - error::{encode_error_result, KeylessDeployError}, - state::SandboxDb, -}; - -/// Executes a keyless deploy call and returns the frame result. -/// -/// Implements Nick's Method contract deployment: -/// -/// 1. Validates the call (no ether transfer). -/// 2. Decodes the pre-EIP-155 transaction from calldata. -/// 3. Rex5+: pre-checks `keyless_tx.input().len() <= cfg().max_initcode_size()` — op-revm's deposit -/// path bypasses revm's `validate_env`, so the sandbox enforces the configured initcode size -/// limit itself. -/// 4. Validates the gas limit override against the transaction's gas limit. -/// 5. Recovers the signer and calculates the deploy address. -/// 6. Rex5+: pre-charges `new_account_storage_gas(deploy_signer)` against the outer Gas counter -/// when the parent-visible signer is unmaterialized (alongside `KEYLESS_DEPLOY_OVERHEAD_GAS`, -/// retained on every sandbox outcome — see `charge_caller_materialization_pre_sandbox`), then -/// preflights known sandbox intrinsic usage against the parent's remaining resource envelope and -/// reverts with `ParentBudgetExceeded` if it would not fit. -/// 7. Executes contract creation in an isolated sandbox environment. Rex5+ runs the sandbox tx as -/// an OP deposit-like, fee-free transaction with `gas_limit_override` pre-debited from the outer -/// Gas counter. -/// 8. On sandbox completion, refunds the unused portion of the reservation to the outer Gas counter -/// and either merges state (normal path) or rejects without merging (Rex5 overflow safety net), -/// via `apply_sandbox_post_accounting`. -/// -/// Must only be called at `depth == 0` (enforced by `evm/execution.rs`); a wrapping contract -/// must not be able to intercept and revert the charge. See the module-level `Spam Protection` -/// section for the full payment invariants across the Rex5 defense layers (preflight, -/// upfront cap, post-merge safety net, sandbox-`validate()` rejection). -pub fn execute_keyless_deploy_call( - ctx: &mut MegaContext, - call_inputs: &revm::interpreter::CallInputs, - tx_bytes: &Bytes, - gas_limit_override: U256, -) -> FrameResult { - let mut gas = Gas::new(call_inputs.gas_limit); - let return_memory_offset = call_inputs.return_memory_offset.clone(); - - // Frame-result constructors. Using macros (rather than closures) so each call site - // can move `gas` / `return_memory_offset` without borrow-checker conflicts. - // `make_halt!` delegates to the module-level `oog_frame_result` so the OOG shape is - // shared with `reject_if_tx_limit_overflow`. - macro_rules! make_halt { - () => { - oog_frame_result(gas.limit(), &return_memory_offset) - }; - } - - macro_rules! make_error { - ($error:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new(InstructionResult::Revert, encode_error_result($error), gas), - return_memory_offset, - )) - }; - } - - macro_rules! make_success { - ($gas_used:expr, $deployed_address:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - IKeylessDeploy::keylessDeployCall::abi_encode_returns( - &IKeylessDeploy::keylessDeployReturn { - gasUsed: $gas_used, - deployedAddress: $deployed_address, - errorData: Bytes::new(), - }, - ) - .into(), - gas, - ), - return_memory_offset, - )) - }; - } - - // Builds a success-style frame result with the error encoded in `errorData`. Used for - // in-sandbox failures (paired with `apply_sandbox_state` so the consumed replay barrier - // — the signer nonce bump from `make_create_frame` — is merged into the parent). - macro_rules! make_execution_failure { - ($gas_used:expr, $error:expr) => { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, // Success, not Revert - IKeylessDeploy::keylessDeployCall::abi_encode_returns( - &IKeylessDeploy::keylessDeployReturn { - gasUsed: $gas_used, - deployedAddress: Address::ZERO, - errorData: encode_error_result($error).to_vec().into(), - }, - ) - .into(), - gas, - ), - return_memory_offset, - )) - }; - } - - // Step 1: charge the fixed dispatch overhead (100K covers RLP decoding, sig recovery, - // state filtering). Rex3+ also records it as compute gas. - let cost = constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS; - let has_sufficient_gas = gas.record_cost(cost); - if !has_sufficient_gas { - return make_halt!(); - } - if ctx.spec.is_enabled(MegaSpecId::REX3) { - let mut additional_limit = ctx.additional_limit.borrow_mut(); - if !additional_limit.record_compute_gas(cost) { - let crate::LimitCheck::ExceedsLimit { limit, used, frame_local, .. } = - additional_limit.compute_gas.check_limit() - else { - unreachable!() - }; - return if frame_local { - // Frame-local: revert; gas returns to caller. - make_error!(KeylessDeployError::InsufficientComputeGas { limit, used }) - } else { - // TX-level: halt with OOG, marked as exceeding. - // - // REX6+: rescue the outer `Gas`'s unspent portion (after the - // `KEYLESS_DEPLOY_OVERHEAD_GAS` charge) so it is refunded to the sender, - // matching the per-opcode `compute_gas!` path's TX-level-exceed rescue. - // The eventual `make_halt!` spends `gas.limit()` at the frame level; - // `last_frame_result` then erases `rescued_gas` from the final spend, so - // the receipt's `gas_used` excludes the rescued amount. Pre-REX6 specs - // leave the un-rescued full-spend in place for replay parity. - if ctx.spec.is_enabled(MegaSpecId::REX6) { - additional_limit.try_rescue_gas(&gas); - } - let mut result = make_halt!(); - mark_frame_result_as_exceeding_limit( - &mut result, - crate::AdditionalLimit::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); - result - }; - } - } - - // Step 2: keyless deploys are fee-free. - if !call_inputs.value.get().is_zero() { - return make_error!(KeylessDeployError::NoEtherTransfer); - } - - // Step 3: decode the keyless transaction (Nick's Method requires nonce = 0). - let keyless_tx = match decode_keyless_tx(tx_bytes, ctx.spec) { - Ok(tx) => tx, - Err(e) => return make_error!(e), - }; - if keyless_tx.nonce() != 0 { - return make_error!(KeylessDeployError::NonZeroTxNonce { tx_nonce: keyless_tx.nonce() }); - } - - // Rex5+: enforce the configured init code size limit. Pre-Rex5 specs run the sandbox - // through op-revm's non-deposit path, where revm's `validate_env` enforces it for us. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - let max = ctx.cfg().max_initcode_size(); - let size = keyless_tx.input().len(); - if size > max { - return make_error!(KeylessDeployError::InitCodeTooLarge { - size: size as u64, - max: max as u64, - }); - } - } - - // Step 4: validate `gasLimitOverride` covers the keyless tx's own gas limit. The - // Rex5+ cap is deferred to step 4b below so it observes the materialization charge. - let tx_gas_limit = keyless_tx.gas_limit(); - let mut gas_limit_override_u64: u64 = gas_limit_override.try_into().unwrap_or(u64::MAX); - if gas_limit_override_u64 < tx_gas_limit { - return make_error!(KeylessDeployError::GasLimitTooLow { - tx_gas_limit, - provided_gas_limit: gas_limit_override_u64, - }); - } - - // Step 5: recover the signer and restrict keyless deploys to signer nonce ≤ 1. - // Allowing 1 keeps deploys possible when the signer previously attempted the raw - // keyless tx and failed under MegaETH's gas regime. - let deploy_signer = match recover_signer(&keyless_tx) { - Ok(addr) => addr, - Err(e) => return make_error!(e), - }; - let deploy_address = calculate_keyless_deploy_address(deploy_signer); - - // Rex5+ reads the deploy signer's parent-state account info once via a cold-marked - // `inspect_account`, then drives the upcoming nonce check, EIP-3607 enforcement, and - // materialization charge from that single source. The helper itself gates `load_code` - // on `cfg.disable_eip3607` to preserve the canonical revm - // `validate_account_nonce_and_code` no-`code_by_hash` short-circuit. Pre-Rex5 keeps - // the raw-DB `get_account_nonce` path unchanged to preserve stable-spec semantics - // (no journal cache write for the signer). - let rex5_signer_info = if ctx.spec.is_enabled(MegaSpecId::REX5) { - match inspect_signer_parent_state(ctx, deploy_signer) { - Ok(info) => Some(info), - Err(e) => return make_error!(e), - } - } else { - None - }; - - let signer_nonce = if let Some(info) = &rex5_signer_info { - info.nonce - } else { - match get_account_nonce(ctx, deploy_signer) { - Ok(nonce) => nonce, - Err(e) => return make_error!(e), - } - }; - if signer_nonce > 1 { - return make_error!(KeylessDeployError::SignerNonceTooHigh { signer_nonce }); - } - - if let Some(signer_info) = &rex5_signer_info { - // Rex5+: re-enforce the EIP-3607 caller-with-code check that the deposit-style - // sandbox would otherwise bypass via op-revm's - // `validate_against_state_and_deduct_caller`. - if let Err(e) = validate_signer_code(ctx, signer_info) { - return make_error!(e); - } - - // Rex5+: pre-charge deploy-signer materialization gas (and record the state-growth - // event) before the sandbox is constructed, alongside `KEYLESS_DEPLOY_OVERHEAD_GAS`. - // Upfront timing makes the charge symmetric across all sandbox outcomes (success, - // in-sandbox failure, sandbox-validate reject) and prevents the relayer from sizing - // the outer budget to exclude materialization. - match charge_caller_materialization_pre_sandbox( - ctx, - &mut gas, - deploy_signer, - signer_info, - &return_memory_offset, - ) { - Err(e) => return make_error!(e), - Ok(Some(halt)) => return halt, - Ok(None) => {} - } - } - - // Step 4b: Rex5+ cap of `gas_limit_override` to the outer's remaining gas. Runs after - // materialization has been debited so the reservation in step 8b only covers the - // sandbox envelope itself. - // - // After the cap, re-enforce the signer's "must execute with at least `tx_gas_limit`" - // guarantee. The relayer can shrink the outer envelope so that `gas.remaining()` - // drops below the keyless `tx_gas_limit`, in which case the cap brings the override - // below the signed minimum. Rejecting here with the same `GasLimitTooLow` shape - // surfaces the failure cleanly instead of letting the sandbox OOG silently. The - // pre-cap check above (Step 4) is retained so a relayer passing - // `override < tx_gas_limit` outright still fails before the signer-recovery / - // materialization work. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - gas_limit_override_u64 = gas_limit_override_u64.min(gas.remaining()); - if gas_limit_override_u64 < tx_gas_limit { - return make_error!(KeylessDeployError::GasLimitTooLow { - tx_gas_limit, - provided_gas_limit: gas_limit_override_u64, - }); - } - } - - // Step 6: build the sandbox transaction (nonce forced to 0, raw keyless RLP carried - // in `enveloped_tx`). Rex5+ runs the sandbox tx as an OP deposit-like transaction - // (gas_price=0, source_hash set) so caller balance is never debited for gas; pre-Rex5 - // keeps the original signed gas price. - let sandbox_tx = if ctx.spec.is_enabled(MegaSpecId::REX5) { - build_fee_free_sandbox_deposit_tx( - deploy_signer, - &keyless_tx, - tx_bytes, - gas_limit_override_u64, - ) - } else { - let tx = TxEnv { - caller: deploy_signer, - kind: TxKind::Create, - data: keyless_tx.input().clone(), - value: keyless_tx.value(), - gas_limit: gas_limit_override_u64, - gas_price: keyless_tx.effective_gas_price(None), - nonce: 0, - ..Default::default() - }; - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(tx_bytes.clone()); - mega_tx - }; - - // Step 7: check the deterministic deploy address isn't already occupied. - // - // REX6 reads occupancy through the journaled, cold `inspect_account_code_hash` so the deploy - // address lands in the returned `EvmState` / witness; pre-REX6 keeps the raw `database.basic` - // read that bypasses the journal. The gate is load-bearing: the pre-REX5 legacy merge - // (`apply_sandbox_state_legacy`, `merge_status = false`) does not carry `AccountStatus` through - // an already-`Occupied` journal entry, so journaling this read there would drop a deployed - // address's `Created|Touched` status and let `commit()` discard it — silently losing successful - // pre-REX5 deploys (guarded by - // `test_keyless_deploy_pre_rex6_success_still_commits_deployed_code`). Only the witness - // changes, not the `ContractAlreadyExists` decision — the interceptor fires only at - // `depth == 0`, so while access-list warming may already have journaled `deploy_address` - // (read-only, same `code_hash` as the database), no reachable path can have changed its - // `code_hash` before this check (writing EIP-7702 delegation code to it would require the - // deploy address's own signing key, which does not exist for a CREATE-derived address). - // - // `inspect_account_code_hash` (not `inspect_account(.., false)`) because the occupancy decision - // needs only `code_hash`: `inspect_account`'s already-resident branch force-loads `info.code` - // via `code_by_hash` regardless of `load_code`, so if the outer tx's access list pre-warmed an - // occupied `deploy_address`, that read would demand the address's bytecode in a stateless - // witness carrying only its account proof and turn the expected revert into a spurious DB - // error. - if ctx.spec.is_enabled(MegaSpecId::REX6) { - let deploy_code_hash = inspect_account_code_hash(ctx.journal_mut(), deploy_address) - .map_err(|e| { - error!( - error = %e, - deploy_address = ?deploy_address, - "keyless deploy deploy-address state read failed", - ); - KeylessDeployError::InternalError - }); - match deploy_code_hash { - Ok(code_hash) if code_hash != KECCAK_EMPTY => { - return make_error!(KeylessDeployError::ContractAlreadyExists); - } - Err(e) => return make_error!(e), - _ => {} - } - } else { - let deploy_account = ctx.journal_mut().database.basic(deploy_address).map_err(|e| { - error!( - error = %e, - deploy_address = ?deploy_address, - "keyless deploy deploy-address state read failed", - ); - KeylessDeployError::InternalError - }); - match deploy_account { - Ok(Some(info)) if info.code_hash != KECCAK_EMPTY => { - return make_error!(KeylessDeployError::ContractAlreadyExists); - } - Err(e) => return make_error!(e), - _ => {} - } - } - - // Step 8: Rex5+ preflight. Short-circuits before sandbox setup when the sandbox's - // pre-frame intrinsic alone would exceed the parent's envelope. - let sandbox_tx_limits = - ctx.spec.is_enabled(MegaSpecId::REX5).then(|| sandbox_runtime_limits(ctx)); - if let Some(error) = sandbox_intrinsic_overflow_error(ctx.spec, &sandbox_tx, sandbox_tx_limits) - { - return make_error!(error); - } - - // Step 8b: Rex5+ pre-debit the sandbox's gas reservation from the outer gas counter, - // mirroring revm's standard message-call shape (pre-debit on entry, refund unused on - // exit). The unconditional success follows from step 4b's - // `gas_limit_override.min(gas.remaining())` cap — there is no intervening gas - // movement between the cap and this debit. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - let ok = gas.record_cost(gas_limit_override_u64); - debug_assert!( - ok, - "Rex5+ sandbox pre-debit must succeed: gas_limit_override is capped to gas.remaining()", - ); - } - - // Step 9: Execute sandbox and apply state changes. - match execute_keyless_deploy_sandbox(ctx, sandbox_tx, sandbox_tx_limits) { - SandboxOutcome::Completed { state, completion, limit_usage, volatile_accesses } => { - let gas_used = completion.gas_used(); - - if ctx.spec.is_enabled(MegaSpecId::REX5) { - if let Some(halt) = apply_sandbox_post_accounting( - ctx, - &mut gas, - limit_usage, - volatile_accesses, - gas_limit_override_u64, - gas_used, - &return_memory_offset, - ) { - return halt; - } - } - - if let Err(e) = apply_sandbox_state(ctx, state, deploy_signer) { - return make_error!(e); - } - - // Dispatch ABI return shape. `Deployed` and `EmptyCode` both forward - // constructor logs into the parent receipt (run-to-completion EVM side - // effect); `ExecutionFailed` (Revert / Halt) does not, because revm's - // own frame accounting already rolled the failed frame's logs back. - match completion { - SandboxCompletion::Deployed { gas_used, deploy_address: deployed, logs } => { - if deployed != deploy_address { - return make_error!(KeylessDeployError::AddressMismatch); - } - for log in logs { - ctx.log(log); - } - make_success!(gas_used, deployed) - } - SandboxCompletion::EmptyCode { gas_used, logs } => { - for log in logs { - ctx.log(log); - } - make_execution_failure!( - gas_used, - KeylessDeployError::EmptyCodeDeployed { gas_used } - ) - } - SandboxCompletion::ExecutionFailed { gas_used, error } => { - // Success-style outer return so the merged sandbox state (signer - // nonce bump from `make_create_frame`, plus any committed sandbox - // writes) persists; outer caller sees the failure reason in - // `errorData`. - make_execution_failure!(gas_used, error) - } - } - } - SandboxOutcome::Rejected(e) => { - // Sandbox bailed before producing a frame — typically a validate-reject - // (`FailedDeposit` → `InvalidTransaction`) or an internal error. Refund - // the full reservation; the materialization charge already applied - // upfront is intentionally retained, mirroring the upfront - // `KEYLESS_DEPLOY_OVERHEAD_GAS` charge. - if ctx.spec.is_enabled(MegaSpecId::REX5) { - gas.erase_cost(gas_limit_override_u64); - } - make_error!(e) - } - } -} - -/// Builds a sandbox transaction that runs as an OP deposit-like transaction. -/// -/// Rex5+ only: `source_hash` makes op-revm treat the tx as a deposit (skips L1/operator -/// fee, `validate_env`, balance / nonce check, and `reward_beneficiary` distribution); -/// `gas_price = 0` keeps the deposit-path caller balance escrow at zero so the inner -/// signer is never charged for sandbox gas. `deposit.mint` is explicitly `None` to -/// guarantee no ETH is minted to the signer. -fn build_fee_free_sandbox_deposit_tx( - deploy_signer: Address, - keyless_tx: &Signed, - raw_tx_bytes: &Bytes, - gas_limit: u64, -) -> MegaTransaction { - let tx = TxEnv { - caller: deploy_signer, - kind: TxKind::Create, - data: keyless_tx.input().clone(), - value: keyless_tx.value(), - gas_limit, - gas_price: 0, - nonce: 0, - ..Default::default() - }; - let mut mega_tx = MegaTransaction::new(tx); - mega_tx.enveloped_tx = Some(raw_tx_bytes.clone()); - mega_tx.deposit.source_hash = SANDBOX_TX_SOURCE_HASH; - mega_tx.deposit.mint = None; - mega_tx -} - -/// Executes the contract creation in a sandbox environment. -/// -/// Uses a type-erased `SandboxDb` to prevent infinite type instantiation. -/// -/// # Arguments -/// -/// * `ctx` - The parent context to execute in -/// * `sandbox_tx` - The transaction to execute, with `enveloped_tx` set to the original raw keyless -/// deploy transaction bytes -pub(crate) fn execute_keyless_deploy_sandbox( - ctx: &mut MegaContext, - sandbox_tx: MegaTransaction, - sandbox_tx_limits: Option, -) -> SandboxOutcome { - let deploy_signer = sandbox_tx.caller(); - let gas_limit = sandbox_tx.gas_limit(); - let gas_price = sandbox_tx.gas_price(); - let value = sandbox_tx.value(); - - // Extract values we need BEFORE borrowing the journal - let mega_spec = ctx.mega_spec(); - let block = ctx.block().clone(); - let chain = ctx.chain().clone(); - - // REX4+: Clone Rc references to parent's external envs before `journal_mut()` mutably - // borrows `ctx`, after which its fields are no longer accessible. - let shared_external_envs = mega_spec - .is_enabled(MegaSpecId::REX4) - .then(|| (Rc::clone(&ctx.salt_env), Rc::clone(&ctx.oracle_env))); - - // Deliberately do not merge `DynamicGasCost.accessed_bucket_ids` back into the - // parent. Sandbox and parent share the same immutable-in-block `SaltEnv`, while - // the sandbox's dynamic-gas cache is intentionally local to that context. - // Revisit if `SaltEnv` becomes block-mutable or bucket ids become a primary - // parallel-EVM conflict signal. - let journal = ctx.journal_mut(); - - // Create type-erased sandbox database with split borrows: - // - Immutable reference to journal state (for cached accounts) - // - Mutable reference to underlying database (for cache misses) - // Override the signer's nonce to 0 for keyless deploy (Nick's Method requires nonce=0) - let mut sandbox_db = SandboxDb::new(&journal.inner.state, &mut journal.database) - .with_nonce_override(deploy_signer); - - // Check signer balance - let signer_account = match sandbox_db.basic(deploy_signer) { - Ok(info) => info.unwrap_or_default(), - Err(e) => { - error!( - error = %e, - deploy_signer = ?deploy_signer, - "keyless deploy signer balance read failed", - ); - return SandboxOutcome::Rejected(KeylessDeployError::InternalError); - } - }; - - // Ensure signer can cover the transfer (and pre-Rex5 also the gas escrow). - // Rex5+ runs the sandbox as a fee-free deposit-like tx (gas_price=0), so the only - // remaining requirement is enough balance for `value`. Pre-Rex5 keeps the - // `gas_cost + value` check, matching its non-deposit sandbox path. - let total_cost = if mega_spec.is_enabled(MegaSpecId::REX5) { - value - } else { - let gas_cost = U256::from(gas_limit) * U256::from(gas_price); - match gas_cost.checked_add(value) { - Some(total) => total, - None => return SandboxOutcome::Rejected(KeylessDeployError::InsufficientBalance), - } - }; - if signer_account.balance < total_cost { - return SandboxOutcome::Rejected(KeylessDeployError::InsufficientBalance); - } - - // Execute sandbox - using type-erased SandboxDb prevents infinite type instantiation. - // The two branches differ only in which MegaContext constructor to use: REX4+ shares - // the parent's salt and oracle envs, while pre-REX4 creates an EmptyExternalEnv for - // backward compatibility. Everything after context construction is identical and is - // factored into `run_sandbox_ctx`. - if let Some((salt_env, oracle_env)) = shared_external_envs { - let sandbox_ctx = MegaContext::<_, ExtEnvs>::new_with_shared_ext_envs( - sandbox_db, mega_spec, salt_env, oracle_env, - ); - run_sandbox_ctx(sandbox_ctx, sandbox_tx, sandbox_tx_limits, block, chain) - } else { - let sandbox_ctx = MegaContext::new(sandbox_db, mega_spec); - run_sandbox_ctx(sandbox_ctx, sandbox_tx, sandbox_tx_limits, block, chain) - } -} - -/// Applies the shared sandbox-context configuration, runs the sandbox tx, and returns the -/// processed outcome. Factored out of `execute_keyless_deploy_sandbox` so the REX4+ and -/// pre-REX4 branches only differ in the `MegaContext` constructor they call. -fn run_sandbox_ctx( - sandbox_ctx: MegaContext, - sandbox_tx: MegaTransaction, - sandbox_tx_limits: Option, - block: BlockEnv, - chain: L1BlockInfo, -) -> SandboxOutcome { - let sandbox_ctx = match sandbox_tx_limits { - Some(limits) => sandbox_ctx.with_tx_runtime_limits(limits), - None => sandbox_ctx, - }; - let sandbox_ctx = sandbox_ctx.with_block(block).with_chain(chain).with_inside_sandbox(true); - let is_rex5_enabled = sandbox_ctx.mega_spec().is_enabled(MegaSpecId::REX5); - let is_rex6_enabled = sandbox_ctx.mega_spec().is_enabled(MegaSpecId::REX6); - let mut sandbox_evm = MegaEvm::new(sandbox_ctx); - let result = sandbox_evm.transact_raw(sandbox_tx); - let limit_usage = sandbox_evm.ctx.additional_limit.borrow().get_usage(); - let volatile_accesses = - sandbox_evm.ctx.volatile_data_tracker.borrow().get_volatile_data_accessed(); - process_sandbox_transact_result( - result, - limit_usage, - volatile_accesses, - is_rex5_enabled, - is_rex6_enabled, - ) -} - -/// Outcome of sandbox execution. -/// -/// Splits the two questions the caller actually has to answer separately: -/// -/// - **`Completed` vs `Rejected`** — did the sandbox EVM run far enough to produce merge-able side -/// effects (state / resource usage / volatile-access footprint / logs)? `Rejected` means the -/// sandbox bailed before producing a frame (validate-reject or internal error); nothing should be -/// applied to the parent context. -/// - **`SandboxCompletion::{Deployed, EmptyCode, ExecutionFailed}`** — when the sandbox did -/// complete, what wire shape should the outer caller report? -/// -/// Logs naturally live on the completion variants where the EVM ran to a -/// non-reverted exit (`Deployed` and `EmptyCode`). `ExecutionFailed` covers -/// Revert / Halt — revm's own frame accounting already rolled those logs back, -/// so there is nothing to forward. -#[derive(Debug)] -pub enum SandboxOutcome { - /// Sandbox EVM ran to a frame exit (success, empty-code success, revert, or - /// halt). State, resource usage, and volatile-access footprint are - /// merge-able into the parent context. - Completed { - /// Sandbox state to merge into the parent context. - state: EvmState, - /// Wire-shape dispatch for what the outer caller should report. - completion: SandboxCompletion, - /// Resource usage from the sandbox's additional limit trackers. - limit_usage: LimitUsage, - /// Volatile-access footprint to merge into the parent after sandbox return. - volatile_accesses: VolatileDataAccess, - }, - /// Sandbox bailed before producing a frame (validate-reject `InvalidTransaction` - /// or `InternalError`). No state, resource usage, or volatile-access footprint - /// applies — the outer caller must refund the full pre-debited reservation. - Rejected(KeylessDeployError), -} - -/// Wire-shape dispatch for a completed sandbox execution. -/// -/// `Deployed` and `EmptyCode` both surface as success-shape outer returns: the -/// outer caller forwards their logs into the parent receipt before encoding the -/// ABI response. `EmptyCodeDeployed` is an ABI-layer "deploy did not stick" -/// signal — it is *not* an EVM execution failure. Pre-REX5 collapses -/// `EmptyCode` into `ExecutionFailed { error: EmptyCodeDeployed }` so logs are -/// dropped, preserving the frozen replay behavior. -/// -/// `ExecutionFailed` covers Revert / Halt. revm rolled the frame's logs back -/// inside the sandbox; there is nothing to forward to the parent. -#[derive(Debug)] -pub enum SandboxCompletion { - /// Inner CREATE succeeded with non-empty runtime bytecode. - Deployed { - /// Gas consumed by the sandbox EVM execution. - gas_used: u64, - /// Address at which the contract was deployed. - deploy_address: Address, - /// Logs emitted by the constructor; forwarded into the parent receipt. - logs: Vec, - }, - /// Inner CREATE succeeded but returned empty runtime bytecode. - /// - /// REX5+ only. Pre-REX5 routes empty-code through `ExecutionFailed` with - /// `EmptyCodeDeployed` so logs are dropped, preserving the frozen replay - /// behavior. - EmptyCode { - /// Gas consumed by the sandbox EVM execution. - gas_used: u64, - /// Logs emitted by the constructor; forwarded into the parent receipt - /// per the keyless-deploy spec's "merged state includes ... logs when - /// applicable" rule. - logs: Vec, - }, - /// Sandbox EVM execution did not result in a successful deploy reachable - /// by the parent. - /// - /// Covers two cases that share an ABI wire shape but have different - /// underlying reasons for not forwarding logs: - /// - `ExecutionResult::Revert` and `ExecutionResult::Halt` — revm already rolled the failed - /// frame's logs back inside the sandbox; nothing exists to forward. - /// - Pre-REX5 `EmptyCodeDeployed` — the constructor ran successfully and emitted logs, but - /// pre-REX5 deliberately drops them at this layer for replay parity. REX5+ uses - /// [`SandboxCompletion::EmptyCode`] to forward them instead. - ExecutionFailed { - /// Gas consumed by the sandbox EVM execution before the failure. - gas_used: u64, - /// ABI-encoded failure reason. - error: KeylessDeployError, - }, -} - -impl SandboxCompletion { - /// Returns the gas consumed by the sandbox EVM. Used by the outer caller to - /// compute the unused reservation to refund. - pub(crate) fn gas_used(&self) -> u64 { - match self { - Self::Deployed { gas_used, .. } | - Self::EmptyCode { gas_used, .. } | - Self::ExecutionFailed { gas_used, .. } => *gas_used, - } - } -} - -/// Processes the result of sandbox EVM execution into a [`SandboxOutcome`]. -/// -/// Handles all execution result variants (success, revert, halt) and transact errors. -/// -/// `transact_raw` errors are split into two `KeylessDeployError` variants by selector -/// so relayer-side decoders can tell them apart: -/// - `InvalidTransaction` when `IsTxError::is_tx_error()` returns `true`. -/// - `InternalError` for everything else (DB I/O, header validation, `EVMError::Custom`). -/// -/// `is_rex5_enabled` gates the empty-code branch: REX5+ produces -/// [`SandboxCompletion::EmptyCode`] (which forwards the constructor's emitted logs into -/// the parent receipt per the keyless-deploy spec), pre-REX5 collapses to -/// [`SandboxCompletion::ExecutionFailed`] with `EmptyCodeDeployed` so logs are dropped -/// for replay parity. -/// -/// `is_rex6_enabled` enables the EIP-6780 SELFDESTRUCT check: when revm reports -/// `Success { Output::Create(bytecode, addr) }` but the sandbox-state account at `addr` has -/// `is_selfdestructed() == true` (same-tx create + SELFDESTRUCT), `apply_sandbox_state`'s -/// `apply_sandbox_created_selfdestruct` will zero balance/storage and leave no code at the -/// merged address — so reporting `Deployed { addr }` would surface a non-zero -/// `deployedAddress` for an address that has no on-chain code after merge. REX6 collapses -/// this case onto the same empty-code branch as `bytecode.is_empty()` (REX6 implies REX5, -/// so logs forward via `SandboxCompletion::EmptyCode`); the outer caller returns -/// `EmptyCodeDeployed` with `deployedAddress = 0x0`. Pre-REX6 specs preserve the original -/// surface (`Deployed { addr }` returned for create+SELFDESTRUCT) for replay parity. -fn process_sandbox_transact_result( - result: Result, E>, - limit_usage: LimitUsage, - volatile_accesses: VolatileDataAccess, - is_rex5_enabled: bool, - is_rex6_enabled: bool, -) -> SandboxOutcome { - let completed = |state, completion| SandboxOutcome::Completed { - state, - completion, - limit_usage, - volatile_accesses, - }; - - match result { - Ok(ResultAndState { result: exec_result, state: sandbox_state }) => match exec_result { - ExecutionResult::Success { gas_used, output, logs, .. } => { - let revm::context::result::Output::Create(bytecode, Some(created_addr)) = output - else { - // Contract creation didn't return an address — should never happen - // (the sandbox tx always asks for `TxKind::Create`), but we return - // a Rejected outcome instead of panicking to avoid crashing the node. - return SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated); - }; - // REX6: also treat same-tx create + SELFDESTRUCT as empty-code. revm reports - // `Success` with the constructor's returned bytecode, but - // `apply_sandbox_created_selfdestruct` zeroes the account on merge — so the - // parent-visible code at `created_addr` is empty. Folding into the same arm - // as `bytecode.is_empty()` produces a consistent `EmptyCodeDeployed` outcome - // (logs forwarded under REX5+). - let selfdestructed = is_rex6_enabled && - sandbox_state - .get(&created_addr) - .is_some_and(|account| account.is_selfdestructed()); - if bytecode.is_empty() || selfdestructed { - // REX5+: surface as `EmptyCode` so the outer caller forwards the - // constructor's logs into the parent receipt before returning - // success-style `EmptyCodeDeployed` errorData. Pre-REX5 collapses - // back to `ExecutionFailed { EmptyCodeDeployed }` so logs are - // dropped, preserving the frozen replay behavior. - if is_rex5_enabled { - return completed( - sandbox_state, - SandboxCompletion::EmptyCode { gas_used, logs }, - ); - } - return completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::EmptyCodeDeployed { gas_used }, - }, - ); - } - completed( - sandbox_state, - SandboxCompletion::Deployed { gas_used, deploy_address: created_addr, logs }, - ) - } - ExecutionResult::Revert { gas_used, output } => completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::ExecutionReverted { gas_used, output }, - }, - ), - ExecutionResult::Halt { gas_used, reason } => { - // `FailedDeposit` on this path means op-revm's deposit `catch_error` wrapped a - // sandbox tx-validation failure into a synthetic halt. Runtime halts under the - // deposit-style sandbox tx are intercepted in `MegaHandler::execution_result` - // and surface here with their real halt reason instead, so they fall through to - // the normal `ExecutionHalted` failure branch and consume the Nick's-Method - // replay barrier as expected. Validation rejects must NOT consume the barrier, - // so we drop the discarded sandbox state and surface as Rejected. - if matches!(reason, MegaHaltReason::Base(op_revm::OpHaltReason::FailedDeposit)) { - warn!(gas_used, "keyless deploy sandbox failed deposit (validation-reject)",); - return SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction); - } - // The halt `reason` is dropped on the ABI wire (the Solidity error - // carries only `gasUsed`) and `decode_error_result` synthesizes a - // placeholder on the way back, so node-side `tracing` is the only - // place the real cause is observable. - warn!( - reason = ?reason, - gas_used, - "keyless deploy sandbox halted", - ); - completed( - sandbox_state, - SandboxCompletion::ExecutionFailed { - gas_used, - error: KeylessDeployError::ExecutionHalted { gas_used, reason }, - }, - ) - } - }, - // Split tx-validation rejections (selector `InvalidTransaction`) from genuine - // internal failures (selector `InternalError`) so relayer-side decoders can tell - // them apart. Both are selector-only on the wire — see `encode_error_result`. - Err(e) if e.is_tx_error() => { - warn!( - error = %e, - "keyless deploy sandbox transaction rejected during validation", - ); - SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction) - } - Err(e) => { - error!( - error = %e, - "keyless deploy sandbox failed with internal error", - ); - SandboxOutcome::Rejected(KeylessDeployError::InternalError) - } - } -} - -/// Rex5+ post-sandbox accounting. Order is load-bearing: -/// (a) merge multidim usage — always; survives any later halt -/// (b) merge volatile bitmap — always; survives any later halt -/// (c) refund unused sandbox gas — always; pure `erase_cost`, never halts -/// (d) reject if tx-level overflow — may halt with exceeding mark -/// -/// (a) and (b) run before the halt-deciding helper so the parent transaction's -/// reported footprint reflects what the sandbox actually accessed even on halt -/// paths. The caller invokes `apply_sandbox_state` only after this returns -/// `None`, following the standard "halted transactions commit only -/// pre-execution state" convention. -/// -/// `reservation` is the amount pre-debited from the outer `gas` before the -/// sandbox ran (step 8b in `execute_keyless_deploy_call`); `sandbox_gas_used` is -/// the amount the sandbox actually consumed (read from -/// [`SandboxCompletion::gas_used`]). Their difference is the unused reservation -/// that must be returned to the outer frame — mirroring revm's standard CALL -/// semantics. -/// -/// Caller-side spec gating keeps this path Rex5-only. -fn apply_sandbox_post_accounting( - ctx: &MegaContext, - gas: &mut Gas, - limit_usage: LimitUsage, - volatile_accesses: VolatileDataAccess, - reservation: u64, - sandbox_gas_used: u64, - return_memory_offset: &core::ops::Range, -) -> Option { - merge_sandbox_limit_usage(ctx, limit_usage); - ctx.volatile_data_tracker.borrow_mut().merge_accesses_from_bitmap(volatile_accesses); - refund_unused_sandbox_gas(gas, reservation, sandbox_gas_used); - reject_if_tx_limit_overflow(ctx, gas, return_memory_offset) -} - -/// If the deploy signer is unmaterialized in the parent journal-visible state, -/// pre-charges `new_account_storage_gas(deploy_signer)` against the outer Gas -/// counter and records a deposit-caller state-growth event. Mirrors the upfront -/// `KEYLESS_DEPLOY_OVERHEAD_GAS` charge in step 1: paid before the sandbox runs, -/// retained even when the sandbox is never constructed (e.g., sandbox-validate -/// reject), so the relayer cannot squeeze the sandbox into a budget that excludes -/// the parent's materialization-side state-growth invariant. -/// -/// `signer_info` is the parent-state `AccountInfo` loaded by -/// `inspect_signer_parent_state`. Treating absent/empty alike via `is_empty()` -/// (rather than re-reading the DB) keeps the materialization decision aligned with -/// what the upstream `make_create_frame` will observe for the same signer. -/// -/// Returns: -/// - `Ok(None)` when the signer was already materialized, or the charge fit and the resulting -/// state-growth event was within the parent's TX-level budget; -/// - `Ok(Some(halt))` when either the outer Gas could not absorb the charge (plain OOG), or -/// recording the state-growth event tripped a non-frame-local TX-level limit (canonical -/// exceeding-limit OOG, with parent gas rescued — see `reject_if_tx_limit_overflow`); -/// - `Err(InternalError)` when the dynamic-gas computation fails. -fn charge_caller_materialization_pre_sandbox( - ctx: &MegaContext, - gas: &mut Gas, - deploy_signer: Address, - signer_info: &AccountInfo, - return_memory_offset: &core::ops::Range, -) -> Result, KeylessDeployError> { - if !signer_info.is_empty() { - return Ok(None); - } - - // Call `DynamicGasCost::new_account_gas` directly rather than the `HostExt` helper: - // the helper stashes the SALT/env error into `ctx.error()`, which the outer transaction's - // own `execution_result` would later drain into an EVM-level `Err(Custom)` — breaking - // the spec contract that this failure surfaces as a `Revert(InternalError())` selector - // and leaves the outer transaction otherwise well-formed. - let caller_storage_gas = - ctx.dynamic_storage_gas_cost.borrow_mut().new_account_gas(deploy_signer).map_err(|e| { - error!( - error = %e, - deploy_signer = ?deploy_signer, - "pre-sandbox caller storage gas computation failed", - ); - KeylessDeployError::InternalError - })?; - if !gas.record_cost(caller_storage_gas) { - return Ok(Some(oog_frame_result(gas.limit(), return_memory_offset))); - } - // `record_deposit_caller_creation` can latch `has_exceeded_limit` to a non-frame-local - // `StateGrowthLimitExceeded`. Convert it to the canonical exceeding-limit OOG halt - // (with rescued gas) here — interceptor short-circuit bypasses `after_frame_run`'s - // standard `try_rescue_gas` hook, so any subsequent Revert-shaped error in this - // function would let `before_frame_return_result::` convert it to a Halt - // without ever rescuing the parent gas. - ctx.additional_limit.borrow_mut().record_deposit_caller_creation(); - if let Some(halt) = reject_if_tx_limit_overflow(ctx, gas, return_memory_offset) { - return Ok(Some(halt)); - } - Ok(None) -} - -/// Merges the sandbox's multidim usage into the parent's trackers. -/// -/// This merge is intentionally not undone on later halt paths, because -/// block-level multidim counters survive halts. -fn merge_sandbox_limit_usage( - ctx: &MegaContext, - limit_usage: LimitUsage, -) { - ctx.additional_limit.borrow_mut().merge_usage(limit_usage); -} - -/// Returns the unused portion of the sandbox's pre-debited gas reservation to the -/// outer frame. Mirrors revm's standard CALL semantics: pre-debit on entry, refund -/// `reservation - used` on exit. Pure `Gas::erase_cost`, never halts. -fn refund_unused_sandbox_gas(gas: &mut Gas, reservation: u64, sandbox_gas_used: u64) { - // Sandbox cannot consume more than the reservation it was given (revm's frame - // accounting enforces `gas_used ≤ gas_limit`), but `saturating_sub` keeps the - // arithmetic defensive against any future change in how `gas_used` is reported. - let unused = reservation.saturating_sub(sandbox_gas_used); - if unused > 0 { - gas.erase_cost(unused); - } -} - -/// Rejects the outer call when already-merged sandbox usage pushes the parent -/// over a non-frame-local TX-level limit. -/// -/// Returns `Some(FrameResult)` when the outer handler must short-circuit -/// (rescue remaining gas, return as exceeding-limit OOG), `None` when the -/// merged usage fits. -/// -/// State must not be merged after this returns `Some(_)`; the footprint -/// side effects already applied by `apply_sandbox_post_accounting` remain. -fn reject_if_tx_limit_overflow( - ctx: &MegaContext, - gas: &Gas, - return_memory_offset: &core::ops::Range, -) -> Option { - let mut limit = ctx.additional_limit.borrow_mut(); - let limit_check = limit.check_limit(); - if !limit_check.exceeded_limit() || limit_check.is_frame_local() { - return None; - } - limit.rescue_gas(gas); - let mut result = oog_frame_result(gas.limit(), return_memory_offset); - mark_frame_result_as_exceeding_limit( - &mut result, - crate::AdditionalLimit::EXCEEDING_LIMIT_INSTRUCTION_RESULT, - Default::default(), - ); - Some(result) -} - -/// Single source of truth for the `OutOfGas` halt `FrameResult` shape (empty return -/// data, all gas consumed). Callers that need the exceeding-limit marker apply -/// `mark_frame_result_as_exceeding_limit` on the returned value. -fn oog_frame_result(gas_limit: u64, return_memory_offset: &core::ops::Range) -> FrameResult { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::OutOfGas, - Bytes::new(), - Gas::new_spent(gas_limit), - ), - return_memory_offset.clone(), - )) -} - -/// Rex5+ preflight: rejects the outer call when the sandbox's known pre-frame intrinsic -/// usage alone would not fit inside the parent's remaining envelope. -/// -/// Running such a sandbox is guaranteed to fail internally, so this short-circuits before -/// sandbox EVM construction, signer balance DB read, and halt/rescue teardown — using a -/// lightweight trial-run via `AdditionalLimit::intrinsic_check_for_tx`. -/// -/// Returns `Some(KeylessDeployError::ParentBudgetExceeded { .. })` when the outer call -/// should revert, or `None` when the sandbox is permitted to start. -fn sandbox_intrinsic_overflow_error( - spec: MegaSpecId, - sandbox_tx: &MegaTransaction, - sandbox_tx_limits: Option, -) -> Option { - let limits = sandbox_tx_limits?; - match AdditionalLimit::intrinsic_check_for_tx(spec, sandbox_tx, limits) { - LimitCheck::ExceedsLimit { kind, limit, used, .. } => { - Some(KeylessDeployError::ParentBudgetExceeded { kind, limit, used }) - } - // `intrinsic_check_for_tx` builds a fresh trial tracker that never has `Exempt` stamped, - // so only the two real outcomes are reachable here. - LimitCheck::WithinLimit | LimitCheck::Exempt => None, - } -} - -/// Derives the sandbox's TX runtime limits from the parent's remaining budgets. -/// -/// Tightens the four resource dimensions (compute gas, data size, KV updates, state growth) -/// to the parent's frame-local remaining capacity. The base is the parent's active -/// `EvmTxRuntimeLimits` (not spec defaults), so any custom detention caps -/// (`block_env_access_compute_gas_limit`, `oracle_access_compute_gas_limit`) are -/// preserved. -/// -/// Intrinsic usage is NOT pre-subtracted here — the sandbox's own tracker records it -/// during transaction startup, so double-subtracting would leave the sandbox -/// under-budgeted. Pre-frame intrinsic overflow is instead caught by -/// `sandbox_intrinsic_overflow_error`, and any future TX-level persistent contribution -/// added before the first sandbox frame MUST be mirrored in -/// `AdditionalLimit::intrinsic_check_for_tx` to keep the preflight estimator sound. -fn sandbox_runtime_limits( - ctx: &MegaContext, -) -> EvmTxRuntimeLimits { - let parent_limit = ctx.additional_limit.borrow(); - let limits = parent_limit.limits; - - limits - .with_tx_compute_gas_limit(parent_limit.current_call_remaining_compute_gas()) - .with_tx_data_size_limit(parent_limit.current_call_remaining_data_size()) - .with_tx_kv_updates_limit(parent_limit.current_call_remaining_kv_updates()) - .with_tx_state_growth_limit(parent_limit.current_call_remaining_state_growth()) -} - -/// Reads an account nonce from the journal cache first, then falls back to the backing database. -fn get_account_nonce( - ctx: &mut MegaContext, - address: Address, -) -> Result { - let journal = ctx.journal_mut(); - if let Some(acc) = journal.state.get(&address) { - return Ok(acc.info.nonce); - } - Ok(journal - .database - .basic(address) - .map_err(|e| { - error!( - error = %e, - address = ?address, - "keyless deploy nonce read failed", - ); - KeylessDeployError::InternalError - })? - .map(|info| info.nonce) - .unwrap_or(0)) -} - -/// Loads the deploy signer's parent-state `AccountInfo` via `JournalInspectTr::inspect_account` -/// (cold-marked) for Rex5+. -/// -/// The single lookup feeds the nonce check, the EIP-3607 caller-with-code check, and the -/// materialization `is_empty()` check from one source — keeping the "cold-marked, no -/// EIP-2929 pollution" contract documented in one place. -/// -/// `load_code` is derived from `!cfg.disable_eip3607`: EIP-3607 needs the bytecode to -/// distinguish a real contract from an EIP-7702 delegation designation, but when -/// `disable_eip3607 = true` the canonical revm `validate_account_nonce_and_code` -/// short-circuits without touching `code_by_hash`. The nonce check reads `info.nonce` -/// and the materialization check reads `info.is_empty()` (which uses `code_hash`, not the -/// hydrated bytes), so neither requires the bytecode to be loaded. -/// -/// Edge case — the `disable_eip3607 = true` no-`code_by_hash` short-circuit holds only when -/// the signer is not already present in the parent journal cache as a lazy-code occupied -/// entry. `inspect_account`'s occupied branch unconditionally invokes `code_by_hash` on -/// `code_hash != KECCAK_EMPTY && info.code.is_none()` regardless of `load_code` — this -/// hydration is load-bearing for the pre-REX5 EIP-7702 detection path in -/// `inspect_account_delegated` (see `evm/host.rs`) and changing it would shift behavior on -/// frozen specs. In the normal third-party relayer keyless-deploy flow the signer is -/// recovered from the inner RLP at step 5 of `execute_keyless_deploy_call` and the outer -/// EVM has not touched it before that, so the signer's journal entry is vacant when this -/// helper runs. If an outer transaction or replay harness has already cached the signer -/// (e.g., the relayer happens to be the signer, or a witness / stateless harness pre-fills -/// the journal with lazy-code entries), the occupied-entry caveat above applies. -fn inspect_signer_parent_state( - ctx: &mut MegaContext, - address: Address, -) -> Result { - let load_code = !ctx.cfg().disable_eip3607; - let account = ctx.journal_mut().inspect_account(address, load_code).map_err(|e| { - error!( - error = %e, - address = ?address, - "keyless deploy signer parent-state inspection failed", - ); - KeylessDeployError::InternalError - })?; - Ok(account.info.clone()) -} - -/// Enforces the EIP-3607 caller-with-code rule against the provided parent-state info, -/// honoring `cfg.disable_eip3607` exactly like the canonical revm path. -/// -/// The op-revm deposit path skips this check in `validate_against_state_and_deduct_caller`, -/// so the sandbox enforces it itself for Rex5+ to keep the no-contract-sender invariant. -/// The lookup itself lives in `inspect_signer_parent_state`; this function only inspects -/// the resulting info. -fn validate_signer_code( - ctx: &MegaContext, - signer_info: &AccountInfo, -) -> Result<(), KeylessDeployError> { - if ctx.cfg().disable_eip3607 { - return Ok(()); - } - if let Some(code) = &signer_info.code { - if !code.is_empty() && !code.is_eip7702() { - return Err(KeylessDeployError::SignerHasCode); - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use revm::context::result::Output; - - /// Test error type that lets us drive `process_sandbox_transact_result`'s - /// `Err` arms (which map to `SandboxOutcome::Rejected`) directly without - /// standing up a full sandbox EVM. The two arms differ only by - /// `IsTxError::is_tx_error()`, so a single struct with a configurable flag - /// covers both selector mappings. - struct FakeTxErr { - is_tx: bool, - msg: &'static str, - } - - impl core::fmt::Display for FakeTxErr { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(self.msg) - } - } - - impl IsTxError for FakeTxErr { - fn is_tx_error(&self) -> bool { - self.is_tx - } - } - - /// The sandbox's create transaction always asks for `TxKind::Create`, but if revm - /// ever surfaces a `Success` with `Output::Call` for that input shape the merge code - /// would otherwise unwrap into an address-less success. Pin the defensive - /// `NoContractCreated` mapping. - #[test] - fn test_process_result_call_output_maps_to_no_contract_created() { - let result: Result, FakeTxErr> = Ok(ResultAndState { - result: ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas_used: 1, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Call(Bytes::new()), - }, - state: EvmState::default(), - }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated)), - "unexpected: {out:?}", - ); - } - - /// `Output::Create(_, None)` — Create succeeded but revm did not return an address. - /// Same defensive `NoContractCreated` shape as the Call branch. - #[test] - fn test_process_result_create_without_address_maps_to_no_contract_created() { - let result: Result, FakeTxErr> = Ok(ResultAndState { - result: ExecutionResult::Success { - reason: revm::context::result::SuccessReason::Stop, - gas_used: 1, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Create(Bytes::from_static(&[0x60, 0x00]), None), - }, - state: EvmState::default(), - }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::NoContractCreated)), - "unexpected: {out:?}", - ); - } - - /// `transact_raw` error where `is_tx_error()` is `false` (DB I/O, header validation, - /// `EVMError::Custom`, etc.) MUST map to the selector-only `InternalError`. Pinned - /// because a regression that re-collapses this into `InvalidTransaction` would - /// silently re-classify infrastructure failures as user-input rejections. - #[test] - fn test_process_result_non_tx_error_maps_to_internal_error() { - let result: Result, FakeTxErr> = - Err(FakeTxErr { is_tx: false, msg: "db blew up" }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::InternalError)), - "unexpected: {out:?}", - ); - } - - /// Mirror of the above for `is_tx_error() == true`: MUST map to - /// `InvalidTransaction` with its dedicated selector. - #[test] - fn test_process_result_tx_error_maps_to_invalid_transaction() { - let result: Result, FakeTxErr> = - Err(FakeTxErr { is_tx: true, msg: "intrinsic gas too low" }); - let out = process_sandbox_transact_result( - result, - LimitUsage::default(), - VolatileDataAccess::empty(), - true, - false, - ); - assert!( - matches!(out, SandboxOutcome::Rejected(KeylessDeployError::InvalidTransaction)), - "unexpected: {out:?}", - ); - } - - /// `get_account_nonce`: cache miss path on a failing DB MUST map the underlying - /// `DBError` to selector-only `InternalError`. This is the only sandbox-internal - /// call site that reads a nonce via the parent journal database directly (rather - /// than via the journal cache or `SandboxDb` fallthrough), so the `error!` `map_err` - /// is the only place the failure can be classified. - #[test] - fn test_get_account_nonce_db_error_maps_to_internal_error() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - // Cache is empty → cache miss → DB fallback → injected error. - let out = get_account_nonce(&mut ctx, signer); - assert!(matches!(out, Err(KeylessDeployError::InternalError)), "unexpected: {out:?}"); - } - - /// `get_account_nonce` MUST take the journal-cache branch (without re-reading the - /// database) when the address is already present in `journal.inner.state`. Pinned - /// because the cache-hit branch and the DB-fallback branch return identical values on - /// the happy path; only an end-to-end harness or a direct unit assertion can tell them - /// apart. - #[test] - fn test_get_account_nonce_returns_cached_nonce_without_touching_database() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - use revm::{primitives::KECCAK_EMPTY, state::AccountInfo}; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - // DB fails on every `basic(signer)` call. The cache-hit branch is the only way - // `get_account_nonce` can return successfully — if the DB-fallback branch is taken, - // the test fails with the injected error. - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - // Seed the journal cache directly so `get_account_nonce` finds the signer in - // `journal.inner.state` and short-circuits before reaching the DB fallback. - let cached_info = - AccountInfo { nonce: 7, balance: U256::ZERO, code_hash: KECCAK_EMPTY, code: None }; - ctx.journal_mut().inner.state.insert(signer, cached_info.into()); - - let nonce = get_account_nonce(&mut ctx, signer).expect("cache hit must not error"); - assert_eq!(nonce, 7, "cache-hit nonce must reflect the seeded journal entry"); - } - - /// `inspect_signer_parent_state` MUST surface an `inspect_account` DB failure as - /// `Err(KeylessDeployError::InternalError)`. This is the only Rex5+ pre-sandbox call - /// site that performs the parent-state read — every downstream check (`signer_nonce`, - /// `validate_signer_code`, materialization) inspects the returned `AccountInfo` - /// without touching the DB again, so the `error!` `map_err` here is the only place - /// the failure can be classified. - #[test] - fn test_inspect_signer_parent_state_db_error_maps_to_internal_error() { - use crate::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, - }; - use alloy_primitives::address; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - db.fail_on_account = Some(signer); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - let out = inspect_signer_parent_state(&mut ctx, signer); - assert!( - matches!(out, Err(KeylessDeployError::InternalError)), - "inspect_account DB error must map to InternalError; got {out:?}", - ); - } - - /// `inspect_signer_parent_state` MUST NOT invoke `code_by_hash` when - /// `cfg.disable_eip3607 = true` AND the signer is not yet present in the parent - /// journal cache — i.e., the vacant-branch path used by the normal keyless-deploy flow - /// when the signer is not pre-cached in the parent journal (signer recovered from inner - /// RLP at step 5 of `execute_keyless_deploy_call`, after which only this helper - /// inspects it). - /// - /// Pin the contract that the canonical revm `validate_account_nonce_and_code` - /// short-circuits without hydrating the signer's bytecode on the vacant path; without - /// this, a DB whose `code_by_hash` fails turns an EIP-3607-disabled precheck into - /// `InternalError`. The pre-cached lazy-code occupied path is a documented edge case - /// (see `inspect_signer_parent_state` docstring) — `inspect_account`'s occupied branch - /// unconditionally hydrates and that behavior is load-bearing for stable specs. - /// - /// The workspace's `MemoryDatabase` eagerly inlines `AccountInfo.code` inside `basic()`, - /// so the in-tree integration tests cannot exercise this lazy-code shape — hence a - /// dedicated `revm::Database` impl here that mirrors reth's - /// `StateProviderDatabase::basic` contract (`code: None`, real `code_hash`). - #[test] - fn test_inspect_signer_parent_state_skips_code_by_hash_on_vacant_when_eip3607_disabled() { - use alloy_primitives::{address, keccak256, B256}; - use revm::{bytecode::Bytecode, primitives::Bytes as PrimitivesBytes}; - - #[derive(Debug, Default)] - struct LazyCodeSignerDb { - signer: Address, - signer_info: AccountInfo, - } - - impl RevmDatabase for LazyCodeSignerDb { - type Error = core::convert::Infallible; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - if address == self.signer { - // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo with - // `code: None` even when `code_hash` references real on-chain bytecode. - Ok(Some(self.signer_info.clone())) - } else { - Ok(None) - } - } - - fn code_by_hash(&mut self, _code_hash: B256) -> Result { - panic!( - "code_by_hash must not be called on the vacant signer path when \ - disable_eip3607 = true (canonical validate_account_nonce_and_code \ - short-circuit)", - ); - } - - fn storage(&mut self, _address: Address, _index: U256) -> Result { - Ok(U256::ZERO) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } - } - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let bytecode = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - let code_hash = keccak256(&bytecode); - let signer_info = AccountInfo { nonce: 0, balance: U256::ZERO, code_hash, code: None }; - let db = LazyCodeSignerDb { signer, signer_info }; - - let mut ctx = MegaContext::<_, crate::EmptyExternalEnv>::new(db, MegaSpecId::REX5); - ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); - - let info = inspect_signer_parent_state(&mut ctx, signer) - .expect("lookup must succeed without hydrating code"); - assert_eq!(info.code_hash, code_hash, "code_hash must propagate from the DB"); - assert!( - info.code.is_none(), - "disable_eip3607 = true must leave info.code as None on the vacant branch", - ); - } - - /// `validate_signer_code` MUST be a no-op when `cfg.disable_eip3607 = true`, even - /// when the provided `AccountInfo` has bytecode that would otherwise trip the - /// caller-with-code check. Mirrors the canonical revm `validate_account_nonce_and_code` - /// semantics and pins the early-return contract. - #[test] - fn test_validate_signer_code_disable_eip3607_short_circuits() { - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use revm::{ - bytecode::Bytecode, - primitives::{keccak256, Bytes as PrimitivesBytes}, - }; - - let code_bytes = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - let code_hash = keccak256(&code_bytes); - let signer_info = AccountInfo { - nonce: 0, - balance: U256::ZERO, - code_hash, - code: Some(Bytecode::new_raw(code_bytes)), - }; - - let mut ctx = - MegaContext::<_, EmptyExternalEnv>::new(MemoryDatabase::default(), MegaSpecId::REX5); - ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); - - let out = validate_signer_code(&ctx, &signer_info); - assert!( - matches!(out, Ok(())), - "disable_eip3607 must short-circuit before the code inspection; got {out:?}", - ); - } - - /// `charge_caller_materialization_pre_sandbox` MUST surface a SALT/dynamic-gas failure - /// as `Err(KeylessDeployError::InternalError)` without writing to `ctx.error()`. - /// - /// The contract is load-bearing: op-revm's `Handler::execution_result` drains - /// `ctx.error()` and converts any non-empty `ContextError` into an EVM-level - /// `Err(Custom(...))`. Routing a SALT failure through the - /// `HostExt::new_account_storage_gas` helper — which stashes the error into - /// `ctx.error()` — would promote an interceptor-level failure into a whole-transaction - /// execution error and break the `InternalError()` selector contract. The - /// pre-sandbox charge path must therefore call `DynamicGasCost::new_account_gas` - /// directly and keep the error local. - #[test] - fn test_charge_caller_materialization_salt_failure_returns_internal_error_without_ctx_pollution( - ) { - use crate::{test_utils::MemoryDatabase, BucketId, OracleEnv, SaltEnv}; - use alloy_primitives::{address, B256}; - use core::fmt::{self, Display, Formatter}; - - // Minimal `SaltEnv` whose `get_bucket_capacity` always fails. This drives - // `DynamicGasCost::new_account_gas` (called from - // `charge_caller_materialization_pre_sandbox`) to return `Err`, exercising the - // failure-handling path under test. - #[derive(Debug, Clone, Copy)] - struct AlwaysFailSalt; - - #[derive(Debug, Clone)] - struct InjectedSaltError; - impl Display for InjectedSaltError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.write_str("injected SALT failure") - } - } - - impl SaltEnv for AlwaysFailSalt { - type Error = InjectedSaltError; - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err(InjectedSaltError) - } - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } - } - - #[derive(Debug, Clone, Copy)] - struct NoopOracle; - impl OracleEnv for NoopOracle { - fn get_oracle_storage(&self, _slot: U256) -> Option { - None - } - fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} - } - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let db = MemoryDatabase::default(); - let envs: crate::ExternalEnvs<(AlwaysFailSalt, NoopOracle)> = - crate::ExternalEnvs { salt_env: AlwaysFailSalt, oracle_env: NoopOracle }; - let mut ctx = MegaContext::new(db, MegaSpecId::REX5).with_external_envs(envs); - - let mut gas = Gas::new(10_000_000); - let return_memory_offset = 0..0; - - // Signer is unmaterialized (default `AccountInfo` is `is_empty()` == true) - // → the materialization branch fires. - let signer_info = AccountInfo::default(); - let out = charge_caller_materialization_pre_sandbox( - &ctx, - &mut gas, - signer, - &signer_info, - &return_memory_offset, - ); - assert!( - matches!(out, Err(KeylessDeployError::InternalError)), - "SALT failure must surface as InternalError, got {out:?}", - ); - - // The whole point of the fix: ctx.error() must NOT have been polluted, so the outer - // transaction's `execution_result` doesn't drain it into `Err(Custom)`. - let ctx_error = core::mem::replace(ctx.error(), Ok(())); - assert!( - matches!(ctx_error, Ok(())), - "ctx.error() must remain Ok after a SALT failure in the pre-sandbox charge; \ - got {ctx_error:?}", - ); - - // record_deposit_caller_creation must NOT have fired either. - assert_eq!( - ctx.additional_limit.borrow().get_usage().state_growth, - 0, - "deposit-caller state-growth must not be recorded when the storage gas computation fails", - ); - } -} diff --git a/crates/mega-evm/src/sandbox/mod.rs b/crates/mega-evm/src/sandbox/mod.rs deleted file mode 100644 index c59c9889c..000000000 --- a/crates/mega-evm/src/sandbox/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Sandbox execution environment for keyless contract deployment. -//! -//! This module provides isolated EVM execution for implementing "Nick's Method" - a technique -//! for deterministic contract deployment that allows deploying contracts to the same address -//! across different chains using pre-EIP-155 transactions. -//! -//! # Overview -//! -//! The sandbox executes keyless deployment transactions in an isolated environment, then -//! applies only the resulting state changes to the parent context. This approach: -//! -//! - Validates pre-EIP-155 legacy transactions -//! - Recovers the signer and computes the deterministic deploy address -//! - Executes contract creation with a nonce override of 0 -//! - Merges state changes back to the parent journal -//! -//! # Spam Protection -//! -//! The sandbox is designed to guarantee that **every execution that starts and completes is paid -//! for** — either by the signer through merged sandbox state on normal completion, or by the -//! outer caller through `record_cost` on Rex5 residual-overflow rejects. This prevents spam -//! attacks where an attacker triggers execution but avoids paying. -//! -//! ## General Protections -//! -//! 1. **Top-level only (`depth == 0`)**: Sandbox interception only occurs for direct transaction -//! calls. Calls from contracts (depth > 0) hit the Solidity fallback which reverts with -//! `NotIntercepted()`. This prevents wrapping the call to observe and revert. -//! -//! 2. **Execution errors return success**: Failures like `ExecutionReverted`, `ExecutionHalted`, -//! and `EmptyCodeDeployed` return normally with error data so state changes (including the -//! signer's balance deduction via merged state) are committed. -//! -//! 3. **Atomic state application**: `apply_sandbox_state` is the sole writer that makes a deploy -//! (and the signer-side charge) survive. Pre-Rex5 keeps the legacy direct merge for replay -//! compatibility, while Rex5 records stateful diffs in the parent journal so a later outer-frame -//! revert or halt can unwind them. -//! -//! ## Rex5 Resource-Envelope Defenses -//! -//! Rex5 adds three layers to keep a parent-budget-exceeding sandbox from either corrupting -//! accounting or escaping its charge: -//! -//! 1. **Upfront cap**: sandbox TX limits are tightened to the parent's remaining envelope before -//! execution starts, so normal execution cannot escape the envelope. -//! -//! 2. **Intrinsic preflight**: if the sandbox's known pre-frame intrinsic usage alone would exceed -//! the envelope, the outer call reverts with `ParentBudgetExceeded` before any sandbox EVM -//! construction. -//! -//! 3. **Post-merge safety net**: residual overflow (e.g., a single-opcode overshoot at a TX-level -//! compute-gas check) is caught after the sandbox completes. On this path the sandbox state is -//! NOT merged, the sandbox's EVM gas is charged to the outer caller via `record_cost`, remaining -//! outer gas is rescued for refund, and the outer call halts with `OutOfGas` — matching the revm -//! "halted transactions commit only pre-execution state" convention. Only this path halts the -//! outer call. -//! -//! # Module Structure -//! -//! - `execution` - Core sandbox execution logic and the main entry point -//! [`execute_keyless_deploy_call`] -//! - `state` - Type-erased database wrapper ([`SandboxDb`]) for isolated execution -//! - `state_merge` - Replay-safe merge of sandbox state into the parent journal -//! - `tx` - Transaction decoding and validation for pre-EIP-155 transactions -//! - `error` - Error types ([`KeylessDeployError`]) that map to Solidity errors in `IKeylessDeploy` -//! -//! # Type Erasure Strategy -//! -//! A key challenge in implementing sandbox execution is preventing infinite type instantiation. -//! If `MegaContext` creates a sandbox with `MegaContext`, the compiler would attempt -//! to instantiate `MegaContext>>`, causing an Internal Compiler -//! Error (ICE) during monomorphization. -//! -//! The solution is [`SandboxDb`], a type-erased database wrapper: -//! -//! ```text -//! MegaContext -//! └─> sandbox execution -//! └─> MegaContext // SandboxDb is a concrete type, not MegaContext<...> -//! ``` -//! -//! [`SandboxDb`] implements the `Database` trait while internally holding a type-erased -//! reference to the parent database via the `ErasedDatabase` trait. This breaks the recursive -//! type chain while still allowing the sandbox to read from the parent's state. -//! -//! # Usage -//! -//! The sandbox is invoked automatically when a call to the `KeylessDeploy` precompile is -//! intercepted in `MegaContext::call`. The entry point is [`execute_keyless_deploy_call`], -//! which validates the transaction, creates a sandbox environment, executes the deployment, -//! and returns the result. -//! -//! [`execute_keyless_deploy_call`]: execution::execute_keyless_deploy_call -//! [`SandboxDb`]: state::SandboxDb - -mod error; -mod execution; -mod state; -mod state_merge; -mod tx; - -pub use error::*; -pub use execution::*; -pub use state::*; -pub use tx::*; diff --git a/crates/mega-evm/src/sandbox/state.rs b/crates/mega-evm/src/sandbox/state.rs deleted file mode 100644 index 1376745b9..000000000 --- a/crates/mega-evm/src/sandbox/state.rs +++ /dev/null @@ -1,516 +0,0 @@ -//! Sandbox database for isolated EVM execution. -//! -//! This module uses type erasure to prevent infinite type instantiation -//! (`SandboxDb>`) that would cause a compiler ICE during monomorphization. - -#![allow(unreachable_pub)] // Types are pub for trait impls but module is private - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{ - boxed::Box, - string::{String, ToString}, -}; - -use alloy_primitives::{map::HashMap, Address, B256}; -use core::cell::RefCell; -use revm::{ - database::DBErrorMarker, - primitives::{StorageKey, StorageValue, KECCAK_EMPTY}, - state::{AccountInfo, Bytecode, EvmState}, - Database, -}; - -/// Error type for sandbox database operations. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SandboxDbError(String); - -impl core::fmt::Display for SandboxDbError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.0) - } -} - -impl core::error::Error for SandboxDbError {} -impl DBErrorMarker for SandboxDbError {} - -/// Type-erased database trait for sandbox operations. -/// -/// This trait erases the concrete database type to prevent infinite type -/// instantiation when creating nested sandboxes. -/// -/// # Why not `Box`? -/// -/// The [`Database`] trait has an associated type `Error`, which makes it not -/// object-safe. You cannot use `Box` directly because the compiler -/// doesn't know what error type to use at runtime: -/// -/// ```ignore -/// pub trait Database { -/// type Error; // This makes it NOT object-safe -/// fn basic(&mut self, ...) -> Result<..., Self::Error>; -/// } -/// ``` -/// -/// Even `Box>` won't work because the trait -/// requires `Self::Error` to match exactly - you can't erase a `DB::Error` into -/// a different type through a trait object. -/// -/// This `ErasedDatabase` trait solves the problem by: -/// 1. Having no associated types (all methods return our fixed [`SandboxDbError`]) -/// 2. Converting errors via `.to_string()` in the [`DatabaseWrapper`] implementation -trait ErasedDatabase { - fn basic(&self, address: Address) -> Result, SandboxDbError>; - fn storage(&self, address: Address, index: StorageKey) -> Result; - fn block_hash(&self, number: u64) -> Result; - fn code_by_hash(&self, code_hash: B256) -> Result; -} - -/// Wrapper that implements [`ErasedDatabase`] for any [`Database`] type. -/// -/// Uses `RefCell` for interior mutability since `Database` methods take `&mut self`. -struct DatabaseWrapper<'a, DB> { - db: RefCell<&'a mut DB>, -} - -impl ErasedDatabase for DatabaseWrapper<'_, DB> -where - DB::Error: core::fmt::Display, -{ - #[inline] - fn basic(&self, address: Address) -> Result, SandboxDbError> { - self.db.borrow_mut().basic(address).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn storage(&self, address: Address, index: StorageKey) -> Result { - self.db.borrow_mut().storage(address, index).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn block_hash(&self, number: u64) -> Result { - self.db.borrow_mut().block_hash(number).map_err(|e| SandboxDbError(e.to_string())) - } - - #[inline] - fn code_by_hash(&self, code_hash: B256) -> Result { - self.db.borrow_mut().code_by_hash(code_hash).map_err(|e| SandboxDbError(e.to_string())) - } -} - -/// A sandbox database for isolated EVM execution. -/// -/// Used for keyless deploy sandbox where we need to read from the parent state -/// directly without cloning the entire state upfront. -/// -/// **Important**: This type uses lifetime parameters to hold references to the -/// parent journal's state and database, avoiding expensive cloning. Values are -/// cloned lazily only when accessed. -pub struct SandboxDb<'a> { - /// Reference to the parent journal's state. - journal_state: &'a EvmState, - /// Type-erased reference to the underlying database for cache misses. - db: Box, - /// Index from `code_hash` to address for O(1) bytecode lookup. - code_index: HashMap, - /// Address whose nonce should be overridden to 0 (for keyless deploy). - nonce_override_address: Option
, -} - -impl<'a> core::fmt::Debug for SandboxDb<'a> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("SandboxDb").finish_non_exhaustive() - } -} - -impl<'a> SandboxDb<'a> { - /// Creates a new sandbox database with references to the journal's state and database. - /// - /// This does NOT clone the state or database - it holds references and clones values - /// lazily when accessed. The `code_index` is built upfront for O(1) bytecode lookup. - /// - /// # Arguments - /// - /// * `state` - Reference to the journal's cached state - /// * `db` - Mutable reference to the underlying database for cache misses - /// - /// # Split Borrowing - /// - /// This constructor takes separate references to state and database to allow - /// split borrowing at the call site. The caller should do: - /// ```ignore - /// let journal = ctx.journal_mut(); - /// let sandbox_db = SandboxDb::new(&journal.inner.state, &mut journal.database); - /// ``` - pub fn new(state: &'a EvmState, db: &'a mut DB) -> Self - where - DB: Database, - DB::Error: core::fmt::Display, - { - // Build code index for O(1) bytecode lookup - let mut code_index = HashMap::default(); - for (addr, account) in state { - if let Some(code) = &account.info.code { - if !code.is_empty() { - code_index.insert(account.info.code_hash, *addr); - } - } - } - - Self { - journal_state: state, - db: Box::new(DatabaseWrapper { db: RefCell::new(db) }), - code_index, - nonce_override_address: None, - } - } - - /// Sets an address whose nonce should be overridden to 0. - /// - /// This is used for keyless deploy where the transaction must have nonce=0 - /// regardless of the signer's actual nonce in the database. - pub fn with_nonce_override(mut self, address: Address) -> Self { - self.nonce_override_address = Some(address); - self - } -} - -impl Database for SandboxDb<'_> { - type Error = SandboxDbError; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - // Check journal state first - clone only when accessed - if let Some(account) = self.journal_state.get(&address) { - let mut info = account.info.clone(); - // Override nonce to 0 for the keyless deploy signer - if self.nonce_override_address == Some(address) { - info.nonce = 0; - } - return Ok(Some(info)); - } - // Not found in journal state - query underlying database - let result = self.db.basic(address)?; - // Override nonce to 0 for the keyless deploy signer - if let Some(mut info) = result { - if self.nonce_override_address == Some(address) { - info.nonce = 0; - } - return Ok(Some(info)); - } - Ok(None) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - if code_hash == KECCAK_EMPTY { - return Ok(Bytecode::default()); - } - - // Use index for O(1) lookup in journal state - if let Some(addr) = self.code_index.get(&code_hash) { - if let Some(account) = self.journal_state.get(addr) { - return Ok(account.info.code.clone().unwrap_or_default()); - } - } - - // Not found in journal state - query underlying database - self.db.code_by_hash(code_hash) - } - - fn storage( - &mut self, - address: Address, - index: StorageKey, - ) -> Result { - // Check journal state for cached storage values - if let Some(account) = self.journal_state.get(&address) { - if let Some(slot) = account.storage.get(&index) { - return Ok(slot.present_value); - } - } - // Not found in journal state - query underlying database - self.db.storage(address, index) - } - - fn block_hash(&mut self, number: u64) -> Result { - // Block hashes are not stored in journal state - query database - self.db.block_hash(number) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256, Bytes, U256}; - use revm::{ - context::JournalTr, - database::EmptyDB, - state::{AccountStatus, EvmStorageSlot}, - Journal, - }; - - const TEST_ADDR_1: Address = address!("1111111111111111111111111111111111111111"); - const TEST_ADDR_2: Address = address!("2222222222222222222222222222222222222222"); - const TEST_ADDR_3: Address = address!("3333333333333333333333333333333333333333"); - - fn create_test_journal() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - // Add a test account to the journal - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from(1000), - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_1, account); - journal - } - - fn create_journal_with_contract() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - - // Create bytecode and compute its hash - let bytecode_bytes = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); // PUSH0 PUSH0 RETURN - let bytecode = Bytecode::new_raw(bytecode_bytes.clone()); - let code_hash = keccak256(&bytecode_bytes); - - // Add contract account with bytecode - let contract_account = revm::state::Account { - info: AccountInfo { balance: U256::ZERO, nonce: 1, code_hash, code: Some(bytecode) }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_2, contract_account); - journal - } - - fn create_journal_with_storage() -> Journal { - let mut journal = Journal::::new(EmptyDB::default()); - - // Add account with storage - let mut storage = HashMap::default(); - storage.insert(U256::from(1), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - storage - .insert(U256::from(100), EvmStorageSlot::new_changed(U256::ZERO, U256::from(999), 0)); - - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from(5000), - nonce: 10, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage, - status: AccountStatus::empty(), - }; - journal.inner.state.insert(TEST_ADDR_1, account); - journal - } - - // ==================== basic() tests ==================== - - #[test] - fn test_basic_returns_account_from_journal() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let result = sandbox.basic(TEST_ADDR_1).unwrap(); - assert!(result.is_some()); - let info = result.unwrap(); - assert_eq!(info.balance, U256::from(1000)); - assert_eq!(info.nonce, 1); - } - - #[test] - fn test_basic_queries_database_on_cache_miss() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // TEST_ADDR_3 is not in journal, so it queries EmptyDB which returns None - let result = sandbox.basic(TEST_ADDR_3).unwrap(); - assert!(result.is_none()); - } - - #[test] - fn test_basic_returns_contract_account_info() { - let mut journal = create_journal_with_contract(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let result = sandbox.basic(TEST_ADDR_2).unwrap(); - assert!(result.is_some()); - let info = result.unwrap(); - assert_eq!(info.nonce, 1); - assert_ne!(info.code_hash, KECCAK_EMPTY); - } - - // ==================== storage() tests ==================== - - #[test] - fn test_storage_returns_value_from_journal() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let value = sandbox.storage(TEST_ADDR_1, U256::from(1)).unwrap(); - assert_eq!(value, U256::from(42)); - - let value = sandbox.storage(TEST_ADDR_1, U256::from(100)).unwrap(); - assert_eq!(value, U256::from(999)); - } - - #[test] - fn test_storage_returns_zero_for_unset_slot_in_journal() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Slot 50 is not set in journal storage, queries database (EmptyDB returns zero) - let value = sandbox.storage(TEST_ADDR_1, U256::from(50)).unwrap(); - assert_eq!(value, U256::ZERO); - } - - #[test] - fn test_storage_queries_database_for_unknown_account() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // TEST_ADDR_3 not in journal, queries EmptyDB which returns zero - let value = sandbox.storage(TEST_ADDR_3, U256::from(1)).unwrap(); - assert_eq!(value, U256::ZERO); - } - - // ==================== code_by_hash() tests ==================== - - #[test] - fn test_code_by_hash_returns_empty_for_keccak_empty() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let code = sandbox.code_by_hash(KECCAK_EMPTY).unwrap(); - assert!(code.is_empty()); - } - - #[test] - fn test_code_by_hash_returns_bytecode_from_journal_via_index() { - let mut journal = create_journal_with_contract(); - - // Get the code hash from the contract account - let code_hash = journal.inner.state.get(&TEST_ADDR_2).unwrap().info.code_hash; - - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let code = sandbox.code_by_hash(code_hash).unwrap(); - assert!(!code.is_empty()); - // Bytecode may have padding, so check it starts with our expected bytes - assert!(code.bytes_slice().starts_with(&[0x60, 0x00, 0x60, 0x00, 0xf3])); - } - - #[test] - fn test_code_by_hash_queries_database_for_unknown_hash() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Random hash not in journal - queries EmptyDB which returns empty bytecode - let unknown_hash = keccak256(b"unknown code"); - let code = sandbox.code_by_hash(unknown_hash).unwrap(); - assert!(code.is_empty()); - } - - #[test] - fn test_code_index_built_correctly() { - let mut journal = create_journal_with_contract(); - let code_hash = journal.inner.state.get(&TEST_ADDR_2).unwrap().info.code_hash; - - let sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Verify code_index contains the mapping - assert!(sandbox.code_index.contains_key(&code_hash)); - assert_eq!(sandbox.code_index.get(&code_hash), Some(&TEST_ADDR_2)); - } - - #[test] - fn test_code_index_excludes_empty_code() { - let mut journal = create_test_journal(); - let sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Account with no code should not be in code_index - assert!(!sandbox.code_index.contains_key(&KECCAK_EMPTY)); - assert!(sandbox.code_index.is_empty()); - } - - // ==================== block_hash() tests ==================== - - #[test] - fn test_block_hash_queries_database() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Block hash is always queried from database - // EmptyDB returns keccak256(block_number) - let hash = sandbox.block_hash(100).unwrap(); - assert_ne!(hash, B256::ZERO); // EmptyDB returns non-zero hash - } - - #[test] - fn test_block_hash_different_blocks_different_hashes() { - let mut journal = create_test_journal(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - let hash_100 = sandbox.block_hash(100).unwrap(); - let hash_200 = sandbox.block_hash(200).unwrap(); - - assert_ne!(hash_100, hash_200); - } - - // ==================== Multiple accounts tests ==================== - - #[test] - fn test_multiple_accounts_in_journal() { - let mut journal = Journal::::new(EmptyDB::default()); - - // Add multiple accounts - for (i, addr) in [TEST_ADDR_1, TEST_ADDR_2, TEST_ADDR_3].iter().enumerate() { - let account = revm::state::Account { - info: AccountInfo { - balance: U256::from((i + 1) * 1000), - nonce: i as u64, - code_hash: KECCAK_EMPTY, - code: None, - }, - transaction_id: 0, - storage: Default::default(), - status: AccountStatus::empty(), - }; - journal.inner.state.insert(*addr, account); - } - - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Verify all accounts are accessible - let info1 = sandbox.basic(TEST_ADDR_1).unwrap().unwrap(); - assert_eq!(info1.balance, U256::from(1000)); - - let info2 = sandbox.basic(TEST_ADDR_2).unwrap().unwrap(); - assert_eq!(info2.balance, U256::from(2000)); - - let info3 = sandbox.basic(TEST_ADDR_3).unwrap().unwrap(); - assert_eq!(info3.balance, U256::from(3000)); - } - - // ==================== Journal priority tests ==================== - - #[test] - fn test_journal_state_takes_priority_over_database() { - let mut journal = create_journal_with_storage(); - let mut sandbox = SandboxDb::new(&journal.inner.state, &mut journal.database); - - // Storage slot 1 has value 42 in journal - // Even if database had a different value, journal takes priority - let value = sandbox.storage(TEST_ADDR_1, U256::from(1)).unwrap(); - assert_eq!(value, U256::from(42)); - } -} diff --git a/crates/mega-evm/src/sandbox/state_merge.rs b/crates/mega-evm/src/sandbox/state_merge.rs deleted file mode 100644 index 4ec3c5013..000000000 --- a/crates/mega-evm/src/sandbox/state_merge.rs +++ /dev/null @@ -1,910 +0,0 @@ -//! Sandbox state merge logic. -//! -//! Keeps the execution entry point focused on validation and sandbox orchestration while this -//! module owns the replay-sensitive details of applying sandbox state to the parent journal. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use alloy_evm::Database as AlloyDatabase; -use alloy_primitives::{Address, U256}; -use revm::{context::ContextTr, primitives::KECCAK_EMPTY, state::EvmState, Journal, JournalEntry}; -use tracing::error; - -use crate::{ - merge_evm_state_optional_status, ExternalEnvTypes, JournalInspectTr, MegaContext, MegaSpecId, -}; - -use super::error::KeylessDeployError; - -/// Applies all state changes from sandbox execution to the parent journal. -/// -/// All accounts from the sandbox view are merged into the parent journal — including accounts that -/// were only read and not written — because the `ReadSet` for stateless witness generation requires -/// knowing which accounts a sandbox touched. -/// -/// Coldness metadata is NOT merged: sandbox state changes are treated as a silent database update -/// that does not affect the parent transaction's own observable coldness-dependent gas costs. -/// Pre-Rex5 also keeps the legacy "do not merge status into existing parent accounts" behavior. -/// Rex5 records only the status entries needed for stateful diffs, such as created/touched account -/// markers, so normal journal commit/revert semantics stay correct. -/// -/// The sandbox runs with the signer's nonce overridden to `0` (Nick's Method), and the post-CREATE -/// nonce of `1` is intentionally preserved in the merged state to record that the signer has been -/// used for a keyless deploy. -/// -/// Pre-Rex5 keeps the legacy direct merge for replay compatibility. Rex5 records state-changing -/// diffs as journal entries so that an outer-frame revert or halt unwinds the sandbox's effects via -/// the normal checkpoint-revert mechanism. The Rex5 merge still keeps read-only accounts, bytecode, -/// and storage slots in the parent journal cache for witness generation; revm's default journal -/// entries can mark those cache entries cold again but cannot remove them from the cache map. -pub(super) fn apply_sandbox_state( - ctx: &mut MegaContext, - sandbox_state: EvmState, - _deploy_signer: Address, -) -> Result<(), KeylessDeployError> { - if ctx.spec.is_enabled(MegaSpecId::REX5) { - apply_sandbox_state_journaled(ctx, sandbox_state) - } else { - apply_sandbox_state_legacy(ctx, &sandbox_state); - Ok(()) - } -} - -/// Applies sandbox state with the pre-Rex5 direct merge. -/// -/// This intentionally bypasses revm journal entries to preserve historical replay semantics for -/// stable specs. -fn apply_sandbox_state_legacy( - ctx: &mut MegaContext, - sandbox_state: &EvmState, -) { - let journal = ctx.journal_mut(); - merge_evm_state_optional_status(&mut journal.state, sandbox_state, false); -} - -/// Applies sandbox state through an internal journal checkpoint. -/// -/// The checkpoint makes defensive merge errors atomic: partial journal entries are reverted before -/// the error is returned, while successful entries are committed into the caller's active -/// checkpoint. -fn apply_sandbox_state_journaled( - ctx: &mut MegaContext, - sandbox_state: EvmState, -) -> Result<(), KeylessDeployError> { - let journal = ctx.journal_mut(); - let checkpoint = journal.inner.checkpoint(); - match apply_sandbox_state_journaled_inner(journal, sandbox_state) { - Ok(()) => { - journal.inner.checkpoint_commit(); - Ok(()) - } - Err(error) => { - journal.inner.checkpoint_revert(checkpoint); - Err(error) - } - } -} - -/// Replays sandbox account diffs into the parent journal as revm journal entries. -/// -/// Stateful diffs become revertible by any enclosing frame checkpoint. Read/cache-only accounts, -/// bytecode, and storage slots may remain in the parent journal cache for witness generation. -fn apply_sandbox_state_journaled_inner( - journal: &mut Journal, - sandbox_state: EvmState, -) -> Result<(), KeylessDeployError> { - for (address, sandbox_account) in &sandbox_state { - // Ensure the account is loaded into the parent journal cache without warming it. - // Sandbox state merge must preserve the parent's own observable coldness-dependent gas - // semantics. `load_code = false` — this path doesn't read `info.code`. - journal.inspect_account(*address, false).map_err(|e| { - error!( - error = %e, - address = ?address, - "sandbox merge inspect_account failed", - ); - KeylessDeployError::InternalError - })?; - - if sandbox_account.is_selfdestructed() { - apply_sandbox_created_selfdestruct(journal, *address, sandbox_account)?; - continue; - } - - // Snapshot parent state before applying diffs. - let parent_balance = journal.inner.state.get(address).unwrap().info.balance; - let parent_nonce = journal.inner.state.get(address).unwrap().info.nonce; - let parent_code_hash = journal.inner.state.get(address).unwrap().info.code_hash; - - if sandbox_account.is_created() { - ensure_sandbox_create_can_merge(parent_nonce, parent_code_hash)?; - mark_account_created_for_sandbox_merge(journal, *address); - zero_parent_storage_absent_from_sandbox(journal, *address, sandbox_account); - } - - // Balance diff. - if sandbox_account.info.balance != parent_balance { - journal.inner.journal.push(JournalEntry::BalanceChange { - address: *address, - old_balance: parent_balance, - }); - journal.inner.state.get_mut(address).unwrap().info.balance = - sandbox_account.info.balance; - } - - if sandbox_account.info.nonce < parent_nonce { - error!( - address = ?address, - parent_nonce, - sandbox_nonce = sandbox_account.info.nonce, - "sandbox merge would decrease parent account nonce", - ); - return Err(KeylessDeployError::InternalError); - } - - // Nonce diff (one NonceChange entry per increment for correct revert). - let nonce_diff = sandbox_account.info.nonce - parent_nonce; - for _ in 0..nonce_diff { - journal.inner.journal.push(JournalEntry::NonceChange { address: *address }); - } - if nonce_diff > 0 { - journal.inner.state.get_mut(address).unwrap().info.nonce = sandbox_account.info.nonce; - } - - // Code diff. - if sandbox_account.info.code_hash == parent_code_hash { - // Treat empty cached bytecode as missing: when `code_hash != KECCAK_EMPTY` but the - // parent's loaded `info.code` is empty, the cache is stale (e.g. an `EmptyDB` returned - // a default Bytecode for the hash) and should be replaced by the sandbox's real load. - let parent_code_missing = journal - .inner - .state - .get(address) - .unwrap() - .info - .code - .as_ref() - .is_none_or(|code| code.is_empty()); - if parent_code_hash != KECCAK_EMPTY && parent_code_missing { - if let Some(code) = &sandbox_account.info.code { - // Preserve the old merge behavior for read-only code loads: bytecode cached by - // the sandbox is witness/cache metadata, not a stateful code change. - journal.inner.state.get_mut(address).unwrap().info.code = Some(code.clone()); - } - } - } else { - if parent_code_hash != KECCAK_EMPTY { - error!( - address = ?address, - "sandbox merge would replace non-empty parent code", - ); - return Err(KeylessDeployError::InternalError); - } - let Some(code) = &sandbox_account.info.code else { - error!( - address = ?address, - "sandbox account changed code hash without bytecode", - ); - return Err(KeylessDeployError::InternalError); - }; - journal.inner.set_code_with_hash( - *address, - code.clone(), - sandbox_account.info.code_hash, - ); - } - - // Touch — sandbox-modified accounts are genuinely touched in the parent tx. - if sandbox_account.is_touched() { - journal.inner.touch(*address); - } - - // Storage merge mirrors `merge_evm_state_optional_status(..., false)`: existing - // parent slots keep their original/cold metadata and only `present_value` changes; - // slots absent from the parent are inserted as cold, including read-only slots. - for (key, sandbox_slot) in &sandbox_account.storage { - let parent_slot = - journal.inner.state.get(address).and_then(|a| a.storage.get(key)).cloned(); - let had_value = parent_slot - .as_ref() - .map(|slot| slot.present_value) - .unwrap_or_else(|| sandbox_slot.original_value()); - if sandbox_slot.present_value != had_value { - journal.inner.journal.push(JournalEntry::StorageChanged { - key: *key, - had_value, - address: *address, - }); - } - - if let Some(parent_slot) = - journal.inner.state.get_mut(address).unwrap().storage.get_mut(key) - { - parent_slot.present_value = sandbox_slot.present_value; - } else { - let mut merged_slot = sandbox_slot.clone(); - merged_slot.mark_cold(); - journal.inner.state.get_mut(address).unwrap().storage.insert(*key, merged_slot); - } - } - } - - Ok(()) -} - -/// Validates that a sandbox-created account can be merged as a new parent account. -/// -/// Creating over an account with nonce or code would not match EVM `CREATE` semantics and is -/// treated as an internal merge invariant violation. -fn ensure_sandbox_create_can_merge( - parent_nonce: u64, - parent_code_hash: alloy_primitives::B256, -) -> Result<(), KeylessDeployError> { - if parent_nonce != 0 || parent_code_hash != KECCAK_EMPTY { - error!( - parent_nonce, - parent_code_hash = ?parent_code_hash, - "sandbox merge would create over non-empty parent account", - ); - return Err(KeylessDeployError::InternalError); - } - Ok(()) -} - -/// Marks an account as locally created and records the matching journal entry. -/// -/// The `AccountCreated` entry is required so final commit clears stale database storage and -/// checkpoint revert restores the previous account status. -fn mark_account_created_for_sandbox_merge( - journal: &mut Journal, - address: Address, -) { - let is_created_globally = journal.inner.state.get_mut(&address).unwrap().mark_created_locally(); - journal.inner.journal.push(JournalEntry::AccountCreated { address, is_created_globally }); -} - -/// Clears loaded parent storage slots that are absent from a sandbox-created account. -/// -/// A created account replaces any stale storage at the same address, so parent slots not present in -/// the sandbox result must be journaled to zero before commit. -fn zero_parent_storage_absent_from_sandbox( - journal: &mut Journal, - address: Address, - sandbox_account: &revm::state::Account, -) { - let parent_keys = - journal.inner.state.get(&address).unwrap().storage.keys().copied().collect::>(); - - for key in parent_keys { - if sandbox_account.storage.contains_key(&key) { - continue; - } - zero_parent_storage_slot(journal, address, key); - } -} - -/// Journals a loaded parent storage slot to zero when it still has a non-zero value. -fn zero_parent_storage_slot( - journal: &mut Journal, - address: Address, - key: U256, -) { - let had_value = journal - .inner - .state - .get(&address) - .and_then(|account| account.storage.get(&key)) - .map(|slot| slot.present_value()) - .unwrap_or_default(); - if had_value.is_zero() { - return; - } - journal.inner.journal.push(JournalEntry::StorageChanged { key, had_value, address }); - journal.inner.state.get_mut(&address).unwrap().storage.get_mut(&key).unwrap().present_value = - U256::ZERO; -} - -/// Applies the merge result for an account created and selfdestructed inside the sandbox. -/// -/// The parent commit must observe an empty created account: existing balance and loaded storage are -/// journaled to zero while the created marker is preserved. -fn apply_sandbox_created_selfdestruct( - journal: &mut Journal, - address: Address, - sandbox_account: &revm::state::Account, -) -> Result<(), KeylessDeployError> { - if !sandbox_account.is_created() { - error!( - address = ?address, - "sandbox selfdestructed account was not created in the sandbox", - ); - return Err(KeylessDeployError::InternalError); - } - - let parent = journal.inner.state.get(&address).unwrap(); - ensure_sandbox_create_can_merge(parent.info.nonce, parent.info.code_hash)?; - - mark_account_created_for_sandbox_merge(journal, address); - journal.inner.touch(address); - - let old_balance = journal.inner.state.get(&address).unwrap().info.balance; - if !old_balance.is_zero() { - journal.inner.journal.push(JournalEntry::BalanceChange { address, old_balance }); - journal.inner.state.get_mut(&address).unwrap().info.balance = U256::ZERO; - } - - let parent_keys = - journal.inner.state.get(&address).unwrap().storage.keys().copied().collect::>(); - for key in parent_keys { - zero_parent_storage_slot(journal, address, key); - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, Bytes}; - use revm::{ - context_interface::journaled_state::JournalTr, - database::EmptyDB, - state::{Account, AccountInfo, EvmStorageSlot}, - Database, DatabaseCommit, - }; - - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - - fn sandbox_created_account(code: Bytes) -> Account { - let code = revm::bytecode::Bytecode::new_raw(code); - let code_hash = revm::primitives::keccak256(code.bytes_slice()); - let mut account = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash, - code: Some(code), - }); - account.mark_touch(); - account.mark_created(); - account - } - - #[test] - fn test_rex4_apply_sandbox_state_uses_legacy_direct_merge() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX4); - let checkpoint = JournalTr::checkpoint(ctx.journal_mut()); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - account - .storage - .insert(U256::from(0), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let journal = ctx.journal_mut(); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_created(), - "legacy merge should preserve created status for a newly inserted account" - ); - - JournalTr::checkpoint_revert(journal, checkpoint); - assert!( - journal.inner.state.contains_key(&deploy_addr), - "pre-Rex5 keeps the legacy direct-merge semantics instead of journal rollback" - ); - } - - /// Proves that `apply_sandbox_state` records journal entries for stateful diffs: - /// after a checkpoint-revert the parent values are restored, while revm may keep - /// cold cache/read-set entries that are not committed as state changes. - #[test] - fn test_rex5_apply_sandbox_state_revert_restores_parent() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let getter_addr = address!("cccccccccccccccccccccccccccccccccccc0003"); - let original_balance = U256::from(1_000_000u64); - let read_only_slot = U256::from(7); - let read_only_value = U256::from(123); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - - // Seed signer in parent state with known balance and nonce. - journal.inner.state.insert(signer, { - let mut acc = Account::from(AccountInfo { - balance: original_balance, - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - acc.mark_touch(); - acc - }); - let getter_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x01])); - let getter_code_hash = revm::primitives::keccak256(getter_code.bytes_slice()); - journal.inner.state.insert(getter_addr, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: getter_code_hash, - code: None, - }); - acc.mark_cold(); - acc - }); - - // Take a checkpoint before applying sandbox state. - let checkpoint = JournalTr::checkpoint(journal); - - // Build sandbox state: signer paid gas (lower balance, nonce bumped), - // deploy_addr is a new account with code and a storage slot. - let mut sandbox_state = EvmState::default(); - - // Signer: balance decreased, nonce = 1. - sandbox_state.insert(signer, { - let mut acc = Account::from(AccountInfo { - balance: U256::from(500_000u64), - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }); - acc.mark_touch(); - acc - }); - - // Deploy address: new account with code and storage. - sandbox_state.insert(deploy_addr, { - let mut acc = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - acc.storage - .insert(U256::from(0), EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - acc - }); - sandbox_state.insert(getter_addr, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 1, - code_hash: getter_code_hash, - code: Some(getter_code), - }); - acc.storage.insert(read_only_slot, EvmStorageSlot::new(read_only_value, 0)); - acc - }); - - // Apply sandbox state — should record journal entries. - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - - // Verify merge applied. - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.balance, - U256::from(500_000u64), - "signer balance should reflect sandbox deduction" - ); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.nonce, - 1, - "signer nonce should be bumped" - ); - assert!( - journal.inner.state.contains_key(&deploy_addr), - "deploy address should exist after merge" - ); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_created(), - "created account status must be preserved for final commit" - ); - assert!( - journal.inner.state.get(&signer).unwrap().is_touched(), - "stateful signer diff should leave signer touched" - ); - assert!( - journal.inner.state.get(&deploy_addr).unwrap().is_touched(), - "stateful deploy diff should leave deployed account touched" - ); - assert!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .info - .code - .as_ref() - .is_some_and(|code| !code.is_empty()), - "read-only bytecode loaded by sandbox should be cached for witnesses" - ); - assert_eq!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .storage - .get(&read_only_slot) - .map(|slot| slot.present_value()), - Some(read_only_value), - "read-only storage loaded by sandbox should be cached for witnesses" - ); - - // Revert to checkpoint — should undo all sandbox state changes. - JournalTr::checkpoint_revert(journal, checkpoint); - - // Verify parent state is restored. - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.balance, - original_balance, - "signer balance should be restored after revert" - ); - assert_eq!( - journal.inner.state.get(&signer).unwrap().info.nonce, - 0, - "signer nonce should be restored after revert" - ); - // deploy_addr was loaded from EmptyDB by apply_sandbox_state, so it can remain in - // the cache (AccountWarmed revert marks it cold, but does not remove it). Its - // stateful values must still be reverted. - if let Some(deploy_account) = journal.inner.state.get(&deploy_addr) { - assert_eq!( - deploy_account.info.code_hash, KECCAK_EMPTY, - "deployed code should be reverted" - ); - assert_eq!(deploy_account.info.nonce, 0, "deploy address nonce should be reverted"); - assert_eq!( - deploy_account.storage.get(&U256::from(0)).map(|slot| slot.present_value()), - Some(U256::ZERO), - "deployed storage should be reverted to the pre-sandbox value" - ); - } - assert!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .info - .code - .as_ref() - .is_some_and(|code| !code.is_empty()), - "read-only bytecode cache may remain after revert" - ); - assert_eq!( - journal - .inner - .state - .get(&getter_addr) - .unwrap() - .storage - .get(&read_only_slot) - .map(|slot| slot.present_value()), - Some(read_only_value), - "read-only storage cache may remain after revert without becoming a stateful diff" - ); - } - - #[test] - fn test_rex5_apply_sandbox_state_error_reverts_partial_merge() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let original_balance = U256::from(1_000_000u64); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - journal.inner.state.insert(target, { - Account::from(AccountInfo { - balance: original_balance, - nonce: 1, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - let journal_len_before = journal.inner.journal.len(); - let depth_before = journal.inner.depth; - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut account = Account::from(AccountInfo { - balance: U256::from(500_000u64), - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - account.mark_touch(); - account - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("nonce decrease should fail defensively"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&target).unwrap().info.balance, - original_balance, - "partial balance diff must be reverted on merge error" - ); - assert_eq!( - journal.inner.state.get(&target).unwrap().info.nonce, - 1, - "parent nonce must be restored on merge error" - ); - assert_eq!( - journal.inner.journal.len(), - journal_len_before, - "partial journal entries must be removed on merge error" - ); - assert_eq!(journal.inner.depth, depth_before, "checkpoint depth must be balanced"); - } - - #[test] - fn test_rex5_apply_sandbox_state_created_commit_clears_stale_storage() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let stale_slot = U256::from(9); - let deployed_slot = U256::from(0); - let mut db = MemoryDatabase::default(); - db.set_account_storage(deploy_addr, stale_slot, U256::from(99)); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = sandbox_created_account(Bytes::from_static(&[0x60, 0x00])); - account - .storage - .insert(deployed_slot, EvmStorageSlot::new_changed(U256::ZERO, U256::from(42), 0)); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let state = JournalTr::finalize(ctx.journal_mut()); - ctx.db_mut().commit(state); - - assert_eq!( - ctx.db_mut().storage(deploy_addr, deployed_slot).unwrap(), - U256::from(42), - "deployed storage should be committed" - ); - assert_eq!( - ctx.db_mut().storage(deploy_addr, stale_slot).unwrap(), - U256::ZERO, - "created-account commit must clear stale database storage" - ); - } - - #[test] - fn test_rex5_apply_sandbox_state_created_selfdestruct_revert_restores_parent() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - let original_balance = U256::from(7); - let storage_slot = U256::from(3); - let original_storage = U256::from(11); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - let journal = ctx.journal_mut(); - journal.inner.state.insert(deploy_addr, { - let mut account = Account::from(AccountInfo { - balance: original_balance, - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }); - account.storage.insert(storage_slot, EvmStorageSlot::new(original_storage, 0)); - account - }); - let checkpoint = JournalTr::checkpoint(journal); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(deploy_addr, { - let mut account = Account::from(AccountInfo::default()); - account.mark_touch(); - account.mark_created(); - account.mark_selfdestruct(); - account - }); - - apply_sandbox_state(&mut ctx, sandbox_state, signer).expect("apply should succeed"); - let journal = ctx.journal_mut(); - assert_eq!( - journal.inner.state.get(&deploy_addr).unwrap().info.balance, - U256::ZERO, - "created+selfdestructed account should be empty after merge" - ); - assert_eq!( - journal - .inner - .state - .get(&deploy_addr) - .unwrap() - .storage - .get(&storage_slot) - .unwrap() - .present_value(), - U256::ZERO, - "created+selfdestructed account should clear loaded parent storage" - ); - - JournalTr::checkpoint_revert(journal, checkpoint); - - let restored = journal.inner.state.get(&deploy_addr).unwrap(); - assert_eq!( - restored.info.balance, original_balance, - "balance should be restored after revert" - ); - assert_eq!( - restored.storage.get(&storage_slot).unwrap().present_value(), - original_storage, - "storage should be restored after revert" - ); - assert!(!restored.is_created(), "created marker should be reverted with the checkpoint"); - } - - /// Parent has non-empty code and the sandbox attempts to install a different code - /// hash — defensive merge MUST reject. Pinned because silently overwriting code on a - /// live account would let a keyless deploy hijack any address whose code happened to - /// be loaded into the cache during the parent's prior steps. - #[test] - fn test_rex5_apply_sandbox_state_rejects_non_empty_parent_code_replacement() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - // Parent: an existing contract with non-empty code. - let parent_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x01])); - let parent_code_hash = revm::primitives::keccak256(parent_code.bytes_slice()); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(target, { - Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - code_hash: parent_code_hash, - code: Some(parent_code), - }) - }); - - // Sandbox: tries to replace with a different code hash. - let sandbox_code = revm::bytecode::Bytecode::new_raw(Bytes::from_static(&[0x60, 0x02])); - let sandbox_code_hash = revm::primitives::keccak256(sandbox_code.bytes_slice()); - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - code_hash: sandbox_code_hash, - code: Some(sandbox_code), - }); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject code replacement"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// Sandbox account reports a non-empty `code_hash` but no `info.code` payload. - /// Defensive merge MUST reject because the inner `set_code_with_hash` call would - /// otherwise panic / silently install no bytecode. - #[test] - fn test_rex5_apply_sandbox_state_rejects_code_hash_without_bytecode() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - // Parent: empty (KECCAK_EMPTY) so the "different code_hash, parent is empty" branch fires. - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo { - balance: U256::ZERO, - nonce: 0, - // Non-empty code_hash but `code: None` — exactly the invariant violation. - code_hash: revm::primitives::keccak256([0x60u8, 0x00]), - code: None, - }); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject mismatched code_hash without bytecode"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `ensure_sandbox_create_can_merge`: sandbox is marked `is_created()` but the - /// parent already has a non-zero nonce (not an empty slot). Defensive merge MUST - /// reject — committing a CREATE over an existing account would silently overwrite - /// its on-chain state. - #[test] - fn test_rex5_apply_sandbox_state_rejects_create_over_non_empty_parent_nonce() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let deploy_addr = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(deploy_addr, { - Account::from(AccountInfo { - balance: U256::ZERO, - // Non-zero nonce triggers the rejection. - nonce: 5, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - - let mut sandbox_state = EvmState::default(); - sandbox_state - .insert(deploy_addr, sandbox_created_account(Bytes::from_static(&[0x60, 0x00]))); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject CREATE over non-empty parent"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `inspect_account` may surface a `DBError` (the DB call fails mid-merge). The - /// merge MUST translate that into the selector-only `InternalError` and revert any - /// partial journal entries via the inner checkpoint. Without this guard a DB blip - /// could leave a partially merged sandbox state in the parent journal. - #[test] - fn test_rex5_apply_sandbox_state_db_error_during_inspect_maps_to_internal_error() { - use crate::test_utils::ErrorInjectingDatabase; - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); - // The merge's first DB-touching step is the `inspect_account` call for each - // sandbox-modified address. Fail that lookup for `target`. - db.fail_on_account = Some(target); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(db, MegaSpecId::REX5); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo::default()); - acc.mark_touch(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("inspect_account DB error must surface as InternalError"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } - - /// `apply_sandbox_created_selfdestruct` guard: sandbox account is selfdestructed - /// but NOT marked `is_created()`. That's not a same-tx CREATE+SELFDESTRUCT — it's - /// the sandbox trying to wipe an account that existed before the keyless tx. - /// Defensive merge MUST reject. - #[test] - fn test_rex5_apply_sandbox_state_rejects_selfdestruct_without_created_marker() { - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let target = address!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb0002"); - - let mut ctx = MegaContext::<_, EmptyExternalEnv>::new(EmptyDB::default(), MegaSpecId::REX5); - ctx.journal_mut().inner.state.insert(target, { - Account::from(AccountInfo { - balance: U256::from(1u64), - nonce: 0, - code_hash: KECCAK_EMPTY, - code: None, - }) - }); - - let mut sandbox_state = EvmState::default(); - sandbox_state.insert(target, { - let mut acc = Account::from(AccountInfo::default()); - acc.mark_touch(); - // No `mark_created()`: this is the invariant violation. - acc.mark_selfdestruct(); - acc - }); - - let error = apply_sandbox_state(&mut ctx, sandbox_state, signer) - .expect_err("merge must reject selfdestruct without created marker"); - assert!(matches!(error, KeylessDeployError::InternalError), "unexpected error: {error:?}"); - } -} diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md deleted file mode 100644 index dd2ad6442..000000000 --- a/crates/mega-evm/src/system/AGENTS.md +++ /dev/null @@ -1,57 +0,0 @@ -# AGENTS.md - -## OVERVIEW -System contract integration layer with canonical addresses, deployment transactions, and frame-init interception logic. - -## STRUCTURE -- `deploy.rs`: shared deployment primitive — declarative `SystemContractSpec`, the uniform `transact_deploy` state patch, and the `flat_system_contract_specs()` registry of all flat (storage-less) contracts. -- `oracle.rs`: oracle contract address, code constants, spec builder. -- `keyless_deploy.rs`: keyless deploy address, code constants, spec builder. -- `control.rs`: MegaAccessControl address, selectors, spec builder, revert payload builders. -- `limit_control.rs`: MegaLimitControl address and spec builder. -- `sequencer_registry.rs`: SequencerRegistry address, seeded deploy, role-change application, system-address resolution. -- `intercept.rs`: interceptor dispatch and synthetic frame-result handling. -- `tx.rs`: helpers for system/deposit-like transaction construction. - -## KEY PATTERNS -- Deployment helpers are idempotent and keyed by code hash equality. -- Gating happens in each contract's `_spec()` builder, which takes the resolved `MegaSpecId` and gates on `spec.reaches(...)` — POSITION comparison, so alias (rollback) windows do not retract deploys. Nothing in the deploy layer takes a hardfork config — the spec builders and the crate-private `*_for` helpers receive the resolved spec and typed params, so a per-fork activation gate cannot be reintroduced. The `pub` `transact_deploy_*` wrappers keep their `(hardforks, block_timestamp)` shape for external callers and resolve everything themselves. -- Builders must never gate on `is_enabled` (behavior): predeploys are one-way, and a hardfork that rolls behavior back does not un-deploy them or change which bytecode version is expected to be installed. -- Interceptors return `None` to fall through to on-chain bytecode on unknown selectors. -- View/control interceptors reject non-zero transfer values with `NonZeroTransfer()`. -- Synthetic interceptor results bypass normal child-frame init and require empty tracking frame push by caller. -- Keep selector constants and ABI encode/decode paths aligned with `mega-system-contracts` interfaces. -- Pre-block helpers (`transact_deploy_*`, `transact_apply_pending_changes`, etc.) return `Option` and let the block executor commit. They never call `db.commit(...)` directly — the executor fires `system_caller.on_state(source, &state)` between collection and commit, and that hook feeds the stateless witness generator. See `PRE-BLOCK STATE CHANGE CONTRACT` below. - -## PRE-BLOCK STATE CHANGE CONTRACT - -Pre-block helpers in this module participate in the `pre_execution_changes` → `commit_system_call_outcomes` pipeline on `MegaBlockExecutor`. The contract for a new or modified helper: - -- **Never call `db.commit(...)` inside the helper.** Return the prepared state; let the executor commit. -- **Return `Ok(None)` only when the step is gated out entirely** — wrong hardfork, feature disabled, etc. Not as an "already up to date" shortcut. -- **On an idempotent no-change path** (e.g., the contract is already deployed with the correct code hash), return `Some(EvmState)` that carries the observed account as a read-only entry: `Account { info, ..Default::default() }` with no `touched`/`created` flags. Returning `None` here is a bug — the account disappears from the stateless witness read set and the generated proof is incomplete. -- **On a real-change path**, include every account and storage slot the helper touched, including slots read in preparation for the change. The witness recorder must see the complete set. - -The returned `EvmState` serves two purposes, both load-bearing: - -1. **Commit** — `db.commit(state)` applies the writes. -2. **Witness recording** — `system_caller.on_state(source, &state)` runs before commit and feeds the stateless witness generator with the full read/write set for that outcome. Without this, a stateless client cannot verify the block against its pre-state. - -The counterpart block-executor side (collection, `on_state`, commit order) is documented in `crates/mega-evm/src/block/AGENTS.md`. - -## ANTI-PATTERNS -- Do not intercept unknown selectors with a synthetic revert unless spec requires it. -- Preserve on-chain-bytecode fallback for unknown calls. -- Do not accept value transfers for view/control interceptors unless explicitly specified and tested. -- Do not deploy system bytecode by raw literals in this crate. -- Reuse constants generated by `mega-system-contracts`. -- Do not call `db.commit(...)` inside a helper that participates in `pre_execution_changes`. It bypasses the `on_state` witness-recorder hook and silently produces incomplete stateless proofs. -- Do not return `None` from a helper on a "no change needed" path. Return `Some(EvmState)` with the account entries observed, even when nothing is written. - -## WHERE TO LOOK -- Add a new flat (storage-less) system contract deployment: new `.rs` with a `_spec()` builder, registered in `deploy.rs::flat_system_contract_specs()`. -- Add a stateful system contract with bespoke deploy logic (seeded storage, migration guards): own `transact_deploy_*` helper called from `block/executor.rs::pre_execution_changes` — see `sequencer_registry.rs`. -- Add interceptor method behavior: `intercept.rs` for decode/dispatch and revert policy. -- Change access-control volatile disable semantics: `control.rs` + `intercept.rs` + `access/tracker.rs`. -- Change keyless deploy interception entrypoint: `intercept.rs` and `keyless_deploy.rs`. -- Update system contract address or code hash references: corresponding module constant definitions. diff --git a/crates/mega-evm/src/system/deploy.rs b/crates/mega-evm/src/system/deploy.rs deleted file mode 100644 index 1b9a753f1..000000000 --- a/crates/mega-evm/src/system/deploy.rs +++ /dev/null @@ -1,386 +0,0 @@ -//! Shared primitive for deploying `MegaETH` system (predeploy) contracts. -//! -//! Every system contract is materialized by the same state patch: set the -//! predeploy account's bytecode (idempotently, keyed on code hash), optionally -//! seed flat storage slots, and mark the account touched (and created on a fresh -//! deploy). The only things that differ per contract are the address, the -//! bytecode (which can vary by spec, e.g. the Oracle's v1.0.0 → v1.1.0 → v2.0.0 -//! line), whether an in-place upgrade should still mark the account created, and -//! whether any storage is seeded. -//! -//! [`SystemContractSpec`] captures those differences declaratively and -//! [`transact_deploy`] applies them uniformly, so the per-contract -//! `transact_deploy_*` wrappers and external tooling (foundry, `mega-evme`) share -//! one deployment path instead of re-implementing the pattern. -//! -//! Like the per-contract functions, `transact_deploy` does NOT commit to the -//! database — it returns the [`EvmState`] witness for the caller to commit. - -#[cfg(not(feature = "std"))] -use alloc as std; - -use alloy_evm::Database; -use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; -use revm::{ - database::State, - state::{Account, Bytecode, EvmState, EvmStorageSlot}, -}; -use std::vec::Vec; - -use crate::{MegaHardforks, MegaSpecId}; - -/// Declarative description of a single system-contract deployment. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SystemContractSpec { - /// Predeploy address the bytecode is installed at. - pub address: Address, - /// Runtime bytecode to install (already version-selected for the spec). - pub code: Bytes, - /// Keccak-256 hash of `code`. Used for the idempotence check. - pub code_hash: B256, - /// Flat storage slots to seed `(slot, value)` on a fresh deploy. Empty for - /// every contract except the `SequencerRegistry`. - pub seed: Vec<(U256, U256)>, - /// Whether an in-place bytecode upgrade of an already-existing account should - /// still mark it `created` (which clears its storage on commit). - /// - /// - `false` for the standard contracts (an upgrade preserves storage). - /// - For the Oracle this is `true` pre-Rex5 and `false` on Rex5+, preserving the canonical - /// mainnet state at the Rex2 boundary. - /// - `true` for the `SequencerRegistry` (always a fresh, seeded deploy). - pub force_create_on_upgrade: bool, -} - -impl SystemContractSpec { - /// A spec with no seeded storage and standard (storage-preserving) upgrade - /// semantics. - pub fn new(address: Address, code: Bytes, code_hash: B256) -> Self { - Self { address, code, code_hash, seed: Vec::new(), force_create_on_upgrade: false } - } - - /// Sets the seeded storage slots applied on a fresh deploy. - /// - /// Seeding applies only when the account is (re)created — a fresh deploy, or - /// an in-place upgrade with - /// [`with_force_create_on_upgrade`](Self::with_force_create_on_upgrade). A non-empty seed - /// on a storage-preserving upgrade is therefore ignored. - pub fn with_seed(mut self, seed: Vec<(U256, U256)>) -> Self { - self.seed = seed; - self - } - - /// Sets whether an in-place upgrade marks the account created. - pub fn with_force_create_on_upgrade(mut self, force: bool) -> Self { - self.force_create_on_upgrade = force; - self - } -} - -/// Deploys a system contract described by `spec`, returning the [`EvmState`] -/// witness (account + any seeded storage). The caller commits it. -/// -/// If the contract is already deployed with the matching code hash, the account -/// is returned read-only (marked neither touched nor created, no seeding) so it -/// is recorded in the witness without changing state. -pub fn transact_deploy( - db: &mut State, - spec: &SystemContractSpec, -) -> Result { - // The spec's `code_hash` must be the hash of its `code`. The per-contract - // `*_spec` builders derive both from one bytecode constant, so this only - // guards against a future hand-built spec installing code under a wrong hash. - debug_assert_eq!( - keccak256(spec.code.as_ref()), - spec.code_hash, - "SystemContractSpec code_hash does not match code for {:?}", - spec.address - ); - - let acc = db.load_cache_account(spec.address)?; - - // Already deployed with the correct code — record the read, change nothing. - let existing_info = acc.account_info(); - if let Some(account_info) = &existing_info { - if account_info.code_hash == spec.code_hash { - return Ok(EvmState::from_iter([( - spec.address, - Account { info: account_info.clone(), ..Default::default() }, - )])); - } - } - - let account_existed = existing_info.is_some(); - let mut acc_info = existing_info.unwrap_or_default(); - acc_info.code_hash = spec.code_hash; - acc_info.code = Some(Bytecode::new_raw(spec.code.clone())); - - let mut revm_acc: Account = acc_info.into(); - revm_acc.mark_touch(); - // Mark created on a fresh deploy, or when the contract opts to clear storage - // on an in-place upgrade. Not marking created preserves existing storage. - if !account_existed || spec.force_create_on_upgrade { - revm_acc.mark_created(); - // Seed only on (re)creation. Seeding onto an account whose storage is - // preserved (an in-place upgrade) would mix genesis slots into live - // storage and record a wrong `original_value` for an already-set slot. - for (slot, value) in &spec.seed { - revm_acc.storage.insert(*slot, EvmStorageSlot::new_changed(U256::ZERO, *value, 0)); - } - } - - Ok(EvmState::from_iter([(spec.address, revm_acc)])) -} - -/// Returns the deploy descriptors for the "flat" system contracts active at the -/// given block timestamp, in deploy order: Oracle, high-precision timestamp -/// Oracle, `KeylessDeploy`, `MegaAccessControl`, `MegaLimitControl`. -/// -/// This is the canonical, single-source-of-truth list both the block executor -/// and `mega-evme` iterate to materialize predeploys, instead of each hardcoding -/// the per-contract gate and bytecode selection. -/// -/// The `SequencerRegistry` (Rex5) is intentionally excluded: it seeds storage -/// from chain-config parameters, guards against overwriting foreign state, and is -/// paired with a pre-block `applyPendingChanges` system call — see -/// [`transact_deploy_sequencer_registry`](crate::transact_deploy_sequencer_registry). -pub fn flat_system_contract_specs( - hardforks: impl MegaHardforks, - block_timestamp: u64, -) -> Vec { - flat_system_contract_specs_for(hardforks.spec_id(block_timestamp)) -} - -/// [`flat_system_contract_specs`] against an already-resolved spec. -/// -/// The block executor resolves the spec once per block and calls this directly; the public -/// wrapper above resolves it for callers that hold a hardfork config. -pub(crate) fn flat_system_contract_specs_for(spec: MegaSpecId) -> Vec { - // Compose the per-contract spec builders (each its own single source of gate - // + bytecode-version selection). `None` entries (inactive contracts) drop out. - [ - super::oracle::oracle_spec(spec), - super::oracle::high_precision_timestamp_oracle_spec(spec), - super::keyless_deploy::keyless_deploy_spec(spec), - super::control::access_control_spec(spec), - super::limit_control::limit_control_spec(spec), - ] - .into_iter() - .flatten() - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - MegaHardfork, MegaHardforkConfig, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX2, - ORACLE_CONTRACT_CODE_HASH_REX5, - }; - use alloy_hardforks::ForkCondition; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, Database as _, DatabaseCommit}; - - fn addrs(specs: &[SystemContractSpec]) -> Vec
{ - specs.iter().map(|s| s.address).collect() - } - - const SEEDED_ADDR: Address = address!("0x6342000000000000000000000000000000000099"); - const SEED_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); - const UNRELATED_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); - - /// Builds a spec whose code hash differs from any pre-existing account, so - /// `transact_deploy` takes the bytecode-upgrade path rather than the - /// idempotent early return. - fn seeded_spec(force_create_on_upgrade: bool) -> SystemContractSpec { - let code = Bytes::from_static(&[0x60, 0x00]); - let code_hash = keccak256(&code); - SystemContractSpec::new(SEEDED_ADDR, code, code_hash) - .with_seed(Vec::from([(SEED_SLOT, U256::from(42))])) - .with_force_create_on_upgrade(force_create_on_upgrade) - } - - /// An in-place upgrade that does NOT recreate the account must not write seed - /// slots: doing so would mix genesis storage into preserved live storage and - /// record a wrong `original_value`. Guards the `force_create_on_upgrade = - /// false` + non-empty `seed` configuration that no current contract uses. - #[test] - fn test_seed_skipped_on_storage_preserving_upgrade() { - let mut db = InMemoryDB::default(); - // Pre-existing account with different bytecode (so the upgrade path runs) - // and a live value at the slot the spec would otherwise seed. - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - db.insert_account_storage(SEEDED_ADDR, SEED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_touched()); - assert!(!account.is_created(), "storage-preserving upgrade must not recreate"); - assert!( - !account.storage.contains_key(&SEED_SLOT), - "seed must not be written when storage is preserved" - ); - - // Committing the upgrade must leave the pre-existing slot at its old value. - state.commit(result); - assert_eq!( - state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), - U256::from(99), - "preserved storage must keep its pre-upgrade value after commit" - ); - } - - /// The same spec with `force_create_on_upgrade = true` recreates the account - /// and therefore does seed — the path the `SequencerRegistry` relies on. - #[test] - fn test_seed_written_on_force_created_upgrade() { - let mut db = InMemoryDB::default(); - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - // An unrelated live slot that recreation must clear. - db.insert_account_storage(SEEDED_ADDR, UNRELATED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(true)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "force_create_on_upgrade must recreate"); - let slot = account.storage.get(&SEED_SLOT).expect("seed slot must be written"); - assert_eq!(slot.present_value, U256::from(42)); - assert_eq!(slot.original_value, U256::ZERO); - - // Recreation clears prior storage: after commit the seed slot holds its - // value and the unrelated pre-existing slot reads back as zero. - state.commit(result); - assert_eq!(state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), U256::from(42)); - assert_eq!( - state.storage(SEEDED_ADDR, UNRELATED_SLOT).unwrap(), - U256::ZERO, - "recreation must clear unrelated pre-existing storage" - ); - } - - /// A fresh deploy seeds regardless of `force_create_on_upgrade`. - #[test] - fn test_seed_written_on_fresh_deploy() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "fresh deploy creates the account"); - assert_eq!( - account.storage.get(&SEED_SLOT).expect("seed slot must be written").present_value, - U256::from(42) - ); - } - - #[test] - fn test_registry_empty_before_mini_rex() { - // MiniRex activates at timestamp 100; nothing is active before it. - let hf = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)); - assert!(flat_system_contract_specs(&hf, 99).is_empty()); - } - - #[test] - fn test_registry_grows_with_hardforks_and_picks_oracle_version() { - let hf = MegaHardforkConfig::default().with_all_activated(); - let specs = flat_system_contract_specs(&hf, 0); - // Rex5 active → all five flat contracts, in deploy order, Oracle first. - assert_eq!(specs.len(), 5); - assert_eq!(specs[0].address, ORACLE_CONTRACT_ADDRESS); - // Rex5 → Oracle v2.0.0 and NOT force-created on upgrade. - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(!specs[0].force_create_on_upgrade); - // SequencerRegistry is intentionally not in the flat registry. - assert!(!addrs(&specs).contains(&crate::SEQUENCER_REGISTRY_ADDRESS)); - } - - /// Inside mainnet's `MiniRex1` rollback window the registry must still yield both `MiniRex` - /// predeploys. Gating on the executing spec (`EQUIVALENCE` there) would drop them, and with - /// them their read-only witness entries — a replay-observable change on frozen history. - #[test] - fn test_registry_survives_mainnet_rollback_window() { - let hf = crate::mainnet_hardforks(); - let ForkCondition::Timestamp(ts) = hf.mega_fork_activation(MegaHardfork::MiniRex1) else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - - let spec = hf.spec_id(ts); - assert_eq!(spec, crate::MegaSpecId::MINI_REX_1); - assert_eq!(spec.behavior(), crate::MegaSpecId::EQUIVALENCE); - - // The single scheduled spec keeps setup via position comparison even while its - // behavior projects back to EQUIVALENCE. - let specs = flat_system_contract_specs(&hf, ts); - assert_eq!( - addrs(&specs), - [ORACLE_CONTRACT_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS] - ); - // Still the pre-Rex2 bytecode line, with the pre-Rex5 upgrade semantics. - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH); - assert!(specs[0].force_create_on_upgrade); - } - - /// A config that schedules Rex6 without Rex5 must still materialize every lower-spec - /// predeploy, at the Rex5 Oracle version. Under per-fork gating none of them deployed. - #[test] - fn test_registry_complete_on_partial_ladder() { - let hf = MegaHardforkConfig::new() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)); - - assert_eq!( - hf.mega_fork_activation(MegaHardfork::MiniRex), - ForkCondition::Never, - "no lower fork is scheduled" - ); - - let specs = flat_system_contract_specs(&hf, 0); - assert_eq!(specs.len(), 5, "the partial ladder must still deploy all five flat contracts"); - assert_eq!(specs[0].address, ORACLE_CONTRACT_ADDRESS); - assert_eq!(specs[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(!specs[0].force_create_on_upgrade); - } - - #[test] - fn test_registry_oracle_version_by_spec() { - // Only MiniRex active: Oracle v1.0.0, force-created on upgrade (pre-Rex5), - // and just Oracle + high-precision Oracle. - let mini = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let mini = flat_system_contract_specs(&mini, 0); - assert_eq!(mini.len(), 2); - assert_eq!(mini[0].code_hash, ORACLE_CONTRACT_CODE_HASH); - assert!(mini[0].force_create_on_upgrade); - - // Rex2 active but not Rex5: Oracle v1.1.0, still force-created on upgrade. - let rex2 = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - let rex2 = flat_system_contract_specs(&rex2, 0); - assert_eq!(rex2[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); - assert!(rex2[0].force_create_on_upgrade); - } -} diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs deleted file mode 100644 index 6420340e4..000000000 --- a/crates/mega-evm/src/system/intercept.rs +++ /dev/null @@ -1,619 +0,0 @@ -//! Trait and implementations for system contract call interception in `frame_init`. -//! -//! System contracts are intercepted before normal EVM frame initialization. -//! Each interceptor checks whether the call targets its contract address, -//! decodes the ABI input, and either performs a side-effect (returning `None` -//! to continue normal execution) or returns a synthetic [`FrameResult`] to -//! short-circuit frame creation. - -use alloy_evm::Database; -use alloy_primitives::Bytes; -use alloy_sol_types::{SolCall, SolError}; -use revm::{ - context::{ContextTr, LocalContextTr}, - handler::FrameResult, - interpreter::{CallInput, CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult}, -}; - -use crate::{ - sandbox::execute_keyless_deploy_call, ExternalEnvTypes, IKeylessDeploy, IMegaAccessControl, - IMegaLimitControl, IOracle, MegaContext, MegaSpecId, OracleEnv, ACCESS_CONTROL_ADDRESS, - DISABLED_BY_PARENT_REVERT_DATA, KEYLESS_DEPLOY_ADDRESS, LIMIT_CONTROL_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; - -/// The result of a system contract call interception attempt. -/// -/// - `None`: The interceptor did not handle this call. The caller should try the next interceptor -/// or proceed with normal frame initialization. -/// - `Some(FrameResult)`: The interceptor handled the call and produced a synthetic result. The -/// caller should return this as `FrameInitResult::Result` and push an empty frame to keep the -/// limit tracker stack balanced. -pub type InterceptResult = Option; - -alloy_sol_types::sol! { - /// Shared error used by view/control system contract interceptors when value is sent. - error NonZeroTransfer(); -} - -/// Reads the first four bytes of a call input without materializing the full payload. -/// -/// Returns `None` when the input is shorter than four bytes. For -/// [`CallInput::SharedBuffer`], only the four-byte head slice is borrowed from -/// shared memory — the trailing bytes are never read. -#[inline] -fn peek_selector(input: &CallInput, ctx: &CTX) -> Option<[u8; 4]> { - let mut out = [0u8; 4]; - match input { - CallInput::Bytes(bytes) => { - if bytes.len() < 4 { - return None; - } - out.copy_from_slice(&bytes[..4]); - Some(out) - } - CallInput::SharedBuffer(range) => { - if range.len() < 4 { - return None; - } - let head = range.start..range.start + 4; - let slice = ctx.local().shared_memory_buffer_slice(head)?; - out.copy_from_slice(&slice); - Some(out) - } - } -} - -/// Trait for intercepting calls to system contracts during `frame_init`. -/// -/// Implementors check whether an incoming call matches their contract address and function -/// selectors, then either perform a side-effect or return a synthetic result. -/// -/// # Contract -/// -/// - The caller guarantees that `call_inputs` comes from a `FrameInput::Call`. Create frames are -/// never dispatched to interceptors. -/// - When the method returns `Some(FrameResult)`, the caller is responsible for calling -/// `additional_limit.push_empty_frame()` to keep the frame tracker stack balanced. -/// - Returning `Some(FrameResult)` produces a **synthetic** result that bypasses -/// `AdditionalLimit::before_frame_init`. The caller only pushes an empty tracking frame for stack -/// alignment; no per-frame gas adjustments (stipend, compute cap, etc.) are applied. If a future -/// interceptor needs full child-frame gas semantics, it must go through the normal frame -/// lifecycle instead of returning a synthetic result. -/// - When the method returns `None`, the caller proceeds as if no interception occurred. -pub trait SystemContractInterceptor { - /// Attempts to intercept a call to a system contract. - /// - /// # Arguments - /// - /// * `ctx` - The EVM context providing access to all `MegaETH` state. - /// * `call_inputs` - The call inputs (target address, input data, gas limit, caller, etc.). - /// * `depth` - The frame depth from `FrameInit::depth`, which equals the caller's journal - /// depth. - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult; -} - -/// Dispatches system contract interceptors in order. -/// -/// Returns `Some(FrameResult)` if any interceptor handled the call, `None` otherwise. -/// The caller is responsible for calling `push_empty_frame()` when `Some` is returned. -pub fn dispatch_system_contract_interceptors( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, -) -> InterceptResult { - let spec = ctx.spec; - - // Oracle Hint (Rex2+) — side-effect only, never returns Some. - // The assertion makes the invariant explicit so a future change that returns - // Some(FrameResult) is caught in debug builds rather than silently ignored. - if spec.is_enabled(OracleHintInterceptor::ACTIVATION_SPEC) { - let hint_result = OracleHintInterceptor::intercept(ctx, call_inputs, depth); - debug_assert!( - hint_result.is_none(), - "OracleHintInterceptor must be side-effect only and never short-circuit", - ); - } - - // Keyless Deploy (Rex2+) - if spec.is_enabled(KeylessDeployInterceptor::ACTIVATION_SPEC) { - if let Some(result) = KeylessDeployInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - // Access Control (Rex4+) - if spec.is_enabled(AccessControlInterceptor::ACTIVATION_SPEC) { - if let Some(result) = AccessControlInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - // MegaLimitControl (Rex4+) - if spec.is_enabled(LimitControlInterceptor::ACTIVATION_SPEC) { - if let Some(result) = LimitControlInterceptor::intercept(ctx, call_inputs, depth) { - return Some(result); - } - } - - None -} - -/// Returns a synthetic revert result when the call carries non-zero transferred value. -/// -/// This is used by view-style system contract interceptors to prevent silently accepting -/// value-bearing calls. -fn reject_non_zero_transfer(call_inputs: &CallInputs) -> InterceptResult { - if call_inputs.transfer_value().is_some_and(|value| !value.is_zero()) { - return Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Revert, - Bytes::copy_from_slice(&NonZeroTransfer::SELECTOR), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))); - } - None -} - -/// Interceptor for oracle hint calls (`IOracle::sendHint`). -/// -/// When a call to the oracle contract matches the `sendHint(bytes32,bytes)` selector, the -/// hint is forwarded to the oracle service backend via `OracleEnv::on_hint`. -/// Execution continues normally (no early return). -#[derive(Debug)] -pub struct OracleHintInterceptor; - -impl OracleHintInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX2; -} - -impl SystemContractInterceptor - for OracleHintInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != ORACLE_CONTRACT_ADDRESS { - return None; - } - - // REX6 mirrors the SLOAD volatile-access guard (`instructions::sload`) on this surface. - // Unlike SLOAD, `on_hint` forwarding is not gated on the disabled-subtree tracker on - // pre-REX6 specs, so a disabled (or since-reverted) child can still leak a hint to the - // off-chain backend there. The hint is an off-chain side-channel, not consensus - // state, so skip forwarding (return `None`) instead of reverting like SLOAD does — a - // revert here would change the caller's on-chain control flow for what should be a - // silently-dropped side effect. Uses the caller's depth passed by the dispatcher (not - // `HostExt::volatile_access_disabled`, which reads the current journal depth — at this - // point in `frame_init` that still is the caller's depth, but `depth` is the documented, - // explicit contract). Gated to REX6 (not retroactive to REX4/REX5): this restricts - // previously-ungated behavior and REX5 is sealed. - if ctx.spec.is_enabled(MegaSpecId::REX6) && - ctx.volatile_data_tracker.borrow().volatile_access_disabled(depth) - { - return None; - } - - let is_rex5_enabled = ctx.spec.is_enabled(MegaSpecId::REX5); - - // REX5+: zero-gas calls cannot run the canonical Oracle bytecode anyway. Skip the - // hint forwarding and let the inner frame OOG canonically. Pre-REX5 the - // interceptor forwarded the hint regardless of `gas_limit`, which let a caller - // push payloads to the off-chain backend for free while the inner Oracle frame - // OOG'd. REX5+ closes that side channel. - if is_rex5_enabled && call_inputs.gas_limit == 0 { - return None; - } - - // REX5+: peek the selector first so non-matching dispatch never materializes the - // (potentially huge) calldata. For `sendHint` the full payload is still needed to - // decode the `bytes data` argument, but the allocation cost is now paid at most - // once per legitimate `sendHint` call. - if is_rex5_enabled { - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector != IOracle::sendHintCall::SELECTOR { - return None; - } - let input_bytes = call_inputs.input.bytes(ctx); - - // Meter the materialized payload against the TX data-size budget BEFORE - // decoding. The host has already paid the materialization cost; charge the - // raw `input_bytes.len()` so a caller cannot force unmetered host work by - // appending huge trailing bytes after a valid ABI envelope — - // `alloy_sol_types::abi_decode` silently accepts trailing junk (pinned by - // `test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls` - // below). This also subsumes the malformed-payload case: bytes are charged - // whether or not `abi_decode` later succeeds. - // - // The hint is a TX-scoped side-channel into the off-chain oracle backend - // (not consensus state), so we record into the TX intrinsic lane — same as - // calldata. On overflow: do NOT forward the hint, and do NOT synthesize a - // result. Returning `None` lets the next `before_frame_init` step observe - // the freshly-flipped `has_exceeded_limit` and produce the canonical - // TX-level `OutOfGas` halt via `create_exceeded_limit_result`. The failure - // shape (and rescued-gas refund) matches every other data-size overflow. - // - // Direct top-level Oracle transactions intentionally pay both the normal - // intrinsic calldata charge and this hint-side-channel charge. - let within = ctx - .additional_limit - .borrow_mut() - .record_oracle_hint_bytes(input_bytes.len() as u64); - if !within { - return None; - } - - // Trailing junk after a valid ABI envelope is silently dropped by - // `abi_decode`; a malformed envelope is rejected outright. In either case - // we have already charged for the host-side materialization above, so we - // just fall through without forwarding on the rejection path. - let Ok(call) = IOracle::sendHintCall::abi_decode(&input_bytes) else { - return None; - }; - - ctx.oracle_env.borrow().on_hint(call_inputs.caller, call.topic, call.data); - return None; - } - - // Pre-REX5 path verbatim — preserves replay determinism on stable specs. - let input_bytes = call_inputs.input.bytes(ctx); - if let Ok(call) = IOracle::sendHintCall::abi_decode(&input_bytes) { - ctx.oracle_env.borrow().on_hint(call_inputs.caller, call.topic, call.data); - } - - // Side-effect only — do not short-circuit. - None - } -} - -/// Interceptor for keyless deploy calls (`IKeylessDeploy::keylessDeploy`). -/// -/// Intercepts top-level calls to the keyless deploy contract, decodes the pre-EIP-155 -/// transaction, and executes deployment in a sandbox. -/// Only active when sandbox is not disabled (to prevent infinite recursion) and the call -/// is at depth 0. -#[derive(Debug)] -pub struct KeylessDeployInterceptor; - -impl KeylessDeployInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX2; -} - -impl SystemContractInterceptor - for KeylessDeployInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - // Only intercept at top-level and when sandbox is not disabled. - if ctx.is_inside_sandbox() || depth != 0 { - return None; - } - - if call_inputs.target_address != KEYLESS_DEPLOY_ADDRESS { - return None; - } - - // Peek selector before materializing calldata. The full payload is still - // decoded for the `(bytes, uint64)` args after the selector matches. - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector != IKeylessDeploy::keylessDeployCall::SELECTOR { - return None; - } - let input_bytes = call_inputs.input.bytes(ctx); - let call = IKeylessDeploy::keylessDeployCall::abi_decode(&input_bytes).ok()?; - Some(execute_keyless_deploy_call( - ctx, - call_inputs, - &call.keylessDeploymentTransaction, - call.gasLimitOverride, - )) - } -} - -/// Interceptor for `MegaAccessControl` system contract calls. -/// -/// Handles three functions: -/// - `disableVolatileDataAccess()`: activates volatile data access restriction at the caller's -/// depth. -/// - `enableVolatileDataAccess()`: re-enables volatile data access. Reverts with -/// `DisabledByParent()` if a parent frame disabled it. -/// - `isVolatileDataAccessDisabled()`: queries whether volatile data access is disabled at the -/// caller's depth. -#[derive(Debug)] -pub struct AccessControlInterceptor; - -impl AccessControlInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX4; -} - -impl AccessControlInterceptor { - /// Handles `disableVolatileDataAccess()`. Caller is the journal-depth of the frame - /// that issued the call; see `intercept`'s comment for the mapping rationale. - /// - /// Takes `&MegaContext` because the mutation goes through the interior `RefCell` - /// on `volatile_data_tracker`; the context itself is read immutably. - fn handle_disable( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - ctx.volatile_data_tracker.borrow_mut().disable_access(caller_journal_depth); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } - - fn handle_enable( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let success = ctx.volatile_data_tracker.borrow_mut().enable_access(caller_journal_depth); - let result = if success { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::new(), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) - } else { - FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Revert, - Bytes::copy_from_slice(&DISABLED_BY_PARENT_REVERT_DATA), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - )) - }; - Some(result) - } - - fn handle_is_disabled( - ctx: &MegaContext, - call_inputs: &CallInputs, - caller_journal_depth: usize, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let disabled = - ctx.volatile_data_tracker.borrow().volatile_access_disabled(caller_journal_depth); - let output = - IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&disabled); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::from(output), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } -} - -impl SystemContractInterceptor - for AccessControlInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != ACCESS_CONTROL_ADDRESS { - return None; - } - - // depth equals the caller's journal depth (because journal.depth = frame.depth + 1, - // and the caller's frame.depth = frame_init.depth - 1). - let caller_journal_depth = depth; - - // Admission is selector-match alone; do not add a length check. The historical - // `abi_decode::<()>` admission accepted selector + arbitrary trailing bytes, - // and that decision is consensus-visible under stable specs. - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR { - return Self::handle_disable(ctx, call_inputs, caller_journal_depth); - } - if selector == IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR { - return Self::handle_enable(ctx, call_inputs, caller_journal_depth); - } - if selector == IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR { - return Self::handle_is_disabled(ctx, call_inputs, caller_journal_depth); - } - // Unknown selector — not intercepted. - None - } -} - -/// Interceptor for `MegaLimitControl` system contract calls. -/// -/// Handles: -/// - `remainingComputeGas()`: returns remaining compute gas of the current call. -#[derive(Debug)] -pub struct LimitControlInterceptor; - -impl LimitControlInterceptor { - /// The minimum spec required for this interceptor to be active. - pub const ACTIVATION_SPEC: MegaSpecId = MegaSpecId::REX4; -} - -impl LimitControlInterceptor { - fn handle_remaining_compute_gas( - ctx: &MegaContext, - call_inputs: &CallInputs, - ) -> InterceptResult { - if let Some(result) = reject_non_zero_transfer(call_inputs) { - return Some(result); - } - let remaining = ctx.additional_limit.borrow().current_call_remaining_compute_gas(); - let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&remaining); - Some(FrameResult::Call(CallOutcome::new( - InterpreterResult::new( - InstructionResult::Return, - Bytes::from(output), - Gas::new(call_inputs.gas_limit), - ), - call_inputs.return_memory_offset.clone(), - ))) - } -} - -impl SystemContractInterceptor - for LimitControlInterceptor -{ - fn intercept( - ctx: &mut MegaContext, - call_inputs: &CallInputs, - _depth: usize, - ) -> InterceptResult { - if call_inputs.target_address != LIMIT_CONTROL_ADDRESS { - return None; - } - - let selector = peek_selector(&call_inputs.input, ctx)?; - if selector == IMegaLimitControl::remainingComputeGasCall::SELECTOR { - return Self::handle_remaining_compute_gas(ctx, call_inputs); - } - // Unknown selector — not intercepted. - None - } -} - -#[cfg(test)] -mod tests { - use alloy_primitives::{Bytes, U256}; - use alloy_sol_types::SolCall; - use revm::{ - bytecode::opcode::{CALLCODE, MSTORE, RETURN}, - context::tx::TxEnvBuilder, - }; - - use crate::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, - }; - - const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; - - /// Pins the `abi_decode`-accepts-trailing-junk behaviour of `alloy-sol-types`'s - /// `decode_sequence::<()>` for parameterless system-contract methods. The - /// interceptor dispatch's selector-only admission relies on this: if a future - /// alloy upgrade rejects trailing bytes, historical replays would diverge from - /// the original `abi_decode` admission and break replay determinism on stable - /// specs. - #[test] - fn test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls() { - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let exact = selector; - let with_junk: Vec = selector.iter().copied().chain(core::iter::once(0xff)).collect(); - let with_pad: Vec = selector.iter().copied().chain([0u8; 32]).collect(); - - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&exact).is_ok(), - "exact 4-byte selector must decode", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_junk).is_ok(), - "current alloy-sol-types accepts selector+1B junk for empty-tuple decode; if this \ - fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - assert!( - IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_pad).is_ok(), - "current alloy-sol-types accepts selector+32B padding for empty-tuple decode; if \ - this fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ - selector probe before landing", - ); - } - - /// Unit test for the explicit call-scheme guard in `frame_init`. - /// - /// A `CALLCODE` to a system contract address with a recognized selector must NOT be - /// intercepted. - /// The scheme guard rejects it before any interceptor sees the call. - /// The call falls through to on-chain bytecode, which reverts with `NotIntercepted()`, - /// leaving the `CALLCODE` success flag as 0. - #[test] - fn test_callcode_scheme_guard_skips_interception() { - let code = BytecodeBuilder::default() - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize (selector length) - .push_number(0_u64) // argsOffset (selector at memory[0]) - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALLCODE) // success flag (0=fail, 1=success) on stack - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let caller = alloy_primitives::address!("0000000000000000000000000000000000300000"); - let contract = alloy_primitives::address!("0000000000000000000000000000000000300001"); - - let mut db = MemoryDatabase::default() - .account_balance(caller, U256::from(1_000_000)) - .account_code(contract, code) - .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default() - .caller(caller) - .call(contract) - .gas_limit(100_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "outer tx should succeed"); - - let output = result.result.output().expect("should have output"); - let success_flag = U256::from_be_slice(output); - assert_eq!( - success_flag, - U256::ZERO, - "CALLCODE to system contract must not be intercepted — scheme guard must reject it" - ); - } -} diff --git a/crates/mega-evm/src/sandbox/error.rs b/crates/mega-evm/src/system/keyless/error.rs similarity index 91% rename from crates/mega-evm/src/sandbox/error.rs rename to crates/mega-evm/src/system/keyless/error.rs index c5e84d22c..de7925f21 100644 --- a/crates/mega-evm/src/sandbox/error.rs +++ b/crates/mega-evm/src/system/keyless/error.rs @@ -1,10 +1,10 @@ -//! Error types for sandbox execution. +//! Error types of keyless deployment. use alloy_primitives::Bytes; use alloy_sol_types::SolError; use mega_system_contracts::keyless_deploy::IKeylessDeploy; -use crate::{LimitKind, MegaHaltReason}; +use crate::MegaHaltReason; /// Error types for keyless deployment operations. /// @@ -52,19 +52,15 @@ pub enum KeylessDeployError { /// The reason reason: MegaHaltReason, }, - /// Rex5 preflight rejected the call: the parent's remaining TX-level budget for some - /// dimension is smaller than the sandbox's known pre-frame intrinsic usage, so the - /// sandbox is guaranteed to fail internally and is not started. - /// - /// Returned as a Revert (like other validation errors) since no sandbox execution - /// has started and no signer state needs to persist. + /// The call's remaining budget in some resource dimension was below the deployment's + /// known upfront usage, so the deployment was not started. ParentBudgetExceeded { - /// The dimension whose parent remaining is too small. - kind: LimitKind, - /// The parent's remaining limit for that dimension, i.e. the cap the sandbox - /// would have been given. + /// The resource dimension, as the raw `kind` code of the `IKeylessDeploy` error. The + /// Satin resource dimensions and their codes are not defined yet. + kind: u8, + /// The remaining budget in that dimension. limit: u64, - /// The sandbox's known pre-frame intrinsic usage for that dimension. + /// The deployment's known upfront usage in that dimension. used: u64, }, /// Contract creation succeeded but returned empty bytecode @@ -160,9 +156,7 @@ pub fn encode_error_result(error: KeylessDeployError) -> Bytes { IKeylessDeploy::ExecutionHalted { gasUsed: gas_used }.abi_encode().into() } KeylessDeployError::ParentBudgetExceeded { kind, limit, used } => { - IKeylessDeploy::ParentBudgetExceeded { kind: kind.as_u8(), limit, used } - .abi_encode() - .into() + IKeylessDeploy::ParentBudgetExceeded { kind, limit, used }.abi_encode().into() } KeylessDeployError::EmptyCodeDeployed { gas_used } => { IKeylessDeploy::EmptyCodeDeployed { gasUsed: gas_used }.abi_encode().into() @@ -240,16 +234,14 @@ pub fn decode_error_result(output: &[u8]) -> Option { // Note: The actual halt reason is lost in ABI encoding, use OutOfGas as placeholder return Some(KeylessDeployError::ExecutionHalted { gas_used: e.gasUsed, - reason: MegaHaltReason::Base(op_revm::OpHaltReason::Base( - revm::context::result::HaltReason::OutOfGas( - revm::context::result::OutOfGasError::Basic, - ), + reason: MegaHaltReason::Base(revm::context::result::HaltReason::OutOfGas( + revm::context::result::OutOfGasError::Basic, )), }); } if let Ok(e) = IKeylessDeploy::ParentBudgetExceeded::abi_decode(output) { return Some(KeylessDeployError::ParentBudgetExceeded { - kind: LimitKind::from_u8(e.kind)?, + kind: e.kind, limit: e.limit, used: e.used, }); @@ -325,6 +317,16 @@ mod tests { assert_eq!(decoded, original); } + /// `ParentBudgetExceeded` keeps every field of the ABI error through a round-trip. + #[test] + fn test_parent_budget_exceeded_roundtrip_preserves_fields() { + let original = + KeylessDeployError::ParentBudgetExceeded { kind: 3, limit: 1_000, used: 1_001 }; + let encoded = encode_error_result(original.clone()); + assert_eq!(encoded[..4], IKeylessDeploy::ParentBudgetExceeded::SELECTOR); + assert_eq!(decode_error_result(&encoded), Some(original)); + } + /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. #[test] fn test_signer_has_code_roundtrip_is_selector_only() { diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs new file mode 100644 index 000000000..875ba7aa7 --- /dev/null +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -0,0 +1,13 @@ +//! Keyless deployment (Nick's Method): the transaction format, its validation rules and the +//! error ABI. +//! +//! These are data-only helpers: decoding the pre-EIP-155 transaction, recovering its signer, +//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. The +//! interceptor that dispatches `keylessDeploy` calls and the deployment as a native CREATE +//! sub-frame are not here yet. + +mod error; +mod tx; + +pub use error::*; +pub use tx::*; diff --git a/crates/mega-evm/src/sandbox/tx.rs b/crates/mega-evm/src/system/keyless/tx.rs similarity index 88% rename from crates/mega-evm/src/sandbox/tx.rs rename to crates/mega-evm/src/system/keyless/tx.rs index ed9cd3adc..8f2d1e199 100644 --- a/crates/mega-evm/src/sandbox/tx.rs +++ b/crates/mega-evm/src/system/keyless/tx.rs @@ -11,7 +11,7 @@ //! //! Structural validation of the transaction format: //! - Valid RLP encoding of a legacy transaction -//! - No trailing bytes after the RLP payload (Rex5+; rejected as `MalformedEncoding`) +//! - No trailing bytes after the RLP payload (rejected as `MalformedEncoding`) //! - EIP-2718 typed envelopes (0x01, 0x02, etc.) rejected as `MalformedEncoding` //! - `to` field must be empty (contract creation) //! - `v` must be 27 or 28 (pre-EIP-155, no chain ID) @@ -33,8 +33,6 @@ use alloy_consensus::{transaction::RlpEcdsaDecodableTx, Signed, TxLegacy}; use alloy_primitives::Address; -use crate::MegaSpecId; - use super::error::KeylessDeployError; /// Decodes a pre-EIP-155 legacy transaction from RLP bytes. @@ -43,28 +41,24 @@ use super::error::KeylessDeployError; /// /// # Validation /// - The RLP encoding must be valid -/// - Rex5+: the input must not contain trailing bytes after the RLP transaction +/// - The input must not contain trailing bytes after the RLP transaction /// - The `to` field must be empty (contract creation) /// - The `v` value must be 27 or 28 (pre-EIP-155) /// /// # Returns /// - `Ok(Signed)` if the transaction is valid -/// - `Err(KeylessDeployError::MalformedEncoding)` on invalid RLP or trailing bytes (REX5+) +/// - `Err(KeylessDeployError::MalformedEncoding)` on invalid RLP or trailing bytes /// - `Err(KeylessDeployError::NotContractCreation)` if `to` is not empty /// - `Err(KeylessDeployError::NotPreEIP155)` if a chain id is present -pub fn decode_keyless_tx( - rlp_bytes: &[u8], - spec: MegaSpecId, -) -> Result, KeylessDeployError> { +pub fn decode_keyless_tx(rlp_bytes: &[u8]) -> Result, KeylessDeployError> { let mut buf = rlp_bytes; let signed = TxLegacy::rlp_decode_signed(&mut buf).map_err(|_| KeylessDeployError::MalformedEncoding)?; - // Rex5+: Reject trailing bytes. The raw input is reused as `enveloped_tx` for L1 data-fee + // Reject trailing bytes. The raw input is reused as `enveloped_tx` for L1 data-fee // accounting, so any bytes past the signed RLP payload would otherwise be silently // charged without being part of the signed transaction. - // Pre-Rex5 behavior (accepted trailing bytes) is preserved for replay compatibility. - if spec.is_enabled(MegaSpecId::REX5) && !buf.is_empty() { + if !buf.is_empty() { return Err(KeylessDeployError::MalformedEncoding); } @@ -170,8 +164,8 @@ pub mod tests { #[test] fn test_decode_create2_factory_deployment() { // The canonical CREATE2 factory deployment - a well-known pre-EIP-155 transaction - let signed = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5) - .expect("should decode CREATE2 factory tx"); + let signed = + decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode CREATE2 factory tx"); let tx = signed.tx(); assert_eq!(tx.nonce, 0); @@ -203,7 +197,7 @@ pub mod tests { #[test] fn test_recover_signer_create2_factory() { // Verify we can recover the correct signer from the CREATE2 factory tx - let tx = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5).expect("should decode"); + let tx = decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode"); let signer = recover_signer(&tx).expect("should recover signer"); // The canonical CREATE2 factory signer address @@ -213,7 +207,7 @@ pub mod tests { #[test] fn test_calculate_create2_factory_deploy_address() { // Verify the deployment address calculation matches the known CREATE2 factory address - let tx = decode_keyless_tx(CREATE2_FACTORY_TX, MegaSpecId::REX5).expect("should decode"); + let tx = decode_keyless_tx(CREATE2_FACTORY_TX).expect("should decode"); let signer = recover_signer(&tx).expect("should recover signer"); let deploy_address = calculate_keyless_deploy_address(signer); @@ -225,7 +219,7 @@ pub mod tests { fn test_decode_rejects_post_eip155_chain_1() { // Transaction generated with: cast mktx ... --chain 1 --create 0x6080604052 // v = 1 * 2 + 35 + 1 = 38 (0x26) - let result = decode_keyless_tx(POST_EIP155_CHAIN_1_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(POST_EIP155_CHAIN_1_TX); assert_eq!(result, Err(KeylessDeployError::NotPreEIP155)); } @@ -233,7 +227,7 @@ pub mod tests { fn test_decode_rejects_post_eip155_chain_1337() { // Transaction generated with: cast mktx ... --chain 1337 --create 0x6080604052 // v = 1337 * 2 + 35 + 0 = 2709 (0x0a95) - let result = decode_keyless_tx(POST_EIP155_CHAIN_1337_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(POST_EIP155_CHAIN_1337_TX); assert_eq!(result, Err(KeylessDeployError::NotPreEIP155)); } @@ -241,7 +235,7 @@ pub mod tests { fn test_decode_rejects_non_contract_creation() { // Transaction with to=0x4242...42 (not a contract creation) // Generated with: cast mktx ... --legacy 0x4242424242424242424242424242424242424242 - let result = decode_keyless_tx(NON_CONTRACT_CREATION_TX, MegaSpecId::REX5); + let result = decode_keyless_tx(NON_CONTRACT_CREATION_TX); assert_eq!(result, Err(KeylessDeployError::NotContractCreation)); } @@ -249,13 +243,13 @@ pub mod tests { fn test_decode_rejects_malformed_rlp() { // Random bytes, not valid RLP let invalid_rlp = hex!("deadbeef"); - let result = decode_keyless_tx(&invalid_rlp, MegaSpecId::REX5); + let result = decode_keyless_tx(&invalid_rlp); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } #[test] fn test_decode_rejects_empty_input() { - let result = decode_keyless_tx(&[], MegaSpecId::REX5); + let result = decode_keyless_tx(&[]); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } @@ -263,35 +257,23 @@ pub mod tests { fn test_decode_rejects_truncated_rlp() { // Truncate the CREATE2 factory tx let truncated = &CREATE2_FACTORY_TX[..CREATE2_FACTORY_TX.len() - 10]; - let result = decode_keyless_tx(truncated, MegaSpecId::REX5); + let result = decode_keyless_tx(truncated); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } #[test] - fn test_decode_rejects_trailing_bytes_rex5() { - // Rex5+: trailing bytes after the signed RLP payload are rejected to prevent + fn test_decode_rejects_trailing_bytes() { + // Trailing bytes after the signed RLP payload are rejected to prevent // unsigned bytes from affecting `enveloped_tx` / L1 data-fee accounting. let mut with_trailing = CREATE2_FACTORY_TX.to_vec(); with_trailing.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX5); + let result = decode_keyless_tx(&with_trailing); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); // A single trailing byte must also be rejected. let mut with_one_trailing = CREATE2_FACTORY_TX.to_vec(); with_one_trailing.push(0x00); - let result = decode_keyless_tx(&with_one_trailing, MegaSpecId::REX5); + let result = decode_keyless_tx(&with_one_trailing); assert_eq!(result, Err(KeylessDeployError::MalformedEncoding)); } - - #[test] - fn test_decode_accepts_trailing_bytes_pre_rex5() { - // Pre-Rex5 (Rex2–Rex4): trailing bytes were silently accepted for replay compatibility. - let mut with_trailing = CREATE2_FACTORY_TX.to_vec(); - with_trailing.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX4); - assert!(result.is_ok(), "pre-Rex5 should accept trailing bytes"); - - let result = decode_keyless_tx(&with_trailing, MegaSpecId::REX2); - assert!(result.is_ok(), "pre-Rex5 should accept trailing bytes"); - } } diff --git a/crates/mega-evm/src/system/keyless_deploy.rs b/crates/mega-evm/src/system/keyless_deploy.rs deleted file mode 100644 index cd1acf6a3..000000000 --- a/crates/mega-evm/src/system/keyless_deploy.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! The keyless deploy system contract for the `MegaETH` EVM. -//! -//! This contract enables deploying contracts using pre-EIP-155 transactions (Nick's Method) -//! with custom gas limits, solving the problem of contracts failing to deploy on `MegaETH` -//! due to the different gas model. -//! -//! ## Nick's Method Overview -//! -//! Nick's Method allows deterministic contract deployment across different EVM chains without -//! needing the deployer's private key: -//! -//! 1. Create a contract deployment transaction (to = null, nonce = 0) -//! 2. Generate a random signature (v, r, s) with v = 27 or 28 (pre-EIP-155) -//! 3. Recover the signer address from the signature (nobody knows this private key) -//! 4. Fund the signer address with enough ETH for gas -//! 5. Broadcast the signed transaction -//! -//! The deployment address is deterministic: `keccak256(rlp([signer, 0]))[12:]` - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -// Re-export error types and transaction functions from sandbox -pub use crate::sandbox::{ - calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, recover_signer, - KeylessDeployError, -}; - -/// The address of the keyless deploy system contract. -pub const KEYLESS_DEPLOY_ADDRESS: Address = address!("0x6342000000000000000000000000000000000003"); - -/// The code of the keyless deploy contract (version 1.0.0). -pub use mega_system_contracts::keyless_deploy::V1_0_0_CODE as KEYLESS_DEPLOY_CODE; - -/// The code hash of the keyless deploy contract (version 1.0.0). -pub use mega_system_contracts::keyless_deploy::V1_0_0_CODE_HASH as KEYLESS_DEPLOY_CODE_HASH; - -pub use mega_system_contracts::keyless_deploy::IKeylessDeploy; - -/// Ensures the keyless deploy contract is deployed in the designated address and returns the -/// state changes. Note that the database `db` is not modified in this function. The caller is -/// responsible to commit the changes to database. -pub fn transact_deploy_keyless_deploy_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - keyless_deploy_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the keyless-deploy contract active under -/// `spec`, or `None` if `REX2` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn keyless_deploy_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX2).then(|| { - SystemContractSpec::new( - KEYLESS_DEPLOY_ADDRESS, - KEYLESS_DEPLOY_CODE, - KEYLESS_DEPLOY_CODE_HASH, - ) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::MegaHardforkConfig; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_deploy_keyless_deploy_contract_on_fresh_db() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert!(account.is_touched()); - assert!(account.is_created(), "fresh deploy must mark account as created"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - } - - /// Covers the `account_existed = true` branch: an account already exists with wrong code, - /// so the deploy updates the code without marking the account as created. - #[test] - fn test_deploy_keyless_deploy_contract_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - KEYLESS_DEPLOY_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "in-place bytecode update of an existing account must not mark it as created" - ); - } - - #[test] - fn test_deploy_keyless_deploy_contract_requires_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // A complete ladder topping out at Rex1: Rex2 is genuinely not reached. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX1); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Should succeed"); - assert_eq!(result, None, "should not deploy before Rex2 activation"); - } -} diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index 6ef1847fb..e046b0c6a 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -1,40 +1,6 @@ -//! System contract and transaction helpers. +//! System contracts of the Satin engine. //! -//! # Pre-Block Helper Contract -//! -//! Deploy helpers and pre-block system-call helpers in this module -//! (`transact_deploy_*`, `transact_apply_pending_changes`, etc.) **must never** call -//! `db.commit(...)` directly. They return `Option` (or -//! `Option>`), and the block executor commits the collected outcomes -//! after running its `on_state` hook so the stateless witness generator captures the full -//! read/write set. -//! -//! Specifically: -//! -//! - Return `Ok(None)` only when the step is gated out entirely (wrong hardfork, etc.). -//! - On an idempotent "no change" path (e.g., the contract is already deployed with the correct -//! code hash), return `Some(EvmState)` containing the observed account as a read-only entry -//! (`Account { info, ..Default::default() }`, no `touched`/`created` flags). Returning `None` -//! here loses the account from the witness read set. -//! - On a real-change path, include every account and slot the helper touched, including slots read -//! in preparation for the change. -//! -//! See `crate::block` module docs for the executor side of this contract. - -mod control; -mod deploy; -mod intercept; -mod keyless_deploy; -mod limit_control; -mod oracle; -mod sequencer_registry; -mod tx; +//! Filled when the interceptor dispatch, the deployment at activation and the oracle and control +//! contracts land. For now it holds only the keyless-deployment data helpers. -pub use control::*; -pub use deploy::*; -pub use intercept::*; -pub use keyless_deploy::*; -pub use limit_control::*; -pub use oracle::*; -pub use sequencer_registry::*; -pub use tx::*; +pub mod keyless; diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs deleted file mode 100644 index fe9a9fa05..000000000 --- a/crates/mega-evm/src/system/oracle.rs +++ /dev/null @@ -1,605 +0,0 @@ -//! The oracle system contract for the `MegaETH` EVM. The oracle contract is implemented in -//! `../../../system-contracts/contracts/Oracle.sol`. - -use alloy_evm::Database; -use alloy_primitives::{address, b256, bytes, Address, Bytes, B256}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the oracle system contract. -pub const ORACLE_CONTRACT_ADDRESS: Address = address!("0x6342000000000000000000000000000000000001"); - -/// The code of the oracle contract (version 1.0.0, pre-Rex2). -pub use mega_system_contracts::oracle::V1_0_0_CODE as ORACLE_CONTRACT_CODE; - -/// The code hash of the oracle contract (version 1.0.0, pre-Rex2). -pub use mega_system_contracts::oracle::V1_0_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH; - -/// The code of the oracle contract (version 1.1.0, Rex2+). -/// This version includes the `sendHint` function for the oracle hint mechanism. -pub use mega_system_contracts::oracle::V1_1_0_CODE as ORACLE_CONTRACT_CODE_REX2; - -/// The code hash of the oracle contract (version 1.1.0, Rex2+). -pub use mega_system_contracts::oracle::V1_1_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH_REX2; - -/// The code of the oracle contract (version 2.0.0, Rex5+). -/// This version reads the authorized system address from `SequencerRegistry` instead of -/// using a constructor `immutable`, enabling system address change without redeployment. -pub use mega_system_contracts::oracle::V2_0_0_CODE as ORACLE_CONTRACT_CODE_REX5; - -/// The code hash of the oracle contract (version 2.0.0, Rex5+). -pub use mega_system_contracts::oracle::V2_0_0_CODE_HASH as ORACLE_CONTRACT_CODE_HASH_REX5; - -pub use mega_system_contracts::oracle::IOracle; - -/// Ensures the oracle contract is deployed in the designated address and returns the state changes. -/// Note that the database `db` is not modified in this function. The caller is responsible to -/// commit the changes to database. -/// -/// The deployed bytecode depends on the scheduled spec: -/// - Pre-Rex2: v1.0.0 bytecode (without `sendHint` function) -/// - Rex2 to Rex4: v1.1.0 bytecode (with `sendHint` function for oracle hints) -/// - Rex5+: v2.0.0 bytecode (reads the system address from the `SequencerRegistry`) -pub fn transact_deploy_oracle_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - oracle_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the Oracle contract active under `spec`, -/// or `None` if `MINI_REX` is not yet enabled. -/// -/// Single source of the Oracle's gate, bytecode-version selection, and upgrade -/// semantics — shared by [`transact_deploy_oracle_contract`] and the deploy -/// registry ([`flat_system_contract_specs`](crate::flat_system_contract_specs)). -/// -/// `spec` is the scheduled spec, gated by position (`reaches`) rather than behavior: an Oracle -/// already installed under `MINI_REX` stays installed through an alias (rollback) window. -pub(crate) fn oracle_spec(spec: MegaSpecId) -> Option { - if !spec.reaches(MegaSpecId::MINI_REX) { - return None; - } - - // Select the appropriate bytecode based on the spec. - // - Pre-Rex2: v1.0.0 (without `sendHint`) - // - Rex2-Rex4: v1.1.0 (with `sendHint`) - // - Rex5+: v2.0.0 (reads system address from SequencerRegistry) - let rex5 = spec.reaches(MegaSpecId::REX5); - let (target_code, target_code_hash) = if rex5 { - (ORACLE_CONTRACT_CODE_REX5, ORACLE_CONTRACT_CODE_HASH_REX5) - } else if spec.reaches(MegaSpecId::REX2) { - (ORACLE_CONTRACT_CODE_REX2, ORACLE_CONTRACT_CODE_HASH_REX2) - } else { - (ORACLE_CONTRACT_CODE, ORACLE_CONTRACT_CODE_HASH) - }; - - // Starting from Rex5 we stop marking the account as created on in-place bytecode upgrades so - // that the existing Oracle storage is preserved across the upgrade. Pre-Rex5 the old behaviour - // is preserved to maintain canonical mainnet state at the Rex2 activation boundary (where - // mainnet had non-zero DB-backed Oracle storage that was cleared by the old code). - Some( - SystemContractSpec::new(ORACLE_CONTRACT_ADDRESS, target_code, target_code_hash) - .with_force_create_on_upgrade(!rex5), - ) -} - -/// The address of the high precision timestamp oracle contract. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS: Address = - address!("0x6342000000000000000000000000000000000002"); - -/// The code hash of the high precision timestamp oracle contract. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH: B256 = - b256!("0x1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2"); - -/// The code of the high precision timestamp oracle contract. The oracle contract address is -/// embedded in to the contract code. -pub const HIGH_PRECISION_TIMESTAMP_ORACLE_CODE: Bytes = bytes!("0x608060405234801561000f575f5ffd5b5060043610610064575f3560e01c806382ab890a1161004d57806382ab890a146100f55780638582b7bc1461010a578063b80777ea1461013f575f5ffd5b806328af7f3c146100685780633e6890fb146100a9575b5f5ffd5b61008f7f000000000000000000000000000000000000000000000000000000000000000881565b60405163ffffffff90911681526020015b60405180910390f35b6100d07f000000000000000000000000634200000000000000000000000000000000000181565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100a0565b6101086101033660046103b6565b610147565b005b6101317f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016100a0565b610131610154565b6101515f82610165565b50565b5f5f61015f5f610245565b92915050565b8161016f8161031a565b73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000063420000000000000000000000000000000000011663fbc0d0356101d5857f00000000000000000000000000000000000000000000000000000000000000006103cd565b60405160e083901b7fffffffff000000000000000000000000000000000000000000000000000000001681526004810191909152602481018590526044015f604051808303815f87803b15801561022a575f5ffd5b505af115801561023c573d5f5f3e3d5ffd5b50505050505050565b5f816102508161031a565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000634200000000000000000000000000000000000116637eba7ba66102b6857f00000000000000000000000000000000000000000000000000000000000000006103cd565b6040518263ffffffff1660e01b81526004016102d491815260200190565b602060405180830381865afa1580156102ef573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103139190610405565b9392505050565b63ffffffff7f00000000000000000000000000000000000000000000000000000000000000081661034c8260016103cd565b10610151576040517fef94d8420000000000000000000000000000000000000000000000000000000081526004810182905263ffffffff7f000000000000000000000000000000000000000000000000000000000000000816602482015260440160405180910390fd5b5f602082840312156103c6575f5ffd5b5035919050565b8082018082111561015f577f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f60208284031215610415575f5ffd5b505191905056fea2646970667358221220290614c973d24b9016b73a6b3fa98b2485a5c324199ceeb767818495dbe785e864736f6c634300081e0033"); - -/// Ensures the high precision timestamp oracle contract is deployed in the designated address and -/// returns the state changes. Note that the database `db` is not modified in this function. The -/// caller is responsible to commit the changes to database. -pub fn transact_deploy_high_precision_timestamp_oracle( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - high_precision_timestamp_oracle_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the high-precision timestamp Oracle -/// active under `spec`, or `None` if `MINI_REX` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see [`oracle_spec`]. -pub(crate) fn high_precision_timestamp_oracle_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::MINI_REX).then(|| { - SystemContractSpec::new( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - ) - }) -} - -#[cfg(test)] -mod tests { - use crate::MegaHardforkConfig; - - use super::*; - use alloy_primitives::keccak256; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_oracle_contract_code_hash_matches() { - // Compute the keccak256 hash of the oracle contract code (v1.0.0, pre-Rex2) - let computed_hash = keccak256(&ORACLE_CONTRACT_CODE); - - // Verify it matches the hardcoded constant - assert_eq!( - computed_hash, ORACLE_CONTRACT_CODE_HASH, - "Oracle contract code hash mismatch: computed {}, expected {}", - computed_hash, ORACLE_CONTRACT_CODE_HASH - ); - } - - #[test] - fn test_oracle_contract_code_hash_rex2_matches() { - // Compute the keccak256 hash of the oracle contract code (v1.1.0, Rex2+) - let computed_hash = keccak256(&ORACLE_CONTRACT_CODE_REX2); - - // Verify it matches the hardcoded constant - assert_eq!( - computed_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Oracle contract Rex2 code hash mismatch: computed {}, expected {}", - computed_hash, ORACLE_CONTRACT_CODE_HASH_REX2 - ); - } - - #[test] - fn test_deploy_oracle_contract_on_fresh_db() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5, so we expect Rex5 (v2.0.0) bytecode - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&ORACLE_CONTRACT_ADDRESS), - "State changes should contain oracle contract address" - ); - - // Verify the account in the state changes - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info (Rex5 = v2.0.0 bytecode) - let info = &account.info; - assert_eq!( - info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match the v2.0.0 value" - ); - assert!(info.code.is_some(), "Code should be set"); - - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - ORACLE_CONTRACT_CODE_REX5, - "Code bytes should match the v2.0.0 value" - ); - } - - #[test] - fn test_deploy_oracle_contract_idempotent() { - // Create a database with the oracle contract already deployed correctly (Rex5 = v2.0.0) - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX5, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX5)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should return state with the account marked as read (no update needed) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - assert_eq!( - result.len(), - 1, - "Deployment should return state with account marked as read when contract is already correctly deployed" - ); - - // Verify the account is in the result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_with_wrong_code_hash() { - // Create a database with the oracle address already having different code - let mut db = InMemoryDB::default(); - - // Insert an account with wrong code hash at the oracle address - let wrong_code = bytes!("0x6000"); - let wrong_code_hash = keccak256(&wrong_code); - - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex2 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should update the contract with correct code (Rex5 = v2.0.0 bytecode) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned (contract was updated) - assert_eq!(result.len(), 1, "Should have state changes to update the contract"); - - // Verify the updated account has the correct code hash - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should be updated to v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_marks_account_as_touched() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Get the account from result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist in result"); - - // Verify the account is marked as touched (required for state changes to be committed) - assert!( - account.is_touched(), - "Deployed account must be marked as touched for state changes to take effect" - ); - assert!(account.is_created(), "Account should be marked as created"); - } - - #[test] - fn test_deploy_oracle_contract_pre_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // A complete ladder topping out at Rex1 (pre-Rex2, pre-Rex5). - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX1); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH, - "Should deploy v1.0.0 bytecode pre-Rex2" - ); - } - - #[test] - fn test_deploy_oracle_contract_rex2() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // Activate Rex2 but not Rex5 - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Should deploy v1.1.0 bytecode on Rex2 (pre-Rex5)" - ); - } - - #[test] - fn test_deploy_oracle_contract_rex5() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // Activate all including Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Should deploy v2.0.0 bytecode on Rex5" - ); - } - - #[test] - fn test_deploy_oracle_contract_upgrade_to_rex2() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex2 active, Rex5 not active - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2, - "Should upgrade to v1.1.0 bytecode on Rex2 activation" - ); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!( - account.is_created(), - "Pre-Rex5 Oracle upgrades must still mark the account as created to match canonical mainnet state" - ); - } - - #[test] - fn test_deploy_oracle_contract_upgrade_to_rex5() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX2, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX2)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Should upgrade to v2.0.0 bytecode on Rex5 activation" - ); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!( - !account.is_created(), - "In-place bytecode upgrade must not mark the existing account as created, otherwise existing storage gets cleared on commit" - ); - } - - #[test] - fn test_high_precision_timestamp_oracle_deployment() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the high precision timestamp oracle contract - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), - "State changes should contain high precision timestamp oracle address" - ); - - // Verify the account in the state changes - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info - let info = &account.info; - assert_eq!( - info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash should match the expected value" - ); - assert!(info.code.is_some(), "Code should be set"); - - // Verify code matches - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - "Code bytes should match the expected value" - ); - - // Verify code hash matches computed hash - let computed_hash = keccak256(&HIGH_PRECISION_TIMESTAMP_ORACLE_CODE); - assert_eq!( - computed_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash constant should match computed hash" - ); - } - - /// Canonical-state regression: upgrading Oracle v1.0.0 → v1.1.0 at the Rex2 boundary - /// (pre-Rex5) MUST preserve the old `mark_created()` behaviour so that replay against - /// canonical mainnet state (which was built with the old code) produces the same state root. - /// On mainnet mainnet had non-zero DB-backed Oracle storage at the Rex2 boundary, and the old - /// code cleared it; the gated fix must not retroactively change that. - #[test] - fn test_oracle_storage_cleared_at_rex2_upgrade_canonical_behaviour() { - let stored_slot = revm::primitives::U256::from(42); - let stored_value = revm::primitives::U256::from(0xdeadbeefu64); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE)), - }, - ); - db.insert_account_storage(ORACLE_CONTRACT_ADDRESS, stored_slot, stored_value) - .expect("Should insert storage slot"); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex2 active, Rex5 NOT active → pre-Rex5 path → old behaviour preserved. - // A complete ladder topping out at Rex4: Rex2 reached, Rex5 not. - let hardforks = MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); - assert!(account.is_touched()); - assert!( - account.is_created(), - "pre-Rex5: Oracle upgrade must still mark created to match canonical mainnet state" - ); - - // Commit the upgrade: because is_created=true the cache treats this as newly_created and - // storage is cleared — matching the canonical mainnet state root. - revm::DatabaseCommit::commit(&mut state, result); - - let read_back = revm::Database::storage(&mut state, ORACLE_CONTRACT_ADDRESS, stored_slot) - .expect("Storage read should succeed"); - assert_eq!( - read_back, - revm::primitives::U256::ZERO, - "pre-Rex5: Oracle storage must be cleared at Rex2 upgrade to match canonical mainnet state" - ); - } - - /// Regression: upgrading the Oracle bytecode from v1.1.0 (Rex2) to v2.0.0 (Rex5) - /// must not clear existing Oracle storage. - #[test] - fn test_oracle_storage_survives_rex2_to_rex5_upgrade() { - let stored_slot = revm::primitives::U256::from(7); - let stored_value = revm::primitives::U256::from(0xcafebabeu64); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX2, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX2)), - }, - ); - db.insert_account_storage(ORACLE_CONTRACT_ADDRESS, stored_slot, stored_value) - .expect("Should insert storage slot"); - - let mut state = State::builder().with_database(&mut db).build(); - // Rex5 active → upgrade target is v2.0.0. - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Sanity check: this is an upgrade, not a fresh deploy. - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5); - assert!(account.is_touched()); - assert!(!account.is_created(), "upgrade must not mark account as created"); - - revm::DatabaseCommit::commit(&mut state, result); - - let read_back = revm::Database::storage(&mut state, ORACLE_CONTRACT_ADDRESS, stored_slot) - .expect("Storage read should succeed"); - assert_eq!(read_back, stored_value, "Oracle storage must survive bytecode upgrade"); - } - - /// Covers the `account_existed = true` branch in - /// `transact_deploy_high_precision_timestamp_oracle`: when the account already exists with - /// wrong code, the deploy updates the code without marking the account as created. - #[test] - fn test_high_precision_timestamp_oracle_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "existing account must not be marked as created on code update" - ); - } -} diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs deleted file mode 100644 index 1b7a64758..000000000 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ /dev/null @@ -1,1494 +0,0 @@ -//! The `SequencerRegistry` system contract for the `MegaETH` EVM. -//! -//! Tracks two independent roles: system address (Oracle/system-tx authority) and -//! sequencer (mini-block signing). Each role has its own change lifecycle. -//! -//! Unlike intercepted system contracts (`LimitControl`, `AccessControl`), this contract runs -//! normal on-chain bytecode. It does not have an interceptor. -//! -//! Deployed via raw state patch with initial storage seeded at deploy time. -//! Due changes are applied via a single pre-block EVM system call to -//! `applyPendingChanges()`, following the same pattern as EIP-2935 and EIP-4788. -//! The current system transaction sender should always be read through -//! [`resolve_system_address`], which returns the legacy constant for pre-REX5 and -//! reads the on-chain `SequencerRegistry` state for REX5+. - -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - Database, -}; -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, - INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, -}; -use revm::{ - context_interface::result::ResultAndState, - database::State, - primitives::KECCAK_EMPTY, - state::{Account, Bytecode, EvmState, EvmStorageSlot}, - Database as RevmDatabase, -}; - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use crate::{ - HardforkParams, HardforkParamsError, MegaHardfork, MegaHardforks, SystemContractSpec, - MEGA_SYSTEM_ADDRESS, -}; - -/// The address of the `SequencerRegistry` system contract. -pub const SEQUENCER_REGISTRY_ADDRESS: Address = - address!("0x6342000000000000000000000000000000000006"); - -/// The code of the `SequencerRegistry` contract (version 1.0.0, pre-Rex6). -pub use mega_system_contracts::sequencer_registry::V1_0_0_CODE as SEQUENCER_REGISTRY_CODE; - -/// The code hash of the `SequencerRegistry` contract (version 1.0.0, pre-Rex6). -pub use mega_system_contracts::sequencer_registry::V1_0_0_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH; - -/// The code of the `SequencerRegistry` contract (version 2.0.0, Rex6+). -/// This version requires an EIP-712 possession proof by the new sequencer key and a minimum -/// scheduling-to-activation delay when scheduling a sequencer change. -pub use mega_system_contracts::sequencer_registry::V2_0_0_CODE as SEQUENCER_REGISTRY_CODE_REX6; - -/// The code hash of the `SequencerRegistry` contract (version 2.0.0, Rex6+). -pub use mega_system_contracts::sequencer_registry::V2_0_0_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH_REX6; - -pub use mega_system_contracts::sequencer_registry::ISequencerRegistry; - -/// Bootstrap configuration for `SequencerRegistry` (attached to Rex5 via [`HardforkParams`]). -/// -/// The initial system address is fixed to [`MEGA_SYSTEM_ADDRESS`] at genesis and is not -/// configurable: pre-Rex5 components (payload executor, txpool, replay) all assume the -/// system tx sender equals the legacy constant, and a configurable initial value would -/// silently break those invariants. After Rex5 activation, the system address can be -/// rotated via the registry's scheduling/apply flow. -/// -/// Field names carry an explicit `rex5_` prefix because these values seed the -/// `SequencerRegistry` only when Rex5 activates; pre-Rex5 blocks read the system address -/// from the legacy constant and ignore this struct entirely. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SequencerRegistryConfig { - /// The initial sequencer (mini-block signing key) seeded at Rex5 activation. - pub rex5_initial_sequencer: Address, - /// The initial admin for the registry, seeded at Rex5 activation. - pub rex5_initial_admin: Address, -} - -impl HardforkParams for SequencerRegistryConfig { - const FORK: MegaHardfork = MegaHardfork::Rex5; - - fn validate(&self) -> Result<(), HardforkParamsError> { - if self.rex5_initial_sequencer.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.rex5_initial_sequencer must not be zero".into(), - }); - } - if self.rex5_initial_admin.is_zero() { - return Err(HardforkParamsError { - message: "SequencerRegistryConfig.rex5_initial_admin must not be zero".into(), - }); - } - Ok(()) - } -} - -/// Rotation-hardening configuration for `SequencerRegistry` v2.0.0 (attached to Rex6 via -/// [`HardforkParams`]). -/// -/// The value seeds the registry's `_minRotationDelay` storage slot when Rex6 activates: -/// on a fresh Rex6 bootstrap it is written alongside the other seeded slots, and on the -/// in-place v1.0.0 → v2.0.0 upgrade it is the only slot written. The contract exposes no -/// setter, so this is the effective delay until a future bytecode upgrade. -/// -/// Kept separate from the Rex5-pinned [`SequencerRegistryConfig`], with the same -/// fork-prefixed field-naming convention. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SequencerRegistryRex6Config { - /// The minimum number of blocks between scheduling a sequencer change and its activation - /// block, seeded into the registry at Rex6 activation. - pub rex6_min_rotation_delay: u64, -} - -impl HardforkParams for SequencerRegistryRex6Config { - const FORK: MegaHardfork = MegaHardfork::Rex6; - - fn validate(&self) -> Result<(), HardforkParamsError> { - // A zero delay disables the reaction window the field exists to guarantee, so it is a - // structural invariant rather than a policy choice. - if self.rex6_min_rotation_delay == 0 { - return Err(HardforkParamsError { - message: "SequencerRegistryRex6Config.rex6_min_rotation_delay must not be zero" - .into(), - }); - } - Ok(()) - } -} - -/// Encodes an address into its `U256` storage representation (standard Solidity address-in-slot). -fn address_to_storage_value(address: Address) -> U256 { - U256::from_be_bytes(address.into_word().0) -} - -/// Reads a committed `SequencerRegistry` storage slot. -fn read_registry_storage( - db: &mut State, - slot: U256, -) -> Result { - RevmDatabase::storage(db, SEQUENCER_REGISTRY_ADDRESS, slot).map_err(BlockExecutionError::other) -} - -/// Returns whether a pending role change is due and records every storage read into the witness -/// account. -fn is_role_due( - db: &mut State, - account: &mut Account, - pending_slot: U256, - activation_slot: U256, - block_number: u64, -) -> Result { - let pending = read_registry_storage(db, pending_slot)?; - // Read-only witness entry: record the slot access without marking it as changed. - account.storage.insert(pending_slot, EvmStorageSlot::new(pending, 0)); - if pending.is_zero() { - return Ok(false); - } - - let activation_block = read_registry_storage(db, activation_slot)?; - account.storage.insert(activation_slot, EvmStorageSlot::new(activation_block, 0)); - - Ok(block_number >= activation_block.saturating_to::()) -} - -/// Deploys the `SequencerRegistry` contract and seeds initial storage. -/// -/// The installed bytecode depends on the active hardfork: -/// - Rex5 (pre-Rex6): v1.0.0. -/// - Rex6+: v2.0.0 (rotation hardening: EIP-712 possession proof + minimum rotation delay). -/// -/// On first deploy, writes the flat storage slots: -/// - `_currentSystemAddress`, `_currentSequencer`, `_admin` -/// - `_initialSystemAddress`, `_initialSequencer`, `_initialFromBlock` -/// - `_minRotationDelay` (v2.0.0 only) -/// -/// At the Rex6 boundary, an already-deployed v1.0.0 registry is upgraded **in place**: the -/// bytecode is swapped to v2.0.0 and only the new `_minRotationDelay` slot is written, while -/// all live state (roles, pending changes, histories) is preserved. A pending sequencer change -/// scheduled under v1.0.0 therefore still activates normally under v2.0.0. -/// -/// The dynamic change-history arrays remain empty on bootstrap and grow only when -/// `applyPendingChanges()` commits a due change. -/// If already deployed with the correct code hash, returns the account as-is. -pub fn transact_deploy_sequencer_registry( - hardforks: impl MegaHardforks, - block_timestamp: u64, - current_block_number: u64, - db: &mut State, - config: &SequencerRegistryConfig, -) -> Result, BlockExecutionError> { - let spec = hardforks.spec_id(block_timestamp); - let rex6_config = hardforks.fork_params::(); - transact_deploy_sequencer_registry_for(spec, rex6_config, current_block_number, db, config) -} - -/// [`transact_deploy_sequencer_registry`] against an already-resolved spec. -/// -/// The block executor resolves the spec once per block and calls this directly; the public -/// wrapper above resolves it for callers that hold a hardfork config. Like the flat-registry -/// spec builders, this deliberately does not take a hardfork config — everything a deploy -/// depends on arrives resolved (the spec and the typed params), so a per-fork activation gate -/// cannot be reintroduced here. -pub(crate) fn transact_deploy_sequencer_registry_for( - spec: crate::MegaSpecId, - rex6_config: Option<&SequencerRegistryRex6Config>, - current_block_number: u64, - db: &mut State, - config: &SequencerRegistryConfig, -) -> Result, BlockExecutionError> { - // Gate and bytecode selection follow the scheduled spec, not per-fork registration: - // a registry once deployed stays deployed through a spec rollback, and a config that - // schedules only a later fork must still get the Rex5 bootstrap. - if !spec.reaches(crate::MegaSpecId::REX5) { - return Ok(None); - } - - // Belt-and-braces: `with_params` already calls `validate()` at chain-config load time. - debug_assert!( - config.validate().is_ok(), - "SequencerRegistryConfig::validate() failed at deploy time — \ - this should have been caught by with_params()" - ); - - // Select the bytecode version and, for v2.0.0, resolve the seeded minimum rotation delay. - // The Rex6 params are required as soon as Rex6 is active: failing fast here surfaces a - // misconfigured chain at the activation block instead of deploying an unseeded registry. - let rex6 = spec.reaches(crate::MegaSpecId::REX6); - let (target_code, target_code_hash) = if rex6 { - (SEQUENCER_REGISTRY_CODE_REX6, SEQUENCER_REGISTRY_CODE_HASH_REX6) - } else { - (SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_HASH) - }; - let min_rotation_delay = if rex6 { - let params = rex6_config.ok_or_else(|| BlockValidationError::BlockHashContractCall { - message: "Rex6 active but SequencerRegistryRex6Config not configured".into(), - })?; - debug_assert!( - params.validate().is_ok(), - "SequencerRegistryRex6Config::validate() failed at deploy time — \ - this should have been caught by with_params()" - ); - Some(U256::from(params.rex6_min_rotation_delay)) - } else { - None - }; - - // Guard against silently overwriting a foreign stateful contract, and handle - // the Rex6 v1.0.0 → v2.0.0 in-place upgrade. Both are specific to the registry - // (which carries change history); the generic deploy below otherwise - // overwrites bytecode in place. - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - if let Some(account_info) = acc.account_info() { - if rex6 && account_info.code_hash == SEQUENCER_REGISTRY_CODE_HASH { - // Rex6 boundary: in-place, storage-preserving v1.0.0 → v2.0.0 upgrade. The account - // is intentionally NOT marked created (that would clear live roles, pending changes - // and histories on commit), so it cannot go through the generic force-create - // deploy below; the only storage write is the new `_minRotationDelay` slot, which - // no v1.0.0 code path has ever touched. - let mut acc_info = account_info; - acc_info.code_hash = target_code_hash; - acc_info.code = Some(Bytecode::new_raw(target_code)); - - let mut revm_acc: Account = acc_info.into(); - revm_acc.mark_touch(); - - let original = read_registry_storage(db, MIN_ROTATION_DELAY)?; - let delay = min_rotation_delay.expect("Rex6 upgrade path implies Rex6 params"); - revm_acc - .storage - .insert(MIN_ROTATION_DELAY, EvmStorageSlot::new_changed(original, delay, 0)); - - return Ok(Some(EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, revm_acc)]))); - } - if account_info.code_hash != target_code_hash && account_info.code_hash != KECCAK_EMPTY { - return Err(BlockValidationError::BlockHashContractCall { - message: format!( - "SequencerRegistry at {} has unexpected code hash {} (expected {}); \ - refusing to overwrite stateful contract storage without migration", - SEQUENCER_REGISTRY_ADDRESS, account_info.code_hash, target_code_hash, - ), - } - .into()); - } - } - - // Seed initial storage (flat slots only, no dynamic arrays). - // The initial system address is fixed to MEGA_SYSTEM_ADDRESS at genesis — see - // [`SequencerRegistryConfig`] for rationale. - let initial_system_address = address_to_storage_value(MEGA_SYSTEM_ADDRESS); - let initial_sequencer = address_to_storage_value(config.rex5_initial_sequencer); - let initial_admin = address_to_storage_value(config.rex5_initial_admin); - let initial_from_block = U256::from(current_block_number); - let mut seed = Vec::from([ - (CURRENT_SYSTEM_ADDRESS, initial_system_address), - (CURRENT_SEQUENCER, initial_sequencer), - (ADMIN, initial_admin), - (INITIAL_SYSTEM_ADDRESS, initial_system_address), - (INITIAL_SEQUENCER, initial_sequencer), - (INITIAL_FROM_BLOCK, initial_from_block), - ]); - // v2.0.0 fresh deploys additionally seed the minimum rotation delay. - if let Some(delay) = min_rotation_delay { - seed.push((MIN_ROTATION_DELAY, delay)); - } - - // The registry is always a fresh, seeded deploy (force_create), and the - // generic deploy returns the account read-only when it is already present - // with the matching code hash. (The Rex6 storage-preserving upgrade never - // reaches this point — it is handled above.) - let spec = SystemContractSpec::new(SEQUENCER_REGISTRY_ADDRESS, target_code, target_code_hash) - .with_seed(seed) - .with_force_create_on_upgrade(true); - let state = crate::transact_deploy(db, &spec).map_err(BlockExecutionError::other)?; - Ok(Some(state)) -} - -/// Returns `(due, witness_state)` where `due` indicates whether the caller should issue -/// the pre-block `applyPendingChanges()` system call. -/// -/// The returned `EvmState` captures all reads (account + storage slots) as a witness record. -/// The executor MUST push this into outcomes regardless of `due` so that the reads enter -/// the stateless witness via `system_caller.on_state()`. -pub(crate) fn is_apply_pending_changes_due( - db: &mut State, - block_number: u64, -) -> Result<(bool, EvmState), BlockExecutionError> { - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - - let Some(info) = acc.account_info() else { - // Account does not exist — record a not-existing account entry for the witness. - let account = Account::new_not_existing(0); - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - return Ok((false, state)); - }; - - // Account exists — build a read-only account entry to record all slot reads. - let mut account = Account { info, ..Default::default() }; - - let system_address_due = is_role_due( - db, - &mut account, - PENDING_SYSTEM_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - block_number, - )?; - let sequencer_due = - is_role_due(db, &mut account, PENDING_SEQUENCER, SEQUENCER_ACTIVATION_BLOCK, block_number)?; - - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - Ok((system_address_due || sequencer_due, state)) -} - -/// Executes the pre-block `applyPendingChanges()` system call on the `SequencerRegistry`. -/// -/// This single system call applies both the system address change and the sequencer -/// change if they are due in the current block. -/// Caller should gate this with [`is_apply_pending_changes_due`] to avoid an EVM -/// call on every block. -/// -/// The system call is issued with `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` -/// instead of the upstream-fixed 30M. `applyPendingChanges()` writes role-rotation -/// slots whose actual cost depends on REX dynamic storage gas, so the upstream default -/// is no longer guaranteed to be enough on activation blocks. -pub(crate) fn transact_apply_pending_changes( - evm: &mut crate::MegaEvm, -) -> Result, BlockExecutionError> -where - DB: alloy_evm::Database, - ExtEnvs: crate::ExternalEnvTypes, -{ - let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); - let gas_limit = - evm.block_env_ref().gas_limit.max(crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR); - let result_and_state = match evm.transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - gas_limit, - ) { - Ok(res) => res, - Err(e) => { - return Err(BlockValidationError::BlockHashContractCall { - message: format!("SequencerRegistry applyPendingChanges() system call failed: {e}"), - } - .into()); - } - }; - - if !result_and_state.result.is_success() { - return Err(BlockValidationError::BlockHashContractCall { - message: "SequencerRegistry applyPendingChanges() reverted or halted".into(), - } - .into()); - } - - Ok(result_and_state) -} - -/// Resolves the current system address. -/// -/// Must be called after `commit_system_call_outcomes()` so that `SequencerRegistry` is -/// already deployed and its storage committed. -/// -/// - Pre-REX5: returns `(MEGA_SYSTEM_ADDRESS, None)`. -/// - REX5: reads `_currentSystemAddress` from committed registry storage. -/// -/// The single `spec` is read through two projections that answer different questions: -/// `is_enabled` (behavior) gates whether dynamic system-address resolution applies — an alias -/// window whose behavior projects below REX5 returns [`MEGA_SYSTEM_ADDRESS`] again — while -/// `reaches` (position) selects which registry bytecode version the pre-block deploy installed, -/// which a rollback does not change. -/// -/// The optional `EvmState` captures account + slot reads as a witness record. -/// The executor MUST commit this via `system_caller.on_state()` + `db.commit()`. -pub fn resolve_system_address( - hardforks: impl MegaHardforks, - spec: crate::MegaSpecId, - db: &mut State, -) -> Result<(Address, Option), BlockExecutionError> { - // One spec, two projections: `is_enabled` (behavior) gates whether dynamic resolution - // applies at all; `reaches` (position) selects the installed bytecode version below. - if !spec.is_enabled(crate::MegaSpecId::REX5) { - return Ok((MEGA_SYSTEM_ADDRESS, None)); - } - - // Fail fast if Rex5 is active but params are not configured. - hardforks.fork_params::().ok_or_else(|| { - BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistryConfig not configured".into(), - } - })?; - - let acc = - db.load_cache_account(SEQUENCER_REGISTRY_ADDRESS).map_err(BlockExecutionError::other)?; - - // Unreachable: deploy always runs and commits before resolve. - let Some(info) = acc.account_info() else { - return Err(BlockValidationError::BlockHashContractCall { - message: "Rex5 active but SequencerRegistry account does not exist".into(), - } - .into()); - }; - - // Unreachable: deploy verifies the code hash before seeding storage. The expected version - // follows the scheduled spec, matching what the pre-block deploy installed: the - // bytecode was already swapped to v2.0.0 at the Rex6 activation block, so an exact match - // holds on every block. - let expected_code_hash = if spec.reaches(crate::MegaSpecId::REX6) { - SEQUENCER_REGISTRY_CODE_HASH_REX6 - } else { - SEQUENCER_REGISTRY_CODE_HASH - }; - if info.code_hash != expected_code_hash { - return Err(BlockValidationError::BlockHashContractCall { - message: format!( - "SequencerRegistry code hash mismatch: expected {}, got {}", - expected_code_hash, info.code_hash - ), - } - .into()); - } - - // Build read-only witness: account entry + slot read. - let mut account = Account { info, ..Default::default() }; - let value = read_registry_storage(db, CURRENT_SYSTEM_ADDRESS)?; - // Read-only witness entry: record the slot access without marking it as changed. - account.storage.insert(CURRENT_SYSTEM_ADDRESS, EvmStorageSlot::new(value, 0)); - - // Unreachable: deploy seeds a non-zero initial system address. - if value.is_zero() { - return Err(BlockValidationError::BlockHashContractCall { - message: "SequencerRegistry deployed but _currentSystemAddress is zero".into(), - } - .into()); - } - - let state = EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, account)]); - - Ok((Address::from_word(value.into()), Some(state))) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256, B256}; - use mega_system_contracts::sequencer_registry::storage_slots::PENDING_ADMIN; - use revm::{ - context::BlockEnv, - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - use crate::{MegaHardforkConfig, MegaSpecId}; - - const TEST_SEQUENCER: Address = address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); - const TEST_ADMIN: Address = address!("0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); - /// A non-system test address, used as a stand-in for a `_currentSystemAddress` that has - /// already been rotated away from the genesis `MEGA_SYSTEM_ADDRESS`. Distinct from - /// genesis so tests can tell the two apart. - const TEST_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); - - const TEST_MIN_ROTATION_DELAY: u64 = 100; - - fn test_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: TEST_SEQUENCER, - rex5_initial_admin: TEST_ADMIN, - } - } - - fn test_rex6_config() -> SequencerRegistryRex6Config { - SequencerRegistryRex6Config { rex6_min_rotation_delay: TEST_MIN_ROTATION_DELAY } - } - - /// A chain running Rex5: the pre-upgrade world where the registry runs v1.0.0. - fn rex5_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX5) - .with_params(test_config()) - } - - /// All hardforks including Rex6, with both registry param sets attached. - fn rex6_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()) - .with_params(test_rex6_config()) - } - - #[test] - fn test_code_hash_matches() { - assert_eq!(keccak256(&SEQUENCER_REGISTRY_CODE), SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(keccak256(&SEQUENCER_REGISTRY_CODE_REX6), SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_ne!(SEQUENCER_REGISTRY_CODE_HASH, SEQUENCER_REGISTRY_CODE_HASH_REX6); - } - - /// Verifies that Rust slot constants match the Solidity storage layout. - /// These values come from `forge inspect SequencerRegistry storage-layout`. - /// If the Solidity field order changes, this test MUST be updated. - #[test] - fn test_slot_constants_match_solidity_layout() { - assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::from(0), "_currentSystemAddress = slot 0"); - assert_eq!(CURRENT_SEQUENCER, U256::from(1), "_currentSequencer = slot 1"); - assert_eq!(ADMIN, U256::from(2), "_admin = slot 2"); - assert_eq!(PENDING_ADMIN, U256::from(3), "_pendingAdmin = slot 3"); - assert_eq!(INITIAL_SYSTEM_ADDRESS, U256::from(4), "_initialSystemAddress = slot 4"); - assert_eq!(INITIAL_SEQUENCER, U256::from(5), "_initialSequencer = slot 5"); - assert_eq!(INITIAL_FROM_BLOCK, U256::from(6), "_initialFromBlock = slot 6"); - assert_eq!(PENDING_SYSTEM_ADDRESS, U256::from(7), "_pendingSystemAddress = slot 7"); - assert_eq!( - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(8), - "_systemAddressActivationBlock = slot 8" - ); - assert_eq!(PENDING_SEQUENCER, U256::from(9), "_pendingSequencer = slot 9"); - assert_eq!( - SEQUENCER_ACTIVATION_BLOCK, - U256::from(10), - "_sequencerActivationBlock = slot 10" - ); - // Slots 11 (_systemAddressHistory) and 12 (_sequencerHistory) are dynamic arrays. - assert_eq!(MIN_ROTATION_DELAY, U256::from(13), "_minRotationDelay = slot 13 (v2.0.0+)"); - } - - #[test] - fn test_deploy_requires_rex5() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - MegaHardforkConfig::default(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap(); - assert_eq!(result, None); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_sequencer() { - let mut config = test_config(); - config.rex5_initial_sequencer = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_sequencer must be rejected"); - assert!( - err.message.contains("rex5_initial_sequencer must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_admin() { - let mut config = test_config(); - config.rex5_initial_admin = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_admin must be rejected"); - assert!( - err.message.contains("rex5_initial_admin must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_deploy_seeds_storage() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert_eq!(account.storage.len(), 6, "should write exactly 6 flat slots"); - - assert_eq!( - account.storage.get(&CURRENT_SYSTEM_ADDRESS).unwrap().present_value(), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - "initial system address is hardcoded to MEGA_SYSTEM_ADDRESS", - ); - assert_eq!( - account.storage.get(&INITIAL_SYSTEM_ADDRESS).unwrap().present_value(), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - "_initialSystemAddress is hardcoded to MEGA_SYSTEM_ADDRESS", - ); - assert_eq!( - account.storage.get(&CURRENT_SEQUENCER).unwrap().present_value(), - U256::from_be_bytes(TEST_SEQUENCER.into_word().0), - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value(), - U256::from_be_bytes(TEST_ADMIN.into_word().0), - ); - assert_eq!( - account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), - U256::from(1000), - ); - } - - #[test] - fn test_deploy_is_idempotent() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 2000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "idempotent deploy should not re-create"); - assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); - } - - #[test] - fn test_deploy_wrong_existing_code_hash_returns_error() { - let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: wrong_code.hash_slow(), - code: Some(wrong_code), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let err = - transact_deploy_sequencer_registry(&hardforks, 0, 2000, &mut state, &test_config()) - .expect_err("wrong code hash must fail closed"); - - let msg = err.to_string(); - assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); - assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); - } - - #[test] - fn test_deploy_on_top_of_eoa_with_balance() { - let mut db = InMemoryDB::default(); - // Simulate an EOA that received ETH before Rex5. - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - balance: U256::from(1_000_000), - ..Default::default() // code_hash = KECCAK_EMPTY - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let result = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - // Pre-existing balance is preserved. - assert_eq!(account.info.balance, U256::from(1_000_000)); - } - - #[test] - fn test_validate_rejects_zero_min_rotation_delay() { - let config = SequencerRegistryRex6Config { rex6_min_rotation_delay: 0 }; - let err = config.validate().expect_err("zero rex6_min_rotation_delay must be rejected"); - assert!( - err.message.contains("rex6_min_rotation_delay must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_deploy_fresh_at_rex6_seeds_v2_with_min_rotation_delay() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - account.storage.len(), - 7, - "fresh Rex6 deploy writes the 6 bootstrap slots plus _minRotationDelay" - ); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value(), - U256::from_be_bytes(TEST_ADMIN.into_word().0), - ); - assert_eq!( - account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), - U256::from(1000), - ); - } - - #[test] - fn test_deploy_rex6_upgrades_v1_in_place_preserving_storage() { - // A live V1 registry with a pending sequencer change and a non-empty history. The Rex6 - // upgrade must swap only the bytecode and write only the new _minRotationDelay slot. - let pending_sequencer = address!("0x1111111111111111111111111111111111111111"); - let sequencer_history_length_slot = U256::from(12); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - TEST_SEQUENCER.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - pending_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(2000), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - sequencer_history_length_slot, - U256::from(1), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1500, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "in-place upgrade must not recreate the account"); - assert!(account.is_touched()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!(account.storage.len(), 1, "only _minRotationDelay is written on upgrade"); - let slot = account.storage.get(&MIN_ROTATION_DELAY).unwrap(); - assert_eq!(slot.original_value(), U256::ZERO); - assert_eq!(slot.present_value(), U256::from(TEST_MIN_ROTATION_DELAY)); - - // After commit, the live pre-upgrade storage must be intact next to the new slot. - revm::DatabaseCommit::commit(&mut state, result); - assert_eq!( - read_registry_storage(&mut state, PENDING_SEQUENCER).unwrap(), - U256::from_be_bytes(pending_sequencer.into_word().0), - ); - assert_eq!( - read_registry_storage(&mut state, SEQUENCER_ACTIVATION_BLOCK).unwrap(), - U256::from(2000), - ); - assert_eq!( - read_registry_storage(&mut state, sequencer_history_length_slot).unwrap(), - U256::from(1), - ); - assert_eq!( - read_registry_storage(&mut state, MIN_ROTATION_DELAY).unwrap(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - assert_eq!( - read_registry_storage(&mut state, CURRENT_SEQUENCER).unwrap(), - U256::from_be_bytes(TEST_SEQUENCER.into_word().0), - ); - } - - #[test] - fn test_deploy_rex6_is_idempotent_when_v2_present() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "idempotent deploy should not re-create"); - assert!(!account.is_touched(), "idempotent deploy should not touch the account"); - assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); - } - - #[test] - fn test_deploy_rex6_missing_config_errors() { - // Rex6 active but only the Rex5 params attached: deploy must fail fast instead of - // installing a v2.0.0 registry with an unseeded _minRotationDelay. - let hardforks = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()); - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .expect_err("missing Rex6 params must fail closed"); - assert!( - err.to_string().contains("SequencerRegistryRex6Config not configured"), - "unexpected message: {err}" - ); - } - - #[test] - fn test_deploy_rex6_on_top_of_eoa_with_balance() { - let mut db = InMemoryDB::default(); - // Simulate an EOA that received ETH before the registry was ever deployed. Even at - // Rex6 this is a fresh bootstrap, not a storage-preserving upgrade: the full seed - // (including _minRotationDelay) must be written. - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!(account.info.balance, U256::from(1_000_000)); - assert_eq!(account.storage.len(), 7); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - } - - #[test] - fn test_deploy_rex6_wrong_existing_code_hash_errors() { - let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: wrong_code.hash_slow(), - code: Some(wrong_code), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .expect_err("wrong code hash must fail closed"); - - let msg = err.to_string(); - assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); - assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); - } - - #[test] - fn test_resolve_rex6_expects_v2_code_hash() { - // A V2 registry resolves normally at REX6. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - assert!(witness.is_some()); - } - - #[test] - fn test_resolve_rex6_rejects_v1_code_hash() { - // At REX6 the pre-block deploy has already upgraded the bytecode, so a V1 code hash at - // resolve time is a broken pipeline and must fail closed. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state) - .expect_err("V1 code hash at REX6 must fail closed"); - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_resolve_pre_rex5_returns_legacy() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, _) = - resolve_system_address(MegaHardforkConfig::default(), MegaSpecId::REX4, &mut state) - .unwrap(); - assert_eq!(addr, MEGA_SYSTEM_ADDRESS); - } - - #[test] - fn test_resolve_rex5_returns_stored_system_address_with_witness() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - - // Witness must capture the registry account and the CURRENT_SYSTEM_ADDRESS slot. - let witness = witness.expect("post-deploy resolve must produce witness"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("registry account in witness"); - assert_eq!(acc.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert!( - acc.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), - "witness must include CURRENT_SYSTEM_ADDRESS slot" - ); - assert_eq!(acc.storage.len(), 1, "witness should contain exactly one slot"); - let slot = acc.storage.get(&CURRENT_SYSTEM_ADDRESS).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - - #[test] - fn test_resolve_rex5_zero_slot_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state); - assert!(result.is_err(), "zero _currentSystemAddress should be an error"); - } - - #[test] - fn test_resolve_rex5_missing_registry_errors() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let err = resolve_system_address(&hardforks, MegaSpecId::REX5, &mut state) - .expect_err("missing registry at Rex5 must fail closed"); - assert!(err.to_string().contains("does not exist")); - } - - #[test] - fn test_resolve_rex5_wrong_code_hash_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: B256::ZERO, - code: Some(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state) - .expect_err("wrong code hash must fail closed"); - - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_is_apply_pending_changes_due_no_registry() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must contain a not-existing account entry. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert_eq!(acc.status, revm::state::AccountStatus::LoadedAsNotExisting); - assert!(acc.storage.is_empty(), "no-registry witness should have no slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_no_pending() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must include both PENDING_* slots (both zero = no change pending). - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert!( - acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS), - "witness must include PENDING_SYSTEM_ADDRESS" - ); - assert!( - acc.storage.contains_key(&PENDING_SEQUENCER), - "witness must include PENDING_SEQUENCER" - ); - // No activation slots needed because both pending values are zero. - assert_eq!(acc.storage.len(), 2, "no-pending witness should have exactly 2 slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_system_address_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_addr = address!("0x1111111111111111111111111111111111111111"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_addr.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - // Not yet due at block 999. - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 999).unwrap(); - assert!(!due, "not yet due"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - - // Exactly due at block 1000 (fresh State to avoid cache from prior call). - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(due, "exactly due"); - // Both roles' pending slots are always read into the witness. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - } - - #[test] - fn test_is_apply_pending_changes_due_sequencer_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(500), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 500).unwrap(); - assert!(due); - // System address has no pending change (slot is zero) so only PENDING_SYSTEM_ADDRESS - // is read. Then sequencer path reads PENDING_SEQUENCER + SEQUENCER_ACTIVATION_BLOCK. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 3); - } - - #[test] - fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_sys = address!("0x1111111111111111111111111111111111111111"); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_sys.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1001), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!( - due, - "sequencer change should still trigger the pre-block call when the system address is not due yet" - ); - // System address is not due (activation at 1001) but its pending slot + activation - // slot are still read. Then the sequencer path reads its own pending + activation. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 4, "both roles' slots should be in the witness"); - for slot_key in [ - PENDING_SYSTEM_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - PENDING_SEQUENCER, - SEQUENCER_ACTIVATION_BLOCK, - ] { - let slot = acc.storage.get(&slot_key).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - } - - #[test] - fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let next_system_address = address!("0x1111111111111111111111111111111111111111"); - let next_sequencer = address!("0x2222222222222222222222222222222222222222"); - - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - TEST_SEQUENCER.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - next_system_address.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - next_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let result = - transact_apply_pending_changes(&mut evm).expect("applyPendingChanges() should succeed"); - let state = result.state; - drop(evm); - - revm::DatabaseCommit::commit(&mut db, state); - - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS) - .unwrap(), - address_to_storage_value(next_system_address), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER) - .unwrap(), - address_to_storage_value(next_sequencer), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - } - - #[test] - fn test_transact_apply_pending_changes_uses_block_gas_limit() { - // Block gas_limit > 30M must be passed through to the system call so that - // applyPendingChanges() can absorb the variable cost from REX dynamic - // storage gas instead of being capped at the upstream-fixed 30M. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 250_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!(revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, 250_000_000); - } - - #[test] - fn test_transact_apply_pending_changes_respects_30m_floor() { - // When the block gas limit is below the 30M floor, the system call must - // still receive at least the historical default budget. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 1_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!( - revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, - crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR, - ); - } - - #[test] - fn test_transact_apply_pending_changes_errors_when_registry_reverts() { - let revert_code = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: revert_code.hash_slow(), - code: Some(revert_code), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let err = transact_apply_pending_changes(&mut evm) - .expect_err("reverting registry bytecode must fail closed"); - - assert!(err.to_string().contains("reverted or halted")); - } -} diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs deleted file mode 100644 index 4d3fcc06f..000000000 --- a/crates/mega-evm/src/system/tx.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! System transaction for the `MegaETH` EVM. -//! -//! The mega system transaction is a special protocol-maintenance transaction with minimal -//! side effects: -//! - no transaction fee (no L2 gas fee, no L1 data fee, no base fee, etc.), thus no state change to -//! the block beneficiary or any fee vaults. -//! - system address's nonce still bumps as normal transactions -//! -//! This module contains constants, types, and utilities related to mega system transactions. - -use alloy_primitives::{address, b256, Address, TxKind, B256}; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; -use revm::context::Transaction; - -use crate::{types::MegaTransaction, ORACLE_CONTRACT_ADDRESS}; - -/// The `MegaETH` system address for deposit-like transaction processing. -/// Normal transactions sent from this address are processed as deposit transactions, -/// bypassing signature validation, nonce verification, and fee deduction. -/// -/// It can only call whitelisted addresses. -pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); - -/// The whitelist of addresses that are allowed to be called by the `MegaETH` system address. -pub const MEGA_SYSTEM_TX_WHITELIST: &[Address] = &[ORACLE_CONTRACT_ADDRESS]; - -/// The source hash of the `MegaETH` system transaction, used to set the `source_hash` field of the -/// op deposit info. The value is `keccak256("MEGA_SYSTEM_TRANSACTION")`. -pub const MEGA_SYSTEM_TRANSACTION_SOURCE_HASH: B256 = - b256!("852c082c0faff590c6300c2c34815d1f79882552fa95ba413cd5aeb1dba84957"); - -/// The source hash of the `MegaETH` keyless-deploy sandbox transaction. Used to set the -/// `source_hash` field of the op deposit info so the sandbox tx is treated as a deposit-like -/// transaction (bypasses L1/operator fee, validation, fee distribution). The value is -/// `keccak256("MEGA_SANDBOX_TRANSACTION")`. -pub const SANDBOX_TX_SOURCE_HASH: B256 = - b256!("3bc757a39ecb6dc5b5e5715352016c2b6fd38968a78cc57e878d9be249bc62f4"); - -/// Checks if a transaction is sent from the given system address. -pub fn sent_from_system_address(tx: &MegaTransaction, system_address: Address) -> bool { - tx.caller() == system_address -} - -/// Checks if a transaction is a mega system transaction using the given system address. -/// A mega system transaction is a legacy transaction that is submitted by the system address -/// and calls a whitelisted address in `MEGA_SYSTEM_TX_WHITELIST`. -pub fn is_mega_system_transaction_with(tx: &MegaTransaction, system_address: Address) -> bool { - check_if_mega_system_transaction(tx.caller(), tx.tx_type(), tx.kind(), system_address) -} - -/// Checks if a transaction is a mega system transaction. -/// -/// # Arguments -/// -/// * `tx_signer` - The signer of the transaction -/// * `tx_type` - The type of the transaction -/// * `tx_kind` - The kind of the transaction -/// * `system_address` - The current system address for this block -/// -/// # Returns -/// -/// Returns `true` if the transaction is a mega system transaction, `false` otherwise. -pub fn check_if_mega_system_transaction( - tx_signer: Address, - tx_type: u8, - tx_kind: TxKind, - system_address: Address, -) -> bool { - if tx_type == 0x0 && tx_signer == system_address { - // a mega system transaction must be a legacy transaction - match tx_kind { - TxKind::Create => false, - TxKind::Call(address) => MEGA_SYSTEM_TX_WHITELIST.contains(&address), - } - } else { - false - } -} - -/// Checks if a transaction should be processed as a deposit-like transaction. -/// -/// This includes both actual deposit transactions (`DEPOSIT_TRANSACTION_TYPE`) and normal -/// transactions from the `MegaETH` system address (mega system transactions). -/// -/// # Arguments -/// -/// * `tx` - The transaction to check -/// -/// # Returns -/// -/// Returns `true` if the transaction should be processed as deposit-like, `false` otherwise. -pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address) -> bool { - // Check if it's an actual deposit transaction - if tx.tx_type() == DEPOSIT_TRANSACTION_TYPE { - return true; - } - - // Check if it's from the mega system address - is_mega_system_transaction_with(tx, system_address) -} - -/// Checks if a transaction is *system-originated*: produced by the protocol itself or by the -/// sequencer acting as the system address, as opposed to any user transaction. -/// -/// A transaction is system-originated when either: -/// - its caller is the EIP-2935 / EIP-4788 system address (`0xff..fe`), which is how mega-evm's own -/// pre-block system calls (block-hash, beacon-root, `SequencerRegistry`) are issued; or -/// - it is a mega system transaction: a legacy transaction from `system_address` calling a -/// whitelisted contract (see [`is_mega_system_transaction_with`]). -/// -/// Neither branch can be produced by a user: `0xff..fe` has no key and is only ever set as -/// caller by the protocol's own pre-block helpers, and matching `system_address` requires the -/// protocol's deposit-injection path. In particular this deliberately does **not** match an -/// arbitrary user deposit transaction (`DEPOSIT_TRANSACTION_TYPE`), unlike -/// [`is_deposit_like_transaction`]. -/// -/// REX6+ uses this to exempt system-originated execution from `MegaETH`'s per-transaction resource -/// metering (SALT-scaled storage gas, the four `AdditionalLimit` dimensions, and gas detention), -/// so protocol-mandated state changes can never fail due to metering — e.g. when SALT buckets -/// grow. The standard EVM `gas_limit` still bounds the work as a runaway guard. -/// -/// The exemption is evaluated in `MegaContext::on_new_tx`, which runs *after* `before_run` has -/// already deposit-promoted a mega system tx (stamping [`MEGA_SYSTEM_TRANSACTION_SOURCE_HASH`] and -/// flipping `tx_type()` to a deposit). The source-hash branch below therefore carries the match for -/// promoted txs; the `is_mega_system_transaction_with` branch covers the pre-promotion shape for -/// any other caller. Both the source hash and the system-address+whitelist gate are protocol-set, -/// so a user deposit (different source hash, non-system caller) is never matched — unlike -/// [`is_deposit_like_transaction`]. -pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bool { - // Internal pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) use `0xff..fe` and - // run via `run_system_call`, so they are never deposit-promoted. - tx.caller() == alloy_eips::eip4788::SYSTEM_ADDRESS || - // A mega system tx that `before_run` has already promoted to a deposit. - tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH || - // A mega system tx in its original (pre-promotion) legacy shape. - is_mega_system_transaction_with(tx, system_address) -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::TxKind; - - const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; - const USER: Address = address!("0000000000000000000000000000000000009999"); - const NON_WHITELIST: Address = address!("00000000000000000000000000000000000000ab"); - - /// Builds a legacy (type 0x0) call transaction with the given caller and callee. - fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { - let mut tx = MegaTransaction::default(); - tx.base.tx_type = 0; - tx.base.caller = caller; - tx.base.kind = TxKind::Call(to); - tx - } - - #[test] - fn test_is_system_originated_matches_eip_system_address_caller() { - // The protocol's own pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) - // use `0xff..fe` as caller; it matches regardless of the resolved system address or target. - let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(is_system_originated(&tx, USER)); - } - - #[test] - fn test_is_system_originated_matches_mega_system_tx() { - // Sequencer mega system tx: legacy tx from the system address to a whitelisted contract. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { - // System address calling a non-whitelisted contract is not a mega system tx. - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NON_WHITELIST); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_matches_promoted_mega_system_tx() { - // `before_run` promotes a mega system tx to a deposit (stamping the source hash and - // flipping `tx_type()`) *before* `on_new_tx` evaluates the exemption. The promoted shape - // must still be recognized as system-originated. - let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "promotion flips tx_type to deposit"); - assert!( - !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), - "the legacy-typed check no longer matches after promotion", - ); - assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "but the source-hash branch does"); - } - - #[test] - fn test_is_system_originated_rejects_user_tx() { - let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - - #[test] - fn test_is_system_originated_rejects_user_deposit_tx() { - // Anti-bypass: a user deposit transaction (non-system caller) must NOT be treated as - // system-originated, even though `is_deposit_like_transaction` classifies any deposit as - // deposit-like. Otherwise a user could craft a deposit to escape SALT-scaled storage gas. - let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - // A non-zero deposit source hash makes `tx_type()` report `DEPOSIT_TRANSACTION_TYPE`. - tx.deposit.source_hash = B256::repeat_byte(0x11); - assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } -} diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index 4bfb1817b..47afb46ca 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -4,8 +4,8 @@ use alloy_primitives::{Address, Bytes, B256, U256}; use delegate::delegate; use revm::{ database::{AccountState, CacheDB, DBErrorMarker, EmptyDB}, - primitives::{HashMap, StorageKey, StorageValue}, - state::{Account, AccountInfo, Bytecode}, + primitives::{StorageKey, StorageValue}, + state::{AccountInfo, Bytecode, EvmState}, }; /// A memory database for testing purposes. @@ -116,7 +116,7 @@ impl revm::Database for MemoryDatabase { impl revm::DatabaseCommit for MemoryDatabase { delegate! { to self.db { - fn commit(&mut self, changes: revm::primitives::HashMap); + fn commit(&mut self, changes: EvmState); } } } @@ -189,7 +189,7 @@ impl revm::Database for ErrorInjectingDatabase { } impl revm::DatabaseCommit for ErrorInjectingDatabase { - fn commit(&mut self, changes: HashMap) { + fn commit(&mut self, changes: EvmState) { self.inner.commit(changes); } } diff --git a/crates/mega-evm/src/test_utils/evm.rs b/crates/mega-evm/src/test_utils/evm.rs index 58f0ef1e2..5a54bc43b 100644 --- a/crates/mega-evm/src/test_utils/evm.rs +++ b/crates/mega-evm/src/test_utils/evm.rs @@ -1,45 +1,52 @@ +use alloy_evm::{Database, Evm}; +use alloy_op_evm::OpTx; use alloy_primitives::{Address, Bytes, TxKind, U256}; -use core::fmt::Debug; -use revm::{ - context::{ - result::{EVMError, ResultAndState}, - TxEnv, - }, - Database, +use op_revm::{L1BlockInfo, OpTransaction}; +use revm::context::{ + result::{EVMError, ResultAndState}, + TxEnv, }; -use crate::{ - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, -}; +use crate::{MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionError}; + +/// L1 block info with zero operator fee, so a transaction pays no L1-side fee. +pub fn zero_fee_l1_block_info() -> L1BlockInfo { + L1BlockInfo { + operator_fee_scalar: Some(U256::ZERO), + operator_fee_constant: Some(U256::ZERO), + ..Default::default() + } +} + +/// Wraps `tx` as a non-deposit OP transaction with an empty enveloped encoding, so its L1 data +/// fee is zero. +pub fn op_transaction(tx: TxEnv) -> OpTransaction { + OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() } +} -/// Executes a transaction on the EVM. -pub fn transact( +/// Executes one transaction on a fresh [`MegaEvm`] over `db` and returns its result and state +/// without committing. +/// +/// The L1 fees are zero (see [`zero_fee_l1_block_info`] and [`op_transaction`]) and so is the +/// gas price, so the caller needs no balance beyond `value`. A `gas_limit` above the execution +/// cap puts the excess into the state-gas reservoir. +pub fn transact( spec: MegaSpecId, db: DB, caller: Address, callee: Option
, data: Bytes, value: U256, -) -> Result, EVMError> -where - DB: Database + Debug, - DB::Error: Send + Sync + Debug + 'static, -{ - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); + gas_limit: u64, +) -> Result, EVMError> { + let context = MegaContext::new(db, spec).with_chain(zero_fee_l1_block_info()); let tx = TxEnv { caller, kind: callee.map_or(TxKind::Create, TxKind::Call), data, value, - gas_limit: 1000000000000000000, + gas_limit, ..Default::default() }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) + MegaEvm::new(context).transact_raw(OpTx(op_transaction(tx))) } diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index 3e6f7c544..cd9b7c74e 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -5,9 +5,11 @@ mod database; mod evm; mod inspectors; mod opcode_gen; +mod scenario; pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; pub use opcode_gen::*; +pub use scenario::*; diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs index 788cecb32..a5dca8e55 100644 --- a/crates/mega-evm/src/test_utils/opcode_gen.rs +++ b/crates/mega-evm/src/test_utils/opcode_gen.rs @@ -163,14 +163,11 @@ mod tests { use core::convert::Infallible; use alloy_primitives::address; - use revm::context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - }; + use revm::context::result::{EVMError, ResultAndState}; use crate::{ - test_utils::MemoryDatabase, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, + test_utils::{transact, MemoryDatabase}, + MegaHaltReason, MegaSpecId, MegaTransactionError, }; use super::*; @@ -178,19 +175,19 @@ mod tests { fn execute_bytecode( bytecode: Bytes, ) -> Result, EVMError> { + let caller = address!("0000000000000000000000000000000000100000"); let contract = address!("0000000000000000000000000000000000100001"); let mut db = MemoryDatabase::default(); db.set_account_code(contract, bytecode); - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default().call(contract).gas_limit(1_000_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) + transact( + MegaSpecId::SATIN, + &mut db, + caller, + Some(contract), + Bytes::new(), + U256::ZERO, + 1_000_000, + ) } #[test] diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs new file mode 100644 index 000000000..0739b5c01 --- /dev/null +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -0,0 +1,536 @@ +//! Transaction scenarios: a pre-state and a sequence of transactions, read from JSON. +//! +//! A [`Scenario`] describes a transaction sequence as data, so it can run through [`MegaEvm`] +//! and through another EVM alike. The `corpus` bench reads its inputs in this format, so its +//! instruction counts move when the semantics or the pricing of those scenarios move. +//! +//! The block, the configuration and the L1 fees are fixed, so a scenario is fully described by +//! its accounts and transactions: +//! +//! - the block is [`Scenario::block`]: number 1, timestamp 1, the scenario's coinbase, zero base +//! fee, unlimited gas; +//! - the configuration is what [`MegaContext`] fixes for the spec; +//! - the L1 fees are zero ([`zero_fee_l1_block_info`], [`op_transaction`]), and the gas price is +//! the transaction's own (zero unless it sets one). + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::{collections::BTreeMap, format, string::String, vec::Vec}; + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use core::convert::Infallible; +use revm::{ + context::{ + result::{EVMError, ResultAndState}, + transaction::{ + AccessList, AccessListItem, Authorization, RecoveredAuthority, RecoveredAuthorization, + TransactionType, + }, + BlockEnv, TxEnv, + }, + state::{AccountInfo, Bytecode}, + Database, DatabaseCommit, +}; +use serde::Deserialize; + +use crate::{ + test_utils::{op_transaction, zero_fee_l1_block_info, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionError, +}; + +/// The outcome of one scenario transaction on [`MegaEvm`]. +pub type ScenarioTxOutcome = + Result, EVMError>; + +/// A pre-state and the transactions to run on it, in order. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Scenario { + /// Name of the scenario; the harness reports differences under it. + pub name: String, + /// What the scenario exercises, for the reader. + #[serde(default)] + pub description: String, + /// The block beneficiary. + #[serde(default)] + pub coinbase: Address, + /// The accounts that exist before the first transaction. + pub pre: BTreeMap, + /// The transactions, run in order, each on the state the previous one left. + pub txs: Vec, +} + +/// An account of the pre-state. +#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PreAccount { + /// Account nonce. + #[serde(default)] + pub nonce: u64, + /// Account balance. + #[serde(default)] + pub balance: U256, + /// Legacy bytecode; empty for an account without code. + #[serde(default)] + pub code: Bytes, + /// Storage slots. + #[serde(default)] + pub storage: BTreeMap, +} + +/// How a scenario transaction is run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ScenarioTxKind { + /// A message call to `to`. + #[default] + Call, + /// A contract-creation transaction with `data` as init code. + Create, + /// A system call to `to`, as a block executor makes one: no fee, no nonce, the engine's + /// system-call gas limit. + SystemCall, +} + +/// A scenario transaction. +/// +/// The nonce is the caller's nonce in the state the transaction runs on. The transaction type +/// follows from the lists: EIP-7702 with an authorization list, EIP-2930 with only an access +/// list, legacy otherwise. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScenarioTx { + /// Sender. + pub caller: Address, + /// Target of a call or a system call; absent for a create. + #[serde(default)] + pub to: Option
, + /// Calldata, or init code for a create. + #[serde(default)] + pub data: Bytes, + /// Value sent. + #[serde(default)] + pub value: U256, + /// Gas limit. Required for calls and creates; a system call runs with the engine's + /// system-call gas limit and must not set one. + #[serde(default)] + pub gas_limit: Option, + /// Gas price. With the block's zero base fee it is the effective price of every + /// transaction type; zero by default, so a caller needs no balance for gas. + #[serde(default)] + pub gas_price: u128, + /// How the transaction is run. + #[serde(default)] + pub kind: ScenarioTxKind, + /// EIP-2930 access list. + #[serde(default)] + pub access_list: Vec, + /// EIP-7702 authorization list. + #[serde(default)] + pub authorization_list: Vec, +} + +/// An EIP-2930 access list entry. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AccessListEntry { + /// Address to warm. + pub address: Address, + /// Storage keys of `address` to warm. + #[serde(default)] + pub storage_keys: Vec, +} + +/// An EIP-7702 authorization with its signer already recovered. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuthorizationEntry { + /// Chain id the authorization is valid on; zero for any chain. + #[serde(default)] + pub chain_id: U256, + /// Address the authority delegates to. + pub address: Address, + /// Nonce the authority must have. + pub nonce: u64, + /// The recovered signer; absent for a signature that does not recover. + #[serde(default)] + pub authority: Option
, +} + +impl Scenario { + /// Checks that the pre-state code decodes and that each transaction carries the fields its + /// kind needs. + pub fn validate(&self) -> Result<(), String> { + for (address, account) in &self.pre { + if let Err(err) = Bytecode::new_raw_checked(account.code.clone()) { + return Err(format!("{}: code of {address}: {err:?}", self.name)); + } + } + for (i, tx) in self.txs.iter().enumerate() { + let problem = match tx.kind { + ScenarioTxKind::Call if tx.to.is_none() => Some("a call needs `to`"), + ScenarioTxKind::Create if tx.to.is_some() => Some("a create must not set `to`"), + ScenarioTxKind::Create if !tx.authorization_list.is_empty() => { + Some("an EIP-7702 transaction cannot create") + } + ScenarioTxKind::Call | ScenarioTxKind::Create if tx.gas_limit.is_none() => { + Some("a call or a create needs `gas_limit`") + } + ScenarioTxKind::SystemCall if tx.to.is_none() => Some("a system call needs `to`"), + ScenarioTxKind::SystemCall + if tx.gas_limit.is_some() || + tx.gas_price != 0 || + !tx.value.is_zero() || + !tx.access_list.is_empty() || + !tx.authorization_list.is_empty() => + { + Some("a system call takes only `caller`, `to` and `data`") + } + _ => None, + }; + if let Some(problem) = problem { + return Err(format!("{}: tx[{i}]: {problem}", self.name)); + } + } + Ok(()) + } + + /// The pre-state as a database. + /// + /// Code is decoded as the node decodes it: an EIP-7702 delegation designator becomes a + /// delegation, anything else legacy bytecode. + /// + /// # Panics + /// + /// If the scenario does not [`validate`](Self::validate). + pub fn database(&self) -> MemoryDatabase { + let mut db = MemoryDatabase::default(); + for (address, account) in &self.pre { + let mut info = AccountInfo { + nonce: account.nonce, + balance: account.balance, + ..Default::default() + }; + if !account.code.is_empty() { + let code = Bytecode::new_raw_checked(account.code.clone()) + .expect("validated: the pre-state code decodes"); + info.code_hash = code.hash_slow(); + info.code = Some(code); + } + db.insert_account_info(*address, info); + for (slot, value) in &account.storage { + db.set_account_storage(*address, *slot, *value); + } + } + db + } + + /// The block every transaction of the scenario runs in. + pub fn block(&self) -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1), + beneficiary: self.coinbase, + basefee: 0, + gas_limit: u64::MAX, + ..Default::default() + } + } + + /// Runs every transaction on a fresh [`MegaEvm`] over `db`, committing the state of each + /// successful one before the next. Returns the outcomes in order and the final database. + /// + /// # Panics + /// + /// If the scenario does not [`validate`](Self::validate). + pub fn run(&self, mut db: MemoryDatabase) -> (Vec, MemoryDatabase) { + let mut outcomes = Vec::with_capacity(self.txs.len()); + for tx in &self.txs { + let ctx = MegaContext::new(&mut db, MegaSpecId::SATIN) + .with_block(self.block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + let outcome = match tx.kind { + ScenarioTxKind::SystemCall => evm.transact_system_call( + tx.caller, + tx.to.expect("validated: a system call has a target"), + tx.data.clone(), + ), + ScenarioTxKind::Call | ScenarioTxKind::Create => { + let nonce = evm.db_mut().basic(tx.caller).unwrap().map_or(0, |info| info.nonce); + evm.transact_raw(OpTx(op_transaction(tx.tx_env(nonce)))) + } + }; + drop(evm); + if let Ok(outcome) = &outcome { + db.commit(outcome.state.clone()); + } + outcomes.push(outcome); + } + (outcomes, db) + } +} + +impl ScenarioTx { + /// The EIP-2718 transaction type the lists imply. + pub fn tx_type(&self) -> TransactionType { + if !self.authorization_list.is_empty() { + TransactionType::Eip7702 + } else if !self.access_list.is_empty() { + TransactionType::Eip2930 + } else { + TransactionType::Legacy + } + } + + /// The transaction as the EVM executes it, with `nonce` as the sender's nonce. + /// + /// Only meaningful for calls and creates; a system call is built by the engine. + /// + /// # Panics + /// + /// If the transaction has no gas limit, which [`Scenario::validate`] rejects for a call or + /// a create. + pub fn tx_env(&self, nonce: u64) -> TxEnv { + let access_list = AccessList( + self.access_list + .iter() + .map(|entry| AccessListItem { + address: entry.address, + storage_keys: entry.storage_keys.iter().map(|key| (*key).into()).collect(), + }) + .collect(), + ); + let authorizations = self + .authorization_list + .iter() + .map(|entry| { + RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: entry.chain_id, + address: entry.address, + nonce: entry.nonce, + }, + entry.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + ) + }) + .collect(); + TxEnv::builder() + .tx_type(Some(self.tx_type() as u8)) + .caller(self.caller) + .kind(self.to.map_or(TxKind::Create, TxKind::Call)) + .data(self.data.clone()) + .value(self.value) + .gas_limit(self.gas_limit.expect("a call or a create has a gas limit")) + .gas_price(self.gas_price) + .gas_priority_fee( + (self.tx_type() == TransactionType::Eip7702).then_some(self.gas_price), + ) + .nonce(nonce) + .access_list(access_list) + .authorization_list_recovered(authorizations) + .build_fill() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::BytecodeBuilder; + use alloy_primitives::address; + + const CALLER: Address = address!("0x0000000000000000000000000000000000000aaa"); + const CALLEE: Address = address!("0x0000000000000000000000000000000000000bbb"); + + fn call(gas_limit: Option) -> ScenarioTx { + ScenarioTx { + caller: CALLER, + to: Some(CALLEE), + data: Bytes::new(), + value: U256::ZERO, + gas_limit, + gas_price: 0, + kind: ScenarioTxKind::Call, + access_list: Vec::new(), + authorization_list: Vec::new(), + } + } + + fn scenario(txs: Vec) -> Scenario { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)).stop().build(); + Scenario { + name: "sstore".into(), + description: String::new(), + coinbase: Address::ZERO, + pre: [ + (CALLER, PreAccount { balance: U256::from(10), ..Default::default() }), + (CALLEE, PreAccount { nonce: 1, code, ..Default::default() }), + ] + .into_iter() + .collect(), + txs, + } + } + + #[test] + fn test_validate_rejects_a_call_without_gas_limit() { + assert!(scenario(vec![call(Some(100_000))]).validate().is_ok()); + let err = scenario(vec![call(None)]).validate().unwrap_err(); + assert_eq!(err, "sstore: tx[0]: a call or a create needs `gas_limit`"); + } + + /// Each kind needs the fields of its own shape; a missing or an excess field is rejected + /// with the rule that names it, so a scenario cannot reach the arms as something else. + #[test] + fn test_validate_rejects_a_transaction_that_does_not_match_its_kind() { + let reject = |tx: ScenarioTx| scenario(vec![tx]).validate().unwrap_err(); + let create = + || ScenarioTx { kind: ScenarioTxKind::Create, to: None, ..call(Some(100_000)) }; + + assert_eq!( + reject(ScenarioTx { to: None, ..call(Some(100_000)) }), + "sstore: tx[0]: a call needs `to`" + ); + assert_eq!( + reject(ScenarioTx { kind: ScenarioTxKind::Create, ..call(Some(100_000)) }), + "sstore: tx[0]: a create must not set `to`" + ); + assert_eq!( + reject(ScenarioTx { + authorization_list: vec![AuthorizationEntry { + chain_id: U256::ZERO, + address: CALLEE, + nonce: 0, + authority: None, + }], + ..create() + }), + "sstore: tx[0]: an EIP-7702 transaction cannot create" + ); + assert!(scenario(vec![create()]).validate().is_ok()); + } + + /// A system call is built by the engine, so it takes only what the engine does not fix; + /// each of the other fields is rejected on its own. + #[test] + fn test_validate_rejects_a_system_call_that_sets_an_engine_field() { + let system_call = || ScenarioTx { kind: ScenarioTxKind::SystemCall, ..call(None) }; + let reject = |tx: ScenarioTx| scenario(vec![tx]).validate().unwrap_err(); + let extra = "sstore: tx[0]: a system call takes only `caller`, `to` and `data`"; + let authorization = + AuthorizationEntry { chain_id: U256::ZERO, address: CALLEE, nonce: 0, authority: None }; + let access = AccessListEntry { address: CALLEE, storage_keys: Vec::new() }; + + assert!(scenario(vec![system_call()]).validate().is_ok()); + assert_eq!( + reject(ScenarioTx { to: None, ..system_call() }), + "sstore: tx[0]: a system call needs `to`" + ); + assert_eq!(reject(ScenarioTx { gas_limit: Some(100_000), ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { gas_price: 1, ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { value: U256::from(1), ..system_call() }), extra); + assert_eq!(reject(ScenarioTx { access_list: vec![access], ..system_call() }), extra); + assert_eq!( + reject(ScenarioTx { authorization_list: vec![authorization], ..system_call() }), + extra + ); + } + + /// The block is the same for every scenario, except for the beneficiary, which the scenario + /// sets. + #[test] + fn test_block_is_fixed_except_for_the_beneficiary() { + let mut scenario = scenario(vec![]); + scenario.coinbase = CALLEE; + let block = scenario.block(); + + assert_eq!(block.number, U256::from(1)); + assert_eq!(block.timestamp, U256::from(1)); + assert_eq!(block.beneficiary, CALLEE); + assert_eq!(block.basefee, 0); + assert_eq!(block.gas_limit, u64::MAX); + } + + /// Each transaction runs on the state the previous one committed, with the caller's + /// current nonce. + #[test] + fn test_run_commits_each_transaction_before_the_next() { + let scenario = scenario(vec![call(Some(100_000)), call(Some(100_000))]); + let (outcomes, mut db) = scenario.run(scenario.database()); + + assert_eq!(outcomes.len(), 2); + assert!(outcomes.iter().all(|outcome| outcome.as_ref().unwrap().result.is_success())); + assert_eq!(db.basic(CALLER).unwrap().unwrap().nonce, 2); + assert_eq!(db.storage(CALLEE, U256::ZERO).unwrap(), U256::from(7)); + } + + /// The database holds every field of every pre-state account. + #[test] + fn test_database_holds_the_pre_state() { + let mut scenario = scenario(vec![]); + scenario.pre.get_mut(&CALLEE).unwrap().storage.insert(U256::from(1), U256::from(9)); + let mut db = scenario.database(); + + let caller = db.basic(CALLER).unwrap().unwrap(); + assert_eq!((caller.nonce, caller.balance), (0, U256::from(10))); + let callee = db.basic(CALLEE).unwrap().unwrap(); + assert_eq!((callee.nonce, callee.balance), (1, U256::ZERO)); + assert_eq!(callee.code.unwrap().original_bytes(), scenario.pre[&CALLEE].code); + assert_eq!(db.storage(CALLEE, U256::from(1)).unwrap(), U256::from(9)); + } + + /// A delegation designator in the pre-state is a delegation, not legacy code that starts + /// with an invalid opcode. + #[test] + fn test_database_decodes_a_delegation_designator() { + let mut scenario = scenario(vec![]); + let designator: Bytes = [&[0xef, 0x01, 0x00][..], CALLEE.as_slice()].concat().into(); + scenario.pre.get_mut(&CALLER).unwrap().code = designator; + assert!(scenario.validate().is_ok()); + + let code = scenario.database().basic(CALLER).unwrap().unwrap().code.unwrap(); + assert!(code.is_eip7702()); + + scenario.pre.get_mut(&CALLER).unwrap().code = Bytes::from_static(&[0xef, 0x01, 0x00]); + assert!(scenario.validate().unwrap_err().starts_with("sstore: code of")); + } + + #[test] + fn test_tx_type_follows_the_lists() { + let mut tx = call(Some(100_000)); + assert_eq!(tx.tx_env(0).tx_type, TransactionType::Legacy as u8); + tx.access_list.push(AccessListEntry { address: CALLEE, storage_keys: vec![U256::ZERO] }); + assert_eq!(tx.tx_env(0).tx_type, TransactionType::Eip2930 as u8); + tx.authorization_list.push(AuthorizationEntry { + chain_id: U256::ZERO, + address: CALLEE, + nonce: 0, + authority: None, + }); + tx.gas_price = 5; + let env = tx.tx_env(3); + assert_eq!(env.tx_type, TransactionType::Eip7702 as u8); + assert_eq!((env.nonce, env.gas_price, env.gas_priority_fee), (3, 5, Some(5))); + } + + #[test] + fn test_scenario_parses_from_json() { + let json = r#"{ + "name": "transfer", + "pre": { "0x0000000000000000000000000000000000000aaa": { "balance": "0x10" } }, + "txs": [{ + "caller": "0x0000000000000000000000000000000000000aaa", + "to": "0x0000000000000000000000000000000000000bbb", + "value": "0x1", + "gas_limit": 21000, + "access_list": [{ "address": "0x0000000000000000000000000000000000000bbb", "storage_keys": ["0x1"] }] + }] + }"#; + let scenario: Scenario = serde_json::from_str(json).unwrap(); + assert_eq!(scenario.pre[&CALLER].balance, U256::from(16)); + assert_eq!(scenario.txs[0].access_list[0].storage_keys, vec![U256::from(1)]); + assert!(serde_json::from_str::(&json.replace("gas_limit", "gas")).is_err()); + } +} diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs index 2ef9e0ce2..636adb107 100644 --- a/crates/mega-evm/src/types.rs +++ b/crates/mega-evm/src/types.rs @@ -1,13 +1,34 @@ -//! Common type definitions for the `MegaETH` EVM. +//! Common type definitions of the Satin engine. +//! +//! These stay aliases of the OP types, because Satin adds nothing to them: +//! +//! - [`MegaTransaction`], [`MegaTxType`] and [`MegaTxEnvelope`]: Satin executes OP transactions. +//! - [`MegaHaltReason`]: Satin halts only where the EVM does. A resource limit stops a transaction +//! with a revert whose output is [`MegaLimitExceeded`](crate::MegaLimitExceeded), not with a +//! halt, so the halt set is op-revm's. +//! - [`MegaTransactionError`]: Satin validates transactions as op-revm does. +//! +//! What Satin does add has types of its own: the gas a transaction spent by ledger +//! ([`MegaGasUsage`](crate::MegaGasUsage)), the limit verdict and revert data +//! ([`LimitCheck`](crate::LimitCheck), [`MegaLimitExceeded`](crate::MegaLimitExceeded)) and the +//! block's counters ([`BlockGasCounters`](crate::BlockGasCounters)). -use revm::context::TxEnv; +/// `MegaETH` transaction as the EVM executes it. +/// +/// It is alloy-op-evm's wrapper of [`op_revm::OpTransaction`], which carries the conversions +/// from signed transactions that the node's block executor needs. +pub type MegaTransaction = alloy_op_evm::OpTx; -/// `MegaETH` transaction type used in revm. -pub type MegaTransaction = op_revm::OpTransaction; -/// `MegaETH` transaction builder type used in revm. -pub type MegaTransactionBuilder = op_revm::transaction::abstraction::OpTransactionBuilder; +/// Why a transaction halted: an EVM halt, or a failed deposit. +/// +/// A resource limit does not halt a transaction; see the module documentation. +pub type MegaHaltReason = op_revm::OpHaltReason; + +/// Transaction validation error, as the alloy-evm interface reports it. +pub type MegaTransactionError = alloy_op_evm::OpTxError; /// `MegaETH` transaction type. pub type MegaTxType = op_alloy_consensus::OpTxType; + /// `MegaETH` transaction envelope type. pub type MegaTxEnvelope = op_alloy_consensus::OpTxEnvelope; diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md new file mode 100644 index 000000000..da80c6b9a --- /dev/null +++ b/crates/mega-evm/tests/_pending/README.md @@ -0,0 +1,246 @@ +# Pending tests + +Tests of the legacy engine that survive into Satin but cannot run until the mechanism that owns them lands. +The dispositions come from the test inventory made for the engine rewrite and were applied mechanically when the Satin skeleton replaced the legacy core. +Every test the inventory marks `legacy-only` or `retired` was deleted; every other test is marked `keep`, `rewrite` or `undecided` and was moved here unchanged. +Decision ids (`Dnn`) index the Satin decision table, the numbered list of design decisions behind this engine; it is published with the engine's specification. + +## How this directory is excluded from the build + +Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`. +`_pending/` has no `main.rs`, so nothing below it is compiled, formatted or linted. +Do not add a `_pending/main.rs`. + +## Rules for porting + +- Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. +- `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. +- Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. +- The 44 legacy mutant killers the inventory kept (`tests/mutation/`) are not here: each was keyed to a surviving mutant of the legacy sources, and the test gates found no survivor in the Satin sources to regenerate one for. + A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`; what the retired rows cited is kept in "Retired mutant killers" below. +- Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. + The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. +- Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. + +## Tests per owning mechanism + +| Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | +|---|---:|---:|---:|---:|---:|---:| +| the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | +| the Satin gas table | 34 | 27 | 7 | 7 | 27 | 0 | +| SALT pricing | 75 | 64 | 11 | 17 | 58 | 0 | +| history gas | 28 | 24 | 4 | 4 | 24 | 0 | +| compute gas | 26 | 26 | 0 | 0 | 26 | 0 | +| the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | +| detention | 81 | 76 | 5 | 73 | 8 | 0 | +| the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | +| revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | +| the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | +| the system contract interceptors | 61 | 53 | 8 | 52 | 9 | 0 | +| system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | +| the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | +| native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | +| the block executor | 53 | 23 | 30 | 39 | 14 | 0 | +| inspector support | 4 | 4 | 0 | 1 | 3 | 0 | +| — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | +| **Total** | **747** | **624** | **123** | **426** | **293** | **28** | + +## Tests ported in place + +These rows came back with the code they test and run in `crates/mega-evm/src`, so the counts above are lower than the inventory's per-mechanism totals by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `src/evm/context.rs` | the Satin skeleton (3) | 3 | `src/evm/context.rs` | +| `src/evm/factory.rs` | the Satin skeleton (1) | 1 | `src/evm/factory.rs` | +| `src/evm/mod.rs` | the Satin skeleton (6) | 6 | `src/evm/mod.rs` | +| `src/evm/spec.rs` | the Satin skeleton (3) | 3 | `src/evm/spec.rs` | +| `src/external/hasher/mod.rs` | SALT pricing (5) | 5 | `src/external/hasher/mod.rs` | +| `src/external/mod.rs` | the Satin skeleton (1) | 1 | `src/external/mod.rs` | +| `src/external/test_utils.rs` | the Satin skeleton (1) | 1 | `src/external/test_utils.rs` | +| `src/sandbox/error.rs` | native keyless deployment (4) | 4 | `src/system/keyless/error.rs` | +| `src/sandbox/tx.rs` | native keyless deployment (10) | 10 | `src/system/keyless/tx.rs` | +| `src/test_utils/opcode_gen.rs` | the Satin skeleton (2) | 2 | `src/test_utils/opcode_gen.rs` | +| **Total** | | **36** | | + +## Retired mutant killers + +What the retired `tests/mutation/` rows cited, for the mechanisms that own them. + +| Owning mechanism | Tests | Disposition | Decision | +|---|---:|---|---| +| the Satin gas table | 2 | rewrite | D04 | +| the Satin gas table | 1 | rewrite | D11 | +| SALT pricing | 8 | keep | the test gates regenerate | +| compute gas | 1 | rewrite | D53 | +| the data-size limit | 2 | keep | 13,107,200 unchanged | +| detention | 6 | keep | the test gates regenerate | +| the state-growth and KV limits | 1 | undecided | D46 | +| the state-growth and KV limits | 1 | rewrite | D45 | +| the block executor | 17 | keep | the test gates regenerate | +| the block executor | 5 | rewrite | single spec / Satin schedule | + +## Tests parked under the common execution layer + +These 21 rows belong to the test gates in the inventory and pin canonical CREATE and CREATE2 behavior. +The test gates had turned them into scenarios of a differential harness against revm 43; that harness is maintained outside this repository now, so the rows are parked here again, owed to the common execution layer, and counted under it above. +6 of them also assert the halt reason of a creation in a static callee: those assertions already run in `tests/satin/static_callee.rs`, under the same test names, and a port of one of those rows carries the rest of its assertions. + +| Legacy file | Test | Static-callee halt reason | +|---|---|---| +| `rex4/create_safety.rs` | `test_create2_with_oversize_initcode_len_does_not_panic` | — | +| `rex5/create2_empty_initcode.rs` | `test_create2_len_zero_offset_zero_succeeds_on_both_specs` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_nonzero_offset_max_still_halts` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_large_offset_skips_memory_expansion` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_max_succeeds` | — | +| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_zero_succeeds` | — | +| `rex5/create2_resize_gas_metering.rs` | `test_create2_missing_salt_halts_consistently_across_specs` | — | +| `rex5/create2_resize_gas_metering.rs` | `test_rex5_create2_with_non_trivial_resize_succeeds` | — | +| `rex6/create2_metering_order.rs` | `test_create2_exact_boundary_initcode_length` | — | +| `rex6/create2_metering_order.rs` | `test_create2_missing_salt_consistent_rex5_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_moderately_oversized_initcode_same_reason_both_specs` | — | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_initcode_halts_before_prework_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6` | — | +| `rex6/create2_metering_order.rs` | `test_create2_static_hugely_oversized_initcode_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_missing_operands_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_oversized_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_low_gas_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/create2_metering_order.rs` | `test_create_static_low_gas_halt_reason` | `tests/satin/static_callee.rs` | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | — | +| `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | — | + +## Tests ported by the common execution layer + +These 45 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. + +| Legacy file | Owner in the inventory | Tests | Now in | +|---|---|---:|---| +| `equivalence/evm_state.rs` | the common execution layer (3) | 3 | `tests/satin/state.rs` | +| `mini_rex/db_error.rs` | the common execution layer (4) | 4 | `tests/satin/db_error.rs` | +| `rex4/eip7702_delegation_cycle.rs` | the common execution layer (1) | 1 | `tests/satin/state.rs` | +| `rex5/call_too_deep_guard.rs` | the system contract interceptors (4) | 4 | `tests/satin/synthetic_frame_gas.rs` | +| `rex5/frame_target_updated_dedup.rs` | the common execution layer (5) | 5 | `tests/satin/write_records.rs` | +| `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | +| `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | +| `src/evm/host.rs` | the common execution layer (10) | 10 | `src/evm/host.rs` | +| `src/evm/mod.rs` | the common execution layer (1) | 1 | `tests/satin/outcome.rs` | +| `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | +| `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | +| `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | +| **Total** | | **45** | | + +## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism + +| File | Test | Parked under | Reason | +|---|---|---|---| +| `src/evm/context.rs` | `test_shared_salt_env_keeps_dynamic_gas_cache_isolated` | SALT pricing | exercises the dynamic storage-gas cache that SALT pricing brings back | +| `src/evm/factory.rs` | `test_dyn_precompiles_builder_receives_the_behavior_spec` | the Satin gas table | the dynamic precompile builder returns with the Satin precompile set; the behavior projection it pinned has no counterpart in a single-spec engine | +| `src/evm/mod.rs` | `test_mega_evm_exposes_state_wrapper_block_hashes` | the block executor | reads the accessed-block-hash record, which returns with the block executor | + +## Files + +Each cell lists `disposition count (mechanism · decision)`. + +| File | Tests | Owners | +|---|---:|---| +| `block_executor/accessed_block_hashes.rs` | 1 | keep 1 (the block executor) | +| `block_executor/block_limits.rs` | 14 | keep 12 (the block executor · D47); undecided 2 (the state-growth and KV limits · D46) | +| `block_executor/canonical_schedule.rs` | 1 | rewrite 1 (the block executor · single Satin fork; the specification pages own the doc side) | +| `block_executor/deposit_da_exemption.rs` | 4 | keep 4 (the block executor · D23) | +| `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | +| `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | +| `block_executor/trait_factory_runtime_limits.rs` | 4 | rewrite 4 (the block executor · D10 (200M execution cap replaces compute-gas runtime limit)) | +| `compute_gas/claims.rs` | 14 | keep 2 (the system contract interceptors); rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); keep 1 (the Satin gas table · D04 (KZG 100k)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 2 (the Satin gas table · D13); rewrite 1 (the Satin gas table · D11); rewrite 1 (the data-size limit · D33/D48) | +| `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | +| `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | +| `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | +| `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | +| `mini_rex/contract_size_limit.rs` | 12 | rewrite 12 (the Satin gas table · D04 (512 KiB kept; the decision table does not pin the initcode bound under Osaka/EIP-3860)) | +| `mini_rex/gas.rs` | 26 | rewrite 14 (SALT pricing · D12 (state gas x m via pricing hook)); rewrite 6 (SALT pricing · D12/D13); undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)); rewrite 4 (the Satin gas table · D11/D55 (7976 floor)) | +| `mini_rex/mega_system_transaction.rs` | 15 | keep 15 (the system contract interceptors · D51) | +| `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | +| `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | +| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | +| `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | +| `rex/storage_gas.rs` | 15 | rewrite 15 (SALT pricing · D12 (base price and min-bucket value change; multiplier logic kept)) | +| `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | +| `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | +| `rex3/keyless_deploy.rs` | 2 | rewrite 2 (the system contract interceptors · D15 (explicit 100k compute) / D48) | +| `rex3/oracle_gas_limit.rs` | 8 | keep 7 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | +| `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | +| `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | +| `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | +| `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | +| `rex4/eip7702_delegation_cycle.rs` | 8 | keep 8 (SALT pricing · account inspection on the pricing path) | +| `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | +| `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | +| `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | +| `rex4/keyless_deploy.rs` | 2 | keep 2 (native keyless deployment · native sub-frame inherits env) | +| `rex4/limit_control.rs` | 14 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)); keep 5 (the system contract interceptors) | +| `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | +| `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | +| `rex5/callcode_storage_gas.rs` | 6 | rewrite 3 (SALT pricing · D12); keep 3 (SALT pricing · pricing-failure propagation) | +| `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | +| `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | +| `rex5/db_error.rs` | 4 | rewrite 3 (native keyless deployment · native path surfaces DB errors); keep 1 (the system contract interceptors) | +| `rex5/deposit_caller_accounting.rs` | 7 | rewrite 7 (the system contract interceptors · D16 (kept; must not double-charge with 2780)) | +| `rex5/deposit_create_storage_gas.rs` | 4 | rewrite 4 (SALT pricing · D12/D37) | +| `rex5/eip7702_metering.rs` | 4 | rewrite 4 (SALT pricing · D12/D45) | +| `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | +| `rex5/gas_validation.rs` | 4 | rewrite 4 (the Satin gas table · D49/D55 (intrinsic state component; floor vs cap)) | +| `rex5/interceptor_selector_probe.rs` | 6 | keep 6 (the system contract interceptors) | +| `rex5/keyless_deploy_dispatch_parity.rs` | 3 | keep 3 (the system contract interceptors) | +| `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | +| `rex5/keyless_fee_free.rs` | 12 | rewrite 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); keep 4 (native keyless deployment · rules unchanged) | +| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | rewrite 3 (native keyless deployment · native sub-frame gas handling) | +| `rex5/keyless_replay_barrier.rs` | 3 | rewrite 3 (native keyless deployment · D36 (real nonce increment)) | +| `rex5/oracle_hint_metering.rs` | 9 | keep 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); rewrite 1 (the oracle and control contracts · D11 intrinsic number); rewrite 1 (revert-class aborts · D48) | +| `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | +| `rex5/precompile_compute_gas.rs` | 3 | rewrite 3 (the Satin gas table · D04/D40 (assert via gas_used)) | +| `rex5/sandbox_accounting.rs` | 9 | rewrite 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | +| `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | +| `rex5/sstore_storage_gas_error.rs` | 1 | keep 1 (SALT pricing · pricing-failure path) | +| `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | +| `rex5/system_tx_replay.rs` | 12 | keep 12 (the system contract interceptors) | +| `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | +| `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | +| `rex6/create_frame_accounting.rs` | 1 | keep 1 (SALT pricing) | +| `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | +| `rex6/error_paths.rs` | 4 | keep 2 (SALT pricing); keep 2 (the common execution layer · canonical) | +| `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | +| `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | +| `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | +| `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | +| `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | +| `rex6/sequencer_registry_rotation.rs` | 6 | keep 5 (system contract deployment); keep 1 (the block executor · params validation at load) | +| `rex6/system_tx_metering_exemption.rs` | 3 | rewrite 3 (SALT pricing · D51 (m = 1 for system source; history exempt)) | +| `src/access/volatile.rs` | 4 | keep 4 (detention) | +| `src/block/chain.rs` | 5 | rewrite 4 (the block executor · Satin activation timestamps; fallback pin = Satin); keep 1 (the block executor) | +| `src/block/eips.rs` | 1 | keep 1 (the block executor) | +| `src/block/hardfork.rs` | 12 | rewrite 3 (the block executor · single fork); keep 9 (the block executor) | +| `src/block/helpers.rs` | 3 | keep 3 (the block executor) | +| `src/block/limit.rs` | 5 | keep 5 (the block executor) | +| `src/block/result.rs` | 2 | rewrite 2 (the block executor · D48 (error shape)) | +| `src/evm/context.rs` | 1 | keep 1 (SALT pricing · SALT pricing for the SALT cache test) | +| `src/evm/factory.rs` | 1 | rewrite 1 (the Satin gas table · no behaviour projection) | +| `src/evm/host.rs` | 1 | keep 1 (SALT pricing) | +| `src/evm/mod.rs` | 4 | keep 3 (the pre-block system calls); keep 1 (the block executor) | +| `src/evm/precompiles.rs` | 6 | keep 6 (the Satin gas table · D04) | +| `src/evm/state.rs` | 1 | keep 1 (the block executor) | +| `src/external/gas.rs` | 9 | rewrite 9 (SALT pricing · D12/D51) | +| `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | +| `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | +| `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | +| `src/limit/limit.rs` | 4 | keep 4 (history gas · D51) | +| `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | +| `src/system/control.rs` | 8 | keep 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | +| `src/system/deploy.rs` | 4 | keep 3 (system contract deployment); rewrite 1 (system contract deployment · single version) | +| `src/system/intercept.rs` | 2 | keep 2 (the system contract interceptors) | +| `src/system/keyless_deploy.rs` | 2 | keep 2 (system contract deployment) | +| `src/system/limit_control.rs` | 5 | keep 5 (system contract deployment) | +| `src/system/oracle.rs` | 7 | keep 7 (system contract deployment · v2.0.0 only) | +| `src/system/sequencer_registry.rs` | 24 | keep 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | +| `src/system/tx.rs` | 6 | keep 6 (the system contract interceptors · D51) | diff --git a/crates/mega-evm/tests/block_executor/accessed_block_hashes.rs b/crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/accessed_block_hashes.rs rename to crates/mega-evm/tests/_pending/block_executor/accessed_block_hashes.rs diff --git a/crates/mega-evm/tests/block_executor/block_limits.rs b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/block_limits.rs rename to crates/mega-evm/tests/_pending/block_executor/block_limits.rs diff --git a/crates/mega-evm/tests/block_executor/canonical_schedule.rs b/crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/canonical_schedule.rs rename to crates/mega-evm/tests/_pending/block_executor/canonical_schedule.rs diff --git a/crates/mega-evm/tests/block_executor/deposit_da_exemption.rs b/crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/deposit_da_exemption.rs rename to crates/mega-evm/tests/_pending/block_executor/deposit_da_exemption.rs diff --git a/crates/mega-evm/tests/block_executor/inspector.rs b/crates/mega-evm/tests/_pending/block_executor/inspector.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/inspector.rs rename to crates/mega-evm/tests/_pending/block_executor/inspector.rs diff --git a/crates/mega-evm/tests/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs similarity index 91% rename from crates/mega-evm/tests/block_executor/main.rs rename to crates/mega-evm/tests/_pending/block_executor/main.rs index 1ab0ed938..1d7f9b265 100644 --- a/crates/mega-evm/tests/block_executor/main.rs +++ b/crates/mega-evm/tests/_pending/block_executor/main.rs @@ -5,6 +5,5 @@ mod block_limits; mod canonical_schedule; mod deposit_da_exemption; mod inspector; -mod partial_ladder; mod sequencer_registry; mod trait_factory_runtime_limits; diff --git a/crates/mega-evm/tests/block_executor/sequencer_registry.rs b/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/sequencer_registry.rs rename to crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs diff --git a/crates/mega-evm/tests/block_executor/trait_factory_runtime_limits.rs b/crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs similarity index 100% rename from crates/mega-evm/tests/block_executor/trait_factory_runtime_limits.rs rename to crates/mega-evm/tests/_pending/block_executor/trait_factory_runtime_limits.rs diff --git a/crates/mega-evm/tests/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs similarity index 79% rename from crates/mega-evm/tests/compute_gas/claims.rs rename to crates/mega-evm/tests/_pending/compute_gas/claims.rs index 7f4fa05fe..6539fd31e 100644 --- a/crates/mega-evm/tests/compute_gas/claims.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/claims.rs @@ -146,53 +146,6 @@ fn test_interception_costs_the_same_as_a_plain_call() { } } -/// Spec: [Transaction Intrinsic Gas] — "A node MUST NOT include `MegaETH`'s intrinsic storage gas -/// additions ... in the recorded compute gas, even though both are added to the same intrinsic gas -/// total charged against the transaction's gas limit." -/// -/// Rex adds `TX_INTRINSIC_STORAGE_GAS` (39,000) on top of `MiniRex`'s intrinsic. With empty -/// calldata that flat charge is the *only* intrinsic difference between the two specs, so it -/// isolates cleanly: `gas_used` must rise by exactly 39,000 while `compute_gas` must not move at -/// all. -#[test] -fn test_intrinsic_compute_gas_excludes_megaeth_storage_gas() { - const TX_INTRINSIC_STORAGE_GAS: u64 = 39_000; - - // A bare transfer to an account that already exists: no code, no storage gas, no calldata. - let build = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_balance(EXISTING_TARGET, U256::from(ONE_ETH)) - }; - - let mini_rex = transact(MegaSpecId::MINI_REX, build()); - let rex = transact(MegaSpecId::REX, build()); - - assert_eq!( - mini_rex.compute_gas, rex.compute_gas, - "the 39,000 intrinsic storage gas must not enter compute gas (MiniRex={} Rex={})", - mini_rex.compute_gas, rex.compute_gas - ); - assert_eq!( - rex.gas_used.checked_sub(mini_rex.gas_used).unwrap_or_else(|| panic!( - "Rex must not charge less total gas than MiniRex (MiniRex={} Rex={})", - mini_rex.gas_used, rex.gas_used - )), - TX_INTRINSIC_STORAGE_GAS, - "Rex must charge exactly {TX_INTRINSIC_STORAGE_GAS} more total gas than MiniRex \ - (MiniRex={} Rex={})", - mini_rex.gas_used, - rex.gas_used - ); - assert!( - rex.gas_used > rex.compute_gas, - "the storage intrinsic must still be charged against the gas limit \ - (gas_used={} compute_gas={})", - rex.gas_used, - rex.compute_gas - ); -} - /// Spec: [Refund Exclusion] — "A node MUST NOT subtract EVM gas refunds from compute gas usage. /// Refunds affect final gas settlement but do not reduce the compute gas recorded during /// execution." @@ -249,41 +202,6 @@ fn test_refunds_do_not_reduce_compute_gas() { } } -/// Spec: [Precompiles] — "For a transaction whose recipient is a precompile, the invocation runs -/// before any call-frame budget exists", and the effective gas limit then reduces to the -/// transaction-level remaining compute gas, net of the recorded intrinsic gas. -/// -/// A direct transaction with empty calldata to the KZG precompile under a 30,000 tx compute -/// limit: the intrinsic records 21,000, leaving 9,000 of transaction-level remainder. The -/// forwarded cap is that remainder, which is below the precompile's 100,000 minimum cost, so the -/// invocation fails and records exactly the 9,000 cap — total recorded compute gas is exactly -/// the 30,000 limit. A cap that ignored the recorded intrinsic (forwarding 30,000) or one derived -/// from an undefined frame budget would shift the total away from the limit. -#[test] -fn test_direct_precompile_transaction_cap_is_the_tx_level_remainder() { - const TX_COMPUTE_LIMIT: u64 = 30_000; - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::REX5) { - continue; - } - let limits = - EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(TX_COMPUTE_LIMIT); - let (result, usage) = - transact_with_limits(spec, base_db(Bytes::new()), PRECOMPILE_KZG, limits); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "{spec_name}: the underfunded direct precompile transaction should halt, got \ - {result:?}" - ); - assert_eq!( - usage.compute_gas, TX_COMPUTE_LIMIT, - "{spec_name}: the no-frame cap must be the transaction-level remainder, so intrinsic \ - plus the recorded cap must equal the tx compute limit exactly" - ); - } -} - /// Spec: [Precompiles], the KZG branch — "`KZG_POINT_EVALUATION_GAS_COST`, when the invocation /// targeted the KZG point-evaluation precompile and its effective gas limit was at least /// `KZG_POINT_EVALUATION_GAS_COST`". @@ -385,94 +303,6 @@ fn corpus_program(name: &str) -> crate::Program { .unwrap_or_else(|| panic!("corpus must contain {name}")) } -/// Spec: [Forwarded Gas Exclusion] — "`forwarded_child_gas` MUST be the child frame's gas limit, -/// less the standard EVM `CALL_STIPEND` when all of the following hold: the spec is Rex5 or later, -/// the call scheme is `CALL` or `CALLCODE`, and the call transfers non-zero value." -/// -/// The snapshot records the resulting numbers but not the rule. This test states it: the exclusion -/// makes the parent record exactly `CALL_STIPEND` more compute gas from Rex5 onward, and only for -/// the qualifying scheme-and-value combination. Each of the rule's three conditions gets a -/// negative case, so dropping any one of them fails here. -#[test] -fn test_call_stipend_is_excluded_from_forwarded_gas_only_when_the_rule_applies() { - /// The inherited EVM's value-transfer call stipend. - const CALL_STIPEND: u64 = 2_300; - - let delta_rex4_to_rex5 = |name: &str| -> i64 { - let program = corpus_program(name); - let rex4 = transact(MegaSpecId::REX4, (program.build_db)()); - let rex5 = transact(MegaSpecId::REX5, (program.build_db)()); - assert_eq!(rex4.outcome, "success", "{name}: Rex4 run should succeed"); - assert_eq!(rex5.outcome, "success", "{name}: Rex5 run should succeed"); - rex5.compute_gas as i64 - rex4.compute_gas as i64 - }; - - // Qualifying: CALL and CALLCODE that transfer value. - for name in ["call_value_to_existing", "call_value_to_empty", "callcode_value"] { - assert_eq!( - delta_rex4_to_rex5(name), - CALL_STIPEND as i64, - "{name}: Rex5 must exclude CALL_STIPEND from the forwarded amount, making the parent \ - record exactly {CALL_STIPEND} more compute gas than Rex4" - ); - } - - // Non-qualifying by scheme: DELEGATECALL and STATICCALL never carry a stipend. - // Non-qualifying by value: a CALL with value == 0 does not receive one either. - for name in ["delegatecall", "staticcall", "call_no_value_to_code"] { - assert_eq!( - delta_rex4_to_rex5(name), - 0, - "{name}: does not satisfy the scheme-and-value condition, so Rex5 must record the \ - same compute gas as Rex4" - ); - } -} - -/// Spec: [Contract Creation Memory Expansion] — the three-way split of which window records -/// `CREATE2`'s wrapper-side memory-expansion gas (MiniRex–Rex4 second window skipped on inner -/// failure / Rex5 separate eager window / Rex6 folded into the single window). -/// -/// The split is observable only on the failure path, where the expansion happens but the inner -/// opcode never completes. On the success path all three arrangements must agree — that agreement -/// is the spec's claim that Rex6 is behavior-preserving there. -#[test] -fn test_create2_memory_expansion_window_differs_only_on_the_failure_path() { - let readings = |name: &str| { - let program = corpus_program(name); - [MegaSpecId::MINI_REX, MegaSpecId::REX4, MegaSpecId::REX5, MegaSpecId::REX6] - .map(|spec| transact(spec, (program.build_db)()).compute_gas) - }; - - // Success path: the window arrangement is unobservable, so every spec must agree. - let [succ_mini, succ_rex4, succ_rex5, succ_rex6] = readings("create2_with_initcode"); - assert_eq!( - [succ_mini, succ_rex4, succ_rex5], - [succ_rex6; 3], - "on the straight-line success path every spec must record the same CREATE2 compute gas \ - (MiniRex={succ_mini} Rex4={succ_rex4} Rex5={succ_rex5} Rex6={succ_rex6})" - ); - - // Failure path: the initcode is oversized, so the memory expansion runs but the inner opcode - // rejects. Only Rex5's eager recording captures the expansion. - let [fail_mini, fail_rex4, fail_rex5, fail_rex6] = readings("create2_oversized_initcode"); - assert_eq!( - fail_mini, fail_rex4, - "MiniRex and Rex4 both skip the trailing record when the inner opcode fails \ - (MiniRex={fail_mini} Rex4={fail_rex4})" - ); - assert_eq!( - fail_rex6, fail_rex4, - "Rex6 halts before the expansion, so it records the same as the specs that skip the \ - trailing record (Rex4={fail_rex4} Rex6={fail_rex6})" - ); - assert!( - fail_rex5 > fail_rex4, - "Rex5 records the memory-expansion gas eagerly, before the inner opcode rejects, so it \ - must record strictly more than the others (Rex4={fail_rex4} Rex5={fail_rex5})" - ); -} - /// Builds a caller that STATICCALLs `callee`, forwarding all available gas (`GAS`), and returns the /// callee's reported remaining gas as the transaction output. fn forwarding_probe() -> (Bytes, Bytes) { @@ -506,51 +336,6 @@ fn forwarding_probe() -> (Bytes, Bytes) { (caller, callee) } -/// Spec: [Forwarded Gas Exclusion] — "Under `MiniRex`, `CALLCODE`, `DELEGATECALL`, and `STATICCALL` -/// do not apply the 98/100 forwarding cap ... From Rex onward these three opcodes are subject to -/// the same forwarding cap as `CALL`." -/// -/// Without `MegaETH`'s cap, `STATICCALL` forwards the inherited EVM's 63/64 (98.4375%); with it, -/// the forwarded amount is capped at 98/100. Rex is therefore strictly stingier than `MiniRex`, and -/// the gap is large enough at this gas limit to be unambiguous. -/// -/// This pins the frozen `MiniRex` quirk: if a refactor ever "fixes" `MiniRex` by routing these -/// opcodes through the cap, replay for MiniRex-era blocks breaks, and this test fails. -#[test] -fn test_minirex_staticcall_is_not_subject_to_the_forwarding_cap() { - let (caller_code, callee_code) = forwarding_probe(); - let build = || base_db(caller_code.clone()).account_code(CALLEE, callee_code.clone()); - - let forwarded = |spec| { - let o = transact_output(spec, build()); - U256::from_be_slice(&o).to::() - }; - - let mini_rex = forwarded(MegaSpecId::MINI_REX); - let rex = forwarded(MegaSpecId::REX); - - assert!( - mini_rex > rex, - "MiniRex STATICCALL must forward more than Rex (uncapped 63/64 vs capped 98/100): \ - MiniRex={mini_rex} Rex={rex}" - ); - - // 63/64 = 98.4375%, 98/100 = 98%. Confirm each side lands on its own rule rather than merely - // differing, using the caller's pre-call remaining gas reconstructed from the forwarded amount. - let ratio_bp = |fwd: u64, base: u64| fwd * 10_000 / base; - let base = mini_rex * 64 / 63; // caller's remaining before the MiniRex forward - assert!( - (9_800..=9_850).contains(&ratio_bp(mini_rex, base)), - "MiniRex should forward ~63/64 (9843 bp), got {} bp", - ratio_bp(mini_rex, base) - ); - assert!( - (9_750..=9_805).contains(&ratio_bp(rex, base)), - "Rex should forward ~98/100 (9800 bp), got {} bp", - ratio_bp(rex, base) - ); -} - /// The inherited EVM's cold account access cost (EIP-2929). const COLD_ACCOUNT_ACCESS_COST: u64 = 2_600; /// The inherited EVM's warm account access cost (EIP-2929 `WARM_STORAGE_READ_COST`). diff --git a/crates/mega-evm/tests/compute_gas/main.rs b/crates/mega-evm/tests/_pending/compute_gas/main.rs similarity index 91% rename from crates/mega-evm/tests/compute_gas/main.rs rename to crates/mega-evm/tests/_pending/compute_gas/main.rs index 44b9904bf..970fb979d 100644 --- a/crates/mega-evm/tests/compute_gas/main.rs +++ b/crates/mega-evm/tests/_pending/compute_gas/main.rs @@ -818,86 +818,6 @@ fn snapshot_path() -> std::path::PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/compute_gas/snapshot.txt") } -#[test] -fn test_compute_gas_snapshot_matches() { - let actual = render_snapshot(); - let path = snapshot_path(); - - if std::env::var_os("UPDATE_COMPUTE_GAS_SNAPSHOT").is_some() { - std::fs::write(&path, &actual).expect("failed to write snapshot"); - return; - } - - let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| { - panic!( - "missing snapshot at {}: {e}\n\ - Generate it with: UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas", - path.display() - ) - }); - - if actual != expected { - // Report the first differing line to keep the failure readable. - let diff = expected - .lines() - .zip(actual.lines()) - .enumerate() - .find(|(_, (e, a))| e != a) - .map(|(i, (e, a))| format!("line {}:\n expected: {e}\n actual: {a}", i + 1)) - .unwrap_or_else(|| "snapshots differ in length".to_string()); - panic!( - "compute-gas snapshot mismatch.\n{diff}\n\n\ - If this change is intentional, review it against docs/spec/evm/compute-gas.md and \ - regenerate with:\n UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas" - ); - } -} - -/// Rex7 is the unstable spec and carries no behavior of its own yet: it delegates its instruction -/// table, runtime limits, and precompile set to Rex6 unchanged. -/// -/// The snapshot alone does not pin this. Its rows differ by the spec-name column, so a Rex7 row -/// that drifted from its Rex6 counterpart would still render as a well-formed snapshot and could be -/// blessed by a regeneration. Comparing the readings directly makes the first accidental Rex7 -/// divergence a failure. When Rex7 gains its first deliberate behavior change, this test is -/// expected to fail and should be narrowed to the corpus entries that behavior does not reach. -#[test] -fn test_rex7_matches_rex6_on_every_program() { - for program in corpus() { - let rex6 = transact(MegaSpecId::REX6, (program.build_db)()); - let rex7 = transact(MegaSpecId::REX7, (program.build_db)()); - assert_eq!( - (rex7.compute_gas, rex7.gas_used, &rex7.outcome), - (rex6.compute_gas, rex6.gas_used, &rex6.outcome), - "{}: Rex7 must be behaviorally identical to Rex6 \ - (Rex6: compute_gas={} gas_used={} outcome={}; \ - Rex7: compute_gas={} gas_used={} outcome={})", - program.name, - rex6.compute_gas, - rex6.gas_used, - rex6.outcome, - rex7.compute_gas, - rex7.gas_used, - rex7.outcome, - ); - } -} - -/// Equivalence does not meter compute gas at all — no instruction wrappers, no precompile -/// recording. This is stated normatively in the spec's Overview; pin it directly so a wrapper -/// accidentally applied to the Equivalence table fails here rather than only shifting a number. -#[test] -fn test_equivalence_records_no_compute_gas() { - for program in corpus() { - let o = transact(MegaSpecId::EQUIVALENCE, (program.build_db)()); - assert_eq!( - o.compute_gas, 0, - "{}: Equivalence must not record compute gas, got {}", - program.name, o.compute_gas - ); - } -} - /// Compute gas is the sole non-revertible resource dimension: a child frame that reverts still /// contributes its consumption to the transaction total. #[test] diff --git a/crates/mega-evm/tests/mini_rex/access_beneficiary_balance.rs b/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/access_beneficiary_balance.rs rename to crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs diff --git a/crates/mega-evm/tests/mini_rex/block_env_access_tracking.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/block_env_access_tracking.rs rename to crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs diff --git a/crates/mega-evm/tests/mini_rex/block_env_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/block_env_gas_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs diff --git a/crates/mega-evm/tests/mini_rex/compute_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs similarity index 87% rename from crates/mega-evm/tests/mini_rex/compute_gas_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs index 7fd21894b..59a0a1598 100644 --- a/crates/mega-evm/tests/mini_rex/compute_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs @@ -232,47 +232,6 @@ fn test_compute_gas_limit_exceeded() { assert!(halt_actual > halt_limit); } -#[test] -fn test_compute_gas_refund_on_limit_exceeded() { - let mut bytecode = BytecodeBuilder::default(); - // Add many operations (need execution gas > 21,000 for validation) - for _ in 0..2000 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(10_000_000) // High tx gas limit for validation - .build_fill(); - - // First measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Compute gas tracks only opcode execution gas (intrinsic gas is reset after validation) - // 2000 iterations of (PUSH1 + PUSH1 + ADD + POP) = 2000 × 11 = 22,000 gas - assert!(actual_usage >= 22_000, "Expected at least 22,000 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Call with low compute gas limit just below actual usage - let limit = actual_usage - 1000; - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded, but remaining gas is refunded - assert!(is_compute_gas_limit_exceeded(&result)); - assert_eq!(compute_gas_used, result.result.gas_used()); - assert!(result.result.gas_used() < 43_000); -} - // ============================================================================ // INSTRUCTION COVERAGE TESTS // ============================================================================ @@ -658,101 +617,6 @@ fn test_compute_gas_limit_resets_after_volatile_access_rex1() { ); } -/// Test that compute gas limit is NOT reset between transactions in pre-Rex1 specs. -/// -/// Before Rex1, the compute gas limit was not reset between transactions. This test verifies -/// that the old behavior is preserved for backward compatibility: after accessing volatile data -/// (like oracle), the lowered compute gas limit persists to subsequent transactions. -#[test] -fn test_compute_gas_limit_not_reset_pre_rex1() { - use mega_evm::{ - constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, MegaTransaction, ORACLE_CONTRACT_ADDRESS, - }; - use revm::ExecuteEvm; - - // Contract 1: Calls the oracle, which lowers compute_gas_limit to 1M - let oracle_caller = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - // Contract 2: Expensive contract that uses >1M compute gas via SHA3 operations. - // In pre-Rex1, this will fail because the limit is stuck at 1M from oracle access. - let mut expensive_builder = BytecodeBuilder::default(); - expensive_builder = - expensive_builder.push_number(0xdeadbeefu32).push_number(0u8).append(MSTORE); - for _ in 0..30000 { - expensive_builder = - expensive_builder.push_number(32u8).push_number(0u8).append(KECCAK256).append(POP); - } - let expensive_contract = expensive_builder.append(STOP).build(); - - let compute_gas_limit: u64 = 10_000_000; // 10M - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_code(CONTRACT, oracle_caller) - .account_code(CONTRACT2, expensive_contract); - - // Use REX spec (pre-Rex1) where limits are NOT reset between transactions - let mut context = MegaContext::new(db, MegaSpecId::REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(compute_gas_limit) - .with_oracle_access_compute_gas_limit(ORACLE_ACCESS_COMPUTE_GAS), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - // TX1: Call oracle contract - this lowers compute_gas_limit to 1M - let tx1 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1).unwrap(); - assert!(result1.result.is_success(), "TX1 should succeed"); - - // Verify TX1 lowered the compute_gas_limit to oracle limit - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "TX1 should have lowered compute_gas_limit to oracle access limit" - ); - - // TX2: Expensive contract that uses >1M compute gas on the SAME EVM instance. - // In pre-Rex1, this should FAIL because the limit is stuck at 1M. - let tx2 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT2).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result2 = evm.transact_one(tx2).unwrap(); - - // TX2 should fail because the limit was NOT reset (pre-Rex1 behavior) - assert!( - !result2.is_success(), - "TX2 should fail in pre-Rex1 because compute_gas_limit was NOT reset. \ - The limit should be stuck at {} from oracle access in TX1", - ORACLE_ACCESS_COMPUTE_GAS - ); - - // Verify the limit is still at the lowered oracle limit (not reset) - let actual_limit = evm.ctx_ref().additional_limit.borrow().compute_gas_limit(); - assert_eq!( - actual_limit, ORACLE_ACCESS_COMPUTE_GAS, - "compute_gas_limit should still be at oracle limit ({}) in pre-Rex1, not reset to {}", - ORACLE_ACCESS_COMPUTE_GAS, compute_gas_limit - ); -} - // ============================================================================ // SPEC COMPARISON TESTS // ============================================================================ @@ -781,32 +645,6 @@ fn test_compute_gas_tracked_in_mini_rex() { assert!(compute_gas_used > 0); } -#[test] -fn test_compute_gas_not_tracked_in_equivalence() { - let bytecode = BytecodeBuilder::default() - .append(PUSH1) - .append(1) - .append(PUSH1) - .append(2) - .append(ADD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::EQUIVALENCE, &mut db, 10_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // In EQUIVALENCE, compute gas should NOT be tracked - assert_eq!(compute_gas_used, 0); -} - // ============================================================================ // PRECOMPILE TESTS // ============================================================================ diff --git a/crates/mega-evm/tests/mini_rex/contract_size_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs similarity index 81% rename from crates/mega-evm/tests/mini_rex/contract_size_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs index 02b14ec19..fb6da8fc2 100644 --- a/crates/mega-evm/tests/mini_rex/contract_size_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/contract_size_limit.rs @@ -43,26 +43,6 @@ fn initcode_size_limit_test_case(spec: MegaSpecId, initcode_size: usize, success } } -/// Test that verifies `EQUIVALENCE` spec allows deployment with EIP-3860 max initcode size. -#[test] -fn test_equivalence_eip3860_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip3860::MAX_INITCODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects deployment with `MiniRex` max initcode size. -#[test] -fn test_equivalence_minirex_max_initcode_size() { - initcode_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - constants::mini_rex::MAX_INITCODE_SIZE, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows deployment with EIP-3860 max initcode size. #[test] fn test_minirex_eip3860_max_initcode_size() { @@ -137,26 +117,6 @@ fn contract_size_limit_test_case(spec: MegaSpecId, contract_size: usize, success } } -/// Test that verifies `EQUIVALENCE` spec allows deployment with EIP-170 max code size. -#[test] -fn test_equivalence_eip170_max_code_size() { - contract_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects deployment with `MiniRex` max contract size. -#[test] -fn test_equivalence_minirex_max_contract_size() { - contract_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - constants::mini_rex::MAX_CONTRACT_SIZE, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows deployment with EIP-170 max code size. #[test] fn test_minirex_eip170_max_code_size() { @@ -252,26 +212,6 @@ fn contract_factory_code_size_limit_test_case( } } -/// Test that verifies `EQUIVALENCE` spec allows CREATE opcode with EIP-170 max code size. -#[test] -fn test_equivalence_create_eip170_max_code_size() { - contract_factory_code_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE, - true, - ); -} - -/// Test that verifies `EQUIVALENCE` spec rejects CREATE opcode with EIP-170 max code size + 1. -#[test] -fn test_equivalence_create_eip170_max_code_size_plus_one() { - contract_factory_code_size_limit_test_case( - MegaSpecId::EQUIVALENCE, - revm::primitives::eip170::MAX_CODE_SIZE + 1, - false, - ); -} - /// Test that verifies `MINI_REX` spec allows CREATE opcode with EIP-170 max code size. #[test] fn test_minirex_create_eip170_max_code_size() { diff --git a/crates/mega-evm/tests/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs similarity index 80% rename from crates/mega-evm/tests/mini_rex/gas.rs rename to crates/mega-evm/tests/_pending/mini_rex/gas.rs index 249d00cbe..c131f5235 100644 --- a/crates/mega-evm/tests/mini_rex/gas.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/gas.rs @@ -193,17 +193,6 @@ fn test_sstore_clear_with_bucket_expansion() { sstore_test_case(MegaSpecId::MINI_REX, UpdateMode::Clear, 1, 21_206); } -/// Tests SSTORE uses standard EVM gas costs in equivalence spec, not `MegaETH`'s increased costs. -#[test] -fn test_sstore_gas_unchanged_in_equivalence_spec() { - sstore_test_case( - MegaSpecId::EQUIVALENCE, - UpdateMode::Set, - 0, - 21_006 + constants::equivalence::SSTORE_SET + constants::equivalence::COLD_SLOAD_COST, - ); -} - /// Tests EIP-2929: First SSTORE to a slot charges cold access penalty (2100 gas), subsequent /// SSTOREs to the same slot in the same transaction use warm pricing. #[test] @@ -332,12 +321,6 @@ fn test_ether_transfer_to_existent_account() { ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 21_000); } -/// Tests ether transfer uses standard EVM gas costs in equivalence spec. -#[test] -fn test_ether_transfer_gas_unchanged_in_equivalence_spec() { - ether_transfer_test_case(MegaSpecId::EQUIVALENCE, UpdateMode::Reset, 0, 21_000); -} - /// Executes a nested ether transfer test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -429,12 +412,6 @@ fn test_nested_ether_transfer_to_existent_account() { nested_ether_transfer_test_case(MegaSpecId::MINI_REX, UpdateMode::Reset, 0, 30_316); } -/// Tests nested ether transfer uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_ether_transfer_gas_unchanged_in_equivalence_spec() { - nested_ether_transfer_test_case(MegaSpecId::EQUIVALENCE, UpdateMode::Reset, 0, 30_316); -} - /// Executes a create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -496,12 +473,6 @@ fn test_create_contract_to_non_existent_account_with_bucket_expansion() { ); } -/// Tests CREATE uses standard EVM gas costs in equivalence spec. -#[test] -fn test_create_contract_gas_unchanged_in_equivalence_spec() { - create_contract_test_case(MegaSpecId::EQUIVALENCE, 0, 53_554); -} - /// Executes a nested create contract test case, verifying gas usage for account creation and bucket /// expansion scenarios. /// @@ -597,17 +568,6 @@ fn test_nested_create_contract_to_non_existent_account_with_bucket_expansion() { ); } -/// Tests nested CREATE uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_create_contract_gas_unchanged_in_equivalence_spec() { - nested_create_contract_test_case( - MegaSpecId::EQUIVALENCE, - false, - 0, - 21_255 + constants::equivalence::CREATE, - ); -} - /// Tests nested CREATE2 charges `CREATE_GAS` plu`NEW_ACCOUNT_GAS`AS plus KECCAK256 cost. #[test] fn test_nested_create2_contract_to_non_existent_account() { @@ -636,17 +596,6 @@ fn test_nested_create2_contract_to_non_existent_account_with_bucket_expansion() ); } -/// Tests nested CREATE2 uses standard EVM gas costs in equivalence spec. -#[test] -fn test_nested_create2_contract_gas_unchanged_in_equivalence_spec() { - nested_create_contract_test_case( - MegaSpecId::EQUIVALENCE, - true, - 0, - 21_270 + constants::equivalence::CREATE, - ); -} - /// Executes a calldata test case, verifying gas usage for calldata scenarios. /// /// # Arguments @@ -675,21 +624,6 @@ fn calldata_test_case(spec: MegaSpecId, expected_gas_ assert_eq!(gas_used, expected_gas_used); } -/// Tests calldata charges additional per-byte cost in `MegaETH` (100x standard cost). -#[test] -fn test_calldata_additional_cost() { - calldata_test_case::<1024>( - MegaSpecId::MINI_REX, - 133_640, // 21,000 base + 110 gas/byte × 1,024 bytes (10 intrinsic + 100 storage floor) - ); -} - -/// Tests calldata uses standard EVM gas costs in equivalence spec. -#[test] -fn test_calldata_no_additional_cost_in_equivalence_spec() { - calldata_test_case::<1024>(MegaSpecId::EQUIVALENCE, 31_240); -} - /// Executes a log test case, verifying gas usage for log scenarios. /// /// # Arguments @@ -730,23 +664,6 @@ fn log_test_case( assert_eq!(gas_used, expected_gas_used); } -/// Tests LOG charges additional per-byte and per-topic cost in `MegaETH` (100x standard cost). -#[test] -fn test_log_additional_cost() { - log_test_case::<1, 1024>( - MegaSpecId::MINI_REX, - 30_049 + - constants::mini_rex::LOG_TOPIC_STORAGE_GAS + - constants::mini_rex::LOG_DATA_STORAGE_GAS * 1024, - ); -} - -/// Tests LOG uses standard EVM gas costs in equivalence spec. -#[test] -fn test_log_no_additional_cost_in_equivalence_spec() { - log_test_case::<1, 1024>(MegaSpecId::EQUIVALENCE, 30_049); -} - /// Executes a gas forward test case, verifying gas usage for gas forwarding scenarios. /// /// # Arguments @@ -849,18 +766,6 @@ fn test_gas_forward_to_create_in_mini_rex() { gas_forward_test_case(MegaSpecId::MINI_REX, true, 1_003_520_000); } -/// Tests gas forwarding to CALL uses standard 63/64 rule in equivalence spec. -#[test] -fn test_gas_forward_to_call_in_equivalence_spec() { - gas_forward_test_case(MegaSpecId::EQUIVALENCE, false, 1_008_000_000); -} - -/// Tests gas forwarding to CREATE uses standard 63/64 rule in equivalence spec. -#[test] -fn test_gas_forward_to_create_in_equivalence_spec() { - gas_forward_test_case(MegaSpecId::EQUIVALENCE, true, 1_008_000_000); -} - /// Executes a floor gas test case, verifying gas usage includes additional floor gas costs. /// /// # Arguments @@ -905,13 +810,6 @@ fn test_floor_gas_large_calldata_mini_rex() { floor_gas_test_case(MegaSpecId::MINI_REX, 1024, 471_560); } -/// Tests floor gas is not charged in EQUIVALENCE spec. -#[test] -fn test_floor_gas_no_additional_cost_in_equivalence_spec() { - // Test with 100 bytes of calldata - should not include additional floor gas - floor_gas_test_case(MegaSpecId::EQUIVALENCE, 100, 25_000); -} - /// Tests floor gas with empty calldata (edge case). #[test] fn test_floor_gas_empty_calldata() { @@ -923,97 +821,3 @@ fn test_floor_gas_empty_calldata() { fn test_floor_gas_minimal_calldata() { floor_gas_test_case(MegaSpecId::MINI_REX, 1, 21_440); } - -/// Tests that insufficient gas for account creation storage gas results in OOG (not invalid tx). -/// This transaction has enough gas for intrinsic costs but not for account creation storage. -#[test] -fn test_mini_rex_insufficient_storage_gas_for_new_account_oog() { - use mega_evm::SaltEnv; - use std::convert::Infallible; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - let new_account = address!("9000000000000000000000000000000000000009"); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(new_account); - let multiplier = 10u64; - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * multiplier); - - // MiniRex account creation storage gas: 2,000,000 × 10 = 20,000,000 - // Intrinsic: 21,000 - // Set gas limit to cover intrinsic but not storage: 22,000 - let insufficient_gas_limit = 22_000; - - // Override gas limit in the test - let mut context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(new_account), - data: Bytes::new(), - value: U256::from(1), - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Transaction should succeed but execution should be OOG - assert!(!res.result.is_success()); - assert!(res.result.is_halt()); - assert_eq!(res.result.gas_used(), insufficient_gas_limit); -} - -/// Tests that insufficient gas for contract creation storage gas results in OOG (not invalid tx). -#[test] -fn test_mini_rex_insufficient_storage_gas_for_contract_creation_oog() { - use mega_evm::SaltEnv; - use std::convert::Infallible; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - // Empty init code to minimize calldata gas - let init_code = Bytes::new(); - let created_address = CALLER.create(0); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(created_address); - let multiplier = 10u64; - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * multiplier); - - // MiniRex contract creation storage gas: 2,000,000 × 10 = 20,000,000 - // Base intrinsic for CREATE: 21,000 + 32,000 (CREATE base) = 53,000 - // Set gas limit to cover intrinsic but not storage: 60,000 - let insufficient_gas_limit = 60_000; - - let mut context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Create, - data: init_code, - value: U256::ZERO, - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Transaction should succeed but execution should be OOG - assert!(!res.result.is_success()); - assert!(res.result.is_halt()); - assert_eq!(res.result.gas_used(), insufficient_gas_limit); -} diff --git a/crates/mega-evm/tests/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs similarity index 87% rename from crates/mega-evm/tests/mini_rex/main.rs rename to crates/mega-evm/tests/_pending/mini_rex/main.rs index aee27a700..c94d58cc7 100644 --- a/crates/mega-evm/tests/mini_rex/main.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/main.rs @@ -5,8 +5,6 @@ mod block_env_access_tracking; mod block_env_gas_limit; mod compute_gas_limit; mod contract_size_limit; -mod db_error; -mod disallow_selfdestruct; mod gas; mod mega_system_transaction; mod oracle; diff --git a/crates/mega-evm/tests/mini_rex/mega_system_transaction.rs b/crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs similarity index 100% rename from crates/mega-evm/tests/mini_rex/mega_system_transaction.rs rename to crates/mega-evm/tests/_pending/mini_rex/mega_system_transaction.rs diff --git a/crates/mega-evm/tests/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs similarity index 78% rename from crates/mega-evm/tests/mini_rex/oracle.rs rename to crates/mega-evm/tests/_pending/mini_rex/oracle.rs index 481f463e7..5d80ffc90 100644 --- a/crates/mega-evm/tests/mini_rex/oracle.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs @@ -78,158 +78,6 @@ fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool ) } -/// Test that calling the oracle contract is detected. -#[test] -fn test_oracle_access_detected_on_call() { - // Create bytecode that calls the oracle contract - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "Compute gas limit should be set to oracle access limit" - ); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - -/// Test that calling a non-oracle contract is not detected as oracle access. -#[test] -fn test_oracle_access_not_detected_on_regular_call() { - const OTHER_CONTRACT: alloy_primitives::Address = - address!("3000000000000000000000000000000000000003"); - - // Create bytecode that calls a different contract (not oracle) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(OTHER_CONTRACT) // callee: some other contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected"); -} - -/// Test that oracle access is not detected when no CALL is made. -#[test] -fn test_oracle_access_not_detected_without_call() { - // Simple bytecode that doesn't call anything - let bytecode = BytecodeBuilder::default().push_number(42u8).stop().build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected"); -} - -/// Test that oracle access is NOT detected in EQUIVALENCE spec (uses standard CALL). -/// Oracle detection only works in `MINI_REX` spec with custom CALL instruction. -#[test] -fn test_oracle_access_not_detected_in_equivalence_spec() { - // Create bytecode that calls the oracle contract - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - // Oracle detection only works in MINI_REX spec, not EQUIVALENCE - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = execute_transaction( - MegaSpecId::EQUIVALENCE, - &mut db, - &external_envs, - NoOpInspector, - CALLEE, - ); - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "Oracle access should not be detected in EQUIVALENCE spec"); -} - -/// Test that oracle access is detected with explicit 0 value parameter. -#[test] -fn test_oracle_access_detected_with_explicit_zero_value() { - // Create bytecode that calls the oracle contract with explicit 0 wei value - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei (explicit) - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - -/// Test that multiple calls to oracle are still tracked (should not fail). -#[test] -fn test_oracle_access_detected_on_multiple_calls() { - // Create bytecode that calls the oracle contract twice - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args again - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract again - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle access should be detected"); -} - /// Test that contract runs out of gas when trying to execute expensive operations after oracle /// access. #[test] @@ -994,81 +842,3 @@ fn test_mega_system_address_exempted_from_oracle_tracking() { "Compute gas limit should NOT be set for mega system address transactions" ); } - -/// Test that STATICCALL to oracle is NOT detected in MiniRex. -/// -/// In MiniRex, STATICCALL bypasses oracle access detection along with CALLCODE and -/// DELEGATECALL. Rex fixes this by adding STATICCALL to the detection path. -#[test] -fn test_mini_rex_staticcall_oracle_access_not_detected() { - // STATICCALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(STATICCALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "STATICCALL to oracle should not be detected in MiniRex"); -} - -/// Test that DELEGATECALL to oracle is NOT detected in MiniRex. -/// -/// DELEGATECALL sets `target_address` to the caller's own address (not oracle), so the oracle -/// detection check in `frame_init` does not match. -#[test] -fn test_mini_rex_delegatecall_oracle_access_not_detected() { - // DELEGATECALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(DELEGATECALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "DELEGATECALL to oracle should not be detected in MiniRex"); -} - -/// Test that CALLCODE to oracle is NOT detected in MiniRex. -/// -/// CALLCODE sets `target_address` to the caller's own address (not oracle), so the oracle -/// detection check in `frame_init` does not match. -#[test] -fn test_mini_rex_callcode_oracle_access_not_detected() { - // CALLCODE: gas, addr, value, argsOff, argsLen, retOff, retLen (7 args) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff, value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALLCODE) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "CALLCODE to oracle should not be detected in MiniRex"); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs new file mode 100644 index 000000000..4e1f5934e --- /dev/null +++ b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs @@ -0,0 +1,220 @@ +//! Tests for the state growth limit feature of the `MegaETH` EVM. +//! +//! These tests verify that the state growth limit functionality correctly tracks and limits +//! the creation of new accounts and storage slots during transaction execution. + +use std::convert::Infallible; + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + MegaTransactionError, +}; +use revm::{ + bytecode::opcode::*, + context::{ + result::{EVMError, ExecutionResult, ResultAndState}, + tx::TxEnvBuilder, + TxEnv, + }, + handler::EvmTr, + Database, DatabaseCommit, +}; + +// Test addresses +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0000000000000000000000000000000000100001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); +const NEW_ACCOUNT: Address = address!("0000000000000000000000000000000000100003"); + +// ============================================================================ +// HELPER FUNCTIONS +// ============================================================================ + +/// Executes a transaction with specified state growth limit. +/// +/// Returns the execution result and the actual state growth used. +fn transact( + spec: MegaSpecId, + db: &mut MemoryDatabase, + state_growth_limit: u64, + tx: TxEnv, +) -> Result<(ResultAndState, u64), EVMError> { + let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), + ); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; + + let ctx = evm.ctx_ref(); + let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; + Ok((r, state_growth)) +} + +/// Checks if the execution result indicates that the state growth limit was exceeded. +fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { + matches!( + &result.result, + ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } + ) +} + +/// Creates a default transaction builder calling a contract. +fn default_tx_builder(to: Address) -> TxEnvBuilder { + TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) +} + +// ============================================================================ +// BASIC STATE GROWTH TRACKING TESTS +// ============================================================================ + +// ============================================================================ +// NET GROWTH MODEL TESTS +// ============================================================================ + +// ============================================================================ +// FRAME-BASED TRACKING TESTS +// ============================================================================ + +// ============================================================================ +// LIMIT ENFORCEMENT TESTS +// ============================================================================ + +#[test] +fn test_limit_exactly_at_limit() { + // Create exactly 3 slots with limit of 3 + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .sstore(U256::from(2), U256::from(3)) // +1 + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_success()); + assert_eq!(state_growth, 3, "Exactly at limit should succeed"); +} + +#[test] +fn test_limit_exceeded_by_one() { + // Try to create 4 slots with limit of 3 + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .sstore(U256::from(2), U256::from(3)) // +1 + .sstore(U256::from(3), U256::from(4)) // +1 (exceeds limit) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); + + // Verify the halt reason details - the actual growth is preserved in the halt reason + match &result.result { + ExecutionResult::Halt { + reason: MegaHaltReason::StateGrowthLimitExceeded { limit, actual }, + .. + } => { + assert_eq!(*limit, 3); + assert_eq!(*actual, 4, "Should report actual growth that exceeded limit"); + } + _ => panic!("Expected StateGrowthLimitExceeded halt"), + } +} + +#[test] +fn test_limit_exceeded_in_nested_call() { + // Child creates 2 slots + let child_code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .stop() + .build(); + + // Parent creates 2 slots, then calls child (total would be 4, limit is 3) + let parent_code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(1)) // +1 + .sstore(U256::from(1), U256::from(2)) // +1 + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(0_u64) // argsSize + .push_number(0_u64) // argsOffset + .push_number(0_u64) // value + .push_address(CONTRACT) // child address + .push_number(10_000_000_u64) // gas + .append(CALL) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, parent_code) + .account_code(CONTRACT, child_code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); +} + +#[test] +fn test_state_reverted_when_exceeding_limit() { + // Create 2 slots, then exceed limit on 3rd (with limit of 2) + let code = BytecodeBuilder::default() + .sstore(U256::from(0), U256::from(100)) // +1 + .sstore(U256::from(1), U256::from(200)) // +1 + .sstore(U256::from(2), U256::from(300)) // +1 (exceeds) + .stop() + .build(); + + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, code); + + let tx = default_tx_builder(CALLEE).build_fill(); + let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); + + assert!(result.result.is_halt()); + assert!(is_state_growth_limit_exceeded(&result)); + + // State should not be committed + db.commit(result.state); + + // Verify the storage was not persisted + let storage_0 = db.storage(CALLEE, U256::from(0)).unwrap(); + let storage_1 = db.storage(CALLEE, U256::from(1)).unwrap(); + let storage_2 = db.storage(CALLEE, U256::from(2)).unwrap(); + + assert_eq!(storage_0, U256::ZERO, "Storage should be reverted"); + assert_eq!(storage_1, U256::ZERO, "Storage should be reverted"); + assert_eq!(storage_2, U256::ZERO, "Storage should be reverted"); +} + +// ============================================================================ +// COMPLEX SCENARIOS TESTS +// ============================================================================ + +// ============================================================================ +// TRACKER MIGRATION COVERAGE TESTS +// ============================================================================ diff --git a/crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs similarity index 82% rename from crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs rename to crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs index ceb11ef87..fb18534ff 100644 --- a/crates/mega-evm/tests/mini_rex/tx_data_and_kv_update_limit.rs +++ b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs @@ -640,23 +640,6 @@ fn test_nested_creation_revert() { // SPEC COMPARISON TESTS // ============================================================================ -/// Test that data size and KV update counts are not measured in EQUIVALENCE spec. -/// -/// This test verifies that when using the EQUIVALENCE spec, the data size and -/// KV update counting functionality is disabled. This ensures that the EQUIVALENCE -/// spec behaves like standard Ethereum without the additional data limit tracking -/// that is present in the `MINI_REX` spec. -#[test] -fn test_data_size_and_kv_update_count_are_not_measured_in_equivalence_spec() { - let mut db = MemoryDatabase::default(); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::EQUIVALENCE, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - assert_eq!(kv_update_count, 0); - assert_eq!(data_size, 0); -} - // ============================================================================ // LIMIT ENFORCEMENT TESTS // ============================================================================ @@ -1003,173 +986,6 @@ fn test_limits_reset_across_multiple_transactions() { // GAS PRESERVATION TESTS // ============================================================================ -/// Test that remaining gas is preserved (not consumed) when data limit is exceeded. -/// -/// This test verifies that when a transaction exceeds the data limit, the remaining -/// gas is refunded to the sender rather than being consumed as a penalty. This ensures -/// fair gas accounting where users only pay for work actually performed. -#[test] -fn test_data_limit_exceeded_preserves_remaining_gas() { - let mut db = MemoryDatabase::default(); - - // Simple contract with one SSTORE - let code = BytecodeBuilder::default() - .push_number(1u8) - .push_number(0u8) - .append(SSTORE) - .append(STOP) - .build(); - - db.set_account_code(CALLEE, code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Run with limit that will be exceeded - // Base tx + caller update + storage slot write - 1 (just under minimum needed) - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Verify the transaction halted due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify gas accounting - remaining gas should be significant - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Most gas should remain since we barely started execution - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining (transaction barely started), but got {}", - gas_remaining - ); -} - -/// Test that remaining gas is preserved when KV update limit is exceeded. -/// -/// This verifies that KV limit violations don't consume all gas as penalty, -/// but rather preserve the remaining gas for refund to the sender. -#[test] -fn test_kv_update_limit_exceeded_preserves_remaining_gas() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - - // Value transfer creates 2 KV updates (caller and callee account updates) - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CALLEE) - .value(U256::from(1)) - .gas_limit(1_000_000_000) - .build_fill(); - - // Set KV limit to 1 (will exceed on the 2nd update) - let (result, _, _) = transact( - MegaSpecId::MINI_REX, - &mut db, - u64::MAX, - 2 - 1, // Same as test_kv_update_limit_just_exceed - tx, - ) - .unwrap(); - - // Verify the transaction halted due to KV limit - assert!(is_kv_update_limit_exceeded(&result), "Expected KV update limit exceeded"); - - // Verify gas accounting - most gas should remain - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Transaction barely started before hitting limit - assert!( - gas_remaining > 997_000_000, - "Expected >997m gas remaining (transaction barely started), but got {}", - gas_remaining - ); -} - -/// Test that remaining gas is preserved when data limit is exceeded in a nested call. -/// -/// This test verifies that when a nested call exceeds the data limit: -/// 1. The nested call preserves its remaining gas -/// 2. The parent call also preserves its remaining gas -/// 3. Both amounts are refunded to the transaction sender -#[test] -fn test_nested_call_data_limit_exceeded_preserves_gas() { - let mut db = MemoryDatabase::default(); - - // Parent contract that calls library - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // value, argOffset, argLen, returnOffset, returnLen - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - - // Library that does SLOAD and SSTORE - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SLOAD, SSTORE, STOP]).build(); - db.set_account_code(LIBRARY, library_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Same limit as test_data_limit_exceed_in_nested_call - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Verify halt due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify significant gas remains from both parent and child - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Should have most of the gas remaining (stopped very early) - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining in nested call scenario, got {}", - gas_remaining - ); -} - -/// Test that gas is correctly preserved across multiple limit-exceeding operations. -/// -/// This test creates a scenario with multiple operations that exceed limits, -/// verifying that gas accounting remains correct throughout. -#[test] -fn test_multiple_operations_with_limit_exceeded_preserves_gas() { - let mut db = MemoryDatabase::default(); - - // Contract that does a few SSTOREs - let code = BytecodeBuilder::default() - .push_number(1u8) - .push_number(0u8) - .append(SSTORE) - .push_number(2u8) - .push_number(1u8) - .append(SSTORE) - .push_number(3u8) - .push_number(2u8) - .append(SSTORE) - .append(STOP) - .build(); - - db.set_account_code(CALLEE, code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Set limit to allow: base tx + caller update + only 1 storage write - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE; - let (result, _, _) = - transact(MegaSpecId::MINI_REX, &mut db, tight_limit, u64::MAX, tx).unwrap(); - - // Should halt due to data limit - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - // Verify gas is preserved - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - // Should have significant gas remaining (stopped after 1 write instead of 3) - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining with multiple operations, got {}", - gas_remaining - ); -} - // ============================================================================ // TRACKER MIGRATION COVERAGE TESTS // ============================================================================ @@ -1346,101 +1162,3 @@ impl Inspector for GasSpendingInspector { } } } - -/// Test that `rescue_gas` correctly preserves remaining gas when an inspector calls -/// `spend_all()` in `call_end`, for the `inspect_frame_init` early-return path. -/// -/// The KV limit is exceeded in `before_frame_init` (value transfer creates 2 KV updates -/// but limit is 1), so `frame_init` returns an error result immediately. `try_rescue_gas` -/// captures the gas before `frame_end` → `call_end` fires on the inspector. -/// Without the fix, the inspector's `spend_all()` would zero the gas before rescue. -#[test] -fn test_rescue_gas_with_gas_spending_inspector_frame_init() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CALLEE) - .value(U256::from(1)) - .gas_limit(1_000_000_000) - .build_fill(); - - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(2 - 1), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut inspector = GasSpendingInspector; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(is_kv_update_limit_exceeded(&result), "Expected KV update limit exceeded"); - - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 997_000_000, - "Expected >997m gas remaining (rescue_gas should capture gas before inspector spend_all), got {}", - gas_remaining - ); -} - -/// Test that `rescue_gas` correctly preserves remaining gas when an inspector calls -/// `spend_all()` in `call_end`, for the `inspect_frame_run` path. -/// -/// The data limit is exceeded during SSTORE execution inside a nested call. -/// `after_frame_run` rescues gas, then `frame_end` → `call_end` fires on the inspector. -/// Without the fix, the inspector's `spend_all()` would zero the gas before rescue. -#[test] -fn test_rescue_gas_with_gas_spending_inspector_frame_run() { - let mut db = MemoryDatabase::default(); - - // Parent contract that calls a library - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(LIBRARY) - .append(GAS) - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - - // Library that does SSTORE, which will exceed the data limit - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SSTORE, STOP]).build(); - db.set_account_code(LIBRARY, library_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill(); - - // Set data limit tight enough that SSTORE exceeds it - let tight_limit = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE - 1; - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(tight_limit) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut inspector = GasSpendingInspector; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(is_data_limit_exceeded(&result), "Expected data limit exceeded"); - - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 990_000_000, - "Expected >990m gas remaining (rescue_gas should capture gas before inspector spend_all), got {}", - gas_remaining - ); -} diff --git a/crates/mega-evm/tests/rex/main.rs b/crates/mega-evm/tests/_pending/rex/main.rs similarity index 76% rename from crates/mega-evm/tests/rex/main.rs rename to crates/mega-evm/tests/_pending/rex/main.rs index 2706ccd5e..f474f301d 100644 --- a/crates/mega-evm/tests/rex/main.rs +++ b/crates/mega-evm/tests/_pending/rex/main.rs @@ -1,5 +1,3 @@ //! Tests for Rex hardfork features. - -mod intrinsic_gas; mod oracle; mod storage_gas; diff --git a/crates/mega-evm/tests/rex/oracle.rs b/crates/mega-evm/tests/_pending/rex/oracle.rs similarity index 100% rename from crates/mega-evm/tests/rex/oracle.rs rename to crates/mega-evm/tests/_pending/rex/oracle.rs diff --git a/crates/mega-evm/tests/rex/storage_gas.rs b/crates/mega-evm/tests/_pending/rex/storage_gas.rs similarity index 93% rename from crates/mega-evm/tests/rex/storage_gas.rs rename to crates/mega-evm/tests/_pending/rex/storage_gas.rs index 7042dd19f..a9455333d 100644 --- a/crates/mega-evm/tests/rex/storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex/storage_gas.rs @@ -557,58 +557,6 @@ fn test_combined_contract_creation_and_sstore() { assert_eq!(gas_used, expected_total); } -#[test] -fn test_rex_vs_minirex_comparison() { - // Compare REX vs Mini-Rex storage gas costs - // Mini-Rex: 2,000,000 × multiplier - // REX: base × (multiplier - 1) where base is 20k/25k/32k - - let mut db_rex = MemoryDatabase::default(); - let mut db_minirex = MemoryDatabase::default(); - - db_rex.set_account_balance(CALLER, U256::from(10_000_000_000_000u64)); - db_minirex.set_account_balance(CALLER, U256::from(10_000_000_000_000u64)); - - let multiplier = 10u64; - let bucket_capacity = MIN_BUCKET_SIZE as u64 * multiplier; - - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NEW_ACCOUNT); - let external_envs = TestExternalEnvs::new().with_bucket_capacity(bucket_id, bucket_capacity); - - // Account creation comparison - let rex_result = transact( - MegaSpecId::REX, - &mut db_rex, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000_000, - ) - .expect("REX transaction should succeed"); - - let minirex_result = transact( - MegaSpecId::MINI_REX, - &mut db_minirex, - &external_envs, - CALLER, - Some(NEW_ACCOUNT), - Bytes::new(), - U256::from(1_000), - 100_000_000, - ) - .expect("Mini-Rex transaction should succeed"); - - // REX should charge less for dynamic operations but has higher intrinsic - // REX: 21k + 39k + 25k×(10-1) = 285k - // Mini-Rex: 21k + 0 + 2M×10 = 20,021k - assert!( - rex_result.result.gas_used() < minirex_result.result.gas_used(), - "REX should charge less total gas than Mini-Rex for account creation" - ); -} - #[test] fn test_large_multiplier_linear_scaling() { // Verify storage gas scales linearly even with large multipliers diff --git a/crates/mega-evm/tests/rex2/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs similarity index 94% rename from crates/mega-evm/tests/rex2/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs index 180647020..cf4024147 100644 --- a/crates/mega-evm/tests/rex2/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs @@ -379,66 +379,6 @@ fn test_keyless_deploy_contract_already_exists_deploy_address_in_witness_rex6() ); } -/// Pre-REX6 replay parity: the journaled read is gated to REX6+. Pre-REX6 (sealed) must keep using -/// the raw, unjournaled DB read for the occupancy check, so the deploy address must NOT appear in -/// the returned `EvmState` / witness — no retroactive behavior change. -#[test] -fn test_keyless_deploy_contract_already_exists_deploy_address_not_in_witness_pre_rex6() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::ContractAlreadyExists); - assert!( - !result.state.contains_key(&CREATE2_FACTORY_CONTRACT), - "pre-REX6 (sealed) must keep the raw DB read: the deploy address must NOT appear in the \ - returned EvmState — no retroactive witness change", - ); -} - -/// Regression guard for the critical issue this fix's review caught: journaling the deploy- -/// address occupancy read pre-REX5 corrupts the legacy sandbox-state merge -/// (`apply_sandbox_state_legacy` / `merge_evm_state_optional_status` with `merge_status = false`), -/// which copies `info`/storage for an already-`Occupied` journal entry but does NOT merge account -/// status. A deploy address pre-inserted into the journal by the occupancy check (as a -/// `LoadedAsNotExisting|Cold` placeholder) would hit that `Occupied` branch instead of the -/// `Vacant` one, losing the `Created|Touched` status the successfully deployed contract needs to -/// survive `revm`'s commit (which discards untouched accounts). This test performs a full -/// `db.commit(result.state)` round trip and confirms the deployed contract's code is actually -/// present afterward — the exact thing a `state.get(..).info.code` check on the raw `EvmState` -/// (as the other success tests in this file do) would NOT catch, since `info` is still copied -/// correctly; only the `AccountStatus` bits needed for `commit()` to keep the account are lost. -#[test] -fn test_keyless_deploy_pre_rex6_success_still_commits_deployed_code() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - assert!(result.result.is_success(), "keyless deploy should succeed: {:?}", result.result); - - db.commit(result.state); - let deployed = db.basic(CREATE2_FACTORY_CONTRACT).unwrap(); - assert!( - deployed.is_some_and(|info| info.code_hash == CREATE2_FACTORY_CODE_HASH), - "the deployed contract must survive a commit() round trip on pre-REX6 — a regression \ - here means the occupancy-check journal read is corrupting the legacy state merge", - ); -} - /// REX6 twin of the test above: under REX6 the step-7 occupancy check journals the deploy /// address (cold, via `inspect_account_code_hash`) *before* the sandbox runs, so at merge time /// the address is already an occupied journal entry rather than a fresh one. The merge must @@ -1009,37 +949,6 @@ fn test_keyless_deploy_signer_nonce_too_high() { // Spec Version Tests // ============================================================================= -#[test] -fn test_keyless_deploy_not_available_before_rex2() { - // In REX1, the keyless deploy contract is not deployed at the address. - // Calling an address with no code succeeds with empty output (no deployment occurs). - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX1, // Before REX2 - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // In REX1, there's no code at the keyless deploy address, so the call succeeds - // with empty output (calling an address with no code returns success). - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success (no-op) in REX1, got: {:?}", - result - ); - - // Verify that the contract was NOT deployed (no code at target address) - assert!( - !state.contains_key(&CREATE2_FACTORY_CONTRACT), - "Contract should NOT be deployed in REX1" - ); -} - #[test] fn test_keyless_deploy_not_intercepted_for_inner_calls() { // Keyless deploy should only work for top-level calls (depth == 0). diff --git a/crates/mega-evm/tests/rex2/main.rs b/crates/mega-evm/tests/_pending/rex2/main.rs similarity index 80% rename from crates/mega-evm/tests/rex2/main.rs rename to crates/mega-evm/tests/_pending/rex2/main.rs index 4a20cfef8..af70245a9 100644 --- a/crates/mega-evm/tests/rex2/main.rs +++ b/crates/mega-evm/tests/_pending/rex2/main.rs @@ -2,4 +2,3 @@ mod keyless_deploy; mod oracle_hint; -mod selfdestruct; diff --git a/crates/mega-evm/tests/rex2/oracle_hint.rs b/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs similarity index 93% rename from crates/mega-evm/tests/rex2/oracle_hint.rs rename to crates/mega-evm/tests/_pending/rex2/oracle_hint.rs index 35ca8314d..908d73b3d 100644 --- a/crates/mega-evm/tests/rex2/oracle_hint.rs +++ b/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs @@ -187,31 +187,6 @@ fn test_on_hint_called_on_rex2() { assert_eq!(hints[0].data, hint_data, "Hint data should match"); } -/// Test that `on_hint` is NOT called when Rex1 is enabled (pre-Rex2). -#[test] -fn test_on_hint_not_called_on_rex1() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - // Main contract that calls sendHint on the oracle contract - let main_code = create_call_send_hint_bytecode(user_topic, &hint_data); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - // Deploy the actual v1.1.0 oracle contract - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let result = execute_transaction(MegaSpecId::REX1, &mut db, &external_envs, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that on_hint was NOT called - let hints = external_envs.recorded_hints(); - assert!(hints.is_empty(), "Should NOT have recorded any hints on Rex1"); -} - /// Test that `on_hint` is NOT called for calls to non-oracle contracts. /// Even if a contract has a sendHint function, it must be the oracle contract /// for the hint to be intercepted. diff --git a/crates/mega-evm/tests/rex3/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs similarity index 84% rename from crates/mega-evm/tests/rex3/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs index 7259b7b3d..7c75ed261 100644 --- a/crates/mega-evm/tests/rex3/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex3/keyless_deploy.rs @@ -86,31 +86,6 @@ fn test_rex3_keyless_deploy_records_compute_gas() { ); } -/// Test that Rex2 keyless deploy does NOT count toward compute gas (backward compat). -#[test] -fn test_rex2_keyless_deploy_does_not_record_compute_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let (result, compute_gas_used) = execute_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - - // In Rex2, keyless deploy returns early before compute gas tracking. - // The only compute gas recorded should be intrinsic tx gas, NOT the keyless deploy overhead. - assert!( - compute_gas_used < constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - "Rex2 compute gas ({}) should NOT include keyless deploy overhead ({})", - compute_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - /// Test that keyless deploy halts when compute gas limit is set below the 100K overhead. /// In Rex3, the 100K overhead is recorded as compute gas, so if the compute gas limit /// is lower than 100K, the transaction should fail. diff --git a/crates/mega-evm/tests/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs similarity index 100% rename from crates/mega-evm/tests/rex3/main.rs rename to crates/mega-evm/tests/_pending/rex3/main.rs diff --git a/crates/mega-evm/tests/rex3/oracle_gas_limit.rs b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs similarity index 83% rename from crates/mega-evm/tests/rex3/oracle_gas_limit.rs rename to crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs index 96901b85e..327f491c8 100644 --- a/crates/mega-evm/tests/rex3/oracle_gas_limit.rs +++ b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs @@ -141,74 +141,6 @@ fn test_rex3_call_oracle_without_sload_no_detention() { ); } -/// Test that REX2 still uses CALL-based oracle access detection (1M limit). -#[test] -fn test_rex2_oracle_access_still_uses_1m_compute_gas_limit() { - // For Rex2, just calling oracle (no code needed) triggers detention - let bytecode = build_call_oracle_bytecode(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX2, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert_eq!( - compute_gas_limit, - mega_evm::constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, - "REX2 compute gas limit should be 1M after oracle access" - ); -} - -/// Test that a transaction consuming >1M but <20M compute gas after oracle access succeeds -/// under REX3 but fails under REX2. -/// -/// Rex3 path: CALL oracle (with SLOAD code) triggers 20M detention, then ~4.4M SSTOREs succeed. -/// Rex2 path: CALL oracle triggers 1M detention, then ~4.4M SSTOREs exceed the limit. -#[test] -fn test_oracle_access_succeeds_rex3_fails_rex2() { - // Oracle contract code for Rex3 - performs SLOAD to trigger detention - let oracle_code = build_oracle_sload_code(); - - // Build callee bytecode: call oracle, then do ~200 SSTOREs (~4.4M compute gas) - let mut builder = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP); - - // 200 SSTOREs to unique slots: ~200 * 22,100 = ~4.4M compute gas - for i in 1..=200u32 { - builder = builder.push_number(i).push_number(i).append(SSTORE); - } - let bytecode = builder.append(STOP).build(); - - // REX3: should succeed (4.4M < 20M limit) - let mut db_rex3 = MemoryDatabase::default(); - db_rex3.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db_rex3.set_account_code(CALLEE, bytecode.clone()); - let (result_rex3, _) = execute_transaction(MegaSpecId::REX3, &mut db_rex3, CALLEE); - assert!( - result_rex3.is_success(), - "REX3 transaction should succeed: ~4.4M compute gas is within the 20M oracle access limit" - ); - - // REX2: should fail (4.4M > 1M limit). No oracle code needed - CALL triggers detention. - let mut db_rex2 = MemoryDatabase::default(); - db_rex2.set_account_code(CALLEE, bytecode); - let (result_rex2, _) = execute_transaction(MegaSpecId::REX2, &mut db_rex2, CALLEE); - assert!( - !result_rex2.is_success(), - "REX2 transaction should fail: ~4.4M compute gas exceeds the 1M oracle access limit" - ); - assert!( - is_volatile_data_access_oog(&result_rex2), - "REX2 should fail with VolatileDataAccessOutOfGas" - ); -} - /// Test that REX3 still enforces the 20M limit (not unlimited). /// A transaction consuming >20M compute gas after oracle SLOAD should still fail. #[test] diff --git a/crates/mega-evm/tests/rex3/system_address.rs b/crates/mega-evm/tests/_pending/rex3/system_address.rs similarity index 100% rename from crates/mega-evm/tests/rex3/system_address.rs rename to crates/mega-evm/tests/_pending/rex3/system_address.rs diff --git a/crates/mega-evm/tests/rex4/access_control.rs b/crates/mega-evm/tests/_pending/rex4/access_control.rs similarity index 96% rename from crates/mega-evm/tests/rex4/access_control.rs rename to crates/mega-evm/tests/_pending/rex4/access_control.rs index 8ef61d7c2..976f8ab06 100644 --- a/crates/mega-evm/tests/rex4/access_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/access_control.rs @@ -502,39 +502,6 @@ fn test_delegatecall_also_restricted() { // 7. BACKWARD COMPATIBILITY // ============================================================================ -/// On Rex3, calling the access control address has no special effect (contract not deployed). -#[test] -fn test_pre_rex4_no_interception() { - // On Rex3, the access control contract is not deployed, so calling it - // should not activate any volatile access restrictions. - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: attempt to call disableVolatileDataAccess, then call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - // Use Rex3 spec - let mut context = MegaContext::new(&mut db, MegaSpecId::REX3); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // The child should succeed (TIMESTAMP not blocked on Rex3) - assert!(result.result.is_success(), "On Rex3, volatile access should NOT be disabled"); - assert_log_call_status(&result, 0, true); -} - // ============================================================================ // 8. CONDITIONAL VOLATILE OPCODES // ============================================================================ @@ -2027,50 +1994,3 @@ fn test_blocked_selfdestruct_beneficiary_does_not_pollute_tracker() { "compute_gas_limit should not be set after blocked SELFDESTRUCT to beneficiary" ); } - -/// On Rex3 (pre-Rex4), SELFDESTRUCT targeting the beneficiary should NOT be checked or -/// restricted for volatile data access. The volatile data check is Rex4-only. -#[test] -fn test_selfdestruct_beneficiary_not_restricted_pre_rex4() { - let beneficiary = Address::ZERO; - - // Child: SELFDESTRUCT targeting the beneficiary - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // Parent: call child, log call status - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - // Use Rex3 spec (pre-Rex4) - let mut context = MegaContext::new(&mut db, MegaSpecId::REX3); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // SELFDESTRUCT targeting beneficiary should succeed on Rex3 - assert!( - result.result.is_success(), - "On Rex3, SELFDESTRUCT to beneficiary should not be restricted" - ); - assert_log_call_status(&result, 0, true); - - // Volatile data tracker should NOT have marked beneficiary balance access - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "On Rex3, SELFDESTRUCT to beneficiary should not mark volatile data access" - ); -} diff --git a/crates/mega-evm/tests/rex4/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs similarity index 93% rename from crates/mega-evm/tests/rex4/beneficiary_detention.rs rename to crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs index 0fc5f4859..5944b95e9 100644 --- a/crates/mega-evm/tests/rex4/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs @@ -387,35 +387,6 @@ fn test_caller_is_beneficiary_eager_detention() { // TEST 5b: Caller is beneficiary — pre-REX4 no eager detention // ============================================================================ -/// Pre-REX4 specs never had eager beneficiary detention at TX start. -/// Same scenario as test 5 but with REX3: `detained_limit` should remain at TX limit. -#[test] -fn test_caller_is_beneficiary_pre_rex4_no_eager_detention() { - // Simple code: just STOP. We check detained_limit, not remainingComputeGas - // (MegaLimitControl interception is REX4-only). - let callee_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(BENEFICIARY, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = TxEnvBuilder::default() - .caller(BENEFICIARY) - .call(CALLEE) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact_with_spec(MegaSpecId::REX3, &mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx) - .unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - detained_limit, 200_000_000, - "Pre-REX4 caller=beneficiary: detained limit should remain at TX limit (no eager detention)" - ); -} - // ============================================================================ // TEST 6: Recipient is beneficiary — eager detention from TX start // ============================================================================ @@ -456,33 +427,6 @@ fn test_recipient_is_beneficiary_eager_detention() { // TEST 6b: Recipient is beneficiary — pre-REX4 no eager detention // ============================================================================ -/// Pre-REX4 specs never had eager beneficiary detention at TX start. -/// Same scenario as test 6 but with REX3: `detained_limit` should remain at TX limit. -#[test] -fn test_recipient_is_beneficiary_pre_rex4_no_eager_detention() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact_with_spec(MegaSpecId::REX3, &mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx) - .unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - detained_limit, 200_000_000, - "Pre-REX4 recipient=beneficiary: detained limit should remain at TX limit (no eager detention)" - ); -} - // ============================================================================ // TEST 7: SELFBALANCE in beneficiary contract triggers detention (integration) // ============================================================================ diff --git a/crates/mega-evm/tests/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs similarity index 52% rename from crates/mega-evm/tests/rex4/create_safety.rs rename to crates/mega-evm/tests/_pending/rex4/create_safety.rs index dab3c32c4..363729117 100644 --- a/crates/mega-evm/tests/rex4/create_safety.rs +++ b/crates/mega-evm/tests/_pending/rex4/create_safety.rs @@ -148,113 +148,3 @@ fn run_create2_and_get_compute_gas( let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; (res.result, compute_gas) } - -#[test] -fn test_create2_memory_expansion_recorded_as_compute_gas() { - // 32000-byte initcode -> 1000 words -> ~4953 gas of memory expansion. - const INITCODE_LEN: u64 = 32_000; - let words = INITCODE_LEN.div_ceil(32); - let expected_expansion = memory_expansion_gas(INITCODE_LEN); - // KECCAK256 over the initcode (charged inside CREATE2). - let expected_hash = 6 * words; - // CREATE2 per-initcode-word cost (part of CREATE2's static charge). - let expected_init_word = 2 * words; - // Sum of all three initcode_len-scaled costs. The expansion cost is what the wrapper must - // record into the compute gas tracker. - let expected_extra = expected_expansion + expected_hash + expected_init_word; - - let (baseline_result, baseline_compute_gas) = run_create2_and_get_compute_gas(0, 10_000_000); - assert!( - matches!(baseline_result, ExecutionResult::Success { .. }), - "baseline CREATE2 with empty initcode should succeed: {:?}", - baseline_result - ); - - let (big_result, big_compute_gas) = run_create2_and_get_compute_gas(INITCODE_LEN, 10_000_000); - assert!( - matches!(big_result, ExecutionResult::Success { .. }), - "large-initcode CREATE2 should succeed: {:?}", - big_result - ); - - // The delta should equal the sum of all three initcode-length-scaled costs (within a - // small tolerance for the differing PUSH opcode used to push the length itself: PUSH0 - // for 0 vs PUSHn for 32000). If the wrapper failed to record the expansion gas, the - // delta would be short by `expected_expansion`. - let delta = big_compute_gas - baseline_compute_gas; - let diff = delta.abs_diff(expected_extra); - assert!( - diff < 50, - "compute gas delta ({}) should ~equal expansion ({}) + hash ({}) + init_word ({}) = {}; \ - baseline={}, big={}, diff={}. If diff is close to {}, the wrapper's resize_memory! \ - consumed interpreter gas but never recorded it into the compute gas tracker.", - delta, - expected_expansion, - expected_hash, - expected_init_word, - expected_extra, - baseline_compute_gas, - big_compute_gas, - diff, - expected_expansion, - ); -} - -#[test] -fn test_create2_resize_gas_skipped_when_canonical_create2_oogs() { - // Verifies the deferred-recording semantics: when the inner CREATE2 OOGs (after the - // wrapper's resize_memory! has already consumed interpreter gas), the compute gas - // tracker must NOT receive the resize_gas. This mirrors `wrap_op_compute_gas`'s - // "skip on inner error" pattern — historically the canonical CREATE2's expansion gas - // was only recorded when the inner instruction completed without an EVM error. - // - // Strategy: pick a tx gas budget tight enough that, after intrinsic + bytecode + the - // wrapper's resize, the remaining gas cannot cover the canonical CREATE2's static - // base cost (32_000). The two runs (small vs big initcode) both halt with OutOfGas. - // With deferred recording: compute gas delta ≈ 1 (just the differing PUSH opcode for - // the length argument). With (hypothetical) immediate recording: delta would be - // ≈ 1 + expected_expansion. - const INITCODE_LEN: u64 = 32_000; - let expected_expansion = memory_expansion_gas(INITCODE_LEN); - - // REX4 intrinsic = 21_000 (base) + 39_000 (REX TX_INTRINSIC_STORAGE_GAS) = 60_000. - // After intrinsic, leave 31_000 for the frame: PUSHes (~9) + (for big run) resize - // (~4953) + canonical CREATE2 base (32_000+). Small run has ~30_992 for canonical's - // 32_000 base → OOG; big run has ~26_038 for canonical's 40_000 (32k base + 2k init - // + 6k keccak) → also OOG. Both halt inside canonical CREATE2. - let tight_gas: u64 = 91_000; - - let (small_result, small_compute_gas) = run_create2_and_get_compute_gas(0, tight_gas); - let (big_result, big_compute_gas) = run_create2_and_get_compute_gas(INITCODE_LEN, tight_gas); - - // Both must OOG (otherwise the test premise is broken and the assertion below is - // not actually exercising the deferred-recording path). - assert!( - matches!(small_result, ExecutionResult::Halt { .. }), - "small-initcode run should OOG inside canonical CREATE2 at tight_gas={}: {:?}", - tight_gas, - small_result - ); - assert!( - matches!(big_result, ExecutionResult::Halt { .. }), - "big-initcode run should OOG inside canonical CREATE2 at tight_gas={}: {:?}", - tight_gas, - big_result - ); - - // The only legitimate compute-gas difference between the two runs is the length-PUSH - // opcode (PUSH0 vs PUSHn, ~1 gas). If the wrapper recorded resize_gas eagerly, the - // big-initcode run would also be charged ~`expected_expansion` extra, putting the - // delta near 4953 instead of near 0. - let delta = big_compute_gas.abs_diff(small_compute_gas); - assert!( - delta < 50, - "compute gas delta on OOG ({}) should be ~0; got small={}, big={}. If delta is \ - close to expected_expansion ({}), the resize gas leaked into the tracker even \ - though the inner CREATE2 errored — the deferred-recording skip path is broken.", - delta, - small_compute_gas, - big_compute_gas, - expected_expansion, - ); -} diff --git a/crates/mega-evm/tests/rex4/deployment.rs b/crates/mega-evm/tests/_pending/rex4/deployment.rs similarity index 92% rename from crates/mega-evm/tests/rex4/deployment.rs rename to crates/mega-evm/tests/_pending/rex4/deployment.rs index 0c339519e..de45f65ff 100644 --- a/crates/mega-evm/tests/rex4/deployment.rs +++ b/crates/mega-evm/tests/_pending/rex4/deployment.rs @@ -163,14 +163,3 @@ fn test_rex4_system_contract_deployment_is_idempotent() { ); }); } - -#[test] -fn test_rex3_boundary_does_not_deploy_rex4_system_contracts() { - with_executor(MegaSpecId::REX3, rex3_chain_spec(), |executor| { - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let db_ref = executor.evm_mut().db_mut(); - assert_contract_not_deployed(db_ref, ACCESS_CONTROL_ADDRESS, "MegaAccessControl"); - assert_contract_not_deployed(db_ref, LIMIT_CONTROL_ADDRESS, "MegaLimitControl"); - }); -} diff --git a/crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs similarity index 71% rename from crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs rename to crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs index d348fe450..91f504a0c 100644 --- a/crates/mega-evm/tests/rex4/eip7702_delegation_cycle.rs +++ b/crates/mega-evm/tests/_pending/rex4/eip7702_delegation_cycle.rs @@ -16,12 +16,6 @@ //! The issue only manifests when a *contract* performs a CALL-family opcode targeting the //! poisoned address. //! -//! ## Storage isolation tests -//! -//! EIP-7702 delegation only affects code — storage always belongs to the original address. -//! `inspect_storage` (used by the wrapped SLOAD/SSTORE for storage gas accounting) must -//! access the original address's storage, not the delegate's. -//! //! ## EIP-7702 spec note //! //! EIP-7702 specifies that clients must resolve at most one level of delegation. @@ -368,135 +362,3 @@ fn test_delegation_cycle_via_create2() { "CREATE2 with cyclic delegation should complete without stack overflow" ); } - -// --------------------------------------------------------------------------- -// Storage isolation tests — verify `inspect_storage` uses the original address -// --------------------------------------------------------------------------- - -/// Builds a contract that sequentially CALLs `first` then `second`, returning the -/// 32-byte returndata from the second call. -fn build_two_calls_return_second(first: Address, second: Address) -> Bytes { - BytecodeBuilder::default() - // CALL first target (no returndata needed) - .append(PUSH0) // retLength - .append(PUSH0) // retOffset - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(first) - .append(GAS) - .append(CALL) - .append(POP) // discard success flag - // CALL second target — capture 32 bytes of returndata at memory[0] - .push_number(32u8) // retLength - .append(PUSH0) // retOffset = 0 - .append(PUSH0) // argsLength - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(second) - .append(GAS) - .append(CALL) - .append(POP) // discard success flag - // Return memory[0..32] - .push_number(32u8) // size - .append(PUSH0) // offset - .append(RETURN) - .build() -} - -/// Sets up and runs the `inspect_storage` pollution scenario for a given spec. -/// -/// Setup: -/// - DELEGATOR delegates to DELEGATE via EIP-7702. -/// - DELEGATE's code does `SSTORE(slot=1, 0x77)` then `SLOAD(1)` then RETURN. -/// - DELEGATOR has storage[1] = 42, DELEGATE has storage[1] = 99. -/// -/// PARENT's code does two sequential CALLs in one transaction: -/// 1. CALL DELEGATOR — runs DELEGATE's code in DELEGATOR's context. The wrapped SSTORE calls -/// `inspect_storage(DELEGATOR, 1)`. -/// 2. CALL DELEGATE directly — runs DELEGATE's code in its own context. -/// -/// Returns the `ResultAndState` for spec-specific assertions. -fn run_inspect_storage_pollution_scenario(spec: MegaSpecId) -> ResultAndState { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000u64)); - - // DELEGATE: code does SSTORE(1, 0x77) then SLOAD(1) then RETURN. - // Has storage[1] = 99 which should never be confused with DELEGATOR's. - let delegate_code = BytecodeBuilder::default() - .sstore(U256::from(1), U256::from(0x77)) - .push_number(1u8) // slot 1 - .append(SLOAD) - .append(PUSH0) - .append(MSTORE) - .push_number(32u8) - .append(PUSH0) - .append(RETURN) - .build(); - db.set_account_code(DELEGATE, delegate_code); - db.set_account_storage(DELEGATE, U256::from(1), U256::from(99)); - db.set_account_balance(DELEGATE, U256::from(1_000_000u64)); - - // DELEGATOR: delegates to DELEGATE, storage[1] = 42 - set_eip7702_delegation(&mut db, DELEGATOR, DELEGATE); - db.set_account_storage(DELEGATOR, U256::from(1), U256::from(42)); - db.set_account_balance(DELEGATOR, U256::from(1_000_000u64)); - - // PARENT: calls DELEGATOR first (triggers inspect_storage), then DELEGATE directly - db.set_account_code(PARENT, build_two_calls_return_second(DELEGATOR, DELEGATE)); - db.set_account_balance(PARENT, U256::from(1_000_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let result = transact(spec, &mut db, tx).expect("transaction should succeed"); - assert!(result.result.is_success(), "execution should succeed: {:?}", result.result); - - let output = result.result.output().expect("should have output"); - let second_call_sload = U256::from_be_slice(output); - // After SSTORE(1, 0x77), SLOAD(1) should return 0x77 (the just-written value) - // regardless of spec — the pollution only affects original_value, not present_value. - assert_eq!( - second_call_sload, - U256::from(0x77), - "SLOAD after SSTORE should return the just-written value" - ); - - result -} - -/// REX4+: `inspect_storage` no longer follows EIP-7702 delegation, so the delegate's -/// journal is not polluted. -/// DELEGATE's slot 1 `original_value` should be 99 (its own DB value). -#[test] -fn test_inspect_storage_does_not_pollute_delegate_journal_rex4() { - let result = run_inspect_storage_pollution_scenario(MegaSpecId::REX4); - - let delegate_account = result.state.get(&DELEGATE).expect("DELEGATE should be in state"); - let slot = - delegate_account.storage.get(&U256::from(1)).expect("slot 1 should exist in DELEGATE"); - assert_eq!( - slot.original_value(), - U256::from(99), - "REX4: DELEGATE's slot 1 original_value should be 99 (its own), not 42 (DELEGATOR's)" - ); -} - -/// Pre-REX4: `inspect_storage` follows EIP-7702 delegation (original behavior), so the -/// delegate's journal gets polluted with the delegator's storage value. -/// DELEGATE's slot 1 `original_value` will be 42 (DELEGATOR's value) instead of 99. -#[test] -fn test_inspect_storage_pollutes_delegate_journal_pre_rex4() { - let result = run_inspect_storage_pollution_scenario(MegaSpecId::REX3); - - let delegate_account = result.state.get(&DELEGATE).expect("DELEGATE should be in state"); - let slot = - delegate_account.storage.get(&U256::from(1)).expect("slot 1 should exist in DELEGATE"); - // Pre-REX4 preserves the old behavior: inspect_storage follows delegation and - // pollutes the delegate's journal with the delegator's storage value. - assert_eq!( - slot.original_value(), - U256::from(42), - "Pre-REX4: DELEGATE's slot 1 original_value should be 42 (polluted from DELEGATOR)" - ); -} diff --git a/crates/mega-evm/tests/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs similarity index 73% rename from crates/mega-evm/tests/rex4/frame_limits.rs rename to crates/mega-evm/tests/_pending/rex4/frame_limits.rs index 92ec811e7..83bdcc404 100644 --- a/crates/mega-evm/tests/rex4/frame_limits.rs +++ b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs @@ -454,50 +454,6 @@ fn test_data_size_child_exceed_followed_by_sibling_success() { assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(98)); } -#[test] -fn test_data_size_rex3_no_per_frame_limits() { - // REX3: child writes 99 slots with TX limit = 100 slots → succeeds (TX-level only). - let limit = tx_intrinsic_data_size() + n_sstore_data(99); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX3, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame data size limits"); - assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(99)); -} - -#[test] -fn test_data_size_rex3_tx_exceed_halts() { - // REX3: child exceeds TX-level limit → Halt (not Revert). - let limit = n_sstore_data(10); - let child_code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(MegaSpecId::REX3, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level data size exceed"); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - // ============================================================================ // KV UPDATE PER-FRAME LIMITS // ============================================================================ @@ -726,49 +682,6 @@ fn test_kv_update_child_exceed_followed_by_sibling_success() { assert_eq!(kv_updates, 1 + 98); } -#[test] -fn test_kv_update_rex3_no_per_frame_limits() { - // REX3: child writes 99 KV ops with TX limit = 100 → succeeds. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX3, &mut db, u64::MAX, 100, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame KV limits"); - assert_eq!(kv_updates, 1 + 99); -} - -#[test] -fn test_kv_update_rex3_tx_exceed_halts() { - // REX3: child exceeds TX-level KV limit → Halt. - let child_code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - // KV limit = 10: caller(1) + 10 sstores = 11 > 10 - let (result, _, _) = transact_data_kv(MegaSpecId::REX3, &mut db, u64::MAX, 10, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level KV exceed"); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - )); -} - // ============================================================================ // COMPUTE GAS PER-FRAME LIMITS // ============================================================================ @@ -792,164 +705,3 @@ fn burn_gas_code(target_gas: u64) -> Bytes { code.push(STOP); Bytes::from(code) } - -#[test] -fn test_compute_gas_child_exceeds_budget_frame_local_revert() { - // TX limit = 2_000_000; child budget = 1_960_000. - // Burn 1_970_000 in child (> frame budget). Keep total TX usage under 2_000_000 - // so this remains frame-local and parent can continue. - let tx_limit = 2_000_000_u64; - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child frame-local revert"); - assert!(!result.result.is_halt(), "Should NOT be halt"); -} - -#[test] -fn test_compute_gas_child_gas_still_counts_despite_revert() { - // Unlike StateGrowth, ComputeGas is persistent: even after per-frame revert, - // the child's gas is counted in the parent's total. - // Set TX limit high (2_000_000). Child budget = 1_960_000. Child burns 1_970_000. - // Parent's total compute gas should INCLUDE the child's gas. - - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - // Child budget = 2_000_000 * 98 / 100 = 1_960_000. - // Child burns 1_970_000 > 1_960_000 → per-frame revert. - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, 2_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Child's gas persists — total should be significantly more than just the parent's minimal ops. - // The parent itself uses very little gas (just the CALL setup and POP/STOP). - assert!( - compute_gas > 1_900_000, - "Child's gas should be counted despite revert: got {compute_gas}" - ); -} - -#[test] -fn test_compute_gas_revert_data_encodes_mega_limit_exceeded() { - // kind=2 (ComputeGas), limit=child's frame budget - let tx_limit = 2_000_000_u64; - let child_code = burn_gas_code(1_970_000); - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 2, "kind should be 2 (ComputeGas)"); - assert!( - decoded.limit <= tx_limit * 98 / 100, - "limit should be <= 98% of tx limit after parent pre-call gas; got {}", - decoded.limit - ); -} - -#[test] -fn test_compute_gas_rex3_no_per_frame_limits() { - // REX3: no per-frame compute gas limits. Child with budget 98% frame budget - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX3, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame compute gas limits"); -} - -#[test] -fn test_compute_gas_sibling_frames_independent() { - // After child A reverts (per-frame exceed), child B still gets a fresh budget. - // TX limit = 2_500_000. Child A budget = 2_450_000, burns 2_460_000 → Revert. - // Parent remaining after A's gas (persistent) is still enough for child B. - // Child B burns 10 gas and succeeds. - // - // This test mainly verifies the TX doesn't halt after multiple children run. - let tx_limit = 2_500_000_u64; - let child_a_code = burn_gas_code(2_460_000); // > 2_450_000 (98% of 2_500_000) - let child_b_code = burn_gas_code(10); // tiny gas, should succeed - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 5_000_000) - .append(POP) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(CONTRACT2) - .push_number(5_000_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(result.result.is_success(), "TX should succeed with multiple children"); -} - -#[test] -fn test_compute_gas_top_level_exceed_is_frame_local_revert() { - // Top-level frame exceeds its own remaining compute budget in Rex4: should Revert, not Halt. - // Burn more than the first-frame budget after intrinsic compute gas is deducted. - let tx_limit = 2_000_000_u64; - let code = burn_gas_code(tx_limit); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, compute_gas) = transact_compute(MegaSpecId::REX4, &mut db, tx_limit, tx).unwrap(); - - assert!(matches!(result.result, ExecutionResult::Revert { .. })); - assert!(!result.result.is_halt()); - assert!(compute_gas > tx_limit, "Persistent compute gas should still exceed the TX limit"); -} diff --git a/crates/mega-evm/tests/rex4/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs similarity index 91% rename from crates/mega-evm/tests/rex4/gas_detention.rs rename to crates/mega-evm/tests/_pending/rex4/gas_detention.rs index 821bd2d90..463179592 100644 --- a/crates/mega-evm/tests/rex4/gas_detention.rs +++ b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs @@ -265,31 +265,3 @@ fn test_rex4_multiple_volatile_accesses_first_wins() { "Detained limit should be anchored at first access (~25M), got {detained_limit}" ); } - -/// Pre-REX4: Same scenario as `test_rex4_volatile_access_after_heavy_compute_succeeds` -/// but with `MINI_REX` spec — should halt immediately (backward compatibility). -#[test] -fn test_pre_rex4_absolute_cap_preserved() { - // Burn 25M compute gas, then access TIMESTAMP. - // Pre-REX4 absolute cap = 20M. 25M > 20M -> halts immediately. - let builder = append_burn_gas(BytecodeBuilder::default(), 25_000_000); - let code = builder.append(TIMESTAMP).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, _compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::MINI_REX, &mut db, 1_000_000_000, BLOCK_ENV_CAP, tx) - .unwrap(); - - assert!( - is_volatile_data_access_oog(&result.result), - "Pre-REX4 should halt with absolute cap when usage exceeds 20M before access" - ); - assert_eq!( - detained_limit, BLOCK_ENV_CAP, - "Pre-REX4 detained limit should be the absolute cap (20M)" - ); -} diff --git a/crates/mega-evm/tests/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs similarity index 100% rename from crates/mega-evm/tests/rex4/intrinsic_limit_bypass.rs rename to crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs diff --git a/crates/mega-evm/tests/rex4/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs similarity index 76% rename from crates/mega-evm/tests/rex4/keyless_deploy.rs rename to crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs index d570507e2..b746a8277 100644 --- a/crates/mega-evm/tests/rex4/keyless_deploy.rs +++ b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs @@ -236,61 +236,6 @@ fn test_rex4_keyless_deploy_uses_salt_env() { ); } -/// Rex3 keyless deploy ignores the salt env (backward compatibility). -/// -/// Pre-Rex4 sandbox always uses `EmptyExternalEnv`, so changing bucket capacity -/// should not affect sandbox `gas_used`. -#[test] -fn test_rex3_keyless_deploy_ignores_salt_env() { - // Run with default bucket capacity - let mut db_default = MemoryDatabase::default(); - db_default.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let env_default = TestExternalEnvs::::new(); - let (result_default, gas_default) = execute_keyless_deploy_with_envs( - MegaSpecId::REX3, - &mut db_default, - &env_default, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_default.is_success(), - "Default deploy should succeed, got: {:?}", - result_default - ); - - // Run with elevated bucket capacity - let mut db_high = MemoryDatabase::default(); - db_high.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let high_capacity = (MIN_BUCKET_SIZE as u64) * 2; - let env_high = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket_id(), high_capacity) - .with_bucket_capacity(deployer_bucket_id(), high_capacity); - let (result_high, gas_high) = execute_keyless_deploy_with_envs( - MegaSpecId::REX3, - &mut db_high, - &env_high, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_high.is_success(), - "High-capacity deploy should succeed, got: {:?}", - result_high - ); - - // Pre-REX4 sandbox uses EmptyExternalEnv, so gas should be the same regardless of capacity - assert_eq!( - gas_default, gas_high, - "REX3 sandbox gas should be the same regardless of bucket capacity: default={}, high={}", - gas_default, gas_high, - ); -} - /// Rex4 keyless deploy sandbox forwards oracle hints emitted in constructors. #[test] fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { @@ -316,26 +261,3 @@ fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { assert_eq!(hints[0].topic, topic, "hint topic should match constructor input"); assert_eq!(hints[0].data, Bytes::copy_from_slice(hint_data), "hint data should match"); } - -/// Rex3 keyless deploy sandbox keeps the historical empty oracle env behavior. -#[test] -fn test_rex3_keyless_deploy_constructor_ignores_oracle_env() { - let topic = B256::repeat_byte(0x22); - let hint_data = b"rex3-sandbox-hint"; - let init_code = create_constructor_send_hint_init_code(topic, hint_data); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - let (result, _) = - execute_keyless_deploy_with_envs(MegaSpecId::REX3, &mut db, &external_envs, tx_bytes); - - assert!(result.is_success(), "keyless deploy should succeed, got: {:?}", result); - assert!( - external_envs.recorded_hints().is_empty(), - "pre-REX4 sandbox should not forward oracle hints", - ); -} diff --git a/crates/mega-evm/tests/rex4/limit_control.rs b/crates/mega-evm/tests/_pending/rex4/limit_control.rs similarity index 98% rename from crates/mega-evm/tests/rex4/limit_control.rs rename to crates/mega-evm/tests/_pending/rex4/limit_control.rs index 0e0b93ba2..fa5d1cb1c 100644 --- a/crates/mega-evm/tests/rex4/limit_control.rs +++ b/crates/mega-evm/tests/_pending/rex4/limit_control.rs @@ -732,16 +732,3 @@ fn test_callcode_not_intercepted() { // ============================================================================ // 6. BACKWARD COMPATIBILITY // ============================================================================ - -/// On Rex3, calling the address has no special interception behavior. -#[test] -fn test_pre_rex4_no_interception() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(MegaSpecId::REX3, &mut db, direct_query_tx(LIMIT_CONTROL_ADDRESS)).unwrap(); - - assert!(result.result.is_success()); - let output = result.result.output().expect("success must include output"); - assert!(output.is_empty(), "REX3 should not intercept this system contract call"); -} diff --git a/crates/mega-evm/tests/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs similarity index 83% rename from crates/mega-evm/tests/rex4/main.rs rename to crates/mega-evm/tests/_pending/rex4/main.rs index dde7619c9..b75668583 100644 --- a/crates/mega-evm/tests/rex4/main.rs +++ b/crates/mega-evm/tests/_pending/rex4/main.rs @@ -6,10 +6,8 @@ mod create_safety; mod deployment; mod eip7702_delegation_cycle; mod frame_limits; -mod frame_state_growth; mod gas_detention; mod intrinsic_limit_bypass; mod keyless_deploy; mod limit_control; -mod selfdestruct_state_growth; mod storage_call_stipend; diff --git a/crates/mega-evm/tests/rex4/storage_call_stipend.rs b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs similarity index 69% rename from crates/mega-evm/tests/rex4/storage_call_stipend.rs rename to crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs index 1a5fa49b6..c629ec73d 100644 --- a/crates/mega-evm/tests/rex4/storage_call_stipend.rs +++ b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs @@ -281,28 +281,6 @@ fn test_log1_in_receive_succeeds_under_rex4() { } } -/// Under REX3 (pre-REX4), the same CALL should fail because `STORAGE_CALL_STIPEND` is not -/// available and the callee only gets 2,300 gas which is insufficient for LOG1 (4,500). -#[test] -fn test_log1_in_receive_fails_under_rex3() { - let sender_code = build_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX3, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "inner CALL should fail under REX3 (no STORAGE_CALL_STIPEND)" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - /// The storage-call stipend only applies to internal `CALL`/`CALLCODE`, not to the /// top-level transaction frame. #[test] @@ -366,68 +344,6 @@ fn test_callcode_gets_storage_call_stipend() { } } -/// `STORAGE_CALL_STIPEND` should be burned on return. -/// When the callee does nothing (STOP), the parent should NOT recover the stipend as free gas. -/// We verify this by comparing `gas_used` with and without value transfer. -#[test] -fn test_storage_call_stipend_burned_on_return() { - // Contract that CALLs EMPTY_RECEIVER with value (gets stipend, stipend should be burned) - let sender_with_value = build_transfer_contract(EMPTY_RECEIVER); - // Contract that CALLs EMPTY_RECEIVER without value (no stipend) - let sender_no_value = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value = 0 (no transfer) - .push_address(EMPTY_RECEIVER) - .push_number(0_u64) // gas = 0 - .append(CALL) - .append(STOP) - .build(); - let empty_code = BytecodeBuilder::default().append(STOP).build(); - - // Test with value transfer (gets STORAGE_CALL_STIPEND) - let mut db_with_value = - setup_db(&[(SENDER_CONTRACT, sender_with_value), (EMPTY_RECEIVER, empty_code.clone())]); - let result_with_value = transact(MegaSpecId::REX4, &mut db_with_value, default_tx()).unwrap(); - let gas_used_with_value = match &result_with_value.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("expected Success, got {other:?}"), - }; - - // The gas_used should NOT include the burned STORAGE_CALL_STIPEND as "free" gas. - // If the stipend leaked, the parent would have more remaining gas, resulting in lower gas_used. - // We verify that gas_used is at least what we'd expect with the CALLVALUE cost. - // CALLVALUE cost = 9000, so the transfer CALL should cost the parent at least 9000 more. - let sender_no_value_addr = address!("0000000000000000000000000000000000200004"); - let mut db_no_value = - setup_db(&[(sender_no_value_addr, sender_no_value), (EMPTY_RECEIVER, empty_code)]); - let tx_no_value = TxEnvBuilder::default() - .caller(CALLER) - .call(sender_no_value_addr) - .gas_limit(100_000_000) - .build_fill(); - let result_no_value = transact(MegaSpecId::REX4, &mut db_no_value, tx_no_value).unwrap(); - let gas_used_no_value = match &result_no_value.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("expected Success, got {other:?}"), - }; - - // With value transfer: parent pays CALLVALUE (9000), but recovers the original - // CALL_STIPEND (2300) as unused gas. Net cost ≈ 6700. - // Without value: no CALLVALUE cost, no stipend. - // The difference should be approximately CALLVALUE - CALL_STIPEND = 6700. - // If STORAGE_CALL_STIPEND (23000) leaked, the difference would be negative - // (parent would gain ~23000 free gas, far exceeding the CALLVALUE cost). - let diff = gas_used_with_value.saturating_sub(gas_used_no_value); - assert!( - diff >= 6000, - "STORAGE_CALL_STIPEND should be burned, not leaked. \ - gas_used_with_value={gas_used_with_value}, gas_used_no_value={gas_used_no_value}, diff={diff}" - ); -} - /// CALL without value transfer should NOT receive `STORAGE_CALL_STIPEND`. #[test] fn test_no_stipend_without_value_transfer() { @@ -532,41 +448,6 @@ fn test_staticcall_no_storage_call_stipend() { assert!(matches!(result.result, ExecutionResult::Success { .. }), "STATICCALL should succeed"); } -/// When the callee reverts, the `STORAGE_CALL_STIPEND` should still be burned -/// (not returned to the parent). -#[test] -fn test_storage_call_stipend_burned_on_revert() { - // Receiver that emits LOG1 then reverts - let receiver_code = BytecodeBuilder::default() - .push_number(0xdeadbeef_u64) - .push_number(0_u64) - .push_number(0_u64) - .append(LOG1) - .revert() - .build(); - let sender_code = build_transfer_contract(RECEIVER); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - // Inner CALL reverts, so success_flag = 0 - assert_eq!(success_flag, U256::ZERO, "inner CALL should revert"); - } - other => panic!("expected outer Success (inner revert), got {other:?}"), - } - // The key check: the transaction's total gas_used should be reasonable. - // The STORAGE_CALL_STIPEND should have been burned, not leaked back to the parent. - let gas_used = match &result.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - _ => unreachable!(), - }; - // Gas used should be at least the intrinsic + CALLVALUE cost. - // If stipend leaked, gas_used would be much lower. - assert!(gas_used > 21_000 + 9_000, "gas_used should reflect CALLVALUE cost, got {gas_used}"); -} - /// `STORAGE_CALL_STIPEND` must NOT be usable for pure computation. /// A callee that only does compute (PUSH/POP loops, no LOG or storage ops) should still /// be limited to `CALL_STIPEND` (2,300) worth of compute gas. @@ -685,45 +566,6 @@ fn test_intercepted_value_call_does_not_leak_storage_call_stipend() { ); } -/// Top-level keyless deploy interception must preserve the gas already consumed by the -/// interceptor itself. -#[test] -fn test_top_level_keyless_deploy_value_call_preserves_gas_accounting() { - let call_data = Bytes::from( - IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::new(), - gasLimitOverride: U256::ZERO, - } - .abi_encode(), - ); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(KEYLESS_DEPLOY_ADDRESS) - .gas_limit(200_000) - .data(call_data) - .value(U256::from(1_u64)) - .build_fill(); - - let mut rex3_db = setup_db(&[]); - let rex3_result = transact(MegaSpecId::REX3, &mut rex3_db, tx.clone()).unwrap(); - let rex3_gas_used = match rex3_result.result { - ExecutionResult::Revert { gas_used, .. } => gas_used, - other => panic!("expected Revert, got {other:?}"), - }; - - let mut rex4_db = setup_db(&[]); - let rex4_result = transact(MegaSpecId::REX4, &mut rex4_db, tx).unwrap(); - let rex4_gas_used = match rex4_result.result { - ExecutionResult::Revert { gas_used, .. } => gas_used, - other => panic!("expected Revert, got {other:?}"), - }; - - assert_eq!( - rex4_gas_used, rex3_gas_used, - "REX4 should preserve keyless-deploy interceptor gas accounting on top-level value calls" - ); -} - /// Nested value-transferring calls: A calls B with value, B calls C with value. /// Both B and C should independently receive and burn their own `STORAGE_CALL_STIPEND`, /// exercising the stipend stack push/pop alignment across multiple depth levels. @@ -843,118 +685,3 @@ fn test_stipend_not_leaked_on_frame_local_limit_exceed() { "gas_used {gas_used} is too low — STORAGE_CALL_STIPEND may have leaked to parent" ); } - -/// When CALL with value targets an EOA (no code), revm's `frame_init` returns a Result -/// immediately without creating an interpreter frame. The `STORAGE_CALL_STIPEND` must -/// still be burned via `before_frame_return_result` and not leak to the parent. -/// -/// This exercises the `after_frame_init` Result path, which is distinct from the normal -/// frame execution path tested by `test_storage_call_stipend_burned_on_return`. -#[test] -fn test_stipend_burned_on_eoa_value_transfer() { - let sender_code = build_transfer_contract(EOA_RECEIVER); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - db.set_account_balance(EOA_RECEIVER, U256::from(1_000_000u128)); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!(success_flag, U256::from(1), "inner CALL to EOA should succeed"); - } - other => panic!("expected Success, got {other:?}"), - } - - let gas_used = match &result.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - _ => unreachable!(), - }; - // Intrinsic gas + CALL costs (cold access 2,600 + value transfer 9,000 + - // gas_stipend deduction 2,300) + parent opcodes. - // If the 23,000 stipend leaked via the after_frame_init Result path, - // gas_used would drop by ~23,000. - assert!( - gas_used > 50_000, - "gas_used {gas_used} is too low — STORAGE_CALL_STIPEND may have leaked on EOA transfer" - ); -} - -/// On the REX4 legacy-inflation path, when a value-transferring child frame that received a -/// `STORAGE_CALL_STIPEND` hits a TX-level detained compute-gas limit, `rescue_gas` must EXCLUDE -/// the stipend from the gas rescued back to the sender (system-granted gas must not leak). -/// -/// This pins the exact `gas_used` so the stipend exclusion is observable end-to-end: with the -/// exclusion (correct) the rescued gas is capped at the pre-stipend limit; without it the full -/// child `gas.remaining()` is rescued, refunding ~13k extra gas and lowering `gas_used`. -/// -/// Kills the mutant `current_frame_stipend -> 0` in `storage_call_stipend.rs`: with the mutant, -/// `effective_remaining_for_rescue` skips the exclusion and `gas_used` drops from `69_321` to -/// `56_325`. -#[test] -fn test_stipend_excluded_from_rescued_gas_on_tx_level_detention_exceed() { - let sender_code = build_value_call_contract(RECEIVER, 100_000); - let receiver_code = - append_burn_gas(BytecodeBuilder::default().append(TIMESTAMP).append(POP), 20_000) - .append(STOP) - .build(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let tx = default_tx(); - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX4, &mut db, tx, limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, - gas_used, - } => { - // Exact gas_used with the stipend correctly excluded from the rescued gas. - // If `current_frame_stipend` returns 0 (mutant), the exclusion is skipped, the full - // child `gas.remaining()` is rescued, and gas_used drops to 56_325. - assert_eq!( - *gas_used, 69_321, - "STORAGE_CALL_STIPEND must be excluded from rescued gas on TX-level exceed; \ - a lower gas_used means the system-granted stipend leaked back to the sender" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas halt, got {other:?}"), - } -} - -/// If a value-transferring child frame with an active `STORAGE_CALL_STIPEND` hits a TX-level -/// detained compute gas limit, `rescue_gas` must cap the refund at the pre-stipend limit instead -/// of panicking in debug builds. -#[test] -fn test_stipend_with_tx_level_detention_exceed_does_not_panic() { - let sender_code = build_value_call_contract(RECEIVER, 100_000); - let receiver_code = - append_burn_gas(BytecodeBuilder::default().append(TIMESTAMP).append(POP), 20_000) - .append(STOP) - .build(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let tx = default_tx(); - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX4, &mut db, tx, limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { limit, .. }, - gas_used, - } => { - assert!( - *limit <= 1_000_000, - "detained limit should stay within the tx compute gas limit, got {limit}" - ); - assert!( - *gas_used < 200_000, - "gas_used should reflect rescued gas rather than the full child gas limit, got {gas_used}" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas, got {other:?}"), - } -} diff --git a/crates/mega-evm/tests/rex5/apply_pending_changes_gas_budget.rs b/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs similarity index 100% rename from crates/mega-evm/tests/rex5/apply_pending_changes_gas_budget.rs rename to crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs diff --git a/crates/mega-evm/tests/rex5/callcode_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs similarity index 92% rename from crates/mega-evm/tests/rex5/callcode_storage_gas.rs rename to crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs index f664a68ee..6193eaf91 100644 --- a/crates/mega-evm/tests/rex5/callcode_storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/callcode_storage_gas.rs @@ -227,24 +227,6 @@ fn test_rex5_callcode_from_eip7702_authority_no_storage_gas() { // CALLCODE: Pre-Rex5 frozen behavior — bug preserved // ============================================================================ -/// Pre-Rex5 (Rex4) preserves the original (buggy) behavior: a value-transferring -/// `CALLCODE` to an empty code-source charges new-account storage gas based on the -/// code-source's bucket. This test pins that behavior so a future regression in -/// stable-spec semantics is caught. -#[test] -fn test_rex4_callcode_to_empty_charges_new_account_storage_gas() { - let bytecode = callcode_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX4, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX4, bytecode, 10); - - let expected_extra = NEW_ACCOUNT_STORAGE_GAS_BASE * 9; - assert_eq!( - gas_mult10 - gas_mult1, - expected_extra, - "Rex4 (frozen) must keep charging new-account storage gas against the code-source bucket", - ); -} - // ============================================================================ // CALL: behavior unchanged — value-transferring CALL to empty target still charges // ============================================================================ @@ -266,22 +248,6 @@ fn test_rex5_call_to_empty_still_charges_new_account_storage_gas() { ); } -/// Pre-Rex5 (Rex4) `CALL` behavior is unchanged: value-transferring CALL to an -/// empty target charges new-account storage gas based on the target's bucket. -#[test] -fn test_rex4_call_to_empty_charges_new_account_storage_gas() { - let bytecode = call_bytecode(EMPTY_TARGET); - let gas_mult1 = run_with_target_multiplier(MegaSpecId::REX4, bytecode.clone(), 1); - let gas_mult10 = run_with_target_multiplier(MegaSpecId::REX4, bytecode, 10); - - let expected_extra = NEW_ACCOUNT_STORAGE_GAS_BASE * 9; - assert_eq!( - gas_mult10 - gas_mult1, - expected_extra, - "Rex4 CALL must charge new-account storage gas against the target bucket", - ); -} - // ============================================================================ // Error-path tests — coverage for FatalExternalError branches in call_code // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/create2_empty_initcode.rs b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs similarity index 87% rename from crates/mega-evm/tests/rex5/create2_empty_initcode.rs rename to crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs index c1a96a17b..01457e980 100644 --- a/crates/mega-evm/tests/rex5/create2_empty_initcode.rs +++ b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs @@ -113,21 +113,6 @@ fn test_rex5_create2_len_nonzero_offset_max_still_halts() { ); } -/// REX4 (pre-REX5) baseline: same input MUST halt — the stable-spec path runs -/// `as_usize_or_fail!(U256::MAX)` and surfaces an `InvalidOperandOOG`-shaped -/// halt. Frozen for replay parity; pinned so a future change that backports the -/// short-circuit to stable specs is caught here. -#[test] -fn test_rex4_create2_len_zero_offset_max_halts() { - let code = build_create2_empty_initcode_at_offset(U256::MAX); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "REX4 CREATE2(len=0, offset=U256::MAX) must halt (frozen stable-spec behavior); \ - got {result:?}", - ); -} - /// REX5: `CREATE2(len=0, offset=large_finite)` MUST succeed without paying for /// memory expansion. Without the short-circuit, `resize_memory!(1<<30, 0)` /// quadratically prices the implied range — pricing canonical revm explicitly @@ -163,16 +148,6 @@ fn test_rex5_create2_len_zero_offset_zero_succeeds() { assert!(result.is_success(), "REX5 CREATE2(len=0, offset=0) must succeed; got {result:?}",); } -/// REX4: `CREATE2(len=0, offset=0)` happy path — pinned to confirm pre-REX5 -/// still succeeds via the frozen "observe offset (=0), trivial resize, slice -/// empty, hash empty" sequence. -#[test] -fn test_rex4_create2_len_zero_offset_zero_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!(result.is_success(), "REX4 CREATE2(len=0, offset=0) must succeed; got {result:?}",); -} - /// REX5 vs REX4 deployed-address parity for `len=0, offset=0`. Both must derive /// the same address `creator.create2(0, KECCAK_EMPTY)` — REX5 via the /// short-circuit, REX4 via `keccak256(slice_len(0, 0))` which equals diff --git a/crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs similarity index 86% rename from crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs rename to crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs index f695721f7..ed1c754ee 100644 --- a/crates/mega-evm/tests/rex5/create2_resize_gas_metering.rs +++ b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs @@ -89,37 +89,6 @@ fn test_rex5_create2_with_non_trivial_resize_succeeds() { ); } -/// REX4 baseline: same scenario under the pre-REX5 spec succeeds via the trailing -/// late-record path. Pinned to guarantee replay parity is preserved. -#[test] -fn test_rex4_create2_with_non_trivial_resize_succeeds() { - let (result, compute) = transact_create2(MegaSpecId::REX4, INITCODE_LEN); - assert!(result.is_success(), "REX4 CREATE2 happy path must succeed; got {result:?}"); - assert!( - compute > 0, - "REX4 compute_gas tracker must register usage including resize_gas; got {compute}", - ); -} - -/// Cross-spec parity: REX5's early-record path and pre-REX5's late-record path must -/// register the same `resize_gas` total on a successful CREATE2. A multi-KiB delta -/// would indicate either a double-count under REX5 (early + trailing both recording -/// the same `resize_gas`) or a miss-count (early-record path skipped without the -/// trailing block taking over). -#[test] -fn test_create2_compute_gas_parity_across_specs() { - let (result_rex5, compute_rex5) = transact_create2(MegaSpecId::REX5, INITCODE_LEN); - let (result_rex4, compute_rex4) = transact_create2(MegaSpecId::REX4, INITCODE_LEN); - assert!(result_rex5.is_success(), "REX5 must succeed; got {result_rex5:?}"); - assert!(result_rex4.is_success(), "REX4 must succeed; got {result_rex4:?}"); - - let diff = compute_rex5.abs_diff(compute_rex4); - assert!( - diff < 1_000, - "REX5 ({compute_rex5}) vs REX4 ({compute_rex4}) compute_gas must agree within 1K gas — diff = {diff}", - ); -} - /// Runs a CREATE2 contract built from raw bytecode (used to construct stack-underflow /// scenarios that `build_create2_contract` cannot express). Mirrors `transact_create2`. fn transact_create2_with_code( diff --git a/crates/mega-evm/tests/rex5/db_error.rs b/crates/mega-evm/tests/_pending/rex5/db_error.rs similarity index 100% rename from crates/mega-evm/tests/rex5/db_error.rs rename to crates/mega-evm/tests/_pending/rex5/db_error.rs diff --git a/crates/mega-evm/tests/rex5/deposit_caller_accounting.rs b/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs similarity index 92% rename from crates/mega-evm/tests/rex5/deposit_caller_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs index 19dacf310..91767300f 100644 --- a/crates/mega-evm/tests/rex5/deposit_caller_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/deposit_caller_accounting.rs @@ -234,42 +234,6 @@ fn test_rex5_non_empty_caller_no_extra_charge() { let _ = gas_normal; // referenced for clarity; precise inequality is implicit via growth check. } -/// REX4 replay parity: under stable REX4, deposit-driven caller materialisation -/// does NOT charge caller-side storage gas and does NOT record a state-growth -/// event. Any drift here breaks replay of historical REX4 blocks. -#[test] -fn test_rex4_baseline_behaviour() { - let db_empty = - MemoryDatabase::default().account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_empty = make_op_deposit_tx(EMPTY_CALLER, 1_000_000u128, TARGET_CONTRACT); - let (res_empty, evm_empty) = transact_with(MegaSpecId::REX4, db_empty, tx_empty); - let res_empty = res_empty.expect("ok"); - assert!(res_empty.result.is_success()); - - let db_funded = MemoryDatabase::default() - .account_balance(FUNDED_CALLER, U256::from(1u64)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let tx_funded = make_op_deposit_tx(FUNDED_CALLER, 1_000_000u128, TARGET_CONTRACT); - let (res_funded, evm_funded) = transact_with(MegaSpecId::REX4, db_funded, tx_funded); - let res_funded = res_funded.expect("ok"); - assert!(res_funded.result.is_success()); - - // REX4: empty vs funded must produce identical gas usage on the deposit-caller path - // (the only legitimate gas delta would come from the deposit-caller rule, which is REX5-gated). - assert_eq!( - res_empty.result.gas_used(), - res_funded.result.gas_used(), - "REX4 deposit gas must be identical between empty and funded caller", - ); - // REX4: state_growth must be unaffected by the deposit caller materialisation. - let growth_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage().state_growth; - let growth_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage().state_growth; - assert_eq!( - growth_empty, growth_funded, - "REX4 state_growth must not differ between empty and funded caller", - ); -} - /// Routes every account to a single high-capacity bucket so the new-account /// storage gas charge under REX5 (`25_000 × (multiplier - 1)`) is non-zero. #[derive(Debug, Clone, Copy)] diff --git a/crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs b/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs similarity index 91% rename from crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs rename to crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs index c1ace9870..c70520043 100644 --- a/crates/mega-evm/tests/rex5/deposit_create_storage_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/deposit_create_storage_gas.rs @@ -147,25 +147,6 @@ fn test_deposit_create_storage_gas_uses_state_nonce() { ); } -/// Same diverging-nonce setup under REX4: pre-REX5 prices storage gas at -/// `caller.create(tx.nonce)`, which lands in the default cheap bucket. -#[test] -fn test_pre_rex5_preserves_tx_nonce_storage_gas_pricing() { - let mut db = seed_caller(STATE_NONCE); - let envs = envs_with_heavy_bucket_at(STATE_NONCE); - let gas_limit = 50_000_000; - let tx = deposit_create_tx(TX_NONCE, gas_limit); - - let res = run(MegaSpecId::REX4, &mut db, &envs, tx); - - assert!(res.result.is_success(), "deposit CREATE must succeed: {:?}", res.result); - let gas_used = res.result.gas_used(); - assert!( - gas_used < EXPECTED_HEAVY_STORAGE_GAS, - "expected gas_used < {EXPECTED_HEAVY_STORAGE_GAS} (cheap bucket), got {gas_used}", - ); -} - /// Non-deposit CREATE under REX5: `tx.nonce == state.nonce`, so the /// state-nonce read returns the same value as `tx.nonce()` did. #[test] diff --git a/crates/mega-evm/tests/rex5/eip7702_metering.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs similarity index 100% rename from crates/mega-evm/tests/rex5/eip7702_metering.rs rename to crates/mega-evm/tests/_pending/rex5/eip7702_metering.rs diff --git a/crates/mega-evm/tests/rex5/eip7702_state_growth.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs similarity index 92% rename from crates/mega-evm/tests/rex5/eip7702_state_growth.rs rename to crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs index aaf77b308..189fbfb49 100644 --- a/crates/mega-evm/tests/rex5/eip7702_state_growth.rs +++ b/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs @@ -106,39 +106,6 @@ fn test_rex5_new_authority_state_growth() { ); } -/// The same transaction under REX4 should NOT include authority accounts in state growth. -/// -/// Pre-REX5, EIP-7702 authority accounts are not counted toward state growth. -#[test] -fn test_rex4_single_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // REX4 does not count authority accounts in state growth. - assert_eq!( - usage.state_growth, 0, - "REX4 should not count authority accounts in state growth: {}", - usage.state_growth - ); -} - /// REX5 with two new authorities should count +2 state growth. #[test] fn test_rex5_two_new_authorities_state_growth() { diff --git a/crates/mega-evm/tests/rex5/gas_validation.rs b/crates/mega-evm/tests/_pending/rex5/gas_validation.rs similarity index 86% rename from crates/mega-evm/tests/rex5/gas_validation.rs rename to crates/mega-evm/tests/_pending/rex5/gas_validation.rs index 86b91faba..f6d7752c7 100644 --- a/crates/mega-evm/tests/rex5/gas_validation.rs +++ b/crates/mega-evm/tests/_pending/rex5/gas_validation.rs @@ -222,41 +222,6 @@ fn test_rex5_valid_tx_still_passes() { // second pre-REX5 code path (REX adds `TX_INTRINSIC_STORAGE_GAS`, so MINI_REX and REX..REX4 walk // Mega-step-D differently). -/// REX4 (stable spec) must preserve the historical bug-shape behavior: `validate()` accepts -/// the tx, `pre_execution()` debits and bumps, and execution synthesizes an OOG halt with -/// `gas_used == gas_limit`. This test fails loudly if any future change leaks the REX5 -/// rejection back into a stable spec. -#[test] -fn test_rex4_preserves_legacy_oog_after_full_gas_charge() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000u64)); - - let multiplier = 10u64; - let external_envs = external_envs_with_hot_account(NEW_ACCOUNT, multiplier); - - // Same scenario shape as the REX5 test, with a gas limit that covers intrinsic+REX - // intrinsic-storage but not new-account storage gas. - let insufficient_gas_limit = 80_000; - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(NEW_ACCOUNT), - data: Bytes::new(), - value: U256::from(1), - gas_limit: insufficient_gas_limit, - ..Default::default() - }; - - let res = run_tx(MegaSpecId::REX4, &mut db, external_envs, tx) - .expect("pre-REX5 specs must NOT reject this as a validation error"); - assert!(!res.result.is_success(), "REX4 must still produce a halt, not success"); - assert!(res.result.is_halt(), "REX4 must still produce a halt-shaped result"); - assert_eq!( - res.result.gas_used(), - insufficient_gas_limit, - "REX4 must still consume the entire gas limit (bug-shape preserved)" - ); -} - // `_` to prove `InvalidTransaction` from `revm::context::result` is reachable via the // public re-export and to catch a future revm bump that drops the variant. const _: fn() = || { diff --git a/crates/mega-evm/tests/rex5/interceptor_selector_probe.rs b/crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs similarity index 100% rename from crates/mega-evm/tests/rex5/interceptor_selector_probe.rs rename to crates/mega-evm/tests/_pending/rex5/interceptor_selector_probe.rs diff --git a/crates/mega-evm/tests/rex5/keyless_deploy_dispatch_parity.rs b/crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs similarity index 100% rename from crates/mega-evm/tests/rex5/keyless_deploy_dispatch_parity.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_deploy_dispatch_parity.rs diff --git a/crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs b/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs similarity index 85% rename from crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs index a04aee7ab..c70e692e0 100644 --- a/crates/mega-evm/tests/rex5/keyless_empty_code_logs.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs @@ -242,46 +242,6 @@ fn test_rex5_keyless_empty_code_forwards_log_to_parent_receipt() { ); } -/// REX4 (pre-REX5 frozen): same input MUST return success-style with -/// `EmptyCodeDeployed` errorData, but the parent receipt MUST contain NO logs -/// (legacy "drop logs" behavior, preserved for replay parity). -#[test] -fn test_rex4_keyless_empty_code_drops_logs_for_replay_parity() { - let topic = - B256::from_slice(&hex!("ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11")); - let init_code = build_log1_then_empty_return_init_code(topic); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // REX4 sandbox is NOT fee-free — fund signer so the inner tx can pay - // `gas_limit_override × signed_gas_price` upfront. - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000u128)); - - // REX4 sandbox debits `gas_limit_override × signed_gas_price` from signer at - // pre-execution. With `signed_gas_price = 100 gwei`, an override of 1M gas - // costs 0.0001 ETH — well within the 1 ETH funding above. Using - // `LARGE_GAS_LIMIT_OVERRIDE` (10^10) here would demand 10^21 wei = 1000 ETH - // and trip the `InsufficientBalance` precheck before the sandbox can run. - let rex4_gas_limit_override: u64 = 1_000_000; - let result = - run_keyless_outer(MegaSpecId::REX4, &mut db, keyless_tx_bytes, rex4_gas_limit_override); - - let error_data = extract_error_data(&result); - let decoded_err = decode_error_result(&error_data); - assert!( - matches!(decoded_err, Some(KeylessDeployError::EmptyCodeDeployed { .. })), - "REX4 empty-code path must surface EmptyCodeDeployed in errorData; got {decoded_err:?}", - ); - - let logs = result.logs(); - assert!( - logs.is_empty(), - "REX4 empty-code path must NOT forward sandbox logs (frozen for replay parity); \ - got logs = {logs:?}", - ); -} - /// REX5 with an empty-code constructor that emits NO logs MUST report /// `EmptyCodeDeployed` AND a zero-length receipt log list. Pins that the /// `SandboxCompletion::EmptyCode` wiring forwards exactly the logs the sandbox emitted, not diff --git a/crates/mega-evm/tests/rex5/keyless_fee_free.rs b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs similarity index 96% rename from crates/mega-evm/tests/rex5/keyless_fee_free.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs index 746f3e9f9..3c8bf8483 100644 --- a/crates/mega-evm/tests/rex5/keyless_fee_free.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs @@ -235,41 +235,6 @@ fn test_rex5_value_zero_signer_zero_balance_deploys_successfully() { // 2. REX4 keeps the `gas_cost + value` balance precheck // ============================================================================ -/// REX4 (frozen spec): the sandbox's pre-execution balance check must reject an -/// unfunded signer, because pre-Rex5 runs the sandbox as a non-deposit tx that -/// debits `gas_limit × gas_price` from the signer. The fee-free simplification -/// is REX5-only. -#[test] -fn test_rex4_unfunded_signer_still_rejected_by_balance_precheck() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // signer NOT funded; pre-Rex5 gas_cost > 0 so balance check trips. - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - _ => panic!( - "REX4 must revert when sandbox pre-check rejects unfunded signer; got {result:?}" - ), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - assert!( - matches!(err, KeylessDeployError::InsufficientBalance), - "REX4 must reject unfunded signer with InsufficientBalance; got {err:?}", - ); -} - // ============================================================================ // 3. value > 0 still requires the signer to fund the transfer (REX5) // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs b/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs similarity index 89% rename from crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs index 67429f4e1..f8181ede7 100644 --- a/crates/mega-evm/tests/rex5/keyless_gas_cap_postcap_recheck.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs @@ -208,42 +208,6 @@ fn test_rex5_envelope_above_signed_min_proceeds_normally() { ); } -/// REX4 parity: same envelope-too-small setup must NOT produce the post-cap -/// `GasLimitTooLow` shape under the pre-REX5 spec (no cap is applied, so the -/// recheck never sees a capped value smaller than `tx_gas_limit`). Any other -/// outcome — sandbox OOG, balance precheck, etc. — is acceptable as the -/// baseline; we just pin that the new REX5 path is genuinely REX5-gated. -#[test] -fn test_rex4_envelope_too_small_does_not_fire_post_cap_recheck() { - let (keyless_tx_bytes, signer) = build_keyless_tx(); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Fund signer enough to cover the REX4 sandbox's `gas_limit × gas_price` - // balance precheck when the sandbox runs uncapped at `LARGE_OVERRIDE`. - db.set_account_balance(signer, U256::from(100_000_000_000_000_000_000u128)); - - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - keyless_tx_bytes, - LARGE_OVERRIDE, - TIGHT_OUTER_GAS, - ); - - if let ExecutionResult::Revert { output, .. } = &result { - if let Some(KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit }) = - decode_error_result(output) - { - assert!( - provided_gas_limit >= tx_gas_limit, - "REX4 must not produce the post-cap-capped GasLimitTooLow shape; \ - got provided_gas_limit ({provided_gas_limit}) < tx_gas_limit ({tx_gas_limit})", - ); - } - } -} - /// Post-cap recheck must fire on the materialization-drain shape: outer envelope is /// fat enough to clear intrinsic + `KEYLESS_DEPLOY_OVERHEAD_GAS` without dipping below /// `tx_gas_limit`, but `charge_caller_materialization_pre_sandbox` for an unfunded diff --git a/crates/mega-evm/tests/rex5/keyless_replay_barrier.rs b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs similarity index 87% rename from crates/mega-evm/tests/rex5/keyless_replay_barrier.rs rename to crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs index fab84fa55..cc0dc2cce 100644 --- a/crates/mega-evm/tests/rex5/keyless_replay_barrier.rs +++ b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs @@ -201,51 +201,6 @@ fn test_keyless_signer_charge_implies_replay_barrier() { ); } -/// REX4 (stable spec) must preserve the historical bug-shape behavior on the same input: -/// outer call returns `Success` with errorData (not Revert), the signer IS fee-debited, -/// and no replay barrier is installed (signer nonce stays 0, deploy address has no code). -/// This test fails loudly if any future change leaks the REX5 sandbox-validate rejection -/// back into a stable spec. -#[test] -fn test_rex4_keyless_preserves_signer_charge_without_barrier() { - let mut db = MemoryDatabase::default(); - - let signer_starting_balance = U256::from(1_000_000_000_000_000_000_000u128); // 1000 ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, signer_starting_balance); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let contract_bucket = - ::bucket_id_for_account(CREATE2_FACTORY_CONTRACT); - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket, MIN_BUCKET_SIZE as u64 * 2); - - let gas_limit_override = 120_000; - - let result = run_keyless_outer( - MegaSpecId::REX4, - &mut db, - external_envs, - Bytes::from_static(CREATE2_FACTORY_TX), - gas_limit_override, - ); - - // Outer call surfaces as Success — the keyless interceptor returns success-with-error-data - // on inner failure under stable specs, so the relayer is not penalized. - assert!( - result.is_success(), - "REX4 keyless inner-fail path MUST keep returning outer Success; got {result:?}", - ); - // Signer IS charged for the full sandbox gas budget (the historical drain shape). - let signer_after = account_info(&mut db, CREATE2_FACTORY_DEPLOYER); - assert!( - signer_after.balance < signer_starting_balance, - "REX4: signer balance must be reduced (stable bug-shape preserved)", - ); - // No barrier installed: nonce stays at 0, deploy address has no code → still replayable. - assert_eq!(signer_after.nonce, 0, "REX4: signer nonce must stay replayable"); - assert!(!has_code(&mut db, CREATE2_FACTORY_CONTRACT), "REX4: deploy address must remain empty",); -} - // ============================================================================ // 2. Runtime-revert path: signer charge AND nonce bump (barrier consumed) // ============================================================================ diff --git a/crates/mega-evm/tests/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs similarity index 89% rename from crates/mega-evm/tests/rex5/main.rs rename to crates/mega-evm/tests/_pending/rex5/main.rs index f1e341aac..abf4efcd9 100644 --- a/crates/mega-evm/tests/rex5/main.rs +++ b/crates/mega-evm/tests/_pending/rex5/main.rs @@ -1,17 +1,14 @@ //! Tests for `Rex5` hardfork features. mod apply_pending_changes_gas_budget; -mod call_too_deep_guard; mod callcode_storage_gas; mod create2_empty_initcode; mod create2_resize_gas_metering; -mod create_atomicity; mod db_error; mod deposit_caller_accounting; mod deposit_create_storage_gas; mod eip7702_metering; mod eip7702_state_growth; -mod frame_target_updated_dedup; mod gas_validation; mod interceptor_selector_probe; mod keyless_deploy_dispatch_parity; diff --git a/crates/mega-evm/tests/rex5/oracle_hint_metering.rs b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs similarity index 89% rename from crates/mega-evm/tests/rex5/oracle_hint_metering.rs rename to crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs index 6e7451a1d..e64e732cd 100644 --- a/crates/mega-evm/tests/rex5/oracle_hint_metering.rs +++ b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs @@ -164,34 +164,6 @@ fn test_rex5_zero_gas_send_hint_does_not_forward() { assert!(hints.is_empty(), "zero-gas sendHint must not forward to on_hint (REX5)",); } -/// Pre-REX5 baseline: zero-gas sendHint still forwards. Pinned to guarantee replay -/// determinism on stable specs. -#[test] -fn test_rex4_zero_gas_send_hint_still_forwards() { - let code = build_send_hint_bytecode(TOPIC, 64, 0); - let (result, hints, _) = run_with_oracle(MegaSpecId::REX4, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "REX4 must keep the pre-REX5 unmetered, zero-gas-accepting path",); -} - -/// REX4 replay parity: a normal sendHint with a large payload under REX4 must NOT -/// be charged against `data_size_used`. This pins the pre-REX5 unmetered invariant — -/// if hint metering accidentally activated on stable specs, the data-size lane -/// would grow and replay of historical REX4 blocks would diverge. -#[test] -fn test_rex4_does_not_meter_send_hint_payload() { - let payload_size = 1024; - let code = build_send_hint_bytecode(TOPIC, payload_size, 100_000); - let (result, hints, data_size) = run_with_oracle(MegaSpecId::REX4, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "REX4 must still forward normal sendHints"); - assert!( - data_size < payload_size as u64, - "REX4 must NOT charge the {payload_size}-byte payload against data_size (got {})", - data_size, - ); -} - /// REX5 invariant 2: a normal sendHint with positive gas still forwards to `on_hint` /// (parity with the pre-REX5 happy path). #[test] @@ -389,37 +361,6 @@ fn test_rex5_trailing_junk_after_valid_send_hint_is_metered() { assert!(hints.is_empty(), "trailing junk must NOT forward when over budget"); } -/// The REX5 `input_bytes.len()` charge is strictly larger than the legacy -/// `data.len() + 32` formula. Verified by comparing REX5 (with metering) to REX4 -/// (no metering, baseline pinned by `test_rex4_does_not_meter_send_hint_payload`) -/// for a `sendHint(topic, empty data)` call: the encoded ABI envelope is -/// `selector(4) + topic(32) + data_offset(32) + data_length(32) = 100` bytes; the -/// legacy formula would have charged `0 + HINT_TOPIC_BYTES = 32` bytes. A regression -/// that restored the legacy `call.data.len() + 32` charge would shrink `extra` below -/// the legacy threshold. -#[test] -fn test_rex5_charge_is_strictly_more_conservative_than_legacy_formula() { - let code = build_send_hint_bytecode(TOPIC, 0, 100_000); // empty `data` - let (_, _, rex4) = run_with_oracle(MegaSpecId::REX4, code.clone(), u64::MAX); - let (_, _, rex5) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - - let new_charge: u64 = 100; // input_bytes.len() for sendHint(topic, empty) - let pre_fix_charge: u64 = 32; // legacy: data.len() + HINT_TOPIC_BYTES - - let extra = rex5 - .checked_sub(rex4) - .expect("REX5 must record at least as much data_size as REX4 for identical bytecode"); - assert!( - extra >= new_charge, - "REX5 must charge at least input_bytes.len()={new_charge} more than REX4 (got {extra})", - ); - assert!( - extra > pre_fix_charge, - "post-fix REX5 must charge strictly more than the legacy formula \ - (data.len()+32={pre_fix_charge}); got extra={extra}", - ); -} - /// REX5 invariant: consecutive `sendHint` calls in the same TX accumulate their /// `input_bytes.len()` charges into the TX `persistent_usage` lane. With a budget sized /// for one call but not two, the first sendHint must forward and the second must be diff --git a/crates/mega-evm/tests/rex5/pre_block_system_calls.rs b/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs similarity index 86% rename from crates/mega-evm/tests/rex5/pre_block_system_calls.rs rename to crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs index 2e7b1f1e7..bd52867ca 100644 --- a/crates/mega-evm/tests/rex5/pre_block_system_calls.rs +++ b/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs @@ -247,109 +247,6 @@ fn test_rex5_block_rejected_when_beacon_root_pre_block_call_halts() { ); } -/// Same heavy-SALT scenario under a Rex4 chain spec: pre-REX5 keeps its -/// existing accept-and-commit-empty behavior so historical replay is -/// byte-for-byte deterministic. -#[test] -fn test_pre_rex5_preserves_silent_pre_block_call_failure() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex4_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX4, BLOCK_GAS_LIMIT), - ); - - executor - .apply_pre_execution_changes() - .expect("pre-REX5 must accept a halted pre-block system call"); - - // The OOG'd SSTORE never wrote the parent hash to the ring-buffer slot the - // contract targets, `(block.number - 1) % 8191`. - let storage_after = executor - .evm_mut() - .db_mut() - .storage( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - U256::from((ACTIVATION_BLOCK - 1) % 8191), - ) - .unwrap(); - let parent_hash_word = U256::from_be_bytes(B256::from([0x29; 32]).0); - assert_ne!( - storage_after, parent_hash_word, - "history-storage slot 0 must not contain the parent hash; the SSTORE OOG'd", - ); -} - -/// The counterpart to `test_rex5_block_aware_budget_accepts_pre_block_call_above_30m`: on a -/// pre-REX5 chain the same ≈100M-per-SSTORE costs must still OOG, because pre-REX5 keeps -/// revm's upstream-fixed 30M budget for replay parity. The budget selection must follow the -/// `REX5` spec exactly — a gate at any earlier spec would run these historical blocks with -/// the block-aware budget and commit writes that mainnet history does not contain. The block -/// is still accepted (no fail-closed pre-REX5), but neither contract's slot may be written. -#[test] -fn test_pre_rex5_keeps_upstream_30m_budget_for_pre_block_calls() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(medium_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex4_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX4, BLOCK_GAS_LIMIT), - ); - - executor - .apply_pre_execution_changes() - .expect("pre-REX5 must accept the halted pre-block system calls"); - - // EIP-2935: the ≈100M SSTORE OOG'd inside the 30M budget, so the ring-buffer slot the - // contract writes the parent hash to — `(block.number - 1) % 8191` — must stay empty. - let history_slot = executor - .evm_mut() - .db_mut() - .storage( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - U256::from((ACTIVATION_BLOCK - 1) % 8191), - ) - .unwrap(); - assert_ne!( - history_slot, - U256::from_be_bytes(B256::from([0x29; 32]).0), - "EIP-2935 must stay on the 30M budget pre-REX5, so the ≈100M write cannot land", - ); - - // EIP-4788: same for the beacon-roots timestamp slot (the contract's ring buffer keys - // slots by `timestamp % 8191`). - let timestamp_slot = U256::from(1_800_000_000u64 % 8191); - let stored_timestamp = executor - .evm_mut() - .db_mut() - .storage(alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, timestamp_slot) - .unwrap(); - assert_ne!( - stored_timestamp, - U256::from(1_800_000_000u64), - "EIP-4788 must stay on the 30M budget pre-REX5, so the ≈100M writes cannot land", - ); -} - /// Medium SALT makes each EIP-2935 / EIP-4788 SSTORE cost ≈ 100M of /// dynamic storage gas — above revm's upstream-fixed 30M default but /// within the REX5 `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` diff --git a/crates/mega-evm/tests/rex5/precompile_compute_gas.rs b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs similarity index 57% rename from crates/mega-evm/tests/rex5/precompile_compute_gas.rs rename to crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs index a3cf42465..59a154f95 100644 --- a/crates/mega-evm/tests/rex5/precompile_compute_gas.rs +++ b/crates/mega-evm/tests/_pending/rex5/precompile_compute_gas.rs @@ -177,130 +177,6 @@ fn kzg_wrapper_bytecode(input: &[u8], forwarded_gas: u64) -> Bytes { // TESTS // ============================================================================ -/// A precompile CALL that fails with `PrecompileOOG` should record the full forwarded gas -/// as compute gas in REX5, but 0 in REX4. -/// -/// ecrecover (address 0x01) costs 3000 gas. Forwarding only 2999 gas triggers -/// `PrecompileOOG`. The parent permanently loses the 2999 gas (`is_ok_or_revert()` is -/// false -> no refund), but pre-REX5 specs record 0 compute gas because `spent()` = 0. -/// REX5 fixes this by recording `limit()` (= forwarded gas) on error paths. -#[test] -fn test_rex5_precompile_oog_records_forwarded_gas_as_compute_gas() { - // ecrecover requires 3000 gas. Forward only 2999 to trigger PrecompileOOG. - let forwarded_gas: u64 = 2_999; - - // Contract: store 128 bytes of input in memory (ecrecover expects 128 bytes), - // then CALL ecrecover with insufficient gas. - let code = BytecodeBuilder::default() - // Write 128 bytes of zeros at memory offset 0 (valid-length but invalid-content - // input for ecrecover, but irrelevant because it will OOG before processing). - .mstore(0, [0u8; 32]) - .mstore(32, [0u8; 32]) - .mstore(64, [0u8; 32]) - .mstore(96, [0u8; 32]) - // CALL ecrecover with 128-byte input but only 2999 gas - .push_number(32_u64) // retSize - .push_number(128_u64) // retOffset - .push_number(128_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ECRECOVER) - .push_number(forwarded_gas) // gas (< 3000, triggers OOG) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, compute_gas_rex5) = transact(MegaSpecId::REX5, &mut db, tx.clone()); - assert!( - result_rex5.result.is_success(), - "outer tx should succeed (precompile failure is caught by CALL)" - ); - - let (result_rex4, compute_gas_rex4) = transact(MegaSpecId::REX4, &mut db, tx); - assert!( - result_rex4.result.is_success(), - "outer tx should succeed (precompile failure is caught by CALL)" - ); - - // REX5 should record more compute gas because the failing precompile's forwarded gas - // is now counted. REX4 records 0 for the failing precompile path (spent() = 0). - assert!( - compute_gas_rex5 > compute_gas_rex4, - "REX5 compute gas ({compute_gas_rex5}) should be higher than REX4 ({compute_gas_rex4}) \ - due to PrecompileOOG compute gas accounting" - ); - - // The difference should be approximately the forwarded gas amount. - let diff = compute_gas_rex5 - compute_gas_rex4; - assert!( - diff >= forwarded_gas, - "compute gas difference ({diff}) should be at least the forwarded gas ({forwarded_gas})" - ); -} - -/// A precompile CALL that fails with `PrecompileError` (not OOG) should also record -/// the full forwarded gas as compute gas in REX5. -/// -/// Blake2f (0x09) requires exactly 213 bytes of input. Calling it with wrong-length -/// input triggers `PrecompileError::Other`, which is distinct from `PrecompileOOG`. -/// Both error types hit the same `!is_ok_or_revert()` branch, but this test guards -/// against future regressions that might split the handling. -#[test] -fn test_rex5_precompile_error_records_forwarded_gas_as_compute_gas() { - let forwarded_gas: u64 = 50_000; - - // Contract: CALL blake2f with 1 byte of input (wrong length → PrecompileError). - let code = BytecodeBuilder::default() - // Store 1 byte at memory[0] - .mstore(0, [0xffu8; 1]) - // CALL blake2f with 1-byte input - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(1_u64) // argsSize = 1 (invalid: blake2f requires 213) - .push_number(31_u64) // argsOffset (last byte of the 32-byte word) - .push_number(0_u64) // value - .push_address(BLAKE2F) - .push_number(forwarded_gas) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, compute_gas_rex5) = transact(MegaSpecId::REX5, &mut db, tx.clone()); - assert!(result_rex5.result.is_success(), "outer tx should succeed"); - - let (result_rex4, compute_gas_rex4) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result_rex4.result.is_success(), "outer tx should succeed"); - - // Same pattern as OOG test: REX5 records forwarded gas, REX4 records 0. - assert!( - compute_gas_rex5 > compute_gas_rex4, - "REX5 compute gas ({compute_gas_rex5}) should be higher than REX4 ({compute_gas_rex4}) \ - due to PrecompileError compute gas accounting" - ); - - let diff = compute_gas_rex5 - compute_gas_rex4; - assert!( - diff >= forwarded_gas, - "compute gas difference ({diff}) should be at least the forwarded gas ({forwarded_gas})" - ); -} - // ============================================================================ // KZG fixed-cost compute-gas accounting (REX5) // ============================================================================ @@ -397,84 +273,3 @@ fn test_rex5_kzg_invalid_input_length_records_exact_gas_cost() { on a wrong-length KZG call (REX5={compute_gas_rex5}, REX4={compute_gas_rex4})." ); } - -/// Cap-induced OOG: `tx_compute_gas_limit = KZG_GAS_COST - 1` so the REX5 cap -/// drives `effective_gas_limit < KZG_GAS_COST`. The wrapper's own -/// `gas_limit < GAS_COST` pre-check fires before verification runs; the -/// recorded compute-gas matches the cap, **not** `KZG_GAS_COST` — the -/// fixed-cost arm must not fire on this path. -#[test] -fn test_rex5_kzg_cap_induced_oog_still_records_capped_limit() { - // `forwarded_gas` is deliberately set well above KZG_GAS_COST. The wrapper - // contract pushes this onto the stack as the CALL opcode's `gas` argument, - // but it does NOT bound the precompile here — `tx_compute_gas_limit` does, - // via the REX5 cap inside `PrecompilesMap::run`. Setting `forwarded_gas` - // small enough to OOG on its own would exercise a different code path. - let forwarded_gas: u64 = 500_000; - let tx_compute_gas_limit = KZG_GAS_COST - 1; - let code = kzg_wrapper_bytecode(&valid_kzg_input(), forwarded_gas); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // The outer tx may halt (TX-level compute limit exceeded) — `transact_raw` - // returns `ResultAndState` either way. We only care about the compute-gas - // tracker's final value. - let (_, compute_gas) = - transact_with_compute_limit(MegaSpecId::REX5, &mut db, tx, Some(tx_compute_gas_limit)); - - // If the fixed-cost arm had fired, the precompile alone would contribute - // KZG_GAS_COST and total compute_gas would be >= KZG_GAS_COST. With the cap - // engaging at GAS_COST - 1 the precompile contribution is bounded by the cap. - assert!( - compute_gas < KZG_GAS_COST, - "cap-induced OOG must NOT take the fixed-cost arm (compute_gas={compute_gas}, \ - KZG_GAS_COST={KZG_GAS_COST}). If it had fired, the precompile contribution \ - alone would equal KZG_GAS_COST." - ); - // Total compute_gas is bounded by the TX-level cap (clamped at limit on overflow). - assert!( - compute_gas <= tx_compute_gas_limit, - "total compute_gas ({compute_gas}) must not exceed tx_compute_gas_limit \ - ({tx_compute_gas_limit})" - ); -} - -/// Stable-spec replay-preservation guard. REX4 keeps the KZG -/// verification-failure precompile contribution at 0 compute-gas; any change -/// to this would shift `tx_compute_gas_used` on historical REX4 blocks and -/// break byte-for-byte replay. -/// -/// Assertion strategy: this test cannot assert `compute_gas == 0` because the -/// wrapper contract's MSTORE / PUSH / CALL opcodes themselves consume some -/// compute-gas (~23k observed). The bound pinned here is "the precompile -/// contributes strictly less than `KZG_GAS_COST` on REX4". The differential -/// test `test_rex5_kzg_invalid_proof_records_exact_gas_cost` separately -/// asserts `REX5 - REX4 == KZG_GAS_COST`, which together with this bound pins -/// the per-spec contribution exactly. -#[test] -fn test_rex4_kzg_invalid_proof_keeps_zero_compute_gas() { - let forwarded_gas: u64 = 500_000; - let code = kzg_wrapper_bytecode(&invalid_proof_kzg_input(), forwarded_gas); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, compute_gas) = transact(MegaSpecId::REX4, &mut db, tx); - assert!(result.result.is_success(), "outer tx should succeed (KZG failure caught by CALL)"); - assert!( - compute_gas < KZG_GAS_COST, - "REX4 precompile contribution must remain 0. Total compute_gas \ - ({compute_gas}) >= KZG_GAS_COST ({KZG_GAS_COST}) indicates the precompile \ - alone contributed KZG_GAS_COST — a replay-determinism regression where the \ - REX5 fixed-cost arm silently activated on REX4." - ); -} diff --git a/crates/mega-evm/tests/rex5/sandbox_accounting.rs b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs similarity index 57% rename from crates/mega-evm/tests/rex5/sandbox_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs index 584454505..d9e13f7cd 100644 --- a/crates/mega-evm/tests/rex5/sandbox_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs @@ -391,27 +391,6 @@ fn test_rex5_sandbox_success_propagates_resource_usage() { assert!(usage.state_growth > 0, "state growth should include new account from sandbox"); } -/// REX4 sandbox does NOT propagate resource usage to the parent transaction. -/// -/// The same constructor that works in REX5 should have zero state growth in REX4 -/// because sandbox usage is not propagated. -#[test] -fn test_rex4_sandbox_does_not_propagate_resource_usage() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(minimal_1byte_constructor(42)); - let mut db = funded_signer_db(signer); - - let (result, usage) = - execute_keyless_deploy(MegaSpecId::REX4, &mut db, tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - assert!(result.is_success(), "keyless deploy should succeed: {result:?}"); - - // The sandbox's storage writes should NOT appear in parent usage in REX4. - assert_eq!( - usage.state_growth, 0, - "REX4 should not propagate sandbox state growth, got: {}", - usage.state_growth - ); -} - /// Executes a keyless deploy with custom runtime limits, returning the full `ResultAndState`. fn execute_keyless_deploy_with_limits( spec: MegaSpecId, @@ -466,507 +445,6 @@ fn assert_preflight_failure_without_sandbox_state( error } -/// REX5 must fail the sandbox internally when the parent's remaining state-growth budget is -/// smaller than the sandbox's required state growth. -/// -/// Regression test for the upfront-cap design: tightening the parent state-growth limit -/// should now make the sandbox fail internally, returning success-style `errorData` -/// instead of letting the sandbox succeed and halting the outer transaction afterwards. -#[test] -fn test_rex5_sandbox_tight_state_growth_budget_fails_inside_sandbox() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(42)); - assert!(baseline_usage.state_growth > 0, "baseline deploy should consume state growth"); - - // Give the parent slightly less state growth than the successful sandbox needs. - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_state_growth_limit(baseline_usage.state_growth.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // The outer transaction should still return successfully with encoded execution failure. - assert!( - result_and_state.result.is_success(), - "outer transaction should return success-style failure, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - - // The deployed contract must NOT exist in the finalized state. - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract code must not survive sandbox-internal limit failure"); -} - -/// REX5: when `record_deposit_caller_creation` (inside -/// `charge_caller_materialization_pre_sandbox`) latches a non-frame-local -/// `StateGrowthLimitExceeded`, the keyless-deploy interceptor MUST emit the canonical -/// exceeding-limit OOG halt — with parent gas rescued — at the latch point. -/// -/// If the conversion is deferred, `before_frame_return_result::` still rewrites the -/// final Revert into a Halt at tx end, but its docstring's "gas should already have been -/// rescued at the point where the limit was exceeded" precondition is violated: -/// `after_frame_run`'s `try_rescue_gas` does not run on the interceptor short-circuit -/// path, so the parent loses its entire outer gas budget. -/// -/// The deploy address is pre-occupied with code so a deferred halt is observable: the -/// flow would reach the `ContractAlreadyExists` check and surface -/// `Revert(ContractAlreadyExists())` instead of the canonical state-growth Halt — which -/// the halt-vs-Revert assertion below distinguishes. -#[test] -fn test_rex5_pre_sandbox_materialization_state_growth_overflow_halts_immediately() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - // Signer must be empty (no balance, no nonce, no code) to enter the materialization - // branch — `AccountInfo::is_empty()` is the gate. Funding it would short-circuit the - // branch before the state-growth latch could fire. - let mut db = MemoryDatabase::default(); - // Pre-occupy the deploy address. The state-growth halt MUST fire before the - // `ContractAlreadyExists` check; if it ever fires later, the check surfaces - // `Revert(ContractAlreadyExists())` and the assertions below catch the regression. - let preexisting_code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - db.set_account_code(deploy_address, preexisting_code.clone()); - - // `tx_state_growth_limit = 0` so the materialization-side `+1` immediately overflows - // the TX-level state-growth budget on `record_deposit_caller_creation`. - let tx_limits = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0); - - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Must be a canonical exceeding-limit Halt, NOT a business-error Revert. - let halt_reason = match &result_and_state.result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - ExecutionResult::Revert { output, .. } => { - let err = decode_error_result(output); - panic!( - "state-growth overflow must produce a canonical Halt, not a business \ - Revert; got Revert with selector {err:?}", - ); - } - other => panic!("expected Halt, got {other:?}"), - }; - assert!( - matches!(halt_reason, MegaHaltReason::StateGrowthLimitExceeded { limit: 0, actual: 1 }), - "halt reason must be the canonical StateGrowthLimitExceeded {{ limit: 0, actual: 1 }}, \ - got {halt_reason:?}", - ); - - // Signer never bumped — the sandbox was never constructed. - let signer_nonce = result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!(signer_nonce, 0, "signer nonce must remain 0 when halt fires pre-sandbox"); - - // Deploy address's pre-existing code is untouched. - if let Some(acc) = result_and_state.state.get(&deploy_address) { - if let Some(code) = &acc.info.code { - assert_eq!( - code.bytes_slice(), - preexisting_code.as_ref(), - "pre-existing deploy-address code must not be overwritten", - ); - } - } - - // Gas was rescued — the unspent outer budget is returned to the sender; only the - // dispatch overhead, materialization charge, and tx intrinsic are reported as used. - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); -} - -/// REX5 preflights sandbox intrinsic compute gas before starting sandbox execution. -/// -/// If the parent's remaining compute budget cannot fit the sandbox transaction's intrinsic -/// compute gas, the sandbox must not start and signer state must not be merged. -#[test] -fn test_rex5_sandbox_intrinsic_compute_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_compute = intrinsic_compute_gas(&outer_tx); - let sandbox_intrinsic_compute = intrinsic_compute_gas(&sandbox_tx); - assert!(sandbox_intrinsic_compute > 0, "sandbox tx should have intrinsic compute gas"); - - // Parent limit = outer_intrinsic + overhead + sandbox_intrinsic - 1. Just below what - // the sandbox's own intrinsic recording would consume; preflight must reject. - let tx_limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit( - outer_intrinsic_compute + - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + - sandbox_intrinsic_compute - - 1, - ); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); -} - -/// REX5 preflights sandbox intrinsic data size before starting sandbox execution. -/// -/// This covers the `before_tx_start()` path where the sandbox tracker records base tx size, -/// input bytes, and caller account update as tx-level persistent usage. -#[test] -fn test_rex5_sandbox_intrinsic_data_size_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(7); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_data_size = intrinsic_data_size(&outer_tx); - let sandbox_intrinsic_data_size = intrinsic_data_size(&sandbox_tx); - assert!(sandbox_intrinsic_data_size > 0, "sandbox tx should have intrinsic data size"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(outer_intrinsic_data_size + sandbox_intrinsic_data_size - 1); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); -} - -/// REX5 preflights sandbox intrinsic KV updates before starting sandbox execution. -/// -/// This covers the `before_tx_start()` path where the sandbox tracker records the -/// sandbox caller account update as TX-level persistent usage. -#[test] -fn test_rex5_sandbox_intrinsic_kv_update_preflight_fails_without_sandbox() { - let init_code = minimal_1byte_constructor(7); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code.clone()); - let deploy_address = calculate_keyless_deploy_address(signer); - - let outer_tx = keyless_deploy_call_tx(tx_bytes.clone(), LARGE_GAS_LIMIT_OVERRIDE); - let sandbox_tx = sandbox_create_tx_for_intrinsic(init_code, signer); - let outer_intrinsic_kv_updates = intrinsic_kv_updates(&outer_tx); - let sandbox_intrinsic_kv_updates = intrinsic_kv_updates(&sandbox_tx); - assert!(sandbox_intrinsic_kv_updates > 0, "sandbox tx should have intrinsic KV updates"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_updates_limit(outer_intrinsic_kv_updates + sandbox_intrinsic_kv_updates - 1); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - let error = - assert_preflight_failure_without_sandbox_state(&result_and_state, deploy_address, signer); - assert!( - matches!(error, KeylessDeployError::ParentBudgetExceeded { kind: LimitKind::KVUpdate, .. }), - "KV preflight should reject with ParentBudgetExceeded(KVUpdate), got: {error:?}" - ); -} - -/// REX5 must fail the sandbox internally when the parent's remaining KV-update budget is -/// smaller than the sandbox's required KV updates. -/// -/// This covers execution-time KV updates after intrinsic preflight has passed, so the -/// sandbox should return a success-style failure and must not deploy the contract. -#[test] -fn test_rex5_sandbox_tight_kv_update_budget_fails_inside_sandbox() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.kv_updates > 0, "baseline deploy should consume KV updates"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_kv_updates_limit(baseline_usage.kv_updates.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert!( - result_and_state.result.is_success(), - "outer transaction should return success-style failure, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract code must not survive sandbox KV limit failure"); -} - -/// REX5 must reject the outer transaction cleanly when a sandbox TX-level overflow on the -/// compute-gas dimension pushes the parent over its limit. -/// -/// The safety net in `merge_and_reject_if_overflow` detects post-merge overflow, refuses to -/// merge sandbox state (preventing the deployed contract from surviving via the unchecked -/// direct journal write), absorbs the sandbox's EVM gas via `record_cost` on the outer -/// caller, and rescues the remaining gas. Without this safety net the outer caller would -/// be seized the full parent gas AND the deployed contract would persist on a "halt" tx. -#[test] -fn test_rex5_sandbox_compute_gas_overflow_rejects_cleanly() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(42)); - assert!(baseline_usage.compute_gas > 0, "baseline deploy should consume compute gas"); - - // Tighten parent's compute gas limit just below what the full deploy needs so the - // sandbox's merged usage overshoots parent's remaining envelope by a single opcode. - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(baseline_usage.compute_gas.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Outer tx must halt — the parent's compute budget does not fit the sandbox. - assert!( - result_and_state.result.is_halt(), - "outer transaction should halt on sandbox compute gas overflow, got: {:?}", - result_and_state.result, - ); - - // The halt must NOT consume the full parent tx gas: the safety net rescues remaining - // gas and only charges the caller for the KeylessDeploy overhead plus sandbox gas. - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); - - // Deployed contract must NOT survive — the safety net skipped `apply_sandbox_state`. - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract must not survive outer reject"); - - // Signer state must NOT be modified — sandbox state was never merged. - let signer_nonce = result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!( - signer_nonce, 0, - "signer nonce must not be bumped on sandbox overflow reject, got: {signer_nonce}" - ); -} - -/// REX5 must reject cleanly when a sandbox TX-level data-size overflow — either intrinsic -/// or opcode-level — pushes the parent over its limit. -/// -/// The sandbox's `DataSizeTracker::before_tx_start` records the base transaction size, -/// the input length, and the caller account update as non-discardable TX-level usage. -/// Even if the frame-local check would normally revert a sandbox frame on data-size -/// exceed, TX-level overflow (when persistent usage alone is above cap) takes the -/// non-frame-local path and must be rejected by the safety net. -#[test] -fn test_rex5_sandbox_data_size_overflow_rejects_cleanly() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.data_size > 0, "baseline deploy should consume data size"); - - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(baseline_usage.data_size.saturating_sub(1)); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - // Either outer halts (TX-level overflow path) or outer returns a success-style failure - // (frame-local revert path inside sandbox). Both are acceptable, but in the halt case - // the safety net must have rescued gas and prevented state survival. - if result_and_state.result.is_halt() { - assert!( - result_and_state.result.gas_used() < OUTER_TX_GAS_LIMIT / 2, - "outer caller must be rescued; gas_used={} should be well below tx limit {}", - result_and_state.result.gas_used(), - OUTER_TX_GAS_LIMIT, - ); - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract must not survive outer reject"); - let signer_nonce = - result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!( - signer_nonce, 0, - "signer nonce must not be bumped on sandbox overflow reject, got: {signer_nonce}" - ); - } else { - // Frame-local revert path: sandbox failed internally, returned errorData. - assert!( - result_and_state.result.is_success(), - "outer transaction should be success-style failure if not halted, got: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "internal sandbox failure should not deploy" - ); - assert!(!decoded.errorData.is_empty(), "failure path should return encoded error data"); - } -} - -/// REX5 should succeed when the parent's remaining compute-gas budget exactly matches the -/// sandbox's baseline compute usage. -/// -/// Companion to the state-growth exact-fit boundary test: covers compute gas, the other -/// dimension where overshoot from a single opcode would break the cap invariant. -#[test] -fn test_rex5_sandbox_exact_remaining_compute_gas_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.compute_gas > 0, "baseline deploy should consume compute gas"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(baseline_usage.compute_gas); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should succeed when the parent's remaining data-size budget exactly matches the -/// sandbox's baseline data-size usage. -#[test] -fn test_rex5_sandbox_exact_remaining_data_size_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.data_size > 0, "baseline deploy should consume data size"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(baseline_usage.data_size); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should succeed when the parent's remaining KV-update budget exactly matches the -/// sandbox's baseline KV usage. -#[test] -fn test_rex5_sandbox_exact_remaining_kv_updates_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(7)); - assert!(baseline_usage.kv_updates > 0, "baseline deploy should consume KV updates"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(baseline_usage.kv_updates); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - -/// REX5 should still succeed when the parent's remaining state-growth budget exactly matches -/// the sandbox's required state growth. -/// -/// This boundary test guards the capped-limit math: the sandbox should be allowed to -/// consume the full remaining budget, and merging its usage back must not make the outer -/// transaction fail afterwards. -#[test] -fn test_rex5_sandbox_exact_remaining_budget_succeeds() { - let (tx_bytes, signer, deploy_address, baseline_usage) = - rex5_baseline(minimal_1byte_constructor(99)); - assert!(baseline_usage.state_growth > 0, "baseline deploy should consume state growth"); - - let tx_limits = - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(baseline_usage.state_growth); - - let mut db = funded_signer_db(signer); - let result_and_state = execute_keyless_deploy_with_limits( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - tx_limits, - ); - - assert_exact_fit_success(&result_and_state, deploy_address); -} - /// Shared assertion: the outer tx succeeds, returns the expected deploy address with /// empty `errorData`, and the deployed bytecode survives in the finalized state. /// Used by both exact-remaining-budget boundary tests. @@ -1157,33 +635,6 @@ fn test_rex5_sandbox_outer_gas_used_includes_sandbox_gas_used_on_success() { ); } -/// REX4 parity: outer `gas_used` does NOT include `sandbox_gas_used`. Replay -/// determinism — pre-REX5 behavior must be preserved byte-for-byte. -#[test] -fn test_rex4_sandbox_outer_gas_used_excludes_sandbox_gas_used() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - let (result, _usage, _volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX4, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - let outer_gas_used = result.gas_used(); - let decoded = decode_keyless_deploy_return(&result); - let sandbox_gas_used = decoded.gasUsed; - - assert!( - outer_gas_used < constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + sandbox_gas_used, - "REX4: outer gas_used ({}) must NOT include sandbox gas_used ({}); only \ - dispatch overhead ({}) plus relayer-frame ops should be charged", - outer_gas_used, - sandbox_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - /// REX5 sandbox: on in-sandbox failure (`EmptyCodeDeployed` via STOP-only /// constructor), the outer `gas_used` must still include `sandbox_gas_used`. #[test] diff --git a/crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs similarity index 93% rename from crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs rename to crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs index a9cca7fd5..e45281c84 100644 --- a/crates/mega-evm/tests/rex5/selfdestruct_beneficiary.rs +++ b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs @@ -97,40 +97,6 @@ fn test_rex5_selfdestruct_to_empty_beneficiary_records_state_growth() { ); } -/// SELFDESTRUCT to an empty beneficiary should NOT record additional metering in REX4. -/// -/// REX4 does not have the SELFDESTRUCT beneficiary metering hook. The baseline usage -/// from REX4 should be lower than REX5 for the same scenario. -#[test] -fn test_rex4_selfdestruct_to_empty_beneficiary_comparison() { - let code = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code.clone()) - .account_balance(CONTRACT, U256::from(1_000_000u64)) - }; - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result_rex5, usage_rex5) = transact(MegaSpecId::REX5, &mut build_db(), tx.clone()); - assert!(result_rex5.result.is_success(), "REX5 should succeed: {result_rex5:?}"); - - let (result_rex4, usage_rex4) = transact(MegaSpecId::REX4, &mut build_db(), tx); - assert!(result_rex4.result.is_success(), "REX4 should succeed: {result_rex4:?}"); - - // REX5 should have higher state growth due to beneficiary metering. - assert!( - usage_rex5.state_growth > usage_rex4.state_growth, - "REX5 state growth ({}) should be higher than REX4 ({}) due to beneficiary metering", - usage_rex5.state_growth, - usage_rex4.state_growth - ); -} - /// SELFDESTRUCT with zero balance should NOT charge new-account fees. /// /// When a contract has zero balance and selfdestructs to an empty address, diff --git a/crates/mega-evm/tests/rex5/sstore_storage_gas_error.rs b/crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs similarity index 100% rename from crates/mega-evm/tests/rex5/sstore_storage_gas_error.rs rename to crates/mega-evm/tests/_pending/rex5/sstore_storage_gas_error.rs diff --git a/crates/mega-evm/tests/rex5/stipend_accounting.rs b/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs similarity index 60% rename from crates/mega-evm/tests/rex5/stipend_accounting.rs rename to crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs index 1d8894235..0fe4872f0 100644 --- a/crates/mega-evm/tests/rex5/stipend_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs @@ -360,104 +360,6 @@ fn build_keccak256_leaky_receiver() -> Bytes { // Parent compute-gas attribution: +CALL_STIPEND delta on value-transfer CALL // ============================================================================ -/// REX5 records `CALL_STIPEND` (2,300) of additional parent compute-gas per -/// value-transferring `CALL`. REX4 under-counts by exactly that amount. -#[test] -fn test_call_value_transfer_parent_compute_gas_delta_rex5_vs_rex4() { - let sender_code = build_zero_gas_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "REX5 must record exactly +CALL_STIPEND (2,300) more parent compute-gas \ - than REX4 for a single value-transferring CALL" - ); -} - -/// Same invariant for `CALLCODE`. -#[test] -fn test_callcode_value_transfer_parent_compute_gas_delta_rex5_vs_rex4() { - let sender_code = build_zero_gas_callcode_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "REX5 must record exactly +CALL_STIPEND (2,300) more parent compute-gas \ - than REX4 for a single value-transferring CALLCODE" - ); -} - -/// DELEGATECALL receives no `CALL_STIPEND` from revm, so the fix must not -/// adjust its parent compute-gas attribution. REX4 and REX5 must record -/// identical parent compute-gas for a DELEGATECALL. -#[test] -fn test_delegatecall_parent_compute_gas_parity_across_specs() { - let sender_code = build_delegatecall_contract(RECEIVER, 100_000); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, rex4_compute, - "DELEGATECALL has no CALL_STIPEND; REX4 and REX5 must record identical \ - parent compute-gas" - ); -} - -/// STATICCALL receives no `CALL_STIPEND` from revm (no value transfer -/// semantics). Same parity guard as DELEGATECALL. -#[test] -fn test_staticcall_parent_compute_gas_parity_across_specs() { - let sender_code = build_staticcall_contract(RECEIVER, 100_000); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - assert!(matches!(rex4_result, ExecutionResult::Success { .. })); - assert!(matches!(rex5_result, ExecutionResult::Success { .. })); - assert_eq!( - rex5_compute, rex4_compute, - "STATICCALL has no CALL_STIPEND; REX4 and REX5 must record identical \ - parent compute-gas" - ); -} - // ============================================================================ // Storage allowance coverage per charging site // ============================================================================ @@ -484,131 +386,6 @@ fn test_log1_value_transfer_succeeds_at_zero_gas_rex5() { } } -/// First-time-write SSTORE inside `receive()` succeeds on REX5 when forwarded gas -/// covers the standard EIP-2200 cost. The 20,000 Mega `sstore_set_storage_gas` -/// surcharge drains from the 23,000 allowance. -#[test] -fn test_sstore_in_receive_succeeds_at_minimum_envelope_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 22_500); - let receiver_code = build_sstore_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: first-time SSTORE in receive() must succeed when forwarded gas \ - covers standard EIP-2200 cost; Mega surcharge drains from allowance" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the SSTORE-in-receive fixture: same forwarded amount must -/// succeed via legacy `gas.limit()` inflation. -#[test] -fn test_sstore_in_receive_succeeds_at_minimum_envelope_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 22_500); - let receiver_code = build_sstore_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX4: same fixture must succeed via legacy inflation" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// SELFDESTRUCT to an empty beneficiary inside `receive()` succeeds on REX5 when -/// forwarded gas covers the standard EVM cost plus the residual portion of the -/// Mega new-account surcharge (25,000 − 23,000 = 2,000 at multiplier=2). The -/// allowance covers 23,000 of the surcharge; the residual comes from forwarded gas. -#[test] -fn test_selfdestruct_in_receive_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 50_000); - let receiver_code = build_selfdestruct_receiver(FRESH_TARGET); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: SELFDESTRUCT to empty beneficiary must succeed; allowance \ - drains the Mega surcharge" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the SELFDESTRUCT-in-receive fixture. -#[test] -fn test_selfdestruct_in_receive_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 50_000); - let receiver_code = build_selfdestruct_receiver(FRESH_TARGET); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// Nested value-transfer CALL B → C where C is empty exercises the -/// `wrap_call_with_storage_gas!` drain site. B's allowance covers 23,000 of the -/// 25,000 new-account surcharge; C receives its own fresh allowance because B → C -/// is itself a value-transfer CALL. Forwarded gas covers the residual + standard -/// CALL EVM costs. -#[test] -fn test_nested_call_to_empty_account_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_nested_value_call_receiver(FRESH_TARGET, 50_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: nested value-transfer CALL to fresh empty target must succeed; \ - each frame gets its own allowance" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for the nested CALL-to-empty fixture. -#[test] -fn test_nested_call_to_empty_account_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_nested_value_call_receiver(FRESH_TARGET, 50_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - // ============================================================================ // Compute-leak isolation: stipend cannot fund compute-only opcodes // ============================================================================ @@ -674,93 +451,10 @@ fn test_storage_stipend_unused_portion_does_not_inflate_caller_gas_rex5() { ); } -/// CREATE2 inside a value-transferring child's `receive()` exercises the -/// `storage_gas_ext::create` drain site. With generous forwarded gas, both specs -/// succeed: REX5 drains 23,000 of the 32,000 `create_contract_storage_gas` -/// (multiplier=2) from the allowance; REX4 covers it via legacy inflation. -#[test] -fn test_create2_in_receive_succeeds_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_create2_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: CREATE2 inside stipend-receiving frame must succeed" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// REX4 parity for CREATE2-in-receive. -#[test] -fn test_create2_in_receive_succeeds_rex4_parity() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 200_000); - let receiver_code = build_create2_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!(inner_call_success_flag(output.data()), U256::from(1), "REX4 parity guard"); - } - other => panic!("expected Success, got {other:?}"), - } -} - // ============================================================================ // Negative controls // ============================================================================ -/// Stipend (REX5 allowance or REX4 inflated gas) bridges at most its 23,000 -/// portion. A child forwarded gas below the standard EVM opcode cost must fail -/// the inner CALL on both specs. Fixture: SSTORE receiver with 5,000 forwarded -/// gas (well below the 22,100 EIP-2200 cost). -#[test] -fn test_sstore_underforward_fails_on_both_specs() { - // Forward only 5,000 EVM gas — far below the 22,100 standard SSTORE cost. - // Effective gas = 5,000 + CALL_STIPEND = 7,300, still well below the - // standard SSTORE cost — child must OOG on both specs regardless of stipend. - let sender_code = build_value_transfer_with_gas(RECEIVER, 5_000); - let receiver_code = build_sstore_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex5_db = setup_db(&contracts); - let rex5_result = transact(MegaSpecId::REX5, &mut rex5_db, default_tx()).unwrap(); - let mut rex4_db = setup_db(&contracts); - let rex4_result = transact(MegaSpecId::REX4, &mut rex4_db, default_tx()).unwrap(); - - // Both specs return successfully at the OUTER tx level (the parent's CALL - // returns failure but the parent contract itself returns the flag = 0). - // What we assert: the INNER CALL flag is 0 on both specs. - match &rex5_result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX5: under-forwarded SSTORE child must fail" - ); - } - other => panic!("REX5: expected outer Success, got {other:?}"), - } - match &rex4_result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX4: under-forwarded SSTORE child must fail — stipend can't bridge \ - beyond its 23,000 size" - ); - } - other => panic!("REX4: expected outer Success, got {other:?}"), - } -} - // ============================================================================ // Synthetic interceptor frame stack alignment // ============================================================================ @@ -784,19 +478,6 @@ fn test_intercepted_value_call_stack_alignment_rex5() { ); } -/// REX4 parity for the synthetic interceptor stack alignment. -#[test] -fn test_intercepted_value_call_stack_alignment_rex4_parity() { - let sender_code = build_intercepted_value_call(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - assert!( - matches!(result.result, ExecutionResult::Success { .. } | ExecutionResult::Revert { .. }), - "REX4 parity guard" - ); -} - /// The stipend is granted only to internal (depth > 0) value-transferring /// CALL/CALLCODE. A top-level value-transfer transaction must NOT receive /// the stipend on either spec; LOG1 in the receiver should fail under both @@ -825,43 +506,6 @@ fn test_top_level_value_transfer_does_not_get_stipend_rex5() { // TX-level rescue + revert path inside a stipend-receiving child // ============================================================================ -/// Value-transferring child enters with a stipend allowance, accesses TIMESTAMP -/// to trigger volatile-data detention, then burns compute past the detained -/// `tx_compute_gas_limit`. REX5's `rescue_gas` returns `gas.remaining()` directly -/// (the allowance never bled into `gas.limit()`), so the rescue path produces a -/// bounded refund without panic; the halt is `VolatileDataAccessOutOfGas` and -/// `gas_used` reflects the rescued gas (far below the forwarded child-frame gas). -#[test] -fn test_stipend_receiving_child_tx_level_rescue_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 100_000); - let receiver_code = build_timestamp_detention_receiver(20_000); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(1_000_000) - .with_block_env_access_compute_gas_limit(10_000); - let result = transact_with_limits(MegaSpecId::REX5, &mut db, default_tx(), limits).unwrap(); - - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::VolatileDataAccessOutOfGas { limit, .. }, - gas_used, - } => { - assert!( - *limit <= 1_000_000, - "detained limit should stay within the tx compute gas limit, got {limit}" - ); - assert!( - *gas_used < 200_000, - "REX5 rescue_gas must refund excess gas — gas_used {gas_used} indicates no \ - refund occurred. Allowance must NOT inflate the rescued amount; it never \ - entered gas.limit() on REX5" - ); - } - other => panic!("expected VolatileDataAccessOutOfGas, got {other:?}"), - } -} - /// Stipend-receiving child drains its allowance via SSTORE then REVERTs. The /// drained allowance is consumed — it does not refund across the revert. Outer /// tx succeeds, inner CALL flag is 0, SSTORE state is rolled back, and the diff --git a/crates/mega-evm/tests/rex5/system_tx_replay.rs b/crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs similarity index 100% rename from crates/mega-evm/tests/rex5/system_tx_replay.rs rename to crates/mega-evm/tests/_pending/rex5/system_tx_replay.rs diff --git a/crates/mega-evm/tests/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs similarity index 91% rename from crates/mega-evm/tests/rex6/beneficiary_detention.rs rename to crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs index e6b4fbc26..4b448da87 100644 --- a/crates/mega-evm/tests/rex6/beneficiary_detention.rs +++ b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs @@ -204,34 +204,6 @@ fn test_rex6_selfdestruct_source_eq_beneficiary_disabled_reverts() { assert_eq!(usage.state_growth, 0, "no on_selfdestruct_new_account: {}", usage.state_growth); } -/// REX5 baseline for the source-side case above. Same code and setup; REX5's outer wrapper -/// checks only the stack target, so a source-side SELFDESTRUCT to a non-beneficiary target -/// succeeds. Freeze-guards the pre-REX6 behavior. -#[test] -fn test_rex5_selfdestruct_source_eq_beneficiary_disabled_does_not_revert() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(EMPTY_NON_BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - assert!( - result.result.is_success(), - "REX5 must NOT revert the SELFDESTRUCT — the source-side check is REX6-only; got: {result:?}", - ); -} - /// REX6: SELFDESTRUCT with the stack target == beneficiary, volatile disabled. /// Same target-side case that REX5 already covers: the REX6 wrapper must still /// revert here. The source-side check is additive, and the target-side check is @@ -313,40 +285,6 @@ fn test_rex6_call_to_eip7702_delegator_to_beneficiary_disabled_reverts() { ); } -/// REX5 baseline: same setup, but REX5's wrapper compares the raw stack -/// operand (DELEGATOR != BENEFICIARY), so no revert. The CALL succeeds and the -/// delegate's STOP runs. -#[test] -fn test_rex5_call_to_eip7702_delegator_to_beneficiary_disabled_does_not_revert() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(DELEGATOR_TO_BENEFICIARY) - .push_number(100_000_u64) - .append(CALL) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code) - .account_code(BENEFICIARY, beneficiary_code); - set_eip7702_delegation(&mut db, DELEGATOR_TO_BENEFICIARY, BENEFICIARY); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - assert!( - result.result.is_success(), - "REX5 wrapper must NOT revert — compares raw stack operand only: {result:?}", - ); -} - /// REX6: A CALL to an EIP-7702 delegator pointing at the beneficiary, with /// volatile access enabled, must engage beneficiary detention via /// `MegaContext::load_account_delegated`'s resolved-delegate mark. @@ -481,34 +419,6 @@ fn test_rex6_selfdestruct_to_empty_target_still_records_state_growth() { // SELFDESTRUCT target-side freeze, enabled-path detention, self-target, DB-error // ============================================================================ -/// REX5 must still revert SELFDESTRUCT when the stack target is the beneficiary under disabled -/// volatile access: the target-side guard is spec-independent, only the source-side guard is -/// REX6-only. Mirrors `test_rex6_selfdestruct_target_eq_beneficiary_disabled_still_reverts`. -#[test] -fn test_rex5_selfdestruct_target_eq_beneficiary_disabled_still_reverts() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX5, &mut db, tx).unwrap(); - let output = result.result.output().expect("REX5 must still revert on target==beneficiary"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "REX5 target-side revert must be preserved by the hand-written wrapper: {output:?}", - ); -} - /// With volatile access enabled, a SELFDESTRUCT whose source is the beneficiary engages detention /// purely via the entry mark: reaching beneficiary-as-executor requires entering its frame (here /// the tx recipient is the beneficiary, so `on_new_tx` eagerly marks the beneficiary balance), so diff --git a/crates/mega-evm/tests/rex6/common.rs b/crates/mega-evm/tests/_pending/rex6/common.rs similarity index 100% rename from crates/mega-evm/tests/rex6/common.rs rename to crates/mega-evm/tests/_pending/rex6/common.rs diff --git a/crates/mega-evm/tests/rex6/create2_metering_order.rs b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs similarity index 79% rename from crates/mega-evm/tests/rex6/create2_metering_order.rs rename to crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs index 4f815d543..f411f4d41 100644 --- a/crates/mega-evm/tests/rex6/create2_metering_order.rs +++ b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs @@ -171,29 +171,6 @@ fn db_with(code: Bytes) -> MemoryDatabase { .account_code(CONTRACT, code) } -#[test] -fn test_create2_happy_path_compute_gas_identical_rex5_rex6() { - let r5 = transact_default(MegaSpecId::REX5, db_with(build_create2_contract())); - let r6 = transact_default(MegaSpecId::REX6, db_with(build_create2_contract())); - - assert!(r5.is_success(), "REX5 CREATE2 happy path must succeed; got {:?}", r5.result); - assert!(r6.is_success(), "REX6 CREATE2 happy path must succeed; got {:?}", r6.result); - - // The REX6 single recording (resize + inner, taken once after the body) equals the REX5 eager - // resize record + inner record exactly — no double count, no miss count. - assert_eq!( - r5.compute_gas, r6.compute_gas, - "CREATE2 happy-path compute_gas must be identical; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - // The EVM-gas operations are byte-identical across the two orders. - assert_eq!( - r5.gas_used, r6.gas_used, - "CREATE2 happy-path gas_used must be identical; REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - #[test] fn test_create2_missing_salt_consistent_rex5_rex6() { // Three CREATE2 operands, salt OMITTED: the wrapper's `stack.inspect::<3>()` fails, halting @@ -225,93 +202,6 @@ fn test_create2_missing_salt_consistent_rex5_rex6() { ); } -#[test] -fn test_create2_compute_limit_divergence_rex5_rex6() { - // Measure the compute-gas usage accumulated before the CREATE2 opcode (TX intrinsic + the four - // operand pushes), then place the limit just above it — inside the memory-expansion window. - let usage_before_create2 = - transact_default(MegaSpecId::REX6, db_with(build_pushes_only_contract())).compute_gas; - let compute_limit = usage_before_create2 + 100; - - let limits = - |spec| EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - - let r5 = - transact(MegaSpecId::REX5, db_with(build_create2_contract()), limits(MegaSpecId::REX5)); - let r6 = - transact(MegaSpecId::REX6, db_with(build_create2_contract()), limits(MegaSpecId::REX6)); - - // Both transactions exceed the compute-gas limit and fail. - assert!(!r5.is_success(), "REX5 must fail under the tight compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must fail under the tight compute limit; got {:?}", r6.result); - - // REX5 halts at the eager resize record, before the inner CREATE2 executes: its reading covers - // only the memory-expansion gas on top of the pre-CREATE2 usage. - assert!( - r5.compute_gas < usage_before_create2 + 15_000, - "REX5 should halt at the eager resize record (memory-expansion only); \ - usage_before={usage_before_create2}, got {}", - r5.compute_gas - ); - // REX6 defers recording until after the inner CREATE2 has executed, so it additionally records - // the inner opcode's compute gas (CREATE2 base cost 32,000 + initcode word cost) before the - // limit check fires. - assert!( - r6.compute_gas > usage_before_create2 + 30_000, - "REX6 should record the inner CREATE2 compute gas before the limit fires; \ - usage_before={usage_before_create2}, got {}", - r6.compute_gas - ); - assert!( - r6.compute_gas > r5.compute_gas, - "REX6 records strictly more compute gas than REX5 under the tight limit; \ - REX5={} REX6={}", - r5.compute_gas, - r6.compute_gas - ); -} - -#[test] -fn test_create2_late_record_skipped_on_compute_limit_halt_pre_rex5() { - // Pre-REX5 path through `storage_gas_ext::create` records the CREATE2 memory-expansion gas in - // a trailing `if resize_gas > 0 { compute_gas!(...) }` block AFTER the post-body compute-gas - // recording. If the compute-gas limit trips at the post-body recording, the late-record block - // MUST be skipped — otherwise it adds `resize_gas` to the tracker after the OOG halt was - // already set, diverging from the pre-PR behavior on a frozen spec. - // - // Pin to REX4 (last pre-REX5 spec) so `compute_created_address` leaves `resize_gas > 0` and - // the late-record block has real work to skip. - let spec = MegaSpecId::REX4; - - // Happy path: with a generous limit, the late-record runs successfully, so the final - // tracker equals `previous + body_gas + resize_gas`. - let happy = transact_default(spec, db_with(build_create2_contract())).compute_gas; - - // Measure the pre-CREATE2 compute-gas usage so we can position the limit precisely. - let usage_before_create2 = - transact_default(spec, db_with(build_pushes_only_contract())).compute_gas; - - // Position the limit just past the pre-CREATE2 usage so the limit trips inside - // `record_storage_compute_gas!` immediately after the inner CREATE2 body completes. - let compute_limit = usage_before_create2 + 100; - let limits = EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - let tight = transact(spec, db_with(build_create2_contract()), limits); - - assert!(!tight.is_success(), "tight compute limit must halt; got {:?}", tight.result); - - // With the fix, `record_storage_compute_gas!` halts and returns, so the late-record block - // does not run — `tight.compute_gas` is strictly less than `happy` by approximately the - // memory-expansion gas of the 32 KiB initcode. Without the fix, the late-record block adds - // `resize_gas` to the tracker after the halt, making `tight.compute_gas == happy`. - assert!( - tight.compute_gas < happy, - "pre-REX5 CREATE2 late-record block must be skipped on post-body halt; \ - happy={} tight={}", - happy, - tight.compute_gas - ); -} - /// An oversized CREATE2 initcode must halt with `CreateInitCodeSizeLimit` under REX6 /// BEFORE any memory-expansion/copy/keccak256 prework runs, not after. /// @@ -348,37 +238,6 @@ fn test_create2_oversized_initcode_halts_before_prework_rex6() { ); } -/// Pre-REX6 replay parity: the early size check is gated to REX6 only. REX5 (sealed) must keep -/// performing the resize/copy/keccak256 prework before any size check runs — no retroactive fix. -/// For the same 10 MiB initcode as the REX6 test above, REX5's `resize_memory!` itself exhausts the -/// gas limit and halts with `MemoryOOG`, never reaching the canonical EIP-3860 check at all — -/// contrasted with REX6's immediate `CreateInitCodeSizeLimit` above. This is the direct, -/// observable proof that pre-REX6 still performs the prework this finding is about. -#[test] -fn test_create2_oversized_initcode_pre_rex6_still_does_prework() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, far past the 548,864-byte cap - - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(HUGE_INITCODE_LEN) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code)); - - assert!( - matches!(&r5.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("OutOfGas(Memory)")), - "REX5 (sealed) must still attempt resize_memory! for an oversized initcode and halt \ - with an OutOfGas(Memory) halt (MemoryOOG), never reaching the canonical EIP-3860 \ - check; got {:?}", - r5.result, - ); -} - /// Halt-reason parity for a "moderately" oversized initcode (bigger than the 548,864-byte cap, /// but small enough that `resize_memory!`'s own gas cost stays well within the 100M tx gas /// limit). Both specs reach `CreateInitCodeSizeLimit` — REX5 via the slower prework-then-inner- diff --git a/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs new file mode 100644 index 000000000..1f9e9d19c --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex6/create_frame_accounting.rs @@ -0,0 +1,166 @@ +//! REX6 CREATE-frame resource-accounting tests. +//! +//! Under REX6, `StateGrowthTracker` records +1 state growth for a `CREATE` only when the +//! deployment address is a net-new account; a pre-funded balance-only target already exists +//! and is not counted. Pre-REX6 records +1 unconditionally. +//! +//! This file also pins that a child-CREATE's creator nonce-bump account-info write is charged +//! to the parent frame's discardable lane under REX6, so the charge survives the child's revert +//! and is correctly attributed to the frame that owns the on-chain effect. + +use alloy_primitives::{Address, Bytes, U256}; +use mega_evm::{ + test_utils::{ErrorInjectingDatabase, MemoryDatabase}, + EmptyExternalEnv, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + MegaTransaction, ACCOUNT_INFO_WRITE_SIZE, +}; +use revm::{ + context::{ + result::{ExecutionResult, ResultAndState}, + BlockEnv, ContextSetters, TxEnv, + }, + handler::EvmTr, + primitives::TxKind, +}; + +const CALLER: Address = Address::new([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0xDE, 0x00, 0x01, +]); +const CALLER_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH +const TX_GAS_LIMIT: u64 = 5_000_000; // generous headroom for a trivial CREATE; not a bound under test + +type TestEvm = MegaEvm; +type TestResult = ResultAndState; + +/// Builds a configured `MegaEvm` for `spec` with the given `limits` and operator fees zeroed +/// (so only the accounting under test moves). Single source of truth for block/chain setup. +fn make_evm_with_limits( + spec: MegaSpecId, + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, +) -> TestEvm { + let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); + context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + MegaEvm::new(context) +} + +/// Builds a configured `MegaEvm` for `spec` with no tx runtime limits and operator fees zeroed. +/// Shared by every test in this file that doesn't need custom limits. +fn make_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { + make_evm_with_limits(spec, db, EvmTxRuntimeLimits::no_limits()) +} + +/// Init code that immediately STOPs (deploys empty runtime) — a trivial successful CREATE. +fn stop_init_code() -> Bytes { + Bytes::from_static(&[0x00]) // STOP +} + +fn run(spec: MegaSpecId, db: MemoryDatabase, init_code: Bytes) -> (TestResult, TestEvm) { + let mut evm = make_evm(spec, db); + + let tx_env = TxEnv { + caller: CALLER, + kind: TxKind::Create, + gas_limit: TX_GAS_LIMIT, + gas_price: 0, + data: init_code, + value: U256::ZERO, + ..Default::default() + }; + let mut tx = MegaTransaction::new(tx_env); + tx.enveloped_tx = Some(Bytes::new()); + + let r = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); + (r, evm) +} + +/// The address a top-level CREATE from CALLER (nonce 0) deploys to. +fn first_create_address() -> Address { + CALLER.create(0) +} + +const OUTER_CREATOR: Address = Address::new([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0xDE, 0x00, 0xFF, +]); + +/// Init code that returns `code_len` bytes of zeros from `memory[0..code_len]`. +/// +/// Layout: PUSH3 `code_len`; PUSH1 0; RETURN. +fn return_zeros_initcode(code_len: u32) -> Bytes { + let bytes = code_len.to_be_bytes(); + let mut code = Vec::with_capacity(7); + code.push(0x62); // PUSH3 + code.extend_from_slice(&bytes[1..]); // 3-byte big-endian length + code.push(0x60); // PUSH1 + code.push(0x00); + code.push(0xf3); // RETURN + Bytes::from(code) +} + +/// Runs a top-level CREATE under `spec` with `data_size_limit` as the tx data-size budget and a +/// constructor that RETURNs `code_len` runtime bytes, with `tx_gas_limit` available to the frame. +fn run_create_with_limits( + spec: MegaSpecId, + data_size_limit: u64, + code_len: u32, + tx_gas_limit: u64, +) -> TestResult { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data_size_limit); + let mut evm = make_evm_with_limits(spec, db, limits); + + let tx_env = TxEnv { + caller: CALLER, + kind: TxKind::Create, + gas_limit: tx_gas_limit, + gas_price: 0, + data: return_zeros_initcode(code_len), + value: U256::ZERO, + ..Default::default() + }; + let mut tx = MegaTransaction::new(tx_env); + tx.enveloped_tx = Some(Bytes::new()); + alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError") +} + +/// REX6: a DB failure while inspecting the CREATE target for the net-new state-growth check must +/// surface as an error, not be silently swallowed. A normal `MemoryDatabase` is infallible, so the +/// `inspect_account(created_address, ..)?` error branch is only exercised by injecting a DB read +/// failure here. The created-address read happens after the caller-nonce read, so failing on +/// `first_create_address()` lets the caller read succeed and trips exactly the created-address +/// inspect. +#[test] +fn test_rex6_create_net_new_inspect_db_error_surfaces() { + let inner = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); + let mut db = ErrorInjectingDatabase::new(inner); + db.fail_on_account = Some(first_create_address()); + + let mut context = MegaContext::new(db, MegaSpecId::REX6); + context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + let mut evm = MegaEvm::new(context); + + let tx_env = TxEnv { + caller: CALLER, + kind: TxKind::Create, + gas_limit: TX_GAS_LIMIT, + gas_price: 0, + data: stop_init_code(), + value: U256::ZERO, + ..Default::default() + }; + let mut tx = MegaTransaction::new(tx_env); + tx.enveloped_tx = Some(Bytes::new()); + + let res = alloy_evm::Evm::transact_raw(&mut evm, tx); + assert!(res.is_err(), "DB error during REX6 CREATE net-new inspect must surface as Err"); +} diff --git a/crates/mega-evm/tests/rex6/eip7702_authority_accounting.rs b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs similarity index 100% rename from crates/mega-evm/tests/rex6/eip7702_authority_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs diff --git a/crates/mega-evm/tests/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs similarity index 100% rename from crates/mega-evm/tests/rex6/error_paths.rs rename to crates/mega-evm/tests/_pending/rex6/error_paths.rs diff --git a/crates/mega-evm/tests/rex6/fee_reward_accounting.rs b/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs similarity index 90% rename from crates/mega-evm/tests/rex6/fee_reward_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs index fcf239f2f..e6442557c 100644 --- a/crates/mega-evm/tests/rex6/fee_reward_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs @@ -405,63 +405,6 @@ fn test_rex6_beneficiary_tip_materialization_records_accounting() { // REX5 freeze guard // ============================================================================ -/// REX5 freeze guard: under `MegaSpecId::REX5` the fee-reward path must record -/// **no** fee-recipient accounting. An empty vs pre-funded `BASE_FEE_RECIPIENT` -/// must produce byte-identical `state_growth`, `data_size`, and `kv_updates`. -#[test] -fn test_rex5_freeze_no_fee_recipient_accounting() { - // --- Run A: BASE_FEE_RECIPIENT absent (would materialise under REX6) ---------- - let db_empty = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - - let (res_empty, evm_empty) = - transact_with_spec(MegaSpecId::REX5, db_empty, BASEFEE, make_call_tx()); - assert!( - res_empty.expect("REX5 empty run must not produce a validation error").result.is_success(), - "REX5 empty run: tx must succeed", - ); - let empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - // --- Run B: BASE_FEE_RECIPIENT pre-funded ------------------------------------ - let db_funded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)); - - let (res_funded, evm_funded) = - transact_with_spec(MegaSpecId::REX5, db_funded, BASEFEE, make_call_tx()); - assert!( - res_funded - .expect("REX5 funded run must not produce a validation error") - .result - .is_success(), - "REX5 funded run: tx must succeed", - ); - let funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - // Under REX5 the fee-reward path is frozen: no accounting is recorded for any - // fee-recipient balance change, so all usage fields must be identical. - assert_eq!( - empty.state_growth, funded.state_growth, - "REX5: state_growth must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.state_growth, funded.state_growth, - ); - assert_eq!( - empty.data_size, funded.data_size, - "REX5: data_size must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.data_size, funded.data_size, - ); - assert_eq!( - empty.kv_updates, funded.kv_updates, - "REX5: kv_updates must be equal regardless of BASE_FEE_RECIPIENT presence \ - (empty={}, funded={})", - empty.kv_updates, funded.kv_updates, - ); -} - // ============================================================================ // Recipient dedup (beneficiary coincides with a fee vault) // ============================================================================ diff --git a/crates/mega-evm/tests/rex6/frame_local_accounting.rs b/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs similarity index 67% rename from crates/mega-evm/tests/rex6/frame_local_accounting.rs rename to crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs index 1da0b99f8..1a9e95c14 100644 --- a/crates/mega-evm/tests/rex6/frame_local_accounting.rs +++ b/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs @@ -61,20 +61,6 @@ fn test_rex6_log0_empty_charges_base_overhead_vs_rex5() { ); } -#[test] -fn test_rex5_log0_empty_is_free_frozen() { - // Freeze guard: under REX5, LOG0(0,0) contributes ZERO data_size beyond the no-log baseline - // (preserved byte-for-byte pre-REX6). - let with_log = transact_default(MegaSpecId::REX5, base_db(log0_empty_code())); - let no_log = - transact_default(MegaSpecId::REX5, base_db(BytecodeBuilder::default().stop().build())); - assert_eq!( - with_log.data_size, no_log.data_size, - "REX5 LOG0(0,0) must remain free in data_size (frozen); with_log={} no_log={}", - with_log.data_size, no_log.data_size, - ); -} - #[test] fn test_rex6_log1_with_data_base_plus_topics_plus_data() { // LOG1 with 32 bytes of data: REX6 = REX5 + LOG_BASE_SIZE (one log → one base overhead); the @@ -139,27 +125,6 @@ fn tight_compute_limits() -> EvmTxRuntimeLimits { limits } -#[test] -fn test_rex6_compute_abort_at_call_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, compute_abort_db(), tight_compute_limits()); - let r6 = transact(MegaSpecId::REX6, compute_abort_db(), tight_compute_limits()); - // Both halt (frame-local compute-limit Revert) at the CALL. - assert!(!r5.is_success(), "REX5 must halt on the compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt on the compute limit; got {:?}", r6.result); - // REX5 swallows the forwarded gas (~98% of the 100M tx limit) → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before halting → gas_used stays small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas (not swallow it); gas_used={}", - r6.gas_used, - ); -} - /// DB where [`CONTRACT`] performs a `CREATE` with a one-byte init code, forwarding gas to the init /// frame. The `CREATE` is the first compute-significant opcode, so its compute overhead overruns /// the tight budget while the child `NewFrame(Create)` is pending and its forwarded gas deducted. @@ -179,27 +144,6 @@ fn compute_abort_create_db() -> MemoryDatabase { .account_balance(CONTRACT, U256::from(ONE_ETH)) } -#[test] -fn test_rex6_compute_abort_at_create_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, compute_abort_create_db(), tight_compute_limits()); - let r6 = transact(MegaSpecId::REX6, compute_abort_create_db(), tight_compute_limits()); - // Both halt (frame-local compute-limit Revert) at the CREATE. - assert!(!r5.is_success(), "REX5 must halt on the compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt on the compute limit; got {:?}", r6.result); - // REX5 swallows the gas forwarded to the discarded init frame → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before halting → gas_used stays small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas (not swallow it); gas_used={}", - r6.gas_used, - ); -} - /// DB where [`CONTRACT`] accesses volatile block env (`TIMESTAMP`) to arm a relative compute-gas /// detention cap, then performs a gas-forwarding CALL to a code-bearing target. With a tight /// detention cap and a large per-frame budget, the CALL's own compute overshoots the *tx-level* @@ -235,39 +179,6 @@ fn tx_level_detention_limits() -> EvmTxRuntimeLimits { limits } -/// The forwarded gas is returned to the parent on a *tx-level* (detained) compute-limit halt at a -/// CALL, not only on the frame-local one: a child `NewFrame` whose gas revm already deducted is -/// discarded when the detained `OutOfGas` fires, so without the erase that gas is swallowed into -/// `gas_used`. REX6 returns it; pre-REX6 leaves it swallowed. -#[test] -fn test_rex6_tx_level_compute_abort_at_call_returns_forwarded_gas() { - let r5 = transact(MegaSpecId::REX5, tx_level_detained_abort_db(), tx_level_detention_limits()); - let r6 = transact(MegaSpecId::REX6, tx_level_detained_abort_db(), tx_level_detention_limits()); - // Both halt at the tx-level detained limit (a Halt, distinct from the frame-local Revert). - assert!( - matches!(r5.result, ExecutionResult::Halt { .. }), - "REX5 must hit the tx-level detained OutOfGas (Halt), not a frame-local Revert; got {:?}", - r5.result, - ); - assert!( - matches!(r6.result, ExecutionResult::Halt { .. }), - "REX6 must hit the tx-level detained OutOfGas (Halt), not a frame-local Revert; got {:?}", - r6.result, - ); - // REX5 swallows the gas forwarded to the discarded child → gas_used inflated. - assert!( - r5.gas_used > 50_000_000, - "REX5 must swallow the forwarded gas (frozen bug); gas_used={}", - r5.gas_used, - ); - // REX6 erases the forwarded gas back to the parent before the detained halt → gas_used small. - assert!( - r6.gas_used < 1_000_000, - "REX6 must return the forwarded gas on a tx-level halt too; gas_used={}", - r6.gas_used, - ); -} - #[test] fn test_rex6_two_logs_charge_two_base_overheads() { // Two LOG0(0,0) → two per-log base overheads under REX6. diff --git a/crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs b/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs similarity index 85% rename from crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs rename to crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs index 852e4c8a7..2191f405c 100644 --- a/crates/mega-evm/tests/rex6/keyless_sandbox_hardening.rs +++ b/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs @@ -269,74 +269,6 @@ fn test_rex6_create_then_selfdestruct_surfaces_as_empty_code() { // Keyless dispatch-overhead OOG rescues parent gas // ============================================================================ -/// REX6: when the `KEYLESS_DEPLOY_OVERHEAD_GAS` charge exceeds the -/// `AdditionalLimit`'s tx-level compute-gas cap, the outer Gas counter's -/// unused remainder must be rescued. Pre-REX6 leaves the unused remainder -/// fully spent so the sender pays the entire outer envelope for a halt that -/// barely touched anything. -/// -/// We compare the outer tx's reported `gas_used` between REX5 and REX6 and -/// pin both an inequality (REX6 < REX5) and an absolute lower bound on the -/// rescue delta. The bound is set well below the realistic rescue amount -/// (≈ outer envelope − intrinsic − overhead) but high enough that a -/// partial-rescue regression (e.g., rescuing only the overhead, or missing -/// the post-overhead remainder) would fail it. -#[test] -fn test_rex6_keyless_overhead_oog_rescues_parent_gas() { - // Minimal init code — never executes because the 100K overhead halts first. - let init_code = - BytecodeBuilder::default().push_number(0_u8).push_number(0_u8).append(RETURN).build(); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - // Squeeze tx compute gas below 100K so the keyless overhead record overflows. - let tx_compute_gas_limit: u64 = 50_000; - - let build_db = || { - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - db - }; - - let mut db_rex5 = build_db(); - let result_rex5 = run_keyless_outer( - MegaSpecId::REX5, - &mut db_rex5, - keyless_tx_bytes.clone(), - LARGE_GAS_LIMIT_OVERRIDE, - Some(tx_compute_gas_limit), - None, - ); - - let mut db_rex6 = build_db(); - let result_rex6 = run_keyless_outer( - MegaSpecId::REX6, - &mut db_rex6, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - Some(tx_compute_gas_limit), - None, - ); - - let gas_used_rex5 = result_rex5.gas_used(); - let gas_used_rex6 = result_rex6.gas_used(); - assert!( - gas_used_rex6 < gas_used_rex5, - "REX6 must rescue parent gas on tx-level compute exceed: REX6={gas_used_rex6} \ - < REX5={gas_used_rex5}", - ); - - // Pin the rescue delta against a conservative lower bound. With - // `OUTER_GAS_LIMIT = 30_000_000`, the rescued amount should be roughly the - // outer envelope minus the intrinsic + 100K overhead. A partial-rescue - // regression (only the overhead, or only the storage-stipend slice) would - // produce a delta well under 25M and fail this assertion. - let rescue_delta = gas_used_rex5 - gas_used_rex6; - assert!( - rescue_delta >= 25_000_000, - "REX6 rescue delta too small: {rescue_delta} (REX5={gas_used_rex5}, REX6={gas_used_rex6})", - ); -} - // ============================================================================ // Bytecode invariant pins (EIP-3541 / EIP-170 enforcement reaches the // sandbox dispatch path) diff --git a/crates/mega-evm/tests/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs similarity index 96% rename from crates/mega-evm/tests/rex6/main.rs rename to crates/mega-evm/tests/_pending/rex6/main.rs index 8f33582f0..a6e652c07 100644 --- a/crates/mega-evm/tests/rex6/main.rs +++ b/crates/mega-evm/tests/_pending/rex6/main.rs @@ -13,7 +13,6 @@ mod error_paths; mod fee_reward_accounting; mod frame_local_accounting; mod keyless_sandbox_hardening; -mod metering_order_parity; mod oracle_hint_volatile_access; mod self_transfer_account_dedup; mod sequencer_registry_rotation; diff --git a/crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs similarity index 93% rename from crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs rename to crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs index d20a8c65a..2f946ee1f 100644 --- a/crates/mega-evm/tests/rex6/oracle_hint_volatile_access.rs +++ b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs @@ -222,20 +222,3 @@ fn test_rex6_disabled_send_hint_is_not_metered_against_data_size() { ); assert!(hints.is_empty(), "a disabled sendHint call must not forward"); } - -/// REX5 replay parity: the guard is gated to REX6+. REX5 is sealed and must keep forwarding -/// `sendHint` regardless of the volatile-access-disabled state — no retroactive behavior change. -#[test] -fn test_rex5_disabled_frame_still_forwards_send_hint() { - let code = - call_send_hint(call_disable_volatile_data_access(BytecodeBuilder::default()), 64, 100_000) - .stop() - .build(); - let (result, hints) = run_with_oracle(MegaSpecId::REX5, code, None); - assert!(result.is_success(), "outer tx must succeed: {result:?}"); - assert_eq!( - hints.len(), - 1, - "REX5 (sealed) must keep forwarding sendHint regardless of volatile-access-disabled state", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs new file mode 100644 index 000000000..ce6adfd2b --- /dev/null +++ b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs @@ -0,0 +1,136 @@ +//! REX6 value self-transfer account-info dedup for `DataSize` / KV. +//! +//! A value transfer whose target equals the caller touches a single account. The caller-side +//! account-info write (or, at the top level, the `before_tx_start` caller record) already accounts +//! for it, so the target-side write would double-count the same account on the block +//! `DataSize` / KV-update limiter lanes. Under REX6 the redundant target-side write is suppressed +//! when `target == caller`; non-self transfers (`A -> B`) and zero-value calls are unchanged, and +//! pre-REX6 specs keep the frozen double-count. +//! +//! The tests measure the *value-transfer-induced delta* (a `value > 0` run minus an otherwise +//! identical `value == 0` run). That delta isolates exactly the target-side account-info write: +//! +//! - `A -> B`, `value=1`: target write records B → delta = one account-info write on every spec. +//! - `A -> A`, `value=1` (REX6): target write suppressed → delta = 0. +//! - `A -> A`, `value=1` (REX5): target write recorded → delta = one account-info write (frozen). + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EmptyExternalEnv, LimitUsage, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + ACCOUNT_INFO_WRITE_SIZE, +}; +use revm::{ + bytecode::opcode::*, + context::{BlockEnv, ContextSetters, TxEnv}, + handler::EvmTr, + primitives::TxKind, +}; + +/// EOA sender / self-transfer target. +const A: Address = address!("00000000000000000000000000000000A0000001"); +/// Distinct non-self transfer target. +const B: Address = address!("00000000000000000000000000000000B0000002"); +/// A pure-EOA sender used for the nested cases, so the tx caller has no code (EIP-3607). +const EOA: Address = address!("00000000000000000000000000000000E0A00003"); +/// A self-calling contract used in the nested cases (its frame CALLs itself with value). +const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); +/// Pre-funded coinbase so beneficiary materialisation never adds noise. +const COINBASE: Address = address!("00000000000000000000000000000000C0FFEE01"); + +const TX_GAS_LIMIT: u64 = 1_000_000; +const A_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH + +type TestEvm = MegaEvm; + +/// Builds a fee-free EVM (`gas_price` = basefee = 0, operator fees zeroed, coinbase pre-funded) so +/// the post-execution fee-reward writes never perturb the `DataSize` / KV measurement. +fn build_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { + let mut context = MegaContext::new(db, spec); + context.set_block(BlockEnv { + gas_limit: 1_000_000_000, + basefee: 0, + beneficiary: COINBASE, + ..Default::default() + }); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::from(0)); + chain.operator_fee_constant = Some(U256::from(0)); + }); + MegaEvm::new(context) +} + +fn base_db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(A, U256::from(A_BALANCE)) + .account_balance(EOA, U256::from(A_BALANCE)) + .account_balance(COINBASE, U256::from(1u64)) +} + +/// A top-level call `A -> to` with the given `value`. +fn call_tx(to: Address, value: u128) -> MegaTransaction { + let mut tx = MegaTransaction { + base: TxEnv { + caller: A, + kind: TxKind::Call(to), + gas_limit: TX_GAS_LIMIT, + gas_price: 0, + value: U256::from(value), + ..Default::default() + }, + ..Default::default() + }; + tx.enveloped_tx = Some(Bytes::new()); + tx +} + +/// Runs `tx` under `spec` against a fresh `db`, asserts success, and returns the limiter usage. +fn usage_of(spec: MegaSpecId, db: MemoryDatabase, tx: MegaTransaction) -> LimitUsage { + let mut evm = build_evm(spec, db); + let r = alloy_evm::Evm::transact_raw(&mut evm, tx); + assert!( + r.expect("no validation error").result.is_success(), + "tx must succeed for a clean usage reading", + ); + let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); + usage +} + +// ============================================================================ +// Top-level self-transfer: A -> A +// ============================================================================ + +// ============================================================================ +// Non-self transfer: A -> B (unchanged on every spec) +// ============================================================================ + +// ============================================================================ +// Nested self-call with value: A's code CALLs A with value +// ============================================================================ + +// ============================================================================ +// Nested self-call where the parent frame already did a value transfer +// (`parent_needs_update == false` arm of the dedup predicate) +// ============================================================================ + +// ============================================================================ +// Zero-value call records no account-info write (unchanged) +// ============================================================================ + +/// A zero-value top-level call records no target-side account-info write on either spec, so the +/// `value=1` vs `value=0` comparison is the only thing that moves — already asserted above. This +/// test pins that REX6 and REX5 agree on the zero-value absolute usage (no behaviour change for the +/// non-transfer path). +#[test] +fn test_zero_value_call_unchanged_across_specs() { + let rex6 = usage_of(MegaSpecId::REX6, base_db(), call_tx(B, 0)); + let rex5 = usage_of(MegaSpecId::REX5, base_db(), call_tx(B, 0)); + assert_eq!( + rex6.data_size, rex5.data_size, + "zero-value A->B call data_size must be identical across specs", + ); + assert_eq!( + rex6.kv_updates, rex5.kv_updates, + "zero-value A->B call kv_updates must be identical across specs", + ); +} diff --git a/crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs similarity index 79% rename from crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs rename to crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs index e8934b409..97664c952 100644 --- a/crates/mega-evm/tests/rex6/sequencer_registry_rotation.rs +++ b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs @@ -261,110 +261,6 @@ fn test_rex6_bootstrap_deploys_v2_and_resolves_system_address() { ); } -/// The grandfathering boundary case: a rotation scheduled under v1.0.0 whose activation block -/// is exactly the Rex6 activation block. In that single block the executor must both upgrade -/// the bytecode in place (preserving all live storage) and apply the due rotation. -#[test] -fn test_rex6_upgrade_block_applies_v1_scheduled_rotation() { - let (new_sequencer, _) = new_sequencer_keypair(); - let activation_block = 1000u64; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - seed_v1_registry_with_pending_rotation(&mut db, new_sequencer, activation_block); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = executor_factory().create_executor( - &mut state, - block_ctx(), - evm_env_at_block(activation_block), - ); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - drop(executor); - - // The upgrade landed... - assert_eq!( - registry_code_hash(&mut state), - SEQUENCER_REGISTRY_CODE_HASH_REX6, - "registry must run v2.0.0 after the Rex6 activation block" - ); - assert_eq!( - read_registry_slot(&mut state, MIN_ROTATION_DELAY), - U256::from(MIN_ROTATION_DELAY_BLOCKS), - ); - // ...the grandfathered rotation flipped in the same block... - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the v1-scheduled rotation must activate normally across the upgrade" - ); - assert_eq!(read_registry_slot(&mut state, PENDING_SEQUENCER), U256::ZERO); - assert_eq!(read_registry_slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), U256::ZERO); - // ...and untouched live storage survived the upgrade. - assert_eq!( - read_registry_slot(&mut state, ADMIN), - U256::from_be_bytes(BOOTSTRAP_ADMIN.into_word().0), - "live admin slot must survive the in-place upgrade" - ); - assert_eq!( - read_registry_slot(&mut state, CURRENT_SYSTEM_ADDRESS), - U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), - ); -} - -/// The common mainnet upgrade shape: a rotation scheduled under v1.0.0 whose activation block -/// lands AFTER the Rex6 activation block. The upgrade block must swap the bytecode without -/// flipping the not-yet-due rotation, and the later activation block must flip it under the -/// v2.0.0 bytecode. -#[test] -fn test_rex6_v1_scheduled_rotation_activates_after_upgrade_block() { - let (new_sequencer, _) = new_sequencer_keypair(); - let upgrade_block = 1000u64; - let activation_block = upgrade_block + 50; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - seed_v1_registry_with_pending_rotation(&mut db, new_sequencer, activation_block); - - let mut state = State::builder().with_database(&mut db).build(); - let factory = executor_factory(); - - // Upgrade block: bytecode swaps, but the rotation is not yet due and must stay pending. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(upgrade_block)); - executor.apply_pre_execution_changes().expect("upgrade block pre-execution should succeed"); - drop(executor); - - assert_eq!(registry_code_hash(&mut state), SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(BOOTSTRAP_SEQUENCER.into_word().0), - "a not-yet-due rotation must not flip on the upgrade block" - ); - assert_eq!( - read_registry_slot(&mut state, PENDING_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the pending rotation must survive the upgrade untouched" - ); - assert_eq!( - read_registry_slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), - U256::from(activation_block), - ); - - // Activation block: the rotation flips under the v2.0.0 bytecode. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(activation_block)); - executor.apply_pre_execution_changes().expect("activation block pre-execution should succeed"); - drop(executor); - - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the v1-scheduled rotation must flip at its activation block under v2.0.0" - ); - assert_eq!(read_registry_slot(&mut state, PENDING_SEQUENCER), U256::ZERO); -} - /// Full v2.0.0 round trip through normal transactions: the admin schedules a rotation with /// the new key's EIP-712 possession proof in one block, and the rotation activates in a /// later block's pre-execution phase. diff --git a/crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs similarity index 89% rename from crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs rename to crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs index 01c7dbd1a..6362475fd 100644 --- a/crates/mega-evm/tests/rex6/system_tx_metering_exemption.rs +++ b/crates/mega-evm/tests/_pending/rex6/system_tx_metering_exemption.rs @@ -222,48 +222,6 @@ fn test_rex6_pre_block_calls_accepted_under_heavy_salt() { assert!(saw_beacon_root, "EIP-4788 pre-block call must succeed and commit under REX6"); } -/// Parity counterpart to the test above: the identical heavy-SALT setup, but with -/// `cfg.spec = REX5` and a REX5-only chain spec, must reject the block. This pins the parity -/// claim — exemption is only in effect under REX6 — inside this file rather than relying on the -/// reader to cross-reference the REX5 test suite. -#[test] -fn test_rex5_pre_block_calls_rejected_under_heavy_salt() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let block_ctx = MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx, - evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("REX5 must reject the heavy-SALT EIP-2935 pre-block call"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "Expected BlockHashContractCall, got: {validation_err:?}" - ); -} - // ============================================================================ // 2. Sequencer mega system tx (oracle write) succeeds under heavy SALT // ============================================================================ diff --git a/crates/mega-evm/tests/_pending/src/access/volatile.rs b/crates/mega-evm/tests/_pending/src/access/volatile.rs new file mode 100644 index 000000000..7aa7e6405 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/access/volatile.rs @@ -0,0 +1,85 @@ +//! Unit tests extracted from `crates/mega-evm/src/access/volatile.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/access/volatile.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::VolatileDataAccessType; + + #[test] + fn test_empty_access_has_no_flags() { + let access = VolatileDataAccess::empty(); + + assert!(!access.has_block_env_access()); + assert!(!access.has_beneficiary_balance_access()); + assert!(!access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 0); + assert_eq!(access.count_accessed(), 0); + assert_eq!(access.block_env_only(), VolatileDataAccess::empty()); + assert_eq!(access.raw(), 0); + } + + #[test] + fn test_block_env_helpers_ignore_non_block_flags() { + let access = VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::BLOB_HASH | + VolatileDataAccess::BENEFICIARY_BALANCE | + VolatileDataAccess::ORACLE; + + assert!(access.has_block_env_access()); + assert!(access.has_beneficiary_balance_access()); + assert!(access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 2); + assert_eq!(access.count_accessed(), 2); + assert_eq!( + access.block_env_only(), + VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH + ); + assert_eq!(access.raw(), access.bits()); + } + + #[test] + fn test_from_volatile_data_access_type_covers_all_variants() { + let expected: &[(VolatileDataAccessType, VolatileDataAccess)] = &[ + (VolatileDataAccessType::BlockNumber, VolatileDataAccess::BLOCK_NUMBER), + (VolatileDataAccessType::Timestamp, VolatileDataAccess::TIMESTAMP), + (VolatileDataAccessType::Coinbase, VolatileDataAccess::COINBASE), + (VolatileDataAccessType::Difficulty, VolatileDataAccess::DIFFICULTY), + (VolatileDataAccessType::GasLimit, VolatileDataAccess::GAS_LIMIT), + (VolatileDataAccessType::BaseFee, VolatileDataAccess::BASE_FEE), + (VolatileDataAccessType::PrevRandao, VolatileDataAccess::PREV_RANDAO), + (VolatileDataAccessType::BlockHash, VolatileDataAccess::BLOCK_HASH), + (VolatileDataAccessType::BlobBaseFee, VolatileDataAccess::BLOB_BASE_FEE), + (VolatileDataAccessType::BlobHash, VolatileDataAccess::BLOB_HASH), + (VolatileDataAccessType::Beneficiary, VolatileDataAccess::BENEFICIARY_BALANCE), + (VolatileDataAccessType::Oracle, VolatileDataAccess::ORACLE), + ]; + + for &(access_type, expected_flag) in expected { + let converted = VolatileDataAccess::from(access_type); + assert_eq!(converted, expected_flag); + assert_eq!(converted.as_u8(), expected_flag.as_u8()); + } + } + + #[test] + fn test_all_block_env_flags_counted_correctly() { + let all_block_env = VolatileDataAccess::BLOCK_NUMBER | + VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::COINBASE | + VolatileDataAccess::DIFFICULTY | + VolatileDataAccess::GAS_LIMIT | + VolatileDataAccess::BASE_FEE | + VolatileDataAccess::PREV_RANDAO | + VolatileDataAccess::BLOCK_HASH | + VolatileDataAccess::BLOB_BASE_FEE | + VolatileDataAccess::BLOB_HASH; + + assert_eq!(all_block_env.count_block_env_accessed(), 10); + assert!(all_block_env.has_block_env_access()); + assert!(!all_block_env.has_beneficiary_balance_access()); + assert!(!all_block_env.has_oracle_access()); + assert_eq!(all_block_env.block_env_only(), all_block_env); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/chain.rs b/crates/mega-evm/tests/_pending/src/block/chain.rs new file mode 100644 index 000000000..ff0d74c55 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/chain.rs @@ -0,0 +1,100 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/chain.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/chain.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MegaHardfork, MegaHardforks, MegaSpecId}; + + #[test] + fn test_mainnet_schedule_resolves_specs_by_timestamp() { + let hf = mainnet_hardforks(); + assert_eq!(hf.spec_id(1764851940), MegaSpecId::REX); + assert_eq!(hf.spec_id(1776659200), MegaSpecId::REX4); + // Just before Rex5, still Rex4; at/after Rex5, Rex5. + assert_eq!(hf.spec_id(1780631999), MegaSpecId::REX4); + assert_eq!(hf.spec_id(1780632000), MegaSpecId::REX5); + // Just before Rex6, still Rex5; at/after Rex6, Rex6. + assert_eq!(hf.spec_id(1787626799), MegaSpecId::REX5); + assert_eq!(hf.spec_id(1787626800), MegaSpecId::REX6); + // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. + assert!(hf.fork_params::().is_some()); + assert!(hf.fork_params::().is_some()); + } + + #[test] + fn test_testnet_schedule_resolves_specs_by_timestamp() { + let hf = testnet_hardforks(); + assert_eq!(hf.spec_id(1776400000), MegaSpecId::REX4); + // Just before Rex5, still Rex4; at/after Rex5, Rex5. + assert_eq!(hf.spec_id(1780459199), MegaSpecId::REX4); + assert_eq!(hf.spec_id(1780459200), MegaSpecId::REX5); + // Just before Rex6, still Rex5; at/after Rex6, Rex6. + assert_eq!(hf.spec_id(1786330799), MegaSpecId::REX5); + assert_eq!(hf.spec_id(1786330800), MegaSpecId::REX6); + // Rex5 carries the SequencerRegistryConfig, Rex6 the SequencerRegistryRex6Config. + assert!(hf.fork_params::().is_some()); + assert!(hf.fork_params::().is_some()); + } + + #[test] + fn test_schedule_dispatch_by_chain_id() { + assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1780632000), MegaSpecId::REX5); + assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1780459200), MegaSpecId::REX5); + assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(1787626800), MegaSpecId::REX6); + assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(1786330800), MegaSpecId::REX6); + // Unknown chain: every fork up to the pinned rung, active at genesis. + assert_eq!(hardfork_schedule(1).spec_id(0), MegaSpecId::REX7); + } + + #[test] + fn test_unknown_chain_fallback_carries_sequencer_registry_config() { + // Rex5 block execution fails pre-block without a SequencerRegistryConfig, + // so the all-activated fallback must attach placeholder roles. + let hf = hardfork_schedule(999_999); + assert_eq!(hf.spec_id(0), MegaSpecId::REX7); + let params = hf + .fork_params::() + .expect("fallback schedule must carry a SequencerRegistryConfig"); + assert_eq!(params.rex5_initial_sequencer, MEGA_SYSTEM_ADDRESS); + assert_eq!(params.rex5_initial_admin, MEGA_SYSTEM_ADDRESS); + // Rex6 is also active at genesis in the fallback, and the v2.0.0 registry + // deploy fails pre-block without a SequencerRegistryRex6Config — without + // this, every unknown-chain block aborts before the registry can deploy. + let rex6_params = hf + .fork_params::() + .expect("fallback schedule must carry a SequencerRegistryRex6Config"); + assert!(rex6_params.rex6_min_rotation_delay > 0); + } + + /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. + /// + /// Unknown chains run their rung from genesis, so it is their semantics from block zero with + /// no fork boundary. Introducing a spec must therefore leave them alone: registering a fork + /// above the pinned rung would rewrite what history they have already produced means, and + /// `mega-evme replay` resolves an unknown chain ID through this same schedule. + /// + /// A newly introduced spec leaves this test green — the pin holding still is the safe + /// direction, so nothing fails to force a decision. What the test pins is drift: the + /// fallback silently following `MegaSpecId::default` again (it fails here once the default + /// advances past the rung), and the rung advancing without this `RUNG` constant being edited + /// in the same change. + #[test] + fn test_unknown_chain_fallback_pins_its_rung() { + let hf = all_activated_hardforks(); + const RUNG: MegaSpecId = MegaSpecId::REX7; + + assert_eq!(hf.spec_id(0), RUNG, "the rung applies from genesis"); + assert_eq!(hf.spec_id(u64::MAX), RUNG, "and is terminal — no later fork is registered"); + + for fork in MegaHardfork::VARIANTS { + let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; + assert_eq!( + registered, + RUNG.is_enabled(fork.spec_id()), + "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" + ); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/eips.rs b/crates/mega-evm/tests/_pending/src/block/eips.rs new file mode 100644 index 000000000..0bba32f6f --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/eips.rs @@ -0,0 +1,92 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/eips.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/eips.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::address; + use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; + + #[test] + fn test_balance_increment_commit_equivalence() { + // This is the most important test: verify that our approach is equivalent + // to the original increment_balances + balance_increment_state approach + + // Setup: create two identical database states + let addr1 = address!("0x1000000000000000000000000000000000000001"); + let addr2 = address!("0x2000000000000000000000000000000000000002"); + let addr3 = address!("0x3000000000000000000000000000000000000003"); + + // Fund only addr1 and addr2, but leave addr3 empty (non-existent) + let setup_db = |db: &mut InMemoryDB| { + for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { + db.insert_account_info( + addr, + AccountInfo { + balance: U256::from(balance), + nonce, + code_hash: alloy_primitives::B256::ZERO, + code: None, + }, + ); + } + }; + + // Setup database 1: will use original approach (increment_balances) + let mut db1 = InMemoryDB::default(); + setup_db(&mut db1); + let mut state1 = State::builder().with_database(&mut db1).build(); + + // Setup database 2: will use our approach (transact_balance_increments + commit) + let mut db2 = InMemoryDB::default(); + setup_db(&mut db2); + let mut state2 = State::builder().with_database(&mut db2).build(); + + // Apply balance increments + let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; + + // Method 1: Original approach + state1 + .increment_balances(balance_increments.clone()) + .expect("increment_balances should succeed"); + + // Method 2: Refactored approach (transact + commit, matching the actual usage pattern) + // The refactoring separates increment_balances into two steps: + // 1. transact_balance_increments() - produces EvmState delta + // 2. commit() - integrates the delta and fixes status transitions + // This allows extracting the intermediate state for system_caller.on_state() hooks + let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) + .expect("transact_balance_increments should succeed") + .expect("Should return state"); + + // Commit the state changes (this applies proper status transitions via apply_evm_state) + state2.commit(result_state); + + // Verify final states match after both approaches + for (addr, _expected_increment) in balance_increments { + let account1 = state1.load_cache_account(addr).expect("Should load from state1"); + let account2 = state2.load_cache_account(addr).expect("Should load from state2"); + + let info1 = account1.account_info().expect("Should have account info"); + let info2 = account2.account_info().expect("Should have account info"); + + assert_eq!( + info1.balance, info2.balance, + "Balance for {:?} should be identical after both methods", + addr + ); + assert_eq!(info1.nonce, info2.nonce, "Nonce for {:?} should be identical", addr); + assert_eq!( + info1.code_hash, info2.code_hash, + "Code hash for {:?} should be identical", + addr + ); + assert_eq!( + account1.status, account2.status, + "Account status for {:?} should be identical after both methods", + addr + ); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/hardfork.rs b/crates/mega-evm/tests/_pending/src/block/hardfork.rs new file mode 100644 index 000000000..5094ee39b --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/hardfork.rs @@ -0,0 +1,233 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/hardfork.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/hardfork.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::SequencerRegistryConfig; + + #[test] + fn test_mega_hardfork_spec_ids_match_expected_specs() { + // Note: MiniRex1 and MiniRex2 map to alias rungs whose behavior reverts to earlier specs. + let cases = [ + (MegaHardfork::MiniRex, MegaSpecId::MINI_REX), + (MegaHardfork::MiniRex1, MegaSpecId::MINI_REX_1), + (MegaHardfork::MiniRex2, MegaSpecId::MINI_REX_2), + (MegaHardfork::Rex, MegaSpecId::REX), + (MegaHardfork::Rex1, MegaSpecId::REX1), + (MegaHardfork::Rex2, MegaSpecId::REX2), + (MegaHardfork::Rex3, MegaSpecId::REX3), + (MegaHardfork::Rex4, MegaSpecId::REX4), + (MegaHardfork::Rex5, MegaSpecId::REX5), + (MegaHardfork::Rex6, MegaSpecId::REX6), + (MegaHardfork::Rex7, MegaSpecId::REX7), + ]; + + for (hardfork, expected_spec) in cases { + assert_eq!(hardfork.spec_id(), expected_spec); + } + } + + #[test] + fn test_default_config_contains_upstream_forks_and_no_mega_forks() { + let config = MegaHardforkConfig::default(); + + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Frontier), + ForkCondition::Block(0) + ); + assert_eq!( + config.ethereum_fork_activation(EthereumHardfork::Prague), + ForkCondition::Timestamp(0) + ); + assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); + assert_eq!(config.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_config_builder_helpers_override_and_remove_hardforks() { + let mut config = MegaHardforkConfig::new() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(10)) + .with(MegaHardfork::Rex4, ForkCondition::Timestamp(80)); + + assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(10))); + assert_eq!(config.get(MegaHardfork::Rex4), Some(&ForkCondition::Timestamp(80))); + + config.insert(MegaHardfork::MiniRex, ForkCondition::Timestamp(20)); + assert_eq!(config.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(20))); + + let config = config.without(MegaHardfork::MiniRex); + assert_eq!(config.get(MegaHardfork::MiniRex), None); + + let from_iter = MegaHardforkConfig::from( + [ + (MegaHardfork::MiniRex, ForkCondition::Timestamp(1)), + (MegaHardfork::Rex2, ForkCondition::Timestamp(2)), + ] + .into_iter(), + ); + assert_eq!(from_iter.get(MegaHardfork::MiniRex), Some(&ForkCondition::Timestamp(1))); + assert_eq!(from_iter.get(MegaHardfork::Rex2), Some(&ForkCondition::Timestamp(2))); + } + + #[test] + fn test_with_all_activated_enables_all_mega_hardforks() { + let config = MegaHardforkConfig::default().with_all_activated(); + + // Driven off `VARIANTS`, which the `hardfork!` macro generates from the same variant list + // that declares the enum. A second hand-written list here would assert only that the + // forks someone remembered to name are activated — a new fork missing from both the + // builder and the list would fail neither. + for hardfork in MegaHardfork::VARIANTS { + assert_eq!( + config.mega_fork_activation(*hardfork), + ForkCondition::Timestamp(0), + "{hardfork:?}" + ); + } + } + + #[test] + fn test_fork_params_typed_access() { + let params = SequencerRegistryConfig { + rex5_initial_sequencer: alloy_primitives::address!( + "0x2222222222222222222222222222222222222222" + ), + rex5_initial_admin: alloy_primitives::address!( + "0x3333333333333333333333333333333333333333" + ), + }; + + let config = MegaHardforkConfig::default() + .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) + .with_params(params.clone()); + + let retrieved = config + .fork_params::() + .expect("should have SequencerRegistryConfig"); + assert_eq!(retrieved, ¶ms); + } + + #[test] + fn test_fork_params_none_when_not_configured() { + let config = + MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); + + assert!(config.fork_params::().is_none()); + } + + #[test] + fn test_default_validate_accepts_any_value() { + #[derive(Debug)] + struct NullParams; + + impl HardforkParams for NullParams { + const FORK: MegaHardfork = MegaHardfork::Rex4; + } + + assert!(NullParams.validate().is_ok()); + } + + #[test] + fn test_hardfork_params_error_display() { + let e = HardforkParamsError { message: "something went wrong".into() }; + assert_eq!(e.to_string(), "something went wrong"); + } + + #[test] + #[should_panic(expected = "Invalid params for fork")] + fn test_with_params_panics_on_validation_error() { + #[derive(Debug)] + struct AlwaysErrParams; + + impl HardforkParams for AlwaysErrParams { + const FORK: MegaHardfork = MegaHardfork::Rex4; + + fn validate(&self) -> Result<(), HardforkParamsError> { + Err(HardforkParamsError { message: "intentional test error".into() }) + } + } + + MegaHardforkConfig::default().with_all_activated().with_params(AlwaysErrParams); + } + + /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered + /// by block number never contributes its own spec to it. `spec_id`/`hardfork` share this + /// limitation; every canonical schedule uses `Timestamp` or `Never`, and + /// `validate_schedule` rejects anything else. + #[test] + fn test_resolution_ignores_block_numbered_forks() { + let hf = MegaHardforkConfig::new() + .with(MegaHardfork::MiniRex, ForkCondition::Block(0)) + .with(MegaHardfork::Rex, ForkCondition::Timestamp(0)); + + assert!( + !hf.mega_fork_activation(MegaHardfork::MiniRex).active_at_timestamp(0), + "block-numbered forks are not timestamped" + ); + // The resolved spec comes from Rex alone; it still covers MINI_REX by ordinal + // inclusion, so the projected predicate reports active even though the MiniRex event + // itself never fires. + assert_eq!(hf.spec_id(0), MegaSpecId::REX); + assert!(hf.spec_id(0).is_enabled(MegaSpecId::MINI_REX)); + assert!(hf.is_mini_rex_active_at_timestamp(0)); + assert_eq!( + hf.validate_schedule(), + Err(ScheduleError::NonTimestampActivation { fork: MegaHardfork::MiniRex }) + ); + } + + /// A scheduled fork whose required params are missing fails at validation time instead of at + /// the first block of the fork. + #[test] + fn test_validate_schedule_requires_scheduled_fork_params() { + let rex5_no_params = + MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX5); + assert_eq!( + rex5_no_params.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Rex5, + params: "SequencerRegistryConfig" + }) + ); + + let rex6_no_params = MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(SequencerRegistryConfig { + rex5_initial_sequencer: crate::MEGA_SYSTEM_ADDRESS, + rex5_initial_admin: crate::MEGA_SYSTEM_ADDRESS, + }); + assert_eq!( + rex6_no_params.validate_schedule(), + Err(ScheduleError::MissingParams { + fork: MegaHardfork::Rex6, + params: "SequencerRegistryRex6Config" + }) + ); + } + + #[test] + fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { + let config = MegaHardforkConfig::default() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) + .with(MegaHardfork::Rex4, ForkCondition::Timestamp(200)) + .with(MegaHardfork::Rex5, ForkCondition::Timestamp(300)) + .with(MegaHardfork::Rex6, ForkCondition::Timestamp(400)) + .with(MegaHardfork::Rex7, ForkCondition::Timestamp(500)); + + assert_eq!(config.hardfork(99), None); + assert_eq!(config.hardfork(100), Some(MegaHardfork::MiniRex)); + assert_eq!(config.hardfork(200), Some(MegaHardfork::Rex4)); + assert_eq!(config.hardfork(300), Some(MegaHardfork::Rex5)); + assert_eq!(config.hardfork(400), Some(MegaHardfork::Rex6)); + assert_eq!(config.hardfork(500), Some(MegaHardfork::Rex7)); + assert_eq!(config.spec_id(99), MegaSpecId::EQUIVALENCE); + assert_eq!(config.spec_id(100), MegaSpecId::MINI_REX); + assert_eq!(config.spec_id(200), MegaSpecId::REX4); + assert_eq!(config.spec_id(300), MegaSpecId::REX5); + assert_eq!(config.spec_id(400), MegaSpecId::REX6); + assert_eq!(config.spec_id(500), MegaSpecId::REX7); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/helpers.rs b/crates/mega-evm/tests/_pending/src/block/helpers.rs new file mode 100644 index 000000000..9a45b97fd --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/helpers.rs @@ -0,0 +1,205 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/helpers.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/helpers.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; + use alloy_primitives::{address, bytes::BufMut, Signature}; + use revm::context::TxEnv; + + const CALLER: Address = address!("2000000000000000000000000000000000000001"); + const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); + + #[derive(Debug, Clone)] + struct MockTx { + nonce: u64, + gas_limit: u64, + value: U256, + input: Bytes, + } + + impl Typed2718 for MockTx { + fn ty(&self) -> u8 { + 0 + } + } + + impl Encodable2718 for MockTx { + fn encode_2718_len(&self) -> usize { + self.input.len() + } + + fn encode_2718(&self, out: &mut dyn BufMut) { + out.put_slice(&self.input); + } + } + + impl Transaction for MockTx { + fn chain_id(&self) -> Option { + Some(1) + } + + fn nonce(&self) -> u64 { + self.nonce + } + + fn gas_limit(&self) -> u64 { + self.gas_limit + } + + fn gas_price(&self) -> Option { + Some(9) + } + + fn max_fee_per_gas(&self) -> u128 { + 9 + } + + fn max_priority_fee_per_gas(&self) -> Option { + None + } + + fn max_fee_per_blob_gas(&self) -> Option { + None + } + + fn priority_fee_or_price(&self) -> u128 { + 9 + } + + fn effective_gas_price(&self, _base_fee: Option) -> u128 { + 9 + } + + fn is_dynamic_fee(&self) -> bool { + false + } + + fn kind(&self) -> TxKind { + TxKind::Call(CONTRACT) + } + + fn is_create(&self) -> bool { + false + } + + fn value(&self) -> U256 { + self.value + } + + fn input(&self) -> &Bytes { + &self.input + } + + fn access_list(&self) -> Option<&AccessList> { + None + } + + fn blob_versioned_hashes(&self) -> Option<&[B256]> { + None + } + + fn authorization_list(&self) -> Option<&[SignedAuthorization]> { + None + } + } + + #[derive(Debug, Clone)] + struct MockRecoveredTx { + tx: TxEnv, + signer: Address, + } + + impl RecoveredTx for MockRecoveredTx { + fn tx(&self) -> &TxEnv { + &self.tx + } + + fn signer(&self) -> &Address { + &self.signer + } + } + + impl IntoTxEnv for MockRecoveredTx { + fn into_tx_env(self) -> TxEnv { + self.tx + } + } + + fn legacy_tx() -> TxLegacy { + TxLegacy { + chain_id: Some(1), + nonce: 7, + gas_price: 9, + gas_limit: 21_000, + to: TxKind::Call(CONTRACT), + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + } + } + + fn legacy_envelope() -> MegaTxEnvelope { + MegaTxEnvelope::Legacy(Signed::new_unchecked( + legacy_tx(), + Signature::test_signature(), + Default::default(), + )) + } + + #[test] + fn test_mega_transaction_ext_works_for_envelope_and_recovered_types() { + let tx = legacy_envelope(); + let recovered = Recovered::new_unchecked(tx.clone(), CALLER); + + assert_eq!(MegaTransactionExt::tx_hash(&tx), tx.tx_hash()); + assert_eq!(MegaTransactionExt::tx_hash(&recovered), tx.tx_hash()); + assert!(MegaTransactionExt::estimated_da_size(&tx) > 0); + assert!(MegaTransactionExt::tx_size(&tx) > 0); + } + + #[test] + fn test_enriched_mega_tx_new_slow_computes_hash_and_sizes() { + let tx = MockTx { + nonce: 7, + gas_limit: 21_000, + value: U256::from(11), + input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), + }; + let expected_hash = tx.trie_hash(); + let expected_da_size = + op_alloy_flz::tx_estimated_size_fjord_bytes(tx.encoded_2718().as_slice()); + let expected_tx_size = tx.encode_2718_len() as u64; + + let enriched = EnrichedMegaTx::new_slow(tx); + + assert_eq!(MegaTransactionExt::tx_hash(&enriched), expected_hash); + assert_eq!(enriched.da_size, expected_da_size); + assert_eq!(enriched.tx_size, expected_tx_size); + assert_eq!(enriched.nonce(), 7); + assert_eq!(enriched.gas_limit(), 21_000); + assert_eq!(enriched.value(), U256::from(11)); + assert_eq!(enriched.kind(), TxKind::Call(CONTRACT)); + } + + #[test] + fn test_enriched_mega_tx_delegates_recovered_transaction_methods() { + let tx_env = TxEnv { + caller: CALLER, + gas_limit: 21_000, + kind: TxKind::Call(CONTRACT), + value: U256::from(11), + data: Bytes::from_static(&[0xaa, 0xbb]), + ..Default::default() + }; + let recovered = MockRecoveredTx { tx: tx_env.clone(), signer: CALLER }; + let enriched = EnrichedMegaTx::new(recovered, TxHash::ZERO, 1, 2); + + assert_eq!(enriched.tx(), &tx_env); + assert_eq!(*enriched.signer(), CALLER); + + let converted: TxEnv = enriched.into_tx_env(); + assert_eq!(converted, tx_env); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/limit.rs b/crates/mega-evm/tests/_pending/src/block/limit.rs new file mode 100644 index 000000000..ebe3786ae --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/limit.rs @@ -0,0 +1,97 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/limit.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/limit.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::B256; + + fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_gas_limit = block_gas_limit; + limits.tx_gas_limit = u64::MAX; + limits + } + + fn limits_with_block_tx_size(block_txs_encode_size_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_txs_encode_size_limit = block_txs_encode_size_limit; + limits + } + + fn limits_with_block_da_size(block_da_size_limit: u64) -> BlockLimits { + let mut limits = BlockLimits::no_limits(); + limits.block_da_size_limit = block_da_size_limit; + limits + } + + #[test] + fn test_pre_execution_check_block_gas_addition_saturates() { + // Block has very high accumulated usage and a transaction with a near-`u64::MAX` + // gas limit; unchecked addition would wrap and accidentally pass the limit check. + let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); + limiter.block_gas_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); + assert!(result.is_err(), "saturating_add must keep the rejection in place"); + } + + #[test] + fn test_pre_execution_check_block_tx_size_addition_saturates() { + let mut limiter = BlockLimiter::new(limits_with_block_tx_size(1_000_000)); + limiter.block_tx_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); + assert!(result.is_err()); + } + + #[test] + fn test_pre_execution_check_block_da_size_addition_saturates() { + let mut limiter = BlockLimiter::new(limits_with_block_da_size(1_000_000)); + limiter.block_da_size_used = u64::MAX - 10; + let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); + assert!(result.is_err()); + } + + #[test] + fn test_post_execution_update_raw_saturates_all_counters() { + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_gas_used = u64::MAX - 1; + limiter.block_tx_size_used = u64::MAX - 1; + limiter.block_da_size_used = u64::MAX - 1; + limiter.block_data_used = u64::MAX - 1; + limiter.block_kv_updates_used = u64::MAX - 1; + limiter.block_compute_gas_used = u64::MAX - 1; + limiter.block_state_growth_used = u64::MAX - 1; + + limiter.post_execution_update_raw( + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + u64::MAX, + false, + ); + + assert_eq!(limiter.block_gas_used, u64::MAX); + assert_eq!(limiter.block_tx_size_used, u64::MAX); + assert_eq!(limiter.block_da_size_used, u64::MAX); + assert_eq!(limiter.block_data_used, u64::MAX); + assert_eq!(limiter.block_kv_updates_used, u64::MAX); + assert_eq!(limiter.block_compute_gas_used, u64::MAX); + assert_eq!(limiter.block_state_growth_used, u64::MAX); + } + + #[test] + fn test_post_execution_update_raw_skips_da_for_deposits() { + // Deposit transactions should not advance `block_da_size_used`, even when the value + // would otherwise saturate. + let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + limiter.block_da_size_used = 100; + + limiter.post_execution_update_raw(0, 0, u64::MAX, 0, 0, 0, 0, true); + + assert_eq!(limiter.block_da_size_used, 100); + } +} diff --git a/crates/mega-evm/tests/_pending/src/block/result.rs b/crates/mega-evm/tests/_pending/src/block/result.rs new file mode 100644 index 000000000..a0c55ca24 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/block/result.rs @@ -0,0 +1,65 @@ +//! Unit tests extracted from `crates/mega-evm/src/block/result.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/block/result.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_transaction_limit_error_reports_usage_and_limit() { + let cases = [ + (MegaTxLimitExceededError::TransactionGasLimit { tx_gas_limit: 31, limit: 30 }, 31, 30), + ( + MegaTxLimitExceededError::TransactionEncodeSizeLimit { tx_size: 101, limit: 100 }, + 101, + 100, + ), + ( + MegaTxLimitExceededError::DataAvailabilitySizeLimit { da_size: 11, limit: 10 }, + 11, + 10, + ), + ]; + + for (error, expected_usage, expected_limit) in cases { + assert_eq!(error.usage(), expected_usage); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + } + } + + #[test] + fn test_block_limit_error_reports_block_usage_and_limit() { + let cases = [ + (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + (MegaBlockLimitExceededError::KVUpdateLimit { block_used: 2, limit: 11 }, 2, 11), + (MegaBlockLimitExceededError::ComputeGasLimit { block_used: 3, limit: 12 }, 3, 12), + ( + MegaBlockLimitExceededError::TransactionEncodeSizeLimit { + block_used: 4, + tx_used: 1, + limit: 13, + }, + 4, + 13, + ), + ( + MegaBlockLimitExceededError::DataAvailabilitySizeLimit { + block_used: 5, + tx_used: 1, + limit: 14, + }, + 5, + 14, + ), + (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 6, limit: 15 }, 6, 15), + ]; + + for (error, expected_block_used, expected_limit) in cases { + assert_eq!(error.block_used(), expected_block_used); + assert_eq!(error.limit(), expected_limit); + assert!(!error.is_nonce_too_low()); + } + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/context.rs b/crates/mega-evm/tests/_pending/src/evm/context.rs new file mode 100644 index 000000000..de57bad9d --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/context.rs @@ -0,0 +1,50 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/context.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/context.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + use alloy_primitives::address; + use revm::{context::CfgEnv, database::EmptyDB}; + + use crate::TestExternalEnvs; + + /// Sharing SALT env handles between parent and sandbox must not merge their bucket caches. + #[test] + fn test_shared_salt_env_keeps_dynamic_gas_cache_isolated() { + let external_envs = TestExternalEnvs::new(); + let parent = MegaContext::new(EmptyDB::default(), MegaSpecId::REX4) + .with_external_envs(external_envs.into()); + let parent_address = address!("0000000000000000000000000000000000100001"); + let sandbox_address = address!("0000000000000000000000000000000000100002"); + + parent + .dynamic_storage_gas_cost + .borrow_mut() + .new_account_gas(parent_address) + .expect("parent bucket lookup should succeed"); + let parent_bucket_ids = parent.accessed_bucket_ids(); + + let sandbox = + MegaContext::<_, TestExternalEnvs>::new_with_shared_ext_envs( + EmptyDB::default(), + MegaSpecId::REX4, + Rc::clone(&parent.salt_env), + Rc::clone(&parent.oracle_env), + ) + .with_block(parent.block().clone()) + .with_chain(parent.chain().clone()) + .with_inside_sandbox(true); + sandbox + .dynamic_storage_gas_cost + .borrow_mut() + .new_account_gas(sandbox_address) + .expect("sandbox bucket lookup should succeed"); + + assert_eq!(parent.accessed_bucket_ids(), parent_bucket_ids); + assert_ne!(sandbox.accessed_bucket_ids(), parent_bucket_ids); + } + +} diff --git a/crates/mega-evm/tests/_pending/src/evm/factory.rs b/crates/mega-evm/tests/_pending/src/evm/factory.rs new file mode 100644 index 000000000..6e3a8b9da --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/factory.rs @@ -0,0 +1,31 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/factory.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/factory.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_dyn_precompiles_builder_receives_the_behavior_spec() { + use alloy_evm::EvmFactory as _; + use core::sync::atomic::{AtomicU8, Ordering}; + + // The builder must see the behavior projection, never an alias rung: an external + // builder keyed on exact specs would otherwise install a different precompile set + // during a rollback window. + static SEEN_SPEC: AtomicU8 = AtomicU8::new(u8::MAX); + + let factory = + MegaEvmFactory::new().with_dyn_precompiles_builder(std::sync::Arc::new(|spec| { + SEEN_SPEC.store(spec as u8, Ordering::SeqCst); + revm::primitives::HashMap::default() + })); + + let mut evm_env = EvmEnv::::default(); + evm_env.cfg_env.spec = MegaSpecId::MINI_REX_1; + let _evm = factory.create_evm(crate::test_utils::MemoryDatabase::default(), evm_env); + + assert_eq!(SEEN_SPEC.load(Ordering::SeqCst), MegaSpecId::EQUIVALENCE as u8); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/host.rs b/crates/mega-evm/tests/_pending/src/evm/host.rs new file mode 100644 index 000000000..534e16b6b --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/host.rs @@ -0,0 +1,123 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/host.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/host.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, keccak256}; + use core::cell::Cell; + use revm::{ + primitives::HashMap, + state::{AccountInfo, Bytecode}, + Database, + }; + + /// Minimal `revm::Database` implementation that mimics the production + /// `reth`-style `StateProviderDatabase` contract: `basic()` returns + /// `AccountInfo { code: None, code_hash: }` for accounts with + /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via + /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — + /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache + /// miss against it would always see the code already hydrated. + #[derive(Default)] + struct LazyCodeDatabase { + accounts: HashMap, + codes: HashMap, + storage_calls: Cell, + } + + impl LazyCodeDatabase { + fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { + let code = Bytecode::new_raw(bytecode); + let code_hash = code.hash_slow(); + self.accounts.insert( + address, + AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, + ); + self.codes.insert(code_hash, code); + self + } + + fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { + let code = Bytecode::new_eip7702(delegate); + let code_hash = code.hash_slow(); + self.accounts.insert( + address, + AccountInfo { balance: U256::ZERO, nonce: 0, code_hash, code: None }, + ); + self.codes.insert(code_hash, code); + self + } + + fn storage_calls(&self) -> usize { + self.storage_calls.get() + } + } + + impl revm::Database for LazyCodeDatabase { + type Error = core::convert::Infallible; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without + // populating `code`, even when the account has on-chain bytecode. + Ok(self.accounts.get(&address).cloned()) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) + } + + fn storage(&mut self, _address: Address, _index: U256) -> Result { + self.storage_calls.set(self.storage_calls.get() + 1); + Ok(U256::ZERO) + } + + fn block_hash(&mut self, _number: u64) -> Result { + Ok(B256::ZERO) + } + } + + /// On REX5+, `inspect_account_delegated` must follow the EIP-7702 hop on the + /// very first cold inspection against a lazy-code database. Regression guard: + /// any refactor that re-introduces a code-None branch silently degrades the + /// walk to "treat the delegator as a regular EOA". + #[test] + fn test_inspect_account_delegated_follows_eip7702_on_cold_first_touch() { + use revm::context::JournalTr; + + const DELEGATOR: Address = address!("00000000000000000000000000000000000000d1"); + const DELEGATE: Address = address!("00000000000000000000000000000000000000d2"); + let delegate_bytecode = Bytes::from_static(&[0x60, 0x42, 0x60, 0x00, 0x55]); // PUSH1 0x42 PUSH1 0 SSTORE + + let db = LazyCodeDatabase::default() + .with_eip7702_delegation(DELEGATOR, DELEGATE) + .with_account_code(DELEGATE, delegate_bytecode.clone()); + + let mut journal = Journal::new(db); + + let resolved = journal + .inspect_account_delegated(MegaSpecId::REX5, DELEGATOR) + .expect("inspect_account_delegated must succeed on a cold-cache first touch"); + + // The resolved account must be the delegate, not the delegator. The only way + // to distinguish them is the code: the delegator's code is the EIP-7702 + // designation pointing at DELEGATE; the delegate's code is the raw bytecode. + let hydrated = resolved.info.code.as_ref().expect( + "delegate's bytecode must be hydrated by the inner inspect_account call — \ + without the vacant-path hydration, the cold-touch on DELEGATE would leave \ + code as None and any subsequent EIP-7702 walk would see a wrongly-empty target", + ); + assert!( + !matches!(hydrated, Bytecode::Eip7702(_)), + "resolved account must NOT be the delegator (whose code is the EIP-7702 \ + designation); got: {hydrated:?}", + ); + assert_eq!( + hydrated.original_bytes().as_ref(), + delegate_bytecode.as_ref(), + "resolved account's code must match the delegate's raw bytecode — confirms \ + the delegation was followed exactly one hop", + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs new file mode 100644 index 000000000..e0f5e2abd --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/mod.rs @@ -0,0 +1,111 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/mod.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/mod.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use alloy_primitives::{address, Bytes, U256}; + use revm::{ + context::{ + result::{ExecResultAndState, ExecutionResult}, + ContextSetters, TxEnv, + }, + database::State, + inspector::NoOpInspector, + state::EvmState, + ExecuteCommitEvm, ExecuteEvm, InspectEvm, SystemCallEvm, + }; + + const CALLER: Address = address!("4000000000000000000000000000000000000001"); + const CALLEE: Address = address!("5000000000000000000000000000000000000001"); + + fn configure_context(db: DB) -> MegaContext { + let mut context = MegaContext::new(db, MegaSpecId::REX4); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + context + } + + fn tx_env() -> TxEnv { + TxEnv { + caller: CALLER, + gas_limit: 100_000, + kind: alloy_primitives::TxKind::Call(CALLEE), + value: U256::ZERO, + data: Bytes::new(), + ..Default::default() + } + } + + fn mega_tx() -> MegaTransaction { + let mut tx = MegaTransaction::new(tx_env()); + tx.enveloped_tx = Some(Bytes::new()); + tx + } + + #[test] + fn test_revm_system_call_with_caller_works() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + let system_call: ExecutionResult = + SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) + .unwrap(); + assert!(system_call.is_success()); + } + + #[test] + fn test_transact_system_call_with_gas_limit_uses_passed_value() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut evm = MegaEvm::new(configure_context(&mut db)); + + let result = evm + .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) + .unwrap(); + assert!(result.result.is_success()); + // The custom gas limit must be applied to the underlying tx. + assert_eq!(evm.inner.ctx.tx.base.gas_limit, 123_456_789); + } + + #[test] + fn test_default_system_call_keeps_upstream_30m_gas_limit() { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(CALLEE, Bytes::new()); + let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + context.block.gas_limit = 100_000_000; + let mut evm = MegaEvm::new(context); + + // The default system-call entry point must NOT be widened by REX5 — only the + // explicit `transact_system_call_with_gas_limit` path should pick up the live + // block budget. This preserves byte-level behavior of EIP-2935 / EIP-4788 + // pre-block calls across all specs. + SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) + .unwrap(); + // Literal, not `SYSTEM_CALL_GAS_LIMIT_FLOOR`: this assertion verifies revm's + // upstream hardcoded default. If upstream ever drifts from our floor, this + // test should fail loudly rather than be auto-aligned by our constant. + assert_eq!(evm.inner.ctx.tx.base.gas_limit, 30_000_000); + } + + #[test] + fn test_mega_evm_exposes_state_wrapper_block_hashes() { + let mut db = MemoryDatabase::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(7, B256::from([7_u8; 32])); + + let evm = MegaEvm::new(configure_context(&mut state)); + assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); + } +} diff --git a/crates/mega-evm/tests/_pending/src/evm/precompiles.rs b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs new file mode 100644 index 000000000..8f5e776b3 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/precompiles.rs @@ -0,0 +1,211 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/precompiles.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/precompiles.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + #[cfg(not(feature = "std"))] + use alloc as std; + use std::{rc::Rc, vec::Vec}; + + use super::{kzg_point_evaluation::GAS_COST, mini_rex, rex, MegaPrecompiles}; + use crate::{ + test_utils::MemoryDatabase, AdditionalLimit, EvmTxRuntimeLimits, MegaContext, MegaSpecId, + }; + use alloy_evm::precompiles::PrecompilesMap; + use alloy_primitives::Bytes; + use core::cell::RefCell; + use revm::{ + handler::PrecompileProvider, + interpreter::{InputsImpl, InstructionResult}, + }; + use sha2::{Digest, Sha256}; + + /// Generate valid KZG Point Evaluation test data from EIP-4844 test vectors. + fn generate_kzg_test_input() -> InputsImpl { + let commitment = hex::decode("8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7").unwrap(); + let mut versioned_hash = Sha256::digest(&commitment).to_vec(); + versioned_hash[0] = 0x01; // VERSIONED_HASH_VERSION_KZG + let z = hex::decode("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000") + .unwrap(); + let y = hex::decode("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9") + .unwrap(); + let proof = hex::decode("a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c").unwrap(); + + let mut input = Vec::new(); + input.extend_from_slice(&versioned_hash); + input.extend_from_slice(&z); + input.extend_from_slice(&y); + input.extend_from_slice(&commitment); + input.extend_from_slice(&proof); + + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + InputsImpl { + target_address: address, + bytecode_address: Some(address), + caller_address: address, + input: revm::interpreter::CallInput::Bytes(Bytes::from(input)), + call_value: Default::default(), + } + } + + /// Mirror of `generate_kzg_test_input()` but with the last byte of the proof + /// flipped — structurally valid (192 bytes, matching versioned hash) but + /// upstream verification returns `PrecompileError::BlobVerifyKzgProofFailed`. + fn generate_invalid_proof_kzg_test_input() -> InputsImpl { + let mut inputs = generate_kzg_test_input(); + let bytes = match inputs.input { + revm::interpreter::CallInput::Bytes(b) => b, + _ => panic!("expected Bytes"), + }; + let mut buf = bytes.to_vec(); + let last = buf.len() - 1; + buf[last] ^= 0x01; + inputs.input = revm::interpreter::CallInput::Bytes(Bytes::from(buf)); + inputs + } + + fn set_spec_for_context( + precompiles_map: &mut PrecompilesMap, + _context: &MegaContext, + spec: op_revm::OpSpecId, + ) -> bool { + >>::set_spec( + precompiles_map, + spec, + ) + } + + #[test] + fn test_kzg_precompile_sufficient_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); + assert!(result.is_ok(), "Precompile should succeed with sufficient gas"); + let output = result.unwrap().unwrap(); + assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_kzg_precompile_exact_gas_limit() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST); + assert!(result.is_ok(), "Precompile should succeed with exact GAS_COST"); + let output = result.unwrap().unwrap(); + assert!(matches!(output.result, InstructionResult::Return), "Result should be Return"); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_set_spec_preserves_mega_kzg_override() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + + let changed = + set_spec_for_context(&mut precompiles_map, &context, op_revm::OpSpecId::ISTHMUS); + assert!(!changed, "Mega precompile table must remain unchanged"); + + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + let result = precompiles_map.run(&mut context, &address, &inputs, true, 200_000); + let output = result.expect("run ok").expect("Some output"); + assert!(matches!(output.result, InstructionResult::Return)); + assert_eq!(output.gas.spent(), GAS_COST); + } + + #[test] + fn test_kzg_precompile_insufficient_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 50_000); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + #[test] + fn test_kzg_precompile_one_below_gas_limit() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, GAS_COST - 1); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + #[test] + fn test_kzg_precompile_zero_gas() { + let mut db = MemoryDatabase::default(); + let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX); + let mut precompiles_map = PrecompilesMap::from_static( + MegaPrecompiles::new_with_spec(MegaSpecId::MINI_REX).precompiles(), + ); + let inputs = generate_kzg_test_input(); + let address = revm::precompile::kzg_point_evaluation::ADDRESS; + + let result = precompiles_map.run(&mut context, &address, &inputs, true, 0); + assert!(result.is_ok(), "Should not panic"); + let output = result.unwrap(); + assert!(output.is_some(), "Precompile should return Some(result)"); + let interpreter_result = output.unwrap(); + assert!( + matches!(interpreter_result.result, InstructionResult::PrecompileOOG), + "Result should be PrecompileOOG" + ); + } + + /// Replaces the context's `additional_limit` with one whose `tx_compute_gas_limit` + /// is set to `limit`, so tests can exercise the REX5 compute-gas cap path with a + /// small remaining budget without having to pre-record large gas amounts. + fn set_tx_compute_gas_limit( + context: &mut MegaContext, + spec: MegaSpecId, + limit: u64, + ) { + let tx_limits = EvmTxRuntimeLimits { + tx_compute_gas_limit: limit, + ..EvmTxRuntimeLimits::from_spec(spec) + }; + context.additional_limit = Rc::new(RefCell::new(AdditionalLimit::new(spec, tx_limits))); + } + +} diff --git a/crates/mega-evm/tests/_pending/src/evm/state.rs b/crates/mega-evm/tests/_pending/src/evm/state.rs new file mode 100644 index 000000000..54b6172b8 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/evm/state.rs @@ -0,0 +1,43 @@ +//! Unit tests extracted from `crates/mega-evm/src/evm/state.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/state.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, Address, B256, U256}; + use revm::{ + database::{InMemoryDB, State}, + state::{AccountInfo, EvmStorageSlot}, + }; + + const TEST_ADDRESS: Address = address!("1000000000000000000000000000000000000001"); + + fn account_with_status(status: AccountStatus) -> Account { + Account { + info: AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: B256::ZERO, + code: None, + }, + transaction_id: 0, + storage: Default::default(), + status, + } + } + + #[test] + fn test_state_exposes_accessed_block_hashes() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + state.block_hashes.insert(1, B256::ZERO); + state.block_hashes.insert(2, B256::from([2_u8; 32])); + + let hashes = state.get_accessed_block_hashes(); + assert_eq!(hashes.len(), 2); + assert_eq!(hashes.get(&1), Some(&B256::ZERO)); + assert_eq!(hashes.get(&2), Some(&B256::from([2_u8; 32]))); + } + +} diff --git a/crates/mega-evm/tests/_pending/src/external/gas.rs b/crates/mega-evm/tests/_pending/src/external/gas.rs new file mode 100644 index 000000000..271776c5d --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/external/gas.rs @@ -0,0 +1,120 @@ +//! Unit tests extracted from `crates/mega-evm/src/external/gas.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/external/gas.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::external::test_utils::TestExternalEnvs; + + fn cost_with_capacity(spec: MegaSpecId, capacity: u64) -> DynamicGasCost { + // Map the bucket id that the simple bucket hasher will produce for the zero address / + // zero slot to the requested capacity. + let bucket_for_account = + ::bucket_id_for_account(Address::ZERO); + let bucket_for_slot = + ::bucket_id_for_slot(Address::ZERO, U256::ZERO); + let env = TestExternalEnvs::new() + .with_bucket_capacity(bucket_for_account, capacity) + .with_bucket_capacity(bucket_for_slot, capacity); + DynamicGasCost::new(spec, env, 0) + } + + /// `MIN_BUCKET_SIZE * u64::MAX` cannot be represented in `u64`; verify the hardened + /// arithmetic does not panic and saturates instead of wrapping. + #[test] + fn test_sstore_set_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + #[test] + fn test_new_account_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.new_account_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.new_account_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + #[test] + fn test_create_contract_gas_saturates_on_huge_multiplier() { + let mut cost = cost_with_capacity(MegaSpecId::REX, u64::MAX); + let gas = cost.create_contract_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + + let mut cost = cost_with_capacity(MegaSpecId::MINI_REX, u64::MAX); + let gas = cost.create_contract_gas(Address::ZERO).unwrap(); + assert_eq!(gas, u64::MAX); + } + + /// REX6 system-exempt path: the unscaled cost (`multiplier = 1`) is `0` for the REX-family + /// formula `base × (multiplier − 1)`, and is independent of the actual bucket capacity. This + /// is what makes a system call's storage cost immune to SALT bucket scaling. + #[test] + fn test_unscaled_gas_is_zero_for_rex_and_independent_of_capacity() { + for capacity in [MIN_BUCKET_SIZE as u64, 1_280_000, u64::MAX] { + let cost = cost_with_capacity(MegaSpecId::REX6, capacity); + assert_eq!(cost.sstore_set_gas_unscaled(), 0); + assert_eq!(cost.new_account_gas_unscaled(), 0); + assert_eq!(cost.create_contract_gas_unscaled(), 0); + } + } + + /// The unscaled helpers are REX-family API: pin the debug assert exactly at the REX + /// boundary (the first spec where the `base × (multiplier − 1)` formula exists), so a + /// tightened gate (e.g. REX1) fails here. + #[test] + fn test_unscaled_gas_is_available_from_rex_exactly() { + let cost = cost_with_capacity(MegaSpecId::REX, MIN_BUCKET_SIZE as u64); + assert_eq!(cost.sstore_set_gas_unscaled(), 0); + assert_eq!(cost.new_account_gas_unscaled(), 0); + assert_eq!(cost.create_contract_gas_unscaled(), 0); + } + + /// Pre-REX callers must trip the debug assert — a loosened gate (e.g. `MiniRex`) would + /// silently serve the REX-family formula to a spec that prices storage differently. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_sstore_set_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .sstore_set_gas_unscaled(); + } + + /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_new_account_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .new_account_gas_unscaled(); + } + + /// See [`test_sstore_set_gas_unscaled_asserts_pre_rex`]. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "assertion failed")] + fn test_create_contract_gas_unscaled_asserts_pre_rex() { + let _ = cost_with_capacity(MegaSpecId::MINI_REX, MIN_BUCKET_SIZE as u64) + .create_contract_gas_unscaled(); + } + + /// The unscaled result equals the SALT-driven result evaluated at the minimum bucket + /// capacity, confirming the shared formula helper produces consistent values across both paths. + #[test] + fn test_unscaled_matches_salt_path_at_min_capacity() { + let mut cost = cost_with_capacity(MegaSpecId::REX6, MIN_BUCKET_SIZE as u64); + assert_eq!( + cost.sstore_set_gas_unscaled(), + cost.sstore_set_gas(Address::ZERO, U256::ZERO).unwrap(), + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs new file mode 100644 index 000000000..8696695dc --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs @@ -0,0 +1,28 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/compute_gas.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/compute_gas.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// Usage exactly equal to the detained limit must NOT count as a detained exceed: + /// the predicate is strictly-greater-than (`used > detained_limit`), not `>=`. + #[test] + fn test_is_detained_exceed_is_strict_at_boundary() { + // tx_limit = 100, detained lowered to 50 (< tx_limit, so detention is binding). + let mut tracker = ComputeGasTracker::new(MegaSpecId::MINI_REX, 100); + tracker.set_detained_limit(50); + + // Usage exactly at the detained limit: not exceeded. + tracker.record_gas_used(50); + assert!( + !tracker.is_detained_exceed(), + "usage == detained_limit must not be a detained exceed" + ); + + // One unit over the limit: exceeded. + tracker.record_gas_used(1); + assert!(tracker.is_detained_exceed(), "usage > detained_limit must be a detained exceed"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/data_size.rs b/crates/mega-evm/tests/_pending/src/limit/data_size.rs new file mode 100644 index 000000000..e7a8ba712 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/data_size.rs @@ -0,0 +1,26 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/data_size.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/data_size.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// The originated data-size constants are *sums* of their salt key/value components, + /// not products. Pin the values against independent literals so an arithmetic slip + /// (e.g. `+` -> `*`) is caught (8 + 32 = 40, not 8 * 32 = 256). + #[test] + fn test_originated_data_size_constants() { + assert_eq!(STORAGE_SLOT_WRITE_SIZE, 40); + assert_eq!(ACCOUNT_INFO_WRITE_SIZE, 40); + } + + /// `has_active_frame` must reflect the underlying frame stack, not a constant. + #[test] + fn test_has_active_frame_reflects_frame_stack() { + let mut tracker = DataSizeTracker::new(MegaSpecId::MINI_REX, u64::MAX); + assert!(!tracker.has_active_frame(), "no frame pushed yet"); + tracker.push_empty_frame(); + assert!(tracker.has_active_frame(), "a frame is on the stack"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs new file mode 100644 index 000000000..f7d03325d --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs @@ -0,0 +1,19 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/kv_update.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/kv_update.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + + /// `record_account_update` must charge exactly one KV update against the current frame + /// (used by REX5+ SELFDESTRUCT-beneficiary metering); it must not be a no-op. + #[test] + fn test_record_account_update_charges_one_kv() { + let mut tracker = KVUpdateTracker::new(MegaSpecId::MINI_REX, u64::MAX); + tracker.push_empty_frame(); + assert_eq!(tracker.tx_usage(), 0); + tracker.record_account_update(); + assert_eq!(tracker.tx_usage(), 1, "record_account_update must add exactly 1 KV update"); + } +} diff --git a/crates/mega-evm/tests/_pending/src/limit/limit.rs b/crates/mega-evm/tests/_pending/src/limit/limit.rs new file mode 100644 index 000000000..8a2bdf354 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/limit/limit.rs @@ -0,0 +1,98 @@ +//! Unit tests extracted from `crates/mega-evm/src/limit/limit.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/limit.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod metering_exemption_tests { + use super::*; + + /// Tiny per-dimension limits so a single recording trivially exceeds them. + fn tiny_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits { + tx_data_size_limit: 1, + tx_kv_updates_limit: 1, + tx_compute_gas_limit: 1, + tx_state_growth_limit: 1, + block_env_access_compute_gas_limit: u64::MAX, + oracle_access_compute_gas_limit: u64::MAX, + } + } + + #[test] + fn test_metering_enforced_when_not_exempt() { + // Default (non-exempt): halted once compute gas exceeds the (tiny) limit. The REX6 × + // system-origin gate that would stamp `Exempt` lives in `MegaContext::on_new_tx`; here we + // exercise the tracker directly. + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + assert!(!al.record_compute_gas(1_000_000), "non-exempt tx must report exceeded limit"); + assert!(al.check_limit().exceeded_limit()); + } + + #[test] + fn test_metering_bypassed_when_exempt() { + // When the system-tx exemption is stamped, `check_limit` short-circuits on the sticky + // `Exempt` state, covering the four dimensions *and* gas detention, so the same + // over-limit usage never halts. Usage is still recorded (only the halt decision is + // suppressed). + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + al.mark_exempt(); + assert!(al.record_compute_gas(1_000_000), "exempt tx must not report exceeded limit"); + assert!(!al.check_limit().exceeded_limit()); + assert!(al.check_limit().is_exempt(), "check_limit must surface the sticky Exempt state"); + assert!(al.get_usage().compute_gas >= 1_000_000, "usage is still accumulated while exempt"); + } + + #[test] + fn test_detained_compute_gas_does_not_halt_when_exempt() { + // Gas detention lowers the detained compute-gas limit; enforcement runs through the same + // `check_limit` chokepoint, so the exemption neutralizes detention too. + let mut al = + AdditionalLimit::new(MegaSpecId::REX6, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX6)); + al.mark_exempt(); + al.set_compute_gas_limit(1); // detain hard + assert!(al.record_compute_gas(10_000_000), "exempt tx must ignore gas detention"); + assert!(!al.check_limit().exceeded_limit()); + } + + #[test] + fn test_reset_clears_exempt() { + // The sticky `Exempt` state must not leak to the next transaction reusing the same tracker. + let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); + al.mark_exempt(); + assert!(al.has_exceeded_limit.is_exempt()); + al.reset(); + assert!(!al.has_exceeded_limit.is_exempt(), "reset must clear the sticky Exempt state"); + assert!( + al.has_exceeded_limit.within_limit(), + "reset must restore the WithinLimit baseline" + ); + assert!(!al.record_compute_gas(1_000_000), "after reset, metering is enforced again"); + } +} + +#[cfg(test)] +mod tests { + use revm::context::tx::TxEnvBuilder; + + use super::{super::LimitKind, *}; + + fn test_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits { + tx_data_size_limit: 100, + tx_kv_updates_limit: 1_000, + tx_compute_gas_limit: 1_000_000, + tx_state_growth_limit: 1_000, + block_env_access_compute_gas_limit: 1_000_000, + oracle_access_compute_gas_limit: 1_000_000, + } + } + + /// Returns the latched limit kind, or `None` when within limit. + fn latched_kind(limit: &AdditionalLimit) -> Option { + match limit.has_exceeded_limit { + LimitCheck::ExceedsLimit { kind, .. } => Some(kind), + LimitCheck::WithinLimit | LimitCheck::Exempt => None, + } + } + +} diff --git a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs new file mode 100644 index 000000000..10b913932 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs @@ -0,0 +1,159 @@ +//! Unit tests extracted from `crates/mega-evm/src/sandbox/execution.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/execution.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use revm::context::result::Output; + + /// Test error type that lets us drive `process_sandbox_transact_result`'s + /// `Err` arms (which map to `SandboxOutcome::Rejected`) directly without + /// standing up a full sandbox EVM. The two arms differ only by + /// `IsTxError::is_tx_error()`, so a single struct with a configurable flag + /// covers both selector mappings. + struct FakeTxErr { + is_tx: bool, + msg: &'static str, + } + + impl core::fmt::Display for FakeTxErr { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(self.msg) + } + } + + impl IsTxError for FakeTxErr { + fn is_tx_error(&self) -> bool { + self.is_tx + } + } + + /// `validate_signer_code` MUST be a no-op when `cfg.disable_eip3607 = true`, even + /// when the provided `AccountInfo` has bytecode that would otherwise trip the + /// caller-with-code check. Mirrors the canonical revm `validate_account_nonce_and_code` + /// semantics and pins the early-return contract. + #[test] + fn test_validate_signer_code_disable_eip3607_short_circuits() { + use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; + use revm::{ + bytecode::Bytecode, + primitives::{keccak256, Bytes as PrimitivesBytes}, + }; + + let code_bytes = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); + let code_hash = keccak256(&code_bytes); + let signer_info = AccountInfo { + nonce: 0, + balance: U256::ZERO, + code_hash, + code: Some(Bytecode::new_raw(code_bytes)), + }; + + let mut ctx = + MegaContext::<_, EmptyExternalEnv>::new(MemoryDatabase::default(), MegaSpecId::REX5); + ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); + + let out = validate_signer_code(&ctx, &signer_info); + assert!( + matches!(out, Ok(())), + "disable_eip3607 must short-circuit before the code inspection; got {out:?}", + ); + } + + /// `charge_caller_materialization_pre_sandbox` MUST surface a SALT/dynamic-gas failure + /// as `Err(KeylessDeployError::InternalError)` without writing to `ctx.error()`. + /// + /// The contract is load-bearing: op-revm's `Handler::execution_result` drains + /// `ctx.error()` and converts any non-empty `ContextError` into an EVM-level + /// `Err(Custom(...))`. Routing a SALT failure through the + /// `HostExt::new_account_storage_gas` helper — which stashes the error into + /// `ctx.error()` — would promote an interceptor-level failure into a whole-transaction + /// execution error and break the `InternalError()` selector contract. The + /// pre-sandbox charge path must therefore call `DynamicGasCost::new_account_gas` + /// directly and keep the error local. + #[test] + fn test_charge_caller_materialization_salt_failure_returns_internal_error_without_ctx_pollution( + ) { + use crate::{test_utils::MemoryDatabase, BucketId, OracleEnv, SaltEnv}; + use alloy_primitives::{address, B256}; + use core::fmt::{self, Display, Formatter}; + + // Minimal `SaltEnv` whose `get_bucket_capacity` always fails. This drives + // `DynamicGasCost::new_account_gas` (called from + // `charge_caller_materialization_pre_sandbox`) to return `Err`, exercising the + // failure-handling path under test. + #[derive(Debug, Clone, Copy)] + struct AlwaysFailSalt; + + #[derive(Debug, Clone)] + struct InjectedSaltError; + impl Display for InjectedSaltError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str("injected SALT failure") + } + } + + impl SaltEnv for AlwaysFailSalt { + type Error = InjectedSaltError; + fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { + Err(InjectedSaltError) + } + fn bucket_id_for_account(_account: Address) -> BucketId { + 0 + } + fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { + 0 + } + } + + #[derive(Debug, Clone, Copy)] + struct NoopOracle; + impl OracleEnv for NoopOracle { + fn get_oracle_storage(&self, _slot: U256) -> Option { + None + } + fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} + } + + let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); + let db = MemoryDatabase::default(); + let envs: crate::ExternalEnvs<(AlwaysFailSalt, NoopOracle)> = + crate::ExternalEnvs { salt_env: AlwaysFailSalt, oracle_env: NoopOracle }; + let mut ctx = MegaContext::new(db, MegaSpecId::REX5).with_external_envs(envs); + + let mut gas = Gas::new(10_000_000); + let return_memory_offset = 0..0; + + // Signer is unmaterialized (default `AccountInfo` is `is_empty()` == true) + // → the materialization branch fires. + let signer_info = AccountInfo::default(); + let out = charge_caller_materialization_pre_sandbox( + &ctx, + &mut gas, + signer, + &signer_info, + &return_memory_offset, + ); + assert!( + matches!(out, Err(KeylessDeployError::InternalError)), + "SALT failure must surface as InternalError, got {out:?}", + ); + + // The whole point of the fix: ctx.error() must NOT have been polluted, so the outer + // transaction's `execution_result` doesn't drain it into `Err(Custom)`. + let ctx_error = core::mem::replace(ctx.error(), Ok(())); + assert!( + matches!(ctx_error, Ok(())), + "ctx.error() must remain Ok after a SALT failure in the pre-sandbox charge; \ + got {ctx_error:?}", + ); + + // record_deposit_caller_creation must NOT have fired either. + assert_eq!( + ctx.additional_limit.borrow().get_usage().state_growth, + 0, + "deposit-caller state-growth must not be recorded when the storage gas computation fails", + ); + } +} diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/tests/_pending/src/system/control.rs similarity index 60% rename from crates/mega-evm/src/system/control.rs rename to crates/mega-evm/tests/_pending/src/system/control.rs index 7ac6bbf0b..97b91a79f 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/tests/_pending/src/system/control.rs @@ -1,74 +1,6 @@ -//! The access control system contract for the `MegaETH` EVM. -//! -//! This contract provides functions to control access restrictions during EVM execution. -//! The first function, `disableVolatileDataAccess()`, prevents inner calls from accessing -//! volatile data (block env fields, beneficiary balance, oracle). - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use alloy_sol_types::SolError; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the access control system contract. -pub const ACCESS_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000004"); - -/// The code of the access control contract (version 1.0.0). -pub use mega_system_contracts::access_control::V1_0_0_CODE as ACCESS_CONTROL_CODE; - -/// The code hash of the access control contract (version 1.0.0). -pub use mega_system_contracts::access_control::V1_0_0_CODE_HASH as ACCESS_CONTROL_CODE_HASH; - -pub use mega_system_contracts::access_control::IMegaAccessControl; -pub use IMegaAccessControl::VolatileDataAccessType; - -/// Selector for `VolatileDataAccessDisabled(uint8)` custom error. -/// Selector: `keccak256("VolatileDataAccessDisabled(uint8)")[0..4]`. -pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; - -/// Builds the full ABI-encoded revert data for `VolatileDataAccessDisabled(uint8 accessType)`. -pub fn volatile_data_access_disabled_revert_data( - access_type: VolatileDataAccessType, -) -> alloy_primitives::Bytes { - alloy_primitives::Bytes::from( - ::abi_encode( - &IMegaAccessControl::VolatileDataAccessDisabled { accessType: access_type }, - ), - ) -} - -/// ABI-encoded revert data for `DisabledByParent()` custom error. -pub const DISABLED_BY_PARENT_REVERT_DATA: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; - -/// Ensures the access control contract is deployed in the designated address and returns the -/// state changes. -/// The caller is responsible for committing the returned `EvmState` changes to the database. -pub fn transact_deploy_access_control_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - access_control_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the access-control contract active under -/// `spec`, or `None` if `REX4` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn access_control_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX4).then(|| { - SystemContractSpec::new( - ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE, - ACCESS_CONTROL_CODE_HASH, - ) - }) -} +//! Unit tests extracted from `crates/mega-evm/src/system/control.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/control.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { @@ -117,17 +49,6 @@ mod tests { assert_eq!(decoded.accessType, VolatileDataAccessType::Oracle); } - #[test] - fn test_deploy_access_control_contract_requires_rex4() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = - transact_deploy_access_control_contract(MegaHardforkConfig::default(), 0, &mut state) - .unwrap(); - assert_eq!(result, None); - } - #[test] fn test_deploy_access_control_contract_on_fresh_db() { let mut db = InMemoryDB::default(); diff --git a/crates/mega-evm/tests/_pending/src/system/deploy.rs b/crates/mega-evm/tests/_pending/src/system/deploy.rs new file mode 100644 index 000000000..b8c6f6ee1 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/deploy.rs @@ -0,0 +1,150 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/deploy.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/deploy.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + MegaHardfork, MegaHardforkConfig, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX2, + ORACLE_CONTRACT_CODE_HASH_REX5, + }; + use alloy_hardforks::ForkCondition; + use alloy_primitives::address; + use revm::{database::InMemoryDB, state::AccountInfo, Database as _, DatabaseCommit}; + + fn addrs(specs: &[SystemContractSpec]) -> Vec
{ + specs.iter().map(|s| s.address).collect() + } + + const SEEDED_ADDR: Address = address!("0x6342000000000000000000000000000000000099"); + const SEED_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); + const UNRELATED_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); + + /// Builds a spec whose code hash differs from any pre-existing account, so + /// `transact_deploy` takes the bytecode-upgrade path rather than the + /// idempotent early return. + fn seeded_spec(force_create_on_upgrade: bool) -> SystemContractSpec { + let code = Bytes::from_static(&[0x60, 0x00]); + let code_hash = keccak256(&code); + SystemContractSpec::new(SEEDED_ADDR, code, code_hash) + .with_seed(Vec::from([(SEED_SLOT, U256::from(42))])) + .with_force_create_on_upgrade(force_create_on_upgrade) + } + + /// An in-place upgrade that does NOT recreate the account must not write seed + /// slots: doing so would mix genesis storage into preserved live storage and + /// record a wrong `original_value`. Guards the `force_create_on_upgrade = + /// false` + non-empty `seed` configuration that no current contract uses. + #[test] + fn test_seed_skipped_on_storage_preserving_upgrade() { + let mut db = InMemoryDB::default(); + // Pre-existing account with different bytecode (so the upgrade path runs) + // and a live value at the slot the spec would otherwise seed. + let existing_code = Bytes::from_static(&[0xfe]); + db.insert_account_info( + SEEDED_ADDR, + AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: keccak256(&existing_code), + code: Some(Bytecode::new_raw(existing_code)), + }, + ); + db.insert_account_storage(SEEDED_ADDR, SEED_SLOT, U256::from(99)).unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_touched()); + assert!(!account.is_created(), "storage-preserving upgrade must not recreate"); + assert!( + !account.storage.contains_key(&SEED_SLOT), + "seed must not be written when storage is preserved" + ); + + // Committing the upgrade must leave the pre-existing slot at its old value. + state.commit(result); + assert_eq!( + state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), + U256::from(99), + "preserved storage must keep its pre-upgrade value after commit" + ); + } + + /// The same spec with `force_create_on_upgrade = true` recreates the account + /// and therefore does seed — the path the `SequencerRegistry` relies on. + #[test] + fn test_seed_written_on_force_created_upgrade() { + let mut db = InMemoryDB::default(); + let existing_code = Bytes::from_static(&[0xfe]); + db.insert_account_info( + SEEDED_ADDR, + AccountInfo { + balance: U256::from(1), + nonce: 1, + code_hash: keccak256(&existing_code), + code: Some(Bytecode::new_raw(existing_code)), + }, + ); + // An unrelated live slot that recreation must clear. + db.insert_account_storage(SEEDED_ADDR, UNRELATED_SLOT, U256::from(99)).unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(true)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_created(), "force_create_on_upgrade must recreate"); + let slot = account.storage.get(&SEED_SLOT).expect("seed slot must be written"); + assert_eq!(slot.present_value, U256::from(42)); + assert_eq!(slot.original_value, U256::ZERO); + + // Recreation clears prior storage: after commit the seed slot holds its + // value and the unrelated pre-existing slot reads back as zero. + state.commit(result); + assert_eq!(state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), U256::from(42)); + assert_eq!( + state.storage(SEEDED_ADDR, UNRELATED_SLOT).unwrap(), + U256::ZERO, + "recreation must clear unrelated pre-existing storage" + ); + } + + /// A fresh deploy seeds regardless of `force_create_on_upgrade`. + #[test] + fn test_seed_written_on_fresh_deploy() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); + let account = result.get(&SEEDED_ADDR).unwrap(); + + assert!(account.is_created(), "fresh deploy creates the account"); + assert_eq!( + account.storage.get(&SEED_SLOT).expect("seed slot must be written").present_value, + U256::from(42) + ); + } + + #[test] + fn test_registry_oracle_version_by_spec() { + // Only MiniRex active: Oracle v1.0.0, force-created on upgrade (pre-Rex5), + // and just Oracle + high-precision Oracle. + let mini = + MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); + let mini = flat_system_contract_specs(&mini, 0); + assert_eq!(mini.len(), 2); + assert_eq!(mini[0].code_hash, ORACLE_CONTRACT_CODE_HASH); + assert!(mini[0].force_create_on_upgrade); + + // Rex2 active but not Rex5: Oracle v1.1.0, still force-created on upgrade. + let rex2 = MegaHardforkConfig::default() + .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) + .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); + let rex2 = flat_system_contract_specs(&rex2, 0); + assert_eq!(rex2[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); + assert!(rex2[0].force_create_on_upgrade); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/intercept.rs b/crates/mega-evm/tests/_pending/src/system/intercept.rs new file mode 100644 index 000000000..e6fb0a3e0 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/intercept.rs @@ -0,0 +1,114 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/intercept.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/intercept.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use alloy_primitives::{Bytes, U256}; + use alloy_sol_types::SolCall; + use revm::{ + bytecode::opcode::{CALLCODE, MSTORE, RETURN}, + context::tx::TxEnvBuilder, + }; + + use crate::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + }; + + const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = + IMegaLimitControl::remainingComputeGasCall::SELECTOR; + + /// Pins the `abi_decode`-accepts-trailing-junk behaviour of `alloy-sol-types`'s + /// `decode_sequence::<()>` for parameterless system-contract methods. The + /// interceptor dispatch's selector-only admission relies on this: if a future + /// alloy upgrade rejects trailing bytes, historical replays would diverge from + /// the original `abi_decode` admission and break replay determinism on stable + /// specs. + #[test] + fn test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls() { + let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; + let exact = selector; + let with_junk: Vec = selector.iter().copied().chain(core::iter::once(0xff)).collect(); + let with_pad: Vec = selector.iter().copied().chain([0u8; 32]).collect(); + + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&exact).is_ok(), + "exact 4-byte selector must decode", + ); + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_junk).is_ok(), + "current alloy-sol-types accepts selector+1B junk for empty-tuple decode; if this \ + fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ + selector probe before landing", + ); + assert!( + IMegaAccessControl::disableVolatileDataAccessCall::abi_decode(&with_pad).is_ok(), + "current alloy-sol-types accepts selector+32B padding for empty-tuple decode; if \ + this fails the pre-REX5 dispatch path's admission rule has changed — re-spec the \ + selector probe before landing", + ); + } + + /// Unit test for the explicit call-scheme guard in `frame_init`. + /// + /// A `CALLCODE` to a system contract address with a recognized selector must NOT be + /// intercepted. + /// The scheme guard rejects it before any interceptor sees the call. + /// The call falls through to on-chain bytecode, which reverts with `NotIntercepted()`, + /// leaving the `CALLCODE` success flag as 0. + #[test] + fn test_callcode_scheme_guard_skips_interception() { + let code = BytecodeBuilder::default() + .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) + // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) + .push_number(0_u64) // retSize + .push_number(0_u64) // retOffset + .push_number(4_u64) // argsSize (selector length) + .push_number(0_u64) // argsOffset (selector at memory[0]) + .push_number(0_u64) // value + .push_address(LIMIT_CONTROL_ADDRESS) + .push_number(100_000_u64) // gas + .append(CALLCODE) // success flag (0=fail, 1=success) on stack + .push_number(0_u64) + .append(MSTORE) + .push_number(32_u64) + .push_number(0_u64) + .append(RETURN) + .build(); + + let caller = alloy_primitives::address!("0000000000000000000000000000000000300000"); + let contract = alloy_primitives::address!("0000000000000000000000000000000000300001"); + + let mut db = MemoryDatabase::default() + .account_balance(caller, U256::from(1_000_000)) + .account_code(contract, code) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE); + + let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = MegaEvm::new(context); + let tx = TxEnvBuilder::default() + .caller(caller) + .call(contract) + .gas_limit(100_000_000) + .build_fill(); + let mut tx = MegaTransaction::new(tx); + tx.enveloped_tx = Some(Bytes::new()); + + let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); + assert!(result.result.is_success(), "outer tx should succeed"); + + let output = result.result.output().expect("should have output"); + let success_flag = U256::from_be_slice(output); + assert_eq!( + success_flag, + U256::ZERO, + "CALLCODE to system contract must not be intercepted — scheme guard must reject it" + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs new file mode 100644 index 000000000..a87f1be64 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs @@ -0,0 +1,64 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/keyless_deploy.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/keyless_deploy.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use crate::MegaHardforkConfig; + use revm::{ + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + #[test] + fn test_deploy_keyless_deploy_contract_on_fresh_db() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); + assert!(account.is_touched()); + assert!(account.is_created(), "fresh deploy must mark account as created"); + assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); + } + + /// Covers the `account_existed = true` branch: an account already exists with wrong code, + /// so the deploy updates the code without marking the account as created. + #[test] + fn test_deploy_keyless_deploy_contract_existing_account_not_marked_created() { + let wrong_code = alloy_primitives::bytes!("0x6000"); + let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + KEYLESS_DEPLOY_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); + assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); + assert!(account.is_touched()); + assert!( + !account.is_created(), + "in-place bytecode update of an existing account must not mark it as created" + ); + } + +} diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/tests/_pending/src/system/limit_control.rs similarity index 63% rename from crates/mega-evm/src/system/limit_control.rs rename to crates/mega-evm/tests/_pending/src/system/limit_control.rs index 43c387970..b0e5cf5ce 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/tests/_pending/src/system/limit_control.rs @@ -1,49 +1,6 @@ -//! The `MegaLimitControl` system contract for the `MegaETH` EVM. -//! -//! This contract currently provides a read-only query to return remaining compute gas -//! of the current call. -//! The runtime result is produced by EVM interception, not by executing on-chain bytecode. - -use alloy_evm::Database; -use alloy_primitives::{address, Address}; -use revm::{database::State, state::EvmState}; - -use crate::{MegaHardforks, MegaSpecId, SystemContractSpec}; - -/// The address of the `MegaLimitControl` system contract. -pub const LIMIT_CONTROL_ADDRESS: Address = address!("0x6342000000000000000000000000000000000005"); - -/// The code of the `MegaLimitControl` contract (version 1.0.0). -pub use mega_system_contracts::limit_control::V1_0_0_CODE as LIMIT_CONTROL_CODE; - -/// The code hash of the `MegaLimitControl` contract (version 1.0.0). -pub use mega_system_contracts::limit_control::V1_0_0_CODE_HASH as LIMIT_CONTROL_CODE_HASH; - -pub use mega_system_contracts::limit_control::IMegaLimitControl; - -/// Ensures the `MegaLimitControl` contract is deployed in the designated address and returns -/// the state changes. -/// The caller is responsible for committing the returned `EvmState` changes to the database. -pub fn transact_deploy_limit_control_contract( - hardforks: impl MegaHardforks, - block_timestamp: u64, - db: &mut State, -) -> Result, DB::Error> { - limit_control_spec(hardforks.spec_id(block_timestamp)) - .map(|s| crate::transact_deploy(db, &s)) - .transpose() -} - -/// Builds the [`SystemContractSpec`] for the `MegaLimitControl` contract active -/// under `spec`, or `None` if `REX4` is not yet enabled. -/// -/// `spec` is the scheduled spec, compared by position — see -/// [`oracle_spec`](crate::system::oracle::oracle_spec). -pub(crate) fn limit_control_spec(spec: MegaSpecId) -> Option { - spec.reaches(MegaSpecId::REX4).then(|| { - SystemContractSpec::new(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, LIMIT_CONTROL_CODE_HASH) - }) -} +//! Unit tests extracted from `crates/mega-evm/src/system/limit_control.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/limit_control.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. #[cfg(test)] mod tests { @@ -63,17 +20,6 @@ mod tests { assert_eq!(computed_hash, LIMIT_CONTROL_CODE_HASH); } - #[test] - fn test_deploy_limit_control_contract_requires_rex4() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = - transact_deploy_limit_control_contract(MegaHardforkConfig::default(), 0, &mut state) - .unwrap(); - assert_eq!(result, None); - } - #[test] fn test_deploy_limit_control_contract_on_fresh_db() { let mut db = InMemoryDB::default(); diff --git a/crates/mega-evm/tests/_pending/src/system/oracle.rs b/crates/mega-evm/tests/_pending/src/system/oracle.rs new file mode 100644 index 000000000..c85499e48 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/oracle.rs @@ -0,0 +1,257 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/oracle.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/oracle.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use crate::MegaHardforkConfig; + + use super::*; + use alloy_primitives::keccak256; + use revm::{ + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + #[test] + fn test_deploy_oracle_contract_on_fresh_db() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex5, so we expect Rex5 (v2.0.0) bytecode + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the oracle contract + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned + assert_eq!(result.len(), 1, "Should have state changes for one account"); + assert!( + result.contains_key(&ORACLE_CONTRACT_ADDRESS), + "State changes should contain oracle contract address" + ); + + // Verify the account in the state changes + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert!(account.is_touched(), "Account should be marked as touched"); + assert!(account.is_created(), "Account should be marked as created"); + + // Verify the account info (Rex5 = v2.0.0 bytecode) + let info = &account.info; + assert_eq!( + info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should match the v2.0.0 value" + ); + assert!(info.code.is_some(), "Code should be set"); + + let code = info.code.as_ref().unwrap(); + assert_eq!( + code.original_bytes(), + ORACLE_CONTRACT_CODE_REX5, + "Code bytes should match the v2.0.0 value" + ); + } + + #[test] + fn test_deploy_oracle_contract_idempotent() { + // Create a database with the oracle contract already deployed correctly (Rex5 = v2.0.0) + let mut db = InMemoryDB::default(); + db.insert_account_info( + ORACLE_CONTRACT_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: ORACLE_CONTRACT_CODE_HASH_REX5, + code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX5)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex5 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy should return state with the account marked as read (no update needed) + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + assert_eq!( + result.len(), + 1, + "Deployment should return state with account marked as read when contract is already correctly deployed" + ); + + // Verify the account is in the result + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should match v2.0.0 bytecode" + ); + } + + #[test] + fn test_deploy_oracle_contract_with_wrong_code_hash() { + // Create a database with the oracle address already having different code + let mut db = InMemoryDB::default(); + + // Insert an account with wrong code hash at the oracle address + let wrong_code = bytes!("0x6000"); + let wrong_code_hash = keccak256(&wrong_code); + + db.insert_account_info( + ORACLE_CONTRACT_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + // with_all_activated() includes Rex2 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy should update the contract with correct code (Rex5 = v2.0.0 bytecode) + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned (contract was updated) + assert_eq!(result.len(), 1, "Should have state changes to update the contract"); + + // Verify the updated account has the correct code hash + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Code hash should be updated to v2.0.0 bytecode" + ); + } + + #[test] + fn test_deploy_oracle_contract_marks_account_as_touched() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the oracle contract + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Get the account from result + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist in result"); + + // Verify the account is marked as touched (required for state changes to be committed) + assert!( + account.is_touched(), + "Deployed account must be marked as touched for state changes to take effect" + ); + assert!(account.is_created(), "Account should be marked as created"); + } + + #[test] + fn test_deploy_oracle_contract_rex5() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + // Activate all including Rex5 + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); + assert_eq!( + account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, + "Should deploy v2.0.0 bytecode on Rex5" + ); + } + + #[test] + fn test_high_precision_timestamp_oracle_deployment() { + // Create a fresh in-memory database + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + // Deploy the high precision timestamp oracle contract + let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + // Verify that state changes were returned + assert_eq!(result.len(), 1, "Should have state changes for one account"); + assert!( + result.contains_key(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), + "State changes should contain high precision timestamp oracle address" + ); + + // Verify the account in the state changes + let account = + result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); + assert!(account.is_touched(), "Account should be marked as touched"); + assert!(account.is_created(), "Account should be marked as created"); + + // Verify the account info + let info = &account.info; + assert_eq!( + info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + "Code hash should match the expected value" + ); + assert!(info.code.is_some(), "Code should be set"); + + // Verify code matches + let code = info.code.as_ref().unwrap(); + assert_eq!( + code.original_bytes(), + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, + "Code bytes should match the expected value" + ); + + // Verify code hash matches computed hash + let computed_hash = keccak256(&HIGH_PRECISION_TIMESTAMP_ORACLE_CODE); + assert_eq!( + computed_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + "Code hash constant should match computed hash" + ); + } + + /// Covers the `account_existed = true` branch in + /// `transact_deploy_high_precision_timestamp_oracle`: when the account already exists with + /// wrong code, the deploy updates the code without marking the account as created. + #[test] + fn test_high_precision_timestamp_oracle_existing_account_not_marked_created() { + let wrong_code = alloy_primitives::bytes!("0x6000"); + let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + AccountInfo { + balance: revm::primitives::U256::ZERO, + nonce: 0, + code_hash: wrong_code_hash, + code: Some(Bytecode::new_raw(wrong_code)), + }, + ); + + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = MegaHardforkConfig::default().with_all_activated(); + + let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) + .expect("Deployment should succeed") + .expect("Should return state"); + + let account = + result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); + assert_eq!(account.info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH); + assert!(account.is_touched()); + assert!( + !account.is_created(), + "existing account must not be marked as created on code update" + ); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs new file mode 100644 index 000000000..8c7612abb --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs @@ -0,0 +1,778 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/sequencer_registry.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/sequencer_registry.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, keccak256, B256}; + use mega_system_contracts::sequencer_registry::storage_slots::PENDING_ADMIN; + use revm::{ + context::BlockEnv, + database::InMemoryDB, + state::{AccountInfo, Bytecode}, + }; + + use crate::{MegaHardforkConfig, MegaSpecId}; + + const TEST_SEQUENCER: Address = address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); + const TEST_ADMIN: Address = address!("0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); + /// A non-system test address, used as a stand-in for a `_currentSystemAddress` that has + /// already been rotated away from the genesis `MEGA_SYSTEM_ADDRESS`. Distinct from + /// genesis so tests can tell the two apart. + const TEST_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); + + const TEST_MIN_ROTATION_DELAY: u64 = 100; + + fn test_config() -> SequencerRegistryConfig { + SequencerRegistryConfig { + rex5_initial_sequencer: TEST_SEQUENCER, + rex5_initial_admin: TEST_ADMIN, + } + } + + fn test_rex6_config() -> SequencerRegistryRex6Config { + SequencerRegistryRex6Config { rex6_min_rotation_delay: TEST_MIN_ROTATION_DELAY } + } + + /// A chain running Rex5: the pre-upgrade world where the registry runs v1.0.0. + fn rex5_hardforks() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX5) + .with_params(test_config()) + } + + /// All hardforks including Rex6, with both registry param sets attached. + fn rex6_hardforks() -> MegaHardforkConfig { + MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(test_config()) + .with_params(test_rex6_config()) + } + + /// Verifies that Rust slot constants match the Solidity storage layout. + /// These values come from `forge inspect SequencerRegistry storage-layout`. + /// If the Solidity field order changes, this test MUST be updated. + #[test] + fn test_slot_constants_match_solidity_layout() { + assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::from(0), "_currentSystemAddress = slot 0"); + assert_eq!(CURRENT_SEQUENCER, U256::from(1), "_currentSequencer = slot 1"); + assert_eq!(ADMIN, U256::from(2), "_admin = slot 2"); + assert_eq!(PENDING_ADMIN, U256::from(3), "_pendingAdmin = slot 3"); + assert_eq!(INITIAL_SYSTEM_ADDRESS, U256::from(4), "_initialSystemAddress = slot 4"); + assert_eq!(INITIAL_SEQUENCER, U256::from(5), "_initialSequencer = slot 5"); + assert_eq!(INITIAL_FROM_BLOCK, U256::from(6), "_initialFromBlock = slot 6"); + assert_eq!(PENDING_SYSTEM_ADDRESS, U256::from(7), "_pendingSystemAddress = slot 7"); + assert_eq!( + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(8), + "_systemAddressActivationBlock = slot 8" + ); + assert_eq!(PENDING_SEQUENCER, U256::from(9), "_pendingSequencer = slot 9"); + assert_eq!( + SEQUENCER_ACTIVATION_BLOCK, + U256::from(10), + "_sequencerActivationBlock = slot 10" + ); + // Slots 11 (_systemAddressHistory) and 12 (_sequencerHistory) are dynamic arrays. + assert_eq!(MIN_ROTATION_DELAY, U256::from(13), "_minRotationDelay = slot 13 (v2.0.0+)"); + } + + #[test] + fn test_validate_rejects_zero_rex5_initial_sequencer() { + let mut config = test_config(); + config.rex5_initial_sequencer = Address::ZERO; + let err = config.validate().expect_err("zero rex5_initial_sequencer must be rejected"); + assert!( + err.message.contains("rex5_initial_sequencer must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_validate_rejects_zero_rex5_initial_admin() { + let mut config = test_config(); + config.rex5_initial_admin = Address::ZERO; + let err = config.validate().expect_err("zero rex5_initial_admin must be rejected"); + assert!( + err.message.contains("rex5_initial_admin must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_validate_rejects_zero_min_rotation_delay() { + let config = SequencerRegistryRex6Config { rex6_min_rotation_delay: 0 }; + let err = config.validate().expect_err("zero rex6_min_rotation_delay must be rejected"); + assert!( + err.message.contains("rex6_min_rotation_delay must not be zero"), + "unexpected message: {}", + err.message, + ); + } + + #[test] + fn test_deploy_fresh_at_rex6_seeds_v2_with_min_rotation_delay() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 1000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(account.is_created()); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); + assert_eq!( + account.storage.len(), + 7, + "fresh Rex6 deploy writes the 6 bootstrap slots plus _minRotationDelay" + ); + assert_eq!( + account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), + U256::from(TEST_MIN_ROTATION_DELAY), + ); + assert_eq!( + account.storage.get(&ADMIN).unwrap().present_value(), + U256::from_be_bytes(TEST_ADMIN.into_word().0), + ); + assert_eq!( + account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), + U256::from(1000), + ); + } + + #[test] + fn test_deploy_rex6_is_idempotent_when_v2_present() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 2000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(!account.is_created(), "idempotent deploy should not re-create"); + assert!(!account.is_touched(), "idempotent deploy should not touch the account"); + assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); + } + + #[test] + fn test_deploy_rex6_missing_config_errors() { + // Rex6 active but only the Rex5 params attached: deploy must fail fast instead of + // installing a v2.0.0 registry with an unseeded _minRotationDelay. + let hardforks = MegaHardforkConfig::default() + .with_all_activated_through(MegaSpecId::REX6) + .with_params(test_config()); + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let err = + transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) + .expect_err("missing Rex6 params must fail closed"); + assert!( + err.to_string().contains("SequencerRegistryRex6Config not configured"), + "unexpected message: {err}" + ); + } + + #[test] + fn test_deploy_rex6_on_top_of_eoa_with_balance() { + let mut db = InMemoryDB::default(); + // Simulate an EOA that received ETH before the registry was ever deployed. Even at + // Rex6 this is a fresh bootstrap, not a storage-preserving upgrade: the full seed + // (including _minRotationDelay) must be written. + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 1000, + &mut state, + &test_config(), + ) + .unwrap() + .unwrap(); + + let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); + assert!(account.is_created()); + assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); + assert_eq!(account.info.balance, U256::from(1_000_000)); + assert_eq!(account.storage.len(), 7); + assert_eq!( + account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), + U256::from(TEST_MIN_ROTATION_DELAY), + ); + } + + #[test] + fn test_deploy_rex6_wrong_existing_code_hash_errors() { + let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: wrong_code.hash_slow(), + code: Some(wrong_code), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let err = transact_deploy_sequencer_registry( + &rex6_hardforks(), + 0, + 2000, + &mut state, + &test_config(), + ) + .expect_err("wrong code hash must fail closed"); + + let msg = err.to_string(); + assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); + assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); + } + + #[test] + fn test_resolve_rex6_expects_v2_code_hash() { + // A V2 registry resolves normally at REX6. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (addr, witness) = + resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state).unwrap(); + assert_eq!(addr, TEST_SYSTEM_ADDRESS); + assert!(witness.is_some()); + } + + #[test] + fn test_resolve_rex6_rejects_v1_code_hash() { + // At REX6 the pre-block deploy has already upgraded the bytecode, so a V1 code hash at + // resolve time is a broken pipeline and must fail closed. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let err = resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state) + .expect_err("V1 code hash at REX6 must fail closed"); + assert!(err.to_string().contains("code hash mismatch")); + } + + #[test] + fn test_resolve_rex5_returns_stored_system_address_with_witness() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (addr, witness) = + resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state).unwrap(); + assert_eq!(addr, TEST_SYSTEM_ADDRESS); + + // Witness must capture the registry account and the CURRENT_SYSTEM_ADDRESS slot. + let witness = witness.expect("post-deploy resolve must produce witness"); + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("registry account in witness"); + assert_eq!(acc.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert!( + acc.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), + "witness must include CURRENT_SYSTEM_ADDRESS slot" + ); + assert_eq!(acc.storage.len(), 1, "witness should contain exactly one slot"); + let slot = acc.storage.get(&CURRENT_SYSTEM_ADDRESS).expect("slot must exist"); + assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); + assert_eq!(slot.original_value(), slot.present_value()); + } + + #[test] + fn test_resolve_rex5_zero_slot_errors() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let result = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state); + assert!(result.is_err(), "zero _currentSystemAddress should be an error"); + } + + #[test] + fn test_resolve_rex5_missing_registry_errors() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + let hardforks = rex5_hardforks(); + + let err = resolve_system_address(&hardforks, MegaSpecId::REX5, &mut state) + .expect_err("missing registry at Rex5 must fail closed"); + assert!(err.to_string().contains("does not exist")); + } + + #[test] + fn test_resolve_rex5_wrong_code_hash_errors() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: B256::ZERO, + code: Some(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let err = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state) + .expect_err("wrong code hash must fail closed"); + + assert!(err.to_string().contains("code hash mismatch")); + } + + #[test] + fn test_is_apply_pending_changes_due_no_registry() { + let mut db = InMemoryDB::default(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(!due); + // Witness must contain a not-existing account entry. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); + assert_eq!(acc.status, revm::state::AccountStatus::LoadedAsNotExisting); + assert!(acc.storage.is_empty(), "no-registry witness should have no slots"); + } + + #[test] + fn test_is_apply_pending_changes_due_no_pending() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(!due); + // Witness must include both PENDING_* slots (both zero = no change pending). + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); + assert!( + acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS), + "witness must include PENDING_SYSTEM_ADDRESS" + ); + assert!( + acc.storage.contains_key(&PENDING_SEQUENCER), + "witness must include PENDING_SEQUENCER" + ); + // No activation slots needed because both pending values are zero. + assert_eq!(acc.storage.len(), 2, "no-pending witness should have exactly 2 slots"); + } + + #[test] + fn test_is_apply_pending_changes_due_system_address_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_addr = address!("0x1111111111111111111111111111111111111111"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + new_addr.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + // Not yet due at block 999. + let mut state = State::builder().with_database(&mut db).build(); + let (due, witness) = is_apply_pending_changes_due(&mut state, 999).unwrap(); + assert!(!due, "not yet due"); + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + + // Exactly due at block 1000 (fresh State to avoid cache from prior call). + let mut state = State::builder().with_database(&mut db).build(); + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!(due, "exactly due"); + // Both roles' pending slots are always read into the witness. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + } + + #[test] + fn test_is_apply_pending_changes_due_sequencer_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_seq = address!("0x2222222222222222222222222222222222222222"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + new_seq.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(500), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 500).unwrap(); + assert!(due); + // System address has no pending change (slot is zero) so only PENDING_SYSTEM_ADDRESS + // is read. Then sequencer path reads PENDING_SEQUENCER + SEQUENCER_ACTIVATION_BLOCK. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); + assert_eq!(acc.storage.len(), 3); + } + + #[test] + fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + let new_sys = address!("0x1111111111111111111111111111111111111111"); + let new_seq = address!("0x2222222222222222222222222222222222222222"); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + new_sys.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1001), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + new_seq.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + let mut state = State::builder().with_database(&mut db).build(); + + let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); + assert!( + due, + "sequencer change should still trigger the pre-block call when the system address is not due yet" + ); + // System address is not due (activation at 1001) but its pending slot + activation + // slot are still read. Then the sequencer path reads its own pending + activation. + let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); + assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); + assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); + assert_eq!(acc.storage.len(), 4, "both roles' slots should be in the witness"); + for slot_key in [ + PENDING_SYSTEM_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + PENDING_SEQUENCER, + SEQUENCER_ACTIVATION_BLOCK, + ] { + let slot = acc.storage.get(&slot_key).expect("slot must exist"); + assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); + assert_eq!(slot.original_value(), slot.present_value()); + } + } + + #[test] + fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let next_system_address = address!("0x1111111111111111111111111111111111111111"); + let next_sequencer = address!("0x2222222222222222222222222222222222222222"); + + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + TEST_SYSTEM_ADDRESS.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SEQUENCER, + TEST_SEQUENCER.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SYSTEM_ADDRESS, + next_system_address.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + PENDING_SEQUENCER, + next_sequencer.into_word().into(), + ) + .unwrap(); + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + U256::from(1000), + ) + .unwrap(); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + let result = + transact_apply_pending_changes(&mut evm).expect("applyPendingChanges() should succeed"); + let state = result.state; + drop(evm); + + revm::DatabaseCommit::commit(&mut db, state); + + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS) + .unwrap(), + address_to_storage_value(next_system_address), + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER) + .unwrap(), + address_to_storage_value(next_sequencer), + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage( + &mut db, + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + ) + .unwrap(), + U256::ZERO, + ); + assert_eq!( + revm::Database::storage( + &mut db, + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_ACTIVATION_BLOCK, + ) + .unwrap(), + U256::ZERO, + ); + } + + #[test] + fn test_transact_apply_pending_changes_uses_block_gas_limit() { + // Block gas_limit > 30M must be passed through to the system call so that + // applyPendingChanges() can absorb the variable cost from REX dynamic + // storage gas instead of being capped at the upstream-fixed 30M. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 250_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + transact_apply_pending_changes(&mut evm).expect("system call should succeed"); + assert_eq!(revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, 250_000_000); + } + + #[test] + fn test_transact_apply_pending_changes_respects_30m_floor() { + // When the block gas limit is below the 30M floor, the system call must + // still receive at least the historical default budget. + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 1_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + transact_apply_pending_changes(&mut evm).expect("system call should succeed"); + assert_eq!( + revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, + crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR, + ); + } + + #[test] + fn test_transact_apply_pending_changes_errors_when_registry_reverts() { + let revert_code = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); + + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: revert_code.hash_slow(), + code: Some(revert_code), + ..Default::default() + }, + ); + + let block = + BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; + let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut evm = crate::MegaEvm::new(context); + + let err = transact_apply_pending_changes(&mut evm) + .expect_err("reverting registry bytecode must fail closed"); + + assert!(err.to_string().contains("reverted or halted")); + } +} diff --git a/crates/mega-evm/tests/_pending/src/system/tx.rs b/crates/mega-evm/tests/_pending/src/system/tx.rs new file mode 100644 index 000000000..4314fa100 --- /dev/null +++ b/crates/mega-evm/tests/_pending/src/system/tx.rs @@ -0,0 +1,79 @@ +//! Unit tests extracted from `crates/mega-evm/src/system/tx.rs` when the Satin skeleton replaced the legacy core. +//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/tx.rs`. +//! Owning mechanisms are listed in `tests/_pending/README.md`. + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::TxKind; + + const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; + const USER: Address = address!("0000000000000000000000000000000000009999"); + const NON_WHITELIST: Address = address!("00000000000000000000000000000000000000ab"); + + /// Builds a legacy (type 0x0) call transaction with the given caller and callee. + fn legacy_call_tx(caller: Address, to: Address) -> MegaTransaction { + let mut tx = MegaTransaction::default(); + tx.base.tx_type = 0; + tx.base.caller = caller; + tx.base.kind = TxKind::Call(to); + tx + } + + #[test] + fn test_is_system_originated_matches_eip_system_address_caller() { + // The protocol's own pre-block system calls (EIP-2935 / EIP-4788 / SequencerRegistry) + // use `0xff..fe` as caller; it matches regardless of the resolved system address or target. + let tx = legacy_call_tx(EIP_SYSTEM_ADDRESS, USER); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(is_system_originated(&tx, USER)); + } + + #[test] + fn test_is_system_originated_matches_mega_system_tx() { + // Sequencer mega system tx: legacy tx from the system address to a whitelisted contract. + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { + // System address calling a non-whitelisted contract is not a mega system tx. + let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NON_WHITELIST); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_matches_promoted_mega_system_tx() { + // `before_run` promotes a mega system tx to a deposit (stamping the source hash and + // flipping `tx_type()`) *before* `on_new_tx` evaluates the exemption. The promoted shape + // must still be recognized as system-originated. + let mut tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "promotion flips tx_type to deposit"); + assert!( + !is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS), + "the legacy-typed check no longer matches after promotion", + ); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "but the source-hash branch does"); + } + + #[test] + fn test_is_system_originated_rejects_user_tx() { + let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } + + #[test] + fn test_is_system_originated_rejects_user_deposit_tx() { + // Anti-bypass: a user deposit transaction (non-system caller) must NOT be treated as + // system-originated, even though `is_deposit_like_transaction` classifies any deposit as + // deposit-like. Otherwise a user could craft a deposit to escape SALT-scaled storage gas. + let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + // A non-zero deposit source hash makes `tx_type()` report `DEPOSIT_TRANSACTION_TYPE`. + tx.deposit.source_hash = B256::repeat_byte(0x11); + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); + assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + } +} diff --git a/crates/mega-evm/tests/block_executor/partial_ladder.rs b/crates/mega-evm/tests/block_executor/partial_ladder.rs deleted file mode 100644 index 0a49dd341..000000000 --- a/crates/mega-evm/tests/block_executor/partial_ladder.rs +++ /dev/null @@ -1,404 +0,0 @@ -//! End-to-end tests for pre-block setup on partial and rollback hardfork ladders. -//! -//! Pre-block setup (system-contract predeploys, the EIP-2935/EIP-4788 fail-closed checks, the -//! `SequencerRegistry` bootstrap) is gated on the resolved spec position-compared via -//! `reaches`, not on per-fork registration and not on the behavior projection. These tests pin -//! both directions of that choice: -//! -//! - A *partial* ladder — a config scheduling a later fork without its predecessors — must still -//! run every lower fork's setup, rather than silently skipping it. -//! - A *rollback* window — mainnet's `MiniRex1`, which maps back to `EQUIVALENCE` — must keep -//! running the setup that earlier forks already activated, rather than retracting it. - -use std::{ - convert::Infallible, - sync::{Arc, Mutex}, -}; - -use alloy_evm::{ - block::{BlockExecutor, BlockValidationError, OnStateHook, StateChangeSource}, - EvmEnv, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, bytes, Address, Bytes, B256, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, - MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaSpecId, ScheduleError, - SequencerRegistryConfig, SequencerRegistryRex6Config, TestExternalEnvs, ACCESS_CONTROL_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, KEYLESS_DEPLOY_ADDRESS, LIMIT_CONTROL_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX5, - SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH_REX6, -}; -use mega_system_contracts::sequencer_registry::storage_slots::MIN_ROTATION_DELAY; -use revm::{ - context::BlockEnv, - database::{Database as _, State}, - state::{AccountInfo, Bytecode, EvmState}, -}; - -const BLOCK_NUMBER: u64 = 1000; -const BLOCK_GAS_LIMIT: u64 = 30_000_000; -const MIN_ROTATION_DELAY_BLOCKS: u64 = 100; - -const BOOTSTRAP_SEQUENCER: Address = address!("0x4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("0x5000000000000000000000000000000000000005"); - -/// Runtime bytecode that unconditionally reverts (`PUSH0 PUSH0 REVERT`). Installed at the -/// EIP-2935 history-storage address to force a failing pre-block system call. -/// -/// A heavy SALT bucket — the mechanism `tests/rex5/pre_block_system_calls.rs` uses — cannot force -/// the failure here: the pre-block call's caller is `eip4788::SYSTEM_ADDRESS`, which counts as -/// system-originated, so from Rex6 the transaction is exempt from resource metering and its -/// storage writes are charged un-scaled. Bucket capacity no longer influences the outcome. -const ALWAYS_REVERT_CODE: Bytes = bytes!("0x5f5ffd"); - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -/// A partial ladder: Rex6 activates while Rex5 is registered but never activates, and no earlier -/// fork is registered at all. `Rex5` must be present as an entry to carry -/// [`SequencerRegistryConfig`] — parameter lookup is activation-independent, but `with_params` -/// requires the entry to exist. -fn rex6_only_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Never) - .with_params(sequencer_registry_config()) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }) -} - -fn create_evm_env(spec: MegaSpecId, timestamp: u64) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let block_env = BlockEnv { - number: U256::from(BLOCK_NUMBER), - timestamp: U256::from(timestamp), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -/// Non-zero parent hash and beacon root on a non-genesis block, so both EIP helpers actually -/// issue their system call rather than taking the genesis-skip early return. -fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ) -} - -fn install_code(db: &mut MemoryDatabase, address: Address, code: Bytes) { - let bytecode = Bytecode::new_raw(code); - db.insert_account_info( - address, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -fn install_eip_contracts(db: &mut MemoryDatabase) { - install_code( - db, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_CODE.clone(), - ); - install_code( - db, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_CODE.clone(), - ); -} - -/// Records every account observed by the on-state hook, so a test can assert that a read-only -/// pre-block outcome reached the witness path. -#[derive(Debug, Default, Clone)] -struct RecordingStateHook { - accounts: Arc>>, -} - -impl OnStateHook for RecordingStateHook { - fn on_state(&mut self, _source: StateChangeSource, state: &EvmState) { - self.accounts.lock().unwrap().extend(state.keys().copied()); - } -} - -/// A config that activates Rex6 without ever activating Rex5 must still materialize every -/// lower-spec predeploy — at the Rex5 Oracle version — and bootstrap the `SequencerRegistry` at -/// v2.0.0. Under per-fork gating none of this ran. -#[test] -fn test_partial_ladder_runs_lower_fork_setup() { - let chain_spec = rex6_only_chain_spec(); - // Precondition: this really is a partial ladder (no activation event below Rex6), and the - // executing spec is Rex6. The `is_*_active_at_timestamp` predicates cannot state this — they - // project the scheduled spec, which a partial ladder keeps high by design. - assert_eq!(chain_spec.mega_fork_activation(MegaHardfork::Rex5), ForkCondition::Never); - assert_eq!(chain_spec.mega_fork_activation(MegaHardfork::MiniRex), ForkCondition::Never); - assert_eq!(chain_spec.spec_id(0), MegaSpecId::REX6); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - executor.apply_pre_execution_changes().expect("partial-ladder pre-block setup must succeed"); - - for address in [ - ORACLE_CONTRACT_ADDRESS, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - KEYLESS_DEPLOY_ADDRESS, - ACCESS_CONTROL_ADDRESS, - LIMIT_CONTROL_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - ] { - let info = state.basic(address).unwrap(); - assert!( - info.is_some_and(|i| i.code_hash != revm::primitives::KECCAK_EMPTY), - "{address} must be deployed on a partial ladder" - ); - } - - // The Oracle takes its Rex5 bytecode, and the registry its Rex6 bytecode with the seeded - // rotation delay — i.e. the position drives version selection too, not just the on/off gate. - assert_eq!( - state.basic(ORACLE_CONTRACT_ADDRESS).unwrap().unwrap().code_hash, - ORACLE_CONTRACT_CODE_HASH_REX5 - ); - assert_eq!( - state.basic(SEQUENCER_REGISTRY_ADDRESS).unwrap().unwrap().code_hash, - SEQUENCER_REGISTRY_CODE_HASH_REX6 - ); - assert_eq!( - state.storage(SEQUENCER_REGISTRY_ADDRESS, MIN_ROTATION_DELAY).unwrap(), - U256::from(MIN_ROTATION_DELAY_BLOCKS) - ); -} - -/// The Rex5 fail-closed rule on pre-block system calls must be enforced on a partial ladder too. -/// Under per-fork gating the Rex5 check was skipped and a reverting EIP-2935 call was silently -/// accepted. -/// -/// Kept separate from the deployment test above: a pre-block EIP failure returns before the -/// predeploy loop is reached, so one block cannot assert both. -#[test] -fn test_partial_ladder_enforces_pre_block_fail_closed() { - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - // Break EIP-2935 specifically. - install_code(&mut db, alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, ALWAYS_REVERT_CODE); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex6_only_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("a reverting EIP-2935 pre-block call must reject the block"); - let alloy_evm::block::BlockExecutionError::Validation(validation_err) = &err else { - panic!("expected a validation error, got: {err:?}"); - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "expected BlockHashContractCall, got: {validation_err:?}" - ); - // Assert the *specific* failure. Both gating styles reject this block, but for different - // reasons: under per-fork gating the Rex5 check is skipped and the reverting call is - // accepted, only for `resolve_system_address` to later trip over the registry that was - // never deployed. Matching on the error variant alone would pass either way. - assert!( - format!("{validation_err:?}").contains("EIP-2935 pre-block system call did not succeed"), - "block must be rejected by the EIP-2935 fail-closed check itself, got: {validation_err:?}" - ); -} - -/// A config that activates Rex6 with no Rex5 entry at all cannot carry the -/// [`SequencerRegistryConfig`] the Rex5 bootstrap requires. Pre-block setup must fail closed -/// with a configuration error rather than silently skipping the registry. -/// -/// This drives `pre_execution_changes` directly rather than `apply_pre_execution_changes`: the -/// latter also runs `resolve_system_address`, which gates on the executing spec and so raises the -/// same error under either gating style. Only the pre-block setup step distinguishes them — -/// under per-fork gating it returns `Ok`, having quietly skipped the registry entirely. -#[test] -fn test_rex6_without_any_rex5_entry_fails_closed() { - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX6, 0), - ); - - let err = executor - .pre_execution_changes() - .expect_err("Rex5 setup without its config must fail rather than be skipped"); - assert!( - format!("{err:?}").contains("SequencerRegistryConfig not configured"), - "expected the missing-config error, got: {err:?}" - ); -} - -/// The load-time params roster (`validate_schedule` → `MissingParams`) and the block-time -/// fail-closed checks are written independently but must cover the same requirements: one -/// config missing a required params type has to fail BOTH surfaces. A params rule registered -/// on only one side — a schedule accepted at load that dies at the fork's first block, or a -/// load-time rule with no execution-time counterpart — fails this pairing. -#[test] -fn test_missing_params_fail_at_load_time_and_pre_block_alike() { - let ladder_through = |top: MegaHardfork| { - MegaHardfork::VARIANTS - .iter() - .copied() - .filter(|fork| { - !fork.spec_id().is_alias() && fork.spec_id() as u8 <= top.spec_id() as u8 - }) - .fold(MegaHardforkConfig::default(), |config, fork| { - config.with(fork, ForkCondition::Timestamp(0)) - }) - }; - let run_pre_block = |chain_spec: MegaHardforkConfig, spec: MegaSpecId| { - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = MegaBlockExecutorFactory::new( - chain_spec, - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(spec, 0), - ); - executor - .pre_execution_changes() - .err() - .map(|err| format!("{err:?}")) - .expect("a schedule missing required params must fail pre-block execution") - }; - - // Rex5 scheduled without `SequencerRegistryConfig`. - let rex5_without_params = ladder_through(MegaHardfork::Rex5); - assert_eq!( - rex5_without_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex5, - params: "SequencerRegistryConfig" - }) - ); - let err = run_pre_block(rex5_without_params, MegaSpecId::REX5); - assert!(err.contains("SequencerRegistryConfig not configured"), "got: {err}"); - - // Rex6 scheduled with the Rex5 params attached but without `SequencerRegistryRex6Config`. - let rex6_without_params = - ladder_through(MegaHardfork::Rex6).with_params(sequencer_registry_config()); - assert_eq!( - rex6_without_params.validate_schedule(), - Err(ScheduleError::MissingParams { - fork: MegaHardfork::Rex6, - params: "SequencerRegistryRex6Config" - }) - ); - let err = run_pre_block(rex6_without_params, MegaSpecId::REX6); - assert!(err.contains("SequencerRegistryRex6Config not configured"), "got: {err}"); -} - -/// Mainnet's `MiniRex1` window rolls the executing spec back to `EQUIVALENCE` while `MiniRex`'s -/// predeploys remain installed. Pre-block setup must keep emitting their read-only outcomes: -/// dropping them would remove the accounts from the on-state hook that feeds the stateless -/// witness and the state-sync transition shard — a replay-observable change on frozen history. -#[test] -fn test_rollback_window_still_emits_predeploy_witness_entries() { - let chain_spec = mega_evm::mainnet_hardforks(); - let ForkCondition::Timestamp(timestamp) = - chain_spec.mega_fork_activation(MegaHardfork::MiniRex1) - else { - panic!("mainnet must schedule MiniRex1 by timestamp"); - }; - // Precondition: inside the window the scheduled spec is the alias rung and its behavior - // projects back to EQUIVALENCE. - assert_eq!(chain_spec.spec_id(timestamp), MegaSpecId::MINI_REX_1); - assert_eq!(chain_spec.spec_id(timestamp).behavior(), MegaSpecId::EQUIVALENCE); - - let mut db = MemoryDatabase::default(); - install_eip_contracts(&mut db); - // Both MiniRex predeploys are already installed, as they would be on mainnet by then, so the - // deploy takes its idempotent read-only path. - install_code(&mut db, ORACLE_CONTRACT_ADDRESS, mega_evm::ORACLE_CONTRACT_CODE); - install_code( - &mut db, - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - mega_evm::HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = - MegaEvmFactory::new().with_external_env_factory(TestExternalEnvs::::new()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::MINI_REX_1, timestamp), - ); - - let recorder = RecordingStateHook::default(); - let accounts = recorder.accounts.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - executor.apply_pre_execution_changes().expect("rollback-window pre-block setup must succeed"); - - let observed = accounts.lock().unwrap(); - for address in [ORACLE_CONTRACT_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS] { - assert!( - observed.contains(&address), - "{address} must still reach the witness hook during the rollback window" - ); - } - - // The rollback window is pre-Rex2, so the Oracle keeps its v1.0.0 bytecode. - assert_eq!( - state.basic(ORACLE_CONTRACT_ADDRESS).unwrap().unwrap().code_hash, - ORACLE_CONTRACT_CODE_HASH - ); -} diff --git a/crates/mega-evm/tests/compute_gas/snapshot.txt b/crates/mega-evm/tests/compute_gas/snapshot.txt deleted file mode 100644 index 000b0fef1..000000000 --- a/crates/mega-evm/tests/compute_gas/snapshot.txt +++ /dev/null @@ -1,429 +0,0 @@ -# Cross-spec compute-gas snapshot. -# -# Generated by `crates/mega-evm/tests/compute_gas`. Do not edit by hand. -# Regenerate: UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas -# -# `compute_gas` is the post-transaction compute-gas tracker reading; `gas_used` is the -# receipt value, which is neither counter nor their sum: refunds lower it, gas consumed -# outside a completed window raises it, and the calldata floor can raise it further. -# -# Frozen specs (Equivalence through Rex6) must never change: a diff there is a -# replay-breaking regression. -# -# program spec compute_gas gas_used outcome - -intrinsic_only Equivalence 0 21000 success -intrinsic_only MiniRex 21000 21000 success -intrinsic_only MiniRex1 0 21000 success -intrinsic_only MiniRex2 21000 21000 success -intrinsic_only Rex 21000 60000 success -intrinsic_only Rex1 21000 60000 success -intrinsic_only Rex2 21000 60000 success -intrinsic_only Rex3 21000 60000 success -intrinsic_only Rex4 21000 60000 success -intrinsic_only Rex5 21000 60000 success -intrinsic_only Rex6 21000 60000 success -intrinsic_only Rex7 21000 60000 success - -plain_arithmetic Equivalence 0 21352 success -plain_arithmetic MiniRex 21352 21352 success -plain_arithmetic MiniRex1 0 21352 success -plain_arithmetic MiniRex2 21352 21352 success -plain_arithmetic Rex 21352 60352 success -plain_arithmetic Rex1 21352 60352 success -plain_arithmetic Rex2 21352 60352 success -plain_arithmetic Rex3 21352 60352 success -plain_arithmetic Rex4 21352 60352 success -plain_arithmetic Rex5 21352 60352 success -plain_arithmetic Rex6 21352 60352 success -plain_arithmetic Rex7 21352 60352 success - -plain_memory_expansion Equivalence 0 21437 success -plain_memory_expansion MiniRex 21437 21437 success -plain_memory_expansion MiniRex1 0 21437 success -plain_memory_expansion MiniRex2 21437 21437 success -plain_memory_expansion Rex 21437 60437 success -plain_memory_expansion Rex1 21437 60437 success -plain_memory_expansion Rex2 21437 60437 success -plain_memory_expansion Rex3 21437 60437 success -plain_memory_expansion Rex4 21437 60437 success -plain_memory_expansion Rex5 21437 60437 success -plain_memory_expansion Rex6 21437 60437 success -plain_memory_expansion Rex7 21437 60437 success - -volatile_timestamp Equivalence 0 21004 success -volatile_timestamp MiniRex 21004 21004 success -volatile_timestamp MiniRex1 0 21004 success -volatile_timestamp MiniRex2 21004 21004 success -volatile_timestamp Rex 21004 60004 success -volatile_timestamp Rex1 21004 60004 success -volatile_timestamp Rex2 21004 60004 success -volatile_timestamp Rex3 21004 60004 success -volatile_timestamp Rex4 21004 60004 success -volatile_timestamp Rex5 21004 60004 success -volatile_timestamp Rex6 21004 60004 success -volatile_timestamp Rex7 21004 60004 success - -sstore_zero_to_nonzero Equivalence 0 43106 success -sstore_zero_to_nonzero MiniRex 43106 2043106 success -sstore_zero_to_nonzero MiniRex1 0 43106 success -sstore_zero_to_nonzero MiniRex2 43106 2043106 success -sstore_zero_to_nonzero Rex 43106 82106 success -sstore_zero_to_nonzero Rex1 43106 82106 success -sstore_zero_to_nonzero Rex2 43106 82106 success -sstore_zero_to_nonzero Rex3 43106 82106 success -sstore_zero_to_nonzero Rex4 43106 82106 success -sstore_zero_to_nonzero Rex5 43106 82106 success -sstore_zero_to_nonzero Rex6 43106 82106 success -sstore_zero_to_nonzero Rex7 43106 82106 success - -sstore_nonzero_to_nonzero Equivalence 0 26006 success -sstore_nonzero_to_nonzero MiniRex 26006 26006 success -sstore_nonzero_to_nonzero MiniRex1 0 26006 success -sstore_nonzero_to_nonzero MiniRex2 26006 26006 success -sstore_nonzero_to_nonzero Rex 26006 65006 success -sstore_nonzero_to_nonzero Rex1 26006 65006 success -sstore_nonzero_to_nonzero Rex2 26006 65006 success -sstore_nonzero_to_nonzero Rex3 26006 65006 success -sstore_nonzero_to_nonzero Rex4 26006 65006 success -sstore_nonzero_to_nonzero Rex5 26006 65006 success -sstore_nonzero_to_nonzero Rex6 26006 65006 success -sstore_nonzero_to_nonzero Rex7 26006 65006 success - -sstore_nonzero_to_zero Equivalence 0 21206 success -sstore_nonzero_to_zero MiniRex 26006 21206 success -sstore_nonzero_to_zero MiniRex1 0 21206 success -sstore_nonzero_to_zero MiniRex2 26006 21206 success -sstore_nonzero_to_zero Rex 26006 60206 success -sstore_nonzero_to_zero Rex1 26006 60206 success -sstore_nonzero_to_zero Rex2 26006 60206 success -sstore_nonzero_to_zero Rex3 26006 60206 success -sstore_nonzero_to_zero Rex4 26006 60206 success -sstore_nonzero_to_zero Rex5 26006 60206 success -sstore_nonzero_to_zero Rex6 26006 60206 success -sstore_nonzero_to_zero Rex7 26006 60206 success - -log0_empty Equivalence 0 21381 success -log0_empty MiniRex 21381 21381 success -log0_empty MiniRex1 0 21381 success -log0_empty MiniRex2 21381 21381 success -log0_empty Rex 21381 60381 success -log0_empty Rex1 21381 60381 success -log0_empty Rex2 21381 60381 success -log0_empty Rex3 21381 60381 success -log0_empty Rex4 21381 60381 success -log0_empty Rex5 21381 60381 success -log0_empty Rex6 21381 60381 success -log0_empty Rex7 21381 60381 success - -log1_32bytes Equivalence 0 22027 success -log1_32bytes MiniRex 22027 28337 success -log1_32bytes MiniRex1 0 22027 success -log1_32bytes MiniRex2 22027 28337 success -log1_32bytes Rex 22027 67337 success -log1_32bytes Rex1 22027 67337 success -log1_32bytes Rex2 22027 67337 success -log1_32bytes Rex3 22027 67337 success -log1_32bytes Rex4 22027 67337 success -log1_32bytes Rex5 22027 67337 success -log1_32bytes Rex6 22027 67337 success -log1_32bytes Rex7 22027 67337 success - -log4_128bytes Equivalence 0 23965 success -log4_128bytes MiniRex 23965 49205 success -log4_128bytes MiniRex1 0 23965 success -log4_128bytes MiniRex2 23965 49205 success -log4_128bytes Rex 23965 88205 success -log4_128bytes Rex1 23965 88205 success -log4_128bytes Rex2 23965 88205 success -log4_128bytes Rex3 23965 88205 success -log4_128bytes Rex4 23965 88205 success -log4_128bytes Rex5 23965 88205 success -log4_128bytes Rex6 23965 88205 success -log4_128bytes Rex7 23965 88205 success - -log2_log3_sequence Equivalence 0 24176 success -log2_log3_sequence MiniRex 24176 48046 success -log2_log3_sequence MiniRex1 0 24176 success -log2_log3_sequence MiniRex2 24176 48046 success -log2_log3_sequence Rex 24176 87046 success -log2_log3_sequence Rex1 24176 87046 success -log2_log3_sequence Rex2 24176 87046 success -log2_log3_sequence Rex3 24176 87046 success -log2_log3_sequence Rex4 24176 87046 success -log2_log3_sequence Rex5 24176 87046 success -log2_log3_sequence Rex6 24176 87046 success -log2_log3_sequence Rex7 24176 87046 success - -call_no_value_to_code Equivalence 0 23621 success -call_no_value_to_code MiniRex 23621 23621 success -call_no_value_to_code MiniRex1 0 23621 success -call_no_value_to_code MiniRex2 23621 23621 success -call_no_value_to_code Rex 23621 62621 success -call_no_value_to_code Rex1 23621 62621 success -call_no_value_to_code Rex2 23621 62621 success -call_no_value_to_code Rex3 23621 62621 success -call_no_value_to_code Rex4 23621 62621 success -call_no_value_to_code Rex5 23621 62621 success -call_no_value_to_code Rex6 23621 62621 success -call_no_value_to_code Rex7 23621 62621 success - -call_value_to_empty Equivalence 0 55321 success -call_value_to_empty MiniRex 55321 2055321 success -call_value_to_empty MiniRex1 0 55321 success -call_value_to_empty MiniRex2 55321 2055321 success -call_value_to_empty Rex 55321 94321 success -call_value_to_empty Rex1 55321 94321 success -call_value_to_empty Rex2 55321 94321 success -call_value_to_empty Rex3 55321 94321 success -call_value_to_empty Rex4 55321 94321 success -call_value_to_empty Rex5 57621 94321 success -call_value_to_empty Rex6 57621 94321 success -call_value_to_empty Rex7 57621 94321 success - -call_value_to_existing Equivalence 0 30321 success -call_value_to_existing MiniRex 30321 30321 success -call_value_to_existing MiniRex1 0 30321 success -call_value_to_existing MiniRex2 30321 30321 success -call_value_to_existing Rex 30321 69321 success -call_value_to_existing Rex1 30321 69321 success -call_value_to_existing Rex2 30321 69321 success -call_value_to_existing Rex3 30321 69321 success -call_value_to_existing Rex4 30321 69321 success -call_value_to_existing Rex5 32621 69321 success -call_value_to_existing Rex6 32621 69321 success -call_value_to_existing Rex7 32621 69321 success - -callcode_value Equivalence 0 30321 success -callcode_value MiniRex 30321 30321 success -callcode_value MiniRex1 0 30321 success -callcode_value MiniRex2 30321 30321 success -callcode_value Rex 30321 69321 success -callcode_value Rex1 30321 69321 success -callcode_value Rex2 30321 69321 success -callcode_value Rex3 30321 69321 success -callcode_value Rex4 30321 69321 success -callcode_value Rex5 32621 69321 success -callcode_value Rex6 32621 69321 success -callcode_value Rex7 32621 69321 success - -delegatecall Equivalence 0 23618 success -delegatecall MiniRex 23618 23618 success -delegatecall MiniRex1 0 23618 success -delegatecall MiniRex2 23618 23618 success -delegatecall Rex 23618 62618 success -delegatecall Rex1 23618 62618 success -delegatecall Rex2 23618 62618 success -delegatecall Rex3 23618 62618 success -delegatecall Rex4 23618 62618 success -delegatecall Rex5 23618 62618 success -delegatecall Rex6 23618 62618 success -delegatecall Rex7 23618 62618 success - -staticcall Equivalence 0 23618 success -staticcall MiniRex 23618 23618 success -staticcall MiniRex1 0 23618 success -staticcall MiniRex2 23618 23618 success -staticcall Rex 23618 62618 success -staticcall Rex1 23618 62618 success -staticcall Rex2 23618 62618 success -staticcall Rex3 23618 62618 success -staticcall Rex4 23618 62618 success -staticcall Rex5 23618 62618 success -staticcall Rex6 23618 62618 success -staticcall Rex7 23618 62618 success - -nested_calls_depth3 Equivalence 0 26236 success -nested_calls_depth3 MiniRex 26236 26236 success -nested_calls_depth3 MiniRex1 0 26236 success -nested_calls_depth3 MiniRex2 26236 26236 success -nested_calls_depth3 Rex 26236 65236 success -nested_calls_depth3 Rex1 26236 65236 success -nested_calls_depth3 Rex2 26236 65236 success -nested_calls_depth3 Rex3 26236 65236 success -nested_calls_depth3 Rex4 26236 65236 success -nested_calls_depth3 Rex5 26236 65236 success -nested_calls_depth3 Rex6 26236 65236 success -nested_calls_depth3 Rex7 26236 65236 success - -create_empty_initcode Equivalence 0 53009 success -create_empty_initcode MiniRex 53009 2053009 success -create_empty_initcode MiniRex1 0 53009 success -create_empty_initcode MiniRex2 53009 2053009 success -create_empty_initcode Rex 53009 92009 success -create_empty_initcode Rex1 53009 92009 success -create_empty_initcode Rex2 53009 92009 success -create_empty_initcode Rex3 53009 92009 success -create_empty_initcode Rex4 53009 92009 success -create_empty_initcode Rex5 53009 92009 success -create_empty_initcode Rex6 53009 92009 success -create_empty_initcode Rex7 53009 92009 success - -create2_empty_initcode Equivalence 0 53012 success -create2_empty_initcode MiniRex 53012 2053012 success -create2_empty_initcode MiniRex1 0 53012 success -create2_empty_initcode MiniRex2 53012 2053012 success -create2_empty_initcode Rex 53012 92012 success -create2_empty_initcode Rex1 53012 92012 success -create2_empty_initcode Rex2 53012 92012 success -create2_empty_initcode Rex3 53012 92012 success -create2_empty_initcode Rex4 53012 92012 success -create2_empty_initcode Rex5 53012 92012 success -create2_empty_initcode Rex6 53012 92012 success -create2_empty_initcode Rex7 53012 92012 success - -create2_with_initcode Equivalence 0 53032 success -create2_with_initcode MiniRex 53032 2053032 success -create2_with_initcode MiniRex1 0 53032 success -create2_with_initcode MiniRex2 53032 2053032 success -create2_with_initcode Rex 53032 92032 success -create2_with_initcode Rex1 53032 92032 success -create2_with_initcode Rex2 53032 92032 success -create2_with_initcode Rex3 53032 92032 success -create2_with_initcode Rex4 53032 92032 success -create2_with_initcode Rex5 53032 92032 success -create2_with_initcode Rex6 53032 92032 success -create2_with_initcode Rex7 53032 92032 success - -create_deploying_runtime_code Equivalence 0 59431 success -create_deploying_runtime_code MiniRex 59431 2379431 success -create_deploying_runtime_code MiniRex1 0 59431 success -create_deploying_runtime_code MiniRex2 59431 2379431 success -create_deploying_runtime_code Rex 59431 418431 success -create_deploying_runtime_code Rex1 59431 418431 success -create_deploying_runtime_code Rex2 59431 418431 success -create_deploying_runtime_code Rex3 59431 418431 success -create_deploying_runtime_code Rex4 59431 418431 success -create_deploying_runtime_code Rex5 59431 418431 success -create_deploying_runtime_code Rex6 59431 418431 success -create_deploying_runtime_code Rex7 59431 418431 success - -create2_far_memory_offset Equivalence 0 67367 success -create2_far_memory_offset MiniRex 67367 2067367 success -create2_far_memory_offset MiniRex1 0 67367 success -create2_far_memory_offset MiniRex2 67367 2067367 success -create2_far_memory_offset Rex 67367 106367 success -create2_far_memory_offset Rex1 67367 106367 success -create2_far_memory_offset Rex2 67367 106367 success -create2_far_memory_offset Rex3 67367 106367 success -create2_far_memory_offset Rex4 67367 106367 success -create2_far_memory_offset Rex5 67367 106367 success -create2_far_memory_offset Rex6 67367 106367 success -create2_far_memory_offset Rex7 67367 106367 success - -create2_oversized_initcode Equivalence 0 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex1 0 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode MiniRex2 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex1 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex2 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex3 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex4 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex5 763907 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex6 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) -create2_oversized_initcode Rex7 21012 100000000 halt Base(Base(CreateInitCodeSizeLimit)) - -selfdestruct_to_empty Equivalence 0 53603 success -selfdestruct_to_empty MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty MiniRex1 0 53603 success -selfdestruct_to_empty MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_empty Rex2 53603 92603 success -selfdestruct_to_empty Rex3 53603 92603 success -selfdestruct_to_empty Rex4 53603 92603 success -selfdestruct_to_empty Rex5 53603 92603 success -selfdestruct_to_empty Rex6 53603 92603 success -selfdestruct_to_empty Rex7 53603 92603 success - -selfdestruct_to_existing Equivalence 0 28603 success -selfdestruct_to_existing MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing MiniRex1 0 28603 success -selfdestruct_to_existing MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_existing Rex2 28603 67603 success -selfdestruct_to_existing Rex3 28603 67603 success -selfdestruct_to_existing Rex4 28603 67603 success -selfdestruct_to_existing Rex5 28603 67603 success -selfdestruct_to_existing Rex6 28603 67603 success -selfdestruct_to_existing Rex7 28603 67603 success - -selfdestruct_to_self Equivalence 0 26003 success -selfdestruct_to_self MiniRex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self MiniRex1 0 26003 success -selfdestruct_to_self MiniRex2 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex1 21003 100000000 halt Base(Base(InvalidFEOpcode)) -selfdestruct_to_self Rex2 26003 65003 success -selfdestruct_to_self Rex3 26003 65003 success -selfdestruct_to_self Rex4 26003 65003 success -selfdestruct_to_self Rex5 26003 65003 success -selfdestruct_to_self Rex6 26003 65003 success -selfdestruct_to_self Rex7 26003 65003 success - -precompile_identity Equivalence 0 21157 success -precompile_identity MiniRex 23657 23657 success -precompile_identity MiniRex1 0 21157 success -precompile_identity MiniRex2 23657 23657 success -precompile_identity Rex 23657 62657 success -precompile_identity Rex1 23657 62657 success -precompile_identity Rex2 23657 62657 success -precompile_identity Rex3 23657 62657 success -precompile_identity Rex4 23657 62657 success -precompile_identity Rex5 23657 62657 success -precompile_identity Rex6 23657 62657 success -precompile_identity Rex7 23657 62657 success - -precompile_sha256 Equivalence 0 21211 success -precompile_sha256 MiniRex 23711 23711 success -precompile_sha256 MiniRex1 0 21211 success -precompile_sha256 MiniRex2 23711 23711 success -precompile_sha256 Rex 23711 62711 success -precompile_sha256 Rex1 23711 62711 success -precompile_sha256 Rex2 23711 62711 success -precompile_sha256 Rex3 23711 62711 success -precompile_sha256 Rex4 23711 62711 success -precompile_sha256 Rex5 23711 62711 success -precompile_sha256 Rex6 23711 62711 success -precompile_sha256 Rex7 23711 62711 success - -precompile_kzg_invalid_input Equivalence 0 221133 success -precompile_kzg_invalid_input MiniRex 23633 223633 success -precompile_kzg_invalid_input MiniRex1 0 221133 success -precompile_kzg_invalid_input MiniRex2 23633 223633 success -precompile_kzg_invalid_input Rex 23633 262633 success -precompile_kzg_invalid_input Rex1 23633 262633 success -precompile_kzg_invalid_input Rex2 23633 262633 success -precompile_kzg_invalid_input Rex3 23633 262633 success -precompile_kzg_invalid_input Rex4 23633 262633 success -precompile_kzg_invalid_input Rex5 123633 262633 success -precompile_kzg_invalid_input Rex6 123633 262633 success -precompile_kzg_invalid_input Rex7 123633 262633 success - -precompile_underfunded Equivalence 0 21140 success -precompile_underfunded MiniRex 23639 23640 success -precompile_underfunded MiniRex1 0 21140 success -precompile_underfunded MiniRex2 23639 23640 success -precompile_underfunded Rex 23639 62640 success -precompile_underfunded Rex1 23639 62640 success -precompile_underfunded Rex2 23639 62640 success -precompile_underfunded Rex3 23639 62640 success -precompile_underfunded Rex4 23639 62640 success -precompile_underfunded Rex5 23640 62640 success -precompile_underfunded Rex6 23640 62640 success -precompile_underfunded Rex7 23640 62640 success - -reverting_subcall Equivalence 0 24326 success -reverting_subcall MiniRex 24326 24326 success -reverting_subcall MiniRex1 0 24326 success -reverting_subcall MiniRex2 24326 24326 success -reverting_subcall Rex 24326 63326 success -reverting_subcall Rex1 24326 63326 success -reverting_subcall Rex2 24326 63326 success -reverting_subcall Rex3 24326 63326 success -reverting_subcall Rex4 24326 63326 success -reverting_subcall Rex5 24326 63326 success -reverting_subcall Rex6 24326 63326 success -reverting_subcall Rex7 24326 63326 success diff --git a/crates/mega-evm/tests/equivalence/evm_state.rs b/crates/mega-evm/tests/equivalence/evm_state.rs deleted file mode 100644 index 0d93c3466..000000000 --- a/crates/mega-evm/tests/equivalence/evm_state.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! Tests for the EVM state. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::bytecode::opcode::{INVALID, PUSH0, SLOAD}, - test_utils::{transact, MemoryDatabase}, - *, -}; -use revm::database::StateBuilder; - -/// Test that verifies the EVM state correctly tracks storage access for non-existent storage slots. -/// This test ensures that when a contract performs an SLOAD operation on a storage slot that -/// doesn't exist (storage slot 0), the EVM state properly records this access and includes -/// the storage slot in the contract's storage map, even though the slot was previously -/// uninitialized. -#[test] -fn test_evm_state_zero_storage() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, revm::bytecode::opcode::SLOAD]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO) - .unwrap(); - let state = result.state; - let contract = state.get(&contract_address).unwrap(); - // the non-existent storage slot will present in the state - assert_eq!(contract.storage.len(), 1); - assert!(contract.storage.contains_key(&U256::ZERO)); -} - -/// Test that verifies EVM state includes storage reads from failed transactions. -/// -/// This test ensures that when a transaction fails (reverts), any storage reads -/// that occurred before the failure are still properly recorded in the EVM state. -/// The contract reads storage slot 0 and then executes INVALID to cause a revert, -/// but the storage access should still be tracked in the resulting state. -#[test] -fn test_evm_state_include_failed_tx_reads() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, SLOAD, INVALID]; // read slot 0 and then revert - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO) - .unwrap(); - let storage = &result.state.get(&contract_address).as_ref().unwrap().storage; - assert!(storage.contains_key(&U256::ZERO)); -} - -/// Test that when an existing empty account is called but with no state changes, the account is -/// still marked as destroyed according to EIP-161: Specification-d. At the end of the transaction, -/// any account touched by the execution of that transaction which is now empty SHALL instead become -/// non-existent (i.e. deleted), where an account is considered to be touched when it is involved in -/// any potentially state-changing operation. This includes, but is not limited to, being the -/// recipient of a transfer of zero value. -#[test] -fn test_state_clear_with_noop_call() { - let empty_account = address!("0000000000000000000000000000000000100001"); - let caller = address!("0000000000000000000000000000000000100000"); - let mut db = MemoryDatabase::default().account_nonce(empty_account, 0); - let mut state = StateBuilder::::default() - .with_database(&mut db) - .with_bundle_update() - .build(); - - // Call the non-existing account with no transfer - let result = transact( - MegaSpecId::REX, - &mut state, - caller, - Some(empty_account), - Bytes::default(), - U256::ZERO, - ) - .unwrap(); - // assert that the non-existing account is marked as touched - assert!(result.state.get(&empty_account).unwrap().is_touched()); - - // apply the state changes and get the transitions - let transitions = state.cache.apply_evm_state(result.state); - let (_, transition) = - transitions.iter().find(|(address, _)| *address == empty_account).unwrap(); - // assert that the storage is marked as destroyed - assert!(transition.storage_was_destroyed); -} diff --git a/crates/mega-evm/tests/equivalence/main.rs b/crates/mega-evm/tests/equivalence/main.rs deleted file mode 100644 index 89780e3d6..000000000 --- a/crates/mega-evm/tests/equivalence/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Tests for Equivalence spec (baseline EVM behavior). - -mod evm_state; diff --git a/crates/mega-evm/tests/mini_rex/db_error.rs b/crates/mega-evm/tests/mini_rex/db_error.rs deleted file mode 100644 index cd54ac334..000000000 --- a/crates/mega-evm/tests/mini_rex/db_error.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! Tests for DB error handling via `JournalInspectTr`. -//! -//! Verifies that when the database returns an error during `inspect_account_delegated` or -//! `inspect_storage`, the EVM properly halts with `FatalExternalError` and surfaces the error -//! as `EVMError::Custom`. - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, - EVMError, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::CALL, - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); -const TARGET: Address = address!("3000000000000000000000000000000000000003"); - -fn transact( - spec: MegaSpecId, - db: ErrorInjectingDatabase, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// When `inspect_storage` fails during SSTORE (in `additional_limit_ext::sstore`), -/// the EVM should halt with `FatalExternalError` and return `EVMError::Custom`. -#[test] -fn test_sstore_db_error_on_inspect_storage() { - let storage_key = U256::from(0x42); - let storage_value = U256::from(0x1); - - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when the SSTORE instruction's `inspect_storage` tries to read this slot. - db.fail_on_storage = Some((CALLEE, storage_key)); - - let result = transact( - MegaSpecId::MINI_REX, - db, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 1_000_000, - ); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected storage()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -/// When `inspect_account_delegated` fails during CALL with value transfer -/// (in `wrap_call_with_storage_gas!`), the EVM should halt with `FatalExternalError`. -#[test] -fn test_call_with_transfer_db_error_on_inspect_account() { - // Build bytecode that does CALL with value transfer to TARGET. - // CALL args: gas, addr, value, argsOffset, argsSize, retOffset, retSize - let bytecode = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value (non-zero to trigger value transfer path) - .push_address(TARGET) - .push_number(100_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when the CALL instruction's `inspect_account_delegated` tries to load TARGET. - db.fail_on_account = Some(TARGET); - - let result = transact( - MegaSpecId::MINI_REX, - db, - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, - 1_000_000, - ); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected basic()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} - -/// Regression: `inspect_storage` must not query `DB::storage` for accounts created in the -/// current transaction. Their post-CREATE storage is guaranteed empty (EIP-161 / EIP-6780), -/// so any DB read returns ZERO at best — and fails outright under stateless replay, where -/// no witness exists for these slots when CREATE lands on a pre-funded address (its -/// `Loaded` cache status bypasses revm's `State::storage` short-circuit). -/// -/// The injected DB is configured to error on every `storage()` read of slot 0 at the -/// to-be-created address. With the fix, `inspect_storage` short-circuits to ZERO for -/// newly-created accounts and the error is never triggered, so the CREATE succeeds. -/// Without the fix, the constructor's SSTORE pre-read would surface `EVMError::Custom` -/// (mini-rex routes SSTORE through `additional_limit_ext::sstore`, which calls -/// `inspect_storage` to compute the original/present values before writing). -#[test] -fn test_inspect_storage_skips_db_for_newly_created_account() { - // Initcode: SSTORE slot 0 = 0x42; STOP. The SSTORE pre-read goes through - // `inspect_storage` and is the path the fix targets. - let initcode = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(0x42)).stop().build(); - - // CALLER's nonce starts at 0, so the top-level CREATE deploys to `CALLER.create(0)`. - let created = CALLER.create(0); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - // Pre-fund the future contract address so its DB cache status is `Loaded` rather than - // `Vacant` — this is the scenario that exposed the original bug. - inner_db.set_account_balance(created, U256::from(1)); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // The fix means this DB call must never happen. If it does, the test fails. - db.fail_on_storage = Some((created, U256::ZERO)); - - let result = transact(MegaSpecId::MINI_REX, db, CALLER, None, initcode, U256::ZERO, 10_000_000); - - let res = result.expect("CREATE should not surface a DB error"); - assert!( - res.result.is_success(), - "CREATE should succeed without DB::storage being queried, got: {:?}", - res.result - ); -} - -/// When `inspect_account_delegated` fails during STATICCALL (in `wrap_call_with_storage_gas!`), -/// the EVM should halt with `FatalExternalError`. -/// This tests a different code path from CALL-with-transfer: STATICCALL has no value parameter -/// but still calls `inspect_account_delegated` on the target to check `is_empty`. -/// -/// Uses REX spec because `wrap_call_with_storage_gas!` (which calls `inspect_account_delegated`) -/// is only wired for STATICCALL starting from REX (`MINI_REX` uses `compute_gas_ext::static_call` -/// which delegates directly to revm's handler without inspecting first). -#[test] -fn test_staticcall_db_error_on_inspect_account() { - // STATICCALL stack layout: gas, addr, argsOffset, argsSize, retOffset, retSize - let bytecode = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(TARGET) // addr - .push_number(100_000_u64) // gas - .append(revm::bytecode::opcode::STATICCALL) - .stop() - .build(); - - let mut inner_db = MemoryDatabase::default(); - inner_db.set_account_balance(CALLER, U256::from(100_000_000_000u64)); - inner_db.set_account_code(CALLEE, bytecode); - - let mut db = ErrorInjectingDatabase::new(inner_db); - // Fail when STATICCALL's `inspect_account_delegated` tries to load TARGET. - db.fail_on_account = Some(TARGET); - - let result = - transact(MegaSpecId::REX, db, CALLER, Some(CALLEE), Bytes::new(), U256::ZERO, 1_000_000); - - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected basic()"), - "error message should contain injected error, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected error, got success: {:?}", result.result), - } -} diff --git a/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs b/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs deleted file mode 100644 index 5aae3f245..000000000 --- a/crates/mega-evm/tests/mini_rex/disallow_selfdestruct.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Tests for the disabled SELFDESTRUCT opcode in the Mini-Rex spec. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::{ - bytecode::opcode::{PUSH0, SELFDESTRUCT}, - context::result::{ExecutionResult, ResultAndState}, - }, - test_utils::{transact, MemoryDatabase}, - *, -}; - -/// Test that verifies the SELFDESTRUCT opcode works normally before the Mini-Rex hardfork. -/// This test ensures that contracts using the SELFDESTRUCT opcode execute successfully -/// and consume the expected amount of gas when using the `EQUIVALENCE` spec. -#[test] -fn test_selfdestruct_allowed_before_mini_rex() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::EQUIVALENCE, &mut db, caller, callee, Bytes::default(), U256::ZERO); - assert!(result.is_ok()); - assert_eq!(result.unwrap().result.gas_used(), 26004); -} - -/// Test that verifies the SELFDESTRUCT opcode is disabled and returns `InvalidFEOpcode` after -/// the Mini-Rex hardfork. This test ensures that contracts attempting to use the SELFDESTRUCT -/// opcode are properly rejected with the correct halt reason when using the `MINI_REX` spec. -#[test] -fn test_selfdestruct_disallowed_after_mini_rex() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = - transact(MegaSpecId::MINI_REX, &mut db, caller, callee, Bytes::default(), U256::ZERO); - assert!(matches!( - result, - Ok(ResultAndState { - result: ExecutionResult::Halt { - reason: MegaHaltReason::Base(OpHaltReason::Base(EthHaltReason::InvalidFEOpcode)), - .. - }, - .. - }) - )); -} diff --git a/crates/mega-evm/tests/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/mini_rex/state_growth_limit.rs deleted file mode 100644 index 431cabc30..000000000 --- a/crates/mega-evm/tests/mini_rex/state_growth_limit.rs +++ /dev/null @@ -1,807 +0,0 @@ -//! Tests for the state growth limit feature of the `MegaETH` EVM. -//! -//! These tests verify that the state growth limit functionality correctly tracks and limits -//! the creation of new accounts and storage slots during transaction execution. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, DatabaseCommit, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const NEW_ACCOUNT: Address = address!("0000000000000000000000000000000000100003"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified state growth limit. -/// -/// Returns the execution result and the actual state growth used. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -/// Checks if the execution result indicates that the state growth limit was exceeded. -fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } - ) -} - -/// Creates a default transaction builder calling a contract. -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -// ============================================================================ -// BASIC STATE GROWTH TRACKING TESTS -// ============================================================================ - -#[test] -fn test_empty_transaction() { - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Empty transaction should have zero state growth"); -} - -#[test] -fn test_create_new_account_via_value_transfer() { - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // Transfer value to a new account - let tx = default_tx_builder(NEW_ACCOUNT).value(U256::from(100)).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Creating new account via value transfer should count as +1"); -} - -#[test] -fn test_create_new_storage_slot() { - // Contract that writes to a single storage slot - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(42)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Writing to empty storage slot should count as +1"); -} - -#[test] -fn test_clear_storage_slot() { - // Contract that writes to a slot then clears it - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(42)) // Write: 0 -> 42 (+1) - .sstore(U256::from(0), U256::from(0)) // Clear: 42 -> 0 (-1) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Creating then clearing a slot should result in zero net growth"); -} - -#[test] -fn test_contract_creation() { - // Simple contract to deploy - let deployed_code = BytecodeBuilder::default().stop().build(); - - // Deployment code that returns the contract code - let init_code = BytecodeBuilder::default().return_with_data(deployed_code).build(); - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - // CREATE transaction - let tx = TxEnvBuilder::default() - .caller(CALLER) - .create() - .data(init_code) - .gas_limit(10_000_000) - .build_fill(); - - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Contract creation should count as +1"); -} - -#[test] -fn test_multiple_writes_same_slot() { - // Contract that writes to the same slot multiple times - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // First write: 0 -> 1 (+1) - .sstore(U256::from(0), U256::from(2)) // Overwrite: 1 -> 2 (0) - .sstore(U256::from(0), U256::from(3)) // Overwrite: 2 -> 3 (0) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Multiple writes to same slot should only count first write"); -} - -// ============================================================================ -// NET GROWTH MODEL TESTS -// ============================================================================ - -#[test] -fn test_net_growth_calculation() { - // Create 3 slots, clear 1 slot -> net growth = 2 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Net growth should be 3 - 1 = 2"); -} - -#[test] -fn test_growth_eventually_zero() { - // Create and clear multiple slots, ending at zero - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .sstore(U256::from(1), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "All creates and clears should cancel out to zero"); -} - -#[test] -fn test_multiple_operations_net_growth() { - // Complex sequence: create 5, clear 2 -> net 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(1)) // +1 - .sstore(U256::from(2), U256::from(1)) // +1 - .sstore(U256::from(3), U256::from(1)) // +1 - .sstore(U256::from(4), U256::from(1)) // +1 - .sstore(U256::from(0), U256::from(0)) // -1 - .sstore(U256::from(1), U256::from(0)) // -1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Net growth should be 5 - 2 = 3"); -} - -#[test] -fn test_storage_slot_already_exists() { - // Write to a slot that already has a value (should not count) - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(100)) // Modify existing slot (0) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // Pre-populate the storage slot - db.set_account_storage(CALLEE, U256::from(0), U256::from(42)); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Modifying existing storage slot should not count as growth"); -} - -// ============================================================================ -// FRAME-BASED TRACKING TESTS -// ============================================================================ - -#[test] -fn test_simple_call_executes() { - // First, verify that a simple CALL actually executes the child code - // Child returns a specific value to prove it executed - let child_code = BytecodeBuilder::default().return_with_data(vec![0x42_u8]).build(); - - // Parent calls child and checks return value - let parent_code = BytecodeBuilder::default() - .push_number(32_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - // CALL result is on stack (1 = success, 0 = failure) - .assert_stack_value(0, U256::from(1)) // Verify CALL succeeded - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed if child executes"); -} - -#[test] -fn test_nested_call_successful_child() { - // Child contract that creates a storage slot - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in child - .stop() - .build(); - - // Parent contract that creates a storage slot and calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in parent - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - increased - .append(CALL) - // Check if CALL succeeded - .assert_stack_value(0, U256::from(1)) // CALL should return 1 on success - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Parent and child growth should both count"); -} - -#[test] -fn test_nested_call_reverting_child() { - // Child contract that creates a storage slot then reverts - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in child (will be discarded) - .revert() - .build(); - - // Parent contract that creates a storage slot and calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 in parent - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Child growth should be discarded on revert"); -} - -#[test] -fn test_deeply_nested_calls() { - // Level 2 contract: creates 1 slot - let level2_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .stop() - .build(); - - // Level 1 contract: creates 1 slot, calls level 2 - let level1_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // level 2 address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - // Level 0 (parent): creates 1 slot, calls level 1 - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CALLEE) // level 1 address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(address!("0000000000000000000000000000000000100010"), parent_code) - .account_code(CALLEE, level1_code) - .account_code(CONTRACT, level2_code); - - let tx = default_tx_builder(address!("0000000000000000000000000000000000100010")).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "All levels should contribute to growth"); -} - -#[test] -fn test_parent_creates_child_reverts() { - // Child that reverts after creating state - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 (will be discarded) - .sstore(U256::from(1), U256::from(2)) // +1 (will be discarded) - .revert() - .build(); - - // Parent creates 3 slots, calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Only parent growth should count"); -} - -#[test] -fn test_both_parent_and_child_create_state() { - // Child creates 2 slots - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .stop() - .build(); - - // Parent creates 3 slots, calls child - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5, "Parent (3) + child (2) = 5 total growth"); -} - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -#[test] -fn test_limit_exactly_at_limit() { - // Create exactly 3 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Exactly at limit should succeed"); -} - -#[test] -fn test_limit_exceeded_by_one() { - // Try to create 4 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .sstore(U256::from(3), U256::from(4)) // +1 (exceeds limit) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // Verify the halt reason details - the actual growth is preserved in the halt reason - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit, actual }, - .. - } => { - assert_eq!(*limit, 3); - assert_eq!(*actual, 4, "Should report actual growth that exceeded limit"); - } - _ => panic!("Expected StateGrowthLimitExceeded halt"), - } -} - -#[test] -fn test_limit_exceeded_in_nested_call() { - // Child creates 2 slots - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .stop() - .build(); - - // Parent creates 2 slots, then calls child (total would be 4, limit is 3) - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); -} - -#[test] -fn test_state_reverted_when_exceeding_limit() { - // Create 2 slots, then exceed limit on 3rd (with limit of 2) - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(100)) // +1 - .sstore(U256::from(1), U256::from(200)) // +1 - .sstore(U256::from(2), U256::from(300)) // +1 (exceeds) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // State should not be committed - db.commit(result.state); - - // Verify the storage was not persisted - let storage_0 = db.storage(CALLEE, U256::from(0)).unwrap(); - let storage_1 = db.storage(CALLEE, U256::from(1)).unwrap(); - let storage_2 = db.storage(CALLEE, U256::from(2)).unwrap(); - - assert_eq!(storage_0, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_1, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_2, U256::ZERO, "Storage should be reverted"); -} - -#[test] -fn test_gas_preserved_on_limit_exceeded() { - // Create slots until limit exceeded - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 (exceeds) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let gas_limit = 10_000_000_u64; - let tx = TxEnvBuilder::default().caller(CALLER).call(CALLEE).gas_limit(gas_limit).build_fill(); - - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // Gas should not all be consumed - let gas_used = result.result.gas_used(); - assert!(gas_used < gas_limit, "Gas should be preserved on limit exceeded, not all consumed"); -} - -// ============================================================================ -// COMPLEX SCENARIOS TESTS -// ============================================================================ - -#[test] -fn test_mixed_operations() { - // Contract that creates account via CREATE and writes storage - let deployed_code = BytecodeBuilder::default().stop().build(); - - let init_code = BytecodeBuilder::default().return_with_data(deployed_code).build(); - - // Main contract: writes storage then creates contract - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 storage - .sstore(U256::from(1), U256::from(2)) // +1 storage - .push_number(0_u64) // value - .mstore(0x00, init_code.clone()) // Store init code in memory - .push_number(init_code.len() as u64) // size - .push_number(0x00_u64) // offset - .append(CREATE) // +1 account - .append(POP) // Pop created address - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "2 storage slots + 1 account = 3 growth"); -} - -#[test] -fn test_multiple_transactions_reset_counters() { - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - // First transaction - let tx1 = default_tx_builder(CALLEE).nonce(0).build_fill(); - let (result1, state_growth1) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx1).unwrap(); - assert!(result1.result.is_success()); - assert_eq!(state_growth1, 1); - - // Commit first transaction - db.commit(result1.state); - - // Second transaction - counter should reset, but slot is now non-zero - let tx2 = default_tx_builder(CALLEE).nonce(1).build_fill(); - let (result2, state_growth2) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx2).unwrap(); - assert!(result2.result.is_success()); - assert_eq!(state_growth2, 0, "Second tx should have 0 growth as slot already exists"); -} - -#[test] -fn test_state_growth_tracked_in_mini_rex() { - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(1)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "MINI_REX spec should track state growth"); -} - -#[test] -fn test_state_growth_not_tracked_in_equivalence() { - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(1)).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::EQUIVALENCE, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "EQUIVALENCE spec should not track state growth"); -} - -// ============================================================================ -// TRACKER MIGRATION COVERAGE TESTS -// ============================================================================ - -/// Tests that when a child frame both writes a storage slot (+1 growth) and resets it back -/// to zero (-1 refund), then reverts, BOTH the growth and the refund are discarded. -/// -/// This exercises the new tracker's separate `discardable_usage` and `refund` fields -/// (vs the old tracker's single `i64 discardable`), ensuring they are both dropped on revert. -#[test] -fn test_child_write_and_refund_both_discarded_on_revert() { - // Child: write slot 0 from 0→1 (+1 growth), then reset slot 0 from 1→0 (-1 refund), then REVERT - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // growth: +1 - .sstore(U256::from(0), U256::from(0)) // refund: -1 - .revert() - .build(); - - // Parent: write slot 5 from 0→1 (+1 growth), CALL child, STOP - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(5), U256::from(1)) // growth: +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - // Only parent's slot 5 write should count; child's write (+1) and refund (-1) both discarded. - assert_eq!( - state_growth, 1, - "Child's growth and refund should both be discarded on revert, leaving only parent's +1" - ); -} diff --git a/crates/mega-evm/tests/mutation/access_evm.rs b/crates/mega-evm/tests/mutation/access_evm.rs deleted file mode 100644 index 8592160f1..000000000 --- a/crates/mega-evm/tests/mutation/access_evm.rs +++ /dev/null @@ -1,479 +0,0 @@ -//! Value / behavioral tests that close surviving mutants in `crates/mega-evm/src/access/` and -//! the `crates/mega-evm/src/evm/mod.rs` accessor methods. -//! -//! The `access/*` modules carry inline `#[cfg(test)] mod tests`, but those unit tests do not kill -//! the relevant mutants: the mutation run builds the integration test targets, and (for -//! `VolatileDataAccess::as_u8`) the inline assertions are tautological — they compare -//! `converted.as_u8()` against `expected_flag.as_u8()`, so a `-> 0` / `-> 1` mutant changes both -//! sides identically and the equality still holds. These integration tests instead pin the exact -//! discriminant / boolean / option value through the crate's public API. -//! -//! Covered survivors: -//! * `access/volatile.rs:89` — `VolatileDataAccess::as_u8 -> 0` and `-> 1`. Killed by asserting the -//! exact bit-position discriminant of several distinct variants (so neither constant matches all -//! of them). -//! * `access/tracker.rs:131` — `has_accessed_beneficiary_balance -> true`. Killed by asserting it -//! is `false` on a fresh tracker. -//! * `access/tracker.rs:104` — `get_volatile_data_info -> Some(Default::default())`. Killed by -//! asserting it is `None` on a fresh (no-access) tracker; the mutant returns `Some(empty)`. -//! * `access/tracker.rs:180` — `disable_access` depth guard (`>=` vs `<`, and the match-guard -//! replaced with `true` / `false`). Killed by re-disabling at a deeper / shallower depth and -//! observing whether the shallower depth is retained. -//! * `evm/mod.rs:107` — `Debug for MegaEvm::fmt -> Ok(())`. Killed by asserting the formatted -//! output contains the struct name and field; the mutant writes nothing. -//! * `evm/mod.rs:251` — `block_env_mut -> Box::leak(Box::new(Default::default()))`. Killed by -//! mutating a field through `block_env_mut` and reading it back via `block_env_ref`; the mutant -//! writes to a throwaway leaked env so the read shows the original value. -//! * `evm/mod.rs:379` — `get_accessed_bucket_ids -> vec![]` and `vec![Default::default()]`. Killed -//! by executing an `SSTORE`-set transaction under `TestExternalEnvs` (non-zero bucket IDs) and -//! asserting the returned IDs are non-empty and equal the predicted (non-zero) bucket ID. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - constants, - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, TestExternalEnvs, - VolatileDataAccess, VolatileDataAccessTracker, MIN_BUCKET_SIZE, -}; -use revm::context::{BlockEnv, TxEnv}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); -/// Block beneficiary (coinbase) used by the `disable_beneficiary` tests. -const BENEFICIARY: Address = address!("3000000000000000000000000000000000000003"); - -// ============================================================================ -// access/volatile.rs — VolatileDataAccess::as_u8 discriminant encoder -// ============================================================================ - -/// `as_u8()` returns the single-set-bit position. Pinning several distinct variants kills both the -/// `-> 0` mutant (the `BENEFICIARY_BALANCE`/`ORACLE` cases are non-zero) and the `-> 1` mutant -/// (the `BLOCK_NUMBER` case is zero), since no single constant can satisfy all of them. -#[test] -fn test_as_u8_returns_exact_bit_position_for_each_variant() { - assert_eq!(VolatileDataAccess::BLOCK_NUMBER.as_u8(), 0, "BLOCK_NUMBER is bit 0"); - assert_eq!(VolatileDataAccess::TIMESTAMP.as_u8(), 1, "TIMESTAMP is bit 1"); - assert_eq!(VolatileDataAccess::COINBASE.as_u8(), 2, "COINBASE is bit 2"); - assert_eq!(VolatileDataAccess::BLOB_HASH.as_u8(), 9, "BLOB_HASH is bit 9"); - assert_eq!( - VolatileDataAccess::BENEFICIARY_BALANCE.as_u8(), - 10, - "BENEFICIARY_BALANCE is bit 10" - ); - assert_eq!(VolatileDataAccess::ORACLE.as_u8(), 11, "ORACLE is bit 11"); -} - -// ============================================================================ -// access/tracker.rs — VolatileDataAccessTracker accessors -// ============================================================================ - -fn new_tracker() -> VolatileDataAccessTracker { - VolatileDataAccessTracker::new(20_000_000, 20_000_000) -} - -/// A fresh tracker has not accessed the beneficiary balance. The `-> true` mutant flips this. -#[test] -fn test_has_accessed_beneficiary_balance_is_false_until_marked() { - let mut tracker = new_tracker(); - assert!( - !tracker.has_accessed_beneficiary_balance(), - "fresh tracker must report no beneficiary-balance access (kills the `-> true` mutant)" - ); - - tracker.mark_beneficiary_balance_accessed(); - assert!( - tracker.has_accessed_beneficiary_balance(), - "after marking, beneficiary-balance access must be reported" - ); -} - -/// A fresh tracker reports `None` for volatile-data info. The `-> Some(Default::default())` mutant -/// returns `Some(empty)`, which is `!= None`. -#[test] -fn test_get_volatile_data_info_is_none_until_accessed() { - let tracker = new_tracker(); - assert_eq!( - tracker.get_volatile_data_info(), - None, - "fresh tracker must report no volatile-data info (kills the `Some(empty)` mutant)" - ); - - let mut tracker = new_tracker(); - tracker.mark_beneficiary_balance_accessed(); - assert_eq!( - tracker.get_volatile_data_info(), - Some(VolatileDataAccess::BENEFICIARY_BALANCE), - "after a beneficiary access, the info must report exactly that access" - ); -} - -/// `disable_access` keeps the *shallower* (smaller) depth when already active and is a no-op when -/// the new depth is deeper. -/// -/// Killing the three `:180` mutants: -/// * `>=` → `<`: after `disable_access(5)` then `disable_access(8)`, the real code keeps depth 5 -/// (`8 >= 5` is a no-op). The mutant takes the else branch and overwrites with 8, so -/// `volatile_access_disabled(5)` would become false. -/// * guard → `false`: the guard is never taken, so `disable_access(8)` overwrites with 8 — same -/// observable failure as above. -/// * guard → `true`: the guard is always taken, so `disable_access(2)` becomes a no-op and the -/// shallower depth 2 is never adopted, leaving `volatile_access_disabled(2)` false. -#[test] -fn test_disable_access_keeps_shallower_depth() { - let mut tracker = new_tracker(); - - tracker.disable_access(5); - assert!(tracker.volatile_access_disabled(5), "depth 5 is disabled after disable_access(5)"); - assert!(!tracker.volatile_access_disabled(4), "depth 4 (shallower) is not disabled"); - - // Disabling at a deeper depth must NOT relax the restriction: depth 5 stays disabled. - // Real: `8 >= 5` → no-op, keeps 5. Mutants `<` / guard-`false`: overwrite with 8, so - // `volatile_access_disabled(5)` would become false (`5 >= 8` is false). - tracker.disable_access(8); - assert!( - tracker.volatile_access_disabled(5), - "re-disabling at a deeper depth must keep the shallower depth (kills `<` and guard-false)" - ); - - // Disabling at a shallower depth must tighten the restriction down to depth 2. - // Real: `2 >= 5` is false → else branch sets 2. Mutant guard-`true`: no-op, keeps 5, so - // `volatile_access_disabled(2)` would be false (`2 >= 5` is false). - tracker.disable_access(2); - assert!( - tracker.volatile_access_disabled(2), - "re-disabling at a shallower depth must adopt it (kills the guard-true mutant)" - ); -} - -// ============================================================================ -// evm/mod.rs — MegaEvm accessor methods -// ============================================================================ - -/// Build a bare `MegaEvm` over an empty in-memory database (no transaction executed). -fn empty_evm( - db: &mut MemoryDatabase, -) -> MegaEvm<&mut MemoryDatabase, revm::inspector::NoOpInspector, mega_evm::EmptyExternalEnv> { - let context = MegaContext::new(db, MegaSpecId::REX4); - MegaEvm::new(context) -} - -/// The `Debug` impl writes the struct name and the `inspect` field. The -/// `fmt -> Ok(Default::default())` mutant skips all writes, producing an empty body. -#[test] -fn test_debug_impl_writes_struct_name_and_field() { - let mut db = MemoryDatabase::default(); - let evm = empty_evm(&mut db); - - let rendered = format!("{evm:?}"); - assert!( - rendered.contains("MegaethEvm"), - "Debug output must contain the struct name, got: {rendered:?}" - ); - assert!( - rendered.contains("inspect"), - "Debug output must contain the `inspect` field, got: {rendered:?}" - ); -} - -/// `block_env_mut` must return a reference to the EVM's own block env, so a write through it is -/// visible via `block_env_ref`. The mutant returns a leaked default env, so the write is lost. -#[test] -fn test_block_env_mut_returns_live_block_env() { - let mut db = MemoryDatabase::default(); - let mut evm = empty_evm(&mut db); - - let sentinel = U256::from(0xABCD_u64); - evm.block_env_mut().number = sentinel; - - assert_eq!( - evm.block_env_ref().number, - sentinel, - "a write through block_env_mut must be observable via block_env_ref \ - (kills the leaked-default mutant)" - ); -} - -/// `get_accessed_bucket_ids` must report the SALT buckets touched during execution. An -/// `SSTORE`-set (zero → non-zero) records the slot's bucket. Under `TestExternalEnvs` the bucket -/// ID is non-zero, so the result distinguishes both the `vec![]` mutant (empty) and the -/// `vec![Default::default()]` mutant (`[0]`). -#[test] -fn test_get_accessed_bucket_ids_reports_touched_non_zero_bucket() { - let storage_slot = U256::from(1_u64); - - // Contract that sets storage slot 1 to a non-zero value, then stops. - let code = BytecodeBuilder::default().sstore(storage_slot, U256::from(1_u64)).stop().build(); - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - db.set_account_code(CONTRACT, code); - - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit: 10_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "SSTORE transaction should succeed: {:?}", result.result); - - // The SSTORE-set records the slot's bucket. Predict it from the same hasher the EVM uses. - let expected_bucket = - as SaltEnv>::bucket_id_for_slot(CONTRACT, storage_slot); - assert_ne!(expected_bucket, 0, "TestExternalEnvs must produce a non-zero bucket ID"); - - let buckets = evm.get_accessed_bucket_ids(); - assert!( - !buckets.is_empty(), - "an SSTORE-set transaction must record at least one accessed bucket (kills `vec![]`)" - ); - assert!( - buckets.contains(&expected_bucket), - "accessed buckets {buckets:?} must contain the SSTORE slot's bucket {expected_bucket} \ - (kills the `vec![Default::default()]` = [0] mutant)" - ); -} - -// ============================================================================ -// evm/context.rs:521 — MegaContext::disable_beneficiary -// ============================================================================ - -/// Runs a simple value-transfer transaction whose entire gas price is a priority fee (block -/// `basefee` is 0), and returns the block beneficiary's (coinbase's) post-transaction balance. -/// -/// When `disable` is true, `MegaContext::disable_beneficiary()` is called before execution; the -/// consumer at `evm/execution.rs:689` then skips `reward_beneficiary`, so the coinbase is NOT -/// credited the priority fee. Operator fees are zeroed so the only thing crediting the beneficiary -/// is the priority-fee reward. -fn beneficiary_balance_after_transfer(disable: bool) -> U256 { - const GAS_PRICE: u128 = 7; - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - - let block = BlockEnv { beneficiary: BENEFICIARY, basefee: 0, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - if disable { - context.disable_beneficiary(); - } - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - // Plain value transfer to a fresh account: no code runs, so the only beneficiary credit is - // the priority-fee reward. - kind: TxKind::Call(CONTRACT), - gas_limit: 1_000_000, - gas_price: GAS_PRICE, - value: U256::from(1_u64), - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "transfer should succeed: {:?}", result.result); - - result.state.get(&BENEFICIARY).map(|acct| acct.info.balance).unwrap_or(U256::ZERO) -} - -/// `disable_beneficiary()` must suppress the post-transaction coinbase reward. -/// -/// Control run (not disabled): the beneficiary is credited the priority fee, so its balance is -/// non-zero. Disabled run: the beneficiary reward is skipped, so its balance is zero. -/// -/// The `disable_beneficiary -> ()` no-op mutant never sets the flag, so the "disabled" run behaves -/// like the control and credits the beneficiary — making the `assert_eq!(disabled, ZERO)` below -/// fail, which kills the mutant. -#[test] -fn test_disable_beneficiary_suppresses_coinbase_reward() { - let credited = beneficiary_balance_after_transfer(false); - assert!( - credited > U256::ZERO, - "control run must credit the beneficiary the priority fee (sanity check)" - ); - - let suppressed = beneficiary_balance_after_transfer(true); - assert_eq!( - suppressed, - U256::ZERO, - "disable_beneficiary() must suppress the coinbase reward (kills the `-> ()` no-op mutant); \ - got {suppressed} vs control {credited}" - ); -} - -// ============================================================================ -// evm/execution.rs:167 — MegaHandler::before_execution intrinsic-gas boundary -// ============================================================================ - -/// Executes a plain call (no calldata, no access list, no value) to an existing code account that -/// immediately `STOP`s, with the given `gas_limit`, and returns the `transact_raw` outcome. -/// -/// Under REX the intrinsic gas of such a call is exactly `21000 + TX_INTRINSIC_STORAGE_GAS` -/// (no calldata words, no new-account creation since the callee already has code and the value is -/// zero). `MegaHandler::before_execution` (`evm/execution.rs:167`) halts the tx out-of-gas when -/// `gas_limit < initial_gas`. Operator fees and the basefee are zeroed so the only thing that can -/// make the tx fail at the boundary is that intrinsic-gas guard. -fn intrinsic_boundary_result( - gas_limit: u64, -) -> Result< - revm::context::result::ResultAndState, - revm::context::result::EVMError, -> { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_u64)); - // Callee already exists (has code) and just STOPs, so the call adds no new-account storage gas - // and burns no execution gas beyond the intrinsic cost. - db.set_account_code(CONTRACT, BytecodeBuilder::default().stop().build()); - - let block = BlockEnv { basefee: 0, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - gas_limit, - gas_price: 0, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// `before_execution` must allow a tx whose `gas_limit` equals its (fully Mega-adjusted) intrinsic -/// gas, and reject one below it. This pins the `<` boundary at `evm/execution.rs:167`. -/// -/// Under REX the intrinsic gas of the bare call above is `21000 + TX_INTRINSIC_STORAGE_GAS` -/// (= 60000). With `gas_limit == initial_gas` the real `gas_limit < initial_gas` check is `false`, -/// so `before_execution` returns `Ok(None)` and the tx executes and succeeds. The `<` → `<=` -/// mutant makes it `60000 <= 60000` → `true`, wrongly halting the exact-gas tx out-of-gas — caught -/// by the `is_success()` assertion below. The `gas_limit == initial_gas - 1` case pins the lower -/// side of the boundary: validation (`initial_gas > gas_limit`) rejects it as a transaction error. -#[test] -fn test_before_execution_allows_exact_intrinsic_gas() { - // Fully Mega-adjusted intrinsic gas for the bare REX call: base 21000 + the REX intrinsic - // storage surcharge. The `gas_used == intrinsic` assertion below self-validates this value. - let intrinsic: u64 = 21_000 + constants::rex::TX_INTRINSIC_STORAGE_GAS; - - // Exactly intrinsic gas: must execute and succeed (kills the `<` → `<=` mutant, which would - // OOG-halt this exact-gas tx). - let exact = intrinsic_boundary_result(intrinsic).expect("exact-gas tx must not be rejected"); - assert!( - exact.result.is_success(), - "a call with gas_limit == intrinsic gas ({intrinsic}) must succeed, not OOG-halt; \ - got {:?}", - exact.result - ); - assert_eq!( - exact.result.gas_used(), - intrinsic, - "the exact-gas call must consume exactly the intrinsic gas" - ); - - // One below intrinsic gas: must NOT succeed (pins the lower side of the boundary). Under REX - // this is surfaced as a `CallGasCostMoreThanGasLimit` validation error. - let one_below = intrinsic_boundary_result(intrinsic - 1); - assert!( - one_below.is_err() || !one_below.unwrap().result.is_success(), - "a call with gas_limit == intrinsic gas - 1 ({}) must fail the intrinsic-gas guard", - intrinsic - 1 - ); -} - -// ============================================================================ -// evm/context.rs:563 — MegaContext::on_new_block refreshes the dynamic gas cache -// ============================================================================ - -/// `on_new_block()` (invoked by `with_block`) must refresh the dynamic storage gas-cost -/// calculator for the new block. Concretely it calls `DynamicGasCost::on_new_block`, which -/// `reset`s the calculator and **clears its cached per-bucket cost multipliers**. The -/// `MegaContext::on_new_block -> ()` no-op mutant skips this, leaving a stale cached multiplier. -/// -/// Observable effect: under `MINI_REX` (but not REX), the SSTORE-set gas is -/// `SSTORE_SET_STORAGE_GAS * (capacity / MIN_BUCKET_SIZE)`. The calculator caches the multiplier -/// the first time a bucket is queried. If the underlying SALT bucket capacity changes between -/// blocks, the cached multiplier is stale until `on_new_block` clears it. -/// -/// The test primes the cache at capacity `C1`, then mutates the shared `TestExternalEnvs` bucket -/// capacity to `C2` (the env is shared by `Rc`), then calls `with_block` to drive -/// `on_new_block`, and asserts the recomputed SSTORE gas reflects `C2`. The no-op mutant keeps the -/// stale `C1` multiplier, so the assertion fails — killing the mutant. -#[test] -fn test_on_new_block_clears_stale_dynamic_gas_cache() { - let min_bucket = MIN_BUCKET_SIZE as u64; - // Two capacities yielding distinct multipliers (capacity / MIN_BUCKET_SIZE). - let cap_before = 2 * min_bucket; // multiplier 2 - let cap_after = 3 * min_bucket; // multiplier 3 - let base = constants::mini_rex::SSTORE_SET_STORAGE_GAS; - let gas_before = base * 2; - let gas_after = base * 3; - - let storage_slot = U256::from(7_u64); - let bucket = - as SaltEnv>::bucket_id_for_slot(CONTRACT, storage_slot); - - // Shared env handle. `with_bucket_capacity` mutates the shared `Rc` map and returns - // `self`; cloning shares the same map, so later edits are visible to the EVM's clone. - let env = TestExternalEnvs::::new().with_bucket_capacity(bucket, cap_before); - - let mut db = MemoryDatabase::default(); - // MINI_REX (not REX) so the gas formula is the simple `base * multiplier`. - let context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs(env.clone().into()); - - // Prime the cache: the calculator now caches multiplier = cap_before / MIN_BUCKET_SIZE. - let primed = context - .dynamic_storage_gas_cost - .borrow_mut() - .sstore_set_gas(CONTRACT, storage_slot) - .unwrap(); - assert_eq!(primed, gas_before, "primed SSTORE gas must reflect the initial capacity"); - - // Change the shared bucket capacity. Without a cache clear, the calculator keeps `cap_before`. - env.clear_bucket_capacity(); - let _ = env.clone().with_bucket_capacity(bucket, cap_after); - assert_eq!( - as SaltEnv>::get_bucket_capacity(&env, bucket).unwrap(), - cap_after, - "the shared env must now report the new capacity" - ); - - // Drive `on_new_block` via the public `with_block`. Real code clears the stale cache; the - // no-op mutant leaves it. - let context = context.with_block(BlockEnv { number: U256::from(2_u64), ..Default::default() }); - - let recomputed = context - .dynamic_storage_gas_cost - .borrow_mut() - .sstore_set_gas(CONTRACT, storage_slot) - .unwrap(); - assert_eq!( - recomputed, gas_after, - "after on_new_block the dynamic gas cache must be refreshed to the new capacity \ - (kills the `on_new_block -> ()` no-op mutant; stale value would be {gas_before})" - ); -} diff --git a/crates/mega-evm/tests/mutation/block.rs b/crates/mega-evm/tests/mutation/block.rs deleted file mode 100644 index 0c55baac5..000000000 --- a/crates/mega-evm/tests/mutation/block.rs +++ /dev/null @@ -1,618 +0,0 @@ -//! Value/behavioral tests that close surviving mutants in `crates/mega-evm/src/block/`. -//! -//! The `src/block/*` modules carry inline `#[cfg(test)] mod tests`, but those unit tests are not -//! exercised by the mutation run (which builds the integration test targets). These integration -//! tests re-assert the same invariants through the crate's public API, using exact-value -//! assertions (never `> 0`, so the `-> 1` constant-return mutants die too). -//! -//! Covered survivors: -//! * `helpers.rs` — `MegaTransactionExt::{tx_size, tx_hash, estimated_da_size}` for -//! `MegaTxEnvelope`, `Recovered`, `Recovered<&MegaTxEnvelope>` and -//! `EnrichedMegaTx` (constant-return / `Default::default()` mutants). -//! * `limit.rs` — `BlockLimits::from_hardfork_and_block_gas_limit` per-field initializers (deleting -//! a field initializer makes it fall back to `..limits`, i.e. a different value). -//! * `hardfork.rs` — `MegaHardforks::is_*_active_at_timestamp` (`-> false` mutants). -//! * `chain.rs` — `hardfork_schedule` mainnet / testnet match arms (deleting an arm falls through -//! to the all-activated fallback, which has different activation conditions). - -use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; -use alloy_hardforks::ForkCondition; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, U256}; -use mega_evm::{ - constants, hardfork_schedule, mainnet_hardforks, testnet_hardforks, BlockLimits, - EnrichedMegaTx, MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaTransactionExt, - MegaTxEnvelope, MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000001"); -const CONTRACT: Address = address!("3000000000000000000000000000000000000001"); - -/// A known, non-zero cached tx hash baked into the test envelope. `MegaTxEnvelope::tx_hash` returns -/// the cached `Signed` hash, so storing a non-zero value here lets us distinguish the real accessor -/// from the `-> Default::default()` (== `TxHash::ZERO`) mutant. -const STORED_TX_HASH: alloy_primitives::B256 = - alloy_primitives::b256!("00000000000000000000000000000000000000000000000000000000000000aa"); - -/// A legacy transaction with a small, non-empty calldata so its encoded size and DA size are both -/// strictly greater than 1 (which kills both the `-> 0` and the `-> 1` constant-return mutants), -/// and a known non-zero cached hash so the `tx_hash` mutant is distinguishable. -fn legacy_envelope() -> MegaTxEnvelope { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 7, - gas_price: 9, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::from(11), - input: Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0xaa]), - }; - MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), STORED_TX_HASH)) -} - -// ============================================================================ -// block/helpers.rs — MegaTransactionExt accessors -// ============================================================================ - -/// `MegaTxEnvelope::tx_size`/`estimated_da_size` must return the real encoded sizes (well above 1), -/// and `tx_hash` must return the real hash (not `Default::default()`). -#[test] -fn test_mega_tx_envelope_ext_returns_real_size_da_and_hash() { - let tx = legacy_envelope(); - - // A signed legacy tx with 5 bytes of calldata encodes to far more than 1 byte. - let tx_size = MegaTransactionExt::tx_size(&tx); - let da_size = MegaTransactionExt::estimated_da_size(&tx); - assert!(tx_size > 1, "tx_size collapsed to a constant: {tx_size}"); - assert!(da_size > 1, "estimated_da_size collapsed to a constant: {da_size}"); - - // tx_hash must return the cached hash, not Default::default() (== TxHash::ZERO). - let h = MegaTransactionExt::tx_hash(&tx); - assert_ne!(h, alloy_primitives::TxHash::ZERO, "tx_hash returned Default::default()"); - assert_eq!(h, STORED_TX_HASH, "tx_hash mismatch"); -} - -/// `Recovered::tx_hash` must return the inner envelope hash, not the default. -#[test] -fn test_recovered_mega_tx_envelope_ext_returns_real_hash() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx, CALLER); - - let h = MegaTransactionExt::tx_hash(&recovered); - assert_ne!(h, alloy_primitives::TxHash::ZERO, "recovered tx_hash returned Default::default()"); - assert_eq!(h, STORED_TX_HASH, "recovered tx_hash mismatch"); -} - -/// `Recovered<&MegaTxEnvelope>::tx_hash` must return the inner envelope hash, not the default. -/// Same shape as the owned `Recovered` case above, but for the by-reference impl -/// `MegaBlockExecutor::run_transaction` needs now that its bound is `MegaTransactionExt` (a -/// zero-copy `Recovered<&Tx>` is the common way a caller satisfies `Copy` without cloning the -/// transaction). -#[test] -fn test_recovered_ref_mega_tx_envelope_ext_returns_real_hash() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(&tx, CALLER); - - let h = MegaTransactionExt::tx_hash(&recovered); - assert_ne!( - h, - alloy_primitives::TxHash::ZERO, - "recovered-ref tx_hash returned Default::default()" - ); - assert_eq!(h, STORED_TX_HASH, "recovered-ref tx_hash mismatch"); -} - -/// `EnrichedMegaTx::{tx_size, estimated_da_size, tx_hash}` must dispatch to the stored fields, not -/// recompute from the inner transaction. Constructs the wrapper with stored values that -/// deliberately differ from what a fresh recomputation on the inner tx would produce, so a mutant -/// collapsing the override to a constant (or one that silently falls back to recomputing) is -/// distinguishable. -#[test] -fn test_enriched_mega_tx_ext_returns_stored_fields_not_recomputed() { - let tx = legacy_envelope(); - let recovered = Recovered::new_unchecked(tx, CALLER); - - let real_da_size = MegaTransactionExt::estimated_da_size(&recovered); - let real_tx_size = MegaTransactionExt::tx_size(&recovered); - - const STORED_DA_SIZE: u64 = 424_242; - const STORED_TX_SIZE: u64 = 131_313; - assert_ne!(STORED_DA_SIZE, real_da_size, "stored da_size must differ from a fresh recompute"); - assert_ne!(STORED_TX_SIZE, real_tx_size, "stored tx_size must differ from a fresh recompute"); - - let enriched = EnrichedMegaTx::new(recovered, STORED_TX_HASH, STORED_DA_SIZE, STORED_TX_SIZE); - - assert_eq!( - MegaTransactionExt::estimated_da_size(&enriched), - STORED_DA_SIZE, - "estimated_da_size must return the stored field, not a recomputed value" - ); - assert_eq!( - MegaTransactionExt::tx_size(&enriched), - STORED_TX_SIZE, - "tx_size must return the stored field, not a recomputed value" - ); - assert_eq!( - MegaTransactionExt::tx_hash(&enriched), - STORED_TX_HASH, - "tx_hash must return the stored field, not Default::default()" - ); -} - -// ============================================================================ -// block/limit.rs — BlockLimits::from_hardfork_and_block_gas_limit -// ============================================================================ - -/// For a Rex hardfork, all three block-level field initializers must be set to their constants. -/// Deleting any initializer drops back to `..limits` (== `no_limits()` => `u64::MAX` for -/// state-growth, and the same `MiniRex` constants for data/kv), so asserting the exact value kills -/// the field-deletion mutants on lines 399/400/401. -#[test] -fn test_block_limits_from_rex_sets_all_three_block_fields() { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::Rex4, 50_000_000); - - assert_eq!( - limits.block_txs_data_limit, - constants::mini_rex::BLOCK_DATA_LIMIT, - "block_txs_data_limit initializer dropped" - ); - assert_eq!( - limits.block_kv_update_limit, - constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - "block_kv_update_limit initializer dropped" - ); - assert_eq!( - limits.block_state_growth_limit, - constants::rex::BLOCK_STATE_GROWTH_LIMIT, - "block_state_growth_limit initializer dropped" - ); - assert_eq!(limits.block_gas_limit, 50_000_000, "block gas limit not applied"); -} - -/// For the `MiniRex` arm, `block_txs_data_limit` and `block_kv_update_limit` are set to the -/// `MiniRex` constants while `block_state_growth_limit` stays at the `no_limits()` default -/// (`u64::MAX`). Asserting the exact data/kv values kills the field-deletion mutants on lines -/// 405/406; the state-growth assertion pins the arm's distinct shape. -#[test] -fn test_block_limits_from_mini_rex_sets_data_and_kv_fields() { - let limits = BlockLimits::from_hardfork_and_block_gas_limit(MegaHardfork::MiniRex, 30_000_000); - - assert_eq!( - limits.block_txs_data_limit, - constants::mini_rex::BLOCK_DATA_LIMIT, - "MiniRex block_txs_data_limit initializer dropped" - ); - assert_eq!( - limits.block_kv_update_limit, - constants::mini_rex::BLOCK_KV_UPDATE_LIMIT, - "MiniRex block_kv_update_limit initializer dropped" - ); - // MiniRex does not set a block state-growth limit; it inherits no_limits(). - assert_eq!( - limits.block_state_growth_limit, - u64::MAX, - "MiniRex must not set a block state-growth limit" - ); -} - -// ============================================================================ -// block/hardfork.rs — is_*_active_at_timestamp -// ============================================================================ - -/// Build a config where every named fork activates at a distinct, increasing timestamp so each -/// `is_*_active_at_timestamp` can be probed both before and at activation. -fn staged_config() -> MegaHardforkConfig { - MegaHardforkConfig::new() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(100)) - .with(MegaHardfork::MiniRex1, ForkCondition::Timestamp(200)) - .with(MegaHardfork::MiniRex2, ForkCondition::Timestamp(300)) - .with(MegaHardfork::Rex, ForkCondition::Timestamp(400)) - .with(MegaHardfork::Rex1, ForkCondition::Timestamp(500)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(600)) - .with(MegaHardfork::Rex3, ForkCondition::Timestamp(700)) - .with(MegaHardfork::Rex4, ForkCondition::Timestamp(800)) - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(900)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(1000)) - .with(MegaHardfork::Rex7, ForkCondition::Timestamp(1100)) -} - -/// Each `is_*_active_at_timestamp` returns `true` at/after activation and `false` before, on a -/// complete ordered ladder (where the position-projected predicates coincide with the activation -/// events). This kills the `-> false` mutants on the predicate bodies in -/// `crates/mega-evm/src/block/hardfork.rs` at the lines referenced below. -/// -/// Every predicate is probed on **both** sides of its own activation, which is what pins the -/// spec each one projects. A behavior-introducing predicate's body is -/// `spec_id(t).reaches(MegaSpecId::X)`, so shifting `X` one rung either way is a -/// live mutation: shifting down makes the predicate fire at the rung below (caught by the -/// `false` assertion one second early), shifting up makes it stop firing at its own rung (caught -/// by the `true` assertion). A one-sided probe kills neither direction. -#[test] -fn test_hardfork_activation_predicates_are_true_at_activation() { - let cfg = staged_config(); - - // MiniRex (hardfork.rs:192) — spec-introducing (MINI_REX). Shifting down lands on - // EQUIVALENCE, which is enabled at every timestamp, so only the `false` side catches it. - assert!(!cfg.is_mini_rex_active_at_timestamp(99)); - assert!(cfg.is_mini_rex_active_at_timestamp(100)); - - // MiniRex1 (hardfork.rs:203) — alias fork, raw event query. - assert!(!cfg.is_mini_rex_1_active_at_timestamp(199)); - assert!(cfg.is_mini_rex_1_active_at_timestamp(200)); - - // MiniRex2 (hardfork.rs:213) — alias fork, raw event query. - assert!(!cfg.is_mini_rex_2_active_at_timestamp(299)); - assert!(cfg.is_mini_rex_2_active_at_timestamp(300)); - - // Rex (hardfork.rs:220). - assert!(!cfg.is_rex_active_at_timestamp(399)); - assert!(cfg.is_rex_active_at_timestamp(400)); - - // Rex1 (hardfork.rs:227). - assert!(!cfg.is_rex_1_active_at_timestamp(499)); - assert!(cfg.is_rex_1_active_at_timestamp(500)); - - // Rex2 (hardfork.rs:234). - assert!(!cfg.is_rex_2_active_at_timestamp(599)); - assert!(cfg.is_rex_2_active_at_timestamp(600)); - - // Rex3 (hardfork.rs:241). - assert!(!cfg.is_rex_3_active_at_timestamp(699)); - assert!(cfg.is_rex_3_active_at_timestamp(700)); - - // Rex4 (hardfork.rs:248). - assert!(!cfg.is_rex_4_active_at_timestamp(799)); - assert!(cfg.is_rex_4_active_at_timestamp(800)); - - // Rex5 (hardfork.rs:255). - assert!(!cfg.is_rex_5_active_at_timestamp(899)); - assert!(cfg.is_rex_5_active_at_timestamp(900)); - - // Rex6 (hardfork.rs:262). - assert!(!cfg.is_rex_6_active_at_timestamp(999)); - assert!(cfg.is_rex_6_active_at_timestamp(1000)); - - // Rex7 (hardfork.rs:269). - assert!(!cfg.is_rex_7_active_at_timestamp(1099)); - assert!(cfg.is_rex_7_active_at_timestamp(1100)); -} - -// ============================================================================ -// block/chain.rs — hardfork_schedule match arms -// ============================================================================ - -/// Deleting the `MAINNET_CHAIN_ID` arm makes `hardfork_schedule(4326)` fall through to the -/// all-activated fallback, which activates `MiniRex1` at genesis. The real mainnet schedule -/// activates `MiniRex1` at a specific non-zero timestamp, so the per-fork conditions distinguish -/// the two. -#[test] -fn test_hardfork_schedule_mainnet_arm_returns_mainnet_schedule() { - let from_dispatch = hardfork_schedule(MAINNET_CHAIN_ID); - let expected = mainnet_hardforks(); - - // MiniRex1 activation timestamp is mainnet-specific (1764845637), differs from the genesis - // activation of the all-activated fallback. - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - expected.get(MegaHardfork::MiniRex1), - "mainnet arm did not return the mainnet schedule" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - Some(&ForkCondition::Timestamp(1764845637)), - "mainnet MiniRex1 activation timestamp changed" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::Rex5), - Some(&ForkCondition::Timestamp(1780632000)), - "mainnet Rex5 activation timestamp changed" - ); -} - -/// Deleting the `TESTNET_CHAIN_ID` arm makes `hardfork_schedule(6343)` fall through to the -/// all-activated fallback. The testnet schedule sets MiniRex1/MiniRex2 to `Never` and Rex5 to a -/// testnet-specific timestamp, none of which the fallback reproduces. -#[test] -fn test_hardfork_schedule_testnet_arm_returns_testnet_schedule() { - let from_dispatch = hardfork_schedule(TESTNET_CHAIN_ID); - let expected = testnet_hardforks(); - - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - expected.get(MegaHardfork::MiniRex1), - "testnet arm did not return the testnet schedule" - ); - // Testnet disables MiniRex1 (Never) — the all-activated fallback would activate it at genesis. - assert_eq!( - from_dispatch.get(MegaHardfork::MiniRex1), - Some(&ForkCondition::Never), - "testnet MiniRex1 should be Never" - ); - assert_eq!( - from_dispatch.get(MegaHardfork::Rex5), - Some(&ForkCondition::Timestamp(1780459200)), - "testnet Rex5 activation timestamp changed" - ); -} - -// ============================================================================ -// block/limit.rs — BlockLimiter -// ============================================================================ -// -// `BlockLimiter` (`pub`, re-exported via `block::*`) is constructed directly with -// `BlockLimiter::new(BlockLimits)` and its `pub` usage counters are written directly, -// mirroring the inline `#[cfg(test)]` pattern at `limit.rs:1027+`. We start from -// `BlockLimits::no_limits()` (every limit == `u64::MAX`) and tighten exactly the one -// dimension under test, so the other clauses/checks cannot interfere. -// -// Covered survivors: -// * `pre_execution_check` boundary `>` checks (778/789/802/839): an at-limit value must return `Ok` -// (kills both `>`→`==` and `>`→`>=`, which error at equality); a strictly over-limit value must -// return the expected `Err`. -// * `post_execution_update` (947) `==`→`!=` on the deposit-type check: a non-deposit tx must -// advance `block_da_size_used`; a deposit tx must not. The `!=` mutant inverts both. -// * `is_block_limit_reached` (1011-1019): one per-dimension test with only that dimension at `used -// == limit` (others strictly below) asserting `true` kills that clause's `>=`→`<` and the -// adjacent `||`→`&&` (only one true clause ⇒ `&&` collapses to false); an all-below test -// asserting `false` kills the whole-fn `->true`, and the per-dimension trues kill the whole-fn -// `->false`. - -use alloy_consensus::transaction::Recovered as MegaRecovered; -use alloy_primitives::B256; -use mega_evm::{BlockLimiter, BlockMegaTransactionOutcome, MegaHaltReason, MegaTransactionOutcome}; -use revm::{ - context::result::{ExecutionResult, Output, SuccessReason}, - state::EvmState, -}; - -/// Builds a `BlockMegaTransactionOutcome` wrapping the given recovered tx, with the supplied -/// `da_size` and otherwise-zero usage, and a trivial `Success` execution result. Used to drive -/// `post_execution_update` and observe how the deposit-type branch routes the da accounting. -fn outcome_for( - tx: MegaRecovered, - da_size: u64, -) -> BlockMegaTransactionOutcome> { - BlockMegaTransactionOutcome { - tx, - tx_size: 0, - da_size, - depositor: None, - inner: MegaTransactionOutcome { - result: ExecutionResult::::Success { - reason: SuccessReason::Stop, - gas_used: 0, - gas_refunded: 0, - logs: Vec::new(), - output: Output::Call(Bytes::new()), - }, - state: EvmState::default(), - data_size: 0, - kv_updates: 0, - compute_gas_used: 0, - state_growth_used: 0, - }, - } -} - -/// A non-deposit (legacy, tx type 0) recovered transaction. -fn legacy_recovered() -> MegaRecovered { - let tx = TxLegacy { - chain_id: Some(1), - nonce: 0, - gas_price: 1, - gas_limit: 21_000, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO); - MegaRecovered::new_unchecked(MegaTxEnvelope::Legacy(signed), CALLER) -} - -// --------------------------------------------------------------------------- -// pre_execution_check boundaries -// --------------------------------------------------------------------------- - -/// 778:22 (`gas_limit > self.limits.tx_gas_limit`). A gas limit *equal* to the per-tx cap must -/// pass (kills `>`→`==` and `>`→`>=`, which both error at equality); one over must error. -#[test] -fn test_pre_execution_check_tx_gas_limit_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.tx_gas_limit = 1_000; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 1_000, 0, 0, false).is_ok(), - "gas_limit == tx_gas_limit must be admitted (boundary is strict `>`)" - ); - let over = limiter.pre_execution_check(B256::ZERO, 1_001, 0, 0, false); - assert!(over.is_err(), "gas_limit == tx_gas_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionGasLimit"), - "over-limit gas must report the per-tx gas-limit error" - ); -} - -/// 789:58 (`block_gas_used + gas_limit > block_gas_limit`). With `block_gas_used == 0`, a -/// `gas_limit` exactly equal to `block_gas_limit` must pass (kills `>`→`>=`); one over errors. -#[test] -fn test_pre_execution_check_block_gas_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 1_000; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 1_000, 0, 0, false).is_ok(), - "block_gas_used + gas_limit == block_gas_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 1_001, 0, 0, false); - assert!(over.is_err(), "block_gas_used + gas_limit == block_gas_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionGasLimitMoreThanAvailableBlockGas"), - "over-limit block gas must report the available-block-gas error" - ); -} - -/// 802:20 (`tx_size > self.limits.tx_encode_size_limit`). A `tx_size` equal to the cap must pass -/// (kills `>`→`==` and `>`→`>=`); one over errors. -#[test] -fn test_pre_execution_check_tx_size_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.tx_encode_size_limit = 500; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 0, 500, 0, false).is_ok(), - "tx_size == tx_encode_size_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 0, 501, 0, false); - assert!(over.is_err(), "tx_size == tx_encode_size_limit + 1 must be rejected"); - assert!( - format!("{:?}", over.unwrap_err()).contains("TransactionEncodeSizeLimit"), - "over-limit tx size must report the per-tx encode-size error" - ); -} - -/// 839:64 (`da_size + block_da_size_used > block_da_size_limit`). With `block_da_size_used == 0`, -/// a non-deposit `da_size` equal to `block_da_size_limit` must pass (kills `>`→`>=`); one over -/// errors. (`tx_da_size_limit` stays `u64::MAX`, so the per-tx da check at 828 never triggers.) -#[test] -fn test_pre_execution_check_block_da_size_boundary() { - let mut limits = BlockLimits::no_limits(); - limits.block_da_size_limit = 800; - let limiter = BlockLimiter::new(limits); - - assert!( - limiter.pre_execution_check(B256::ZERO, 0, 0, 800, false).is_ok(), - "da_size + block_da_size_used == block_da_size_limit must be admitted" - ); - let over = limiter.pre_execution_check(B256::ZERO, 0, 0, 801, false); - assert!( - over.is_err(), - "da_size + block_da_size_used == block_da_size_limit + 1 must be rejected" - ); - assert!( - format!("{:?}", over.unwrap_err()).contains("DataAvailabilitySizeLimit"), - "over-limit block da must report the data-availability error" - ); -} - -// --------------------------------------------------------------------------- -// post_execution_update — deposit-type branch (947 `==`→`!=`) -// --------------------------------------------------------------------------- - -/// 947 (`outcome.tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE`). A non-deposit (legacy) tx must -/// advance `block_da_size_used` by `da_size`. Under the `==`→`!=` mutant the legacy type is -/// (mis)classified as a deposit, so the da counter would stay at 0. -#[test] -fn test_post_execution_update_advances_da_for_non_deposit() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - let outcome = outcome_for(legacy_recovered(), 1_234); - - limiter.post_execution_update(&outcome).expect("post_execution_update should succeed"); - - assert_eq!( - limiter.block_da_size_used, 1_234, - "a non-deposit tx must accumulate da_size; the `==`→`!=` mutant would skip it (0)" - ); -} - -// --------------------------------------------------------------------------- -// is_block_limit_reached — per-dimension boundary + all-clause OR (1011-1019) -// --------------------------------------------------------------------------- - -/// All counters strictly below their limits ⇒ `false`. Kills the whole-fn `->true` mutant. -#[test] -fn test_is_block_limit_reached_all_below_is_false() { - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 10; - limits.block_txs_encode_size_limit = 10; - limits.block_da_size_limit = 10; - limits.block_txs_data_limit = 10; - limits.block_kv_update_limit = 10; - limits.block_compute_gas_limit = 10; - limits.block_state_growth_limit = 10; - let mut limiter = BlockLimiter::new(limits); - limiter.block_gas_used = 9; - limiter.block_tx_size_used = 9; - limiter.block_da_size_used = 9; - limiter.block_data_used = 9; - limiter.block_kv_updates_used = 9; - limiter.block_compute_gas_used = 9; - limiter.block_state_growth_used = 9; - - assert!( - !limiter.is_block_limit_reached(), - "with every counter strictly below its limit the block is not full" - ); -} - -/// Helper: a limiter where exactly one dimension sits at `used == limit` and all others are -/// strictly below (limit 10, used 0). Asserting `true` kills that clause's `>=`→`<` (equality -/// would become false) and the adjacent `||`→`&&` (with a single true clause, `&&` ⇒ false). -macro_rules! only_dimension_at_limit { - ($limit_field:ident, $used_field:ident) => {{ - let mut limits = BlockLimits::no_limits(); - limits.block_gas_limit = 10; - limits.block_txs_encode_size_limit = 10; - limits.block_da_size_limit = 10; - limits.block_txs_data_limit = 10; - limits.block_kv_update_limit = 10; - limits.block_compute_gas_limit = 10; - limits.block_state_growth_limit = 10; - limits.$limit_field = 5; - let mut limiter = BlockLimiter::new(limits); - // all counters strictly below their (10) limits... - limiter.block_gas_used = 0; - limiter.block_tx_size_used = 0; - limiter.block_da_size_used = 0; - limiter.block_data_used = 0; - limiter.block_kv_updates_used = 0; - limiter.block_compute_gas_used = 0; - limiter.block_state_growth_used = 0; - // ...except the one under test, which sits exactly at its (5) limit. - limiter.$used_field = 5; - limiter - }}; -} - -#[test] -fn test_is_block_limit_reached_gas_dimension() { - let limiter = only_dimension_at_limit!(block_gas_limit, block_gas_used); - assert!(limiter.is_block_limit_reached(), "gas at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_tx_size_dimension() { - let limiter = only_dimension_at_limit!(block_txs_encode_size_limit, block_tx_size_used); - assert!(limiter.is_block_limit_reached(), "tx encode size at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_da_size_dimension() { - let limiter = only_dimension_at_limit!(block_da_size_limit, block_da_size_used); - assert!(limiter.is_block_limit_reached(), "da size at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_data_dimension() { - let limiter = only_dimension_at_limit!(block_txs_data_limit, block_data_used); - assert!(limiter.is_block_limit_reached(), "tx data at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_kv_updates_dimension() { - let limiter = only_dimension_at_limit!(block_kv_update_limit, block_kv_updates_used); - assert!(limiter.is_block_limit_reached(), "kv updates at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_compute_gas_dimension() { - let limiter = only_dimension_at_limit!(block_compute_gas_limit, block_compute_gas_used); - assert!(limiter.is_block_limit_reached(), "compute gas at limit ⇒ block full"); -} - -#[test] -fn test_is_block_limit_reached_state_growth_dimension() { - let limiter = only_dimension_at_limit!(block_state_growth_limit, block_state_growth_used); - assert!(limiter.is_block_limit_reached(), "state growth at limit ⇒ block full"); -} diff --git a/crates/mega-evm/tests/mutation/constants.rs b/crates/mega-evm/tests/mutation/constants.rs deleted file mode 100644 index 904d37882..000000000 --- a/crates/mega-evm/tests/mutation/constants.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Value-pinning tests for the arithmetic `pub const` definitions in -//! `src/constants.rs`. -//! -//! Several constants are defined via compile-time arithmetic (e.g. -//! `12 * 1024 * 1024 + 512 * 1024`). Mutation testing replaces individual -//! operators (`*`→`+`, `+`→`-`, `/`→`*`, …) inside these expressions, which -//! changes the resulting numeric value but leaves the program compiling. None -//! of the targeted expressions are no-ops, so every operator swap is a true -//! behavioral change. -//! -//! Each test below asserts the constant equals its exact unmutated value. Any -//! arithmetic mutation on the relevant line yields a different value and is -//! therefore killed. - -use mega_evm::constants::{mini_rex, rex}; - -/// Pins `mini_rex::ADDITIONAL_INITCODE_SIZE` (`24 * 1024`). -/// -/// Kills `constants.rs:25:52 replace * with /` and `:25:52 replace * with +`. -#[test] -fn test_mini_rex_additional_initcode_size() { - assert_eq!(mini_rex::ADDITIONAL_INITCODE_SIZE, 24 * 1024); - assert_eq!(mini_rex::ADDITIONAL_INITCODE_SIZE, 24_576); -} - -/// Pins `mini_rex::MAX_INITCODE_SIZE` -/// (`MAX_CONTRACT_SIZE + ADDITIONAL_INITCODE_SIZE`). -/// -/// Kills `constants.rs:27:60 replace + with -`. -#[test] -fn test_mini_rex_max_initcode_size() { - // 512 * 1024 + 24 * 1024 = 524_288 + 24_576 - assert_eq!(mini_rex::MAX_INITCODE_SIZE, 548_864); - assert_eq!( - mini_rex::MAX_INITCODE_SIZE, - mini_rex::MAX_CONTRACT_SIZE + mini_rex::ADDITIONAL_INITCODE_SIZE - ); -} - -/// Pins `mini_rex::BLOCK_DATA_LIMIT` (`12 * 1024 * 1024 + 512 * 1024`, 12.5 MB). -/// -/// Kills `constants.rs:59:62 replace * with +`, `:59:56 replace + with -`, -/// `:59:62 replace * with /`, and `:59:56 replace + with *`. -#[test] -fn test_mini_rex_block_data_limit() { - assert_eq!(mini_rex::BLOCK_DATA_LIMIT, 12 * 1024 * 1024 + 512 * 1024); - assert_eq!(mini_rex::BLOCK_DATA_LIMIT, 13_107_200); -} - -/// Pins `mini_rex::TX_DATA_LIMIT` (`BLOCK_DATA_LIMIT * 25 / 100`, 25% of block). -/// -/// Kills `constants.rs:62:58 replace / with *` and `:62:53 replace * with +`. -#[test] -fn test_mini_rex_tx_data_limit() { - assert_eq!(mini_rex::TX_DATA_LIMIT, mini_rex::BLOCK_DATA_LIMIT * 25 / 100); - assert_eq!(mini_rex::TX_DATA_LIMIT, 3_276_800); -} - -/// Pins `mini_rex::TX_KV_UPDATE_LIMIT` -/// (`BLOCK_KV_UPDATE_LIMIT * 25 / 100`, 25% of block). -/// -/// Kills `constants.rs:68:68 replace / with *` and `:68:63 replace * with +`. -#[test] -fn test_mini_rex_tx_kv_update_limit() { - assert_eq!(mini_rex::TX_KV_UPDATE_LIMIT, mini_rex::BLOCK_KV_UPDATE_LIMIT * 25 / 100); - assert_eq!(mini_rex::TX_KV_UPDATE_LIMIT, 125_000); -} - -/// Pins `rex::TX_DATA_LIMIT` (`12 * 1024 * 1024 + 512 * 1024`, same as the -/// block data limit). -/// -/// Kills the full operator-swap cluster on line 188: `+:53 with *`/`with -`, -/// `*:46 with +`/`with /`, `*:59 with +`/`with /`, and `*:39 with /`/`with +`. -#[test] -fn test_rex_tx_data_limit() { - assert_eq!(rex::TX_DATA_LIMIT, 12 * 1024 * 1024 + 512 * 1024); - assert_eq!(rex::TX_DATA_LIMIT, 13_107_200); -} diff --git a/crates/mega-evm/tests/mutation/external_exec.rs b/crates/mega-evm/tests/mutation/external_exec.rs deleted file mode 100644 index 28a205961..000000000 --- a/crates/mega-evm/tests/mutation/external_exec.rs +++ /dev/null @@ -1,347 +0,0 @@ -//! Value/behavioral tests that close surviving mutants in `crates/mega-evm/src/block/executor.rs` -//! and `crates/mega-evm/src/external/`. -//! -//! The `src/**` modules carry inline `#[cfg(test)] mod tests`, but those unit tests are not -//! exercised by the mutation run (which builds the integration test targets). These integration -//! tests re-assert the same invariants through the crate's public / `test-utils`-gated API. -//! -//! Covered survivors: -//! * `block/executor.rs:70` — `Debug::fmt` replaced with `Ok(Default::default())`. The real impl -//! writes the struct name; the mutant writes nothing. We pin the formatted output. -//! * `block/executor.rs:297` — `post_execution_changes -> Ok(vec![])`. The real body *always* -//! pushes exactly one `PostBlock(BalanceIncrements)` outcome (because -//! `eips::transact_balance_increments` unconditionally returns `Some(state)`), so a fresh -//! executor's `post_execution_changes()` returns a length-1 vec. The mutant returns length 0. -//! * `block/executor.rs:496` — `get_accessed_bucket_ids -> vec![]` and `-> -//! vec![Default::default()]` (i.e. `vec![0]`). After a transaction that performs an `SSTORE` -//! (zero→non-zero), the dynamic storage gas tracker records the slot's bucket id. With -//! `TestExternalEnvs`'s default `SimpleBucketHasher`, that id lies in `[NUM_META_BUCKETS, -//! NUM_BUCKETS)` (≥ `65_536`), so the returned set is non-empty and never `{0}` — killing both -//! variants. -//! * `external/hasher/fallback.rs:{109,112,120}` — value-changing mutations in -//! `DeterministicHasher::write`. `AHashBucketHasher` is the public, production-compatible hasher -//! whose contract is to reproduce SPECIFIC bucket ids matching the `salt` crate. We pin known -//! input→bucket-id pairs, one per affected `write` branch, against the documented expected values -//! (the same constants cross-checked against `salt` in `src/external/hasher/mod.rs`). The `125:47 -//! |`→`&` mutant is also killed by `ahash_bucket_id_small_input_is_pinned` (the small-input -//! combine), but the `125:47 |`→`^` mutant is provably equivalent and is recorded in -//! `mutants/suppressions.toml`: at line 125 the `|` ORs `value[0] as u128` (occupies only bits -//! 0..63) with `(value[1] as u128) << 64` (occupies only bits 64..127); the operands have -//! disjoint set bits for every input, so `| == ^` identically and no input distinguishes them. -//! * `external/hasher/fallback.rs:{108,112}` — the `>`→`>=` length-routing boundary mutants in -//! `write`. The full run hid these because no pinned input had a length sitting exactly on a -//! boundary; we add `len == {8,32}` inputs whose bucket id flips when the comparison does -//! (`ahash_bucket_id_len{8,32}_*`). The sibling line-109 `> 16`→`>= 16` is provably equivalent (a -//! len-16 input hashes identically either way — see the suppression note below) and is recorded -//! in `mutants/suppressions.toml`. -//! -//! The remaining `fallback.rs` survivors are recorded in `mutants/suppressions.toml` as -//! dead/unreachable code rather than killed here: the typed `write_u8/u16/u32/u64/u128 -> ()` -//! stubs and the two `^`→`|`/`&` mutants inside `update`. `AHashBucketHasher::bucket_id` drives -//! only the slice `write` (→ `large_update`); it never invokes the typed `write_uN` methods nor -//! `update`. Those are reachable solely via `core::hash::Hasher` trait dispatch on the -//! `pub(crate)`, non-re-exported `DeterministicHasher`, which no integration test (separate crate) -//! can construct — and no non-test caller anywhere in `mega-evm` invokes them. So no public-API -//! input distinguishes the mutants. -//! -//! `external/mod.rs:94` (`EmptyExternalEnv::external_envs` → -//! `ExternalEnvs::from(Default::default())`) is provably equivalent and is recorded in -//! `mutants/suppressions.toml` instead of being killed here: `EmptyExternalEnv` is a unit struct, -//! so both the real body (`ExternalEnvs { salt_env: EmptyExternalEnv, oracle_env: EmptyExternalEnv -//! }`) and the mutant (`From>` of the `Default` impl, which yields -//! the identical fields) construct the same value; no observable behavior distinguishes them. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{ - block::{BlockExecutor, StateChangePostBlockSource, StateChangeSource}, - EvmEnv, EvmFactory, -}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - AHashBucketHasher, BlockLimits, BucketHasher, MegaBlockExecutionCtx, MegaBlockExecutor, - MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, TestExternalEnvs, -}; -use revm::{context::BlockEnv, database::State}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const STORAGE_CONTRACT: Address = address!("1000000000000000000000000000000000000003"); - -/// Lower bound of the valid SALT bucket range (`NUM_BUCKETS / MIN_BUCKET_SIZE`, i.e. 256^3 / 256). -/// Both `SimpleBucketHasher` and `AHashBucketHasher` map keys into `[NUM_META_BUCKETS, -/// NUM_BUCKETS)`. -const NUM_META_BUCKETS: u32 = (1u32 << 24) / 256; // 65_536 - -fn create_transaction( - nonce: u64, - to: Address, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit: 1_000_000, - to: TxKind::Call(to), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Wires a `MegaBlockExecutor` over `state` at the `MiniRex` spec, with a `TestExternalEnvs` salt -/// environment (default `SimpleBucketHasher`). Mirrors -/// `tests/block_executor/accessed_block_hashes`. -macro_rules! build_executor { - ($state:expr) => {{ - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm = evm_factory.create_evm($state, EvmEnv::new(cfg_env, block_env)); - - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - MegaBlockExecutor::new(evm, block_ctx, chain_spec, OpAlloyReceiptBuilder::default()) - }}; -} - -// ============================================================================ -// block/executor.rs:70 — Debug::fmt -// ============================================================================ - -/// `Debug` for `MegaBlockExecutor` must write the struct name. The mutant returns `Ok(())` -/// without writing anything, producing an empty string. -#[test] -fn test_block_executor_debug_writes_struct_name() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let executor = build_executor!(&mut state); - - let rendered = format!("{executor:?}"); - assert!( - rendered.contains("MegaethBlockExecutor"), - "Debug output must name the struct, got {rendered:?}" - ); - assert!(!rendered.is_empty(), "Debug output must not be empty"); -} - -// ============================================================================ -// block/executor.rs:297 — post_execution_changes -// ============================================================================ - -/// `post_execution_changes` always produces exactly one `PostBlock(BalanceIncrements)` outcome, -/// because `eips::transact_balance_increments` unconditionally returns `Some(state)`. The mutant -/// drops it to an empty vec. -#[test] -fn test_post_execution_changes_yields_balance_increment_outcome() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = build_executor!(&mut state); - - let outcomes = - executor.post_execution_changes().expect("post_execution_changes should succeed"); - - assert_eq!( - outcomes.len(), - 1, - "post_execution_changes must yield exactly one system-call outcome; the mutant drops it" - ); - assert!( - matches!( - outcomes[0].source, - StateChangeSource::PostBlock(StateChangePostBlockSource::BalanceIncrements) - ), - "the single outcome must be the post-block balance-increment source, got {:?}", - outcomes[0].source - ); -} - -// ============================================================================ -// block/executor.rs:496 — get_accessed_bucket_ids -// ============================================================================ - -/// A contract that writes a non-zero value to a previously-zero storage slot, then stops. -/// The `SSTORE` triggers the dynamic SALT gas hook, recording the slot's bucket id. -fn sstore_contract() -> Bytes { - BytecodeBuilder::default().sstore(U256::from(7), U256::from(42)).stop().build() -} - -/// After a transaction performs an `SSTORE`, `get_accessed_bucket_ids` returns the non-empty set -/// of buckets touched. With the default `SimpleBucketHasher` every recorded id is in -/// `[NUM_META_BUCKETS, NUM_BUCKETS)` (≥ `65_536`), so the result is neither empty (kills `vec![]`) -/// nor `{0}` (kills `vec![Default::default()]`). -#[test] -fn test_get_accessed_bucket_ids_records_sstore_bucket() { - let mut db = MemoryDatabase::default(); - db.set_account_code(STORAGE_CONTRACT, sstore_contract()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = build_executor!(&mut state); - - executor - .execute_transaction(&create_transaction(0, STORAGE_CONTRACT)) - .expect("sstore tx should succeed"); - - let ids = executor.get_accessed_bucket_ids(); - assert!(!ids.is_empty(), "an SSTORE must record at least one accessed bucket id"); - assert!( - ids.iter().all(|&id| id >= NUM_META_BUCKETS), - "every recorded bucket id must lie in the valid KV range (>= {NUM_META_BUCKETS}); \ - a `vec![0]` mutant would violate this, got {ids:?}" - ); -} - -// ============================================================================ -// external/hasher/fallback.rs:{109,112,120,125} — DeterministicHasher::write branches -// ============================================================================ -// -// `AHashBucketHasher::bucket_id(key)` = `hash(key) % NUM_KV_BUCKETS + NUM_META_BUCKETS`, where -// `hash` is the deterministic AHash fallback. Its `write` routes by input length: -// -// * len <= 8 -> small branch; line 125 `|` combine -// * 9 <= len <= 16 -> mid branch; line 120 `|` combine, and the line-109 `> 16` outer guard -// (false here) selects this branch -// * len >= 17 -> large branch; the line-109 `> 16` outer guard (true) and the line-112 -// `while data.len() > 16` loop guard both gate the 16-byte block reads -// -// The four mutations (`>`→`==` on 109/112, `|`→`&` on 120/125) all change the produced hash for an -// input that hits their branch, hence change the bucket id. We pin one input per branch against the -// expected unmutated value. Expected hashes are the documented cross-checked values from -// `src/external/hasher/mod.rs` (`hash("hello") = 1027176506268606463`, etc.); expected bucket ids -// for the >=17-byte inputs are the documented `bucket_id` cross-check values from that same module. - -/// `NUM_KV_BUCKETS = NUM_BUCKETS - NUM_META_BUCKETS = 16_777_216 - 65_536`. -const NUM_KV_BUCKETS: u64 = (1u64 << 24) - ((1u64 << 24) / 256); -const NUM_META_BUCKETS_U64: u64 = (1u64 << 24) / 256; - -/// Maps a documented `hash(key)` value to the expected bucket id. -const fn bucket_id_from_hash(hash: u64) -> u32 { - (hash % NUM_KV_BUCKETS + NUM_META_BUCKETS_U64) as u32 -} - -/// `len <= 8` (small branch, line 125): `"hello"` is 5 bytes. -/// `hash("hello") = 1_027_176_506_268_606_463` (documented in `external/hasher/mod.rs`). -#[test] -fn test_ahash_bucket_id_small_input_is_pinned() { - assert_eq!( - AHashBucketHasher::bucket_id(b"hello"), - bucket_id_from_hash(1_027_176_506_268_606_463), - "small-input (<=8B) bucket id changed: a `|`->`&` mutant on the line-125 combine alters it" - ); -} - -/// `9 <= len <= 16` (mid branch, lines 120 and 109): `"hash test"` is 9 bytes. -/// `hash("hash test") = 2_116_618_212_096_523_432` (documented in `external/hasher/mod.rs`). -/// A `> 16`→`== 16` mutant on line 109 would route a 9-byte input identically, but a `>`→`==` -/// at line 109 also misroutes the boundary len 16 and all len >= 17 — covered by the large test — -/// while the `|`->`&` mutant on line 120 directly changes this 9-byte result. -#[test] -fn test_ahash_bucket_id_mid_input_is_pinned() { - assert_eq!( - AHashBucketHasher::bucket_id(b"hash test"), - bucket_id_from_hash(2_116_618_212_096_523_432), - "mid-input (9..=16B) bucket id changed: a `|`->`&` mutant on the line-120 combine alters it" - ); -} - -/// `len >= 17` (large branch, lines 109 + 112). -/// -/// `[0u8; 20]` -> bucket id `12_666_336`; the 52-byte address+slot key -> `9_450_146`; the 20-byte -/// `deadbeef` address -> `12_196_828`. All three are documented cross-check values from -/// `external/hasher/mod.rs`. At these lengths the loop `while data.len() > 16` runs at least once -/// (and three times for the 52-byte key); the `> 16`→`== 16` mutants on lines 109/112 skip or -/// misroute those reads, changing the hash. -#[test] -fn test_ahash_bucket_id_large_input_is_pinned() { - // 20-byte all-zero key: single loop iteration after the tail update. - assert_eq!( - AHashBucketHasher::bucket_id(&[0u8; 20]), - 12_666_336, - "large-input (20B) bucket id changed: a `> 16`->`== 16` mutant on line 109/112 alters it" - ); - - // 20-byte non-zero address: distinct branch input, documented cross-check value. - let addr: [u8; 20] = [ - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0a, 0x0b, - ]; - assert_eq!(AHashBucketHasher::bucket_id(&addr), 12_196_828, "20B address bucket id changed"); - - // 52-byte address+slot key: the loop iterates multiple times (52 -> 36 -> 20), so the - // line-112 `while data.len() > 16` guard is exercised across several reads. - let mut slot_key = [0u8; 52]; - slot_key[..20].copy_from_slice(&addr); - slot_key[51] = 1; - assert_eq!( - AHashBucketHasher::bucket_id(&slot_key), - 9_450_146, - "52B slot key bucket id changed: a `> 16`->`== 16` mutant truncates the block loop" - ); -} - -// ============================================================================ -// external/hasher/fallback.rs:{108,112} — length-routing boundary mutants -// ============================================================================ -// -// `write` routes by input length with three `>` comparisons. The full run hid the -// `>`→`>=` boundary variants because no pinned input had a length sitting exactly on a -// boundary. Each test below uses an input whose length lands on the relevant boundary so -// the `>`→`>=` flip changes which branch (or how many loop iterations) executes, and thus -// the produced hash and bucket id: -// -// * line 108 `data.len() > 8` : at len == 8 the original takes the small branch (read_small); -// `>= 8` reroutes len-8 input into the mid branch (read_u64 front + read_last_u64 back), a -// different combine. -// * line 112 `while data.len() > 16` : with a len that is a multiple of 16 (== 32), the loop hits -// `data.len() == 16` mid-iteration. `>` stops there (1 pass); `>= 16` runs a second read_u128 -// pass, changing the hash. -// -// The line-109 `> 16`→`>= 16` mutant is NOT here: it is provably equivalent (a len-16 input -// produces the identical single `large_update(le_u128(bytes[0..16]))` under both branches — -// the mid branch's `front | (back << 64)` reassembles the same little-endian u128 that the -// large branch's `read_last_u128` reads), so it is recorded in `mutants/suppressions.toml`. -// -// Expected bucket ids are the unmutated `AHashBucketHasher::bucket_id` outputs for these -// exact inputs (the production hasher's contract is to reproduce specific salt-compatible -// bucket ids), pinned the same way as the documented large-input cross-check values above. - -/// `len == 8` boundary (line 108 `> 8`). The small branch (`read_small`) is taken; a `>= 8` -/// mutant misroutes this input into the mid branch. -#[test] -fn test_ahash_bucket_id_len8_boundary_is_pinned() { - let key: [u8; 8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]; - assert_eq!( - AHashBucketHasher::bucket_id(&key), - 1_978_187, - "len-8 bucket id changed: a `> 8`->`>= 8` mutant on line 108 reroutes the small branch" - ); -} - -/// `len == 32` boundary (line 112 `while data.len() > 16`). The loop reaches `data.len() -/// == 16` after one 16-byte read; `>` stops (one pass) while a `>= 16` mutant runs a second -/// `read_u128` pass, changing the hash. -#[test] -fn test_ahash_bucket_id_len32_loop_boundary_is_pinned() { - let key: [u8; 32] = [0x22; 32]; - assert_eq!( - AHashBucketHasher::bucket_id(&key), - 10_093_090, - "len-32 bucket id changed: a `> 16`->`>= 16` mutant on the line-112 loop guard adds a pass" - ); -} diff --git a/crates/mega-evm/tests/mutation/limit.rs b/crates/mega-evm/tests/mutation/limit.rs deleted file mode 100644 index 2c0d065cc..000000000 --- a/crates/mega-evm/tests/mutation/limit.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Attempts to kill the frame-interaction mutants in `src/limit/limit.rs`: -//! -//! * `:585` — `AdditionalLimit::before_frame_run -> Option` replaced with -//! `None`. The four sub-tracker `before_frame_run` calls use the default trait no-op, so the only -//! behavioral effect of this hook is its early `check_limit()` halt: when a TX-level limit was -//! already latched (e.g. a CREATE child frame whose `after_frame_init` recording of the created -//! account tipped the KV/data budget over), the hook short-circuits the frame *before* its init -//! code runs. The mutant drops that short-circuit, so the init code runs. -//! -//! * `:676` — `&&` replaced with `||` in the `duplicate_return_frame_result` guard of -//! `before_frame_return_result`. The flag distinguishes the two `last_frame_result` / -//! `frame_return_result` calls for a top-level frame that has child frames. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const FACTORY: Address = address!("0000000000000000000000000000000000200001"); - -/// Constructor (init) code that runs `SSTORE(0, 1)` then `RETURN(0, 1)`: 8 bytes, -/// `PUSH1 1 PUSH0 SSTORE PUSH1 1 PUSH0 RETURN`. The SSTORE makes the constructor's execution -/// observable in gas and state: if the created frame is short-circuited at `before_frame_run`, -/// the SSTORE never runs. -fn create_init_code() -> Vec { - vec![PUSH1, 0x01, PUSH0, SSTORE, PUSH1, 0x01, PUSH0, RETURN] -} - -/// Factory that stores the init code in memory and CREATEs a contract from it, then STOPs. -fn create_factory_code() -> Bytes { - let init = create_init_code(); - let init_len = init.len() as u64; - BytecodeBuilder::default() - .mstore(0, init) // left-aligned init code at offset 0 - .push_number(init_len) // size - .push_number(0_u64) // offset - .push_number(0_u64) // value - .append(CREATE) - .append(POP) - .append(STOP) - .build() -} - -fn transact_with_kv_limit( - db: &mut MemoryDatabase, - kv_update_limit: u64, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(kv_update_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// A CREATE child frame whose `after_frame_init` records the created account's KV update, -/// tipping the TX over the KV-update budget, must be short-circuited at `before_frame_run` -/// before its constructor body executes. The transaction halts with `KVUpdateLimitExceeded`. -/// -/// This pins `gas_used`: if `before_frame_run` is mutated to always return `None`, the -/// constructor's SSTORE runs before the exceed is re-detected in `after_frame_run`, -/// changing the gas consumed by the create frame and therefore the transaction `gas_used`. -#[test] -fn test_before_frame_run_short_circuits_already_exceeded_create_frame() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - db.set_account_code(FACTORY, create_factory_code()); - - // KV updates: caller nonce (1) + factory nonce (1) + created account (1) = 3. - // The created-account KV is recorded in the CREATE frame's `after_frame_init`; with a - // budget of 2 it tips the limit over, so `before_frame_run` must short-circuit the - // constructor. - let tx = - TxEnvBuilder::default().caller(CALLER).call(FACTORY).gas_limit(10_000_000).build_fill(); - - let result = transact_with_kv_limit(&mut db, 2, tx).unwrap(); - - let gas_used = match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, - gas_used, - } => *gas_used, - other => panic!("expected KVUpdateLimitExceeded halt, got {other:?}"), - }; - // Pinned `gas_used` with the constructor short-circuited at `before_frame_run`. - // Calibrated against the unmutated build; the `-> None` mutant lets the constructor run - // and produces a different value. - assert_eq!( - gas_used, GAS_USED_SHORT_CIRCUITED, - "before_frame_run must short-circuit the over-budget CREATE frame before its \ - constructor runs; a different gas_used means the short-circuit was dropped" - ); -} - -/// Calibrated `gas_used` for the unmutated build, where `before_frame_run` short-circuits the -/// over-budget CREATE frame before its SSTORE constructor runs. -const GAS_USED_SHORT_CIRCUITED: u64 = 2_053_023; diff --git a/crates/mega-evm/tests/mutation/main.rs b/crates/mega-evm/tests/mutation/main.rs deleted file mode 100644 index b7478369f..000000000 --- a/crates/mega-evm/tests/mutation/main.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Auto-generated mutation-killing **system tests** for `crates/mega-evm/src/`. -//! -//! # What lives here -//! -//! This directory holds tests that were generated by the mutation-improvement -//! workflow (the `improve-mutation-score` skill) to close *specific* surviving -//! mutants surfaced by `cargo-mutants`. Each submodule targets the survivors of -//! one source area; every test maps back to a concrete mutant and kills it by -//! either asserting an exact value (constants, discriminants, computed limits) -//! or observing a behavioral difference through the public EVM harness. -//! -//! # Scope: system tests only -//! -//! Only **system / integration-level** tests belong here — those that exercise -//! mega-evm through its public (or `test-utils`-gated) API end-to-end, because -//! the mutant they kill is only observable through whole-EVM behavior. -//! -//! A mutant that can be killed by a **unit test** of one module does **not** -//! belong here: put that test inline next to the code it covers, in the source -//! module's own `#[cfg(test)] mod tests`. Reserve this directory for the cases -//! that genuinely need a full-execution harness to observe. -//! -//! Mutants found to be provably equivalent or dead are not tested at all — they -//! are recorded in `mutants/suppressions.toml` with a justification and reviewer. -//! -//! # Do not hand-edit -//! -//! These tests are **machine-generated and machine-maintained**. Treat them as -//! generated artifacts: -//! -//! - Do **not** rename, reword, or refactor them by hand — each test is keyed to a mutant, and -//! editing it can silently stop it from killing that mutant. -//! - Do **not** add unrelated assertions here; write ordinary tests in the relevant module or the -//! spec-organized suites under `tests/` instead. -//! - To close a *new* survivor, re-run the `improve-mutation-score` skill rather than authoring a -//! test here manually, so it stays linked to its mutant and the suppression bookkeeping stays -//! consistent. -//! -//! If a test here is wrong or stale, fix the source/suppression and regenerate; -//! don't patch the generated test in place. -//! -//! See `mutants/README.md` and the `improve-mutation-score` skill for the full -//! methodology. - -mod access_evm; -mod block; -mod constants; -mod external_exec; -mod limit; diff --git a/crates/mega-evm/tests/rex/intrinsic_gas.rs b/crates/mega-evm/tests/rex/intrinsic_gas.rs deleted file mode 100644 index 034a4a64f..000000000 --- a/crates/mega-evm/tests/rex/intrinsic_gas.rs +++ /dev/null @@ -1,317 +0,0 @@ -//! Tests for Rex hardfork additional intrinsic gas costs. - -use std::convert::Infallible; - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - constants, test_utils::MemoryDatabase, EVMError, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, MegaTransactionError, TestExternalEnvs, -}; -use revm::{ - context::{result::ResultAndState, TxEnv}, - primitives::Address, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); - -/// Base intrinsic gas cost for all transactions -const BASE_INTRINSIC_GAS: u64 = 21_000; - -/// Executes a transaction on the EVM. -#[allow(clippy::too_many_arguments)] -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, - gas_limit: u64, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Tests that Rex hardfork adds 39,000 gas to base transaction cost for simple transfer. -#[test] -fn test_rex_intrinsic_gas_simple_transfer() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // Rex: 21,000 (base) + 39,000 (Rex intrinsic storage gas) = 60,000 - assert_eq!(gas_used, BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that `MiniRex` does NOT charge the additional 39,000 intrinsic gas. -#[test] -fn test_mini_rex_no_additional_intrinsic_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::MINI_REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // `MiniRex`: only 21,000 (base) - no additional intrinsic gas - assert_eq!(gas_used, BASE_INTRINSIC_GAS); -} - -/// Tests that `Equivalence` spec does NOT charge the additional 39,000 intrinsic gas. -#[test] -fn test_equivalence_no_additional_intrinsic_gas() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::EQUIVALENCE, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // `Equivalence`: only 21,000 (base) - no additional intrinsic gas - assert_eq!(gas_used, BASE_INTRINSIC_GAS); -} - -/// Tests `Rex` intrinsic gas with calldata (combines calldata costs + intrinsic storage gas). -#[test] -fn test_rex_intrinsic_gas_with_calldata() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - // Create calldata with 100 bytes (all non-zero for maximum gas cost) - let calldata = Bytes::from(vec![1u8; 100]); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // `Rex` inherits `MiniRex` calldata costs and adds 39,000 intrinsic storage gas - // For 100 bytes of non-zero calldata: - // - MiniRex base cost: 38,600 (from floor gas test calculations) - // - Rex intrinsic storage gas: 39,000 - // Total: 77,600 - let expected_gas = 77_600; - assert_eq!(gas_used, expected_gas); -} - -/// Tests that Rex transaction fails if gas limit is below intrinsic gas requirement. -#[test] -fn test_rex_intrinsic_gas_insufficient_gas_limit() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - // Set gas limit to just below the Rex intrinsic gas (60,000) - let insufficient_gas_limit = BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS - 1; - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), - insufficient_gas_limit, - ); - - // Transaction should fail due to insufficient gas - assert!(res.is_err()); -} - -/// Tests that Rex intrinsic gas applies to contract creation transactions. -#[test] -fn test_rex_intrinsic_gas_contract_creation() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - - // Simple contract bytecode that does nothing (PUSH0 PUSH0 RETURN) - let init_code = Bytes::from(vec![0x5f, 0x5f, 0xf3]); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - None, // None means CREATE - init_code, - U256::ZERO, - 10_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // Should include the Rex intrinsic storage gas + other costs - // At minimum, it should be more than base + Rex intrinsic - assert!(gas_used >= BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that `Rex` intrinsic gas is exactly 39,000 more than `MiniRex` for same transaction. -#[test] -fn test_rex_vs_mini_rex_gas_difference() { - let mut db_rex = MemoryDatabase::default(); - db_rex.set_account_balance(CALLER, U256::from(1_000_000)); - db_rex.set_account_balance(CALLEE, U256::from(100)); - - let mut db_mini_rex = MemoryDatabase::default(); - db_mini_rex.set_account_balance(CALLER, U256::from(1_000_000)); - db_mini_rex.set_account_balance(CALLEE, U256::from(100)); - - // Use empty calldata for simplest comparison - let calldata = Bytes::new(); - - let res_rex = transact( - MegaSpecId::REX, - &mut db_rex, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata.clone(), - U256::from(1), - 1_000_000, - ) - .unwrap(); - - let res_mini_rex = transact( - MegaSpecId::MINI_REX, - &mut db_mini_rex, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::from(1), - 1_000_000, - ) - .unwrap(); - - assert!(res_rex.result.is_success()); - assert!(res_mini_rex.result.is_success()); - - let gas_used_rex = res_rex.result.gas_used(); - let gas_used_mini_rex = res_mini_rex.result.gas_used(); - - // For transactions without calldata, the difference should be exactly - // the Rex intrinsic storage gas (39,000) - assert_eq!(gas_used_rex - gas_used_mini_rex, constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests that Rex intrinsic gas applies even for zero-value transfers. -#[test] -fn test_rex_intrinsic_gas_zero_value_transfer() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_balance(CALLEE, U256::from(100)); - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::ZERO, // Zero value transfer - 1_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - // Rex: 21,000 (base) + 39,000 (Rex intrinsic storage gas) = 60,000 - assert_eq!(gas_used, BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS); -} - -/// Tests Rex intrinsic gas with new account creation (combines new account gas + intrinsic gas). -#[test] -fn test_rex_intrinsic_gas_new_account_creation() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000)); - // CALLEE doesn't exist in db (new account) - - let res = transact( - MegaSpecId::REX, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Bytes::new(), - U256::from(1), // Non-zero value to trigger new account gas - 10_000_000, - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - - // Rex charges: - // - Base: 21,000 - // - Rex intrinsic storage gas: 39,000 - // Total: 2,060,000 - let expected_gas = BASE_INTRINSIC_GAS + constants::rex::TX_INTRINSIC_STORAGE_GAS; - assert_eq!(gas_used, expected_gas); -} diff --git a/crates/mega-evm/tests/rex2/selfdestruct.rs b/crates/mega-evm/tests/rex2/selfdestruct.rs deleted file mode 100644 index baff77d9b..000000000 --- a/crates/mega-evm/tests/rex2/selfdestruct.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! Tests for the SELFDESTRUCT opcode behavior in Rex2. - -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::{ - bytecode::opcode::{PUSH0, SELFDESTRUCT}, - context::result::{ExecutionResult, ResultAndState}, - }, - test_utils::{transact, MemoryDatabase}, - *, -}; - -#[test] -fn test_selfdestruct_allowed_in_rex2() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - let code = vec![PUSH0, PUSH0, SELFDESTRUCT]; - db.set_account_code(contract_address, code.into()); - - let caller = address!("0000000000000000000000000000000000100000"); - let callee = Some(contract_address); - let result = transact(MegaSpecId::REX2, &mut db, caller, callee, Bytes::default(), U256::ZERO); - - assert!(matches!(result, Ok(ResultAndState { result: ExecutionResult::Success { .. }, .. }))); -} diff --git a/crates/mega-evm/tests/rex4/frame_state_growth.rs b/crates/mega-evm/tests/rex4/frame_state_growth.rs deleted file mode 100644 index 80ee392ef..000000000 --- a/crates/mega-evm/tests/rex4/frame_state_growth.rs +++ /dev/null @@ -1,962 +0,0 @@ -//! Tests for Rex4 per-frame state growth limits. -//! -//! Rex4 introduces per-frame state growth budgets: each inner call frame receives -//! `remaining * 98 / 100` of the parent's remaining state growth budget. -//! When a frame exceeds its budget, it reverts (not halts) with ABI-encoded -//! `MegaLimitExceeded(uint8 kind, uint64 limit)` revert data. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolError; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaSpecId, - MegaTransaction, MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, DatabaseCommit, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); -const CONTRACT3: Address = address!("0000000000000000000000000000000000100004"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified state growth limit. -/// -/// Returns the execution result and the actual state growth used. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -/// Checks if the execution result indicates that the state growth limit was exceeded (TX-level). -fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } - ) -} - -/// Creates a default transaction builder calling a contract. -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -/// Builds bytecode that writes `n` distinct storage slots (slot 0..n-1) to non-zero values. -fn write_n_slots(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - builder -} - -/// Builds bytecode that writes `n` slots and then clears `m` of them back to zero. -fn write_n_clear_m_slots(builder: BytecodeBuilder, n: u64, m: u64) -> BytecodeBuilder { - let mut b = write_n_slots(builder, n); - for i in 0..m { - b = b.sstore(U256::from(i), U256::from(0)); - } - b -} - -/// Appends a CALL to `target` with the given gas amount onto the builder. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Appends a CALL that captures the return data: calls `target`, then copies RETURNDATASIZE -/// bytes of return data to memory offset 0, then RETURNs it. -fn append_call_and_return_revert_data( - builder: BytecodeBuilder, - target: Address, - gas: u64, -) -> BytecodeBuilder { - append_call(builder, target, gas) - .append(POP) // discard CALL success flag - // Copy return data to memory - .append(RETURNDATASIZE) // size - .push_number(0_u64) // dataOffset - .push_number(0_u64) // destOffset - .append(RETURNDATACOPY) - // Return the return data - .append(RETURNDATASIZE) - .push_number(0_u64) // offset - .append(RETURN) -} - -// ============================================================================ -// 1. BASIC PER-FRAME BUDGET ALLOCATION -// ============================================================================ - -#[test] -fn test_top_level_frame_gets_full_tx_limit() { - // Top-level frame should get the full TX limit (no 98/100 reduction). - let code = write_n_slots(BytecodeBuilder::default(), 100).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 100, "Top-level frame should be able to use full TX limit"); -} - -#[test] -fn test_child_frame_budget_is_98_percent_of_parent() { - // TX limit = 100 → child budget = 100 * 98/100 = 98 - // Child creates 98 slots → should succeed - let child_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 98, "Child with budget 98 should succeed creating 98 slots"); -} - -#[test] -fn test_child_frame_exceeds_98_percent_budget() { - // TX limit = 100 → child budget = 98 - // Child creates 99 slots → exceeds per-frame budget → reverted - // Parent continues → TX succeeds - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child's frame-local revert"); - assert_eq!(state_growth, 0, "Child's growth should be discarded on frame-local revert"); -} - -#[test] -fn test_grandchild_budget_progressive_reduction() { - // TX limit = 1000 - // Child budget = 1000 * 98/100 = 980 - // Grandchild budget = 980 * 98/100 = 960 - // Grandchild creates 960 slots → succeeds - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 960).stop().build(); - - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 960, "Grandchild should succeed within 960 budget"); -} - -#[test] -fn test_grandchild_exceeds_progressive_budget() { - // TX limit = 1000, grandchild budget = 960 - // Grandchild creates 961 → exceeds → reverted - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 961).stop().build(); - - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent/child should succeed after grandchild revert"); - assert_eq!(state_growth, 0, "Grandchild's 961 slots discarded on revert"); -} - -#[test] -fn test_child_budget_accounts_for_parent_usage() { - // TX limit = 1000, parent creates 200 slots (remaining = 800) - // Child budget = 800 * 98/100 = 784 - // Child creates 784 → succeeds - let child_code = write_n_slots(BytecodeBuilder::default(), 784).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 200 + 784, "Parent (200) + child (784) = 984"); -} - -#[test] -fn test_child_exceeds_budget_after_parent_usage() { - // TX limit = 1000, parent uses 200, child budget = 784 - // Child creates 785 → exceeds → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 785).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 200, "Only parent's 200 slots should persist"); -} - -#[test] -fn test_sibling_frames_get_independent_budgets() { - // TX limit = 1000 - // Child A: creates 100 slots, succeeds → parent remaining = 900 - // Child B: budget = 900 * 98/100 = 882, creates 882 → succeeds - let child_a_code = write_n_slots(BytecodeBuilder::default(), 100).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 882).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 100 + 882, "Child A (100) + Child B (882) = 982"); -} - -#[test] -fn test_zero_remaining_budget_child_gets_zero() { - // TX limit = 100, parent creates 100 slots (remaining = 0) - // Child budget = 0 * 98/100 = 0 → child creates 1 slot → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 1).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 100); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed"); - assert_eq!(state_growth, 100, "Only parent's 100 slots should persist"); -} - -#[test] -fn test_small_remaining_budget_integer_division() { - // TX limit = 100, parent creates 99 slots (remaining = 1) - // Child budget = 1 * 98/100 = 0 (integer floor division) - // Child creates 1 slot → exceeds 0 → reverted - let child_code = write_n_slots(BytecodeBuilder::default(), 1).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 99); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed"); - assert_eq!(state_growth, 99, "Only parent's 99 slots"); -} - -// ============================================================================ -// 2. FRAME-LOCAL ABSORPTION SEMANTICS -// ============================================================================ - -#[test] -fn test_frame_local_exceed_reverts_not_halts() { - // TX limit = 100, child budget = 98, child creates 99 → reverted (absorbed) - // Overall TX result is success, NOT halt. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Should be success, not halt"); - assert!(!result.result.is_halt(), "Should NOT be halt"); -} - -#[test] -fn test_frame_local_exceed_gas_returned_to_parent() { - // Child exceeds, parent continues executing (proving gas was returned). - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - // Parent: CALL child (reverts), then write own slot to prove it continues. - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .append(POP) - .sstore(U256::from(0), U256::from(42)) // prove parent continues - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let gas_limit = 100_000_000_u64; - let tx = TxEnvBuilder::default().caller(CALLER).call(CALLEE).gas_limit(gas_limit).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Parent wrote 1 slot after child revert"); - let gas_used = result.result.gas_used(); - assert!(gas_used < gas_limit, "Gas should not be fully consumed"); -} - -#[test] -fn test_frame_local_exceed_child_state_discarded() { - // Child exceeds and reverts → child's storage writes not persisted. - // Parent's writes are persisted. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(42)); // parent write - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 1, "Only parent's slot counts"); - - // Commit and verify storage - db.commit(result.state); - - let parent_val = db.storage(CALLEE, U256::from(0)).unwrap(); - assert_eq!(parent_val, U256::from(42), "Parent storage should persist"); - - let child_val = db.storage(CONTRACT, U256::from(0)).unwrap(); - assert_eq!(child_val, U256::ZERO, "Child storage should be reverted"); -} - -#[test] -fn test_parent_continues_after_child_exceed() { - // Parent creates 2 slots, calls child (exceeds), parent creates 2 more. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(1), U256::from(2)); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000) - .append(POP) - .sstore(U256::from(2), U256::from(3)) - .sstore(U256::from(3), U256::from(4)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 4, "Parent's 4 slots should persist, child's discarded"); -} - -#[test] -fn test_top_level_exceed_is_frame_local_revert() { - // In Rex4, even the top-level frame uses per-frame enforcement. - // TX limit = 10, top-level frame creates 11 slots → per-frame exceed → Revert. - // (This differs from pre-Rex4, where this would be a TX-level Halt.) - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 10, tx).unwrap(); - - assert!( - matches!(result.result, ExecutionResult::Revert { .. }), - "Rex4 top-level exceed should be a revert, not halt" - ); -} - -#[test] -fn test_child_exceed_followed_by_sibling_success() { - // Child A exceeds (reverted), Child B succeeds within budget. - // TX limit = 100, each child budget = 98. - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 50).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 50, "Only Child B's 50 slots should persist"); -} - -// ============================================================================ -// 3. REVERT DATA ENCODING -// ============================================================================ - -#[test] -fn test_revert_data_contains_mega_limit_exceeded() { - // TX limit = 100 → child budget = 98. - // Child exceeds → parent captures revert data → TX returns it. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - // Parent: CALL child, copy return data to memory, RETURN it. - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - // Decode the revert data - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 3, "kind should be 3 (StateGrowth)"); - assert_eq!(decoded.limit, 98, "limit should be the child's per-frame budget (98)"); -} - -#[test] -fn test_revert_data_limit_value_matches_frame_budget() { - // TX limit = 1000, parent uses 200, child budget = 800 * 98/100 = 784 - // Child exceeds → revert data says limit = 784. - let child_code = write_n_slots(BytecodeBuilder::default(), 785).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 200); - let parent_code = append_call_and_return_revert_data(parent_code, CONTRACT, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 3, "kind should be 3 (StateGrowth)"); - assert_eq!(decoded.limit, 784, "limit should be 784 (800 * 98/100)"); -} - -#[test] -fn test_revert_data_empty_for_tx_level_exceed() { - // REX3 (pre-Rex4): child exceeds TX-level state growth → Halt, no revert data. - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 10, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); -} - -// ============================================================================ -// 4. NESTED FRAME SCENARIOS -// ============================================================================ - -#[test] -fn test_deeply_nested_budget_propagation() { - // TX limit = 1000 - // Level 0 (parent): budget = 1000 - // Level 1 (A): budget = 1000 * 98/100 = 980 - // Level 2 (B): budget = 980 * 98/100 = 960 - // Level 3 (C): budget = 960 * 98/100 = 940 - // C creates 940 slots → succeeds - let level3_code = write_n_slots(BytecodeBuilder::default(), 940).stop().build(); - - let level2_code = - append_call(BytecodeBuilder::default(), CONTRACT3, 80_000_000).append(POP).stop().build(); - - let level1_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 85_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, level1_code) - .account_code(CONTRACT2, level2_code) - .account_code(CONTRACT3, level3_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 940, "Level 3 should succeed with 940 slots"); -} - -#[test] -fn test_deeply_nested_exceed() { - // Same setup but C creates 941 → exceeds 940 budget → reverted at level 3. - let level3_code = write_n_slots(BytecodeBuilder::default(), 941).stop().build(); - - let level2_code = - append_call(BytecodeBuilder::default(), CONTRACT3, 80_000_000).append(POP).stop().build(); - - let level1_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 85_000_000).append(POP).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, level1_code) - .account_code(CONTRACT2, level2_code) - .account_code(CONTRACT3, level3_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success(), "Parent chain should succeed"); - assert_eq!(state_growth, 0, "Level 3's growth discarded on revert"); -} - -#[test] -fn test_nested_child_reverts_growth_discarded() { - // Parent (3 slots) → Child (2 slots, succeeds) → Grandchild (creates 5, REVERTs normally) - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 5).revert().build(); - - let child_code = write_n_slots(BytecodeBuilder::default(), 2); - let child_code = append_call(child_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let parent_code = write_n_slots(BytecodeBuilder::default(), 3); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5, "Parent (3) + child (2) = 5; grandchild's 5 discarded"); -} - -#[test] -fn test_nested_exceed_absorbed_at_correct_level() { - // Parent → Child → Grandchild exceeds per-frame budget - // Grandchild reverted, Child continues (writes 2 slots), Parent succeeds. - // TX limit = 1000 - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 961).stop().build(); - - let child_code = append_call(BytecodeBuilder::default(), CONTRACT2, 80_000_000) - .append(POP) // grandchild reverted - .sstore(U256::from(0), U256::from(1)) // child continues - .sstore(U256::from(1), U256::from(2)) - .stop() - .build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 90_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1000, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 2, "Only child's 2 slots should persist"); -} - -#[test] -fn test_multiple_nested_exceeds() { - // Parent calls Child A (exceeds), then Child B (exceeds), then Child C (within budget). - // TX limit = 100, each child budget = 98. - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_c_code = write_n_slots(BytecodeBuilder::default(), 50).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 30_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 30_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT3, 30_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code) - .account_code(CONTRACT3, child_c_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 50, "Only Child C's 50 slots should persist"); -} - -// ============================================================================ -// 5. BACKWARD COMPATIBILITY -// ============================================================================ - -#[test] -fn test_rex3_no_per_frame_limits() { - // REX3 spec: no per-frame limits. Child creates 99 slots with TX limit = 100 → succeeds - // (only TX-level check: 99 <= 100). - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "REX3 has no per-frame limits"); - assert_eq!(state_growth, 99); -} - -#[test] -fn test_rex3_exceed_halts_not_reverts() { - // REX3 spec, TX limit = 10, creates 11 slots → Halt (TX-level exceed). - let code = write_n_slots(BytecodeBuilder::default(), 11).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 10, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level exceed"); - assert!(is_state_growth_limit_exceeded(&result)); -} - -// ============================================================================ -// 6. REFUND AND NET GROWTH INTERACTIONS -// ============================================================================ - -#[test] -fn test_refund_increases_remaining_budget() { - // TX limit = 100, child budget = 98 - // Child creates 90 slots, clears 50 back to zero. - // Net = 90 - 50 = 40, within budget (98) → succeeds. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 90, 50).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 40, "Net growth = 90 - 50 = 40"); -} - -#[test] -fn test_child_within_budget_after_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 40 slots, clears 10 → net = 30, within budget (49) → succeeds. - // Note: the frame-local check is eager — `used` must not exceed `limit` at any point - // during execution. Here the peak usage (40) is within the budget (49). - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 40, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 30, "Net growth = 40 - 10 = 30"); -} - -#[test] -fn test_child_exceed_with_insufficient_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 60, clears 10 → net = 50 > 49 → exceeds → reverted. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 60, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 0, "Child's growth discarded on revert"); -} - -#[test] -fn test_eager_check_reverts_despite_future_refunds() { - // TX limit = 50, child budget = 49 - // Child creates 50 slots, then would clear 10 → final net would be 40. - // But the eager check fires when net reaches 50 (at slot 50), exceeding budget 49. - // The child reverts before reaching the clearing step. - let child_code = write_n_clear_m_slots(BytecodeBuilder::default(), 50, 10).stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child revert"); - assert_eq!(state_growth, 0, "Child's growth discarded — eager check reverted before refunds"); -} - -#[test] -fn test_rex3_eager_check_halts_despite_future_refunds() { - // REX3: TX limit = 50, no per-frame limits. - // Code creates 51 slots, then would clear 10 → final net would be 41. - // But the eager TX-level check fires when net reaches 51, exceeding limit 50. - // The TX halts before reaching the clearing step. - let code = write_n_clear_m_slots(BytecodeBuilder::default(), 51, 10).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _) = transact(MegaSpecId::REX3, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_halt(), "REX3 should halt on TX-level exceed"); - assert!(is_state_growth_limit_exceeded(&result)); -} - -#[test] -fn test_create_clear_create_within_budget() { - // TX limit = 52 → child budget = 52 * 98/100 = 50 - // Child: create 40 slots (net=40), clear 10 (net=30), create 20 more (net=50). - // Net never exceeds 50 at any point → child succeeds. - let mut b = write_n_slots(BytecodeBuilder::default(), 40); - for i in 0..10_u64 { - b = b.sstore(U256::from(i), U256::from(0)); - } - for i in 40..60_u64 { - b = b.sstore(U256::from(i), U256::from(i + 1)); - } - let child_code = b.stop().build(); - - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 52, tx).unwrap(); - - assert!(result.result.is_success(), "Child should succeed — net never exceeds 50"); - assert_eq!(state_growth, 50, "Net growth = 40 - 10 + 20 = 50"); -} - -#[test] -fn test_rex3_create_clear_create_within_budget() { - // REX3: TX limit = 50, no per-frame limits. - // Code: create 40 slots (net=40), clear 10 (net=30), create 20 more (net=50). - // Net never exceeds 50 → TX succeeds. - let mut b = write_n_slots(BytecodeBuilder::default(), 40); - for i in 0..10_u64 { - b = b.sstore(U256::from(i), U256::from(0)); - } - for i in 40..60_u64 { - b = b.sstore(U256::from(i), U256::from(i + 1)); - } - let code = b.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 50, tx).unwrap(); - - assert!(result.result.is_success(), "TX should succeed — net never exceeds 50"); - assert_eq!(state_growth, 50, "Net growth = 40 - 10 + 20 = 50"); -} - -#[test] -fn test_child_refund_reflected_in_sibling_budget() { - // TX limit = 100 - // Child A: creates 10 slots, clears 5 → net = 5, succeeds. - // Parent remaining after Child A = 100 - 5 = 95. - // Child B budget = 95 * 98/100 = 93. - // Child B creates 93 slots → succeeds. - // This proves Child A's refunds flow back to the parent, giving Child B a larger budget - // than if the gross usage (10) were used (which would yield 90 * 98/100 = 88). - let child_a_code = write_n_clear_m_slots(BytecodeBuilder::default(), 10, 5).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 93).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP); - let parent_code = append_call(parent_code, CONTRACT2, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 5 + 93, "Child A net (5) + Child B (93) = 98"); -} diff --git a/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs b/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs deleted file mode 100644 index a67b545bf..000000000 --- a/crates/mega-evm/tests/rex4/selfdestruct_state_growth.rs +++ /dev/null @@ -1,609 +0,0 @@ -//! Regression tests for Finding 3: SELFDESTRUCT State Growth Overcounting. -//! -//! Before the fix, `StateGrowthTracker` recorded +1 for CREATE and +1 per new storage slot, -//! but had no SELFDESTRUCT hook. When a same-TX-created contract selfdestructed (EIP-6780), -//! the committed state had neither the account nor its storage, yet the tracker still -//! reported positive growth. -//! -//! The fix adds an `after_selfdestruct` hook that records refunds for the account and its -//! new storage slots when a `CreatedLocal` account is destroyed. Gated to REX4 only. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); -const CALLEE: Address = address!("0000000000000000000000000000000000500001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000500002"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let state_growth = evm.ctx_ref().additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Builds init code bytes: `body` opcodes followed by SELFDESTRUCT to CALLER. -fn init_code_selfdestruct(body: BytecodeBuilder) -> Vec { - body.push_address(CALLER).append(SELFDESTRUCT).build_vec() -} - -/// Builds init code: N SSTOREs then SELFDESTRUCT. -fn init_code_sstore_selfdestruct(n: u64) -> Vec { - let mut builder = BytecodeBuilder::default(); - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - init_code_selfdestruct(builder) -} - -/// Builds bytecode that CREATEs a contract with the given init code bytes. -fn create_with_init(builder: BytecodeBuilder, init_code: &[u8]) -> BytecodeBuilder { - let mut b = builder; - for (i, chunk) in init_code.chunks(32).enumerate() { - let mut word = [0u8; 32]; - word[..chunk.len()].copy_from_slice(chunk); - b = b.mstore(i * 32, word); - } - b.push_number(init_code.len() as u64).push_number(0_u64).push_number(0_u64).append(CREATE) -} - -/// Builds bytecode that CREATE2s a contract with the given init code bytes and salt. -fn create2_with_init(builder: BytecodeBuilder, init_code: &[u8], salt: u64) -> BytecodeBuilder { - let mut b = builder; - for (i, chunk) in init_code.chunks(32).enumerate() { - let mut word = [0u8; 32]; - word[..chunk.len()].copy_from_slice(chunk); - b = b.mstore(i * 32, word); - } - b.push_number(salt) - .push_number(init_code.len() as u64) - .push_number(0_u64) - .push_number(0_u64) - .append(CREATE2) -} - -/// Builds bytecode for a CALL to `target` with given gas. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(target) - .push_number(gas) - .append(CALL) -} - -// ============================================================================ -// TEST 1: CREATE + SELFDESTRUCT — net growth = 0 -// ============================================================================ - -#[test] -fn test_create_selfdestruct_zero_growth() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 2: CREATE + SSTORE + SELFDESTRUCT — net growth = 0 -// ============================================================================ - -#[test] -fn test_create_sstore_selfdestruct_zero_growth() { - let init_code = init_code_sstore_selfdestruct(1); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + 1 SSTORE + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 3: CREATE + N SSTOREs + SELFDESTRUCT — all slots refunded -// ============================================================================ - -#[test] -fn test_create_multiple_sstore_selfdestruct_zero_growth() { - let init_code = init_code_sstore_selfdestruct(5); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE + 5 SSTOREs + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 4: Cross-frame CREATE then SELFDESTRUCT -// ============================================================================ - -/// Child frame creates a contract (returns runtime code with SELFDESTRUCT). -/// Parent frame then calls the created contract, triggering SELFDESTRUCT. -#[test] -fn test_cross_frame_create_then_selfdestruct() { - // Runtime code: PUSH20(CALLER) SELFDESTRUCT - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: store runtime in memory, RETURN it. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CALLEE: CREATE → store address in memory → CALL it → STOP - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code) - // Stack: [created_addr]. Store it. - .push_number(0x100_u64) - .append(MSTORE) - // CALL the created contract - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) // load created_addr - .push_number(50_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Cross-frame create+selfdestruct should succeed"); - assert_eq!( - state_growth, 0, - "Cross-frame CREATE then SELFDESTRUCT should produce zero net growth" - ); -} - -// ============================================================================ -// TEST 5: Ancestor revert discards SELFDESTRUCT refund -// ============================================================================ - -/// Child frame creates a contract and successfully selfdestructs it, then returns -/// to parent. Parent then REVERTs. Both the creation growth and the refund from -/// the destruction must be discarded together. -#[test] -fn test_ancestor_revert_discards_selfdestruct_refund() { - // Runtime code for the created contract: SELFDESTRUCT to CALLER. - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: store runtime in memory, RETURN it. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CONTRACT: CREATE a child, store its address, CALL it (triggers SELFDESTRUCT), - // then REVERT the entire frame. - let contract_code = create_with_init(BytecodeBuilder::default(), &init_code) - .push_number(0x100_u64) - .append(MSTORE) // store created addr - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) // load created addr - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Now REVERT the entire frame — should discard both creation growth and refund. - .push_number(0_u64) - .push_number(0_u64) - .append(REVERT) - .build(); - - // CALLEE: CALL CONTRACT (which will revert), POP, STOP. - let callee_code = - append_call(BytecodeBuilder::default(), CONTRACT, 1_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(CONTRACT, contract_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success(), "Top-level should succeed after child revert"); - assert_eq!( - state_growth, 0, - "Ancestor revert should discard both creation growth and SELFDESTRUCT refund" - ); -} - -// ============================================================================ -// TEST 6: Pre-existing account SELFDESTRUCT — no refund -// ============================================================================ - -#[test] -fn test_pre_existing_account_selfdestruct_no_refund() { - let contract_code = - BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).stop().build(); - let callee_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(CONTRACT, contract_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "Pre-existing account SELFDESTRUCT should not produce refund"); -} - -// ============================================================================ -// TEST 7: Ephemeral create-destroy loop -// ============================================================================ - -#[test] -fn test_ephemeral_create_destroy_loop() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - - let mut callee = BytecodeBuilder::default(); - for _ in 0..3 { - callee = create_with_init(callee, &init_code).append(POP); - } - let callee_code = callee.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - // Limit = 1: would fail if any net growth accumulated. - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 1, tx).unwrap(); - - assert!(result.result.is_success(), "Ephemeral create-destroy loop should succeed"); - assert_eq!(state_growth, 0, "Ephemeral loop should produce zero net growth"); -} - -// ============================================================================ -// TEST 8: CREATE2 + SELFDESTRUCT — zero growth -// ============================================================================ - -#[test] -fn test_create2_selfdestruct_zero_growth() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create2_with_init(BytecodeBuilder::default(), &init_code, 42).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "CREATE2 + SELFDESTRUCT should produce zero net growth"); -} - -// ============================================================================ -// TEST 9: Pre-REX4 — overcounting preserved -// ============================================================================ - -/// On REX3, the refund hook is not active. Same-TX CREATE+SELFDESTRUCT still -/// shows +1 state growth (the old overcounting behavior preserved for replay). -#[test] -fn test_pre_rex4_selfdestruct_overcounting_preserved() { - let init_code = init_code_selfdestruct(BytecodeBuilder::default()); - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX3, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 1, - "Pre-REX4: CREATE + SELFDESTRUCT should still show +1 (overcounting preserved)" - ); -} - -// ============================================================================ -// TEST 10: SSTORE-then-clear before SELFDESTRUCT — cleared slots not counted -// ============================================================================ - -/// A same-TX-created contract writes a storage slot and then clears it (back to zero) -/// before SELFDESTRUCT. The refund logic filters on -/// `original_value().is_zero() && !present_value().is_zero()`, so cleared slots -/// must NOT be counted in the refund. Only the account itself is refunded. -#[test] -fn test_sstore_then_clear_before_selfdestruct_zero_growth() { - // Init code: SSTORE(0, 42), SSTORE(1, 99), SSTORE(0, 0), then SELFDESTRUCT. - // Slot 0 is set then cleared → present_value = 0, should not be refunded. - // Slot 1 remains non-zero → should be refunded. - // Net: CREATE +1 (account), slot 1 +1, SELFDESTRUCT refunds -1 (account) -1 (slot 1) = 0. - let init_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(42)) // set slot 0 - .sstore(U256::from(1), U256::from(99)) // set slot 1 - .sstore(U256::from(0), U256::ZERO) // clear slot 0 - .push_address(CALLER) - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 0, - "SSTORE-then-clear slot should not be counted in refund; net growth should be 0" - ); -} - -// ============================================================================ -// TEST 11: SELFDESTRUCT with mixed set-and-cleared slots -// ============================================================================ - -/// A same-TX-created contract writes 3 slots: 2 remain non-zero, 1 is cleared. -/// The refund should only count the 2 remaining slots plus the account itself. -#[test] -fn test_selfdestruct_mixed_set_and_cleared_slots() { - // Init code: SSTORE(0, 1), SSTORE(1, 2), SSTORE(2, 3), SSTORE(1, 0), SELFDESTRUCT. - // Slot 0: non-zero → refunded. - // Slot 1: set then cleared → NOT refunded. - // Slot 2: non-zero → refunded. - // Net: CREATE +1 (account), slot 0 +1, slot 1 +1 (then cleared, -1 from tracker), - // slot 2 +1, SELFDESTRUCT refunds -1 (account) -2 (slots 0 and 2) = 0. - let init_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(1), U256::from(2)) - .sstore(U256::from(2), U256::from(3)) - .sstore(U256::from(1), U256::ZERO) // clear slot 1 - .push_address(CALLER) - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - state_growth, 0, - "Cleared slot should not be counted in refund; net growth should be 0" - ); -} - -// ============================================================================ -// TEST 12: SELFDESTRUCT refund makes boundary difference -// ============================================================================ - -/// Set `state_growth_limit` = 2. Create a contract with 2 SSTOREs (growth = 3: -/// 1 account + 2 slots), then SELFDESTRUCT it (growth = 0 after refund -3). -/// Then write 2 new SSTOREs on the callee (growth = 2). Without refunds, -/// the total growth would be 5 (exceeding limit=2). With refunds, the -/// SELFDESTRUCT clears the first 3, leaving only the callee's 2 SSTOREs. -#[test] -fn test_selfdestruct_refund_enables_reuse_at_boundary() { - let init_code_sd = init_code_sstore_selfdestruct(2); - - // CALLEE: CREATE (2 SSTOREs + SELFDESTRUCT), POP, then write 2 SSTOREs on callee itself. - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code_sd) - .append(POP) - .sstore(U256::from(100), U256::from(1)) - .sstore(U256::from(101), U256::from(2)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 2, tx).unwrap(); - - assert!( - result.result.is_success(), - "SELFDESTRUCT refunds should free up budget for callee's SSTOREs" - ); - assert_eq!( - state_growth, 2, - "Net growth should be 2 (callee's 2 new SSTOREs; created contract refunded)" - ); -} - -// ============================================================================ -// TEST 13: SELFDESTRUCT to self -// ============================================================================ - -/// A same-TX-created contract selfdestructs to its own address. The refund should -/// still work correctly since the `address` parameter (the selfdestructing account) -/// is the one inspected, regardless of `target`. -#[test] -fn test_selfdestruct_to_self_zero_growth() { - // Init code: PUSH20(self_address)... but we can't know the address at build time. - // Instead, use ADDRESS opcode to push the current contract's address, then SELFDESTRUCT. - let init_code = BytecodeBuilder::default() - .append(ADDRESS) // push own address - .append(SELFDESTRUCT) - .build_vec(); - - let callee_code = - create_with_init(BytecodeBuilder::default(), &init_code).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 0, "SELFDESTRUCT to self should produce zero net growth"); -} - -// ============================================================================ -// TEST 14: Repeated SELFDESTRUCT must not double-refund -// ============================================================================ - -/// A same-TX-created contract is selfdestructed twice in the same transaction. -/// The second SELFDESTRUCT must not produce an additional refund. -/// After both destructions, one new SSTORE should bring net growth to 1. -#[test] -fn test_repeated_selfdestruct_no_double_refund() { - // Runtime code: SELFDESTRUCT to CALLER. - let runtime = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build_vec(); - - // Init code: return runtime. - let mut init = BytecodeBuilder::default(); - let runtime_len = runtime.len(); - let mut word = [0u8; 32]; - word[..runtime_len.min(32)].copy_from_slice(&runtime[..runtime_len.min(32)]); - init = init.mstore(0, word); - let init_code = - init.push_number(runtime_len as u64).push_number(0_u64).append(RETURN).build_vec(); - - // CALLEE: CREATE contract, store addr, CALL it twice (two SELFDESTRUCTs), - // then write one new SSTORE to produce +1 growth. - let callee_code = create_with_init(BytecodeBuilder::default(), &init_code) - // Store created address - .push_number(0x100_u64) - .append(MSTORE) - // First CALL: triggers SELFDESTRUCT (first effective destruction) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Second CALL: triggers SELFDESTRUCT again (previously_destroyed = true) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0x100_u64) - .append(MLOAD) - .push_number(50_000_u64) - .append(CALL) - .append(POP) - // Write one new storage slot to produce +1 net growth - .sstore(U256::from(999), U256::from(1)) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, state_growth) = transact(MegaSpecId::REX4, &mut db, 100, tx).unwrap(); - - assert!(result.result.is_success()); - // CREATE +1, first SELFDESTRUCT -1, second SELFDESTRUCT should NOT -1 again, - // new SSTORE +1. Net = 1. - assert_eq!( - state_growth, 1, - "Repeated SELFDESTRUCT must not double-refund. Expected net growth = 1 \ - (create +1, first destroy -1, SSTORE +1), got {state_growth}" - ); -} diff --git a/crates/mega-evm/tests/rex5/call_too_deep_guard.rs b/crates/mega-evm/tests/rex5/call_too_deep_guard.rs deleted file mode 100644 index 7ad6fa40a..000000000 --- a/crates/mega-evm/tests/rex5/call_too_deep_guard.rs +++ /dev/null @@ -1,253 +0,0 @@ -//! Tests for the REX5+ `CALL_STACK_LIMIT` depth guard before system contract -//! interceptor dispatch. -//! -//! Pre-REX5: an attacker who could already build the call stack to revm's `CALL_STACK_LIMIT` -//! could still invoke a system contract — the interceptor dispatch in `frame_init` ran -//! *before* revm's own depth check (which only fires inside `make_call_frame`), so the -//! synthetic interceptor result bypassed the depth boundary entirely. -//! -//! Under REX5: a `CALL_STACK_LIMIT` check is inserted between the TX-level -//! exceeded-limit guard and interceptor dispatch. Calls past the limit short-circuit -//! with `CallTooDeep` and never reach the interceptors. -//! -//! These tests drive `EvmTr::frame_init` directly with a synthetic [`FrameInit`] at the -//! depth boundary, since recursing 1025 deep through real bytecode is prohibitively -//! expensive. - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, IMegaAccessControl, MegaContext, MegaEvm, MegaSpecId, - ACCESS_CONTROL_ADDRESS, -}; -use revm::{ - context::ContextTr, - handler::{EvmTr, FrameResult, ItemOrResult}, - inspector::InspectorEvmTr, - interpreter::{ - interpreter::SharedMemory, interpreter_action::FrameInit, - interpreter_types::InterpreterTypes, CallInput, CallInputs, CallOutcome, CallScheme, - CallValue, FrameInput, Gas, InstructionResult, InterpreterResult, - }, - primitives::CALL_STACK_LIMIT, - Inspector, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000300010"); -const GAS_LIMIT: u64 = 100_000; - -fn make_call_frame_init(target: Address, selector: [u8; 4], depth: usize) -> FrameInit { - FrameInit { - depth, - memory: SharedMemory::new(), - frame_input: FrameInput::Call(Box::new(CallInputs { - input: CallInput::Bytes(Bytes::copy_from_slice(&selector)), - return_memory_offset: 0..0, - gas_limit: GAS_LIMIT, - bytecode_address: target, - target_address: target, - caller: CALLER, - value: CallValue::Transfer(U256::ZERO), - scheme: CallScheme::Call, - is_static: false, - })), - } -} - -fn assert_call_too_deep(outcome_result: &FrameResult) { - let FrameResult::Call(outcome) = outcome_result else { - panic!("expected a Call frame result, got {:?}", outcome_result); - }; - assert_eq!( - outcome.result.result, - InstructionResult::CallTooDeep, - "depth guard should produce CallTooDeep" - ); - assert_eq!(outcome.result.gas.spent(), 0, "no gas should be spent on CallTooDeep"); - assert_eq!( - outcome.result.gas.remaining(), - GAS_LIMIT, - "all forwarded gas should be available for caller refund" - ); -} - -#[test] -fn test_rex5_depth_guard_returns_call_too_deep_for_system_contract() { - // REX5: a Call to a system contract at depth > CALL_STACK_LIMIT short-circuits with - // CallTooDeep before any interceptor runs. The selector targets a real system - // contract handler (AccessControlInterceptor::disableVolatileDataAccess) so the - // test would also detect a regression that lets the interceptor fire. - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(frame_result) = result else { - panic!("expected Result variant, got Item"); - }; - assert_call_too_deep(&frame_result); - - // Side-effect check: AccessControlInterceptor would have called disable_access(depth) - // on the volatile tracker if it had fired. Confirm it did not. - let ctx = evm.ctx_ref(); - assert!( - !ctx.volatile_data_tracker.borrow().volatile_access_disabled(CALL_STACK_LIMIT as usize), - "interceptor must not have fired", - ); -} - -#[test] -fn test_rex5_depth_boundary_allows_call_at_limit() { - // REX5: depth == CALL_STACK_LIMIT is the last permitted depth. The depth guard does - // not fire and the interceptor should run normally (matches revm's `depth > limit` - // boundary in `make_call_frame`). - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result from interceptor"); - }; - // At depth == CALL_STACK_LIMIT the interceptor still runs and returns its synthetic - // Return result; the depth guard's CallTooDeep would have aborted execution otherwise. - assert_eq!(outcome.result.result, InstructionResult::Return); -} - -#[test] -fn test_pre_rex5_depth_guard_disabled() { - // REX4: the depth guard is intentionally absent for backward compatibility — the - // interceptor still fires at any depth, matching pre-fix behavior. This pins the - // replay invariant for stable specs. - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX4); - let mut evm = MegaEvm::new(context); - - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected interceptor Call result"); - }; - // The interceptor still fires under REX4, producing its synthetic Return result. - assert_eq!( - outcome.result.result, - InstructionResult::Return, - "pre-REX5 must preserve existing behavior (interceptor fires at any depth)", - ); -} - -#[test] -fn test_rex5_exceeded_tx_limit_wins_over_call_too_deep() { - // Priority-ordering regression: when both a TX-level additional-limit exceed AND - // a CALL_STACK_LIMIT overflow apply, the exceeded-limit path must win — it carries - // gas rescue semantics that CallTooDeep does not. `frame_init` and - // `inspect_frame_init` must run their existing exceeded-limit check BEFORE the - // new depth guard so the rescue path is preserved. - use mega_evm::{AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, LimitKind}; - use std::{cell::RefCell, rc::Rc}; - - let mut db = MemoryDatabase::default(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - // Construct an AdditionalLimit whose `has_exceeded_limit` is pre-set to a TX-level - // exceed. This mirrors the state produced by intrinsic-overflow detection in - // `before_tx_start` without depending on its internal API. - let mut additional = - AdditionalLimit::new(MegaSpecId::REX5, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX5)); - additional.set_has_exceeded_limit_for_test(LimitCheck::ExceedsLimit { - kind: LimitKind::KVUpdate, - limit: 0, - used: 1, - frame_local: false, - }); - context.additional_limit = Rc::new(RefCell::new(additional)); - - let mut evm = MegaEvm::new(context); - let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - let frame_init = - make_call_frame_init(ACCESS_CONTROL_ADDRESS, selector, CALL_STACK_LIMIT as usize + 1); - - let result = EvmTr::frame_init(&mut evm, frame_init).expect("frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result"); - }; - // TX-level exceed produces OutOfGas (halt path), not CallTooDeep. If the depth - // guard fires first, this assertion fails — CallTooDeep would skip gas rescue. - assert_eq!( - outcome.result.result, - InstructionResult::OutOfGas, - "exceeded-limit halt must take priority over CallTooDeep depth guard", - ); -} - -/// Inspector that unconditionally intercepts every CALL by returning a synthetic -/// success outcome from `call(...)`. Tracks how many times `call` and `call_end` -/// fire so the test can verify the inspector callback pairing is preserved. -#[derive(Default)] -struct AlwaysInterceptInspector { - call_count: usize, - call_end_count: usize, -} - -impl Inspector for AlwaysInterceptInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - self.call_count += 1; - Some(CallOutcome { - result: InterpreterResult { - result: InstructionResult::Stop, - output: Bytes::new(), - gas: Gas::new(inputs.gas_limit), - }, - memory_offset: inputs.return_memory_offset.clone(), - }) - } - - fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.call_end_count += 1; - } -} - -#[test] -fn test_rex5_inspect_frame_init_depth_guard_overrides_inspector() { - // REX5 inspect mirror: when an inspector returns Some(output) for a call past - // CALL_STACK_LIMIT, the depth guard must: - // 1. Override the inspector's success with CallTooDeep - // 2. Still call `call_end` so the inspector's start/end pairs balance - let mut db = MemoryDatabase::default(); - let context = MegaContext::new(&mut db, MegaSpecId::REX5); - let evm = MegaEvm::new(context); - let mut evm = evm.with_inspector(AlwaysInterceptInspector::default()); - - // Target a regular address (not a system contract). The inspector will intercept; - // without the depth guard, the inspector's synthetic Stop result would survive. - let target = address!("0000000000000000000000000000000000300001"); - let frame_init = make_call_frame_init(target, [0u8; 4], CALL_STACK_LIMIT as usize + 1); - - let result = InspectorEvmTr::inspect_frame_init(&mut evm, frame_init) - .expect("inspect_frame_init should not error"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("expected Call result"); - }; - // Depth guard wins over inspector synthetic Stop. - assert_eq!( - outcome.result.result, - InstructionResult::CallTooDeep, - "depth guard must override inspector's synthetic output", - ); - // call_end must have fired to keep the inspector start/end pair balanced. If a - // future refactor drops the `frame_end(...)` from the depth-guard early return, - // this asserts catches it. - let insp = evm.inspector(); - assert_eq!(insp.call_count, 1, "inspector should see exactly one call_start"); - assert_eq!(insp.call_end_count, 1, "inspector's call_end must be paired"); -} diff --git a/crates/mega-evm/tests/rex5/create_atomicity.rs b/crates/mega-evm/tests/rex5/create_atomicity.rs deleted file mode 100644 index 2ddb94c34..000000000 --- a/crates/mega-evm/tests/rex5/create_atomicity.rs +++ /dev/null @@ -1,281 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! Tests for REX5 CREATE atomicity. -//! -//! Under `MegaSpecId::REX5`, a frame-local compute-gas exceed caused by -//! the canonical code-deposit charge must take effect before -//! `process_next_action` commits the CREATE checkpoint. The result is -//! `Revert` and no code is deployed. Pre-REX5 keeps its existing -//! split-outcome behavior (`Revert` result with committed code). - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, EthHaltReason, EvmTxRuntimeLimits, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, OpHaltReason, TestExternalEnvs, -}; -use revm::{ - context::{ - result::{ExecutionResult, Output, ResultAndState}, - TxEnv, - }, - state::EvmState, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); - -/// Build init code that returns `code_len` bytes of zeros from memory[0..code_len]. -/// -/// Layout (PUSH3 used so we can pick large code_len up to ~16M): -/// PUSH3 // 4 bytes -/// PUSH1 0 // 2 bytes -/// RETURN // 1 byte -/// Total: 7 bytes. -/// -/// Compute gas inside the constructor: 3 (PUSH3) + 3 (PUSH1) + 0 (RETURN) -/// + memory expansion gas for `code_len`. -fn return_zeros_initcode(code_len: u32) -> Bytes { - let bytes = code_len.to_be_bytes(); - let mut code = Vec::with_capacity(7); - code.push(0x62); // PUSH3 - code.extend_from_slice(&bytes[1..]); // 3-byte big-endian length - code.push(0x60); // PUSH1 - code.push(0x00); - code.push(0xf3); // RETURN - Bytes::from(code) -} - -/// Build init code that returns `code_len` bytes starting with 0xEF (EIP-3541 -/// prohibited prefix) — the rest is whatever was in memory (zeros). Used to -/// pin the EIP-3541 branch of the helper predicate. -fn return_ef_prefix_initcode() -> Bytes { - // Constructor: - // PUSH1 0xEF // value - // PUSH1 0 // memory offset - // MSTORE8 // store 1 byte at offset 0 - // PUSH1 0x10 // length = 16 bytes - // PUSH1 0 // memory offset - // RETURN - Bytes::from(vec![0x60, 0xef, 0x60, 0x00, 0x53, 0x60, 0x10, 0x60, 0x00, 0xf3]) -} - -fn run_create( - spec: MegaSpecId, - tx_compute_gas_limit: u64, - init_code: Bytes, - inspector: bool, -) -> ResultAndState { - run_create_with_gas_limit(spec, tx_compute_gas_limit, 100_000_000, init_code, inspector) -} - -fn run_create_with_gas_limit( - spec: MegaSpecId, - tx_compute_gas_limit: u64, - tx_gas_limit: u64, - init_code: Bytes, - inspector: bool, -) -> ResultAndState { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(tx_compute_gas_limit); - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs(TestExternalEnvs::::new().into()) - .with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: tx_gas_limit, - gas_price: 0, - data: init_code, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - if inspector { - // Default no-op inspector — forces inspect_frame_run path. - let mut evm = MegaEvm::new(context).with_inspector(revm::inspector::NoOpInspector {}); - alloy_evm::Evm::transact_raw(&mut evm, tx) - .expect("transact (inspector) should not surface EVMError") - } else { - let mut evm = MegaEvm::new(context); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError") - } -} - -/// Returns true if the post-state delta contains a non-empty code account -/// at the deployed address. Looking at `state.code` is more reliable than -/// scanning the journal because it reflects what `transact_raw` reports as -/// the committed state delta. -fn deployed_account_has_code(state: &EvmState, deployed_address: Address) -> bool { - state - .get(&deployed_address) - .map(|acc| { - acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false) || - acc.info.code_hash != revm::primitives::KECCAK_EMPTY - }) - .unwrap_or(false) -} - -/// Constructor returns 8000 bytes; canonical `code_len * 200` = 1.6M. -const CODE_LEN: u32 = 8_000; - -/// Per-frame compute budget calibrated so only the code-deposit charge -/// can overshoot: constructor + intrinsic stay well below 1M. -const TIGHT_COMPUTE_BUDGET: u64 = 1_000_000; - -/// Per-frame compute budget large enough to cover code-deposit too. -const GENEROUS_COMPUTE_BUDGET: u64 = 4_000_000; - -/// Under REX5, a tight compute budget that overshoots only on the -/// code-deposit charge produces a `Revert` result with no committed code. -#[test] -fn test_create_compute_gas_exceed_during_codedeposit_does_not_split_outcome() { - let res = - run_create(MegaSpecId::REX5, TIGHT_COMPUTE_BUDGET, return_zeros_initcode(CODE_LEN), false); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!( - !deployed_account_has_code(&res.state, deployed_address), - "deployed account at {deployed_address} must not have code; state entry: {:?}", - res.state.get(&deployed_address) - ); -} - -/// Same fixture under REX4: pre-REX5 keeps its existing split-outcome -/// behavior (`Revert` result with code already committed by -/// `return_create`). -#[test] -fn test_pre_rex5_preserves_split_outcome() { - let res = - run_create(MegaSpecId::REX4, TIGHT_COMPUTE_BUDGET, return_zeros_initcode(CODE_LEN), false); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!( - deployed_account_has_code(&res.state, deployed_address), - "REX4 split outcome: deployed account at {deployed_address} must have code; \ - state entry: {:?}", - res.state.get(&deployed_address) - ); -} - -/// Generous compute budget allows CREATE to commit normally. -#[test] -fn test_create_compute_gas_within_budget_still_commits_normally() { - let res = run_create( - MegaSpecId::REX5, - GENEROUS_COMPUTE_BUDGET, - return_zeros_initcode(CODE_LEN), - false, - ); - - assert!(res.result.is_success(), "got: {:?}", res.result); - - let deployed_address = match &res.result { - ExecutionResult::Success { output: Output::Create(_, Some(addr)), .. } => *addr, - other => panic!("Expected Create output with address, got: {other:?}"), - }; - assert_eq!(deployed_address, CALLER.create(0)); - assert!(deployed_account_has_code(&res.state, deployed_address)); -} - -/// `inspect_frame_run` shares the same hooks as `frame_run`; the REX5 -/// behavior must apply identically on the inspector path. -#[test] -fn test_inspect_frame_run_path_matches_frame_run() { - let res = run_create( - MegaSpecId::REX5, - TIGHT_COMPUTE_BUDGET, - return_zeros_initcode(CODE_LEN), - true, // forces inspect_frame_run path - ); - - let result_is_revert = matches!(&res.result, ExecutionResult::Revert { .. }); - let result_is_halt = matches!(&res.result, ExecutionResult::Halt { .. }); - assert!(result_is_revert || result_is_halt, "got: {:?}", res.result); - - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// A CREATE whose constructor returns code starting with 0xEF takes -/// `return_create`'s EIP-3541 revert path; the pre-charge must not fire, -/// so a generous compute budget produces a clean reject. -#[test] -fn test_create_with_eip3541_prefix_skips_pre_charge() { - let res = - run_create(MegaSpecId::REX5, GENEROUS_COMPUTE_BUDGET, return_ef_prefix_initcode(), false); - - // op-revm classifies the EIP-3541 reject as either Halt or Revert - // depending on wrapping; what matters is no success and no code. - assert!( - matches!(&res.result, ExecutionResult::Halt { .. } | ExecutionResult::Revert { .. }), - "got: {:?}", - res.result - ); - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// `gas.remaining() < code_deposit_gas` at RETURN must skip the REX5 pre-charge: -/// revm's `return_create` reverts on its own with `OutOfGas`. A spurious -/// pre-charge would surface as `ComputeGasLimitExceeded` instead, so the halt -/// reason discriminates the two paths. -#[test] -fn test_create_insufficient_gas_for_code_deposit_skips_pre_charge() { - // tx gas (1_650_000) just below code_deposit_gas (CODE_LEN * 200 = 1_600_000) - // plus constructor cost, so revm's record_cost on the deposit fails. - let res = run_create_with_gas_limit( - MegaSpecId::REX5, - TIGHT_COMPUTE_BUDGET, - 1_650_000, - return_zeros_initcode(CODE_LEN), - false, - ); - - let reason = match &res.result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - other => panic!("Expected Halt, got: {other:?}"), - }; - assert!( - matches!(reason, MegaHaltReason::Base(OpHaltReason::Base(EthHaltReason::OutOfGas(_)))), - "got: {reason:?}", - ); - - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} - -/// A CREATE whose constructor returns more than `max_code_size` bytes -/// takes `return_create`'s EIP-170 revert path; the pre-charge must not -/// fire, so a generous compute budget produces a clean reject. -#[test] -fn test_create_with_oversized_code_skips_pre_charge() { - // Larger than both EIP-170 (0x6000) and EIP-7907 (0xc000). - const OVERSIZE_CODE_LEN: u32 = 64_000; - let res = run_create( - MegaSpecId::REX5, - GENEROUS_COMPUTE_BUDGET, - return_zeros_initcode(OVERSIZE_CODE_LEN), - false, - ); - - assert!(!res.result.is_success(), "got: {:?}", res.result); - let deployed_address = CALLER.create(0); - assert!(!deployed_account_has_code(&res.state, deployed_address)); -} diff --git a/crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs b/crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs deleted file mode 100644 index d3cd9ee2f..000000000 --- a/crates/mega-evm/tests/rex5/frame_target_updated_dedup.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! Tests for Rex5's caller-account deduplication within a parent frame. -//! -//! Pre-Rex5, `DataSizeTracker::before_frame_init` and `KVUpdateTracker::before_frame_init` -//! checked the parent frame's `target_updated` flag to decide whether to charge the parent's -//! caller-account update for a value-transferring CALL / CALLCODE or CREATE, but never set -//! the flag to `true` after charging. As a result, every subsequent value-transferring call -//! or create from the same parent frame re-charged the caller account, overcounting data -//! size and KV updates. -//! -//! Rex5 marks the parent's flag after charging, so subsequent operations from the same -//! parent frame no longer double-charge the caller account. Per-target charges for distinct -//! callee / created addresses are unchanged. Pre-Rex5 specs keep their existing (frozen) -//! overcounting behavior for backward compatibility. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, -}; -use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, INVALID, POP, PUSH0, PUSH1, STOP}, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); - -/// Runs the given `tx` on `spec` with unlimited data/KV budgets and returns the -/// recorded data size and KV update counts. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let usage = ctx.additional_limit.borrow().get_usage(); - Ok((r, usage.data_size, usage.kv_updates)) -} - -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Appends `CALL(gas=GAS, target, value=1, args=[], ret=[])`, leaving the CALL -/// success flag on the stack. -fn append_value_call(builder: BytecodeBuilder, target: Address) -> BytecodeBuilder { - builder - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .append(PUSH1) - .append(1u8) // value - .push_address(target) - .append(GAS) - .append(CALL) -} - -/// Appends a CREATE with value=1 and an empty init code (immediately returns). -fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .append_many([PUSH0, PUSH0]) // initLen, initOff (empty init code) - .append(PUSH1) - .append(1u8) // value - .append(CREATE) -} - -/// Base intrinsic data size for a TX with no calldata / access-list / 7702 entries: -/// `BASE_TX_SIZE` + caller account write. -fn intrinsic_data_size() -> u64 { - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE -} - -// ============================================================================ -// Two consecutive value-transferring CALLs -// ============================================================================ - -/// CALLEE does two value-transferring CALLs to two distinct targets. -/// -/// Expected charges for the caller (= CALLEE parent frame) update: -/// - Rex5: charged once (deduplicated) -/// - Pre-Rex5 (Rex4): charged twice (overcounting bug) -/// -/// The two distinct target accounts are always charged separately. -fn two_value_calls_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); - builder = append_value_call(builder, CONTRACT2).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_two_value_calls_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_value_calls_code()); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE, counted once) + 1 (CONTRACT) + 1 (CONTRACT2) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate the CALLEE (parent) update across both calls"); - // Data size: intrinsic + 3 discardable account writes (CALLEE once, CONTRACT, CONTRACT2). - assert_eq!(data_size, intrinsic_data_size() + 3 * ACCOUNT_INFO_WRITE_SIZE); -} - -#[test] -fn test_rex4_two_value_calls_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_value_calls_code()); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5 behavior: the CALLEE parent update is charged on BOTH calls. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double-charged) + 1 (CONTRACT) + 1 (CONTRACT2) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); - assert_eq!(data_size, intrinsic_data_size() + 4 * ACCOUNT_INFO_WRITE_SIZE); -} - -// ============================================================================ -// CREATE followed by value-transferring CALL -// ============================================================================ - -/// CALLEE does a CREATE followed by a value-transferring CALL, both from the same -/// parent frame. The parent update should only be charged once under Rex5. -fn create_then_call_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_create(builder).append(POP); - builder = append_value_call(builder, CONTRACT).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_create_then_call_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, create_then_call_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE parent, counted once) + 1 (created account) - // + 1 (CONTRACT) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE update across CREATE and CALL"); -} - -#[test] -fn test_rex4_create_then_call_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, create_then_call_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5 behavior: CALLEE parent charged both by CREATE and by the subsequent CALL. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double-charged) + 1 (created) + 1 (CONTRACT) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); -} - -// ============================================================================ -// Two consecutive CREATEs from the same parent -// ============================================================================ - -/// CALLEE does two CREATEs from the same parent frame. The parent update should -/// only be charged once under Rex5 (created accounts still counted per-CREATE). -fn two_creates_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_create(builder).append(POP); - builder = append_value_create(builder).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_two_creates_dedup_parent_kv() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_creates_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE, once) + 2 (two distinct created accounts) = 4. - assert_eq!(kv_updates, 4, "Rex5 must deduplicate CALLEE across both CREATEs"); -} - -#[test] -fn test_rex4_two_creates_overcount_preserved() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, two_creates_code()); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5: CALLEE parent charged on BOTH CREATEs. - // KV updates: 1 (caller nonce) + 2 (CALLEE, double) + 2 (created accounts) = 5. - assert_eq!(kv_updates, 5, "Rex4 must preserve the pre-Rex5 overcounting behavior"); -} - -// ============================================================================ -// Reverted child still discards its accumulated charges -// ============================================================================ - -/// CALLEE CALLs CONTRACT with value. CONTRACT is an INVALID instruction that -/// halts, so the child frame's discardable usage must be dropped on revert, -/// regardless of spec. -fn call_that_reverts_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); - builder.append(STOP).build() -} - -#[test] -fn test_rex5_reverted_child_drops_discardable_charges() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, call_that_reverts_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success(), "outer TX succeeds even though child reverts"); - - // The child's discardable charges (CALLEE parent update + CONTRACT target update) are - // dropped on revert. Only the persistent caller nonce survives. - assert_eq!(kv_updates, 1, "Reverted child's discardable KV updates must be dropped"); - assert_eq!(data_size, intrinsic_data_size(), "Reverted child's data size must be dropped"); -} - -#[test] -fn test_rex4_reverted_child_drops_discardable_charges() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, call_that_reverts_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success(), "outer TX succeeds even though child reverts"); - - // Existing revert behavior must stay unchanged pre-Rex5. - assert_eq!(kv_updates, 1); - assert_eq!(data_size, intrinsic_data_size()); -} - -// ============================================================================ -// Reverted first child followed by a successful second child (revert-then-retry) -// ============================================================================ - -/// CALLEE first CALLs CONTRACT with value (reverts), then CALLs CONTRACT2 with value (succeeds). -/// Under Rex5, the parent (CALLEE) account update should be charged exactly once — from the -/// second (successful) call, not zero times. Without the flag-reset-on-revert fix, Rex5 would -/// set `target_updated` on the first call, see it still set on the second, and charge 0 times. -fn revert_then_succeed_code() -> Bytes { - let mut builder = BytecodeBuilder::default(); - builder = append_value_call(builder, CONTRACT).append(POP); // CONTRACT reverts - builder = append_value_call(builder, CONTRACT2).append(POP); // CONTRACT2 succeeds - builder.append(STOP).build() -} - -#[test] -fn test_rex5_reverted_first_child_flag_reset_allows_second_charge() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, revert_then_succeed_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); // CONTRACT2 has no code → EOA - - let (res, data_size, kv_updates) = - transact(MegaSpecId::REX5, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // KV updates: 1 (caller nonce) + 1 (CALLEE parent, charged on successful 2nd call) - // + 1 (CONTRACT2) = 3. - // The first call's charges (CALLEE + CONTRACT) are dropped on revert, and the - // target_updated flag is reset, so the second call correctly re-charges CALLEE. - assert_eq!( - kv_updates, 3, - "Rex5 must charge CALLEE once after revert-then-retry (not undercount to 0)" - ); - assert_eq!(data_size, intrinsic_data_size() + 2 * ACCOUNT_INFO_WRITE_SIZE); -} - -#[test] -fn test_rex4_reverted_first_child_flag_not_set() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_balance(CALLEE, U256::from(10_000_000)) - .account_code(CALLEE, revert_then_succeed_code()) - .account_code(CONTRACT, Bytes::from_static(&[INVALID])); - - let (res, _data_size, kv_updates) = - transact(MegaSpecId::REX4, &mut db, default_tx(CALLEE)).unwrap(); - assert!(res.result.is_success()); - - // Pre-Rex5: flag is never set, so both calls charge the parent independently. - // KV updates: 1 (caller nonce) + 1 (CALLEE from 1st call, dropped on revert) - // + 1 (CALLEE from 2nd call) + 1 (CONTRACT2) = 3. - // Note: the first call's CALLEE charge is dropped on revert, so Rex4 also gives 3 here. - // The overcounting in Rex4 manifests when BOTH calls succeed (tested separately above). - assert_eq!(kv_updates, 3); -} diff --git a/crates/mega-evm/tests/rex6/create_frame_accounting.rs b/crates/mega-evm/tests/rex6/create_frame_accounting.rs deleted file mode 100644 index 5ee963336..000000000 --- a/crates/mega-evm/tests/rex6/create_frame_accounting.rs +++ /dev/null @@ -1,395 +0,0 @@ -//! REX6 CREATE-frame resource-accounting tests. -//! -//! Under REX6, `StateGrowthTracker` records +1 state growth for a `CREATE` only when the -//! deployment address is a net-new account; a pre-funded balance-only target already exists -//! and is not counted. Pre-REX6 records +1 unconditionally. -//! -//! This file also pins that a child-CREATE's creator nonce-bump account-info write is charged -//! to the parent frame's discardable lane under REX6, so the charge survives the child's revert -//! and is correctly attributed to the frame that owns the on-chain effect. - -use alloy_primitives::{Address, Bytes, U256}; -use mega_evm::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, ACCOUNT_INFO_WRITE_SIZE, -}; -use revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - BlockEnv, ContextSetters, TxEnv, - }, - handler::EvmTr, - primitives::TxKind, -}; - -const CALLER: Address = Address::new([ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0xDE, 0x00, 0x01, -]); -const CALLER_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH -const TX_GAS_LIMIT: u64 = 5_000_000; // generous headroom for a trivial CREATE; not a bound under test - -type TestEvm = MegaEvm; -type TestResult = ResultAndState; - -/// Builds a configured `MegaEvm` for `spec` with the given `limits` and operator fees zeroed -/// (so only the accounting under test moves). Single source of truth for block/chain setup. -fn make_evm_with_limits( - spec: MegaSpecId, - db: MemoryDatabase, - limits: EvmTxRuntimeLimits, -) -> TestEvm { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -/// Builds a configured `MegaEvm` for `spec` with no tx runtime limits and operator fees zeroed. -/// Shared by every test in this file that doesn't need custom limits. -fn make_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { - make_evm_with_limits(spec, db, EvmTxRuntimeLimits::no_limits()) -} - -/// Init code that immediately STOPs (deploys empty runtime) — a trivial successful CREATE. -fn stop_init_code() -> Bytes { - Bytes::from_static(&[0x00]) // STOP -} - -fn run(spec: MegaSpecId, db: MemoryDatabase, init_code: Bytes) -> (TestResult, TestEvm) { - let mut evm = make_evm(spec, db); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - data: init_code, - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - (r, evm) -} - -/// The address a top-level CREATE from CALLER (nonce 0) deploys to. -fn first_create_address() -> Address { - CALLER.create(0) -} - -/// REX6: a CREATE deploying to an address that ALREADY exists (pre-funded balance-only) must -/// NOT record a state-growth account-creation event; a fresh-address CREATE still records +1. -#[test] -fn test_rex6_create_to_prefunded_address_records_no_state_growth() { - // --- fresh address: no pre-existing account --- - let db_fresh = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let (res_fresh, evm_fresh) = run(MegaSpecId::REX6, db_fresh, stop_init_code()); - assert!(res_fresh.result.is_success(), "fresh CREATE must succeed: {:?}", res_fresh.result); - let growth_fresh = evm_fresh.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - // --- prefunded address: target already has a balance-only account --- - let db_prefunded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_balance(first_create_address(), U256::from(1u64)); - let (res_pre, evm_pre) = run(MegaSpecId::REX6, db_prefunded, stop_init_code()); - assert!(res_pre.result.is_success(), "prefunded CREATE must succeed: {:?}", res_pre.result); - let growth_pre = evm_pre.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - assert_eq!( - growth_fresh.saturating_sub(growth_pre), - 1, - "REX6 CREATE must record +1 state_growth only for a net-new address \ - (fresh={growth_fresh}, prefunded={growth_pre})", - ); -} - -const OUTER_CREATOR: Address = Address::new([ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0xDE, 0x00, 0xFF, -]); - -/// Bytecode: PUSH5 0x60006000fd; PUSH1 0; MSTORE; PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP; STOP. -/// The inner CREATE deploys init code [60 00 60 00 FD] = PUSH1 0; PUSH1 0; REVERT, which reverts, -/// so the nested CREATE frame reverts while this outer contract returns success. -fn outer_creator_code() -> Bytes { - Bytes::from_static(&[ - 0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, // PUSH5 - 0x60, 0x00, // PUSH1 0 (mem offset) - 0x52, // MSTORE - 0x60, 0x05, // PUSH1 5 (create length) - 0x60, 0x1b, // PUSH1 27 (create offset) - 0x60, 0x00, // PUSH1 0 (create value) - 0xf0, // CREATE - 0x50, // POP - 0x00, // STOP - ]) -} - -#[test] -fn test_rex6_nested_create_revert_charges_creator_nonce_bump_to_parent() { - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(OUTER_CREATOR, outer_creator_code()) - }; - let make_call = || { - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - kind: TxKind::Call(OUTER_CREATOR), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - tx - }; - let usage = |spec: MegaSpecId| { - let mut evm = make_evm(spec, build_db()); - let r = alloy_evm::Evm::transact_raw(&mut evm, make_call()); - assert!(r.expect("ok").result.is_success(), "outer call must succeed (spec {spec:?})"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage - }; - let rex5 = usage(MegaSpecId::REX5); - let rex6 = usage(MegaSpecId::REX6); - assert_eq!( - rex6.data_size.saturating_sub(rex5.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "REX6 must keep the creator nonce-bump account-info write (+{ACCOUNT_INFO_WRITE_SIZE}) on \ - the surviving parent (rex5={}, rex6={})", - rex5.data_size, - rex6.data_size, - ); - assert_eq!( - rex6.kv_updates.saturating_sub(rex5.kv_updates), - 1, - "REX6 must keep the creator nonce-bump KV write (+1) on the surviving parent \ - (rex5={}, rex6={})", - rex5.kv_updates, - rex6.kv_updates, - ); -} - -/// Init code that returns `code_len` bytes of zeros from `memory[0..code_len]`. -/// -/// Layout: PUSH3 `code_len`; PUSH1 0; RETURN. -fn return_zeros_initcode(code_len: u32) -> Bytes { - let bytes = code_len.to_be_bytes(); - let mut code = Vec::with_capacity(7); - code.push(0x62); // PUSH3 - code.extend_from_slice(&bytes[1..]); // 3-byte big-endian length - code.push(0x60); // PUSH1 - code.push(0x00); - code.push(0xf3); // RETURN - Bytes::from(code) -} - -/// Runs a top-level CREATE under `spec` with `data_size_limit` as the tx data-size budget and a -/// constructor that RETURNs `code_len` runtime bytes, with `tx_gas_limit` available to the frame. -fn run_create_with_limits( - spec: MegaSpecId, - data_size_limit: u64, - code_len: u32, - tx_gas_limit: u64, -) -> TestResult { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data_size_limit); - let mut evm = make_evm_with_limits(spec, db, limits); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: tx_gas_limit, - gas_price: 0, - data: return_zeros_initcode(code_len), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError") -} - -/// A CREATE whose Mega code-deposit-storage charge runs out of gas while the frame's data-size -/// budget is simultaneously exceeded is absorbed into the frame-local `Revert` and its unspent -/// child gas is returned to the caller — identically on REX6 and pre-REX6. The frame-local absorb -/// treats an already-failed CREATE the same as a successful-but-over-limit one, so REX5 and REX6 -/// produce the same result class and the same `gas_used` (no spec divergence on this path). -/// -/// Setup: the constructor RETURNs an 8_000-byte runtime blob. The Mega code-deposit-storage charge -/// (`CODEDEPOSIT_STORAGE_GAS` per byte) far exceeds the 400_000-gas frame budget, so the frame -/// returns `OutOfGas`. At the same time the runtime blob overshoots the tiny `tx_data_size_limit` -/// (2000 bytes), so the frame-local data-size limit is also exceeded — the exact edge where the -/// absorb fires. -#[test] -fn test_rex6_create_oog_over_limit_matches_rex5_frozen() { - // Runtime blob large enough that the code-deposit-storage charge cannot fit in `GAS`, and - // large enough to overshoot DATA_SIZE_LIMIT so the frame-local data-size limit also trips. - const CODE_LEN: u32 = 8_000; - const DATA_SIZE_LIMIT: u64 = 2_000; - // Frame gas budget far below the code-deposit-storage charge (CODE_LEN * 10_000), so the - // charge runs OutOfGas; large enough for the constructor + intrinsic to run first. - const GAS: u64 = 400_000; - - let r5 = run_create_with_limits(MegaSpecId::REX5, DATA_SIZE_LIMIT, CODE_LEN, GAS); - let r6 = run_create_with_limits(MegaSpecId::REX6, DATA_SIZE_LIMIT, CODE_LEN, GAS); - - // Both specs absorb the failed CREATE into the frame-local Revert. - assert!( - matches!(r5.result, ExecutionResult::Revert { .. }), - "REX5 absorbs the OutOfGas CREATE into a frame-local Revert: {:?}", - r5.result, - ); - assert!( - matches!(r6.result, ExecutionResult::Revert { .. }), - "REX6 absorbs the OutOfGas CREATE into a frame-local Revert identically to REX5: {:?}", - r6.result, - ); - - // Same result class → same returned gas; no REX6 burn-vs-refund divergence on this path. - assert_eq!( - r6.result.gas_used(), - r5.result.gas_used(), - "REX6 must return the absorbed CREATE's gas identically to REX5 \ - (rex5_gas_used={}, rex6_gas_used={})", - r5.result.gas_used(), - r6.result.gas_used(), - ); -} - -/// Pre-REX6 freeze: under REX5 a CREATE records state growth unconditionally, so deploying to a -/// pre-funded (already-existing) address records the same state growth as deploying to a fresh -/// one — the net-new distinction is REX6-only. -#[test] -fn test_rex5_freeze_create_state_growth_unconditional() { - let db_fresh = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let (rf, ef) = run(MegaSpecId::REX5, db_fresh, stop_init_code()); - assert!(rf.result.is_success(), "REX5 fresh CREATE must succeed"); - let fresh = ef.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - let db_pre = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_balance(first_create_address(), U256::from(1u64)); - let (rp, ep) = run(MegaSpecId::REX5, db_pre, stop_init_code()); - assert!(rp.result.is_success(), "REX5 prefunded CREATE must succeed"); - let pre = ep.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - assert_eq!( - fresh, pre, - "REX5 must record CREATE state_growth unconditionally (fresh={fresh}, prefunded={pre})", - ); -} - -/// REX6: a DB failure while inspecting the CREATE target for the net-new state-growth check must -/// surface as an error, not be silently swallowed. A normal `MemoryDatabase` is infallible, so the -/// `inspect_account(created_address, ..)?` error branch is only exercised by injecting a DB read -/// failure here. The created-address read happens after the caller-nonce read, so failing on -/// `first_create_address()` lets the caller read succeed and trips exactly the created-address -/// inspect. -#[test] -fn test_rex6_create_net_new_inspect_db_error_surfaces() { - let inner = MemoryDatabase::default().account_balance(CALLER, U256::from(CALLER_BALANCE)); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(first_create_address()); - - let mut context = MegaContext::new(db, MegaSpecId::REX6); - context.set_block(BlockEnv { gas_limit: 1_000_000_000, ..Default::default() }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Create, - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - data: stop_init_code(), - value: U256::ZERO, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - - let res = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(res.is_err(), "DB error during REX6 CREATE net-new inspect must surface as Err"); -} - -/// Bytecode like [`outer_creator_code`] but with the reverting CREATE performed TWICE -/// (revert-then-retry). The creator's account-info write must be charged once, not once per -/// attempt: the first CREATE's parent-lane charge survives the child's revert (the nonce bump -/// does too), so the unwind must not re-arm the dedup flag. -fn outer_double_creator_code() -> Bytes { - Bytes::from_static(&[ - 0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, // PUSH5 - 0x60, 0x00, // PUSH1 0 (mem offset) - 0x52, // MSTORE - 0x60, 0x05, // PUSH1 5 (create length) - 0x60, 0x1b, // PUSH1 27 (create offset) - 0x60, 0x00, // PUSH1 0 (create value) - 0xf0, // CREATE (#1 — reverts) - 0x50, // POP - 0x60, 0x05, // PUSH1 5 - 0x60, 0x1b, // PUSH1 27 - 0x60, 0x00, // PUSH1 0 - 0xf0, // CREATE (#2 — reverts again) - 0x50, // POP - 0x00, // STOP - ]) -} - -/// REX6: a reverted-then-retried nested CREATE charges the creator's account-info write exactly -/// once. Before the unwind gate, `pop_frame_unwind_parent` reset the parent's dedup flag while -/// the parent-lane charge survived — the retry charged the same creator update again. -#[test] -fn test_rex6_nested_create_revert_then_retry_charges_creator_once() { - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(OUTER_CREATOR, outer_double_creator_code()) - }; - let make_call = || { - let mut tx = MegaTransaction::new(TxEnv { - caller: CALLER, - kind: TxKind::Call(OUTER_CREATOR), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }); - tx.enveloped_tx = Some(Bytes::new()); - tx - }; - let usage = |spec: MegaSpecId| { - let mut evm = make_evm(spec, build_db()); - let r = alloy_evm::Evm::transact_raw(&mut evm, make_call()); - assert!(r.expect("ok").result.is_success(), "outer call must succeed (spec {spec:?})"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage - }; - let rex5 = usage(MegaSpecId::REX5); - let rex6 = usage(MegaSpecId::REX6); - assert_eq!( - rex6.data_size.saturating_sub(rex5.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "double reverted CREATE must charge the creator write ONCE under REX6 \ - (rex5={}, rex6={})", - rex5.data_size, - rex6.data_size, - ); - assert_eq!( - rex6.kv_updates.saturating_sub(rex5.kv_updates), - 1, - "double reverted CREATE must charge the creator KV update ONCE under REX6 \ - (rex5={}, rex6={})", - rex5.kv_updates, - rex6.kv_updates, - ); -} diff --git a/crates/mega-evm/tests/rex6/metering_order_parity.rs b/crates/mega-evm/tests/rex6/metering_order_parity.rs deleted file mode 100644 index 70c1c01d0..000000000 --- a/crates/mega-evm/tests/rex6/metering_order_parity.rs +++ /dev/null @@ -1,240 +0,0 @@ -//! REX6 unifies the per-opcode gas-metering order: compute gas is recorded exactly once, after the -//! opcode body has fully executed, with the storage gas charged in the opcode excluded. -//! -//! For every storage-affecting opcode **except CREATE2**, the pre-REX6 layering already followed -//! this order (nothing consumes EVM gas before the storage-gas charge), so the REX6 canonical path -//! must be byte-for-byte behavior-preserving relative to REX5: identical execution result, -//! compute-gas tracker reading, and `gas_used`. -//! -//! These tests pin that equivalence. CREATE2's intended divergence on the failure path is covered -//! in [`super::create2_metering_order`]. - -use crate::common::{transact, transact_default, CALLER, CONTRACT, EMPTY_TARGET}; -use alloy_primitives::{Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaSpecId, -}; -use revm::bytecode::opcode::{ - CALL, CALLCODE, CREATE, DELEGATECALL, LOG1, SELFDESTRUCT, SSTORE, STATICCALL, STOP, -}; - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// Runs `build_db()` under REX5 and REX6 (identical runtime limits) and asserts the execution -/// result, compute-gas reading, and `gas_used` are identical — i.e. the REX6 canonical metering -/// order reproduces the frozen REX5 behavior exactly. -fn assert_rex5_rex6_parity( - label: &str, - expect_success: bool, - build_db: impl Fn() -> MemoryDatabase, -) { - let r5 = transact_default(MegaSpecId::REX5, build_db()); - let r6 = transact_default(MegaSpecId::REX6, build_db()); - - assert_eq!( - r5.is_success(), - expect_success, - "{label}: REX5 success expectation mismatch; got {:?}", - r5.result - ); - assert_eq!( - r5.is_success(), - r6.is_success(), - "{label}: success mismatch REX5={:?} REX6={:?}", - r5.result, - r6.result - ); - assert_eq!( - r5.compute_gas, r6.compute_gas, - "{label}: compute_gas must be identical (behavior-preserving); REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - assert_eq!( - r5.gas_used, r6.gas_used, - "{label}: gas_used must be identical (behavior-preserving); REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - -fn base_db(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) -} - -#[test] -fn test_sstore_metering_parity_rex5_rex6() { - // SSTORE zero -> non-zero triggers the dynamic storage-gas path in `storage_gas_ext::sstore`. - let code = BytecodeBuilder::default().sstore(U256::from(7), U256::from(99)).stop().build(); - assert_rex5_rex6_parity("SSTORE", true, || base_db(code.clone())); -} - -#[test] -fn test_log_metering_parity_rex5_rex6() { - // LOG1 with 32 bytes of data exercises the topic + data storage-gas charge in - // `storage_gas_ext::log`. Stack for LOG1 pops offset, len, topic (offset on top). - let code = BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .push_number(0xabcu64) // topic0 - .push_number(32u64) // len - .push_number(0u64) // offset - .append(LOG1) - .stop() - .build(); - assert_rex5_rex6_parity("LOG1", true, || base_db(code.clone())); -} - -#[test] -fn test_call_value_transfer_metering_parity_rex5_rex6() { - // CALL transferring value to an empty account exercises the new-account storage-gas path in - // `storage_gas_ext::call`. Stack pops gas, to, value, aoff, asz, roff, rsz (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(CALL) - .stop() - .build(); - assert_rex5_rex6_parity("CALL", true, || base_db(code.clone())); -} - -#[test] -fn test_create_metering_parity_rex5_rex6() { - // CREATE (non-CREATE2) with empty initcode. Stack pops value, offset, length (value on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .stop() - .build(); - assert_rex5_rex6_parity("CREATE", true, || base_db(code.clone())); -} - -#[test] -fn test_selfdestruct_new_beneficiary_metering_parity_rex5_rex6() { - // SELFDESTRUCT to an empty, non-beneficiary target while the contract holds balance exercises - // the new-account storage-gas path in `storage_gas_ext::selfdestruct` (REX5+). - let code = BytecodeBuilder::default().push_address(EMPTY_TARGET).append(SELFDESTRUCT).build(); - assert_rex5_rex6_parity("SELFDESTRUCT", true, || base_db(code.clone())); -} - -#[test] -fn test_delegatecall_metering_parity_rex5_rex6() { - // DELEGATECALL has no value operand, so `storage_charged` is always 0; this pins the - // `storage_gas_ext::delegate_call` REX6 path. Stack pops gas, to, argsOffset, argsSize, - // retOffset, retSize (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(DELEGATECALL) - .stop() - .build(); - assert_rex5_rex6_parity("DELEGATECALL", true, || base_db(code.clone())); -} - -#[test] -fn test_staticcall_metering_parity_rex5_rex6() { - // STATICCALL has no value operand either; same stack layout as DELEGATECALL. - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(STATICCALL) - .stop() - .build(); - assert_rex5_rex6_parity("STATICCALL", true, || base_db(code.clone())); -} - -/// Pushes the same operands as a `SSTORE(slot=7, value=99)` but stops before the SSTORE byte, so -/// the run measures the compute-gas accumulated up to the opcode under test (TX intrinsic + the -/// two PUSH instructions). This is the same baseline-measurement trick used by -/// `super::create2_metering_order::build_pushes_only_contract`. -fn build_sstore_pushes_only_contract() -> Bytes { - BytecodeBuilder::default() - .push_u256(U256::from(99u64)) // value - .push_u256(U256::from(7u64)) // slot - .append(STOP) - .build() -} - -fn build_sstore_contract() -> Bytes { - BytecodeBuilder::default() - .push_u256(U256::from(99u64)) // value - .push_u256(U256::from(7u64)) // slot - .append(SSTORE) - .append(STOP) - .build() -} - -#[test] -fn test_sstore_compute_limit_halt_parity_rex5_rex6() { - // Place the compute-gas limit just past the pre-SSTORE usage so the limit trips after the - // storage-gas charge (storage gas doesn't bill compute) and after the inner SSTORE body has - // run — i.e. at the post-body `record_storage_compute_gas!` call. This is the consensus- - // critical halt boundary the REX6 metering-order claim rests on: REX5 ↔ REX6 must be - // byte-identical here, since nothing between `gas_before` and the storage charge consumes - // EVM gas on the non-CREATE2 opcodes. - let usage_before_sstore = - transact_default(MegaSpecId::REX6, base_db(build_sstore_pushes_only_contract())) - .compute_gas; - let compute_limit = usage_before_sstore + 100; - - let limits = - |spec| EvmTxRuntimeLimits::from_spec(spec).with_tx_compute_gas_limit(compute_limit); - - let r5 = transact(MegaSpecId::REX5, base_db(build_sstore_contract()), limits(MegaSpecId::REX5)); - let r6 = transact(MegaSpecId::REX6, base_db(build_sstore_contract()), limits(MegaSpecId::REX6)); - - assert!(!r5.is_success(), "REX5 must halt under the tight compute limit; got {:?}", r5.result); - assert!(!r6.is_success(), "REX6 must halt under the tight compute limit; got {:?}", r6.result); - assert_eq!( - format!("{:?}", r5.result), - format!("{:?}", r6.result), - "SSTORE halt: result must be identical; REX5={:?} REX6={:?}", - r5.result, - r6.result - ); - assert_eq!( - r5.compute_gas, r6.compute_gas, - "SSTORE halt: compute_gas must be identical; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); - assert_eq!( - r5.gas_used, r6.gas_used, - "SSTORE halt: gas_used must be identical; REX5={} REX6={}", - r5.gas_used, r6.gas_used - ); -} - -#[test] -fn test_callcode_value_transfer_metering_parity_rex5_rex6() { - // CALLCODE with value transfer goes through the same `new_account_storage_gas` charge path as - // CALL (via `storage_gas_ext::call_code`). Stack pops gas, to, value, aoff, asz, roff, rsz - // (gas on top). - let code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(1u64) // value - .push_address(EMPTY_TARGET) // to - .push_number(1_000_000u64) // gas - .append(CALLCODE) - .stop() - .build(); - assert_rex5_rex6_parity("CALLCODE", true, || base_db(code.clone())); -} diff --git a/crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs b/crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs deleted file mode 100644 index e156f860f..000000000 --- a/crates/mega-evm/tests/rex6/self_transfer_account_dedup.rs +++ /dev/null @@ -1,391 +0,0 @@ -//! REX6 value self-transfer account-info dedup for `DataSize` / KV. -//! -//! A value transfer whose target equals the caller touches a single account. The caller-side -//! account-info write (or, at the top level, the `before_tx_start` caller record) already accounts -//! for it, so the target-side write would double-count the same account on the block -//! `DataSize` / KV-update limiter lanes. Under REX6 the redundant target-side write is suppressed -//! when `target == caller`; non-self transfers (`A -> B`) and zero-value calls are unchanged, and -//! pre-REX6 specs keep the frozen double-count. -//! -//! The tests measure the *value-transfer-induced delta* (a `value > 0` run minus an otherwise -//! identical `value == 0` run). That delta isolates exactly the target-side account-info write: -//! -//! - `A -> B`, `value=1`: target write records B → delta = one account-info write on every spec. -//! - `A -> A`, `value=1` (REX6): target write suppressed → delta = 0. -//! - `A -> A`, `value=1` (REX5): target write recorded → delta = one account-info write (frozen). - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EmptyExternalEnv, LimitUsage, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - ACCOUNT_INFO_WRITE_SIZE, -}; -use revm::{ - bytecode::opcode::*, - context::{BlockEnv, ContextSetters, TxEnv}, - handler::EvmTr, - primitives::TxKind, -}; - -/// EOA sender / self-transfer target. -const A: Address = address!("00000000000000000000000000000000A0000001"); -/// Distinct non-self transfer target. -const B: Address = address!("00000000000000000000000000000000B0000002"); -/// A pure-EOA sender used for the nested cases, so the tx caller has no code (EIP-3607). -const EOA: Address = address!("00000000000000000000000000000000E0A00003"); -/// A self-calling contract used in the nested cases (its frame CALLs itself with value). -const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); -/// Pre-funded coinbase so beneficiary materialisation never adds noise. -const COINBASE: Address = address!("00000000000000000000000000000000C0FFEE01"); - -const TX_GAS_LIMIT: u64 = 1_000_000; -const A_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH - -type TestEvm = MegaEvm; - -/// Builds a fee-free EVM (`gas_price` = basefee = 0, operator fees zeroed, coinbase pre-funded) so -/// the post-execution fee-reward writes never perturb the `DataSize` / KV measurement. -fn build_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { - let mut context = MegaContext::new(db, spec); - context.set_block(BlockEnv { - gas_limit: 1_000_000_000, - basefee: 0, - beneficiary: COINBASE, - ..Default::default() - }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -fn base_db() -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(A, U256::from(A_BALANCE)) - .account_balance(EOA, U256::from(A_BALANCE)) - .account_balance(COINBASE, U256::from(1u64)) -} - -/// A top-level call `A -> to` with the given `value`. -fn call_tx(to: Address, value: u128) -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: A, - kind: TxKind::Call(to), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - value: U256::from(value), - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Runs `tx` under `spec` against a fresh `db`, asserts success, and returns the limiter usage. -fn usage_of(spec: MegaSpecId, db: MemoryDatabase, tx: MegaTransaction) -> LimitUsage { - let mut evm = build_evm(spec, db); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!( - r.expect("no validation error").result.is_success(), - "tx must succeed for a clean usage reading", - ); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage -} - -/// Returns `(data_size_delta, kv_delta)` between a `value=1` and a `value=0` top-level call to -/// `to`. The delta isolates the target-side account-info write. -fn value_transfer_delta(spec: MegaSpecId, to: Address) -> (u64, u64) { - let with_value = usage_of(spec, base_db(), call_tx(to, 1)); - let zero_value = usage_of(spec, base_db(), call_tx(to, 0)); - ( - with_value.data_size.saturating_sub(zero_value.data_size), - with_value.kv_updates.saturating_sub(zero_value.kv_updates), - ) -} - -// ============================================================================ -// Top-level self-transfer: A -> A -// ============================================================================ - -/// REX6: a top-level `A -> A` value transfer adds NO extra account-info write — A is already -/// recorded by `before_tx_start`, so the target-side write is suppressed. -#[test] -fn test_rex6_top_level_self_transfer_no_double_count() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX6, A); - assert_eq!( - data_delta, 0, - "REX6 A->A value transfer must not add a duplicate account-info write (data_size)", - ); - assert_eq!( - kv_delta, 0, - "REX6 A->A value transfer must not add a duplicate account-info write (kv_updates)", - ); -} - -/// REX5 baseline: the same top-level `A -> A` transfer still double-counts (frozen). -#[test] -fn test_rex5_top_level_self_transfer_still_double_counts() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX5, A); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX5 A->A value transfer keeps the frozen duplicate account-info write (data_size)", - ); - assert_eq!( - kv_delta, 1, - "REX5 A->A value transfer keeps the frozen duplicate account-info write (kv_updates)", - ); -} - -// ============================================================================ -// Non-self transfer: A -> B (unchanged on every spec) -// ============================================================================ - -#[test] -fn test_rex6_non_self_transfer_counts_target() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX6, B); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX6 A->B value transfer must record the target write (data_size)", - ); - assert_eq!(kv_delta, 1, "REX6 A->B value transfer must record the target write (kv_updates)"); -} - -#[test] -fn test_rex5_non_self_transfer_counts_target() { - let (data_delta, kv_delta) = value_transfer_delta(MegaSpecId::REX5, B); - assert_eq!( - data_delta, ACCOUNT_INFO_WRITE_SIZE, - "REX5 A->B value transfer must record the target write (data_size)", - ); - assert_eq!(kv_delta, 1, "REX5 A->B value transfer must record the target write (kv_updates)"); -} - -// ============================================================================ -// Nested self-call with value: A's code CALLs A with value -// ============================================================================ - -/// A contract at `SELF_CALLER` that self-calls **exactly once** with `value` wei. -/// -/// To bound the recursion the contract branches on `CALLDATASIZE`: the outer invocation (reached -/// from the EOA tx with 1 byte of calldata) takes the self-call branch and CALLs itself with an -/// EMPTY args buffer (`argsSize = 0`); the inner invocation therefore sees `CALLDATASIZE == 0` and -/// STOPs immediately. The result is a single `caller == target == SELF_CALLER` value frame. -fn self_calling_code(value: u64) -> Bytes { - // Layout (byte offsets matter for the JUMPDEST target): - // CALLDATASIZE ; cond - // PUSH1 ; dest - // JUMPI ; if calldatasize != 0 -> self-call branch - // STOP ; inner invocation (calldatasize == 0) returns here - // JUMPDEST ; <- self-call branch - // - // POP STOP - // - // Prefix bytes: CALLDATASIZE(1) PUSH1(2) JUMPI(1) STOP(1) = 5 bytes, so the JUMPDEST is at - // offset 5. - const JUMPDEST_OFFSET: u8 = 5; - BytecodeBuilder::default() - .append(CALLDATASIZE) - .push_number(JUMPDEST_OFFSET) // u8 -> single-byte PUSH1 - .append(JUMPI) - .append(STOP) - .append(JUMPDEST) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize (empty -> inner invocation sees CALLDATASIZE == 0) - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(SELF_CALLER) // target == self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .stop() - .build() -} - -/// A top-level no-value call `EOA -> SELF_CALLER` carrying 1 byte of calldata (so the outer -/// invocation takes the self-call branch). -fn nested_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: EOA, - kind: TxKind::Call(SELF_CALLER), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - value: U256::ZERO, - data: Bytes::from_static(&[0x01]), - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Reads `(data_size, kv_updates)` for a top-level no-value `EOA -> SELF_CALLER` call where the -/// contract frame CALLs itself once with `inner_value` wei. `SELF_CALLER` is pre-funded so the -/// inner value transfer always succeeds. -fn nested_usage(spec: MegaSpecId, inner_value: u64) -> (u64, u64) { - let db = base_db() - .account_balance(SELF_CALLER, U256::from(A_BALANCE)) - .account_code(SELF_CALLER, self_calling_code(inner_value)); - let u = usage_of(spec, db, nested_tx()); - (u.data_size, u.kv_updates) -} - -/// REX6: a nested `A -> A` value call records A only once — the caller-side write covers it, the -/// target-side write is suppressed. The delta over an inner `value=0` self-call is therefore one -/// account-info write (the caller-side write), not two. -#[test] -fn test_rex6_nested_self_call_with_value_counts_once() { - let (data_value, kv_value) = nested_usage(MegaSpecId::REX6, 1); - let (data_zero, kv_zero) = nested_usage(MegaSpecId::REX6, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - ACCOUNT_INFO_WRITE_SIZE, - "REX6 nested A->A value call must add exactly one account-info write (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 1, - "REX6 nested A->A value call must add exactly one account-info write (kv_updates)", - ); -} - -/// REX5 baseline: the nested `A -> A` value call double-counts A — the delta over an inner -/// `value=0` self-call is two account-info writes (caller + target), frozen. -#[test] -fn test_rex5_nested_self_call_with_value_double_counts() { - let (data_value, kv_value) = nested_usage(MegaSpecId::REX5, 1); - let (data_zero, kv_zero) = nested_usage(MegaSpecId::REX5, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 2 * ACCOUNT_INFO_WRITE_SIZE, - "REX5 nested A->A value call double-counts (caller + target) in data_size", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 2, - "REX5 nested A->A value call double-counts (caller + target) in kv_updates", - ); -} - -// ============================================================================ -// Nested self-call where the parent frame already did a value transfer -// (`parent_needs_update == false` arm of the dedup predicate) -// ============================================================================ - -/// A contract at `SELF_CALLER` that, on its outer invocation, first CALLs `B` with `value` wei and -/// then CALLs **itself** with `value` wei. The first value-transferring call sets the frame's -/// `target_updated` flag, so the second (self) call has `parent_needs_update == false` — the -/// caller-side write is already skipped there, and the dedup predicate (`target == caller`) is what -/// suppresses the redundant target-side write under REX6. Recursion is bounded the same way as -/// [`self_calling_code`]: the self-call passes `argsSize = 0`, so the inner invocation sees -/// `CALLDATASIZE == 0` and STOPs. -fn self_calling_code_two(value: u64) -> Bytes { - const JUMPDEST_OFFSET: u8 = 5; - let mut b = BytecodeBuilder::default() - .append(CALLDATASIZE) - .push_number(JUMPDEST_OFFSET) - .append(JUMPI) - .append(STOP) - .append(JUMPDEST); - // CALL #1: SELF_CALLER -> B (distinct target), value. Sets `target_updated` on this frame. - b = b - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(B) // target != self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP); - // CALL #2: SELF_CALLER -> SELF_CALLER (self), value. `parent_needs_update == false` here. - b.push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize (empty -> inner invocation STOPs) - .push_number(0_u64) // argsOffset - .push_number(value) // value - .push_address(SELF_CALLER) // target == self - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .stop() - .build() -} - -/// `(data_size, kv_updates)` for `EOA -> SELF_CALLER` where the contract frame CALLs `B` then -/// itself, each with `inner_value` wei. -fn nested_two_call_usage(spec: MegaSpecId, inner_value: u64) -> (u64, u64) { - let db = base_db() - .account_balance(SELF_CALLER, U256::from(A_BALANCE)) - .account_code(SELF_CALLER, self_calling_code_two(inner_value)); - let u = usage_of(spec, db, nested_tx()); - (u.data_size, u.kv_updates) -} - -/// REX6: the `parent_needs_update == false` self-transfer is still deduped. The value-transfer -/// delta is two account-info writes — `SELF_CALLER` (the first call's caller write) and `B` (its -/// target) — and the second, self-targeted call adds nothing. Crucially this is not an under-count: -/// the frame account is still recorded exactly once. -#[test] -fn test_rex6_nested_pnu_false_self_transfer_counts_once() { - let (data_value, kv_value) = nested_two_call_usage(MegaSpecId::REX6, 1); - let (data_zero, kv_zero) = nested_two_call_usage(MegaSpecId::REX6, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 2 * ACCOUNT_INFO_WRITE_SIZE, - "REX6 must record SELF_CALLER and B once each; the self-targeted second call adds nothing \ - (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 2, - "REX6 must record SELF_CALLER and B once each; the self-targeted second call adds nothing \ - (kv_updates)", - ); -} - -/// REX5 baseline: the self-targeted second call still records `SELF_CALLER` a second time (frozen), -/// so the delta is three account-info writes. -#[test] -fn test_rex5_nested_pnu_false_self_transfer_double_counts() { - let (data_value, kv_value) = nested_two_call_usage(MegaSpecId::REX5, 1); - let (data_zero, kv_zero) = nested_two_call_usage(MegaSpecId::REX5, 0); - assert_eq!( - data_value.saturating_sub(data_zero), - 3 * ACCOUNT_INFO_WRITE_SIZE, - "REX5 keeps the frozen duplicate SELF_CALLER target write (data_size)", - ); - assert_eq!( - kv_value.saturating_sub(kv_zero), - 3, - "REX5 keeps the frozen duplicate SELF_CALLER target write (kv_updates)", - ); -} - -// ============================================================================ -// Zero-value call records no account-info write (unchanged) -// ============================================================================ - -/// A zero-value top-level call records no target-side account-info write on either spec, so the -/// `value=1` vs `value=0` comparison is the only thing that moves — already asserted above. This -/// test pins that REX6 and REX5 agree on the zero-value absolute usage (no behaviour change for the -/// non-transfer path). -#[test] -fn test_zero_value_call_unchanged_across_specs() { - let rex6 = usage_of(MegaSpecId::REX6, base_db(), call_tx(B, 0)); - let rex5 = usage_of(MegaSpecId::REX5, base_db(), call_tx(B, 0)); - assert_eq!( - rex6.data_size, rex5.data_size, - "zero-value A->B call data_size must be identical across specs", - ); - assert_eq!( - rex6.kv_updates, rex5.kv_updates, - "zero-value A->B call kv_updates must be identical across specs", - ); -} diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs new file mode 100644 index 000000000..c94d91fbc --- /dev/null +++ b/crates/mega-evm/tests/satin/common.rs @@ -0,0 +1,59 @@ +//! Shared setup of the Satin tests. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{op_transaction, zero_fee_l1_block_info}, + LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, +}; +use revm::{ + context::{result::ResultAndState, BlockEnv, TxEnv}, + Database, +}; + +/// A block with room for any transaction the tests run. +pub(crate) fn block() -> BlockEnv { + BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, ..Default::default() } +} + +/// A Satin context over `db` with zero L1 fees. +pub(crate) fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +/// A call from `caller` to `to` with zero gas price. +pub(crate) fn call(caller: Address, to: Address, value: U256, gas_limit: u64) -> MegaTransaction { + tx(caller, TxKind::Call(to), Bytes::new(), value, gas_limit) +} + +/// A call from `caller` to `to` carrying `data`. +pub(crate) fn call_with_data( + caller: Address, + to: Address, + data: Bytes, + gas_limit: u64, +) -> MegaTransaction { + tx(caller, TxKind::Call(to), data, U256::ZERO, gas_limit) +} + +/// A creation from `caller` running `init_code`. +pub(crate) fn create(caller: Address, init_code: Bytes, gas_limit: u64) -> MegaTransaction { + tx(caller, TxKind::Create, init_code, U256::ZERO, gas_limit) +} + +fn tx(caller: Address, kind: TxKind, data: Bytes, value: U256, gas_limit: u64) -> MegaTransaction { + OpTx(op_transaction(TxEnv { caller, kind, data, value, gas_limit, ..Default::default() })) +} + +/// Runs `tx` on a fresh Satin EVM over `db` and returns its result and what the common execution +/// layer counted. +pub(crate) fn run( + db: DB, + tx: MegaTransaction, +) -> (ResultAndState, LimitUsage) { + let mut evm = MegaEvm::new(context(db)); + let result = evm.transact_raw(tx).expect("the transaction is valid"); + let usage = evm.ctx().additional_limit().usage(); + (result, usage) +} diff --git a/crates/mega-evm/tests/satin/db_error.rs b/crates/mega-evm/tests/satin/db_error.rs new file mode 100644 index 000000000..319dd3463 --- /dev/null +++ b/crates/mega-evm/tests/satin/db_error.rs @@ -0,0 +1,101 @@ +//! A database error during execution fails the transaction with that error; it is never a halt +//! the transaction is included with. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CALL, STATICCALL}, + context::result::EVMError, +}; + +use crate::common::{call, context, create}; + +const CALLER: Address = address!("2000000000000000000000000000000000000002"); +const CALLEE: Address = address!("1000000000000000000000000000000000000001"); +const TARGET: Address = address!("3000000000000000000000000000000000000003"); + +fn transact( + db: ErrorInjectingDatabase, + tx: MegaTransaction, +) -> Result< + revm::context::result::ResultAndState, + EVMError, +> { + MegaEvm::new(context(db)).transact_raw(tx) +} + +fn assert_db_error( + result: Result>, + expected: &str, +) { + match result { + Err(EVMError::Database(error)) => { + assert!(format!("{error}").contains(expected), "got: {error}"); + } + other => panic!("expected a database error, got: {other:?}"), + } +} + +fn funded(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(100_000_000_000u64)) + .account_code(CALLEE, code) +} + +/// A failing storage read in `SSTORE` surfaces as the database error. +#[test] +fn test_sstore_storage_read_error_fails_the_transaction() { + let key = U256::from(0x42); + let code = BytecodeBuilder::default().sstore(key, U256::from(1)).stop().build(); + let mut db = ErrorInjectingDatabase::new(funded(code)); + db.fail_on_storage = Some((CALLEE, key)); + assert_db_error( + transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), + "injected storage()", + ); +} + +fn call_target(opcode: u8) -> Bytes { + let code = BytecodeBuilder::default() + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64); + let code = if opcode == CALL { code.push_number(1_u64) } else { code }; + code.push_address(TARGET).push_number(100_000_u64).append(opcode).stop().build() +} + +/// A failing account read of a value transfer's recipient surfaces as the database error. +#[test] +fn test_value_call_account_read_error_fails_the_transaction() { + let mut db = ErrorInjectingDatabase::new(funded(call_target(CALL))); + db.fail_on_account = Some(TARGET); + assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); +} + +/// A creation that writes storage never reads the created account's storage from the database: +/// it is empty, and a stateless witness has nothing for it. +#[test] +fn test_created_account_storage_is_never_read_from_the_database() { + let init_code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(0x42)).stop().build(); + let created = CALLER.create(0); + let inner = MemoryDatabase::default() + .account_balance(CALLER, U256::from(100_000_000_000u64)) + .account_balance(created, U256::from(1)); + let mut db = ErrorInjectingDatabase::new(inner); + db.fail_on_storage = Some((created, U256::ZERO)); + let result = transact(db, create(CALLER, init_code, 10_000_000)).expect("no database read"); + assert!(result.result.is_success(), "{:?}", result.result); +} + +/// A failing account read of a `STATICCALL` target surfaces as the database error. +#[test] +fn test_staticcall_account_read_error_fails_the_transaction() { + let mut db = ErrorInjectingDatabase::new(funded(call_target(STATICCALL))); + db.fail_on_account = Some(TARGET); + assert_db_error(transact(db, call(CALLER, CALLEE, U256::ZERO, 1_000_000)), "injected basic()"); +} diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs new file mode 100644 index 000000000..8817fca82 --- /dev/null +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -0,0 +1,264 @@ +//! `MegaEvm` on Satin adds nothing to op-revm yet. +//! +//! The same transaction on the same `CfgEnv`, block and L1 info must produce the same result +//! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and +//! the resulting state. Once later changes add `MegaETH` behavior (SALT pricing, history gas, +//! limits), these cases stay the baseline that shows where the two diverge on purpose. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, TxKind, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, +}; +use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use revm::{ + context::{ + result::{ExecResultAndState, ExecutionResult}, + BlockEnv, CfgEnv, Context, ContextTr, TxEnv, + }, + context_interface::cfg::GasParams, + inspector::NoOpInspector, + primitives::hardfork::SpecId, + state::EvmState, + ExecuteEvm, Journal, +}; + +const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); +const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); + +type Outcome = ExecResultAndState, EvmState>; +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +fn block() -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1_800_000_000u64), + gas_limit: 10_000_000_000, + ..Default::default() + } +} + +/// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the +/// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes and that `CfgEnv`. +fn run_both(db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, CfgEnv) { + run_both_in(db, tx, block()) +} + +/// [`run_both`] in `block`. +fn run_both_in( + db: MemoryDatabase, + tx: TxEnv, + block: BlockEnv, +) -> (Outcome, Outcome, CfgEnv) { + let (mut mega, mut op, cfg) = both_evms(db, block); + let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap(); + let op_outcome = op.transact(op_transaction(tx)).unwrap(); + (mega_outcome, op_outcome, cfg) +} + +/// A `MegaEvm` and an `OpEvm` over `db` in `block`, on the same `CfgEnv`. +fn both_evms( + db: MemoryDatabase, + block: BlockEnv, +) -> (MegaEvm, OpEvm, CfgEnv) { + let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) + .with_block(block.clone()) + .with_chain(zero_fee_l1_block_info()); + let cfg = ctx.cfg().clone(); + let op_ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_block(block) + .with_chain(zero_fee_l1_block_info()); + (MegaEvm::new(ctx), OpEvm::new(op_ctx, NoOpInspector), cfg) +} + +/// Asserts the two outcomes agree field by field, then as a whole so a field added later is +/// covered too. +fn assert_same(mega: &Outcome, op: &Outcome) { + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); + assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); + assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); + assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); + assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); + assert_eq!(m, o, "ResultGas"); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result, op.result, "execution result"); + assert_eq!(mega.state, op.state, "state"); +} + +/// Both engines run on the Satin configuration: Karst on the Osaka gas table, EIP-8037 and +/// EIP-2780 switched on, the 200M execution cap, EIP-7708 and the system-call reservoir margin +/// off. +fn assert_satin_cfg(cfg: &CfgEnv) { + assert_eq!(cfg.spec, OpSpecId::KARST); + assert_eq!(cfg.gas_params.table(), GasParams::new_spec(SpecId::OSAKA).table()); + assert!(cfg.enable_amsterdam_eip8037); + assert!(cfg.enable_amsterdam_eip2780); + assert_eq!(cfg.tx_gas_limit_cap, Some(200_000_000)); + assert!(!cfg.enable_amsterdam_eip7708); + assert!(!cfg.system_call_state_gas_margin_in_reservoir); +} + +#[test] +fn test_empty_transaction_matches_op_revm() { + // The gas limit exceeds the execution cap, so the rest goes to the EIP-8037 reservoir; an + // empty call draws no state gas, so all of it is left over. + let reservoir = 1_000_000; + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: TX_GAS_LIMIT_CAP + reservoir, + ..Default::default() + }; + let (mega, op, cfg) = run_both(MemoryDatabase::default(), tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.result.gas().reservoir_remaining(), reservoir); + assert_same(&mega, &op); +} + +#[test] +fn test_value_transfer_matches_op_revm() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value: U256::from(1_000), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.state[&CALLEE].info.balance, U256::from(1_000)); + assert_same(&mega, &op); +} + +#[test] +fn test_sstore_matches_op_revm() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success()); + assert_eq!(mega.state[&CALLEE].storage[&U256::ZERO].present_value, U256::from(42)); + // The Osaka gas table has no state-gas prices, so the new slot draws no state gas even with + // EIP-8037 on. The Satin gas table prices it; this assertion changes with it. + assert_eq!(mega.result.gas().state_gas_spent_final(), 0); + assert_same(&mega, &op); +} + +const COINBASE: Address = address!("0x00000000000000000000000000000000000c0ffe"); + +/// A priced transaction pays its fee, gets its unused gas back and rewards the beneficiary and +/// the fee vaults exactly as op-revm has it. +#[test] +fn test_fees_match_op_revm() { + let db = + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))).account_code( + CALLEE, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + let block = BlockEnv { basefee: 7, beneficiary: COINBASE, ..block() }; + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value: U256::from(1_000), + gas_price: 10, + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, _) = run_both_in(db, tx, block); + assert!(mega.result.is_success()); + assert!(mega.state[&COINBASE].info.balance > U256::ZERO, "the beneficiary was paid"); + assert!( + mega.state[&CALLER].info.balance > U256::from(10u64.pow(18) - 10 * 1_000_000 - 1_000), + "the unused gas came back" + ); + assert_same(&mega, &op); +} + +/// A storage refund is applied exactly as op-revm has it. +#[test] +fn test_refund_matches_op_revm() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code).account_storage( + CALLEE, + U256::ZERO, + U256::from(5), + ); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mega, op, _) = run_both(db, tx); + assert!(mega.result.is_success()); + assert!(mega.result.gas().inner_refunded() > 0, "the clear is refunded"); + assert_same(&mega, &op); +} + +/// A system call runs exactly as op-revm runs it. +#[test] +fn test_system_call_matches_op_revm() { + use revm::handler::system_call::SystemCallEvm; + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(3)).stop().build(); + let (mut mega, mut op, _) = + both_evms(MemoryDatabase::default().account_code(CALLEE, code), block()); + let mega_outcome = mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let op_outcome = op.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + assert!(mega_outcome.result.is_success()); + assert_same(&mega_outcome, &op_outcome); +} + +/// A transaction op-revm rejects, Satin rejects with the same error. +#[test] +fn test_invalid_transaction_matches_op_revm() { + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let (mut mega, mut op, _) = both_evms(MemoryDatabase::default(), block()); + let unenveloped = OpTransaction { base: tx, enveloped_tx: None, ..Default::default() }; + let mega_error = mega.transact(OpTx(unenveloped.clone())).unwrap_err(); + let op_error = op.transact(unenveloped).unwrap_err(); + assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); + assert!(format!("{mega_error:?}").contains("MissingEnvelopedTx"), "{mega_error:?}"); + + // A gas limit above the block's is rejected before anything is charged. + let small_block = BlockEnv { gas_limit: 500_000, ..block() }; + let (mut mega, mut op, _) = both_evms(MemoryDatabase::default(), small_block); + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }; + let mega_error = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap_err(); + let op_error = op.transact(op_transaction(tx)).unwrap_err(); + assert_eq!(format!("{mega_error:?}"), format!("{op_error:?}")); + assert!(format!("{mega_error:?}").contains("CallerGasLimitMoreThanBlock"), "{mega_error:?}"); +} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs new file mode 100644 index 000000000..b80a5ad8c --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -0,0 +1,553 @@ +//! Inspectors on Satin: what a rewriting inspector gets, the one rewrite refused, and the +//! admission gate block execution keys on. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, Log, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, + DeclaredObserver, MegaContext, MegaEvm, FORBIDDEN_CREATE_REVIVAL, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, + context::result::EVMError, + inspector::NoOpInspector, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, + }, + Database, Inspector, +}; +use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000400000"); +const A: Address = address!("00000000000000000000000000000000000000A1"); +const B: Address = address!("00000000000000000000000000000000000000B1"); +const FAKE: Address = address!("00000000000000000000000000000000000FA4E0"); +const GAS_LIMIT: u64 = 1_000_000; + +/// Calls `B` with `value` and stores the call's success flag in slot 0. +fn call_b_and_store_flag(value: u64) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(B) + .append(GAS) + .append(CALL) + .append(PUSH0) + .append(SSTORE) + .stop() + .build() +} + +/// Creates a contract from `init_code` (at most 32 bytes) and stores the address in slot 0. +fn create_and_store_address(init_code: &[u8]) -> Bytes { + let mut word = [0u8; 32]; + word[..init_code.len()].copy_from_slice(init_code); + BytecodeBuilder::default() + .mstore(0, word) + .push_number(init_code.len() as u64) + .append_many([PUSH0, PUSH0]) + .append(CREATE) + .append(PUSH0) + .append(SSTORE) + .stop() + .build() +} + +/// Rewrites what execution produces, one way per field. +#[derive(Default)] +struct Rewriter { + opcode: u8, + /// Gas charged after every `SSTORE`. + charge_after_sstore: u64, + /// Gas handed back after every `SSTORE`. + erase_after_sstore: u64, + /// Turns every call result into a success. + call_succeeds: bool, + /// Answers every call to `B` itself with a success. + answer_calls: bool, + /// Replaces every created address. + created_address: Option
, + /// Turns every creation result into a success. + create_succeeds: bool, +} + +impl Inspector, EthInterpreter> for Rewriter { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.opcode == SSTORE { + assert!(interp.gas.record_regular_cost(self.charge_after_sstore)); + interp.gas.erase_cost(self.erase_after_sstore); + } + } + + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + (self.answer_calls && inputs.target_address == B).then(|| { + CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if self.call_succeeds { + outcome.result.result = InstructionResult::Stop; + } + } + + fn create_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + if let Some(address) = self.created_address { + outcome.address = Some(address); + } + if self.create_succeeds { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(FAKE); + } + } +} + +fn run_with, EthInterpreter>>( + db: MemoryDatabase, + inspector: INSP, + value: u64, +) -> Result< + revm::context::result::ResultAndState, + EVMError, +> { + let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)) +} + +fn writes_two_slots() -> MemoryDatabase { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + MemoryDatabase::default().account_code(A, code) +} + +/// Gas an inspector charges or hands back in `step_end` lands on the receipt, exactly. +#[test] +fn test_step_end_charge_and_refund_land_on_the_receipt() { + let gas_used = |rewriter: Rewriter| { + let result = run_with(writes_two_slots(), rewriter, 0).unwrap(); + assert!(result.result.is_success()); + result.result.gas().tx_gas_used() + }; + let baseline = gas_used(Rewriter::default()); + assert_eq!( + gas_used(Rewriter { charge_after_sstore: 1_000, ..Default::default() }), + baseline + 2_000 + ); + assert_eq!( + gas_used(Rewriter { erase_after_sstore: 500, ..Default::default() }), + baseline - 1_000 + ); +} + +/// A call result rewritten in `call_end` is what the caller sees. +#[test] +fn test_call_end_rewrite_reaches_the_caller() { + let db = || { + MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + }; + let flag = |rewriter| { + run_with(db(), rewriter, 0).unwrap().state[&A].storage[&U256::ZERO].present_value() + }; + assert_eq!(flag(Rewriter::default()), U256::ZERO, "B reverts"); + assert_eq!(flag(Rewriter { call_succeeds: true, ..Default::default() }), U256::from(1)); +} + +/// A value call the inspector answers itself moves no value, and counts no write. +#[test] +fn test_short_circuited_value_call_moves_no_value() { + let db = MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(5)) + .account_balance(A, U256::from(100)); + let mut evm = MegaEvm::new(context(db)) + .with_inspector(Rewriter { answer_calls: true, ..Default::default() }); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(result.result.is_success()); + assert_eq!( + result.state[&A].storage[&U256::ZERO].present_value(), + U256::from(1), + "the answer is a success" + ); + assert_eq!(result.state[&A].info.balance, U256::from(100), "no value left A"); + assert!(result.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value reached B"); + assert_eq!(evm.ctx().additional_limit().usage().write_records, 1, "only A's slot 0"); +} + +/// An address rewritten in `create_end` is what the caller sees, but the code is where the +/// creation put it. +#[test] +fn test_create_end_address_rewrite_reaches_the_caller_not_the_code() { + // Init code returning one byte of runtime code (0x00). + let init_code = [0x60, 0x01, 0x60, 0x00, 0xf3]; + let db = MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); + let result = + run_with(db, Rewriter { created_address: Some(FAKE), ..Default::default() }, 0).unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + let stored = result.state[&A].storage[&U256::ZERO].present_value(); + assert_eq!(Address::from_word(stored.into()), FAKE, "the caller got the rewritten address"); + let created = A.create(0); + assert!(result.state[&created].info.code.as_ref().is_some_and(|code| !code.is_empty())); + assert!(result.state.get(&FAKE).is_none_or(|fake| fake.info.is_empty_code_hash())); +} + +/// A failed creation rewritten into a success is refused: the transaction fails with the +/// refusal. +#[test] +fn test_create_revival_is_refused() { + let db = MemoryDatabase::default() + .account_code(A, create_and_store_address(&[PUSH0, PUSH0, REVERT])); + let result = run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0); + match result { + Err(EVMError::Custom(message)) => { + assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") + } + other => panic!("expected the refusal, got {other:?}"), + } + + // A creation that succeeded may be rewritten freely; the refusal is for revivals only. + let db = MemoryDatabase::default() + .account_code(A, create_and_store_address(&[0x60, 0x01, 0x60, 0x00, 0xf3])); + assert!(run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0) + .unwrap() + .result + .is_success()); +} + +/// A declared observer that writes back fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer wrote to the interpreter in `step_end`")] +fn test_false_declaration_fails_in_debug() { + let rewriter = Rewriter { charge_after_sstore: 1, ..Default::default() }; + let mut evm = MegaEvm::new(context(writes_two_slots())) + .with_trusted_inspector(DeclaredObserver(rewriter)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared call rewrite fails too. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a call result")] +fn test_false_declaration_of_a_call_rewrite_fails_in_debug() { + let db = MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[INVALID])); + let rewriter = Rewriter { call_succeeds: true, ..Default::default() }; + let mut evm = MegaEvm::new(context(db)).with_trusted_inspector(DeclaredObserver(rewriter)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared observer that only reads produces the transaction no inspector produces. +#[test] +fn test_declared_tracer_changes_nothing() { + let db = || { + MemoryDatabase::default() + .account_code(A, call_b_and_store_flag(0)) + .account_code(B, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + }; + let plain = + MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); + let mut evm = MegaEvm::new(context(db())).with_trusted_inspector(DeclaredObserver(tracer)); + let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_eq!(plain.result, traced.result); + assert_eq!(plain.state, traced.state); + assert_eq!(evm.inspector().0.traces().nodes().len(), 2, "the tracer saw both frames"); +} + +/// The admission gate: only an enabled inspector that did not arrive declared is a rewriting one. +#[test] +fn test_has_rewriting_inspector_truth_table() { + let evm = || MegaEvm::new(context(MemoryDatabase::default())); + assert!(!evm().has_rewriting_inspector(), "no inspector"); + assert!(evm().with_inspector(NoOpInspector).has_rewriting_inspector(), "a tool's inspector"); + assert!( + evm().with_inspector(GasInspector::new()).has_rewriting_inspector(), + "test utilities are tools" + ); + assert!(!evm().with_trusted_inspector(NoOpInspector).has_rewriting_inspector()); + let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); + assert!(!evm().with_trusted_inspector(DeclaredObserver(tracer)).has_rewriting_inspector()); + + let mut disabled = evm().with_inspector(Rewriter::default()); + disabled.set_inspector_enabled(false); + assert!(!disabled.has_rewriting_inspector(), "a disabled inspector does not run"); + disabled.set_inspector_enabled(true); + assert!(disabled.has_rewriting_inspector()); +} + +/// Counts frame starts and ends. +#[derive(Default)] +struct Pairs { + calls: usize, + call_ends: usize, + creates: usize, + create_ends: usize, +} + +impl Inspector for Pairs { + fn call(&mut self, _context: &mut CTX, _inputs: &mut CallInputs) -> Option { + self.calls += 1; + None + } + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.call_ends += 1; + } + fn create(&mut self, _context: &mut CTX, _inputs: &mut CreateInputs) -> Option { + self.creates += 1; + None + } + fn create_end( + &mut self, + _context: &mut CTX, + _inputs: &CreateInputs, + _outcome: &mut CreateOutcome, + ) { + self.create_ends += 1; + } +} + +/// Every frame the inspector sees start, it sees end: a frame that ran, one answered before it +/// ran (a value transfer the sender cannot fund, a latched transaction's first frame), and a +/// creation. +#[test] +fn test_frame_start_and_end_stay_paired() { + let pairs = |db: MemoryDatabase, limits: mega_evm::EvmTxRuntimeLimits, value: u64| { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Pairs::default()); + let _ = evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)).unwrap(); + let pairs = evm.inspector(); + (pairs.calls, pairs.call_ends, pairs.creates, pairs.create_ends) + }; + let no_limits = mega_evm::EvmTxRuntimeLimits::no_limits(); + let unfunded = MemoryDatabase::default().account_code(A, call_b_and_store_flag(5)); + assert_eq!(pairs(unfunded, no_limits, 0), (2, 2, 0, 0)); + let creates = MemoryDatabase::default().account_code(A, create_and_store_address(&[0x00])); + assert_eq!(pairs(creates, no_limits, 0), (1, 1, 1, 1)); + let funded = MemoryDatabase::default().account_balance(CALLER, U256::from(10)); + let latched = no_limits.with_tx_data_size_limit(0); + assert_eq!(pairs(funded, latched, 1), (1, 1, 0, 0), "the stopped first frame ends too"); +} + +/// Counts every callback it gets. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Recorder { + initialize_interp: usize, + step: usize, + step_end: usize, + log_full: usize, + frame_start: usize, + frame_end: usize, + call: usize, + call_end: usize, + create: usize, + create_end: usize, + selfdestruct: usize, +} + +impl Inspector, EthInterpreter> for Recorder { + fn initialize_interp(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.initialize_interp += 1; + } + fn step(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.step += 1; + } + fn step_end(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.step_end += 1; + } + fn log_full(&mut self, _: &mut Interpreter, _: &mut MegaContext, _: Log) { + self.log_full += 1; + } + fn frame_start( + &mut self, + _: &mut MegaContext, + _: &mut revm::interpreter::FrameInput, + ) -> Option { + self.frame_start += 1; + None + } + fn frame_end( + &mut self, + _: &mut MegaContext, + _: &revm::interpreter::FrameInput, + _: &mut revm::handler::FrameResult, + ) { + self.frame_end += 1; + } + fn call(&mut self, _: &mut MegaContext, _: &mut CallInputs) -> Option { + self.call += 1; + None + } + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, _: &mut CallOutcome) { + self.call_end += 1; + } + fn create(&mut self, _: &mut MegaContext, _: &mut CreateInputs) -> Option { + self.create += 1; + None + } + fn create_end(&mut self, _: &mut MegaContext, _: &CreateInputs, _: &mut CreateOutcome) { + self.create_end += 1; + } + fn selfdestruct(&mut self, _: Address, _: Address, _: U256) { + self.selfdestruct += 1; + } +} + +/// A contract that logs, creates a contract, calls `B` and self-destructs. +fn busy_contract() -> MemoryDatabase { + let init_code = [0x60, 0x01, 0x60, 0x00, 0xf3]; + let mut word = [0u8; 32]; + word[..init_code.len()].copy_from_slice(&init_code); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .append(revm::bytecode::opcode::LOG0) + .mstore(0, word) + .push_number(init_code.len() as u64) + .append_many([PUSH0, PUSH0]) + .append(CREATE) + .append(revm::bytecode::opcode::POP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append(GAS) + .append(CALL) + .append(revm::bytecode::opcode::POP) + .push_address(B) + .append(revm::bytecode::opcode::SELFDESTRUCT) + .build(); + MemoryDatabase::default().account_code(A, code).account_code(B, Bytes::from_static(&[0x00])) +} + +/// A declared observer forwards every callback to the inspector inside. +#[test] +fn test_declared_observer_forwards_every_callback() { + let mut plain = MegaEvm::new(context(busy_contract())).with_inspector(Recorder::default()); + plain.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let mut declared = MegaEvm::new(context(busy_contract())) + .with_trusted_inspector(DeclaredObserver::new(Recorder::default())); + declared.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + let seen = plain.inspector().clone(); + assert_eq!(declared.inspector().0, seen); + assert!( + seen.initialize_interp > 0 && + seen.step > 0 && + seen.step_end > 0 && + seen.log_full > 0 && + seen.frame_start > 0 && + seen.frame_end > 0 && + seen.call > 0 && + seen.call_end > 0 && + seen.create > 0 && + seen.create_end > 0 && + seen.selfdestruct > 0, + "every callback ran: {seen:?}" + ); + assert_eq!(DeclaredObserver::new(Recorder::default()).into_inner(), Recorder::default()); +} + +/// Edits a frame's inputs, writes to the journal, or rewrites a frame result, one per flag. +#[derive(Default)] +struct Writer { + edit_inputs: bool, + log_in_step: bool, + rewrite_frame_end: bool, +} + +impl Inspector, EthInterpreter> for Writer { + fn step(&mut self, _interp: &mut Interpreter, context: &mut MegaContext) { + if self.log_in_step { + let log = Log { address: A, data: Default::default() }; + revm::context::JournalTr::log(revm::context::ContextTr::journal_mut(context), log); + } + } + + fn frame_start( + &mut self, + _context: &mut MegaContext, + frame_input: &mut revm::interpreter::FrameInput, + ) -> Option { + if let (true, revm::interpreter::FrameInput::Call(inputs)) = (self.edit_inputs, frame_input) + { + inputs.gas_limit -= 1; + } + None + } + + fn frame_end( + &mut self, + _context: &mut MegaContext, + _frame_input: &revm::interpreter::FrameInput, + frame_result: &mut revm::handler::FrameResult, + ) { + if self.rewrite_frame_end { + frame_result.interpreter_result_mut().output = Bytes::from_static(b"rewritten"); + } + } +} + +fn run_declared(writer: Writer) { + let mut evm = + MegaEvm::new(context(writes_two_slots())).with_trusted_inspector(DeclaredObserver(writer)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); +} + +/// A declared observer that edits a frame's inputs fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a frame's inputs")] +fn test_false_declaration_of_an_input_edit_fails_in_debug() { + run_declared(Writer { edit_inputs: true, ..Default::default() }); +} + +/// A declared observer that writes to the journal fails its declaration in a debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer wrote to the journal in `step`")] +fn test_false_declaration_of_a_journal_write_fails_in_debug() { + run_declared(Writer { log_in_step: true, ..Default::default() }); +} + +/// A declared observer that rewrites a frame result in `frame_end` fails its declaration in a +/// debug build. +#[test] +#[cfg(debug_assertions)] +#[should_panic(expected = "a declared observer rewrote a frame result in `frame_end`")] +fn test_false_declaration_of_a_frame_end_rewrite_fails_in_debug() { + run_declared(Writer { rewrite_frame_end: true, ..Default::default() }); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs new file mode 100644 index 000000000..6974ff689 --- /dev/null +++ b/crates/mega-evm/tests/satin/main.rs @@ -0,0 +1,12 @@ +//! Tests of the Satin engine. + +mod common; +mod db_error; +mod equivalence; +mod inspector; +mod outcome; +mod state; +mod static_callee; +mod strategic_stop; +mod synthetic_frame_gas; +mod write_records; diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs new file mode 100644 index 000000000..e6a59ecd6 --- /dev/null +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -0,0 +1,119 @@ +//! The transaction outcome: the result, the gas by ledger, the usage counted and the stop. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, + MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000600000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); + +fn writer() -> MemoryDatabase { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + MemoryDatabase::default().account_code(CONTRACT, code) +} + +fn execute( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + gas_limit: u64, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, gas_limit)) + .unwrap() +} + +/// The ledgers split the raw spend, the receipt reports revm's gas used, and the reservoir the +/// sender gets back is reported. +#[test] +fn test_outcome_reports_the_ledgers() { + let outcome = execute(writer(), EvmTxRuntimeLimits::no_limits(), 1_000_000_000); + assert!(outcome.result.is_success()); + let gas = outcome.gas; + let result_gas = outcome.result.gas(); + assert_eq!(gas.regular + gas.state + gas.history, result_gas.total_gas_spent()); + assert_eq!(gas.gas_used, result_gas.tx_gas_used()); + assert_eq!(gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP); + assert_eq!(gas.history, 0, "nothing prices history bytes yet"); + assert_eq!(outcome.usage, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); + assert_eq!(outcome.limit_exceeded, None); + + let mut block = BlockGasCounters::default(); + block.record(&gas); + block.record(&gas); + assert_eq!(block.execution, 2 * gas.block_execution_gas()); + assert_eq!(block.state, 2 * gas.state); +} + +/// A stopped transaction reports the stop. +#[test] +fn test_outcome_reports_the_stop() { + let outcome = + execute(writer(), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(40), 1_000_000); + assert!(!outcome.result.is_success()); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 40, + used: 80, + frame_local: false + }) + ); + assert_eq!(outcome.usage, LimitUsage::ZERO, "the stopped transaction keeps nothing"); +} + +/// A contract reverting with `MegaLimitExceeded`'s bytes on its own is not a stop. +#[test] +fn test_spoofed_revert_data_is_not_a_stop() { + let data: Bytes = MegaLimitExceeded { kind: 0, limit: 1 }.abi_encode().into(); + let code = BytecodeBuilder::default().revert_with_data(&data).build(); + let outcome = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + EvmTxRuntimeLimits::no_limits(), + 1_000_000, + ); + assert_eq!(outcome.result.output(), Some(&data)); + assert_eq!(outcome.limit_exceeded, None); +} + +/// Counts the steps it sees. +#[derive(Default)] +struct Steps(usize); + +impl revm::Inspector for Steps { + fn step( + &mut self, + _interp: &mut revm::interpreter::Interpreter< + revm::interpreter::interpreter::EthInterpreter, + >, + _context: &mut CTX, + ) { + self.0 += 1; + } +} + +/// `execute_transaction` runs the inspector when one is enabled, and not otherwise. +#[test] +fn test_convenience_execution_methods_work() { + let mut evm = MegaEvm::new(context(writer())).with_inspector(Steps::default()); + let inspected = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + assert!(inspected.result.is_success()); + let steps = evm.inspector().0; + assert!(steps > 0, "the enabled inspector ran"); + alloy_evm::Evm::set_inspector_enabled(&mut evm, false); + let executed = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + assert!(executed.result.is_success()); + assert_eq!(evm.inspector().0, steps, "the disabled inspector did not run"); + assert_eq!(inspected.gas, executed.gas); +} diff --git a/crates/mega-evm/tests/satin/state.rs b/crates/mega-evm/tests/satin/state.rs new file mode 100644 index 000000000..bec75ebc7 --- /dev/null +++ b/crates/mega-evm/tests/satin/state.rs @@ -0,0 +1,113 @@ +//! What a Satin transaction leaves in its returned state. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::test_utils::{BytecodeBuilder, MemoryDatabase}; +use revm::{ + bytecode::opcode::{CALL, GAS, INVALID, MSTORE, POP, PUSH0, RETURN, SLOAD}, + database::{AccountState, StateBuilder}, + state::Bytecode, +}; + +use crate::common::{call, run}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100001"); +const GAS_LIMIT: u64 = 1_000_000; + +/// A read of a slot that was never written still puts the slot in the returned state. +#[test] +fn test_evm_state_zero_storage() { + let db = MemoryDatabase::default().account_code(CONTRACT, Bytes::from_static(&[PUSH0, SLOAD])); + let (result, _) = run(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + let contract = &result.state[&CONTRACT]; + assert_eq!(contract.storage.len(), 1); + assert!(contract.storage.contains_key(&U256::ZERO)); +} + +/// A failed transaction's reads are in the returned state too. +#[test] +fn test_evm_state_include_failed_tx_reads() { + let db = MemoryDatabase::default() + .account_code(CONTRACT, Bytes::from_static(&[PUSH0, SLOAD, INVALID])); + let (result, _) = run(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + assert!(!result.result.is_success()); + assert!(result.state[&CONTRACT].storage.contains_key(&U256::ZERO)); +} + +/// A call to an existing empty account touches it, and EIP-161 clears it when the state is +/// applied. +#[test] +fn test_state_clear_with_noop_call() { + let empty_account = CONTRACT; + let mut db = MemoryDatabase::default().account_nonce(empty_account, 0); + let mut state = StateBuilder::::default() + .with_database(&mut db) + .with_bundle_update() + .build(); + let (result, _) = run(&mut state, call(CALLER, empty_account, U256::ZERO, GAS_LIMIT)); + assert!(result.state[&empty_account].is_touched()); + + let transitions = state.cache.apply_evm_state(result.state, |_, _| {}); + let (_, transition) = + transitions.iter().find(|(address, _)| *address == empty_account).unwrap(); + assert!(transition.storage_was_destroyed); +} + +const PARENT: Address = address!("0000000000000000000000000000000000500001"); +const DELEGATOR: Address = address!("0000000000000000000000000000000000500005"); +const DELEGATE: Address = address!("0000000000000000000000000000000000500006"); + +/// A contract that calls `first`, then `second`, and returns the 32 bytes `second` returned. +fn two_calls_returning_the_second(first: Address, second: Address) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(first) + .append(GAS) + .append(CALL) + .append(POP) + .push_number(32u8) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(second) + .append(GAS) + .append(CALL) + .append(POP) + .push_number(32u8) + .append(PUSH0) + .append(RETURN) + .build() +} + +/// A write through an EIP-7702 delegator goes to the delegator's storage: the delegate's own slot +/// keeps its original value when the delegate later runs in its own context. +#[test] +fn test_write_through_a_delegator_leaves_the_delegate_storage_alone() { + let delegate_code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(0x77)) + .push_number(1u8) + .append(SLOAD) + .append(PUSH0) + .append(MSTORE) + .push_number(32u8) + .append(PUSH0) + .append(RETURN) + .build(); + let mut db = MemoryDatabase::default() + .account_code(DELEGATE, delegate_code) + .account_storage(DELEGATE, U256::from(1), U256::from(99)) + .account_storage(DELEGATOR, U256::from(1), U256::from(42)) + .account_code(PARENT, two_calls_returning_the_second(DELEGATOR, DELEGATE)); + let delegation = Bytecode::new_eip7702(DELEGATE); + let account = db.load_account(DELEGATOR).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + account.account_state = AccountState::None; + + let (result, _) = run(db, call(CALLER, PARENT, U256::ZERO, 100_000_000)); + assert!(result.result.is_success(), "{:?}", result.result); + let second = U256::from_be_slice(result.result.output().unwrap()); + assert_eq!(second, U256::from(0x77), "the delegate reads its own write back"); + let slot = &result.state[&DELEGATE].storage[&U256::from(1)]; + assert_eq!(slot.original_value(), U256::from(99), "the delegate's own original value"); + let slot = &result.state[&DELEGATOR].storage[&U256::from(1)]; + assert_eq!(slot.original_value(), U256::from(42), "the delegator's own original value"); +} diff --git a/crates/mega-evm/tests/satin/static_callee.rs b/crates/mega-evm/tests/satin/static_callee.rs new file mode 100644 index 000000000..daa8b4379 --- /dev/null +++ b/crates/mega-evm/tests/satin/static_callee.rs @@ -0,0 +1,123 @@ +//! The halt reason of a creation inside a static call. +//! +//! A `CREATE` or `CREATE2` in a static frame halts with `StateChangeDuringStaticCall` before it +//! reads an operand, sizes its init code or charges anything, as in canonical revm. The +//! transaction does not expose an inner frame's halt reason, so these read it off the frame's +//! outcome as the caller receives it. The transactions are those of the parked tests of the same +//! names (`tests/_pending/rex6/create2_metering_order.rs`). + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::{CREATE, CREATE2, STATICCALL, STOP}, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult}, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000700000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000700001"); +const STATIC_CALLEE: Address = address!("0000000000000000000000000000000000700002"); + +/// The result of the static callee's frame, as its caller receives it. +#[derive(Default)] +struct CalleeResult(Option); + +impl Inspector, EthInterpreter> for CalleeResult { + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == STATIC_CALLEE { + self.0 = Some(outcome.result.result); + } + } +} + +/// Runs `CONTRACT`, which `STATICCALL`s `STATIC_CALLEE` running `callee` with `forward_gas`, and +/// returns the callee's result. +fn static_callee_result(callee: Bytes, forward_gas: u64) -> Option { + let caller_code = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_address(STATIC_CALLEE) + .push_number(forward_gas) + .append(STATICCALL) + .append(STOP) + .build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, caller_code) + .account_code(STATIC_CALLEE, callee); + let mut evm = MegaEvm::new(context(db)).with_inspector(CalleeResult::default()); + let result = evm.transact_raw(call(CALLER, CONTRACT, U256::ZERO, 100_000_000)).unwrap(); + assert!(result.result.is_success(), "the static call's failure does not fail the caller"); + evm.inspector().0 +} + +/// `CREATE2(value 0, offset 0, size, salt 0)`. +fn create2(initcode_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(0u64) + .push_number(initcode_len) + .push_number(0u64) + .push_number(0u64) + .append(CREATE2) + .append(STOP) + .build() +} + +const STATIC_REJECTION: Option = + Some(InstructionResult::StateChangeDuringStaticCall); + +/// Oversized init code in a static frame reports the static rejection, not the size limit. +#[test] +fn test_create2_static_oversized_initcode_reports_static_rejection() { + assert_eq!(static_callee_result(create2(600_000), 50_000_000), STATIC_REJECTION); +} + +/// So does init code whose memory could never be paid for: nothing is sized. +#[test] +fn test_create2_static_hugely_oversized_initcode_halt_reason() { + assert_eq!(static_callee_result(create2(10 * 1024 * 1024), 50_000_000), STATIC_REJECTION); +} + +/// Empty init code in a static frame reports the static rejection. +#[test] +fn test_create2_static_zero_length_initcode_reports_static_rejection() { + assert_eq!(static_callee_result(create2(0), 50_000_000), STATIC_REJECTION); +} + +/// With little gas forwarded the static rejection still comes first: nothing is charged. +#[test] +fn test_create2_static_zero_length_low_gas_halt_reason() { + assert_eq!(static_callee_result(create2(0), 10_000), STATIC_REJECTION); +} + +/// Plain `CREATE` is rejected the same way. +#[test] +fn test_create_static_low_gas_halt_reason() { + let create = BytecodeBuilder::default() + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(STOP) + .build(); + assert_eq!(static_callee_result(create, 10_000), STATIC_REJECTION); +} + +/// The rejection precedes the operand reads: a bare `CREATE2` reports it, not a stack underflow. +#[test] +fn test_create2_static_missing_operands_halt_reason() { + let bare = BytecodeBuilder::default().append(CREATE2).append(STOP).build(); + assert_eq!(static_callee_result(bare, 50_000_000), STATIC_REJECTION); +} diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs new file mode 100644 index 000000000..f6fd52460 --- /dev/null +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -0,0 +1,547 @@ +//! The abort protocol: a transaction-level limit stops the transaction with a revert. +//! +//! The frame that crosses the limit reverts with `MegaLimitExceeded`, the transaction is latched, +//! no caller resumes, and the transaction settles like an EIP-8037 revert: the sender gets the +//! unspent regular gas and the whole reservoir back. A frame budget reverts only its frame. A real +//! out-of-gas still halts and burns. The limit here is the configurable data-size cap of +//! `EvmTxRuntimeLimits`; a write record is 40 bytes. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, + MegaLimitExceeded, MegaTransaction, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, SSTORE}, + context::result::{ExecutionResult, ResultAndState}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const A: Address = address!("00000000000000000000000000000000000000A0"); +const B: Address = address!("00000000000000000000000000000000000000B0"); +const C: Address = address!("00000000000000000000000000000000000000C0"); +const D: Address = address!("00000000000000000000000000000000000000D0"); +const GAS_LIMIT: u64 = 1_000_000; + +/// Writes slot 1, calls `next` with all its gas, then writes slot 2 and emits a log: the part +/// after the call is what a resumed caller would run. +fn relay(next: Address) -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP) + .sstore(U256::from(2), U256::from(1)) + .append_many([PUSH0, PUSH0]) + .append(LOG0) + .stop() + .build() +} + +/// Writes slots 1 to 3. +fn writer() -> Bytes { + (1..=3u64) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .stop() + .build() +} + +/// `A -> B -> C -> D`, each writing a slot before its call; `D`, at depth 3, writes three. +fn chain() -> MemoryDatabase { + MemoryDatabase::default() + .account_code(A, relay(B)) + .account_code(B, relay(C)) + .account_code(C, relay(D)) + .account_code(D, writer()) +} + +fn evm_with( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + inspector: INSP, +) -> MegaEvm { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(inspector) +} + +fn run( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + tx: MegaTransaction, +) -> (ResultAndState, Option) { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = evm.transact_raw(tx).unwrap(); + (result, evm.ctx().additional_limit().latched().copied()) +} + +fn cap(bytes: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) +} + +fn limit_exceeded(kind: LimitKind, limit: u64) -> Bytes { + MegaLimitExceeded { kind: kind.as_u8(), limit }.abi_encode().into() +} + +fn assert_stopped(result: &ExecutionResult, kind: LimitKind, limit: u64) { + match result { + ExecutionResult::Revert { output, .. } => { + assert_eq!(output, &limit_exceeded(kind, limit), "the stop's revert data") + } + other => panic!("expected a revert-class stop, got {other:?}"), + } +} + +/// Records every step, and every call result the inspector sees end. +#[derive(Default)] +struct Probe { + steps: Vec, + call_results: Vec<(Address, InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for Probe { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.steps.push(interp.bytecode.opcode()); + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + self.call_results.push(( + inputs.target_address, + outcome.result.result, + outcome.result.output.clone(), + )); + } +} + +/// Crossing the cap at depth 3 reverts the whole transaction with `MegaLimitExceeded`: nothing +/// it wrote or logged stays, no caller runs another instruction, and the transaction is latched. +#[test] +fn test_cap_crossed_at_depth_three_stops_the_transaction() { + // A, B, C and D's first write are four records (160 bytes); D's second crosses 180. + let limit = 180; + for inspect in [false, true] { + let mut evm = evm_with(chain(), cap(limit), Probe::default()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert_stopped(&result.result, LimitKind::DataSize, limit); + assert!(result.result.logs().is_empty()); + for account in [A, B, C, D] { + let storage = &result.state[&account].storage; + assert!(storage.values().all(|slot| !slot.is_changed()), "{account} kept a write"); + } + let latched = evm.ctx().additional_limit().latched().copied(); + assert_eq!( + latched, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: 200, + frame_local: false + }) + ); + if inspect { + let probe = evm.inspector(); + let sstores = probe.steps.iter().filter(|op| matches!(op, &&SSTORE)).count(); + assert_eq!(sstores, 5, "A, B, C and D's first two writes ran"); + assert_eq!(probe.steps.last(), Some(&SSTORE), "nothing ran after the crossing write"); + assert!(!probe.steps.contains(&LOG0), "no caller resumed"); + let stops = probe.call_results.iter().map(|(target, result, output)| { + assert_eq!(output, &limit_exceeded(LimitKind::DataSize, limit)); + (*target, *result) + }); + assert_eq!( + stops.collect::>(), + vec![ + (D, InstructionResult::Revert), + (C, InstructionResult::Revert), + (B, InstructionResult::Revert), + (A, InstructionResult::Revert) + ], + "every frame returned the stop, the deepest first" + ); + } + } +} + +/// With and without an inspector the stopped transaction spends the same gas, and the gas does +/// not depend on what the callers would have run after the call: they never resume. +#[test] +fn test_stop_bills_only_what_ran() { + let gas_of = |db: MemoryDatabase, inspect: bool| { + let mut evm = evm_with(db, cap(180), Probe::default()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 180); + result.result.gas().tx_gas_used() + }; + let plain = gas_of(chain(), false); + assert_eq!(gas_of(chain(), true), plain, "an observing inspector changes nothing"); + assert!(plain < GAS_LIMIT / 2, "the stop does not burn the gas: {plain}"); + + // Callers whose code after the call is far more expensive spend exactly as much. + let heavy = |next: Address| { + let mut code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP); + for slot in 10..30u64 { + code = code.sstore(U256::from(slot), U256::from(1)); + } + code.stop().build() + }; + let db = MemoryDatabase::default() + .account_code(A, heavy(B)) + .account_code(B, heavy(C)) + .account_code(C, heavy(D)) + .account_code(D, writer()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 80); + let light = |next: Address| { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build() + }; + let db = MemoryDatabase::default() + .account_code(A, light(B)) + .account_code(B, light(C)) + .account_code(C, light(D)) + .account_code(D, writer()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); + let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert_stopped(&light_result.result, LimitKind::DataSize, 80); + assert_eq!( + result.result.gas().tx_gas_used(), + light_result.result.gas().tx_gas_used(), + "the code after the calls never ran" + ); +} + +/// The stopped transaction gives the whole reservoir back, and spends the same gas whatever its +/// gas limit, so a limit above the execution cap changes nothing but the refund. +#[test] +fn test_stop_refills_the_reservoir_at_any_gas_limit() { + let at = |gas_limit: u64| { + let (result, _) = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); + assert_stopped(&result.result, LimitKind::DataSize, 180); + *result.result.gas() + }; + let small = at(100_000_000); + let large = at(1_000_000_000); + assert_eq!(small.reservoir_remaining(), 0, "a limit under the cap has no reservoir"); + assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP, "all of it back"); + assert_eq!(small.tx_gas_used(), large.tx_gas_used()); + assert_eq!(small.total_gas_spent(), large.total_gas_spent()); +} + +/// An `SSTORE` that runs out of gas after its Host call records nothing, so a cap of zero does +/// not stop the transaction: it halts out of gas and burns its gas. +#[test] +fn test_true_out_of_gas_still_halts_and_burns() { + let db = MemoryDatabase::default().account_code(A, writer()); + let gas_limit = 21_000 + 5_000; + let (result, latched) = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); + assert!( + matches!( + result.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(revm::context::result::HaltReason::OutOfGas(_)), + .. + } + ), + "{:?}", + result.result + ); + assert_eq!(result.result.gas().tx_gas_used(), gas_limit, "the halt burns the gas"); + assert_eq!(latched, None); +} + +/// A child that runs out of gas halts alone; its caller goes on and writes within the cap. +#[test] +fn test_child_out_of_gas_under_a_cap_does_not_latch() { + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(5_000_u64) + .append(CALL) + .append(POP) + .sstore(U256::from(9), U256::from(1)) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(A, parent).account_code(B, writer()); + let (result, latched) = run(db, cap(40), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&A].storage[&U256::from(9)].present_value(), U256::from(1)); + assert_eq!(latched, None); +} + +/// A cap crossed by the writes the first frame's start makes (a value transfer's recipient) +/// reverts the transaction before the frame runs: the recipient's code never runs, its balance +/// is untouched, and the transaction spends what an empty call does. +#[test] +fn test_cap_crossed_before_the_first_frame_reverts_without_running() { + let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); + let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); + let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); + assert_stopped(&result.result, LimitKind::DataSize, 39); + assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); + assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); + + assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO, "nothing kept"); + + let (empty_call, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); + assert!(empty_call.result.is_success()); + assert_eq!(result.result.gas().tx_gas_used(), empty_call.result.gas().tx_gas_used()); +} + +/// A frame budget reverts the frame that crosses it and nothing else: the caller resumes and the +/// transaction is not latched. +#[test] +fn test_frame_budget_reverts_the_frame_without_a_latch() { + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append(GAS) + .append(CALL) + .append(POP) + .sstore(U256::from(9), U256::from(1)) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(A, parent).account_code(B, writer()); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let mut evm = evm_with(db, limits, Probe::default()); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + result.state[&A].storage[&U256::from(9)].present_value(), + U256::from(1), + "A resumed" + ); + assert!(result.state[&B].storage.values().all(|slot| !slot.is_changed()), "B reverted"); + assert_eq!(evm.ctx().additional_limit().latched(), None); + let (target, outcome, output) = evm.inspector().call_results[0].clone(); + assert_eq!((target, outcome), (B, InstructionResult::Revert)); + assert_eq!(output, limit_exceeded(LimitKind::DataSize, 100)); + assert!(evm.inspector().steps.contains(&SSTORE)); +} + +/// A frame budget crossed by the outermost frame reverts the transaction, still without a latch. +#[test] +fn test_frame_budget_of_the_outermost_frame_reverts_the_transaction() { + let db = MemoryDatabase::default().account_code(A, writer()); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let (result, latched) = run(db, limits, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert_stopped(&result.result, LimitKind::DataSize, 100); + assert_eq!(latched, None); +} + +/// A later latch does not replace the first. +#[test] +fn test_first_latch_wins() { + let mut layer = mega_evm::AdditionalLimit::default(); + let first = layer.latch(LimitKind::KVUpdate, 1, 2); + let second = layer.latch(LimitKind::DataSize, 3, 4); + assert_eq!(first, second); + assert_eq!(layer.latched(), Some(&first)); + assert!(first.exceeded_limit() && !first.is_frame_local()); +} + +/// The layer's state belongs to one transaction: a latch and the usage counted do not reach the +/// next transaction or system call, through any entry point. +#[test] +fn test_the_latch_does_not_outlive_its_transaction() { + let db = chain().account_code(B, writer()); + let mut evm = + MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))).with_inspector(Probe::default()); + let stopped = + |evm: &MegaEvm| evm.ctx().additional_limit().latched().is_some(); + + // B writes three slots: 120 bytes cross the cap. + alloy_evm::Evm::set_inspector_enabled(&mut evm, false); + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + assert!(stopped(&evm)); + // An empty call runs clean, through the plain and the inspected path. + assert!(evm + .transact_raw(call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)) + .unwrap() + .result + .is_success()); + assert!(!stopped(&evm)); + assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO); + + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + alloy_evm::Evm::set_inspector_enabled(&mut evm, true); + assert!(evm + .transact_raw(call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)) + .unwrap() + .result + .is_success()); + assert!(!stopped(&evm)); + + // So does a system call. + assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); + let system = evm.transact_system_call(CALLER, CALLER, Bytes::new()).unwrap(); + assert!(system.result.is_success()); + assert!(!stopped(&evm)); +} + +/// A creation transaction stopped before its first frame still bumps the sender's nonce, like any +/// included creation transaction: it cannot be replayed. +#[test] +fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { + let tx = crate::common::create(CALLER, writer(), GAS_LIMIT); + let (result, latched) = run(MemoryDatabase::default(), cap(39), tx); + assert_stopped(&result.result, LimitKind::DataSize, 39); + assert!(latched.is_some()); + assert_eq!(result.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); + assert!(result.state.get(&CALLER.create(0)).is_none_or(|a| a.info.is_empty_code_hash())); + assert!(result.result.gas().tx_gas_used() < GAS_LIMIT / 2, "the stop burns nothing"); + + // The stopped creation's result carries the reservoir back. + let tx = crate::common::create(CALLER, writer(), 1_000_000_000); + let (result, _) = run(MemoryDatabase::default(), cap(39), tx); + assert_eq!(result.result.gas().reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); +} + +/// A limit is crossed by usage above it: usage equal to the limit does not stop a transaction or +/// a frame. +#[test] +fn test_usage_equal_to_the_limit_does_not_stop() { + // A writes three slots: 120 bytes. + let db = || MemoryDatabase::default().account_code(A, writer()); + let (result, latched) = run(db(), cap(120), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(latched, None); + let budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(120); + let (result, _) = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + let (result, _) = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert_stopped(&result.result, LimitKind::DataSize, 119); +} + +/// A tool's inspector that writes to the running frame's gas or results. +#[derive(Default)] +struct Charger { + opcode: u8, + /// State gas charged after the first `SSTORE` of the transaction. + state_gas: u64, + /// History gas charged after the first `SSTORE` of the transaction. + history_gas: u64, + charged: bool, + /// Turns every call result into a success. + calls_succeed: bool, +} + +impl Inspector, EthInterpreter> for Charger { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.opcode == SSTORE && !self.charged { + self.charged = true; + assert!(interp.gas.record_state_cost(self.state_gas)); + assert!(interp.gas.record_history_cost(self.history_gas)); + } + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if self.calls_succeed { + outcome.result.result = InstructionResult::Stop; + } + } +} + +fn execute_with( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + charger: Charger, + gas_limit: u64, +) -> mega_evm::MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(charger) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)) + .unwrap() +} + +/// State gas drawn from the reservoir before the stop is refilled by it: the stopped transaction +/// hands the whole reservoir back, where a transaction that kept the state keeps the charge. +#[test] +fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { + let gas_limit = 1_000_000_000; + let reservoir = gas_limit - TX_GAS_LIMIT_CAP; + let charger = || Charger { state_gas: 50_000, ..Default::default() }; + let kept = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), charger(), gas_limit); + assert!(kept.result.is_success()); + assert_eq!(kept.gas.reservoir_remaining, reservoir - 50_000, "the kept charge"); + assert_eq!(kept.gas.state, 50_000); + + let stopped = execute_with(chain(), cap(180), charger(), gas_limit); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); + assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); + assert_eq!(stopped.gas.state, 0); +} + +/// History gas a transaction spent is reported on its outcome, apart from regular gas; a stop +/// takes it back with the rest. +#[test] +fn test_outcome_reports_history_gas() { + let charger = || Charger { history_gas: 700, ..Default::default() }; + let kept = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), charger(), GAS_LIMIT); + let plain = + execute_with(chain(), EvmTxRuntimeLimits::no_limits(), Charger::default(), GAS_LIMIT); + assert!(kept.result.is_success()); + assert_eq!(kept.gas.history, 700); + assert_eq!(kept.gas.regular, plain.gas.regular, "history is not regular gas"); + assert_eq!(kept.gas.gas_used, plain.gas.gas_used + 700); + + let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); + assert_eq!(stopped.gas.history, 0); +} + +/// Under the latch every returned result is the stop, whatever an inspector made of it: rewriting +/// the calls' results into successes neither resumes a caller nor lets the transaction succeed. +#[test] +fn test_latch_overrides_a_rewritten_result() { + let charger = Charger { calls_succeed: true, ..Default::default() }; + let outcome = execute_with(chain(), cap(180), charger, GAS_LIMIT); + assert_stopped(&outcome.result, LimitKind::DataSize, 180); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(outcome.usage, mega_evm::LimitUsage::ZERO, "every lane failed"); + assert!(outcome.result.logs().is_empty()); +} diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs new file mode 100644 index 000000000..4178bcb79 --- /dev/null +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -0,0 +1,221 @@ +//! Frame results `MegaETH` builds without running a frame carry the reservoir the frame +//! inherited and settle like revm's own. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, test_utils::MemoryDatabase, EvmTxRuntimeLimits, LimitKind, MegaEvm, +}; +use revm::{ + context::{ContextTr, JournalTr}, + handler::{EvmTr, FrameResult, ItemOrResult}, + inspector::InspectorEvmTr, + interpreter::{ + interpreter::SharedMemory, interpreter_action::FrameInit, + interpreter_types::InterpreterTypes, CallInput, CallInputs, CallOutcome, CallScheme, + CallValue, FrameInput, Gas, InstructionResult, InterpreterResult, + }, + primitives::CALL_STACK_LIMIT, + Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000300010"); +const TARGET: Address = address!("0000000000000000000000000000000000300001"); +const GAS_LIMIT: u64 = 100_000; +const RESERVOIR: u64 = 7_000_000; + +fn call_frame_init(depth: usize) -> FrameInit { + FrameInit { + depth, + memory: SharedMemory::new(), + frame_input: FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: GAS_LIMIT, + bytecode_address: TARGET, + known_bytecode: Default::default(), + target_address: TARGET, + caller: CALLER, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + reservoir: RESERVOIR, + charged_new_account_state_gas: false, + })), + } +} + +fn assert_call_too_deep(result: &FrameResult) { + let FrameResult::Call(outcome) = result else { panic!("expected a call result: {result:?}") }; + assert_eq!(outcome.result.result, InstructionResult::CallTooDeep); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT, "the forwarded gas is untouched"); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR, "the inherited reservoir is carried"); + assert_eq!(outcome.result.gas.state_gas_spent(), 0); +} + +/// A call past the call-stack limit is answered with `CallTooDeep` before anything could +/// intercept it, with the forwarded gas untouched and the inherited reservoir carried. +#[test] +fn test_depth_guard_returns_call_too_deep_with_the_inherited_reservoir() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize + 1)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("no frame is built past the limit") }; + assert_call_too_deep(&result); +} + +/// `CALL_STACK_LIMIT` itself is the last permitted depth: the guard does not fire there. +#[test] +fn test_depth_boundary_allows_call_at_limit() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account(TARGET).unwrap(); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("a call to an account without code is answered at once"); + }; + assert_eq!(outcome.result.result, InstructionResult::Stop, "the call went through"); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR); +} + +/// Answers every call itself, and counts the calls and their ends. +#[derive(Default)] +struct AlwaysAnswers { + calls: usize, + call_ends: usize, +} + +impl Inspector for AlwaysAnswers { + fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { + self.calls += 1; + Some(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + } + + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { + self.call_ends += 1; + } +} + +/// An inspector's answer to a call past the limit gives way to `CallTooDeep`, and the inspector +/// still sees the call end. +#[test] +fn test_inspect_frame_init_depth_guard_overrides_inspector() { + let mut evm = + MegaEvm::new(context(MemoryDatabase::default())).with_inspector(AlwaysAnswers::default()); + let result = InspectorEvmTr::inspect_frame_init( + &mut evm, + call_frame_init(CALL_STACK_LIMIT as usize + 1), + ) + .expect("inspect_frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("the frame was answered") }; + assert_call_too_deep(&result); + assert_eq!( + (evm.inspector().calls, evm.inspector().call_ends), + (1, 1), + "call and call_end pair" + ); +} + +/// A latched transaction's frame is answered with the stop, even past the call-stack limit: the +/// latch is checked first, and its answer carries the reservoir too. +#[test] +fn test_exceeded_tx_limit_wins_over_call_too_deep() { + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let stop = evm.ctx_mut().additional_limit_mut().latch(LimitKind::KVUpdate, 0, 1); + let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize + 1)) + .expect("frame_init does not fail"); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("a latched transaction's frame is answered"); + }; + assert_eq!(outcome.result.result, InstructionResult::Revert, "the stop, not CallTooDeep"); + assert_eq!(outcome.result.output, stop.revert_data()); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT); + assert_eq!(outcome.result.gas.reservoir(), RESERVOIR); +} + +/// A first frame answered with the stop before it runs gives the whole reservoir back, and costs +/// the same at a gas limit under the execution cap and far above it. +#[test] +fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { + let at = |gas_limit: u64| { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, TARGET, U256::from(1), gas_limit)) + .unwrap(); + assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); + *result.result.gas() + }; + let (small, large) = (at(100_000_000), at(1_000_000_000)); + assert_eq!(small.reservoir_remaining(), 0); + assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); + assert_eq!(small.tx_gas_used(), large.tx_gas_used()); + assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); +} + +/// `settle_frame_result` settles a result into its caller's gas exactly as revm's frame return +/// does, for a success, a revert and a halt, with state gas drawn from the reservoir and spilled +/// onto regular gas. +#[test] +fn test_settle_frame_result_matches_revms_frame_return() { + use mega_evm::{settle_frame_result, synthetic_frame_result}; + use revm::context::result::EVMError; + + for result_kind in + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] + { + let code = Bytes::from_static(&[revm::bytecode::opcode::STOP]); + let mut evm = + MegaEvm::new(context(MemoryDatabase::default().account_code(TARGET, code.clone()))); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account(TARGET).unwrap(); + let mut caller_init = call_frame_init(1); + if let FrameInput::Call(inputs) = &mut caller_init.frame_input { + let bytecode = revm::state::Bytecode::new_raw(code.clone()); + inputs.known_bytecode = (bytecode.hash_slow(), bytecode); + } + let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, caller_init).unwrap() else { + panic!("the caller frame is built"); + }; + + // The child the caller starts: 30,000 gas of the caller's, and its reservoir. + let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); + let caller_frame = frames.get(); + assert!(caller_frame.interpreter.gas.record_regular_cost(30_000)); + let child_input = { + let FrameInput::Call(mut inputs) = call_frame_init(2).frame_input else { + unreachable!() + }; + inputs.gas_limit = 30_000; + inputs.reservoir = caller_frame.interpreter.gas.reservoir(); + FrameInput::Call(inputs) + }; + let mut result = synthetic_frame_result(&child_input, result_kind, Bytes::new()); + // The child spent regular gas, and state gas beyond the reservoir that spilled. + let child_gas = result.gas_mut(); + assert!(child_gas.record_regular_cost(1_000)); + assert!(child_gas.record_state_cost(RESERVOIR + 500)); + + let mut expected = *caller_frame.interpreter.gas.tracker(); + settle_frame_result::<_, EVMError>( + ctx, + &mut expected, + &mut result.clone(), + ) + .unwrap(); + caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); + assert_eq!(caller_frame.interpreter.gas.tracker(), &expected, "{result_kind:?}"); + } +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs new file mode 100644 index 000000000..d0faaaff5 --- /dev/null +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -0,0 +1,821 @@ +//! The observe-stage-commit layer and the write records it counts. +//! +//! A write record is one account or storage write, 40 bytes of data size. The sites: the first +//! change of a slot in the transaction (taken back when the slot is written back), a value +//! transfer's sender and recipient, a creation's creator nonce and created account, a +//! `SELFDESTRUCT` that moves value to another account, an applied EIP-7702 authority, and the +//! transaction's own value recipient or created account. The sender's own account is part of the +//! transaction body and is not a record. Records are deduplicated per frame and discarded with the +//! frame that fails. + +use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, + SELFDESTRUCT, SSTORE, STOP, + }, + interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, + Database, Inspector, +}; + +use crate::common::{call, call_with_data, context, create, run}; + +const CALLER: Address = address!("0000000000000000000000000000000000100000"); +const CALLEE: Address = address!("0000000000000000000000000000000000100001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); +const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); +const GAS_LIMIT: u64 = 10_000_000; + +const fn records(n: u64) -> LimitUsage { + LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_000_000)) + .account_balance(CALLEE, U256::from(10_000_000)) +} + +/// Appends `CALL(gas=GAS, target, value, args=[], ret=[])`, leaving the success flag. +fn append_value_call(builder: BytecodeBuilder, target: Address, value: u8) -> BytecodeBuilder { + builder + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(value) + .push_address(target) + .append(GAS) + .append(CALL) +} + +/// Appends a `CREATE` with value 1 and empty init code. +fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { + builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) +} + +/* ---------- value transfers and creations, deduplicated per frame ---------- */ + +/// Two value transfers from one frame record the sender once and each recipient. +#[test] +fn test_two_value_calls_record_the_sender_once() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, CONTRACT, CONTRACT2"); +} + +/// A creation and a value transfer from one frame record the frame's account once. +#[test] +fn test_create_then_call_record_the_frame_account_once() { + let code = append_value_create(BytecodeBuilder::default()).append(POP); + let code = append_value_call(code, CONTRACT, 1).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, the created account, CONTRACT"); +} + +/// Two creations from one frame record the creator once and each created account. +#[test] +fn test_two_creates_record_the_creator_once() { + let code = append_value_create(BytecodeBuilder::default()).append(POP); + let code = append_value_create(code).append(POP).append(STOP).build(); + let (result, usage) = + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE once, two created accounts"); +} + +/// A value transfer into a child that fails is discarded with the child, sender included. +#[test] +fn test_failed_child_discards_its_transfer_records() { + let code = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "the outer call succeeds although the child halts"); + assert_eq!(usage, LimitUsage::ZERO); +} + +/// After a failed transfer the sender can be recorded again by the next one. +#[test] +fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(2), "CALLEE and CONTRACT2, from the second transfer"); +} + +const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); + +/// `PUSH5 ; PUSH1 0; MSTORE; (PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP) x +/// n`: `n` creations whose init code reverts. +fn reverting_creations(n: usize) -> Bytes { + let mut code = vec![0x64, 0x60, 0x00, 0x60, 0x00, 0xFD, 0x60, 0x00, 0x52]; + for _ in 0..n { + code.extend_from_slice(&[0x60, 0x05, 0x60, 0x1b, 0x60, 0x00, 0xf0, 0x50]); + } + code.push(0x00); + code.into() +} + +/// A reverted creation keeps the creator's nonce record: the nonce bump survives the revert. +#[test] +fn test_reverted_nested_create_keeps_the_creator_nonce_record() { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(1)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1), "the creator's nonce; the created account is gone"); +} + +/// Two reverted creations record the creator once: the first record survives, so the second +/// finds the creator recorded. +#[test] +fn test_reverted_then_retried_create_records_the_creator_once() { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(2)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1)); +} + +/// A creation the creator cannot fund never starts (the opcode checks the endowment before it +/// builds a frame), so it records nothing. +#[test] +fn test_creation_without_funds_records_nothing() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_000_000_000_000_u64) + .append(CREATE) + .append(POP) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); +} + +const A: Address = address!("00000000000000000000000000000000A0000001"); +const B: Address = address!("00000000000000000000000000000000B0000002"); +const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); + +fn value_delta(to: Address) -> LimitUsage { + let db = || MemoryDatabase::default().account_balance(A, U256::from(1_000_000)); + let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), GAS_LIMIT)); + let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, GAS_LIMIT)); + assert!(with_value.result.is_success() && zero_value.result.is_success()); + usage_value.saturating_sub(usage_zero) +} + +/// A top-level transfer to the sender itself writes no account the body does not already count. +#[test] +fn test_top_level_self_transfer_no_double_count() { + assert_eq!(value_delta(A), LimitUsage::ZERO); +} + +/// A top-level transfer to another account records the recipient. +#[test] +fn test_top_level_transfer_counts_the_recipient() { + assert_eq!(value_delta(B), records(1)); +} + +/// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty +/// calldata stops at once. +fn self_calling_code(targets: &[Address], value: u64) -> Bytes { + let mut code = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(5_u8) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST); + for target in targets { + code = code + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(*target) + .push_number(100_000_u64) + .append(CALL) + .append(POP); + } + code.stop().build() +} + +fn nested_delta(targets: &[Address]) -> LimitUsage { + let usage = |value| { + let db = MemoryDatabase::default() + .account_balance(A, U256::from(1_000_000)) + .account_balance(SELF_CALLER, U256::from(1_000_000)) + .account_code(SELF_CALLER, self_calling_code(targets, value)); + let (result, usage) = + run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), GAS_LIMIT)); + assert!(result.result.is_success()); + usage + }; + usage(1).saturating_sub(usage(0)) +} + +/// A nested transfer to the frame's own account is one account write. +#[test] +fn test_nested_self_call_with_value_counts_once() { + assert_eq!(nested_delta(&[SELF_CALLER]), records(1)); +} + +/// After a transfer to another account recorded the frame's account, a transfer to itself adds +/// nothing. +#[test] +fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { + assert_eq!(nested_delta(&[B, SELF_CALLER]), records(2)); +} + +/* ---------- storage, logs, selfdestruct ---------- */ + +/// A slot's first change is a record; writing it back to its original value takes it back. +#[test] +fn test_sstore_first_change_records_and_write_back_refunds() { + type Writes = &'static [(u64, u64)]; + let cases: [(Writes, u64, LimitUsage); 4] = [ + (&[(0, 1)], 0, records(1)), + (&[(0, 1), (0, 2)], 0, records(1)), + (&[(0, 1), (0, 0)], 0, LimitUsage::ZERO), + (&[(0, 0)], 5, records(1)), + ]; + for (writes, original, expected) in cases { + let mut code = BytecodeBuilder::default(); + for (slot, value) in writes { + code = code.sstore(U256::from(*slot), U256::from(*value)); + } + let db = MemoryDatabase::default() + .account_code(CALLEE, code.stop().build()) + .account_storage(CALLEE, U256::ZERO, U256::from(original)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected, "writes {writes:?} over original {original}"); + } +} + +/// A write-back in a child refunds the record its caller made, and the refund dies with a +/// failing child. +#[test] +fn test_write_back_in_a_child_refunds_the_caller_record() { + let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); + let failing_child = + BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).append(INVALID).build(); + for (code, expected) in [(child, LimitUsage::ZERO), (failing_child, records(1))] { + // CALLEE writes slot 0, then DELEGATECALLs CONTRACT, which writes it back in CALLEE's + // storage. + let parent = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build(); + let db = + MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected); + } +} + +/// A log counts 32 bytes for its address, 32 per topic and its data; no write record. +#[test] +fn test_log_counts_its_bytes() { + let code = BytecodeBuilder::default() + .push_number(0x22_u8) + .push_number(0x11_u8) + .push_number(10_u8) + .append(PUSH0) + .append(LOG2) + .stop() + .build(); + let (result, usage) = run( + MemoryDatabase::default().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + ); + assert!(result.result.is_success()); + assert_eq!(result.result.logs().len(), 1); + assert_eq!(usage, LimitUsage { data_size: 32 + 2 * 32 + 10, write_records: 0 }); +} + +/// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the +/// destructed one and the sender, whose account the transaction body counts. +#[test] +fn test_selfdestruct_records_the_beneficiary_when_value_moves() { + let destruct_to = |beneficiary: Address| { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() + }; + let cases = [ + (U256::from(5), CONTRACT, records(1)), + (U256::from(5), CALLEE, LimitUsage::ZERO), + (U256::from(5), CALLER, LimitUsage::ZERO), + (U256::ZERO, CONTRACT, LimitUsage::ZERO), + ]; + for (balance, beneficiary, expected) in cases { + let db = MemoryDatabase::default() + .account_code(CALLEE, destruct_to(beneficiary)) + .account_balance(CALLEE, balance); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); + } +} + +/// A top-level creation records the created account, and nothing when it fails. +#[test] +fn test_top_level_create_records_the_created_account() { + let (result, usage) = + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(1)); + + let (result, usage) = + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), GAS_LIMIT)); + assert!(!result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO); +} + +/* ---------- the commit happens after the opcode ---------- */ + +/// Records, after each opcode, what the layer holds. +#[derive(Default)] +struct LayerProbe { + /// `(opcode, staged record left, usage)` after each opcode. + steps: Vec<(u8, bool, LimitUsage)>, + opcode: u8, + /// Stages a log through the Host before every `SSTORE`, as a stale record. + stage_before_sstore: bool, +} + +impl Inspector, EthInterpreter> for LayerProbe { + fn step(&mut self, interp: &mut Interpreter, context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + if self.stage_before_sstore && self.opcode == SSTORE { + let log = Log { + address: CALLEE, + data: LogData::new(vec![B256::ZERO], Bytes::new()).unwrap(), + }; + revm::context_interface::Host::log(context, log); + assert!(matches!( + context.additional_limit().staged_record(), + Some(StagedRecord::Log { .. }) + )); + } + } + + fn step_end( + &mut self, + _interp: &mut Interpreter, + context: &mut MegaContext, + ) { + let layer = context.additional_limit(); + self.steps.push((self.opcode, layer.staged_record().is_some(), layer.usage())); + } +} + +fn probe( + db: MemoryDatabase, + gas_limit: u64, + stage_before_sstore: bool, +) -> Vec<(u8, bool, LimitUsage)> { + let mut evm = MegaEvm::new(context(db)) + .with_inspector(LayerProbe { stage_before_sstore, ..Default::default() }); + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); + evm.inspector().steps.clone() +} + +fn after_sstore(steps: &[(u8, bool, LimitUsage)]) -> (bool, LimitUsage) { + let (_, staged, usage) = steps.iter().find(|(op, ..)| *op == SSTORE).copied().unwrap(); + (staged, usage) +} + +/// A completed `SSTORE` commits its record: nothing is left staged and the record is counted by +/// the time the opcode ends. +#[test] +fn test_completed_sstore_commits_its_record() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, false); + let (staged, usage) = after_sstore(&steps); + assert!(!staged); + assert_eq!(usage, records(1)); +} + +/// An `SSTORE` that runs out of gas after its Host call wrote the slot discards the staged +/// record: the Host observed the write, the failure takes it back, and nothing is counted. +#[test] +fn test_sstore_out_of_gas_after_the_write_discards_the_record() { + // CALLEE calls CONTRACT with 5,000 gas: past the EIP-2200 stipend check, so the Host call + // writes the slot, but short of the 22,100 a cold first write charges after it. + let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .push_number(5_000_u64) + .append(CALL) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, child); + let steps = probe(db, GAS_LIMIT, false); + let (staged, usage) = after_sstore(&steps); + assert!(!staged, "the record is discarded, not left for the next opcode"); + assert_eq!(usage, LimitUsage::ZERO, "a failed opcode's write is not counted"); +} + +/// A record staged outside an opcode's wrapper is discarded when the next wrapper starts, so it +/// is never committed for that opcode. +#[test] +fn test_wrapper_discards_a_stale_record_on_entry() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, true); + let (staged, usage) = after_sstore(&steps); + assert!(!staged); + assert_eq!(usage, records(1), "the SSTORE's record, and not the stale log's bytes"); +} + +/* ---------- applied EIP-7702 authorities ---------- */ + +const DELEGATE: Address = address!("00000000000000000000000000000000DE1E0001"); +const AUTHORITY_1: Address = address!("00000000000000000000000000000000A0717001"); +const AUTHORITY_2: Address = address!("00000000000000000000000000000000A0717002"); + +/// A type-4 transaction from `CALLER` to `to` with value `value`, carrying authorizations +/// `(authority, nonce)` that delegate to `DELEGATE`. +fn authorizing_call( + to: Address, + value: u64, + authorizations: &[(Address, u64)], +) -> mega_evm::MegaTransaction { + use revm::{ + context::{transaction::TransactionType, TxEnv}, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + let authorization_list = authorizations + .iter() + .map(|(authority, nonce)| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: DELEGATE, nonce: *nonce }, + RecoveredAuthority::Valid(*authority), + )) + }) + .collect(); + alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: alloy_primitives::TxKind::Call(to), + value: U256::from(value), + gas_limit: GAS_LIMIT, + gas_priority_fee: Some(0), + authorization_list, + ..Default::default() + })) +} + +/// Each distinct applied authority is one record, however many of its authorizations applied; +/// an authorization that does not apply (a wrong nonce) records nothing. +#[test] +fn test_applied_authorities_record_once_each() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run( + db(), + authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0), (AUTHORITY_2, 0), (AUTHORITY_1, 1)]), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, records(2)); + + let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 7)])); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO, "a wrong nonce applies nothing"); + + let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(CALLER, 1)])); + assert!(result.result.is_success()); + assert_eq!(usage, LimitUsage::ZERO, "the sender's own account is part of the body"); +} + +/// A value transfer to an applied authority records the authority once, not again as the +/// recipient. +#[test] +fn test_value_to_an_applied_authority_records_it_once() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run(db, authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, records(1)); +} + +/// A frame running as the transaction's sender (a delegated sender called back) records no +/// write to the sender's account: the transaction body counts it. +#[test] +fn test_frames_running_as_the_sender_do_not_record_it() { + // CALLER is delegated to CONTRACT, whose code sends value to CONTRACT2. CALLEE calls CALLER. + let relay = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CALLER) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let mut db = funded().account_code(CALLEE, relay).account_code(CONTRACT, sender_code); + let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); + let account = db.load_account(CALLER).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); + assert_eq!(usage, records(1), "CONTRACT2 only; the sender is part of the body"); +} + +/// Raises the endowment of every creation past what the creator holds. +struct OverfundCreations; + +impl Inspector, EthInterpreter> for OverfundCreations { + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut revm::interpreter::CreateInputs, + ) -> Option { + inputs.set_value(U256::MAX); + None + } +} + +/// A creation that fails before bumping the creator's nonce (here, an endowment an inspector +/// raised past the creator's balance) takes its creator record back with it. +#[test] +fn test_creation_failing_before_the_nonce_bump_records_nothing() { + let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); + let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, code))) + .with_inspector(OverfundCreations); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); + assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO); +} + +/// A creation that collides with an existing account fails after bumping the creator's nonce, so +/// the creator record stays and the created account's goes. +#[test] +fn test_colliding_creation_keeps_the_creator_record() { + let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); + let db = funded().account_code(CALLEE, code).account_nonce(CALLEE.create(0), 1); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); + assert_eq!(usage, records(1), "the creator's nonce only"); +} + +/// A creation a frame budget stops before it runs reverts like one that ran: the creator's nonce +/// is bumped and its record kept, the created account's record goes. +#[test] +fn test_creation_stopped_at_init_bumps_the_creator_nonce() { + // CALLEE writes a slot (40 bytes of its 100-byte budget), then creates: the creation's two + // records (80 bytes) exceed the 60 bytes left to it. CALLEE stores the created address. + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0]) + .append(CREATE) + .append(PUSH0) + .append(SSTORE) + .stop() + .build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CALLEE].info.nonce, 1, "the stopped creation bumped the nonce"); + assert_eq!(result.state[&CALLEE].storage[&U256::ZERO].present_value(), U256::ZERO, "it failed"); + assert_eq!(evm.ctx().additional_limit().usage(), records(2), "slot 1 and the creator's nonce"); +} + +/// Authorities whose records would cross the transaction's data-size limit are not applied: the +/// limit is enforced before the writes it guards, and the transaction is stopped before its first +/// frame. +#[test] +fn test_authorities_crossing_the_cap_are_not_applied() { + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let with_cap = |cap| { + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(cap); + MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) + .unwrap() + }; + let at_the_cap = with_cap(40); + assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); + assert_eq!(at_the_cap.usage, records(1)); + + let outcome = with_cap(39); + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_some()); + let authority = outcome.state.get(&AUTHORITY_1); + assert!( + authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "the delegation was not applied: {authority:?}" + ); + assert_eq!(outcome.usage, LimitUsage::ZERO); +} + +/// A transaction that runs out of gas after its authorities were applied, before its first frame, +/// keeps none of their records: the out-of-gas takes the delegations back. +#[test] +fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { + // The call target is an authority the transaction delegates: calling it pays for the + // delegation target's access after the authorities were applied. Find the gas limit one short + // of the whole runtime phase. + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000)); + let tx = |gas_limit| { + let mut tx = authorizing_call(AUTHORITY_1, 0, &[(AUTHORITY_1, 0)]); + tx.0.base.gas_limit = gas_limit; + tx + }; + let run_at = + |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)).unwrap(); + let mut gas_limit = 40_000; + while !run_at(gas_limit).result.is_success() { + gas_limit += 1; + assert!(gas_limit < 200_000, "the transaction never succeeds"); + } + let outcome = run_at(gas_limit - 1); + assert!(outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.usage, LimitUsage::ZERO); + assert_eq!(outcome.limit_exceeded, None); + assert!( + outcome.state.get(&AUTHORITY_1).is_none_or(|a| a.info.nonce == 0), + "the out-of-gas took the delegation back" + ); +} + +/* ---------- which frame's account counts as recorded ---------- */ + +const D: Address = address!("00000000000000000000000000000000000000D1"); + +/// A child that received value records its own account then: its own value transfers do not +/// record it again. +#[test] +fn test_value_receiving_child_records_itself_once() { + let a = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(3), "CALLEE, CONTRACT once, CONTRACT2"); +} + +/// A child that received nothing starts with its own account unrecorded, whatever its caller's +/// state. +#[test] +fn test_zero_value_child_starts_unrecorded() { + let a = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let b = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded() + .account_code(CALLEE, a) + .account_code(CONTRACT, b) + .account_balance(CONTRACT, U256::from(5)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(usage, records(3), "CALLEE as the recipient, CONTRACT, CONTRACT2"); +} + +/// Calls `D` with `DELEGATECALL`. +fn delegate_to_d() -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(D) + .append(GAS) + .append(revm::bytecode::opcode::DELEGATECALL) + .append(POP) + .stop() + .build() +} + +/// A `DELEGATECALL` runs as its caller's account, and inherits whether that account is recorded. +#[test] +fn test_delegatecall_child_inherits_the_frame_account_record() { + let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(CALLEE, delegate_to_d()).account_code(D, d); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + assert!(result.result.is_success()); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); + assert_eq!(usage, records(2), "CALLEE as the recipient, CONTRACT2"); +} + +/// A created frame's account is recorded by the creation; a `DELEGATECALL` from its init code +/// inherits that. +#[test] +fn test_created_frame_delegatecall_inherits_the_created_account_record() { + let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let db = funded().account_code(D, d); + let tx = { + let mut tx = create(CALLER, delegate_to_d(), GAS_LIMIT); + tx.0.base.value = U256::from(5); + tx + }; + let (result, usage) = run(db, tx); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(2), "the created account, CONTRACT2"); +} + +/// A transaction calling its own sender (delegated) counts the sender as recorded from the start. +#[test] +fn test_top_level_self_call_counts_the_sender_as_recorded() { + let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) + .append(POP) + .append(STOP) + .build(); + let mut db = funded().account_code(CONTRACT, sender_code); + let delegation = revm::state::Bytecode::new_eip7702(CONTRACT); + let account = db.load_account(CALLER).unwrap(); + account.info.code_hash = delegation.hash_slow(); + account.info.code = Some(delegation); + let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(usage, records(1), "CONTRACT2 only"); +} + +/// Answers every call to `CONTRACT` itself. +struct AnswerContract; + +impl Inspector, EthInterpreter> for AnswerContract { + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut revm::interpreter::CallInputs, + ) -> Option { + (inputs.target_address == CONTRACT).then(|| { + revm::interpreter::CallOutcome::new( + revm::interpreter::InterpreterResult::new( + revm::interpreter::InstructionResult::Stop, + Bytes::new(), + revm::interpreter::Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// A call an inspector answers gets an empty lane of its own, so its caller's lane is intact for +/// what the caller does next. +#[test] +fn test_inspector_answered_call_keeps_the_caller_lane() { + let a = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append(GAS) + .append(CALL) + .append(POP); + let a = append_value_call(a, CONTRACT2, 1).append(POP).append(STOP).build(); + let mut evm = + MegaEvm::new(context(funded().account_code(CALLEE, a))).with_inspector(AnswerContract); + let result = + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().additional_limit().usage(), records(2), "CALLEE and CONTRACT2"); +} diff --git a/mutants/README.md b/mutants/README.md index 83bdd5c0e..776d89b47 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -3,18 +3,25 @@ Mutation testing measures **test adequacy**: it deliberately introduces small faults ("mutants") into the source and checks whether the test suite catches them. A mutant that survives a green test run is a place where the code could be wrong and no test would notice — a test gap. -Target: **`crates/mega-evm`**. -(`mega-system-contracts` is excluded — its `src/` is generated bytecode artifacts and produces zero mutants.) +Two scopes, mutated and gated separately: + +- **production** — `crates/mega-evm`'s engine code, with generated code and test helpers excluded as noise. + (`mega-system-contracts` is excluded too — its `src/` is generated bytecode artifacts and produces zero mutants.) +- **infrastructure** — the code that implements the test gates, which the helper exclusion removes from the production scope: the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`). + Mutated against `mega-evm`'s tests. + +The two scopes are disjoint; a mutant belongs to exactly one of them. ## Layout | Path | Purpose | |------|---------| -| `.cargo/mutants.toml` | Canonical `cargo-mutants` config (scope, nextest, excludes, timeouts). | -| `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating. | -| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `. | +| `.cargo/mutants.toml` | Canonical `cargo-mutants` config for the production scope (nextest, excludes, timeouts). | +| `.cargo/mutants-infra.toml` | Config for the infrastructure scope (no helper exclusion). | +| `mutants/suppressions.toml` | Reviewed equivalent / dead-code mutants excluded from gating, in either scope. | +| `scripts/mutation_test.sh` | Driver: `diff `, `full`, `file `, `infra`; `MUTANTS_SHARD=k/n` runs one shard. | | `scripts/mutation_gate.py` | Scores a run, applies suppressions, gates the PR. | -| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment. | +| `.github/workflows/mutation.yml` | Diff-scoped PR gate + result comment, and the infrastructure job. | ## Local use @@ -26,8 +33,19 @@ python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' + +# The infrastructure scope (its own output directory, so it does not overwrite the production run): +OUT_DIR=target/mutants-infra scripts/mutation_test.sh infra +python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.out \ + --suppressions mutants/suppressions.toml + +# Shard k of n of a large run (cargo-mutants' --shard), each into its own directory: +MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main ``` +The driver needs bash 4 or later and Python 3.11 or later on `PATH`; with the macOS defaults (bash 3.2, Python 3.9) it fails before mutating anything. +When to shard is in `REVIEW.md` (Test gates, Mutation testing). + ## The gate PR CI runs **diff-scoped** (`cargo mutants --in-diff`), so every mutant lives on a line the PR touched. diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 8894c2255..592ecf856 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -43,85 +43,7 @@ # entries against real source for exactly this reason. # ───────────────────────────────────────────────────────────────────────────── -# crates/mega-evm/src/limit/ survivors. -# -# The real test gap here — `AdditionalLimit::before_frame_run -> None` -# (limit.rs:585) — is closed behaviorally by -# `crates/mega-evm/tests/mutation/limit.rs`. The remaining survivors below are -# provably equivalent / dead and are recorded here with justification. - -# --- Dead `tx_limit()` trait methods (equivalent: zero call sites) ---------------- -# -# `::tx_limit` is a -# trivial passthrough to the inherent `FrameLimitTracker::tx_limit()`. Every internal -# consumer (each tracker's own `check_limit()` / `current_call_remaining()`, and -# `AdditionalLimit`) calls `self.frame_tracker.tx_limit()` directly; the *trait* method -# on these three trackers is never invoked anywhere in the crate (verified by grepping -# all `.tx_limit()` call sites — only `ComputeGasTracker`'s trait method is live, since -# its `check_limit` calls `self.tx_limit()` and composes it with `detained_limit`). -# Because the function is dead, replacing its body (`-> 0` / `-> 1`) cannot change any -# observable behavior: the full mega-evm test suite passes with the mutation applied. -# These are required only to satisfy the `TxRuntimeLimit` trait contract. -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/data_size.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/kv_update.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -[[suppress]] -kind = "function" -category = "dead" -file = "crates/mega-evm/src/limit/state_growth.rs" -pattern = "::tx_limit" -justification = "Dead/equivalent: this trait method has zero call sites; all callers use the inherent frame_tracker.tx_limit(). Mutating it (-> 0 / -> 1) changes no observable behavior (full suite green with the mutant). Required only to satisfy the TxRuntimeLimit trait." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- effective_remaining_for_rescue boundary (equivalent) ------------------------- -# -# `if stipend > 0 { gas.remaining().min(gas.limit() - stipend) } else { gas.remaining() }`. -# The `> 0` -> `>= 0` mutant only diverges when `stipend == 0`, in which case the then- -# branch computes `gas.remaining().min(gas.limit() - 0) = gas.remaining().min(gas.limit())`. -# Since `gas.remaining() <= gas.limit()` is invariant in revm (remaining starts at limit and -# only decreases; the REX4 stipend inflates both limit and remaining together), this equals -# `gas.remaining()` — identical to the else-branch. The four other mutants in this function -# are caught by the rex4 storage_call_stipend tests; only this true boundary equivalent -# survives. -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/storage_call_stipend.rs" -mutant = "replace > with >= in StorageCallStipendTracker::effective_remaining_for_rescue" -justification = "Equivalent: the > vs >= boundary only differs when stipend == 0, where the then-branch reduces to gas.remaining().min(gas.limit()) == gas.remaining() (the else-branch) because remaining <= limit is invariant. No reachable input observes the difference." -reviewer = "improve-mutation-score (William Aaron Cheung)" - -# --- before_frame_return_result de-dup flag (equivalent) -------------------------- -# -# `let duplicate_return_frame_result = LAST_FRAME && !has_active_frame();`. The `&&` -> `||` -# mutant can only diverge when (a) LAST_FRAME is true while a frame is still active, or -# (b) LAST_FRAME is false while no frame is active. Neither is reachable: the `` -# (`last_frame_result`) call always runs after the frame's tracker has already been popped -# by the preceding `` (`frame_return_result`) pass, so `has_active_frame()` is always -# false at `` calls (making `&& X` == `|| X` == true); and at `` calls -# LAST_FRAME is false. The full mega-evm suite — including all nested/parent-child/sibling -# and top-level frame-local & TX-level-detention exceed tests — passes with the mutant -# applied, confirming no observable difference. -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/limit.rs" -mutant = "replace && with || in AdditionalLimit::before_frame_return_result" -justification = "Equivalent: at every (last_frame_result) call has_active_frame() is already false (the frame was popped by the preceding frame_return_result pass), so LAST_FRAME && !has_active == LAST_FRAME || !has_active == true; at calls LAST_FRAME is false in both. Full suite (incl. all multi-frame exceed tests) green with the mutant." -reviewer = "improve-mutation-score (William Aaron Cheung)" +# crates/mega-evm/src/external/ survivors. # --- EmptyExternalEnv::external_envs (equivalent) --------------------------------- # EmptyExternalEnv is a unit struct. The real body constructs @@ -259,60 +181,108 @@ justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs reviewer = "improve-mutation-score (William Aaron Cheung)" # ───────────────────────────────────────────────────────────────────────────── -# spec-gate operator survivors (universalmutator + comby; scripts/umutate.py). -# -# Equivalent mutants of backward-compat spec gates in src/limit/. The one real -# survivor (limit.rs:203) is closed behaviorally by -# `test_intrinsic_check_for_tx_requires_rex5_spec`. The state_growth entries use -# the full `file:line:col:` form because three sites share identical source text. +# crates/mega-evm/src/evm/ survivors. -# --- data_size.rs:173 defensive invariant guard (equivalent) ----------------- +# --- From for EthSpecId (equivalent while revm's default is Osaka) ----- +# `MegaSpecId` has the single variant SATIN, which maps to OSAKA. revm 40's +# `SpecId::default()` is also OSAKA, so the `Default::default()` mutant returns the +# same value for every input. A line entry keeps the mutant generated: once a revm +# upgrade moves the default, `test_all_specs_map_to_karst_and_osaka` kills it and this +# entry becomes a no-op. [[suppress]] kind = "line" category = "equivalent" -file = "crates/mega-evm/src/limit/data_size.rs" -mutant = "spec-gate rex5_enabled: spec.is_enabled(MegaSpecId::REX5), -> rex5_enabled: spec.is_enabled(MegaSpecId::REX4)," -justification = "Equivalent: rex5_enabled only feeds the debug_assert! at data_size.rs:173, which executes only inside the `used > limit` branch with an active frame — a TX-level data-size exceed while a frame is live. Pre-REX5 that state is unreachable in valid execution (before_tx_start, the only mid-execution tx_entry writer, runs before any frame; an exceed there halts before a frame is pushed). Relaxing the guard to REX4 cannot change behavior on any reachable input." -reviewer = "improve-mutation-score (William Aaron Cheung)" +file = "crates/mega-evm/src/evm/spec.rs" +mutant = "replace for EthSpecId>::from -> Self with Default::default()" +justification = "Equivalent: revm's SpecId::OSAKA carries #[default], and Satin's sole rung (SATIN) maps to EthSpecId::OSAKA, so Default::default() returns the same value on every current input. test_all_specs_map_to_karst_and_osaka pins the mapping; if the upstream default moves, that test kills this mutant and the entry becomes a no-op." +reviewer = "RealiCZ" + +# ───────────────────────────────────────────────────────────────────────────── +# Infrastructure scope (.cargo/mutants-infra.toml) survivors. -# --- frame_limit.rs:113 per-frame derivation gate (equivalent: coupled) ------- +# --- Scenario::block field deletions that restore the same value (equivalent) ------ +# `Scenario::block` writes five fields over `..Default::default()`. Three of them write +# exactly what revm 40's `BlockEnv::default()` already holds — `timestamp: U256::ONE`, +# `basefee: 0`, `gas_limit: u64::MAX` — so deleting the field yields the identical +# BlockEnv for every scenario, and no scenario or unit test can distinguish it. The two +# that do differ from the default (`number`, and `beneficiary`, which carries the +# scenario's coinbase) are killed by `test_block_is_fixed_except_for_the_beneficiary`, +# which pins all five values: if a revm upgrade moves one of these defaults, that test +# kills the mutant and the entry below becomes a no-op. Line entries, so they stay +# generated and are re-checked on every run. [[suppress]] kind = "line" category = "equivalent" -file = "crates/mega-evm/src/limit/frame_limit.rs" -mutant = "spec-gate rex4_enabled: spec.is_enabled(MegaSpecId::REX4), -> rex4_enabled: spec.is_enabled(MegaSpecId::REX3)," -justification = "Equivalent (coupled gates): frame_limit rex4_enabled gates only per-frame limit DERIVATION (push_call_frame_info, line 339). ENFORCEMENT (exceeds_current_frame_limit) is gated separately on each dimension's own REX4 check. Shifting derivation to REX3 sets per-frame limits that no dimension checks at REX3 — their checks stay TX-level — so net_usage and every limit outcome are unchanged." -reviewer = "improve-mutation-score (William Aaron Cheung)" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field timestamp from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes U256::from(1) and revm 40's BlockEnv::default() already has timestamp: U256::ONE, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" -# --- state_growth.rs REX4 per-frame gates (equivalent: coupled/REX5-only) ----- [[suppress]] kind = "line" category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:121:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent (coupled): push_frame shifted to REX3 derives per-frame state-growth limits at REX3, but check_limit (line 206, unmutated) skips the per-frame check pre-REX4 and uses TX-level net_usage only. The derived frame limits are never read, so no observable change." -reviewer = "improve-mutation-score (William Aaron Cheung)" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field basefee from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes 0 and revm 40's BlockEnv::default() already has basefee: 0, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:206:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent (coupled): check_limit shifted to REX3 runs the per-frame check at REX3, but push_frame (line 121, unmutated) pushes frames with u64::MAX limit pre-REX4, so exceeds_current_frame_limit never fires and control falls through to the identical TX-level check." -reviewer = "improve-mutation-score (William Aaron Cheung)" +file = "crates/mega-evm/src/test_utils/scenario.rs" +mutant = "delete field gas_limit from struct BlockEnv expression in Scenario::block" +justification = "Equivalent: the field writes u64::MAX and revm 40's BlockEnv::default() already has gas_limit: u64::MAX, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." +reviewer = "RealiCZ" +# ───────────────────────────────────────────────────────────────────────────── +# crates/mega-evm/src/ survivors of the common execution layer. + +# --- inspect_frame_init: logs journaled by frame init (dead while EIP-7708 is off) -------- +# `inspect_frame_init` mirrors revm's: after `frame_init`, the logs journaled since `logs_i` +# (EIP-7708 transfer logs, a precompile's logs) go to the inspector's `log` callback. Satin's +# spec configuration fixes EIP-7708 off (`MegaContext::with_cfg`), and op-revm's precompile set +# journals no log, so frame init never journals one: the length comparisons are always false +# and `inspect_logs` is never entered. Flipping `!=` to `==` would call `inspect_logs` over an +# empty range, a no-op; stubbing it changes nothing reachable. Live again when the Satin gas +# table switches EIP-7708 on, at which point a transfer-log test kills them. [[suppress]] kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:169:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX3) {" -justification = "Equivalent: current_call_remaining is only read when building a child sandbox budget (sandbox/execution.rs:1037, KeylessDeploy, REX5+); it is never called at REX3/REX4. And at REX3 frames carry u64::MAX limits (push_frame, line 121), so frame_remaining.min(tx_remaining) == tx_remaining regardless." -reviewer = "improve-mutation-score (William Aaron Cheung)" +category = "dead" +file = "crates/mega-evm/src/evm/execution.rs" +mutant = "replace != with == in >::inspect_frame_init" +justification = "Dead in Satin: frame init journals no log (EIP-7708 is fixed off by the spec configuration, op-revm's precompiles journal none), so both `logs().len() != logs_i` comparisons are always false; with `==` the call hands the inspector an empty range, a no-op. Becomes live, and killable, when EIP-7708 is switched on." +reviewer = "RealiCZ" + +[[suppress]] +kind = "line" +category = "dead" +file = "crates/mega-evm/src/evm/execution.rs" +mutant = "replace inspect_logs with ()" +justification = "Dead in Satin: only called for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile). Becomes live, and killable, when EIP-7708 is switched on." +reviewer = "RealiCZ" +# --- DeclaredObserver::log forwarding (dead while EIP-7708 is off) ---------------------- +# revm hands a log to `Inspector::log` (without an interpreter) only from the frame-init path +# above; every log an opcode emits goes to `log_full`, which the forwarding test covers. +[[suppress]] +kind = "line" +category = "dead" +file = "crates/mega-evm/src/evm/inspector.rs" +mutant = "replace for DeclaredObserver>::log with ()" +justification = "Dead in Satin: revm calls `Inspector::log` only for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile); opcode logs reach `log_full`, which test_declared_observer_forwards_every_callback covers. Becomes live when EIP-7708 is switched on." +reviewer = "RealiCZ" + +# --- AdditionalLimit::discard_stale_record (equivalent) --------------------------------- +# Every wrapper discards a record staged before its opcode on entry. The three wrapped opcodes +# each stage their own record through the Host whenever they complete (SSTORE through +# sstore_skip_cold_load, LOG through log, SELFDESTRUCT through selfdestruct), which overwrites a +# stale one, and a failing opcode's wrapper discards whatever is staged. So a stale record can +# never be committed with or without the entry discard; it is the contract's guard for a future +# wrapped opcode that completes without a Host call. [[suppress]] kind = "line" category = "equivalent" -file = "crates/mega-evm/src/limit/state_growth.rs" -mutant = "crates/mega-evm/src/limit/state_growth.rs:169:1: spec-gate if self.spec.is_enabled(MegaSpecId::REX4) { -> if self.spec.is_enabled(MegaSpecId::REX5) {" -justification = "Equivalent: current_call_remaining is only read by the REX5+ KeylessDeploy sandbox (sandbox/execution.rs:1037). The REX4->REX5 shift differs only at exactly REX4, where the function is never called — no observable change." -reviewer = "improve-mutation-score (William Aaron Cheung)" +file = "crates/mega-evm/src/limit/limit.rs" +mutant = "replace AdditionalLimit::discard_stale_record with ()" +justification = "Equivalent: each wrapped opcode (SSTORE, LOG0-4, SELFDESTRUCT) stages its own record through the Host whenever it completes, overwriting a stale one, and a failing opcode's wrapper discards the staged record, so no stale record can be committed with or without the entry discard (test_wrapper_discards_a_stale_record_on_entry shows the stale log is not counted either way)." +reviewer = "RealiCZ" diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 90fddfe30..2be52d012 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -5,16 +5,33 @@ # diff Mutate only lines changed vs (PR gate mode). # full Mutate the whole mega-evm crate (nightly mode; slow). # file Mutate files matching (local iteration). +# infra Mutate the test gates' own infrastructure (see INFRA_FILES below). +# +# `diff`, `full` and `file` run the production scope of .cargo/mutants.toml, which excludes test +# helpers as noise. `infra` runs the second scope, .cargo/mutants-infra.toml: the scenario runner +# is helper code by that rule, but the benches and later tests rest on it, so it is mutated on its +# own. # # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). # Run scripts/mutation_gate.py afterwards to score + gate the run. +# +# MUTANTS_SHARD=k/n runs only shard k (0-based) of n of whichever mutant set the +# subcommand selects (cargo-mutants' own --shard), for a diff too large for one +# job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" OUT_DIR="${OUT_DIR:-$ROOT_DIR/target/mutants}" SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" JOBS="${JOBS:-$(nproc)}" -PKG="mega-evm" +PKG_ARGS=(--package mega-evm) +CONFIG_ARGS=() + +# The test gates' own executable logic: the scenario runner's transaction conversion and its +# execute/commit loop. +INFRA_FILES=( + crates/mega-evm/src/test_utils/scenario.rs +) cd "$ROOT_DIR" @@ -35,6 +52,9 @@ fi EXCLUDE_ARGS=() [[ -n "$exclude_re_output" ]] && mapfile -t EXCLUDE_ARGS <<< "$exclude_re_output" +SHARD_ARGS=() +[[ -n "${MUTANTS_SHARD:-}" ]] && SHARD_ARGS=(--shard "$MUTANTS_SHARD") + run_mutants() { rm -rf "$OUT_DIR" mkdir -p "$(dirname "$OUT_DIR")" # cargo-mutants creates OUT_DIR itself but not its parents @@ -43,12 +63,14 @@ run_mutants() { # -vV: verbose progress + version banner, for diagnosable CI logs. local rc=0 cargo mutants \ - --package "$PKG" \ + "${CONFIG_ARGS[@]}" \ + "${PKG_ARGS[@]}" \ --jobs "$JOBS" \ --output "$OUT_DIR" \ --no-shuffle \ -vV \ "${EXCLUDE_ARGS[@]}" \ + "${SHARD_ARGS[@]}" \ "$@" || rc=$? # cargo-mutants exit codes (https://mutants.rs/exit-codes.html): 0 = all caught, @@ -86,8 +108,14 @@ case "$cmd" in glob="${1:?usage: mutation_test.sh file }" run_mutants -f "$glob" ;; + infra) + CONFIG_ARGS=(--config "$ROOT_DIR/.cargo/mutants-infra.toml") + FILE_ARGS=() + for file in "${INFRA_FILES[@]}"; do FILE_ARGS+=(-f "$file"); done + run_mutants "${FILE_ARGS[@]}" "$@" + ;; *) - echo "usage: mutation_test.sh {diff |full|file }" >&2 + echo "usage: mutation_test.sh {diff |full|file |infra}" >&2 exit 2 ;; esac From baebbb92b6a0206355ff070c6d0a8c4275dd0e34 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 14:49:48 +0800 Subject: [PATCH 183/201] feat!: the Satin history gas, resource limits, gas detention and the execution-spec gate (#387) Co-authored-by: mega-putin --- .cargo/config.toml | 5 + .cargo/mutants.toml | 7 +- .claude/skills/satin-review/SKILL.md | 255 ++ .github/pull_request_template.md | 2 + .github/scripts/bench_compare.py | 576 ---- .github/scripts/bench_paired.sh | 70 - .github/workflows/benchmark.yml | 416 --- .github/workflows/build-and-test.yml | 74 +- .github/workflows/codspeed.yml | 8 +- .github/workflows/coverage.yml | 18 +- .github/workflows/exec-spec-satin.yml | 439 +++ .github/workflows/exec-spec.yml | 7 +- .github/workflows/fuzz.yml | 126 + .github/workflows/mutation.yml | 164 +- .github/workflows/on-release.yml | 4 +- .github/workflows/price-grid.yml | 63 + .github/workflows/replay-bench.yml | 269 -- .gitignore | 5 + AGENTS.md | 548 +++- ARCH.md | 3 +- Cargo.lock | 2714 ++++++++++++++--- Cargo.toml | 64 +- README.md | 16 +- REVIEW.md | 129 +- bench/replay/README.md | 132 - bench/replay/fixtures/attack_deploy.json | 151 - bench/replay/fixtures/large_defi.json | 119 - bench/replay/fixtures/log_heavy.json | 143 - bench/replay/fixtures/medium_call.json | 104 - bench/replay/fixtures/system_call.json | 86 - bench/replay/manifest.json | 47 - bench/replay/run.py | 304 -- bin/mega-evme/AGENTS.md | 26 +- bin/mega-evme/Cargo.toml | 16 +- bin/mega-evme/README.md | 90 +- bin/mega-evme/src/block/cmd.rs | 344 +++ bin/mega-evme/src/block/exec.rs | 87 + bin/mega-evme/src/block/inputs.rs | 412 +++ bin/mega-evme/src/block/legacy.rs | 204 ++ bin/mega-evme/src/block/mod.rs | 22 + bin/mega-evme/src/block/record.rs | 239 ++ bin/mega-evme/src/block/satin.rs | 238 ++ bin/mega-evme/src/block/state.rs | 567 ++++ bin/mega-evme/src/cmd.rs | 204 +- bin/mega-evme/src/common/env.rs | 100 +- bin/mega-evme/src/common/error.rs | 120 +- bin/mega-evme/src/common/hardfork.rs | 49 - bin/mega-evme/src/common/hex.rs | 63 +- bin/mega-evme/src/common/mod.rs | 5 +- bin/mega-evme/src/common/outcome.rs | 216 +- .../src/common/provider/cache_store.rs | 88 +- bin/mega-evme/src/common/provider/mod.rs | 219 +- bin/mega-evme/src/common/schedule.rs | 446 +++ bin/mega-evme/src/common/state.rs | 575 +++- bin/mega-evme/src/common/trace.rs | 128 +- bin/mega-evme/src/common/tx.rs | 283 +- bin/mega-evme/src/common/tx_override.rs | 157 +- bin/mega-evme/src/engine.rs | 221 ++ bin/mega-evme/src/lib.rs | 19 +- bin/mega-evme/src/main.rs | 16 +- bin/mega-evme/src/replay/cmd.rs | 711 +++-- bin/mega-evme/src/replay/fixture.rs | 441 --- bin/mega-evme/src/replay/hardforks.rs | 10 - bin/mega-evme/src/replay/mod.rs | 3 - bin/mega-evme/src/run/README.md | 492 --- bin/mega-evme/src/run/cmd.rs | 55 +- bin/mega-evme/src/tx/cmd.rs | 49 +- bin/mega-evme/tests/block_replay.rs | 647 ++++ bin/mega-evme/tests/common/blocks.rs | 200 ++ bin/mega-evme/tests/common/mod.rs | 19 +- bin/mega-evme/tests/differences.rs | 334 ++ bin/mega-evme/tests/dump_code.rs | 168 + .../blocks/blocks/2640/26400001.json.zst | Bin 0 -> 21070 bytes .../blocks/blocks/2640/26400007.json.zst | Bin 0 -> 15182 bytes .../blocks/blocks/2640/26400110.json.zst | Bin 0 -> 14860 bytes ...29f62d443a99baaa366699ef84f802ae5801b4.bin | Bin 0 -> 17424 bytes ...32584526f97a5ca267c8eef73a1831f53720f2.bin | Bin 0 -> 1106 bytes ...c621c8d9b020d9aa6e83879561426943aee0b0.bin | Bin 0 -> 1480 bytes ...0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin | Bin 0 -> 362 bytes ...31a5d59bde918169800b8d219754360a1f58b2.bin | Bin 0 -> 2670 bytes ...92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin | Bin 0 -> 8592 bytes ...65c80e43b953eaa41c27d9a03515fb9cad660f.bin | Bin 0 -> 5148 bytes ...81d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin | Bin 0 -> 2227 bytes ...b887f802218d9ac86f142ef0994da43ea5eeb6.bin | Bin 0 -> 515 bytes ...9fa5e552daf4719552131a0abce779daec0a5d.bin | Bin 0 -> 83 bytes ...17cb2a2327d87970645a2c1012e61f617551ee.bin | Bin 0 -> 24357 bytes ...d08af36ea1ead283270da9bf554c306a6c87b9.bin | Bin 0 -> 15686 bytes ...34f57600420d103a4401ef7555bd50b229dc55.bin | Bin 0 -> 2664 bytes ...a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin | Bin 0 -> 24314 bytes ...3516ec43590177c4009049afc16fa1bc9f8dc4.bin | Bin 0 -> 19034 bytes ...3a32662470f639863b356e5cd453b03bb0ce42.bin | Bin 0 -> 348 bytes ...5ab0b3d5c8861acb422b6fec63cf36234f36a6.bin | Bin 0 -> 170 bytes ...e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin | Bin 0 -> 1710 bytes ...ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin | Bin 0 -> 397 bytes ...2b7d433b94a4aa840e943aa9b6ada3f7847cad.bin | Bin 0 -> 1969 bytes ...61c8cca605219541f7e9bb9aadc66ee9e277fe.bin | Bin 0 -> 1969 bytes ...0c2fc6640176b13d2c10b5df218f920f3a1dc5.bin | Bin 0 -> 9995 bytes ...3c5edc085ef7ece05077c3382b8d3b367863b0.bin | Bin 0 -> 23791 bytes ...65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin | Bin 0 -> 5365 bytes ...184f4e6642e083d8031f89854e6de590c5b999.bin | Bin 0 -> 1969 bytes ...17fb06613189b4e0459b3a2263fc0ed240cf5c.bin | Bin 0 -> 5009 bytes ...23477c857b80d45c69929c1f38b031ff5d2919.bin | Bin 0 -> 5223 bytes ...a2b574f528d515f6f765506edc1205705b4139.bin | Bin 0 -> 20724 bytes ...52f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin | Bin 0 -> 97 bytes ...a262aeb634b015222134d5abfd8f7b7828276a.bin | Bin 0 -> 5692 bytes ...d09d575674eb0852c0fa3187e59e98ef977998.bin | Bin 0 -> 2059 bytes ...b722b2b22633e13900c4b13767742b9f5f5a90.bin | Bin 0 -> 141 bytes .../fixtures/test_satin_run_basic_return.json | 26 + .../fixtures/test_satin_run_codefile.json | 27 + .../tests/fixtures/test_satin_run_create.json | 29 + .../fixtures/test_satin_run_dump_inline.json | 74 + .../tests/fixtures/test_satin_run_input.json | 28 + .../fixtures/test_satin_run_prestate.json | 34 + .../tests/fixtures/test_satin_run_revert.json | 26 + .../test_satin_run_rpc_args_parse.json | 34 + .../test_satin_run_storage_override.json | 28 + .../fixtures/test_satin_run_trace_inline.json | 112 + .../tests/fixtures/test_satin_tx_create.json | 50 + .../fixtures/test_satin_tx_halt_oog.json | 51 + .../tests/fixtures/test_satin_tx_revert.json | 49 + .../test_satin_tx_value_transfer.json | 65 + bin/mega-evme/tests/integration.rs | 384 +++ bin/mega-evme/tests/legacy_line.rs | 181 ++ bin/mega-evme/tests/limits.rs | 290 ++ bin/mega-evme/tests/provider.rs | 70 +- bin/mega-evme/tests/replay_dump.rs | 9 +- bin/mega-evme/tests/replay_paths.rs | 674 ++++ bin/mega-evme/tests/satin-differences.md | 78 + bin/mega-evme/tests/state.rs | 579 +++- bin/mega-t8n/Cargo.toml | 32 - bin/mega-t8n/src/cmd.rs | 446 --- bin/mega-t8n/src/error.rs | 37 - bin/mega-t8n/src/io.rs | 119 - bin/mega-t8n/src/main.rs | 26 - bin/mega-t8n/src/types/mod.rs | 87 - bin/mega-t8n/src/types/receipt.rs | 88 - bin/mega-t8n/src/types/transaction.rs | 257 -- bin/mega-t8n/src/utils.rs | 66 - clippy.toml | 2 +- crates/mega-evm/Cargo.toml | 14 +- crates/mega-evm/README.md | 167 +- crates/mega-evm/benches/block.rs | 182 +- crates/mega-evm/benches/corpus.rs | 49 +- crates/mega-evm/benches/data/analysis.hex | 1 - crates/mega-evm/benches/data/snailtracer.hex | 1 - .../benches/fixtures/known_attack_deploy.json | 96 - crates/mega-evm/benches/transact.rs | 441 ++- crates/mega-evm/src/access/detention.rs | 1515 +++++++++ crates/mega-evm/src/access/mod.rs | 184 +- crates/mega-evm/src/access/volatile.rs | 265 ++ crates/mega-evm/src/block/chain.rs | 89 +- crates/mega-evm/src/block/eips.rs | 348 ++- crates/mega-evm/src/block/executor.rs | 669 +++- crates/mega-evm/src/block/factory.rs | 13 +- crates/mega-evm/src/block/genesis.rs | 621 ++++ crates/mega-evm/src/block/hardfork.rs | 340 +-- crates/mega-evm/src/block/l1_block_info.rs | 183 ++ crates/mega-evm/src/block/limit.rs | 671 +++- crates/mega-evm/src/block/mod.rs | 4 + crates/mega-evm/src/block/result.rs | 90 +- crates/mega-evm/src/constants.rs | 54 +- crates/mega-evm/src/evm/context.rs | 763 ++++- crates/mega-evm/src/evm/execution.rs | 1372 ++++++++- crates/mega-evm/src/evm/factory.rs | 203 +- crates/mega-evm/src/evm/frame.rs | 12 +- crates/mega-evm/src/evm/history.rs | 365 +++ crates/mega-evm/src/evm/host.rs | 724 ++--- crates/mega-evm/src/evm/inspector.rs | 410 ++- crates/mega-evm/src/evm/instructions.rs | 529 +++- crates/mega-evm/src/evm/mod.rs | 266 +- crates/mega-evm/src/evm/precompiles.rs | 311 +- crates/mega-evm/src/evm/prices.rs | 37 +- crates/mega-evm/src/evm/result.rs | 100 +- crates/mega-evm/src/evm/schedule.rs | 291 +- crates/mega-evm/src/evm/spec.rs | 16 +- crates/mega-evm/src/evm/state.rs | 178 +- crates/mega-evm/src/evm/validation.rs | 154 + crates/mega-evm/src/external/AGENTS.md | 6 +- crates/mega-evm/src/external/gas.rs | 145 +- crates/mega-evm/src/external/hasher/mod.rs | 19 + crates/mega-evm/src/external/oracle.rs | 11 + crates/mega-evm/src/external/salt.rs | 8 +- crates/mega-evm/src/external/test_utils.rs | 18 - crates/mega-evm/src/lib.rs | 89 +- crates/mega-evm/src/limit/frame_limit.rs | 412 ++- crates/mega-evm/src/limit/limit.rs | 1609 +++++++++- crates/mega-evm/src/limit/mod.rs | 576 +++- crates/mega-evm/src/limit/record.rs | 108 +- crates/mega-evm/src/system/AGENTS.md | 66 +- crates/mega-evm/src/system/control.rs | 99 +- crates/mega-evm/src/system/intercept.rs | 38 +- .../mega-evm/src/system/keyless/dispatch.rs | 509 +++- crates/mega-evm/src/system/keyless/error.rs | 112 +- crates/mega-evm/src/system/keyless/mod.rs | 114 +- crates/mega-evm/src/system/keyless/settle.rs | 383 +++ crates/mega-evm/src/system/limit_control.rs | 61 +- crates/mega-evm/src/system/mod.rs | 15 +- crates/mega-evm/src/system/oracle.rs | 141 +- crates/mega-evm/src/system/predeploys.rs | 206 ++ .../mega-evm/src/system/sequencer_registry.rs | 566 +++- crates/mega-evm/src/system/tx.rs | 268 +- crates/mega-evm/src/test_utils/bytes.rs | 22 + crates/mega-evm/src/test_utils/database.rs | 165 +- crates/mega-evm/src/test_utils/inspectors.rs | 200 +- crates/mega-evm/src/test_utils/logs.rs | 51 + crates/mega-evm/src/test_utils/mod.rs | 8 + crates/mega-evm/src/test_utils/neutral.rs | 292 ++ crates/mega-evm/src/test_utils/opcode_gen.rs | 146 +- crates/mega-evm/src/test_utils/price_guard.rs | 61 + crates/mega-evm/src/test_utils/scenario.rs | 113 +- crates/mega-evm/src/test_utils/witness.rs | 702 +++++ crates/mega-evm/src/types.rs | 6 +- crates/mega-evm/tests/_pending/README.md | 293 -- .../_pending/block_executor/block_limits.rs | 243 -- .../_pending/block_executor/inspector.rs | 424 --- .../tests/_pending/block_executor/main.rs | 5 - .../block_executor/sequencer_registry.rs | 620 ---- .../tests/_pending/compute_gas/claims.rs | 568 ---- .../tests/_pending/compute_gas/main.rs | 853 ------ .../mini_rex/access_beneficiary_balance.rs | 558 ---- .../mini_rex/block_env_access_tracking.rs | 271 -- .../_pending/mini_rex/block_env_gas_limit.rs | 713 ----- .../_pending/mini_rex/compute_gas_limit.rs | 1161 ------- .../mega-evm/tests/_pending/mini_rex/gas.rs | 536 ---- .../mega-evm/tests/_pending/mini_rex/main.rs | 10 - .../tests/_pending/mini_rex/oracle.rs | 844 ----- .../_pending/mini_rex/state_growth_limit.rs | 220 -- .../mini_rex/tx_data_and_kv_update_limit.rs | 1164 ------- crates/mega-evm/tests/_pending/rex/main.rs | 3 - crates/mega-evm/tests/_pending/rex/oracle.rs | 141 - .../tests/_pending/rex2/keyless_deploy.rs | 1824 ----------- crates/mega-evm/tests/_pending/rex2/main.rs | 4 - .../tests/_pending/rex2/oracle_hint.rs | 347 --- crates/mega-evm/tests/_pending/rex3/main.rs | 4 - .../tests/_pending/rex3/oracle_gas_limit.rs | 366 --- .../tests/_pending/rex3/system_address.rs | 164 - .../tests/_pending/rex4/access_control.rs | 1996 ------------ .../_pending/rex4/beneficiary_detention.rs | 749 ----- .../tests/_pending/rex4/create_safety.rs | 150 - .../tests/_pending/rex4/deployment.rs | 165 - .../tests/_pending/rex4/frame_limits.rs | 707 ----- .../tests/_pending/rex4/gas_detention.rs | 267 -- .../_pending/rex4/intrinsic_limit_bypass.rs | 602 ---- .../tests/_pending/rex4/keyless_deploy.rs | 263 -- .../tests/_pending/rex4/limit_control.rs | 579 ---- crates/mega-evm/tests/_pending/rex4/main.rs | 13 - .../_pending/rex4/storage_call_stipend.rs | 687 ----- .../rex5/apply_pending_changes_gas_budget.rs | 325 -- .../_pending/rex5/create2_empty_initcode.rs | 168 - .../rex5/create2_resize_gas_metering.rs | 192 -- .../mega-evm/tests/_pending/rex5/db_error.rs | 236 -- .../_pending/rex5/eip7702_state_growth.rs | 366 --- .../_pending/rex5/keyless_empty_code_logs.rs | 272 -- .../tests/_pending/rex5/keyless_fee_free.rs | 931 ------ .../rex5/keyless_gas_cap_postcap_recheck.rs | 302 -- .../_pending/rex5/keyless_replay_barrier.rs | 319 -- crates/mega-evm/tests/_pending/rex5/main.rs | 19 - .../_pending/rex5/oracle_hint_metering.rs | 527 ---- .../_pending/rex5/pre_block_system_calls.rs | 672 ---- .../tests/_pending/rex5/sandbox_accounting.rs | 777 ----- .../_pending/rex5/selfdestruct_beneficiary.rs | 442 --- .../tests/_pending/rex5/stipend_accounting.rs | 565 ---- .../_pending/rex6/beneficiary_detention.rs | 799 ----- crates/mega-evm/tests/_pending/rex6/common.rs | 69 - .../_pending/rex6/create2_metering_order.rs | 568 ---- .../rex6/eip7702_authority_accounting.rs | 981 ------ .../tests/_pending/rex6/error_paths.rs | 147 - .../_pending/rex6/fee_reward_accounting.rs | 567 ---- .../_pending/rex6/frame_local_accounting.rs | 204 -- .../rex6/keyless_sandbox_hardening.rs | 383 --- crates/mega-evm/tests/_pending/rex6/main.rs | 18 - .../rex6/oracle_hint_volatile_access.rs | 224 -- .../rex6/self_transfer_account_dedup.rs | 136 - .../rex6/sequencer_registry_rotation.rs | 398 --- .../tests/_pending/src/access/volatile.rs | 85 - crates/mega-evm/tests/_pending/src/evm/mod.rs | 111 - .../tests/_pending/src/limit/compute_gas.rs | 28 - .../tests/_pending/src/limit/data_size.rs | 26 - .../tests/_pending/src/limit/kv_update.rs | 19 - .../tests/_pending/src/limit/limit.rs | 98 - .../tests/_pending/src/sandbox/execution.rs | 159 - .../tests/_pending/src/system/control.rs | 139 - .../tests/_pending/src/system/deploy.rs | 150 - .../_pending/src/system/keyless_deploy.rs | 64 - .../_pending/src/system/limit_control.rs | 110 - .../tests/_pending/src/system/oracle.rs | 257 -- .../_pending/src/system/sequencer_registry.rs | 778 ----- crates/mega-evm/tests/block/activation.rs | 229 ++ crates/mega-evm/tests/block/bucket_ids.rs | 295 ++ .../mega-evm/tests/block/building_policy.rs | 310 ++ crates/mega-evm/tests/block/common.rs | 273 +- crates/mega-evm/tests/block/counters.rs | 254 +- crates/mega-evm/tests/block/deposits.rs | 209 ++ crates/mega-evm/tests/block/detention.rs | 83 + crates/mega-evm/tests/block/eips.rs | 456 ++- crates/mega-evm/tests/block/external_envs.rs | 108 + crates/mega-evm/tests/block/factory.rs | 143 +- crates/mega-evm/tests/block/inspector.rs | 317 +- crates/mega-evm/tests/block/l1_attributes.rs | 144 + crates/mega-evm/tests/block/limits.rs | 303 +- crates/mega-evm/tests/block/main.rs | 18 + crates/mega-evm/tests/block/predeploys.rs | 274 ++ .../mega-evm/tests/block/receipt_goldens.rs | 321 ++ crates/mega-evm/tests/block/receipts.rs | 50 +- crates/mega-evm/tests/block/rules.rs | 117 +- crates/mega-evm/tests/block/salt.rs | 20 +- crates/mega-evm/tests/block/schedule.rs | 201 +- .../tests/block/sequencer_registry.rs | 807 +++++ crates/mega-evm/tests/block/sequences.rs | 139 + crates/mega-evm/tests/block/stale.rs | 186 ++ crates/mega-evm/tests/block/state_gas.rs | 77 + .../mega-evm/tests/block/system_tx_budgets.rs | 189 ++ crates/mega-evm/tests/block/transfer_logs.rs | 317 ++ crates/mega-evm/tests/block/witness/basics.rs | 276 ++ .../mega-evm/tests/block/witness/harness.rs | 676 ++++ .../mega-evm/tests/block/witness/history.rs | 60 + .../mega-evm/tests/block/witness/keyless.rs | 233 ++ crates/mega-evm/tests/block/witness/mod.rs | 16 + crates/mega-evm/tests/block/witness/oracle.rs | 478 +++ .../tests/block/witness/predeploys.rs | 117 + crates/mega-evm/tests/block/witness/skips.rs | 233 ++ crates/mega-evm/tests/block/witness/state.rs | 552 ++++ crates/mega-evm/tests/block/witness/stops.rs | 197 ++ crates/mega-evm/tests/block/witness/system.rs | 114 + crates/mega-evm/tests/fuzz/blocks.rs | 534 ++++ crates/mega-evm/tests/fuzz/differential.rs | 252 ++ crates/mega-evm/tests/fuzz/gen/case.rs | 328 ++ crates/mega-evm/tests/fuzz/gen/mod.rs | 153 + crates/mega-evm/tests/fuzz/gen/program.rs | 932 ++++++ crates/mega-evm/tests/fuzz/gen/tx.rs | 790 +++++ crates/mega-evm/tests/fuzz/gen/world.rs | 366 +++ crates/mega-evm/tests/fuzz/harness.rs | 401 +++ crates/mega-evm/tests/fuzz/keyless.rs | 342 +++ crates/mega-evm/tests/fuzz/main.rs | 17 + crates/mega-evm/tests/fuzz/prices.rs | 199 ++ crates/mega-evm/tests/fuzz/properties.rs | 633 ++++ crates/mega-evm/tests/fuzz/regressions.rs | 147 + crates/mega-evm/tests/fuzz/render.rs | 56 + crates/mega-evm/tests/satin/common.rs | 182 +- crates/mega-evm/tests/satin/compute_gas.rs | 705 +++++ crates/mega-evm/tests/satin/contract_size.rs | 62 +- crates/mega-evm/tests/satin/corpus.rs | 59 + crates/mega-evm/tests/satin/count_order.rs | 83 + crates/mega-evm/tests/satin/create_opcodes.rs | 231 ++ crates/mega-evm/tests/satin/data_size.rs | 1518 +++++++++ .../mega-evm/tests/satin/data_size_counts.rs | 406 +++ crates/mega-evm/tests/satin/deposit_charge.rs | 623 ++++ .../tests/satin/detained_transfers.rs | 580 ++++ crates/mega-evm/tests/satin/detention.rs | 1751 +++++++++++ crates/mega-evm/tests/satin/equivalence.rs | 580 +++- crates/mega-evm/tests/satin/failed_deposit.rs | 286 ++ crates/mega-evm/tests/satin/floor_exempt.rs | 216 ++ crates/mega-evm/tests/satin/history_bytes.rs | 983 ++++++ .../mega-evm/tests/satin/history_exemption.rs | 328 ++ crates/mega-evm/tests/satin/history_gas.rs | 345 +++ .../mega-evm/tests/satin/history_reservoir.rs | 308 ++ .../mega-evm/tests/satin/inherited_costs.rs | 240 ++ crates/mega-evm/tests/satin/inspector.rs | 296 +- .../tests/satin/inspector_cheatcodes.rs | 423 +++ .../mega-evm/tests/satin/inspector_limits.rs | 305 ++ .../tests/satin/inspector_settlement.rs | 862 ++++++ crates/mega-evm/tests/satin/intrinsic.rs | 319 +- .../mega-evm/tests/satin/limit_exemption.rs | 164 + crates/mega-evm/tests/satin/limit_stop.rs | 187 ++ crates/mega-evm/tests/satin/main.rs | 33 + crates/mega-evm/tests/satin/neutral.rs | 374 +++ crates/mega-evm/tests/satin/outcome.rs | 60 +- .../mega-evm/tests/satin/pool_validation.rs | 634 ++++ crates/mega-evm/tests/satin/precompile_gas.rs | 10 +- crates/mega-evm/tests/satin/pricing-table.md | 64 +- crates/mega-evm/tests/satin/pricing_table.rs | 64 +- crates/mega-evm/tests/satin/salt.rs | 263 +- .../mega-evm/tests/satin/salt_delegation.rs | 31 +- crates/mega-evm/tests/satin/salt_deposit.rs | 33 +- crates/mega-evm/tests/satin/salt_failure.rs | 17 +- crates/mega-evm/tests/satin/salt_refund.rs | 213 +- crates/mega-evm/tests/satin/schedule.rs | 196 +- ...atin__corpus__corpus_outcomes_and_gas.snap | 96 + crates/mega-evm/tests/satin/spec_numbers.rs | 499 +++ crates/mega-evm/tests/satin/state_growth.rs | 638 ++++ crates/mega-evm/tests/satin/static_callee.rs | 4 +- crates/mega-evm/tests/satin/stops.rs | 1636 ++++++++++ .../tests/satin/storage_call_stipend.rs | 798 +++++ crates/mega-evm/tests/satin/strategic_stop.rs | 369 ++- .../tests/satin/synthetic_frame_gas.rs | 140 +- crates/mega-evm/tests/satin/system_call.rs | 509 ++++ crates/mega-evm/tests/satin/transfer_logs.rs | 1288 ++++++++ .../mega-evm/tests/satin/volatile_access.rs | 865 ++++++ crates/mega-evm/tests/satin/withheld_gas.rs | 1848 +++++++++++ crates/mega-evm/tests/satin/write_records.rs | 1020 ++++++- crates/mega-evm/tests/shared/snapshot.rs | 50 + .../mega-evm/tests/system/access_control.rs | 691 +++++ crates/mega-evm/tests/system/common.rs | 147 +- crates/mega-evm/tests/system/control.rs | 13 +- crates/mega-evm/tests/system/dispatch.rs | 75 +- .../mega-evm/tests/system/keyless/charges.rs | 347 +++ .../mega-evm/tests/system/keyless/deploy.rs | 928 ++++++ .../tests/system/keyless/detention.rs | 686 +++++ .../tests/system/keyless/differential.rs | 1051 +++++++ .../{keyless.rs => keyless/dispatch.rs} | 96 +- crates/mega-evm/tests/system/keyless/frame.rs | 386 +++ .../tests/system/keyless/inspector.rs | 420 +++ .../tests/system/keyless/interface.rs | 31 + .../mega-evm/tests/system/keyless/limits.rs | 525 ++++ crates/mega-evm/tests/system/keyless/mod.rs | 328 ++ .../tests/system/keyless/precedence.rs | 381 +++ crates/mega-evm/tests/system/keyless/rules.rs | 1170 +++++++ ...erential__keyless_differential_record.snap | 153 + crates/mega-evm/tests/system/limit_control.rs | 69 +- crates/mega-evm/tests/system/main.rs | 6 + crates/mega-evm/tests/system/oracle.rs | 343 ++- .../mega-evm/tests/system/oracle_storage.rs | 831 +++++ crates/mega-evm/tests/system/predeploys.rs | 182 ++ .../tests/system/remaining_compute_gas.rs | 597 ++++ crates/mega-evm/tests/system/system_tx.rs | 434 ++- crates/mega-evm/tests/tracers/gas.rs | 197 ++ crates/mega-evm/tests/tracers/harness.rs | 793 +++++ crates/mega-evm/tests/tracers/main.rs | 40 + crates/mega-evm/tests/tracers/scenarios.rs | 952 ++++++ ...acers__harness__create__call_with_log.snap | 14 + ...acers__harness__create__prestate_diff.snap | 20 + ...first_frame_start_stop__call_with_log.snap | 15 + ...first_frame_start_stop__prestate_diff.snap | 16 + ...p_caught_by_the_parent__call_with_log.snap | 26 + ...p_caught_by_the_parent__prestate_diff.snap | 25 + ...cers__harness__deposit__call_with_log.snap | 26 + ...cers__harness__deposit__prestate_diff.snap | 24 + ...es_again_in_the_parent__call_with_log.snap | 28 + ...es_again_in_the_parent__prestate_diff.snap | 16 + ...sses_again_in_the_parent__struct_logs.snap | 1119 +++++++ ..._harness__eth_transfer__call_with_log.snap | 26 + ..._harness__eth_transfer__prestate_diff.snap | 23 + ...me_budget_child_revert__call_with_log.snap | 35 + ...me_budget_child_revert__prestate_diff.snap | 16 + ...s__identity_precompile__call_with_log.snap | 14 + ...s__identity_precompile__prestate_diff.snap | 16 + ...rness__keyless_refused__call_with_log.snap | 15 + ...rness__keyless_refused__prestate_diff.snap | 16 + ...rness__keyless_success__call_with_log.snap | 26 + ...rness__keyless_success__prestate_diff.snap | 26 + ...s__nested_inner_revert__call_with_log.snap | 34 + ...s__nested_inner_revert__prestate_diff.snap | 16 + ...ness__precompile_child__call_with_log.snap | 24 + ...ness__precompile_child__prestate_diff.snap | 16 + ...ness__reservoir_sstore__call_with_log.snap | 13 + ...ness__reservoir_sstore__prestate_diff.snap | 25 + ...rness__sstore_new_slot__call_with_log.snap | 13 + ...rness__sstore_new_slot__prestate_diff.snap | 25 + ...s__timestamp_detention__call_with_log.snap | 15 + ...s__timestamp_detention__prestate_diff.snap | 16 + ...ess__timestamp_detention__struct_logs.snap | 235 ++ crates/mega-state-test/AGENTS.md | 56 +- crates/mega-state-test/Cargo.toml | 37 +- crates/mega-state-test/DEVIATIONS.md | 140 + crates/mega-state-test/README.md | 144 + .../mega-state-test/src/blockchain/chain.rs | 540 ++++ .../mega-state-test/src/blockchain/fixture.rs | 184 ++ crates/mega-state-test/src/blockchain/mod.rs | 840 +++++ .../mega-state-test/src/blockchain/skips.rs | 358 +++ crates/mega-state-test/src/deviations.rs | 1521 +++++++++ crates/mega-state-test/src/exceptions.rs | 322 ++ crates/mega-state-test/src/fork.rs | 101 + crates/mega-state-test/src/lib.rs | 39 +- crates/mega-state-test/src/mode.rs | 198 ++ crates/mega-state-test/src/roots.rs | 167 + crates/mega-state-test/src/runner.rs | 2005 +++++------- crates/mega-state-test/src/skips.rs | 113 + .../mega-state-test/src/types/account_info.rs | 20 - .../mega-state-test/src/types/deserializer.rs | 44 - crates/mega-state-test/src/types/env.rs | 91 - crates/mega-state-test/src/types/error.rs | 66 - crates/mega-state-test/src/types/mega_env.rs | 92 - crates/mega-state-test/src/types/mod.rs | 32 - crates/mega-state-test/src/types/spec.rs | 235 -- crates/mega-state-test/src/types/test.rs | 318 -- .../src/types/test_authorization.rs | 75 - .../mega-state-test/src/types/test_suite.rs | 8 - crates/mega-state-test/src/types/test_unit.rs | 163 - .../mega-state-test/src/types/transaction.rs | 164 - crates/mega-state-test/src/utils.rs | 122 - crates/mega-state-test/src/witness.rs | 251 ++ crates/mega-state-test/tests/bench_fixture.rs | 27 - crates/mega-state-test/tests/blockchain.rs | 668 ++++ .../mega-state-test/tests/dump_roundtrip.rs | 175 -- crates/mega-state-test/tests/hardening.rs | 348 --- crates/mega-state-test/tests/replay_corpus.rs | 45 - crates/mega-state-test/tests/runner.rs | 501 +++ crates/mega-state-test/tests/witness.rs | 184 ++ crates/state-test/AGENTS.md | 12 +- crates/state-test/Cargo.toml | 16 +- crates/state-test/README.md | 31 +- crates/state-test/src/btest.rs | 199 ++ crates/state-test/src/compare.txt | 85 - crates/state-test/src/compare_failed.txt | 85 - crates/state-test/src/main.rs | 401 +-- crates/state-test/tests/cli.rs | 322 ++ crates/state-test/tests/cli_exit.rs | 101 - crates/system-contracts/AGENTS.md | 9 +- crates/system-contracts/build.rs | 43 +- .../contracts/interfaces/IKeylessDeploy.sol | 81 +- .../interfaces/IMegaLimitControl.sol | 10 +- .../system-contracts/test/KeylessDeploy.t.sol | 59 + .../test/MegaAccessControl.t.sol | 76 + .../test/MegaLimitControl.t.sol | 66 + docs/mega-evme/commands/replay.md | 154 +- docs/mega-evme/commands/run.md | 34 +- docs/mega-evme/commands/tx.md | 22 +- .../mega-evme/configuration/chain-and-spec.md | 120 +- .../configuration/state-management.md | 53 +- docs/mega-evme/cookbook.md | 32 + docs/mega-evme/overview.md | 40 +- docs/spec/SUMMARY.md | 2 +- docs/spec/glossary.md | 46 +- docs/spec/hardfork-spec.md | 30 +- docs/spec/overview.md | 13 +- docs/spec/system-contracts/keyless-deploy.md | 48 + docs/spec/upgrades/overview.md | 6 +- docs/spec/upgrades/rex6.md | 2 +- docs/spec/upgrades/rex7.md | 47 - docs/spec/upgrades/satin.md | 1103 +++++++ mutants/README.md | 34 +- mutants/operators/spec-gate/generate.py | 22 +- mutants/operators/spec-gate/spec-gate.rules | 1 - mutants/suppressions.toml | 151 +- scripts/fuzz_price_monotonic.py | 74 + scripts/keyless_deploy.sh | 236 -- scripts/mutation_gate.py | 468 ++- scripts/mutation_test.sh | 131 +- scripts/price_grid.sh | 133 + scripts/test_mutation_gate.py | 671 ++++ scripts/umutate.py | 86 +- 531 files changed, 90504 insertions(+), 45454 deletions(-) create mode 100644 .cargo/config.toml create mode 100644 .claude/skills/satin-review/SKILL.md delete mode 100644 .github/scripts/bench_compare.py delete mode 100755 .github/scripts/bench_paired.sh delete mode 100644 .github/workflows/benchmark.yml create mode 100644 .github/workflows/exec-spec-satin.yml create mode 100644 .github/workflows/fuzz.yml create mode 100644 .github/workflows/price-grid.yml delete mode 100644 .github/workflows/replay-bench.yml delete mode 100644 bench/replay/README.md delete mode 100644 bench/replay/fixtures/attack_deploy.json delete mode 100644 bench/replay/fixtures/large_defi.json delete mode 100644 bench/replay/fixtures/log_heavy.json delete mode 100644 bench/replay/fixtures/medium_call.json delete mode 100644 bench/replay/fixtures/system_call.json delete mode 100644 bench/replay/manifest.json delete mode 100644 bench/replay/run.py create mode 100644 bin/mega-evme/src/block/cmd.rs create mode 100644 bin/mega-evme/src/block/exec.rs create mode 100644 bin/mega-evme/src/block/inputs.rs create mode 100644 bin/mega-evme/src/block/legacy.rs create mode 100644 bin/mega-evme/src/block/mod.rs create mode 100644 bin/mega-evme/src/block/record.rs create mode 100644 bin/mega-evme/src/block/satin.rs create mode 100644 bin/mega-evme/src/block/state.rs delete mode 100644 bin/mega-evme/src/common/hardfork.rs create mode 100644 bin/mega-evme/src/common/schedule.rs create mode 100644 bin/mega-evme/src/engine.rs delete mode 100644 bin/mega-evme/src/replay/fixture.rs delete mode 100644 bin/mega-evme/src/replay/hardforks.rs delete mode 100644 bin/mega-evme/src/run/README.md create mode 100644 bin/mega-evme/tests/block_replay.rs create mode 100644 bin/mega-evme/tests/common/blocks.rs create mode 100644 bin/mega-evme/tests/differences.rs create mode 100644 bin/mega-evme/tests/dump_code.rs create mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst create mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst create mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/39/3927f2a4803c5e18153ff5742d0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/3f/3f77685d5db0f99bf10bf1f0cd31a5d59bde918169800b8d219754360a1f58b2.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/45/459716bd908d0ccf47599b42af92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/4d/4d9be648c5bf39973670d9f8b481d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6f/6f5dd02efc31c07c6d99d8d36417cb2a2327d87970645a2c1012e61f617551ee.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6f/6f77a5c9db7cfef9a4d05faff0d08af36ea1ead283270da9bf554c306a6c87b9.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/78/78dd15e7753d3e60a8003bda403516ec43590177c4009049afc16fa1bc9f8dc4.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/7e/7eff9da33cc2042d53428940c03a32662470f639863b356e5cd453b03bb0ce42.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/8e/8e3fe7a416d3e5f3b7be74ddd4e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/a2/a220f51e097a419ab9cc99098261c8cca605219541f7e9bb9aadc66ee9e277fe.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/ab/ab5d51e60951e30c2843d8fa783c5edc085ef7ece05077c3382b8d3b367863b0.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/cc/cc7e366c8e998368260791347f23477c857b80d45c69929c1f38b031ff5d2919.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f5/f57acd40259872606d76197ef052f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f7/f7bdad905f90d6e7cb07182aeba262aeb634b015222134d5abfd8f7b7828276a.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/fa/fa8c9db6c6cab7108dea276f4cd09d575674eb0852c0fa3187e59e98ef977998.bin create mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/fd/fdf85d183a122fe611bc878683b722b2b22633e13900c4b13767742b9f5f5a90.bin create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_codefile.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_create.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_input.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_prestate.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_revert.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_tx_create.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_tx_revert.json create mode 100644 bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json create mode 100644 bin/mega-evme/tests/legacy_line.rs create mode 100644 bin/mega-evme/tests/limits.rs create mode 100644 bin/mega-evme/tests/replay_paths.rs create mode 100644 bin/mega-evme/tests/satin-differences.md delete mode 100644 bin/mega-t8n/Cargo.toml delete mode 100644 bin/mega-t8n/src/cmd.rs delete mode 100644 bin/mega-t8n/src/error.rs delete mode 100644 bin/mega-t8n/src/io.rs delete mode 100644 bin/mega-t8n/src/main.rs delete mode 100644 bin/mega-t8n/src/types/mod.rs delete mode 100644 bin/mega-t8n/src/types/receipt.rs delete mode 100644 bin/mega-t8n/src/types/transaction.rs delete mode 100644 bin/mega-t8n/src/utils.rs delete mode 100644 crates/mega-evm/benches/data/analysis.hex delete mode 100644 crates/mega-evm/benches/data/snailtracer.hex delete mode 100644 crates/mega-evm/benches/fixtures/known_attack_deploy.json create mode 100644 crates/mega-evm/src/access/detention.rs create mode 100644 crates/mega-evm/src/access/volatile.rs create mode 100644 crates/mega-evm/src/block/genesis.rs create mode 100644 crates/mega-evm/src/block/l1_block_info.rs create mode 100644 crates/mega-evm/src/evm/history.rs create mode 100644 crates/mega-evm/src/evm/validation.rs create mode 100644 crates/mega-evm/src/system/keyless/settle.rs create mode 100644 crates/mega-evm/src/system/predeploys.rs create mode 100644 crates/mega-evm/src/test_utils/logs.rs create mode 100644 crates/mega-evm/src/test_utils/neutral.rs create mode 100644 crates/mega-evm/src/test_utils/price_guard.rs create mode 100644 crates/mega-evm/src/test_utils/witness.rs delete mode 100644 crates/mega-evm/tests/_pending/README.md delete mode 100644 crates/mega-evm/tests/_pending/block_executor/block_limits.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/inspector.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/main.rs delete mode 100644 crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs delete mode 100644 crates/mega-evm/tests/_pending/compute_gas/claims.rs delete mode 100644 crates/mega-evm/tests/_pending/compute_gas/main.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/gas.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/main.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/oracle.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex/oracle.rs delete mode 100644 crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/rex2/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex2/oracle_hint.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs delete mode 100644 crates/mega-evm/tests/_pending/rex3/system_address.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/access_control.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/create_safety.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/deployment.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/frame_limits.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/gas_detention.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/limit_control.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/db_error.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs delete mode 100644 crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/common.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/error_paths.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/main.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs delete mode 100644 crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs delete mode 100644 crates/mega-evm/tests/_pending/src/access/volatile.rs delete mode 100644 crates/mega-evm/tests/_pending/src/evm/mod.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/compute_gas.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/data_size.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/kv_update.rs delete mode 100644 crates/mega-evm/tests/_pending/src/limit/limit.rs delete mode 100644 crates/mega-evm/tests/_pending/src/sandbox/execution.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/control.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/limit_control.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/oracle.rs delete mode 100644 crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs create mode 100644 crates/mega-evm/tests/block/activation.rs create mode 100644 crates/mega-evm/tests/block/bucket_ids.rs create mode 100644 crates/mega-evm/tests/block/building_policy.rs create mode 100644 crates/mega-evm/tests/block/deposits.rs create mode 100644 crates/mega-evm/tests/block/detention.rs create mode 100644 crates/mega-evm/tests/block/external_envs.rs create mode 100644 crates/mega-evm/tests/block/l1_attributes.rs create mode 100644 crates/mega-evm/tests/block/predeploys.rs create mode 100644 crates/mega-evm/tests/block/receipt_goldens.rs create mode 100644 crates/mega-evm/tests/block/sequencer_registry.rs create mode 100644 crates/mega-evm/tests/block/sequences.rs create mode 100644 crates/mega-evm/tests/block/stale.rs create mode 100644 crates/mega-evm/tests/block/state_gas.rs create mode 100644 crates/mega-evm/tests/block/system_tx_budgets.rs create mode 100644 crates/mega-evm/tests/block/transfer_logs.rs create mode 100644 crates/mega-evm/tests/block/witness/basics.rs create mode 100644 crates/mega-evm/tests/block/witness/harness.rs create mode 100644 crates/mega-evm/tests/block/witness/history.rs create mode 100644 crates/mega-evm/tests/block/witness/keyless.rs create mode 100644 crates/mega-evm/tests/block/witness/mod.rs create mode 100644 crates/mega-evm/tests/block/witness/oracle.rs create mode 100644 crates/mega-evm/tests/block/witness/predeploys.rs create mode 100644 crates/mega-evm/tests/block/witness/skips.rs create mode 100644 crates/mega-evm/tests/block/witness/state.rs create mode 100644 crates/mega-evm/tests/block/witness/stops.rs create mode 100644 crates/mega-evm/tests/block/witness/system.rs create mode 100644 crates/mega-evm/tests/fuzz/blocks.rs create mode 100644 crates/mega-evm/tests/fuzz/differential.rs create mode 100644 crates/mega-evm/tests/fuzz/gen/case.rs create mode 100644 crates/mega-evm/tests/fuzz/gen/mod.rs create mode 100644 crates/mega-evm/tests/fuzz/gen/program.rs create mode 100644 crates/mega-evm/tests/fuzz/gen/tx.rs create mode 100644 crates/mega-evm/tests/fuzz/gen/world.rs create mode 100644 crates/mega-evm/tests/fuzz/harness.rs create mode 100644 crates/mega-evm/tests/fuzz/keyless.rs create mode 100644 crates/mega-evm/tests/fuzz/main.rs create mode 100644 crates/mega-evm/tests/fuzz/prices.rs create mode 100644 crates/mega-evm/tests/fuzz/properties.rs create mode 100644 crates/mega-evm/tests/fuzz/regressions.rs create mode 100644 crates/mega-evm/tests/fuzz/render.rs create mode 100644 crates/mega-evm/tests/satin/compute_gas.rs create mode 100644 crates/mega-evm/tests/satin/corpus.rs create mode 100644 crates/mega-evm/tests/satin/count_order.rs create mode 100644 crates/mega-evm/tests/satin/create_opcodes.rs create mode 100644 crates/mega-evm/tests/satin/data_size.rs create mode 100644 crates/mega-evm/tests/satin/data_size_counts.rs create mode 100644 crates/mega-evm/tests/satin/deposit_charge.rs create mode 100644 crates/mega-evm/tests/satin/detained_transfers.rs create mode 100644 crates/mega-evm/tests/satin/detention.rs create mode 100644 crates/mega-evm/tests/satin/failed_deposit.rs create mode 100644 crates/mega-evm/tests/satin/floor_exempt.rs create mode 100644 crates/mega-evm/tests/satin/history_bytes.rs create mode 100644 crates/mega-evm/tests/satin/history_exemption.rs create mode 100644 crates/mega-evm/tests/satin/history_gas.rs create mode 100644 crates/mega-evm/tests/satin/history_reservoir.rs create mode 100644 crates/mega-evm/tests/satin/inherited_costs.rs create mode 100644 crates/mega-evm/tests/satin/inspector_cheatcodes.rs create mode 100644 crates/mega-evm/tests/satin/inspector_limits.rs create mode 100644 crates/mega-evm/tests/satin/inspector_settlement.rs create mode 100644 crates/mega-evm/tests/satin/limit_exemption.rs create mode 100644 crates/mega-evm/tests/satin/limit_stop.rs create mode 100644 crates/mega-evm/tests/satin/neutral.rs create mode 100644 crates/mega-evm/tests/satin/pool_validation.rs create mode 100644 crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap create mode 100644 crates/mega-evm/tests/satin/spec_numbers.rs create mode 100644 crates/mega-evm/tests/satin/state_growth.rs create mode 100644 crates/mega-evm/tests/satin/stops.rs create mode 100644 crates/mega-evm/tests/satin/storage_call_stipend.rs create mode 100644 crates/mega-evm/tests/satin/system_call.rs create mode 100644 crates/mega-evm/tests/satin/transfer_logs.rs create mode 100644 crates/mega-evm/tests/satin/volatile_access.rs create mode 100644 crates/mega-evm/tests/satin/withheld_gas.rs create mode 100644 crates/mega-evm/tests/shared/snapshot.rs create mode 100644 crates/mega-evm/tests/system/access_control.rs create mode 100644 crates/mega-evm/tests/system/keyless/charges.rs create mode 100644 crates/mega-evm/tests/system/keyless/deploy.rs create mode 100644 crates/mega-evm/tests/system/keyless/detention.rs create mode 100644 crates/mega-evm/tests/system/keyless/differential.rs rename crates/mega-evm/tests/system/{keyless.rs => keyless/dispatch.rs} (66%) create mode 100644 crates/mega-evm/tests/system/keyless/frame.rs create mode 100644 crates/mega-evm/tests/system/keyless/inspector.rs create mode 100644 crates/mega-evm/tests/system/keyless/interface.rs create mode 100644 crates/mega-evm/tests/system/keyless/limits.rs create mode 100644 crates/mega-evm/tests/system/keyless/mod.rs create mode 100644 crates/mega-evm/tests/system/keyless/precedence.rs create mode 100644 crates/mega-evm/tests/system/keyless/rules.rs create mode 100644 crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap create mode 100644 crates/mega-evm/tests/system/oracle_storage.rs create mode 100644 crates/mega-evm/tests/system/predeploys.rs create mode 100644 crates/mega-evm/tests/system/remaining_compute_gas.rs create mode 100644 crates/mega-evm/tests/tracers/gas.rs create mode 100644 crates/mega-evm/tests/tracers/harness.rs create mode 100644 crates/mega-evm/tests/tracers/main.rs create mode 100644 crates/mega-evm/tests/tracers/scenarios.rs create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__struct_logs.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__call_with_log.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__prestate_diff.snap create mode 100644 crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__struct_logs.snap create mode 100644 crates/mega-state-test/DEVIATIONS.md create mode 100644 crates/mega-state-test/README.md create mode 100644 crates/mega-state-test/src/blockchain/chain.rs create mode 100644 crates/mega-state-test/src/blockchain/fixture.rs create mode 100644 crates/mega-state-test/src/blockchain/mod.rs create mode 100644 crates/mega-state-test/src/blockchain/skips.rs create mode 100644 crates/mega-state-test/src/deviations.rs create mode 100644 crates/mega-state-test/src/exceptions.rs create mode 100644 crates/mega-state-test/src/fork.rs create mode 100644 crates/mega-state-test/src/mode.rs create mode 100644 crates/mega-state-test/src/roots.rs create mode 100644 crates/mega-state-test/src/skips.rs delete mode 100644 crates/mega-state-test/src/types/account_info.rs delete mode 100644 crates/mega-state-test/src/types/deserializer.rs delete mode 100644 crates/mega-state-test/src/types/env.rs delete mode 100644 crates/mega-state-test/src/types/error.rs delete mode 100644 crates/mega-state-test/src/types/mega_env.rs delete mode 100644 crates/mega-state-test/src/types/mod.rs delete mode 100644 crates/mega-state-test/src/types/spec.rs delete mode 100644 crates/mega-state-test/src/types/test.rs delete mode 100644 crates/mega-state-test/src/types/test_authorization.rs delete mode 100644 crates/mega-state-test/src/types/test_suite.rs delete mode 100644 crates/mega-state-test/src/types/test_unit.rs delete mode 100644 crates/mega-state-test/src/types/transaction.rs delete mode 100644 crates/mega-state-test/src/utils.rs create mode 100644 crates/mega-state-test/src/witness.rs delete mode 100644 crates/mega-state-test/tests/bench_fixture.rs create mode 100644 crates/mega-state-test/tests/blockchain.rs delete mode 100644 crates/mega-state-test/tests/dump_roundtrip.rs delete mode 100644 crates/mega-state-test/tests/hardening.rs delete mode 100644 crates/mega-state-test/tests/replay_corpus.rs create mode 100644 crates/mega-state-test/tests/runner.rs create mode 100644 crates/mega-state-test/tests/witness.rs create mode 100644 crates/state-test/src/btest.rs delete mode 100644 crates/state-test/src/compare.txt delete mode 100644 crates/state-test/src/compare_failed.txt create mode 100644 crates/state-test/tests/cli.rs delete mode 100644 crates/state-test/tests/cli_exit.rs create mode 100644 crates/system-contracts/test/KeylessDeploy.t.sol create mode 100644 crates/system-contracts/test/MegaAccessControl.t.sol create mode 100644 crates/system-contracts/test/MegaLimitControl.t.sol delete mode 100644 docs/spec/upgrades/rex7.md create mode 100644 docs/spec/upgrades/satin.md create mode 100755 scripts/fuzz_price_monotonic.py delete mode 100755 scripts/keyless_deploy.sh create mode 100755 scripts/price_grid.sh create mode 100644 scripts/test_mutation_gate.py diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..4c056702c --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,5 @@ +# A `cargo update` picks, for each dependency, the newest release whose declared `rust-version` the +# workspace's own (1.94) builds, so the lock stays on the declared minimum toolchain; CI's msrv +# job checks it there. Resolver "2" would otherwise pick the newest release whatever it declares. +[resolver] +incompatible-rust-versions = "fallback" diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 840fddfda..4c354b6d9 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -34,8 +34,11 @@ exclude_globs = [ ] # Give slow EVM-execution tests headroom before a mutant is ruled a timeout -# (a timeout is treated as "could not decide", not as a survivor). -minimum_test_timeout = 120 +# (a timeout is treated as "could not decide", not as a survivor). The floor +# covers CI, where mutants build and test in parallel on one runner: a mutant +# caught only by a test late in the order can take three times the unmutated +# baseline to reach it. +minimum_test_timeout = 300 timeout_multiplier = 3.0 # Seed each scratch build directory from ./target so mutant builds reuse the diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md new file mode 100644 index 000000000..5b40e67ff --- /dev/null +++ b/.claude/skills/satin-review/SKILL.md @@ -0,0 +1,255 @@ +--- +name: satin-review +description: Guide for reviewing the Satin engine pull request (#385) in megaeth-labs/mega-evm, after the stacked pull requests merged down into it. Use when reviewing #385 or the Satin engine, or when the user says "review satin". Gives the scope, the module map with the invariants to check, the reading order, how to rate a finding and the decisions already made. Temporary: removed before the Satin pull request merges. +--- + +# Reviewing the Satin engine (pull request #385) + +This guide is temporary. +It is deleted before the Satin pull request merges, so nothing else may link to it. +It is a map: where each part of the engine lives, what to check there, and what is already decided. +Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them and does not restate them. +[`REVIEW.md`](../../../REVIEW.md) is the repository's own review rubric; its consensus-critical list overlaps the checks below. + +## What is under review + +- The Satin engine, in pull request #385 (`satin` is the base branch; the diff range is `satin..`), judged at its final state once the stacked pull requests #386–#400 and #404 have merged down into it. +- Judge the final code. + A defect an earlier commit introduced and a later one fixed is not a defect; history only explains why something is as it is. + A test deleted or parked in an intermediate commit is not a finding either: test completeness is judged on the whole. +- Satin is the first spec of a line, so keep the extension points a line needs (spec-keyed constants, a spec argument); a later fork that first needs configuration parameters adds a mechanism for them then. + Satin is a new spec: simpler semantics win over parity with the legacy engine. +- Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. + Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. +- Fork code: the `megaeth-labs/revm` (`v40.0.3-mega.4`) and `megaeth-labs/op-revm` (`v20.0.0-mega.3`) forks at their tags are pinned dependencies with their own review; their diff is not part of this pull request. + A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. + The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). +- Where code belongs: upstream revm first, then the fork, then mega-evm. + The fork is only for data from the middle of revm's own flow that mega-evm cannot reach from outside; what can be done at a boundary mega-evm owns (frame start or end, the Host, the handler, the inspect path) belongs in mega-evm. + For each mechanism, ask whether it sits in the cheapest layer. +- The OP base may move (Karst to a later OP fork) before launch; a finding that depends on Karst specifics should say so. + +## Running the checks + +Commands are in [`AGENTS.md`, "Build & Development Commands"](../../../AGENTS.md#build--development-commands) and the gates in [`AGENTS.md`, "Test Gates"](../../../AGENTS.md#test-gates). +Four notes that are easy to miss: + +- the `mega-evme` tests run with `--manifest-path bin/mega-evme/Cargo.toml`, not `-p`; +- run the suite with `MEGA_SATIN_CPSB` and `MEGA_SATIN_CPHB` unset, or the tests that pin the spec's byte prices skip; +- after any test change, run `scripts/price_grid.sh --pr`; +- the execution-spec gate needs Ethereum's fixture releases, at the versions `.github/workflows/exec-spec-satin.yml` downloads. + +Evidence that a change alters no result: `state-test --mode satin --json-outcome` at two commits, detached, sorted and compared byte for byte, plus the gates and the byte-price grid. +A golden or snapshot changes only for a stated reason: regenerate it and read the diff. + +## Reading order + +1. The consensus core: limits (the vocabulary of lane, stop and crossing), then execution and frames with gas detention, then the block executor, then the system contracts and system address. +2. The gas schedule and pricing. +3. The inspector contract. +4. The node surface, validation and the witness. +5. Tools, tests, goldens and CI. Skim the goldens and snapshots; read what changes them. + +Skim without reading: the SALT bucket-hasher internals, the generated pricing table, the tracer snapshots, the receipt goldens and the keyless differential digest. +The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; each entry names which to read first. +A test name or a line count is not a reason to trust the code: read the code against the spec. + +## Glossary of the terms the checks use + +- **Live system address**: the address the `SequencerRegistry` names (`_currentSystemAddress`). + `MEGA_SYSTEM_ADDRESS` in code is only the default a test's registry names (`test_utils::MemoryDatabase::sequencer_registry`). +- **Pre-block caller**: `0xff…fe`, the EIP-4788 system address, the caller of the pre-block system calls. + It is a different address from the live system address. +- **MST** (Mega System Transaction): a signed legacy transaction from the live system address to a whitelisted system contract (today the Oracle), promoted to a deposit by the engine. +- **System-originated** (spec §19, `originates_from_the_protocol` in `src/system/tx.rs`), decided from the transaction's own fields: + an MST before or after promotion; any transaction whose caller is the pre-block caller; any deposit carrying the source hash the promotion stamps, `keccak256("MEGA_SYSTEM_TRANSACTION")`, whoever sends it. + Such work is exempt from history gas, per-transaction limits and detention, and priced at the minimum bucket. +- **Lane**: the per-frame record of data size and write records; a success merges into the caller's lane, a failure discards it. +- **Stop**: what a limit does. The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, its caller resumes and may catch it. +- **Answered frame**: a frame that gets a result without running (an interceptor, the engine, an inspector's hook). +- **Byte-price grid**: the CI job that runs the suite at other costs per state and history byte, because the prices are provisional. + +## Module map + +Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. +For each module: where it is, what to check, the spec sections, and the `AGENTS.md` subsection with the detail. + +### Limits: data size, write records, the stop + +- **Where:** `src/limit/` (byte table, `LimitKind`, `AdditionalLimit`, `FrameLimitTracker`, `Lane`, `StagedRecord`), `src/block/limit.rs` (`ProtocolLimits::for_spec`), `src/constants.rs`. +- **Read first:** the module docs of `src/limit/mod.rs` and `src/limit/limit.rs`. +- **Check:** + - A record is counted where it is made and taken back with its frame; the one exception is a failed creation's creator-nonce record, which lands on the creator and is held to the creator's limits. + - The transaction limit is checked before the frame budget, at one site (`AdditionalLimit::check`); every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work. + - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a charge of its own crosses again. + - `LimitKind` keeps its encoding: data size 0, compute gas 2, and `from_u8` answers `None` for 1 and 3. + - Limits are per-spec constants, never chain configuration; a bare `MegaContext` defaults to them; `BlockLimits` is builder policy and can only tighten. + - Nothing limits the KV count, state growth or the block's execution gas; the ledgers and `BlockGasCounters` report them. + - `KV × 40 ≤ data size` holds after every instruction. + - A hint that would cross the limit is neither counted nor forwarded; an admitted hint stays counted through any stop. +- **Spec:** §7, §10, §11, §19, §20. **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer). + +### Execution and frames + +- **Where:** `src/evm/execution.rs` (`MegaHandler`, the frame lifecycle), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/host.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`. +- **Read first:** the module docs of `src/evm/execution.rs` and `src/evm/host.rs`. +- **Check:** + - The Host only observes; a staged record is committed after the opcode completes and dropped when it fails. + - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). + - A frame whose start would cross a limit is answered with the stop before it is built, so no value moves; `take_back_a_stopped_answer` takes back what an answer rewritten into a crossing had moved. + - A frame start is counted before revm decides the frame, by predicting its refusals (`caller_refuses_start`, `assert_start_as_counted`); see "What follows" for what changes here. + - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. + - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on). + - Per-transaction state resets with the transaction; a system call has its own entry point and reservoir split. +- **Spec:** §3, §4, §5, §9, §11, §14, §21. **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today). + +### Gas detention + +- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, `hold_precompile` and `settle_answer` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. +- **Read first:** the module doc of `src/access/detention.rs`. +- **Check:** + - The split into spendable and withheld gas is applied when a read completes, when a frame starts or resumes, and after an `SSTORE`; only regular charges are held to the spendable part, every other reader sees both. + - The withheld part goes back to the sender unspent. + - A crossing leaves the frame's gas as it was before the charge and stops the frame with `MegaLimitExceeded(2, limit)`; the caller gets everything the frame had. + - A precompile is decided from its price before it runs; one outside the Satin set runs on the allowance. + - A system-originated transaction and a system call are never detained. + - Compute today excludes what a callee spends of a value call's 2,300 stipend and counts a halting frame's leftover through the halt-noting machinery; both change (see "What follows"), so report a defect in the current rules only if that change would not remove it. +- **Spec:** §12, §13. **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention). + +### Block executor and block rules + +- **Where:** `src/block/` (`executor.rs`, `limit.rs`, `result.rs`, `eips.rs`, `l1_block_info.rs`, `factory.rs`, `helpers.rs`). +- **Read first:** the module doc of `src/block/executor.rs`. +- **Check:** + - The activation-block rule is caller-set (`no_user_tx_activation_block`, default `false`); `MegaHardforks::admits_only_deposits` is what a builder computes it from. + - A transaction is an MST when it is a legacy transaction of the system shape from the live system address, decided before it runs; a failed read of the address is an internal error. + - A deposit and an MST are never refused by the packing budget or building policy and count towards them; the header gas limit (`BlockLimiter::pre_execution_check`) and the DA footprint (`check_da_footprint`) still apply. + - `commit_transaction_outcome` refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal). + - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info; a pre-block call that does not succeed makes the block invalid, and a fatal database error is an internal error. + - A rewriting inspector is refused at every block-execution entry, as an internal error. + - The block's ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited. + - When the OP base moves, diff the file against the new base's `OpBlockExecutor`. +- **Spec:** §1, §18, §19, §20, §21. + +### System contracts and the system address + +- **Where:** `src/system/` (`intercept.rs`, `oracle.rs`, `control.rs`, `limit_control.rs`, `keyless/`, `tx.rs`, `predeploys.rs`, `sequencer_registry.rs`), `crates/system-contracts/`. +- **Read first:** the module doc of `src/system/tx.rs`. +- **Check:** + - Every transaction reads the registry's account and its `_currentSystemAddress` slot, warm, by comparing the code hash, without running the registry's code. + - A transaction from the live system address without the system shape is invalid; a deposit from it, which never has the shape, is a failed deposit, including one carrying the MST source hash. + - A deposit carrying the MST source hash from any **other** sender is not refused: it is system-originated, so it is held to no limit, pays no history gas, is not detained and is priced at the minimum bucket. + The spec's basis is that no deposit derived from L1 carries the hash. This is the widest exemption in the engine, so check that claim. + - An MST is validated (chain id, nonce, EIP-3607) before it is promoted to a deposit. + - Satin deploys, upgrades and seeds no predeploy. The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage; anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`. No other block reads them. + - An Oracle read in a system call reads chain storage, never the oracle service. + - Keyless: the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set. + - The interceptor dispatch order is scheme guard, address, selector, then value policy; an unknown selector is not intercepted. + - Deployed bytecode and code hashes match the attested artifacts (`build.rs`). +- **Spec:** §13, §15, §16, §17, §18, §19. + +### Gas schedule and pricing + +- **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`. +- **Check:** + - Every regular entry is Amsterdam's; state creation is paid once, in state gas. + - State gas = schedule entry × bucket multiplier `m`; regular gas never scales. + A failed capacity lookup is a node fault: the transaction gets no outcome and is not settled, and the node reports an internal error with the cause. + - History gas uses the limit layer's byte table, so a record's history bytes are its data size; the three sites where the totals part are in the `src/limit/mod.rs` module doc, "The byte table". + - A deposit, a protocol-produced transaction and a system call pay no history gas. + - The history allowance (160 bytes, `storage_call_stipend()` in `src/evm/history.rs`) draws only on a log's charge. + - The EIP-7623 floor is still computed and validated. + - The constants are provisional; a build with `satin-price-override` must never reach a node. +- **Spec:** §2, §4, §5, §6, §7, §8, §9. + +### Inspector contract + +- **Where:** `src/evm/inspector.rs`, and the admission checks in `src/evm/mod.rs`, `src/block/factory.rs`, `src/block/executor.rs`. +- **Check:** + - The module documentation of `src/evm/inspector.rs` is the contract (the spec does not describe inspectors); check that each rewrite it permits is settled as it says. + - An answered frame and a revived call settle as a frame that kept nothing: state and history gas rolled back, refund dropped, lane discarded, the upfront charge given back at the price it was made at. + - A success rewritten into a failure has its journal taken back to the frame's checkpoint. + - A pre-block system call runs on the plain system-call path, with no callback. + - A declared observer must not answer a frame, edit inputs or rewrite a result (checked in debug builds). + +### Node surface, validation and the stateless witness + +- **Where:** `src/lib.rs` (explicit exports), `src/block/hardfork.rs`, `src/block/chain.rs`, `src/block/genesis.rs`, `src/evm/validation.rs`, `src/evm/state.rs`, `src/block/l1_block_info.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs`. +- **Check:** + - `validate_schedule` refuses a schedule in which a base fork Satin runs on is not active by `satinTime`. + - The genesis format has exactly one key, `satinTime`; Satin carries no parameter, and every other `satin*` key (the old registry and limit keys included) is refused. + - The pool and the engine refuse the same oversize body with the same error (`TX_BODY_OVER_DATA_SIZE_LIMIT`): body + 40 × authorizations over the transaction limit. + - The witness holds every read: block hashes, SALT bucket ids, the Oracle reads of the block's transactions (none for system calls), the L1 block info, the registry. + - The witness is the sequence of states the block commits: each pre-block step commits its state on its own, read-only entries included, where a commit hook on `State` receives it whole; nothing else hands the pre-block states out. +- **Spec:** §1, §21, §22, "Node integrators". + +### Tools, tests, goldens, benches and CI + +- **Where:** `bin/mega-evme/` (`bin/mega-evme/src/engine.rs` picks the engine from `--spec`: Satin in-tree, legacy specs on a released crate; `run` and `tx` default to the legacy `Rex6`), `crates/mega-state-test/`, `crates/state-test/`, `crates/mega-evm/tests/` (`satin/`, `block/`, `system/`, `fuzz/`, `tracers/`), `crates/mega-evm/benches/`, `.github/workflows/`, `scripts/`, `mutants/suppressions.toml`. +- **Check:** + - No consensus path changed for a tool's sake; tool overrides (`--override.limits`, `with_tx_runtime_limits`, `with_protocol_limits` under `test-utils`) are explicit and never default. + - A test pins a spec rule, not the implementation; a new or changed test says which rule it checks (some headers carry a `[S
.]` tag: the spec section and item). + - A figure the schedule determines is asserted against its derivation, not pinned; snapshots and goldens own only outputs with no computable expectation. + - The suite passes at the byte-price grid's points, not only at the spec's prices. + - The mutation gate is fail-closed: a suppression without a locator may cover only one mutant. + - A fuzz run that checks nothing fails (zero cases, zero comparisons). + +## Judging a finding + +1. **Reachability first.** Does the node's block execution or building path reach it? With the default configuration, or only with a non-default limit? Is it listed below, or in "What follows"? +2. **Severity**, in this order: + 1. not reachable from block execution or building: at most low (tools, test APIs); + 2. reachable only with a non-default configuration: one level lower; + 3. already decided below: not a new finding; say what is new about it; + 4. only an error kind or text differs, with no effect on state root, receipts, gas used, logs or block validity: not a consensus defect; + 5. can halt the chain (an activation-block error, a pre-block failure, a valid deposit refused): high, whatever the likelihood. +3. **A claim in the pull request description**: turn it into a checklist item and verify it with `file:line` against the final code. +4. **A mechanism** is open to question unless the Satin design settled it: ask what problem it solves, whether that problem still exists, whether a native replacement exists, and how it could be simpler. +5. A consensus defect is a difference in state root, receipts root, gas used, logs or block validity between two honest nodes, or between the engine and its specification. + +## Already decided — do not re-report + +Each is a decision with its reason; "in this pull request" means review the code, not the decision. + +- **KV, state-gas and block execution-gas limits are removed**: data size bounds the records and history gas prices them, state gas prices state, so removal changes no result. +- **Consensus limits are one per-spec table** (`ProtocolLimits::for_spec`), not chain configuration: configured values could stop the L1-attributes deposit and cost a silent factory fallback. +- **No latch**: a crossing is a native revert of the crossing frame, which callers may catch; with data size and detention as the only limits no transaction ends over a limit. +- **An oversize transaction body is refused at validation** (a deposit becomes a failed deposit): the body is known before execution, and at Satin's constants the bound is unreachable (6,732,889 < 13,107,200). +- **`tx_chain_id_check` is pinned on**: it is revm 40's default, and it makes the system-transaction chain-id guard effective. +- **Every transaction pre-warms the registry read**, so gas does not depend on the envelope type; the non-warming journal read is not a generic upstream candidate. +- **A delayed commit re-checks only the sender's nonce and balance**: other staleness is the builder's documented responsibility, as the system-transaction-first flow requires. +- **An MST is never refused by a packing budget or builder policy**: it serves a user transaction already admitted. +- **Satin has no deploy or upgrade path**: it runs on a chain that ran the legacy forks, and its activation block refuses any predeploy without Satin's code; no contract changes. +- **Keyless refuses only an empty code deposit** at the deploy address; the four producer-less errors are deleted, which changes no deployed byte. +- **Creation revival by an inspector is allowed** (Foundry parity), settled as a frame that kept nothing; the upfront refund is given back at the price it was charged at. +- **The Amsterdam regular gas table is taken wholesale**: the earlier press-back to Osaka priced creation twice. +- **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart. An unknown chain has no schedule (`hardfork_schedule` answers `None`). +- **A rewriting inspector in block execution is an internal error**, not a block verdict: the inspector is the node's own choice. +- **Explicit crate-root exports; dead helpers and legacy-era remnants are deleted.** +- **Satin carries no fork parameter**, and the fork-parameter mechanism was removed with nothing using it. +- **An absurd state-gas price makes the operation run out of gas**; no reachable divergence. +- **The pending-changes due check uses the direct-read convention** (any database error is an internal error), as the other direct reads and upstream do. +- **Precompile prices are looked up by id**: a precompile set replaced around the engine, through the mutable accessors, keeps the built-in prices; the spec states the boundary, and nodes change the set through `with_dyn_precompiles` or the factory builder. +- **A keyless signer that is the block beneficiary is detained**, as in the legacy engine. +- **No MST in the activation block**: it admits only deposits and every MST consumer is a non-deposit; documented in the spec. +- **Write records are deduplicated per frame**, not per transaction: documented as an upper bound. +- **The limit override is an explicit tool opt-out** (`with_tx_runtime_limits`); block execution and validation use the chain's limits. +- **No spec ladder in Satin yet**: it comes with the next spec, with the extension points kept; `AGENTS.md` says how to add it. +- **The fork finalizes the journal on an error** (`bluealloy/revm#3780`, carried early): kept; a fork documentation note is pending. +- **Answered-frame settlement stays in mega-evm**, and `OpBlockExecutor` is not composed (it requires `PostExecEvm` and returns `OpTxResult`). +- **The 98/100 frame budget and dropping a hint from a frame whose volatile access is off are kept**: without a latch the budget protects the caller's own work. +- **An inspector answer with effects is mis-accounted** (a mock that transfers value, an isolated run): the settlement assumes none; tools only, kept. +- **Mechanisms kept as in the legacy engine** (not under review): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the data-size limit's 98/100 share, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint, and the inspector admission gate. +- **The upstream revm change `new_answer`** for answers to frames that did not run (`bluealloy/revm#3979`) is opt-in: the handler does not normalise answers, because real inspectors' answers can have effects. + +## What follows + +Two changes follow this pull request, and the code under review is the code before them. +The first changes detention's final semantics and the frame-start corners, with a small revm fork release. +Detention will count every successful regular charge, stipend-funded work included, with `SSTORE` refills not subtracted, computed in mega-evm from the suspended frames' sum; the halt-noting machinery (`CallerRecord`, `note_halt`, `unbounded_charge!`) goes, and the fork adds only a cold-path record of the gas remaining before a failed charge, so halting frames are exact. +Frame-start records will be counted in `MegaEvm::frame_init` after revm decides the start, replacing the prediction (`caller_refuses_start`, `assert_start_as_counted`); two corners change and go into the spec: a creation onto an occupied address no longer stops the transaction when its records would cross, and a start revm refuses is charged then refunded, so an underfunded caller short of about 7,040 gas halts out of gas. +The fork pin then moves to the next fork tag. +Report a defect in the current rules only if that change would not remove it. + +The second change is a simplification of `limit/` after the first: one byte dimension, no prediction, and counters for hints and transfer logs, with no result change as its target and its own pull request. +It starts from a reviewed design note and may close if the note finds little to slim. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 0f99d22da..b5bbb2f1c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -10,5 +10,7 @@ + + diff --git a/.github/scripts/bench_compare.py b/.github/scripts/bench_compare.py deleted file mode 100644 index ba3a225e5..000000000 --- a/.github/scripts/bench_compare.py +++ /dev/null @@ -1,576 +0,0 @@ -#!/usr/bin/env python3 -"""Aggregate paired, order-interleaved A/B benchmark rounds into a drift-robust -comparison comment. - -The old harness ran the whole feature suite, then the whole baseline suite, and -compared two single point estimates. Those two passes are minutes apart, so the -runner's slow drift (thermal throttling, frequency scaling, noisy neighbours) -lands entirely on the feature-vs-baseline axis and shows up as a ±2-5% phantom -delta — large enough to bury a real 2-4% optimization. - -This script consumes the output of the new measurement strategy: R short rounds -where each round runs the feature binary and the baseline binary back-to-back -(A B A B ...). Because the two halves of a pair share the same local machine -state, the per-round paired Δ% cancels the common-mode drift. We then take the -mean of the R paired Δ% and a seeded bootstrap CI over them, and call a change -significant ONLY when that CI excludes zero — so a single lucky round can't flip -the verdict either. - -The statistics (median / quantile / seeded bootstrap CI) are ported verbatim -from ARO's significance gate (aro/stats.py) so the two harnesses share one tested -implementation. - -I/O is via environment variables: - ROUNDS_DIR directory holding the round files (default ".") - OUT output markdown path (default "comparison.md") - FEATURE_SHA feature commit (for the comment header link) - BASELINE_SHA baseline commit (for the comment header link) - REPO_URL repository html url (for the commit links) - BOOTSTRAP_ITERS bootstrap resamples (default 2000) - AA_CHECK "true" when feature_sha == baseline_sha (A/A self-check) - -Round files are named "____r.txt" where phase is "feature" -or "baseline" and the body is criterion `--output-format bencher` output. -""" -from __future__ import annotations - -import glob -import math -import os -import random -import re - -# --------------------------------------------------------------------------- -# Statistics — ported verbatim from ARO (aro/stats.py). stdlib-only, -# deterministic given the seed so a re-run reproduces the same verdict. -# --------------------------------------------------------------------------- - - -def median(values) -> float: - v = sorted(x for x in values if _finite(x)) - n = len(v) - if n == 0: - return math.nan - if n % 2 == 1: - return v[n // 2] - return (v[n // 2 - 1] + v[n // 2]) / 2.0 - - -def quantile(values, q: float) -> float: - """Linear-interpolated quantile at q in [0,1]. NaNs dropped.""" - v = sorted(x for x in values if _finite(x)) - n = len(v) - if n == 0: - return math.nan - if n == 1: - return v[0] - q = min(max(q, 0.0), 1.0) - pos = q * (n - 1) - lo = int(math.floor(pos)) - hi = int(math.ceil(pos)) - if hi >= n: - hi = n - 1 - if lo == hi: - return v[lo] - frac = pos - lo - return v[lo] + (v[hi] - v[lo]) * frac - - -def seed_for_metric(metric: str) -> int: - """Stable 64-bit seed per metric (FNV-1a-ish) so each bootstrap is - reproducible and independent of metric ordering.""" - h = 0xCBF29CE484222325 - for b in metric.encode("utf-8"): - h ^= b - h = (h * 0x00000100000001B3) & 0xFFFFFFFFFFFFFFFF - return h ^ 0x9E3779B97F4A7C15 - - -def bootstrap_ci(deltas_pct, iters: int = 2000, seed: int = 0): - """~95% bootstrap CI (percent) on paired Δ% values; returns (low, high). - - Resamples with replacement `iters` times, takes each resample's mean, and - returns the 2.5th / 97.5th percentiles of those means. Deterministic given - `seed`. Empty input -> (0.0, 0.0).""" - if not deltas_pct: - return (0.0, 0.0) - if iters == 0: - m = sum(deltas_pct) / len(deltas_pct) - return (m, m) - rng = random.Random(seed) - n = len(deltas_pct) - means = [] - for _ in range(iters): - s = 0.0 - for _ in range(n): - s += deltas_pct[rng.randrange(n)] - means.append(s / n) - means.sort() - return (quantile(means, 0.025), quantile(means, 0.975)) - - -def _finite(x) -> bool: - try: - return not (math.isnan(x) or math.isinf(x)) - except TypeError: - return False - - -# --------------------------------------------------------------------------- -# Parsing -# --------------------------------------------------------------------------- - -# "test snailtracer/revm_pinned ... bench: 12345 ns/iter (+/- 678)" -_BENCH_LINE = re.compile( - r"^test\s+(.+?)\s+\.\.\.\s+bench:\s+([\d,]+)\s+ns/iter\s+\(\+/-\s+([\d,]+)\)" -) -# "____r.txt" -_ROUND_FILE = re.compile(r"^(feature|baseline)__(.+)__r(\d+)\.txt$") - -# A change must clear this many usable paired rounds before its bootstrap CI is -# allowed to claim significance — a CI over 1-2 points is not trustworthy. -MIN_PAIRS = 3 - -# Floor clamps, mirrored from ARO's calibrate_floors: never trust a floor below -# 0.5% (we don't claim to resolve sub-0.5% effects), and fall back to 2.0% when -# there aren't enough samples to estimate one. -FLOOR_MIN = 0.5 -FLOOR_FALLBACK = 2.0 - - -def parse_bencher(text: str) -> dict: - out = {} - for line in text.splitlines(): - m = _BENCH_LINE.match(line) - if m: - name = m.group(1).strip() - ns = float(m.group(2).replace(",", "")) - out[name] = ns - return out - - -def load_rounds(rounds_dir: str): - """Return {phase: {(target, bench_name): {round: ns}}} for phase in - feature/baseline. The key is (target, bench_name), not bench_name alone: all - per-target artifacts are downloaded into one directory, so two targets that - happen to emit the same criterion name would otherwise overwrite each other.""" - data = {"feature": {}, "baseline": {}} - # Recurse: download-artifact + merge-multiple may place the round files - # directly under the download root (when upload-artifact collapses the - # `rounds/` prefix) or one level down — search both so the comparator finds - # them regardless. - paths = glob.glob(os.path.join(rounds_dir, "**", "*.txt"), recursive=True) - for path in sorted(paths): - fm = _ROUND_FILE.match(os.path.basename(path)) - if not fm: - continue - phase, target, rnd = fm.group(1), fm.group(2), int(fm.group(3)) - try: - with open(path, "r", encoding="utf-8") as fh: - parsed = parse_bencher(fh.read()) - except OSError: - continue - for name, ns in parsed.items(): - data[phase].setdefault((target, name), {})[rnd] = ns - return data - - -# --------------------------------------------------------------------------- -# Aggregation -# --------------------------------------------------------------------------- - - -def noise_floor(series_list) -> float: - """A/A noise floor (percent) for one bench, computed from the round-to-round - variation of repeated measurements of the SAME binary — so it costs no extra - runs. Each phase's per-round values (feature_1..feature_R, baseline_1..R) are - repeats of one binary; the spread of their relative |Δ%| estimates the - machine's own jitter. Floor = 90th percentile of those magnitudes, clamped — - exactly ARO's calibrate_floors, fed from in-band data instead of a separate - A/A pass. - - Compare only rounds of the SAME execution slot. `bench_paired.sh` alternates - the within-pair order every round, so for each phase the odd and even series - represent different first-vs-second slots. Consecutive rounds therefore - straddle the slot boundary and their delta is dominated by the slot-order - effect (frequency ramp, cold cache) — which the paired *mean* already - cancels. Pairing within a slot (odd-with-odd, even-with-even) keeps this - floor measuring the random jitter it is meant to, instead of re-importing the - slot effect the mean removed and over-suppressing real sub-floor changes. - - `series_list` is a list of {round: ns} dicts (one per phase).""" - mags = [] - for series in series_list: - for parity in (0, 1): - vals = [series[r] for r in sorted(series) if r % 2 == parity] - for a, b in zip(vals, vals[1:]): - if _finite(a) and _finite(b) and a != 0.0: - mags.append(abs((b - a) / a * 100.0)) - if len(mags) < 2: - return FLOOR_FALLBACK - q90 = quantile(mags, 0.90) - return max(q90, FLOOR_MIN) if _finite(q90) else FLOOR_FALLBACK - - -class Comparison: - __slots__ = ( - "target", "name", "n_pairs", "mean_delta", "ci_low", "ci_high", "floor", - "feature_ns", "baseline_ns", "significant", "noise_limited", - "regressed", "improved", - ) - - def __init__(self, target, name, n_pairs, mean_delta, ci_low, ci_high, floor, - feature_ns, baseline_ns): - self.target = target - self.name = name - self.n_pairs = n_pairs - self.mean_delta = mean_delta - self.ci_low = ci_low - self.ci_high = ci_high - self.floor = floor - self.feature_ns = feature_ns - self.baseline_ns = baseline_ns - # ARO's two-part gate: the bootstrap CI must exclude zero (the sign of - # the effect is resolved) AND the effect must clear the machine's own - # A/A noise floor (it's bigger than the jitter that produced the CI). - # Either alone is a known false-positive source — drift fakes a clean CI, - # and a tiny CI-excluding effect can still be pure measurement noise. - excludes_zero = (ci_low > 0 and ci_high > 0) or (ci_low < 0 and ci_high < 0) - enough = n_pairs >= MIN_PAIRS - self.significant = excludes_zero and enough and abs(mean_delta) > floor - # CI resolved a direction the floor just can't certify above its jitter. - self.noise_limited = excludes_zero and enough and not self.significant - self.regressed = self.significant and mean_delta > 0 - self.improved = self.significant and mean_delta < 0 - - -def compare(data, iters: int): - feature, baseline = data["feature"], data["baseline"] - keys = sorted(set(feature) & set(baseline)) # (target, bench_name) tuples - out = [] - for key in keys: - target, name = key - frounds, brounds = feature[key], baseline[key] - deltas, fvals, bvals = [], [], [] - for rnd in sorted(set(frounds) & set(brounds)): - f, b = frounds[rnd], brounds[rnd] - if not _finite(f) or not _finite(b) or b == 0.0: - continue - deltas.append((f - b) / b * 100.0) - fvals.append(f) - bvals.append(b) - if not deltas: - continue - mean_delta = sum(deltas) / len(deltas) - ci_low, ci_high = bootstrap_ci(deltas, iters, seed_for_metric(f"{target}/{name}")) - floor = noise_floor([frounds, brounds]) - out.append(Comparison(target, name, len(deltas), mean_delta, ci_low, - ci_high, floor, median(fvals), median(bvals))) - return out - - -# --------------------------------------------------------------------------- -# Baseline-gap section (HEAD only) — unchanged in spirit from the old harness: -# for every group that contains `revm_pinned`, show how each later row scales -# relative to it. Uses the feature (HEAD) median time per row. -# --------------------------------------------------------------------------- - -BASELINE_ROW = "revm_pinned" -ROW_ORDER = [ - "revm_pinned", "revm_latest", "op_revm_pinned", "op_revm_latest", - "equivalence", "mini_rex", "rex", "rex1", "rex2", "rex3", "rex4", "rex5", - "rex6", "rex7", -] -SPECS = set(ROW_ORDER) - - -def format_time(ns: float) -> str: - if ns >= 1_000_000: - return f"{ns / 1_000_000:.2f} ms" - if ns >= 1_000: - return f"{ns / 1_000:.2f} µs" - return f"{ns:.0f} ns" - - -def split_spec(full_name): - """Split a criterion name into (group, spec). `spec` is the segment naming an - EVM layer (`revm_pinned`, `rex4`, ...); `group` is the rest of the path. The - spec is NOT always the last segment: a per-row variant suffix produces - `//` (e.g. `sstore_heavy/revm_pinned/existing_account_50`), - so locate the spec by name rather than assuming position — otherwise groups - with a variant lose their `revm_pinned` row and drop out of the table. Returns - None when no segment is a spec (not a baseline-comparison bench).""" - segs = full_name.split("/") - idx = next((i for i, s in enumerate(segs) if s in SPECS), None) - if idx is None: - return None - group = "/".join(segs[:idx] + segs[idx + 1:]) - return (group, segs[idx]) if group else None - - -def baseline_gap_section(feature) -> str: - # feature: {(target, bench_name): {round: ns}} → median ns per (target, row). - groups = {} - for (target, full_name), rounds in feature.items(): - parsed = split_spec(full_name) - if parsed is None: - continue - group, spec = parsed - groups.setdefault((target, group), {})[spec] = median(list(rounds.values())) - - # Prefix the target only when the same group name came from >1 target, so - # colliding groups get distinct headers instead of duplicates. - targets_by_group = {} - for target, group in groups: - targets_by_group.setdefault(group, set()).add(target) - - out = "" - for target, group in sorted(groups): - rows = groups[(target, group)] - base = rows.get(BASELINE_ROW) - if base is None: - continue - ordered = [r for r in ROW_ORDER if rows.get(r) is not None] - extras = sorted(r for r in rows if r not in ROW_ORDER) - title = f"{target}/{group}" if len(targets_by_group[group]) > 1 else group - out += f"\n### `{title}`\n\n" - out += "| spec | time | × vs `revm_pinned` |\n" - out += "|------|------|--------------------|\n" - for row in ordered + extras: - ns = rows[row] - marker = " (baseline)" if row == BASELINE_ROW else "" - out += f"| `{row}` | {format_time(ns)} | {ns / base:.2f}×{marker} |\n" - - # A ROW_ORDER entry that no bench emitted is dropped silently by the filter above, so the - # table looks complete while a spec is missing from it. That is how `rex6` went unreported - # after it was added to the bench spec list but not here. Name the gap instead. - seen = {spec for rows in groups.values() for spec in rows} - missing = [row for row in ROW_ORDER if row not in seen] - if missing: - names = ", ".join(f"`{row}`" for row in missing) - out += ( - f"\n> No benchmark emitted a row for {names}. " - f"Either add the spec to `SPEC_IDS` in `crates/mega-evm/benches/common/mod.rs`, " - f"or drop it from `ROW_ORDER` here.\n" - ) - return out - - -# --------------------------------------------------------------------------- -# Rendering -# --------------------------------------------------------------------------- - - -def icon(c: Comparison) -> str: - if c.improved: - return ":rocket:" - if c.regressed: - return ":x:" if c.mean_delta > 15 else ":warning:" - if c.noise_limited: - return ":eyes:" # directional, but below this machine's noise floor - return ":white_circle:" - - -def ci_str(c: Comparison) -> str: - return f"[{c.ci_low:+.1f}%, {c.ci_high:+.1f}%]" - - -def row_str(c: Comparison, label: str) -> str: - sign = "+" if c.mean_delta > 0 else "" - return (f"| {label} | {format_time(c.baseline_ns)} | {format_time(c.feature_ns)} " - f"| {sign}{c.mean_delta:.1f}% | {ci_str(c)} | ±{c.floor:.1f}% | {icon(c)} |") - - -TABLE_HEADER = ( - "| Benchmark | Baseline | Feature | Δ (mean) | 95% CI | A/A floor | |\n" - "|-----------|----------|---------|----------|--------|-----------|-|\n" -) - -LEGEND = ( - "_:rocket: significant speedup · :x:/:warning: significant regression · " - ":eyes: directional but below the A/A noise floor · :white_circle: within " - "noise._\n" -) - -METHODOLOGY = ( - "**Paired, order-interleaved A/B.** Each round runs the feature and " - "baseline binaries back-to-back on the same runner; the verdict is the " - "mean of the per-round paired Δ% with a 95% bootstrap CI over the " - "rounds. A change is flagged only when its **CI excludes 0 _and_ |Δ| " - "clears the bench's A/A noise floor** (that bench's own round-to-round " - "jitter), so minutes-apart machine drift no longer reads as a regression " - "and a real sub-5% change is no longer buried in it.\n\n" + LEGEND -) - -# Lanes that run upstream revm / op-revm, not this repo's EVM code. A PR that -# doesn't touch the bench harness or vendored dependencies cannot change what -# these lanes execute — so a significant delta on them measures the -# binary-layout / link-order difference between the two builds (the relink -# floor), not the change under review. -CONTROL_SPECS = {"revm_pinned", "revm_latest", "op_revm_pinned", "op_revm_latest"} - -# Significant rows shown expanded; the rest fold into a
. -TOP_SIGNIFICANT = 15 - -# GitHub caps issue comments at 65536 characters; stay comfortably under it by -# dropping the bulkiest folded sections (full table first, then baseline gap) -# instead of failing the post. The raw round files ride in the run artifact -# either way. Env-overridable so tests can exercise the drop path. -MAX_COMMENT_CHARS = int(os.environ.get("MAX_COMMENT_CHARS", "60000")) - - -def _is_control(label: str) -> bool: - return any(seg in CONTROL_SPECS for seg in label.split("/")) - - -def _details(summary: str, inner: str) -> str: - return f"
{summary}\n\n{inner}\n
\n\n" - - -def _table(cs, label_of) -> str: - return TABLE_HEADER + "\n".join(row_str(c, label_of[id(c)]) for c in cs) + "\n" - - -def render(comparisons, feature_rounds, feature_sha, baseline_sha, repo_url, - aa_check: bool) -> str: - """One screen tells the verdict; everything long folds into
. - - Order: header → headline counts → relink-floor hint (when control lanes - flag) → significant table (worst first, top rows expanded) → folded - baseline-gap / full-table / methodology sections.""" - body = "## Criterion Benchmark Comparison\n\n" - body += ( - f"> Comparing [`baseline`]({repo_url}/commit/{baseline_sha})" - f" → [`feature`]({repo_url}/commit/{feature_sha})\n\n" - ) - - if aa_check: - body += ( - "> :test_tube: **A/A self-check run** — feature and baseline are the " - "**same commit**. Every row should report ≈0% with a CI that " - "contains 0; that is the measured noise floor. Any row flagged " - ":rocket:/:warning:/:x: here is a methodology bug.\n\n" - ) - - gap = baseline_gap_section(feature_rounds) - gap_section = "" - if gap: - gap_section = _details( - "Baseline gap — each EVM layer vs revm_pinned (HEAD only)", - "_Read the highest `rex*` row present (the latest spec benchmarked) " - 'for the "user-visible mega gap"; the earlier `rex*` rows are prior ' - "specs. The non-`rex` rows are diagnostic: they show which layer " - "adds cost._\n" + gap, - ) - - if not comparisons: - body += "_No comparable benchmarks found._\n\n" - return body + gap_section - - comparisons = sorted(comparisons, key=lambda c: (c.name, c.target)) - # Only prefix the target when the same bench name came from more than one - # target — otherwise two targets that collide on a name would render as two - # indistinguishable rows. The common (no-collision) case stays unprefixed. - targets_by_name = {} - for c in comparisons: - targets_by_name.setdefault(c.name, set()).add(c.target) - label_of = { - id(c): (f"{c.target}/{c.name}" if len(targets_by_name[c.name]) > 1 else c.name) - for c in comparisons - } - regressions = sum(1 for c in comparisons if c.regressed) - improvements = sum(1 for c in comparisons if c.improved) - noise_limited = sum(1 for c in comparisons if c.noise_limited) - significant = [c for c in comparisons if c.significant] - within = len(comparisons) - len(significant) - noise_limited - n_rounds = max((c.n_pairs for c in comparisons), default=0) - - # The verdict, first — the counts used to sit at the very bottom. - body += ( - f"**{len(comparisons)} benchmarks · up to {n_rounds} paired rounds** — " - f"{regressions} :warning: significant regressions · " - f"{improvements} :rocket: significant improvements · " - f"{noise_limited} :eyes: noise-limited · " - f"{within} :white_circle: within noise\n\n" - ) - - ctrl = [c for c in significant if _is_control(label_of[id(c)])] - if ctrl and not aa_check: - worst = max(ctrl, key=lambda c: abs(c.mean_delta)) - body += ( - f"> :straight_ruler: **Relink-floor hint:** {len(ctrl)} significant " - f"row(s) sit on upstream control lanes (`revm_*` / `op_revm_*`), " - f"worst {worst.mean_delta:+.1f}% on `{label_of[id(worst)]}`. Those " - "lanes do not execute this repo's EVM code — unless the PR touches " - "the bench harness or vendored dependencies, a significant delta " - "there measures binary-layout / link-order noise between the two " - "builds, and same-magnitude findings on mega lanes should be read " - "against that floor.\n\n" - ) - - if significant: - # Regressions strictly before improvements (each worst-first): ranking - # by |Δ| alone would let a stack of big speedups push a real +6% - # regression below the fold — the one row a reviewer must not miss. - by_impact = sorted(significant, - key=lambda c: (c.improved, -abs(c.mean_delta))) - head, tail = by_impact[:TOP_SIGNIFICANT], by_impact[TOP_SIGNIFICANT:] - body += "### Significant changes (worst first)\n\n" - body += _table(head, label_of) + "\n" - if tail: - body += _details(f"{len(tail)} more significant rows", - _table(tail, label_of)) - body += LEGEND + "\n" - else: - body += ( - "**No significant changes** — no bench cleared both the bootstrap " - "CI and its A/A noise floor.\n\n" - ) - - # Folded bulk, dropped last-first when the comment would blow the size cap: - # the full table goes before the baseline gap (it is the least-read — the - # significant rows are already shown and the rounds live in the artifact). - optional = [] - if gap_section: - optional.append(("the baseline-gap tables", gap_section)) - optional.append((f"the all-{len(comparisons)}-comparisons table", - _details(f"All {len(comparisons)} comparisons", - _table(comparisons, label_of)))) - methodology = _details("Methodology", METHODOLOGY) - dropped = [] - while optional and (len(body) + sum(len(s) for _, s in optional) - + len(methodology) > MAX_COMMENT_CHARS): - dropped.append(optional.pop()[0]) - for _, section in optional: - body += section - body += methodology - if dropped: - body += ( - f"_Dropped to fit GitHub's comment size limit: " - f"{', '.join(reversed(dropped))}. The complete data is in the " - "run's `criterion-benchmark-results` artifact._\n" - ) - return body - - -def main(): - rounds_dir = os.environ.get("ROUNDS_DIR", ".") - out_path = os.environ.get("OUT", "comparison.md") - feature_sha = os.environ.get("FEATURE_SHA", "") - baseline_sha = os.environ.get("BASELINE_SHA", "") - repo_url = os.environ.get("REPO_URL", "") - iters = int(os.environ.get("BOOTSTRAP_ITERS", "2000")) - aa_check = os.environ.get("AA_CHECK", "").lower() == "true" - - data = load_rounds(rounds_dir) - comparisons = compare(data, iters) - body = render(comparisons, data["feature"], feature_sha, baseline_sha, - repo_url, aa_check) - - with open(out_path, "w", encoding="utf-8") as fh: - fh.write(body) - print(body) - - -if __name__ == "__main__": - main() diff --git a/.github/scripts/bench_paired.sh b/.github/scripts/bench_paired.sh deleted file mode 100755 index 0950adf82..000000000 --- a/.github/scripts/bench_paired.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env bash -# -# Paired, order-interleaved A/B measurement for one bench target. -# -# Runs the feature and baseline bench binaries back-to-back for R short rounds, -# alternating which side goes first each round (A B / B A / A B ...). Keeping the -# two halves of every pair adjacent in time is the whole point: the runner's slow -# drift (thermal/frequency/noisy-neighbour) hits both halves equally, so the -# per-round paired Δ% computed downstream cancels it. The single sequential -# feature-then-baseline pass it replaces could not — its two halves are minutes -# apart, turning drift into a ±2-5% phantom delta. -# -# Each round uses a deliberately SHORT criterion config; precision is recovered -# across rounds by the bootstrap CI, not within a round. Per round it writes one -# `--output-format bencher` file per side, which bench_compare.py then pairs. -# -# Usage: -# bench_paired.sh \ -# -# -# may be empty (target absent at the baseline commit) or equal to -# (the A/A self-check) — both are valid and handled. -set -euo pipefail - -target="$1" -feature_bin="$2" -baseline_bin="$3" -out_dir="$4" -rounds="$5" -sample_size="$6" -warmup="$7" -measure="$8" - -if [ "$rounds" -lt 2 ] || [ $((rounds % 2)) -ne 0 ]; then - echo "round count must be an even number >= 2 so feature-first and baseline-first slots balance" >&2 - exit 1 -fi - -mkdir -p "$out_dir" - -run_one() { - # $1 = binary, $2 = output file - "$1" --bench --output-format bencher --noplot \ - --sample-size "$sample_size" \ - --warm-up-time "$warmup" \ - --measurement-time "$measure" \ - >"$2" -} - -for r in $(seq 1 "$rounds"); do - rr=$(printf '%02d' "$r") - feat_out="${out_dir}/feature__${target}__r${rr}.txt" - base_out="${out_dir}/baseline__${target}__r${rr}.txt" - - # Alternate the within-pair order every round so no side is structurally - # favoured by always warming the cache / running on a hotter core first. - # Convention: odd round = feature-first, even round = baseline-first. - # `bench_compare.py` noise_floor relies on this (same-parity rounds = same - # execution slot) — keep the two in sync. - if [ "$baseline_bin" = "" ]; then - run_one "$feature_bin" "$feat_out" # feature-only (no baseline) - elif [ $((r % 2)) -eq 1 ]; then - run_one "$feature_bin" "$feat_out" - run_one "$baseline_bin" "$base_out" - else - run_one "$baseline_bin" "$base_out" - run_one "$feature_bin" "$feat_out" - fi - echo "round ${rr}/${rounds} done for ${target}" -done diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml deleted file mode 100644 index b6ab9e728..000000000 --- a/.github/workflows/benchmark.yml +++ /dev/null @@ -1,416 +0,0 @@ -name: Criterion Benchmark - -on: - schedule: - - cron: '0 2 * * 1' # Weekly Monday 2am UTC - workflow_dispatch: - inputs: - aa_check: - description: 'A/A self-check: compare HEAD against itself to measure the noise floor (no real change should be flagged).' - type: boolean - default: false - issue_comment: - types: [created] - -# The group is suffixed with "is this a real trigger": issue_comment fires for -# EVERY new comment (codecov, mutation bots, humans chatting), and with a single -# group + cancel-in-progress an unrelated comment lands in the same group and -# cancels a live benchmark mid-flight. Non-trigger comment runs now share their -# own group and only ever cancel each other; real runs still debounce real -# re-triggers. The suffix mirrors the prepare job's FULL trigger gate -# (PR-comment + /benchmark + author association) — any comment that would fail -# the gate must not share a group with real runs, or it cancels a live run it -# cannot replace (a benchmark-DoS on public PRs); keep the two in sync. -concurrency: - group: ${{ github.workflow }}-${{ github.event.issue.number || github.ref }}-${{ github.event_name != 'issue_comment' || (github.event.issue.pull_request && contains(github.event.comment.body, '/benchmark') && contains(fromJSON('["MEMBER","COLLABORATOR","OWNER"]'), github.event.comment.author_association)) }} - cancel-in-progress: true - -# Paired, order-interleaved A/B knobs. The harness runs the feature and baseline -# bench binaries back-to-back for BENCH_ROUNDS short rounds (A B / B A / ...), -# then takes the mean of the per-round paired Δ% with a bootstrap CI. Short -# per-round configs keep the wall-clock close to the old single sequential pass; -# precision is recovered across rounds, not within one. Tune here. -env: - # Keep BENCH_ROUNDS even: the within-pair order alternates each round - # (feature-first / baseline-first), so an even count runs each side first - # exactly as often and the order-effect cancels in the mean. An odd count - # leaves a one-round imbalance that biases even the A/A self-check. - BENCH_ROUNDS: '16' - BENCH_SAMPLE_SIZE: '10' - BENCH_WARMUP: '0.2' - BENCH_MEAS: '0.5' - BOOTSTRAP_ITERS: '2000' - -# Least privilege by default: only the jobs that post to the PR get write, and -# the job that compiles + runs untrusted PR code (`bench`) gets read-only — so a -# malicious PR run with `/benchmark` has no write-scoped token to abuse. -permissions: - contents: read - -jobs: - # Resolve the exact commits ONCE, up front. Every bench job then checks out - # these fixed SHAs, so a push to the PR while the run is queued/in-flight - # cannot make different jobs measure different code (or mislabel the result). - prepare: - name: Resolve commits - runs-on: blacksmith-2vcpu-ubuntu-2404 - timeout-minutes: 10 - # Reacts to the triggering comment; does not execute PR code. - # `issues: write` is required to react to the (issue) comment — PR - # conversation comments live under the issues API; `pull-requests: write` - # does not cover their reactions. - permissions: - contents: read - issues: write - pull-requests: write - if: >- - github.event_name != 'issue_comment' || ( - github.event.issue.pull_request && - contains(github.event.comment.body, '/benchmark') && - (github.event.comment.author_association == 'MEMBER' || - github.event.comment.author_association == 'COLLABORATOR' || - github.event.comment.author_association == 'OWNER') - ) - outputs: - feature_sha: ${{ steps.resolve.outputs.feature_sha }} - baseline_sha: ${{ steps.resolve.outputs.baseline_sha }} - compare: ${{ steps.resolve.outputs.compare }} - aa_check: ${{ steps.resolve.outputs.aa_check }} - steps: - # Resolve the feature/baseline commits via the API ONLY — no checkout and - # no fetch of the PR ref. This write-privileged job therefore never brings - # untrusted PR code (or even a PR-controlled ref) into the workspace; the - # actual PR code is only ever materialized in the read-only `bench` job. - - name: Resolve commits and react - id: resolve - uses: actions/github-script@v7 - with: - script: | - if (context.eventName === 'workflow_dispatch' && - context.payload.inputs && context.payload.inputs.aa_check === 'true') { - // A/A self-check: compare the checked-out commit against ITSELF. - // A correctly-paired harness must flag nothing — the spread it - // measures is the pure noise floor. - core.setOutput('feature_sha', context.sha); - core.setOutput('baseline_sha', context.sha); - core.setOutput('compare', 'true'); - core.setOutput('aa_check', 'true'); - return; - } - if (context.eventName !== 'issue_comment') { - // schedule / workflow_dispatch: benchmark the checked-out ref, - // no baseline comparison. - core.setOutput('feature_sha', context.sha); - core.setOutput('baseline_sha', ''); - core.setOutput('compare', 'false'); - core.setOutput('aa_check', 'false'); - return; - } - const { owner, repo } = context.repo; - const pull_number = context.payload.issue.number; - const pr = await github.rest.pulls.get({ owner, repo, pull_number }); - const featureSha = pr.data.head.sha; - // GitHub's compare endpoint returns the merge-base of the PR base - // branch and the PR head — same commit `git merge-base` would pick. - const cmp = await github.rest.repos.compareCommitsWithBasehead({ - owner, - repo, - basehead: `${pr.data.base.ref}...${featureSha}`, - }); - const baselineSha = cmp.data.merge_base_commit.sha; - core.setOutput('feature_sha', featureSha); - core.setOutput('baseline_sha', baselineSha); - core.setOutput('compare', 'true'); - core.setOutput('aa_check', 'false'); - core.info(`Feature: ${featureSha} Baseline: ${baselineSha}`); - // Best-effort acknowledgement: the outputs above are already set, so - // a failed reaction must NOT fail this job (which would skip bench + - // compare). Swallow any error and carry on. - try { - await github.rest.reactions.createForIssueComment({ - owner, - repo, - comment_id: context.payload.comment.id, - content: 'rocket', - }); - } catch (e) { - core.warning(`could not add :rocket: reaction: ${e.message}`); - } - - # Claim/refresh THE report comment right away: it names the action run so - # a watcher knows where the benchmark lives, and the compare job later - # edits this same comment in place — repeated /benchmark runs never stack - # a second giant report. Best-effort: a failed post must not skip bench. - - name: Post in-progress status comment - if: github.event_name == 'issue_comment' - continue-on-error: true - uses: actions/github-script@v7 - env: - FEATURE_SHA: ${{ steps.resolve.outputs.feature_sha }} - BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }} - with: - script: | - const marker = ''; - const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; - const short = (s) => (s || '').slice(0, 12); - const body = [ - marker, - '## Criterion Benchmark Comparison', - '', - `:hourglass_flowing_sand: **Benchmark in progress** — [watch the run](${runUrl})`, - '', - `Comparing \`${short(process.env.BASELINE_SHA)}\` (baseline) → ` + - `\`${short(process.env.FEATURE_SHA)}\` (feature). ` + - 'This comment is updated in place when the run finishes.', - ].join('\n'); - const { owner, repo } = context.repo; - const issue_number = context.payload.issue.number; - const comments = await github.paginate(github.rest.issues.listComments, - { owner, repo, issue_number, per_page: 100 }); - const mine = comments.filter(c => c.user && c.user.login === 'github-actions[bot]' - && c.body && c.body.includes(marker)).pop(); - if (mine) { - await github.rest.issues.updateComment({ owner, repo, comment_id: mine.id, body }); - } else { - await github.rest.issues.createComment({ owner, repo, issue_number, body }); - } - - # One job per bench target. Each job builds BOTH the feature and baseline bench - # binaries up front (no rebuild during measurement), then runs them paired and - # order-interleaved on the SAME runner for BENCH_ROUNDS short rounds. Pairing - # the two sides inside each round cancels the runner's slow drift, which the - # old "whole feature suite, then whole baseline suite" pass turned into a - # ±2-5% phantom delta. Jobs run in parallel across targets. - bench: - name: Bench ${{ matrix.target }} - needs: prepare - runs-on: blacksmith-32vcpu-ubuntu-2404 - # Paired interleaving runs each round's measurement ~1.5x the old single - # pass, and re-pays per-bench setup once per round; give heavy-setup targets - # (block_bench / attack_replay / comp_cost) generous headroom. Lower - # BENCH_ROUNDS in env to trade back time. - timeout-minutes: 180 - # This job compiles and runs untrusted PR code — keep it read-only so there - # is no write-scoped token to exfiltrate. `pull-requests: read` lets - # `gh pr checkout` resolve the (fork) PR head. - permissions: - contents: read - pull-requests: read - strategy: - fail-fast: false - matrix: - # The Satin bench set: `block`, `transact`, `corpus` and `factory`, - # until the suite is rebuilt on Satin, which restores the full list. - # Scheduled and comment-triggered runs use the default branch's copy of - # this file. - target: [block, corpus, factory, transact] - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - fetch-depth: 0 - - # Pin the measurement runner to the TRUSTED base-repo version. The initial - # checkout above is the default branch (for issue_comment events), so this - # copy is taken before any `git checkout ` swaps in PR code — - # a PR cannot alter how its own numbers are collected. - - name: Stash measurement script - run: | - mkdir -p "$RUNNER_TEMP/scripts" - cp .github/scripts/bench_paired.sh "$RUNNER_TEMP/scripts/" - chmod +x "$RUNNER_TEMP/scripts/bench_paired.sh" - - # Fetch the PR head commit by its pull ref, which GitHub keeps in the base - # repo for fork PRs and even after the source branch is deleted (merged - # PRs) — unlike `gh pr checkout`, which needs the source branch to exist. - # `git checkout ` below then resolves against the fetched - # commit. - - name: Fetch PR head - if: github.event_name == 'issue_comment' - run: git fetch --no-tags origin "pull/${{ github.event.issue.number }}/head" - - - name: Install Rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - # Empty rustflags overrides this action's default `-D warnings`. - # Measurement builds should not fail on unrelated warnings; the - # previous align-all-functions flag is gone (layout stabilization - # was ineffective), but the opt-out of `-D warnings` stays. - rustflags: "" - - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - - # Build the feature bench binary without running it, capture its path from - # cargo's JSON output, and copy it out of target/ so a later baseline build - # (or working-tree checkout) cannot disturb it. - - name: Build feature bench binary - run: | - git checkout --quiet ${{ needs.prepare.outputs.feature_sha }} - git submodule update --init --recursive - bin=$(cargo bench --no-run -p mega-evm --bench ${{ matrix.target }} --message-format=json \ - | jq -r 'select(.reason=="compiler-artifact" and .target.name=="${{ matrix.target }}" and (.target.kind|index("bench")) and .executable!=null) | .executable' \ - | tail -1) - test -n "$bin" || { echo "could not locate feature bench binary"; exit 1; } - cp "$bin" "$RUNNER_TEMP/feature_bin" - echo "feature bench binary: $bin" - - # Build the baseline binary too (skipped for the A/A self-check, where it - # is identical, and when the target did not exist at the baseline commit). - - name: Build baseline bench binary - if: needs.prepare.outputs.compare == 'true' - run: | - if [ "${{ needs.prepare.outputs.aa_check }}" = "true" ]; then - cp "$RUNNER_TEMP/feature_bin" "$RUNNER_TEMP/baseline_bin" - echo "A/A self-check: baseline binary = feature binary" - exit 0 - fi - git checkout --quiet ${{ needs.prepare.outputs.baseline_sha }} - git submodule update --init --recursive - if ! grep -q 'name = "${{ matrix.target }}"' crates/mega-evm/Cargo.toml; then - echo "target '${{ matrix.target }}' absent at baseline commit — feature-only" - exit 0 - fi - bin=$(cargo bench --no-run -p mega-evm --bench ${{ matrix.target }} --message-format=json \ - | jq -r 'select(.reason=="compiler-artifact" and .target.name=="${{ matrix.target }}" and (.target.kind|index("bench")) and .executable!=null) | .executable' \ - | tail -1) - test -n "$bin" || { echo "could not locate baseline bench binary"; exit 1; } - cp "$bin" "$RUNNER_TEMP/baseline_bin" - echo "baseline bench binary: $bin" - - # Check out the feature working tree so BOTH prebuilt binaries read the same - # (PR) fixtures at runtime — a fair comparison on identical inputs. - - name: Prepare measurement working tree - run: | - git checkout --quiet ${{ needs.prepare.outputs.feature_sha }} - git submodule update --init --recursive - - - name: Run paired interleaved benchmark - if: needs.prepare.outputs.compare == 'true' - run: | - mkdir -p rounds - baseline_bin="" - [ -f "$RUNNER_TEMP/baseline_bin" ] && baseline_bin="$RUNNER_TEMP/baseline_bin" - "$RUNNER_TEMP/scripts/bench_paired.sh" \ - "${{ matrix.target }}" \ - "$RUNNER_TEMP/feature_bin" \ - "$baseline_bin" \ - rounds \ - "$BENCH_ROUNDS" "$BENCH_SAMPLE_SIZE" "$BENCH_WARMUP" "$BENCH_MEAS" - - # Schedule / dispatch (no comparison): one full-config feature run, kept for - # the artifact history only — there is no PR to comment on. - - name: Run standalone benchmark - if: needs.prepare.outputs.compare != 'true' - run: | - "$RUNNER_TEMP/feature_bin" --bench --output-format bencher --noplot \ - | tee "feature_${{ matrix.target }}.txt" - - - name: Upload round results - if: always() - uses: actions/upload-artifact@v4 - with: - name: bench-rounds-${{ matrix.target }} - path: | - rounds/ - feature_${{ matrix.target }}.txt - if-no-files-found: ignore - - # Join all per-target round files and post the comparison comment. Cheap (no - # compile, no benches) so it gets a short budget. - compare: - name: Compare and comment on PR - needs: [prepare, bench] - runs-on: blacksmith-2vcpu-ubuntu-2404 - timeout-minutes: 10 - # `!cancelled()` (NOT `always()`): a failed bench leg still updates the - # status comment (partial rounds aggregated under a warning banner), but a - # CANCELLED run must not run compare — the newer run that cancelled it owns - # the shared comment now, and `always()` would overwrite its fresh - # "in progress" status with this run's stale partial report. - if: >- - ${{ !cancelled() && needs.prepare.result == 'success' && - needs.prepare.outputs.compare == 'true' }} - # Posts the comparison comment; consumes artifacts plus the TRUSTED base-repo - # aggregation script (checked out below from the default branch, never PR - # code). - permissions: - contents: read - pull-requests: write - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - - name: Download all round results - # May find nothing when every bench leg failed; the aggregate step - # tolerates an empty dir and the comment step banners the failure. - continue-on-error: true - uses: actions/download-artifact@v4 - with: - pattern: bench-rounds-* - path: all_rounds - merge-multiple: true - - - name: Aggregate rounds into a comparison - env: - # Point at the download root; upload-artifact collapses the `rounds/` - # prefix, so the round files land directly under here. The comparator - # globs recursively, so a one-level-deeper layout also works. - ROUNDS_DIR: all_rounds - OUT: comparison.md - FEATURE_SHA: ${{ needs.prepare.outputs.feature_sha }} - BASELINE_SHA: ${{ needs.prepare.outputs.baseline_sha }} - REPO_URL: ${{ github.event.repository.html_url }} - AA_CHECK: ${{ needs.prepare.outputs.aa_check }} - BOOTSTRAP_ITERS: ${{ env.BOOTSTRAP_ITERS }} - run: | - mkdir -p all_rounds - python3 .github/scripts/bench_compare.py - - # Update the status comment the prepare job claimed (create if it is - # somehow missing) — one report comment per PR, edited in place, never a - # growing stack of giant comments. - - name: Comment on PR - if: github.event_name == 'issue_comment' - uses: actions/github-script@v7 - env: - BENCH_RESULT: ${{ needs.bench.result }} - with: - script: | - const fs = require('fs'); - const marker = ''; - const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; - let report; - try { - report = fs.readFileSync('comparison.md', 'utf8'); - } catch (e) { - report = '## Criterion Benchmark Comparison\n\n_No comparison was produced._\n'; - } - let banner = ''; - if (process.env.BENCH_RESULT !== 'success') { - banner = `> :warning: **Some bench jobs did not succeed** ` + - `(bench: \`${process.env.BENCH_RESULT}\`) — results below may be ` + - `partial; see the [run log](${runUrl}).\n\n`; - } - const body = `${marker}\n${banner}${report}\n_Produced by [this run](${runUrl})._`; - const { owner, repo } = context.repo; - const issue_number = context.issue.number; - const comments = await github.paginate(github.rest.issues.listComments, - { owner, repo, issue_number, per_page: 100 }); - const mine = comments.filter(c => c.user && c.user.login === 'github-actions[bot]' - && c.body && c.body.includes(marker)).pop(); - if (mine) { - await github.rest.issues.updateComment({ owner, repo, comment_id: mine.id, body }); - } else { - await github.rest.issues.createComment({ owner, repo, issue_number, body }); - } - - - name: Upload comparison - if: always() - uses: actions/upload-artifact@v4 - with: - name: criterion-benchmark-results - path: | - comparison.md - all_rounds diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index fb57502e8..a2136d5be 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -43,10 +43,82 @@ jobs: uses: actions-rust-lang/setup-rust-toolchain@v1 - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 + - name: Install cargo-insta + uses: taiki-e/install-action@v2 + with: + # The release of the insta version Cargo.lock resolves. + tool: cargo-insta@1.47.2 - name: Build run: cargo build - name: Run Test - run: cargo test --workspace + # `cargo test --workspace`, run once through cargo-insta. A snapshot that differs fails its + # test and nothing is written (--check); a snapshot file no test compared fails the run + # (--unreferenced=reject). The last three flags keep cargo test's own behaviour: the + # cargo test runner, its per-test output, and stopping at the first failing test binary. + # A pending snapshot (`.snap.new`, `.pending-snap`) in the tree is a change nobody + # accepted, which the unreferenced check does not look at: it fails the step too. + run: | + cargo insta test --workspace --check --unreferenced=reject --test-runner cargo-test --no-quiet --fail-fast + pending=$(find . -path ./target -prune -o \( -name '*.snap.new' -o -name '*.pending-snap' \) -print) + if [ -n "$pending" ]; then + echo "::error::pending snapshots in the tree:" + echo "$pending" + exit 1 + fi + + test-release: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + - name: Run tests in release + run: cargo test --workspace --release --locked + + system-contracts: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + - name: Run forge tests + working-directory: crates/system-contracts + run: forge test + + msrv: + runs-on: ubuntu-24.04 + # Sized for a cold cache, which compiles the whole graph, the legacy leg's included, and then + # the no_std target. + timeout-minutes: 15 + env: + # The workspace's declared `rust-version`; the variable takes precedence over + # rust-toolchain.toml, so every cargo call below runs on it. + RUSTUP_TOOLCHAIN: "1.94.0" + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Install Rust 1.94.0 + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + # Installed in place of rust-toolchain.toml's, and set as the directory's override; the + # cache is keyed on it, apart from the other jobs'. + toolchain: "1.94.0" + target: riscv64imac-unknown-none-elf + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + - name: Check the workspace + run: cargo check --workspace --all-targets --all-features --locked + - name: Check no_std + run: cargo check -p mega-evm --target riscv64imac-unknown-none-elf --no-default-features --locked no-std: runs-on: ubuntu-24.04 diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 6fe83f1a1..09df2f2ec 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -29,11 +29,11 @@ concurrency: jobs: codspeed: name: instruction count - runs-on: blacksmith-32vcpu-ubuntu-2404 + runs-on: ubuntu-24.04 # A cold full-suite run measured ~13 min on a GitHub-hosted 4-vCPU runner # (simulation mode executes each bench once — no criterion sampling loop); - # the 32vcpu runner only shortens the build — 30 min is ample headroom. - timeout-minutes: 30 + # 45 min leaves headroom for a cold build on this runner. + timeout-minutes: 45 steps: - uses: actions/checkout@v4 with: @@ -46,7 +46,7 @@ jobs: with: # Empty rustflags overrides this action's default `-D warnings` — # measurement builds should not fail on unrelated warnings (clippy CI - # is the warnings gate). Mirrors benchmark.yml. + # is the warnings gate). rustflags: "" - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 0298efd37..6b596ed2f 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -21,6 +21,9 @@ jobs: name: mega-evm core coverage runs-on: ubuntu-24.04 timeout-minutes: 45 + permissions: + contents: read + id-token: write # Codecov upload over OIDC; no token secret steps: - uses: actions/checkout@v4 with: @@ -50,14 +53,25 @@ jobs: - name: Record Rust version run: echo "RUST=$(rustc --version)" >> "$GITHUB_ENV" + # A failed upload does not fail the job (Codecov being down must not turn every PR red), but + # it is reported: the next step warns, so a missing report is seen rather than silent. - name: Upload coverage to Codecov + id: codecov uses: codecov/codecov-action@v5 + continue-on-error: true with: disable_search: true - fail_ci_if_error: false + fail_ci_if_error: true files: target/coverage/mega-evm/lcov.info flags: mega-evm-core name: mega-evm-core - token: ${{ secrets.CODECOV_TOKEN }} + use_oidc: true env_vars: RUST verbose: true + + - name: Warn when the Codecov upload failed + if: steps.codecov.outcome == 'failure' + run: | + echo "::warning title=Codecov upload failed::The coverage report did not reach Codecov, so no coverage comment or status follows. See the upload step's log." + echo "> [!WARNING]" >> "$GITHUB_STEP_SUMMARY" + echo "> The Codecov upload failed: no coverage comment or status for this run. See the upload step's log." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml new file mode 100644 index 000000000..104068d6c --- /dev/null +++ b/.github/workflows/exec-spec-satin.yml @@ -0,0 +1,439 @@ +name: Execution-spec tests on Satin + +# Runs the execution-spec-test state fixtures through MegaEvm with the state-test runner +# (crates/mega-state-test), on one download of the fixtures: +# +# - equivalence mode, a gate: Satin's machinery priced as each fixture fork prices it, on the +# Osaka entries of the main release and the Amsterdam entries of the glamsterdam devnet +# release. Every test passes, is skipped for a reason the fork's own runner shares, or fails on +# a deviation registered in crates/mega-state-test/src/deviations.rs, which lists the exact +# entries it explains with the hashes Satin produces, and every listed entry fails exactly as +# listed; the executed and skipped counts are pinned below. +# - Satin mode, a report: the same entries under Satin's own configuration, counted by outcome +# in the step summary. It does not fail the job. +# - the witness replay, a gate: every entry of both fixture releases, in both modes, executed on +# a recorder of every read and replayed on a strict database and environments that serve +# exactly a witness (crates/mega-state-test/src/witness.rs). An entry the engine executes +# replays on the record of every read and on the witness a node builds from its channels; one +# it rejects, on the record alone. Any entry that fails to replay fails the job. +# - the blockchain tests, a gate: the Osaka tests of the main release's `blockchain_tests`, imported +# block by block through Satin's block executor in equivalence mode's configuration (`state-test +# btest`). Every block's gas used, logs bloom, receipts root and state root are held to its +# header, and every block the fixture expects to be invalid must be refused for the exception it +# names. A block that differs passes only when a registered deviation lists that test and block +# with exactly the outcome Satin produces, and the chain is imported on from Satin's state, so +# every later block is held too; the summary counts the blocks checked against Ethereum apart +# from those matched to a deviation. A test passes, deviates as listed, is skipped for a class +# decided from its content, or fails; the executed and skipped counts are pinned below. The +# devnet release's blockchain tests are not run: the fork's runner skips them too. +# +# The fixture releases are the ones the revm fork's `scripts/run-tests.sh` names at the tag +# Cargo.lock pins, so this gate and the fork runner's (exec-spec.yml) judge the same fixtures. +# +# The `execution-spec gate on Satin` job always runs and reports the gate: it passes when the gate +# passed, or when a pull request changes nothing the gate covers and the gate did not run. It is +# the check a branch rule can require; a path filter on the pull request trigger would leave that +# check pending on every pull request it filters out, so pull requests are filtered by the +# `changes` job instead. + +on: + workflow_dispatch: + pull_request: + push: + branches: [satin] + paths: + - Cargo.lock + - Cargo.toml + - rust-toolchain.toml + - crates/mega-evm/** + - crates/mega-state-test/** + - crates/state-test/** + - crates/system-contracts/** + - .github/workflows/exec-spec-satin.yml + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + changes: + name: changes the gate covers + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + run: ${{ steps.diff.outputs.run }} + steps: + - uses: actions/checkout@v4 + if: github.event_name == 'pull_request' + with: + # The merge commit and its parents; the first parent is the base it merges into. + fetch-depth: 2 + persist-credentials: false + + - name: Compare the pull request with its base + id: diff + env: + EVENT: ${{ github.event_name }} + run: | + set -euo pipefail + # A push to satin passed the push trigger's path filter, and a manual run asks for the gate. + if [ "$EVENT" != pull_request ]; then + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! git rev-parse --verify -q 'HEAD^2' > /dev/null; then + echo "::warning::HEAD is not the pull request's merge commit; running the gate" + echo "run=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The paths the push trigger filters on; the two lists stay equal. + # Exit 0: nothing covered changed. Exit 1: a covered path changed. Any other exit fails + # the step. `--no-renames` counts a file moved out of a covered path as a deletion there. + if git diff --quiet --no-renames 'HEAD^1' HEAD -- \ + Cargo.lock \ + Cargo.toml \ + rust-toolchain.toml \ + 'crates/mega-evm/**' \ + 'crates/mega-state-test/**' \ + 'crates/state-test/**' \ + 'crates/system-contracts/**' \ + .github/workflows/exec-spec-satin.yml + then + run=false + else + status=$? + if [ "$status" -ne 1 ]; then + echo "::error::git diff exited $status" >&2 + exit "$status" + fi + run=true + fi + echo "the gate runs: $run" + echo "run=$run" >> "$GITHUB_OUTPUT" + + exec-spec-satin: + name: execution-spec tests on Satin + needs: changes + if: needs.changes.outputs.run == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + # Tests equivalence mode executes and skips, per fork, on the pinned fixture releases. The + # runner skips what the fork's own runner skips, so these are the counts exec-spec.yml pins + # for it. A change that moves the fork pin, and with it the fixtures, updates both, and the + # entries the deviations in crates/mega-state-test/src/deviations.rs list. + OSAKA_EXECUTED: "19465" + OSAKA_SKIPPED: "52" + AMSTERDAM_EXECUTED: "15754" + AMSTERDAM_SKIPPED: "72" + # The Osaka blockchain tests the blockchain gate executes, and those it skips by class. A + # change that moves the fixtures updates both, and the blockchain tests the deviations list. + BLOCKCHAIN_EXECUTED: "18713" + BLOCKCHAIN_SKIPPED: >- + withdrawals=62 blob-transactions=2540 requests=174 header-or-body=17 + undecodable-invalid-transaction=2 create-collision-with-storage=50 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + persist-credentials: false + + - name: Read the fork pin from Cargo.lock + id: pin + run: | + sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) + if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then + printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2 + exit 1 + fi + tag=${sources#*tag=} + tag=${tag%%#*} + commit=${sources##*#} + echo "fork tag $tag at $commit" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "commit=$commit" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v4 + with: + repository: megaeth-labs/revm + ref: ${{ steps.pin.outputs.tag }} + path: revm-fork + sparse-checkout: scripts + persist-credentials: false + + - name: Check the tag names the locked revision + working-directory: revm-fork + env: + COMMIT: ${{ steps.pin.outputs.commit }} + run: test "$(git rev-parse HEAD)" = "$COMMIT" + + - name: Read the fixture releases the fork's runner downloads + id: fixtures + run: | + set -euo pipefail + script=revm-fork/scripts/run-tests.sh + # One `NAME="value"` assignment each; a script that no longer has one fails the step + # rather than downloading something else. + read_var() { + local value + value=$(sed -n "s/^$1=\"\(.*\)\"$/\1/p" "$script") + if [ -z "$value" ] || [ "$(printf '%s\n' "$value" | grep -c .)" -ne 1 ]; then + echo "::error::$script: no single $1 assignment" >&2 + return 1 + fi + printf '%s' "$value" + } + main_version=$(read_var MAIN_VERSION) + devnet_version=$(read_var DEVNET_VERSION) + main_url=$(read_var FIXTURES_URL) + devnet_url=$(read_var DEVNET_FIXTURES_URL) + devnet_tar=$(read_var DEVNET_TAR) + # The runner downloads the develop release unless REVM_STATETEST_STABLE is set. + grep -q '^ MAIN_TAR="fixtures_develop.tar.gz"$' "$script" + main="$main_url/$main_version/fixtures_develop.tar.gz" + devnet="$devnet_url/$devnet_version/$devnet_tar" + # The directories taken out of each archive: the state tests of both, and the blockchain + # tests of the main release. + main_dirs="state_tests blockchain_tests" + devnet_dirs="state_tests" + # The cache is keyed on the archives themselves, and on what is taken out of them: + # another name or host at the same version is another download, and a cache that holds + # other directories is another cache. + archives=$(printf '%s\n%s\n%s\n%s\n' "$main" "$devnet" "$main_dirs" "$devnet_dirs" \ + | sha256sum | cut -c1-16) + { + echo "main=$main" + echo "devnet=$devnet" + echo "main_dirs=$main_dirs" + echo "devnet_dirs=$devnet_dirs" + echo "key=eest-fixtures-$main_version-$devnet_version-$archives" + } >> "$GITHUB_OUTPUT" + + - name: Restore the fixtures + id: cache + uses: actions/cache@v4 + with: + path: fixtures + key: ${{ steps.fixtures.outputs.key }} + + - name: Download the fixtures + if: steps.cache.outputs.cache-hit != 'true' + env: + MAIN_URL: ${{ steps.fixtures.outputs.main }} + DEVNET_URL: ${{ steps.fixtures.outputs.devnet }} + MAIN_DIRS: ${{ steps.fixtures.outputs.main_dirs }} + DEVNET_DIRS: ${{ steps.fixtures.outputs.devnet_dirs }} + run: | + set -euo pipefail + # fetch NAME URL DIRS: the directories DIRS names, out of the archive at URL, under + # fixtures/NAME. The archive's top-level `fixtures/` directory is stripped, as the fork's + # runner strips it. + fetch() { + local dir members=() + for dir in $3; do members+=("fixtures/$dir"); done + mkdir -p "fixtures/$1" + curl -fsSL --retry 5 --retry-delay 2 --retry-all-errors "$2" -o "fixtures/$1.tar.gz" + tar -xzf "fixtures/$1.tar.gz" --strip-components=1 -C "fixtures/$1" "${members[@]}" + rm "fixtures/$1.tar.gz" + } + fetch main "$MAIN_URL" "$MAIN_DIRS" + fetch devnet "$DEVNET_URL" "$DEVNET_DIRS" + + - uses: actions-rust-lang/setup-rust-toolchain@v1 + + - uses: foundry-rs/foundry-toolchain@v1 + + - name: Build the runner + run: cargo build --release --locked -p state-test + + - name: Equivalence mode, the gate + run: | + set -uo pipefail + { + echo "### Equivalence mode" + echo + echo "| Fixtures | Executed | Skipped | Passed | Deviated | Unattributed | Unreproduced |" + echo "|---|---:|---:|---:|---:|---:|---:|" + } >> "$GITHUB_STEP_SUMMARY" + gate() { + local fork=$1 dir=$2 executed=$3 skipped=$4 status=0 + target/release/state-test --fork "$fork" "$dir" \ + --expect-executed "$executed" --expect-skipped "$skipped" --expect-deviations \ + --summary-json "equivalence-$fork.json" || status=$? + if [ -f "equivalence-$fork.json" ]; then + jq -r --arg fork "$fork" '.summary as $s | "| \($fork) | \($s.executed) | \([$s.skipped[]] | add // 0) | \($s.passed) | \([$s.deviated[]] | add // 0) | \($s.unattributed) | \([$s.unreproduced[]] | add // 0) |"' \ + "equivalence-$fork.json" >> "$GITHUB_STEP_SUMMARY" + fi + if [ "$status" -ne 0 ]; then + echo "::error::equivalence mode failed on the $fork fixtures" + fi + return "$status" + } + status=0 + gate Osaka fixtures/main/state_tests "$OSAKA_EXECUTED" "$OSAKA_SKIPPED" || status=1 + gate Amsterdam fixtures/devnet/state_tests "$AMSTERDAM_EXECUTED" "$AMSTERDAM_SKIPPED" || status=1 + exit "$status" + + - name: Satin mode, the report + if: ${{ !cancelled() }} + continue-on-error: true + run: | + set -uo pipefail + { + echo "### Satin mode (a report)" + echo + echo "| Fixtures | Executed | Skipped | Passed | Failed | Failed by kind |" + echo "|---|---:|---:|---:|---:|---|" + } >> "$GITHUB_STEP_SUMMARY" + status=0 + for run in "Osaka fixtures/main/state_tests" "Amsterdam fixtures/devnet/state_tests"; do + read -r fork dir <<< "$run" + target/release/state-test --mode satin --fork "$fork" "$dir" \ + --summary-json "satin-$fork.json" || status=1 + if [ -f "satin-$fork.json" ]; then + jq -r --arg fork "$fork" '.summary as $s | "| \($fork) | \($s.executed) | \([$s.skipped[]] | add // 0) | \($s.passed) | \([$s.failed[]] | add // 0) | \($s.failed | to_entries | map("\(.key) \(.value)") | join(", ")) |"' \ + "satin-$fork.json" >> "$GITHUB_STEP_SUMMARY" + fi + done + exit "$status" + + - name: Witness replay over the fixtures, the gate + if: ${{ !cancelled() }} + run: | + set -uo pipefail + { + echo "### Witness replay" + echo + echo "| Fixtures | Mode | Replayed on both witnesses | Rejected, replayed on the record alone | Skipped | Failed |" + echo "|---|---|---:|---:|---:|---:|" + } >> "$GITHUB_STEP_SUMMARY" + cargo test --release --locked -p mega-state-test --test witness --no-run || exit 1 + status=0 + for run in "Osaka fixtures/main/state_tests" "Amsterdam fixtures/devnet/state_tests"; do + read -r fork dir <<< "$run" + for mode in equivalence satin; do + # The test runs in the package's directory, so the fixtures are named by an absolute path. + rc=0 + MEGA_STATE_TEST_FIXTURES="$GITHUB_WORKSPACE/$dir" MEGA_STATE_TEST_SAMPLE=0 \ + MEGA_STATE_TEST_FORK="$fork" MEGA_STATE_TEST_MODE="$mode" \ + cargo test --release --locked -p mega-state-test --test witness -- --ignored --nocapture \ + 2>&1 | tee "witness-$fork-$mode.log" || rc=$? + if [ "$rc" -ne 0 ]; then + echo "::error::the witness replay failed on the $fork fixtures in $mode mode" + status=1 + fi + # A run passes only on exactly one summary line, in the full format, for this fork and + # mode, that executed entries and failed none: a run that tested nothing, or whose + # output changed shape, fails the gate rather than passing silently. + mapfile -t lines < <(grep '^witness replay of ' "witness-$fork-$mode.log" || true) + summary='^witness replay of ([0-9]+) fixture files in ([a-z]+) mode on ([A-Za-z]+): ([0-9]+) executed and replayed on both witnesses, ([0-9]+) rejected and replayed on the database record alone, ([0-9]+) skipped, ([0-9]+) failed$' + if [ "${#lines[@]}" -ne 1 ]; then + echo "::error::the $fork $mode run printed ${#lines[@]} summary lines, not one" + status=1 + elif ! [[ ${lines[0]} =~ $summary ]]; then + echo "::error::the $fork $mode summary is not in the expected format: ${lines[0]}" + status=1 + elif [ "${BASH_REMATCH[3]}" != "$fork" ] || [ "${BASH_REMATCH[2]}" != "$mode" ]; then + echo "::error::the $fork $mode run reported ${BASH_REMATCH[3]} in ${BASH_REMATCH[2]} mode" + status=1 + elif [ "${BASH_REMATCH[1]}" -eq 0 ] || [ "${BASH_REMATCH[4]}" -eq 0 ]; then + echo "::error::the $fork $mode run executed nothing: ${lines[0]}" + status=1 + elif [ "${BASH_REMATCH[7]}" -ne 0 ]; then + echo "::error::the $fork $mode run failed ${BASH_REMATCH[7]} entries" + status=1 + else + echo "| $fork | $mode | ${BASH_REMATCH[4]} | ${BASH_REMATCH[5]} | ${BASH_REMATCH[6]} | ${BASH_REMATCH[7]} |" \ + >> "$GITHUB_STEP_SUMMARY" + fi + done + done + exit "$status" + + - name: Blockchain tests through the block executor, the gate + if: ${{ !cancelled() }} + run: | + set -uo pipefail + { + echo "### Blockchain tests" + echo + echo "| Fixtures | Executed | Skipped | Passed | Deviated | Unattributed | Unreproduced | Blocks checked against Ethereum | Blocks matched to a deviation |" + echo "|---|---:|---:|---:|---:|---:|---:|---:|---:|" + } >> "$GITHUB_STEP_SUMMARY" + pins=() + for pin in $BLOCKCHAIN_SKIPPED; do pins+=(--expect-skipped "$pin"); done + rm -f blockchain-Osaka.json + status=0 + target/release/state-test btest fixtures/main/blockchain_tests \ + --expect-executed "$BLOCKCHAIN_EXECUTED" "${pins[@]}" --expect-deviations \ + --summary-json blockchain-Osaka.json || status=$? + if [ "$status" -ne 0 ]; then + echo "::error::the blockchain tests failed the gate" + fi + # The gate passes only on a summary in the expected shape, for the Osaka blockchain tests, + # that executed tests and has no failed test (no block differing from its header without + # the exact outcome a registered deviation lists for it), no unread fixture and no listed + # test that did not deviate as listed: a run that tested nothing, or whose summary changed + # shape, fails the gate rather than passing silently. + shape='.suite == "blockchain" and .fork == "Osaka" and (.skip_reasons | type) == "object" + and (.summary | (.executed | type) == "number" and (.passed | type) == "number" + and (.unattributed | type) == "number" and (.file_failures | type) == "number" + and (.skipped | type) == "object" and (.deviated | type) == "object" + and (.unreproduced | type) == "object" and (.blocks.matched | type) == "number" + and (.blocks.refused | type) == "number" and (.blocks.deviated | type) == "number")' + if [ ! -f blockchain-Osaka.json ]; then + echo "::error::the blockchain tests wrote no summary" + status=1 + elif ! jq -e "$shape" blockchain-Osaka.json > /dev/null 2>&1; then + echo "::error::the blockchain tests' summary is not in the expected shape" + status=1 + elif ! jq -e '.summary.executed > 0' blockchain-Osaka.json > /dev/null; then + echo "::error::the blockchain tests executed nothing" + status=1 + elif ! jq -e '.summary | .unattributed == 0 and .file_failures == 0 and (.unreproduced | add // 0) == 0' \ + blockchain-Osaka.json > /dev/null; then + echo "::error::the blockchain tests have a failed test, an unread fixture or a listed test that did not deviate as listed" + status=1 + else + jq -r '.summary as $s | "| Osaka | \($s.executed) | \([$s.skipped[]] | add // 0) | \($s.passed) | \([$s.deviated[]] | add // 0) | \($s.unattributed) | \([$s.unreproduced[]] | add // 0) | \($s.blocks.matched + $s.blocks.refused) | \($s.blocks.deviated) |"' \ + blockchain-Osaka.json >> "$GITHUB_STEP_SUMMARY" + { + echo + echo "| Skipped for | Tests | Why |" + echo "|---|---:|---|" + jq -r '.summary.skipped as $s | .skip_reasons | to_entries[] | "| \(.key) | \($s[.key] // 0) | \(.value) |"' \ + blockchain-Osaka.json + } >> "$GITHUB_STEP_SUMMARY" + fi + exit "$status" + + gate: + name: execution-spec gate on Satin + needs: [changes, exec-spec-satin] + # Always, a cancelled run included: a required check that is skipped counts as passed. + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Report the gate's outcome + env: + CHANGES: ${{ needs.changes.result }} + RUN: ${{ needs.changes.outputs.run }} + GATE: ${{ needs.exec-spec-satin.result }} + run: | + if [ "$CHANGES" != success ]; then + echo "::error::could not tell whether the gate had to run: the changes job ended $CHANGES" + exit 1 + fi + if [ "$RUN" != true ]; then + echo "nothing the gate covers changed; the gate did not run" + exit 0 + fi + if [ "$GATE" != success ]; then + echo "::error::the gate ended $GATE" + exit 1 + fi + echo "the gate passed" diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 5493ccd01..227f3c190 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -5,8 +5,8 @@ name: Execution-spec tests # and skips for Osaka (the main fixtures) and Amsterdam (the glamsterdam devnet fixtures) and # checks them against the numbers pinned below. # -# An interim gate until the state-test tool is ported to Satin. It checks the fork MegaEvm runs -# on, not MegaEvm. Not a required check. +# It checks the fork MegaEvm runs on, not MegaEvm; exec-spec-satin.yml runs the same fixture +# releases through MegaEvm. Not a required check. on: workflow_dispatch: @@ -14,6 +14,9 @@ on: # weekly once `satin` is the default branch. Until then, dispatch it by hand on `satin`. schedule: - cron: "0 4 * * 1" # Weekly, Monday 4:00 UTC + # Engine source is not a path here. This job runs the revm fork's own runner + # at the revision Cargo.lock pins, so a change to the engine cannot move its + # result. exec-spec-satin.yml runs when the engine changes. pull_request: paths: - Cargo.lock diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 000000000..fa1492af1 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,126 @@ +name: Randomized tests, long mode + +# Runs the randomized tests of the Satin engine (crates/mega-evm/tests/fuzz) in their long mode: +# many more cases per property than the bounded run every pull request makes, drawn from a seed +# this run chooses (or the one given), in a debug build, where every debug assertion runs, and in +# a release build, where none does. A failure prints the seed and the case count that reproduce it +# and the minimal case it shrank to; the job's log is the record. +# +# It also runs the byte-price record at two prices and compares them: where a case followed the +# same path at both, its state gas must not fall as the cost per state byte rises, nor its history +# gas as the cost per history byte rises (scripts/fuzz_price_monotonic.py). +# +# Dispatch only: a scheduled trigger fires on the default branch alone, which the Satin +# integration branch is not. Dispatch it from the branch to test, with a seed to reproduce a run +# or none to draw a new one. +# +# The two inputs, and how they meet the long mode: +# +# - `cases` empty (the default): each property runs fifty times its own bounded count, 6,400 to +# 38,400 cases, which is what `MEGA_FUZZ_LONG=1` means on its own. +# - `cases` set: every property runs exactly that many cases. The count replaces the bounded count +# and the multiplier alike; it is not multiplied by fifty. +# - `seed` empty: the run draws one seed from the clock, prints it, and uses it for every property +# and both profiles, so one number reproduces the run. +# +# The runner itself reads an empty `MEGA_FUZZ_CASES` or `MEGA_FUZZ_SEED` as unset, so an input left +# empty cannot fail the run. + +on: + workflow_dispatch: + inputs: + cases: + description: "Cases per property, exactly; empty runs each at fifty times its bounded count" + required: false + default: "" + seed: + description: "The seed to draw the cases from; empty draws one from the clock" + required: false + default: "" + +permissions: + contents: read + +jobs: + seed: + name: the run's seed + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + seed: ${{ steps.seed.outputs.seed }} + steps: + - name: Take the seed given, or draw one + id: seed + env: + GIVEN: ${{ inputs.seed }} + run: | + seed="$GIVEN" + [ -n "$seed" ] || seed="$(date +%s)" + echo "seed=$seed" >> "$GITHUB_OUTPUT" + echo "Seed \`$seed\`: reproduce with \`MEGA_FUZZ_SEED=$seed\` and the case count each property prints." >> "$GITHUB_STEP_SUMMARY" + + long: + name: long mode (${{ matrix.profile }}) + needs: seed + runs-on: ubuntu-24.04 + timeout-minutes: 120 + strategy: + fail-fast: false + matrix: + profile: [debug, release] + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Run the properties + env: + MEGA_FUZZ_LONG: "1" + # Empty unless the dispatch named a count, and then every property runs exactly it. + MEGA_FUZZ_CASES: ${{ inputs.cases }} + MEGA_FUZZ_SEED: ${{ needs.seed.outputs.seed }} + run: | + if [ "${{ matrix.profile }}" = "release" ]; then + cargo test --release --locked -p mega-evm --test fuzz -- --nocapture + else + cargo test --locked -p mega-evm --test fuzz -- --nocapture + fi + + price-monotonicity: + name: state and history gas along the byte prices + needs: seed + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + # Both records are drawn from the same seed and the same case count, so the cases match by + # index: the long mode's count unless the dispatch named one. + - name: Record the cases at the constants and at dearer bytes + env: + MEGA_FUZZ_LONG: "1" + MEGA_FUZZ_CASES: ${{ inputs.cases }} + MEGA_FUZZ_SEED: ${{ needs.seed.outputs.seed }} + run: | + cargo test --release --locked -p mega-evm --features satin-price-override,test-utils --test fuzz --no-run + MEGA_FUZZ_PRICE_RECORD="$PWD/target/price-low.txt" \ + cargo test --release --locked -p mega-evm --features satin-price-override,test-utils --test fuzz -- price_record + MEGA_SATIN_CPSB=2000 MEGA_SATIN_CPHB=100 MEGA_FUZZ_PRICE_RECORD="$PWD/target/price-high.txt" \ + cargo test --release --locked -p mega-evm --features satin-price-override,test-utils --test fuzz -- price_record + + - name: Compare the records + run: python3 scripts/fuzz_price_monotonic.py target/price-low.txt target/price-high.txt diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index a74acc03f..520a81851 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -4,18 +4,21 @@ name: Mutation Testing # * cargo-mutants gate — generic operators (diff-scoped on PRs, full nightly) # * infrastructure gate — the same operators on the code that implements the # test gates, which the production scope excludes -# * spec-gate — universalmutator + comby custom operators for -# backward-compat spec gates (diff PR + nightly sweep) # * suppression hygiene — flag suppressions that no longer match a live mutant -# All four share the scorer scripts/mutation_gate.py. See mutants/README.md. +# * gate self-test — the scorer's and the driver's own tests +# The cargo-mutants and infrastructure gates share the scorer +# scripts/mutation_gate.py. +# The spec-gate operator pack stays on disk. A single-spec engine has no spec +# gate for it to mutate, so this workflow does not run it. Suppression hygiene +# still plans the pack and accepts an empty plan. See mutants/README.md. on: workflow_dispatch: pull_request: schedule: # Nightly: full-crate cargo-mutants re-verify (the diff gate never mutates - # #[cfg(test)] code, so the in-repo killing tests are only re-checked here), - # the full spec-gate sweep, and the suppression-hygiene check. + # #[cfg(test)] code, so the in-repo killing tests are only re-checked here) + # and the suppression-hygiene check. - cron: "0 3 * * *" concurrency: @@ -67,6 +70,8 @@ jobs: # On a PR: mutate only the changed lines (fast gate). On manual dispatch # there is no PR base, so run the whole crate as an on-demand baseline # instead of feeding an empty base into `diff` mode (which would fail). + # The driver re-runs a mutant that timed out once, alone, into + # target/mutants/recheck; the gate takes that outcome for it. run: | if [ "${{ github.event_name }}" = "pull_request" ]; then scripts/mutation_test.sh diff "${{ github.event.pull_request.base.sha }}" @@ -78,6 +83,7 @@ jobs: run: | python3 scripts/mutation_gate.py report \ --results target/mutants/mutants.out \ + --recheck target/mutants/recheck/mutants.out \ --suppressions mutants/suppressions.toml \ --comment mutation-report.md \ --summary "$GITHUB_STEP_SUMMARY" @@ -95,7 +101,7 @@ jobs: try { body = fs.readFileSync('mutation-report.md', 'utf8'); } catch { - body = '## 🧬 Mutation testing\n\nNo report produced (no mega-evm changes to mutate).'; + body = '## 🧬 Mutation testing\n\nNo report produced: the mutation run failed before the gate scored it. See the job log.'; } const marker = ''; body = `${marker}\n${body}`; @@ -123,7 +129,10 @@ jobs: name: mutation-results path: | target/mutants/mutants.out + target/mutants/recheck/mutants.out target/mutants.diff + target/mutants.log + target/mutants/recheck.log mutation-report.md if-no-files-found: ignore @@ -174,6 +183,7 @@ jobs: run: | python3 scripts/mutation_gate.py report \ --results target/mutants-infra/mutants.out \ + --recheck target/mutants-infra/recheck/mutants.out \ --suppressions mutants/suppressions.toml \ --summary "$GITHUB_STEP_SUMMARY" @@ -182,141 +192,25 @@ jobs: uses: actions/upload-artifact@v4 with: name: mutation-results-infra - path: target/mutants-infra/mutants.out - if-no-files-found: ignore - - # ── spec-gate: diff-scoped blocking gate on PRs ──────────────────────────── - # Only files+lines the PR changed are mutated, so most PRs generate zero - # spec-gate mutants and this is near-instant. - spec-gate: - name: diff-scoped spec-gate - if: github.event_name == 'pull_request' - runs-on: ubuntu-24.04 - timeout-minutes: 60 - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - fetch-depth: 0 # need base history for the diff - - name: Install Rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - - name: Install cargo-nextest - uses: taiki-e/install-action@nextest - - name: Install universalmutator (mise) - uses: jdx/mise-action@v2 - - name: Install comby - # Pin the version (reproducible mutant generation). The prebuilt links - # against libev/libpcre, which are not on the runner by default. - run: | - sudo apt-get update - sudo apt-get install -y libpcre3 libev4 - sudo curl -fsSL https://github.com/comby-tools/comby/releases/download/1.8.1/comby-1.8.1-x86_64-linux -o /usr/local/bin/comby - sudo chmod +x /usr/local/bin/comby - comby -version - - name: Run diff-scoped spec-gate mutation - run: | - python3 scripts/umutate.py run --packs spec-gate \ - --diff "${{ github.event.pull_request.base.sha }}" \ - --output target/umutate - - name: Score and gate - run: | - python3 scripts/mutation_gate.py report \ - --results target/umutate \ - --suppressions mutants/suppressions.toml \ - --comment spec-gate-report.md \ - --summary "$GITHUB_STEP_SUMMARY" - - name: Upsert PR comment - if: always() && github.event_name == 'pull_request' - continue-on-error: true - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - let body; - try { - body = fs.readFileSync('spec-gate-report.md', 'utf8'); - } catch { - body = '## 🧬 Spec-gate mutation\n\nNo report produced.'; - } - const marker = ''; - body = `${marker}\n${body}`; - const { data: comments } = await github.rest.issues.listComments({ - owner: context.repo.owner, repo: context.repo.repo, - issue_number: context.issue.number, per_page: 100, - }); - const existing = comments.find(c => c.body.includes(marker)); - if (existing) { - await github.rest.issues.updateComment({ - owner: context.repo.owner, repo: context.repo.repo, - comment_id: existing.id, body, - }); - } else { - await github.rest.issues.createComment({ - owner: context.repo.owner, repo: context.repo.repo, - issue_number: context.issue.number, body, - }); - } - - name: Upload artifacts - if: always() - uses: actions/upload-artifact@v4 - with: - name: spec-gate-mutation-diff path: | - target/umutate - spec-gate-report.md + target/mutants-infra/mutants.out + target/mutants-infra/recheck/mutants.out + target/mutants-infra.log + target/mutants-infra/recheck.log if-no-files-found: ignore - # ── spec-gate: nightly full sweep, sharded by subsystem ──────────────────── - # Each shard stays bounded (analyze is sequential). Informational: surfaces - # survivors but does not fail the workflow — triage into suppressions or tests. - spec-gate-sweep: - name: spec-gate sweep (${{ matrix.subsystem }}) - if: github.event_name != 'pull_request' + # ── gate self-test: the scorer's and the driver's own tests ──────────────── + # The gate reads a run fail-closed; its tests hold every way a run can leave + # results that say nothing to a failure, and the driver's refusal of an old + # bash. Seconds long, so it runs on every PR. + gate-selftest: + name: mutation gate self-test runs-on: ubuntu-24.04 - timeout-minutes: 330 - strategy: - fail-fast: false - matrix: - subsystem: [evm, limit, block, access, external, system, sandbox] + timeout-minutes: 10 steps: - uses: actions/checkout@v4 - with: - submodules: recursive - - name: Install Rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - - name: Install cargo-nextest - uses: taiki-e/install-action@nextest - - name: Install universalmutator (mise) - uses: jdx/mise-action@v2 - - name: Install comby - run: | - sudo apt-get update - sudo apt-get install -y libpcre3 libev4 - sudo curl -fsSL https://github.com/comby-tools/comby/releases/download/1.8.1/comby-1.8.1-x86_64-linux -o /usr/local/bin/comby - sudo chmod +x /usr/local/bin/comby - comby -version - - name: Run spec-gate mutation (${{ matrix.subsystem }}) - run: | - python3 scripts/umutate.py run --packs spec-gate \ - --files "crates/mega-evm/src/${{ matrix.subsystem }}/*" \ - --output "target/umutate/${{ matrix.subsystem }}" - - name: Score (informational) - run: | - python3 scripts/mutation_gate.py report \ - --results "target/umutate/${{ matrix.subsystem }}" \ - --suppressions mutants/suppressions.toml \ - --summary "$GITHUB_STEP_SUMMARY" || true - - name: Upload artifacts - if: always() - uses: actions/upload-artifact@v4 - with: - name: spec-gate-mutation-${{ matrix.subsystem }} - path: target/umutate/${{ matrix.subsystem }} - if-no-files-found: ignore + - name: Test the gate and the driver's guards + run: python3 -m unittest discover -s scripts -p 'test_*.py' -v # ── suppression hygiene: gate on relevant PR changes, plus nightly ───────── # `changes` scopes the hygiene job to PRs that could orphan a suppression diff --git a/.github/workflows/on-release.yml b/.github/workflows/on-release.yml index c6ff19453..9fab3482f 100644 --- a/.github/workflows/on-release.yml +++ b/.github/workflows/on-release.yml @@ -106,8 +106,10 @@ jobs: - uses: foundry-rs/foundry-toolchain@b00af27efadbc7b4ca8b82abbd903b17cc874d2a # v1 + # Selected by manifest path: the tool links the released mega-evme 1.7.1 + # as its legacy leg, so `-p mega-evme` names two packages. - name: Build mega-evme - run: cargo build --release --locked -p mega-evme + run: cargo build --release --locked --manifest-path bin/mega-evme/Cargo.toml # The built binary must report the tag's version (`mega-evme X.Y.Z`): # a mismatch warns on a rehearsal and stops a release; a binary that diff --git a/.github/workflows/price-grid.yml b/.github/workflows/price-grid.yml new file mode 100644 index 000000000..2abdcc19d --- /dev/null +++ b/.github/workflows/price-grid.yml @@ -0,0 +1,63 @@ +name: Byte-price grid + +# Runs the mega-evm test suite at state and history byte prices other than the constants, through +# the `satin-price-override` feature and the MEGA_SATIN_CPSB / MEGA_SATIN_CPHB variables +# (scripts/price_grid.sh). Both prices are provisional until the economics sign-off, so the suite +# must hold at any price it may end at, and a test that only holds at the constants shows here: +# +# - on a pull request, five points: both bytes free, both at one gas (1 / 1), the cheapest and the +# dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate +# (10000 / 1000); +# - nightly and on dispatch, the whole grid: a cost per state byte of 0, 1, 312.5, 700, 1530, 2000, +# 5000 and 10000 by a cost per history byte of 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 +# on both. +# +# The run at the constants is the `test` job of build-and-test.yml. + +on: + workflow_dispatch: + pull_request: + schedule: + - cron: "0 4 * * *" + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + price-grid: + name: byte-price grid + runs-on: ubuntu-24.04 + # The pull-request points take minutes; the nightly grid runs the suite 73 times. + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Run the suite at each point + env: + EVENT: ${{ github.event_name }} + run: | + if [ "$EVENT" = "pull_request" ]; then + scripts/price_grid.sh --pr + else + scripts/price_grid.sh --full + fi + + - name: Upload the logs of a failing run + if: failure() + uses: actions/upload-artifact@v4 + with: + name: price-grid-logs + path: target/price-grid/ + retention-days: 7 diff --git a/.github/workflows/replay-bench.yml b/.github/workflows/replay-bench.yml deleted file mode 100644 index 808da589e..000000000 --- a/.github/workflows/replay-bench.yml +++ /dev/null @@ -1,269 +0,0 @@ -name: Replay Throughput Benchmark - -# Replays a corpus of real, characteristic MegaETH mainnet transactions -# (committed self-contained fixtures, timed by `state-test --bench`) and compares -# PR throughput against the merge-base, so a change that slows down (or speeds -# up) real-transaction execution is visible on the PR. -# -# This is the real-transaction counterpart to the synthetic Criterion suite in -# benchmark.yml, and follows the same hardened structure: the job that compiles -# and runs untrusted PR code (`bench`) is read-only, and only the jobs that touch -# the PR (`prepare`, `compare`) get a write-scoped token — so a malicious PR run -# triggered with `/replay-bench` has no write token to abuse. - -on: - schedule: - - cron: '0 3 * * 1' # Weekly Monday 3am UTC (after the Criterion job) - workflow_dispatch: - issue_comment: - types: [created] - -# Suffixed with "is this a real trigger" so unrelated comments (bots, chat) -# land in their own group instead of cancelling a live run — same fix as -# benchmark.yml: mirror the FULL trigger gate (PR-comment + /replay-bench + -# author association); a comment that would fail the gate must not cancel a -# live run it cannot replace. -concurrency: - group: ${{ github.workflow }}-${{ github.event.issue.number || github.ref }}-${{ github.event_name != 'issue_comment' || (github.event.issue.pull_request && contains(github.event.comment.body, '/replay-bench') && contains(fromJSON('["MEMBER","COLLABORATOR","OWNER"]'), github.event.comment.author_association)) }} - cancel-in-progress: true - -permissions: - contents: read - -jobs: - # Resolve the exact commits ONCE, up front, via the API only — no checkout and - # no fetch of the PR ref — so this write-privileged job never brings untrusted - # PR code (or even a PR-controlled ref) into the workspace. - prepare: - name: Resolve commits - runs-on: blacksmith-2vcpu-ubuntu-2404 - timeout-minutes: 10 - permissions: - contents: read - pull-requests: write - # The comment-reaction endpoint needs Issues write (a PR comment is an - # issue comment); the reaction is also wrapped non-fatally below. - issues: write - if: >- - github.event_name != 'issue_comment' || ( - github.event.issue.pull_request && - contains(github.event.comment.body, '/replay-bench') && - (github.event.comment.author_association == 'MEMBER' || - github.event.comment.author_association == 'COLLABORATOR' || - github.event.comment.author_association == 'OWNER') - ) - outputs: - feature_sha: ${{ steps.resolve.outputs.feature_sha }} - baseline_sha: ${{ steps.resolve.outputs.baseline_sha }} - compare: ${{ steps.resolve.outputs.compare }} - steps: - - name: Resolve commits and react - id: resolve - uses: actions/github-script@v7 - with: - script: | - if (context.eventName !== 'issue_comment') { - // schedule / workflow_dispatch: measure the checked-out ref, - // no baseline comparison. - core.setOutput('feature_sha', context.sha); - core.setOutput('baseline_sha', ''); - core.setOutput('compare', 'false'); - return; - } - const { owner, repo } = context.repo; - const pull_number = context.payload.issue.number; - const pr = await github.rest.pulls.get({ owner, repo, pull_number }); - const featureSha = pr.data.head.sha; - // The compare endpoint's merge_base is the commit `git merge-base` - // would pick for the PR base branch and head. - const cmp = await github.rest.repos.compareCommitsWithBasehead({ - owner, - repo, - basehead: `${pr.data.base.ref}...${featureSha}`, - }); - core.setOutput('feature_sha', featureSha); - core.setOutput('baseline_sha', cmp.data.merge_base_commit.sha); - core.setOutput('compare', 'true'); - core.info(`Feature: ${featureSha} Baseline: ${cmp.data.merge_base_commit.sha}`); - // Cosmetic acknowledgement — never let it fail the run (and so block - // the benchmark) if the token lacks the reaction permission. - try { - await github.rest.reactions.createForIssueComment({ - owner, - repo, - comment_id: context.payload.comment.id, - content: 'rocket', - }); - } catch (e) { - core.warning(`Could not react to the comment: ${e.message}`); - } - - # Compiles and runs untrusted PR code (the PR's state-test binary + driver + - # corpus), so it is read-only: there is no write-scoped token to exfiltrate. - # `pull-requests: read` lets `gh pr checkout` resolve a fork PR head. - bench: - name: Replay throughput - needs: prepare - # Disabled on the satin branch: this job builds `state-test`, which is not a - # workspace member until it is ported to the Satin engine; the port removes - # this line. (`compare` needs this job, so it is skipped with it.) Scheduled - # and comment-triggered runs use the default branch's copy of this file. - if: false - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 90 - permissions: - contents: read - pull-requests: read - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - fetch-depth: 0 - # This job builds and runs untrusted PR code; don't leave a git - # credential on disk for that code to pick up. - persist-credentials: false - - - name: Fetch PR head - if: github.event_name == 'issue_comment' - env: - GH_TOKEN: ${{ github.token }} - run: gh pr checkout ${{ github.event.issue.number }} - - - name: Install Rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - - # Only the binary under test changes between feature and baseline; the - # driver + corpus always come from the PR-head checkout. Build each binary - # at its pinned SHA into its own directory the driver resolves. - - name: Build feature binary - run: | - git checkout --quiet ${{ needs.prepare.outputs.feature_sha }} - git submodule update --init --recursive - cargo build --release -p state-test - mkdir -p /tmp/pr && cp target/release/state-test /tmp/pr/ - - - name: Build baseline binary - if: needs.prepare.outputs.compare == 'true' - run: | - git checkout --quiet ${{ needs.prepare.outputs.baseline_sha }} - git submodule update --init --recursive - cargo build --release -p state-test - mkdir -p /tmp/base && cp target/release/state-test /tmp/base/ - - # Restore the PR-head driver + corpus, then run. If the baseline predates - # `state-test --bench` (the feature this PR may introduce), fall back to - # measuring the feature binary alone instead of failing. - - name: Run replay benchmark - run: | - git checkout --quiet ${{ needs.prepare.outputs.feature_sha }} - git submodule update --init --recursive - BINS=(--bin "pr=/tmp/pr") - if [ "${{ needs.prepare.outputs.compare }}" = "true" ] && \ - /tmp/base/state-test --bench --bench-runs 1 --bench-warmup 0 \ - bench/replay/fixtures/medium_call.json >/dev/null 2>&1; then - BINS=(--bin "base=/tmp/base" --bin "pr=/tmp/pr") - echo "Comparing PR vs baseline." - else - echo "Measuring the PR binary only (no baseline, or baseline predates the fixture bench)." - fi - python3 bench/replay/run.py "${BINS[@]}" \ - --rounds 7 --threshold-pct 7 \ - --markdown-out replay-bench.md \ - --json-out replay-bench.json - - - name: Write job summary - if: always() - run: | - if [ -f replay-bench.md ]; then - { - cat replay-bench.md - echo - echo "> Comparing \`baseline\` (${{ needs.prepare.outputs.baseline_sha }}) → \`feature\` (${{ needs.prepare.outputs.feature_sha }})." - echo "> Sub-10µs cases are noisy on shared runners; read the larger cases and the trend for real signal." - } >> "$GITHUB_STEP_SUMMARY" - fi - - # Upload the machine-readable JSON (not just the rendered markdown): the - # trusted compare job re-renders the table from these numbers so it never - # posts PR-controlled strings (case names/notes) verbatim. The markdown is - # kept only for the job summary above. - - name: Upload report - if: always() - uses: actions/upload-artifact@v4 - with: - name: replay-bench-report - path: | - replay-bench.json - replay-bench.md - if-no-files-found: ignore - - # Posts the comparison comment. Consumes only the report artifact, never PR - # code, so it can safely hold a write-scoped token. - compare: - name: Comment on PR - needs: [prepare, bench] - runs-on: blacksmith-2vcpu-ubuntu-2404 - timeout-minutes: 10 - if: needs.prepare.outputs.compare == 'true' - permissions: - contents: read - pull-requests: write - steps: - - name: Download report - uses: actions/download-artifact@v4 - with: - name: replay-bench-report - - - name: Comment on PR - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - // Re-render the table here, in the trusted (write-scoped) job, from the - // numbers the bench job computed — never the markdown the PR's driver - // emitted. Case name/category come from the PR's manifest, so escape - // them; everything else is a number formatted locally. - if (!fs.existsSync('replay-bench.json')) return; - const summary = JSON.parse(fs.readFileSync('replay-bench.json', 'utf8')); - const esc = (s) => String(s ?? '').replace(/\r?\n/g, ' ').replace(/[|`<>\\]/g, '\\$&').slice(0, 80); - const fmtNs = (ns) => ns >= 1e6 ? `${(ns / 1e6).toFixed(3)} ms` : ns >= 1e3 ? `${(ns / 1e3).toFixed(2)} µs` : `${Math.round(ns)} ns`; - const fmtInt = (n) => Math.round(n).toLocaleString('en-US'); - const labels = summary.labels || []; - const compare = labels.length === 2; - const lines = []; - if (compare) { - const [base, pr] = labels; - lines.push(`| transaction | category | gas | \`${esc(base)}\` median | \`${esc(pr)}\` median | Δ time | \`${esc(base)}\` Mgas/s | \`${esc(pr)}\` Mgas/s | verdict |`); - lines.push('|---|---|--:|--:|--:|--:|--:|--:|---|'); - for (const c of summary.cases) { - const d = `${c.delta_pct >= 0 ? '+' : ''}${c.delta_pct.toFixed(1)}%`; - lines.push(`| ${esc(c.name)} | ${esc(c.category)} | ${fmtInt(c.gas)} | ${fmtNs(c.base_median_ns)} | ${fmtNs(c.pr_median_ns)} | ${d} | ${fmtInt(c.base_mgas_per_sec)} | ${fmtInt(c.pr_mgas_per_sec)} | ${esc(c.verdict)} |`); - } - } else { - const only = labels[0] || 'pr'; - lines.push(`| transaction | category | gas | \`${esc(only)}\` median | \`${esc(only)}\` Mgas/s |`); - lines.push('|---|---|--:|--:|--:|'); - for (const c of summary.cases) { - lines.push(`| ${esc(c.name)} | ${esc(c.category)} | ${fmtInt(c.gas)} | ${fmtNs(c.median_ns)} | ${fmtInt(c.mgas_per_sec)} |`); - } - } - let table = lines.join('\n'); - if (compare) { - table += `\n\n**${summary.cases.length} transactions — ${fmtInt(summary.regressions)} regression(s), ${fmtInt(summary.improvements)} improvement(s)** (threshold ±${Number(summary.threshold_pct).toFixed(1)}% on median time; ABBA-interleaved).`; - } - const base = '${{ needs.prepare.outputs.baseline_sha }}'; - const head = '${{ needs.prepare.outputs.feature_sha }}'; - const repo = context.payload.repository.html_url; - const body = - table + - `\n\n> Comparing [\`baseline\`](${repo}/commit/${base}) → [\`feature\`](${repo}/commit/${head}).` + - `\n> Sub-10µs cases are noisy on shared runners; read the larger cases and the overall trend.`; - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - body, - }); diff --git a/.gitignore b/.gitignore index de945a462..4a559fb23 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,8 @@ # Python bytecode cache (scripts/) __pycache__/ + +# insta's pending snapshots: a differing snapshot's new value, written beside it outside CI, until +# it is reviewed and accepted (or rejected) with `cargo insta review`. +*.snap.new +*.pending-snap diff --git a/AGENTS.md b/AGENTS.md index 0b691789b..eb470a8c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,32 +6,53 @@ This file provides guidance to AI agents (e.g., claude code, codex, cursor, etc. MegaEVM (mega-evm) — a specialized EVM implementation for MegaETH, built on **revm** and **op-revm** by customizing the hooks revm exposes through its traits. -This branch (`satin`) builds **Satin**, the new engine: a single spec on the MegaETH fork of revm 40.0.3 and the MegaETH fork of op-revm 20.0.0. -Today's `main` is the legacy engine; Satin is the only active spec. -The legacy engine (specs `Equivalence` through `Rex7`, the 1.x crate line on crates.io revm 27) is frozen and is not edited here. +This branch (`satin`) builds **Satin**, the new engine's first spec, on the MegaETH fork of revm 40.0.3 and the MegaETH fork of op-revm 20.0.0. +Today's `main` is the legacy engine; the specs after Satin are added to this engine (see Spec System below). +The legacy engine (specs `Equivalence` through `Rex6`, the 1.x crate line on crates.io revm 27) is frozen and is not edited here. +Satin follows Rex6 on the spec ladder and is the one unstable spec. -Satin is being built mechanism by mechanism from an empty skeleton. -The module table below says what exists and which mechanisms fill the rest. +Every mechanism of the Satin spec is in place; the module table below says where each lives. ## Build & Development Commands ```bash -# Build -cargo build +# Build (plain `cargo build`, `cargo check` and `cargo test` cover only the default member, mega-evm) +cargo build --workspace # Test -cargo test # all tests +cargo test --workspace # all tests +# The debug CI job: the same run through cargo-insta, failing on a differing or unreferenced snapshot +cargo insta test --workspace --check --unreferenced=reject --test-runner cargo-test --no-quiet --fail-fast +cargo insta review # go through the .snap.new files a failing local run wrote +cargo test --workspace --release --locked # the release CI job cargo test -p mega-evm # core crate only cargo test -p mega-evm -- test_name # single test +cargo test --manifest-path bin/mega-evme/Cargo.toml # the mega-evme tool (not `-p`: it links mega-evme 1.7.1) # The gas schedule's byte prices are an input; this feature lets a measurement build change them cargo test -p mega-evm --features satin-price-override,test-utils # Run the suite with MEGA_SATIN_CPSB and MEGA_SATIN_CPHB unset: with either of them set the tests # that assert the spec's own byte prices skip, and the suite checks less than it looks like it does +# The suite at other byte prices, as the byte-price grid job runs it (logs under target/price-grid) +scripts/price_grid.sh --pr # five points; --full for the whole grid, or name points: 312.5/20 + # Regenerate the checked-in pricing table after an intentional schedule or engine change UPDATE_SATIN_PRICING_TABLE=1 cargo test -p mega-evm --test satin +# The execution-spec gate (see Test Gates): Ethereum's state-test fixtures through MegaEvm, per fork +cargo run --release -p state-test -- --fork Osaka /state_tests +cargo run --release -p state-test -- --fork Amsterdam /state_tests +cargo run --release -p state-test -- --mode satin --fork Osaka /state_tests # the report +# The blockchain tests through the block executor, with the pins the gate's job passes +cargo run --release -p state-test -- btest /blockchain_tests --expect-deviations +# The witness replay over the fixtures, as the gate's job runs it: every file (SAMPLE=0), per fork and mode, +# the fixtures named by an absolute path (the test runs in the package's directory) +MEGA_STATE_TEST_FIXTURES=$PWD//state_tests MEGA_STATE_TEST_SAMPLE=0 MEGA_STATE_TEST_FORK=Osaka \ + MEGA_STATE_TEST_MODE=satin cargo test --release -p mega-state-test --test witness -- --ignored --nocapture +# Regenerate the rendered deviation registry after changing crates/mega-state-test/src/deviations.rs +UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations + # Check compiler errors (preferred over clippy for quick checks) cargo check cargo check -p mega-evm @@ -48,91 +69,302 @@ cargo codspeed build -p mega-evm --bench && cargo codspeed run # inst # no_std check (run against riscv target) cargo check -p mega-evm --target riscv64imac-unknown-none-elf --no-default-features +# The declared minimum toolchain, as CI's msrv job runs it +cargo +1.94.0 check --workspace --all-targets --all-features --locked + # System contracts (requires Foundry) cd crates/system-contracts && forge build +cd crates/system-contracts && forge test # the system-contract CI job ``` Git submodules are required — clone with `--recursive` or run `git submodule update --init --recursive`. ## Workspace Structure -| Crate | Path | Member | Purpose | -| ----------------------- | ------------------------- | ------ | ------------------------------------------------------------ | -| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | -| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | -| `mega-state-test` | `crates/mega-state-test` | no | State-test runner library; rejoins when ported to Satin | -| `state-test` | `crates/state-test` | no | State-test CLI; rejoins when ported to Satin | -| `mega-evme` | `bin/mega-evme` | no | EVM execution CLI; rejoins when ported to Satin | -| `mega-t8n` | `bin/mega-t8n` | no | State transition (t8n) tool; rejoins when ported to Satin | +| Crate | Path | Member | Purpose | +| ----------------------- | ------------------------- | ------ | ---------------------------------------------------------------------------------------- | +| `mega-evm` | `crates/mega-evm` | yes | The Satin engine | +| `mega-system-contracts` | `crates/system-contracts` | yes | Solidity system contracts with Rust bindings (Foundry-based) | +| `mega-state-test` | `crates/mega-state-test` | yes | Execution-spec runner on Satin: the state-test gate and report, the blockchain-test gate | +| `state-test` | `crates/state-test` | yes | The runner's CLI | +| `mega-evme` | `bin/mega-evme` | yes | EVM execution CLI: Satin in-tree, legacy specs on the released 1.7.1 CLI | -The four tool crates still target the legacy engine. -They are outside `[workspace] members`, so no workspace command builds them; do not edit their sources until they are ported to Satin. +`mega-evme` runs a command on the engine its spec names: `Satin` on the in-tree sources, a spec from `Equivalence` to `Rex6` on the released `mega-evme` 1.7.1 and `mega-evm` 1.7.1, which it links under the aliases `mega-evme-legacy` and `mega-evm-legacy` (its `legacy` feature, on by default). +Because it links a package of its own name, select it by manifest path, not with `-p`: `cargo test --manifest-path bin/mega-evme/Cargo.toml`. +The legacy line's versions are pinned to the 1.7.1 release's lockfile and guarded by `bin/mega-evme/tests/legacy_line.rs`, the precompiles' backends and the encodings it shares with the engine included; the few the engine's alloy 2 line holds above the release are pinned where they are. ### Dependencies on the forks The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crates to the MegaETH fork with `[patch.crates-io]`. -`op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates (`alloy-op-evm`, `op-alloy-*`) come from the same monorepo revision. +`op-revm` is declared from the OP monorepo revision the node locks and redirected to the MegaETH fork of op-revm with `[patch."https://github.com/ethereum-optimism/optimism"]`; the OP alloy crates the engine links (`alloy-op-evm`, `op-alloy-consensus`, `op-alloy-network`, `op-alloy-rpc-types`) come from the same monorepo revision, and `op-alloy-flz` is a crates.io pin. - Patch the twelve revm crates together, or the build resolves a second copy of revm. -- `cargo tree -i revm` must show exactly one revm, from the fork. +- `cargo tree -i revm` must show exactly one revm, from the fork: the engine's graph (the default member) never reaches another. + The workspace also locks revm 27.1.0, linked only by `mega-evme`: its `legacy` feature, and its `mega-state-test` 1.7.1 dev-dependency, which is unconditional, so a test build without `legacy` links it too (`cargo tree --workspace -i revm@27.1.0`). - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. +- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), and on the fork's precompile price (`Precompile::required_gas`), neither of which upstream revm has. +- The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance. +- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation. ## Architecture ### Spec System (`MegaSpecId`) -`MegaSpecId` has a single rung, `SATIN`, running on `OpSpecId::KARST` (Ethereum `OSAKA`). -`MegaHardfork` has the single fork `Satin`, which activates `SATIN`. +`MegaSpecId` has one rung so far, `SATIN`, running on `OpSpecId::KARST` (Ethereum `OSAKA`). +`MegaHardfork` has one fork so far, `Satin`, which activates `SATIN`. - `SATIN` is the unstable spec under active development: it has no activation timestamp yet (`block/chain.rs` lists the two chains with the Satin timestamp unset), and its behavior may change until it is sealed. - Display and `FromStr` use `"Satin"`; serde uses the variant name `"SATIN"`. -- The legacy spec names (`Equivalence` … `Rex7`) parse to `ParseMegaSpecError::Legacy`; they are never mapped to Satin. -- There are no spec gates: a single-spec engine has nothing to gate. - The spec that follows Satin introduces the first `is_enabled`-style gate. +- The legacy spec names (`Equivalence` … `Rex6`) parse to `ParseMegaSpecError::Legacy`; they are never mapped to Satin. +- There are no spec gates yet: with one rung there is nothing to gate. +- The next spec is added as the legacy engine added Rex1 (#115, eleven files): a `MegaSpecId` variant after `SATIN` with its name and its `into_op_spec` arm; a `MegaHardfork` variant that activates it, and a params mechanism if it is the first fork to need chain-configuration parameters (Satin carries none); an `is_enabled`-style ordering on `MegaSpecId` and a gate at every site whose behavior changes; the constants it changes, keyed by spec, a limit it changes as its own arm of `ProtocolLimits::for_spec`; and its upgrade page under `docs/spec/upgrades/`. + From then on Satin's behavior is fixed: a gate keeps Satin's path as it is. + The extension points it builds on are already in place: the spec argument the factory and the context take, the per-spec limits table, and `into_op_spec`. ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds now | Filled by | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle, the interceptor scheme guard and the system-transaction promotion in `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the SALT pricing hook, the block-hash record and the non-warming journal reads (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); the Satin precompile set with the repriced KZG (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver` and the creation-revival refusal (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm) | history gas, compute gas; revert-class policy aborts, the system-call reservoir split; EIP-7708 and SLOTNUM; native keyless deployment (`MegaEvm::rewrite_keyless`), inspector support | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `BlockLimits`, `BlockLimiter` (`limit.rs`); `BlockGasCounters`, `MegaBlockTxResult` (`result.rs`); the pre-block call helpers (`eips.rs`); `MegaTransactionExt` (`helpers.rs`); the block-hash record (`evm/state.rs`) | the pre-block system calls and system contract deployment (the two hook points of `apply_pre_execution_changes`), the state-gas and write-record block limits | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | the oracle | -| `limit/` | `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes and write records (`frame_limit.rs`), staging, the latch; `EvmTxRuntimeLimits` (a data-size cap and a flat frame budget, both unlimited by default) | the data-size limit (its limit and per-frame budget rule, the transaction-body and code-deposit bytes), detention, the state-growth and KV limits | -| `access/` | nothing | volatile-data access tracking (detention) | -| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` and `MegaLimitControl` interceptors (`control.rs`, `limit_control.rs`); the Oracle's hint path (`oracle.rs`); the `KeylessDeploy` dispatch and its fixed overhead (`keyless/dispatch.rs`) next to the Nick's Method transaction format, validation helpers and error ABI (data only); the system-address transaction and its whitelist (`tx.rs`) | system contract deployment; the oracle and control contracts (the detention and compute-ledger semantics the two control contracts answer with, and the Host's oracle reads); keyless deployment as a native CREATE sub-frame | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits) | the Satin gas schedule reads the state-gas numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | — | -| `test_utils/` | `MemoryDatabase`, `ErrorInjectingDatabase`, `BytecodeBuilder`, `GasInspector`, `transact`, the JSON `Scenario` format | `BytecodeBuilder` is extended with EIP-7708 and SLOTNUM | +| Module | Holds | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, and the system-transaction promotion in `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, the volatile-read wrappers, the out-of-gas notes and the `KECCAK256` and copy wrappers that exist for them, and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, and which calls gas detention may price from it (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver`, the settlement of a frame that kept nothing, the journal's revert of a success an inspector rewrites into a failure and the guard that keeps an inspector's refused charge from classifying a frame (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch and the system-call reservoir split the spec fixes on, whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`); the system-call entry points, `transact_system_call_with_gas_limit` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size budget), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its data-size limit (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes, write records, history allowances and the log and code bytes of the history byte count (`frame_limit.rs`), staging, the stops its frames return and the one the transaction reports, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; `EvmTxRuntimeLimits` (the data-size limit: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | +| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | +| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | ### How Satin executes today - `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. -- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 off, the system-call reservoir margin off, the contract size limit at 512 KiB and the initcode size limit at 1 MiB. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, a system call's gas above 30M in its reservoir (the fork's `system_call_state_gas_margin_in_reservoir` on), the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB and the initcode size limit at 1 MiB. + That function is exported as `spec_cfg`: a node builds its `EvmEnv` through it, so what reads the env before an EVM exists (reth's gas estimation reads the execution cap) reads the configuration the EVM runs with. +- What a transaction pool can decide without state is the handler's own `validate_env` and `validate_initial_tx_gas`, run on an EVM over an empty database (`validate_transaction_stateless`, `evm/validation.rs`). + `validate_env` is split at the state read of the live system address (`MegaHandler::validate_env_as`): the pool passes the address in, read with `system::live_system_address`, and the system address's nonce and code are left to the state, as every sender's are. + It reports the intrinsic gas by ledger (`IntrinsicGas`): regular, state (zero under EIP-2780, which charges the state a transaction adds when it runs), the body's history, and the floor. + op-revm includes a deposit that fails validation as a failed deposit rather than refusing it, so for a deposit or a promoted system-address transaction the error says it would fail. Gas above the 200M execution cap goes to the EIP-8037 reservoir. -- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the seventeen entries EIP-8038 repriced go back to their Osaka values, and the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte. - It is built once per process and installed on every configuration; the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. +- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte, and the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`). + Every regular-gas entry is Amsterdam's, EIP-8038's state-access prices included, so creating state costs the access and the write in regular gas and the new state itself in state gas alone, as upstream. + The static opcode prices, which revm keeps in the instruction table, are Amsterdam's too (`satin_gas_table`): they part from the Osaka base's only in EIP-8038's 200-gas base of `EXTCODESIZE` and `EXTCODECOPY`. + It is built once per process, with a second copy that prices that entry at zero for a transaction exempt from history gas (`satin_gas_params_history_exempt`); the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. `crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, what nine probe transactions spent, and what two of those probes spend with the bucket they write into crowded; a test renders it and compares it to the file. - The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the metering wrappers go in; `CLZ` is gated on Osaka and needs no activation. + `SLOTNUM` pushes `BlockEnv::slot_num`, which the node supplies, and zero for a block that leaves it unset. - The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000, carried as an alloy-evm `PrecompilesMap` so a node can add or replace an address (`MegaEvmFactory::with_dyn_precompiles_builder`). -- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did, the block-hash read the Host records and the state-gas price the Host scales. - With no limit configured Satin still equals op-revm: `tests/satin/equivalence.rs` pins it on the same `CfgEnv`, field by field; a later change that alters behavior on purpose updates that baseline. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did, the block-hash read the Host records, the state-gas price the Host scales and the loads of volatile data the Host marks or refuses. + Satin's one divergence from op-revm on an ordinary transaction is the history gas it charges: `tests/satin/equivalence.rs` holds every baseline case to op-revm's total plus the history ledger, on op-revm's own state gas, logs and state, and pins what that ledger is made of; a later change that alters behavior on purpose updates that baseline. - SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`). A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. - A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or the address a creation transaction deploys at, by an applied EIP-7702 authority, and by the beneficiary a `SELFDESTRUCT` moves a balance to; the bytes a creation deposits are charged in the deployed address's bucket. + A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or the address a creation transaction deploys at, by an applied EIP-7702 authority (its account and its delegation indicator), by the beneficiary a `SELFDESTRUCT` moves a balance to, by the caller a deposit-like transaction creates, and by a keyless deployment's signer when the creation's nonce bump creates it and its deploy address; the bytes a creation deposits are charged in the deployed address's bucket. The capacities come from the transaction's `SaltEnv` through `BucketMultipliers` (`external/gas.rs`), which reads a bucket once per transaction; the cache is cleared with the rest of the per-transaction state. A system-originated transaction prices at the minimum bucket and reads no capacity at all, so a state change the protocol mandates cannot be priced out by the growth of a region it does not control; that is a transaction whose caller is the EIP-4788 system address, the sequencer's own system transaction — before or after the engine promotes it to a deposit — and every transaction run through a system-call entry point. A failed capacity lookup reports nothing and records its cause the way a failed `sload` does; the transaction fails with that cause rather than settling at a price nobody chose. At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. -- The common execution layer counts data-size bytes and write records per frame and enforces nothing by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to drive the abort protocol. +- History gas prices the bytes a transaction appends to the chain, at `MegaETH`'s cost per history byte and never scaled by SALT — history bytes live in no bucket (`evm/history.rs`). + The byte table is the `limit` module's, the same counts the data-size limit meters, so a record's history bytes are its own data size and the two cannot drift apart: a transaction body of 310 bytes (110 for the envelope and one 40-byte record for each of the five writes every transaction makes — the sender's account and the four accounts its fees are credited to), one byte per calldata byte, 20 per access-list address and 32 per key, 101 per EIP-7702 authorization, a log's 32 for its address and 32 per topic plus its data, one 40-byte record per kept account or storage write, and one byte per byte of deployed code. + The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body in the EIP-8037 intrinsic state-gas slot, where the reservoir pays it first and it is not held to the execution cap, and the two record charges in pre-execution, where the records are made. + A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas, and the settled result takes the body back out of the state gas it reports. + Every other charge is made where the record is: the opcode wrappers charge what the Host staged for them, and `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their caller for the records the frame they start makes, out of what the caller kept rather than out of what it forwards. + What a frame does not keep comes back, at the same price, to whoever paid it. + The pairing is per record: per transaction the two totals part at three sites, each by decision — an Oracle hint's payload is data size that is never history, an EIP-7708 transfer log is data size that is never history either, and the body's five records are an upper bound, so a transfer to the block beneficiary or a fee vault pays a record the body already bound. + A deposit, a transaction the protocol itself produced and a system call pay no history at all (`MegaContext::prices_history`), and an exempt transaction runs a schedule that prices a deposited byte at zero, so the one history charge revm makes itself is off it too. + The EIP-7623 calldata floor is still computed and validated. + At the spec's byte prices it never raises the gas used of a transaction that pays history, because history charges the same bytes at a higher rate; it can raise an exempt transaction's, and it binds the figure a block counts on its execution ledger, `max(regular, floor)`. +- A value-transferring `CALL` or `CALLCODE` below the transaction's own frame grants the frame it starts a history allowance of 160 bytes — one three-topic event carrying a word — at the cost per history byte, so a `receive()` hook reached through Solidity's `transfer()` can still emit an event. + It is not gas: it never enters the frame's `Gas`, only a log's charge may draw on it, and what it pays for is on no ledger, because no pool of the transaction's gas paid it. + The history bytes a transaction reports count those bytes all the same, so the byte column and the history gas column part by exactly what allowances paid. + The transfer log of the value that granted the allowance draws nothing from it: the log costs no history. +- EIP-7708 is on: every value movement — the transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT`'s balance moved to another account — emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm journals itself, without a `LOG` opcode, and the receipt carries in execution order among the contracts' own logs. + A `CALLCODE`, a call to itself and a transaction's value to its own sender move nothing to another account and log nothing; a deposit's value is logged and its mint is not; a destruction to itself burns the balance of an account created in the transaction without a log, because the base spec predates EIP-8246 and this revm emits no `Burn` log. + A transfer log is data size like any log, counted by the rule a `LOG3` of one word is — 160 bytes, `TRANSFER_LOG_SIZE` — and nothing else: it is no write record and pays no history gas, because Ethereum prices it at nothing and it is not a byte the transaction chose to write. + It is counted where the value moves, on the lane of the frame whose journal checkpoint holds the move: a frame start's log with its records, before revm builds the frame and so before its checkpoint, which lets a crossing answer the frame with the stop before any value moves; a `SELFDESTRUCT`'s with its beneficiary's record once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. + A frame start is counted before revm decides it, from what revm itself checks as far as the caller's account decides it, read from the journal without loading anything (`caller_refuses_start` in `evm/execution.rs`): a start revm refuses there — a value its caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes nothing, so it counts no log and no record, is charged no history, and no limit stops it. + The one refusal decided after the count is a creation onto an occupied address, which revm reads off the created address's account only when it builds the frame: its records and log are counted, so a crossing they cause stops the creation where revm would have failed it on the collision. + A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted, so no start is counted for a nonce revm never bumps. + A debug build asserts after every frame start that revm refused exactly the starts predicted and journaled exactly the log that was counted; `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. +- The data-size limit holds a transaction to `EvmTxRuntimeLimits::tx_data_size_limit` and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left, under an optional frame cap. + The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes). + A frame that crosses its budget or the transaction's limit reverts alone, and its caller resumes (the contracts below). + Every `MegaContext`, a bare one included, runs under its spec's limits, and a block executor installs the same (see the protocol limits below): Satin holds each transaction to `TX_DATA_LIMIT` and the block to `BLOCK_DATA_LIMIT`, 12.5 MiB each. + The block's data size is a packing budget (see the block executor below). + `tests/satin/data_size.rs` derives where the stop gives way to out-of-gas: a top-level fresh `SSTORE` is counted at 152,306 gas, and keeping its record costs its 3,520 history on top. +- A limit stop names one of two runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), counted on the lanes with a transaction limit and frame budgets, and compute gas (2), gas detention's stop. + The legacy engine's KV updates (1) and state growth (3) name no dimension: `LimitKind::from_u8` answers `None` for them. +- No limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write, deduplicated per frame and taken back with a write-back or a failed frame — and the count is still reported, in the outcome's usage and the block's. + The sender's account and the fee accounts are the body's, not records, so a transaction that writes nothing counts none. + A record is forty bytes of data size, counted and taken back with them, so `KV × 40 ≤ data size` holds after every instruction (`tests/satin/write_records.rs`), and at the production data-size caps a transaction or a block keeps at most 327,680 records. + History gas prices every record. +- No limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in, so what bounds it is what it costs — the transaction's gas limit and the block's (`tests/satin/state_growth.rs`). +- The limits that change a result are protocol values fixed per spec, as the legacy engine's were: `ProtocolLimits::for_spec` (`block/limit.rs`) is the one table of them, keyed by `MegaSpecId`, with one arm, `SATIN`, every field written out. + It holds the four per-transaction limits (`tx_runtime_limits`, an `EvmTxRuntimeLimits`: data size per transaction 13,107,200, no frame cap beyond the 98/100 share, detention's two caps 20,000,000 each) and the block's data-size budget, 13,107,200; the values are provisional with the constants. + No chain configuration carries them: they are not fork params, a genesis file names none, and a node passes none of them; a test holds them to what the removed load-time check held a chain's values to (none zero, the data size above `TX_BODY_SIZE`, the detention caps below `MAX_TX_COMPUTE_GAS`, 199,987,900, so detention binds), and `tests/block/l1_attributes.rs` holds the block's L1 attributes deposit to them. + Three layers keep three scopes: `ProtocolLimits::for_spec` the consensus values; `EvmTxRuntimeLimits` what one EVM runs under, the table's by default (`Default` is the default spec's), which a tool or a test may replace; `BlockLimits` the builder's policy, which only tightens. + `MegaContext::new` starts under its spec's limits, so an EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) and a bare context run under the limits block execution would hold their block to without being told; `MegaEvmFactory::with_tx_runtime_limits` and `MegaContext::with_tx_runtime_limits` are the explicit opt-outs, for equivalence, tools and tests. + The block executor reads the table for the spec its EVM executes, installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to its data-size budget; `MegaBlockExecutor::with_protocol_limits`, which exists only under `cfg(test)` or `test-utils`, holds a block to other limits, for tests and for `mega-evme --override.limits`. + The block's gas limit is the executor's state (`BlockLimiter::block_gas_limit`), taken from the block environment; no policy carries one. + The node's block context carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap on the data-size budget that `BlockLimits::within` holds below the protocol's, so a policy tightens and never loosens; its default restricts nothing, and a validator leaves it so. + A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/building_policy.rs`). + Satin carries no fork parameter: the `SequencerRegistry`'s roles are what the registry the legacy forks left holds. + A genesis file's `config` object carries Satin as one key, `satinTime`, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads it with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value that is not a 64-bit integer, and a schedule `validate_schedule` refuses; the key format is provisional. +- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. + It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit. + What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is. + A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction it refuses as any legacy transaction, because the block decides on the envelope (see the block executor below). + A user's deposit is not system-originated and is held to every per-transaction limit. +- Gas detention caps the compute a transaction may spend once it read volatile data — the block environment, the block beneficiary's account, the Oracle's storage — at its compute at the read plus a cap, a runtime limit of 20,000,000 by default (see Gas detention below). + It holds a frame's spendable gas with the revm fork's withheld part, which every reader of the frame's gas but a regular charge counts, so a detained transaction runs as it would without the read until a regular charge needs the withheld part. + That crossing stops the frame that makes the charge, with `MegaLimitExceeded` of kind compute, and its caller resumes held to what the limit leaves; every other out-of-gas halts as it would without the read. - `MegaBlockExecutor` runs a block: alloy-evm's `BlockExecutor` over a `MegaEvm`, mirroring what alloy-op-evm's `OpBlockExecutor` does for an OP chain. - It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to `BlockLimits` and fills `BlockGasCounters`. - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` names two hook points that are empty today: system contract deployment and the pre-block system calls. -- Four of the six system contracts answer calls through their interceptors (`system/`). + It applies the three block rules of the Karst base — an activation block admits only deposits, the data-availability footprint is a block limit reported as the block's blob gas, and the L1 block info is read by the first transaction that prices against it — holds every transaction to the spec's `ProtocolLimits` and the builder's `BlockLimits`, and fills `BlockGasCounters`. + The block's data-size limit, known only after execution, packs the transaction that reaches it and then refuses every later transaction before it runs. + It never refuses a deposit or a Mega System Transaction: it is a packing budget for the transactions the builder chooses, and neither is chosen; both still count towards it, so the transactions after them find the room they used. + Nor does the builder's policy refuse either. + No block limit holds the execution, state or history ledger, or the write records: they are counted and reported. + A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which an activation block refuses and which the data-availability limits and footprint hold like any non-deposit transaction, but the block decides before the engine promotes it that it is one (`MegaBlockTxResult::is_system_transaction`: a legacy call of the system shape from the live system address, read with `live_system_address` and `classify_system_transaction`), and the data-size budget and the builder's policy do not refuse it; the commit-time check reads the same flag. + alloy-evm's `commit_transaction` cannot fail, and its contract is that an outcome commits before the next transaction executes; a builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the counters again and refuses what no longer fits, and a debug build asserts the same check in `commit_transaction`. + The checked commit also refuses an outcome whose sender's nonce or balance — the system address's, for a system-address transaction — another commit moved since it executed (`MegaBlockExecutionError::StaleOutcome`, an internal error; the executor reads the sender's account before every transaction into `MegaBlockTxResult::{sender, sender_nonce, sender_balance}`), and a debug build asserts it in `commit_transaction`; any other state a candidate read is the builder's to keep fresh, which the system-transaction-first flow relies on (`tests/block/stale.rs`). + It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, read-only entries included — that sequence of committed states, with the included transactions' and the exports, is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`), which receives each state whole, where the block's transitions keep only what a state changed; after the two EIP calls it checks the seven predeploys in Satin's activation block alone (see below), applies a role change the `SequencerRegistry` has due in the block (see the system calls below), and last commits the L1 block contract's account and every slot the transactions can be priced against (`L1_BLOCK_INFO_SLOTS`: 1, 3, 5, 7 and 8) as read-only entries (`read_l1_block_info`), because op-revm and the executor read them on the block's state rather than through a transaction's journal, so they land in no transaction's state. + The overhead (5) is in the entry whatever the Ecotone scalars hold: op-revm reads it when the scalars it finds at the block's first non-deposit transaction are empty, which a deposit earlier in the block decides, so an entry listing it only under empty pre-block scalars would leave a read no state names (`tests/block/witness/state.rs`). + The pre-block step does not read the live system address: the executor reads it before every non-deposit transaction, as above, and every transaction reads it itself when it is validated (see below). +- Satin deploys, upgrades and seeds no contract: it runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs (the Oracle at v2.0.0, Rex5's, and the `SequencerRegistry` at v2.0.0, Rex6's), and whose genesis OP's tooling gave the EIP-7997 factory. + The block in which Satin activates reads the seven in order, and each must hold exactly Satin's code, whatever its nonce, balance and storage (`check_system_contract`, `system/predeploys.rs`); anything else — no account, no code, an older version, other code — refuses the block with one error naming the address and both code hashes (`MegaBlockExecutionError::UnexpectedSystemContractCode`, a verdict on the block), and each read is a read-only pre-block state. + The node says which block that is (`MegaBlockExecutionCtx::satin_activation_block`, off by default), from its schedule and the parent's timestamp as it sets `no_user_tx_activation_block`; no other block reads the seven. + A test or a tool that runs a Satin block on a state of its own puts them there in the shape Rex6 left them (`test_utils::rex6_predeploys`, `MemoryDatabase::rex6_predeploys`, `SequencerRegistryRoles`). + Three of the six system contracts have interceptors (`system/`) — `MegaAccessControl` and `MegaLimitControl` answer, the Oracle's forwards a hint and lets its bytecode run, or answers a hint that would cross the data-size limit with the stop — and `KeylessDeploy`'s `keylessDeploy` is taken by the keyless dispatch before interception. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input; an unknown selector is not intercepted and runs the contract's own bytecode. - `MegaAccessControl` and `MegaLimitControl` answer with what the common execution layer knows until detention and compute gas fill them in, the Oracle forwards a `sendHint` payload to the node's oracle service, and a `keylessDeploy` transaction is charged its fixed overhead and handed to the keyless rewrite hook. -- The system address may send transactions the protocol pays nothing for (`system/tx.rs`): a legacy transaction from it to a whitelisted contract is validated — the whitelist, the chain id, the nonce, EIP-3607 — and promoted to a deposit, and the account a deposit-like transaction creates for its caller is charged the account-creation state gas once. -- The legacy engine's gas leakage pitfalls, limit-check protocol and storage-gas stipend describe mechanisms that do not exist here; the contracts below replace them. + `MegaAccessControl` steers detention's switch for the frame that calls it (see Gas detention), `MegaLimitControl.remainingComputeGas()` answers the compute the calling frame could still spend, and the Oracle forwards a `sendHint` payload to the node's oracle service. + `remainingComputeGas()` answers the lesser of two figures, read when the call reaches the interceptor, after the calling opcode charged its own costs: the caller's own regular gas with the gas the call forwarded counted back (the answer returns it untouched, so this is what the caller holds when the call returns), and, once a read of volatile data set a limit, what the limit leaves the transaction (`Detention::allowance`). + That is the caller's spendable regular gas before the forward, which detention caps; a transaction that calls the contract directly hears its own frame's regular gas, or detention's cap when it is detained from its start (its sender is the block beneficiary). + The figure is regular gas only: the reservoir is not in it, so a transaction above the execution cap hears at most the cap's share. + Of the legacy engine's figure one property carries over, that the gas a call forwards is not counted; the figure itself departs from it, because the legacy one came from a separate compute ledger, with per-frame budgets of 98/100 of the caller's remaining compute under the transaction's compute limit, and could exceed the caller's gas, where here compute is regular gas and the answer is at most the caller's own. + A `sendHint` from a frame whose volatile-data access is off — its own switch or one above it — is dropped: not forwarded and not counted, while the call runs the bytecode as any other. +- The Oracle's storage is read through the oracle environment: an `SLOAD` in the Oracle's own frame (a load whose owner is the Oracle) loads the slot through the journal, then asks `OracleEnv::get_oracle_storage`, and gets the environment's value when it answers — even over a value the Oracle's frame stored earlier in the transaction — and the loaded value when it answers `None`; `EmptyExternalEnv` always answers `None`. + A node that replays a block without the service must price and witness it as the node that built it did, and it cannot tell which source the building node read, so nothing may depend on the source: every such read is priced as a cold access, however often the slot was read, and the slot is loaded on both paths, so afterwards it is warm for the frame's `SSTORE` and it is in the transaction's state, which a stateless witness is built from. + A frame whose regular gas, the part detention withholds included, cannot pay the cold access reads nothing and asks nothing, and a refused read asks nothing either; a detained frame that holds the gas but may not spend it does ask, and the charge then stops that frame at the compute limit. + It is a volatile read for detention, under the Oracle's cap, and a hint reaches the service synchronously as `sendHint` is called, so a read after a hint finds the service told. + A system call, a pre-block call among them, asks no service: its Oracle read answers the chain's slot and records nothing (`MegaContext::is_system_call`, set in `on_new_system_call` and cleared by the next transaction), so a chain whose EIP-2935 or EIP-4788 code reads the Oracle still replays from its witness. + Every such read by a transaction is recorded with its answer on the transaction's outcome (`MegaTransactionOutcome::oracle_reads`, the context's `OracleReadRecord`, emptied before every transaction and system call), which is where a node building a stateless witness takes the oracle answers of the transactions it includes from. +- A `keylessDeploy(bytes,uint256)` call a transaction makes is a native keyless deployment (`system/keyless/`): the pre-EIP-155 creation it carries is deployed as a `CREATE` of its signer, at the signer's Nick's-Method address. + The dispatch (`keyless::is_dispatched`) runs in `frame_init` before interception, and revm builds the call's frame as any call's: on the contract, at depth 0, on revm's frame stack, with its own journal checkpoint and gas. + No code runs in it: `frame_run` makes its actions by hand (`keyless::run`), on its first run the refusal or the creation, and on its resume, once the creation returned into it, the answer. + An inspector sees the frames the deployment is made of: the call, started and ended as any call's, with no interpreter initialized and no step in it, and the creation as its child, one journal depth below. + It charges the fixed overhead, which pays for decoding the transaction and recovering its signer, and holds the call to the legacy engine's nine rules and error ABI in the legacy engine's order, so a call several rules refuse reports the legacy engine's error. + Among the rules it charges the signer's account when the creation's nonce bump creates it, SALT-priced state gas, where the legacy engine charged it; after every rule, what the `CREATE` opcode charges its frame: its regular gas (the schedule's `create` entry and EIP-3860's cost per word of init code), the created account, SALT-priced state gas, and the creation's two write records. + It then starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left, which must still cover the signed gas limit. + Its lane is the one any depth-0 call pushes, running as the signer from the first run on. + The creation returns into the call through `frame_return_result`, which reads the creation's outcome before revm merges it (`keyless::returning`) and takes the nonce back after (`keyless::settle`), before the call resumes, and the call answers in the ABI on its resume. + The frame is built on the contract as its target: the contract's account, which the transaction loads with its code to start its first frame, is touched by a call that returns, as a call's target is; a witness holds the account and its code for any transaction to the contract, so the frame adds nothing to it. + A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm builds its frame, so no value moves and nothing its start would write is counted. + The dispatch is by address and selector, whatever the address holds: where the state holds no contract code, the frame is built on the contract's own, which never runs. + A stop of the call itself — its own charges past detention's limit, or a limit the creator's nonce record crosses on it — reverts it with the stop and takes the deployment back, the signer's nonce included; otherwise the call succeeds with the deployed address or the error the creation failed with, a limit's stop the creation crossed included. + `ORIGIN` and `GASPRICE` in the init code are the transaction's, and `gasUsed` is what the creation spent from either pool, the same below and above the execution cap. + Rule 4 (signer nonce at most 1) counts real nonces: the creation's bump stands from 0 to 1, which is the replay barrier. + From nonce 1 the settlement sets the nonce back, whether the deployment succeeded or failed, only when the creation's bump is the last nonce change the deployment made, so the signer stays at 1, as in the legacy engine: no number of failing calls — the call is permissionless and the signed transaction public — gets the signer's deployment refused, and a resubmission of one that deployed is refused `ContractAlreadyExists()`. + The bump's write record and its history go back with it, unless the creation succeeded and moved value out of the signer, whose account then keeps a write of its own. + A signer whose own code spends a nonce in the constructor that survives it keeps every bump, ends above 1, and every later deployment of it is refused `SignerNonceTooHigh`; on a default configuration only a delegated signer's code can do that, with a `CREATE` or `CREATE2`, successful or not. + The nonce is never moved back under a later bump, because a later bump may stand for an account. + `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError` are gone from the Rust enum and from `IKeylessDeploy.sol`, which changes no deployed byte: the sandbox's preflight and validation are gone, the overhead is regular gas a call that cannot pay runs out of, and a failed read or SALT lookup fails the transaction with its cause. + `tests/system/keyless/interface.rs` holds the generated binding's errors to the set `docs/spec/system-contracts/keyless-deploy.md` lists for Satin. +- The system address may send transactions the protocol pays nothing for (`system/tx.rs`): a legacy transaction from it to a whitelisted contract is validated — the chain id, which it must carry and which no configuration switches off, the nonce, EIP-3607 — and promoted to a deposit by the engine as it runs it (the block decides on the legacy envelope: see the block executor above), and the account a deposit-like transaction creates for its caller is charged the account-creation state gas once. + Which address that is, the `SequencerRegistry` says, and the transaction reads it itself (`system::load_system_address`, called first thing in `MegaHandler::validate_env`): every transaction, whatever its shape, loads the registry's account and `_currentSystemAddress` with revm's own loads, without the registry's code, and the two stay warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary, so what a transaction pays never depends on its envelope. + A transaction of the system shape — a legacy call to a whitelisted contract, tested on its own fields — whose caller is that address is a system-address transaction. + A transaction from that address without the system shape is invalid (`system::SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`, an `InvalidTransaction::Str`, so a pool and a block reject it, and op-revm includes a deposit, which never has the shape, as a failed deposit); every other sender is an ordinary one, an address a rotation retired included. + The read is an untouched entry of the transaction's state, which a commit skips, so it moves no state root; the comparisons with op-revm and Ethereum take it out first (`test_utils::take_system_address_read`). + The Oracle's `onlySystemAddress` tests the sender alone, so the refusal is what keeps the system key's other transactions, an L1 deposit from it included, from writing the Oracle; the legacy engine refused them with an error that is not a transaction's, so a deposit from the system address left its block unexecutable. + Nothing inside a block can change the address after the block's pre-block call — a change is scheduled for a later block and applied by that block's pre-block call — so every transaction of a block reads the address the pre-block step left, a rotation governs its activation block, and an EVM a node builds outside block execution (an RPC call, a trace replay) reads the one in the state it runs on without being told. + The read names no address unless the registry holds the code this engine requires (v2.0.0) and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution Satin's activation block refuses a chain whose registry does not hold the code, and a later block runs on the state it is given. + It is a read of the transaction's own, so the slot is in every transaction's state and witness, not in the pre-block witness. +- A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which its state writes draw first before spilling onto the regular budget. + The split is the fork's (`Handler::system_call_gas`, both system-call paths), switched on by `spec_cfg`; the neutral configuration leaves it off for both forks, as revm's runner does, and no state fixture makes a system call. + A system call stays the protocol's own work: priced at the minimum SALT bucket, paying no history gas, held to no per-transaction limit and not detained, so it settles exactly as op-revm's does on the same configuration (`tests/satin/system_call.rs`, `tests/satin/equivalence.rs`). + A transaction is not a system call: every transaction's gas is split by the execution cap, the system-address transaction's included. + The system calls the engine makes, and their gas limits: + + | System call | Target | Gas limit | Regular | Reservoir | + | ------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------------------- | ------------------------ | --------------------------------------- | + | EIP-2935 block hashes, pre-block | `0x0000F908…2935` | `pre_block_call_gas_limit`: max(block gas limit, 30M) | 30M | the block gas limit less 30M, or none | + | EIP-4788 beacon root, pre-block | `0x000F3df6…Beac02` | the same | 30M | the same | + | `SequencerRegistry.applyPendingChanges()`, pre-block, when a change is due | `0x6342…0006` | the same | 30M | the same | + | alloy-evm's `transact_system_call`, revm's `SystemCallEvm` and `InspectSystemCallEvm` | the caller's | revm's `SYSTEM_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 | + | `MegaEvm::transact_system_call_with_gas_limit` | the caller's | the caller's | the lesser of it and 30M | the rest | + + The pre-block calls run as the EIP-4788 system address (`0xff…fe`). + Their budget is the legacy engine's, kept as it was rather than replaced: it was widened for the storage gas a crowded SALT bucket multiplied past 30M, which a system call no longer pays, and what it adds above 30M is reservoir, which nobody pays for when the call does not draw it; a block of 30M or less gives no reservoir, and the calls' few writes spill onto 30M of regular gas. + A pre-block call that does not succeed refuses the block before its state is committed. + One helper runs all three pre-block calls and holds one rule for them (`block/eips.rs`, `transact_pre_block_call`): a database error the database calls fatal (`DBErrorMarker::is_fatal`) is an internal error (`BlockExecutionError::other`), because a read the database could not serve says nothing about the block and a node must not refuse a valid block because its storage failed; any other failure — a database error that is not fatal (under revm's `State`, an EIP-7928 block access list that does not cover a read), an EVM error other than the database's, or an outcome that is not a success — refuses the block with the call's own validation error (`BlockValidationError::BlockHashContractCall`, `BlockValidationError::BeaconRootContractCall`, `MegaBlockExecutionError::ApplyPendingChangesFailed`). + It is the rule alloy-evm's block executor holds a transaction's database error to (`BlockExecutionError::evm`). + +- The legacy engine's limit-check protocol describes mechanisms that do not exist here; the contracts below replace it. + Its gas leakage pitfalls have no counterpart: detention, the one mechanism that caps a frame's gas, withholds it inside the frame's own tracker, where every reader but a regular charge still counts it, so nothing it withholds is ever moved or released (see Gas detention). + Its storage-gas stipend does have a counterpart, the history allowance above, and it is a different thing: it never enters a frame's gas limit, so there is nothing to burn on return. + +### Gas detention + +`MegaETH`'s parallel executor redoes a transaction whose reads another transaction's writes invalidate, and some data changes with every block or transaction. +Detention caps how much a transaction may still compute once it read such data (`access/`). + +- **What is volatile.** + The block environment (`NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH`); the block beneficiary's account, through every account opcode, the four calls and the EIP-7702 delegate they follow, `SELFDESTRUCT` at either end, a sender or recipient that is the beneficiary, a recipient that delegates to it, an applied EIP-7702 authority that is, and a keyless deployment's signer that is (the call reads the signer's account through the journal, so it marks the read itself, at its compute then); the Oracle's storage, through `SLOAD` in the Oracle's own frame. + `BLOBHASH` is not: it reads the transaction's own blob hashes. + A system-originated transaction and a system call are not detained, whatever they read, the block environment included: the same rule exempts them from every per-transaction limit. + Neither is a transaction under `no_limits()`, which the execution-spec gate's runner installs. +- **Where a read is marked.** + Where the Host loads the value (`evm/host.rs`), and committed by the opcode's wrapper once the opcode completed (`evm/instructions.rs`), as a write record is; a load that fails, and a read whose opcode then fails, mark nothing. +- **The cap.** + Compute is the regular gas the transaction spends on what it runs, read off `Gas`: a frame's limit less what it has left — its withheld part included, so withheld gas is never spent — less the state and history gas that spilled onto its regular gas; what a halting frame burns is not compute either. + The transaction's compute is the running frame's regular gas spent plus every suspended caller's, each less its child's gas limit, which takes a value call's stipend off with it, less what halts burned: the regular ledger at every moment, the burns taken out. + The stipend stays outside compute on purpose, compute being regular gas drawn from the transaction's own pools: a callee may run up to 2,300 gas on each value call's stipend, and each value call costs its caller at least 9,100 of compute, so the gas run after a read is at most about 25% more than the cap. + A read sets a limit — the transaction's compute at the read plus its cap, `EvmTxRuntimeLimits::block_env_access_compute_gas_limit` or `oracle_access_compute_gas_limit`, 20,000,000 each by default (`BLOCK_ENV_ACCESS_COMPUTE_GAS`, `ORACLE_ACCESS_COMPUTE_GAS`) — and the limit only goes down, so the most restrictive read binds. + Nothing per frame is kept for the figure until a read sets a limit: `MegaEvm::frame_init` records a caller's regular gas spent and gas limit when revm is about to build a child of it (`record_caller`, `Detention::on_child_build`), and the first read rebuilds what the frames it runs under add from those records (`Detention::track`); from there every frame is kept as it starts, suspends, resumes and ends, and debug builds keep the eager figures from the first frame on and assert the kept ones equal to them. + `no_limits()` leaves both caps unlimited, and a transaction whose caps are both unlimited is not detained: that is how the neutral configuration's runner turns detention off. + It turns detention off together with every other per-transaction limit, so it is for equivalence mode and tests, not for executing the chain; `EvmTxRuntimeLimits::default()` and `ProtocolLimits::for_spec` detain, with caps below `MAX_TX_COMPUTE_GAS`, so a node running the chain never turns detention off. +- **The enforcement point: the withheld part.** + The revm fork keeps a frame's regular gas in two parts (`GasTracker`): a spendable part, the only one a regular charge draws, and a withheld part. + Every other reader sees their sum — `GAS`, the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold checks, the gas a child returns, the reimbursement — and a forward or a state or history spill draws the withheld part first. + Detention holds a frame's spendable part at what the limit leaves the transaction (`Gas::limit_spendable`): at the read, once its wrapper committed it; at the frame's start and every resume (`before_frame_run`); and after `SSTORE`, whose restore of a slot to its original value refills regular gas. + So a detained transaction runs exactly as it would without the read until a regular charge needs the withheld part: that charge fails as it would with nothing withheld, and the fork records a `WithheldCrossing` holding the regular gas the frame had before it, both parts together. + Nothing withheld is ever released: a frame's withheld part goes back to its caller with the rest of its gas, and `return_create`'s deposit and hash charges, the creating frame's own compute, draw the spendable part like any other regular charge. +- **The classification.** + A frame whose result carries a crossing record crossed the cap (`Detention::on_frame_end`). + It is read in `after_frame_run`, after revm processed the frame's last action — `return_create` included — and before the result reaches the caller, or, for the transaction's own frame, `last_frame_result`, which overwrites the frame's gas with the transaction's. + The frame becomes the stop's revert, `MegaLimitExceeded(2, limit)`, with its gas put back to the record's `remaining`: the charge that crossed is not made, the spendable and withheld parts go back to its caller, and the transaction's compute at the crossing is less than one charge short of the limit. + The caller resumes held to what the limit leaves, less than the charge that crossed, so a regular charge of its own past that crosses again and stops it in turn; one that ends within it ends the transaction within the limit. + The settlement is the same whether the halt zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, `return_create`'s own out-of-gas on a deposit charge). + The stop reports the transaction's compute at the crossing as what was used (`LimitCheck::ExceedsLimit`), the figure the regular ledger bills, computed the same way at every crossing site; the size of the charge that crossed is not kept, so it is at most the limit, unless a halting frame's leftover, counted as compute, took the transaction past the limit before the charge. + Every other out-of-gas halts and burns as it would without the read: an operand above `usize`, a failed state or history charge, a regular charge beyond the frame's whole gas. +- **Answers.** + revm runs a precompile inside the frame's start, against the frame's gas limit, so a precompile forwarded more than the allowance its frame would start with is decided before it runs (`hold_precompile` in `MegaEvm::frame_init`). + One the engine prices (`PricedPrecompiles::price`, `evm/precompiles.rs`) is decided from its price, read with `Precompile::required_gas` off the Satin table's own entry: priced within the allowance, it runs on its whole forward, as without the read; priced past the allowance and within the forward, it is answered without running, out of gas and marked `WithheldCrossing::with_remaining(forward)` (`Detention::cross_at_price`), and stopped by the same classification; priced past its whole forward, it runs on the forward and runs out of gas, a failed call its caller survives, as without the read. + A call revm refuses on its caller's account runs no precompile and is answered as without the read. + One residual is a choice: the price does not tell whether an input passes the checks a precompile makes after its gas check, so an input priced between the allowance and the forward that would fail such a check is the stop, where without the read the check fails the call, which its caller survives. + The Satin table prices an address only while the dispatched entry is still its own: not an address a node replaced through `MegaEvm::with_dyn_precompiles` (recorded, whatever id its precompile carries), not one whose dispatched entry carries another id, and nothing once the neutral configuration installed the fixture fork's set; a node's own precompiles carry no price either. + Every entry of the Satin table carries one, op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing included: the op-revm fork prices an input within a wrapper's size limit as the run it wraps does, and one past it, which the wrapper refuses before any gas check, at nothing. + alloy-evm's `PrecompilesMap` erases what it holds once a node changes it, so a change made around the engine, through the mutable reference to the map that revm's `EvmTr::all_mut` and alloy-evm's `Evm::components_mut` hand out, is not seen: an entry replaced through the map's mutable accessors under the replaced entry's id, and a whole set put in the map's place, whose entries are then priced from the Satin table wherever they carry its ids. + Neither accessor is a sign of a change — revm reaches the context through `all_mut` on every frame, and alloy-evm's tracer calls `components_mut` — so a node changes the set through `with_dyn_precompiles` or the factory's builder. + A precompile the engine cannot price is run on the allowance and sees it as its gas limit; its answer gets the rest of the forward back (`Detention::restore_forward`), and one that runs out of the allowance is marked as a crossing with its forward and stopped, whether its price is within the forward or not. + An interceptor builds its answer on the whole forward, the caller's withheld part included: an answer that spent more regular gas than the allowance the frame would have run on is answered out of gas, marked with `set_withheld_crossing` — its spending the charge that crossed, so its frame gets its whole gas back, less a spill the revert credits — and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer in `inspect_frame_init`); the one answer of the engine's own that spends regular gas is that of a `keylessDeploy` call carrying value, and a crossing answer is settled on the limit the caller forwarded, whatever limit an inspector built it on. + An answer that halts otherwise burns its whole gas limit. +- **A keyless deployment's call.** + The call is the transaction's own frame and runs no code, and detention holds it as any frame: its gas is held to what the limit leaves it when it first runs (`before_frame_run`), before it charges anything, so its own work — the overhead, then the `CREATE` opcode's regular gas — draws the spendable part, and a charge past the limit is a crossing its frame end stops, whether a rule would then have refused the call or its creation would have run. + The forward to the creation is not the call's work and draws the withheld part first, as a `CREATE` opcode's does. + A call that starts its creation suspends on it as a frame suspends on its child, so the creation's first run adds the call's charges to the transaction's compute, as a caller's work before a `CREATE` is, and the creation runs under what the limit leaves it like any frame; its crossing stops the creation, and the call answers that stop as `ExecutionReverted` on its resume. + On its resume the call is held again, as every frame's resume is; it charges nothing more. + A call carrying value is an answer, held by the rule above. +- **What a halt burns.** + An out-of-gas zeroes a frame's gas before the frame returns, so the wrapper of the opcode whose charge failed notes what the frame had first (`Detention::note_halt`); `KECCAK256` and the four copies into memory are wrapped for that alone, their charge having no bound, and so is `EXP`, whose exponent charge reaches 1,600; a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. + The one charge no wrapper sees is an opcode's static gas, which the step loop makes before the opcode runs: when it fails, what the halting frame had left counts as compute, per halting frame, under the failed charge's price (at most 4,999, on `SELFDESTRUCT`). + Burned gas is counted as compute, so the stop comes earlier, never later; a frame whose leftover takes the compute past the limit does so without a crossing, so the stop is its caller's next charge, and the regular ledger at the stop holds that leftover's part past the limit beside the limit. +- **Refused reads.** + `MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, once the answer is settled and only when gas detention did not turn it into the stop (`Detention::disable_access_on_answer`), until that frame calls `enableVolatileDataAccess()` or returns; a frame below cannot switch back on what a frame above switched off (`DisabledByParent()`), and `isVolatileDataAccessDisabled()` answers for the caller. + The caller is the frame one level above the one the call would start (frame depth = the frame-init depth less one, where the legacy engine used the caller's journal depth, the same frame); a transaction that calls the contract directly has no frame above it, so disabling changes nothing, enabling succeeds and the query answers `false`. + The state is `Detention`'s, and `MegaContext::with_volatile_access_disabled_from` is the test helper that sets it without a call. + The Host then refuses the load and the wrapper reverts the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas, so a refused read pays its static gas and nothing else. + `BLOCKHASH` names `BlockHash` (7), though revm's instruction loads the block number first; `SLOTNUM` names access type 12 (`system::SLOT_NUM_ACCESS_TYPE`), which the contract's enum does not declare. + The error's argument is encoded as a `uint8`, and Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value out of range, and the Rust `IMegaAccessControl` binding decodes 12 to its `__Invalid` placeholder; `decode_volatile_data_access_disabled` is the Rust side's decoder. + The system contracts are not changed for it: their bytecode, and so their code hashes, stay as deployed. ### Contracts of the common execution layer @@ -140,56 +372,165 @@ Every later mechanism plugs into these; a change to one comes back to this layer - **The Host only observes.** `sstore`, `log` and `selfdestruct` stage the facts revm hands them (`StagedRecord`) and record nothing. - Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop the transaction for a write that never happened. + Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop a frame for a write that never happened. - **Commit after the opcode.** - The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed. - Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's. + The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed, and charge the frame the history the record costs — which is the record's own data size, so the charge and the count are the same number. + A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its record, and is charged nothing for it. + The wrappers of `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their own frame for the records the frame they start makes, after revm computed the gas they forward, so the frame's budget carries none of them. + Two things follow from charging after revm's instruction has built the frame's input: the frame carries a copy of the caller's reservoir, taken before the charge, so the wrapper writes the post-charge reservoir back into it — a frame that inherited the earlier one would hand the charge back on return, and a frame answered without running would hand it back twice. + And the frame is already pending as the interpreter's action, which halts on an instruction's error only when no action is pending, so a caller that cannot pay drops the pending frame before it fails; otherwise the frame starts and its records are never paid for. + The opcodes that can read volatile data run in detention's read wrapper, around the wrapper above when they have one (see Gas detention). + Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's Amsterdam one. - **Write records.** One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account. The sender's own account is part of the transaction body: it is never a record, and a frame running as the sender (through an EIP-7702 delegation) counts it as recorded. Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped. - The KV count a node reports is the write-record count. + That record lands on the creator after the creation's own check, so the creator is held to its budget with it before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_frame_return`). + The KV count a node reports is the write-record count; no limit holds it. - **Lanes stay aligned with frames.** - `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the latch, the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran. -- **The latch.** - A transaction-level limit stops the transaction with a revert, never a halt: the frame that crosses it reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)`, the transaction is latched (`AdditionalLimit::latch`), no caller resumes (`before_frame_run`), no frame starts, every result returned above is rewritten to the stop, and the outermost frame settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. - A frame budget reverts its frame alone, without a latch. - A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed), and EIP-7702 authorities whose records would cross it are taken back before the first frame. - A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted. - The layer's state belongs to one transaction: every entry point of `MegaEvm` resets it before it runs the handler. - The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes. + `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran. + A `keylessDeploy` call's frame has the lane any depth-0 call has, and its creation's lane is pushed above it as any child's. +- **The stop.** + A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, the one verdict, which the exemption answers), what it counted goes with its lane, and its caller resumes as after any revert. + There is no latch: a caller that resumes is within every limit, is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and computes past detention's limit only by what halting frames left; a caller that catches the stop and ends lets the transaction succeed. + The frame budget is what keeps a caller's own work within reach of a callee: a child inherits the whole reservoir and history gas draws it first, so gas does not bound what a child appends, and without a budget a callee could take the transaction to its limit and leave the caller that caught its stop nothing to carry on with. + The one stop a frame returns before running another instruction is the one a child left it (`AdditionalLimit::stop_before_run`, `before_frame_run`): a failed creation's nonce record, which lands on its creator unchecked, putting the creator over a limit. + A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. + Nothing is rescued for the sender on a stop, because nothing was taken from it: the stop settles on the gas the frames hold, and detention withholds inside a frame's own tracker. + A stop of the transaction's own frame reverts what the frames did, the first frame's value and write record included, and nothing pre-execution applied: an admitted EIP-7702 authority keeps its nonce, its delegation, its state gas, its record and that record's history, and a deposit keeps its mint and the caller account it created, as through any failed first frame (`tests/satin/state_growth.rs`). + A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed). + Nothing counted before the first frame crosses the data-size limit: validation (`MegaHandler::validate_initial_tx_gas`, before any gas check) refuses a transaction whose body, with a 40-byte record for each entry of its authorization list, exceeds it (`AdditionalLimit::admits_tx_body`, `TX_BODY_OVER_DATA_SIZE_LIMIT`, an `InvalidTransaction::Str`), the system-originated exempt; a deposit refused so is a failed deposit, and a pool refuses it through `validate_transaction_stateless` alike. + `record_tx_body` is a pure count, and `record_applied_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`). + A frame revm answers with a success and the engine then rewrites to the stop — gas detention's crossing — has its journal taken back to where its start began, at any depth, as revm takes back a frame that fails (`take_back_a_stopped_answer`): its caller resumes and keeps its own writes, and no caller's revert follows to take the answer's back. + A record is checked before its history is charged, so a record the limit rejects is not charged and the stop is what its frame reports; at a frame start the caller pays at its opcode, before the records are counted, so there an out-of-gas comes first. + A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted and keeps the body. + The layer's state belongs to one transaction: the handler resets it first thing, in `validate_env`, once it knows whether the transaction is the protocol's own, and every system-call entry point of `MegaEvm` resets it before it runs the handler's system-call path. + The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own data-size budget — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none. + `LimitStop::from_result` (and `MegaTransactionOutcome::limit_stop`) reads a stop off the two together, for an RPC's error; `decode_mega_limit_exceeded` reads the bytes alone, which make no stop by themselves. + `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing. +- **A per-frame gas cap stays inside the frame's tracker.** + Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame ends (`after_frame_run`). + A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. - **Synthetic frame results carry the caller's pools.** A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). - **The admission gate.** - A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses, and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. - alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type: block execution checks it at every entry point — the pre-block changes, a transaction, a commit and the end of the block — because an inspector can be enabled after the block was set up and a caller can run transactions without setting it up. + A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses — as an internal error, since the inspector is the node's choice and no verdict on the block — and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. + alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type: block execution checks it wherever an outcome is produced or chosen — the pre-block changes, a transaction's execution, the end of the block and `commit_transaction_outcome`, the checked commit — because an inspector can be enabled after the block was set up and a caller can run transactions without setting it up. + alloy-evm's `commit_transaction` checks nothing and needs no check: it cannot fail, runs no code, and commits the outcome the last execution produced under the gate, which no inspector enabled since can reach. `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route. - The one rewrite refused is a failed creation turned into a success (`FORBIDDEN_CREATE_REVIVAL`, an `EVMError::Custom`). + In a block a declared observer sees the transactions, user and system alike, and nothing else: the pre-block calls run on the handler's plain system-call path, as alloy-evm's `transact_system_call` runs one, and the end of the block runs no code; the module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase. + No rewrite is refused: a failed creation an inspector turns into a success settles as a frame that kept nothing, like a call it revives (below), and its caller is handed the address the inspector gave. + A creation stopped by a limit is a failed creation like any other, and is settled the same way if revived. The test utilities' inspectors are not declared. +- **A frame that kept nothing settles as one, whatever an inspector made of its result.** + A frame an inspector answered in place of running never started, and a frame that failed had its journal checkpoint reverted before the inspector saw its result. + Whatever the inspector hands the caller for either, the caller gets the success, the output and the regular gas it chose, and nothing else (`settle_kept_nothing` in `evm/inspector.rs`): no state or history gas and no refund, no write record — the lane is discarded as a failure's, and the history its caller paid for the records comes back — and the upfront state gas its caller's opcode was charged for an account the frame did not add comes back — for a call, as recorded before the inspector's hooks ran, so a rewritten target does not change the price it comes back at — as does, for the transaction's own frame, the history of its write record. + So Foundry's `expectRevert` on a call that wrote and reverted bills the transaction as the revert does. + The reverse holds too: a success an inspector rewrites into a failure has its journal taken back to the frame's checkpoint — for a start revm answered without building a frame, to where the start began — as revm takes back a frame that fails, so the state follows the failure its ledgers settle as (`ResultSource` and `revert_journal_to` in `evm/inspector.rs`); a creation keeps its creator's nonce bump, which revm makes before the checkpoint, and the journal's depth is left as it was. + Everything journaled since the checkpoint goes, what the inspector wrote to the journal in the callback that rewrote the result included: the one place the rewrite and a real failure part, since revm takes a failed frame back before `call_end`. +- **An inspector's writes to gas.** + Gas an inspector writes in the `step_end` of a frame's last instruction reaches nobody: the instruction copied the frame's gas into its result; the result's gas, rewritten in `call_end`, is what the caller merges, reservoir included. + An answer is the exception: the frame it stands for never ran, so it carries nothing but the regular gas the inspector chose, and its caller merges back the reservoir it forwarded whatever `Gas` the answer was built on — `Gas::new(limit)`, which Foundry answers every cheatcode on, carries none, and Foundry's default gas limit of 2^30 is above the execution cap. + A charge the frame cannot pay is refused and takes nothing, and the frame runs on; revm's instruction loop sees the inspector through `StepGuard`, which puts back the withheld-part crossing such a refusal records, so gas detention never stops a frame for an inspector's charge. + An inspector that overwrites the interpreter's gas (Foundry's `pauseGasMetering` restores a snapshot before every instruction) overwrites detention's split with it, and the frame runs on the snapshot's split until detention next holds it: at a read, a start or resume, or after an `SSTORE`. - **The interceptor dispatch.** Its order is the scheme guard, the address, the selector, then the method's value policy, each step cheaper than the next: `CALLCODE` and `DELEGATECALL` never reach an interceptor, because they run the callee's code in the caller's context; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes; the selector is peeked without materialising the calldata behind it, and is admitted on its four bytes alone, trailing bytes and all. A selector a contract does not intercept is not intercepted: the call falls through, which is to say the deployed bytecode runs, and what it answers is that contract's own. - The two control contracts have a fallback that reverts with `NotIntercepted()`; `KeylessDeploy` has none, so a selector it does not declare reverts with empty data while a `keylessDeploy` call reaches the method body's `NotIntercepted()`; the Oracle's other selectors are methods it runs, and one it does not declare reverts with empty data. + The two control contracts have a fallback that reverts with `NotIntercepted()`; `KeylessDeploy` has none, so a selector it does not declare reverts with empty data while a `keylessDeploy` call the keyless dispatch did not take — one a contract makes — reaches the method body's `NotIntercepted()`; the Oracle's other selectors are methods it runs, and one it does not declare reverts with empty data. A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names, after the selector matched — so a value-bearing call to an unknown selector still falls through. - An answer is a synthetic frame result and carries the reservoir; an interceptor that lets the frame run may charge it instead, by taking gas off the frame's limit. + An answer is a synthetic frame result and carries the reservoir; an interceptor that lets the frame run charges nothing. - **One hook prices every state charge.** `Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced. A charge is given back two ways, and neither reads a second table: `SSTORE`'s own restore, a caller's upfront charge for a call or creation that did not add the leaf, the transaction-level refund and the settlement of a synthetic frame result re-price the same `(id, site)` pair through the hook; a frame that fails rolls its own charges back by the amounts it recorded while running, without asking for a price at all. Both cancel the charge exactly whatever the price was — the re-priced sites because a bucket's multiplier is read once per transaction, so the two cannot disagree even if the environment's answer would, and the rolled-back amounts because nothing but the hook priced them. A mechanism that adds a state charge adds a `StateGasCharge` at the site the state lands on; it must not price the charge itself. -- **Three ledgers.** +- **Three ledgers, and the bytes beside the third.** `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. - `gas_used` is the receipt's figure; `BlockGasCounters` sums the three per block. + The regular ledger is `total − state − history`, read off the result revm's `Gas` settled into; nothing counts compute beside it, so gas an inspector edits moves it with the receipt. + The figure a block counts is `max(regular, floor)`, history taken out before the floor applies: the fork's `block_regular_gas_used` keeps history in, and subtracting it afterwards can land below the floor. + The three add up to the raw spend, which is why what a history allowance paid for is on none of them: no pool of the transaction's gas paid it. + `history_bytes` counts it all the same — the body, one 40-byte record per kept write, the kept logs but for the transfer logs, and the deposited code — so the bytes at the cost per history byte exceed the history gas by exactly what allowances paid; an exempt transaction reports neither. + It is the history the schedule prices, not the chain's physical growth: an exempt transaction's bytes are not in it, and a body counts its five fixed write records even when fewer fee accounts are written. + For a transaction that pays history it is the data size the transaction kept less its Oracle hints' payloads and its transfer logs: both columns read one count at every site, deployed code included, which the data-size limit makes before the creation commits and only for code revm deposits. + `gas_used` is the receipt's figure; `BlockGasCounters` sums the three ledgers and the history bytes per block. ## Test Organization (`crates/mega-evm/tests/`) - `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). -- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters, the factory and the admission gate. -- `_pending/` — the legacy tests the test inventory keeps, parked until the mechanism they test lands. - It has no `main.rs`, so Cargo does not build it; its `README.md` names the mechanism that owns every file. - The change that ports a pending test deletes it from `_pending/` in the same commit. +- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters, the factory and the admission gate; under `block/witness/`, the witness-replay harness: a block executed on a recorder of every read, then again on a strict database and environments that serve exactly a witness — the record of every read, and the witness a node builds from the states the block committed (the pre-block steps' and the included transactions') and the exports — each replay held to the recording, one case per mechanism that reads and per read that gas or a limit skips. +- `system/` — tests of the system contracts: the interceptor dispatch, what each contract answers, keyless deployment (`system/keyless/`) and the system-address transaction. +- `fuzz/` — randomized tests: properties the engine must hold on any input, and the neutral differential against op-revm and revm's mainnet EVM (see Randomized tests below). +- `shared/` — no target: `snapshot.rs` holds `assert_sorted_json_snapshot!`, which every target includes with `#[path = "../shared/snapshot.rs"] mod snapshot;`. + It has no `main.rs`, so Cargo builds nothing there; the snapshot files live in `snapshots/` beside the file that asserts. - Unit tests live next to the code in `#[cfg(test)] mod tests`. +### Randomized tests (`crates/mega-evm/tests/fuzz/`) + +The hand-written tests fix an input and an expectation; the randomized ones draw the input and state what must hold of any outcome. +They run on `proptest`, through the target's own runner (`harness.rs`), and every property is one `#[test]`. + +```bash +cargo test -p mega-evm --test fuzz # the bounded mode, as CI runs it +cargo test --release -p mega-evm --test fuzz # the same in release, where the debug assertions are gone +MEGA_FUZZ_LONG=1 cargo test -p mega-evm --test fuzz -- --nocapture # the long mode: 50x the cases, a seed from the clock, printed +MEGA_FUZZ_SEED=7 MEGA_FUZZ_CASES=5000 cargo test -p mega-evm --test fuzz -- --nocapture a_stop_keeps # one property, a chosen run +for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --test fuzz || break; done # other seeds, before changing a generator +``` + +- **Two modes.** + The bounded mode is deterministic: seed 0, a fixed case count per property (128 to 768), under ten seconds in debug. + It is part of `cargo test --workspace`, which `build-and-test.yml` runs in debug (`test`), where every debug assertion runs, and in release (`test-release`), where none does. + The long mode (`MEGA_FUZZ_LONG=1`) multiplies each property's count by fifty and draws a seed from the clock unless `MEGA_FUZZ_SEED` names one; `fuzz.yml` runs it on `workflow_dispatch`, in debug and in release, since a schedule fires only on the default branch. + `MEGA_FUZZ_SEED` names the seed in either mode. + `MEGA_FUZZ_CASES` names the case count in either mode, and it is the count: every property runs exactly that many cases, and the long mode's multiplier does not apply to it. + Either variable set to the empty string counts as unset, which is how `fuzz.yml` passes an input left empty. +- **The properties hold for any seed.** + Seed 0 is what CI runs, not what the properties are true of: a change to a generator redraws every case, so a property that held on one seed by luck fails on the pull request that touches a weight. + Before changing a generator or a property, run the bounded mode on a few dozen seeds and the long mode on a few; a failure there is a bug to fix or a property to correct, never a seed to avoid. +- **A failure is reproducible.** + The runner panics with the property's name, the reason, the seed and case count that reproduce the run, and the case proptest shrank to within its shrink limits (two minutes and 4,096 steps, so not always the minimal one), rendered as the generator types (`Case`, `BlockCase`), from which a regression test is written by hand into `regressions.rs`. +- **The generators** (`gen/`) build a `Case`: a `World` (four fixed accounts, a beneficiary that may be one of them, a delegation, SALT capacities with multipliers above one and a failing bucket, the Oracle's answers, runtime limits in place of the spec's, the block), a `Tx` of one of six shapes (call, creation, EIP-7702, deposit, system-address, keyless) at five gas tiers, and the `Program`s of the three contracts, lists of self-contained ops biased towards what the engine meters. + A keyless deployment carries its own world: the signer's funds, nonce and code, what the deploy address holds, how the carried transaction is encoded and what it is signed for, so that each of its rules is reached. + The keyless property also pads one init code in eight with zero bytes, which never run, to the initcode size limit, one byte past it or twice it; the other properties draw init code at its own size, since a mebibyte of calldata in their cases would buy nothing they check. + The weights keep what refuses a transaction before it runs rare — about one case in five — because most properties have nothing to check of a refusal. + `Case::execute` runs it on a fresh EVM; `blocks.rs` runs envelopes through `MegaBlockExecutor`. + `Flavor::Neutral` replaces what only `MegaETH` has by its plain counterpart, for the differential, and `Case::without_destruction_in_creation` takes every self-destruction out of init code for the one comparison that settles it otherwise, Ethereum's on Amsterdam. +- **What the properties state** (`properties.rs`, `keyless.rs`, `blocks.rs`, `differential.rs`): the same outcome twice, under a recording inspector, and on an EVM that already ran another transaction, one that ended in an error included; the gas ledgers, the reservoir exactly; `KV × 40 ≤ data size` after every instruction, and every transaction keeps its body and the hints it forwarded; what a stop keeps; a keyless deployment's rules in the spec's order, its answer and its signer's nonce; a block's counters as the sum of what its transactions report, and its budgets; the neutral differential. + A panic fails whichever property draws the case. + Several print a tally of what they reached (`--nocapture`): how the previous transaction ended, each keyless rule, the cases rewritten for Amsterdam. +- **To add a property**, write a `#[test]` that calls `harness::check(name, bounded_cases, || case(Flavor::Satin), |case| { ... })` and returns `Err` through `prop_eq!` / `prop_check!` where the outcome breaks the property; keep the bounded case count such that the whole target stays under a minute in debug. + A property that does not hold by design is stated as what does hold, with the reason in its doc comment, never weakened silently. + An expected value is computed from the case or from what the transactions themselves report, never read back from the thing under test: an assertion that restates a definition, or compares a counter with itself, cannot fail. + To add an op or a transaction shape, extend the enum and its strategy in `gen/`, its assembly, and, if op-revm cannot express it, its `neutralized` counterpart. +- **The byte prices** are a process-wide constant, so a case cannot run at two prices in one test. + `prices.rs` checks the schedule builder's monotonicity in-process, and under `satin-price-override` records what every case spent (`MEGA_FUZZ_PRICE_RECORD`) for `scripts/fuzz_price_monotonic.py` to compare two runs at two prices, which `fuzz.yml` does. + The properties themselves hold at any byte price and run in the byte-price grid; the regression tests that fall short of a charge pin a minimal case at the spec's prices and return early at others. + +## Test Gates + +`REVIEW.md` lists the test gates a pull request meets ("Test gates"); three of them are this repository's own execution gates — the op-revm baseline, the execution-spec gate and the witness replay — and the byte-price grid holds the suite at other byte prices. + +- **The op-revm baseline** (`tests/satin/equivalence.rs`): an ordinary transaction through `MegaEvm` against op-revm on the same configuration, which Satin differs from by its history ledger alone. +- **The execution-spec gate** (`crates/mega-state-test`, `.github/workflows/exec-spec-satin.yml`): Ethereum's state-test fixtures through `MegaEvm`, on the fixture releases the fork's own runner (`.github/workflows/exec-spec.yml`) uses. + - Equivalence mode is the gate: Satin's machinery — handler, frame lifecycle, Host, instruction table — priced as the fixture's fork prices it, through the neutral configuration (`MegaContext::with_neutral_cfg`, `test_utils::{neutral_cfg, neutralize_evm}`), which exists only behind `test-utils`, and held to no runtime limit (`EvmTxRuntimeLimits::no_limits()`, installed by the runner itself). + Every failure must be explained by a deviation in `crates/mega-state-test/src/deviations.rs`, with its rule, its reason and the exact entries it explains, each with the hashes Satin produces, and every listed entry must fail exactly as listed; the executed and skipped counts are pinned in the workflow and equal the fork runner's. + - Satin mode is a report: the same fixtures under Satin's own configuration, counted by outcome in the step summary; it never fails the job. + - The blockchain tests are a gate too (`state-test btest`, `crates/mega-state-test/src/blockchain/`): the main release's Osaka `blockchain_tests`, imported block by block through `MegaBlockExecutor` on `MegaEvm` in equivalence mode's configuration, held to no limit (`ProtocolLimits::no_limits()`, installed by the runner through the executor's test-and-tool override), as the state-test runner holds a transaction. + Every accepted block's gas used, logs bloom, receipts root and state root are held to its header, every block expecting a `TransactionException` must be refused for an exception it names, leaving the chain at the previous block, and the chain must end at the fixture's last block and post-state. + The runner seeds the seven predeploys, in the shape Rex6 left them, where a fixture's pre-state lacks them, and sets the activation signal from the schedule; the state root takes out those accounts and OP's three fee vaults a Satin block adds (`SATIN_ACCOUNTS`) only when the pre-state does not hold one and it holds exactly what was put there. + A test is skipped only for a class decided from its content: withdrawals, blob transactions, EIP-7685 requests, a header or body `BlockException` a node checks before execution, a transaction an OP block cannot encode, and the state-test gate's own storage-collision files; the executed tests and each class are pinned in the workflow. + A block that differs passes only when a deviation the registry already has lists that test and block with exactly the outcome Satin produces (gas used, logs bloom, receipts root, state root); the chain is imported on from Satin's state, every later block held to its header or its own listed outcome, and the summary counts blocks checked against Ethereum apart from blocks matched to a deviation. +- **The witness replay** (`tests/block/witness/`, `crates/mega-state-test`'s `witness::check_replay`): a block, or a fixture's transaction, executed on a recorder of every read and replayed twice on a strict database and environments that serve exactly a witness and refuse everything else — once on the record of every database read, once on the witness a node builds from the states the block committed — the pre-block steps' and the included transactions' returned states — and the engine's exports (`WitnessRecord::from_channels`); every replay runs only the transactions the recorded block included and must agree with the recording on everything produced, the replay must read nothing its witness does not hold, and the executor's exported buckets and block hashes must be the side-channel reads the block made, a bucket only where the SALT environment answered it with a valid capacity. + The channel replay is the check a validator's witness must pass; the database-level replay shows the block has no hidden input. + A fixture entry the engine rejects has no returned state to build the channel witness from, and replays on the record alone. + The block tests cover each mechanism that reads, in the `test` job; `exec-spec-satin.yml` replays every Osaka and Amsterdam entry of the fixture releases in both modes and fails on any entry that does not replay, counting the entries replayed on both witnesses apart from the rejected ones. + The fixture test is always ignored by default: it runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set to the fixtures, and setting the variable alone runs nothing. +- **The byte-price grid** (`scripts/price_grid.sh`, `.github/workflows/price-grid.yml`): the `mega-evm` suite with the `satin-price-override` feature at other costs per state and history byte, five points on a pull request and the whole grid nightly. + The prices are provisional, so a test holds at any of them — a byte price of nothing, or one gas per byte up to the grid's dearest point: it sizes its gas from the schedule at the prices in effect, and a case whose scenario is state or history gas returns early where that byte costs nothing (`state_is_free`, `history_is_free`). + Below one gas per byte the schedule's entries round to nothing one at a time, and no test is held there. + Each guard leaves a note (`test_utils::note_price_guard`), and the grid reports per point how many tests were guarded beside how many passed. + A test that only skipped a snapshot comparison leaves a note of its own (`test_utils::note_snapshot_skipped`), which the grid counts apart, as snapshot skips: it ran every assertion it makes. + ## Version Control `satin` is the integration branch of the new engine; pull requests for Satin target `satin`. @@ -230,6 +571,9 @@ When a PR creation is requested, the agent should: When generating the PR title and description, consider the overall changes in this branch across commits. In the PR description, make sure a `Summary` section is put on the top. The PR will be merged with `Squash and Merge` operation, whose commit description should include the summary. +7. Label the PR as `.github/pull_request_template.md` lists. + Satin is the unstable spec, so a PR that changes Satin's behavior is `spec:unstable`. + `spec:new` is only for a PR that introduces a new `MegaSpecId` variant. ### Implementing features or bug fixes @@ -240,17 +584,41 @@ When the agent is requested to implement a new feature or bug fix, it should con ## Caveats for Agents -- **Satin is the only active spec; the legacy engine is frozen.** - Do not add legacy specs, alias rungs or spec gates to this crate, and do not port a legacy mechanism the legacy test inventory retired. +- **Reviewing the Satin pull request: use `.claude/skills/satin-review/`.** + It is temporary and removed before the Satin pull request merges. +- **Satin is the unstable spec; the legacy engine is frozen.** + Do not add legacy specs or alias rungs to this crate, and do not port a legacy mechanism the legacy test inventory retired. + Spec gates come with the next spec (see Spec System), not before. Behavior of the legacy specs is changed only on the legacy line, never here. -- **Build from the skeleton, one mechanism at a time.** - Each module is filled by the mechanisms named in the module table; do not implement another mechanism to make yours work. - If a change needs an interface that belongs to another mechanism, stub the smallest interface and name the mechanism that owns it. +- **Keep each change in the module that owns it.** + The module table says where each mechanism lives; a change that needs another module's interface extends that module rather than re-implementing it in its own. +- **Export from the crate root by name.** + `lib.rs` lists every item of the public surface explicitly, and the few `pub(crate)` items the modules share through the root; there are no glob exports and no short aliases. + A new `pub` item is added to that list or made `pub(crate)`: the `unreachable_pub` lint flags one that is neither. - **Always test logic changes.** Any logic change or modification to mega-evm should be equipped with tests if there is no specific reason of not adding tests. The agent should always consider accompanying tests or suggest to add additional tests. - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. +- **Hold a test at any byte price.** + A gas limit is regular room on top of what the scenario adds at the prices in effect (`satin_gas_params()`, `history_gas`), never a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for. + A charge a scenario must not be able to pay is derived the same way — a gas limit one short of it — not a number that is short of it only while a byte is dear. + A test that pins the spec's own numbers returns early at other prices (`runs_at_measurement_prices`); run `scripts/price_grid.sh --pr` before committing a test change. +- **Pin only outputs with no computable expectation.** + A snapshot or a golden is the owner of an output no test can compute an expectation for, and of nothing else. + Those outputs are the tracers' formats (`tests/tracers/`, the call-with-logs and prestate-diff views per scenario with the gas figures redacted, and the opcode view of two), recorded traces, such as the keyless differential's record pinned by one digest per case (`tests/system/keyless/differential.rs`), and the receipt bytes a node hashes, hand-pinned in `tests/block/receipt_goldens.rs`. + A figure the schedule and the named constants determine — gas on any ledger, a usage count, a limit, a balance, a slot, a log — is asserted with `assert_eq!` against its derivation, never pinned. + A snapshot is never a net over a behaviour test: a test that runs a transaction asserts what it owns and snapshots nothing of its outcome. + A digest stands for a record too large to keep in the tree, so a changed digest is reviewed through the record's dump: `MEGA_KEYLESS_RECORD=` writes the keyless record, written at the base and at the head and diffed; it is never accepted on the digest alone. + A digest also moves wholesale when the rendering of a type it covers changes, such as a dependency's `Debug` format, and the dump is how that change is read too. + Snapshot changes are reviewed one by one like code: with `cargo insta review`, or by diffing each `.snap.new` against its `.snap` and accepting it on its own (`cargo insta accept --snapshot `, or, without cargo-insta, moving it over the `.snap` without its `assertion_line:` header line). + They are never blanket-accepted (`cargo insta accept` of every pending snapshot, `--accept`, `--force-update-snapshots`, `INSTA_UPDATE=always`). + Snapshot comparisons run at the spec's byte prices only: at other prices the macro skips the comparison and leaves a note of the skip (`test_utils::note_snapshot_skipped`), not a price guard. + The receipt goldens are the one pin outside insta, on purpose: the receipts root, the blooms and the encoded receipts are hand-written constants, the stronger pin for consensus bytes, which no snapshot tool can then rewrite. + The generated documents (`crates/mega-state-test/DEVIATIONS.md`, `crates/mega-evm/tests/satin/pricing-table.md`, `bin/mega-evme/tests/satin-differences.md`) stay rendered by their tests and checked against the file, not snapshotted. +- **Keep the execution-spec gate honest.** + A change that makes Satin's machinery differ from Ethereum's fixtures on purpose registers a deviation (its rule, its reason, the entries it fails with the hashes Satin produces for them) and regenerates `crates/mega-state-test/DEVIATIONS.md`; a failure that is a bug is fixed, never registered. + A price or a limit `MegaETH` sets is not a deviation: equivalence mode takes it out, and a new pricing or limit dimension extends the neutral configuration, or the limits the runner installs, rather than the registry. - **Add benchmarks for performance-sensitive changes.** Changes on the EVM execution hot path must be accompanied by benchmarks. This includes new or modified opcode behavior, gas mechanics, system contract interception, resource limit tracking, and block executor pipeline changes. @@ -264,17 +632,24 @@ When the agent is requested to implement a new feature or bug fix, it should con If editing nearby tests in the same module, align names to the same `test_` style when reasonable. - **System contracts carry over as they are.** Satin reuses the Solidity sources and bindings in `crates/system-contracts`; changing a contract needs a decision of its own, not a side effect of an engine change. -- **Rules for system contract interceptors (once the interceptors land).** +- **Rules for system contract interceptors.** For read-only or control methods, reject calls with non-zero `transfer_value` in the interceptor; if a method intentionally accepts value, document the reason in spec and code comments and add dedicated tests. - Do not intercept unknown selectors: they fall through to on-chain bytecode and revert with a stable custom error such as `NotIntercepted()`. + Do not intercept unknown selectors: they fall through to the contract's own bytecode, where the two control contracts revert with `NotIntercepted()` and `KeylessDeploy` and the Oracle revert with empty data on a selector they do not declare. Only `CALL` and `STATICCALL` reach interceptor dispatch; `CALLCODE` and `DELEGATECALL` are rejected by the call-scheme guard before any interceptor is consulted. Interceptor tests cover the intercepted path, non-zero value, unknown selector fallback, and CALL vs DELEGATECALL/CALLCODE boundaries. -- **Validate per-fork parameters at load time.** - A hardfork parameters type overrides `HardforkParams::validate()` with field-level invariant checks, so a bad chain config fails when it is loaded rather than at the fork's first block. - The fork-requires-params rule is registered in `MegaHardforks::validate_schedule` too — one `require_params::

()` per params type — so a schedule that activates the fork without its params is rejected at load time. -- **Pre-block helpers must return state, not commit directly.** - Any helper participating in pre-block execution (system contract deploys, pre-block system calls, etc.) returns `Option` and never calls `db.commit(...)` directly, so the witness generator sees the complete read and write set. - `block/eips.rs` holds the ones that exist — the EIP-2935 and EIP-4788 calls and the post-block balance increments — and the block executor is what commits them. +- **Validate the schedule at load time.** + `MegaHardforks::validate_schedule` refuses a schedule a chain cannot run when the chain configuration is loaded rather than at the fork's first block. + It refuses a schedule in which a fork Satin runs on and the schedule activates by timestamp (Ethereum Shanghai to Osaka, Optimism Regolith to Karst) is not active at Satin's activation (`ScheduleError::InactiveBaseFork`); the engine's own schedules activate those forks from the first block, so they are active by `satinTime`, and pass. + That Jovian, Karst and Osaka do not activate before Satin is the node's to check, not the engine's. +- **Keep the workspace on its declared minimum toolchain (1.94).** + CI's msrv job checks the workspace on 1.94.0, every feature on, with the lock as it is. + A dependency whose newer releases declare a newer compiler (alloy 2.2 and later declare 1.94.1) stays on the newest release the declared version builds: `.cargo/config.toml` sets the resolver's `incompatible-rust-versions = "fallback"`, so a `cargo update` run in the repository picks it. +- **Pre-block helpers return their state and never commit.** + A helper that takes part in `apply_pre_execution_changes` (the activation block's check of the predeploys, the pre-block system calls, the registry's due-change read, the L1 block info read) never calls `db.commit(...)`: it returns the prepared state — an `EvmState`, or a `ResultAndState` for a system call — and the executor commits it on its own, in order, so the sequence of committed states is the witness a stateless client needs. + A read that changes nothing (a predeploy holding Satin's code, the L1 block info) returns `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. + Returning nothing there is a bug — the account disappears from the stateless witness read set. + A step that writes includes every account and storage slot it touched; a predeploy holding other code is an error, never an overwrite. + `system/predeploys.rs` holds the predeploy check, `block/eips.rs` the EIP-2935 and EIP-4788 calls, `system/sequencer_registry.rs` the registry's due-change read and its `applyPendingChanges()` call, `block/l1_block_info.rs` the L1 block info read, and the block executor is what commits them. - **Respect `no_std` in `mega-evm` crate.** Do not use `std::` directly. Follow the existing pattern: `#[cfg(not(feature = "std"))] use alloc as std;` then `use std::{vec::Vec, ...};`. @@ -295,7 +670,8 @@ When the agent is requested to implement a new feature or bug fix, it should con Run `cargo fmt --all --check` before completion. - **Keep documentation up to date.** When making changes, always check whether related documentation needs updating. - The primary documentation is in `docs/`; it still describes the legacy engine until the Satin specification pages are written. + The primary documentation is in `docs/`. + `docs/spec/upgrades/satin.md` specifies Satin and is updated with any change to its behavior; the `docs/spec/evm/` and `docs/spec/system-contracts/` pages still describe the legacy engine. The spec documentation is under `docs/spec/`, and the mega-evme documentation is under `docs/mega-evme/`. Also update this `AGENTS.md` when relevant (e.g., the module table, the unstable-spec marker). - **One sentence, one line.** diff --git a/ARCH.md b/ARCH.md index 2d289518d..3f5d87717 100644 --- a/ARCH.md +++ b/ARCH.md @@ -18,7 +18,8 @@ This document provides detailed technical specifications and implementation deta The implementation exposes multiple EVM versions (`MegaSpecId`). String names and hardfork-to-spec mapping live in `crates/mega-evm/src/evm/spec.rs` and `crates/mega-evm/src/block/hardfork.rs`. -Available specs: `EQUIVALENCE`, `MINI_REX`, `MINI_REX_1`, `MINI_REX_2`, `REX`, `REX1`, `REX2`, `REX3`, `REX4`, `REX5`, `REX6`, `REX7` (`MINI_REX_1` and `MINI_REX_2` are alias rungs executing `EQUIVALENCE` and `MINI_REX` behavior respectively). +The legacy engine's specs are `EQUIVALENCE`, `MINI_REX`, `MINI_REX_1`, `MINI_REX_2`, `REX`, `REX1`, `REX2`, `REX3`, `REX4`, `REX5`, `REX6` (`MINI_REX_1` and `MINI_REX_2` are alias rungs executing `EQUIVALENCE` and `MINI_REX` behavior respectively), and all of them are frozen. +`SATIN` follows `REX6` and is the unstable spec; it is the only spec this crate executes. This page details only the first few; the authoritative per-spec behavior is the specification under `docs/spec/`, whose upgrade pages cover every spec. diff --git a/Cargo.lock b/Cargo.lock index d267e10ba..b50a95875 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,17 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addchain" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b2e69442aa5628ea6951fa33e24efe8313f4321a91bd729fc2f75bdfc858570" +dependencies = [ + "num-bigint 0.3.3", + "num-integer", + "num-traits", +] + [[package]] name = "ahash" version = "0.8.12" @@ -42,16 +53,42 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90d103d3e440ad6f703dd71a5b58a6abd24834563bde8a5fabe706e00242f810" +dependencies = [ + "alloy-eips 1.8.3", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 1.8.3", + "alloy-trie", + "alloy-tx-macros 1.1.2", + "auto_impl", + "c-kzg", + "derive_more", + "either", + "k256", + "once_cell", + "rand 0.8.5", + "secp256k1 0.30.0", + "serde", + "serde_json", + "serde_with", + "thiserror", +] + +[[package]] +name = "alloy-consensus" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b836b372d3b742b7c083d2617d6e68563cd5dadbd8752c461a935a756551e69" +checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" dependencies = [ - "alloy-eips", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.1.1", "alloy-trie", - "alloy-tx-macros", + "alloy-tx-macros 2.1.1", "auto_impl", "borsh", "c-kzg", @@ -69,15 +106,29 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48ead76c8c84ab3a50c31c56bc2c748c2d64357ad2131c32f9b10ab790a25e1a" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 1.8.3", + "serde", +] + +[[package]] +name = "alloy-consensus-any" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1befb37485ea71e8599e32ffd76c98af7c3720a34741d30abd87f41c3148407" +checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.1.1", "serde", ] @@ -120,6 +171,20 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-eip7928" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b827a6d7784fe3eb3489d40699407a4cdcce74271421a01bdffe60cf573bb16" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "borsh", + "once_cell", + "serde", + "thiserror", +] + [[package]] name = "alloy-eip7928" version = "0.4.11" @@ -136,17 +201,40 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "2.4.2" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6ef28c9fdad22d4eec52d894f5f2673a0895f1e5ef196734568e68c0f6caca8" +dependencies = [ + "alloy-eip2124", + "alloy-eip2930", + "alloy-eip7702", + "alloy-eip7928 0.3.7", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 1.8.3", + "auto_impl", + "borsh", + "c-kzg", + "derive_more", + "either", + "serde", + "serde_with", + "sha2 0.10.9", +] + +[[package]] +name = "alloy-eips" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3e76d47e8de277cb55e7e77fa38adde835162fc01cddbe1b258b5e0a86035b" +checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", - "alloy-eip7928", + "alloy-eip7928 0.4.11", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.1.1", "auto_impl", "borsh", "c-kzg", @@ -156,7 +244,26 @@ dependencies = [ "ethereum_ssz_derive", "serde", "serde_with", - "sha2", + "sha2 0.10.9", +] + +[[package]] +name = "alloy-evm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28de0dd1bbb0634ef7c3715e8e60176b77b82f8b6b15b2e35fe64cf6640f6550" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-hardforks 0.2.13", + "alloy-primitives", + "alloy-sol-types", + "auto_impl", + "derive_more", + "op-alloy-consensus 0.18.14", + "op-revm 8.1.0", + "revm 27.1.0", + "thiserror", ] [[package]] @@ -165,35 +272,48 @@ version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6e494529570a4d25eb4d1a7456d8f969c3202aceaf703e4006cec5f730aee96" dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-hardforks", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-hardforks 0.4.8", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-rpc-types-eth", + "alloy-rpc-types-eth 2.1.1", "alloy-sol-types", "auto_impl", "derive_more", - "revm", + "revm 40.0.3", "thiserror", "tracing", ] [[package]] name = "alloy-genesis" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0680a2f7d4bbc6f48c0cb43368fa544918a1fa291e772bdb47c834ade338f363" +checksum = "027ba57264c5d05e4ff52e6090b3592e7526f5d5f5a844add6bbdd17c071c911" dependencies = [ - "alloy-eips", + "alloy-eips 2.1.1", "alloy-primitives", - "alloy-serde", + "alloy-serde 2.1.1", "alloy-trie", "borsh", "serde", "serde_with", ] +[[package]] +name = "alloy-hardforks" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165210652f71dfc094b051602bafd691f506c54050a174b1cba18fb5ef706a3" +dependencies = [ + "alloy-chains", + "alloy-eip2124", + "alloy-primitives", + "auto_impl", + "dyn-clone", +] + [[package]] name = "alloy-hardforks" version = "0.4.8" @@ -221,9 +341,24 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "2.4.2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "003f46c54f22854a32b9cc7972660a476968008ad505427eabab49225309ec40" +dependencies = [ + "alloy-primitives", + "alloy-sol-types", + "http", + "serde", + "serde_json", + "thiserror", + "tracing", +] + +[[package]] +name = "alloy-json-rpc" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a523ca087dda941e53f6ecde5bf5df78b9dbe760f3f77488e13dbf355de4a84" +checksum = "c4691c60de5d628533752cd07e102d17c47874c06c04c91af33960fd94c484f4" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -236,20 +371,46 @@ dependencies = [ [[package]] name = "alloy-network" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "612296e6b723470bb1101420a73c63dfd535aa9bf738ce09951aedbd4ab7292e" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-consensus-any 1.1.0", + "alloy-eips 1.8.3", + "alloy-json-rpc 1.1.2", + "alloy-network-primitives 1.1.0", + "alloy-primitives", + "alloy-rpc-types-any 1.1.0", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", + "alloy-signer 1.1.2", + "alloy-sol-types", + "async-trait", + "auto_impl", + "derive_more", + "futures-utils-wasm", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "alloy-network" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f263c8d752b15e19b7c2d3cbad00338ec2d7cc923a46cd1ff98aea2fa333166b" +checksum = "9d912bb639bf4ac31e83095afe9e907c8b9774ce0c405966228368309fcfc45f" dependencies = [ - "alloy-consensus", - "alloy-consensus-any", - "alloy-eips", - "alloy-json-rpc", - "alloy-network-primitives", + "alloy-consensus 2.1.1", + "alloy-consensus-any 2.1.1", + "alloy-eips 2.1.1", + "alloy-json-rpc 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", - "alloy-rpc-types-any", - "alloy-rpc-types-eth", - "alloy-serde", - "alloy-signer", + "alloy-rpc-types-any 2.1.1", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", + "alloy-signer 2.1.1", "alloy-sol-types", "async-trait", "auto_impl", @@ -262,41 +423,82 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0e7918396eecd69d9c907046ec8a93fb09b89e2f325d5e7ea9c4e3929aa0dd2" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-primitives", + "alloy-serde 1.8.3", + "serde", +] + +[[package]] +name = "alloy-network-primitives" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8795eecf50374a0dd942caff57922c59333c9991ead9eccbbc1709f55d73c7c2" +checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", - "alloy-serde", + "alloy-serde 2.1.1", "serde", ] +[[package]] +name = "alloy-op-evm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0afe768962308a08b42fddef8a4296324f140b5a8dd0d4360038229885ce9434" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-evm 0.15.0", + "alloy-op-hardforks 0.2.13", + "alloy-primitives", + "auto_impl", + "op-alloy-consensus 0.18.14", + "op-revm 8.1.0", + "revm 27.1.0", +] + [[package]] name = "alloy-op-evm" version = "0.32.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-evm", - "alloy-op-hardforks", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-evm 0.36.0", + "alloy-op-hardforks 0.5.0", "alloy-primitives", "auto_impl", "op-alloy", - "op-revm", - "revm", + "op-revm 20.0.0", + "revm 40.0.3", "thiserror", ] +[[package]] +name = "alloy-op-hardforks" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3417f4187eaf7f7fb0d7556f0197bca26f0b23c4bb3aca0c9d566dc1c5d727a2" +dependencies = [ + "alloy-chains", + "alloy-hardforks 0.2.13", + "auto_impl", +] + [[package]] name = "alloy-op-hardforks" version = "0.5.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ "alloy-chains", - "alloy-hardforks", + "alloy-hardforks 0.4.8", "alloy-primitives", "auto_impl", ] @@ -312,7 +514,7 @@ dependencies = [ "cfg-if", "const-hex", "derive_more", - "foldhash", + "foldhash 0.2.0", "hashbrown 0.17.1", "indexmap 2.10.0", "itoa", @@ -331,25 +533,64 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55c1313a527a2e464d067c031f3c2ec073754ef615cc0eabca702fd0fe35729c" +dependencies = [ + "alloy-chains", + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-json-rpc 1.1.2", + "alloy-network 1.1.0", + "alloy-network-primitives 1.1.0", + "alloy-primitives", + "alloy-rpc-client 1.1.2", + "alloy-rpc-types-eth 1.1.0", + "alloy-signer 1.1.2", + "alloy-sol-types", + "alloy-transport 1.1.2", + "alloy-transport-http 1.1.2", + "async-stream", + "async-trait", + "auto_impl", + "dashmap", + "either", + "futures", + "futures-utils-wasm", + "lru 0.13.0", + "parking_lot", + "pin-project", + "reqwest 0.12.24", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-provider" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef487e44dfae9c87cb732989d3f43682f65aefb11a0f56045b26be357f671fcf" +checksum = "0e7d526d184d392a8fbcf4293e457789b307bb70646e4f8b902989a246529450" dependencies = [ "alloy-chains", - "alloy-consensus", - "alloy-eips", - "alloy-json-rpc", - "alloy-network", - "alloy-network-primitives", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-json-rpc 2.1.1", + "alloy-network 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", - "alloy-rpc-client", + "alloy-rpc-client 2.1.1", "alloy-rpc-types-debug", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", - "alloy-signer", + "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-trace 2.1.1", + "alloy-signer 2.1.1", "alloy-sol-types", - "alloy-transport", - "alloy-transport-http", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", "async-stream", "async-trait", "auto_impl", @@ -357,11 +598,10 @@ dependencies = [ "either", "futures", "futures-utils-wasm", - "http", - "lru", + "lru 0.16.4", "parking_lot", "pin-project", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "thiserror", @@ -395,17 +635,40 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "2.4.2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31c89883fe6b7381744cbe80fef638ac488ead4f1956a4278956a1362c71cd2e" +dependencies = [ + "alloy-json-rpc 1.1.2", + "alloy-primitives", + "alloy-transport 1.1.2", + "alloy-transport-http 1.1.2", + "futures", + "pin-project", + "reqwest 0.12.24", + "serde", + "serde_json", + "tokio", + "tokio-stream", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-rpc-client" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98267c2d47f9c185b575bac3f772a8ca66bcbd712693535e50980c12eab80a42" +checksum = "755447dc13a04c6fa6db8dedb5d32ab5edfa4dd7aa34487ff192a3d873e0e8cf" dependencies = [ - "alloy-json-rpc", + "alloy-json-rpc 2.1.1", "alloy-primitives", - "alloy-transport", - "alloy-transport-http", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", "futures", "pin-project", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "tokio", @@ -418,24 +681,35 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdbf6d1766ca41e90ac21c4bc5cbc5e9e965978a25873c3f90b3992d905db4cb" +dependencies = [ + "alloy-consensus-any 1.1.0", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", +] + +[[package]] +name = "alloy-rpc-types-any" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1176430031ba27abfb51b95516cf71e8ce3ff4172c72f3136627f0f89813a739" +checksum = "911a513723ef0b90c3b072f65eebf54d6ebc8b651d06734e252d024bd89b88ac" dependencies = [ - "alloy-consensus-any", - "alloy-network-primitives", + "alloy-consensus-any 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "serde", "serde_json", ] [[package]] name = "alloy-rpc-types-debug" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a97960aa11b9984a18580b8dfbfc3eacfce1befa0d588b03ccc0bc5563d01f8" +checksum = "b9e9c1f9ac81c56b2d96901201db7eb95c4e9fc3c21237a4690f8c652aa62089" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -446,15 +720,15 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "2.4.2" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a43d7b6b86be4885c7a76f1dfcde9651af2d419ff571e8ee7257de47101203b" +checksum = "5b1f682c4881aa7000ac7cc86d7aeeb3b09836a77a90b329820140233651aeea" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.1.1", "derive_more", "ethereum_ssz", "ethereum_ssz_derive", @@ -465,17 +739,38 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.4.2" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a15e4831b71eea9d20126a411c1c09facf1d01d5cac84fd51d532d3c429cfc26" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-consensus-any 1.1.0", + "alloy-eips 1.8.3", + "alloy-network-primitives 1.1.0", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 1.8.3", + "alloy-sol-types", + "itertools 0.14.0", + "serde", + "serde_json", + "serde_with", + "thiserror", +] + +[[package]] +name = "alloy-rpc-types-eth" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "756eb5803e70985be4066b636194ccb5f6629e5d141817c1f0c50cea8350bf5c" +checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" dependencies = [ - "alloy-consensus", - "alloy-consensus-any", - "alloy-eips", - "alloy-network-primitives", + "alloy-consensus 2.1.1", + "alloy-consensus-any 2.1.1", + "alloy-eips 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-serde", + "alloy-serde 2.1.1", "alloy-sol-types", "itertools 0.14.0", "serde", @@ -486,13 +781,27 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "2.4.2" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a854af3fe8fce1cfe319fcf84ee8ba8cda352b14d3dd4221405b5fc6cce9e1" +dependencies = [ + "alloy-primitives", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "alloy-rpc-types-trace" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1933d60c2f51b8906103484ea2ca2218357264dbf16f948f7c2dd4ac5818e1d8" +checksum = "796729a4e1783904c6040f11a503c4d55ddb16f69dc199ad15e50c4ad039f371" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "serde", "serde_json", "thiserror", @@ -500,9 +809,20 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.4.2" +version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc142e40df0c3eb5983b1637a68ab33471d8d22b8f402c9ed8260411a4e89d86" +checksum = "11ece63b89294b8614ab3f483560c08d016930f842bf36da56bf0b764a15c11e" +dependencies = [ + "alloy-primitives", + "serde", + "serde_json", +] + +[[package]] +name = "alloy-serde" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1e97b3e0b9f816b25083045dcfa69431bd059a078e828e4d82d296d1949b96c" dependencies = [ "alloy-primitives", "serde", @@ -511,9 +831,9 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "2.4.2" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c84f88f8a29d2607f98993687ed55a5943ba06819bc2126bb078dca54be943" +checksum = "ecc39ad2c0a3d2da8891f4081565780703a593f090f768f884049aa3aa929cbc" dependencies = [ "alloy-primitives", "async-trait", @@ -525,10 +845,25 @@ dependencies = [ ] [[package]] -name = "alloy-sol-macro" -version = "1.6.0" +name = "alloy-signer" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" +checksum = "6913d06ccc0d9c6ab67e2f82e2fbe292706da1f91442f30cded2d04b56bf0d58" +dependencies = [ + "alloy-primitives", + "async-trait", + "auto_impl", + "either", + "elliptic-curve", + "k256", + "thiserror", +] + +[[package]] +name = "alloy-sol-macro" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", @@ -596,11 +931,34 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "2.4.2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae82426d98f8bc18f53c5223862907cac30ab8fc5e4cd2bb50808e6d3ab43d8" +dependencies = [ + "alloy-json-rpc 1.1.2", + "auto_impl", + "base64 0.22.1", + "derive_more", + "futures", + "futures-utils-wasm", + "parking_lot", + "serde", + "serde_json", + "thiserror", + "tokio", + "tower", + "tracing", + "url", + "wasmtimer", +] + +[[package]] +name = "alloy-transport" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6576826236d84590b037e333bfc3643ae0a90cb325ca9da565419102047b3b81" +checksum = "999adfe5c91035c6bf4c4210e0eb8d0caed79d76fbf5e1b70d78721f6097ac04" dependencies = [ - "alloy-json-rpc", + "alloy-json-rpc 2.1.1", "auto_impl", "base64 0.22.1", "derive_more", @@ -619,14 +977,29 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "2.4.2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90aa6825760905898c106aba9c804b131816a15041523e80b6d4fe7af6380ada" +dependencies = [ + "alloy-json-rpc 1.1.2", + "alloy-transport 1.1.2", + "reqwest 0.12.24", + "serde_json", + "tower", + "tracing", + "url", +] + +[[package]] +name = "alloy-transport-http" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e38c841f63141cad3f1a4378cedf121914b32932cf09b66c6006d4a906112136" +checksum = "0e79a2c1793afc61eed9ca0963da370a988b27d2bbfa67c78013e262d47424c4" dependencies = [ - "alloy-json-rpc", - "alloy-transport", + "alloy-json-rpc 2.1.1", + "alloy-transport 2.1.1", "itertools 0.14.0", - "reqwest", + "reqwest 0.13.5", "serde_json", "tower", "tracing", @@ -651,9 +1024,21 @@ dependencies = [ [[package]] name = "alloy-tx-macros" -version = "2.4.2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae109e33814b49fc0a62f2528993aa8a2dd346c26959b151f05441dc0b9da292" +dependencies = [ + "darling 0.21.3", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "alloy-tx-macros" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25484345e4d89c259235e200d4f895eba33e70f125f4e8bb37a7aa69a97bd656" +checksum = "406bc1183f6843e0aba09f7b3365e828b597213d60793ba5cb41befc863e3a78" dependencies = [ "darling 0.23.0", "proc-macro2", @@ -682,12 +1067,56 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.103" @@ -742,7 +1171,7 @@ dependencies = [ "fnv", "hashbrown 0.15.4", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "zeroize", @@ -759,7 +1188,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", @@ -779,7 +1208,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", @@ -800,7 +1229,7 @@ dependencies = [ "digest 0.10.7", "educe", "itertools 0.13.0", - "num-bigint", + "num-bigint 0.4.6", "num-traits", "paste", "zeroize", @@ -842,7 +1271,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", @@ -854,7 +1283,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", @@ -867,7 +1296,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", @@ -900,7 +1329,7 @@ dependencies = [ "ark-relations", "ark-std 0.5.0", "educe", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "tracing", @@ -915,7 +1344,7 @@ dependencies = [ "ark-ff 0.5.0", "ark-std 0.5.0", "tracing", - "tracing-subscriber", + "tracing-subscriber 0.2.25", ] [[package]] @@ -936,7 +1365,7 @@ checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" dependencies = [ "ark-std 0.4.0", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -949,7 +1378,7 @@ dependencies = [ "ark-std 0.5.0", "arrayvec", "digest 0.10.7", - "num-bigint", + "num-bigint 0.4.6", ] [[package]] @@ -1005,6 +1434,16 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -1071,6 +1510,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "az" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b7e4c2464d97fe331d41de9d5db0def0a96f4d823b8b32a2efd503578988973" + [[package]] name = "base16ct" version = "0.2.0" @@ -1095,6 +1540,15 @@ version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.8.0" @@ -1154,6 +1608,28 @@ dependencies = [ "wyz", ] +[[package]] +name = "blake3" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" +dependencies = [ + "arrayref", + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -1246,9 +1722,9 @@ dependencies = [ [[package]] name = "c-kzg" -version = "2.1.8" +version = "2.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d04308254695569fdb9bfe3bacc1c91837a670d0806605eb82d63748fbd3a6" +checksum = "6648ed1e4ea8e8a1a4a2c78e1cda29a3fd500bc622899c340d8525ea9a76b24a" dependencies = [ "blst", "cc", @@ -1336,6 +1812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -1344,8 +1821,22 @@ version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.104", ] [[package]] @@ -1423,7 +1914,19 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", +] + +[[package]] +name = "console" +version = "0.15.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "windows-sys 0.59.0", ] [[package]] @@ -1465,6 +1968,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "constant_time_eq" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" + [[package]] name = "convert_case" version = "0.10.0" @@ -1474,6 +1983,16 @@ 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-sys" version = "0.8.7" @@ -1572,6 +2091,16 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + [[package]] name = "darling" version = "0.23.0" @@ -1592,6 +2121,21 @@ dependencies = [ "darling_macro 0.24.1", ] +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "serde", + "strsim", + "syn 2.0.104", +] + [[package]] name = "darling_core" version = "0.23.0" @@ -1619,6 +2163,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core 0.21.3", + "quote", + "syn 2.0.104", +] + [[package]] name = "darling_macro" version = "0.23.0" @@ -1655,6 +2210,24 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + [[package]] name = "defmt" version = "1.1.1" @@ -1793,6 +2366,27 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -1872,6 +2466,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "enum-ordinalize" version = "4.3.0" @@ -1905,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.52.0", ] [[package]] @@ -1982,10 +2591,27 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ + "byteorder", + "ff_derive", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "ff_derive" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f10d12652036b0e99197587c6ba87a8fc3031986499973c030d8b44fcc151b60" +dependencies = [ + "addchain", + "num-bigint 0.3.3", + "num-integer", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -2010,12 +2636,33 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -2125,6 +2772,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42012b0f064e01aa58b545fe3727f90f7dd4020f4a3ea735b50344965f5a57e9" +[[package]] +name = "gcd" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d758ba1b47b00caf47f24925c0074ecb20d6dfcffe7f6d53395c0465674841a" + [[package]] name = "generic-array" version = "0.14.7" @@ -2176,6 +2829,16 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" +[[package]] +name = "gmp-mpfr-sys" +version = "1.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66d61197a68f6323b9afa616cf83d55d69191e1bf364d4eb7d35ae18defe776" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "group" version = "0.13.0" @@ -2188,15 +2851,40 @@ dependencies = [ ] [[package]] -name = "half" -version = "2.6.0" +name = "h2" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.10.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" dependencies = [ "cfg-if", "crunchy", ] +[[package]] +name = "hash-db" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" + [[package]] name = "hashbrown" version = "0.12.3" @@ -2216,17 +2904,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" dependencies = [ "allocator-api2", + "equivalent", + "foldhash 0.1.5", ] [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", "serde", "serde_core", ] @@ -2309,6 +3008,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.12" @@ -2328,9 +3033,11 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2338,6 +3045,38 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.20" @@ -2356,9 +3095,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2537,6 +3278,30 @@ dependencies = [ "serde", ] +[[package]] +name = "indicatif" +version = "0.17.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" +dependencies = [ + "console", + "number_prefix", + "portable-atomic", + "web-time", +] + +[[package]] +name = "insta" +version = "1.47.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4a6248eb93a4401ed2f37dfe8ea592d3cf05b7cf4f8efa867b6895af7e094e" +dependencies = [ + "once_cell", + "serde", + "similar", + "tempfile", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -2551,9 +3316,15 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.10.5" @@ -2563,6 +3334,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.13.0" @@ -2672,7 +3452,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -2695,6 +3475,20 @@ dependencies = [ "sha3-asm", ] +[[package]] +name = "kzg-rs" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9201effeea3fcc93b587904ae2df9ce97e433184b9d6d299e9ebc9830a546636" +dependencies = [ + "ff", + "hex", + "serde_arrays", + "sha2 0.10.9", + "sp1_bls12_381", + "spin", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -2713,6 +3507,61 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" +[[package]] +name = "libredox" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" +dependencies = [ + "libc", +] + +[[package]] +name = "libsecp256k1" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e79019718125edc905a079a70cfa5f3820bc76139fc91d6f9abc27ea2a887139" +dependencies = [ + "arrayref", + "base64 0.22.1", + "digest 0.9.0", + "libsecp256k1-core", + "libsecp256k1-gen-ecmult", + "libsecp256k1-gen-genmult", + "rand 0.8.5", + "serde", + "sha2 0.9.9", +] + +[[package]] +name = "libsecp256k1-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" +dependencies = [ + "crunchy", + "digest 0.9.0", + "subtle", +] + +[[package]] +name = "libsecp256k1-gen-ecmult" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809" +dependencies = [ + "libsecp256k1-core", +] + +[[package]] +name = "libsecp256k1-gen-genmult" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c" +dependencies = [ + "libsecp256k1-core", +] + [[package]] name = "linux-raw-sys" version = "0.9.4" @@ -2742,11 +3591,20 @@ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "lru" -version = "0.18.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25" +checksum = "227748d55f2f0ab4735d87fd623798cb6b664512fe979705f829c9f81c934465" dependencies = [ - "hashbrown 0.17.1", + "hashbrown 0.15.4", +] + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", ] [[package]] @@ -2760,28 +3618,202 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "mega-evm" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a4ced1e43118907936957ffd224fdcef42ec2d2abfc5f4e417361af1fd011ef" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-evm 0.15.0", + "alloy-hardforks 0.2.13", + "alloy-op-evm 0.15.0", + "alloy-op-hardforks 0.2.13", + "alloy-primitives", + "alloy-sol-types", + "auto_impl", + "bitflags 2.11.1", + "delegate", + "derive_more", + "mega-system-contracts 1.7.1", + "once_cell", + "op-alloy-consensus 0.18.14", + "op-alloy-flz", + "op-revm 8.1.0", + "revm 27.1.0", + "serde", + "thiserror", + "tracing", +] + [[package]] name = "mega-evm" version = "2.0.0-alpha.1" dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-evm", - "alloy-hardforks", - "alloy-op-evm", - "alloy-op-hardforks", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-evm 0.36.0", + "alloy-hardforks 0.4.8", + "alloy-op-evm 0.32.0", + "alloy-op-hardforks 0.5.0", "alloy-primitives", + "alloy-rpc-types-trace 2.1.1", "alloy-sol-types", + "alloy-trie", "auto_impl", "codspeed-criterion-compat", "delegate", "derive_more", - "mega-evm", - "mega-system-contracts", - "op-alloy-consensus", - "op-revm", - "revm", - "revm-inspectors", + "insta", + "mega-evm 2.0.0-alpha.1", + "mega-system-contracts 2.0.0-alpha.1", + "op-alloy-consensus 2.0.0", + "op-revm 20.0.0", + "proptest", + "revm 40.0.3", + "revm-inspectors 0.40.4", + "serde", + "serde_json", +] + +[[package]] +name = "mega-evme" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d04688d5d68411127148df8b35d64469a3056a1c38c30705c80e8a1c067d7eae" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-json-rpc 1.1.2", + "alloy-network 1.1.0", + "alloy-primitives", + "alloy-provider 1.1.0", + "alloy-rpc-client 1.1.2", + "alloy-rpc-types-eth 1.1.0", + "alloy-rpc-types-trace 1.0.24", + "alloy-serde 1.8.3", + "alloy-sol-types", + "alloy-transport 1.1.2", + "alloy-transport-http 1.1.2", + "clap", + "dirs", + "mega-evm 1.7.1", + "mega-state-test 1.7.1", + "op-alloy-consensus 0.18.14", + "op-alloy-network 0.18.14", + "op-alloy-rpc-types 0.18.14", + "reqwest 0.12.24", + "revm-inspectors 0.27.3", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", + "tower", + "tracing", + "tracing-subscriber 0.3.20", +] + +[[package]] +name = "mega-evme" +version = "2.0.0-alpha.1" +dependencies = [ + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-json-rpc 2.1.1", + "alloy-network 2.1.1", + "alloy-primitives", + "alloy-provider 2.1.1", + "alloy-rpc-client 2.1.1", + "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-trace 2.1.1", + "alloy-serde 2.1.1", + "alloy-sol-types", + "alloy-transport 2.1.1", + "alloy-transport-http 2.1.1", + "alloy-trie", + "clap", + "dirs", + "mega-evm 1.7.1", + "mega-evm 2.0.0-alpha.1", + "mega-evme 1.7.1", + "mega-evme 2.0.0-alpha.1", + "mega-state-test 1.7.1", + "op-alloy-consensus 2.0.0", + "op-alloy-network 2.0.0", + "op-alloy-rpc-types 2.0.0", + "revm 40.0.3", + "revm-inspectors 0.40.4", + "rstest", + "serde", + "serde_json", + "tempfile", + "thiserror", + "tokio", + "tower", + "tracing", + "tracing-subscriber 0.3.20", + "wiremock", + "zstd", +] + +[[package]] +name = "mega-state-test" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d0704469463ed0c3c0041e2aa37b3d81a39f9979b36ab497d48a9b1d8704e14" +dependencies = [ + "alloy-eips 1.8.3", + "alloy-primitives", + "alloy-rlp", + "alloy-serde 1.8.3", + "hash-db", + "indicatif", + "k256", + "mega-evm 1.7.1", + "plain_hasher", + "serde", + "serde_json", + "thiserror", + "triehash", + "walkdir", +] + +[[package]] +name = "mega-state-test" +version = "2.0.0-alpha.1" +dependencies = [ + "alloy-eips 2.1.1", + "alloy-rlp", + "alloy-trie", + "mega-evm 2.0.0-alpha.1", + "revm 40.0.3", + "serde", + "serde_json", + "tempfile", + "thiserror", + "walkdir", +] + +[[package]] +name = "mega-system-contracts" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4db5b3bdbdf4673e208e1dd2d9b9563d16a50fe7f9d51536613f8ee45b208db1" +dependencies = [ + "alloy-primitives", + "alloy-sol-types", + "semver 1.0.26", "serde", "serde_json", ] @@ -2803,6 +3835,12 @@ version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "mio" version = "1.2.3" @@ -2835,6 +3873,23 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "native-tls" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "nix" version = "0.31.3" @@ -2856,13 +3911,22 @@ dependencies = [ "serde", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num" 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", @@ -2870,6 +3934,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6f7833f2cbf2360a6cfd58cd41a53aa7a90bd4c202f5b1c7dd2ed73c57b2c3" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -2921,7 +3996,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", ] @@ -2962,11 +4037,18 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77e878c846a8abae00dd069496dbe8751b16ac1c3d6bd2a7283a938e8228f90d" dependencies = [ + "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.104", ] +[[package]] +name = "number_prefix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" + [[package]] name = "nybbles" version = "0.4.3" @@ -2991,6 +4073,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oorandom" version = "11.1.5" @@ -3002,25 +4090,43 @@ name = "op-alloy" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "op-alloy-consensus", - "op-alloy-network", + "op-alloy-consensus 2.0.0", + "op-alloy-network 2.0.0", "op-alloy-provider", - "op-alloy-rpc-types", + "op-alloy-rpc-types 2.0.0", "op-alloy-rpc-types-engine", ] +[[package]] +name = "op-alloy-consensus" +version = "0.18.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c88d2940558fd69f8f07b3cbd7bb3c02fc7d31159c1a7ba9deede50e7881024" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-network 1.1.0", + "alloy-primitives", + "alloy-rlp", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", + "derive_more", + "serde", + "thiserror", +] + [[package]] name = "op-alloy-consensus" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-network", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-network 2.1.1", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "bytes", "derive_more", "reth-codecs", @@ -3030,17 +4136,39 @@ dependencies = [ "thiserror", ] +[[package]] +name = "op-alloy-flz" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a79f352fc3893dcd670172e615afef993a41798a1d3fc0db88a3e60ef2e70ecc" + +[[package]] +name = "op-alloy-network" +version = "0.18.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7071d7c3457d02aa0d35799cb8fbd93eabd51a21d100dcf411f4fcab6fdd2ea5" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-network 1.1.0", + "alloy-primitives", + "alloy-provider 1.1.0", + "alloy-rpc-types-eth 1.1.0", + "alloy-signer 1.1.2", + "op-alloy-consensus 0.18.14", + "op-alloy-rpc-types 0.18.14", +] + [[package]] name = "op-alloy-network" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus", - "alloy-network", - "alloy-provider", - "alloy-rpc-types-eth", - "op-alloy-consensus", - "op-alloy-rpc-types", + "alloy-consensus 2.1.1", + "alloy-network 2.1.1", + "alloy-provider 2.1.1", + "alloy-rpc-types-eth 2.1.1", + "op-alloy-consensus 2.0.0", + "op-alloy-rpc-types 2.0.0", ] [[package]] @@ -3048,29 +4176,48 @@ name = "op-alloy-provider" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-network", + "alloy-network 2.1.1", "alloy-primitives", - "alloy-provider", + "alloy-provider 2.1.1", "alloy-rpc-types-engine", - "alloy-transport", + "alloy-transport 2.1.1", "async-trait", "op-alloy-rpc-types-engine", ] +[[package]] +name = "op-alloy-rpc-types" +version = "0.18.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f22201e53e8cbb67a053e88b534b4e7f02265c5406994bf35978482a9ad0ae26" +dependencies = [ + "alloy-consensus 1.1.0", + "alloy-eips 1.8.3", + "alloy-network-primitives 1.1.0", + "alloy-primitives", + "alloy-rpc-types-eth 1.1.0", + "alloy-serde 1.8.3", + "derive_more", + "op-alloy-consensus 0.18.14", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "op-alloy-rpc-types" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-network", - "alloy-network-primitives", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", + "alloy-network 2.1.1", + "alloy-network-primitives 2.1.1", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-serde", + "alloy-rpc-types-eth 2.1.1", + "alloy-serde 2.1.1", "derive_more", - "op-alloy-consensus", + "op-alloy-consensus 2.0.0", "reth-rpc-traits", "serde", "serde_json", @@ -3082,31 +4229,98 @@ name = "op-alloy-rpc-types-engine" version = "2.0.0" source = "git+https://github.com/ethereum-optimism/optimism?rev=f67d87cd5c9992b62d215c043917b94e3f019629#f67d87cd5c9992b62d215c043917b94e3f019629" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-serde", + "alloy-serde 2.1.1", "ethereum_ssz", "ethereum_ssz_derive", - "op-alloy-consensus", + "op-alloy-consensus 2.0.0", "serde", - "sha2", + "sha2 0.10.9", "snap", "thiserror", ] +[[package]] +name = "op-revm" +version = "8.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ce1dc7533f4e5716c55cd3d62488c6200cb4dfda96e0c75a7e484652464343b" +dependencies = [ + "auto_impl", + "once_cell", + "revm 27.1.0", + "serde", +] + [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.2#260f65329f1f47b7412a1b2c1fda85453f66521c" +source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.3#58bc98e2fcaffcdea23595b2680fc68daddd7b69" dependencies = [ "auto_impl", - "revm", + "revm 40.0.3", "serde", ] +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.11.1", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "p256" version = "0.13.2" @@ -3116,7 +4330,128 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2", + "sha2 0.10.9", +] + +[[package]] +name = "p3-baby-bear" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7521838ecab2ddf4f7bc4ceebad06ec02414729598485c1ada516c39900820e8" +dependencies = [ + "num-bigint 0.4.6", + "p3-field", + "p3-mds", + "p3-poseidon2", + "p3-symmetric", + "rand 0.8.5", + "serde", +] + +[[package]] +name = "p3-dft" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46414daedd796f1eefcdc1811c0484e4bced5729486b6eaba9521c572c76761a" +dependencies = [ + "p3-field", + "p3-matrix", + "p3-maybe-rayon", + "p3-util", + "tracing", +] + +[[package]] +name = "p3-field" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48948a0516b349e9d1cdb95e7236a6ee010c44e68c5cc78b4b92bf1c4022a0d9" +dependencies = [ + "itertools 0.12.1", + "num-bigint 0.4.6", + "num-traits", + "p3-util", + "rand 0.8.5", + "serde", +] + +[[package]] +name = "p3-matrix" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e4de3f373589477cb735ea58e125898ed20935e03664b4614c7fac258b3c42f" +dependencies = [ + "itertools 0.12.1", + "p3-field", + "p3-maybe-rayon", + "p3-util", + "rand 0.8.5", + "serde", + "tracing", +] + +[[package]] +name = "p3-maybe-rayon" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3968ad1160310296eb04f91a5f4edfa38fe1d6b2b8cd6b5c64e6f9b7370979e" + +[[package]] +name = "p3-mds" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2356b1ed0add6d5dfbf7a338ce534a6fde827374394a52cec16a0840af6e97c9" +dependencies = [ + "itertools 0.12.1", + "p3-dft", + "p3-field", + "p3-matrix", + "p3-symmetric", + "p3-util", + "rand 0.8.5", +] + +[[package]] +name = "p3-poseidon2" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da1eec7e1b6900581bedd95e76e1ef4975608dd55be9872c9d257a8a9651c3a" +dependencies = [ + "gcd", + "p3-field", + "p3-mds", + "p3-symmetric", + "rand 0.8.5", + "serde", +] + +[[package]] +name = "p3-symmetric" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edb439bea1d822623b41ff4b51e3309e80d13cadf8b86d16ffd5e6efb9fdc360" +dependencies = [ + "itertools 0.12.1", + "p3-field", + "serde", +] + +[[package]] +name = "p3-util" +version = "0.2.3-succinct" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c2c2010678b9332b563eaa38364915b585c1a94b5ca61e2c7541c087ddda5c" +dependencies = [ + "serde", +] + +[[package]] +name = "pairing" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fec4625e73cf41ef4bb6846cafa6d44736525f442ba45e407c4a000a13996f" +dependencies = [ + "group", ] [[package]] @@ -3194,13 +4529,24 @@ dependencies = [ "ucd-trie", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", + "serde", +] + [[package]] name = "phf" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros", + "phf_macros 0.13.1", "phf_shared 0.13.1", "serde", ] @@ -3214,14 +4560,37 @@ dependencies = [ "phf_shared 0.14.0", ] +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.5", +] + [[package]] name = "phf_generator" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "fastrand", - "phf_shared 0.13.1", + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.104", ] [[package]] @@ -3230,13 +4599,22 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator", + "phf_generator 0.13.1", "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.104", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -3303,6 +4681,15 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plain_hasher" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e19e6491bdde87c2c43d70f4c194bc8a758f2eb732df00f61e43f7362e3b4cc" +dependencies = [ + "crunchy", +] + [[package]] name = "plotters" version = "0.3.7" @@ -3572,6 +4959,17 @@ dependencies = [ "bitflags 2.11.1", ] +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror", +] + [[package]] name = "ref-cast" version = "1.0.24" @@ -3621,6 +5019,52 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + +[[package]] +name = "reqwest" +version = "0.12.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "reqwest" version = "0.13.5" @@ -3658,8 +5102,8 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9c37bb4d1bac98661bf9128e1141b969034640d68697b22f70377e492fd332c" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -3688,19 +5132,19 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9102518f0bbf99bc8f0e656a56fb2a7513248630275b608d3706076a82fde42b" dependencies = [ - "alloy-consensus", - "alloy-eips", + "alloy-consensus 2.1.1", + "alloy-eips 2.1.1", "alloy-genesis", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth", + "alloy-rpc-types-eth 2.1.1", "alloy-trie", "bytes", "derive_more", "once_cell", - "revm-bytecode", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", "secp256k1 0.30.0", "serde", "thiserror", @@ -3712,11 +5156,11 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa03a2c9681c385ae1c72b169ac9c3525163b71db0b3362f16e8929e19e45fd" dependencies = [ - "alloy-consensus", - "alloy-network", + "alloy-consensus 2.1.1", + "alloy-network 2.1.1", "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-signer", + "alloy-rpc-types-eth 2.1.1", + "alloy-signer 2.1.1", "reth-primitives-traits", "thiserror", ] @@ -3730,126 +5174,280 @@ dependencies = [ "zstd", ] +[[package]] +name = "revm" +version = "27.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6bf82101a1ad8a2b637363a37aef27f88b4efc8a6e24c72bf5f64923dc5532" +dependencies = [ + "revm-bytecode 6.2.1", + "revm-context 8.0.4", + "revm-context-interface 9.0.0", + "revm-database 7.0.4", + "revm-database-interface 7.0.4", + "revm-handler 8.1.0", + "revm-inspector 8.1.0", + "revm-interpreter 24.0.0", + "revm-precompile 25.0.0", + "revm-primitives 20.2.1", + "revm-state 7.0.4", +] + [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +dependencies = [ + "revm-bytecode 11.0.1", + "revm-context 18.0.3", + "revm-context-interface 19.0.3", + "revm-database 15.0.2", + "revm-database-interface 12.1.1", + "revm-handler 20.0.3", + "revm-inspector 21.0.3", + "revm-interpreter 37.0.3", + "revm-precompile 36.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "revm-statetest-types", +] + +[[package]] +name = "revm-bytecode" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d800e6c2119457ded5b0af71634eb2468040bf97de468eee5a730272a106da0" 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", + "bitvec", + "phf 0.11.3", + "revm-primitives 20.2.1", + "serde", ] [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "bitvec", "phf 0.13.1", - "revm-primitives", + "revm-primitives 24.0.1", + "serde", +] + +[[package]] +name = "revm-context" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cd508416a35a4d8a9feaf5ccd06ac6d6661cd31ee2dc0252f9f7316455d71f9" +dependencies = [ + "cfg-if", + "derive-where", + "revm-bytecode 6.2.1", + "revm-context-interface 9.0.0", + "revm-database-interface 7.0.4", + "revm-primitives 20.2.1", + "revm-state 7.0.4", "serde", ] [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "bitvec", "cfg-if", "derive-where", - "revm-bytecode", - "revm-context-interface", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context-interface 19.0.3", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-context-interface" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc90302642d21c8f93e0876e201f3c5f7913c4fcb66fb465b0fd7b707dfe1c79" +dependencies = [ + "alloy-eip2930", + "alloy-eip7702", + "auto_impl", + "either", + "revm-database-interface 7.0.4", + "revm-primitives 20.2.1", + "revm-state 7.0.4", "serde", ] [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-eip2930", "alloy-eip7702", "auto_impl", "either", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-database" +version = "7.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40000c7d917c865f6c232a78581b78e70c43f52db17282bd1b52d4f0565bc8a2" +dependencies = [ + "alloy-eips 1.8.3", + "alloy-provider 1.1.0", + "alloy-transport 1.1.2", + "revm-bytecode 6.2.1", + "revm-database-interface 7.0.4", + "revm-primitives 20.2.1", + "revm-state 7.0.4", "serde", + "tokio", ] [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ - "alloy-eips", + "alloy-eips 2.1.1", + "alloy-provider 2.1.1", + "alloy-transport 2.1.1", "derive_more", - "revm-bytecode", - "revm-database-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-database-interface 12.1.1", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", + "tokio", +] + +[[package]] +name = "revm-database-interface" +version = "7.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ccea7a168cba1196b1e57dd3e22c36047208c135f600f8e58cbe7d49957dba" +dependencies = [ + "auto_impl", + "either", + "revm-primitives 20.2.1", + "revm-state 7.0.4", "serde", + "tokio", ] [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "either", - "revm-primitives", - "revm-state", + "revm-primitives 24.0.1", + "revm-state 12.0.1", "serde", "thiserror", + "tokio", +] + +[[package]] +name = "revm-handler" +version = "8.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1529c8050e663be64010e80ec92bf480315d21b1f2dbf65540028653a621b27d" +dependencies = [ + "auto_impl", + "derive-where", + "revm-bytecode 6.2.1", + "revm-context 8.0.4", + "revm-context-interface 9.0.0", + "revm-database-interface 7.0.4", + "revm-interpreter 24.0.0", + "revm-precompile 25.0.0", + "revm-primitives 20.2.1", + "revm-state 7.0.4", + "serde", ] [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "derive-where", - "revm-bytecode", - "revm-context", - "revm-context-interface", - "revm-database-interface", - "revm-interpreter", - "revm-precompile", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context 18.0.3", + "revm-context-interface 19.0.3", + "revm-database-interface 12.1.1", + "revm-interpreter 37.0.3", + "revm-precompile 36.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", +] + +[[package]] +name = "revm-inspector" +version = "8.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78db140e332489094ef314eaeb0bd1849d6d01172c113ab0eb6ea8ab9372926" +dependencies = [ + "auto_impl", + "either", + "revm-context 8.0.4", + "revm-database-interface 7.0.4", + "revm-handler 8.1.0", + "revm-interpreter 24.0.0", + "revm-primitives 20.2.1", + "revm-state 7.0.4", "serde", + "serde_json", ] [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "auto_impl", "either", - "revm-context", - "revm-database-interface", - "revm-handler", - "revm-interpreter", - "revm-primitives", - "revm-state", + "revm-context 18.0.3", + "revm-database-interface 12.1.1", + "revm-handler 20.0.3", + "revm-interpreter 37.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", + "serde", + "serde_json", +] + +[[package]] +name = "revm-inspectors" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2483827fec2c31db4ada14e0b5523c377d1084337d1dbe135faaf14c218ab1af" +dependencies = [ + "alloy-primitives", + "alloy-rpc-types-eth 1.1.0", + "alloy-rpc-types-trace 1.0.24", + "alloy-sol-types", + "anstyle", + "colorchoice", + "revm 27.1.0", "serde", "serde_json", + "thiserror", ] [[package]] @@ -3859,33 +5457,73 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e93b96ddc470322a7294b8aecad862480625a9f1346d42fea51b1cce54afdb05" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth", - "alloy-rpc-types-trace", + "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-trace 2.1.1", "alloy-sol-types", "anstyle", "colorchoice", - "revm", + "revm 40.0.3", "serde", "serde_json", "thiserror", ] +[[package]] +name = "revm-interpreter" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff9d7d9d71e8a33740b277b602165b6e3d25fff091ba3d7b5a8d373bf55f28a7" +dependencies = [ + "revm-bytecode 6.2.1", + "revm-context-interface 9.0.0", + "revm-primitives 20.2.1", + "serde", +] + [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ - "revm-bytecode", - "revm-context-interface", - "revm-primitives", - "revm-state", + "revm-bytecode 11.0.1", + "revm-context-interface 19.0.3", + "revm-primitives 24.0.1", + "revm-state 12.0.1", "serde", ] +[[package]] +name = "revm-precompile" +version = "25.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cee3f336b83621294b4cfe84d817e3eef6f3d0fce00951973364cc7f860424d" +dependencies = [ + "ark-bls12-381", + "ark-bn254", + "ark-ec", + "ark-ff 0.5.0", + "ark-serialize 0.5.0", + "arrayref", + "aurora-engine-modexp", + "blst", + "c-kzg", + "cfg-if", + "k256", + "kzg-rs", + "libsecp256k1", + "once_cell", + "p256", + "revm-primitives 20.2.1", + "ripemd", + "rug", + "secp256k1 0.31.1", + "sha2 0.10.9", +] + [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -3899,34 +5537,75 @@ dependencies = [ "cfg-if", "k256", "p256", - "revm-context-interface", - "revm-primitives", + "revm-context-interface 19.0.3", + "revm-primitives 24.0.1", "ripemd", "secp256k1 0.31.1", - "sha2", + "sha2 0.10.9", +] + +[[package]] +name = "revm-primitives" +version = "20.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa29d9da06fe03b249b6419b33968ecdf92ad6428e2f012dc57bcd619b5d94e" +dependencies = [ + "alloy-primitives", + "num_enum", + "once_cell", + "serde", ] [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ "alloy-primitives", "once_cell", "serde", ] +[[package]] +name = "revm-state" +version = "7.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d7f39ea56df3bfbb3c81c99b1f028d26f205b6004156baffbf1a4f84b46cfa" +dependencies = [ + "bitflags 2.11.1", + "revm-bytecode 6.2.1", + "revm-primitives 20.2.1", + "serde", +] + [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.2#2e7ad0d2d4310a6625f8a2f256f5bf271a4b7df7" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" dependencies = [ - "alloy-eip7928", + "alloy-eip7928 0.4.11", "bitflags 2.11.1", "nonmax", - "revm-bytecode", - "revm-primitives", + "revm-bytecode 11.0.1", + "revm-primitives 24.0.1", + "serde", +] + +[[package]] +name = "revm-statetest-types" +version = "19.0.3" +source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +dependencies = [ + "alloy-eip7928 0.4.11", + "k256", + "revm-context 18.0.3", + "revm-context-interface 19.0.3", + "revm-database 15.0.2", + "revm-primitives 24.0.1", + "revm-state 12.0.1", "serde", + "serde_json", + "thiserror", ] [[package]] @@ -3939,6 +5618,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ripemd" version = "0.1.3" @@ -3958,6 +5651,45 @@ dependencies = [ "rustc-hex", ] +[[package]] +name = "rstest" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" +dependencies = [ + "rstest_macros", + "rustc_version 0.4.1", +] + +[[package]] +name = "rstest_macros" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f168d99749d307be9de54d23fd226628d99768225ef08f6ffb52e0182a27746" +dependencies = [ + "cfg-if", + "glob", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version 0.4.1", + "syn 2.0.104", + "unicode-ident", +] + +[[package]] +name = "rug" +version = "1.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4207e8d668e5b8eb574bda8322088ccd0d7782d3d03c7e8d562e82ed82bdcbc3" +dependencies = [ + "az", + "gmp-mpfr-sys", + "libc", + "libm", +] + [[package]] name = "ruint" version = "1.17.2" @@ -3971,7 +5703,7 @@ dependencies = [ "bytes", "fastrlp 0.3.1", "fastrlp 0.4.0", - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", "parity-scale-codec", @@ -4032,7 +5764,40 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.60.2", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -4053,6 +5818,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + [[package]] name = "same-file" version = "1.0.6" @@ -4062,6 +5833,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.9.0" @@ -4148,6 +5928,29 @@ dependencies = [ "cc", ] +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.11.1", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "0.11.0" @@ -4185,6 +5988,15 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde_arrays" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94a16b99c5ea4fe3daccd14853ad260ec00ea043b2708d1fd1da3106dcd8d9df" +dependencies = [ + "serde", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -4219,6 +6031,18 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "serde_with" version = "3.23.0" @@ -4262,6 +6086,19 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.9.0", + "opaque-debug", +] + [[package]] name = "sha2" version = "0.10.9" @@ -4293,6 +6130,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -4309,6 +6155,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "siphasher" version = "1.0.1" @@ -4346,6 +6198,58 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "sp1-lib" +version = "5.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fbb6e3d8741c0fcdaa37e74d2dd9a2bdcbf958d192e438eec59e8071e08124c" +dependencies = [ + "bincode", + "serde", + "sp1-primitives", +] + +[[package]] +name = "sp1-primitives" +version = "5.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4d2be9803acce74985f8861b6d5eb375ad1c5f176a68c2c735755937248f25e" +dependencies = [ + "bincode", + "blake3", + "cfg-if", + "hex", + "lazy_static", + "num-bigint 0.4.6", + "p3-baby-bear", + "p3-field", + "p3-poseidon2", + "p3-symmetric", + "serde", + "sha2 0.10.9", +] + +[[package]] +name = "sp1_bls12_381" +version = "0.8.0-sp1-5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac255e1704ebcdeec5e02f6a0ebc4d2e9e6b802161938330b6810c13a610c583" +dependencies = [ + "cfg-if", + "ff", + "group", + "pairing", + "rand_core 0.6.4", + "sp1-lib", + "subtle", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + [[package]] name = "spki" version = "0.7.3" @@ -4362,6 +6266,18 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "state-test" +version = "2.0.0-alpha.1" +dependencies = [ + "alloy-rlp", + "clap", + "mega-evm 2.0.0-alpha.1", + "mega-state-test 2.0.0-alpha.1", + "serde_json", + "tempfile", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -4476,6 +6392,27 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.11.1", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -4492,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -4515,6 +6452,15 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "threadpool" version = "1.8.1" @@ -4587,6 +6533,7 @@ version = "1.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", @@ -4606,6 +6553,26 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -4627,6 +6594,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -4734,6 +6702,32 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-subscriber" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "thread_local", + "tracing", + "tracing-core", +] + +[[package]] +name = "triehash" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1631b201eb031b563d2e85ca18ec8092508e262a3196ce9bd10a67ec87b9f5c" +dependencies = [ + "hash-db", + "rlp", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -4788,6 +6782,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -4807,12 +6807,24 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -4957,13 +6969,23 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "winapi-util" 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.52.0", ] [[package]] @@ -4975,8 +6997,8 @@ dependencies = [ "windows-implement", "windows-interface", "windows-link 0.1.3", - "windows-result", - "windows-strings", + "windows-result 0.3.4", + "windows-strings 0.4.2", ] [[package]] @@ -5013,6 +7035,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-result" version = "0.3.4" @@ -5022,6 +7055,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-strings" version = "0.4.2" @@ -5031,22 +7073,31 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-sys" -version = "0.59.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] name = "windows-sys" -version = "0.60.2" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.53.2", + "windows-targets", ] [[package]] @@ -5064,30 +7115,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" -dependencies = [ - "windows_aarch64_gnullvm 0.53.0", - "windows_aarch64_msvc 0.53.0", - "windows_i686_gnu 0.53.0", - "windows_i686_gnullvm 0.53.0", - "windows_i686_msvc 0.53.0", - "windows_x86_64_gnu 0.53.0", - "windows_x86_64_gnullvm 0.53.0", - "windows_x86_64_msvc 0.53.0", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -5096,96 +7131,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" - [[package]] name = "winnow" version = "0.7.12" @@ -5204,6 +7191,29 @@ dependencies = [ "memchr", ] +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64 0.22.1", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + [[package]] name = "wit-bindgen-rt" version = "0.39.0" diff --git a/Cargo.toml b/Cargo.toml index ead272edc..ae3ba2ae5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,12 @@ [workspace] -# The tool crates (`bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, -# `crates/state-test`) still target the legacy engine; their sources are kept -# untouched and each rejoins the workspace when it is ported to Satin. -members = ["crates/mega-evm", "crates/system-contracts"] +members = [ + "bin/mega-evme", + "crates/mega-evm", + "crates/mega-state-test", + "crates/state-test", + "crates/system-contracts", +] default-members = ["crates/mega-evm"] exclude = [] @@ -13,7 +16,7 @@ resolver = "2" [workspace.package] version = "2.0.0-alpha.1" edition = "2021" -rust-version = "1.94.1" +rust-version = "1.94" license = "MIT OR Apache-2.0" homepage = "https://github.com/megaeth-labs/mega-evm" repository = "https://github.com/megaeth-labs/mega-evm" @@ -119,7 +122,13 @@ too_long_first_doc_paragraph = "allow" [workspace.dependencies] # megaeth mega-evm = { path = "./crates/mega-evm", version = "2.0.0-alpha.1", default-features = false } +# The `-legacy` entries are the legacy line (specs `Equivalence` through `Rex6`, crates.io revm +# 27), linked only by the `mega-evme` tool's legacy leg and pinned exactly: the tool replays +# history with what shipped. +mega-evm-legacy = { package = "mega-evm", version = "=1.7.1", default-features = false } +mega-evme-legacy = { package = "mega-evme", version = "=1.7.1", default-features = false } mega-state-test = { path = "./crates/mega-state-test", version = "2.0.0-alpha.1", default-features = false } +mega-state-test-legacy = { package = "mega-state-test", version = "=1.7.1", default-features = false } mega-system-contracts = { path = "./crates/system-contracts", version = "2.0.0-alpha.1", default-features = false } # revm @@ -150,39 +159,32 @@ alloy-serde = { version = "2.1.1", default-features = false } alloy-sol-types = { version = "1.6.0", default-features = false } alloy-transport = { version = "2.1.1", default-features = false } alloy-transport-http = { version = "2.1.1", default-features = false } +alloy-trie = { version = "0.9.5", default-features = false } op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false, features = ["k256"] } -op-alloy-flz = { version = "0.13.1", default-features = false } op-alloy-network = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } op-alloy-rpc-types = { git = "https://github.com/ethereum-optimism/optimism", rev = "f67d87cd5c9992b62d215c043917b94e3f019629", default-features = false } # misc auto_impl = { version = "1.3", default-features = false } -bitflags = { version = "2.6", default-features = false } clap = { version = "4", default-features = false, features = ["derive"] } delegate = { version = "0.13", default-features = false } derive_more = { version = "2", default-features = false } dirs = { version = "6", default-features = false } -getrandom = { version = "0.3", default-features = false } -hash-db = { version = "0.15", default-features = false } -hex = { version = "0.4", default-features = false } -indicatif = { version = "0.17", default-features = false } -k256 = { version = "0.13.4", default-features = false } -once_cell = { version = "1.21", default-features = false } -plain_hasher = { version = "0.2", default-features = false } -rand = { version = "0.10", default-features = false } +insta = { version = "1.47.2", default-features = false, features = ["json"] } +proptest = { version = "1.7", default-features = false } rstest = { version = "0.25", default-features = false } semver = { version = "1", default-features = false } serde = { version = "1.0", default-features = false } serde_json = { version = "1.0", default-features = false } -sha2 = { version = "0.10.9", default-features = false } tempfile = { version = "3", default-features = false } thiserror = { version = "2.0", default-features = false } tokio = { version = "1", default-features = false } +tower = { version = "0.5", default-features = false } tracing = { version = "0.1", default-features = false } tracing-subscriber = { version = "0.3", default-features = false } -triehash = { version = "0.8", default-features = false } walkdir = { version = "2.5", default-features = false } wiremock = { version = "0.6", default-features = false } +zstd = { version = "0.13", default-features = false } # Speed up compilation time for dev builds by reducing emitted debug info. # NOTE: Debuggers may provide less useful information with this setting. @@ -194,6 +196,8 @@ split-debuginfo = "unpacked" # Speed up tests. [profile.dev.package] +blst.opt-level = 3 +c-kzg.opt-level = 3 proptest.opt-level = 3 rand_chacha.opt-level = 3 rand_xorshift.opt-level = 3 @@ -228,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.2" } +revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm tag above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.2" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.3" } diff --git a/README.md b/README.md index e99cff180..b976a9e72 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ A specialized Ethereum Virtual Machine (EVM) implementation tailored for MegaETH ## Crates -| Crate | Description | -| ------------------------------------------------ | ------------------------------------------------------------------------- | -| [mega-evm](crates/mega-evm) | Core EVM implementation with MegaETH specs (`EQUIVALENCE` through `REX7`) | -| [mega-system-contracts](crates/system-contracts) | Solidity system contracts with Rust bindings | -| [mega-evme](bin/mega-evme) | CLI tool for EVM execution (`run`, `tx`, `replay`) | -| [mega-t8n](bin/mega-t8n) | Standalone state transition (t8n) tool | -| [state-test](crates/state-test) | Ethereum state test runner | +| Crate | Description | +| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | +| [mega-evm](crates/mega-evm) | Core EVM implementation: the Satin engine (`SATIN`, unstable); the legacy engine is `EQUIVALENCE` through `REX6` | +| [mega-system-contracts](crates/system-contracts) | Solidity system contracts with Rust bindings | +| [mega-evme](bin/mega-evme) | CLI tool for EVM execution (`run`, `tx`, `replay`) | +| [mega-state-test](crates/mega-state-test) | Execution-spec state-test runner on the Satin engine | +| [state-test](crates/state-test) | CLI of the execution-spec state-test runner | ## Installation @@ -25,7 +25,7 @@ The `--locked` flag ensures the exact tested dependency versions are used. Or build from source: ```bash -cargo build --release -p mega-evme +cargo build --release --manifest-path bin/mega-evme/Cargo.toml ``` ### Prebuilt binary diff --git a/REVIEW.md b/REVIEW.md index d8a3ac1ec..8451aeeb4 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -7,36 +7,47 @@ Defer to the baseline for everything not listed here; the rules below take prece ## Correctness and safety -### Spec backward compatibility +### Spec compatibility -This is the single most important correctness concern in mega-evm. - -- **Existing stable specs must never change behavior.** - Check `CLAUDE.md` for which spec is currently unstable — all others are frozen. - New EVM behavior, gas cost changes, or opcode modifications must introduce a new spec and be gated with `spec.is_enabled(MegaSpecId::NEW_SPEC)`. -- System contract changes (Solidity sources or Rust integration) require a new spec. -- Modified constants must be gated per-spec — verify that old spec paths still use the old values. -- If a PR claims to "fix" behavior for an existing spec, scrutinize whether this changes consensus. - A true bug fix in a frozen spec is rare and must be justified. +- Satin is the one spec of this engine and it is unstable: it has no activation timestamp yet, so a PR may change its behavior, and `docs/spec/upgrades/satin.md` and `AGENTS.md` change with it. + The legacy engine (`Equivalence` through `Rex6`) is frozen on `main` and is not edited here; flag a PR that adds a legacy spec, an alias rung or a ported legacy mechanism. +- There are no spec gates yet. + The next spec is added as the spec system in `AGENTS.md` describes; from then on Satin's path is fixed, and a change to behavior or to a constant that Satin shipped is gated on the new spec, with Satin's path left as it is. + Flag a PR that adds an `is_enabled` gate before a second spec exists. +- A change that makes Satin differ from op-revm on purpose updates `tests/satin/equivalence.rs`; a change that makes it differ from Ethereum's fixtures on purpose registers a deviation (see Test gates). +- System contract changes need a decision of their own: the Solidity sources and bindings carry over unchanged, so a change to one is not a side effect of an engine change. +- A change to a limit, a price or a constant says which of the spec's numbers moved, and regenerates the documents rendered from them. ### Consensus-critical execution - All execution logic must be **deterministic and architecture-independent** — no `mem::transmute`, no native-endian byte conversions, no platform-dependent operations in consensus paths. -- Pre-block helpers (system contract deploys, pre-exec system calls, etc.) must return `Option` for the block executor to commit — never call `db.commit(...)` directly. - Even idempotent "no change" paths must return `Some(EvmState)` with a read-only account entry; silently returning `None` drops the account from the stateless witness read set and produces an incomplete proof. - On `main` the full contract is in `crates/mega-evm/src/system/AGENTS.md` → `PRE-BLOCK STATE CHANGE CONTRACT`; on `satin` the helpers that exist live in `crates/mega-evm/src/block/eips.rs` and the block executor is what commits them, and the rest arrive with the pre-block system calls and the system contract deployments. - The same applies inside execution: read through the journal (`inspect_account`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state — and an early halt placed before the sandbox state merge drops that read set entirely. -- Per-frame gas mechanisms (stipends, adjustments) must handle all frame termination paths: system contract interception, gas rescue on limit exceed, and frame return. - Missing any path causes gas leakage. -- **Metering must be symmetric across every exit path of the instruction it wraps, and must not double-count.** - A `record_*` / `compute_gas!` sitting on the success arm, or after the inner revm instruction returns, is skipped by stack underflow, OOG, decode failure and inner-call failure; conversely, charge per applied action rather than per candidate, and dedup across every frame shape (top-level, `caller == target` self-transfer, repeated recipients). -- **Ordering: guards before work, enforcement before mutation.** - `inspect_account` / `resize_memory!` / `keccak256` / storage-gas computation belong after the wrapped instruction's own validity checks (salt underflow, EIP-3860 size, EIP-214 static, empty initcode), and a limit must be enforced before the state change it guards — a latched flag surfacing as a `Halt` after `pre_execution` journaled the writes leaves them committed under a failed receipt. -- **Keyless / sandbox child execution must reconcile every effect dimension into the parent and block:** gas, each limit dimension, volatile access, logs and the read set. - A `SandboxOutcome` carrying state but dropping logs, or a tracker allocated fresh instead of merged, is a consensus bug; and a value validated before execution (a gas-limit override) must not be mutated afterwards. -- **The volatile-access / beneficiary-detention boundary must cover every sensitive surface** — a new volatile-derived read or side effect (Oracle SLOAD or hint, SELFDESTRUCT beneficiary, EIP-7702 delegate) has to consult the tracker; resolve the delegate before marking, and check the destructing contract itself, not only the stack target. -- **System calls and system-address transactions:** a mandatory pre-block system call with dynamic cost needs a `block.gas_limit`-derived budget, not revm's fixed default, or a spec flipping it fail-closed rejects blocks persistently; a system-address transaction must validate nonce, chain-id and EIP-3607 against replay, and a commit step re-checking block limits must re-check the nonce too. -- **Hot-path accounting must stay O(1)** in attacker-controlled call depth and authorization count — no frame-stack walk per opcode, no unindexed `Vec` scan per authorization. +- Pre-block helpers (the activation block's predeploy check, pre-block system calls, the registry's due-change read, the L1 block info read) return their state (an `EvmState`, or a `ResultAndState` for a system call) for the block executor to commit on its own, in order; they never call `db.commit(...)`. + An idempotent "no change" path returns an `EvmState` that carries the observed account as a read-only entry; returning nothing drops the account from the stateless witness read set and produces an incomplete proof. + The same applies inside execution: read through the journal with revm's own loads (`load_account`, `sload`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state. +- **The Host only observes; the opcode's wrapper commits.** + `sstore`, `log` and `selfdestruct` stage a record and record nothing; the wrapper commits it after the opcode completed and discards it if the opcode failed. + A record, a charge or a read mark made before the opcode can still fail counts a write that never happened. + Check that every exit path of a wrapped instruction (stack underflow, out of gas, decode failure, a failed inner call) leaves the staged record discarded and nothing counted. +- **A limit is enforced before the write it guards.** + A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop. + Flag a stop that surfaces as a halt, a limit that is checked after the state change it guards, a stopped frame whose writes, logs or counted bytes survive into its caller, and an answer the engine turns into the stop whose journal is not taken back. + The outcome's `limit_exceeded`, not the output bytes, tells a stop from a contract that reverts with the same bytes. +- **Lanes, pools and ledgers stay aligned with frames.** + `frame_init` pushes one lane per frame result revm returns, including a frame answered without running; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`. + A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at. + The three ledgers (regular, state, history) add up to the raw spend, and the block counts `max(regular, floor)` with history taken out first. +- **Gas detention caps a frame inside the frame's own tracker.** + It withholds a part of the frame's regular gas (`Gas::limit_spendable`) that every reader but a regular charge counts, so there is nothing to move or release; a mechanism that caps a frame's gas uses the same part, holds the frame at its start and after every credit, and never releases a creating frame's withheld part before `return_create`. + A read of volatile data is marked where the Host loads the value and committed by the opcode's wrapper once the opcode completed; a new volatile-derived read or side effect (the block environment, the beneficiary's account through any account opcode, the Oracle's storage, an EIP-7702 delegate) has to be marked, and the delegate resolved before marking. + Flag a bound or an economic claim in a comment or the spec that the code does not meet. +- **Keyless deployment is a native creation.** + The `keylessDeploy` call's frame runs no code and makes its actions by hand; check that the creation's outcome returns into the call through `frame_return_result`, that every effect (gas, the data-size lane, volatile access, logs, state) is reconciled in the one frame stack, that the signer's nonce rule holds on success and on failure, and that a value validated before execution (a gas-limit override) is not mutated afterwards. +- **The interceptor dispatch is ordered cheapest-first and fails closed.** + The call-scheme guard, then the address, then the selector, then the method's value policy; only `CALL` and `STATICCALL` reach an interceptor; an unknown selector is not intercepted and falls through to the contract's bytecode; a method that takes no value answers a value-bearing call with its error. +- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits and history gas, priced at the minimum SALT bucket and not detained; a pre-block call with dynamic cost takes a `block.gas_limit`-derived budget; a database error the database calls fatal is an internal error and any other failure refuses the block with the call's own validation error; a system-address transaction validates nonce, chain id and EIP-3607 against replay, and a commit step that re-checks block limits re-checks the sender's nonce and balance too. +- **The stateless witness must hold every read.** + A change that makes block execution read state outside a transaction's journal commits the read as a read-only entry of a pre-block state or exports it, and adds a witness-replay case; nothing may depend on which source (the database, the SALT environment, the oracle service) answered. +- **Hot-path accounting stays O(1)** in attacker-controlled call depth and authorization count — no frame-stack walk per opcode, no unindexed `Vec` scan per authorization. ## Design and architecture @@ -64,12 +75,13 @@ This is the single most important correctness concern in mega-evm. - A test that asserts one of the spec's own byte-price numbers must return early when the process runs at other prices (`runs_at_measurement_prices`). A measurement build fixes other prices through the `satin-price-override` feature, and a test without the guard fails there on a price the developer asked for. Flag a new state-gas assertion that lacks it: the failure only shows in the configuration nobody watches. +- Every other test holds at a byte price of nothing and at any price from one gas per byte up to the grid's dearest point, and the byte-price grid job checks it. + Below one gas per byte the schedule's entries round to nothing one at a time, and past the grid a fixed-size scenario outgrows any transaction below the execution cap; no test is held there. + A gas limit is its regular room on top of what the scenario adds at the prices in effect, read off the schedule and `history_gas`, not a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for. + A case whose scenario is state or history gas — a limit to cross, a bucket to scale, a charge that cannot be paid — returns early where that byte costs nothing (`state_is_free`, `history_is_free` in each test target's `common.rs`), and its other assertions still run. - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. Missing the required explicit hardfork pin can silently bench the wrong fork when a shared bench subject defaults to a different one. - For the paired Criterion-style harness, use an even round count. - Odd defeats A/B alternation there. - Do not apply that even-round rule to the replay ABBA harness. Adjudicate quantitatively. Don't drop a `saturating_sub`/guard "for speed" without a measured, attributable gain. - **Storage-layout parity.** @@ -85,6 +97,12 @@ This is the single most important correctness concern in mega-evm. These checks guard every change to the Satin engine. `lint`, `test`, `no-std` and `require-label` are the required checks on `satin`; the rest inform the review, and the reviewer reads them. +### The op-revm baseline + +- `crates/mega-evm/tests/satin/equivalence.rs` runs ordinary transactions through `MegaEvm` and through op-revm on the same configuration, and holds Satin to op-revm's total plus the history ledger, on op-revm's own state gas, logs and state. +- It runs in the `test` check. +- A change that makes Satin differ from op-revm on purpose updates a case or adds one, so the difference is pinned; a case changed to absorb a difference nobody chose is the defect. + ### Differential harness - The differential harness, which runs JSON scenarios through `MegaEvm` and through stock revm and compares them field by field, is maintained outside this repository. @@ -93,14 +111,48 @@ These checks guard every change to the Satin engine. ### Execution-spec tests -- No check in this repository runs execution-spec tests on `MegaEvm` itself until the state-test tool is ported to Satin. - `.github/workflows/exec-spec.yml` runs the fork's own runner on the execution-spec-test fixtures, at the fork tag `Cargo.lock` pins, and checks the Osaka and Amsterdam executed and skipped counts pinned in the workflow. - It checks the fork `MegaEvm` runs on, not `MegaEvm`, and it is not a required check. -- It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. + It checks the fork `MegaEvm` runs on, not `MegaEvm`. + It runs when `Cargo.toml` or `Cargo.lock` changes (the pin may have moved); a change that moves the pin updates the pinned counts and says why they moved. +- `.github/workflows/exec-spec-satin.yml` runs the same fixture releases through `MegaEvm` with the state-test runner (`crates/mega-state-test`). + Equivalence mode is the gate: Satin's machinery priced as the fixture's fork prices it, where every failure must be explained by a deviation registered in `crates/mega-state-test/src/deviations.rs`, with its reason and the exact entries it explains, each with the hashes Satin produces; every listed entry must fail exactly as listed, and the executed and skipped counts equal the fork runner's pins. + Satin mode reports the same fixtures under Satin's own configuration in the step summary, and does not fail the job. + The gate runs when a pull request changes the engine, the runner, the system contracts, the toolchain or the lock; the workflow's `execution-spec gate on Satin` job runs on every pull request and reports it, passing when the gate passed or had nothing to run. +- The same workflow imports the main release's Osaka blockchain tests through Satin's block executor (`state-test btest`, `crates/mega-state-test/src/blockchain/`), in equivalence mode's configuration: every accepted block's gas used, logs bloom, receipts root and state root are held to its header, every block the fixture expects to be invalid must be refused for an exception it names, and the chain must end at the fixture's last block and post-state. + A block that differs passes only when a deviation the registry already has lists that test and block with exactly the outcome Satin produces — gas used, logs bloom, receipts root and state root — and the chain goes on from Satin's state, so a listed block exempts nothing after it; a block listed as differing only by an earlier block's state must run as on Ethereum otherwise, and a chain that ends on a listed block's state says why its post-state is not compared. + The summary counts the blocks checked against Ethereum apart from those matched to a deviation; the executed tests and the skips of each class are pinned in the workflow. + A skip is decided from the fixture before anything runs, and a class added to the list says what Ethereum's block has that an OP block does not, or which check a node makes before the executor does. + The accounts the runner and a Satin block add — the predeploys, which the runner seeds as Rex6 left them where the fixture's pre-state lacks them, and the fee vaults op-revm credits — are taken out of the state root only when the fixture's pre-state does not hold them and they hold exactly what was put there (`SATIN_ACCOUNTS`); widening that rule is reviewed like a deviation. +- A deviation is a rule Satin keeps on purpose and is reviewed as one: an entry added to explain a failure that is a bug is the defect, and an entry added, removed or given new hashes says which fixtures moved and why. + `crates/mega-state-test/DEVIATIONS.md` is rendered from the registry, and a test keeps the two equal. +- Neither workflow is a required check; `execution-spec gate on Satin` is the job a branch rule would require. + +### Witness replay + +- `crates/mega-evm/tests/block/witness/` executes a block on a recorder of every read and replays the transactions it included twice, on a strict database and environments that serve exactly a witness and refuse everything else: once on the record of every database read, once on the witness a node builds from the states the block committed — the pre-block steps' and the included transactions' returned states — and the engine's exports. + `witness::check_replay` in `crates/mega-state-test` does the same for a fixture's transaction; an entry the engine rejects has no returned state and replays on the record alone. + Its test over the execution-spec fixtures is always ignored by default: it runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set to the fixtures, and setting the variable alone runs nothing. +- The replay on the node's witness is the one that finds a read the witness lacks; the replay on the record of every read shows the block has no input outside its database and environments. + A change that makes block execution read state outside a transaction's journal commits the read as a read-only entry of a pre-block state, or exports it, and adds the case that makes the read. +- The block cases run in the `test` check. + `.github/workflows/exec-spec-satin.yml` runs the fixture replay after the equivalence gate, on the same fixture releases: every Osaka and Amsterdam entry, in equivalence and in Satin mode; an entry that does not replay fails the job, and so `execution-spec gate on Satin`, and so does a run that prints no single well-formed summary, executes nothing or reports a failed entry. + The step summary counts the entries replayed on both witnesses apart from the rejected ones. + +### Byte-price grid + +- `.github/workflows/price-grid.yml` runs the `mega-evm` suite at byte prices other than the constants, through `scripts/price_grid.sh`: a cost per state byte and a cost per history byte per point, each run with `--no-fail-fast`. +- On a pull request it runs five points: both bytes free (0 / 0), both at one gas (1 / 1), the cheapest and the dearest pair under consideration (312.5 / 20 and 5000 / 300), and a point past every candidate (10000 / 1000). + Between them they have failed every test the whole grid failed; 1 / 1 is where a premise that a charge cannot be paid, true only while a byte is dear, breaks. +- Nightly and on dispatch it runs the whole grid: CPSB 0, 1, 312.5, 700, 1530, 2000, 5000 and 10000 by CPHB 0, 1, 20, 50, 88, 100, 200, 300 and 1000, and 0.001 on both. +- It is not a required check. + A failure is a test that assumes a price, a scenario that does not scale with it, or an engine defect; the first two are fixed in the test, the third is not hidden behind a guard. +- Each point reports how many tests a price guard held back (`guarded`, from `note_price_guard`; the tests are listed in the point's `.guards` file beside its log): every point passes the same number of tests, and this column tells a point at which tests returned early from one at which they ran. +- Locally, `scripts/price_grid.sh --pr`, `--full`, or the points named (`scripts/price_grid.sh 312.5/20 5000/300`); each point's log is under `target/price-grid/`. ### Instruction counts (CodSpeed) -- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (the JSON scenarios under `benches/scenarios` through `MegaEvm`, a bench input rather than a conformance suite) and `factory` (EVM construction through `MegaEvmFactory`), all in `crates/mega-evm/benches`. +- The bench set is `transact` (`MegaEvm` next to op-revm's `OpEvm`, from an empty transaction to 64-deep calls and loops of storage writes and logs), `corpus` (the JSON scenarios under `benches/scenarios` through `MegaEvm`, a bench input rather than a conformance suite), `factory` (EVM construction through `MegaEvmFactory`) and `block` (a block through `MegaBlockExecutor`), all in `crates/mega-evm/benches`. +- `block` measures a chain's steady state: a block on a state holding the predeploys as Rex6 left them, under `BlockLimits::default()`; the one-off check of the activation block is not measured. - `codspeed.yml` runs them under instrumentation on every pull request that touches code and on every push to `satin`; the baseline a pull request is compared with is the latest `satin` push. - Read regressions from the CodSpeed report on the pull request (the CodSpeed comment and the `CodSpeed Performance Analysis` check). The regression threshold that fails that check is a setting of the repository's CodSpeed project; it is not recorded in this repository or in the reports CodSpeed posts, so this file does not state a number. @@ -112,7 +164,7 @@ These checks guard every change to the Satin engine. - The `cargo-mutants gate` job mutates the lines a pull request changes and fails on a surviving mutant that no reviewed suppression covers. Reference point, the pull request that brought the Satin skeleton: 115 mutants, 49 caught, 0 survived, 1 suppressed, 65 unviable, in 7m41s on CI and 4m12s on a 15-core laptop with `JOBS=8`. - That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --suppressions mutants/suppressions.toml`. + That population is the diff against `a8f8c7c9`, the last commit of the legacy core, and it is reproduced by `scripts/mutation_test.sh diff a8f8c7c9` followed by `python3 scripts/mutation_gate.py report --results target/mutants/mutants.out --recheck target/mutants/recheck/mutants.out --suppressions mutants/suppressions.toml`. Take the numbers from that pair, not from `cargo mutants` on its own: the driver turns the function-scoped suppressions into `--exclude-re` before generation, and the gate filters the line-scoped ones after the run, so the bare command reports a different population and a different survivor count. - The job is bounded to 330 minutes. Shard a series whose diff lists more than 1,000 mutants (`cargo mutants --list --in-diff --package mega-evm`): at the reference rate that is about an hour, and the rate falls as the test suite grows. @@ -120,7 +172,7 @@ These checks guard every change to the Satin engine. - The gate has a second scope, for its own infrastructure: `.cargo/mutants-infra.toml` and `scripts/mutation_test.sh infra` mutate the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`) against `mega-evm`'s tests. The production scope excludes test helpers as noise, so that code is otherwise never mutated, though the benches and later tests rest on it. The two scopes are disjoint and the production one keeps its exclusions; a suppression may belong to either, and the suppression-hygiene job lists both scopes into its mutant universe. - The `cargo-mutants infrastructure` job runs the scope on a pull request that touches those files, either configuration, the driver or the gate, and nightly; it is bounded to 90 minutes and is not a required check. + The `cargo-mutants infrastructure` job runs the scope nightly and on a pull request that changes `.cargo/mutants-infra.toml`, the scenario runner (`crates/mega-evm/src/test_utils/scenario.rs`), `scripts/mutation_test.sh` or `scripts/mutation_gate.py`; it never reads `.cargo/mutants.toml`, and a change to `mutants/suppressions.toml` alone does not start it on a pull request (the suppression-hygiene job and the nightly run cover that file); it is bounded to 90 minutes and is not a required check. Reference point: 39 mutants, 34 caught, 0 survived, 3 suppressed, 2 unviable, in 5m45s on a 15-core laptop with `JOBS=8`. The three suppressed ones write a `BlockEnv` field that already holds that value by default, so no test can distinguish them; the test that pins those values kills them the moment a revm upgrade moves a default. - The spec-gate operator pack stays in place but finds nothing on Satin: a single-spec engine has no spec gate to mutate, and the suppression-hygiene job accepts the empty plan. @@ -129,17 +181,16 @@ These checks guard every change to the Satin engine. ### Scheduled workflows -- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, weekly benchmark, replay-bench, doc-audit, the weekly execution-spec run) stay inert until `satin` is the default branch. +- GitHub fires a `schedule` trigger only from the default branch's copy of a workflow, so the schedules in `satin`'s copies (nightly mutation, doc-audit, the weekly execution-spec run, the nightly byte-price grid) stay inert until `satin` is the default branch. - Run them on `satin` by hand: `gh workflow run .yml --ref satin` runs `satin`'s copy of the workflow on `satin`'s head, so none of them needs a `ref` input. - - `mutation.yml`: the whole-crate cargo-mutants run, the spec-gate sweep and suppression hygiene. - - `benchmark.yml`: the Satin bench set on `satin`'s head, without a baseline (`-f aa_check=true` measures the noise floor). + - `mutation.yml`: the whole-crate cargo-mutants run and suppression hygiene. - `exec-spec.yml`: the execution-spec fixtures at the pinned fork tag. - `doc-audit.yml`: the documentation audit of `satin`'s docs. - - `replay-bench.yml`: nothing yet; its bench job is disabled on `satin` until the state-test tool is ported. + - `price-grid.yml`: the whole byte-price grid. ## Dev tools and test infrastructure -Applies to `bin/mega-evme`, `bin/mega-t8n`, `crates/mega-state-test`, `crates/state-test`, test utilities and benches — not consensus code, but `mega-state-test` is a published library and tool output feeds fixtures and indexers. Default severity cap `[Minor]`; raise only when the defect reaches that published API or corrupts a downstream fixture. +Applies to `bin/mega-evme`, `crates/mega-state-test`, `crates/state-test`, test utilities and benches — not consensus code, but `mega-state-test` is a published library and tool output feeds fixtures and indexers. Default severity cap `[Minor]`; raise only when the defect reaches that published API or corrupts a downstream fixture. - An input-handling path (fixture, CLI flag, file path, RPC response) must fail with a structured error instead of aborting the process: a panic, unchecked index or overflow on **untrusted** input is the defect, as is `process::exit` from a library path — an idiomatic `unwrap` on a known-good value is not. A batch loop records a per-item rejection rather than aborting and dropping the rest. - A computed output field — state root, receipt field, contract address, log index, provenance — must carry its real value or an explicit error; substituting a zero, `None`, `default()` or a silently clamped bound reports success for a result the tool never computed. Serialized output must be deterministically ordered, and an advertised flag must not be a stub returning `Ok(())`. diff --git a/bench/replay/README.md b/bench/replay/README.md deleted file mode 100644 index 739fbdc90..000000000 --- a/bench/replay/README.md +++ /dev/null @@ -1,132 +0,0 @@ -# Replay corpus & throughput benchmark - -`fixtures/` is a single corpus of characteristic MegaETH workloads, used two ways: - -- **Correctness** — `crates/state-test/tests/replay_corpus.rs` re-executes each - fixture and checks its recorded post-state (state/logs root, gas, status) on - **every PR** (via `cargo test`). A change that alters execution turns this red. -- **Performance** — `run.py` times each fixture and compares a PR against its - merge-base (`.github/workflows/replay-bench.yml`, on demand), so a speed-up or - slow-down on real workloads is visible. This is the real-workload counterpart - to the synthetic Criterion suite (`crates/mega-evm/benches/`). - -Keeping one corpus means a fixture added for either purpose serves both. - -## The unit: a self-contained fixture - -Every case is one **self-contained state-test fixture** (`fixtures/.json`): -it carries its own pre-state, transaction, block environment, and MegaETH -external environment, so it replays in isolation with **no RPC and no archive -node**. The same EEST `TestUnit` shape `mega-evme replay --dump-fixture` -produces: - -```jsonc -{ - "": { - "env": { currentNumber, currentTimestamp, currentBaseFee, … }, - "pre": { "0x…": { balance, code, nonce, storage }, … }, // the prestate - "transaction": { type, sender, to, data, gasLimit, value, … }, - "megaEnv": { bucketCapacities, oracleStorage }, - "post": { "Rex5": [ { hash, logs, megaGasUsed, megaStatus } ] } - } -} -``` - -Because the fixture is self-contained, the source of the workload does not -matter — a real mined transaction (`mega-evme replay --dump-fixture`), a -`debug_traceCall` + `prestateTracer` snapshot, or a hand-crafted case all become -the same kind of JSON. The corpus stores each as a committed fixture and times -it with `state-test --bench`. - -## How it works - -1. **Build the fixture.** For a real transaction, dump it once (offline once - captured, or straight from RPC): - - ```bash - mega-evme replay --rpc --dump-fixture bench/replay/fixtures/.json - ``` - - The dump only writes if the local replay reproduces the on-chain receipt's gas - and status, so the fixture is faithful by construction. For a non-on-chain - workload, produce the same `TestUnit` shape by other means (see below). - -2. **Replay offline.** The driver times each fixture's isolated EVM `transact` - call with `state-test --bench`, reporting `min`/`median`/`mean` and Mgas/s. - -3. **Compare.** With two binaries (base and PR) the driver interleaves them - **ABBA** across several rounds so machine drift cancels, takes each binary's - median, and reports Δ% per case. A case whose PR median is more than the - threshold slower is flagged a regression. - -## Corpus - -`manifest.json` lists the bench cases — each chosen for a distinct workload shape -(system-contract interception, plain compute, log-heavy metering, heavy -multi-call, limit-tracker stress). Every case records `expected_gas`; the driver -fails if a binary runs it with different gas (that would mean different work is -being timed). A case names its `spec` explicitly only when its fixture carries an -empty `post`; otherwise the spec is taken from the fixture's `post` key. - -The correctness test (`replay_corpus.rs`) globs `fixtures/` directly, so every -fixture with a populated `post` is validated. `fixtures/attack_deploy.json` is a -mainnet attack contract deployment (#299) converted from a `prestateTracer` -snapshot — a non-on-chain, 142M-gas limit-tracker stress case; its `post` was -filled offline with `state-test --fill`, so it too is validated and benched. - -## Running locally - -```bash -cargo build --release -p mega-evme -p state-test - -# Measure the current build: -python3 bench/replay/run.py --bin pr=target/release - -# Compare two builds (each --bin is a directory containing mega-evme + state-test, -# or the path to mega-evme with state-test alongside it): -python3 bench/replay/run.py \ - --bin base=/path/to/main/target/release \ - --bin pr=target/release \ - --rounds 7 --threshold-pct 7 --fail-on-regression -``` - -Useful flags: `--runs` / `--warmup`, `--rounds` (ABBA rounds), `--threshold-pct`, -`--json-out` / `--markdown-out`, `--fail-on-regression`. - -## Adding a case - -For a **mined transaction**, dump it (step 1 above) into `fixtures/.json`, -then add a `manifest.json` entry with `"type": "fixture"`, the `fixture` path, -`expected_gas`, `category`, and a `note`. - -For a **non-on-chain workload** (an attack/edge case from a `prestateTracer` -snapshot or a hand-crafted scenario), produce the `TestUnit` JSON directly -(`env` + `pre` + `transaction` + an empty `post: {}`), then fill its `post` so it -is validated too: - -```bash -state-test --fill --bench-spec bench/replay/fixtures/.json -``` - -Add the `manifest.json` entry as above (no `spec` needed once `post` is filled). - -Both kinds end up with a populated `post`, so they are picked up by the per-PR -correctness test automatically — no extra wiring. - -Verify with `python3 bench/replay/run.py --bin pr=target/release` (bench) and -`cargo test -p mega-state-test --test replay_corpus` (correctness). - -> To benchmark a single transaction ad-hoc, dump it -> (`mega-evme replay --dump-fixture /tmp/x.json `) and time it -> (`state-test --bench /tmp/x.json`) — no manifest entry needed. - -## CI - -- **Correctness** runs on every PR: `cargo test` (`build-and-test.yml`) executes - `replay_corpus.rs`, which validates the recorded post-state of every fixture. -- **Performance** runs on demand: `replay-bench.yml` (weekly / manual dispatch / - member `/replay-bench` PR comment) builds the PR and merge-base binaries, - runs the driver, and posts the comparison table (job summary + PR comment). - -Timing on shared runners is noisy for sub-10µs cases; read the larger cases and -the overall trend across the corpus for real signal. diff --git a/bench/replay/fixtures/attack_deploy.json b/bench/replay/fixtures/attack_deploy.json deleted file mode 100644 index 3bf39efc3..000000000 --- a/bench/replay/fixtures/attack_deploy.json +++ /dev/null @@ -1,151 +0,0 @@ -{ - "attack_deploy": { - "_info": null, - "env": { - "currentChainID": "0x10e6", - "currentCoinbase": "0x4200000000000000000000000000000000000011", - "currentDifficulty": "0x0", - "currentGasLimit": "0x2540be400", - "currentNumber": "0xfda7da", - "currentTimestamp": "0x6a0fcfad", - "currentBaseFee": "0xf4240", - "currentRandom": "0x9facac34967efd2bd06396afe5433cc0746ac1893c40f72f472204bbd025fd5a", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x0000000000000000000000000000000000000001": { - "balance": "0xd8750d6ceef", - "code": "0x", - "nonce": "0x0", - "storage": {} - }, - "0x1c6100bfa8e67837ba9d13a7447c853e32728204": { - "balance": "0x0", - "code": "0x", - "nonce": "0x0", - "storage": {} - }, - "0x355ac514807d5118ec8160e7b4bb2a108f7d74da": { - "balance": "0x0", - "code": "0x", - "nonce": "0x0", - "storage": { - "0x0": "0x0", - "0x1": "0x0", - "0x2": "0x0", - "0x3": "0x0", - "0x4": "0x0" - } - }, - "0x4200000000000000000000000000000000000011": { - "balance": "0x161526c2a4454d7a", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x4200000000000000000000000000000000000019": { - "balance": "0x24786b4c6222b4540", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001a": { - "balance": "0x2da889885f77cbf", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001b": { - "balance": "0x0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x578d8871249a0b9956542a60024a30306f747852": { - "balance": "0x0", - "code": "0x608060405234801561000f575f80fd5b50600436106100cb575f3560e01c806370a082311161008857806395d89b411161006357806395d89b41146101a2578063a9059cbb146101aa578063d505accf146101bd578063dd62ed3e146101d2575f80fd5b806370a082311461014c5780637ecebe001461017457806384b0196e14610187575f80fd5b806306fdde03146100cf578063095ea7b3146100ed57806318160ddd1461011057806323b872dd14610122578063313ce567146101355780633644e51514610144575b5f80fd5b6100d761020a565b6040516100e49190610c2c565b60405180910390f35b6101006100fb366004610c60565b61029a565b60405190151581526020016100e4565b6002545b6040519081526020016100e4565b610100610130366004610c88565b6102b3565b604051601281526020016100e4565b6101146102d6565b61011461015a366004610cc1565b6001600160a01b03165f9081526020819052604090205490565b610114610182366004610cc1565b6102e4565b61018f610301565b6040516100e49796959493929190610cda565b6100d7610343565b6101006101b8366004610c60565b610352565b6101d06101cb366004610d71565b61035f565b005b6101146101e0366004610dde565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b60606003805461021990610e0f565b80601f016020809104026020016040519081016040528092919081815260200182805461024590610e0f565b80156102905780601f1061026757610100808354040283529160200191610290565b820191905f5260205f20905b81548152906001019060200180831161027357829003601f168201915b5050505050905090565b5f336102a781858561049a565b60019150505b92915050565b5f336102c08582856104ac565b6102cb858585610528565b506001949350505050565b5f6102df610585565b905090565b6001600160a01b0381165f908152600760205260408120546102ad565b5f6060805f805f60606103126106ae565b61031a6106db565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b60606004805461021990610e0f565b5f336102a7818585610528565b834211156103885760405163313c898160e11b8152600481018590526024015b60405180910390fd5b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886103d38c6001600160a01b03165f90815260076020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f61042d82610708565b90505f61043c82878787610734565b9050896001600160a01b0316816001600160a01b031614610483576040516325c0072360e11b81526001600160a01b0380831660048301528b16602482015260440161037f565b61048e8a8a8a61049a565b50505050505050505050565b6104a78383836001610760565b505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f19811015610522578181101561051457604051637dc7a0d960e11b81526001600160a01b0384166004820152602481018290526044810183905260640161037f565b61052284848484035f610760565b50505050565b6001600160a01b03831661055157604051634b637e8f60e11b81525f600482015260240161037f565b6001600160a01b03821661057a5760405163ec442f0560e01b81525f600482015260240161037f565b6104a7838383610832565b5f306001600160a01b037f000000000000000000000000578d8871249a0b9956542a60024a30306f747852161480156105dd57507f00000000000000000000000000000000000000000000000000000000000010e646145b1561060757507fd1bf0a1ec1283fc6b7484c5b5a5aea13b60c5ddd2dc50014ed7e19f01601d37590565b6102df604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f637597a3c1426ec850b48a1ea08e2596b554a91e4fa8e14e3d777635b0ad0c2a918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60606102df7f546573745365635553440000000000000000000000000000000000000000000a6005610958565b60606102df7f31000000000000000000000000000000000000000000000000000000000000016006610958565b5f6102ad610714610585565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f8061074488888888610a01565b9250925092506107548282610ac9565b50909695505050505050565b6001600160a01b0384166107895760405163e602df0560e01b81525f600482015260240161037f565b6001600160a01b0383166107b257604051634a1406b160e11b81525f600482015260240161037f565b6001600160a01b038085165f908152600160209081526040808320938716835292905220829055801561052257826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161082491815260200190565b60405180910390a350505050565b6001600160a01b03831661085c578060025f8282546108519190610e47565b909155506108cc9050565b6001600160a01b0383165f90815260208190526040902054818110156108ae5760405163391434e360e21b81526001600160a01b0385166004820152602481018290526044810183905260640161037f565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b0382166108e857600280548290039055610906565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161094b91815260200190565b60405180910390a3505050565b606060ff83146109725761096b83610b85565b90506102ad565b81805461097e90610e0f565b80601f01602080910402602001604051908101604052809291908181526020018280546109aa90610e0f565b80156109f55780601f106109cc576101008083540402835291602001916109f5565b820191905f5260205f20905b8154815290600101906020018083116109d857829003601f168201915b505050505090506102ad565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610a3a57505f91506003905082610abf565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610a8b573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116610ab657505f925060019150829050610abf565b92505f91508190505b9450945094915050565b5f826003811115610adc57610adc610e66565b03610ae5575050565b6001826003811115610af957610af9610e66565b03610b175760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610b2b57610b2b610e66565b03610b4c5760405163fce698f760e01b81526004810182905260240161037f565b6003826003811115610b6057610b60610e66565b03610b81576040516335e2f38360e21b81526004810182905260240161037f565b5050565b60605f610b9183610bc2565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f60ff8216601f8111156102ad57604051632cd44ac360e21b815260040160405180910390fd5b5f81518084525f5b81811015610c0d57602081850181015186830182015201610bf1565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f610c3e6020830184610be9565b9392505050565b80356001600160a01b0381168114610c5b575f80fd5b919050565b5f8060408385031215610c71575f80fd5b610c7a83610c45565b946020939093013593505050565b5f805f60608486031215610c9a575f80fd5b610ca384610c45565b9250610cb160208501610c45565b9150604084013590509250925092565b5f60208284031215610cd1575f80fd5b610c3e82610c45565b60ff60f81b881681525f602060e06020840152610cfa60e084018a610be9565b8381036040850152610d0c818a610be9565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825260208088019350909101905f5b81811015610d5f57835183529284019291840191600101610d43565b50909c9b505050505050505050505050565b5f805f805f805f60e0888a031215610d87575f80fd5b610d9088610c45565b9650610d9e60208901610c45565b95506040880135945060608801359350608088013560ff81168114610dc1575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215610def575f80fd5b610df883610c45565b9150610e0660208401610c45565b90509250929050565b600181811c90821680610e2357607f821691505b602082108103610e4157634e487b7160e01b5f52602260045260245ffd5b50919050565b808201808211156102ad57634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f52602160045260245ffdfea26469706673582212200fa3d3d17ba488a0031995f9da2c1e6aec1eecd579a8e846babe56aa7286101564736f6c63430008180033", - "nonce": "0x1", - "storage": { - "0x213b9ef722885121b6bf233baaf1feb2baa4e1c38e5a6bb52c2caba2878310d0": "0x0", - "0x412b2a79ba55ab55c0b244056436f982b53c897ea723181bcc9526d610d16fec": "0x0", - "0x5de41bfeea9b974a4c1153f1bbe02a33fd5b35f2f7fa3395a32f9b8d51611a25": "0x0", - "0x5fca353663f6f9935bf2a9a8fe1d01e70ed429ffb39a1e8e2a5e8c9bee308eb5": "0x0", - "0x9c9b00837f0d78bb3c52145f309fe3a14fa68532cb2c348fca275ba98bf24f12": "0x0", - "0xafd34d6b52de283969cab1deb3a652d8c16a9f10b3260769521e40fbc87cffe2": "0x0", - "0xc66533f103d34d4c87a84143199cf05b541308f878c7ee0224a302a19961e71c": "0x33b2e3c9fd0803ce8000000", - "0xc6c74f62bfa1cb8d48cede291887c0d1cb390939ec5512846ef312ac741eae2a": "0x0", - "0xc80bbbf4eec8fdcb43a21dd2f2ba3ec0060e478e7e2466e4698ba3dd301ee16c": "0x0", - "0xdbc7913112c06ca7601ac55969b95e2c3ace896ce372ddfb11236d7973e35b00": "0x0" - } - }, - "0x632b7da5ea5912330ed23af39d09e457294168ee": { - "balance": "0x0", - "code": "0x", - "nonce": "0x0", - "storage": { - "0x0": "0x0", - "0x1": "0x0", - "0x2": "0x0" - } - }, - "0xd4c1ecfc39ad51ab8ecdd0240a27dadd363b4739": { - "balance": "0x0", - "code": "0x", - "nonce": "0x0", - "storage": { - "0x1": "0x0", - "0x5de41bfeea9b974a4c1153f1bbe02a33fd5b35f2f7fa3395a32f9b8d51611a25": "0x0", - "0xc80bbbf4eec8fdcb43a21dd2f2ba3ec0060e478e7e2466e4698ba3dd301ee16c": "0x0" - } - }, - "0xfb0de6ab3cd3aeee1b3abeb51ee3b98d576e929b": { - "balance": "0x89dbbd283b4d9", - "code": "0x", - "nonce": "0x5", - "storage": {} - } - }, - "post": { - "Rex5": [ - { - "indexes": { - "data": 0, - "gas": 0, - "value": 0 - }, - "hash": "0x88c7f86774c0fdd60dfe6d3fbb89ac3147b9da909726dd37096436695111bd52", - "logs": "0x8520535971d35c7f4b16759e777438a30e53ca1ba223355342ae2bbf642da118", - "megaGasUsed": 141927106, - "megaStatus": "success" - } - ] - }, - "transaction": { - "type": 2, - "data": [ - "0x608060405234801561000f575f5ffd5b5060405161432638038061432683398181016040528101906100319190610723565b5f73ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff160361009f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100969061082e565b60405180910390fd5b600a8710156100e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100da906108bc565b60405180910390fd5b5f600a886100f19190610934565b90505f8990505f828a6101049190610964565b90508a73ffffffffffffffffffffffffffffffffffffffff1663d505accf89307fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8b8b8b8b6040518863ffffffff1660e01b815260040161016b97969594939291906109d3565b5f604051808303815f87803b158015610182575f5ffd5b505af1158015610194573d5f5f3e3d5ffd5b505050508173ffffffffffffffffffffffffffffffffffffffff166323b872dd8930846040518463ffffffff1660e01b81526004016101d593929190610a40565b6020604051808303815f875af11580156101f1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102159190610aaa565b508a60405161022390610602565b61022d9190610ad5565b604051809103905ff080158015610246573d5f5f3e3d5ffd5b505f5f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff1663095ea7b35f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff168c6040518363ffffffff1660e01b81526004016102e0929190610aee565b6020604051808303815f875af11580156102fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103209190610aaa565b505f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663b6b55f258b6040518263ffffffff1660e01b815260040161037a9190610b15565b5f604051808303815f87803b158015610391575f5ffd5b505af11580156103a3573d5f5f3e3d5ffd5b505050508a6040516103b49061060f565b6103be9190610ad5565b604051809103905ff0801580156103d7573d5f5f3e3d5ffd5b5060015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff1663a9059cbb60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16856040518363ffffffff1660e01b8152600401610473929190610aee565b6020604051808303815f875af115801561048f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104b39190610aaa565b505f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff168b6040516104e29061061c565b6104ed929190610b2e565b604051809103905ff080158015610506573d5f5f3e3d5ffd5b5060025f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060025f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166388a8aec660015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16858c6040518463ffffffff1660e01b81526004016105c593929190610b55565b5f604051808303815f87803b1580156105dc575f5ffd5b505af11580156105ee573d5f5f3e3d5ffd5b505050505050505050505050505050610b8a565b610c3c80610ddd83390190565b610d4280611a1983390190565b611bcb8061275b83390190565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6106568261062d565b9050919050565b6106668161064c565b8114610670575f5ffd5b50565b5f815190506106818161065d565b92915050565b5f819050919050565b61069981610687565b81146106a3575f5ffd5b50565b5f815190506106b481610690565b92915050565b5f60ff82169050919050565b6106cf816106ba565b81146106d9575f5ffd5b50565b5f815190506106ea816106c6565b92915050565b5f819050919050565b610702816106f0565b811461070c575f5ffd5b50565b5f8151905061071d816106f9565b92915050565b5f5f5f5f5f5f5f5f610100898b0312156107405761073f610629565b5b5f61074d8b828c01610673565b985050602061075e8b828c016106a6565b975050604061076f8b828c01610673565b96505060606107808b828c01610673565b95505060806107918b828c016106a6565b94505060a06107a28b828c016106dc565b93505060c06107b38b828c0161070f565b92505060e06107c48b828c0161070f565b9150509295985092959890939650565b5f82825260208201905092915050565b7f4578706c6f697453657475703a207a65726f20726563656976657200000000005f82015250565b5f610818601b836107d4565b9150610823826107e4565b602082019050919050565b5f6020820190508181035f8301526108458161080c565b9050919050565b7f4578706c6f697453657475703a2073656564416d6f756e7420746f6f20736d615f8201527f6c6c000000000000000000000000000000000000000000000000000000000000602082015250565b5f6108a66022836107d4565b91506108b18261084c565b604082019050919050565b5f6020820190508181035f8301526108d38161089a565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61093e82610687565b915061094983610687565b925082610959576109586108da565b5b828204905092915050565b5f61096e82610687565b915061097983610687565b925082820190508082111561099157610990610907565b5b92915050565b6109a08161064c565b82525050565b6109af81610687565b82525050565b6109be816106ba565b82525050565b6109cd816106f0565b82525050565b5f60e0820190506109e65f83018a610997565b6109f36020830189610997565b610a0060408301886109a6565b610a0d60608301876109a6565b610a1a60808301866109b5565b610a2760a08301856109c4565b610a3460c08301846109c4565b98975050505050505050565b5f606082019050610a535f830186610997565b610a606020830185610997565b610a6d60408301846109a6565b949350505050565b5f8115159050919050565b610a8981610a75565b8114610a93575f5ffd5b50565b5f81519050610aa481610a80565b92915050565b5f60208284031215610abf57610abe610629565b5b5f610acc84828501610a96565b91505092915050565b5f602082019050610ae85f830184610997565b92915050565b5f604082019050610b015f830185610997565b610b0e60208301846109a6565b9392505050565b5f602082019050610b285f8301846109a6565b92915050565b5f604082019050610b415f830185610997565b610b4e6020830184610997565b9392505050565b5f606082019050610b685f830186610997565b610b7560208301856109a6565b610b826040830184610997565b949350505050565b61024680610b975f395ff3fe608060405234801561000f575f5ffd5b506004361061003f575f3560e01c806348eb76ee14610043578063bcead63e14610061578063fbfa77cf1461007f575b5f5ffd5b61004b61009d565b6040516100589190610185565b60405180910390f35b6100696100c2565b60405161007691906101be565b60405180910390f35b6100876100e7565b60405161009491906101f7565b60405180910390f35b60025f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f819050919050565b5f61014d6101486101438461010b565b61012a565b61010b565b9050919050565b5f61015e82610133565b9050919050565b5f61016f82610154565b9050919050565b61017f81610165565b82525050565b5f6020820190506101985f830184610176565b92915050565b5f6101a882610154565b9050919050565b6101b88161019e565b82525050565b5f6020820190506101d15f8301846101af565b92915050565b5f6101e182610154565b9050919050565b6101f1816101d7565b82525050565b5f60208201905061020a5f8301846101e8565b9291505056fea2646970667358221220ab8ca3bad83057bc6502e4d5e818ec45197087ada5dff4a28bd506a700a0182364736f6c634300081e003360a060405234801561000f575f5ffd5b50604051610c3c380380610c3c833981810160405281019061003191906100c9565b8073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff1681525050506100f4565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100988261006f565b9050919050565b6100a88161008e565b81146100b2575f5ffd5b50565b5f815190506100c38161009f565b92915050565b5f602082840312156100de576100dd61006b565b5b5f6100eb848285016100b5565b91505092915050565b608051610b1b6101215f395f81816101b20152818161039b0152818161044a01526105ba0152610b1b5ff3fe608060405234801561000f575f5ffd5b506004361061005f575f3560e01c8062f714ce1461006357806301e1d1141461007f5780633a98ef391461009d578063b6b55f25146100bb578063ce7c2ac2146100d7578063fc0c546a14610107575b5f5ffd5b61007d600480360381019061007891906106cf565b610125565b005b610087610398565b604051610094919061071c565b60405180910390f35b6100a5610436565b6040516100b2919061071c565b60405180910390f35b6100d560048036038101906100d09190610735565b61043c565b005b6100f160048036038101906100ec9190610760565b6105a4565b6040516100fe919061071c565b60405180910390f35b61010f6105b8565b60405161011c91906107e6565b60405180910390f35b815f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205410156101a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161019b9061087f565b60405180910390fd5b5f6101ae836105dc565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b815260040161020b9291906108ac565b6020604051808303815f875af1158015610227573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061024b9190610908565b505f8273ffffffffffffffffffffffffffffffffffffffff163b11156102d4578173ffffffffffffffffffffffffffffffffffffffff16633531bb2833836040518363ffffffff1660e01b81526004016102a69291906108ac565b5f604051808303815f87803b1580156102bd575f5ffd5b505af11580156102cf573d5f5f3e3d5ffd5b505050505b825f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825403925050819055508260015f82825403925050819055508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167ff341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567838660405161038b929190610933565b60405180910390a3505050565b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016103f2919061095a565b602060405180830381865afa15801561040d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104319190610987565b905090565b60015481565b5f61044682610604565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b81526004016104a5939291906109b2565b6020604051808303815f875af11580156104c1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e59190610908565b50805f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282546105319190610a14565b925050819055508060015f8282546105499190610a14565b925050819055503373ffffffffffffffffffffffffffffffffffffffff167f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a158383604051610598929190610933565b60405180910390a25050565b5f602052805f5260405f205f915090505481565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f6001546105e8610398565b836105f39190610a47565b6105fd9190610ab5565b9050919050565b5f5f6001540361061657819050610639565b61061e610398565b6001548361062c9190610a47565b6106369190610ab5565b90505b919050565b5f5ffd5b5f819050919050565b61065481610642565b811461065e575f5ffd5b50565b5f8135905061066f8161064b565b92915050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61069e82610675565b9050919050565b6106ae81610694565b81146106b8575f5ffd5b50565b5f813590506106c9816106a5565b92915050565b5f5f604083850312156106e5576106e461063e565b5b5f6106f285828601610661565b9250506020610703858286016106bb565b9150509250929050565b61071681610642565b82525050565b5f60208201905061072f5f83018461070d565b92915050565b5f6020828403121561074a5761074961063e565b5b5f61075784828501610661565b91505092915050565b5f602082840312156107755761077461063e565b5b5f610782848285016106bb565b91505092915050565b5f819050919050565b5f6107ae6107a96107a484610675565b61078b565b610675565b9050919050565b5f6107bf82610794565b9050919050565b5f6107d0826107b5565b9050919050565b6107e0816107c6565b82525050565b5f6020820190506107f95f8301846107d7565b92915050565b5f82825260208201905092915050565b7f56756c6e657261626c655661756c743a20696e73756666696369656e742073685f8201527f6172657300000000000000000000000000000000000000000000000000000000602082015250565b5f6108696024836107ff565b91506108748261080f565b604082019050919050565b5f6020820190508181035f8301526108968161085d565b9050919050565b6108a681610694565b82525050565b5f6040820190506108bf5f83018561089d565b6108cc602083018461070d565b9392505050565b5f8115159050919050565b6108e7816108d3565b81146108f1575f5ffd5b50565b5f81519050610902816108de565b92915050565b5f6020828403121561091d5761091c61063e565b5b5f61092a848285016108f4565b91505092915050565b5f6040820190506109465f83018561070d565b610953602083018461070d565b9392505050565b5f60208201905061096d5f83018461089d565b92915050565b5f815190506109818161064b565b92915050565b5f6020828403121561099c5761099b61063e565b5b5f6109a984828501610973565b91505092915050565b5f6060820190506109c55f83018661089d565b6109d2602083018561089d565b6109df604083018461070d565b949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f610a1e82610642565b9150610a2983610642565b9250828201905080821115610a4157610a406109e7565b5b92915050565b5f610a5182610642565b9150610a5c83610642565b9250828202610a6a81610642565b91508282048414831517610a8157610a806109e7565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f610abf82610642565b9150610aca83610642565b925082610ada57610ad9610a88565b5b82820490509291505056fea26469706673582212202a8c0a6b9c40bfa0255196a7ac23db2258484ca87e3a6a9d5a996a2ff8383b1264736f6c634300081e003360a060405234801561000f575f5ffd5b50604051610d42380380610d42833981810160405281019061003191906100c9565b8073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff1681525050506100f4565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100988261006f565b9050919050565b6100a88161008e565b81146100b2575f5ffd5b50565b5f815190506100c38161009f565b92915050565b5f602082840312156100de576100dd61006b565b5b5f6100eb848285016100b5565b91505092915050565b608051610c0d6101355f395f818160c7015281816101a70152818161028101528181610338015281816103f00152818161046e01526105a30152610c0d5ff3fe608060405234801561000f575f5ffd5b506004361061004a575f3560e01c806315770f921461004e5780635296a4311461006c578063bf333f2c14610088578063fc0c546a146100a6575b5f5ffd5b6100566100c4565b60405161006391906105dd565b60405180910390f35b61008660048036038101906100819190610689565b610162565b005b61009061059c565b60405161009d91906105dd565b60405180910390f35b6100ae6105a1565b6040516100bb9190610760565b60405180910390f35b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161011e9190610799565b602060405180830381865afa158015610139573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061015d91906107c6565b905090565b5f83116101a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161019b9061084b565b60405180910390fd5b827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016101fe9190610799565b602060405180830381865afa158015610219573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061023d91906107c6565b101561027e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610275906108d9565b60405180910390fd5b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016102d89190610799565b602060405180830381865afa1580156102f3573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031791906107c6565b90505f612710600a8661032a9190610924565b6103349190610992565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33876040518363ffffffff1660e01b81526004016103919291906109c2565b6020604051808303815f875af11580156103ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103d19190610a1e565b503373ffffffffffffffffffffffffffffffffffffffff1663ee8725587f0000000000000000000000000000000000000000000000000000000000000000878488886040518663ffffffff1660e01b8152600401610433959493929190610aa3565b5f604051808303815f87803b15801561044a575f5ffd5b505af115801561045c573d5f5f3e3d5ffd5b50505050808261046c9190610aef565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016104c59190610799565b602060405180830381865afa1580156104e0573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061050491906107c6565b1015610545576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161053c90610b92565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff167f31aaad38f00845a242d16ae90d7bd72fc68f0e22581470f9dc0de241210c2886868360405161058d929190610bb0565b60405180910390a25050505050565b600a81565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f819050919050565b6105d7816105c5565b82525050565b5f6020820190506105f05f8301846105ce565b92915050565b5f5ffd5b5f5ffd5b610607816105c5565b8114610611575f5ffd5b50565b5f81359050610622816105fe565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f84011261064957610648610628565b5b8235905067ffffffffffffffff8111156106665761066561062c565b5b60208301915083600182028301111561068257610681610630565b5b9250929050565b5f5f5f604084860312156106a05761069f6105f6565b5b5f6106ad86828701610614565b935050602084013567ffffffffffffffff8111156106ce576106cd6105fa565b5b6106da86828701610634565b92509250509250925092565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f819050919050565b5f61072861072361071e846106e6565b610705565b6106e6565b9050919050565b5f6107398261070e565b9050919050565b5f61074a8261072f565b9050919050565b61075a81610740565b82525050565b5f6020820190506107735f830184610751565b92915050565b5f610783826106e6565b9050919050565b61079381610779565b82525050565b5f6020820190506107ac5f83018461078a565b92915050565b5f815190506107c0816105fe565b92915050565b5f602082840312156107db576107da6105f6565b5b5f6107e8848285016107b2565b91505092915050565b5f82825260208201905092915050565b7f466c6173684c6f616e50726f76696465723a207a65726f20616d6f756e7400005f82015250565b5f610835601e836107f1565b915061084082610801565b602082019050919050565b5f6020820190508181035f83015261086281610829565b9050919050565b7f466c6173684c6f616e50726f76696465723a20696e73756666696369656e74205f8201527f6c69717569646974790000000000000000000000000000000000000000000000602082015250565b5f6108c36029836107f1565b91506108ce82610869565b604082019050919050565b5f6020820190508181035f8301526108f0816108b7565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61092e826105c5565b9150610939836105c5565b9250828202610947816105c5565b9150828204841483151761095e5761095d6108f7565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f61099c826105c5565b91506109a7836105c5565b9250826109b7576109b6610965565b5b828204905092915050565b5f6040820190506109d55f83018561078a565b6109e260208301846105ce565b9392505050565b5f8115159050919050565b6109fd816109e9565b8114610a07575f5ffd5b50565b5f81519050610a18816109f4565b92915050565b5f60208284031215610a3357610a326105f6565b5b5f610a4084828501610a0a565b91505092915050565b5f82825260208201905092915050565b828183375f83830152505050565b5f601f19601f8301169050919050565b5f610a828385610a49565b9350610a8f838584610a59565b610a9883610a67565b840190509392505050565b5f608082019050610ab65f83018861078a565b610ac360208301876105ce565b610ad060408301866105ce565b8181036060830152610ae3818486610a77565b90509695505050505050565b5f610af9826105c5565b9150610b04836105c5565b9250828201905080821115610b1c57610b1b6108f7565b5b92915050565b7f466c6173684c6f616e50726f76696465723a2072657061796d656e74206661695f8201527f6c65640000000000000000000000000000000000000000000000000000000000602082015250565b5f610b7c6023836107f1565b9150610b8782610b22565b604082019050919050565b5f6020820190508181035f830152610ba981610b70565b9050919050565b5f604082019050610bc35f8301856105ce565b610bd060208301846105ce565b939250505056fea26469706673582212206691e76a4659ab3c827b6e86570c1be41fc2a147f0025be0326de7283c36b97e64736f6c634300081e003360c060405234801561000f575f5ffd5b50604051611bcb380380611bcb833981810160405281019061003191906100fe565b8173ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff16815250508073ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff1681525050505061013c565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100cd826100a4565b9050919050565b6100dd816100c3565b81146100e7575f5ffd5b50565b5f815190506100f8816100d4565b92915050565b5f5f60408385031215610114576101136100a0565b5b5f610121858286016100ea565b9250506020610132858286016100ea565b9150509250929050565b60805160a0516119e96101e25f395f818161014a015281816102260152818161047001528181610731015281816109f301528181610ac401528181610c5601528181610ef701528181610fd601526110a701525f81816102c601528181610394015281816104ac0152818161052c015281816105b20152818161066f01528181610c9201528181610d1201528181610d9801528181610e55015261108301526119e95ff3fe608060405234801561000f575f5ffd5b506004361061007b575f3560e01c806388a8aec61161005957806388a8aec6146100d3578063ee872558146100ef578063fbfa77cf1461010b578063fc0c546a146101295761007b565b806327a7833f1461007f5780633531bb281461009b57806364dd891a146100b7575b5f5ffd5b6100996004803603810190610094919061112b565b610147565b005b6100b560048036038101906100b09190611189565b6102c4565b005b6100d160048036038101906100cc91906111c7565b61041f565b005b6100ed60048036038101906100e891906111f2565b6107df565b005b610109600480360381019061010491906112a3565b610b64565b005b610113611081565b6040516101209190611382565b60405180910390f35b6101316110a5565b60405161013e91906113bb565b60405180910390f35b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016101a191906113e3565b602060405180830381865afa1580156101bc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101e09190611410565b90505f8111610224576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161021b90611495565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b815260040161027f9291906114c2565b6020604051808303815f875af115801561029b573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102bf919061151e565b505050565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610352576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161034990611593565b60405180910390fd5b60015f9054906101000a900460ff16158061036c57505f81145b61041b576064600254101561041b5760025f81548092919061038d906115de565b91905055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b81526004016103ed929190611625565b5f604051808303815f87803b158015610404575f5ffd5b505af1158015610416573d5f5f3e3d5ffd5b505050505b5050565b60015f9054906101000a900460ff161561046e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161046590611696565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663095ea7b37f0000000000000000000000000000000000000000000000000000000000000000836040518363ffffffff1660e01b81526004016104e99291906114c2565b6020604051808303815f875af1158015610505573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610529919061151e565b507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b6b55f25826040518263ffffffff1660e01b815260040161058391906116b4565b5f604051808303815f87803b15801561059a575f5ffd5b505af11580156105ac573d5f5f3e3d5ffd5b505050507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ce7c2ac2306040518263ffffffff1660e01b815260040161060991906113e3565b602060405180830381865afa158015610624573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106489190611410565b5f819055505f6002819055506001805f6101000a81548160ff0219169083151502179055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b81526004016106c8929190611625565b5f604051808303815f87803b1580156106df575f5ffd5b505af11580156106f1573d5f5f3e3d5ffd5b505050505f60015f6101000a81548160ff0219169083151502179055507f45776e8c4137c2d25b59c6bc4e32fd07c3789be92c2623f548bdcc1c513ffad67f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161078891906113e3565b602060405180830381865afa1580156107a3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107c79190611410565b6040516107d491906116b4565b60405180910390a150565b60015f9054906101000a900460ff161561082e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161082590611696565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361089c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161089390611717565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff160361090a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016109019061177f565b60405180910390fd5b8260035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508273ffffffffffffffffffffffffffffffffffffffff16635296a431836040518263ffffffff1660e01b815260040161098391906117d0565b5f604051808303815f87803b15801561099a575f5ffd5b505af11580156109ac573d5f5f3e3d5ffd5b505050505f60035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610a4a91906113e3565b602060405180830381865afa158015610a65573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a899190611410565b90507f45776e8c4137c2d25b59c6bc4e32fd07c3789be92c2623f548bdcc1c513ffad681604051610aba91906116b4565b60405180910390a17f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b8152600401610b1d9291906114c2565b6020604051808303815f875af1158015610b39573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b5d919061151e565b5050505050565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610bf3576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bea9061186c565b60405180910390fd5b60015f9054906101000a900460ff1615610c42576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c39906118d4565b60405180910390fd5b8284610c4e91906118f2565b6004819055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663095ea7b37f0000000000000000000000000000000000000000000000000000000000000000866040518363ffffffff1660e01b8152600401610ccf9291906114c2565b6020604051808303815f875af1158015610ceb573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0f919061151e565b507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b6b55f25856040518263ffffffff1660e01b8152600401610d6991906116b4565b5f604051808303815f87803b158015610d80575f5ffd5b505af1158015610d92573d5f5f3e3d5ffd5b505050507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ce7c2ac2306040518263ffffffff1660e01b8152600401610def91906113e3565b602060405180830381865afa158015610e0a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e2e9190611410565b5f819055505f6002819055506001805f6101000a81548160ff0219169083151502179055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b8152600401610eae929190611625565b5f604051808303815f87803b158015610ec5575f5ffd5b505af1158015610ed7573d5f5f3e3d5ffd5b505050505f60015f6101000a81548160ff0219169083151502179055505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610f4e91906113e3565b602060405180830381865afa158015610f69573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f8d9190611410565b9050600454811015610fd4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fcb90611995565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb336004546040518363ffffffff1660e01b81526004016110319291906114c2565b6020604051808303815f875af115801561104d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611071919061151e565b505f600481905550505050505050565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6110fa826110d1565b9050919050565b61110a816110f0565b8114611114575f5ffd5b50565b5f8135905061112581611101565b92915050565b5f602082840312156111405761113f6110c9565b5b5f61114d84828501611117565b91505092915050565b5f819050919050565b61116881611156565b8114611172575f5ffd5b50565b5f813590506111838161115f565b92915050565b5f5f6040838503121561119f5761119e6110c9565b5b5f6111ac85828601611117565b92505060206111bd85828601611175565b9150509250929050565b5f602082840312156111dc576111db6110c9565b5b5f6111e984828501611175565b91505092915050565b5f5f5f60608486031215611209576112086110c9565b5b5f61121686828701611117565b935050602061122786828701611175565b925050604061123886828701611117565b9150509250925092565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f84011261126357611262611242565b5b8235905067ffffffffffffffff8111156112805761127f611246565b5b60208301915083600182028301111561129c5761129b61124a565b5b9250929050565b5f5f5f5f5f608086880312156112bc576112bb6110c9565b5b5f6112c988828901611117565b95505060206112da88828901611175565b94505060406112eb88828901611175565b935050606086013567ffffffffffffffff81111561130c5761130b6110cd565b5b6113188882890161124e565b92509250509295509295909350565b5f819050919050565b5f61134a611345611340846110d1565b611327565b6110d1565b9050919050565b5f61135b82611330565b9050919050565b5f61136c82611351565b9050919050565b61137c81611362565b82525050565b5f6020820190506113955f830184611373565b92915050565b5f6113a582611351565b9050919050565b6113b58161139b565b82525050565b5f6020820190506113ce5f8301846113ac565b92915050565b6113dd816110f0565b82525050565b5f6020820190506113f65f8301846113d4565b92915050565b5f8151905061140a8161115f565b92915050565b5f60208284031215611425576114246110c9565b5b5f611432848285016113fc565b91505092915050565b5f82825260208201905092915050565b7f41747461636b65725661756c743a206e6f2070726f66697400000000000000005f82015250565b5f61147f60188361143b565b915061148a8261144b565b602082019050919050565b5f6020820190508181035f8301526114ac81611473565b9050919050565b6114bc81611156565b82525050565b5f6040820190506114d55f8301856113d4565b6114e260208301846114b3565b9392505050565b5f8115159050919050565b6114fd816114e9565b8114611507575f5ffd5b50565b5f81519050611518816114f4565b92915050565b5f60208284031215611533576115326110c9565b5b5f6115408482850161150a565b91505092915050565b7f41747461636b65725661756c743a20756e747275737465642063616c6c6572005f82015250565b5f61157d601f8361143b565b915061158882611549565b602082019050919050565b5f6020820190508181035f8301526115aa81611571565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f6115e882611156565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361161a576116196115b1565b5b600182019050919050565b5f6040820190506116385f8301856114b3565b61164560208301846113d4565b9392505050565b7f616c72656164792061747461636b696e670000000000000000000000000000005f82015250565b5f61168060118361143b565b915061168b8261164c565b602082019050919050565b5f6020820190508181035f8301526116ad81611674565b9050919050565b5f6020820190506116c75f8301846114b3565b92915050565b7f41747461636b65725661756c743a207a65726f2070726f7669646572000000005f82015250565b5f611701601c8361143b565b915061170c826116cd565b602082019050919050565b5f6020820190508181035f83015261172e816116f5565b9050919050565b7f41747461636b65725661756c743a207a65726f207265636569766572000000005f82015250565b5f611769601c8361143b565b915061177482611735565b602082019050919050565b5f6020820190508181035f8301526117968161175d565b9050919050565b5f82825260208201905092915050565b50565b5f6117bb5f8361179d565b91506117c6826117ad565b5f82019050919050565b5f6040820190506117e35f8301846114b3565b81810360208301526117f4816117b0565b905092915050565b7f41747461636b65725661756c743a20756e7472757374656420666c617368206c5f8201527f6f616e2063616c6c657200000000000000000000000000000000000000000000602082015250565b5f611856602a8361143b565b9150611861826117fc565b604082019050919050565b5f6020820190508181035f8301526118838161184a565b9050919050565b7f41747461636b65725661756c743a20616c72656164792061747461636b696e675f82015250565b5f6118be60208361143b565b91506118c98261188a565b602082019050919050565b5f6020820190508181035f8301526118eb816118b2565b9050919050565b5f6118fc82611156565b915061190783611156565b925082820190508082111561191f5761191e6115b1565b5b92915050565b7f41747461636b65725661756c743a20696e73756666696369656e742070726f665f8201527f697420746f20726570617920666c617368206c6f616e00000000000000000000602082015250565b5f61197f60368361143b565b915061198a82611925565b604082019050919050565b5f6020820190508181035f8301526119ac81611973565b905091905056fea2646970667358221220fc1f514f8b97ef8f8315bfe00f89ae09b20c0d1dcb5cae7ddb997ba15b28585364736f6c634300081e0033000000000000000000000000578d8871249a0b9956542a60024a30306f74785200000000000000000000000000000000000000000000152d02c7e14af6800000000000000000000000000000b376fb62b70b26530ec271aadd6fcd046c5ee680000000000000000000000000fb0de6ab3cd3aeee1b3abeb51ee3b98d576e929bffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000001c0fd5bab052786547f33569ce66da6a5c5d53de3e080540a8296c7d2cc49f082c37cbe2d20bc2dcddec5b2794549c4e322f95cd25a30af781c226530b68d2e55d" - ], - "gasLimit": [ - "0x47868c00" - ], - "gasPrice": null, - "nonce": "0x5", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0xfb0de6ab3cd3aeee1b3abeb51ee3b98d576e929b", - "to": "", - "value": [ - "0x0" - ], - "maxFeePerGas": "0x1e8480", - "maxPriorityFeePerGas": "0xf4240", - "initcodes": null, - "accessLists": [ - null - ], - "authorizationList": null, - "blobVersionedHashes": [], - "maxFeePerBlobGas": null - }, - "out": "0x608060405234801561000f575f5ffd5b506004361061003f575f3560e01c806348eb76ee14610043578063bcead63e14610061578063fbfa77cf1461007f575b5f5ffd5b61004b61009d565b6040516100589190610185565b60405180910390f35b6100696100c2565b60405161007691906101be565b60405180910390f35b6100876100e7565b60405161009491906101f7565b60405180910390f35b60025f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f819050919050565b5f61014d6101486101438461010b565b61012a565b61010b565b9050919050565b5f61015e82610133565b9050919050565b5f61016f82610154565b9050919050565b61017f81610165565b82525050565b5f6020820190506101985f830184610176565b92915050565b5f6101a882610154565b9050919050565b6101b88161019e565b82525050565b5f6020820190506101d15f8301846101af565b92915050565b5f6101e182610154565b9050919050565b6101f1816101d7565b82525050565b5f60208201905061020a5f8301846101e8565b9291505056fea2646970667358221220ab8ca3bad83057bc6502e4d5e818ec45197087ada5dff4a28bd506a700a0182364736f6c634300081e0033" - } -} \ No newline at end of file diff --git a/bench/replay/fixtures/large_defi.json b/bench/replay/fixtures/large_defi.json deleted file mode 100644 index 56afae056..000000000 --- a/bench/replay/fixtures/large_defi.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "replay_0xb9fb1e85540f9f63e9bbc2c365cb4ed84ecfb6bf23ad39705ee2947d3d2179d6": { - "_info": null, - "env": { - "currentChainID": "0x10e6", - "currentCoinbase": "0x4200000000000000000000000000000000000011", - "currentDifficulty": "0x0", - "currentGasLimit": "0x2540be400", - "currentNumber": "0x11557ee", - "currentTimestamp": "0x6a277dc1", - "currentBaseFee": "0xf4240", - "currentRandom": "0x257b1f30cba44be7941133b715be042b3e078c096663493d671e6606001cfe73", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x0000000000000000000000000000000000000001": { - "balance": "0xd8750d6ceef", - "code": "0x", - "nonce": "0x0", - "storage": {} - }, - "0x4200000000000000000000000000000000000011": { - "balance": "0x5146dc51c366b4ed", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x4200000000000000000000000000000000000019": { - "balance": "0x3043298c38a2aba00", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001a": { - "balance": "0x38dfb8842bc30b0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001b": { - "balance": "0x0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x57677bdc4f24d5c08ddce87e06670c26a00cac0b": { - "balance": "0x0", - "code": "0x60806040523661001357610011610017565b005b6100115b61001f6101b7565b6001600160a01b0316336001600160a01b0316141561016f5760606001600160e01b031960003516631b2ce7f360e11b8114156100655761005e6101ea565b9150610167565b6001600160e01b0319811663278f794360e11b14156100865761005e610241565b6001600160e01b031981166308f2839760e41b14156100a75761005e610287565b6001600160e01b031981166303e1469160e61b14156100c85761005e6102b8565b6001600160e01b03198116635c60da1b60e01b14156100e95761005e6102f8565b60405162461bcd60e51b815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f78792074617267606482015261195d60f21b608482015260a4015b60405180910390fd5b815160208301f35b61017761030c565b565b606061019e83836040518060600160405280602781526020016108576027913961031c565b9392505050565b90565b6001600160a01b03163b151590565b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b546001600160a01b0316919050565b60606101f4610394565b600061020336600481846106a2565b81019061021091906106e8565b905061022d8160405180602001604052806000815250600061039f565b505060408051602081019091526000815290565b606060008061025336600481846106a2565b8101906102609190610719565b915091506102708282600161039f565b604051806020016040528060008152509250505090565b6060610291610394565b60006102a036600481846106a2565b8101906102ad91906106e8565b905061022d816103cb565b60606102c2610394565b60006102cc6101b7565b604080516001600160a01b03831660208201529192500160405160208183030381529060405291505090565b6060610302610394565b60006102cc610422565b610177610317610422565b610431565b6060600080856001600160a01b0316856040516103399190610807565b600060405180830381855af49150503d8060008114610374576040519150601f19603f3d011682016040523d82523d6000602084013e610379565b606091505b509150915061038a86838387610455565b9695505050505050565b341561017757600080fd5b6103a8836104d3565b6000825111806103b55750805b156103c6576103c48383610179565b505b505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6103f46101b7565b604080516001600160a01b03928316815291841660208301520160405180910390a161041f81610513565b50565b600061042c6105bc565b905090565b3660008037600080366000845af43d6000803e808015610450573d6000f35b3d6000fd5b606083156104c15782516104ba576001600160a01b0385163b6104ba5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161015e565b50816104cb565b6104cb83836105e4565b949350505050565b6104dc8161060e565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b6001600160a01b0381166105785760405162461bcd60e51b815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201526564647265737360d01b606482015260840161015e565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80546001600160a01b0319166001600160a01b039290921691909117905550565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc6101db565b8151156105f45781518083602001fd5b8060405162461bcd60e51b815260040161015e9190610823565b6001600160a01b0381163b61067b5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b606482015260840161015e565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc61059b565b600080858511156106b257600080fd5b838611156106bf57600080fd5b5050820193919092039150565b80356001600160a01b03811681146106e357600080fd5b919050565b6000602082840312156106fa57600080fd5b61019e826106cc565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561072c57600080fd5b610735836106cc565b9150602083013567ffffffffffffffff8082111561075257600080fd5b818501915085601f83011261076657600080fd5b81358181111561077857610778610703565b604051601f8201601f19908116603f011681019083821181831017156107a0576107a0610703565b816040528281528860208487010111156107b957600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b60005b838110156107f65781810151838201526020016107de565b838111156103c45750506000910152565b600082516108198184602087016107db565b9190910192915050565b60208152600082518060208401526108428160408501602087016107db565b601f01601f1916919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122012bb4f564f73959a03513dc74fc3c6e40e8386e6f02c16b78d6db00ce0aa16af64736f6c63430008090033", - "nonce": "0x1", - "storage": { - "0x1a89030203d60e0ad3b81bef15ce871dce0e07aae1860154d717eed1bcdf786": "0x18757dd9200006a277dc0019eaa432e30", - "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc": "0xb9f0bd0733c4aecd175186a09c0e160d28d12397", - "0x36f93d1b992f5727acfd63b56bd8b6e1b802c83abc98ad9ea260c0c56ed63008": "0x2346d600006a277dc0019eaa432e30", - "0x4e83eb67fb6976c1c8c8492885b74090afb5a9ef8837d5c63bdbbb849cdeb451": "0x81755400006a277dc0019eaa432e30", - "0xa91154c2546f3abd80cd80f44e07b7e780e03f0a625896da84d11cf7227c7a7f": "0xdde7244da00006a277dc0019eaa432e30", - "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103": "0xa2b0067002df61df015c11b2cf0be4f34fc41cf8" - } - }, - "0xb9f0bd0733c4aecd175186a09c0e160d28d12397": { - "balance": "0x0", - "code": "0x608060405234801561001057600080fd5b50600436106101825760003560e01c80639037ecae116100d8578063c274583a1161008c578063f90c492411610066578063f90c492414610371578063fb2eeb3b14610378578063fc57d4df1461038b57600080fd5b8063c274583a14610311578063e8689daa14610326578063f50b2efe1461035e57600080fd5b8063b24ebfcc116100bd578063b24ebfcc146102d6578063b7a16251146102e9578063b95ed06f146102fe57600080fd5b80639037ecae146102b0578063971b9c03146102c357600080fd5b806355a547d51161013a5780637de92016116101145780637de9201614610275578063858b033d1461028857806386a8a7221461029057600080fd5b806355a547d51461022c578063612f56bb14610234578063729bfda41461024757600080fd5b806343ba8cad1161016b57806343ba8cad146101e657806344e02982146101f957806348a1371b1461020c57600080fd5b806302b9c828146101875780633ce142f5146101c1575b600080fd5b6101ae610195366004611ceb565b73ffffffffffffffffffffffffffffffffffffffff1690565b6040519081526020015b60405180910390f35b6101d46101cf366004611ceb565b61039e565b60405160ff90911681526020016101b8565b6101ae6101f4366004611d08565b61050c565b6101ae610207366004611d08565b61051f565b61021f61021a366004611dc3565b610532565b6040516101b89190611e62565b6101ae6105d3565b6101ae610242366004611ea6565b61072c565b61025a610255366004611d08565b610746565b604080519384526020840192909252908201526060016101b8565b61021f610283366004611dc3565b6107f9565b6101ae610894565b6102a361029e366004611ec8565b6108e8565b6040516101b89190611f4e565b6101ae6102be366004611d08565b6109f4565b61021f6102d1366004611ec8565b610a08565b6101ae6102e4366004611ec8565b610aa3565b6102fc6102f7366004611ec8565b610aae565b005b6101ae61030c366004611ceb565b610ba3565b610319610bd2565b6040516101b89190611fa7565b610339610334366004611ceb565b610c06565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016101b8565b6102fc61036c366004611d08565b610c77565b60036101d4565b61025a610386366004611d08565b610c83565b6101ae610399366004611ceb565b610cf9565b600073ffffffffffffffffffffffffffffffffffffffff8216738bb8f32df04c8b654987daaed53d6b6091e3b774036103d957506000919050565b73ffffffffffffffffffffffffffffffffffffffff821673deb22f54738d54976c4c0fe5ce6d408e40d884990361041257506001919050565b73ffffffffffffffffffffffffffffffffffffffff82167351ce04be4b3e32572c4ec9135221d0691ba7d2020361044b57506002919050565b73ffffffffffffffffffffffffffffffffffffffff821673dd682daec5a90dd295d14da4b0bec9281017b5be0361048457506003919050565b73ffffffffffffffffffffffffffffffffffffffff8216739c5ae89c4af6aa32ce58588dbaf90d18a855b6de036104bd57506004919050565b6040517fec459bc000000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff831660048201526024015b60405180910390fd5b600061051782610c83565b509392505050565b600061052a82610c83565b949350505050565b6060815167ffffffffffffffff81111561054e5761054e611d21565b604051908082528060200260200182016040528015610577578160200160208202803683370190505b50905060005b82518110156105cd576105a883828151811061059b5761059b612013565b6020026020010151610cf9565b8282815181106105ba576105ba612013565b602090810291909101015260010161057d565b50919050565b6000806105de610d07565b905060006105eb82610e3c565b925061ffff169050600081900361062e576040517f8552ff3c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b8181101561072657600061064484610ea4565b9050600080610654606887612071565b905060006106628236612084565b9050803592508265ffffffffffff166000036106aa576040517f336dc9d000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b876000036106c2578265ffffffffffff169750610703565b878365ffffffffffff1614610703576040517fd9d1f46500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61070d8488612071565b965050505050808061071e90612097565b915050610631565b50505090565b600061073d6402540be400836120cf565b90505b92915050565b60008181527f5e9fb4cb0eb3c2583734d3394f30bb14b241acb9b3a034f7e7ba1a62db4370f160205260408120805465ffffffffffff80821693660100000000000083049091169290917f0100000000000000000000000000000000000000000000000000000000000000900460ff16156107c757806001015491506107f1565b80546c01000000000000000000000000900472ffffffffffffffffffffffffffffffffffffff1691505b509193909250565b6060815167ffffffffffffffff81111561081557610815611d21565b60405190808252806020026020018201604052801561083e578160200160208202803683370190505b50905060005b82518110156105cd5761086f83828151811061086257610862612013565b6020026020010151610ba3565b82828151811061088157610881612013565b6020908102919091010152600101610844565b60006108e37f45544800000000000000000000000000000000000000000000000000000000006102427f455448000000000000000000000000000000000000000000000000000000000061051f565b905090565b6060815167ffffffffffffffff81111561090457610904611d21565b60405190808252806020026020018201604052801561095957816020015b61094660405180606001604052806000815260200160008152602001600081525090565b8152602001906001900390816109225790505b50905060005b82518110156105cd5761098a83828151811061097d5761097d612013565b6020026020010151610746565b84848151811061099c5761099c612013565b60200260200101516000018585815181106109b9576109b9612013565b60200260200101516020018686815181106109d6576109d6612013565b6020908102919091010151604001929092529190525260010161095f565b60006109ff82610c83565b50909392505050565b6060815167ffffffffffffffff811115610a2457610a24611d21565b604051908082528060200260200182016040528015610a4d578160200160208202803683370190505b50905060005b82518110156105cd57610a7e838281518110610a7157610a71612013565b602002602001015161051f565b828281518110610a9057610a90612013565b6020908102919091010152600101610a53565b600061074082610ed8565b600080610aba83610ee3565b91509150610ac781610c77565b65ffffffffffff811115610b0a576040517f48f06f0800000000000000000000000000000000000000000000000000000000815260048101829052602401610503565b65ffffffffffff421115610b4c576040517f5cf61159000000000000000000000000000000000000000000000000000000008152426004820152602401610503565b60005b8351811015610b9d57610b95848281518110610b6d57610b6d612013565b6020026020010151848381518110610b8757610b87612013565b602002602001015184610ef9565b600101610b4f565b50505050565b600073ffffffffffffffffffffffffffffffffffffffff821681610bc68261051f565b905061052a828261072c565b60606040517f608b530700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008173ffffffffffffffffffffffffffffffffffffffff16636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c53573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074091906120e6565b610c8081610fdf565b50565b6000806000610c9184610746565b91945092509050610ca484848484611095565b610cf2576040517f4f319ffe00000000000000000000000000000000000000000000000000000000815260048101859052602481018490526044810183905260648101829052608401610503565b9193909250565b600061074061030c83610c06565b60006602ed57011e00007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe036013581161480610d6f576040517fe7764c9e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60003660291115610dac576040517f5796f78a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd736013560006009610de5600362ffffff8516612071565b610def9190612071565b905036610dfd600283612071565b1115610e35576040517fc30a7bd700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b9392505050565b60008080610e4b602085612071565b905036811115610e87576040517f5796f78a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b3681900335925082610e9a600286612071565b9250925050915091565b6000806000610eb2846110ba565b9092509050604e610ec4826020612071565b610ece90846120cf565b61052a9190612071565b60006107408261110d565b60606000610ef08361124a565b91509150915091565b6000806000610f0786610746565b925092509250610f1682611497565b610f56576040518681527fd2fed36e637cb43fd01b51ddf3b0ca9d9966df112183894d5699cd9a16f85eb5906020015b60405180910390a1505050505050565b838310610f8d576040518681527ff34a55619bad9bd385340bece69770212d10a808ac72a95e6454acf05462ac1b90602001610f46565b84610fc2576040518681527fad6ebdc3909f212583bf7e8a0f31338c8c92f403f2fd37d23014fb3fd34e310290602001610f46565b610fcd86868661153b565b610fd78686611669565b505050505050565b6000610fed6103e883612132565b90508042101561104857603c6110034283612084565b1115611044576040517fb6b0916d00000000000000000000000000000000000000000000000000000000815260048101829052426024820152604401610503565b5050565b60b46110548242612084565b1115611044576040517f0321d0b500000000000000000000000000000000000000000000000000000000815260048101829052426024820152604401610503565b600080821180156110b15750426110af6201a5e085612071565b115b95945050505050565b60008080808060206110cd604188612071565b6110d79190612071565b6110e19036612084565b8035935090506110f2600382612084565b62ffffff9390931696923563ffffffff169550919350505050565b600081516002036111645760028260018151811061112d5761112d612013565b60200260200101518360008151811061114857611148612013565b602002602001015161115a9190612071565b6107409190612132565b815160000361119f576040517f9e198af900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6111a8826116ac565b6000600283516111b89190612132565b9050600283516111c89190612146565b6000036112285760008382815181106111e3576111e3612013565b6020026020010151846001846111f99190612084565b8151811061120957611209612013565b602002602001015161121b9190612071565b905061052a600282612132565b82818151811061123a5761123a612013565b6020026020010151915050919050565b6060600080835167ffffffffffffffff81111561126957611269611d21565b604051908082528060200260200182016040528015611292578160200160208202803683370190505b5090506000845167ffffffffffffffff8111156112b1576112b1611d21565b6040519080825280602002602001820160405280156112da578160200160208202803683370190505b5090506000855167ffffffffffffffff8111156112f9576112f9611d21565b60405190808252806020026020018201604052801561132c57816020015b60608152602001906001900390816113175790505b509050600360005b87518110156113a5578167ffffffffffffffff81111561135657611356611d21565b60405190808252806020026020018201604052801561137f578160200160208202803683370190505b5083828151811061139257611392612013565b6020908102919091010152600101611334565b5060006113b0610d07565b905060006113bd82610e3c565b60405190935061ffff909116915060005b8281101561147e5760006113e58c8a8a8a896116f4565b90955090506000819003611425576040517fdfb25a7900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b89811461146e578960000361143c5780995061146e565b6040517f4cbc474200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50602082016040526001016113ce565b50611489858861199d565b985050505050505050915091565b60003373d603f68957a482b41b5fd0489d00446a36dcbe1e14806114ce5750337374bcb6a2daea27a2dc81c08482d38f4f3919eb8d145b806114ec57503373aabc917301fffe56f8e3710171f85955a5c09320145b8061150a57503373cd6bfda4d95d5c0f3f2882dc221d792392c99714145b8061152857503373c4d1ae5e796e6d7561cdc8335f85e6b57a36e097145b156115335750421190565b506000919050565b60007f5e9fb4cb0eb3c2583734d3394f30bb14b241acb9b3a034f7e7ba1a62db4370f160008581526020918252604090819020815160808101835265ffffffffffff8681168083524290911694820185905272ffffffffffffffffffffffffffffffffffffff8881169483018590528811606090920182905282547fffffffffffffffffffffffffffffffffffffffff00000000000000000000000016176601000000000000909402939093176bffffffffffffffffffffffff166c010000000000000000000000009092027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16919091177f010000000000000000000000000000000000000000000000000000000000000083021781559150801561166257600182018490555b5050505050565b6040805182815260208101849052428183015290517ff36866d965ee70c8632ff558f5cf8d41ee9ca1d0d0bc7700786e57be607473909181900360600190a15050565b8051602082016020820281019150805b82811015610b9d57815b818110156116eb5781518151808210156116e1578084528183525b50506020016116c6565b506020016116bc565b6000806000806000611705866110ba565b909250905060008060608180600d61171e602088612071565b61172890896120cf565b6117329190612071565b9150600061174160688d612071565b61174b9036612084565b905060008361175b60418f612071565b6117659190612071565b61176f9036612084565b905061177b848261178e565b94508360208601209550813592506117d0565b604080518381526020818501810190925260009101838382377fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0019392505050565b8265ffffffffffff169a506117f18660418f6117ec9190612071565b611ac5565b96506117fc8761039e565b60ff16995050505050505050604e866118159190612071565b955060008060005b8481101561198a576020611831858b612071565b61183b9190612071565b98506118478985611c5d565b909350915060005b8d51811015611981578d818151811061186a5761186a612013565b602002602001015184036119795760008c828151811061188c5761188c612013565b602002602001015190506118a581896001901b16151590565b1580156118ce5750600360ff168e83815181106118c4576118c4612013565b6020026020010151105b1561197357838c83815181106118e6576118e6612013565b60200260200101518f848151811061190057611900612013565b60200260200101518151811061191857611918612013565b6020026020010181815250508d828151811061193657611936612013565b60200260200101805180919061194b90612097565b9052506001881b81178d838151811061196657611966612013565b6020026020010181815250505b50611981565b60010161184f565b5060010161181d565b5050508594505050509550959350505050565b60606000835167ffffffffffffffff8111156119bb576119bb611d21565b6040519080825280602002602001820160405280156119e4578160200160208202803683370190505b509050600360005b8551811015611abb5781858281518110611a0857611a08612013565b60200260200101511015611a6e57848181518110611a2857611a28612013565b6020026020010151826040517f2b13aef5000000000000000000000000000000000000000000000000000000008152600401610503929190918252602082015260400190565b6000611a92878381518110611a8557611a85612013565b6020026020010151610aa3565b905080848381518110611aa757611aa7612013565b6020908102919091010152506001016119ec565b5090949350505050565b60003682900380359060208101359060400135831a601b8114801590611aef575060ff8116601c14155b15611b29576040517f666b7cba00000000000000000000000000000000000000000000000000000000815260048101879052602401610503565b7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0821115611b86576040517f666b7cba00000000000000000000000000000000000000000000000000000000815260048101879052602401610503565b60408051600081526020810180835288905260ff831691810191909152606081018490526080810183905260019060a0016020604051602081039080840390855afa158015611bd9573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015194505073ffffffffffffffffffffffffffffffffffffffff8416611c54576040517f666b7cba00000000000000000000000000000000000000000000000000000000815260048101879052602401610503565b50505092915050565b60008080611c6b8536612084565b9050803592506020810135915060218410611cb5576040517fc000fc4200000000000000000000000000000000000000000000000000000000815260048101859052602401610503565b8360200360080282901c9150509250929050565b73ffffffffffffffffffffffffffffffffffffffff81168114610c8057600080fd5b600060208284031215611cfd57600080fd5b8135610e3581611cc9565b600060208284031215611d1a57600080fd5b5035919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016810167ffffffffffffffff81118282101715611d9757611d97611d21565b604052919050565b600067ffffffffffffffff821115611db957611db9611d21565b5060051b60200190565b60006020808385031215611dd657600080fd5b823567ffffffffffffffff811115611ded57600080fd5b8301601f81018513611dfe57600080fd5b8035611e11611e0c82611d9f565b611d50565b81815260059190911b82018301908381019087831115611e3057600080fd5b928401925b82841015611e57578335611e4881611cc9565b82529284019290840190611e35565b979650505050505050565b6020808252825182820181905260009190848201906040850190845b81811015611e9a57835183529284019291840191600101611e7e565b50909695505050505050565b60008060408385031215611eb957600080fd5b50508035926020909101359150565b60006020808385031215611edb57600080fd5b823567ffffffffffffffff811115611ef257600080fd5b8301601f81018513611f0357600080fd5b8035611f11611e0c82611d9f565b81815260059190911b82018301908381019087831115611f3057600080fd5b928401925b82841015611e5757833582529284019290840190611f35565b602080825282518282018190526000919060409081850190868401855b82811015611f9a5781518051855286810151878601528501518585015260609093019290850190600101611f6b565b5091979650505050505050565b600060208083528351808285015260005b81811015611fd457858101830151858201604001528201611fb8565b5060006040828601015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168501019250505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082018082111561074057610740612042565b8181038181111561074057610740612042565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82036120c8576120c8612042565b5060010190565b808202811582820484141761074057610740612042565b6000602082840312156120f857600080fd5b8151610e3581611cc9565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b60008261214157612141612103565b500490565b60008261215557612155612103565b50069056fea26469706673582212200ddba53f4a8694e0f704e87e0bd4c3c63ad35b9ab4ac26f88077e03c856a845864736f6c63430008110033", - "nonce": "0x1", - "storage": {} - }, - "0xd603f68957a482b41b5fd0489d00446a36dcbe1e": { - "balance": "0xfeea3948195156e", - "code": "0x", - "nonce": "0x8237c4", - "storage": {} - } - }, - "post": { - "Rex5": [ - { - "indexes": { - "data": 0, - "gas": 0, - "value": 0 - }, - "hash": "0xf9684260d1dca8c06f299c57ab13efdc835c0970b29fc04e5b33b57d90ffad35", - "logs": "0xc773337abbae20201effe79f9783f8f8ec164ab99e3cf2eda3d4015c88ae885d", - "megaGasUsed": 600700, - "megaStatus": "success" - } - ] - }, - "transaction": { - "type": 2, - "data": [ - "0xb7a1625100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004424e420000000000000000000000000000000000000000000000000000000000534f4c0000000000000000000000000000000000000000000000000000000000444f47450000000000000000000000000000000000000000000000000000000077695452595f46554e44414d454e54414c2f5553446d00000000000000000000424e4200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dde82fd02019eaa433218000000200000010e2897f312dd6cd8500d7dd6424470d172e8d98d4d57ec24642e4d3742068dfa361f8db12a6484bccb6e03685598959992f9a573593dc215f234dbdc179b6f551b424e4200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dde82fd02019eaa4332180000002000000104d4fdb683fa9c5c0d2c5bb15d4773808b5664f5398ebb31944995c916a9e4f71261a525ee036da1876463d852ba6efbe158f3f535117de91eb3c1bb8ac9130a1b424e4200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000dde82fd02019eaa43321800000020000001588ab60ceb947407b4ed9166fb7e91f7055528f75e65b725641538e10e85daae466aedc593277737a4e26c8667a598033b8f89a397899d2e0fcfc8dc9d6d21c61c534f4c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018758de2c019eaa433218000000200000015fdfa8a15531bfccebe181c224f03564fc9abb9198b8147484152e7af76808ce76be10da7a3ffc396140033947175d04386f65925f3bee35a6a14adbb8e51bdd1b534f4c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018758de2c019eaa4332180000002000000173252dd9b037bfb4947d3a4a4f19803968cafde8866191a1d16508743fd5f55e78a9a57a65b18c74aefaad83385f52bf5c379a737e44f6ba01a96fff137bece01b534f4c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018758de2c019eaa433218000000200000013335283f98d1c3589d734609ad12ee9b76413f510b2f54732f033736213e55ec24bcd0cb0909fb2a53e39abaa6e0addb36237f1eacf7cd17a7facac944668d8e1b444f4745000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000816fc4019eaa43321800000020000001fb667f499cb28ec8f8c30cdd3ce1a70ad6519fc0b2640181fc4a9d54b5bfaca4251b6116dd691d199268d07ab4a29d5f3f5b90515c324f1f908e8e2380561a0e1c444f4745000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000816fc4019eaa43321800000020000001d8cbd0b12c558c69a4db551864ead4d5ef829a73d62335631e9c55c68a43e9af59af626ee360d32f8ea017d18d6013fdcee3ffbccea4e6ed503f132ad5ccca721c444f4745000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000816fc4019eaa4332180000002000000156b879cf37fafa2b5556a09b4a7ba273673d7087957471262c0bbd9131ffa8e02f9ab15d5bca5bb0cf8c6e7d7c6ba1b0cdd50fffdfa303862bceadccba4295c41c77695452595f46554e44414d454e54414c2f5553446d0000000000000000000000000000000000000000000000000000000000000000000000000000002344af019eaa43321800000020000001316a37dd18cb6f0989c54e483136ea82262661c601a2b939e9f6bec9836ba4e6495ffb631cce39617148f5c829b0c3149aad394de25adc837955a527502664d91b77695452595f46554e44414d454e54414c2f5553446d0000000000000000000000000000000000000000000000000000000000000000000000000000002344d4019eaa43321800000020000001c2ddb44ff26d7cf9586cafa5e3a487b8e7ba188831ba97a02546b97cd93b438436073866c34bae046b4102fd00354ee5d0beeeca6495e945da89a3373c3209291b77695452595f46554e44414d454e54414c2f5553446d000000000000000000000000000000000000000000000000000000000000000000000000000000234481019eaa43321800000020000001f3a35db9822028805b270de96027fe3f3b7fcb26ec7e50b8a1ea446d3faff37639167ab776b03f1f92ef2028bd8be07910fc090383f21e5ad14c67df114514371c000c3137383039373239393137373323302e392e3023646174612d7061636b616765732d77726170706572000029000002ed57011e0000" - ], - "gasLimit": [ - "0x2625a0" - ], - "gasPrice": null, - "nonce": "0x8237c4", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0xd603f68957a482b41b5fd0489d00446a36dcbe1e", - "to": "0x57677bdc4f24d5c08ddce87e06670c26a00cac0b", - "value": [ - "0x0" - ], - "maxFeePerGas": "0x124f80", - "maxPriorityFeePerGas": "0x30d40", - "initcodes": null, - "accessLists": [ - [] - ], - "authorizationList": null, - "blobVersionedHashes": [], - "maxFeePerBlobGas": null - }, - "out": "0x", - "megaEnv": { - "bucketCapacities": [], - "oracleStorage": [] - } - } -} \ No newline at end of file diff --git a/bench/replay/fixtures/log_heavy.json b/bench/replay/fixtures/log_heavy.json deleted file mode 100644 index 28ab12c77..000000000 --- a/bench/replay/fixtures/log_heavy.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "replay_0x25db2df776d9192861893742b32bd5621a0a50ae911134dd862cad6fb11ebb76": { - "_info": null, - "env": { - "currentChainID": "0x10e6", - "currentCoinbase": "0x4200000000000000000000000000000000000011", - "currentDifficulty": "0x0", - "currentGasLimit": "0x2540be400", - "currentNumber": "0x1155801", - "currentTimestamp": "0x6a277dd4", - "currentBaseFee": "0xf4240", - "currentRandom": "0x257b1f30cba44be7941133b715be042b3e078c096663493d671e6606001cfe73", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x3416869d6f3de7d2ae20660d8041670592877c79": { - "balance": "0x3b774e0cb8e2a43", - "code": "0x", - "nonce": "0x6c451b", - "storage": {} - }, - "0x4200000000000000000000000000000000000011": { - "balance": "0x5147095e47043783", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x4200000000000000000000000000000000000019": { - "balance": "0x30433220460642740", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001a": { - "balance": "0x38dfbb41ba696ac", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001b": { - "balance": "0x0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x5e3ae52eba0f9740364bd5dd39738e1336086a8b": { - "balance": "0x0", - "code": "0x60806040526004361015610054575b34610050575f8073ffffffffffffffffffffffffffffffffffffffff680400000000000000005416368280378136915af43d5f803e1561004c573d5ff35b3d5ffd5b5f80fd5b5f3560e01c63661b33080361000e57346100505760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100505760043573ffffffffffffffffffffffffffffffffffffffff811681036100505760243573ffffffffffffffffffffffffffffffffffffffff81168103610050576044359173ffffffffffffffffffffffffffffffffffffffff831683036100505773ffffffffffffffffffffffffffffffffffffffff5f5416330361013457680400000000000000005568010000000000000000556802000000000000000055005b7f10c95c62000000000000000000000000000000000000000000000000000000005f5260045ffd", - "nonce": "0x1", - "storage": { - "0x10000000000000014": "0x10a12120414fafddbb3fc7688494971a79cc65dca3ef82079e7", - "0x40000000000000000": "0x7494c1319d44ac2e74964d02568a7ac32d921340", - "0x40000000000000014": "0x140a000000040a1212070a4200000000000000000000000000000000000006", - "0x5e00000001000000000000001e": "0x1ff2043ea60000000000000000000000000002cf0b88bca55f7b24c000", - "0x3416869d6f3de7d2ae20660d8041670592877c79000040000000005e": "0x202", - "0xf12fe484ab504276a454e750f54a9b7fbe5b06870000000000000028": "0x16000000000000a41000000000000186a00b0e03003200640000000400000001" - } - }, - "0x7494c1319d44ac2e74964d02568a7ac32d921340": { - "balance": "0x0", - "code": "0x60e0806040526004361015610040575b503461003c575f3560e81c62ffffff036100355760025b60401b545f1960601c1661301d565b6001610026565b5f80fd5b5f905f3560e01c90816304bedf6a14611fd15750806311f3d2be14611f4357806312e9955b14611f165780631445936d14611ec157806324313ed614611e7b5780632b956ff714611e585780632ed6673014611e185780633388022214611d535780633701143c14611d13578063407a2ed214611c445780634182834e1461209357806342afb01314611c0a578063434aee6314611b9557806348a430951461197e5780635175cbc6146118fa57806354686b11146118415780635504ce961461180757806359c250ca146117a25780635c5184c51461172d57806364ee5a0c146116795780636548b40d146120e55780636a79d2a7146114ae5780636ac6eb60146114875780636da4606d14611456578063707789c5146113cf57806371686efb14611390578063721983e11461135f578063761966b7146113175780637cb11549146112f35780638639d47a14611235578063939eb7c2146111f05780639598c7b11461118c57806398d75f28146111375780639940a9f9146110fd5780639b433f371461106f5780639db3d68a146110525780639dca362f14611030578063a066fae914611011578063a461592d14610f62578063a542e39514610f35578063af36d34014610de2578063b1cfd47f14610d10578063bd1f4b52146120e5578063bf9e851814610c7b578063c7e9c1a914610c3d578063d3dbedc414610b32578063d712cb7714610a83578063d803a4cf146107a0578063db2b954014610637578063e5b72e2e146105d9578063efcb2ea414610584578063efd8ded214610565578063f16572621461053a578063f39439471461050e578063f42dcf0a14612093578063f6782dcb146104a95763f72c85eb0361000f57346104a65761042b6020916102cf3661207d565b91906102da336126b0565b8160401c5f1960c01c908116929081169061032361031d8460601c60ff16870b6103058188876130a5565b946103175f1960c01c8b16809961216f565b906130a5565b8361216f565b925f1960c01c84161561049d575b8160801c5f1960d41c169261036b9061035387848d1c63ffffffff16876130e0565b856103658661ffff8660501c1661481a565b91613166565b958160781c5f1960c01c168015158061048e575b610486575b508760401c5f1960d41c16926103a390600160ed1b1615158484613112565b975f1960c01c620186a06103b78b8a61219b565b04169889159081610478575b5061046f575b606c1c5f1960c01c16906103dd89836121cc565b8360b81c5f1960c01c169150811515908161045f575b50610433575b50508361216f8789809661041396610419998b85986131d1565b9261216f565b9160401b9160801b9060c01b17171790565b604051908152f35b8598508780938896610413966104506104199a9661216f9661216f565b9c9950965096509350506103f9565b5f1960c01c16821090505f6103f3565b600198506103c9565b61ffff91501615155f6103c3565b96505f610384565b505f1960c01c8816811061037f565b60019350610331565b80fd5b50346104a65760403660031901126104a6576104c361201e565b600b600160401b01545f1960601c1633036104ff5760401b600b811754156104f057603360243591175580f35b63044145c360e01b8252600482fd5b636f72244560e11b8252600482fd5b50346104a65760403660031901126104a657610528611ff8565b50600160411b545f1960601c1661301d565b50346104a65760203660031901126104a65760206015610558611ff8565b60401b1754604051908152f35b50346104a65760203660031901126104a657602061042b612f6361206a565b50346104a65760603660031901126104a65761059e61201e565b906105a7612057565b6105af612044565b9060283360401b1754156105ca576105c792936130e0565b80f35b6302a3661160e61b8352600483fd5b50346104a65760206105ea3661207d565b61061f816105f7336126b0565b936106038282876127ac565b61060e828287612901565b610619828287612e44565b94612d83565b9160401b905f1960c01c1660801b1717604051908152f35b50346104a65760603660031901126104a65761065161201e565b610659612057565b610661612044565b9060283360401b175415610791575f1960c01c8216156107825761068483613264565b6014600160401b01549092909161069a90612f63565b5f1960801c8416935f1960c01c6106b1868661329b565b1662080003602d1b8717546103e860ff8760e81c169161ffff60ff8960f01c1681600a6106ec8960c01c9a6106e68d8d6140ea565b906132c9565b9602160116905f1960c01c16020401908181106107735703905f1960c01c9060801c169384821061074b575b876105c788610732898961072c8a8a6140ea565b91614dd1565b9060201b5f1960c01c60201b1660011760401b601e1755565b849160ff600a9260a01c16020410610764575f80610718565b6351940b3960e11b8652600486fd5b6351940b3960e11b8952600489fd5b636b230dbd60e11b8452600484fd5b6302a3661160e61b8452600484fd5b50346104a65760403660031901126104a6576107ba61201e565b602435905f1960c01c8211610a7f5736602383011215610a7f576004820135905f1960c01c8211610a7b576024830192602436918460051b010111610a7b575f1960d41c169161080983612684565b839084925b8381811015610a635760016108248284866140ae565b35910194603f821680155f146109265750506102006103ff8260061c16145f146108a1578060701c5f1960c01c1690868214801561088f575b156108805761080e918160101c63ffffffff169160301c5f1960c01c169061377a565b63d07a9d6b60e01b8852600488fd5b508060301c5f1960c01c16871461085d565b90926040519163645dd7dd60e01b835286600484015260248301526020826044818a305af191821561091b5787926108eb575b5081156108e3575b509161080e565b90505f6108dc565b61090d91925060203d8111610914575b61090581836120fe565b8101906140d2565b905f6108d4565b503d6108fb565b6040513d89823e3d90fd5b92959490928260101c5f1960601c16906021906109438184612f49565b5003610a08576109949260209161095b888a896140ae565b60405163934bd5f560e01b81525f1960c01c8c1660048201526024810193909352356044830152909384919082908c9082906064820190565b03925af19182156109fd5788926109dd575b5081156109d5575b50925b5f19146109c1576002019261080e565b634e487b7160e01b86526011600452602486fd5b90505f6109ae565b6109f691925060203d81116109145761090581836120fe565b905f6109a6565b6040513d8a823e3d90fd5b610a1a9260209161095b888a896140ae565b03925af19182156109fd578892610a43575b508115610a3b575b50926109b1565b90505f610a34565b610a5c91925060203d81116109145761090581836120fe565b905f610a2c565b868685610a6e575080f35b610a7790613ae0565b5080f35b8380fd5b8280fd5b50346104a65760603660031901126104a657610a9d61201e565b90610aa6612057565b91610aaf612044565b9260283360401b1754156105ca575f1960c01c841615610b2357610ad4848284613f8d565b15610b1457610b0e6105c79394610afe610aee848661327d565b918260801c5f1960c01c166140ea565b8160c01c915f1960801c16614dd1565b91614091565b6351940b3960e11b8352600483fd5b636b230dbd60e11b8352600483fd5b50346104a65760403660031901126104a657610b4c61206a565b90602435918260010b809303610c2a5781545f1960601c163303610c2e5763ffffffff1691603c631fffffff610b8061483f565b60031c160460401b63ffffffff60401b1683176003602c1b1754610c2a57603c631fffffff610bad61483f565b60031c16049180805b63ffffffff831690600b821015610be257610bd963ffffffff9286600193614da3565b93011691610bb6565b8560401b63ffffffff60401b1687176003602c1b17555084610c16603c631fffffff610c0c61483f565b60031c160461266c565b60e01b906610000000000003602c1b175580f35b5080fd5b630864ae3160e11b8252600482fd5b50346104a65760603660031901126104a6576020610c6d610c5c612031565b610c64612044565b90600435612478565b604051905f1960c01c168152f35b50346104a65760403660031901126104a65780610c96611ff8565b60243590610cac8260401c5f1960d41c16612684565b610cb581612f0c565b505f1960601c1690813b15610d0c578291602483926040519485938492635eceb66b60e11b845260048401525af18015610d0157610cf05750f35b81610cfa916120fe565b6104a65780f35b6040513d84823e3d90fd5b5050fd5b50346104a65760403660031901126104a657610d2a611ff8565b815460243591905f1960601c163303610dd357610d46826126ff565b8160401b6028178054915f1960081c16600b60f91b1791610dc5575f1960601c8316604083811b5f1960c01c60401b16602b1791909155919055517fc854ea664d2f1b7408d7c8bd5ef6d0327c7f5fbd894fde7c5389e7de318942f09290918291610dbf9163ffffffff8281169260201c169084612448565b0390a180f35b6206d96360ea1b8552600485fd5b630864ae3160e11b8352600483fd5b50346104a65760803660031901126104a657610dfc611ff8565b610e046120b5565b610e0c6120c5565b610e146120d5565b84549093905f1960601c163303610f26575f1960601c16928315610f175760ff82169260ff811692848410610f085760405163313ce56760e01b8152926020846004818a5afa9384156109fd578894610ed7575b5060ff84168511610ec85760a01b86179060a81b179060b01b179060b81b17608560c11b176014600160401b01556040805193845260016020850152830152606082015260805f516020615efe5f395f51905f5291a16105c7600161330d565b63292f3b9560e21b8852600488fd5b610efa91945060203d602011610f01575b610ef281836120fe565b81019061303a565b925f610e68565b503d610ee8565b638075cdef60e01b8752600487fd5b6334cd134f60e11b8552600485fd5b630864ae3160e11b8552600485fd5b50346104a65760403660031901126104a657602061042b610f5461201e565b610f5c612057565b9061327d565b50346104a65760403660031901126104a657610f7c611ff8565b815460243591905f1960601c163303610dd357610f98826126ff565b8160401b6028178054915f1960081c16600b60f81b1791610dc5575f1960601c8316604083811b5f1960c01c60401b1660291791909155919055517fe9dbd65c63f1ed3a2799aa728daddc4c0ae216d96b694b8b044fd470b3808c8e9290918291610dbf9163ffffffff8281169260201c169084612448565b50346104a65760203660031901126104a6576020610c6d6138a861206a565b50346104a657806003193601126104a657600160411b545f1960601c1661301d565b50346104a65760203660031901126104a6576105c761383561206a565b50346104a65760403660031901126104a657611089611ff8565b90602435801515809103610c2a5781545f1960601c163303610c2e5760288360401b1754156110ee5781925f1960601c1690813b15610d0c57829160248392604051948593849263795e38bb60e01b845260048401525af18015610d0157610cf05750f35b6302a3661160e61b8252600482fd5b50346104a65760403660031901126104a65780611118611ff8565b6024359061112e8260401c5f1960d41c16612684565b610cb581612f32565b50346104a65760403660031901126104a65760409061115461201e565b63ffffffff611161612057565b61116b818461381d565b935016600160201b17906005602c1b91841b17175482519182526020820152f35b50346104a65760603660031901126104a6576111a661201e565b6111ae612031565b6044359063ffffffff82168203610a7b576105c7925f1960d41c91821691166111e3813360401b176001602e1b175460ff1690565b61377a5761377a82612684565b50346104a65760403660031901126104a65761120a612031565b9060283360401b175415611226576020610c6d83600435612356565b6302a3661160e61b8152600490fd5b50346104a65760403660031901126104a65761124f611ff8565b602480358060501c5f1960d41c1692849260209261126c86612684565b611275836126b0565b5060405163face848160e01b815260048101919091529384928391905f1960601c165af19081156112e85783916112b6575b505f1960c01c16610a6e575080f35b90506020813d6020116112e0575b816112d1602093836120fe565b81010312610a7f57515f6112a7565b3d91506112c4565b6040513d85823e3d90fd5b50346104a657806003193601126104a657602063ffffffff60145416604051908152f35b50346104a65760403660031901126104a657606090611337610f5461201e565b604080515f1960801c831681528260801c5f1960c01c1660208201529160c01c908201529050f35b50346104a65760203660031901126104a65761137961206a565b81545f1960601c163303610c2e576105c79061330d565b50346104a65760603660031901126104a6576113aa61206a565b81545f1960601c163303610c2e576024359060401b63ffffffff60401b166017175580f35b50346104a65760203660031901126104a6576113e9611ff8565b81545f1960601c163303610c2e57600b600160401b015460019190839080611433575b50508060401b9082600a8317555f1960601c16600b8360401b015565400000000001175580f35b60401b5f1960601c60401b16654000000000018117829055600a1755825f61140c565b50346104a65760203660031901126104a65760205f1960601c600b61147961201e565b60401b175416604051908152f35b50346104a65760403660031901126104a6576020610c6d6114a6612031565b6004356121e2565b50346104a65761042b6020916114c33661207d565b6114cc336126b0565b915f1960c01c808216918060401c909116906115138560601c60ff16870b61150d6114f88286886130a5565b5f1960c01c881696909290610317888861216f565b9061216f565b918160801c5f1960d41c1690611546906115348563ffffffff8a16856130e0565b856103658461ffff8b60501c1661481a565b955f1960c01c8160b81c16978815158061166a575b61165f575b9697509495939487948760401c5f1960d41c169361158790600160ed1b1615158584613112565b975f1960c01c620186a061159b8b8961219b565b04169889159081611651575b5080611642575b611639575b606c1c5f1960c01c16906115c789836121cc565b8360781c5f1960c01c1691508115159081611629575b506115fd575b50509261216f8786610413958295858b6104199b9a6131d1565b859850918661041395899561161a61216f956104199b9a9761216f565b9b5095509550509194956115e3565b5f1960c01c16821090505f6115dd565b600198506115b3565b505f1960c01c861615156115ae565b61ffff91501615155f6115a7565b909796508790611560565b505f1960c01c8816891061155b565b50346104a65760403660031901126104a657611693611ff8565b602480358060501c5f1960d41c169284926020926116b086612684565b6116b9836126b0565b5060405163cfb2314360e01b815260048101919091529384928391905f1960601c165af19081156112e85783916116fa575b50600180911614610a6e575080f35b90506020813d602011611725575b81611715602093836120fe565b81010312610a7f575160016116eb565b3d9150611708565b50346104a65760403660031901126104a65780611748611ff8565b6024359061175e8260401c5f1960d41c16612684565b61176781612f32565b505f1960601c1690813b15610d0c578291602483926040519485938492633de8737360e11b845260048401525af18015610d0157610cf05750f35b50346104a65760403660031901126104a6576117bc611ff8565b81545f1960601c163303610c2e578060401b90602882175480151590816117f9575b50156105ca576117f3602c9160243590612fa2565b91175580f35b6021915060f81c145f6117de565b50346104a65760403660031901126104a65761182161201e565b611829612031565b9060283360401b1754156105ca57906105c791613053565b50346104a65760403660031901126104a65761185b611ff8565b602480358060801c5f1960d41c1692849260209261187886612684565b61188183612f32565b5060405163291508e760e11b815260048101919091529384928391905f1960601c165af19081156112e85783916118c7575b50600190811603610a7757610a7790613ae0565b90506020813d6020116118f2575b816118e2602093836120fe565b8101031261003c575160016118b3565b3d91506118d5565b50346104a65760403660031901126104a657611914611ff8565b602480358060801c5f1960d41c1692849260209261193186612684565b61193a83612f0c565b506040516244758d60e71b815260048101919091529384928391905f1960601c165af19081156112e85783916118c75750600190811603610a7757610a7790613ae0565b50346104a65760e03660031901126104a657611998611ff8565b6119a06120b5565b916119a96120c5565b6119b16120d5565b916084359260ff84168403610c2a5760a4359260ff84168403610a7f5760c435948515158603610a7b5783545f1960601c163303611b8657601360ff6119f7848b612131565b1611611b77576014545f1960801c908116600101939063ffffffff90851681811015611b68576014558416975f1960601c16988915611b595760ff84169660ff821696888810611b4a57906004929160208d6040519586809263313ce56760e01b82525afa938415611b3d578194611b1c575b5060ff84168911611b0d57509360209b96936014935f516020615efe5f395f51905f529a979360809a9760f01b94600560c11b9460e81b9363ffffffff60c81b8960c81b169360b81b9260b01b9160a81b9060a01b8c17171717171717179163ffffffff60401b9063ffffffff60401b9060401b16161755604051928352868884015260408301526060820152a1611b0457604051908152f35b61042b8161330d565b63292f3b9560e21b8152600490fd5b611b3691945060203d602011610f0157610ef281836120fe565b925f611a6a565b50604051903d90823e3d90fd5b638075cdef60e01b8152600490fd5b6334cd134f60e11b8652600486fd5b633a4733d960e11b8752600487fd5b63292f3b9560e21b8452600484fd5b630864ae3160e11b8452600484fd5b50346104a65760403660031901126104a65780611bb0611ff8565b60243590611bc68260501c5f1960d41c16612684565b611bcf816126b0565b505f1960601c1690813b15610d0c578291602483926040519485938492632c77e6cf60e21b845260048401525af18015610d0157610cf05750f35b50346104a65760403660031901126104a65780611c25611ff8565b60243590611c3b8260401c5f1960d41c16612684565b61176781612f0c565b50346104a65760403660031901126104a657611c5e611ff8565b90611c67612031565b81545f1960601c163303610c2e578260401b9060288217549182156107915783945f1960601c169260218160f81c14611cd7575b5050813b15610d0c57604051630bfa806b60e41b8152905f1960c01c16600482015290829060248391829084905af18015610d0157610cf05750f35b604090811b63ffffffff60401b16602a1754901b5f1960601c60401b16602c908117545f1960c01c60301b19168360301b179117555f80611c9b565b50346104a65760403660031901126104a657611d2d611ff8565b602480358060801c5f1960d41c16928492602092611d4a86612684565b61193a83612f32565b50346104a65760603660031901126104a657611d6d611ff8565b611d75612057565b82545f1960601c163303610dd357611d8c81612f63565b15611e09578160401b9160288317928354610dc5576040927f52c318d3336758ca179bca5d70988951f7c34ae7185387f8b2ddbc4f61d33b629492602c63ffffffff93611ddb60443584612fa2565b925f1960601c169586602a878a1b878b1b16175584602160f81b17905517558351928352166020820152a180f35b634a58fdfd60e11b8352600483fd5b50346104a65760403660031901126104a657611e32611ff8565b602480358060801c5f1960d41c16928492602092611e4f86612684565b61188183612f0c565b50346104a65760203660031901126104a65760205f1960c01c600a611479611ff8565b50346104a6576020611e8c3661207d565b61061f81611e99336126b0565b93611ea58282876127ac565b611eb0828287612901565b611ebb828287612d83565b94612e44565b50346104a65760403660031901126104a657611edb611ff8565b81545f1960601c163303610c2e576028611ef66024356126ff565b9160401b178054915f1960081c1660ff60f81b83161791156105ca575580f35b50346104a65760403660031901126104a657602061042b611f3561201e565b611f3d612057565b906126cf565b503461003c57604036600319011261003c57611f5d611ff8565b60243590611f738260501c5f1960d41c16612684565b611f7c816126b0565b505f1960601c1690813b1561003c575f91602483926040519485938492632587bd1560e01b845260048401525af18015611fc657611fb8575080f35b611fc491505f906120fe565b005b6040513d5f823e3d90fd5b3461003c57602036600319011261003c576020906028611fef611ff8565b60401b17548152f35b600435905f1960601c8216820361003c57565b602435905f1960601c8216820361003c57565b600435905f1960c01c8216820361003c57565b602435905f1960c01c8216820361003c57565b604435905f1960c01c8216820361003c57565b6024359063ffffffff8216820361003c57565b6004359063ffffffff8216820361003c57565b604090600319011261003c576004359060243590565b3461003c57604036600319011261003c576120ac61201e565b5061052861200b565b6024359060ff8216820361003c57565b6044359060ff8216820361003c57565b6064359060ff8216820361003c57565b3461003c57604036600319011261003c57610528611ff8565b90601f01601f19168101905f1960c01c82119082101761211d57604052565b634e487b7160e01b5f52604160045260245ffd5b9060ff8091169116039060ff821161214557565b634e487b7160e01b5f52601160045260245ffd5b5f1960801c918216908216039190821161214557565b5f1960c01c918216908216039190821161214557565b90600a820291808304600a149015171561214557565b8181029291811591840414171561214557565b81156121b8570490565b634e487b7160e01b5f52601260045260245ffd5b5f1960c01c918216908216019190821161214557565b6121eb336126b0565b918160801c5f1960d41c1691612208838560501c61ffff1661481a565b9261ffff841615612345578160401c5f1960c01c9081169461222e620186a0918761219b565b0416915f1960c01c169161224c60ff8760601c165f0b8092856130a5565b918660781c5f1960c01c1680151580612336575b61232c575b506122919063ffffffff88169061228a61227e83612f63565b925f1960801c9261327d565b169061329b565b915f1960c01c8082169084161115612321576122c563ffffffff6122bb6106e6936122d29661216f565b9860201c16612f63565b91865f1960c01c956130a5565b16925f1960c01c811684111561231a5761230d935f1960c01c916122f8919085026121ae565b1691808311612310575b5061150d90826132f5565b90565b915061150d612302565b5050905090565b505050505050505f90565b9250612291612265565b505f1960c01c84168110612260565b5060401c5f1960c01c169392505050565b90600160e81b821615612421576123c6908260701c5f1960d41c16908360501c63ffffffff16906123c09062a715706123b361ffff881661219b60108a901c5f1960c01c16846123a6848861219b565b045f1960c01c169561216f565b045f1960c01c169061216f565b916130e0565b80609c1c5f1960d41c908116908260701c1681811461241a5761230d916123ec84613357565b9361241463ffffffff8260501c169161240483612f63565b9060101c5f1960c01c16906134b1565b906136d6565b5050505f90565b506123c68160101c5f1960c01c168260501c63ffffffff1683609c1c5f1960d41c166130e0565b905f1960601c16815263ffffffff91821660208201529116604082015260600190565b9190820180921161214557565b91612482336126b0565b8360801c5f1960d41c16929061249f848260501c61ffff1661481a565b8560401c5f1960c01c90811695916124bb620186a0918861219b565b0416955f1960c01c16906124d960ff8460601c165f0b8098846130a5565b938360781c5f1960c01c168015158061265d575b612655575b5061251663ffffffff851661250681612f63565b9061228a5f1960801c918661327d565b975f1960c01c868116908a16111561264857612546818961254063ffffffff9482612578976130a5565b966130a5565b95805f1960c01c80891690871610612633575061256d90612567888761216f565b906121cc565b945b60201c16612f63565b936125885f1960c01c91866132c9565b165f1960c01c841611612607575b5060ff8360e81c1690600a820291808304600a1490151715612145576125d76103e8916125d160ff6125df9760f01c165f1960c01c9561246b565b9061219b565b0416906121cc565b925f1960c01c808516908216101561231a5761230d935f1960c01c916122f8919085026121ae565b612612919650613d9f565b5f8160070b12612629575f1960c01c16945f612596565b5050505050505f90565b6126429150612567868961216f565b9461256f565b5050505050505050505f90565b94505f6124f2565b505f1960c01c861681106124ed565b63ffffffff60019116019063ffffffff821161214557565b61269a903360401b176001602e1b175460ff1690565b156126a157565b63d07a9d6b60e01b5f5260045ffd5b60401b6028175480156126c05790565b6302a3661160e61b5f5260045ffd5b9060401b63ffffffff60401b16176003602d1b175490565b5f91820b910b0390607f198212607f83131761214557565b61271163ffffffff8260201c16612f63565b90811561279d5761272763ffffffff8216612f63565b90811561278e5761276f60ff8460a81c1660ff612765818660a81c1692828060601b612757865f0b845f0b6126e7565b60601b169860b01c16612131565b9460b01c16612131565b60681b9260ff60681b199260701b9162ff00ff60601b19161717161790565b63ffd9d17d60e01b5f5260045ffd5b6370802daf60e01b5f5260045ffd5b91909163ffffffff6101e0816101fe6127c361483f565b0116049160201c1692836003602c1b17936610000000000003602c1b179384548060e01c63ffffffff851614155f1461288957838160e01c612878575b5050505f1960c01c838116918060ad1c8216918560ac1c168215612870575b8361284e57505050505f915b600160801b83101561003c579060e01b9060801b5f1960c01c60801b1617179055565b6128626128689282905f1960c01c16614de7565b92614de7565b01029161282b565b91508161281f565b612881926141cf565b5f8083612800565b6128ae948360ad1c5f1960c01c9081169550938416938160ac1c811693501690614125565b9055565b60070b5f19603f1b8114612145575f0390565b600791820b910b03905f19603f1b82125f1960c11c83131761214557565b600791820b910b01905f19603f1b82125f1960c11c83131761214557565b9192918160401c5f1960c01c90811692918060601c60ff165f0b918084169061292b8487846130a5565b165f1960c01c88169561294d85612947895f1960c01c9461216f565b856130a5565b168103908111612145576129aa948060801c5f1960d41c1691612976905f1960c01c1683613053565b600160ac1b1615612d5a579163ffffffff5f1960d41c8960401c16985b5f1960c01c9060ac1c169160201c16978893614923565b8060a052602c1c5f1960d41c168060c0526129c690849061381d565b60a0515f1960d41c16806080529093906129e190829061381d565b9160070b9081905f831261003c578560401c5f1960c01c1660070b94612a0d61425a85614242896128b2565b915f1960c01c8660401c1660070b95612a5d612a2c61425a888a614242565b91612a46835f1960c01c169b8960a0519160c051906142d3565b60a05190612a53896128b2565b90608051906142d3565b5f1960c01c8481169991612a979116808b1115612d4d5782975b612a838960a051614464565b5f1960c01c89169283918260070b906128c5565b9b1115612ce0575093949350612ab59050855f1960c01c861661216f565b9260c0516001602d1b179663ffffffff60a05160d81c1698612ad78a8a615260565b9b909b965b5f1960c01c81168015612c54578c908c612b0b612afd848d60c05190614901565b60a051908d60c05191614969565b918260401c5f1960c01c1690811115612ba6575050612b7a9291612b5791612b3c845f1960c01c8360401c1661216f565b60c051915f1960c01c60401b19169060401b1791908c614c12565b60805160a051915f1960c01c1660070b915f1960581b1617602c8a901b1761467b565b5f975b5f1960c01c8916612b8f575b97612adc565b9b612b9e9197508a8c916155b0565b96909b612b89565b939b9390929080612bd35750612b7d92600160a01b199291612bc7916154f6565b50168d60c0518b614c12565b90612c35612be9612c3b93612b7d96959f61216f565b60c051909e908e90612c08906001602c1b17856001602d1b8417615de5565b612c46575b6154d690602c1b6080515f1960581b60a0511617175f1960c01c8360401c1660070b9061467b565b926154f6565b508d60c0518b614c12565b90600160a11b191690612c0d565b505090939983986128e394969c50612cb39a50612ca09750612c8e90612c81612c98959a9360c051615139565b5f1960c01c92831661216f565b1660070b906128c5565b60a05161467b565b60070b612cd4576128c58460c051614749565b60070b612cc857612cc690608051614749565b565b612cc690608051615653565b6128c58460c051615653565b612ca09550996128e392879892612cb39a98969c9b959b11612d05575b509050612c98565b612c8e83612d24612d19612d46968561216f565b60c05160a051615319565b612d3b63ffffffff60a05160d81c16608051615139565b5f1960c01c9261216f565b805f612cfd565b5f1960c01c861697612a77565b968060401c5f1960d41c16929063ffffffff90612993565b60ff16604d811161214557600a0a90565b918160801c5f1960d41c1691612da4600160ed1b821615156001858761312d565b9161ffff831615612e3b57612de0925f1960c01c91620186a091612dc991841661219b565b041660ff8560601c165f0b915f1960c01c166130a5565b908260781c5f1960c01c1680612e23575b50909161230d919063ffffffff5f1960801c612e1b612e158460681c60ff16612d72565b8761219b565b1691166134d0565b5f1960c01c8316811015612df157915061230d612df1565b50505050505f90565b91908160401c5f1960d41c1690612e65600160ed1b821615155f848761312d565b9061ffff821615612e3b575f1960c01c612ea092612e89620186a09187841661219b565b041660ff8660601c165f0b915f1960c01c166130a5565b918360781c5f1960c01c169081612ed6575b50919261230d925063ffffffff5f1960801c612e1b612e158460681c60ff16612d72565b606c1c5f1960c01c90811691908190612eef84876121cc565b161115612eb25761230d935090612f059161216f565b915f612eb2565b612f15906126b0565b600b8160f81c03612f235790565b6373e44a3b60e01b5f5260045ffd5b612f3b906126b0565b60168160f81c03612f235790565b612f52906126b0565b9060ff8260f81c911603612f235790565b63ffffffff811615612f825760401b63ffffffff60401b166014175490565b6307ed98ed60e31b5f5260045ffd5b51905f1960c01c8216820361003c57565b604051634196411760e11b8152906020906004839182905f1960601c165afa908115611fc6575f91612fe3575b50905f1960c01c60301b19169060301b1790565b90506020813d602011613015575b81612ffe602093836120fe565b8101031261003c5761300f90612f91565b5f612fcf565b3d9150612ff1565b5f8091368280378136915af43d5f803e15613036573d5ff35b3d5ffd5b9081602091031261003c575160ff8116810361003c5790565b61305c81613264565b8060c01c92905f1960c01c8216841061309657612cc69361308a610732935f1960c01c8460801c169261216f565b915f1960801c16614dd1565b630de8eec560e11b5f5260045ffd5b6130b692915f1960c01c16906147b6565b6001603f1b5f1960801c821610156130d1575f1960c01c1690565b634a4ef77f60e11b5f5260045ffd5b906130eb818361327d565b8060801c5f1960c01c9081169491908216851061309657610afe610b0e92612cc69661216f565b916131275761ffff61230d9260401c1661481a565b50505f90565b929190918115908161315e575b5061241a5761230d9261ffff91156131555760501c1661481a565b60401c1661481a565b90505f61313a565b919061ffff82161561241a57620186a0838302045f1960c01c169283156131c8575b5f1960c01c8281169116146131c357620186a09102045f1960c01c90811682031680156131bb575b90035f1960c01c1690565b5060016131b0565b505090565b60019350613188565b9294846132386132319496612cc6999487613231613223966132238d8660ff6132048563ffffffff8960201c169961216f565b9660701c169561321c5f1960801c916125d189612d72565b16876136d6565b6125d15f1960801c93612d72565b16906134d0565b8660ff61324c8563ffffffff89169961216f565b9660681c169561321c5f1960801c916125d189612d72565b60201b5f1960c01c60201b1660011760401b601e175490565b60201b5f1960c01c60201b169063ffffffff161760401b601e175490565b906132c59060ff80808560b01c169460a81c165f1960c01c940316600a0a905f1960801c166121ae565b1690565b9060ff6132da9260f01c169061219b565b600381029080820460031490151715612145576103e8900490565b905f1960c01c169081156121b8575f1960c01c160690565b63ffffffff811615612f825760401b63ffffffff60401b16601417545f1960601c811615613348578060401b5f1960601c60401b1660151755565b634a58fdfd60e11b5f5260045ffd5b60016032540163400000008110156134a9575b8061230d9160325563ffffffff61337f61483f565b9160201b63ffffffff60201b169116178060401b603217839055918060501c63ffffffff1681609c1c5f1960d41c166133c2856001602c1b84811790841761485b565b508260701c5f1960d41c16906133df86846001602c1b851761485b565b506133ea83826156f8565b6133f48383615653565b8360101c5f1960c01c1690613437908461340e81836126cf565b613421858260401c5f1960c01c166121cc565b905f1960c01c60401b19169060401b17916157e5565b61345161344484846126cf565b915f1960c01c83166121cc565b90815f1960401b8216179461ffff8660801c1661ffff821611613477575b5050506157e5565b905f1960c01c61ffff60801b0119169161ffff60801b1916919091179060801b61ffff60801b161792505f808061346f565b50600161336a565b9060ff80808460b01c169360a81c165f1960801c930316600a0a021690565b905f1960801c8116801580156135cb575b6135c5576134ef838561327d565b600160201b63ffffffff85161760401b601e17545f1960801c82169290919083106135b65761353c613528916135288661354f96612159565b8160c01c9160801c5f1960c01c1690614dd1565b935f1960801c831680156135ab5761410f565b61355a828486614091565b600160201b63ffffffff84161760401b601e17555f1960801c161561357e575b5050565b6001602c1b63ffffffff8216811760601b831717545f1960c01c16156135a2575050565b612cc69161579d565b61410f8760016156f8565b6351940b3960e11b5f5260045ffd5b50505050565b505f1960c01c84166001146134e1565b90915f1960801c8216801580156136c4575b6135c557601e60015f1960c01c60201b602087811b82168317604090811b8517549187901b909216909217901b9091175490915f1960801c8316919082106135b657613528613645601e946135288861365896612159565b955f1960801c831680156136b95761410f565b60015f1960c01c60201b602087811b82168317604090811b861788905595901b161790921b17555f1960801c161561368d5750565b6001602c1b6510000000000160601b018117545f1960c01c16156136ae5750565b6001612cc69161579d565b61410f6001886156f8565b505f1960c01c848116908316146135ed565b91925f1960801c82169081158015613768575b613761576136f7848661327d565b613701858361327d565b925f1960801c82169081106135b6576137489361352861372988946135288961373c96612159565b965f1960801c831680156137575761410f565b91614091858389614091565b5f1960801c161561357e575050565b61410f86886156f8565b5050505050565b505f1960c01c858116908216146136e9565b9091613787818484614901565b928360401c5f1960c01c16156135c557603c631fffffff6137a661483f565b60031c160463ffffffff808660801c169116146135c557613817612cc6946137cd84613835565b82856138116137db876138a8565b876138086137e882612f63565b60ff806014600160401b01549260a81c169160a81c165f0b905f0b6126e7565b91808686614923565b92614969565b92614c12565b9060401b63ffffffff60401b16176005602c1b175490565b63ffffffff6101e0816101fe61384961483f565b011604911690816003602c1b17916610000000000003602c1b179182548060e01c63ffffffff8416810361387e575050505050565b8390613897575b50505060e01b90555f80808080613761565b6138a0926141cf565b5f8082613885565b60401b63ffffffff60401b166017175460ff811660028114613941576004146138da57637144370360e11b5f5260045ffd5b604051634c6afee560e11b81529060209060048391829060081c5f1960601c165afa908115611fc6575f9161390d575090565b90506020813d602011613939575b81613928602093836120fe565b8101031261003c5761230d90612f91565b3d915061391b565b5060405163313ce56760e01b81529060081c5f1960601c16602082600481845afa908115611fc6576004925f92613abc575b5060a09060405193848092633fabe5a360e21b82525afa918215611fc6575f92613a6a575b5060ff1660010b91815f8412613a39575b5091905b6001603b1b81101580613a2d575b156139d157600a9004905f190160010b906139ad565b5b600a81061580613a21575b156139f357600a9004905f190160010b906139d2565b906001603b1b82101561003c5760208160010b121561003c5760ff16906020600160401b039060051b161790565b505f8260010b136139dd565b505f8260010b136139bb565b915091617fff198114612145575f0361ffff1690604d821161214557613a6291600a0a9061219b565b5f915f6139a9565b90915060a0813d60a011613ab4575b81613a8660a093836120fe565b8101031261003c5780613a9a60ff92614c33565b50613aac608060208301519201614c33565b509190613998565b3d9150613a79565b60a0919250613ad99060203d602011610f0157610ef281836120fe565b9190613973565b90613aec600283614c44565b6014600160401b0154909290613b029082615a46565b91613b0c84614c8c565b1580613d92575b613d8a576014600160401b015460a81c60ff16939092845f0b915b613b3781614c8c565b15613c4b5783613b4691614cb8565b9091613b51826138a8565b9080613b5c84612f63565b93613b6f8760ff8760a81c165f0b6126e7565b90613b7b86828b615b1f565b91613b87818488615b69565b92600f0b5f125f149560ff613bec613bfb96613be6613bfb97613c019b613c2057613bdf908d613bd9878260e81c1691614d59613bd38a613bc786614d42565b9360f01c168093614d6f565b93614d42565b91615bb0565b9a90614d85565b98614d85565b9860e81c1660010b928b615c0f565b92614d85565b9081600f0b81600f0b135f14613c1957505b90613b2e565b9050613c13565b613bdf908d613bd9878260e81c1691614d6f613bd38a613c3f86614d42565b9360f01c168093614d59565b5092935050613c5b600282614c6c565b613c6481614c8c565b15613d695781613c7391614d00565b63ffffffff8116600163ffffffff60c0602087828604620fffff602c1b90602c1b161760401b17549306161b1615613cb8575b505f83600f0b12613c5b575050505f90565b61ffff613d28613d0c613ccd849795976138a8565b93613cd781612f63565b94613d0686613cff60ff8260a81c1660ff6014600160401b015460a81c165f0b905f0b6126e7565b938a615b1f565b90615b69565b9260ff613d1d818360e81c16614d42565b9160f01c1690614d59565b1660010b6103e803617fff198112617fff8213176121455760010b90600f0b029081600f0b918203612145576103e8613d62920590614d85565b915f613ca6565b50505f81600f0b12613d7b5760070b90565b63313ffa7d60e21b5f5260045ffd5b925050505f90565b505f83600f0b1215613b13565b90613dab600283614c44565b6014600160401b0154909290613dc19082615a46565b6014600160401b015460a81c60ff1693845f0b91905b613de081614c8c565b15613e8f5783613def91614cb8565b9091613dfa826138a8565b9080613e0584612f63565b93613e188760ff8760a81c165f0b6126e7565b90613e2486828b615b1f565b91613e30818488615b69565b92600f0b5f125f149560ff613bec613bfb96613be6613bfb97613e709b613c2057613bdf908d613bd9878260e81c1691614d59613bd38a613bc786614d42565b9081600f0b81600f0b135f14613e8857505b90613dd7565b9050613e82565b5093505090613e9f600283614c6c565b613ea881614c8c565b15613f835782613eb791614d00565b91909163ffffffff8116600163ffffffff60c0602088828604620fffff602c1b90602c1b161760401b17549306161b1615613ef4575b5090613e9f565b61ffff613f42613d0c613f09849895986138a8565b93613f1381612f63565b94613d0686613f3b60ff8260a81c1660ff6014600160401b015460a81c165f0b905f0b6126e7565b938b615b1f565b1660010b6103e803617fff198112617fff8213176121455760010b90600f0b029081600f0b918203612145576103e8613f7c920590614d85565b925f613eed565b5091905060070b90565b9190613f99818461327d565b92613fa382612f63565b91613fb45f1960801c86168461329b565b915f1960c01c613fc483836126cf565b16906103e860ff8660e81c16600a60ff8860f01c16910201830204928215159081614080575b50614051575b50508460c01c019081811115612e3b57039260801c5f1960c01c1682019081841061401f575b50505050600190565b60ff600a9160a01c1684020410918215614047575b5050614043575f808080614016565b5f90565b1090505f80614034565b61405a90613d9f565b5f8160070b12612321575f1960c01c166032029081811115613ff0570390505f80613ff0565b6001915063ffffffff16145f613fea565b60201b5f1960c01c60201b169063ffffffff161760401b601e1755565b91908110156140be5760051b0190565b634e487b7160e01b5f52603260045260245ffd5b9081602091031261003c5751801515810361003c5790565b01600160401b811015614100575f1960c01c1690565b63379168e560e01b5f5260045ffd5b5f1960801c918216908216019190821161214557565b5f1960c01c821694909391928515614194575f1960c01c82161561418c575b612862816141529394614de7565b01025f1960801c82160191600160801b83101561003c5761417c908260801c5f1960a01c1661410f565b60801b905f1960201c1916171790565b905080614144565b50505050905090565b63ffffffff5f199116019063ffffffff821161214557565b9063ffffffff8091169116039063ffffffff821161214557565b91909161420e6142028360e01c9361ffff846141ea8761419d565b60401b63ffffffff60401b1617541660010b90614e51565b9261266c848285614f5f565b63ffffffff841663ffffffff8216106142275750505050565b61423b8161266c8563ffffffff9486614f5f565b905061420e565b8160070b8160070b135f14614255575090565b905090565b8060070b5f135f1461230d57505f90565b81810392915f13801582851316918412161761214557565b9190915f838201938412911290801582169115161761214557565b81810292915f8212600160ff1b82141661214557818405149015171561214557565b600b0b5f19605f1b8114612145575f0390565b612cc6939263ffffffff91603c631fffffff6142ed61483f565b60031c1604908060e01c158015614450575b1561432d575060e01b9060401b5f1960c01c60401b16178360581c5f1960c01c1617925b60d81c1690615122565b91908560581c5f1960c01c9081169084168181036143eb575b50508260e01c848216811061438e575b5061436f918360401c5f1960c01c1660070b91506128e3565b905f1960c01c60401b19169060401b5f1960c01c60401b161792614323565b926143dd6143ac8361436f9596888b60d81c166003602c1b17615052565b5f1960201c92906143cf6143d79160030b8360401c5f1960c01c1660070b61429e565b600b0b6142c0565b906150df565b169060e01b1791905f614356565b5f949192945061443f61441561440e5f1960c01c8560401c1660070b8094615035565b9285615035565b614439888b60d81c16600160201b178a6005602c1b9160401b17179384549261426b565b90614283565b90555f1960401b1617915f80614346565b508060401c5f1960c01c1660070b156142ff565b915f1960c01c821691908215614675575f1960d41c8416905f1960d41c85602c1c1663ffffffff8660d81c16948661449d878487614901565b8060401c5f1960c01c166145ff575b5050505f1960c01c8416156145ec576001602d1b811793916144ce8686615260565b979097935b5f1960c01c81169081156145d5576144f28386886149698d8383614901565b918260401c5f1960c01c169081111561456c57509061452882614519614540948987615319565b8260401c5f1960c01c1661216f565b905f1960c01c60401b19169060401b17888587614c12565b5f915b5f1960c01c8316614555575b916144d3565b976145649194508688916155b0565b93909761454f565b614585816145439361216f61459e948b899a989a615319565b946001808260a11c1614806145bd575b6145b1576154d6565b6145a88a8a6154f6565b50898688614c12565b600160a11b19166154d6565b506145956001602c1b88178c6001602d1b8b17615de5565b5050509550849350615139915093612cc694615139565b61513991955084935093612cc694615139565b90838661460f9398949598614969565b918260401c5f1960c01c16908110614652579061462b9161216f565b5f949161464a91905f1960c01c60401b19169060401b17868386614c12565b5f86816144ac565b6146629061464a9296939661216f565b945f1960c01c60401b1916868386614c12565b92505050565b908060070b1561357a57612cc6915f1960d41c81602c1c16915f1960d41c8216906146d26146be63ffffffff8560d81c169484876149698361561b8a8585614901565b915f1960c01c908116908360401c166121cc565b905f1960c01c60401b19169060401b1792838060a11c6001165f1901614721575b506001808560a01c160315614c12579261471484846001602d1b851761485b565b50600160a01b1792614c12565b90935061473b6001602c1b8317846001602d1b871761485b565b50600160a11b17925f6146f3565b63ffffffff60601b8260601b1681176001602c1b17549163ffffffff16915f1960c01c1615614776575050565b60c08204906210000063ffffffff8316101561003c57602091620fffff602c1b90602c1b161760401b1790600163ffffffff60c084549306161b19169055565b905f1960801c168160051c5f1960c51c16029190601f165f918203820b03908113156147f657600a0a025b6001607f1b8110156130d1575f1960801c1690565b5f8112614804575b506147e1565b90614814915f03600a0a906121ae565b5f6147fe565b905f1960c01c81166001146131275760401b6033175460011461483a5790565b505f90565b636592007f19420142811161214557603c63ffffffff91041690565b905f1960c01c8316156148f25760601b1780545f1960c01c811660018181019392019063ffffffff8410156148e35760048410156148b557508260061b93838504604014841517156121455763ffffffff941b1790551690565b83603e1b5f1960401b1683178054916002190160061b60c0169590951b179093559190915563ffffffff1690565b6303e98cf160e21b5f5260045ffd5b6342c1dde960e01b5f5260045ffd5b602c1b1760401b5f1960801c60401b169063ffffffff16176007602c1b175490565b602c1b179160581b5f1960c01c60581b16919091179060981b5f1960c01c60981b16179060d81b179060f81b60ff60f81b161790565b600160ff1b8114612145575f0390565b939293603c631fffffff61497b61483f565b60031c16049163ffffffff8260801c169363ffffffff84169081861480614bfb575b614bf1578360401c5f1960c01c16918215614bd6578260070b6149c6815f1960c01c8816615035565b60588b901c5f1960c01c1698906149e7906149e1848c615035565b9061426b565b948b60f81d601f815f0b01607f198112607f821317612145575f0b604d811161214557600a0a9182156121b857600160ff1b88145f1984141661214557614a498e93890560070b98614a42614a3b82614959565b868d61581c565b848961581c565b8a5f968510614b28575b505050505050614a64838386615847565b815f925f8160070b12614b16575b5060070b995f925b6307ffffff8c11614b065760405190601f1b60049c909c1b9b909b1790921760e01b5f1960201c19168260481b5f1960c01c60a01b16179060601b179060981c63ffffffff60401b16175f1960c01c928316178852959661230d968216929091169060207f694c782211d4a1ae789d781d714ba17f15c6ed8630cbcfc224532618132d651591a36157fc565b929a600a600191049b0192614a7a565b600193505f90810360070b9150614a72565b614bcb9598965062989680614b7a614b6f614b8b95614bc49795614b60614b859663ffffffff8960d81c169b8c6003602c1b17615052565b9660981c5f1960c01c166130a5565b9360030b809461429e565b0560070b80976128e3565b9761429e565b600b0b614bb7614bb0614b9d836142c0565b6143d7614baa878d61381d565b916142c0565b848a615122565b6143d7614baa848861381d565b9084615122565b5f808a81808a614a53565b50959661230d965060581c5f1960c01c1694506157fc915050565b5091955050505050565b505f1960c01c84811660588a901c9091161461499d565b602c1b1760401b5f1960801c60401b169063ffffffff16176007602c1b1755565b51905f1960b01c8216820361003c57565b9060208260401b1754908160e01c908115614c645761230d936020615882565b505050505f90565b90601f8260401b1754908160e01c908115614c645761230d93601f615882565b630fffffff8160241c169081156131275763ffffffff9060ff630fffffff8260081c1691160116111590565b63ffffffff90929192614cfa60ff821694630fffffff8360081c169283630fffffff8260241c169160c082049060401c93878060018c01169216906020615982565b93011690565b63ffffffff90929192614cfa60ff821694630fffffff8360081c169283630fffffff8260241c169160c082049060401c93878060018c0116921690601f615982565b61ffff600a9116029061ffff821691820361214557565b9061ffff8091169116019061ffff821161214557565b9061ffff8091169116039061ffff821161214557565b600f91820b910b01905f19607f1b82125f1960811c83131761214557565b919063ffffffff614dcc915f196001856010011b0116169160018101810260011c9060041b0190565b1b1790565b9190915f1960801c169160801b9060c01b171790565b614e1890614dfc601f8416601f83169061426b565b9260051c5f1960c51c1690603b1b5f1960c51c60401b166121ae565b905f8112614e3a575b5f8113614e30575b5060221c90565b600a0a025f614e29565b90614e4b90825f03600a0a906121ae565b90614e21565b908160801c5f1960a01c168015614f3b578160010b929160201b60050b5f1960801c92831691909104909116600f0b5f19601f1b016298968002015f811215614f30575f19601f1b015b600160201b9005908082035f811380614f25575b15614ef557506103e89150015b5f811380614eea575b15614ed557506175305b60010b90565b61752f19811215614ecf575061752f19614ecf565b506175308113614ec5565b5f81129081614f18575b50614f0b575b50614ebc565b6103e7190190505f614f05565b6103e7191390505f614eff565b506103e88113614eaf565b638000000001614e9b565b50905090565b600391820b910b01905f19601f1b8212637fffffff83131761214557565b909161ffff8116915f9160010b5b63ffffffff8316600a81108061501d575b15614fda57614fbe614fd392614fb88386614fa563ffffffff6001614fc4981b168c6141b5565b60401b63ffffffff60401b161754615d56565b90614f41565b9361266c565b938363ffffffff861691614da3565b9291614f6d565b50909293915b600a63ffffffff82161061500057505060401b63ffffffff60401b161755565b819463ffffffff6001615017930116958691614da3565b93614fe0565b5063ffffffff6001821b1663ffffffff871611614f7e565b601f5f1960c51c8260051c169116601f03600a0a9160070b020290565b929190615068906150628361419d565b926141b5565b905f935f945b63ffffffff841661507f5750505050565b6001808516146150a6575b6001810180911161214557637fffffff909360011c169261506e565b91946150c86150d991614fb8858563ffffffff60401b8b60401b161754615d56565b9563ffffffff6001851b16906141b5565b9161508a565b90600b90810b8260801c5f1960a01c1690910b015f1960a11c81135f19605f1b82121761214557905f1960a01c60801b19169060801b5f1960a01c60801b161790565b9060401b63ffffffff60401b16176005602c1b1755565b91826001602d1b1763ffffffff8316905f1960c01c818360601b17541615615259576151658282615260565b6001602c1b949067ffffefffffffffff81169086161580156152145761518c888a84614901565b9392935b8060401c5f1960c01c1661524d578989916151ab89896154f6565b50831561523e57600160a01b1916925b15615234576151c993614c12565b63ffffffff811615801590615228575b1561521f5783836151e9926155b0565b90919067ffffefffffffffff81169086161580156152145761520c888a84614901565b939293615190565b61520c88838b614901565b50945050505050565b508060c01c15156151d9565b926151c993614c12565b61524790615d9d565b926151bb565b50505050945050505050565b5050915050565b9060601b17908154915f9063ffffffff841690811561530a5760038211156152d35784603e1b633fffffff60401b16175490600319019163ffffffff83116152bf57506003633fffffff6152bb949560021c16921690615dbd565b9091565b634e487b7160e01b81526011600452602490fd5b50926152e3915060401c9261419d565b63ffffffff8116600403600690811b84901b9391901b643fffffffc0161c5f1960c01c1690565b639349665b60e01b5f5260045ffd5b90915f1960c01c8116156154d1578160d81c63ffffffff16926001602d1b5f1960d41c84169081179390929161534f8686615260565b90976001602c1b945b5f1960c01c811680156154c45767ffffefffffffffff8416908761537d8c848c614901565b958660401c5f1960c01c166154b6575b50508a61539d88848c8199614969565b918260401c5f1960c01c169081111561543057506154049392916153e791506153cf848260401c5f1960c01c1661216f565b905f1960c01c60401b19169060401b178c838c614c12565b905f1960c01c1660070b905f1960581b87161785602c1b1761467b565b5f945b5f1960c01c8616615419575b94615358565b986154289192508789916155b0565b919098615413565b9398939091908061545c57509061544a6154079392615d9d565b91615455828d6154f6565b508a614c12565b61546f61544a916154079594939b61216f565b996154818c846001602d1b8717615de5565b6154aa575b615d9d8160401c5f1960c01c1660070b5f1960581b8c168617602c8c901b1761467b565b600160a01b1916615486565b81160361003c57875f61538d565b5050975050505050505050565b505050565b6001808260a11c160361483a575f1960c01c60401b600160a01b01191690565b9060601b178054905f1960c01c82169081156155a1575f198301926003831161554d5760061b5f1960c01c60061b1692828404604003612145575f1960c01c81851c8116941b1916915b5f19810111612145575590565b603e1b5f1960c21c60401b16811780546003198401949391908286116121455760c0600387169660061b169580870460401490151715612145575f1960c01c80871b19821690925590941c90931692615540565b63251b322360e11b5f5260045ffd5b8060c01c806155ff575063ffffffff1691821561530a576152bb925f19019163ffffffff83169263ffffffff60401b9060401b16179060601b175460039082615dbd576002915060401c615dbd565b939250905063ffffffff8116905f1960801b9060401b16179190565b905f1960c01c82161561562c575090565b9050603c631fffffff61563d61483f565b60031c160460801b9060581c5f1960c01c161790565b90819060208360401b1792835463ffffffff83169460c086049163ffffffff8316946210000086101561003c578160e01c88116156d4575b509050926156af575b5050600163ffffffff60c06020949506161b179160401b1755565b602c1b620fffff602c1b16178060401b602017549092509050600163ffffffff615694565b905f1960201c169060e01b5f1960201c191617908190851561568b5755805f61568b565b908190601f8360401b1792835463ffffffff83169460c086049163ffffffff8316946210000086101561003c578160e01c8811615779575b50905092615754575b5050600163ffffffff60c0601f949506161b179160401b1755565b602c1b620fffff602c1b16178060401b601f17549092509050600163ffffffff615739565b905f1960201c169060e01b5f1960201c19161790819085156157305755805f615730565b9063ffffffff169060c08204906210000063ffffffff8316101561003c57601f91620fffff602c1b90602c1b161760401b1790600163ffffffff60c084549306161b19169055565b9060401b63ffffffff60401b16176003602d1b1755565b5f1960c01c63ffffffff60801b0119169060801b17905f1960c01c161790565b63ffffffff6128ae9260d81c16600160201b17906005602c1b9160401b171791614439835491614959565b908260070b8015614c64575f12156158695761230d925f1960c01c1691615ea0565b9061587661230d936128b2565b5f1960c01c1691615ea0565b93909291945f925f925b63ffffffff8216978863ffffffff8683011611615975575b63ffffffff811660c081109081615961575b81615953575b50156158d05760010163ffffffff166158a4565b92979493919463ffffffff83850116116123215760c063ffffffff841610615924575060019163ffffffff9101169101945f1960c01c86169285855f98620fffff602c1b90602c1b161760401b175461588c565b90945064ffffffff009193955060ff925060401b9463ffffffff60241b9060241b169360081b16911617171790565b600191501b8216155f6158bc565b90508963ffffffff878401161115906158b6565b5050509450505050505f90565b9596919392969490945b63ffffffff8216978863ffffffff8683011611615975575b63ffffffff811660c081109081615a32575b81615a24575b50156159d05760010163ffffffff166159a4565b92979493919463ffffffff83850116116123215760c063ffffffff841610615924575060019163ffffffff9101169101945f1960c01c86169285855f98620fffff602c1b90602c1b161760401b175461598c565b600191501b8216155f6159bc565b90508963ffffffff878401161115906159b6565b8060201b5f1960c01c60201b1660011760401b601e175490915f1960c01c915f1960801c615a769291169061329b565b9162080003602d1b17549116600f0b5f1960c01c821661016d612710615aa66121858660801c61ffff168561219b565b040490606582029180830460651490151715612145575f1960c01c916064615ad09291049061246b565b1660070b9003905f19607f1b82125f1960811c831317612145576103d49060401c5f1960c01c1681810292918115918404141715612145576103e861230d92045f1960c01c1660070b90614d85565b91615b479190615b3d5f1960c01c915f1960801c61228a858861327d565b16600f0b926126cf565b905f1960c01c821661016d612710615aa66121858660801c61ffff168561219b565b90915f83600f0b12615b8f575f1960801c92615b8892908416906147b6565b16600f0b90565b5f1960801c92615ba492905f038416906147b6565b16600f0b5f03600f0b90565b61ffff90939293600f0b91166103e80161ffff8111612145576103e8615bde61ffff80931660010b8461429e565b0593166103e80361ffff8111612145576103e89161ffff615c03921660010b9061429e565b0591600f0b91600f0b90565b9094939291615c1e868361381d565b8060401c5f1960c01c1660070b969092908715615d4957600160201b9063ffffffff1690811760401b9091176005602c1b175490601f85015f0b600a0a80156121b8576064928391615cfd9105600f0b615c7f888c5f1960c01c8a16615b69565b03600f0b9685615c91828d8b99615b69565b948a850160010b9885808b8902600f0b059c810360010b809802600f0b059d629896805f1960a01c8360801c16600b0b600b0b0560070b92603c631fffffff615cd861483f565b60031c16049260e01c9263ffffffff81168410615d1f575b5050505060070b90615b69565b948502600f0b059302600f0b059303600f0b01600f0b9303600f0b01600f0b90565b6298968093615d33926003602c1b17615052565b60030b020560070b900360070b5f808080615cf0565b50505050505090505f5f91565b9063ffffffff916001600f5f1982856010011b018093615d818660018101810260011c9060041b0190565b1c1693011b8216615d95575b501660030b90565b19175f615d8d565b6001808260a01c160361483a575f1960c01c60401b600160a11b01191690565b92915f1960061c8216820361214557838260040360061b1b17925f1960c01c9160061b1c1690565b9060601b17805490915f1960c01c8216908115614c645760038211615e42578260061b5f1960c01c60061b16918204604003612145575f1960c01c90811683831c9091160361241a575f1960c01c901b19165b5f19019055600190565b82603e1b5f1960c21c60401b16841780549092909160031982019182116121455760c0600383169260061b169180830460401490151715612145575f1960c01c90811683831c90911603612e3b575f1960c01c901b19169055615e38565b615ea981613264565b92615ebc816014600160401b01546134b1565b935f1960801c808616911610615ed65750614043926135db565b919061230d9350600360cb1b92600160501b92609c1b9160701b9060101b1717171761335756fe2295a7b3f9aeed5ef4433422665e962977c49a4af64f57698022950944eadbf1", - "nonce": "0x1", - "storage": {} - }, - "0xf12fe484ab504276a454e750f54a9b7fbe5b0687": { - "balance": "0x0", - "code": "0x60a06040526004361015610011575f80fd5b5f3560e01c8063138d2c2814610b485780631d8853a814610b1c57806321e1f52b14610afe578063223ac68014610abc578063259cacac14610a9e57806327ac088e14610a805780632d4eecb814610a465780632de7723014610a0b578063393210f5146109ed5780633c9d58fe146109b357806342439ff8146109545780634a0a62cd146109335780634bb52d8e146109155780635209e84f146108f8578063522a11ce146108b657806354e5a52b146108985780636063f8e6146106fc578063628b5acb146106c057806372f9570814610698578063795e38bb146106035780637bd0e6e6146105d35780638043b48314610553578063832c822e146105285780638f06d80a146104b5578063934bd5f51461035a578063992ae9f01461032d578063bd9d6cd6146102fd578063bfa806b0146102a9578063c7ff158414610280578063cb2085451461023c578063d9a8b4581461021f578063e9edf853146101c55763fd05789d14610184575f80fd5b346101c15760403660031901126101c1576101bd6101b16101a3610bbd565b6101ab610bf6565b906132db565b60405191829182610c5b565b0390f35b5f80fd5b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b16610201576101ff600435611cb6565b005b634200948f60e11b5f5260045ffd5b63026e41fb60e41b5f5260045ffd5b346101c1576101bd6101b161023336610c09565b929190916129f9565b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b16610201576020610278600435612b53565b604051908152f35b346101c1575f3660031901126101c1576020640b0000000154600160e01b161515604051908152f35b346101c15760203660031901126101c1576102c2610be3565b640b000000015433905f1960601c160361021057640b0000000180545f1960c01c60a01b19169160a01b5f1960c01c60a01b16919091179055005b346101c15760203660031901126101c157640b000000015433905f1960601c1603610210576101ff600435612fe8565b346101c15760403660031901126101c1576101bd6101b161034c610bbd565b610354610bf6565b90613024565b346101c15760603660031901126101c157610373610be3565b640b0000000154604435916024359133905f1960601c1603610210575f916103ff8160061c16600181145f1461042857505f1960c01c8416610414575b8360801c5f1960c01c166103d0575b5050602091505b6040519015158152f35b640b0000000154600160e01b16610201576020936103f892600f6120e49360b01c1691612fbb565b8115610407575b5082806103bf565b60019150811614826103ff565b6103b0612fe860018360b41c168487612fa8565b919390916002036104a6575f1960c01c8116610492575b8060801c5f1960c01c16610459575b5050602091506103c6565b640b000000015491925090600160e01b1661020157610489612b5360019392602095600f869560b01c1691612fbb565b1614828061044e565b61043f612f6a60018460b41c168684612fa8565b63f445d2a960e01b5f5260045ffd5b346101c1575f3660031901126101c15763ffffffff60325460c01c165f5b63ffffffff82166104e957604051908152602090f35b60018101809111610514579060201b63ffffffff60201b166032175460c01c63ffffffff16906104d3565b634e487b7160e01b5f52601160045260245ffd5b346101c1575f3660031901126101c157640b00000001546040519060a01c5f1960c01c168152602090f35b346101c15760203660031901126101c15761056c610bbd565b63ffffffff60325460c01c165f5b63ffffffff82161515806105c4575b156105b95760018101809111610514579060201b63ffffffff60201b166032175460c01c63ffffffff169061057a565b602090604051908152f35b5063ffffffff83168110610589565b346101c15760203660031901126101c157640b000000015433905f1960601c1603610210576101ff600435612f6a565b346101c15760203660031901126101c157600435801515908181036101c157640b000000015433905f1960601c160361021057640b0000000154901561068b57600160e01b17905b600160e01b821615150361066257640b0000000155005b60405162461bcd60e51b81526020600482015260016024820152603360f91b6044820152606490fd5b600160e01b19169061064b565b346101c1575f3660031901126101c157640b0000000154604051905f1960601c168152602090f35b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b166102015760206102786004356120e4565b346101c15760603660031901126101c157610715610be3565b61071d610bd0565b906044359063ffffffff82168092036101c1576040918251906107408483610dd4565b602082527f3031323334353637383941424344454647484a4b4d4e5051525354565758595a6020830152835192610778606085610dd4565b60348452602084019560403688375f5b601c8110610840575090603c1b5f1960c01c603c1b16601c91821b63ffffffff601c1b161791909117905b603481106107e9575050508151928391602083525180918160208501528484015e5f828201840152601f01601f19168101030190f35b601a198101818111610514576005810290808204600514901517156105145760780390607882116105145760019161082b601f8560ff60f81b931c1686611c91565b51165f1a6108398287611c91565b53016107b3565b60058102818104600514821517156105145760a0039060a082116105145760041982019182116105145760019160ff60f81b906108839030901c601f1688611c91565b51165f1a6108918289611c91565b5301610788565b346101c15760203660031901126101c1576020610278600435611a1c565b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b166102015760206102786004355f1960101c16612b53565b346101c1576101bd6101b161090c36610c09565b9291909161280e565b346101c15760203660031901126101c1576020610278600435611699565b346101c1575f3660031901126101c157602064020000000154604051908152f35b346101c1575f3660031901126101c15763ffffffff60285460c01c165f5b63ffffffff821661098857604051908152602090f35b60018101809111610514579060201b63ffffffff60201b166028175460c01c63ffffffff1690610972565b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b16610201576101ff6004356115a6565b346101c15760203660031901126101c1576020610278611574610be3565b346101c1575f3660031901126101c1576020610a25613a09565b610a2d613a35565b6040519160801b5f1960801b16905f1960801c16178152f35b346101c15760403660031901126101c1576020610a72610a64610be3565b610a6c610bd0565b906114d5565b604051905f1960c01c168152f35b346101c15760203660031901126101c15760206102786004356112b4565b346101c15760203660031901126101c157602061027861127d610be3565b346101c15760203660031901126101c157640b0000000154335f1960601c82160361021057600160e01b166102015760206102786004355f1960101c166120e4565b346101c15760203660031901126101c1576020610278600435610e70565b346101c15760403660031901126101c1576020610a72610b3a610be3565b610b42610bd0565b90610cdd565b346101c15760203660031901126101c157610b61610bbd565b63ffffffff60285460c01c165f5b63ffffffff8216151580610bae575b156105b95760018101809111610514579060201b63ffffffff60201b166028175460c01c63ffffffff1690610b6f565b5063ffffffff83168110610b7e565b6004359063ffffffff821682036101c157565b6024359063ffffffff821682036101c157565b600435905f1960c01c821682036101c157565b602435905f1960c01c821682036101c157565b60809060031901126101c1576004355f1960c01c811681036101c1579060243563ffffffff811681036101c1579060443563ffffffff811681036101c157906064355f1960c01c811681036101c15790565b60206040818301928281528451809452019201905f5b818110610c7e5750505090565b8251845260209384019390920191600101610c71565b63ffffffff60019116019063ffffffff821161051457565b63ffffffff166001019063ffffffff821161051457565b9063ffffffff8091169116019063ffffffff821161051457565b905f906028549363ffffffff8560c01c16918215610d995760a09590951c63ffffffff60201b1660281754929492915f905b610d1f5f1960c01c851687611da8565b80610d8a575b15610d6d579063ffffffff610d4a92169063ffffffff60201b9060201b161795610c94565b8260a01c63ffffffff60201b16602817549095909260c01c63ffffffff16610d0f565b509350939163ffffffff91508116911611610d8757505f90565b90565b5063ffffffff81161515610d25565b5093505050505f90565b8181029291811591840414171561051457565b8115610dc0570490565b634e487b7160e01b5f52601260045260245ffd5b90601f01601f19168101905f1960c01c821190821017610df357604052565b634e487b7160e01b5f52604160045260245ffd5b51905f1960c01c821682036101c157565b5f1960c01c91821681529116602082015260400190565b5f1960c01c918216908216019190821161051457565b5f1960c01c9081165f19019190821161051457565b5f1960c01c918216908216039190821161051457565b90640b00000001545f1960601c1633146101c1576028546402000000015463ffffffff8260c01c1690815f1960c01c8660401c16938493156112735760a01c63ffffffff60201b1660281754955f1960c01c8116151595868061125f575b611253575f959495945f60ff610ee333611e09565b9660401c165f0b945b5f1960c01c8516158a61123f575b8061122f575b80611220575b156111fa5760808b901c5f1960d41c9081168660c01c909116146111ef5750610f3086338c611e8f565b5f1960c01c8b811690610f44888484611f74565b165f1960c01c8b1681101561100057505090610f84610f72888a8e610fbe968a60ec1c151560f01b90611ff9565b9860408a901c5f1960c01c1690610e2f565b988860c01c905f1960c01c81168211610ff457610fb891610fa491610e5a565b985b5f1960c01c8181169160801c16610e2f565b90610e2f565b975b63ffffffff8a60c01c1680610fdb575b989098979697610eec565b60a09a909a1c63ffffffff60201b166028175499610fd0565b5050610fb85f98610fa6565b98959392969a9190999b97949b5b5f1960c01c82161515806111df575b156111cb575f1960c01c818116979061103c8c610db68b878516610da3565b1691821561115e5760405163c03ad24360e01b815260208180611063868860048401610e18565b0381335afa80156111c0578f948f925f9261117c575b509061108491610e2f565b935f1960c01c86811690861611611174575b5f1960c01c916110a891908690611f74565b161561115e576110c388838d8a60ec1c151560f01b87611ff9565b60805260805160c01c9182156111475760805161110a916110ed9160401c5f1960c01c1690610e2f565b60808051919c91610fb8915f1960c01c8281169290911c16610e2f565b98821161112e57611125929161111f91610e5a565b92610e5a565b9695969061100e565b5050611125906111415f98939893610e45565b97610e5a565b9c509a505050509091935098919498979397610fc0565b9a509a5050509091935098919498979397610fc0565b859450611096565b95509150506020843d82116111b8575b8161119960209383610dd4565b810103126101c1576110848f94918f926111b290610e07565b91611079565b3d915061118c565b6040513d5f823e3d90fd5b985050909193975098919498979397610fc0565b5060015f1960c01c82161161101d565b989098979697610fd0565b509693509150969350610d8795506112129250610e5a565b905f1960c01c1690826120c8565b5063ffffffff81161515610f06565b5060015f1960c01c8a1611610f00565b50610efa5f1960c01c8c8116908716611da8565b96505050505050505f90565b50610ece5f1960c01c838116908a16611dd9565b505f955050505050565b602081811b63ffffffff60201b166032175491901c63ffffffff168160ac1c620fffff16036112af575f1960541c1690565b505f90565b90640b00000001545f1960601c1633146101c1576028548260801c5f1960c01c9081169384928060c01c63ffffffff16928216919083156112735760a01c63ffffffff60201b166028175494821594851580806114c4575b6114b7575f9695969561131e33611e09565b955f985b82846114a6575b80611497575b80611488575b156114585760808b901c5f1960d41c9081168860c01c90911614611452578b61135f89338e611e8f565b915f1960c01c808416921682116113f557506113a7575b5063ffffffff8a60c01c16918261138e575b91611322565b60a09a909a1c63ffffffff60201b166028175499611388565b9a8b6113b5919a929a610e5a565b9a87898c8960ec1c151560f01b6113cb94611ff9565b976113e19060408a901c5f1960c01c1690610e2f565b9760c01c6113ee91610e2f565b975f611376565b939c9a61144a9250611439915061142f61141d8b8f8f908f918e60ec1c151560f01b90611ff9565b9b60408d901c5f1960c01c1690610e2f565b9a60c01c90610e2f565b9960408c901c5f1960c01c16610e5a565b505f9a611388565b91611388565b50505050935095610d879594925061147b91506114758185610e5a565b93610e5a565b925f1960c01c16916120c8565b5063ffffffff81161515611335565b505f1960c01c8c16151561132f565b506113295f1960c01c8c1683611da8565b5050955050505050505f90565b5061130c855f1960c01c8a16611dd9565b905f906032549363ffffffff8560c01c16918215610d995760a09590951c63ffffffff60201b1660321754929492915f905b6115175f1960c01c85168761253f565b80611565575b15610d6d579063ffffffff61154292169063ffffffff60201b9060201b161795610c94565b8260a01c63ffffffff60201b16603217549095909260c01c63ffffffff16611507565b5063ffffffff8116151561151d565b602081811b63ffffffff60201b166028175491901c63ffffffff168160ac1c620fffff16036112af575f1960541c1690565b9060285463ffffffff8160c01c16908115611693578060a01c63ffffffff60201b1660281754939092915f905b82821080611684575b1561167a576001820180921161051457909361162991906125a7620fffff60201b88608c1c1663ffffffff8416178860801c5f1960d41c1660408a901c5f1960c01c908116908b16612570565b8460c01c63ffffffff1692905f1960401c1663ffffffff60c01b8616179183611656575b919390926115d3565b60a09590951c63ffffffff60201b1660281780545f1960201c81169091559461164d565b5050509150602855565b5063ffffffff811615156115dc565b50509050565b640b00000001545f1960601c1633146101c157640200000001546032548060c01c63ffffffff16925f928160801c5f1960c01c908116938493918216908715611a105760a01c63ffffffff60201b166032175497811515806119ff575b6119f2575f969495969460ff61170b33611e09565b9560401c165f0b985b5f1960c01c8b1690611726828661253f565b806119e2575b806119d3575b156119b0578b91908260801c5f1960d41c9081168860c01c909116146119a2575061175e8733846126ef565b905f1960c01c61176f8d8484611f74565b168c5f1960c01c8c1682101561183b5750505061179f87896117ec95946117ad948a60ec1c151560f01b9061270d565b975f1960c01c891690610e2f565b978760401c5f1960c01c16908860c01c6117c78382610e2f565b5f1960c01c83811691161115611822575050505f965b60801c5f1960c01c1690610e2f565b965b63ffffffff8a60c01c1680611809575b979097969596611714565b60a09a909a1c63ffffffff60201b1660321754996117fe565b6118359261182f91610e2f565b90610e5a565b966117dd565b929a9b949993919b989690989795975b5f1960c01c8c169081151580611992575b1561197f575f1960c01c818116906118788d610db68487610da3565b1692831561196a578f90841061194c575b61189987855f1960c01c93611f74565b1615611938576118d96118c86118ba8c8a898e60ec1c151560f01b8961270d565b985f1960c01c8a1690610e2f565b9d8860801c5f1960c01c1690610e2f565b968060401c5f1960c01c908116929160c01c91906118f78484610e2f565b16111561191d575050506119159061190f5f96610e45565b9c610e5a565b9a999361184b565b9161182f979e97611932926119159594610e2f565b95610e5a565b509a9c5050959750505096509290926117ee565b5090945092506001015f1960c01c8111610514578d938f938e611889565b50509a9c5050959750505096509290926117ee565b9a9c5050959750505096509290926117ee565b5060015f1960c01c82161161185c565b9150509790979695966117fe565b5050949591509795610d87975061147b93506119cc9250610e5a565b9282610e2f565b5063ffffffff81161515611732565b5060015f1960c01c8a161161172c565b9750505050505050505f90565b506116f65f1960c01c8a1683611dd9565b50505050505050505f90565b640b00000001545f1960601c1633146101c1576032549063ffffffff8260c01c1690815f1960c01c8260401c166040519063c03ad24360e01b82528060048301525f6024830152602082604481335afa9081156111c0575f91611c54575b611a849250610e2f565b935f1960c01c83169315611c4b5760a01c63ffffffff60201b16603217549483151580611c3a575b611c30575f93919392611abe33611e09565b915f935f965b611ad45f1960c01c8b168361253f565b80611c21575b80611c12575b15611bfa57895f915f1960d41c8660c01c165f1960d41c8360801c1603611be7575b5f1960c01c83811691908c168211611bb35750611b53575b505063ffffffff8960c01c169081611b3a575b611ad4905b919050611ac4565b60a09990991c63ffffffff60201b166032175498611b2d565b611b8361179f878a611b9b94611b73879f97611bab999f989e9d9e610e5a565b9e8a60ec1c151560f01b9061270d565b97610fb88860401c5f1960c01c1660c08a901c610e2f565b9560801c5f1960c01c1690610e2f565b955f89611b1a565b99925050611b8361179f878a611b9b94611bdc979e5f9d9c9d508a60ec1c151560f01b9061270d565b95611ad45f98611b32565b9150611bf48633836126ef565b91611b02565b5050969492939050610d87955061147b915082610e2f565b5063ffffffff81161515611ae0565b505f1960c01c89161515611ada565b9450505050505f90565b50611aac5f1960c01c871685611dd9565b50505050505f90565b90506020823d602011611c89575b81611c6f60209383610dd4565b810103126101c157611c83611a8492610e07565b90611a7a565b3d9150611c62565b908151811015611ca2570160200190565b634e487b7160e01b5f52603260045260245ffd5b60325463ffffffff8160c01c16908115611da3578060a01c63ffffffff60201b166032175493909290915f905b82821080611d94575b15611d8a5760018201809211610514579093611d399190612617620fffff60201b88608c1c1663ffffffff8416178860801c5f1960d41c1660408a901c5f1960c01c908116908b1661347d565b8460c01c63ffffffff1692905f1960401c1663ffffffff60c01b8616179183611d66575b91939092611ce3565b60a09590951c63ffffffff60201b1660321780545f1960201c811690915594611d5d565b5050509150603255565b5063ffffffff81161515611cec565b505050565b601f5f1960c51c8260051c16911691601f5f1960c51c8260051c169116601f03600a0a0291601f03600a0a02111590565b601f5f1960c51c8260051c16911691601f5f1960c51c8260051c169116601f03600a0a0291601f03600a0a021090565b6402000000015460405163a066fae960e01b8152602091821c63ffffffff16600482015291829060249082905f1960601c165afa9081156111c0575f91611e55575b505f1960c01c1690565b90506020813d602011611e87575b81611e7060209383610dd4565b810103126101c157611e8190610e07565b5f611e4b565b3d9150611e63565b91905f1960601c16905f1960c01c90811690611ead9084168261253f565b15611f325750640b0000000154604051630356375b60e51b8152600481019390935260a01c5f1960c01c16602483015260209082908180604481015b03915afa9081156111c0575f91611efe575090565b90506020813d602011611f2a575b81611f1960209383610dd4565b810103126101c157610d8790610e07565b3d9150611f0c565b640b000000015460405163c7e9c1a960e01b815260048101949094525f1960c01c918216602485015260a01c1660448301526020908290818060648101611ee9565b905f1960c01c168160051c5f1960c51c16029190601f165f918203820b0390811315611fd557600a0a025b6001607f1b811015611fc6576001603f1b5f1960801c82161015611fc6575f1960c01c1690565b634a4ef77f60e11b5f5260045ffd5b5f8112611fe3575b50611f9f565b90611ff3915f03600a0a90610db6565b5f611fdd565b9391929093612006613a35565b60ad1b5f1960c01c60ad1b16935f1960541c1693909317600160ac1b17928460f01c60ff166120bb575b92935f1960c01c60ac1b9260ac1b9290921690606c1b175f1960d41c60401b9160401c919091161717604051916372db971760e11b8352600483015260248201526020816044815f335af19081156111c0575f9161208c575090565b90506020813d6020116120b3575b816120a760209383610dd4565b810103126101c1575190565b3d915061209a565b92600160ed1b1792612030565b9291909160c01b9260801b9160401b905f1960c01c1617171790565b5f905f1960c01c81166120f68161349f565b1561253057612104826134c2565b60ff8260f01c16806123cb575b505f1960d41c8260801c169260285463ffffffff8160201c169081156123bd575b5063ffffffff612140613513565b91169063ffffffff60201b9060201b16175f1960c01c8460401c1694600f8560ac1c1695817fb6726367238b3876d22b2b1331db02f672a448c80681d6c12e69752878eedc0060206121948a878a87613596565b604051908152a25f95868160b01c5f1960c01c811661235057505083836121ba92613640565b9081156123435760028814612334578160401c5f1960c01c1690811415976003146123015750905b6402000000015463ffffffff61220b604083811c60ff165f0b9086901c5f1960c01c1689611f74565b9160201c16333b156101c15760405163036cae5560e61b8152600481019390935260248301525f1960c01c1660448201525f8160648183335af180156111c0576122ec575b506028548060201c63ffffffff16939084156122ca57602863ffffffff60201b8660201b16175463ffffffff60201b9060201b169063ffffffff60201b1916176028555b5090608c1b63ffffffff60ac1b16905f1960541c16179063ffffffff8416156122c057610d8793613914565b610d8793506138d0565b63ffffffff811694506122dc85610c94565b905f1960201b1617602855612294565b6122f99193505f90610dd4565b5f915f612250565b9195505f5160206143b05f395f51905f5294506020935061232a9291905f1960c01c1690613567565b604051908152a290565b6334f297f160e21b5f5260045ffd5b5050505050505050600190565b925097909296506123ae578463ffffffff61236b92166135cd565b9463ffffffff861615612393575b63ffffffff86166121e25763d7170efd60e01b5f5260045ffd5b94506123a8848260d01c63ffffffff166135cd565b94612379565b6306f5352760e41b5f5260045ffd5b63ffffffff9150165f612132565b60011c607f16156123dd575b5f612111565b63ffffffff6402000000015460201c1660405163a066fae960e01b8152816004820152602081602481335afa9081156111c0575f916124f6575b506040516377ec6f6960e11b81526004810192909252601f81169060051c5f1960c51c16602083602481335afa9283156111c0575f936124c2575b508260ee1c6103fc169260f01c60ff168015600491850491909114171561051457601f8516928560051c5f1960c51c1692906103e8908101908110610514576103e8926124a592601f03600a0a02610da3565b0491601f03600a0a02106123d757630c484f3b60e11b5f5260045ffd5b9092506020813d6020116124ee575b816124de60209383610dd4565b810103126101c15751915f612452565b3d91506124d1565b90506020813d602011612528575b8161251160209383610dd4565b810103126101c15761252290610e07565b5f612417565b3d9150612504565b630a05e72f60e11b5f5260045ffd5b601f5f1960c51c8260051c16911691601f5f1960c51c8260051c169116601f03600a0a0291601f03600a0a02101590565b5f5160206143b05f395f51905f52929360209261259e92612592818389613a61565b5f1960c01c1690613ac2565b604051908152a2565b81906125b282610c94565b63ffffffff8083169116145f146125e7575f1960c01b9260201b63ffffffff60201b1660281792909255905f1960201b161790565b602081811c63ffffffff1663ffffffff60201b9490911b9384166028175563ffffffff60201b1916909117919050565b819061262282610c94565b63ffffffff8083169116145f14612657575f1960c01b9260201b63ffffffff60201b1660321792909255905f1960201b161790565b602081811c63ffffffff1663ffffffff60201b9490911b9384166032175563ffffffff60201b1916909117919050565b909161269281610c94565b63ffffffff8084169116145f146126c6575f1960c01b8160201b63ffffffff60201b16909317929092555f1960201b161790565b63ffffffff8260201c169060201b9263ffffffff60201b8416175563ffffffff60201b19161790565b91905f1960601c16905f1960c01c90811690611ead90841682611da8565b939192909361271a613a09565b60ad1b5f1960c01c60ad1b16935f1960541c1693909317928460f01c60ff1661279a575b92935f1960c01c60ac1b9260ac1b9290921690606c1b175f1960d41c60401b9160401c919091161717604051916312189f6b60e11b8352600483015260248201526020816044815f335af19081156111c0575f9161208c575090565b92600160ed1b179261273e565b5f1960c01c8111610df35760051b60200190565b906127c5826127a7565b6127d26040519182610dd4565b82815280926127e3601f19916127a7565b0190602036910137565b805115611ca25760200190565b8051821015611ca25760209160051b010190565b939290919261282a63ffffffff61282486610c94565b166127bb565b6028545f9590935f1960c01c81166129b7575063ffffffff8460c01c1693841561299a5760a01c63ffffffff60201b1660281754965b5f935b8860401c5f1960c01c1680151580612985575b80612976575b15612927575f1960c01c831660808b901c5f1960d41c16146128d5575b5060018801809811610514578763ffffffff88161115612863578860a01c63ffffffff60201b16602817549860c01c63ffffffff169550612863565b90946129209161290290620fffff60201b608c8d901c1663ffffffff8a1617905f1960c01c8d1690613ac2565b61291a63ffffffff61291384610cac565b16876127fa565b52610c94565b935f612899565b5097929650929450508060801c63ffffffff60201b169263ffffffff16929092179160401c5f1960c01c1615905061296b575b60201b17612967826127ed565b5290565b505f1960c01c61295a565b5063ffffffff8816891061287c565b5063ffffffff841663ffffffff871610612876565b5091955093505f1960c01c60201b925061296791508390506127ed565b96935063ffffffff871693602863ffffffff60201b8960201b1617549763ffffffff808a60a01c169160201c1614612860575b6398a9acb360e01b5f5260045ffd5b9392909192612a0f63ffffffff61282486610c94565b6032545f9590935f1960c01c8116612b12575063ffffffff8460c01c1693841561299a5760a01c63ffffffff60201b1660321754965b5f935b8860401c5f1960c01c1680151580612afd575b80612aee575b15612927575f1960c01c831660808b901c5f1960d41c1614612aba575b5060018801809811610514578763ffffffff88161115612a48578860a01c63ffffffff60201b16603217549860c01c63ffffffff169550612a48565b9094612ae79161290290620fffff60201b608c8d901c1663ffffffff8a1617905f1960c01c8d1690613ac2565b935f612a7e565b5063ffffffff88168910612a61565b5063ffffffff841663ffffffff871610612a5b565b96935063ffffffff871693603263ffffffff60201b8960201b1617549763ffffffff808a60a01c169160201c1614612a45576398a9acb360e01b5f5260045ffd5b5f905f1960c01c8116612b658161349f565b1561253057612b73826134c2565b60ff8260f01c1680612e05575b505f1960d41c8260801c169260325463ffffffff8160201c16908115612df7575b5063ffffffff612baf613513565b91169063ffffffff60201b9060201b16175f1960c01c8460401c1694600f8560ac1c1695817f994d1f10d7d73f3765b557bce9826b2fafd1bad3862fa6192211b39a121838156020612c038a878a87613596565b604051908152a25f95868160b01c5f1960c01c8116612d995750508383612c2992613b40565b9081156123435760028814612334578160401c5f1960c01c169081141597600314612d705750905b6402000000015463ffffffff612c7a604083811c60ff165f0b9086901c5f1960c01c1689611f74565b9160201c16333b156101c15760405163036cae5560e61b8152600481019390935260248301525f1960c01c1660448201525f8160648183335af180156111c057612d5b575b506032548060201c63ffffffff1693908415612d3957603263ffffffff60201b8660201b16175463ffffffff60201b9060201b169063ffffffff60201b1916176032555b5090608c1b63ffffffff60ac1b16905f1960541c16179063ffffffff841615612d2f57610d8793613edd565b610d879350613e99565b63ffffffff81169450612d4b85610c94565b905f1960201b1617603255612d03565b612d689193505f90610dd4565b5f915f612cbf565b9195505f5160206143d05f395f51905f5294506020935061232a9291905f1960c01c1690613567565b925097909296506123ae578463ffffffff612db49216613aeb565b9463ffffffff861615612ddc575b63ffffffff8616612c515763d7170efd60e01b5f5260045ffd5b9450612df1848260d01c63ffffffff16613aeb565b94612dc2565b63ffffffff9150165f612ba1565b60011c607f1615612e17575b5f612b80565b63ffffffff6402000000015460201c1660405163a066fae960e01b8152816004820152602081602481335afa9081156111c0575f91612f30575b506040516377ec6f6960e11b81526004810192909252601f81169060051c5f1960c51c16602083602481335afa9283156111c0575f93612efc575b508260ee1c6103fc169260f01c60ff168015600491850491909114171561051457601f8516928560051c5f1960c51c1692906103e8908103908111610514576103e892612edf92601f03600a0a02610da3565b0491601f03600a0a0211612e1157630c484f3b60e11b5f5260045ffd5b9092506020813d602011612f28575b81612f1860209383610dd4565b810103126101c15751915f612e8c565b3d9150612f0b565b90506020813d602011612f62575b81612f4b60209383610dd4565b810103126101c157612f5c90610e07565b5f612e51565b3d9150612f3e565b612f7381613fd2565b8060401c5f1960c01c169182612f8857505050565b612fa6925f1960c01c808316939260401c5f1960d41c16921661347d565b565b5f1960c01c169060401b1790606c1b1790565b5f1960c01c60b01b8160101c1692600f60ac1b9060ac1b169160801b905f1960801c9060401c1617171790565b612ff181614115565b8060401c5f1960c01c16918261300657505050565b612fa6925f1960c01c808316939260401c5f1960d41c169216612570565b9061304a63ffffffff612824610c9482861695637fffffff600182169160011c16610cc3565b925f915f1960c01c81166132a3575060285463ffffffff8160c01c169081156132935760a01c63ffffffff60201b1660281754949091905b640b00000001545f92905f1960601c169183915f1960c01c8916906130a685611e09565b955b60408b901c5f1960c01c1615158061328a575b15613185578a5f1960c01c80821690851680820361311657505090610fb888886130e494611e8f565b965b8989106130f4575b966130a8565b5060a08a901c63ffffffff60201b16602817549960c01c63ffffffff166130ee565b93945095999050600181018091116105145780996001808316145f1461315c57505060401b5f1960c01c60401b161760801b925b9061315686868c611e8f565b966130e6565b929092179060401b5f1960c01c60401b16179390849061317f9060011c856127fa565b5261314a565b9298509893509193505f1960c01c8360401c161595865f1461325557600181018091116105145780946001808316145f14613228575060011c9160018301809311610514575f1960c01c169060401b5f1960c01c60401b161760801b906131ec90876127fa565b525b819315613202575b505050612967826127ed565b9160201b63ffffffff60201b16179060601c63ffffffff60401b161790505f80806131f6565b925f1960c01c16929092179060401b5f1960c01c60401b16179061324f9060011c876127fa565b526131ee565b9391505060018084161461326a575b506131ee565b8260011c600181018091116105145761328390876127fa565b525f613264565b508989106130bb565b5050929150505f612967826127ed565b9363ffffffff851690602863ffffffff60201b8760201b1617549563ffffffff808860a01c169160201c16036129ea57919091613082565b9061330163ffffffff612824610c9482861695637fffffff600182169160011c16610cc3565b925f915f1960c01c8116613445575060325463ffffffff8160c01c169081156132935760a01c63ffffffff60201b1660321754949091905b640b00000001545f92905f1960601c169183915f1960c01c89169061335d85611e09565b955b60408b901c5f1960c01c1615158061343c575b15613185578a5f1960c01c8082169085168082036133cd57505090610fb8888861339b946126ef565b965b8989106133ab575b9661335f565b5060a08a901c63ffffffff60201b16603217549960c01c63ffffffff166133a5565b93945095999050600181018091116105145780996001808316145f1461341357505060401b5f1960c01c60401b161760801b925b9061340d86868c6126ef565b9661339d565b929092179060401b5f1960c01c60401b1617939084906134369060011c856127fa565b52613401565b50898910613372565b9363ffffffff851690603263ffffffff60201b8760201b1617549563ffffffff808860a01c169160201c16036129ea57919091613339565b5f5160206143d05f395f51905f52929360209261259e92612592818389613a61565b600a8160051c5f1960c51c160615801591906134b9575090565b601f9150161590565b60401c5f1960c01c16801561350457640b000000015460a01c5f1960c01c168015610dc05790065f1960c01c166134f557565b6390ac740b60e01b5f5260045ffd5b633ec958c360e11b5f5260045ffd5b6408000000015461352b8160c01c620fffff16610c94565b906210000063ffffffff83161461355e575b620fffff60c01b19168160c01b63ffffffff60c01b16176408000000015590565b6001915061353d565b9160801b5f1960c01c60801b169160401b5f1960c01c60401b1691909117905f1960c01c1617600360c01b1790565b9260c01b60ff60c01b169160801b5f1960c01c60801b16919091179160401b5f1960c01c60401b1691909117905f1960c01c161790565b9063ffffffff82166135dd575090565b8160201b63ffffffff60201b16602817548060401c5f1960c01c161591821561360a575b50506112af5790565b5f1960c51c600583811c8216601f9485168503600a90810a919091029184901c909216928416909303900a021190505f80613601565b60325490938160c01c63ffffffff1692908560401c5f1960c01c908116919087169085156138c7578460a01c63ffffffff60201b16603217549661368a5f1960c01c891684611dd9565b6138bd575f96919695939295906136a033611e09565b925b6136b25f1960c01c8b168961253f565b806138ae575b8061389f575b1561386c575f958b5f1960c01c891660808d901c5f1960d41c160361385f575060ff8c60f01c1615613850578b965b5f1960c01c81811690881681116137f057808d916137c5575b6137299596979899505f1960c01c8260401c16809110613784575b505050612617565b8860c01c63ffffffff1697905f1960401c1663ffffffff60c01b8a16179688613760575b6136b2905b9795949392919890506136a2565b60a09990991c63ffffffff60201b1660321780545f1960201c81169091559861374d565b6137bd9261379191610e5a565b620fffff60201b82608c1c1663ffffffff861617918060801c5f1960d41c1691905f1960c01c1661347d565b5f8b81613721565b96978886976137299787856137dd886137e497610e5a565b9e88614232565b9594508d989796613706565b505097999561380f858495849c956136b2958b61381f968c9b9c614232565b948760401c5f1960c01c16610e5a565b955f965f1960c01c60401b199060401b911617998a5f1960201c16603263ffffffff60201b8c60201b161755613752565b633157f54960e11b5f5260045ffd5b96506136ed85338d6126ef565b50505050939594509150506032555f1960c01c81161561389957905f1960c01c60401b19169060401b1790565b50505f90565b5063ffffffff811615156136be565b505f1960c01c851615156136b8565b5095505050505050565b95505050505050565b91906028549263ffffffff8460c01c1680156138f057612fa69450613914565b509150602863ffffffff60201b8360201b16175560c01b905f1960401c1617602855565b8060201b63ffffffff60201b166028175492905f5b6139395f1960c01c861687611da8565b806139fa575b1561396657508360a01c63ffffffff60201b16602817549360c01c63ffffffff1690613929565b919294509250602863ffffffff60201b8260201b1617805463ffffffff60c01b1963ffffffff60c01b8760c01b16911617905560e01b905f1960201c8360c01b16905f1960401c161717602863ffffffff60201b8460201b16175563ffffffff81166139d0575050565b60201b63ffffffff60201b1660281780545f1960201c169160e01b5f1960201c1916919091179055565b5063ffffffff8216151561393f565b6028545f9063ffffffff8160c01c16613a20575090565b60a01c63ffffffff60201b1660281754919050565b6032545f9063ffffffff8160c01c16613a4c575090565b60a01c63ffffffff60201b1660321754919050565b91613a7b9160ff6402000000015460401c165f0b91611f74565b90333b156101c157604051632a82674b60e11b8152915f9183918291613aa5919060048401610e18565b038183335af180156111c057613ab85750565b5f612fa691610dd4565b9160801b5f1960c01c60801b169160401b5f1960c01c60401b1691909117905f1960c01c161790565b9063ffffffff8216613afb575090565b8160201b63ffffffff60201b16603217548060401c5f1960c01c161591908215613b285750506112af5790565b613b3992505f1960c01c1690611dd9565b5f80613601565b6028545f1960c01c8083169592948260c01c63ffffffff16949293918660401c16908515613e8f578460a01c63ffffffff60201b166028175496613b8a895f1960c01c8a16611dd9565b613e83575f96929695939592613b9f33611e09565b945b5f1960c01c8a16613bb2818d611da8565b80613e74575b80613e65575b15613e36575f905f1960c01c891660808d901c5f1960d41c1603613e225760ff8560f01c1615613850578b905b5f1960c01c83811691908d168211613ce6575080613cb8575b613c2694939291908160401c5f1960c01c16908111613c77575b5050506125a7565b8860c01c63ffffffff1697905f1960401c1663ffffffff60c01b8a16179688613c53575b96979097613ba1565b60a09990991c63ffffffff60201b1660281780545f1960201c811690915598613c4a565b613cb092613c8491610e5a565b620fffff60201b82608c1c1663ffffffff861617918060801c5f1960d41c1691905f1960c01c16612570565b5f8b81613c1e565b969a90613cda89613ccf85613c2698979695610e5a565b9d8987858b886142c2565b97909192939450613c04565b9b97613d0e93508991508786613cfd94898c6142c2565b9560408c901c5f1960c01c16610e5a565b640b00000001545f9a9060a01c5f1960c01c908116908316109081613dfa575b5015613db457613d6c9291906125a790620fffff60201b608c8e901c1663ffffffff8516179060808e901c5f1960d41c16905f1960c01c8f16612570565b8860c01c63ffffffff1697905f1960401c1663ffffffff60c01b8a1617968815613c4a5760a09990991c63ffffffff60201b1660281780545f1960201c811690915598613c4a565b5f1960201c9060401b9081165f1960c01c5f1960a01c60801b018c16178360201b63ffffffff60201b1660281755995f1960c01c60401b19169099179890979096613c4a565b9050613e1a60ff6402000000015460401c165f0b835f1960c01c93611f74565b16155f613d2e565b90508a613e30883383611e8f565b91613beb565b50602855509497509395505050505f1960c01c821615905061389957905f1960c01c60401b19169060401b1790565b5063ffffffff83161515613bbe565b505f1960c01c8a161515613bb8565b96505050945050505090565b5050945050505090565b91906032549263ffffffff8460c01c168015613eb957612fa69450613edd565b509150603263ffffffff60201b8360201b16175560c01b905f1960401c1617603255565b8060201b63ffffffff60201b166032175492905f5b613f025f1960c01c86168761253f565b80613fc3575b15613f2f57508360a01c63ffffffff60201b16603217549360c01c63ffffffff1690613ef2565b919294509250603263ffffffff60201b8260201b1617805463ffffffff60c01b1963ffffffff60c01b8760c01b16911617905560e01b905f1960201c8360c01b16905f1960401c161717603263ffffffff60201b8460201b16175563ffffffff8116613f99575050565b60201b63ffffffff60201b1660321780545f1960201c169160e01b5f1960201c1916919091179055565b5063ffffffff82161515613f08565b63ffffffff81168160401c5f1960d41c1681158080614108575b6140d8576140c9578260201b63ffffffff60201b1660321754928360401c5f1960c01c161580156140ed575b806140e0575b6140d85760201c63ffffffff168360ac1c620fffff16036140c9578260801c5f1960d41c16036140ba5763ffffffff60201b8260c01c908116603217805463ffffffff60c01b191663ffffffff60c01b851617905561408c919063ffffffff16614092575b60328054612687565b60325590565b8260a01c63ffffffff60201b1660321780545f1960201c165f1960201c198516179055614083565b6315d7ede560e31b5f5260045ffd5b631e4c198360e01b5f5260045ffd5b505050505f90565b50600181606c1c1461401e565b508060201c63ffffffff168460ac1c620fffff161415614018565b50600184606c1c14613fec565b63ffffffff81168160401c5f1960d41c1681158080614225575b6140d8576140c9578260201b63ffffffff60201b1660281754928360401c5f1960c01c1615801561420a575b806141fd575b6140d85760201c63ffffffff168360ac1c620fffff16036140c9578260801c5f1960d41c16036140ba5763ffffffff60201b8260c01c908116602817805463ffffffff60c01b191663ffffffff60c01b85161790556141cf919063ffffffff166141d5575b60288054612687565b60285590565b8260a01c63ffffffff60201b1660281780545f1960201c165f1960201c1985161790556141c6565b50600181606c1c14614161565b508060201c63ffffffff168460ac1c620fffff16141561415b565b50600184606c1c1461412f565b936142666142585f5160206143f05f395f51905f5295988886866040989a9b979b61270d565b925f1960c01c841690610e2f565b96620fffff60201b86608c1c169063ffffffff16179061428461435b565b84519384528660a01b5f1960c01c60a01b169160601b91909117602092831b171790820152608093841c5f1960d41c9081169590941c90931692a390565b936142f76142e75f5160206143f05f395f51905f5295988886866040989b979a611ff9565b9283851c5f1960c01c1690610e2f565b96620fffff60201b87608c1c169063ffffffff16179061431561435b565b84519384528760a01b5f1960c01c60a01b169260601b92909217602091821b17909117600160e01b1790820152608093841c5f1960d41c9081169590941c90931692a390565b6408000000015463ffffffff8160d41c16630fffffff81145f146143a057506001905b63ffffffff60d41b19168160d41b63ffffffff60d41b16176408000000015590565b6143a990610c94565b9061437e56fe99966d65b8eddb61874f6af338e41fb8d7d87838b527761d9a54c8179ad754f13b52ea198de442a281d40e329a98fb523c624dd8518543c0a6fa2d73a6cc484518552bd75bd768d6b943973270f4b4cb69370ade12f8e60e7cd6d5019b13467d", - "nonce": "0x1", - "storage": { - "0x28": "0x3700000000000000000000000000000000000000090000003d", - "0x32": "0x19000000000000000000000000000000000000001100000029", - "0x100000032": "0x800000010095f20000000059b00000000000f424000000000005146a2", - "0x200000001": "0xb0e030000000400000001", - "0x700000032": "0x1e00000022095ef0000000059b00000000000f42400000000000513a22", - "0x800000001": "0x1074f09648000000000000000000000000000000000000000000000000", - "0x800000032": "0x1500000001096360000000005e000000008ff1f9c00000000000514402", - "0xb00000001": "0x7a1205e3ae52eba0f9740364bd5dd39738e1336086a8b", - "0xc00000032": "0x1900000024096480000000005e000000001200278000000000005125a2", - "0x1000000032": "0x10000001d095f30000000059b00000000000f42400000000000514ac2", - "0x1500000032": "0x2200000008095f10000000059b00000000000f42400000000000514262", - "0x1600000028": "0x2e00000030095f90000000005e00000000908a9040000000000050ee02", - "0x1900000032": "0xc096460000000005e000000004817816000000000005120a2", - "0x1b00000028": "0x360000002e095e50000000059b00000000000f4240000000000050f362", - "0x1e00000032": "0x2400000007095ee0000000059b00000000000f42400000000000081f01", - "0x2200000032": "0x700000015095f00000000059b00000000000f42400000000000513e42", - "0x2400000032": "0xc0000001e096440000000005e000000006c17d0600000000000512be2", - "0x2e00000028": "0x1b00000016095e60000000059b00000000000f4240000000000050ef42", - "0x3000000028": "0x1600000018095e70000000059b00000000000f4240000000000050eb22", - "0x3500000028": "0x3700000039096410000000005e000000001207c8a00000000000511562", - "0x3600000028": "0x390000001b095e40000000059b00000000000f4240000000000050f7a2", - "0x3700000028": "0x35096450000000005e00000000481f22800000000000511aa2", - "0x3900000028": "0x3500000036096330000000005e000000006c4597200000000000510b42" - } - } - }, - "post": { - "Rex5": [ - { - "indexes": { - "data": 0, - "gas": 0, - "value": 0 - }, - "hash": "0x9e34ed9cb72c8d145461686d3393a1d4eec33f06d0fb221f3802e2d3cbfdf857", - "logs": "0x42335aab92f4801a8ca1d1617cb19f834135d437341ed5ed1f010cdb67c80285", - "megaGasUsed": 456913, - "megaStatus": "success" - } - ] - }, - "transaction": { - "type": 2, - "data": [ - "0xd803a4cf000000000000000000000000000000000000000000000000000000000000005e0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000c00000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b06870056000000000000000000000000481f22800000000000511b82000096450000003700000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b068700560000000000000000000000001207c8a000000000005116e2000096410000003500000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b068700560000000000000000000000006c3df6000000000000510fa2000096330000003900000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b068700560000000000000000000000009082ef20000000000050f4a2000095f90000001600000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b06870096000000000000000000000000481781600000000000512182000096460000001900000000000000000010f12fe484ab504276a454e750f54a9b7fbe5b068700960000000000000000000000008fea58a000000000005148620000963600000008" - ], - "gasLimit": [ - "0x28a640" - ], - "gasPrice": null, - "nonce": "0x6c451b", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x3416869d6f3de7d2ae20660d8041670592877c79", - "to": "0x5e3ae52eba0f9740364bd5dd39738e1336086a8b", - "value": [ - "0x0" - ], - "maxFeePerGas": "0x124f80", - "maxPriorityFeePerGas": "0x0", - "initcodes": null, - "accessLists": [ - [] - ], - "authorizationList": null, - "blobVersionedHashes": [], - "maxFeePerBlobGas": null - }, - "out": "0x", - "megaEnv": { - "bucketCapacities": [], - "oracleStorage": [] - } - } -} \ No newline at end of file diff --git a/bench/replay/fixtures/medium_call.json b/bench/replay/fixtures/medium_call.json deleted file mode 100644 index 52171c0a6..000000000 --- a/bench/replay/fixtures/medium_call.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "replay_0x41d34e7e13dfe0f85da9d407e2b2c381955d8c7eed428b17dc82327b2616b000": { - "_info": null, - "env": { - "currentChainID": "0x10e6", - "currentCoinbase": "0x4200000000000000000000000000000000000011", - "currentDifficulty": "0x0", - "currentGasLimit": "0x2540be400", - "currentNumber": "0x1154a2d", - "currentTimestamp": "0x6a277000", - "currentBaseFee": "0xf4240", - "currentRandom": "0x5cd8791a477b467456670744425e11d5bd91fd54575d6d3bf80d761ab39d957f", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x14112799a39f2905b901067d3cd4a1f63c1cebda": { - "balance": "0x2bb077a7d9ab1a", - "code": "0x", - "nonce": "0x195cb", - "storage": {} - }, - "0x4200000000000000000000000000000000000011": { - "balance": "0x5125353fb2d2cd25", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x4200000000000000000000000000000000000019": { - "balance": "0x303ca0651aedfa080", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001a": { - "balance": "0x38dd0ce3ffcb29e", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x420000000000000000000000000000000000001b": { - "balance": "0x0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a", - "nonce": "0x0", - "storage": {} - }, - "0x681e908b8ab57c49c74d770f369754ccc3e1ae09": { - "balance": "0x0", - "code": "0x6080806040526004361015610180575b503461017c57335f908152600860205260409020546001600160a01b03811690811561016d5760601b6bffffffffffffffffffffffff1916906100555f3560e01c613552565b6004361180159061015e575b61014f575f52600760205260405f209060ff604051926100808461264a565b54818116845260081c16602083015260045b36811061009b57005b803560ff81169060ff8551168211610140576100c266ffffffffffffff8260081c16613569565b916100cc83613595565b8085179266ffffffffffffff806100e881875460081c16613569565b169116111561013857816100fc91876135c4565b156101295760ff191690555b6020810180911115610092575b634e487b7160e01b5f52601160045260245ffd5b637257d48760e11b5f5260045ffd5b505050610108565b633628a81b60e01b5f5260045ffd5b631182458b60e01b5f5260045ffd5b50602060031936081515610061565b630a02739760e41b5f5260045ffd5b5f80fd5b5f3560e01c90816301ffc9a71461252457508063186071b81461247457806318892f46146124345780631d14159e14611ec05780631e2eaeaf14611ea4578063248a9ca314611e725780632f2ff15d14611e35578063313ce56714611e1a5780633549bd0414611de857806335fd631a14611d9257806336568abe14611d4e57806338a43b0714611c5d5780633943262914611bb35780633a0416e514611b815780633f4e425114611b645780634312c51414611a7057806350e2230f14611a3257806353bfbb751461175b5780635abb1580146116db57806375b238fc146116a157806378ce3ae11461162b578063790d7aae146115a057806388f3543a146114fd578063893ddf87146114ba57806389f7d2cc1461145d57806391d14854146114155780639214554d146113b05780639be7621614610e0a5780639eaa1b0914610dee578063a217fddf14610dd4578063a9faa07c14610d42578063acf0ebbb14610c57578063af0e42f414610b45578063b5e4b81314610ad1578063ba3f48e4146108c5578063cb684f6714610773578063d4a34be7146106c2578063d547741f1461067e578063dbd035ff14610606578063e84afaeb14610531578063eeb8e988146104cd5763eff773691461035a575f61000f565b3461017c57604036600319011261017c576024356001600160401b03811161017c5761038a903690600401612577565b610395600435613552565b33915f5b8281106103a257005b6103b56103b0828585613037565b6127c4565b6001600160a01b038082165f81815260086020526040902054909392911683146104be573383146104af575f8091604051602081019063d117ca5f60e01b82523360248201526024815261040a604482612665565b51915afa3d156104a7573d9061041f8261273d565b9161042d6040519384612665565b82523d5f602084013e5b1561017c5760208180518101031261017c576020015180159081150361017c5761017c575f82815260086020526040812080546001600160a01b0319168717905560019233917fb376638bce241c897c2642b8d44ad3b7102fb88001ca080fc1d68683803403fd9080a301610399565b606090610437565b63e200a9fd60e01b5f5260045ffd5b6382ba25e560e01b5f5260045ffd5b3461017c57602036600319011261017c5760406104f36004356104ee61323f565b61325e565b8151602080825282516001600160a01b0390811682840152908301511681840152910151606080830152819061052d9060808301906125a7565b0390f35b3461017c57602036600319011261017c576004356001600160401b03811161017c57610561903690600401612577565b905f5b82811061056d57005b6001600160a01b036105836103b0838686613037565b16903382146104be575f828152600860205260409020546001600160a01b031633036105f3575f82815260086020526040812080546001600160a01b031916905560019233917fe11732b8fc05ea8677eaa2d4c9b2749a7a7a259ddcd42d049cec9895bcd82f249080a301610564565b63294f8a1760e01b5f523360045260245ffd5b3461017c57602036600319011261017c576004356001600160401b03811161017c57610636903690600401612577565b6040519160408360208152836020820152019160051b8301916020806040850193925b8335548152019101908483821015610675575060208091610659565b60408186030190f35b3461017c57604036600319011261017c576106c060043561069d6125e1565b906106bb6106b6825f525f602052600160405f20015490565b61339d565b61345d565b005b3461017c57604036600319011261017c576004356106de6125e1565b6106fc826106f7815f52600260205260405f2054151590565b612eec565b5f828152600660205260409020546107209033906001600160a01b0316811461300f565b5f82815260056020526040812080546001600160a01b0319166001600160a01b039390931692831790559091907f0e105a17cc4a6874ea7675f4d5a22c1d7ff7561b56c38f6180bae5e586edfc379080a3005b3461017c57602036600319011261017c576004356001600160401b03811161017c576107a3903690600401612577565b906107ad82612726565b916107bb6040519384612665565b808352601f196107ca82612726565b015f5b8181106108ae5750505f5b81811061086757836040518091602082016020835281518091526020604084019201905f5b81811061080b575050500390f35b919350916020608082610859600194885166ffffffffffffff606080926001600160401b03815116855261ffff602082015116602086015261ffff6040820151166040860152015116910152565b0194019101918493926107fd565b8061089261088d61087b6001948688613037565b3561088461320b565b506104ee61323f565b6136b0565b61089c828761282b565b526108a7818661282b565b50016107d8565b6020906108b961320b565b828288010152016107cd565b3461017c57606036600319011261017c576004356024356001600160401b03811161017c576108f8903690600401612577565b916044356001600160401b03811161017c573660238201121561017c57806004013561092381612726565b916109316040519384612665565b8183526024602084019260051b8201019036821161017c5760248101925b828410610a91575050505061096382613552565b8051840361017c573393925f5b84811061097957005b6001600160a01b0361098f6103b0838886613037565b165f818152600860205260409020549091906001600160a01b031682146104be573382146104af5760405160208101904682523060408201528660608201528360808201523360a082015260a081526109e960c082612665565b5190207f19457468657265756d205369676e6564204d6573736167653a0a3332000000005f52601c52610a36610a2d603c5f20610a26848861282b565b519061389a565b909291926138d4565b6001600160a01b0316820361017c575f82815260086020526040812080546001600160a01b0319168917905560019233917fb376638bce241c897c2642b8d44ad3b7102fb88001ca080fc1d68683803403fd9080a301610970565b83356001600160401b03811161017c5782013660438201121561017c57602091610ac683923690604460248201359101612758565b81520193019261094f565b3461017c57602036600319011261017c57610aea61320b565b506080610afe61088d6004356104ee61323f565b610b43604051809266ffffffffffffff606080926001600160401b03815116855261ffff602082015116602086015261ffff6040820151166040860152015116910152565bf35b3461017c57606036600319011261017c576004356024356001600160801b0381169081810361017c57604435906001600160801b0382169283830361017c57610b9d856106f7815f52600260205260405f2054151590565b5f85815260066020526040902054610bc19033906001600160a01b0316811461300f565b8381101561017c577f9b53e4468e38fe13fcc9587da14596e3de9b2d184e370ac6a3e377e73c13520f9360405191610bf88361264a565b825260208201908152855f5260046020526001600160801b0360405f20925116906001600160801b0319905160801b16179055610c52604051928392839092916001600160801b0360209181604085019616845216910152565b0390a2005b3461017c57604036600319011261017c576004356024356001549081808210911802189081808210911802811880910390610c9182612726565b91610c9f6040519384612665565b808352610cab81612726565b602084019290601f19013684375f5b828110610d05578385604051918291602083019060208452518091526040830191905f5b818110610cec575050500390f35b8251845285945060209384019390920191600101610cde565b600190815f528083017fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf60154610d3b828861282b565b5201610cba565b3461017c57602036600319011261017c57600435610d6f816106f7815f52600260205260405f2054151590565b5f81815260066020526040902054610d939033906001600160a01b0316811461300f565b5f81815260056020526040812080546001600160a01b03191690557f7fe2baa02b99750768e2fd8894fda836daad39f04f902fb29a6f6cdc0fb8ebff9080a2005b3461017c575f36600319011261017c5760206040515f8152f35b3461017c575f36600319011261017c5760206040516127108152f35b3461017c57604036600319011261017c57610e236125cb565b602435906001600160401b03821161017c573660238301121561017c576001600160401b0382600401351161017c5736602460608460040135028401011161017c57336001600160a01b038216148015611379575b1561136a576001600160a01b038181165f818152600860205260409020549091160361016d5760018060a01b0381165f52600760205260405f209060ff60405192610ec28461264a565b54818116845260081c1660208301525f925b80600401358410610ee157005b83610ef7610f84958360040135602485016131ed565b35610f11816106f7815f52600260205260405f2054151590565b805f52600360205280610f6c6040805f20610f536002835192610f338461262f565b80546001600160a01b039081168552600182015416602085015201612686565b9182910152602001518060601c918160141a9160151a90565b98909290916001600160a01b03888116911614612f06565b610fa16020610f9b858760040135602489016131ed565b016131fd565b610fb86040610f9b86886004013560248a016131ed565b9060ff821660048110156113475760ff8951169060ff83169182116101405760ff8a5116821480611359575b611347578160ff8616148061133b575b61132857611002858a6132f0565b61100c848b6132f0565b916110248d8860ff60018184161b8616161515612f20565b6001811b9360ff85851616611313575050908b60ff9261106782898e61105e61105284848460601b1761337c565b8c8c8460601b176132c7565b60601b1761329d565b878c606081901b808317908917036112c0578593945060601b175f52600b602052816001818060405f20981695161b16191616176080171660ff198254161790555b6040516110cd816110bf85858c602085016127ec565b03601f198101835282612665565b845f526003602052600260405f2001908051906001600160401b0382116112ac576110f883546125f7565b601f811161125b575b50602090601f83116001146111ca57928260019a9b9c9d96937ffb7baee2e9eb6f67002dd5cd410f7b5c441b28effa9378cb3ff55abca631828998969361119f965f926111bf575b50505f19600383901b1c1916908b1b1790555b808b60601b175f52600a60205260405f2054156111ab575b6040805160ff9586168152958516602087015290841690850152909116606083015281906080820190565b0390a201929190610ed4565b6111b9818c60601b176137a9565b50611174565b015190508f80611149565b90601f19831691845f52815f20925f5b8181106112435750937ffb7baee2e9eb6f67002dd5cd410f7b5c441b28effa9378cb3ff55abca631828998969360019c9d9e9f9895938d938361119f99961061122b575b505050811b01905561115c565b01515f1960f88460031b161c191690558f808061121e565b929360206001819287860151815501950193016111da565b8281111561110157835f5260205f20601f840160051c90602085106112a4575b81601f9101920160051c03905f5b828110611297575050611101565b5f82820155600101611289565b5f915061127b565b634e487b7160e01b5f52604160045260245ffd5b91859291839260601b175f52600b6020528160018160405f2096161b16191616608017168319825416179055838a60601b175f52600b6020528160405f209316176080171660ff198254161790556110a9565b6318ed9cc160e21b5f5260045260245260445ffd5b85631e174bbd60e01b5f5260045260245ffd5b508060ff8c1614610ff4565b630490ed8f60e41b5f5260045260245ffd5b5060ff60208b015116811015610fe4565b6348e56b6760e01b5f5260045ffd5b50335f9081527f7d7ffb7a348e1c6a02869081a26547b49160dd3df72d1d75a570eb9b698292ec602052604090205460ff16610e78565b3461017c57602036600319011261017c576004355f908152600360205260409020805460018201546001600160a01b039081169291169061052d906113f790600201612686565b604051938493845260208401526060604084015260608301906125a7565b3461017c57604036600319011261017c5761142e6125e1565b6004355f525f60205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b3461017c57602036600319011261017c57608066ffffffffffffff61148360043561318d565b6114b2604093929351809460ff6040809263ffffffff8151168552826020820151166020860152015116910152565b166060820152f35b3461017c57602036600319011261017c57600480355f90815260209182526040908190205481516001600160801b038216815260809190911c9281019290925290f35b3461017c57602036600319011261017c57600435805f5260026020526115298160405f20541515612eec565b5f526003602052608061155560405f2061154b600260405192610f338461262f565b60408201526136b0565b66ffffffffffffff6001600160401b038251169161ffff602082015116906103e883606061ffff60408501511693015116049160405194855260208501526040840152166060820152f35b3461017c57602036600319011261017c576004356115cd816106f7815f52600260205260405f2054151590565b5f526003602052602061161a60ff6116136040805f20610f5360028351926115f48461262f565b80546001600160a01b0390811685526001820154168985015201612686565b93916132f0565b60018260405194161b161615158152f35b3461017c57608036600319011261017c576116446125cb565b6064356001600160401b03811161017c573660238201121561017c5780600401356001600160401b03811161017c57366024828401011161017c5760209260246116979301906044359060243590613047565b6040519015158152f35b3461017c575f36600319011261017c5760206040517fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c217758152f35b3461017c575f36600319011261017c57335f908152600860205260409020546001600160a01b031680158015611752575b6104af57335f81815260086020526040812080546001600160a01b03191690557fe11732b8fc05ea8677eaa2d4c9b2749a7a7a259ddcd42d049cec9895bcd82f249080a3005b5033811461170c565b3461017c57602036600319011261017c576004356001600160401b03811161017c5761178b903690600401612577565b905f915b80831061179857005b6117a3838284613037565b35926117be846106f7815f52600260205260405f2054151590565b835f5260036020526117df6040805f20610f536002835192610f338461262f565b919591336001600160a01b0388161480156119fb575b1561136a5760ff8061180d84808b60601b179a6132f0565b8184169961183060018c1b9561182a8189878a8816161515612f20565b8261329d565b5f52600b6020528160405f2094161916166080171660ff198254161790556040515f60208201525f60348201525f603582015260168152611872603682612665565b825f526003602052600260405f2001908051906001600160401b0382116112ac5761189d83546125f7565b601f81116119aa575b50602090601f831160011461191e5792827ff410acb19fb88f4410fa5c7f036abd226af716ba3588430600014a5e2cc3428495936001999a9b936040965f92611913575b50505f19600383901b1c191690891b1790555b60ff8351921682526020820152a201919061178f565b015190508c806118ea565b90601f19831691845f52815f20925f5b8181106119925750936001999a9b93604096938b93837ff410acb19fb88f4410fa5c7f036abd226af716ba3588430600014a5e2cc342849a981061197a575b505050811b0190556118fd565b01515f1960f88460031b161c191690558c808061196d565b9293602060018192878601518155019501930161192e565b828111156118a657835f5260205f20601f840160051c90602085106119f3575b81601f9101920160051c03905f5b8281106119e65750506118a6565b5f828201556001016119d8565b5f91506119ca565b50335f9081527f7d7ffb7a348e1c6a02869081a26547b49160dd3df72d1d75a570eb9b698292ec602052604090205460ff166117f5565b3461017c57604036600319011261017c57611a4b6125cb565b6024359060ff8216820361017c57602091611a65916132f0565b60ff60405191168152f35b3461017c57606036600319011261017c57600435611a8c6125e1565b6044356001600160a01b03811692919083900361017c57611abc826106f7815f52600260205260405f2054151590565b5f82815260066020526040902054611ae09033906001600160a01b0316811461300f565b6001600160a01b03169081151580611b5b575b80611b51575b1561017c575f81815260036020526040812080546001600160a01b03199081168517825560019091018054909116851790557f3595cc7fd5cc47819c3f867feaca948401d4c12ef70e636e442b98f3fee0c3f49080a4005b5082821415611af9565b50821515611af3565b3461017c575f36600319011261017c576020600154604051908152f35b3461017c57602036600319011261017c576004355f526005602052602060018060a01b0360405f205416604051908152f35b3461017c57602036600319011261017c57600435611be0816106f7815f52600260205260405f2054151590565b5f81815260056020526040902054611c049033906001600160a01b0316811461300f565b5f81815260056020908152604080832080546001600160a01b03199081169091556006909252822080543392168217905591907f348cf049fafe42de2416e7f9c12d1ab8e0bbd96829f0584bed500eeafc6c22759080a3005b3461017c57602036600319011261017c576101a0611c7c600435612fb9565b66ffffffffffffff608060405192611cb484825160ff6040809263ffffffff8151168552826020820151166020860152015116910152565b611ce56020820151606086019060ff6040809263ffffffff8151168552826020820151166020860152015116910152565b604081810151805163ffffffff1660c0870152602081015160ff90811660e088015291015116610100850152611d43606082015161012086019060ff6040809263ffffffff8151168552826020820151166020860152015116910152565b015116610180820152f35b3461017c57604036600319011261017c57611d676125e1565b336001600160a01b03821603611d83576106c09060043561345d565b63334bd91960e11b5f5260045ffd5b3461017c57604036600319011261017c576024356004356040519160408360208152826020820152019060051b8301916001602060408501935b8354815201910190848382101561067557506020600191611dcc565b3461017c57602036600319011261017c576004355f526006602052602060018060a01b0360405f205416604051908152f35b3461017c575f36600319011261017c57602060405160088152f35b3461017c57604036600319011261017c576106c0600435611e546125e1565b90611e6d6106b6825f525f602052600160405f20015490565b6133d5565b3461017c57602036600319011261017c576020611e9c6004355f525f602052600160405f20015490565b604051908152f35b3461017c57602036600319011261017c57600435545f5260205ff35b3461017c57604036600319011261017c57611ed96125cb565b6024356001600160401b03811161017c573660238201121561017c578060040135916001600160401b03831161017c576024820191602436918560061b01011161017c576001600160a01b0381169133831480156123fd575b1561136a575f838152600860205260409020546001600160a01b031683900361016d57606082901b93925f5b848110611f6757005b611f72818685612edc565b356020611f80838887612edc565b013590611f9c816106f7815f52600260205260405f2054151590565b611fb5826106f7815f52600260205260405f2054151590565b805f52600360205261206e60408261205861207d86898061203f875f20886120046002825193611fe48561262f565b80546001600160a01b039081168652600182015416602086015201612686565b9101908152845f526003602052885f2061202560028b5192610f338461262f565b998a91015251602001518060601c918160141a9160151a90565b9991969098602001518060601c918160141a9160151a90565b989097919390916001600160a01b031614612f06565b6001600160a01b031614612f06565b6120e68c838c6120c2828660ff818b881797179461209b8c826132f0565b908d8d85858216868216036123e957506120b3925084845b60018285161b16161515612f20565b6120e16120cf898561337c565b93896120db858561337c565b916132c7565b6132c7565b6040516120fc816110bf85858f602085016127ec565b855f526003602052600260405f2001908051906001600160401b0382116112ac57819061212984546125f7565b601f8111612390575b50602090601f831160011461232d575f92612322575b50508160011b915f199060031b1c19161790555b604051612172816110bf87878f602085016127ec565b865f526003602052600260405f2001908051906001600160401b0382116112ac5761219d83546125f7565b601f81116122d1575b50602090601f831160011461224057928260019b9a999896937f7345d8deb957df4afcbd74193d3990236d4d479e457909c52887b420d8b07bff98969361222c965f92612235575b50505f19600383901b1c1916908c1b1790556040805160ff958616815295851660208701529084169085015291909116606083015281906080820190565b0390a301611f5e565b015190505f806121ee565b90601f19831691845f52815f20925f5b8181106122b95750937f7345d8deb957df4afcbd74193d3990236d4d479e457909c52887b420d8b07bff98969361222c969360019e9d9c9b9996938f9484116122a1575b505050811b019055611174565b01515f1960f88460031b161c191690555f8080612294565b92936020600181928786015181550195019301612250565b828111156121a657835f5260205f20601f840160051c906020851061231a575b81601f9101920160051c03905f5b82811061230d5750506121a6565b5f828201556001016122ff565b5f91506122f1565b015190508f80612148565b5f8581528281209350601f198516905b8181106123785750908460019594939210612360575b505050811b01905561215c565b01515f1960f88460031b161c191690558f8080612353565b9293602060018192878601518155019501930161233d565b8281111561213257909150835f5260205f20601f840160051c90602085106123e1575b849392601f0160051c82900391015f5b8281106123d1575050612132565b5f818301558594506001016123c3565b5f91506123b3565b6123f786916120b3956132f0565b946120b3565b50335f9081527f7d7ffb7a348e1c6a02869081a26547b49160dd3df72d1d75a570eb9b698292ec602052604090205460ff16611f32565b3461017c57602036600319011261017c576001600160a01b036124556125cb565b165f526008602052602060018060a01b0360405f205416604051908152f35b3461017c57602036600319011261017c576004356001600160401b03811161017c576124a76124ad913690600401612577565b9061283f565b6040518091602082016020835281518091526040830190602060408260051b8601019301915f905b8282106124e457505050500390f35b919360019193955060206125148192603f198a82030186526040838a5180518452015191818582015201906125a7565b96019201920185949391926124d5565b3461017c57602036600319011261017c576004359063ffffffff60e01b821680920361017c57602091637965db0b60e01b8114908115612566575b5015158152f35b6301ffc9a760e01b1490508361255f565b9181601f8401121561017c578235916001600160401b03831161017c576020808501948460051b01011161017c57565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b038216820361017c57565b602435906001600160a01b038216820361017c57565b90600182811c92168015612625575b602083101461261157565b634e487b7160e01b5f52602260045260245ffd5b91607f1691612606565b606081019081106001600160401b038211176112ac57604052565b604081019081106001600160401b038211176112ac57604052565b90601f801991011681019081106001600160401b038211176112ac57604052565b9060405191825f825492612699846125f7565b808452936001811690811561270457506001146126c0575b506126be92500383612665565b565b90505f9291925260205f20905f915b8183106126e85750509060206126be928201015f6126b1565b60209193508060019154838589010152019101909184926126cf565b9050602092506126be94915060ff191682840152151560051b8201015f6126b1565b6001600160401b0381116112ac5760051b60200190565b6001600160401b0381116112ac57601f01601f191660200190565b9291926127648261273d565b916127726040519384612665565b82948184528183011161017c578281602093845f960137010152565b91908110156127b05760051b8101359060be198136030182121561017c570190565b634e487b7160e01b5f52603260045260245ffd5b356001600160a01b038116810361017c5790565b356001600160801b038116810361017c5790565b60609190911b6bffffffffffffffffffffffff1916815260f891821b6001600160f81b031990811660148301529290911b909116601582015260160190565b80518210156127b05760209160051b010190565b919061284a81612726565b926128586040519485612665565b818452601f1961286783612726565b015f5b818110612eb8575050838215612eb25750335f52600760205260405f2091604051926128958461264a565b549160ff8316845260ff602085019360081c1683523360601b335f52600860205260405f2060018060a01b0333166bffffffffffffffffffffffff60a01b82541617905560ff808651161015612e9f57845160ff168117923060601b5f5b82811061293257505050505050335f52600760205260ff8060405f209351161660ff198354161782555161ff0082549160081b169061ff001916179055565b60ff808951161015612e9f5761294c6103b082858861278e565b612962602061295c84878a61278e565b016127c4565b906001600160a01b031680158015612e8e575b8015612e7c575b612e6d5760ff89511615612e5e575b885160405160208101914683528660408301528a605483015260ff60f81b9060f81b166074820152605581526129c2607582612665565b5190206129ce8161381c565b506001600160a01b036129e7608061295c878a8d61278e565b1615612e3c576129fd608061295c86898c61278e565b5f82815260066020526040902080546001600160a01b0319166001600160a01b039092169190911790555b876001600160801b0380612a586060612a4c898c612a526040612a4c84848c61278e565b016127d8565b9761278e565b169116101561017c57612a716040612a4c86898c61278e565b612a816060612a4c878a8d61278e565b6001600160801b0360405192612a968461264a565b1682526001600160801b036020830191168152825f5260046020526001600160801b0360405f20925116906001600160801b0319905160801b1617905560ff8b5116612af460ff8c5116916110bf60405193849233602085016127ec565b6002604051612b028161262f565b8481526001600160a01b03958616602080830182815260408085019687525f8881526003909352909120925183549089166001600160a01b03199182161784559051600184018054919099169116179096559151805191909201916001600160401b0382116112ac578190612b7784546125f7565b601f8111612de3575b50602090601f8311600114612d80575f92612d75575b50508160011b915f199060031b1c19161790555b612bb860ff8b51168a61329d565b885f52600b60205260405f20548a60808216612d47575b50508c848c5160ff168c5160ff1660405191829133916020840192612bf3936127ec565b03601f1981018252612c059082612665565b60405190612c128261264a565b8482526020820152612c24828461282b565b52612c2e9161282b565b50612c3a84878a61278e565b608001612c46906127c4565b612c5185888b61278e565b604001612c5d906127d8565b90612c6986898c61278e565b606001612c75906127d8565b8d5160ff16908d5160ff1660405192839133916020840192612c96936127ec565b03601f1981018352612ca89083612665565b604051938493600160a01b600190031684526001600160801b031660208401526001600160801b03166040830152606082016080905260808201612ceb916125a7565b037f69095d3f30a8151c6e9dec6c33a2bd4997e041407b5cb7c8185d8c4d4f466dc391a4865160ff1660010160ff16808852600414612d2d575b6001016128f3565b5f8752875160ff9081166001011680895284179550612d25565b60ff600181809351161b16911617895f52600b60205260ff60405f20911660ff198254161790555f8a612bcf565b015190505f80612b96565b5f8581528281209350601f198516905b818110612dcb5750908460019594939210612db3575b505050811b019055612baa565b01515f1960f88460031b161c191690555f8080612da6565b92936020600181928786015181550195019301612d90565b82811115612b8057909150835f5260205f20601f840160051c9060208510612e34575b849392601f0160051c82900391015f5b828110612e24575050612b80565b5f81830155859450600101612e16565b5f9150612e06565b5f81815260066020526040902080546001600160a01b03191633179055612a28565b612e67886137a9565b5061298b565b6330d3116760e21b5f5260045ffd5b506001600160a01b038216811461297c565b506001600160a01b03821615612975565b6318503dbd60e21b5f523360045260245ffd5b93505050565b602090604051612ec78161264a565b5f81526060838201528282890101520161286a565b91908110156127b05760061b0190565b15612ef45750565b630138152d60e61b5f5260045260245ffd5b15612f0e5750565b630298dc7960e31b5f5260045260245ffd5b15612f29575050565b9060ff8092630252bbb960e51b5f52166004521660245260445ffd5b60405190612f528261262f565b5f6040838281528260208201520152565b6040519060a082018281106001600160401b038211176112ac576040525f608083612f8c612f45565b8152612f96612f45565b6020820152612fa3612f45565b6040820152612fb0612f45565b60608201520152565b612fe86040612fd2612fc9612f63565b936104ee61323f565b0151602001518060601c918160141a9160151a90565b50906001600160a01b0381161561300a57613007925060601b176134dd565b90565b505090565b156130175750565b634813e70560e11b5f9081526001600160a01b0391909116600452602490fd5b91908110156127b05760051b0190565b9391929061305481613552565b6001600160a01b03851691821561016d5760ff8516938461308066ffffffffffffff8860081c16613569565b9761308a89613595565b60601b179666ffffffffffffff806130a7818b5460081c16613569565b169116111561318257613121610a2d9261312794604051602081019146835230604083015288606083015260808201528960a082015260a081526130ec60c082612665565b5190207f19457468657265756d205369676e6564204d6573736167653a0a3332000000005f52601c52603c5f20923691612758565b9061389a565b6001600160a01b0316810361017c575f52600760205260405f206040519061314e8261264a565b5460ff8082169182845260081c1660208301528211610140576131729183916135c4565b156101295760ff19169055600190565b505050505050505f90565b906131a76040612fd261319e612f45565b946104ee61323f565b939091906001600160a01b038216156131e457506131dd6131d666ffffffffffffff9360809360601b176134dd565b9485613652565b9301511690565b93505f92915050565b91908110156127b0576060020190565b3560ff8116810361017c5790565b60405190608082018281106001600160401b038211176112ac576040525f6060838281528260208201528260408201520152565b6040519061324c8261262f565b60606040835f81525f60208201520152565b50613278816106f7815f52600260205260405f2054151590565b5f52600360205260405f20613295600260405192610f338461262f565b604082015290565b906003811161017c576030906004030260100161ffff65ffffffffffff821b19835416911b179055565b91906003811161017c57603090600403026010019065ffffffffffff821b19835416911b179055565b90808260601b175f52600b60205260405f20549160808316613374576020925060018060a01b03165f526007825260ff60405f2091604051926133328461264a565b5492828085169485835260081c1694859101521681811061336c571461335757505f90565b6001901b5f1981019081116101155760ff1690565b505050600f90565b5050600f1690565b906003811161017c57603065ffffffffffff925491600403026010011c1690565b5f8181526020818152604080832033845290915290205460ff16156133bf5750565b63e2517d3f60e01b5f523360045260245260445ffd5b5f818152602081815260408083206001600160a01b038616845290915290205460ff16613457575f818152602081815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b50505f90565b5f818152602081815260408083206001600160a01b038616845290915290205460ff1615613457575f818152602081815260408083206001600160a01b0395909516808452949091528120805460ff19169055339291907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b9061354b65ffffffffffff6134f0612f63565b935466ffffffffffffff613508818360081c16613569565b16608086015261351a8160d01c61386f565b855261352a828260a01c1661386f565b602086015261353d828260701c1661386f565b604086015260401c1661386f565b6060830152565b421161355a57565b63559895a360e01b5f5260045ffd5b66ffffffffffffff81116135835766ffffffffffffff1690565b633f5067df60e21b5f5260045260245ffd5b66ffffffffffffff6103e891160466ffffffffffffff429116116135b557565b630ff02cef60e01b5f5260045ffd5b9060ff8083511691160361364b576020015160ff16600481101561364b57806135fb57505f195b1667ffffffffffffffff19161590565b80600403906004821161011557603082029182046030149060041417156101155760400180604011610115576001901b5f198101908111156135eb57634e487b7160e01b5f52601160045260245ffd5b5050600190565b919060ff9061365f612f45565b50169182156136ab57600183146136a3576002831461369b57600383146136935782634e6153af60e11b5f5260045260245ffd5b606001519150565b604001519150565b602001519150565b519150565b906136d560406136be61320b565b930151602001518060601c918160141a9160151a90565b916001600160a01b03811615613795576136fd916136f69160601b176134dd565b9182613652565b604081019060ff808351161480613785575b613771579161ffff61376160ff608094836137548360208a8d6001600160401b0366ffffffffffffff9d51601f6307ffffff821691601b1c161b169052015116613948565b1660208a01525116613948565b1660408601520151166060830152565b505061271060408401819052602084015250565b5060ff806020830151161461370f565b505061271060208401819052604084015250565b805f52600a60205260405f2054155f1461381757600954600160401b8110156112ac5760018101806009558110156127b0577f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af018190556009545f918252600a602052604090912055600190565b505f90565b805f52600260205260405f2054155f1461381757600154600160401b8110156112ac5760018101806001558110156127b057819060015f5260205f200155600154905f52600260205260405f2055600190565b9060ff61387a612f45565b9263ffffffff8160101c168452818160081c166020850152166040830152565b81519190604183036138ca576138c39250602082015190606060408401519301515f1a90613973565b9192909190565b50505f9160029190565b600481101561393457806138e6575050565b600181036138fd5763f645eedf60e01b5f5260045ffd5b60028103613918575063fce698f760e01b5f5260045260245ffd5b6003146139225750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b9061395282613c78565b9290921561395d5750565b60ff9063011da7ab60e61b5f521660045260245ffd5b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084116139f5579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa156139ea575f516001600160a01b038116156139e057905f905f90565b505f906001905f90565b6040513d5f823e3d90fd5b5050505f9160039190565b60405190613a1061022083612665565b61020082527f20ec2182221822ae234423da24702506259c263226c8275e27f4288a29202710610200837c0100020003000400050006000700080009000c000e001000120014001660208201527e18001a001c001e00200022002400260028002a002c002e003000320034003660408201527e38003a003c003e00400042004400460048004a004c004e005000520054005660608201527e58005a005c005e00600062006400660068006a006c006e007000720074007660808201527e7b00800085008a008f00940099009e00a300a800ad00b200b700bc00c100c660a08201527ecb00d000d500da00df00e400e900ee00f300f800fd01020107010c0111011660c08201527f011b01200125012a012f01340139013e01430148014d01520157015c0161016660e08201527f016b01700175017a017f01840189018e01930198019d01a201a701ac01b101b66101008201527f01c001ca01d401de01e801f201fc02060210021a0224022e02380242024c02566101208201527f0260026a0274027e02880292029c02a602b002ba02c402ce02d802e202ec02f66101408201527f0300030a0314031e03280332033c03460350035a0364036e03780382038c03966101608201527f03a003aa03b403be03c803d203dc03e603f003fa0404040e04180422042c04366101808201527f04cc056205f8068e072407ba085008e6097c0a120aa80b3e0bd40c6a0d000d966101a08201527f0e2c0ec20f580fee1084111a11b0124612dc13721408149e153415ca166016f66101c08201527f178c182218b8194e19e41a7a1b101ba61c3c1cd21d681dfe1e941f2a1fc020566101e08201520152565b613c80613a00565b5160011c8015908115613cf2575b8115613ce4575b50613cdd5760011b6101fe16613cd261ff0080613cb984613cb4613a00565b613cff565b5160f01c1616916001613cca613a00565b910190613cff565b5160f81c1790600190565b505f905f90565b905060ff821610155f613c95565b60ff838116119150613c8e565b9081518110156127b057016020019056fea2646970667358221220221ab5e7169d4fe558bad829068a5c5baba2551d9e16d1d2eda7ca881cb1a16364736f6c63430008210033", - "nonce": "0x1", - "storage": { - "0xd622e34f9f6e1c96032d45ead8ff60c54838d13000000000000000000000000": "0x5cdc2949000000000000000027bac86a060000000000000000019eaa0d787200", - "0x95191f9da9b73a1282d7a8cae0d352b0b11bfadf2603d32929f695c1cdd9c42e": "0xd622e34f9f6e1c96032d45ead8ff60c54838d13", - "0xb0296c0e3ea88b9cf74eaaf0baa46f18c015c86fd13c93e4236537bf71a16b1c": "0x300" - } - } - }, - "post": { - "Rex5": [ - { - "indexes": { - "data": 0, - "gas": 0, - "value": 0 - }, - "hash": "0x2231d71ba07daff0df2620ff18a3a91c23357f01b2552c30c03c9220db5f0abb", - "logs": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", - "megaGasUsed": 75514, - "megaStatus": "success" - } - ] - }, - "transaction": { - "type": 2, - "data": [ - "0x6a2770765cdc2b31000000000000000027ba5f49020000000000000000019eaa0d7bec00" - ], - "gasLimit": [ - "0x249f0" - ], - "gasPrice": null, - "nonce": "0x195cb", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x14112799a39f2905b901067d3cd4a1f63c1cebda", - "to": "0x681e908b8ab57c49c74d770f369754ccc3e1ae09", - "value": [ - "0x0" - ], - "maxFeePerGas": "0x200b20", - "maxPriorityFeePerGas": "0x186a0", - "initcodes": null, - "accessLists": [ - [] - ], - "authorizationList": null, - "blobVersionedHashes": [], - "maxFeePerBlobGas": null - }, - "out": "0x", - "megaEnv": { - "bucketCapacities": [], - "oracleStorage": [] - } - } -} \ No newline at end of file diff --git a/bench/replay/fixtures/system_call.json b/bench/replay/fixtures/system_call.json deleted file mode 100644 index b08d0d07b..000000000 --- a/bench/replay/fixtures/system_call.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "replay_0x722a6878f48952f3906045547c18270a060e8415be534046719002fa096d9299": { - "_info": null, - "env": { - "currentChainID": "0x10e6", - "currentCoinbase": "0x4200000000000000000000000000000000000011", - "currentDifficulty": "0x0", - "currentGasLimit": "0x2540be400", - "currentNumber": "0x1155808", - "currentTimestamp": "0x6a277ddb", - "currentBaseFee": "0xf4240", - "currentRandom": "0x257b1f30cba44be7941133b715be042b3e078c096663493d671e6606001cfe73", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x6342000000000000000000000000000000000001": { - "balance": "0x0", - "code": "0x608060405234801561000f575f5ffd5b50600436106100b9575f3560e01c80637eba7ba61161007257806399bd21151161005857806399bd211514610193578063a21e2d69146101d3578063fbc0d035146101f3575f5ffd5b80637eba7ba6146101605780638d4909dc14610180575f5ffd5b8063348a0cdc116100a2578063348a0cdc146100e557806354fd4d501461010e57806366cdf82f1461014d575f5ffd5b806301caec13146100bd578063138f5ec5146100d2575b5f5ffd5b6100d06100cb366004610649565b610206565b005b6100d06100e03660046106b5565b610282565b6100f86100f33660046106fd565b6102cc565b6040516101059190610788565b60405180910390f35b604080518082018252600581527f322e302e30000000000000000000000000000000000000000000000000000000602082015290516101059190610809565b6100d061015b366004610822565b505050565b61017261016e366004610899565b5490565b604051908152602001610105565b6100d061018e366004610822565b610443565b6101ae73634200000000000000000000000000000000000681565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610105565b6101e66101e13660046106fd565b610456565b60405161010591906108b0565b6100d06102013660046108f2565b6104cc565b82811461024e576040517f5b7232fa00000000000000000000000000000000000000000000000000000000815260048101849052602481018290526044015b60405180910390fd5b8382845f5b818110156102705760208102838101359085013555600101610253565b5050505061027c6104db565b50505050565b805f5b818110156102c2576102ba858585848181106102a3576102a3610912565b90506020028101906102b5919061093f565b6105c2565b600101610285565b505061015b6104db565b60608167ffffffffffffffff8111156102e7576102e76109a0565b60405190808252806020026020018201604052801561031a57816020015b60608152602001906001900390816103055790505b5090505f5b8281101561043c575f803086868581811061033c5761033c610912565b905060200281019061034e919061093f565b60405161035c9291906109cd565b5f60405180830381855af49150503d805f8114610394576040519150601f19603f3d011682016040523d82523d5f602084013e610399565b606091505b509150915081610414578051156103b257805181602001fd5b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f4d756c746963616c6c3a2063616c6c206661696c6564000000000000000000006044820152606401610245565b8084848151811061042757610427610912565b6020908102919091010152505060010161031f565b5092915050565b61044e8383836105c2565b61015b6104db565b60608167ffffffffffffffff811115610471576104716109a0565b60405190808252806020026020018201604052801561049a578160200160208202803683370190505b5090506020810183835f5b818110156104c257602081028381013554908501526001016104a5565b5050505092915050565b8082556104d76104db565b5050565b73634200000000000000000000000000000000000673ffffffffffffffffffffffffffffffffffffffff1663de7a36af6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610538573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061055c91906109dc565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146105c0576040517f5e742c5a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b827fda678492695e6a825d786c2375f7fdf3c1dc012451c61c1804227f499b0fc53e83836040516105f4929190610a0f565b60405180910390a2505050565b5f5f83601f840112610611575f5ffd5b50813567ffffffffffffffff811115610628575f5ffd5b6020830191508360208260051b8501011115610642575f5ffd5b9250929050565b5f5f5f5f6040858703121561065c575f5ffd5b843567ffffffffffffffff811115610672575f5ffd5b61067e87828801610601565b909550935050602085013567ffffffffffffffff81111561069d575f5ffd5b6106a987828801610601565b95989497509550505050565b5f5f5f604084860312156106c7575f5ffd5b83359250602084013567ffffffffffffffff8111156106e4575f5ffd5b6106f086828701610601565b9497909650939450505050565b5f5f6020838503121561070e575f5ffd5b823567ffffffffffffffff811115610724575f5ffd5b61073085828601610601565b90969095509350505050565b5f81518084528060208401602086015e5f6020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b828110156107fd577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08786030184526107e885835161073c565b945060209384019391909101906001016107ae565b50929695505050505050565b602081525f61081b602083018461073c565b9392505050565b5f5f5f60408486031215610834575f5ffd5b83359250602084013567ffffffffffffffff811115610851575f5ffd5b8401601f81018613610861575f5ffd5b803567ffffffffffffffff811115610877575f5ffd5b866020828401011115610888575f5ffd5b939660209190910195509293505050565b5f602082840312156108a9575f5ffd5b5035919050565b602080825282518282018190525f918401906040840190835b818110156108e75783518352602093840193909201916001016108c9565b509095945050505050565b5f5f60408385031215610903575f5ffd5b50508035926020909101359150565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f5f83357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112610972575f5ffd5b83018035915067ffffffffffffffff82111561098c575f5ffd5b602001915036819003821315610642575f5ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b818382375f9101908152919050565b5f602082840312156109ec575f5ffd5b815173ffffffffffffffffffffffffffffffffffffffff8116811461081b575f5ffd5b60208152816020820152818360408301375f818301604090810191909152601f9092017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016010191905056fea164736f6c634300081e000a", - "nonce": "0x0", - "storage": { - "0x0": "0x653c91816c1bd" - } - }, - "0x6342000000000000000000000000000000000006": { - "balance": "0x0", - "code": "0x608060405234801561000f575f5ffd5b50600436106100cf575f3560e01c806354fd4d501161007d578063e3093f5011610058578063e3093f50146101d5578063e8129030146101e8578063f851a44014610206575f5ffd5b806354fd4d501461016657806375829def146101a5578063de7a36af146101b8575f5ffd5b80632b20d6e5116100ad5780632b20d6e5146101385780633411f3c31461014b57806344d744591461015e575f5ffd5b80630e18b681146100d3578063129c8240146100dd578063267822471461011a575b5f5ffd5b6100db610224565b005b6100f06100eb366004610d94565b6102f7565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020015b60405180910390f35b60035473ffffffffffffffffffffffffffffffffffffffff166100f0565b6100db610146366004610dd3565b61041d565b6100db610159366004610dd3565b6106cf565b6100db610973565b604080518082018252600581527f312e302e30000000000000000000000000000000000000000000000000000000602082015290516101119190610dfb565b6100db6101b3366004610e4e565b610985565b5f5473ffffffffffffffffffffffffffffffffffffffff166100f0565b6100f06101e3366004610d94565b610a35565b60015473ffffffffffffffffffffffffffffffffffffffff166100f0565b60025473ffffffffffffffffffffffffffffffffffffffff166100f0565b60035473ffffffffffffffffffffffffffffffffffffffff16338114610276576040517f058d9a1b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff00000000000000000000000000000000000000008084168217909455600380549094169093556040519116919082907ff8ccb027dfcd135e000e9d45e6cc2d662578a8825d4c45b5e32e0adf67e79ec6905f90a35050565b5f43821115610332576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60065482101561036e576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c54805b80156103fc575f600c610387600184610e9b565b8154811061039757610397610eb4565b5f91825260209091200180549091506bffffffffffffffffffffffff1685106103e957546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b50806103f481610ee1565b915050610373565b505060055473ffffffffffffffffffffffffffffffffffffffff1692915050565b610425610b5b565b43811161045e576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff810361058d5773ffffffffffffffffffffffffffffffffffffffff8216156104d3576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600980547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f600a81905560015473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf97fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60405161058191815260200190565b60405180910390a35050565b6bffffffffffffffffffffffff8111156105d3576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8216610620576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6009805473ffffffffffffffffffffffffffffffffffffffff84167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155600a82905561068860015473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167f7ac0520c61d87c77ffc308e23c801f5a351140175ec3f6356a3a890aa0cfdbf98360405161058191815260200190565b6106d7610b5b565b438111610710576040517fc2fdad0400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81036108325773ffffffffffffffffffffffffffffffffffffffff821615610785576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600780547fffffffffffffffffffffffff00000000000000000000000000000000000000001690555f6008819055805473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9157fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60405161058191815260200190565b6bffffffffffffffffffffffff811115610878576040517f9d7378d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff82166108c5576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff84167fffffffffffffffffffffffff00000000000000000000000000000000000000009091168117909155600882905561092c5f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fd839b7efbcae2bd482a7aa1c098265fdb6b43c10e3e5138a8fa2b395a02eb9158360405161058191815260200190565b61097b610bac565b610983610ca1565b565b61098d610b5b565b6003805473ffffffffffffffffffffffffffffffffffffffff83167fffffffffffffffffffffffff000000000000000000000000000000000000000090911681179091556109f060025473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff167fe5cd1c804f1c9cc6d7009e4c0fb532f0e2d8863524c3323a6b3790c3f80bf25c60405160405180910390a350565b5f43821115610a70576040517fdbe289ad00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600654821015610aac576040517fd2c461b000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b54805b8015610b3a575f600b610ac5600184610e9b565b81548110610ad557610ad5610eb4565b5f91825260209091200180549091506bffffffffffffffffffffffff168510610b2757546c01000000000000000000000000900473ffffffffffffffffffffffffffffffffffffffff16949350505050565b5080610b3281610ee1565b915050610ab1565b505060045473ffffffffffffffffffffffffffffffffffffffff1692915050565b60025473ffffffffffffffffffffffffffffffffffffffff163314610983576040517f7bfa4b9f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60075473ffffffffffffffffffffffffffffffffffffffff1680610bcd5750565b60085443811115610bdc575050565b5f805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600b8054600181018255908552905191519095166c01000000000000000000000000029316929092177f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db990930192909255600780549091169055600855565b60095473ffffffffffffffffffffffffffffffffffffffff1680610cc25750565b600a5443811115610cd1575050565b6001805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff000000000000000000000000000000000000000091821681178355604080518082019091526bffffffffffffffffffffffff948516815260208101918252600c805494850181555f908152905191519095166c01000000000000000000000000029316929092177fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c790910155600980549091169055600a55565b5f60208284031215610da4575f5ffd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff81168114610dce575f5ffd5b919050565b5f5f60408385031215610de4575f5ffd5b610ded83610dab565b946020939093013593505050565b602081525f82518060208401528060208501604085015e5f6040828501015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011684010191505092915050565b5f60208284031215610e5e575f5ffd5b610e6782610dab565b9392505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81810381811115610eae57610eae610e6e565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f81610eef57610eef610e6e565b507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff019056fea164736f6c634300081e000a", - "nonce": "0x0", - "storage": { - "0x0": "0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d" - } - }, - "0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d": { - "balance": "0x0", - "code": "0x", - "nonce": "0x98191c7", - "storage": {} - } - }, - "post": { - "Rex5": [ - { - "indexes": { - "data": 0, - "gas": 0, - "value": 0 - }, - "hash": "0x05fb521b8bd2559574f433c2871a5d27d50dcb32fef0028b94645a048c847c99", - "logs": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", - "megaGasUsed": 81740, - "megaStatus": "success" - } - ] - }, - "transaction": { - "type": 0, - "data": [ - "0x01caec1300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000653c91818250f" - ], - "gasLimit": [ - "0x253e8c4e4" - ], - "gasPrice": "0x0", - "nonce": "0x98191c7", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d", - "to": "0x6342000000000000000000000000000000000001", - "value": [ - "0x0" - ], - "maxFeePerGas": null, - "maxPriorityFeePerGas": null, - "initcodes": null, - "accessLists": [ - null - ], - "authorizationList": null, - "blobVersionedHashes": [], - "maxFeePerBlobGas": null - }, - "out": "0x", - "megaEnv": { - "bucketCapacities": [], - "oracleStorage": [] - } - } -} \ No newline at end of file diff --git a/bench/replay/manifest.json b/bench/replay/manifest.json deleted file mode 100644 index 68699eaa2..000000000 --- a/bench/replay/manifest.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "description": "Characteristic MegaETH workloads for the replay-throughput benchmark. Each case is a self-contained state-test fixture (pre-state + tx + env + megaEnv), replayed offline in isolation — no RPC, no archive node. Most are real mainnet transactions dumped via `mega-evme replay --dump-fixture`; non-on-chain cases (e.g. attack snapshots) use the same format. See run.py and README.md.", - "default_runs": 50, - "default_warmup": 5, - "cases": [ - { - "name": "system_call", - "category": "system-contract", - "type": "fixture", - "fixture": "fixtures/system_call.json", - "expected_gas": 81740, - "note": "Call into a 0x6342… system contract — exercises interceptor dispatch and volatile-data/oracle paths." - }, - { - "name": "medium_call", - "category": "plain-call", - "type": "fixture", - "fixture": "fixtures/medium_call.json", - "expected_gas": 75514, - "note": "Medium contract call with no logs — baseline compute + a few SLOAD/SSTORE." - }, - { - "name": "log_heavy", - "category": "logs", - "type": "fixture", - "fixture": "fixtures/log_heavy.json", - "expected_gas": 456913, - "note": "12 logs — exercises LOG opcodes and the dual (compute + storage) gas metering on topics/data." - }, - { - "name": "large_defi", - "category": "heavy", - "type": "fixture", - "fixture": "fixtures/large_defi.json", - "expected_gas": 600700, - "note": "Large multi-call DeFi transaction — deep call stack, many storage writes." - }, - { - "name": "attack_deploy", - "category": "attack/limit-stress", - "type": "fixture", - "fixture": "fixtures/attack_deploy.json", - "expected_gas": 141927106, - "note": "Mainnet attack contract deployment captured as a self-contained prestate fixture (not a mined tx; converted from crates/mega-evm/benches/fixtures/known_attack_deploy.json, #299). 142M gas of CREATE — the heaviest stress on the multi-dimensional AdditionalLimit accounting. Its post was filled offline (`state-test --fill --bench-spec Rex5`), so it is validated and benched like the others." - } - ] -} diff --git a/bench/replay/run.py b/bench/replay/run.py deleted file mode 100644 index aff5e823a..000000000 --- a/bench/replay/run.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python3 -"""Replay-throughput benchmark driver for mega-evm. - -Runs a corpus of characteristic MegaETH workloads through ``state-test --bench`` -fully offline — each case is a self-contained state-test fixture (pre-state + -tx + env), so the benchmark is deterministic and needs no network — and reports -per-case EVM throughput. - -With a single ``--bin`` it just measures (useful for a baseline or a quick local -check). With two ``--bin`` entries it does an **ABBA-interleaved** base-vs-PR -comparison: for each case the two binaries are run in alternating order across -several rounds so that slow monotonic drift on the CI machine cancels out, then -the median of each binary's samples is compared. A case whose PR median is more -than ``--threshold-pct`` slower than base is flagged as a regression (and, with -``--fail-on-regression``, fails the run). - -The driver shells out to ``state-test`` and parses the single-document JSON it -prints; it has no third-party dependencies. ``--bin`` is a build directory (or -the path to a binary in one); the ``state-test`` binary is resolved from it. - -Manifest format (JSON):: - - { - "default_runs": 50, - "default_warmup": 5, - "cases": [ - { - "name": "erc20_transfer", - "category": "storage+log", - "fixture": "fixtures/erc20_transfer.json", - "expected_gas": 51234, - "spec": "Rex5", - "note": "USDC transfer: 1 log, 2 SSTORE" - } - ] - } - -``spec`` is optional (defaults to the fixture's single ``post`` spec). ``fixture`` -paths are resolved relative to the manifest file. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import subprocess -import sys -from dataclasses import dataclass -from pathlib import Path - - -@dataclass -class Measurement: - """One binary's measured throughput for one transaction.""" - - median_ns: float - mgas_per_sec: float - gas_used: int - - -def resolve_state_test(path: str) -> str: - """Resolve the ``state-test`` binary from one ``--bin`` value. - - ``path`` may be a build directory containing the binary, or the path to a - binary in one (``state-test`` is then taken as a sibling) — so both - ``--bin target/release`` and ``--bin target/release/mega-evme`` work. - """ - p = Path(path) - return str(p / "state-test") if p.is_dir() else str(p.parent / "state-test") - - -def run_case(state_test: str, case: dict, manifest_dir: Path, runs: int, warmup: int) -> Measurement: - """Benchmark one self-contained fixture case via ``state-test --bench``.""" - fixture = (manifest_dir / case["fixture"]).resolve() - cmd = [state_test, "--bench", "--bench-runs", str(runs), "--bench-warmup", str(warmup)] - if case.get("spec"): - cmd += ["--bench-spec", case["spec"]] - cmd.append(str(fixture)) - - proc = subprocess.run(cmd, capture_output=True, text=True, timeout=600) - if proc.returncode != 0: - raise RuntimeError( - f"{case['name']} failed (exit {proc.returncode}):\n{proc.stderr.strip()}" - ) - try: - out = json.loads(proc.stdout.strip()) - except json.JSONDecodeError as exc: - raise RuntimeError(f"could not parse bench JSON for {case['name']}: {exc}") from exc - bench = out.get("bench") - if bench is None: - raise RuntimeError(f"no `bench` field in output for {case['name']}") - return Measurement( - median_ns=float(bench["medianNs"]), - mgas_per_sec=float(bench["mgasPerSec"]), - gas_used=int(out["gas_used"]), - ) - - -def measure_abba( - binaries: list[tuple[str, str]], - case: dict, - manifest_dir: Path, - runs: int, - warmup: int, - rounds: int, -) -> dict[str, Measurement]: - """Collect `rounds` samples per binary, interleaving order each round. - - Round r runs the binaries in normal order when r is even and reversed when r - is odd (A B / B A / A B ...), so a machine that slowly speeds up or slows - down over the run does not systematically favor either binary. The reported - measurement per binary is the median of its per-round samples. - """ - samples: dict[str, list[Measurement]] = {label: [] for label, _ in binaries} - for r in range(rounds): - order = binaries if r % 2 == 0 else list(reversed(binaries)) - for label, state_test in order: - samples[label].append(run_case(state_test, case, manifest_dir, runs, warmup)) - result: dict[str, Measurement] = {} - for label, _ in binaries: - ss = samples[label] - result[label] = Measurement( - median_ns=statistics.median(s.median_ns for s in ss), - mgas_per_sec=statistics.median(s.mgas_per_sec for s in ss), - gas_used=ss[0].gas_used, - ) - return result - - -def fmt_ns(ns: float) -> str: - if ns >= 1_000_000: - return f"{ns / 1_000_000:.3f} ms" - if ns >= 1_000: - return f"{ns / 1_000:.2f} µs" - return f"{ns:.0f} ns" - - -def classify(delta_pct: float, threshold: float) -> str: - """Marker for a median-time delta (positive = slower = regression).""" - if delta_pct > threshold: - return "🔴 regression" - if delta_pct < -threshold: - return "🟢 improvement" - return "⚪ noise" - - -def build_report( - cases: list[dict], - results: list[dict[str, Measurement]], - labels: list[str], - threshold: float, -) -> tuple[str, dict, int]: - """Render a markdown table and a machine-readable summary. - - Returns (markdown, json_summary, regression_count). Comparison columns are - only emitted when exactly two binaries were measured (labels[0] = base, - labels[1] = pr). - """ - compare = len(labels) == 2 - lines: list[str] = [] - if compare: - base, pr = labels - lines.append(f"| transaction | category | gas | `{base}` median | `{pr}` median | Δ time | `{base}` Mgas/s | `{pr}` Mgas/s | verdict |") - lines.append("|---|---|--:|--:|--:|--:|--:|--:|---|") - else: - only = labels[0] - lines.append(f"| transaction | category | gas | `{only}` median | `{only}` Mgas/s |") - lines.append("|---|---|--:|--:|--:|") - - regressions = 0 - improvements = 0 - json_cases = [] - for case, res in zip(cases, results): - name, cat, gas = case["name"], case.get("category", ""), case["expected_gas"] - if compare: - base, pr = labels - b, p = res[base], res[pr] - if b.median_ns <= 0: - sys.exit(f"case {name}: baseline median is zero; cannot compute a delta") - delta = (p.median_ns - b.median_ns) / b.median_ns * 100.0 - verdict = classify(delta, threshold) - regressions += verdict.startswith("🔴") - improvements += verdict.startswith("🟢") - lines.append( - f"| {name} | {cat} | {gas:,} | {fmt_ns(b.median_ns)} | {fmt_ns(p.median_ns)} | " - f"{delta:+.1f}% | {b.mgas_per_sec:,.0f} | {p.mgas_per_sec:,.0f} | {verdict} |" - ) - json_cases.append( - { - "name": name, - "category": cat, - "gas": gas, - "base_median_ns": b.median_ns, - "pr_median_ns": p.median_ns, - "delta_pct": delta, - "base_mgas_per_sec": b.mgas_per_sec, - "pr_mgas_per_sec": p.mgas_per_sec, - "verdict": verdict, - } - ) - else: - only = labels[0] - m = res[only] - lines.append( - f"| {name} | {cat} | {gas:,} | {fmt_ns(m.median_ns)} | {m.mgas_per_sec:,.0f} |" - ) - json_cases.append( - { - "name": name, - "category": cat, - "gas": gas, - "median_ns": m.median_ns, - "mgas_per_sec": m.mgas_per_sec, - } - ) - - md = "\n".join(lines) - if compare: - summary = ( - f"\n\n**{len(cases)} transactions — " - f"{regressions} regression(s), {improvements} improvement(s)** " - f"(threshold ±{threshold:.1f}% on median time; ABBA-interleaved)." - ) - md += summary - json_summary = { - "threshold_pct": threshold, - "labels": labels, - "regressions": regressions, - "improvements": improvements, - "cases": json_cases, - } - return md, json_summary, regressions - - -def parse_bin(spec: str) -> tuple[str, str]: - if "=" not in spec: - raise argparse.ArgumentTypeError(f"--bin must be LABEL=PATH, got {spec!r}") - label, path = spec.split("=", 1) - return label, path - - -def main() -> int: - here = Path(__file__).resolve().parent - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--manifest", type=Path, default=here / "manifest.json") - ap.add_argument( - "--bin", - type=parse_bin, - action="append", - required=True, - metavar="LABEL=PATH", - help="binary to measure; pass twice (base then pr) to compare", - ) - ap.add_argument("--runs", type=int, default=None, help="timed iterations per invocation") - ap.add_argument("--warmup", type=int, default=None, help="discarded warmup iterations") - ap.add_argument("--rounds", type=int, default=5, help="ABBA rounds per transaction") - ap.add_argument("--threshold-pct", type=float, default=5.0) - ap.add_argument("--json-out", type=Path, default=None) - ap.add_argument("--markdown-out", type=Path, default=None) - ap.add_argument("--fail-on-regression", action="store_true") - args = ap.parse_args() - - if len(args.bin) > 2: - ap.error("at most two --bin entries (base and pr) are supported") - - manifest = json.loads(args.manifest.read_text()) - runs = args.runs or manifest.get("default_runs", 50) - warmup = args.warmup if args.warmup is not None else manifest.get("default_warmup", 5) - cases = manifest["cases"] - labels = [label for label, _ in args.bin] - binaries = [(label, resolve_state_test(path)) for label, path in args.bin] - manifest_dir = args.manifest.resolve().parent - - results: list[dict[str, Measurement]] = [] - for case in cases: - res = measure_abba(binaries, case, manifest_dir, runs, warmup, args.rounds) - # Sanity: every binary must reproduce the recorded on-chain gas, or the - # comparison is meaningless (different work being timed). - for label, m in res.items(): - if m.gas_used != case["expected_gas"]: - raise SystemExit( - f"{label} replayed {case['name']} with gas {m.gas_used} != " - f"expected {case['expected_gas']} — corpus/binary mismatch" - ) - results.append(res) - print(f" measured {case['name']} ({len(labels)} bin × {args.rounds} rounds)", file=sys.stderr) - - md, summary, regressions = build_report(cases, results, labels, args.threshold_pct) - title = "## Replay throughput benchmark\n\n" - print(title + md) - if args.markdown_out: - args.markdown_out.write_text(title + md + "\n") - if args.json_out: - args.json_out.write_text(json.dumps(summary, indent=2)) - - if args.fail_on_regression and regressions: - print(f"\n::error::{regressions} transaction(s) regressed beyond {args.threshold_pct:.1f}%", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 7dc0e9460..780505a48 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -2,23 +2,35 @@ ## OVERVIEW CLI toolbox for direct MegaEVM execution (`run`, `tx`, `replay`) with optional forking, tracing, and state dump workflows. +Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` runs on the released `mega-evme` 1.7.1 and `mega-evm` 1.7.1, linked as `mega-evme-legacy` / `mega-evm-legacy` (feature `legacy`, on by default). ## STRUCTURE -- `src/main.rs`: CLI bootstrap and panic hook. -- `src/cmd.rs`: top-level command dispatch and error surface. -- `src/common/`: shared CLI args, state loading, tracing, tx parsing, output printers. +- `src/main.rs`: the binary: installs the panic hook and hands the arguments to `cmd::run_cli`. +- `src/lib.rs`: the library every command lives in: the module declarations and the panic hook (`set_thread_panic_hook`). +- `src/cmd.rs`: argument parsing, engine selection, and dispatch; `--genesis` is applied here (a `run` or `tx` that left `--spec` out runs Satin under it), and the chain is checked against the file before the engine is picked. +- `src/engine.rs`: which engine a spec or a block runs on; the hand-off to the legacy CLI, which gets a legacy spec's arguments unchanged but for `--spec Rex6` added, before any `--`, to a `run` or `tx` that left `--spec` out (the 1.7.1 default is `Rex7`). +- `src/common/`: shared CLI args, state loading, tracing, tx parsing, output printers; `schedule.rs` is the one place a Satin run's hardfork schedule, and so its protocol limits, is chosen, `--override.limits` included. - `src/run/`: bytecode execution command. - `src/tx/`: full transaction execution command with raw-tx override support. -- `src/replay/`: RPC-backed historical transaction replay through block executor. +- `src/replay/`: RPC-backed historical transaction replay through block executor (Satin; a legacy spec is the 1.7.1 CLI's). +- `src/block/`: `replay --block`, whole blocks on either engine compared with the chain: inputs and the block cache (`inputs.rs`), the parent state in plain data (`state.rs`), one executor per engine exchanging only plain data (`satin.rs`, `legacy.rs`), the plain data both hand back (`exec.rs`), records and the comparison (`record.rs`), the driver (`cmd.rs`). +- `tests/satin-differences.md`: the pinned differences between the engines, rendered by `tests/differences.rs` (`UPDATE_EVME_DIFFERENCES=1` rewrites it). ## KEY PATTERNS -- Shared argument groups are flattened from `run` argument structs into sibling commands. +- Shared argument groups are defined in `src/common/` and flattened into each command; `run` re-exports them, and `tx` names them through it (`crate::run::TxArgs`). - Command handlers follow staged flow: parse inputs → build state/env → execute → print summary/receipt/trace. - Replay uses block executor flow, including pre-execution system calls and preceding transactions. - Logging is structured via tracing macros, with explicit progress milestones. - Output paths keep both human-readable summaries and optional machine artifacts (trace/state dump). +- The engine is decided where a command needs it (`cmd.rs` for `run`/`tx`, `replay::Cmd::engine` for a transaction replay, `block/cmd.rs` per block), always through `Engine` (`of_spec`, `of_block`, `of_chain`), and a Satin run's schedule through `common::satin_schedule`; both read the chain's activation table, so they agree. A transaction replay's engine is decided at the timestamp of the block the replay runs it in (its own, or the latest for a pending one), the one whose schedule it runs under: keep a new site to the same pair. +- Output on Satin is additive to the legacy output: every legacy field keeps its name and meaning, and what only Satin counts goes in the `satin` object (`tests/integration.rs` checks it on every fixture pair). + ## ANTI-PATTERNS +- Do not edit or re-implement the legacy leg: it is the released 1.7.1 code, pinned with its dependency versions (`tests/legacy_line.rs`). +- Do not move a package `tests/legacy_line.rs` pins without deciding it there. The leg shares most of its dependencies with the Satin engine and the tool, one copy per compatibility line: the precompiles' backends (`secp256k1`, `k256`, `sha2`, `ripemd`, `aurora-engine-modexp`, arkworks, `blst`, `c-kzg`, `p256`), hashing and word arithmetic (`alloy-primitives`, `ruint`, `sha3`) and the encodings. Each is pinned at the release's version; `alloy-rlp`, `alloy-trie` and the `alloy-sol-types` family, which the Satin engine's alloy 2 line holds above it, are pinned at the version the workspace holds (`AHEAD_OF_THE_RELEASE`). Transport, JSON and derive crates float. +- Do not use `cargo ... -p mega-evme`: the name also matches the linked 1.7.1 package. Use `--manifest-path bin/mega-evme/Cargo.toml`. +- Build no Satin hardfork schedule in the CLI but the counterfactual's (`common::schedule::counterfactual`): the chain's own schedule with Satin from genesis, or the engine's base forks with Satin from genesis for a chain the table does not know. A chain's own Satin schedule — the engine's table's (`mega_evm::hardfork_schedule`, which knows mainnet and testnet and no other chain), or the one `mega_evm::SatinChainConfig::hardforks` builds from the chain's genesis file (`--genesis`) — is used as it is or refused. A replay of a chain neither names is refused unless `--override.spec` names the engine (`engine::unknown_chain`). Under `--genesis` no Satin run is a counterfactual: one the file does not run on Satin is refused (`satin_schedule`), and the file's chain is checked before a command's engine is picked (`check_genesis_chain`). Do not parse a genesis file's Satin keys here either: `SatinChainConfig::from_genesis_config` is the one parser every reader shares. - Do not duplicate chain/spec parsing logic across commands. - Add shared parsing in `src/common/` and reuse. - Do not print partial execution output before final outcome object assembly. @@ -26,8 +38,8 @@ CLI toolbox for direct MegaEVM execution (`run`, `tx`, `replay`) with optional f - Do not mutate command-level defaults in one subcommand without mirroring related aliases/help text. ## WHERE TO LOOK -- Add a new top-level command: `src/cmd.rs` enum + module wiring in `src/main.rs`. +- Add a new top-level command: `src/cmd.rs` enum + module wiring in `src/lib.rs`. - Add a new shared CLI option family: `src/common/*` and flatten into command structs. - Change state-forking or prestate merge semantics: `src/common/state.rs`. -- Change replay hardfork/spec selection: `src/replay/{cmd.rs,hardforks.rs}`. +- Change which engine a spec or block runs on: `src/engine.rs`; which Satin schedule and limits it runs under: `src/common/schedule.rs`, which also holds the genesis file a run was given (`--genesis`) and the activation table `src/engine.rs` reads through it. - Change receipt/summary formatting: `src/common/outcome.rs` and printer helpers. diff --git a/bin/mega-evme/Cargo.toml b/bin/mega-evme/Cargo.toml index ea3a8a712..ebdf0760f 100644 --- a/bin/mega-evme/Cargo.toml +++ b/bin/mega-evme/Cargo.toml @@ -20,9 +20,11 @@ path = "src/main.rs" [dependencies] # megaeth mega-evm = { workspace = true, features = ["default", "test-utils"] } -mega-state-test.workspace = true +mega-evm-legacy = { workspace = true, optional = true, features = ["std", "test-utils"] } +mega-evme-legacy = { workspace = true, optional = true } # revm +revm = { workspace = true, features = ["alloydb"] } revm-inspectors = { workspace = true, features = ["std"] } # alloy @@ -39,6 +41,7 @@ alloy-serde = { workspace = true, features = ["default"] } alloy-sol-types.workspace = true alloy-transport.workspace = true alloy-transport-http = { workspace = true, features = ["reqwest"] } +alloy-trie = { workspace = true, features = ["std", "ethereum"] } # op op-alloy-consensus.workspace = true @@ -48,22 +51,27 @@ op-alloy-rpc-types.workspace = true # misc clap = { workspace = true, features = ["default", "env"] } dirs.workspace = true -reqwest = "0.12" serde.workspace = true serde_json.workspace = true tempfile.workspace = true thiserror.workspace = true -tokio = { workspace = true, features = ["rt", "macros"] } -tower = { version = "0.5", default-features = false } +tokio = { workspace = true, features = ["rt", "rt-multi-thread", "macros"] } +tower.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["fmt", "env-filter", "std", "ansi"] } +zstd.workspace = true [dev-dependencies] mega-evme = { path = ".", features = ["test-utils"] } +mega-state-test-legacy.workspace = true rstest.workspace = true wiremock.workspace = true [features] +default = ["legacy"] +# The legacy leg: specs `Equivalence` through `Rex6` run on the released 1.7.1 CLI and engine, +# linked beside the Satin engine. Without it the binary runs Satin only. +legacy = ["dep:mega-evm-legacy", "dep:mega-evme-legacy"] test-utils = [] [lib] diff --git a/bin/mega-evme/README.md b/bin/mega-evme/README.md index 63ef5a55d..a8510ddf7 100644 --- a/bin/mega-evme/README.md +++ b/bin/mega-evme/README.md @@ -17,11 +17,28 @@ A command-line tool for executing and debugging EVM bytecode, similar to go-ethe `mega-evme` provides three main commands for EVM execution: -| Command | Description | -| -------- | ----------------------------------------------- | -| `run` | Execute arbitrary EVM bytecode directly | -| `tx` | Run a transaction with full transaction context | -| `replay` | Replay an existing transaction from RPC | +| Command | Description | +| -------- | ------------------------------------------------------------------------ | +| `run` | Execute arbitrary EVM bytecode directly | +| `tx` | Run a transaction with full transaction context | +| `replay` | Replay an existing transaction, or whole blocks compared with the chain | + +### Two engines + +Every command runs on the engine its spec names. +`Satin` runs on the Satin engine, this repository's `mega-evm`. +`Equivalence` through `Rex6` run on the legacy engine: the released `mega-evme` and `mega-evm` 1.7.1, linked in as `mega-evme-legacy` and `mega-evm-legacy`, which receive the command's arguments unchanged, so a legacy spec prints exactly what the 1.7.1 tool printed. +`Rex7` is refused: it never activated on a chain, and Satin supersedes it. + +On Satin every output field keeps its legacy name and meaning, and a `satin` object is added with the gas by ledger (`regular_gas`, `state_gas`, `history_gas`, `history_bytes`, `reservoir_remaining`, `floor_gas`) and the limits' counts (`data_size`, `write_records`, `limit_exceeded`, and under `--override.limits` the limits the run was held to, `limits_override`). +`tests/integration.rs` checks that on every fixture pair, and `tests/satin-differences.md` pins what the two engines produce on the same inputs. + +A Satin run is held to Satin's protocol limits, which the spec fixes for every chain. +`--override.limits ` on `run`, `tx` and `replay` replaces the fields it names of those limits, a counterfactual; it is refused on a legacy spec. +`--genesis ` gives a chain the tool does not know, a devnet for one, its own Satin configuration: its genesis file's `satinTime` replaces the tool's table for that chain, read with the parser a node reads it with. +Under it `run` and `tx` default to `--spec Satin`, and a run the file cannot configure — on another chain, on a legacy spec, before the file's `satinTime`, or on a file without Satin keys — is refused rather than run on the tool's table. + +The legacy leg is the default feature `legacy`; `--no-default-features` builds a Satin-only binary. ## Installation @@ -34,10 +51,13 @@ cargo install mega-evme --locked Or build from source: ```bash -cargo build --release -p mega-evme +cargo build --release --manifest-path bin/mega-evme/Cargo.toml # The binary will be at target/release/mega-evme ``` +Select the tool by manifest path, not with `-p mega-evme`: it links the released `mega-evme` 1.7.1, a package of the same name, so `-p mega-evme` names two packages. +The same holds for its tests: `cargo test --manifest-path bin/mega-evme/Cargo.toml`. + The `--locked` flag ensures the exact tested dependency versions are used. ### Prebuilt binary @@ -100,7 +120,7 @@ mega-evme run --create 0x6080604052... | `--input ` | Input data as hex string | | `--inputfile ` | Path to file containing input data | -For detailed documentation, see [run/README.md](src/run/README.md). +For detailed documentation, see [the `run` command's page](../../docs/mega-evme/commands/run.md). --- @@ -113,10 +133,10 @@ Run a transaction with full transaction context. Similar to `run`, but with addi mega-evme tx --input 0x1234 --receiver 0x1234... # Fork state from remote RPC -mega-evme tx --fork --fork.rpc https://rpc.example.com --receiver 0x1234... +mega-evme tx --fork --rpc https://rpc.example.com --receiver 0x1234... # Fork from specific block -mega-evme tx --fork --fork.block 12345678 --receiver 0x1234... +mega-evme tx --fork --rpc https://rpc.example.com --fork.block 12345678 --receiver 0x1234... ``` #### Transaction Options @@ -189,27 +209,25 @@ mega-evme tx --tx-type 4 \ #### Fork Options -| Option | Default | Description | -| ----------------------- | --------------------- | ------------------------------------ | -| `--fork` | false | Enable state forking from RPC | -| `--fork.rpc ` | http://localhost:8545 | RPC URL for forking (env: `RPC_URL`) | -| `--fork.block ` | latest | Block number to fork from | +| Option | Default | Description | +| ----------------------- | --------------- | -------------------------------------------------------------------------------------------- | +| `--fork` | false | Enable state forking from RPC | +| `--rpc ` | none — required | RPC URL for forking (alias `--rpc-url`; `--fork.rpc` is accepted); `RPC_URL` is not read | +| `--fork.block ` | latest | Block number to fork from | --- ### replay Command Replay an existing transaction from RPC. Fetches the transaction and its execution context from a remote node and re-executes it locally. +The spec, and so the engine, comes from the chain's schedule at the block's timestamp; `--override.spec Satin` replays the transaction as it would run on Satin. ```bash # Replay a transaction -mega-evme replay 0x1234...txhash...5678 - -# Replay with custom RPC -mega-evme replay 0x1234...txhash --rpc https://rpc.example.com +mega-evme replay 0x1234...txhash...5678 --rpc https://rpc.example.com # Replay with execution trace -mega-evme replay 0x1234...txhash --trace +mega-evme replay 0x1234...txhash --rpc https://rpc.example.com --trace ``` #### Arguments @@ -220,9 +238,9 @@ mega-evme replay 0x1234...txhash --trace #### Options -| Option | Default | Description | -| ------------- | --------------------- | --------------------------------- | -| `--rpc ` | http://localhost:8545 | RPC URL to fetch transaction from | +| Option | Default | Description | +| ------------- | --------------- | ----------------------------------------------------------------------------------------------------------- | +| `--rpc ` | none — required | RPC URL to fetch the transaction from (alias `--rpc-url`; `--fork.rpc` is accepted); `RPC_URL` is not read | #### Transaction Override Options @@ -246,6 +264,28 @@ mega-evme replay 0x1234...txhash --override.input 0xabcdef mega-evme replay 0x1234...txhash --override.input-file calldata.hex ``` +#### Whole Blocks + +`--block N[..M]` replays whole blocks, each on the engine its spec names, and compares every receipt (status, gas used, cumulative gas used, logs) and the receipts root with the chain's; the state the block leaves is not compared with the header's state root. + +| Option | Description | +| --------------------- | ------------------------------------------------------------------------------------------------------- | +| `--block ` | Replay block N, or blocks N through M | +| `--block-cache

` | Read blocks from DIR; write blocks fetched over `--rpc` to it, with what their replay read beyond the trace | +| `--verify` | Exit with code 2 when a block differs from the chain | +| `--json` | One JSON record per transaction and per block | + +```bash +# Check 200 blocks against the chain and record them +mega-evme replay --block 26400000..26400199 --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify + +# The same blocks on Satin, as NDJSON (the first Satin run reads the L1 fee overhead slot over RPC; +# later runs of the same blocks can drop --rpc) +mega-evme replay --block 26400000..26400199 --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --override.spec Satin --json > satin.ndjson +``` + +Fetching a block needs an archive endpoint with the `debug` namespace (`debug_traceBlockByNumber` with `prestateTracer`); a cached block replays offline. + --- ## Common Options @@ -265,7 +305,7 @@ These options are available across all commands. | Option | Default | Description | | ---------------------- | ------- | ----------------------------------------- | -| `--spec ` | Rex7 | Spec: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` (`MiniRex1`/`MiniRex2` are aliases executing `Equivalence`/`MiniRex` behavior) | +| `--spec ` | Rex6 | Spec: `Satin` (the Satin engine), or `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` (the legacy engine; `MiniRex1`/`MiniRex2` are aliases executing `Equivalence`/`MiniRex` behavior); `Satin` by default under `--genesis` | | `--chain-id ` | 6342 | Chain ID | ### Block Environment @@ -350,7 +390,7 @@ mega-evme run --create 0x6080604052... --dump # Fork mainnet state and execute against a contract mega-evme tx \ --fork \ - --fork.rpc https://eth-mainnet.example.com \ + --rpc https://eth-mainnet.example.com \ --receiver 0xContractAddress \ --input 0xMethodSelector... ``` @@ -408,4 +448,4 @@ State files use JSON format with Ethereum quantity encoding: ## See Also -- [run Command Documentation](src/run/README.md) +- [The `run`, `tx` and `replay` command pages](../../docs/mega-evme/commands/) diff --git a/bin/mega-evme/src/block/cmd.rs b/bin/mega-evme/src/block/cmd.rs new file mode 100644 index 000000000..3c78654d9 --- /dev/null +++ b/bin/mega-evme/src/block/cmd.rs @@ -0,0 +1,344 @@ +//! `mega-evme replay --block`: replay whole blocks and compare them with the chain. + +use std::path::PathBuf; + +use clap::Args; +use tracing::info; + +use super::{ + inputs::BlockSource, + record::{records, BlockRecord, TxRecord}, + satin, + state::{BlockState, ParentStateRpc}, +}; +use crate::{ + common::{EvmeError, LimitsOverride, Result, RpcArgs}, + engine::Engine, +}; + +/// Block replay configuration +#[derive(Args, Debug, Clone, Default)] +#[command(next_help_heading = "Block Replay Options")] +pub struct BlockArgs { + /// Replay whole blocks instead of one transaction: `N`, or `N..M` for blocks N through M. + /// Each block runs on the engine its spec names: the one `--override.spec` forces, or the + /// one the chain's schedule gives at the block's timestamp. + #[arg( + long = "block", + value_name = "N[..M]", + value_parser = parse_block_range, + conflicts_with_all = [ + "tx_hash", "dump_fixture", "trace", "dump", "gas_limit", "value", "input", + "input_file", "capture_file", "replay_file", + ], + )] + pub block: Option, + + /// Block cache directory. A block is read from it when it is there, and a block fetched over + /// `--rpc` is written to it, with the state its replay read beyond the block's trace, so the + /// next replay of it is offline. Layout: `blocks//.json.zst` and + /// `codes//.bin`. + #[arg(long = "block-cache", value_name = "DIR", requires = "block")] + pub block_cache: Option, + + /// Compare every replayed transaction (status, gas used, cumulative gas used, logs) and the + /// block's receipts root with the chain's, and exit with code 2 when a block differs. + #[arg(long = "verify", requires = "block")] + pub verify: bool, +} + +/// An inclusive range of block numbers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BlockRange { + /// The first block. + pub from: u64, + /// The last block. + pub to: u64, +} + +/// Parses `N` or `N..M`, with `M >= N`. +pub fn parse_block_range(s: &str) -> std::result::Result { + let number = |part: &str| { + part.trim().parse::().map_err(|e| format!("invalid block number {part:?}: {e}")) + }; + let (from, to) = match s.split_once("..") { + Some((from, to)) => (number(from)?, number(to)?), + None => (number(s)?, number(s)?), + }; + if to < from { + return Err(format!("the range {s} ends before it starts")); + } + if from == 0 { + return Err("block 0 has no parent to replay it on".to_string()); + } + Ok(BlockRange { from, to }) +} + +/// What a replay of blocks came to. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct ReplaySummary { + /// Blocks replayed. + pub blocks: usize, + /// Blocks whose every transaction and receipts root match the chain. + pub matching: usize, + /// Blocks that could not be replayed, with why. + pub failed: Vec<(u64, String)>, +} + +impl ReplaySummary { + /// The process exit code: 1 when a block could not be replayed, 2 when `verify` and a block + /// differs from the chain, 0 otherwise. + pub fn exit_code(&self, verify: bool) -> i32 { + if !self.failed.is_empty() { + 1 + } else if verify && self.matching != self.blocks { + 2 + } else { + 0 + } + } +} + +/// Replays `range` and prints a record per transaction and per block (`json`) or a line per +/// block. +pub async fn replay_blocks( + range: BlockRange, + args: &BlockArgs, + rpc_args: &RpcArgs, + bucket_capacities: &[(u32, u64)], + spec_override: Option<&str>, + limits_override: Option<&LimitsOverride>, + json: bool, +) -> Result { + let (provider, chain_id) = if rpc_args.rpc_url.is_some() { + let (provider, chain_id) = rpc_args.build_lookup_provider().await?; + (Some(provider), Some(chain_id)) + } else if args.block_cache.is_some() { + (None, None) + } else { + return Err(EvmeError::InvalidInput( + "'replay --block' needs '--block-cache ', '--rpc ', or both".to_string(), + )); + }; + let forced_engine = spec_override.map(Engine::of_spec).transpose()?; + let source = BlockSource::new(args.block_cache.clone(), provider, chain_id); + let mut codes = source.code_store(); + let mut summary = ReplaySummary::default(); + + for number in range.from..=range.to { + summary.blocks += 1; + let outcome = async { + let mut inputs = source.load(number, &mut codes).await?; + let engine = match forced_engine { + Some(engine) => engine, + None => Engine::of_block(inputs.chain_id, inputs.header.timestamp)?, + }; + // The parent's timestamp is fetched only for a Satin block whose schedule makes the + // activation-block rule depend on it, so every other block replays from the cache. + if engine == Engine::Satin && + inputs.parent_timestamp.is_none() && + satin::needs_parent_timestamp(inputs.chain_id, inputs.header.timestamp)? + { + source.complete_parent_timestamp(&mut inputs).await?; + } + let fallback = + source.provider().and_then(|p| ParentStateRpc::new(p.clone(), number - 1)); + let mut state = + BlockState::new(inputs.prestate.clone(), std::mem::take(&mut codes), fallback); + let executed = execute_block( + engine, + &inputs, + bucket_capacities, + spec_override, + limits_override, + &mut state, + ); + let rpc_reads = state.fallback_reads; + let BlockState { prestate, codes: mut store, .. } = state; + let result = match executed { + Ok((executed, spec)) => { + if !inputs.from_cache || rpc_reads > 0 { + source.store(&inputs, &prestate, &mut store)?; + } + Ok(records(&inputs, &executed, engine, &spec, rpc_reads)) + } + Err(e) => Err(e), + }; + codes = store; + result + } + .await; + match outcome { + Ok((txs, block)) => { + if block.matches_chain { + summary.matching += 1; + } + print_block(&txs, &block, json); + } + Err(e) => { + let message = e.to_string(); + if json { + println!( + "{}", + serde_json::json!({ "kind": "block", "block": number, "error": message }) + ); + } else { + println!("block {number} error: {}", crate::sanitize_terminal_text(&message)); + } + summary.failed.push((number, message)); + } + } + } + info!(?summary, "Block replay finished"); + if !json { + println!( + "{} block(s) replayed: {} match the chain, {} differ, {} failed", + summary.blocks, + summary.matching, + summary.blocks - summary.matching - summary.failed.len(), + summary.failed.len() + ); + } + Ok(summary) +} + +/// Executes the block `inputs` describes on `engine` over `state`, returning what it produced +/// and the spec it ran under: `spec_override` when given, otherwise, on the legacy engine, the +/// spec the chain's schedule gives at the block's timestamp. +/// +/// `limits_override` replaces the protocol limits a Satin block runs under; a legacy block, +/// whose limits its spec fixes, is refused with one. Under a genesis file (`--genesis`) a block of +/// another chain is refused first, and then a legacy block: the legacy engine runs a chain on its +/// own table, which knows nothing of the file, and for a chain it does not know that is a spec no +/// chain ran. +pub fn execute_block( + engine: Engine, + inputs: &super::inputs::BlockInputs, + bucket_capacities: &[(u32, u64)], + spec_override: Option<&str>, + limits_override: Option<&LimitsOverride>, + state: &mut BlockState, +) -> Result<(super::exec::ExecutedBlock, String)> { + crate::common::check_genesis_chain(inputs.chain_id)?; + match engine { + Engine::Satin => { + let executed = satin::execute( + inputs.chain_id, + &inputs.header, + inputs.parent_timestamp, + &inputs.transactions, + bucket_capacities, + limits_override, + state, + )?; + Ok((executed, mega_evm::MegaSpecId::SATIN.to_string())) + } + Engine::Legacy if limits_override.is_some() => Err(EvmeError::InvalidInput(format!( + "block {} runs on the legacy engine, whose limits its spec fixes; --override.limits \ + applies to Satin only", + inputs.header.number + ))), + Engine::Legacy if crate::common::genesis_in_use() => Err(EvmeError::InvalidInput(format!( + "block {} runs on the legacy engine, which runs a chain on its own table; \ + --genesis applies to Satin blocks only", + inputs.header.number + ))), + Engine::Legacy => run_legacy_block(inputs, bucket_capacities, spec_override, state), + } +} + +#[cfg(feature = "legacy")] +fn run_legacy_block( + inputs: &super::inputs::BlockInputs, + bucket_capacities: &[(u32, u64)], + spec_override: Option<&str>, + state: &mut BlockState, +) -> Result<(super::exec::ExecutedBlock, String)> { + let spec = + super::legacy::resolve_spec(inputs.chain_id, inputs.header.timestamp, spec_override)?; + let executed = super::legacy::execute( + inputs.chain_id, + &inputs.header, + &inputs.transactions, + bucket_capacities, + spec_override, + state, + )?; + Ok((executed, spec)) +} + +#[cfg(not(feature = "legacy"))] +fn run_legacy_block( + inputs: &super::inputs::BlockInputs, + _bucket_capacities: &[(u32, u64)], + _spec_override: Option<&str>, + _state: &mut BlockState, +) -> Result<(super::exec::ExecutedBlock, String)> { + Err(EvmeError::InvalidInput(format!( + "block {} runs on the legacy engine, and this build runs Satin only (built without \ + the `legacy` feature)", + inputs.header.number + ))) +} + +/// Prints a block's records: every record as a JSON line, or one line for the block. +fn print_block(txs: &[TxRecord], block: &BlockRecord, json: bool) { + if json { + for tx in txs { + println!("{}", serde_json::to_string(tx).expect("a record serializes")); + } + println!("{}", serde_json::to_string(block).expect("a record serializes")); + return; + } + let verdict = if block.matches_chain { + "matches the chain".to_string() + } else { + let root = if block.receipts_root == block.chain_receipts_root { + "" + } else { + ", receipts root differs" + }; + format!("{} of {} transactions differ{root}", block.differing, block.transactions) + }; + let ledgers = block.satin.as_ref().map_or_else(String::new, |satin| { + let overridden = if satin.limits_override.is_some() { ", limits overridden" } else { "" }; + format!( + " [regular {} state {} history {}{overridden}]", + satin.regular_gas, satin.state_gas, satin.history_gas + ) + }); + println!( + "block {} {} {} {} txs gas {}{ledgers} (chain {}) {verdict}", + block.block, + block.engine, + block.spec, + block.transactions, + block.gas_used, + block.chain_gas_used, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_block_ranges_parse() { + assert_eq!(parse_block_range("7").unwrap(), BlockRange { from: 7, to: 7 }); + assert_eq!(parse_block_range("7..9").unwrap(), BlockRange { from: 7, to: 9 }); + assert!(parse_block_range("9..7").is_err()); + assert!(parse_block_range("0").is_err(), "block 0 has no parent"); + assert!(parse_block_range("x").is_err()); + } + + #[test] + fn test_exit_codes() { + let clean = ReplaySummary { blocks: 2, matching: 2, failed: vec![] }; + assert_eq!(clean.exit_code(true), 0); + let differing = ReplaySummary { blocks: 2, matching: 1, failed: vec![] }; + assert_eq!(differing.exit_code(true), 2); + assert_eq!(differing.exit_code(false), 0, "a difference is a failure only when verifying"); + let failed = ReplaySummary { blocks: 2, matching: 1, failed: vec![(1, "x".into())] }; + assert_eq!(failed.exit_code(true), 1); + } +} diff --git a/bin/mega-evme/src/block/exec.rs b/bin/mega-evme/src/block/exec.rs new file mode 100644 index 000000000..7a2960ffc --- /dev/null +++ b/bin/mega-evme/src/block/exec.rs @@ -0,0 +1,87 @@ +//! What either engine hands back for a block: plain data, the same shape from both. +//! +//! An executor takes the block's header fields, its transactions as EIP-2718 envelopes and a +//! [`BlockState`](super::state::BlockState), and returns every transaction's receipt as its +//! EIP-2718 encoding and the fields a comparison reads. No type of either revm line crosses. + +use alloy_primitives::{Bytes, Log}; + +use mega_evm::ProtocolLimits; + +use crate::common::SatinReport; + +/// How an included transaction ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecStatus { + /// It succeeded. + Success, + /// It reverted. + Revert, + /// It halted. + Halt, +} + +impl ExecStatus { + /// The status's name in output. + pub const fn name(self) -> &'static str { + match self { + Self::Success => "success", + Self::Revert => "revert", + Self::Halt => "halt", + } + } +} + +/// A receipt as the engine built it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReceiptData { + /// The receipt's EIP-2718 encoding, which the receipts root is built from. + pub encoded: Bytes, + /// Whether the transaction succeeded. + pub success: bool, + /// The block's gas used after the transaction. + pub cumulative_gas_used: u64, + /// The logs. + pub logs: Vec, +} + +/// What happened to one transaction of the block. +#[derive(Debug, Clone)] +pub enum TxResult { + /// The transaction ran and its receipt is in the block. + Included { + /// How it ended. + status: ExecStatus, + /// The halt reason or the decoded revert, when it did not succeed. + reason: Option, + /// Its receipt. + receipt: ReceiptData, + /// What Satin counted, on the Satin engine. + satin: Option, + }, + /// The engine refused the transaction; it is not in the block and changed nothing. + Refused { + /// Why. + reason: String, + }, +} + +/// What executing a block produced. +#[derive(Debug, Clone)] +pub struct ExecutedBlock { + /// One result per transaction, in block order. + pub transactions: Vec, + /// The protocol limits a Satin block ran under when `--override.limits` replaced the + /// schedule's; `None` otherwise, and on the legacy engine. + pub limits_override: Option, +} + +impl ExecutedBlock { + /// The receipts of the included transactions, in order. + pub fn receipts(&self) -> impl Iterator { + self.transactions.iter().filter_map(|tx| match tx { + TxResult::Included { receipt, .. } => Some(receipt), + TxResult::Refused { .. } => None, + }) + } +} diff --git a/bin/mega-evme/src/block/inputs.rs b/bin/mega-evme/src/block/inputs.rs new file mode 100644 index 000000000..dd34de4f6 --- /dev/null +++ b/bin/mega-evme/src/block/inputs.rs @@ -0,0 +1,412 @@ +//! Everything replaying a block needs from the chain, fetched over RPC or read from a block cache. +//! +//! Three requests describe a block: the block with its transactions, its receipts, and a +//! `prestateTracer` trace from which its pre-state is built. The block cache keeps them per block +//! as one zstd-compressed JSON file, `blocks//.json.zst`, with contract code split +//! out into a shared store, `codes//.bin`. + +use std::path::{Path, PathBuf}; + +use alloy_consensus::BlockHeader as _; +use alloy_eips::Encodable2718; +use alloy_primitives::{keccak256, Address, Bytes, Log, B256, U256, U64}; +use alloy_provider::Provider; +use alloy_rpc_types_eth::Block; +use op_alloy_rpc_types::Transaction; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::state::{write_atomically, BlockPrestate, CodeStore}; +use crate::common::{EvmeError, OpProvider, Result}; + +/// Version of the cached block format. +const CACHE_VERSION: u32 = 1; + +/// zstd level cached blocks are written at. +const CACHE_ZSTD_LEVEL: i32 = 3; + +/// A block's inputs as cached: the RPC responses for the block and its receipts, the pre-state +/// built from its trace, and the parent block's timestamp. +#[derive(Debug, Serialize, Deserialize)] +pub struct CachedBlock { + /// Format version. + pub version: u32, + /// Chain the block belongs to. + pub chain_id: u64, + /// `eth_getBlockByNumber` result, with full transactions. + pub block: Value, + /// `eth_getBlockReceipts` result. + pub receipts: Value, + /// Pre-state; codes live in the code store. + pub prestate: BlockPrestate, + /// The parent block's timestamp, which decides whether a fork activates in the block. + /// + /// Kept once a replay of the block on Satin needed it; absent otherwise, and from an entry + /// written before the cache kept it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent_timestamp: Option, +} + +/// The header fields block execution reads, in plain data. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeaderFields { + /// The block's hash. + pub hash: B256, + /// The block's number. + pub number: u64, + /// The block's timestamp. + pub timestamp: u64, + /// The block's beneficiary. + pub beneficiary: Address, + /// The block's gas limit. + pub gas_limit: u64, + /// The block's base fee. + pub base_fee: u64, + /// The block's difficulty. + pub difficulty: U256, + /// The block's `mixHash`, which is its `PREVRANDAO`. + pub mix_hash: B256, + /// The block's excess blob gas. + pub excess_blob_gas: u64, + /// The parent block's hash. + pub parent_hash: B256, + /// The parent beacon block root. + pub parent_beacon_block_root: Option, + /// The block's extra data. + pub extra_data: Bytes, + /// The block's receipts root. + pub receipts_root: B256, +} + +/// A transaction of the block, as either engine takes it: its EIP-2718 envelope and its sender. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TxInput { + /// The transaction's hash. + pub hash: B256, + /// The EIP-2718 encoding of the transaction. + pub envelope: Bytes, + /// The recovered sender. + pub sender: Address, +} + +/// A log as the chain recorded it. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct ChainLog { + /// The emitting contract. + pub address: Address, + /// The topics. + pub topics: Vec, + /// The data. + pub data: Bytes, +} + +/// The parts of a receipt a replay is compared with. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChainReceipt { + /// Hash of the transaction. + pub transaction_hash: B256, + /// Gas used as the chain recorded it. + pub gas_used: U64, + /// Cumulative gas used as the chain recorded it. + pub cumulative_gas_used: U64, + /// `0x1` for success. + #[serde(default)] + pub status: Option, + /// Logs as the chain recorded them. + #[serde(default)] + pub logs: Vec, +} + +impl ChainReceipt { + /// Whether the transaction succeeded. + pub fn success(&self) -> bool { + self.status.is_some_and(|status| status == U64::from(1)) + } + + /// Whether `logs` are the chain's logs, in order. + pub fn logs_equal(&self, logs: &[Log]) -> bool { + self.logs.len() == logs.len() && + self.logs.iter().zip(logs).all(|(chain, log)| { + chain.address == log.address && + chain.topics == log.data.topics() && + chain.data == log.data.data + }) + } +} + +/// A block ready to replay. +#[derive(Debug)] +pub struct BlockInputs { + /// Chain the block belongs to. + pub chain_id: u64, + /// The header fields execution reads. + pub header: HeaderFields, + /// The transactions, in block order. + pub transactions: Vec, + /// Receipts, in transaction order. + pub receipts: Vec, + /// The part of the parent block's state the block reads. + pub prestate: BlockPrestate, + /// The parent block's timestamp, when the cache holds it or a Satin replay of the block + /// fetched it ([`BlockSource::complete_parent_timestamp`]). + pub parent_timestamp: Option, + /// Whether the block cache holds these inputs as they are: false for inputs fetched over RPC, + /// wholly or in part, which the replay writes to the cache. + pub from_cache: bool, + /// The block and receipts responses as received, for writing the cache entry. + raw: (Value, Value), +} + +impl BlockInputs { + /// Parses the RPC responses of a block into its inputs. + pub fn from_responses( + chain_id: u64, + block: Value, + receipts: Value, + prestate: BlockPrestate, + parent_timestamp: Option, + from_cache: bool, + ) -> Result { + let parsed: Block = serde_json::from_value(block.clone()) + .map_err(|e| EvmeError::RpcError(format!("Malformed block: {e}")))?; + let chain_receipts: Vec = serde_json::from_value(receipts.clone()) + .map_err(|e| EvmeError::RpcError(format!("Malformed receipts: {e}")))?; + let header = &parsed.header; + let number = header.number(); + let fields = HeaderFields { + hash: header.hash, + number, + timestamp: header.timestamp(), + beneficiary: header.beneficiary(), + gas_limit: header.gas_limit(), + base_fee: header.base_fee_per_gas().unwrap_or_default(), + difficulty: header.difficulty(), + mix_hash: header.mix_hash().unwrap_or_default(), + excess_blob_gas: header.excess_blob_gas().ok_or_else(|| { + EvmeError::RpcError(format!("block {number} has no excess_blob_gas")) + })?, + parent_hash: header.parent_hash(), + parent_beacon_block_root: header.parent_beacon_block_root(), + extra_data: header.extra_data().clone(), + receipts_root: header.receipts_root(), + }; + let raw_txs = block["transactions"].as_array().cloned().unwrap_or_default(); + let transactions = parsed + .transactions + .into_transactions() + .zip(raw_txs) + .map(|(tx, raw)| tx_input(tx, &raw)) + .collect::>>()?; + if transactions.is_empty() && + block["transactions"].as_array().is_some_and(|t| !t.is_empty()) + { + return Err(EvmeError::RpcError(format!( + "block {number} lists transaction hashes, not transactions" + ))); + } + if chain_receipts.len() != transactions.len() { + return Err(EvmeError::RpcError(format!( + "block {number} has {} transactions but {} receipts", + transactions.len(), + chain_receipts.len() + ))); + } + for (tx, receipt) in transactions.iter().zip(&chain_receipts) { + if tx.hash != receipt.transaction_hash { + return Err(EvmeError::RpcError(format!( + "block {number}: receipt of {} listed at the position of {}", + receipt.transaction_hash, tx.hash + ))); + } + } + Ok(Self { + chain_id, + header: fields, + transactions, + receipts: chain_receipts, + prestate, + parent_timestamp, + from_cache, + raw: (block, receipts), + }) + } + + /// The cache entry of these inputs, with `prestate` as the block's pre-state. + fn to_cached(&self, prestate: &BlockPrestate) -> CachedBlock { + CachedBlock { + version: CACHE_VERSION, + chain_id: self.chain_id, + block: self.raw.0.clone(), + receipts: self.raw.1.clone(), + prestate: prestate.clone(), + parent_timestamp: self.parent_timestamp, + } + } +} + +/// The EIP-2718 envelope and sender of `tx`, whose re-encoding must hash to the hash the chain +/// reports for it: the envelope is rebuilt from the RPC object, and a field the object dropped +/// would otherwise replay a different transaction. +fn tx_input(tx: Transaction, raw: &Value) -> Result { + let reported: B256 = serde_json::from_value(raw["hash"].clone()) + .map_err(|e| EvmeError::RpcError(format!("Malformed transaction hash: {e}")))?; + let recovered = tx.inner.inner; + let sender = recovered.signer(); + let envelope = Bytes::from(recovered.inner().encoded_2718()); + let hash = keccak256(&envelope); + if hash != reported { + return Err(EvmeError::RpcError(format!( + "transaction {reported} re-encodes to a different hash, {hash}" + ))); + } + Ok(TxInput { hash, envelope, sender }) +} + +/// Where a block's inputs come from: a block cache, an RPC provider, or both, in that order. +#[derive(Debug)] +pub struct BlockSource { + cache_dir: Option, + provider: Option, + chain_id: Option, +} + +impl BlockSource { + /// A source reading `cache_dir` first and `provider` (on chain `chain_id`) for what the + /// cache lacks. + pub fn new( + cache_dir: Option, + provider: Option, + chain_id: Option, + ) -> Self { + Self { cache_dir, provider, chain_id } + } + + /// The code store the cache keeps codes in. + pub fn code_store(&self) -> CodeStore { + CodeStore::new(self.cache_dir.as_ref().map(|dir| dir.join("codes"))) + } + + /// The provider, when there is one. + pub fn provider(&self) -> Option<&OpProvider> { + self.provider.as_ref() + } + + fn block_path(dir: &Path, number: u64) -> PathBuf { + dir.join("blocks").join((number / 10_000).to_string()).join(format!("{number}.json.zst")) + } + + /// The inputs of block `number`, adding the codes its trace carries to `codes`. + pub async fn load(&self, number: u64, codes: &mut CodeStore) -> Result { + if let Some(dir) = &self.cache_dir { + let path = Self::block_path(dir, number); + if path.exists() { + let compressed = std::fs::read(&path)?; + let json = zstd::decode_all(compressed.as_slice())?; + let cached: CachedBlock = serde_json::from_slice(&json) + .map_err(|e| EvmeError::FixtureError(format!("{}: {e}", path.display())))?; + if cached.version != CACHE_VERSION { + return Err(EvmeError::FixtureError(format!( + "{}: cache version {} is not {CACHE_VERSION}", + path.display(), + cached.version + ))); + } + if let Some(chain_id) = self.chain_id { + if cached.chain_id != chain_id { + return Err(EvmeError::FixtureError(format!( + "{}: cached for chain {}, the RPC serves chain {chain_id}", + path.display(), + cached.chain_id + ))); + } + } + return BlockInputs::from_responses( + cached.chain_id, + cached.block, + cached.receipts, + cached.prestate, + cached.parent_timestamp, + true, + ); + } + } + let (Some(provider), Some(chain_id)) = (&self.provider, self.chain_id) else { + return Err(EvmeError::Other(format!( + "block {number} is not in the block cache, and there is no '--rpc' to fetch it" + ))); + }; + let tag = format!("0x{number:x}"); + let request = |method: &'static str, params: Value| async move { + provider + .raw_request::<_, Value>(method.into(), params) + .await + .map_err(|e| EvmeError::RpcError(format!("{method} of block {number}: {e}"))) + }; + let block = request("eth_getBlockByNumber", json!([tag, true])).await?; + if block.is_null() { + return Err(EvmeError::BlockNotFound(number)); + } + let receipts = request("eth_getBlockReceipts", json!([tag])).await?; + let trace = + request("debug_traceBlockByNumber", json!([tag, { "tracer": "prestateTracer" }])) + .await?; + let prestate = BlockPrestate::from_block_trace(trace, codes)?; + BlockInputs::from_responses(chain_id, block, receipts, prestate, None, false) + } + + /// Fetches the parent block's timestamp `inputs` lack, over RPC, and marks the inputs to be + /// written back to the cache with it; without a provider, leaves them as they are. + /// + /// Only a block that runs on Satin under a schedule that makes the answer depend on it needs + /// the timestamp ([`needs_parent_timestamp`](super::satin::needs_parent_timestamp)), so the + /// caller asks for it then and only then: a block another engine runs, or one no parent could + /// make an activation block, replays from what the cache holds. + pub async fn complete_parent_timestamp(&self, inputs: &mut BlockInputs) -> Result<()> { + if inputs.parent_timestamp.is_some() { + return Ok(()); + } + if let Some(timestamp) = self.parent_timestamp(inputs.header.number).await? { + inputs.parent_timestamp = Some(timestamp); + inputs.from_cache = false; + } + Ok(()) + } + + /// The timestamp of block `number`'s parent, over RPC; `None` without a provider, or for + /// block 0, which has no parent. + async fn parent_timestamp(&self, number: u64) -> Result> { + let (Some(provider), Some(parent)) = (&self.provider, number.checked_sub(1)) else { + return Ok(None); + }; + let header: Value = provider + .raw_request("eth_getBlockByNumber".into(), json!([format!("0x{parent:x}"), false])) + .await + .map_err(|e| { + EvmeError::RpcError(format!("eth_getBlockByNumber of block {parent}: {e}")) + })?; + if header.is_null() { + return Err(EvmeError::BlockNotFound(parent)); + } + let timestamp: U64 = serde_json::from_value(header["timestamp"].clone()).map_err(|e| { + EvmeError::RpcError(format!("block {parent} has a malformed timestamp: {e}")) + })?; + Ok(Some(timestamp.to())) + } + + /// Writes `inputs` to the cache with `prestate` as their pre-state, and the codes it holds. + /// A no-op without a cache directory. + pub fn store( + &self, + inputs: &BlockInputs, + prestate: &BlockPrestate, + codes: &mut CodeStore, + ) -> Result<()> { + let Some(dir) = &self.cache_dir else { return Ok(()) }; + codes.persist()?; + let json = serde_json::to_vec(&inputs.to_cached(prestate)) + .map_err(|e| EvmeError::Other(format!("serializing block cache entry: {e}")))?; + let compressed = zstd::encode_all(json.as_slice(), CACHE_ZSTD_LEVEL)?; + write_atomically(&Self::block_path(dir, inputs.header.number), &compressed) + } +} diff --git a/bin/mega-evme/src/block/legacy.rs b/bin/mega-evme/src/block/legacy.rs new file mode 100644 index 000000000..8cbdfbdb8 --- /dev/null +++ b/bin/mega-evme/src/block/legacy.rs @@ -0,0 +1,204 @@ +//! A block on the legacy engine, `mega-evm` 1.7.1. +//! +//! Everything of the legacy line is reached through `mega_evm_legacy`'s own re-exports, so no +//! legacy crate is named at a version of its own here. The block is configured as the 1.7.1 +//! `replay` command configures the block of the transaction it replays: the chain's schedule, +//! the spec it gives at the block's timestamp unless one is forced, the block limits of the +//! hardfork active at the block, and a transaction runtime limit of the forced spec when one is. + +use alloy_primitives::{Address, B256, U256}; +use mega_evm_legacy::{ + alloy_consensus::transaction::Recovered, + alloy_eips::{Decodable2718, Encodable2718}, + alloy_evm::{block::BlockExecutor, EvmEnv}, + alloy_op_evm::block::OpAlloyReceiptBuilder, + op_alloy_consensus::OpTxEnvelope, + op_revm::OpHaltReason, + revm::{ + context::{result::ExecutionResult, BlockEnv, CfgEnv}, + database::{DBErrorMarker, State}, + primitives::eip4844, + state::{AccountInfo, Bytecode}, + Database, + }, + AHashBucketHasher, BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, + MegaBlockExecutorFactory, MegaEvmFactory, MegaHaltReason, MegaHardforks, MegaSpecId, + TestExternalEnvs, +}; + +use super::{ + exec::{ExecStatus, ExecutedBlock, ReceiptData, TxResult}, + inputs::{HeaderFields, TxInput}, + state::{BlockState, StateReadError}, +}; +use crate::common::{decode_revert_reason, EvmeError, Result}; + +impl DBErrorMarker for StateReadError {} + +/// The legacy engine's view of a [`BlockState`]. +#[derive(Debug)] +struct LegacyDb<'a>(&'a mut BlockState); + +impl Database for LegacyDb<'_> { + type Error = StateReadError; + + fn basic(&mut self, address: Address) -> std::result::Result, Self::Error> { + Ok(self.0.account(address)?.map(|account| { + AccountInfo::new( + account.balance, + account.nonce, + account.code_hash, + Bytecode::new_raw(account.code), + ) + })) + } + + fn code_by_hash(&mut self, code_hash: B256) -> std::result::Result { + Ok(Bytecode::new_raw(self.0.code(code_hash)?)) + } + + fn storage(&mut self, address: Address, index: U256) -> std::result::Result { + self.0.storage(address, index) + } + + fn block_hash(&mut self, number: u64) -> std::result::Result { + self.0.block_hash(number) + } +} + +/// The legacy spec a block of `chain_id` at `timestamp` runs, or `spec_override`. +pub(super) fn resolve_spec( + chain_id: u64, + timestamp: u64, + spec_override: Option<&str>, +) -> Result { + if let Some(name) = spec_override { + let spec: MegaSpecId = name + .parse() + .map_err(|e| EvmeError::InvalidInput(format!("Invalid legacy spec {name:?}: {e:?}")))?; + return Ok(spec.to_string()); + } + Ok(mega_evm_legacy::hardfork_schedule(chain_id).spec_id(timestamp).to_string()) +} + +/// Executes the block `header` describes, with `transactions`, on the legacy engine over `state`. +pub(super) fn execute( + chain_id: u64, + header: &HeaderFields, + transactions: &[TxInput], + bucket_capacities: &[(u32, u64)], + spec_override: Option<&str>, + state: &mut BlockState, +) -> Result { + let hardforks = mega_evm_legacy::hardfork_schedule(chain_id); + let mut cfg = CfgEnv::default(); + cfg.chain_id = chain_id; + cfg.spec = hardforks.spec_id(header.timestamp); + let hardfork = hardforks.hardfork(header.timestamp).ok_or_else(|| { + EvmeError::Other(format!("no MegaHardfork active at timestamp {}", header.timestamp)) + })?; + let mut block_limits = + BlockLimits::from_hardfork_and_block_gas_limit(hardfork, header.gas_limit); + if let Some(name) = spec_override { + let spec: MegaSpecId = name + .parse() + .map_err(|e| EvmeError::InvalidInput(format!("Invalid legacy spec {name:?}: {e:?}")))?; + cfg.spec = spec; + block_limits = block_limits.with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); + } + + let mut block_env = BlockEnv { + number: U256::from(header.number), + beneficiary: header.beneficiary, + timestamp: U256::from(header.timestamp), + gas_limit: header.gas_limit, + basefee: header.base_fee, + difficulty: header.difficulty, + prevrandao: Some(header.mix_hash), + blob_excess_gas_and_price: None, + }; + block_env.set_blob_excess_gas_and_price( + header.excess_blob_gas, + eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_CANCUN, + ); + + let mut envs = TestExternalEnvs::::new(); + for &(bucket, capacity) in bucket_capacities { + envs = envs.with_bucket_capacity(bucket, capacity); + } + let factory = MegaBlockExecutorFactory::new( + &hardforks, + MegaEvmFactory::new().with_external_env_factory(envs), + OpAlloyReceiptBuilder::default(), + ); + let block_ctx = MegaBlockExecutionCtx::new( + header.parent_hash, + header.parent_beacon_block_root, + header.extra_data.clone(), + block_limits, + ); + + let result = { + let mut db = State::builder().with_database(LegacyDb(state)).with_bundle_update().build(); + let mut executor = factory.create_executor(&mut db, block_ctx, EvmEnv::new(cfg, block_env)); + let mut run = || -> Result { + executor + .apply_pre_execution_changes() + .map_err(|e| EvmeError::Other(format!("pre-block changes: {e}")))?; + let mut results = Vec::with_capacity(transactions.len()); + for tx in transactions { + let envelope = OpTxEnvelope::decode_2718(&mut tx.envelope.as_ref()) + .map_err(|e| EvmeError::Other(format!("decoding {}: {e}", tx.hash)))?; + let recovered = Recovered::new_unchecked(envelope, tx.sender); + let outcome = match executor.run_transaction(recovered.as_recovered_ref()) { + Ok(outcome) => outcome, + Err(e) => { + results.push(TxResult::Refused { reason: e.to_string() }); + continue; + } + }; + let (status, reason) = match &outcome.inner.result { + ExecutionResult::Success { .. } => (ExecStatus::Success, None), + ExecutionResult::Revert { output, .. } => { + (ExecStatus::Revert, Some(decode_revert_reason(output))) + } + ExecutionResult::Halt { reason, .. } => { + (ExecStatus::Halt, Some(halt_reason(reason))) + } + }; + if let Err(e) = executor.commit_transaction_outcome(outcome) { + results.push(TxResult::Refused { reason: e.to_string() }); + continue; + } + let receipt = + executor.receipts.last().expect("a committed transaction has a receipt"); + results.push(TxResult::Included { + status, + reason, + receipt: ReceiptData { + encoded: receipt.encoded_2718().into(), + success: receipt.status(), + cumulative_gas_used: receipt.cumulative_gas_used(), + logs: receipt.logs().to_vec(), + }, + satin: None, + }); + } + Ok(ExecutedBlock { transactions: results, limits_override: None }) + }; + run() + }; + if let Some(miss) = &state.miss { + return Err(EvmeError::Other(format!("block {}: {miss}", header.number))); + } + result +} + +/// A legacy halt reason, printed as the 1.7.1 tool prints it. +fn halt_reason(reason: &MegaHaltReason) -> String { + match reason { + MegaHaltReason::Base(OpHaltReason::Base(eth)) => format!("{eth:?}"), + MegaHaltReason::Base(op) => format!("{op:?}"), + other => format!("{other:?}"), + } +} diff --git a/bin/mega-evme/src/block/mod.rs b/bin/mega-evme/src/block/mod.rs new file mode 100644 index 000000000..895c24b77 --- /dev/null +++ b/bin/mega-evme/src/block/mod.rs @@ -0,0 +1,22 @@ +//! Whole-block replay, on either engine, compared with the chain. +//! +//! One driver loads a block's inputs (the block, its receipts and the state its parent left, +//! from a block cache or over RPC), picks the engine the block runs on, hands the engine plain +//! data, and compares the receipts it gets back with the chain's. The two executors +//! ([`satin`] and, with the `legacy` feature, `legacy`) exchange nothing but plain data with the +//! driver, so the driver, the cache and the comparison are written once for both engines. + +mod cmd; +mod exec; +mod inputs; +#[cfg(feature = "legacy")] +mod legacy; +mod record; +mod satin; +mod state; + +pub use cmd::*; +pub use exec::*; +pub use inputs::*; +pub use record::*; +pub use state::*; diff --git a/bin/mega-evme/src/block/record.rs b/bin/mega-evme/src/block/record.rs new file mode 100644 index 000000000..7c1dde2bb --- /dev/null +++ b/bin/mega-evme/src/block/record.rs @@ -0,0 +1,239 @@ +//! What a replayed block is reported as, and how it compares with the chain. +//! +//! One record per transaction and one per block. The columns every engine has come first; a +//! Satin record adds the `satin` object and nothing else, so a legacy record's columns are a +//! subset of a Satin record's. + +use alloy_primitives::{Bytes, B256}; +use serde::Serialize; + +use super::{ + exec::{ExecutedBlock, TxResult}, + inputs::{BlockInputs, ChainReceipt}, +}; +use crate::{common::SatinReport, engine::Engine}; + +/// What the chain recorded for a transaction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct ChainView { + /// `success` or `failure`: a receipt records whether the transaction succeeded, not how it + /// failed. + pub status: &'static str, + /// Gas used. + pub gas_used: u64, + /// The block's gas used after the transaction. + pub cumulative_gas_used: u64, + /// Number of logs. + pub logs: usize, +} + +/// One replayed transaction. +#[derive(Debug, Clone, Serialize)] +pub struct TxRecord { + /// Always `tx`. + pub kind: &'static str, + /// The block number. + pub block: u64, + /// The transaction's index in the block. + pub index: usize, + /// The transaction's hash. + pub hash: B256, + /// The engine it ran on. + pub engine: &'static str, + /// The spec it ran under. + pub spec: String, + /// `success`, `revert`, `halt`, or `refused` (the engine did not include it). + pub status: &'static str, + /// Gas used; zero when refused. + pub gas_used: u64, + /// The block's gas used after the transaction. + pub cumulative_gas_used: u64, + /// Number of logs. + pub logs: usize, + /// Why it reverted, halted or was refused. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// What the chain recorded. + pub chain: ChainView, + /// The fields that differ from the chain's: `refused`, `status`, `gas_used`, + /// `cumulative_gas_used`, `logs`. + pub differs: Vec<&'static str>, + /// What Satin counted; only on a Satin record. + #[serde(skip_serializing_if = "Option::is_none")] + pub satin: Option, +} + +/// One replayed block. +#[derive(Debug, Clone, Serialize)] +pub struct BlockRecord { + /// Always `block`. + pub kind: &'static str, + /// The block number. + pub block: u64, + /// The block's hash. + pub hash: B256, + /// The engine it ran on. + pub engine: &'static str, + /// The spec it ran under. + pub spec: String, + /// Number of transactions. + pub transactions: usize, + /// Transactions the engine refused. + pub refused: usize, + /// Transactions whose record differs from the chain's. + pub differing: usize, + /// The block's gas used as replayed. + pub gas_used: u64, + /// The block's gas used as the chain recorded it. + pub chain_gas_used: u64, + /// The receipts root of the replayed receipts. + pub receipts_root: B256, + /// The receipts root in the block's header. + pub chain_receipts_root: B256, + /// Whether every transaction and the receipts root match the chain. + pub matches_chain: bool, + /// Reads the block's pre-state did not hold, served by the parent block over RPC. + pub rpc_reads: usize, + /// What Satin counted over the block's included transactions; only on a Satin record. + #[serde(skip_serializing_if = "Option::is_none")] + pub satin: Option, +} + +/// The receipts root of `encoded` receipts: the ordered trie of their EIP-2718 encodings. +pub fn receipts_root(encoded: &[Bytes]) -> B256 { + alloy_trie::root::ordered_trie_root_with_encoder(encoded, |receipt, buf| { + buf.extend_from_slice(receipt) + }) +} + +/// The records of `executed`, compared with the chain's receipts in `inputs`. +pub fn records( + inputs: &BlockInputs, + executed: &ExecutedBlock, + engine: Engine, + spec: &str, + rpc_reads: usize, +) -> (Vec, BlockRecord) { + let number = inputs.header.number; + let mut previous = 0; + let mut txs = Vec::with_capacity(executed.transactions.len()); + for (index, ((tx, result), chain)) in + inputs.transactions.iter().zip(&executed.transactions).zip(&inputs.receipts).enumerate() + { + let chain_view = chain_view(chain); + let mut record = TxRecord { + kind: "tx", + block: number, + index, + hash: tx.hash, + engine: engine.name(), + spec: spec.to_string(), + status: "refused", + gas_used: 0, + cumulative_gas_used: previous, + logs: 0, + reason: None, + chain: chain_view, + differs: Vec::new(), + satin: None, + }; + match result { + TxResult::Refused { reason } => { + record.reason = Some(reason.clone()); + record.differs.push("refused"); + } + TxResult::Included { status, reason, receipt, satin } => { + record.status = status.name(); + record.gas_used = receipt.cumulative_gas_used.saturating_sub(previous); + record.cumulative_gas_used = receipt.cumulative_gas_used; + record.logs = receipt.logs.len(); + record.reason.clone_from(reason); + record.satin = satin.clone(); + previous = receipt.cumulative_gas_used; + if receipt.success != chain.success() { + record.differs.push("status"); + } + if record.gas_used != chain_view.gas_used { + record.differs.push("gas_used"); + } + if record.cumulative_gas_used != chain_view.cumulative_gas_used { + record.differs.push("cumulative_gas_used"); + } + if !chain.logs_equal(&receipt.logs) { + record.differs.push("logs"); + } + } + } + txs.push(record); + } + + let encoded: Vec = executed.receipts().map(|r| r.encoded.clone()).collect(); + let root = receipts_root(&encoded); + let differing = txs.iter().filter(|tx| !tx.differs.is_empty()).count(); + let satin = (engine == Engine::Satin).then(|| SatinReport { + limits_override: executed.limits_override.map(Box::new), + ..sum_satin(txs.iter().filter_map(|t| t.satin.as_ref())) + }); + let block = BlockRecord { + kind: "block", + block: number, + hash: inputs.header.hash, + engine: engine.name(), + spec: spec.to_string(), + transactions: txs.len(), + refused: txs.iter().filter(|tx| tx.status == "refused").count(), + differing, + gas_used: previous, + chain_gas_used: inputs.receipts.last().map_or(0, |r| r.cumulative_gas_used.to()), + receipts_root: root, + chain_receipts_root: inputs.header.receipts_root, + matches_chain: differing == 0 && root == inputs.header.receipts_root, + rpc_reads, + satin, + }; + (txs, block) +} + +fn chain_view(chain: &ChainReceipt) -> ChainView { + ChainView { + status: if chain.success() { "success" } else { "failure" }, + gas_used: chain.gas_used.to(), + cumulative_gas_used: chain.cumulative_gas_used.to(), + logs: chain.logs.len(), + } +} + +/// The sum of `reports` over a block: every ledger and count added up; the reservoir left and +/// the floor are per transaction and summed as they are; no limit stop. +fn sum_satin<'a>(reports: impl Iterator) -> SatinReport { + reports.fold(SatinReport::default(), |acc, r| SatinReport { + regular_gas: acc.regular_gas + r.regular_gas, + state_gas: acc.state_gas + r.state_gas, + history_gas: acc.history_gas + r.history_gas, + history_bytes: acc.history_bytes + r.history_bytes, + reservoir_remaining: acc.reservoir_remaining + r.reservoir_remaining, + floor_gas: acc.floor_gas + r.floor_gas, + data_size: acc.data_size + r.data_size, + write_records: acc.write_records + r.write_records, + limit_exceeded: None, + limits_override: None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{b256, bytes}; + + /// No receipts give the empty trie's root; the root depends on the order of the receipts. + #[test] + fn test_receipts_root() { + assert_eq!( + receipts_root(&[]), + b256!("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") + ); + let a = bytes!("01"); + let b = bytes!("02"); + assert_ne!(receipts_root(&[a.clone(), b.clone()]), receipts_root(&[b, a])); + } +} diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs new file mode 100644 index 000000000..3e2eb3159 --- /dev/null +++ b/bin/mega-evme/src/block/satin.rs @@ -0,0 +1,238 @@ +//! A block on the Satin engine. + +use alloy_consensus::transaction::Recovered; +use alloy_eips::{Decodable2718, Encodable2718}; +use alloy_primitives::U256; +use mega_evm::{ + alloy_evm::{block::BlockExecutor, EvmEnv}, + alloy_op_evm::block::OpAlloyReceiptBuilder, + revm::{ + context::{result::ExecutionResult, BlockEnv, CfgEnv}, + database::State, + inspector::NoOpInspector, + primitives::eip4844, + }, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, + MegaHardforkConfig, MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits, +}; + +use super::{ + exec::{ExecStatus, ExecutedBlock, ReceiptData, TxResult}, + inputs::{HeaderFields, TxInput}, + state::{BlockState, SatinDb}, +}; +use crate::common::{ + decode_revert_reason, format_halt_reason, satin_limits, satin_schedule, EvmeError, + EvmeExternalEnvs, LimitsOverride, Result, SatinReport, +}; + +/// Executes the block `header` describes, with `transactions`, on Satin over `state`. +/// +/// The block runs as a validator runs it: under the schedule [`satin_schedule`] gives — the +/// chain's own when it runs Satin at the block, otherwise the engine's fallback, a counterfactual +/// — held to Satin's protocol limits, or `limits_override` over them, a counterfactual, with no +/// building policy, and with the block's gas limit from its header. Whether the block admits only +/// deposits is worked out from that schedule and `parent_timestamp`, the parent block's timestamp +/// ([`admits_only_deposits`]). A transaction the engine refuses is reported as refused and left +/// out, and the block goes on. +pub(super) fn execute( + chain_id: u64, + header: &HeaderFields, + parent_timestamp: Option, + transactions: &[TxInput], + bucket_capacities: &[(u32, u64)], + limits_override: Option<&LimitsOverride>, + state: &mut BlockState, +) -> Result { + let hardforks = satin_schedule(chain_id, header.timestamp)?; + let limits_override: Option = + limits_override.map(|limits| satin_limits(Some(limits))).transpose()?; + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = chain_id; + let mut block_env = BlockEnv { + number: U256::from(header.number), + beneficiary: header.beneficiary, + timestamp: U256::from(header.timestamp), + gas_limit: header.gas_limit, + basefee: header.base_fee, + difficulty: header.difficulty, + prevrandao: Some(header.mix_hash), + blob_excess_gas_and_price: None, + slot_num: 0, + }; + block_env.set_blob_excess_gas_and_price( + header.excess_blob_gas, + eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_CANCUN, + ); + let mut envs = EvmeExternalEnvs::new(); + for &(bucket, capacity) in bucket_capacities { + envs = envs.with_bucket_capacity(bucket, capacity); + } + let factory = MegaBlockExecutorFactory::new( + OpAlloyReceiptBuilder::default(), + &hardforks, + MegaEvmFactory::new().with_external_env_factory(envs), + ); + let only_deposits = + admits_only_deposits(&hardforks, header.number, parent_timestamp, header.timestamp)?; + // Without the parent's timestamp the block admits every transaction only where no fork the + // schedule activates after genesis is active at it, so Satin does not activate in it either. + let activates_satin = parent_timestamp + .is_some_and(|parent| hardforks.is_satin_activation_block(parent, header.timestamp)); + let block_ctx = MegaBlockExecutionCtx::new( + header.parent_hash, + header.parent_beacon_block_root, + header.extra_data.clone(), + BlockLimits::default(), + ) + .with_no_user_tx_activation_block(only_deposits) + .with_satin_activation_block(activates_satin); + + let result = { + let mut db = State::builder().with_database(SatinDb(state)).with_bundle_update().build(); + let mut executor = factory.create_executor_with_trusted_inspector( + &mut db, + EvmEnv::new(cfg, block_env), + block_ctx, + NoOpInspector, + ); + if let Some(limits) = limits_override { + executor = executor.with_protocol_limits(limits); + } + let mut run = || -> Result { + executor + .apply_pre_execution_changes() + .map_err(|e| EvmeError::Other(format!("pre-block changes: {e}")))?; + let mut results = Vec::with_capacity(transactions.len()); + for tx in transactions { + let envelope = MegaTxEnvelope::decode_2718(&mut tx.envelope.as_ref()) + .map_err(|e| EvmeError::Other(format!("decoding {}: {e}", tx.hash)))?; + let recovered = Recovered::new_unchecked(envelope, tx.sender); + let outcome = match executor.run_transaction(recovered.as_recovered_ref()) { + Ok(outcome) => outcome, + Err(e) => { + results.push(TxResult::Refused { reason: e.to_string() }); + continue; + } + }; + let satin = SatinReport::of(&outcome.inner); + let (status, reason) = match &outcome.inner.result { + ExecutionResult::Success { .. } => (ExecStatus::Success, None), + ExecutionResult::Revert { output, .. } => { + (ExecStatus::Revert, Some(decode_revert_reason(output))) + } + ExecutionResult::Halt { reason, .. } => { + (ExecStatus::Halt, Some(format_halt_reason(reason))) + } + }; + if let Err(e) = executor.commit_transaction_outcome(outcome) { + results.push(TxResult::Refused { reason: e.to_string() }); + continue; + } + let receipt = + executor.receipts().last().expect("a committed transaction has a receipt"); + results.push(TxResult::Included { + status, + reason, + receipt: ReceiptData { + encoded: receipt.encoded_2718().into(), + success: receipt.status(), + cumulative_gas_used: receipt.cumulative_gas_used(), + logs: receipt.logs().to_vec(), + }, + satin: Some(satin), + }); + } + Ok(ExecutedBlock { transactions: results, limits_override }) + }; + run() + }; + // A read the state could not serve fails the block, whatever the engine made of it. + if let Some(miss) = &state.miss { + return Err(EvmeError::Other(format!("block {}: {miss}", header.number))); + } + result +} + +/// Whether running the block of chain `chain_id` at `timestamp` on Satin, under the schedule +/// [`satin_schedule`] gives it, needs its parent's timestamp: a fork that schedule activates after +/// timestamp 0 is active at the block, so whether the fork activates in this block depends on when +/// its parent came ([`admits_only_deposits`]). +pub(super) fn needs_parent_timestamp(chain_id: u64, timestamp: u64) -> Result { + let hardforks = satin_schedule(chain_id, timestamp)?; + Ok(hardforks.admits_only_deposits(0, timestamp)) +} + +/// Whether block `number`, at `timestamp`, admits only deposits under `hardforks`, as a node works +/// it out: a fork the schedule activates is active at the block's timestamp and not at its +/// parent's ([`MegaHardforks::admits_only_deposits`]). +/// +/// Without the parent's timestamp the answer is known only where no parent could change it: no +/// fork the schedule activates after timestamp 0 is active at the block, so the block admits every +/// transaction whatever its parent's timestamp. Any other block is refused, since the tool cannot +/// tell whether a fork activates in it, and the refusal says how to recover: one replay with an +/// RPC endpoint writes the timestamp to the block cache. +fn admits_only_deposits( + hardforks: &MegaHardforkConfig, + number: u64, + parent_timestamp: Option, + timestamp: u64, +) -> Result { + match parent_timestamp { + Some(parent_timestamp) => Ok(hardforks.admits_only_deposits(parent_timestamp, timestamp)), + None if !hardforks.admits_only_deposits(0, timestamp) => Ok(false), + None => Err(EvmeError::Other(format!( + "block {number}: a fork its schedule activates is active at its timestamp, and \ + whether the fork activates in this block depends on its parent's timestamp, which \ + the block cache does not hold; replay it once with '--rpc', which fetches the \ + timestamp and writes it to the block cache, and it then replays offline" + ))), + } +} + +#[cfg(test)] +mod tests { + use mega_evm::{alloy_hardforks::ForkCondition, MegaHardfork, MegaHardforkConfig}; + + use super::admits_only_deposits; + + const ACTIVATION: u64 = 1_800_000_000; + + fn satin_at(timestamp: u64) -> MegaHardforkConfig { + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(timestamp)) + } + + /// [S1.8] [S21.12] [S1] With the parent's timestamp, the block admits only deposits exactly + /// where a fork activates in it: active at the block, not at the parent. + /// + /// Expected values: independent (the schedule's own timestamps and the rule). + #[test] + fn test_the_parent_timestamp_decides_the_activation_block() { + let schedule = satin_at(ACTIVATION); + assert!(admits_only_deposits(&schedule, 7, Some(ACTIVATION - 1), ACTIVATION).unwrap()); + assert!(admits_only_deposits(&schedule, 7, Some(ACTIVATION - 9), ACTIVATION + 1).unwrap()); + assert!(!admits_only_deposits(&schedule, 7, Some(ACTIVATION), ACTIVATION + 1).unwrap()); + assert!(!admits_only_deposits(&schedule, 7, Some(0), ACTIVATION - 1).unwrap()); + } + + /// [S1.8] [S1] Without it, a block no parent could make an activation block admits every + /// transaction: every fork active from genesis, or none active yet. Any other block is + /// refused, naming the block and how to recover. + /// + /// Expected values: independent (the schedule's own timestamps and the rule). + #[test] + fn test_without_the_parent_timestamp_only_an_undecidable_block_is_refused() { + let all_activated = MegaHardforkConfig::default().with_all_activated(); + assert!(!admits_only_deposits(&all_activated, 7, None, ACTIVATION).unwrap()); + assert!(!admits_only_deposits(&satin_at(0), 7, None, ACTIVATION).unwrap()); + assert!(!admits_only_deposits(&satin_at(ACTIVATION), 7, None, ACTIVATION - 1).unwrap()); + for timestamp in [ACTIVATION, ACTIVATION + 1] { + let error = admits_only_deposits(&satin_at(ACTIVATION), 7, None, timestamp) + .expect_err("a fork activated at or before the block, after genesis") + .to_string(); + assert!(error.contains("block 7: "), "{error}"); + assert!(error.contains("parent's timestamp"), "{error}"); + assert!(error.contains("replay it once with '--rpc'"), "the way back: {error}"); + } + } +} diff --git a/bin/mega-evme/src/block/state.rs b/bin/mega-evme/src/block/state.rs new file mode 100644 index 000000000..09db3782f --- /dev/null +++ b/bin/mega-evme/src/block/state.rs @@ -0,0 +1,567 @@ +//! The state a replayed block starts from, kept in plain data so that either engine can read it. +//! +//! A block's pre-state comes from a `prestateTracer` trace of the block. The trace reports, for +//! every transaction, the accounts and storage slots it touched as they stood just before it +//! ran; keeping the value from the first transaction that touched each account and slot gives +//! the state the parent block left, for everything the block's transactions read or wrote. +//! +//! What the trace does not cover (what only a pre-block system call reads, or a path a +//! counterfactual execution takes that the chain did not) is read from the parent block over RPC +//! when a provider is available, and folded into the pre-state, so a cached block written +//! afterwards replays offline along the same path. +//! +//! [`BlockState`] answers in `alloy-primitives` types only. Each engine reads it through a +//! `Database` of its own revm line: [`SatinDb`] here, and the legacy leg's in its module. + +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + fs, + io::Write as _, + path::{Path, PathBuf}, +}; + +use alloy_primitives::{keccak256, Address, Bytes, B256, U256, U64}; +use alloy_provider::Provider; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use tracing::debug; + +use crate::common::{EvmeError, OpProvider, Result}; + +/// The hash of empty code. +pub const EMPTY_CODE_HASH: B256 = alloy_primitives::KECCAK256_EMPTY; + +/// An account as the parent block left it, with the storage slots known so far. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreAccount { + /// Balance in wei. + pub balance: U256, + /// Nonce. + #[serde(default, skip_serializing_if = "is_zero")] + pub nonce: u64, + /// Hash of the account's code, absent for an account without code. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code_hash: Option, + /// Storage slots known so far, by key. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub storage: BTreeMap, +} + +const fn is_zero(n: &u64) -> bool { + *n == 0 +} + +impl PreAccount { + /// Whether the account does not exist. + /// + /// Neither a trace nor an RPC endpoint can say "no such account": they report zeros for it. + /// A node's database answers `None`, and the difference is observable (EIP-7702 refunds an + /// authorization whose authority already exists), so an all-zero account is absent. An + /// existing empty account cannot occur on a chain that has had EIP-161 from genesis. + pub fn is_absent(&self) -> bool { + self.balance.is_zero() && self.nonce == 0 && self.code_hash.is_none() + } +} + +/// The part of the parent block's state a block's execution reads. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct BlockPrestate { + /// Accounts by address. + pub accounts: BTreeMap, + /// Hashes of earlier blocks, by number, for `BLOCKHASH`. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub block_hashes: BTreeMap, +} + +/// One transaction's entry in a `prestateTracer` block trace. +#[derive(Debug, Deserialize)] +struct TracedTx { + #[serde(rename = "txHash", default)] + tx_hash: Option, + #[serde(default)] + result: Option>, + #[serde(default)] + error: Option, +} + +/// An account in a `prestateTracer` result. +#[derive(Debug, Deserialize)] +struct TracedAccount { + #[serde(default)] + balance: Option, + #[serde(default)] + nonce: Option, + #[serde(default)] + code: Option, + #[serde(default)] + storage: BTreeMap, +} + +impl BlockPrestate { + /// Builds the pre-state from a `prestateTracer` trace of a whole block, adding every code it + /// carries to `codes`. + /// + /// Transactions are taken in block order and the first value seen for each account and slot + /// wins: a later transaction sees what the earlier ones left, not what the parent block did. + pub fn from_block_trace(trace: serde_json::Value, codes: &mut CodeStore) -> Result { + let traced: Vec = serde_json::from_value(trace) + .map_err(|e| EvmeError::RpcError(format!("Malformed prestate trace: {e}")))?; + let mut prestate = Self::default(); + for (index, tx) in traced.into_iter().enumerate() { + let Some(accounts) = tx.result else { + return Err(EvmeError::RpcError(format!( + "Prestate trace of transaction {index} ({}) failed: {}", + tx.tx_hash.map(|h| h.to_string()).unwrap_or_default(), + tx.error.unwrap_or_else(|| "no result".to_string()), + ))); + }; + for (address, traced) in accounts { + let account = prestate.accounts.entry(address).or_insert_with(|| PreAccount { + balance: traced.balance.unwrap_or_default(), + nonce: traced.nonce.unwrap_or_default(), + code_hash: traced + .code + .filter(|code| !code.is_empty()) + .map(|code| codes.insert(code)), + storage: BTreeMap::new(), + }); + for (slot, value) in traced.storage { + account.storage.entry(slot).or_insert_with(|| value.into()); + } + } + } + Ok(prestate) + } +} + +/// Contract code by hash, kept in memory and, when a directory is given, on disk as one file per +/// code so that blocks sharing a contract share its bytes. +#[derive(Debug, Default)] +pub struct CodeStore { + dir: Option, + codes: HashMap, + unsaved: Vec, +} + +impl CodeStore { + /// A store persisted under `dir`, or kept in memory only. + pub fn new(dir: Option) -> Self { + Self { dir, ..Default::default() } + } + + fn path(&self, hash: &B256) -> Option { + let hex = hash.to_string(); + self.dir.as_ref().map(|dir| dir.join(&hex[2..4]).join(format!("{}.bin", &hex[2..]))) + } + + /// Adds `code`, returning its hash. + pub fn insert(&mut self, code: Bytes) -> B256 { + let hash = keccak256(&code); + if let std::collections::hash_map::Entry::Vacant(entry) = self.codes.entry(hash) { + entry.insert(code); + self.unsaved.push(hash); + } + hash + } + + /// The code with `hash`, loading it from disk if it is not in memory. + pub fn get(&mut self, hash: &B256) -> Result> { + if *hash == EMPTY_CODE_HASH { + return Ok(Some(Bytes::new())); + } + if let Some(code) = self.codes.get(hash) { + return Ok(Some(code.clone())); + } + let Some(path) = self.path(hash) else { return Ok(None) }; + match fs::read(&path) { + Ok(bytes) => { + let code = Bytes::from(bytes); + if keccak256(&code) != *hash { + return Err(EvmeError::FixtureError(format!( + "code store entry {} does not hash to its name", + path.display() + ))); + } + self.codes.insert(*hash, code.clone()); + Ok(Some(code)) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + } + + /// Writes the codes added since the last call to disk. Files are written whole and renamed + /// into place, so processes sharing a store never see a partial one. + pub fn persist(&mut self) -> Result<()> { + if self.dir.is_none() { + self.unsaved.clear(); + return Ok(()); + } + for hash in std::mem::take(&mut self.unsaved) { + let path = self.path(&hash).expect("a store with a directory has paths"); + if path.exists() { + continue; + } + let code = self.codes.get(&hash).expect("an unsaved code is in memory"); + write_atomically(&path, code)?; + } + Ok(()) + } +} + +/// Writes `bytes` to `path` through a temporary file in the same directory. +pub(super) fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> { + let dir = path.parent().expect("a file path has a parent"); + fs::create_dir_all(dir)?; + let mut tmp = tempfile::NamedTempFile::new_in(dir)?; + tmp.write_all(bytes)?; + tmp.persist(path).map_err(|e| EvmeError::FileRead(e.error))?; + // A temporary file is private to its owner; a cache entry is readable like any other file. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o644))?; + } + Ok(()) +} + +/// Reads the state after block `parent` over RPC, one request at a time. +#[derive(Debug)] +pub struct ParentStateRpc { + provider: OpProvider, + parent: u64, + runtime: tokio::runtime::Handle, +} + +impl ParentStateRpc { + /// Reads the state after block `parent`. `None` outside a tokio runtime. + pub fn new(provider: OpProvider, parent: u64) -> Option { + let runtime = tokio::runtime::Handle::try_current().ok()?; + Some(Self { provider, parent, runtime }) + } + + fn block_on(&self, future: F) -> F::Output { + tokio::task::block_in_place(|| self.runtime.block_on(future)) + } + + fn call( + &self, + method: &'static str, + params: serde_json::Value, + ) -> Result { + self.block_on(self.provider.raw_request::<_, R>(method.into(), params)) + .map_err(|e| EvmeError::RpcError(format!("{method}: {e}"))) + } + + fn account(&self, address: Address) -> Result<(PreAccount, Bytes)> { + let block = format!("0x{:x}", self.parent); + let balance: U256 = self.call("eth_getBalance", json!([address, block]))?; + let nonce: U64 = self.call("eth_getTransactionCount", json!([address, block]))?; + let code: Bytes = self.call("eth_getCode", json!([address, block]))?; + let code_hash = (!code.is_empty()).then(|| keccak256(&code)); + Ok((PreAccount { balance, nonce: nonce.to(), code_hash, storage: BTreeMap::new() }, code)) + } + + fn storage(&self, address: Address, slot: B256) -> Result { + self.call("eth_getStorageAt", json!([address, slot, format!("0x{:x}", self.parent)])) + } + + fn block_hash(&self, number: u64) -> Result> { + let block: Option = + self.call("eth_getBlockByNumber", json!([format!("0x{number:x}"), false]))?; + block + .map(|block| { + serde_json::from_value::(block["hash"].clone()) + .map_err(|e| EvmeError::RpcError(format!("Malformed block {number}: {e}"))) + }) + .transpose() + } +} + +/// An account as an engine reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountData { + /// Balance in wei. + pub balance: U256, + /// Nonce. + pub nonce: u64, + /// Hash of the code. + pub code_hash: B256, + /// The code. + pub code: Bytes, +} + +/// The first read a block's state could not serve, which fails the block. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct StateReadError(pub String); + +impl revm::database::DBErrorMarker for StateReadError {} + +/// The state a block executes against: its pre-state, falling back to the parent block over RPC +/// for what the pre-state does not hold. +#[derive(Debug)] +pub struct BlockState { + /// The pre-state; grows with every read the fallback serves. + pub prestate: BlockPrestate, + /// Contract code. + pub codes: CodeStore, + fallback: Option, + /// Number of reads the fallback served. + pub fallback_reads: usize, + /// The first read neither the pre-state nor a fallback could serve. + pub miss: Option, +} + +impl BlockState { + /// A state over `prestate` and `codes`, reading what they lack through `fallback`. + pub fn new( + prestate: BlockPrestate, + codes: CodeStore, + fallback: Option, + ) -> Self { + Self { prestate, codes, fallback, fallback_reads: 0, miss: None } + } + + fn fail(&mut self, message: String) -> StateReadError { + self.miss.get_or_insert_with(|| message.clone()); + StateReadError(message) + } + + fn missing(&mut self, what: String) -> StateReadError { + self.fail(format!("state not in the block's pre-state and no RPC to read it: {what}")) + } + + /// The account at `address`, or `None` when it does not exist. + pub fn account( + &mut self, + address: Address, + ) -> std::result::Result, StateReadError> { + if !self.prestate.accounts.contains_key(&address) { + let Some(fallback) = &self.fallback else { + return Err(self.missing(format!("account {address}"))); + }; + let (account, code) = match fallback.account(address) { + Ok(read) => read, + Err(e) => return Err(self.fail(format!("reading account {address}: {e}"))), + }; + self.fallback_reads += 1; + debug!(%address, "Read an account the pre-state lacks from the parent block"); + if !code.is_empty() { + self.codes.insert(code); + } + self.prestate.accounts.insert(address, account); + } + let account = self.prestate.accounts[&address].clone(); + if account.is_absent() { + return Ok(None); + } + let code_hash = account.code_hash.unwrap_or(EMPTY_CODE_HASH); + let code = self.code(code_hash)?; + Ok(Some(AccountData { balance: account.balance, nonce: account.nonce, code_hash, code })) + } + + /// The code with `code_hash`. + pub fn code(&mut self, code_hash: B256) -> std::result::Result { + match self.codes.get(&code_hash) { + Ok(Some(code)) => Ok(code), + Ok(None) => Err(self.missing(format!("code {code_hash}"))), + Err(e) => Err(self.fail(format!("reading code {code_hash}: {e}"))), + } + } + + /// The value of `slot` in `address`'s storage. + pub fn storage( + &mut self, + address: Address, + slot: U256, + ) -> std::result::Result { + let key = B256::from(slot); + if let Some(value) = + self.prestate.accounts.get(&address).and_then(|account| account.storage.get(&key)) + { + return Ok(*value); + } + if self.fallback.is_none() { + // A slot of an account the trace saw is a slot the block did not touch before it + // was read here; only an account the pre-state holds whole could answer zero, and + // none does. + return Err(self.missing(format!("storage {address}[{key}]"))); + } + // The slot is recorded under its account, so the account must be in the pre-state + // first; otherwise an empty entry would later pass for the account. + if !self.prestate.accounts.contains_key(&address) { + self.account(address)?; + } + let fallback = self.fallback.as_ref().expect("checked above"); + let value = match fallback.storage(address, key) { + Ok(value) => value, + Err(e) => return Err(self.fail(format!("reading storage {address}[{key}]: {e}"))), + }; + self.fallback_reads += 1; + debug!(%address, %key, "Read a storage slot the pre-state lacks from the parent block"); + self.prestate.accounts.get_mut(&address).expect("loaded above").storage.insert(key, value); + Ok(value) + } + + /// The hash of block `number`. + pub fn block_hash(&mut self, number: u64) -> std::result::Result { + if let Some(hash) = self.prestate.block_hashes.get(&number) { + return Ok(*hash); + } + let Some(fallback) = &self.fallback else { + return Err(self.missing(format!("hash of block {number}"))); + }; + let hash = match fallback.block_hash(number) { + Ok(Some(hash)) => hash, + Ok(None) => return Err(self.fail(format!("block {number} does not exist"))), + Err(e) => return Err(self.fail(format!("reading the hash of block {number}: {e}"))), + }; + self.fallback_reads += 1; + self.prestate.block_hashes.insert(number, hash); + Ok(hash) + } + + /// The keys of the pre-state, to tell what a replay read beyond them. + pub fn keys(&self) -> BTreeSet<(Address, Option)> { + self.prestate + .accounts + .iter() + .flat_map(|(address, account)| { + std::iter::once((*address, None)) + .chain(account.storage.keys().map(|slot| (*address, Some(*slot)))) + }) + .collect() + } +} + +/// The Satin engine's view of a [`BlockState`]. +#[derive(Debug)] +pub struct SatinDb<'a>(pub &'a mut BlockState); + +impl revm::Database for SatinDb<'_> { + type Error = StateReadError; + + fn basic( + &mut self, + address: Address, + ) -> std::result::Result, Self::Error> { + Ok(self.0.account(address)?.map(|account| { + revm::state::AccountInfo::new( + account.balance, + account.nonce, + account.code_hash, + revm::state::Bytecode::new_raw(account.code), + ) + })) + } + + fn code_by_hash( + &mut self, + code_hash: B256, + ) -> std::result::Result { + Ok(revm::state::Bytecode::new_raw(self.0.code(code_hash)?)) + } + + fn storage(&mut self, address: Address, index: U256) -> std::result::Result { + self.0.storage(address, index) + } + + fn block_hash(&mut self, number: u64) -> std::result::Result { + self.0.block_hash(number) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::{address, bytes}; + + const ALICE: Address = address!("0x00000000000000000000000000000000000a11ce"); + const TOKEN: Address = address!("0x0000000000000000000000000000000000007070"); + + fn slot(n: u8) -> B256 { + B256::with_last_byte(n) + } + + fn word(n: u64) -> String { + B256::from(U256::from(n)).to_string() + } + + /// Two transactions touch the same account and slot; the second one saw what the first + /// left. The pre-state keeps the first sighting of each, and the second transaction's + /// sighting of a slot the first did not touch. + #[test] + fn test_the_first_sighting_of_each_account_and_slot_is_the_parent_state() { + let trace = json!([ + { + "txHash": B256::with_last_byte(1), + "result": { + ALICE.to_string(): { "balance": "0x64", "nonce": 7 }, + TOKEN.to_string(): { + "balance": "0x0", + "code": "0x6001600055", + "storage": { slot(1).to_string(): word(10) } + } + } + }, + { + "txHash": B256::with_last_byte(2), + "result": { + ALICE.to_string(): { "balance": "0x32", "nonce": 8 }, + TOKEN.to_string(): { + "balance": "0x0", + "code": "0x6001600055", + "storage": { slot(1).to_string(): word(11), slot(2).to_string(): word(20) } + } + } + } + ]); + let mut codes = CodeStore::new(None); + let prestate = BlockPrestate::from_block_trace(trace, &mut codes).unwrap(); + + let alice = &prestate.accounts[&ALICE]; + assert_eq!((alice.balance, alice.nonce, alice.code_hash), (U256::from(100), 7, None)); + let token = &prestate.accounts[&TOKEN]; + assert_eq!(token.storage[&slot(1)], U256::from(10), "the first transaction's view"); + assert_eq!(token.storage[&slot(2)], U256::from(20), "first seen by the second transaction"); + let code = bytes!("6001600055"); + assert_eq!(token.code_hash, Some(keccak256(&code))); + assert_eq!(codes.get(&keccak256(&code)).unwrap().unwrap(), code, "kept once, by hash"); + } + + #[test] + fn test_a_failed_transaction_trace_fails_the_block() { + let trace = json!([{ "txHash": B256::ZERO, "error": "execution timeout" }]); + let err = BlockPrestate::from_block_trace(trace, &mut CodeStore::new(None)).unwrap_err(); + assert!(err.to_string().contains("execution timeout"), "{err}"); + } + + /// An all-zero account is absent; offline, anything the pre-state lacks fails the read and + /// is remembered as the block's miss. + #[test] + fn test_reads_of_the_block_state() { + let mut prestate = BlockPrestate::default(); + prestate.accounts.insert(ALICE, PreAccount::default()); + prestate.accounts.insert( + TOKEN, + PreAccount { + balance: U256::from(5), + storage: BTreeMap::from([(slot(1), U256::from(9))]), + ..Default::default() + }, + ); + let mut state = BlockState::new(prestate, CodeStore::new(None), None); + + assert_eq!(state.account(ALICE).unwrap(), None, "all zeros is no account"); + let token = state.account(TOKEN).unwrap().unwrap(); + assert_eq!((token.balance, token.code_hash), (U256::from(5), EMPTY_CODE_HASH)); + assert_eq!(state.storage(TOKEN, U256::from(1)).unwrap(), U256::from(9)); + assert!(state.miss.is_none()); + + let err = state.storage(TOKEN, U256::from(2)).unwrap_err(); + assert!(err.0.contains("no RPC to read it"), "{err}"); + assert!(state.account(Address::ZERO).is_err()); + assert_eq!(state.miss.as_deref(), Some(err.0.as_str()), "the first miss is kept"); + } +} diff --git a/bin/mega-evme/src/cmd.rs b/bin/mega-evme/src/cmd.rs index d70d496e5..065cfa99b 100644 --- a/bin/mega-evme/src/cmd.rs +++ b/bin/mega-evme/src/cmd.rs @@ -1,7 +1,17 @@ -use clap::{Parser, Subcommand}; +use std::ffi::OsString; + +use clap::{parser::ValueSource, ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand}; use tracing::error; -use crate::common::LogArgs; +use mega_evm::MegaSpecId; + +use crate::{ + common::{ + check_genesis_chain, parse_genesis, sanitize_terminal_text, use_genesis, EvmeError, + GenesisChain, LimitsOverride, LogArgs, + }, + engine::Engine, +}; /// Main CLI for the mega-evme tool #[derive(Parser, Debug)] @@ -11,6 +21,14 @@ pub struct MainCmd { #[command(flatten)] pub log: LogArgs, + /// Satin only: the genesis file of the chain the command runs on. Its `config` object's + /// `chainId` and Satin key (`satinTime`) replace the engine's table for that chain: which + /// blocks run Satin, and the schedule they run under. + /// `run` and `tx` default to `--spec Satin` under it. A run on another chain, on a legacy + /// spec, before the file's `satinTime`, or on a file without Satin keys is refused + #[arg(long = "genesis", global = true, value_name = "FILE", value_parser = parse_genesis)] + pub genesis: Option, + /// Subcommand to execute #[command(subcommand)] pub command: Commands, @@ -24,7 +42,7 @@ pub enum Commands { Run(crate::run::Cmd), /// Run arbitrary transaction Tx(crate::tx::Cmd), - /// Replay a transaction from RPC + /// Replay a transaction, or whole blocks, from RPC or a block cache Replay(crate::replay::Cmd), } @@ -36,33 +54,175 @@ pub enum Error { Custom(&'static str), /// Evme error (used by run, tx, and replay commands) #[error("{0}")] - Evme(#[from] crate::common::EvmeError), + Evme(#[from] EvmeError), +} + +/// Parses `args` (the program name first), picks the engine the command's spec names and runs the +/// command on it. +/// +/// A command on a legacy spec is handed, with `args` as they are, to the released 1.7.1 CLI, +/// which parses them again and runs on the legacy engine; everything else runs here, on Satin. +/// The one argument added is the default spec of a `run` or `tx` that left `--spec` out. +pub async fn run_cli(args: Vec) -> Result<(), Error> { + let matches = MainCmd::command().get_matches_from(&args); + let spec_is_default = spec_is_default(&matches); + let mut cmd = MainCmd::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); + if let Some(genesis) = &cmd.genesis { + use_genesis(genesis.clone())?; + // The file configures Satin alone, so a `run` or `tx` that left `--spec` out runs it. + if spec_is_default { + cmd.command.set_spec(MegaSpecId::SATIN.to_string()); + } + } + // The chain is checked before the engine is picked: a run on another chain than the file's is + // refused for its chain, whatever its spec. + if let Some(chain_id) = cmd.command.chain_id() { + check_genesis_chain(chain_id)?; + } + + // Whole-block replay runs here for both engines, choosing one per block. + let engine = match &cmd.command { + Commands::Replay(replay) if replay.replays_blocks() => Ok(Engine::Satin), + command => command.engine().await, + }?; + match engine { + // The released CLI knows no such flag: its engine holds a transaction to its spec's own + // limits. Refused here rather than left to its parser. + Engine::Legacy if cmd.command.limits_override().is_some() => Err(EvmeError::InvalidInput( + "--override.limits applies to Satin only: the legacy engine holds a \ + transaction to its spec's own limits" + .to_string(), + ) + .into()), + Engine::Legacy if cmd.genesis.is_some() => Err(EvmeError::InvalidInput( + "--genesis applies to Satin only: the legacy engine runs a chain on its own \ + table" + .to_string(), + ) + .into()), + Engine::Legacy => { + crate::engine::run_legacy(args, spec_is_default).await.map_err(Into::into) + } + Engine::Satin => cmd.run().await, + } +} + +/// Writes `message` as one line, without terminal controls. +/// +/// A write that fails, a closed pipe included, is dropped: the exit status reports the failure. +pub(crate) fn write_cli_error(mut out: impl std::io::Write, message: &str) { + let message = sanitize_terminal_text(message); + let _ = writeln!(out, "{message}"); +} + +/// Prints `err` to stderr and exits 1, whether or not stderr could take the line. +pub fn report_cli_error(err: &Error) -> ! { + write_cli_error(std::io::stderr().lock(), &err.to_string()); + std::process::exit(1); +} + +/// Whether `run`'s or `tx`'s `--spec` was left at its default. Always `false` for `replay`, which +/// has no `--spec`. +fn spec_is_default(matches: &ArgMatches) -> bool { + match matches.subcommand() { + Some(("run" | "tx", sub)) => sub.value_source("spec") != Some(ValueSource::CommandLine), + _ => false, + } +} + +impl Commands { + /// The engine this command runs on. + pub async fn engine(&self) -> Result { + match self { + Self::Run(cmd) => Engine::of_spec(&cmd.env_args.chain.spec), + Self::Tx(cmd) => Engine::of_spec(&cmd.env_args.chain.spec), + Self::Replay(cmd) => cmd.engine().await, + } + } + + /// The chain `run` or `tx` runs on (`--chain-id`); `None` for `replay`, which learns its + /// chain from the source it replays. + pub const fn chain_id(&self) -> Option { + match self { + Self::Run(cmd) => Some(cmd.env_args.chain.chain_id), + Self::Tx(cmd) => Some(cmd.env_args.chain.chain_id), + Self::Replay(_) => None, + } + } + + /// Sets the spec of `run` or `tx` (`--spec`) to `spec`; `replay` has none. + fn set_spec(&mut self, spec: String) { + match self { + Self::Run(cmd) => cmd.env_args.chain.spec = spec, + Self::Tx(cmd) => cmd.env_args.chain.spec = spec, + Self::Replay(_) => {} + } + } + + /// The protocol limits the command overrides the chain's with (`--override.limits`), if any. + pub const fn limits_override(&self) -> Option<&LimitsOverride> { + match self { + Self::Run(cmd) => cmd.env_args.chain.limits_override.as_ref(), + Self::Tx(cmd) => cmd.env_args.chain.limits_override.as_ref(), + Self::Replay(cmd) => cmd.limits_override.as_ref(), + } + } } impl MainCmd { - /// Execute the main command + /// Execute the command on the Satin engine. pub async fn run(self) -> Result<(), Error> { // Initialize logging first self.log.init(); - match self.command { - Commands::Run(cmd) => { - cmd.run().await?; - Ok(()) - } - Commands::Tx(cmd) => { - cmd.run().await?; - Ok(()) - } - Commands::Replay(cmd) => { - cmd.run().await?; - Ok(()) - } - } - .inspect_err(|e| { + // The command's error is bound first and then reported: a `?` inside an arm would return + // from this function before the report. + let result = match self.command { + Commands::Run(cmd) => cmd.run().await, + Commands::Tx(cmd) => cmd.run().await, + Commands::Replay(cmd) => cmd.run().await, + }; + result.map_err(Error::from).inspect_err(|e| { error!(err = ?e, "Error executing command"); - eprintln!("{e}"); - std::process::exit(1); }) } } + +#[cfg(test)] +mod tests { + use std::io::{self, Write}; + + use super::write_cli_error; + + /// A writer that refuses every write with a broken pipe. + struct Closed; + + impl Write for Closed { + fn write(&mut self, _buf: &[u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "closed")) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + #[test] + fn test_a_command_error_is_one_line_on_the_writer() { + let mut out = Vec::new(); + write_cli_error(&mut out, "Failed to read file"); + assert_eq!(out, b"Failed to read file\n"); + } + + #[test] + fn test_a_reported_error_strips_terminal_controls() { + let mut out = Vec::new(); + write_cli_error(&mut out, "Invalid input: \u{1b}[2Jpath\r"); + assert_eq!(out, b"Invalid input: path\n"); + } + + #[test] + fn test_a_closed_writer_drops_the_error_line() { + write_cli_error(Closed, "Failed to read file"); + } +} diff --git a/bin/mega-evme/src/common/env.rs b/bin/mega-evme/src/common/env.rs index 1f6b7379a..8d0999d48 100644 --- a/bin/mega-evme/src/common/env.rs +++ b/bin/mega-evme/src/common/env.rs @@ -12,45 +12,65 @@ use mega_evm::{ context::{block::BlockEnv, cfg::CfgEnv}, primitives::eip4844, }, - AHashBucketHasher, MegaContext, MegaSpecId, TestExternalEnvs, + AHashBucketHasher, MegaContext, MegaSpecId, ProtocolLimits, TestExternalEnvs, }; /// External environment type for mega-evme using the real AHash-based SALT bucket hasher. pub type EvmeExternalEnvs = TestExternalEnvs; use tracing::{debug, trace}; -use super::{EvmeError, Result}; +use super::{ + parse_limits_override, satin_limits, satin_schedule, EvmeError, LimitsOverride, Result, +}; /// Chain configuration arguments (spec and chain ID) #[derive(Args, Debug, Clone)] #[command(next_help_heading = "Chain Options")] pub struct ChainArgs { - /// Name of spec to use, possible values: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, - /// `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` (`MiniRex1`/`MiniRex2` - /// are alias specs executing `Equivalence`/`MiniRex` behavior) - #[arg(long = "spec", default_value = "Rex7")] + /// Name of spec to use. `Satin` runs on the Satin engine; `Equivalence`, `MiniRex`, + /// `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` run on the + /// legacy engine, the released 1.7.1 (`MiniRex1`/`MiniRex2` are alias specs executing + /// `Equivalence`/`MiniRex` behavior). Under `--genesis` the default is `Satin` + #[arg(long = "spec", default_value = "Rex6")] pub spec: String, /// `ChainID` to use #[arg(long = "chain-id", visible_aliases = ["chainid"], default_value = "6342")] pub chain_id: u64, + + /// Satin only: run under these protocol limits instead of the spec's, a counterfactual. A JSON + /// object in `ProtocolLimits`' shape (camelCase, per-transaction limits under + /// `txRuntimeLimits`), inline or in a file; the fields it names replace the spec's, every + /// other stays. Refused when it names an unknown field or a value of the wrong type + #[arg(long = "override.limits", value_name = "JSON|FILE", value_parser = parse_limits_override)] + pub limits_override: Option, } impl ChainArgs { - /// Gets the spec ID from the spec name + /// Gets the spec ID from the spec name. Only `Satin` parses: a legacy spec runs on the + /// legacy engine, which this crate hands the command to before it gets here. pub fn spec_id(&self) -> Result { MegaSpecId::from_str(&self.spec) - .map_err(|e| EvmeError::InvalidInput(format!("Invalid spec name: {:?}", e))) + .map_err(|e| EvmeError::InvalidInput(format!("Invalid spec name: {e}"))) } - /// Creates [`CfgEnv`]. + /// Creates [`CfgEnv`]. The fields Satin fixes (its gas schedule, the EIP-8037 and EIP-2780 + /// switches, the execution cap, the code-size limits) are set when the context takes it. pub fn create_cfg_env(&self) -> Result> { - let mut cfg = CfgEnv::default(); + let mut cfg = CfgEnv::new_with_spec(self.spec_id()?); cfg.chain_id = self.chain_id; - cfg.spec = self.spec_id()?; debug!(cfg = ?cfg, "Evm CfgEnv created"); Ok(cfg) } + + /// The protocol limits a Satin run of this chain at `timestamp` is held to: Satin's + /// ([`satin_limits`]), with `--override.limits` over them. The run's schedule + /// ([`satin_schedule`]) is checked first, so a run the chain's configuration cannot make — + /// one before `--genesis` activates Satin, say — is refused here too. + pub fn protocol_limits(&self, timestamp: u64) -> Result { + satin_schedule(self.chain_id, timestamp)?; + satin_limits(self.limits_override.as_ref()) + } } /// Block environment configuration arguments @@ -106,6 +126,7 @@ impl BlockEnvArgs { difficulty: self.block_difficulty, prevrandao: Some(self.block_prevrandao), blob_excess_gas_and_price: None, + slot_num: 0, }; // Set blob excess gas if provided @@ -185,12 +206,23 @@ impl EnvArgs { self.ext.create_external_envs() } + /// The protocol limits a Satin run is held to when `--override.limits` replaced the spec's, + /// for its report; `None` without an override. + pub fn limits_override_in_force(&self) -> Result>> { + if self.chain.limits_override.is_none() { + return Ok(None); + } + self.chain.protocol_limits(self.block.block_timestamp).map(|limits| Some(Box::new(limits))) + } + /// Creates a [`MegaContext`] with all environment configurations. /// - /// The `system_address` defaults to `MEGA_SYSTEM_ADDRESS`. For `run`/`tx` modes this is - /// correct: these paths don't go through the block executor and don't resolve from - /// `SequencerRegistry`. If fork-state simulation with a changed sequencer is needed, - /// a `--system-address` CLI override can be added in the future. + /// The transaction is held to the per-transaction limits a block would hold it to + /// ([`ChainArgs::protocol_limits`]), as a node's EVM factory holds an EVM it builds outside + /// block execution. + /// + /// This function does not set a system address. A transaction of the system shape reads the + /// live address from the `SequencerRegistry` in the database it runs on. pub fn create_evm_context( &self, db: DB, @@ -198,11 +230,13 @@ impl EnvArgs { let cfg = self.create_cfg_env()?; let block = self.create_block_env()?; let external_envs = self.create_external_envs()?; + let limits = self.chain.protocol_limits(self.block.block_timestamp)?; + debug!(limits = ?limits.tx_runtime_limits, "Per-transaction limits resolved"); - Ok(MegaContext::new(db, cfg.spec) + Ok(MegaContext::new_with_external_envs(db, cfg.spec, external_envs.into()) .with_cfg(cfg) .with_block(block) - .with_external_envs(external_envs.into())) + .with_tx_runtime_limits(limits.tx_runtime_limits)) } } @@ -228,3 +262,35 @@ pub fn parse_bucket_capacity(s: &str) -> Result<(u32, u64)> { trace!(string = %s, bucket_id = %bucket_id, capacity = %capacity, "Parsed bucket capacity"); Ok((bucket_id, capacity)) } + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{revm::database::EmptyDB, MegaEvm}; + + /// A `run` or `tx` on Satin is held to Satin's per-transaction limits, as a bare context of + /// the spec is; `--override.limits` replaces the fields it names. + #[test] + fn test_a_satin_run_is_held_to_the_protocol_limits() { + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + let args = EnvArgs::parse_from(["run", "--spec", "Satin"]); + let evm = MegaEvm::new(args.create_evm_context(EmptyDB::default()).unwrap()); + assert_eq!(*evm.tx_runtime_limits(), satin); + assert_eq!( + *MegaEvm::new(MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN)) + .tx_runtime_limits(), + satin, + "a bare context holds the same limits" + ); + + let args = EnvArgs::parse_from([ + "run", + "--spec", + "Satin", + "--override.limits", + r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#, + ]); + let evm = MegaEvm::new(args.create_evm_context(EmptyDB::default()).unwrap()); + assert_eq!(*evm.tx_runtime_limits(), satin.with_tx_data_size_limit(350)); + } +} diff --git a/bin/mega-evme/src/common/error.rs b/bin/mega-evme/src/common/error.rs index c3956c064..4207f679c 100644 --- a/bin/mega-evme/src/common/error.rs +++ b/bin/mega-evme/src/common/error.rs @@ -1,14 +1,9 @@ use alloy_primitives::{hex::FromHexError, BlockNumber, TxHash, B256}; -use alloy_provider::transport::TransportError; -use mega_evm::{alloy_evm::block::BlockExecutionError, revm::bytecode::BytecodeDecodeError}; +use mega_evm::revm::{bytecode::BytecodeDecodeError, database_interface::bal::EvmDatabaseError}; /// Error types for the replay command #[derive(Debug, thiserror::Error)] pub enum EvmeError { - /// RPC transport error - #[error("RPC transport error: {0}")] - RpcTransportError(TransportError), - /// Transaction not found #[error("Transaction not found: {0}")] TransactionNotFound(TxHash), @@ -17,10 +12,6 @@ pub enum EvmeError { #[error("Block not found: {0}")] BlockNotFound(BlockNumber), - /// Block execution error - #[error("Block execution error: {0}")] - BlockExecutionError(#[from] BlockExecutionError), - /// Invalid bytecode #[error("Invalid bytecode: {0}")] InvalidBytecode(#[from] BytecodeDecodeError), @@ -65,10 +56,119 @@ pub enum EvmeError { /// Other error #[error("Other error: {0}")] Other(String), + + /// A failure the released CLI returned, already rendered the way that CLI prints it on stderr. + #[error("{0}")] + ReleasedCli(String), } // Implement DBErrorMarker to allow EvmeError to be used as Database error type impl mega_evm::revm::database::DBErrorMarker for EvmeError {} +impl From> for EvmeError { + fn from(err: EvmDatabaseError) -> Self { + match err { + EvmDatabaseError::Database(e) => e, + EvmDatabaseError::Bal(e) => Self::Other(format!("BAL error: {e}")), + } + } +} + /// Result type for the mega-evme command pub type Result = std::result::Result; + +/// Drops what would move the cursor or restyle the terminal from `text`, and keeps the rest. +/// +/// A revert reason or an error is printed as text, and its bytes are not the tool's. Removed: ANSI +/// escape sequences, the C0 controls but `\n` and `\t`, DEL, the C1 controls (U+0080 to U+009F, +/// which include the one-character CSI, OSC and DCS introducers) and the bidirectional overrides +/// and isolates (U+202A to U+202E, U+2066 to U+2069), which make a line read otherwise than its +/// bytes. Line breaks and tabs stay, so a multi-line message keeps its lines. +/// +/// This is for text a human reads. A JSON value carries the reason's characters escaped and needs +/// no filtering. +pub(crate) fn sanitize_terminal_text(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + skip_ansi(&mut chars); + continue; + } + let bidi = matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'); + if (c.is_control() && c != '\n' && c != '\t') || bidi { + continue; + } + out.push(c); + } + out +} + +/// Consumes one ANSI sequence whose ESC was already read. +fn skip_ansi(chars: &mut std::iter::Peekable>) { + let Some(next) = chars.next() else { return }; + match next { + // CSI: ESC [ parameters and intermediates, then one final byte. + '[' => { + for c in chars.by_ref() { + if ('\u{40}'..='\u{7e}').contains(&c) { + break; + } + } + } + // OSC: ESC ] ... BEL, or ESC ] ... ST (ESC \). + ']' => { + while let Some(c) = chars.next() { + if c == '\u{7}' { + break; + } + if c == '\u{1b}' { + if chars.peek() == Some(&'\\') { + chars.next(); + } + break; + } + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::sanitize_terminal_text; + + #[test] + fn test_terminal_text_drops_controls_and_ansi() { + assert_eq!(sanitize_terminal_text("café"), "café"); + assert_eq!(sanitize_terminal_text("a\u{7f}b"), "ab"); + // Clear screen and cursor home. + assert_eq!(sanitize_terminal_text("\u{1b}[2J\u{1b}[Hleft"), "left"); + // An OSC title sequence, ended by BEL. + assert_eq!(sanitize_terminal_text("\u{1b}]0;title\u{7}left"), "left"); + // A lone ESC and a one-byte escape drop with their follower. + assert_eq!(sanitize_terminal_text("\u{1b}"), ""); + assert_eq!(sanitize_terminal_text("\u{1b}Aleft"), "left"); + } + + #[test] + fn test_terminal_text_keeps_lines_and_tabs() { + assert_eq!(sanitize_terminal_text("line one\nline two"), "line one\nline two"); + assert_eq!(sanitize_terminal_text("a\tb"), "a\tb"); + // A carriage return can overwrite what the line printed before it. + assert_eq!(sanitize_terminal_text("owned\r\nit"), "owned\nit"); + } + + #[test] + fn test_terminal_text_drops_c1_controls_and_bidi_overrides() { + // The one-character CSI and OSC introducers, as UTF-8 text. + assert_eq!(sanitize_terminal_text("\u{9b}2J\u{9b}Hcleared"), "2JHcleared"); + assert_eq!(sanitize_terminal_text("\u{9d}0;title\u{9c}x"), "0;titlex"); + assert!((0x80..=0x9f) + .all(|c| sanitize_terminal_text(&char::from_u32(c).unwrap().to_string()).is_empty())); + assert_eq!(sanitize_terminal_text("\u{202e}gnp.exe"), "gnp.exe"); + assert_eq!(sanitize_terminal_text("\u{2066}x\u{2069}"), "x"); + // Letters beside the ranges stay. + assert_eq!(sanitize_terminal_text("\u{a0}\u{a1}\u{2028}"), "\u{a0}\u{a1}\u{2028}"); + } +} diff --git a/bin/mega-evme/src/common/hardfork.rs b/bin/mega-evme/src/common/hardfork.rs deleted file mode 100644 index 3ffb94883..000000000 --- a/bin/mega-evme/src/common/hardfork.rs +++ /dev/null @@ -1,49 +0,0 @@ -use mega_evm::{ - alloy_hardforks::{EthereumHardfork, ForkCondition}, - alloy_op_hardforks::{EthereumHardforks, OpHardfork, OpHardforks}, - MegaHardfork, MegaHardforks, MegaSpecId, -}; - -/// Fixed hardfork configuration for replay -#[derive(Debug, Clone, Copy)] -pub struct FixedHardfork { - spec: MegaSpecId, -} - -impl FixedHardfork { - /// Create a new [`FixedHardfork`] with the given `spec` - pub fn new(spec: MegaSpecId) -> Self { - Self { spec } - } -} - -impl EthereumHardforks for FixedHardfork { - fn ethereum_fork_activation(&self, fork: EthereumHardfork) -> ForkCondition { - if fork <= EthereumHardfork::Prague { - ForkCondition::Timestamp(0) - } else { - ForkCondition::Never - } - } -} - -impl OpHardforks for FixedHardfork { - fn op_fork_activation(&self, fork: OpHardfork) -> ForkCondition { - if fork <= OpHardfork::Isthmus { - ForkCondition::Timestamp(0) - } else { - ForkCondition::Never - } - } -} - -impl MegaHardforks for FixedHardfork { - fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { - let mapped_spec = fork.spec_id(); - if mapped_spec <= self.spec { - ForkCondition::Timestamp(0) - } else { - ForkCondition::Never - } - } -} diff --git a/bin/mega-evme/src/common/hex.rs b/bin/mega-evme/src/common/hex.rs index 4d0cc8a92..774470e13 100644 --- a/bin/mega-evme/src/common/hex.rs +++ b/bin/mega-evme/src/common/hex.rs @@ -6,6 +6,9 @@ use alloy_primitives::{hex, Bytes}; use super::{EvmeError, Result}; +/// Largest hex input or cache file this tool reads whole, in bytes. +pub(crate) const MAX_TEXT_INPUT_BYTES: u64 = 64 * 1024 * 1024; + /// Load hex-encoded bytes from an argument or a file. If the file is a dash (-), read from stdin. /// Priority: arg > file. Returns `None` if neither is provided. pub fn load_hex(arg: Option, file: Option) -> Result> { @@ -13,19 +16,42 @@ pub fn load_hex(arg: Option, file: Option) -> Result MAX_TEXT_INPUT_BYTES { + return Err(hex_input_too_large(hex_string.len() as u64)); + } decode_hex(&hex_string).map(|bytes| Some(Bytes::from(bytes))) } +/// Reads `reader` only up to [`MAX_TEXT_INPUT_BYTES`]. `known_len` rejects a file before the +/// read when its size is already over the limit. +fn read_bounded_text(reader: impl Read, known_len: Option) -> Result { + if let Some(len) = known_len.filter(|len| *len > MAX_TEXT_INPUT_BYTES) { + return Err(hex_input_too_large(len)); + } + let mut text = String::new(); + reader.take(MAX_TEXT_INPUT_BYTES + 1).read_to_string(&mut text)?; + if text.len() as u64 > MAX_TEXT_INPUT_BYTES { + return Err(hex_input_too_large(text.len() as u64)); + } + Ok(text) +} + +fn hex_input_too_large(len: u64) -> EvmeError { + EvmeError::InvalidInput(format!( + "hex input is {len} bytes; the limit is {MAX_TEXT_INPUT_BYTES} bytes" + )) +} + /// Decode hex string, handling optional 0x prefix fn decode_hex(s: &str) -> Result> { let s = s.trim(); @@ -45,3 +71,32 @@ fn decode_hex(s: &str) -> Result> { Ok(hex::decode(hex_str)?) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_load_hex_reads_a_file_within_the_limit() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("code.hex"); + fs::write(&path, "0x00").expect("write"); + let bytes = + load_hex(None, Some(path.to_string_lossy().into())).expect("load").expect("some"); + assert_eq!(bytes.as_ref(), &[0x00]); + } + + #[test] + fn test_load_hex_rejects_an_oversized_file() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("big.hex"); + fs::File::create(&path) + .expect("create") + .set_len(MAX_TEXT_INPUT_BYTES + 1) + .expect("set_len"); + let err = load_hex(None, Some(path.to_string_lossy().into())).expect_err("over the limit"); + let msg = err.to_string(); + assert!(msg.contains(&MAX_TEXT_INPUT_BYTES.to_string()), "{msg}"); + assert!(msg.contains(&(MAX_TEXT_INPUT_BYTES + 1).to_string()), "{msg}"); + } +} diff --git a/bin/mega-evme/src/common/mod.rs b/bin/mega-evme/src/common/mod.rs index 96ddf3e2e..f4bbef346 100644 --- a/bin/mega-evme/src/common/mod.rs +++ b/bin/mega-evme/src/common/mod.rs @@ -1,22 +1,23 @@ mod env; mod error; -mod hardfork; mod hex; mod logging; mod outcome; mod provider; +mod schedule; mod state; mod trace; mod tx; mod tx_override; pub use env::*; +pub(crate) use error::sanitize_terminal_text; pub use error::*; -pub use hardfork::*; pub use hex::*; pub use logging::*; pub use outcome::*; pub use provider::*; +pub use schedule::*; pub use state::*; pub use trace::*; pub use tx::*; diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index 906c9315b..942cbfe83 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -5,14 +5,14 @@ use std::{path::Path, time::Duration}; use super::{EvmeError, StateDumpArgs, TraceArgs}; use alloy_consensus::{Eip658Value, Receipt}; -use alloy_primitives::{hex, Address, BlockHash, Bytes, TxHash, B256}; +use alloy_primitives::{hex, Address, BlockHash, Bytes, TxHash}; use alloy_rpc_types_eth::TransactionReceipt; use alloy_sol_types::{Panic, Revert, SolError}; use clap::Parser; use mega_evm::{ op_revm::OpHaltReason, revm::{context::result::ExecutionResult, state::EvmState}, - MegaHaltReason, MegaTxType, + LimitCheck, LimitKind, MegaHaltReason, MegaTransactionOutcome, MegaTxType, ProtocolLimits, }; use op_alloy_consensus::{OpDepositReceipt, OpReceiptEnvelope}; use serde::Serialize; @@ -33,6 +33,84 @@ pub struct EvmeOutcome { pub exec_time: Duration, /// Optional trace data (if tracing was enabled) pub trace_data: Option, + /// What Satin counted beside the result + pub satin: SatinReport, +} + +/// What the Satin engine counts for a transaction beside revm's result: the gas by ledger, the +/// data size and write records it kept, and the limit that stopped it. +/// +/// It is the one part of the output a legacy run has no counterpart for, so it is carried in a +/// field of its own and every other field keeps its legacy name and meaning. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct SatinReport { + /// Regular (compute) gas spent, before the refund. + pub regular_gas: u64, + /// EIP-8037 state gas spent, net of refills. + pub state_gas: u64, + /// History gas spent, net of refills. + pub history_gas: u64, + /// History bytes the transaction appended, whoever paid for them. + pub history_bytes: u64, + /// The EIP-8037 reservoir left unspent, which the sender gets back. + pub reservoir_remaining: u64, + /// The EIP-7623 floor the receipt's gas used cannot fall below. + pub floor_gas: u64, + /// Data-size bytes the transaction kept. + pub data_size: u64, + /// Account and storage write records the transaction kept: its KV count. + pub write_records: u64, + /// The limit that stopped the transaction, if one did: the crossing that produced the result + /// of its own frame, a transaction-level limit or that frame's own data-size budget. + pub limit_exceeded: Option, + /// The protocol limits the run was held to, in the shape `--override.limits` takes them; + /// present only when that flag replaced the schedule's, so the record of a counterfactual + /// says what it ran under. Boxed: only such a run carries them. + #[serde(skip_serializing_if = "Option::is_none")] + pub limits_override: Option>, +} + +/// A limit that stopped a Satin transaction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct LimitStop { + /// The dimension: `data_size` or `compute_gas`. + pub kind: &'static str, + /// The limit crossed, in the dimension's unit. + pub limit: u64, + /// The usage that crossed it, where it crossed it. + pub used: u64, +} + +impl SatinReport { + /// The report of `outcome`. + pub fn of(outcome: &MegaTransactionOutcome) -> Self { + let gas = outcome.gas; + Self { + regular_gas: gas.regular, + state_gas: gas.state, + history_gas: gas.history, + history_bytes: gas.history_bytes, + reservoir_remaining: gas.reservoir_remaining, + floor_gas: gas.floor, + data_size: outcome.usage.data_size, + write_records: outcome.usage.write_records, + limit_exceeded: match outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, limit, used, .. }) => { + Some(LimitStop { kind: limit_kind_name(kind), limit, used }) + } + _ => None, + }, + limits_override: None, + } + } +} + +/// The name of a limit dimension in output. +pub const fn limit_kind_name(kind: LimitKind) -> &'static str { + match kind { + LimitKind::DataSize => "data_size", + LimitKind::ComputeGas => "compute_gas", + } } impl EvmeOutcome { @@ -44,7 +122,7 @@ impl EvmeOutcome { // Build base receipt let receipt = Receipt { status: Eip658Value::Eip658(self.exec_result.is_success()), - cumulative_gas_used: self.exec_result.gas_used(), + cumulative_gas_used: self.exec_result.tx_gas_used(), logs: self.exec_result.logs().to_vec(), }; @@ -54,6 +132,7 @@ impl EvmeOutcome { MegaTxType::Eip2930 => OpReceiptEnvelope::Eip2930(receipt.with_bloom()), MegaTxType::Eip1559 => OpReceiptEnvelope::Eip1559(receipt.with_bloom()), MegaTxType::Eip7702 => OpReceiptEnvelope::Eip7702(receipt.with_bloom()), + MegaTxType::PostExec => OpReceiptEnvelope::PostExec(receipt.with_bloom()), MegaTxType::Deposit => { let deposit_receipt = OpDepositReceipt { inner: receipt, @@ -77,20 +156,24 @@ pub fn op_receipt_to_tx_receipt( contract_address: Option
, effective_gas_price: u128, gas_used: u64, - transaction_hash: Option, // only used for replay command where tx hash is known - block_hash: Option, // only used for replay command where block hash is known + transaction_hash: Option, + block_hash: Option, transaction_index: u64, + // Block-level index of this receipt's first log. Zero for a lone `tx`. A replay passes the + // number of logs the included preceding transactions emitted. + log_index_base: u64, ) -> OpTxReceipt { // Map logs to include block/tx metadata - let mut log_index = 0; + let tx_hash = transaction_hash.unwrap_or_default(); + let mut log_index = log_index_base; let inner = receipt.clone().map_logs(|log| { let log = alloy_rpc_types_eth::Log { inner: log, block_hash: None, block_number: Some(block_number), block_timestamp: Some(block_timestamp), - transaction_hash: Some(B256::ZERO), - transaction_index: Some(0), + transaction_hash: Some(tx_hash), + transaction_index: Some(transaction_index), log_index: Some(log_index), removed: false, }; @@ -100,7 +183,7 @@ pub fn op_receipt_to_tx_receipt( TransactionReceipt { inner, - transaction_hash: transaction_hash.unwrap_or_default(), + transaction_hash: tx_hash, transaction_index: Some(transaction_index), block_hash, block_number: Some(block_number), @@ -123,8 +206,9 @@ pub fn print_execution_summary( println!(); println!("=== Transaction Summary ==="); + let gas_used = exec_result.tx_gas_used(); match exec_result { - ExecutionResult::Success { gas_used, logs, output, .. } => { + ExecutionResult::Success { logs, output, .. } => { println!("Status: Success"); println!("Gas Used: {}", gas_used); println!("Execution Time: {:?}", exec_time); @@ -139,13 +223,16 @@ pub fn print_execution_summary( println!("Output: 0x{}", hex::encode(output_data)); } } - ExecutionResult::Revert { gas_used, output } => { + ExecutionResult::Revert { output, .. } => { println!("Status: Reverted"); println!("Gas Used: {}", gas_used); println!("Execution Time: {:?}", exec_time); - println!("Revert Reason: {}", decode_revert_reason(output)); + println!( + "Revert Reason: {}", + super::sanitize_terminal_text(&decode_revert_reason(output)) + ); } - ExecutionResult::Halt { gas_used, reason } => { + ExecutionResult::Halt { reason, .. } => { println!("Status: Halted"); println!("Gas Used: {}", gas_used); println!("Execution Time: {:?}", exec_time); @@ -154,13 +241,36 @@ pub fn print_execution_summary( } } +/// Print what Satin counted, after the summary it adds to. +pub fn print_satin_report(report: &SatinReport) { + println!(); + println!("=== Satin Gas ==="); + println!("Regular Gas: {}", report.regular_gas); + println!("State Gas: {}", report.state_gas); + println!("History Gas: {}", report.history_gas); + println!("History Bytes: {}", report.history_bytes); + println!("Reservoir Left: {}", report.reservoir_remaining); + println!("Floor Gas: {}", report.floor_gas); + println!("Data Size: {}", report.data_size); + println!("Write Records: {}", report.write_records); + if let Some(stop) = report.limit_exceeded { + println!("Limit Exceeded: {} (limit {}, used {})", stop.kind, stop.limit, stop.used); + } + if let Some(limits) = &report.limits_override { + println!("Limits Override: {}", serde_json::to_string(limits).expect("limits serialize")); + } +} + /// Decode revert reason from output bytes using alloy's built-in decoders. /// /// Supports: /// - `Error(string)` via `alloy_sol_types::Revert` /// - `Panic(uint256)` via `alloy_sol_types::Panic` /// - Raw hex fallback -fn decode_revert_reason(output: &Bytes) -> String { +/// +/// The text is the reason's own characters. A terminal printer filters it with +/// [`sanitize_terminal_text`](super::sanitize_terminal_text); JSON output escapes it. +pub fn decode_revert_reason(output: &Bytes) -> String { if output.is_empty() { return "(empty)".to_string(); } @@ -184,15 +294,7 @@ fn decode_revert_reason(output: &Bytes) -> String { } /// Format halt reason for display. -fn format_halt_reason(reason: &MegaHaltReason) -> String { - match reason { - MegaHaltReason::Base(op_reason) => format_op_halt_reason(op_reason), - _ => format!("{:?}", reason), - } -} - -/// Format OP halt reason for display. -fn format_op_halt_reason(reason: &OpHaltReason) -> String { +pub fn format_halt_reason(reason: &MegaHaltReason) -> String { match reason { OpHaltReason::Base(eth_reason) => format!("{:?}", eth_reason), _ => format!("{:?}", reason), @@ -274,6 +376,9 @@ pub struct ExecutionSummary { /// Transaction receipt (present only for `tx` command) #[serde(skip_serializing_if = "Option::is_none")] pub receipt: Option, + /// What Satin counted beside the result; absent on a legacy run, which has no counterpart + #[serde(skip_serializing_if = "Option::is_none")] + pub satin: Option, } impl ExecutionSummary { @@ -319,12 +424,13 @@ impl ExecutionSummary { exec_result: &ExecutionResult, contract_address: Option
, ) -> Self { + let gas_used = exec_result.tx_gas_used(); match exec_result { - ExecutionResult::Success { gas_used, logs, output, .. } => { + ExecutionResult::Success { logs, output, .. } => { let output_data = output.data(); Self { success: true, - gas_used: *gas_used, + gas_used, output: if output_data.is_empty() { None } else { @@ -335,16 +441,14 @@ impl ExecutionSummary { ..Default::default() } } - ExecutionResult::Revert { gas_used, output } => Self { - gas_used: *gas_used, + ExecutionResult::Revert { output, .. } => Self { + gas_used, revert_reason: Some(decode_revert_reason(output)), ..Default::default() }, - ExecutionResult::Halt { gas_used, reason } => Self { - gas_used: *gas_used, - halt_reason: Some(format!("{:?}", reason)), - ..Default::default() - }, + ExecutionResult::Halt { reason, .. } => { + Self { gas_used, halt_reason: Some(format!("{:?}", reason)), ..Default::default() } + } } } } @@ -378,4 +482,52 @@ mod tests { let raw = Bytes::from(vec![0xde, 0xad]); assert_eq!(decode_revert_reason(&raw), "0xdead"); } + + #[test] + fn test_decode_revert_reason_keeps_the_reasons_characters() { + let encoded = Revert::from("\u{1b}[2Jowned\nit").abi_encode(); + assert_eq!(decode_revert_reason(&encoded.into()), "Error(\"\u{1b}[2Jowned\nit\")"); + } + + #[test] + fn test_receipt_logs_carry_the_transaction_and_block_index() { + use alloy_primitives::{Address, Log, LogData, B256}; + + let tx_hash = B256::repeat_byte(0xab); + let log = Log { + address: Address::repeat_byte(0x11), + data: LogData::new_unchecked(vec![], Bytes::new()), + }; + let receipt = Receipt { + status: Eip658Value::Eip658(true), + cumulative_gas_used: 21_000, + logs: vec![log.clone(), log], + }; + let envelope = OpReceiptEnvelope::Legacy(receipt.with_bloom()); + let mapped = op_receipt_to_tx_receipt( + &envelope, + 10, + 20, + Address::ZERO, + None, + None, + 1, + 21_000, + Some(tx_hash), + Some(B256::repeat_byte(0xcd)), + 3, + 10, + ); + + assert_eq!(mapped.transaction_hash, tx_hash); + assert_eq!(mapped.transaction_index, Some(3)); + let logs = mapped.inner.logs(); + assert_eq!(logs.len(), 2); + assert_eq!(logs[0].transaction_hash, Some(tx_hash)); + assert_eq!(logs[1].transaction_hash, Some(tx_hash)); + assert_eq!(logs[0].transaction_index, Some(3)); + assert_eq!(logs[1].transaction_index, Some(3)); + assert_eq!(logs[0].log_index, Some(10)); + assert_eq!(logs[1].log_index, Some(11)); + } } diff --git a/bin/mega-evme/src/common/provider/cache_store.rs b/bin/mega-evme/src/common/provider/cache_store.rs index ef7c717ec..fe6d20b2c 100644 --- a/bin/mega-evme/src/common/provider/cache_store.rs +++ b/bin/mega-evme/src/common/provider/cache_store.rs @@ -11,7 +11,7 @@ use std::{ fmt, fs, - io::Write as _, + io::{Read, Write as _}, path::{Path, PathBuf}, }; @@ -252,12 +252,44 @@ impl CacheFileEnvelope { /// Read and validate an envelope from `path`. pub(super) fn load(path: &Path) -> Result { - let content = fs::read_to_string(path).map_err(|e| { + let file = fs::File::open(path).map_err(|e| { EvmeError::FixtureError(format!( "Failed to read RPC cache file {}: {e}", path.display() )) })?; + let len = file + .metadata() + .map_err(|e| { + EvmeError::FixtureError(format!( + "Failed to read RPC cache file {}: {e}", + path.display() + )) + })? + .len(); + if len > crate::common::hex::MAX_TEXT_INPUT_BYTES { + return Err(EvmeError::FixtureError(format!( + "RPC cache file {} is {len} bytes; the limit is {} bytes", + path.display(), + crate::common::hex::MAX_TEXT_INPUT_BYTES, + ))); + } + let mut content = String::new(); + file.take(crate::common::hex::MAX_TEXT_INPUT_BYTES + 1) + .read_to_string(&mut content) + .map_err(|e| { + EvmeError::FixtureError(format!( + "Failed to read RPC cache file {}: {e}", + path.display() + )) + })?; + if content.len() as u64 > crate::common::hex::MAX_TEXT_INPUT_BYTES { + return Err(EvmeError::FixtureError(format!( + "RPC cache file {} exceeds the {} byte limit", + path.display(), + crate::common::hex::MAX_TEXT_INPUT_BYTES, + ))); + } let envelope: Self = serde_json::from_str(&content).map_err(|e| { EvmeError::FixtureError(format!( "Failed to parse RPC cache file {}: {e}", @@ -275,7 +307,14 @@ impl CacheFileEnvelope { } /// Atomically write this envelope to `path`. + /// + /// An envelope [`Self::load`] would refuse for its size is not written: the file already at + /// `path` stays as it is, and the error says so. The tool never writes a file it cannot read. pub(super) fn save(&self, path: &Path) -> Result<()> { + self.save_within(path, crate::common::hex::MAX_TEXT_INPUT_BYTES) + } + + fn save_within(&self, path: &Path, limit: u64) -> Result<()> { let dir = path.parent().unwrap_or_else(|| Path::new(".")); fs::create_dir_all(dir).map_err(|e| { EvmeError::FixtureError(format!( @@ -291,6 +330,16 @@ impl CacheFileEnvelope { )) })?; + if serialized.len() as u64 > limit { + return Err(EvmeError::FixtureError(format!( + "The RPC cache for {} would be {} bytes, over the {limit} byte limit the tool \ + reads back; it was not written, and the file already there is unchanged. Capture \ + into a new file, or delete this one", + path.display(), + serialized.len(), + ))); + } + let mut tmp = tempfile::NamedTempFile::new_in(dir).map_err(|e| { EvmeError::FixtureError(format!("Failed to create temp file in {}: {e}", dir.display())) })?; @@ -392,4 +441,39 @@ mod tests { let msg = format!("{err}"); assert!(msg.contains("parse"), "error should mention parse: {msg}"); } + + #[test] + fn test_envelope_rejects_an_oversized_file() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("big.json"); + let limit = crate::common::hex::MAX_TEXT_INPUT_BYTES; + fs::File::create(&path).expect("create").set_len(limit + 1).expect("set_len"); + let err = CacheFileEnvelope::load(&path).expect_err("over the limit"); + let msg = err.to_string(); + assert!(msg.contains(&limit.to_string()), "{msg}"); + assert!(msg.contains(&(limit + 1).to_string()), "{msg}"); + assert!(!msg.contains("parse"), "{msg}"); + } + + #[test] + fn test_envelope_save_refuses_what_load_would_refuse() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("grow.json"); + let envelope = CacheFileEnvelope::new(&TransportCache::new(), 4326, None); + envelope.save(&path).expect("a small envelope saves"); + let before = fs::read(&path).expect("read"); + let size = before.len() as u64; + + // At the limit the envelope is written, one byte under it is not, and the file stays. + envelope.save_within(&path, size).expect("at the limit"); + let err = envelope.save_within(&path, size - 1).expect_err("over the limit"); + let msg = err.to_string(); + assert!(msg.contains(&size.to_string()) && msg.contains("unchanged"), "{msg}"); + assert_eq!(fs::read(&path).expect("read"), before); + + // A path with no file is not created either. + let fresh = dir.path().join("fresh.json"); + envelope.save_within(&fresh, size - 1).expect_err("over the limit"); + assert!(!fresh.exists()); + } } diff --git a/bin/mega-evme/src/common/provider/mod.rs b/bin/mega-evme/src/common/provider/mod.rs index 94369a6fc..ae6f54f45 100644 --- a/bin/mega-evme/src/common/provider/mod.rs +++ b/bin/mega-evme/src/common/provider/mod.rs @@ -101,10 +101,11 @@ pub struct RpcArgs { #[arg(id = "cache_size", long = "rpc.cache-size", default_value_t = 10_000)] pub cache_size: u32, - /// Directory for per-chain RPC cache files. + /// Directory for per-endpoint RPC cache files. /// - /// Each chain's cache is stored as `{cache_dir}/rpc-cache-{chain_id}.json`. Different chains - /// cannot share a file, so cross-chain contamination is impossible by construction. + /// Each endpoint of a chain is stored as `{cache_dir}/rpc-cache-{chain_id}-{endpoint}.json`, + /// where `{endpoint}` is a short hash of the URL with any userinfo removed. The name does + /// not contain the URL, and two endpoints of one chain do not share a file. /// /// Defaults to the platform cache directory (`$XDG_CACHE_HOME/mega-evme/rpc` on /// Linux, `~/Library/Caches/mega-evme/rpc` on macOS). Pass `--rpc.no-cache-file` @@ -151,18 +152,21 @@ impl RpcArgs { EvmeError::InvalidInput("No RPC URL provided. Pass '--rpc '.".to_string()) })?; - let url: reqwest::Url = rpc_url_str.parse().map_err(|e| { - EvmeError::RpcError(format!("Invalid RPC URL '{}': {}", rpc_url_str, e)) - })?; + let url = parse_rpc_url(rpc_url_str)?; // 1. Resolve chain id (always needed by downstream consumers). let chain_id = self.resolve_chain_id(url.clone()).await?; - // 2. Fast path: cache fully disabled. + // 2. Fast path: cache fully disabled. A clear still deletes the on-disk file: leaving + // it would reload the wiped entries the next time the cache is turned back on. if self.cache_size == 0 { + if self.clear_cache && !self.no_cache_file { + let path = resolve_cache_path(self.cache_dir.as_deref(), chain_id, rpc_url_str)?; + clear_cache_file(&path)?; + } let provider = build_bare_op_provider(self.build_retry_client(url)); info!( - rpc_url = %rpc_url_str, + rpc_url = %redact_rpc_url(rpc_url_str), max_retries = self.max_retries, backoff_ms = self.backoff_ms, "Built RPC provider (cache disabled)", @@ -179,7 +183,7 @@ impl RpcArgs { let cache_path = if self.no_cache_file { None } else { - Some(resolve_cache_path(self.cache_dir.as_deref(), chain_id)?) + Some(resolve_cache_path(self.cache_dir.as_deref(), chain_id, rpc_url_str)?) }; // 4. Build the cache layer and (optionally) the disk store. @@ -188,16 +192,7 @@ impl RpcArgs { let cache_store = match cache_path { Some(path) => { if self.clear_cache { - if let Err(e) = fs::remove_file(&path) { - if e.kind() != std::io::ErrorKind::NotFound { - return Err(EvmeError::RpcError(format!( - "Failed to clear RPC cache at {}: {e}", - path.display(), - ))); - } - } else { - info!(path = %path.display(), "Cleared existing RPC cache"); - } + clear_cache_file(&path)?; } if let Some(parent) = path.parent() { if let Err(e) = fs::create_dir_all(parent) { @@ -231,7 +226,7 @@ impl RpcArgs { .connect_client(client); info!( - rpc_url = %rpc_url_str, + rpc_url = %redact_rpc_url(rpc_url_str), cache_size = self.cache_size, max_retries = self.max_retries, backoff_ms = self.backoff_ms, @@ -246,6 +241,27 @@ impl RpcArgs { }) } + /// A provider for reading what decides a command's engine (the chain id, and a block's + /// timestamp), over the same source the command reads, without a cache that could be + /// persisted: the replay file when one is given, otherwise the RPC endpoint directly. + pub async fn build_lookup_provider(&self) -> Result<(OpProvider, u64)> { + if self.replay_file.is_some() { + let BuildProviderOutput { provider, chain_id, .. } = + self.build_replay_provider().await?; + return Ok((provider, chain_id)); + } + let rpc_url_str = self.rpc_url.as_deref().ok_or_else(|| { + EvmeError::InvalidInput( + "'mega-evme replay' requires '--rpc ', '--rpc.capture-file ', or \ + '--rpc.replay-file '" + .to_string(), + ) + })?; + let url = parse_rpc_url(rpc_url_str)?; + let chain_id = self.resolve_chain_id(url.clone()).await?; + Ok((build_bare_op_provider(self.build_retry_client(url)), chain_id)) + } + /// Build the provider in replay mode (`--rpc.replay-file` without `--rpc`). /// /// Loads the envelope's transport-level cache and builds the provider over @@ -300,9 +316,7 @@ impl RpcArgs { let path = self.capture_file.as_ref().expect("capture mode requires --rpc.capture-file"); let rpc_url_str = self.rpc_url.as_ref().expect("capture mode requires --rpc"); - let url: reqwest::Url = rpc_url_str.parse().map_err(|e| { - EvmeError::RpcError(format!("Invalid RPC URL '{}': {}", rpc_url_str, e)) - })?; + let url = parse_rpc_url(rpc_url_str)?; // Load existing envelope if the file exists. let existing_envelope = if path.exists() { @@ -334,7 +348,10 @@ impl RpcArgs { // Resolve chain_id through the caching provider (hits network, response captured). let chain_id = provider.get_chain_id().await.map_err(|e| { - EvmeError::RpcError(format!("Failed to fetch chain ID from '{}': {e}", rpc_url_str)) + EvmeError::RpcError(format!( + "Failed to fetch chain ID from '{}': {e}", + redact_rpc_url(rpc_url_str) + )) })?; // Validate chain_id match, then merge existing entries into the cache. @@ -355,7 +372,7 @@ impl RpcArgs { } info!( - rpc_url = %rpc_url_str, + rpc_url = %redact_rpc_url(rpc_url_str), path = %path.display(), chain_id, "Built RPC provider (capture to cache file)", @@ -372,7 +389,7 @@ impl RpcArgs { } /// Build an `RpcClient` over HTTP, wired with the configured retry layer. - fn build_retry_client(&self, url: reqwest::Url) -> RpcClient { + fn build_retry_client(&self, url: alloy_transport_http::reqwest::Url) -> RpcClient { self.build_client(alloy_transport_http::Http::new(url.clone()), &url) } @@ -382,7 +399,7 @@ impl RpcArgs { fn build_client( &self, transport: T, - url: &reqwest::Url, + url: &alloy_transport_http::reqwest::Url, ) -> RpcClient { let is_local = url.host_str().is_some_and(|h| h == "localhost" || h == "127.0.0.1" || h == "::1"); @@ -404,11 +421,11 @@ impl RpcArgs { /// Resolve the chain ID by issuing `eth_chainId` against a throwaway /// cache-less provider using the configured retry policy. - async fn resolve_chain_id(&self, url: reqwest::Url) -> Result { - let url_str = url.as_str().to_string(); + async fn resolve_chain_id(&self, url: alloy_transport_http::reqwest::Url) -> Result { + let url_str = redact_rpc_url(url.as_str()); let bare = build_bare_op_provider(self.build_retry_client(url)); bare.get_chain_id().await.map_err(|e| { - EvmeError::RpcError(format!("Failed to fetch chain ID from '{}': {}", url_str, e)) + EvmeError::RpcError(format!("Failed to fetch chain ID from '{}': {e}", url_str)) }) } } @@ -444,6 +461,66 @@ fn build_bare_op_provider(client: RpcClient) -> OpProvider { ) } +/// The URL with any userinfo removed, for a log line, an error, or a cache file name. +/// +/// Userinfo is the part of the authority before its last `@`, as the URL standard reads it, so a +/// password holding an `@` goes whole. It is removed from the text itself, so it holds for a URL +/// written without its scheme (`user:password@host`) and for one that does not parse. Credentials +/// anywhere else in the URL, such as an API key in the path or the query, are not recognised and +/// stay. +pub(crate) fn redact_rpc_url(raw: &str) -> String { + let (scheme, rest) = raw.find("://").map_or(("", raw), |at| raw.split_at(at + 3)); + let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let stripped = match rest[..authority_end].rfind('@') { + Some(at) => format!("{scheme}{}", &rest[at + 1..]), + None => return normalized(raw), + }; + normalized(&stripped) +} + +/// `raw` as the URL parser writes it, or unchanged when it does not parse. +fn normalized(raw: &str) -> String { + raw.parse::() + .map_or_else(|_| raw.to_string(), |u| u.to_string()) +} + +/// Parses `--rpc`. The transport speaks HTTP, so any other scheme is refused here, before the URL +/// reaches a library whose error text would repeat it whole. +fn parse_rpc_url(raw: &str) -> Result { + let url: alloy_transport_http::reqwest::Url = raw.parse().map_err(|e| { + EvmeError::RpcError(format!("Invalid RPC URL '{}': {e}", redact_rpc_url(raw))) + })?; + if !matches!(url.scheme(), "http" | "https") { + return Err(EvmeError::InvalidInput(format!( + "Invalid RPC URL '{}': it has to start with http:// or https://", + redact_rpc_url(raw) + ))); + } + Ok(url) +} + +/// `rpc-cache-{chain_id}-{endpoint}.json`. `{endpoint}` is eight hex characters of the +/// keccak of the URL with userinfo removed. +pub fn rpc_cache_file_name(chain_id: u64, rpc_url: &str) -> String { + let digest = alloy_primitives::keccak256(redact_rpc_url(rpc_url).as_bytes()); + format!("rpc-cache-{chain_id}-{}.json", alloy_primitives::hex::encode(&digest[..4])) +} + +/// Deletes `path` when `--rpc.clear-cache` asked for it. A missing file is already clear. +fn clear_cache_file(path: &Path) -> Result<()> { + if let Err(e) = fs::remove_file(path) { + if e.kind() != std::io::ErrorKind::NotFound { + return Err(EvmeError::RpcError(format!( + "Failed to clear RPC cache at {}: {e}", + path.display(), + ))); + } + } else { + info!(path = %path.display(), "Cleared existing RPC cache"); + } + Ok(()) +} + /// Resolve the absolute cache file path for `chain_id`. /// /// If the user passed `--rpc.cache-dir` we use it verbatim. Otherwise we fall back to @@ -451,7 +528,11 @@ fn build_bare_op_provider(client: RpcClient) -> OpProvider { /// on Linux, `~/Library/Caches/mega-evme/rpc` on macOS, `%LOCALAPPDATA%\mega-evme\rpc` on /// Windows. If the platform has no cache directory we error out and ask the user to /// either pass `--rpc.cache-dir` or `--rpc.no-cache-file`. -fn resolve_cache_path(user_cache_dir: Option<&Path>, chain_id: u64) -> Result { +fn resolve_cache_path( + user_cache_dir: Option<&Path>, + chain_id: u64, + rpc_url: &str, +) -> Result { let dir = match user_cache_dir { Some(dir) => dir.to_path_buf(), None => dirs::cache_dir() @@ -465,7 +546,7 @@ fn resolve_cache_path(user_cache_dir: Option<&Path>, chain_id: u64) -> Result.json` inside it. + /// Explicit `--rpc.cache-dir` is used verbatim. The file names the chain and a hash of the + /// endpoint, and the hash does not change when only the userinfo does. #[test] fn test_resolve_cache_path_with_explicit_dir() { let dir = PathBuf::from("/some/user/dir"); - // 4326 = MegaETH mainnet. - let path = resolve_cache_path(Some(&dir), 4326).expect("resolve"); - assert_eq!(path, PathBuf::from("/some/user/dir/rpc-cache-4326.json")); + let url = "http://alice:secret@example.com/rpc"; + let path = resolve_cache_path(Some(&dir), 4326, url).expect("resolve"); + let name = rpc_cache_file_name(4326, url); + assert_eq!(path, dir.join(&name)); + assert!(name.starts_with("rpc-cache-4326-"), "{name}"); + assert!(!name.contains("secret") && !name.contains("alice") && !name.contains("example")); + assert_eq!(name, rpc_cache_file_name(4326, "http://example.com/rpc")); + assert_ne!(name, rpc_cache_file_name(4326, "http://other.example/rpc")); + } + + #[test] + fn test_redact_rpc_url_strips_userinfo() { + assert_eq!( + redact_rpc_url("http://alice:secret@example.com/rpc"), + redact_rpc_url("http://example.com/rpc") + ); + assert!(!redact_rpc_url("http://alice:secret@example.com/rpc").contains("secret")); + let broken = redact_rpc_url("http://alice:secret@not a url"); + assert!(!broken.contains("secret") && !broken.contains("alice"), "{broken}"); + assert_eq!(redact_rpc_url("not a url"), "not a url"); + } + + /// A URL written without its scheme parses as a scheme named after the user. Its userinfo + /// goes all the same. + #[test] + fn test_redact_rpc_url_strips_userinfo_of_a_url_without_a_scheme() { + assert_eq!(redact_rpc_url("alice:s3cret@rpc.example.com"), "rpc.example.com"); + assert_eq!( + redact_rpc_url("alice:s3cret@rpc.example.com:8545/path"), + "rpc.example.com:8545/path" + ); + assert_eq!(redact_rpc_url("rpc.example.com"), "rpc.example.com"); + assert_eq!(redact_rpc_url("localhost:8545"), "localhost:8545"); + } + + /// The userinfo ends at the last `@` of the authority, so an `@` in the password does not + /// leave its tail behind, whether the URL parses or not. + #[test] + fn test_redact_rpc_url_strips_a_password_holding_an_at_sign() { + assert_eq!( + redact_rpc_url("http://alice:p@ss@example.com/rpc"), + redact_rpc_url("http://example.com/rpc") + ); + let broken = redact_rpc_url("http://alice:p@ss@bad host/"); + assert_eq!(broken, "http://bad host/"); + assert_eq!(redact_rpc_url("alice:p@ss@example.com"), "example.com"); + // An `@` after the authority belongs to the path or the query. + assert_eq!(redact_rpc_url("http://example.com/a@b"), "http://example.com/a@b"); + assert_eq!(redact_rpc_url("http://example.com/?mail=a@b"), "http://example.com/?mail=a@b"); + } + + /// Only HTTP is spoken, and the refusal of another scheme names the URL without its userinfo. + #[test] + fn test_parse_rpc_url_refuses_another_scheme_without_the_userinfo() { + let error = parse_rpc_url("alice:s3cret@rpc.example.com").unwrap_err().to_string(); + assert!(error.contains("http://") && !error.contains("s3cret"), "{error}"); + let error = parse_rpc_url("ftp://alice:s3cret@example.com").unwrap_err().to_string(); + assert!(!error.contains("s3cret"), "{error}"); + assert!(parse_rpc_url("http://alice:s3cret@example.com").is_ok()); + assert!(parse_rpc_url("https://example.com").is_ok()); } /// No explicit dir falls back to `dirs::cache_dir()` on platforms that have one. - /// The path ends in `mega-evme/rpc/rpc-cache-.json`. + /// The path ends in `mega-evme/rpc/` and the endpoint's file name. #[test] fn test_resolve_cache_path_default_is_under_platform_cache() { let Some(expected_root) = dirs::cache_dir() else { // Skip on exotic platforms where no cache directory is available. return; }; - let path = resolve_cache_path(None, 11_155_420).expect("resolve"); - let expected = expected_root.join("mega-evme").join("rpc").join("rpc-cache-11155420.json"); + let url = "https://example.test/rpc"; + let path = resolve_cache_path(None, 11_155_420, url).expect("resolve"); + let expected = + expected_root.join("mega-evme").join("rpc").join(rpc_cache_file_name(11_155_420, url)); assert_eq!(path, expected); } } diff --git a/bin/mega-evme/src/common/schedule.rs b/bin/mega-evme/src/common/schedule.rs new file mode 100644 index 000000000..ca93f4ea0 --- /dev/null +++ b/bin/mega-evme/src/common/schedule.rs @@ -0,0 +1,446 @@ +//! The hardfork schedule a Satin run executes under, and the protocol limits it is held to. + +use std::sync::OnceLock; + +use mega_evm::{ + alloy_hardforks::ForkCondition, ChainActivation, MegaHardfork, MegaHardforkConfig, + MegaHardforks, MegaSpecId, ProtocolLimits, SatinChainConfig, +}; +use serde_json::{Map, Value}; + +use super::{EvmeError, Result}; + +/// The hardfork schedule a Satin run for chain `chain_id` at `timestamp` executes under. +/// +/// A block the chain's own schedule runs on Satin runs under that schedule. A schedule the engine +/// refuses ([`MegaHardforks::validate_schedule`]) is refused rather than replaced: a run under +/// another schedule would report results the chain does not produce. +/// +/// Any other run is a counterfactual — `--override.spec Satin`, or `run` and `tx` with +/// `--spec Satin` — and executes under the chain's own schedule with Satin from genesis +/// ([`counterfactual`]), so no block of the run is Satin's activation block. Satin carries no +/// parameter: the `SequencerRegistry`'s roles are what the state the run executes on holds. +/// +/// The limits are not the schedule's: they are fixed per spec ([`satin_limits`]). +/// +/// The chain's own schedule is the one its genesis file gives, when the run was given the file +/// (`--genesis`), and otherwise the Satin engine's table ([`mega_evm::hardfork_schedule`]), which +/// knows `MegaETH` mainnet and testnet and no other chain. A run given the file makes no +/// counterfactual: one the file does not run on Satin — before its `satinTime`, or on a file +/// without Satin keys — is refused, since the file was given to configure the run and cannot. +pub fn satin_schedule(chain_id: u64, timestamp: u64) -> Result { + let chain = match GENESIS.get() { + Some(genesis) => Some(genesis_schedule(genesis, chain_id, timestamp)?), + None => mega_evm::hardfork_schedule(chain_id), + }; + schedule_for(chain, timestamp) +} + +/// The schedule of a Satin counterfactual on the chain whose schedule is `chain`: that schedule +/// with Satin from genesis, or, for a chain neither the engine's table nor a genesis file names, +/// the engine's base forks with Satin from genesis. +fn counterfactual(chain: Option) -> MegaHardforkConfig { + chain.unwrap_or_default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)) +} + +/// The protocol limits a Satin run is held to: Satin's ([`ProtocolLimits::for_spec`]), the ones +/// every chain's Satin blocks are held to, with the fields `limits_override` names replaced, a +/// counterfactual. +pub fn satin_limits(limits_override: Option<&LimitsOverride>) -> Result { + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); + match limits_override { + Some(limits_override) => limits_override.apply(limits), + None => Ok(limits), + } +} + +/// The genesis file this run was given (`--genesis`), set once before the command runs. +static GENESIS: OnceLock = OnceLock::new(); + +/// A chain as its genesis file configures it: its chain id, and its Satin key, read by the parser +/// every reader of a genesis file shares ([`SatinChainConfig::from_genesis_config`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GenesisChain { + /// The genesis file's `chainId`. + pub chain_id: u64, + /// The chain's Satin configuration; `None` when the file does not activate Satin. + pub satin: Option, +} + +/// Makes `genesis` the chain configuration of every run of its chain from now on: its schedule is +/// the one [`satin_schedule`] starts from, and its Satin activation the one the engine of a block +/// is picked by ([`chain_activation`]). +/// +/// # Errors +/// +/// When the process already uses another genesis file: it holds one for its lifetime. +pub fn use_genesis(genesis: GenesisChain) -> Result<()> { + let in_use = GENESIS.get_or_init(|| genesis.clone()); + if *in_use != genesis { + return Err(EvmeError::InvalidInput( + "--genesis: this process already runs another genesis file".to_string(), + )); + } + Ok(()) +} + +/// Whether the run was given a genesis file (`--genesis`). +pub fn genesis_in_use() -> bool { + GENESIS.get().is_some() +} + +/// The activation table of `chain_id`: the genesis file's when the run was given one for that +/// chain, and otherwise the Satin engine's ([`mega_evm::chain_activation`]). +pub fn chain_activation(chain_id: u64) -> Option { + match GENESIS.get() { + Some(genesis) if genesis.chain_id == chain_id => Some(ChainActivation { + chain_id, + satin: genesis.satin.map(|satin| satin.activation_time), + }), + _ => mega_evm::chain_activation(chain_id), + } +} + +/// Refuses a run on `chain_id` when the run was given the genesis file of another chain. +/// +/// A command checks this before it picks its engine, where it knows its chain first, so that a +/// run on the wrong chain is refused for its chain rather than for a spec the file cannot +/// configure. +pub fn check_genesis_chain(chain_id: u64) -> Result<()> { + GENESIS.get().map_or(Ok(()), |genesis| genesis.check_chain(chain_id)) +} + +impl GenesisChain { + /// Refuses a run on `chain_id` unless it is this file's chain. + fn check_chain(&self, chain_id: u64) -> Result<()> { + if self.chain_id != chain_id { + return Err(EvmeError::InvalidInput(format!( + "--genesis configures chain {}, and the run is on chain {chain_id}", + self.chain_id + ))); + } + Ok(()) + } +} + +/// The schedule a Satin run of `chain_id` at `timestamp` takes from `genesis`: refused when the +/// file is another chain's, has no Satin keys, or activates Satin after `timestamp`. +fn genesis_schedule( + genesis: &GenesisChain, + chain_id: u64, + timestamp: u64, +) -> Result { + genesis.check_chain(chain_id)?; + let Some(satin) = &genesis.satin else { + return Err(EvmeError::InvalidInput(format!( + "--genesis: the file has no Satin keys, so chain {chain_id} never runs Satin on it; \ + a Satin run needs a file that activates Satin" + ))); + }; + if timestamp < satin.activation_time { + return Err(EvmeError::InvalidInput(format!( + "--genesis activates Satin at timestamp {}, and the run is at timestamp {timestamp}: \ + the file configures no Satin run before it", + satin.activation_time + ))); + } + satin.hardforks().map_err(|e| { + EvmeError::InvalidInput(format!("--genesis: the schedule it makes is refused: {e}")) + }) +} + +/// Parses `--genesis`: the path of a genesis file, whose `config` object carries the chain id and +/// the Satin key. A file that is the `config` object itself is read as one. +pub fn parse_genesis(path: &str) -> std::result::Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("reading {path}: {e}"))?; + let file: Value = serde_json::from_str(&text).map_err(|e| format!("not JSON: {e}"))?; + let config = file.get("config").unwrap_or(&file); + let chain_id = config + .get("chainId") + .and_then(Value::as_u64) + .ok_or("the chain configuration has no integer `chainId`")?; + let satin = SatinChainConfig::from_genesis_config(config).map_err(|e| e.to_string())?; + Ok(GenesisChain { chain_id, satin }) +} + +/// [`satin_schedule`] for a chain whose schedule is `chain`, `None` for a chain nothing names. +fn schedule_for(chain: Option, timestamp: u64) -> Result { + let schedule = match chain { + Some(chain) if chain.spec_id(timestamp) == Some(MegaSpecId::SATIN) => chain, + chain => counterfactual(chain), + }; + schedule.validate_schedule().map_err(|e| { + EvmeError::InvalidInput(format!( + "the chain's schedule runs Satin at timestamp {timestamp} but cannot run it: {e}" + )) + })?; + Ok(schedule) +} + +/// Protocol limits to run under in place of the spec's (`--override.limits`): a JSON object in +/// [`ProtocolLimits`]' shape, naming only the fields it replaces. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LimitsOverride(Map); + +impl LimitsOverride { + /// The limits `base` becomes with the fields this names replaced, recursively. + /// + /// The result is refused when it names a field [`ProtocolLimits`] does not have, or a value + /// of the wrong type. Any value of the right type is run: an override is a counterfactual, and + /// a limit of zero, or `u64::MAX` for both detention caps, which turns detention off, is one + /// a tool may ask for. + pub fn apply(&self, base: ProtocolLimits) -> Result { + let invalid = + |message: String| EvmeError::InvalidInput(format!("--override.limits: {message}")); + let mut merged = serde_json::to_value(base).expect("limits serialize"); + merge(&mut merged, &self.0); + serde_json::from_value(merged).map_err(|e| invalid(e.to_string())) + } +} + +/// Writes every field of `patch` into `target`, merging the objects both hold. +fn merge(target: &mut Value, patch: &Map) { + let Value::Object(target) = target else { unreachable!("limits serialize to an object") }; + for (key, value) in patch { + match (target.get_mut(key), value) { + (Some(existing @ Value::Object(_)), Value::Object(patch)) => merge(existing, patch), + _ => { + target.insert(key.clone(), value.clone()); + } + } + } +} + +/// Parses `--override.limits`: a JSON object given inline, or the path of a file that holds one. +/// An argument that starts like JSON (`{` or `[`) is inline. +pub fn parse_limits_override(arg: &str) -> std::result::Result { + let text = if arg.trim_start().starts_with(['{', '[']) { + arg.to_string() + } else { + std::fs::read_to_string(arg).map_err(|e| format!("reading {arg}: {e}"))? + }; + match serde_json::from_str(&text).map_err(|e| format!("not JSON: {e}"))? { + Value::Object(fields) => Ok(LimitsOverride(fields)), + _ => Err("must be a JSON object".to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{ChainActivation, MAINNET_CHAIN_ID, TESTNET_CHAIN_ID}; + + const ACTIVATION: u64 = 1_800_000_000; + + fn scheduled() -> MegaHardforkConfig { + ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(ACTIVATION) }.hardforks() + } + + /// A counterfactual runs on the chain's own schedule with Satin from genesis, whatever the + /// chain; a chain the engine does not know gets the engine's base forks with Satin from + /// genesis. No block of a counterfactual is Satin's activation block. + #[test] + fn test_a_counterfactual_runs_on_the_chains_schedule_with_satin_from_genesis() { + for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, 6342, 1] { + let schedule = satin_schedule(chain_id, 1_700_000_000).unwrap(); + assert_eq!(schedule.spec_id(0), Some(MegaSpecId::SATIN), "chain {chain_id}"); + assert!(!schedule.is_satin_activation_block(0, 1_700_000_000), "chain {chain_id}"); + assert_eq!(schedule.validate_schedule(), Ok(())); + } + let known = mega_evm::hardfork_schedule(MAINNET_CHAIN_ID).unwrap(); + let counterfactual = satin_schedule(MAINNET_CHAIN_ID, 1_700_000_000).unwrap(); + let osaka = mega_evm::alloy_hardforks::EthereumHardfork::Osaka; + assert_eq!(counterfactual.get(osaka), known.get(osaka), "the chain's own forks"); + } + + /// Before a chain's scheduled activation a Satin run is a counterfactual on the chain's + /// schedule with Satin from genesis; from it on, the run takes the chain's schedule, which + /// needs no parameter. + #[test] + fn test_a_real_satin_block_runs_on_the_chains_own_schedule() { + let before = schedule_for(Some(scheduled()), ACTIVATION - 1).unwrap(); + assert_eq!(before.spec_id(0), Some(MegaSpecId::SATIN), "Satin from genesis"); + let from = schedule_for(Some(scheduled()), ACTIVATION).unwrap(); + assert_eq!(from.spec_id(ACTIVATION - 1), None, "the chain's own activation holds"); + assert_eq!(from.spec_id(ACTIVATION), Some(MegaSpecId::SATIN)); + } + + /// A chain whose schedule the engine refuses is refused, not run on another schedule: one + /// that activates Satin before a fork Satin runs on. + #[test] + fn test_a_real_satin_block_on_a_refused_schedule_is_refused() { + use mega_evm::alloy_hardforks::{EthereumHardfork, ForkCondition}; + let late = ForkCondition::Timestamp(ACTIVATION + 1); + let chain = scheduled().with(EthereumHardfork::Osaka, late); + let error = schedule_for(Some(chain), ACTIVATION).unwrap_err().to_string(); + assert!(error.contains("the Osaka fork it runs on is not active"), "{error}"); + assert!(error.contains(&ACTIVATION.to_string()), "{error}"); + assert!(error.contains("cannot run it"), "{error}"); + } + + /// Without an override a run is held to Satin's limits, whatever the chain. + #[test] + fn test_a_run_is_held_to_the_specs_limits() { + assert_eq!(satin_limits(None).unwrap(), ProtocolLimits::for_spec(MegaSpecId::SATIN)); + } + + fn overriding(json: &str) -> LimitsOverride { + parse_limits_override(json).unwrap() + } + + /// An override replaces the fields it names and keeps every other one of Satin's. + #[test] + fn test_an_override_replaces_only_the_fields_it_names() { + let limits = satin_limits(Some(&overriding( + r#"{"txRuntimeLimits":{"txDataSizeLimit":350},"blockTxsDataLimit":7}"#, + ))) + .unwrap(); + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let expected = satin + .with_tx_runtime_limits(satin.tx_runtime_limits.with_tx_data_size_limit(350)) + .with_block_txs_data_limit(7); + assert_eq!(limits, expected); + } + + /// An override is held to the limits' shape: no unknown field, no value of the wrong type. + /// Any value of the right type is a counterfactual the tool runs: a limit of zero, or + /// detention turned off. + #[test] + fn test_an_override_is_held_to_the_limits_shape() { + let refused = |json: &str| satin_limits(Some(&overriding(json))).unwrap_err().to_string(); + let unknown = refused(r#"{"txDataSizeLimit":350}"#); + assert!(unknown.contains("unknown field `txDataSizeLimit`"), "{unknown}"); + let not_a_number = refused(r#"{"blockTxsDataLimit":"1"}"#); + assert!(not_a_number.starts_with("Invalid input: --override.limits:"), "{not_a_number}"); + + let zero = + satin_limits(Some(&overriding(r#"{"txRuntimeLimits":{"frameDataSizeLimit":0}}"#))) + .unwrap(); + assert_eq!(zero.tx_runtime_limits.frame_data_size_limit, 0); + let undetained = serde_json::to_string(&ProtocolLimits::no_limits()).unwrap(); + assert_eq!( + satin_limits(Some(&overriding(&undetained))).unwrap(), + ProtocolLimits::no_limits() + ); + } + + /// A genesis file whose `config` carries `chainId` and the Satin key: Satin at + /// [`ACTIVATION`]. + fn genesis_file(dir: &tempfile::TempDir, chain_id: u64) -> (String, SatinChainConfig) { + let satin = SatinChainConfig { activation_time: ACTIVATION }; + let mut config = serde_json::to_value(satin).unwrap(); + config["chainId"] = serde_json::json!(chain_id); + config["optimism"] = serde_json::json!({ "eip1559Elasticity": 6 }); + let path = dir.path().join("genesis.json"); + std::fs::write(&path, serde_json::json!({ "config": config, "alloc": {} }).to_string()) + .unwrap(); + (path.to_str().unwrap().to_string(), satin) + } + + /// A genesis file's schedule is its chain's: Satin from its `satinTime`. Without the file the + /// engine's table does not know the chain, and a Satin run on it is a counterfactual. + #[test] + fn test_a_genesis_file_gives_its_chain_its_schedule() { + let dir = tempfile::tempdir().unwrap(); + let (path, satin) = genesis_file(&dir, 6342); + let genesis = parse_genesis(&path).unwrap(); + assert_eq!(genesis, GenesisChain { chain_id: 6342, satin: Some(satin) }); + + for timestamp in [ACTIVATION, u64::MAX] { + let chain = genesis_schedule(&genesis, 6342, timestamp).unwrap(); + let schedule = schedule_for(Some(chain), timestamp).unwrap(); + assert_eq!(schedule.spec_id(ACTIVATION - 1), None); + assert_eq!(schedule.spec_id(ACTIVATION), Some(MegaSpecId::SATIN)); + } + assert!(mega_evm::hardfork_schedule(6342).is_none(), "the engine table does not know it"); + let counterfactual = schedule_for(None, ACTIVATION).unwrap(); + assert_eq!( + counterfactual.spec_id(0), + Some(MegaSpecId::SATIN), + "without the file, a counterfactual from genesis" + ); + + // Before its activation the file configures no Satin run: the run is refused, not made + // the counterfactual a run without the file would be. + for timestamp in [0, ACTIVATION - 1] { + let error = genesis_schedule(&genesis, 6342, timestamp).unwrap_err().to_string(); + assert!( + error.contains(&format!( + "--genesis activates Satin at timestamp {ACTIVATION}, and the run is at \ + timestamp {timestamp}" + )), + "{error}" + ); + } + } + + /// A genesis file is its own chain's: a run on another chain is refused rather than run on + /// either schedule, and so is a Satin run on a file without Satin keys, at any timestamp. + #[test] + fn test_a_genesis_file_of_another_chain_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let (path, _) = genesis_file(&dir, 6342); + let genesis = parse_genesis(&path).unwrap(); + for timestamp in [0, ACTIVATION] { + let error = genesis_schedule(&genesis, 6343, timestamp).unwrap_err().to_string(); + assert!(error.contains("--genesis configures chain 6342"), "{error}"); + assert!(genesis.check_chain(6343).is_err()); + } + assert!(genesis.check_chain(6342).is_ok()); + + let without_satin = GenesisChain { chain_id: 6342, satin: None }; + for timestamp in [0, u64::MAX] { + let error = genesis_schedule(&without_satin, 6342, timestamp).unwrap_err().to_string(); + assert!(error.contains("--genesis: the file has no Satin keys"), "{error}"); + } + let error = genesis_schedule(&without_satin, 6343, 0).unwrap_err().to_string(); + assert!(error.contains("--genesis configures chain 6342"), "the chain first: {error}"); + } + + /// The file is read as a genesis file or as its `config` object; one without a chain id, or + /// whose Satin keys the shared parser refuses, is refused with the parser's reason: an old + /// file that still names the registry's roles among them. + #[test] + fn test_the_genesis_file_is_parsed_by_the_shared_parser() { + let dir = tempfile::tempdir().unwrap(); + let write = |name: &str, json: Value| { + let path = dir.path().join(name); + std::fs::write(&path, json.to_string()).unwrap(); + path.to_str().unwrap().to_string() + }; + let bare = write("config.json", serde_json::json!({ "chainId": 7 })); + assert_eq!(parse_genesis(&bare), Ok(GenesisChain { chain_id: 7, satin: None })); + let no_chain_id = write("no-id.json", serde_json::json!({ "config": {} })); + assert!(parse_genesis(&no_chain_id).unwrap_err().contains("chainId")); + let satin = write("satin.json", serde_json::json!({ "chainId": 7, "satinTime": 0 })); + let expected = + GenesisChain { chain_id: 7, satin: Some(SatinChainConfig { activation_time: 0 }) }; + assert_eq!(parse_genesis(&satin), Ok(expected)); + let old = write( + "old.json", + serde_json::json!({ "chainId": 7, "satinTime": 0, "satinInitialAdmin": "0x33" }), + ); + let error = parse_genesis(&old).unwrap_err(); + assert!( + error.contains("`satinInitialAdmin` is not a Satin chain-configuration key"), + "{error}" + ); + assert!(parse_genesis(dir.path().join("absent").to_str().unwrap()) + .unwrap_err() + .contains("reading")); + } + + /// The flag takes an object inline or from a file, and nothing but an object. + #[test] + fn test_the_override_parses_inline_or_from_a_file() { + let inline = r#" {"blockTxsDataLimit": 7}"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("limits.json"); + std::fs::write(&path, inline).unwrap(); + assert_eq!(parse_limits_override(inline), parse_limits_override(path.to_str().unwrap())); + assert!(parse_limits_override("[1]").unwrap_err().contains("must be a JSON object")); + assert!(parse_limits_override("{").unwrap_err().contains("not JSON")); + let missing = dir.path().join("absent.json"); + assert!(parse_limits_override(missing.to_str().unwrap()).unwrap_err().contains("reading")); + } +} diff --git a/bin/mega-evme/src/common/state.rs b/bin/mega-evme/src/common/state.rs index acc655180..cf2f88035 100644 --- a/bin/mega-evme/src/common/state.rs +++ b/bin/mega-evme/src/common/state.rs @@ -3,15 +3,15 @@ use std::{collections::BTreeMap, path::PathBuf, str::FromStr}; use alloy_network::Network; -use alloy_primitives::{map::DefaultHashBuilder, Address, BlockNumber, Bytes, B256, U256}; +use alloy_primitives::{Address, BlockNumber, Bytes, B256, U256}; use alloy_provider::Provider; use clap::Parser; use op_alloy_network::Optimism; -use mega_evm::revm::{ +use revm::{ database::{AlloyDB, CacheDB, EmptyDB, WrapDatabaseAsync}, primitives::HashMap, - state::{Account, AccountInfo, Bytecode, EvmState, EvmStorageSlot}, + state::{Account, AccountInfo, Bytecode, EvmState, EvmStorageSlot, TransactionId}, Database, DatabaseRef, }; use tracing::{debug, info, trace}; @@ -214,8 +214,23 @@ impl PreStateArgs { Ok(entries) } - /// Load prestate as [`EvmState`] from file if provided + /// Load prestate as [`EvmState`] from file if provided. + /// + /// Balance, storage, sender and faucet overrides that name an account the file already holds + /// are applied to that account. Overrides of any other account are not inserted here: a + /// default account would hide the rest of a forked account. [`Self::create_initial_state`] + /// applies those as field overlays on top of the backend. pub fn load_prestate(&self, sender: &Address) -> Result { + let PreparedPrestate { mut accounts, overlays, .. } = self.prepare_prestate(sender)?; + for (address, overlay) in overlays { + overlay.apply_to(accounts.entry(address).or_default(), address)?; + } + Ok(accounts) + } + + /// The file accounts with the overrides that name them applied, and the overrides split by + /// whether the file holds the account. + fn prepare_prestate(&self, sender: &Address) -> Result { let mut prestate = if let Some(pre_state_path) = &self.prestate { info!(prestate_path = ?pre_state_path, "Loading prestate from file"); let prestate_content = std::fs::read_to_string(pre_state_path)?; @@ -224,10 +239,8 @@ impl PreStateArgs { EvmeError::InvalidInput(format!("Failed to parse prestate JSON: {}", e)) })?; trace!(loaded_prestate = ?loaded_prestate, "Prestate loaded from file"); - let mut prestate = EvmState::with_capacity_and_hasher( - loaded_prestate.len(), - DefaultHashBuilder::default(), - ); + let mut prestate = + EvmState::with_capacity_and_hasher(loaded_prestate.len(), Default::default()); for (address, account_state) in loaded_prestate { let account = account_state.into_account()?; prestate.insert(address, account); @@ -238,37 +251,32 @@ impl PreStateArgs { debug!("No prestate file provided"); HashMap::default() }; + let mut overrides: HashMap = HashMap::default(); - // Apply balance overrides for (address, balance) in self.parse_balance()? { info!(address = %address, balance = %balance, "Overriding balance"); - prestate.entry(address).or_default().info.balance = balance; + set_balance_override(&mut prestate, &mut overrides, address, balance); } - // Apply storage overrides for (address, slot, value) in self.parse_storage()? { info!(address = %address, slot = %slot, value = %value, "Overriding storage"); - prestate - .entry(address) - .or_default() - .storage - .insert(slot, EvmStorageSlot::new(value, 0)); + set_storage_override(&mut prestate, &mut overrides, address, slot, value); } - // Set balance for the sender if specified (overrides prestate) if let Some(sender_balance_str) = &self.sender_balance { let sender_balance = parse_ether_value(sender_balance_str)?; info!(sender = %sender, sender_balance = %sender_balance, "Overriding sender balance"); - prestate.entry(*sender).or_default().info.set_balance(sender_balance); + set_balance_override(&mut prestate, &mut overrides, *sender, sender_balance); } - // Apply faucet balances for (address, balance) in self.parse_faucet()? { info!(address = %address, balance = %balance, "Faucet: adding balance"); - prestate.entry(address).or_default().info.balance += balance; + add_faucet(&mut prestate, &mut overrides, address, balance)?; } - Ok(prestate) + let (file_overrides, overlays) = + overrides.into_iter().partition(|(address, _)| prestate.contains_key(address)); + Ok(PreparedPrestate { accounts: prestate, overlays, file_overrides }) } /// Build the initial execution state and the clean-exit RPC cache store. @@ -282,7 +290,8 @@ impl PreStateArgs { sender: &Address, rpc_args: &super::RpcArgs, ) -> Result<(EvmeState, RpcCacheStore)> { - let prestate = self.load_prestate(sender)?; + let PreparedPrestate { accounts: prestate, overlays, file_overrides } = + self.prepare_prestate(sender)?; let block_hashes = self.parse_block_hashes()?; if self.fork { @@ -299,16 +308,116 @@ impl PreStateArgs { } let super::BuildProviderOutput { provider, cache_store, .. } = rpc_args.build_provider().await?; - let state = + let mut state = EvmeState::new_forked(provider, self.fork_block, prestate, block_hashes).await?; + state.overlays = overlays; + state.file_overrides = file_overrides; Ok((state, cache_store)) } else { debug!("Creating local state"); - Ok((EvmeState::new_empty(prestate, block_hashes), RpcCacheStore::noop())) + if let Some((address, code_hash)) = unloaded_code(&prestate).next() { + return Err(EvmeError::InvalidInput(format!( + "Prestate account {address} has `code: null` and codeHash {code_hash}, and \ + nothing to load its code from: put the code in the prestate file or run \ + with '--fork'" + ))); + } + let mut state = EvmeState::new_empty(prestate, block_hashes); + state.overlays = overlays; + state.file_overrides = file_overrides; + Ok((state, RpcCacheStore::noop())) } } } +/// The prestate file's accounts and the CLI's field overrides, before a state is built from them. +struct PreparedPrestate { + /// The file's accounts, with the overrides that name them applied. + accounts: EvmState, + /// The overrides of accounts the file does not hold. + overlays: HashMap, + /// The overrides of accounts the file holds, as given. + file_overrides: HashMap, +} + +/// The CLI's field overrides of one account. +/// +/// For an account the prestate file does not already hold, applied on read, on top of the backend +/// account or of an entry added to the prestate later, so a balance or one storage slot does not +/// replace the rest of a forked account. +#[derive(Debug, Default, Clone)] +struct AccountOverlay { + /// Replaces the balance when set. Applied before [`Self::faucet`]. + balance: Option, + /// Added to the resolved balance. + faucet: U256, + /// Slots that replace the underlying value. Other slots stay with the account. + storage: HashMap, +} + +impl AccountOverlay { + /// Writes the overrides into `account`: the balance, then the faucet, then the slots. + fn apply_to(&self, account: &mut Account, address: Address) -> Result<()> { + if let Some(balance) = self.balance { + account.info.balance = balance; + } + if !self.faucet.is_zero() { + account.info.balance = checked_faucet(account.info.balance, self.faucet, address)?; + } + account.storage.extend(self.storage.iter().map(|(slot, value)| (*slot, value.clone()))); + Ok(()) + } +} + +/// Records a balance override, and applies it to the account when the file holds it. +fn set_balance_override( + prestate: &mut EvmState, + overrides: &mut HashMap, + address: Address, + balance: U256, +) { + if let Some(account) = prestate.get_mut(&address) { + account.info.balance = balance; + } + overrides.entry(address).or_default().balance = Some(balance); +} + +/// Records a storage override, and applies it to the account when the file holds it. +fn set_storage_override( + prestate: &mut EvmState, + overrides: &mut HashMap, + address: Address, + slot: U256, + value: U256, +) { + let stored = EvmStorageSlot::new(value, TransactionId::ZERO); + if let Some(account) = prestate.get_mut(&address) { + account.storage.insert(slot, stored.clone()); + } + overrides.entry(address).or_default().storage.insert(slot, stored); +} + +/// Records a faucet, and adds it to the account's balance when the file holds it. +fn add_faucet( + prestate: &mut EvmState, + overrides: &mut HashMap, + address: Address, + amount: U256, +) -> Result<()> { + if let Some(account) = prestate.get_mut(&address) { + account.info.balance = checked_faucet(account.info.balance, amount, address)?; + } + let overlay = overrides.entry(address).or_default(); + overlay.faucet = checked_faucet(overlay.faucet, amount, address)?; + Ok(()) +} + +fn checked_faucet(balance: U256, add: U256, address: Address) -> Result { + balance.checked_add(add).ok_or_else(|| { + EvmeError::InvalidInput(format!("Faucet overflows the balance of {address}")) + }) +} + /// State dump configuration arguments #[derive(Parser, Debug, Clone)] #[command(next_help_heading = "State Dump Options")] @@ -411,38 +520,99 @@ impl AccountState { } /// Converts into [`Account`]. + /// + /// Code present in the dump is checked against `code_hash`. + /// Code left out stays unloaded: the stored hash is kept and `code` stays `None`. Empty + /// bytecode is not substituted for it. [`PreStateArgs::create_initial_state`] fetches such an + /// account's code from the fork, or refuses the file when there is no fork. pub fn into_account(self) -> Result { - let code = self.code.unwrap_or_default(); - let bytecode = if code.is_empty() { - Bytecode::default() - } else { - Bytecode::new_raw_checked(code).map_err(EvmeError::InvalidBytecode)? - }; - let computed_hash = bytecode.hash_slow(); - if let Some(code_hash) = self.code_hash { - if computed_hash != code_hash { - return Err(EvmeError::CodeHashMismatch { - expected: code_hash, - computed: computed_hash, - }); + let info = match self.code { + Some(code) => { + let bytecode = if code.is_empty() { + Bytecode::default() + } else { + Bytecode::new_raw_checked(code).map_err(EvmeError::InvalidBytecode)? + }; + let computed_hash = bytecode.hash_slow(); + if let Some(code_hash) = self.code_hash { + if computed_hash != code_hash { + return Err(EvmeError::CodeHashMismatch { + expected: code_hash, + computed: computed_hash, + }); + } + } + AccountInfo::new( + self.balance.unwrap_or_default(), + self.nonce.unwrap_or_default(), + computed_hash, + bytecode, + ) } - } - - let info = AccountInfo::new( - self.balance.unwrap_or_default(), - self.nonce.unwrap_or_default(), - computed_hash, - bytecode, - ); + None => AccountInfo { + balance: self.balance.unwrap_or_default(), + nonce: self.nonce.unwrap_or_default(), + code_hash: self.code_hash.unwrap_or(revm::primitives::KECCAK_EMPTY), + account_id: None, + code: None, + }, + }; let storage = self .storage .unwrap_or_default() .into_iter() - .map(|(slot, value)| (slot, EvmStorageSlot::new(value, 0))); + .map(|(slot, value)| (slot, EvmStorageSlot::new(value, TransactionId::ZERO))); Ok(Account::from(info).with_storage(storage)) } } +/// The accounts of `prestate` that name their code by hash only: `code: null` in the file, with a +/// hash that is not the empty code's. +fn unloaded_code(prestate: &EvmState) -> impl Iterator + '_ { + prestate.iter().filter_map(|(address, account)| { + (account.info.code.is_none() && account.info.code_hash != revm::primitives::KECCAK_EMPTY) + .then_some((*address, account.info.code_hash)) + }) +} + +/// Fills bytecode into journal accounts that were loaded without it. +/// +/// A dump records `code: null` together with the account's hash when the code was never fetched. +/// Loading it here, while the database is still open, puts the bytes in the dump so a later run +/// can execute them without that database. The bytes come from `basic_ref`. A hash that does not +/// match is left unloaded. +pub(crate) fn materialize_dumped_code( + db: &DB, + state: &mut EvmState, +) -> std::result::Result<(), DB::Error> { + for (address, account) in state.iter_mut() { + if account.info.code.is_some() || account.info.code_hash == revm::primitives::KECCAK_EMPTY { + continue; + } + let Some(info) = db.basic_ref(*address)? else { + continue; + }; + if info.code_hash != account.info.code_hash { + continue; + } + if let Some(code) = info.code { + account.info.code = Some(code); + } + } + Ok(()) +} + +/// Whether an account an RPC endpoint reported is one that does not exist. +/// +/// JSON-RPC cannot say "no such account": `eth_getBalance`, `eth_getTransactionCount` and +/// `eth_getCode` answer zeros for it. A node's database answers `None`, and the difference is +/// observable (EIP-7702 refunds an authorization whose authority already exists), so an all-zero +/// answer is read as absent. An existing account that is empty cannot occur on a chain that has +/// had EIP-161 from genesis, as every `MegaETH` chain has. +fn rpc_reads_as_absent(info: &AccountInfo) -> bool { + info.balance.is_zero() && info.nonce == 0 && info.code_hash == revm::primitives::KECCAK_EMPTY +} + /// Backend database type with generic provider and network #[derive(Debug)] enum EvmeBackend @@ -467,6 +637,12 @@ where backend: EvmeBackend, /// Prestate overrides (accounts that override the database) prestate: EvmState, + /// Field overrides for accounts the prestate file does not hold. Applied on top of the + /// backend so one named field does not hide the rest of a forked account. + overlays: HashMap, + /// Field overrides for accounts the prestate file holds, already applied to them: kept to be + /// applied again to an account that replaces one of them, a local predeploy's. + file_overrides: HashMap, /// Code hash to bytecode map (extracted from prestate accounts) code_map: HashMap, /// Block hash overrides (block number -> block hash) @@ -488,43 +664,14 @@ where }) .collect(); - Self { backend: EvmeBackend::Empty(EmptyDB::default()), prestate, code_map, block_hashes } - } - - /// Inserts an account override - /// This will override the existing account if it exists. - pub fn insert_account(&mut self, address: Address, account: Account) { - // Add code to code_map if present - if let Some(ref code) = account.info.code { - self.code_map.insert(account.info.code_hash, code.clone()); - } - self.prestate.insert(address, account); - } - - /// Inserts storage overrides for an account - pub fn insert_storage(&mut self, address: Address, storage: HashMap) { - self.prestate.entry(address).or_default().storage.extend(storage); - } - - /// Inserts an account with storage. - /// This will override the existing account if it exists. - pub fn insert_account_with_storage( - &mut self, - address: Address, - info: AccountInfo, - storage: HashMap, - ) { - // Add code to code_map if present - if let Some(ref code) = info.code { - self.code_map.insert(info.code_hash, code.clone()); + Self { + backend: EvmeBackend::Empty(EmptyDB::default()), + prestate, + overlays: HashMap::default(), + file_overrides: HashMap::default(), + code_map, + block_hashes, } - let account = Account::from(info).with_storage(storage.into_iter()); - self.prestate.insert(address, account); - } - - /// Set the balance for an account. - pub fn set_account_balance(&mut self, address: Address, balance: U256) { - self.prestate.entry(address).or_default().info.balance = balance; } /// Set the nonce for an account. @@ -538,42 +685,112 @@ where self.prestate.entry(address).or_default().info.set_code(code); } - /// Set the storage for an account. - pub fn set_account_storage(&mut self, address: Address, storage: HashMap) { - self.prestate - .entry(address) - .or_default() - .storage - .extend(storage.into_iter().map(|(slot, value)| (slot, EvmStorageSlot::new(value, 0)))); + /// Puts Satin's predeploys, the six system contracts and the EIP-7997 factory, where the state + /// lacks the code Satin expects. + /// + /// `run` and `tx` execute no block, and a chain Satin runs on holds the predeploys, so an + /// address that already holds the expected code is left as it is: a forked state keeps the + /// chain's account, nonce and storage. Elsewhere a forked state gets the code alone, its + /// account otherwise as the chain holds it; a local state gets the account a chain that ran + /// Rex6 holds ([`rex6_predeploys`](mega_evm::test_utils::rex6_predeploys)): the six at nonce + /// 0, the factory at a nonzero nonce, and the `SequencerRegistry` naming + /// [`MEGA_SYSTEM_ADDRESS`](mega_evm::system::MEGA_SYSTEM_ADDRESS) in every role. + /// + /// The CLI's balance, faucet and storage overrides hold over the account installed, whether + /// or not the prestate file held an account at the address. + /// + /// # Errors + /// + /// When a forked state cannot load one of the accounts. + pub fn deploy_system_contracts(&mut self) -> Result<()> { + use mega_evm::{system::MEGA_SYSTEM_ADDRESS, test_utils::rex6_predeploys}; + + let local = matches!(self.backend, EvmeBackend::Empty(_)); + for (address, rex6, storage) in rex6_predeploys(MEGA_SYSTEM_ADDRESS) { + let held = self.basic_without_overlay(address)?; + if held.as_ref().is_some_and(|info| info.code_hash == rex6.code_hash) { + continue; + } + let code = rex6.code.clone().expect("a predeploy carries its code"); + let account = self.prestate.entry(address).or_default(); + if local { + account.info = rex6; + account.storage.extend( + storage.into_iter().map(|(slot, value)| { + (slot, EvmStorageSlot::new(value, TransactionId::ZERO)) + }), + ); + // This replaces the account the file held here, if any, which had the overrides + // naming it applied; they hold over the replacement, as the overlay of an address + // the file does not hold holds over it on read. + if let Some(overrides) = self.file_overrides.get(&address) { + overrides.apply_to(account, address)?; + } + } else { + // A forked state keeps the account it held, the file's with its overrides + // included. + account.info = held.unwrap_or_default(); + } + self.set_account_code(address, code); + } + Ok(()) } - /// Deploys system contracts based on the given spec. - pub fn deploy_system_contracts(&mut self, spec: mega_evm::MegaSpecId) { - use mega_evm::{ - flat_system_contract_specs, MegaSpecId, SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_REX6, - }; + /// The account at `address` as the prestate or the backend holds it, before any field + /// overlay. + fn basic_without_overlay(&mut self, address: Address) -> Result> { + if let Some(account) = self.prestate.get(&address) { + trace!(address = %address, account = ?account, "Loaded account basic from prestate"); + return Ok(Some(account.info.clone())); + } + Ok(match &mut self.backend { + EvmeBackend::Empty(db) => { + let account = db.basic(address).unwrap(); + trace!(address = %address, account = ?account, "Loaded account basic from empty state"); + account + } + EvmeBackend::Forked(db) => { + let account = db.basic(address).map_err(|e| { + EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) + })?; + trace!(address = %address, account = ?account, "Loaded account basic from forked state"); + account.filter(|info| !rpc_reads_as_absent(info)) + } + }) + } - // Flat predeploys (Oracle, high-precision timestamp Oracle, KeylessDeploy, - // MegaAccessControl, MegaLimitControl) come from the canonical registry shared - // with the block executor. mega-evme runs with a fixed spec, so activations are - // resolved via a `FixedHardfork` at timestamp 0, and the bytecode is applied as a - // raw state patch (no witness / storage seeding needed for local execution). - for contract in flat_system_contract_specs(super::FixedHardfork::new(spec), 0) { - self.set_account_code(contract.address, Bytecode::new_raw(contract.code)); - } - - // Rex5+: SequencerRegistry (v1.0.0 pre-Rex6, v2.0.0 from Rex6). Only the bytecode - // is installed here — a local run has no chain-config sequencer/admin to seed (the - // registry's storage is otherwise read from forked state). - if spec.reaches(MegaSpecId::REX5) { - let code = if spec.reaches(MegaSpecId::REX6) { - SEQUENCER_REGISTRY_CODE_REX6 - } else { - SEQUENCER_REGISTRY_CODE - }; - self.set_account_code(SEQUENCER_REGISTRY_ADDRESS, Bytecode::new_raw(code)); + /// Replaces the balance and adds the faucet on top of `info`. A storage-only overlay leaves + /// the account as the backend reported it. + fn apply_account_overlay( + &self, + address: Address, + info: Option, + ) -> Result> { + let Some(overlay) = self.overlays.get(&address) else { + return Ok(info); + }; + if overlay.balance.is_none() && overlay.faucet.is_zero() { + return Ok(info); } + let mut info = info.unwrap_or_default(); + if let Some(balance) = overlay.balance { + info.balance = balance; + } + if !overlay.faucet.is_zero() { + info.balance = checked_faucet(info.balance, overlay.faucet, address)?; + } + Ok(Some(info)) + } + + /// The overridden value of one slot, when this address has a field overlay for it. + fn overlay_slot(&self, address: Address, index: U256) -> Option { + self.overlays + .get(&address) + .and_then(|overlay| overlay.storage.get(&index)) + .map(|slot| { + trace!(address = %address, index = %index, slot = %slot.present_value, "Loaded storage from field overlay"); + slot.present_value + }) } } @@ -614,14 +831,41 @@ where let db = CacheDB::new(wrapped_db); // Extract code hash → bytecode mappings from prestate - let code_map: HashMap<_, _> = prestate + let mut code_map: HashMap<_, _> = prestate .values() .filter_map(|account| { account.info.code.clone().map(|code| (account.info.code_hash, code)) }) .collect(); - Ok(Self { backend: EvmeBackend::Forked(Box::new(db)), prestate, code_map, block_hashes }) + // An account the file names by code hash only keeps its entry, and its code is fetched + // from the fork here: the fork's database cannot serve a code hash on its own, and the + // prestate entry hides the account from the fork's cache. + for (address, code_hash) in unloaded_code(&prestate) { + let fetched = db + .basic_ref(address) + .map_err(|e| { + EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) + })? + .filter(|info| info.code_hash == code_hash) + .and_then(|info| info.code); + let Some(code) = fetched else { + return Err(EvmeError::InvalidInput(format!( + "Prestate account {address} has `code: null` and codeHash {code_hash}, but \ + the fork holds no code with that hash at the account" + ))); + }; + code_map.insert(code_hash, code); + } + + Ok(Self { + backend: EvmeBackend::Forked(Box::new(db)), + prestate, + overlays: HashMap::default(), + file_overrides: HashMap::default(), + code_map, + block_hashes, + }) } } @@ -633,27 +877,11 @@ where type Error = EvmeError; fn basic(&mut self, address: Address) -> std::result::Result, Self::Error> { - // Check prestate overrides first - if let Some(account) = self.prestate.get(&address) { - trace!(address = %address, account = ?account, "Loaded account basic from prestate"); - return Ok(Some(account.info.clone())); - } - - // Query backend database - match &mut self.backend { - EvmeBackend::Empty(db) => { - let account = db.basic(address).unwrap(); - trace!(address = %address, account = ?account, "Loaded account basic from empty state"); - Ok(account) - } - EvmeBackend::Forked(db) => { - let account = db.basic(address).map_err(|e| { - EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) - })?; - trace!(address = %address, account = ?account, "Loaded account basic from forked state"); - Ok(account) - } - } + // Prestate overrides first, then the backend. An overlay applies on top of an entry too: + // `run` and `tx` add entries (the receiver's code, the predeploys) after the overlays were + // taken. + let account = self.basic_without_overlay(address)?; + self.apply_account_overlay(address, account) } fn code_by_hash( @@ -687,6 +915,9 @@ where } fn storage(&mut self, address: Address, index: U256) -> std::result::Result { + if let Some(value) = self.overlay_slot(address, index) { + return Ok(value); + } // Check storage overrides first if let Some(account) = self.prestate.get(&address) { if let Some(slot) = account.storage.get(&index) { @@ -754,27 +985,34 @@ where type Error = EvmeError; fn basic_ref(&self, address: Address) -> std::result::Result, Self::Error> { - // Check prestate overrides first + // Check prestate overrides first; the overlay applies as it does in `basic`. + // This read is for a consumer that wants the account whole (a state dump), so it carries + // the code of an account the file names by hash only. if let Some(account) = self.prestate.get(&address) { trace!(address = %address, account = ?account, "Loaded account basic from prestate"); - return Ok(Some(account.info.clone())); + let mut info = account.info.clone(); + if info.code.is_none() { + info.code = self.code_map.get(&info.code_hash).cloned(); + } + return self.apply_account_overlay(address, Some(info)); } // Query backend database - match &self.backend { + let account = match &self.backend { EvmeBackend::Empty(db) => { let account = db.basic_ref(address).unwrap(); trace!(address = %address, account = ?account, "Loaded account basic from empty state"); - Ok(account) + account } EvmeBackend::Forked(db) => { let account = db.basic_ref(address).map_err(|e| { EvmeError::RpcError(format!("Failed to fetch account {}: {:?}", address, e)) })?; trace!(address = %address, account = ?account, "Loaded account basic from forked state"); - Ok(account) + account.filter(|info| !rpc_reads_as_absent(info)) } - } + }; + self.apply_account_overlay(address, account) } fn code_by_hash_ref( @@ -808,6 +1046,9 @@ where } fn storage_ref(&self, address: Address, index: U256) -> std::result::Result { + if let Some(value) = self.overlay_slot(address, index) { + return Ok(value); + } // Check storage overrides first if let Some(account) = self.prestate.get(&address) { if let Some(slot) = account.storage.get(&index) { @@ -866,3 +1107,51 @@ where } } } + +#[cfg(test)] +mod tests { + use alloy_provider::DynProvider; + use op_alloy_network::Optimism; + + use super::*; + + fn lazy_account(hash: B256) -> Account { + Account::from(AccountInfo { + balance: U256::from(5u64), + nonce: 3, + code_hash: hash, + account_id: None, + code: None, + }) + } + + #[test] + fn test_lazy_code_reload_keeps_the_hash() { + let hash = B256::repeat_byte(0xab); + let loaded = AccountState::from_account(lazy_account(hash)).into_account().unwrap(); + assert!(loaded.info.code.is_none()); + assert_eq!(loaded.info.code_hash, hash); + assert_eq!(loaded.info.balance, U256::from(5u64)); + assert_eq!(loaded.info.nonce, 3); + } + + #[test] + fn test_dump_loads_unfetched_code() { + let bytecode = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00, 0x56])); + let hash = bytecode.hash_slow(); + let address = Address::repeat_byte(0x11); + let mut db: EvmeState> = + EvmeState::new_empty(EvmState::default(), HashMap::default()); + db.set_account_code(address, bytecode.clone()); + + let mut state = EvmState::default(); + state.insert(address, lazy_account(hash)); + let other = Address::repeat_byte(0x22); + state.insert(other, lazy_account(B256::repeat_byte(0xcd))); + + materialize_dumped_code(&db, &mut state).unwrap(); + + assert_eq!(state.get(&address).unwrap().info.code.as_ref(), Some(&bytecode)); + assert!(state.get(&other).unwrap().info.code.is_none()); + } +} diff --git a/bin/mega-evme/src/common/trace.rs b/bin/mega-evme/src/common/trace.rs index 0086f07e4..f0ac83825 100644 --- a/bin/mega-evme/src/common/trace.rs +++ b/bin/mega-evme/src/common/trace.rs @@ -9,20 +9,16 @@ use alloy_rpc_types_trace::geth::{ use clap::{Parser, ValueEnum}; use mega_evm::{ revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - ContextTr, - }, + context::result::{ExecutionResult, ResultAndState}, database::DatabaseRef, state::EvmState, - ExecuteEvm, InspectEvm, }, MegaContext, MegaEvm, MegaHaltReason, MegaTransaction, }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use tracing::{debug, info, trace}; -use super::{EvmeError, EvmeExternalEnvs, EvmeState}; +use super::{EvmeError, EvmeExternalEnvs, EvmeState, SatinReport}; /// Tracer type for execution analysis #[derive(Debug, Clone, Copy, ValueEnum, Default)] @@ -97,10 +93,32 @@ impl TraceArgs { self.trace } - /// Creates a [`TracingInspector`] configured for full tracing + /// Creates a [`TracingInspector`] that records what this tracer and its flags ask for. + /// + /// The opcode flags turn memory, stack, storage and return data on or off here. A call trace + /// records logs only with `--trace.call.with-log`. A pre-state trace is rendered from the + /// execution result, so its inspector records nothing. pub fn create_inspector(&self) -> TracingInspector { - let config = TracingInspectorConfig::all(); - TracingInspector::new(config) + TracingInspector::new(self.inspector_config()) + } + + /// The inspector config for [`Self::tracer`] and the flags that apply to it. + fn inspector_config(&self) -> TracingInspectorConfig { + match self.tracer { + TracerType::Opcode => { + let mut options = self.create_geth_options(); + // `from_geth_config` reads `enable_memory`. The flag is disable-memory, and memory + // is on unless that flag is set. + options.enable_memory = Some(!self.trace_opcode_disable_memory); + TracingInspectorConfig::from_geth_config(&options) + } + TracerType::Call => { + TracingInspectorConfig::from_geth_call_config(&self.create_call_config()) + } + TracerType::PreState => { + TracingInspectorConfig::from_geth_prestate_config(&self.create_prestate_config()) + } + } } /// Creates [`GethDefaultTracingOptions`] from CLI arguments @@ -150,7 +168,7 @@ impl TraceArgs { // Generate the geth trace let geth_trace = - geth_builder.geth_traces(exec_result.gas_used(), Bytes::from(output), opts); + geth_builder.geth_traces(exec_result.tx_gas_used(), Bytes::from(output), opts); // Format as JSON serde_json::to_string_pretty(&geth_trace) @@ -168,7 +186,8 @@ impl TraceArgs { debug!(config = ?config, "Generating call trace"); // Generate the call trace - let call_frame: CallFrame = geth_builder.geth_call_traces(config, exec_result.gas_used()); + let call_frame: CallFrame = + geth_builder.geth_call_traces(config, exec_result.tx_gas_used()); // Format as JSON serde_json::to_string_pretty(&call_frame) @@ -213,11 +232,12 @@ impl TraceArgs { } /// Execute transaction with optional tracing + #[allow(clippy::type_complexity)] pub fn execute_transaction( &self, evm_context: MegaContext<&mut EvmeState, EvmeExternalEnvs>, tx: MegaTransaction, - ) -> Result<(ExecutionResult, EvmState, Option), EvmeError> + ) -> Result<(ExecutionResult, EvmState, Option, SatinReport), EvmeError> where N: alloy_network::Network, P: alloy_provider::Provider + std::fmt::Debug, @@ -228,26 +248,92 @@ impl TraceArgs { let mut inspector = self.create_inspector(); let mut evm = MegaEvm::new(evm_context).with_inspector(&mut inspector); - let result_and_state = evm - .inspect_tx(tx) + let outcome = evm + .execute_transaction(tx) .map_err(|e| EvmeError::ExecutionError(format!("EVM execution failed: {:?}", e)))?; - trace!(result_and_state = ?result_and_state, "Evm execution result and state"); + trace!(outcome = ?outcome, "Evm execution outcome"); + let satin = SatinReport::of(&outcome); // Generate trace string based on tracer type - let trace_str = self.generate_trace(evm.inspector, &result_and_state, evm.db_ref()); + let trace_str = { + use mega_evm::alloy_evm::Evm as _; + let db = evm.db(); + self.generate_trace(evm.inspector(), &outcome.result_and_state, db) + }; trace!(trace_str = ?trace_str, "Generated trace"); - Ok((result_and_state.result, result_and_state.state, Some(trace_str))) + let ResultAndState { result, state } = outcome.result_and_state; + Ok((result, state, Some(trace_str), satin)) } else { info!("Evm executing without tracing"); // Execute without tracing let mut evm = MegaEvm::new(evm_context); - let result_and_state = evm - .transact(tx) + let outcome = evm + .execute_transaction(tx) .map_err(|e| EvmeError::ExecutionError(format!("EVM execution failed: {:?}", e)))?; - trace!(result_and_state = ?result_and_state, "Evm execution result and state"); + trace!(outcome = ?outcome, "Evm execution outcome"); + let satin = SatinReport::of(&outcome); - Ok((result_and_state.result, result_and_state.state, None)) + let ResultAndState { result, state } = outcome.result_and_state; + Ok((result, state, None, satin)) } } } + +#[cfg(test)] +mod tests { + use revm_inspectors::tracing::StackSnapshotType; + + use super::*; + + fn args(flags: &[&str]) -> TraceArgs { + let mut cmd = vec!["mega-evme"]; + cmd.extend_from_slice(flags); + TraceArgs::try_parse_from(cmd).expect("flags parse") + } + + #[test] + fn test_an_opcode_trace_records_what_its_flags_leave_on() { + let config = *args(&[]).create_inspector().config(); + assert!(config.record_steps); + assert!(config.record_memory_snapshots); + assert_eq!(config.record_stack_snapshots, StackSnapshotType::Full); + assert!(config.record_state_diff); + assert!(!config.record_returndata_snapshots); + + let disabled = *args(&[ + "--trace.opcode.disable-memory", + "--trace.opcode.disable-stack", + "--trace.opcode.disable-storage", + ]) + .create_inspector() + .config(); + assert!(!disabled.record_memory_snapshots); + assert_eq!(disabled.record_stack_snapshots, StackSnapshotType::None); + assert!(!disabled.record_state_diff); + + let with_return = *args(&["--trace.opcode.enable-return-data"]).create_inspector().config(); + assert!(with_return.record_returndata_snapshots); + } + + #[test] + fn test_a_call_trace_records_logs_only_when_asked() { + let plain = *args(&["--tracer", "call"]).create_inspector().config(); + assert!(!plain.record_steps); + assert!(!plain.record_logs); + + let with_log = + *args(&["--tracer", "call", "--trace.call.with-log"]).create_inspector().config(); + assert!(with_log.record_logs); + assert!(!with_log.record_steps); + } + + #[test] + fn test_a_prestate_trace_records_nothing() { + let config = *args(&["--tracer", "prestate"]).create_inspector().config(); + assert!(!config.record_steps); + assert!(!config.record_memory_snapshots); + assert!(!config.record_state_diff); + assert!(!config.record_logs); + } +} diff --git a/bin/mega-evme/src/common/tx.rs b/bin/mega-evme/src/common/tx.rs index ca8de9968..cec0ea01e 100644 --- a/bin/mega-evme/src/common/tx.rs +++ b/bin/mega-evme/src/common/tx.rs @@ -1,5 +1,10 @@ //! Transaction configuration for mega-evme +use alloy_eips::{ + eip2930::{AccessList, AccessListItem}, + eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization}, + Decodable2718, Encodable2718, Typed2718 as _, +}; use alloy_primitives::{address, Address, Bytes, Signature, B256, U256}; use clap::Args; use mega_evm::{ @@ -7,15 +12,14 @@ use mega_evm::{ transaction::SignerRecoverable, Sealed, Signed, Transaction as _, TxEip1559, TxEip2930, TxEip7702, TxLegacy, }, - alloy_eips::{ - eip2930::{AccessList, AccessListItem}, - eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization}, - Decodable2718, Encodable2718, Typed2718 as _, - }, + alloy_op_evm::OpTx, op_alloy_consensus::{OpTxEnvelope, TxDeposit}, - op_revm::transaction::deposit::DepositTransactionParts, - revm::{context::tx::TxEnv, primitives::TxKind}, - Either, MegaTransaction, MegaTxEnvelope, MegaTxType, + op_revm::{transaction::deposit::DepositTransactionParts, OpTransaction}, + revm::{ + context::{either::Either, tx::TxEnv}, + primitives::TxKind, + }, + MegaTransaction, MegaTxEnvelope, MegaTxType, }; use tracing::{debug, trace}; @@ -347,8 +351,9 @@ impl TxArgs { /// Loads input data from `--input` or `--inputfile` arguments. pub fn create_tx(&self, chain_id: u64) -> Result { let tx_env = self.create_tx_env(chain_id)?; - let envelope = create_fake_envelope(&tx_env)?; - let mut tx = MegaTransaction::new(tx_env); + let envelope = + create_fake_envelope(&tx_env, self.source_hash.unwrap_or(B256::ZERO), self.mint)?; + let mut tx = OpTx(OpTransaction::new(tx_env)); tx.enveloped_tx = Some(Bytes::from(envelope.encoded_2718())); // Set deposit fields if this is a deposit transaction (type 126) @@ -362,6 +367,18 @@ impl TxArgs { Ok(tx) } + + /// The hash of the transaction [`Self::create_tx`] builds, when it has one. + /// + /// A deposit is unsigned, so the hash of its encoding is its hash. Any other type would be + /// signed, and the tool signs nothing: the encoding it builds carries a placeholder signature + /// and hashes to no transaction, so there is none. + pub fn tx_hash(&self, tx: &MegaTransaction) -> Option { + if !matches!(MegaTxType::try_from(tx.base.tx_type), Ok(MegaTxType::Deposit)) { + return None; + } + tx.enveloped_tx.as_ref().map(alloy_primitives::keccak256) + } } /// Result of decoding a raw EIP-2718 transaction. @@ -374,6 +391,8 @@ pub struct DecodedRawTx { /// Deposit-specific fields, if this is a deposit transaction. /// `(source_hash, mint, is_system_transaction)` pub deposit: Option<(B256, Option, bool)>, + /// Whether an override changed the transaction from the one the bytes encode. + pub overridden: bool, } impl DecodedRawTx { @@ -397,14 +416,14 @@ impl DecodedRawTx { }); let decoded_chain_id = envelope.chain_id(); - let (gas_price, gas_priority_fee) = match envelope { + let (gas_price, gas_priority_fee) = match &envelope { OpTxEnvelope::Legacy(_) | OpTxEnvelope::Eip2930(_) => { (envelope.gas_price().unwrap_or(0), None) } OpTxEnvelope::Eip1559(_) | OpTxEnvelope::Eip7702(_) => { (envelope.max_fee_per_gas(), envelope.max_priority_fee_per_gas()) } - OpTxEnvelope::Deposit(_) => (0, None), + OpTxEnvelope::Deposit(_) | OpTxEnvelope::PostExec(_) => (0, None), }; let authorization_list = envelope @@ -429,7 +448,7 @@ impl DecodedRawTx { chain_id: decoded_chain_id, }; - Ok(Self { tx_env, raw_bytes, deposit }) + Ok(Self { tx_env, raw_bytes, deposit, overridden: false }) } /// Applies explicitly-set [`TxArgs`] fields as overrides to the decoded [`TxEnv`]. @@ -437,8 +456,10 @@ impl DecodedRawTx { /// Only fields that were explicitly provided via CLI flags are overridden; /// `None` / empty fields in `tx_args` leave the base value unchanged. pub fn override_tx_env(mut self, tx_args: &TxArgs) -> Result { + let decoded = (self.tx_env.clone(), self.deposit); if let Some(tx_type) = tx_args.tx_type { self.tx_env.tx_type = tx_type; + self.drop_fields_the_type_cannot_carry(); } if let Some(gas) = tx_args.gas { self.tx_env.gas_limit = gas; @@ -486,14 +507,106 @@ impl DecodedRawTx { *mint = tx_args.mint; } } + self.reject_inconsistent_override(tx_args)?; + self.overridden |= decoded != (self.tx_env.clone(), self.deposit); Ok(self) } + /// The hash of the transaction that runs: the hash of the signed bytes, or none once an + /// override changed what they encode. + pub fn tx_hash(&self) -> Option { + (!self.overridden).then(|| alloy_primitives::keccak256(&self.raw_bytes)) + } + + /// Drops what the raw transaction carries and its new type cannot: the priority fee of a type + /// without one, the access list of a type without one, the authorization list of a type that + /// is not EIP-7702. Changing only the type then runs the transaction as that type, with what + /// it can carry. Fields given by a flag are set after this, so a flag that names one of them + /// for a type that cannot carry it is still refused. + fn drop_fields_the_type_cannot_carry(&mut self) { + let Ok(tx_type) = MegaTxType::try_from(self.tx_env.tx_type) else { return }; + if matches!(tx_type, MegaTxType::Legacy | MegaTxType::Eip2930) { + self.tx_env.gas_priority_fee = None; + } + if !matches!(tx_type, MegaTxType::Eip2930 | MegaTxType::Eip1559 | MegaTxType::Eip7702) { + self.tx_env.access_list = Default::default(); + } + if tx_type != MegaTxType::Eip7702 { + self.tx_env.authorization_list.clear(); + } + } + + /// Rejects a type and field combination [`TxArgs::validate`] would reject. + /// + /// The check reads the transaction after the override, with what the old type carried and the + /// new one cannot already dropped, so what it finds comes from a flag. It does not require + /// `--receiver`: a raw transaction already has its own destination. Setting `--tx-type 126` + /// does not fill deposit fields, so a raw transaction that is not a deposit cannot become + /// one. + fn reject_inconsistent_override(&self, tx_args: &TxArgs) -> Result<()> { + let tx_type = MegaTxType::try_from(self.tx_env.tx_type) + .map_err(|_| EvmeError::UnsupportedTxType(self.tx_env.tx_type))?; + + if tx_args.create() && tx_args.receiver.is_some() { + return Err(EvmeError::InvalidInput( + "--receiver must not be set when --create is specified".to_string(), + )); + } + + let deposit_flags = tx_args.source_hash.is_some() || tx_args.mint.is_some(); + if tx_type == MegaTxType::Deposit && self.deposit.is_none() { + return Err(EvmeError::InvalidInput( + "--tx-type 126 does not make a raw transaction a deposit; --source-hash is \ + required for deposit transactions and is not applied here" + .to_string(), + )); + } + if tx_type != MegaTxType::Deposit && self.deposit.is_some() { + return Err(EvmeError::InvalidInput(format!( + "the raw transaction is a deposit (type 126), and --tx-type {} would make it \ + another type", + self.tx_env.tx_type + ))); + } + if tx_type != MegaTxType::Deposit && deposit_flags { + return Err(EvmeError::InvalidInput( + "--source-hash and --mint are only valid for deposit transactions (--tx-type 126)" + .to_string(), + )); + } + + if matches!(tx_type, MegaTxType::Legacy | MegaTxType::Eip2930) && + self.tx_env.gas_priority_fee.is_some() + { + return Err(EvmeError::InvalidInput( + "--priority-fee is not valid for legacy (0) or EIP-2930 (1) transactions" + .to_string(), + )); + } + + if tx_type != MegaTxType::Eip7702 && !self.tx_env.authorization_list.is_empty() { + return Err(EvmeError::InvalidInput( + "--auth is only valid for EIP-7702 transactions (--tx-type 4)".to_string(), + )); + } + + if !self.tx_env.access_list.is_empty() && + !matches!(tx_type, MegaTxType::Eip2930 | MegaTxType::Eip1559 | MegaTxType::Eip7702) + { + return Err(EvmeError::InvalidInput( + "--access is only valid for EIP-2930 (1), EIP-1559 (2), or EIP-7702 (4) transactions" + .to_string(), + )); + } + + Ok(()) + } + /// Converts the decoded raw transaction into a [`MegaTransaction`]. /// /// Uses the stored raw bytes for `enveloped_tx` (used in L1 fee calculation). pub fn into_tx(self) -> MegaTransaction { - let mut tx = MegaTransaction::new(self.tx_env); + let mut tx = OpTx(OpTransaction::new(self.tx_env)); tx.enveloped_tx = Some(self.raw_bytes); if let Some((source_hash, mint, is_system_transaction)) = self.deposit { tx.deposit = DepositTransactionParts { source_hash, mint, is_system_transaction }; @@ -506,9 +619,15 @@ impl DecodedRawTx { /// /// The created envelope only contains the information available in [`TxEnv`] and fills many /// fields with placeholder values. The encoded envelope is used for L1 data fee calculation. +/// A deposit has no signature, so its envelope is the transaction itself, with the given +/// `source_hash` and `mint`. /// A dummy signature is used since the CLI doesn't have access to signing keys — the non-zero /// r/s bytes ensure the encoded size is realistic (matching real signed transactions). -fn create_fake_envelope(tx_env: &TxEnv) -> Result { +fn create_fake_envelope( + tx_env: &TxEnv, + source_hash: B256, + mint: Option, +) -> Result { let dummy_sig = Signature::new(U256::from(1u64), U256::from(1u64), false); let chain_id = tx_env.chain_id.unwrap_or(0); let tx_type = MegaTxType::try_from(tx_env.tx_type) @@ -594,10 +713,10 @@ fn create_fake_envelope(tx_env: &TxEnv) -> Result { } MegaTxType::Deposit => { let tx = TxDeposit { - source_hash: B256::ZERO, + source_hash, from: tx_env.caller, to: tx_env.kind, - mint: 0, + mint: mint.unwrap_or(0), value: tx_env.value, gas_limit: tx_env.gas_limit, is_system_transaction: false, @@ -605,5 +724,135 @@ fn create_fake_envelope(tx_env: &TxEnv) -> Result { }; Ok(MegaTxEnvelope::Deposit(Sealed::new_unchecked(tx, B256::ZERO))) } + MegaTxType::PostExec => Err(EvmeError::UnsupportedTxType(tx_env.tx_type)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bare_args() -> TxArgs { + TxArgs { + tx_type: None, + gas: None, + basefee: None, + priority_fee: None, + sender: None, + receiver: None, + nonce: None, + create: None, + value: None, + input: None, + inputfile: None, + source_hash: None, + mint: None, + auth: Vec::new(), + access: Vec::new(), + } + } + + fn legacy_raw() -> DecodedRawTx { + let tx_env = mega_evm::revm::context::tx::TxEnvBuilder::new() + .tx_type(Some(0)) + .build() + .expect("legacy transaction"); + DecodedRawTx { tx_env, raw_bytes: Bytes::new(), deposit: None, overridden: false } + } + + #[test] + fn test_raw_override_rejects_priority_fee_on_legacy() { + let mut args = bare_args(); + args.priority_fee = Some(1); + let err = legacy_raw() + .override_tx_env(&args) + .expect_err("a legacy transaction has no priority fee"); + assert!(matches!(err, EvmeError::InvalidInput(msg) if msg.contains("priority-fee"))); + } + + #[test] + fn test_raw_override_rejects_making_a_deposit() { + let mut args = bare_args(); + args.tx_type = Some(126); + args.source_hash = Some(B256::ZERO); + let err = legacy_raw() + .override_tx_env(&args) + .expect_err("tx-type 126 does not fill deposit fields"); + assert!(matches!(err, EvmeError::InvalidInput(_))); + } + + #[test] + fn test_raw_override_keeps_an_eip1559_priority_fee() { + let tx_env = mega_evm::revm::context::tx::TxEnvBuilder::new() + .tx_type(Some(2)) + .gas_priority_fee(Some(1)) + .build() + .expect("EIP-1559 transaction"); + let decoded = + DecodedRawTx { tx_env, raw_bytes: Bytes::new(), deposit: None, overridden: false } + .override_tx_env(&bare_args()) + .expect("an EIP-1559 transaction may carry a priority fee"); + assert_eq!(decoded.tx_env.tx_type, 2); + assert_eq!(decoded.tx_env.gas_priority_fee, Some(1)); + } + + /// A raw EIP-1559 transaction carrying a priority fee and an access list. + fn eip1559_raw() -> DecodedRawTx { + let item = AccessListItem { address: Address::repeat_byte(0x11), storage_keys: vec![] }; + let tx_env = mega_evm::revm::context::tx::TxEnvBuilder::new() + .tx_type(Some(2)) + .gas_priority_fee(Some(1)) + .access_list(AccessList(vec![item])) + .build() + .expect("EIP-1559 transaction"); + DecodedRawTx { tx_env, raw_bytes: Bytes::new(), deposit: None, overridden: false } + } + + /// Changing only the type of a raw transaction runs it as the new type: what the old type + /// carried and the new one cannot is dropped, and no flag the user did not pass is blamed. + #[test] + fn test_raw_override_of_the_type_alone_drops_what_the_type_cannot_carry() { + for tx_type in [0, 1] { + let mut args = bare_args(); + args.tx_type = Some(tx_type); + let decoded = eip1559_raw() + .override_tx_env(&args) + .unwrap_or_else(|e| panic!("type {tx_type} alone: {e}")); + assert_eq!(decoded.tx_env.tx_type, tx_type); + assert_eq!(decoded.tx_env.gas_priority_fee, None, "type {tx_type}"); + // Type 1 keeps the access list its type carries; type 0 has none. + assert_eq!(decoded.tx_env.access_list.0.len(), usize::from(tx_type == 1)); + } + } + + /// A flag that names a field the new type cannot carry is still refused, and by that flag. + #[test] + fn test_raw_override_refuses_a_flag_the_new_type_cannot_carry() { + let mut args = bare_args(); + args.tx_type = Some(0); + args.priority_fee = Some(2); + let err = eip1559_raw().override_tx_env(&args).expect_err("--priority-fee on type 0"); + assert!(matches!(err, EvmeError::InvalidInput(msg) if msg.contains("--priority-fee"))); + } + + /// A raw deposit cannot change its type, and the refusal names the type flag, not the + /// deposit flags the user did not pass. + #[test] + fn test_raw_override_of_a_deposits_type_names_the_type_flag() { + let tx_env = mega_evm::revm::context::tx::TxEnvBuilder::new() + .tx_type(Some(126)) + .build() + .expect("deposit"); + let decoded = DecodedRawTx { + tx_env, + raw_bytes: Bytes::new(), + deposit: Some((B256::ZERO, None, false)), + overridden: false, + }; + let mut args = bare_args(); + args.tx_type = Some(2); + let err = decoded.override_tx_env(&args).expect_err("a deposit stays a deposit"); + let EvmeError::InvalidInput(msg) = err else { panic!("{err:?}") }; + assert!(msg.contains("--tx-type 2") && !msg.contains("--source-hash"), "{msg}"); } } diff --git a/bin/mega-evme/src/common/tx_override.rs b/bin/mega-evme/src/common/tx_override.rs index 1ab6d4add..979af4ce8 100644 --- a/bin/mega-evme/src/common/tx_override.rs +++ b/bin/mega-evme/src/common/tx_override.rs @@ -3,23 +3,12 @@ //! This module provides the ability to override transaction fields when replaying //! transactions from RPC. -use std::cell::RefCell; - -use alloy_eips::{Encodable2718, Typed2718}; -use alloy_primitives::{Address, Bytes, TxHash, U256}; +use alloy_primitives::{Bytes, TxHash, U256}; use clap::Args; -use mega_evm::{ - alloy_evm::{IntoTxEnv, RecoveredTx}, - MegaTransaction, MegaTransactionExt, -}; +use mega_evm::{alloy_evm::block::ExecutableTxParts, MegaTransaction, MegaTransactionExt}; use super::{load_hex, parse_ether_value, Result}; -// Thread-local storage for input override (Bytes is not Copy, so we can't store it in TxOverrides) -thread_local! { - static INPUT_OVERRIDE: RefCell> = const { RefCell::new(None) }; -} - /// Transaction override arguments for the replay command. #[derive(Args, Debug, Clone, Default)] #[command(next_help_heading = "Transaction Override Options")] @@ -53,23 +42,14 @@ impl TxOverrideArgs { } /// Wraps a transaction with overrides. - pub fn wrap(&self, tx: T) -> Result> { - // Parse and store input override in thread-local if present - let has_input_override = - if let Some(bytes) = load_hex(self.input.clone(), self.input_file.clone())? { - INPUT_OVERRIDE.with(|cell| cell.borrow_mut().replace(bytes)); - true - } else { - INPUT_OVERRIDE.with(|cell| cell.borrow_mut().take()); - false - }; - + pub fn wrap(&self, tx: T) -> Result> { + let input = load_hex(self.input.clone(), self.input_file.clone())?; Ok(OverriddenTx { inner: tx, overrides: TxOverrides { gas_limit: self.gas_limit, value: self.value.as_deref().map(parse_ether_value).transpose()?, - has_input_override, + input, }, }) } @@ -77,102 +57,129 @@ impl TxOverrideArgs { /// Parsed transaction overrides. /// -/// All fields must be `Copy` because `OverriddenTx` must implement `Copy` -/// (required by block executor's `run_transaction`). The input override is stored -/// in a thread-local (`INPUT_OVERRIDE`) since `Bytes` is not `Copy`. -#[derive(Debug, Clone, Copy, Default)] +/// The input bytes live on this value. Two overrides on one thread keep their own calldata. +#[derive(Debug, Clone, Default)] pub struct TxOverrides { /// Override for gas limit. pub gas_limit: Option, /// Override for value. pub value: Option, - /// Whether input data should be overridden (actual data in thread-local). - pub has_input_override: bool, + /// Override for input data. + pub input: Option, } impl TxOverrides { /// Apply overrides to a [`MegaTransaction`]. - pub fn apply(&self, tx: &mut MegaTransaction) { + pub fn apply(self, tx: &mut MegaTransaction) { if let Some(gas_limit) = self.gas_limit { tx.base.gas_limit = gas_limit; } if let Some(value) = self.value { tx.base.value = value; } - if self.has_input_override { - if let Some(input) = INPUT_OVERRIDE.with(|cell| cell.borrow().clone()) { - tx.base.data = input; - } + if let Some(input) = self.input { + tx.base.data = input; } } } -/// A wrapper that applies overrides when converting to `TxEnv`. +/// A wrapper that applies overrides to the transaction environment the block executor builds. /// -/// This wrapper implements all the required traits by delegating to the inner -/// transaction, but intercepts `IntoTxEnv` to apply overrides. -#[derive(Debug, Clone, Copy)] -pub struct OverriddenTx { +/// Only the environment changes: the recovered transaction, its encoding and so its hash and +/// sizes stay the original's, which is what the executor charges the data-availability size of. +#[derive(Debug, Clone)] +pub struct OverriddenTx { inner: T, overrides: TxOverrides, } -impl OverriddenTx { +impl OverriddenTx { /// Get a reference to the inner transaction. pub fn inner(&self) -> &T { &self.inner } } -// Implement IntoTxEnv - this is where we apply the overrides -impl + Copy> IntoTxEnv for OverriddenTx { - fn into_tx_env(self) -> MegaTransaction { - let mut tx = self.inner.into_tx_env(); +// The block executor builds the environment through `into_parts`; this is where the overrides +// apply. +impl ExecutableTxParts for OverriddenTx +where + T: ExecutableTxParts, +{ + type Recovered = T::Recovered; + + fn into_parts(self) -> (MegaTransaction, Self::Recovered) { + let (mut tx, recovered) = self.inner.into_parts(); self.overrides.apply(&mut tx); - tx + (tx, recovered) } } -// Delegate RecoveredTx to inner -impl + Copy> RecoveredTx for OverriddenTx { - fn tx(&self) -> &Tx { - self.inner.tx() +// Delegate MegaTransactionExt to inner so `OverriddenTx` is accepted by `run_transaction`: the +// hash and the two sizes are the original transaction's. +impl MegaTransactionExt for OverriddenTx { + fn tx_hash(&self) -> TxHash { + self.inner.tx_hash() } - fn signer(&self) -> &Address { - self.inner.signer() + fn tx_size(&self) -> u64 { + self.inner.tx_size() } -} -// Delegate Typed2718 to inner (required as the `Encodable2718` supertrait below). -impl Typed2718 for OverriddenTx { - fn ty(&self) -> u8 { - self.inner.ty() + fn estimated_da_size(&self) -> u64 { + self.inner.estimated_da_size() } } -// Delegate Encodable2718 to inner. Overrides only affect the `TxEnv` produced by `IntoTxEnv`, not -// the EIP-2718 encoding, so the encoded size reflects the original transaction — matching the -// `tx_size`/`da_size` the executor charged before override support existed. -impl Encodable2718 for OverriddenTx { - fn type_flag(&self) -> Option { - self.inner.type_flag() +#[cfg(test)] +mod tests { + use alloy_primitives::{Address, Bytes}; + use mega_evm::{ + alloy_evm::{block::ExecutableTxParts, tx::RecoveredTx}, + alloy_op_evm::OpTx, + op_revm::OpTransaction, + revm::context::tx::TxEnvBuilder, + }; + + use super::*; + + struct EnvOnly(MegaTransaction); + + struct NoRecovered; + + impl ExecutableTxParts for EnvOnly { + type Recovered = NoRecovered; + + fn into_parts(self) -> (MegaTransaction, NoRecovered) { + (self.0, NoRecovered) + } } - fn encode_2718_len(&self) -> usize { - self.inner.encode_2718_len() + impl RecoveredTx<()> for NoRecovered { + fn tx(&self) -> &() { + &() + } + + fn signer(&self) -> &Address { + &Address::ZERO + } } - fn encode_2718(&self, out: &mut dyn alloy_primitives::bytes::BufMut) { - self.inner.encode_2718(out) + fn blank() -> EnvOnly { + let tx_env = TxEnvBuilder::new().tx_type(Some(0)).build().expect("legacy transaction"); + EnvOnly(OpTx(OpTransaction::new(tx_env))) } -} -// Delegate MegaTransactionExt to inner so `OverriddenTx` is accepted by `run_transaction`. -// `tx_size`/`estimated_da_size` fall back to the trait defaults (recomputed from the delegated -// encoding above); only `tx_hash` needs explicit forwarding. -impl MegaTransactionExt for OverriddenTx { - fn tx_hash(&self) -> TxHash { - self.inner.tx_hash() + #[test] + fn test_input_overrides_stay_on_their_wrapper() { + let first = TxOverrideArgs { input: Some("0x11".to_string()), ..TxOverrideArgs::default() }; + let second = + TxOverrideArgs { input: Some("0x22".to_string()), ..TxOverrideArgs::default() }; + let wrapped_first = first.wrap(blank()).expect("first override"); + let wrapped_second = second.wrap(blank()).expect("second override"); + let (tx_first, _) = ExecutableTxParts::::into_parts(wrapped_first); + let (tx_second, _) = ExecutableTxParts::::into_parts(wrapped_second); + assert_eq!(tx_first.base.data, Bytes::from_static(&[0x11])); + assert_eq!(tx_second.base.data, Bytes::from_static(&[0x22])); } } diff --git a/bin/mega-evme/src/engine.rs b/bin/mega-evme/src/engine.rs new file mode 100644 index 000000000..6c3e58415 --- /dev/null +++ b/bin/mega-evme/src/engine.rs @@ -0,0 +1,221 @@ +//! Which engine runs a command, and the hand-off to the legacy one. +//! +//! Every spec name belongs to exactly one engine, so the spec a command runs is the engine it runs +//! on: `Satin` is the Satin engine, `Equivalence` through `Rex6` are the legacy engine. The legacy +//! engine is the released 1.7.1 line, and a command on it runs the released 1.7.1 CLI, so what a +//! legacy spec prints is what the 1.7.1 tool printed. + +use std::ffi::OsString; + +use mega_evm::{ChainActivation, MegaSpecId, ParseMegaSpecError}; + +use crate::common::{chain_activation, EvmeError, Result}; + +/// The spec `run` and `tx` default to: the chain's current spec, on the legacy engine. +pub const DEFAULT_SPEC: &str = "Rex6"; + +/// The engine a command runs on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Engine { + /// The Satin engine, the workspace's `mega-evm`. + Satin, + /// The legacy engine: `mega-evm` 1.7.1 and the `mega-evme` 1.7.1 CLI that drives it. + Legacy, +} + +impl Engine { + /// The engine that runs the spec named `name`. + /// + /// `Rex7` is refused: it exists only on the legacy line, it never activated on a chain, and + /// Satin supersedes it. + pub fn of_spec(name: &str) -> Result { + match name.parse::() { + Ok(_) => Ok(Self::Satin), + Err(ParseMegaSpecError::Legacy(_)) => Ok(Self::Legacy), + Err(ParseMegaSpecError::Unknown) if name == "Rex7" => Err(EvmeError::InvalidInput( + "Rex7 never activated on a chain and Satin supersedes it; use `Satin`, or a spec \ + from `Equivalence` to `Rex6`" + .to_string(), + )), + Err(ParseMegaSpecError::Unknown) => Err(EvmeError::InvalidInput(format!( + "Invalid spec name: {name:?}; possible values: `Equivalence`, `MiniRex`, \ + `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, \ + `Satin`" + ))), + } + } + + /// The engine a block of `chain_id` with timestamp `timestamp` executed on, or will execute + /// on. + /// + /// A known chain runs Satin from the timestamp its activation table gives, and the legacy + /// engine before it, or throughout while Satin is not scheduled. A chain the run was given the + /// genesis file of (`--genesis`) is known, by its file's `satinTime`. + /// + /// # Errors + /// + /// For a chain that is not known ([`unknown_chain`]). + pub fn of_block(chain_id: u64, timestamp: u64) -> Result { + Self::under(chain_activation(chain_id), timestamp).ok_or_else(|| unknown_chain(chain_id)) + } + + /// The engine a block with timestamp `timestamp` runs on under `activation`, the activation + /// table of its chain; `None` for a chain without one. + fn under(activation: Option, timestamp: u64) -> Option { + match activation? { + ChainActivation { satin: Some(satin), .. } if timestamp >= satin => Some(Self::Satin), + _ => Some(Self::Legacy), + } + } + + /// The engine every block of `chain_id` runs on, if the chain's schedule decides it without + /// a timestamp: `None` when the chain switches engines at a scheduled timestamp. + /// + /// # Errors + /// + /// For a chain that is not known ([`unknown_chain`]). + pub fn of_chain(chain_id: u64) -> Result> { + match chain_activation(chain_id) { + None => Err(unknown_chain(chain_id)), + Some(ChainActivation { satin: None, .. }) => Ok(Some(Self::Legacy)), + Some(ChainActivation { satin: Some(_), .. }) => Ok(None), + } + } + + /// The engine's name in output. + pub const fn name(self) -> &'static str { + match self { + Self::Satin => "satin", + Self::Legacy => "legacy", + } + } +} + +/// The refusal of a chain neither the tool's table nor a genesis file names: the tool cannot tell +/// which engine its blocks run on, so the run names it. +pub fn unknown_chain(chain_id: u64) -> EvmeError { + EvmeError::InvalidInput(format!( + "chain {chain_id} is not a MegaETH chain this tool knows (mainnet {}, testnet {}): give its \ + genesis file (--genesis) or name the spec to run (--override.spec)", + mega_evm::MAINNET_CHAIN_ID, + mega_evm::TESTNET_CHAIN_ID + )) +} + +/// Runs `args` on the released 1.7.1 CLI. +/// +/// `add_default_spec` adds `--spec Rex6` for a `run` or `tx` whose `--spec` was left out: +/// the 1.7.1 parser's own default is `Rex7`, which this tool refuses. +#[cfg(feature = "legacy")] +pub async fn run_legacy(mut args: Vec, add_default_spec: bool) -> Result<()> { + use clap::Parser; + + if add_default_spec { + args = with_default_spec(args); + } + if let Err(e) = mega_evme_legacy::cmd::MainCmd::parse_from(args).run().await { + // The released CLI's `main` prints this on stderr (`Error:` plus the error's `Debug`) + // and also echoes the `Debug` form to stdout. The text comes back unchanged; this + // process prints it once, with every other command error. + return Err(EvmeError::ReleasedCli(format!("Error: {e:?}"))); + } + Ok(()) +} + +/// `args` with `--spec Rex6` added where the 1.7.1 parser reads it as the option: before the first +/// `--`, which ends the options, or at the end when there is none. +/// +/// After a `--` every argument is a positional, so a flag appended behind one would be read as +/// the code or the raw transaction. No option of either CLI takes a value starting with a hyphen, +/// so the first `--` after the program name is the separator. +#[cfg(feature = "legacy")] +fn with_default_spec(mut args: Vec) -> Vec { + let at = args.iter().skip(1).position(|arg| arg == "--").map_or(args.len(), |i| i + 1); + args.splice(at..at, [OsString::from("--spec"), OsString::from(DEFAULT_SPEC)]); + args +} + +/// Refuses a legacy spec in a build without the legacy leg. +#[cfg(not(feature = "legacy"))] +pub async fn run_legacy(_args: Vec, _add_default_spec: bool) -> Result<()> { + Err(EvmeError::InvalidInput( + "this build runs Satin only (built without the `legacy` feature); a spec from \ + `Equivalence` to `Rex6` needs the legacy leg" + .to_string(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{MAINNET_CHAIN_ID, TESTNET_CHAIN_ID}; + + #[test] + fn test_each_spec_names_its_engine() { + assert_eq!(Engine::of_spec("Satin").unwrap(), Engine::Satin); + for legacy in mega_evm::LEGACY_SPEC_NAMES { + assert_eq!(Engine::of_spec(legacy).unwrap(), Engine::Legacy, "{legacy}"); + } + assert_eq!(Engine::of_spec(DEFAULT_SPEC).unwrap(), Engine::Legacy); + } + + /// The default spec goes where the 1.7.1 parser reads it as the option: at the end, or + /// before the first `--`, after which every argument is a positional. + #[cfg(feature = "legacy")] + #[test] + fn test_the_default_spec_goes_before_the_options_end() { + let args = |list: &[&str]| list.iter().map(OsString::from).collect::>(); + assert_eq!( + with_default_spec(args(&["mega-evme", "run", "--json", "0x00"])), + args(&["mega-evme", "run", "--json", "0x00", "--spec", "Rex6"]) + ); + assert_eq!( + with_default_spec(args(&["mega-evme", "run", "--json", "--", "0x00"])), + args(&["mega-evme", "run", "--json", "--spec", "Rex6", "--", "0x00"]) + ); + // A `--` after the separator is a positional, and the program name is no argument. + assert_eq!( + with_default_spec(args(&["--", "tx", "--", "--"])), + args(&["--", "tx", "--spec", "Rex6", "--", "--"]) + ); + } + + #[test] + fn test_rex7_and_unknown_names_are_refused() { + let rex7 = Engine::of_spec("Rex7").unwrap_err().to_string(); + assert!(rex7.contains("Satin supersedes it"), "{rex7}"); + let unknown = Engine::of_spec("Prague").unwrap_err().to_string(); + assert!(unknown.contains("Invalid spec name"), "{unknown}"); + // Spec names are case-sensitive, as both engines' parsers are. + assert!(Engine::of_spec("satin").is_err()); + } + + /// Mainnet and testnet have no Satin timestamp yet: every block of theirs is legacy, and the + /// schedule says so without a timestamp. A chain the tool does not know is refused, naming + /// how to run it. + #[test] + fn test_the_chain_schedule_picks_the_engine() { + for chain_id in [MAINNET_CHAIN_ID, TESTNET_CHAIN_ID] { + assert_eq!(Engine::of_chain(chain_id).unwrap(), Some(Engine::Legacy)); + assert_eq!(Engine::of_block(chain_id, 0).unwrap(), Engine::Legacy); + assert_eq!(Engine::of_block(chain_id, u64::MAX).unwrap(), Engine::Legacy); + } + for error in [ + Engine::of_chain(1_337).unwrap_err().to_string(), + Engine::of_block(1_337, 0).unwrap_err().to_string(), + ] { + assert!(error.contains("chain 1337 is not a MegaETH chain this tool knows"), "{error}"); + assert!(error.contains("--genesis") && error.contains("--override.spec"), "{error}"); + } + } + + /// Once a known chain schedules Satin, its blocks before the timestamp stay legacy and the + /// block at the timestamp is the first Satin one. A chain without a table has no engine. + #[test] + fn test_a_scheduled_chain_switches_at_the_timestamp() { + let scheduled = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(1_800_000_000) }; + assert_eq!(Engine::under(Some(scheduled), 1_799_999_999), Some(Engine::Legacy)); + assert_eq!(Engine::under(Some(scheduled), 1_800_000_000), Some(Engine::Satin)); + assert_eq!(Engine::under(None, 0), None); + } +} diff --git a/bin/mega-evme/src/lib.rs b/bin/mega-evme/src/lib.rs index 02c41cb56..2574bb20b 100644 --- a/bin/mega-evme/src/lib.rs +++ b/bin/mega-evme/src/lib.rs @@ -6,11 +6,15 @@ //! the library directly and exercise the public API the same way an external //! consumer would. +/// Whole-block replay on either engine, compared with the chain. +pub mod block; /// Top-level CLI command parser and dispatch (`MainCmd`, `Commands`, `Error`). pub mod cmd; /// Shared building blocks: RPC provider/session, state, env, error, output /// formatting, tracing, transaction utilities. pub mod common; +/// Which engine runs a command, and the hand-off to the legacy one. +pub mod engine; /// Historical transaction replay command. pub mod replay; /// Arbitrary EVM bytecode execution command. @@ -25,7 +29,8 @@ pub use common::*; /// Install a thread panic hook that prints a custom backtrace and exits with a /// non-zero status. Lets failing tests and CLI runs surface a useful trace -/// without relying on `RUST_BACKTRACE`. +/// without relying on `RUST_BACKTRACE`. A panic of `println!` on a closed stdout is no failure +/// of the run: the hook exits 0 without a trace. pub fn set_thread_panic_hook() { use std::{ backtrace::Backtrace, @@ -34,6 +39,18 @@ pub fn set_thread_panic_hook() { }; let orig_hook = take_hook(); set_hook(Box::new(move |panic_info| { + // `println!` panics when stdout is a closed pipe (`mega-evme … | head`). The reader went + // away on purpose, so the run ends quietly with the status it had reached: it was + // printing its result, so it succeeded. + let message = panic_info + .payload() + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic_info.payload().downcast_ref::<&str>().copied()) + .unwrap_or_default(); + if message.starts_with("failed printing to stdout: Broken pipe") { + exit(0); + } // Raw stderr rather than `tracing`: the subscriber may not be // installed yet when a panic fires during CLI startup. eprintln!("Custom backtrace: {}", Backtrace::capture()); diff --git a/bin/mega-evme/src/main.rs b/bin/mega-evme/src/main.rs index da36f3dec..f62445cd6 100644 --- a/bin/mega-evme/src/main.rs +++ b/bin/mega-evme/src/main.rs @@ -2,16 +2,14 @@ //! //! All business logic lives in the `mega_evme` library crate (`src/lib.rs`). //! This binary is intentionally minimal: parse CLI arguments, install the panic -//! hook, dispatch to the parsed command, and exit. +//! hook, hand the arguments to the engine the spec names, and exit. -use clap::Parser; -use mega_evme::{ - cmd::{Error, MainCmd}, - set_thread_panic_hook, -}; +use mega_evme::set_thread_panic_hook; -#[tokio::main] -async fn main() -> std::result::Result<(), Error> { +#[tokio::main(flavor = "multi_thread")] +async fn main() { set_thread_panic_hook(); - MainCmd::parse().run().await.inspect_err(|e| println!("{e:?}")) + if let Err(error) = mega_evme::cmd::run_cli(std::env::args_os().collect()).await { + mega_evme::cmd::report_cli_error(&error); + } } diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 572bb722c..032b47bff 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -1,4 +1,4 @@ -use std::{str::FromStr, time::Instant}; +use std::time::Instant; use alloy_consensus::{BlockHeader, Transaction as _}; use alloy_primitives::{B256, U256}; @@ -6,30 +6,36 @@ use alloy_provider::Provider; use alloy_rpc_types_eth::Block; use clap::Parser; use mega_evm::{ - alloy_evm::{block::BlockExecutor, Evm, EvmEnv}, + alloy_evm::{ + block::{BlockExecutionError, BlockExecutor}, + Evm, EvmEnv, + }, alloy_op_evm::block::OpAlloyReceiptBuilder, revm::{ - context::{result::ExecutionResult, BlockEnv, ContextTr}, + context::{result::ExecutionResult, BlockEnv, CfgEnv, ContextTr}, database::{states::bundle_state::BundleRetention, StateBuilder}, - primitives::eip4844, - DatabaseRef, + inspector::JournalExt, + interpreter::{CallInputs, CallOutcome, CreateInputs, CreateOutcome, Interpreter}, + primitives::{eip4844, Address, Log}, + DatabaseRef, Inspector, }, - BlockLimits, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, - MegaEvmFactory, MegaHardforks, MegaSpecId, + BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, + MegaHardforks, MegaSpecId, }; use tracing::{debug, info, trace, warn}; -use alloy_network::ReceiptResponse; use op_alloy_rpc_types::Transaction; use crate::{ common::{ - op_receipt_to_tx_receipt, parse_bucket_capacity, print_execution_summary, - print_execution_trace, print_receipt, BuildProviderOutput, EvmeExternalEnvs, EvmeOutcome, - ExecutionSummary, ExternalEnvSnapshot, OpTxReceipt, RpcCacheStore, TxOverrideArgs, + check_genesis_chain, op_receipt_to_tx_receipt, parse_bucket_capacity, + parse_limits_override, print_execution_summary, print_execution_trace, print_receipt, + print_satin_report, satin_limits, satin_schedule, BuildProviderOutput, EvmeExternalEnvs, + EvmeOutcome, ExecutionSummary, ExternalEnvSnapshot, LimitsOverride, OpTxReceipt, + RpcCacheStore, SatinReport, TxOverrideArgs, }, - replay::get_hardfork_config, - run, ChainArgs, EvmeState, + engine::Engine, + run, EvmeState, }; use super::{ReplayError, Result}; @@ -38,8 +44,12 @@ use super::{ReplayError, Result}; #[derive(Parser, Debug)] pub struct Cmd { /// Transaction hash to replay - #[arg(value_name = "TX_HASH")] - pub tx_hash: B256, + #[arg(value_name = "TX_HASH", required_unless_present = "block")] + pub tx_hash: Option, + + /// Block replay configuration (`--block`) + #[command(flatten)] + pub block_args: crate::block::BlockArgs, /// RPC configuration #[command(flatten)] @@ -57,10 +67,19 @@ pub struct Cmd { #[command(flatten)] pub trace_args: run::TraceArgs, - /// Override the spec to use (default: auto-detect from chain ID and block timestamp) + /// Override the spec to use (default: auto-detect from chain ID and block timestamp). + /// `Satin` replays on the Satin engine, a legacy spec on the legacy engine #[arg(long = "override.spec", value_name = "SPEC")] pub spec_override: Option, + /// Satin only: replay under these protocol limits instead of the spec's, a counterfactual. A + /// JSON object in `ProtocolLimits`' shape (camelCase, per-transaction limits under + /// `txRuntimeLimits`), inline or in a file; the fields it names replace the spec's, every + /// other stays. Refused when it names an unknown field or a value of the wrong type, and for a + /// block that runs on the legacy engine + #[arg(long = "override.limits", value_name = "JSON|FILE", value_parser = parse_limits_override)] + pub limits_override: Option, + /// Transaction override configuration #[command(flatten)] pub tx_override_args: TxOverrideArgs, @@ -75,10 +94,10 @@ pub struct Cmd { /// The fixture captures the pre-state read closure, block environment, /// transaction, and `MegaETH` external environment, and records `post` /// expectations (state/logs roots, gas, status) computed by the state-test - /// runner. Re-running the file through `state-test` self-validates the - /// replay, and `state-test --bench` benchmarks it. The dump is rejected - /// unless the local replay reproduces the on-chain receipt's gas and success - /// status. Incompatible with transaction overrides and `--override.spec`. + /// runner. Re-running the file through the 1.7.1 `state-test` self-validates the + /// replay. The dump is rejected unless the local replay reproduces the on-chain receipt's gas + /// and success status. Incompatible with transaction overrides and `--override.spec`. + /// Legacy specs only: no state-test runner prices a transaction as Satin does. #[arg(long = "dump-fixture", value_name = "FILE")] pub dump_fixture: Option, } @@ -98,8 +117,6 @@ pub(super) struct ReplayOutcome { pub outcome: EvmeOutcome, /// The transaction receipt pub receipt: OpTxReceipt, - /// Self-validating fixture draft, present iff `--dump-fixture` was given. - pub fixture: Option, } /// Intermediate context fetched from RPC before execution. @@ -112,38 +129,99 @@ struct ReplayContext { } impl Cmd { - /// Replay a historical transaction. + /// The engine the replayed transaction runs on: the one `--override.spec` names, otherwise + /// the one its chain ran, or runs, its block on. + /// + /// Without an override this reads the chain id, and, only on a chain that switches engines + /// at a scheduled timestamp, the timestamp of the block the replay runs the transaction in, + /// from the source the replay itself reads, through a provider that persists nothing: the + /// transaction's block, or for a pending transaction the latest block, whose environment and + /// schedule the replay runs it in. Under `--genesis` a chain other than the file's is refused + /// once the chain id is read, before an engine is picked for it. + pub async fn engine(&self) -> Result { + let tx_hash = self.tx_hash(); + if let Some(spec) = &self.spec_override { + return Engine::of_spec(spec); + } + let (provider, chain_id) = self.rpc_args.build_lookup_provider().await?; + check_genesis_chain(chain_id)?; + if let Some(engine) = Engine::of_chain(chain_id)? { + return Ok(engine); + } + let tx = provider + .get_transaction_by_hash(tx_hash) + .await + .map_err(|e| ReplayError::RpcError(format!("Failed to fetch transaction: {e}")))? + .ok_or(ReplayError::TransactionNotFound(tx_hash))?; + let transport = |e| ReplayError::RpcError(format!("RPC transport error: {e}")); + let number = match tx.block_number { + Some(number) => number, + None => provider.get_block_number().await.map_err(transport)?, + }; + let timestamp = provider + .get_block_by_number(number.into()) + .await + .map_err(transport)? + .ok_or(ReplayError::BlockNotFound(number))? + .header + .timestamp(); + Engine::of_block(chain_id, timestamp) + } + + /// Whether this replays whole blocks (`--block`), which runs here for both engines. + pub fn replays_blocks(&self) -> bool { + self.block_args.block.is_some() + } + + /// The transaction to replay; present unless `--block` is. + fn tx_hash(&self) -> B256 { + self.tx_hash.expect("clap requires TX_HASH unless --block is given") + } + + /// Replay a historical transaction on the Satin engine, or whole blocks on either engine. pub async fn run(&self) -> Result<()> { - // Pure input validation — reject before any network/state work. A dumped - // fixture must represent the on-chain transaction, so it can neither apply - // transaction overrides nor force a spec: both would make the recorded - // execution a what-if, not the on-chain one. - if self.dump_fixture.is_some() { - if self.tx_override_args.has_overrides() { - return Err(ReplayError::Other( - "--dump-fixture cannot be combined with transaction overrides (the \ - isolated execution would not represent the on-chain transaction)" - .to_string(), - )); - } - if self.spec_override.is_some() { - return Err(ReplayError::Other( - "--dump-fixture cannot be combined with --override.spec (the fixture \ - must record the spec auto-detected for the on-chain block, not a \ - manually forced one)" - .to_string(), - )); + if let Some(range) = self.block_args.block { + let bucket_capacities = self + .ext_args + .bucket_capacity + .iter() + .map(|s| parse_bucket_capacity(s)) + .collect::>>()?; + let summary = crate::block::replay_blocks( + range, + &self.block_args, + &self.rpc_args, + &bucket_capacities, + self.spec_override.as_deref(), + self.limits_override.as_ref(), + self.output_args.json, + ) + .await?; + let code = summary.exit_code(self.block_args.verify); + if code != 0 { + std::process::exit(code); } + return Ok(()); + } + + // A dumped fixture is re-executed by a state-test runner that prices the transaction as + // the chain does; no such runner exists for Satin, so the dump is refused before any + // network or state work. On a legacy spec the dump is the 1.7.1 tool's, unchanged. + if self.dump_fixture.is_some() { + return Err(ReplayError::Other( + "--dump-fixture is not available on Satin: no state-test runner prices a \ + transaction as Satin does; it is available on the legacy specs" + .to_string(), + )); } let mut pctx = self.resolve_provider().await?; let rctx = self.fetch_replay_context(&pctx.provider, pctx.chain_id).await?; let (external_envs, env_snapshot) = self.resolve_external_envs(&pctx)?; - // Execute, report, and (for --dump-fixture) finalize/write — but defer - // error propagation until the cache store has persisted: in capture mode - // an execution or dump-gate failure is exactly the case you'd want to - // debug offline, so the captured RPC responses must not be discarded. + // Execute and report, but defer error propagation until the cache store has persisted: + // in capture mode an execution failure is exactly the case you'd want to debug + // offline, so the captured RPC responses must not be discarded. let run_result = self.execute_and_report(&pctx.provider, &rctx, external_envs).await; // Hand the effective external-env snapshot to the store before the final @@ -168,11 +246,10 @@ impl Cmd { } } - /// Execute the replay, print the results, and (for `--dump-fixture`) - /// finalize and write the fixture. + /// Execute the replay and print the results. /// /// Split out of [`Self::run`] so the caller can persist the RPC cache store - /// regardless of which of these steps fails. + /// regardless of whether this step fails. async fn execute_and_report

( &self, provider: &P, @@ -183,14 +260,7 @@ impl Cmd { P: Provider + Clone + std::fmt::Debug, { let result = self.execute(provider, rctx, external_envs).await?; - self.output_results(&result)?; - // Write the self-validating fixture (re-executes the isolated unit through - // state-test and cross-checks it against the replay before writing). - if let (Some(path), Some(draft)) = (&self.dump_fixture, result.fixture) { - super::fixture::finalize_and_write(draft, path)?; - info!(path = %path.display(), "Wrote self-validating fixture"); - } - Ok(()) + self.output_results(&result) } /// Select the right provider based on `--rpc`, `--rpc.capture-file`, and @@ -210,7 +280,7 @@ impl Cmd { info!(path = %path.display(), "Provider mode: offline replay from cache file"); self.rpc_args.build_replay_provider().await? } else if let Some(rpc) = &self.rpc_args.rpc_url { - info!(rpc = %rpc, "Provider mode: online RPC"); + info!(rpc = %crate::redact_rpc_url(rpc), "Provider mode: online RPC"); self.rpc_args.build_provider().await? } else { return Err(ReplayError::Other( @@ -229,12 +299,13 @@ impl Cmd { where P: Provider, { - info!(tx_hash = %self.tx_hash, "Fetching transaction"); + let tx_hash = self.tx_hash(); + info!(%tx_hash, "Fetching transaction"); let target_tx = provider - .get_transaction_by_hash(self.tx_hash) + .get_transaction_by_hash(tx_hash) .await .map_err(|e| ReplayError::RpcError(format!("Failed to fetch transaction: {e}")))? - .ok_or_else(|| ReplayError::TransactionNotFound(self.tx_hash))?; + .ok_or(ReplayError::TransactionNotFound(tx_hash))?; debug!(block_number = ?target_tx.block_number, "Transaction found"); let (state_base_block, block_number, is_pending) = if let Some(n) = target_tx.block_number { @@ -264,15 +335,14 @@ impl Cmd { .map_err(|e| ReplayError::RpcError(format!("RPC transport error: {e}")))? .ok_or(ReplayError::BlockNotFound(block_number))?; - let mut preceding_tx_hashes = vec![]; - if !is_pending { - for hash in block.transactions.hashes() { - if hash == self.tx_hash { - break; - } - preceding_tx_hashes.push(hash); - } - } + let preceding_tx_hashes = preceding_transactions( + tx_hash, + target_tx.block_number, + target_tx.block_hash, + block.number(), + block.hash(), + block.transactions.hashes(), + )?; debug!(chain_id, preceding_count = preceding_tx_hashes.len(), "Replay context ready"); @@ -340,7 +410,8 @@ impl Cmd { Ok((envs, snapshot)) } - /// Execute the target transaction (with preceding transactions) and return the outcome. + /// Execute the target transaction (with preceding transactions) on Satin and return the + /// outcome. async fn execute

( &self, provider: &P, @@ -350,10 +421,11 @@ impl Cmd { where P: Provider + Clone + std::fmt::Debug, { - let hardforks = get_hardfork_config(ctx.chain_id); - let spec = hardforks.spec_id(ctx.block.header.timestamp()); - let chain_args = ChainArgs { chain_id: ctx.chain_id, spec: spec.to_string() }; - debug!(chain_id = ctx.chain_id, spec = %spec, "Chain configuration"); + let timestamp = ctx.block.header.timestamp(); + let hardforks = satin_schedule(ctx.chain_id, timestamp)?; + let limits_override = + self.limits_override.as_ref().map(|limits| satin_limits(Some(limits))).transpose()?; + debug!(chain_id = ctx.chain_id, spec = %MegaSpecId::SATIN, "Chain configuration"); info!(fork_block = ctx.parent_block.header.number(), "Forking state from parent block",); let mut database = EvmeState::new_forked( @@ -366,126 +438,60 @@ impl Cmd { let block_env = retrieve_block_env(&ctx.block)?; trace!(?block_env, "Block environment built"); - let mut evm_env = EvmEnv::new(chain_args.create_cfg_env()?, block_env); - - // For `--dump-fixture`, snapshot the two inputs a fixture - // needs before the external env is moved into the factory: the effective - // MegaETH external environment, and the on-chain receipt gas used as the - // fidelity anchor. They live or die together (kept in one `Option`), so the - // fixture builder never has to assume one without the other. - // - // The receipt is fetched here (before the executor borrows the database) so - // it is captured by `--rpc.capture-file`. A fixture/benchmark is only - // meaningful if the local replay reproduces the receipt's gas and success - // status — a mismatch means a wrong spec or hardfork config, which - // self-validation alone cannot catch. - let fixture_inputs = if self.dump_fixture.is_some() { - // A pending transaction has no receipt yet, so the fidelity gate cannot - // run; fail clearly instead of surfacing the receipt lookup's confusing - // `TransactionNotFound`. - if ctx.target_tx.block_number.is_none() { - return Err(ReplayError::Other( - "--dump-fixture does not support pending transactions: the fidelity \ - gate needs the on-chain receipt, which does not exist yet" - .to_string(), - )); - } - // Sort the accessed buckets/oracle slots so the dumped fixture is - // byte-reproducible: these come from hash-map iteration, whose order - // is otherwise non-deterministic across runs (noisy diffs, and an - // online dump would not byte-match an offline re-dump). - let mut bucket_capacities = external_envs.bucket_capacities(); - bucket_capacities.sort_unstable(); - let mut oracle_storage = external_envs.oracle_storage(); - oracle_storage.sort_unstable(); - let mega_env = state_test::types::MegaEnv { bucket_capacities, oracle_storage }; - let receipt = provider - .get_transaction_receipt(self.tx_hash) - .await - .map_err(|e| ReplayError::RpcError(format!("RPC transport error: {e}")))? - .ok_or(ReplayError::TransactionNotFound(self.tx_hash))?; - // Anchor the receipt to the replayed block: across a reorg or a - // load-balanced endpoint serving divergent views, the receipt can - // describe a different inclusion than the block fetched earlier, - // and the fidelity gate would then compare the replay against the - // wrong on-chain execution. - if let Some(receipt_block_hash) = receipt.block_hash() { - let replayed_block_hash = ctx.block.hash(); - if receipt_block_hash != replayed_block_hash { - return Err(ReplayError::Other(format!( - "receipt block hash {receipt_block_hash} != replayed block hash \ - {replayed_block_hash}: the receipt describes a different inclusion \ - than the fetched block (reorg in progress, or a load-balanced \ - endpoint serving divergent views); retry the dump once the chain \ - settles" - ))); - } - } - // RLP-hash the receipt's logs with the same helper the state-test - // runner uses for `logsRoot`, so the dump can check the replay's logs - // against the chain (the rich RPC logs' `inner` is the consensus log). - let receipt_logs: Vec<_> = - receipt.inner.logs().iter().map(|log| log.inner.clone()).collect(); - let anchor = super::fixture::OnchainAnchor { - gas_used: receipt.gas_used(), - success: receipt.inner.status(), - logs_root: state_test::utils::log_rlp_hash(&receipt_logs), - }; - Some((mega_env, anchor)) - } else { - None - }; + let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg_env.chain_id = ctx.chain_id; + let evm_env = EvmEnv::new(cfg_env, block_env); let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); let block_executor_factory = MegaBlockExecutorFactory::new( + OpAlloyReceiptBuilder::default(), &hardforks, evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut block_limits = BlockLimits::from_hardfork_and_block_gas_limit( - hardforks.hardfork(ctx.block.header.timestamp()).ok_or(ReplayError::Other(format!( - "No `MegaHardfork` active at block timestamp: {}", - ctx.block.header.timestamp() - )))?, - ctx.block.header.gas_limit(), ); - - if let Some(spec_override) = &self.spec_override { - info!(spec_override = %spec_override, "Overriding EVM spec"); - let spec = MegaSpecId::from_str(spec_override) - .map_err(|e| ReplayError::Other(format!("Invalid spec: {e:?}")))?; - evm_env.cfg_env.spec = spec; - block_limits = block_limits.with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - } - - // The spec the target transaction will execute under (after any override), - // captured before `evm_env` is moved into the executor. - let executed_spec = evm_env.cfg_env.spec; - + // The block is held to Satin's protocol limits, or the override's, with no building + // policy, as a validator holds it; the block's gas limit comes from its header. Whether + // it admits only deposits comes from the schedule and the parent block's timestamp, as a + // node works it out. + let parent_timestamp = ctx.parent_block.header.timestamp(); + let only_deposits = hardforks.admits_only_deposits(parent_timestamp, timestamp); + let activates_satin = hardforks.is_satin_activation_block(parent_timestamp, timestamp); let block_ctx = MegaBlockExecutionCtx::new( ctx.parent_block.hash(), ctx.block.header.parent_beacon_block_root(), ctx.block.header.extra_data().clone(), - block_limits, - ); + BlockLimits::default(), + ) + .with_no_user_tx_activation_block(only_deposits) + .with_satin_activation_block(activates_satin); let start = Instant::now(); - let mut inspector = self.trace_args.create_inspector(); + // The tracer reads and writes nothing back, so block execution admits it declared. + // It is attached only for `--trace`: otherwise preceding transactions would be recorded + // and then discarded. + let mut inspector = DeclaredObserver::new(ReplayTracer::from_args(&self.trace_args)); let mut state = StateBuilder::new().with_database(&mut database).with_bundle_update().build(); - let mut block_executor = block_executor_factory.create_executor_with_inspector( + let mut block_executor = block_executor_factory.create_executor_with_trusted_inspector( &mut state, - block_ctx, evm_env, + block_ctx, &mut inspector, ); + if let Some(limits) = limits_override { + block_executor = block_executor.with_protocol_limits(limits); + } block_executor .apply_pre_execution_changes() .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; - // Execute preceding transactions + // Execute preceding transactions. A validation error is a refusal: a block import + // records it and continues, and the target runs on the state the included ones left. + // A database failure or an internal error stops the replay. The receipt index counts + // only the included transactions. info!(preceding_count = ctx.preceding_tx_hashes.len(), "Executing preceding transactions",); + let mut included_preceding = 0u64; + let mut log_index_base = 0u64; for tx_hash in &ctx.preceding_tx_hashes { debug!(tx_hash = %tx_hash, "Executing preceding transaction"); let tx = provider @@ -493,21 +499,35 @@ impl Cmd { .await .map_err(|e| ReplayError::RpcError(format!("RPC transport error: {e}")))? .ok_or(ReplayError::TransactionNotFound(*tx_hash))?; - let outcome = block_executor - .run_transaction(tx.as_recovered()) - .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; + let outcome = match block_executor.run_transaction(tx.as_recovered()) { + Ok(outcome) => outcome, + Err(e) => match predecessor_error(&e) { + PredecessorError::Skip => { + warn!(tx_hash = %tx_hash, error = %e, "Skipping refused preceding transaction"); + continue; + } + PredecessorError::Propagate(error) => return Err(error), + }, + }; trace!(tx_hash = %tx_hash, ?outcome, "Preceding transaction executed"); - block_executor - .commit_transaction_outcome(outcome) - .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; + if let Err(e) = block_executor.commit_transaction_outcome(outcome) { + match predecessor_error(&e) { + PredecessorError::Skip => { + warn!(tx_hash = %tx_hash, error = %e, "Skipping refused preceding transaction"); + continue; + } + PredecessorError::Propagate(error) => return Err(error), + } + } + included_preceding += 1; + log_index_base += block_executor + .receipts() + .last() + .map(|receipt| receipt.logs().len() as u64) + .unwrap_or(0); } - // Clear block hash reads accumulated by the preceding transactions so the - // fixture gate below sees only the target transaction's BLOCKHASH reads. - block_executor.clear_accessed_block_hashes(); - - // Execute target transaction. Override-incompatibility with - // --dump-fixture is validated up front in `run()`. + // Execute target transaction. info!("Executing target transaction"); if self.tx_override_args.has_overrides() { info!(overrides = ?self.tx_override_args, "Applying transaction overrides"); @@ -515,24 +535,33 @@ impl Cmd { let wrapped_tx = self.tx_override_args.wrap(ctx.target_tx.as_recovered())?; let pre_execution_nonce = block_executor .evm() - .db_ref() + .db() .basic_ref(wrapped_tx.inner().signer())? .map(|acc| acc.nonce) .unwrap_or(0); - block_executor.inspector_mut().fuse(); + // The trace covers the target transaction only. + if let ReplayTracer::On(tracer) = &mut block_executor.evm_mut().inspector_mut().0 { + tracer.fuse(); + } let outcome = block_executor .run_transaction(wrapped_tx) .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; trace!(tx_hash = %ctx.target_tx.inner.inner.tx_hash(), ?outcome, "Target transaction executed"); + let mut satin = SatinReport::of(&outcome.inner); + satin.limits_override = limits_override.map(Box::new); let exec_result = outcome.inner.result.clone(); let evm_state = outcome.inner.state.clone(); match &exec_result { - ExecutionResult::Success { gas_used, .. } => info!(gas_used, "Execution succeeded"), - ExecutionResult::Revert { gas_used, .. } => warn!(gas_used, "Execution reverted"), - ExecutionResult::Halt { reason, gas_used } => { - warn!(?reason, gas_used, "Execution halted") + ExecutionResult::Success { .. } => { + info!(gas_used = exec_result.tx_gas_used(), "Execution succeeded") + } + ExecutionResult::Revert { .. } => { + warn!(gas_used = exec_result.tx_gas_used(), "Execution reverted") + } + ExecutionResult::Halt { reason, .. } => { + warn!(?reason, gas_used = exec_result.tx_gas_used(), "Execution halted") } } @@ -541,50 +570,19 @@ impl Cmd { state: evm_state.clone(), }; - let trace_data = self.trace_args.is_tracing_enabled().then(|| { - self.trace_args.generate_trace( - block_executor.inspector(), + let trace_data = match &block_executor.inspector().0 { + ReplayTracer::On(tracer) => Some(self.trace_args.generate_trace( + tracer, &result_and_state, - block_executor.evm().db_ref(), - ) - }); - - // Build the self-validating fixture draft while the database still reflects - // the pre-target-transaction state (preceding txs committed, target not yet). - let fixture = match fixture_inputs { - Some((mega_env, anchor)) => { - // A dumped fixture cannot faithfully reproduce BLOCKHASH: the - // state-test runner does not seed block hashes, so the isolated - // re-execution would read default hashes instead of the ones this - // replay observed. The access record is cleared after the preceding - // transactions, so it holds exactly the target transaction's reads; - // if the target read any block hash, refuse to dump rather than - // write a fixture that self-validates against the wrong roots. - let accessed_block_hashes = block_executor.get_accessed_block_hashes(); - if !accessed_block_hashes.is_empty() { - return Err(ReplayError::Other(format!( - "--dump-fixture does not support transactions that read block \ - hashes (BLOCKHASH): {} block hash(es) were accessed and the \ - fixture cannot faithfully reproduce them", - accessed_block_hashes.len() - ))); - } - Some(super::fixture::build_draft( - block_executor.evm().db_ref(), - &evm_state, - ctx.chain_id, - executed_spec, - &ctx.block, - &ctx.target_tx, - super::fixture::FixtureInputs { mega_env, result: &exec_result, anchor }, - )?) - } - None => None, + block_executor.evm().db(), + )), + ReplayTracer::Off => None, }; - let gas_used = block_executor + let gas_output = block_executor .commit_transaction_outcome(outcome) .map_err(|e| ReplayError::Other(format!("Block execution error: {e}")))?; + let gas_used = gas_output.tx_gas_used(); let duration = start.elapsed(); let (evm, block_result) = block_executor @@ -610,7 +608,8 @@ impl Cmd { gas_used, Some(ctx.target_tx.inner.inner.tx_hash()), Some(ctx.block.hash()), - ctx.preceding_tx_hashes.len() as u64, + included_preceding, + log_index_base, ); Ok(ReplayOutcome { @@ -620,9 +619,9 @@ impl Cmd { state: evm_state, exec_time: duration, trace_data, + satin, }, receipt, - fixture, }) } @@ -637,6 +636,7 @@ impl Cmd { summary.fill_trace_and_dump(&result.outcome, &self.trace_args, &self.dump_args)?; summary.receipt = Some(serde_json::to_value(&result.receipt).expect("failed to serialize receipt")); + summary.satin = Some(result.outcome.satin.clone()); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") @@ -647,6 +647,7 @@ impl Cmd { result.receipt.contract_address, result.outcome.exec_time, ); + print_satin_report(&result.outcome.satin); print_receipt(&result.receipt); print_execution_trace( result.outcome.trace_data.as_deref(), @@ -660,6 +661,62 @@ impl Cmd { } } +/// What the preceding-transaction loop does with an execution error. +#[derive(Debug)] +enum PredecessorError { + /// A validation error: the block refused the transaction, and the replay continues. + Skip, + /// A database failure or an internal error. The replay stops. + Propagate(ReplayError), +} + +/// Classifies `error` for the preceding-transaction loop. +/// +/// A validation error is a refusal a block import records and continues past. +/// A database failure or an internal error stops the replay, so the target runs on the state +/// the included predecessors left. +fn predecessor_error(error: &BlockExecutionError) -> PredecessorError { + if error.as_validation().is_some() { + PredecessorError::Skip + } else { + PredecessorError::Propagate(ReplayError::Other(format!("Block execution error: {error}"))) + } +} + +/// Hashes of the transactions before `target_hash` in the fetched block. +/// +/// A pending transaction has no block yet, so it has no predecessors here. A mined transaction +/// must name this block's number and hash, and the hash must occur in the block. Otherwise every +/// transaction in the block would be treated as preceding and the target would still run. +fn preceding_transactions( + target_hash: B256, + target_block_number: Option, + target_block_hash: Option, + block_number: u64, + block_hash: B256, + hashes: impl IntoIterator, +) -> Result> { + let Some(tx_block_number) = target_block_number else { + return Ok(Vec::new()); + }; + if tx_block_number != block_number || target_block_hash != Some(block_hash) { + let tx_block_hash = + target_block_hash.map(|hash| hash.to_string()).unwrap_or_else(|| "none".to_string()); + return Err(ReplayError::Other(format!( + "transaction {target_hash} belongs to block {tx_block_number} ({tx_block_hash}), \ + not block {block_number} ({block_hash})" + ))); + } + let mut preceding = Vec::new(); + for hash in hashes { + if hash == target_hash { + return Ok(preceding); + } + preceding.push(hash); + } + Err(ReplayError::Other(format!("transaction {target_hash} is not in block {block_number}"))) +} + /// Build a [`BlockEnv`] from the RPC block header. /// /// Reads `excess_blob_gas` directly from the header rather than using a @@ -675,6 +732,7 @@ fn retrieve_block_env(block: &Block) -> Result { difficulty: block.header.difficulty(), prevrandao: block.header.mix_hash(), blob_excess_gas_and_price: None, + slot_num: 0, }; let excess_blob_gas = block.header.excess_blob_gas().ok_or_else(|| { @@ -692,6 +750,87 @@ fn retrieve_block_env(block: &Block) -> Result { Ok(block_env) } +/// The tracer a replay attaches. Absent unless `--trace` is set. +enum ReplayTracer { + On(revm_inspectors::tracing::TracingInspector), + Off, +} + +impl ReplayTracer { + fn from_args(args: &run::TraceArgs) -> Self { + if args.is_tracing_enabled() { + Self::On(args.create_inspector()) + } else { + Self::Off + } + } +} + +impl Inspector for ReplayTracer +where + CTX: ContextTr, +{ + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + if let Self::On(inspector) = self { + inspector.step(interp, context); + } + } + + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + if let Self::On(inspector) = self { + inspector.step_end(interp, context); + } + } + + fn log(&mut self, context: &mut CTX, log: Log) { + if let Self::On(inspector) = self { + inspector.log(context, log); + } + } + + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + if let Self::On(inspector) = self { + inspector.call(context, inputs) + } else { + None + } + } + + fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if let Self::On(inspector) = self { + inspector.call_end(context, inputs, outcome); + } + } + + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { + if let Self::On(inspector) = self { + inspector.create(context, inputs) + } else { + None + } + } + + fn create_end( + &mut self, + context: &mut CTX, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + if let Self::On(inspector) = self { + inspector.create_end(context, inputs, outcome); + } + } + + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + if let Self::On(inspector) = self { + // The hook takes no context, so the inspector's generic impl cannot be inferred. + , + >>::selfdestruct(inspector, contract, target, value); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -742,4 +881,116 @@ mod tests { other => panic!("unexpected error variant: {other:?}"), } } + + #[test] + fn test_preceding_transactions_stop_at_the_target() { + let target = B256::repeat_byte(1); + let earlier = B256::repeat_byte(2); + let block_hash = B256::repeat_byte(4); + let got = preceding_transactions( + target, + Some(9), + Some(block_hash), + 9, + block_hash, + [earlier, target, B256::repeat_byte(3)], + ) + .expect("target is in the block"); + assert_eq!(got, vec![earlier]); + } + + #[test] + fn test_preceding_transactions_reject_a_missing_target() { + let target = B256::repeat_byte(1); + let block_hash = B256::repeat_byte(4); + let err = preceding_transactions( + target, + Some(9), + Some(block_hash), + 9, + block_hash, + [B256::repeat_byte(2)], + ) + .expect_err("the target hash never occurs"); + match err { + ReplayError::Other(msg) => assert!(msg.contains("not in block"), "{msg}"), + other => panic!("unexpected error variant: {other:?}"), + } + } + + #[test] + fn test_preceding_transactions_reject_a_different_block() { + let target = B256::repeat_byte(1); + let err = preceding_transactions( + target, + Some(9), + Some(B256::repeat_byte(4)), + 8, + B256::repeat_byte(5), + [target], + ) + .expect_err("the transaction names a different block"); + assert!(matches!(err, ReplayError::Other(_))); + } + + #[test] + fn test_replay_attaches_a_tracer_only_when_trace_is_set() { + let off = run::TraceArgs::try_parse_from(["mega-evme"]).expect("defaults parse"); + assert!(matches!(ReplayTracer::from_args(&off), ReplayTracer::Off)); + + let on = run::TraceArgs::try_parse_from([ + "mega-evme", + "--trace", + "--trace.opcode.disable-stack", + ]) + .expect("trace flags parse"); + let ReplayTracer::On(inspector) = ReplayTracer::from_args(&on) else { + panic!("--trace attaches a tracer"); + }; + assert_eq!( + inspector.config().record_stack_snapshots, + revm_inspectors::tracing::StackSnapshotType::None + ); + } + + #[test] + fn test_a_predecessor_error_skips_a_refusal_and_propagates_an_internal_error() { + use mega_evm::alloy_evm::block::BlockValidationError; + + let refusal = BlockExecutionError::from(BlockValidationError::BlockGasExceeded); + assert!( + matches!(predecessor_error(&refusal), PredecessorError::Skip), + "a validation error is a refusal: {refusal}" + ); + + let internal = BlockExecutionError::msg("database read failed"); + match predecessor_error(&internal) { + PredecessorError::Propagate(ReplayError::Other(message)) => { + assert_eq!(message, format!("Block execution error: {internal}")); + } + other => panic!("an internal error propagates: {other:?}"), + } + + let other = BlockExecutionError::other(std::io::Error::other("rpc failed")); + match predecessor_error(&other) { + PredecessorError::Propagate(ReplayError::Other(message)) => { + assert_eq!(message, format!("Block execution error: {other}")); + } + other => panic!("an internal error propagates: {other:?}"), + } + } + + #[test] + fn test_preceding_transactions_skip_a_pending_transaction() { + let got = preceding_transactions( + B256::repeat_byte(1), + None, + None, + 9, + B256::repeat_byte(4), + [B256::repeat_byte(2)], + ) + .expect("a pending transaction has no predecessors"); + assert!(got.is_empty()); + } } diff --git a/bin/mega-evme/src/replay/fixture.rs b/bin/mega-evme/src/replay/fixture.rs deleted file mode 100644 index f51ab721f..000000000 --- a/bin/mega-evme/src/replay/fixture.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! Build a self-validating EEST state-test fixture from a replayed transaction. -//! -//! `mega-evme replay --dump-fixture ` produces a single [`TestUnit`] JSON -//! file that captures everything needed to deterministically re-execute the -//! target transaction in isolation: the pre-state read closure, block -//! environment, transaction, and `MegaETH` external environment (SALT bucket -//! capacities, oracle storage). -//! -//! The recorded `post` roots are computed by `state-test`'s own -//! [`execute_unit_collect`] — the exact code path that validates the fixture — -//! so a dumped fixture is self-consistent by construction: re-running it through -//! the state-test runner reproduces the same roots. As a safety net, the -//! dump cross-checks the gas, status, and output computed from the isolated -//! fixture against the values observed during the full replay, and refuses to -//! write a fixture that does not reproduce them (e.g. an incomplete pre-state -//! closure or an unsupported transaction shape). - -use std::{collections::BTreeMap, fmt::Display}; - -use alloy_consensus::{BlockHeader, Transaction as _}; -use alloy_eips::Typed2718 as _; -use alloy_primitives::KECCAK256_EMPTY; -use alloy_rpc_types_eth::Block; -use mega_evm::{ - revm::{ - context::result::ExecutionResult, - primitives::{Address, Bytes, B256, U256}, - state::EvmState, - DatabaseRef, - }, - MegaHaltReason, MegaSpecId, -}; -use op_alloy_consensus::OpTxEnvelope; -use op_alloy_rpc_types::Transaction; -use state_test::{ - runner::{execute_unit_collect, execution_status, halt_reason}, - types::{AccountInfo, Env, MegaEnv, SpecName, Test, TestSuite, TestUnit, TransactionParts}, -}; - -use super::{ReplayError, Result}; - -/// The on-chain receipt values a dumped fixture is anchored to: a replay that -/// does not reproduce all of these did not reproduce the on-chain transaction. -pub(crate) struct OnchainAnchor { - /// Gas the transaction used on-chain. - pub gas_used: u64, - /// Whether the transaction succeeded on-chain. - pub success: bool, - /// RLP-hash of the on-chain receipt's logs (the same `log_rlp_hash` the - /// state-test runner records as `logsRoot`), so the replay's logs can be - /// checked against the chain, not just its gas and status. - pub logs_root: B256, -} - -/// The fixture-specific inputs gathered during a replay: the `MegaETH` external -/// environment snapshot, the target transaction's execution result, and the -/// on-chain receipt it is anchored to. -/// -/// Bundling these keeps the fixture's gas, status, and output derived from a -/// single `ExecutionResult` — there is no second place that recomputes the -/// status string, so the dumped and validated values cannot drift. -pub(crate) struct FixtureInputs<'a> { - /// Effective `MegaETH` external environment (SALT buckets, oracle storage). - pub mega_env: MegaEnv, - /// The target transaction's execution result from the full replay. - pub result: &'a ExecutionResult, - /// The on-chain receipt this replay is checked against — the fidelity anchor. - pub anchor: OnchainAnchor, -} - -/// Deposit transaction type byte (EIP-2718 `0x7e`). Deposit transactions carry -/// MegaETH/Optimism-specific fields (mint, source hash, system flag) that the -/// EEST schema cannot represent, so they cannot be dumped. -const DEPOSIT_TX_TYPE: u8 = 0x7e; - -/// EIP-7702 set-code transaction type byte (`0x04`). The fixture builder does not -/// yet serialize the authorization list, so dropping it would silently change -/// execution (the delegations would not apply). Reject these explicitly rather -/// than emit a fixture whose isolated run diverges from the chain. -const EIP7702_TX_TYPE: u8 = 0x04; - -/// A fixture built from a replay, awaiting its `post` expectation. -/// -/// The `post` map is filled by [`finalize_and_write`] after re-executing the -/// isolated unit through `state-test`. -pub(crate) struct FixtureDraft { - /// The assembled unit (pre / env / transaction / megaEnv); `post` is empty. - unit: TestUnit, - /// Spec the transaction executed under — becomes the `post` map key. - spec: SpecName, - /// Gas observed during the full replay, cross-checked before writing. - actual_gas: u64, - /// Status observed during the full replay, cross-checked before writing. - actual_status: String, - /// Halt reason observed during the full replay (`None` unless the status is - /// `"halt"`), cross-checked before writing: two different halts typically - /// burn the same full gas with no output and no logs, so the coarse status - /// comparison alone cannot tell them apart. - actual_halt_reason: Option, - /// Output observed during the full replay, cross-checked before writing. - actual_output: Option, - /// Logs root observed during the full replay (already equal to the on-chain - /// receipt's logs root), cross-checked against the isolated run before writing. - actual_logs_root: B256, - /// Suite key (transaction hash) under which the unit is stored. - name: String, -} - -/// Build a fixture draft from the replayed target transaction. -/// -/// `db` must be read at the point *after* preceding transactions have committed -/// but *before* the target transaction commits, so that the pre-state closure -/// reflects exactly what the target transaction observed. -pub(crate) fn build_draft( - db: &DB, - evm_state: &EvmState, - chain_id: u64, - spec: MegaSpecId, - block: &Block, - target_tx: &Transaction, - inputs: FixtureInputs<'_>, -) -> Result -where - DB: DatabaseRef, - DB::Error: Display, -{ - let envelope: &OpTxEnvelope = &target_tx.inner.inner; - if envelope.ty() == DEPOSIT_TX_TYPE { - return Err(ReplayError::Other( - "--dump-fixture does not support deposit transactions".to_string(), - )); - } - if envelope.ty() == EIP7702_TX_TYPE { - return Err(ReplayError::Other( - "--dump-fixture does not support EIP-7702 (set-code) transactions: the \ - fixture builder does not serialize the authorization list" - .to_string(), - )); - } - - let actual_gas = inputs.result.gas_used(); - let actual_status = execution_status(inputs.result).to_string(); - let actual_halt_reason = halt_reason(inputs.result); - let actual_output = inputs.result.output().cloned(); - let actual_logs_root = state_test::utils::log_rlp_hash(inputs.result.logs()); - - // Fidelity gate: the local replay must reproduce the on-chain receipt's gas, - // success status, and logs. A mismatch means the replay executed under the - // wrong spec / hardfork config for this chain and block; self-validation - // cannot catch this, because the fixture is validated under the same spec it - // was dumped with. Refuse to build a fixture that does not match the chain. - // - // Logs are checked, not just inferred from gas: LOG gas depends on topic count - // and data length, never content, so two executions can burn identical gas yet - // emit different log payloads (e.g. a preceding-tx divergence that changes a - // value the target re-emits). The receipt's logs are already fetched, so the - // comparison is a single root equality. `finalize_and_write` then re-checks the - // isolated run's logs root against this same value, so any gas-, output-, or - // log-visible divergence from the zeroed L1 data fee aborts the dump. One - // channel stays open by construction: the isolated run's sender balance is - // shifted by the zeroed fee, so a contract that stores a balance-derived value - // bakes that shifted value into `post` (gas, status, output, and logs all - // still match). The fixture still self-validates and reproduces gas exactly. - let anchor = &inputs.anchor; - if actual_gas != anchor.gas_used { - return Err(ReplayError::Other(format!( - "replay gas {actual_gas} != on-chain receipt gas {}: the local replay does \ - not reproduce on-chain execution (likely a wrong spec or hardfork config \ - for chain {chain_id} at this block)", - anchor.gas_used - ))); - } - if inputs.result.is_success() != anchor.success { - return Err(ReplayError::Other(format!( - "replay status (success={}) != on-chain receipt status (success={}): the \ - local replay does not reproduce on-chain execution for chain {chain_id}", - inputs.result.is_success(), - anchor.success - ))); - } - if actual_logs_root != anchor.logs_root { - return Err(ReplayError::Other(format!( - "replay logs root {actual_logs_root} != on-chain receipt logs root {}: the \ - local replay emits different logs than the chain for chain {chain_id} \ - (same gas/status, different log contents)", - anchor.logs_root - ))); - } - - let pre = build_pre_state(db, evm_state)?; - let env = build_env(chain_id, block); - let transaction = build_transaction(target_tx)?; - let spec_name = SpecName::from_mega_spec(spec); - if spec_name == SpecName::Unknown { - return Err(ReplayError::Other(format!( - "--dump-fixture: spec {spec:?} has no fixture mapping" - ))); - } - - let unit = TestUnit { - info: None, - env, - pre, - post: BTreeMap::new(), - transaction, - out: None, - mega_env: Some(inputs.mega_env), - extra: BTreeMap::new(), - }; - - let name = format!("replay_{:#x}", target_tx.inner.inner.tx_hash()); - - Ok(FixtureDraft { - unit, - spec: spec_name, - actual_gas, - actual_status, - actual_halt_reason, - actual_output, - actual_logs_root, - name, - }) -} - -/// Re-execute the isolated unit through `state-test`, cross-check it against the -/// observed replay outcome, fill the `post` expectation, and write the fixture. -pub(crate) fn finalize_and_write(draft: FixtureDraft, path: &std::path::Path) -> Result<()> { - let executed = execute_unit_collect(&draft.unit, &draft.spec) - .map_err(|e| ReplayError::Other(format!("fixture self-execution failed: {e}")))?; - - // Cross-check the isolated execution against the full replay. These values - // are independent of the L1 data fee (which state-test zeroes), so they must - // match exactly; a mismatch means the fixture would not reproduce the replay. - if executed.gas_used != draft.actual_gas { - return Err(ReplayError::Other(format!( - "fixture not reproducible: gas {} != replay gas {} (incomplete pre-state?)", - executed.gas_used, draft.actual_gas - ))); - } - if executed.status != draft.actual_status { - return Err(ReplayError::Other(format!( - "fixture not reproducible: status {:?} != replay status {:?}", - executed.status, draft.actual_status - ))); - } - // A halted target needs more than the coarse status: two different halt - // reasons typically burn the same full gas with no output and no logs, so - // without this check the fixture would bake in the wrong failure mode. - if executed.halt_reason != draft.actual_halt_reason { - return Err(ReplayError::Other(format!( - "fixture not reproducible: halt reason {:?} != replay halt reason {:?}", - executed.halt_reason, draft.actual_halt_reason - ))); - } - if executed.output != draft.actual_output { - return Err(ReplayError::Other( - "fixture not reproducible: output differs from replay".to_string(), - )); - } - // Unlike gas/status/output, the logs root is sensitive to the L1 data fee: the - // full replay charges it (reducing the sender's balance), the isolated run - // zeroes it, so a log that reflects the sender's balance can diverge here even - // when everything else matches. `actual_logs_root` already equals the on-chain - // receipt's logs root, so this also pins the baked `post` logs to the chain. - if executed.logs_root != draft.actual_logs_root { - return Err(ReplayError::Other(format!( - "fixture not reproducible: logs root {} != replay logs root {} \ - (isolated run diverges from the full replay, e.g. via the L1 data fee)", - executed.logs_root, draft.actual_logs_root - ))); - } - - let mut unit = draft.unit; - unit.out = executed.output.clone(); - let test = - Test::for_dump(executed.state_root, executed.logs_root, executed.gas_used, executed.status); - unit.post = BTreeMap::from([(draft.spec, vec![test])]); - - let suite = TestSuite(BTreeMap::from([(draft.name, unit)])); - let json = serde_json::to_string_pretty(&suite) - .map_err(|e| ReplayError::Other(format!("failed to serialize fixture: {e}")))?; - // Write to a sibling temp file and rename so an interrupted write cannot - // truncate an existing fixture at `path` (e.g. a committed corpus entry - // being refreshed in place). - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, json).map_err(|e| { - ReplayError::Other(format!("failed to write fixture {}: {e}", tmp.display())) - })?; - std::fs::rename(&tmp, path).map_err(|e| { - ReplayError::Other(format!( - "failed to rename fixture {} -> {}: {e}", - tmp.display(), - path.display() - )) - }) -} - -/// Read the pre-execution values of every account in the target transaction's -/// read/write closure. -/// -/// Accounts that did not exist before the transaction (created during execution) -/// are omitted from `pre`. Storage is recorded as each touched slot's -/// `original_value`, which is the value the transaction first read. -fn build_pre_state(db: &DB, evm_state: &EvmState) -> Result> -where - DB: DatabaseRef, - DB::Error: Display, -{ - let mut pre = BTreeMap::new(); - for (address, account) in evm_state { - let Some(info) = db - .basic_ref(*address) - .map_err(|e| ReplayError::Other(format!("pre-state read for {address}: {e}")))? - else { - // The database reports no account. RPC-backed databases (AlloyDB) - // always materialize an account (possibly all-empty), so on a forked - // replay this branch never fires and accounts created by the target - // transaction enter `pre` as explicit empty accounts — equivalent - // under EIP-161 state clearing. A database that can signal - // nonexistence omits the account here. - continue; - }; - - let code = resolve_code(db, info.code_hash, info.code.as_ref())?; - - // BTreeMap (not HashMap) so storage slots serialize in a deterministic - // order, keeping the dumped fixture byte-reproducible. - let storage: BTreeMap = account - .storage - .iter() - .filter(|(_, slot)| !slot.original_value.is_zero()) - .map(|(key, slot)| (*key, slot.original_value)) - .collect(); - - pre.insert( - *address, - AccountInfo { balance: info.balance, code, nonce: info.nonce, storage }, - ); - } - Ok(pre) -} - -/// Resolve an account's bytecode bytes, fetching by hash if not materialized. -fn resolve_code( - db: &DB, - code_hash: B256, - code: Option<&mega_evm::revm::state::Bytecode>, -) -> Result -where - DB: DatabaseRef, - DB::Error: Display, -{ - if let Some(bytecode) = code { - return Ok(bytecode.original_byte_slice().to_vec().into()); - } - if code_hash == KECCAK256_EMPTY { - return Ok(Bytes::new()); - } - let bytecode = db - .code_by_hash_ref(code_hash) - .map_err(|e| ReplayError::Other(format!("code fetch for {code_hash}: {e}")))?; - Ok(bytecode.original_byte_slice().to_vec().into()) -} - -/// Build the EEST `env` from the replayed block header. -fn build_env(chain_id: u64, block: &Block) -> Env { - let header = &block.header; - Env { - current_chain_id: Some(U256::from(chain_id)), - current_coinbase: header.beneficiary(), - current_difficulty: header.difficulty(), - current_gas_limit: U256::from(header.gas_limit()), - current_number: U256::from(header.number()), - current_timestamp: U256::from(header.timestamp()), - current_base_fee: header.base_fee_per_gas().map(U256::from), - current_random: header.mix_hash().map(|h| U256::from_be_bytes(h.0)), - current_excess_blob_gas: header.excess_blob_gas().map(U256::from), - // Remaining fields are not needed to reproduce a single transaction. - previous_hash: None, - parent_timestamp: None, - parent_gas_used: None, - parent_gas_limit: None, - parent_base_fee: None, - parent_hash: None, - parent_uncle_hash: None, - parent_beacon_block_root: None, - parent_difficulty: None, - block_hashes: None, - ommers: None, - withdrawals: None, - current_beacon_root: None, - current_withdrawals_root: None, - parent_blob_gas_used: None, - parent_excess_blob_gas: None, - parent_target_blobs_per_block: None, - current_blob_gas_used: None, - } -} - -/// Build the EEST `transaction` (single-element index arrays) from the target tx. -fn build_transaction(target_tx: &Transaction) -> Result { - let sender = target_tx.inner.inner.signer(); - let tx: &OpTxEnvelope = &target_tx.inner.inner; - let tx_type = tx.ty(); - - // Legacy / EIP-2930 carry a gas price; fee-market types carry max fees. - // A type-0/1 envelope always carries a gas price, but if that invariant - // ever broke, falling back to 0 would bake a wrong price into a fixture - // that still self-validates — so refuse instead of guessing. - let (gas_price, max_fee_per_gas) = match tx_type { - 0 | 1 => { - let gas_price = tx.gas_price().ok_or_else(|| { - ReplayError::Other(format!( - "--dump-fixture: transaction type {tx_type} reports no gas price; \ - refusing to record a guessed price in the fixture" - )) - })?; - (Some(U256::from(gas_price)), None) - } - _ => (None, Some(U256::from(tx.max_fee_per_gas()))), - }; - - Ok(TransactionParts { - tx_type: Some(tx_type), - data: vec![tx.input().clone()], - gas_limit: vec![U256::from(tx.gas_limit())], - gas_price, - nonce: U256::from(tx.nonce()), - secret_key: B256::ZERO, - sender: Some(sender), - to: tx.to(), - value: vec![tx.value()], - max_fee_per_gas, - max_priority_fee_per_gas: tx.max_priority_fee_per_gas().map(U256::from), - initcodes: None, - access_lists: vec![tx.access_list().cloned()], - authorization_list: None, - blob_versioned_hashes: tx.blob_versioned_hashes().map(|h| h.to_vec()).unwrap_or_default(), - max_fee_per_blob_gas: tx.max_fee_per_blob_gas().map(U256::from), - }) -} diff --git a/bin/mega-evme/src/replay/hardforks.rs b/bin/mega-evme/src/replay/hardforks.rs deleted file mode 100644 index 011514f2b..000000000 --- a/bin/mega-evme/src/replay/hardforks.rs +++ /dev/null @@ -1,10 +0,0 @@ -use mega_evm::MegaHardforkConfig; - -/// Returns the hardfork configuration for a given chain ID. -/// -/// Delegates to the canonical per-chain schedule in `mega-evm` -/// ([`mega_evm::hardfork_schedule`]), which is the single source of truth for -/// `MegaETH` mainnet/testnet activation timestamps. -pub fn get_hardfork_config(chain_id: u64) -> MegaHardforkConfig { - mega_evm::hardfork_schedule(chain_id) -} diff --git a/bin/mega-evme/src/replay/mod.rs b/bin/mega-evme/src/replay/mod.rs index 8424e9fa2..5afe64fbb 100644 --- a/bin/mega-evme/src/replay/mod.rs +++ b/bin/mega-evme/src/replay/mod.rs @@ -4,11 +4,8 @@ //! by fetching them from an RPC endpoint and re-executing them. mod cmd; -mod fixture; -mod hardforks; pub use cmd::Cmd; -pub use hardforks::*; // Re-export EvmeError and Result from common module pub use crate::common::{EvmeError as ReplayError, Result, RpcArgs}; diff --git a/bin/mega-evme/src/run/README.md b/bin/mega-evme/src/run/README.md deleted file mode 100644 index a69df9a6e..000000000 --- a/bin/mega-evme/src/run/README.md +++ /dev/null @@ -1,492 +0,0 @@ -# mega-evme run - -A command-line tool for executing arbitrary EVM bytecode, similar to go-ethereum's `evm run` command. This tool provides a convenient way to test and debug EVM bytecode execution with full control over the execution environment. - -## Table of Contents - -- [Overview](#overview) -- [Basic Usage](#basic-usage) -- [Command Line Arguments](#command-line-arguments) -- [Features](#features) - - [State Management](#state-management) - - [SALT Bucket Capacity Configuration](#salt-bucket-capacity-configuration) - - [Execution Tracing](#execution-tracing) - - [Benchmarking](#benchmarking) - - [Contract Creation](#contract-creation) - - [Block Environment Configuration](#block-environment-configuration) - - [Fork Selection](#fork-selection) -- [State File Format](#state-file-format) -- [Examples](#examples) -- [Architecture](#architecture) - -## Overview - -The `mega-evme run` command executes EVM bytecode in a controlled environment with configurable parameters. It supports: - -- Arbitrary bytecode execution (call or create mode) -- State management (prestate loading and state dumping) -- SALT bucket capacity configuration -- Execution tracing with Geth-compatible output -- Performance benchmarking -- Full control over transaction and block environment - -## Basic Usage - -```bash -# Execute bytecode directly -mega-evme run 0x60016000526001601ff3 - -# Execute bytecode from file -mega-evme run --codefile contract.hex - -# Execute with input data -mega-evme run 0x60016000526001601ff3 --input 0x1234567890 - -# Execute with custom gas limit -mega-evme run 0x60016000526001601ff3 --gas 5000000 -``` - -## Command Line Arguments - -### Code Input - -- `CODE` (positional): EVM bytecode as hex string -- `--codefile `: Path to file containing bytecode (use `-` for stdin) - -### Transaction Configuration - -- `--create`: Execute in create mode (deploy contract) -- `--gas `: Gas limit (default: 10000000) -- `--price `: Gas price in wei (default: 0) -- `--priorityfee `: EIP-1559 priority fee -- `--tx-type `: Transaction type (0=Legacy, 1=EIP-2930, 2=EIP-1559) -- `--value `: Value to send with transaction (default: 0) -- `--sender

`: Transaction sender (default: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266) -- `--receiver
`: Transaction receiver (default: 0x0000000000000000000000000000000000000000) - -### Input Data - -- `--input `: Input data as hex string -- `--inputfile `: Path to file containing input data - -### State Management - -- `--prestate `: JSON file with initial state -- `--dump`: Dump final state after execution -- `--dump.output `: Output file for state dump (prints to console if not specified) -- `--sender.balance `: Initial balance to allocate to sender account - -### SALT Configuration - -- `--bucket-capacity `: Configure bucket capacity (can be specified multiple times) - - Format: `bucket_id:capacity` - - Example: `--bucket-capacity 123:1000000` - -### Tracing - -- `--tracer trace`: Enable Geth-compatible execution tracing -- `--trace.disable-memory`: Disable memory capture in traces -- `--trace.disable-stack`: Disable stack capture in traces -- `--trace.disable-storage`: Disable storage capture in traces -- `--trace.enable-return-data`: Enable return data capture in traces -- `--trace.output `: Output file for trace data - -### Debugging - -- `--statdump`: Display stack and memory information -- `--bench`: Benchmark execution time - -### Chain Configuration - -- `--spec `: EVM spec (default: `Rex2`) - - `MiniRex`: MegaETH MiniRex hardfork - - `Rex`: MegaETH Rex hardfork - - `Rex1`: MegaETH Rex1 hardfork - - `Rex2`: MegaETH Rex2 hardfork - - `Equivalence`: Optimism Isthmus compatibility mode -- `--chain-id `: Chain ID (default: 6342) - -### Block Environment - -- `--block.number `: Block number (default: 1) -- `--block.coinbase
`: Block beneficiary/coinbase address -- `--block.timestamp `: Block timestamp (default: 1) -- `--block.gaslimit `: Block gas limit (default: 30000000) -- `--block.basefee `: EIP-1559 base fee (default: 0) -- `--block.difficulty `: Block difficulty (default: 0) -- `--block.prevrandao `: Previous randao value (post-merge) -- `--block.blobexcessgas `: EIP-4844 blob excess gas (default: 0) - -## Features - -### State Management - -The tool supports loading initial state from JSON files and dumping final state after execution. - -#### Loading Prestate - -```bash -# Load initial state from JSON file -mega-evme run 0x60016000526001601ff3 --prestate initial_state.json -``` - -The prestate file should contain account information in Ethereum JSON format (see [State File Format](#state-file-format)). - -#### Dumping State - -```bash -# Dump state to console -mega-evme run 0x60016000526001601ff3 --dump - -# Save state to file -mega-evme run 0x60016000526001601ff3 --dump --dump.output final_state.json -``` - -#### Setting Sender Balance - -By default, the sender account has zero balance. You can allocate balance explicitly: - -```bash -# Allocate 1 ETH to sender -mega-evme run 0x60016000526001601ff3 --sender.balance 1000000000000000000 -``` - -**Note**: Balance is only allocated when `--sender.balance` is specified. This gives you explicit control over account balances. - -#### Round-Trip State Management - -You can dump state, modify it, and reload it: - -```bash -# 1. Execute and dump state -mega-evme run contract.hex --dump --dump.output state1.json - -# 2. Modify state1.json as needed - -# 3. Execute with modified state -mega-evme run next_contract.hex --prestate state1.json --dump --dump.output state2.json -``` - -### SALT Bucket Capacity Configuration - -Configure SALT bucket capacities for testing storage gas costs: - -```bash -# Configure single bucket -mega-evme run contract.hex --bucket-capacity 123:1000000 - -# Configure multiple buckets -mega-evme run contract.hex \ - --bucket-capacity 123:1000000 \ - --bucket-capacity 456:2000000 \ - --bucket-capacity 789:500000 -``` - -The bucket capacity configuration uses the format `bucket_id:capacity` where: -- `bucket_id`: 32-bit bucket identifier -- `capacity`: Current capacity in bytes - -This affects gas costs for storage operations in MiniRex hardfork. - -### Execution Tracing - -Enable Geth-compatible execution tracing to see opcode-level execution: - -```bash -# Basic tracing -mega-evme run 0x60016000526001601ff3 --tracer trace - -# Optimized tracing (disable memory and stack) -mega-evme run contract.hex \ - --tracer trace \ - --trace.disable-memory \ - --trace.disable-stack - -# Save trace to file -mega-evme run contract.hex --tracer trace --trace.output trace.json -``` - -Trace output includes: -- Gas costs per operation -- Stack state (unless disabled) -- Memory state (unless disabled) -- Storage changes (unless disabled) -- Return data (if enabled) - -### Benchmarking - -Measure execution time: - -```bash -mega-evme run contract.hex --bench -``` - -Output includes: -- Total execution time -- Gas used -- Execution result - -### Contract Creation - -Deploy contracts using create mode: - -```bash -# Deploy contract (code is init code) -mega-evme run --create 0x6080604052... - -# Deploy with constructor arguments -mega-evme run --create 0x6080604052... --input 0x0000000000000000000000001234... -``` - -In create mode: -- The bytecode is treated as init code -- Input data is appended to init code -- Returns the deployed contract address - -### Block Environment Configuration - -Configure block parameters for testing: - -```bash -mega-evme run contract.hex \ - --block.number 1000 \ - --block.timestamp 1234567890 \ - --block.coinbase 0x1111111111111111111111111111111111111111 \ - --block.gaslimit 50000000 \ - --block.basefee 1000000000 -``` - -This is useful for: -- Testing time-dependent contracts -- Simulating specific block conditions -- Testing EIP-1559 base fee mechanics - -### Spec Selection - -Choose between different EVM specifications: - -```bash -# Use MiniRex spec -mega-evme run contract.hex --spec MiniRex - -# Use Optimism Isthmus compatibility -mega-evme run contract.hex --spec Equivalence -``` - -Differences: -- **MiniRex**: Includes SALT dynamic gas costs, LOG cost increases, large contract support -- **Equivalence**: Optimism Isthmus compatibility, parallel execution support - -## State File Format - -State files use JSON format with Ethereum quantity encoding: - -```json -{ - "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": { - "balance": "0xde0b6b3a7640000", - "nonce": "0x1", - "code": "0x60806040...", - "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", - "storage": { - "0x0": "0x2a", - "0x1": "0x64" - } - }, - "0x0000000000000000000000000000000000100001": { - "balance": "0x0", - "nonce": "0x0", - "code": "0x", - "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", - "storage": {} - } -} -``` - -### Field Descriptions - -- **balance**: Account balance in wei (quantity format: 0x-prefixed hex without leading zeros) -- **nonce**: Transaction nonce (quantity format) -- **code**: Contract bytecode (hex string with 0x prefix) -- **codeHash**: Keccak256 hash of the code (hex string with 0x prefix, always 32 bytes) -- **storage**: Key-value map of storage slots (both keys and values use quantity format) - -### Format Notes - -- Uses Ethereum "quantity" format: `0x` prefix with no leading zeros (except `0x0` for zero) -- Empty code is represented as `"0x"` -- Empty storage is represented as `{}` -- All addresses are checksummed (though case-insensitive during parsing) - -## Examples - -### Example 1: Simple Execution - -Execute bytecode that returns value 1: - -```bash -mega-evme run 0x60016000526001601ff3 -# Output: 0x01 -``` - -Bytecode breakdown: -- `60 01`: PUSH1 0x01 -- `60 00`: PUSH1 0x00 -- `52`: MSTORE (store 0x01 at memory position 0) -- `60 01`: PUSH1 0x01 -- `60 1f`: PUSH1 0x1f (31 bytes offset) -- `f3`: RETURN (return 1 byte starting at position 31) - -### Example 2: State Persistence - -Create initial state, execute, and verify: - -```bash -# Create initial state file -cat > state.json << 'EOF' -{ - "0x1000000000000000000000000000000000000001": { - "balance": "0x1000000", - "nonce": "0x0", - "code": "0x", - "codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", - "storage": {} - } -} -EOF - -# Execute with prestate -mega-evme run 0x60016000526001601ff3 --prestate state.json --dump -``` - -### Example 3: Contract Deployment - -Deploy a simple storage contract: - -```bash -# Init code that deploys runtime code -mega-evme run --create 0x600a600c600039600a6000f3602a60005260206000f3 --dump -``` - -### Example 4: Testing with Tracing - -Debug contract execution with full traces: - -```bash -mega-evme run contract.hex \ - --tracer trace \ - --trace.enable-return-data \ - --trace.output trace.json \ - --gas 10000000 -``` - -### Example 5: SALT Bucket Testing - -Test storage operations with bucket capacity limits: - -```bash -# Set up account with code -cat > contract_state.json << 'EOF' -{ - "0x0000000000000000000000000000000000000001": { - "balance": "0x0", - "nonce": "0x0", - "code": "0x60aa60005560bb60015560cc600255", - "codeHash": "0xabcd...", - "storage": {} - } -} -EOF - -# Execute with bucket capacity limits -mega-evme run 0x00 \ - --receiver 0x0000000000000000000000000000000000000001 \ - --prestate contract_state.json \ - --bucket-capacity 1:1000 \ - --bucket-capacity 2:2000 \ - --dump -``` - -### Example 6: Benchmarking Gas Costs - -Compare gas usage between implementations: - -```bash -# Benchmark first version -mega-evme run contract_v1.hex --bench - -# Benchmark optimized version -mega-evme run contract_v2.hex --bench -``` - -## Architecture - -### Module Structure - -``` -run/ -├── mod.rs # Module exports and utility functions -│ # - load_code() / load_input(): Input loading -│ # - parse_bucket_capacity(): Bucket config parsing -│ # - StateDump: State serialization struct -│ # - AccountState: Account data struct -└── cmd.rs # Command implementation - # - Cmd: CLI argument struct - # - RunResult: Execution result struct - # - Main execution logic -``` - -### Key Components - -#### `Cmd` Struct - -Defines all CLI arguments using `clap`: -- Transaction configuration (gas, value, sender, etc.) -- State management (prestate, dump) -- Tracing options -- Block environment -- Fork selection -- SALT configuration - -#### `StateDump` / `AccountState` - -Handles state serialization/deserialization: -- **StateDump**: Root struct containing accounts map -- **AccountState**: Individual account data (balance, nonce, code, storage) -- Uses `alloy_serde` for proper Ethereum quantity format -- Implements `from_evm_state()` for conversion from REVM state - -#### Execution Flow - -1. **Input Loading**: Load bytecode and input data -2. **State Setup**: Create initial state (prestate + code + sender balance) -3. **Environment Configuration**: Setup cfg, block, tx, and external envs -4. **Execution**: Run transaction with optional tracing -5. **Output**: Print results, traces, and state dumps - -### Dependencies - -- **revm**: Core EVM execution engine -- **alloy-primitives**: Ethereum types (Address, U256, Bytes, B256) -- **alloy-serde**: Proper Ethereum serialization -- **revm-inspectors**: Execution tracing -- **clap**: CLI argument parsing -- **serde_json**: JSON serialization - -### Design Decisions - -1. **Explicit Balance Allocation**: Only allocate sender balance when `--sender.balance` is specified. This prevents implicit behavior and gives users full control. - -2. **Built-in Serialization**: Use `alloy-primitives`' built-in serde implementations instead of custom serialization. This ensures compatibility with Ethereum tooling and reduces maintenance burden. - -3. **Structured State**: Use `StateDump` and `AccountState` structs instead of manual JSON manipulation. This provides type safety and better error messages. - -4. **Separation of Concerns**: Keep CLI parsing (`Cmd`), execution logic, and state management separate for better testability and maintainability. - -5. **Flexible Output**: Support both console and file output for traces and state dumps, making it suitable for both interactive and automated use. - -## See Also - -- [Project Architecture](../../../../ARCH.md) -- [Main README](../../../../README.md) -- [Main README](../../../../README.md) diff --git a/bin/mega-evme/src/run/cmd.rs b/bin/mega-evme/src/run/cmd.rs index 90bc33402..9784de44e 100644 --- a/bin/mega-evme/src/run/cmd.rs +++ b/bin/mega-evme/src/run/cmd.rs @@ -6,7 +6,8 @@ use tracing::{debug, info, trace, warn}; use super::{load_hex, Result, RunError}; use crate::common::{ - print_execution_summary, print_execution_trace, EvmeOutcome, ExecutionSummary, + print_execution_summary, print_execution_trace, print_satin_report, EvmeOutcome, + ExecutionSummary, }; // Re-export TracerType from common module @@ -72,18 +73,16 @@ impl Cmd { self.prestate_args.create_initial_state(&sender, &self.rpc_args).await?; debug!(sender = %sender, "State initialized"); - // Deploy system contracts based on spec - let spec = self.env_args.spec_id()?; - state.deploy_system_contracts(spec); - debug!(spec = ?spec, "System contracts deployed"); + // Install Satin's predeploys + state.deploy_system_contracts()?; + debug!("System contracts deployed"); let pre_execution_nonce = state.basic_ref(sender)?.map(|acc| acc.nonce).unwrap_or(0); debug!(nonce = pre_execution_nonce, "Pre-execution nonce"); // Run-specific: If not in create mode, set the code at the receiver address if !self.tx_args.create() && !code.is_empty() { - let bytecode = Bytecode::new_raw_checked(code.clone()) - .unwrap_or_else(|_| Bytecode::new_legacy(code.clone())); + let bytecode = checked_run_bytecode(code.clone())?; debug!(receiver = %self.tx_args.receiver(), "Setting code at receiver address"); state.set_account_code(self.tx_args.receiver(), bytecode); } @@ -107,19 +106,24 @@ impl Cmd { // Create EVM context and execute transaction let evm_context = self.env_args.create_evm_context(&mut state)?; let start = Instant::now(); - let (exec_result, evm_state, trace_data) = + let (exec_result, mut evm_state, trace_data, mut satin) = self.trace_args.execute_transaction(evm_context, tx)?; + if self.dump_args.dump { + crate::materialize_dumped_code(&state, &mut evm_state)?; + } + satin.limits_override = self.env_args.limits_override_in_force()?; let exec_time = start.elapsed(); // Log execution result + let gas_used = exec_result.tx_gas_used(); match &exec_result { - ExecutionResult::Success { gas_used, .. } => { + ExecutionResult::Success { .. } => { info!(gas_used, "Execution succeeded"); } - ExecutionResult::Revert { gas_used, .. } => { + ExecutionResult::Revert { .. } => { warn!(gas_used, "Execution reverted"); } - ExecutionResult::Halt { reason, gas_used } => { + ExecutionResult::Halt { reason, .. } => { warn!(?reason, gas_used, "Execution halted"); } } @@ -130,6 +134,7 @@ impl Cmd { state: evm_state, exec_time, trace_data, + satin, }; // Step 4: Output results (including state dump if requested) @@ -151,6 +156,7 @@ impl Cmd { if self.output_args.json { let mut summary = ExecutionSummary::from_result(&outcome.exec_result, contract_address); summary.fill_trace_and_dump(outcome, &self.trace_args, &self.dump_args)?; + summary.satin = Some(outcome.satin.clone()); println!( "{}", serde_json::to_string_pretty(&summary).expect("failed to serialize output") @@ -158,6 +164,7 @@ impl Cmd { } else { // Human-readable summary print_execution_summary(&outcome.exec_result, contract_address, outcome.exec_time); + print_satin_report(&outcome.satin); print_execution_trace( outcome.trace_data.as_deref(), @@ -172,3 +179,29 @@ impl Cmd { Ok(()) } } + +/// Bytecode placed at the receiver. +/// +/// A designation that is not valid EIP-7702 bytecode is an error, rather than code to execute. +fn checked_run_bytecode(code: alloy_primitives::Bytes) -> Result { + Bytecode::new_raw_checked(code).map_err(RunError::InvalidBytecode) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_run_bytecode_rejects_a_broken_delegation() { + let err = checked_run_bytecode(alloy_primitives::Bytes::from_static(&[0xef, 0x01])) + .expect_err("a truncated EIP-7702 designation is not bytecode"); + assert!(matches!(err, RunError::InvalidBytecode(_))); + } + + #[test] + fn test_run_bytecode_accepts_ordinary_code() { + let bytecode = checked_run_bytecode(alloy_primitives::Bytes::from_static(&[0x00])) + .expect("STOP is valid code"); + assert_eq!(bytecode.original_bytes().as_ref(), &[0x00]); + } +} diff --git a/bin/mega-evme/src/tx/cmd.rs b/bin/mega-evme/src/tx/cmd.rs index 6e2d43390..ce54b28a9 100644 --- a/bin/mega-evme/src/tx/cmd.rs +++ b/bin/mega-evme/src/tx/cmd.rs @@ -12,7 +12,7 @@ use tracing::{debug, info, trace, warn}; use crate::common::{ load_hex, op_receipt_to_tx_receipt, print_execution_summary, print_execution_trace, - print_receipt, DecodedRawTx, EvmeError, EvmeOutcome, ExecutionSummary, + print_receipt, print_satin_report, DecodedRawTx, EvmeError, EvmeOutcome, ExecutionSummary, }; use super::Result; @@ -63,19 +63,22 @@ impl Cmd { // Step 1: Create transaction info!("Creating transaction"); - let tx = if let Some(ref raw) = self.raw { + let (tx, tx_hash) = if let Some(ref raw) = self.raw { let raw_bytes = load_hex(Some(raw.clone()), None)?.unwrap_or_default(); let decoded = DecodedRawTx::from_raw(raw_bytes)?.override_tx_env(&self.tx_args)?; - if decoded.tx_env.chain_id != Some(chain_id) { + if let Some(decoded_chain_id) = decoded.tx_env.chain_id.filter(|id| *id != chain_id) { warn!( chain_id, - decoded_chain_id = decoded.tx_env.chain_id, - "Raw transaction chain_id does not match the configured chain_id" + decoded_chain_id, + "Raw transaction carries another chain's id, which Satin refuses" ); } - decoded.into_tx() + let tx_hash = decoded.tx_hash(); + (decoded.into_tx(), tx_hash) } else { - self.tx_args.create_tx(chain_id)? + let tx = self.tx_args.create_tx(chain_id)?; + let tx_hash = self.tx_args.tx_hash(&tx); + (tx, tx_hash) }; debug!( @@ -92,7 +95,7 @@ impl Cmd { self.prestate_args.create_initial_state(&sender, &self.rpc_args).await?; debug!(sender = %sender, "State initialized"); - state.deploy_system_contracts(spec); + state.deploy_system_contracts()?; debug!(spec = ?spec, "System contracts deployed"); let pre_execution_nonce = state.basic_ref(sender)?.map(|acc| acc.nonce).unwrap_or(0); @@ -102,19 +105,24 @@ impl Cmd { info!("Executing transaction"); let evm_context = self.env_args.create_evm_context(&mut state)?; let start = Instant::now(); - let (exec_result, evm_state, trace_data) = + let (exec_result, mut evm_state, trace_data, mut satin) = self.trace_args.execute_transaction(evm_context, tx.clone())?; + if self.dump_args.dump { + crate::materialize_dumped_code(&state, &mut evm_state)?; + } + satin.limits_override = self.env_args.limits_override_in_force()?; let exec_time = start.elapsed(); // Log execution result + let gas_used = exec_result.tx_gas_used(); match &exec_result { - ExecutionResult::Success { gas_used, .. } => { + ExecutionResult::Success { .. } => { info!(gas_used, "Execution succeeded"); } - ExecutionResult::Revert { gas_used, .. } => { + ExecutionResult::Revert { .. } => { warn!(gas_used, "Execution reverted"); } - ExecutionResult::Halt { reason, gas_used } => { + ExecutionResult::Halt { reason, .. } => { warn!(?reason, gas_used, "Execution halted"); } } @@ -125,11 +133,12 @@ impl Cmd { state: evm_state, exec_time, trace_data, + satin, }; // Step 4: Output results (including state dump if requested) trace!("Writing output results"); - self.output_results(&outcome, &tx)?; + self.output_results(&outcome, &tx, tx_hash)?; // Step 5: Persist the RPC cache (clean-exit only). cache_store.persist()?; @@ -138,7 +147,12 @@ impl Cmd { } /// Output execution results - fn output_results(&self, outcome: &EvmeOutcome, tx: &MegaTransaction) -> Result<()> { + fn output_results( + &self, + outcome: &EvmeOutcome, + tx: &MegaTransaction, + tx_hash: Option, + ) -> Result<()> { let tx_type = MegaTxType::try_from(tx.base.tx_type) .map_err(|_| EvmeError::UnsupportedTxType(tx.base.tx_type))?; let sender = tx.base.caller; @@ -164,15 +178,17 @@ impl Cmd { receiver, contract_address, effective_gas_price, - outcome.exec_result.gas_used(), - None, + outcome.exec_result.tx_gas_used(), + tx_hash, None, 0, + 0, ); if self.output_args.json { let mut summary = ExecutionSummary::from_result(&outcome.exec_result, contract_address); summary.fill_trace_and_dump(outcome, &self.trace_args, &self.dump_args)?; + summary.satin = Some(outcome.satin.clone()); summary.receipt = Some(serde_json::to_value(&receipt).expect("failed to serialize receipt")); println!( @@ -182,6 +198,7 @@ impl Cmd { } else { // Human-readable summary print_execution_summary(&outcome.exec_result, contract_address, outcome.exec_time); + print_satin_report(&outcome.satin); print_receipt(&receipt); diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs new file mode 100644 index 000000000..1fd09502f --- /dev/null +++ b/bin/mega-evme/tests/block_replay.rs @@ -0,0 +1,647 @@ +//! `mega-evme replay --block`: whole blocks on either engine, compared with the chain, on the +//! recorded mainnet blocks of `tests/fixtures/blocks` (see `common/blocks.rs`). +#![cfg(feature = "legacy")] + +mod common; + +use std::path::Path; + +use alloy_primitives::{Address, B256, U256}; +use common::blocks::{ + block_path, cache_copy, cache_copy_for_satin, code_of, factory_account, fixtures, is_deposit, + overhead_slot, read_block, refused_for_block_gas, run_evme, satin_genesis, set_overhead, + timestamp_of, write_block, BLOCKS, FACTORY, L1_BLOCK, +}; +use mega_evm::{system::MEGA_SYSTEM_ADDRESS, MegaSpecId, ProtocolLimits}; +use serde_json::Value; + +fn blocks_of(records: &[Value]) -> Vec<&Value> { + records.iter().filter(|r| r["kind"] == "block").collect() +} + +/// `replay --block N --block-cache DIR`, with `extra` arguments. +fn replay(number: u64, dir: &Path, extra: &[&str]) -> common::blocks::Run { + let mut args = vec![ + "replay".to_string(), + "--block".to_string(), + number.to_string(), + "--block-cache".to_string(), + dir.to_str().unwrap().to_string(), + "--json".to_string(), + ]; + args.extend(extra.iter().map(|s| s.to_string())); + run_evme(&args) +} + +/// The legacy leg replays each recorded block exactly as the chain executed it: every +/// transaction's status, gas used, cumulative gas used and logs, and the receipts root. +/// Offline, a replay writes nothing to the cache. +#[test] +fn test_the_legacy_leg_replays_recorded_blocks_as_the_chain_did() { + let cache = cache_copy(); + let before = std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(); + for number in BLOCKS { + let run = replay(number, cache.path(), &["--verify"]); + assert_eq!(run.code, 0, "block {number}: {}", run.stderr); + let records = run.records(); + let blocks = blocks_of(&records); + assert_eq!(blocks.len(), 1); + let block = blocks[0]; + assert_eq!(block["engine"], "legacy"); + assert_eq!(block["spec"], "Rex6"); + assert_eq!(block["matches_chain"], true, "block {number}: {block}"); + assert_eq!(block["receipts_root"], block["chain_receipts_root"]); + assert_eq!(block["rpc_reads"], 0); + let txs: Vec<_> = records.iter().filter(|r| r["kind"] == "tx").collect(); + assert_eq!(txs.len(), block["transactions"].as_u64().unwrap() as usize); + assert!(txs.iter().all(|tx| tx["differs"] == Value::Array(vec![])), "block {number}"); + assert!(txs.iter().all(|tx| tx.get("satin").is_none()), "a legacy record has no satin"); + } + // The failed transaction of 26400007 failed in the replay too. + let records = replay(26_400_007, cache.path(), &[]).records(); + assert!(records.iter().any(|r| r["kind"] == "tx" && r["chain"]["status"] == "failure")); + assert_eq!(std::fs::read(block_path(cache.path(), BLOCKS[0])).unwrap(), before); +} + +/// A Satin replay of a recorded block reads what the recording lacks: offline, the block fails +/// and names the first of them it met, and the exit code is 1. A counterfactual block is not +/// Satin's activation block, so it reads no predeploy, and its miss is the L1 fee overhead, which +/// the pre-block read of the L1 block info reads beside the fee scalars the recording holds set. +/// Satin's activation block — under a genesis file that activates Satin at the block, whose +/// parent came a second earlier — checks the predeploys first, and its miss is the EIP-7997 +/// factory. +#[test] +fn test_a_read_the_recording_lacks_fails_the_block_offline() { + let refusal = |dir: &Path, args: &[&str]| { + let run = replay(BLOCKS[0], dir, args); + assert_eq!(run.code, 1); + let error = run.records()[0]["error"].as_str().unwrap().to_lowercase(); + assert!(error.contains("no rpc to read it"), "{error}"); + error + }; + + let cache = cache_copy(); + let error = refusal(cache.path(), &["--override.spec", "Satin"]); + assert!(error.contains(&format!("storage {L1_BLOCK:#x}[{}]", overhead_slot())), "{error}"); + + let dir = tempfile::tempdir().unwrap(); + let mut block = read_block(cache.path(), BLOCKS[0]); + let timestamp = timestamp_of(&block); + block.parent_timestamp = Some(timestamp - 1); + write_block(cache.path(), BLOCKS[0], &block); + let genesis = satin_genesis(dir.path(), mega_evm::MAINNET_CHAIN_ID, timestamp); + let error = refusal(cache.path(), &["--genesis", &genesis]); + assert!(error.contains(&format!("account {FACTORY:#x}")), "{error}"); +} + +/// The Satin counterfactual of the recorded blocks: every block runs, a transaction is refused +/// only for the block gas it declared ([`refused_for_block_gas`]), every record carries the +/// legacy columns, every record of what ran adds `satin`, and `--verify` reports the difference +/// from the chain with exit code 2. +#[test] +fn test_the_satin_counterfactual_of_recorded_blocks() { + let cache = cache_copy_for_satin(); + for number in BLOCKS { + let run = replay(number, cache.path(), &["--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + let records = run.records(); + let block = blocks_of(&records)[0]; + assert_eq!(block["engine"], "satin"); + assert_eq!(block["spec"], "Satin"); + assert_eq!(block["refused"], refused_for_block_gas(&records)); + assert_eq!(block["matches_chain"], false); + assert!(block["satin"]["history_gas"].as_u64().unwrap() > 0); + } + + let legacy = replay(BLOCKS[0], cache.path(), &[]).records(); + let run = replay(BLOCKS[0], cache.path(), &["--override.spec", "Satin", "--verify"]); + assert_eq!(run.code, 2, "a counterfactual differs from the chain"); + let satin = run.records(); + assert_eq!(legacy.len(), satin.len()); + for (legacy, satin) in legacy.iter().zip(&satin) { + let (Value::Object(l), Value::Object(s)) = (legacy, satin) else { panic!() }; + for key in l.keys() { + assert!(s.contains_key(key), "the Satin record lacks the legacy column {key}"); + } + // A refused transaction ran nothing and has no ledgers. + if satin["status"] != "refused" { + assert!(s.contains_key("satin"), "{satin}"); + } + } +} + +/// Whatever the L1 fee overhead holds, the Satin rows of the recorded blocks are the same: the +/// blocks' fee scalars are set, so no transaction is priced with it, and the pre-block read that +/// reads it is no transaction. +#[test] +fn test_the_overhead_does_not_change_the_satin_rows() { + let zero = cache_copy_for_satin(); + let set = cache_copy_for_satin(); + for number in BLOCKS { + let mut block = read_block(set.path(), number); + set_overhead(&mut block, U256::from(188)); + write_block(set.path(), number, &block); + } + for number in BLOCKS { + let rows = |dir: &Path| { + let run = replay(number, dir, &["--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + run.records() + }; + assert_eq!(rows(zero.path()), rows(set.path()), "block {number}"); + } +} + +/// [S18] A block fetched over RPC replays as the chain did, is written to the block cache with +/// what its replay read beyond the trace, and then replays offline from the cache. The mock +/// serves the recorded responses, and the trace is the recorded pre-state as one transaction's +/// sighting. The Satin replay, a counterfactual and so no activation block, reads one slot the +/// recording lacks, the L1 fee overhead its pre-block read of the L1 block info reads, and the +/// cache keeps it; it reads no predeploy, so the cache holds no EIP-7997 factory. +/// +/// Expected values: independent (the chain's own receipts, and the one pre-block read). +#[tokio::test(flavor = "multi_thread")] +async fn test_a_block_fetched_over_rpc_is_cached_and_replays_offline() { + let number = BLOCKS[2]; + let server = recorded_chain(number, Parent::Block).await; + let cache = tempfile::tempdir().unwrap(); + let uri = server.uri(); + + let run = replay(number, cache.path(), &["--rpc", &uri, "--verify"]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!(blocks_of(&run.records())[0]["matches_chain"], true); + assert!(block_path(cache.path(), number).exists(), "the fetched block is cached"); + + let run = replay(number, cache.path(), &["--rpc", &uri, "--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 1, "the L1 fee overhead came over RPC"); + + // Offline now: the cache holds the block, and the overhead the Satin replay read. + drop(server); + let run = replay(number, cache.path(), &["--verify"]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!(blocks_of(&run.records())[0]["matches_chain"], true); + let run = replay(number, cache.path(), &["--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!(blocks_of(&run.records())[0]["rpc_reads"], 0); + let cached = read_block(cache.path(), number).prestate; + assert!(!cached.accounts.contains_key(&FACTORY), "no predeploy was read"); + assert_eq!(cached.accounts[&L1_BLOCK].storage.get(&overhead_slot()), Some(&U256::ZERO)); +} + +/// `--override.limits` replays a Satin block under other protocol limits: the fields it names +/// replace the spec's, and every other stays. At the spec's own values it changes nothing; under a +/// transaction data-size limit of what the block's L1 attributes deposit keeps, every transaction +/// that keeps more without the override is held to it — stopped where it crosses it, or refused at +/// validation when its body alone does — but the protocol's own, which no per-transaction limit +/// holds, and which run past it; a block data budget of one byte packs the first transaction and +/// refuses every later one. +#[test] +fn test_an_override_replays_a_satin_block_under_other_limits() { + let cache = cache_copy_for_satin(); + let number = BLOCKS[0]; + let replay_under = |limits: Option<&str>| -> (Vec, Value) { + let mut args = vec!["--override.spec", "Satin"]; + if let Some(limits) = limits { + args.extend(["--override.limits", limits]); + } + let run = replay(number, cache.path(), &args); + assert_eq!(run.code, 0, "{}", run.stderr); + let records = run.records(); + let block = blocks_of(&records)[0].clone(); + (records.into_iter().filter(|r| r["kind"] == "tx").collect(), block) + }; + + let (counterfactual, plain) = replay_under(None); + assert!(plain["satin"].get("limits_override").is_none(), "{}", plain["satin"]); + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let defaults = serde_json::to_string(&satin).unwrap(); + let (on_the_defaults, overridden) = replay_under(Some(&defaults)); + assert_eq!(on_the_defaults, counterfactual, "it runs on the spec's limits"); + assert_eq!( + overridden["satin"]["limits_override"], + serde_json::to_value(satin).unwrap(), + "the block's record says what it ran under" + ); + let dir = cache.path().to_str().unwrap(); + let block = number.to_string(); + let args = ["replay", "--block", &block, "--block-cache", dir, "--override.spec", "Satin"]; + let human = run_evme(&[&args[..], &["--override.limits", &defaults]].concat()); + assert_eq!(human.code, 0, "{}", human.stderr); + assert!(human.stdout.contains(", limits overridden]"), "{}", human.stdout); + assert!(!run_evme(&args).stdout.contains("limits overridden")); + assert!(counterfactual.iter().all(|tx| tx["satin"]["limit_exceeded"].is_null())); + + let recorded = read_block(cache.path(), number); + let sent = recorded.block["transactions"].as_array().unwrap(); + let limit = counterfactual[0]["satin"]["data_size"].as_u64().unwrap(); + let (stopped, stopped_block) = + replay_under(Some(&format!(r#"{{"txRuntimeLimits":{{"txDataSizeLimit":{limit}}}}}"#))); + assert_eq!( + stopped_block["satin"]["limits_override"]["txRuntimeLimits"]["txDataSizeLimit"], + limit + ); + let (mut protocols, mut others) = (0, 0); + for ((tx, sent), unlimited) in stopped.iter().zip(sent).zip(&counterfactual) { + let from: Address = sent["from"].as_str().unwrap().parse().unwrap(); + let kept = unlimited["satin"]["data_size"].as_u64(); + if from == MEGA_SYSTEM_ADDRESS { + // The protocol's transactions carry gas limits close to the block's, so the gas the + // block has left may refuse one, as it may without the override; no limit does. + if tx["status"] == "refused" { + let reason = tx["reason"].as_str().unwrap(); + assert!(reason.contains("blocks available gas"), "{reason}"); + continue; + } + assert!( + tx["satin"]["limit_exceeded"].is_null(), + "the protocol's transaction {} is held to no limit", + tx["index"] + ); + if tx["satin"]["data_size"].as_u64().unwrap() > limit { + protocols += 1; + } + } else if kept.is_some_and(|kept| kept > limit) { + others += 1; + if tx["status"] == "refused" { + let reason = tx["reason"].as_str().unwrap(); + assert!(reason.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{reason}"); + continue; + } + let stop = &tx["satin"]["limit_exceeded"]; + assert_eq!(stop["kind"], "data_size", "{tx}"); + assert_eq!(stop["limit"], limit, "{tx}"); + assert!(stop["used"].as_u64().unwrap() > limit, "{tx}"); + } + } + assert!(protocols > 0 && others > 0, "{protocols} {others}"); + + // The budget refuses every transaction after the one that reaches it but the protocol's own: + // a Mega System Transaction is never refused by it. + let (packed, block) = replay_under(Some(r#"{"blockTxsDataLimit":1}"#)); + let is_protocols = |index: usize| { + let from: Address = sent[index]["from"].as_str().unwrap().parse().unwrap(); + from == MEGA_SYSTEM_ADDRESS + }; + let protocol_txs = (1..packed.len()).filter(|&index| is_protocols(index)).count(); + assert!(protocol_txs > 0, "the block holds Mega System Transactions"); + assert_eq!(block["refused"], block["transactions"].as_u64().unwrap() - 1 - protocol_txs as u64,); + assert_eq!(packed[0], counterfactual[0], "the transaction that reaches the budget is packed"); + for (index, tx) in packed.iter().enumerate().skip(1) { + if is_protocols(index) { + assert_ne!(tx["status"], "refused", "the budget does not refuse the protocol's: {tx}"); + continue; + } + assert_eq!(tx["status"], "refused", "{tx}"); + let reason = tx["reason"].as_str().unwrap(); + assert!(reason.contains("Block transactions data limit reached"), "{reason}"); + } +} + +/// `--override.limits` is Satin's: a block the legacy engine replays is refused with it, and +/// the replay exits with code 1. +#[test] +fn test_an_override_refuses_a_legacy_block() { + let cache = cache_copy(); + let run = replay(BLOCKS[0], cache.path(), &["--override.limits", "{}"]); + assert_eq!(run.code, 1, "{}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("--override.limits applies to Satin only"), "{error}"); +} + +/// A genesis file of mainnet activating Satin at `satin_time`, in `dir`. +fn mainnet_genesis(dir: &tempfile::TempDir, satin_time: u64) -> String { + genesis_of(dir, mega_evm::MAINNET_CHAIN_ID, satin_time) +} + +/// [`mainnet_genesis`] for chain `chain_id`. +fn genesis_of(dir: &tempfile::TempDir, chain_id: u64, satin_time: u64) -> String { + satin_genesis(dir.path(), chain_id, satin_time) +} + +/// A genesis file decides which of its chain's blocks run Satin, and the schedule they run under: +/// a recorded mainnet block, legacy by the engine's table, runs on Satin from a file's `satinTime` +/// of zero, held to Satin's limits, which no file names, as the replay without the file is. A block +/// before the file's `satinTime` would run on the legacy engine, which runs a chain on its own +/// table and knows nothing of the file: it is refused, and so is one a forced legacy spec runs, +/// one a forced Satin runs before the file's `satinTime`, and a block of another chain. +#[test] +fn test_a_genesis_file_runs_its_chains_blocks_on_its_schedule() { + let cache = cache_copy_for_satin(); + let dir = tempfile::tempdir().unwrap(); + + let run = replay(BLOCKS[0], cache.path(), &["--genesis", &mainnet_genesis(&dir, 0)]); + assert_eq!(run.code, 0, "{}", run.stderr); + let records = run.records(); + let block = blocks_of(&records)[0]; + assert_eq!(block["engine"], "satin"); + assert!(block["satin"].get("limits_override").is_none(), "{}", block["satin"]); + let txs: Vec<_> = records.iter().filter(|r| r["kind"] == "tx").collect(); + assert!(!txs.is_empty()); + assert!( + txs.iter().all(|tx| tx["satin"]["limit_exceeded"].is_null()), + "no transaction of the block comes near Satin's limits" + ); + + let later = mainnet_genesis(&dir, u64::MAX); + let forced = mainnet_genesis(&dir, 0); + for args in [&["--genesis", &later][..], &["--genesis", &forced, "--override.spec", "Rex6"]] { + let run = replay(BLOCKS[0], cache.path(), args); + assert_eq!(run.code, 1, "{args:?}: {}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("--genesis applies to Satin blocks only"), "{args:?}: {error}"); + } + + let run = replay(BLOCKS[0], cache.path(), &["--genesis", &later, "--override.spec", "Satin"]); + assert_eq!(run.code, 1, "{}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + assert!( + error.contains(&format!("--genesis activates Satin at timestamp {}", u64::MAX)), + "{error}" + ); + + // A block of another chain is refused for its chain, before the engine the table gives it. + let run = replay(BLOCKS[0], cache.path(), &["--genesis", &genesis_of(&dir, 6342, 0)]); + assert_eq!(run.code, 1, "{}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + let expected = format!( + "--genesis configures chain 6342, and the run is on chain {}", + mega_evm::MAINNET_CHAIN_ID + ); + assert!(error.contains(&expected), "{error}"); +} + +/// The reason the Satin engine refuses a transaction of a block that admits only deposits. +const ACTIVATION_REFUSAL: &str = "non-deposit transaction in fork activation block"; + +/// Checks the transaction records of a replay of the recorded `block` as its activation block: +/// every deposit runs, and every other transaction — the protocol's legacy transactions +/// included — is refused for the rule. +fn assert_refused_as_activation_block(block: &mega_evme::block::CachedBlock, records: &[Value]) { + let txs: Vec<_> = records.iter().filter(|r| r["kind"] == "tx").collect(); + let deposits = (0..txs.len()).filter(|&i| is_deposit(block, i)).count(); + assert!( + deposits > 0 && deposits < txs.len(), + "the block holds deposits and other transactions" + ); + for (index, tx) in txs.iter().enumerate() { + if is_deposit(block, index) { + assert_ne!(tx["status"], "refused", "deposit {index} runs: {tx}"); + } else { + assert_eq!(tx["status"], "refused", "transaction {index}: {tx}"); + let reason = tx["reason"].as_str().unwrap(); + assert!(reason.contains(ACTIVATION_REFUSAL), "transaction {index}: {reason}"); + } + } + assert_eq!(blocks_of(records)[0]["refused"], txs.len() - deposits); +} + +/// [S1.8] [S21.12] [S1] A replayed block is told whether it admits only deposits as a node is: +/// from its schedule and its parent's timestamp, which the block cache keeps beside the block. +/// Under a genesis file that activates Satin at the recorded block's own timestamp, the block +/// whose parent came a second earlier is Satin's activation block: its deposits run and every +/// other transaction is refused. With its parent at the block's own timestamp Satin is active at +/// both, and nothing is refused for the activation, only for the block gas a transaction declared +/// ([`refused_for_block_gas`]). Without the parent's timestamp and without `--rpc` the tool +/// cannot tell, and the block fails saying why. +/// +/// Expected values: independent. +#[test] +fn test_a_replayed_activation_block_refuses_its_user_transactions() { + let cache = cache_copy_for_satin(); + let dir = tempfile::tempdir().unwrap(); + let number = BLOCKS[0]; + let recorded = read_block(cache.path(), number); + let timestamp = timestamp_of(&recorded); + let genesis = satin_genesis(dir.path(), mega_evm::MAINNET_CHAIN_ID, timestamp); + let with_parent_at = |parent_timestamp: Option| { + let mut block = read_block(cache.path(), number); + block.parent_timestamp = parent_timestamp; + write_block(cache.path(), number, &block); + replay(number, cache.path(), &["--genesis", &genesis]) + }; + + let run = with_parent_at(Some(timestamp - 1)); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_refused_as_activation_block(&recorded, &run.records()); + + let run = with_parent_at(Some(timestamp)); + assert_eq!(run.code, 0, "{}", run.stderr); + let records = run.records(); + assert_eq!( + blocks_of(&records)[0]["refused"], + refused_for_block_gas(&records), + "the block after admits every transaction its gas fits" + ); + + let run = with_parent_at(None); + assert_eq!(run.code, 1, "{}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("depends on its parent's timestamp"), "{error}"); + assert!(error.contains("replay it once with '--rpc'"), "it says how to recover: {error}"); +} + +/// What a [`recorded_chain`] answers for the parent block's header. +enum Parent { + /// The recorded block's own header, at the block's own timestamp. + Block, + /// A header at this timestamp. + At(u64), + /// No block: the endpoint does not have the parent. + Missing, +} + +/// A mock of the chain serving the recorded `number` block, its receipts, its pre-state as a +/// trace, and the reads Satin's pre-block changes make beyond it; the parent block's header is +/// what `parent` says. +async fn recorded_chain(number: u64, parent: Parent) -> wiremock::MockServer { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + let recorded = read_block(fixtures(), number); + let mut trace_accounts = serde_json::Map::new(); + for (address, account) in &recorded.prestate.accounts { + let mut entry = serde_json::json!({ "balance": account.balance, "nonce": account.nonce }); + if let Some(hash) = account.code_hash { + entry["code"] = Value::String(alloy_primitives::hex::encode_prefixed(code_of(hash))); + } + let storage: serde_json::Map<_, _> = account + .storage + .iter() + .map(|(slot, value)| (slot.to_string(), Value::String(B256::from(*value).to_string()))) + .collect(); + entry["storage"] = Value::Object(storage); + trace_accounts.insert(address.to_string(), entry); + } + let first_tx = recorded.block["transactions"][0]["hash"].clone(); + let trace = serde_json::json!([{ "txHash": first_tx, "result": trace_accounts }]); + + let server = MockServer::start().await; + let respond = |method: &'static str, result: Value| { + Mock::given(matchers::method("POST")) + .and(matchers::body_string_contains(format!("\"{method}\""))) + .respond_with(move |req: &wiremock::Request| { + let body: Value = serde_json::from_slice(&req.body).unwrap(); + ResponseTemplate::new(200).set_body_json( + serde_json::json!({ "jsonrpc": "2.0", "id": body["id"], "result": result }), + ) + }) + }; + let parent = match parent { + Parent::Block => None, + Parent::At(timestamp) => { + let mut header = recorded.block.clone(); + header["number"] = format!("0x{:x}", number - 1).into(); + header["timestamp"] = format!("0x{timestamp:x}").into(); + Some(header) + } + Parent::Missing => Some(Value::Null), + }; + if let Some(parent) = parent { + Mock::given(matchers::method("POST")) + .and(matchers::body_string_contains("\"eth_getBlockByNumber\"")) + .and(matchers::body_string_contains(format!("\"0x{:x}\"", number - 1))) + .respond_with(move |req: &wiremock::Request| { + let body: Value = serde_json::from_slice(&req.body).unwrap(); + ResponseTemplate::new(200).set_body_json( + serde_json::json!({ "jsonrpc": "2.0", "id": body["id"], "result": parent }), + ) + }) + .with_priority(1) + .mount(&server) + .await; + } + respond("eth_chainId", serde_json::json!("0x10e6")).mount(&server).await; + respond("eth_getBlockByNumber", recorded.block.clone()).mount(&server).await; + respond("eth_getBlockReceipts", recorded.receipts.clone()).mount(&server).await; + respond("debug_traceBlockByNumber", trace).mount(&server).await; + // The parent state of what the trace does not hold: the factory, as the chain holds it + // ([`factory_account`]), which Satin's activation block checks, and the L1 fee overhead, which + // is zero. + let factory = factory_account(); + let per_account = |method: &'static str, factory_value: Value, other: Value| { + Mock::given(matchers::method("POST")) + .and(matchers::body_string_contains(format!("\"{method}\""))) + .respond_with(move |req: &wiremock::Request| { + let body: Value = serde_json::from_slice(&req.body).unwrap(); + let asked = body["params"][0].as_str().unwrap_or_default().to_lowercase(); + let result = if asked == format!("{FACTORY:#x}") { + factory_value.clone() + } else { + other.clone() + }; + ResponseTemplate::new(200).set_body_json( + serde_json::json!({ "jsonrpc": "2.0", "id": body["id"], "result": result }), + ) + }) + }; + respond("eth_getBalance", serde_json::json!("0x0")).mount(&server).await; + per_account( + "eth_getTransactionCount", + serde_json::json!(format!("0x{:x}", factory.nonce)), + serde_json::json!("0x0"), + ) + .mount(&server) + .await; + per_account( + "eth_getCode", + Value::String(alloy_primitives::hex::encode_prefixed(code_of(factory.code_hash.unwrap()))), + serde_json::json!("0x"), + ) + .mount(&server) + .await; + respond("eth_getStorageAt", serde_json::json!(B256::ZERO)).mount(&server).await; + server +} + +/// [S1.8] [S1] A block fetched over RPC is fetched with its parent's timestamp, and the cache +/// keeps it: under a genesis file that activates Satin at the block's timestamp, with the parent +/// a second earlier, the replay refuses the block's user transactions online, writes the +/// parent's timestamp to the cache, and refuses them again offline. A cached entry that lacks the +/// timestamp gets it over RPC and is written back with it. +/// +/// Expected values: independent. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_block_fetched_over_rpc_keeps_its_parents_timestamp() { + let number = BLOCKS[2]; + let recorded = read_block(fixtures(), number); + let timestamp = timestamp_of(&recorded); + let server = recorded_chain(number, Parent::At(timestamp - 1)).await; + let uri = server.uri(); + let cache = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let genesis = satin_genesis(dir.path(), mega_evm::MAINNET_CHAIN_ID, timestamp); + + let run = replay(number, cache.path(), &["--rpc", &uri, "--genesis", &genesis]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_refused_as_activation_block(&recorded, &run.records()); + assert_eq!(read_block(cache.path(), number).parent_timestamp, Some(timestamp - 1)); + + // An entry written without it gets it over RPC, and keeps it. + let mut entry = read_block(cache.path(), number); + entry.parent_timestamp = None; + write_block(cache.path(), number, &entry); + let run = replay(number, cache.path(), &["--rpc", &uri, "--genesis", &genesis]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_refused_as_activation_block(&recorded, &run.records()); + assert_eq!(read_block(cache.path(), number).parent_timestamp, Some(timestamp - 1)); + + drop(server); + let run = replay(number, cache.path(), &["--genesis", &genesis]); + assert_eq!(run.code, 0, "{}", run.stderr); + assert_refused_as_activation_block(&recorded, &run.records()); +} + +/// How many times `server` was asked for the header of block `number`'s parent. +async fn parent_requests(server: &wiremock::MockServer, number: u64) -> usize { + let tag = format!("\"0x{:x}\"", number - 1); + server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|request| { + let body = String::from_utf8_lossy(&request.body); + body.contains("\"eth_getBlockByNumber\"") && body.contains(&tag) + }) + .count() +} + +/// [S1] A cached block asks for its parent's header only when the activation-block rule needs +/// the parent's timestamp. With the recorded entries, written before the cache kept it, and an +/// endpoint that does not have the parent, the legacy replay matches the chain and the Satin +/// counterfactual, whose schedule activates every fork at genesis, runs, refusing a transaction +/// only for the block gas it declared: neither asks for the parent. Under a genesis file that +/// activates Satin at the block's timestamp the answer depends on the parent, which the endpoint +/// does not have, and the block fails naming it. +/// +/// Expected values: independent. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_cached_block_asks_for_its_parent_only_when_the_rule_needs_it() { + let number = BLOCKS[2]; + let server = recorded_chain(number, Parent::Missing).await; + let uri = server.uri(); + let cache = cache_copy(); + assert_eq!(read_block(cache.path(), number).parent_timestamp, None, "an entry without it"); + + let run = replay(number, cache.path(), &["--rpc", &uri, "--verify"]); + assert_eq!(run.code, 0, "{}{}", run.stderr, run.stdout); + assert_eq!(blocks_of(&run.records())[0]["matches_chain"], true, "the legacy replay"); + let run = replay(number, cache.path(), &["--rpc", &uri, "--override.spec", "Satin"]); + assert_eq!(run.code, 0, "{}{}", run.stderr, run.stdout); + let records = run.records(); + assert_eq!( + blocks_of(&records)[0]["refused"], + refused_for_block_gas(&records), + "the Satin counterfactual" + ); + assert_eq!(parent_requests(&server, number).await, 0, "neither asked for the parent"); + + let dir = tempfile::tempdir().unwrap(); + let timestamp = timestamp_of(&read_block(cache.path(), number)); + let genesis = satin_genesis(dir.path(), mega_evm::MAINNET_CHAIN_ID, timestamp); + let run = replay(number, cache.path(), &["--rpc", &uri, "--genesis", &genesis]); + assert_eq!(run.code, 1, "{}", run.stdout); + let error = run.records()[0]["error"].as_str().unwrap().to_string(); + assert!(error.contains(&format!("Block not found: {}", number - 1)), "{error}"); + assert_eq!(parent_requests(&server, number).await, 1, "the rule asked for it once"); +} diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs new file mode 100644 index 000000000..6c4e012df --- /dev/null +++ b/bin/mega-evme/tests/common/blocks.rs @@ -0,0 +1,200 @@ +//! The recorded mainnet blocks under `tests/fixtures/blocks`, and running the binary on them. +//! +//! The fixtures are three `MegaETH` mainnet blocks (Rex6) in the block cache layout, recorded +//! from the chain: each block with its transactions, the chain's receipts, and the state its +//! parent left for everything the block read. 26400001 is the most varied block of its range (39 +//! transactions to 19 distinct call targets), 26400007 holds a transaction that failed on chain, +//! 26400110 a plain value transfer. + +use std::{ + path::{Path, PathBuf}, + process::Command, +}; + +use alloy_primitives::{address, Address, B256, U256}; +use mega_evme::block::{CachedBlock, PreAccount}; +use serde_json::Value; + +/// The recorded blocks. +pub(crate) const BLOCKS: [u64; 3] = [26_400_001, 26_400_007, 26_400_110]; + +/// The EIP-7997 factory, which Satin's activation block checks and the legacy engine never reads: +/// the one account a Satin replay of an activation block reads that the recording does not hold. +pub(crate) const FACTORY: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); + +/// The factory as `MegaETH` mainnet holds it: its code, at the nonce its use has brought it to. +pub(crate) fn factory_account() -> PreAccount { + PreAccount { + nonce: 1_443, + code_hash: Some(mega_evm::system::CREATE2_FACTORY_CODE_HASH), + ..PreAccount::default() + } +} + +/// The L1 block contract, whose L1 fee overhead slot Satin's pre-block changes read with the +/// rest of the L1 block info, whatever the fee scalars hold. The legacy engine reads the slot +/// only when the scalars are empty, which they are not on these blocks, so no recording holds it. +pub(crate) const L1_BLOCK: Address = address!("0x4200000000000000000000000000000000000015"); + +/// The L1 fee overhead slot of [`L1_BLOCK`]. +pub(crate) fn overhead_slot() -> B256 { + B256::with_last_byte(5) +} + +/// The recorded block cache. +pub(crate) fn fixtures() -> &'static Path { + Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) +} + +/// Where block `number` lives in the cache at `dir`. +pub(crate) fn block_path(dir: &Path, number: u64) -> PathBuf { + dir.join("blocks").join((number / 10_000).to_string()).join(format!("{number}.json.zst")) +} + +/// Block `number` of the cache at `dir`. +pub(crate) fn read_block(dir: &Path, number: u64) -> CachedBlock { + let compressed = std::fs::read(block_path(dir, number)).unwrap(); + serde_json::from_slice(&zstd::decode_all(compressed.as_slice()).unwrap()).unwrap() +} + +/// Writes `block` as block `number` of the cache at `dir`. +pub(crate) fn write_block(dir: &Path, number: u64, block: &CachedBlock) { + let json = serde_json::to_vec(block).unwrap(); + std::fs::write(block_path(dir, number), zstd::encode_all(json.as_slice(), 3).unwrap()).unwrap(); +} + +/// The code with `hash` from the recorded code store, or the factory's ([`factory_account`]), +/// which no recording holds. +pub(crate) fn code_of(hash: B256) -> Vec { + if hash == mega_evm::system::CREATE2_FACTORY_CODE_HASH { + return mega_evm::system::CREATE2_FACTORY_CODE.to_vec(); + } + std::fs::read(code_path(fixtures(), hash)).unwrap() +} + +/// Where the code with `hash` lives in the code store of the cache at `dir`. +fn code_path(dir: &Path, hash: B256) -> PathBuf { + let hex = hash.to_string(); + dir.join("codes").join(&hex[2..4]).join(format!("{}.bin", &hex[2..])) +} + +/// A copy of the recorded block cache, so no test can write to the fixtures. +pub(crate) fn cache_copy() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + copy_dir(fixtures(), dir.path()); + dir +} + +/// A copy of the recorded block cache in which every block's pre-state holds what a Satin replay +/// reads beyond the recording: the factory, as the chain holds it ([`factory_account`], its code +/// in the cache's code store), which only Satin's activation block reads, and the L1 fee overhead, +/// zero, as the chain held it. `block_replay.rs` shows the overhead's value changes no transaction +/// row. +pub(crate) fn cache_copy_for_satin() -> tempfile::TempDir { + let dir = cache_copy(); + let factory = factory_account(); + let code = code_path(dir.path(), factory.code_hash.unwrap()); + std::fs::create_dir_all(code.parent().unwrap()).unwrap(); + std::fs::write(code, mega_evm::system::CREATE2_FACTORY_CODE).unwrap(); + for number in BLOCKS { + let mut block = read_block(dir.path(), number); + block.prestate.accounts.insert(FACTORY, factory.clone()); + set_overhead(&mut block, U256::ZERO); + write_block(dir.path(), number, &block); + } + dir +} + +/// Has `block`'s pre-state hold `value` as the L1 fee overhead. +pub(crate) fn set_overhead(block: &mut CachedBlock, value: U256) { + let l1_block = block.prestate.accounts.get_mut(&L1_BLOCK).expect("every block reads it"); + l1_block.storage.insert(overhead_slot(), value); +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_dir(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), target).unwrap(); + } + } +} + +/// What a run of the binary printed. +pub(crate) struct Run { + /// The exit code. + pub(crate) code: i32, + /// Standard output. + pub(crate) stdout: String, + /// Standard error. + pub(crate) stderr: String, +} + +impl Run { + /// The JSON lines of standard output. + pub(crate) fn records(&self) -> Vec { + self.stdout.lines().filter_map(|line| serde_json::from_str(line).ok()).collect() + } +} + +/// The reason the block executor gives a transaction whose declared gas limit is more than the +/// gas its block has left. +const NO_BLOCK_GAS: &str = "is more than blocks available gas"; + +/// How many transactions `records`, a replay of one block, shows refused, every one of them for +/// the gas it declared and the block no longer had. +/// +/// The recorded transactions declare gas limits close to their block's own, and a Satin replay of +/// a recorded block spends more gas than the chain did, so a transaction late in the block can +/// find too little gas left to be included. That is the one refusal a replay whose schedule has +/// every fork active at the block can make; any other fails the assertion. +pub(crate) fn refused_for_block_gas(records: &[Value]) -> usize { + let refused: Vec<&Value> = + records.iter().filter(|r| r["kind"] == "tx" && r["status"] == "refused").collect(); + for record in &refused { + let reason = record["reason"].as_str().unwrap_or_default(); + assert!(reason.contains(NO_BLOCK_GAS), "a refusal for more than block gas: {record}"); + } + refused.len() +} + +/// Runs `mega-evme` with `args` on a thread of its own, so a test's runtime can serve it a mock. +pub(crate) fn run_evme>(args: &[S]) -> Run { + let args: Vec = args.iter().map(|a| a.as_ref().to_string()).collect(); + std::thread::spawn(move || { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(&args).output().unwrap(); + Run { + code: output.status.code().unwrap(), + stdout: String::from_utf8(output.stdout).unwrap(), + stderr: String::from_utf8(output.stderr).unwrap(), + } + }) + .join() + .unwrap() +} + +/// The timestamp of a cached block. +pub(crate) fn timestamp_of(block: &CachedBlock) -> u64 { + let hex = block.block["timestamp"].as_str().expect("a hex timestamp"); + u64::from_str_radix(hex.trim_start_matches("0x"), 16).expect("a timestamp") +} + +/// Whether the `index`-th transaction of a cached block is a deposit. +pub(crate) fn is_deposit(block: &CachedBlock, index: usize) -> bool { + block.block["transactions"][index]["type"] == "0x7e" +} + +/// A genesis file of chain `chain_id` activating Satin at `satin_time`, written in `dir`; its +/// path. +pub(crate) fn satin_genesis(dir: &Path, chain_id: u64, satin_time: u64) -> String { + let satin = mega_evm::SatinChainConfig { activation_time: satin_time }; + let mut config = serde_json::to_value(satin).unwrap(); + config["chainId"] = chain_id.into(); + let path = dir.join(format!("satin-genesis-{chain_id}-{satin_time}.json")); + std::fs::write(&path, serde_json::json!({ "config": config }).to_string()).unwrap(); + path.to_str().unwrap().to_string() +} diff --git a/bin/mega-evme/tests/common/mod.rs b/bin/mega-evme/tests/common/mod.rs index 54dfc716f..1ebbaa75e 100644 --- a/bin/mega-evme/tests/common/mod.rs +++ b/bin/mega-evme/tests/common/mod.rs @@ -4,10 +4,13 @@ //! is not picked up as a standalone test target. //! //! Add helpers only when a third caller shows up; the current set is sized to -//! the patterns shared between `tests/provider.rs` and `tests/state.rs`. +//! the patterns shared between `tests/provider.rs` and `tests/state.rs`, and +//! (`blocks`) between the tests that replay the recorded blocks. #![allow(dead_code)] // Each test binary uses a different subset of helpers. +pub(crate) mod blocks; + use clap::Parser; use mega_evme::common::RpcArgs; use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; @@ -101,12 +104,26 @@ impl MockRpcServer { .await; } + /// Drops every mounted mock and the recorded requests. + pub(crate) async fn reset(&self) { + self.server.reset().await; + } + /// Total number of POSTs the server has received since it started. pub(crate) async fn received_request_count(&self) -> usize { self.server.received_requests().await.expect("received_requests").len() } } +/// The on-disk cache file `build_provider` uses for `url` on `chain_id` under `dir`. +pub(crate) fn rpc_cache_path( + dir: &std::path::Path, + chain_id: u64, + url: &str, +) -> std::path::PathBuf { + dir.join(mega_evme::rpc_cache_file_name(chain_id, url)) +} + /// Build [`RpcArgs`] for a test pointed at `url` with the on-disk cache disabled. /// /// Defaults: `--rpc.cache-size 0` (no cache layer, no disk persistence), diff --git a/bin/mega-evme/tests/differences.rs b/bin/mega-evme/tests/differences.rs new file mode 100644 index 000000000..8dfa53f59 --- /dev/null +++ b/bin/mega-evme/tests/differences.rs @@ -0,0 +1,334 @@ +//! The expected differences between Satin and the legacy engine, pinned. +//! +//! Renders `tests/satin-differences.md` from what the two engines produce on the same inputs, and +//! compares it with the checked-in file, so a change that moves any number of either engine +//! shows up as a diff of that file. After an intended change, rewrite it with +//! `UPDATE_EVME_DIFFERENCES=1 cargo test --manifest-path bin/mega-evme/Cargo.toml --test +//! differences`. +//! +//! The inputs are the ones this repository can build without a chain: the `run` and `tx` +//! fixtures, each run on both engines (`test_.json` and `test_satin_.json`, whose +//! outputs `tests/integration.rs` holds the binary to), and the recorded mainnet blocks of +//! `tests/fixtures/blocks`, whose legacy replay matches the chain. +#![cfg(feature = "legacy")] + +mod common; + +use std::{collections::BTreeMap, fmt::Write as _, path::Path}; + +use common::blocks::{cache_copy_for_satin, read_block, run_evme, BLOCKS}; +use mega_evm::constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE}; +use serde_json::Value; + +const TABLE: &str = "tests/satin-differences.md"; + +fn manifest_dir() -> &'static Path { + Path::new(env!("CARGO_MANIFEST_DIR")) +} + +/// `a / b` to two decimals, rounded down. +fn ratio(a: u64, b: u64) -> String { + if b == 0 { + return "-".to_string(); + } + let hundredths = u128::from(a) * 100 / u128::from(b); + format!("{}.{:02}", hundredths / 100, hundredths % 100) +} + +fn signed(a: u64, b: u64) -> String { + if a >= b { + format!("+{}", a - b) + } else { + format!("-{}", b - a) + } +} + +fn u64_of(value: &Value) -> u64 { + value.as_u64().unwrap_or_else(|| panic!("not a number: {value}")) +} + +/// `success`, `revert` or `halt`, from a `run`/`tx` JSON summary. +fn summary_status(summary: &Value) -> &'static str { + if summary["success"] == true { + "success" + } else if summary.get("halt_reason").is_some() { + "halt" + } else { + "revert" + } +} + +/// The mechanisms a Satin row shows, from its numbers. +fn classes(satin: &Value, legacy_success: bool, satin_success: bool, log_delta: i64) -> String { + let mut classes = Vec::new(); + if u64_of(&satin["history_gas"]) > 0 { + classes.push("history".to_string()); + } + if u64_of(&satin["state_gas"]) > 0 { + classes.push("state".to_string()); + } + if log_delta > 0 { + classes.push(format!("+{log_delta} logs")); + } + if legacy_success != satin_success { + classes.push("status".to_string()); + } + if let Some(kind) = satin["limit_exceeded"]["kind"].as_str() { + classes.push(format!("stop:{kind}")); + } + classes.join(", ") +} + +fn render_fixtures(out: &mut String) { + let dir = manifest_dir().join("tests/fixtures"); + let mut names: Vec = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|entry| { + let name = entry.unwrap().file_name().into_string().unwrap(); + name.strip_prefix("test_satin_").map(|rest| rest.trim_end_matches(".json").to_string()) + }) + .collect(); + names.sort(); + writeln!(out, "## `run` and `tx` fixtures\n").unwrap(); + writeln!( + out, + "Each fixture's command run on both engines: `tests/fixtures/test_.json` and \ + `test_satin_.json`, which is the same command with `--spec Satin`.\n" + ) + .unwrap(); + writeln!( + out, + "| Fixture | Legacy | Satin | Satin - legacy | Regular | State | History | History bytes \ + | Logs | Classes |" + ) + .unwrap(); + writeln!(out, "|---|---|---|---:|---:|---:|---:|---:|---|---|").unwrap(); + for name in names { + let load = |file: String| -> Value { + let fixture: Value = + serde_json::from_str(&std::fs::read_to_string(dir.join(file)).unwrap()).unwrap(); + fixture["expected"].clone() + }; + let legacy = load(format!("test_{name}.json")); + let satin = load(format!("test_satin_{name}.json")); + let (legacy_gas, satin_gas) = (u64_of(&legacy["gas_used"]), u64_of(&satin["gas_used"])); + let (legacy_logs, satin_logs) = + (u64_of(&legacy["logs_count"]), u64_of(&satin["logs_count"])); + let ledgers = &satin["satin"]; + writeln!( + out, + "| {name} | {} {legacy_gas} | {} {satin_gas} | {} | {} | {} | {} | {} | {legacy_logs} \ + -> {satin_logs} | {} |", + summary_status(&legacy), + summary_status(&satin), + signed(satin_gas, legacy_gas), + ledgers["regular_gas"], + ledgers["state_gas"], + ledgers["history_gas"], + ledgers["history_bytes"], + classes( + ledgers, + legacy["success"] == true, + satin["success"] == true, + satin_logs as i64 - legacy_logs as i64 + ), + ) + .unwrap(); + } +} + +/// One transaction of a recorded block, on both engines. +struct TxPair { + target: String, + selector: String, + legacy: Value, + satin: Value, +} + +fn is_success(record: &Value) -> bool { + record["status"] == "success" +} + +fn render_blocks(out: &mut String) { + let cache = cache_copy_for_satin(); + let mut pairs = Vec::new(); + writeln!(out, "## Recorded mainnet blocks\n").unwrap(); + writeln!( + out, + "The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The \ + legacy replay of each matches the chain (every receipt and the receipts root), so the \ + legacy column is the chain's. Satin runs the transactions as signed, on the state \ + their parent block left.\n" + ) + .unwrap(); + writeln!( + out, + "| Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | \ + History | Status differs | Logs | Refused |" + ) + .unwrap(); + writeln!(out, "|---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:|").unwrap(); + for number in BLOCKS { + let replay = |spec: Option<&str>| -> Vec { + let mut args = vec![ + "replay".to_string(), + "--block".to_string(), + number.to_string(), + "--block-cache".to_string(), + cache.path().to_str().unwrap().to_string(), + "--json".to_string(), + ]; + if let Some(spec) = spec { + args.extend(["--override.spec".to_string(), spec.to_string()]); + } + let run = run_evme(&args); + assert_eq!(run.code, 0, "{}", run.stderr); + run.records() + }; + let (legacy, satin) = (replay(None), replay(Some("Satin"))); + let block = |records: &[Value]| records.last().unwrap().clone(); + let (legacy_block, satin_block) = (block(&legacy), block(&satin)); + assert_eq!(legacy_block["matches_chain"], true, "the legacy replay of {number}"); + + let recorded = read_block(cache.path(), number); + let txs = recorded.block["transactions"].as_array().unwrap(); + let (mut status_differs, mut legacy_logs, mut satin_logs) = (0, 0, 0); + for ((legacy, satin), tx) in legacy.iter().zip(&satin).zip(txs) { + if legacy["kind"] != "tx" { + continue; + } + status_differs += usize::from(is_success(legacy) != is_success(satin)); + legacy_logs += u64_of(&legacy["logs"]); + satin_logs += u64_of(&satin["logs"]); + let input = tx["input"].as_str().unwrap_or("0x"); + let (target, selector) = if tx["type"] == "0x7e" { + ("deposit".to_string(), "-".to_string()) + } else { + ( + tx["to"].as_str().unwrap_or("create").to_string(), + if input.len() >= 10 { input[..10].to_string() } else { "-".to_string() }, + ) + }; + pairs.push(TxPair { target, selector, legacy: legacy.clone(), satin: satin.clone() }); + } + let ledgers = &satin_block["satin"]; + writeln!( + out, + "| {number} | {} | {} | {} | {} | {} | {} | {} | {status_differs} | {legacy_logs} -> \ + {satin_logs} | {} |", + legacy_block["transactions"], + legacy_block["gas_used"], + satin_block["gas_used"], + ratio(u64_of(&satin_block["gas_used"]), u64_of(&legacy_block["gas_used"])), + ledgers["regular_gas"], + ledgers["state_gas"], + ledgers["history_gas"], + satin_block["refused"], + ) + .unwrap(); + } + + writeln!(out, "\n## Recorded transactions by call target\n").unwrap(); + writeln!( + out, + "The transactions of the three blocks grouped by the contract they call and the \ + selector they call it with; `deposit` is the block's L1 attributes deposit, `-` a call \ + without calldata.\n" + ) + .unwrap(); + writeln!( + out, + "| Call target | Selector | Transactions | Legacy gas | Satin gas | Satin / legacy | \ + State gas | Status differs | Logs |" + ) + .unwrap(); + writeln!(out, "|---|---|---:|---:|---:|---:|---:|---:|---|").unwrap(); + let mut groups: BTreeMap<(String, String), Vec<&TxPair>> = BTreeMap::new(); + for pair in &pairs { + groups.entry((pair.target.clone(), pair.selector.clone())).or_default().push(pair); + } + let mut groups: Vec<_> = groups.into_iter().collect(); + groups.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0))); + for ((target, selector), txs) in groups { + let sum = |f: &dyn Fn(&TxPair) -> u64| txs.iter().map(|p| f(p)).sum::(); + let legacy_gas = sum(&|p| u64_of(&p.legacy["gas_used"])); + let satin_gas = sum(&|p| u64_of(&p.satin["gas_used"])); + // A transaction the block refused ran nothing and has no ledgers. + let state_gas = sum(&|p| { + if p.satin["status"] == "refused" { + 0 + } else { + u64_of(&p.satin["satin"]["state_gas"]) + } + }); + let status = txs.iter().filter(|p| is_success(&p.legacy) != is_success(&p.satin)).count(); + let legacy_logs = sum(&|p| u64_of(&p.legacy["logs"])); + let satin_logs = sum(&|p| u64_of(&p.satin["logs"])); + writeln!( + out, + "| {target} | {selector} | {} | {legacy_gas} | {satin_gas} | {} | {state_gas} | \ + {status} | {legacy_logs} -> {satin_logs} |", + txs.len(), + ratio(satin_gas, legacy_gas), + ) + .unwrap(); + } +} + +fn render() -> String { + let mut out = String::new(); + writeln!(out, "# Satin against the legacy engine: the expected differences\n").unwrap(); + writeln!( + out, + "Generated by `cargo test --manifest-path bin/mega-evme/Cargo.toml --test differences`; \ + the test compares this file to what it renders, so every number here is one the two \ + engines produced. After an intended change of either, rewrite it with \ + `UPDATE_EVME_DIFFERENCES=1`.\n" + ) + .unwrap(); + writeln!( + out, + "Legacy is `Rex6` on the released `mega-evm` 1.7.1. Satin is the in-tree engine at a \ + cost per state byte of {COST_PER_STATE_BYTE} and a cost per history byte of \ + {COST_PER_HISTORY_BYTE}, the minimum SALT bucket everywhere. Every row runs one input on \ + both engines.\n" + ) + .unwrap(); + writeln!(out, "What the Satin columns show:\n").unwrap(); + for line in [ + "- **Regular**: execution, at the Satin schedule (Amsterdam's, EIP-8038's state-access \ + prices included) and EIP-2780's intrinsic cost.", + "- **State**: EIP-8037 state gas for the state a transaction adds (a slot, an account, \ + deployed code), at the cost per state byte.", + "- **History**: gas for the bytes a transaction appends to history (its body, one \ + 40-byte record per kept write, its logs, its deployed code), at the cost per history \ + byte; **History bytes** is their count. The legacy engine has neither ledger.", + "- **Logs**: Satin emits an EIP-7708 `Transfer` log for every value movement; the \ + legacy engine does not.", + "- **Classes**: the mechanisms a row shows, read off its numbers: `history`, `state`, \ + `+N logs`, `status` (success differs), `stop:` (a Satin limit stopped it).", + ] { + writeln!(out, "{line}").unwrap(); + } + writeln!(out).unwrap(); + render_fixtures(&mut out); + writeln!(out).unwrap(); + render_blocks(&mut out); + out +} + +#[test] +fn test_the_difference_table_is_current() { + let rendered = render(); + let path = manifest_dir().join(TABLE); + if std::env::var_os("UPDATE_EVME_DIFFERENCES").is_some() { + std::fs::write(&path, &rendered).unwrap(); + return; + } + let pinned = std::fs::read_to_string(&path).unwrap_or_default(); + assert!( + pinned == rendered, + "{TABLE} is out of date; rerun with UPDATE_EVME_DIFFERENCES=1 and review the diff.\n\n\ + Rendered:\n{rendered}" + ); +} diff --git a/bin/mega-evme/tests/dump_code.rs b/bin/mega-evme/tests/dump_code.rs new file mode 100644 index 000000000..ab1785e65 --- /dev/null +++ b/bin/mega-evme/tests/dump_code.rs @@ -0,0 +1,168 @@ +//! A prestate account that names its code only by hash (`code: null` with a `codeHash`): offline +//! there is nothing to load it from and the run is refused; forked, its code is fetched and +//! checked against the hash, and the dumped state carries the code, not a null. + +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::tempdir; +use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + +/// The contract the fork serves, and the account the prestate names by hash. +const CONTRACT: &str = "0x00000000000000000000000000000000000000aa"; +/// `PUSH1 1 PUSH0 MSTORE PUSH1 32 PUSH0 RETURN`: returns the word 1. +const CONTRACT_CODE: &str = "0x600160005260206000f3"; +const CONTRACT_HASH: &str = "0xc1d5b4ce3e2a6227293fccce2904121c8647bbe16c1216340b851bf12d12560e"; +/// `PUSH1 0xaa BALANCE POP STOP`: touches the contract's account without loading its code. +const TOUCH_CONTRACT: &str = "0x60aa315000"; +/// A second account, holding `TOUCH_CONTRACT`'s code, for a transaction to touch the first. +const TOUCHER: &str = "0x00000000000000000000000000000000000000bb"; +/// `STATICCALL` of the contract with all gas and no input, returning its 32-byte output. +const CALL_CONTRACT: &str = "0x60205f5f5f60aa5afa5060205ff3"; + +/// Serves `eth_chainId` and one contract; every other account is empty. +async fn mount_fork(server: &MockServer) { + Mock::given(matchers::method("POST")) + .respond_with(|req: &wiremock::Request| { + let body: Value = serde_json::from_slice(&req.body).unwrap_or_default(); + let address = body["params"][0].as_str().unwrap_or(""); + let is_contract = address.eq_ignore_ascii_case(CONTRACT); + let result = match body["method"].as_str().unwrap_or("") { + "eth_chainId" => "0x10e6", + "eth_getBalance" if is_contract => "0x64", + "eth_getTransactionCount" if is_contract => "0x7", + "eth_getCode" if is_contract => CONTRACT_CODE, + "eth_getCode" => "0x", + _ => "0x0", + }; + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "jsonrpc": "2.0", "id": body["id"].clone(), "result": result, + })) + }) + .mount(server) + .await; +} + +/// Writes a prestate file holding the contract by hash and returns its path. +fn lazy_prestate(dir: &std::path::Path, code_hash: &str) -> String { + let path = dir.join("prestate.json"); + std::fs::write( + &path, + format!( + r#"{{"{CONTRACT}":{{"balance":"0x64","nonce":"0x7","code":null,"codeHash":"{code_hash}","storage":{{}}}},"{TOUCHER}":{{"balance":"0x0","nonce":"0x1","code":"{TOUCH_CONTRACT}","storage":{{}}}}}}"# + ), + ) + .unwrap(); + path.to_str().unwrap().to_string() +} + +async fn mega_evme(args: Vec) -> Output { + tokio::task::spawn_blocking(move || { + Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(&args).output().unwrap() + }) + .await + .unwrap() +} + +fn strings(args: &[&str]) -> Vec { + args.iter().map(ToString::to_string).collect() +} + +fn fork_args(uri: &str) -> Vec { + strings(&["--fork", "--fork.block", "100", "--rpc", uri, "--rpc.no-cache-file"]) +} + +fn dumped_code(stdout: &[u8], address: &str) -> Value { + let json: Value = serde_json::from_slice(stdout).expect("json output"); + json["state"][address]["code"].clone() +} + +/// Offline, a prestate account whose code is not in the file is refused, as a hash that does not +/// match the code was: it would otherwise run as empty code under a non-empty `EXTCODEHASH`. +#[tokio::test] +async fn test_an_unloadable_account_is_refused_offline() { + let dir = tempdir().unwrap(); + let prestate = lazy_prestate(dir.path(), CONTRACT_HASH); + let mut args = strings(&["run", "--spec", "Satin", CALL_CONTRACT, "--prestate"]); + args.push(prestate); + let output = mega_evme(args).await; + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.to_lowercase().contains(CONTRACT) && stderr.contains("`code: null`"), + "{stderr}" + ); +} + +/// Forked, the code of such an account is fetched, checked against its hash and run. +#[tokio::test(flavor = "multi_thread")] +async fn test_an_unloaded_account_runs_its_fetched_code() { + let server = MockServer::start().await; + mount_fork(&server).await; + let dir = tempdir().unwrap(); + let mut args = strings(&["run", "--spec", "Satin", CALL_CONTRACT, "--json", "--prestate"]); + args.push(lazy_prestate(dir.path(), CONTRACT_HASH)); + args.extend(fork_args(&server.uri())); + let output = mega_evme(args).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stderr}"); + let json: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(json["output"], format!("0x{:064x}", 1), "{json}"); +} + +/// Forked, code that does not match the hash is an error, never a panic or an empty run. +#[tokio::test(flavor = "multi_thread")] +async fn test_an_unloaded_account_with_another_hash_is_refused() { + let server = MockServer::start().await; + mount_fork(&server).await; + let dir = tempdir().unwrap(); + let mut args = strings(&["run", "--spec", "Satin", CALL_CONTRACT, "--prestate"]); + args.push(lazy_prestate(dir.path(), &format!("0x{}", "ab".repeat(32)))); + args.extend(fork_args(&server.uri())); + let output = mega_evme(args).await; + assert_eq!(output.status.code(), Some(1), "no panic"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.to_lowercase().contains(CONTRACT), "{stderr}"); + assert!(!stderr.contains("panicked"), "{stderr}"); +} + +/// `run --dump` carries the code of an account the prestate named by hash. +#[tokio::test(flavor = "multi_thread")] +async fn test_run_dump_carries_the_code_of_an_unloaded_account() { + let server = MockServer::start().await; + mount_fork(&server).await; + let dir = tempdir().unwrap(); + let mut args = + strings(&["run", "--spec", "Satin", TOUCH_CONTRACT, "--json", "--dump", "--prestate"]); + args.push(lazy_prestate(dir.path(), CONTRACT_HASH)); + args.extend(fork_args(&server.uri())); + let output = mega_evme(args).await; + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(dumped_code(&output.stdout, CONTRACT), CONTRACT_CODE); +} + +/// `tx --dump` carries the code of an account the prestate named by hash. +#[tokio::test(flavor = "multi_thread")] +async fn test_tx_dump_carries_the_code_of_an_unloaded_account() { + let server = MockServer::start().await; + mount_fork(&server).await; + let dir = tempdir().unwrap(); + let mut args = strings(&[ + "tx", + "--spec", + "Satin", + "--receiver", + TOUCHER, + "--sender.balance", + "1ether", + "--json", + "--dump", + "--prestate", + ]); + args.push(lazy_prestate(dir.path(), CONTRACT_HASH)); + args.extend(fork_args(&server.uri())); + let output = mega_evme(args).await; + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(dumped_code(&output.stdout, CONTRACT), CONTRACT_CODE); +} diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst new file mode 100644 index 0000000000000000000000000000000000000000..7b683daafe32e0d92752b9c473431f63c6cc6c4f GIT binary patch literal 21070 zcmV)6K*+x+wJ-euSUg|>dQ|UlBM?(k(gFNG#vjiBaL6PX;yC}k@t+5eG)a<~4IEWf zRaI~Uh6lq2!3K{>(o;62R=h$KaPe<#@~kJjvcsvOJ;Y>h>iptoq9-IY|8&a7WUU4% zlxW5sNlqd*uT0Ec^LI5ONETs-iggC#e&XgN%wd%XT(mdD#SCr};V4bx^&IU_thB^w zZ|OI85<*~zR#gs>z8@~BGMB3IGP|*|Jj9p~n-j$iR*ujc4!jG;;M^U8t!uux7xA!z z!q3|Hp=*8+&$w|Et3MBn zD|OzGGezFa&{30XuM~omacm%M*PSxmK&|;f{vtGZ^w$yGk=ic=@708R$*aN?6Uh*e zQm#FlN13rmT$!Y0*Dv**>l>-pf5Ucb_w9>ydhi=zWh_$A9KOx3Cq>nXqU(n;-(8wK zHw)p{>xd>)ifk|{!mhx!cq1-J*(HISb#Gk1ezQ2nD>VIFbih}yp%g8-4Bt-P(q-B| z^FCqfJ?ywMu#aNae(m;Nvhgk`;-ly+D|@I8x!yl{^PRa^bl_6={^R`lwnnJnTihN( z*3CJC&DrDeWcX&_KS|ydrY=;=P^QaJZ)t&caY8LlS2wt=MSDGtDV&mxMj`XIOd=B^ z8Qp!%=30;r7tWVHg`y%TV$=K{V)(EBMUwPSl4vDWJKcZNujBNWqL0xVF!=6fhtKqs zf33%?Ke1+B8s~vygEf-V zQPItc)rb2o(q1Mf#Y&;dtit}w1RD$H?~nCW#UUfXZR(3G*kjpQ2$k1XVQHZ*cxaNS zlH&TF=MeFlQbCLz41qRPy_Qs1R$Z=|_C{4jX0|FXM(mmm7)X!+1`M28oArEbX09=a zRa`G-=+aufh7u`eh@f&HXdpoa6i84313sV`_^kPWX5e7KL9k?p!snTm-hIZv?^TPI z2!oUOp7hqa+!%sNF43CB8n*-$wEWC9k5Fkdgy|gok3T*OrPk|7lPEGWyo`1fITKFf z*!#reucF>r@HhUmR;Oo&p3H{uWxCgg(7O`NTRrX&K7KH^qpRj>e$%VR+-yezqDasW zdB;vl99j_(uga;`j)YxVgf5(MaI(pY59fk_gIF+vgOH#C27Dk6BG7;a5-^}Z1KuC- zo&W&~=zs(jC<8!H!NG!qosHS)o5&50s&kTV&O6efelX{=sGUBIX8r- zuEK>fno|he#m>S(0{b}3A|f*+2Q)B&1mgBq0p|b)v;z$$FbWz(w0c+Y2MZ4J^hm-< zF575??I?`*IotBY$c@xG5zBd$Fv#^|aPZo>0uE5X;9$XlqXt0G;6MZt0KmZnB*1}# z1qY^KA&`K|*Y9hVu<(bRDvl**(13w+U<3Qh zJxFG&k}7=IN)f8q-Yz=VHJIKoTDS>VD@o_RWI-2T3NRpm2`FH70SJHr1LrWn9t2jk zpb?NRh+(`<5l_d22;W@hAh);wyJOKq094t6EkCwa%(zMk=N2e(hOm_JouUlo)A#~93uGlMC)zfC#2lTap z5gNlfXs1k`VF)=X}!4hF&f`lMpqH1Dff<)9+L26*z9b@L;wNks2#a)Xt&czVu;@tvG`TD3G85D}xENf(8c*4p4&Sm~83( z8(a9D{^!JF45uJ9pZe!GT_jXC>B?bLN^U>_1r6{9+JM2qf&-D5s=z0ZAOi;r4zMVz zqxz>r<4FoNRIXT!P^(lk-{RR?SXFF8_72{~+`_;yz!N}#)B+3+794P8`f%W48Z{TR z3$u7*3{@0zYjmoTEv%dW_iki(54ySsXfT0Spc*(>a1iF_I+OViF>E9`PKYZSG%n99 z*9wC3p4=vCdud2F5<>Vu901_J0u0mw2O$6L(o+nk(-mo>p zRh*c)4D;v%u?sni(N@ETNSAPWL1rW7v!;`3)(BZ@=|&4_KbNf4Pe&l45}+%4TW4A}z3n8*BZh`#9KWXv&*YgE^OK<_E0q2^Uc4P{RZXm?yhVZya7i zS*}_~XsQm>HM3n|1KLq{CZDeb3B3GW7y?yM!;Ch0aA(t=Rs?Zf)eKxqGA&Ju%l2Aw zv2Beld)bfpz7cv?qvb363(K+j!ikiORuR3pu;Hw*DK`)EO!XP1o=ehXmf1)o)8YFp zt*0=T?0twT4OPNzcSNbsiP~k}2IQ79hODn{r_`04?mng8kriRw-mzb}O29_0> zWYL*mUp={&#gTaWsF&9qL(hldqlqVC{(EF_-NHo+V$_CP6S7BU!Fri8KIF;~;h@5w z3ZfWV(t=!S7lM48Bc==41eAbyVl5Qw8|ogHE07B{`-X<6ZVrAul*3G|7>!Wm)yyHJ zoSg4Q_?TBzPM<*7G@;CeW#X?DmHC)1uXWihrg5Ynsj@AYB9LNLa&>=4bJcGr!ZGU^ z6K#Y2en53PVbS+s((IZNKZw|)*cDbIYl>GFA)0PVR_uK9HdsjmeUJ&&dO_E-i;P&_ zXz`}C;xzSX=>|s5e&Yt#v z&h2&IHydv)F*Y@bWcf|_kwp=?4{kq5a=BtdGS2-5%d={;XFQV)54jE%W@b;G0g7?H%x9dYm;k5Vmi%{8G2>Bf`y$Ke)$iy zmY}YaWMO&9H0ouwh_5Wg-Vb?-ztM?G5X2emOgiwzx!Li z>=sI(%X{m|30%#IGdwMEPNCgJ7ah;sZ$5lHUrWWrV1)@UsdcpR84IbtQo;LOw)9uW z_Jyhh71wFnAx;_tGouGIT zR;tNKB2a743@HI8T+2!b^@PX68=o7R$HM&MEDoK1U=GBBU1Ud=sqM|x;dSP;M$hs8 z@gF+myA_&;+8?2_%Q)fo!*Syc_BUFQt%&oTP_kbhUkY2@Tsu7(XNQH(tP0h>ISV6& zQi1gGq(ewhb%}3bFqsS@62ux50`p}i{g4JRHPY4SAlQ_bb46KFAw^aaf?9sggP4sX!V2^c{6vFR;{> ztcMee5TQKvbK>~^njjIc!(m3%DxU*SSUv1qa~4yA3$OA7rn;#@3maT&?h_i+^vh2x zA=9hb02GL0qXnj@01f*=bnMP^Jlnyul6d>oY23etrV$r4x}BXn;@we@ojs-0|sS8Ht`4(8*G!AQQ4T7|IH&mJ%k-H z8j9Ab%?%~OQp_o$kAc4*HEH!lEZq}gerCRc}^^vd^X^7vUW)@ zGfWD_zYiHE)Ei>9$&F|~nH*N7)Aa3w8@~o%qdP%zN0g$%|Md!(t3Aiu*jOWT@WK{8x&p?s4xM_M25j`E{hdFkyA>J)>{W zJksu~dv-Er7`vWmLe?-Eg^IQ}_h;K8iMA1=@P%x|Zn@UoLzc>QT56B&!>!R_t20#* zbvBCRfk7vbEOXm}smpa3uWnqP5hKREhZ(UEQP&`uF)x|O?xucaOs%z!q{T(Oc@x6$ zq)W-sUA?r}Na%u91V7z`ZN+=9<>)i5B-Q7U&@0g;;@|&Fzn(XF`K=12DD3{;9F_wH@*rNzOx@o~5lv;PT9LZwfuCe%v*j+Mjdb zPd`~Q=<1W9&?@GJ3bgrARhgK;Z>}=g4q{Uzo^UBr_WSyCb3dHr6!#%tuU~6o+Y` zK)3%9>ds@#a0y9I%MeM8Vn2G}L>lXhb)zSub=jSZA0B~0PGUUQ?TvnfV+ym1Dym#r zkYbTljD5E~6n;$@s-!a$5}fvw3UT@!KZ_Vk!&YRk)SY31f+lCeuW^;Cci5b7hF=pc zj@d4aiHeudIHFMI!HC<-0jq0%RlM{$yuK^CZjiZe@WI7!T9wd&cBnQ;%@l`#p_-Xw zq(V6crAwo7PCq7vjGg?k(M#TwPaLt;j9fO4@uYDx1=e%#%W~Z+IU65Q5KB{T(?1`M zCe7c$$W5aUra}MA)&p7l7U{;kUB|+iWmbn3U75~|kU4xrF{RHy52tk*ND)PiRv5pp zLc@m+MpTIsiN;dNxYsengI4#;BqiIqvsWXYRvYQkJ?*q!;g^cFy6Z#Wj2H~0+5D4U z0V&dFADL2ABm~?yw@No=9L%2xbWb>cI1&_^P&@5;og`c+3NzKK=qc&g_`h>wGgf(| zwJylI`Sh!c-{rw4T6z(>O?%8`l;UH!DSCRFg6D5jc%kbLZ;R3)y;ERqYg;=*NHO>)pN`NRy9{Ik-fClr#S(9kg;nO0M1?m5ZF za=)b`$0X9o&K3L$Yb!*PyofcoL|qDRm(LTB9O=R$VXj=V6(ddhl&`nnsb7T<&dI|o zV$#Ld?xq?f&`~)4Cu+JGH)@n%jjAWarpL@pn}fK-cAFj2{_QDKj&>e$#HE9hS1ZFE zCK84c-H67e%jA5>3mSgpdNyE|hLR7F(CelsE~3q|>SbE7%RH!dQE?k2ib7m37sE=4 z!9!%#{6oA?jyJ@$JYBI?l0T)>9hMavN&6Rb(?a0DPyT_n6}j9#DiSg^!JYg$xI*YH z5fpH$O=OEM0W8nQdcyI)d_)(HQT|W2T$eO)NScTs;_;cQQ0qX zx1?!;LdraLRho~((wku*LYlA~zhfCPaG=vv5b27FFfsEUxY)dFNt%L@goSawXnp}B z5P74cMLFH2Iy~D4v;UzB9O!PBeHV^6SeS{4AQL0!WQDad@qu9}Crf5(&Wc9fn~jz_ zNcE|H5YB|i(%eSGFJADX$r>tS3=XOf_^J^s7@}72kTG{!qF9bH(&o;ganHRN(@v(1 zcd}%rMx*+oSSbUZ6^$$yfiu8>J^&8dJ3v7Oyn=ZEBKE<82^>&&Xk*~ptff1l$_Tud z{*0&*vAzy7srq|nQnMnDzx@A!IFJAU4j8Zm8la$o9*6*cCq${%JqiBuECm=4fS6UF z7*KYA00aYG0Kotr2nG%oU;qOgm;e9=3>bI?-2rI8T0w&eC}8$~uRw$XLUR!BfCLQ` z102Wz2l!yYfpDOKHW#~n@-0fKbg{3 z%vg&pjx6xUuzM!{DI-5Dn{o)o;Um`>LKm>g{yV?Ld%iG4SHOV=Iza`fEf{J#gZ~8_ z)Nz1<0Z1@`1R0pXxQDdC$yv4IqM;l<456(+(eIcEbN{sDXk;?QWkH>?9j*gkvwS>Go4`0D=oSl(diu>9v&Znu6@AsuK ze1>PK?~U#(nwC)X?2gYb`j9liiRrFCPBic=bW3uVS-|`%&EkvbUuO%Rbo(Fr`v#k8 zgWo!m%c6r*f8Q$neFpROY&ns>Yr4%Y*+A9zFH`h^hIuEgjZ0VS&vsp!2SfQ$*xZN5 zQY?oV^$BrFwY0vMj~Z6LdN<6rhHZOtPpA$TD`id6v#yO{@~U(JBX3tI#MN|Z$hiA% z>-=um@EX+a@#bJFy02%a>{hlJX*SvyFIu5Y`f|y+!_9nXcf-gv8C%oN!NoUtj!jpO(a^D)I)cZ^0*h>(Ok&bd_oL%XjY0wt^Q{&4= zzOxQnJ9-f)lrp`1p@+kSV5W4T6BzI+f^8(e2X1e~?b4&Uo-f+KAw}2*!&{Jjc0ZP# zs0u4VivNvnXZdUF$?8TBw>Y-#LQtTqwI7ZYBePn6Y>_pi@b9i3Xe6F{eW|Y(O|m$6 zpdoY)Y~oB6yoEG76Q{zE(MYG#u?~}tiYAk6XX!{@eh-dw%8Uhutf0PxjqaLJ{Euc` z^QzL0g;(5-8K2mPlZQ_Z#{46+m5ZpHq$6`mJMmN{&N`&@zZYVDLnjAA-=%U-*ZlJc za^aQ(a+yZhrdKh_U%ClXjD{C4uZKX~DyH*Tq4kN6m9D|Kz0!xyB@fryxFfWL->{a5 zhce+=?lj11_y+gu%<8 zo%Amuqpq9w+7xj}n3Xk`O0@GO4c+O(M+k-664%hdZ* zX-p&-v6jmmWs8Q3{GD07C>w2s(Yxrnb5Bieubeszo}jF|$npxb;agIPm*>QjJeXaj z|8ur%QxH$fmQbO>+@<*m8^y&M>7~VSu-Z1e?aJ0^sqWs~`P+Y2WYqZ`Hpdxbk)qzk zSJZIbRny?66@8q$v}AKdhM5zF8>rJaI}QXf1|dTTF~$%=2tkPT0~dfG7!U>of@ASS znN}YYz(7U=ad;pSibH`wAPfeBf`A|x3`)@!V--L0{o3(y=bJz`8Uv*d%p=7)dDNvQnqMB6g+SeEYXM& z5H%Lo`;GM2FU7dfU}Zhru0~7X>o$Sby|V!V>@stcpcy)TzJOk4!vk_?=L2aW*tq~r z2D39EtmjDH?3u&VR2cGtB-YqY!D&csv%wAo7a`%14Q z0@#L1L8Th`(?qv-Vbb0E(!xb12 zziVi1KN;bI&P!n_#z2Bby<-bT89~EfVaa2h2mX6>K?mpvExH+X#DfeNf80Ef07`(Y zsDygikNm$Ky(zVb)=CA;K5Y;kDjU40tB>0ql|^ia0HC1<=j?@=)FJ%`)@{{4Gz{5z z7GM`f3H;+I-StsjGE5aiPaM3nl;G?OGVsF@%G5-qjS8|!m+(P=YFD^{8gHR`AvRIt zyVm8z);VD9r8UAIMs$1N?Mrl)9 zCISFQP*;waTD1>eG8yIsWBxZINn3*P2zcxsV@#kwm9P|J;DGM8WDCYjKs(dQ@)_aZ zvW&JXM#x9z{w<6#Y@o7~t_5S_K&g;iRWQ!m2y~FQvTC1yc#uI|hpRWYu(4)^nqg_A zhdQcDy#IobczOl)zU?$~D|%VrgT#oQfYTg7~ zV(oSozMNAcjWe>(CmhU+35so=bPld)@GK%O3^M@RC|!cL)5GNuG7}$1m0@{^CC?*= zsAh5cv4OGxLuw;GrFQ^=VQbwYkcW09B`5^Yx4l?Ix2{tn6DAE#d|IA0>C z5hK01YxN{i4l}H(TpRJ@Z&2KQsxPsgm=lAm;6vOTmh3?k<0wG2Z%yD1Y?}e;WaRNA zm^jD5hAT0gJyQ{1gqFn19^_#T9D5B>`iMpHY~hDF2Jv15Y5#Srhj9poPsOGn`v_cp zOU&_&GBIcL9r0{)HpKU^9`TUhWkAMcaZyBvOPELyaDd^#S1C3=G;@xrOH3fLXB-d& z2h+2_MEOZnF%!EkFasXzgsjnl2HpAhLokW5d#v%@TQmMESdlikZq#l)H{6hLz7Q*L zay~jXq#<1<>@k?}xYQv8p`8j$oC$WI>C|}=0A$V;dk`S=Hbz%W%wPiJyf}PdBNC3? z!Pwx8^L}wo!whhwa*Y{*2EoDVs$|3n<}rumF@_1`aS2J1SfmAL z8j)QrIygM$y^h7Oe?~&vQj7A6y0EZ%7DVYO`v@#)vc>#B3cw8x%nFo!-s%lTAQ4$W z(s?;BpocULsa=UrKkMZ%gqh?*+u>|0LNb)Y))i-(|duQ6uDX{WX!mD{7 zS;Y&uxUD4&w6Xez>IlR@yB%;sF1Qf0e;U_ZJM?R@3412aLu4VqT;&H)y#^b|#amzu z6Z|w>3@pby%OC*E$)xu!C^lcx4YL0uV^Xa_fyA^mzFu-BVsh?9W&03|#iYC~+|m!; zo^LsFp7|#aU;Q@_e8Mfc&8@vVBd; zb9*ZsG3?ogZ9XYa=JBd!L1oX?$D}+T*Ng#6i;b?m6y?c~h48$NxntlkDWp8!+A)`n z4TZVDot-z6*s-ApfUL!rBA}7?lur9?^@i(`u`<}dK01*34X9f@G}PGsFen%F&3*c zT8%IvIrX_ugURkcitcwf%73t(ITiHyCB}*^ZEibv7}^7Nz77D={z;C4!67DGBlK=_ z2J6SHZp|1dV#|~+zZD=L5j*H@Tfoe1Y%aI0D>q5Ox+Nf=?ye$KPTO{=T@#*uNx`zV z1zoA^z$$h?CN5$=tGR?VzGR~LPzZ`6G5Ws7aUMJl0KjjTBUmY29B{MXjH`|yO`M+_ z0I}dDzr(RBhkJzmE<)+ulJ4Q$W$zv*JoU21aMlsTC&dHnehJV;MFD8DqA8in%;JNF zCczJ$2m%1A;OLI2@{y&yAX7_yC>SssS(i@w2D^9s9L08s5PADa0r1S)9S6@`Al)$242_i=@%X}BJMIouXdU2|WdF3G!qqTyE{|7*55O&WIRG$tF$uRgW4Q9I&_yitrSy6==(kAi?~~NuDx1GS zc7Kob{x13ZHoffZ{;hqzKeT}N793jJncV`}4p0$u4QOn>`Uk>H#B~38=_B(1W~~G_ zV0IA@8-;X%%>vTzG2jZ@uxKFOUO<8NySd*L{(qbU@4z2op)j0GG=S@c?&jZUaUTO@ z&w!Mdi6hYQy~hZ&!DlhA5dlA9mSi&^MnYuJZJ79-t=-};^7eU$G7 z=w_-?sRVWBj$+3$i!YjAG|A@Y+GMNrFoEpX)2VZHvJ-gmYlH6Fe8BY~)<^269&li# z%P7G*rtq+q$BG+0HPb$z)!?TkL$;LG1GmoufPXsR>goA^Jny`70~s}O*IpjhDG8iUF#w$+z&%BQbBclQ zlmqA~-_9w#=_%olFOW{N0og5uu@AWLYp-UU{ewOpXT1(%w2B>204_-zPli#H)WUiu~5tfTRP z+~=K}j}|>Co#043aEa{ye;fAB$e&rM!pq{Z8JCgY22^2`EY+d%{s${6o!HL9^gJTmPKW@s@Fp%J5R@A#cvzuSHdlbiXgeiG!I~9tw`_?!EGD2C z5l9HU>n6}@QBvD${Qallz21m(<4yVx(8DjUPnI|1<=y%+Sz^8cKGKSfE+CU;S8(~D z?P?gvK+qp!cQZSRlzkEQ0>~_PFGzGC=*p-rATvNWkoh=Dzgo)88tLLQp2q0qXze$+ zpY9#)Ej(4#&ov%lbh+fCERr=4ImMIQ)f4E6>q;GHsZro`NZ?aDh)b=@9prAp;4bNG z{KA88evd63bTF-aFdWMgVlGq#>(pVAA>Qx~3U0>SjOWd5zV(Zeho6P{B21 zHq;n-sNpiG#>Pesl}8&VaLE<3f`u-y!=F|^j&D;SBRyog#_6!j>o?+t@#B|nz`uZb z2~ZSVZ_IQ}OdcP%!V>^s_z$`QuJ;J2sTmHsD?D+Rn{`*Y>$}8ZcQt)?`FwYYMeo|2 zPj;92`32JCXb%8N#7A?W4Jgh!m*yAF+4ZPm=*Puvr$?O|;J^Xe=%45A@D&CCXv4cYZ3#ad4GuIHn=wKyS8;q1 z9R7Z8uwqar0{vG2>#093+W>&_U`G>-9*4NcQTqUA z>CsW9?hIJEh&?^|c(`lQ*f9+1__iKX)8uuw1l*7Ztwlp&9rE+ge6ARso_*a;<)`VS zoR2k=ELAYdvv6)CKAIyS0#fH8=&aboWmBM*1I8HcEEzJI}O3Ysgxg zeMpb04a}7?_IwjmU2e^qlXfTohlD8x4QZtqyS?$@Sems{Ml>StM|+H`+I&uC&gSX@ z97;f#(}W_3OO~Mw)1(ht_XN_6HT@&D`~7<{X^Vo=!7?vV_vg;##igbiWe!}k6S~1< zpiI7C(Dozoy7GX5omrR7MP)>0XNDm{1Njd@mV3QCK!S`p<1KPN_{7{Qy;@sDa2PHmZmB5bc0 z90S9|!><)XMHR!5WWfNc&=CQ=v^lnM(^U=tO#T@B6Cd*t-W zdch^#F#(Iqs$0$lvIVdOQgJy?sjgXt^w>poi;9dJbFAc-Bvwpe+e_2ZvFBX2Ck_MK ztnvp;q%L0D$IH-9haDW8mg_COdwNZc^O%t-G2|q1`#%J16(juh38o`1G7}76bsQ^Q zJ-0zGB#;%2%?*ZEX#3K7?3<7i=*y&ZOv|aUXhq!u`{j zzG(BuX?z<-EZi169YpCr77VNKEPB=5Pd3P(({2BFTAQfpNF949 zq`E_wGA|{Nn=E1l#;p&wZlUk=|kV>3&(!cktb zS!_3SgEMl3;KU4F62h-U_((63vlqD*^c?EfRemW!yvC$H$A@M~6NL@}a78WsDAQIz&lM9?^=CPQ?S?tqntV}{+* z81g!(saX(0MheHT@C|gspl&!+iY*ej*FnfPmWGJPa7jCA>%GGQ$L#;%AWLvbb~81y z2pG)t5b1?@^aF9QU{?7;i^7G45WLeix}GDkGKA1e97w;GW?ATG_^tkLByy3)f?AU_ z-fT#1D1$ECUCG$^a4-$c{5Qv4&}?r^@>~wi0ri^ggOJDUO6QC`b+zzk2ccxe$XK|g zl#VLQx42f$eG{Y5Y#f$Sb+TM4kHB`7S>ZmkhY1vl2BS_m>rT)FKmS@|A|STqNKLSG zEZuX?l$mQBY2N2$A;SwrXbRy|cV1sXm`uz{NTq`iIXS0T)_O^W8FXwVaUJuOlI*OM zB`T5)mmem4&SRrg>bg5BsVhZ|g%8_}Eh)i6DXHplhTUp;;R@GG(ySOH9m&}8fWNuU z#(2SZ0;T*7&nHZGv-NIJ3L*9DU)jDq+`Op{H#?`7&t+)G=;03(ijvJkcOueWCuAms zKcRzE<4N_;(V0vr|F>YDzo7J_dz!!Py-&9`)(0XtC~P{vwRcF0&@j&Yh)dPkwzlQN zPV+Iw8H`PsY=t-fq)k+_ zqWuJ`Z}g0X-LSZyLh_CghOqCOegp^Y`^qbQjbwNnVKWq@_&%^SXuU=?%^!c91n#Y? zWoiq@6dmM=oHx|3V$txDLDY;ms7$f-1Z50sb+N%!_CT`pK71)&0j+?72ByKTorun> zp+YidDOj&PW^Vd99vCo#nFS-o1ibSsKMHtLzy}M&D92FNh$a-5LzIl=aYE#e;Nac) zIt)WA26PWZ0DuD#0RRpdG?;(`6fo<72mo;46=>jK!308u2=^NBEYL`JoZFqxDUP_T zkf=6H9j2~cCdy?MuAB)Oi76bB9ZB>ve{&A8lO;1X8PJMGa4_I{7`d(r;u9efYAS@h zFN=l^m9WE`dTE}z(VF=YNhF!I0_|Hco_vcdeS7<=5zT6r}IH z_dkKd#-k|0?g?XJ|Ay<-r+G{$%E$>UXVx|h9J&viipydJcl?;7lZb-^ci7S@?5^rx zqmC@y?LJ(ba75Z>V%ZZF{6(^(DW_zT{tIjp9OSQ5H(u2XpL0V{Cl9`y=uC;trDnQd zLKJ%%RIA(tqXVjQw&5^&8Xaz6M{Wor@_|sp4iw5b?mx7;RkQf{%ryo+y&x{L-_#Bq z3e)PMe)Jlm<6qyROY{91x06i~{}QP<-Cllp+O)lxg^Eo#9aR#u?bd>QUr{LM#|M@V zj=g%1LAmn6Y-%kd#d&!kt7y$;75(Tbw0|-Q;>HxAbRH+kHh+pOgira}bFmE)auRnt zu!lh9m|Ee|3u{l8KKin5skAFI-lya*ux1CDiSQW0hB?1(t)Td_1LKXdDdyi;1sgKUcD%k2Yz`w+4&SpfI}yg6vu1|x5>-ke9a9m9_C7DR_#t`Ty4D?VOZ1QTqDpi@7qY0br6Zjknh3D$8M)|+haq8(V+dgX5v?a z;dY8Ih$d`wW`@c{`w)q>KHo~&jcSphH|+1XV(|RoX9X6|`3XcZ9mJ?q6r!DcXn1r> zM)|nb#a)Pob<{PR26C)mmv*X#f0x z+_ZE3ywo-+DyNMbR8?ous$*6c-n36BitGJ=w~i8BF>Q?{!JIV2V;1(#&wJ#jSe5gS-y2+l~FTzx7<)@ z>_8^d8b5v^Xr8zBM($WO25xnw@UXeWDFzPWrYjiYS7{UD`aTweNJBS(X} ztnW)3H~8~q9F!zv5q{|u7aC?rL+-`B8JTMyO}rNQDvzKb&Jn30J?4qCw-B?Gz#Gz0 zeWa9J>G03f-;=leMPI)0JS)N`@h$f~5qJ?hD%ZAQ0R{Cspon{Ls_~OJ4WCQmN+`79 zOe-9YkS*_Ra>xumi*yC;%V2XFPvH^Jt3E<=gkGh;vf(n3)O$1Ams@t0q13PT|ry>{|I8W-kcS7x0jBskwSP+wSA3@!nF`4D{x@p!@PaGbqZcj*M7#qaigBC zA$gSoPlOe}4ZUYe*UyTx(v*)$BORvW#Dg>Rf*2MPVRYb~=I-D&7x0@`+8qVEOyYvL zDu#!13kGMC_m!~J8Xnga6BHR#LbtKx_H2)y3+6^!OQ;Q>9e9M9^lKdIe6wqv%8W%_ zSJ=af6XD=i*ZFvS_;OnO4;A@dIv$@gVU-#Pki;4a}KVF(dPzUqw1ZoRYCXGooLSjCQaZ>J(+mjV0Fy4g>spyhu zWr(AIMI&J$6EWXIdYWSp(hnXBv0iwF))~$9hojyh1Xua^wv&T?8j-ux*2JesKZm(J z6N=BA$MkK{xd{GYD7npU-dMgu!Vdw%j6R>`_imZ12Fwr<&>L^ke6^a+R1t%QY!nb9 zPz8;&w>YHXneOE_gF^&f7apR=q@57!;}NYR{fL zUjBH~gMaf&0grlp+YHSztoY+(S=QPF(wKeN4btV@72aQz9T8>sGQx%BR&m^e&Wa+d z%VO+IQt&XN74AcLIC?i2%2=uG9?|mjc(9PP;h`(}k|FoiBYfPM1?te<(xO72j1pv$lDpC@(L%<9 z#pqDjKgGuDF%5J;o6X`Q1jp}sp8#k_OsK;5%`YdG4baJXY+>5Y20o! zyltrLOI^(65aL6yl+&dLb(t&5rkkS+6L0g$z4kTjl3g;qd*MQV2!9>d_%GV43mLZP zk%u7!AFJkf`{}G!zjvjNC+lb1Euxr~c93A(Fs>oy1<{-pU2Z%hZk*WaJ4y?U_iOw= zH4!1~a)v-=)?EJbAw;E1vRJ2$;L&!WNp$*%NZ}XS79L{^qY+VX;RWW`{R{r5Ei7g~ zZ`UDE=OR5+gxf0bwx=b zwl-xfIDeTIfBDd#U{Oylng?m3B%GZ0>%$zU@?YE2!uwIr;ORr7??ua6{ZD1I8=P7F zYJYDqut^SO_?pnPbhBCKnjttCYwXrpm-(_GQquLJZ&m1W7rEz8B=p7Ev(;Y7oXMt1 zk!O^fh4wD}xkC?34>^>>680oFbYNBY`6&PAi_-RWf9O{ZZFSM*C?*zG3@wF*XD53@ z#tKT&oHn1{PluM)3UjzAHam?>S`m7aX+5K|3e!7>$rQ_$t=a?AA~Mt1yMG!dJIy^R zc<>EG@8iLPU276kmrnR(=;De7ufJPXB$n_YP)CMhaXmZ?^@nTYv$G@8)+~QxWDY7^ zSFMJ!Gn(5)Bw_9=7@_~aR;|$CM|fvm2z{q=YP!yqoP*Cia)`~_e~Dw2$@6CC`yOkX zl&j;6bAdO=KLxY)B(Kg$>X4CpXy-lNNHratDosN%=;_=9K4o+^)D6rboEA1!D#@6_ za8c-8^APXSchirlCDrm#xf5nwQXW28TvT@V!h?tVo_AeA0=!J7KkF7ewq6J1Qn#UpuMsoao+>od)zvbiJgHq^(MN#4`sutA5HS)o!iBN)L5 zMlgb4wW8*l38nON-g-r90q6MB(2I?F?zQ_SkVMCX=#)8K3#mjxO9)eQV#f?c;Yr9c zEqRFhf=j0K4d=p~$0NntK9NGu=$GEZcnT5}f6|;VD^ziVQ;4EtRcibhYD~UsY3?vu zrVwEiaYigwF40q$D2pw% zD3sZHixTLsS>y2wqcndDYl)bUct1MF=9XW{&3)gc6k>koj*?dy9o>1ku6|HC*NwlQfAE-`%DNzN z=M$nGXwr9USvD-=vMcYd52H>qXIfWXs01_bhENKO=~w0+I^cegvTyWT=f#cmrYh>Q zpd{pT(y@opWwa^5wbwg7LYcAzzJ80Fe>XYW zgQ_;)%!l9h=Mhn`gJ2Mi@bpV-rBxveh79+&-w%WYoTI6Ep;eZ^&=vTR6n0;N3IpA;J5BNN*FHFU!0mJ#2_TJ~U?**HB)MUK7-kjQ^FEMI_v# zUn6Uf4A$mieQ}rLz!-wR4@T4X{aM%_l(g|-}ZV*m4~5UWc4 z%s^CM9D-0<3(I2YURbYM=e|GNJ!e*qr$B-E@4WBKbrH%!yhZ1wXxdoI%^5|cI?cl` zu>9qZv;@cQ*Do90Su0k*lZ@#EaB(0x(>|q6@rO= z;B@7`1fQ19+6z1W+R3Z+E15^M+#Nf|N?K-XD-JJi{0uF&*i+K;s1}GKZ~{9gtp%w_ zlhc=$3lZ$G^PApq3X4C2hrl@I+-PBp|E%wSE%>D24Q{&jvVFT!Fcb^Jbsu3hQ4dKe z^4c;zZRXO+VZ#)TXm{thTtG7MkNqB1-7c(oE*@3-pi9_ECH^DF^L%>yVB(G_=?|Cs#?dj*Bwv zQyf~I;DxoQgUB+B!XU;NV+bO~7-JAoiai4sU?30(4u}H;!Z1>Vq7M_mzzhU|AQTFR z!vRq!31ksbS#gQM>@Q8ApkI|Se-f%gx0M9K+;S#%edi4M51U3O-2Z+2a=g&61F*d7LmpV z-^qe%skswff8a{x*6vB{^s6{1Gwwip46YY)!0JtJapXrJQf$8sD>;Ush(?a*(!1e5 zp}}HO8yOa#9~Jl|?J2hY*w;mO2>K@_aP7OGvq%q7^6cP#SN!3ZS({yDF-)>CW>Wkm!= zd~Q4Fr*M?Nu9W2SC#9Eq(|S2w(n{La(o5EG_vuIVK86ptzpxRMJrUy82Ntx~*(n70 z&1RTcMIHr=Q3qEdzWX8x5fXl|(lAI|S$QyA=qxibunbC^g&N-6$L#Z-a&*XP zmvtsYQLoZva8BLpG!6^VJ}w;G=MzZY?gZb&#HYBE)CzI>htwNE*3;K)O2;}#1t=vl>(j}KfoVtBp*1vUz_dTl> zit?H1U;bX`tf)T*g+2r5H9FpfkqC%E`%{C7lJXna<@pL%@&~+ z?36v1U7L)o!}G{xk}G~KbvNwHJKE&Ud~T&U#dR`nVZ1+}6PH6!)e(JnC-Lh`{rK7F z(l#7)9BG2M3JcX*J?cg&K(0d4PXIHt0uX=@*6Ro(`kYf2&F~C_PLVXwrMcO160H1= zjQR_dKrYjQuNfrDa>S{pbn)DBIGu`+Mf7!4?tD;nLDT%6=KxJe)W3R^vTqrJBLPdWe|yO(x8AHUj9fQlLtqk=HA%gTEwk zS&9CmxKGoq^{ z9$FI32XmWKo8jQ|S5dB6;<(dr*Tg_=0h;{=2#%=31S9RRV_$oN;OCol2H^Kp1vl#a zn-MkyC{tL80tbx?(KlH&psR^D4O&KkE4VW^ekY+MR`t!wjpQ3pN`mwM7C)~5*F^~w zsAUO4xD=2wQWkGJIGPqDuFFg3$bK~WARFqC4N78)&m8Fe!zK4hjCxi4lK!S>%s5n2 z5%Pl2cR-n}Ljghc z0@*bZcM&r#fu#DvlG-5C6!{FueD;q}E-G7Ry9=92z>hQ0Vuxw_?)X`NND=<+Y>g3$ ztzjeEc%H&&FvD>$GSz0_fyGJ^f1ChlK;)3f%7J;7;oe`?F-sE_NL7Z|p@V-fR+{i3 z&iuJbR<@_6XjT)e|3ApeMtqnF!#5^fDx?P!891Eh{B@myNCX;WY~h)({>a||!W3gW zKj=&UU+k}hM`xJ}RaFw{%%p%I zv{m5?_97-7avHFQAdX;ddwwcoS754aJfmO4<<>XY85yy1XJm9W4rV>eALS=p1U2<( z=1rH_%afQKVXdt4`a^?OHiPq~1OZ0E_eA)TWmB>_)HsuTyH9L4Z9#)<6MMt^8K@LP zcsL2dx#i&G`36?5?qaQF3O{e|bF&p$5pWfzKrHzm+OFA{di6KEJZ{A8UzaE96jyiW z;|t&A?PpMV;EJy@ejFwrez3!eB$ne@glGa#16|Q2Alcddx%N}2e(`ijD$}zh>kHIR zZ`}wOm!Y#~T*QI?^^A=uV-}yH86j>pwx!Hg6GXQC%RQoyAIH4*tzXkrHY|1Pa@D6u zNq|H*g|SZ}_UiZdP``%Y|1kJ}koFHQxHjz~D1{{|ar(^$xeMMA%~2>wbtMQpbZUZ) zpC&mz0~W5I8UX6z3rOC5)G3OBOVr(sgel}f++ww#m|s$d7e?y86gbYE+?D>xar`Kp zQhdL}I9O8Z8cb5PMMhx@;0D=Gpr3Gc03Vp6t1ax%^|<-49Uj{Bc?nRcvc0X+lQIK= z(noqB6!#4;94Mopo@bKrCXrHr%Zn6i5=i7PE=-rbqiErxPXy z2;*y9?Ys1c|fDb{3$<5mD` zs$?%t@6?=(JH>1P_zxK@N(Co3#4bYrHYijdT21_5X`_~39wm~Itf^BNg$(&|O_cP_ zUP&jwASLQTHG2F%^mF^^mf>db5}`Y32I`CH`1dPeCVXv0ARwnIKUJQS&tj(`2&b0K1x!ROB!SoxMRaCf*q~VyhrN`m$Xrx z&r$ANX(J)uEMRXFM@$1q%?)hch$@Jca@e#{a6q&&vJyGc8D^q`-CFAmDi5 zpU$J6MdkzN2lnQtEFs-5xW`5t4=BcwgDar2AzyhXNo++~+GHT}GD(VMO*KK=@IAz# zn5(`>V2|u{QmXKA$L?mMARRiI7@4b9F!T;~212z{00EDW>*hRe9tgtP=`<-~@1GFN)K$lIaAnxx{WnJJS28%&bZ| z`+WL0=If;$=MS`vVz45|c|cc@!b%;%0Z>iInmK+0M(i*Pc0|q#v5W1*amSmsM;z%L z@?Q!Y>s9CIEC_<6S0s+~r~#Ro&GMGmC z`B|I>b&DNxWR#UmS%4379zPHrE^(a0nJOs=O%#oV%|H}^1Osxv8FKilrA2;iLz*hd zB5ZV81`*NhAcZ_HL=U0Fr9RiojK>mxz*{tCX5#)E)~L4 zJI)jpoRX8wH0W47Y3?ZKd6hvic_Npp4j^6p1l_Vu0AU0vj6pjm~Rp$7qms409t5*S8zy9 z#ug%D8{pFMqNY@`@T*Zg0MQAv@|XE7bV>XNtuwrH%B!0#9nk@fGvDcg7pwu17B% zs0-(x{gT9hby1=)&UaGJ3dGUcw-LB;3tNGD;#gU9AL36Qe!_66{0~i_B4{cNO9VKv z7;whj9v_G0n{CER$od25d|jVjIKUdZZs89Nae4B@Pdp40ma=ZCT^p`Nw?{ap(?iUV z6u|Zg>p)PQHPtgXlK1h|y0DI(-OdyPd_6Aig?(2%u6Y`w$5ukXs0ah7`s`np(sD6P Z5eS$`D4h|%|KlzWMEd8z`}e~W1p5P&V!!|Z literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst new file mode 100644 index 0000000000000000000000000000000000000000..1d7a3d2b50582460ea6e1a9555cb5f133da371a6 GIT binary patch literal 15182 zcmV-UJF&zlwJ-euScLolIxzZ6BM?(k(gFNG#vcz5P)>#sqB#G(@t+4TBu$c;4IEWf zRaI~UHU)76a|B#Ep~m`-`K2$m(^$HPj@bF3r)4B6h*743hxY8EF*kDU&k)i#xYYQB z*s2Pwa;ZUzZ;WEG!;L1rtRvCj4E#_SIrwEn9U@7FQ3U< z803jJyW!K<6!aaA?bE>d*a^W#2{cOaeIyxQUq@o9`8o0+)Y#VnF@(4??lE(bV_Dhw zVGX`C<>RsOW)<;t_{Ut&wZ84SWs!TyZW&{%;pvblx3N%aEYvVHVJwB-^LgD9^-|@Y z4xKwx=nqNq5YKwL#zxf6_$qO z_YzsGRApAU|1xM}Xw_>;Qdd@8uA25nRYhjDg(@#b?3xW2NRR*q44hdt_}I*ZJ`}46 zy_ca&YxNpRq?Z_|50RF2l|+S zVJV0{tGqasUR=nvK$Q)Qx!-IQ7WnW~oRdB5&|K;7*U6HZf2gu%^#&U)>Zv)-4dJO! z7()5X10ix3I}4*khhwvd$i(D;1~MRlxV=@tIWU2Cpg{(Vf(EVL75u@11Jp4VU2XM9 z`!T7edF|a!jX@PcG<8|#@F6e)V>(grznm-J00j&V7999#00a#VL?8hG985q095`5T zuwg0$5->PeaA1ZzhPRSwS;|GZS)p9Y^`<8GLnd4~vZ|p5 z9t9M;c$*@gj=>1uT;?FR2#uX7A3~FFWBO3UOrRdn3fck}_lMMEfbyNWZYo(E%O-!n+fd(XS_6iOb9C)2^n2fs)CTkirTa1Z3f-I$4r}7eY z!v_m!j6nY(cq^xabPAWd(U)S5tSH65Joo?tBWx*pgW2R5)+g zZ@WSVXpjM~Ks9i%;DCwS_+x#?MY;Ej+hvhL@RO~_zIoBmwrm-md3gI#!v_37901_J z0u0mw2O_Pp-LI~L;lGOg2 zM@Ff9G1Tz*oilU%HQ~r+6*K&^tV~GnWrAym)G`zczOoPQs@w6Vd(E!61k8ELxz!9? z@y(0Hw_37K&$*T#8`3MG+TW*}ZSj|y#I7(#xq(46U<4v@q)Y0y-U<|T`JwA$uH>e< zbP_^@2pF=hCK+{1J}+^y5;gG8N|%OpSKPo*Ss4ab=Xtq*nrzn-SAH*B!fC$vwl`N| zYfwelhz>o%w|qyow(Ja2t2`G%5QXBC6dln;-qckJ{tBzimpu;}W=?G9CX9RB=&Y6% z4w(bXxk#f++2iIbey={X^YF=SwocU`dz8vchI^-={uFOfdCk(+6c)aqq@ggAhtqFl zGPJ^UlC(7-bL;+UGsy|2Pf&R(x13Wybv5@GnV+}d%~!V-wk+8~Zq|AIZCUBBllN$8 zS0GjO`w%b?Hx|B!t(ZYK7DW8sb>t`yR!g~15@KbP(Qxb)ok?Tyb zC0=?7Z^^gq#JeKm?&ruIbFo(p8)R3q7>9!(oh634zeHzUpFG!|=ljqf!v3flz5ksy zXG3a2|2fM^XY%Fv1tniS!U|)CU$y<+CnWms;Yoip<+TFkaJtG+2`jaFo=%mtH*U>v z6(?pcyA1Sk*L9r5XREjv>4HH6%521EEhp9ZbOc?fRn{=lK#p+RTFMEI*$uqHX(FCUSq5jBlq72{hnOKP%qz)EEp~e0{panyp!nq7y`wLoq=zYJS%nL6OA@?; z3hB!qdV5_+%=M^#8k1k?qhL|R5UZK6PMgnj!~VjcX2qg6yXdxvYg~8B9%oWvtTFEx zyVkjc=S;IydNM~XP|pk2Zu?>q3O4CRHdRS>W9>(X5MIeRowj#FU1GAzwKVN5+iOXP zZR=~y$_ixx z$ywsKEyIPn5Y9Cp#WTYANpVi#ero?v9+guMQf?cKLD&9*L^-oQg>_VrpX1;Pwm$Q9 zpR(~~hPKhH0f#5thvy#NV0)*Z9Ks}&2L)PmD3J>}4_Ti|XuwdauxUjr=J?o6amsAr zF*dRH8S|nO_Q%7(d1v<_-A6i)Q4R7N_u=lcQg55y7CM{;pJXi0N%AHh=DKAzR9;VV?WnpB!91oU-s?>+WL+TZD9^z{ZnG!gXZ7{|nuGiQW(@D6c=7 zM{DfC&O?Y%?zN5JKhfa38zi`?56`vGxS8VeC{SahFcNN0_`murTPb~-#ivKghA^wh zVeJ%7ICPtK_~qhYhc8n_HriI}{5iB0SlO>y6LhBgm?o)G{qYM$YL2zem)V(LnWdqnI=Ovk*!^WrC{o_dLplNxJ@9X!3rF2FzDmz&9nlc-doVBef%tVC_ z4jZqd&`q*4Kfy8nBjyNQuC@?U@l$Fg>d2T7>?Nuto2gkuvIZj7)j_QQGDhuEU9(zr;Rwa=V|xHt)OcRh3#E=brw zK|)-QggOZoXo7r_e1d3#f|3FW1sx>`B_SONWkjSr6&*LfI`>)xaVB*B)-a1fiB5TP zB8>0N6c~cv7NHG4VfMIQn9r>X=|HozrIziL;rtMsL+$XUd_8HXkrpCUbKi3J3>zgk z<2VU!bwKI9N@y1XzfmSc_v|8W1P&xwKfgQ-Mihden?xN6c|lbse; zWT<|0MxR=NV?|@yQ{4$J7kVw~sf!*%IoZVq@R# z;W}w|pjh67!BMn$+6mWsp@rr85l`nOI|O^=6Xe1=)d&=pP0rEJdA5+U+a%EWXHq!1 zY{I$O?OPbpIlT>ItD`v?or%wrmsO5#5*REEJ!t5EK%;J~J`L+5kz!1#4+@zL4$*qA zK|9=|S5DjPS84RR=7oA!ht9vY`1mcmcWFg?=en}V@zXB@TLyRa7S*R?y4Zo8c8*@tEf;5KU-!eJNXcq9eoOKwsvJy7p{VjB$;r|IYd2jU`7Mm>ZZ8>Mn- z3wA*(WAUW2b9Z4w<~x(vQ;7GbNl~2tjSw7l+AH{XK~F?4kbMJF&i3uS{Zan8jRk9( z`n9B5;=MYJ;38J?ftQ?_XI4*?nHmbsS5*p8qFVTud!rq%plOl+S zob67Q%+zQi_XR7O`jZa zW`yF=4@;c#T16aoEQQ>?yw^+ATPJ5ZY3GEJ?3QNKF0dV3YYD~j^I!s}?atX-*D^axhGO|iBc@3hHQUb?x#D^Xjyj1J;Lgm1ya)lJ&zSQEGT zDYShJA;nDFS@5a{E@z;jB=O@AT8KhW#al#qNJ*n0>oL=S{4@0kh5Swv0)s&H2A-amFHox z#dlMZA|-~Z%Jneu)5UG^;(aqN?e_JggsO39VZf8MmSO`o}YZ#BHC$L!RAkSUvG=+p^n-LkdkA z*k&}xnaloyw-Kw(!cAbkCn~>_`2|IEzAp=HY2kJ0{y30SW;3~EXf=^)4aUi9!AKRa zv}Ic*YL!;}T$@rVy5+@WkGMrKRB@27vE*voZajS{VL4Cgx&zO>2lZz84c8vjP75mc zIYIs>|4Y@vVep{kIaBQ29UNC9T{aslkM;cnRxP5uVemRDGY#iS6h#+1X}j#_jkF+K zHVq3LPOm|?zl=rSOVe0``@N+CgtptRxsACvI zj6^YG3^9ZdLWl$+GwB0E7N8&)5C#OoV{w5z$vzW+K!)N_fEW&lLP0PP5CnpPU?3m} z0to^P1_HrAAP^u11q7lvxqJioz|2$WYvNW31`z3{`4GqVgfzMjIHI@1MUfxOx_EX| zDaQ0IeMTtMjYGDmT5%$P_PNT$+ZHWtmM)pJzcK0w{Gk9#836?z%MIHz z9>(E=S6Qr$aVzjx9;{)+KXF^gIPd)1YqG&tk9Alt$?k5J%(l%Gve+2YXp)wJ$N}H-5?4Pts9rbLgkHQV1Hz z7FpxUs0w0UUJ}HA5xJyYDzk7LRE1#aE1;xa-vYB!G!x+P?Z@}RxWee?2|-?kI{Lva zL%4b1!G=Mf>*w!ylAn7r{cpM>xFT%v9aN_~KBG_?U)d4gI!4{0X z6kRWCff9ZDrPw1~B*1YT83M!$S|@4DdbcTju?En?v9VrsAU1b(5@jP*%zn>F2E=Sm>~9SWTXd-k}yjd8Gde3+scfO z0!tNG9b-mdAv-o^R0@pJi~VJs2Np1FQH#PjPjO!9K<-M}L8*SQ8>POC$wC(N0SLhV z!NBpY9Xuy^$0dtAt~=QE1B_9Mpu}SlY}fQYxxnz+BpC+RRSovd^73;21#9qjB((}Y}v@D7RaZuY^6LZpOkQH3PbNq z#(9vh!dR^Nr6K>@i}GaNo|ZMhj*Do4Un^K(@fK(UaCTi3ew{>ahZp4;c;QInqD&b* zkOl?2PO3vksK;4s1HNMqjtrDi&;~liCBtA#kNvng44_-A;a=#8oP^vByddk?cPxi! zDcu5&wMQ64H~9Y)c;uV~(gA?49ZF_so= z4GTg`3DrzGXQSSIv*ned8XMWk0>LT-AL1~evBg1RRR?3hK}0Dt*+hqXB`qcDv6kcw z)m}=l>}!mO%8>`HblxB6EL0HW9sEg4%?1jeO0q@F`*d2#GDeg60AD3Ci|P!Hjied{LhN!_lTeg{ zIO=;0#f3FkWw_-8t}U=rEfKlncUCe~Q8kdq5-aD}SZl4l!|Bus24e3R6$RIL*CMX| zgKN%iO|A4>iOAfvUEu`-_Dxox5jBw9hXVzvKg$)qp9ccd2lgFPd8|H^heQB~2m4wl zn7cR3mpu%S`>-JFvWL*i_nX6hK5UDzT)H|8LHgOGEewKKw?B{-X7FzZG2UlZy+O(i zq@c`DeT18bL=c`8UiY^lG*)yr_$~keo+uCYWe&N6bA2&J3jhcU=dePidbcY-rwDF=+9@LAjVqaW;F?x}0U%csFlsdogJp6^FldxjS zZE-B{3fC4@a-`~UobmW%8Q7aC9)VUNi?`ds0)THMKvyHi&@Y69_G_C+!}Rwd0PO^P z6d~Go$-q7bA9lwdBEtNkjQ46?_1l-O;Spv{{o^elz~pJ&G6M!vj6nGI=H~fw1$=D)^rwNEJ5r_zwtE(N#j=Q&JKO zGrlz(Lv4UL%M=+|b07K?9!D?@lC1+DxSET4wdC&UPqV6g<0;Y1j#LHd0CiFNx2pbV z)imSB(l@R>9sm#?)=!;HeWd)#6Pv`NY91n!l@y1bzP(#(epNXv#$)iW0l=$pxMN>i zUjfN)caGTrRRt6(;W(7O38Z>M=ED{3fGr0tzb83s8hgiz zJbGaautC%#E$e;8)@a2Eqn||X$=C{S<_~OCl@u}=H5aDqPyiraD@gYH)7k5%q4izg z8i2LP^=)@+XS>L}6>2t&Go3rlf>dv%p|>Ix-vTz?O8UNW+7*)l0L=wxN$`L*X5M+d z{*$n?dkiS6tFgZrd1-x`ac`Xuf>Fuc4^Ra-%@v{4 za_dfGjVb_m$^nO2MgUrvI$g+47a|-Nc1IV2S{JHS7xvDDRrx|2>cT96E)4J$+BaWJ zIy}$-pb#1mCZs^>ZZ`Y7h+uLQr|=H*v#28l(#O|1gSN5}J$LqQ^b;__h zv(2F#ml*^EZ#1B{?LSA%aXBXqdo{9B6`g%{s~cW&T{is^Y|b|SNw z24=pcm{j2rqu@bpyYUeQB@w1@hpA*0;9llE>KZVnud_ACz#3ZDzG;D>Q6&PKA>9y) z7JoRe^i9B}%3~bT*OM~Q8T>I(|rS%MA1>@cBZ8c>;+EsI;@J5PNW?d`c zM?jXVC!bG~_hA4m*p=%X=-Ct$sUZ!_6T#j>%u?dQkdEpfrQ}NEKTm&8hW$WD z@fUsh#`CNQo5Z(-?}@k&v7-{&HVjWrL*t3Kqlcy7RO3M+D1I)9E1l3{Ff9x>Lbk+F zq8%cCdVDkYEYgMAA<-siJcS3I-(Gmt2Q~-xDt#y$E)z+W@Mg9zVcA)d^7SwT^{2FtN1jw9GJZ25>Fktc^DRC4$kRUSvny2kMQ zos#j3&EmzpB*f2xo{?88(Ho!pgluPrZWC78{p7k#BA~eHg@<#?p|i>R3NE#VM`(%(ibNIcHkR>b%ni)! zJ=>$f<#MB~1#9uM;{shK{TgEh-|Wi4vY;2{t}Cpswy_lO0xdP}AQ9h%g|pwgVQ{-K z;pt;j;c$?PWds*%Tb16hW0y0wAA+vCMdIj;cy(liHn=pticOknFbhxgUr3V(>R{d- zq_!|+(wJ1EBj#{1PRfnBJy|%&7edI8iY|#(Vgw4j3N#TB5n%_Id6#K^D5M`ehOu53 z?5s1I>%)zDW5}&?;IN&H`a$`AmTnWDB6xBpSN0KR^x^Khd~pI#?IT5Ki>{xQl!HDJ1XL;hTO02i#TTXI7u|pHk`_Mr0@W#9_;jRlpEoA|}~z2i>dm zGlZ0bYLy_n{Ov?{jY4BViOV`YEMJtudxUr%XS011Clm`e$0=R`t$>0y4R-Ckb6yP< zk}*rUdNutVkHbqev*4o`ybwIg0|mS(;DZHXG-M}hv>c*082RoTI_$7@0^I`<0N_AG z0DuDq4Klz13Yhgk1OPbj3N&!AU;;5FT)~P);@+Esh)5EJOX0vWUd0PmG!l}-PKw1h zWQ6zT)x^`dT2<h!`V7w z&=hXm^x=HDp#MpUy85|ERkUzY>=;%;zM|RPFp&5%Y0zFnrv58lor}3BmfIuOOyhMQ z{j~Z|c*78O3t1S+l!nXuZ=3!lVps^iJ)eBy-J|7XWB-j3a_rB+2483aY;Ol;ZY zi)g|G)xzCnN>1CqP%P35=VS)9>cBlizAKu)BFT#|7zi^RIRx@!*0lF7vXCq0Fw@NT zrf=pIPGNM4&O&km+gGx!I$Q_I22r`+BMUU;luXhekWGS7K9uUlt9spYE}}YlaL9?} z5V5bbnLMP$da}dV{mdQzNT@C@awui*{O=*W^QvUfUB0zMA1M~ymC0F>Q;x)1+dJb$ znDf_>4@7A1z%q{TkF9RiLlKh2!{-pwy=iw9g0FZKOR{g{dzV0p>k!w+0HwMI)9U7n?J>d_$gl-9CPw^8`%-5{89@;dR=YMrH>9-Vckug zO1m=SeM&wcYc|SE;2+}R1P|R>sQ0W{L8@cIj1J~s2u11M9r?m2n_hkxE3_fAY`@SU zPf};9)`_|IKGAsYl6DY+C>o4KXjl=m=XwcDr--0F6rMg2?t09&dkW#Y zU+^Y0v;y5ZM)1Z3iEJr!B|bK`FhWKMkFa`HtW-_(X^cb|D+Lm_$JSc~N>l`753GF& zQM5h|i2XPj^hrz8^=YCXb((_TEy|vQ$5x_BsLzT+f0T?qg(13LsJWmx2TRr4eiVG@ zk`qdlsHdCu5|6TSbIA?$ZZ7;2h6#F9T9OHWEgJkv=k1*)3Uxt|x~}%@$>ZgJ!FbZ9 z=RV9Y;RWjTZL>2=T=8$N{F^MxTAMf;v&UVOF6S#!R#tlqez=&b0my6nZy zB%$Ms7KRVu;pknold+RpQsW9q-tCSaXOGtUxNv>Dc75Au>`roo58SP^#E#fmlg+BQN-(-@KyV5Mr zLdJu}wXd*kJ4eHRK8+%Vo$PBBPOf_ONg&eeRJTx6y11tl?IWev90F;`2sWMpD^log zI-CwigIsFSS(UkjVQvihJ0FKOTpM`2O7VW&J6(4Jxwmjy`^ep;oL2DMa@w8PoSI4Flvns&)98Qu*Tuph%;$2Gpn{=aBL1t|coJ25Sssn!mXYa70`y9_9rv!cs=!HD}NwmJk# zL+lH`#{W|jff#PXyPSw*X3gaz)Q*_D&kCbY$*KsAS2Bd?f26j3#a+4& z>^314u|iQ2#@42cq4Sq%@s|&MkSprRJ#&=Kc@G^f$Ep0+HfUY=QBU+N@uAW8qGhfA zr!v|_=e>Vq^-%j8=8#QtDDi8sX(`O6Ylhrhtg%~Xh0K@5NJ-Za9ae=x?w$yCh+xlF z8%idaY?>5#M!B6mhGBb`{)BKImyQ_gokKY+xIwb2JNPL7Z-?&3er0T{5M6#^Vz^>w zDKtDg*^3z~Cq)yqIcWH4Y-uf=aGPSY)5j!7GFpMX$+VtPS#{~1!(@78%U11iX%U%e z?A^aK%hTr`g^s>R^gfP`7Fv_IJdUVKCwww=Z$;7TLs-@$7JQ7;k)haI567YY$I!;X zf(0UN&GI)sW>nz{)oLd@qq$u~`+Old;R}t<|6i+CDBMSQX9mO$K_#f^I#+VeJ@ZJo zYu^5lH&&TEA>S7QDy%Ha*WVJ}FH@4>jn7 zK@Q62Y^RINA)JPrDwSkRVYesrt{Lt^NKM~O4@@mjX@_a~z2i<4=&kGQWP?TymV|cF zTRaaX9j^I%_+D8oU#fP^R>#JsE5e^S(Rc)2++J$q2_qQ62u3ghCz24oh?aBR3qhHY z2s)~jKy#hIFMQ7oVKbGgdcx-@cUT)GJrl7HjGEIF@pt3t9s;*&?xx>MS;|-h<-v?h z=3GrFy$l!on9*=osti*SEDs4isAk8+W+Tf4Zc19~H{CDMFm;#TxufJ&Mu9@`a$WtP za;`A`9{jPDuke0Tl`1_7RZABUh9525iznO0s?w%frG;D5Bh-(g6<{jy{7;zlVoLOA4y#Blf)sl?= zm6k;W!=HyfR+J3Z=3;$um%zw}=!aeOYBxV($|A3yv&m7a`hnW!Tdu zU|U{R2(z2BrbgHzWT}!=BNWc>$*z)HBC$zj(unp^+l-mn5mH9S7|6nTJnW?#(w3j7 zxVtiNS8&{|)UDZ)`MgO7*S+SdHjH5C4VL9Z#9^o(v1QWD@OX=TB0`47+3-n!K80;L z>csxRqe84I^)r#Ez8Fy`t%YSTbOWwet#gMDwi}#TInu`J2`MiBo%fx&LSR{lx9GeS zO`G$HNOhWr2W0t>KhhE$yI;R-6oR#0^*hPP?nY++@^9BZ*CufmvENvcaF&L2p4jhZ z|J$~ZGd}L2FM_1pb$Eu)Zb9us_m<(%s;h4PRK9juY~M2u70gpl)jQejC>XRpuxSnl zYp6TB5`Ipr(8xSrh$i}R)0O{%J}sSCAuRCMPKH_!CG&TdyJNwxl9t)pio=WhKC#92 z+NPxEPYsD8Zjham)=(^z(D)!{HC{?y5c}bcs?n#RJ#E7&MtHE${TT43cOWLe! zJWWnDp?}%2vS~epTdj-;#F-oVPN=J=O_Y~282D_&$p7|Ux$OwqHm*btmtCC@rSlwAkCq16dyBfN`DiH%b^Bke85vk`-7jVf4@BsC3Ph9S!wCJpgDm6thE7=#t5BY0wt!YGD8#t=k|LB=q{)E?6nfFKwI zU^E&Ms9C6l+6NN=!p%c*SR4$9L_%QR?8L>zXZMAC;Ilm2hl>Ej0{iDfb z@_mK*+X;c;LnVDtAD3DSzVpzPgt|K0aDQf#x~vzZ-6e?Ls&+hcH^@?%J80%#*dt>E zEXE^BS)d?7YAwp0q)tL6jqUKCWF*Wh9y$<7ltCpvCH*$dw$hEpct`c+eHh?Z@Bz`L zRrX$TPa8XgdYVvy^+jy6PFdd%X-SpDfuEWg6WO=qy1$gW-X8YT870mDW;(85(IsMF zP3;2K@)97^X_2f^L9YjgKx=c4MBBiFfNUoMJ{%TS!2VWikZ2Qg?JXWw9tr7^x@2Q5 zZj+F4_k=NRM+_wx1|JM3LrRzmNUJ3vRtJqVU*LhxM>YBw-d#bQLfXS`e_Y1oP+tJ* zu;0yHf!(y}W5R2i%sCnM!6DqaLT#bbSaYh&{72M6^Ksz2#aov+)G++cYvZp~ztu2E zJ(3DN!ykgAXuv}>Jagv1SAx@Qi4(mEtf%soHxUYIKnAck-)mZ0VW_7RJVDhBq9XT< zPP@%G2>9<_Yqd?yB>vs^{IUk?WUM^8XEo#USDSj^xTA>*f#MlPZNyqHx0*^a@t2_6 z$N1w}SjGO7UgJHva73E@2k+farzc8?4UD7~D3RR{G@1~2OGHp-j%&B|fM z({CB~zLg6lgJcJ7U95G+2Ke|)>&OJ!br~+300IrkYOo^Dw_DP@fHE$L%)bv1z~N?30B#-Vj>-JFl1v(?38W^CYX5QlREYDDwR0F zRbYE^P?v3i54b>z(`?%VzXh_&-UwUB6dz(UYaUZ>__c&H1rS8~?Kg?jOzM3!Bazo9 zqJjFOiZ||o{Z_&O-|UYv)aV<}o`mkqEK^VDjdI7veQ3xdH>wl0tZGBJta^=f`${pz zlgLa}m*tPwD!P%9q~L(#I^*byqy5Y`r_M$El!DrPD|m^Bcun;X>%hc zAWuv#?THW*U_+DGV7uNDy|rZcAQZKz7BDV3YZo2Gn_WSQ*3vC8b7)L5Fn>*s$P81u zXu~S*I+L1=T7rylNX)4ly!(HBKx_iKm;fg6{_RNUbhC8BJsV^^HHBXGfhBOJ3eDdbRk9kLM$3L(>LK{GFO9K@^b1`+HhNI&sIr!^?4mBuXx ztd{jUwtCoqDA7>w-maQ-5%5U)&SEf*-vM@9xT=qf&R?TM z7ME(uh;%DsBIu%sX&pzow0fegY2p^&$UFC~{nH;N+5uNxOnL$6p6oXK*FXr*2y8~L zFpCR7qgRPGj71?x(#CrZcvta4HE2pX%4Fv`c6$7C-YH>O9) znahjs7yu3;V^c|2RB`_a22et1@DGwrj`%zRmDUWpLmMd|nSqoRo5Q2YnB1s#c@yjq z#jpoOkoiWn&m_Y#6Q+dzA$Le9H_Xh}V|%0CN4)zwhgggnGSd73LcB}OIuK~H*}jzM zO*b&H5dp`+l^g}A7BvD6c+>#FLFmR#N*rZA3Id1KV@Z~5L`^_=i^5kEdo&CurTPNm z9{L`p9C0F&JwwF(&H{MKK^zZ^2?)*TSgA1<$%yRnP;dhpqmNw?&XUjp?JY;7dS`^Q z@fVUYi$h_qN0Fkb-tJ@qr5JDVqIBxm{y}EbEh8#${?H0bfo*C*MoQ4Mxqu7E)PyBZ zhMZ${IetVCRxZlqFBC44K{tQ9Vn+Fp;$XZ-K^LSjMwsausVFDHQ%L|zqcbfdF4*ZI zb&<|z`F(Hvwe}qfqR`TFH~~?BfLT0L2a*fO{vRfD3teNl4$`ZfSc?ZGlOYgqz!xBT zJJ8@jfUM6}XQU0Cooj{EX=+J=UpZM`Kzxgh9!X3 zcW+Kl{{oNKMQ0<85CT{gy?@*I96;@?19Y$;6W%U-2%6bdF1tpDrcS&Js5+K;v7^H) zgjstV2Vl0``I28O2|YkZ4_8%Op?r{5CREIepcq_`G{&#L?c6Be0oMn_gu&I2aRxc2 z7`6%BMBr$taJ+Xj+tX~(De7H)zB6O0K)>3Dr?EM_wl2<{PGg_8oR2TxBrNb4+!HI@ zaff9^!m70l6Fp`wHA+f>9v|^XLZod`vkS9$jESR|VZ0_hVMp>CHE{cd8l_=8Ljqqs z40j^}fZ0(V9=pEF$rcqbI$X#E?QY#e!-6MS$XTqHHjrUxZV0_r#{j30oo=KcX1*Q9 zpkxQ~!cAatcpAA?o)F|fa10Q<5ri`+JoZ3c<2j(Nt$G|7yuX`#qeD_Mix`=1m~*D400Ny1~* zg3ph57Qs)dyguJ?WW&X43euvnSy89#o*-~?&kt@KK~?MA!T?9Yx^qvM7#H=dEEVs# zgi}c(EUY*jqd}NeE%`z-8S+}g7I1Csju*D5>IA6a5>v@8i$?JSB4&8yvytATe$C6d z&5cb22-rCmqESUq^9o|yjdTKWBQsmx*h0WWvS;BMMfstVxGh$r+@6<~ai5J1{lAU* zTb&!}HR|KEUu?0NN?}?>6mY@E;w?YX@j}8qBn@x`C%;O40X8lR>!y-%Wgqy7N=;}r!DjDdwoW;Fxd-iyp0Bc@iDxqsHFw!H78;EI{+63-b_{Noim?`MmYNQj$ z*V);!#^P^%i)*wZ5Ho|=?8ZKVi;9UQZzKrXv2u-D1!6`Bi`6JMz)SP8pEuHLqM(-E IF65fr2?m0OxBvhE literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst new file mode 100644 index 0000000000000000000000000000000000000000..324da2d61b739d9b0f43bfe288dabb59d2202d4a GIT binary patch literal 14860 zcmV+nI`hRSwJ-euSiA)RS~?z0BM?(k(gFNG#vjiBa2T6ph~xbC#(y5XFbuLQlX*3pT|K7)X!+1`NJ?HGbu(yUS3ILLho!Yc(2g za)!R-#mFKE8c0w91rk)ifVH{#z-HiJ!9fJAd8HBr9L$0d9JmA(FhD*K2N7sM0|^*V zpn>-fyib4t1$01y3YGyNsNi71!E7)@sSh5*j2MiH8lLIUesU|wPAd(CxRj~jpiNaK z3$);1Lu%wPoowipAWyXzc*+*J!q=%Byp6)HF>&Qv`;UhPYXgTuVKVy=yS-Y@XR}2< zHQ34_J$02A+h~83*5)k+AdPox_YT!oEqhDs@WAdtd_KNNS&$04dxjX1B&eK&T+&Mja>JLQ>2G#>xfm@(~1Rgk8a1b>W z)&Lbe1O5x}43-ZT9DGke!2|~j4(`K6Z-Q2hxA5_4$^^AvLP}V!vhhq0x@Hy&OI8(# zwd?~D8@9m`U@K_wfj?MqAjP3}PXig)1`Iv}5;QniaA3T?=+6KG5%nBp5@bMv1TfeN z94t8aGanVs00$;GSa1M>1{mN#OAvwtez4#msx)duA||S8X0kFWA|q!eA|wM8P=Eme zFsJ|p7&usP@SYv!VS|ys;z^KJCuv}~XO3BJFAg9QgD z?DY{I8gIXuSukW1;bgEc{Y}k_`mo5hp2_`jPR~4LFaZS;H0Wh8!B)`VV8KC2%Vo&$ zNn2mFDVT-Z>8+b4XrVXELi&Ep&AxP_plY1QKMRNXw%< zOvy$dDcme&u^J&?DepeUGq&Vibi;nn_v&_G@EGU`AV6yY1_uicP_xEqazmwL2;Q68 z9F)aB2{q(lgk8f$pG6H$DSHTc5*fj9ubfdv?>1r9_2fP)J(1sLFi1vgXxIB*FlFo6VXfj(Fu063U{ z0tpyY@Etf1L7_kNXvhR}k@>2O-S8ggg0A;5lx~Nh-jxyeAZ@4WJ;~RVUDCG%wwoSa z;T`^JNO_H$N6|Ms$Du&Kt<<=&Ni!-}RNu~c6&;_QiK0vLUTe;Kdtnhysd%pa9pPP4 z71|0b@A{mM`eR!hf`77=GQy#4RnP~G$6khnvFI)JlE``x?DDM;9wHFYbVLf(h1hNGSczl~^-UOOFuZ@N*dn0}BuY7RXxl3Bq#$P&-K#a$8J9^Mx&`to`D@K;qb^5ZL>yR;ik{ z(nBT*Ww4LrSt{rPNe6Ci59k)eAthnMY+5ldnR5tkJBBcmO}9iVI_a=4Sgs>-eL?TF zL=->mKV(e??>?ShW}J!2Fw^(-Tn#ZVw$!uYaGTpE{cxWhl3_ovGTa1xi%p9~)I@UZ zs5G2V>Nf5?uju(fI(XF^!aGr|&N32RI6QNHRWOEfEyT<&Je&w}-zh9iGx3tJGW8SM zv@M+Y!+)V*d55a-0fQGCJ~ExoI){vhmq{zH$%W%&P7+&Z{^M{&NR2IhKJp@g=07Z_ z6fo-V%>D3tN}Ff|vRv7!xD&f_mi1w~lDC{lt}v-)-5Ux)(hSSkOIbSn zTOWI@M$o~dDGCl{>lH{_yyiS?1q-iv=4Y4M+A;vht<4x-L*kzP-^m!il+j?`W6DND`JH z_w`Nsj!t-9cg6{NQKHSO=40Vj!d<#b3#-Z;xgUMkX}I9L97xXdth`|#e&FK0LeWC^h}6s@u7I-zKm{}4tpy83K2lVT#~LQB3QdSJo1{f2SlF!q@jvGlux#8!Yf+V5ELZmBf??*MsUT-`Y;k6`ws2cCO zUU1cqkdf{T5gn{XAEre@R%T(W!f5tudse~AeHnA8QyhIlin+4X!lj2lPx!~Xk^1+h zan>h;ZcS;obs^PsFsmc(Ks--LxGW)J!pNujNjS;wiDjFq=v3L{utDEh65VwJuRiZN zT{xBd5@RTQT`$%;-h*asxhyz>@oI@CV!U0`Mr*NDHsWiBij-!J-snp+1q)5}%^8wi z+joM>r8dPDrEmKmri4W3quYu@AuU0vdIPOZ8*`4}xvhDil#4pA39VUj7hHBI)OG=7 z!`XJ2ee@;GJpMSjo^i}#qRAM~{Tf?H)3#PlO`hQ4V)QXsV zhhx;SE(y8)A3E3qQ$=HkB~4Pwl#+H=YY*+-MwLc<4-OK(Fa_Bs=?KBjkKK{XE$9}? zWp0om&&64oi16-B+vQ7?BN>vGqE#ib!=l4>By^r(kl^Jg#2>aBH&E(!dHrorZfJfA z@r7r2is+82B&RID8iFUHh@a~&?3Wr8$S(sHe}tnam%ppL_>HiwWz`4mo0ADPTH1o* zPC+Sy@MO>kjx4!*!-TpoVQ_fZIn6&SsX{|98Kp!BzNGrJT^{|^;C^><>}8uop;Ag# z>F>2F-9h{1b9QP|uTC0HAGc1b+=0@!D^#|4+;l+%4pi;9qleX@1@xM z5Xv04`u|eCmn_$5lri2+I=)b*h565F%V4!g*-a73B*FMbO>2m3?mw+>9bBfZ`Yf#Q z1nGYnX>N@P$euo=u03zXWsyo)DOUb}6FkKC1gta51XE(uFN z9zl4;+Z#q3*%5DCOghmq%#m2$SgI6+o#wbc9CFAw!75U!ci zMOUkX&gF#6tNLnh9+gMX#fg#I!j@dHo1+V#dO!@%k z-+zSkWpTZ1Ee#HZ^6IdM4Y}jRwGO6O_)05sMqx?2OcI(n!^CMT5qGI5GQteW^M24w zcrX4|x}>l|NU=QJeA4D1Emc9wEl=B4db~^WvUYIOLNT@2hph6&?_GK*Qetc7l+dXU z4nbQSPH_Xvn|JHggvMlKy+S+B4PCB5zbr=>M~?NKDNYy|XhkDo;XPnbrf@hGxmJNE z!_BLSXGP^mVj|v=CEiza_QAd@yf?2Vg}Al)#-0d)dE|RmG(zFMJqn$;l}LtO4Oh!_ zv}C4cHSw%yhNC=aBd&LGs5;!jn=(gBW@;w9H?Jn1;_}^OLUDnugBU~Qy(``uV>g4%F3qgZ8OkG-;P#hKiGv{ z|Bmzd5FgSfvOm+oQ*k#1iyKIM?zoNTQ5}1(p!vtr&@rj1ln;DFp?9kY+MnC^s1Bk+QF(1;ol^Yfh1-N0uiH7pV^aEI`L zIFJAU4j8lq8la%T9*Dq$i%+02q(G5TySL#+&WeXAz<>bKtb)bBwgUtp82AFX;DKP^ zU;zd&z<~(>aKM1USKuCi2E7$Dn1F)r58*2i5fKrgfHqJ04oJ{oF~ETgaG)7*pusj6 z!2wcAhU@u2gNf#lHdT+pAslhSv$m>i-t}nuZVy9f<@Th(qZa;rrn`@;DVsH8#h<#U z+R%~>zWgo5qPNd^$>61-YWeF!cUu7m8teoWkbr^>SD!%$3pl9b00jfMKvRGL0Z1@` z1R0pXx(7?a9iObcX4XXdPF{Sq!$01cfR!9A>7_xjIJn^VgyYzqLz2Jra=p*+<*4Ce zH}|-F)wVY8`4c`k(?&Ls&eVC5@5|1H8N%_n%exYf$0`Zl`rVsv8D@XJYmzOD2V4$v zb!oPLT1&Z5grySngOcwO*I^0qVtTMg8eY5ORLEy1-3}q=7U3d1PH5Lqzgyb|mks+s zia5)AqoY(T)^x!_uPR@NKgpoV)*ja?uK3e&H)7><7ziVn@q41Hj{$49F(bB>shu1kejq56Q zm|08H#@)551ebJY9m<|yO@S-4T^VD+qtB`Ce%=v7U?Lon-u36XlgyAfS6rFmD_4j0 z82(-vAx!N(@r2rR!?KxbqA3Pf)=IUF;AgdQ{5->$LK5{DHaY}+Eb1v{ru|rP8{uWN0*{#OfwiEcn*bHRHNJ;}TJ^PLta8&Sku6s}heYoT1py zau5o;)hB_MFM`H8(BGGVZr!j2XM#@PG3)3ij4RcALk#`#to$b?PCmj6$gU_M zZi3uXT^uI{$0WI~a@9+PM5tqEI}9Y1L4*)O2q8p7gy?(|7l0rb5DElBgqa*m$_Ep` z0L9`!h$IdOgTYW35C#InKp+?l1cHG;Fc1g?g970|5C&p|DnE;KX<42+0VcV`RC1kc zBfW2ch^@A1j1VAT2)1qvevzPZdo`kcB6hZY<3ZrDzgeKs9GFT;HfaP7oIwq*4x`+` zW82r=cqqtqdsw=S^xg!#WW=hPN+Z<5>?Q=Pu=A%|s;mHWmWo=tX%qoK&<47bHkBSY z;XS~uOpFNg9_W|?Yvh1#|ZIlV<6H+#73ii<1Ocm4X=Sl zddY$kCXz)fO#b>)6$ST<0F;T!AFn^UfT$7*Tw9tn0@SJ*`v9KWI$C2&hK0)qz>z%G zz5pbSVe1cl5&)6nc)7S?TYq#}9MU+9b$tE#}wACg;H+u7}T05b)$5^$f_p=jVx|((&9zi z!1T0~u>x)F_;VbmEjRyTowjsP^!sE|q3)tV1tuP|~gP`7WjKTx!Ze2BF zAUCLnO_C35GR6fa55caC9)dU+z|xG*0y`kFEu%-kLPFV^(dpaLYRijpUNyE+T{}Xp3j@Ea60Os45&>XhRLl(jrL|LV$>bk`=YMfL;9aq-!YKL8 z)M8tXah~(#t{g&<0>ko*nF3{Oz|v%#_lDOc&?_fswj<+{02xcLlyOnean9Q(Xh=s;%q zEHeD0s?ig~WWQgN7CubJmmDT+FTWE*b9^t8bepH3L6y%4*mxk9C4h-2yq|4FaH$ z9dCiQ;AJ}wZs9ZB$iowb2??>45A!QoO#QPP0yqhAC{Lbv#KaOuA(7X*#R=Aqkl=)Ob@WS&iKDe=ogkqA(O#o^AC>BY1a||F8 zI4*~8_XomKyv5k;iH14QC|?d=H%P6}jX{QxUf}Ww19+S}gs`|1&xg%tD3pnq-*wOE zdwHG-c=8*~W`GX_mVl1ruA>NpqFz!zMhb}fpaZ&k9CVx%(KII;A>kqcd>fN*Z3b{m z0dJulPUb$IZAK29CsI2krQA11w#By_C}jMgf(;DrE(Ad9ON|$F%h{2W%#OyQz;X!k z$Yx3P*Prfg8c>fK?d|M;PbkXcL3Yh{>BC6}bxz8wgVoapr5uATJ1K7msu|j-UkB{$ zNqMBVKXiqSrflm^%6ozcCq#ejfSo-lj|8`4SB@_O+j>%-7*rKHA1#yhJt+?W{^*Bb zRg-J#NqKCKS$_nflIzDwdDUJw!Y5sFw(H4~5)-Vb^t6=s4G~sz?Tc)uKyfZ0yT(j9Oji%BZ`0;@qi zkCSp~ZtBB*Z(ttO8838}0sPqaP4PPffF_(F@muU{W)frs9+^r48L$rHA`W1nrihrM z-c~bKHllp^-+>M&(k6z&bj6=FpeXwrxJLqpCF zA#IkZIeWuV89M`v&LJc!)@B~G;NL?C=s^pjiQ{I?k##fPHapgaM9Ae)E;!y0n?D5M zrqU@$dDe{u=75HXBZDmXkBTD-z|%ih9@i3Lv-cE>GuiwbL7}feyD+`(_-Y zQ-Ca^T9J>biz`?q00OsoOMQm`aiCH$O?eTx{lU`p;?wcs@%f}Q#}CflALJarxFo(v ztnm&nwkSb-E4$x~2i@#2?d<`kU=Vb(5eqW`!ZciEq$L?}%cwI%pq%+E7hq!^SH&K(7|A#luUY|e29GMBh~7X*M}F%@+2 zm3uL}`Yc=V;zoTjrF+q+dvUmVF}?alHSk4A?!%s%9+u1%^Gh2@puKEsPAln_Oma>P zz03^=uOcun+8n|PGp{mSO$xkM)mEC0>isF2z$A8|$;=>L`hh6M8MiKT?)Uh1=&yx# zmo@WyvHE&3UDxZyy646H^`gLe805@*NaK3N+~lq8AONUaIL^mFF~cZtI;bHSvP#Xk zMAub_jN**DKr0fc?E|XR4o-`}A0QZBkAc4ic7G9n|1$La#dN+U>G4uYq)gviKkci{7R?oa?s^BjTV2!;7z7Yl5ay#k!Aza13)`8y5}; ze}!}>?tMVj>BWTohwFtHc_oKRq+ zJQ{j=ZEHl+RCPdU)&M|k0WuDN-KwAx955m`smZn<^RJ>dE)R%j$QqS`Ejjc+RvKfIq>{mzROk`_0B_krl)%MK zpZkHf%28Iu;+yj~KbaYC1-H!El|PorF97EaK5|$ba-eElrm&-57JCjb!HKDL#!%UQ zSkXX&Ru|>-DURdWKbX{j^+>R=p~%}$^uBSwiCDuEx{*-;fD8icvNk2I+|qTH03D)m zjK+|soqonq&lUznl4S>Nz#W*4-iSSbvH<|0%ZnBeCe%RDA~Tw|-N1NObMqJwlOYJ$ zQ>0GIz)_GukfshX9pfE0xXEJ0=10i!<``Q%mZvC}mKNKhjARG&W zzo4c*ZfnG@t6!hhhW%b1@q8EnkYkKQ8xTptwAiX(!N~WZ znhDsh8bVf}L2!ceIHlxL%xLpu0xasUn9>t(B3G-Qp7mxY0MT@P=UaD^{O}lw$JAD_ zKKh%801kIhKI@L{GNe*;fHA3^U4o1zpvmD)IEFqd5!fT5hCKS~!;7VF0)UuJ<9{}-vD?fT_7I}LV@Z!GBt!8-LuVQfgvxCgGqrZX6#=S+BHR&|lsO?hx) z*h7@n&7dP^a*q_D#9zk6se`38!AgbN)6>jc(D>fzM_J>pyy*lcLIjrT0<&X9X{ANGm_c@9(_#Ft$Pb@`SZWWyiTlKi9(h0a<7&-h5boBB*{cdH`b;W4pJKCtH;pz@ zNmFz@)6xPR?_F1>vTWF*pyAtPCwHV2=Niq_U!T@q1FYbZ@b z8n@jRAD-wm#7M^ncWfcQ9h-`$(3!&}RFd%@hzOzxbl(0PFdox*CuKqfnXZ(~|J6r) zO!;dQfAju8P|JnxZ00dEs-Vf?CFl?L?6_$&Pm){MHf@Zq5mNVIOe*_m zE0+xi{A=s!bf?qQ40YcqLTb$Y>)TP zJ^XwiN|+;TUeAe!#=ep+6V*?&PK=%8h;V_0?Jn#lStn1l_p3S9*Fvc5Q>)EHJd=FVwkv+l&_?)#a6~7*$037* zGm=5G-A50{WD+dfd3ipB)}V z*(ub!u9+#s)lG8tCm4uWcsg?7y?NCH<4#`R z+rseFd4qH7eS2X%U3@F&kX3AW9Ge75W-HQJoA@7&989By+|z?GH^$Rf{{NyhdkuD_1W1G zt*_PxYwXUIt}9gsozs!w~VVdYOK=a%;=qrLBXZd*l$k*~2N0 zm1@riLPqj!PJ`J!hYvPZQr`K-xol1efzr%h>B}{gJT;UL?cV1ddum$xdz#cX7ISas zCi}MW+i*F%Ls~6aS4zp6!jMrY{OTdzX+5+4HMw}WVXA3xo`0gFU|wh_d>cAha{jc) ziC;C%@gg038pF1j2B~5;;~g6tuegBrMDsC`6|OnincRAkx2pCR15TEYh;8SDvY?#_ zbh^RaLrZR~=t|aqAC727MO4p1ZNSeA>o{jYRDJYHv8vuz#A{E%PNO5S!kvbh|8>od zceWW6n)GC+P|@<-f4}q>mKB&6Wkb)fOnn|2f99ur6h8^?%>Hb@5Rg~#&E%V-~eBJ#%?6dcR%Higc#TnECk5H8Y zTW8&~dMQa~?eGFmob(F80K#kk3%RQ>EbdhAvU??o1Z z)qOMGZNWB}-Ru;h2!K7I7* z1XEu}U~e4jHF-)gG@Jh)nCB`vc|;R7wTD&AM-d)ztETrI3dC@!NHh+ zw-Xz&gd=zsPwcFZVLlMpo|I)B7ee~Jl@G;f%U{q?^fTv}eS1M&W`T7*a46@G!e)4c zu))G>HGF7f*S19rSEz@hiq|~j7#b1S`W7TikK6iJw@|e$>*I=|x*c0u@GFXK4H2>> zng%$#tq`Wmn)=t1tGS)EFmKjt+@x2(Qq>du9 zXMZNuqi*Ht7Z%?#h49ll{p0{kd=DV(8U6DUS&=I+zfH zWI-rp3B!Lj-fY{Vh8wH2Aw0hj^bRB2&fvo`Yg6qy!(q;5hT$cumO?zHA`UGS{gH35 zLuLu#$*weZD`;U^b``2zx$nDejW5$^|76JCcY?LcQi#!zGQmxv?mA2dS^w)%X`#jH z=qV5NZeuXjJ_(8HVuB~grimQhnwXd0!{XYg*;e6-QFZxvz*Cb5^5{q`rwKbqRYVP+ z`f86Uv>`fF@?qq9Lf;;Tv5}Qd!mAFn&&D5!mg-Ox>N!FWi?m4umkT}-co96yVTpo! zo+$F4e@ypO^CxkeL7C*2P>AzvD-TD=_>cmhT-v*M=tDkFrMeUHZXcznpc$d2Vl{a< z$i=i1o@u?8t!vH$_h+dS{~hv{s&Z_2%HV#l!&1!!GViL>s*~`c(#1XPMJ1j z8tN$&YV!LV)tQngISrxSkf~17UId>~R2`{gDrbMBXv`O#EAf8QCGv46MolD@QdXw7 zT*Sc(f$}CO}F`D z$@0OwG~j5N7TW~Un1y6c@%r}4@Ikg85&f7?BVJmLQ+8MudtVrXXO!}DW-Bj*^mI6L z8p;^Tq1GDn5pj>tr==3d$FgV;P35p38RE_?Fp9ougAKnN@@hnN+^C&OW~lQ^+@5lO zB0fEA#3}A$VyEqypbet3?IWH+rj`>r>4Ncw?zM2W%uzY;d#GrWrCWX_UJgBVvo9Ht zmlT7LDM>M1=@-kq0z+=;hTy^?8vbJ|F7h+CLO~lPgUKjqd#RbCh0F)duVbYfyUtz+ z8fZ2%428p1%Lu4Ehpnr_>a`0_nn8b)1JoJyk1tQ5aM_|Va}eQZV_6Q zz1(zro(7%}m^NK}Js9TS^_ThR-=)?3M-WkQVpMP|dXT$%_dXa?%qA2Kjs=OSOC;+s z;k3n+up(U?!WCZi-7;faAeGeSm7 zJ)M5;%bYsh99>QXo1pD%p~hd-OQxAGFFj;@*g?+=zY(e|giyrU*>ZKMVT>O^C!ii? zMqlr0aR1xkEf4RdKd-$(-Hs8(wsNL?JxI`P8rcx_QdWm$xgF1_9VfW_j?~ie0$YbL zHE+|*t(jzI-t|F3W|Y2Yi@Dke9yL;OhC<`QYm8|$B8o1&><-J}CeI~5+`6=w zg)qU+Gs*ER_^O(*$_LY(Pw7!vL{+oN8dA4AT4gvc*;P?mvs6`!-i3#dnJ`?x z&FN;=6)9zKvC3F}hqA2>^+VwVi+q&PKE;WY@cdBcsXnmrZQ+I4*L?k<+3-c&TOISqSO>yS=M@`-YKV3qs*Y=@vhme|idq=)Tvs|&A3F+o$I>ETi5 z)L=oWrXv`^2u3i1gS6NEm7wI7`E2$uwf+9r7ua1gp!)~ue$dP-#0&k!ltDr+O8uK3 z@-x;j1Ye^t`+*UWI!D2~$bmwHJ%46@IYMm{YOdtLSV=3sfWa&kFGO!PBjE+gLkf}M zyxG;G;50TNH4%DyosqUjr5VPJA@$#zPO+;c zg{pCbBZeMcw-d#~g){q@kRee+f~$AbO;Q9O6QhoiWarAqU;!nZgsue(%2UGC5lZqz zH^aj-$ds3u%_8?eszMo2{6XqseWaEg|lP+RM$gWmK(>eqN28EC_a zecI!fyB9tqQ?MsLsl^ZU=_gz2f#cp8RXNWZE18EbdN@?|IUW)kql2@3&A+s>B%VVE z*`nDl6+CC{4f|EYk@fX>m0DX8n=nqLDzMx#Yp>K zm>q@-CgwR73XNxDxMpsC`R_6vTZQG`LATLgIQGEFuFj+cfY`Qzf66(ox<>^c;WUh!Ya1VmHjv3o2f?l!mT z_-e0*p-Q{oeFEr}vrt0O^l{Fl;DEDZU7q)%^6_ESkk!n%x)o4vSpa!%pMy1UNHC6dX9;NY{n?1eR< zt7n%&E)xp7vTK7!s4{d48Doecgb+hSL`0-&526YX1R=mcj08bvnNklDKwwc0V<3p4 zAdEo}0U?AC0Wro9LIi{mqYxpAkx~yljCf@-+lg{XfU}IVh^$`$4nmTG_r{;MMNZtH z<+5=6dLb%M#yPyPRti`f(STClE)?kWu8WDox_xLXKxM%5vjtUjVL>^J0bT5 zHZ7(krfB%1z5w!kCQuoW-g(|8xK8tF(GbT4*+3xP1q;LmM@~JEBX9@y)0V783A`iT zG&O7PI-duP!5dG3*T}ozFFOqgQo~^#sO4R5;>^IYVHo9>QU?hHSP*O}M!>Ca45j@Z zA`FL+!cz4T%)~KHp<{SJYT4BzGZRougR_&!fXl9zMR(Qr-a4%Pxuvx`Z}KsbLcy`D za55e-S?Ziwi)_UUy*WHMozfL*ZZu561MYN?N%ruD5e|?ll*$g>hlpldwc0vbFc8%U z&U{2+Eyjs8M%L+3P^X=v`y~CBp`?_NE2tj=i8p77+y^>oo6#YF;=STX5MfAsws@3P zYiu1cHEIFzeQ$J3l>urkP_q)X5vwvyXK^5-%;Q5H@7^bHLEUouK~S4&6=H%MpqU4lNpz{`w9*&cpg40cTxS zuU0tW$8+c4hKw^qw;Oc+_0X{5MS!m9$4y0a@H+#^b=d#j7CkOr)uwox7WWCX6D~7l zKsiro^SLF$PX&YB_Y&u%&+Wsae?{eGXiN0$Zukkr=USAcf~HcK$wuR0VBee&gX9(P zCtg!4M;Hg6TEv`}%D)8XCSx=o2R4=hXq955$I2LnB%6=C;1LL@TlvfOI})lDU2GZR zAmF{KGH5q3OS_FK1YMQ#-4-Tla<4K%fVN?WLk+L$#P}z68e_Sejs+Sv0T3J*E5)l( zoXl`FZP3>&okW8LNR)X-AS*$W0N_vH3Clt@4MSK?k~!xbOAits2e0NP#t=G0kS(CS zi|8Xxk6IHH^LUN)`pXX^ z`ioyv{&@%*5<70s^(b(rYnBa^)c-89lK#>GEwjYp0)-V`Hp%rl{>*5v1R#`hg&8zb z1Llw8d#c{n@CVR7|IfSerq{P5h}U7&LPmuTPz^Ketu`J5n(!s2drvVBJ2n1}w~>R$ zJp7*<1c~A75e^8iuh8jO_PWGHYEHC!1oSa-? zB^qFaMgz46gC?U=A*gpWghOD7^qLmyDzYFeT^#Xvh4CDS*B@qlOQdcGVt31Lt98BKR>tnxD5isiIX6`ssQZaH84w@H50-BZ8m7 zgT0WYz;OxX(?R{FwqtG}U?^C95QhXuNbLt$@`icBD^$P0L7h3H_XGeC- z*OC663jkKH&Z&E;v8lvh$CwjWgK31<)?PKLrn7DS@^#dT5+hhk)qi*z3As=qJbofqY$oY{ zqRg9S8Zi(aWKo;1u>t2U?jr-P7@&oZP8;Y?`Qqwl)~WrGeIf}D3P&d`o#+v#B{OnJ zRGZC%0KnXUTH#aD)+8AqR-r7hyO)iALoHZ&+-r^h*o9mm`Z&fPtV+JAw_v8SoKAcp zs$GOyTzf-Zj2Xpc``W1iA_`5`aUTOXr?Cfbhf#?QEM^J>G+#{)UpRi|@~YZ$fjsZX z%}+E9CR@DPc%8B}Qg12+isCWhB3FlZsN+8|A1ASagMpBNJ{nnIEQrZQT(Wv;h+`ze zUIcB~>4oEQ0oPHqbrhd9i-xk(p%JYKHml4N=4Cv*M2H-0f*=6TZx6GtHSayjz=<{` z+QHk&{Z7Yf_F)>F5FvwdZ!u24V_I30#8K319>zrqZqUH?jxneakDPkBrWqHh%D@QvIzUj`WlS$bB}F?FXJQ(#t5Qc~X}5Mtbe$)en5_ zP$@1L%D*olaC`lSV2UDW^N#T?`@KuROES~;R#VFBMkNl_F=T078kWwDo+A!UfC&6L!RLQh@AZkUiYd8WshG7#ZuEspODB;(hul5`wt>KoLfz zZ^n-%Ux7~Z`p>--gpE#~LL9^7TZP-BBJ;^ZsT@9L4ohscs8* zl+Xi${VgMo^Z@N!50vQD#}Py@m6*KB9YugltZa_-^a3KLU)X-&lfvrA@CD5KuKTD< yQ3T(?F+L?3UJBqP#b}jTZl2JlQfMGo)nXQcTvq{qAaDMHb{p~S-V=!MMrkyP>n^7N literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin b/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin new file mode 100644 index 0000000000000000000000000000000000000000..17ca87df93a3abb58f762f0780eaa9c4ed9c7bad GIT binary patch literal 17424 zcmcJ03w%`NnKzRJL;~bGXA)*00|ZFGkdOf35+Hzf{j}OigdErDI_Dv_Zms*(#ctPL zJ!dYtBj=o%$s_@kPq)_oN?X6GU24~swyW)aZg*XarCsf=tyb%P;%dFr+A8~h-uIlj zB?#>I`}irm=bZQQywCOjJnuW&QLVdIE8AGJA&2OT)=ht5ZIddn_)cW6kp_bs;sx}b{S!3x-4DjlyavtKCDFBLHlcZN&d=u6QrSajCa-)7^p;+S=H%*^ zUPZG7%}0*h{L@-0c^A#^-Z$rdG{21I56^hxX!7PC4<;@{vkT3i-}m6PXf~kv(&@La zsU^>&YX7^lZ##lkT(EpSdA_G=-5a&idQUaC$@2(#{x^B8AEHgPlFgL*s<+EnZ^6cq|)N5KGs+3YmrK)+fXZ;G5crg7L zt!x7YzS$R^74F|PD|Jx&r9T2Sh`bx_FZrK4|DZkZK8l$ga!NWj()^42!nS2v)cpIt z3td(VQps(+@S1DHHcX@UbvZ{QN4XYsXqV)Az1VNAqn5WvD)~N@Ki3y__iBpG%Du{W z`X0PG5zvnM>lF)syH5%>;4}BmI{OCl=W@8!`Wtt{(*;%fK`E%xJ&vH-8r{xXZfjI} zYd*o+r5h}*af8*7zgWbg(ldrOC!lB^qc#F1Y*Isl?zlo_wQ4w~=>hSqQ0WtDI26)? zR*03t^m>_}1>9p{Yr!OyzHMt26ns9Z-5*daYW;R!*zi)>MHnB|sr0)LhsO#TN^KOY zL*YvAr`F$So|yJvK#31h>wSG;D`{F0?>3Sa!(F z)4Z}_NMG|LZ7rDADhARyg0Q$wWmjYMvK`cVlje!@>H~4HdjA`jJ^5v*ucM?wEAy15 z{|x?U?Ry|>B@z}-QPB4ijEa><3&KvoPmgX@(d=5))PjCFBv;STVdujH!V58?n zr=QQhk`4WpEu(M+SAccz!-j7rDi zGr?i-EUI|Dr8H-sGYm!sD))WB|6}dfe&&x>7WMR^XCwd9q5a;kUCON+%y;GZddOhT zl@3vPBF^JC^iK;YJQ>6~joB`_qSrLnm-Rux=iQCxTj)hzVWD)Ahx8 zpL*?|UZ(|Pp59oGO&8s!X$d)QeHqRfAp-{-^v11ly@9ohoLklK6z45r``baeDiG!&P9<8BXF+8On*8fHI zhQ~030cf+05>t3 zWdno_?4jwbp1NP*u%!nSUp9*8BN!gLpXS{l&1oL|ADa`^J|!mMp>Wl?ku%A;`oXgj zT>beR!TFHj{Tbm3(b0mO2bgK~g}1n?cjqFw+*SD&xvTPB&aUSF!tI+k6O~h*(=QS} zJN@#noy+MLioX04ec?P$U;YKKvMlSKqQX1jRpazm=p`5)Rq}fkztYVt{=~fEtD(pc zU}9FG#JLxj7QeWmXb4CNYTZW6V@HkNc#ody_1GRW5;owx=6`{mm)RGN_OKUB#yv^X z_E?(7L-YR<@mGX%kEM7V=PSID^B%yc=(X&mTgtQnX2jH*_9Vr83D!6(>ZJvfs&+JO zre(+n6i_rU+D_S4#0=Ad2C?&mGDwR7dvsbb!eUzR7ph!_7F=N~vWcOLBotqo=BKb1 z-~dUvGo_g}?JTmO1r-oqGL*DLA4Xf2Qbh{}0q?*F{1*}*48%`butM|&kNBHml-QQx zwc=&9(pL-gw%~+XhL3qzrP{?RX4dmNa<4L@l|EYVIvh@K!H}Kqke*@<5nQmMuu)4v zj6*c(_Fy^pwHZ}BmMI;(^VT$!NPY23%z&XdCDlqa_EOt&SQ% zDHWFv#pBfQ$-Xf5jozccUtX%51=YsKI92Q)8o7fizB4|ey&OOu^QzyZ24qbWTK9-p zhj&Q}Tk&Ry7jrfPo>sh}QpItLD*nczh1cP`q}+hYu*Vf+fv?DfEeGaJtri){L*nd)NeE>`yfJsz+QgzgfD(|z*0dS3ZELNh*9}L9~ zWEnar7^>;Ln%)Bz2y*@ea_ph1c@|Zkwjg;ix5H>n*L$qPVC->Ayp9@*ZCVaTC&2lt zwJKGuuq~=;kgT_b0LIhfpccRYoU2-4Qq|7LL~DfpuTuT(JykIsA}n6F|Mo@wDbVu3M8Z%`3FbDTMWKkU2k{h!45 z7`~6-`_J(%k`~`NLKsG2CT5vZVHHC=7T8yD<_z-r>aVj7?t!)NSp0Ps9};zQQJ8Ns zZtKtp;ZGDhii|%tqYFtzy{Uv(*QpjM7}fr*8iB0SRI^07j&x)q9F0@$z3eDzGveL6fvpT z3I1jYCqrr0trRcxSzhR`jD+Y4%Yn_X4&kHS-hVv!h`q;(q&i#C@dxZru0!!~`7oSM1=p@BIkNIT!c6yX^Cc`#TppSE@J;N9Y55RxKMlUHzRWFW*08xx#qR~p7lsJ>GdwG;jUB&IP^ z`k=(1fV`-nOb1w^78eX)K5K7^l&ge>SRt)xZy|f0;SXjgTR*~5nu`42o^3~L zqrmQy3^@k9vg>wm&rt-oI#1)_2J1tw+9zy5AmxbOPGjySFSPk1V!ROI`_0T(Kai8o_P6j-5d zE5l&&-8DE&zL(P}@_jXxjcq2aT7c*xx(|aEwzuivCn-Os7+M^yLl*vN3!ISmWeOo%;?ID0$ds4ts`;K;b{@(S{?EpQ8(U-vu6 zfjP-+s$VSFU+*=kz9KR%qWNL5zp2S2)u9MwVc(fMGgRMhQ@s}g;-P8LB{X#yJ}3h| zkB4k%z3&w$u9*tih>$Ym%2LaL`E&5{?g>pl!3LLpa7kVYt!N?V}} zJJt-lRfO;Qe{>?ZEp;K!+xXfsA}?h7E`bt(X7NYHXXP!2k8rFUobx`;1l8O3n8IP? zgY+mH4i`UM6d3K*wK9~vB3dKTrbP@W}v! zdIsw!16)Q2wD7;^U`;k16INM8{s&;e{%g3FEjBvLV@!kmOu(X(X4o=AwCL~IU?$DU zJa`R*nIL})48|X0n;s$mp%nRV9lR?;{;y2lHF4*WJB8}pS#0CLqeHH;D%uGIaH(iT z=9`WTlYbE+uN?w~`D;9rxifO)@R3l_#A#*>Xo3FNhG4X9sN#s;V;4^^Q=r%1_MS)>PwSiAeN40?% z%U=LmlNNnO0@}bnxJ;vm^Qgexsz(cQ%9)qpw!7&nqI+RDTzpSaID|A1jLd92T%2NE zSUge`4;OESS6J!0z<9X+^XHC-i$Chb!vM~xisNCsuP`1i{xe~Dh==Wk@i2fq4jjh} zT$gw>5Y=X*ih(?^;8ANR)#lAB!CUcfl^1L)?D75sD$(B!uE^z%e)OG}oLtU|Iv85i z?X4&(L1vVrnif#<4SLC57>v*cM(HLLzz_uux{8hLr3@$d^<&o(IGlI=qi3 zTxu22`yMLo`GhvCW9^4XpJbv zgBC@*R5(CM#tnvtmb~Pm0;D*znb=1IN{NM%jS{hDSdJOqf5p|myFGV^8!@V>;Wpjv&MUy|2J*L)Nb}O zcs?1>y8WDSq(+(uy{fmX<|n z{r6!iXQJ343Mk7Tms)%hc82(1=TLW0qVDC7po8!{w6vQx)Ied2lLEoVI7h^kR*^s! ztE7$Fzq!Bv#^s}%KK109H8ty=E_rMJ-(3EqImS=FxAtRy)pXk{&&)z$d1-27aAc4+ zpf13n)aboCk{&Q{J}M>z?aM=eE3p_Yeb}ar-4H9H>GIvGRx(se%h#($HiDQ&tv92U z;;jd4bq!lmy{ug8ju|Y?NI6O?jxC5T)m`E%KC5n4#+5b_sCh?4vV?b0)rT0eD;vKp%awR~&_)WhYbwtt4#*Y~@CXHa!6w;Ht5qptiE?nS`jwve>yk zi#cgo3VoOT9`%_Btl%V+!ivzc5O$poMS8&h-S8GU;o?8Yuc~e(`W}V0cYWx4X|d9WBAw9xMcbAkJ}1u_%TAKcpkt8mM2w7?tnr| zf2H=H@-2K9e#AN5#txR>7msRBI82m-Y5AwI@|-s}tjgWa5EEJY^iR?7CNu|Fr4UdU~0USi) z!KTJ9+Dmw-ap|Utzb=_;1tQ287*+(l@(~#(&B8 z`zxAw$cn0ILukb^H$XM|1St3;YySo={XmO_(DfKl0N)Q;@uJAE;P~?IG&K1juD!1QV_7aaIO-(E zqj$=*{K+^Ue(ZH$)gwE{A#+Hqw{qD`>#bC0TCe>A)@z?>J=`c-X&ZU_i#z*U`IuY} zr`wK8V26pA9)?THOU*?+M^vEBWks*$%h4h3h&7kt_yW8$hs;?NVZP>7-^CT64I zs;LW&hShaLqQ$82`JJ`QF9P?)JjYT z*lS~`W6Da`2qKA)>j7X(wlQj6B)8jK6Q}vdP#YMeRqynLd&S<95o($Q2G78$+em)+ z!jtF@JyWEj;S9m{G4PR=>qSb{{Bac~=l4`L5=Gh&A`_yOfMw8WOnRdgieYk|4`q8X#h{YR#nxe_31u$vMIT}ODPlSpsv+P^ zeEHY|xhNw=y}Ckl&Waj|RlbndRG&-8$g^e=^6Gb4$gAOx&no2A51&=Yt1mASGUwL$ zLSB8j5c295&sWG0<7yn3=ka|tT&<(PIliyPrOJHPwhQint!HQL>dVw3&gS6envdke z%{8|c!OgX^!2t+33pcY_Eju#6yO!UfgA~x3uU`P%oV==`^3E4OpP&GvJ{&6ZXPH@72el5lf7Jc1C5fSWB>7QxN-z0^{QzAb-V2sbbJ zZXVox;v8^uI*@F65I}Ov|IG)IEzjhDa$M_U z-9Za@r7T{jiH1*Y-Fg5yGkUR)cmti71>66^PiaLol-tf4x_p zhXL8)cB}{{IEsP9x!9CNg-C6EBH>0nk)h#!zrmN| z95MO&&tx{bP#Y@w$y6vki7Hm^I<7vcc_12w-0MD!B_IgN|87n&b-xWRt?L^Ykhesz z&I{lOZ~;V+*Ae+Jy4`MqX$c2pth)joCqffAjCZ1ajHQMvEm*33FRDJ-E5UjyOG7)Z zg<}$MKjzVsLj46fz`yzHu_n;EmrV!JgbkF~+e=_+A%+tYngAl?kTvMl9M15@%uobp z58;u`j+skgb(q4T+pDLXALrDz1IGq@cqrAj<14JT9g*p33rh0Tw&RQEP}}u2 zXHnbr3s`N%iqvuBtZKV{W4_w1_c#*k*pGDun-h>wHt?QPLLHmo!9?N3jf68L!`i%D zm2{3*_o7 z_iz7)Yk!c->2H`TZu8QHH3qzbxP&570drsFtXX2G@B_5rdNnMvixVhYp`&9%Ctx*l zg1vCj{Id$$u#IbLy5k0PcF=h?D(-Yk;(S^u=HWCI_XhpAERD$u2XcCTw!s)?3hMCF zhYi0FJSs?<+0ErbkC!h?ZJfuhfG^l!Flcx*pv^{g5cTVZR64Co3!z$JmIs$wDB8)J)_F7bGo+)H)nO)bQjywrkmABdQ@~6MiMEn zs~~We(xwQk`OFwscF`@Qj*jyd5uZ@Q8d3lmI$u@w0~U2Yii5q*=Ja@GVp67C;yhEg zDyb8fDA-l5L;;A;+vOfJ9H`);#S>(NjB zXn9`VO1pE2cD3WgIu$yATY=Qc7q~*1$uw=MNW|0e!)Xwl9;HnU<70;oi>|3bSA4i; zh(t9V85c~0($#ZlL1llE#TG;{F>C8%!W-|U&R&?-I`z%}k+UUKLN}gHbQ}=wg$t!g z5W~@-eXkS-%Vtt#j^gwIi@=94#9>0k`LtlNxD>nbJ9sJj;R+{o_c$J%OF(>;PW<5l z4}ga)Mv1}%%zx9XD$o_Gs$4I|;<+#qlY~Qtj!3yw%n&IrB8tnwxVKE3H;cswvNwY_ zzrzZ+`J-wmR-oLlvt(9TOxoNGs!%#WnKB!{P^yBT(48_kJcz4HgTm$!c=y6RF;PJr zRl^Oq^npOxHRz8^;vELj<|p9Zp>KtxJIV$(@+|wGU;w{_gA*~cr;L2rlQ!?bK$Lf+ z|6prIq7jsC_GlqcvbZ|PRf2-PADrG7CNBC~wB@swcE-&mU^kI+OPn{Dd1no)qc>g& zt-)>M2=HGNgT4q!=5CPYoic1Wu7ZRJL~4n8SD}Z5_6RZIU%6B91cv5$$1Q)D!8?N9 zeD7$&J#Gcaa=jyM-E2$kQ%vEmT>l5QvF-vJrtK8piVy-(aI|iT%ggNlwjV6=e^8Ne z+Bz~UhB}wlXnPF)&xZd?BjdhHx!&k2wZ?#dsM;UO(6)ui(6AL69H6duQ^RAT3x0f6c!$x=MW(Vp>fAunxvP^E1*gIl;pmn$#c;g%N@P&G}*BSZ^#&31bta8O>MI|moN;0#iv z!doRXF%NSFIk)qJI59u|IvN1N@Qf)w_Gzw*5XJpT(FMKXTPJ-JX2u*BB0zxJzNpAB zW1_En0V_h=*1~K;BecD32zN*L{<}q6QGtLf+Z#${;LX|Xia~HBnDH#WTo4pvSF<(i z#Ye;=yg1(%7S~E(qq!E$zrDzjZ~vC#$hi{3jyxNIW^m+uk)qI%!@`kchG|EMAebGw zyz05*2kgjqv=%#Z49Iun+kcyNsI$9dn)1jR8pN z)({N7-@J1!?7aJDDs}&Z%0%Z>gxSI=r(lW#j7{CA*}rr@D@Q=rq)UtCu4IczbVtWa zsrzBoosT^r)Dpj{&5LeXsKnN>m%7I+89fy0#x+5$UEf112RW=TW-k04O>XC)58=z1 zA%=Z=Po4g?_MCfa+P~z3^|2hL7kbGGg_KjfIZ#X8a2lxIyPJu-o2kWq@goKFi;I3c zaN|a7W*Q53tvDMC;m(U#xC_V{Oh*-*nVwzsf>_9=FWCx!P{hKW|D0vvP8^nKO)d+Y zrn4~XLfBbkS-A7DJm&1AvodEViceYQ?Bv^ewCkg^>spz+z3Nmk(-T7j2zL`xhcbu6 z?MzuOK)xWZvW+_~et=P}BYU4oyW+GP)5m*~@!o-gALwhEpK%IKM`M1}ulV;zdNM8* z4(gRQQvoxn*!MufpyzkA>&2PrIh2_acjN6?!cp)-f(8o-+U?B|G?-724T8A#fwQtG z;3+8MA3MK4VNM^CREXsXec4?fsAX1JCce+c>$f zeQM$lyog-`wYPrtQ0(|*ev4?g~}&Uyb<{q_qB PKljt8JcnvN@cI7&)sym1 literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin b/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin new file mode 100644 index 0000000000000000000000000000000000000000..4240bb68e5f5869b74c41e80124f67be88e58ada GIT binary patch literal 1106 zcmbtTO=uHA6rRbh8hWv*$wIBzAUUYFqUk}Kw)lgBKO~FnO6Rci*w|JSs^s9I;Oe~X z_T8P2ydk_ai6_I8as}Oan<-!*H$3upO9vL?qZRiDnhcG=#&GZrgb z$QLMnslyhV3(FV?fKCOVZM9g(+7f9y@iN?%XNyIkZ|jMxohk(FRiq+s&d5GbsnF?G zE2c!&0~*TESal)Ib>`p&K~-lI zEqn~C%;9-4tM%kSdlC1h7)mVJM>-;t!|AiVlSij7{+6=MbxfY&I<_4f`3p|Z#c&k` z_x)b=?1k~#=^Z`!T^qA6Yp;(Yp@14($iD35j`w#Vx)!Ni~_aI4c HCwqPZe7`vr literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin b/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin new file mode 100644 index 0000000000000000000000000000000000000000..3b3dc27059a4f3bc772ce9e62db4cf8a9a28cd74 GIT binary patch literal 1480 zcmbVMO=#3W6wYk2R#0%a?yg9ME=2?{Le;H@qOENY>Y*k%Y}AOIaf?+b_*3u~?PQXy z9uy~8wSwY5D5CYIQb7a}Jcx?ai&R)WNYQ!{RFtZ3Cfn9SEz&n6c{A_5@BL0N#m(k& znkGuZ!U`R=b*wcch;kKnIb2>q3&k7P>ykv-Ytceq&3P4AyTYajGJw5zd8+|zH?TjK zd};*NiJ&4|*w=%IuNdi15#`31sCD4@ZMmm~w(?>I>~qjsx3PaauSmv6Gm@^5j9F4V0$R!p~)FCF-8^bHiDX@_I0q0rKAfG1)ONE zKI7iMkZ3sfz^^ zlz12wl@hgusKZA|yj>U&)z~_xrMW1#f$nm>Bo>#-ILkb>I!)Bwl?#>&grK*5&7s{> zbXUQOiC1II#0y2_(8erveF-!W0kK@ySdl18f`eDlx#Oci_i?R@s)_oca+Y%(q4M2= zhp7AWHpTH8(d99Se|*ch$we6lIZnc7$$4p_HCpgU2q;~^Opl>ZcO3*?kGbGO+Zeel z`KV+wKLIEEEHCGo;vn=zPMR^zOU)zk1;6OBYr&~s;Yw3hCuczFGpzQ(@h>ZAc2>+L zApfHI@#}3`6UYNaVb|e`YfI$XE=GMLTmg{2+9+kZ zK(@59hqHPlX_ny7=!kN^%{VO`>=39Sw z3rIpt8-TpJHf;hCm;|!VI@t0DK;DSi)om82+k~~NXtquAEJ$L-IOSq27InwL)-PM7 zt6W%gl~lIlqS#ZAzi>g!HPBDRC4g*K0r{*!ae8Hna9FON0r@Y(^+Eo-XnLN>L&~WQ zO4@Ot?igmJG;z4OAHU07HcK{IA+k5rjvXR@F?Yv2!3 zuVR|WDa+9`<6_y!1>wgv3Sy3Uh!RFV&IngHF6~`|QxjLo zB-7FChAgOC4Nx<#W8)jBD!!;t_Z?0gO-Qt;jGh;Vr(k%>Wnm@}-;aX@3>GdA=18d& z2iIV5O(n=}8Tm$t#tIRg1Fq|g5Kw+Bnl#|iZdt4Y)P7MTHYqAnK%*NIW7k26>miXP zE=WutRUURia$C_X)A&X*3DzY{NZdbaFW^4xy6lVYEN)|BgF)S_iN-!dENae~{*_mu zx!7LSCcC)KZW^Y$o6YuQvrUlr-spzJ5yL_9CO$8krBca!k&3%|L2?bcT_jlIoDsZ0 z2k8Js-*AgykvCk|2yzf@BUNtx3)hy?`B($#UvC8C*;94ue`I zB$pVyy}giJ7ALTWihJZ`24!qB(SNp^fn=9qLvmBmbj-5oE8!QV^hcH6=I8{00gyZr#C)&t#Bvq8yL6!}GQcEL6S4nMOIgdE+$KA!J$HrYP_si& zZ6S4IU=t4Y^$3bRmzpg^B&1G2ZB8vnnNikJ6;jI#3aKSgm9Ws}APom7FJm=vm|%7| z5cJb{{VeBrN+Twqik@iBKyavK;nIK0u5eEAH9)B%R&GRHO-$ zgdVaSYFz|)ItFy|HNCMMM00mLuC)$5Fkead<-E34ls_x1bgtMxPniwCRmCFsgEtep`w5ZUovj!OX6~ zMBT`kR}$>0Z;7|Z)j}%%ifE`21$=NMG~UHaZ*;7EqO)t&W365*z%Bi#ag)cf(RBxt;7$dSg=(Qg- z@3q(3d#}CLzt-A^$fVvkR4%3#n?x+~rGST|)!C?^qE|~gE95Equ(Mn2)bg$*PkHUp ziNn!cisr@KAN5Cby4iG4aUPogy5Y<%X#O0{Z>6_Spt;15YVe|O2kG>TwJ)G~Et=*9tm&ZEV`%>V*(NWVpQ5>Q^5MB?UXC%a-J!n~q!s0BL^Sus zNE0^P`4>AChJ!T!Q@0aMhuOrepQ0IBB926JA)4V$8?QlAPvk}adXVUi{@rK}Me~u> zm)4_sXKdE(yOzEPv9my8O$QZDp*gzqIu*@}XpVVySUDJSV+_`v`v-v33et#=8qTBn zUs8apoeEp1&{0RyXvGk5l&tNWE8Ae8erVmK+iFa{(&6O@%jOoK$?8&mvuV z#K~t;;SYXHg7~l4q{>Y6(sPX=Yex4_HHNI!)LO=e_OV%mxhM#T=(MWIU`an}vNo`J zRli0r<9htEPNLQcacLQMFjm>y9>ivYLR63XbXD*XA{g6Y3u*C%GA6hP}WzB1=8M%vt+Xq;=I<6yN8}%@a#$&XL4bH?qN-sW>z~FSj43r@W?Qy<<`FA;!n`p8FX1MBEtL&Lk>^yD1um zuxW8+_ae{=v7}r>bv7^g!?}TH6^pihMPPXO?d~Vg=(^ zFj{+M{OgQ?TmJN$ydxcN-MxP6-U9<{t{r>97zCr(E906;r`O!|^$UX!O`O=a>tbHX zrU@^92*y{yn8q351TANOxcXH~FF%Ser3y7CNn;k-KkiDGplzD&QfV&k!qXo0c%Vf# z^dH91vUZHHA)+ z*B&zaz~QT3yOndkCdDPK@X!p=A86HLq8;dS!N=eFYTDHcrWtv`g?!`7*$sPSnPyb! z)V;zVh$d+-{_kF!IBe+A zoA0@4w`1F=%{zbh%+PQCwyUh^{o5b@g1CL8UUAEf=7wd}**;w`HmaooIHG!_#q3{k z`+6Gba^eR5EXla`#t4+~g+CxSK9t0$r#%ug(S*Ow2rMtsu18auab~eZGmCpM*%{Ws5SxIHanWMR$Gf%esuyM>4mB0wp+R*o$bc8jX-(63y z%}SGK7I68BUYm6vKW>0#-NEc1v5R>#Zkom4gg;C=AJd7Ti@HLyu8~rBc-CT5HCgkq z@cd-euy`2^asbF$1M-?AGO-AukU`uD;?88ETL^~@;xQ19^-!vp)bsEg(R~~yvL4|2 z&FV67PLBayPyJ-~muPnXUi6cFcc12vy}&$k_B;rim$YxnuEsQnY#n5H90$E5RLj2C zaJzay*t@JL)9hUu%|FR}6SklIXN9t;YI+od(403^u1DR&!j#HWF+v!wlO^|N^uG6GTvt-A;hZw}ruq9I zPnp7C#7R2Kjey{0E}@A^c+&qBBf{n0D~-h6+=^c)A@Bq8NK#!&s#U?M3arTRD1uHi z>XAyiPa)UIl@(fW0!QSR3S`ZV1SxZa$TCk9(UIn^58{W~I@shd`F-3oXx-($&ZGz- zcBP6C#GlcMpyAI{^dJw&@B;IoELHK9iZ4GqmXduqkQH3My% zGB-c+o5@ofH-FyPw7Hy#pam=h(1O=uOfSxPWuLyT<_Fpz7c4FqG-T=0=vU&Gmxdj= z$?>n-j*cH>jWf}LgW+(P7T?0Q{SI2rnFey0`D?*vR6MQG8dP&g#Tt;k*~Um@1ht6` zumU7#xHH>merGRljm+-L3b-#dkp3)r9&LCOUuZkEHL49g1d26>cYF_lfD+XXSh2k% zc^atgw@t!^PQ%9RfsSRSjxh;8Fag^^GRnx`sO=r|`l;5G9YQS-x{mAk>C(j)`%+0aUQqicl{z;wAAr+(sh!p0##I{q{j3kuVJj34Kvr%> zT>D9E?PSu{fX`$e`r+&Vu%VU|P-vyx`f!gBKfJg7hqd_7e$7>0vkcoG8=V597S zo5@;oX;e59(`WXQL=;9-ClSFOa$bU*mwJ=)UTQg^9&#>1&c$Bj6kX5dup*D8d9jqP z$Q4WJL&2Smc*zk-sEgwU7f~l(Nc0W{nY`?C{D52GiEWb}zj`ZN zq&TQ!jjFXMlH@})Pu7wtv`PMj|*-apnh;o z<>UVrJ+Q*TsRJ1G^|!W6etgdCpVEW-hddBEwc{6cohuxHVp==|U}Q(K4^5hNcHb4B zCB*C~qN4EA72ORakdc%4%v>|9IAzV(fZJQ9vb-f#&9+c+F4Gusp`8#t$}(29F=Zl< zcnwZhtgzIVS%G%0SwOw`kF!Uy7_}~l(^5B_cxZ6-S(|EBmog#Z0dhN=B!c&kpgw`8 zgDlI#bD+wU!BevaMH76wx8>Z7>Bp!2!}2V;I^SUT z#u|GVR-%lpf55q3)f&17MY__*C;Zh%}736W6emz zTuh^`02%d^NttG{P}kh}9O`-^s8ZLH{=hPiM%-b+-QiJ?`cT(lLrEG}Qb<6)9QDD} z1Wi+iwWPk5_-LnK=4A2LkyViRMVRfybvCw*vOoC)%Q60KtMN|U?ONz~j z9XJW}69_UmDP1ff$d(KWEiq12a*H|ZR~}k&=b{j;xE~194!;FQ8;8bHMQStRMahE_ zEqO30UIay2`Zy43sZk!4EX9naNiz_5N;W8qaP8&J;$nClD=|vo_C&tfhDZQ23(!-Aj-u{rI~<29_z}azgxa%63ai$T(41rbNp!6L;vvg_q5dg2wHY z4FG*W5?y7W|DQ!$&L^Tx&o(SLjirWBpa!51m=F9DaFOtwvS_QJp0W^xBdhCHrG@=qnc%r0|X=`&)_W?_kh!ix*QbskWqz~A5W^n z*-ga(B6Xuv@WSL$mi|E}t!Vsyr-3EMo<&h0R?G?+nYi%~%&!PoQ4_S$iXD7`S1sT6 znM0U$y-{!gH${?ZRrLxapD5gP1c#J|P@KqIa%G?mK5Zg}cB?_Lu$Wd{GDehI)V~U? zIKV73MyxC|h@M&=@aWN};+=|+kUXlY&4s7e z6%ziNzU?z}jQA{OUzK?OtK7+Fcu0CV%TSH2%UXyXtn!$#ceOUo#!B+a&x~PBAk|Q0 z5v`1UK&_=!c3PFI(#mxxA1k3pU=&G**_Eq;Cg>WXP^$(JRW}(TqWGE@P=kPpDoN77 zKE}|W>SGi=h)15PT7O{0ax<`Cdv1IYQN5}vD6n3nPC*qWTptqjpb@vLR!N#yPC|EP^%+wA^KB~-niQVCUfL}F$TS3)&D z7O(-imR5Hw;R@%kPJRA_V^`zY-#IHw`*6~5PzV|6O7$uvDY7@@3oC-RH7xi-f;SWb zJ`%kh`ommy{_0scek}zV;#zlX^AGJ`C0O zX^5m+6PzJIVBfn8ue~aZ9~`&%tD0_)PnYo=$V@q-USbb$?gnOZqQcBHVTknk4%elM z)V*KAe=dVX1^9xD+^|?x(}E6HvbdOcyDu1*u6X0Fe^m!4j30nlR9Z7i!hc$WXJbzq zcR`Fzz}N(1te@_`{M^);4^MBNcuk=@@BIz8-4$Ne`AypC1vzi;dt>;~z^d(=ue~5Y X);S{dU~uBp=D80|x!sa!w+#7zJb*A{ literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin b/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin new file mode 100644 index 0000000000000000000000000000000000000000..fda99a2f9e5ff826d6e6a83f84ce8f283ed018de GIT binary patch literal 5148 zcmcIoeQX=$8TZA`N7tl@lk=s}ir(4?PzTytw@}&vra^oOTIXu}#%|laZ|ozDn)*`P z5p7p=_ntqhezCi_1%VJ00<=XHMKC(S#86k*N2j7qY#Q{R8ro8X#3m&mq;5%h?rdM| z)M@M>E|Twexx450zR&x-&+~f@smRA6*DY-x>~Qm(=0Nf8Sa4>iR;7ukRf5=bcwlRQP{PSN1co)D}>O4c^ zc?$tSdKKidTZhQvd==ixkG;TNx@SBmQ1{zaCe0bv66MJdw_`;gl3QTR` zMdk9GK9;fC_^_m zU89EeVGbc;T_Uw`KB$igrjMPvw^L;J3<8K^_I2@z{*Y{1C5n)sh{22thdU!#{u6uaFgPosWX-sik{kWOYiN~W8 z?9B0kA3H_(MHFR}xG(9(&gJ|x)19=A&~V91%42)~^UL4Z`Z%N1+euv6ocxGoqH zPy|?%rjy$aUTJFbKM;2;a={3Y2X(zYGAs1=sNnzNd5t0Il- zF;DDxblM046#~N$u881igU+>I^7VbtUoNV($=sfMdIur-X;$vEZPEPts!JvH$$l0_)vc|v26LO?_%9{*QE8$L-7RL zE3tR5Kbh*TTF34#dd9RKl@o=ajM;Ycpx~JrGi`ioCN-~dkeH}oMSEg^QC9t9)83+E5@?taRJWmLX z=VW-*gXi4HtHmcE*(y_pGxgFz0*oG1o^8GJ#CGxCckUTG_2%Y>c0YS$Z0Sdx(vCY0 zUpPCuZ{*xXD62h5!iiS0eV$k}X7;oO0yK!4kw^olSILxud`ji1loel+2kJH-{MW|d z4i~j!x4bEJ>r}mTGSe*6|!`Ug{-+$qAh3 zm!nVx*f`!SP40+UTEC{ux|HaTNs$U$t#pf3udCRK!Dnt5D1#uc#`0lbgF&c0Wv|vG ztV)yu0U<-I{Q-JL#dFV?ifHZ*UNj|ut^G{RXKKH6UittRah5)$(T$Lq`6@>*M(|!Z^iY399HJ@ zT9(V#Q+>HFY?YgtSp)_Z@KzkV#yD|HhA&GeC0o*l3?y(d;GOX~jp-CCXL_%}D0^~^ z&um~GraSIFz3A^Rj;5};UwLxz$eCm3emh^@6ybALc2V4W&m6LeD*%!67A0kkeGCih zRI|Swv+=jDM?`f26;TTfL}?(As=w2GA29M13eF7cT!v?L;Xrj zYZ;2-D27l@3YxQOwEbPhg+O&8#L##lDCp$1Km+sUqk1M)rE+gRw@**0tw z;6B80mKnO%c)PxwAN=PQY@2*?eAfe5*_viP1 z-|zjt_uf&RHpw->%?tro2waJxaw?wTQ3m9YqEdq2;UF(8oH(0R3?v?+)VXmX$d^*C zS_lU#e!EUD1`T}5X-KvX$RCPoOF%mEEDUN0;qq;LOA*L$0}js9JQ)zUX1zu)Ie>jG zU~n>kzxb3*FFSw}F5uJ2fHm|?kX~>Azq^1N2xw|u|5WgM`fJdTsYtyhk!cH^kAM9u z6A(*wLqdzC+PXUu5Yb?LRFe|%-oC{mM7rn`4AmJE!w`$bQ(`+rqw68OQB1|fZiW(5 zkm#ThL_z6VdM!xPjQwrG7S(M&JEj_~RJ6!-6-W>8(-al;P$0W3iy@emO|nkQnKA-_ z5G}XsfS;qN+jEj6DQY&KAKQrf;$n8m^&hM%-|&p`N>%c}%)>X{A+h<5;ZLqyE$sbq zUrFZvwZN+@C$`MaA_-e?6!;+)3?9CQdW|&r_9&`Bvf!CvXTf&`my*C!X*jAxR~2W- z5=QWEDXJvVCLJ@u2wSH3fGMGr)4}uH6h4Z4{!&%}SOcDJ)1<_qn99r&bXdS+Ply|y zLiYY7aln7)WaIgABH)x;tV~?KU@d`)xCwSn!Yr6%i|0`<`fQIc$a`*!_s&z?%_#xr z)LWHLEi=w2WRM8>I@A*IGZR@V7H?!$k0ND*j(*GnJ{7{-wnWQH>5>K_n9RclQ*J=G zm?n+D_c2~uQqdQ5hJSg$vIfE1rl_y(Kr8U0sE=cZ^@PyYF%|fCE%2UZ%bBf(I`9WW zlCBm5e>?>IG0Osid`QN^`d^AH?`wIi5aNx z3|=XO=hs#I8N&oEyz@oKYz6O;(71saq29T?OCvtuHez!mlF*XL#n@=kDC@3RJXRTw z$5IIhr#Oyt8j(f_kaZ}{0528-{-6y7mlSnqyK5hKe>T839hKw8=gYwqvi&13{f3tp4;&rmz@%AGs}I4X}&P-3v)F$#y%N<8AaquO7F_5U>}0 zzqlB8`eFZ>X}$l9rKsU&mu-F?-xrjVX*2c8biPx=9NJ`MScJbKAK|aI zoCxf1Y?tbeTltS}q9niUqKpi&r3@{zND=tk^Y^L^gF$*jcz~aGYqJceLs@Co5a<#j z;7qm5Lc^L-g1BMC4Ldjk=Z9&?TX1>|62dqRyObss2MCi<>x>qQ5LwSpkerlr20o`+ z#te-3CuA6;)ne}?e7*S3D|jE7_+ud)=$uVtW-|6_pwviHaS$O`G+1RMhl35DiTGZ^ z=Q^8UG6Y&sQwEpL18Et{f>kAW446O9~=_f$r;OLQkvV_?a&$3B6}j8 z-R;R$^NPfx&sHcak~?DIvIzbb@7Tf07-cHuqYgGe$S4KL*a_i+pV E2k000tN;K2 literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin new file mode 100644 index 0000000000000000000000000000000000000000..e299bee5cb399af9d9a122ebc9fee2682a829cfa GIT binary patch literal 515 zcmaKo&q~8U5XN_C1@YqF77t?g;JH+2ix;8bSxgp54goVuEM5c;MLl+tthor1q*X6o z^aXqx!DC-Q5Ik3%EUk!87na?b`DW(FhYCBQsVb5!y1qa5EG)N|Bx|~U3r8C&I2`X= zYm)7_D$qgqg}%!53L$osts;m7&V{1CU2oJIZ1zDOfkLmu>^c-ZnHmWPc_DpvXd5EQ`|HE^i`g3(3k8;8GI#9xp{=w~$Tc8O;K(P01VA9~ zfBk<(Sc{>01&~=*PM3gqD0~TR`Z{ ZhB(E(9TGNye?A`f&Q60pHowUhz5ykB&+z~N literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin b/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin new file mode 100644 index 0000000000000000000000000000000000000000..b135cf2c69e8e74211703e2103c4b988924b9b2b GIT binary patch literal 83 zcmXpm{*MX%i6pp%Cn%UPCpd-2npPnlgm5GTHVbk0 zTsmwg-94kjHV_lYK@JGX{z9?=V#2v$2^&Hmk-a&I0n)9Fh=t4Bdp}C~9V5*NMZ9{Xp$F~~I zF=#e^ZvNvws$7NUx@c^dkE*-STz~s_CZKl&nj5yi*6yR=F*LW{varWT6`w(~>8eK_ z^wGpO&}{kGC1q$XN3*r?XT3fOypQI-pM-vjWC%e&PoZax#Wed=piRPJ$-+Kkk(P-X6`{wy* z{5~|lvi|qL&Ujw!_GQ0l^w9;+pn1n*PaH*a6q;*fQ8%FZ?A#vAJCafT;+^y7`>2SQc>R(2 zx1bs4=F`8yX%-zp^UWhy9zv53_O0~FEod@!-k$eZv3tgUy=LAcJ}SIbZ-1vY@n_KG zczr1qepRQ!xuV*pg2$Fo^{3mywnYWMT0%3v+7>oNVC8hIzhLB(P~ z>nI^_k=fZn3(vHL)8q}vp~p1iBuzQe7Pe%6Otu|)E3Wye@CF^z8a(Y2m6}7|OEBr4 zj`)enb}$PjrG?M7g%jjGlB9uwqzHjuwgv$eEuyw?k14KE5NU?rZ&2YE^e`1B!E_x8 zR5j<#mhgyIgPPwTkJF+H+QNNu{X?GQ8S>tFted9TZQ(+#zsql#RCo;@r^3thu=u1q zH$Zx>3y}Y$EgTa+a69dg>6hapa{Ll}hIn@!T}CezPQYKq$zzFrTJ)c7VMp%T2G85V z2wLK7Fc1h>;QGcU%WQrtoahgA7^zP8IjmlBsuz#&Ut9S4lc8SxmkNc*`!|RPJ^(FR zYK0=?eTyYWKW_X-TNwDUL)as_?`sS9^6hwAI3&k+YGx^UkMiggMlWg$L(o7n;kZTP zGU2W8l&hn^kE(q<3ZROTfGeSvc&Tsz1JPv$T5xD@=wgYesj~yE##`a`!gZVO6VC^u z5PH$~!|j({S+hyJkhvUYk)l~t^%@|r0emJG&*8w$du z1qZ2GU~aWFk(-H%Zj@WIsOW1{eId|QbURhA0$qw(OXSp8=%+drJ>;Y$&GF6(Zoaro z{4p5A&SF`7Ra4QQ6l>7PDwB%dQOuE|k=|&ugJymibB`Ry%~|hpvx1xR*D_Dc`#dNY zi&^RrK?{MvIXlV+d1R9WnMUqY5RasDAs+PwT}~ARD~&p;)5v&?7Dt#pM)s*g^aWZR zU`5i6Q5n}#ay*T^Et#any=`Ib(C86fF)!E=Xd&;*VxR+hO0z*rVxUXBQK^}tm`1+R z1)4iWBY%J51U0_SyuA2+kXV7{(cG;R6nZQZG&bsT-K)ARaJ80-N71)c4|f2uoiu7e zR~L<%-Q6u`vFXCc8UNKm2@}3G;Q>B^VsfChEgZMSfGBpvnM$po5VMdTF=&*(E!^Ie zE?Ef*OX66PAUOB33zuEEyky!1cjImxmvLOWXXsuILyn{FR5V{xrvQ(ZQSr6|WbMhjca1J;Vjf4-EVJXHDCqHE{55cA9vPzL%oll z5{)OR@q2CII@^;LYoicZ5g(12rh~ByMv!+PDn?dnKJ<;gQ8&cp8R3(R`V2pfKCXxH zd7Vz9OKek=y7JK$3p3+rc?WRwU!S|-5-?*YcHaq-HL~|RFz%xwy< z#gNQYyzjiL6whu8CzA;(z63VmTNwHoi&p&^IKxE@B0ZWD>-mDD_>?RAif@*Z#HQkJ zNm1eq5`Ge?td&cubt?XOJQ}C9P8-Osq)exh60mS8O~rqw;y;6u7heN06IH4k3Q2Ob z2{B<~7I41gZJQb)VloWsiqQ;%4wkBod7`>xn-t;}tC*^3U7L|OSwl+eZ6+(c>9(-%Dfbfc1=nZ~8H}qC_sBIWwIW`6wEQx|wOP<9}AD4Yj z63UV;yrnIi@_?~RZigL`KX->acWWq4V=u@~K6a!#In6i(l6XF7U0gbX|4BetVTN!> z?V}IhwrGf!%sVqtO=Az!*gaG|6C^P<>`MN^I;#1Uq%>FXviUGns2Mc&gi@N2YBcud zXx1E(!imOy%cKRPKsPP}n)QCVz^g}X2m%%m=|n2-v>*K0_b{4R%_GIhg<%1@r4V5 zpBeqs!*?J2>whi2_GskpuHC=6c2Cz!zgg6^{td^nqnPRYwmjY_Y*L2lU2~|G=71m;H|$G8*?|U7QIf1D5!D5Fg*+j~@gBA|dX@r!?SvfmYFIG^L>XJfb?`X=WiWSYjHH zCJ9rrk!RfFRHQTyAbo^Uda>l3+rIr zMra&t4v6`2zs2*$Rgb=o9drPP9l+tzMe`JwC{IFEu1GSZuO4 zWDg@W#jF@a7~AlrFX|?{VPHXPc<%p~gDZZ7bCibD5bn>IRj$!L^k@t!8!y2DG!~Uj zA65d*8}3j=BgU)qmyAkfdzJZHb_f>2idm4yAsC7<7eVnwknVOIW^_xm$p$dhpzf?d z%oC?nc7vj*vad*qDmK_3%F`&VafQ6;w z4|D|sZ|Ih(+#~1C^C-$E>GIHH0)l(mPH=~7j+)>O7(&BMve`wOQD?y2l`ugI2(y$q_JC>2J``@%+W|aR{kJ(iIZHNy{coyo} zwID38wkdhL{3&?iRQ|B2PQ_d+&RfprZ&QTIZ)^)U*dZ#1Y-2H>aK*gzvhqo|TH;jr zS|FyCYdds@LRd6meul+aKmjBJlHF|1nG^CLZ9r<_KrN^ncb+_Mq6wEvP8e(!fJH1R z$J__}(_M3sI)hdbutk+qI}x&yaLUt}dEH2l?}x5C>-&jvWm)&0tu(+0*hr;iBhcd?lfa%;l*jKS-)qri zrwr)Gp`BW<+D)hkN@%>7G=&Bb|%vq{x4r1lw%}|qB}{J877U8- z`0vifcQOH`OngVH!c*jbi_ewgI2}nucY2~diDL-UoIWMvJBZ)dvb(E?v{DS}k@xx} z8cv6L@L$MI_mCfMliZ;jzw!S9{KWAa|E)L^c_)bo4*6kp=E6Dt8=wLEdP5z+U|VKf zr`AAjl#l zP%>16z_!p{P%=dOU^ti!3arVg3rO>G4A#H_7_6)=fTZ)QtcI6A{ps@>tV1Oc1-?5B zM@!}vv!Y;U8Q=@NjxDR;P~a6&3lkX%Z2`_ig}=lUJ0#w%^hGG}#Be*Ki2z>%*IHSDwy~w_Z%l)9aETLRWRE>`XwNMwabUAf{Ay_b3_mq z+V3;)_FP9YcbF65`I|KH>A{DIR7MjHb0X-K6~aUqxx?VKqWJuPSIl$)uUH7c*#`mO zhc;eyLcH|P!42{o0=5go^Eq3KD!w3Lpo(5;n%h+IC1smeApQriZ4s}7^&QvZ(oPb$ zWUn~nbAMer;rAz{X%Nf#ok851AO@)7)%Y=*0?$klUrHFK`otT-G%Tch@%eHvrBw67!7lM|P)osA zaNso9@E$Dq5yugbmj9G<#QIB(M}zf~#;!z@gLqLVhl?6Bp2SV`k@whdkzs7;6LXLc z;aWKqtR3V-h{y50UgOIQ1`4@ zz=^eR_&_u|N1N}P_=_bU-TTwP>7O3ByuYjIo%^=GG;vSIyWf58uHE#D`a@|))Jn2X z(WIZlML<9ja^7{5dXi#JM|ZH}SP;w*7gGe>NUJr_8e_K5q`}G|g!b)w-+vzjIyh+1 zn74_^D*qvBhC#yQP5ELyM-$b#=cNUBwi0o9Sb#E-qR6J2CP(w~5|h7}$xBQ=oy|*3 z{%STaG5HQ|az-L8vlGJ*-{ham`3KXSm_?KS8#+*iYdD#a7pxfoPGVZXmfBK=x`t4+ z^6#tWDxFxh#P#oIJRs=>>LqK*piNbKTzUbsR(;$l#p;s|Kr4)r$%uwz@g?2FH#$NmNGJk;E`q zbTAOk?NX!84jnb9YhxzOFla7Gk$KZ&u5-H@EtSJ#Fman9XbY~U9Og6FDYv4U7lD0uq+Df4uO*731-20@6vaNv zAMmSLO|!tUO}`y4^kutn>o&a*NXlEXJOf(ZTOCXh-fmx8IsWqH$wmV#xMEO{VD^Fd|NjKQEkrKm!UxehjogAFjo>mKw zW!h9oa+=zq&b|{q*;Iq3eg-xaBp!<>qtcOKGThK#bs zrD*EIz0yJH=P;<8#!kwu_edx-p7d;`sm1y6Qk|xGRq_xpzh+yB0-6Fh1wLY|jHZob z;QU@IN{iosw}R#QlBOc>6AD=&bcEEu2$~M>gQkYjDVKSN?Vo0@FF`!-U2OFODee2NI{Fl?TTY>&g4LBC1-Ikjfi_^60<8Vx& zk_zQ|T94efdtu277~#(%D=w~A5f>bpTni?gk80%RZJPGGI4uD=r>Le_aUejz5l(wg zor0w@TF|N%Exm`smdk!GH_n?50esHeDF|4UDd1z7B~b_j2$bYNEJWS~g{w#i9DI)3 z!t@1d5fd>Sml15Lxkiy?ET>Q{s_BXI5?QiD<|0drJ$U90NsKO1H05>!>YB%3T)M>A zAD3j1iVY^l8GAsCGj{NKPai9ROlVZ|KT7j5QDTE&Sd}1RoA+#G63FakBAl^Cr|GNB zE}FhfKADcv^iTE4WqRdj4?m62LziZCz>%IYTgNKx7EM2Zx)N1I!c`dQaF%3KH2w4P z8D8;z(4)Kn$Bl8GfV7z+XvPX~$@BwB zgeg$xk*4YRblF6WNF(uB^D;W+3`u5_8c>wPo$%P2$5jL_Ezk_h8XC0(+WT0xx|w0f z;6jL1C~o9g;NsGZ@9O|26PR>wTez>5f$`6Yu6fXR7#6XkC3Xp9_R)%Hxi}h|03pwk zn`VxZ!=u@Q;jrV(luk1zsT)ed$lf@5k1(Nq9rot{%?z7KZaPszh#<|pFc~R{M@neM zbI?#CsP&8QKt8dzmCm-r$KbvU;IqOJmj~@b10x17v_cC6G%l=ZA9&{H*FovKyJ^4N zn0I^b5;0N<6LNMYc|M?-Ka?puk5&i=3~!=<> z;I)!weF~I@6XRo!nH)9yHWa;`5Z^+fj-O^-tcPPXYaClBB0!My&3T&D+h2^VBvrr5{v#xe%9U>1ABStg- z${n|)V*o%t2{G0aN}=k*1T3b8z_~^1=76}d2B;Hb?yanVgu@v|yuh0n<({v)6D^nD z*;96JOC^s7&%JF!&F0A&2Z)d{!$^s3#If@1ns|p2DvHrMA&6&hPSEVeE(vW~@`2KU zn(4JrSOCCi_RZ;>vtZNg%UrC)WZVSU{1!^PXkM$XP8Cx>tDTk;w&dhU3vtFjy1C1c3TiaF66I8z{3(D-tW`qsxj^ z4c%#)Gm_Rv6109x7tQ*5M*Suk4BYOaIc+p&I!1JMV+d~3oV78zY3+0umPDw#$)fd$ z58}e2IXl%XAPu)$j*XkzNj!;&tZ@wDblz4y+83rd*YXUs5z<4B>H-BLZw^>#)?IDk z(->L%EMf)eREXx>W`z=RR1z$OCmbvc6oS2bC2eCS@ib6JbN&luI?Wg3dFynqn%G3i z3f1n`k6XuSZXwP2Yy5-+dz)8*%~v*Uy9C>FU0l#EPSH+`71g zA;##DVDOW&3v#Cd;u_|)ja7D*V`ig?5hU+2F1hvfO0c@9?Y4pe+I%hc-Iv)q&F#{| zeKhBn0G#Ib+kK(#<2JSa0Od*+I%3e?r&9=48#MP(D3`fcJJ|ghh!H?_uT3o7uP3k9+wA#oTF(1HI33)ZfKj%@jjg*$*= z!HYeBx#ce8w&nRS?2cMAZ%xc~6JvpD*#Qh$sgtpOn)PhD_xcdk-gXKfr~B~Hg#p)6 zZK~%~3h+`BO3dW+PE6sHk)=q0$%B_d2h~2NgDm3w#Fp)D*L^zG-pjNmyLbcYstqPu zX0UA6p6&^q1Sn2Nzr&#P_g;Ux=X4p(8vzMu0j3l`j9B`-DnecCymh^a48j<1mF-8r@FY5D5t4^o+ZKbon7>S?dCw}nZcA&3=G||{fjX)7#Q-NfV3fOr zC(RR>gqie!LGvf`o?-pLEs?AP@Qg~DuhIO{xcC?+OK9GuZ76-?89AxA6beo53b`(b z|9StdL;p|nqT%X&whC;^m7#3o(tMbF?hYbxwE+toV2cPe7;F5raFN~+c`Mw&-mr;cH{@HPSDLsa#FViFtVauVQO;tLX?Vw&{q0LN- zTGa%~DwSgv2mPUjn#DR(EiPmgR{I4nzxDt&>>5L~@D9f%YKykq2_Eu@wLv*v+O`Y- z(=}Kbo!fW4b2RrTYPkQ1;twvya5b{51y92x(Gm(Il!uj+KsMaltKgtTQ*{t56PXnD zT)eG}TL)&C$raR#_5szdlf~|{?WaW{on0$g>YaVef;GITjyc5T0QhB0^|4ri>&kIq z&7%8s#bhY(;Vjjnd*mS79RnhcdRdPx`o12vyz+oKw;w`QW6?LIxMhq$RW5?AaME#F zyo46lrhBoalj#mLY4PM<{GCX`bX_!{GMZg%H>x`KUU;amYZkMphaUv@qDzVal(Mro zh--Nxr8?m#LMZT5i?_H_W#{?Wu=5OCF3Y5!e?ti*s7P4(lO!k2<*YJOj6&3n7GKI)028SZ6(Hh3I>G8@U_gc{;O{PtgN;HVIV*EW z#;XWaAVeWA(Xeb3%@{#-tp%J=#4uB@i5vM&e8(DVIi!%9Ny$0!bK>P}mRz z3)MXhGpFuxotFMjEFq-=V0MooktII)1S;Ju+lrM^9c+!dZB$oh<1a~d7eP+!=DI&r zj$%I&0iZdq3}>Ncpe}@0`hiaC@L~eheNR zi)B!zj0-VYc;rAJLR5E{Fg{R(%2|{IvNRo5&~h}(3Esei-=_pDny)bkz}CLYVEP$M_Nu$R-Z_OEIXxR2S-Z5K_fh3X^`ve zYlE5O4KTLsM?3)A&%=iBbV_Wv8%Gc)26#FI{3`5y`KM4DRp=H5 z)ADf%r6+PD)drWhrm#0!z6|Azb#+~|e4E;1Z*Gsv5348AF;%}U`ysJ)D9@;t| z>QDHn_-wL=li;WwU|a@27?#=cw22pf*gJts@5aA)4p3~SYIym-xz)N-m>5Z>AJ!T? zX2n!sBTdVnM%7s(m_0!&Drxy2J7@)p`0+V`mcJF1aZ|`ukRt>Rziq*6gS0B!j+Pt6 zunoLz!H%aRy(34t7I;9eif>RbSF$M+hAo^-XktZ6HZ%cb3mKQN^WzeBG#8gZ9MwxJ zx@4RIIEle){j!t^9ArRN4*zgWp!5~r%)|_$w8Fx<=Rtz{CzQLHnkYbAVC7Ea6MVGd zMZNusjmy0`OMp{}J3sNki|5!;DA~nHiNU7S%85D$fOD49%8hI}tz0tHa+>BT6L!|M0L#5@-;tvFt2;PvBH2tv3N5OSC8NhEEPcHCFPaGX zhpz<7iSZ?o@`$eoCQbd@wA$NC^{?Tpk5-R4O{-_=RR5B7g6d!Bh^kkgF5E};&vsM& zV@bMjJ(gl4$iRyLm+`XPV^jEtZQ)Z;Qi-;3zxw1yagxq4x@aP^Io|@mj)(6vzGMP| zg{!CNA>gZi8Tv!C8dmU-buW|auHJIay8Cci4!`}kx?L1RY3C>L=;}{qkkxPn{Dam1 zig&44Zz<86auD;z4* z@%piVE8dTcwc9u#T z2C`JTrZ_{TYbFh$(lxVlRJx|_A5-a?tNs}(9YkwuPDom7__d_9H61_^=*OZpx5y1M z0j>FVW*=)i^(d{mOA$~eG7j;dqoK|ZqoFl_0}b)im=uJwb_)~E+Hvvzo_?2b)=tbP zoVAVrkZ=?a|8L1+t(hSU6cw%cKiIPkjU&kc(rWFEs2yj&)uFXtS4!KawLg?*MN-2p z*ci$wrnUd!TH`Q7`Hje=~r&H3NLO|f*hnYE+fdM^%H3Qs2K7+ zDG+*`*1g_A>%KhLcH%;8HWhX?Goj5m6o<{Y`>-pQZhdCm2;(niCnu5UyM%OU0Y zr;~Cp)WiA->=BKE@)#wR$NK%Q1qFN?=!>vMnTGm5rV-QhBAzqB@JAC9G&^3dxhXlo z9En9esd%|vZsD$G`!ly>MMMM%JdYR%MtvHKRx@6db?vdM5>5`?G$=U)YdGb|J@8w1 zFdCXK^yE2Ry1tv^H?E<^Y-W5ojrFcD`x3kfHw2y0ZpM9N>$p$*gc7&bgd z8@?68<2}8d$7IM^TG13j+ES8Zr#{7GyA9#Kdm3g$SRzv1>v#zv&=Y8;O%Zk#uJqZ2n=S>t(x%x_+Vm0Hv@YG%Aw&Q90g)p^PA<@i2t6l! zkRp{ZA&s#Kq7|?pz1c^bj-ZG%*{PB_DGMDTFwmx?Nt-sN5NxDPUrHbAI@Nzlu9ZfS zdK3h#`3%~04}{64@9Id&@DsNpu_g07UD$-oFsXctyd9!Vy}&|kurqL6V&j;~=>SnZ zp*X^VO>6B?N;-y|w%|+IpX;(>N!nbR>Q6%h4#|a;(&jz7MVo6?tQ-VHn|H`}btIoC z8V)2eg~S9lw~=G%n^6O?d56=R>XlJd6$O$spBd`b%dm8ShuguiVb*6)RGLf-stJFc zHvfV)|5!3{Led74#U(Lno8FyBsI!!~XJ%wxfM`G{>KqeQ3J*ev9@@f%Nx*i3 z^_kZXz;%bV_~RU2n}?`}3ZLQPOfcYjzCh!a)#yR=Eue;VOf+!Mtxg~IfpSD~LVG2Gy8!faBA;KYV$J~$^bk-2_*UH*9acKzy>Cl0^M}vRw zporzv1NhMa8&z!@3Ld;s6g-#{u+ls5_lgVHQ#>j)o(h%YDTv{SSx#GvSWs>G9cH7g zemmk-ej03}2yFq^Dm=1rg}C%o9S10uz}v>v)_T^ZQl7UTaYh`iSnpZyrnOcpk&8-{ z%mkdi+WNK*tf2N%9v4q(;w^Z`tq6%j9dCURzPoIEUxzRq8BE0zcsbe^cMId>v}vwk z<(Xq*jWQ5W#>*9*q5y91$e=i@^;kU^l)^iX~-YiemDlfu$RN7 z5yver+MzM`jVd`Aagh9i|98BMc8mmRHGz7AqVRg_`rv8nG{S)aJ|ATkMa5PZ(Pt#0 zK}eS9SH&$jH!UDBfjn}cv$>}imPW6P-$MCSAN}~wYo?Yxano(r+;GjLD|Xy;)c@eC z$%T(R_LG`DGbT=$cf@bsOnVEV_f83f1MI@n_+5qVcwLfHDiO={0#qpO?QqO#$0I%c zy`e+>y*QfB(T>Y#$FUyTaep5^1no$udW0^PQm2or$d}aFy?|80hl05??4NsC*RrZ+ zd>VbyD(K7V?j3j1j_=Tp8(^ zqnozx0c$EegfiBO2ED(x&<=%g3mSm`G5<O+)i_-NY=irCN34v;-EP5GU? zG$jxXWy$eCE-+%XyAwfC6kwu!dT%!t!auhCaK`5uS0%@_!}T99MGYhr=77kNOpoZ3 zyb|q5XkBhm~Ee8qVo$tX%)6#NGjK?@JcRVISr3wTsSSZzjpyzRq<}g{%K0t-v zN%()9r%KMl*@9U?LA_KNYckV#f5nQo<$S(zJqc0j33@c_&0~7Z0^zAdURZiUU<_&fV-(~`?$?{pOS>u%hIn68Atg|S zACQnz!O5x*3t>P!^?($BGO=c{ir7_;^rSg~b}eGQomz>BSf@m2*Bsu%M zD!Sd8hBF96`DynWoui8UvQSVIv6+s_Urr&|g`hYDLfVhw&?`L5SOp%eiAR>`ZYPV- z>Y!DGT%H$T7_=MW#ZSB5)$y}XFWVsx182~#S7qRe8WH~9+@VN!RaOOfqus;S(1&%h;ne{@IV2hrlnj=NKU&Ivdy=YKb=^e=4?T!JS zDoHR=&=A;CRI&NMHD?6{KtIyu6uK0DAB{=B6A^rD!HT3JX@vlkeuUz#U&-begiq+3 zc*_+eZP=16Bo3_<$QxAxp-+Rb;iEiCq2FL=Mp;-Bf8#kY6Yb46v4FgXav_HL_uAFh9sEsm$41Q?v7OD*wT;2t>iT z98KN=Tj3cLp~u+RX@T9-9MP%i669amH^Io-VA}fVz`*Mud8P;p@6Uoqnm>Y3PG`5u z{=iJg_j{W6=v`elHQj+9qmq6Ass@@jvW`X_nC5_bnpffR$5PS;mvA6eZTKx}p3k(^ zJY9$1)AYI{%gT_}9De=g^1St_2>~WTSL~RyvO{SW;UUlh*LC2P-=^Qal*#|;W=~#>q%f#=bDC3Ha96#+T)rB{TU{LcjdK?yA`&wW{9VghS!lP^> z6zn%Y03Y2eZ&UNV=^jx4n!phsxF3g$a-~cJ2ruEOH!=9f3LI*F1$l->ylB9Y4;M3{ z&?`nFzZtiJDccGj<|WT+u8IcXwx_mT9M0K>GUtgC#aXsI14;I@TL;f|c=MP-q#p|( z)B?lpX?49&t52PESdjzE!IuBjvxvv;;bO*)!$MxU&bn3Kp2~Sc>=kcsBC94oyz6*Qzz%6b$*;yGqP(U8n zlF0ua&s0yklus=uAh=Lzg}`1%g!ZJE@cNkc_@AUgW;x|nd)Z~dgMyFjY$cofKn+U< z(52C$@FEk$)Ostz6a0&5UJzbutIlpkBOcux^rGfF4xdEE_T@Zg0+f-)R2%~^JyLA7 zVp`>${6s2K6Z30JTKn7We-L|FlR@7~_fo9MFd+2`$q;9%E>K6?Lvg#iI zS#=JO`nnGRQePo~)K_4P#2z*>eAJ-opN<+}pK>aELy5`vB!EoSB^4fcgJp&RX)VuO z>OOfNmHG~QH(-TocEIFs*)ZPldsiD*##&HH4WAIvZFn`(0f@l*+It220jg{jhRMON zVFc~{Jo^T+?p&>*Zm9%zOPd@k};V4wC_4SE5gs3rLf)heVjAL`@%Q^ zEc7(kTP1-s+WRf2qCW7OGHYT9o&YHbaaK+khZ(dFF>N?}^4j)j_>DseN>XzYiAevD zAWRGGO#}3F=rDse!cO%dDUY8MYz(@VQw?aphF?@4E$g||@1-KE!PUGG+RJ(>)FoHz zh)WNK_TD39lv0%J9rg6uDW^AWxdzfd-2eVny#M{k?PLG@^7p^*|HJnp(WjDC{D~s4{hxREM_ObO%l$o1#L3tfkY^Cp$a5*pET#Ro z(UgDX8W&j4_zf0W=?q`)i2Ksyk-z16f18&)|7Z=S;#$<>g7l;Rc_u`F&4nG}0*{k%= zBwfRzOs)PsOrQ%}91CA;k#)}?wpwKSD3UpCt=W&UuZcXOgc~>aEzvxu- z#IcjIC*7SuwyvZ`=CaD*_QZ zAo&hf4BY9A6+?>0vQ~^NkRGW5GH_#Js5XL;8|26|>unot8T8FqJBk~Xxr0az+u(F? zo6b?!tf^z8dN$9}L4-XP;~0^bOP}Sm7VI97sRus+#aY;BzR?qBqY5>YFnppOTZK8; z=!xMc1Yz{Zm!8itdh%Atyeq&fSgmxBGZzQHqYBF%I(Q!f3M^Pqz9wH>Rh5?pJYNX* zgU`V@Zrtin-OFsPvZjISARfUBcpeeL=k@rVh07tWOZiu=1N?^U2UB~#_PxK|_Ugg6 fH!Pic@xk8NSKohX`(JnKA2+79WbAAnoQdgGNg_?Ws z%w!|Vy)y}dfFk%8TU&Qu5$pcCp|;iH`&ergDeg;s4-|@E{@-)%++-34pM5TqbMHNK z?pc1z_xJt%hN&v653r27TsO&TFyxy>^7>#+*w6wjn|TAQ-taas8UOC^I5ox4(CwNa zW1b)Nru%}WsZ_Kagc_h~dNqXUmdJ37=jmr} z=)d$aFLM^wWxFvhq4O}unmgDbdyKGpG9)(5(3<7mKkRnVgz}(IZ7yIp>~T@~+8~-8 zRg2M_h2~h7`z{xadk)QU(;s{Y&3n--@7%Tv&DCgDRsHv6Xx5@RbKZL^(JVr<_PnPv zTr~DW-aOe{gk~Jgx~9%&(7XuEIrn}q%SFYPp*i=gi4`vLJci~O8OnQTYG^LFXrUj? z}?_gODn$>7t^6XRVT$CR|^U|l>s*9Arp}FqSIVaG(2hAJ*c*eVE zPDS&kkvBi+BKHn7+YdLK;Ud>bG&|&A{KXfaJmsPhK{Ov4weX0G zhM$e*6NmPUanZ0>(cHV>+(RzP{tcQhU3oF~ENcy#`*)rHfr~OEVmmZ(*ri|Ue`37Z_=rn0QSFVgod_MtYMHf9VKg_&Q`An`lSddp!{hI8w zR_B%d(0R@66idV7u--Q{&8zlVkwT>{-)LlVyvA&K?8nU;{#ahzv3}yhJ^PpZ={iq%zWoHXR{>37rK z%Xjmu_na8=aqCY$-nst|kFLG*=9?#Me`|kb#es&cWHLzZI?D=zNL7n@dN z8@E$8?vzDk)}<^8A_1|AKmY>xfGo)-8{&!J(+htRlN0e!q_#oBZP|!MbU2sHbwL$0Yhlt$0^0B?%{DD#9)nMXAkZAa1pHMre;fa#w$g~Wbm+Fp*byhe>-ACaQDXa=-c z^cf=h3>0F!W5P%%@dzZ^FpZW`xtHd@yyVKYAOCpWk=J)l8{2ZU$h1}Otc9g1z zH-&tC>RI%wFN^ra$C@zv;~9gx!Es}mW>dm z;-MhsBW(I&Jurh|^8>An;WL8MlVRR>;FIluc^~=_doF3-4R1@~*=w&{v3kY2YrL0S zwes2(%e@z_ShI#!t~g^@O|^u7peDru8dgWcD%rfSmxfJ@wu|le8#L!m=wsZB)13YN z4oK0(%2Ev1Kqcw;_bmO;>ziOV`b16at1j2Ev+RRmUXzCXHWG)|T*Q4?ttr!_r7-CM zIU&bs=*6}yq-Yln``D5)rqZx)AcU#@VE9>FLHbbR|4GtqpO9YuR0}t2Vxu5*)`8-# z4zm#vcWLr#Wr!i0wjYIeK!IrI;99n$)oNvaQ_`}kl-gEY*f4sf5 zvf!fG!+yK#A3ynE-k3m60xLCX__2t<-8$@mE(7MrIH0wxtIRMhZe!zqrEi*rh99>T z93+iEIN*;*;t|M!I3(WPYiiu$Zvu+96yIs=v~67dsT$c}XsVuT7B~v*hE|}OPJ>36 zwv8KcH(rxO9I$aT;sHw!h0+-?d2(HJw&hhv4hcqLd|f&$7rZpO1cZ&Nhc8MRxDlV) z22S@!1F>$np+r)Yk{Po z4t_$Da{Hd8;#C?|MiXAb?vy8mwjM$&bP}dAk~EdJvg+JqCLfkF7Uh?Ys4RL}$zdm?;BtUM;u%+H!awUm>W{)AM#3Q`?VDd%cdufhuET*4d?gseF=cwrTMSs#=I zaEt+#=yC%*VT^mDiLLO`IvgP5aG0@TXosuFWbPt>j?G5guoMSd(XJsRbx~C&JYLQ{ z46oT5YqRFqVa*Yr@SK#hht=a@YrFNZ(|U-oSXWpESN<{QAc*bYD%%@TOe<1my`2b} zT`Gb-16Jn5unRjRPnSb3c}VZ zFINxElRy|AQxqCA2HIq7V7+n5U8#56PPvy;ZXge2! zYwKc6GdwDQQb)d%Mn4yfC7_9TjO`wd?bh%TK*z9mv(lq@ltM+xXKKEJ=v;5$#s`?u zPr0vXl>2Nf*2Q<5CIP}ZVGcAo60m$+GQsW@9s_EIORQyaeU!I=8PDgV(4Hn!2ccae=`o7abn7nQKU3YKpN!*r*U{PB(< zd{I8lBg6FPE#vRP3XesZ)1&Y;Hf~f^8a=Kl6i)y(%38dwRrYI*at~ZF<-Lh$Q3IWl zCkG=q6>r$fN}@6wQVbg%!{GM@LmDeFfkSc6nGBLf-vQymS2*m}B z5V-WyGT*l&7c&+&Bk@6k#7}>dB}H6_B1svFbPni;PKiNMM!DG8=7P_*JhHe6}&k>?EH;kGvarL1@My4Cp;0%c z_cns9<2H-4b=*3^AlarBCJK~*h+}EYQG+=w8znq!0>m4DY=AKy5#Wy<=bl1ckZZb# zr{LO>u^2WFx+Sc$!p|4~ab^!Pu3&7#?e2FeDOilDc1%Go801=-c^l-~^(d=P#1nqC zn-8JJn>oiP0u4PS%&-FsXb8})4Z2bX&roZ{R(MUIn|edTwjtK%>opoEmqU9EtO72E}pWNqjGn3*M1P&)2!q|%x@8-q_ zF;QR4WRUa22xI&jxXG_1@P7s;X}aM{xEB$J@hz*YB{%F~x~SGRe_m3GST8AK20AeJ zk#BKe9ew^QVG3^mG2)Yg8o>|rpQhT6D@a*n0fgm)F#F(8%H9Wy_NoJNw~+z!##uQj zcO-z_I5q~$PEh`al#tX2 zn;|ulOZl5Q>zBVPqDQSbIZpY{MAIHPH?3UpDgT{;M{Q#jv&ZZMU+n^X6@G1luU?f3 zMn)|sb*DITxcx0uFoVfmo*pWgqII-&w)dd`T{v>Q&~n#Mfo|@m2Y6{58<-lXXPC_r zpS3&?h2~MgYF1}CX|OqB&Rl!aJL!V$sZP4^=L4N|;W#+ymLs{pc;xOq8yDpsU)JJW z^>pc~qsrde_Omi2dCBF|UR)UMNiccKom&y~a0gvDW{`vK5DprE$sbp&P$;ky5d-CK zw0vq8_U7aCKD96opV~KgVnZVGzfR`P&AC)~bBa4H0I(bEPP^bv3$IDC_s0o9r4}c^L-nE+ zNmBw-=Qkk+w$*0+-{xMRsLS#$NlIo151D~_B8C+n7yUXti8qM9D>{%Sm=X$y0eR}m zt&#_b51)Rn1DvAP;1sw5fsst5s5!9D*8xBbQ&t;*%3{ECEww!_x4i!HIoh@btt}t# z>yFC%pPznoRP(iqrfxp`&4Cw>80x)He_eOEspwzWUmdQa=x}n!QVbD?OAXw@^>4^P z9|R2%@gMpL58LloPxlS-95{_j;48F(Nw`BQ&PcOIcEHJ#e)Vc(&_)<$Bg=%p)N#KC z+Jc<`(>bf_i}Q|uv+(V5<%54cUs<&0z*B#{vf_)S=YQrK_3??TOV_1mI!WF^#q0Tz zS3Q~HCIS56M~feif|LIa2!M*;6S#n}R=ADt@CBT%hH%U;fQ7=I1K{TD8D55iW(V2@ z<*$$|!3WaVvpB%;lMHV2JB<$ijofJpCP~$eu`7jW_ZeXwf$i8x5Ii>$Ked9wZmv21 zuZ8`Y#Z$l+XEHNtxdtUEcY%rmn4CqqgW46Gdnl5Iac8ngV_&wl_7pJ_RK&N4*+8iU z>6qOwfvL;1X!~)9tpsg9?wZrk_OGX#iI>K0!wOGf`M*s?8lWTIux(FLr!wxZwlx~) zYzKo9D-s7fiwKT_(}^Z4uQOvT)05;aY~z7Y9qBZngtC)K=NXPbS58TgE5c&&{J3s- zY__*#C3oi~tF_h`O@9m217iIWHPYTDu4Dk7l5OdAmr9;UZ}@DEg1pxPbdq-|d4Jm4 zp^|q&TiDx9-VEl@{Rt{L6g!o$Xze2`I9YEI7MusPW9N22Tkizs*pPy3w{(Kh0O5Qp zrLo1_WNc3NV6$Ij~OmB5FaBvwkeD8 ztNB~o+WOzx`oF!E#t*Mkyt>v>!At|~z27=@c>o+1L_fP&w-m zR%!g_=@C-tlbm(ZSOH46D{;cfApwEah zxu-i3&!sY!GX3$VAx+9INk9Fv`S$dygNEr#$D5SB8w??*#!5JCq8m;VSwCJWQ1+@= zLpA28MdU`#a)Uf6d(m1(*<;XyvZJjgRH#Sj7Ss&){tpPS1g|(XTg+o@fGjF+6tU_ci)Ud2ebGQ$P360({Fi2bafCsWk-mo-4^C#*3)UZ25YDhw2K8iyjgYSAQu!h5 zh@IGk7fkek>7xlQEzTAccIr+UhOj=;2~-e8&eGIkaNx3)=HCQXDlW&m6K0&s(|W9o zT0>w7&^fxI#sy3T;BCHX#ovbGp623(QWLI#ELfqlDDS}om*I=hgfMIq$ggOULf2~t zyCSa|le?o>QPK~AbN2IWuQzULMpTYQ<;yui#yJ}ZLP?>5G$eKhv$74WjlyvkA@!+u zaZA^VNYI99;v<-y7wK&ka?lWob@0S7Dih2oUiT+H26mQ@ z+im)IIT$Ynal5VbZt~k)zyTFFXN=_z@xbNr9UpkxIt%L&&y-GDZWqx^S`E>)i)gyF zXaGtoP=~JZY*cuYJR5U@SYU76H0fdf3JuVJJyWRFIc42SOY>KzaG=%p@mTB&^iNYX zA&Tf{-BSnLV+=NZaOECw%rR5^W(IAXZe^Q6@Ul^b# znbI+NDgz^cLPaqNFXD?JtIa(8D;DYkpKQfOHOhceM3^BfVZeITR=ME8++d9QHQWPlG>eD`pXqtXIB2dg~J@}^SfQmeGgG*FOw)?RO zJT5U8N085lWeaq&27F>0j(H6HuducJG#bIDRJ_2}^(FSH;*T25DTYB8$H*;l#Rp8q zRN6Xk6I0=@m=~mqlj3e`N0+!eAb{>qYZWT?Fh*Q~$Z#yvCT>BVRGP9B?B$dTFvb*^ zP_&{^YdEYI^uit13r)U72(f9(4Wg6%PMV^LuiG=T#}xuFWs@ZUoRi_Yh4=BiE~gGS zZS>vp)U0;{BC;t*z|M2tHTPKzoruP3`fwj-p8Pb`p$T*xg$5-37g92)QHsDc@<13# z?Y2O;9c`zPKxzhQ@koQw(YHB;rmo~i8<8J}B~}|uV+%5R`NpP36Hdjn^2->xUSv&S zHh?Cl{v;JmR{jI#EG7L^sd6+~xsF2!?G!XgQ}>9KA!~<(T06Fb6LEqX=tQu{z` zH?1-pns$aQ-At8f+G0b#X~?@fjN86R(a( z`ldJyXf-vhN7L>%EK84mi6|Tb^c$>g{^`{q-c~*{Kqq{v?GQK@ zRaU}10!vK>krQqUw4nnxk+Q6)9f4?mkB=%RaHGKUm#`ilE(0C*;eeY6dtpTFEM~Zq zro!PQ@$=M8=^ z;?Q8NkehK)1wyuzJ8r62hi?@4=07dI(O0XOz-DlNZa^ex`tP8`5L#3>AbkbnsO!SJ z)8tjD-V_l%HUc*AND$v`mgl%D+52{a4>LiYdz5(M*!>mT4RA3*t8Sh1A$`N?# zN%kI|BlnK~%dO;~(4VRR^ateuVOVY$kR(YXfDzKrJ9Jo;T(Mwb5NzBOMs+Dwby3yX zyo!mcHi?$t(5Y&dby1IXQPsoN1tdGbp#oKX2)kPK8dd#)s+yZZ3A>06v{srx9e{{y z2sT@TFPJebNHenHA^}gc{*KjQ?|ov6X5@>FICsnkLpUeJIl<%?ML?K=?51&Y08rsu z3#g35O@k&1-s~^LP>lc|z@1!70s5KIm;Gz+tINNGW^{Il>V2M@-DGFZRGP6{+c3C% zf2JO!nd4EN7N?n$y0PoFw?qvbw7y;B&P54aM}G<2j8FgV5;$J`7Oyi!X_-~|W-loT zu%O>|If^*@nHO2M6KPslVpE58vVYN_1LxtF3o}=n5p(db4q(anzKegtXc{zgw{@s9 z?-HloZ67MAl)eMhaey-s-O$Xx)6D;}cPzow1m8k&oB&~UkP)6*jV>Z>oXB%kMzBhW-E1;iiwsQSkA+!l7w;@v?v zRrd&w++SfMhUfdil9lpo2G~-kgXPLdo35~a0-}33Ofxx&!B=)_S0i0VL)G~%*#;Ws z830d>C{(i+xE31GpVQ8QBeV=SRvD+7>LfUg>uOBtjv*ey8F$A(jVZj4w&v=fi)w;F zA3sT)tS5}h6ax{1?1lpHbHF*X9PyXs@avR0C#M?6WUO@-^A5tmdO3s7Y5AHcKuEx< z1#nZ%vqDb~`hU7W6ct$Z(XvMazh}#CE1YKE05mITWk33cx4ZQiJqm)aZgdqn5d=g` z#wOPwBhymV)}D9kt-WLQk0yS4(|Pi%>u+={@l6_9KjZBB-8Cz&8;KN1QmFYZe200s z|E-B6XYtkCl4aF@{q6QC=X|_!_@aunPt2`-^|RldT>i=U1Lxd7H{WB=!l2solRHbZ zzOc+>gRL-Bo2^Cq>=5#p;6tglNMnC4ra9L&g;3^PJ4M&o4*brDUt6`#wexZ7dixeH zcxLtX6@v|G3N6f|+DmyL-MG1DmpB^ngCYC15Qy4H(7xiQ+`PcI@}2&A6SyP$DJlg_ zCBwd2h@UV~?Gt?HoG+&Rvwvvrnj(O@;7RMwhZOU~MzS^x*DBS14WTRyDJzq|ox+Lo z8hDh+IiXhEKtV!h=nhlQU^85}<;sWI#=UwdL%sF5U!L7m`$;e*4DI`c6r`IQ6{upb zL3Lqaz`E9%B3c+?epo+qKF}K+5%$U{_KJso zXXKK@YsFdQkn}){_tWuuX+i0OWsAz*EWdt2=7en%t0(?`(&dwmOzy1kPC|DnvR;-P zl2gi%hDe!GmXs|Gl}1RTq+DsVn)Nh#iUMYqtq>Jk?xXqN%u>?lpd9SCH-1@Uiz)T zgtxvV{aJcldQ*BwIwXB0eJ&lAj!7qFhnyvkkn?0@hcWRM*&}=93Gx)VN}eUpmCuyV zlFyYdgdPXwWirWEumhskkL2s+b@I(}3mAY7`F7CHo8|5DPI&P0Q*sV-x}4*jlbzMhdCtX7pYu}Za_6^d*#?~#&wrWDS6J@MDhW26XDA|mClf0 z)R|l?el|$+{s+k!H_bbQaF^!&9oEc4@;3_2dkx&1O7otK(!9sTcW55cGk*3(u>#vG z)4YA+E(qP^gJZ?{TiR3zEG-@FEiHQD17-Wg?=9W?Mnz`lvd{xN8^_+Iy!zT_yZ5yhKXOm=@-^38-F%jm IJzlE$|573)g8%>k literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin b/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin new file mode 100644 index 0000000000000000000000000000000000000000..78ea0add13f517c7ec7239bccf1811eafc1fcedb GIT binary patch literal 2664 zcma)7TWl0n7~ZopyE{t^mtHn%3AiJ!$Dw?Ox1cpPF`_jxTj82Ttw(a0!bIm`>&J>3iBC zKGhW47#V_iblHP_5Wk1`_n8ZMh!fIKbQGTyD{pK{k3n>rE300+V+@v#Vnv8;EcPqJ zEt8vdY+49$=lQD-LEPNjPrkm~icP1n()w2KIf&nxmWYrjyaMxK+Z!)0qrAe{x=pg98n%_DD49bxJQapc6F z%KABOlU$zN^Y1)Q5N2kWB)>6oaXMSIJR@7}XlxHm=kA_ldxD5R)D#* zM=9Sm1rA?=7%suaC6+!Cf$q4514}^OC15>BuiR~Nd|Egt3KCEfC;?|m!VGjv4|E&A zAQyFwX**r@dQAkTtTFLFJ20iE8JJ*|vb`a`&X+A);NmH~w(Ux&>jlRK%F3`nIn-(P zF1oHjGBT8cYZPpn^T}GKfF+cMa3A82GqufhN{I9myhN;%0_>{x`O8OU)MSn*(xEEY zNi(z)uj=M~{d@Z=tiS)!ocPV{WPSb5?6`i8ZWNn$0MW-$5#Q$}q^jO$;$Nmpa{-Ts zK}d+9>jHTt3*;L}OE9R%^E_FTn^i*H4NJRkQ3>@OSqXGh-0AjKlL&t>hv(_eTJhR|J1Dbi4xysstcL6|8T& z)(*ZT9x)5Hy|y3*B_1pmL>;rPsH2#qx}a%dyQu#d0+=G>%y;JD`PFSKaYi;^@7@Qt zT`$aBDT-{W&uXIN{ZdVH9tm|11)_I0* zVB?|1+Mv>cmF;rHzroUg)UxD(LH8hGNrKiM(T9Lz4ijRw)AyQNk56wMd3*SfJ|bY3 zzG%^}OIKgYonF2HGyaWcercNdqwWqy9)}MFqx#VBlpUm16J}BifCe7Q~KQmZYh;Oje?=`Q)QftcAFf0uDWJvTd<{V+E6QY4fC88o3 z^qOHatwR*rmq&&gH-fFLx&_!;NiG75EGP9=rZM^L%!X8ZQEKZ**Ox5P4obz)D9wr3 zM)U?4A!;mkh|*}sHaku2Uga?Kl`begTA1}Ifv`eN}0(vslpg}^BsrD5z z4Mt?mC3$EuDtcOpEbC6bfdLnie2DdG&lCH1&uzQw8rz^Nsfzm#V*uTgzg;md`rQiQ zEi4`J-y;tEOw-*(C#7GPfndCcdN&Ugw{^O^{!cWIO+~{!ceRcBazkP@4PpASw9iZP zjvk)Dy`*(CL*NFk8C(V&L&GDhZSLW+3^+k?44MU|w@Y_C16re0|Gd9r&-4A24KZz5 GY{7rUr4)ex literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin b/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin new file mode 100644 index 0000000000000000000000000000000000000000..d43b07e4d1815e15f39bb34510e77acc90ec8136 GIT binary patch literal 24314 zcmb_^33wA#_jji$$|@~QQc8gaC<3w-O3T_(N}-fB326riC37t(D6isB6d=X%0 zV~5WGx&UU*OC1LA3V^+yzMkG42r%3C_(44x(gWa-F<)N^uob{z34K@UN%k^;dBtC2 z4%q_0(bwKMT2BVm0W5r}W4fLUbOJ1@Tf7h;0XXsR@!#vofD-^`bU*3UlgsE3*2ntZ zswcYlDEPiIP*3{p0$7%NfB?(`IH$wE)AXe8hX5;nDa{3_0G!viV+z2j0Iz*%S9d+> zvl-x$de;zu(*Ry)?)(72_5g2v#=J&PE?q~#x2{z5r1#eVmuD~q4l>i?dv*Rs*7Xf@~@j(pH`Eh{%9r8n4fQta` zUilvO*g)Gp+wQ8F04W}xTe8chC;CkQpO-4Iij*$_zI=W9YJj}~?%VeV=&bz=fcxh? z`Guae+X3*s3H6`qNt=9t2eL+Z^rUqyz=N%}y{jh|eGBlj%a0cT{13om?ME&J*azUr zZm0g#lcf77c=i|wMt2b4nfA7;g4_KsKc@!&4I4f|7%xZYSeEPLRXJ316udkvg2 z@Z-M|1d~-LbeL>Pxm_rx`?iA~l=o-kh_si`@G1Py$^Q3;& zsFA;)emQB~)4z1tU%Bn&TfI|8EUNV^u5MWM)2^Zfn=vhJo3c=MPR01%-Pa%Jc=*e+ ztA2Rxsa{iWxv0mC4>opv|C=`T)>Y|#^yVD#{?)6t^*nU%zL&Cgzun=>4^C%3_PgoD zZ`F_YUjEU7FZ(3O;{D=p%`Ao_J*O=q=@qsJ;4A64D>U+X5oI73wdX@EC8H=?oz~Ze zmVEL1@*Q{2JvuQV`;|2(uG~NM$5R;(-TA}e7fjE*qwSq+vZ*cuX?2ztNvpY})jD6O zlk*HGG^9&5qf&;gbcdQd@4DuJ2Nx6{?|OxcEZ+In{3WmZZOgyyzOkls_o{`zZto4e z$Yjbsw(kw;F5p}#bE^E5z5B+LF4(fw{zLVl9y51V_k6rc`kYH1bkMeY;Gs7K(*<tn(f8Itv^y|Ux}W1k6MWw@-N?uqA)a$sXg{ni{Kf&JzQUUtV3^ zdt>WuYd`6}{oN&lUoxi_59zitx&8Yue)X(IIyELmvZ(?mb4nSVj$m?eKIb*p9e=FT zj@`~_nZodnza%F+?mPV$cWKIGdNy?H0vEF8&{}cP+Oo7({iZa|!4DCtHO?+E-87*DJZIP$X>5^_hrW zMh`yKN9MMIbO?xEpdptxlh#B10W+CByW9@CaSO$2m2--C$;9)GfgvdMfUtxtPnGlX zTT>Iy*Bn%rgtqQxg`)Go>Z*;u$eZ>&f7o(upB?$1WQ<+;%u8>4VaeF}!0eZcZV?(; zfV4iWNr%>7HW6{ZY#;a0bsrvnxNOPbhHL&?_~Ga+v$s|Z>{ejty0jrne2R&R_DXGxo-UN@Pv3OLSX z)U+oo7Eihjo)nzm$VRi6{)n_6w_^ux)om!93IlD4gcLZ8+F zQ)IHmXT&CeJT>6}^2=4Pq*{;ulZ`S~w@?$FblN_ke5%h$e>=~V6G&SZX}he7wB56o zw7qFH8?Tm3y1U$-r;-W&a=Qw8T~l2v?8z{?y&%S;8AhQmXuVn(fWM+eb*Y@&&CQcI zkBq75I3Y7#;$*8v_#vK*Lff?^=H#z1Kd_r}Byo8IwMPrWe=1n}g+ciL{%pGB#w}?jY?7n4Zsfy9)9lJY67Z8UMpO?lZd-p|wuXWn>tQ4s>!C z+9!FO`U9K4J0C8okZx))h@{pgtbSTp%Y4N*<=}7XIyvrhzj)mYzRaOPD)=xUz zPC6XfP)ACC#4;@ggO9NuMLFr#om^U~p) z%`uCKx^zR3x;bJl1-U}+-~;n93Kh-r$DCh%vVnAjPv9q)Jc}s{d;Dg$+Dis#s};4i z`XslNTvFt*s0<@&Xa#&ed0pm~!{Yj1id?8QpI^*>Cf0 zk5BD2=+nVpuNQ)mhmocH6^9!Qn)dk55)4b%kOp2?(s21oX$Tv#_Sq2SyvtXj? za8H1A>;{Ph^!1=TjDb`Kxugpykm{v;a>*NvwUvBD4R8)LzA0NSGd2 zMDolz4JniS5x-I)$t(D<6QG)n)C^6&oEJ>$N-8-O(1y=R{pFahqAuOm946H$yI6(! zl$_?nen`GpaEI&%muJqe=$YrME%_vQI(+`o2D^cDxRQ5TZ+!gQsP1AeYBWV(O(mQj zeRO9i%3l%0P|`~0%o}nqi+L#Ok_k2}J)f%1U|7wL&^RP;Os=9m-eDBzcWC{_5cPS=G*amy9z-4H$DFS%)#>Lso=hU*&bL{Bj&} zuhD*KDsvgllayjo{3;k$vO0h7_;kaKKi!;q*_&sUk20hMuE=Vi@O}3;zIl3B?Xmm6 zHfpAzWK!ss38ITrT(0Csf=@{!DepiOl9ZPP!Rz&Utdfm#8;nNy9ZV$)Iw8@+*#e## zFc|$-IV+jRr;bXV0PYI{=uahFf{SyJNxd)wm2|onW-Uibj#Ew0=`q5AHD&grUs1E6u~OFoSC%>_ z4GYBVWYlG~Rokad#~~R$#zqNAH6Z=0YW$(rO{5qQeV9xwUtL#SS5+G#ERs5zq+Sl& zWbKNzLh%YbR=XZQRSAQ*V8%S6~OGi4(cg8tUFUh zYMu$4Vh08@sO^xtBFc71y|LV04N9(}@`kk}skfEG)MAo^TrLyaNf z#Yi%^5(bqRDNR$TiO5Mpri%lyXulHuVi%ck3*AipZJ0{H!#Z(6Pnl$y!jT9oP(Tb zSQo*G#IT7Ob1u6C-@v$;r@B~$Z{dcs>#;H&3q1?g^l+Td|0(-WIU{koqyhf1sKUU32xe-t5O;;{=`M^ax7UCTe1MIw6XVOo z__WvUC6hS1hZ1&<2@Eo;3+9CDyG&fcx^k}Wf4Jh_ zYyaWvRNc)9GkvxE4cmS$oAln9Pm;fVdHxRxny~hm5N%8A=k`{!hl9&TSfDfF0Syho zFax4`QETjM;YnJB%SI-G;Dk)9y0Z}+@2LYzq(D8Aw8wcxtXfObHuwc@&DwQ7lD3(O z1WDjBR7bi3r=V*(qCSv>WsngD=syT5GrWW}STL?CY(W*&NM^chtY)N<_AhT%1g;K! zxvOgf{$!H&HSN$WWgy}}((a)hIMM~3TgedqGNN;(%psyX>?p!mh~r2;ub0b}%D4cx zo+D{50Gpl1DRMQ2sx}FkAh=dtB@PVZNhY03AWkyr9g6<)a=U}1T|uR`SyD*nVOVpP zH>89hQZyChrLv4MSMw31crLdV;5-K(1;eGC--`+)Q9g|mYD;Vk8a0`m83F|SM$-Gi z24vz&Xay~wJ1Bclc9htRzR)x^_%v3$G{gVFd8b!j=)A#N;C|3uSU46oDtMCqHA(+O z>oO}>$YcIgy~rgoVg8BM(aJlc!~(&cr;NV}{JsnDn}Udwkx zv>|#5N;Nu@9(l(;@y;Xj4wUxSZTaT9F`KvXuivqHtukflOuJ;*=WvPlL5MjEPp{WS zZ$|VLwWjc)k#rW8YCfpR?6Y&=DPyRHr;JfiUbbYU%C>879%1N=stZ9}#75eTB;#+M zWb6Yc2WJ_dfFqvQ&?Rs*T71fZ`@vc)h70>u6vHXeYSO50; z-aj>j30bo29PD!59F3;vDIht=E;#$e|+M;hy6aYVy9t&ZlfV%A>x2>4uiNzSGa*H zNLzvuv&o)nm@6E#olhm*dO`+*bYaR=L5ZnWpTWSCwBqA@W<0E#WyQ=oXety)w>pi+ zy4}+}jm6`|1e+43K-q{KppPfr+X)RoS(vQOokk+vuL%28=|(9n?r3GsrB8JJ{mj~R zAB_0mG`H!Wy*KynZ2R<<^&`IW*!P&OdSv2v5ybZAQ0v?nx`?_A5nGnq?VNdR{O?ge z##{v3HpL)fPO)ZH_Y)Cjl>#o!9GDY>* zNap1vvqJVF4h0HfE)0EU3l$ET%VQ2|aUeq)ggPXdf6|Ese>Xad5B|Gwd&h;f9e2Of(3bq-ym48V zyxjG7jB@5=eKMu0=1Q-4A4f9BU=5iS#5773vT6gNz5;Bj&VTkS>>sl&QI|4}8$x=p z9&T^0hvoHe9gcb=<|5Ps;#raMhl-Fd`*K6KA-adZcgKtsvAm%GsVM6zmG`@lMz+7Yx)Xw>l@3nuiY=I?7ab z&7x}--MEM>UUb`n`Hk%pgkrRUxg8IqoDHM15&7$w3w-o%4!_uHxZ>-ql0u! z-Dw0TOeCv>6eDUwxg*3(*$_;Pn;aE=Dn!^a)Qn`gn69JIvv`SA*=n-UAtJhsuz3ZO zLbBdvJ~|6nN3=3USjJf=HQkzZx_R9S5#75atUWKxfq*RUy_+Y!tHM~gu;(M~w=aN60DD2-0_3@$0Ahf@u`D)M(lkPFj`GUpp5ix zV8}oMgIwA{%5js)Gr`-JrXj*ZGatakr86%?WJTDbz{RB%yo+i@wq?#KKMfgOyXn;M z5z3Q?KK<&I8*ZI&a*2QcT?M(ze(IFo@1Do04~h@ua8AJJyWb(wXPbzR90R%ZEFYdz z+)@;qQAaNQ0jc|;Ii&0*K z*wF;P5jPq&%(*GP&y8Vp;Wxd&n5Xn{#|J{dv!p47sI{RV*Q z|4-p+{ki)`L&Ru@5wkHhuZiV^*vqq~7}#)65T!R-q&2u;?8YU0RcMU1d$HCv3y zjf^gf|I%c^Wj9ilk%hQ4vb2c9LS?snzGAkXI@beeI+6_7hTfivlHIbAI_!QYE!&LX z#U>!js3J1%MP9AeQ%43Yr5*O~#3L)_uAI7Y)iKD0ps-X_cYNIF$bf0QnP$%ijONAA zg3{wYNNecgA->G{-0dIDG5y@@tlzRn}wLb5}P!)P7G-`^dwC<_;X~7VkqU zQ^DY^c~OQI?tiA%f+~qQzvts#0-vvv{zv6t%)S55Kv6K}E?e_GG`Czp=5>Ywry^QV zHP{TY8jwo!_@Z;y+BNq!!C}M=jT%CDqxoheRphgF=fmAfH%GK<0%9L%Q#W!7wXhzv zeBS`XKP56C5S{Ns0gWZ#AeWskXGy&Q2!0|x5u!&bZ58vM6Jrpu` zqC|8Pk1>LLMM}1j)Qyxzo{)vCe4?9WE>KX?dZCyM5TTq0o(L<#78n{)%Gp2$T|?c`L8eGs=R84y zK@Q$U24$p7yNwbNQ3SDo@;vhzkN|K zA-7M-3!dB9if7&id(kb!rE}w_gAO(!jEEZ%iZnvnH1+H0)+nr&gr*%>DhiSa;=({v zc}PQ%LC1(zJ2JSBP>gaAVLozxelqAE_}@=sXQDJx#0)6NB38(1BJ58qL|Ac1b}4U0 z&Rr#gr;@?NWbiY!ZdM$kDt^|Xj|?sgjp%T*5)YP$@S?b5@RI1_4tJ=wgC>Kml121O zKIdmIubLGzkEl!8nvG1YJ6PKxg~>m%QL~ygG9j4VjwS?YQrV)4D2PC9g$YwY9tg&B zzEGG#vWpN-%kCLY_F>H~Hk??9;+wPT6vDr^ICgZ3cC)sak zc8ww-v(th?Y*F@_${LgAtd6gF!=+QBK@ur2$dJ*RMKxr+#_$bfh%=Ix;u$J2>^S6a zcz)`w1gQ9EGYT?4Ov_^G9jzVzSg59Pf!EB}{C_gJSs zb%ie&FkiIOI3bd7VqvJmpm>c5m`4`I({#ho$r?I_T0?cTDj7=T99i=zrtAxCbrcmq zkVIxAqJE1PyG@L71|uIvH4*JsK-i8^byI5zEu4v8Z5$B0;K*xq0NkFV18P1AiHtZ% z&ZLL}&=A6+1WU6F>Cf@#NNyQVaukxYQfA_V2@IM~&84~3+%(?oQJ~yel}4y%Dc4v_ zay}qAdr?YSg=8m6NlDIITG^XY!|Ff-tPXV8B`gVeVTGVVp$D}bVSVQ|x>*%88+{LI zKK(EqTT=5mY!R#Z9JZC#eBQ}cM~ju#)-)~itZ7o_>5VA!bX&EGgHZA2u%G__6mRAx zqIgpzIiJxAjNJB76&S<*DYtu3;jAT*bNgw?b-sM{k8eeiNG$AT;m%;av)8F^n>Qo2 zN#wPJk}Mh>ZAzbw4o^Ja>%4is0!z8V8!-M+2JWEieB6C~|l}hbxOzh`U0473Z^5SuGN({DgX;5MOSKh?*q?(ER*fqRRA9Qpm9F0lb2^ok0$#7ege?#rQSdWM`yD1boLzJIZtb~~iB?7EL zT|@&i{2o>atCHbcS$xgsJn`xsMt6r3g}<7sKOHRnJF@G@UN7t`==IPQgU)R1x$&w5 zoozytTilk&QVB8qVV3WR3$m)XVW$|X9hkt5ms{&^+YWz35?y zPj#p=$?uK;@P$t+smxABZqRTy^8VoWBf;-o>^rOru)SpLhH%C%zSd#o-XJyy!uKe> zp>Cny?F-d;Q$G$?DJxYQyNV}cufggRGOB`%THqt2vb9N!8WH?141P}ve&ciqC4f=0 zv~L=6gIg55`5*R;5&dM;?I`KhN-8*5Y(pZ2Vl%K{LU^5wdW>}tvtwiD@MP2v@gm)c z5j$3JJbK3prtoBRPoL^N&yK}OO(d2f!XHW91;f#&7;jdQ)SbVd%_=e%_5;JZWFGIj2WP9v7Z1rK!J{-jjK0&ekXWl|6ob|Lw<~ zO0h`)W5F?MK~l#6mExhwD^y&$jJ5IbsqDYK| zlHso}^h5SNd((s8R9~f*+~qve?b)_#Kh5g+*+*C3)U@C$rrv9G4Z;9f?j}`U@g|Vy zwMxJZtzB~)t61$?!9mnj;G7i7)_lpN;Q5xKC=n={&^(F?P!{E*b}CR*yXVByvRpF>rQ5P}_@m+|=e1}%FP7mTcpY-M>H6szj zw{Xxg$$>Z+D+W~KDlUgra+rJ$hWJ7h_%|ZHFfWYwIC+VrGBOeo+~#Pruub!b9}8Tx zU~Z)FZ6$6&PF%!~99M1+VIAn9<%dER#gVxNb0#BDFV7fRi8mvi!zwyVs>8k#h5BUN z?NH`$#!#3FIvqEkq6_7faXTp^BhKJpLQ`~+aU(Dj&RvV3XRX`c$jRdnSBcxL!%D{e zqc|@+y5i1$y~i%vRRoD9OM}OYq`COek0jD zj2g+|I4L!l5qT(jB^)ZvVP{iWD@UX0?ud&@8yVkL(hAGmRs>wNQ0w@|wZgLTLs?;& zObg3AEi5e4IgqA~yEoy|vhlT1rDbG1>c^U|EE~TZB%@W9d0Azd$|}p;oT75TlKyv; zmC>g~3y!s;E=`pbH#<4$aJe`dZbaE`X1bB%AR*z?grm#sod&=t?#^%auDjX0h_!|+ z(TE;sS+5msDjm1g(EZYKB;q?%TAKfUO69`(5KuUo{HuT1-C{p(Y>LkuP5BA z9htxp*+;3>?ADG<1aS0Dk~uahmjv12cGPjhQG7@v)bK*+p$kk4zmN%E`9t|O^ofH5 zsN>dtbw!@)WnCfYBzd`7n$Tc$fFksC7tU#-9E2_sKKrkgUlF z*^2P2CL>B@O-7VVreuMpV0*+&OgJa6`q(Lql0|4?@|iitajaG};18f&v`Q-%#j%DG z7;dT=t?-o4fSpe_;z*2@F}C&?N+?LlqsaUshT_1y5t*Ueoy+JwgkHMCU^^`C5Kotl z>xgwB-K1&3CfgG898PhBj*+-DTA@8DxY?bZEeYKeo9rbhSHOvA@oUS3#1xK3HSmu z0oH=_I?K>QrK33t=xK(%^pe;NyJ#_x(rq-&R{8*s7bF0qrF44p3QX((40++gm#T|C<&HXJpwbL!@Rb@oHjf?^Qu-PQ17b%)Umy-9Z7>WeJ%X?) zB^a6BhU}*#!zjimw)}*ijpp7b_l16f3jecV#($g9+~HePg=vYvbwY$be{O7K5 zJHu_70UV)Nvrvqaywtu8FVe+M2v0-Bac~3NM!(xYrrk<&zEky)Y2$O}eCZ+MX~jS| z2w++YzR9#iUW&hy3BjW&HYxz7e$PwJ&rVt&&G_>54U1mhzVOWO)eqP9-}-CiE1Qgc z|ClrFk6yce@j*a(TF|lEs-whE=59e-WUkOul5D{@uHa=ipqk2&`eDa}FEfIKY7L<- zl%EdTps1C{YR80a8xYO8@#G*=FNHnOKs~r=OIr4ff`__;jD9K}+)~nT*1dMNdoyGZ zz7;`6p>1zLNpp^lOi!XJFjyGpU?~aBUsB2RQkIMIM}-x`BWi&5LK2oC4=Z;mh0OSq zC)2-E$n?cX1JOEJoY_N>D5R@ssDpTzfjH^(y%3DTLa0-GXl@Att*$D-UIBtvfv}e! zyEM58oq<r>_$1Rma|LrwB8)~hc9=h$@slbd znbD2uE;3_2gg2RSGks^0Sj*nNkTh!Pk1<$?x`bvZ)HFjeEOS;j?2>fsNHA1|wMIKt ztFiH~$3K+&ayy)q_AP#BD z1sp|0;h-2?G!x9v3L21W?oB7w42{)?MEI1-bzjg*?TU zy2A>cKCe9>VzFf_8fcU$$P%bXn6O~TqKl?5QS!BLvf5LgmBIFrRt@D zSTAom!e?#;reS^0TnLXE%7mIBac~q?CU_A6nK>QKmfI1ijk{BRPgVS`nL0roNZg}m zi8fulc_s!+V4-AG^SQJP!pQ%}Js?)R5rA#_%>T7?)2(;&O&>bs3J>fLwL@U>j=2b$3J|<7!l~H} zO-XCGRO%H#tihhw!mMShsc(n_j^9-eyLmy)9hFPD-xgc?{gJ%j`kT{M)g<pII zPhPtF3!hHe1hIy|4Hd9^KjMhfe;ttn-4x1nxW=MjikkW0;NeSk6yfSrg64DwfODK_cot&rv>QL;rRO zuUFtv2#C$6K^C72&TaW8RD-L2vk1zKI1Y-}j1hha{SEfvgs%cBeEf8y3p>di{P3gk z7p$WT=AStCg87g53tBIWQewUFvO#RUvqrXjy|WO&hNG{!zk<${E1c-6BeSm245}9S z(Jq~e2+^#2qoXq^Au%OMiHOP=RCkg-&7d_?{XT`vI-nGhSw1>ELiV%1qO9joA?sAX zDv{Y2AsMHbMcVUO{N%t7z?jOOKnq8@OG)yi7|84*{OZE7-xM-Chc;C40=KBAW~2U* zj-!&GXR}?d;dxZfg7bzP-D9qyIx7olr*?=DxzIa^ZDc)Muhniupi7L)-)@D(g@~ zLgsV@@|_=j^W0xCqA%()C|#hM!Njxc9{&so=7D;K9Do2^N}ml(=x7{cf-R| zc7FNh`k%d-@BLuha>{bopO4@0Tt(f?K9Hv^NHYgK0VXbGOKnXRoMT!vfTKiGXdD_9 znDZBt30fU9Ir1osn>oM0e2#6zsDjoy6MGh!3j>?j2at-x8Ff?sxSWz3lYINfn;WOVEf^jAsW=wUH`jwtOV6 zaU{%fo?f%IF2KSP5tFVsKwl5$ciY%|!4R_dayFm#Mlcn~sQ8H|6<@2&8&S%N6ucwH zxpit+M+|18E`ys%2|yw9@Nxwj51ls<3zKlX1cuRv&);`b)Dtlm!44!i`efb)u-m*V zSoAPNi;8ny-7Z7SLs6HZ$QI~>zJZR+n^*pCoC*@%ee)MBx#EUdJv*6(-G2Dl&TW4$ sIsWQpi95EW*5|eQ`Ay*>fC~W@&-r8}z$$vDj_0PX+!>QaE` z0Ib`)^bo)a96WJR4ZyJg9k(Ai3UCy_rey~=0UQo+%@q$H1~?3$_t0P&;28j~tQpRk z%;4ZF_G17o09!gfw&jx43vk2GX+D6*0d9P>W+%Y!0k-cxG!5X_0F|a6p8@!HfZHCt zISb(50B*nQPZ)*tzW{f6U-%y2Ujg2BxN0oGw*lThJU1WU>j3Y4;OGwkUk3QV?dLFn zF97`A>UZ7(_%y&Lo}3SvNlya&XvnM$03QMPx9zzv0(=PIHzz*27T^N_k6u*A`MuX! z|KkHUYy)(cm=hYY+~K0(-|=E53fmE0T+fR|D01KD#V!;%(@76{!)$@M!$p_zTzvH7%gKj%ZVX~c4f8%FWZdql$ z{c$xQP-oMuR$HFB6f9NwYU8q?25o*jnlafg*;PeVBv-0>+W;49fH>RJpWe84z$yL| zJCm6OJy|X*#7}$8d6&$V*R5@!HcyM(*eY-Gw0O<^*#fjWk?=g%bE&h8I_4_~Pcxt5 z@cf&mbwS)}eJWXhLJLo&izT|sFR$bto=QQCB&0hD%enB6WL6hu{M;Hyqo4UPER z;WD1@;m;#4#&SrzI^5bHYQ0Ik{T+XMAP|0SJL#Z8lIN=Hf)R?=-O=5lu_~>nTSz-Rv|xa- z&C-pwF1wA%os!+ANp^=zt)YRp(!d}aQWtJ%Qys284_Q_>rLET+zd!?@VuR}hZj~J@ z;Elxt2Sme5^@jh)u?~)4Rk^~2+AL1oK4EAqhufq?4V&N&f?`z>h1V1|xaQ2H`TUrOm0m&7$ZHp8L` zYvyp(v0g4{${&tm+zN*)sO?ZGy-A_`dmY$P^B+Nd`rVYihtjX(vy>T`CEhX2e20w+ zu5h^KXIrUYHShC)LgRBe@CN{V=Sx2nptG^71p;W3vC2sq80q_zez>cP3SLEng7rG}zZ!i@gw3$X>Lxa~dY6Mzk3=L3Gn#0vi8F`&F@iUCxQr8&L{@z|&H&kFp z*N(1k=Iajg*uC?H;7(I3ws(tklWjAM>1LSHsxA~PtnFd;IyVdU5>+K{gc}`Vsgb=h zQDoc(?=4``U<^xawz^%F+oOp@J%{XSTvebUQgJuR)P8rRD8 z)ZFZClb3ts7EiNxU30x~3fesl(IV>m%o>t%9b(mga71qXsqGOq8V*iXkJ4%P)oOnD z09z!x)YT^TcGIUZ# zx9^StuJ-J0@7@!Shftl{UcxMPR_IRL5#{#p)foGC`eKx0)iEQYj)|!elXWivEbWhY z35nu}D{FTYPwcb}Jp2gL#-`YOy4S3`x7p=zV6Bw(j+3%nim4s9`~wl*gq#7sLb9$2 zM70=XY7wNYTcRS=BZDIEVb zA|JKJ#0`7}8+SjmW+rMv`i8#PlEYz9qVvzv;AHB1IghAf^wShsAz(h$YXn}WcrEy1 zryYQ`tJ~G0Cw_a;z0Y6q{X=_})c6=|fyM`+h{pPP{D_8ZDSp8O?1moN^de5~36H<$#+}_anyuX4UrM`d zTM*sAd16%vacrjWCQ*A8Cc~p+7ByiBY{YT*JtjqOd{r^4imxowUnsJnygU)aP~K=t zIS6s)O*nPpFBJb8p^laE4m&AtXM5?F%94~dd*52M^lFQA^;Yldj(zv#?myd8Q9Sdd zFFts(xjQcB9X2S#Sx<7hdled8&4GP>8vPtR%#-E*f&rUi52_k+D*?&QbAQlSv`;Yg zH{9gqw|Lqb;ls+@!8g)?AuD7~{hj{8iaS^u9?)ey{8}Mno3Gt8BQbVQ*iOuB9(>Ta z_~7oeSG=}*+kImX-}?Na!be^n`r#YLN8kUQ{M4t~J5Miv+wglnw<5$aQQ`z^-)QH@(B& z?N{YGe{Gjy@9vN^RkN#pDX0dKc2LA4^BKQ;5ocIw#MeAuo}gM3nABnoZ8&eGNA|93 zYi(@s$e!l)o+j^F5#$(ZVWp8vlOQtEL}WQNH^e0ocD_L5(Ikk-CL$|5o`#F!k0v~l z{Lx7e$ubd%vwEUdQTxSl zwl;d3#WJsN^0t~{cS8!N!(eup!9|j)utnKaa2aQ^;4ExJ&`4j zCJ+2_uXjbXxD1X#F;(*$6jhp#pXDcAs#gB8K=Vp!&=T$wWa>}Tc6rv z6CB$6XD@sl$rVp-OJcf)nx?DSD|6%B8om7SoWPpO39Ts_lVN1=RF>m6PCl<{@iwm% zWaP$Zz2iO>AIO-wNepC|X&^cg&xW<$=BOM)XdobRdlE#<7QWfrJY}u7wXv;nJvW<; z^^uHZcm<6elmrp;LGhYKY$IG?8-&cvGh+~;vEHzhtx;0eJM|T`@MO7^$KH_yZ?+gI zgR@vchXpV$JqaRa0rZjbiVg7uFm8iJ<61Q;`4epLOq_+OH0~i9cN?qfkh*DHH6+nSe!E! zuv8mM$wfmS6&`a!TS6SFRQQoQAXpqHq05445C!l0okCSN0^q}_VHO&n<`*NS@n?ii zC<|YLk345Stlxa$L`3Eyo5mL>p(y4xzhYh6x)v>_B4na=7H3Tx*^@J!WjeQFQxr+I^8% zaUp*$GBuYum5wx%-)W@@$?Sh-0bu`IPfd*t@^YNHH6TWBZS$zGD0)tI~EFqau|GUqrd^3mi6(QLAtr`adsxYL9tHb1Q!tH|iU1yVg0 zo+h7kUo}eu;G;>;##PFt^J&sCn)JabIp^wXI(tH&$x~?ZuzvfP&ZCy1G0(%91|n|W z@oRTH@iJf26D~fUfgzc1mXq(K$@ghAc@ItA+-d5^xiMj`)8Z}_RlfxT$6%tH=fx-C zN{v~+{WfIIClTMx((0p{qy{;$o`F=xVD=lv_k^_dyAyGds2_ohs zqlrjkb3GPPYuGuB5E1@g2cp^p?kkKjjYNcy&B$|@?kgDM5k%Uf{QHRh8IW;b0cROg zlNj$=r(z{C>hO4{bSFW?oT9^q=xMgnP^7P9AD_$ zv60#@5zT>Z8WcGvhZm{gXUpKs&4sgEHsqp7JZ-fp`@6HGCdjnH+!dTEx3tPPQ==!gW4| zOeKCpdm})W&iBozIh~MxI5JC@3i~<`i)P; z9b|GauvwbffqO~NhttRq&j=+mRJH&+Me+YQ*#fSiRE$gdIDE|KEVJ-v%b>29r5OX9 z+*=X~*L#XTwAN<`jj@=F6ttCQBxC>0wxhLiC9aOud)MQR`3hNfcxFkT$s@#{5l0bmzj15 z?aLhD;L@xSR5p}Kk5lO;Ds83GCMvyzN-v<&>aE*oDtvR5rk@Q=Uvo@Ux{^xWSTg~H zKNmV&Tfxe7epg~Tj-^q}Ef#0sM~7>NdIObiDc`b{imT9FR%$g#)~NJ5D*cQ~-=)&G zsPq*o-G}DIe|ETFO8X2t_JQMO{}x;nAK}T5(yxHZznP}Z;!GBQ!&3^=mhd+V{tlOk z$_6Rj!ETx{gl_lPc%>UQBAgUWxcr<1VDQu*(x45=xcDAwLhRIygw zOy}c64j+2_LZR|M@^G%=Fipv_0T;i=^EOXJ^o06~n0I zzZm$S!B(nx2~7Xd-9<~X94^TQ!qa)LH&Jr|zQVyfUVNyN!3FYEnl(kIG;7#ys`xRQ z5-#qWCiNl_yfoRL#ldTF09hY;3sgv$+t13AJc1j6-P3x068cB$9GBS9i&_HUd}01S&}@1WUt-l8kO zEihXHIFtI+>rB3ZZbn-%;PW|+=L{NyK%;Vkpz&@rjmo?*jbl`K259sd6XZ)0mX4ig zmj&h*q9|43MdfsZQaY!kaY~g7Vkki)^wCt-Q{{%Zl&Z{>o`|Bv)wpt(K`Db%ItEG{ zuIE}>j9J{HQst{k*I>7j!@oeQ{F3Kb%CSw_sPbJsmrW8g?14V22eEi8 zTFo%rRINmko93h#bTUC_&c%Wb%_-eYbIyv=Ws-cc$~w=Qfq*4sp_)r=mqa=RYCQ&v~Eb zd>dEv2hE~~+3cfEXM#{dX$HeNTiOhl%u_Eyjuza8X=&ToXSWy58Ea5a;I{t>WGQpkiG$=-1ydVGkID=@zLDXUCa`Y#McN`nwP_Ou>{jC6ZL?6p>dMQzZc~< zUyRGs@(OPY@}eGD$f3Qhag7H#nKeerx{svzgOP6W)v|Pcz5|wCb~2wr^PZ)72a);h z!HYg;KQwPJwg7x3BsPZxS)UxA^%l>S>%b-ad7XKkb&q^%=EIqyb1zLoiqmvfF4FH+ zgq)8US?a9l5>AQmo2#`lu>{sw}Vy-O=Y~bS~_*R15LymLpLOC_WYM5n<}Q zhxFlO+#9@8)qObU8{TKGt#n?y6RI)X7}O6=s`?iWQMn&WRi9GThgexRME9b_Vszm> zjE4!d7*1rO!>rJU$*&(68UKhzgtQ)`)rZ+ff#Rr+G0a4hZ{}QwaTOxML}WDy9!?;t zIq%~nbn$F`pf%z&EJg*x%BK(Xl*_r#iss9Ceh?D~MdP0d)BLTfeuhiuy(bp2?%^f4 zh>PNI8&SHjy6N2ZV}3&Rhh2nF3deUWGZWgPSgCrdlP3^Ke%<5^*;JSvAIp&xC5OS+ zMF+kgQ}qF7zvqLwymf!U&{tG_ujWpbsM>}d!o&uSz_5)}Kcnhz#K)|l`x>9@hSRhC zp-=wJi9pQ05U1iviPpW;_6EHgJ? zT**_|g(>Vp#S#$r@v!^Br&;hQd>WiEJ>E?V_S1p`-Biup7XIBXRTqjq&+j)QF*jZC zK?fCl&%Y=@mazsH_V5nv(d_=*+1%>9vu4x>pHDk~RldBpBbyd(aw3w#hrS4E+&du4 zo=&^13o#HPa1ycVA|XteNQ+*&BMU@U0QWLo$(Equ+t zd9#G~|1O|~ok*)tF+RTb_2^YW@syZG7}u>D!|`xTR#>Qp&wm>B`nBjBJ2I4}aHML;;KA!I2L5H6ch zYjA*>H8{Y`8XWM**5E*ZItK#G5d8(HGb2Eq83F3d2vBE6fR;!%oi9RvAM#f)U7!GDlhC<#&IN!%{8*+havvC$=(8+ zBKiD6HRos31?!#W3qPnBo`e}SAHo^ee1xOmUEazMlEG5_bioNEO5Q}Um_MSk*4Aync|0M2bFt`VKi=NZ zxOPSBrDJpCrAwqQW*@lw*e{!YTXx-(%T_=3#8>w|{Wr_!-|sv8)#}%uOKoWNHq}=T KNFO<%VvRuK zfbuE?}AfF=OULMw4)aH$yWRVLlGcV1hFlqU!}t#w5Y`*ywm* IkjDQ7077`P2mk;8 literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin new file mode 100644 index 0000000000000000000000000000000000000000..9f6425adc869b8c54592ef47a91218f123b3a652 GIT binary patch literal 170 zcmYdjNN@;B;7Z^Li)M&UkVp_okP3@V2n>q`k_-tx^=2GX7FsV{tjLyrLc>#cXYVOH zg|ai|rYjW|p9+Yz(B2c0zzBp3q?yGgghfvX01{>i3=QT$45VA4zSsg;b`1@p3Hjkb z=I3Z2@%P`Nl+1#(;s_-ng}__UfuEk(+zflP`C+etn$vD`siKe5&Uj5PTixtzXQD8FdeCWi^ADqm=e3kbYL_< zcufP%{hxdU+yuV#$K*-ic6)4;v%g^)+xM~x(-833^u{B=gAK2Ht{*4Jo`Ojr0xkn% zpIyrXZvY>9Vs;YvOCx|yzwrU)7eqk0_95`il;yXbvklHxM@i<&wWP(vKO`;55{t?p zrtAuZ5{0Bi@hP`pkjex(UfBK9qV5D|pS!RA8$7YPTXXJuF+YN{tA0F5?Nete_iKj- zE(b_0GK2YHejSe?9JxXh?ktmn$CYi7HpuDo9r>Ior^sB-Af;gBM}|j-A8*8V82yxD zYsl)kJTfdQZYqSKFrJv`5Z7Ar6?ka5-ZSR+EZm_%Si9>+q`m&)02Co6AmXdmz1myR zY`Nc#dWKB1RieiKwX3-=(V6ju*_rv)Hug|!U+7Nmn=5yIB-T1rQKQ@_woAaFjuBBV zFQp)t@4k6%Yfr|u1tCo`ZUa3{Lm2W$N1o4Q?Nf)<>|ExYiqh5e%xl@)$%X8^%56JK zW5Vmq+=6QJIW;%4pdKAjUlAed>pXL2Cg+P&T1cK}!ByTBFG8Z(#PxEl)!a}%xZTa6 ztvnxb?P}#%&8_vXyX*aK)g)GND<*}O-DQ))PQr65u{|mcxrUktnSK!Vss` zkVed;F^#%RN^2A{>AXg=sV6N*Yj&g%6KYrMza^dvBO2EHawe6R!Uy`e@@3tFE8my7 zvYE81I#+%t^&<0UYdXctOk357FjRCNxsRN{R^3>u>6Plr+A3`=`aU->RA`53E4ruq z8A)|YMhS2AA`VZo3Wc6N9wZ$&W+; literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin b/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin new file mode 100644 index 0000000000000000000000000000000000000000..5e729b9dea275fb0ec3d6a40d0e952d5d178d755 GIT binary patch literal 397 zcmYdjNN@;BU@;R&WUvd5H%)jT(~vA;oBUTKk)a^GAzAciPy>+J24sf(^$h?r*8`cy z^m^BW6+|aE1lCJT`B27y2Q&iBX9Oy2n8-ZgZ?s8+Xd**(czpcd=zv6q7NE6Z(F_pL zi7?Swi44EOKxR)66$R>6U<9#2+CM`S?t&;xaA*i@Xku&%N?>gasyEa#&@;f}j0A-y z#-Is-i44moPDo_b4U3K^-SG(ujY08Efei@?EsQ}xvK8pBR>nA>NlmScj6n$w_5bmM h2MO}cjAAW}j1vO_CINBSzlABq`8mnX3> literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin b/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin new file mode 100644 index 0000000000000000000000000000000000000000..62386fc02a5f583361177382db69005960d0d4fe GIT binary patch literal 1969 zcmb7FU5pb|6rQ`C{qaS1p*zM%vIBMnVnh*kLv~$h0xt5f$?a@ujbqHYv{S8VTGAHC z8j{XWw~!4aw_UsZB?b+V7$4L(coE}jf*SV02Qfa#KKS#Xi6$;8;!@6?p~GsLbiI?z zd~?n{zxRAIU_w~iVfHhrHx81ytW%JOdzthRz74_RdNYwPf3Ng0>2TakoXuUmiBP`> zgN$SmUfq5K5MDxf=l!`82*2}OdA9gIh$?H#KkE@Dn=1O1ehqzHM3sO+Cf!09U7n!0 zYYoEG%$g2_O4DH5Ge5k7yXH}~S00rRUXSZ;$`Fn~kEMZ1bcAL#z<(E@@bWkNF6iSu z^$lz(>MUK>7cTzwo4buk3o)G$!pM&?v6J7I0t$&M1hPUJHY27@Yz-c;^T9EB`pBDpOjyT~sKSi4YnX&tKg9QA9r7l@t9AxbL&46Vg)U5HR%ycb|4ICPpLXT_KxW#7`>lQ40uU_(W;naMx7UEX-* z>l=RUEr6x1uso)C4G($UVe+po5oXWU&QN}e)+wK*-s$7?+}`^0XbXqFXqD8^fN+qw zR8fwMX+Qdrq^hVQr3A5X?`Q7pE_Ngqm?>6{s!eJ zcRSjaMK-ditNK6Zc(XUhlPqQIW`*L2dYEMn8EP_T6tbI&YATJhoK^45aTam$>7il2 zpZ@{>nq$hvEQ4w~nu8zRX`FCLx2#@F@{{+*oe%vv@!`AkBX4e-{4!wQ eJTmw}&iU-;Uj+h#`!3p>_mEn>B{yOgeL16{W+rEoL5P1FH7x5-3DLLy08 zSrIZb$)>t0++@x6@1_1=A1(By3RT%tDi}|36QL1oq{~v%cS@5-w-SgSjl|lJEf0FhZ9!vMDF4r2=(hQ z%t#jD#qG}m!gC0(y*>Xj!f!lRo-O{r6IJ$>e+Lkzd=>pvzl6R{qe{Rqldd3~THa6b z)H;Oe*>wSgif^#(!SA2MQx{ORS00fNexA_Xlpz{}9$N#I=m@P^kpC_~;fXIM-qgo? z8n?5hsq)f0`oihIe{+v9X(6sNLKyiWE>7~66i`T9A&^zls1>su;%G2nYbDJ{O%`)m zL#25$X{h6dky6vSy!yyv^kE4Xs1DJ145QRI3pGTj3=0P1x`fDP4(e)9#=z z!^%4O1lb`r*FdT{yls1VQbgepA)t!8C{x3mnI$b?=DloR&%}U1<;OKJ>esKu@KgKl$LKUr4(hdn((+!Q3M&Q?jhr zYn0**NK=eRT!yC7Z(*vzI}#LSK%j|T@6|0998J*sM?@I{30+eG64qJpV>f!wh3Ql6 zqWUs%qoQ{jY=sDJrHQOrG+D-cjvdSxyVPVZTg)ZGNtV7-`c-6^3YAV>5q@0lX1GpHk_rbGxr( z2k&|MsrxqU)c%~Fz2zh0%SJs63s-mUjYf`fc=TRN*k2VQSbI~daiE$Y2;>qEy)_Gp#k9_ zaoc^`^TR=1nI}a+mn9&|Z?UB7ev4<6kyVS!hbI4FrIirx>TvXF0&T>}0KF3+a#RrCl zTMfMt-7v?Li&+NMDr;qY>CWJUOS*0MVv-*wW^7U>u^9)ahG-69p||4r#gZWER0$r8 zb|Szc43>#9Lx|{(&whMgSAy&NS@#C-TVoHcnj>4W!>s#WPc!E?b;V@dQ_xtAd-IFQ zK&9%sJLu`ku{s5{LSi+1=i$cj%J7L_dp%`7lP)~EX}$XH*MIGvfQ|3%`$~K9Z0Hwr fUs4Z+&fFT^_U%h!^)~{OsX{K3+#~h$N!$Me4y)&c literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin b/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin new file mode 100644 index 0000000000000000000000000000000000000000..ce6f13e0ef20de629d2662ea8e5cb3fb39652d72 GIT binary patch literal 9995 zcmbVS31Ab|*6t+fN()_*Y10OhZU`cqg(^ZzL7s{rO+u3(0Wz1c!+U^iErhaP!^J*!y4o}646K_vU#8Wf1eb$#hdlmOtwr(6fDBz$_L3H9(|`;guyUgo z(T{$ILmH?SDqErNOB#^0F-@-3sU~>E8iCU!l1;}S| zOP>YuYarWp`fVtXV}NYe=xP@rI|2FP(N>Ls3s8)Mcl&VjZ@p< zsU653w~n+0vN@1FPaO@B`OR%|yHJZ_`@mC6!NYc16!RC5)-s_bkRJfqd%|E~GNvPt z{TB3v&0?Z}9J>DASuKjb2;{$Pod*NC3dk`_csL?@Fpy)-2_I`wqsu_P^QCzKkXT}` z{f9S!YyspfxYB&|h*&qGj1oCwtg$w(Eho~z+&fUen0pwaB=biWvB#zt-DhDkYLTV~ zkY@&7&jwNhWO-zVw_&qGK>m?C)dXZeAaBlUQz0L5`*Ha!Em9qExbH-cNCavm@vL@8 z^^=1!Wio0#6^m)4@}h)2b|+F5A!9QBoX4T0ZgwY|$5iTRhKd(#3=|2%YvNPgX=iw5BZ$C$e3q$x-5(d zHQns$;IarVD;y@Dfsd3<^Lc22ix)&2c{TmM{A!*c()llzjV$^!<>cbhJ!#txL|r)Y zz_|9VY1i-KiEjoTAAI4NAQ!tl$cgk{*lRN)?PgbYQ%<8ZI6;lnI~_>9T|nxED0!N~ zWYxQx_M+flfRfkRok31_|C5JKGv|_A)(l2tWzt--@UAKySC=)9$+0M#fGnJqF$s5M zK69!TAx&dRVVYJ*(+njXw>w3YG}-P14p?Fh7p#Q;m>ic0?Nb<>A1phid28A7RZ~_XRFFD0Tg&&kS*Y0GDpqlW1 z!X{uK#^{LwK2X?Ahs%e;F2YkY$52V4OD{0$B!ixo7)V$4usQ2IDuj}bI#&CrFnjf* zLQmkMLJvIgC}j_u6NPk_qzti;PwZhiF2>}cNGb>K1TWKgttezXlU9KAv394&A{6v} z;IfENdsr0uwZjQNw}6UK=sE{e2^z)ZN{1Y%c73$5^<-IF=wZ zIqOmg>n6E7D@a(ol(054u_$Db-D!5QC}aVAGL>A64uuq9(v$_|JEYL=q%4AYI=o<# z(?|L-Sqc{fD9@RS&5TiBKnqTei$-DD4zu88sCjdXeehdTY-=-@RKrO?k6rM_EJs=(r4(uN zl}KZj7-;;uPUo*C0Sly;?f#daT*v|thRn}3nI8}iC0v*JMh(=NNdGR@5^B(pN0?g{ z@^XXL4l~P`icy26AWShb+_5{0yL^H)D+mdaWlNNPuaTj%8Yuq4#ZDHIw-QputkO+y~lI9{?A`H-!5)1Va zMY4|S_6x*OJRrCHIKRNo8d(RveEvCk}kxua3k7)T|MnJC6Y!Tu;p z0}cc@g##bR^At>{C@UpWf=@(IeLyG-c};8~B?_Wd)ajVuBrhe16vSGTR)8O{x|VuC z6JURcxu~CHm=<*c8B4*>qt0{0FWBM?l(JM=8fe^xD#^GFBZzTP!?-~79SFT&EgSoA zW@vWt4}vP}fuvox>#Mh;m>|jfW5OgOVpLaC z;c$dhr2O{FdrE~uF}+D3Ng`DFAVIC9w_K8h^P=tTb8!udJ~P-(r;oQB9Xo4l?<>>H z&wbUnZ0F#H8^k>>7Yi7$CM)?0(!`%#)63R$8u0M#d0XhQmXmM)IclM6vf>PM8#Ri# z34J!sgrw2Ul$D9As(VcKD`%MVxP0N-Uh@u7)irBvc861heoju{zQP#xBB5UK$6DV0#gI z!FIS8l+UeKdb$kh@cuEheM8pZ8!nE8%66t`N+NKF+L2V^9g)W98+kM}j*c;@lH zfBkZ!sY`_|`HdYTD_2GCPH}cP)v901j*vN73vA@W!7HM)Re4;)Sq>?$A`52^ngr6yAsXueP!Am}V8EOBRK zQ0kY!KMbL@I>GEgu}3gwTCT)j^%&OnMA}!SFiLtXVZEn;H$_WNnL-5A0;F9QkfA0j z85J5I8tnXEXcYBwm!*7X%kRJKMnre#?Msy<;!01?q!o`3cl+q_>R!FyJ2La?#m~pB z4oI%<*^f*usgba3{xGW(YcZz&<>J}VTdCldWa_jQZck81ho-%s^eFt643&pXURU) z&F*|!f|Vpo{IRxVj7hQ=9bm73nN)SJjbJcl!q{8lC?`OYc$%<6pr#JR&v7UzgMh~P z$qp3XA%l#(mdEU5T>9*RHsWP}@k&ruWL zR$op)ZGCO1AJiuNfD=p#!TIDVn1ME;?Xf z7mp`)FtGw)A^HNIOOGug(hp#aJYgH~zL(@&elF*=avqAzIeEbS#a`EZ>IDG)z#;?F zJ9!dLgh&gRR&r#3iD#jT6dWx-Q{1*Lg<#kturM%`iz=Lm^w*31^%VLKfu~p>Ni9n1 zuSz^nEAh<+_#bC&!)TyIgfc1cP?hly1*Y|V0PSDm42MfVi8kn-^w*)1B<3QVas;Hm zMMhFm5lZB65lS3gs|dj&!GaRIN@XZc!b=JMlzk2@e zl=X}HoqHvy&9@6~4gJ37wTh%w?_WLjmFdfa&_og}4C|!uttRKUVZ(~+HCrt?>m0%0 zw+xveHhiQJbug76sG+Su?q>36KL?rqY%9A4>w*4Ci(gKJoNpL{3?oG{S0O_bWEh8V z@`lzJw$7I|T~iN|aGT|=l?DK>HEbZu3ARUuT~ZdIIEodCJ7Yg&C^+xBDStgihZl9oSgLkae&GYiHE87RK+GR}sEn z?I8t6o;UHdboYX9UVJXSHySl2V|ugM?&RUOCW-! zH8giD3^5zS1i{P;?kS~9PD@&uO{)1_e*P$j49h|GKehwJN^XDcP z99;gH+t$yLF6{eo_}8Bgd-THW)$>}c{L}sIQo7l_zHi)1-FVXnqmqJ}yLhc?Qg*#H zzu+N4TqcgoqhNYLYBFR6-rYgluDl8+`$u)|Kf1N9QES~j+*9XNugH==)^c?^Lye4G za7r5SXv-W@vHiWawB)|xe|{~&66n$c;y!SUW|v>D)j}k7TzBWdh##mO+Y{b%mTVrq zX0K&<=RLhFMPvWEem1wT2ec62)5b#pOQ5WR9gbtJ8n*7bpD9=RJjr!8*FNHjUB1F} zF}_a2H=!^%sjt_E!AX^Hte2iA@N}^t^1`%2HAym<+>`#NffrWB$`Xl{5LhZ6jWPZo+Qk{vmHYzwh+i=`|eywo!WkkkyPgb@kY_ zxu(_Yd5o#hQovc4ODh%YfTI!dj}loQ_5*O&!qQ>auh+p!4K%$OTGi zhFN7wC(cud(x8L%K?4n`JY_ZnK8q7Sk5UF=D?=*wnRPlT=?W~+DCHdoJS`5_>EH${ zr8lrr)yl*wr99wSvhu8k{y_oc-;mT00^Ags5dgKML3~dWtZ=IZvp={>5|}|Xbdp+1 zbmC$d&`atjJO_rq_}>`#JS1)9|FXjnoYtsqPW zE~TQ%ujc!c5x(k1sSmMlB|bX7xGF~oaG&h)g!@>J%I9GVqvxsTvW4n-T9o#o!|Q>| z#x##Z;KgvxrRHhYr(skaqgExbyoyn&RZsm8$t%SSeBl|HIZLNwQQA(2nS+=B z!v0r15HD!!gZVH1RN8V~FY&)a)+No@a=h)QcT3;A-M{0&gX=4n%?_#u>Z$A5pQ>kl zefw(!`p}}cer|N?!sDW=dpD={oD`Crd!)orb}4*`wMbuF-+EPM*xaQZmo85Z8M?1o z_mPu@4*Dq}{z!QXiK zxu9i(hL0ICu1`v=sdwV2{o4o5n5mif^P+_p_U>BCmz-5S*Z0ijm$pXbMotbJG;Z`L M_scE6;#LYiqa;Jgnhf?jdo@T#3N zYnB$yIWv=_&?B9Z-{qFAz zG&yt5d*0=FpY{Jd@2GfOwYDqYnrc6dn;MD5{~nF4R?mbiv%B)*2kx$;Y1c%;@$QEA zeRMponw{&mnTDeleoMEm$!ZYjYYV;6qn!e!x=7Z(iaeJ@RO1@ut@ljT*W_7DtFEAF4|hgY zYn!FUSDEd9iZY?3F?kM?=OB6Zuc7*Rol(cOY?^zgw6zmBgl!lgE@! zLI0p?4#YdibHY?7La};vI%LqikDw2a`fae@unyqfaL9&5E_h;t*g67@M9XLS1-ts&r~)cXDF{)91PHg9q!t^vNlbG z){;)k7RywrY?XA{eT_5jNWHCRWhXp#qK3-;7}5P+RIM6wKHIQNxA&0|xk$-lEH2$@D{n}8FnF*`gvx%G3)9Gm zt+<(OQQ70g0c^VDMPAV8C>HIxx-*)H$MIrkw0qyqe|(>MCKzj1HOkknnqux&s!}?7 z*OGU(UbS~2O?v_)^)}PAKXgWI3O(2vEz-V(SIFzKNwbN;108Wcd5=cO`w{Yf($Rx!pnyjAVnfWd}sjs**`Zt*o_SQ1}{)B97Lh})m ztD2bz4C9W!Hb+aIGu3-bS?l~g_Ek&Ys%bT-I?62`?zJk=feuy3Sm~w7KZwN0*OG)x zVEW^$ruu2}*CXWHpP&UF?TpG|OauGj>m%RoHu>I>j?)HkBA&E{>Jx@$8x;?tksYw) z1tVZ}MpLRWh)=^I`~`0Wc;uOZ0~nIQd=`E(=3EefOc8@{806m6xYz!M$jF1`@YWfk!a5 zyHmwE=qZ7j)S@C891H6!-)zy+X^^nqSO!EWKNAUusr-TVjcg zE!N+os<9A`4Nyh7YAR4geStcEis!{CU1&m&G^V#*U_up_VM0{?Ma-q5YiurKQ^6D} zS}+BhDpKHvbRN7w6(7k8pD-81LrFuVfGUn9X~%cDr-3BxYQ}_w@9F{_S5JT%SQ1PH zI;@=KK-QN869KAtmMTt34^;7RMmjWlXu<2~Vfrkpc%p~8AY6kK?clXh#Y>qCwa&*K zbqCaFReUf?Z zlA`gKm}y!%4!lMSY>YPkAdTOJ34n)&)JUK1o;J_zj21F_iAJx?3tgiDjXy%;Z%E1P zhJ<@=X4cE|tj9aqW3m}JnYM*t(TlK>gXg>){#~$aCu>o~tDtPy$Y9c9whY zj1JI*_w>+&6*S>P`J4M>UsAkZZ|6$j#wGTV>*{+CN;T=VrB?G<2tZ`E29-CU?g<8zFX3q~ zWSpdJb-lti78)dzqltfuMB`8(6W z<#v~^(=s)?m!e19_BNEe0eV+nABkECn<}sE9Vp~A>Cn$QY`8FB!WhU~IorXE7Y8!| z$I4RWNvd@Ev$Pq88>{K;fPq9~(|4xsTBL zqm3aMRQYMV<%At8KM=->D}R&7Xs+cYU;z<4#-BGVumTHB)%YSSOx_tWsmjnoLsgAt zO26oCI#sRWy~V5iR*UKKM%DXARaK5IJxS9iQPsPs>g~cDP)E{hmO1ZKj~B?X=i%yX3tTY^vwa;|FG3-^$&p?-~&wRhXEfN4AUeF zOKUV+;3-aeBN8=f(i!-qMFZ&-$G(jw9qf#@*l7JchMVlSXz~IlH%Kjg{PAKTKo0vU zItz-#$faoV+DNo7PF25Q12B1uMVI!-)e7dSuxqOl;wHfTqRA8)H)hI&-IHMV1WoRv z$?*(rhK~PXL6_{- zOq0_)o@$qkb&`f^1Z%+Qhu*PFOR0nhdvJjX&_y4kdH*WC^5D9g3s2#q&lDZf_&2|mva)9cE{0Y8d0BR>xr<;NX+LPP>n2C;G^^6 zKFp1EGKMPmQgtx$7KZGw?2-`^B_mRGjXMt5`O9E5aEV7o=>GGzNAJ{u(pWfB!cK%3 zsd~F?k{iT!poeo}*bDH0TFgx7a)CT|gXrpfNe~@`DY(GP!f;gmbzvc+BvL$wn~Pok zrlia1u*tg1){@{>vwF=G&FVD)m(|z&px9WIG_F}A>!q5FIwq{a`u~8<5cU%TNHtvv ziQbC=*%)u-QhtA&rZq-j&8F2vfJ9JDhUUTb@MsNb8U+MjDfMs&jJ6?F*5iRogqBGa zc7xvmkr=A^MlT4+J_We2(7kzJa{y`}+pZe3%4ha;y_Qdl(eLZc_aBc9QQ(KrtW@(C zI5#@_JZ=rJ@Wn$kwK9z$2;Pm6qp8q>?DL$wF)yrl6!Y=EnDyOEQ6T!0MD0wCAdOGTQ+LNYF|P}Hr1|#FPT@BIr3azpoO1>br>0;+SY#U z4vP;clQ8mSWj>!Lr#u-i)ehlhX!=!GI8^(t!T>dY4_=aqV6@gxwY?E_n8^>}_Gt%o zT(o;dhi}uEF6TGx6o!8e?+>aG=rJf1g^(!Een5_Yq3iGVizgA2&I)Fgga0kZYuQzH z3VMoT2%`{&uAtf|8$}rIoY|rpYp8ApTgJM|^DJW+!7UbDJ5!s-+P{On;Rqx^{mUaV z4)`2{_>{*355q1q@^Hgx>d(%CR;CuAl|r~MbUZu|J~4Fs7HnOr5G%lcpuow9_NUWW zM%|4d6*Fee9<=(IzI6{^q|>1+v^Bz`x_dK-;8wK4zW1odSOK@3pl$s%ZoQ=ott zIM5Hb6S}4DiJqJY2L}=z$B)UBj~V%68NdJJjqy)Y;62HtSMt)fCP$y7$=H~t9UFkga2RaU4yX(A?@boXs^PZic3U_DVGF(@8K1C{RyGSg zFgZdkzp$wVwx&SFzk_V8mdOxk#yZfZs$nlPP=KI=5wJ5B8_t~q2{Bw`wkK@Jsg5hn8PJ zOa*7Xx7a)EFbHo0v0^Qhih;t*v2wsDEWnVg03I#}mVww-G*CcAj`ie@#i$O9(QV!H z!KyJMs$Zf&DuGuLM!$XqqV+0V!Q>f?-(G?x{tfzRo3wP3s8O6gW!Sh zIhGgWa{ww1KXi8&=m|N)|Ee)5B0g;*i+JFr^F+L7ppT}N^%bZdn?G=jYJR6>J@5=B zeCxCK{k>$uqYje+D68hfMWa~a2f$$nh*^ff(X@!`+yPWL$G}TB9ZmjfY~No6f%l#8kGe zq!nIt!;{h%&%G75#&QC_)zU{1B!%TT8)H8Ybhp&ub6POFs#Y`UaS~>Gsx6*x_c$Ia z7B$Uksz1Tn1^#oQ4Jcq^F69CA<*}h|ss1L&rE2h~hI#`~pI%Chm8gc-@)IB@?PuxW z%|#t7j`lG4t++yA9qrtDY)ixUE}Ow2#YpGeJg=!9n$eF@t6)@M%J8onZ8yTgNB!7` zD^0N)nPz!VHFA6afypFjI`kDy&#{alT>=af6o~`!`YaY{%To_TevR#caK+pFH2nc& zX!!LKAiue|(s-L zAc4W}M7;75BqfQ+&J3il!1U_rXt!_23<*;HPa0-jq%&PoCD9Fo0I>oY(J6^wRWS;(Z{y!FK~@ zqZxCT6S2@{KxKnROG8bJ+tGVY28tG z)a$3vU1KXA)GH2s1}hF7$BNSw+Kb%B`rhJ_k5gzH6c{f#LzjB6n$Q7|pt#lyuQl{8 zy;kApG+xhA=#v>xtsu(fzG&S{JpesRau2H1xryWwR*os_{$ zg$8CU#V#Beb?$z)=`?p2>=*JAGdhzpXx7lU(u`OUSDN`My8RH(0`3g7HD@ZUyhSs5 zOu5%v(BGdi)R8DEif1$=PWTgcd3$WmZZztSm+zE~O=ikbfy3Db<% z1P41WK@o$-bySm0GnYZpAgQJ!nwt!}m+cH3)wh<^n z%s`B0UcnkLAC47hCiG{XX5O0@^c!l{RwLjs&X6$8FoO$?|0Y?9nU7<9nu)9t%{=pF zWB(M)#4)=?4U=RKGKNk+G=x&_K53x1VNP)u8=r_!!}^k4JfU~7Vc+O3vOk0#4{B&o z$JB5d8-WR<(|Cv)KBjr(sG;L67dmddoTuCX7gn~rAtcHYPGQ6CNevu>8yZCCGynpM z<*4CF7dCGA9$;e$0I1Mb-Se8!foP`@_>*FBjO$Hnp*b@X+!yyKbFMu2)U=!rn zO+7U()39;F-JojY_BWww<2+Z%Gi)5A24q^pd8=UOsBvJ3@uJhAUafNj1!_#YTBk=a zK&H7jor{^nTx6=_a@#ce zt7&#SCJeI7uAo_ek&b%|4Y7mudwb=zW25w*T~nOa?5&X@n!T82x7?hS*ZN$7TQ{Hk z8rn_3baL`vK1Q>ac1C-U?412>M#5)b7yC34o|66r#_)P)^eD}~8UON7X0!Wfb_y6f zQmDvyAwM$6=(o$gte?&Xrya1Z%$PIBIV-4l2_XWa0+9dg)W?Zq%)q9LN+0jjDb(2& zH~VSUFC%nu<(u&EEZ84}D>hx+BxAvZa5hq|lZK1$j>5Z5X_&@~_Z3@mLR`-ZQs1-* zw2$RD;0HiH6=3DXUypwc=~AtHzyuVcmwpeN>QuX2 zBjW|Of(5$xmv%0!4ub|79&o`tAL0VQHT(%&a`B&wv*aYbAvaS7e9fkXJWmODN~b{= zYpLM8TnbFH>^~8noYRh)yzsAhRA8&{`>Nf9J2kNlpo@Vw2=|CFrKb0YWzCCGwG9t^ z113P6nj+Zh;^dJR8k4285pbyK0cyHCEl@dgtt17R@1Lo?NclzCTSah4dj%^-53aa2Rek8H|oH|UJ$+-ziZcY=k@0^{E=2|2{Y0fgb z^j(~@>0h;^ZTXfmyy&FnuCv0EZXT zycYra0x9P4I&$)g__lyU@}}C5Ei*g-e&pXu!e8We>cs48_oYTGS~1_$7+$ZIs%lcrU6Lhmw+AS z%X$Er`Y?9@8O|t#WM!aC3~GsWMz8i{ZcQZ0+$MP|&B^u!^D$DK7BpaI7a;MjkQJJM z#jDG8Bun#uXQ>hCHK!^oZFJQKttS!Og7J81{s=liS`wxQuFCxX(##kSrCBA;|1(Q7 z_H6!la3AS?n*U8O1xn4rKw!|EsX4)m8wTJRUhh8igPaLk2rZ#OG~L2#gH@s5;p8{} zKx4;ZF$XNd`qJ?v%Nt&Aou8bzbp}aI<3xI8rDhh6m^~x_&R&R0QkZ`xGb#`A2~a( z4VwVV7A=~PNE{Pj8N<<{MzfFYQ=N|AoDFp z<0oke@NHW1A@CVS`REwPyr{PbGT(S%ka-D+3r6wM;?J|rp+)y35^(zjWL^wi29P;f z1eq7VT?Aoq8^&7n6K>AL8by^C{aQ6?C>%ic{{mNDyfA`}8B=CJdGT(HwiwuzTX3e) z9`JVyEnb5^wCLePY78+ZjU~ru(YLVei~AVZ2DK2_F;biv!;)#y{cH)&dR9b{v2D3D zEgrUeGH|6zA!O7xP61I|2stGXGBUrML&K8cji*W=WWWvZpE&e88z*My_%=|Q7pa;H zXFqh(1GMB4X2&pu2(%Qo zq9tEC2Q6N7CHfc&_t>-um{mCCr$um>W6)U(A7LeM^K(natjPZ?Iaa9_2}psRXp+*~ z3e~#Mv4$!$>uBj$BFcw9yCdE2+j@z2EMo=qseA7`-*^FcOr22kC6RQ7X2vSmmw9c> zms$D=Q5|Dm#?pJ(%UC*eo|i#O??m(iiwWJruEtUnc}R9|#fBHI#UgpA;s|h`Or$^4 zr6VnSA4Ejms(hR&&86Z__olmFxE)2diT1A7IH|?Xl|##Bu%sd^S$d~~D7DI>eZ8PD z-b}QpTWe_9J9vJ})~Z``XY;)pNzk(Wcr8zxzRcXej1(~Iq^HgC=sU;|EUVI!U$&^! zvs!kC^m+8WHKWQLN>O9Amb#Ue0y5&YFFOJWTJ|l+b@46Q1PcWxViP-;alpF(sg^yd zb9Ah+yLaz<^~l%;f$MFp)KSCcM{vJlDI|Htyoj2qJi=+PJ*u(C3?_^uY!0$AX<+VI z1Y3>)pA~-r!0U(tIvc1ntpMDQ3SU~jFDFqRr?Yq>=zRI35u}Gu^11waN6pMj1p8*g zWCA_bfr16!7{Ek;%iUpk(8cXgX`tyfQV;G?tAbn>EJfimU2gJ_s3s3B|FKQ`4|XEx zKz-88(SaK>VC2AHPsfldi`^VYB0+g-Xa$^rfOWvhLvX{i{3^&!y=p{)$ODcF&~i8g z-EH}*bz`)HYL%(TxbRu6B>dIojQGf8al>SaHls?HF+p0PkpJSWI=XbhI)pQr3)}G` zl}bpMq!mC)xK3Kr*JKhlPvHIeCkIs2X?9xiuL)EOZCF^^Z>reuDBV^(A#}sgi?xT4 zFwB5b!6f9kNVpXv(q@!y%EQSQ%&!4kEH*Q1sA1Dr1jMh#9+==S)Zt)CgBi?e5Y$Z9 zQ1eZ^(ak9OLt&V_sZe2>FQAw-fXo^8(*~Jo#jTk1;-Fh~3Q|jPjvmm;!7-xdy`%f^ z43hM+CCJc0Mw_<-xpilE0H44UvW^tGsiPI`pjwfpdLLH7CNO7H^NXODl~JEd8dAJwC)uH$w_c>`htob?gPSpin2voe9anBR-iywMvNzp=VUB~G*&15;D-aUn z4dc(75fn*PX55txXOT1@!8rEMLTOOASGIyyp3pqX-2Ds+M~hTNl~$ToK@QLjEYg8^ zj8*}{*K}nDPk_Oj5ee!Y^{`7Omqn*ce{!9*v!Bqam?}#O+Gf+L_v@X5gPNeW!=S$! z8NDN=45?U^9i>%v5tdv1xd@II+^Q=vkvd*=w_7e5r&a%=3-)ug>ibzWlGP=VQV(g- zs-I<$LumUoxPewZYo>ar9RaPQrc}iMz!ad|S8u1)2L@<$EB*}9>gX-B`ePAVz0NvD zt5;?d>P4W1%jyqA!f?1(^{@q?)ttmVXWW*Pdfek@kINZrz-w?LSO2q6bw0oP zjUutuJQzvP>K~3(Ft33D)O!OlY)l}MG4lUIwYML3!cS{zzz947`i3LC#-ugZ(3-ia zp@J?`&(WIYI+D-RnplR`9E62p;-9mZv8rNuYEJKj^SRlMO{i zUOF;TZ%)PUL~TH#T^M1|u1u)t1_)?JYaVdQHR+ugt*HcYY`76PVBjLBy8kwF;RzXvu3xxm98lO0WAR3FW-^%C%~xto}SP)~|Tae^4UdUbibx0N4(7;KWg)o( ze?pbjYy08C9Th<}Y*@7Rt4V1=Yripo)&{Mu#}s7xh*4T<)pd)%TJd7$KTb&3pC=EGMPX-gJjyvQVf}#ALeH>K_M@GHQmsp7&EQv!4 zJhDmaegl4!btKs*VIOtfV-Z^SZCdwry}Wg&2awwYJ#%u>&BnVy^s0dH2vsatx$fMq zw@1f<08B2Y9tv~d{5yfv`K(88tR2n-KwbvJX;sM$HUA$pNbnrCJHPr9{O2`i7DvQBiW0VIljGWO!E_K6|_}7^fmUKi& zW6+RE?LZ)tvf+c^YpDYOgpr1KvEdd*GfYq17RAzi1T4e&KNDcX)mW9@)g*IY7XMIC zgb8@ks@fC8OQ^H-WXjMyqkKWU#0)$o<3aF3EmJ{LREfiac&j|pF>H(cb*&4vOmfdf zDNhRPk@;f&h_LDdG1~CBP{D#+m};@cB-DE`ga23Q*22vtHFeaIitx6qL@>>tjzmD} zaEyP+Z__MuY}0S2e02ewie;2+6b|#2!eOX>{GOE<^?59tHa;i}nlW^CMhiS`d=v#O zEFsuT?~9xaXP2y!kI%q?v&%fmGM|%>!&;ke!|=4}I-W!d;)zhiL_TU$EaF9)k#`$2 z!U+a5RZW|ga4SrfD~I6iRNCs+kdZ3$p->U89N?$4sSTMd)I4lz!sOAe+6rS0o3`-Q z;)ie1ruV@HB1I@gz*A|{pc|*FX1F*!{KhvTUU_fh8}57hO~zNXdPwlNRZ<=jT7K4;e)Bv$|6IX zUS_^&oo&awXpZ`5!MsVkMrqfL zQ-^@-n=ml?fJn&F0C>oQ1mpPdQE-e5^U{wT9P4U*nh}w_v`KOsC+W6FN2p{-_<&=D za#=))M?HoEUC=;b%qr*M_5E-9X_S6I$|@VAR7dI)Q`M2Ac2U6)Q{;hE;+Z(zJQege zL!*!3F%-3CJ;L;WW>uaN_CfLCc9|Od18wBtFo6*^{~%(PI!c@;65GD+v{T|Q(dLIx zD?@8F%Xc7n)@(wXpQd%EwQB%Ew1%hywpZMP_*)yV1Mk1dNI3PStJ`v^4jt2`F@`5A zh`*DJ=V{vjLho(;5mnt|YEfeUr^f<+GM8^l0{M%Yd0cT4DNI{#r!6OF%K$W$)OOP) zD0oQGs&%L&$WX@zIXv06H$s=qNYZ5ilijM{1^e0V|2BBk5I5_wV4uEtm@lver$cbU z@K9gAm+uOpk$%M`Qq=%?kZ9;PtYhx1kjh{(zZMJ(NoBJB4R60^RL^1>s2MNGb8l;o zgj00cE}ISjhXaVnsSNz;HF{0peax<7&jMhq#;O1Gv92So~rD z6uH8#qRLe@b`z+77n!$i$z0@RqutpKv}9H}d=HQ?EB}qv!U| z-#2t{N2|wp^t)$ly6g-Jsi1j#p{RQU)Cqhe%$X0Ni!nf3FS7dBY%UJ=xlg(10#AoS z{m9Frd@$kZx7rK115II@aLw#?WM6>B8_w-@v~?RyI=C5nz#bzELg>#jhXc~N3;{H4 ztHfbUPWsKOcE5XKYlgRRT7i=-vfsUs(_^wlaVZx_vCS$o`aOmgkTg<|dIvcPnU^Hw zHa@0I+mN@XtxwBCbn39jG=$QJKFL3_z{Nv@UW1Qj_z6MR zMhgZ|=z2-fyG+6cf~R34wtNzziO72k3aj~b_kFDEUufH1Sdb*7ghnzK)EBa3$aS2y z{fxGqLZkjsLT2SLRA@DAK@ps^(^)&4w*9dPx(|n72RR%Y4#jEv<}~m) zj~)Y|tV|f==ofWN!$bLL`{sy@F&c~1yEBsz0~Kw+yxavtTPE<2K~FAsEyk&CXaL%8 ze;s@a7G=A^fSin)WcVC1hXUsFj>bbs^vs4+a!S4)U&_LkatF@%VDVV&FgRJFcIz z^h_Qd1&4M#Q3Qu}Ede;R<9B1=(2iH#e7O8j_QJ?ELkpPDWHZBMT#lMMhy$FRAgCjOxUKKuVN@!KkdxsaGo-Z z1T!L8Q9|*o8^{6lrJesoJ3ohm_gp@Qyd7OxhSf)DCn~UEHFk2T2vZ%TLtwTOXSMva z^D7bB`D@zwbTXUO$Af_n=ocN@c`qc4cK&-(3Sl6o?g`;tb2tmLYwGz~7@XqYnWdc{ z(8-rw<#?aBz%2uV@g5^0?b;_Cg)}v5(}0_?$kDFrfI9OMau)46f#bKkKBDW0TA7H5 z1ePNd9W|2!Qui=t3rC zgzV_#)AQE)_!V^_H3d(vuMvWk?;&EHsy$99wEJsJnH`{^I}f`HnaY(TyPl= z;ptNxY{&;z9eX;Ms^aVKxyo^EAdA0=)@XGrU}Qh--4`(#D8}jepenDDw{bohhSi4} zC;*;1TJ>B#G!QTI#7q|i`b^_70bE@ zkr;V@14DosnZ48Whg$hCm0$I~$ge&Kog0T^hlc?fa3OZ58sU zY=p@ljLMVm^OMW}HPQpQN(2V79fep?(?}XCL&tN2cHx$w779z^arlF>RQ-iP9?zhiE95PwK$j!@!a;!J zT;*)@*Kk~Z6RKq;CxDY{Tx-7LcR=V6y@iaExbBOZ!kqF?xL`dVvn(1chu)Op3q8%FXtNZHbn-$}DEbXx|`S5N(2f zFYIG9yj33qj*XpQAp%!c z&xH0vRGq;*N}%LMGR++ThES467)ilp3?mGJ-!9Kl%Vv9YAyvk3(&^aHd0tTm?Y|2v z&4&*|JB^G3zlPNa%0F9!dI;47KduQppe6taMsULv=C}YD9SZ68OP#6CQ)W{V^V9y* zpnEu+$3Lx03j=lz$i9_-i|cRW+B9n0BI^&Au0Q<$Vf|sOe{4bF3oIy%1#zZH7@tGD z(Qh_GE=X?j?|6vX^6-^VCHXq6(`co+SOjTBZTBbTOJvwa$k|We4W`B$Tujq#_avh- z@*PsrR8o;hSzcr#7sqv!Fv5Dos#9rvX%=z?+|Ci~OuGo9V_}9#Jex}Gm$7Y*ha76( zfP!JnlS@yefAPcQ$w9}8c}t%GM8aHgUWt*-7=ROx8VM%q3)JJQJJ-t+`4sS9ua zb4GtR+?d~nyx{LC9gjaSC1?#`yxe z;s>A?H*s(C;k^vaBZ z3voK|2{>MSyj<7BXgpcIe@BRz0pq#n+DD5AZ;PSSkrj-V2QcaB3!7`3Iwz@Se5Xu& z6r{K4z+W}&o&xwYh8(#ly?n=j#mfSpGbadk&)m+@q|Asxiq3l?XZdnS*O;ChPAUs$ zra*wslPCw2i+4xhf>Z=^Nip~-*WgRTJmTO32KXKdw+ZMm9a0x?B4RNr+zz@(>x~@X0er2B8SXS5Wg)^5WuH!6HMQLr9Fhq zVLA4b6$*=`W0Xm?pR5|&03uijx$)~B{&gk@*#8WW4@}7I`ZpyC>MeCGD*51KXgK$5 zFiun6Pmz9EX%dMH2{~}sGjcaYKBpN%!VSP!FbFt~fEd}5uMdN#D$i4}-Uq({@GJ62 z68wl*B>g64rjRLUjUVq3VCW!1D|8XZaa1~}ztRE`H5Wf=^P@{xZ*os1aXB#^+^Y}6 zi6G!RvR-F}=VoAU?#GnmD=pF>FyI!~dSwH2@Y-aeLvoYWf#TO=@xDttd@&du%-|a& z5SQUGvO$(w?%GLsmi)D29^Qs@yR6s9-OkD>P6xd(Iq-rbuR@mS;KTY`xNM4iix7YLUmK~)un%_-_rby3n+8~ebPXncKqz9CSvnx-spmEn^(D=}@ z48F$^G|thXOL1nM#Xk?aqE$TPlC`Tm5-kkm3%Puj-KKa52M!ORV4GDmeuThu=rkSr z;n@TpphI`}sYW2quj94TFanUu6LKjT?vpp#eL`M3^lduyZvb>Q;F}^j)0OVmU%#=V zJC&6i34ApNU=AT=JgAm)(2kCV#Z~9%y_A>-VHLYV@8sac*5al*bi z$7;z%e5lJ0H_^f^q7Kh_P~*)BM!+PIvu~odk8=fCG#izzDZH z7W(Upf!4aRu0UP+q^{=g`Uzg6t~-Q`w*F!}xz6zS3wC{-zviS1^QNxvq2`&tj4LLF ztLv-Sp)krosO#le9_PVi@vQfaxQ^FxMzQO-xGYlhKv8@PBAhQMjD+ZXgcD_mu6?R< z)H?xe4e;9b`P4P;vuj45;cI++qX}#ojMWx-PeY4vFa}f*&JSmGlf|qqJQqv5VcZll zJ&02nT*493YF8gtk#~U$=oB0TTQtR(|0vI~H-VCic09di^5b7Q6>ZC1{GC(3h*-Q}=hx`QziSH~)I&&t9KY`&yN~qIT%I ip5_0L{q3cn{?Mb>4_tNd_!Wt#zO&`y!GY*kZ~4C@V#?tF literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin b/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin new file mode 100644 index 0000000000000000000000000000000000000000..51aee095916cf106a36b356020b0cfb4b4f850c2 GIT binary patch literal 5365 zcmb_g4R93I9lw{meB9-d+*dYr66FR(=r9f8BUq@hS3;0!Bi%diV_*aOo-w9W#0i0l z;CQ=xyNQC1ySWHf3<+RWw15;*8SIFr6I%_Fp=D}XIt>LW(y2wEtw<-N|9y7{cVQ1g zhMjEQf8WRd`~TkW9Tu=JFiR*UrjiKH4|6QG%ytmdsR&<qd!QuN@Cow%05gPxx zZuTA^8-659FO|C*BK_sv?|j88LlDavH;&i6bbFAT%3Wh--D2Bj(v*4*UGABL7t%<6d#n}dck8Q==cKnQA}toOl}r6Jk%sNUrUK_vfgi7uN4Eqaci4VQ;( zJE$Tml}ONJ{Y&r*5|RQqR}4gFR9011nX*6FE1`huhn1R2+{==p|3Ufhg)ch?9E*Y= zHO%qXv;rKIGm%=MJE*7-)}d=Hz&Y0(&E~S15VV~A5%6s^_t_WAvs-2|fln+b8H8aD z=Lp6EV zt$j^eT3@&SWTkDW`SjL4l~;GLEV!>$a+VTv3)TJDiKllN2}<>i(mgLIIbiKBy7u?K zA#bMU8MUL<+JgcI#cKIpgvWMb?!!nX?n_}#42lk7{$m7Q;&Fn08sv;u)w~F7)Yym9 zeZnXXVwn;Nu0ZJmRf}<2cg9(G!W=6Q%S@4Y?g?`m%M$aipo_)1#$jMOU=C!C)Jo0G&gE99bl-r z%#b`h9&f^illO>POFXN>TnrLF?-k0$`Nd}|jZ{hXWvaxJyn`g~t+qCzZ<4Z1ils28 zva+G7jA-2LA^8)j?9WOM?oP=uYBOc)`C!Pf{rY>2etwjxS_s<|HAM0^WX%?cq@j%K zCrq235cx;0N(dI}lNMqAnM4taPEwGt|0WlqXeL(HxCkXE!h+4?Nt^t!7GVJtVU_?f zSzJ0e=bf|f?Vfs6diC`RtJF07_FH#5PM&gacy9Z?=X)v-l#Zzet@E#TIqZ2EB`87( zS~pSiZ$b%546&XZr!NgXA>Tj(7f6u6wjXB04cYVedd`mN`J3iUV*5F9JOhV^Z5wfl zVI8wvMnSg#3c9bUnbZXrdhc&)S<|$#v1wJHsd;(p>Q#>?D;aw=fI*^Ph@n^jBUmxr zsK(R!R60Mpv9-5v%e$9q{FVLnUoY-|{PynkWm`%ve!TP5rGcq)d?jKG1)|EIW89H} zyKWoa_f77~C37FB+v71^w4eBV?Y0+wwq((P4@DU!{dVi{>%l|k?CXZe6luuH{%5DZ z@kw+3;ZN$Dr+s_l#y*Te;sOlFE>MMgKv7NA0x{6otZJYzJ|rPIAo$f7@r88T?pa&9)5+nh?OqB`R4yvmi;CBsqx#aP0Z=^eq4zvt4 zjEz12h`lc>$jqL5rw&&LKdyMG?^Dy(`jY)KzC1D5R((hBjJXfrrS@JZJl6oJ2Y>YZ zgwjobx}pWN#Kr~ciX^)B20>k60@M{d0Mr$dqAeMquIP;jDSBf}psr|m9H6ea;0mZK zYNw#iVjQg`sLL9LnI0%vYXAC+KkB|Zjjr@$p07Oqf#e~@zotuX>}cjm@h5QWQQC<| zfgPjxs75@$)PVsEoWefrZF?#?@~_Jyih_M2pyd)v1YYV`$YoTGFH`_%jgH>?mqu2$ zMqXxb9Xc~@!B5J)Jv#0$Sw0S31w6vwa!)D1_YyI}($5M{DF>hLj)R@PDe{7j@+Bn5 zfemT^kH}1iggT%KF&2>mJ%Wg2Xpo9~5ccZX?iJ0dz6&TzF6x>%tdSa?zo$mO`Li%S z+WK_hsnf@iADm=Z%pyY^;y4W1yh+C?@W4i&pC$7I;@B0@Clmy0^)uD+UPPbIXW3Wc zV>s9}36NO~u731}4f}7#!QH9Qd%uYEdsLwigmVN*Ayt9vwdPl!XEN_jIdKNOUKT}b z-g)J_^ByyQdF=GTE$_duZj!%c{jAg7GxzT`Jv*W2)&pu>k4^{!wgF%WcZY%y*ksLW zv~xQ(+LkcdxtAJ^;Yw#1fSYW!T?lq6NDT4td&D)Z9$Nm;?^<#zYJ&e<%-orGzbF0+ zkEJI^o)$KBJ=yT@*FJ*c3h5X+VX_TO<{@civ#XT2-)L^`voqMW-qVPY_YNo467E7BXkK z%V=-At|CIP%sqv6bZ(As0^X>TW-2J)iz&JS?tAGlakDY1KqvObArK+!Cw6e2`jHF2|TWvvAMiFaco`M_F(Iy ND;jG}1-F@O{|822WGw&y literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin b/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin new file mode 100644 index 0000000000000000000000000000000000000000..ff7f4b086a2219cf49af69140db24f0978d0273f GIT binary patch literal 1969 zcmb7FU2NM_6!vZ0AD)(OsS#qLW-E*_F@CmI)4D=Lr%rvCbmOJTgeP?FVh4hv1SQ#^ z2oc*!GgL8josw?dUIs#�#(Eg(1d6L0TVp;O~L;VXy~~m_$KrqYLNSi&s#jlxxZU ze9k?;_k1>35Y={D1564hL9$kL3i3#pNuT1|Ff4DjQibX@rJqU1lUC|Xe(?{4`dt`d zB!_Tu*K2_ABEmZ#&%cB4N8goii|>!1%HIC>W`ssdMZeaspsx$45-`G~n+W5p2Py8_ zfG|C~p$nnXGI)C5PcPxF%cwdak4gx?P3m6C5RE~ft$|8(gq9oPzY9=&@w>?n^@+a5 z!)zs9S@}d?y71QxZyS@A5;`M`h0v`5(`v^Xgr2dT+VtLB2<=zLJ3_$WHa*S2*|7#qcHiT2xY}G z&0x)+P()mtGW9U@-0Ur%}e@^+`qzCeVP zb@BZgb~dP_4ZxntHgPcbprM=4Q)+QlmUSzc0H_HEHsv+PmPK)1QNQY0wkid(3f8HzRT0++5`CWHNAmocqoS{qFx@D>0t zgv%;nT`QsrE8eML5@vlrpTauiZGu;w45X%lok0s-n9Q!zgiqm#2>O)Ek6wK4W^QoD zD=$B}X^-~j^z40Km_Ib?5m>st=RkDmG)K;gF+s|{uX`t9;abCnnrJhVuX|nIa_O6^ zLG5jTt*x;*(vOMBJhEPKpUjl5aRZ7Zqi49;>+y*tM_#HDA3M}mI- z2mEV}DHpR0s#Vb{_|cug372%+4r7v^CueL@A+Z?;r-o<_VLj&)_{WkU>eL8sjCLZx zG7MITGDC>yPK*8cy{?8f4zS)${=dc^UNc9wVn5DrpBedereY~rr75a literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin b/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin new file mode 100644 index 0000000000000000000000000000000000000000..d23f1cd60327c9040f416130bc3c6e73e1ddcdc8 GIT binary patch literal 5009 zcmcIoeQX=$8TZ-FN9jjm=kC(dYJC^7Ax)}Aamz}JI+L(6Cc&Jm;~Trey>IO!&6@gB z+u7Q#lkYvBgGO6+XRkw`2?F7xOla&=6QF^rf`CHNCNzzqZH)*FG}!)VHX*{&?76dJ zpA)xqITS z`G)rfSQ2<1;Py`++XFBPFgn(MnkDTY*>L982*6(gJQ!K~I6wwq%6OM&$?87?Jhb|Y z8o(65!_P+UW67!^fOP2MivYa>4 zF+ux9?2iss-{fUV1>B60374>zLs8t46Q}{#RzoQ2CW`8Pqf{swjAdGasWSz$AYe?L zTdb9@W9F1(C)NoCqov2PH6#nzhmnA1aacxCo+HgSiZbosNYkXKRs$^|8X!&ig^#nI z%m1c%jpH=ZloTc6Pl-~bHVG7lHO{2OKOjmR@vmsy!zSLOoMVCk^TemwP8h~=r8*ZN zzTM&_Qd5l|?DvlU^NwKWyGPi^_pZ3tcw!{4{p8~x^sZ`oskghZ<%5A2PV$y+ z@txS;-;102A(^n20u;QA`dwyVzC4Vzz*x^E##%2mX5w(4r3)D8jQuhEeb^&qZ~N+Z z4_1R-h`?I_`vu%B&qx$*Z1c_vo0QQkClx*I#5XSHi1*tu2`9iyw)M>6v4y6pPoPE- z_Co}i!`*Pn-qI8K`gSxjoFEwmWmFZVRW(_C--B<0w`L?Wk|*Bb#=Ri77c!JmNaAqW zTLNYF4W`lFAvM0g>?MMmqP+p)-4v4+rrur_XZ{-T-*1|xj%qDcIIF-b>TOwy^hKn;IoG(h~Hh!ngO z8=o)lo^N~~Ne+~&Xlxrqc zv0DOV>kX1-dOj)I_oVql68s33qj`#S?1)LcRzo!N96Ps|i2`ph{dMihQ9irv_xq1O z)%B-`UOwIZ%(>O?yg9w`r~g7Pyl=gAX73-Bcdqux+PJ68_~9CFc0lufbKQru6rDJ6 z_g1s6W1ZIuKD$rV9W_bIo8|cdr_}b16_1LPvSh_BQR7JK2ckCj25@0^UO4k_Jv7Rj z{n-cGzI^(KeDiO2O`ZMqfm`o+@X4t!yw#~3-FfQ0^A}ExPreTwvM)yk+2O*6spG~b zHzyEqgPBDg>5%j#dNP3Sn3AjPmVeN%c@K>JVPF4IKXddRb-(fCQ|!+^uWZ}=rL%uO z|9sL}i$*s=9TH6;Ahjb(N_ADtGB?3z+?yb!W=LjGO#(@yG&!JDcf>NSudA`HWCl}8 z0xjHX?k%=-iG=DFpS@wAOMz0FDwTZ$2B9_7eA z+3wI48E4BkTgK%}GVX^Z8Rs%{(mcs)qe3xXQgu0|Xcj@$mDQbF)%{O3b(@NyGZQqN zQqoE?v#_S-_X<70kt_ZhYdF1i*9$nTCg+VTSGaG1_FPP4ZsM0w7)&%&H+G%(k=47z z8ai>MuL5}>a5)-U^gW&LlHo4=jyxar)+-#vQ4Sa(bIzOM1NpPu~H zT6KRyoN(AB8#w;<6BWmGfGmXO6kmf!5(MkiaK5LPlkae!jJ;6}GaD?-=zJl^k+x4n z2_xEWu%zvEQOkqI%rnJ&5$L^bL zj&sAV>jd72!{E~xwY>{{nnf|Xn-NAwnLFjYKFTlx!&An`z&UFv()-4_g}`1J_{xf8 z!{Xi3!BbaFT=-3V!;9;8oYIelK6{o10@EYswvRve%{L^PYbR~Di;)P0p0oHw$(pZ# zrbD3pAemM)m;b&Uqs5q(Q6O!fi%D76^y)zmpBEw=hnv>xwnHU5H2cWtNElk#(?Y8ZTYE z1|t>mYPa9Z3f17zl2C>J3)pIu;;^--zATm#t}jio;@O-nCiTkk91iB#e@S7jJGudO zrdBPtx(HM>95ZE~8I$VP2Q=1@)1G1%A4v=j-7W8J^w;$352D-MgF9Ix4r|nMgDs;zFuWIe`)%QD?@x9m+xMX72W5s$xMurAat6B}#HFVL z)cyAgs-}71dYoX6zYIWVOg3x?8Kh^a8*a6_R38r|n znh0M(bIH0>j{wySXl6EV8VAkx{DPTJui6Gwe8*YG$5UwjOVvD)iSQZ`UY&wNB)Tf4 z5p+7G;YOJm3Qi#2(w!jtSo5epEl>qwoV1dlGH>YD&9KQzW4>dnFk9|EOdtW#tvpm6w0=oX?(aV=yp#Ws}g#YfH!*X_Rc zH;+DF_SM!u-1x#1uUz%_rg=YO<3^`;O#JB2PnwEpBy6g{n2wXetYl zko(b)A!bdKWm%=YFqofYA?ApVfgI*2n(O!y>mU{h&b7Z@P_RgMdU{l;|8&9)7s*vm zU;ozKOO~WpPJMUj%-L7gp8s(D>$mKqU}2V^a@K;w4wBFwBB5)0wjD`A4;~EkmN1Zv z8v!!T0Hho$_DhZ-_DUj1uQ^%faus7^fW(N^kl@2AJS6%OSHH}3s^~Zo07O#+9t#c| z{7f}Cz)A3*9OHmSK8^(s_C+rV1o6fgMl8q-5_~~rk|r?;3mTP;XblNvRT3I+QUiJ< zGzL0jNL8H6&o@Le2>_-o%b%VG)6)h`V*%N=KRE{`=M0`qpiIV}?1IUz+$1vsU_s!G z8$C5TOi?gGBnZwcIgD#WAfZQc&}4aR4%JdEsakJ)uLNdE$l@G8#e%S1bw7BcspoQS&Uk11A*RXe1n0 z(kyO|QBSE;G8xkVYlOGJrdzyCfp22~4uFLsdz)Y&4l_o=harMgU6s-bZsi59m4=8D z5V(3o+z1L+m_)*-GiK5xrOQ(q?6qArk^mPDkqrDbI)HymHk#ZFlC$s>vl|ZfKzBY= z<{dQO&%gVqIN;g?CQ!Wwk5jSTS#Z?EYeA?Zf$Mp zz_U12iY)GG?YOXOQCsJf%Py9dEK0XFdvw>fwRd%Dx8fE~H9oPZt)sJ*v`iRjYeB#k z-}sS2Dmulp7C@wgTApJ$y^;&wNJ<xu5!iPG-<=>k)`rSK`|i%*-XI=2D0Ea z%RnZ)S_~fFv4u#<9UR4zJ8Iv?>(Bjs`&|pJzN_!A?PLCtX=?c(NJh_A0gn)2CU-pZ zM)?PKpXz`7^`pl|RqvR)`?s&YUJnEdfdF{~Kfa-E;)|Pm-R1XusBGTfaBF{NR0s%` z13|zen5{pPcz*n}>*onCmnF*%>{@V1WC9Ru0fL}Mpl>=>anZZy?b!6YuG<1HfA_YU z`}TYS1P6g21O)uR=}Uic#n&HrvJZrY{LwnnGlne)bmZY#{1($smE3(2b}`a?Sj5Nc zxcyFr$mA`*t zb^F*KL^qG#y5zBWElpeh(=>l;9p88B3uGa}s)!V?m+j3`8ClD#!wH(Gg>$d>R*r^FNyd7u1UdNZX!* z^(Nd1yA=2ikB-a@QGc(s`MnOGKGK%HZ`brgb@Jan-g)4GwYR?&8*47VA+`2T_luv+ zd%{z0`FJoN;^jdu@saZFB-+M35h90%!#qn=`~^y5h}+*nJuA3+cz~x+&w;}$Y*2}# zTSYaF38ME}sF(GQRE0Sq(KWox4Txu?qDz$udgu{3);#-@iiN{~5v_svRB=ev2Q(+z zHa`=oSfj#|&%g){CrPxxSLF3h(IS9U#eNmaA|ylRgea3mF5F)rL6q-;1c8GTv=q5O zwY%T>;@^{ZK6_OA;e~&!@BUu;P}9kY!L_sFU(_sq=k&eL{$#lcKp>GC2T+vY!7ArU z4;6BZKq8YYi$wbT^v>sV1(#VQ9$#$@=`Snp^DrN|ZyB|glXGSia+t*J3ekYO(+pDe z7VjE37$lKBDi{hb5l|(;4TMCVbU~YyH*+CKU=P%F7$Ruo?Lkx+L(&G)tVat8#lYbp zIVUol2L=}`GsX0-b&Gr6j2v+c7Q_!C z2)*$0j9Gabpe6bvFceSjq_WL4{ccurp!@UOY+tX3Fn@__+dfU7lm(iNgO}{Ia}4`D zhI_3X!(L#B1ElhhmGQDaFy|fzcT2!j<%vwj=h-jy0?+>qk}4X?YI#x4E$X#F{G%HXnx{?Vs8FH4He2>lk zmRTERHEKgdi@m5?NlW1a{0>TD@I7G7YClwY@JqmDk;;_v%Q<8#28BNyf@LgZYm{e> z_;*x8)@57C7)b8PAO(VpZFAW35Xyj-2hrFEU_57ae~vQ%YA9on6_^9LrNM!KZ(22F zlYbU)A^kd>NqjaiVf}qR6R2_qv}}k*HHr85$19i_E;m+&8#=zxpCR!r7Kz`P0toR? zII!NcQv9WyMKWNejBlm*vD}z%rT9s|+XLXjqv~vgK&|mJ{vf{_^-8+;p#v}~xn~Kb zO9w&82W{2OK2InPs3-ARfihO$q(g1Ukr&vb!b7U&av#onMAc58xg>k4Dqz(xM3agL zJ`ljlsy9@4yp@vgQaTM7HI#;|>e|74DXG3#Ju3m@1py_fvQIzMvZ(#`jydDvi5=RB w1G`Qg%%+!C&slNP$&+0;+x*_Kd#0|L@xYg_JYDx(OUIpy(=&z9F=6um0Z1vOYybcN literal 0 HcmV?d00001 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin b/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin new file mode 100644 index 0000000000000000000000000000000000000000..a9e9a7ae041de8687d8f99bdbd5e925f28dd48b5 GIT binary patch literal 20724 zcmcJ1d0-P|-hZcQDU_?FP14fZrY&+Gx#;XCyIg>9-t_KsIRW#fv{qKpXZrL(zNx(_m3awlV_fpd5-UW z4Wc9#JH(j$1T#e?I^EKFmpe~9mM&Gsjox=4nM^TGbpIW(9L@H z)u++@3ElkZC(P)6hwj8TW~Qb(YB z7~P8dXT6K=Tj*XsCx0Kh2hhEuc@bOU71rH1HVfT-=!(%jTd}1)-4*tf z2he>S-Ib4yO+j}jy0`wz-i+=;=&nBX*e~ebkFIy&YnP+j%DVqZy&m0-=+++1jzPBx z-L-wb-hr-$Zhh+o0d(!GYkukqbT47u_x^ec-I?gVa^iFpx>M0T-fJS;&SZ2?pFh49-SO!D)N|x- z=#D}6Y_B;3&>ey9`MBsNbO)pR+tF9pygAOwwt3t8pqIgkfi7|{bW!>#)*N6>J!?|Y zq-m^KjHdsMXi|HiNqLtwe`3uX*0ATSRje6+#&Q%*(hID)4o$xwShImOb6I0Sljvm) zyG(ctP2W~DeI91b9jwVk(|Z$ZGST!r$C@pyS;?AcH1T($>G2$E*f!$Y&~*EhH9J|8 zgeLZTG%*jb#=)8lG$u5nfWNJ2CfQ;lQ-9||7h{HTtSc7hi>6eeAMeNHk*Po?6V59R zK!29rC({BNa0{EtNdsEi&!#D6iivfSX@yJ|y}i&?&IU|BJMrGzUeOkClj-5AXIAtL zJo(C`2i`bz%@)UzBU698?K0cKCv*Sues|mLr?(x5Yv!+3R7JJ>bME{{yMDc?cFvp? z+cv$lcz@w9wp+iT0iR&);B@zt!z76K!PAbWe1bscy&OC|9MH_0I+3u{1Y$ z-+kUy`N7DXDd9`EX5xoksGr~6?)Wx7)q)~ps&cHQ%8nmgVp|AqI?Qb0mni0D5nzkC zL8h2l08vIywnwSV?{SDWkD#fVLsn(MWl}LuOrFYjE~c4M6^mlvLZ4G?Kj(84vkvo2 z$Me8L%o`l+6!RWkd<8@6CkkEcS?Kap%=cJXlzc*&*k(}|x>U()qSz0eb_tWmzUZ{8 z6gxzt*uIpJz0ieDs)sTzTj+97Y>q-1SF>IoFzTn++bMP##r~OMXNkqtn2%9Rahi$E zO0i2Q)+LHHLRn=S{;;u7N2QFr*}0!F=)!m>;FYn1N1S$w-5Nl%iDDb|waff`VfN~v2<$_M8K zaoO<+>NZRVZntq`brP011-q%+41J)2x~-7M{$c6_#Z5A#>$R+fucKqwG9iiQf2Av+gIq9Q^gqI1{hGqOes|pEV7`=2|*%K60H>1 z09nI?Qk+}I2E}a`MGwV6zJ&%zDAq^(nm_!q{%)B@amU3>MG!MnEuu~E@>i7x+3S!! zLLw7jiVT_KbvFs)1p!NSlx^LuA=wt3T;}iPi#dwW4|wnIr0%oSd~lsC#t3r@vSYdjoh5^-?|_3Rt?)z|0eC5y~vU)C#$lVddzgX?9^jCrdz`i0uXYO z0ML>h8YF`lBL`>oSr(mh2W0BejlI)Mm>&G zkB@2aSy0jtEUj4>yyI6pHP!8sPQ8Q7z=rr!~o0T6N z`tj;^{9wvIa<}+-5N?%O<HK*pE=dkc5r#3Z~v2SX^WfU zAyzvI2&~x_DFDhX;dxn)dKQTW6N-Z35J!u@q%lnfev-;0rq%qKta=5nSGdxxD1ujT zh?$%x1p#`Y+z!5Fdr&cp zHq0OvyKUuWGutu)34kPshH4LPL);tIsQ@)6I;ba|=c(6F#^^Bu^#tEQ&8p&(JZN0% zHAUg7T=Zh-zPtwNHDA{dy()C|+iNimIkeE_&1;OH^R7&m5S?o(^=ho;mX%V#1r0V{ z`EKmPZ*qwcd`@ivqt^+JTyX$eae6H`AjBm#f?xGJ#5Ofx5xqX#xvyHk^8&yR4eM9k zs-nssS^QiUO#VgRQ}0+NOorYHtWobIH}y^paCs?FOft+r>ILhu6RvuX4{HzmW<$hC zA&yT~Ws9m+==9?b-PRO~THy`}NlVq*V{w}z_HUgrS7+HI*F zS=SmlP*HW&7xiBW&mOlOC@qOz{=`=|M)gko$E#;%m4E%wujQA-Zn=z0T3wm@0~+-$ zqQ3L}VqfsM&mkTYZ8e~+V?JmF#+<5GF^R<>H-6=Zw#Hq9Cq+pS9B#1{t+-eAm^A#_ zBoFLf*&+A^Lm2m6vp4`hHzqpDd%r&Ku3EEegKNX${+GG>U%CEr zaZ#E$ojtTfJ@2wtU0`2AxtaQYfK?!sV2k(_+2Jjd8rlIOArJyYkcccDA(G(h%#xrE zN$lvCXqX=mW`0k|S#dk6rjKr2pZMQn_J3_${N|XH*{mC^4~%eKDi3%DTcn@}5us zT>tdBz2Df&`fQ}KtS3$Hp6ipbde(2*YbR|EDe(wC01LFiAXQ~}2+ZP2d_*U7(dh zhkjVJyWe$9$3y{&5N7LT@7Z>R)pSQr(*YTjXUyvhqDW;{Hn$@>b8{zs((i8&G+J1t zP`_$jg7v#omtg%GbqU6Va;N#I-!3lwsNWu$M&Gv(B;N0H7)Bwns)~D6>i2=lg&#y5 zw#gM=<(XZ(v<`>s2=1f=L*gW*gav#%2nWv#7#r3HAZ^hU2H_LeO-w$t>6VQjpNP*N z(z18You)+|cgueoVWwfHHyf`llK&_KxxD0y0qj($n^eK|mkzDlEC!ZD61Y>Ebzl6@)( zVGLOsgn&MUFJcNxUgxFJXJB5-Wt99>cx6i7h4s7<534lhJZuX*c%NhI>(H4tU{JJvWyOpB?teT1693O?|dochdBk0`jV^z zTFqr~>wle5(`{c-(tA~P-g#HAYhl}3{(sn3h=p0KqB-Kq9|7+`#1)I&1To&|1M_QY z1AI-U2nLaeXs*~5JQ(FK_F@H$t;`5dQAP&00e`a$x9|HFNW0v0BI%=pc*QJqp?1&heI*!>y9_X@#r^Z)#+H726Hy zUOw|X28cE`*|9+Zavs~M zrU-E6tS39e4$yDY{i2XmEEikTLqe7dp>{y36xUuFcLAZBQXTYSaOPI##$Zc2qT38M zVvbC)YJ-6-Cz>hcb*DR(#Z3|^_Ory*ToL7NvVhzAsDEpgGGaQWBg>1%y75*|HX;8GQu6y|0-By?Dul!bM&99oVruu}ppo#GoRGMg3=BU&U!%&)&tp*q$oS zjy&~X7~!hj?50#iu5t^^;N#S#3tb-eOI>Mpp_uyLOZ@}7*6P2J2EZV-b9F>%E@%)O zz)$_3^+F{wDFe`3R2IIn$xw&kA?QVzmz{=0He`fj*&`Bv1VLJM(c1oEZ|G%4j{N?y zPD4>m+S=*gEOT{R~?t9$1goPOfM< z1asAdLrd!)&i-KY%l{tm)Pdfgy?rio$B(w>zR=#^ch%vmKN}R~4m+RiVliYo1$!k% zDoJoBQ+lPdL^jC=A5Ko7^!Xsj%H99a{%VkbqlAa25!I1OOeMyHkK@6c*n_65gHLpN zu%ig!o*1KBbUgYEWUW30zen$avio0%%)Gj%f_oF5Kyj|uwrQW*!PuH~4;paWMdX1YcyQ;bU+ z(^fnx)^3u-;3OeAD`^(ZB7`pC1VQ{`YlbWUX=;|}@NL-Trgl$oR$giSOuQ%M?2enR zoq1E^k>%;fedSC3qa;)2M(4^|($luRLkcdrGU}E1y!ic(Uz^)|B)iq0nuX`^1+ z-r%ph^?S$mR|hO^@^y=0x7ImVO4~l_HSARC&TY@Ha!0>1&~3isnV;FMI_Ju#-|zXK zo6k2rdidRsx+U+t;>lfy4rj7k9;dz1^r&T-c#=mz_29D@quFs56K|t=E3nqh8ddxg zY-zu7U{#EcxPt0#cdvKE)zpZq(soyx+U|nsQw$gjpl8y87kOke^dE2rGMM643a7x? z=gerE1{&e6u^XmGkQA78sDfB*VvtzCz7fQNd$;TM3)yNh6MSlx-+;d^`N_5(bOpNx z)(x<2%hworvE@Wj5tOd7C2oiWQIs7Dx8C%W21JGJ(~zhzDUPeUKU61v9h4G$`&rQu z50sQo6Hi4xkQ4Dh^4o8VUj-katSMyM$_x%T=@3xKly%f8Mzi1houUap*E=guKV&jQ zTpJ919o2Tqx|!nEgV(aEC<{?W*>TOK3+B1!EpUpjV0IXw*T!G><=QWM4E|Ewmj*Lc zZ~*ppytmVM?@6*DCy4j3<%svX&#hhB#d}{E@BN2tZ}InLl+TWQ@1eS$9o|!sBr*cU zOaf5$a4M)}zvK9CP{6Q^*#HEYvgg6=Lx_*E%Z=x*(4$V-ON^*f_Fs(~tN1TyB*?m; zHQ2+H{eVK*_v!*UGpHY_U>7Ex+#MtU7c$e62wRGBmO3?wvOn}w_P31^gF?3YyF&%dxmG6sd}0hE`7D1)me}9A6`3SW4xgI83UzH4UKw zkZ~C@K-e$5;>Zml^`4pPL6D}Z__zU7xllH|OnNx5wO;WcHu^=Be`= z>)!pFU(ed)oOaqZQ3z<&IC*nZLjvV|$WCsT(}c*W^|K0P?o{y?F92czL=b+KB+A)~ zL>9bF(5$}(DRH?%XcPhhp0VJWGh8RTgXGFNMF0_Y&3eqx0pIGZr*L9b7^7lD z;%zH$_wx1_YhgLzhjFRCV|NhML6WkJldRn(Of}vT)k8pR~;&fT^E&85Koy^Gj;wiA$i&;s6*+my;JMCD* zapTS}jJL5(rc6Tc5oEK4F22+`#q23Cn=R-kfm=gzvQr+3F1`_JtMY@%-P+~E=;8+u zvRbFxyrP({pE3v-?l*McwsLoqE=91aY@xxIu^m+-RK+4x2$>*APlE&+)VDc2 zw3h~DY`&ZAR!^JZ!0onscJk>njB++2xg+Wf814`9Aki&D<5+X%{ zN&e&Efko$lQx@(SbgZ#T-GAW8go8KVc9(niggd5Qa%$wL-|~kp&%HVEwxR3YZ}j^& z6L*87a85?m?LtqDK27JRDubVpeq_o72QsN!m`-k}2DMk~DKdsqk%wiV!aBT%c+B7- zc(-#f21u zV>>#eftN0H^)vgK_#IdP#<1UZG%uXUx+eM?r;rg91u2{_vLMRUxPWxJ9o^QZ3`WRSKZa2p5K~}?+$DQeRw^Ss8Gg9Sz zlc4BDB7%ewLwG>PBanryYk0tu#4d0Wgqc+ux(1TQLqlU0x=P>@j2`N|AnRx}^n5rr z?X>`iH1rKG+0rp7*z@{FZ`zFWA)3XO2UQw@R+ce_@@c4MF)t*pa7dF}z35!Pt4DPk zXmk(GS{}rxhh;M&qoFAbv$+SIG%VN4uNp+jE6}h)nT8H$)_JRsJw3mgU;1g7Q{jhE z#bb4-kr;Lj&X&K>)d;b-R@g+tZn}%#ZibA!Q)r=KzBT-ssi{U^BNMqTG(4keO=CcV ziubE{FbZQAOe59mrv<(&qOBHD4cMH;EK`YJk!27JR9ILl!J&sj#8y_A5W2CKr!H|_ z%%rt=jA>~`fig-QXm~E7Rm@H=Q*AVSGKldFQ04HsBowa^a0bvszDmO@{Ja{7hF_`C zc$9|F@N4UI#2B~;#V3Fi6XibWq~Ue7{0Uekb;1T3-crvm8)*0zkOyGgOv4}6djT50 z8$Hm9pN1pV!yt=A_v>RC4Sy$e_v3m4TVlPio`!$3mS1A3GwW$WyiO>g#6T`jcB+kD z7Uy4tjWh&9{WRh-KaH5Axi!jN1LDy2mQD${!3Erix%v?Ud<1k17II@lmlqglTPgEJ4E|wz*)?pwJnS!m_Y}(N4{yWKec(+zM zLVV-HH?RI}OaJ^U1Bbicf8zP_@*mvNeO;;GQ9EhW@ZZgBjOqr)ihZ6&?bC_ns*?-u z2JGQbgqVz(x4;vP`dPDgrOe$l5)12PFS+r0*$c*yb?s~qmOwr56IvqLoc`xN21M%uq zQW-sM@x+MzaNcPrF5w4EXS*An6Hx-#E)C_TVF^&2x1PC02y1rTO5bc4Tz{kjD2Sc_ zbQTZIA{2X}Iv|8%+18##0HiCwK(oUyz~+Nf|9%2RLfv^VvcnwQ(QP4r1Nqc6ML$l+ zlj!Vp(3lq8?-JMs$9}1~ zXzYP%rJOrYY6VUdQTrdx@4*pZ6%%96pvoppF#kVxL}Q-^fsMNz$z4PCj8jliJ8osW zirO(J7{X{Q3Y}3=JMKCNRfKL(Ur6H~rEz-xr}5gQp1Vt27rzq=H}kFmG9sdzc{jtH3Pv~G z2ze$@UJWaH0-3W)4=GTMqHKZkZU^O3-d3fIY%7?y&D$aC-2ml1h0#1zo(0@4PZ>*D zF$5ex|k z0avXzf%1p3O(E!*Kgf>{6N(`(xD%2;LG^j-s;O`tmRAE%=J~6fYrswUjMA}*YLu@F ze#%b(a@SM-HO>}Mp!_+Iodd7Txi{?hRDSZwx&04rTkIG%vAC}nRKd(v5r+Lt9(2mp>+M=) z2j!nYWFly^f^t+D_R9Fb7zv)|I!o@5aT*lRReSC@yvX+Lpz|9({?{(s)H4-X^Y<)m zd$8BuY}dpOM_w_a067J9jTiv^>BXp z%Y1{jwLGz4$QYaimB+v?fY01391;(sC*f3jkDbAopf$~e_|RT}p3jHNI>?dWrIcp! zFe%dRx(3%aT(6;Nr(jsBH2oH=)%(z%wc_z$-8@iGne)#ZjxyS6M@z6Q5SsL}5@=@C zfJY%XAygw{oRi{$F;2HAIuKDzV_WSQ$((owv;lcMsX#OZ{ufEC8@>ROTxMCuAj19x zt7CW?5lFUJgTRE`WGq{TUyGGPkfm=$HnNvJ)`laA61zO6Um`05XqF*6W3hTFf&v=w zM13DB>q8>|DMq3(0`LX#4#?tNi^kWpYAj@rG)-AD6BG1IWf52;usR|sLF$#3ule*?? znDMFL7AjbQugNaMOLz(&m6e5JHu~$vHwU3=59E|lQ$hvzF)`Br*Tb8`$cKZW$mxER zm{7r|K&8!-fCC+14~7%5*})jKCRSNADu7DXXmX6^LGg+yO;dQX1Qnw!Q^N8TVkUx4 zlask|z>TW~nTCL5$`_g!NrOzUAjYO6Jd!|@7hz$1(-51E>LT_{$>at4t1=KG(B$cu zRkO<~O-AGmUnF7f6}qPDdOFn8MNW55#B_nsbZgLKNWx!6b9(k@@@bhSf1+=9$vaibGv+i)07=fyGIlno6v1ywr@Cn z({7EfayL_|fI`2XyYZodAGw7vZf!7ou+wrnq5+ z2gFQKaCpmM!Kku}3U&OeQiDAp`K-)mfZxH&9t-DTuO6hZ3uid(N@7_$x8-5OQ(-Td z{mfbb`AOh=Yq^F`o(l0%PUWi$Qf|hExZRF4b23+7JlW5clgz$yQM>{$iH=7Y&q%Q$ z;BTP9yS+Tx8Njzmg%4I!CX5#<+@*SnhlUIHfbsUT$WY-+`bSDscu>_pRBDkVDm=1= zGT+B!RCrS3EJ}sn8TT=E4wK%*=s>VhQCuy5l!_8Gnt`ues3;Ys4xiw5o27}024W=? z!!@}ZT#_$=ie@n)=6{S&rBr_&(>z+BX}#)iXr?0fS}I!N-`KKIUzlyZk&2eBt)-bT zz?)UrZS~x4D=uZ12J6}doCjST@6dmf5Y6z6DEbe4*~s9vMLL`A24^@e=nKMpGH zO~rBE;Qd16+^N`VTsypVX;#fJBw6OL=tbByUMijtd;!2fGSS{_ht}6Nv@|s|2J9QO z4OH|hqdY1mk8ZM}q~5Ea7q*K)#kVSk3{9Zo2k<#raU&J4Lt0a}RLgj6A{B2|U~NFe z!Wu3H&rvQjj)!P!G0$!5 zD^10BqknWIA-t06mSA_wWt!k!^do>g6~Qj-q7_62{X;X4GLLQQi_XgRO}miKiqQ4# z?Zzo)v)hC!S!d;Y&um#0);o6Gz^t0n4$~JiX-rb!oF!J2QNm{^>82<&1*vJdT-9^u z&iwqr7&ZM_wYgk`5qVQwsp3z*^jBdP#|bAOd) z{>;QNYF+qSni$P`VoV|+aap7)&I$sMrmd1`S}Bk~(^hl+M$>Ba5!hc??jC35&ojOa ze#s58rfJ)Z`_b(F^C%zs^<;~lr4P=E$=(o6u;DRrGEIArMN2C4KKsFAd{?Pgo$eUVV()hg7lP&2@ZViG`*4?$1Wz6sTF$Y1>Ycdh^%x_C6Q5`4hyg#jEAN# zYk(}9eHZY-WXbd-K#FN_7{itjRV`>Uh=t=BR7KNYfW%OO6;4K8EAlb7jcMerYKGl5 zroMtN<0;s8v1zgZgBS%*g2dhL8QqvX2gbP#Gb06|8k<1V@h?l@F{Ml{lTbK4V-%xO zfo7l(1s_s75LB8m2&?`sJJ5`i9jXXf$e=ildF!m$WyX^<<6cD+svC^LjUY)H-wg&Y zb=C}MU7Bo>#18(|fe>OCgIjb~;bg6;`Kb1jQ9_OySs~BeUlY?j$q*1To1sT$dYsF) zY}e|yyLNtNvmAV?`SVXi?7EE`S-8ov$UeBOZ4JEMU-F@9Omq12@SQ9CZ}>aFtV7jA z3Fhgdb9zb*Q3V6d9@w%oVF7|P$L2k|*a!vaq}hIi|EmT}o{Q<&8qEaAu}r=x==~~r zeld&LIy3h(iHoDyOswPwyl1ZzqgH1{%nUb4ouW9VxLKiMA%an;i|1e1tJ?3J6%uOJ zDx?}_%|I5&-4MVG4b?~)!YqMnA_kbR+U#{8#KgSRVz_C{(ep_74yWC*gQsQ{C9{?~ zVU01d0wh3g@gC%ihJrr~a_&(eb~P0RLpUwXl3=F?JTlBLm1butb%w1)v-^0(LgS)Q zk*yo+%bV8J`@Hq_)y8OZEzQ2c>4G$#y~t?|c*_G`#kiGBv-2T6s^FZ-X{qefC03u* zadlNJOjC7+E(|#bT?~fi31HuT%w+F87Z?lSX(Q^}?u1euP8ME6EUaNCub^4)AgZMK z-2s|=Gx%P#!ADFNH2x$)A9JsB!Y@?Q7+nkE;xw^P!FxWh)x*tB#To><0uem-3TK6@ z0-A2F!&z;GPSPz|rl;mkbGkr3a|h^UG^q%`V0BpauutcvJ84diTx~560U9Xra#Zj| z6(DqOqEimt4tQ%hoW;y)zEO)OIU251it3XMz}H(FedUcl{yN^C)667}onNw#g|#(S z5O@W&E+1lmm;<6$TI@9E{SD1_&-y02*8}VCo(6wI2$yqCamA_6Vo__X6+8j4m;usD zv#@D*8K4}z59vp9eqph^xv>pv`Td9!N;TGUcXbWT!N26db_cV24(#XPFU_3{g_xP9 zURwn6k)ooaf_@|4D~CT|ra{F2#3qp34t~Rqzzq8ak!C~9U|NtvJq) ze3;R^s)K)?3I99=V9(Ht*y<(!b%x-KZ)O>s0a_i*)ydJQD)ppjlGgx=D*LRe%<#-! z$J;M55QT30tSxornp9&v9q`s!!5uQA8a!>LOCEC8(j|@!8#mou=dTHk^4dbI%bu!M zQY>miiof29275)Z0UE&GY>o_W;^57X59yG;g z?9uPR9{s*r=$lKj0kY-|_C|)CfU&ey^;#=vZVgwai#bzcCwxI`Z3R|1>G61K_!7Qy zk1?qPL}9|YFfAE+FM;$je(=E`7-rriC&Z6GV1<+H#b$JHC!3>nMpQj%enT*TwVCR4 z`(eT|R)sHK`mz&KlaSa(snid=C|(0sL42B{gNUJdFZg`E5aQ*v zR+_g54BUkjQY+Tbym&B+&qSr>Fh>BLrR>{&eP1Z2VWL!K88lSF(fl8A%gZ+q8v4xX zGSPe+p8^nuam?aWHYVDY3I(^`VYj5vu5ilvuQ?Sf&A-a4gsHNwD>y;8w1Wf9--)So zs7f>+MFkQpqWOKnq4V$8tlIA!l$lNQ6&$sL?5yUp(@pbN0iO!^Za!j5x*rasmgd73 z1lP%iXD(?pzXu-)4!CI^>{u%8t9odz7uckE;8nlWxD=co`r{8YKo^x3`IN8*s^_5R z2T?2?MLOg(lVqi`5~2Xex!*Zkip86vR%q;q^Iiuz!j1LYVV+raErB2d@c9oX@_{Iv z##S0t1Q_PA16MwpRJn#be)h`O-yOAwcey=_>`;QkuTd$id)=Cakw>Lx80XEK3J|!d z^!UQxF7R?}wkAum9?$-8u7a?v}OS?M>;2PWEVZ)TaibER!C1>-`f0>c5=wOtyW)*+TcA zUygnA?2G1Gs)SdeaZ8yC>KJP)>*8TRy z6Nc?MaOI&Zu1{Hg^OrkL$=>HP7i1}aziiNJ1*_x!`^|yM@5V-5;QUb=Z{BDv8PWS} zc8;)i%;Sg7%{;c^hADrtem48BQ3e0=qC4sW=NB$8zwq6Qt1aH%-xYsvuRStK{%vCV z#GGeeF3frGnvuV5%HH(nsGQYiCHwfvrnNUb^-*tW+Cy)~&HdnK`*(-LrSp||045TY>6BYk#yM$+fdl{l(Bf29i8_9jeb<>P;p&`-`mper+7p517RlQ+$1rN3K%q ze~hyslSj6$<6VC$SUfVxyQyH=o|_{^=^SN5I*%Ho`IKhpoayE}^qr`2w#;-niv)IS zuAQc+%ktz5QfCioUaRWoYsChB6{-)C)-y-*gGP;a-&U}Q*<%r_xMumMAE7^{uu#l? z!z#Y=z@Iy5p+!oyD7J~#kv6~*QUr<()9J&C(@aWp<4P=MiFJZvjCcLGU z%EQsk3YZWzq%(@BcT%%L~#{g8_A<4B>b&N+*TBTIbOTQ}IISfHI@O zpyB3Tvx?`RdEHf^M&lIA(Gav8sx;H4(xG8T*Ik^eQm-xA)aD!p3QGH2OZ%?QwGC!? z=)FC@1@c2pQei+?6y?!3iIo5ai7E$YWe5O-cb`|Ve6-dF{njaR?Eu$~;)!a(iUA+} zCjcLrQ9->uQU=l%p(S|qCG@EVY|EohHx*0^ZQ>||I6z`kr14?j162wIEDsB%C(rQ0 zhC7CX62MswsmBh-miCi2Y|V-q*B%YgRc=$$VOp}^zAr=D{u&9T{0tyBj z9B#8{dGe0*25#sM77r^LDG}q*^j!PV`qY6_3ax?1Uae59!t%An^L9z2XqDwLXAY9> z;vLJkDbbpH%oy8pl-|a2+gyV(C@C{&5KW@eVuBn=HC$<9G>^LL(w(T*W%E8%7AhY*8u$3PS4=6G^ciz8baG_Q#H#o={D*B9vpMK6GcOxOiqRaZMI z@f4Yn3`jDgNRnhHNK&NJA{~&5Er=)=Mxh4OmY#~wJQoxa#S<|kzWfvhP{MO zN|TnC7Anm%3@j|t)(rz}MiSV(D?-B>8WwQei#A^}oLbm1KCC!%jas>Bk>$4ezVMn0 z+%a6EM#b1US#4QrGq@PO*KB%uc#m3Z+Hhvnpeda%KWJ8TN9SGNG%ZO~6)_hQn>xRd zF2!YY2_r5r%c}F-uv5*Y1Y!*OA#U-64f`kHOkH{I6muspd|j@4s%Z<}6*Dbr_*p}f zgW;m`v-Ut0(Rsq8^i5NHwyvH3>E(m3zc_yH$FJyL|M0?lK4o8f?WOnjpR@jZpMLm) zfq$N}n_^Jf{7vlE8*kZ8+SqoOVw#u$;t&dyJ}ISbPnGhWtB<4S47j zW7Od>F?qQRypiUwlt)lVAvVc5SZBakje#tvwi>2W70fMGti-ZgDnSwyKW7p2ZS|6m@rxyb7JH19%$)^$HS!@I@{R(4`*Q^ZNE zRzibP4`Npp^ficEF0CoE1k$4+(`&=B%0eg&E1NANE;FVYB$J5MONons%NIz#qG^{2 zw@)peNoihuHSazO2+I}P1NNz{fGuc^GvG7h9VfYNG(br9%dupb2w>-^olo-aEeOi? z7?wR{|99_O%B)0dYsWWyLt7-hxCCs$nyrai;0Kkqa1f4xDpX82gfgSPU&B)RzHdU& zeLpkZ$yk7eDOE;Vi`LdAy!+q{JlTn3rH(So!(4qMF610oVV3t*P2O|V4IWS0&`nQT z{0y&dL`V29X#GqGuvq6*$4e3g;hdZUL~q7<%PgG;UPp1WtmT%>7e z(!3VcV61k>rbwHDz2*a%%^WuOz+rQ@A2N3a7JP$ZVN#o&k<({+Z==sn@>QG6?AEm> zyzqkq_nq{-F?8RS+oGj2h1YPARM(r0bvV1QyB>-FRIYpgNR_{WRmx8^okRm13>fVcITZnCC~9L{ z&;I7}9{+u(?My%a$o2R9F1mT$xjTNC|HIHke!t&;#FJ!60QE#PwPk39&DN9+eEX6gy)0E`v<)xMHvE;Kx_~5Qh_F#iq_iW1x~ilv?#4 zSn8@*fd3K&aiJe^=QK@*D-aBcP41xE8MG`hkPRHm5In zs`T?!UqV;+=OVl4Hc?>JKdEj;s}gfkC>k24P~Tp81dAz;o&1euVKC|J9*q#^kZecQD3oceCw zb3P8>mWO`%cw1P=wlKx}?hIYF5x03y7e>xKSAS+{WZS(m(F#*C+^Q(BOxJn$6Vg4n z2n6wECj5%akp7)A;I7k{7sgM9NZ7W_M_bFZ<$hu0$GDAHX2RUKXc&l7DqxQKJbn?a z@ffXvVW(MHWe;9%BUD{xr$F(9*}}F;ZXb_dFZBuw=J6doKIK&_yzga69gQJ8ezV(b zKvp7|J@yc09ketZ88(*}1 zobuLJb1xos^3c-{kMFCVwO;?sKPP%mdtoMdbasF0ROb^VUag0+|s_yO-fm-l~mj`xq@EeTP+CT~3by#SnnClZvG{XE;^RCLH^ z1RGbkpp@_v!qE}ubYr#LU`s38Yx(m5H=#qC-P=>Lw1iIVlq=%zDLPtksr_frgZ zM=PKmmb?6nvrbNLx#r?8Ub1=1ml0d&blEp9Gt###?e=5IuVb|VFSH3JY`J)+D|&1< z!INoo(fAB>2uU?kuDU_kNV@Qch#v5kak@)(S z#7rp~IOPyMhdgR=eM2B``)YO{*H1%|THN*D>0_2$5_r9+xfIv?(S7CS9Vaez7gry+ z{Jy29Mn9XSdE7qc!S|E$_MzWG^R+{7A6&o3<;hQkNW~3Ye~cWWG8?V2uvyqVc~f{L z(RW~&bS@WP_*&mrGZCq%H_Y+XXI^ta)eo9DIpne;hEhr@D{t-{zwF9OuD;;CiS&7m y#|u||;JIyoUD2_3P2tv1kUC0Dx;j#`Rqz9bZ;$N`dz-uuN$ld%WUNu! z`H{O^k_lCJmsbDq53$yd?GJ~b6*h_#M9?DmM?qzv>@N|73a+vu)cL%3N&Fydrr;g9 z_j#Y^d7sbU^M)BLrZ6$G4TQ%vCWP7LJB;`dcIoz35Qa66YzN^JB+v8=ok0(?A$kbt4{m?5iJ8^c0F7?fRvRMS+_!h&N%=vjATIDY$z?iyOI8(INzhbx`9*5I)n z$yAt3(2nY!Bx3y}M!3Bmg7`sI-d&fkK%f&X3qZ7dq-Az)-`xDJ;MnIq5BFYpd3i{F z`pbdvIeC7W9^HHQ;vrkrZQ3vdQvx5+FqeGGr&DhVn>;*HCKiao?qc1zAs2c+b^uYOETR<@sEF8ZJqr3z0T6jN5OxnVX{(x zV|F{*e_o^g9eM}&UeUleZ9-sP)hTcFvXy6YNUC)?w zsj;C_i388Sr^1o9$`QZ|XZg+2=$b=m)L??y4*n;3PaVp3?qK&viBupsRndZi)njsz z41qt3N0~!)>fmdF_-{cl_%{$FlIi3a7QPk6+$ncPW;=j10K zm97J$1_B^BT@D4Y&E~Zi+uYjER4BzQVqF~mUs@oZsUwB)VeQu!SNeYXttS~haNg?u?2Wx&Or3FXp4{td&V{BCZkVen z;V1^b_3mtkLz<6Yq3CbxfZ)#_8$n)x;7449qswB&GM9#KsY*jq(Un#xpWE!p&5N c+O!G-OmK*8D!f3y&m|_Z>G-hFa;vcA4Zz%qc1=O2yOj&5XaIqp=`UwqB-JQLs>=eq*n47LtSbQoV)n@.json` is `test_.json` run with `--spec Satin`; both pin their +/// full output, so comparing the pinned outputs compares what the two engines print. +#[test] +fn test_satin_output_is_additive_to_legacy_output() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + let mut pairs = 0; + for entry in std::fs::read_dir(&dir).unwrap() { + let path = entry.unwrap().path(); + let name = path.file_name().unwrap().to_str().unwrap().to_string(); + let Some(rest) = name.strip_prefix("test_satin_") else { continue }; + let legacy_path = dir.join(format!("test_{rest}")); + let load = |p: &Path| -> Fixture { + serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap() + }; + let (satin, legacy) = (load(&path), load(&legacy_path)); + assert_eq!( + satin.args[..satin.args.len() - 2], + legacy.args[..], + "{name} runs the legacy fixture's command with `--spec Satin` appended" + ); + assert_eq!(satin.args[satin.args.len() - 2..], ["--spec", "Satin"], "{name}"); + assert_superset(&satin.expected, &legacy.expected, &name, "$"); + assert!(satin.expected.get("satin").is_some_and(|v| v.is_object()), "{name}"); + assert!(legacy.expected.get("satin").is_none(), "a legacy run has no `satin` field"); + pairs += 1; + } + assert!(pairs >= 14, "every run and tx fixture has its Satin twin, found {pairs}"); +} + +/// Asserts that every object key of `legacy` is in `satin` at the same path, with the same JSON +/// kind, recursively. Array elements are compared up to the shorter length: an opcode trace is +/// as long as the run, and Satin prices the run differently, not with other opcodes. +fn assert_superset(satin: &serde_json::Value, legacy: &serde_json::Value, name: &str, at: &str) { + use serde_json::Value; + let kind = |v: &Value| match v { + Value::Null => "null", + Value::Bool(_) => "bool", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + }; + assert_eq!(kind(satin), kind(legacy), "{name}: {at} changed kind"); + match (satin, legacy) { + (Value::Object(s), Value::Object(l)) => { + for (key, value) in l { + let found = s.get(key).unwrap_or_else(|| panic!("{name}: {at}.{key} is missing")); + assert_superset(found, value, name, &format!("{at}.{key}")); + } + } + (Value::Array(s), Value::Array(l)) => { + for (i, (sv, lv)) in s.iter().zip(l).enumerate() { + assert_superset(sv, lv, name, &format!("{at}[{i}]")); + } + } + _ => {} + } +} + +/// An error prints once, on stderr, and stdout stays empty. A legacy spec keeps the line the +/// 1.7.1 binary printed on stderr (`Error:` plus the error's `Debug`). Satin prints the error's +/// message. Both exit with code 1. +#[cfg(feature = "legacy")] +#[test] +fn test_errors_print_as_their_engine_prints_them() { + let run = |args: &[&str]| { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); + let text = |bytes: Vec| String::from_utf8(bytes).unwrap(); + (output.status.code(), text(output.stdout), text(output.stderr)) + }; + + let (code, stdout, stderr) = run(&["run", "--codefile", "/nonexistent/code.hex"]); + assert_eq!(code, Some(1)); + assert_eq!(stdout, ""); + assert!(stderr.starts_with("Error: Evme(FileRead(Os {"), "{stderr}"); + assert_eq!(stderr.lines().count(), 1, "{stderr}"); + + let (code, stdout, stderr) = + run(&["run", "--codefile", "/nonexistent/code.hex", "--spec", "Satin"]); + assert_eq!(code, Some(1)); + assert_eq!(stdout, ""); + assert_eq!( + stderr.lines().collect::>(), + ["Failed to read file: No such file or directory (os error 2)"] + ); +} + +/// A legacy `run` or `tx` that leaves `--spec` out runs on the tool's default spec whatever shape +/// its arguments take: a `--` ending the options, which the 1.7.1 CLI accepts, still prints what +/// the pinned fixture and the same command with `--spec Rex6` print. +#[cfg(feature = "legacy")] +#[test] +fn test_a_legacy_command_ending_its_options_runs_on_the_default_spec() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + let fixture = |name: &str| -> Fixture { + serde_json::from_str(&std::fs::read_to_string(dir.join(name)).unwrap()).unwrap() + }; + let run = |args: &[&str]| -> serde_json::Value { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); + assert!( + output.status.success(), + "{args:?} exited {:?}: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() + }; + + // `run`, the code after the separator. + let basic = fixture("test_run_basic_return.json"); + let ["run", code] = basic.args.iter().map(String::as_str).collect::>()[..] else { + panic!("the fixture runs one code: {:?}", basic.args) + }; + assert_eq!(run(&["run", "--json", "--", code]), basic.expected); + assert_eq!(run(&["run", "--spec", "Rex6", "--json", "--", code]), basic.expected); + + // `tx`, a separator with nothing after it. + let transfer = fixture("test_tx_value_transfer.json"); + let mut args: Vec<&str> = transfer.args.iter().map(String::as_str).collect(); + args.extend(["--json", "--"]); + assert_eq!(run(&args), transfer.expected); +} + +/// Runs the binary and returns its stdout, failing on a non-zero exit. +fn run_ok(args: &[&str]) -> String { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); + assert!( + output.status.success(), + "{args:?} exited {:?}: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} + +/// `SELFBALANCE PUSH0 MSTORE PUSH1 32 PUSH0 RETURN`: returns the executing account's balance. +const SELF_BALANCE_CODE: &str = "0x475f5260205ff3"; + +/// The 32-byte word `value` as the `Output:` line of a human run prints it. +fn word(value: u64) -> String { + format!("0x{value:064x}") +} + +/// A `--balance` or `--faucet` override of the `run` receiver survives the code `run` installs +/// at that address afterwards. +#[test] +fn test_a_balance_override_of_the_run_receiver_survives_its_code() { + let receiver = "0x2000000000000000000000000000000000000002"; + let balance = format!("{receiver}=1000"); + let faucet = format!("{receiver}+=1000"); + for overrides in [["--balance", balance.as_str()], ["--faucet", faucet.as_str()]] { + let mut args = vec!["run", "--spec", "Satin", SELF_BALANCE_CODE, "--receiver", receiver]; + args.extend(overrides); + let stdout = run_ok(&args); + assert!(stdout.contains(&word(1000)), "{overrides:?}: {stdout}"); + } +} + +/// A `--balance` or `--faucet` override of a system predeploy survives the deployment of its code. +#[test] +fn test_a_balance_override_of_a_predeploy_survives_its_deployment() { + // A contract that returns the balance of the MegaAccessControl predeploy: + // PUSH20 BALANCE PUSH0 MSTORE PUSH1 32 PUSH0 RETURN. + let predeploy = mega_evm::system::ACCESS_CONTROL_ADDRESS; + let code = format!("0x73{}315f5260205ff3", alloy_primitives::hex::encode(predeploy)); + let balance = format!("{predeploy}=777"); + let faucet = format!("{predeploy}+=777"); + for overrides in [["--balance", balance.as_str()], ["--faucet", faucet.as_str()]] { + let mut args = vec!["run", "--spec", "Satin", code.as_str()]; + args.extend(overrides); + let stdout = run_ok(&args); + assert!(stdout.contains(&word(777)), "{overrides:?}: {stdout}"); + } +} + +/// A pipe whose read end is already closed: a write to it fails with a broken pipe. +fn closed_pipe() -> std::io::PipeWriter { + let (reader, writer) = std::io::pipe().unwrap(); + drop(reader); + writer +} + +/// A command that fails exits 1 whatever happens to the line that reports it: with stderr a +/// closed pipe the exit status is the only failure signal left. +#[test] +fn test_a_failing_command_exits_1_when_stderr_is_a_closed_pipe() { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")) + .args(["run", "--spec", "Satin", "0xef01"]) + .stderr(closed_pipe()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); +} + +/// A run that succeeds, with stdout a closed pipe (`mega-evme … | head -0`), ends quietly: no +/// panic, no backtrace, and the exit status of the run. +#[test] +fn test_a_successful_run_does_not_panic_when_stdout_is_a_closed_pipe() { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")) + .args(["run", "--spec", "Satin", "0x00"]) + .stdout(closed_pipe()) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(stderr, "", "a closed stdout is not an error to report"); + assert_eq!(output.status.code(), Some(0)); +} + +/// Bytecode that reverts with `Error(reason)`. +fn revert_with(reason: &str) -> String { + use alloy_sol_types::{Revert, SolError}; + + let data = Revert::from(reason).abi_encode(); + let mut code = Vec::new(); + for (i, chunk) in data.chunks(32).enumerate() { + let mut word = [0u8; 32]; + word[..chunk.len()].copy_from_slice(chunk); + // PUSH32 word, PUSH2 offset, MSTORE. + code.push(0x7f); + code.extend_from_slice(&word); + code.push(0x61); + code.extend_from_slice(&((i * 32) as u16).to_be_bytes()); + code.push(0x52); + } + // PUSH2 length, PUSH0, REVERT. + code.push(0x61); + code.extend_from_slice(&(data.len() as u16).to_be_bytes()); + code.extend_from_slice(&[0x5f, 0xfd]); + alloy_primitives::hex::encode_prefixed(code) +} + +/// A revert reason is attacker-chosen text. The terminal output drops what would drive the +/// terminal and keeps its lines; the JSON output carries the reason's characters, escaped. +#[test] +fn test_a_revert_reason_is_filtered_for_the_terminal_and_not_in_json() { + let reason = "one\n\u{9b}2Jtwo\ttab\u{1b}[H"; + let code = revert_with(reason); + + let human = run_ok(&["run", "--spec", "Satin", &code]); + assert!(human.contains("Revert Reason: Error(\"one\n2Jtwo\ttab\")"), "{human}"); + assert!(!human.contains('\u{9b}') && !human.contains('\u{1b}'), "{human:?}"); + + let json: serde_json::Value = + serde_json::from_str(&run_ok(&["run", "--spec", "Satin", &code, "--json"])).unwrap(); + assert_eq!(json["revert_reason"], format!("Error(\"{reason}\")")); +} + +/// No place the tool writes the `--rpc` URL carries its userinfo: not the log of a replay, not an +/// error, whether the URL is complete, holds an `@` in its password, or lacks its scheme. +#[test] +fn test_the_rpc_url_userinfo_reaches_no_output() { + for url in [ + "http://alice:s3cret@127.0.0.1:9/", + "http://alice:s3c@ret@127.0.0.1:9/", + "alice:s3cret@127.0.0.1:9", + ] { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")) + .args(["replay", &format!("0x{}", "11".repeat(32)), "--override.spec", "Satin"]) + .args(["--rpc", url, "--rpc.max-retries", "0", "--rpc.no-cache-file", "-vvv"]) + .output() + .unwrap(); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.status.code(), Some(1), "{url}: {text}"); + assert!(!text.contains("s3c") && !text.contains("ret@"), "{url}: {text}"); + assert!(!text.contains("alice"), "{url}: {text}"); + } +} + +const ZERO_HASH: &str = "0x0000000000000000000000000000000000000000000000000000000000000000"; +const SENDER: &str = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"; +const RECEIVER: &str = "0x0000000000000000000000000000000000000001"; + +/// The `transactionHash` of the receipt a `tx` run prints. +fn printed_hash(args: &[&str]) -> String { + let mut full = vec!["tx", "--spec", "Satin", "--json"]; + full.extend_from_slice(args); + let json: serde_json::Value = serde_json::from_str(&run_ok(&full)).unwrap(); + json["receipt"]["transactionHash"].as_str().unwrap().to_string() +} + +/// The hash of the deposit `tx` runs for these flags: the keccak of its EIP-2718 encoding. +fn deposit_hash(source_hash: &str, mint: u128) -> String { + use alloy_eips::Encodable2718; + use op_alloy_consensus::{OpTxEnvelope, TxDeposit}; + + let deposit = TxDeposit { + source_hash: source_hash.parse().unwrap(), + from: SENDER.parse().unwrap(), + to: alloy_primitives::TxKind::Call(RECEIVER.parse().unwrap()), + mint, + value: alloy_primitives::U256::from(1000), + gas_limit: 100_000, + is_system_transaction: false, + input: Default::default(), + }; + let encoded = + OpTxEnvelope::Deposit(alloy_consensus::Sealable::seal_slow(deposit)).encoded_2718(); + alloy_primitives::keccak256(encoded).to_string() +} + +/// A deposit built from flags prints its own hash: the source hash and the mint are in it, so +/// deposits that differ in either print different hashes, and the hash is the encoding's. +#[test] +fn test_a_deposit_built_from_flags_prints_the_hash_of_what_ran() { + let one = format!("0x{}", "11".repeat(32)); + let two = format!("0x{}", "22".repeat(32)); + let mut seen = std::collections::BTreeSet::new(); + for (source_hash, mint) in [(&one, 0u128), (&one, 1000), (&two, 0), (&two, 1000)] { + let mint_flag = mint.to_string(); + let hash = printed_hash(&[ + "--tx-type", + "126", + "--sender", + SENDER, + "--receiver", + RECEIVER, + "--value", + "1000", + "--gas", + "100000", + "--source-hash", + source_hash, + "--mint", + &mint_flag, + ]); + assert_eq!(hash, deposit_hash(source_hash, mint)); + seen.insert(hash); + } + assert_eq!(seen.len(), 4, "four different deposits, four hashes"); +} + +/// A signed transaction built from flags has no hash: the tool signs nothing, so it prints the +/// zero hash and not the hash of an unsigned stand-in no transaction has. +#[test] +fn test_a_signed_transaction_built_from_flags_prints_no_hash() { + for tx_type in ["0", "1", "2"] { + let hash = printed_hash(&[ + "--tx-type", + tx_type, + "--sender", + SENDER, + "--receiver", + RECEIVER, + "--value", + "1000", + "--sender.balance", + "1ether", + ]); + assert_eq!(hash, ZERO_HASH, "type {tx_type}"); + } +} + +/// A raw transaction prints its own hash while it runs as it was signed, and none once a flag +/// changed what runs. +#[test] +fn test_a_raw_transaction_prints_its_hash_until_a_flag_changes_it() { + use alloy_eips::Encodable2718; + use op_alloy_consensus::{OpTxEnvelope, TxDeposit}; + + let deposit = TxDeposit { + source_hash: format!("0x{}", "33".repeat(32)).parse().unwrap(), + from: SENDER.parse().unwrap(), + to: alloy_primitives::TxKind::Call(RECEIVER.parse().unwrap()), + mint: 5, + value: alloy_primitives::U256::from(1000), + gas_limit: 100_000, + is_system_transaction: false, + input: Default::default(), + }; + let raw = OpTxEnvelope::Deposit(alloy_consensus::Sealable::seal_slow(deposit)).encoded_2718(); + let raw_hex = alloy_primitives::hex::encode_prefixed(&raw); + + assert_eq!(printed_hash(&[&raw_hex]), alloy_primitives::keccak256(&raw).to_string()); + assert_eq!(printed_hash(&[&raw_hex, "--value", "1"]), ZERO_HASH); +} diff --git a/bin/mega-evme/tests/legacy_line.rs b/bin/mega-evme/tests/legacy_line.rs new file mode 100644 index 000000000..4167cd1d4 --- /dev/null +++ b/bin/mega-evme/tests/legacy_line.rs @@ -0,0 +1,181 @@ +//! The legacy leg runs the line the chain ran, at the versions it shipped with. +//! +//! The released `mega-evme` 1.7.1 and `mega-evm` 1.7.1 are pinned exactly in the manifest, but +//! what they depend on is resolved in this workspace's lockfile, where a `cargo update` could +//! move it. Every package below is pinned to the version the 1.7.1 release's own lockfile holds; +//! a change of any of them changes how history replays and has to be a decision, made here. +//! +//! Many of them the leg shares with the Satin engine and the tool, and a lockfile holds one +//! version of a package per compatibility line, so the two engines run the same copy. Where the +//! Satin engine's own dependencies require a newer version than the release shipped, the leg +//! cannot have the released one; those packages are pinned at the version the workspace holds, +//! next to the one the release held, so that a further move is a decision too. + +/// The workspace lockfile. +const LOCKFILE: &str = include_str!("../../../Cargo.lock"); + +/// The legacy line: every package whose version decides what the legacy leg executes or prints, +/// at the version `v1.7.1`'s `Cargo.lock` holds. +const LEGACY_LINE: &[(&str, &str)] = &[ + // The released engine, CLI and the crates they are published with. + ("mega-evm", "1.7.1"), + ("mega-evme", "1.7.1"), + ("mega-state-test", "1.7.1"), + ("mega-system-contracts", "1.7.1"), + // revm 27 and op-revm 8: what executes. + ("revm", "27.1.0"), + ("revm-bytecode", "6.2.1"), + ("revm-context", "8.0.4"), + ("revm-context-interface", "9.0.0"), + ("revm-database", "7.0.4"), + ("revm-database-interface", "7.0.4"), + ("revm-handler", "8.1.0"), + ("revm-inspector", "8.1.0"), + ("revm-interpreter", "24.0.0"), + ("revm-precompile", "25.0.0"), + ("revm-primitives", "20.2.1"), + ("revm-state", "7.0.4"), + ("op-revm", "8.1.0"), + // The block executor's layer and the hardfork tables. + ("alloy-evm", "0.15.0"), + ("alloy-op-evm", "0.15.0"), + ("alloy-hardforks", "0.2.13"), + ("alloy-op-hardforks", "0.2.13"), + // What the legacy CLI decodes, encodes, fetches and prints. + ("alloy-consensus", "1.1.0"), + ("alloy-eips", "1.8.3"), + ("alloy-network", "1.1.0"), + ("alloy-provider", "1.1.0"), + ("alloy-rpc-types-eth", "1.1.0"), + ("alloy-rpc-types-trace", "1.0.24"), + ("op-alloy-consensus", "0.18.14"), + ("op-alloy-network", "0.18.14"), + ("op-alloy-rpc-types", "0.18.14"), + ("revm-inspectors", "0.27.3"), + // The precompiles' backends, as revm-precompile 25 selects them: secp256k1 for ecrecover, + // sha2, ripemd, the modexp crate, arkworks for BN254, blst for BLS12-381, c-kzg for the point + // evaluation, p256 for P256VERIFY; k256 recovers EIP-7702 authorities. + ("secp256k1", "0.31.1"), + ("secp256k1-sys", "0.11.0"), + ("sha2", "0.10.9"), + ("ripemd", "0.1.3"), + ("aurora-engine-modexp", "1.2.0"), + ("ark-bn254", "0.5.0"), + ("ark-ec", "0.5.0"), + ("ark-ff", "0.5.0"), + ("ark-ff-asm", "0.5.0"), + ("ark-ff-macros", "0.5.0"), + ("ark-serialize", "0.5.0"), + ("blst", "0.3.16"), + ("c-kzg", "2.1.7"), + ("p256", "0.13.2"), + ("primeorder", "0.13.6"), + ("k256", "0.13.4"), + ("ecdsa", "0.16.9"), + ("elliptic-curve", "0.13.8"), + ("crypto-bigint", "0.5.5"), + // Hashing and word arithmetic. + ("alloy-primitives", "1.6.0"), + ("ruint", "1.17.2"), + ("sha3", "0.11.0"), + ("keccak", "0.2.0"), + // Encodings: access lists and authorizations, trie paths, the FastLZ size the L1 fee is + // priced on, and the roots a dumped fixture carries. + ("alloy-eip2930", "0.2.3"), + ("alloy-eip7702", "0.6.3"), + ("nybbles", "0.4.3"), + ("op-alloy-flz", "0.13.1"), + ("triehash", "0.8.4"), + ("rlp", "0.5.2"), + ("hash-db", "0.15.2"), +]; + +/// The packages of the legacy leg's encodings that the Satin engine's alloy 2 line holds above +/// the released version: `(name, locked, released)`. The alloy 2 line the workspace locks (2.1) +/// requires `alloy-rlp` 0.3.14, `alloy-trie` 0.9.2 and `alloy-sol-types` 1.6.0 at least, so the leg +/// runs these at `locked`. +const AHEAD_OF_THE_RELEASE: &[(&str, &str, &str)] = &[ + ("alloy-rlp", "0.3.16", "0.3.12"), + ("alloy-rlp-derive", "0.3.16", "0.3.12"), + ("alloy-trie", "0.9.5", "0.9.0"), + ("alloy-sol-types", "1.6.0", "1.4.1"), + ("alloy-sol-macro", "1.6.0", "1.4.1"), + ("alloy-sol-macro-expander", "1.6.0", "1.4.1"), + ("alloy-sol-macro-input", "1.6.0", "1.4.1"), + ("syn-solidity", "1.6.0", "1.4.1"), +]; + +/// Every `(name, version)` package in `lockfile`. +fn locked_packages(lockfile: &str) -> Vec<(&str, &str)> { + lockfile + .split("[[package]]") + .skip(1) + .filter_map(|entry| { + let field = |key: &str| { + entry.lines().find_map(|line| { + line.strip_prefix(key)?.strip_prefix(" = \"")?.strip_suffix('"') + }) + }; + Some((field("name")?, field("version")?)) + }) + .collect() +} + +/// The semver-compatibility line of `version`: its major, or `0.minor` below 1. +fn compatibility_line(version: &str) -> &str { + let mut parts = version.splitn(3, '.'); + let major = parts.next().unwrap_or_default(); + if major == "0" { + let minor_len = parts.next().map_or(0, str::len); + &version[..major.len() + 1 + minor_len] + } else { + major + } +} + +/// The versions of `name` the lockfile holds on `pinned`'s compatibility line. +fn locked_on_the_line_of<'a>(locked: &[(&str, &'a str)], name: &str, pinned: &str) -> Vec<&'a str> { + let line = compatibility_line(pinned); + locked + .iter() + .filter(|(n, v)| *n == name && compatibility_line(v) == line) + .map(|(_, v)| *v) + .collect() +} + +#[test] +fn test_the_legacy_line_is_at_its_released_versions() { + let locked = locked_packages(LOCKFILE); + for &(name, pinned) in LEGACY_LINE { + let versions = locked_on_the_line_of(&locked, name, pinned); + assert_eq!( + versions, + [pinned], + "{name}: the legacy line resolves {versions:?}, the 1.7.1 release shipped {pinned}" + ); + } +} + +#[test] +fn test_the_packages_ahead_of_the_release_stay_where_they_are() { + let locked = locked_packages(LOCKFILE); + for &(name, pinned, released) in AHEAD_OF_THE_RELEASE { + assert_ne!(pinned, released, "{name} is at its released version: move it to the line"); + let versions = locked_on_the_line_of(&locked, name, pinned); + assert_eq!( + versions, + [pinned], + "{name}: the legacy leg resolves {versions:?}, pinned at {pinned} (released {released})" + ); + } +} + +#[test] +fn test_the_lockfile_parser_reads_packages() { + let lock = "[[package]]\nname = \"revm\"\nversion = \"27.1.0\"\nsource = \"registry\"\n\n\ + [[package]]\nname = \"revm\"\nversion = \"40.0.3\"\n"; + assert_eq!(locked_packages(lock), [("revm", "27.1.0"), ("revm", "40.0.3")]); + assert_eq!(compatibility_line("27.1.0"), "27"); + assert_eq!(compatibility_line("0.18.14"), "0.18"); + assert_eq!(compatibility_line("2.0.0-alpha.1"), "2"); +} diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs new file mode 100644 index 000000000..a8fe8c507 --- /dev/null +++ b/bin/mega-evme/tests/limits.rs @@ -0,0 +1,290 @@ +//! `--override.limits` on `run` and `tx`: a Satin transaction held to protocol limits other than +//! the spec's, the fields the override names replacing the spec's and every other staying. + +use std::process::Command; + +use mega_evm::{MegaSpecId, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE}; +use serde_json::{json, Value}; + +/// Two fresh `SSTORE`s, keeping two write records: 310 bytes of body and 40 per record. +const TWO_WRITES: &str = "0x60016000556001600155"; + +/// A transaction data-size limit with room for the body and one write record, which the second of +/// [`TWO_WRITES`] crosses. +const ONE_RECORD: u64 = TX_BODY_SIZE + WRITE_RECORD_SIZE; + +/// What [`TWO_WRITES`] keeps: the body and its two write records. +const TWO_RECORDS: u64 = ONE_RECORD + WRITE_RECORD_SIZE; + +struct Output { + code: i32, + stdout: String, + stderr: String, +} + +impl Output { + fn json(&self) -> Value { + assert_eq!(self.code, 0, "{}", self.stderr); + serde_json::from_str(&self.stdout).unwrap() + } +} + +fn evme(args: &[&str]) -> Output { + let output = Command::new(env!("CARGO_BIN_EXE_mega-evme")).args(args).output().unwrap(); + Output { + code: output.status.code().unwrap(), + stdout: String::from_utf8(output.stdout).unwrap(), + stderr: String::from_utf8(output.stderr).unwrap(), + } +} + +/// `run --spec Satin` of [`TWO_WRITES`], under `limits` when given. +fn run_two_writes(limits: Option<&str>) -> Value { + let mut args = vec!["run", TWO_WRITES, "--spec", "Satin", "--json"]; + if let Some(limits) = limits { + args.extend(["--override.limits", limits]); + } + evme(&args).json() +} + +/// Satin's limits with `txDataSizeLimit` at `limit`, as a report carries them. +fn defaults_with_tx_data_size(limit: u64) -> Value { + let mut limits = serde_json::to_value(ProtocolLimits::for_spec(MegaSpecId::SATIN)).unwrap(); + limits["txRuntimeLimits"]["txDataSizeLimit"] = json!(limit); + limits +} + +/// Without an override the run keeps both writes; an override of the transaction data size stops +/// it at the second write, and takes both back. A run under an override reports the limits it ran +/// under, and one on the spec's limits reports none. +#[test] +fn test_an_override_holds_a_satin_run_to_other_limits() { + let kept = run_two_writes(None); + assert_eq!(kept["success"], true); + assert_eq!(kept["satin"]["data_size"], 390); + assert_eq!(kept["satin"]["write_records"], 2); + assert_eq!(kept["satin"]["limit_exceeded"], Value::Null); + assert!(kept["satin"].get("limits_override").is_none(), "{}", kept["satin"]); + + let data_size = run_two_writes(Some(r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#)); + assert_eq!(data_size["success"], false); + assert_eq!( + data_size["satin"]["limit_exceeded"], + json!({ "kind": "data_size", "limit": 350, "used": 390 }) + ); + assert_eq!(data_size["satin"]["write_records"], 0, "the stop takes the writes back"); + assert_eq!(data_size["satin"]["limits_override"], defaults_with_tx_data_size(350)); +} + +/// The override is read from a file as it is given inline. +#[test] +fn test_an_override_is_read_from_a_file() { + let limits = r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("limits.json"); + std::fs::write(&path, limits).unwrap(); + let mut from_file = run_two_writes(Some(path.to_str().unwrap())); + let mut inline = run_two_writes(Some(limits)); + for output in [&mut from_file, &mut inline] { + output.as_object_mut().unwrap().remove("exec_time"); + } + assert_eq!(from_file, inline); +} + +/// `tx` takes the override too: a body one byte over the transaction data-size limit is rejected +/// at validation, and a limit the body fits runs it and names the override. +#[test] +fn test_an_override_holds_a_satin_tx_to_other_limits() { + let args = ["tx", "--spec", "Satin", "--input", "0x00", "--json", "--override.limits"]; + let limit = |bytes: u64| format!(r#"{{"txRuntimeLimits":{{"txDataSizeLimit":{bytes}}}}}"#); + let rejected = evme(&[&args[..], &[limit(310).as_str()]].concat()); + assert_ne!(rejected.code, 0, "{}", rejected.stdout); + assert!( + rejected.stderr.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), + "{}", + rejected.stderr + ); + + let ran = evme(&[&args[..], &[limit(311).as_str()]].concat()).json(); + assert_eq!(ran["success"], true); + assert_eq!(ran["satin"]["limit_exceeded"], Value::Null); + assert_eq!(ran["satin"]["limits_override"], defaults_with_tx_data_size(311)); +} + +/// The human-readable report names the limits a run was held to under an override, and says +/// nothing of them otherwise. +#[test] +fn test_the_report_names_an_override() { + let limits = r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#; + let overridden = evme(&["run", TWO_WRITES, "--spec", "Satin", "--override.limits", limits]); + assert_eq!(overridden.code, 0, "{}", overridden.stderr); + let line = overridden + .stdout + .lines() + .find(|line| line.starts_with("Limits Override:")) + .unwrap_or_else(|| panic!("no override line: {}", overridden.stdout)); + let named: Value = serde_json::from_str(line["Limits Override:".len()..].trim()).unwrap(); + assert_eq!(named, defaults_with_tx_data_size(350)); + + let plain = evme(&["run", TWO_WRITES, "--spec", "Satin"]); + assert_eq!(plain.code, 0, "{}", plain.stderr); + assert!(!plain.stdout.contains("Limits Override"), "{}", plain.stdout); +} + +/// An override is held to the limits' shape: an unknown field or a value of the wrong type is an +/// error, with nothing on stdout. Any value of the right type is a counterfactual the tool runs, +/// a limit of zero included. +#[test] +fn test_an_override_of_the_wrong_shape_is_refused() { + let run = |limits: &str| { + evme(&["run", "0x00", "--spec", "Satin", "--json", "--override.limits", limits]) + }; + let refused = |limits: &str, code: i32, message: &str| { + let output = run(limits); + assert_eq!(output.code, code, "{limits}: {}", output.stderr); + assert!(output.stdout.is_empty(), "{limits}: {}", output.stdout); + assert!(output.stderr.contains(message), "{limits}: {}", output.stderr); + }; + refused(r#"{"txDataSizeLimit":350}"#, 1, "unknown field `txDataSizeLimit`"); + refused(r#"{"blockTxsDataLimit":"1"}"#, 1, "--override.limits: invalid type"); + refused("[1]", 2, "must be a JSON object"); + + let zero = run(r#"{"txRuntimeLimits":{"frameDataSizeLimit":0}}"#).json(); + assert_eq!(zero["satin"]["limits_override"]["txRuntimeLimits"]["frameDataSizeLimit"], 0); +} + +/// A command on a legacy spec, the default one included, is refused with the override before it +/// reaches the released CLI, which knows no such flag: `run`, `tx` and a transaction replay. +#[test] +fn test_an_override_is_refused_on_a_legacy_spec() { + for args in [ + &["run", "0x00", "--override.limits", "{}"][..], + &["run", "0x00", "--spec", "Rex3", "--override.limits", "{}"], + &["tx", "--spec", "Rex6", "--override.limits", "{}"], + // The engine comes from the forced spec, so the refusal needs no RPC. + &[ + "replay", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "--override.spec", + "Rex6", + "--override.limits", + "{}", + ], + ] { + let output = evme(args); + assert_eq!(output.code, 1, "{args:?}: {}", output.stderr); + assert!(output.stdout.is_empty(), "{args:?}: {}", output.stdout); + assert!( + output.stderr.contains("--override.limits applies to Satin only"), + "{args:?}: {}", + output.stderr + ); + } +} + +/// A genesis file for chain `chain_id` activating Satin at `satin_time`, in `dir`. +fn genesis(dir: &tempfile::TempDir, chain_id: u64, satin_time: u64) -> String { + let satin = mega_evm::SatinChainConfig { activation_time: satin_time }; + let mut config = serde_json::to_value(satin).unwrap(); + config["chainId"] = json!(chain_id); + let path = dir.path().join(format!("genesis-{chain_id}-{satin_time}.json")); + std::fs::write(&path, json!({ "config": config }).to_string()).unwrap(); + path.to_str().unwrap().to_string() +} + +/// A genesis file configures a chain, not its limits: a Satin run given its chain's file is held to +/// Satin's limits, and keeps both writes. `run` and `tx` run Satin under the file without being +/// told `--spec Satin`. +#[test] +fn test_a_genesis_file_runs_satin_under_the_specs_limits() { + let dir = tempfile::tempdir().unwrap(); + let genesis = genesis(&dir, 6342, 0); + let run = |extra: &[&str]| { + let args = [&["run", TWO_WRITES, "--json", "--genesis", &genesis], extra]; + evme(&args.concat()) + }; + for spec in [&["--spec", "Satin"][..], &[]] { + let kept = run(spec).json(); + assert_eq!(kept["success"], true, "{spec:?}"); + assert_eq!(kept["satin"]["data_size"], TWO_RECORDS, "{spec:?}"); + assert_eq!(kept["satin"]["limit_exceeded"], Value::Null, "{spec:?}"); + assert!(kept["satin"].get("limits_override").is_none(), "{}", kept["satin"]); + } + let tx = evme(&["tx", "--input", "0x00", "--json", "--genesis", &genesis]).json(); + assert_eq!(tx["success"], true); + assert_eq!(tx["satin"]["data_size"], 311, "a Satin report: {tx}"); + + // An override replaces what it names under the file too. + let limits = format!(r#"{{"txRuntimeLimits":{{"txDataSizeLimit":{ONE_RECORD}}}}}"#); + let overridden = run(&["--override.limits", &limits]).json(); + assert_eq!( + overridden["satin"]["limit_exceeded"], + json!({ "kind": "data_size", "limit": ONE_RECORD, "used": TWO_RECORDS }) + ); + + // The file is its chain's: a run on another chain is refused. + let other = run(&["--chain-id", "6343"]); + assert_eq!(other.code, 1, "{}", other.stderr); + assert!(other.stderr.contains("--genesis configures chain 6342"), "{}", other.stderr); +} + +/// A run the file cannot configure is refused rather than run on the engine's own schedule: one +/// before the file's `satinTime`, and one on a file without Satin keys. From the file's +/// `satinTime` on, the run is made. +#[test] +fn test_a_genesis_file_refuses_a_run_it_cannot_configure() { + const SATIN_TIME: &str = "1800000000"; + let dir = tempfile::tempdir().unwrap(); + let later = genesis(&dir, 6342, SATIN_TIME.parse().unwrap()); + let without_satin = dir.path().join("without-satin.json"); + std::fs::write(&without_satin, json!({ "config": { "chainId": 6342 } }).to_string()).unwrap(); + let without_satin = without_satin.to_str().unwrap(); + + let refused = |args: &[&str], message: &str| { + let output = evme(args); + assert_eq!(output.code, 1, "{args:?}: {}", output.stderr); + assert!(output.stdout.is_empty(), "{args:?}: {}", output.stdout); + assert!(output.stderr.contains(message), "{args:?}: {}", output.stderr); + }; + let before = "--genesis activates Satin at timestamp 1800000000, and the run is at timestamp"; + for command in [&["run", TWO_WRITES][..], &["tx", "--input", "0x00"]] { + for spec in [&["--spec", "Satin"][..], &[]] { + let args = [command, spec, &["--json", "--genesis", &later]].concat(); + refused(&args, &format!("{before} 1:")); + let args = [&args[..], &["--block.timestamp", "1799999999"]].concat(); + refused(&args, &format!("{before} 1799999999:")); + let args = [command, spec, &["--json", "--genesis", without_satin]].concat(); + refused(&args, "--genesis: the file has no Satin keys"); + } + } + + let from = + evme(&["run", TWO_WRITES, "--json", "--genesis", &later, "--block.timestamp", SATIN_TIME]) + .json(); + assert_eq!(from["success"], true); + assert_eq!(from["satin"]["data_size"], TWO_RECORDS); +} + +/// The file applies to Satin only: a command on a legacy spec is refused with it, as with an +/// override, before it reaches the released CLI. The chain is checked first: a legacy run on +/// another chain than the file's is refused for its chain. +#[test] +fn test_a_genesis_file_is_refused_on_a_legacy_spec() { + let dir = tempfile::tempdir().unwrap(); + let genesis = genesis(&dir, 6342, 0); + for command in [&["run", "0x00"][..], &["tx", "--input", "0x00"]] { + let args = [command, &["--spec", "Rex6", "--genesis", &genesis]].concat(); + let output = evme(&args); + assert_eq!(output.code, 1, "{args:?}: {}", output.stderr); + assert!(output.stderr.contains("--genesis applies to Satin only"), "{}", output.stderr); + + let args = [&args[..], &["--chain-id", "4326"]].concat(); + let output = evme(&args); + assert_eq!(output.code, 1, "{args:?}: {}", output.stderr); + assert!( + output.stderr.contains("--genesis configures chain 6342, and the run is on chain 4326"), + "{}", + output.stderr + ); + } +} diff --git a/bin/mega-evme/tests/provider.rs b/bin/mega-evme/tests/provider.rs index f575964f8..bfc24c798 100644 --- a/bin/mega-evme/tests/provider.rs +++ b/bin/mega-evme/tests/provider.rs @@ -18,7 +18,7 @@ use mega_evme::common::{BuildProviderOutput, EvmeError, RpcArgs}; use tempfile::tempdir; mod common; -use common::{test_rpc_args, test_rpc_args_cached, MockRpcServer}; +use common::{rpc_cache_path, test_rpc_args, test_rpc_args_cached, MockRpcServer}; // ─── CLI parsing ───────────────────────────────────────────────────────────── @@ -137,7 +137,10 @@ async fn test_build_provider_with_cache_names_file_from_fetched_chain_id() { let BuildProviderOutput { cache_store, .. } = args.build_provider().await.expect("build_provider"); assert!(!cache_store.is_noop(), "cache_size > 0 + cache_dir must produce a real store"); - assert_eq!(cache_store.cache_path(), Some(dir.path().join("rpc-cache-4326.json").as_path())); + assert_eq!( + cache_store.cache_path(), + Some(rpc_cache_path(dir.path(), 4326, &server.uri()).as_path()) + ); } #[tokio::test(flavor = "multi_thread")] @@ -152,6 +155,27 @@ async fn test_build_provider_invalid_url() { } } +/// A chain-id failure reports the endpoint without the URL's userinfo. +#[tokio::test(flavor = "multi_thread")] +async fn test_chain_id_error_omits_rpc_userinfo() { + let server = MockRpcServer::start().await; + server.respond_status_always(500).await; + let url = server.uri().replacen("http://", "http://alice:secret@", 1); + let args = RpcArgs::parse_from([ + "mega-evme", + "--rpc", + &url, + "--rpc.cache-size", + "0", + "--rpc.max-retries", + "0", + ]); + let err = args.build_provider().await.expect_err("chain id fetch fails"); + let msg = err.to_string(); + assert!(msg.contains("Failed to fetch chain ID"), "{msg}"); + assert!(!msg.contains("secret") && !msg.contains("alice"), "{msg}"); +} + // ─── Chain-id resolution ───────────────────────────────────────────────────── /// `build_provider` must call `eth_chainId` against the endpoint, name the @@ -179,8 +203,8 @@ async fn test_build_provider_fetches_chain_id_from_rpc() { args.build_provider().await.expect("build_provider"); assert_eq!( cache_store.cache_path(), - Some(dir.path().join("rpc-cache-4326.json").as_path()), - "cache file must be named after the fetched chain id", + Some(rpc_cache_path(dir.path(), 4326, &server.uri()).as_path()), + "cache file must be named after the fetched chain id and the endpoint", ); assert_eq!(chain_id, 4326, "chain_id must match the fetched value"); assert!( @@ -242,7 +266,7 @@ async fn test_atomic_save_round_trip() { cache_store.cache().expect("real store").put(key, value.clone()).expect("seed put"); cache_store.persist().expect("persist"); - let cache_file = dir.path().join("rpc-cache-4326.json"); + let cache_file = rpc_cache_path(dir.path(), 4326, &server.uri()); assert!(cache_file.exists(), "save must produce the target file"); // Atomic save uses a temp file in the same parent dir; nothing should remain. @@ -276,12 +300,40 @@ async fn test_build_provider_tolerates_missing_or_corrupt_cache_file() { assert!(cache_store.cache().expect("real store").get(&B256::ZERO).is_none()); // Corrupt file — load fails, cache starts empty. - std::fs::write(dir.path().join("rpc-cache-42.json"), b"not json").expect("write corrupt"); + std::fs::write(rpc_cache_path(dir.path(), 42, &server.uri()), b"not json") + .expect("write corrupt"); let BuildProviderOutput { cache_store, .. } = args.build_provider().await.expect("corrupt file"); assert!(cache_store.cache().expect("real store").get(&B256::ZERO).is_none()); } +/// `--rpc.clear-cache` deletes the on-disk file even when `--rpc.cache-size 0` disables the +/// cache. The next run that turns the cache back on must not reload it. +#[tokio::test(flavor = "multi_thread")] +async fn test_clear_cache_deletes_the_file_when_the_cache_is_disabled() { + let server = MockRpcServer::start().await; + server.respond_eth_chain_id(4326, 1).await; + + let dir = tempdir().expect("tempdir"); + let cache_file = rpc_cache_path(dir.path(), 4326, &server.uri()); + std::fs::write(&cache_file, b"{}").expect("write seed"); + + let args = RpcArgs::parse_from([ + "mega-evme", + "--rpc", + &server.uri(), + "--rpc.cache-size", + "0", + "--rpc.cache-dir", + dir.path().to_str().unwrap(), + "--rpc.clear-cache", + ]); + let BuildProviderOutput { cache_store, .. } = + args.build_provider().await.expect("build_provider"); + assert!(cache_store.is_noop(), "cache_size == 0 stays a no-op store"); + assert!(!cache_file.exists(), "clear-cache must delete the file while the cache is disabled"); +} + /// `--rpc.clear-cache` must remove the file before load so the new session /// starts empty even when a previous file existed. #[tokio::test(flavor = "multi_thread")] @@ -290,7 +342,7 @@ async fn test_build_provider_clear_cache_deletes_file_before_load() { server.respond_eth_chain_id(99, 1).await; let dir = tempdir().expect("tempdir"); - let cache_file = dir.path().join("rpc-cache-99.json"); + let cache_file = rpc_cache_path(dir.path(), 99, &server.uri()); // Phase 1: populate and persist to disk. let seed_args = test_rpc_args_cached(&server.uri(), dir.path(), None); @@ -343,7 +395,7 @@ async fn test_build_provider_clear_cache_hard_errors_on_unlink_failure() { let dir = tempdir().expect("tempdir"); let chain_id: u64 = 88; // Seed a "polluted" cache file the user would want to wipe. - let cache_file = dir.path().join(format!("rpc-cache-{chain_id}.json")); + let cache_file = rpc_cache_path(dir.path(), chain_id, &server.uri()); std::fs::write(&cache_file, r#"{"polluted":"content"}"#).expect("write seed"); // Revoke write permission on the parent dir so `remove_file` fails. @@ -403,7 +455,7 @@ async fn test_build_provider_auto_creates_cache_dir() { assert!(fresh_dir.exists(), "build_provider must create the cache directory"); store.persist().expect("persist"); assert!( - fresh_dir.join("rpc-cache-4326.json").exists(), + rpc_cache_path(&fresh_dir, 4326, &server.uri()).exists(), "persist must write the per-chain file", ); } diff --git a/bin/mega-evme/tests/replay_dump.rs b/bin/mega-evme/tests/replay_dump.rs index 516e06619..85d96ffc1 100644 --- a/bin/mega-evme/tests/replay_dump.rs +++ b/bin/mega-evme/tests/replay_dump.rs @@ -5,8 +5,11 @@ //! (`fixtures/replay_offline.cache.json`, which includes the on-chain receipt), //! so it is deterministic: the tests dump a fixture, validate the written file //! with the state-test runner, check byte-reproducibility, and verify the -//! transaction-override and `--override.spec` guards. (Benchmarking lives in -//! `state-test --bench`; see `bench/replay/`.) +//! transaction-override and `--override.spec` guards. +//! +//! The dump is the legacy leg's: the transaction replays on the released 1.7.1 CLI, and the +//! fixture is validated by the 1.7.1 state-test runner. +#![cfg(feature = "legacy")] use std::{ process::Command, @@ -78,7 +81,7 @@ fn test_replay_dump_fixture_writes_validatable_file() { // Validate the dumped fixture through the state-test runner (no RPC). let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - let result = state_test::runner::execute_test_suite(&out, &elapsed, false, false); + let result = mega_state_test_legacy::runner::execute_test_suite(&out, &elapsed, false, false); let _ = std::fs::remove_file(&out); result.unwrap_or_else(|e| panic!("dumped fixture failed to validate: {e}")); } diff --git a/bin/mega-evme/tests/replay_paths.rs b/bin/mega-evme/tests/replay_paths.rs new file mode 100644 index 000000000..4762cf033 --- /dev/null +++ b/bin/mega-evme/tests/replay_paths.rs @@ -0,0 +1,674 @@ +//! A transaction replayed alone, over RPC, is the same transaction the block replay runs. +//! +//! `replay ` forks the parent block's state lazily over RPC and runs the block's +//! earlier transactions first; `replay --block` runs the whole block on the pre-state recorded +//! with it. The two paths share no state source, so their agreeing on every transaction checked +//! here is evidence for both: on the legacy engine (the 1.7.1 CLI against the chain's receipts) +//! and on Satin (the in-tree port against the block driver). +//! +//! The RPC is a mock that answers only from the recorded block: a read the recording does not +//! hold is an error, not a guess. The two exceptions are what Satin's pre-block changes read and +//! no recording holds: the EIP-7997 factory, which Satin's activation block checks, served with +//! its code as the chain holds it, and the L1 block contract's L1 fee overhead, served as zero, as +//! the chain held it. `block_replay.rs` shows the overhead changes no transaction row. +#![cfg(feature = "legacy")] + +mod common; + +use std::{ + collections::{BTreeMap, HashMap}, + sync::Arc, +}; + +use alloy_primitives::{address, Address, B256, U256}; +use common::blocks::{ + cache_copy_for_satin, code_of, factory_account, fixtures, is_deposit, overhead_slot, + read_block, run_evme, satin_genesis, timestamp_of, FACTORY, L1_BLOCK, +}; +use mega_evme::block::{CachedBlock, PreAccount}; +use serde_json::{json, Value}; +use wiremock::{matchers, Mock, MockServer, Respond, ResponseTemplate}; + +const BLOCK: u64 = 26_400_110; + +/// Answers JSON-RPC from the recorded block alone. +struct Recording { + block: CachedBlock, + /// The parent block's timestamp; the block's own when not given. + parent_timestamp: Option, + /// Code a test added to the recording, by hash. + codes: HashMap>, +} + +impl Recording { + fn account(&self, address: Address) -> Option { + match self.block.prestate.accounts.get(&address) { + Some(account) if address == L1_BLOCK => { + let mut account = account.clone(); + account.storage.entry(overhead_slot()).or_insert(U256::ZERO); + Some(account) + } + Some(account) => Some(account.clone()), + None if address == FACTORY => Some(factory_account()), + None => None, + } + } + + fn parent(&self) -> Value { + let mut parent = self.block.block.clone(); + parent["number"] = json!(format!("0x{:x}", BLOCK - 1)); + parent["hash"] = self.block.block["parentHash"].clone(); + parent["transactions"] = json!([]); + if let Some(timestamp) = self.parent_timestamp { + parent["timestamp"] = json!(format!("0x{timestamp:x}")); + } + parent + } + + fn result(&self, method: &str, params: &[Value]) -> Result { + let block_arg = |i: usize| params.get(i).and_then(Value::as_str).unwrap_or_default(); + let at_parent = |i: usize| block_arg(i) == format!("0x{:x}", BLOCK - 1); + let address = || -> Result { + serde_json::from_value(params[0].clone()).map_err(|e| e.to_string()) + }; + match method { + "eth_chainId" => Ok(json!("0x10e6")), + "eth_getTransactionByHash" => self.block.block["transactions"] + .as_array() + .unwrap() + .iter() + .find(|tx| tx["hash"] == params[0]) + .cloned() + .ok_or_else(|| "unknown transaction".to_string()), + "eth_getTransactionReceipt" => self + .block + .receipts + .as_array() + .unwrap() + .iter() + .find(|r| r["transactionHash"] == params[0]) + .cloned() + .ok_or_else(|| "unknown receipt".to_string()), + "eth_getBlockByNumber" if block_arg(0) == format!("0x{BLOCK:x}") => { + let mut block = self.block.block.clone(); + if params.get(1) == Some(&json!(false)) { + let hashes: Vec = block["transactions"] + .as_array() + .unwrap() + .iter() + .map(|tx| tx["hash"].clone()) + .collect(); + block["transactions"] = Value::Array(hashes); + } + Ok(block) + } + "eth_getBlockByNumber" if at_parent(0) => Ok(self.parent()), + "eth_getBalance" | "eth_getTransactionCount" | "eth_getCode" if at_parent(1) => { + let account = self.account(address()?).ok_or("account not recorded")?; + Ok(match method { + "eth_getBalance" => json!(account.balance), + "eth_getTransactionCount" => json!(format!("0x{:x}", account.nonce)), + _ => json!(account + .code_hash + .map(|hash| { + let code = + self.codes.get(&hash).cloned().unwrap_or_else(|| code_of(hash)); + alloy_primitives::hex::encode_prefixed(code) + }) + .unwrap_or_else(|| "0x".to_string())), + }) + } + "eth_getStorageAt" if at_parent(2) => { + let account = self.account(address()?).ok_or("account not recorded")?; + let slot: U256 = + serde_json::from_value(params[1].clone()).map_err(|e| e.to_string())?; + account + .storage + .get(&B256::from(slot)) + .map(|value| json!(B256::from(*value))) + .ok_or_else(|| "slot not recorded".to_string()) + } + _ => Err(format!("not recorded: {method} {params:?}")), + } + } +} + +impl Respond for Recording { + fn respond(&self, request: &wiremock::Request) -> ResponseTemplate { + let body: Value = serde_json::from_slice(&request.body).unwrap(); + let params = body["params"].as_array().cloned().unwrap_or_default(); + let reply = match self.result(body["method"].as_str().unwrap(), ¶ms) { + Ok(result) => json!({ "jsonrpc": "2.0", "id": body["id"], "result": result }), + Err(message) => json!({ + "jsonrpc": "2.0", + "id": body["id"], + "error": { "code": -32000, "message": message }, + }), + }; + ResponseTemplate::new(200).set_body_json(reply) + } +} + +struct Server(Arc); + +impl Server { + async fn start(block: CachedBlock) -> Self { + Self::with_parent_at(block, None).await + } + + /// A server whose parent block is at `parent_timestamp`, or at the block's own timestamp. + async fn with_parent_at(block: CachedBlock, parent_timestamp: Option) -> Self { + Self::with_codes(block, parent_timestamp, HashMap::default()).await + } + + /// A server that also serves `codes`, by hash, for accounts a test added to the block. + async fn with_codes( + block: CachedBlock, + parent_timestamp: Option, + codes: HashMap>, + ) -> Self { + let server = MockServer::start().await; + Mock::given(matchers::method("POST")) + .respond_with(Recording { block, parent_timestamp, codes }) + .mount(&server) + .await; + Self(Arc::new(server)) + } +} + +/// The block replay's transaction records, on `spec`'s engine, under `limits` when given. +fn block_rows(spec: Option<&str>, limits: Option<&str>) -> Vec { + let cache = cache_copy_for_satin(); + let mut args = vec!["replay", "--block", "26400110", "--json", "--block-cache"]; + args.push(cache.path().to_str().unwrap()); + if let Some(spec) = spec { + args.extend(["--override.spec", spec]); + } + if let Some(limits) = limits { + args.extend(["--override.limits", limits]); + } + let run = run_evme(&args); + assert_eq!(run.code, 0, "{}", run.stderr); + run.records().into_iter().filter(|record| record["kind"] == "tx").collect() +} + +/// The transactions checked: the first user transaction, the plain value transfer, one in the +/// middle, the first a limit stopped, the one at `held`, and the last the block ran before it +/// refused one. +/// +/// A Satin replay can refuse a transaction the chain included, for the block gas it declared. +/// The selection stops there: a later transaction of the same block may itself be refused for +/// the gas it declared, and this comparison is about transactions the block included. A replay +/// of one transaction skips a predecessor the executor refuses and still runs, which +/// [`test_a_replay_skips_a_refused_predecessor_and_keeps_its_state`] holds. +fn checked(rows: &[Value], held: Option) -> Vec { + let ran = rows.iter().position(|row| row["status"] == "refused").unwrap_or(rows.len()); + let rows = &rows[..ran]; + let transfer = rows.iter().position(|row| row["logs"] == 0 && row["index"] != 0).unwrap_or(1); + let stopped = rows.iter().position(|row| !row["satin"]["limit_exceeded"].is_null()); + let mut picks = vec![1, transfer, rows.len() / 2, rows.len() - 1]; + picks.extend(stopped); + picks.extend(held.filter(|held| *held < ran)); + picks.sort_unstable(); + picks.dedup(); + picks +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_a_transaction_replayed_alone_is_the_one_the_block_replay_runs() { + let recorded = read_block(fixtures(), BLOCK); + let server = Server::start(recorded).await; + let uri = server.0.uri(); + + // The last leg holds both paths to a transaction data-size limit one byte below the most a + // transaction of the block keeps, which stops the frame of that transaction that crosses it: + // the transaction keeps less than it did, whether that frame was its own or a caller caught + // the stop. + let unlimited = block_rows(Some("Satin"), None); + let kept = |row: &Value| row["satin"]["data_size"].as_u64(); + let most = unlimited.iter().filter_map(kept).max().expect("the block keeps data"); + let heaviest = unlimited.iter().position(|row| kept(row) == Some(most)); + let holding = format!(r#"{{"txRuntimeLimits":{{"txDataSizeLimit":{}}}}}"#, most - 1); + let mut held = 0; + for (spec, engine, limits) in [ + (None, "legacy", None), + (Some("Satin"), "satin", None), + (Some("Satin"), "satin", Some(holding.as_str())), + ] { + let rows = block_rows(spec, limits); + let heaviest = heaviest.filter(|_| limits.is_some()); + for index in checked(&rows, heaviest) { + let row = &rows[index]; + let mut args = vec!["replay", row["hash"].as_str().unwrap(), "--rpc", &uri]; + args.extend(["--rpc.no-cache-file", "--rpc.max-retries", "0", "--json"]); + if let Some(spec) = spec { + args.extend(["--override.spec", spec]); + } + if let Some(limits) = limits { + args.extend(["--override.limits", limits]); + if heaviest == Some(index) { + assert!(kept(row).is_some_and(|kept| kept < most), "the limit held tx {index}"); + held += 1; + } + } + let run = run_evme(&args); + assert_eq!(run.code, 0, "{engine} tx {index}: {}{}", run.stderr, run.stdout); + let mut single: Value = serde_json::from_str(&run.stdout).unwrap(); + // A transaction replayed alone reports the limits an override held it to; a block's + // record reports them for its transactions. + let overridden = single + .get_mut("satin") + .and_then(|satin| satin.as_object_mut().unwrap().remove("limits_override")); + assert_eq!(overridden.is_some(), limits.is_some(), "{engine} tx {index}"); + assert_eq!(single["gas_used"], row["gas_used"], "{engine} tx {index}"); + assert_eq!(single["success"], row["status"] == "success", "{engine} tx {index}"); + assert_eq!(single["logs_count"], row["logs"], "{engine} tx {index}"); + assert_eq!( + single["receipt"]["cumulativeGasUsed"], + json!(format!("0x{:x}", row["cumulative_gas_used"].as_u64().unwrap())), + "{engine} tx {index}" + ); + if engine == "satin" { + assert_eq!(single["satin"], row["satin"], "Satin tx {index}: the ledgers agree"); + } else { + assert!(single.get("satin").is_none(), "the legacy output is 1.7.1's"); + assert_eq!(row["differs"], json!([]), "legacy tx {index} matches the chain"); + } + } + } + assert_eq!(held, 1, "the limits leg checks the transaction the limit held"); +} + +/// [S1.8] [S21.12] [S1] A transaction replay is told whether its block admits only deposits as a +/// node is, from the schedule and the parent block it forks. Under a genesis file that activates +/// Satin at the block's timestamp, with the parent a second earlier, the block is Satin's +/// activation block: a user transaction of it is refused for the rule, and its deposit replays. +/// With the parent at the block's own timestamp the user transaction replays. +/// +/// Expected values: independent. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_transaction_replay_refuses_a_user_transaction_in_an_activation_block() { + let recorded = read_block(fixtures(), BLOCK); + let timestamp = timestamp_of(&recorded); + assert!(is_deposit(&recorded, 0) && !is_deposit(&recorded, 1)); + let dir = tempfile::tempdir().unwrap(); + let genesis = satin_genesis(dir.path(), mega_evm::MAINNET_CHAIN_ID, timestamp); + let hash = |index: usize| recorded.block["transactions"][index]["hash"].as_str().unwrap(); + + for (parent_timestamp, activation) in [(timestamp - 1, true), (timestamp, false)] { + let server = + Server::with_parent_at(read_block(fixtures(), BLOCK), Some(parent_timestamp)).await; + let uri = server.0.uri(); + let run = |index: usize| { + run_evme(&[ + "replay", + hash(index), + "--rpc", + &uri, + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + "--json", + "--genesis", + &genesis, + ]) + }; + let deposit = run(0); + assert_eq!(deposit.code, 0, "the deposit replays: {}{}", deposit.stderr, deposit.stdout); + let user = run(1); + if activation { + assert_ne!(user.code, 0, "{}", user.stdout); + let output = format!("{}{}", user.stdout, user.stderr); + assert!( + output.contains("non-deposit transaction in fork activation block"), + "{output}" + ); + } else { + assert_eq!(user.code, 0, "the block after: {}{}", user.stderr, user.stdout); + } + } +} + +/// A replay of one transaction runs it on the state the block's included predecessors left, +/// and skips a predecessor the block executor refuses. +/// +/// The recorded block supplies the parent state and the header. Its transactions are replaced +/// by three calls: a value transfer, a call whose gas limit is below Satin's intrinsic cost, and +/// a later transfer that spends part of what the first one credited. The middle call is the +/// refusal. The last one succeeds only when the first one's credit is in the state it runs on, +/// and its receipt index counts the included predecessor alone. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_replay_skips_a_refused_predecessor_and_keeps_its_state() { + const PAYER: Address = address!("0x1111111111111111111111111111111111111111"); + const REFUSED: Address = address!("0x2222222222222222222222222222222222222222"); + const RECIPIENT: Address = address!("0x3333333333333333333333333333333333333333"); + /// One ether, the value the included predecessor credits. + const GIFT: u128 = 1_000_000_000_000_000_000; + /// Room above a value transfer that creates an account, at the spec's byte prices. + const GAS: u64 = 5_000_000; + + let mut recorded = read_block(fixtures(), BLOCK); + let ether = U256::from(GIFT); + recorded + .prestate + .accounts + .insert(PAYER, PreAccount { balance: ether * U256::from(10), ..PreAccount::default() }); + recorded + .prestate + .accounts + .insert(REFUSED, PreAccount { balance: ether, ..PreAccount::default() }); + recorded.prestate.accounts.insert(RECIPIENT, PreAccount::default()); + + let block_hash = recorded.block["hash"].clone(); + let block_number = recorded.block["number"].clone(); + let tx = |hash: &str, index: u64, from: Address, to: Address, gas: u64, value: U256| { + json!({ + "type": "0x2", + "chainId": "0x10e6", + "nonce": "0x0", + "gas": format!("0x{gas:x}"), + "maxFeePerGas": "0xf4240", + "maxPriorityFeePerGas": "0x0", + "to": to, + "value": format!("0x{value:x}"), + "accessList": [], + "input": "0x", + "r": "0x64c0524917585101b7ffb2286d4de676ca987554b33c6f9a37e7ad7508bfbb84", + "s": "0xe5199cacc6e07c6a9f8c74d0b06f964ce36dd362199b1c19d866f1a6f52d510", + "yParity": "0x1", + "v": "0x1", + "hash": hash, + "blockHash": block_hash, + "blockNumber": block_number, + "transactionIndex": format!("0x{index:x}"), + "from": from, + "gasPrice": "0xf4240", + }) + }; + let target = "0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + recorded.block["transactions"] = json!([ + tx( + "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + 0, + PAYER, + RECIPIENT, + GAS, + ether, + ), + tx( + "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + 1, + REFUSED, + RECIPIENT, + 1, + U256::ZERO, + ), + tx(target, 2, RECIPIENT, PAYER, GAS, U256::from(1)), + ]); + + let server = Server::start(recorded).await; + let uri = server.0.uri(); + let run = run_evme(&[ + "replay", + target, + "--rpc", + &uri, + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + "--override.spec", + "Satin", + "--json", + "--dump", + ]); + assert_eq!(run.code, 0, "{}{}", run.stderr, run.stdout); + let summary: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(summary["success"], true, "{summary}"); + // The refused predecessor is not an included transaction. The value transfer is. + assert_eq!(summary["receipt"]["transactionIndex"], "0x1", "{summary}"); + let cumulative = u64::from_str_radix( + summary["receipt"]["cumulativeGasUsed"].as_str().unwrap().trim_start_matches("0x"), + 16, + ) + .unwrap(); + assert!(cumulative > summary["gas_used"].as_u64().unwrap(), "{summary}"); + + let state = &summary["state"]; + let account = |address: Address| &state[&address.to_string()]; + let balance = |address: Address| -> U256 { + account(address)["balance"].as_str().unwrap().parse().unwrap() + }; + let nonce = |address: Address| { + u64::from_str_radix( + account(address)["nonce"].as_str().unwrap().trim_start_matches("0x"), + 16, + ) + .unwrap() + }; + // The payer's nonce is the included predecessor's bump. The recipient spends one wei of the + // ether that predecessor credited and keeps the rest. + assert_eq!(nonce(PAYER), 1, "{state}"); + assert_eq!(nonce(RECIPIENT), 1, "{state}"); + let left = balance(RECIPIENT); + assert!(left < ether && left > ether - U256::from(10u64.pow(16)), "{left} {state}"); +} + +/// A predecessor whose account the RPC cache cannot serve is a database failure. +/// +/// The mock answers an unrecorded account with an error. That is not a validation refusal, so +/// the replay stops instead of running the target on the parent state. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_replay_stops_when_a_predecessor_account_cannot_be_read() { + const PAYER: Address = address!("0x1111111111111111111111111111111111111111"); + const MISSING: Address = address!("0x4444444444444444444444444444444444444444"); + const RECIPIENT: Address = address!("0x3333333333333333333333333333333333333333"); + const GAS: u64 = 5_000_000; + + let mut recorded = read_block(fixtures(), BLOCK); + assert!( + !recorded.prestate.accounts.contains_key(&MISSING) && MISSING != FACTORY, + "the predecessor's sender has to be an account the cache cannot serve" + ); + recorded + .prestate + .accounts + .insert(PAYER, PreAccount { balance: U256::from(10u128.pow(18)), ..PreAccount::default() }); + recorded.prestate.accounts.insert(RECIPIENT, PreAccount::default()); + + let block_hash = recorded.block["hash"].clone(); + let block_number = recorded.block["number"].clone(); + let tx = |hash: &str, index: u64, from: Address, to: Address| { + json!({ + "type": "0x2", + "chainId": "0x10e6", + "nonce": "0x0", + "gas": format!("0x{GAS:x}"), + "maxFeePerGas": "0xf4240", + "maxPriorityFeePerGas": "0x0", + "to": to, + "value": "0x0", + "accessList": [], + "input": "0x", + "r": "0x64c0524917585101b7ffb2286d4de676ca987554b33c6f9a37e7ad7508bfbb84", + "s": "0xe5199cacc6e07c6a9f8c74d0b06f964ce36dd362199b1c19d866f1a6f52d510", + "yParity": "0x1", + "v": "0x1", + "hash": hash, + "blockHash": block_hash, + "blockNumber": block_number, + "transactionIndex": format!("0x{index:x}"), + "from": from, + "gasPrice": "0xf4240", + }) + }; + let target = "0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; + recorded.block["transactions"] = json!([ + tx( + "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + 0, + MISSING, + RECIPIENT, + ), + tx(target, 1, PAYER, RECIPIENT), + ]); + + let server = Server::start(recorded).await; + let uri = server.0.uri(); + let run = run_evme(&[ + "replay", + target, + "--rpc", + &uri, + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + "--override.spec", + "Satin", + ]); + assert_ne!(run.code, 0, "a failed predecessor read is not skipped: {}", run.stdout); + let output = format!("{}{}", run.stdout, run.stderr); + assert!(output.contains("Block execution error"), "{output}"); + assert!(output.contains("account not recorded"), "{output}"); +} + +/// A block of calls from one payer to contracts the test adds to the recorded block's parent +/// state, and the server that serves it. Each call is `(to, gas)`; the payer's nonce counts up. +struct SyntheticBlock { + server: Server, + /// Hash of the `index`-th call. + hashes: Vec, +} + +const PAYER: Address = address!("0x1111111111111111111111111111111111111111"); + +impl SyntheticBlock { + /// `contracts` are `(address, code, storage)` added to the parent state. + async fn start( + contracts: &[(Address, Vec, BTreeMap)], + calls: &[Address], + ) -> Self { + const GAS: u64 = 5_000_000; + let mut recorded = read_block(fixtures(), BLOCK); + recorded.prestate.accounts.insert( + PAYER, + PreAccount { balance: U256::from(10u128.pow(18)), ..PreAccount::default() }, + ); + let mut codes = HashMap::new(); + for (address, code, storage) in contracts { + let code_hash = alloy_primitives::keccak256(code); + codes.insert(code_hash, code.clone()); + recorded.prestate.accounts.insert( + *address, + PreAccount { + code_hash: Some(code_hash), + storage: storage.clone(), + ..Default::default() + }, + ); + } + let block_hash = recorded.block["hash"].clone(); + let block_number = recorded.block["number"].clone(); + let hashes: Vec = + (0..calls.len()).map(|i| format!("0x{:064x}", 0xa0 + i)).collect(); + recorded.block["transactions"] = Value::Array( + calls + .iter() + .enumerate() + .map(|(index, to)| { + json!({ + "type": "0x2", + "chainId": "0x10e6", + "nonce": format!("0x{index:x}"), + "gas": format!("0x{GAS:x}"), + "maxFeePerGas": "0xf4240", + "maxPriorityFeePerGas": "0x0", + "to": to, + "value": "0x0", + "accessList": [], + "input": "0x", + "r": "0x64c0524917585101b7ffb2286d4de676ca987554b33c6f9a37e7ad7508bfbb84", + "s": "0xe5199cacc6e07c6a9f8c74d0b06f964ce36dd362199b1c19d866f1a6f52d510", + "yParity": "0x1", + "v": "0x1", + "hash": hashes[index], + "blockHash": block_hash, + "blockNumber": block_number, + "transactionIndex": format!("0x{index:x}"), + "from": PAYER, + "gasPrice": "0xf4240", + }) + }) + .collect(), + ); + Self { server: Server::with_codes(recorded, None, codes).await, hashes } + } + + /// Replays the `index`-th call alone on Satin, with `--dump`. + fn replay(&self, index: usize) -> Value { + let uri = self.server.0.uri(); + let run = run_evme(&[ + "replay", + &self.hashes[index], + "--rpc", + &uri, + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + "--override.spec", + "Satin", + "--json", + "--dump", + ]); + assert_eq!(run.code, 0, "{}{}", run.stderr, run.stdout); + serde_json::from_str(&run.stdout).unwrap() + } +} + +/// A replay of one transaction numbers its logs in the block: after the logs of the included +/// predecessors it ran first, and its receipt carries the transaction's index and hash. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_replayed_log_carries_the_block_level_index() { + // PUSH0 PUSH0 LOG0 PUSH0 PUSH0 LOG0 STOP: two logs per call. + let logger = address!("0x5555555555555555555555555555555555555555"); + let code = vec![0x5f, 0x5f, 0xa0, 0x5f, 0x5f, 0xa0, 0x00]; + let block = + SyntheticBlock::start(&[(logger, code, BTreeMap::new())], &[logger, logger, logger]).await; + + for (index, first_log) in [(0usize, 0u64), (1, 2), (2, 4)] { + let summary = block.replay(index); + let logs = summary["receipt"]["logs"].as_array().unwrap(); + assert_eq!(logs.len(), 2, "{summary}"); + for (i, log) in logs.iter().enumerate() { + assert_eq!(log["logIndex"], format!("0x{:x}", first_log + i as u64), "tx {index}"); + assert_eq!(log["transactionIndex"], format!("0x{index:x}"), "tx {index}"); + assert_eq!(log["transactionHash"], block.hashes[index], "tx {index}"); + } + } +} + +/// A state dump of a replay carries the code of an account an included predecessor wrote and the +/// target only touched: the block's state keeps the code of every account it holds. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_replay_dump_carries_the_code_of_a_predecessors_account() { + // PUSH1 1 PUSH0 SSTORE STOP: writes slot 0. + let storer = address!("0x6666666666666666666666666666666666666666"); + let storer_code = vec![0x60, 0x01, 0x5f, 0x55, 0x00]; + // PUSH20 BALANCE POP STOP: touches the storer's account and loads no code. + let toucher = address!("0x7777777777777777777777777777777777777777"); + let mut toucher_code = vec![0x73]; + toucher_code.extend_from_slice(storer.as_slice()); + toucher_code.extend_from_slice(&[0x31, 0x50, 0x00]); + let slots = BTreeMap::from([(B256::ZERO, U256::ZERO)]); + let block = SyntheticBlock::start( + &[(storer, storer_code.clone(), slots), (toucher, toucher_code, BTreeMap::new())], + &[storer, toucher], + ) + .await; + + let summary = block.replay(1); + assert_eq!( + summary["state"][storer.to_string()]["code"], + alloy_primitives::hex::encode_prefixed(&storer_code), + "{summary}" + ); +} diff --git a/bin/mega-evme/tests/satin-differences.md b/bin/mega-evme/tests/satin-differences.md new file mode 100644 index 000000000..3f133ef8d --- /dev/null +++ b/bin/mega-evme/tests/satin-differences.md @@ -0,0 +1,78 @@ +# Satin against the legacy engine: the expected differences + +Generated by `cargo test --manifest-path bin/mega-evme/Cargo.toml --test differences`; the test compares this file to what it renders, so every number here is one the two engines produced. After an intended change of either, rewrite it with `UPDATE_EVME_DIFFERENCES=1`. + +Legacy is `Rex6` on the released `mega-evm` 1.7.1. Satin is the in-tree engine at a cost per state byte of 1530 and a cost per history byte of 88, the minimum SALT bucket everywhere. Every row runs one input on both engines. + +What the Satin columns show: + +- **Regular**: execution, at the Satin schedule (Amsterdam's, EIP-8038's state-access prices included) and EIP-2780's intrinsic cost. +- **State**: EIP-8037 state gas for the state a transaction adds (a slot, an account, deployed code), at the cost per state byte. +- **History**: gas for the bytes a transaction appends to history (its body, one 40-byte record per kept write, its logs, its deployed code), at the cost per history byte; **History bytes** is their count. The legacy engine has neither ledger. +- **Logs**: Satin emits an EIP-7708 `Transfer` log for every value movement; the legacy engine does not. +- **Classes**: the mechanisms a row shows, read off its numbers: `history`, `state`, `+N logs`, `status` (success differs), `stop:` (a Satin limit stopped it). + +## `run` and `tx` fixtures + +Each fixture's command run on both engines: `tests/fixtures/test_.json` and `test_satin_.json`, which is the same command with `--spec Satin`. + +| Fixture | Legacy | Satin | Satin - legacy | Regular | State | History | History bytes | Logs | Classes | +|---|---|---|---:|---:|---:|---:|---:|---|---| +| run_basic_return | success 60018 | success 42298 | -17720 | 15018 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_codefile | success 60018 | success 42298 | -17720 | 15018 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_create | success 103716 | success 241060 | +137344 | 24162 | 185130 | 31768 | 361 | 0 -> 0 | history, state | +| run_dump_inline | success 82106 | success 155826 | +73720 | 27106 | 97920 | 30800 | 350 | 0 -> 0 | history, state | +| run_input | success 60726 | success 42718 | -18008 | 15086 | 0 | 27632 | 314 | 0 -> 0 | history | +| run_prestate | success 62118 | success 44398 | -17720 | 17118 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_revert | revert 60004 | revert 42284 | -17720 | 15004 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_rpc_args_parse | success 60018 | success 42298 | -17720 | 15018 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_storage_override | success 62118 | success 44398 | -17720 | 17118 | 0 | 27280 | 310 | 0 -> 0 | history | +| run_trace_inline | success 60018 | success 42298 | -17720 | 15018 | 0 | 27280 | 310 | 0 -> 0 | history | +| tx_create | success 103716 | success 241060 | +137344 | 24162 | 185130 | 31768 | 361 | 0 -> 0 | history, state | +| tx_halt_oog | halt 60100 | halt 60100 | +0 | 32820 | 0 | 27280 | 310 | 0 -> 0 | history | +| tx_revert | revert 60004 | revert 42284 | -17720 | 15004 | 0 | 27280 | 310 | 0 -> 0 | history | +| tx_value_transfer | success 63000 | success 238400 | +175400 | 24000 | 183600 | 30800 | 350 | 0 -> 1 | history, state, +1 logs | + +## Recorded mainnet blocks + +The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The legacy replay of each matches the chain (every receipt and the receipts root), so the legacy column is the chain's. Satin runs the transactions as signed, on the state their parent block left. + +| Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:| +| 26400001 | 39 | 10592072 | 13873243 | 1.30 | 8818227 | 0 | 5065016 | 17 | 138 -> 121 | 4 | +| 26400007 | 25 | 8428932 | 10696856 | 1.26 | 6203136 | 0 | 4493720 | 0 | 119 -> 119 | 0 | +| 26400110 | 27 | 8051381 | 10550686 | 1.31 | 6059166 | 0 | 4491520 | 1 | 121 -> 121 | 1 | + +## Recorded transactions by call target + +The transactions of the three blocks grouped by the contract they call and the selector they call it with; `deposit` is the block's L1 attributes deposit, `-` a call without calldata. + +| Call target | Selector | Transactions | Legacy gas | Satin gas | Satin / legacy | State gas | Status differs | Logs | +|---|---|---:|---:|---:|---:|---:|---:|---| +| 0x6342000000000000000000000000000000000001 | 0x01caec13 | 31 | 2532545 | 771030 | 0.30 | 0 | 5 | 0 -> 0 | +| 0x897a33a0af45b3ba097bd6045187d622252e6acd | 0x9aec351f | 30 | 18019164 | 26445264 | 1.46 | 0 | 0 | 330 -> 330 | +| deposit | - | 3 | 304908 | 141288 | 0.46 | 0 | 0 | 0 -> 0 | +| 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x21d5c9bb | 2 | 601407 | 832935 | 1.38 | 0 | 0 | 6 -> 6 | +| 0x57677bdc4f24d5c08ddce87e06670c26a00cac0b | 0xb7a16251 | 2 | 1559890 | 1647024 | 1.05 | 0 | 0 | 19 -> 19 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fad7 | 2 | 151028 | 135924 | 0.89 | 0 | 0 | 0 -> 0 | +| 0x0b5cca2dd7bcc50b17213aa4828fc8e4bf9bcfc2 | 0xf7a30806 | 1 | 161042 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x12759afca690637b425ffba3265f0dc2f6242a8d | 0x93ca625d | 1 | 314985 | 413681 | 1.31 | 0 | 0 | 5 -> 5 | +| 0x256307f3b2fd8468afd2070e349d8dd033e56e2e | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x2d35f7dc723f7e16416a1113c7f11ebb68490769 | 0x38dd01ff | 1 | 235148 | 400000 | 1.70 | 0 | 1 | 2 -> 0 | +| 0x3b4c89aabae1804a631d51b3d9dc0e3da228a701 | 0xf7a30806 | 1 | 161122 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x3fc0045863135c4a4eaee7e3a4d167508269bd7e | 0x38dd01ff | 1 | 235545 | 400000 | 1.69 | 0 | 1 | 2 -> 0 | +| 0x4d184a91727f98b75b557dd209903b71c7184739 | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x5b00d5668600db5803073677f51bd6698531a93b | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x5e3ae52eba0f9740364bd5dd39738e1336086a8b | 0x91680b93 | 1 | 649146 | 630510 | 0.97 | 0 | 0 | 0 -> 0 | +| 0x609ca0a22ed2e361a2787939f4903b1fd4bc54ca | 0x38dd01ff | 1 | 235544 | 400000 | 1.69 | 0 | 1 | 2 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fadc | 1 | 75514 | 67962 | 0.89 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fadd | 1 | 75514 | 67962 | 0.89 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb42 | 1 | 75514 | 67962 | 0.89 | 0 | 0 | 0 -> 0 | +| 0x681e908b8ab57c49c74d770f369754ccc3e1ae09 | 0x6aa4fb43 | 1 | 75514 | 67962 | 0.89 | 0 | 0 | 0 -> 0 | +| 0x6b2b9db1413cbf64572c320d6b7c941c57901794 | 0xf7a30806 | 1 | 161042 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0x8c0e2c6916a5437ae65c51439ce986d38b09c0db | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0xaef423246a0851139e115403c6924c94fd6804ef | 0x38dd01ff | 1 | 235148 | 400000 | 1.70 | 0 | 1 | 2 -> 0 | +| 0xbfd77de81cf6200203889a56c4c0812ffee1bc03 | - | 1 | 60000 | 39280 | 0.65 | 0 | 0 | 0 -> 0 | +| 0xcc13277a5d6b3dd640981ff39da89672828e2ba3 | 0xdd1b6137 | 1 | 188717 | 212001 | 1.12 | 0 | 0 | 1 -> 1 | +| 0xf1641c9d17e7a783441b48ab65d55fdaa7d920f2 | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | +| 0xfb6c17f7510308e054daa72e5a5c1a3a8bfaaf42 | 0xf7a30806 | 1 | 160658 | 220000 | 1.36 | 0 | 1 | 1 -> 0 | diff --git a/bin/mega-evme/tests/state.rs b/bin/mega-evme/tests/state.rs index bb811a915..916af7caf 100644 --- a/bin/mega-evme/tests/state.rs +++ b/bin/mega-evme/tests/state.rs @@ -15,7 +15,240 @@ use mega_evme::common::{PreStateArgs, RpcArgs}; use tempfile::tempdir; mod common; -use common::{test_rpc_args_cached, MockRpcServer}; +use common::{rpc_cache_path, test_rpc_args, test_rpc_args_cached, MockRpcServer}; + +// ─── The predeploys `run` and `tx` put in the state ────────────────────────── + +/// A mock of a chain holding the factory with its code at nonce 1443, the Oracle without code at +/// nonce 5, and the other five system contracts with their code at nonce 0; every other account, +/// balance and slot is empty. +async fn predeploy_chain() -> wiremock::MockServer { + use mega_evm::system::{ + system_contract_specs, CREATE2_FACTORY_ADDRESS, ORACLE_CONTRACT_ADDRESS, + }; + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + let chain = system_contract_specs(); + Mock::given(matchers::method("POST")) + .respond_with(move |req: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap(); + let address = body["params"][0].as_str().unwrap_or_default().to_lowercase(); + let held = chain.iter().find(|spec| format!("{:#x}", spec.address) == address); + let is = |target: Address| format!("{target:#x}") == address; + let result = match body["method"].as_str().unwrap() { + "eth_chainId" => serde_json::json!("0x10e6"), + "eth_getTransactionCount" if is(CREATE2_FACTORY_ADDRESS) => { + serde_json::json!("0x5a3") + } + "eth_getTransactionCount" if is(ORACLE_CONTRACT_ADDRESS) => { + serde_json::json!("0x5") + } + "eth_getTransactionCount" | "eth_getBalance" => serde_json::json!("0x0"), + "eth_getCode" => match held { + Some(spec) if spec.address != ORACLE_CONTRACT_ADDRESS => { + serde_json::json!(alloy_primitives::hex::encode_prefixed(&spec.code)) + } + _ => serde_json::json!("0x"), + }, + _ => serde_json::json!(B256::ZERO), + }; + ResponseTemplate::new(200).set_body_json( + serde_json::json!({ "jsonrpc": "2.0", "id": body["id"], "result": result }), + ) + }) + .mount(&server) + .await; + server +} + +/// A state with Satin's predeploys installed: forked from `chain`, or local without one; built +/// with the CLI `overrides`, from a prestate file that holds an account without code at each of +/// `file_accounts` (and no file when there are none). +async fn state_with_predeploys( + chain: Option<&wiremock::MockServer>, + file_accounts: &[Address], + overrides: &[String], +) -> impl DatabaseRef { + let dir = tempdir().expect("tempdir"); + let mut argv = vec!["mega-evme".to_string()]; + if chain.is_some() { + argv.extend(["--fork", "--fork.block", "7"].map(String::from)); + } + if !file_accounts.is_empty() { + let path = dir.path().join("prestate.json"); + let accounts: serde_json::Map = file_accounts + .iter() + .map(|address| { + let empty = serde_json::json!({ + "balance": "0x0", "nonce": "0x0", "code": "0x", "storage": {} + }); + (format!("{address:#x}"), empty) + }) + .collect(); + std::fs::write(&path, serde_json::Value::Object(accounts).to_string()) + .expect("write prestate"); + argv.extend(["--prestate".to_string(), path.to_str().unwrap().to_string()]); + } + argv.extend(overrides.iter().cloned()); + let rpc_args = match chain { + Some(server) => test_rpc_args(&server.uri(), Some(0)), + // Without --fork no endpoint is contacted. + None => test_rpc_args("http://localhost:8545", None), + }; + let (mut state, _) = PreStateArgs::parse_from(argv) + .create_initial_state(&Address::ZERO, &rpc_args) + .await + .expect("the state"); + state.deploy_system_contracts().expect("the predeploys"); + state +} + +/// `run` and `tx` put Satin's predeploys only where the state lacks the code Satin expects. On a +/// fork of a chain that holds the factory with its code at nonce 1443 and the six system +/// contracts at nonce 0, those accounts stay as the chain holds them; an address the chain holds +/// without the code gets the code and keeps its nonce. Nothing is rewritten to a nonce of the +/// tool's own. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_fork_keeps_the_predeploys_it_holds() { + use mega_evm::system::{ + system_contract_specs, CREATE2_FACTORY_ADDRESS, ORACLE_CONTRACT_ADDRESS, + }; + + let chain = predeploy_chain().await; + let state = state_with_predeploys(Some(&chain), &[], &[]).await; + for spec in system_contract_specs() { + let info = state.basic_ref(spec.address).expect("readable").expect("present"); + assert_eq!(info.code_hash, spec.code_hash, "{} holds Satin's code", spec.address); + let nonce = match spec.address { + CREATE2_FACTORY_ADDRESS => 1_443, + ORACLE_CONTRACT_ADDRESS => 5, + _ => 0, + }; + assert_eq!(info.nonce, nonce, "{} keeps the nonce the chain holds", spec.address); + } +} + +/// Without a fork, an address the prestate file gives Satin's code keeps the account the file +/// holds — the factory at nonce 1443, the Oracle at nonce 3 with a slot of its own — and every +/// other predeploy gets the account Rex6 left: the code at nonce 0, the `SequencerRegistry` naming +/// the system address. +#[tokio::test] +async fn test_a_local_prestate_keeps_the_predeploys_it_holds() { + use mega_evm::system::{ + system_contract_specs, CREATE2_FACTORY_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + }; + + let specs = system_contract_specs(); + let held = |address: Address, nonce: u64, storage: serde_json::Value| { + let spec = specs.iter().find(|spec| spec.address == address).unwrap(); + serde_json::json!({ + "balance": "0x0", + "nonce": format!("{nonce:#x}"), + "code": alloy_primitives::hex::encode_prefixed(&spec.code), + "codeHash": spec.code_hash, + "storage": storage, + }) + }; + let dir = tempdir().expect("tempdir"); + let path = dir.path().join("prestate.json"); + let prestate = serde_json::json!({ + format!("{CREATE2_FACTORY_ADDRESS:#x}"): held(CREATE2_FACTORY_ADDRESS, 1_443, serde_json::json!({})), + format!("{ORACLE_CONTRACT_ADDRESS:#x}"): held(ORACLE_CONTRACT_ADDRESS, 3, serde_json::json!({ "0x1": "0x7" })), + }); + std::fs::write(&path, prestate.to_string()).expect("write prestate"); + let prestate_args = + PreStateArgs::parse_from(["mega-evme", "--prestate", path.to_str().unwrap()]); + // Without --fork no endpoint is contacted. + let rpc_args = test_rpc_args("http://localhost:8545", None); + let (mut state, _) = + prestate_args.create_initial_state(&Address::ZERO, &rpc_args).await.expect("the state"); + state.deploy_system_contracts().expect("the predeploys"); + + for spec in &specs { + let info = state.basic_ref(spec.address).expect("readable").expect("present"); + assert_eq!(info.code_hash, spec.code_hash, "{} holds Satin's code", spec.address); + let nonce = match spec.address { + CREATE2_FACTORY_ADDRESS => 1_443, + ORACLE_CONTRACT_ADDRESS => 3, + _ => 0, + }; + assert_eq!(info.nonce, nonce, "{}", spec.address); + } + let slot = + |address: Address, index: u64| state.storage_ref(address, U256::from(index)).unwrap(); + assert_eq!(slot(ORACLE_CONTRACT_ADDRESS, 1), U256::from(7), "the Oracle keeps its slot"); + assert_eq!( + slot(SEQUENCER_REGISTRY_ADDRESS, 0), + U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0), + "the registry names the system address" + ); +} + +/// A balance override and a faucet on a predeploy hold over the account `run` and `tx` install +/// there, locally and on a fork, whether or not the prestate file holds an account without code at +/// the address: the Oracle gets its code and the overridden balance plus the faucet. The rest of +/// the account is the one installed: the account Rex6 left locally, on a fork the chain's (nonce 5) +/// or the file's. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_balance_override_holds_over_a_predeploy() { + use mega_evm::system::{ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH}; + + let chain = predeploy_chain().await; + let overrides = [ + format!("--balance={ORACLE_CONTRACT_ADDRESS}=100wei"), + format!("--faucet={ORACLE_CONTRACT_ADDRESS}+=5wei"), + ]; + for fork in [None, Some(&chain)] { + for file_accounts in [&[][..], &[ORACLE_CONTRACT_ADDRESS][..]] { + let case = + format!("fork {}, file account {}", fork.is_some(), !file_accounts.is_empty()); + let state = state_with_predeploys(fork, file_accounts, &overrides).await; + let oracle = state.basic_ref(ORACLE_CONTRACT_ADDRESS).unwrap().expect("installed"); + assert_eq!(oracle.code_hash, ORACLE_CONTRACT_CODE_HASH, "{case}"); + assert_eq!(oracle.balance, U256::from(105), "{case}: the override and the faucet hold"); + let nonce = if fork.is_some() && file_accounts.is_empty() { 5 } else { 0 }; + assert_eq!(oracle.nonce, nonce, "{case}"); + } + } +} + +/// A storage override on the `SequencerRegistry` holds over the account `run` and `tx` install +/// there, locally and on a fork, whether or not the prestate file holds an account without code +/// at the address: the overridden slot keeps its value. Every other slot is the installed +/// account's: the registry Rex6 left locally, on a fork the chain's (empty in the mock) or the +/// file's. +#[tokio::test(flavor = "multi_thread")] +async fn test_a_storage_override_holds_over_a_predeploy() { + use mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + test_utils::rex6_predeploys, + }; + + let (_, _, rex6_slots) = rex6_predeploys(MEGA_SYSTEM_ADDRESS) + .into_iter() + .find(|(address, ..)| *address == SEQUENCER_REGISTRY_ADDRESS) + .expect("the registry is a predeploy"); + let chain = predeploy_chain().await; + let overrides = [format!("--storage={SEQUENCER_REGISTRY_ADDRESS}:0=4660")]; + for fork in [None, Some(&chain)] { + for file_accounts in [&[][..], &[SEQUENCER_REGISTRY_ADDRESS][..]] { + let case = + format!("fork {}, file account {}", fork.is_some(), !file_accounts.is_empty()); + let state = state_with_predeploys(fork, file_accounts, &overrides).await; + for (slot, rex6) in &rex6_slots { + let expected = match (slot.is_zero(), fork) { + (true, _) => U256::from(4660), + (false, None) => *rex6, + (false, Some(_)) => U256::ZERO, + }; + let held = state.storage_ref(SEQUENCER_REGISTRY_ADDRESS, *slot).unwrap(); + assert_eq!(held, expected, "{case}: slot {slot}"); + } + } + } +} // ─── Synthetic branch wiring tests (no network required) ───────────────────── @@ -36,10 +269,8 @@ async fn test_create_initial_state_non_fork_store_is_noop() { assert!(cache_store.is_noop(), "non-fork must wire a no-op cache store"); cache_store.persist().expect("persist"); - assert!( - !dir.path().join("rpc-cache-4326.json").exists(), - "non-fork persist must not produce any cache file", - ); + let left: Vec<_> = std::fs::read_dir(dir.path()).expect("read_dir").collect(); + assert!(left.is_empty(), "non-fork persist must not produce any cache file"); } /// Fork mode with `--fork.block N` constructs the state without hitting the @@ -68,7 +299,7 @@ async fn test_create_initial_state_fork_store_persists_cache() { assert!(!cache_store.is_noop(), "fork + cache_dir must wire a real store"); cache_store.persist().expect("persist"); assert!( - dir.path().join("rpc-cache-4326.json").exists(), + rpc_cache_path(dir.path(), 4326, &server.uri()).exists(), "fork persist must write the cache file", ); } @@ -103,15 +334,18 @@ async fn test_storage_cache_hit_round_trip_via_mock() { let storage_hex = "0x000000000000000000000000000000000000000000000000000000000000002a"; let expected_value = U256::from(0x2a); + // One endpoint for both phases: the cache file is named from the URL, so a second + // mock would be a different file. + let server = MockRpcServer::start().await; + let rpc_url = server.uri(); + server.respond_eth_chain_id(chain_id, 1).await; + server.respond_jsonrpc_result(storage_hex, 2).await; + // ── Phase 1: mock returns the storage value, populate cache, persist. ── let phase1_value = { - let server = MockRpcServer::start().await; - server.respond_eth_chain_id(chain_id, 1).await; - server.respond_jsonrpc_result(storage_hex, 2).await; - let prestate_args = PreStateArgs::parse_from(["mega-evme", "--fork", "--fork.block", &block_number_str]); - let rpc_args = test_rpc_args_cached(&server.uri(), dir.path(), None); + let rpc_args = test_rpc_args_cached(&rpc_url, dir.path(), None); let sender = Address::ZERO; let (state, cache_store) = prestate_args @@ -131,21 +365,20 @@ async fn test_storage_cache_hit_round_trip_via_mock() { assert_eq!(phase1_value, expected_value, "phase 1 must parse the mock's hex result"); assert!( - dir.path().join(format!("rpc-cache-{chain_id}.json")).exists(), + rpc_cache_path(dir.path(), chain_id, &rpc_url).exists(), "phase 1 persist must produce the cache file", ); - // ── Phase 2: only eth_chainId mock, same cache directory. ────────────── + // ── Phase 2: only eth_chainId left mounted, same endpoint and directory. ── let phase2_value = { - // Only `eth_chainId` is mounted: any other outbound request would be - // answered by wiremock's default 404 handler, which `storage_ref` - // would then surface as an error. - let server = MockRpcServer::start().await; + // Any request other than `eth_chainId` is answered by wiremock's default 404, + // which `storage_ref` would surface as an error. + server.reset().await; server.respond_eth_chain_id(chain_id, 1).await; let prestate_args = PreStateArgs::parse_from(["mega-evme", "--fork", "--fork.block", &block_number_str]); - let rpc_args = test_rpc_args_cached(&server.uri(), dir.path(), None); + let rpc_args = test_rpc_args_cached(&rpc_url, dir.path(), None); let sender = Address::ZERO; let (state, _cache_store) = prestate_args @@ -176,7 +409,8 @@ async fn test_storage_cache_hit_round_trip_via_mock() { /// `MEGA_EVME_TEST_RPC_URL` environment variable. Run with: /// /// ```text -/// cargo test -p mega-evme test_create_initial_state_fork_real_rpc_smoke -- --ignored +/// cargo test --manifest-path bin/mega-evme/Cargo.toml --test state \ +/// test_create_initial_state_fork_real_rpc_smoke -- --ignored /// ``` /// /// Stability: the Oracle is a `MegaETH` system contract predeployed at @@ -225,7 +459,7 @@ async fn test_create_initial_state_fork_real_rpc_smoke() { cache_store.persist().expect("persist"); // MegaETH mainnet chain id is 4326, so the cache filename is fixed. - let cache_file = dir.path().join("rpc-cache-4326.json"); + let cache_file = rpc_cache_path(dir.path(), 4326, &rpc_url); assert!(cache_file.exists(), "cache file must exist after persist"); let metadata = std::fs::metadata(&cache_file).expect("metadata"); assert!(metadata.len() > 0, "cache file must be non-empty after a real query"); @@ -247,7 +481,8 @@ async fn test_create_initial_state_fork_real_rpc_smoke() { /// `MEGA_EVME_TEST_RPC_URL` environment variable. /// /// ```text -/// cargo test -p mega-evme test_create_initial_state_fork_real_rpc_storage_cache_hit -- --ignored +/// cargo test --manifest-path bin/mega-evme/Cargo.toml --test state \ +/// test_create_initial_state_fork_real_rpc_storage_cache_hit -- --ignored /// ``` #[tokio::test(flavor = "multi_thread")] #[ignore = "requires network access for phase 1"] @@ -288,7 +523,7 @@ async fn test_create_initial_state_fork_real_rpc_storage_cache_hit() { value }; - let cache_file = dir.path().join("rpc-cache-4326.json"); + let cache_file = rpc_cache_path(dir.path(), 4326, &rpc_url); assert!(cache_file.exists(), "cache file must exist after phase 1 persist"); let metadata = std::fs::metadata(&cache_file).expect("metadata"); assert!(metadata.len() > 0, "cache file must be non-empty after phase 1"); @@ -319,3 +554,303 @@ async fn test_create_initial_state_fork_real_rpc_storage_cache_hit() { assert_eq!(phase1_value, phase2_value, "cache reload must return the same storage value"); } + +/// A forked state reads an account the RPC reports as all zeros as absent, and an account with a +/// balance as present: an RPC answers zeros for an account that does not exist. +#[tokio::test(flavor = "multi_thread")] +async fn test_forked_state_reads_an_all_zero_account_as_absent() { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + let absent = Address::from_str("0x00000000000000000000000000000000000000aa").unwrap(); + let funded = Address::from_str("0x00000000000000000000000000000000000000bb").unwrap(); + let server = MockServer::start().await; + let respond = |method: &'static str, needle: Option, result: &'static str| { + let mut mock = Mock::given(matchers::method("POST")) + .and(matchers::body_string_contains(format!("\"{method}\""))); + if let Some(needle) = needle { + mock = mock.and(matchers::body_string_contains(needle)); + } + mock.respond_with(move |req: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap(); + ResponseTemplate::new(200).set_body_json( + serde_json::json!({ "jsonrpc": "2.0", "id": body["id"], "result": result }), + ) + }) + }; + respond("eth_chainId", None, "0x10e6").mount(&server).await; + respond("eth_getBalance", Some(format!("{funded:#x}")), "0x64") + .with_priority(1) + .mount(&server) + .await; + respond("eth_getBalance", None, "0x0").with_priority(2).mount(&server).await; + respond("eth_getTransactionCount", None, "0x0").mount(&server).await; + respond("eth_getCode", None, "0x").mount(&server).await; + + let prestate_args = PreStateArgs::parse_from(["mega-evme", "--fork", "--fork.block", "100"]); + let rpc_args = RpcArgs::parse_from([ + "mega-evme", + "--rpc", + &server.uri(), + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + ]); + let (state, _store) = + prestate_args.create_initial_state(&Address::ZERO, &rpc_args).await.expect("fork"); + + assert_eq!(state.basic_ref(absent).expect("absent account"), None); + let present = state.basic_ref(funded).expect("funded account").expect("present"); + assert_eq!(present.balance, U256::from(100)); +} + +const FORK_ACCOUNT: &str = "0x00000000000000000000000000000000000000aa"; + +/// Answers `eth_chainId` and one account: balance 100, nonce 7, code `0x6000`, slot 0 = `0x11`, +/// any other slot = `0x22`. +async fn mount_fork_account(server: &wiremock::MockServer) { + use wiremock::{matchers, Mock, ResponseTemplate}; + + Mock::given(matchers::method("POST")) + .respond_with(|req: &wiremock::Request| { + let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap_or_default(); + let method = body["method"].as_str().unwrap_or(""); + let params = body["params"].as_array(); + let result = match method { + "eth_chainId" => "0x10e6".to_string(), + "eth_getBalance" => "0x64".to_string(), + "eth_getTransactionCount" => "0x7".to_string(), + "eth_getCode" => "0x6000".to_string(), + "eth_getStorageAt" => { + let slot = params + .and_then(|params| params.get(1)) + .and_then(|slot| slot.as_str()) + .and_then(|slot| U256::from_str(slot).ok()) + .unwrap_or(U256::ZERO); + if slot.is_zero() { + "0x11".to_string() + } else { + "0x22".to_string() + } + } + _ => "0x0".to_string(), + }; + let id = body["id"].clone(); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "result": result, + })) + }) + .mount(server) + .await; +} + +fn fork_rpc_args(url: &str) -> RpcArgs { + RpcArgs::parse_from([ + "mega-evme", + "--rpc", + url, + "--rpc.no-cache-file", + "--rpc.max-retries", + "0", + ]) +} + +/// A balance, faucet, or storage override names one field of a forked account. The account's +/// nonce, code and every other slot stay the values the fork returned. +#[tokio::test(flavor = "multi_thread")] +async fn test_field_override_keeps_the_rest_of_a_forked_account() { + let code_hash = alloy_primitives::keccak256([0x60, 0x00]); + let address = Address::from_str(FORK_ACCOUNT).unwrap(); + + let server = wiremock::MockServer::start().await; + mount_fork_account(&server).await; + let rpc_args = fork_rpc_args(&server.uri()); + + let storage_only = PreStateArgs::parse_from([ + "mega-evme", + "--fork", + "--fork.block", + "100", + "--storage", + &format!("{FORK_ACCOUNT}:0x0=0x99"), + ]); + let (state, _) = storage_only + .create_initial_state(&Address::ZERO, &rpc_args) + .await + .expect("storage override"); + let info = state.basic_ref(address).expect("basic").expect("present"); + assert_eq!(info.balance, U256::from(100), "a storage override must not replace the balance"); + assert_eq!(info.nonce, 7, "a storage override must not replace the nonce"); + assert_eq!(info.code_hash, code_hash, "a storage override must not replace the code"); + assert_eq!(state.storage_ref(address, U256::ZERO).expect("slot 0"), U256::from(0x99)); + assert_eq!( + state.storage_ref(address, U256::from(1)).expect("slot 1"), + U256::from(0x22), + "a storage override must not hide the account's other slots", + ); + + let balance_only = PreStateArgs::parse_from([ + "mega-evme", + "--fork", + "--fork.block", + "100", + "--balance", + &format!("{FORK_ACCOUNT}=5"), + ]); + let (state, _) = balance_only + .create_initial_state(&Address::ZERO, &rpc_args) + .await + .expect("balance override"); + let info = state.basic_ref(address).expect("basic").expect("present"); + assert_eq!(info.balance, U256::from(5)); + assert_eq!(info.nonce, 7); + assert_eq!(info.code_hash, code_hash); + assert_eq!(state.storage_ref(address, U256::from(1)).expect("slot 1"), U256::from(0x22)); + + let faucet = PreStateArgs::parse_from([ + "mega-evme", + "--fork", + "--fork.block", + "100", + "--faucet", + &format!("{FORK_ACCOUNT}+=50"), + ]); + let (state, _) = faucet.create_initial_state(&address, &rpc_args).await.expect("faucet"); + let info = state.basic_ref(address).expect("basic").expect("present"); + assert_eq!(info.balance, U256::from(150)); + assert_eq!(info.nonce, 7); + assert_eq!(info.code_hash, code_hash); + + let sender_balance = PreStateArgs::parse_from([ + "mega-evme", + "--fork", + "--fork.block", + "100", + "--sender.balance", + "9", + ]); + let (state, _) = + sender_balance.create_initial_state(&address, &rpc_args).await.expect("sender balance"); + let info = state.basic_ref(address).expect("basic").expect("present"); + assert_eq!(info.balance, U256::from(9)); + assert_eq!(info.nonce, 7); + assert_eq!(info.code_hash, code_hash); +} + +/// On an empty state the same flags still set exactly the fields they name. +#[tokio::test] +async fn test_field_override_on_empty_state_sets_the_named_field() { + let address = Address::from_str(FORK_ACCOUNT).unwrap(); + let rpc_args = test_rpc_args("http://127.0.0.1:1", None); + let args = PreStateArgs::parse_from([ + "mega-evme", + "--balance", + &format!("{FORK_ACCOUNT}=10"), + "--faucet", + &format!("{FORK_ACCOUNT}+=5"), + "--storage", + &format!("{FORK_ACCOUNT}:0x0=0x9"), + ]); + let (state, store) = + args.create_initial_state(&Address::ZERO, &rpc_args).await.expect("local overrides"); + assert!(store.is_noop()); + let info = state.basic_ref(address).expect("basic").expect("the balance override creates it"); + assert_eq!(info.balance, U256::from(15)); + assert_eq!(info.nonce, 0); + assert_eq!(state.storage_ref(address, U256::ZERO).expect("slot 0"), U256::from(9)); + assert_eq!(state.storage_ref(address, U256::from(1)).expect("slot 1"), U256::ZERO); +} + +/// A faucet that does not fit in the balance is refused, whether the balance comes from the +/// prestate file, from the sum of the faucet entries, or from the account the override lands on. +#[tokio::test] +async fn test_faucet_overflow_is_invalid_input() { + use mega_evme::EvmeError; + + let rpc_args = test_rpc_args("http://127.0.0.1:1", None); + let max = U256::MAX.to_string(); + let overflow = |err: EvmeError| matches!(err, EvmeError::InvalidInput(msg) if msg.contains("Faucet overflows")); + + let summed = PreStateArgs::parse_from([ + "mega-evme", + "--faucet", + &format!("{FORK_ACCOUNT}+={max}"), + "--faucet", + &format!("{FORK_ACCOUNT}+=1"), + ]); + let err = summed + .create_initial_state(&Address::ZERO, &rpc_args) + .await + .expect_err("two faucet entries past the maximum"); + assert!(overflow(err)); + + let replaced = PreStateArgs::parse_from([ + "mega-evme", + "--balance", + &format!("{FORK_ACCOUNT}={max}"), + "--faucet", + &format!("{FORK_ACCOUNT}+=1"), + ]); + let (state, _) = replaced.create_initial_state(&Address::ZERO, &rpc_args).await.expect("build"); + let err = state + .basic_ref(Address::from_str(FORK_ACCOUNT).unwrap()) + .expect_err("balance override plus faucet past the maximum"); + assert!(overflow(err)); + + let dir = tempdir().expect("tempdir"); + let path = dir.path().join("prestate.json"); + std::fs::write( + &path, + format!( + r#"{{"{FORK_ACCOUNT}":{{"balance":"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","nonce":"0x4","code":"0x","codeHash":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","storage":{{"0x1":"0x3"}}}}}}"# + ), + ) + .expect("write prestate"); + let from_file = PreStateArgs::parse_from([ + "mega-evme", + "--prestate", + path.to_str().unwrap(), + "--faucet", + &format!("{FORK_ACCOUNT}+=1"), + ]); + let err = from_file + .create_initial_state(&Address::ZERO, &rpc_args) + .await + .expect_err("prestate balance plus faucet past the maximum"); + assert!(overflow(err)); +} + +/// Overrides of an account the prestate file already holds change that field and leave the +/// account's other fields, including its other slots. +#[tokio::test] +async fn test_field_override_keeps_prestate_account_fields() { + let dir = tempdir().expect("tempdir"); + let path = dir.path().join("prestate.json"); + std::fs::write( + &path, + format!( + r#"{{"{FORK_ACCOUNT}":{{"balance":"0x8","nonce":"0x4","code":"0x","codeHash":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","storage":{{"0x1":"0x3"}}}}}}"# + ), + ) + .expect("write prestate"); + let args = PreStateArgs::parse_from([ + "mega-evme", + "--prestate", + path.to_str().unwrap(), + "--balance", + &format!("{FORK_ACCOUNT}=1"), + "--faucet", + &format!("{FORK_ACCOUNT}+=5"), + "--storage", + &format!("{FORK_ACCOUNT}:0x0=0x9"), + ]); + let rpc_args = test_rpc_args("http://127.0.0.1:1", None); + let (state, _) = args.create_initial_state(&Address::ZERO, &rpc_args).await.expect("prestate"); + let address = Address::from_str(FORK_ACCOUNT).unwrap(); + let info = state.basic_ref(address).expect("basic").expect("present"); + assert_eq!(info.balance, U256::from(6)); + assert_eq!(info.nonce, 4); + assert_eq!(state.storage_ref(address, U256::ZERO).expect("slot 0"), U256::from(9)); + assert_eq!(state.storage_ref(address, U256::from(1)).expect("slot 1"), U256::from(3)); +} diff --git a/bin/mega-t8n/Cargo.toml b/bin/mega-t8n/Cargo.toml deleted file mode 100644 index 62900574b..000000000 --- a/bin/mega-t8n/Cargo.toml +++ /dev/null @@ -1,32 +0,0 @@ -[package] -name = "mega-t8n" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -description = "MegaETH state transition (t8n) tool" - -[lints] -workspace = true - -[[bin]] -name = "mega-t8n" -path = "src/main.rs" - -[dependencies] -# megaeth -mega-evm = { workspace = true, features = ["default", "test-utils"] } -mega-state-test.workspace = true - -# alloy -alloy-consensus = { workspace = true, features = ["serde"] } -alloy-primitives.workspace = true -alloy-serde = { workspace = true, features = ["default"] } - -# misc -clap = { workspace = true, features = ["default"] } -serde.workspace = true -serde_json.workspace = true -thiserror.workspace = true diff --git a/bin/mega-t8n/src/cmd.rs b/bin/mega-t8n/src/cmd.rs deleted file mode 100644 index 7117b59fa..000000000 --- a/bin/mega-t8n/src/cmd.rs +++ /dev/null @@ -1,446 +0,0 @@ -use std::{path::PathBuf, str::FromStr}; - -use clap::Parser; -use mega_evm::{ - revm::{ - context::{ - block::BlockEnv, cfg::CfgEnv, either::Either, result::ExecutionResult, tx::TxEnv, - }, - database::{CacheState, EmptyDB, State}, - primitives::{eip4844, hardfork::SpecId, Bytes, TxKind, B256}, - state::{AccountInfo, Bytecode}, - ExecuteCommitEvm, - }, - MegaContext, MegaEvm, MegaSpecId, MegaTransaction, -}; -use state_test::types::Env; - -use crate::{ - calculate_logs_bloom, calculate_logs_root, calculate_state_root, - extract_post_state_alloc_from_state, load_alloc, load_env, load_from_stdin, load_transactions, - recover_address_from_secret_key, write_alloc_to_file, write_body_output, write_result_to_file, - RejectedTx, Result, StateAlloc, T8nError, T8nOutput, Transaction, TransactionLog, - TransactionReceipt, TransitionInputs, TransitionResults, -}; - -/// Executes a full state transition -#[derive(Parser, Debug)] -pub(crate) struct Cmd { - /// Configures the use of the JSON opcode tracer. This tracer emits traces to files - /// as trace--.jsonl - #[arg(long)] - pub trace: bool, - - /// The configurations for the custom tracer specified by --trace.tracer. If - /// provided, must be in JSON format - #[arg(long = "trace.jsonconfig")] - pub trace_jsonconfig: Option, - - /// Enable full memory dump in traces - #[arg(long = "trace.memory")] - pub trace_memory: bool, - - /// Disable stack output in traces - #[arg(long = "trace.nostack")] - pub trace_nostack: bool, - - /// Enable return data output in traces - #[arg(long = "trace.returndata")] - pub trace_returndata: bool, - - /// Enable call frames output in traces - #[arg(long = "trace.callframes")] - pub trace_callframes: bool, - - /// Specifies where output files are placed. Will be created if it does not exist. - #[arg(long = "output.basedir")] - pub output_basedir: Option, - - /// Determines where to put the `alloc` of the post-state. - /// `stdout` - into the stdout output - /// `stderr` - into the stderr output - /// - into the file - #[arg(long = "output.alloc", default_value = "alloc.json")] - pub output_alloc: String, - - /// Determines where to put the `result` (stateroot, txroot etc) of the post-state. - /// `stdout` - into the stdout output - /// `stderr` - into the stderr output - /// - into the file - #[arg(long = "output.result", default_value = "result.json")] - pub output_result: String, - - /// If set, the RLP of the transactions (block body) will be written to this file. - #[arg(long = "output.body")] - pub output_body: Option, - - /// File name of where to find the prestate alloc to use. - #[arg(long = "input.alloc", default_value = "stdin")] - pub input_alloc: String, - - /// File name of where to find the prestate env to use. - #[arg(long = "input.env", default_value = "stdin")] - pub input_env: String, - - /// File name of where to find the transactions to apply. If the file - /// extension is '.rlp', then the data is interpreted as an RLP list of signed - /// transactions. The '.rlp' format is identical to the output.body format. - #[arg(long = "input.txs", default_value = "stdin")] - pub input_txs: String, - - /// Name of hardfork to use, possible values: `Equivalence`, `MiniRex`, `MiniRex1`, - /// `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` - /// (`MiniRex1`/`MiniRex2` are alias specs executing `Equivalence`/`MiniRex` behavior) - #[arg(long = "state.fork", default_value = "MiniRex")] - pub fork: String, - - /// `ChainID` to use - #[arg(long = "state.chainid", default_value = "6342")] - pub chain_id: u64, - - /// Mining reward. Set to -1 to disable - #[arg(long = "state.reward", default_value = "0")] - pub reward: i64, -} - -impl Cmd { - fn spec_id(&self) -> MegaSpecId { - MegaSpecId::from_str(&self.fork).expect("Invalid hardfork name") - } - - /// Execute the state transition in three main steps: - /// 1. Load inputs (alloc, env, txs) - /// 2. Run EVM state transition - /// 3. Output results - pub(crate) fn run(&self) -> Result<()> { - // Step 1: Load inputs - let inputs = self.load_inputs()?; - - // Step 2: Run EVM state transition - let results = self.run_evm_transition(inputs)?; - - // Step 3: Output results - self.output_results(results)?; - - Ok(()) - } - - /// Step 1: Load input files (alloc.json, env.json, txs.json) or from stdin - fn load_inputs(&self) -> Result { - // Check if we should read from stdin (when any input is "stdin") - if self.input_alloc == "stdin" || self.input_env == "stdin" || self.input_txs == "stdin" { - return load_from_stdin(); - } - - // Load prestate allocation - let alloc = load_alloc(&self.input_alloc)?; - - // Load block environment - let env = load_env(&self.input_env)?; - - // Load transactions - let txs = load_transactions(&self.input_txs)?; - - Ok(TransitionInputs { alloc, env, txs }) - } - - /// Step 2: Execute state transition using the EVM - fn run_evm_transition(&self, inputs: TransitionInputs) -> Result { - // Setup configuration - let mut cfg = CfgEnv::default(); - cfg.chain_id = self.chain_id; - cfg.spec = self.spec_id(); - - // Setup block environment - let block = self.create_block_env(&inputs.env); - - // Setup state from prestate allocation - let mut state = self.create_initial_state(&inputs.alloc)?; - - // Execute transactions sequentially - let mut total_gas_used = 0u64; - let mut all_logs = Vec::new(); - let mut receipts = Vec::new(); - let mut rejected = Vec::new(); - - for (tx_index, tx_data) in inputs.txs.iter().enumerate() { - // Calculate transaction hash by converting to envelope - let tx = - tx_data.to_envelope().map_err(|e| T8nError::InvalidTransaction(e.to_string()))?; - let tx_hash = tx.tx_hash(); - - // Convert transaction to TxEnv - let tx_env = match self.convert_transaction_to_env(tx_data) { - Ok(env) => env, - Err(e) => { - rejected.push(RejectedTx { - index: tx_index as u64, - error: format!("Failed to convert transaction: {:?}", e), - }); - - // Create failed receipt - let receipt = TransactionReceipt { - status: 0, - cumulative_gas_used: total_gas_used, - logs: Vec::new(), - transaction_hash: tx_hash, - gas_used: 0, - root: None, - logs_bloom: None, - contract_address: None, - effective_gas_price: None, - block_hash: None, - transaction_index: None, - blob_gas_used: None, - blob_gas_price: None, - delegations: None, - }; - receipts.push(receipt); - continue; - } - }; - - // Create EVM context and transaction - let evm_context = MegaContext::default() - .with_db(&mut state) - .with_cfg(cfg.clone()) - .with_block(block.clone()); - - let mut tx = MegaTransaction::new(tx_env.clone()); - tx.enveloped_tx = Some(Bytes::default()); - - // Execute transaction - let mut evm = MegaEvm::new(evm_context); - let exec_result = evm.transact_commit(tx); - - match &exec_result { - Ok(result) => { - let tx_gas_used = result.gas_used(); - total_gas_used += tx_gas_used; - - // Determine if execution was successful based on execution result type - let is_success = matches!(result, ExecutionResult::Success { .. }); - - // Only add logs if execution was successful - if is_success { - all_logs.extend_from_slice(result.logs()); - } - - // Create receipt with status based on execution result - let receipt = TransactionReceipt { - status: if is_success { 1 } else { 0 }, - cumulative_gas_used: total_gas_used, - logs: if is_success { - result - .logs() - .to_vec() - .into_iter() - .enumerate() - .map(|(log_index, log)| { - let (topics, data) = log.data.split(); - TransactionLog { - address: log.address, - topics, - data, - block_number: 0, - transaction_hash: tx_hash, - transaction_index: tx_index as u64, - block_hash: B256::default(), - log_index: log_index as u64, - removed: false, - } - }) - .collect() - } else { - Vec::new() - }, - transaction_hash: tx_hash, - gas_used: tx_gas_used, - root: None, - logs_bloom: None, - contract_address: None, - effective_gas_price: None, - block_hash: None, - transaction_index: None, - blob_gas_used: None, - blob_gas_price: None, - delegations: None, - }; - receipts.push(receipt); - } - Err(e) => { - // For failed transactions, we still update the state but mark as failed - let receipt = TransactionReceipt { - status: 0, - cumulative_gas_used: total_gas_used, // Don't add gas for failed tx - logs: Vec::new(), - transaction_hash: tx_hash, - gas_used: 0, - root: None, - logs_bloom: None, - contract_address: None, - effective_gas_price: None, - block_hash: None, - transaction_index: None, - blob_gas_used: None, - blob_gas_price: None, - delegations: None, - }; - receipts.push(receipt); - - rejected.push(RejectedTx { index: tx_index as u64, error: format!("{:?}", e) }); - } - } - } - - // Calculate bloom filter from all logs - let logs_bloom = calculate_logs_bloom(&all_logs); - - // Calculate roots - let state_root = calculate_state_root(&state); - let tx_root = B256::default(); // TODO: Calculate transaction trie root - let receipts_root = B256::default(); // TODO: Calculate receipts root - let logs_hash = calculate_logs_root(&all_logs); - - // Extract post-state allocation - let post_state_alloc = extract_post_state_alloc_from_state(&state); - - Ok(TransitionResults { - state_root, - tx_root, - receipts_root, - logs_hash, - logs_bloom, - receipts, - rejected, - difficulty: inputs.env.current_difficulty, - gas_used: total_gas_used, - base_fee: inputs.env.current_base_fee.unwrap_or_default(), - post_state_alloc, - }) - } - - /// Create block environment from the input environment - fn create_block_env(&self, env: &Env) -> BlockEnv { - let mut block = BlockEnv { - number: env.current_number, - beneficiary: env.current_coinbase, - timestamp: env.current_timestamp, - gas_limit: env.current_gas_limit.try_into().unwrap_or(u64::MAX), - basefee: env.current_base_fee.unwrap_or_default().try_into().unwrap_or(u64::MAX), - difficulty: env.current_difficulty, - prevrandao: env.current_random.map(|i| i.into()), - blob_excess_gas_and_price: None, - }; - - // Set blob excess gas from currentExcessBlobGas if available - if let Some(current_excess_blob_gas) = env.current_excess_blob_gas { - block.set_blob_excess_gas_and_price( - current_excess_blob_gas.to(), - eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_CANCUN, - ); - } - - block - } - - /// Create initial state from prestate allocation - fn create_initial_state(&self, alloc: &StateAlloc) -> Result> { - // Determine state clear flag based on EVM spec (Spurious Dragon and later) - let has_state_clear = self.spec_id().into_eth_spec().is_enabled_in(SpecId::SPURIOUS_DRAGON); - let mut cache_state = CacheState::new(has_state_clear); - - for (address, info) in alloc { - let bytecode = Bytecode::new_raw_checked(info.code.clone()) - .unwrap_or_else(|_| Bytecode::new_legacy(info.code.clone())); - let code_hash = bytecode.hash_slow(); - - let acc_info = AccountInfo { - balance: info.balance, - code_hash, - code: Some(bytecode), - nonce: info.nonce, - }; - - cache_state.insert_account_with_storage( - *address, - acc_info, - info.storage.iter().map(|(k, v)| (*k, *v)).collect(), - ); - } - - Ok(State::builder().with_cached_prestate(cache_state).with_bundle_update().build()) - } - - /// Convert Transaction to `TxEnv` - fn convert_transaction_to_env(&self, tx: &Transaction) -> Result { - // Determine sender from secret_key if provided, otherwise use signature recovery - let caller = if let Some(secret_key) = tx.secret_key { - recover_address_from_secret_key(&secret_key)? - } else { - // TODO: Implement signature recovery from v, r, s - return Err(T8nError::InvalidTransaction( - "Missing secret key for transaction".to_string(), - )); - }; - - Ok(TxEnv { - caller, - gas_price: tx.gas_price.or(tx.max_fee_per_gas).unwrap_or_default().into(), - gas_priority_fee: tx.max_priority_fee_per_gas.map(|b| b.into()), - blob_hashes: tx.blob_versioned_hashes.clone(), - max_fee_per_blob_gas: tx - .max_fee_per_blob_gas - .map(|b| u128::try_from(b).expect("max fee less than u128::MAX")) - .unwrap_or(u128::MAX), - tx_type: tx.tx_type.unwrap_or(0), - gas_limit: tx.gas, - data: tx.data.clone(), - nonce: tx.nonce, - value: tx.value, - access_list: tx.access_list.clone().unwrap_or_default(), - authorization_list: tx - .authorization_list - .clone() - .map(|auth_list| auth_list.into_iter().map(Either::Left).collect::>()) - .unwrap_or_default(), - kind: match tx.to { - Some(addr) => TxKind::Call(addr), - None => TxKind::Create, - }, - chain_id: tx.chain_id.map(|c| c.to()), - }) - } - - /// Step 3: Write output files (result.json, alloc.json) - fn output_results(&self, results: TransitionResults) -> Result<()> { - // Create T8N output format with alloc and result - let t8n_output = - T8nOutput { alloc: results.post_state_alloc.clone(), result: results.clone() }; - - // Always print result to stdout as JSON (default behavior) - let result_json = serde_json::to_string_pretty(&t8n_output) - .map_err(|e| T8nError::JsonParse { file: "stdout".to_string(), source: e })?; - println!("{}", result_json); - - // Additionally write to files if specified - if self.output_result != "stdout" { - write_result_to_file(&results, &self.output_result, self.output_basedir.as_ref())?; - } - - if self.output_alloc != "stdout" { - write_alloc_to_file( - &results.post_state_alloc, - &self.output_alloc, - self.output_basedir.as_ref(), - )?; - } - - // Write body.rlp if requested - if let Some(ref body_file) = self.output_body { - write_body_output(body_file, self.output_basedir.as_ref())?; - } - - Ok(()) - } -} diff --git a/bin/mega-t8n/src/error.rs b/bin/mega-t8n/src/error.rs deleted file mode 100644 index c6a96ef62..000000000 --- a/bin/mega-t8n/src/error.rs +++ /dev/null @@ -1,37 +0,0 @@ -/// Custom error type for t8n operations -#[derive(Debug, thiserror::Error)] -pub(crate) enum T8nError { - /// Failed to load an input file - #[error("Failed to load input file '{file}': {source}")] - InputLoad { - /// The file path that failed to load - file: String, - /// The underlying I/O error - source: std::io::Error, - }, - - /// Failed to parse JSON content - #[error("Failed to parse JSON from '{file}': {source}")] - JsonParse { - /// The file path where JSON parsing failed - file: String, - /// The underlying JSON parsing error - source: serde_json::Error, - }, - - /// Failed to write an output file - #[error("Failed to write output file '{file}': {source}")] - OutputWrite { - /// The file path that failed to write - file: String, - /// The underlying I/O error - source: std::io::Error, - }, - - /// Invalid transaction data provided - #[error("Invalid transaction data: {0}")] - InvalidTransaction(String), -} - -/// Result type alias for T8N operations -pub(crate) type Result = std::result::Result; diff --git a/bin/mega-t8n/src/io.rs b/bin/mega-t8n/src/io.rs deleted file mode 100644 index 41bed9efa..000000000 --- a/bin/mega-t8n/src/io.rs +++ /dev/null @@ -1,119 +0,0 @@ -use std::{fs, io::Read, path::PathBuf}; - -use state_test::types::Env; - -use crate::{ - Result, StateAlloc, StdinInput, T8nError, Transaction, TransitionInputs, TransitionResults, -}; - -/// Load prestate allocation from a JSON file -pub(crate) fn load_alloc(path: &str) -> Result { - let content = std::fs::read_to_string(path) - .map_err(|e| T8nError::InputLoad { file: path.to_string(), source: e })?; - - let alloc: StateAlloc = serde_json::from_str(&content) - .map_err(|e| T8nError::JsonParse { file: path.to_string(), source: e })?; - - Ok(alloc) -} - -/// Load environment from a JSON file -pub(crate) fn load_env(path: &str) -> Result { - let content = std::fs::read_to_string(path) - .map_err(|e| T8nError::InputLoad { file: path.to_string(), source: e })?; - - let env: Env = serde_json::from_str(&content) - .map_err(|e| T8nError::JsonParse { file: path.to_string(), source: e })?; - - Ok(env) -} - -/// Load transactions from a JSON file -pub(crate) fn load_transactions(path: &str) -> Result> { - let content = std::fs::read_to_string(path) - .map_err(|e| T8nError::InputLoad { file: path.to_string(), source: e })?; - - let txs: Vec = serde_json::from_str(&content) - .map_err(|e| T8nError::JsonParse { file: path.to_string(), source: e })?; - - Ok(txs) -} - -/// Load inputs from stdin in combined JSON format -pub(crate) fn load_from_stdin() -> Result { - let mut buffer = String::new(); - std::io::stdin() - .read_to_string(&mut buffer) - .map_err(|e| T8nError::InputLoad { file: "stdin".to_string(), source: e })?; - - let stdin_input: StdinInput = serde_json::from_str(&buffer) - .map_err(|e| T8nError::JsonParse { file: "stdin".to_string(), source: e })?; - - Ok(TransitionInputs { alloc: stdin_input.alloc, env: stdin_input.env, txs: stdin_input.txs }) -} - -/// Write the post-state alloc to a file -pub(crate) fn write_alloc_to_file( - post_state_alloc: &StateAlloc, - output_alloc: &str, - output_basedir: Option<&PathBuf>, -) -> Result<()> { - let output_path = if let Some(base_dir) = output_basedir { - base_dir.join(output_alloc) - } else { - PathBuf::from(output_alloc) - }; - - // Convert to serializable format - let json_output = serde_json::to_string_pretty(post_state_alloc) - .map_err(|e| T8nError::JsonParse { file: output_path.display().to_string(), source: e })?; - - // Create base directory if it doesn't exist - if let Some(parent) = output_path.parent() { - fs::create_dir_all(parent) - .map_err(|e| T8nError::OutputWrite { file: parent.display().to_string(), source: e })?; - } - - fs::write(&output_path, &json_output).map_err(|e| T8nError::OutputWrite { - file: output_path.display().to_string(), - source: e, - })?; - - Ok(()) -} - -/// Write the execution result to a file -pub(crate) fn write_result_to_file( - results: &TransitionResults, - output_result: &str, - output_basedir: Option<&PathBuf>, -) -> Result<()> { - let output_path = if let Some(base_dir) = output_basedir { - base_dir.join(output_result) - } else { - PathBuf::from(output_result) - }; - - let json_output = serde_json::to_string_pretty(results) - .map_err(|e| T8nError::JsonParse { file: output_path.display().to_string(), source: e })?; - - // Create base directory if it doesn't exist - if let Some(parent) = output_path.parent() { - fs::create_dir_all(parent) - .map_err(|e| T8nError::OutputWrite { file: parent.display().to_string(), source: e })?; - } - - fs::write(&output_path, &json_output).map_err(|e| T8nError::OutputWrite { - file: output_path.display().to_string(), - source: e, - })?; - - Ok(()) -} - -/// Write the transaction body RLP to output file -pub(crate) fn write_body_output(_body_file: &str, _output_basedir: Option<&PathBuf>) -> Result<()> { - // TODO: Generate RLP-encoded transaction body - // eprintln!("body RLP output not yet implemented"); - Ok(()) -} diff --git a/bin/mega-t8n/src/main.rs b/bin/mega-t8n/src/main.rs deleted file mode 100644 index 83e33b166..000000000 --- a/bin/mega-t8n/src/main.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! `MegaETH` state transition (t8n) tool - -#![cfg_attr(not(test), warn(unused_crate_dependencies))] -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] - -use clap::Parser; - -mod cmd; -mod error; -mod io; -mod types; -mod utils; - -use cmd::*; -use error::*; -use io::*; -use types::*; -use utils::*; - -fn main() { - let cmd = Cmd::parse(); - if let Err(e) = cmd.run() { - eprintln!("{e}"); - std::process::exit(1); - } -} diff --git a/bin/mega-t8n/src/types/mod.rs b/bin/mega-t8n/src/types/mod.rs deleted file mode 100644 index 7c20dd15b..000000000 --- a/bin/mega-t8n/src/types/mod.rs +++ /dev/null @@ -1,87 +0,0 @@ -mod transaction; -pub(crate) use transaction::*; - -mod receipt; -pub(crate) use receipt::*; - -use std::collections::HashMap; - -use mega_evm::revm::primitives::{alloy_primitives::Bloom, Address, B256, U256}; -use state_test::types::{AccountInfo, Env}; - -/// Input data for state transition -#[derive(Debug)] -pub(crate) struct TransitionInputs { - /// Pre-state allocation of accounts - pub alloc: StateAlloc, - /// Block environment configuration - pub env: Env, - /// List of transactions to execute - pub txs: Vec, -} - -/// Results from state transition (internal) -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct TransitionResults { - /// Final state root hash - pub state_root: B256, - /// Transaction trie root hash - pub tx_root: B256, - /// Receipts trie root hash - pub receipts_root: B256, - /// Hash of all logs - pub logs_hash: B256, - /// Bloom filter of all logs - pub logs_bloom: Bloom, - /// Transaction receipts - pub receipts: Vec, - /// List of rejected transactions - #[serde(skip_serializing_if = "Vec::is_empty")] - pub rejected: Vec, - /// Current block difficulty - #[serde(rename = "currentDifficulty")] - pub difficulty: U256, - /// Total gas used in block - #[serde(rename = "gasUsed", with = "alloy_serde::quantity")] - pub gas_used: u64, - /// Current base fee per gas - #[serde(rename = "currentBaseFee")] - pub base_fee: U256, - /// Post-state allocation (not serialized here, moved to `T8nOutput`) - #[serde(skip)] - pub post_state_alloc: StateAlloc, -} - -/// T8N tool output format expected by execution-spec-tests -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub(crate) struct T8nOutput { - /// Post-state allocation - pub alloc: StateAlloc, - /// Transition results - pub result: TransitionResults, -} - -/// Information about a rejected transaction -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub(crate) struct RejectedTx { - /// Index of the rejected transaction - #[serde(with = "alloy_serde::quantity")] - pub index: u64, - /// Error message explaining why the transaction was rejected - pub error: String, -} - -/// Prestate account allocation (address -> account info mapping) -pub(crate) type StateAlloc = HashMap; - -/// Combined stdin input format -#[derive(Debug, serde::Deserialize)] -pub(crate) struct StdinInput { - /// Pre-state allocation of accounts - pub alloc: StateAlloc, - /// Block environment configuration - pub env: Env, - /// List of transactions to execute - pub txs: Vec, -} diff --git a/bin/mega-t8n/src/types/receipt.rs b/bin/mega-t8n/src/types/receipt.rs deleted file mode 100644 index 5fe8cddd4..000000000 --- a/bin/mega-t8n/src/types/receipt.rs +++ /dev/null @@ -1,88 +0,0 @@ -use mega_evm::revm::primitives::{alloy_primitives::Bloom, Address, Bytes, B256}; - -/// Transaction log entry -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct TransactionLog { - /// Address that generated this log - pub address: Address, - /// Indexed topics of the log - pub topics: Vec, - /// Log data - pub data: Bytes, - /// Block number where this log was generated - #[serde(with = "alloy_serde::quantity")] - pub block_number: u64, - /// Hash of the transaction that generated this log - pub transaction_hash: B256, - /// Index of the transaction in the block - #[serde(with = "alloy_serde::quantity")] - pub transaction_index: u64, - /// Hash of the block containing this log - pub block_hash: B256, - /// Index of this log within the transaction - #[serde(with = "alloy_serde::quantity")] - pub log_index: u64, - /// Whether this log was removed due to a chain reorganization - pub removed: bool, -} - -/// Receipt delegation entry for EIP-7702 set-code transactions -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ReceiptDelegation { - /// Address that delegated code execution - #[serde(rename = "from")] - pub from_address: Address, - /// Nonce used for the delegation - #[serde(with = "alloy_serde::quantity")] - pub nonce: u64, - /// Target address that provides the code - pub target: Address, -} - -/// Transaction receipt containing execution results -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct TransactionReceipt { - /// Hash of the transaction - pub transaction_hash: B256, - /// Gas used by this transaction - #[serde(with = "alloy_serde::quantity")] - pub gas_used: u64, - /// State root after this transaction (pre-Byzantium) - #[serde(skip_serializing_if = "Option::is_none")] - pub root: Option, - /// Status of transaction execution (post-Byzantium: 1=success, 0=failure) - #[serde(with = "alloy_serde::quantity")] - pub status: u64, - /// Cumulative gas used in the block up to and including this transaction - #[serde(with = "alloy_serde::quantity")] - pub cumulative_gas_used: u64, - /// Bloom filter for logs in this transaction - #[serde(skip_serializing_if = "Option::is_none")] - pub logs_bloom: Option, - /// Array of log entries generated by this transaction - pub logs: Vec, - /// Address of created contract (for contract creation transactions) - #[serde(skip_serializing_if = "Option::is_none")] - pub contract_address: Option
, - /// Effective gas price paid for this transaction - #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")] - pub effective_gas_price: Option, - /// Hash of the block containing this transaction - #[serde(skip_serializing_if = "Option::is_none")] - pub block_hash: Option, - /// Index of this transaction within the block - #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")] - pub transaction_index: Option, - /// Gas used by blobs in this transaction (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")] - pub blob_gas_used: Option, - /// Price per unit of blob gas (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none", with = "alloy_serde::quantity::opt")] - pub blob_gas_price: Option, - /// List of code delegations in this transaction (EIP-7702) - #[serde(skip_serializing_if = "Option::is_none")] - pub delegations: Option>, -} diff --git a/bin/mega-t8n/src/types/transaction.rs b/bin/mega-t8n/src/types/transaction.rs deleted file mode 100644 index d073ef934..000000000 --- a/bin/mega-t8n/src/types/transaction.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! Transaction type definitions for the `mega-t8n` tool. - -use alloy_consensus::{Signed, TxEip1559, TxEip2930, TxEip7702, TxLegacy}; -use alloy_primitives::{Signature, TxKind}; -use mega_evm::{ - revm::{ - context_interface::transaction::{AccessList, SignedAuthorization}, - primitives::{Address, Bytes, B256, U256}, - }, - MegaTxEnvelope, -}; - -/// Error type for transaction conversion failures -#[derive(Debug, thiserror::Error)] -pub(crate) enum TransactionConversionError { - /// Unsupported transaction type - #[error("Unsupported transaction type: {0}")] - UnsupportedType(u8), - /// Missing required field - #[error("Missing required field: {0}")] - MissingField(&'static str), - /// Invalid signature components - #[error("Invalid signature: {0}")] - InvalidSignature(String), - /// EIP-7702 transactions cannot be contract creation transactions - #[error("EIP-7702 transactions cannot be contract creation transactions")] - Eip7702CannotBeCreate, -} - -/// Transaction data for t8n (individual signed transaction) -#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct Transaction { - /// Transaction type (0=Legacy, 1=EIP-2930, 2=EIP-1559, 3=EIP-4844, 4=EIP-7702) - #[serde(rename = "type", default, with = "alloy_serde::quantity::opt")] - pub tx_type: Option, - /// Chain ID - pub chain_id: Option, - /// Transaction nonce - #[serde(with = "alloy_serde::quantity")] - pub nonce: u64, - /// Gas price (legacy/EIP-2930) - #[serde(with = "alloy_serde::quantity::opt")] - pub gas_price: Option, - /// Maximum fee per gas (EIP-1559) - #[serde(rename = "gasFeeCap", with = "alloy_serde::quantity::opt", default)] - pub max_fee_per_gas: Option, - /// Maximum priority fee per gas (EIP-1559) - #[serde(rename = "gasTipCap", with = "alloy_serde::quantity::opt", default)] - pub max_priority_fee_per_gas: Option, - /// Gas limit - #[serde(default, with = "alloy_serde::quantity")] - pub gas: u64, - /// Recipient address (None for contract creation) - pub to: Option
, - /// Ether value to transfer - pub value: U256, - /// Transaction data/input - #[serde(default, alias = "input")] - pub data: Bytes, - /// Access list (EIP-2930, EIP-1559) - pub access_list: Option, - /// Authorization list (EIP-7702) - pub authorization_list: Option>, - /// Maximum fee per blob gas (EIP-4844) - pub max_fee_per_blob_gas: Option, - /// Blob versioned hashes (EIP-4844) - #[serde(default)] - pub blob_versioned_hashes: Vec, - /// Signature v component - pub v: U256, - /// Signature r component - pub r: U256, - /// Signature s component - pub s: U256, - /// Secret key (for unsigned transactions) - pub secret_key: Option, -} - -impl Transaction { - /// Converts this transaction into a `MegaTxEnvelope` - pub(crate) fn to_envelope(&self) -> Result { - // Convert v, r, s to Signature - let signature = self.to_signature()?; - - // Convert to field to TxKind - let tx_kind = match self.to { - Some(addr) => TxKind::Call(addr), - None => TxKind::Create, - }; - - // Determine transaction type (default to 0 for legacy) - let tx_type = self.tx_type.unwrap_or(0); - - match tx_type { - // Legacy transaction (type 0) - 0 => { - let gas_price = - self.gas_price.ok_or(TransactionConversionError::MissingField("gas_price"))? - as u128; - - let tx = TxLegacy { - chain_id: self.chain_id.and_then(|id| id.try_into().ok()), - nonce: self.nonce, - gas_price, - gas_limit: self.gas, - to: tx_kind, - value: self.value, - input: self.data.clone(), - }; - - let signed = Signed::new_unhashed(tx, signature); - Ok(MegaTxEnvelope::Legacy(signed)) - } - - // EIP-2930 transaction (type 1) - 1 => { - let chain_id = self - .chain_id - .and_then(|id| id.try_into().ok()) - .ok_or(TransactionConversionError::MissingField("chain_id"))?; - - let gas_price = - self.gas_price.ok_or(TransactionConversionError::MissingField("gas_price"))? - as u128; - - let tx = TxEip2930 { - chain_id, - nonce: self.nonce, - gas_price, - gas_limit: self.gas, - to: tx_kind, - value: self.value, - access_list: self.access_list.clone().unwrap_or_default(), - input: self.data.clone(), - }; - - let signed = Signed::new_unhashed(tx, signature); - Ok(MegaTxEnvelope::Eip2930(signed)) - } - - // EIP-1559 transaction (type 2) - 2 => { - let chain_id = self - .chain_id - .and_then(|id| id.try_into().ok()) - .ok_or(TransactionConversionError::MissingField("chain_id"))?; - - let max_fee_per_gas = self - .max_fee_per_gas - .ok_or(TransactionConversionError::MissingField("max_fee_per_gas"))? - as u128; - - let max_priority_fee_per_gas = self - .max_priority_fee_per_gas - .ok_or(TransactionConversionError::MissingField("max_priority_fee_per_gas"))? - as u128; - - let tx = TxEip1559 { - chain_id, - nonce: self.nonce, - gas_limit: self.gas, - max_fee_per_gas, - max_priority_fee_per_gas, - to: tx_kind, - value: self.value, - access_list: self.access_list.clone().unwrap_or_default(), - input: self.data.clone(), - }; - - let signed = Signed::new_unhashed(tx, signature); - Ok(MegaTxEnvelope::Eip1559(signed)) - } - - // EIP-4844 (blob transactions) - not supported in OpTxEnvelope - 3 => Err(TransactionConversionError::UnsupportedType(3)), - - // EIP-7702 transaction (type 4) - 4 => { - let chain_id = self - .chain_id - .and_then(|id| id.try_into().ok()) - .ok_or(TransactionConversionError::MissingField("chain_id"))?; - - let max_fee_per_gas = self - .max_fee_per_gas - .ok_or(TransactionConversionError::MissingField("max_fee_per_gas"))? - as u128; - - let max_priority_fee_per_gas = self - .max_priority_fee_per_gas - .ok_or(TransactionConversionError::MissingField("max_priority_fee_per_gas"))? - as u128; - - // EIP-7702 transactions must have a target address (cannot be contract creation) - let to_addr = self.to.ok_or(TransactionConversionError::Eip7702CannotBeCreate)?; - - let authorization_list = self - .authorization_list - .clone() - .ok_or(TransactionConversionError::MissingField("authorization_list"))?; - - let tx = TxEip7702 { - chain_id, - nonce: self.nonce, - gas_limit: self.gas, - max_fee_per_gas, - max_priority_fee_per_gas, - to: to_addr, - value: self.value, - access_list: self.access_list.clone().unwrap_or_default(), - authorization_list, - input: self.data.clone(), - }; - - let signed = Signed::new_unhashed(tx, signature); - Ok(MegaTxEnvelope::Eip7702(signed)) - } - - // Unknown transaction type - _ => Err(TransactionConversionError::UnsupportedType(tx_type)), - } - } - - /// Converts the v, r, s signature components to an alloy Signature - fn to_signature(&self) -> Result { - // Calculate y_parity from v - // For EIP-155 transactions: v = chain_id * 2 + 35 + y_parity - // For pre-EIP-155: v = 27 + y_parity - let y_parity = if let Some(chain_id) = self.chain_id { - let chain_id_u64: u64 = chain_id.try_into().map_err(|_| { - TransactionConversionError::InvalidSignature("chain_id too large".to_string()) - })?; - - let v_u64: u64 = self.v.try_into().map_err(|_| { - TransactionConversionError::InvalidSignature("v value too large".to_string()) - })?; - - // EIP-155: v = chain_id * 2 + 35 + y_parity - if v_u64 >= chain_id_u64 * 2 + 35 { - v_u64 - chain_id_u64 * 2 - 35 == 1 - } else { - // Fall back to pre-EIP-155 if v doesn't match EIP-155 formula - v_u64 == 28 - } - } else { - // Pre-EIP-155: v = 27 or 28 - let v_u64: u64 = self.v.try_into().map_err(|_| { - TransactionConversionError::InvalidSignature("v value too large".to_string()) - })?; - v_u64 == 28 - }; - - // Create signature from r, s, and y_parity - Ok(Signature::new(self.r, self.s, y_parity)) - } -} diff --git a/bin/mega-t8n/src/utils.rs b/bin/mega-t8n/src/utils.rs deleted file mode 100644 index a0b920104..000000000 --- a/bin/mega-t8n/src/utils.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::collections::HashMap; - -use mega_evm::revm::{ - database::{EmptyDB, State}, - primitives::{alloy_primitives::Bloom, Address, Log, B256}, -}; -use state_test::types::AccountInfo; - -use crate::{Result, StateAlloc, T8nError}; - -/// Calculate state root from the final state -pub(crate) fn calculate_state_root(state: &State) -> B256 { - state_test::utils::state_merkle_trie_root(state.cache.trie_account()) -} - -/// Calculate logs root from all transaction logs -pub(crate) fn calculate_logs_root(logs: &[Log]) -> B256 { - state_test::utils::log_rlp_hash(logs) -} - -/// Calculate bloom filter from all transaction logs -pub(crate) fn calculate_logs_bloom(logs: &[Log]) -> Bloom { - let mut bloom = Bloom::default(); - for log in logs { - bloom.accrue_log(log); - } - bloom -} - -/// Extract post-state allocation from EVM state -pub(crate) fn extract_post_state_alloc_from_state(state: &State) -> StateAlloc { - let mut post_alloc = HashMap::new(); - - // Extract all accounts from the state - for (address, account) in state.cache.trie_account() { - let account_info = AccountInfo { - nonce: account.info.nonce, - balance: account.info.balance, - code: account - .info - .code - .as_ref() - .map(|bytecode| bytecode.original_bytes()) - .unwrap_or_default(), - storage: account - .storage - .iter() - .map(|(k, v)| (*k, *v)) // v is already a U256 value - .collect(), - }; - post_alloc.insert(Address::from(*address), account_info); - } - - post_alloc -} - -/// Recover address from secret key -pub(crate) fn recover_address_from_secret_key(secret_key: &B256) -> Result
{ - // Use the same recovery function as in state_test::utils - state_test::utils::recover_address(secret_key.as_slice()).ok_or_else(|| { - T8nError::InvalidTransaction(format!( - "Failed to recover address from secret key: {:?}", - secret_key - )) - }) -} diff --git a/clippy.toml b/clippy.toml index 392025ce4..058aa492e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,4 +1,4 @@ -msrv = "1.94.1" +msrv = "1.94" too-large-for-stack = 128 doc-valid-idents = [ "P2P", diff --git a/crates/mega-evm/Cargo.toml b/crates/mega-evm/Cargo.toml index ff7beefed..b92d1b6cd 100644 --- a/crates/mega-evm/Cargo.toml +++ b/crates/mega-evm/Cargo.toml @@ -20,7 +20,7 @@ alloy-evm.workspace = true alloy-hardforks.workspace = true alloy-op-evm.workspace = true alloy-op-hardforks.workspace = true -alloy-primitives.workspace = true +alloy-primitives = { workspace = true, features = ["serde"] } alloy-sol-types.workspace = true op-alloy-consensus.workspace = true op-revm = { workspace = true, features = ["dev", "serde"] } @@ -35,15 +35,22 @@ mega-system-contracts = { workspace = true, default-features = false } auto_impl.workspace = true delegate.workspace = true derive_more = { workspace = true, optional = true, features = ["debug", "deref", "deref_mut", "display", "error"] } -serde = { workspace = true, features = ["derive"] } +serde = { workspace = true, features = ["alloc", "derive"] } [dev-dependencies] +# alloy +alloy-rpc-types-trace = { workspace = true } +alloy-trie = { workspace = true, features = ["std", "ethereum"] } + # CodSpeed drop-in: `codspeed-criterion-compat` re-exports criterion's API, so # `use criterion::...` in the benches is unchanged. Under a normal `cargo bench` # it behaves exactly like criterion; under `cargo codspeed` it runs each bench # once under valgrind and reports layout-insensitive instruction counts. criterion = { package = "codspeed-criterion-compat", version = "5.0.1", default-features = false, features = ["cargo_bench_support", "html_reports", "plotters"] } +insta.workspace = true mega-evm = { path = ".", features = ["test-utils"] } +proptest = { workspace = true, features = ["std"] } +revm = { workspace = true, features = ["tracer"] } revm-inspectors = { workspace = true, features = ["std"] } serde_json = { workspace = true, features = ["std"] } @@ -64,8 +71,7 @@ satin-price-override = ["std"] # The Satin bench set: `transact` (MegaEvm next to op-revm), `corpus` (the JSON scenarios under # benches/scenarios, a bench input), `factory` (EVM construction) and `block` (a block through -# MegaBlockExecutor). The inputs under benches/data (revm_bench) and benches/fixtures -# (attack_replay) stay for the rebuild of the rest of the suite. +# MegaBlockExecutor). [[bench]] name = "block" harness = false diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index d63deff5a..9bb86423e 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -3,12 +3,12 @@ The EVM of MegaETH, built on [revm](https://github.com/bluealloy/revm) and [op-revm](https://github.com/ethereum-optimism/optimism/tree/develop/rust/op-revm). This is the 2.x line: the **Satin** engine. -The legacy engine (specs `Equivalence` through `Rex7`) is the 1.x line. +The legacy engine (specs `Equivalence` through `Rex6`) is the 1.x line. ## Base - **revm**: 40.0.3, from the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) (the revm 43 gas core with EIP-8037 and EIP-2780, plus MegaETH hooks) -- **op-revm**: 20.0.0, from the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) +- **op-revm**: 20.0.0, from the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) (op-revm's size-limited precompiles priced through the revm fork's `Precompile::required_gas`) - **alloy-evm**: 0.36; **alloy-op-evm**: 0.32 A consumer redirects all twelve revm crates and `op-revm` to the forks with `[patch]` entries; see this repository's root `Cargo.toml`. @@ -27,21 +27,49 @@ The legacy spec names do not parse: `"Rex6".parse::()` fails with `P Satin is under construction. Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. -The gas schedule is Amsterdam's with two changes: the entries EIP-8038 repriced go back to their Osaka values, and the EIP-8037 state-gas entries are rebuilt from MegaETH's own cost per state byte, so a new storage slot draws 97,920 state gas and a new account 183,600. +The gas schedule is Amsterdam's, EIP-8038's state-access prices included, with two changes: the EIP-8037 state-gas entries are rebuilt from MegaETH's own cost per state byte, so a new storage slot draws 97,920 state gas and a new account 183,600, and a byte of deployed code is priced at MegaETH's cost per history byte. The schedule also brings the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`) and raises the code-size limits to 512 KiB of contract and 1 MiB of initcode. +`SLOTNUM` pushes the slot number the node supplies in `BlockEnv::slot_num`, zero when it leaves it unset. +Satin takes EIP-7708 from Amsterdam too: every value movement — a transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT`'s balance moved to another account — emits a `Transfer(from, to, amount)` log from `0xff…fe` into the receipt, in execution order among the contracts' own logs. +A deposit's value is logged and its mint is not, and a destruction to itself burns the balance without a log. Its byte prices are an input: the `satin-price-override` feature, off by default, lets a measurement build install other ones. `tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, with what a handful of probe transactions spent. The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000. It is carried as an alloy-evm `PrecompilesMap`, so a node can add or replace an address through `MegaEvmFactory::with_dyn_precompiles_builder`. -The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the abort protocol that stops a transaction crossing a limit with a revert, and the inspector admission gate. -No limit is enforced by default; `EvmTxRuntimeLimits` sets a data-size cap and a frame budget to exercise the protocol. -`MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers, the usage counted and the limit that stopped the transaction, if any. +The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the stop protocol that reverts the frame crossing a limit, which its caller may catch, and the inspector contract: the admission gate and what a rewrite does not change. + +The data-size limit is in place on top of it. +A transaction is held to a data-size limit, and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left. +The bytes are the ones history gas prices — the body, every write record, every log, every byte of deployed code — plus an Oracle hint's payload and the EIP-7708 transfer logs. +A transfer log counts what a `LOG3` of one word counts, 160 bytes, where the value moves: with the records of the frame start that moves it, before any value moves, or with a `SELFDESTRUCT`'s beneficiary. +A frame start revm refuses on its caller's account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — counts nothing; a creation onto an occupied address is counted, and revm refuses it after the count. +A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped with a revert carrying `MegaLimitExceeded`, and pays only for what ran. +A record is checked before its history is charged, so a record the limit rejects costs nothing and the stop is what the transaction reports. +The limits are fixed per spec, `ProtocolLimits::for_spec`: Satin holds each transaction and the block to 12.5 MiB of data size and a detained transaction to 20,000,000 of compute past its read, and every EVM, a bare one included, runs under them; `EvmTxRuntimeLimits` sets others on an EVM, a tool's or a test's counterfactual. +The block's data size is a packing budget: the transaction that crosses it is packed and the next one refused. +`MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers beside the history bytes, the usage counted and the limit that stopped the transaction, if any. Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read by the first transaction that prices against it, so the block's own L1 info deposit is what the transactions after it are priced with. -Every transaction is held to the block's `BlockLimits`, and the block counts what its transactions spent on each of the three ledgers. -`apply_pre_execution_changes` leaves two hook points empty: system contract deployment and the pre-block system calls. +Every transaction is held to the spec's limits, and the block counts what its transactions spent on each of the three ledgers and the history bytes they appended. +The limits that change a result are protocol values fixed per spec, `ProtocolLimits::for_spec`: the per-transaction runtime limits and the block's data-size budget, the same on every chain, so no chain configuration carries them and a node passes none of them. +The block context a node passes carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap that can lower the block's data-size budget and never raise it, so a validator that leaves it at its default computes the block a builder packed under any policy. +The execution figure a block counts for a transaction is its regular ledger — its gas less state and history, read off revm's `Gas` — at least its EIP-7623 floor. +The block's data-size cap never refuses a deposit, which the block must include; a deposit still counts towards it. +A builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the block's counters again; alloy-evm's `commit_transaction` cannot fail and expects each outcome to commit before the next transaction executes, and a debug build asserts it. +`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the node says with `MegaBlockExecutionCtx::satin_activation_block` — checks that the six MegaETH system contracts and the EIP-7997 `CREATE2` factory hold the code Satin runs, which the legacy forks and OP's genesis tooling installed and without which that block is invalid, applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call, and last reads the L1 block contract's account and the five slots the block's transactions can be priced against, which op-revm and the executor read on the database rather than through a transaction. +It commits each pre-block state on its own, in order, read-only entries included — the two EIP calls, the activation block's seven reads, the read of the registry's pending changes and its call, and the L1 block info; with the included transactions' states and oracle reads, and the block hashes and buckets the executor exports, the sequence of committed states is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`). +A database that cannot serve one of those L1 reads fails the block before its first transaction, as an internal error, whatever the block holds. + +A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which the state it writes draws first. +revm's default system-call gas limit, 31,566,720, is 30,000,000 and a reservoir of sixteen fresh slots. +The block's pre-block calls run on the block's gas limit and never less than 30,000,000, the legacy engine's budget kept as it was; what it adds above 30,000,000 is reservoir, not regular gas. +The legacy engine widened it for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays: it prices its state at the minimum bucket. +A pre-block call that does not succeed refuses the block with the call's own validation error; a database error the database calls fatal is an internal error instead, since it says nothing about the block. +That is the rule alloy-evm's block executor holds a transaction's database error to. +A system call pays no history gas, is held to no per-transaction limit and is not detained. +A transaction is not a system call: every transaction's gas, the system-address transaction's included, is split by the execution cap. SALT pricing is in place: every EIP-8037 state gas charge costs the schedule's entry times the capacity of the SALT bucket it lands in, counted in minimum buckets, so a slot written into a region eight times as crowded as the minimum costs eight times as much. The multiplier applies to the state dimension only; regular gas never scales. @@ -49,17 +77,97 @@ Capacities come from the transaction's `SaltEnv`, read once per bucket per trans Without a SALT environment every bucket is minimal, so the numbers above are what a transaction pays. `tests/satin/pricing-table.md` shows two probes at three multipliers. -The six system contracts live at their fixed `0x6342…` addresses, and four of them answer calls through an interceptor instead of running their bytecode. +The six system contracts live at their fixed `0x6342…` addresses, and the EIP-7997 factory at `0x4e59…`; the legacy forks installed the six and OP's genesis tooling the factory, and Satin deploys none of them. +Three of them answer calls through an interceptor instead of running their bytecode, and `KeylessDeploy` turns the `keylessDeploy` calls a transaction makes into the deployments they stand for. A `CALL` or `STATICCALL` is dispatched on its target address, then on the four selector bytes of its input: `CALLCODE` and `DELEGATECALL` never reach an interceptor, and a selector a contract does not intercept falls through to the deployed bytecode, whose answer is that contract's own — the two control contracts revert with `NotIntercepted()` from their fallback, and `KeylessDeploy` and the Oracle, which have none, revert with empty data on a selector they do not declare. A method that takes no value answers a value-bearing call with `NonZeroTransfer()`. -`MegaAccessControl` and `MegaLimitControl` answer with what the engine knows so far — nothing has switched volatile-data access off, and `remainingComputeGas()` reports the regular gas the call was forwarded — until detention and compute gas fill them in. -The Oracle forwards a `sendHint` payload to the node's oracle service, and a `keylessDeploy` transaction is charged its fixed 100,000 gas and handed to the keyless rewrite hook that native keyless deployment fills in. - -The system address (`MEGA_SYSTEM_ADDRESS`) sends the protocol's own transactions: a legacy transaction from it to a whitelisted contract is validated — the whitelist, the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. +`MegaAccessControl` steers gas detention's switch: `disableVolatileDataAccess()` switches volatile-data access off for the calling frame and every frame below it, until that frame switches it back on or returns, `enableVolatileDataAccess()` reverts with `DisabledByParent()` in a frame below the one that switched it off, and `isVolatileDataAccessDisabled()` answers for the caller. +`MegaLimitControl.remainingComputeGas()` answers the compute the calling frame could still spend: the lesser of its own regular gas, with the gas the call forwarded counted back, and what gas detention leaves the transaction once it read volatile data. +It is regular gas only, so a transaction above the execution cap hears at most the cap's share. +Only one property of the legacy engine's answer carries over, that the gas a call forwards is not counted: the legacy answer came from a separate compute ledger and could exceed the caller's gas, while this one is at most the caller's own. +The Oracle forwards a `sendHint` payload to the node's oracle service, unless the calling frame's volatile-data access is off. + +The Oracle's storage is read through the node's oracle service: an `SLOAD` in the Oracle's own frame loads the slot from the chain's state, then asks `OracleEnv`, and answers the service's value when it has one and the loaded value otherwise. +A node that replays a block without the service must price and witness it as the node that built it did, and it cannot tell which source the building node read, so nothing may depend on the source: every such read is priced as a cold access, and the slot is loaded either way, so a later write to it finds it warm and a stateless witness carries it. + +`KeylessDeploy` deploys a pre-EIP-155 signed creation — Nick's Method — at the address its signer's first creation gets on every chain, with the gas limit the caller chooses. +A `keylessDeploy` call a transaction makes is taken before any interceptor sees it, and runs as a frame of its own in which no code runs; the deployment is a native creation, the call's child, and a tracer sees the call, and the creation as its child. +The call's frame is built on the contract as any call's is: the contract's account, which a transaction to it loads with its code in any case, is touched by a call that returns, and the contract's bytecode never runs for it. +A call carrying value is refused before its frame is built, so no value moves. +The call pays a fixed 100,000 gas for decoding the transaction and recovering its signer, and is held to the legacy engine's nine rules and error ABI, in the legacy engine's order. +It pays for the signer's account when the creation's nonce bump is what creates it, and what a `CREATE` opcode charges its frame: its regular gas, the created account, and the two write records of the creation's start. +It then starts the creation as the signer, below it, with `gasLimitOverride` capped to what it has left. +From there the creation is an ordinary frame, priced, limited, journaled and traced as one, and its `ORIGIN` and `GASPRICE` are the transaction's. +Once the creation returns the call answers in the contract's ABI — the deployed address, or the error the creation failed with; a limit the creation crosses stops the creation alone, and the call answers with the error that stop produced, while a stop of the call's own charges reverts the call and takes the deployment back whole. +A signer is refused once its nonce is above 1. +A deployment spends the signer's nonce from 0 to 1. +A signer at nonce 1 stays there, as in the legacy engine, however often its deployment fails, so nobody can use up its attempts, and once it deploys, so a resubmission finds the address taken (`ContractAlreadyExists()`). +The creation's bump is taken back with its write record, which stays only when a creation that succeeded moved value out of the signer. +The exception is a signer whose own code spends a nonce in the constructor that survives it — on a default configuration, a delegated signer's `CREATE` or `CREATE2`, successful or not: every bump stays, the creation's included, because a later bump may stand for an account, so the signer ends above 1 and every later deployment of it is refused. +A `keylessDeploy` call a contract makes is not a deployment: it runs the method body, which reverts with `NotIntercepted()`. + +The system address sends the protocol's own transactions: a legacy transaction from it to a whitelisted contract is validated — the chain id, the nonce and EIP-3607 — and promoted to a deposit, which pays no fee and rewards none. +It is the address the `SequencerRegistry` holds, and every transaction reads it itself when it is validated: it loads the registry's account and `_currentSystemAddress`, which stay warm for the rest of the transaction, so an access to either costs the same whatever the envelope. +A transaction of that shape from that address is a system-address transaction; one of another shape from it is invalid, and a deposit from it, which never has the shape, is a failed deposit. +The registry cannot change the address inside a block after its pre-block call, so every transaction of a block reads the address a rotation due in the block left, and an EVM a node builds outside block execution — an RPC call, the replay of a block's transactions for a trace — reads the one in the state it runs on, with nothing to set. +A registry that is absent, holds other code or names a zero address promotes nothing. +The read is in every transaction's own state and witness; the pre-block steps no longer carry it. The account such a transaction creates for its caller is charged the account-creation state gas exactly once. -History gas, the resource limits, gas detention, system contract deployment and keyless deployment arrive in later changes. -Until history gas lands, nothing prices a history byte and the schedule's history entry stays at zero, and a system transaction's history ledger is zero with it. +History gas is in place: every byte a transaction appends to the chain is priced at MegaETH's cost per history byte, and the byte counts are the ones the data-size limit meters, so a record's history bytes are its own data size. +A transaction body is 310 bytes — 110 for the envelope and one 40-byte record for each of the five writes every transaction makes, its sender's account and the four accounts its fees are credited to — plus one byte per calldata byte, 20 per access-list address, 32 per key and 101 per EIP-7702 authorization. +A log costs 32 bytes for its address, 32 per topic and its data; every account or storage write a transaction keeps costs one 40-byte record; every byte of deployed code costs a byte. +The body is charged at validation, in the EIP-8037 intrinsic state-gas slot so the reservoir pays it first: a gas limit that cannot cover it is rejected before inclusion, and the receipt's state figure does not include it. +Everything else is charged where the write is made and given back, at the same price, by whoever's failure takes it back. +The records a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` starts a frame for are charged to the caller out of what it kept after forwarding gas: a caller that cannot pay halts, and the frame does not start. +A deposit, a transaction the protocol itself sent and a system call pay no history at all. +The last two are held to no per-transaction limit either, for the same reason — the protocol's maintenance must not fail on a resource limit: no data-size limit and no frame budget stops them, and what they use is counted and reported all the same. +A user's deposit is held to every limit. + +The pairing between the two counts is per record, not per transaction. +An Oracle hint's payload is data size that is never history, because the bytes go to the node's oracle service rather than into a block; an EIP-7708 transfer log is data size that is never history either, because Ethereum prices it at nothing and it is not a byte the transaction chose to write; and the five records a transaction's body carries are an upper bound on the accounts its inclusion writes, so a transfer to the block beneficiary or a fee vault pays a record the body already bound. + +A value-transferring `CALL` or `CALLCODE` grants the frame it starts a history allowance of 160 bytes — one three-topic event carrying a word — so a `receive()` hook reached through Solidity's `transfer()` can still emit an event. +The allowance is not gas: it never enters the frame's `Gas`, only a log's charge may draw on it, and what it pays for is on no ledger, because no pool of the transaction's gas paid it. +The history bytes a transaction reports count those bytes all the same, so a block's byte column and its history gas column part by exactly what allowances paid. +The transfer log of the value that granted an allowance draws nothing from it. +The byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, a body counts its five fixed write records even when fewer fee accounts are written, and the transfer logs are not in it. + +No limit holds the KV count or the state a transaction adds. +The KV count is the write-record count the layer keeps — one record per account or storage write the transaction keeps, the sender and the fee accounts being the body's. +Every record is forty bytes of data size, so at the production data-size caps a transaction or a block keeps at most 327,680 records. +The transaction's KV count is in its outcome's usage and the block's in its result. +A transaction's state growth is the EIP-8037 state gas it spends, at the price of the SALT bucket it lands in: what bounds it is what it costs. + +Gas detention is in place: a transaction that reads volatile data — the block environment, the block beneficiary's account, the Oracle's storage — may compute at most 20,000,000 more gas after the read than it had spent at it. +Compute is the regular gas spent: the state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. +The one exception is what a frame has left when an opcode's static gas fails, which counts as compute: under that charge's price per halting frame, so the stop only comes earlier. +The Host marks the read where it loads the value, and the most restrictive read binds. +Every frame's spendable gas is held to what the limit leaves the transaction, and the rest is withheld, with the revm fork's withheld part of a frame's regular gas: a regular charge cannot draw it, and every other reader of the frame's gas — `GAS`, the gas a call forwards, the `SSTORE` sentry, what a callee returns — counts it. +So a transaction that reads runs as it would without the read until a regular charge needs the withheld gas. +That charge crossed the cap, and it is not made: the frame that makes the charge is stopped with a revert carrying `MegaLimitExceeded` of kind compute, its compute counted up to that charge, less than one charge short of the limit, and its caller gets back everything the frame had, the part withheld included. +The stop reports that compute as what was used. +The caller resumes held to what the limit leaves it, and the transaction is stopped only when the stopped frame is its own. +A precompile forwarded more than what the limit leaves its frame is decided from its price before it runs: priced within what the limit leaves, it runs as without the read; priced past it and within its forward, it computes nothing and is the same crossing, as is an interceptor's answer that spent more than the limit leaves; priced past its whole forward, it is a failed call its caller survives, as without the read. +So an input priced between what the limit leaves and the forward that would fail a check made after the gas check is the crossing too, where without the read that check fails the call. +Every precompile of the Satin set is priced, op-revm's size-limited BN254 pairing and BLS12-381 MSMs and pairing included. +A precompile the engine cannot price — a node's own, an address a node replaced — is run on what the limit leaves its frame, and one it does not pay is the crossing, whatever its price. +A keyless deployment's call is the transaction's own frame, held to the limit as any frame is: the overhead and the `CREATE` opcode's regular gas it charges are compute whether a rule then refuses the call or its creation runs, and the creation runs under what the limit leaves it. +Every other out-of-gas halts and burns as it would without the read. +While `MegaAccessControl`'s switch is off for a frame, its volatile reads are refused: the frame reverts with `VolatileDataAccessDisabled`, having paid the opcode's static gas and nothing more. +The error's argument is a `uint8`: a refused `SLOTNUM` names access type 12, which the contract's `VolatileDataAccessType` does not declare, so a Solidity handler must decode it as `uint8`, and `decode_volatile_data_access_disabled` decodes it on the Rust side. +The two caps are runtime limits, 20,000,000 each by default; `EvmTxRuntimeLimits::no_limits()` leaves them unlimited, and a transaction whose caps are both unlimited is not detained. +The protocol's own transactions and the system calls are not detained either. + +Every limit — the transaction's data size, a frame's data-size budget and gas detention's compute limit — stops the frame that crosses it the same way. +That frame reverts with `MegaLimitExceeded(kind, limit)`, keeping nothing it wrote or logged, and its caller resumes as after any revert: the call fails, the stop is its return data, and the gas the frame had comes back. +The caller is held to what the transaction has left, so a write or a charge of its own that crosses again stops it in turn, and a caller that catches the stop and ends lets the transaction succeed. +Only a stop of the transaction's own frame is the transaction's result, and `LimitStop` reports only that one. +It settles like any EIP-8037 revert: the transaction keeps nothing it wrote or logged, its sender pays the intrinsic gas and what ran, and gets back the rest of its regular gas and the reservoir, less the body's history. +Nothing is rescued, because nothing was taken: detention withholds gas inside a frame's own tracker and never spends it. +An inspector may rewrite a stop as it may any failure; a frame that kept nothing settles as one whatever the inspector made of its result. +A real out-of-gas and a precompile given less than its price still halt and burn what their frame was given. +`tests/satin/stops.rs` pins every limit crossed by the transaction's own frame and by a frame three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing. ## Quick start @@ -79,7 +187,7 @@ let tx = OpTx(op_revm::OpTransaction { let result = evm.transact_raw(tx)?; ``` -A node executes a block through the factory, which installs the block's limits on the EVM: +A node executes a block through the factory, which installs the spec's limits on the EVM; the EVM factory runs the EVMs it creates outside block execution — an RPC call, a simulation — under the same limits without being told: ```rust,ignore use alloy_evm::block::{BlockExecutor as _, BlockExecutorFactory as _}; @@ -105,7 +213,32 @@ let evm = MegaEvm::new(context).with_trusted_inspector(DeclaredObserver(tracer)) assert!(!evm.has_rewriting_inspector()); ``` +A declared observer sees a block's transactions, user and system alike, and nothing else: the pre-block calls run no inspector, and the end of the block runs no code. +Outside block execution an inspector may rewrite what execution produces — Foundry's cheatcodes are built on that — within the inspector contract. +A failed creation rewritten into a success is refused, and a limit's stop is not rewritten. +A frame an inspector answered in place of running, or a failed frame it turned into a success, settles into its caller as a frame that kept nothing: the caller sees the success, the output and the regular gas the inspector chose, and no state gas, history gas, refund or write record of writes the journal does not hold. +An answer hands its caller back the reservoir it forwarded, whatever gas the inspector built it on. +A success an inspector rewrites into a failure has its journal taken back as a failed frame's is, so the state follows the failure its ledgers settle as. +Gas an inspector writes after a frame's last instruction reaches nobody, and a charge a frame cannot pay is refused without stopping it. +`tests/satin/inspector_cheatcodes.rs` drives `deal`, `store`, `pauseGasMetering` / `resumeGasMetering` and `expectRevert` through the engine as Foundry's inspector does. + +## Node integration + +A node, a stateless validator and a tool take the following from the engine rather than restating it, so they cannot disagree with it. +The crate builds on Rust 1.94. + +- `spec_cfg(cfg)` is the configuration Satin runs on: the caller's configuration with every field the spec fixes set from the spec. + A node builds its `EvmEnv` through it, so what reads the env before an EVM exists — gas estimation reads the execution cap — reads what the EVM executes on. +- `validate_transaction_stateless(cfg, block, tx, system_address)` is a pool's check: it runs the handler's own validation phases on an EVM over an empty database and returns the intrinsic gas by ledger, `IntrinsicGas { regular, state, history, floor }`. + `system::live_system_address(db)` reads the address it takes, off the state the pool validates against, as a transaction's validation reads it. + The state a transaction adds is charged when it runs, so a new recipient or authority is not in the intrinsic gas; a deposit that fails validation is included as a failed deposit rather than refused. +- `MegaTransactionOutcome::limit_stop()`, or `LimitStop::from_result(result, limit_exceeded)` for a result read elsewhere, gives the kind, limit and usage of the limit that stopped a transaction, for an RPC's error. + `decode_mega_limit_exceeded` reads revert data alone; bytes that decode are no stop without the outcome's `limit_exceeded`. +- `SatinChainConfig::from_genesis_config(config)` reads a genesis file's `config` object: `satinTime`, the one Satin key; Satin carries no parameter, the limits are the spec's, and no key names them. + It refuses any other key starting with `satin`, those of the format's earlier versions among them, a mistyped value and a schedule `validate_schedule` refuses, and `hardforks()` builds the schedule; it serializes to the same key, for a genesis generator. + The key format is provisional. + ## Documentation -- [Specification](https://megaeth-labs.github.io/mega-evm/) (describes the legacy engine until the Satin pages land) +- [The Satin specification](../../docs/spec/upgrades/satin.md); the other pages under `docs/spec/` describe the legacy engine - [Architecture](../../ARCH.md) diff --git a/crates/mega-evm/benches/block.rs b/crates/mega-evm/benches/block.rs index 0e6c9ea20..35e6b8396 100644 --- a/crates/mega-evm/benches/block.rs +++ b/crates/mega-evm/benches/block.rs @@ -1,8 +1,19 @@ //! A block through `MegaBlockExecutor`: what block execution costs per transaction on top of -//! what the transaction itself costs. +//! what the transaction itself costs, in a chain's steady state. //! -//! Two workloads of `N` transactions each, both with the block's limits unset so the -//! per-transaction work is the executor's own: the admission checks, the size estimates, the +//! Every block runs as a node runs one: +//! +//! - on a state that holds the seven predeploys as a chain that ran Rex6 holds them, with what the +//! previous block's pre-block changes left: no block but Satin's activation block reads the +//! predeploys, and none deploys them; +//! - with the EIP-2935 and EIP-4788 contracts' own code, so the pre-block calls record the parent +//! hash and the beacon root; +//! - under the spec's limits, `ProtocolLimits::for_spec`: the production data-size limits and gas +//! detention's caps, with no building policy on top (`BlockLimits::default()`); +//! - from a fresh `State` over that database, as a node starts each block. +//! +//! Two workloads of `N` transactions each, whose per-transaction work beyond the transaction +//! itself is the executor's own: the admission checks, the size estimates, the limits, the //! counters, the receipt and the commit. //! //! - `transfers`: value transfers to accounts with no code — the cheapest transaction there is, so @@ -11,25 +22,34 @@ //! calldata, so every transaction changes storage and carries a write record through the //! counters, with a log-free receipt. //! -//! The pre-block calls and the state the block is built on are setup, and the measurement runs -//! `apply_pre_execution_changes`, the transactions and `finish` — the whole block a node -//! executes. +//! The measurement runs `apply_pre_execution_changes`, the transactions and `finish` — the whole +//! block a node executes — and hands the state back, so dropping it is not measured. One more arm, +//! `steady_pre_block`, measures `apply_pre_execution_changes` alone on the steady state: the +//! per-block cost of the pre-block system calls and reads. #![allow(missing_docs)] use alloy_consensus::{transaction::Recovered, Signed, TxLegacy}; +use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, +}; use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, + system::{MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + test_utils::{BytecodeBuilder, CommittedStates, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, }; +use op_revm::constants::L1_BLOCK_CONTRACT; use revm::{ bytecode::opcode::{CALLDATALOAD, SSTORE}, context::{BlockEnv, CfgEnv}, database::State, + state::EvmState, + DatabaseCommit, }; use std::hint::black_box; @@ -45,6 +65,11 @@ const BLOCK_NUMBER: u64 = 1_000; /// The timestamp of the block the bench executes. const BLOCK_TIMESTAMP: u64 = 1_800_000_000; +/// A non-zero parent hash and beacon root. A zero stored over an empty slot is not a write, so +/// the pre-block calls would leave no storage behind. +const PARENT_HASH: B256 = B256::repeat_byte(0xab); +const PARENT_BEACON_ROOT: B256 = B256::repeat_byte(0xcd); + const SENDER: Address = address!("0x2000000000000000000000000000000000000002"); const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); const WRITER: Address = address!("0x1000000000000000000000000000000000000001"); @@ -67,32 +92,47 @@ fn slot_calldata(nonce: u64) -> Bytes { Bytes::from(U256::from(nonce + 1).to_be_bytes::<32>()) } -/// The database every iteration starts from. +/// The accounts the workloads use, the EIP-2935 and EIP-4788 contracts' code, and the seven +/// predeploys as a chain that ran Rex6 holds them. fn database() -> MemoryDatabase { - let mut db = MemoryDatabase::default(); + let mut db = MemoryDatabase::default().rex6_predeploys(MEGA_SYSTEM_ADDRESS); db.set_account_code(WRITER, writer_code()); db.set_account_code(RECIPIENT, Bytes::new()); db.set_account_balance(SENDER, U256::from(1_000_000_000_000_000_u64)); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); db } -fn evm_env() -> EvmEnv { +/// The environment of block `number`, one second after the block before it. +fn evm_env_at(number: u64) -> EvmEnv { let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); cfg_env.chain_id = CHAIN_ID; EvmEnv { cfg_env, block_env: BlockEnv { - number: U256::from(BLOCK_NUMBER), - timestamp: U256::from(BLOCK_TIMESTAMP), + number: U256::from(number), + timestamp: U256::from(BLOCK_TIMESTAMP + number - BLOCK_NUMBER), gas_limit: 1_000_000_000, ..Default::default() }, } } -/// A block whose limits are all unset, so what is measured is the executor's own work. +/// The environment of the block the bench executes. +fn evm_env() -> EvmEnv { + evm_env_at(BLOCK_NUMBER) +} + +/// A block packed under no building policy, as a validator executes one: the chain's limits +/// alone hold it. fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits()) + MegaBlockExecutionCtx::new( + PARENT_HASH, + Some(PARENT_BEACON_ROOT), + Bytes::new(), + BlockLimits::default(), + ) } /// `N` transactions to `to`, one per nonce, each carrying the input `input` builds for it. @@ -120,8 +160,72 @@ fn transactions( .collect() } +fn chain_spec() -> MegaHardforkConfig { + MegaHardforkConfig::default().with_all_activated() +} + +/// Runs the pre-block changes of block `number` on a state over `db` and returns what they +/// committed to it, in order, as a commit hook on the state receives it; `db` itself is not +/// changed. +fn pre_block_states(db: MemoryDatabase, number: u64) -> Vec { + let spec = chain_spec(); + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env_at(number)); + let mut executor = + MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); + executor.apply_pre_execution_changes().expect("the pre-block changes apply"); + drop(executor); + committed.states() +} + +/// The database the chain's steady state starts a block from: [`database`] with what the +/// previous block's pre-block changes left in it, committed in the order the executor commits +/// them. +fn steady_database() -> MemoryDatabase { + let mut db = database(); + for state in pre_block_states(db.clone(), BLOCK_NUMBER - 1) { + db.commit(state); + } + db +} + +/// Asserts that the pre-block changes of the bench's block on `db` are a steady block's: the two +/// calls, which write their contracts, then the reads of the registry's pending changes and of the +/// L1 block info, and no read of a predeploy, which only Satin's activation block makes. Each step +/// names one account. +fn assert_steady_pre_block(db: &MemoryDatabase) { + let states = pre_block_states(db.clone(), BLOCK_NUMBER); + let named: Vec<_> = states + .iter() + .map(|state| { + assert_eq!(state.len(), 1, "a pre-block step names one account: {state:?}"); + *state.keys().next().expect("one account") + }) + .collect(); + assert_eq!( + named, + [ + HISTORY_STORAGE_ADDRESS, + BEACON_ROOTS_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + L1_BLOCK_CONTRACT + ], + "a steady block reads no predeploy" + ); + // Outside every measured section: both calls wrote the contract the bench seeded. + for (call, address) in states.iter().zip([HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]) { + let writes = call[&address].storage.values().filter(|slot| slot.is_changed()).count(); + assert!(writes > 0, "the call to {address} wrote its contract's storage"); + } +} + fn bench_block(c: &mut Criterion) { - let spec = MegaHardforkConfig::default().with_all_activated(); + let spec = chain_spec(); + let steady = steady_database(); + // Checked once before measurement, so a block that is not a steady one is not measured as one. + assert_steady_pre_block(&steady); + let workloads = [ // Both budgets clear the state gas the Satin gas table charges: a transfer to an account // that does not exist yet pays for the new account, a storage write pays for the slot. @@ -134,7 +238,7 @@ fn bench_block(c: &mut Criterion) { // The workload runs once outside the measurement, so a block that does not execute — or // one whose transactions keep nothing — is caught here rather than being measured. { - let mut state = State::builder().with_database(database()).build(); + let mut state = State::builder().with_database(steady.clone()).build(); let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); let mut executor = MegaBlockExecutor::new(evm, block_ctx(), &spec, OpAlloyReceiptBuilder::default()); @@ -143,6 +247,7 @@ fn bench_block(c: &mut Criterion) { let outcome = executor.execute_transaction_without_commit(tx).expect("the transaction runs"); assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "no limit stops the workload"); assert!( outcome.usage.write_records > 0, "every transaction of the workload keeps a write record" @@ -157,8 +262,34 @@ fn bench_block(c: &mut Criterion) { group.bench_function(*name, |b| { b.iter_batched( - || State::builder().with_database(database()).build(), + || State::builder().with_database(steady.clone()).build(), |mut state| { + let result = { + let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + block_ctx(), + &spec, + OpAlloyReceiptBuilder::default(), + ); + executor.apply_pre_execution_changes().unwrap(); + for tx in txs { + black_box(executor.execute_transaction(tx).unwrap()); + } + executor.finish_with_counters().unwrap().1 + }; + (state, black_box(result)) + }, + BatchSize::SmallInput, + ); + }); + } + + group.bench_function("steady_pre_block", |b| { + b.iter_batched( + || State::builder().with_database(steady.clone()).build(), + |mut state| { + let used = { let evm = MegaEvmFactory::new().create_evm(&mut state, evm_env()); let mut executor = MegaBlockExecutor::new( evm, @@ -167,15 +298,14 @@ fn bench_block(c: &mut Criterion) { OpAlloyReceiptBuilder::default(), ); executor.apply_pre_execution_changes().unwrap(); - for tx in txs { - black_box(executor.execute_transaction(tx).unwrap()); - } - black_box(executor.finish_with_counters().unwrap().1) - }, - BatchSize::SmallInput, - ); - }); - } + executor.limiter().block_gas_used + }; + (state, black_box(used)) + }, + BatchSize::SmallInput, + ); + }); + group.finish(); } diff --git a/crates/mega-evm/benches/corpus.rs b/crates/mega-evm/benches/corpus.rs index efccc8300..b3b16d962 100644 --- a/crates/mega-evm/benches/corpus.rs +++ b/crates/mega-evm/benches/corpus.rs @@ -1,11 +1,15 @@ //! A set of JSON scenarios through `MegaEvm`. //! //! The inputs are the scenarios under `benches/scenarios` (the `test_utils::Scenario` format), -//! picked to spread over the mechanisms the engine runs. They are bench inputs, not a conformance -//! suite: nothing here compares their outcome with another engine, so an instruction-count change -//! means only that the execution or the pricing of those scenarios moved. Each scenario runs all -//! its transactions, one fresh `MegaEvm` per transaction; building the pre-state is setup and is -//! not measured. +//! picked to spread over the mechanisms the engine runs. They are bench inputs. Their outcome +//! and gas are pinned by a test, `tests/satin/corpus.rs`, so a pricing change that takes a +//! shorter path fails there instead of being timed here. +//! +//! A scenario is a block: one `MegaEvm`, built with the pre-state in the setup, runs all its +//! transactions and commits each before the next (`Scenario::run_on`). What is measured is the +//! transactions and their commits; building the EVM, like building the pre-state, is setup and is +//! not measured, as in `transact`, so the two families measure per-transaction execution alike. +//! The one difference is the commit to the in-memory database, which `transact` does not do. #![allow(missing_docs)] use std::path::Path; @@ -33,31 +37,30 @@ const SLICE: &[(&str, &str)] = &[ ("modexp", "precompile_modexp"), ]; -fn load(path: &str) -> Scenario { - let file = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("benches/scenarios") - .join(format!("{path}.json")); - let text = std::fs::read_to_string(&file).unwrap_or_else(|err| panic!("{file:?}: {err}")); - let scenario: Scenario = serde_json::from_str(&text).unwrap(); - scenario.validate().unwrap(); - scenario -} - fn bench_corpus(c: &mut Criterion) { let mut group = c.benchmark_group("corpus"); - for (id, path) in SLICE { - let scenario = load(path); - // The measured path must be the scenario's execution, not a rejected transaction. - let (outcomes, _) = scenario.run(scenario.database()); - for (i, outcome) in outcomes.iter().enumerate() { - assert!(outcome.is_ok(), "{path}: tx[{i}] is rejected: {outcome:?}"); - } + for (id, name) in SLICE { + let scenario = load(name); group.bench_function(*id, |b| { - b.iter_batched(|| scenario.database(), |db| scenario.run(db), BatchSize::SmallInput); + b.iter_batched( + || scenario.evm(scenario.database()), + |mut evm| scenario.run_on(&mut evm), + BatchSize::SmallInput, + ); }); } group.finish(); } +fn load(name: &str) -> Scenario { + let file = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!("benches/scenarios/{name}.json")); + let text = std::fs::read_to_string(&file).unwrap_or_else(|err| panic!("{file:?}: {err}")); + let scenario: Scenario = serde_json::from_str(&text).unwrap_or_else(|err| { + panic!("{file:?}: {err}"); + }); + scenario.validate().unwrap_or_else(|err| panic!("{file:?}: {err}")); + scenario +} + criterion_group!(benches, bench_corpus); criterion_main!(benches); diff --git a/crates/mega-evm/benches/data/analysis.hex b/crates/mega-evm/benches/data/analysis.hex deleted file mode 100644 index 4d2cbe91b..000000000 --- a/crates/mega-evm/benches/data/analysis.hex +++ /dev/null @@ -1 +0,0 @@ -6060604052341561000f57600080fd5b604051610dd1380380610dd18339810160405280805190602001909190805182019190602001805190602001909190805182019190505083600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508360008190555082600390805190602001906100a79291906100e3565b5081600460006101000a81548160ff021916908360ff16021790555080600590805190602001906100d99291906100e3565b5050505050610188565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061012457805160ff1916838001178555610152565b82800160010185558215610152579182015b82811115610151578251825591602001919060010190610136565b5b50905061015f9190610163565b5090565b61018591905b80821115610181576000816000905550600101610169565b5090565b90565b610c3a806101976000396000f3006060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a72305820df254047bc8f2904ad3e966b6db116d703bebd40efadadb5e738c836ffc8f58a0029 \ No newline at end of file diff --git a/crates/mega-evm/benches/data/snailtracer.hex b/crates/mega-evm/benches/data/snailtracer.hex deleted file mode 100644 index 954618729..000000000 --- a/crates/mega-evm/benches/data/snailtracer.hex +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b506004361061004c5760003560e01c806330627b7c1461005157806375ac892a14610085578063784f13661461011d578063c294360114610146575b600080fd5b610059610163565b604080516001600160f81b03199485168152928416602084015292168183015290519081900360600190f35b6100a86004803603604081101561009b57600080fd5b50803590602001356102d1565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100e25781810151838201526020016100ca565b50505050905090810190601f16801561010f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100596004803603606081101561013357600080fd5b508035906020810135906040013561055b565b6100a86004803603602081101561015c57600080fd5b5035610590565b6000806000610176610400610300610834565b60405180606001604052806001546000546207d5dc028161019357fe5b058152600060208083018290526040928301919091528251600b81905583820151600c81905593830151600d819055835160608082018652928152808401959095528484015282519081018352600654815260075491810191909152600854918101919091526102259161021c916102139161020e91612ef7565b612f64565b6207d5dc612feb565b620f424061301e565b8051600e556020810151600f55604001516010556102416142dd565b61025a816102556102006101806008613064565b613212565b90506102708161025561014561021c6008613064565b905061028481610255610258806008613064565b905061029a8161025561020a61020c6008613064565b90506102a781600461301e565b90506102b1613250565b8051602082015160409092015160f891821b9692821b9550901b92509050565b606060005b6000548112156104c95760006102ed828686613064565b90506002816000015160f81b90808054603f811680603e811461032a576002830184556001831661031c578192505b600160028404019350610342565b600084815260209081902060ff198516905560419094555b505050600190038154600116156103685790600052602060002090602091828204019190065b909190919091601f036101000a81548160ff02191690600160f81b840402179055506002816020015160f81b90808054603f811680603e81146103c557600283018455600183166103b7578192505b6001600284040193506103dd565b600084815260209081902060ff198516905560419094555b505050600190038154600116156104035790600052602060002090602091828204019190065b909190919091601f036101000a81548160ff02191690600160f81b840402179055506002816040015160f81b90808054603f811680603e81146104605760028301845560018316610452578192505b600160028404019350610478565b600084815260209081902060ff198516905560419094555b5050506001900381546001161561049e5790600052602060002090602091828204019190065b815460ff601f929092036101000a9182021916600160f81b90930402919091179055506001016102d6565b506002805460408051602060018416156101000260001901909316849004601f8101849004840282018401909252818152929183018282801561054d5780601f106105225761010080835404028352916020019161054d565b820191906000526020600020905b81548152906001019060200180831161053057829003601f168201915b505050505090505b92915050565b60008060008061056c878787613064565b8051602082015160409092015160f891821b9a92821b9950901b9650945050505050565b600154606090600019015b600081126107a35760005b6000548112156107995760006105bd828487613064565b90506002816000015160f81b90808054603f811680603e81146105fa57600283018455600183166105ec578192505b600160028404019350610612565b600084815260209081902060ff198516905560419094555b505050600190038154600116156106385790600052602060002090602091828204019190065b909190919091601f036101000a81548160ff02191690600160f81b840402179055506002816020015160f81b90808054603f811680603e81146106955760028301845560018316610687578192505b6001600284040193506106ad565b600084815260209081902060ff198516905560419094555b505050600190038154600116156106d35790600052602060002090602091828204019190065b909190919091601f036101000a81548160ff02191690600160f81b840402179055506002816040015160f81b90808054603f811680603e81146107305760028301845560018316610722578192505b600160028404019350610748565b600084815260209081902060ff198516905560419094555b5050506001900381546001161561076e5790600052602060002090602091828204019190065b815460ff601f929092036101000a9182021916600160f81b90930402919091179055506001016105a6565b506000190161059b565b506002805460408051602060018416156101000260001901909316849004601f810184900484028201840190925281815292918301828280156108275780601f106107fc57610100808354040283529160200191610827565b820191906000526020600020905b81548152906001019060200180831161080a57829003601f168201915b505050505090505b919050565b8160008190555080600181905550604051806080016040528060405180606001604052806302faf08081526020016303197500815260200163119e7f8081525081526020016108a460405180606001604052806000815260200161a673198152602001620f423f19815250612f64565b815260006020808301829052604092830182905283518051600355808201516004558301516005558381015180516006559081015160075582015160085582820151600955606092830151600a805460ff1916911515919091179055815192830190915260015490548291906207d5dc028161091c57fe5b058152600060208083018290526040928301919091528251600b81905583820151600c81905593830151600d819055835160608082018652928152808401959095528484015282519081018352600654815260075491810191909152600854918101919091526109979161021c916102139161020e91612ef7565b8051600e55602080820151600f55604091820151601055815160a08101835264174876e8008152825160608082018552641748862a40825263026e8f00828501526304dd1e008286015282840191825284518082018652600080825281860181905281870181905284870191825286518084018852620b71b081526203d09081880181905281890152928501928352608085018181526011805460018082018355919093528651600b9093027f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c688101938455955180517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c69880155808901517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6a8801558901517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6b870155925180517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6c870155808801517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6d8701558801517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6e860155925180517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c6f860155958601517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c7085015594909501517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c71830155517f31ecc21a745e3968a04e9570e4425bc18fa8019c68028196b546d1669c200c72909101805492949192909160ff1990911690836002811115610c1057fe5b0217905550505060116040518060a0016040528064174876e8008152602001604051806060016040528064174290493f19815260200163026e8f0081526020016304dd1e008152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806203d09081526020016203d0908152602001620b71b0815250815260200160006002811115610cb657fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff1990921691908490811115610d5857fe5b0217905550505060116040518060a0016040528064174876e800815260200160405180606001604052806302faf080815260200163026e8f00815260200164174876e800815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620b71b08152602001620b71b08152602001620b71b0815250815260200160006002811115610dfd57fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff1990921691908490811115610e9f57fe5b0217905550505060116040518060a0016040528064174876e800815260200160405180606001604052806302faf080815260200163026e8f00815260200164173e54e97f1981525081526020016040518060600160405280600081526020016000815260200160008152508152602001604051806060016040528060008152602001600081526020016000815250815260200160006002811115610f3f57fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff1990921691908490811115610fe157fe5b0217905550505060116040518060a0016040528064174876e800815260200160405180606001604052806302faf080815260200164174876e80081526020016304dd1e00815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620b71b08152602001620b71b08152602001620b71b081525081526020016000600281111561108657fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff199092169190849081111561112857fe5b0217905550505060116040518060a0016040528064174876e800815260200160405180606001604052806302faf080815260200164174399c9ff1981526020016304dd1e00815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620b71b08152602001620b71b08152602001620b71b08152508152602001600060028111156111ce57fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff199092169190849081111561127057fe5b0217905550505060116040518060a0016040528062fbc5208152602001604051806060016040528063019bfcc0815260200162fbc52081526020016302cd29c0815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561131157fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff19909216919084908111156113b357fe5b0217905550505060116040518060a001604052806323c34600815260200160405180606001604052806302faf080815260200163289c455081526020016304dd1e008152508152602001604051806060016040528062b71b00815260200162b71b00815260200162b71b00815250815260200160405180606001604052806000815260200160008152602001600081525081526020016000600281111561145657fe5b905281546001818101845560009384526020938490208351600b90930201918255838301518051838301558085015160028085019190915560409182015160038501558185015180516004860155808701516005860155820151600685015560608501518051600786015595860151600885015594015160098301556080830151600a83018054949593949193909260ff19909216919084908111156114f857fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f208152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016305a1f4a081525081526020016040518060600160405280630459e44081526020016302f34f6081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561160c57fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff19909216919084908111156116fd57fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f20815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001600081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016305a1f4a08152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561180e57fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff19909216919084908111156118ff57fe5b0217905550505060126040518060e001604052806040518060600160405280630555a9608152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e44081526020016302f34f6081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016305a1f4a08152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e58815250815260200160016002811115611a1357fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff1990921691908490811115611b0457fe5b0217905550505060126040518060e001604052806040518060600160405280630555a960815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016305a1f4a081525081526020016040518060600160405280630459e4408152602001600081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e58815250815260200160016002811115611c1557fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff1990921691908490811115611d0657fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f208152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e44081526020016302f34f6081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016303aa6a608152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e58815250815260200160016002811115611e1a57fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff1990921691908490811115611f0b57fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f20815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016303aa6a6081525081526020016040518060600160405280630459e4408152602001600081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561201c57fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff199092169190849081111561210d57fe5b0217905550505060126040518060e001604052806040518060600160405280630555a9608152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016303aa6a6081525081526020016040518060600160405280630459e44081526020016302f34f6081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561222157fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff199092169190849081111561231257fe5b0217905550505060126040518060e001604052806040518060600160405280630555a960815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001600081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016303aa6a608152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561242357fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff199092169190849081111561251457fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f208152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016303aa6a6081525081526020016040518060600160405280630555a9608152602001630188c2e081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561262857fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff199092169190849081111561271957fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f208152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630555a9608152602001630188c2e081526020016304a62f8081525081526020016040518060600160405280630459e4408152602001630188c2e081526020016305a1f4a08152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e5881525081526020016001600281111561282d57fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff199092169190849081111561291e57fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f20815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630555a960815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016303aa6a608152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e58815250815260200160016002811115612a3257fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff1990921691908490811115612b2357fe5b0217905550505060126040518060e00160405280604051806060016040528063035e1f20815260200163016a8c8081526020016304a62f8081525081526020016040518060600160405280630459e440815260200163016a8c8081526020016305a1f4a081525081526020016040518060600160405280630555a960815260200163016a8c8081526020016304a62f808152508152602001604051806060016040528060008152602001600081526020016000815250815260200160405180606001604052806000815260200160008152602001600081525081526020016040518060600160405280620f3e588152602001620f3e588152602001620f3e58815250815260200160016002811115612c3757fe5b905281546001818101845560009384526020938490208351805160139094029091019283558085015183830155604090810151600280850191909155858501518051600386015580870151600486015582015160058501558185015180516006860155808701516007860155820151600885015560608501518051600986015580870151600a860155820151600b85015560808501518051600c86015580870151600d860155820151600e85015560a08501518051600f860155958601516010850155940151601183015560c0830151601283018054949593949193909260ff1990921691908490811115612d2857fe5b0217905550505060005b601254811015612ef257600060128281548110612d4b57fe5b600091825260209182902060408051610140810182526013909302909101805460e08401908152600182015461010085015260028083015461012086015290845282516060818101855260038401548252600484015482880152600584015482860152858701919091528351808201855260068401548152600784015481880152600884015481860152858501528351808201855260098401548152600a84015481880152600b840154818601528186015283518082018552600c8401548152600d84015481880152600e84015481860152608086015283519081018452600f830154815260108301549581019590955260118201549285019290925260a0830193909352601283015491929160c084019160ff90911690811115612e6c57fe5b6002811115612e7757fe5b815250509050612eac61020e612e95836020015184600001516132cd565b612ea7846040015185600001516132cd565b612ef7565b60128381548110612eb957fe5b60009182526020918290208351600960139093029091019182015590820151600a820155604090910151600b9091015550600101612d32565b505050565b612eff6142dd565b604051806060016040528083602001518560400151028460400151866020015102038152602001836040015185600001510284600001518660400151020381526020018360000151856020015102846020015186600001510203815250905092915050565b612f6c6142dd565b604082015160208301518351600092612f9292918002918002919091019080020161330c565b90506040518060600160405280828560000151620f42400281612fb157fe5b058152602001828560200151620f42400281612fc957fe5b058152602001828560400151620f42400281612fe157fe5b0590529392505050565b612ff36142dd565b5060408051606081018252835183028152602080850151840290820152928101519091029082015290565b6130266142dd565b60405180606001604052808385600001518161303e57fe5b0581526020018385602001518161305157fe5b05815260200183856040015181612fe157fe5b61306c6142dd565b6000546013805463ffffffff1916918502860163ffffffff169190911790556130936142dd565b905060005b828112156131f157600061317261314c61021c613115600b60405180606001604052908160008201548152602001600182015481526020016002820154815250506207a1206000546207a1206130ec613343565b63ffffffff16816130f957fe5b0663ffffffff168d620f424002018161310e57fe5b0503612feb565b60408051606081018252600e548152600f5460208201526010549181019190915260015461025591906207a12090816130ec613343565b604080516060810182526006548152600754602082015260085491810191909152613212565b6040805160e081019091526003546080820190815260045460a083015260055460c083015291925060009181906131ae9061025586608c612feb565b81526020016131bc84612f64565b815260006020820181905260409091015290506131e5846102556131df8461336c565b8861301e565b93505050600101613098565b5061320861021c61320183613753565b60ff612feb565b90505b9392505050565b61321a6142dd565b50604080516060810182528251845101815260208084015181860151019082015291810151928101519092019181019190915290565b60008080556001819055613266906002906142fe565b60006003819055600481905560058190556006819055600781905560088190556009819055600a805460ff19169055600b819055600c819055600d819055600e819055600f81905560108190556132bf90601190614345565b6132cb60126000614366565b565b6132d56142dd565b5060408051606081018252825184510381526020808401518186015103908201528282015184830151039181019190915292915050565b80600260018201055b8181121561333d5780915060028182858161332c57fe5b05018161333557fe5b059050613315565b50919050565b6013805463ffffffff19811663ffffffff9182166341c64e6d0261303901821617918290551690565b6133746142dd565b600a826040015113156133a657604051806060016040528060008152602001600081526020016000815250905061082f565b60008060006133b48561379f565b91945092509050826133e857604051806060016040528060008152602001600081526020016000815250935050505061082f565b6133f0614387565b6133f86143c7565b6134006142dd565b6134086142dd565b600086600181111561341657fe5b1415613505576011858154811061342957fe5b60009182526020918290206040805160a081018252600b90930290910180548352815160608082018452600183015482526002808401548388015260038401548386015285870192909252835180820185526004840154815260058401548188015260068401548186015285850152835180820185526007840154815260088401549681019690965260098301549386019390935291830193909352600a830154919291608084019160ff909116908111156134e157fe5b60028111156134ec57fe5b8152505093508360600151915083604001519050613653565b6012858154811061351257fe5b600091825260209182902060408051610140810182526013909302909101805460e08401908152600182015461010085015260028083015461012086015290845282516060818101855260038401548252600484015482880152600584015482860152858701919091528351808201855260068401548152600784015481880152600884015481860152858501528351808201855260098401548152600a84015481880152600b840154818601528186015283518082018552600c8401548152600d84015481880152600e84015481860152608086015283519081018452600f830154815260108301549581019590955260118201549285019290925260a0830193909352601283015491929160c084019160ff9091169081111561363357fe5b600281111561363e57fe5b8152505092508260a001519150826080015190505b6040820151600190811215613669575060408201515b808360200151131561367c575060208201515b808360400151131561368f575060408201515b60408a01805160010190819052600512156136f75780620f42406136b1613343565b63ffffffff16816136be57fe5b0663ffffffff1612156136e8576136e16136db84620f4240612feb565b8261301e565b92506136f7565b50965061082f95505050505050565b6136ff6142dd565b600088600181111561370d57fe5b14156137255761371e8b878b613a57565b9050613733565b6137308b868b613aec565b90505b6137448361025561021c8785613baa565b9b9a5050505050505050505050565b61375b6142dd565b60405180606001604052806137738460000151613be8565b81526020016137858460200151613be8565b81526020016137978460400151613be8565b905292915050565b60008080808080805b6011548110156138c2576000613890601183815481106137c457fe5b60009182526020918290206040805160a081018252600b90930290910180548352815160608082018452600183015482526002808401548388015260038401548386015285870192909252835180820185526004840154815260058401548188015260068401548186015285850152835180820185526007840154815260088401549681019690965260098301549386019390935291830193909352600a830154919291608084019160ff9091169081111561387c57fe5b600281111561388757fe5b9052508a613c13565b90506000811380156138a957508415806138a957508481125b156138b957809450600093508192505b506001016137a8565b5060005b601254811015613a49576000613a17601283815481106138e257fe5b600091825260209182902060408051610140810182526013909302909101805460e08401908152600182015461010085015260028083015461012086015290845282516060818101855260038401548252600484015482880152600584015482860152858701919091528351808201855260068401548152600784015481880152600884015481860152858501528351808201855260098401548152600a84015481880152600b840154818601528186015283518082018552600c8401548152600d84015481880152600e84015481860152608086015283519081018452600f830154815260108301549581019590955260118201549285019290925260a0830193909352601283015491929160c084019160ff90911690811115613a0357fe5b6002811115613a0e57fe5b9052508a613cbb565b9050600081138015613a305750841580613a3057508481125b15613a4057809450600193508192505b506001016138c6565b509196909550909350915050565b613a5f6142dd565b6000613a7a856000015161025561021c886020015187612feb565b90506000613a8f61020e8387602001516132cd565b9050600085608001516002811115613aa357fe5b1415613ae1576000613ab9828860200151613e0c565b12613acd57613aca81600019612feb565b90505b613ad8868383613e31565b9250505061320b565b613ad8868383613fc1565b613af46142dd565b6000613b0f856000015161025561021c886020015187612feb565b6060860151909150620a2c2a9015613b2757506216e3605b6000620f4240613b3f87606001518960200151613e0c565b81613b4657fe5b05905060008112613b55576000035b64e8d4a5100081800281038380020281900590036000811215613b8c57613b8188858960600151613fc1565b94505050505061320b565b613b9e88858960600151868686614039565b98975050505050505050565b613bb26142dd565b50604080516060810182528251845102815260208084015181860151029082015291810151928101519092029181019190915290565b600080821215613bfa5750600061082f565b620f4240821315613c0f5750620f424061082f565b5090565b600080613c28846020015184600001516132cd565b90506000620f4240613c3e838660200151613e0c565b81613c4557fe5b865191900591506000908002613c5b8480613e0c565b838402030190506000811215613c775760009350505050610555565b613c808161330c565b90506103e88183031315613c9957900391506105559050565b6103e88183011315613caf570191506105559050565b50600095945050505050565b600080613cd0846020015185600001516132cd565b90506000613ce6856040015186600001516132cd565b90506000613cf8856020015183612ef7565b90506000620f4240613d0a8584613e0c565b81613d1157fe5b0590506103e71981138015613d2757506103e881125b15613d39576000945050505050610555565b85518751600091613d49916132cd565b9050600082613d588386613e0c565b81613d5f57fe5b0590506000811280613d735750620f424081135b15613d875760009650505050505050610555565b6000613d938388612ef7565b9050600084613da68b6020015184613e0c565b81613dad57fe5b0590506000811280613dc35750620f4240818401135b15613dd957600098505050505050505050610555565b600085613de68985613e0c565b81613ded57fe5b0590506103e88112156137445760009950505050505050505050610555565b6040808201519083015160208084015190850151845186510291020191020192915050565b613e396142dd565b6000620f424080613e48613343565b63ffffffff1681613e5557fe5b0663ffffffff16625fdfb00281613e6857fe5b0590506000620f4240613e79613343565b63ffffffff1681613e8657fe5b0663ffffffff1690506000613e9a8261330c565b6103e8029050613ea86142dd565b620186a0613eb98760000151614216565b1315613ee657604051806060016040528060008152602001620f4240815260200160008152509050613f09565b6040518060600160405280620f4240815260200160008152602001600081525090505b613f1661020e8288612ef7565b90506000613f2761020e8884612ef7565b9050613f7f61020e613f64613f5285620f424088613f448c61422e565b0281613f4c57fe5b05612feb565b61025585620f424089613f448d61424e565b6102558a613f7689620f42400361330c565b6103e802612feb565b9150613fb460405180608001604052808a81526020018481526020018b6040015181526020018b60600151151581525061336c565b9998505050505050505050565b613fc96142dd565b6000613ffb61020e8660200151613ff686620f4240613fec898c60200151613e0c565b60020281613f4c57fe5b6132cd565b90506140306040518060800160405280868152602001838152602001876040015181526020018760600151151581525061336c565b95945050505050565b6140416142dd565b60608701516000199015614053575060015b600061408961020e61021c61406c8c602001518a612feb565b613ff68b6140798a61330c565b620f42408c8e0205018802612feb565b60608a0151909150620f42408601906140ba57620f42406140aa838a613e0c565b816140b157fe5b05620f42400390505b60408a0151619c406c0c9f2c9cd04674edea40000000620ea6008480028502850285020205019060021261415e5761412a61411f60405180608001604052808d81526020018681526020018e6040015181526020018e6060015115151581525061336c565b82620f424003612feb565b92506141448361025561413e8e8e8e613fc1565b84612feb565b925061415383620f424061301e565b94505050505061420c565b600281056203d09001620f4240614173613343565b63ffffffff168161418057fe5b0663ffffffff1612156141b2576141536141a461419e8d8d8d613fc1565b83612feb565b600283056203d0900161301e565b6142056141f76141ec60405180608001604052808e81526020018781526020018f6040015181526020018f6060015115151581525061336c565b83620f424003612feb565b60028305620b71b00361301e565b9450505050505b9695505050505050565b60008082131561422757508061082f565b5060000390565b60008061423a8361424e565b905061320b81820264e8d4a510000361330c565b60005b600082121561426757625fdfb082019150614251565b5b625fdfb0821261427f57625fdfb082039150614268565b6001828160025b818313156142d457818385028161429957fe5b0585019450620f4240808788860202816142af57fe5b05816142b757fe5b600095909503940592506001810181029190910290600201614286565b50505050919050565b60405180606001604052806000815260200160008152602001600081525090565b50805460018160011615610100020316600290046000825580601f106143245750614342565b601f0160209004906000526020600020908101906143429190614401565b50565b50805460008255600b02906000526020600020908101906143429190614416565b50805460008255601302906000526020600020908101906143429190614475565b6040518060a00160405280600081526020016143a16142dd565b81526020016143ae6142dd565b81526020016143bb6142dd565b81526020016000905290565b6040518060e001604052806143da6142dd565b81526020016143e76142dd565b81526020016143f46142dd565b81526020016143a16142dd565b5b80821115613c0f5760008155600101614402565b5b80821115613c0f57600080825560018201819055600282018190556003820181905560048201819055600582018190556006820181905560078201819055600882018190556009820155600a8101805460ff19169055600b01614417565b5b80821115613c0f576000808255600182018190556002820181905560038201819055600482018190556005820181905560068201819055600782018190556008820181905560098201819055600a8201819055600b8201819055600c8201819055600d8201819055600e8201819055600f820181905560108201819055601182015560128101805460ff1916905560130161447656fea2646970667358221220037024f5647853879c58fbcc61ac3616455f6f731cc6e84f91eb5a3b4e06c00464736f6c63430007060033 \ No newline at end of file diff --git a/crates/mega-evm/benches/fixtures/known_attack_deploy.json b/crates/mega-evm/benches/fixtures/known_attack_deploy.json deleted file mode 100644 index aae4e07c8..000000000 --- a/crates/mega-evm/benches/fixtures/known_attack_deploy.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "description": "MegaETH mainnet attack contract deployment. State snapshot captured via debug_traceCall + prestateTracer at MegaETH mainnet block 16623578 (0xfda9da) on 2026-05-22. The constructor depends on multiple existing contracts on mainnet (proxy contracts at 0x4200..., an ERC20 at 0x578d...), so the prestate must be loaded before replaying this deploy.", - "tx": { - "caller": "0xfb0de6ab3cd3aeee1b3abeb51ee3b98d576e929b", - "nonce": 5, - "gas_limit": 1200000000, - "max_fee_per_gas": 2000000, - "max_priority_fee_per_gas": 1000000, - "value": "0x0", - "chain_id": 4326, - "input": "0x608060405234801561000f575f5ffd5b5060405161432638038061432683398181016040528101906100319190610723565b5f73ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff160361009f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100969061082e565b60405180910390fd5b600a8710156100e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100da906108bc565b60405180910390fd5b5f600a886100f19190610934565b90505f8990505f828a6101049190610964565b90508a73ffffffffffffffffffffffffffffffffffffffff1663d505accf89307fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8b8b8b8b6040518863ffffffff1660e01b815260040161016b97969594939291906109d3565b5f604051808303815f87803b158015610182575f5ffd5b505af1158015610194573d5f5f3e3d5ffd5b505050508173ffffffffffffffffffffffffffffffffffffffff166323b872dd8930846040518463ffffffff1660e01b81526004016101d593929190610a40565b6020604051808303815f875af11580156101f1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102159190610aaa565b508a60405161022390610602565b61022d9190610ad5565b604051809103905ff080158015610246573d5f5f3e3d5ffd5b505f5f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff1663095ea7b35f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff168c6040518363ffffffff1660e01b81526004016102e0929190610aee565b6020604051808303815f875af11580156102fc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103209190610aaa565b505f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663b6b55f258b6040518263ffffffff1660e01b815260040161037a9190610b15565b5f604051808303815f87803b158015610391575f5ffd5b505af11580156103a3573d5f5f3e3d5ffd5b505050508a6040516103b49061060f565b6103be9190610ad5565b604051809103905ff0801580156103d7573d5f5f3e3d5ffd5b5060015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508173ffffffffffffffffffffffffffffffffffffffff1663a9059cbb60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16856040518363ffffffff1660e01b8152600401610473929190610aee565b6020604051808303815f875af115801561048f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104b39190610aaa565b505f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff168b6040516104e29061061c565b6104ed929190610b2e565b604051809103905ff080158015610506573d5f5f3e3d5ffd5b5060025f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060025f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166388a8aec660015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16858c6040518463ffffffff1660e01b81526004016105c593929190610b55565b5f604051808303815f87803b1580156105dc575f5ffd5b505af11580156105ee573d5f5f3e3d5ffd5b505050505050505050505050505050610b8a565b610c3c80610ddd83390190565b610d4280611a1983390190565b611bcb8061275b83390190565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6106568261062d565b9050919050565b6106668161064c565b8114610670575f5ffd5b50565b5f815190506106818161065d565b92915050565b5f819050919050565b61069981610687565b81146106a3575f5ffd5b50565b5f815190506106b481610690565b92915050565b5f60ff82169050919050565b6106cf816106ba565b81146106d9575f5ffd5b50565b5f815190506106ea816106c6565b92915050565b5f819050919050565b610702816106f0565b811461070c575f5ffd5b50565b5f8151905061071d816106f9565b92915050565b5f5f5f5f5f5f5f5f610100898b0312156107405761073f610629565b5b5f61074d8b828c01610673565b985050602061075e8b828c016106a6565b975050604061076f8b828c01610673565b96505060606107808b828c01610673565b95505060806107918b828c016106a6565b94505060a06107a28b828c016106dc565b93505060c06107b38b828c0161070f565b92505060e06107c48b828c0161070f565b9150509295985092959890939650565b5f82825260208201905092915050565b7f4578706c6f697453657475703a207a65726f20726563656976657200000000005f82015250565b5f610818601b836107d4565b9150610823826107e4565b602082019050919050565b5f6020820190508181035f8301526108458161080c565b9050919050565b7f4578706c6f697453657475703a2073656564416d6f756e7420746f6f20736d615f8201527f6c6c000000000000000000000000000000000000000000000000000000000000602082015250565b5f6108a66022836107d4565b91506108b18261084c565b604082019050919050565b5f6020820190508181035f8301526108d38161089a565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61093e82610687565b915061094983610687565b925082610959576109586108da565b5b828204905092915050565b5f61096e82610687565b915061097983610687565b925082820190508082111561099157610990610907565b5b92915050565b6109a08161064c565b82525050565b6109af81610687565b82525050565b6109be816106ba565b82525050565b6109cd816106f0565b82525050565b5f60e0820190506109e65f83018a610997565b6109f36020830189610997565b610a0060408301886109a6565b610a0d60608301876109a6565b610a1a60808301866109b5565b610a2760a08301856109c4565b610a3460c08301846109c4565b98975050505050505050565b5f606082019050610a535f830186610997565b610a606020830185610997565b610a6d60408301846109a6565b949350505050565b5f8115159050919050565b610a8981610a75565b8114610a93575f5ffd5b50565b5f81519050610aa481610a80565b92915050565b5f60208284031215610abf57610abe610629565b5b5f610acc84828501610a96565b91505092915050565b5f602082019050610ae85f830184610997565b92915050565b5f604082019050610b015f830185610997565b610b0e60208301846109a6565b9392505050565b5f602082019050610b285f8301846109a6565b92915050565b5f604082019050610b415f830185610997565b610b4e6020830184610997565b9392505050565b5f606082019050610b685f830186610997565b610b7560208301856109a6565b610b826040830184610997565b949350505050565b61024680610b975f395ff3fe608060405234801561000f575f5ffd5b506004361061003f575f3560e01c806348eb76ee14610043578063bcead63e14610061578063fbfa77cf1461007f575b5f5ffd5b61004b61009d565b6040516100589190610185565b60405180910390f35b6100696100c2565b60405161007691906101be565b60405180910390f35b6100876100e7565b60405161009491906101f7565b60405180910390f35b60025f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f5f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f819050919050565b5f61014d6101486101438461010b565b61012a565b61010b565b9050919050565b5f61015e82610133565b9050919050565b5f61016f82610154565b9050919050565b61017f81610165565b82525050565b5f6020820190506101985f830184610176565b92915050565b5f6101a882610154565b9050919050565b6101b88161019e565b82525050565b5f6020820190506101d15f8301846101af565b92915050565b5f6101e182610154565b9050919050565b6101f1816101d7565b82525050565b5f60208201905061020a5f8301846101e8565b9291505056fea2646970667358221220ab8ca3bad83057bc6502e4d5e818ec45197087ada5dff4a28bd506a700a0182364736f6c634300081e003360a060405234801561000f575f5ffd5b50604051610c3c380380610c3c833981810160405281019061003191906100c9565b8073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff1681525050506100f4565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100988261006f565b9050919050565b6100a88161008e565b81146100b2575f5ffd5b50565b5f815190506100c38161009f565b92915050565b5f602082840312156100de576100dd61006b565b5b5f6100eb848285016100b5565b91505092915050565b608051610b1b6101215f395f81816101b20152818161039b0152818161044a01526105ba0152610b1b5ff3fe608060405234801561000f575f5ffd5b506004361061005f575f3560e01c8062f714ce1461006357806301e1d1141461007f5780633a98ef391461009d578063b6b55f25146100bb578063ce7c2ac2146100d7578063fc0c546a14610107575b5f5ffd5b61007d600480360381019061007891906106cf565b610125565b005b610087610398565b604051610094919061071c565b60405180910390f35b6100a5610436565b6040516100b2919061071c565b60405180910390f35b6100d560048036038101906100d09190610735565b61043c565b005b6100f160048036038101906100ec9190610760565b6105a4565b6040516100fe919061071c565b60405180910390f35b61010f6105b8565b60405161011c91906107e6565b60405180910390f35b815f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205410156101a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161019b9061087f565b60405180910390fd5b5f6101ae836105dc565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b815260040161020b9291906108ac565b6020604051808303815f875af1158015610227573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061024b9190610908565b505f8273ffffffffffffffffffffffffffffffffffffffff163b11156102d4578173ffffffffffffffffffffffffffffffffffffffff16633531bb2833836040518363ffffffff1660e01b81526004016102a69291906108ac565b5f604051808303815f87803b1580156102bd575f5ffd5b505af11580156102cf573d5f5f3e3d5ffd5b505050505b825f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825403925050819055508260015f82825403925050819055508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167ff341246adaac6f497bc2a656f546ab9e182111d630394f0c57c710a59a2cb567838660405161038b929190610933565b60405180910390a3505050565b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016103f2919061095a565b602060405180830381865afa15801561040d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104319190610987565b905090565b60015481565b5f61044682610604565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b81526004016104a5939291906109b2565b6020604051808303815f875af11580156104c1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e59190610908565b50805f5f3373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282546105319190610a14565b925050819055508060015f8282546105499190610a14565b925050819055503373ffffffffffffffffffffffffffffffffffffffff167f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a158383604051610598929190610933565b60405180910390a25050565b5f602052805f5260405f205f915090505481565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f6001546105e8610398565b836105f39190610a47565b6105fd9190610ab5565b9050919050565b5f5f6001540361061657819050610639565b61061e610398565b6001548361062c9190610a47565b6106369190610ab5565b90505b919050565b5f5ffd5b5f819050919050565b61065481610642565b811461065e575f5ffd5b50565b5f8135905061066f8161064b565b92915050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61069e82610675565b9050919050565b6106ae81610694565b81146106b8575f5ffd5b50565b5f813590506106c9816106a5565b92915050565b5f5f604083850312156106e5576106e461063e565b5b5f6106f285828601610661565b9250506020610703858286016106bb565b9150509250929050565b61071681610642565b82525050565b5f60208201905061072f5f83018461070d565b92915050565b5f6020828403121561074a5761074961063e565b5b5f61075784828501610661565b91505092915050565b5f602082840312156107755761077461063e565b5b5f610782848285016106bb565b91505092915050565b5f819050919050565b5f6107ae6107a96107a484610675565b61078b565b610675565b9050919050565b5f6107bf82610794565b9050919050565b5f6107d0826107b5565b9050919050565b6107e0816107c6565b82525050565b5f6020820190506107f95f8301846107d7565b92915050565b5f82825260208201905092915050565b7f56756c6e657261626c655661756c743a20696e73756666696369656e742073685f8201527f6172657300000000000000000000000000000000000000000000000000000000602082015250565b5f6108696024836107ff565b91506108748261080f565b604082019050919050565b5f6020820190508181035f8301526108968161085d565b9050919050565b6108a681610694565b82525050565b5f6040820190506108bf5f83018561089d565b6108cc602083018461070d565b9392505050565b5f8115159050919050565b6108e7816108d3565b81146108f1575f5ffd5b50565b5f81519050610902816108de565b92915050565b5f6020828403121561091d5761091c61063e565b5b5f61092a848285016108f4565b91505092915050565b5f6040820190506109465f83018561070d565b610953602083018461070d565b9392505050565b5f60208201905061096d5f83018461089d565b92915050565b5f815190506109818161064b565b92915050565b5f6020828403121561099c5761099b61063e565b5b5f6109a984828501610973565b91505092915050565b5f6060820190506109c55f83018661089d565b6109d2602083018561089d565b6109df604083018461070d565b949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f610a1e82610642565b9150610a2983610642565b9250828201905080821115610a4157610a406109e7565b5b92915050565b5f610a5182610642565b9150610a5c83610642565b9250828202610a6a81610642565b91508282048414831517610a8157610a806109e7565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f610abf82610642565b9150610aca83610642565b925082610ada57610ad9610a88565b5b82820490509291505056fea26469706673582212202a8c0a6b9c40bfa0255196a7ac23db2258484ca87e3a6a9d5a996a2ff8383b1264736f6c634300081e003360a060405234801561000f575f5ffd5b50604051610d42380380610d42833981810160405281019061003191906100c9565b8073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff1681525050506100f4565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100988261006f565b9050919050565b6100a88161008e565b81146100b2575f5ffd5b50565b5f815190506100c38161009f565b92915050565b5f602082840312156100de576100dd61006b565b5b5f6100eb848285016100b5565b91505092915050565b608051610c0d6101355f395f818160c7015281816101a70152818161028101528181610338015281816103f00152818161046e01526105a30152610c0d5ff3fe608060405234801561000f575f5ffd5b506004361061004a575f3560e01c806315770f921461004e5780635296a4311461006c578063bf333f2c14610088578063fc0c546a146100a6575b5f5ffd5b6100566100c4565b60405161006391906105dd565b60405180910390f35b61008660048036038101906100819190610689565b610162565b005b61009061059c565b60405161009d91906105dd565b60405180910390f35b6100ae6105a1565b6040516100bb9190610760565b60405180910390f35b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161011e9190610799565b602060405180830381865afa158015610139573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061015d91906107c6565b905090565b5f83116101a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161019b9061084b565b60405180910390fd5b827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016101fe9190610799565b602060405180830381865afa158015610219573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061023d91906107c6565b101561027e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610275906108d9565b60405180910390fd5b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016102d89190610799565b602060405180830381865afa1580156102f3573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061031791906107c6565b90505f612710600a8661032a9190610924565b6103349190610992565b90507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33876040518363ffffffff1660e01b81526004016103919291906109c2565b6020604051808303815f875af11580156103ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103d19190610a1e565b503373ffffffffffffffffffffffffffffffffffffffff1663ee8725587f0000000000000000000000000000000000000000000000000000000000000000878488886040518663ffffffff1660e01b8152600401610433959493929190610aa3565b5f604051808303815f87803b15801561044a575f5ffd5b505af115801561045c573d5f5f3e3d5ffd5b50505050808261046c9190610aef565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016104c59190610799565b602060405180830381865afa1580156104e0573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061050491906107c6565b1015610545576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161053c90610b92565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff167f31aaad38f00845a242d16ae90d7bd72fc68f0e22581470f9dc0de241210c2886868360405161058d929190610bb0565b60405180910390a25050505050565b600a81565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f819050919050565b6105d7816105c5565b82525050565b5f6020820190506105f05f8301846105ce565b92915050565b5f5ffd5b5f5ffd5b610607816105c5565b8114610611575f5ffd5b50565b5f81359050610622816105fe565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f84011261064957610648610628565b5b8235905067ffffffffffffffff8111156106665761066561062c565b5b60208301915083600182028301111561068257610681610630565b5b9250929050565b5f5f5f604084860312156106a05761069f6105f6565b5b5f6106ad86828701610614565b935050602084013567ffffffffffffffff8111156106ce576106cd6105fa565b5b6106da86828701610634565b92509250509250925092565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f819050919050565b5f61072861072361071e846106e6565b610705565b6106e6565b9050919050565b5f6107398261070e565b9050919050565b5f61074a8261072f565b9050919050565b61075a81610740565b82525050565b5f6020820190506107735f830184610751565b92915050565b5f610783826106e6565b9050919050565b61079381610779565b82525050565b5f6020820190506107ac5f83018461078a565b92915050565b5f815190506107c0816105fe565b92915050565b5f602082840312156107db576107da6105f6565b5b5f6107e8848285016107b2565b91505092915050565b5f82825260208201905092915050565b7f466c6173684c6f616e50726f76696465723a207a65726f20616d6f756e7400005f82015250565b5f610835601e836107f1565b915061084082610801565b602082019050919050565b5f6020820190508181035f83015261086281610829565b9050919050565b7f466c6173684c6f616e50726f76696465723a20696e73756666696369656e74205f8201527f6c69717569646974790000000000000000000000000000000000000000000000602082015250565b5f6108c36029836107f1565b91506108ce82610869565b604082019050919050565b5f6020820190508181035f8301526108f0816108b7565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61092e826105c5565b9150610939836105c5565b9250828202610947816105c5565b9150828204841483151761095e5761095d6108f7565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f61099c826105c5565b91506109a7836105c5565b9250826109b7576109b6610965565b5b828204905092915050565b5f6040820190506109d55f83018561078a565b6109e260208301846105ce565b9392505050565b5f8115159050919050565b6109fd816109e9565b8114610a07575f5ffd5b50565b5f81519050610a18816109f4565b92915050565b5f60208284031215610a3357610a326105f6565b5b5f610a4084828501610a0a565b91505092915050565b5f82825260208201905092915050565b828183375f83830152505050565b5f601f19601f8301169050919050565b5f610a828385610a49565b9350610a8f838584610a59565b610a9883610a67565b840190509392505050565b5f608082019050610ab65f83018861078a565b610ac360208301876105ce565b610ad060408301866105ce565b8181036060830152610ae3818486610a77565b90509695505050505050565b5f610af9826105c5565b9150610b04836105c5565b9250828201905080821115610b1c57610b1b6108f7565b5b92915050565b7f466c6173684c6f616e50726f76696465723a2072657061796d656e74206661695f8201527f6c65640000000000000000000000000000000000000000000000000000000000602082015250565b5f610b7c6023836107f1565b9150610b8782610b22565b604082019050919050565b5f6020820190508181035f830152610ba981610b70565b9050919050565b5f604082019050610bc35f8301856105ce565b610bd060208301846105ce565b939250505056fea26469706673582212206691e76a4659ab3c827b6e86570c1be41fc2a147f0025be0326de7283c36b97e64736f6c634300081e003360c060405234801561000f575f5ffd5b50604051611bcb380380611bcb833981810160405281019061003191906100fe565b8173ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff16815250508073ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff1681525050505061013c565b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100cd826100a4565b9050919050565b6100dd816100c3565b81146100e7575f5ffd5b50565b5f815190506100f8816100d4565b92915050565b5f5f60408385031215610114576101136100a0565b5b5f610121858286016100ea565b9250506020610132858286016100ea565b9150509250929050565b60805160a0516119e96101e25f395f818161014a015281816102260152818161047001528181610731015281816109f301528181610ac401528181610c5601528181610ef701528181610fd601526110a701525f81816102c601528181610394015281816104ac0152818161052c015281816105b20152818161066f01528181610c9201528181610d1201528181610d9801528181610e55015261108301526119e95ff3fe608060405234801561000f575f5ffd5b506004361061007b575f3560e01c806388a8aec61161005957806388a8aec6146100d3578063ee872558146100ef578063fbfa77cf1461010b578063fc0c546a146101295761007b565b806327a7833f1461007f5780633531bb281461009b57806364dd891a146100b7575b5f5ffd5b6100996004803603810190610094919061112b565b610147565b005b6100b560048036038101906100b09190611189565b6102c4565b005b6100d160048036038101906100cc91906111c7565b61041f565b005b6100ed60048036038101906100e891906111f2565b6107df565b005b610109600480360381019061010491906112a3565b610b64565b005b610113611081565b6040516101209190611382565b60405180910390f35b6101316110a5565b60405161013e91906113bb565b60405180910390f35b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016101a191906113e3565b602060405180830381865afa1580156101bc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101e09190611410565b90505f8111610224576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161021b90611495565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b815260040161027f9291906114c2565b6020604051808303815f875af115801561029b573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102bf919061151e565b505050565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610352576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161034990611593565b60405180910390fd5b60015f9054906101000a900460ff16158061036c57505f81145b61041b576064600254101561041b5760025f81548092919061038d906115de565b91905055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b81526004016103ed929190611625565b5f604051808303815f87803b158015610404575f5ffd5b505af1158015610416573d5f5f3e3d5ffd5b505050505b5050565b60015f9054906101000a900460ff161561046e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161046590611696565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663095ea7b37f0000000000000000000000000000000000000000000000000000000000000000836040518363ffffffff1660e01b81526004016104e99291906114c2565b6020604051808303815f875af1158015610505573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610529919061151e565b507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b6b55f25826040518263ffffffff1660e01b815260040161058391906116b4565b5f604051808303815f87803b15801561059a575f5ffd5b505af11580156105ac573d5f5f3e3d5ffd5b505050507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ce7c2ac2306040518263ffffffff1660e01b815260040161060991906113e3565b602060405180830381865afa158015610624573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106489190611410565b5f819055505f6002819055506001805f6101000a81548160ff0219169083151502179055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b81526004016106c8929190611625565b5f604051808303815f87803b1580156106df575f5ffd5b505af11580156106f1573d5f5f3e3d5ffd5b505050505f60015f6101000a81548160ff0219169083151502179055507f45776e8c4137c2d25b59c6bc4e32fd07c3789be92c2623f548bdcc1c513ffad67f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161078891906113e3565b602060405180830381865afa1580156107a3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107c79190611410565b6040516107d491906116b4565b60405180910390a150565b60015f9054906101000a900460ff161561082e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161082590611696565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361089c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161089390611717565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff160361090a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016109019061177f565b60405180910390fd5b8260035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508273ffffffffffffffffffffffffffffffffffffffff16635296a431836040518263ffffffff1660e01b815260040161098391906117d0565b5f604051808303815f87803b15801561099a575f5ffd5b505af11580156109ac573d5f5f3e3d5ffd5b505050505f60035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610a4a91906113e3565b602060405180830381865afa158015610a65573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a899190611410565b90507f45776e8c4137c2d25b59c6bc4e32fd07c3789be92c2623f548bdcc1c513ffad681604051610aba91906116b4565b60405180910390a17f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb83836040518363ffffffff1660e01b8152600401610b1d9291906114c2565b6020604051808303815f875af1158015610b39573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b5d919061151e565b5050505050565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610bf3576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bea9061186c565b60405180910390fd5b60015f9054906101000a900460ff1615610c42576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610c39906118d4565b60405180910390fd5b8284610c4e91906118f2565b6004819055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663095ea7b37f0000000000000000000000000000000000000000000000000000000000000000866040518363ffffffff1660e01b8152600401610ccf9291906114c2565b6020604051808303815f875af1158015610ceb573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0f919061151e565b507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b6b55f25856040518263ffffffff1660e01b8152600401610d6991906116b4565b5f604051808303815f87803b158015610d80575f5ffd5b505af1158015610d92573d5f5f3e3d5ffd5b505050507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663ce7c2ac2306040518263ffffffff1660e01b8152600401610def91906113e3565b602060405180830381865afa158015610e0a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e2e9190611410565b5f819055505f6002819055506001805f6101000a81548160ff0219169083151502179055507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1662f714ce5f54306040518363ffffffff1660e01b8152600401610eae929190611625565b5f604051808303815f87803b158015610ec5575f5ffd5b505af1158015610ed7573d5f5f3e3d5ffd5b505050505f60015f6101000a81548160ff0219169083151502179055505f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610f4e91906113e3565b602060405180830381865afa158015610f69573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f8d9190611410565b9050600454811015610fd4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fcb90611995565b60405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a9059cbb336004546040518363ffffffff1660e01b81526004016110319291906114c2565b6020604051808303815f875af115801561104d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611071919061151e565b505f600481905550505050505050565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6110fa826110d1565b9050919050565b61110a816110f0565b8114611114575f5ffd5b50565b5f8135905061112581611101565b92915050565b5f602082840312156111405761113f6110c9565b5b5f61114d84828501611117565b91505092915050565b5f819050919050565b61116881611156565b8114611172575f5ffd5b50565b5f813590506111838161115f565b92915050565b5f5f6040838503121561119f5761119e6110c9565b5b5f6111ac85828601611117565b92505060206111bd85828601611175565b9150509250929050565b5f602082840312156111dc576111db6110c9565b5b5f6111e984828501611175565b91505092915050565b5f5f5f60608486031215611209576112086110c9565b5b5f61121686828701611117565b935050602061122786828701611175565b925050604061123886828701611117565b9150509250925092565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f84011261126357611262611242565b5b8235905067ffffffffffffffff8111156112805761127f611246565b5b60208301915083600182028301111561129c5761129b61124a565b5b9250929050565b5f5f5f5f5f608086880312156112bc576112bb6110c9565b5b5f6112c988828901611117565b95505060206112da88828901611175565b94505060406112eb88828901611175565b935050606086013567ffffffffffffffff81111561130c5761130b6110cd565b5b6113188882890161124e565b92509250509295509295909350565b5f819050919050565b5f61134a611345611340846110d1565b611327565b6110d1565b9050919050565b5f61135b82611330565b9050919050565b5f61136c82611351565b9050919050565b61137c81611362565b82525050565b5f6020820190506113955f830184611373565b92915050565b5f6113a582611351565b9050919050565b6113b58161139b565b82525050565b5f6020820190506113ce5f8301846113ac565b92915050565b6113dd816110f0565b82525050565b5f6020820190506113f65f8301846113d4565b92915050565b5f8151905061140a8161115f565b92915050565b5f60208284031215611425576114246110c9565b5b5f611432848285016113fc565b91505092915050565b5f82825260208201905092915050565b7f41747461636b65725661756c743a206e6f2070726f66697400000000000000005f82015250565b5f61147f60188361143b565b915061148a8261144b565b602082019050919050565b5f6020820190508181035f8301526114ac81611473565b9050919050565b6114bc81611156565b82525050565b5f6040820190506114d55f8301856113d4565b6114e260208301846114b3565b9392505050565b5f8115159050919050565b6114fd816114e9565b8114611507575f5ffd5b50565b5f81519050611518816114f4565b92915050565b5f60208284031215611533576115326110c9565b5b5f6115408482850161150a565b91505092915050565b7f41747461636b65725661756c743a20756e747275737465642063616c6c6572005f82015250565b5f61157d601f8361143b565b915061158882611549565b602082019050919050565b5f6020820190508181035f8301526115aa81611571565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f6115e882611156565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361161a576116196115b1565b5b600182019050919050565b5f6040820190506116385f8301856114b3565b61164560208301846113d4565b9392505050565b7f616c72656164792061747461636b696e670000000000000000000000000000005f82015250565b5f61168060118361143b565b915061168b8261164c565b602082019050919050565b5f6020820190508181035f8301526116ad81611674565b9050919050565b5f6020820190506116c75f8301846114b3565b92915050565b7f41747461636b65725661756c743a207a65726f2070726f7669646572000000005f82015250565b5f611701601c8361143b565b915061170c826116cd565b602082019050919050565b5f6020820190508181035f83015261172e816116f5565b9050919050565b7f41747461636b65725661756c743a207a65726f207265636569766572000000005f82015250565b5f611769601c8361143b565b915061177482611735565b602082019050919050565b5f6020820190508181035f8301526117968161175d565b9050919050565b5f82825260208201905092915050565b50565b5f6117bb5f8361179d565b91506117c6826117ad565b5f82019050919050565b5f6040820190506117e35f8301846114b3565b81810360208301526117f4816117b0565b905092915050565b7f41747461636b65725661756c743a20756e7472757374656420666c617368206c5f8201527f6f616e2063616c6c657200000000000000000000000000000000000000000000602082015250565b5f611856602a8361143b565b9150611861826117fc565b604082019050919050565b5f6020820190508181035f8301526118838161184a565b9050919050565b7f41747461636b65725661756c743a20616c72656164792061747461636b696e675f82015250565b5f6118be60208361143b565b91506118c98261188a565b602082019050919050565b5f6020820190508181035f8301526118eb816118b2565b9050919050565b5f6118fc82611156565b915061190783611156565b925082820190508082111561191f5761191e6115b1565b5b92915050565b7f41747461636b65725661756c743a20696e73756666696369656e742070726f665f8201527f697420746f20726570617920666c617368206c6f616e00000000000000000000602082015250565b5f61197f60368361143b565b915061198a82611925565b604082019050919050565b5f6020820190508181035f8301526119ac81611973565b905091905056fea2646970667358221220fc1f514f8b97ef8f8315bfe00f89ae09b20c0d1dcb5cae7ddb997ba15b28585364736f6c634300081e0033000000000000000000000000578d8871249a0b9956542a60024a30306f74785200000000000000000000000000000000000000000000152d02c7e14af6800000000000000000000000000000b376fb62b70b26530ec271aadd6fcd046c5ee680000000000000000000000000fb0de6ab3cd3aeee1b3abeb51ee3b98d576e929bffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000001c0fd5bab052786547f33569ce66da6a5c5d53de3e080540a8296c7d2cc49f082c37cbe2d20bc2dcddec5b2794549c4e322f95cd25a30af781c226530b68d2e55d" - }, - "prestate": { - "0x0000000000000000000000000000000000000001": { - "balance": "0xd8750d6ceef" - }, - "0x1c6100bfa8e67837ba9d13a7447c853e32728204": { - "balance": "0x0" - }, - "0x355ac514807d5118ec8160e7b4bb2a108f7d74da": { - "balance": "0x0", - "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000002": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000003": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000004": "0x0000000000000000000000000000000000000000000000000000000000000000" - } - }, - "0x4200000000000000000000000000000000000011": { - "balance": "0x161526c2a4454d7a", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a" - }, - "0x4200000000000000000000000000000000000019": { - "balance": "0x24786b4c6222b4540", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a" - }, - "0x420000000000000000000000000000000000001a": { - "balance": "0x2da889885f77cbf", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a" - }, - "0x420000000000000000000000000000000000001b": { - "balance": "0x0", - "code": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100be5780638f283970146100f8578063f851a440146101185761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61012d565b005b61006b61012d565b34801561008157600080fd5b5061006b6100903660046106dd565b610224565b6100a86100a33660046106f8565b610296565b6040516100b5919061077b565b60405180910390f35b3480156100ca57600080fd5b506100d3610419565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016100b5565b34801561010457600080fd5b5061006b6101133660046106dd565b6104b0565b34801561012457600080fd5b506100d3610517565b60006101577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905073ffffffffffffffffffffffffffffffffffffffff8116610201576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f50726f78793a20696d706c656d656e746174696f6e206e6f7420696e6974696160448201527f6c697a656400000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b3660008037600080366000845af43d6000803e8061021e573d6000fd5b503d6000f35b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061027d575033155b1561028e5761028b816105a3565b50565b61028b61012d565b60606102c07fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614806102f7575033155b1561040a57610305846105a3565b6000808573ffffffffffffffffffffffffffffffffffffffff16858560405161032f9291906107ee565b600060405180830381855af49150503d806000811461036a576040519150601f19603f3d011682016040523d82523d6000602084013e61036f565b606091505b509150915081610401576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603960248201527f50726f78793a2064656c656761746563616c6c20746f206e657720696d706c6560448201527f6d656e746174696f6e20636f6e7472616374206661696c65640000000000000060648201526084016101f8565b91506104129050565b61041261012d565b9392505050565b60006104437fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16148061047a575033155b156104a557507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6104ad61012d565b90565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610509575033155b1561028e5761028b8161060c565b60006105417fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480610578575033155b156104a557507fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc81815560405173ffffffffffffffffffffffffffffffffffffffff8316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a25050565b60006106367fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035490565b7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61038381556040805173ffffffffffffffffffffffffffffffffffffffff80851682528616602082015292935090917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f910160405180910390a1505050565b803573ffffffffffffffffffffffffffffffffffffffff811681146106d857600080fd5b919050565b6000602082840312156106ef57600080fd5b610412826106b4565b60008060006040848603121561070d57600080fd5b610716846106b4565b9250602084013567ffffffffffffffff8082111561073357600080fd5b818601915086601f83011261074757600080fd5b81358181111561075657600080fd5b87602082850101111561076857600080fd5b6020830194508093505050509250925092565b600060208083528351808285015260005b818110156107a85785810183015185820160400152820161078c565b818111156107ba576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b818382376000910190815291905056fea164736f6c634300080f000a" - }, - "0x578d8871249a0b9956542a60024a30306f747852": { - "balance": "0x0", - "code": "0x608060405234801561000f575f80fd5b50600436106100cb575f3560e01c806370a082311161008857806395d89b411161006357806395d89b41146101a2578063a9059cbb146101aa578063d505accf146101bd578063dd62ed3e146101d2575f80fd5b806370a082311461014c5780637ecebe001461017457806384b0196e14610187575f80fd5b806306fdde03146100cf578063095ea7b3146100ed57806318160ddd1461011057806323b872dd14610122578063313ce567146101355780633644e51514610144575b5f80fd5b6100d761020a565b6040516100e49190610c2c565b60405180910390f35b6101006100fb366004610c60565b61029a565b60405190151581526020016100e4565b6002545b6040519081526020016100e4565b610100610130366004610c88565b6102b3565b604051601281526020016100e4565b6101146102d6565b61011461015a366004610cc1565b6001600160a01b03165f9081526020819052604090205490565b610114610182366004610cc1565b6102e4565b61018f610301565b6040516100e49796959493929190610cda565b6100d7610343565b6101006101b8366004610c60565b610352565b6101d06101cb366004610d71565b61035f565b005b6101146101e0366004610dde565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b60606003805461021990610e0f565b80601f016020809104026020016040519081016040528092919081815260200182805461024590610e0f565b80156102905780601f1061026757610100808354040283529160200191610290565b820191905f5260205f20905b81548152906001019060200180831161027357829003601f168201915b5050505050905090565b5f336102a781858561049a565b60019150505b92915050565b5f336102c08582856104ac565b6102cb858585610528565b506001949350505050565b5f6102df610585565b905090565b6001600160a01b0381165f908152600760205260408120546102ad565b5f6060805f805f60606103126106ae565b61031a6106db565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b60606004805461021990610e0f565b5f336102a7818585610528565b834211156103885760405163313c898160e11b8152600481018590526024015b60405180910390fd5b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886103d38c6001600160a01b03165f90815260076020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f61042d82610708565b90505f61043c82878787610734565b9050896001600160a01b0316816001600160a01b031614610483576040516325c0072360e11b81526001600160a01b0380831660048301528b16602482015260440161037f565b61048e8a8a8a61049a565b50505050505050505050565b6104a78383836001610760565b505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f19811015610522578181101561051457604051637dc7a0d960e11b81526001600160a01b0384166004820152602481018290526044810183905260640161037f565b61052284848484035f610760565b50505050565b6001600160a01b03831661055157604051634b637e8f60e11b81525f600482015260240161037f565b6001600160a01b03821661057a5760405163ec442f0560e01b81525f600482015260240161037f565b6104a7838383610832565b5f306001600160a01b037f000000000000000000000000578d8871249a0b9956542a60024a30306f747852161480156105dd57507f00000000000000000000000000000000000000000000000000000000000010e646145b1561060757507fd1bf0a1ec1283fc6b7484c5b5a5aea13b60c5ddd2dc50014ed7e19f01601d37590565b6102df604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f637597a3c1426ec850b48a1ea08e2596b554a91e4fa8e14e3d777635b0ad0c2a918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60606102df7f546573745365635553440000000000000000000000000000000000000000000a6005610958565b60606102df7f31000000000000000000000000000000000000000000000000000000000000016006610958565b5f6102ad610714610585565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f8061074488888888610a01565b9250925092506107548282610ac9565b50909695505050505050565b6001600160a01b0384166107895760405163e602df0560e01b81525f600482015260240161037f565b6001600160a01b0383166107b257604051634a1406b160e11b81525f600482015260240161037f565b6001600160a01b038085165f908152600160209081526040808320938716835292905220829055801561052257826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161082491815260200190565b60405180910390a350505050565b6001600160a01b03831661085c578060025f8282546108519190610e47565b909155506108cc9050565b6001600160a01b0383165f90815260208190526040902054818110156108ae5760405163391434e360e21b81526001600160a01b0385166004820152602481018290526044810183905260640161037f565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b0382166108e857600280548290039055610906565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161094b91815260200190565b60405180910390a3505050565b606060ff83146109725761096b83610b85565b90506102ad565b81805461097e90610e0f565b80601f01602080910402602001604051908101604052809291908181526020018280546109aa90610e0f565b80156109f55780601f106109cc576101008083540402835291602001916109f5565b820191905f5260205f20905b8154815290600101906020018083116109d857829003601f168201915b505050505090506102ad565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610a3a57505f91506003905082610abf565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610a8b573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116610ab657505f925060019150829050610abf565b92505f91508190505b9450945094915050565b5f826003811115610adc57610adc610e66565b03610ae5575050565b6001826003811115610af957610af9610e66565b03610b175760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610b2b57610b2b610e66565b03610b4c5760405163fce698f760e01b81526004810182905260240161037f565b6003826003811115610b6057610b60610e66565b03610b81576040516335e2f38360e21b81526004810182905260240161037f565b5050565b60605f610b9183610bc2565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f60ff8216601f8111156102ad57604051632cd44ac360e21b815260040160405180910390fd5b5f81518084525f5b81811015610c0d57602081850181015186830182015201610bf1565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f610c3e6020830184610be9565b9392505050565b80356001600160a01b0381168114610c5b575f80fd5b919050565b5f8060408385031215610c71575f80fd5b610c7a83610c45565b946020939093013593505050565b5f805f60608486031215610c9a575f80fd5b610ca384610c45565b9250610cb160208501610c45565b9150604084013590509250925092565b5f60208284031215610cd1575f80fd5b610c3e82610c45565b60ff60f81b881681525f602060e06020840152610cfa60e084018a610be9565b8381036040850152610d0c818a610be9565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825260208088019350909101905f5b81811015610d5f57835183529284019291840191600101610d43565b50909c9b505050505050505050505050565b5f805f805f805f60e0888a031215610d87575f80fd5b610d9088610c45565b9650610d9e60208901610c45565b95506040880135945060608801359350608088013560ff81168114610dc1575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215610def575f80fd5b610df883610c45565b9150610e0660208401610c45565b90509250929050565b600181811c90821680610e2357607f821691505b602082108103610e4157634e487b7160e01b5f52602260045260245ffd5b50919050565b808201808211156102ad57634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f52602160045260245ffdfea26469706673582212200fa3d3d17ba488a0031995f9da2c1e6aec1eecd579a8e846babe56aa7286101564736f6c63430008180033", - "nonce": 1, - "storage": { - "0x213b9ef722885121b6bf233baaf1feb2baa4e1c38e5a6bb52c2caba2878310d0": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x412b2a79ba55ab55c0b244056436f982b53c897ea723181bcc9526d610d16fec": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x5de41bfeea9b974a4c1153f1bbe02a33fd5b35f2f7fa3395a32f9b8d51611a25": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x5fca353663f6f9935bf2a9a8fe1d01e70ed429ffb39a1e8e2a5e8c9bee308eb5": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x9c9b00837f0d78bb3c52145f309fe3a14fa68532cb2c348fca275ba98bf24f12": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0xafd34d6b52de283969cab1deb3a652d8c16a9f10b3260769521e40fbc87cffe2": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0xc66533f103d34d4c87a84143199cf05b541308f878c7ee0224a302a19961e71c": "0x0000000000000000000000000000000000000000033b2e3c9fd0803ce8000000", - "0xc6c74f62bfa1cb8d48cede291887c0d1cb390939ec5512846ef312ac741eae2a": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0xc80bbbf4eec8fdcb43a21dd2f2ba3ec0060e478e7e2466e4698ba3dd301ee16c": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0xdbc7913112c06ca7601ac55969b95e2c3ace896ce372ddfb11236d7973e35b00": "0x0000000000000000000000000000000000000000000000000000000000000000" - } - }, - "0x632b7da5ea5912330ed23af39d09e457294168ee": { - "balance": "0x0", - "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000000000000000000000000000000000000000000002": "0x0000000000000000000000000000000000000000000000000000000000000000" - } - }, - "0xd4c1ecfc39ad51ab8ecdd0240a27dadd363b4739": { - "balance": "0x0", - "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x5de41bfeea9b974a4c1153f1bbe02a33fd5b35f2f7fa3395a32f9b8d51611a25": "0x0000000000000000000000000000000000000000000000000000000000000000", - "0xc80bbbf4eec8fdcb43a21dd2f2ba3ec0060e478e7e2466e4698ba3dd301ee16c": "0x0000000000000000000000000000000000000000000000000000000000000000" - } - }, - "0xfb0de6ab3cd3aeee1b3abeb51ee3b98d576e929b": { - "balance": "0x89dbbd283b4d9", - "nonce": 5 - } - }, - "block_number": 16623578, - "expected_gas_used": 141927106, - "block": { - "number": 16623578, - "hash": "0x377fa604074addabe0562e15ed17d73526310e56c6d5c4eaea1b2f7a9f040df8", - "timestamp": 1779421101, - "base_fee_per_gas": 1000000, - "gas_limit": 10000000000, - "beneficiary": "0x4200000000000000000000000000000000000011", - "mix_hash": "0x9facac34967efd2bd06396afe5433cc0746ac1893c40f72f472204bbd025fd5a", - "difficulty": 0 - } -} \ No newline at end of file diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index abb22eed3..1acddffa6 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -8,12 +8,48 @@ //! every frame pays the frame lifecycle's lanes and every `SSTORE` and `LOG` its commit wrapper. //! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the //! `SSTORE` wrapper's commit and refund. -//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit. +//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit, and the one +//! `record_history_cost` each log's bytes cost — no allocation, no second pass over the table. +//! - `calldata`: a call carrying 4 KiB of calldata, which is 4 KiB of the transaction body's +//! history, priced once before the first frame runs. //! - `intercepted_calls`: 200 `STATICCALL`s to `MegaAccessControl`'s //! `isVolatileDataAccessDisabled`, which the interceptor answers: the dispatch and the synthetic //! result, 200 times. //! - `system_address_misses`: the same 200 calls with a selector the contract does not intercept, //! so each pays the dispatch's address match and selector peek and then runs the bytecode. +//! - `remaining_compute_gas`: 200 `STATICCALL`s to `MegaLimitControl`'s `remainingComputeGas`, +//! which the interceptor answers from the caller's gas and gas detention's allowance. +//! - `oracle_reads`: a transaction to the Oracle, whose code loads 200 of its slots: each load +//! reads the database through the journal, asks the oracle service, finds nothing and is priced +//! cold, and gas detention marks and commits it. op-revm reads the same 200 slots from the +//! database. +//! - `value_calls`: 200 one-wei `CALL`s to an account with no code, which revm answers without +//! running: each frame start counts its records and its EIP-7708 transfer log before revm moves +//! the value and journals the log, and op-revm journals the same 200 logs. +//! - `storage_reads`: 200 `SLOAD`s of slots nothing volatile holds: the Host's storage load and the +//! read wrapper around `SLOAD`, which finds nothing to settle. +//! - `volatile_reads`: 200 rounds of `TIMESTAMP`, `NUMBER` and a `BALANCE` of the block +//! beneficiary, then a call to the Oracle, whose code loads 200 of its slots. Every one is a read +//! gas detention marks in the Host and commits in the opcode's wrapper; the first caps the frame, +//! and the call starts and resumes under the limit. +//! - `hashes_and_copies`: 200 rounds of a 32-byte `KECCAK256`, `MCOPY`, `CALLDATACOPY` and +//! `CODECOPY`, an empty `RETURNDATACOPY` and an `EXP` of a one-byte exponent: the wrapper each of +//! them runs in, which notes the frame's gas for gas detention when the opcode's charge fails and +//! compares a result when it does not. +//! - `data_size_limit`: 200 fresh slots and 200 two-topic logs in one frame, run under a +//! transaction data-size limit equal to exactly what the transaction keeps, so every record is +//! checked against a limit it is about to reach (`satin`); the same one byte short of it, so the +//! last log crosses and the transaction is stopped (`stopped`); and through op-revm, which has no +//! limit to check (`op_revm`). +//! - `keyless_deploy`: a `keylessDeploy` of the canonical `CREATE2` factory, which Satin runs as a +//! native creation below the call (`satin`), next to op-revm running the same init code as a +//! creation transaction (`op_revm`). The gap is what the keyless path adds to a creation: +//! decoding the signed transaction, recovering its signer — most of it — the rules' reads, the +//! call's upfront charges, and the creation's return into the call and its ABI answer. +//! +//! `oracle_reads` runs once more through `MegaEvm` alone (`/service`), against an oracle service +//! that answers all 200 slots; every slot is loaded all the same, so the two arms differ by the +//! answers alone. //! //! Two more run through `MegaEvm` alone, because they price something op-revm has no equivalent //! of: `salt_storage_writes` and `salt_new_accounts` each draw one EIP-8037 state gas charge per @@ -21,6 +57,13 @@ //! every bucket is minimal, and once (`/crowded`) against a SALT environment holding every bucket //! at eight times the minimum capacity. The gap is what the pricing hook costs on the hot path: //! one environment read per bucket and a cache hit per charge after it. +//! +//! Every workload is run once before it is measured, and the run is held to what it must draw: +//! each pays its body's history, the logging one pays for the bytes its logs append and the +//! calldata one for the bytes it carries, and the data-size one keeps exactly the bytes and +//! records it is sized for, and stops at its last log one byte short of them. A workload that +//! stopped drawing what it is here to measure would otherwise still benchmark, and measure the +//! wrong thing. #![allow(missing_docs)] use alloy_op_evm::OpTx; @@ -28,15 +71,29 @@ use alloy_primitives::{address, Address, Bytes, TxKind, U160, U256}; use alloy_sol_types::SolCall; use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use mega_evm::{ - system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, MIN_BUCKET_SIZE, + constants::COST_PER_HISTORY_BYTE, + system::{ + keyless::{ + decode_keyless_tx, + tests::{CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_TX}, + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, + }, + IMegaAccessControl, IMegaLimitControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{ + is_transfer_log, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, + MegaSpecId, TestExternalEnvs, VolatileDataAccess, LOG_BASE_SIZE, LOG_TOPIC_SIZE, + MIN_BUCKET_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATALOAD, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, LOG2, MSTORE, POP, - PUSH0, PUSH1, SSTORE, STATICCALL, STOP, SUB, SWAP1, + ADD, ADDRESS, BALANCE, CALL, CALLDATACOPY, CALLDATALOAD, CODECOPY, DUP1, EXP, GAS, ISZERO, + JUMPDEST, JUMPI, KECCAK256, LOG0, LOG2, MCOPY, MSTORE, NUMBER, POP, PUSH0, PUSH1, + RETURNDATACOPY, SLOAD, SSTORE, STATICCALL, STOP, SUB, SWAP1, TIMESTAMP, }, context::{BlockEnv, CfgEnv, Context, ContextTr, TxEnv}, inspector::NoOpInspector, @@ -52,16 +109,35 @@ const SALT_WRITER: Address = address!("0x000000000000000000000000000000000010000 const SALT_CALLER: Address = address!("0x0000000000000000000000000000000000100006"); const INTERCEPTED: Address = address!("0x0000000000000000000000000000000000100007"); const MISSING: Address = address!("0x0000000000000000000000000000000000100008"); +const LIMITED: Address = address!("0x0000000000000000000000000000000000100009"); +const READER: Address = address!("0x000000000000000000000000000000000010000a"); +const VOLATILE: Address = address!("0x000000000000000000000000000000000010000b"); +const HASHER: Address = address!("0x000000000000000000000000000000000010000c"); +const VALUE_CALLER: Address = address!("0x000000000000000000000000000000000010000d"); +const QUERIER: Address = address!("0x000000000000000000000000000000000010000e"); +/// The callers of the three system-call workloads again, summing the success bits of their calls +/// where the measured ones discard them. Run once by the checks, never measured. +const INTERCEPTED_COUNT: Address = address!("0x0000000000000000000000000000000000100010"); +const MISSING_COUNT: Address = address!("0x0000000000000000000000000000000000100011"); +const QUERIER_COUNT: Address = address!("0x0000000000000000000000000000000000100012"); + +/// The block beneficiary of the benchmark's block, `BlockEnv`'s default. +const BENEFICIARY: Address = Address::ZERO; /// A selector `MegaAccessControl` intercepts, and one it does not. const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; const UNKNOWN_SELECTOR: [u8; 4] = [0xde, 0xad, 0xbe, 0xef]; +/// The selector `MegaLimitControl` intercepts. +const REMAINING_COMPUTE_GAS: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; /// Depth the recursive contract reaches. const DEPTH: u8 = 64; /// Slots written, then written back, by the storage workload; logs emitted by the log workload. const REPEAT: u64 = 200; +/// Calldata bytes the `calldata` workload carries, which is what its body's history prices. +const CALLDATA_LEN: usize = 4 * 1024; + /// Offset of the `JUMPDEST` the recursion ends at. const DONE: u8 = 0x1f; @@ -118,6 +194,81 @@ fn logger_code() -> Bytes { code.stop().build() } +/// Loads `REPEAT` slots of its own storage. +fn reader_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 0..REPEAT { + code = code.push_number(slot).append(SLOAD).append(POP); + } + code.stop().build() +} + +/// Hashes a word, copies a word within memory, from calldata and from code, and copies no return +/// data, `REPEAT` times. +fn hasher_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..REPEAT { + code = code + .push_number(32_u8) + .append_many([PUSH0, KECCAK256, POP]) + .push_number(32_u8) + .append_many([PUSH0, PUSH0, MCOPY]) + .push_number(32_u8) + .append_many([PUSH0, PUSH0, CALLDATACOPY]) + .push_number(32_u8) + .append_many([PUSH0, PUSH0, CODECOPY]) + .append_many([PUSH0, PUSH0, PUSH0, RETURNDATACOPY]) + .push_number(0xff_u8) + .push_number(3_u8) + .append_many([EXP, POP]); + } + code.stop().build() +} + +/// Reads the block's timestamp and number and the beneficiary's balance `REPEAT` times, then calls +/// the Oracle, whose code is [`reader_code`]. +fn volatile_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..REPEAT { + code = code + .append_many([TIMESTAMP, POP, NUMBER, POP]) + .push_address(BENEFICIARY) + .append(BALANCE) + .append(POP); + } + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build() +} + +/// Writes `REPEAT` fresh slots, then emits `REPEAT` two-topic logs of 32 bytes: both kinds of +/// bytes the data-size limit counts, each checked against the limit as it is kept. +fn limited_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 0..REPEAT { + code = code.sstore(U256::from(slot), U256::from(1)); + } + for topic in 0..REPEAT { + code = code + .push_number(topic) + .push_number(topic) + .push_number(32_u8) + .append(PUSH0) + .append(LOG2); + } + code.stop().build() +} + +/// What [`limited_code`] keeps: its body, one write record per slot, and each log's bytes. +const LIMITED_KEPT: u64 = + TX_BODY_SIZE + REPEAT * WRITE_RECORD_SIZE + REPEAT * (LOG_BASE_SIZE + 2 * LOG_TOPIC_SIZE + 32); +/// Room for `REPEAT` fresh slots and `REPEAT` logs, far below the execution cap. +const LIMITED_GAS_LIMIT: u64 = 60_000_000; + /// Writes `SALT_REPEAT` fresh slots, each drawing one state gas charge the pricing hook prices. fn salt_writer_code() -> Bytes { let mut code = BytecodeBuilder::default(); @@ -146,6 +297,15 @@ fn salt_caller_code() -> Bytes { code.stop().build() } +/// Sends one wei to [`CALLEE`], an account with no code, `REPEAT` times. +fn value_caller_code() -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..REPEAT { + code = code.call(CALLEE, U256::from(1)).append(POP); + } + code.stop().build() +} + /// A SALT environment holding every bucket at `m` times the minimum capacity. fn salt_envs(m: u64) -> TestExternalEnvs { TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * m) @@ -160,21 +320,38 @@ fn salt_context( .with_chain(zero_fee_l1_block_info()) } -/// `STATICCALL`s `MegaAccessControl` with `selector` `REPEAT` times, discarding the answers. -fn system_caller_code(selector: [u8; 4]) -> Bytes { +/// `STATICCALL`s the system contract at `target` with `selector` `REPEAT` times, discarding the +/// answers. +fn system_caller_code(target: Address, selector: [u8; 4]) -> Bytes { + system_calls(target, selector, false) +} + +/// The same calls, returning how many of them succeeded. +fn system_caller_count_code(target: Address, selector: [u8; 4]) -> Bytes { + system_calls(target, selector, true) +} + +fn system_calls(target: Address, selector: [u8; 4], count: bool) -> Bytes { let mut code = BytecodeBuilder::default().mstore(0x0, selector); + if count { + code = code.push_number(0_u64); + } for _ in 0..REPEAT { code = code .push_number(0_u64) // retSize .push_number(0_u64) // retOffset .push_number(4_u64) // argsSize .push_number(0_u64) // argsOffset - .push_address(ACCESS_CONTROL_ADDRESS) + .push_address(target) .push_number(100_000_u64) .append(STATICCALL) - .append(POP); + .append(if count { ADD } else { POP }); + } + if count { + code.return_top().build() + } else { + code.stop().build() } - code.stop().build() } fn call_tx(to: Address, data: Bytes, gas_limit: u64) -> OpTransaction { @@ -220,9 +397,31 @@ fn bench_transact(c: &mut Criterion) { .account_code(SALT_WRITER, salt_writer_code()) .account_balance(SALT_CALLER, U256::from(10u64.pow(9))) .account_code(SALT_CALLER, salt_caller_code()) - .account_code(INTERCEPTED, system_caller_code(IS_DISABLED)) - .account_code(MISSING, system_caller_code(UNKNOWN_SELECTOR)) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE); + .account_code(INTERCEPTED, system_caller_code(ACCESS_CONTROL_ADDRESS, IS_DISABLED)) + .account_code(MISSING, system_caller_code(ACCESS_CONTROL_ADDRESS, UNKNOWN_SELECTOR)) + .account_code(QUERIER, system_caller_code(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS)) + .account_code( + INTERCEPTED_COUNT, + system_caller_count_code(ACCESS_CONTROL_ADDRESS, IS_DISABLED), + ) + .account_code( + MISSING_COUNT, + system_caller_count_code(ACCESS_CONTROL_ADDRESS, UNKNOWN_SELECTOR), + ) + .account_code( + QUERIER_COUNT, + system_caller_count_code(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS), + ) + .account_code(LIMITED, limited_code()) + .account_balance(VALUE_CALLER, U256::from(REPEAT)) + .account_code(VALUE_CALLER, value_caller_code()) + .account_code(READER, reader_code()) + .account_code(VOLATILE, volatile_code()) + .account_code(HASHER, hasher_code()) + .account_code(ORACLE_CONTRACT_ADDRESS, reader_code()) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); let cfg = mega_context(db.clone()).cfg().clone(); let mut depth = [0u8; 32]; @@ -233,18 +432,94 @@ fn bench_transact(c: &mut Criterion) { ("deep_calls", call_tx(RECURSIVE, Bytes::from(depth.to_vec()), 30_000_000)), ("storage_writes", call_tx(WRITER, Bytes::new(), 30_000_000)), ("logs", call_tx(LOGGER, Bytes::new(), 30_000_000)), + ("calldata", call_tx(CALLEE, Bytes::from(vec![0xab_u8; CALLDATA_LEN]), 30_000_000)), ("intercepted_calls", call_tx(INTERCEPTED, Bytes::new(), 30_000_000)), ("system_address_misses", call_tx(MISSING, Bytes::new(), 30_000_000)), + ("remaining_compute_gas", call_tx(QUERIER, Bytes::new(), 30_000_000)), + ("value_calls", call_tx(VALUE_CALLER, Bytes::new(), 30_000_000)), + ("storage_reads", call_tx(READER, Bytes::new(), 30_000_000)), + ("volatile_reads", call_tx(VOLATILE, Bytes::new(), 30_000_000)), + ("hashes_and_copies", call_tx(HASHER, Bytes::from(vec![0xab_u8; 32]), 30_000_000)), + ("oracle_reads", call_tx(ORACLE_CONTRACT_ADDRESS, Bytes::new(), 30_000_000)), ]; let mut group = c.benchmark_group("transact"); for (workload, tx) in workloads { - let satin = MegaEvm::new(mega_context(db.clone())).transact(OpTx(tx.clone())).unwrap(); + let mut evm = MegaEvm::new(mega_context(db.clone())); + let satin = evm.execute_transaction(OpTx(tx.clone())).unwrap(); assert!(satin.result.is_success(), "{workload}: {:?}", satin.result); - if workload == "deep_calls" { - let written = - satin.state[&RECURSIVE].storage.values().filter(|s| s.is_changed()).count(); - assert_eq!(written, DEPTH as usize, "every frame of the recursion ran"); + // Only the two volatile workloads read what detention caps, and each must read every kind + // it is here to measure. + let detention = evm.ctx().detention(); + if workload == "oracle_reads" { + assert_eq!(detention.accessed(), VolatileDataAccess::ORACLE, "oracle_reads: marked"); + assert!(detention.compute_limit().is_some(), "oracle_reads: the reads must detain"); + } else if workload == "volatile_reads" { + assert_eq!( + detention.accessed(), + VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::BLOCK_NUMBER | + VolatileDataAccess::BENEFICIARY_BALANCE | + VolatileDataAccess::ORACLE, + "volatile_reads: every read must be marked", + ); + assert!(detention.compute_limit().is_some(), "volatile_reads: the reads must detain"); + } else { + assert_eq!(detention.compute_limit(), None, "{workload}: nothing here is volatile"); + } + // Every transaction pays its body's history; the two workloads that are here to measure a + // history charge pay what that charge is worth. + let body = TX_BODY_SIZE + tx.base.data.len() as u64; + assert!( + satin.gas.history >= body * COST_PER_HISTORY_BYTE, + "{workload}: every transaction pays for its body", + ); + match workload { + "deep_calls" => { + let written = + satin.state[&RECURSIVE].storage.values().filter(|s| s.is_changed()).count(); + assert_eq!(written, DEPTH as usize, "every frame of the recursion ran"); + } + "logs" => assert_eq!( + satin.gas.history, + (TX_BODY_SIZE + REPEAT * (LOG_BASE_SIZE + 2 * LOG_TOPIC_SIZE + 32)) * + COST_PER_HISTORY_BYTE, + "the logs must draw history gas, which is what this arm measures", + ), + "calldata" => assert_eq!( + satin.gas.history, + body * COST_PER_HISTORY_BYTE, + "the calldata must draw history gas, which is what this arm measures", + ), + "value_calls" => { + let logs = satin.result.logs().iter().filter(|log| is_transfer_log(log)).count(); + assert_eq!(logs, REPEAT as usize, "every call moved its wei and logged it"); + assert_eq!( + satin.usage.data_size - satin.usage.write_records * WRITE_RECORD_SIZE, + body + REPEAT * TRANSFER_LOG_SIZE, + "every transfer log was counted, which is what this arm measures", + ); + } + "intercepted_calls" | "system_address_misses" | "remaining_compute_gas" => { + // The measured callers discard the answers; the same calls, summed, show what + // they answered: every interceptor's answer succeeds, and every call that falls + // through to the contract's own code reverts. + let counter = match workload { + "intercepted_calls" => INTERCEPTED_COUNT, + "system_address_misses" => MISSING_COUNT, + _ => QUERIER_COUNT, + }; + let succeeded = if workload == "system_address_misses" { 0 } else { REPEAT }; + let counted = MegaEvm::new(mega_context(db.clone())) + .execute_transaction(OpTx(call_tx(counter, Bytes::new(), 30_000_000))) + .unwrap(); + assert_eq!( + counted.result.output().cloned().unwrap_or_default(), + Bytes::copy_from_slice(&U256::from(succeeded).to_be_bytes::<32>()), + "{workload}: {succeeded} of the {REPEAT} calls succeed", + ); + } + _ => {} } group.bench_function(format!("{workload}/satin"), |b| { b.iter_batched( @@ -267,6 +542,134 @@ fn bench_transact(c: &mut Criterion) { }); } + // The data-size arms: one transaction under a limit it exactly reaches and under one a byte + // short of it, next to op-revm running it with no limit at all. + let limited_tx = call_tx(LIMITED, Bytes::new(), LIMITED_GAS_LIMIT); + let limited = |limit| { + mega_context(db.clone()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit)) + }; + let at_limit = + MegaEvm::new(limited(LIMITED_KEPT)).execute_transaction(OpTx(limited_tx.clone())).unwrap(); + assert!(at_limit.result.is_success(), "data_size_limit: {:?}", at_limit.result); + assert_eq!( + at_limit.usage, + LimitUsage { data_size: LIMITED_KEPT, write_records: REPEAT }, + "data_size_limit: the arm must keep every byte and record it is sized for", + ); + let stopped = MegaEvm::new(limited(LIMITED_KEPT - 1)) + .execute_transaction(OpTx(limited_tx.clone())) + .unwrap(); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: LIMITED_KEPT - 1, + used: LIMITED_KEPT, + frame_local: false, + }), + "data_size_limit/stopped: the last log must be the byte that crosses", + ); + for (arm, limit) in [("satin", LIMITED_KEPT), ("stopped", LIMITED_KEPT - 1)] { + group.bench_function(format!("data_size_limit/{arm}"), |b| { + b.iter_batched( + || MegaEvm::new(limited(limit)), + |mut evm| evm.transact(OpTx(limited_tx.clone())).unwrap(), + BatchSize::SmallInput, + ); + }); + } + group.bench_function("data_size_limit/op_revm", |b| { + b.iter_batched( + || { + let ctx = OpContext::new(db.clone(), OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_chain(zero_fee_l1_block_info()); + OpEvm::new(ctx, NoOpInspector) + }, + |mut evm| evm.transact(limited_tx.clone()).unwrap(), + BatchSize::SmallInput, + ); + }); + + // The Oracle's storage answered by the oracle service, every slot of it: each slot is loaded + // all the same, and each read is priced as the database's is. + let service = (0..REPEAT).fold(TestExternalEnvs::new(), |envs, slot| { + envs.with_oracle_storage(U256::from(slot), U256::ONE) + }); + let oracle_tx = call_tx(ORACLE_CONTRACT_ADDRESS, Bytes::new(), 30_000_000); + let from_service = MegaEvm::new(salt_context(db.clone(), service.clone())) + .execute_transaction(OpTx(oracle_tx.clone())) + .unwrap(); + let from_state = MegaEvm::new(mega_context(db.clone())) + .execute_transaction(OpTx(oracle_tx.clone())) + .unwrap(); + assert!(from_service.result.is_success(), "oracle_reads/service: {:?}", from_service.result); + assert_eq!( + from_service.gas, from_state.gas, + "oracle_reads/service: a read the service answers costs what the database's does", + ); + group.bench_function("oracle_reads/service", |b| { + b.iter_batched( + || MegaEvm::new(salt_context(db.clone(), service.clone())), + |mut evm| evm.transact(OpTx(oracle_tx.clone())).unwrap(), + BatchSize::SmallInput, + ); + }); + + // The keyless arms: the canonical `CREATE2` factory through `keylessDeploy`, next to op-revm + // running its init code as a creation transaction. Both must deploy it. + let keyless_tx = call_tx( + KEYLESS_DEPLOY_ADDRESS, + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), + gasLimitOverride: U256::from(10_000_000), + } + .abi_encode() + .into(), + 30_000_000, + ); + let deployed = MegaEvm::new(mega_context(db.clone())) + .execute_transaction(OpTx(keyless_tx.clone())) + .unwrap(); + let output = deployed.result.output().cloned().unwrap_or_default(); + let answer = IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output) + .expect("keyless_deploy: the call answers in the keylessDeploy ABI"); + assert_eq!(answer.deployedAddress, CREATE2_FACTORY_CONTRACT, "keyless_deploy: it deployed"); + assert_eq!( + deployed.state[&CREATE2_FACTORY_CONTRACT].info.code_hash, CREATE2_FACTORY_CODE_HASH, + "keyless_deploy: the factory's code is what it deployed", + ); + let init_code = decode_keyless_tx(CREATE2_FACTORY_TX).unwrap().tx().input.clone(); + let creation_tx = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: init_code, + gas_limit: 30_000_000, + ..Default::default() + }); + let op_ctx = || { + OpContext::new(db.clone(), OpSpecId::KARST) + .with_cfg(cfg.clone()) + .with_chain(zero_fee_l1_block_info()) + }; + let created = OpEvm::new(op_ctx(), NoOpInspector).transact(creation_tx.clone()).unwrap(); + assert!(created.result.is_success(), "keyless_deploy/op_revm: {:?}", created.result); + group.bench_function("keyless_deploy/satin", |b| { + b.iter_batched( + || MegaEvm::new(mega_context(db.clone())), + |mut evm| evm.transact(OpTx(keyless_tx.clone())).unwrap(), + BatchSize::SmallInput, + ); + }); + group.bench_function("keyless_deploy/op_revm", |b| { + b.iter_batched( + || OpEvm::new(op_ctx(), NoOpInspector), + |mut evm| evm.transact(creation_tx.clone()).unwrap(), + BatchSize::SmallInput, + ); + }); + // The SALT arms: the same transaction against a minimal environment and against one where // every bucket is crowded, both through `MegaEvm` — op-revm has nothing to compare to. let salt_workloads = [ diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs new file mode 100644 index 000000000..c013d8c30 --- /dev/null +++ b/crates/mega-evm/src/access/detention.rs @@ -0,0 +1,1515 @@ +//! The state of gas detention for the running transaction. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{cell::Cell, num::NonZeroU64}; +use std::vec::Vec; + +use alloy_primitives::{Bytes, U256}; +use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult}; + +use super::VolatileDataAccess; +use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; + +/// A crossing gas detention stops a frame for: the compute limit the transaction crossed, and its +/// compute at the crossing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ComputeStop { + /// The most compute the transaction may reach. + pub(crate) limit: u64, + /// The transaction's compute before the charge that would have crossed the limit: what its + /// regular ledger bills once the stopped frame's gas is put back. + pub(crate) used: u64, +} + +/// What detention keeps of one frame that runs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct DetainedFrame { + /// The frame's regular gas spent when it suspended on a child ([`regular_spent`]). + at_suspension: u64, + /// While a child of the frame runs: what the frame adds to the transaction's compute, which is + /// [`at_suspension`](Self::at_suspension) less the child's gas limit. + contribution: u64, +} + +/// What detention records of a frame when revm is about to build a child of it, while no read has +/// set a limit: enough to rebuild what the frame adds to the transaction's compute while that +/// child runs, should a read below it set the first limit. +#[derive(Clone, Copy, Debug, Default)] +struct CallerRecord { + /// The frame's regular gas spent ([`regular_spent`]). + spent: u64, + /// The frame's own gas limit: what its caller's regular gas spent is taken less of. + limit: u64, +} + +/// The frames' figures the transaction's compute is read from. +/// +/// Detention keeps them from the first read that sets a limit on; debug builds keep a second copy +/// from the transaction's first frame on, by the same updates, and hold the first to it. +#[derive(Clone, Debug, Default)] +struct FrameFigures { + /// One entry per frame that runs or is suspended, the running one last. + frames: Vec, + /// The compute of the frames suspended on a child that runs. + suspended: u64, +} + +impl FrameFigures { + fn clear(&mut self) { + self.frames.clear(); + self.suspended = 0; + } + + /// The frame at `depth`, whose gas limit is `gas_limit`, is about to run. On its first run its + /// caller's compute is added; on a resume it is taken back out, because the frame's own + /// regular gas spent now accounts for the child. + fn on_frame_run(&mut self, gas_limit: u64, depth: usize) { + if self.frames.len() == depth { + let contribution = self.caller_contribution(depth, gas_limit); + if let Some(caller) = depth.checked_sub(1).and_then(|i| self.frames.get_mut(i)) { + caller.contribution = contribution; + } + self.suspended = self.suspended.saturating_add(contribution); + self.frames.push(DetainedFrame::default()); + } else if let Some(frame) = self.frames.get_mut(depth) { + self.suspended = self.suspended.saturating_sub(frame.contribution); + frame.contribution = 0; + } + debug_assert_eq!(self.frames.len(), depth + 1, "one entry per frame that runs"); + } + + /// The frame at `depth`, whose gas is `gas`, suspended to start a child. + fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) { + if let Some(frame) = self.frames.get_mut(depth) { + frame.at_suspension = regular_spent(gas); + } + } + + /// The frame at `depth` returns. + fn on_frame_end(&mut self, depth: usize) { + debug_assert_eq!(self.frames.len(), depth + 1, "the frame that returns is the last"); + self.frames.pop(); + } + + /// What the caller of a frame at `depth` with `gas_limit` adds to the transaction's compute + /// while the frame runs: its regular gas spent at suspension, less the frame's gas limit. The + /// transaction's own frame has no caller. + fn caller_contribution(&self, depth: usize, gas_limit: u64) -> u64 { + depth + .checked_sub(1) + .and_then(|i| self.frames.get(i)) + .map_or(0, |caller| caller.at_suspension.saturating_sub(gas_limit)) + } + + /// Asserts that `kept`, the figures detention keeps, are these, kept from the transaction's + /// first frame on: the same entries, but for the running frame's regular gas spent at its last + /// suspension, which these keep stale until the frame suspends again and nothing reads before. + #[cfg(debug_assertions)] + fn assert_kept(&self, kept: &Self) { + assert_eq!(kept.suspended, self.suspended, "the compute of the suspended frames"); + assert_eq!(kept.frames.len(), self.frames.len(), "one entry per frame that runs"); + if let Some(((last, below), (eager_last, eager_below))) = + kept.frames.split_last().zip(self.frames.split_last()) + { + assert_eq!(below, eager_below, "the frames the running one runs under"); + assert_eq!(last.contribution, eager_last.contribution, "the running frame's"); + } + } +} + +/// Gas detention for the running transaction: which volatile data it read, and the most compute +/// it may reach because of it. +/// +/// The `access` module describes the mechanism. +/// +/// # Compute +/// +/// Compute is the regular gas the transaction spends on what it runs. A frame's regular gas spent +/// is read off its [`Gas`]: its limit, less what it has left, less the state and history gas that +/// spilled onto its regular gas, which are not compute. What it has left is the whole of its +/// regular gas, the part withheld from regular charges included, so withheld gas is never spent, +/// and every other reader of the frame's gas sees the same figure. +/// +/// The transaction's compute is its frames' compute: the frame that runs, and every frame +/// suspended on a child that runs, as it stood when it suspended, less the child's gas limit. A +/// value call's stipend is part of that limit and gas nobody paid, so taking the whole limit off +/// takes the stipend off too, as the caller's regular gas spent does once the child returned. So +/// the figure follows the regular ledger of the transaction's frames at every moment, before, +/// during and after each child: +/// +/// ```text +/// compute = Σ suspended callers (spent at suspension − child's gas limit) +/// + regular_spent(running frame) +/// − burned +/// ``` +/// +/// The stipend stays outside compute on purpose: compute is regular gas drawn from the +/// transaction's own pools. A callee may run up to 2,300 gas on each value call's stipend beyond +/// the compute counted. A value call costs its caller 9,100 of compute — the 11,300 of the value +/// transfer less the 2,300 stipend it carries, and a warm access of 100 — and a callee that leaves +/// the stipend unspent returns it, which lowers the caller's spent regular gas: a warm value call +/// to an empty account counts 9,100 − 2,300 = 6,800. So the gas run after a read is at most about +/// 34% (2,300 / 6,800) more than the cap. +/// +/// A keyless deployment's call is the transaction's own frame, and runs no code: it charges its +/// own work — the overhead of decoding the signed transaction and recovering its signer, and the +/// `CREATE` opcode's regular gas — on its own gas, held to the limit as any frame's is when it +/// runs, then suspends on its creation. Its charges are compute as a caller's are, whether a rule +/// then refuses the call or its creation runs. +/// +/// The one part of the regular ledger that is not compute is what a halt burns (`burned`): a +/// frame that halts consumes the gas it had left, and its spill, without running anything with +/// it. A frame answered without running that halts burns its whole gas limit. An out-of-gas zeroes +/// what the frame had before the frame returns; the wrapper of the opcode whose charge failed +/// notes it first, `EXP`'s and the unbounded charges of `KECCAK256` and the copies into memory +/// included. +/// +/// The one charge no wrapper sees is an opcode's static gas, which the interpreter's step loop +/// makes before the opcode runs. When it fails, what the halting frame had left counts as +/// compute: per halting frame, less than the failed charge's price, so at most 4,999, on +/// `SELFDESTRUCT`. Burned gas is counted as compute, so the stop comes earlier, never later. A +/// frame whose leftover takes the compute past the limit does so without a crossing, so the stop +/// is its caller's next charge, and the regular ledger at the stop holds that leftover's part +/// past the limit beside the limit. +/// +/// # Keeping the figure +/// +/// Only a read that sets a limit, and what follows it, needs the transaction's compute, so the +/// frames' figures are kept only from the first such read on. Before it, what a halt burns and the +/// switch are kept as every frame starts and ends, and nothing else but one record per frame revm +/// builds a child of: its regular gas spent and its own gas limit then, which is what it stands at +/// while that child runs. At the first read, the frames the reading frame runs under are exactly +/// the frames suspended on a running child, and what each adds is rebuilt from its record: its +/// regular gas spent less the gas limit of the frame above it, the reading frame's own for the +/// last. From there every frame is kept as it starts, suspends, resumes and ends. +/// +/// # Refused reads +/// +/// A frame in a subtree where volatile-data access is switched off does not read volatile data: +/// the Host refuses the load and the opcode's wrapper reverts the frame with +/// `VolatileDataAccessDisabled`. The switch is scoped to the frame that turned it off and the +/// frames below it, and turns back on when that frame returns. `MegaAccessControl`'s interceptor +/// steers it for the frame that calls the contract. +#[derive(Clone, Debug, Default)] +pub struct Detention { + /// What the Host loaded for the running opcode, waiting for its wrapper. + observed: Cell, + /// What the Host refused to load for the running opcode, waiting for its wrapper. + refused: Cell, + /// Whether the transaction's reads are held to a cap. A system-originated transaction's are + /// not, and neither are a transaction's whose caps are both unlimited. + detains: bool, + /// The cap a read of the block environment or of the beneficiary's account sets. + block_env_cap: u64, + /// The cap a read of the Oracle's storage sets. + oracle_cap: u64, + /// Whether the running frame's volatile reads are refused. + refusing: bool, + /// The depth of the shallowest frame that switched volatile-data access off, if one did. + disabled_from: Option, + /// The depth the switch starts off from in every transaction: test tooling. + #[cfg(any(test, feature = "test-utils"))] + disabled_from_at_start: Option, + /// The depth of the frame an answer being settled switches volatile-data access off for, if + /// it does: applied once the answer settles without a crossing. See + /// [`disable_access_on_answer`](Self::disable_access_on_answer). + answer_disables_from: Option, + /// What the transaction read. + accessed: VolatileDataAccess, + /// The most compute the transaction may reach, once it read volatile data. + limit: Option, + /// The regular gas the frames that halted burned without running anything with it. + burned: u64, + /// What the running frame had left when a charge failed on an out-of-gas whose halt zeroes it. + left_at_halt: Option, + /// The frames' figures, once a read set a limit. + figures: FrameFigures, + /// While no read has set a limit: at each depth, the record of the frame there when revm last + /// built a child of it in the transaction ([`on_child_build`](Self::on_child_build)). An entry + /// below the running frame's depth is its caller's, made when revm built the frame above it. + callers: Vec, + /// The frames' figures kept from the transaction's first frame on, in debug builds, to hold + /// the ones rebuilt at the first read, and every one kept after it, to them. + #[cfg(debug_assertions)] + eager: FrameFigures, +} + +impl Detention { + /// Clears the state for a new transaction, keeping its allocation. + /// + /// `detains` is whether the transaction's reads may be held to a cap at all; + /// `block_env_cap` and `oracle_cap` are the caps its reads set, `u64::MAX` for none. A + /// transaction whose caps are both unlimited is not detained: nothing it reads can cap it. + pub(crate) fn reset(&mut self, detains: bool, block_env_cap: u64, oracle_cap: u64) { + self.observed.set(VolatileDataAccess::empty()); + self.refused.set(VolatileDataAccess::empty()); + self.detains = detains && (block_env_cap != u64::MAX || oracle_cap != u64::MAX); + self.block_env_cap = block_env_cap; + self.oracle_cap = oracle_cap; + self.refusing = false; + self.answer_disables_from = None; + #[cfg(any(test, feature = "test-utils"))] + { + self.disabled_from = self.disabled_from_at_start; + } + #[cfg(not(any(test, feature = "test-utils")))] + { + self.disabled_from = None; + } + self.accessed = VolatileDataAccess::empty(); + self.limit = None; + self.burned = 0; + self.left_at_halt = None; + self.figures.clear(); + self.callers.clear(); + #[cfg(debug_assertions)] + self.eager.clear(); + } + + /// Starts every transaction with volatile-data access switched off from `depth` down, as if + /// the frame at `depth` switched it off before its first instruction: test tooling for the + /// switch `MegaAccessControl` steers. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) const fn set_disabled_from_at_start(&mut self, depth: Option) { + self.disabled_from_at_start = depth; + self.disabled_from = depth; + } + + /// What the transaction read so far. + pub const fn accessed(&self) -> VolatileDataAccess { + self.accessed + } + + /// The most compute the transaction may reach, once it read volatile data: its compute at the + /// read plus the read's cap, the lowest of these when it read more than once. `None` while it + /// read nothing a cap holds. + /// + /// Compute here is the transaction's regular gas spent in its frames, without its intrinsic + /// gas. + pub const fn compute_limit(&self) -> Option { + self.limit + } + + /// Whether the transaction's reads are held to a cap. + pub const fn detains(&self) -> bool { + self.detains + } + + /* The Host */ + + /// Whether the Host refuses a load of `access`: the running frame is in a subtree where + /// volatile-data access is switched off. A refusal is recorded for the running opcode's + /// wrapper, which reverts the frame. + #[inline] + pub(crate) fn refuses(&self, access: VolatileDataAccess) -> bool { + if !self.refusing { + return false; + } + self.refused.set(access); + true + } + + /// Records that the Host loaded `access` for the running opcode. Its wrapper commits the read + /// once the opcode completed. + #[inline] + pub(crate) fn observe(&self, access: VolatileDataAccess) { + if self.detains { + self.observed.set(self.observed.get() | access); + } + } + + /* The opcode wrappers */ + + /// Whether the running frame's volatile reads are refused, so its opcodes must keep the gas + /// they started with to hand it back to a refusal. + #[inline] + pub(crate) const fn is_refusing(&self) -> bool { + self.refusing + } + + /// Forgets what the Host observed or refused outside an opcode's wrapper, so it is not + /// committed for the wrong opcode. + #[inline] + pub(crate) fn discard_stale_reads(&self) { + self.observed.set(VolatileDataAccess::empty()); + self.refused.set(VolatileDataAccess::empty()); + } + + /// Whether the Host observed or refused anything for the running opcode. + #[inline] + pub(crate) fn has_reads(&self) -> bool { + !(self.observed.get() | self.refused.get()).is_empty() + } + + /// Names a refusal the running opcode's Host calls made `access`, whichever load was refused: + /// the kind the opcode reads, for an opcode that loads another kind first. + #[inline] + pub(crate) fn name_refusal(&self, access: VolatileDataAccess) { + if !self.refused.get().is_empty() { + self.refused.set(access); + } + } + + /// Takes what the Host refused for the running opcode, if it refused anything. + pub(crate) fn take_refused(&self) -> Option { + let refused = self.refused.replace(VolatileDataAccess::empty()); + (!refused.is_empty()).then_some(refused) + } + + /// Takes what the Host observed for the running opcode. + pub(crate) fn take_observed(&self) -> VolatileDataAccess { + self.observed.replace(VolatileDataAccess::empty()) + } + + /// Commits the reads `observed` of the opcode the running frame, at `depth` and whose gas is + /// `gas`, completed: the transaction's limit becomes its compute now plus the reads' cap, + /// unless it is already lower, and the frame's spendable gas is held to what the limit leaves + /// it. The first read that sets a limit starts keeping the frames' figures + /// ([`track`](Self::track)). + /// + /// `forwarded` is the regular gas the opcode forwarded to a frame it is about to start, which + /// the frame's regular gas spent includes and its compute does not. + pub(crate) fn commit_reads( + &mut self, + observed: VolatileDataAccess, + gas: &mut Gas, + depth: usize, + forwarded: u64, + ) { + self.accessed |= observed; + let cap = self.cap_of(observed); + if cap == u64::MAX { + return; + } + if self.limit.is_none() { + self.track(gas, depth); + } + let compute = self.compute(gas).saturating_sub(forwarded); + let limit = self.lower_limit(compute.saturating_add(cap)); + gas.limit_spendable(limit.saturating_sub(compute)); + } + + /// Records a read the transaction makes by being what it is, before any frame: a sender or a + /// recipient that is the block beneficiary, an EIP-7702 authority that is, or a recipient that + /// delegates to it. No compute has been spent, so the limit is the read's cap. + pub(crate) fn mark_before_execution(&mut self, access: VolatileDataAccess) { + if !self.detains { + return; + } + self.accessed |= access; + let cap = self.cap_of(access); + if cap != u64::MAX { + self.lower_limit(cap); + } + } + + /// Holds the running frame's spendable gas to what the limit leaves the transaction, once a + /// read set one. + /// + /// Called where the frame's spendable gas can have grown past it: when the frame starts, when + /// it resumes on the gas a child handed back, and after a storage write, whose restore of a + /// slot to its original value refills the state and history gas that spilled onto regular gas. + #[inline] + pub(crate) fn hold(&self, gas: &mut Gas) { + if let Some(limit) = self.limit { + gas.limit_spendable(limit.saturating_sub(self.compute(gas))); + } + } + + /// Notes what the running frame has left, `left`, when an opcode's charge failed on an + /// out-of-gas the halt after it zeroes: what the halt burns rather than what the frame ran. + #[inline] + pub(crate) const fn note_halt(&mut self, left: u64) { + self.left_at_halt = Some(left); + } + + /* The frame lifecycle */ + + /// The frame at `depth`, whose gas is `gas`, is about to run: for the first time, or again + /// after a child returned into it. + /// + /// The switch is read for the frame. Once a read set a limit, a frame's first run adds its + /// caller's compute to the transaction's, now that the frame's gas limit is known — what the + /// caller forwarded, and a value call's stipend; a resumed frame takes it back out, because + /// its own regular gas spent now accounts for the child. Then the frame is held to the limit. + #[inline] + pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) { + self.refusing = self.disabled_from.is_some_and(|from| depth >= from); + #[cfg(debug_assertions)] + if self.detains { + self.eager.on_frame_run(gas.limit(), depth); + } + // Only a read of a transaction detention holds sets a limit. + if self.limit.is_none() { + return; + } + debug_assert!(self.detains, "a limit on a transaction detention does not hold"); + self.figures.on_frame_run(gas.limit(), depth); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.figures); + self.hold(gas); + } + + /// The frame at `depth`, whose gas is `gas`, suspended to start a child. Its compute stands + /// still until the child returns. + #[inline] + pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) { + #[cfg(debug_assertions)] + if self.detains { + self.eager.on_frame_suspend(gas, depth); + } + if self.limit.is_none() { + return; + } + self.figures.on_frame_suspend(gas, depth); + } + + /// Whether revm building a frame's child is to be recorded ([`on_child_build`]): the + /// transaction is detained, and no read has set a limit. + /// + /// [`on_child_build`]: Self::on_child_build + #[inline] + pub(crate) const fn records_callers(&self) -> bool { + self.detains && self.limit.is_none() + } + + /// Records the frame at `depth − 1`, whose gas is `caller`, as revm is about to build a child + /// of it at `depth`, while no read has set a limit ([`records_callers`]): its regular gas + /// spent and its gas limit. Until the child returns, that is what the frame stands at, so a + /// read below it rebuilds what the frame adds to the transaction's compute from it + /// ([`track`](Self::track)). + /// + /// A frame answered without running records its caller too, which the caller's next child + /// overwrites; a read is only ever made in a frame revm built. + /// + /// [`records_callers`]: Self::records_callers + #[inline] + pub(crate) fn on_child_build(&mut self, depth: usize, caller: &Gas) { + debug_assert!(self.records_callers() && depth > 0, "a caller recorded while untracked"); + let index = depth - 1; + if index >= self.callers.len() { + self.callers.resize(index + 1, CallerRecord::default()); + } + self.callers[index] = CallerRecord { spent: regular_spent(caller), limit: caller.limit() }; + } + + /// Starts keeping the frames' figures at the first read that sets a limit, made by the frame + /// that runs, at `depth` and whose gas is `gas`. + /// + /// The frames it runs under are those suspended on a running child, and each one's record is + /// the one made when revm built that child: what the frame adds to the transaction's compute is + /// its regular gas spent then less the child's gas limit — the next record's, or the reading + /// frame's own for the last. They are added in the order the frames started, as they would + /// have been when each child first ran. + #[cold] + #[inline(never)] + fn track(&mut self, gas: &Gas, depth: usize) { + // Every frame below the reading one was built in the transaction while no read had set a + // limit, so revm building it recorded its caller. + let records = &self.callers[..depth]; + let reading_limit = gas.limit(); + let figures = &mut self.figures; + figures.clear(); + for (index, record) in records.iter().enumerate() { + let child_limit = records.get(index + 1).map_or(reading_limit, |child| child.limit); + let contribution = record.spent.saturating_sub(child_limit); + figures.suspended = figures.suspended.saturating_add(contribution); + figures.frames.push(DetainedFrame { at_suspension: record.spent, contribution }); + } + figures.frames.push(DetainedFrame::default()); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.figures); + } + + /// Records a read of `access` the running frame, at `depth` and whose gas is `gas`, makes + /// itself rather than through an opcode — a keyless deployment's call reading its signer's + /// account — and holds the frame to the limit it sets, as an opcode's read is committed + /// ([`commit_reads`](Self::commit_reads)). A transaction detention does not hold records + /// nothing, as the Host observes nothing for it. + pub(crate) fn read_by_frame( + &mut self, + access: VolatileDataAccess, + gas: &mut Gas, + depth: usize, + ) { + if self.detains { + self.commit_reads(access, gas, depth, 0); + } + } + + /// The frame at `depth` returns `result` with `gas`, after it ran. The switch turns back on if + /// the frame, or a frame below it, turned it off. A frame that halts burns what it had left. + /// + /// Returns the stop when the frame ran out of gas on a charge the withheld part of its gas + /// would have paid ([`stop`](Self::stop)): the frame crossed the limit, and must revert with + /// the stop rather than halt. The stop's compute is the transaction's with the frame's gas + /// put back. + #[inline] + pub(crate) fn on_frame_end( + &mut self, + result: InstructionResult, + gas: &mut Gas, + depth: usize, + ) -> Option { + let left_at_halt = self.left_at_halt.take(); + if self.disabled_from.is_some_and(|from| from >= depth) { + self.disabled_from = None; + } + if !self.detains { + return None; + } + #[cfg(debug_assertions)] + self.eager.on_frame_end(depth); + if self.limit.is_some() { + self.figures.on_frame_end(depth); + #[cfg(debug_assertions)] + self.eager.assert_kept(&self.figures); + } + if let Some(limit) = self.stop(gas) { + return Some(ComputeStop { limit, used: self.compute(gas) }); + } + if result.is_halt() { + // The settlement rolls the spill back into regular gas and burns it all. + let left = left_at_halt.unwrap_or_else(|| gas.remaining()); + self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled()); + } + None + } + + /// The regular gas a frame at `depth` that its caller forwarded `gas_limit` may spend before + /// the transaction's compute reaches the limit: the spendable part the frame would start + /// with. `None` while no read set a limit. + pub(crate) fn allowance(&self, depth: usize, gas_limit: u64) -> Option { + let limit = self.limit?; + Some(limit.saturating_sub(self.compute_at_start(depth, gas_limit))) + } + + /// The frame at `depth`, whose gas limit was `gas_limit`, was answered without running — + /// `result` is the answer: a precompile's, an interceptor's, a `keylessDeploy` call's that + /// carries value, an inspector's, or revm's for a call it did not start. + /// + /// An answer marked as a crossing — a precompile whose price crosses the limit + /// ([`cross_at_price`](Self::cross_at_price)), or one the engine cannot price that ran out of + /// the allowance it was held to ([`restore_forward`](Self::restore_forward)) — crossed the + /// limit. Otherwise, an answer that halts burns the whole gas limit: nothing ran with it. An + /// answer that spent more regular gas than the limit leaves the frame — the allowance it would + /// have run on — is a charge the frame could not have made; state and history gas that spilled + /// onto its regular gas are not counted, as they are not a running frame's compute. Such an + /// answer is answered out of gas and marked as a crossing, the answer's spending being the + /// charge that crossed. A crossing is settled by the same rule as a frame that ran + /// ([`stop`](Self::stop)): the frame spent nothing before the charge, so it is given its whole + /// gas back, and the stop's compute is the transaction's when the frame started. Returns the + /// stop when it crossed. + /// + /// Until a read sets a limit an answer can only burn: nothing it spends can cross a limit, and + /// only the engine marks an answer as a crossing, which it does only under a limit. + /// + /// A switch-off the answer staged + /// ([`disable_access_on_answer`](Self::disable_access_on_answer)) is applied when the + /// answer did not cross, and dropped when it did. + #[inline] + pub(crate) fn on_answer( + &mut self, + result: &mut InterpreterResult, + depth: usize, + gas_limit: u64, + ) -> Option { + let stop = self.classify_answer(result, depth, gas_limit); + if let Some(caller) = self.answer_disables_from.take() { + if stop.is_none() { + self.disable_access(caller); + } + } + stop + } + + /// [`on_answer`](Self::on_answer)'s verdict on `result`, the answer to the frame at `depth` + /// whose gas limit was `gas_limit`. + #[inline] + fn classify_answer( + &mut self, + result: &mut InterpreterResult, + depth: usize, + gas_limit: u64, + ) -> Option { + if !self.detains { + return None; + } + if self.limit.is_none() && result.gas.withheld_crossing().is_none() { + if result.result.is_halt() { + self.burned = self.burned.saturating_add(gas_limit); + } + return None; + } + self.on_held_answer(result, depth, gas_limit) + } + + /// [`on_answer`](Self::on_answer) once a read set a limit, or for an answer marked as a + /// crossing. + #[inline(never)] + fn on_held_answer( + &mut self, + result: &mut InterpreterResult, + depth: usize, + gas_limit: u64, + ) -> Option { + if result.gas.withheld_crossing().is_none() { + if result.result.is_halt() { + self.burned = self.burned.saturating_add(gas_limit); + return None; + } + let allowance = self.allowance(depth, gas_limit)?; + // The regular gas the answer spent: state and history gas that spilled onto it are not + // compute, as they are not a running frame's. + let spent = gas_limit + .saturating_sub(result.gas.remaining()) + .saturating_sub(result.gas.state_gas_spilled()); + if spent <= allowance { + return None; + } + // The answer spent more than the allowance, and no more than the gas limit, so the + // gas limit is above the allowance and the frame would have had the rest withheld. The + // one answer of the engine's own that spends regular gas is that of a `keylessDeploy` + // call carrying value; the limit is set to the forward all the same, so + // an inspector's answer built on another limit is settled on what the frame was + // forwarded. + // + // The record holds the regular gas the frame had before the charge: the gas limit, + // less the state and history gas that spilled onto it, which the revert that settles + // the stop credits back. The spill is below the gas limit, less the regular gas the + // answer spent, so what is left is never zero. + let remaining = NonZeroU64::new(gas_limit - result.gas.state_gas_spilled())?; + result.result = InstructionResult::OutOfGas; + result.gas.tracker_mut().set_limit(gas_limit); + result.gas.set_withheld_crossing(Some(WithheldCrossing::with_remaining(remaining))); + } + let limit = self.stop(&mut result.gas)?; + // Every crossing an answer carries was marked by the engine with the regular gas the frame + // had before the charge: the forward less the spill here, the forward for a precompile's, + // which spills nothing. Put back, it leaves the answer no regular gas spent, so the stop's + // compute is the transaction's when the frame started. + debug_assert_eq!(regular_spent(&result.gas), 0, "a stopped answer spent nothing"); + Some(ComputeStop { limit, used: self.compute_at_start(depth, gas_limit) }) + } + + /// Gives the answer of a precompile the engine cannot price, which ran on `withheld` less than + /// its caller forwarded — the allowance, not the forward — the rest back, as the frame would + /// have had it withheld: the answer's gas limit is the forward again, and an answer that did + /// not halt keeps the withheld part unspent. A precompile that ran out of gas on the allowance + /// ran out of what the limit left the transaction: the answer is marked as a crossing, and + /// [`on_answer`](Self::on_answer) settles it as the stop. + /// + /// Without a price the run on the allowance is all there is to go by, so such a precompile + /// priced above its whole forward runs out of the allowance as well, and is the stop too. + pub(crate) fn restore_forward(result: &mut InterpreterResult, withheld: NonZeroU64) { + let forward = withheld.saturating_add(result.gas.limit()); + result.gas.tracker_mut().set_limit(forward.get()); + if result.result == InstructionResult::PrecompileOOG { + // The record holds the regular gas the frame had before the charge: its forward. + result.gas.set_withheld_crossing(Some(WithheldCrossing::with_remaining(forward))); + } else if !result.result.is_halt() { + result.gas.erase_cost(withheld.get()); + } + } + + /// Marks `result`, the answer to a precompile call held to an allowance below its forward and + /// answered without running because its price is past the allowance and within the forward, + /// as that crossing: the record holds the forward, the regular gas the frame had before the + /// charge, since the call spent none of it. [`on_answer`](Self::on_answer) settles it as the + /// stop. + pub(crate) fn cross_at_price(result: &mut InterpreterResult) { + if let Some(forward) = NonZeroU64::new(result.gas.limit()) { + result.gas.set_withheld_crossing(Some(WithheldCrossing::with_remaining(forward))); + } + } + + /// Settles a frame whose regular gas ran out on a charge the withheld part would have paid — + /// the fork records it as a [`WithheldCrossing`] — and returns the limit it crossed. + /// + /// The frame's regular gas is put back to what it had before the charge that crossed, the + /// record's [`remaining`](WithheldCrossing::remaining): the charge is not made, so the + /// transaction is billed its compute at the crossing, less than one charge short of the limit, + /// and all the frame had left, its spendable and withheld parts together, goes back to its + /// caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, + /// or `return_create`'s own out-of-gas on a deposit charge), the settlement is the same. A + /// crossing only ever ends a frame on an out-of-gas, and only a frame detention held carries + /// one. + fn stop(&self, gas: &mut Gas) -> Option { + let crossing = gas.withheld_crossing()?; + gas.set_remaining(crossing.remaining()); + gas.clear_withheld_crossing(); + self.limit + } + + /* The switch */ + + /// Switches volatile-data access off for the frame at `depth` and every frame below it. A + /// switch already off from a shallower frame stays as it is. + /// + /// The frame that steers the switch reads it when it resumes, after the call that steered it. + pub fn disable_access(&mut self, depth: usize) { + self.disabled_from = Some(self.disabled_from.map_or(depth, |from| from.min(depth))); + } + + /// Switches volatile-data access off for the frame at `depth`, as + /// [`disable_access`](Self::disable_access) does, once the answer being built for a call it + /// made settles without crossing the compute limit ([`on_answer`](Self::on_answer)): an answer + /// that becomes the stop did not succeed, and the frame that catches it resumes with the + /// switch as it was. + pub(crate) const fn disable_access_on_answer(&mut self, depth: usize) { + self.answer_disables_from = Some(depth); + } + + /// Switches volatile-data access back on for the frame at `depth`, and reports whether it + /// could: a frame cannot switch back on what a frame above it switched off. + pub fn enable_access(&mut self, depth: usize) -> bool { + match self.disabled_from { + Some(from) if depth > from => false, + _ => { + self.disabled_from = None; + true + } + } + } + + /// Whether volatile-data access is switched off for a frame at `depth`. + pub fn is_access_disabled(&self, depth: usize) -> bool { + self.disabled_from.is_some_and(|from| depth >= from) + } + + /* Helpers */ + + /// The transaction's compute while the running frame has `gas`. + fn compute(&self, gas: &Gas) -> u64 { + self.figures.suspended.saturating_add(regular_spent(gas)).saturating_sub(self.burned) + } + + /// The transaction's compute when a frame at `depth` with `gas_limit` starts, before it runs + /// anything: every suspended caller's, the frame's own caller's included. + fn compute_at_start(&self, depth: usize, gas_limit: u64) -> u64 { + self.figures + .suspended + .saturating_add(self.figures.caller_contribution(depth, gas_limit)) + .saturating_sub(self.burned) + } + + /// Lowers the limit to `limit`, unless it is already lower, and returns the limit. + fn lower_limit(&mut self, limit: u64) -> u64 { + let limit = self.limit.map_or(limit, |current| current.min(limit)); + self.limit = Some(limit); + limit + } + + /// The cap a read of `access` sets: the lowest of the caps of the kinds it holds, `u64::MAX` + /// when none of them is capped. + fn cap_of(&self, access: VolatileDataAccess) -> u64 { + let mut cap = u64::MAX; + if access.has_block_env_access() || access.has_beneficiary_balance_access() { + cap = cap.min(self.block_env_cap); + } + if access.has_oracle_access() { + cap = cap.min(self.oracle_cap); + } + cap + } +} + +/// The revert data of a read of `access` refused while volatile-data access is switched off: +/// `VolatileDataAccessDisabled(accessType)`, the access type being the kind's position in the +/// set ([`VolatileDataAccess::as_u8`]). +pub fn volatile_data_access_disabled_revert_data(access: VolatileDataAccess) -> Bytes { + let mut data = Vec::with_capacity(36); + data.extend_from_slice(&VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); + data.extend_from_slice(&U256::from(access.as_u8()).to_be_bytes::<32>()); + data.into() +} + +/// The kind of volatile data the revert data of a refused read names: +/// `VolatileDataAccessDisabled(accessType)`, decoded with its argument as the `uint8` it is +/// encoded as. `None` when `revert_data` is not that error, or names no kind. +/// +/// Decoding the argument as the contract's `VolatileDataAccessType` cannot name a `SLOTNUM` +/// refusal, whose access type, [`SLOT_NUM_ACCESS_TYPE`](crate::system::SLOT_NUM_ACCESS_TYPE), the +/// enum does not declare: the `IMegaAccessControl` binding decodes it to its `__Invalid` +/// placeholder. +pub fn decode_volatile_data_access_disabled(revert_data: &[u8]) -> Option { + let (selector, word) = revert_data.split_first_chunk::<4>()?; + if *selector != VOLATILE_DATA_ACCESS_DISABLED_SELECTOR || word.len() != 32 { + return None; + } + // A `uint8` word: 31 zero bytes, then the value. + let (high, low) = word.split_at(31); + if high.iter().any(|byte| *byte != 0) { + return None; + } + VolatileDataAccess::from_access_type(low[0]) +} + +/// The regular gas a frame spent: its limit, less what it has left — the withheld part included — +/// less the state and history gas that spilled onto its regular gas. +#[inline] +pub(crate) const fn regular_spent(gas: &Gas) -> u64 { + gas.limit().saturating_sub(gas.remaining()).saturating_sub(gas.state_gas_spilled()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}; + + /// A frame's gas: `limit` regular gas and `reservoir`. + fn gas(limit: u64, reservoir: u64) -> Gas { + Gas::new_with_regular_gas_and_reservoir(limit, reservoir) + } + + fn detaining() -> Detention { + let mut detention = Detention::default(); + detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + detention + } + + /// The cap of a read is the lowest of the caps of the kinds it holds. + #[test] + fn test_the_cap_of_a_read_is_its_kinds_lowest() { + let mut detention = Detention::default(); + detention.reset(true, 7, 5); + assert_eq!(detention.cap_of(VolatileDataAccess::TIMESTAMP), 7); + assert_eq!(detention.cap_of(VolatileDataAccess::SLOT_NUM), 7); + assert_eq!(detention.cap_of(VolatileDataAccess::BENEFICIARY_BALANCE), 7); + assert_eq!(detention.cap_of(VolatileDataAccess::ORACLE), 5); + assert_eq!(detention.cap_of(VolatileDataAccess::ORACLE | VolatileDataAccess::TIMESTAMP), 5); + assert_eq!(detention.cap_of(VolatileDataAccess::empty()), u64::MAX); + } + + /// A read holds the frame's spendable gas at its compute then plus the cap; the rest is + /// withheld, and the frame's gas as every other reader sees it does not move. + #[test] + fn test_a_read_withholds_what_the_cap_leaves_over() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 7); + detention.on_frame_run(&mut frame, 0); + assert!(frame.record_regular_cost(1_000)); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + + assert_eq!(detention.compute_limit(), Some(1_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert_eq!(frame.remaining(), 100_000_000 - 1_000); + assert_eq!(frame.reservoir(), 7); + assert_eq!(detention.accessed(), VolatileDataAccess::TIMESTAMP); + assert_eq!(detention.on_frame_end(InstructionResult::Stop, &mut frame, 0), None); + } + + /// A limit only goes down: a later read with room for more leaves it where it is. + #[test] + fn test_the_first_limit_binds_when_it_is_lower() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(frame.record_regular_cost(5_000)); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); + assert_eq!(detention.compute_limit(), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS)); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000); + } + + /// State and history gas draw the withheld part first and are not compute: the frame's + /// allowance is what it was. + #[test] + fn test_state_gas_drawn_from_the_withheld_part_is_not_compute() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(frame.record_state_cost(1_000_000)); + detention.hold(&mut frame); + assert_eq!(detention.compute(&frame), 0); + assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + } + + /// A regular charge the withheld part would have paid is the cap: the frame's gas is put back + /// to what it had before the charge, and the stop's compute is the transaction's then — here + /// the 10 the frame charged after the read, whatever the halt did to its gas. + #[test] + fn test_a_crossing_stops_with_the_gas_it_had_before_the_charge() { + for (result, zeroed) in + [(InstructionResult::OutOfGas, true), (InstructionResult::MemoryOOG, false)] + { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(frame.record_regular_cost(10)); + assert!(!frame.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS)); + if zeroed { + frame.spend_all(); + } + let stop = detention.on_frame_end(result, &mut frame, 0); + let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS; + assert_eq!(stop, Some(ComputeStop { limit, used: 10 }), "{result:?}"); + assert_eq!(frame.remaining(), 100_000_000 - 10); + assert_eq!(frame.withheld_crossing(), None); + assert_eq!(regular_spent(&frame), 10, "the charge that crossed is not made"); + } + } + + /// A child's crossing stops with the compute of the whole transaction: what its callers + /// computed before they suspended, less the gas they forwarded, and what it computed itself. + #[test] + fn test_a_childs_crossing_stops_with_the_transactions_compute() { + let mut detention = detaining(); + let mut caller = gas(100_000_000, 0); + detention.on_frame_run(&mut caller, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + assert!(caller.record_regular_cost(7_000)); + assert!(caller.record_withheld_first_cost(50_000_000)); + detention.on_frame_suspend(&caller, 0); + let mut child = gas(50_000_000, 0); + detention.on_frame_run(&mut child, 1); + assert_eq!(child.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 7_000); + assert!(child.record_regular_cost(3_000)); + assert!(!child.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS)); + child.spend_all(); + + let stop = detention.on_frame_end(InstructionResult::OutOfGas, &mut child, 1); + let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS; + assert_eq!(stop, Some(ComputeStop { limit, used: 7_000 + 3_000 })); + assert_eq!(child.remaining(), 50_000_000 - 3_000); + } + + /// An out-of-gas nothing withheld could have paid halts and burns what the frame had. + #[test] + fn test_an_out_of_gas_beyond_the_whole_gas_halts() { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(!frame.record_regular_cost(100_000_001)); + detention.note_halt(frame.remaining()); + frame.spend_all(); + assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + assert_eq!(detention.burned, 100_000_000); + + // A frame nothing was withheld from runs out of its own gas. + let mut detention = detaining(); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert_eq!(frame.withheld(), 0, "nothing to withhold"); + assert!(!frame.record_regular_cost(1_000_001)); + frame.spend_all(); + assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); + } + + /// A child's compute adds to its caller's; the caller's forwarded gas and the child's stipend + /// do not, and after the child returns the caller's own gas accounts for it the same way. + #[test] + fn test_compute_spans_frames() { + let mut detention = detaining(); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + let mut caller = gas(100_000, 0); + detention.on_frame_run(&mut caller, 0); + assert!(caller.record_regular_cost(9_000 + 60_000)); + detention.on_frame_suspend(&caller, 0); + assert_eq!(detention.compute_at_start(1, 60_000 + 2_300), 9_000 - 2_300); + + let mut child = gas(60_000 + 2_300, 0); + detention.on_frame_run(&mut child, 1); + assert_eq!(detention.compute(&child), 9_000 - 2_300); + assert!(child.record_regular_cost(4_000)); + assert_eq!(detention.compute(&child), 9_000 + 4_000 - 2_300); + detention.on_frame_end(InstructionResult::Stop, &mut child, 1); + + caller.erase_cost(child.remaining()); + detention.on_frame_run(&mut caller, 0); + assert_eq!(detention.compute(&caller), 9_000 + 4_000 - 2_300); + assert_eq!(detention.figures.suspended, 0); + } + + /// Nothing is kept of the frames before a read sets a limit but what a halt burns and one + /// record per frame revm builds a child of. The first read rebuilds what the frames it runs + /// under add to the transaction's compute from those records: each one's regular gas spent less + /// its child's gas limit, a stipend included, and a halted child's burn taken off. + #[test] + fn test_the_first_read_rebuilds_the_compute_of_the_frames_it_runs_under() { + const CAP: u64 = 1_000; + let mut detention = Detention::default(); + detention.reset(true, CAP, CAP); + let mut caller = gas(1_000_000, 0); + detention.on_frame_run(&mut caller, 0); + assert!(caller.record_regular_cost(2_000)); + + // A child that halts after running 1,000 of the 10,000 it was forwarded. + assert!(caller.record_withheld_first_cost(10_000)); + detention.on_frame_suspend(&caller, 0); + detention.on_child_build(1, &caller); + let mut halting = gas(10_000, 0); + detention.on_frame_run(&mut halting, 1); + assert!(halting.record_regular_cost(1_000)); + assert_eq!( + detention.on_frame_end(InstructionResult::InvalidFEOpcode, &mut halting, 1), + None + ); + detention.on_frame_run(&mut caller, 0); + + // A value call: 9,000 of its own, 60,000 forwarded and a stipend of 2,300. + assert!(caller.record_regular_cost(9_000)); + assert!(caller.record_withheld_first_cost(60_000)); + detention.on_frame_suspend(&caller, 0); + detention.on_child_build(1, &caller); + let mut child = gas(60_000 + 2_300, 0); + detention.on_frame_run(&mut child, 1); + assert!(child.record_regular_cost(4_000)); + assert!(child.record_withheld_first_cost(30_000)); + detention.on_frame_suspend(&child, 1); + detention.on_child_build(2, &child); + let mut grandchild = gas(30_000, 0); + detention.on_frame_run(&mut grandchild, 2); + assert!(grandchild.record_regular_cost(500)); + assert!(detention.figures.frames.is_empty(), "nothing kept before a read"); + assert_eq!(detention.burned, 9_000); + + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 2, 0); + let caller_adds = 2_000 + 10_000 + 9_000 + 60_000 - (60_000 + 2_300); + let child_adds = 4_000 + 30_000 - 30_000; + assert_eq!(detention.figures.suspended, caller_adds + child_adds); + let compute = 2_000 + 1_000 + 9_000 - 2_300 + 4_000 + 500; + assert_eq!(detention.compute(&grandchild), compute); + assert_eq!(detention.compute_limit(), Some(compute + CAP)); + assert_eq!(grandchild.spendable(), CAP); + + // From the read on the frames are kept as they return. + assert!(grandchild.record_regular_cost(600)); + assert_eq!(detention.on_frame_end(InstructionResult::Stop, &mut grandchild, 2), None); + child.erase_cost(grandchild.remaining()); + detention.on_frame_run(&mut child, 1); + assert_eq!(detention.figures.suspended, caller_adds); + assert_eq!(detention.compute(&child), compute + 600); + assert_eq!(child.spendable(), CAP - 600); + } + + /// A caller is recorded only while it may be needed: the transaction is detained and no read + /// has set a limit yet. From the first read on, the frames are kept as they run. + #[test] + fn test_callers_are_recorded_only_until_the_first_read() { + let mut free = Detention::default(); + free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + assert!(!free.records_callers(), "a transaction detention does not hold"); + + let mut detention = detaining(); + assert!(detention.records_callers()); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + assert!(!detention.records_callers(), "a read set a limit"); + + detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + assert!(!detention.records_callers(), "a read before any frame set a limit"); + } + + /// A transaction can end with frames still running — an error stops it mid-frame — and the + /// next one starts from nothing: a read in its child rebuilds from its own records alone. + #[test] + fn test_a_reset_forgets_the_frames_a_transaction_left_running() { + let mut detention = detaining(); + let mut caller = gas(1_000_000, 0); + detention.on_frame_run(&mut caller, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + assert!(caller.record_regular_cost(7_000)); + assert!(caller.record_withheld_first_cost(500_000)); + detention.on_frame_suspend(&caller, 0); + let mut child = gas(500_000, 0); + detention.on_frame_run(&mut child, 1); + assert_eq!(detention.figures.suspended, 7_000); + + detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + let mut caller = gas(1_000_000, 0); + detention.on_frame_run(&mut caller, 0); + assert!(caller.record_regular_cost(3_000)); + assert!(caller.record_withheld_first_cost(500_000)); + detention.on_frame_suspend(&caller, 0); + detention.on_child_build(1, &caller); + let mut child = gas(500_000, 0); + detention.on_frame_run(&mut child, 1); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 1, 0); + assert_eq!(detention.figures.suspended, 3_000); + assert_eq!(detention.figures.frames.len(), 2); + assert_eq!(detention.compute_limit(), Some(3_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); + } + + /// A reset forgets the callers a transaction recorded: the next one reads only its own. + #[test] + fn test_a_reset_forgets_the_callers_a_transaction_recorded() { + let mut detention = detaining(); + let caller = gas(1_000_000, 0); + detention.on_child_build(1, &caller); + detention.on_child_build(2, &caller); + assert_eq!(detention.callers.len(), 2); + + detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + assert!(detention.callers.is_empty()); + } + + /// The eager figures debug builds keep catch a kept figure that parts from them. + #[cfg(debug_assertions)] + #[test] + #[should_panic(expected = "the compute of the suspended frames")] + fn test_the_eager_figures_catch_a_kept_one_that_parts_from_them() { + let mut eager = FrameFigures::default(); + eager.on_frame_run(1_000_000, 0); + let mut kept = eager.clone(); + eager.assert_kept(&kept); + kept.suspended = 1; + eager.assert_kept(&kept); + } + + /// What a halting child burns is not compute: its caller's compute after it returns is what + /// the child ran, not the gas the child was given — whether the halt left the gas in place or + /// zeroed it after the child's wrapper noted it. + #[test] + fn test_what_a_halt_burns_is_not_compute() { + for zeroed in [false, true] { + let mut detention = detaining(); + let mut caller = gas(1_000_000, 0); + detention.on_frame_run(&mut caller, 0); + assert!(caller.record_regular_cost(500_000)); + detention.on_frame_suspend(&caller, 0); + let mut child = gas(500_000, 0); + detention.on_frame_run(&mut child, 1); + assert!(child.record_regular_cost(1_000)); + assert!(child.record_state_cost(3_000)); + let result = if zeroed { + detention.note_halt(child.remaining()); + child.spend_all(); + InstructionResult::OutOfGas + } else { + InstructionResult::InvalidFEOpcode + }; + assert_eq!(detention.on_frame_end(result, &mut child, 1), None); + + // The caller's regular gas spent now holds everything it forwarded. + detention.on_frame_run(&mut caller, 0); + assert_eq!(detention.compute(&caller), 1_000, "zeroed: {zeroed}"); + assert_eq!(detention.burned, 500_000 - 1_000); + } + } + + /// An answer that halts burns the gas limit; one that spent more regular gas than the frame's + /// allowance is answered out of gas and stops at the limit, with its whole gas limit back but + /// the spill. State gas that spilled onto the answer's regular gas is not compute. + #[test] + fn test_an_answer_is_held_to_the_allowance_it_would_have_run_on() { + let mut detention = detaining(); + let mut caller = gas(100_000_000, 0); + detention.on_frame_run(&mut caller, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + assert!(caller.record_withheld_first_cost(90_000_000)); + detention.on_frame_suspend(&caller, 0); + + let answer = |spent: u64, result| { + let mut gas = gas(90_000_000, 0); + assert!(gas.record_regular_cost(spent)); + InterpreterResult::new(result, Bytes::new(), gas) + }; + let mut within = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS, InstructionResult::Return); + assert_eq!(detention.on_answer(&mut within, 1, 90_000_000), None); + assert_eq!(within.result, InstructionResult::Return); + + let mut spilled = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS, InstructionResult::Revert); + assert!(spilled.gas.record_state_cost(1_000)); + assert_eq!(spilled.gas.state_gas_spilled(), 1_000); + assert_eq!(detention.on_answer(&mut spilled, 1, 90_000_000), None, "a spill is no compute"); + assert_eq!(spilled.result, InstructionResult::Revert); + + let mut halted = answer(0, InstructionResult::PrecompileError); + assert_eq!(detention.on_answer(&mut halted, 1, 90_000_000), None); + assert_eq!(detention.burned, 90_000_000); + detention.burned = 0; + + // The answer's spending is the charge that crossed: before it the frame had its whole gas + // limit, less the spill, which the revert that settles the stop credits back. + let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS; + for spill in [0, 1_000] { + let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1, InstructionResult::Return); + assert!(beyond.gas.record_state_cost(spill)); + assert_eq!( + detention.on_answer(&mut beyond, 1, 90_000_000), + Some(ComputeStop { limit, used: 0 }), + "the transaction computed nothing before the answer: {spill}" + ); + assert_eq!(beyond.result, InstructionResult::OutOfGas); + assert_eq!(beyond.gas.remaining(), 90_000_000 - spill); + assert_eq!(regular_spent(&beyond.gas), 0); + } + } + + /// A switch-off an answer stages applies once the answer settles without a crossing: an + /// answer gas detention turns into the stop leaves access as it was, one that settles within + /// the limit switches it off, and so does one of a transaction that is not detained. A staged + /// switch goes with the answer it was staged for, whatever that answer settled as. + #[test] + fn test_an_answer_switches_access_off_only_when_it_does_not_cross() { + let mut detention = detaining(); + let mut caller = gas(100_000_000, 0); + detention.on_frame_run(&mut caller, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + assert!(caller.record_withheld_first_cost(90_000_000)); + detention.on_frame_suspend(&caller, 0); + let answer = |spent: u64| { + let mut gas = gas(90_000_000, 0); + assert!(gas.record_regular_cost(spent)); + InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas) + }; + + detention.disable_access_on_answer(0); + let mut beyond = answer(BLOCK_ENV_ACCESS_COMPUTE_GAS + 1); + assert!(detention.on_answer(&mut beyond, 1, 90_000_000).is_some(), "the answer crossed"); + assert!(!detention.is_access_disabled(0), "and access stays on"); + + let mut unstaged = answer(0); + assert_eq!(detention.on_answer(&mut unstaged, 1, 90_000_000), None); + assert!(!detention.is_access_disabled(0), "the crossing answer took its switch with it"); + + detention.disable_access_on_answer(0); + let mut within = answer(0); + assert_eq!(detention.on_answer(&mut within, 1, 90_000_000), None); + assert!(detention.is_access_disabled(0), "an answer within the limit switches it off"); + + let mut free = Detention::default(); + assert!(!free.detains()); + free.disable_access_on_answer(0); + assert_eq!(free.on_answer(&mut answer(0), 1, 90_000_000), None); + assert!(free.is_access_disabled(0), "a transaction that is not detained switches it off"); + } + + /// A precompile run on the allowance gets the rest of the forward back: a success keeps it + /// unspent, a halt burns the forward as it would without the read, and an out-of-gas on the + /// allowance is a crossing, which the answer's settlement stops with the whole forward back. + #[test] + fn test_a_precompile_run_on_the_allowance_is_settled_on_the_forward() { + let mut detention = detaining(); + let mut caller = gas(100_000_000, 0); + detention.on_frame_run(&mut caller, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + assert!(caller.record_withheld_first_cost(90_000_000)); + detention.on_frame_suspend(&caller, 0); + let allowance = detention.allowance(1, 90_000_000).unwrap(); + assert_eq!(allowance, BLOCK_ENV_ACCESS_COMPUTE_GAS); + let withheld = NonZeroU64::new(90_000_000 - allowance).unwrap(); + let answer = |result: InstructionResult, spent: u64| { + let mut gas = gas(allowance, 0); + assert!(gas.record_regular_cost(spent)); + if result.is_halt() { + gas.spend_all(); + } + let mut answer = InterpreterResult::new(result, Bytes::new(), gas); + Detention::restore_forward(&mut answer, withheld); + assert_eq!(answer.gas.limit(), 90_000_000, "{result:?}"); + answer + }; + + let mut answered = answer(InstructionResult::Return, 1_000); + assert_eq!(answered.gas.remaining(), 90_000_000 - 1_000); + assert_eq!(answered.gas.withheld_crossing(), None); + assert_eq!(detention.on_answer(&mut answered, 1, 90_000_000), None); + + let mut failed = answer(InstructionResult::PrecompileError, 0); + assert_eq!(failed.gas.remaining(), 0); + assert_eq!(detention.on_answer(&mut failed, 1, 90_000_000), None); + assert_eq!(detention.burned, 90_000_000, "the forward burns"); + detention.burned = 0; + + let mut out_of_gas = answer(InstructionResult::PrecompileOOG, 0); + let forward = NonZeroU64::new(90_000_000).unwrap(); + assert_eq!( + out_of_gas.gas.withheld_crossing(), + Some(WithheldCrossing::with_remaining(forward)) + ); + assert_eq!( + detention.on_answer(&mut out_of_gas, 1, 90_000_000), + Some(ComputeStop { limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, used: 0 }) + ); + assert_eq!(out_of_gas.gas.remaining(), 90_000_000, "the precompile computed nothing"); + assert_eq!(out_of_gas.gas.withheld_crossing(), None); + assert_eq!(detention.burned, 0, "a crossing burns nothing"); + } + + /// A keyless deployment's call is the transaction's own frame: held to the limit before it + /// charges anything, its charges are compute once its creation runs, and the gas it forwards + /// is not. + #[test] + fn test_a_keyless_call_is_the_transactions_own_frame() { + let mut detention = detaining(); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + let mut call = gas(100_000_000, 0); + detention.on_frame_run(&mut call, 0); + assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + + assert!(call.record_regular_cost(112_000)); + assert!(call.record_withheld_first_cost(50_000_000)); + detention.on_frame_suspend(&call, 0); + let mut creation = gas(50_000_000, 0); + detention.on_frame_run(&mut creation, 1); + assert_eq!(detention.compute(&creation), 112_000, "the charges, not the forward"); + assert_eq!(creation.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000); + assert_eq!(detention.allowance(2, 0), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000)); + } + + /// A frame's own read is committed as an opcode's is: the limit is its compute at the read + /// plus the cap. A transaction detention does not hold records nothing. + #[test] + fn test_a_frames_own_read_sets_the_limit_from_its_compute() { + let mut detention = detaining(); + let mut call = gas(100_000_000, 0); + detention.on_frame_run(&mut call, 0); + assert!(call.record_regular_cost(100_000)); + detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0); + assert_eq!(detention.compute_limit(), Some(100_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); + assert_eq!(detention.accessed(), VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); + + let mut free = Detention::default(); + free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); + free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0); + assert_eq!((free.compute_limit(), free.accessed()), (None, VolatileDataAccess::empty())); + } + + /// The switch holds for the frame that turned it off and every frame below it, turns back on + /// when that frame returns, and cannot be turned back on from below. + #[test] + fn test_the_switch_is_scoped_to_a_subtree() { + let mut detention = detaining(); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.on_frame_suspend(&frame, 0); + let mut child = gas(100_000, 0); + detention.on_frame_run(&mut child, 1); + detention.disable_access(2); + assert!(!detention.is_access_disabled(1)); + detention.disable_access(1); + assert!(!detention.is_refusing(), "the frame reads the switch when it resumes"); + detention.on_frame_run(&mut child, 1); + assert!(detention.is_refusing()); + assert!(!detention.is_access_disabled(0)); + assert!(detention.is_access_disabled(1) && detention.is_access_disabled(2)); + detention.disable_access(2); + assert!(detention.is_access_disabled(1), "a deeper frame keeps the shallower switch"); + assert!(!detention.enable_access(2), "a frame below cannot switch it back on"); + assert!(detention.refuses(VolatileDataAccess::BLOCK_NUMBER)); + detention.name_refusal(VolatileDataAccess::BLOCK_HASH); + assert_eq!(detention.take_refused(), Some(VolatileDataAccess::BLOCK_HASH)); + detention.name_refusal(VolatileDataAccess::BLOCK_HASH); + assert_eq!(detention.take_refused(), None, "nothing refused, nothing named"); + + detention.on_frame_end(InstructionResult::Stop, &mut child, 1); + assert!(!detention.is_access_disabled(1), "on again once the frame returned"); + detention.on_frame_run(&mut frame, 0); + assert!(!detention.is_refusing()); + + detention.disable_access(0); + detention.on_frame_run(&mut frame, 0); + assert!(detention.refuses(VolatileDataAccess::TIMESTAMP)); + assert!(detention.enable_access(0), "the frame that switched it off switches it on"); + detention.on_frame_run(&mut frame, 0); + assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); + } + + /// A refusal's revert data decodes back to the kind it names, for every kind the engine + /// names, the slot number's access type 12 included, which the contract's own ABI type cannot + /// name. + #[test] + fn test_a_refusal_decodes_to_the_kind_it_names() { + use crate::system::{IMegaAccessControl, VolatileDataAccessType, SLOT_NUM_ACCESS_TYPE}; + use alloy_sol_types::SolError; + + for access_type in 0..=SLOT_NUM_ACCESS_TYPE { + let access = VolatileDataAccess::from_access_type(access_type).unwrap(); + let data = volatile_data_access_disabled_revert_data(access); + assert_eq!(data.len(), 36); + assert_eq!(decode_volatile_data_access_disabled(&data), Some(access)); + } + // The enum-typed decoder loses 12 to its placeholder for an undeclared variant, and its + // validating form refuses it: the argument is a `uint8`, and is decoded as one. + let slot_num = volatile_data_access_disabled_revert_data(VolatileDataAccess::SLOT_NUM); + assert_eq!( + IMegaAccessControl::VolatileDataAccessDisabled::abi_decode(&slot_num) + .unwrap() + .accessType, + VolatileDataAccessType::__Invalid, + ); + assert!( + IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&slot_num).is_err() + ); + let oracle = volatile_data_access_disabled_revert_data(VolatileDataAccess::ORACLE); + assert_eq!( + IMegaAccessControl::VolatileDataAccessDisabled::abi_decode_validate(&oracle) + .unwrap() + .accessType, + VolatileDataAccessType::Oracle, + ); + } + + /// Anything else decodes to nothing: another selector, a short or long payload, a word that is + /// not a `uint8`, and an access type past the slot number's. + #[test] + fn test_other_revert_data_decodes_to_nothing() { + let valid = volatile_data_access_disabled_revert_data(VolatileDataAccess::TIMESTAMP); + let mut other_selector = valid.to_vec(); + other_selector[0] ^= 1; + let mut wide = valid.to_vec(); + wide[4] = 1; + let mut wide_low = valid.to_vec(); + wide_low[34] = 1; + let mut past = valid.to_vec(); + past[35] = 13; + let mut long = valid.to_vec(); + long.push(0); + for data in [ + other_selector, + valid[..35].to_vec(), + valid[..4].to_vec(), + valid[..3].to_vec(), + long, + wide, + wide_low, + past, + vec![], + ] { + assert_eq!(decode_volatile_data_access_disabled(&data), None, "{data:?}"); + } + } + + /// A transaction that is not detained records nothing and caps nothing: a system-originated + /// one, and one whose caps are both unlimited. One unlimited cap leaves its kind uncapped. + #[test] + fn test_an_exempt_or_unlimited_transaction_is_not_detained() { + for (detains, block_env_cap, oracle_cap) in [ + (false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS), + (true, u64::MAX, u64::MAX), + ] { + let mut detention = Detention::default(); + detention.reset(detains, block_env_cap, oracle_cap); + assert!(!detention.detains()); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.observe(VolatileDataAccess::TIMESTAMP); + assert!(!detention.has_reads()); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!(detention.compute_limit(), None); + assert_eq!(detention.accessed(), VolatileDataAccess::empty()); + } + + let mut detention = Detention::default(); + detention.reset(true, u64::MAX, 5); + assert!(detention.detains()); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!(detention.compute_limit(), None, "an unlimited cap sets no limit"); + assert_eq!(frame.withheld(), 0); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); + assert_eq!(detention.compute_limit(), Some(5)); + } +} diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index 0a46ba7f8..d02593039 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -1,3 +1,183 @@ -//! Volatile-data access tracking (block environment, beneficiary, oracle) behind gas detention. +//! Gas detention: volatile-data access tracking, and the compute cap a read of volatile data sets. //! -//! Empty until gas detention lands. +//! `MegaETH`'s parallel executor runs transactions side by side and has to redo the ones whose +//! reads another transaction's writes invalidate. Some data changes with every block or every +//! transaction — the block environment, the block beneficiary's account, the Oracle's storage — +//! so a transaction that reads it is likely to be redone, and a long computation after the read +//! is expensive to redo. Detention caps how much a transaction may still compute once it has read +//! such data. +//! +//! # What is volatile +//! +//! | Kind | Read by | Cap | +//! |---|---|---| +//! | the block environment | `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH` | [`block_env_access_compute_gas_limit`](crate::EvmTxRuntimeLimits::block_env_access_compute_gas_limit) | +//! | the block beneficiary's account | `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four calls (and the EIP-7702 delegate they follow), `SELFDESTRUCT` as either end; a transaction whose sender or recipient is the beneficiary or whose recipient delegates to it, an applied EIP-7702 authority that is, and a keyless deployment's signer that is | [`block_env_access_compute_gas_limit`](crate::EvmTxRuntimeLimits::block_env_access_compute_gas_limit) | +//! | the Oracle's storage | `SLOAD` in the Oracle's own frame | [`oracle_access_compute_gas_limit`](crate::EvmTxRuntimeLimits::oracle_access_compute_gas_limit) | +//! +//! The caps are runtime limits ([`EvmTxRuntimeLimits`](crate::EvmTxRuntimeLimits)), fixed per spec +//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)): for Satin +//! [`BLOCK_ENV_ACCESS_COMPUTE_GAS`](crate::constants::BLOCK_ENV_ACCESS_COMPUTE_GAS) and +//! [`ORACLE_ACCESS_COMPUTE_GAS`](crate::constants::ORACLE_ACCESS_COMPUTE_GAS), both below +//! [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a transaction +//! can spend; a tool or a test may set either on an EVM. A cap of `u64::MAX` caps +//! nothing, and a transaction whose caps are both unlimited — under +//! [`no_limits`](crate::EvmTxRuntimeLimits::no_limits), as the execution-spec gate runs — is not +//! detained. `no_limits` turns detention off together with every other per-transaction limit: it is +//! for the gate's equivalence mode and for tests, not for executing the chain. +//! +//! `BLOBHASH` is not on the list: it reads the transaction's own blob hashes, which nothing else +//! decides. A system-originated transaction and a system call are not detained, whatever they +//! read, the block environment included: they are the protocol maintaining its own state, the +//! Oracle's included, and the same rule exempts them from every per-transaction limit. +//! +//! # Where a read is marked +//! +//! Where the Host actually loads the value: its block-environment accessors, its account load +//! (which every account opcode and every call goes through, the EIP-7702 delegate's included), its +//! storage load and its `SELFDESTRUCT`. A load that fails — a cold account the frame cannot pay +//! for, a database error — marks nothing, and neither does an opcode that fails after the load: +//! the Host only observes, and the opcode's wrapper commits the read once the opcode completed, +//! as it does with a write record. +//! +//! # The cap +//! +//! Compute is the regular gas the transaction spends on what it runs, read off revm's `Gas`: state +//! and history gas that spilled onto regular gas are not compute, gas withheld from regular +//! charges is never spent, and what a halting frame burns is not compute either ([`Detention`]). +//! The one burn counted as compute is what a frame has left when an opcode's static gas fails, +//! which no wrapper sees: per halting frame, under the failed charge's price (at most 4,999, on +//! `SELFDESTRUCT`). Burned gas is counted as compute, so the stop comes earlier, never later. +//! A value call's stipend is not compute either: compute is regular gas drawn from the +//! transaction's own pools, and the stipend is gas nobody paid. A callee may run up to 2,300 gas +//! on each value call's stipend, and a warm value call to an empty account counts 6,800 of compute +//! (9,100, less the 2,300 stipend the callee leaves unspent and returns to its caller), so the +//! gas run after a read is at most about 34% (2,300 / 6,800) more than the cap. +//! +//! A read sets a limit: the transaction's compute at the read plus the read's cap. The limit only +//! goes down, so the most restrictive of several reads is the one that binds, whatever their +//! order. +//! +//! # How the cap is enforced +//! +//! The engine has no counter per opcode, and the interpreter stops a frame on one condition only: +//! the frame runs out of regular gas. So the cap is enforced through the frame's gas, with the +//! revm fork's two parts of a frame's regular gas: a spendable part, the only one a regular charge +//! draws, and a withheld part. Every other reader of the frame's gas sees the two together — `GAS`, +//! the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold +//! checks, the gas a child returns, the reimbursement — and a forward or a state or history spill +//! draws the withheld part first. +//! +//! Every frame that runs has its spendable part held at what the limit leaves the transaction +//! (`Gas::limit_spendable`); the rest is withheld. Three points hold this, and between them no +//! frame can compute past the limit (a frame answered without running is held by the rule under +//! the stop below): +//! +//! - **the read**: the opcode that read volatile data holds its own frame once it committed the +//! read, so the instructions after it run on what the cap leaves; +//! - **a frame's start and every resume**: a frame that starts, and a caller a child returned into, +//! is held to what the limit leaves then. A child's read holds its callers as they resume, and +//! the gas a child hands back cannot be computed with past the limit; +//! - **a storage write restored to its original value**: it refills state and history gas that +//! spilled onto regular gas, possibly before the read, onto the spendable part. +//! +//! So a transaction that read volatile data runs exactly as it would without the read until a +//! regular charge needs the withheld part. That charge fails as it would with nothing withheld, +//! and the fork records the crossing, with the regular gas the frame had before the charge. +//! +//! # The stop +//! +//! A frame whose result carries a crossing record crossed the cap, not its own gas: undetained, +//! the withheld part would have paid the charge. The frame is stopped the way every limit stops +//! the frame that crosses it: it reverts alone with `MegaLimitExceeded` (kind: compute), and its +//! caller resumes as after any revert (see [`AdditionalLimit`](crate::AdditionalLimit)). The +//! stopped frame's gas is put back to what it had before the charge that crossed, from the record: +//! the charge is not made, and the spendable part the frame had and the withheld part go back to +//! its caller, and in the end to the sender. The stop reports the transaction's compute at the +//! crossing as what was used, the same figure at every site a crossing is made: a frame that ran, +//! an answer, a precompile; the size of the charge that crossed is not kept. +//! +//! The limit holds without stopping the callers: a caller resumes held to what the limit leaves +//! the transaction, which is less than the charge that crossed, so a regular charge it makes past +//! that crosses again and stops it in turn. A caller that catches the stop and ends within what is +//! left ends the transaction within the limit. +//! +//! Every other out-of-gas halts and burns as it would without the read: an operand above `usize`, +//! a failed state or history charge, and a regular charge the frame's whole gas could not pay. +//! +//! A frame answered without running is held the same way. revm runs a precompile inside the +//! frame's start, against the frame's gas limit, before its answer can be classified, so after a +//! read a precompile forwarded more than the allowance its frame would start with is decided +//! before it runs, from its price where the engine knows it (the `precompiles` module of `evm`): +//! +//! - priced within the allowance, it runs on its whole forward and answers as it would without the +//! read; +//! - priced past the allowance and within the forward, it needs gas the limit withholds: it is +//! answered out of gas without running, the answer is marked as a crossing, and the same rule +//! makes it the stop; +//! - priced past its whole forward, it runs on the forward and runs out of gas, as without the +//! read: a failed call that burns its forward and that its caller survives. +//! +//! One residual is a choice: the price does not tell whether an input passes the checks a +//! precompile makes after its gas check, so an input priced between the allowance and the forward +//! that would fail such a check is the stop, which gives its forward back, where without the read +//! the check fails the call, which burns its forward. Its caller survives either. Running it to +//! find out would compute past the limit. +//! +//! Every entry of the Satin set is priced, op-revm's size-limited wrappers of the BN254 pairing +//! and the BLS12-381 MSMs and pairing included. A precompile the engine cannot price — a node's +//! own, a Satin address a node replaced — is run on the allowance, and its answer gets the rest of +//! the forward back. Within the allowance, it answers as it would without the read. Past it, it +//! answers out of gas without computing, the answer is marked as a crossing, and it is the stop, +//! whether its price is within its forward or not: one priced past its whole forward is the stop +//! too, where without the read it would be a failed call that burns its forward. It also sees the +//! allowance as its gas limit. +//! +//! An interceptor builds its answer on all the gas the caller forwarded, the caller's withheld +//! part included: an answer that spent more regular gas than the allowance the frame would have +//! run on is answered out of gas and marked as a crossing, and the same rule makes it the stop. +//! +//! A keyless deployment's call is the transaction's own frame, and runs no code: it charges its +//! own work — the overhead of decoding and recovering the signer, then the `CREATE` opcode's +//! regular gas — on its frame's gas, held to the limit as any frame's is, so a charge past the +//! limit is a crossing, whether a rule would then refuse the call or its creation would run. A +//! call that starts its creation suspends on it, and its charges are compute as a caller's are; a +//! call carrying value is refused before its frame is built, an answer held by the rule above. +//! The call reads its +//! signer's account through the journal, where the Host marks nothing, so a signer that is the +//! beneficiary is marked there, at the call's compute then: the creation runs for that account, +//! as a `CREATE` runs in a frame of it, which a read of the account started. +//! +//! # Nothing withheld leaks +//! +//! Withheld gas never leaves the frame's tracker, so there is nothing to release and nothing that +//! can escape the cap: a child's withheld part goes back to its caller with the rest of its gas, +//! and the caller is held again as it resumes; a frame answered without running starts with +//! nothing withheld and hands its forwarded gas back; the stop hands the frame's gas back with its +//! revert, both parts as they were before the charge that crossed; and a halt burns the frame's +//! gas, withheld part included, as it would undetained. +//! `return_create`'s deposit and hash charges, the creating frame's own compute, draw the spendable +//! part like any other regular charge. +//! +//! # Refused reads +//! +//! `MegaAccessControl` can switch volatile-data access off for a frame and every frame below it. +//! The Host then refuses the load and the opcode's wrapper reverts the frame with +//! `VolatileDataAccessDisabled(accessType)`. The refusal comes before the load, so a refused read +//! reads nothing and caps nothing, and the frame keeps the gas it had before the opcode: the +//! opcode's static gas is charged, as for any instruction that ran, and nothing else. A refusal +//! names the kind the opcode reads — `BLOCKHASH`'s names the hash, though the opcode loads the +//! block number first — and a `SLOTNUM` refusal names access type 12 +//! ([`SLOT_NUM_ACCESS_TYPE`](crate::system::SLOT_NUM_ACCESS_TYPE)), which the contract's +//! `VolatileDataAccessType` does not declare. The error's argument is encoded as a `uint8`, and +//! Solidity handlers must decode it as `uint8`: Solidity's ABI decoder reverts on an enum value +//! out of range. [`decode_volatile_data_access_disabled`] is the Rust side's decoder. + +mod detention; +mod volatile; + +pub(crate) use detention::ComputeStop; +pub use detention::{ + decode_volatile_data_access_disabled, volatile_data_access_disabled_revert_data, Detention, +}; +pub use volatile::VolatileDataAccess; diff --git a/crates/mega-evm/src/access/volatile.rs b/crates/mega-evm/src/access/volatile.rs new file mode 100644 index 000000000..a91cd4cea --- /dev/null +++ b/crates/mega-evm/src/access/volatile.rs @@ -0,0 +1,265 @@ +//! The kinds of volatile data a transaction can read. + +use core::ops::{BitOr, BitOrAssign}; + +use crate::system::{VolatileDataAccessType, SLOT_NUM_ACCESS_TYPE}; + +/// A set of the kinds of volatile data a transaction read. +/// +/// One bit per kind. A bit's position is the discriminant of the kind in `MegaAccessControl`'s +/// `VolatileDataAccessType`, which is how a refused read names what it refused: bits 0 to 9 are +/// block-environment fields, bit 10 the block beneficiary's account and bit 11 the Oracle's +/// storage. Bit 12 is the block's slot number, which the contract's enum does not declare +/// ([`SLOT_NUM_ACCESS_TYPE`]). +/// +/// Bits 3 (`Difficulty`) and 9 (`BlobHash`) keep their positions but no read sets them, so they +/// have no constant: Satin's base spec answers `DIFFICULTY` with the randomness +/// ([`PREV_RANDAO`](Self::PREV_RANDAO)), and `BLOBHASH` reads the transaction's own blob hashes, +/// which nothing but the transaction decides. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct VolatileDataAccess(u16); + +impl VolatileDataAccess { + /// The block number (`NUMBER`, and the `BLOCKHASH` that compares against it). + pub const BLOCK_NUMBER: Self = Self(1); + /// The block timestamp (`TIMESTAMP`). + pub const TIMESTAMP: Self = Self(1 << 1); + /// The block beneficiary's address (`COINBASE`). + pub const COINBASE: Self = Self(1 << 2); + /// The block gas limit (`GASLIMIT`). + pub const GAS_LIMIT: Self = Self(1 << 4); + /// The base fee (`BASEFEE`). + pub const BASE_FEE: Self = Self(1 << 5); + /// The previous block's randomness (`PREVRANDAO`). + pub const PREV_RANDAO: Self = Self(1 << 6); + /// A block hash (`BLOCKHASH`). + pub const BLOCK_HASH: Self = Self(1 << 7); + /// The blob base fee (`BLOBBASEFEE`). + pub const BLOB_BASE_FEE: Self = Self(1 << 8); + /// The block beneficiary's account: its balance, code or code hash. + pub const BENEFICIARY_BALANCE: Self = Self(1 << 10); + /// The Oracle contract's storage. + pub const ORACLE: Self = Self(1 << 11); + /// The block's slot number (`SLOTNUM`), at [`SLOT_NUM_ACCESS_TYPE`]. + pub const SLOT_NUM: Self = Self(1 << SLOT_NUM_ACCESS_TYPE); + + /// The block-environment kinds: bits 0 to 9, and the slot number. + const BLOCK_ENV_MASK: u16 = 0b0001_0011_1111_1111; + + /// No kind at all. + pub const fn empty() -> Self { + Self(0) + } + + /// Whether no kind is in the set. + pub const fn is_empty(self) -> bool { + self.0 == 0 + } + + /// The bits of the set. + pub const fn bits(self) -> u16 { + self.0 + } + + /// Whether every kind in `other` is in the set. + pub const fn contains(self, other: Self) -> bool { + self.0 & other.0 == other.0 + } + + /// Adds the kinds of `other`. + pub const fn insert(&mut self, other: Self) { + self.0 |= other.0; + } + + /// Whether the set holds a block-environment kind. + pub const fn has_block_env_access(self) -> bool { + self.0 & Self::BLOCK_ENV_MASK != 0 + } + + /// Whether the set holds the beneficiary's account. + pub const fn has_beneficiary_balance_access(self) -> bool { + self.contains(Self::BENEFICIARY_BALANCE) + } + + /// Whether the set holds the Oracle's storage. + pub const fn has_oracle_access(self) -> bool { + self.contains(Self::ORACLE) + } + + /// How many block-environment kinds the set holds. + pub const fn count_block_env_accessed(self) -> usize { + (self.0 & Self::BLOCK_ENV_MASK).count_ones() as usize + } + + /// The kind a refusal names with `access_type`: its discriminant in `VolatileDataAccessType`, + /// or [`SLOT_NUM_ACCESS_TYPE`] for the slot number. `None` for any other value. + pub const fn from_access_type(access_type: u8) -> Option { + if access_type > SLOT_NUM_ACCESS_TYPE { + return None; + } + Some(Self(1 << access_type)) + } + + /// The position of the set's lowest bit, which for a single kind is its discriminant in + /// `VolatileDataAccessType`, or the slot number's 12. + /// + /// # Panics + /// + /// In a debug build, when the set is empty. + pub const fn as_u8(self) -> u8 { + debug_assert!(!self.is_empty(), "an empty set names no kind"); + self.0.trailing_zeros() as u8 + } +} + +impl BitOr for VolatileDataAccess { + type Output = Self; + + fn bitor(self, rhs: Self) -> Self { + Self(self.0 | rhs.0) + } +} + +impl BitOrAssign for VolatileDataAccess { + fn bitor_assign(&mut self, rhs: Self) { + self.0 |= rhs.0; + } +} + +impl From for VolatileDataAccess { + fn from(ty: VolatileDataAccessType) -> Self { + Self(1_u16.checked_shl(ty as u32).unwrap_or(0)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_empty_access_has_no_flags() { + let access = VolatileDataAccess::empty(); + + assert!(access.is_empty()); + assert!(!access.has_block_env_access()); + assert!(!access.has_beneficiary_balance_access()); + assert!(!access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 0); + assert_eq!(access.bits(), 0); + } + + #[test] + fn test_block_env_helpers_ignore_non_block_flags() { + let access = VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::BLOCK_HASH | + VolatileDataAccess::BENEFICIARY_BALANCE | + VolatileDataAccess::ORACLE; + + assert!(!access.is_empty()); + assert!(access.has_block_env_access()); + assert!(access.has_beneficiary_balance_access()); + assert!(access.has_oracle_access()); + assert_eq!(access.count_block_env_accessed(), 2); + + let beneficiary_and_oracle = + VolatileDataAccess::BENEFICIARY_BALANCE | VolatileDataAccess::ORACLE; + assert!(!beneficiary_and_oracle.has_block_env_access()); + assert!(!VolatileDataAccess::ORACLE.has_beneficiary_balance_access()); + assert!(!VolatileDataAccess::BENEFICIARY_BALANCE.has_oracle_access()); + } + + /// Every variant maps to the bit at its discriminant, and every kind a read sets is the + /// variant's constant; `Difficulty` and `BlobHash`, which no read sets, have none. + #[test] + fn test_from_volatile_data_access_type_covers_all_variants() { + let expected: &[(VolatileDataAccessType, Option)] = &[ + (VolatileDataAccessType::BlockNumber, Some(VolatileDataAccess::BLOCK_NUMBER)), + (VolatileDataAccessType::Timestamp, Some(VolatileDataAccess::TIMESTAMP)), + (VolatileDataAccessType::Coinbase, Some(VolatileDataAccess::COINBASE)), + (VolatileDataAccessType::Difficulty, None), + (VolatileDataAccessType::GasLimit, Some(VolatileDataAccess::GAS_LIMIT)), + (VolatileDataAccessType::BaseFee, Some(VolatileDataAccess::BASE_FEE)), + (VolatileDataAccessType::PrevRandao, Some(VolatileDataAccess::PREV_RANDAO)), + (VolatileDataAccessType::BlockHash, Some(VolatileDataAccess::BLOCK_HASH)), + (VolatileDataAccessType::BlobBaseFee, Some(VolatileDataAccess::BLOB_BASE_FEE)), + (VolatileDataAccessType::BlobHash, None), + (VolatileDataAccessType::Beneficiary, Some(VolatileDataAccess::BENEFICIARY_BALANCE)), + (VolatileDataAccessType::Oracle, Some(VolatileDataAccess::ORACLE)), + ]; + + for &(access_type, expected_flag) in expected { + let converted = VolatileDataAccess::from(access_type); + assert_eq!(converted.bits(), 1 << (access_type as u8)); + assert_eq!(converted.as_u8(), access_type as u8); + if let Some(expected_flag) = expected_flag { + assert_eq!(converted, expected_flag); + } + } + // The slot number has no variant of its own: its bit is the one after the enum's. + assert_eq!(VolatileDataAccess::SLOT_NUM.as_u8(), 12); + assert_eq!(SLOT_NUM_ACCESS_TYPE, VolatileDataAccessType::Oracle as u8 + 1); + } + + /// Every access type the engine names maps back to its kind, the slot number's 12 included, + /// and nothing past it does. + #[test] + fn test_from_access_type_maps_every_kind_and_nothing_else() { + for access_type in 0..=SLOT_NUM_ACCESS_TYPE { + let access = VolatileDataAccess::from_access_type(access_type).unwrap(); + assert_eq!(access.as_u8(), access_type); + assert_eq!(access.bits().count_ones(), 1); + } + assert_eq!( + VolatileDataAccess::from_access_type(SLOT_NUM_ACCESS_TYPE), + Some(VolatileDataAccess::SLOT_NUM) + ); + for access_type in [SLOT_NUM_ACCESS_TYPE + 1, 15, 16, u8::MAX] { + assert_eq!(VolatileDataAccess::from_access_type(access_type), None, "{access_type}"); + } + } + + /// Every block-environment kind, the slot number included, counts as one; the beneficiary + /// and the Oracle are not the block environment. + #[test] + fn test_all_block_env_flags_counted_correctly() { + let all_block_env = VolatileDataAccess::BLOCK_NUMBER | + VolatileDataAccess::TIMESTAMP | + VolatileDataAccess::COINBASE | + VolatileDataAccess::GAS_LIMIT | + VolatileDataAccess::BASE_FEE | + VolatileDataAccess::PREV_RANDAO | + VolatileDataAccess::BLOCK_HASH | + VolatileDataAccess::BLOB_BASE_FEE | + VolatileDataAccess::SLOT_NUM; + + assert_eq!(all_block_env.count_block_env_accessed(), 9); + assert!(all_block_env.has_block_env_access()); + assert!(!all_block_env.has_beneficiary_balance_access()); + assert!(!all_block_env.has_oracle_access()); + } + + /// A union keeps a kind both sides hold: it is a union, not a difference. + #[test] + fn test_a_union_keeps_what_both_sides_hold() { + let both = VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE; + assert_eq!(both | VolatileDataAccess::TIMESTAMP, both); + let mut assigned = both; + assigned |= VolatileDataAccess::ORACLE; + assert_eq!(assigned, both); + let mut inserted = both; + inserted.insert(both); + assert_eq!(inserted, both); + } + + /// Inserting is a union, and `contains` asks for every bit of its argument. + #[test] + fn test_insert_and_contains() { + let mut access = VolatileDataAccess::empty(); + access.insert(VolatileDataAccess::TIMESTAMP); + access |= VolatileDataAccess::ORACLE; + assert!(access.contains(VolatileDataAccess::TIMESTAMP)); + assert!(access.contains(VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE)); + assert!(!access.contains(VolatileDataAccess::TIMESTAMP | VolatileDataAccess::COINBASE)); + assert!(access.contains(VolatileDataAccess::empty())); + } +} diff --git a/crates/mega-evm/src/block/chain.rs b/crates/mega-evm/src/block/chain.rs index ed3add095..0aac49600 100644 --- a/crates/mega-evm/src/block/chain.rs +++ b/crates/mega-evm/src/block/chain.rs @@ -2,13 +2,14 @@ //! //! This is the single place that records when each [`MegaHardfork`] activates on the known //! `MegaETH` chains. The node chainspecs decide the schedule; this table mirrors it for tools -//! that replay a real chain, and [`hardfork_schedule`] turns a chain ID into the schedule block -//! execution reads. +//! that replay a real chain, and [`hardfork_schedule`] turns a known chain's ID into the schedule +//! block execution reads. A chain this table does not know has no schedule here: Satin runs on a +//! chain that ran the legacy forks, and whoever runs another names its schedule. use alloy_hardforks::ForkCondition; use alloy_primitives::BlockTimestamp; -use crate::{MegaHardfork, MegaHardforkConfig, MegaSpecId}; +use crate::{MegaHardfork, MegaHardforkConfig}; /// `MegaETH` mainnet chain ID. pub const MAINNET_CHAIN_ID: u64 = 4326; @@ -16,14 +17,6 @@ pub const MAINNET_CHAIN_ID: u64 = 4326; /// `MegaETH` testnet v2 chain ID. pub const TESTNET_CHAIN_ID: u64 = 6343; -/// The rung an unknown chain runs, from genesis. -/// -/// Pinned, not taken from [`MegaSpecId::default`]: an unknown chain runs this spec from block -/// zero with no fork boundary, so introducing a spec must leave it alone — registering a fork -/// above the pin would rewrite what history such a chain has already produced means. Raising the -/// pin is a decision of its own, made by editing this constant. -pub const FALLBACK_RUNG: MegaSpecId = MegaSpecId::SATIN; - /// Activation timestamps of the Satin-engine hardforks on one chain. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ChainActivation { @@ -76,29 +69,15 @@ pub fn testnet_hardforks() -> MegaHardforkConfig { chain_activation(TESTNET_CHAIN_ID).expect("testnet is in the activation table").hardforks() } -/// The schedule an unknown chain runs: every fork up to [`FALLBACK_RUNG`], active at genesis. -pub fn all_activated_hardforks() -> MegaHardforkConfig { - let mut config = MegaHardforkConfig::new(); - for fork in MegaHardfork::VARIANTS { - let condition = if fork.spec_id() <= FALLBACK_RUNG { - ForkCondition::Timestamp(0) - } else { - ForkCondition::Never - }; - config.insert(*fork, condition); - } - config -} - -/// The hardfork schedule of `chain_id`: a known chain's table, or the unknown-chain fallback. -pub fn hardfork_schedule(chain_id: u64) -> MegaHardforkConfig { - chain_activation(chain_id).map_or_else(all_activated_hardforks, |a| a.hardforks()) +/// The hardfork schedule of `chain_id`, a known chain's table; `None` for any other chain. +pub fn hardfork_schedule(chain_id: u64) -> Option { + chain_activation(chain_id).map(|activation| activation.hardforks()) } #[cfg(test)] mod tests { use super::*; - use crate::MegaHardforks; + use crate::{MegaHardforks, MegaSpecId}; #[test] fn test_known_chains_have_satin_unscheduled() { @@ -141,50 +120,18 @@ mod tests { assert_eq!(hf.validate_schedule(), Ok(())); } + /// A known chain's schedule is its table's; another chain has none: the engine names no + /// schedule for a chain it does not know. #[test] fn test_schedule_dispatch_by_chain_id() { - assert_eq!(hardfork_schedule(MAINNET_CHAIN_ID).spec_id(0), None); - assert_eq!(hardfork_schedule(TESTNET_CHAIN_ID).spec_id(0), None); - // Unknown chain: every fork up to the pinned rung, active at genesis. - assert_eq!(hardfork_schedule(1).spec_id(0), Some(FALLBACK_RUNG)); - } - - /// The fallback schedule is one a chain can run: it needs no parameters that are not there, - /// so an unknown chain ID starts rather than failing at its first block. - #[test] - fn test_unknown_chain_fallback_is_a_runnable_schedule() { - let hf = hardfork_schedule(999_999); - - assert_eq!(hf.spec_id(0), Some(FALLBACK_RUNG)); - assert_eq!(hf.validate_schedule(), Ok(())); - } - - /// The fallback rung is pinned, not inherited from [`MegaSpecId::default`]. - /// - /// Unknown chains run their rung from genesis, so it is their semantics from block zero with - /// no fork boundary. Introducing a spec must therefore leave them alone. What this pins is - /// drift: the fallback silently following `MegaSpecId::default` again, and the rung advancing - /// without [`FALLBACK_RUNG`] being edited in the same change. - #[test] - fn test_unknown_chain_fallback_pins_its_rung() { - let hf = all_activated_hardforks(); - const RUNG: MegaSpecId = MegaSpecId::SATIN; - - assert_eq!(FALLBACK_RUNG, RUNG, "the pin moves only by editing it here too"); - assert_eq!(hf.spec_id(0), Some(RUNG), "the rung applies from genesis"); - assert_eq!( - hf.spec_id(u64::MAX), - Some(RUNG), - "and is terminal — no later fork is registered" - ); - - for fork in MegaHardfork::VARIANTS { - let registered = hf.mega_fork_activation(*fork) != ForkCondition::Never; - assert_eq!( - registered, - fork.spec_id() <= RUNG, - "{fork:?} registration must follow the pinned rung, not MegaSpecId::default()" - ); + for activation in CHAIN_ACTIVATIONS { + let schedule = hardfork_schedule(activation.chain_id).expect("a known chain"); + for fork in MegaHardfork::VARIANTS { + assert_eq!(schedule.get(*fork), Some(&activation.condition(*fork))); + } + } + for chain_id in [0, 1, 6342, 999_999] { + assert!(hardfork_schedule(chain_id).is_none(), "chain {chain_id} is unknown"); } } } diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 8b3a2ef09..54531548f 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -1,74 +1,167 @@ -//! The pre-block and post-block calls a block makes before and after its transactions. +//! The pre-block calls a block makes before its transactions. //! -//! Each helper runs the call and hands back the state it produced; none of them commits. A -//! node's witness generator needs to see the read and write set of every step of block -//! execution, and a helper that committed straight to the database would hide its own. +//! Each helper runs the call and hands back the state it produced; none of them commits. The block +//! executor commits each pre-block step's state on its own, in the order the steps run, and that +//! sequence of committed states, read and write sets whole, is what a node's witness generator +//! collects through a commit hook on the block's state. +//! +//! A pre-block call is a system call on [`pre_block_call_gas_limit`], and a block whose +//! pre-block call does not succeed is refused: the state the protocol maintains before the +//! block's transactions is not optional, and a block that could not write it is not one the +//! chain can build on. A database error the database calls fatal is not a verdict on the block: +//! it is an internal error. Every pre-block call runs through [`transact_pre_block_call`], which +//! holds that rule for all of them. +//! +//! The executor's own reads of the block's state outside a call (the activation block's check of +//! the predeploys, the registry's due check, the L1 block info, a sender's account) follow the +//! convention of `alloy-op-evm`'s executor for its reads: any database error is an internal error, +//! fatal or not. #[cfg(not(feature = "std"))] use alloc as std; -use std::{boxed::Box, string::ToString}; +use std::{ + boxed::Box, + format, + string::{String, ToString}, +}; use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; -use alloy_evm::{ - block::{BlockExecutionError, BlockValidationError}, - Evm, -}; +use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use alloy_hardforks::EthereumHardforks; -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, Bytes, B256}; +use op_revm::OpHaltReason; use revm::{ - context::{result::ResultAndState, Block}, - database::State, - state::{Account, EvmState}, - Database, + context::{ + result::{EVMError, ResultAndState}, + Block, ContextTr, DBErrorMarker, + }, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, }; +use crate::{ExternalEnvTypes, MegaEvm}; + /// The caller every pre-block system call runs as. pub use alloy_eips::eip4788::SYSTEM_ADDRESS; +/// The gas limit of every pre-block system call in a block whose gas limit is `block_gas_limit`: +/// the block's gas limit, and never less than 30,000,000. +/// +/// It is the legacy engine's budget, kept as it was rather than replaced by a number nobody +/// chose. The legacy engine sized it to absorb the storage gas a crowded SALT bucket multiplies, +/// which could take a pre-block write past revm's 30M default. On Satin neither half of that +/// holds: a system call prices its state at the minimum bucket, and it runs on at most +/// 30,000,000 of regular gas, the rest of its gas limit being its state-gas reservoir. So what +/// this budget adds above 30M is reservoir, which the call's writes draw first and which nobody +/// pays for when they do not, and the regular budget is 30M whatever the block. In a block whose +/// gas limit is 30M or less the call has no reservoir, and its writes are paid out of the +/// regular budget, which holds them many times over. +pub fn pre_block_call_gas_limit(block_gas_limit: u64) -> u64 { + block_gas_limit.max(SYSTEM_CALL_REGULAR_GAS_LIMIT) +} + +/// Runs the pre-block call `name`: a system call from [`SYSTEM_ADDRESS`] to `target` with `data`, +/// on the pre-block budget of the block `evm` is set up for ([`pre_block_call_gas_limit`]). +/// Answers its result and state; nothing is committed. +/// +/// One rule holds for every pre-block call, and it is the rule alloy-evm's block executor holds a +/// transaction's database error to ([`BlockExecutionError::evm`]): +/// +/// - a database error the database calls fatal ([`DBErrorMarker::is_fatal`]) is an internal error +/// ([`BlockExecutionError::other`]): a read the database could not serve says nothing about the +/// block, and a node must not refuse a valid block because its storage failed; +/// - any other failure refuses the block with the call's own error, which `refused` builds from a +/// message: a database error that is not fatal, an EVM error other than the database's, and an +/// outcome that is not a success, whether the call reverted or halted. Under revm's `State` the +/// one database error that is not fatal is an EIP-7928 block access list that does not cover a +/// read, which is a verdict on the block. +pub(crate) fn transact_pre_block_call( + evm: &mut MegaEvm, + name: &str, + target: Address, + data: Bytes, + refused: impl FnOnce(String) -> BlockExecutionError, +) -> Result, BlockExecutionError> +where + DB: alloy_evm::Database, + ExtEnvs: ExternalEnvTypes, +{ + let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit()); + let outcome = + match evm.transact_system_call_with_gas_limit(SYSTEM_ADDRESS, target, data, gas_limit) { + Ok(outcome) => outcome, + Err(EVMError::Database(error)) if error.is_fatal() => { + return Err(BlockExecutionError::other(error)) + } + Err(error) => return Err(refused(error.to_string())), + }; + if !outcome.result.is_success() { + let message = format!("the {name} pre-block call did not succeed: {:?}", outcome.result); + return Err(refused(message)); + } + Ok(outcome) +} + /// Runs the pre-block call to the [EIP-2935] block hashes contract. /// /// Answers `None`, having run nothing, when Prague is not active or the block is the genesis -/// block, where EIP-2935 makes no call. The state is not committed. +/// block, where EIP-2935 makes no call. A call that does not succeed refuses the block with +/// [`BlockValidationError::BlockHashContractCall`], and its state is handed to nobody; a fatal +/// database error is an internal error, as for every pre-block call. The state is not committed. /// /// [EIP-2935]: https://eips.ethereum.org/EIPS/eip-2935 -pub fn transact_blockhashes_contract_call( +pub fn transact_blockhashes_contract_call( hardforks: H, parent_block_hash: B256, - evm: &mut E, -) -> Result>, BlockExecutionError> { - if !hardforks.is_prague_active_at_timestamp(evm.block().timestamp().saturating_to()) { + evm: &mut MegaEvm, +) -> Result>, BlockExecutionError> +where + H: EthereumHardforks, + DB: alloy_evm::Database, + ExtEnvs: ExternalEnvTypes, +{ + let block = evm.ctx().block(); + if !hardforks.is_prague_active_at_timestamp(block.timestamp().saturating_to()) { return Ok(None); } // The genesis block has no parent to record. - if evm.block().number().is_zero() { + if block.number().is_zero() { return Ok(None); } - evm.transact_system_call(SYSTEM_ADDRESS, HISTORY_STORAGE_ADDRESS, parent_block_hash.0.into()) - .map(Some) - .map_err(|e| BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) + let refused = |message| BlockValidationError::BlockHashContractCall { message }.into(); + let data = parent_block_hash.0.into(); + transact_pre_block_call(evm, "EIP-2935", HISTORY_STORAGE_ADDRESS, data, refused).map(Some) } /// Runs the pre-block call to the [EIP-4788] beacon block root contract. /// /// Answers `None`, having run nothing, when Cancun is not active or the block is the genesis -/// block, where EIP-4788 makes no call and requires a zero root. The state is not committed. +/// block, where EIP-4788 makes no call and requires a zero root. A call that does not succeed +/// refuses the block with [`BlockValidationError::BeaconRootContractCall`], and its state is +/// handed to nobody; a fatal database error is an internal error, as for every pre-block call. +/// The state is not committed. /// /// [EIP-4788]: https://eips.ethereum.org/EIPS/eip-4788 -pub fn transact_beacon_root_contract_call( +pub fn transact_beacon_root_contract_call( hardforks: H, parent_beacon_block_root: Option, - evm: &mut E, -) -> Result>, BlockExecutionError> { - if !hardforks.is_cancun_active_at_timestamp(evm.block().timestamp().saturating_to()) { + evm: &mut MegaEvm, +) -> Result>, BlockExecutionError> +where + H: EthereumHardforks, + DB: alloy_evm::Database, + ExtEnvs: ExternalEnvTypes, +{ + let block = evm.ctx().block(); + if !hardforks.is_cancun_active_at_timestamp(block.timestamp().saturating_to()) { return Ok(None); } let parent_beacon_block_root = parent_beacon_block_root.ok_or(BlockValidationError::MissingParentBeaconBlockRoot)?; - if evm.block().number().is_zero() { + if block.number().is_zero() { if !parent_beacon_block_root.is_zero() { return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { parent_beacon_block_root, @@ -78,133 +171,106 @@ pub fn transact_beacon_root_contract_call( return Ok(None); } - evm.transact_system_call( - SYSTEM_ADDRESS, - BEACON_ROOTS_ADDRESS, - parent_beacon_block_root.0.into(), - ) - .map(Some) - .map_err(|e| { + let refused = |message| { BlockValidationError::BeaconRootContractCall { parent_beacon_block_root: Box::new(parent_beacon_block_root), - message: e.to_string(), + message, } .into() - }) + }; + let data = parent_beacon_block_root.0.into(); + transact_pre_block_call(evm, "EIP-4788", BEACON_ROOTS_ADDRESS, data, refused).map(Some) } -/// The state that applying `balances` to `db` would produce. Nothing is committed. -/// -/// Equivalent to revm's own `increment_balances`, in state rather than in place: committing what -/// this returns leaves the same accounts, balances and account statuses behind, and a witness -/// generator gets to see the delta in between. -pub fn transact_balance_increments( - balances: impl IntoIterator, - db: &mut State, -) -> Result, DB::Error> { - let mut state = EvmState::default(); - - for (address, balance_increment) in balances { - if balance_increment == 0 { - continue; +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + test_utils::{ErrorInjectingDatabase, InjectedDbError, MemoryDatabase}, + MegaContext, MegaSpecId, + }; + use alloy_primitives::{address, U256}; + use revm::{ + context::BlockEnv, + state::{AccountInfo, Bytecode}, + Database, + }; + + /// A database error that says it is not fatal, as a block access list that does not cover a + /// read does. + #[derive(Debug)] + struct NotFatal(InjectedDbError); + + impl core::fmt::Display for NotFatal { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) } - let cache_account = db.load_cache_account(address)?; - let account_info = cache_account.account_info().unwrap_or_default(); - let mut account = Account::default().with_info(account_info); - account.info.balance += U256::from(balance_increment); - account.mark_touch(); - state.insert(address, account); } - Ok(Some(state)) -} + impl core::error::Error for NotFatal {} -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, DatabaseCommit}; - use std::vec; + impl DBErrorMarker for NotFatal { + fn is_fatal(&self) -> bool { + false + } + } - #[test] - fn test_balance_increment_commit_equivalence() { - // The property that matters: this is equivalent to revm's `increment_balances`, which - // the block executor would otherwise call in place. - - let addr1 = address!("0x1000000000000000000000000000000000000001"); - let addr2 = address!("0x2000000000000000000000000000000000000002"); - let addr3 = address!("0x3000000000000000000000000000000000000003"); - - // Fund only addr1 and addr2, but leave addr3 empty (non-existent) - let setup_db = |db: &mut InMemoryDB| { - for (addr, balance, nonce) in [(addr1, 1000u64, 5u64), (addr2, 2000u64, 10u64)] { - db.insert_account_info( - addr, - AccountInfo { balance: U256::from(balance), nonce, ..Default::default() }, - ); - } - }; + /// An [`ErrorInjectingDatabase`] whose errors are not fatal. + #[derive(Debug)] + struct NotFatalDb(ErrorInjectingDatabase); - let mut db1 = InMemoryDB::default(); - setup_db(&mut db1); - let mut state1 = State::builder().with_database(&mut db1).build(); - - let mut db2 = InMemoryDB::default(); - setup_db(&mut db2); - let mut state2 = State::builder().with_database(&mut db2).build(); - - let balance_increments = vec![(addr1, 100u128), (addr2, 200u128), (addr3, 300u128)]; - - // In place, as revm does it. - revm::database_interface::DatabaseCommitExt::increment_balances( - &mut state1, - balance_increments.clone(), - ) - .expect("increment_balances should succeed"); - - // As state, then committed: the commit is what applies the status transitions, so the - // two paths must land on the same accounts. - let result_state = transact_balance_increments(balance_increments.clone(), &mut state2) - .expect("transact_balance_increments should succeed") - .expect("Should return state"); - state2.commit(result_state); - - for (addr, _expected_increment) in balance_increments { - let account1 = state1.load_cache_account(addr).expect("Should load from state1"); - let account2 = state2.load_cache_account(addr).expect("Should load from state2"); - - let info1 = account1.account_info().expect("Should have account info"); - let info2 = account2.account_info().expect("Should have account info"); - - assert_eq!( - info1.balance, info2.balance, - "Balance for {addr:?} should be identical after both methods" - ); - assert_eq!(info1.nonce, info2.nonce, "Nonce for {addr:?} should be identical"); - assert_eq!( - info1.code_hash, info2.code_hash, - "Code hash for {addr:?} should be identical" - ); - assert_eq!( - account1.status, account2.status, - "Account status for {addr:?} should be identical after both methods" - ); + impl Database for NotFatalDb { + type Error = NotFatal; + + fn basic(&mut self, address: Address) -> Result, NotFatal> { + self.0.basic(address).map_err(NotFatal) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + self.0.code_by_hash(code_hash).map_err(NotFatal) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + self.0.storage(address, index).map_err(NotFatal) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.0.block_hash(number).map_err(NotFatal) } } - /// A zero increment is not a touch: it leaves no account in the state at all. + /// A pre-block call's database error is an internal error only when the database calls it + /// fatal; one it does not refuses the block with the call's own error, as a transaction's + /// does. #[test] - fn test_zero_increments_leave_no_account_behind() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let produced = transact_balance_increments( - [(address!("0x1000000000000000000000000000000000000001"), 0u128)], - &mut state, - ) - .expect("no database error") - .expect("Should return state"); - - assert!(produced.is_empty()); + fn test_a_database_error_is_internal_only_when_it_is_fatal() { + let unreadable = address!("0x7000000000000000000000000000000000000007"); + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + db.fail_on_account = Some(unreadable); + let block = + BlockEnv { number: U256::from(1_000), gas_limit: 30_000_000, ..Default::default() }; + let refused = |message| BlockValidationError::BlockHashContractCall { message }.into(); + + let mut fatal = db.clone(); + let mut evm = + MegaEvm::new(MegaContext::new(&mut fatal, MegaSpecId::SATIN).with_block(block.clone())); + let err = transact_pre_block_call(&mut evm, "test", unreadable, Bytes::new(), refused) + .expect_err("the read fails"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + + let mut not_fatal = NotFatalDb(db); + let mut evm = + MegaEvm::new(MegaContext::new(&mut not_fatal, MegaSpecId::SATIN).with_block(block)); + let err = transact_pre_block_call(&mut evm, "test", unreadable, Bytes::new(), refused) + .expect_err("the read fails"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { + message + }) if message.contains("injected basic() error") + ), + "{err:?}" + ); } } diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 40f887fa8..39ae6ab14 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -4,6 +4,14 @@ //! transactions, holds them to the block's limits, builds their receipts and counts what the //! block spent on each of the three gas ledgers. //! +//! # Where the limits come from +//! +//! The executor reads the limits every node must agree on from [`ProtocolLimits::for_spec`], for +//! the spec the EVM executes, installs their per-transaction half on the EVM before every +//! transaction, and holds the block to their data-size budget. A node passes none of them. The +//! node's context adds only the builder's policy ([`BlockLimits`]), which can tighten the budget +//! and never loosen it; a validator leaves it at its default. +//! //! # The block rules of the Karst base //! //! - **An activation block admits only deposits.** The caller sets @@ -34,15 +42,68 @@ //! is the compile-time proof that an inspector observes and writes nothing back; the generic route //! is the checked one. //! -//! # What later mechanisms fill in +//! # Committing an outcome +//! +//! alloy-evm's [`commit_transaction`](BlockExecutor::commit_transaction) cannot fail. Its contract +//! is that a caller commits an outcome before it executes the next transaction, so the block's +//! counters have not moved since the outcome was checked against them. A builder that executes +//! several candidates and chooses among them commits through +//! [`commit_transaction_outcome`](MegaBlockExecutor::commit_transaction_outcome), which checks the +//! counters again and refuses an outcome the block no longer has room for. The trait's commit +//! cannot refuse, and must not accept such an outcome silently either: a debug build makes the +//! same check there and panics. +//! +//! The checked commit also holds an outcome to the state its sender had when it executed: one +//! whose sender's nonce or balance another commit moved since is refused +//! ([`MegaBlockExecutionError::StaleOutcome`]), and the trait's commit asserts the same in a debug +//! build. Any other state the candidate read is not checked: a candidate executed before another +//! commit changed it is the builder's to execute again. +//! +//! # The witness is what the block commits +//! +//! Each pre-block step — the EIP-2935 call, the EIP-4788 call, the activation block's read of each +//! predeploy, the read of the `SequencerRegistry`'s pending changes, the `applyPendingChanges()` +//! call and the read of the L1 block info the block's transactions are priced against — produces an +//! [`EvmState`], and this executor commits each one on its own, in that order, before the first +//! transaction; every committed transaction's returned state follows. A read is a read-only entry +//! of its step's state: an account neither touched nor created, its slots unchanged. The sequence +//! of committed states, with the exported block hashes and buckets, is the witness a stateless +//! client needs. A node takes it with a commit hook on revm's `State` (`State::set_state_hook`), +//! which `commit` hands every state whole, before the cache drops the accounts the state did not +//! touch. The block's transitions and bundle keep only what a state changed, so a witness taken +//! from them would miss the read-only entries — the activation block's predeploys, the registry's +//! pending slots, the L1 block info. +//! +//! The L1 block info is read here because nothing else puts it in a state: op-revm prices the +//! block's first non-deposit transaction against the L1 block contract's slots read on the +//! database itself, and this executor reads the DA footprint gas scalar the same way before every +//! non-deposit transaction, so neither read lands in a transaction's returned state. The +//! pre-block entry carries the account and every slot either read can reach, as the chain held +//! them before the block ([`read_l1_block_info`]) — the L1 fee overhead among them, which +//! op-revm reads only when the scalars the block's deposits left are empty; the block's own L1 +//! attributes deposit, when it has one, carries the values it writes over them in its own +//! returned state. +//! +//! # The pre-block system calls +//! +//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) makes the EIP-2935 +//! and EIP-4788 calls, in the block in which Satin activates checks that the system contracts and +//! the EIP-7997 factory hold the code Satin expects, then applies a role change the +//! `SequencerRegistry` has due in this block. Every call is a system call +//! on the pre-block budget ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)), and +//! one that does not succeed refuses the block. //! -//! [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) names two hook -//! points that are empty today: system contract deployment, and the pre-block system calls. +//! The pre-block step does not read the live system address, but it is what leaves the registry +//! naming this block's address. The executor reads the address off the block's state before every +//! non-deposit transaction, to decide before the transaction runs whether it is a Mega System +//! Transaction, which the data-size budget and the builder's policy do not refuse. Every +//! transaction, a deposit included, then reads the same slot into its own journal when it is +//! validated. #[cfg(not(feature = "std"))] use alloc as std; use core::fmt; -use std::{boxed::Box, collections::BTreeMap, vec::Vec}; +use std::{boxed::Box, collections::BTreeMap, string::String, vec::Vec}; use alloy_consensus::{Eip658Value, Header, Transaction, TransactionEnvelope, TxReceipt}; use alloy_eips::{eip7685::Requests, Encodable2718, Typed2718}; @@ -55,7 +116,7 @@ use alloy_evm::{ Database, Evm, FromRecoveredTx, FromTxWithEncoded, RecoveredTx, }; use alloy_op_evm::block::{receipt_builder::OpReceiptBuilder, OpTxEnv}; -use alloy_primitives::{Bytes, B256}; +use alloy_primitives::{Address, Bytes, TxHash, B256}; use op_alloy_consensus::OpDepositReceipt; use op_revm::{ constants::L1_BLOCK_CONTRACT, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, @@ -63,7 +124,7 @@ use op_revm::{ use revm::{ context::{result::ResultAndState, Block, ContextTr}, database::DatabaseCommitExt, - state::EvmState, + state::{AccountInfo, EvmState}, DatabaseCommit, Inspector, }; @@ -73,16 +134,23 @@ pub type MegaFinishedBlock = (MegaEvm, MegaBlockExecutionResult<::Receipt>); use crate::{ - block::eips, estimated_da_size, BlockGasCounters, BlockLimiter, BlockLimits, ExternalEnvTypes, + block::{eips, read_l1_block_info}, + estimated_da_size, + system::{ + check_system_contract, classify_system_transaction, is_apply_pending_changes_due, + live_system_address, system_contract_specs, transact_apply_pending_changes, + write_unexpected_code, SystemContractCheckError, + }, + BlockGasCounters, BlockLimiter, BlockLimits, BucketId, ExternalEnvTypes, MegaBlockExecutionResult, MegaBlockTxResult, MegaContext, MegaEvm, MegaHardforks, - MegaTransaction, MegaTransactionExt, + MegaTransaction, MegaTransactionExt, ProtocolLimits, }; /// What the node hands block execution beside the EVM. /// /// It carries what the pre-block calls need (the parent hash and the parent beacon block root, as -/// alloy-op-evm does), the block's own extra data, the activation-block flag and the limits the -/// block holds its transactions to. +/// alloy-op-evm does), the block's own extra data, the two activation-block flags and the +/// builder's packing policy. #[derive(Clone, Debug, Default)] pub struct MegaBlockExecutionCtx { /// The parent block's hash, which the EIP-2935 pre-block call records. @@ -97,7 +165,20 @@ pub struct MegaBlockExecutionCtx { /// [`MegaHardforks::admits_only_deposits`], which needs the parent block's timestamp; `false` /// skips the rule. pub no_user_tx_activation_block: bool, - /// The limits this block holds its transactions to. + /// Whether Satin activates in this block, which makes the pre-block step check the system + /// contracts and the EIP-7997 factory. + /// + /// The caller sets it from the chain's schedule with + /// [`MegaHardforks::is_satin_activation_block`], which needs the parent block's timestamp, as + /// it sets [`no_user_tx_activation_block`](Self::no_user_tx_activation_block); `false` + /// skips the check. The two differ: an Optimism fork at or after Jovian also makes a block + /// deposit-only. + pub satin_activation_block: bool, + /// The builder's packing policy: the limits only a builder applies, and a cap on the block's + /// data-size budget below the protocol's ([`BlockLimits`]). + /// + /// A builder sets it; a validator re-executing a block leaves the default, which restricts + /// nothing, so the block is held to the protocol's limits alone. pub block_limits: BlockLimits, } @@ -114,6 +195,7 @@ impl MegaBlockExecutionCtx { parent_beacon_block_root, extra_data, no_user_tx_activation_block: false, + satin_activation_block: false, block_limits, } } @@ -123,6 +205,12 @@ impl MegaBlockExecutionCtx { self.no_user_tx_activation_block = activation_block; self } + + /// Marks this block the one in which Satin activates. + pub const fn with_satin_activation_block(mut self, activation_block: bool) -> Self { + self.satin_activation_block = activation_block; + self + } } /// A block this engine refuses to execute. @@ -139,7 +227,39 @@ pub enum MegaBlockExecutionError { }, /// The EVM runs an inspector that may rewrite what execution produces, which block execution /// does not admit. + /// + /// The inspector is the node's own choice, not a verdict on the block: an internal error. RewritingInspector, + /// In the block in which Satin activates, a predeploy's address does not hold the code Satin + /// expects: it holds other code, an older version of the contract, no code, or no account. + /// + /// Satin deploys and upgrades nothing: the legacy forks install the six system contracts, the + /// `SequencerRegistry` and the Oracle at v2.0.0, and OP's genesis tooling the EIP-7997 + /// factory, so a chain without them is not one Satin runs on. + UnexpectedSystemContractCode { + /// The predeploy's address. + address: Address, + /// The code hash Satin expects there. + expected: B256, + /// The code hash the address holds: the empty code's for no code or no account. + found: B256, + }, + /// The pre-block `SequencerRegistry.applyPendingChanges()` call did not succeed, so a role + /// change due in this block could not be applied. + ApplyPendingChangesFailed { + /// What the call ended with: its result, or the error that stopped it. + message: String, + }, + /// An outcome handed to a delayed commit executed against another nonce or balance of its + /// sender than the block holds now: a commit since its execution moved them. + /// + /// The builder's to execute again, not a verdict on the block: an internal error. + StaleOutcome { + /// The transaction whose outcome is stale. + tx_hash: TxHash, + /// Its sender. + sender: Address, + }, } impl fmt::Display for MegaBlockExecutionError { @@ -160,6 +280,17 @@ impl fmt::Display for MegaBlockExecutionError { Self::RewritingInspector => f.write_str( "block execution does not admit an inspector that may rewrite execution", ), + Self::UnexpectedSystemContractCode { address, expected, found } => { + write_unexpected_code(f, *address, *expected, *found) + } + Self::ApplyPendingChangesFailed { message } => { + write!(f, "the SequencerRegistry's pending changes could not be applied: {message}") + } + Self::StaleOutcome { tx_hash, sender } => write!( + f, + "stale outcome of transaction {tx_hash}: it executed against another nonce or \ + balance of its sender {sender} than the block holds now" + ), } } } @@ -167,8 +298,21 @@ impl fmt::Display for MegaBlockExecutionError { impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { + /// A block refused for what the node itself does is an internal error: an inspector the node + /// runs that may rewrite execution, or an outcome the builder let go stale, says nothing about + /// the block, and a node must not mark a block invalid because of its own choices. Every other + /// refusal is a verdict on the block, a validation error. fn from(error: MegaBlockExecutionError) -> Self { - Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) + match error { + MegaBlockExecutionError::RewritingInspector | + MegaBlockExecutionError::StaleOutcome { .. } => Self::other(error), + MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | + MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | + MegaBlockExecutionError::UnexpectedSystemContractCode { .. } | + MegaBlockExecutionError::ApplyPendingChangesFailed { .. } => { + Self::Validation(alloy_evm::block::BlockValidationError::Other(Box::new(error))) + } + } } } @@ -185,12 +329,11 @@ pub struct MegaBlockExecutor { pub evm: E, /// The receipts of the transactions committed so far. pub receipts: Vec, - /// What the block has used, and the limits it is held to. - pub limiter: BlockLimiter, - /// Whether Canyon is active, which decides whether a deposit receipt carries a version. - is_canyon: bool, - /// Whether Regolith is active, which decides whether a deposit receipt carries a nonce. - is_regolith: bool, + /// What the block has used, and the limits it is held to. Private, so the limits cannot be + /// changed once the executor has read them; [`limiter`](Self::limiter) reads it. + limiter: BlockLimiter, + /// The limits the protocol holds this block to: the spec's. + protocol_limits: ProtocolLimits, } impl MegaBlockExecutor { @@ -229,35 +372,49 @@ where { /// Creates an executor that runs `ctx`'s block on `evm`. /// - /// The block's transaction-level limits are installed on the EVM here, so every route to an - /// executor — this one and both factory constructors — runs the block's transactions under - /// the limits `ctx` carries, whatever the caller did or did not apply. + /// The limits are the spec's ([`ProtocolLimits::for_spec`]), for the spec `evm` executes: + /// their per-transaction half is installed on the EVM here, and again before every + /// transaction, so every route to an executor — this one and both factory constructors — runs + /// the block's transactions under them, whatever the caller did or did not apply to the EVM. + /// The block is held to the protocol's data-size budget, lowered to `ctx`'s building policy + /// where that is lower. /// - /// The block's gas limit comes from the block environment, whatever `ctx` carries: it is the - /// number consensus holds the block to, and it is also the budget the data-availability - /// footprint of the block's transactions is held to. + /// The block's gas limit comes from the block environment, the executor's own state rather + /// than building policy: it is the number consensus holds the block to, and it is also the + /// budget the data-availability footprint of the block's transactions is held to. pub fn new( mut evm: MegaEvm, ctx: MegaBlockExecutionCtx, spec: Spec, receipt_builder: R, ) -> Self { - evm.set_tx_runtime_limits(ctx.block_limits.to_evm_tx_runtime_limits()); - let (timestamp, block_gas_limit) = { - let block = evm.ctx().block(); - (block.timestamp().saturating_to(), block.gas_limit()) - }; - let limits = ctx.block_limits.with_block_gas_limit(block_gas_limit); - Self { - is_canyon: spec.is_canyon_active_at_timestamp(timestamp), - is_regolith: spec.is_regolith_active_at_timestamp(timestamp), - spec, - receipt_builder, - ctx, - evm, - receipts: Vec::new(), - limiter: limits.to_block_limiter(), - } + let block_gas_limit = evm.ctx().block().gas_limit(); + let protocol_limits = ProtocolLimits::for_spec(evm.ctx().spec()); + evm.set_tx_runtime_limits(protocol_limits.tx_runtime_limits); + let limiter = BlockLimiter::new(ctx.block_limits.within(&protocol_limits), block_gas_limit); + Self { spec, receipt_builder, ctx, evm, receipts: Vec::new(), limiter, protocol_limits } + } + + /// The limits the protocol holds this block to: the spec's + /// ([`ProtocolLimits::for_spec`]). + pub const fn protocol_limits(&self) -> &ProtocolLimits { + &self.protocol_limits + } + + /// Holds this block to `limits` in place of the spec's: a counterfactual of a tool's or a + /// test's, which a node executing the chain never runs. + /// + /// Their per-transaction half is installed on the EVM and before every transaction from now + /// on, and the block's data-size budget is theirs, lowered to the building policy where that + /// is lower. What the block counted so far stays counted. Behind the `test-utils` feature, so + /// a node build cannot reach it. + #[cfg(any(test, feature = "test-utils"))] + pub fn with_protocol_limits(mut self, limits: ProtocolLimits) -> Self { + self.evm.set_tx_runtime_limits(limits.tx_runtime_limits); + self.limiter.limits.block_txs_data_limit = + self.ctx.block_limits.within(&limits).block_txs_data_limit; + self.protocol_limits = limits; + self } } @@ -277,7 +434,11 @@ where /// The data-availability footprint gas scalar the L1 block contract holds. /// /// Read per transaction, as the fork's rule is stated: the block's own L1 info transaction - /// may set it, and the transactions after it are held to the value it set. + /// may set it, and the transactions after it are held to the value it set. It is a read of + /// the block's state, made between transactions, so it lands in no transaction's returned + /// state; the pre-block phase's read of the same slot ([`read_l1_block_info`]) is what puts + /// it in the pre-block states a witness is built from, and this read finds it in the state + /// cache that read filled, or the value the L1 info transaction committed over it. fn da_footprint_gas_scalar(&mut self) -> Result { // Load the L1 block account into the cache first; a database that has never seen it // cannot serve its storage. @@ -308,6 +469,70 @@ where Ok(()) } + /// Whether the block, as its counters are now, still has room for the executed transaction + /// `output`: every check its execution held it to, before it ran and after, made again. It + /// reads the counters and changes nothing. + /// + /// Both commit paths share it: [`commit_transaction_outcome`](Self::commit_transaction_outcome) + /// refuses what it refuses, and [`commit_transaction`](BlockExecutor::commit_transaction) + /// asserts it in a debug build. It checks the counters only, not the state `output` executed + /// against. + fn check_room(&self, output: &MegaBlockTxResult) -> Result<(), BlockExecutionError> { + self.limiter.pre_execution_check( + output.tx_hash, + output.gas_limit, + output.tx_size, + output.da_size, + output.is_deposit || output.is_system_transaction, + )?; + self.check_da_footprint(output.da_footprint) + } + + /// Whether `output` executed against the nonce and balance its sender has in the block's state + /// now: a delayed commit's check that no commit since its execution moved them. + /// + /// A commit writes the sender's account as the transaction left it. An outcome executed before + /// another commit moved the sender — a second transaction at the same nonce, a value or a fee + /// credited to the sender — would write that account over what the other commit did: the + /// sender debited once for two transactions, or a credit lost. Every other read the outcome + /// made is not checked; that the state it read is still the block's is the builder's to keep. + /// It reads the sender's account and changes nothing. + fn check_sender_unchanged( + &mut self, + output: &MegaBlockTxResult, + ) -> Result<(), BlockExecutionError> { + let now = self.sender_account(output.sender)?; + if (now.nonce, now.balance) != (output.sender_nonce, output.sender_balance) { + return Err(MegaBlockExecutionError::StaleOutcome { + tx_hash: output.tx_hash, + sender: output.sender, + } + .into()); + } + Ok(()) + } + + /// The account of `sender` as the block's state holds it now, empty when it holds none. A read + /// the database cannot serve is an internal error: it says nothing about the block. + fn sender_account(&mut self, sender: Address) -> Result { + Ok(self + .evm + .ctx_mut() + .db_mut() + .basic(sender) + .map_err(BlockExecutionError::other)? + .unwrap_or_default()) + } + + /// Whether `tx` is a Mega System Transaction: sent from the live system address with the + /// system shape. A transaction from that address of another shape is not (the engine refuses + /// it when it validates it). A read the database cannot serve is an internal error. + fn is_system_transaction(&mut self, tx: &MegaTransaction) -> Result { + let system_address = live_system_address(&mut *self.evm.ctx_mut().db_mut()) + .map_err(BlockExecutionError::other)?; + Ok(classify_system_transaction(tx, system_address).unwrap_or(false)) + } + /// Refuses an EVM that runs an inspector which may rewrite what execution produces. /// /// Checked at every entry point rather than once, because the inspector can be enabled after @@ -344,6 +569,43 @@ where pub fn clear_accessed_block_hashes(&mut self) { self.evm.clear_accessed_block_hashes(); } + + /// The SALT buckets the SALT environment answered with a valid capacity during this block's + /// execution so far, in ascending order: every bucket a state charge was priced in. + /// + /// A bucket's capacity is read through the SALT environment, which no database sees, and a + /// validator that lacks a bucket's proof cannot price the charge that landed in it, so this is + /// where a stateless witness learns which buckets it must carry. The set is complete for the + /// transactions this executor's EVM ran: the engine asks about a bucket at a state charge site + /// and nowhere else, and a validator re-executing them reaches the same charge sites. A lookup + /// that failed, with an error or with a capacity below the minimum bucket, is not in it, + /// because it failed its transaction, which is in no block; the pre-block calls and the system + /// transactions read no bucket and add none. + /// + /// What the record covers, and what it does not: + /// + /// - It holds what this executor's EVM executed since the block started: + /// [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) empties it, + /// and nothing empties it between the block's transactions, whose own multiplier caches are + /// forgotten one transaction at a time. A candidate the builder executed here and dropped + /// leaves its buckets in the set, which a validator does not need but is not harmed by. + /// - It holds nothing of an outcome executed elsewhere: an outcome another EVM produced and + /// this executor committed through + /// [`commit_transaction_outcome`](Self::commit_transaction_outcome) added no bucket here. A + /// node that executes on several EVMs, or builds one per transaction, takes the union of what + /// each reports; one that clears the record between transactions + /// ([`clear_accessed_bucket_ids`](Self::clear_accessed_bucket_ids)) does the same. + /// - An EVM reused across blocks outside a block executor is emptied by neither, and reports + /// every block it ran since it was last cleared. + pub fn get_accessed_bucket_ids(&self) -> Vec { + self.evm.get_accessed_bucket_ids() + } + + /// Forgets the SALT buckets asked about so far, so the next asks are attributable to one + /// transaction. The record decides nothing, so clearing it changes no execution result. + pub fn clear_accessed_bucket_ids(&mut self) { + self.evm.clear_accessed_bucket_ids(); + } } impl BlockExecutor @@ -363,25 +625,48 @@ where /// Runs what a block does before its transactions. /// - /// In order: the admission gate, the reset of the block-hash record, and the EIP-2935 and - /// EIP-4788 pre-block calls. Each call's state is committed here rather than inside its - /// helper, so a witness generator sees every step's read and write set. + /// In order: the admission gate, the reset of the block-hash and bucket records, the EIP-2935 + /// and EIP-4788 pre-block calls, in the block in which Satin activates the check of the + /// predeploys, the `SequencerRegistry`'s due role changes and the read of the L1 block info. + /// Each step's state is committed here, on its own and read-only entries included, rather + /// than inside its helper, so a commit hook on the database sees every step's read and write + /// set. The sequence of committed states is the witness a stateless client needs. + /// + /// The transactions are not priced against the read made here. op-revm's handler fetches the + /// L1 block info when it deducts the caller of the first non-deposit transaction, which is + /// after the block's own L1 info deposit has committed; pricing from this read would price + /// every transaction of the block against the parent block's values. The read here puts the + /// L1 block contract's account and every slot that fetch can reach in the pre-block states, + /// and nothing else. /// - /// The L1 block info is not read here. op-revm's handler reads it when it deducts the caller - /// of the first non-deposit transaction, which is after the block's own L1 info deposit has - /// committed; reading it here would price every transaction of the block against the parent - /// block's values. + /// The EIP-2935 and EIP-4788 calls run before the check. They write the parent hash and the + /// parent beacon root into their own contracts (`0x0…2935` and `0x0…4788`), which are not + /// `MegaETH` system contracts and do not read them, so their outcome does not depend on the + /// check that follows. Each runs on the pre-block budget + /// ([`pre_block_call_gas_limit`](eips::pre_block_call_gas_limit)), and one that does not + /// succeed refuses the block before its state is committed. /// - /// Two hook points are empty: system contract deployment, which deploys the chain's system - /// contracts at the Satin activation, and the pre-block system calls, which apply the - /// pending changes the sequencer registry holds. Both arrive with the mechanisms of those - /// names, after the pre-block calls. + /// The check is made once, in the block in which Satin activates + /// ([`MegaBlockExecutionCtx::satin_activation_block`]): each of the seven predeploys must hold + /// the code Satin expects, and its account is committed as a read-only entry; any other block + /// reads none of them. Satin deploys and upgrades nothing: a chain reaches it through the + /// legacy forks, which leave the six system contracts at the versions Satin runs, and the + /// EIP-7997 factory is OP's predeploy. + /// + /// The registry's role changes come after. Its pending slots are read and committed as a + /// read-only state whatever they say, and when a change is due in this block the + /// `applyPendingChanges()` call applies it on the same pre-block budget, refusing the block + /// if it does not succeed. So a rotation due in this block governs this block's + /// system-address transactions: each reads the live system address out of the registry when + /// it is validated, after these steps are committed, and nothing inside the block can + /// change it again. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.check_admission()?; - // The block starts with an empty block-hash record, so what it holds at the end is what - // this block read. + // The block starts with empty block-hash and bucket records, so what they hold at the end + // is what this block read. self.evm.clear_accessed_block_hashes(); + self.evm.clear_accessed_bucket_ids(); let state = eips::transact_blockhashes_contract_call( &self.spec, @@ -401,8 +686,50 @@ where self.commit(state); } - // Hook point: system contract deployment. - // Hook point: the pre-block system calls. + // The EIP-2935 / EIP-4788 calls above do not depend on these predeploys: they target + // their own contracts, not the MegaETH system addresses or the factory. + if self.ctx.satin_activation_block { + for spec in system_contract_specs() { + let state = + check_system_contract(self.evm.db_mut(), &spec).map_err( + |error| match error { + SystemContractCheckError::Database(error) => { + BlockExecutionError::other(error) + } + SystemContractCheckError::UnexpectedCode { + address, + expected, + found, + } => MegaBlockExecutionError::UnexpectedSystemContractCode { + address, + expected, + found, + } + .into(), + }, + )?; + self.commit(state); + } + } + + let block_number = self.evm.block().number().saturating_to(); + let (due, reads) = is_apply_pending_changes_due(self.evm.db_mut(), block_number) + .map_err(BlockExecutionError::other)?; + self.commit(reads); + if due { + let ResultAndState { state, .. } = transact_apply_pending_changes(&mut self.evm)?; + self.commit(state); + } + + // The L1 block info the transactions are priced against is read on the database itself, + // by op-revm once per block and by `execute` before every non-deposit transaction, so it + // lands in no transaction's state. Read here, it is in the pre-block states instead: + // every slot those reads can reach, because which ones they reach is decided by the state + // the block's deposits leave, not by this one. The read fills the state cache, and its + // commit changes nothing: a commit hook receives the read-only entry, and the cache keeps + // no transition for it. + let state = read_l1_block_info(self.evm.db_mut()).map_err(BlockExecutionError::other)?; + self.commit(state); Ok(()) } @@ -433,7 +760,39 @@ where self.commit_transaction_outcome(output).map(Some) } + /// Commits `output`: builds its receipt, adds it to the block's counters and commits its + /// state. + /// + /// This commit cannot fail, and its contract is alloy-evm's: `output` is the outcome of the + /// transaction executed last, committed before the next one executes. The block's counters + /// are then the ones `output` was checked against, and a release build checks nothing again. + /// A caller that executes several candidates before it commits any commits through + /// [`commit_transaction_outcome`](MegaBlockExecutor::commit_transaction_outcome), which + /// refuses an outcome the block no longer has room for. + /// + /// [`commit_transaction_outcome`](MegaBlockExecutor::commit_transaction_outcome) also refuses + /// an outcome whose sender's nonce or balance another commit moved since it executed; any + /// other state the outcome read is the caller's to keep fresh. + /// + /// # Panics + /// + /// In a debug build, when the block no longer has room for `output`, or when its sender's + /// nonce or balance moved since it executed — a caller that broke the contract, which would + /// otherwise pack the block past a limit or commit a stale outcome. fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { + debug_assert!( + self.check_room(&output).is_ok(), + "commit_transaction was handed an outcome the block no longer has room for, which \ + commit_transaction_outcome refuses: {}", + self.check_room(&output).expect_err("the check just failed"), + ); + #[cfg(debug_assertions)] + if let Err(stale) = self.check_sender_unchanged(&output) { + panic!( + "commit_transaction was handed a stale outcome, which commit_transaction_outcome \ + refuses: {stale}" + ); + } self.limiter.post_execution_update(&output.block_usage()); let MegaBlockTxResult { tx_type, is_deposit, depositor_nonce, inner, .. } = output; @@ -458,12 +817,14 @@ where logs: ctx.result.into_logs(), }; + // Satin executes only at or after Karst, which includes Canyon, and the + // schedule check refuses a schedule in which Canyon is not active when Satin + // activates: every deposit receipt carries Canyon's receipt version, which + // says how the receipt hash is computed. self.receipt_builder.build_deposit_receipt(OpDepositReceipt { inner: receipt, deposit_nonce: depositor_nonce, - // Canyon introduced the deposit receipt version, which says how the - // receipt hash is computed. - deposit_receipt_version: (is_deposit && self.is_canyon).then_some(1), + deposit_receipt_version: is_deposit.then_some(1), }) } }, @@ -514,9 +875,9 @@ where /// computes them from its own encoding is unconditionally safe. /// /// Nothing is committed. Hand the result to - /// [`commit_transaction`](BlockExecutor::commit_transaction), or to - /// [`commit_transaction_outcome`](Self::commit_transaction_outcome) to have the block's - /// admission re-checked first. + /// [`commit_transaction`](BlockExecutor::commit_transaction) before the next transaction + /// executes, or to [`commit_transaction_outcome`](Self::commit_transaction_outcome) when + /// another outcome may commit first. pub fn run_transaction( &mut self, tx: Tx, @@ -531,39 +892,28 @@ where self.execute(tx, Some(reported)) } - /// Alias of [`run_transaction`](Self::run_transaction). - pub fn execute_mega_transaction( - &mut self, - tx: Tx, - ) -> Result< - MegaBlockTxResult<::TxType>, - BlockExecutionError, - > - where - Tx: ExecutableTx + MegaTransactionExt, - { - self.run_transaction(tx) - } - /// Re-checks the block's admission and commits `output`. /// - /// The block's counters may have moved between the transaction executing and its commit — a - /// builder that executes candidates and then picks among them — so everything the block - /// holds a transaction to is checked once more, its data-availability footprint included, and - /// nothing changes before the check passes. + /// This is the commit for a builder that executes several candidates and then chooses among + /// them: the block's counters may have moved between a candidate executing and its commit, so + /// everything the block holds a transaction to is checked once more — its data-availability + /// footprint included — and nothing changes before the check passes. + /// + /// The state `output` executed against may have moved too. The sender's account is checked + /// ([`MegaBlockExecutionError::StaleOutcome`]): an outcome whose sender's nonce or balance + /// another commit moved since it executed — the system address's, for a system-address + /// transaction — is refused, since committing it would write the sender's account over what + /// that commit did. Any other read the outcome made is not checked, and executing a candidate + /// again when another commit moved what it read is the builder's responsibility: a builder + /// that executes an Oracle-reading transaction, then executes and commits the system-address + /// transaction that writes the Oracle before it, commits both. pub fn commit_transaction_outcome( &mut self, output: MegaBlockTxResult<::TxType>, ) -> Result { self.check_admission()?; - self.limiter.pre_execution_check( - output.tx_hash, - output.gas_limit, - output.tx_size, - output.da_size, - output.is_deposit, - )?; - self.check_da_footprint(output.da_footprint)?; + self.check_room(&output)?; + self.check_sender_unchanged(&output)?; Ok(self.commit_transaction(output)) } @@ -617,7 +967,19 @@ where ); let gas_limit = inner.gas_limit(); - self.limiter.pre_execution_check(tx_hash, gas_limit, tx_size, da_size, is_deposit)?; + // A Mega System Transaction is decided before it runs, from the registry's live system + // address as the block's state holds it: the engine reads the same slot when it validates + // the transaction, and a transaction of another shape from that address is no system + // transaction here but refused there. + let is_system_transaction = !is_deposit && self.is_system_transaction(&tx_env)?; + + self.limiter.pre_execution_check( + tx_hash, + gas_limit, + tx_size, + da_size, + is_deposit || is_system_transaction, + )?; // A deposit is exempt from the data-availability footprint of the block, as it is from // its data-availability size. @@ -629,28 +991,24 @@ where footprint }; - // Read before execution, so committing the transaction cannot fail. - let depositor_nonce = if is_deposit && self.is_regolith { - let sender = *tx.signer(); - Some( - self.evm - .ctx_mut() - .db_mut() - .basic(sender) - .map_err(BlockExecutionError::other)? - .unwrap_or_default() - .nonce, - ) - } else { - None - }; - + // The sender's account as the transaction executes against it, read before execution: a + // delayed commit checks it against the state then, and committing the transaction cannot + // fail. Satin executes only at or after Karst, which includes Regolith, and the schedule + // check refuses a schedule in which Regolith is not active when Satin activates: every + // deposit receipt carries the depositor's nonce. + let sender = *tx.signer(); + let sender_before = self.sender_account(sender)?; + let depositor_nonce = is_deposit.then_some(sender_before.nonce); + + // The transaction runs under the block's limits, whatever was set on the EVM since the + // last one. + self.evm.set_tx_runtime_limits(self.protocol_limits.tx_runtime_limits); let outcome = self .evm .execute_transaction(tx_env) .map_err(|err| BlockExecutionError::evm(err, tx_hash))?; - Ok(MegaBlockTxResult { + let result = MegaBlockTxResult { tx_type: inner.tx_type(), tx_hash, gas_limit, @@ -658,9 +1016,14 @@ where da_size, da_footprint, is_deposit, + is_system_transaction, depositor_nonce, + sender, + sender_nonce: sender_before.nonce, + sender_balance: sender_before.balance, inner: outcome, - }) + }; + Ok(result) } /// Finishes the block and reports what it counted, on top of what @@ -718,8 +1081,98 @@ mod tests { ); assert_eq!(executor.evm().block().gas_limit, 30_000_000); - assert_eq!(executor.limiter().limits.block_gas_limit, 30_000_000); + assert_eq!(executor.limiter().block_gas_limit, 30_000_000); + assert_eq!(executor.protocol_limits(), &ProtocolLimits::for_spec(MegaSpecId::SATIN)); + assert_eq!( + executor.evm().tx_runtime_limits().tx_data_size_limit, + crate::constants::TX_DATA_LIMIT, + "the executor installs the spec's per-transaction data-size cap" + ); + assert_eq!(executor.evm().tx_runtime_limits().frame_data_size_limit, u64::MAX); + assert_eq!( + executor.limiter().limits.block_txs_data_limit, + crate::constants::BLOCK_DATA_LIMIT + ); executor.evm_mut().set_inspector_enabled(true); assert!(executor.into_evm().is_inspecting()); } + + /// A block is held to its spec's limits whatever the node hands over: limits it set on the + /// EVM are replaced, a looser building policy gives way to the spec's budget, and the schedule + /// carries none. Only the test-and-tool override replaces them, and a policy still tightens + /// what it installs. + #[test] + fn test_a_block_is_held_to_its_specs_limits_whatever_the_node_passes() { + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN) + .with_tx_runtime_limits(crate::EvmTxRuntimeLimits::no_limits()); + let policy = BlockLimits::no_limits().with_block_txs_data_limit(u64::MAX); + let executor = MegaBlockExecutor::new( + MegaEvm::new(ctx), + MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), policy), + MegaHardforkConfig::default().with_all_activated(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ); + assert_eq!(executor.protocol_limits(), &satin); + assert_eq!(*executor.evm().tx_runtime_limits(), satin.tx_runtime_limits); + assert_eq!(executor.limiter().limits.block_txs_data_limit, 13_107_200); + + let counterfactual = ProtocolLimits::no_limits().with_block_txs_data_limit(7); + let executor = executor.with_protocol_limits(counterfactual); + assert_eq!(executor.protocol_limits(), &counterfactual); + assert_eq!(*executor.evm().tx_runtime_limits(), counterfactual.tx_runtime_limits); + assert_eq!(executor.limiter().limits.block_txs_data_limit, 7); + + let tighter = MegaBlockExecutor::new( + MegaEvm::new(MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN)), + MegaBlockExecutionCtx::new( + B256::ZERO, + None, + Bytes::new(), + BlockLimits::no_limits().with_block_txs_data_limit(5), + ), + MegaHardforkConfig::default().with_all_activated(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ) + .with_protocol_limits(counterfactual); + assert_eq!(tighter.limiter().limits.block_txs_data_limit, 5, "the policy still tightens"); + } + + /// The `MegaBlockExecutionError` an internal error carries; panics on a validation error. + fn internal(error: &BlockExecutionError) -> &MegaBlockExecutionError { + error + .as_internal() + .and_then(|error| error.downcast_other::()) + .unwrap_or_else(|| panic!("not an internal refusal of this engine: {error:?}")) + } + + /// Every refusal but those for what the node itself does — an inspector it runs, here — is a + /// verdict on the block: a validation error. A predeploy that does not hold Satin's code when + /// Satin activates is one. + #[test] + fn test_a_refusal_of_the_block_is_a_validation_error() { + let address = alloy_primitives::Address::repeat_byte(1); + for refusal in [ + MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock, + MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint: 2, + available_block_da_footprint: 1, + }, + MegaBlockExecutionError::UnexpectedSystemContractCode { + address, + expected: B256::ZERO, + found: B256::repeat_byte(1), + }, + MegaBlockExecutionError::ApplyPendingChangesFailed { message: String::new() }, + ] { + let error = BlockExecutionError::from(refusal.clone()); + let Some(alloy_evm::block::BlockValidationError::Other(inner)) = error.as_validation() + else { + panic!("{refusal:?} is a verdict on the block: {error:?}"); + }; + assert_eq!(inner.downcast_ref::(), Some(&refusal)); + } + let inspector = MegaBlockExecutionError::RewritingInspector; + assert_eq!(internal(&BlockExecutionError::from(inspector.clone())), &inspector); + } } diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index 2862938d6..3e4e7bc55 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -16,8 +16,8 @@ use crate::{ /// Creates the block executors a node drives. /// -/// It holds what every block of the chain shares — the hardfork schedule, the EVM factory and -/// the receipt builder — and each block adds its own [`MegaBlockExecutionCtx`]. +/// It holds what every block of the chain shares — the hardfork schedule, the EVM factory and the +/// receipt builder — and each block adds its own [`MegaBlockExecutionCtx`]. #[derive(Clone, Debug, Default)] pub struct MegaBlockExecutorFactory { receipt_builder: R, @@ -27,6 +27,10 @@ pub struct MegaBlockExecutorFactory { impl MegaBlockExecutorFactory { /// Creates a factory over a receipt builder, a hardfork schedule and an EVM factory. + /// + /// The executors hold every block to its spec's limits, whatever the EVM they run on was + /// created with; the EVMs the EVM factory creates outside block execution run under the same + /// ones ([`MegaEvmFactory`]). pub const fn new(receipt_builder: R, spec: Spec, evm_factory: EvmF) -> Self { Self { receipt_builder, spec, evm_factory } } @@ -101,9 +105,8 @@ where /// Creates an executor over an EVM the caller built. /// - /// The block's transaction-level limits are installed by - /// [`MegaBlockExecutor::new`], so an EVM the caller built without them still runs the block's - /// transactions under them. + /// The spec's limits are installed by [`MegaBlockExecutor::new`], so an EVM the caller built + /// with others still runs the block's transactions under them. /// /// alloy-evm asks for an executor for every `I: Inspector`, so this route cannot refuse a /// rewriting inspector by its type; the executor checks the EVM at every entry point instead. diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs new file mode 100644 index 000000000..3fe4ce493 --- /dev/null +++ b/crates/mega-evm/src/block/genesis.rs @@ -0,0 +1,621 @@ +//! The Satin key of a chain configuration: when Satin activates. +//! +//! [`SatinChainConfig`] reads it and states the format, which is provisional. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::fmt; +use std::{ + collections::BTreeMap, + string::{String, ToString}, +}; + +use alloy_hardforks::ForkCondition; +use serde::{ + de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor}, + ser::SerializeMap, + Deserialize, Deserializer, Serialize, Serializer, +}; + +use crate::{MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError}; + +/// The key of Satin's activation timestamp. +pub const SATIN_TIME_KEY: &str = "satinTime"; + +/// Every Satin key of a chain configuration, in the order [`SatinChainConfig`] writes them. +pub const SATIN_CHAIN_CONFIG_KEYS: [&str; 1] = [SATIN_TIME_KEY]; + +/// The prefix every Satin key starts with, compared without regard to case. +const PREFIX: &str = "satin"; + +/// The key `serde_json` built with `arbitrary_precision` hands a number over under. +const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number"; + +/// A chain's Satin configuration, as its genesis file's `config` object carries it: when Satin +/// activates. +/// +/// **The key format is provisional.** It is fixed when a network first publishes a genesis file +/// that carries it; until then a change to it is a change to this parser and to every genesis +/// file written against it. +/// +/// Every reader of a chain's Satin configuration — a node, a stateless validator, a genesis +/// generator, a replay tool — parses it here ([`SatinChainConfig::from_genesis_config`]), so the +/// key names and the rules cannot drift apart between them: a reader that took another value for +/// the key would execute another chain. +/// +/// Satin carries no parameter: a chain that activates it has run the legacy forks, which deployed +/// the `SequencerRegistry` and upgraded it to v2.0.0, and the registry's roles are what it holds. +/// The legacy forks' own keys (`rex5InitialSequencer`, `rex6MinRotationDelay`, ...) are theirs +/// and are not read here. +/// +/// The key sits at the top level of the genesis file's `config` object, beside the other forks' +/// keys, camelCase: +/// +/// | Key | Value | Field | +/// | ----------- | ------- | ------------------------------------------------------ | +/// | `satinTime` | integer | the activation timestamp ([`Self::activation_time`]) | +/// +/// An integer is a JSON number that fits in 64 unsigned bits, `u64::MAX` included, which a writer +/// must emit exactly. +/// +/// The rules: +/// +/// - A configuration with no key starting with `satin` does not activate Satin. +/// - A key starting with `satin`, in any case, that is not `satinTime` is refused, so a misspelled +/// key cannot stand in for the one it meant, and a file written against an earlier version of the +/// format — one that named the registry's roles (`satinInitialSequencer`, ...) or the limits — +/// does not load. Every other key is another fork's and is not read. +/// - A key given twice is refused only where the deserializer still shows both copies, as the +/// object's text through a `serde_json::Deserializer` does. A `serde_json::Value` has already +/// kept the last copy, so a reader that parses the file into one first — `mega-evme --genesis` +/// does, and so does a node that serializes its chain-config type — reads the last value and +/// refuses nothing. +/// - A value of the wrong type is refused, naming its key, and so is a schedule +/// [`validate_schedule`](MegaHardforks::validate_schedule) refuses. One object is read as an +/// integer: `{"$serde_json::private::Number": ""}`, the form `serde_json` hands a number +/// over in when its `arbitrary_precision` feature is on. A deserializer shows that form and the +/// same object written into the file alike, so both are read as the number; every reader parses +/// here, so every reader reads it the same. +/// +/// The parser reads no other fork's key. Satin runs on the OP Karst fork and the Ethereum forks +/// Karst includes, Osaka among them, and [`hardforks`](Self::hardforks) schedules those as active +/// from the first block, which no Satin block can tell apart from the file's times when they are +/// active by `satinTime`. +/// A node's own schedule times those forks from the file, and holds them to both halves of the +/// timing rule [`validate_schedule`](MegaHardforks::validate_schedule) states. +/// +/// A flat key is one entry of the object, so a checker that freezes a configuration key by key +/// freezes `satinTime` on its own and names it when it changes. It does not stop a key being added +/// later; a rule that refuses a new key starting with `satin` once the configuration was first +/// loaded does. +/// +/// It serializes to the key it is read from, so a generator that writes a genesis file with it +/// writes what every reader parses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SatinChainConfig { + /// The timestamp Satin activates at. + pub activation_time: u64, +} + +impl SatinChainConfig { + /// Reads the Satin key of a genesis file's `config` object from `config`, which any + /// self-describing deserializer of the object can supply: a `&serde_json::Value`, or the + /// object's text through a `serde_json::Deserializer`, whose caller checks that the input ends + /// with the object. A node's own chain-config type supplies one by serializing to a + /// `serde_json::Value`. + /// + /// `Ok(None)` when the configuration does not activate Satin; otherwise the configuration, + /// whose schedule [`validate_schedule`](MegaHardforks::validate_schedule) accepts. + /// + /// # Errors + /// + /// Every rule of the [format](Self) that the configuration breaks, the first one found. + pub fn from_genesis_config<'de, D: Deserializer<'de>>( + config: D, + ) -> Result, SatinChainConfigError> { + let Entries { mut entries, duplicate } = config + .deserialize_map(EntriesVisitor) + .map_err(|error| SatinChainConfigError::Malformed(error.to_string()))?; + if let Some(key) = duplicate { + return Err(SatinChainConfigError::DuplicateKey(key)); + } + if let Some(unknown) = + entries.keys().find(|key| !SATIN_CHAIN_CONFIG_KEYS.contains(&key.as_str())) + { + return Err(SatinChainConfigError::UnknownKey(unknown.clone())); + } + let activation_time = match entries.remove(SATIN_TIME_KEY) { + None => return Ok(None), + Some(Entry::Unsigned(value)) => value, + Some(Entry::Other) => { + return Err(SatinChainConfigError::InvalidValue { + key: SATIN_TIME_KEY, + expected: "an integer from 0 to 2^64 - 1", + }) + } + }; + let config = Self { activation_time }; + config.hardforks()?; + Ok(Some(config)) + } + + /// The hardfork schedule this configuration makes: [`MegaHardforkConfig::new`]'s base forks + /// and Satin at [`activation_time`](Self::activation_time). + /// + /// The base forks, every OP and Ethereum fork up to Karst, are active from the first block here + /// whatever the genesis file times them at, so the schedule passes the base-fork check of + /// [`validate_schedule`](MegaHardforks::validate_schedule) whenever Satin activates: a node + /// checks the file's own times against `satinTime` on its own schedule (see the + /// [format](Self)). + /// + /// # Errors + /// + /// A schedule [`validate_schedule`](MegaHardforks::validate_schedule) refuses. + pub fn hardforks(&self) -> Result { + let schedule = MegaHardforkConfig::new() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(self.activation_time)); + schedule.validate_schedule()?; + Ok(schedule) + } +} + +impl Serialize for SatinChainConfig { + /// Writes the key, [`SATIN_TIME_KEY`]. + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(SATIN_CHAIN_CONFIG_KEYS.len()))?; + map.serialize_entry(SATIN_TIME_KEY, &self.activation_time)?; + map.end() + } +} + +/// Why a chain configuration's Satin key cannot be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SatinChainConfigError { + /// The configuration is not an object with string keys. + Malformed(String), + /// A key that starts with `satin` but is not `satinTime`. + UnknownKey(String), + /// A key that starts with `satin`, given twice. + DuplicateKey(String), + /// A key whose value is not of its type. + InvalidValue { + /// The key. + key: &'static str, + /// What its value must be. + expected: &'static str, + }, + /// A schedule [`validate_schedule`](MegaHardforks::validate_schedule) refuses. + Schedule(ScheduleError), +} + +impl fmt::Display for SatinChainConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Malformed(message) => { + write!(f, "the chain configuration is malformed: {message}") + } + Self::UnknownKey(key) => write!(f, "`{key}` is not a Satin chain-configuration key"), + Self::DuplicateKey(key) => write!(f, "`{key}` is given twice"), + Self::InvalidValue { key, expected } => write!(f, "`{key}` must be {expected}"), + Self::Schedule(error) => write!(f, "{error}"), + } + } +} + +impl core::error::Error for SatinChainConfigError {} + +impl From for SatinChainConfigError { + fn from(error: ScheduleError) -> Self { + Self::Schedule(error) + } +} + +/// The value of a key, as far as reading the Satin key needs it: an unsigned integer, or anything +/// else. +#[derive(Debug)] +enum Entry { + Unsigned(u64), + Other, +} + +/// A configuration object's entries whose key starts with [`PREFIX`], and the first such key +/// given twice, if one was. +struct Entries { + entries: BTreeMap, + duplicate: Option, +} + +/// Collects a configuration object's entries whose key starts with [`PREFIX`], and skips the +/// others' values without keeping them. +struct EntriesVisitor; + +impl<'de> Visitor<'de> for EntriesVisitor { + type Value = Entries; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a chain configuration object") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut entries = BTreeMap::new(); + let mut duplicate = None; + while let Some(key) = map.next_key::()? { + if is_satin_key(&key) { + let entry = map.next_value::()?; + if entries.contains_key(&key) { + duplicate.get_or_insert_with(|| key.clone()); + } + entries.insert(key, entry); + } else { + map.next_value::()?; + } + } + Ok(Entries { entries, duplicate }) + } +} + +/// Whether `key` starts with [`PREFIX`], in any case. +fn is_satin_key(key: &str) -> bool { + key.get(..PREFIX.len()).is_some_and(|start| start.eq_ignore_ascii_case(PREFIX)) +} + +impl<'de> Deserialize<'de> for Entry { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(EntryVisitor) + } +} + +struct EntryVisitor; + +impl<'de> Visitor<'de> for EntryVisitor { + type Value = Entry; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("any value") + } + + fn visit_u64(self, value: u64) -> Result { + Ok(Entry::Unsigned(value)) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(u64::try_from(value).map_or(Entry::Other, Entry::Unsigned)) + } + + fn visit_u128(self, value: u128) -> Result { + Ok(u64::try_from(value).map_or(Entry::Other, Entry::Unsigned)) + } + + fn visit_i128(self, value: i128) -> Result { + Ok(u64::try_from(value).map_or(Entry::Other, Entry::Unsigned)) + } + + fn visit_f64(self, _: f64) -> Result { + Ok(Entry::Other) + } + + fn visit_bool(self, _: bool) -> Result { + Ok(Entry::Other) + } + + fn visit_str(self, _: &str) -> Result { + Ok(Entry::Other) + } + + fn visit_unit(self) -> Result { + Ok(Entry::Other) + } + + fn visit_none(self) -> Result { + Ok(Entry::Other) + } + + fn visit_some>(self, deserializer: D) -> Result { + deserializer.deserialize_any(self) + } + + fn visit_seq>(self, mut seq: A) -> Result { + while seq.next_element::()?.is_some() {} + Ok(Entry::Other) + } + + /// A map is no value a key takes, but for one shape: `serde_json` built with its + /// `arbitrary_precision` feature, which a node's dependencies may switch on, hands every number + /// over as a one-entry map from [`ARBITRARY_PRECISION_NUMBER`] to the number's text. That + /// number is read as the same number is read without the feature, so the feature changes + /// nothing a reader accepts. + fn visit_map>(self, mut map: A) -> Result { + let mut entry = Entry::Other; + if let Some(key) = map.next_key::()? { + if key == ARBITRARY_PRECISION_NUMBER { + let text = map.next_value::()?; + entry = text.parse::().map_or(Entry::Other, Entry::Unsigned); + } else { + map.next_value::()?; + } + } + if map.next_entry::()?.is_some() { + entry = Entry::Other; + while map.next_entry::()?.is_some() {} + } + Ok(entry) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MegaSpecId; + use serde_json::{json, Value}; + + const ACTIVATION: u64 = 1_800_000_000; + + fn config() -> SatinChainConfig { + SatinChainConfig { activation_time: ACTIVATION } + } + + /// The keys of the configuration format's earlier versions: the `SequencerRegistry`'s roles and + /// rotation delay, `_initialFromBlock`, and the limits. + const OLD_KEYS: [&str; 10] = [ + "satinInitialSystemAddress", + "satinInitialSequencer", + "satinInitialAdmin", + "satinMinRotationDelay", + "satinInitialFromBlock", + "satinTxDataSizeLimit", + "satinFrameDataSizeLimit", + "satinBlockEnvAccessComputeGasLimit", + "satinOracleAccessComputeGasLimit", + "satinBlockTxsDataLimit", + ]; + + /// A mainnet-shaped genesis `config` object carrying [`config`] among other forks' keys, the + /// legacy forks' registry keys included. + fn genesis_config() -> Value { + let mut object = json!({ + "chainId": 4326, + "homesteadBlock": 0, + "shanghaiTime": 0, + "rex5Time": 1_760_000_000, + "rex6Time": 1_770_000_000, + "rex5InitialSequencer": "0x4444444444444444444444444444444444444444", + "rex5InitialAdmin": "0x5555555555555555555555555555555555555555", + "rex6MinRotationDelay": 100, + "optimism": { "eip1559Elasticity": 6, "eip1559Denominator": 50 }, + "blobSchedule": { "cancun": { "target": 3, "max": 6 } }, + "terminalTotalDifficultyPassed": true, + "depositContractAddress": null, + }); + let keys = serde_json::to_value(config()).unwrap(); + object.as_object_mut().unwrap().extend(keys.as_object().unwrap().clone()); + object + } + + fn parse(config: &Value) -> Result, SatinChainConfigError> { + SatinChainConfig::from_genesis_config(config) + } + + /// The configuration writes `satinTime` alone, and reading it back gives the same + /// configuration, from a `serde_json::Value` and from the object's text alike, with the legacy + /// forks' keys beside it read by nobody here. + #[test] + fn test_the_key_round_trips() { + assert_eq!(serde_json::to_string(&config()).unwrap(), r#"{"satinTime":1800000000}"#); + assert_eq!(SATIN_CHAIN_CONFIG_KEYS, [SATIN_TIME_KEY]); + + assert_eq!(parse(&genesis_config()), Ok(Some(config()))); + let text = genesis_config().to_string(); + assert_eq!( + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&text)), + Ok(Some(config())) + ); + } + + /// The schedule the configuration makes runs Satin from its activation and passes the + /// schedule's own check. + #[test] + fn test_the_schedule_activates_satin() { + let schedule = config().hardforks().unwrap(); + assert_eq!(schedule.spec_id(ACTIVATION - 1), None); + assert_eq!(schedule.spec_id(ACTIVATION), Some(MegaSpecId::SATIN)); + assert_eq!(schedule.validate_schedule(), Ok(())); + } + + /// A configuration without a Satin key does not activate Satin. One whose only Satin key is + /// not `satinTime` is refused for that key. + #[test] + fn test_without_satin_time() { + let mut other_forks = genesis_config(); + other_forks.as_object_mut().unwrap().remove(SATIN_TIME_KEY); + assert_eq!(parse(&other_forks), Ok(None)); + assert_eq!(parse(&json!({})), Ok(None)); + + let mut without_time = other_forks; + without_time.as_object_mut().unwrap().insert("satinInitialSequencer".into(), json!("0x22")); + assert_eq!( + parse(&without_time), + Err(SatinChainConfigError::UnknownKey("satinInitialSequencer".into())) + ); + } + + /// Every key of the format's earlier versions is refused by name, beside `satinTime` or + /// without it, whatever its value: a file written against one does not load. + #[test] + fn test_the_old_keys_are_refused() { + for key in OLD_KEYS { + for with_time in [true, false] { + let mut config = genesis_config(); + if !with_time { + config.as_object_mut().unwrap().remove(SATIN_TIME_KEY); + } + config.as_object_mut().unwrap().insert(key.into(), json!(1)); + assert_eq!( + parse(&config), + Err(SatinChainConfigError::UnknownKey(key.into())), + "{key}, satinTime given: {with_time}" + ); + } + } + } + + /// A key that starts with `satin`, in any case, and is not `satinTime` is refused, so a + /// misspelling cannot stand in for the key it meant; a key that does not is another fork's. + #[test] + fn test_an_unknown_satin_key_is_refused() { + for unknown in [ + "satinTxDataSizeLimt", + "SatinTime", + "SATINTIME", + "satin", + "satinParams", + "satin_time", + "satinProtocolLimits", + ] { + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert(unknown.into(), json!({ "txDataSizeLimit": 1 })); + assert_eq!( + parse(&config), + Err(SatinChainConfigError::UnknownKey(unknown.into())), + "{unknown}" + ); + } + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert("sAtIn".into(), json!(1)); + assert_eq!(parse(&config), Err(SatinChainConfigError::UnknownKey("sAtIn".into()))); + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert("xsatinTime".into(), json!("anything")); + config.as_object_mut().unwrap().insert("sati".into(), json!(1)); + assert_eq!(parse(&config), Ok(Some(super::tests::config())), "another fork's keys"); + } + + /// A `satinTime` that is not an integer from 0 to 2^64 - 1 is refused, naming the key; both + /// ends of the range are read. + #[test] + fn test_a_value_out_of_range_or_of_the_wrong_type_is_refused() { + let with_time = |value: Value| { + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert(SATIN_TIME_KEY.into(), value); + parse(&config) + }; + assert_eq!(with_time(json!(0)).unwrap().unwrap().activation_time, 0); + assert_eq!(with_time(json!(u64::MAX)).unwrap().unwrap().activation_time, u64::MAX); + let refused = Err(SatinChainConfigError::InvalidValue { + key: SATIN_TIME_KEY, + expected: "an integer from 0 to 2^64 - 1", + }); + let text = genesis_config().to_string(); + let past_max = text.replacen("1800000000", "18446744073709551616", 1); + assert_eq!( + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str( + &past_max + )), + refused, + "2^64" + ); + for value in [ + json!("1800000000"), + json!(-1), + json!(1.5), + json!(1e20), + json!(null), + json!(true), + json!([1]), + json!({ "value": 1 }), + json!("0x4"), + ] { + assert_eq!(with_time(value.clone()), refused, "{value}"); + } + } + + /// A key given twice is refused where the deserializer shows both, as in the object's text; a + /// `serde_json::Value` has already kept the last one, and a key of another fork given twice is + /// not read. + #[test] + fn test_a_key_given_twice_is_refused() { + let text = genesis_config().to_string(); + let twice = text.replacen("\"satinTime\":", "\"satinTime\":1,\"satinTime\":", 1); + assert_eq!( + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&twice)), + Err(SatinChainConfigError::DuplicateKey(SATIN_TIME_KEY.into())) + ); + let other = text.replacen("\"chainId\":", "\"chainId\":1,\"chainId\":", 1); + assert_eq!( + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&other)), + Ok(Some(config())) + ); + } + + /// A number `serde_json` hands over as its `arbitrary_precision` feature does — a map from + /// its token to the number's text — reads as the number, and what the text does not hold as + /// an integer in 64 bits is refused as the number would be; any other map is refused. + #[test] + fn test_an_arbitrary_precision_number_reads_as_the_number() { + let with_time = |value: Value| { + let mut config = genesis_config(); + config.as_object_mut().unwrap().insert(SATIN_TIME_KEY.into(), value); + parse(&config) + }; + let number = |text: &str| json!({ ARBITRARY_PRECISION_NUMBER: text }); + assert_eq!(with_time(number("1800000000")), Ok(Some(config()))); + let max = with_time(number("18446744073709551615")).unwrap().unwrap(); + assert_eq!(max.activation_time, u64::MAX); + let refused = Err(SatinChainConfigError::InvalidValue { + key: SATIN_TIME_KEY, + expected: "an integer from 0 to 2^64 - 1", + }); + for text in ["1.5", "-1", "18446744073709551616", "1e3"] { + assert_eq!(with_time(number(text)), refused, "{text}"); + } + let mut two = number("1"); + two.as_object_mut().unwrap().insert("more".into(), json!(1)); + assert_eq!(with_time(two), refused); + assert_eq!(with_time(json!({ "value": 1 })), refused); + } + + /// Anything but an object is refused, saying an object was expected. + #[test] + fn test_a_configuration_that_is_not_an_object_is_refused() { + for config in [json!([]), json!(1), json!("config"), json!(null)] { + match parse(&config) { + Err(SatinChainConfigError::Malformed(message)) => assert!( + message.contains("expected a chain configuration object"), + "{config}: {message}" + ), + other => panic!("{config}: {other:?}"), + } + } + } + + /// A deserializer other than `serde_json`'s can hand a key a value no JSON document holds, a + /// byte array: the configuration is refused as malformed, saying what was expected. + #[test] + fn test_a_value_no_json_holds_is_refused_as_malformed() { + use serde::de::value::{Error, MapDeserializer}; + let entries = [(SATIN_TIME_KEY, &b"\x01"[..])]; + let config = MapDeserializer::<_, Error>::new(entries.into_iter()); + match SatinChainConfig::from_genesis_config(config) { + Err(SatinChainConfigError::Malformed(message)) => { + assert!(message.contains("expected any value"), "{message}") + } + other => panic!("{other:?}"), + } + } + + /// The errors read as what went wrong, naming the key. + #[test] + fn test_the_errors_name_the_key() { + assert_eq!( + SatinChainConfigError::UnknownKey("satinTme".into()).to_string(), + "`satinTme` is not a Satin chain-configuration key" + ); + assert_eq!( + SatinChainConfigError::InvalidValue { key: "satinTime", expected: "an integer" } + .to_string(), + "`satinTime` must be an integer" + ); + assert_eq!( + SatinChainConfigError::DuplicateKey("satinTime".into()).to_string(), + "`satinTime` is given twice" + ); + } +} diff --git a/crates/mega-evm/src/block/hardfork.rs b/crates/mega-evm/src/block/hardfork.rs index bc9f8acd0..13dc8cfb7 100644 --- a/crates/mega-evm/src/block/hardfork.rs +++ b/crates/mega-evm/src/block/hardfork.rs @@ -8,8 +8,8 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::{any::Any, fmt}; -use std::{boxed::Box, string::String, sync::Arc, vec, vec::Vec}; +use core::fmt; +use std::{boxed::Box, vec, vec::Vec}; use alloy_hardforks::{hardfork, EthereumHardfork, EthereumHardforks, ForkCondition, Hardfork}; use alloy_op_hardforks::{OpHardfork, OpHardforks}; @@ -18,11 +18,34 @@ use auto_impl::auto_impl; use crate::MegaSpecId; +/// The Ethereum forks Satin runs on that a schedule activates by timestamp: every one from the +/// first after the Merge up to Osaka. +const SATIN_BASE_ETHEREUM_FORKS: [EthereumHardfork; 4] = [ + EthereumHardfork::Shanghai, + EthereumHardfork::Cancun, + EthereumHardfork::Prague, + EthereumHardfork::Osaka, +]; + +/// The Optimism forks Satin runs on that a schedule activates by timestamp: every one from the +/// first after Bedrock up to Karst. +const SATIN_BASE_OP_FORKS: [OpHardfork; 9] = [ + OpHardfork::Regolith, + OpHardfork::Canyon, + OpHardfork::Ecotone, + OpHardfork::Fjord, + OpHardfork::Granite, + OpHardfork::Holocene, + OpHardfork::Isthmus, + OpHardfork::Jovian, + OpHardfork::Karst, +]; + hardfork! { /// `MegaETH` network upgrades that schedule a Satin-engine spec. It is expected to mix with /// `EthereumHardfork` and `OpHardfork`. /// - /// The forks of the legacy engine (`MiniRex` through `Rex7`) are not variants here; a chain + /// The forks of the legacy engine (`MiniRex` through `Rex6`) are not variants here; a chain /// runs them on the legacy engine up to the Satin activation. #[derive(serde::Serialize, serde::Deserialize)] MegaHardfork { @@ -40,43 +63,6 @@ impl MegaHardfork { } } -/// An invalid value of a [`HardforkParams`] type, as its -/// [`validate`](HardforkParams::validate) reports it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct HardforkParamsError { - /// Which field or invariant is wrong. - pub message: String, -} - -impl fmt::Display for HardforkParamsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.message) - } -} - -impl core::error::Error for HardforkParamsError {} - -/// Parameters a fork needs from the chain configuration. -/// -/// A params type belongs to exactly one fork ([`FORK`](Self::FORK)), so -/// [`fork_params`](MegaHardforks::fork_params) returns it without the caller naming the fork -/// twice. [`validate`](Self::validate) states the invariants of the value itself; -/// [`MegaHardforkConfig::with_params`] runs it when the configuration is built, so a bad value -/// fails at load. A fork that cannot run without its parameters also registers the requirement in -/// [`validate_schedule`](MegaHardforks::validate_schedule). -pub trait HardforkParams: Any + fmt::Debug + Send + Sync { - /// The hardfork these parameters belong to. - const FORK: MegaHardfork; - - /// How [`ScheduleError::MissingParams`] names this type. - const NAME: &'static str; - - /// Checks the invariants of this value. The default accepts anything. - fn validate(&self) -> Result<(), HardforkParamsError> { - Ok(()) - } -} - /// Extends [`OpHardforks`] with the `MegaETH` forks. /// /// Satin is the only `MegaETH` fork, so a schedule answers two questions: whether the chain has @@ -89,16 +75,6 @@ pub trait MegaHardforks: OpHardforks { /// carry it. fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition; - /// The parameters attached to `fork`, type-erased. Forks without parameters answer `None`. - fn fork_params_any(&self, _fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - None - } - - /// The parameters of the fork `P` belongs to, or `None` when the schedule carries none. - fn fork_params(&self) -> Option<&P> { - self.fork_params_any(P::FORK)?.downcast_ref::

() - } - /// The latest `MegaETH` fork active at `timestamp`, or `None` before the first one. /// /// Resolution reads raw activation events and walks [`MegaHardfork::VARIANTS`] from the top, @@ -122,6 +98,17 @@ pub trait MegaHardforks: OpHardforks { self.mega_fork_activation(MegaHardfork::Satin).active_at_timestamp(timestamp) } + /// Whether the block at `block_timestamp`, whose parent is at `parent_timestamp`, is the one + /// in which Satin activates: Satin is active at the block and not at its parent. + /// + /// A chain whose schedule has Satin from genesis has no such block, and neither does a + /// schedule that never activates it. A block that follows a gap in the timestamps is the + /// activation block when the activation falls in the gap. + fn is_satin_activation_block(&self, parent_timestamp: u64, block_timestamp: u64) -> bool { + self.is_satin_active_at_timestamp(block_timestamp) && + !self.is_satin_active_at_timestamp(parent_timestamp) + } + /// Whether the block at `block_timestamp`, whose parent is at `parent_timestamp`, admits /// only deposit transactions. /// @@ -137,19 +124,6 @@ pub trait MegaHardforks: OpHardforks { }) || self.is_no_user_tx_activation_block(parent_timestamp, block_timestamp) } - /// Refuses a schedule that activates `P::FORK` without attaching `P`. - /// - /// This is the rule [`validate_schedule`](Self::validate_schedule) applies to every params - /// type a fork requires; it is public so a params type can be checked on its own. - fn require_params(&self) -> Result<(), ScheduleError> { - if self.mega_fork_activation(P::FORK) != ForkCondition::Never && - self.fork_params::

().is_none() - { - return Err(ScheduleError::MissingParams { fork: P::FORK, params: P::NAME }); - } - Ok(()) - } - /// Checks that this schedule is one a chain can run, so a configuration mistake is caught /// when the chain configuration is loaded rather than at the fork's first block. /// @@ -158,10 +132,12 @@ pub trait MegaHardforks: OpHardforks { /// - Every registered `MegaETH` fork activates by [`ForkCondition::Timestamp`] (or is /// [`ForkCondition::Never`]). Resolution is timestamp-scoped, so a block-number or /// total-difficulty condition would silently never activate the fork. - /// - The parameters every scheduled fork requires are attached - /// ([`require_params`](Self::require_params)). Satin requires none yet: a mechanism that - /// brings a [`HardforkParams`] type registers it here, in the block marked below, and the - /// requirement is enforced from that change on. + /// - Every fork Satin runs on that the schedule activates by timestamp — the Ethereum forks + /// from Shanghai to Osaka and the Optimism forks from Regolith to Karst — is active at + /// Satin's activation, so the engine and the rest of the node, which reads the same schedule, + /// do not apply different rules to one block. The other half of that timing rule, that + /// Jovian, Karst and Osaka do not activate before Satin, is the node's to check: before Satin + /// the chain runs its pre-Satin engine, which this crate does not execute. /// /// There is no ordering or gap check: a single fork has nothing to be out of order with. The /// spec that follows Satin brings the ladder back, and with it those checks. @@ -173,10 +149,42 @@ pub trait MegaHardforks: OpHardforks { } } - // Required parameters, one `self.require_params::

()?` per params type. Satin has none. + require_base_forks(self) + } +} - Ok(()) +/// Refuses a schedule that activates Satin at a timestamp at which a fork it runs on is not +/// active: the half of the timing rule +/// [`validate_schedule`](MegaHardforks::validate_schedule) states that the engine checks. +/// +/// The forks checked are those a schedule activates by timestamp, the Ethereum forks from Shanghai +/// to Osaka and the Optimism forks from Regolith to Karst, each read as block execution reads +/// it: active at Satin's activation timestamp. A fork scheduled by block number or total +/// difficulty instead, or not at all, is not active at any timestamp, and is refused. The forks +/// up to the Merge, and Bedrock, are scheduled by block number or total difficulty, which a +/// timestamp cannot be compared with, and every one of them precedes the first fork scheduled +/// by timestamp; they are not checked. A schedule that does not activate Satin is not checked +/// either. +fn require_base_forks(schedule: &H) -> Result<(), ScheduleError> { + let ForkCondition::Timestamp(satin_time) = schedule.mega_fork_activation(MegaHardfork::Satin) + else { + return Ok(()); + }; + let ethereum = SATIN_BASE_ETHEREUM_FORKS + .iter() + .map(|fork| (fork.name(), schedule.ethereum_fork_activation(*fork))); + let op = + SATIN_BASE_OP_FORKS.iter().map(|fork| (fork.name(), schedule.op_fork_activation(*fork))); + for (base, condition) in ethereum.chain(op) { + if !condition.active_at_timestamp(satin_time) { + return Err(ScheduleError::InactiveBaseFork { + fork: MegaHardfork::Satin, + activation: satin_time, + base, + }); + } } + Ok(()) } /// A schedule a chain cannot run, as [`MegaHardforks::validate_schedule`] reports it. @@ -188,12 +196,14 @@ pub enum ScheduleError { /// The fork with the wrong condition. fork: MegaHardfork, }, - /// A scheduled fork requires parameters that the schedule does not carry. - MissingParams { + /// A fork a scheduled `MegaETH` fork runs on is not active when that fork activates. + InactiveBaseFork { /// The scheduled fork. fork: MegaHardfork, - /// The required params type, as [`HardforkParams::NAME`] names it. - params: &'static str, + /// The timestamp it activates at. + activation: BlockTimestamp, + /// The fork it runs on that is not active then, as [`Hardfork::name`] names it. + base: &'static str, }, } @@ -203,10 +213,11 @@ impl fmt::Display for ScheduleError { Self::NonTimestampActivation { fork } => { write!(f, "hardfork {fork:?} must activate by timestamp, not block number or TTD") } - Self::MissingParams { fork, params } => { + Self::InactiveBaseFork { fork, activation, base } => { write!( f, - "hardfork {fork:?} is scheduled but its {params} params are not configured" + "hardfork {fork:?} activates at timestamp {activation}, where the {base} fork \ + it runs on is not active" ) } } @@ -215,25 +226,24 @@ impl fmt::Display for ScheduleError { impl core::error::Error for ScheduleError {} -/// One fork of a schedule: which fork, when it activates, and the parameters it carries. +/// One fork of a schedule: which fork, and when it activates. #[derive(Debug)] struct ForkEntry { fork: Box, condition: ForkCondition, - params: Option>, } impl Clone for ForkEntry { fn clone(&self) -> Self { - Self { fork: self.fork.clone(), condition: self.condition, params: self.params.clone() } + Self { fork: self.fork.clone(), condition: self.condition } } } /// A chain's hardfork schedule. /// /// [`new`](Self::new) activates every Ethereum and Optimism fork up to and including the base -/// Satin runs on (Osaka / Karst) at genesis, and no `MegaETH` fork: those the caller schedules, -/// with [`with`](Self::with) or [`with_all_activated`](Self::with_all_activated). +/// Satin runs on (Osaka / Karst) from the first block, and no `MegaETH` fork: those the caller +/// schedules, with [`with`](Self::with) or [`with_all_activated`](Self::with_all_activated). #[derive(Debug, Clone)] pub struct MegaHardforkConfig { entries: Vec, @@ -256,7 +266,6 @@ where .map(|(fork, condition)| ForkEntry { fork: Box::new(fork) as Box, condition, - params: None, }) .collect(), } @@ -264,12 +273,13 @@ where } impl MegaHardforkConfig { - /// A schedule with every Ethereum and Optimism fork up to Osaka / Karst active at genesis, - /// and no `MegaETH` fork. + /// A schedule with every Ethereum and Optimism fork up to Osaka / Karst active from the first + /// block, and no `MegaETH` fork. /// /// Karst is the base [`MegaSpecId::SATIN`] runs on, so a chain executing Satin has already /// passed every fork below it; the schedule states that rather than leaving the node to - /// repeat it. + /// repeat it. A chain that ran the legacy forks activated them later than its first block, by + /// Satin's activation, which no Satin block can tell apart from the first block. pub fn new() -> Self { let forks: Vec<(Box, ForkCondition)> = vec![ (EthereumHardfork::Frontier.boxed(), ForkCondition::Block(0)), @@ -309,7 +319,7 @@ impl MegaHardforkConfig { Self { entries: forks .into_iter() - .map(|(fork, condition)| ForkEntry { fork, condition, params: None }) + .map(|(fork, condition)| ForkEntry { fork, condition }) .collect(), } } @@ -322,32 +332,6 @@ impl MegaHardforkConfig { self } - /// Attaches `params` to the fork they belong to. - /// - /// # Panics - /// - /// If the fork is not registered in this schedule, or if `params.validate()` refuses the - /// value — a chain configuration is built once, at load, and a bad one must not start. - pub fn with_params(mut self, params: P) -> Self { - if let Err(e) = params.validate() { - panic!("Invalid params for fork {:?}: {}", P::FORK, e.message); - } - let entry = self - .entries - .iter_mut() - .find(|entry| entry.fork.name() == P::FORK.name()) - .unwrap_or_else(|| { - panic!( - "Cannot attach params to fork {:?}: fork not registered in config. \ - Call .with({:?}, condition) first.", - P::FORK, - P::FORK, - ) - }); - entry.params = Some(Arc::new(params)); - self - } - /// Removes a `MegaETH` fork, which is what [`ForkCondition::Never`] means. pub fn without(mut self, hardfork: MegaHardfork) -> Self { self.entries.retain(|entry| entry.fork.name() != hardfork.name()); @@ -360,14 +344,13 @@ impl MegaHardforkConfig { self } - /// Adds `hardfork` with `condition`. An entry that is already there keeps its parameters and - /// takes the new condition. + /// Adds `hardfork` with `condition`. An entry that is already there takes the new condition. pub fn insert(&mut self, hardfork: impl Hardfork, condition: ForkCondition) { let index = self.entries.iter().position(|entry| entry.fork.name() == hardfork.name()); if let Some(index) = index { self.entries[index].condition = condition; } else { - self.entries.push(ForkEntry { fork: Box::new(hardfork), condition, params: None }); + self.entries.push(ForkEntry { fork: Box::new(hardfork), condition }); } } @@ -396,44 +379,13 @@ impl MegaHardforks for MegaHardforkConfig { fn mega_fork_activation(&self, fork: MegaHardfork) -> ForkCondition { self.get(fork).copied().unwrap_or(ForkCondition::Never) } - - fn fork_params_any(&self, fork: MegaHardfork) -> Option<&(dyn Any + Send + Sync)> { - self.entries - .iter() - .find(|entry| entry.fork.name() == fork.name()) - .and_then(|entry| entry.params.as_deref()) - } } #[cfg(test)] mod tests { use super::*; - use alloy_primitives::address; use core::str::FromStr; - /// A params type of this test module alone: the fork-requires-params rule is a mechanism - /// here, and Satin has no params type of its own yet. - #[derive(Clone, Debug, PartialEq, Eq)] - struct TestParams { - sequencer: alloy_primitives::Address, - } - - impl HardforkParams for TestParams { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "TestParams"; - - fn validate(&self) -> Result<(), HardforkParamsError> { - if self.sequencer.is_zero() { - return Err(HardforkParamsError { message: "sequencer must be set".into() }); - } - Ok(()) - } - } - - fn params() -> TestParams { - TestParams { sequencer: address!("0x2222222222222222222222222222222222222222") } - } - #[test] fn test_satin_fork_schedules_the_satin_spec() { assert_eq!(MegaHardfork::VARIANTS, &[MegaHardfork::Satin]); @@ -445,7 +397,7 @@ mod tests { #[test] fn test_legacy_fork_names_do_not_parse() { assert_eq!(MegaHardfork::from_str("Satin").unwrap(), MegaHardfork::Satin); - for legacy in ["MiniRex", "MiniRex1", "MiniRex2", "Rex", "Rex1", "Rex6", "Rex7"] { + for legacy in ["MiniRex", "MiniRex1", "MiniRex2", "Rex", "Rex1", "Rex6"] { assert!(MegaHardfork::from_str(legacy).is_err(), "{legacy} must not parse"); } } @@ -469,7 +421,6 @@ mod tests { assert_eq!(config.op_fork_activation(OpHardfork::Isthmus), ForkCondition::Timestamp(0)); assert_eq!(config.op_fork_activation(OpHardfork::Karst), ForkCondition::Timestamp(0)); assert_eq!(config.mega_fork_activation(MegaHardfork::Satin), ForkCondition::Never); - assert!(config.fork_params::().is_none()); } #[test] @@ -514,51 +465,6 @@ mod tests { } } - #[test] - fn test_fork_params_typed_access() { - let config = MegaHardforkConfig::default() - .with(MegaHardfork::Satin, ForkCondition::Timestamp(0)) - .with_params(params()); - - let retrieved = config.fork_params::().expect("params were attached"); - assert_eq!(retrieved, ¶ms()); - } - - #[test] - fn test_fork_params_none_when_not_configured() { - let config = - MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); - - assert!(config.fork_params::().is_none()); - } - - #[test] - fn test_default_validate_accepts_any_value() { - #[derive(Debug)] - struct NullParams; - - impl HardforkParams for NullParams { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "NullParams"; - } - - assert!(NullParams.validate().is_ok()); - } - - #[test] - fn test_hardfork_params_error_display() { - let e = HardforkParamsError { message: "something went wrong".into() }; - assert_eq!(e.to_string(), "something went wrong"); - } - - #[test] - #[should_panic(expected = "Invalid params for fork")] - fn test_with_params_panics_on_validation_error() { - MegaHardforkConfig::default() - .with_all_activated() - .with_params(TestParams { sequencer: alloy_primitives::Address::ZERO }); - } - /// Documented domain limit: resolution is timestamp-scoped, so a `MegaHardfork` registered by /// block number never contributes its spec. `validate_schedule` rejects such a schedule at /// load rather than leaving the fork silently inactive. @@ -578,28 +484,6 @@ mod tests { ); } - /// A scheduled fork whose required params are missing fails at validation time instead of at - /// the first block of the fork. - #[test] - fn test_validate_schedule_requires_scheduled_fork_params() { - let unscheduled = MegaHardforkConfig::default(); - assert_eq!(unscheduled.require_params::(), Ok(())); - - let no_params = MegaHardforkConfig::default().with_all_activated(); - assert_eq!( - no_params.require_params::(), - Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "TestParams" }) - ); - assert_eq!( - no_params.require_params::().unwrap_err().to_string(), - "hardfork Satin is scheduled but its TestParams params are not configured" - ); - - let with_params = no_params.with_params(params()); - assert_eq!(with_params.require_params::(), Ok(())); - assert_eq!(with_params.validate_schedule(), Ok(())); - } - /// The block a fork activates in carries the chain's own transactions only, and only that /// block: the one before it and the ones after it are ordinary. #[test] @@ -613,6 +497,34 @@ mod tests { assert!(!config.admits_only_deposits(100, 101), "and not once the parent had it too"); } + /// Satin's activation block is the block at which Satin is active and at whose parent it is + /// not: the first block at the activation, and the first after a gap over it; not the block + /// after it, nor any block of a chain with Satin from genesis or without Satin. An Optimism + /// fork's activation block, which admits only deposits too, is not Satin's. + #[test] + fn test_satin_activation_block_follows_the_parent_timestamp() { + let satin_at = |timestamp| { + MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(timestamp)) + }; + let config = satin_at(100); + assert!(config.is_satin_activation_block(99, 100), "the activation block"); + assert!(config.is_satin_activation_block(90, 105), "the first block after a gap over it"); + assert!(!config.is_satin_activation_block(100, 101), "the block after it"); + assert!(!config.is_satin_activation_block(98, 99), "a block before it"); + + let genesis = satin_at(0); + assert!(!genesis.is_satin_activation_block(0, 1), "Satin from genesis has none"); + assert!(!genesis.is_satin_activation_block(99, 100)); + assert!(!MegaHardforkConfig::default().is_satin_activation_block(99, 100), "nor no Satin"); + + let jovian = genesis + .with(OpHardfork::Jovian, ForkCondition::Timestamp(100)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(200)); + assert!(jovian.admits_only_deposits(99, 100), "Jovian's activation block is deposit-only"); + assert!(!jovian.is_satin_activation_block(99, 100), "but not Satin's activation block"); + } + #[test] fn test_hardfork_and_spec_id_follow_latest_active_timestamp() { let config = diff --git a/crates/mega-evm/src/block/l1_block_info.rs b/crates/mega-evm/src/block/l1_block_info.rs new file mode 100644 index 000000000..ed5989468 --- /dev/null +++ b/crates/mega-evm/src/block/l1_block_info.rs @@ -0,0 +1,183 @@ +//! The L1 block info a block's transactions are priced against, read before the block's +//! transactions and committed as a read-only state of its own. +//! +//! A non-deposit transaction is priced against the L1 block contract: op-revm reads the L1 base +//! fee, the Ecotone blob base fee and fee scalars, the L1 fee overhead when the scalars it finds +//! are empty, and the operator fee scalars, once per block, and block execution reads the DA +//! footprint gas scalar before every non-deposit transaction. Both read the block's state +//! directly, not through a transaction's journal, so the account and the slots they read land in +//! no transaction's returned state. A stateless witness built from the states the block commits +//! would miss them, and a validator re-executing the block from such a witness fails it with an +//! error: a read outside the witness is an error, not a zero to price with. +//! +//! [`read_l1_block_info`] reads the account and the slots before the block's transactions and +//! answers them as read-only entries, as the reads of the `SequencerRegistry`'s pending changes +//! are answered, and block execution commits them as a state of their own, so a witness built +//! from the committed states holds them. Without the read, such a witness holds them only as long +//! as two assumptions no check enforces hold: that the block starts with its L1 attributes +//! deposit, whose returned state names slots 1, 3, 7 and 8 because the deposit writes them, and +//! that the Ecotone scalars the deposit leaves are not both zero, since op-revm then reads the +//! overhead in slot 5, which nothing writes and no other state names. The read takes every slot +//! the pricing can read, whatever the contract holds before the block: op-revm makes its read at +//! the block's first non-deposit transaction, on the state the deposits before it left, so which +//! slots it reads is not decided by the state the block starts from. The entry may therefore +//! carry a slot the block does not read after all. The read loads the account and its slots into +//! the block's state cache and changes nothing: its commit hands a commit hook the read-only +//! entry and keeps no transition, and the transactions' own reads find the same values, or the +//! ones the block's L1 attributes deposit wrote over them. + +use alloy_primitives::U256; +use op_revm::constants::{ + ECOTONE_L1_BLOB_BASE_FEE_SLOT, ECOTONE_L1_FEE_SCALARS_SLOT, L1_BASE_FEE_SLOT, + L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, OPERATOR_FEE_SCALARS_SLOT, +}; +use revm::{ + state::{Account, EvmState, EvmStorageSlot, TransactionId}, + Database, +}; + +/// The slots of the L1 block contract a block's transactions can be priced against, in ascending +/// order: the L1 base fee (1), the Ecotone fee scalars (3), the L1 fee overhead (5), the Ecotone +/// blob base fee (7) and the operator fee scalars (8), which is also the slot of the DA footprint +/// gas scalar. +/// +/// The pricing reads the overhead only when the Ecotone scalars it finds are empty, and the +/// others always. The overhead is in the set all the same: the scalars the pricing finds are the +/// ones the block's deposits left, not the ones the block starts from. +pub const L1_BLOCK_INFO_SLOTS: [U256; 5] = [ + L1_BASE_FEE_SLOT, + ECOTONE_L1_FEE_SCALARS_SLOT, + L1_OVERHEAD_SLOT, + ECOTONE_L1_BLOB_BASE_FEE_SLOT, + OPERATOR_FEE_SCALARS_SLOT, +]; + +/// Reads the L1 block contract's account and every slot of [`L1_BLOCK_INFO_SLOTS`] from `db` and +/// answers them as a read-only state: the account as loaded, neither touched nor created, with +/// each slot as an unchanged entry; or, for a chain that does not hold the contract, the account +/// recorded as not existing and no slot read, since the slots of an absent account are zero +/// without a read. +/// +/// Every slot is read whatever the others hold, the overhead beside set scalars included. +/// +/// Nothing is committed here. Block execution commits the state on its own, which changes +/// nothing and hands a commit hook the read-only entry. +/// +/// # Errors +/// +/// The database's, when a read fails. +pub fn read_l1_block_info(db: &mut DB) -> Result { + let Some(info) = db.basic(L1_BLOCK_CONTRACT)? else { + let absent = Account::new_not_existing(TransactionId::ZERO); + return Ok(EvmState::from_iter([(L1_BLOCK_CONTRACT, absent)])); + }; + let mut account = Account::from(info); + for slot in L1_BLOCK_INFO_SLOTS { + let value = db.storage(L1_BLOCK_CONTRACT, slot)?; + account.storage.insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); + } + Ok(EvmState::from_iter([(L1_BLOCK_CONTRACT, account)])) +} + +#[cfg(test)] +mod tests { + use alloy_primitives::Bytes; + use op_revm::constants::{ + BASE_FEE_SCALAR_OFFSET, BLOB_BASE_FEE_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, + }; + + use super::*; + use crate::test_utils::{ErrorInjectingDatabase, MemoryDatabase}; + + /// The Ecotone fee scalars word with a base fee scalar of 7 and a blob base fee scalar of 9, + /// at the offsets the pricing reads them from: scalars that are set. + fn scalars() -> U256 { + let mut word = [0_u8; 32]; + word[BASE_FEE_SCALAR_OFFSET + 3] = 7; + word[BLOB_BASE_FEE_SCALAR_OFFSET + 3] = 9; + U256::from_be_bytes(word) + } + + /// The value the chain holds in every slot of the set: a distinct non-zero value, with + /// `scalars` at the scalars slot. + fn values(scalars: U256) -> [(U256, U256); 5] { + let mut values = L1_BLOCK_INFO_SLOTS.map(|slot| (slot, slot + U256::from(1_000))); + values[1] = (ECOTONE_L1_FEE_SCALARS_SLOT, scalars); + values + } + + /// A chain holding the L1 block contract with [`values`]. + fn chain(scalars: U256) -> MemoryDatabase { + let mut db = MemoryDatabase::default(); + db.set_account_code(L1_BLOCK_CONTRACT, Bytes::from(vec![0x00])); + for (slot, value) in values(scalars) { + db.set_account_storage(L1_BLOCK_CONTRACT, slot, value); + } + db + } + + /// The set is the five slots the pricing can read: it names the footprint slot and the + /// overhead, holds no slot twice and is ascending. + #[test] + fn test_the_slots_are_distinct_ascending_and_hold_the_footprint_slot_and_the_overhead() { + assert_eq!(L1_BLOCK_INFO_SLOTS.map(|slot| slot.to::()), [1, 3, 5, 7, 8]); + assert!(L1_BLOCK_INFO_SLOTS.contains(&DA_FOOTPRINT_GAS_SCALAR_SLOT)); + assert!(L1_BLOCK_INFO_SLOTS.contains(&L1_OVERHEAD_SLOT)); + assert!(L1_BLOCK_INFO_SLOTS.windows(2).all(|pair| pair[0] < pair[1])); + } + + /// A held contract is answered as loaded and unchanged, with every slot of the set as an + /// unchanged entry holding the chain's value — the overhead among them — whether the scalars + /// are set or empty. + #[test] + fn test_a_held_contract_is_read_as_unchanged_entries_whatever_the_scalars_hold() { + for scalars in [scalars(), U256::ZERO] { + let mut db = chain(scalars); + let state = read_l1_block_info(&mut db).expect("the reads succeed"); + assert_eq!(state.len(), 1, "the L1 block contract alone"); + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(!account.is_touched(), "read, not written"); + assert!(!account.is_created()); + assert!(!account.is_loaded_as_not_existing()); + assert_eq!(account.info.code_hash, alloy_primitives::keccak256([0x00])); + assert_eq!(account.storage.len(), L1_BLOCK_INFO_SLOTS.len(), "the set, no more"); + for (slot, value) in values(scalars) { + let entry = account.storage.get(&slot).expect("in the set"); + assert_eq!(entry.original_value, value, "{slot}"); + assert!(!entry.is_changed(), "{slot} is unchanged"); + } + let overhead = &account.storage[&L1_OVERHEAD_SLOT]; + assert_eq!(overhead.original_value, U256::from(1_005), "scalars {scalars}"); + } + } + + /// A chain without the contract answers it as not existing and reads no slot: a slot read + /// would fail on this database. + #[test] + fn test_an_absent_contract_is_recorded_absent_and_no_slot_is_read() { + for slot in L1_BLOCK_INFO_SLOTS { + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + db.fail_on_storage = Some((L1_BLOCK_CONTRACT, slot)); + let state = read_l1_block_info(&mut db).expect("no slot is read"); + let account = &state[&L1_BLOCK_CONTRACT]; + assert!(account.is_loaded_as_not_existing()); + assert!(!account.is_touched()); + assert!(account.storage.is_empty()); + } + } + + /// A read the database cannot serve is the database's error: the account, or any slot of the + /// set — the overhead too, though the scalars are set. + #[test] + fn test_a_database_error_is_returned() { + let mut db = ErrorInjectingDatabase::new(chain(scalars())); + db.fail_on_account = Some(L1_BLOCK_CONTRACT); + assert!(read_l1_block_info(&mut db).is_err()); + + for slot in L1_BLOCK_INFO_SLOTS { + let mut db = ErrorInjectingDatabase::new(chain(scalars())); + db.fail_on_storage = Some((L1_BLOCK_CONTRACT, slot)); + assert!(read_l1_block_info(&mut db).is_err(), "slot {slot} of the set"); + } + } +} diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index f7459adad..52a91f768 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -1,8 +1,16 @@ //! What a block admits, and what it counts of the transactions it packed. //! -//! [`BlockLimits`] is the configuration a node passes in the block execution context; -//! [`BlockLimiter`] is the state one block keeps while it executes. Every limit defaults to -//! unlimited, so a caller that configures nothing gets op-revm's block rules and nothing else. +//! The limits come from two places, by who must agree on them: +//! +//! - [`ProtocolLimits`] are the limits every node holds a chain's blocks and transactions to, fixed +//! per spec: the per-transaction limits the EVM enforces and the block's data-size budget. +//! - [`BlockLimits`] is the building policy a node passes in the block execution context: the +//! limits only a builder applies — a transaction's declared gas, the encoded sizes and the +//! data-availability sizes — and a cap a builder may put on the block's data-size budget below +//! the protocol's. It never loosens a protocol limit ([`BlockLimits::within`]), and a validator +//! leaves it at its default, which restricts nothing. +//! +//! [`BlockLimiter`] is the state one block keeps while it executes, held to both. //! //! # When each limit is checked //! @@ -10,19 +18,41 @@ //! its own gas limit, encoded size and data-availability size, and what each of those would add //! to the block. //! -//! A limit only known after execution — the execution ledger and the data-size bytes a -//! transaction kept — is accumulated when the transaction commits and checked before the *next* -//! transaction starts. The transaction that crosses such a limit is therefore still packed, and -//! the ones after it are refused; this is what keeps a block full rather than dropping the work -//! already done. A block whose counter has crossed refuses every later transaction, so the -//! overshoot is bounded by one transaction per dimension. +//! The one limit only known after execution — the data-size bytes a transaction kept — is +//! accumulated when the transaction commits. The transaction that crosses it is therefore still +//! packed, and the ones after it are refused; this is what keeps a block full rather than dropping +//! the work already done. A block whose counter has reached its limit refuses every later +//! transaction before it starts — a deposit excepted — so the overshoot is bounded by one +//! transaction, besides what deposits add. +//! +//! # Deposits +//! +//! A deposit is an L1 message the chain cannot censor: the block derived from L1 must include it, +//! and the builder does not choose it. So no limit only a builder applies refuses a deposit — its +//! declared gas, its encoded size and its data-availability size, and what those add to the block +//! — and a deposit does not count towards the block's data-availability size. The data-size limit +//! is a packing budget for the transactions the builder chooses, so it does not refuse a deposit +//! either. A deposit still counts towards it, and towards the block's encoded size, so the +//! transactions after it find the room it used. The one limit that holds a deposit is +//! the block's gas limit, which is the header's. +//! +//! A Mega System Transaction, the protocol's own oracle update, which the sequencer must be able +//! to include whatever the block holds, is refused by none of those limits either and counts as a +//! deposit does. Its envelope is legacy, so it also counts towards the block's data-availability +//! size, and the data-availability footprint, which the executor checks, holds it. +//! +//! The per-transaction limits the block installs on the EVM are not block limits: they hold a +//! deposit's own execution the way they hold any transaction's, and a deposit that crosses one is +//! included with the stop as its result. //! //! # Which dimensions are enforced //! -//! Of the three gas ledgers the block counts ([`BlockGasCounters`]), only execution has a block -//! limit. History has none by design. The state ledger and the write-record count are -//! accumulated here and enforced by nobody: the state-gas block limit arrives with the -//! state-gas limits, and the write-record limit with the state-growth and KV limits. +//! The three gas ledgers the block counts ([`BlockGasCounters`]) have no block limit beside the +//! block's gas limit, the header's: state gas prices the state a block adds, so the block's gas +//! limit bounds it, and the history bytes beside the history ledger are reported, not limited. The +//! write-record count, which is the block's KV count, is reported and has no limit: every record +//! weighs forty bytes of data size, so a block held to +//! [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) keeps at most 327,680 records. use alloy_primitives::TxHash; @@ -33,60 +63,171 @@ use std::boxed::Box; use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ + constants::{ + BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, + }, BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, - MegaTxLimitExceededError, + MegaSpecId, MegaTxLimitExceededError, }; -/// The limits one block holds its transactions to. +/// The limits the protocol holds every block and every transaction to, fixed per spec. /// -/// [`no_limits`](Self::no_limits) is the neutral value every field starts from; a node sets the -/// ones its chain configures, and the block executor always sets -/// [`block_gas_limit`](Self::block_gas_limit) from the block environment. +/// Each of them changes what a validator computes when it re-executes a block, so they are not +/// configuration: [`for_spec`](Self::for_spec) is the one table of them, keyed by the spec a block +/// executes, and every node of every chain holds a block of that spec to the same values. Block +/// execution, the EVM factory and a bare [`MegaContext`](crate::MegaContext) read it, so an +/// execution outside a block — a call, a gas estimate, a simulation — is held to what block +/// execution holds it to without being told. +/// +/// - [`tx_runtime_limits`](Self::tx_runtime_limits) holds each transaction's own execution: a +/// transaction that crosses one is stopped, or a frame reverted, and that is the result its +/// receipt records. There is no tighter setting a builder could run a transaction under and still +/// agree with a validator; a builder that wants to avoid such a transaction leaves it out. +/// - The block's data-size budget holds what a block's transactions keep together. A validator +/// refuses a block that packs a transaction after the block reached it; a builder may pack +/// tighter ([`BlockLimits`]), never looser. +/// +/// A tool or a test that runs under other values says so explicitly +/// ([`MegaContext::with_tx_runtime_limits`](crate::MegaContext::with_tx_runtime_limits), +/// [`MegaEvmFactory::with_tx_runtime_limits`](crate::MegaEvmFactory::with_tx_runtime_limits), and +/// in block execution `MegaBlockExecutor::with_protocol_limits`, which exists for tests and tools +/// only); what it computes is then a counterfactual, not the chain's result. +/// +/// It serializes in the shape a tool takes an override in: camelCase, every field required, no +/// other field accepted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProtocolLimits { + /// The limits every transaction runs under, which the block executor installs on the EVM: + /// data size, per transaction and per frame, and gas detention's two caps. + pub tx_runtime_limits: EvmTxRuntimeLimits, + /// The most data-size bytes a block's transactions may keep together. The transaction that + /// reaches it is packed; after it, only a deposit is. + pub block_txs_data_limit: u64, +} + +impl ProtocolLimits { + /// The limits a block of `spec`, and every transaction in it, is held to. + /// + /// [`MegaSpecId::SATIN`]: a transaction keeps at most [`TX_DATA_LIMIT`] (13,107,200) bytes of + /// data size, and a block's transactions together at most [`BLOCK_DATA_LIMIT`] (13,107,200); + /// every frame gets 98/100 of what its parent has left, the transaction's own frame what the + /// transaction has left, with no further per-frame cap; a read of volatile data caps the + /// transaction's compute at its compute at the read plus [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] or + /// [`ORACLE_ACCESS_COMPUTE_GAS`] (20,000,000 each). Provisional, as the constants are, until + /// the economics sign-off fixes them. + /// + /// Every field is written out, so a limit added later cannot be left unlimited by omission. + pub const fn for_spec(spec: MegaSpecId) -> Self { + match spec { + MegaSpecId::SATIN => Self { + tx_runtime_limits: EvmTxRuntimeLimits { + tx_data_size_limit: TX_DATA_LIMIT, + frame_data_size_limit: u64::MAX, + block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, + oracle_access_compute_gas_limit: ORACLE_ACCESS_COMPUTE_GAS, + }, + block_txs_data_limit: BLOCK_DATA_LIMIT, + }, + } + } + + /// No limit at all, gas detention's caps included, so no transaction is detained + /// ([`EvmTxRuntimeLimits::no_limits`]). + /// + /// For runs that take every limit out — the execution-spec gate's equivalence mode and tests — + /// never for executing the chain. + pub const fn no_limits() -> Self { + Self { tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), block_txs_data_limit: u64::MAX } + } + + /// Sets the limits every transaction runs under. + pub const fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.tx_runtime_limits = limits; + self + } + + /// Sets the block's data-size limit. + pub const fn with_block_txs_data_limit(mut self, limit: u64) -> Self { + self.block_txs_data_limit = limit; + self + } +} + +/// The building policy one block is packed under: the limits only a builder applies, and the cap +/// it may put on the block's data-size budget below the protocol's. +/// +/// A node passes it in the block execution context. None of it is a protocol value: the +/// protocol's limits are [`ProtocolLimits`], which the block executor reads from the spec's +/// table, and this can only make a block tighter than they do ([`within`](Self::within)). So a +/// builder packs under it and a validator re-executing the block leaves it at [`Default`], which +/// restricts nothing: every block a builder packed under a policy fits the protocol's limits, and +/// a validator that applied the builder's policy too would only refuse blocks, never accept one +/// the protocol refuses. +/// +/// - [`tx_gas_limit`](Self::tx_gas_limit), the two encoded-size limits and the two +/// data-availability size limits are the builder's alone: the protocol holds a transaction's +/// declared gas to the block's gas limit, and what a block writes to its data-size budget, which +/// counts calldata. +/// - [`block_txs_data_limit`](Self::block_txs_data_limit) is the builder's cap on the protocol's +/// data-size budget: the block executor holds a block to the smaller of the two. +/// +/// The block's gas limit is not here: it is the header's, which the block executor takes from the +/// block environment ([`BlockLimiter::block_gas_limit`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct BlockLimits { - /// The most gas a single transaction may declare. + /// The most gas a single transaction may declare. Deposits are exempt. pub tx_gas_limit: u64, - /// The block's gas limit: a transaction is admitted only if its declared gas limit fits in - /// what the block has left. Also the budget the data-availability footprint of the block's - /// transactions is held to. - pub block_gas_limit: u64, - /// The most bytes a single transaction's EIP-2718 encoding may take. + /// The most bytes a single transaction's EIP-2718 encoding may take. Deposits are exempt. pub tx_encode_size_limit: u64, - /// The most bytes the block's transaction bodies may take together, uncompressed. + /// The most bytes the block's transaction bodies may take together, uncompressed. Deposits are + /// exempt, and count towards it. pub block_txs_encode_size_limit: u64, /// The most data-availability bytes a single transaction may take. Deposits are exempt. pub tx_da_size_limit: u64, /// The most data-availability bytes the block's transactions may take together. Deposits are /// exempt and do not count towards it. pub block_da_size_limit: u64, - /// The most execution gas the block's transactions may spend together. - pub block_execution_gas_limit: u64, - /// The most data-size bytes the block's transactions may keep together. + /// The most data-size bytes the block's transactions may keep together. The transaction that + /// reaches it is packed; after it, only a deposit is, which it never refuses and which counts + /// towards it. + /// + /// A builder's cap: the block is held to the smaller of this and + /// [`ProtocolLimits::block_txs_data_limit`]. pub block_txs_data_limit: u64, - /// The limits every transaction of the block runs under, which the executor installs on the - /// EVM. - pub tx_runtime_limits: EvmTxRuntimeLimits, } impl Default for BlockLimits { + /// No restriction: what a validator passes. fn default() -> Self { Self::no_limits() } } impl BlockLimits { - /// No limit at all. + /// No restriction at all: every limit unlimited, so a block is held to the protocol's limits + /// alone. pub const fn no_limits() -> Self { Self { tx_gas_limit: u64::MAX, - block_gas_limit: u64::MAX, tx_encode_size_limit: u64::MAX, block_txs_encode_size_limit: u64::MAX, tx_da_size_limit: u64::MAX, block_da_size_limit: u64::MAX, - block_execution_gas_limit: u64::MAX, block_txs_data_limit: u64::MAX, - tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), + } + } + + /// These limits held within `protocol`: the block's data-size budget is the smaller of this + /// policy's cap and the protocol's limit, so a builder's setting can tighten the budget and + /// never loosen it. The limits only a builder applies are kept as they are. + /// + /// A cap above the protocol's limit gives way to it without a word; a node that wants to + /// refuse or report such a setting compares the two itself. + pub fn within(self, protocol: &ProtocolLimits) -> Self { + Self { + block_txs_data_limit: self.block_txs_data_limit.min(protocol.block_txs_data_limit), + ..self } } @@ -96,15 +237,6 @@ impl BlockLimits { self } - /// Sets the block's gas limit. - /// - /// The block executor overwrites it with the block environment's gas limit, which is the - /// number consensus holds the block to. - pub const fn with_block_gas_limit(mut self, limit: u64) -> Self { - self.block_gas_limit = limit; - self - } - /// Sets the per-transaction encoded-size limit. pub const fn with_tx_encode_size_limit(mut self, limit: u64) -> Self { self.tx_encode_size_limit = limit; @@ -129,41 +261,17 @@ impl BlockLimits { self } - /// Sets the block's execution-gas limit. - pub const fn with_block_execution_gas_limit(mut self, limit: u64) -> Self { - self.block_execution_gas_limit = limit; - self - } - - /// Sets the block's data-size limit. + /// Caps the block's data size. pub const fn with_block_txs_data_limit(mut self, limit: u64) -> Self { self.block_txs_data_limit = limit; self } - - /// Sets the limits every transaction of the block runs under. - pub const fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { - self.tx_runtime_limits = limits; - self - } - - /// The limits every transaction of the block runs under. - pub const fn to_evm_tx_runtime_limits(&self) -> EvmTxRuntimeLimits { - self.tx_runtime_limits - } - - /// A limiter that holds a block to these limits. - pub const fn to_block_limiter(self) -> BlockLimiter { - BlockLimiter::new(self) - } } /// What one committed transaction adds to a block's counters. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct BlockUsage { - /// The gas the receipt reports. - pub gas_used: u64, - /// The gas by ledger. + /// The gas by ledger, and the gas the receipt reports ([`MegaGasUsage::gas_used`]). pub gas: MegaGasUsage, /// The data-size bytes and write records the transaction kept. pub usage: LimitUsage, @@ -173,7 +281,8 @@ pub struct BlockUsage { pub da_size: u64, /// The transaction's data-availability footprint, in gas. pub da_footprint: u64, - /// Whether the transaction is a deposit, which the data-availability dimensions exempt. + /// Whether the transaction is a deposit, which the data-availability dimensions exempt and + /// which no limit but the block's gas limit refuses. pub is_deposit: bool, } @@ -185,6 +294,11 @@ pub struct BlockUsage { pub struct BlockLimiter { /// The limits this block is held to. pub limits: BlockLimits, + /// The block's gas limit, the header's: a transaction is admitted only if its declared gas + /// limit fits in what the block has left, and it is also the budget the data-availability + /// footprint of the block's transactions is held to. The block executor takes it from the + /// block environment; it is no building policy. + pub block_gas_limit: u64, /// The gas the block's receipts report, which is the block header's gas used. pub block_gas_used: u64, /// The gas the block's transactions spent, by ledger. @@ -201,13 +315,15 @@ pub struct BlockLimiter { } impl BlockLimiter { - /// A limiter with every counter at zero. - pub const fn new(limits: BlockLimits) -> Self { + /// A limiter of a block whose gas limit is `block_gas_limit`, held to `limits`, with every + /// counter at zero. + pub const fn new(limits: BlockLimits, block_gas_limit: u64) -> Self { Self { limits, + block_gas_limit, block_gas_used: 0, - gas: BlockGasCounters { execution: 0, state: 0, history: 0 }, - usage: LimitUsage { data_size: 0, write_records: 0 }, + gas: BlockGasCounters { execution: 0, state: 0, history: 0, history_bytes: 0 }, + usage: LimitUsage::ZERO, block_tx_size_used: 0, block_da_size_used: 0, block_da_footprint_used: 0, @@ -216,20 +332,22 @@ impl BlockLimiter { /// The gas the block still has for a transaction's declared gas limit. pub const fn available_gas(&self) -> u64 { - self.limits.block_gas_limit.saturating_sub(self.block_gas_used) + self.block_gas_limit.saturating_sub(self.block_gas_used) } /// The data-availability footprint the block still has. The budget is the block's gas limit, /// as the fork's rule states it. pub const fn available_da_footprint(&self) -> u64 { - self.limits.block_gas_limit.saturating_sub(self.block_da_footprint_used) + self.block_gas_limit.saturating_sub(self.block_da_footprint_used) } /// Whether `tx` may execute in this block. /// - /// Checks the transaction against its own limits, and against what the block has left. It - /// reads the counters and changes nothing; - /// [`post_execution_update`](Self::post_execution_update) advances them once the + /// Checks the transaction against its own limits, and against what the block has left; a + /// transaction that is `packing_exempt` — a deposit, or a Mega System Transaction — is held to + /// the block's gas limit alone, to no limit only a builder applies and not to the data-size + /// limit. It reads the counters and changes nothing; + /// [`post_execution_update`](Self::post_execution_update) advances the counters once the /// transaction commits. /// /// # Errors @@ -244,9 +362,11 @@ impl BlockLimiter { gas_limit: u64, tx_size: u64, da_size: u64, - is_deposit: bool, + packing_exempt: bool, ) -> Result<(), BlockExecutionError> { - if gas_limit > self.limits.tx_gas_limit { + // Of the limits checked here, a packing-exempt transaction is held to the block's gas limit + // alone (see the module's documentation on deposits). + if !packing_exempt && gas_limit > self.limits.tx_gas_limit { return Err(invalid_tx( tx_hash, MegaTxLimitExceededError::TransactionGasLimit { @@ -256,7 +376,7 @@ impl BlockLimiter { )); } - if self.block_gas_used.saturating_add(gas_limit) > self.limits.block_gas_limit { + if self.block_gas_used.saturating_add(gas_limit) > self.block_gas_limit { return Err(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { transaction_gas_limit: gas_limit, block_available_gas: self.available_gas(), @@ -264,6 +384,12 @@ impl BlockLimiter { .into()); } + // Nothing below refuses a packing-exempt transaction; `post_execution_update` still counts + // it. + if packing_exempt { + return Ok(()); + } + if tx_size > self.limits.tx_encode_size_limit { return Err(invalid_tx( tx_hash, @@ -286,39 +412,23 @@ impl BlockLimiter { )); } - // A deposit is an L1 message the chain cannot censor, so it is exempt from both - // data-availability limits and does not count towards the block's. - if !is_deposit { - if da_size > self.limits.tx_da_size_limit { - return Err(invalid_tx( - tx_hash, - MegaTxLimitExceededError::DataAvailabilitySizeLimit { - da_size, - limit: self.limits.tx_da_size_limit, - }, - )); - } - - if da_size.saturating_add(self.block_da_size_used) > self.limits.block_da_size_limit { - return Err(invalid_tx( - tx_hash, - MegaBlockLimitExceededError::DataAvailabilitySizeLimit { - block_used: self.block_da_size_used, - tx_used: da_size, - limit: self.limits.block_da_size_limit, - }, - )); - } + if da_size > self.limits.tx_da_size_limit { + return Err(invalid_tx( + tx_hash, + MegaTxLimitExceededError::DataAvailabilitySizeLimit { + da_size, + limit: self.limits.tx_da_size_limit, + }, + )); } - // The dimensions a transaction's own execution reveals: the transaction that crossed one - // is already packed, so what is refused here is the next one. - if self.gas.execution >= self.limits.block_execution_gas_limit { + if da_size.saturating_add(self.block_da_size_used) > self.limits.block_da_size_limit { return Err(invalid_tx( tx_hash, - MegaBlockLimitExceededError::ExecutionGasLimit { - block_used: self.gas.execution, - limit: self.limits.block_execution_gas_limit, + MegaBlockLimitExceededError::DataAvailabilitySizeLimit { + block_used: self.block_da_size_used, + tx_used: da_size, + limit: self.limits.block_da_size_limit, }, )); } @@ -333,9 +443,8 @@ impl BlockLimiter { )); } - // `self.gas.state`, `self.gas.history` and `self.usage.write_records` are accumulated and - // not checked: history has no block limit, the state-gas block limit arrives with the - // state-gas limits, and the write-record limit with the state-growth and KV limits. + // `self.gas` and `self.usage.write_records` are accumulated and not checked: none of them + // has a block limit. Ok(()) } @@ -345,11 +454,9 @@ impl BlockLimiter { /// Every counter saturates: a block that has already crossed a limit stays crossed, and the /// check before the next transaction sees it. pub fn post_execution_update(&mut self, usage: &BlockUsage) { - self.block_gas_used = self.block_gas_used.saturating_add(usage.gas_used); + self.block_gas_used = self.block_gas_used.saturating_add(usage.gas.gas_used); self.gas.record(&usage.gas); - self.usage.data_size = self.usage.data_size.saturating_add(usage.usage.data_size); - self.usage.write_records = - self.usage.write_records.saturating_add(usage.usage.write_records); + self.usage = self.usage.saturating_add(usage.usage); self.block_tx_size_used = self.block_tx_size_used.saturating_add(usage.tx_size); if !usage.is_deposit { self.block_da_size_used = self.block_da_size_used.saturating_add(usage.da_size); @@ -370,19 +477,160 @@ fn invalid_tx( #[cfg(test)] mod tests { use super::*; + use crate::{constants::MAX_TX_COMPUTE_GAS, TX_BODY_SIZE}; use alloy_primitives::B256; - fn limits_with_block_gas(block_gas_limit: u64) -> BlockLimits { - BlockLimits::no_limits().with_block_gas_limit(block_gas_limit).with_tx_gas_limit(u64::MAX) + /// Satin's limits, written out so a change to one is a visible diff: 13,107,200 bytes of data + /// size per transaction and per block, no per-frame cap beyond the 98/100 share, and + /// detention's caps at 20,000,000 each. + /// + /// They also hold what a chain configuration's load-time check used to hold a chain's values + /// to: no limit is zero, a transaction's data size holds at least a body, and both detention + /// caps are below the most compute a transaction can spend, so a read of volatile data is + /// detained. + #[test] + fn test_the_satin_limits_are_written_out() { + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert_eq!( + limits, + ProtocolLimits { + tx_runtime_limits: EvmTxRuntimeLimits { + tx_data_size_limit: 13_107_200, + frame_data_size_limit: u64::MAX, + block_env_access_compute_gas_limit: 20_000_000, + oracle_access_compute_gas_limit: 20_000_000, + }, + block_txs_data_limit: 13_107_200, + } + ); + + let EvmTxRuntimeLimits { + tx_data_size_limit, + frame_data_size_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, + } = limits.tx_runtime_limits; + for limit in [ + tx_data_size_limit, + frame_data_size_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, + limits.block_txs_data_limit, + ] { + assert_ne!(limit, 0); + } + assert!(tx_data_size_limit >= TX_BODY_SIZE, "a transaction's data size holds its body"); + assert!(block_env_access_compute_gas_limit < MAX_TX_COMPUTE_GAS, "a cap that binds"); + assert!(oracle_access_compute_gas_limit < MAX_TX_COMPUTE_GAS, "a cap that binds"); + } + + /// The limits serialize in the shape a tool takes an override in, written out here: camelCase, + /// the per-transaction limits nested. A field left out is an error rather than a zero, and so + /// is one the type does not have. + #[test] + fn test_protocol_limits_round_trip() { + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let limits = satin + .with_tx_runtime_limits(satin.tx_runtime_limits.with_frame_data_size_limit(1)) + .with_block_txs_data_limit(7); + + let json = serde_json::to_string(&limits).expect("serializes"); + assert_eq!( + json, + r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7}"# + ); + assert_eq!(serde_json::from_str::(&json).expect("deserializes"), limits); + + let missing = json.replace(r#","blockTxsDataLimit":7"#, ""); + assert!(serde_json::from_str::(&missing).is_err(), "{missing}"); + let missing_tx = json.replace(r#""frameDataSizeLimit":1,"#, ""); + assert!(serde_json::from_str::(&missing_tx).is_err(), "{missing_tx}"); + let unknown = json.replace(r#""blockTxsDataLimit":7"#, r#""blockTxsDataLimit":7,"x":1"#); + assert!(serde_json::from_str::(&unknown).is_err(), "{unknown}"); + } + + /// `no_limits` leaves every limit unlimited, detention's caps included. Every field is named, + /// so a limit added later cannot be left out of it. + #[test] + fn test_no_protocol_limits_leaves_every_limit_unlimited() { + let ProtocolLimits { tx_runtime_limits, block_txs_data_limit } = + ProtocolLimits::no_limits(); + assert_eq!(tx_runtime_limits, EvmTxRuntimeLimits::no_limits()); + assert_eq!(block_txs_data_limit, u64::MAX); + } + + /// The default building policy restricts nothing, so a validator that leaves it holds a block + /// to the protocol's limits alone. Every field is named, so a limit added later cannot be left + /// out of it. + #[test] + fn test_the_default_building_policy_restricts_nothing() { + assert_eq!(BlockLimits::default(), BlockLimits::no_limits()); + let BlockLimits { + tx_gas_limit, + tx_encode_size_limit, + block_txs_encode_size_limit, + tx_da_size_limit, + block_da_size_limit, + block_txs_data_limit, + } = BlockLimits::default(); + for limit in [ + tx_gas_limit, + tx_encode_size_limit, + block_txs_encode_size_limit, + tx_da_size_limit, + block_da_size_limit, + block_txs_data_limit, + ] { + assert_eq!(limit, u64::MAX); + } + assert_eq!( + BlockLimits::default() + .within(&ProtocolLimits::for_spec(MegaSpecId::SATIN)) + .block_txs_data_limit, + crate::constants::BLOCK_DATA_LIMIT, + "held within the protocol's, the default policy is the protocol's" + ); + } + + /// A builder's cap on the block's data-size budget holds the block only where it is below the + /// protocol's limit: it tightens, and never loosens. The limits only a builder applies pass + /// through. + #[test] + fn test_a_building_policy_tightens_a_budget_and_never_loosens_it() { + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_txs_data_limit(300); + + let tighter = BlockLimits::no_limits() + .with_block_txs_data_limit(30) + .with_tx_gas_limit(1) + .with_tx_encode_size_limit(2) + .with_block_txs_encode_size_limit(3) + .with_tx_da_size_limit(4) + .with_block_da_size_limit(5); + assert_eq!(tighter.within(&protocol), tighter, "every cap is below the protocol's"); + + let looser = BlockLimits::no_limits().with_block_txs_data_limit(3_000); + let held = looser.within(&protocol); + assert_eq!(held.block_txs_data_limit, 300, "a cap above the protocol's gives way to it"); + assert_eq!( + BlockLimits { tx_gas_limit: 7, ..held }, + BlockLimits { tx_gas_limit: 7, ..BlockLimits::no_limits().within(&protocol) }, + "nothing else changes" + ); + } + + /// A limiter of a block whose gas limit is `block_gas_limit`, under no building policy. + fn limiter_with_block_gas(block_gas_limit: u64) -> BlockLimiter { + BlockLimiter::new(BlockLimits::no_limits(), block_gas_limit) } fn saturated_usage() -> BlockUsage { BlockUsage { - gas_used: u64::MAX, gas: MegaGasUsage { + gas_used: u64::MAX, regular: u64::MAX, state: u64::MAX, history: u64::MAX, + history_bytes: u64::MAX, ..Default::default() }, usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX }, @@ -397,7 +645,7 @@ mod tests { fn test_pre_execution_check_block_gas_addition_saturates() { // Block has very high accumulated usage and a transaction with a near-`u64::MAX` // gas limit; unchecked addition would wrap and accidentally pass the limit check. - let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000_000)); + let mut limiter = limiter_with_block_gas(1_000_000); limiter.block_gas_used = u64::MAX - 10; let result = limiter.pre_execution_check(B256::ZERO, u64::MAX, 0, 0, false); assert!(result.is_err(), "saturating_add must keep the rejection in place"); @@ -405,8 +653,10 @@ mod tests { #[test] fn test_pre_execution_check_block_tx_size_addition_saturates() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_txs_encode_size_limit(1_000_000)); + let mut limiter = BlockLimiter::new( + BlockLimits::no_limits().with_block_txs_encode_size_limit(1_000_000), + u64::MAX, + ); limiter.block_tx_size_used = u64::MAX - 10; let result = limiter.pre_execution_check(B256::ZERO, 0, u64::MAX, 0, false); assert!(result.is_err()); @@ -414,8 +664,10 @@ mod tests { #[test] fn test_pre_execution_check_block_da_size_addition_saturates() { - let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_da_size_limit(1_000_000)); + let mut limiter = BlockLimiter::new( + BlockLimits::no_limits().with_block_da_size_limit(1_000_000), + u64::MAX, + ); limiter.block_da_size_used = u64::MAX - 10; let result = limiter.pre_execution_check(B256::ZERO, 0, 0, u64::MAX, false); assert!(result.is_err()); @@ -423,12 +675,13 @@ mod tests { #[test] fn test_post_execution_update_saturates_all_counters() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + let mut limiter = BlockLimiter::new(BlockLimits::no_limits(), u64::MAX); limiter.block_gas_used = u64::MAX - 1; limiter.gas = BlockGasCounters { execution: u64::MAX - 1, state: u64::MAX - 1, history: u64::MAX - 1, + history_bytes: u64::MAX - 1, }; limiter.usage = LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1 }; limiter.block_tx_size_used = u64::MAX - 1; @@ -440,7 +693,12 @@ mod tests { assert_eq!(limiter.block_gas_used, u64::MAX); assert_eq!( limiter.gas, - BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX } + BlockGasCounters { + execution: u64::MAX, + state: u64::MAX, + history: u64::MAX, + history_bytes: u64::MAX, + } ); assert_eq!(limiter.usage, LimitUsage { data_size: u64::MAX, write_records: u64::MAX }); assert_eq!(limiter.block_tx_size_used, u64::MAX); @@ -452,7 +710,7 @@ mod tests { fn test_post_execution_update_skips_da_for_deposits() { // Deposit transactions should not advance the data-availability counters, even when the // value would otherwise saturate. - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); + let mut limiter = BlockLimiter::new(BlockLimits::no_limits(), u64::MAX); limiter.block_da_size_used = 100; limiter.block_da_footprint_used = 200; @@ -467,27 +725,31 @@ mod tests { assert_eq!(limiter.block_tx_size_used, 7, "a deposit still counts as a transaction body"); } - /// The execution ledger is the one gas dimension with a block limit: the transaction that - /// crosses it is already packed, and the next one is refused. + /// A deposit is never refused by the block's data-size limit, however far past it the block + /// is, and still counts towards it: an ordinary transaction after the deposits finds the room + /// they used. #[test] - fn test_execution_gas_limit_refuses_the_transaction_after_the_crossing() { + fn test_data_size_limit_never_refuses_a_deposit_and_counts_it() { let mut limiter = - BlockLimiter::new(BlockLimits::no_limits().with_block_execution_gas_limit(1_000)); - - limiter.post_execution_update(&BlockUsage { - gas: MegaGasUsage { regular: 999, ..Default::default() }, + BlockLimiter::new(BlockLimits::no_limits().with_block_txs_data_limit(1_000), u64::MAX); + let deposit = BlockUsage { + usage: LimitUsage { data_size: 600, write_records: 0 }, + is_deposit: true, ..Default::default() - }); - assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); + }; + + // Two deposits cross the limit between them, and a third finds the block past it. + for _ in 0..3 { + assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, true).is_ok()); + limiter.post_execution_update(&deposit); + } + assert_eq!(limiter.usage.data_size, 1_800, "every deposit counts"); - limiter.post_execution_update(&BlockUsage { - gas: MegaGasUsage { regular: 1, ..Default::default() }, - ..Default::default() - }); let err = limiter .pre_execution_check(B256::ZERO, 0, 0, 0, false) - .expect_err("the block's execution gas has reached its limit"); - assert!(std::format!("{err}").contains("Block execution gas limit reached"), "{err}"); + .expect_err("the deposits used the room an ordinary transaction would need"); + assert!(std::format!("{err}").contains("Block transactions data limit reached"), "{err}"); + assert!(std::format!("{err}").contains("block_used=1800"), "{err}"); } /// Every limit is an inclusive bound: a transaction that exactly fills what the limit — or @@ -503,7 +765,7 @@ mod tests { let cases: [(&str, BlockLimiter, u64, Check); 6] = [ ( "a transaction's own gas limit", - BlockLimiter::new(BlockLimits::no_limits().with_tx_gas_limit(LIMIT)), + BlockLimiter::new(BlockLimits::no_limits().with_tx_gas_limit(LIMIT), u64::MAX), LIMIT, |limiter, gas_limit| { limiter.pre_execution_check(B256::ZERO, gas_limit, 0, 0, false) @@ -511,10 +773,7 @@ mod tests { ), ( "the block's gas limit", - BlockLimiter { - block_gas_used: USED, - ..BlockLimiter::new(BlockLimits::no_limits().with_block_gas_limit(LIMIT)) - }, + BlockLimiter { block_gas_used: USED, ..limiter_with_block_gas(LIMIT) }, LIMIT - USED, |limiter, gas_limit| { limiter.pre_execution_check(B256::ZERO, gas_limit, 0, 0, false) @@ -522,7 +781,10 @@ mod tests { ), ( "a transaction's own encoded size", - BlockLimiter::new(BlockLimits::no_limits().with_tx_encode_size_limit(LIMIT)), + BlockLimiter::new( + BlockLimits::no_limits().with_tx_encode_size_limit(LIMIT), + u64::MAX, + ), LIMIT, |limiter, tx_size| limiter.pre_execution_check(B256::ZERO, 0, tx_size, 0, false), ), @@ -532,6 +794,7 @@ mod tests { block_tx_size_used: USED, ..BlockLimiter::new( BlockLimits::no_limits().with_block_txs_encode_size_limit(LIMIT), + u64::MAX, ) }, LIMIT - USED, @@ -539,7 +802,7 @@ mod tests { ), ( "a transaction's own data-availability size", - BlockLimiter::new(BlockLimits::no_limits().with_tx_da_size_limit(LIMIT)), + BlockLimiter::new(BlockLimits::no_limits().with_tx_da_size_limit(LIMIT), u64::MAX), LIMIT, |limiter, da_size| limiter.pre_execution_check(B256::ZERO, 0, 0, da_size, false), ), @@ -547,7 +810,10 @@ mod tests { "the block's data-availability size", BlockLimiter { block_da_size_used: USED, - ..BlockLimiter::new(BlockLimits::no_limits().with_block_da_size_limit(LIMIT)) + ..BlockLimiter::new( + BlockLimits::no_limits().with_block_da_size_limit(LIMIT), + u64::MAX, + ) }, LIMIT - USED, |limiter, da_size| limiter.pre_execution_check(B256::ZERO, 0, 0, da_size, false), @@ -563,14 +829,81 @@ mod tests { } } + /// No limit only a builder applies refuses a deposit, which the block derived from L1 must + /// include: not its declared gas, not its encoded size, not what its encoding adds to the + /// block's. The same transaction not a deposit is refused by each, and the block's gas limit, + /// the header's, refuses a deposit as it refuses any transaction. + #[test] + fn test_no_building_policy_refuses_a_deposit() { + let cases: [(&str, BlockLimits, u64, u64); 5] = [ + ("a declared gas", BlockLimits::no_limits().with_tx_gas_limit(100), 101, 0), + ("an encoded size", BlockLimits::no_limits().with_tx_encode_size_limit(10), 0, 11), + ( + "the block's encoded size", + BlockLimits::no_limits().with_block_txs_encode_size_limit(10), + 0, + 11, + ), + ("a data-availability size", BlockLimits::no_limits().with_tx_da_size_limit(10), 0, 11), + ( + "the block's data-availability size", + BlockLimits::no_limits().with_block_da_size_limit(10), + 0, + 11, + ), + ]; + for (name, limits, gas_limit, size) in cases { + let limiter = BlockLimiter::new(limits, u64::MAX); + // The one size feeds both the encoded and the data-availability size. + let check = |is_deposit| { + limiter.pre_execution_check(B256::ZERO, gas_limit, size, size, is_deposit) + }; + assert!(check(true).is_ok(), "{name} over the policy: a deposit is admitted"); + assert!(check(false).is_err(), "{name} over the policy: a transaction is refused"); + } + + let limiter = limiter_with_block_gas(100); + let err = limiter + .pre_execution_check(B256::ZERO, 101, 0, 0, true) + .expect_err("the block's gas limit holds a deposit"); + assert!(std::format!("{err}").contains("transaction gas limit 101 is more than"), "{err}"); + } + + /// A deposit counts towards the block's encoded size though it is never refused by it, so the + /// transaction after it finds the room it used. + #[test] + fn test_a_deposit_counts_towards_the_blocks_encoded_size() { + let mut limiter = BlockLimiter::new( + BlockLimits::no_limits().with_block_txs_encode_size_limit(1_000), + u64::MAX, + ); + for _ in 0..2 { + assert!(limiter.pre_execution_check(B256::ZERO, 0, 600, 0, true).is_ok()); + limiter.post_execution_update(&BlockUsage { + tx_size: 600, + is_deposit: true, + ..Default::default() + }); + } + assert_eq!(limiter.block_tx_size_used, 1_200, "every deposit counts"); + + let err = limiter + .pre_execution_check(B256::ZERO, 0, 1, 0, false) + .expect_err("the deposits used the room an ordinary transaction would need"); + assert!(std::format!("{err}").contains("block_used=1200"), "{err}"); + } + /// What the block has left is what its refusal reports, and it is the limit minus what the /// block used. #[test] fn test_available_gas_is_the_limit_less_what_the_block_used() { - let mut limiter = BlockLimiter::new(limits_with_block_gas(1_000)); + let mut limiter = limiter_with_block_gas(1_000); assert_eq!(limiter.available_gas(), 1_000, "an empty block has all of it"); - limiter.post_execution_update(&BlockUsage { gas_used: 400, ..Default::default() }); + limiter.post_execution_update(&BlockUsage { + gas: MegaGasUsage { gas_used: 400, ..Default::default() }, + ..Default::default() + }); assert_eq!(limiter.available_gas(), 600); let err = limiter @@ -582,24 +915,34 @@ mod tests { ); // The block cannot owe gas: a counter past the limit reports nothing left. - limiter.post_execution_update(&BlockUsage { gas_used: u64::MAX, ..Default::default() }); + limiter.post_execution_update(&BlockUsage { + gas: MegaGasUsage { gas_used: u64::MAX, ..Default::default() }, + ..Default::default() + }); assert_eq!(limiter.available_gas(), 0); } - /// The state and history ledgers and the write-record count are accumulated, and no check - /// refuses a transaction on them. + /// The state and history ledgers, the history bytes and the write records are accumulated, and + /// no check refuses a transaction on them. #[test] - fn test_state_history_and_write_records_are_counted_but_not_enforced() { - let mut limiter = BlockLimiter::new(BlockLimits::no_limits()); - - limiter.post_execution_update(&BlockUsage { - gas: MegaGasUsage { state: 10_000, history: 20_000, ..Default::default() }, + fn test_state_and_history_are_counted_but_not_enforced() { + let mut limiter = BlockLimiter::new(BlockLimits::no_limits(), u64::MAX); + let usage = BlockUsage { + gas: MegaGasUsage { + state: 10_000, + history: 20_000, + history_bytes: 250, + ..Default::default() + }, usage: LimitUsage { data_size: 0, write_records: 30 }, ..Default::default() - }); + }; + + limiter.post_execution_update(&usage); assert_eq!(limiter.gas.state, 10_000); assert_eq!(limiter.gas.history, 20_000); + assert_eq!(limiter.gas.history_bytes, 250); assert_eq!(limiter.usage.write_records, 30); assert!(limiter.pre_execution_check(B256::ZERO, 0, 0, 0, false).is_ok()); } diff --git a/crates/mega-evm/src/block/mod.rs b/crates/mega-evm/src/block/mod.rs index 7e06545d8..d9d9b19b9 100644 --- a/crates/mega-evm/src/block/mod.rs +++ b/crates/mega-evm/src/block/mod.rs @@ -4,8 +4,10 @@ mod chain; mod eips; mod executor; mod factory; +mod genesis; mod hardfork; mod helpers; +mod l1_block_info; mod limit; mod result; @@ -13,7 +15,9 @@ pub use chain::*; pub use eips::*; pub use executor::*; pub use factory::*; +pub use genesis::*; pub use hardfork::*; pub use helpers::*; +pub use l1_block_info::*; pub use limit::*; pub use result::*; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index ff18a0936..83243b51c 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -9,15 +9,17 @@ use alloy_evm::{ block::{BlockExecutionResult, TxResult}, InvalidTxError, }; -use alloy_primitives::TxHash; +use alloy_primitives::{Address, TxHash, U256}; use revm::context::result::{InvalidTransaction, ResultAndState}; use crate::{BlockUsage, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome}; -/// A block's gas, on the three ledgers its transactions spend on. +/// A block's gas, on the three ledgers its transactions spend on, and the history bytes they +/// appended. /// -/// The block executor fills it transaction by transaction with [`record`](Self::record) and -/// holds each counter to its own block limit. +/// The block executor fills it transaction by transaction with [`record`](Self::record). No +/// block limit holds any of these counters: each is counted and reported. The block's gas limit +/// is held against the gas its receipts report, which is none of these ledgers. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct BlockGasCounters { /// Regular gas: each transaction's regular ledger, at least its EIP-7623 floor. @@ -26,6 +28,9 @@ pub struct BlockGasCounters { pub state: u64, /// History gas. pub history: u64, + /// The history bytes the block's transactions appended: the sum of their + /// [`MegaGasUsage::history_bytes`], which says what is and is not among them. + pub history_bytes: u64, } impl BlockGasCounters { @@ -34,6 +39,7 @@ impl BlockGasCounters { self.execution = self.execution.saturating_add(gas.block_execution_gas()); self.state = self.state.saturating_add(gas.state); self.history = self.history.saturating_add(gas.history); + self.history_bytes = self.history_bytes.saturating_add(gas.history_bytes); } } @@ -132,13 +138,6 @@ impl InvalidTxError for MegaTxLimitExceededError { /// what the block [used](Self::block_used) and the [limit](Self::limit) it is held to. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MegaBlockLimitExceededError { - /// The block's transactions have spent their execution gas. - ExecutionGasLimit { - /// The execution gas the block has spent. - block_used: u64, - /// The block's execution-gas limit. - limit: u64, - }, /// The block's transactions have kept their data-size bytes. TransactionDataLimit { /// The data-size bytes the block has kept. @@ -170,7 +169,6 @@ impl MegaBlockLimitExceededError { /// What the block used of the resource. pub const fn block_used(&self) -> u64 { match self { - Self::ExecutionGasLimit { block_used, .. } | Self::TransactionDataLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, @@ -180,7 +178,6 @@ impl MegaBlockLimitExceededError { /// The limit of the resource. pub const fn limit(&self) -> u64 { match self { - Self::ExecutionGasLimit { limit, .. } | Self::TransactionDataLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, @@ -191,9 +188,6 @@ impl MegaBlockLimitExceededError { impl fmt::Display for MegaBlockLimitExceededError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ExecutionGasLimit { block_used, limit } => { - write!(f, "Block execution gas limit reached: block_used={block_used} >= limit={limit}") - } Self::TransactionDataLimit { block_used, limit } => { write!(f, "Block transactions data limit reached: block_used={block_used} >= limit={limit}") } @@ -249,9 +243,24 @@ pub struct MegaBlockTxResult { pub da_footprint: u64, /// Whether the transaction is a deposit. pub is_deposit: bool, + /// Whether the transaction is a Mega System Transaction: a legacy call from the live system + /// address, which the engine runs as the protocol's own. The block decided it before the + /// transaction ran, from the registry's system address, and a delayed commit makes the same + /// decision. Like a deposit it is never refused by the data-size packing budget or by the + /// builder's policy, and counts towards them. + pub is_system_transaction: bool, /// The nonce the depositor had before execution, which the deposit receipt reports. `Some` /// only for a deposit. pub depositor_nonce: Option, + /// The transaction's sender: the system address, for a system-address transaction. + pub sender: Address, + /// The sender's nonce as the transaction executed against it, which a delayed commit checks + /// against the block's state then + /// ([`commit_transaction_outcome`](crate::MegaBlockExecutor::commit_transaction_outcome)). + pub sender_nonce: u64, + /// The sender's balance as the transaction executed against it, which a delayed commit checks + /// as it checks the nonce. + pub sender_balance: U256, /// The execution result, the post-state and what `MegaETH` counted, as execution produced /// them. pub inner: MegaTransactionOutcome, @@ -261,7 +270,6 @@ impl MegaBlockTxResult { /// What this transaction adds to the block's counters. pub const fn block_usage(&self) -> BlockUsage { BlockUsage { - gas_used: self.inner.gas.gas_used, gas: self.inner.gas, usage: self.inner.usage, tx_size: self.tx_size, @@ -342,13 +350,28 @@ mod tests { #[test] fn test_block_counters_add_each_ledger() { let mut block = BlockGasCounters::default(); - let first = - MegaGasUsage { regular: 10, state: 20, history: 30, floor: 0, ..Default::default() }; - let floored = - MegaGasUsage { regular: 5, state: 1, history: 2, floor: 50, ..Default::default() }; + let first = MegaGasUsage { + regular: 10, + state: 20, + history: 30, + history_bytes: 7, + floor: 0, + ..Default::default() + }; + let floored = MegaGasUsage { + regular: 5, + state: 1, + history: 2, + history_bytes: 4, + floor: 50, + ..Default::default() + }; block.record(&first); block.record(&floored); - assert_eq!(block, BlockGasCounters { execution: 60, state: 21, history: 32 }); + assert_eq!( + block, + BlockGasCounters { execution: 60, state: 21, history: 32, history_bytes: 11 } + ); } #[test] @@ -380,7 +403,6 @@ mod tests { #[test] fn test_block_limit_error_reports_block_usage_and_limit() { let cases = [ - (MegaBlockLimitExceededError::ExecutionGasLimit { block_used: 3, limit: 12 }, 3, 12), (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { @@ -412,12 +434,20 @@ mod tests { #[test] fn test_block_counters_saturate() { - let mut block = - BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX }; - block.record(&MegaGasUsage { regular: 1, state: 1, history: 1, ..Default::default() }); - assert_eq!( - block, - BlockGasCounters { execution: u64::MAX, state: u64::MAX, history: u64::MAX } - ); + let full = BlockGasCounters { + execution: u64::MAX, + state: u64::MAX, + history: u64::MAX, + history_bytes: u64::MAX, + }; + let mut block = full; + block.record(&MegaGasUsage { + regular: 1, + state: 1, + history: 1, + history_bytes: 1, + ..Default::default() + }); + assert_eq!(block, full); } } diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index 9db7e0493..d11367e6f 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -9,22 +9,32 @@ //! | [`COST_PER_STATE_BYTE`] | 1,530 | gas per byte of new state (EIP-8037 CPSB) | the Satin gas schedule | //! | [`SLOT_STATE_GAS`] | 97,920 | state gas of one new storage slot (64 bytes) | tests of the Satin gas schedule | //! | [`ACCOUNT_STATE_GAS`] | 183,600 | state gas of one new account (120 bytes) | tests of the Satin gas schedule | -//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas (not yet) | +//! | [`COST_PER_HISTORY_BYTE`] | 88 | gas per history byte (CPHB) | history gas, and the schedule's deposited-code entry | //! | [`TX_GAS_LIMIT_CAP`] | 200,000,000 | execution cap: regular gas one transaction may spend | the spec configuration | //! | [`MAX_CONTRACT_SIZE`] | 524,288 | the most bytes a deployed contract may hold | the spec configuration | //! | [`MAX_INITCODE_SIZE`] | 1,048,576 | the most bytes an initcode may hold | the spec configuration | -//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | the data-size limit (not yet) | -//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | the data-size limit (not yet) | +//! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | Satin's protocol limits | +//! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | Satin's protocol limits | +//! | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the block environment or the beneficiary (as Rex6) | Satin's protocol limits | +//! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | Satin's protocol limits | +//! | [`MAX_TX_COMPUTE_GAS`] | 199,987,900 | the most compute one transaction can spend: the execution cap less EIP-2780's base cost and one warm account access | tests of the protocol limits, whose detention caps are below it | //! //! The Satin gas schedule builds its state-gas entries from the EIP-8037 byte counts at //! [`COST_PER_STATE_BYTE`], read through [`SatinPrices`](crate::SatinPrices) so a measurement //! build can run other byte prices without touching this table. [`SLOT_STATE_GAS`] and //! [`ACCOUNT_STATE_GAS`] are two of those products written out: the tests assert the schedule //! against them, and changing one of the two moves a test rather than a price. -//! The storage call stipend and the per-transaction and per-block state-gas limits are further -//! placeholders; history gas and the state-gas limits add them when they land. +//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`] and the two detention caps are Satin's protocol limits +//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)). No limit holds state growth: +//! state gas prices it. -use revm::primitives::eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}; +use revm::{ + context_interface::cfg::gas::WARM_STORAGE_READ_COST, + primitives::{ + eip2780, + eip8037::{NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES}, + }, +}; /// Gas per byte of new state, the EIP-8037 `COST_PER_STATE_BYTE`. Provisional. pub const COST_PER_STATE_BYTE: u64 = 1_530; @@ -38,6 +48,11 @@ pub const SLOT_STATE_GAS: u64 = SSTORE_SET_BYTES * COST_PER_STATE_BYTE; pub const ACCOUNT_STATE_GAS: u64 = NEW_ACCOUNT_BYTES * COST_PER_STATE_BYTE; /// Gas per history byte (logs, deployed code, write records, transaction body). Provisional. +/// +/// Every history charge is a byte count from the byte table at this price, read through +/// [`SatinPrices`](crate::SatinPrices) so a measurement build can run other prices; the schedule's +/// `code_deposit_history_gas` entry is this number, which is the one history charge revm makes +/// itself. pub const COST_PER_HISTORY_BYTE: u64 = 88; /// The execution cap: the most regular gas one transaction may spend. Gas above it goes to @@ -57,6 +72,28 @@ pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; /// The most data one block may produce, 12.5 MiB as in Rex6. Provisional. pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; +/// The compute a transaction may still spend once it read the block environment or the block +/// beneficiary's account: its compute at the read plus this. The value and its relative reading +/// are Rex6's. Provisional. +pub const BLOCK_ENV_ACCESS_COMPUTE_GAS: u64 = 20_000_000; + +/// The compute a transaction may still spend once it read the Oracle's storage: its compute at +/// the read plus this. The value and its relative reading are Rex6's; the legacy engine's first +/// specs capped an Oracle read at 1,000,000. Provisional. +pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; + +/// The most compute one transaction can spend: the most regular gas its first frame can hold +/// when that frame runs code. Derived from [`TX_GAS_LIMIT_CAP`]. +/// +/// Compute is the regular gas a transaction's frames spend, and the first frame holds what the +/// execution cap leaves once the transaction paid for itself: EIP-2780's base cost, which every +/// transaction pays, and the account whose code the frame runs — a recipient other than the sender +/// at the cold rate, the delegate of a sender that calls itself at least at the warm one, 100, +/// which EIP-8038 leaves where it was. A gas-detention cap at or above this never stops a +/// transaction, however early it read, so a spec's caps are below it. +pub const MAX_TX_COMPUTE_GAS: u64 = + TX_GAS_LIMIT_CAP - eip2780::TX_BASE_COST - WARM_STORAGE_READ_COST; + #[cfg(test)] mod tests { use super::*; @@ -71,7 +108,8 @@ mod tests { assert_eq!(TX_GAS_LIMIT_CAP, 200_000_000); assert_eq!(MAX_CONTRACT_SIZE, 524_288); assert_eq!(MAX_INITCODE_SIZE, 1_048_576); - assert_eq!(TX_DATA_LIMIT, 13_107_200); - assert_eq!(BLOCK_DATA_LIMIT, 13_107_200); + // The data-size limits and the detention caps are written out with the protocol limits + // that read them, in `ProtocolLimits::for_spec`'s own test. + assert_eq!(MAX_TX_COMPUTE_GAS, 199_987_900); } } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 79edf4446..03d3fe786 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,19 +1,35 @@ //! The execution context of the Satin engine. +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + use delegate::delegate; -use op_revm::{L1BlockInfo, OpSpecId}; +use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpSpecId}; use revm::{ - context::{BlockEnv, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext}, - primitives::{Address, StorageKey}, + context::{ + BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, + Transaction, + }, + context_interface::{cfg::GasId, context::CodeDeposit}, + primitives::{Address, Bytes, StorageKey}, Database, Journal, }; use crate::{ constants, - evm::schedule::satin_gas_params, - system::{self, MEGA_SYSTEM_ADDRESS}, - AdditionalLimit, BlockHashRecord, BucketError, BucketMultipliers, EmptyExternalEnv, - EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaSpecId, MegaTransaction, SaltEnv, + evm::{ + history::transaction_body_bytes, + inspector::UpfrontRecord, + schedule::{satin_gas_params, satin_gas_params_history_exempt}, + }, + system::{ + self, + keyless::{self, KeylessFrame}, + }, + AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, + Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, + MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` @@ -26,36 +42,64 @@ pub(crate) type MegaInnerContext = /// It wraps op-revm's context and adds what `MegaETH` execution needs on top: the `MegaETH` /// spec and the external environments (SALT, oracle). The configuration is kept twice: the /// [`MegaSpecId`] view that callers see and the [`OpSpecId`] view op-revm executes on. Both are -/// written together, only through [`MegaContext::with_cfg`], so they cannot drift apart. +/// written together, only through [`MegaContext::with_cfg`] (and the test tooling's neutral +/// configuration), so they cannot drift apart. /// /// Every context accessor delegates to the wrapped context, and so does every /// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing -/// opcode did (see the `host` module). It also carries the common execution layer's state for the -/// running transaction ([`AdditionalLimit`]) and the SALT bucket multipliers that transaction has -/// priced state gas with ([`BucketMultipliers`]). +/// opcode did and the ones that load volatile data (see the `host` module). It also carries the +/// common execution layer's state for the running transaction ([`AdditionalLimit`]), gas +/// detention's ([`Detention`]), the SALT bucket multipliers that transaction has priced state +/// gas with ([`BucketMultipliers`]) and the reads of the Oracle's storage it made through the +/// oracle service ([`OracleReadRecord`]). #[derive(Debug)] pub struct MegaContext { pub(crate) inner: MegaInnerContext, cfg: CfgEnv, external_envs: ExternalEnvs, pub(crate) additional_limit: AdditionalLimit, + /// Gas detention for the running transaction. + pub(crate) detention: Detention, + /// What the calling opcode charged upfront for each running frame of an inspected transaction, + /// by depth, taken before the inspector could rewrite the call. + pub(crate) upfront_records: Vec>, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, - /// Whether the running transaction is system-originated, and so prices its state gas at the - /// minimum bucket. See [`system::is_system_originated`]. + /// The SALT buckets execution has asked the environment about, over the block. + bucket_record: BucketRecord, + /// The reads of the Oracle's storage the running transaction made through the oracle + /// service, with the service's answers. + pub(crate) oracle_reads: OracleReadRecord, + /// Whether the running transaction is the protocol's own, decided when it is validated. See + /// [`MegaContext::is_system_originated`]. system_originated: bool, + /// Whether the running execution is a system call rather than a transaction. See + /// [`MegaContext::is_system_call`]. + system_call: bool, + /// Whether the running transaction pays history gas. See [`MegaContext::prices_history`]. + prices_history: bool, + /// Where the running transaction's `keylessDeploy` call stands, from the start of its frame + /// to its answer. See the [`keyless`](crate::system::keyless) module. + pub(crate) keyless_frame: Option, + /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. + #[cfg(any(test, feature = "test-utils"))] + neutral: bool, } impl MegaContext { /// Creates a context over `db` that executes `spec`, without external environments. + /// + /// It runs every transaction under `spec`'s limits ([`ProtocolLimits::for_spec`]), as block + /// execution does; [`with_tx_runtime_limits`](Self::with_tx_runtime_limits) replaces them. pub fn new(db: DB, spec: MegaSpecId) -> Self { Self::new_with_external_envs(db, spec, ExternalEnvs::default()) } } impl MegaContext { - /// Creates a context over `db` that executes `spec` with the given external environments. + /// Creates a context over `db` that executes `spec` with the given external environments, + /// under `spec`'s limits ([`ProtocolLimits::for_spec`]). pub fn new_with_external_envs( db: DB, spec: MegaSpecId, @@ -67,26 +111,93 @@ impl MegaContext { inner, cfg, external_envs, - additional_limit: AdditionalLimit::default(), + additional_limit: AdditionalLimit::new( + ProtocolLimits::for_spec(spec).tx_runtime_limits, + ), + detention: Detention::default(), + upfront_records: Vec::new(), block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), + bucket_record: BucketRecord::default(), + oracle_reads: OracleReadRecord::default(), system_originated: false, + system_call: false, + prices_history: true, + keyless_frame: None, + #[cfg(any(test, feature = "test-utils"))] + neutral: false, } } /// Replaces the configuration. /// /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas schedule, - /// the EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch, the - /// system-call state-gas margin and the two code-size limits. Every other field (chain id, - /// disabled checks, blob schedule) is taken from `cfg`. + /// the EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and its + /// disabling flag, the system-call state-gas margin, the chain-id check and the two code-size + /// limits. Every other field (chain id, the other disabled checks, blob schedule) is taken + /// from `cfg`. + /// + /// A context that ran the neutral configuration returns to the spec's. pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { let cfg = spec_cfg(cfg); self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; + #[cfg(any(test, feature = "test-utils"))] + { + self.neutral = false; + } + self + } + + /// Replaces the configuration with `cfg` as it is given, and turns off every dimension of + /// pricing only `MegaETH` has: the neutral configuration. + /// + /// It is test tooling, behind the `test-utils` feature, for the execution-spec gate, which + /// runs Ethereum's fixtures through Satin's machinery — its handler, frame lifecycle, Host + /// and instruction table — priced as the fixture's own fork prices them, so that what is + /// left to differ is what the machinery does rather than what `MegaETH` charges for. + /// + /// - Every field is taken from `cfg`, including the ones [`with_cfg`](Self::with_cfg) sets from + /// the spec: the gas schedule, the EIP-8037, EIP-2780 and EIP-7708 switches, the execution + /// cap and the code-size limits. + /// - No transaction pays history gas, and none has its schedule swapped for its history + /// exemption: every transaction runs `cfg`'s schedule. + /// - SALT pricing needs nothing here: without a SALT environment every bucket is minimal, and + /// the multiplier is one. + /// - Gas detention is not part of the configuration: its caps are runtime limits, which the + /// gate's runner leaves unlimited with every other one ([`EvmTxRuntimeLimits::no_limits`]), + /// and then no read of volatile data caps anything. + /// + /// The spec stays [`MegaSpecId::SATIN`], and with it the base spec the handler and the + /// journal execute. The precompile set is the EVM's, not the context's: a caller that wants + /// the fixture fork's replaces it on the [`MegaEvm`](crate::MegaEvm). + #[cfg(any(test, feature = "test-utils"))] + pub fn with_neutral_cfg(mut self, cfg: CfgEnv) -> Self { + self.inner = self.inner.with_cfg(op_cfg(&cfg)); + self.cfg = cfg; + self.neutral = true; + self.prices_history = false; + self + } + + /// The spec's configuration with EIP-7708 switched off in both views, for the unit tests that + /// hold a transaction with its transfer logs to the same transaction without them. No + /// configuration a caller can build runs Satin without them. + #[cfg(test)] + pub(crate) fn without_transfer_logs(mut self) -> Self { + self.cfg.enable_amsterdam_eip7708 = false; + self.inner = self.inner.with_cfg(op_cfg(&self.cfg)); self } + /// Whether the context runs the neutral configuration ([`with_neutral_cfg`]). + /// + /// [`with_neutral_cfg`]: Self::with_neutral_cfg + #[cfg(any(test, feature = "test-utils"))] + pub const fn is_neutral(&self) -> bool { + self.neutral + } + /// Replaces the block environment. pub fn with_block(mut self, block: BlockEnv) -> Self { self.inner.block = block; @@ -127,7 +238,8 @@ impl MegaContext { &self.external_envs } - /// Enforces `limits` on every transaction from now on. + /// Enforces `limits` on every transaction from now on, in place of the spec's: a tool's or a + /// test's counterfactual. pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { self.additional_limit.set_limits(limits); self @@ -146,16 +258,53 @@ impl MegaContext { self.block_hash_record.clear(); } + /// The SALT buckets execution has asked the environment about on this context. + /// + /// The record belongs to one block: it is not forgotten between transactions, as the + /// multipliers are ([`bucket_multipliers`](Self::bucket_multipliers)), and block execution + /// empties it when the block starts. + pub const fn bucket_record(&self) -> &BucketRecord { + &self.bucket_record + } + + /// Forgets the SALT buckets asked about so far. + pub fn clear_bucket_record(&mut self) { + self.bucket_record.clear(); + } + + /// The reads of the Oracle's storage the running (or last) transaction made through the + /// oracle service, in order, each with the service's answer. + /// + /// The record belongs to one transaction: it is emptied before every transaction and system + /// call, and the transaction's outcome carries a copy + /// ([`MegaTransactionOutcome::oracle_reads`](crate::MegaTransactionOutcome::oracle_reads)), + /// which is where a node takes the reads of the transactions it includes from. + pub const fn oracle_reads(&self) -> &OracleReadRecord { + &self.oracle_reads + } + /// The common execution layer's state for the running (or last) transaction. pub const fn additional_limit(&self) -> &AdditionalLimit { &self.additional_limit } - /// The common execution layer's state, mutably. For tests and tools that drive the abort - /// protocol directly. + /// Gas detention for the running (or last) transaction: the volatile data it read and the + /// compute limit that set. See the `access` module. + pub const fn detention(&self) -> &Detention { + &self.detention + } + + /// Starts every transaction with volatile-data access switched off for the frame at `depth` + /// and every frame below it, as if that frame had called + /// `MegaAccessControl.disableVolatileDataAccess()` before its first instruction. The switch + /// turns back on when that frame returns. + /// + /// It is test tooling, behind the `test-utils` feature, for a switch set without a call: on + /// the chain, a frame switches it off by calling the contract, whose interceptor steers it. #[cfg(any(test, feature = "test-utils"))] - pub const fn additional_limit_mut(&mut self) -> &mut AdditionalLimit { - &mut self.additional_limit + pub fn with_volatile_access_disabled_from(mut self, depth: usize) -> Self { + self.detention.set_disabled_from_at_start(Some(depth)); + self } /// The SALT bucket multiplier of the account `address`'s own state lives in: the capacity of @@ -166,11 +315,15 @@ impl MegaContext { /// from [`BucketMultipliers`] afterwards. A bucket the environment could not report, and one /// it reported below the minimum capacity a bucket can hold, both fail /// ([`BucketError`](crate::BucketError)). + /// + /// The bucket is recorded for the block's witness ([`bucket_record`](Self::bucket_record)) + /// once the environment answered it with a valid capacity; see + /// [`bucket_multiplier`](Self::bucket_multiplier). pub fn account_bucket_multiplier( &mut self, address: Address, ) -> Result::Error>> { - self.bucket_multipliers.account(&self.external_envs.salt_env, address) + self.bucket_multiplier(::bucket_id_for_account(address)) } /// The SALT bucket multiplier of the slot `key` of `address`, which scales every slot-scoped @@ -181,7 +334,28 @@ impl MegaContext { address: Address, key: StorageKey, ) -> Result::Error>> { - self.bucket_multipliers.slot(&self.external_envs.salt_env, address, key) + self.bucket_multiplier(::bucket_id_for_slot(address, key)) + } + + /// The multiplier of `bucket`: the one the running transaction already read, or the one the + /// environment answers, which is cached for the transaction and recorded for the block's + /// witness. + /// + /// The record is written on the cache miss alone, once the environment answered with a valid + /// capacity: a cache hit adds nothing the miss did not, and a lookup that failed, with an error + /// or with a capacity below the minimum bucket, fails the transaction with its cause, so the + /// transaction is in no block and a validator never makes the lookup — a proof of that bucket + /// is one nobody uses, and a builder whose environment failed on it must not have to prove it. + fn bucket_multiplier( + &mut self, + bucket: BucketId, + ) -> Result::Error>> { + if let Some(multiplier) = self.bucket_multipliers.cached(bucket) { + return Ok(multiplier); + } + let multiplier = self.bucket_multipliers.fetch(&self.external_envs.salt_env, bucket)?; + self.bucket_record.record(bucket); + Ok(multiplier) } /// The SALT bucket multipliers the running (or last) transaction read. @@ -190,30 +364,160 @@ impl MegaContext { } /// Whether the running (or last) transaction is system-originated, and so prices every - /// EIP-8037 state gas charge at the minimum bucket. See [`system::is_system_originated`]. + /// EIP-8037 state gas charge at the minimum bucket and is held to no per-transaction limit + /// (see [`system::is_system_originated`]). A system call always is. + /// + /// A transaction's answer is decided when it is validated: a system-address transaction is + /// recognised by the live system address its validation reads out of the `SequencerRegistry` + /// in the state the EVM runs on, so every EVM answers as block execution does, however it was + /// built. pub const fn is_system_originated(&self) -> bool { self.system_originated } - /// Prepares the common execution layer for a new transaction or system call. Every entry - /// point of [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler. + /// Whether the running (or last) transaction pays history gas for the bytes it appends. /// - /// The SALT bucket multipliers go with it: they are what one transaction read, so the next - /// one reads its own. - pub(crate) fn on_new_tx(&mut self) { - self.additional_limit.reset(); - self.bucket_multipliers.reset(); - self.system_originated = system::is_system_originated(&self.inner.tx, MEGA_SYSTEM_ADDRESS); + /// Three kinds of transaction pay none: a deposit, a transaction the protocol itself produced + /// ([`system::is_system_originated`]) and a system call. What they append is the chain + /// carrying its own weight — a deposit the sequencer relays, the maintenance a system + /// transaction performs, the pre-block calls the protocol makes — and there is no sender to + /// charge for it. + /// + /// The two predicates are distinct and both are needed. A deposit is not system-originated: + /// it carries a user's source hash and a user's caller, so it prices its state gas by the + /// SALT bucket like any other transaction — it is exempt from history alone, because the + /// bytes it appends were paid for on L1. A system transaction is both: it prices at the + /// minimum bucket *and* pays no history. + pub const fn prices_history(&self) -> bool { + self.prices_history + } + + /// Prepares the common execution layer for a new transaction, which is a system-address + /// transaction or not as `system_transaction` says. The handler calls it first thing, once + /// validation has read the live system address, so the layer is prepared before anything + /// else of the transaction runs. + pub(crate) fn on_new_tx(&mut self, system_transaction: bool) { + self.prepare(system::originates_from_the_protocol(&self.inner.tx, system_transaction)); + self.system_call = false; } /// Prepares the context for a system call. Every system-call entry point of - /// [`MegaEvm`](crate::MegaEvm) calls it instead of [`on_new_tx`](Self::on_new_tx). + /// [`MegaEvm`](crate::MegaEvm) calls it before it runs the handler's system-call path, which + /// skips validation and so [`on_new_tx`](Self::on_new_tx). /// /// A system call is system-originated whatever caller it names: it is the protocol running, /// not a transaction anybody sent. pub(crate) fn on_new_system_call(&mut self) { - self.on_new_tx(); - self.system_originated = true; + self.prepare(true); + self.system_call = true; + } + + /// Whether the running execution is a system call: the protocol's own call, such as a + /// pre-block call, rather than a transaction of the block. + /// + /// A system call is a function of the chain's state alone, so it never asks the oracle + /// service: the service's answers reach a stateless validator through the included + /// transactions' records, and a system call has none. Set when the call is prepared and + /// cleared when the next transaction is, so it cannot outlive the call. + #[inline] + pub(crate) const fn is_system_call(&self) -> bool { + self.system_call + } + + /// Prepares the common execution layer for a transaction or a system call that is, or is not, + /// `system_originated`. + /// + /// The SALT bucket multipliers and the oracle reads go with it: they are what one transaction + /// read, so the next one reads its own. + /// + /// A system-originated transaction is exempt from every per-transaction limit — the data size + /// and its frame budgets — before anything is counted, its body included: the protocol's own + /// work must not fail on a resource limit, as it pays no history gas for the same reason. What + /// it uses is counted all the same. A user's deposit is not system-originated and is held + /// to every one of them. + fn prepare(&mut self, system_originated: bool) { + self.additional_limit.reset(); + self.additional_limit.set_transfer_logs(emits_transfer_logs(&self.inner.cfg)); + self.bucket_multipliers.reset(); + self.oracle_reads.clear(); + // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call + // unanswered. + self.keyless_frame = None; + self.system_originated = system_originated; + let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; + self.set_history_exempt(exempt); + if system_originated { + self.additional_limit.exempt(); + } + // The body is data size whether or not the transaction pays history for it. A deposit, + // a system transaction and a system call are exempt from the charge, not from the count. + self.additional_limit.record_tx_body(transaction_body_bytes(self.tx())); + // The protocol's own transactions are not detained: they maintain the volatile data. + let limits = self.additional_limit.limits(); + self.detention.reset( + !system_originated, + limits.block_env_access_compute_gas_limit, + limits.oracle_access_compute_gas_limit, + ); + self.mark_beneficiary_transaction(); + } + + /// Marks a read of the block beneficiary's account when the transaction's sender or its + /// recipient is the beneficiary: the transaction reads and writes that account whatever it + /// runs, so it is detained from its first instruction. + fn mark_beneficiary_transaction(&mut self) { + let beneficiary = self.inner.block.beneficiary; + let tx = &self.inner.tx; + if tx.caller() == beneficiary || tx.kind().to() == Some(&beneficiary) { + self.detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + } + } + + /// Marks a read of the block beneficiary's account when the transaction's recipient is an + /// EIP-7702 delegator whose delegate is the beneficiary: its first frame runs the + /// beneficiary's code, as a call a contract makes to the same delegator does. + /// + /// revm resolves the delegate of the transaction's own frame through the journal rather than + /// through the Host, so the load the Host marks for a contract's call never happens for it. + /// Called once revm has prepared the first frame, when the recipient is loaded with the + /// delegation any applied authorization left; read from the journal as it stands, without + /// loading or warming anything. + pub(crate) fn mark_beneficiary_delegate(&mut self) { + let Some(&recipient) = self.inner.tx.kind().to() else { return }; + let delegate = self + .journal_ref() + .state + .get(&recipient) + .and_then(|account| account.info.code.as_ref()) + .and_then(|code| code.eip7702_address()); + if delegate == Some(self.inner.block.beneficiary) { + self.detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + } + } + + /// Records whether the running transaction is exempt from history gas, and installs the + /// schedule that matches. + /// + /// The engine's own history charges read [`prices_history`](Self::prices_history); the one + /// charge revm makes itself reads the schedule, so an exempt transaction runs the schedule + /// that prices a deposited byte at zero. Both configuration views move together, and only + /// when the transaction's exemption differs from the one in place: the two tables are built + /// once for the process, so the swap is a shared clone. + /// + /// The neutral configuration prices no history and keeps its own schedule. + fn set_history_exempt(&mut self, exempt: bool) { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + self.prices_history = false; + return; + } + self.prices_history = !exempt; + let id = GasId::code_deposit_history_gas(); + let params = if exempt { satin_gas_params_history_exempt() } else { satin_gas_params() }; + if self.inner.cfg.gas_params.get(id) != params.get(id) { + self.cfg.gas_params = params.clone(); + self.inner.cfg.gas_params = params; + } } /// Consumes the context and returns the database, the configuration and the block. @@ -223,28 +527,64 @@ impl MegaContext { } } -/// Sets the configuration fields the spec fixes. +/// The configuration Satin runs on: `cfg` with every field the spec fixes set from the spec, and +/// every other field (chain id, disabled checks, blob schedule) as `cfg` holds it. +/// +/// It is the function [`MegaContext::with_cfg`] applies, so an EVM created from an alloy-evm +/// `EvmEnv` runs `spec_cfg(env.cfg_env)` whatever the env held. A node that builds an `EvmEnv` +/// passes its configuration through it too: what reads the env before an EVM exists — reth's gas +/// estimation reads the execution cap off it — then reads the configuration the EVM runs with. +/// Applying it twice changes nothing. +/// +/// A deposit, a system-originated transaction and a system call pay no history gas, and the EVM +/// runs them on a schedule that prices a deposited byte at nothing; it installs that schedule for +/// such a transaction and the spec's own for every other, so a configuration never carries it. /// /// Satin runs the Satin gas schedule (see [`satin_gas_params`]) on its Karst base, with EIP-8037 /// state gas and the EIP-2780 intrinsic cost switched on and gas above the execution cap going to /// the state-gas reservoir. It raises the code-size limits to `MegaETH`'s own. /// -/// Two switches are set off rather than left alone, because the base spec would turn them on and -/// Satin does not take them: EIP-7708 mints a transfer log for every value movement, which -/// `MegaETH` meters through its own write records instead, and the system-call reservoir margin -/// belongs to the system-call reservoir split. -fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { +/// It takes EIP-7708 from Amsterdam as well: every value movement emits a transfer log into the +/// receipt. The switch is set on and EIP-7708 is not left disabled, because a log in a receipt is +/// part of what a block commits to, not something a caller's configuration may take out. A +/// transfer log is data size like any log, and pays no history gas: Ethereum prices it at +/// nothing, and it is not a byte the transaction chose to write (see the `limit` module). +/// +/// A system call runs as EIP-8037 has it: on at most the base 30,000,000 of regular gas, the +/// rest of its gas limit being its state-gas reservoir, which the state it writes draws first. +/// The switch for it is set on whatever the caller's configuration says, because which pool pays +/// the protocol's own state writes, and what `GAS` reads inside a system contract, are part of +/// executing the chain. It reaches system calls only: every transaction's gas is split by the +/// execution cap as before, the system-address transaction's included, which is a deposit and +/// not a system call. +/// +/// The chain-id check is on, whatever the caller's configuration says: a transaction that carries +/// a chain id must carry the chain's, and one of a type other than legacy must carry one. Which +/// transactions a chain accepts is the chain's rule, not a caller's choice. +pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.gas_params = satin_gas_params(); cfg.enable_amsterdam_eip8037 = true; cfg.enable_amsterdam_eip2780 = true; cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); - cfg.enable_amsterdam_eip7708 = false; - cfg.system_call_state_gas_margin_in_reservoir = false; + cfg.enable_amsterdam_eip7708 = true; + cfg.amsterdam_eip7708_disabled = false; + cfg.system_call_state_gas_margin_in_reservoir = true; + cfg.tx_chain_id_check = true; cfg.limit_contract_code_size = Some(constants::MAX_CONTRACT_SIZE); cfg.limit_contract_initcode_size = Some(constants::MAX_INITCODE_SIZE); cfg } +/// Whether a value movement journals an EIP-7708 transfer log under `cfg`: from Amsterdam on, or +/// with the switch on, unless EIP-7708 is disabled. It is the rule revm's journal applies, read +/// off the configuration the journal was synced with, so the data size counts a transfer log +/// exactly where revm emits one. +fn emits_transfer_logs(cfg: &CfgEnv) -> bool { + let spec = EthSpecId::from(cfg.spec); + (spec.is_enabled_in(EthSpecId::AMSTERDAM) || cfg.enable_amsterdam_eip7708()) && + !cfg.is_eip7708_disabled() +} + /// The op-revm view of `cfg`: the same fields, keyed by the Optimism spec. fn op_cfg(cfg: &CfgEnv) -> CfgEnv { cfg.clone().with_spec_and_gas_params(cfg.spec.into_op_spec(), cfg.gas_params.clone()) @@ -285,6 +625,26 @@ impl ContextTr for MegaContext &mut Result<(), ContextError>; } } + + /// Holds the code a creation deposits to the data-size limit, and counts its history bytes, + /// once `return_create` made every charge for the deposit and before it commits + /// the creation ([`AdditionalLimit::on_code_deposit`]). A crossing refuses the deposit with the + /// stop's revert data: the creation reverts with it, on the gas it had before the deposit. + /// + /// A keyless deployment's constructor that returns empty code for the deploy address is + /// refused the same way, with empty revert data ([`keyless::refuses_empty_deposit`]). + #[inline] + fn admit_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + let destroyed = self + .journal_ref() + .state + .get(&deposit.address) + .is_some_and(|account| account.is_selfdestructed()); + if keyless::refuses_empty_deposit(&mut self.keyless_frame, deposit, destroyed) { + return Err(Bytes::new()); + } + self.additional_limit.on_code_deposit(deposit) + } } impl ContextSetters for MegaContext { @@ -313,8 +673,10 @@ mod tests { assert!(cfg.eip8037, "EIP-8037 must be on"); assert!(cfg.eip2780, "EIP-2780 must be on"); assert_eq!(cfg.cap, Some(constants::TX_GAS_LIMIT_CAP), "execution cap"); - assert!(!cfg.eip7708, "EIP-7708 stays off"); - assert!(!cfg.margin, "the system-call reservoir margin stays off"); + assert!(cfg.eip7708, "EIP-7708 must be on"); + assert!(!cfg.eip7708_disabled, "EIP-7708 must not be disabled"); + assert!(cfg.margin, "a system call's gas above 30M must be its reservoir"); + assert!(cfg.chain_id_check, "the chain id must be checked"); assert_eq!(cfg.code_size, Some(constants::MAX_CONTRACT_SIZE), "contract size"); assert_eq!(cfg.initcode_size, Some(constants::MAX_INITCODE_SIZE), "initcode size"); assert_eq!(cfg.gas_params.table(), satin_gas_params().table(), "gas schedule"); @@ -327,7 +689,9 @@ mod tests { eip2780: bool, cap: Option, eip7708: bool, + eip7708_disabled: bool, margin: bool, + chain_id_check: bool, code_size: Option, initcode_size: Option, gas_params: &'a GasParams, @@ -340,7 +704,9 @@ mod tests { eip2780: cfg.enable_amsterdam_eip2780, cap: cfg.tx_gas_limit_cap, eip7708: cfg.enable_amsterdam_eip7708, + eip7708_disabled: cfg.amsterdam_eip7708_disabled, margin: cfg.system_call_state_gas_margin_in_reservoir, + chain_id_check: cfg.tx_chain_id_check, code_size: cfg.limit_contract_code_size, initcode_size: cfg.limit_contract_initcode_size, gas_params: &cfg.gas_params, @@ -362,6 +728,23 @@ mod tests { assert_satin_cfg(&ctx); } + /// A bare context runs under its spec's limits, the data-size limit included, as block + /// execution does: no caller has to hand them over. A caller's limits replace them, and a + /// configuration does not. + #[test] + fn test_a_bare_context_runs_under_the_specs_limits() { + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + let ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert_eq!(*ctx.additional_limit().limits(), satin); + assert_eq!(ctx.additional_limit().limits().tx_data_size_limit, 13_107_200); + + let ctx = ctx.with_cfg(CfgEnv::new_with_spec(MegaSpecId::SATIN)); + assert_eq!(*ctx.additional_limit().limits(), satin, "a configuration sets no limit"); + + let ctx = ctx.with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + assert_eq!(*ctx.additional_limit().limits(), EvmTxRuntimeLimits::no_limits()); + } + /// A caller's configuration cannot switch off what the spec fixes; every other field is /// taken from it. #[test] @@ -371,8 +754,10 @@ mod tests { cfg.enable_amsterdam_eip8037 = false; cfg.enable_amsterdam_eip2780 = false; cfg.tx_gas_limit_cap = Some(1 << 24); - cfg.enable_amsterdam_eip7708 = true; - cfg.system_call_state_gas_margin_in_reservoir = true; + cfg.enable_amsterdam_eip7708 = false; + cfg.amsterdam_eip7708_disabled = true; + cfg.system_call_state_gas_margin_in_reservoir = false; + cfg.tx_chain_id_check = false; cfg.limit_contract_code_size = Some(24 * 1024); cfg.limit_contract_initcode_size = Some(48 * 1024); cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); @@ -383,51 +768,6 @@ mod tests { assert_eq!(ctx.cfg().chain_id, 4326); } - /// Each switch on its own: setting only that field the other way is overwritten, and the - /// rest of the configuration is untouched by the attempt. - #[test] - fn test_eip8037_stays_on() { - assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip8037 = false)); - } - - #[test] - fn test_eip2780_stays_on() { - assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip2780 = false)); - } - - #[test] - fn test_eip7708_stays_off() { - assert_satin_cfg(&context_with(|cfg| cfg.enable_amsterdam_eip7708 = true)); - } - - #[test] - fn test_the_system_call_reservoir_margin_stays_off() { - assert_satin_cfg(&context_with(|cfg| cfg.system_call_state_gas_margin_in_reservoir = true)); - } - - #[test] - fn test_the_execution_cap_is_the_spec_s() { - assert_satin_cfg(&context_with(|cfg| cfg.tx_gas_limit_cap = None)); - assert_satin_cfg(&context_with(|cfg| cfg.tx_gas_limit_cap = Some(u64::MAX))); - } - - #[test] - fn test_the_code_size_limits_are_the_spec_s() { - assert_satin_cfg(&context_with(|cfg| cfg.limit_contract_code_size = Some(24 * 1024))); - assert_satin_cfg(&context_with(|cfg| cfg.limit_contract_initcode_size = None)); - } - - /// The schedule is the Satin one whatever the caller passed, and it is the same table - /// object every time: it is built once, not per configuration. - #[test] - fn test_the_gas_schedule_is_the_satin_one() { - for spec in [EthSpecId::OSAKA, EthSpecId::AMSTERDAM, EthSpecId::PRAGUE] { - let ctx = context_with(|cfg| cfg.gas_params = GasParams::new_spec(spec)); - assert_satin_cfg(&ctx); - assert_ne!(ctx.mega_cfg().gas_params.table(), GasParams::new_spec(spec).table()); - } - } - /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. #[test] fn test_with_cfg_spec_consistency() { @@ -472,12 +812,97 @@ mod tests { assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); assert_eq!(env.bucket_queries(bucket), 1, "the second charge came from the cache"); - ctx.on_new_tx(); + ctx.on_new_tx(false); assert_eq!(ctx.bucket_multipliers().cached_buckets().len(), 0); assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); assert_eq!(env.bucket_queries(bucket), 2, "the next transaction read it again"); } + /// The bucket record outlives the multipliers: a bucket a transaction asked about stays + /// recorded once the next transaction has forgotten its multiplier, a slot's bucket and an + /// account's are both recorded, a bucket whose lookup failed is not, a cache hit records + /// nothing new, and a system call, which prices at the minimum bucket, records nothing. + /// Clearing empties it. + #[test] + fn test_the_bucket_record_holds_every_ask_over_the_block() { + const ACCOUNT: alloy_primitives::Address = + alloy_primitives::address!("00000000000000000000000000000000000000a1"); + const OTHER: alloy_primitives::Address = + alloy_primitives::address!("00000000000000000000000000000000000000a2"); + let account = ::bucket_id_for_account(ACCOUNT); + let slot = ::bucket_id_for_slot(ACCOUNT, U256::from(3)); + let failing = ::bucket_id_for_account(OTHER); + let env = TestExternalEnvs::::new() + .with_failing_bucket(failing, "salt backend unreachable".into()); + let mut ctx = MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs::> { + salt_env: env.clone(), + oracle_env: env.clone(), + }, + ); + assert!(ctx.bucket_record().is_empty()); + + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(1)); + ctx.on_new_tx(false); + assert_eq!(ctx.bucket_multipliers().cached_buckets().len(), 0, "the multiplier is gone"); + assert_eq!(ctx.bucket_record().to_vec(), vec![account], "the record is not"); + + assert_eq!(ctx.slot_bucket_multiplier(ACCOUNT, U256::from(3)), Ok(1)); + assert!(ctx.account_bucket_multiplier(OTHER).is_err(), "the lookup fails"); + let mut expected = vec![account, slot]; + expected.sort_unstable(); + assert_eq!(ctx.bucket_record().to_vec(), expected, "every answered ask, not the failed"); + assert_eq!(ctx.slot_bucket_multiplier(ACCOUNT, U256::from(3)), Ok(1), "a cache hit"); + assert_eq!(ctx.bucket_record().to_vec(), expected, "which records nothing new"); + assert_eq!(env.bucket_queries(slot), 1, "and asked the environment nothing"); + + ctx.on_new_system_call(); + assert_eq!(ctx.bucket_record().to_vec(), expected, "a system call forgets nothing"); + + ctx.clear_bucket_record(); + assert!(ctx.bucket_record().is_empty()); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(1)); + assert_eq!(ctx.bucket_record().to_vec(), vec![account], "and records again after"); + } + + /// The oracle read record is one transaction's: a transaction and a system call each start + /// with an empty one. + #[test] + fn test_the_oracle_reads_are_forgotten_before_the_next_transaction() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert!(ctx.oracle_reads().is_empty()); + + ctx.oracle_reads.record(U256::from(42), Some(U256::from(1))); + assert_eq!(ctx.oracle_reads().reads().len(), 1); + + ctx.on_new_tx(false); + assert!(ctx.oracle_reads().is_empty(), "the next transaction starts with none"); + + ctx.oracle_reads.record(U256::from(42), None); + ctx.on_new_system_call(); + assert!(ctx.oracle_reads().is_empty(), "so does a system call"); + } + + /// The system-call mark is the call's own: it is set when a system call is prepared and + /// cleared by the next transaction, a Mega System Transaction included. + #[test] + fn test_the_system_call_mark_does_not_outlive_the_call() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert!(!ctx.is_system_call()); + + ctx.on_new_system_call(); + assert!(ctx.is_system_call()); + + ctx.on_new_tx(false); + assert!(!ctx.is_system_call(), "a transaction is not a system call"); + + ctx.on_new_system_call(); + ctx.on_new_tx(true); + assert!(!ctx.is_system_call(), "nor is a system transaction, which the protocol sends"); + } + /// Two contexts may read one SALT environment — a node builds an EVM per transaction over /// the block's environments — and each keeps the multipliers it read to itself. #[test] @@ -523,4 +948,152 @@ mod tests { assert_eq!(ctx.external_envs().salt_env.get_bucket_capacity(7).unwrap(), 1_024); assert_satin_cfg(&ctx); } + + /// An Osaka configuration, every field the spec fixes set the other way from Satin's. + fn osaka_cfg() -> CfgEnv { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = 1; + cfg.gas_params = GasParams::new_spec(EthSpecId::OSAKA); + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.tx_gas_limit_cap = None; + cfg.enable_amsterdam_eip7708 = false; + cfg.amsterdam_eip7708_disabled = true; + cfg.limit_contract_code_size = None; + cfg.limit_contract_initcode_size = None; + cfg + } + + /// Asserts both configuration views carry `cfg` field for field. + fn assert_cfg_is(ctx: &MegaContext, cfg: &CfgEnv) { + assert_eq!(ctx.mega_cfg(), cfg); + assert_eq!(ctx.cfg(), &op_cfg(cfg)); + assert_eq!(ctx.cfg().gas_params.table(), cfg.gas_params.table()); + } + + fn call_from(caller: Address) -> MegaTransaction { + alloy_op_evm::OpTx(crate::test_utils::op_transaction(revm::context::TxEnv { + caller, + ..Default::default() + })) + } + + /// The neutral configuration takes every field from the caller — the ones the spec fixes + /// included — and prices no history. + #[test] + fn test_neutral_cfg_takes_every_field_as_given() { + let cfg = osaka_cfg(); + let ctx = + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg.clone()); + + assert!(ctx.is_neutral()); + assert!(!ctx.prices_history()); + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert_eq!(ctx.cfg().spec, OpSpecId::KARST); + assert_cfg_is(&ctx, &cfg); + } + + /// A new transaction neither prices history nor swaps the schedule for its history + /// exemption, whichever kind of transaction it is: a user's, a system call, a deposit. + #[test] + fn test_neutral_cfg_survives_every_kind_of_transaction() { + let cfg = osaka_cfg(); + let mut ctx = + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg.clone()); + + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert!(!ctx.prices_history(), "a user's transaction pays no history"); + assert_cfg_is(&ctx, &cfg); + + ctx.on_new_system_call(); + assert!(!ctx.prices_history()); + assert_cfg_is(&ctx, &cfg); + + let mut deposit = call_from(Address::repeat_byte(0x22)); + deposit.0.deposit.source_hash = revm::primitives::B256::repeat_byte(1); + deposit.0.base.tx_type = DEPOSIT_TRANSACTION_TYPE; + ctx.set_tx(deposit); + ctx.on_new_tx(false); + assert!(!ctx.prices_history()); + assert_cfg_is(&ctx, &cfg); + + // And back to a user's transaction, after an exempt one would have swapped the schedule. + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert!(!ctx.prices_history()); + assert_cfg_is(&ctx, &cfg); + } + + /// [`MegaContext::with_cfg`] returns a neutral context to the spec's configuration, and its + /// transactions pay history again. + #[test] + fn test_with_cfg_leaves_the_neutral_configuration() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN) + .with_neutral_cfg(osaka_cfg()) + .with_cfg(osaka_cfg()); + + assert!(!ctx.is_neutral()); + assert_satin_cfg(&ctx); + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert!(ctx.prices_history()); + assert_satin_cfg(&ctx); + } + + /// Whether a transaction counts transfer logs follows the rule revm's journal emits them by: + /// the switch turns them on below Amsterdam, and disabling EIP-7708 wins over it. Each + /// transaction reads the configuration afresh, and Satin's emits them. + #[test] + fn test_a_transaction_counts_transfer_logs_where_revm_emits_them() { + let endowed_creation = + revm::interpreter::FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( + Address::repeat_byte(0x11), + revm::interpreter::CreateScheme::Create, + U256::from(1), + revm::primitives::Bytes::new(), + 0, + 0, + ))); + let counts = |cfg: CfgEnv| { + let mut ctx = + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg); + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert_eq!( + ctx.additional_limit.frame_start_transfer_log(&endowed_creation), + emits_transfer_logs(ctx.cfg()), + ); + emits_transfer_logs(ctx.cfg()) + }; + let with = |enabled: bool, disabled: bool| { + let mut cfg = osaka_cfg(); + cfg.enable_amsterdam_eip7708 = enabled; + cfg.amsterdam_eip7708_disabled = disabled; + cfg + }; + assert!(counts(with(true, false))); + assert!(!counts(with(false, false)), "the base spec is below Amsterdam"); + assert!(!counts(with(true, true)), "disabling wins over the switch"); + assert!(!counts(with(false, true))); + + // Satin's own configuration emits them, whatever the caller's said. + let mut ctx = context_with(|cfg| { + cfg.enable_amsterdam_eip7708 = false; + cfg.amsterdam_eip7708_disabled = true; + }); + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert!(ctx.additional_limit.frame_start_transfer_log(&endowed_creation)); + } + + /// A context is not neutral unless it is asked to be. + #[test] + fn test_a_new_context_is_not_neutral() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert!(!ctx.is_neutral()); + ctx.set_tx(call_from(Address::repeat_byte(0x11))); + ctx.on_new_tx(false); + assert!(ctx.prices_history()); + } } diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 441be53ff..0db00ef6f 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -6,10 +6,11 @@ #[cfg(not(feature = "std"))] use alloc as std; -use core::cell::Cell; +use core::{cell::Cell, num::NonZeroU64}; use op_revm::{ handler::{IsTxError, OpHandler}, + transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; use std::vec::Vec; @@ -17,16 +18,18 @@ use std::vec::Vec; use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::{ - result::FromStringError, transaction::TransactionType, ContextError, ContextTr, FrameStack, - JournalTr, Transaction, + result::{FromStringError, InvalidTransaction, ResultGas}, + transaction::TransactionType, + ContextError, ContextTr, FrameStack, JournalTr, Transaction, }, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry}, + journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, Host, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, + execution::runtime_oog_unwind, instructions::InstructionProvider, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, @@ -37,17 +40,23 @@ use revm::{ }, interpreter::{ interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, - InitialAndFloorGas, InstructionResult, InterpreterAction, + InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, }, - primitives::{Address, Bytes, CALL_STACK_LIMIT}, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, Inspector, Journal, }; use crate::{ - evm::inspector::frame_end_checked, - synthetic_frame_result, - system::{is_deposit_like_transaction, MEGA_SYSTEM_ADDRESS}, - ExternalEnvTypes, JournalInspectTr, LimitCheck, MegaContext, MegaEvm, MegaInstructions, + access::ComputeStop, + charge_write_records_history, + evm::inspector::{ + frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, + UpfrontRecord, + }, + history_gas, synthetic_frame_result, + system::keyless, + Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, + PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; /// The Satin handler. @@ -77,6 +86,44 @@ impl Default for MegaHandler { } } +impl MegaHandler +where + DB: Database, + ExtEnvs: ExternalEnvTypes, + EVM: EvmTr, Frame = FRAME>, + ERROR: EvmTrError + From + FromStringError + IsTxError, + FRAME: FrameTr, +{ + /// [`validate_env`](Handler::validate_env) once the live system address is known: decides + /// whether the transaction is a system-address transaction — of the system shape, from + /// `system_address` — and prepares the common execution layer for it, refuses a transaction + /// from `system_address` without the system shape, validates a system-address transaction and + /// promotes it to a deposit, then validates the transaction as op-revm does. + /// + /// The layer is prepared before the refusal, so a deposit the refusal turns into a failed + /// deposit reports its body as data size, as a deposit that fails any other check does. + /// + /// The handler reads the address out of the state, and checks the system address's nonce and + /// code. What validates a transaction without state + /// ([`validate_transaction_stateless`](crate::validate_transaction_stateless)) is given the + /// address and leaves the account to the state, as it leaves every sender's + /// (`check_system_account` false); every other step is this one. + pub(crate) fn validate_env_as( + &self, + evm: &mut EVM, + system_address: Option

, + check_system_account: bool, + ) -> Result<(), ERROR> { + let ctx = evm.ctx_mut(); + let verdict = crate::system::classify_system_transaction(ctx.tx(), system_address); + ctx.on_new_tx(verdict == Ok(true)); + if verdict? { + crate::system::validate_and_promote::<_, _, ERROR>(ctx, check_system_account)?; + } + self.op.validate_env(evm) + } +} + impl Handler for MegaHandler where DB: Database, @@ -97,9 +144,16 @@ where /// own caller pays once, because by the time EIP-2780 looks at the recipient the account /// exists. /// - /// When those records would cross a limit, the limit is enforced before the writes it - /// guards: the authorizations are taken back with the gas they charged, and the transaction, - /// latched, is stopped at its first frame. + /// The two kinds of write record made outside any frame are charged their history here, where + /// they are made: one per applied authority, and the one the transaction's own frame makes — + /// the recipient of its value, or the account it creates. Neither is known at validation: an + /// authority applies or does not, and whether the recipient is already written depends on the + /// authorities that did. A transaction that cannot pay for them runs out of gas before its + /// first frame, the way one that cannot pay its authorizations does. + /// + /// Validation refused every transaction whose body, with a record for each entry of its + /// authorization list, crosses the data-size limit, so neither the body nor the authorities' + /// records cross it here, and no limit stops the transaction before its first frame. fn pre_execution( &self, evm: &mut Self::Evm, @@ -107,32 +161,40 @@ where ) -> Result, Self::Error> { self.load_accounts(evm)?; let checkpoint = evm.ctx().journal_mut().checkpoint(); + // A bail-out of the runtime gas phase unwinds as revm's does: the checkpoint is reverted + // and a creation's sender gets the nonce bump the frame would have made, so an included + // out-of-gas creation cannot be replayed. revm's own pre-execution never needs the bump, + // because only an EIP-7702 transaction, always a call, can bail out there; the two + // charges made here can fail for a creation too. if self.deposit_creates_caller.get() && !charge_created_caller(evm.ctx_mut(), gas) { - evm.ctx().journal_mut().checkpoint_revert(checkpoint); + runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); } - let gas_before = *gas; let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { - evm.ctx().journal_mut().checkpoint_revert(checkpoint); + runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); }; - if record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i).exceeded_limit() { - evm.ctx().journal_mut().checkpoint_revert(checkpoint); - *gas = gas_before; - let checkpoint = evm.ctx().journal_mut().checkpoint(); - return Ok(Some(PreExecutionOutput { eip7702_refund: 0, checkpoint })); + let applied = record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, applied) { + runtime_oog_unwind(evm.ctx(), checkpoint)?; + return Ok(None); } Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } - /// Validates a transaction sent from the system address and promotes it to a deposit, then - /// validates the transaction as op-revm does — as a deposit, when it was promoted. + /// Reads the live system address out of the registry, then decides whether the transaction + /// is a system-address transaction and prepares the common execution layer for it, then + /// validates a system-address transaction and promotes it to a deposit, then validates the + /// transaction as op-revm does — as a deposit, when it was promoted. + /// + /// This is the handler's first phase, so the layer is prepared before anything else of the + /// transaction runs, and a read the database cannot serve fails the transaction through the + /// handler's error path, which discards what the journal loaded. Every transaction reads the + /// live system address, whatever its shape, and the read leaves the registry's account and + /// its slot warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary. fn validate_env(&self, evm: &mut Self::Evm) -> Result<(), Self::Error> { - crate::system::validate_and_promote::<_, _, Self::Error>( - evm.ctx_mut(), - MEGA_SYSTEM_ADDRESS, - )?; - self.op.validate_env(evm) + let system_address = crate::system::load_system_address(evm.ctx_mut().journal_mut())?; + self.validate_env_as(evm, system_address, true) } /// Notes whether this transaction's caller is an account executing it creates, then deducts @@ -150,11 +212,95 @@ where self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } - /// Settles the outermost frame: pops its lane and, when the transaction is latched, turns its - /// result into the latched stop; then settles its gas into the transaction's as op-revm does - /// (op-revm replaces revm's settlement, so revm's never runs here): a stopped transaction - /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. - /// Keeps the history gas the transaction spent. + /// revm's intrinsic gas, with the history gas of the transaction's body added to the + /// EIP-8037 intrinsic state-gas slot. + /// + /// The body's bytes are fixed before the transaction runs, so their price is part of what a + /// gas limit has to cover for the transaction to be valid at all: a limit that falls short is + /// rejected before inclusion rather than included as an out-of-gas that burns the whole limit. + /// revm made that check on its own figure, so the grown figure is checked again here, with the + /// same error naming the same two numbers. + /// + /// The slot it rides in is the state one because that is the pool EIP-8037 pays it from: the + /// reservoir first, spilling onto the regular budget only past it, so a body does not take the + /// execution cap away from computation. The cap check revm made stands as it was — it tests + /// the regular intrinsic gas, which this does not touch — and + /// [`post_execution`](Handler::post_execution) takes the body back out of the state gas the + /// result reports. + /// + /// A transaction exempt from history gas carries none of it + /// ([`MegaContext::prices_history`](crate::MegaContext::prices_history)), so its intrinsic gas + /// is revm's own. + /// + /// Before any of it, the body and a write record for each entry of the authorization list are + /// held to the transaction's data-size limit, on the body count the common execution layer + /// keeps, the one the history gas prices: a transaction over it is refused + /// ([`TX_BODY_OVER_DATA_SIZE_LIMIT`]), whatever its gas, a deposit included, which op-revm + /// then includes as a failed deposit. Those are the only bytes a transaction counts before its + /// first frame, so one that passes cannot cross the limit there. A system-originated + /// transaction is exempt from the limit, and from the check. + fn validate_initial_tx_gas( + &self, + evm: &mut Self::Evm, + ) -> Result { + let authorizations = evm.ctx_ref().tx().authorization_list_len() as u64; + if !evm.ctx_ref().additional_limit.admits_tx_body(authorizations) { + return Err(InvalidTransaction::Str(TX_BODY_OVER_DATA_SIZE_LIMIT.into()).into()); + } + let mut gas = self.op.validate_initial_tx_gas(evm)?; + if !evm.ctx_ref().prices_history() { + return Ok(gas); + } + let bytes = evm.ctx_ref().additional_limit.body_bytes(); + // A byte count with no price saturates, which no gas limit covers: the transaction is + // rejected for not covering its own intrinsic gas. + let history = history_gas(bytes).unwrap_or(u64::MAX); + let gas_limit = evm.ctx_ref().tx().gas_limit(); + let initial_gas = gas + .initial_regular_gas() + .saturating_add(gas.initial_state_gas_final().saturating_add(history)); + if initial_gas > gas_limit { + return Err( + InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }.into() + ); + } + gas.set_initial_state_gas(gas.initial_state_gas_final() + history); + evm.ctx_mut().additional_limit.set_intrinsic_history(history, bytes); + Ok(gas) + } + + /// revm's first frame, with a read of the block beneficiary's account marked for gas detention + /// when the transaction's recipient delegates to the beneficiary: revm resolves that delegate + /// through the journal, where the Host does not see it. + fn first_frame_input( + &mut self, + evm: &mut Self::Evm, + gas: &mut GasTracker, + ) -> Result, Self::Error> { + let Some(frame) = self.op.first_frame_input(evm, gas)? else { + // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge + // for the account the frame adds, a call's recipient or a creation's account, or the + // access to the code a delegated recipient runs, warm or cold. A price of that account + // charge that could not be read ends here too: the lookup recorded its cause, which + // fails the transaction when it settles. In each case revm drops the phase's partial + // charges by rebuilding the transaction's gas from its intrinsic cost, and the history + // charged for the first frame's write record went with them: the settlement must not + // give it back a second time, into a reservoir a transaction below the execution cap + // never had. + evm.ctx_mut().additional_limit.set_top_level_write_record_gas(0); + return Ok(None); + }; + evm.ctx_mut().mark_beneficiary_delegate(); + Ok(Some(frame)) + } + + /// Settles the outermost frame: pops its lane, then settles its gas into the transaction's as + /// op-revm does (op-revm replaces revm's settlement, so revm's never runs here): a transaction + /// whose own frame a limit stopped settles like an EIP-8037 revert, its unspent regular gas + /// and reservoir back to the sender. + /// Keeps the history gas the transaction spent: what the body was charged, and what the frames + /// charged net of what they gave back; and the history bytes it appended, which are what those + /// charges were made for. fn last_frame_result( &mut self, evm: &mut Self::Evm, @@ -163,11 +309,43 @@ where ) -> Result<(), Self::Error> { evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); self.op.last_frame_result(evm, frame_result, parent_gas)?; - let history = frame_result.gas().history_gas_spent().max(0) as u64; - evm.ctx_mut().additional_limit.set_history_gas_spent(history); + // The write record the transaction's own frame makes was charged before execution; a + // frame that failed keeps no such write, so the charge goes back the way EIP-8037 gives + // back the state gas of the account that frame would have created. + let instruction_result = frame_result.instruction_result(); + if !instruction_result.is_ok() { + parent_gas.refill_history(evm.ctx_ref().additional_limit.top_level_write_record_gas()); + if instruction_result.is_halt() { + parent_gas.spend_all(); + } + *frame_result.gas_mut().tracker_mut() = *parent_gas; + } + let priced = evm.ctx_ref().prices_history(); + let layer = &mut evm.ctx_mut().additional_limit; + let history = layer + .intrinsic_history_gas() + .saturating_add_signed(frame_result.gas().history_gas_spent()); + layer.set_history_gas_spent(history); + layer.settle_history_bytes(priced); Ok(()) } + /// revm's post-execution, on the intrinsic gas with the body's history taken back out of the + /// state slot it rode in: the result's state gas is state gas alone, and the history the + /// transaction spent is reported on its own ledger. + fn post_execution( + &self, + evm: &mut Self::Evm, + exec_result: &mut FrameResult, + init_and_floor_gas: InitialAndFloorGas, + eip7702_gas_refund: i64, + ) -> Result { + let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); + let init_and_floor_gas = init_and_floor_gas + .with_initial_state_gas(init_and_floor_gas.initial_state_gas_final() - history); + self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) + } + fn reimburse_caller( &self, evm: &mut Self::Evm, @@ -202,6 +380,11 @@ where self.op.execution_result(evm, result, result_gas) } + /// op-revm's error handling, which answers a deposit's transaction error with a failed-deposit + /// halt and discards everything the deposit did. The halt is what the transaction reports; + /// what the deposit counted stands, the body and the Oracle hints it forwarded before it + /// halted, as for any transaction that halts. Any other error refuses the transaction, and the + /// layer's state is reset by the next one. fn catch_error( &self, evm: &mut Self::Evm, @@ -261,20 +444,36 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = answer_before_building(&mut self.inner.ctx, &frame_init)? { - self.inner.ctx.additional_limit.push_empty_frame(); + if let Some(result) = self.answered_before_building(&frame_init) { return Ok(ItemOrResult::Result(result)); } - if let Some(result) = self.intercept(&mut frame_init) { + let keyless = keyless::is_dispatched(&self.inner.ctx, &frame_init); + let answer = if keyless { + keyless::ready(&mut self.inner.ctx, &mut frame_init)? + } else { + self.intercept(&frame_init) + }; + let (depth, gas_limit) = (frame_init.depth, input_gas_limit(&frame_init.frame_input)); + if let Some(mut result) = answer { self.inner.ctx.additional_limit.push_empty_frame(); + settle_answer(&mut self.inner.ctx, depth, gas_limit, &mut result); return Ok(ItemOrResult::Result(result)); } - let frame_init = self.rewrite_keyless(frame_init); + record_caller(&mut self.inner.ctx, &mut self.inner.frame_stack, depth); let ctx = &mut self.inner.ctx; - let check = ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); - if check.exceeded_limit() { - return Ok(ItemOrResult::Result(stop_before_building(ctx, &frame_init, &check)?)); + let refused = start_refused(ctx, &frame_init.frame_input); + if refused { + ctx.additional_limit.push_empty_frame(); + } else { + let check = + ctx.additional_limit.on_frame_init(&frame_init.frame_input, frame_init.depth); + if check.exceeded_limit() { + return Ok(ItemOrResult::Result(stop_before_building(ctx, &frame_init, &check)?)); + } } - // The creator of a creation, to tell afterwards whether revm bumped its nonce. The - // transaction's own creation has no creator record to take back, so the check is a - // no-op there. - let creator = match &frame_init.frame_input { - FrameInput::Create(inputs) => { - Some((inputs.caller(), account_nonce(ctx, inputs.caller()))) + #[cfg(debug_assertions)] + let counted = ( + ctx.additional_limit.frame_start_transfer_log(&frame_init.frame_input), + refused, + ctx.journal_ref().logs().len(), + ); + let hold = hold_precompile( + ctx, + &self.inner.precompiles, + &self.priced_precompiles, + &mut frame_init, + refused, + ); + // Where the frame's start begins, for an answer the engine then stops. Only gas detention + // turns an answer into the stop, and only once a read set its limit, which a frame's start + // reads nothing to set. + let start = ctx.detention.compute_limit().is_some().then(|| journal_position(ctx)); + let outcome = if hold == PrecompileHold::Crossing { + Err(crossing_answer(&frame_init.frame_input)) + } else { + match self.inner.frame_init(frame_init)? { + ItemOrResult::Item(frame) => Ok(frame.interpreter.input.target_address), + ItemOrResult::Result(result) => Err(result), } - _ => None, - }; - let outcome = match self.inner.frame_init(frame_init)? { - ItemOrResult::Item(frame) => Ok(frame.interpreter.input.target_address), - ItemOrResult::Result(result) => Err(result), }; let ctx = &mut self.inner.ctx; + #[cfg(debug_assertions)] + assert_start_as_counted(ctx, counted, outcome.as_ref().err()); + debug_assert!(!keyless || outcome.is_ok(), "revm builds a keylessDeploy call's frame"); match outcome { Ok(address) => { ctx.additional_limit.set_frame_address(address); + if keyless { + ctx.keyless_frame = Some(keyless::KeylessFrame::Built); + } Ok(ItemOrResult::Item(self.inner.frame_stack.get())) } - Err(result) => { - if let Some((creator, nonce)) = creator { - if account_nonce(ctx, creator) == nonce { - ctx.additional_limit.creation_did_not_bump_nonce(); - } + Err(mut result) => { + if let PrecompileHold::Clamped(withheld) = hold { + Detention::restore_forward(result.interpreter_result_mut(), withheld); + } + let succeeded = result.instruction_result().is_ok(); + settle_answer(ctx, depth, gas_limit, &mut result); + match start { + Some(start) => take_back_a_stopped_answer(ctx, start, succeeded, &result), + None => debug_assert!( + !succeeded || result.instruction_result().is_ok(), + "an answer became the stop with no compute limit set" + ), } Ok(ItemOrResult::Result(result)) } } } - /// Runs the frame on top of the stack, unless the transaction is latched: then the frame - /// returns the stop without running another instruction (see [`before_frame_run`]). + /// Runs the frame on top of the stack, unless it has a stop to return: its own, when what a + /// child left it put it over a limit. Then the frame returns the stop without running another + /// instruction (see [`before_frame_run`]). A `keylessDeploy` call's + /// frame runs no instruction at all: its actions are made by hand ([`keyless::run`]). + /// + /// Gas detention holds the frame to the compute limit before it runs, and settles the frame + /// once it suspends on a child or returns (see [`after_frame_run`]). #[inline] fn frame_run( &mut self, @@ -339,29 +581,49 @@ impl EvmTr for MegaEvm action, + None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, None => frame.interpreter.run_plain( evm.instruction.instruction_table(), evm.instruction.gas_table(), ctx, ), }; - frame.process_next_action(ctx, action).inspect(|next| { + let mut next = frame.process_next_action(ctx, action); + after_frame_run(ctx, frame, &mut next); + next.inspect(|next| { if next.is_result() { frame.set_finished(true); } }) } - /// Pops the returning frame's lane (merged on success, discarded on failure; under a latch the - /// result is first rewritten to the stop), then returns the result to the caller as revm - /// does. + /// Pops the returning frame's lane (merged on success, discarded on failure), then returns the + /// result to the caller as revm does. + /// + /// The creation a `keylessDeploy` call started returns into the call: what the call answers is + /// read off the creation's result before revm merges it ([`keyless::returning`]), and settled + /// into the call after ([`keyless::settle`]). #[inline] fn frame_return_result( &mut self, - mut result: FrameResult, + result: FrameResult, ) -> Result, ContextDbError> { - self.inner.ctx.additional_limit.on_frame_return(&mut result); - self.inner.frame_return_result(result) + let refund = self.inner.ctx.additional_limit.on_frame_return(&result); + let creation = keyless::returning(&self.inner.ctx, &mut self.inner.frame_stack, &result); + let returned = self.inner.frame_return_result(result)?; + // The history of the records the caller paid for and the frame did not keep, given back + // after the merge that adopted the frame's pools. `Some` means the outermost frame + // returned, whose caller is the transaction: it paid for no record of it. + if returned.is_some() { + debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); + return Ok(returned); + } + let caller = &mut self.inner.frame_stack.get().interpreter.gas; + caller.refill_history(refund); + if let Some(creation) = creation { + keyless::settle(&mut self.inner.ctx, caller, creation)?; + } + Ok(returned) } } @@ -408,26 +670,38 @@ where } /// revm's inspected frame start, with the lanes kept aligned: a frame the inspector answers - /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it. + /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it, and its + /// answer settles as a frame that never started ([`answered_by_inspector`]). + /// + /// A frame nothing may start, one past the call-stack limit, is answered by + /// [`EvmTr::frame_init`], after the inspector's `frame_start`, as every frame revm does not + /// build is, and the inspector is told it ended. + /// + /// A keyless deployment is seen as the frames it is made of: the transaction's `keylessDeploy` + /// call, and the creation it starts, one journal depth below it, as its child. The call's + /// frame runs no code, so the inspector is not told an interpreter was initialized for it. #[inline] fn inspect_frame_init( &mut self, mut frame_init: FrameInit, ) -> Result, ContextDbError> { + // An inspector may have rewritten the input the opcode left pending, or rewrite it at the + // frame's start: the caller's answer is asked again on the input it leaves. + let _ = self.inner.ctx.additional_limit.take_start_refused(); let (ctx, inspector) = self.ctx_inspector(); - if let Some(mut output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - // The inspector answered the frame. The latch and the depth guard still hold: an - // answer cannot start a frame of a stopped transaction, nor reach past the call-stack - // limit. - if let Some(answer) = answer_before_building(ctx, &frame_init)? { - output = answer; - } - ctx.additional_limit.push_empty_frame(); - frame_end_checked(ctx, inspector, &frame_init.frame_input, &mut output); + // What the calling opcode charged upfront, before the inspector's hooks can rewrite the + // call it charged for. + let upfront = UpfrontRecord::of(&frame_init.frame_input); + if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { + let output = answered_by_inspector(ctx, inspector, &frame_init, output, upfront); return Ok(ItemOrResult::Result(output)); } - let frame_input = frame_init.frame_input.clone(); - let logs_i = ctx.journal().logs().len(); + let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); + // What the start journals begins here. A start answered with a success without a frame + // is revm's — a call to a precompile or to an account with no code, which takes its + // checkpoint before it journals anything — or an interceptor's, which journals nothing. + let start = journal_position(ctx); + let logs_i = start.log_i; if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { let (ctx, inspector) = self.ctx_inspector(); // Logs the frame journaled without running: the EIP-7708 transfer log, and the logs @@ -443,19 +717,28 @@ where } } } - frame_end_checked(ctx, inspector, &frame_input, &mut output); + let source = ResultSource::Engine(start); + frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source, upfront); return Ok(ItemOrResult::Result(output)); } let (ctx, inspector, frame) = self.ctx_inspector_frame(); + ctx.upfront_records.resize(depth, None); + ctx.upfront_records.push(upfront); if ctx.journal().logs().len() != logs_i { inspect_logs(ctx, inspector, logs_i); } - inspector.initialize_interp(&mut frame.interpreter, ctx); + if !keyless::runs(ctx, frame) { + inspector.initialize_interp(&mut frame.interpreter, ctx); + } Ok(ItemOrResult::Item(frame)) } - /// revm's inspected frame run, with the latch short-circuit of [`EvmTr::frame_run`]: a frame - /// of a latched transaction returns the stop without a step, and the inspector sees it end. + /// revm's inspected frame run, with the stop short-circuit of [`EvmTr::frame_run`]: a frame + /// with a stop to return returns it without a step, and the inspector sees it end. A + /// `keylessDeploy` call's frame makes its actions by hand, as on the plain path, with no step. + /// + /// The step callbacks run through [`StepGuard`], so a charge the inspector makes on the + /// interpreter's gas and the frame cannot pay does not classify the frame's end. #[inline] fn inspect_frame_run( &mut self, @@ -463,46 +746,243 @@ where let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); let action = match before_frame_run(ctx, frame) { Some(action) => action, + None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, None => inspect_instructions( ctx, &mut frame.interpreter, - &mut *inspector, + StepGuard(&mut *inspector), instructions.instruction_table(), instructions.gas_table(), ), }; let mut next = frame.process_next_action(ctx, action); + after_frame_run(ctx, frame, &mut next); if let Ok(ItemOrResult::Result(result)) = &mut next { - frame_end_checked(ctx, inspector, &frame.input, result); + let source = ResultSource::Engine(frame.checkpoint); + let upfront = ctx.upfront_records.get(frame.depth).copied().flatten(); + frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source, upfront); frame.set_finished(true); } next } } -/// The action of a frame about to run: the latched stop, returned without running an -/// instruction, when the transaction is latched; `None` otherwise, and the frame runs. +/// The action of a frame about to run: the stop it returns without running an instruction, when +/// it has one ([`stop_before_run`](crate::AdditionalLimit::stop_before_run)); `None` otherwise, +/// and the frame runs. +/// +/// A frame runs here for the first time or after a child returned into it. A stop is always the +/// latter: the child was a failed creation whose nonce record, which lands on its creator, put the +/// creator over a limit, its budget or the transaction's, and the creator reverts alone, as for a +/// write of its own. A child that crossed a limit itself reverted alone, and its caller resumes. /// -/// A frame runs here for the first time or after a child returned into it. Under a latch it is -/// the latter: the child that crossed the limit reverted, and its caller must not resume. +/// Either way gas detention sees the frame first: a frame's first run adds its caller's compute +/// to the transaction's, a resume takes it back, and the frame's spendable gas is held to what the +/// compute limit leaves it — which is how a child's read of volatile data caps every caller it +/// returns into. #[inline] fn before_frame_run( - ctx: &MegaContext, - frame: &EthFrame, + ctx: &mut MegaContext, + frame: &mut EthFrame, ) -> Option { - let latched = ctx.additional_limit.latched()?; + ctx.detention.on_frame_run(&mut frame.interpreter.gas, frame.depth); + let stop = ctx.additional_limit.stop_before_run()?; Some(InterpreterAction::new_return( InstructionResult::Revert, - latched.revert_data(), + ctx.additional_limit.note_frame_stop(&stop), frame.interpreter.gas, )) } -/// The result of a frame a limit stopped before it ran: a revert with the stop's -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a -/// [`synthetic_frame_result`] that settles like a frame revm ran. -fn stopped_frame_result(frame_init: &FrameInit, check: &LimitCheck) -> FrameResult { - synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, check.revert_data()) +/// Settles gas detention once the frame ran: a frame that suspends on a child keeps its compute +/// for the child's start to add to the transaction's; a frame that returns is classified. +/// +/// The frame's result is read here, after revm processed its last action — `return_create` +/// included, whose deposit and hash charges are the creating frame's own compute — and before +/// revm hands it to the caller or, for the transaction's own frame, to +/// [`last_frame_result`](Handler::last_frame_result), which overwrites its gas with the +/// transaction's. +/// +/// A frame that ran out of gas on a charge the withheld part of its gas would have paid crossed +/// the compute limit rather than its own gas: its halt becomes the compute stop, a revert of that +/// frame alone ([`stop_at_the_compute_limit`]). Every other out-of-gas halts, as it would without +/// the read. +#[inline] +fn after_frame_run( + ctx: &mut MegaContext, + frame: &EthFrame, + next: &mut Result>, E>, +) { + match next { + Ok(ItemOrResult::Item(_)) => { + ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); + } + Ok(ItemOrResult::Result(result)) => { + let instruction_result = result.instruction_result(); + if let Some(stop) = + ctx.detention.on_frame_end(instruction_result, result.gas_mut(), frame.depth) + { + stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); + } + } + Err(_) => {} + } +} + +/// Records, for gas detention, the frame revm is about to build a child of at `depth`, while no +/// read has set a limit ([`Detention::on_child_build`]): the caller is still on top of the stack. +#[inline] +fn record_caller( + ctx: &mut MegaContext, + frame_stack: &mut FrameStack>, + depth: usize, +) { + if depth > 0 && ctx.detention.records_callers() { + debug_assert_eq!(frame_stack.index(), Some(depth - 1), "the caller is on top"); + ctx.detention.on_child_build(depth, &frame_stack.get().interpreter.gas); + } +} + +/// Holds a frame answered without running to the compute limit: the answer to a frame of +/// `gas_limit` at `depth`, which its caller forwarded. +/// +/// An interceptor builds its answer on the whole gas the caller forwarded, the part gas detention +/// withholds from the caller's regular charges included. An answer that spent more than the frame +/// could have run on is answered out of gas and marked as a crossing, and becomes the stop as a +/// frame that ran would ([`Detention::on_answer`]); so does a precompile whose price crosses the +/// limit, and one the engine cannot price that ran out of the allowance it was run on +/// ([`hold_precompile`]). An answer that halts otherwise burns what it was given. +fn settle_answer( + ctx: &mut MegaContext, + depth: usize, + gas_limit: u64, + answer: &mut FrameResult, +) { + let answer = answer.interpreter_result_mut(); + if let Some(stop) = ctx.detention.on_answer(answer, depth, gas_limit) { + stop_at_the_compute_limit(ctx, answer, stop); + } +} + +/// How gas detention holds the precompile call a frame start makes ([`hold_precompile`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PrecompileHold { + /// The call runs as it would without the limit. + Unheld, + /// The call runs on the allowance, and its answer gets back what was taken off the forward. + Clamped(NonZeroU64), + /// The call's price crosses the limit: it is answered without running ([`crossing_answer`]). + Crossing, +} + +/// Holds a precompile the frame `frame_init` is about to call to what gas detention's limit leaves +/// it: revm runs the precompile inside the frame's start, against its gas limit, so a precompile +/// forwarded more than the allowance would otherwise compute past the limit before its answer +/// could be classified. +/// +/// A call to anything else, and a forward within the allowance, run as they are +/// ([`Unheld`](PrecompileHold::Unheld)). A precompile the engine can price +/// ([`PricedPrecompiles::price`]) is decided from its price before it runs: +/// +/// - priced within the allowance, it runs on its whole forward, as without the limit: it charges +/// its price either way; +/// - priced past the allowance and within the forward, it needs gas the limit withholds: it is +/// answered without running ([`Crossing`](PrecompileHold::Crossing)), out of gas and marked as a +/// crossing, which the answer's settlement turns into the stop; +/// - priced past its whole forward, it runs on the forward and runs out of gas, as without the +/// limit: a failed call its caller survives. +/// +/// The price does not tell whether the input passes the checks a precompile makes after its gas +/// check, so an input priced past the allowance and within the forward is the stop even when +/// those checks would fail the call. A call revm refuses on its caller's account — a value it +/// cannot fund — runs no precompile, and revm answers it as without the limit. +/// +/// A precompile the engine cannot price is run on the allowance and sees it as its gas limit +/// ([`Clamped`](PrecompileHold::Clamped), with what was taken off the forward); its answer gets the +/// rest back ([`Detention::restore_forward`]) before it is settled. One priced past the allowance +/// runs out of gas on it and is the stop, whether its price is within the forward or not. +#[inline] +fn hold_precompile( + ctx: &MegaContext, + precompiles: &PrecompilesMap, + priced: &PricedPrecompiles, + frame_init: &mut FrameInit, + refused: bool, +) -> PrecompileHold { + if ctx.detention.compute_limit().is_none() { + return PrecompileHold::Unheld; + } + hold_detained_precompile(ctx, precompiles, priced, frame_init, refused) +} + +/// [`hold_precompile`] once a read set a compute limit. +#[inline(never)] +fn hold_detained_precompile( + ctx: &MegaContext, + precompiles: &PrecompilesMap, + priced: &PricedPrecompiles, + frame_init: &mut FrameInit, + refused: bool, +) -> PrecompileHold { + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { + return PrecompileHold::Unheld; + }; + let Some(allowance) = ctx.detention.allowance(frame_init.depth, inputs.gas_limit) else { + return PrecompileHold::Unheld; + }; + let Some(withheld) = NonZeroU64::new(inputs.gas_limit.saturating_sub(allowance)) else { + return PrecompileHold::Unheld; + }; + if precompiles.get(&inputs.bytecode_address).is_none() { + return PrecompileHold::Unheld; + } + let price = priced.price(precompiles, &inputs.bytecode_address, &inputs.input.as_bytes(ctx)); + let Some(price) = price else { + inputs.gas_limit = allowance; + return PrecompileHold::Clamped(withheld); + }; + if price <= allowance || price > inputs.gas_limit || refused { + return PrecompileHold::Unheld; + } + PrecompileHold::Crossing +} + +/// The answer to the precompile call `input` starts when its price crosses gas detention's limit +/// ([`PrecompileHold::Crossing`]): out of gas without running, the forward untouched, and marked +/// as the crossing ([`Detention::cross_at_price`]). +#[cold] +#[inline(never)] +fn crossing_answer(input: &FrameInput) -> FrameResult { + let mut answer = synthetic_frame_result(input, InstructionResult::PrecompileOOG, Bytes::new()); + Detention::cross_at_price(answer.interpreter_result_mut()); + answer +} + +/// The gas limit of the frame `input` starts. +const fn input_gas_limit(input: &FrameInput) -> u64 { + match input { + FrameInput::Call(inputs) => inputs.gas_limit, + FrameInput::Create(inputs) => inputs.gas_limit(), + FrameInput::Empty => 0, + } +} + +/// Turns a frame that crossed gas detention's compute limit into the compute stop: a revert of +/// that frame alone carrying `MegaLimitExceeded` (kind: compute). The frame's gas is what it had +/// before the charge that crossed, which goes back with the revert to its caller. The caller +/// resumes held to what the limit leaves the transaction, which is less than the charge that +/// crossed, so a caller that carries on is stopped at its next charge past it. +/// +/// The crossing charge's size is not kept, so the stop reports the transaction's compute at the +/// crossing as what was used ([`LimitCheck::ExceedsLimit`]): what its regular ledger bills. +fn stop_at_the_compute_limit( + ctx: &mut MegaContext, + result: &mut InterpreterResult, + stop: ComputeStop, +) { + let stop = ctx.additional_limit.crossed(LimitKind::ComputeGas, stop.limit, stop.used, false); + result.result = InstructionResult::Revert; + result.output = ctx.additional_limit.note_frame_stop(&stop); } impl MegaEvm { @@ -515,47 +995,88 @@ impl MegaEvm { /// contract. A creation reaches no interceptor either. /// /// An answer is a [`synthetic_frame_result`](crate::synthetic_frame_result), so it settles - /// like a frame revm ran. An interceptor that lets the frame run may charge it instead of - /// answering it, which is why the frame is taken mutably. What each contract answers is in - /// the `system` module. + /// like a frame revm ran. What each contract answers is in the `system` module. #[inline] - fn intercept(&mut self, frame_init: &mut FrameInit) -> Option { - let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return None }; + fn intercept(&mut self, frame_init: &FrameInit) -> Option { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; if !matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall) { return None; } - crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth) + // The calling frame is on top of the stack, suspended on this call; the transaction's own + // call has none. + let caller_remaining = match self.inner.frame_stack.index() { + Some(_) => self.inner.frame_stack.get().interpreter.gas.remaining(), + None => 0, + }; + crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth, caller_remaining) } - /// The keyless deployment rewrite: a keyless deployment call turned into the native creation - /// it stands for. - /// - /// The extension point of native keyless deployment; nothing is rewritten yet. - // Takes the EVM mutably: the rewrite validates the deployment against the journal. - #[allow(clippy::needless_pass_by_ref_mut)] + /// Step 1 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may start, one + /// past the call-stack limit ([`call_too_deep`]), with the empty lane that stands in for it. On + /// the inspected path it comes after the inspector's `frame_start`. #[inline] - const fn rewrite_keyless(&mut self, frame_init: FrameInit) -> FrameInit { - frame_init + fn answered_before_building(&mut self, frame_init: &FrameInit) -> Option { + let answer = call_too_deep(frame_init); + if answer.is_some() { + self.inner.ctx.additional_limit.push_empty_frame(); + } + answer } } -/// The answer a frame gets before anything builds or answers it otherwise, in this order: the -/// latched stop of a stopped transaction, then the depth guard's `CallTooDeep`. -fn answer_before_building( +/// Takes the journal back to `start`, where a frame's start began, when revm answered the frame +/// with a success (`succeeded`) that the engine then rewrote into `result`, the stop. +/// +/// revm commits an answered frame's journal checkpoint before its answer returns: a value transfer +/// to an account with no code, or to a precompile that answers, has moved the value, created the +/// recipient and journaled the transfer log by then. The stop is a revert of the frame alone, and +/// the caller that resumes keeps its own writes, so the answer's writes are taken back here, as +/// revm takes back a frame that fails; for the transaction's own frame, which has no caller, this +/// is all that takes them back. The journal's depth is left as it is. +fn take_back_a_stopped_answer( ctx: &mut MegaContext, - frame_init: &FrameInit, -) -> Result, ContextDbError>> { - if let Some(latched) = ctx.additional_limit.latched().copied() { - return stop_before_building(ctx, frame_init, &latched).map(Some); + start: JournalCheckpoint, + succeeded: bool, + result: &FrameResult, +) { + if succeeded && !result.instruction_result().is_ok() { + revert_journal_to(ctx, start); } - Ok(call_too_deep(frame_init)) } -/// Answers a frame a limit stops before it is built with the stop. +/// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as +/// [`EvmTr::frame_init`] settles an answer: the depth guard still holds, so an answer cannot reach +/// past the call-stack limit; an empty lane stands in for the frame, and the answer is held to the +/// compute limit ([`settle_answer`]). Then the inspector is told the frame ended, and the answer +/// settles as a frame that kept nothing: the frame never started, so no value moved and no account +/// was added, and the upfront state gas its caller's opcode was charged comes back whatever the +/// answer ([`frame_end_checked`]). +fn answered_by_inspector( + ctx: &mut MegaContext, + inspector: &mut INSP, + frame_init: &FrameInit, + output: FrameResult, + upfront: Option, +) -> FrameResult +where + INSP: Inspector, EthInterpreter>, +{ + let mut output = call_too_deep(frame_init).unwrap_or(output); + ctx.additional_limit.push_empty_frame(); + let gas_limit = input_gas_limit(&frame_init.frame_input); + settle_answer(ctx, frame_init.depth, gas_limit, &mut output); + let (input, depth) = (&frame_init.frame_input, frame_init.depth); + frame_end_checked(ctx, inspector, input, &mut output, depth, ResultSource::Inspector, upfront); + output +} + +/// Answers a frame a limit stops before it is built with the stop: a revert with the stop's +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a [`synthetic_frame_result`] that +/// settles like a frame revm ran. /// /// A creation still bumps its creator's nonce, as one that starts and reverts does: a nested -/// creation's caller sees an ordinary failed creation, and a creation transaction stopped before -/// its first frame cannot be replayed. +/// creation's caller sees an ordinary failed creation, and a creation transaction whose own frame +/// is stopped at its start cannot be replayed. fn stop_before_building( ctx: &mut MegaContext, frame_init: &FrameInit, @@ -564,19 +1085,25 @@ fn stop_before_building( if let FrameInput::Create(inputs) = &frame_init.frame_input { let _ = ctx.journal_mut().load_account_mut(inputs.caller())?.data.bump_nonce(); } - Ok(stopped_frame_result(frame_init, check)) + let output = ctx.additional_limit.note_frame_stop(check); + Ok(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) } -/// The depth guard: a `CALL` or `STATICCALL` past the call-stack limit, answered with -/// `CallTooDeep`, its gas untouched and its reservoir carried. +/// The depth guard: a frame past the call-stack limit, of any call scheme or a creation, answered +/// with `CallTooDeep`, its gas untouched and its reservoir carried — the answer revm gives it. +/// +/// revm checks the depth first when it builds a frame, before it moves value or bumps a creator's +/// nonce. The guard gives the same answer before anything else sees the frame: an interceptor or an +/// inspector answers before revm builds anything, so without the guard a system contract could be +/// reached at any depth; and a start's writes are counted before revm decides it, so without the +/// guard a creation past the limit would count its creator's nonce record — which outlives a failed +/// creation — for a nonce revm never bumps. /// -/// revm checks the depth when it builds a frame; an interceptor or an inspector answers before -/// revm builds anything, so without the guard a system contract could be reached at any depth. -/// `CALLCODE` and `DELEGATECALL` never reach an interceptor and are left to revm's own check. +/// No transaction reaches the limit: regular gas is capped by the execution cap and every call +/// forwards at most sixty-three sixty-fourths of what its caller has left, so a frame at depth +/// 1,024 has a few gas. fn call_too_deep(frame_init: &FrameInit) -> Option { - let FrameInput::Call(inputs) = &frame_init.frame_input else { return None }; - let guarded = matches!(inputs.scheme, CallScheme::Call | CallScheme::StaticCall); - (guarded && frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { + (frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { synthetic_frame_result( &frame_init.frame_input, InstructionResult::CallTooDeep, @@ -585,6 +1112,60 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } +/// Asserts that revm started a frame the way the data size counted its start, once revm has built +/// the frame or answered it: that revm refused exactly the start [`caller_refuses_start`] +/// predicted, and journaled exactly the EIP-7708 transfer log counted. `counted` is whether the +/// start counts a transfer log when revm makes it +/// ([`frame_start_transfer_log`](crate::AdditionalLimit)), `refused` whether it was predicted +/// refused and so counted nothing, `logs_i` the journal's log count before revm acted, and +/// `answer` revm's answer when it did not build the frame. +/// +/// The count is made before revm decides, from the frame's input and its caller's account, so this +/// is where a divergence from revm's own rules would show. revm refuses a start on its caller's +/// account with `OutOfFunds`, for a value the caller cannot fund, and with a `Return` for a +/// creation whose creator's nonce cannot be bumped — the one creation it answers with a success. +/// It refuses a start past the call-stack limit too, but the depth guard answers that start +/// before revm sees it ([`call_too_deep`]), so revm never answers one. A built frame has run no +/// instruction yet, so the move is all revm has done. An answered call +/// moved the value when it succeeded — a call to an account with no code, a precompile — and took +/// the move back when it failed. A creation revm answers never moved value: it refused before its +/// checkpoint, or reverted it (a creation onto an occupied address). Only transfer logs are +/// compared: a precompile may journal logs of its own. +#[cfg(debug_assertions)] +fn assert_start_as_counted( + ctx: &MegaContext, + (counted, refused, logs_i): (bool, bool, usize), + answer: Option<&FrameResult>, +) { + debug_assert!( + answer.is_none_or(|answer| answer.instruction_result() != InstructionResult::CallTooDeep), + "the depth guard answers every start past the call-stack limit" + ); + let refused_by_revm = match answer { + None => false, + Some(FrameResult::Call(outcome)) => outcome.result.result == InstructionResult::OutOfFunds, + Some(FrameResult::Create(outcome)) => matches!( + outcome.result.result, + InstructionResult::OutOfFunds | InstructionResult::Return + ), + }; + debug_assert_eq!(refused, refused_by_revm, "the start revm refused is the one predicted"); + let moved = match answer { + None => true, + Some(FrameResult::Call(outcome)) => outcome.result.result.is_ok(), + Some(FrameResult::Create(_)) => false, + }; + let journaled = ctx.journal_ref().logs()[logs_i..] + .iter() + .filter(|log| log.address == revm::primitives::eip7708::ETH_TRANSFER_LOG_ADDRESS) + .count(); + debug_assert_eq!( + journaled, + usize::from(counted && moved), + "the transfer log counted is the one revm journaled" + ); +} + /// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. #[cold] #[inline(never)] @@ -605,19 +1186,21 @@ fn inspect_logs( /// whose caller is empty, which the deposit path materialises by bumping its nonce or by minting /// to it. /// -/// Read before op-revm deducts the caller, which is what materialises the account. Every other -/// transaction pays a fee its caller must hold, so it has an account already. +/// Read before op-revm deducts the caller, which is what materialises the account, and after +/// [`validate_env`](Handler::validate_env), which promoted a system-address transaction: a +/// deposit-like transaction is a deposit by then. Every other transaction pays a fee its caller +/// must hold, so it has an account already. /// -/// The read does not warm the account: the transaction's own touches of it pay what they would -/// have paid without the check. +/// The read loads the caller as op-revm's deduction then does: the transaction's caller starts +/// warm, so the read changes nothing the transaction pays. fn deposit_creates_caller( ctx: &mut MegaContext, ) -> Result { - if !is_deposit_like_transaction(ctx.tx(), MEGA_SYSTEM_ADDRESS) { + if ctx.tx().tx_type() != DEPOSIT_TRANSACTION_TYPE { return Ok(false); } let caller = ctx.tx().caller(); - Ok(ctx.journal_mut().inspect_account(caller, false)?.info.is_empty()) + Ok(ctx.journal_mut().load_account(caller)?.data.info.is_empty()) } /// Charges the state gas of the account a deposit-like transaction creates for its caller, as @@ -633,24 +1216,92 @@ fn charge_created_caller( gas.record_state_cost(state_gas) } -/// The nonce of an account the journal holds; zero for one it does not. -fn account_nonce( +/// Whether revm refuses to start the frame `input` asks for on what its caller's account holds: +/// a value the caller cannot fund, which revm answers with `OutOfFunds`, and a creation whose +/// creator's nonce cannot be bumped, which it answers with a `Return` and no address. revm checks +/// both before it moves or writes anything, so a start it refuses makes no write record and +/// journals no transfer log: it is charged nothing and counted nothing. +/// +/// A creation onto an occupied address is the one refusal not predicted. revm decides it on the +/// created address's account after the start is counted, and reading that account here would load +/// it, changing what the transaction has warmed. So the creation's records and transfer log are +/// counted, and a crossing they cause stops the creation before revm could refuse it; without a +/// crossing, revm's refusal fails the creation and its lane goes with it. +pub(crate) fn caller_refuses_start( ctx: &MegaContext, - address: Address, -) -> u64 { - ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) + input: &FrameInput, +) -> bool { + match input { + FrameInput::Call(inputs) => { + inputs.transfers_value() && + caller_refuses(ctx, inputs.caller, inputs.call_value(), false) + } + FrameInput::Create(inputs) => caller_refuses(ctx, inputs.caller(), inputs.value(), true), + FrameInput::Empty => false, + } +} + +/// [`caller_refuses_start`] for the frame `input` asks for, as the opcode starting it — or, for the +/// transaction's own frame, the charge of its record before execution — already found it: nothing +/// between the two changes the caller's account, so a second lookup of it would give the same +/// answer. A debug build makes the lookup and asserts that it does. +/// +/// A start that moves no value and creates nothing is never refused there, and takes nothing. +#[inline] +fn start_refused( + ctx: &mut MegaContext, + input: &FrameInput, +) -> bool { + let refusable = match input { + FrameInput::Call(inputs) => inputs.transfers_value(), + FrameInput::Create(_) => true, + FrameInput::Empty => false, + }; + if !refusable { + return false; + } + let Some(refused) = ctx.additional_limit.take_start_refused() else { + return caller_refuses_start(ctx, input); + }; + debug_assert_eq!( + refused, + caller_refuses_start(ctx, input), + "the answer staged for a frame's start is the one its caller's account gives" + ); + refused +} + +/// Whether `caller`'s account refuses a frame start that moves `value` and, for a `creation`, +/// bumps its nonce: the balance revm's transfer checks, and the nonce revm's creation bumps. +/// +/// The account is read from the journal as it stands, without loading or warming anything, and it +/// is always there. A transaction's sender is loaded by validation, which also credits a deposit's +/// mint (`validate_against_state_and_deduct_caller`, revm's and op-revm's). Any other caller is the +/// account a running frame runs as, which revm loaded to start that frame: a call's target before +/// its value moves, a creation's address when it creates the account. +fn caller_refuses( + ctx: &MegaContext, + caller: Address, + value: U256, + creation: bool, +) -> bool { + let account = ctx.journal_ref().state.get(&caller); + debug_assert!(account.is_some(), "a frame's caller is loaded before the frame starts"); + account.is_some_and(|account| { + account.info.balance < value || (creation && account.info.nonce == u64::MAX) + }) } /// Records the account writes of the EIP-7702 authorities applied since journal entry -/// `journal_i`: each applied authorization bumps its authority's nonce once, so the distinct -/// authorities other than the sender are the accounts written. The sender's write is part of the -/// transaction body. +/// `journal_i`, and answers how many there are: each applied authorization bumps its authority's +/// nonce once, so the distinct authorities other than the sender are the accounts written. The +/// sender's write is part of the transaction body. fn record_applied_authorities( ctx: &mut MegaContext, journal_i: usize, -) -> LimitCheck { +) -> u64 { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return LimitCheck::WithinLimit; + return 0; } let caller = ctx.tx().caller(); let target = ctx.tx().kind().to().copied(); @@ -665,9 +1316,398 @@ fn record_applied_authorities( authorities.dedup(); let target_is_authority = target.is_some_and(|target| authorities.binary_search(&target).is_ok()); - ctx.additional_limit.record_applied_authorities( - caller, - authorities.len() as u64, - target_is_authority, - ) + let applied = authorities.len() as u64; + ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); + // An applied authority that is the block beneficiary wrote the beneficiary's account. + if authorities.binary_search(&ctx.block().beneficiary).is_ok() { + ctx.detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + } + applied +} + +/// Charges the history of the write records a transaction makes outside any frame: one per +/// applied authority, and the one its own frame makes — the recipient of its value, or the +/// account it creates. +/// +/// The authorities' records are the transaction's own and outlive a first frame that fails; the +/// first frame's record does not, so what it cost is kept for the settlement to give back, and +/// whether it makes one is left for that frame's lane to check its own count against. A first +/// frame revm refuses to start on its sender's account makes no record, and is charged none +/// ([`caller_refuses_start`]): among the transactions that pay history, that is a creation from an +/// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can +/// run, and which revm answers with a success. The answer is left for the first frame's init, +/// which asks the same of the same account. +/// `false` when the transaction cannot pay, which is an out-of-gas before it runs. +fn charge_records_made_outside_a_frame( + ctx: &mut MegaContext, + gas: &mut GasTracker, + applied_authorities: u64, +) -> bool { + if !ctx.prices_history() { + return true; + } + let tx = ctx.tx(); + let writes_a_record = match tx.kind() { + TxKind::Create => true, + TxKind::Call(to) => { + !tx.value().is_zero() && + to != tx.caller() && + !ctx.additional_limit.target_is_authority() + } + }; + let (caller, value, creation) = (tx.caller(), tx.value(), tx.kind().is_create()); + let top_level_record = writes_a_record && { + let refused = caller_refuses(ctx, caller, value, creation); + ctx.additional_limit.stage_start_refused(refused); + !refused + }; + let charged = + charge_write_records_history(gas, u64::from(top_level_record), applied_authorities); + let Some((top_level, _)) = charged else { return false }; + ctx.additional_limit.set_top_level_write_record_gas(top_level); + ctx.additional_limit.stage_top_level_records(u64::from(top_level_record)); + true +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{test_utils::MemoryDatabase, MegaSpecId}; + use alloy_primitives::{address, U256}; + use revm::interpreter::{ + gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory, + }; + #[cfg(debug_assertions)] + use revm::interpreter::{CreateInputs, CreateScheme}; + use std::boxed::Box; + + const CALLER: Address = address!("00000000000000000000000000000000000e0001"); + const TARGET: Address = address!("00000000000000000000000000000000000e0002"); + + /// A `CALL` of one wei to `TARGET`, which its opcode charged a new account for. + fn value_call() -> FrameInput { + FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: 100_000, + reservoir: 0, + bytecode_address: TARGET, + known_bytecode: Default::default(), + target_address: TARGET, + caller: CALLER, + value: CallValue::Transfer(U256::from(1)), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: true, + })) + } + + /// A `CREATE` its opcode charged the created account for. + #[cfg(debug_assertions)] + fn creation() -> FrameInput { + let mut inputs = + CreateInputs::new(CALLER, CreateScheme::Create, U256::ZERO, Bytes::new(), 100_000, 0); + inputs.set_charged_create_state_gas(true); + inputs.set_charged_state_gas_address(TARGET); + FrameInput::Create(Box::new(inputs)) + } + + /// A context whose transaction read the block environment before its first frame under a cap + /// of `cap`, so a frame at depth 0 starts with an allowance of `cap`. + fn detained(cap: u64) -> MegaContext { + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + ctx.detention.reset(true, cap, cap); + ctx.detention.mark_before_execution(VolatileDataAccess::TIMESTAMP); + ctx + } + + /// A `STATICCALL` at depth 0 to `to` with `input`, forwarded `forward`. + fn static_call(to: Address, input: &[u8], forward: u64) -> FrameInit { + FrameInit { + depth: 0, + memory: SharedMemory::new(), + frame_input: FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(Bytes::copy_from_slice(input)), + return_memory_offset: 0..0, + gas_limit: forward, + reservoir: 0, + bytecode_address: to, + known_bytecode: Default::default(), + target_address: to, + caller: CALLER, + value: CallValue::Apparent(U256::ZERO), + scheme: CallScheme::StaticCall, + is_static: true, + charged_new_account_state_gas: false, + })), + } + } + + /// What `hold_precompile` decides for a call to `to`, forwarded `forward`, under an allowance + /// of `cap`, with `priced`; and the gas limit the call is left to run on. + fn hold( + cap: u64, + priced: &PricedPrecompiles, + dispatched: &PrecompilesMap, + to: Address, + forward: u64, + refused: bool, + ) -> (PrecompileHold, u64) { + hold_input(cap, priced, dispatched, to, &[0; 32], forward, refused) + } + + /// [`hold`] for a call of `input`. + fn hold_input( + cap: u64, + priced: &PricedPrecompiles, + dispatched: &PrecompilesMap, + to: Address, + input: &[u8], + forward: u64, + refused: bool, + ) -> (PrecompileHold, u64) { + let ctx = detained(cap); + let mut frame_init = static_call(to, input, forward); + let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init, refused); + (held, input_gas_limit(&frame_init.frame_input)) + } + + /// A precompile the engine prices is decided from its price before it runs: within the + /// allowance, and past its whole forward, it runs on the forward as without the limit; past + /// the allowance and within the forward, it is answered without running, out of gas and + /// marked as a crossing whose record is the forward. A call revm refuses on its caller's + /// account runs as without the limit. + #[test] + fn test_a_priced_precompile_is_decided_from_its_price() { + const KZG: Address = crate::kzg_point_evaluation::ADDRESS; + const PRICE: u64 = crate::kzg_point_evaluation::GAS_COST; + let (priced, map) = (PricedPrecompiles::default(), crate::satin_precompiles_map()); + + // Within the allowance: runs on the forward. + let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE, false); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + + // Past the allowance, within the forward: the crossing, without running. + for forward in [PRICE, 3 * PRICE] { + let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, forward, false); + assert_eq!((held, ran_on), (PrecompileHold::Crossing, forward), "the input as it was"); + } + + // Past the whole forward: a plain out-of-gas, run on the forward. + let (held, ran_on) = hold(PRICE / 2, &priced, &map, KZG, PRICE - 1, false); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, PRICE - 1)); + + // Refused on the caller's account: revm answers it without running the precompile. + let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, 3 * PRICE, true); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + + // A forward within the allowance, and a call to anything but a precompile, run as they are. + let (held, ran_on) = hold(3 * PRICE, &priced, &map, KZG, 3 * PRICE, false); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE, false); + assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + } + + /// op-revm's size-limited precompiles in the Satin set — the BN254 pairing and the BLS12-381 + /// G1 MSM, G2 MSM and pairing — are decided from their prices as the KZG entry is. Called + /// with two pairs of zeros, which their EIPs price, the call runs on its forward within the + /// allowance and past its forward, and is the crossing between the two. An input past the size + /// limit is refused before any gas check, so its price is nothing, and it runs on its forward + /// under any allowance, to be refused as without the limit. + #[test] + fn test_a_size_limited_precompile_is_decided_from_its_price() { + use op_revm::precompiles::{bls12_381, bn254_pair}; + let (priced, map) = (PricedPrecompiles::default(), crate::satin_precompiles_map()); + // (the precompile, the length of a pair, the size limit, the price of two pairs) + let wrappers = [ + // EIP-1108: 45,000, and 34,000 a pair. + (bn254_pair::KARST, 192, bn254_pair::KARST_MAX_INPUT_SIZE, 45_000 + 2 * 34_000), + // EIP-2537: 12,000 a pair, two pairs discounted to 949 per mille. + ( + bls12_381::JOVIAN_G1_MSM, + 160, + bls12_381::JOVIAN_G1_MSM_MAX_INPUT_SIZE, + 2 * 12_000 * 949 / 1_000, + ), + // EIP-2537: 22,500 a pair, two pairs undiscounted. + (bls12_381::JOVIAN_G2_MSM, 288, bls12_381::JOVIAN_G2_MSM_MAX_INPUT_SIZE, 2 * 22_500), + // EIP-2537: 37,700, and 32,600 a pair. + ( + bls12_381::JOVIAN_PAIRING, + 384, + bls12_381::JOVIAN_PAIRING_MAX_INPUT_SIZE, + 37_700 + 2 * 32_600, + ), + ]; + for (precompile, pair, limit, price) in wrappers { + let to = *precompile.address(); + let two_pairs = std::vec![0; 2 * pair]; + let hold = |cap, input: &[u8], forward| { + hold_input(cap, &priced, &map, to, input, forward, false) + }; + + // Within the allowance: runs on the forward. + assert_eq!(hold(price, &two_pairs, 3 * price), (PrecompileHold::Unheld, 3 * price)); + + // Past the allowance, within the forward: the crossing, without running. + for forward in [price, 3 * price] { + let held = hold(price - 1, &two_pairs, forward); + assert_eq!(held, (PrecompileHold::Crossing, forward), "{to}: {forward}"); + } + + // Past the whole forward: a plain out-of-gas, run on the forward. + let held = hold(price / 2, &two_pairs, price - 1); + assert_eq!(held, (PrecompileHold::Unheld, price - 1), "{to}"); + + // Past the size limit: priced at nothing, run on the forward. + let over = std::vec![0; limit + pair]; + assert_eq!(hold(1, &over, 3 * price), (PrecompileHold::Unheld, 3 * price), "{to}"); + } + } + + /// The answer to a call whose price crosses the limit is out of gas without running, with its + /// forward untouched and the crossing recorded with the forward. + #[test] + fn test_a_crossing_answer_is_marked_with_its_forward() { + for forward in [1, 100_000, 3_000_000] { + let input = static_call(crate::kzg_point_evaluation::ADDRESS, &[0; 32], forward); + let FrameResult::Call(answer) = crossing_answer(&input.frame_input) else { + panic!("a call's answer") + }; + assert!(!answer.was_precompile_called, "answered without running"); + assert_eq!(answer.result.result, InstructionResult::PrecompileOOG); + assert_eq!(answer.result.gas.limit(), forward); + assert_eq!(answer.result.gas.remaining(), forward, "nothing spent"); + let record = NonZeroU64::new(forward).map(WithheldCrossing::with_remaining); + assert_eq!(answer.result.gas.withheld_crossing(), record); + } + } + + /// A precompile the engine cannot price keeps the clamp: it runs on the allowance, and its + /// answer is owed the rest of the forward. That is a node's own precompile, a Satin address a + /// node replaced, and every precompile of a set that is not the Satin one, op-revm's wrapper of + /// the BN254 pairing included. + #[test] + fn test_an_unpriced_precompile_runs_on_the_allowance() { + const KZG: Address = crate::kzg_point_evaluation::ADDRESS; + let pairing = *op_revm::precompiles::bn254_pair::KARST.address(); + let own = address!("00000000000000000000000000000000000e0003"); + let mut map = crate::satin_precompiles_map(); + map.apply_precompile(&own, |_| { + Some(alloy_evm::precompiles::DynPrecompile::new( + revm::precompile::PrecompileId::Custom("own".into()), + |input| { + Ok(revm::precompile::PrecompileOutput::new(1, Bytes::new(), input.reservoir)) + }, + )) + }); + let mut replaced = PricedPrecompiles::default(); + replaced.record_replaced(KZG); + let mut foreign = PricedPrecompiles::default(); + foreign.record_foreign(); + for (priced, to) in [ + (&PricedPrecompiles::default(), own), + (&replaced, KZG), + (&foreign, KZG), + (&foreign, pairing), + ] { + let (held, ran_on) = hold(1_000, priced, &map, to, 300_000, false); + let clamped = PrecompileHold::Clamped(NonZeroU64::new(299_000).unwrap()); + assert_eq!(held, clamped, "{to}"); + assert_eq!(ran_on, 1_000, "{to}: run on the allowance"); + } + } + + /// A frame answered with a success that the engine then rewrote into the stop, at any depth, + /// has what its start wrote taken back to where its start began. An answer revm made a failure + /// took its writes back itself, and one the engine did not rewrite keeps them. + #[test] + fn test_a_success_answer_rewritten_into_the_stop_is_taken_back() { + for (succeeded, result, taken_back) in [ + (true, InstructionResult::Revert, true), + (true, InstructionResult::Stop, false), + (false, InstructionResult::Revert, false), + ] { + let case = format!("succeeded {succeeded}, now {result:?}"); + let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let start = journal_position(&mut ctx); + // What the answer wrote: a bump of the recipient's nonce. + let _ = ctx.journal_mut().load_account_mut(TARGET).unwrap().data.bump_nonce(); + let answer = synthetic_frame_result(&value_call(), result, Bytes::new()); + take_back_a_stopped_answer(&mut ctx, start, succeeded, &answer); + let nonce = ctx.journal_ref().state.get(&TARGET).map_or(0, |a| a.info.nonce); + assert_eq!(nonce, u64::from(!taken_back), "{case}"); + } + } + + /// The guard trips on a transfer log the data size counted for a frame revm built and did not + /// journal. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "the transfer log counted is the one revm journaled")] + fn test_a_transfer_log_counted_and_not_journaled_trips() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + assert_start_as_counted(&ctx, (true, false, 0), None); + } + + /// The guard trips on a start revm refused on its caller's account that was not predicted, + /// which the data size would have counted. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "the start revm refused is the one predicted")] + fn test_a_refusal_not_predicted_trips() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + let unfunded = + synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); + assert_start_as_counted(&ctx, (true, false, 0), Some(&unfunded)); + } + + /// The guard trips on a start predicted refused that revm made, which the data size did not + /// count. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "the start revm refused is the one predicted")] + fn test_a_predicted_refusal_revm_did_not_make_trips() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + assert_start_as_counted(&ctx, (false, true, 0), None); + } + + /// The guard trips on a start revm answered past the call-stack limit, which the depth guard + /// answers before revm sees it, for a creation and a call alike. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "the depth guard answers every start past the call-stack limit")] + fn test_a_start_revm_answered_past_the_depth_limit_trips() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + for input in [creation(), value_call()] { + let too_deep = + synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); + assert_start_as_counted(&ctx, (false, false, 0), Some(&too_deep)); + } + } + + /// The guard expects no log where nothing moved, whatever the input would count: a start + /// revm refuses on its caller's account, predicted — a value call it answers `OutOfFunds`, a + /// creation whose creator's nonce cannot be bumped, answered with a `Return` — and one it + /// fails otherwise — a creation onto an occupied address, a failing precompile; and none for + /// a frame nothing was counted for. + #[test] + #[cfg(debug_assertions)] + fn test_the_guard_expects_no_transfer_log_where_nothing_moved() { + let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + assert_start_as_counted(&ctx, (false, false, 0), None); + let overflow = synthetic_frame_result(&creation(), InstructionResult::Return, Bytes::new()); + assert_start_as_counted(&ctx, (true, true, 0), Some(&overflow)); + let unfunded = + synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); + assert_start_as_counted(&ctx, (true, true, 0), Some(&unfunded)); + let collision = + synthetic_frame_result(&creation(), InstructionResult::CreateCollision, Bytes::new()); + assert_start_as_counted(&ctx, (true, false, 0), Some(&collision)); + let failed = + synthetic_frame_result(&value_call(), InstructionResult::PrecompileError, Bytes::new()); + assert_start_as_counted(&ctx, (true, false, 0), Some(&failed)); + let answered = synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); + assert_start_as_counted(&ctx, (false, false, 0), Some(&answered)); + } } diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 74106362f..32b7a45d9 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -10,8 +10,8 @@ use revm::{ }; use crate::{ - DynPrecompilesBuilder, EmptyExternalEnv, ExternalEnvFactory, MegaContext, MegaEvm, MegaSpecId, - MegaTransaction, MegaTransactionError, + DynPrecompilesBuilder, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvFactory, MegaContext, + MegaEvm, MegaSpecId, MegaTransaction, MegaTransactionError, ProtocolLimits, }; /// Creates [`MegaEvm`]s for alloy-evm consumers such as a node's block executor. @@ -19,10 +19,22 @@ use crate::{ /// The factory holds the [`ExternalEnvFactory`] that supplies each EVM with the SALT and oracle /// environments of the block it executes, and the optional builder of the dynamic precompiles a /// node adds on top of the Satin set. +/// +/// # The limits an EVM runs under +/// +/// An EVM the factory creates runs under its spec's limits ([`ProtocolLimits::for_spec`]), the +/// ones block execution holds the spec's blocks to, so an RPC call, a simulation or a tool built +/// on the factory stops what the chain stops without having to be told. +/// +/// [`with_tx_runtime_limits`](Self::with_tx_runtime_limits) is the explicit opt-out: every EVM +/// runs under exactly the limits it is given, as the execution-spec gate and tests need. Block +/// execution installs the spec's limits on the EVM whatever it was created with. #[derive(Clone, Default)] pub struct MegaEvmFactory { external_env_factory: ExtEnvFactory, dyn_precompiles_builder: Option, + /// The limits every EVM runs under in place of its spec's, when the caller set them. + tx_runtime_limits: Option, } impl fmt::Debug for MegaEvmFactory { @@ -30,14 +42,20 @@ impl fmt::Debug for MegaEvmFactory { f.debug_struct("MegaEvmFactory") .field("external_env_factory", &self.external_env_factory) .field("dyn_precompiles_builder", &self.dyn_precompiles_builder.is_some()) + .field("tx_runtime_limits", &self.tx_runtime_limits) .finish() } } impl MegaEvmFactory { - /// Creates a factory whose EVMs have no external environments. + /// Creates a factory whose EVMs have no external environments and run under their spec's + /// limits. pub const fn new() -> Self { - Self { external_env_factory: EmptyExternalEnv, dyn_precompiles_builder: None } + Self { + external_env_factory: EmptyExternalEnv, + dyn_precompiles_builder: None, + tx_runtime_limits: None, + } } } @@ -55,6 +73,7 @@ impl MegaEvmFactory { MegaEvmFactory { external_env_factory, dyn_precompiles_builder: self.dyn_precompiles_builder, + tx_runtime_limits: self.tx_runtime_limits, } } @@ -64,6 +83,20 @@ impl MegaEvmFactory { self.dyn_precompiles_builder = Some(builder); self } + + /// Runs every EVM the factory creates under exactly `limits`, in place of its spec's: the + /// explicit opt-out, for the execution-spec gate's equivalence mode + /// ([`EvmTxRuntimeLimits::no_limits`]), for tools and for tests. + pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.tx_runtime_limits = Some(limits); + self + } + + /// The limits an EVM the factory creates for `spec` runs under: the ones given to the factory, + /// or the spec's. + pub fn tx_runtime_limits(&self, spec: MegaSpecId) -> EvmTxRuntimeLimits { + self.tx_runtime_limits.unwrap_or_else(|| ProtocolLimits::for_spec(spec).tx_runtime_limits) + } } impl alloy_evm::EvmFactory for MegaEvmFactory { @@ -78,7 +111,9 @@ impl alloy_evm::EvmFactory for MegaEvmFactory /// The Satin precompile set, with whatever the factory's builder added to it. type Precompiles = PrecompilesMap; - /// Creates an EVM for the block in `evm_env`, with the external environments of that block. + /// Creates an EVM for the block in `evm_env`, with the external environments of that block, + /// running under the limits of the spec the configuration names, or those given to the factory + /// ([`tx_runtime_limits`](MegaEvmFactory::tx_runtime_limits)). /// /// The configuration fields the spec fixes are set from the spec (see /// [`MegaContext::with_cfg`]). @@ -91,9 +126,11 @@ impl alloy_evm::EvmFactory for MegaEvmFactory let external_envs = self.external_env_factory.external_envs(block_env.number.saturating_to()); let spec = cfg_env.spec; + let limits = self.tx_runtime_limits(spec); let ctx = MegaContext::new_with_external_envs(db, spec, external_envs) .with_cfg(cfg_env) - .with_block(block_env); + .with_block(block_env) + .with_tx_runtime_limits(limits); let evm = MegaEvm::new(ctx); match &self.dyn_precompiles_builder { Some(builder) => evm.with_dyn_precompiles(builder(spec)), @@ -131,7 +168,7 @@ mod tests { sync::atomic::{AtomicUsize, Ordering}, }; use revm::{ - context::{CfgEnv, TxEnv}, + context::{CfgEnv, ContextTr, TxEnv}, precompile::{PrecompileId, PrecompileOutput}, primitives::HashMap, }; @@ -146,22 +183,62 @@ mod tests { assert_eq!(got.get_bucket_capacity(7).unwrap(), 1_024); } - /// Whatever configuration the caller passes, the EVM runs with the switches the spec fixes. + /// The configuration [`spec_cfg`](crate::spec_cfg) returns is the one an EVM created from the + /// same env runs with, in both views, before and after it runs a transaction: a node that + /// mirrors it in its `EvmEnv` reads what the EVM executes on. A deposit runs on the schedule + /// that prices no history, and the next transaction that pays history is back on the spec's. #[test] - fn test_create_evm_applies_the_spec_switches() { + fn test_the_exported_cfg_is_the_one_the_evm_runs_with() { let mut cfg_env = CfgEnv::new_with_spec(MegaSpecId::SATIN); cfg_env.chain_id = 4326; + cfg_env.disable_nonce_check = true; cfg_env.tx_gas_limit_cap = Some(1 << 24); cfg_env.enable_amsterdam_eip8037 = false; - let block_env = BlockEnv { number: U256::from(5), ..Default::default() }; + cfg_env.enable_amsterdam_eip2780 = false; + cfg_env.enable_amsterdam_eip7708 = false; + cfg_env.limit_contract_code_size = None; + let exported = crate::spec_cfg(cfg_env.clone()); + assert_eq!(crate::spec_cfg(exported.clone()), exported, "applying it twice is a no-op"); + assert_eq!(exported.chain_id, 4326, "the caller's own fields are kept"); + assert!(exported.disable_nonce_check); + let op_view = exported.clone().with_spec_and_gas_params( + MegaSpecId::SATIN.into_op_spec(), + exported.gas_params.clone(), + ); - let evm = MegaEvmFactory::new() - .create_evm(MemoryDatabase::default(), EvmEnv { cfg_env, block_env }); + let mut evm = MegaEvmFactory::new().create_evm( + MemoryDatabase::default(), + EvmEnv { cfg_env, block_env: evm_env().block_env }, + ); + let runs_with = |evm: &MegaEvm| { + (evm.ctx().mega_cfg().clone(), evm.ctx().cfg().clone()) + }; + assert_eq!(runs_with(&evm), (exported.clone(), op_view.clone())); + let on_chain = |mut tx: MegaTransaction| { + tx.0.base.chain_id = Some(4326); + tx + }; + + evm.transact_raw(on_chain(call(CUSTOM))).unwrap(); + assert_eq!(runs_with(&evm), (exported.clone(), op_view.clone())); + + let mut deposit = on_chain(call(CUSTOM)); + deposit.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); + evm.transact_raw(deposit).unwrap(); + let (mega, _) = runs_with(&evm); + assert_eq!( + mega.gas_params, + crate::satin_gas_params_history_exempt(), + "a deposit runs the schedule that prices no history", + ); + assert_eq!( + mega.with_spec_and_gas_params(exported.spec, exported.gas_params.clone()), + exported, + "and nothing else of the configuration moves", + ); - assert_eq!(evm.chain_id(), 4326); - assert_eq!(evm.cfg_env().tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); - assert!(evm.cfg_env().enable_amsterdam_eip8037); - assert_eq!(evm.block().number, U256::from(5)); + evm.transact_raw(on_chain(call(CUSTOM))).unwrap(); + assert_eq!(runs_with(&evm), (exported, op_view)); } /// Records the block number each EVM's external environments are created for. @@ -196,32 +273,111 @@ mod tests { /// A call from `CALLER` to `to`. fn call(to: Address) -> MegaTransaction { + call_with_gas_limit(to, 1_000_000) + } + + /// A call from `CALLER` to `to` on `gas_limit`. + fn call_with_gas_limit(to: Address, gas_limit: u64) -> MegaTransaction { OpTx(op_transaction(TxEnv { caller: CALLER, kind: TxKind::Call(to), - gas_limit: 1_000_000, + gas_limit, ..Default::default() })) } - /// The factory prints its external environment factory and whether a precompile builder is - /// installed. A closure has no `Debug`, so the builder is reported as a flag rather than - /// dropped: a reader of a node's log can tell the two configurations apart. + /// The factory prints its external environment factory, whether a precompile builder is + /// installed and the limits given to it, if any. A closure has no `Debug`, so the builder is + /// reported by whether it is there rather than dropped: a reader of a node's log can tell the + /// configurations apart. #[test] - fn test_debug_reports_whether_a_precompile_builder_is_installed() { + fn test_debug_reports_the_factorys_configuration() { let factory = MegaEvmFactory::new(); assert_eq!( format!("{factory:?}"), "MegaEvmFactory { external_env_factory: EmptyExternalEnv, \ - dyn_precompiles_builder: false }" + dyn_precompiles_builder: false, tx_runtime_limits: None }" ); let with_builder = factory.with_dyn_precompiles_builder(Arc::new(|_| HashMap::default())); assert_eq!( format!("{with_builder:?}"), "MegaEvmFactory { external_env_factory: EmptyExternalEnv, \ - dyn_precompiles_builder: true }" + dyn_precompiles_builder: true, tx_runtime_limits: None }" + ); + + let fixed = with_builder.with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + assert!(format!("{fixed:?}").contains("tx_runtime_limits: Some(EvmTxRuntimeLimits {")); + } + + /// The factory's EVMs run under their spec's limits, the data-size limit included, as block + /// execution holds the spec's blocks: no schedule or caller has to hand them over. + #[test] + fn test_an_evm_runs_under_its_specs_limits() { + let factory = MegaEvmFactory::new(); + let evm = factory.create_evm(MemoryDatabase::default(), evm_env()); + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + assert_eq!(*evm.tx_runtime_limits(), satin); + assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, 13_107_200); + assert_eq!(factory.tx_runtime_limits(MegaSpecId::SATIN), satin); + } + + /// The opt-out: limits given to the factory are what every EVM runs under, in place of its + /// spec's. + #[test] + fn test_limits_given_to_the_factory_replace_the_specs() { + let factory = MegaEvmFactory::new().with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let evm = factory.create_evm(MemoryDatabase::default(), evm_env()); + assert_eq!(*evm.tx_runtime_limits(), EvmTxRuntimeLimits::no_limits()); + assert_eq!(factory.tx_runtime_limits(MegaSpecId::SATIN), EvmTxRuntimeLimits::no_limits()); + } + + /// And the EVM enforces them, as block execution does: a call that keeps two writes where the + /// limits given to the factory allow one is stopped, and keeps both on an EVM under the spec's. + #[test] + fn test_an_evm_from_the_factory_enforces_its_limits() { + use crate::{test_utils::BytecodeBuilder, LimitCheck, LimitKind}; + use revm::context_interface::cfg::GasId; + const WRITER: Address = address!("0x0000000000000000000000000000000000077700"); + // Below the execution cap the two fresh slots' state gas spills onto regular gas, and the + // body and the two write records pay history: 1,000,000 of regular room on top of what + // they cost at the byte prices in effect, so the second write is made and its record + // counted whatever a byte costs. + let gas_limit = 1_000_000 + + 2 * crate::satin_gas_params().get(GasId::sstore_set_state_gas()) + + crate::history_gas(crate::TX_BODY_SIZE + 2 * crate::WRITE_RECORD_SIZE).unwrap(); + let run = |factory: &MegaEvmFactory| { + let mut db = MemoryDatabase::default(); + db.set_account_code( + WRITER, + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(), + ); + let mut evm = factory.create_evm(db, evm_env()); + evm.execute_transaction(call_with_gas_limit(WRITER, gas_limit)) + .expect("the call is valid") + }; + + let one_record = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .tx_runtime_limits + .with_tx_data_size_limit(crate::TX_BODY_SIZE + 40); + let stopped = run(&MegaEvmFactory::new().with_tx_runtime_limits(one_record)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: crate::TX_BODY_SIZE + 40, + used: crate::TX_BODY_SIZE + 2 * 40, + frame_local: false, + }) ); + + let kept = run(&MegaEvmFactory::new()); + assert_eq!(kept.limit_exceeded, None); + assert!(kept.result.is_success()); } /// The builder runs once per EVM, is handed the spec the EVM executes, and what it returns @@ -292,6 +448,7 @@ mod tests { ); assert_eq!(factory.external_env_factory().0.get(), Some(1_234)); + assert_eq!(evm.block().number, U256::from(1_234), "the EVM runs the block it was given"); assert!(evm.is_inspecting()); } } diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index 09d08538d..f26b53696 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -1,9 +1,9 @@ //! Frame results built without running a frame, and how they settle. //! -//! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, and, -//! when they land, the system contract interceptors, precompile normalisation and native keyless -//! deployment. Such a result goes back to the caller like any frame's, and the caller settles it -//! the way revm settles a frame it ran: +//! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, the +//! system contract interceptors, a `keylessDeploy` call carrying value, and a precompile call gas +//! detention answers from its price without running it. Such a result goes back to the caller like +//! any frame's, and the caller settles it the way revm settles a frame it ran: //! //! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) //! is priced for refund when the frame failed; @@ -15,8 +15,8 @@ //! the reservoir the frame inherited ([`untouched_call_gas`], [`with_pools_of`]), never //! `Gas::new(limit)`, which would carry none and bill the sender for the whole reservoir; and it //! carries the calling opcode's upfront-charge flags, so step 1 refunds the charge. -//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is the settlement, for a -//! mechanism that settles a result into a running frame itself. +//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is that settlement, for a caller +//! that settles a result into its own gas outside revm's frame return. use alloy_primitives::Bytes; use revm::{ diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs new file mode 100644 index 000000000..fbf3be94a --- /dev/null +++ b/crates/mega-evm/src/evm/history.rs @@ -0,0 +1,365 @@ +//! What a byte of history costs, and how many bytes each site appends. +//! +//! History gas is the third ledger of a Satin transaction. It pays for the bytes the transaction +//! appends to the chain's history — its own body, its logs, the code it deploys and one record per +//! account or storage write it keeps — as opposed to the bytes it adds to the world state, which +//! EIP-8037 state gas pays for. Both draw on the same reservoir-first budget and unwind on the same +//! paths; they are counted apart so a node can report and limit them separately. +//! +//! Every charge is a byte count from the byte table (the `limit` module) times the cost per history +//! byte, and the byte counts are the ones the data-size limit meters, so a log costs history for +//! exactly the bytes that limit counts it at. Nothing here reads a SALT bucket: history bytes live +//! in no bucket, and the multiplier that scales the state dimension never touches this one. +//! +//! The one history charge that is not made here is the deployed code's: it is a schedule entry +//! ([`code_deposit_history_gas`](revm::context_interface::cfg::GasId::code_deposit_history_gas)), +//! so revm charges it where it writes the code. The schedule gives that entry the cost of one byte +//! (see the `schedule` module), which is what switches it on. + +use revm::{ + context::{transaction::AccessListItemTr, Transaction}, + context_interface::cfg::gas::GasTracker, +}; + +use crate::{ + evm::prices::active_satin_prices, + limit::{ + ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, LOG_BASE_SIZE, + LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + }, +}; + +/// The gas `bytes` bytes of history cost, or `None` when the price does not fit in a `u64`. +/// +/// A byte count that has no price is not a charge anyone can pay: the caller turns it into an +/// out-of-gas, which is what a count that large would be anyway. +#[inline] +pub fn history_gas(bytes: u64) -> Option { + active_satin_prices().cphb.gas_for(bytes) +} + +/// The gas `records` account or storage write records cost as history. +#[inline] +pub fn write_record_history_gas(records: u64) -> Option { + history_gas(WRITE_RECORD_SIZE.checked_mul(records)?) +} + +/// Charges `gas` the history of two sets of write records, `first` and `second`, in one charge, +/// and answers what each set cost. `None` when a set has no price or `gas` cannot pay the two +/// together, which is an out-of-gas; nothing is charged then. +#[inline] +pub(crate) fn charge_write_records_history( + gas: &mut GasTracker, + first: u64, + second: u64, +) -> Option<(u64, u64)> { + let first = write_record_history_gas(first)?; + let second = write_record_history_gas(second)?; + let cost = first.checked_add(second)?; + gas.record_history_cost(cost).then_some((first, second)) +} + +/// The history bytes the allowance of a value-transferring call covers: one three-topic event +/// carrying a single word, which is what a `receive()` hook emits. +pub const STORAGE_CALL_STIPEND_BYTES: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; + +/// The history allowance a value-transferring `CALL` or `CALLCODE` grants the frame it starts. +/// +/// EVM's own `CALL_STIPEND` buys the recipient of a transfer enough computation to notice it; on +/// a chain that prices the bytes a log appends it buys no log at all, so a `receive()` hook that +/// emits an event would be unreachable through `transfer()`. The allowance is that stipend's +/// counterpart on the history ledger: [`STORAGE_CALL_STIPEND_BYTES`] at the cost per history +/// byte, enough for one event and nothing else. +/// +/// It is separate from the frame's gas in every sense. It never enters the frame's `Gas`, so no +/// settlement can hand it back as gas; it pays history charges and only those, so it cannot buy +/// computation or a write record; and what it pays for appears on no ledger, because no pool of +/// the transaction's gas paid it. +pub fn storage_call_stipend() -> u64 { + history_gas(STORAGE_CALL_STIPEND_BYTES).unwrap_or(u64::MAX) +} + +/// The data-size bytes of `tx`'s body: the fixed body, the calldata, one record per EIP-7702 +/// authorization and the access list. The same count history gas prices. +/// +/// A zero calldata byte counts the same as a non-zero one. The count saturates. +pub fn transaction_body_bytes(tx: &impl Transaction) -> u64 { + let (addresses, slots) = tx + .access_list() + .map(|items| { + items.fold((0_u64, 0_u64), |(addresses, slots), item| { + (addresses + 1, slots + item.storage_slots().count() as u64) + }) + }) + .unwrap_or_default(); + tx_body_history_bytes( + tx.input().len() as u64, + tx.authorization_list_len() as u64, + addresses, + slots, + ) +} + +/// The history bytes a transaction's body appends before it runs: the fixed body +/// ([`TX_BODY_SIZE`]), the calldata, one record per EIP-7702 authorization, and the access list at +/// the size of its addresses and keys. +/// +/// A zero calldata byte costs the same as a non-zero one: both occupy the same space in a block. +/// The count saturates, and a saturated count has no price, so a transaction that would reach it +/// is rejected for not covering its own intrinsic gas. +#[inline] +pub const fn tx_body_history_bytes( + calldata_len: u64, + authorizations: u64, + access_list_addresses: u64, + access_list_slots: u64, +) -> u64 { + TX_BODY_SIZE + .saturating_add(calldata_len) + .saturating_add(AUTHORIZATION_SIZE.saturating_mul(authorizations)) + .saturating_add(ACCESS_LIST_ADDRESS_SIZE.saturating_mul(access_list_addresses)) + .saturating_add(ACCESS_LIST_SLOT_SIZE.saturating_mul(access_list_slots)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + constants::COST_PER_HISTORY_BYTE, evm::prices::runs_at_measurement_prices, + log_history_bytes, + }; + + /// The byte counts of the three sites that count bytes rather than records. + #[test] + fn test_the_byte_counts_follow_the_byte_table() { + assert_eq!(log_history_bytes(0, 0), LOG_BASE_SIZE); + assert_eq!(log_history_bytes(3, 32), LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32); + assert_eq!(log_history_bytes(3, 32), 160); + assert_eq!(log_history_bytes(1, u64::MAX), u64::MAX, "the count saturates"); + + assert_eq!(tx_body_history_bytes(0, 0, 0, 0), TX_BODY_SIZE); + assert_eq!(tx_body_history_bytes(0, 0, 0, 0), 310); + assert_eq!( + tx_body_history_bytes(100, 2, 3, 4), + TX_BODY_SIZE + 100 + 2 * AUTHORIZATION_SIZE + 3 * 20 + 4 * 32 + ); + assert_eq!(tx_body_history_bytes(u64::MAX, 1, 0, 0), u64::MAX, "the count saturates"); + } + + /// The allowance is one three-topic event carrying one word, at the price of a history byte. + #[test] + fn test_the_allowance_is_one_three_topic_event() { + if runs_at_measurement_prices() { + return; + } + assert_eq!(STORAGE_CALL_STIPEND_BYTES, log_history_bytes(3, 32)); + assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); + assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(storage_call_stipend(), history_gas(log_history_bytes(3, 32)).unwrap()); + } + + /// Every way a transaction moves value, as a name, a database, the transaction at a gas limit + /// and the transfer logs it keeps. + #[allow(clippy::type_complexity)] + fn value_movements() -> Vec<( + &'static str, + crate::test_utils::MemoryDatabase, + fn(u64) -> crate::MegaTransaction, + u64, + )> { + use crate::test_utils::{BytecodeBuilder, MemoryDatabase}; + use alloy_primitives::{address, Address, Bytes, TxKind, U256}; + use revm::bytecode::opcode::{ + CALL, CREATE, CREATE2, GAS, LOG3, POP, PUSH0, PUSH1, REVERT, SELFDESTRUCT, STOP, + }; + + const CALLER: Address = address!("00000000000000000000000000000000000c0001"); + const ACTOR: Address = address!("00000000000000000000000000000000000c0002"); + const RECEIVER: Address = address!("00000000000000000000000000000000000c0003"); + const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); + + fn tx(to: TxKind, value: u64, gas_limit: u64) -> crate::MegaTransaction { + alloy_op_evm::OpTx(crate::test_utils::op_transaction(revm::context::TxEnv { + caller: CALLER, + kind: to, + value: U256::from(value), + gas_limit, + ..Default::default() + })) + } + let calling = |target: Address, gas: Option| { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1) + .push_address(target); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code.append(CALL).append(POP) + }; + let funded = || { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(1_000)) + }; + let actor = |code: BytecodeBuilder| funded().account_code(ACTOR, code.stop().build()); + let event = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0]) + .push_number(32_u8) + .append(PUSH0) + .append(LOG3) + .stop() + .build(); + let endowing = |opcode| { + let code = BytecodeBuilder::default(); + let code = if opcode == CREATE2 { code.append(PUSH0) } else { code }; + code.append_many([PUSH0, PUSH0, PUSH1, 1, opcode, POP]) + }; + vec![ + ("the transaction's value", funded(), |gas| tx(TxKind::Call(RECEIVER), 5, gas), 1), + ("a creation transaction's endowment", funded(), |gas| tx(TxKind::Create, 5, gas), 1), + ( + "a value CALL revm builds a frame for", + actor(calling(RECEIVER, None)).account_code(RECEIVER, Bytes::from_static(&[STOP])), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 1, + ), + ( + "a value CALL revm answers, to an account with no code", + actor(calling(RECEIVER, None)), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 1, + ), + ( + "a value CALL to a precompile", + actor(calling(IDENTITY, None)), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 1, + ), + ( + "a CREATE's and a CREATE2's endowments", + actor(BytecodeBuilder::default().append_many( + endowing(CREATE).append_many(endowing(CREATE2).build_vec()).build_vec(), + )), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 2, + ), + ( + "a SELFDESTRUCT's balance", + funded().account_code( + ACTOR, + BytecodeBuilder::default().push_address(RECEIVER).append(SELFDESTRUCT).build(), + ), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 1, + ), + ( + "a transfer passed on to a hook whose event its allowance pays", + actor(calling(RECEIVER, Some(2_300))).account_code(RECEIVER, event), + |gas| tx(TxKind::Call(ACTOR), 7, gas), + 2, + ), + ( + "a value CALL whose callee reverts", + actor(calling(RECEIVER, None)) + .account_code(RECEIVER, Bytes::from_static(&[PUSH0, PUSH0, REVERT])), + |gas| tx(TxKind::Call(ACTOR), 0, gas), + 0, + ), + ] + } + + /// A transfer log costs nothing: every way a transaction moves value spends the same gas on + /// every ledger with EIP-7708 switched on as with it off, reports the same history bytes and + /// write records, and ends in the same state — below the execution cap and above it. What + /// differs is the log in the receipt, beside the events the contracts emitted, and its 160 + /// bytes of data size, one per movement the transaction keeps. The allowance a value call + /// grants pays for its callee's event either way: the transfer log draws nothing from it. + #[test] + fn test_a_transfer_log_costs_no_gas_on_any_ledger() { + use crate::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{is_transfer_log, zero_fee_l1_block_info}, + MegaContext, MegaEvm, MegaSpecId, TRANSFER_LOG_SIZE, + }; + use revm::context::BlockEnv; + + let block = BlockEnv { gas_limit: 10_000_000_000, ..Default::default() }; + for (name, db, tx, moves) in value_movements() { + for gas_limit in [20_000_000, TX_GAS_LIMIT_CAP + 100_000_000] { + let context = || { + MegaContext::new(db.clone(), MegaSpecId::SATIN) + .with_block(block.clone()) + .with_chain(zero_fee_l1_block_info()) + }; + let run = |ctx| MegaEvm::new(ctx).execute_transaction(tx(gas_limit)).unwrap(); + let on = run(context()); + let off = run(context().without_transfer_logs()); + let case = format!("{name} at {gas_limit}"); + + assert!(on.result.is_success(), "{case}: {:?}", on.result); + assert_eq!(on.gas, off.gas, "{case}: every ledger"); + assert_eq!(on.state, off.state, "{case}: the state"); + assert_eq!(on.usage.write_records, off.usage.write_records, "{case}: the records"); + assert_eq!( + on.usage.data_size, + off.usage.data_size + moves * TRANSFER_LOG_SIZE, + "{case}: the data size", + ); + let (logs, events): (Vec<_>, Vec<_>) = + on.result.logs().iter().cloned().partition(is_transfer_log); + assert_eq!(logs.len() as u64, moves, "{case}: the transfer logs"); + assert_eq!(events, off.result.logs(), "{case}: the events"); + assert!(!off.result.logs().iter().any(is_transfer_log), "{case}: none without"); + } + } + } + + /// A charge is its byte count at the cost per history byte, and a count with no price + /// reports none. + #[test] + fn test_a_charge_is_its_byte_count_at_the_price() { + if runs_at_measurement_prices() { + return; + } + assert_eq!(history_gas(0), Some(0)); + assert_eq!(history_gas(1), Some(COST_PER_HISTORY_BYTE)); + assert_eq!(history_gas(160), Some(160 * COST_PER_HISTORY_BYTE)); + assert_eq!(history_gas(u64::MAX), None, "an overflowing count has no price"); + + assert_eq!(write_record_history_gas(0), Some(0)); + assert_eq!(write_record_history_gas(1), Some(WRITE_RECORD_SIZE * COST_PER_HISTORY_BYTE)); + assert_eq!( + write_record_history_gas(3), + Some(3 * WRITE_RECORD_SIZE * COST_PER_HISTORY_BYTE) + ); + assert_eq!(write_record_history_gas(u64::MAX), None, "the byte count overflows"); + } + + /// Two sets of write records are charged in one charge, each answering its own price; a + /// charge the gas cannot pay, and a set with no price, charge nothing. + #[test] + fn test_two_sets_of_write_records_are_charged_in_one() { + let mut gas = GasTracker::new(u64::MAX, u64::MAX, 0); + assert_eq!(charge_write_records_history(&mut gas, 1, u64::MAX), None, "no price"); + assert_eq!((gas.remaining(), gas.history_gas_spent()), (u64::MAX, 0)); + + let one = write_record_history_gas(1).expect("a record has a price"); + let two = write_record_history_gas(2).expect("two records have a price"); + let mut gas = GasTracker::new(one + two, one + two, 0); + assert_eq!(charge_write_records_history(&mut gas, 1, 2), Some((one, two))); + assert_eq!((gas.remaining(), gas.history_gas_spent()), (0, (one + two) as i64)); + + // A charge of nothing is always paid: there is no charge the gas cannot pay. + if one + two == 0 { + #[cfg(feature = "satin-price-override")] + crate::test_utils::note_price_guard("MEGA_SATIN_CPHB prices a history byte at nothing"); + return; + } + let mut short = GasTracker::new(one + two, one + two - 1, 0); + assert_eq!(charge_write_records_history(&mut short, 1, 2), None); + assert_eq!((short.remaining(), short.history_gas_spent()), (one + two - 1, 0)); + } +} diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index f3259d784..cade09497 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -1,18 +1,42 @@ -//! The Host of the Satin engine, and the journal reads that observe without warming. +//! The Host of the Satin engine. //! //! # The Host only observes //! //! revm hands the Host the facts of every state-writing opcode: an `SSTORE`'s original, present and //! new values, a log's topics and data, a `SELFDESTRUCT`'s balance and beneficiary. The Host //! stages them ([`AdditionalLimit::stage_record`](crate::AdditionalLimit)) and records nothing. -//! The opcode's wrapper commits the staged record after the opcode completed, and discards it when -//! the opcode failed. Recording in the Host would count a write the opcode's own failure then takes +//! The opcode's wrapper commits the staged record after the opcode completed, and charges the +//! frame the history the record costs; it discards the record, and charges nothing, when the +//! opcode failed. Recording in the Host would count a write the opcode's own failure then takes //! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the -//! frame with the record already counted. +//! frame with the record already counted — and would have charged the frame for a byte the chain +//! never carries. //! //! `block_hash` serves the read and records it, so a stateless witness learns of a `BLOCKHASH` //! that bypassed the journal. //! +//! # Volatile reads +//! +//! The Host is where gas detention marks a read of volatile data: the block-environment +//! accessors, the account load when the account is the block beneficiary, the storage load when +//! the storage is the Oracle's, and `SELFDESTRUCT` when either end is the beneficiary. A read is +//! marked once the load succeeded, and the opcode's wrapper commits it once the opcode completed +//! (see the `access` module). Every account opcode reaches the account load: `balance`, +//! `load_account_delegated`, `load_account_code` and `load_account_code_hash` are the trait's own, +//! built on it. +//! +//! While volatile-data access is switched off for the running frame, the Host refuses those loads +//! instead: an account or storage load fails as a skipped cold load, and a block-environment +//! accessor answers zero. Nothing is loaded, and the opcode's wrapper turns the refusal into the +//! frame's revert. +//! +//! # The Oracle's storage +//! +//! A storage load whose owner is the Oracle reads the slot from the node's oracle service +//! ([`OracleEnv`]) and falls back to the database for a slot the service has no value for. Every +//! such read is priced as a cold access, because a node replaying a block cannot tell which of the +//! two sources the node that built it read. +//! //! # One hook prices every state charge //! //! [`state_gas_price`](revm::context_interface::Host::state_gas_price) is the one place an @@ -35,7 +59,6 @@ use alloc as std; use std::format; -use alloy_primitives::map::Entry; use delegate::delegate; use revm::{ context::ContextTr, @@ -43,58 +66,135 @@ use revm::{ cfg::{GasId, GasParams, StateGasSite}, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, host::LoadError, - journaled_state::{AccountInfoLoad, AccountLoad}, + journaled_state::AccountInfoLoad, }, - primitives::{Address, Bytes, Log, StorageKey, StorageValue, B256, KECCAK_EMPTY, U256}, - state::{Account, EvmStorageSlot}, - Database, Journal, + primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, + Database, }; -use crate::{ExternalEnvTypes, MegaContext, StagedRecord}; +use crate::{ + system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, StagedRecord, + VolatileDataAccess, +}; impl revm::context_interface::Host for MegaContext { delegate! { to self.inner { - fn basefee(&self) -> U256; - fn blob_gasprice(&self) -> U256; - fn gas_limit(&self) -> U256; - fn difficulty(&self) -> U256; - fn prevrandao(&self) -> Option; - fn block_number(&self) -> U256; - fn timestamp(&self) -> U256; - fn beneficiary(&self) -> Address; - fn slot_num(&self) -> U256; fn chain_id(&self) -> U256; + // `DIFFICULTY` reads the randomness on every spec since the merge; see `prevrandao`. + fn difficulty(&self) -> U256; fn effective_gas_price(&self) -> U256; fn caller(&self) -> Address; fn blob_hash(&self, number: usize) -> Option; fn max_initcode_size(&self) -> usize; fn gas_params(&self) -> &GasParams; fn is_amsterdam_eip8037_enabled(&self) -> bool; - fn sload_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn sload(&mut self, address: Address, key: StorageKey) -> Option>; fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; - fn load_account_info_skip_cold_load( - &mut self, - address: Address, - load_code: bool, - skip_cold_load: bool, - ) -> Result, LoadError>; - fn balance(&mut self, address: Address) -> Option>; - fn load_account_delegated(&mut self, address: Address) -> Option>; - fn load_account_code(&mut self, address: Address) -> Option>; - fn load_account_code_hash(&mut self, address: Address) -> Option>; } } + #[inline] + fn basefee(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::BASE_FEE) { + return Default::default(); + } + self.inner.basefee() + } + + #[inline] + fn blob_gasprice(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::BLOB_BASE_FEE) { + return Default::default(); + } + self.inner.blob_gasprice() + } + + #[inline] + fn gas_limit(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::GAS_LIMIT) { + return Default::default(); + } + self.inner.gas_limit() + } + + #[inline] + fn prevrandao(&self) -> Option { + if !self.read_block_env(VolatileDataAccess::PREV_RANDAO) { + return Some(U256::ZERO); + } + self.inner.prevrandao() + } + + #[inline] + fn block_number(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::BLOCK_NUMBER) { + return Default::default(); + } + self.inner.block_number() + } + + #[inline] + fn timestamp(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::TIMESTAMP) { + return Default::default(); + } + self.inner.timestamp() + } + + #[inline] + fn beneficiary(&self) -> Address { + if !self.read_block_env(VolatileDataAccess::COINBASE) { + return Default::default(); + } + self.inner.beneficiary() + } + + #[inline] + fn slot_num(&self) -> U256 { + if !self.read_block_env(VolatileDataAccess::SLOT_NUM) { + return Default::default(); + } + self.inner.slot_num() + } + + /// Loads the slot; a slot of the Oracle's storage is read through the oracle environment + /// ([`oracle_sload`](Self::oracle_sload)). + #[inline] + fn sload_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + skip_cold_load: bool, + ) -> Result, LoadError> { + if address == ORACLE_CONTRACT_ADDRESS { + return self.oracle_sload(key, skip_cold_load); + } + self.inner.sload_skip_cold_load(address, key, skip_cold_load) + } + + /// Loads the account, marking a read of the block beneficiary's. + #[inline] + fn load_account_info_skip_cold_load( + &mut self, + address: Address, + load_code: bool, + skip_cold_load: bool, + ) -> Result, LoadError> { + let beneficiary = address == self.inner.block.beneficiary; + if beneficiary && self.detention.refuses(VolatileDataAccess::BENEFICIARY_BALANCE) { + return Err(LoadError::ColdLoadSkipped); + } + let load = + self.inner.load_account_info_skip_cold_load(address, load_code, skip_cold_load)?; + if beneficiary { + self.detention.observe(VolatileDataAccess::BENEFICIARY_BALANCE); + } + Ok(load) + } + /// Prices one EIP-8037 state gas unit, scaling the schedule's entry by the SALT bucket /// capacity of the account — or, for a slot-scoped entry, of the storage slot — the charge /// lands on. @@ -141,6 +241,9 @@ impl revm::context_interface::Host /// journal alone would miss it; the record is where a node learns of the read. #[inline] fn block_hash(&mut self, number: u64) -> Option { + if !self.read_block_env(VolatileDataAccess::BLOCK_HASH) { + return Some(B256::ZERO); + } let hash = self.inner.block_hash(number)?; self.block_hash_record.record(number, hash); Some(hash) @@ -183,7 +286,9 @@ impl revm::context_interface::Host self.inner.log(log); } - /// Destructs the account and stages whether value moved and where to. + /// Destructs the account and stages whether value moved and where to, marking a read of the + /// block beneficiary's account when it is either end: the source's balance is read and + /// cleared, the target's read and credited. #[inline] fn selfdestruct( &mut self, @@ -191,10 +296,17 @@ impl revm::context_interface::Host target: Address, skip_cold_load: bool, ) -> Result, LoadError> { + let beneficiary = self.inner.block.beneficiary; + let volatile = target == beneficiary || address == beneficiary; + if volatile && self.detention.refuses(VolatileDataAccess::BENEFICIARY_BALANCE) { + return Err(LoadError::ColdLoadSkipped); + } let load = self.inner.selfdestruct(address, target, skip_cold_load)?; + if volatile { + self.detention.observe(VolatileDataAccess::BENEFICIARY_BALANCE); + } self.additional_limit.stage_record(StagedRecord::SelfDestruct { had_value: load.data.had_value, - target_exists: load.data.target_exists, to_other_account: target != address, beneficiary: target, }); @@ -202,485 +314,86 @@ impl revm::context_interface::Host } } -/// Journal reads that observe an account or a slot without warming it. -/// -/// A read loads what the journal does not hold yet into it, so the returned state and a -/// stateless witness carry it, and marks it cold, so it neither enters the EIP-2929 access list -/// nor leaves a journal entry. Execution that later touches the same account or slot pays for it -/// as if the read never happened. -pub trait JournalInspectTr { - /// The database error. - type DBError; - - /// The account at `address`, without following an EIP-7702 delegation. - /// - /// With `load_code`, the code of an account the database served without it is loaded. An - /// account the journal already holds always has its code loaded. - fn inspect_account( - &mut self, - address: Address, - load_code: bool, - ) -> Result<&mut Account, Self::DBError>; - - /// The code hash of the account at `address`. Never loads the code, so an occupancy check - /// needs only the account in a witness, not its bytecode. - fn inspect_account_code_hash(&mut self, address: Address) -> Result; - - /// The slot `key` of the account at `address`, which is always the account's own storage (an - /// EIP-7702 delegation does not move it). A slot of an account created in this transaction - /// is zero without a database read. - fn inspect_storage( - &mut self, - address: Address, - key: StorageKey, - ) -> Result<&EvmStorageSlot, Self::DBError>; -} - -impl JournalInspectTr for Journal { - type DBError = DB::Error; - - fn inspect_account( - &mut self, - address: Address, - load_code: bool, - ) -> Result<&mut Account, DB::Error> { - let transaction_id = self.transaction_id; - match self.inner.state.entry(address) { - Entry::Occupied(entry) => { - let account = entry.into_mut(); - if account.info.code_hash != KECCAK_EMPTY && account.info.code.is_none() { - account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); - } - Ok(account) - } - Entry::Vacant(entry) => { - let mut account = self - .database - .basic(address)? - .map(Account::from) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - if load_code && - account.info.code_hash != KECCAK_EMPTY && - account.info.code.is_none() - { - account.info.code = Some(self.database.code_by_hash(account.info.code_hash)?); - } - account.mark_cold(); - Ok(entry.insert(account)) - } - } - } - - fn inspect_account_code_hash(&mut self, address: Address) -> Result { - let transaction_id = self.transaction_id; - match self.inner.state.entry(address) { - Entry::Occupied(entry) => Ok(entry.get().info.code_hash), - Entry::Vacant(entry) => { - let mut account = self - .database - .basic(address)? - .map(Account::from) - .unwrap_or_else(|| Account::new_not_existing(transaction_id)); - account.mark_cold(); - Ok(entry.insert(account).info.code_hash) - } +impl MegaContext { + /// Reads the block-environment field `access` stands for: `false` when the read is refused, + /// and the accessor answers zero instead of the field. + #[inline] + fn read_block_env(&self, access: VolatileDataAccess) -> bool { + if self.detention.refuses(access) { + return false; } + self.detention.observe(access); + true } - fn inspect_storage( + /// Reads the slot `key` of the Oracle's storage, in the Oracle's own frame: a storage load + /// whose owner is the Oracle, so an `SLOAD` of any other contract, and a `DELEGATECALL` into + /// the Oracle's code, which runs on its caller's storage, are ordinary loads. + /// + /// The slot is loaded through the journal as any read of it is, then the oracle environment + /// is asked ([`OracleEnv::get_oracle_storage`]): the frame gets the environment's value when + /// it has one, over whatever the chain or the frame itself stored in the slot, and the loaded + /// value otherwise. Hints reach the environment synchronously as the `sendHint` call is made, + /// so a read that follows a hint in execution finds the environment told, as the trait + /// promises. + /// + /// A node replaying a block cannot tell whether the node that built it answered a read from + /// its oracle service or from the chain, so nothing the transaction pays and nothing its + /// state records may depend on the source. The read is always priced cold, whichever source + /// answered and however often the transaction read the slot before; and the slot is loaded on + /// both paths, so afterwards it is warm for the frame's `SSTORE` whichever source answered, + /// and it is in the transaction's state, which a stateless witness is built from, even when + /// the environment's value was the one used. + /// + /// A system call does not ask the environment, whatever it holds: its read answers the chain's + /// slot, so the call is a function of the state a stateless validator is given (see + /// [`MegaContext::is_system_call`]). + /// + /// A frame whose regular gas, the part detention withholds included, cannot pay the cold + /// access reads nothing and asks nothing, as revm's own skipped cold load does. A detained + /// frame that holds the gas but may not spend it does read and ask, and the charge then stops + /// the transaction at the compute limit. + /// + /// It is a read of volatile data: it is refused while the frame's volatile-data access is off, + /// and marked for gas detention, under the Oracle's cap, once it succeeded. + /// + /// The read and the answer are recorded on the context for the transaction's outcome + /// ([`OracleReadRecord`](crate::OracleReadRecord)): the answer is in no database, so a + /// stateless validator is given the included transactions' reads in place of the service. + fn oracle_sload( &mut self, - address: Address, key: StorageKey, - ) -> Result<&EvmStorageSlot, DB::Error> { - let transaction_id = self.transaction_id; - let is_newly_created = self.inspect_account(address, true)?.is_created(); - let account = self.inner.state.get_mut(&address).expect("inspected above"); - match account.storage.entry(key) { - Entry::Occupied(entry) => Ok(entry.into_mut()), - Entry::Vacant(entry) => { - let value = if is_newly_created { - U256::ZERO - } else { - self.database.storage(address, key)? - }; - let mut slot = EvmStorageSlot::new(value, transaction_id); - slot.mark_cold(); - Ok(entry.insert(slot)) - } + skip_cold_load: bool, + ) -> Result, LoadError> { + if self.detention.refuses(VolatileDataAccess::ORACLE) || skip_cold_load { + return Err(LoadError::ColdLoadSkipped); } + let loaded = revm::context_interface::Host::sload_skip_cold_load( + &mut self.inner, + ORACLE_CONTRACT_ADDRESS, + key, + false, + )? + .data; + // A system call reads the chain: it asks the service nothing and records no answer, and + // the read is priced and loaded as any other. + let answer = if self.is_system_call() { + None + } else { + let answer = self.external_envs().oracle_env.get_oracle_storage(key); + self.oracle_reads.record(key, answer); + answer + }; + self.detention.observe(VolatileDataAccess::ORACLE); + Ok(StateLoad::new(answer.unwrap_or(loaded), true)) } } #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{address, keccak256}; - use core::cell::Cell; - use revm::{ - context::JournalTr, - primitives::HashMap, - state::{AccountInfo, Bytecode}, - }; - - /// Minimal `revm::Database` implementation that mimics the production - /// `reth`-style `StateProviderDatabase` contract: `basic()` returns - /// `AccountInfo { code: None, code_hash: }` for accounts with - /// on-chain bytecode, and the bytecode itself is lazy-loaded on demand via - /// `code_by_hash()`. The workspace's `MemoryDatabase` cannot model this — - /// it eagerly populates `AccountInfo.code` inside `basic()`, so any cache - /// miss against it would always see the code already hydrated. - #[derive(Default)] - struct LazyCodeDatabase { - accounts: HashMap, - codes: HashMap, - storage_calls: Cell, - } - - impl LazyCodeDatabase { - fn with_account_code(mut self, address: Address, bytecode: Bytes) -> Self { - let code = Bytecode::new_raw(bytecode); - let code_hash = code.hash_slow(); - self.accounts - .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); - self.codes.insert(code_hash, code); - self - } - - fn with_eip7702_delegation(mut self, address: Address, delegate: Address) -> Self { - let code = Bytecode::new_eip7702(delegate); - let code_hash = code.hash_slow(); - self.accounts - .insert(address, AccountInfo { code_hash, code: None, ..Default::default() }); - self.codes.insert(code_hash, code); - self - } - - fn storage_calls(&self) -> usize { - self.storage_calls.get() - } - } - - impl revm::Database for LazyCodeDatabase { - type Error = core::convert::Infallible; - - fn basic(&mut self, address: Address) -> Result, Self::Error> { - // Mirror reth's `StateProviderDatabase::basic`: return AccountInfo without - // populating `code`, even when the account has on-chain bytecode. - Ok(self.accounts.get(&address).cloned()) - } - - fn code_by_hash(&mut self, code_hash: B256) -> Result { - Ok(self.codes.get(&code_hash).cloned().unwrap_or_default()) - } - - fn storage(&mut self, _address: Address, _index: U256) -> Result { - self.storage_calls.set(self.storage_calls.get() + 1); - Ok(U256::ZERO) - } - - fn block_hash(&mut self, _number: u64) -> Result { - Ok(B256::ZERO) - } - } - - /// `inspect_account(addr, false)` must not hydrate `info.code` on the vacant - /// branch — callers that need it pass `load_code = true`. - #[test] - fn test_inspect_account_vacant_path_does_not_hydrate_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); // PUSH1 1 PUSH1 1 ADD - let expected_hash = keccak256(&bytecode); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let account = journal.inspect_account(ADDR, false).expect("inspect_account must succeed"); - - assert_eq!( - account.info.code_hash, expected_hash, - "code_hash must propagate from the database's `basic()` result", - ); - assert!( - account.info.code.is_none(), - "`load_code = false` must leave `info.code` as-is on the vacant branch", - ); - } - - /// `inspect_account(addr, true)` hydrates `info.code` from `code_by_hash` on - /// first cold inspection against a lazy-code database. - #[test] - fn test_inspect_account_with_load_code_hydrates_lazy_bytecode_on_first_touch() { - const ADDR: Address = address!("00000000000000000000000000000000000000aa"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode.clone()); - let mut journal = Journal::new(db); - - let account = journal - .inspect_account(ADDR, true) - .expect("inspect_account must succeed on first cold-touch"); - let hydrated = account - .info - .code - .as_ref() - .expect("`load_code = true` must populate `info.code` from code_by_hash"); - assert_eq!( - hydrated.original_bytes().as_ref(), - bytecode.as_ref(), - "hydrated bytecode must match what `code_by_hash` would return", - ); - } - - /// The occupied-branch hydration must keep firing — a second `inspect_account` - /// against the same lazy-DB address must observe hydrated `info.code` even with - /// `load_code = false`. - #[test] - fn test_inspect_account_occupied_branch_hydrates_on_second_inspection() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let first_code_hash = journal - .inspect_account(ADDR, false) - .expect("first inspection must succeed") - .info - .code_hash; - let second = journal.inspect_account(ADDR, false).expect("second inspection must succeed"); - - assert_eq!( - second.info.code_hash, first_code_hash, - "code_hash must be identical across cache miss and cache hit", - ); - assert!( - second.info.code.is_some(), - "second inspection must observe the hydrated code via the occupied-branch \ - `code_by_hash` load", - ); - } - - /// `inspect_account(addr, true)` must short-circuit on EOAs — the `code_hash != - /// KECCAK_EMPTY` guard keeps `code_by_hash` off the hot path. - #[test] - fn test_inspect_account_with_load_code_leaves_eoa_code_empty() { - const EOA: Address = address!("00000000000000000000000000000000000000cc"); - - let mut db = LazyCodeDatabase::default(); - db.accounts.insert( - EOA, - AccountInfo { - balance: U256::from(1_000_000u64), - nonce: 5, - code_hash: KECCAK_EMPTY, - code: None, - ..Default::default() - }, - ); - let mut journal = Journal::new(db); - - let account = journal - .inspect_account(EOA, true) - .expect("inspect_account must succeed and be a no-op on EOAs"); - assert_eq!(account.info.code_hash, KECCAK_EMPTY, "EOA code_hash must remain KECCAK_EMPTY"); - assert!( - account.info.code.is_none(), - "EOA code must stay `None`; the `code_hash != KECCAK_EMPTY` guard keeps \ - `code_by_hash` off the hot path for accounts without on-chain code", - ); - let again = journal.inspect_account(EOA, false).expect("occupied read must succeed"); - assert!(again.info.code.is_none(), "the occupied branch keeps the guard too"); - } - - /// `inspect_account_code_hash` returns the account's `code_hash` but must NEVER hydrate - /// `info.code` — on either branch. In particular the occupied branch must not fall through to - /// `code_by_hash` the way `inspect_account(.., false)` does (see - /// `test_inspect_account_occupied_branch_hydrates_on_second_inspection`). This is what lets an - /// occupancy check decide on the hash alone, without demanding an already-warmed occupied - /// address's bytecode in a stateless witness carrying only its proof. - #[test] - fn test_inspect_account_code_hash_never_hydrates_code() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x5b]); // JUMPDEST - let expected_hash = keccak256(&bytecode); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - // Vacant cache-miss: returns the hash from `basic()` without hydrating code. - let vacant_hash = - journal.inspect_account_code_hash(ADDR).expect("vacant read must succeed"); - assert_eq!(vacant_hash, expected_hash, "vacant branch must return the code_hash"); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "vacant branch must not hydrate info.code", - ); - - // The address is now resident with `code == None`. `inspect_account` would hydrate on this - // occupied branch; `inspect_account_code_hash` must not. - let occupied_hash = - journal.inspect_account_code_hash(ADDR).expect("occupied read must succeed"); - assert_eq!( - occupied_hash, expected_hash, - "occupied branch must return the cached code_hash" - ); - assert!( - journal.inner.state.get(&ADDR).is_some_and(|a| a.info.code.is_none()), - "inspect_account_code_hash must NOT hydrate info.code on the occupied branch", - ); - } - - /// Pins the `LazyCodeDatabase` fixture's contract against the production - /// `revm::Database` shape it is modeling: `basic()` returns - /// `code: None` for known accounts, `None` for unknown addresses; - /// `code_by_hash()` falls back to empty bytecode for an unknown hash; - /// `storage()` and `block_hash()` are inert stubs (no tests exercise them via - /// `inspect_account`, but they must remain wired so the fixture is a complete - /// `revm::Database`). If the fixture ever drifts (e.g. someone "helpfully" - /// makes `basic()` eagerly populate `code` like `MemoryDatabase` does), the - /// inspect-account tests above silently lose their load-bearing property — - /// this test fails fast in that case. - #[test] - fn test_lazy_code_database_fixture_pins_reth_style_contract() { - const KNOWN: Address = address!("00000000000000000000000000000000000000ee"); - let bytecode = Bytes::from_static(&[0x00]); - let mut db = LazyCodeDatabase::default().with_account_code(KNOWN, bytecode); - - let known = db.basic(KNOWN).unwrap().expect("known account must resolve"); - assert!( - known.code.is_none(), - "LazyCodeDatabase::basic must NOT pre-populate code — that is the \ - behavior `inspect_account` is being tested against", - ); - assert!( - db.basic(Address::ZERO).unwrap().is_none(), - "unknown address must return None from basic()", - ); - - let unknown_hash = keccak256([0xffu8]); - assert_eq!( - db.code_by_hash(unknown_hash).unwrap().original_bytes().len(), - 0, - "unknown code_hash must fall back to empty bytecode", - ); - - assert_eq!(db.storage(KNOWN, U256::ZERO).unwrap(), U256::ZERO); - assert_eq!(db.block_hash(0).unwrap(), B256::ZERO); - } - - #[test] - fn test_inspect_storage_slot_hit_returns_existing_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000bb"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(3); - let expected_value = U256::from(42); - { - let tid = journal.transaction_id; - let account = journal.inspect_account(ADDR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected_value, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let slot = journal - .inspect_storage(ADDR, key) - .expect("inspect_storage must succeed on existing slot"); - - assert_eq!( - slot.present_value, expected_value, - "a slot hit must return the pre-seeded value" - ); - assert!(slot.is_cold, "inspected slot must remain cold"); - } - - #[test] - fn test_inspect_storage_slot_miss_inserts_and_returns_db_value() { - const ADDR: Address = address!("00000000000000000000000000000000000000cc"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - let key = U256::from(7); - - let slot = journal - .inspect_storage(ADDR, key) - .expect("inspect_storage must succeed on absent slot"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "absent slot on non-created account must return ZERO from database" - ); - assert!(slot.is_cold, "newly inserted slot must be marked cold"); - - let calls_after_first = journal.database.storage_calls(); - let slot2 = - journal.inspect_storage(ADDR, key).expect("second inspect_storage must succeed"); - - assert_eq!(slot2.present_value, U256::ZERO, "second call must return the same value"); - assert_eq!( - journal.database.storage_calls(), - calls_after_first, - "second inspect_storage on the same slot must hit the cache, not the DB", - ); - } - - #[test] - fn test_inspect_storage_newly_created_short_circuits_db() { - const ADDR: Address = address!("00000000000000000000000000000000000000dd"); - let bytecode = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default().with_account_code(ADDR, bytecode); - let mut journal = Journal::new(db); - - { - let account = journal.inspect_account(ADDR, false).unwrap(); - account.mark_created(); - } - - let key = U256::from(1); - - let slot = journal - .inspect_storage(ADDR, key) - .expect("inspect_storage must succeed on newly-created account"); - - assert_eq!( - slot.present_value, - U256::ZERO, - "newly-created account must return ZERO without querying database" - ); - assert!(slot.is_cold, "slot must be marked cold"); - } - - #[test] - fn test_inspect_storage_ignores_eip7702_delegation() { - const DELEGATOR: Address = address!("0000000000000000000000000000000000000d01"); - const DELEGATE: Address = address!("0000000000000000000000000000000000000d02"); - let delegate_code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x01, 0x01]); - let db = LazyCodeDatabase::default() - .with_eip7702_delegation(DELEGATOR, DELEGATE) - .with_account_code(DELEGATE, delegate_code); - let mut journal = Journal::new(db); - - let key = U256::from(2); - let expected = U256::from(99); - { - let tid = journal.transaction_id; - let account = journal.inspect_account(DELEGATOR, false).unwrap(); - let mut slot = EvmStorageSlot::new(expected, tid); - slot.mark_cold(); - account.storage.insert(key, slot); - } - - let slot = journal - .inspect_storage(DELEGATOR, key) - .expect("inspect_storage must succeed for a delegator"); - - assert_eq!( - slot.present_value, expected, - "storage is read from the delegator (original address), not the delegate" - ); - } + use alloy_primitives::{address, Bytes}; + use revm::context::JournalTr; /// The Host stages what each state-writing call observed and counts nothing: counting is the /// opcode wrapper's, after the opcode completed. @@ -722,7 +435,6 @@ mod tests { ctx.additional_limit.staged_record(), Some(&StagedRecord::SelfDestruct { had_value: true, - target_exists: false, to_other_account: true, beneficiary: BENEFICIARY, }) diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs index eb255511e..88d30da55 100644 --- a/crates/mega-evm/src/evm/inspector.rs +++ b/crates/mega-evm/src/evm/inspector.rs @@ -1,48 +1,123 @@ -//! What an inspector may do to a Satin transaction, and the one thing it may not. +//! What an inspector may do to a Satin transaction, and what its rewrites do not change. //! //! An inspector is not a passive observer. A callback holding a live interpreter can write to its -//! gas and its pending action, a callback holding a frame's inputs can change them, and every -//! `*_end` callback can rewrite a result's classification, gas and output. Satin keeps no ledger -//! beside revm's `Gas` (compute is the regular gas spent), so an inspector that changes the gas -//! changes what the transaction owes, and a rewriting inspector gets exactly what it asked for. -//! Rewriting is a tool feature, supported and unmeasured. +//! gas and its pending action, a callback holding a frame's inputs can change them or answer the +//! frame itself, and every `*_end` callback can rewrite a result's classification, gas and output. +//! Satin keeps no ledger beside revm's `Gas` (compute is the regular gas spent), so an inspector +//! that changes the gas changes what the transaction owes, and a rewriting inspector gets what it +//! asked for, within the bounds below. Rewriting is a tool feature — Foundry's cheatcodes are built +//! on it — supported and unmeasured. //! -//! Two things bound it: +//! # Where an inspector runs //! -//! - **The admission gate.** [`TrustedObserver`] is a declaration, made in source about one -//! inspector type, that none of its callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) -//! built with [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the -//! declaration, and [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what -//! block execution refuses a transaction on: a rewriting inspector has no route to a block. -//! [`DeclaredObserver`] carries the declaration for a tracer whose type cannot, and in debug -//! builds checks it around every callback. -//! - **The refusal.** A failed contract creation rewritten into a successful one is refused: the -//! transaction fails with [`FORBIDDEN_CREATE_REVIVAL`] as an `EVMError::Custom`. By the time -//! `create_end` runs, revm has reverted the frame and deposited no code, so the rewrite would -//! push an address for code that does not exist and merge the frame's state gas for state that -//! was rolled back. Every other rewrite is the tool's business. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::{format, string::String}; +//! - **A user transaction** runs every callback: `initialize_interp`, `step` and `step_end`, +//! `log_full`, `log` for what a frame journals without running an instruction (an EIP-7708 +//! transfer log, a precompile's logs), `frame_start` and `frame_end`, `call` and `call_end`, +//! `create` and `create_end`, and `selfdestruct`. A keyless deployment is seen as the frames it +//! is made of: its `keylessDeploy` call, which runs no instruction and so gets no +//! `initialize_interp` and no step, and the creation below it. The inspector may rewrite anything +//! outside block execution, within the bounds below. +//! - **A system transaction** — a system-address transaction, promoted to a deposit before its +//! first callback — runs through the same handler and the same callbacks, and may be rewritten +//! the same way. It is the protocol's own work, held to no per-transaction limit, so no limit +//! stops any of its frames. +//! - **A pre-block system call** — the EIP-2935 and EIP-4788 calls, and the `SequencerRegistry`'s +//! `applyPendingChanges()` — runs on the handler's plain system-call path, as alloy-evm's +//! `transact_system_call` runs one: no callback, whatever inspector the EVM holds, so a block's +//! tracer sees the block's transactions and nothing of its preparation. A tool that wants to +//! watch a system call runs it through revm's `InspectSystemCallEvm`, which does hand it to the +//! inspector, with every exemption a system call has. +//! - **The end of a block** runs no code: the post-block balance increments are database writes. No +//! callback runs, and the EVM handed back carries the inspector with what it collected. +//! +//! # The admission gate +//! +//! [`TrustedObserver`] is a declaration, made in source about one inspector type, that none of its +//! callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) built with +//! [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the declaration, and +//! [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what block execution +//! refuses on: a rewriting inspector has no route to a block. [`DeclaredObserver`] carries the +//! declaration for a tracer whose type cannot, and in debug builds checks it around every callback. +//! +//! Block execution checks the gate before anything changes wherever an outcome is produced or +//! chosen: the pre-block changes, the execution of a transaction — a system transaction as a user +//! one — the end of the block, and +//! [`commit_transaction_outcome`](crate::MegaBlockExecutor::commit_transaction_outcome), the commit +//! of an outcome a builder chose among candidates. alloy-evm's `commit_transaction` checks nothing +//! and needs no check: it cannot fail, runs no code, and commits the outcome the last execution +//! produced, which passed the gate before it ran and which no inspector enabled since can reach. +//! So a declared observer sees the block's transactions, user and system alike, and a rewriting +//! inspector sees nothing of a block: it is refused before the pre-block calls, which it would not +//! run on anyway, and before any transaction. +//! +//! # What a rewrite does not change +//! +//! - **A frame that kept nothing.** A frame the inspector answered in place of running never +//! started, and a frame that failed had its journal checkpoint reverted before the inspector saw +//! its result. Whatever the inspector hands the caller for either — Foundry's `expectRevert` +//! turns a failed call into a success — the caller sees the success, the output and the regular +//! gas the inspector chose, and nothing else of the frame: no state or history gas, no refund and +//! no write record for writes the journal does not hold, and the upfront state gas its caller's +//! opcode was charged for an account the frame did not add comes back, at the price of the +//! account it was charged for: a call whose target the inspector's `call` hook rewrote gives the +//! charge back as recorded before the hook ran. A creation revived this way hands its creator the +//! address the inspector gave, with nothing deployed there. +//! - **A success rewritten into a failure keeps nothing either.** A frame the inspector turns from +//! a success into a failure — Foundry's `expectRevert` on a call that did not revert — has its +//! journal taken back to its checkpoint, as revm takes back a frame that fails: the frame's own, +//! or, for a start revm answers without building a frame (a call to a precompile or to an account +//! with no code), where the start began. So the state follows the failure its ledgers settle as: +//! no account, slot, code, value moved or log of the frame's is kept, and a creation keeps its +//! creator's nonce bump, which revm makes before the creation's checkpoint, as one that fails +//! does. Everything journaled since the checkpoint goes, what the inspector itself wrote to the +//! journal during the frame or in the callback that rewrote its result included; where revm fails +//! a frame the checkpoint is gone before `call_end`, so a write made there stays. The journal's +//! depth is left as it was. +//! +//! A limit stop is the revert of the frame that crossed the limit, and a rewrite of it is a +//! rewrite of a failure like any other: it settles as above, and the transaction reports no stop +//! once the result of its own frame is no longer the stop's revert. Every other rewrite is the +//! tool's business. +//! +//! # What an inspector's writes to gas cannot do +//! +//! - **Gas changed at a frame's end has no effect.** The instruction that ends a frame copies the +//! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas +//! after it reaches nobody. A tool that changes what a frame returns changes its result, in +//! `call_end`, `create_end` or `frame_end`: that gas is what the caller, or the transaction's +//! settlement, takes in. +//! - **An inspector cannot overdraw a frame.** A charge the frame's spendable gas cannot pay is +//! refused and takes nothing, and the frame is not halted: the interpreter does not ask the +//! callback what it did. A tool that wants a frame out of gas says so through its result. Under +//! gas detention the refusal of an opcode's charge the withheld part would have paid is the +//! crossing; the refusal of an inspector's is not, and classifies nothing ([`StepGuard`]). +//! - **Gas an inspector puts back carries the split it was taken with.** The part gas detention +//! withholds is in the frame's `Gas`, and detention sets it where it can have moved: at a read of +//! volatile data, when the frame starts or resumes, and after an `SSTORE`. An inspector that +//! overwrites the interpreter's gas — Foundry's `pauseGasMetering` puts a snapshot back before +//! every instruction — overwrites the split with it, and the frame runs on the snapshot's split +//! until detention next sets it. Only the crossing record is kept from a callback's write. +//! - **An answer carries only the regular gas the inspector chose.** A frame the inspector answered +//! never ran, so it drew nothing from the reservoir: whatever `Gas` the answer is built on — +//! `Gas::new(limit)`, as Foundry answers a cheatcode, carries no reservoir — its caller merges +//! back the reservoir it forwarded, and none of the state gas, history gas or refund the answer +//! carries. The gas of a result a frame ran to produce is the inspector's to rewrite, reservoir +//! included. use revm::{ - context::{ContextError, ContextTr, JournalTr}, + context::{ContextTr, JournalTr}, + context_interface::{cfg::StateGasCharge, journaled_state::JournalCheckpoint, Host}, handler::FrameResult, inspector::{handler::frame_end, JournalExt, NoOpInspector}, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, Interpreter, InterpreterTypes, }, - primitives::{Address, Log, U256}, - Inspector, + primitives::{Address, Bytes, Log, U256}, + Database, Inspector, }; -/// The message of the `EVMError::Custom` a refused creation revival fails the transaction with. -/// -/// Public so a tool driving rewriting inspectors can tell the refusal from an execution failure. -pub const FORBIDDEN_CREATE_REVIVAL: &str = - "inspector rewrote a failed contract creation into a successful one"; +use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; /// A declaration, made in source about one inspector type, that none of its callbacks writes /// anything back to the EVM: nothing to an interpreter's gas or pending action, nothing to a @@ -226,6 +301,56 @@ where } } +/// Hands a running frame's instruction-loop callbacks to the inspector inside, and keeps what they +/// do to the interpreter's gas from classifying the frame. +/// +/// A regular charge the frame's spendable gas cannot pay is refused, and when the part gas +/// detention withholds would have paid it the refusal is recorded as the crossing, which stops the +/// transaction at the compute limit when the frame ends. An opcode's refused charge halts the +/// frame at once, so its record is the frame's end. An inspector's does not: the interpreter never +/// sees it fail and the frame runs on. So the record a callback leaves is put back to what it was +/// before the callback, and the frame ends on the charges it made itself. +/// +/// It stands in for the inspector in revm's instruction loop alone (`inspect_instructions`), which +/// makes the four callbacks forwarded here and no other; frame starts and ends reach the inspector +/// itself. The other callbacks are left to the trait's no-op defaults rather than forwarded, +/// because the loop never makes them and a forward nothing reaches is one nothing tests. So a +/// callback the loop gains in a later revision of the fork reaches no inspector until it is +/// forwarded here: a fork upgrade checks the loop's callbacks against this list. +pub(crate) struct StepGuard<'a, I>(pub(crate) &'a mut I); + +impl Inspector for StepGuard<'_, I> +where + I: Inspector, + INTR: InterpreterTypes, +{ + #[inline] + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let crossing = interp.gas.withheld_crossing(); + self.0.step(interp, context); + interp.gas.set_withheld_crossing(crossing); + } + + #[inline] + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let crossing = interp.gas.withheld_crossing(); + self.0.step_end(interp, context); + interp.gas.set_withheld_crossing(crossing); + } + + #[inline] + fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { + let crossing = interp.gas.withheld_crossing(); + self.0.log_full(interp, context, log); + interp.gas.set_withheld_crossing(crossing); + } + + #[inline] + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.0.selfdestruct(contract, target, value); + } +} + /// The journal's entry and log counts, for the debug-build proof. `None` in release builds. type JournalSnapshot = Option<(usize, usize)>; @@ -323,42 +448,223 @@ fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callbac } } -/// Hands a frame's end to the inspector, then applies the one refusal: a creation that failed, -/// rewritten into a success, is put back and fails the transaction with -/// [`FORBIDDEN_CREATE_REVIVAL`]. +/// What the calling opcode charged upfront for a call, as it stood before the inspector could see +/// the call: whether it charged the new-account state gas, and for which address. /// -/// Every place a frame result reaches the inspector goes through here, so the refusal covers a -/// result a frame ran to produce and one answered without running. A frame the inspector answered -/// with a success itself is no revival: nothing failed. +/// An inspector's `call` hook holds the call's inputs mutably, and a rewritten target would +/// otherwise be the address the charge is given back at, priced in another SALT bucket than the one +/// it was made in. The record is taken before `frame_start` and written into the frame's result +/// when the frame ends, whatever produced the result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct UpfrontRecord { + charged_new_account_state_gas: bool, + charged_state_gas_address: Address, +} + +impl UpfrontRecord { + /// The record of the call `input` starts; none for any other frame, whose creation inputs keep + /// what they charged and where in fields an inspector's hook cannot write. + pub(crate) fn of(input: &FrameInput) -> Option { + match input { + FrameInput::Call(inputs) => Some(Self { + charged_new_account_state_gas: inputs.charged_new_account_state_gas, + charged_state_gas_address: inputs.target_address, + }), + _ => None, + } + } + + /// `input` with the call's upfront charge as the record has it. + fn restore(self, input: &FrameInput) -> FrameInput { + let mut input = input.clone(); + if let FrameInput::Call(inputs) = &mut input { + inputs.charged_new_account_state_gas = self.charged_new_account_state_gas; + inputs.target_address = self.charged_state_gas_address; + } + input + } +} + +/// Where the result [`frame_end_checked`] hands the inspector came from. +#[derive(Clone, Copy, Debug)] +pub(crate) enum ResultSource { + /// The inspector answered the frame in place of running it: nothing of the frame is in the + /// journal. + Inspector, + /// The engine produced it — a frame that ran, or a start revm or the engine answered without + /// building a frame — and what the frame journaled begins at the checkpoint: the frame's own, + /// or where the journal stood when the start began. + Engine(JournalCheckpoint), +} + +/// Hands a frame's end to the inspector, then settles what its rewrite does not change. +/// +/// - **A frame that kept nothing.** A frame the inspector answered in place of running, and a frame +/// that failed before the inspector saw it, made no write the journal kept. Whatever the +/// inspector left the result saying, it settles into its caller as such a frame does +/// ([`settle_kept_nothing`]). +/// - **A success rewritten into a failure.** The journal follows the result: what the frame +/// journaled is taken back to its checkpoint, as revm takes back a frame that fails, so the state +/// holds none of the writes the failure's settlement bills nothing for. A frame the inspector +/// answered journaled nothing, so nothing is taken back for it. +/// +/// Every place a frame result reaches the inspector goes through here, so both cover a result +/// a frame ran to produce and one answered without running. #[inline] -pub(crate) fn frame_end_checked( - context: &mut CTX, +pub(crate) fn frame_end_checked( + context: &mut MegaContext, inspector: &mut INSP, frame_input: &FrameInput, frame_result: &mut FrameResult, + depth: usize, + source: ResultSource, + upfront: Option, ) where - CTX: ContextTr, + DB: Database, + ExtEnvs: ExternalEnvTypes, INTR: InterpreterTypes, - INSP: Inspector, + INSP: Inspector, INTR, FrameInput, FrameResult>, { let before = frame_result.instruction_result(); frame_end(context, inspector, frame_input, frame_result); - refuse_create_revival(context, before, frame_result); + // What the opcode charged is what was recorded before the inspector saw the call, not what its + // hooks left in the inputs. + let restored = upfront.and_then(|record| { + (UpfrontRecord::of(frame_input) != Some(record)).then(|| record.restore(frame_input)) + }); + let frame_input = restored.as_ref().unwrap_or(frame_input); + if upfront.is_some() { + carry_upfront_flags(frame_input, frame_result); + } + let answered = match source { + ResultSource::Inspector => true, + ResultSource::Engine(checkpoint) => { + if before.is_ok() && !frame_result.instruction_result().is_ok() { + revert_journal_to(context, checkpoint); + } + false + } + }; + if answered || !before.is_ok() { + settle_kept_nothing(context, frame_input, frame_result, depth, answered); + } } -/// Puts a revived creation back to `before` and records the refusal as the context's error. -fn refuse_create_revival( - context: &mut CTX, - before: InstructionResult, +/// Settles the result of a frame at `depth` that kept nothing in the journal — one an inspector +/// answered in place of running, or one whose checkpoint was reverted before the inspector saw its +/// result — as such a frame settles, whatever the inspector made of the result. +/// +/// The calling opcode's upfront state-gas charge — the account a value call adds, the account a +/// creation adds, or EIP-2780's for the transaction's own frame — is given back: the frame added +/// no account. The result carries the frame's own upfront-charge flags again, so a result that +/// fails gets it back from revm's settlement, as revm's own do; one an inspector answered carries +/// none of them otherwise. +/// +/// A frame the inspector answered (`answered`) never ran, so it drew nothing from its pools: its +/// answer's gas carries nothing but the regular gas the inspector chose. Whatever `Gas` the answer +/// was built on — `Gas::new(limit)`, which carries no reservoir, or one carrying charges — its +/// state and history charges are rolled back, its refund is dropped, and its reservoir is the one +/// the frame inherited, so its caller merges back the reservoir it forwarded. The rollback comes +/// first: it unwinds the charges against the answer's own reservoir, which the inherited one then +/// replaces, so a charge the answer carries is counted neither in the reservoir nor on a ledger. +/// +/// A result that says success is not one revm's settlement treats as keeping nothing, so it is made +/// to settle like the failure it stands for, save what the inspector chose — the success its caller +/// sees, the output, the regular gas: +/// +/// - its state and history charges are rolled back and its refunds dropped, as a failure's are, +/// before its caller merges them; +/// - the upfront charge comes back through it: the result holds it as state its frame gave back, as +/// a frame that restored a slot its caller filled does, and its caller's merge nets it out; +/// - for the transaction's own frame, the history of the write record charged before execution for +/// its start comes back the same way; +/// - its lane is discarded as a failure's is, so nothing it counted reaches its caller, which gets +/// back the history it paid for the records. +fn settle_kept_nothing( + context: &mut MegaContext, + input: &FrameInput, result: &mut FrameResult, + depth: usize, + answered: bool, ) { - let FrameResult::Create(outcome) = result else { return }; - if before.is_ok() || !outcome.result.result.is_ok() { + carry_upfront_flags(input, result); + let success = result.instruction_result().is_ok(); + let gas = result.gas_mut(); + if answered || success { + gas.rollback_state_gas(); + gas.set_refunded(0); + } + if answered { + gas.set_reservoir(inherited_reservoir(input)); + } + if !success { return; } - outcome.result.result = before; - if context.error().is_ok() { - let message: String = format!("{FORBIDDEN_CREATE_REVIVAL}: {before:?}"); - *context.error() = Err(ContextError::Custom(message)); + // A creation answered with a success and no address is one revm's settlement gives the + // charge back for itself. + let upfront = upfront_charge(input).filter(|_| result.refundable_state_gas_charge().is_none()); + // A failed lookup records its cause, which fails the transaction before the result settles. + let upfront = upfront.map_or(Some(0), |charge| context.state_gas_charge(charge)); + let history = + if depth == 0 { context.additional_limit.top_level_write_record_gas() } else { 0 }; + let gas = result.gas_mut(); + gas.refill_reservoir(upfront.unwrap_or_default()); + gas.refill_history(history); + context.additional_limit.discard_returning_lane(); +} + +/// Where the journal stands: the checkpoint a frame starting now would take, taken without +/// changing the journal's depth. +#[inline] +pub(crate) fn journal_position( + context: &mut MegaContext, +) -> JournalCheckpoint { + let journal = context.journal_mut(); + let checkpoint = journal.checkpoint(); + journal.checkpoint_commit(); + checkpoint +} + +/// Takes back every journal entry, log and self-destruct made since `checkpoint`, as revm takes +/// back a frame that fails, and leaves the journal's depth as it is: the frame's own checkpoint was +/// already closed, so one is opened for the revert to close. +pub(crate) fn revert_journal_to( + context: &mut MegaContext, + checkpoint: JournalCheckpoint, +) { + let journal = context.journal_mut(); + let _ = journal.checkpoint(); + journal.checkpoint_revert(checkpoint); +} + +/// Sets `result`'s upfront-charge flags to those of `input`, the frame it answers: what revm's +/// settlement reads to give the calling opcode's upfront state-gas charge back. +fn carry_upfront_flags(input: &FrameInput, result: &mut FrameResult) { + match (input, result) { + (FrameInput::Call(inputs), FrameResult::Call(outcome)) => { + outcome.charged_new_account_state_gas = inputs.charged_new_account_state_gas; + outcome.charged_state_gas_address = inputs.target_address; + } + (FrameInput::Create(inputs), FrameResult::Create(outcome)) => { + outcome.charged_create_state_gas = inputs.charged_create_state_gas(); + outcome.charged_state_gas_address = inputs.charged_state_gas_address(); + } + _ => {} + } +} + +/// The reservoir the frame `input` starts inherits from its caller. +const fn inherited_reservoir(input: &FrameInput) -> u64 { + match input { + FrameInput::Call(inputs) => inputs.reservoir, + FrameInput::Create(inputs) => inputs.reservoir(), + FrameInput::Empty => 0, } } + +/// The upfront state-gas charge the calling opcode made for the frame `input` starts: the charge +/// revm's settlement gives back when that frame fails. +fn upfront_charge(input: &FrameInput) -> Option { + synthetic_frame_result(input, InstructionResult::Revert, Bytes::new()) + .refundable_state_gas_charge() +} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index e3d5edc1e..7494f5e2c 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,19 +1,60 @@ //! The instruction table of the Satin engine. //! -//! Every opcode runs revm's own instruction, except the three that write state the resource -//! limits count: `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT`. Each of those runs in a wrapper -//! that commits what the Host staged for it after the opcode completed: +//! Every opcode runs revm's own instruction, except the ones that write state the resource +//! limits count. Three of them write it themselves — `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` +//! — and four write it by starting a frame: `CALL`, `CALLCODE`, `CREATE` and `CREATE2`. +//! +//! The first three run in a wrapper that commits what the Host staged for them after the opcode +//! completed: //! //! 1. discard any record staged before the opcode (nothing may commit it for this one); -//! 2. run revm's instruction, whose Host call stages the record; -//! 3. commit the record if the opcode completed, discard it if the opcode failed. +//! 2. run revm's instruction, whose Host call stages the record and which charges the state gas of +//! a fresh slot or a new beneficiary; +//! 3. discard the record if the opcode failed; if it completed, commit it; +//! 4. charge the frame the history gas of what the record appends — and give it back when the +//! record was taken away, as a slot written back to its original value takes its own back. +//! +//! The history a record costs is its data size, so the charge and the count cannot drift apart: +//! a log pays for its address, its topics and its data, a storage write or a destructed account's +//! beneficiary for the forty bytes of one write record. //! //! A commit that crosses a limit stops the opcode's frame with a revert whose output is -//! [`MegaLimitExceeded`](crate::MegaLimitExceeded) (see -//! [`AdditionalLimit`](crate::AdditionalLimit) for the abort protocol). +//! [`MegaLimitExceeded`](crate::MegaLimitExceeded), and its caller resumes as after any revert +//! (see [`AdditionalLimit`](crate::AdditionalLimit) for the stop). A history charge the frame +//! cannot pay is an ordinary out-of-gas, which burns the frame's gas the way any other does. +//! +//! The other four run in a wrapper that charges their frame for the write records the frame it +//! starts makes — a value transfer's sender and recipient, a creation's creator nonce and created +//! account — before the frame runs, so the gas it forwards is not reduced by them and its +//! allowance is free for what the recipient does. What the frame does not keep goes back to the +//! caller when it returns. The frame the opcode is suspending on carries the caller's reservoir, +//! which the charge has just moved, so the wrapper writes the reservoir it left into the frame's +//! input; and a caller that cannot pay the charge drops that frame before it fails, because an +//! interpreter halts on an instruction's error only when no frame is pending. +//! +//! Every opcode that can read volatile data — the block-environment opcodes, the account opcodes, +//! `SLOAD`, the four calls and `SELFDESTRUCT` — runs in a wrapper that settles the reads its Host +//! calls made (see the `access` module): +//! +//! 1. discard any read observed or refused before the opcode; +//! 2. keep the frame's gas, when the frame's reads are refused; +//! 3. run the instruction (or the wrapper above it), whose Host calls observe or refuse the reads; +//! 4. on a refusal, hand the frame back the gas it had before the opcode and revert it with +//! `VolatileDataAccessDisabled`; otherwise, once the opcode completed, commit the reads, which +//! holds the frame's spendable gas to what the compute limit leaves it. //! -//! A wrapper keeps the static gas revm's table charges for its opcode, so the gas schedule is -//! unchanged. +//! `SSTORE` also holds its frame to the compute limit again once it completed: a slot restored to +//! its original value refills regular gas. +//! +//! An opcode whose charge fails with an out-of-gas halts its frame, and the halt zeroes the gas +//! the frame had left before the frame returns. Every wrapper above notes that gas for gas +//! detention first, which does not count what a halt burns as compute; so does a wrapper around +//! the opcodes whose own charge has no bound, `KECCAK256` and the four copies into memory, and +//! around `EXP`, whose exponent charge reaches 1,600. The one charge no wrapper sees is an +//! opcode's static gas, which the interpreter's step loop makes before the opcode runs. +//! +//! A wrapper keeps the static gas the table charges for its opcode, so the gas schedule is +//! unchanged. The static gas table is Amsterdam's ([`satin_gas_table`]). //! //! The table also carries the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), which //! the base spec gates off: Satin takes the Amsterdam schedule, so it takes the opcodes with it. @@ -22,23 +63,32 @@ //! the base spec already has it. use revm::{ - bytecode::opcode::{LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, SSTORE}, + bytecode::opcode::{ + BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, CALLDATACOPY, CODECOPY, COINBASE, + CREATE, CREATE2, DELEGATECALL, DIFFICULTY, EXP, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, + GASLIMIT, KECCAK256, LOG0, LOG1, LOG2, LOG3, LOG4, MCOPY, NUMBER, RETURNDATACOPY, + SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, TIMESTAMP, + }, + context_interface::Host, handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{gas_table_spec, host}, + instructions::{arithmetic, block_info, contract, host, memory, system}, interpreter::EthInterpreter, interpreter_types::LoopControl, - Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, - InterpreterAction, + FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, + Interpreter, InterpreterAction, }, - primitives::hardfork::SpecId, + primitives::{hardfork::SpecId, Bytes}, Database, }; -use crate::{ExternalEnvTypes, LimitCheck, MegaContext}; +use crate::{ + charge_write_records_history, history_gas, limit::HistoryBytes, + volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, +}; -use super::MegaInstructions; +use super::{caller_refuses_start, satin_gas_table, MegaInstructions}; /// The context an instruction of the Satin engine runs with. type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; @@ -46,15 +96,16 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth /// An instruction of the Satin engine. type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; -/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated -/// and `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` wrapped. +/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated, +/// the opcodes that write state the limits count wrapped, and the opcodes that can read volatile +/// data wrapped, on the Satin static gas table. pub(crate) fn mega_instructions( spec: SpecId, ) -> MegaInstructions { let mut table = instruction_table(); enable_amsterdam_opcodes(&mut table); - let mut instructions = EthInstructions::new(table, gas_table_spec(spec), spec); - let wrappers: [(u8, InstructionFn); 7] = [ + let mut instructions = EthInstructions::new(table, satin_gas_table(), spec); + let wrappers: [(u8, InstructionFn); 34] = [ (SSTORE, sstore::), (LOG0, log::<0, DB, ExtEnvs>), (LOG1, log::<1, DB, ExtEnvs>), @@ -62,6 +113,33 @@ pub(crate) fn mega_instructions( (LOG3, log::<3, DB, ExtEnvs>), (LOG4, log::<4, DB, ExtEnvs>), (SELFDESTRUCT, selfdestruct::), + (CALL, call::), + (CALLCODE, call::), + (DELEGATECALL, volatile_call::), + (STATICCALL, volatile_call::), + (CREATE, create::), + (CREATE2, create::), + (COINBASE, coinbase::), + (TIMESTAMP, timestamp::), + (NUMBER, number::), + (DIFFICULTY, difficulty::), + (GASLIMIT, gaslimit::), + (BASEFEE, basefee::), + (BLOBBASEFEE, blobbasefee::), + (SLOTNUM, slotnum::), + (BLOCKHASH, blockhash::), + (BALANCE, balance::), + (SELFBALANCE, selfbalance::), + (EXTCODESIZE, extcodesize::), + (EXTCODECOPY, extcodecopy::), + (EXTCODEHASH, extcodehash::), + (SLOAD, sload::), + (KECCAK256, keccak256::), + (CALLDATACOPY, calldatacopy::), + (CODECOPY, codecopy::), + (RETURNDATACOPY, returndatacopy::), + (MCOPY, mcopy::), + (EXP, exp::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -70,18 +148,24 @@ pub(crate) fn mega_instructions( instructions } -/// Runs `inner` and commits the record its Host call staged once it completed. +/// Runs `inner`, commits the record its Host call staged once it completed, and settles the +/// history gas the record costs. /// /// An opcode completes when it returns `Ok` or stops the frame successfully (`SELFDESTRUCT` /// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the /// staged write back with it. +/// +/// The record is held to the data-size limit first, and only then is its history charged. A record +/// the limit rejects is not kept, so its history is not a charge and the stop is what the frame +/// reports. A record the limit accepts is charged, and a charge the frame cannot pay is an +/// out-of-gas. #[inline(always)] -fn commit_after( +fn commit_after( context: Ctx<'_, DB, ExtEnvs>, inner: InstructionFn, ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; - host.additional_limit.discard_stale_record(); + host.additional_limit.discard_staged_record(); let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); let completed = match result { Ok(()) => true, @@ -89,56 +173,410 @@ fn commit_after( }; if !completed { host.additional_limit.discard_staged_record(); - return result; + return note_halt(interpreter, host, result); } - let check = host.additional_limit.commit_staged_record(); + let (check, history) = host.additional_limit.commit_staged_record(); if check.exceeded_limit() { - return Err(stop_frame(interpreter, &check)); + return Err(stop_frame(interpreter, host.additional_limit.note_frame_stop(&check))); + } + if host.prices_history() { + let settled = settle_history::(interpreter, host, history); + if settled.is_err() { + return note_halt(interpreter, host, settled); + } } result } -/// Stops the running frame with the revert a crossed limit asks for: its output is -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) and its gas is the frame's, so the caller gets -/// the unspent part back. +/// Charges the running frame the history gas of the bytes a record appends, or gives back the +/// history of a record that was taken away. +/// +/// Both sides are priced the same way, so a record taken back cancels its own charge exactly, +/// whichever frame made it: a refill below zero is reconciled when the frame merges into its +/// caller. A byte count with no price and a charge the frame cannot pay are both an out-of-gas. +/// +/// With `FROM_ALLOWANCE` the frame's history allowance pays what it can of the charge before the +/// frame's gas pays the rest ([`storage_call_stipend`](crate::storage_call_stipend)). Only the +/// log site sets it: a write record is the frame's own to pay for, and a record taken back gives +/// back what the frame's gas paid, never what the allowance did — the allowance is spent, not +/// lent. +#[inline] +fn settle_history( + interpreter: &mut Interpreter, + host: &mut MegaContext, + history: HistoryBytes, +) -> Result<(), InstructionResult> { + match history { + HistoryBytes::None => Ok(()), + HistoryBytes::Appended(bytes) => { + let Some(cost) = history_gas(bytes) else { return Err(InstructionResult::OutOfGas) }; + let drawn = + if FROM_ALLOWANCE { host.additional_limit.try_consume_stipend(cost) } else { 0 }; + if interpreter.gas.record_history_cost(cost - drawn) { + Ok(()) + } else { + Err(InstructionResult::OutOfGas) + } + } + HistoryBytes::Taken(bytes) => { + interpreter.gas.refill_history(history_gas(bytes).unwrap_or(0)); + Ok(()) + } + } +} + +/// Stops the running frame with the revert a crossed limit asks for: its output is the stop's +/// [`MegaLimitExceeded`](crate::MegaLimitExceeded), `output`, and its gas is the frame's, so the +/// caller gets the unspent part back. #[cold] #[inline(never)] -fn stop_frame( - interpreter: &mut Interpreter, - check: &LimitCheck, -) -> InstructionResult { +fn stop_frame(interpreter: &mut Interpreter, output: Bytes) -> InstructionResult { if interpreter.bytecode.action().is_some() { // A `SELFDESTRUCT` or a return the opcode already set gives way to the stop. let _ = interpreter.take_next_action(); } let result = InstructionResult::Revert; - interpreter.bytecode.set_action(InterpreterAction::new_return( - result, - check.revert_data(), - interpreter.gas, - )); + interpreter.bytecode.set_action(InterpreterAction::new_return(result, output, interpreter.gas)); result } -/// `SSTORE`, committing the slot's write record. +/// `SSTORE`, committing the slot's write record, then holding the frame to the compute limit +/// again: a slot restored to its original value refills the state and history gas that spilled +/// onto regular gas, and the spill may predate the limit. fn sstore( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - commit_after(context, host::sstore) + let InstructionContext { interpreter, host } = context; + let result = commit_after::( + InstructionContext { interpreter: &mut *interpreter, host: &mut *host }, + host::sstore, + ); + // Only a restore refills, and a restore takes a record back rather than adding one, so it + // never crosses a limit: no stop's result is pending when the frame is held again. + host.detention.hold(&mut interpreter.gas); + result } /// `LOG0`..`LOG4`, committing the log's bytes. fn log( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - commit_after(context, host::log::>) + commit_after::(context, host::log::>) } -/// `SELFDESTRUCT`, committing the beneficiary's write record. +/// `SELFDESTRUCT`, committing the beneficiary's write record and the read of the block +/// beneficiary's account when it is either end. fn selfdestruct( context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { - commit_after(context, host::selfdestruct) + read_volatile(context, |context| commit_after::(context, host::selfdestruct)) +} + +/// Runs `inner` and charges the frame the history of the write records the frame `inner` starts +/// will make. +/// +/// The charge is made after revm's instruction has computed the gas it forwards, so it comes out +/// of what the caller kept rather than out of what the callee gets. An opcode that starts no frame +/// — a creation the balance, the nonce or the depth refuses, an out-of-gas — makes no records and +/// is charged nothing. Neither is a frame revm will refuse on its caller's account — a value call +/// the caller cannot fund ([`caller_refuses_start`]) — which the data size does not count either; +/// the answer is left for the frame's init, which would otherwise read the caller's account again. +/// A frame revm refuses for another reason — one past the call-stack limit — makes no records, +/// and its failure gives the charge back. A charge the caller cannot pay fails the opcode with an +/// out-of-gas, which takes the frame the opcode was suspending on with it ([`abandon_frame`]). +/// +/// revm's instruction has also charged the caller the state gas of the account the frame would +/// add — a value transfer's new recipient, a created account; a frame revm refuses gives it back. +/// +/// The frame inherits the reservoir the charge left, not the one the caller held before it +/// ([`inherit_reservoir`]). +#[inline(always)] +fn charge_frame_start( + context: Ctx<'_, DB, ExtEnvs>, + inner: InstructionFn, +) -> InstructionExecResult { + let InstructionContext { interpreter, host } = context; + let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + // An opcode that starts a frame suspends with the frame's input as its action; one that ends + // otherwise — a creation the balance cannot fund, an out-of-gas — leaves no such action and + // makes no records. + let records = match interpreter.bytecode.action() { + Some(InterpreterAction::NewFrame(input)) => { + let refused = caller_refuses_start(host, input); + host.additional_limit.stage_start_refused(refused); + if refused { + return result; + } + host.additional_limit.frame_start_records(input) + } + _ => return note_halt(interpreter, host, result), + }; + if !host.prices_history() { + return result; + } + let charged = charge_write_records_history( + interpreter.gas.tracker_mut(), + records.on_lane, + u64::from(records.caller), + ); + let Some((on_lane, caller)) = charged else { return abandon_frame(interpreter, host) }; + inherit_reservoir(interpreter); + host.additional_limit.stage_frame_charge(records, on_lane, caller); + result +} + +/// Fails the running opcode with an out-of-gas and drops the frame it was suspending on. +/// +/// The four frame-starting opcodes set the frame's input as the interpreter's action inside +/// revm's instruction, before this wrapper runs. An interpreter halts on an instruction's error +/// only when no action is pending, so a frame left pending here would start anyway — and make +/// write records nobody paid for, at any gas limit at which the caller keeps less after the +/// 63/64 forward than its records cost. +/// +/// The gas the opcode forwarded to the dropped frame goes back to the caller, which the halt then +/// burns with the rest: it never ran, so gas detention counts it with what the halt burns rather +/// than as compute. A value call's stipend was never the caller's, and is not handed back. +#[cold] +#[inline(never)] +fn abandon_frame( + interpreter: &mut Interpreter, + host: &mut MegaContext, +) -> InstructionExecResult { + if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { + interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); + } + note_halt(interpreter, host, Err(InstructionResult::OutOfGas)) +} + +/// Passes `result` on, first noting for gas detention what the running frame has left when +/// `result` is an out-of-gas the interpreter will halt the frame on: the halt zeroes it before the +/// frame returns, and it is what the halt burns rather than what the frame ran. +/// +/// The interpreter halts on an instruction's error only when no action is pending; an opcode that +/// set one ends its frame with that action instead, and burns nothing. +#[inline(always)] +fn note_halt( + interpreter: &mut Interpreter, + host: &mut MegaContext, + result: InstructionExecResult, +) -> InstructionExecResult { + if result == Err(InstructionResult::OutOfGas) && interpreter.bytecode.action().is_none() { + host.detention.note_halt(interpreter.gas.remaining()); + } + result +} + +/// Hands the frame the running opcode is suspending on the reservoir its caller has now. +/// +/// revm's `CALL`, `CALLCODE`, `CREATE` and `CREATE2` copy the caller's reservoir into the frame's +/// input, and they do it before this wrapper charges anything. A returning frame's reservoir is +/// adopted by its caller rather than merged into it, so a frame that inherited the reservoir as +/// it stood before the charge would hand the charge straight back — and a frame answered without +/// running, whose gas is built from the same field, would hand it back a second time. Writing the +/// post-charge reservoir into the input closes both. +#[inline] +fn inherit_reservoir(interpreter: &mut Interpreter) { + let reservoir = interpreter.gas.reservoir(); + if let Some(InterpreterAction::NewFrame(input)) = interpreter.bytecode.action() { + match input { + FrameInput::Call(inputs) => inputs.reservoir = reservoir, + FrameInput::Create(inputs) => inputs.set_reservoir(reservoir), + FrameInput::Empty => {} + } + } +} + +/// `CALL` and `CALLCODE`, charging the caller for the records a value transfer writes and +/// committing the read of the block beneficiary's account when the callee, or the EIP-7702 +/// delegate it runs, is the beneficiary. +/// +/// `CALLCODE` runs the callee's code in the caller's own account, so the two records of a `CALL` +/// — the sender's and the recipient's — are one here. +fn call( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + read_volatile(context, |context| charge_frame_start(context, contract::call::)) +} + +/// `DELEGATECALL` and `STATICCALL`, committing the read of the block beneficiary's account when +/// the callee, or the EIP-7702 delegate it runs, is the beneficiary. They carry no value and write +/// nothing, so no record is charged. +fn volatile_call( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + read_volatile(context, contract::call::) +} + +/// `CREATE` and `CREATE2`, charging the creator for the created account's record and for its own +/// nonce. +fn create( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + charge_frame_start(context, contract::create::) +} + +/// Runs `inner` and settles the reads of volatile data its Host calls made: a refused read +/// reverts the frame with `VolatileDataAccessDisabled`, and a read the opcode completed is +/// committed, capping the frame at what the compute limit leaves it. +/// +/// A refusal hands the frame back the gas it had when the wrapper started, which is after the +/// interpreter charged the opcode's static gas: the Host refuses before it loads anything, but an +/// opcode may charge part of its dynamic gas before its load (a copy's memory, a call's value +/// transfer), and none of that is owed for a read that did not happen. +/// +/// A read the opcode did not complete — the opcode failed after the load — is dropped: it reached +/// no computation, and the frame is failing anyway. +#[inline(always)] +fn read_volatile( + context: Ctx<'_, DB, ExtEnvs>, + inner: impl FnOnce(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult, +) -> InstructionExecResult { + let InstructionContext { interpreter, host } = context; + host.detention.discard_stale_reads(); + let gas = host.detention.is_refusing().then_some(interpreter.gas); + let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + if !host.detention.has_reads() { + return note_halt(interpreter, host, result); + } + settle_reads(interpreter, host, result, gas) +} + +/// The slow half of [`read_volatile`]: the Host observed or refused a read. +#[inline(never)] +fn settle_reads( + interpreter: &mut Interpreter, + host: &mut MegaContext, + result: InstructionExecResult, + gas: Option, +) -> InstructionExecResult { + let observed = host.detention.take_observed(); + if let Some(refused) = host.detention.take_refused() { + return Err(refuse(interpreter, refused, gas)); + } + let completed = match result { + Ok(()) => true, + Err(result) => { + result.is_ok() || + matches!(interpreter.bytecode.action(), Some(InterpreterAction::NewFrame(_))) + } + }; + if !completed { + return note_halt(interpreter, host, result); + } + // A completed opcode leaves no result pending: a `SELFDESTRUCT`'s is built from the frame's + // gas once the wrapper returned, and a stop fails the opcode. + let forwarded = match interpreter.bytecode.action() { + Some(InterpreterAction::NewFrame(input)) => { + forwarded_gas(input, host.gas_params().call_stipend()) + } + _ => 0, + }; + host.detention.commit_reads(observed, &mut interpreter.gas, interpreter.input.depth, forwarded); + result +} + +/// Reverts the running frame with `VolatileDataAccessDisabled` for the read `refused`, on the gas +/// it had before the opcode (`gas`, when the wrapper kept it). +#[cold] +#[inline(never)] +fn refuse( + interpreter: &mut Interpreter, + refused: VolatileDataAccess, + gas: Option, +) -> InstructionResult { + // The Host refuses a load before the opcode builds a frame, so no action is pending. + if let Some(gas) = gas { + interpreter.gas = gas; + } + let result = InstructionResult::Revert; + interpreter.bytecode.set_action(InterpreterAction::new_return( + result, + volatile_data_access_disabled_revert_data(refused), + interpreter.gas, + )); + result +} + +/// The regular gas the running frame paid for the frame `input` starts: the frame's limit, less +/// a value call's stipend, which nobody paid. +fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { + match input { + FrameInput::Call(inputs) if inputs.transfers_value() => { + inputs.gas_limit.saturating_sub(call_stipend) + } + FrameInput::Call(inputs) => inputs.gas_limit, + FrameInput::Create(inputs) => inputs.gas_limit(), + FrameInput::Empty => 0, + } +} + +/// Defines an opcode that reads volatile data — a block-environment field, an account or a slot — +/// as revm's instruction in [`read_volatile`]. +macro_rules! volatile_read { + ($($name:ident => $inner:path, $opcode:literal, $what:literal;)*) => {$( + #[doc = concat!("`", $opcode, "`, committing the read of ", $what, ".")] + fn $name( + context: Ctx<'_, DB, ExtEnvs>, + ) -> InstructionExecResult { + read_volatile(context, $inner) + } + )*}; +} + +volatile_read! { + coinbase => block_info::coinbase, "COINBASE", "the field"; + timestamp => block_info::timestamp, "TIMESTAMP", "the field"; + number => block_info::block_number, "NUMBER", "the field"; + difficulty => block_info::difficulty, "PREVRANDAO", "the field"; + gaslimit => block_info::gaslimit, "GASLIMIT", "the field"; + basefee => block_info::basefee, "BASEFEE", "the field"; + blobbasefee => block_info::blob_basefee, "BLOBBASEFEE", "the field"; + slotnum => block_info::slot_num_enabled, "SLOTNUM", "the field"; + balance => host::balance, "BALANCE", "the block beneficiary's account"; + selfbalance => host::selfbalance, "SELFBALANCE", "the block beneficiary's account"; + extcodesize => host::extcodesize, "EXTCODESIZE", "the block beneficiary's account"; + extcodecopy => host::extcodecopy, "EXTCODECOPY", "the block beneficiary's account"; + extcodehash => host::extcodehash, "EXTCODEHASH", "the block beneficiary's account"; + sload => host::sload, "SLOAD", "the Oracle's storage"; +} + +/// `BLOCKHASH`, committing the read of the block number and of the hash. +/// +/// revm's instruction reads the block number before the hash, so a refusal is of the number +/// first; it is named for the hash, the kind `BLOCKHASH` reads, as the legacy engine named it. +fn blockhash( + context: Ctx<'_, DB, ExtEnvs>, +) -> InstructionExecResult { + read_volatile(context, |InstructionContext { interpreter, host }| { + let result = host::blockhash(InstructionContext { interpreter, host: &mut *host }); + host.detention.name_refusal(VolatileDataAccess::BLOCK_HASH); + result + }) +} + +/// Defines an opcode whose own charge no other wrapper sees, as revm's instruction with what the +/// frame had left noted when the charge fails ([`note_halt`]): the charge of `KECCAK256` and of +/// the four copies into memory has no bound, and `EXP`'s exponent charge reaches 1,600. +macro_rules! unbounded_charge { + ($($name:ident => $inner:path, $opcode:literal;)*) => {$( + #[doc = concat!("`", $opcode, "`, noting what the frame had when its charge fails.")] + fn $name( + context: Ctx<'_, DB, ExtEnvs>, + ) -> InstructionExecResult { + let InstructionContext { interpreter, host } = context; + let result = $inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + note_halt(interpreter, host, result) + } + )*}; +} + +unbounded_charge! { + keccak256 => system::keccak256, "KECCAK256"; + calldatacopy => system::calldatacopy, "CALLDATACOPY"; + codecopy => system::codecopy, "CODECOPY"; + returndatacopy => system::returndatacopy, "RETURNDATACOPY"; + mcopy => memory::mcopy, "MCOPY"; + exp => arithmetic::exp, "EXP"; } #[cfg(test)] @@ -147,14 +585,15 @@ mod tests { use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; use revm::bytecode::opcode::{CLZ, DUPN, EXCHANGE, SLOTNUM, SWAPN}; - /// The wrappers keep the static gas revm charges for their opcodes: the whole table is revm's. + /// The wrappers keep the static gas the Satin table charges for their opcodes: the whole + /// table is revm's Amsterdam one. /// /// Activating the Amsterdam opcodes does not touch it either — their static gas is the same /// on every spec, which is why the activation is an instruction-table change alone. #[test] fn test_wrappers_keep_the_static_gas_table() { let mega = mega_instructions::(SpecId::OSAKA); - assert_eq!(mega.gas_table(), &gas_table_spec(SpecId::OSAKA)); + assert_eq!(mega.gas_table(), &satin_gas_table()); assert_eq!(mega.spec, SpecId::OSAKA); for (opcode, gas) in [(DUPN, 3), (SWAPN, 3), (EXCHANGE, 3), (SLOTNUM, 2), (CLZ, 5)] { assert_eq!(mega.gas_table()[opcode as usize], gas, "opcode {opcode:#04x}"); diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 45dd80c3f..8893e7efc 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -9,6 +9,7 @@ mod context; mod execution; mod factory; mod frame; +mod history; mod host; mod inspector; mod instructions; @@ -18,12 +19,13 @@ mod result; mod schedule; mod spec; mod state; +mod validation; pub use context::*; pub use execution::*; pub use factory::*; pub use frame::*; -pub use host::*; +pub use history::*; pub use inspector::*; pub use precompiles::*; pub use prices::*; @@ -31,10 +33,11 @@ pub use result::*; pub use schedule::*; pub use spec::*; pub use state::*; +pub use validation::*; #[cfg(not(feature = "std"))] use alloc as std; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, vec::Vec}; use alloy_evm::{ precompiles::{DynPrecompile, PrecompilesMap}, @@ -60,7 +63,7 @@ use revm::{ DatabaseCommit, ExecuteCommitEvm, ExecuteEvm, }; -use crate::{EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; +use crate::{BucketId, EmptyExternalEnv, ExternalEnvTypes, MegaTransaction, MegaTransactionError}; /// The instruction table of the Satin engine. pub(crate) type MegaInstructions = @@ -92,6 +95,8 @@ pub struct MegaEvm MegaEvm { @@ -105,7 +110,12 @@ impl MegaEvm MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, trusted_inspector: false, + priced_precompiles: self.priced_precompiles, } } @@ -135,6 +146,7 @@ impl MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, trusted_inspector: true, + priced_precompiles: self.priced_precompiles, } } @@ -170,21 +182,37 @@ impl MegaEvm { /// Adds `dyn_precompiles` on top of the Satin set, replacing an entry whose address is /// already taken. /// - /// A node's RPC builds these; the chain's own set is the one [`MegaEvm::new`] installs. + /// A node's RPC builds these; the chain's own set is the one [`MegaEvm::new`] installs. A + /// Satin address replaced here is no longer priced from the Satin table: gas detention runs a + /// call to it on the allowance, as it does every precompile it cannot price (see the + /// `precompiles` module). pub fn with_dyn_precompiles( mut self, dyn_precompiles: HashMap, ) -> Self { for (address, dyn_precompile) in dyn_precompiles { + self.priced_precompiles.record_replaced(address); self.inner.precompiles.apply_precompile(&address, move |_| Some(dyn_precompile)); } self } + /// Replaces the whole precompile set with `precompiles`, a set that is not the Satin one: the + /// neutral configuration's, the fixture fork's own. Gas detention prices nothing from the + /// Satin table from then on. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) fn replace_precompile_set(&mut self, precompiles: PrecompilesMap) { + self.inner.precompiles = precompiles; + self.priced_precompiles.record_foreign(); + } + /// Enforces `limits` on every transaction this EVM runs from now on. /// - /// Block execution installs the block's limits this way, so a transaction runs under them - /// whatever the caller configured when it built the EVM. + /// Every EVM already runs under its spec's limits + /// ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)), and block execution + /// installs them again this way before every transaction, so a block's transaction runs under + /// them whatever the caller configured on the EVM. Outside block execution — a tool, a test — + /// this is how a caller runs a counterfactual under others. #[must_use] pub fn with_tx_runtime_limits(mut self, limits: crate::EvmTxRuntimeLimits) -> Self { self.set_tx_runtime_limits(limits); @@ -226,6 +254,33 @@ where pub fn clear_accessed_block_hashes(&mut self) { self.ctx_mut().clear_block_hash_record(); } + + /// The SALT buckets the SALT environment answered with a valid capacity on this EVM so far, + /// in ascending order. + /// + /// A bucket's capacity is read through a side channel no database sees, so this is where a + /// stateless witness learns which buckets it must prove. The record holds what this EVM + /// executed since it was last cleared, dropped candidates included and lookups that failed + /// left out: it starts empty, block execution empties it when a block starts, and nothing + /// empties it between the transactions of a block, as the per-transaction multiplier cache + /// is. An EVM reused across blocks outside a block executor reports every block it ran since + /// it was last cleared; a node that executes on several EVMs takes the union of their records. + pub fn get_accessed_bucket_ids(&self) -> Vec { + self.ctx().bucket_record().to_vec() + } + + /// Forgets the SALT buckets asked about so far, so the next asks are attributable to one + /// transaction. The record decides nothing, so clearing it changes no execution result. + pub fn clear_accessed_bucket_ids(&mut self) { + self.ctx_mut().clear_bucket_record(); + } + + /// The reads of the Oracle's storage the running (or last) transaction or system call made + /// through the oracle service, in order, each with the service's answer. It is emptied before + /// every transaction and system call; a transaction's outcome carries a copy. + pub fn oracle_reads(&self) -> &[OracleRead] { + self.ctx().oracle_reads().reads() + } } impl MegaEvm @@ -235,30 +290,29 @@ where ExtEnvs: ExternalEnvTypes, { /// Executes `tx`, through the inspector when one is enabled, and returns its outcome: the - /// result and state, the gas by ledger, the usage the common execution layer counted and the - /// limit that stopped the transaction, if any. Nothing is committed. + /// result and state, the gas by ledger, the usage the common execution layer counted, the + /// limit that stopped the transaction, if any, and the reads of the Oracle's storage it made + /// through the oracle service. Nothing is committed. pub fn execute_transaction( &mut self, tx: MegaTransaction, ) -> Result> { let result_and_state = self.run_transaction(tx)?; let layer = &self.inner.ctx.additional_limit; - let gas = MegaGasUsage::new(result_and_state.result.gas(), layer.history_gas_spent()); + let gas = MegaGasUsage::new( + result_and_state.result.gas(), + layer.history_gas_spent(), + layer.history_bytes(), + ); Ok(MegaTransactionOutcome { result_and_state, gas, usage: layer.usage(), - limit_exceeded: layer.latched().copied(), + limit_exceeded: layer.limit_exceeded().copied(), + oracle_reads: self.inner.ctx.oracle_reads().reads().to_vec(), }) } -} -impl MegaEvm -where - DB: Database, - INSP: Inspector, EthInterpreter>, - ExtEnvs: ExternalEnvTypes, -{ /// Runs `tx` through the inspector when one is enabled, without committing. fn run_transaction( &mut self, @@ -289,7 +343,6 @@ impl ExecuteEvm for MegaEvm Result { self.inner.ctx.set_tx(tx); - self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().run(self) } @@ -300,7 +353,6 @@ impl ExecuteEvm for MegaEvm Result, Self::Error> { - self.inner.ctx.on_new_tx(); let result = MegaHandler::<_, Self::Error, _>::new().run(self)?; Ok(ExecResultAndState::new(result, self.finalize())) } @@ -328,7 +380,6 @@ where fn inspect_one_tx(&mut self, tx: Self::Tx) -> Result { self.inner.ctx.set_tx(tx); - self.inner.ctx.on_new_tx(); MegaHandler::<_, Self::Error, _>::new().inspect_run(self) } } @@ -341,6 +392,20 @@ where { } +/// revm's system-call transaction from `caller` to `contract` with `data` +/// ([`SystemCallTx::new_system_tx_with_caller`]), on `gas_limit` instead of revm's +/// [`SYSTEM_CALL_GAS_LIMIT`](revm::handler::SYSTEM_CALL_GAS_LIMIT). +fn system_tx_with_gas_limit( + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, +) -> MegaTransaction { + let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); + tx.0.base.gas_limit = gas_limit; + tx +} + impl SystemCallEvm for MegaEvm { fn system_call_one_with_caller( &mut self, @@ -348,13 +413,47 @@ impl SystemCallEvm for MegaEvm Result { - self.inner.ctx.set_tx(MegaTransaction::new_system_tx_with_caller( + self.run_system_call(MegaTransaction::new_system_tx_with_caller( caller, system_contract_address, data, - )); + )) + } +} + +impl MegaEvm { + /// Runs a system call from `caller` to `contract` with `data` on `gas_limit`, and returns its + /// result and state. Nothing is committed. + /// + /// It is [`transact_system_call`](alloy_evm::Evm::transact_system_call) on the gas limit the + /// caller names instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]. The limit is split as every + /// system call's is: at most [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas and the + /// rest is the call's state-gas reservoir, so a limit above 30,000,000 widens the reservoir + /// and never the regular budget. The block's pre-block calls run through it. + /// + /// [`SYSTEM_CALL_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_GAS_LIMIT + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_REGULAR_GAS_LIMIT + pub fn transact_system_call_with_gas_limit( + &mut self, + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, + ) -> Result, EVMError> { + let tx = system_tx_with_gas_limit(caller, contract, data, gas_limit); + let result = self.run_system_call(tx).map_err(map_op_err)?; + Ok(ResultAndState::new(result, ExecuteEvm::finalize(self))) + } + + /// Runs `tx` as a system call: the protocol's own work, prepared as such (see + /// [`MegaContext`]'s system-call preparation) and run through the handler's system-call path. + fn run_system_call( + &mut self, + tx: MegaTransaction, + ) -> Result, MegaEvmError> { + self.inner.ctx.set_tx(tx); self.inner.ctx.on_new_system_call(); - MegaHandler::<_, Self::Error, _>::new().run_system_call(self) + MegaHandler::<_, MegaEvmError, _>::new().run_system_call(self) } } @@ -452,8 +551,9 @@ mod tests { use alloy_op_evm::OpTx; use alloy_primitives::{address, TxKind, U256}; use revm::{ - context::{result::InvalidTransaction, ContextSetters, TxEnv}, + context::{result::InvalidTransaction, ContextSetters, Transaction, TxEnv}, database::State, + handler::{SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT}, DatabaseRef, }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; @@ -465,12 +565,62 @@ mod tests { MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()) } + /// Replacing the whole precompile set installs the set it is given, and gas detention prices + /// nothing from the Satin table after it: the fixture fork's set is not the Satin one. + #[test] + fn test_a_replaced_precompile_set_is_dispatched_and_not_priced() { + use revm::{handler::PrecompileProvider, precompile::Precompiles}; + type Ctx = MegaContext; + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let kzg = crate::kzg_point_evaluation::ADDRESS; + let price = |evm: &MegaEvm| { + evm.priced_precompiles.price(&evm.inner.precompiles, &kzg, &[]) + }; + assert_eq!(price(&evm), Some(crate::kzg_point_evaluation::GAS_COST)); + + let osaka = crate::test_utils::neutral_precompiles(crate::EthSpecId::OSAKA).unwrap(); + evm.replace_precompile_set(osaka); + let dispatched = PrecompileProvider::::warm_addresses(&evm.inner.precompiles); + assert!(core::ptr::eq(dispatched, Precompiles::osaka().addresses_set()), "Osaka's set"); + assert_eq!(price(&evm), None); + } + + /// A whole set put in the map's place through the mutable reference `EvmTr::all_mut` hands + /// out is not seen: an address whose dispatched entry carries the id of the Satin table's + /// entry there is still priced from the Satin table, whatever the new set charges for it. + #[test] + fn test_a_set_replaced_through_a_mutable_reference_is_priced_where_its_ids_match() { + use revm::{ + handler::{EvmTr, PrecompileProvider}, + precompile::Precompiles, + }; + type Ctx = MegaContext; + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let kzg = crate::kzg_point_evaluation::ADDRESS; + + let osaka = crate::test_utils::neutral_precompiles(crate::EthSpecId::OSAKA).unwrap(); + *EvmTr::all_mut(&mut evm).2 = osaka; + let dispatched = PrecompileProvider::::warm_addresses(&evm.inner.precompiles); + assert!(core::ptr::eq(dispatched, Precompiles::osaka().addresses_set()), "Osaka's set"); + let osaka_kzg = Precompiles::osaka().get(&kzg).unwrap(); + assert_ne!(osaka_kzg.required_gas(&[]), Some(crate::kzg_point_evaluation::GAS_COST)); + + let price = evm.priced_precompiles.price(&evm.inner.precompiles, &kzg, &[]); + assert_eq!(price, Some(crate::kzg_point_evaluation::GAS_COST), "the Satin table's price"); + } + /// A call to `CALLEE`, with room for the state gas a value transfer to it draws: `CALLEE` - /// holds nothing, so a transfer creates it and pays the new account's state gas. + /// holds nothing, so a transfer creates it and pays the new account's state gas. The room is + /// counted at the byte prices in effect, with the history of the body and of the recipient's + /// write record on top of 100,000 of regular gas. fn tx(value: U256) -> MegaTransaction { + use revm::context_interface::cfg::GasId; + let gas_limit = 100_000 + + crate::satin_gas_params().get(GasId::new_account_state_gas()) + + crate::history_gas(crate::TX_BODY_SIZE + crate::WRITE_RECORD_SIZE).unwrap(); OpTx(op_transaction(TxEnv { caller: CALLER, - gas_limit: 300_000, + gas_limit, kind: TxKind::Call(CALLEE), value, ..Default::default() @@ -571,6 +721,68 @@ mod tests { assert_eq!(evm.inspector().traces().nodes()[0].trace.address, Address::ZERO); } + /// A system call from any caller runs through revm's system-call entry point. + #[test] + fn test_revm_system_call_with_caller_works() { + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + let result = + SystemCallEvm::system_call_one_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) + .unwrap(); + assert!(result.is_success()); + assert_eq!(evm.ctx().tx().caller(), CALLER); + assert_eq!(evm.ctx().tx().kind(), TxKind::Call(CALLEE)); + } + + /// The gas limit a caller names is the system call's: the part above 30M is its reservoir, + /// and a limit below 30M is regular gas alone. + #[test] + fn test_transact_system_call_with_gas_limit_uses_passed_value() { + let mut db = funded_db(); + let mut evm = MegaEvm::new(context(&mut db)); + + let result = evm + .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().tx().gas_limit(), 123_456_789); + assert_eq!( + result.result.gas().reservoir_remaining(), + 123_456_789 - SYSTEM_CALL_REGULAR_GAS_LIMIT, + "an empty callee draws nothing from the reservoir", + ); + + let result = evm + .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 1_000_000) + .unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().tx().gas_limit(), 1_000_000); + assert_eq!(result.result.gas().reservoir_remaining(), 0); + } + + /// The default system-call entry point runs on revm's system-call gas limit whatever the + /// block's gas limit is: its regular budget is the base 30M, and the margin above it is the + /// reservoir. Only an explicit gas limit moves either. + #[test] + fn test_default_system_call_keeps_the_30m_regular_budget() { + let mut db = funded_db(); + let mut evm = MegaEvm::new( + context(&mut db).with_block(BlockEnv { gas_limit: 100_000_000, ..Default::default() }), + ); + + let result = + SystemCallEvm::system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()).unwrap(); + assert!(result.result.is_success()); + // The literals, not revm's constants: this pins what revm's default is. + assert_eq!(evm.ctx().tx().gas_limit(), 31_566_720); + assert_eq!(SYSTEM_CALL_GAS_LIMIT, 31_566_720); + assert_eq!( + result.result.gas().reservoir_remaining(), + 31_566_720 - 30_000_000, + "30M of it is regular gas", + ); + } + #[test] fn test_execute_transaction_fails_with_insufficient_balance() { let mut db = MemoryDatabase::default().account_code(CALLEE, Bytes::new()); diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 712f504e2..1ebe4fddb 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -8,13 +8,48 @@ //! The set is handed to the EVM as an alloy-evm [`PrecompilesMap`], so a node can add or replace //! an address at runtime ([`DynPrecompilesBuilder`]). A map built from the static set looks the //! address up in the same table op-revm would, so carrying it costs no allocation per call. +//! +//! # Prices +//! +//! Gas detention needs a precompile call's price before the call runs, to tell a call its +//! allowance can pay from one that crosses the limit ([`PricedPrecompiles::price`]). A price +//! belongs to the precompile that runs: every entry revm defines carries one +//! ([`Precompile::required_gas`](revm::precompile::Precompile::required_gas)), and so does the +//! KZG entry here. So does every one of op-revm's size-limited wrappers — here the BN254 pairing +//! and the BLS12-381 G1 MSM, G2 MSM and pairing — which prices an input within its size limit as +//! the run it wraps does, and one past it at nothing, since it refuses that input before any gas +//! check. Every entry of the table is priced. +//! +//! The map erases what it holds once a node changes it, so the engine prices from its own table, +//! [`satin_precompiles`], and only an address whose dispatched entry is still the table's. These +//! calls are not priced, and gas detention runs them on the allowance: +//! +//! - a call to a node's own precompile, at a new address; +//! - a call to an address a node replaced: through +//! [`MegaEvm::with_dyn_precompiles`](crate::MegaEvm), which records it, or through the map's own +//! API with an entry of another id; +//! - every call, once the whole set was replaced by one that is not the Satin set: the neutral +//! configuration's, the fixture fork's own. +//! +//! A node changes the set through `with_dyn_precompiles`, or the factory's builder, which calls +//! it. The engine cannot see a change made around it, through the mutable reference to the map +//! that revm's `EvmTr::all_mut` and alloy-evm's `Evm::components_mut` hand out: +//! +//! - an entry replaced through the map's mutable accessors under the id of the entry it replaces; +//! - the whole map replaced by another set: an address whose dispatched entry carries the id of the +//! Satin table's entry there is then priced from the Satin table, whatever the other set charges +//! for it. +//! +//! Neither accessor is a sign of a change: revm reaches the context and the frame stack through +//! `all_mut` on every frame, and alloy-evm's transaction tracer calls `components_mut`, so a +//! trace would stop pricing where block execution priced. #[cfg(not(feature = "std"))] use alloc as std; use std::{string::String, sync::Arc}; use alloy_evm::{ - precompiles::{DynPrecompile, PrecompilesMap}, + precompiles::{DynPrecompile, Precompile as _, PrecompilesMap}, Database, }; use revm::{ @@ -41,10 +76,68 @@ pub fn satin_precompiles_map() -> PrecompilesMap { PrecompilesMap::from_static(satin_precompiles()) } +/// Which precompile calls gas detention may price from the Satin table: what the engine knows of +/// the changes made to the set it dispatches from. +#[derive(Clone, Debug, Default)] +pub(crate) struct PricedPrecompiles { + /// The Satin addresses a node replaced with a precompile of its own + /// ([`MegaEvm::with_dyn_precompiles`](crate::MegaEvm)). + replaced: AddressSet, + /// Whether the whole set was replaced, through the engine, by one that is not the Satin set: + /// the neutral configuration's, the fixture fork's own. A set replaced through a mutable + /// reference to the map is not recorded. + foreign: bool, +} + +impl PricedPrecompiles { + /// Records that a node installed a precompile of its own at `address`. An address outside the + /// Satin set replaces nothing the table prices. + pub(crate) fn record_replaced(&mut self, address: Address) { + if satin_precompiles().contains(&address) { + self.replaced.insert(address); + } + } + + /// Records that the whole set was replaced by one that is not the Satin set: nothing is + /// priced from the Satin table from then on. + #[cfg(any(test, feature = "test-utils"))] + pub(crate) const fn record_foreign(&mut self) { + self.foreign = true; + } + + /// The gas a call of `input` to the precompile `dispatched` runs at `address` needs, read + /// before the call runs, or `None` when the engine cannot price it. + /// + /// The price is the Satin table's, and only for an address whose dispatched entry is still + /// the table's: the set is the Satin one, no node replaced the address through the engine + /// ([`record_replaced`](Self::record_replaced)), and the entry carries the table entry's id, + /// so a replacement made through the map's own API under another id is not priced either. + /// Every entry of the table carries a price function; one built without it would answer + /// `None`. + pub(crate) fn price( + &self, + dispatched: &PrecompilesMap, + address: &Address, + input: &[u8], + ) -> Option { + if self.foreign || self.replaced.contains(address) { + return None; + } + let builtin = satin_precompiles().get(address)?; + if dispatched.get(address)?.precompile_id() != builtin.id() { + return None; + } + builtin.required_gas(input) + } +} + /// Builds the dynamic precompiles an EVM runs on top of the Satin set. /// /// The spec is passed so a builder can key on it; Satin is a single spec, so it is always /// [`MegaSpecId::SATIN`] today. +/// +/// Logs a precompile added here writes itself are not counted in the data size, which counts a +/// log where a `LOG` opcode completes. pub type DynPrecompilesBuilder = Arc HashMap + Send + Sync>; @@ -78,9 +171,18 @@ pub mod kzg_point_evaluation { }) } + /// The price of a KZG point evaluation, read before it runs: [`GAS_COST`] for every input. + /// A call below it is out of gas, and one at or above it gives the same result on every gas + /// limit, a malformed input's failure included, since upstream's checks all come after the + /// gas check. + const fn required_gas(_input: &[u8]) -> u64 { + GAS_COST + } + /// KZG point evaluation, priced at [`GAS_COST`]. pub const KZG_POINT_EVALUATION: Precompile = - Precompile::new(PrecompileId::KzgPointEvaluation, ADDRESS, run_with_fixed_cost); + Precompile::new(PrecompileId::KzgPointEvaluation, ADDRESS, run_with_fixed_cost) + .with_required_gas(required_gas); } /// Runs the Satin precompile set on a [`MegaContext`]. @@ -127,7 +229,7 @@ mod tests { use op_revm::precompiles::bn254_pair::KARST_MAX_INPUT_SIZE; use revm::{ interpreter::{CallInput, CallScheme, CallValue, InstructionResult}, - precompile::secp256r1, + precompile::{secp256r1, PrecompileId, PrecompileOutput}, primitives::U256, }; @@ -290,20 +392,207 @@ mod tests { assert!(result.output.is_empty(), "the signature does not verify"); } - /// The BN254 pairing takes input up to the Karst bound and refuses one byte more, without - /// charging for the work it did not do. + /// The BN254 pairing takes input up to the Karst bound, 57,600 bytes or 300 pairs of 192, and + /// refuses a whole pair more. + /// + /// Both inputs are whole pairs of zeros, which pair to the identity, so the run itself accepts + /// either: the 301st pair is refused by the bound alone. One stray byte past the bound would + /// prove nothing, since a length that is not a whole number of pairs fails whatever the bound. + /// + /// Rule [S2.4]. Expected values `independent`: 57,600 bytes and 300 × 192 by hand, and the + /// EIP-1108 price of 300 pairs, 45,000 + 300 × 34,000. #[test] fn test_bn254_pairing_is_bounded_at_the_karst_size() { assert_eq!(KARST_MAX_INPUT_SIZE, 57_600); let address = *op_revm::precompiles::bn254_pair::KARST.address(); - // At the bound the input is a whole number of pair elements of zeros, which pair to the - // identity: the call succeeds and pays the Istanbul pairing price. - let at_bound = run(address, Bytes::from(std::vec![0u8; KARST_MAX_INPUT_SIZE]), 50_000_000); + let pairs = |n: usize| Bytes::from(std::vec![0u8; n * 192]); + let at_bound = run(address, pairs(300), 50_000_000); assert_eq!(at_bound.result, InstructionResult::Return); - assert!(at_bound.gas.total_gas_spent() > 0); + assert_eq!(at_bound.gas.total_gas_spent(), 45_000 + 300 * 34_000); + + let over = run(address, pairs(301), 50_000_000); + assert_eq!(over.result, InstructionResult::PrecompileError, "a whole pair past the bound"); + } - let over = run(address, Bytes::from(std::vec![0u8; KARST_MAX_INPUT_SIZE + 1]), 50_000_000); - assert_eq!(over.result, InstructionResult::PrecompileError); + /// Every entry of the Satin set carries a price, op-revm's size-limited wrappers of the BN254 + /// pairing and the BLS12-381 G1 MSM, G2 MSM and pairing included, so gas detention decides a + /// call to any of them from its price. + /// + /// Whether an entry has a price is the entry's, not the input's: `required_gas` answers `Some` + /// exactly when the entry carries a price function, and that function answers a number for + /// any input. So the empty input decides the cell, and the inputs beyond it — every length a + /// precompile here reads in words or pairs, around those boundaries, of zeros and of `0xff` + /// bytes, up to past the BN254 pairing's size limit — check that each price function answers + /// them rather than failing on one. + /// + /// Rule [S12.47]. Expected values `independent`: a price is present, whatever the input. + #[test] + fn test_every_satin_entry_is_priced() { + let lengths = + [0, 1, 31, 32, 33, 64, 96, 128, 160, 192, 193, 256, 288, 384, 1_024, 57_600, 57_601]; + for precompile in satin_precompiles().inner().values() { + for len in lengths { + for byte in [0x00, 0xff] { + let input = std::vec![byte; len]; + assert!( + precompile.required_gas(&input).is_some(), + "{:?} is priced at {len} bytes of {byte:#04x}", + precompile.id() + ); + } + } + } + } + + /// op-revm's size-limited entries of the Satin set are priced by their EIPs up to their size + /// limits, and at nothing past them, where the wrapper refuses the input before any gas check: + /// + /// - the BN254 pairing (EIP-1108): 45,000, and 34,000 per whole 192-byte pair, a stray byte + /// included, since the run checks the length after its gas; + /// - the BLS12-381 G1 and G2 MSMs (EIP-2537): 12,000 and 22,500 per pair of 160 and 288 bytes, + /// discounted by the EIP's tables — per mille, 1,000 and 949 for one and two G1 pairs, 1,000 + /// for one and two G2 pairs, and from 128 pairs on 519 and 524 — and nothing for a length + /// that is not a positive multiple of a pair, which the run refuses before its gas check; + /// - the BLS12-381 pairing (EIP-2537): 37,700, and 32,600 per 384-byte pair, and nothing for a + /// length that is not a positive multiple of a pair. + #[test] + fn test_the_size_limited_entries_are_priced_by_their_eips() { + use op_revm::precompiles::{bls12_381, bn254_pair}; + let price = |precompile: &revm::precompile::Precompile, len: usize| { + let entry = satin_precompiles().get(precompile.address()).unwrap(); + assert_eq!(entry.id(), precompile.id(), "the Satin set dispatches the wrapper"); + entry.required_gas(&std::vec![0; len]).unwrap() + }; + + // The BN254 pairing: its 57,600 bytes are 300 pairs. + let pairing = &bn254_pair::KARST; + assert_eq!(bn254_pair::KARST_MAX_INPUT_SIZE, 300 * 192); + for pairs in [0, 1, 2, 300] { + let at = 45_000 + 34_000 * pairs as u64; + assert_eq!(price(pairing, pairs * 192), at, "{pairs} pairs"); + if pairs < 300 { + assert_eq!(price(pairing, pairs * 192 + 1), at, "{pairs} pairs and a byte"); + } + } + for len in [300 * 192 + 1, 301 * 192] { + assert_eq!(price(pairing, len), 0, "{len} bytes: past the limit"); + } + + // The MSMs: the G1 limit is 1,806 pairs, the G2 limit 968. + assert_eq!(bls12_381::JOVIAN_G1_MSM_MAX_INPUT_SIZE, 1_806 * 160); + assert_eq!(bls12_381::JOVIAN_G2_MSM_MAX_INPUT_SIZE, 968 * 288); + let msms = [ + (&bls12_381::JOVIAN_G1_MSM, 160, 12_000, [1_000, 949, 519], 1_806), + (&bls12_381::JOVIAN_G2_MSM, 288, 22_500, [1_000, 1_000, 524], 968), + ]; + for (msm, pair, base, [one, two, most], limit) in msms { + let id = msm.id(); + for (pairs, discount) in [(1, one), (2, two), (128, most), (129, most), (limit, most)] { + let at = pairs as u64 * base * discount / 1_000; + assert_eq!(price(msm, pairs * pair), at, "{id:?}: {pairs} pairs"); + } + for len in [0, pair - 1, pair + 1, limit * pair + 1, (limit + 1) * pair] { + assert_eq!(price(msm, len), 0, "{id:?}: {len} bytes"); + } + } + + // The BLS12-381 pairing: its 156,672 bytes are 408 pairs. + let pairing = &bls12_381::JOVIAN_PAIRING; + assert_eq!(bls12_381::JOVIAN_PAIRING_MAX_INPUT_SIZE, 408 * 384); + for pairs in [1, 2, 408] { + assert_eq!(price(pairing, pairs * 384), 37_700 + 32_600 * pairs as u64, "{pairs}"); + } + for len in [0, 383, 385, 408 * 384 + 1, 409 * 384] { + assert_eq!(price(pairing, len), 0, "{len} bytes"); + } + } + + /// The KZG entry's price is its run's: below [`GAS_COST`](kzg_point_evaluation::GAS_COST) the + /// run is out of gas, and from it on the run gives one result that uses exactly the price, a + /// valid proof, a malformed input and an empty one alike. + #[test] + fn test_the_kzg_price_is_its_runs() { + let kzg = &kzg_point_evaluation::KZG_POINT_EVALUATION; + let mut wrong_proof = kzg_input().to_vec(); + wrong_proof[191] ^= 1; + for input in + [kzg_input(), Bytes::from(wrong_proof), Bytes::from_static(&[1; 100]), Bytes::new()] + { + let price = kzg.required_gas(&input); + assert_eq!(price, Some(kzg_point_evaluation::GAS_COST)); + let price = kzg_point_evaluation::GAS_COST; + for gas_limit in [0, price / 2, price - 1] { + let result = run(kzg_point_evaluation::ADDRESS, input.clone(), gas_limit); + assert_eq!(result.result, InstructionResult::PrecompileOOG, "{gas_limit}"); + } + let at_price = run(kzg_point_evaluation::ADDRESS, input.clone(), price); + assert_ne!(at_price.result, InstructionResult::PrecompileOOG); + for gas_limit in [price + 1, 2 * price + 7, 30_000_000] { + let result = run(kzg_point_evaluation::ADDRESS, input.clone(), gas_limit); + assert_eq!(result.result, at_price.result, "{gas_limit}"); + assert_eq!(result.output, at_price.output, "{gas_limit}"); + if result.result.is_ok_or_revert() { + assert_eq!(result.gas.total_gas_spent(), price, "{gas_limit}"); + } + } + } + } + + /// A Satin address is priced from the Satin table only while the entry the map dispatches + /// there is still the table's: one a node replaced through the engine is not, whatever id its + /// precompile carries, nor is one replaced through the map's own API under another id. An + /// address outside the table is never priced; op-revm's wrapper of the BN254 pairing is, from + /// its own entry. + #[test] + fn test_a_replaced_address_is_not_priced_from_the_satin_table() { + let modexp = *revm::precompile::modexp::OSAKA.address(); + let input = [0_u8; 96]; + let own = |id: PrecompileId| { + DynPrecompile::new(id, |input| { + Ok(PrecompileOutput::new(1, Bytes::new(), input.reservoir)) + }) + }; + let untouched = satin_precompiles_map(); + let none = PricedPrecompiles::default(); + assert_eq!(none.price(&untouched, &modexp, &input), Some(500), "the Osaka minimum"); + assert_eq!( + none.price(&untouched, &kzg_point_evaluation::ADDRESS, &input), + Some(kzg_point_evaluation::GAS_COST) + ); + + // Replaced through the engine, even under the built-in's own id. + let mut replaced = PricedPrecompiles::default(); + replaced.record_replaced(modexp); + let mut map = satin_precompiles_map(); + map.apply_precompile(&modexp, |_| Some(own(PrecompileId::ModExp))); + assert_eq!(replaced.price(&map, &modexp, &input), None); + assert_eq!( + replaced.price(&map, &kzg_point_evaluation::ADDRESS, &input), + Some(kzg_point_evaluation::GAS_COST), + "the other addresses are still the table's" + ); + + // Replaced through the map's own API, under another id. + let mut map = satin_precompiles_map(); + map.apply_precompile(&kzg_point_evaluation::ADDRESS, |_| { + Some(own(PrecompileId::Custom("own".into()))) + }); + assert_eq!(none.price(&map, &kzg_point_evaluation::ADDRESS, &input), None); + assert_eq!(none.price(&map, &modexp, &input), Some(500)); + + // A node's own address, and an address outside the table recorded as replaced. + let own_address = Address::repeat_byte(0xd1); + let mut map = satin_precompiles_map(); + map.apply_precompile(&own_address, |_| Some(own(PrecompileId::Custom("own".into())))); + let mut recorded = PricedPrecompiles::default(); + recorded.record_replaced(own_address); + assert_eq!(recorded.price(&map, &own_address, &input), None); + assert_eq!(recorded.price(&map, &modexp, &input), Some(500)); + + // op-revm's wrapper of the BN254 pairing: one pair, 45,000 and 34,000 per pair (EIP-1108). + let pairing = *op_revm::precompiles::bn254_pair::KARST.address(); + assert!(untouched.get(&pairing).is_some()); + assert_eq!(none.price(&untouched, &pairing, &[0; 192]), Some(45_000 + 34_000)); } /// A `ModExp` header of `base_len`, `exp_len` and `mod_len`, followed by the operands. diff --git a/crates/mega-evm/src/evm/prices.rs b/crates/mega-evm/src/evm/prices.rs index eff2c8ce1..a360f9dae 100644 --- a/crates/mega-evm/src/evm/prices.rs +++ b/crates/mega-evm/src/evm/prices.rs @@ -2,7 +2,8 @@ //! at prices other than the constants. //! //! Every Satin schedule entry that depends on a byte price reads it through -//! [`active_satin_prices`]: today the EIP-8037 state-gas entries, later the history entries. +//! [`active_satin_prices`]: the EIP-8037 state-gas entries and the history price of deposited +//! code. The history charges the engine makes itself read the same prices. //! //! Without the `satin-price-override` feature [`active_satin_prices`] is a constant, so a build //! that does not opt in prices with [`COST_PER_STATE_BYTE`] and [`COST_PER_HISTORY_BYTE`] and has @@ -153,9 +154,6 @@ impl FromStr for BytePrice { } /// The cost per state byte and the cost per history byte the Satin gas table is built from. -/// -/// `cphb` is carried and installable, but prices no schedule entry yet: history gas lands as its -/// own mechanism, and until then the schedule's history entry stays zero. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct SatinPrices { /// Cost per state byte: what one byte added to the world state costs. @@ -277,25 +275,17 @@ pub fn active_satin_prices() -> SatinPrices { /// number in the schedule. A test that asserts one of those numbers returns early instead of /// failing on a price the developer asked for. /// -/// The notice goes straight to stderr and only once: the harness captures the print macros of a -/// test that passes, so a message written with them would never be read. +/// Each test that returns early leaves a note (`note_price_guard`), which the byte-price +/// grid counts. #[cfg(test)] pub(crate) fn runs_at_measurement_prices() -> bool { if active_satin_prices().is_constants() { return false; } #[cfg(feature = "satin-price-override")] - { - use std::io::Write; - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the tests that assert the spec's byte prices, because \ - {CPSB_ENV_VAR} or {CPHB_ENV_VAR} fixed other ones; unset them to run those tests" - ); - }); - } + crate::test_utils::note_price_guard(&format!( + "{CPSB_ENV_VAR} or {CPHB_ENV_VAR} fixed prices other than the spec's" + )); true } @@ -427,8 +417,8 @@ mod tests { let stderr = String::from_utf8_lossy(&run.stderr); assert!(run.status.success(), "the probe failed:\n{stdout}\n{stderr}"); assert!( - stdout.contains("sstore_set_state_gas = 20000"), - "the probe must report the repriced entry; a run that selected no test reports \ + stdout.contains("sstore_set_state_gas = 20000, code_deposit_history_gas = 400"), + "the probe must report the repriced entries; a run that selected no test reports \ nothing:\n{stdout}" ); } @@ -441,12 +431,17 @@ mod tests { fn test_the_environment_prices_build_the_schedule() { use revm::context_interface::cfg::GasId; - let state_gas = crate::satin_gas_params().get(GasId::sstore_set_state_gas()); - std::println!("sstore_set_state_gas = {state_gas}"); + let params = crate::satin_gas_params(); + let state_gas = params.get(GasId::sstore_set_state_gas()); + let history_gas = params.get(GasId::code_deposit_history_gas()); + std::println!( + "sstore_set_state_gas = {state_gas}, code_deposit_history_gas = {history_gas}" + ); assert_eq!(active_satin_prices().cpsb, "312.5".parse().unwrap(), "the state byte price"); assert_eq!(active_satin_prices().cphb, BytePrice::from_gas(400), "the history byte price"); assert_eq!(state_gas, 20_000, "a slot's 64 bytes at 312.5 gas each"); + assert_eq!(history_gas, 400, "one byte of deposited code at 400 gas"); } #[test] diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index 7e75c41b4..b3873f90d 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -12,10 +12,25 @@ //! so it is not compute. The ledgers are raw spend, before the refund; the receipt reports //! [`gas_used`](MegaGasUsage::gas_used), which is their sum less the refund, at least the EIP-7623 //! floor. +//! +//! Beside the history ledger's gas sits the byte count it stands for, +//! [`history_bytes`](MegaGasUsage::history_bytes). The two are not a price apart: the history +//! allowance of a value transfer pays for its callee's first event before the callee's gas does, +//! and what it pays for is on no gas ledger. The byte count is what the transaction appended; the +//! gas is what its own gas paid for. +//! +//! The byte count is the history the schedule prices, not the chain's physical growth: a +//! transaction exempt from history gas reports none of the bytes it carries, a body counts its +//! five fixed write records even when fewer fee accounts are written, and the EIP-7708 transfer +//! logs of its value movements, which nothing prices, are not in it. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; use revm::context::result::{ResultAndState, ResultGas}; -use crate::{LimitCheck, LimitUsage, MegaHaltReason}; +use crate::{LimitCheck, LimitStop, LimitUsage, MegaHaltReason, OracleRead}; /// What executing one transaction produced: revm's result and state, and what `MegaETH` counts /// beside them. @@ -30,10 +45,25 @@ pub struct MegaTransactionOutcome { /// The data-size bytes and write records the transaction kept. The KV count a node reports /// is [`LimitUsage::write_records`]. pub usage: LimitUsage, - /// The transaction-level limit that stopped the transaction, if one did. The result is then a - /// revert whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the - /// output, tells a limit stop from a contract reverting with the same bytes. + /// The crossing that produced the result of the transaction's own frame, if one did: a + /// transaction-level limit, or that frame's own data-size budget. The result is then a revert + /// whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the output, + /// tells a limit stop from a contract reverting with the same bytes, or re-raising those a + /// frame below it was stopped with. pub limit_exceeded: Option, + /// The reads of the Oracle's storage the transaction made through the oracle service, in + /// order, each with the service's answer. The answers are in no database: a node building a + /// stateless witness takes them from the transactions it includes, and a validator given them + /// answers each read as the building node's service did. + pub oracle_reads: Vec, +} + +impl MegaTransactionOutcome { + /// The limit that stopped the transaction, if one did, read off the result and + /// [`limit_exceeded`](Self::limit_exceeded) together ([`LimitStop::from_result`]). + pub fn limit_stop(&self) -> Option { + LimitStop::from_result(&self.result, self.limit_exceeded.as_ref()) + } } impl core::ops::Deref for MegaTransactionOutcome { @@ -54,7 +84,7 @@ impl core::ops::DerefMut for MegaTransactionOutcome { /// /// `regular + state + history` is the transaction's raw spend, /// [`ResultGas::total_gas_spent`]; [`gas_used`](Self::gas_used) is -/// [`ResultGas::tx_gas_used`]. +/// [`ResultGas::tx_gas_used`]. [`history_bytes`](Self::history_bytes) is a byte count, not gas. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct MegaGasUsage { /// Regular gas spent: everything that is neither state nor history gas, before the refund. @@ -63,6 +93,20 @@ pub struct MegaGasUsage { pub state: u64, /// History gas spent, net of refills. pub history: u64, + /// The bytes the transaction appended to history, whoever paid for them: its body, one write + /// record per account or storage write it kept, the logs it emitted and kept and the code it + /// deposited. The EIP-7708 transfer logs revm emits for its value movements are not among + /// them: nothing prices them. + /// + /// At the cost per history byte they are worth [`history`](Self::history) plus what the + /// history allowances of its value transfers paid, which no gas ledger carries. + /// + /// They are the history bytes the schedule prices, not the chain's physical growth: a + /// transaction exempt from history gas (a deposit, a transaction the protocol sent, a system + /// call) reports none, and the body counts its five fixed write records — the sender's + /// account and the four accounts fees are credited to — even when fewer fee accounts are + /// written. + pub history_bytes: u64, /// The EIP-8037 reservoir left unspent, which the sender gets back. pub reservoir_remaining: u64, /// The EIP-7623 floor the receipt's gas used cannot fall below. @@ -72,17 +116,18 @@ pub struct MegaGasUsage { } impl MegaGasUsage { - /// The ledgers of a transaction that settled into `result_gas` and spent `history` gas on - /// history. + /// The ledgers of a transaction that settled into `result_gas`, spent `history` gas on + /// history and appended `history_bytes` bytes of it. /// /// [`ResultGas`] has no history field; its total includes history gas, which is taken back /// out of regular here. - pub const fn new(result_gas: &ResultGas, history: u64) -> Self { + pub const fn new(result_gas: &ResultGas, history: u64, history_bytes: u64) -> Self { let state = result_gas.state_gas_spent_final(); Self { regular: result_gas.total_gas_spent().saturating_sub(state).saturating_sub(history), state, history, + history_bytes, reservoir_remaining: result_gas.reservoir_remaining(), floor: result_gas.floor_gas(), gas_used: result_gas.tx_gas_used(), @@ -100,9 +145,13 @@ impl MegaGasUsage { mod tests { use super::*; use crate::{LimitCheck, LimitKind, MegaHaltReason, MegaLimitExceeded}; + use alloy_primitives::{Address, Bytes}; use alloy_sol_types::SolError; use op_revm::OpHaltReason; - use revm::context::result::{HaltReason as EthHaltReason, OutOfGasError}; + use revm::{ + context::result::{ExecutionResult, HaltReason as EthHaltReason, OutOfGasError}, + state::{Account, EvmState}, + }; fn result_gas(total: u64, state: u64, refunded: u64, floor: u64) -> ResultGas { ResultGas::default() @@ -116,10 +165,11 @@ mod tests { /// The three ledgers add up to the raw spend; the receipt figure is the spend less the refund. #[test] fn test_ledgers_split_the_raw_spend() { - let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000); + let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000, 125); assert_eq!(gas.regular, 60_000); assert_eq!(gas.state, 30_000); assert_eq!(gas.history, 10_000); + assert_eq!(gas.history_bytes, 125, "a byte count, carried as it was given"); assert_eq!(gas.regular + gas.state + gas.history, 100_000); assert_eq!(gas.reservoir_remaining, 5_000); assert_eq!(gas.gas_used, 96_000); @@ -129,7 +179,7 @@ mod tests { /// The floor binds the receipt figure and the block's execution gas, not the ledgers. #[test] fn test_floor_binds_receipt_and_block_execution_gas() { - let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000); + let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000, 0); assert_eq!(gas.regular, 25_000); assert_eq!(gas.floor, 45_000); assert_eq!(gas.gas_used, 45_000); @@ -149,12 +199,7 @@ mod tests { /// dimension. #[test] fn test_limit_stops_are_reverts_with_mega_limit_exceeded() { - for kind in [ - LimitKind::DataSize, - LimitKind::KVUpdate, - LimitKind::ComputeGas, - LimitKind::StateGrowth, - ] { + for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { let stop = LimitCheck::ExceedsLimit { kind, limit: 100, used: 101, frame_local: false }; let decoded = MegaLimitExceeded::abi_decode(&stop.revert_data()).unwrap(); assert_eq!(LimitKind::from_u8(decoded.kind), Some(kind)); @@ -162,6 +207,27 @@ mod tests { } } + /// An outcome reads and writes through to the result and the state it carries. + #[test] + fn test_an_outcome_derefs_to_its_result_and_state() { + let result = ExecutionResult::Revert { + gas: result_gas(21_000, 0, 0, 0), + logs: Vec::new(), + output: Bytes::new(), + }; + let mut outcome = MegaTransactionOutcome { + result_and_state: ResultAndState::new(result, EvmState::default()), + gas: MegaGasUsage::default(), + usage: LimitUsage::ZERO, + limit_exceeded: None, + oracle_reads: Vec::new(), + }; + assert!(!outcome.result.is_success()); + + outcome.state.insert(Address::ZERO, Account::default()); + assert!(outcome.result_and_state.state.contains_key(&Address::ZERO)); + } + /// The one halt reason op-revm adds, a failed deposit, has no Ethereum counterpart. #[test] fn test_op_specific_halt_reason_does_not_convert_to_eth() { diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 85edbf934..793908eac 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -1,80 +1,44 @@ //! The Satin gas schedule. //! -//! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, the EIP-2780 -//! intrinsic decomposition, the EIP-7976 calldata floor and EIP-7981 access-list data — and -//! changes exactly two things: +//! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, EIP-8038's +//! state-access prices, the EIP-2780 intrinsic decomposition, the EIP-7976 calldata floor and +//! EIP-7981 access-list data — and changes exactly two things: //! -//! 1. every regular-gas entry the Amsterdam table changed for EIP-8037 or EIP-8038 goes back to its -//! Osaka value ([`EIP8038_REPRICED`]) — every one but the state-gas, EIP-2780, floor and -//! EIP-7702 entries, which stay Amsterdam's; -//! 2. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte +//! 1. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than -//! Glamsterdam's. +//! Glamsterdam's; +//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), the one entry outside +//! Amsterdam's table: upstream leaves it at zero, and Satin gives it the cost of one history +//! byte, which is what makes a deployment pay for the bytes every node has to carry. //! -//! The first group includes the four entries EIP-8037 moved onto the state dimension, so at these -//! prices state creation is charged on both dimensions: a value `CALL` that creates its recipient -//! pays 25,000 regular and 183,600 state, a `CREATE` opcode 32,000 and 183,600, a slot's first -//! write 22,100 and 97,920, where the Amsterdam schedule charges 0, 12,000 and 12,100 regular -//! against the same state charge. Whether creation keeps its Osaka regular price is an open -//! pricing question; the schedule states the prices, it does not settle them. +//! Every regular-gas entry is Amsterdam's, so state creation is split between the two dimensions +//! as Amsterdam splits it: the regular part is the access and write work EIP-8038 prices, and the +//! new state itself is state gas alone. A value `CALL` that creates its recipient pays the 11,300 +//! of its value transfer, which carries the account write, and no new-account regular gas; a +//! `CREATE` opcode pays 12,000; a slot's first write 10,000 above its load; against 183,600, +//! 183,600 and 97,920 of state gas at the minimum bucket. +//! +//! The static price every opcode pays before its dynamic cost is not in the schedule: revm keeps it +//! in the instruction table, keyed on the spec. Satin's is Amsterdam's too ([`satin_gas_table`]), +//! which differs from its Osaka base's in EIP-8038's two-read base for `EXTCODESIZE` and +//! `EXTCODECOPY` alone. //! //! The state-gas entries are the price at the *minimum* SALT bucket. A charge is scaled from //! there by the capacity of the bucket it lands in, which the pricing hook does //! (`Host::state_gas_price`); the schedule holds the number that scaling starts from. //! -//! Every other entry is Amsterdam's, including the EIP-2780 decomposition entries -//! (`tx_account_write_cost`, `tx_create_access_cost`), the zero `code_deposit_cost` and the floor. -//! The history entry stays at zero: history gas is its own mechanism and switches it on. -//! //! The schedule is built once for the process and handed to every configuration as a shared //! clone ([`MegaContext::with_cfg`](crate::MegaContext)); an opcode reads its price out of the //! table revm already carries. Nothing here runs on the hot path. use revm::{ context_interface::cfg::{GasId, GasParams}, + interpreter::instructions::{gas_table_spec, GasTable}, primitives::{eip8037, hardfork::SpecId, OnceLock}, }; use crate::evm::prices::{active_satin_prices, SatinPrices}; -/// The regular-gas entries Amsterdam repriced for EIP-8037 and EIP-8038, which Satin keeps at -/// their Osaka values. -/// -/// Amsterdam moves them for two reasons. EIP-8038 raises the price of *reaching* state — a cold -/// account, a cold slot, a storage write. EIP-8037 lowers the regular price of *creating* state, -/// having moved that charge onto the state dimension; `new_account_cost`, `create`, -/// `tx_create_cost` and `sstore_set_without_load_cost` are that second group. Satin takes neither -/// move, so state creation keeps its Osaka regular price on top of the state charge at -/// [`COST_PER_STATE_BYTE`](crate::constants::COST_PER_STATE_BYTE). The list is named for EIP-8038 -/// because that is the repricing it was drawn up against. -/// -/// `tx_create_cost` is the one of those four that prices nothing: under EIP-2780 the intrinsic -/// phase charges a creation through `tx_create_access_cost`, so pressing it back moves no -/// transaction. What the other three cost is in the module documentation. -/// -/// The entries Amsterdam introduced for EIP-8037's state gas, EIP-2780, EIP-7976, EIP-7981 and -/// EIP-7702 are not in this list and keep their Amsterdam values, even where the number itself is -/// derived from an EIP-8038 constant. -pub const EIP8038_REPRICED: &[fn() -> GasId] = &[ - GasId::warm_storage_read_cost, - GasId::cold_account_additional_cost, - GasId::cold_storage_additional_cost, - GasId::cold_storage_cost, - GasId::transfer_value_cost, - GasId::new_account_cost, - GasId::new_account_cost_for_selfdestruct, - GasId::sstore_static, - GasId::sstore_set_without_load_cost, - GasId::sstore_reset_without_cold_load_cost, - GasId::sstore_set_refund, - GasId::sstore_reset_refund, - GasId::sstore_clearing_slot_refund, - GasId::create, - GasId::tx_create_cost, - GasId::tx_access_list_address_cost, - GasId::tx_access_list_storage_key_cost, -]; - /// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte /// price. type ScheduleEntry = (fn() -> GasId, u64); @@ -93,6 +57,13 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ (GasId::tx_eip7702_state_gas_bytecode, eip8037::AUTH_BASE_BYTES), ]; +/// The history-gas entries, rebuilt at `MegaETH`'s own cost per history byte. +/// +/// Deposited code is the one history charge the schedule prices, because it is the one revm makes +/// itself: `return_create` writes the code and charges the entry for its length. Every other +/// history charge is made by the engine, which prices its own byte counts (the `history` module). +pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[(GasId::code_deposit_history_gas, 1)]; + /// The Satin gas schedule at the prices in effect. /// /// See the module documentation for what it changes; [`satin_gas_params_at`] is the same schedule @@ -105,17 +76,41 @@ pub fn satin_gas_params() -> GasParams { TABLE.get_or_init(|| satin_gas_params_at(active_satin_prices())).clone() } +/// The Satin gas schedule with no price on a history byte, for a transaction exempt from history +/// gas. +/// +/// The one history charge revm makes itself reads the schedule, so the way to keep it off an +/// exempt transaction is to hand that transaction a schedule that prices it at zero. Built once +/// and handed out as a shared clone, like [`satin_gas_params`]; every other entry is the same. +pub fn satin_gas_params_history_exempt() -> GasParams { + static TABLE: OnceLock = OnceLock::new(); + TABLE + .get_or_init(|| { + let mut params = satin_gas_params(); + params.override_gas(HISTORY_GAS_PRICED.iter().map(|&(id, _)| (id(), 0))); + params + }) + .clone() +} + +/// The Satin static opcode prices: Amsterdam's. +/// +/// Amsterdam's table differs from the Osaka base's in EIP-8038's base for `EXTCODESIZE` and +/// `EXTCODECOPY` alone: two warm accesses, 200, because each reads the account and then its code. +/// The dynamic cold premium is the schedule's, as for every account access. +pub(crate) const fn satin_gas_table() -> GasTable { + gas_table_spec(SpecId::AMSTERDAM) +} + /// The Satin gas schedule at `prices`. pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { - let osaka = GasParams::new_spec(SpecId::OSAKA); let mut params = GasParams::new_spec(SpecId::AMSTERDAM); - params.override_gas(EIP8038_REPRICED.iter().map(|id| { - let id = id(); - (id, osaka.get(id)) - })); params.override_gas( STATE_GAS_REPRICED.iter().map(|&(id, bytes)| (id(), prices.cpsb.fixed_size_gas(bytes))), ); + params.override_gas( + HISTORY_GAS_PRICED.iter().map(|&(id, bytes)| (id(), prices.cphb.fixed_size_gas(bytes))), + ); params } @@ -123,7 +118,9 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { mod tests { use super::*; use crate::{ - constants::{ACCOUNT_STATE_GAS, COST_PER_STATE_BYTE, SLOT_STATE_GAS}, + constants::{ + ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, SLOT_STATE_GAS, + }, evm::prices::{runs_at_measurement_prices, BytePrice}, }; @@ -135,88 +132,25 @@ mod tests { GasParams::new_spec(SpecId::AMSTERDAM) } - /// The seventeen entries Amsterdam repriced are back at their Osaka values, written out so a - /// change to the list is a visible diff. - #[test] - fn test_the_eip8038_repricing_is_pressed_back_to_osaka() { - let satin = satin_gas_params(); - let names = [ - "warm_storage_read_cost", - "cold_account_additional_cost", - "cold_storage_additional_cost", - "cold_storage_cost", - "transfer_value_cost", - "new_account_cost", - "new_account_cost_for_selfdestruct", - "sstore_static", - "sstore_set_without_load_cost", - "sstore_reset_without_cold_load_cost", - "sstore_set_refund", - "sstore_reset_refund", - "sstore_clearing_slot_refund", - "create", - "tx_create_cost", - "tx_access_list_address_cost", - "tx_access_list_storage_key_cost", - ]; - assert_eq!(EIP8038_REPRICED.len(), names.len(), "the list and its names agree"); - for (id, name) in EIP8038_REPRICED.iter().zip(names) { - assert_eq!(id().name(), name); - } - for id in EIP8038_REPRICED { - let id = id(); - assert_eq!(satin.get(id), osaka().get(id), "{} must be Osaka-priced", id.name()); - } - } - - /// The Osaka numbers those seventeen entries carry, so a change in the base schedule shows up - /// here rather than silently moving Satin. + /// Every regular-gas entry is Amsterdam's: every entry but the byte-priced ones. The + /// state-gas entries are rebuilt from the cost per state byte rather than copied, so they are + /// checked separately; at the provisional price they land on Amsterdam's numbers too, which + /// [`test_other_prices_move_only_the_byte_priced_entries`] shows is a coincidence of the + /// price and not a copy. #[test] - fn test_the_pressed_back_entries_carry_the_osaka_numbers() { - let satin = satin_gas_params(); - for (name, value) in [ - ("warm_storage_read_cost", 100), - ("cold_account_additional_cost", 2_500), - ("cold_storage_additional_cost", 2_000), - ("cold_storage_cost", 2_100), - ("transfer_value_cost", 9_000), - ("new_account_cost", 25_000), - ("new_account_cost_for_selfdestruct", 25_000), - ("sstore_static", 100), - ("sstore_set_without_load_cost", 19_900), - ("sstore_reset_without_cold_load_cost", 2_800), - ("sstore_set_refund", 19_900), - ("sstore_reset_refund", 2_800), - ("sstore_clearing_slot_refund", 4_800), - ("create", 32_000), - ("tx_create_cost", 32_000), - ("tx_access_list_address_cost", 2_400), - ("tx_access_list_storage_key_cost", 1_900), - ] { - let id = GasId::from_name(name).expect("a known gas id"); - assert_eq!(satin.get(id), value, "{name}"); - } - } - - /// Every entry outside the seventeen is Amsterdam's. The state-gas entries are rebuilt from - /// the cost per state byte rather than copied, so they are checked separately; at the - /// provisional price they land on Amsterdam's numbers too, which - /// [`test_other_prices_move_only_the_state_entries`] shows is a coincidence of the price and - /// not a copy. - #[test] - fn test_every_other_entry_is_amsterdam() { + fn test_every_regular_entry_is_amsterdam() { let (satin, amsterdam) = (satin_gas_params(), amsterdam()); for slot in 0..=u8::MAX { let id = GasId::new(slot); - let rebuilt = EIP8038_REPRICED.iter().any(|entry| entry() == id) || - STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id); + let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || + HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id); if rebuilt { continue; } assert_eq!(satin.get(id), amsterdam.get(id), "{} must be Amsterdam's", id.name()); } - // The entries Amsterdam introduced whose value is derived from an EIP-8038 constant stay - // Amsterdam's all the same; spelled out because pressing them back would be plausible. + // The entries Amsterdam introduced for EIP-2780, EIP-7976 and EIP-7981, and the zero + // regular code-deposit cost, spelled out beside the EIP-8038 ones below. for (name, value) in [ ("tx_account_write_cost", 9_000), ("tx_create_access_cost", 12_000), @@ -228,16 +162,86 @@ mod tests { ] { let id = GasId::from_name(name).expect("a known gas id"); assert_eq!(satin.get(id), value, "{name}"); - assert_eq!(amsterdam.get(id), value, "{name} is Amsterdam's"); } } - /// History gas is a later mechanism; until it lands the schedule prices no history byte, the - /// way Osaka and Amsterdam do not. + /// The seventeen regular-gas entries Amsterdam repriced for EIP-8038, and for EIP-8037's move + /// of the cost of creating state onto the state dimension, at their Osaka and their Satin + /// (Amsterdam) numbers, written out so a change in either base schedule shows up here rather + /// than silently moving Satin. + /// + /// The Amsterdam numbers are EIP-8038's constants (glamsterdam devnet-8): a cold account + /// access of 3,000 (2,900 above the warm 100), an account write of 9,000 (with the 2,300 + /// stipend, a value transfer of 11,300), a cold slot access of 2,100 with the warm base folded + /// in, a storage write of 10,000, a clearing refund of 11,616, a creation access of 12,000, + /// and access-list items at the cold premium plus EIP-7981's 64 gas per byte. + #[test] + fn test_the_eip8038_entries_carry_the_amsterdam_numbers() { + let satin = satin_gas_params(); + for (name, osaka_value, satin_value) in [ + ("warm_storage_read_cost", 100, 100), + ("cold_account_additional_cost", 2_500, 2_900), + ("cold_storage_additional_cost", 2_000, 2_000), + ("cold_storage_cost", 2_100, 2_000), + ("transfer_value_cost", 9_000, 11_300), + ("new_account_cost", 25_000, 0), + ("new_account_cost_for_selfdestruct", 25_000, 9_000), + ("sstore_static", 100, 100), + ("sstore_set_without_load_cost", 19_900, 10_000), + ("sstore_reset_without_cold_load_cost", 2_800, 10_000), + ("sstore_set_refund", 19_900, 10_000), + ("sstore_reset_refund", 2_800, 10_000), + ("sstore_clearing_slot_refund", 4_800, 11_616), + ("create", 32_000, 12_000), + ("tx_create_cost", 32_000, 12_000), + ("tx_access_list_address_cost", 2_400, 2_900 + 20 * 64), + ("tx_access_list_storage_key_cost", 1_900, 2_000 + 32 * 64), + ] { + let id = GasId::from_name(name).expect("a known gas id"); + assert_eq!(osaka().get(id), osaka_value, "{name} at Osaka"); + assert_eq!(satin.get(id), satin_value, "{name} at Satin"); + } + } + + /// The static opcode prices are Amsterdam's, which part from the Osaka base's in EIP-8038's + /// two-read base for `EXTCODESIZE` and `EXTCODECOPY` alone. #[test] - fn test_the_history_entry_is_not_priced_yet() { + fn test_the_static_prices_are_amsterdams() { + use revm::bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}; + let (satin, osaka) = (satin_gas_table(), gas_table_spec(SpecId::OSAKA)); + let changed: Vec<_> = + (0..=u8::MAX).filter(|&op| satin[op as usize] != osaka[op as usize]).collect(); + assert_eq!(changed, vec![EXTCODESIZE, EXTCODECOPY]); + for opcode in changed { + assert_eq!(osaka[opcode as usize], 100, "opcode {opcode:#04x} at Osaka"); + assert_eq!(satin[opcode as usize], 200, "opcode {opcode:#04x} at Satin"); + } + } + + /// The schedule an exempt transaction runs prices no history byte and is otherwise the same + /// table. + #[test] + fn test_the_exempt_schedule_only_drops_the_history_price() { + let exempt = satin_gas_params_history_exempt(); + let satin = satin_gas_params(); + assert_eq!(exempt.get(GasId::code_deposit_history_gas()), 0); + for slot in 0..=u8::MAX { + let id = GasId::new(slot); + if HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) { + continue; + } + assert_eq!(exempt.get(id), satin.get(id), "{} must not move", id.name()); + } + } + + /// Deposited code costs one history byte per byte, which is the whole of Satin's history + /// schedule. Osaka and Amsterdam price no history byte at all. + #[test] + fn test_deposited_code_is_priced_per_history_byte() { let id = GasId::code_deposit_history_gas(); - assert_eq!(satin_gas_params().get(id), 0); + let satin = satin_gas_params_at(SatinPrices::CONSTANTS); + assert_eq!(satin.get(id), COST_PER_HISTORY_BYTE); + assert_eq!(satin.get(id), 88); assert_eq!(osaka().get(id), 0); assert_eq!(amsterdam().get(id), 0); } @@ -266,10 +270,10 @@ mod tests { assert_eq!(satin.get(GasId::tx_eip7702_state_gas_bytecode()), 35_190); } - /// Other prices move the five state entries and nothing else, which is what makes a - /// measurement build a repricing rather than a different schedule. + /// Other prices move the five state entries and the history entry, and nothing else, which + /// is what makes a measurement build a repricing rather than a different schedule. #[test] - fn test_other_prices_move_only_the_state_entries() { + fn test_other_prices_move_only_the_byte_priced_entries() { let constants = satin_gas_params_at(SatinPrices::CONSTANTS); let prices = SatinPrices { cpsb: "312.5".parse().unwrap(), cphb: BytePrice::from_gas(400) }; let repriced = satin_gas_params_at(prices); @@ -279,6 +283,7 @@ mod tests { (GasId::create_state_gas(), 37_500), (GasId::code_deposit_state_gas(), 313), (GasId::tx_eip7702_state_gas_bytecode(), 7_188), + (GasId::code_deposit_history_gas(), 400), ]; for slot in 0..=u8::MAX { let id = GasId::new(slot); diff --git a/crates/mega-evm/src/evm/spec.rs b/crates/mega-evm/src/evm/spec.rs index 8f17d59bb..315ec7622 100644 --- a/crates/mega-evm/src/evm/spec.rs +++ b/crates/mega-evm/src/evm/spec.rs @@ -14,14 +14,14 @@ use serde::{Deserialize, Serialize}; /// `MegaETH` spec id: the EVM behavior the Satin engine executes. /// -/// Satin is a single-spec engine. The specs of the legacy engine (`Equivalence` through `Rex7`) +/// Satin is a single-spec engine. The specs of the legacy engine (`Equivalence` through `Rex6`) /// are not variants here and never parse to one; they are executed by the legacy engine. /// /// Each spec runs on top of an Optimism spec, which in turn runs on top of an Ethereum spec: /// - [`MegaSpecId::SATIN`] -> [`OpSpecId::KARST`] -> [`EthSpecId::OSAKA`] /// -/// The discriminants continue after the legacy ladder (`EQUIVALENCE` = 0 through `REX7` = 11), -/// so a raw `as u8` of a Satin spec never aliases a legacy one. +/// The discriminants continue after those of the released legacy crate, which assigns 0 through +/// 11, so a raw `as u8` of a Satin spec never aliases a legacy one. #[repr(u8)] #[derive( Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize, @@ -57,7 +57,6 @@ pub const LEGACY_SPEC_NAMES: &[&str] = &[ "Rex4", "Rex5", "Rex6", - "Rex7", ]; impl MegaSpecId { @@ -151,7 +150,7 @@ mod tests { /// Every spec name of the legacy engine, written out by hand so the rejection check does /// not read the list it is checking. - const LEGACY_NAMES: [&str; 12] = [ + const LEGACY_NAMES: [&str; 11] = [ "Equivalence", "MiniRex", "MiniRex1", @@ -163,7 +162,6 @@ mod tests { "Rex4", "Rex5", "Rex6", - "Rex7", ]; #[test] @@ -204,7 +202,7 @@ mod tests { fn test_serde_uses_the_variant_name() { assert_eq!(serde_json::to_string(&MegaSpecId::SATIN).unwrap(), "\"SATIN\""); assert_eq!(serde_json::from_str::("\"SATIN\"").unwrap(), MegaSpecId::SATIN); - for legacy in ["\"REX6\"", "\"REX7\"", "\"EQUIVALENCE\"", "\"Satin\""] { + for legacy in ["\"REX6\"", "\"EQUIVALENCE\"", "\"Satin\""] { assert!( serde_json::from_str::(legacy).is_err(), "{legacy} must not deserialize" @@ -218,8 +216,8 @@ mod tests { assert_eq!(*MegaSpecId::ALL.last().unwrap(), MegaSpecId::default()); } - /// A raw `as u8` of a Satin spec never aliases a legacy rung (`EQUIVALENCE` = 0 through - /// `REX7` = 11). + /// A raw `as u8` of a Satin spec never aliases a legacy one: the released legacy crate + /// assigns 0 through 11. #[test] fn test_discriminant_continues_after_the_legacy_ladder() { assert_eq!(MegaSpecId::SATIN as u8, 12); diff --git a/crates/mega-evm/src/evm/state.rs b/crates/mega-evm/src/evm/state.rs index fed6d1b4c..93ad13228 100644 --- a/crates/mega-evm/src/evm/state.rs +++ b/crates/mega-evm/src/evm/state.rs @@ -1,4 +1,5 @@ -//! The block hashes execution read, which a node's stateless witness needs. +//! What execution read beside the journal, which a node's stateless witness needs: the block +//! hashes, the SALT buckets and the oracle service's answers. //! //! `BLOCKHASH` reads the chain's history through the database, not through the journal, so a //! witness built from a transaction's state alone would miss them. The Host records every hash it @@ -8,12 +9,31 @@ //! The record is kept beside revm's `State`, not read out of it: `State` caches every hash it ever //! served, across every block it was used for, so a database reused over a range of blocks — or //! one whose cache was filled in advance — would report hashes this block never asked for. +//! +//! A SALT bucket's capacity is read through the transaction's [`SaltEnv`](crate::SaltEnv), a side +//! channel no database sees, and a validator that lacks a bucket's proof cannot price the charge +//! that landed in it. The context records every bucket the SALT environment answered with a valid +//! capacity in the [`BucketRecord`], which is emptied when a block starts and not between its +//! transactions: the per-transaction cache of multipliers +//! ([`BucketMultipliers`](crate::BucketMultipliers)) is forgotten before every transaction, and a +//! record that lived there would lose every transaction's buckets but the last one's. +//! +//! The oracle service's answers are in no database either: an `SLOAD` in the Oracle's own frame +//! loads the chain's slot and takes the service's answer over it. The context records every such +//! read with its answer in the [`OracleReadRecord`], which belongs to one transaction and is +//! carried on the transaction's outcome, so a node takes the reads of the transactions it +//! includes and nothing of a candidate it executed and dropped. #[cfg(not(feature = "std"))] use alloc as std; -use std::collections::BTreeMap; +use std::{ + collections::{BTreeMap, BTreeSet}, + vec::Vec, +}; + +use alloy_primitives::{B256, U256}; -use alloy_primitives::B256; +use crate::BucketId; /// The block hashes execution has read, by block number. /// @@ -46,6 +66,97 @@ impl BlockHashRecord { } } +/// The SALT buckets the SALT environment answered with a valid capacity. +/// +/// One entry per bucket, recorded once the environment answered it with a valid capacity, on the +/// cache miss that asked it. A lookup that fails, with an error or with a capacity below the +/// minimum bucket, is not recorded: it fails its transaction with its cause, so the transaction is +/// in no block and a validator never makes the lookup, and a builder whose environment failed on +/// the bucket is not held to proving it. What a block's execution was answered is what a validator +/// re-executing the block asks about, because the engine reads a bucket at a charge site and +/// nothing else decides whether a charge site is reached. +/// +/// The record accumulates over everything one EVM executes for a block — the pre-block calls and +/// the system transactions included, which read none, and a candidate the builder executed and +/// dropped, whose buckets a validator does not need: block execution empties it at the start of +/// the block, and a caller that attributes the reads to one transaction empties it between +/// transactions ([`MegaEvm::clear_accessed_bucket_ids`](crate::MegaEvm)). It records what was +/// read and decides nothing, so emptying it changes no execution result. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct BucketRecord(BTreeSet); + +impl BucketRecord { + /// Records that `bucket` was asked about. + pub fn record(&mut self, bucket: BucketId) { + self.0.insert(bucket); + } + + /// The buckets asked about so far, in ascending order. + pub const fn ids(&self) -> &BTreeSet { + &self.0 + } + + /// The buckets asked about so far, as a vector in ascending order. + pub fn to_vec(&self) -> Vec { + self.0.iter().copied().collect() + } + + /// Whether nothing has been asked about. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Forgets the buckets asked about so far. + pub fn clear(&mut self) { + self.0.clear(); + } +} + +/// One read of the Oracle's storage through the oracle service: the slot, and what the service +/// answered — `None` when it answered nothing and the loaded value stood. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OracleRead { + /// The slot of the Oracle's storage that was read. + pub slot: U256, + /// The service's answer, which the frame saw over the chain's value; `None` when the service + /// had none and the frame saw the loaded value. + pub answer: Option, +} + +/// The reads of the Oracle's storage the running (or last) transaction made through the oracle +/// service, in order, each with its answer. +/// +/// A read is recorded where the service is asked, once the slot was loaded, so a read a frame +/// could not pay for, or one it was refused, is not in it; a read whose frame then fails is, +/// because the service was asked and a validator's service must be asked the same. The record +/// belongs to one transaction: the context empties it before every transaction and system call, +/// and the transaction's outcome carries a copy. A validator given the included transactions' +/// reads, in block order, answers each read as the building node's service did. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OracleReadRecord(Vec); + +impl OracleReadRecord { + /// Records that `slot` was read and the service answered `answer`. + pub fn record(&mut self, slot: U256, answer: Option) { + self.0.push(OracleRead { slot, answer }); + } + + /// The reads so far, in order. + pub fn reads(&self) -> &[OracleRead] { + &self.0 + } + + /// Whether nothing was read. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Forgets the reads so far. + pub fn clear(&mut self) { + self.0.clear(); + } +} + #[cfg(test)] mod tests { use super::*; @@ -85,4 +196,65 @@ mod tests { assert!(record.is_empty()); assert!(record.hashes().is_empty()); } + + /// The bucket record holds every bucket asked about, once each and in ascending order. + #[test] + fn test_the_bucket_record_holds_each_bucket_once_in_order() { + let mut record = BucketRecord::default(); + assert!(record.is_empty()); + + record.record(9); + record.record(2); + record.record(9); + + assert!(!record.is_empty(), "a record that holds an ask is not empty"); + assert_eq!(record.to_vec(), vec![2, 9]); + assert_eq!(record.ids().len(), 2); + } + + /// Clearing empties the bucket record. + #[test] + fn test_clearing_forgets_the_buckets_asked_about() { + let mut record = BucketRecord::default(); + record.record(7); + + record.clear(); + + assert!(record.is_empty()); + assert!(record.to_vec().is_empty()); + } + + /// The oracle read record keeps every read in order, a slot read twice and an unanswered + /// read included. + #[test] + fn test_the_oracle_read_record_keeps_every_read_in_order() { + let mut record = OracleReadRecord::default(); + assert!(record.is_empty()); + + record.record(U256::from(42), Some(U256::from(1))); + record.record(U256::from(7), None); + record.record(U256::from(42), Some(U256::from(2))); + + assert!(!record.is_empty()); + assert_eq!( + record.reads(), + [ + OracleRead { slot: U256::from(42), answer: Some(U256::from(1)) }, + OracleRead { slot: U256::from(7), answer: None }, + OracleRead { slot: U256::from(42), answer: Some(U256::from(2)) }, + ] + ); + } + + /// Clearing empties the oracle read record. + #[test] + fn test_clearing_forgets_the_oracle_reads() { + let mut record = OracleReadRecord::default(); + record.record(U256::ZERO, None); + + record.clear(); + + assert!(record.is_empty()); + assert!(record.reads().is_empty()); + } } diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs new file mode 100644 index 000000000..60d72f154 --- /dev/null +++ b/crates/mega-evm/src/evm/validation.rs @@ -0,0 +1,154 @@ +//! What a transaction pool can decide about a transaction before it reads any state. +//! +//! [`validate_transaction_stateless`] runs the EVM's own validation phases on an EVM over an empty +//! database, so a pool admits and refuses by the rules block execution applies, and reads the +//! intrinsic gas the EVM charges ([`IntrinsicGas`]) rather than recomputing it. + +use core::convert::Infallible; + +use alloy_primitives::Address; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::EmptyDB, + handler::{EthFrame, Handler}, + interpreter::interpreter::EthInterpreter, +}; + +use crate::{MegaContext, MegaEvm, MegaEvmError, MegaHandler, MegaSpecId, MegaTransaction}; + +/// The gas a transaction's gas limit must cover before it runs, by ledger, as the EVM charges it +/// when it validates the transaction. +/// +/// It is fixed by the transaction's own fields, and it is not all a transaction is charged before +/// its first instruction. What the state decides is charged once the transaction is admitted, +/// when it runs: +/// +/// - each EIP-7702 authority that applies: the write to its account, and the state gas of the +/// account and of the delegation it adds when it adds them; +/// - the state gas of a recipient of value or a created account that EIP-2780 finds new; +/// - the history of the write records the transaction's start makes: one for the recipient of its +/// value or the account it creates, and one for each authority that applies. +/// +/// State gas is priced at the SALT bucket the account lands in. Whether an authority applies and +/// whether an account is new are the state's to say; a gas limit that cannot pay them runs out of +/// gas rather than being refused. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct IntrinsicGas { + /// Regular gas: EIP-2780's base cost with its recipient and value charges, the calldata, the + /// access list, the regular part of each EIP-7702 authorization and a creation's init-code + /// words. + pub regular: u64, + /// EIP-8037 state gas. Under EIP-2780 it is zero: the state a transaction adds is charged when + /// it runs, once the state says what it adds. + pub state: u64, + /// The history gas of the transaction's body: its envelope, the five write records every + /// transaction makes, its calldata, access list and authorizations, at the cost per history + /// byte. Zero for a transaction exempt from history gas: a deposit and a system-address + /// transaction. + pub history: u64, + /// The EIP-7623 calldata floor. The gas limit must cover it, and a transaction pays at least + /// it. At the spec's byte prices a transaction that pays history gas pays more than the floor + /// for the same bytes, so the floor binds only one exempt from history; the byte prices are + /// provisional. + pub floor: u64, +} + +impl IntrinsicGas { + /// What the gas limit must cover before the transaction runs: the regular, state and history + /// parts together. + pub const fn total(&self) -> u64 { + self.regular.saturating_add(self.state).saturating_add(self.history) + } + + /// The smallest gas limit that covers both [`total`](Self::total) and the floor. + /// + /// No gas limit below it is valid. One at or above it can still be refused by the other + /// rules: the block's gas limit, and, for a gas limit above the execution cap, a regular part + /// or a floor that the cap does not cover. + /// + /// It is what validation requires, not what the transaction needs to succeed: it leaves out + /// what the state decides (see [`IntrinsicGas`]) and the execution. At the spec's byte prices + /// and this gas limit, a call without value to an account without code runs, and so does a + /// transfer of value to the sender itself; a transfer of value to another account runs out of + /// gas on the history of its recipient's write record, and one to a new account needs that + /// account's state gas as well. Such a transaction is admitted, included, and halts out of + /// gas. + pub fn min_gas_limit(&self) -> u64 { + self.total().max(self.floor) + } +} + +/// Validates `tx` as the EVM does before it reads any state, and returns the intrinsic gas the +/// EVM charges it. +/// +/// It runs the Satin handler's own validation phases — `validate_env` and +/// `validate_initial_tx_gas` — on an EVM over an empty database, configured with +/// [`spec_cfg`](crate::spec_cfg) of `cfg` and running in `block`. What they check: +/// +/// - the block environment: a prevrandao and a blob excess gas are set; +/// - the transaction against the configuration and the block: its chain id, its type and its fees +/// against the block's base fee, a non-empty authorization list, its gas limit against the +/// block's, the init-code size of a creation, a nonce that can still be incremented; +/// - the intrinsic gas: the gas limit covers [`IntrinsicGas::total`] and the floor, and a gas limit +/// above the execution cap leaves the regular part and the floor within the cap. +/// +/// A deposit is validated as op-revm validates one: on its intrinsic gas, and on not being flagged +/// as an L1 system transaction. A system-address transaction has its chain id checked and is +/// promoted to a deposit. Neither pays history gas. +/// +/// What is left to the state is left out: the sender's nonce, balance and code (EIP-3607), the +/// system address's nonce and code for a system-address transaction, and the charges the state +/// decides (see [`IntrinsicGas`]). +/// +/// A transaction whose body, with a write record for each entry of its authorization list, exceeds +/// the spec's transaction data-size limit is refused +/// ([`TX_BODY_OVER_DATA_SIZE_LIMIT`](crate::TX_BODY_OVER_DATA_SIZE_LIMIT)) before its gas is +/// looked at, as block execution refuses it: the EVM this runs on holds the spec's limits. +/// A system-address transaction is exempt from the limit, and from the check. +/// +/// `system_address` is the live system address: the one the `SequencerRegistry` names in the +/// state the pool validates against ([`live_system_address`](crate::system::live_system_address)). +/// A transaction of the system shape from it is a system-address transaction, and one of another +/// shape from it is refused +/// ([`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`](crate::system::SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE)); +/// with `None`, no transaction is either. +/// +/// The address changes only in a block's pre-block step, which applies a change the registry's +/// admin scheduled in an earlier block, and it then holds for every transaction of that block. So +/// a pool reads it again for every block, off the state that block's transactions run on: the +/// state after its pre-block changes. Against the head's state, that is the head's address unless +/// a change is due in the next block +/// ([`is_apply_pending_changes_due`](crate::system::is_apply_pending_changes_due)), and then the +/// one the state [`transact_apply_pending_changes`](crate::system::transact_apply_pending_changes) +/// leaves names. An address read from another state treats the old system address's transactions +/// as the protocol's — no fees, no history gas — and the new one's as a user's, or the reverse. +/// +/// # Errors +/// +/// The error the EVM reports for the same transaction in the same block: an invalid transaction, +/// or a block environment the spec cannot run in. +/// +/// The EVM does not refuse a deposit for any of them, nor a system-address transaction for one +/// found once it is promoted: op-revm includes a deposit that fails validation as a failed +/// deposit, which bumps the sender's nonce, keeps the mint and uses the whole gas limit. For +/// those the error says the transaction would fail, not that it would be refused. +pub fn validate_transaction_stateless( + cfg: CfgEnv, + block: BlockEnv, + tx: MegaTransaction, + system_address: Option
, +) -> Result> { + let ctx = + MegaContext::new(EmptyDB::default(), cfg.spec).with_cfg(cfg).with_block(block).with_tx(tx); + let mut evm = MegaEvm::new(ctx); + let handler = MegaHandler::<_, MegaEvmError, EthFrame>::new(); + handler.validate_env_as(&mut evm, system_address, false)?; + let gas = handler.validate_initial_tx_gas(&mut evm)?; + let history = evm.ctx().additional_limit.intrinsic_history_gas(); + Ok(IntrinsicGas { + regular: gas.initial_regular_gas(), + state: gas.initial_state_gas_final() - history, + history, + floor: gas.floor_gas(), + }) +} diff --git a/crates/mega-evm/src/external/AGENTS.md b/crates/mega-evm/src/external/AGENTS.md index 761ee3097..00cdc0d94 100644 --- a/crates/mega-evm/src/external/AGENTS.md +++ b/crates/mega-evm/src/external/AGENTS.md @@ -15,7 +15,9 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d - Block context is captured at environment creation time, not passed per query. - SALT and oracle are independent traits but consumed together via `ExternalEnvs` bundle. - External errors are propagated to host and then stashed in EVM context error channel. -- `EmptyExternalEnv` must stay deterministic and side-effect free. +- `EmptyExternalEnv` must stay deterministic and side-effect free. It answers no oracle slot, so the Oracle's storage is read from the database. +- A read of the Oracle's storage loads the slot through the journal and is priced cold whichever source answered it: a node that replays a block without the oracle service must price and witness it as the node that built it did, so neither the read's price, nor the price of a later write to the slot, nor the witness may depend on whether the service had a value. +- The service's value is returned even over a value the Oracle's frame stored earlier in the transaction. - A bucket's capacity is read once per transaction and answered from `BucketMultipliers` afterwards, so a state gas charge and the refill that undoes it are priced at the same capacity by construction. - `BucketMultipliers` does not hold the environment; it takes a `&SaltEnv` per call, so there is no second copy of it and no `Clone` bound on the engine's environment types. - `MIN_BUCKET_SIZE` is the smallest capacity a backend may report. @@ -29,6 +31,6 @@ External dependency abstraction for block-scoped SALT and oracle data consumed d ## WHERE TO LOOK - Add a new external backend implementation: implement `SaltEnv`/`OracleEnv` and an `ExternalEnvFactory`. -- Change oracle storage retrieval behavior: `oracle.rs` trait impls (the host integration is not here yet). +- Change oracle storage retrieval behavior: `oracle.rs` trait impls; the Host reads through them in `evm/host.rs` (`oracle_sload`): the slot loaded through the journal, the service's value when it has one and the loaded value otherwise, always priced cold. - Change bucket-id mapping logic: `salt.rs` and `hasher/` helpers. - Change how a bucket capacity becomes a gas multiplier: `gas.rs`. What that multiplier is applied to is the pricing hook in `evm/host.rs`. diff --git a/crates/mega-evm/src/external/gas.rs b/crates/mega-evm/src/external/gas.rs index f09362e17..cf91edf32 100644 --- a/crates/mega-evm/src/external/gas.rs +++ b/crates/mega-evm/src/external/gas.rs @@ -18,8 +18,7 @@ use core::fmt; -use alloy_primitives::{map::Entry, Address}; -use revm::primitives::{HashMap, StorageKey}; +use revm::primitives::HashMap; use crate::{BucketId, SaltEnv, MIN_BUCKET_SIZE}; @@ -59,8 +58,9 @@ impl fmt::Display for BucketError { /// The SALT bucket multipliers the running transaction has looked up. /// /// One entry per bucket the transaction has priced a charge in. It is cleared with the rest of -/// the per-transaction state at every entry point of [`MegaEvm`](crate::MegaEvm), so a -/// transaction never prices against a capacity an earlier transaction read. +/// the per-transaction state before every transaction and system call a +/// [`MegaEvm`](crate::MegaEvm) runs, so a transaction never prices against a capacity an earlier +/// transaction read. /// /// The environment is passed in rather than held, so the cache adds no second copy of it and /// puts no `Clone` bound on the engine's external environment types. @@ -93,47 +93,30 @@ impl BucketMultipliers { } } - /// The multiplier of the bucket `account`'s own state lives in. + /// The multiplier of `bucket` this transaction has already read, if it has. #[inline] - pub fn account( - &mut self, - salt_env: &S, - account: Address, - ) -> Result> { - self.of_bucket(salt_env, S::bucket_id_for_account(account)) - } - - /// The multiplier of the bucket the slot `key` of `address` lives in. - #[inline] - pub fn slot( - &mut self, - salt_env: &S, - address: Address, - key: StorageKey, - ) -> Result> { - self.of_bucket(salt_env, S::bucket_id_for_slot(address, key)) + pub fn cached(&self, bucket: BucketId) -> Option { + self.cached.get(&bucket).copied() } - /// The multiplier of `bucket`, read from `salt_env` the first time this transaction asks for - /// it and from the cache afterwards. + /// Reads the capacity of `bucket` from `salt_env`, turns it into the multiplier and caches + /// it: the cache miss of a lookup that asks [`cached`](Self::cached) first, kept apart so the + /// caller knows whether the environment was asked. /// - /// Only a multiplier is cached, so a bucket whose capacity could not be turned into one is - /// asked for again rather than remembered as anything. + /// A bucket the cache already holds is asked for again, and the answer replaces the cached + /// multiplier. Only a multiplier is cached, so a bucket whose capacity could not be turned + /// into one is asked for again rather than remembered as anything. #[inline] - fn of_bucket( + pub(crate) fn fetch( &mut self, salt_env: &S, bucket: BucketId, ) -> Result> { - match self.cached.entry(bucket) { - Entry::Occupied(entry) => Ok(*entry.get()), - Entry::Vacant(entry) => { - let capacity = salt_env.get_bucket_capacity(bucket).map_err(BucketError::Env)?; - let multiplier = Self::for_capacity(capacity) - .ok_or(BucketError::BelowMinimum { bucket, capacity })?; - Ok(*entry.insert(multiplier)) - } - } + let capacity = salt_env.get_bucket_capacity(bucket).map_err(BucketError::Env)?; + let multiplier = + Self::for_capacity(capacity).ok_or(BucketError::BelowMinimum { bucket, capacity })?; + self.cached.insert(bucket, multiplier); + Ok(multiplier) } /// The buckets this transaction has read, for tests and tools that check the read set. @@ -146,8 +129,9 @@ impl BucketMultipliers { #[cfg(test)] mod tests { use super::*; - use crate::{TestExternalEnvs, MIN_BUCKET_SIZE}; - use alloy_primitives::{address, U256}; + use crate::{ExternalEnvs, MegaContext, MegaSpecId, TestExternalEnvs, MIN_BUCKET_SIZE}; + use alloy_primitives::{address, Address, U256}; + use revm::{database::EmptyDB, primitives::StorageKey}; const ACCOUNT: Address = address!("00000000000000000000000000000000000000a1"); const OTHER: Address = address!("00000000000000000000000000000000000000a2"); @@ -162,14 +146,24 @@ mod tests { ::bucket_id_for_slot(address, key) } + /// A context over `env`: the multipliers are read through it, as every state charge reads them. + fn context( + env: &TestExternalEnvs, + ) -> MegaContext> { + MegaContext::new_with_external_envs( + EmptyDB::default(), + MegaSpecId::SATIN, + ExternalEnvs { salt_env: env.clone(), oracle_env: env.clone() }, + ) + } + /// A bucket at the minimum capacity multiplies by one, so the schedule's own price stands. #[test] fn test_the_minimum_bucket_multiplies_by_one() { - let env = Env::new(); - let mut cache = BucketMultipliers::default(); + let mut ctx = context(&Env::new()); - assert_eq!(cache.account(&env, ACCOUNT), Ok(1)); - assert_eq!(cache.slot(&env, ACCOUNT, U256::ZERO), Ok(1)); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(1)); + assert_eq!(ctx.slot_bucket_multiplier(ACCOUNT, U256::ZERO), Ok(1)); } /// The multiplier is the capacity in minimum buckets, over the range a capacity can take. @@ -195,13 +189,12 @@ mod tests { } let bucket = account_bucket(ACCOUNT); - let env = Env::new().with_bucket_capacity(bucket, 0); - let mut cache = BucketMultipliers::default(); + let mut ctx = context(&Env::new().with_bucket_capacity(bucket, 0)); assert_eq!( - cache.account(&env, ACCOUNT), + ctx.account_bucket_multiplier(ACCOUNT), Err(BucketError::BelowMinimum { bucket, capacity: 0 }), ); - assert_eq!(cache.cached_buckets().len(), 0, "nothing was cached for it"); + assert_eq!(ctx.bucket_multipliers().cached_buckets().len(), 0, "nothing was cached for it"); } /// The two failures read differently, so a node can tell a backend that could not answer from @@ -223,17 +216,18 @@ mod tests { #[test] fn test_a_crowded_bucket_scales_the_account_and_the_slot_separately() { let min = MIN_BUCKET_SIZE as u64; - let env = Env::new() - .with_bucket_capacity(account_bucket(ACCOUNT), min * 8) - .with_bucket_capacity(slot_bucket(ACCOUNT, U256::ZERO), min * 2); - let mut cache = BucketMultipliers::default(); + let mut ctx = context( + &Env::new() + .with_bucket_capacity(account_bucket(ACCOUNT), min * 8) + .with_bucket_capacity(slot_bucket(ACCOUNT, U256::ZERO), min * 2), + ); - assert_eq!(cache.account(&env, ACCOUNT), Ok(8)); - assert_eq!(cache.slot(&env, ACCOUNT, U256::ZERO), Ok(2)); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(8)); + assert_eq!(ctx.slot_bucket_multiplier(ACCOUNT, U256::ZERO), Ok(2)); // A slot of the same account in another bucket is untouched by either. - assert_eq!(cache.slot(&env, ACCOUNT, U256::from(1)), Ok(1)); + assert_eq!(ctx.slot_bucket_multiplier(ACCOUNT, U256::from(1)), Ok(1)); // So is another account. - assert_eq!(cache.account(&env, OTHER), Ok(1)); + assert_eq!(ctx.account_bucket_multiplier(OTHER), Ok(1)); } /// A bucket is read from the environment once; every later charge on it is answered from the @@ -242,28 +236,28 @@ mod tests { fn test_a_bucket_is_read_once_and_cached() { let bucket = account_bucket(ACCOUNT); let env = Env::new().with_bucket_capacity(bucket, MIN_BUCKET_SIZE as u64 * 4); - let mut cache = BucketMultipliers::default(); + let mut ctx = context(&env); for _ in 0..8 { - assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); + assert_eq!(ctx.account_bucket_multiplier(ACCOUNT), Ok(4)); } assert_eq!(env.bucket_queries(bucket), 1, "one capacity query for eight charges"); - assert_eq!(cache.cached_buckets().collect::>(), vec![bucket]); + assert_eq!(ctx.bucket_multipliers().cached_buckets().collect::>(), vec![bucket]); } - /// The cache belongs to one transaction: a reset forgets it, and the next transaction reads - /// the capacity again. + /// The cache belongs to one transaction: a reset forgets what it read, so the next + /// transaction reads the capacity again. #[test] fn test_a_reset_forgets_what_the_transaction_read() { let bucket = account_bucket(ACCOUNT); let env = Env::new().with_bucket_capacity(bucket, MIN_BUCKET_SIZE as u64 * 4); let mut cache = BucketMultipliers::default(); - assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); + assert_eq!(cache.fetch(&env, bucket), Ok(4)); + assert_eq!(cache.cached(bucket), Some(4)); cache.reset(); - assert_eq!(cache.cached_buckets().len(), 0, "the reset emptied the cache"); - assert_eq!(cache.account(&env, ACCOUNT), Ok(4)); - assert_eq!(env.bucket_queries(bucket), 2, "one query per transaction"); + assert_eq!(cache.cached(bucket), None, "the reset emptied the cache"); + assert_eq!(cache.cached_buckets().len(), 0); } /// A failed capacity query is reported, not swallowed: the caller must fail the transaction @@ -273,27 +267,32 @@ mod tests { let bucket = account_bucket(ACCOUNT); let env = TestExternalEnvs::::new() .with_failing_bucket(bucket, "salt backend unreachable".into()); - let mut cache = BucketMultipliers::default(); + let mut ctx = context(&env); assert_eq!( - cache.account(&env, ACCOUNT), + ctx.account_bucket_multiplier(ACCOUNT), Err(BucketError::Env("salt backend unreachable".into())), ); - assert_eq!(cache.cached_buckets().len(), 0, "a failed lookup caches nothing"); + assert_eq!( + ctx.bucket_multipliers().cached_buckets().len(), + 0, + "a failed lookup caches nothing" + ); // It is not cached either, so the next charge asks again. - assert!(cache.account(&env, ACCOUNT).is_err()); + assert!(ctx.account_bucket_multiplier(ACCOUNT).is_err()); assert_eq!(env.bucket_queries(bucket), 2); } /// One bucket failing does not stop another from being priced. #[test] fn test_only_the_failing_bucket_fails() { - let env = TestExternalEnvs::::new() - .with_bucket_capacity(account_bucket(OTHER), MIN_BUCKET_SIZE as u64 * 2) - .with_failing_bucket(account_bucket(ACCOUNT), "unreachable".into()); - let mut cache = BucketMultipliers::default(); + let mut ctx = context( + &TestExternalEnvs::::new() + .with_bucket_capacity(account_bucket(OTHER), MIN_BUCKET_SIZE as u64 * 2) + .with_failing_bucket(account_bucket(ACCOUNT), "unreachable".into()), + ); - assert!(cache.account(&env, ACCOUNT).is_err()); - assert_eq!(cache.account(&env, OTHER), Ok(2)); + assert!(ctx.account_bucket_multiplier(ACCOUNT).is_err()); + assert_eq!(ctx.account_bucket_multiplier(OTHER), Ok(2)); } } diff --git a/crates/mega-evm/src/external/hasher/mod.rs b/crates/mega-evm/src/external/hasher/mod.rs index 7e1178d37..692a82300 100644 --- a/crates/mega-evm/src/external/hasher/mod.rs +++ b/crates/mega-evm/src/external/hasher/mod.rs @@ -122,6 +122,25 @@ mod tests { assert_eq!(bucket_id(&[0u8; 20]), 12_666_336); } + /// Eight bytes, the longest input the small branch of `write` reads (`read_small`). + /// + /// The id is `salt::state::hasher::bucket_id`'s at salt v1.0.6 (and v1.0.5), computed once: + /// salt is not a dependency of this workspace. + #[test] + fn test_bucket_id_at_the_small_input_boundary() { + assert_eq!(bucket_id(&[1, 2, 3, 4, 5, 6, 7, 8]), 1_978_187); + } + + /// Thirty-two bytes: after the large branch of `write` reads the last sixteen and one block, + /// exactly sixteen are left, which the block loop does not read again. + /// + /// The id is `salt::state::hasher::bucket_id`'s at salt v1.0.6 (and v1.0.5), computed once: + /// salt is not a dependency of this workspace. + #[test] + fn test_bucket_id_at_the_block_loop_boundary() { + assert_eq!(bucket_id(&[0x22; 32]), 10_093_090); + } + #[test] fn test_hash_all_write_branches() { let h0 = hash(b""); diff --git a/crates/mega-evm/src/external/oracle.rs b/crates/mega-evm/src/external/oracle.rs index 303638e4d..f1c7505e0 100644 --- a/crates/mega-evm/src/external/oracle.rs +++ b/crates/mega-evm/src/external/oracle.rs @@ -24,6 +24,17 @@ pub trait OracleEnv: Debug + Unpin { /// /// The storage value at the given slot of the oracle contract. If the oracle does not provide a /// value, the result will be `None`. + /// + /// The EVM asks for every `SLOAD` in the oracle contract's own frame, each time it runs, once + /// it loaded the slot from the chain's state, and uses the loaded value when the answer is + /// `None`. An answer is used even over a value the oracle contract's frame stored in the slot + /// earlier in the transaction. The slot is loaded whatever the answer, so a node that replays + /// a block without the service prices and witnesses it as the node that built the block did. + /// + /// A frame whose regular gas, the part gas detention withholds included, cannot pay the read's + /// cold access, and a frame whose volatile-data access is switched off, read nothing and do not + /// ask. A detained frame that holds the gas but may not spend it does ask, and the read's + /// charge then stops that frame at the compute limit. fn get_oracle_storage(&self, slot: U256) -> Option; /// Receives hints emitted on-chain by the oracle contract. A hint is a message sent from diff --git a/crates/mega-evm/src/external/salt.rs b/crates/mega-evm/src/external/salt.rs index b90621a7e..15cd541b4 100644 --- a/crates/mega-evm/src/external/salt.rs +++ b/crates/mega-evm/src/external/salt.rs @@ -42,9 +42,9 @@ pub const MIN_BUCKET_SIZE: usize = 1 << MIN_BUCKET_SIZE_BITS; /// /// # Bucket ID Calculation /// -/// The trait provides default methods [`bucket_id_for_account`](SaltEnv::bucket_id_for_account) -/// and [`bucket_id_for_slot`](SaltEnv::bucket_id_for_slot) that can be overridden by -/// implementations to customize bucket assignment logic. +/// Every implementation supplies [`bucket_id_for_account`](SaltEnv::bucket_id_for_account) and +/// [`bucket_id_for_slot`](SaltEnv::bucket_id_for_slot), which assign a key its bucket: the trait +/// has no default for either. #[auto_impl(&, Box, Rc, Arc)] pub trait SaltEnv: Debug + Unpin { /// Error type returned when bucket capacity cannot be retrieved. @@ -76,7 +76,6 @@ pub trait SaltEnv: Debug + Unpin { /// Maps an account address to its bucket ID. /// /// This method determines which bucket tracks the account creation gas costs. - /// The default implementation can be overridden to customize bucket assignment. /// /// # Arguments /// @@ -86,7 +85,6 @@ pub trait SaltEnv: Debug + Unpin { /// Maps a storage slot to its bucket ID. /// /// This method determines which bucket tracks the storage slot's gas costs. - /// The default implementation can be overridden to customize bucket assignment. /// /// # Arguments /// diff --git a/crates/mega-evm/src/external/test_utils.rs b/crates/mega-evm/src/external/test_utils.rs index 53b02f404..67093120e 100644 --- a/crates/mega-evm/src/external/test_utils.rs +++ b/crates/mega-evm/src/external/test_utils.rs @@ -163,11 +163,6 @@ impl self.recorded_hints.borrow().clone() } - /// Clears all recorded hints. - pub fn clear_recorded_hints(&self) { - self.recorded_hints.borrow_mut().clear(); - } - /// Configures a bucket to have a specific capacity. /// /// This affects the gas multiplier calculation for operations on accounts or storage @@ -194,14 +189,6 @@ impl self } - /// Removes all configured bucket capacities. - /// - /// After calling this, all buckets will return the configured `default_bucket_capacity` if - /// set, otherwise [`MIN_BUCKET_SIZE`](crate::MIN_BUCKET_SIZE). - pub fn clear_bucket_capacity(&self) { - self.bucket_capacity.borrow_mut().clear(); - } - /// Makes the capacity query of `bucket_id` fail with `error`, whatever capacity it carries. /// /// This is what an unreachable SALT backend looks like to the engine: the state gas charge @@ -222,11 +209,6 @@ impl self.bucket_queries.borrow().values().sum() } - /// Forgets the capacity queries counted so far. - pub fn clear_bucket_queries(&self) { - self.bucket_queries.borrow_mut().clear(); - } - /// Configures a storage slot in the oracle contract to have a specific value. /// /// # Arguments diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 0e8b96e4d..28f859579 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -2,7 +2,13 @@ //! //! Satin runs a single spec, [`MegaSpecId::SATIN`], on op-revm's Karst handler with EIP-8037 //! state gas and the EIP-2780 intrinsic cost. The legacy engine (specs `Equivalence` through -//! `Rex7`) is a separate crate line; nothing here executes a legacy spec. +//! `Rex6`) is a separate crate line; nothing here executes a legacy spec. +//! +//! A volatile read that `MegaAccessControl`'s switch refuses reverts its frame with +//! `VolatileDataAccessDisabled(uint8 accessType)`. A refused `SLOTNUM` names access type 12 +//! ([`system::SLOT_NUM_ACCESS_TYPE`]), past the last variant of the contract's +//! `VolatileDataAccessType`, so a Solidity handler must decode the argument as `uint8`; +//! [`decode_volatile_data_access_disabled`] decodes it on the Rust side. #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] @@ -21,11 +27,60 @@ pub mod system; pub mod test_utils; mod types; -pub use block::*; -pub use evm::*; -pub use external::*; -pub use limit::*; -pub use types::*; +pub use access::{ + decode_volatile_data_access_disabled, volatile_data_access_disabled_revert_data, Detention, + VolatileDataAccess, +}; +pub use block::{ + chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, + pre_block_call_gas_limit, read_l1_block_info, testnet_hardforks, + transact_beacon_root_contract_call, transact_blockhashes_contract_call, BlockGasCounters, + BlockLimiter, BlockLimits, BlockUsage, ChainActivation, EnrichedMegaTx, MegaBlockExecutionCtx, + MegaBlockExecutionError, MegaBlockExecutionResult, MegaBlockExecutor, MegaBlockExecutorFactory, + MegaBlockLimitExceededError, MegaBlockTxResult, MegaFinishedBlock, MegaHardfork, + MegaHardforkConfig, MegaHardforks, MegaTransactionExt, MegaTxLimitExceededError, + ProtocolLimits, SatinChainConfig, SatinChainConfigError, ScheduleError, CHAIN_ACTIVATIONS, + L1_BLOCK_INFO_SLOTS, MAINNET_CHAIN_ID, SATIN_CHAIN_CONFIG_KEYS, SATIN_TIME_KEY, SYSTEM_ADDRESS, + TESTNET_CHAIN_ID, +}; +#[cfg(feature = "satin-price-override")] +pub use evm::install_satin_prices; +pub use evm::{ + active_satin_prices, history_gas, kzg_point_evaluation, name, satin_gas_params, + satin_gas_params_at, satin_gas_params_history_exempt, satin_precompiles, satin_precompiles_map, + settle_frame_result, spec_cfg, storage_call_stipend, synthetic_call_result, + synthetic_frame_result, transaction_body_bytes, tx_body_history_bytes, untouched_call_gas, + untouched_create_gas, validate_transaction_stateless, with_pools_of, write_record_history_gas, + BlockHashRecord, BucketRecord, BytePrice, DeclaredObserver, DynPrecompilesBuilder, EthSpecId, + IntrinsicGas, MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, + MegaSpecId, MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, + SatinPriceError, SatinPrices, TrustedObserver, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, + LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, +}; +#[cfg(any(test, feature = "test-utils"))] +pub use external::{ + AHashBucketHasher, BucketHasher, RecordedHint, SimpleBucketHasher, TestExternalEnvs, +}; +pub use external::{ + BucketError, BucketId, BucketMultipliers, EmptyExternalEnv, ExternalEnvFactory, + ExternalEnvTypes, ExternalEnvs, OracleEnv, SaltEnv, MIN_BUCKET_SIZE, MIN_BUCKET_SIZE_BITS, +}; +pub use limit::{ + decode_mega_limit_exceeded, log_history_bytes, AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, + LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, StagedRecord, ACCESS_LIST_ADDRESS_SIZE, + ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BASE_SIZE, + TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, +}; +pub use types::{ + MegaHaltReason, MegaTransaction, MegaTransactionError, MegaTxEnvelope, MegaTxType, +}; + +/* Items the crate's modules share through the root, not part of the public surface */ +pub(crate) use block::transact_pre_block_call; +pub(crate) use evm::{ + charge_write_records_history, MegaInnerContext, MegaInstructions, PricedPrecompiles, +}; /* Re-export of upstream crates, so consumers build against the exact versions used here */ pub use alloy_consensus; @@ -37,25 +92,3 @@ pub use alloy_sol_types; pub use op_alloy_consensus; pub use op_revm; pub use revm; - -/* Short aliases of the mega-evm types */ -/// Alias for [`MegaSpecId`] -pub type SpecId = MegaSpecId; -/// Alias for [`MegaTransaction`] -pub type Transaction = MegaTransaction; -/// Alias for [`MegaHaltReason`] -pub type HaltReason = MegaHaltReason; -/// Alias for [`MegaTransactionError`] -pub type TransactionError = MegaTransactionError; -/// Alias for [`MegaTxType`] -pub type TxType = MegaTxType; -/// Alias for [`MegaEvm`] -pub type Evm = MegaEvm; -/// Alias for [`MegaEvmFactory`] -pub type EvmFactory = MegaEvmFactory; -/// Alias for [`MegaContext`] -pub type Context = MegaContext; -/// Alias for [`MegaBlockExecutor`] -pub type BlockExecutor = MegaBlockExecutor; -/// Alias for [`MegaBlockExecutorFactory`] -pub type BlockExecutorFactory = MegaBlockExecutorFactory; diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs index 14103a4bc..6c6d19214 100644 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ b/crates/mega-evm/src/limit/frame_limit.rs @@ -6,6 +6,10 @@ //! records of applied EIP-7702 authorities) and what the outermost frame kept sit on the //! transaction's own lane. //! +//! The history bytes a frame appends beside its write records — its logs, and the code it +//! deposits when it is a creation — ride on the same lanes and follow the same rule, so what a +//! transaction reports it appended is what it kept. +//! //! Every operation is O(1): the totals are cached and kept in step with each change. #[cfg(not(feature = "std"))] @@ -19,6 +23,17 @@ use super::{LimitUsage, WRITE_RECORD}; /// One frame's lane. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Lane { + /// History gas the caller paid for the records on this lane, which the frame's failure gives + /// back to it. + pub(crate) history_charge: u64, + /// History gas the caller paid for the record of its own account + /// ([`holds_caller_record`](Self::holds_caller_record)), which follows that record's own + /// lifetime: a value transfer's sender record dies with the frame, a creation's nonce record + /// outlives it. + pub(crate) caller_history_charge: u64, + /// Whether the writes this lane stands for were recorded at all. False for a frame answered + /// without running, whose caller paid for records nothing ever made. + pub(crate) records_made: bool, /// What the frame, and the children it kept, counted. pub(crate) used: LimitUsage, /// What the frame, and the children it kept, took back: a slot written back to its original @@ -36,27 +51,84 @@ pub(crate) struct Lane { /// Whether the caller's record on this lane is a creator's nonce, which survives the /// creation's failure once the nonce was bumped. pub(crate) creator_record: bool, - /// The most data-size bytes the frame may keep; `u64::MAX` when it has no budget. + /// The most data-size bytes the frame may keep, `u64::MAX` where the frame has no budget. pub(crate) budget: u64, + /// What is left of the history allowance this frame was granted, if it was granted one. It + /// never enters the frame's gas, and what it does not spend disappears with the frame. + pub(crate) stipend_remaining: u64, + /// The history bytes the frame, and the children it kept, appended that are not write + /// records: the logs it emitted and, when it is a creation, the code it deposits. Its write + /// records are history too, and are counted in [`used`](Self::used), as are these bytes. + pub(crate) log_and_code_bytes: u64, } impl Lane { - /// A lane for a frame running as `address`. - pub(crate) const fn new(address: Option
, account_recorded: bool, budget: u64) -> Self { + /// A lane for a frame running as `address`, whose caller paid `history_charge` for the + /// records the frame's start makes on it. + pub(crate) const fn new( + address: Option
, + account_recorded: bool, + budget: u64, + history_charge: u64, + ) -> Self { Self { used: LimitUsage::ZERO, refund: LimitUsage::ZERO, + history_charge, + caller_history_charge: 0, + records_made: true, address, account_recorded, holds_caller_record: false, creator_record: false, budget, + stipend_remaining: 0, + log_and_code_bytes: 0, + } + } + + /// A lane for a frame that does not run: a result built without an interpreter. Its caller + /// paid `history_charge` for records nothing made, so all of it comes back. + pub(crate) const fn empty(history_charge: u64) -> Self { + Self { records_made: false, ..Self::new(None, false, u64::MAX, history_charge) } + } + + /// The history gas the caller gets back when this frame returns. + /// + /// Everything, when the writes were never recorded; what the frame's failure discards, when + /// they were; nothing, when the frame kept them. A creation's nonce record survives the + /// creation's failure, so the caller keeps paying for it. + pub(crate) const fn history_refund(&self, success: bool) -> u64 { + if !self.records_made { + return self.history_charge.saturating_add(self.caller_history_charge); + } + if success { + return 0; + } + if self.creator_record { + self.history_charge + } else { + self.history_charge.saturating_add(self.caller_history_charge) } } - /// A lane for a frame that does not run: a result built without an interpreter. - pub(crate) const fn empty() -> Self { - Self::new(None, false, u64::MAX) + /// Whether the frame's return hands its caller what no check held the caller to: a failed + /// creation's nonce record, which outlives it and lands on the creator's lane + /// ([`FrameLimitTracker::pop`]), or a success past the frame's own budget, which no frame + /// returns — a frame past its budget failed, and a failure an inspector rewrites into a success + /// has its lane discarded first ([`FrameLimitTracker::discard_running_lane`]) — and which is + /// held all the same. + /// + /// Any other return hands the caller nothing, or what the frame kept within its budget, which + /// is at most the share of what the caller had left. + pub(crate) const fn hands_caller_unchecked(&self, success: bool) -> bool { + if success { + // A lane that stands in for a creation's discarded one carries its creator's nonce + // record, which the discard already landed on the creator. + self.net().exceeds_data_size(self.budget) || (!self.records_made && self.creator_record) + } else { + self.creator_record + } } /// What the frame keeps if it succeeds. @@ -83,6 +155,8 @@ pub(crate) struct FrameLimitTracker { total_used: LimitUsage, /// `tx_refund` plus every lane's `refund`. total_refund: LimitUsage, + /// The log and code bytes the outermost frame kept, plus every lane's. + log_and_code_bytes: u64, } impl FrameLimitTracker { @@ -93,6 +167,7 @@ impl FrameLimitTracker { self.lanes.clear(); self.total_used = LimitUsage::ZERO; self.total_refund = LimitUsage::ZERO; + self.log_and_code_bytes = 0; } /// The number of lanes, which is the number of frames on the call stack. @@ -105,6 +180,12 @@ impl FrameLimitTracker { self.total_used.saturating_sub(self.total_refund) } + /// The history bytes the transaction appended beside its write records — its logs and the + /// code it deposited — with every running frame counted as if it succeeds. + pub(crate) const fn log_and_code_bytes(&self) -> u64 { + self.log_and_code_bytes + } + /// The running frame's lane. pub(crate) fn current(&self) -> Option<&Lane> { self.lanes.last() @@ -115,6 +196,25 @@ impl FrameLimitTracker { self.lanes.last_mut() } + /// Grants the running frame a history allowance of `amount`. + /// + /// Must run right after the frame's lane was pushed: the allowance belongs to the frame that + /// is starting, not to the one that granted it. + pub(crate) fn grant_stipend(&mut self, amount: u64) { + if let Some(lane) = self.lanes.last_mut() { + lane.stipend_remaining = amount; + } + } + + /// Draws up to `amount` from the running frame's allowance and reports what it gave. The + /// caller pays the rest out of the frame's gas. + pub(crate) fn consume_stipend(&mut self, amount: u64) -> u64 { + let Some(lane) = self.lanes.last_mut() else { return 0 }; + let drawn = lane.stipend_remaining.min(amount); + lane.stipend_remaining -= drawn; + drawn + } + /// Pushes the lane of a frame that starts. pub(crate) fn push(&mut self, lane: Lane) { self.total_used = self.total_used.saturating_add(lane.used); @@ -131,6 +231,15 @@ impl FrameLimitTracker { self.total_used = self.total_used.saturating_add(usage); } + /// Counts `bytes` of a log or of deposited code on the running frame's lane, or on the + /// transaction's outside any frame. + pub(crate) fn record_log_and_code_bytes(&mut self, bytes: u64) { + if let Some(lane) = self.lanes.last_mut() { + lane.log_and_code_bytes = lane.log_and_code_bytes.saturating_add(bytes); + } + self.log_and_code_bytes = self.log_and_code_bytes.saturating_add(bytes); + } + /// Counts `usage` on the transaction's own lane, whatever frame is running: what it stands /// for is outside the state, so no frame's failure takes it back. pub(crate) fn record_tx(&mut self, usage: LimitUsage) { @@ -147,10 +256,11 @@ impl FrameLimitTracker { } /// Records the running frame's caller's account on the running frame's lane, unless the - /// caller's lane already counts it. A `creator` record is a creation's nonce. + /// caller's lane already counts it. A `creator` record is a creation's nonce, and + /// `history_charge` is what the caller paid for the record. /// /// Must run right after the running frame's lane was pushed, with the caller's lane below it. - pub(crate) fn record_caller(&mut self, creator: bool) { + pub(crate) fn record_caller(&mut self, creator: bool, history_charge: u64) { let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; if caller.account_recorded { return; @@ -158,29 +268,50 @@ impl FrameLimitTracker { caller.account_recorded = true; lane.holds_caller_record = true; lane.creator_record = creator; + lane.caller_history_charge = history_charge; lane.used = lane.used.saturating_add(WRITE_RECORD); self.total_used = self.total_used.saturating_add(WRITE_RECORD); } - /// Drops the caller's record from the running frame's lane: the frame failed before the - /// write it stands for happened (a creation that did not bump the creator's nonce). - pub(crate) fn drop_caller_record(&mut self) { - let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; - if !lane.holds_caller_record { - return; + /// Settles the running frame's lane as its failure would, before the frame returns: what it + /// counted is discarded, its caller's record with it, and an empty lane stands in for it, + /// holding the history its caller gets back for records the failure did not keep. So the frame + /// returns into its caller as a frame that made nothing, whatever it is popped with. + /// + /// For a frame whose journal checkpoint was reverted and whose result then became a success + /// all the same: the lane follows the checkpoint, not the result. + /// + /// A creation's nonce record outlives its failure, so it has landed on the creator's lane + /// unchecked, and the stand-in remembers it: the creator is held to its budget when the + /// stand-in returns, as it is when the creation fails. + pub(crate) fn discard_running_lane(&mut self) { + let Some(lane) = self.pop(false) else { return }; + let mut standing_in = Lane::empty(lane.history_refund(false)); + standing_in.creator_record = lane.creator_record; + self.lanes.push(standing_in); + } + + /// Takes the record of the running frame's own account back from its lane, where a child + /// left it: the nonce record of a creation that failed, whose bump is being taken back. + /// Returns whether the account was recorded, and so whether there was a record to take. + pub(crate) fn take_back_own_record(&mut self) -> bool { + let Some(lane) = self.lanes.last_mut() else { return false }; + if !lane.account_recorded { + return false; } - caller.account_recorded = false; - lane.holds_caller_record = false; - lane.creator_record = false; + lane.account_recorded = false; lane.used = lane.used.saturating_sub(WRITE_RECORD); self.total_used = self.total_used.saturating_sub(WRITE_RECORD); + true } /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or /// the transaction's), a failure discards it. /// - /// A creator's record outlives the creation's failure; any other record of the caller dies - /// with it, and the caller's account stops counting as recorded. + /// A creator's record outlives the creation's failure and lands on the caller's lane, which + /// nothing here holds to its budget; any other record of the caller dies with it, and the + /// caller's account stops counting as recorded. + #[inline] pub(crate) fn pop(&mut self, success: bool) -> Option { let lane = self.lanes.pop()?; if success { @@ -188,6 +319,8 @@ impl FrameLimitTracker { Some(caller) => { caller.used = caller.used.saturating_add(lane.used); caller.refund = caller.refund.saturating_add(lane.refund); + caller.log_and_code_bytes = + caller.log_and_code_bytes.saturating_add(lane.log_and_code_bytes); if lane.address.is_some() && lane.address == caller.address { caller.account_recorded |= lane.account_recorded; } @@ -201,6 +334,7 @@ impl FrameLimitTracker { } self.total_used = self.total_used.saturating_sub(lane.used); self.total_refund = self.total_refund.saturating_sub(lane.refund); + self.log_and_code_bytes = self.log_and_code_bytes.saturating_sub(lane.log_and_code_bytes); if let Some(caller) = self.lanes.last_mut() { if lane.creator_record { caller.used = caller.used.saturating_add(WRITE_RECORD); @@ -212,6 +346,16 @@ impl FrameLimitTracker { Some(lane) } + /// Whether the return of `returned`, the lane just popped with `success`, handed the running + /// frame what no check held it to ([`Lane::hands_caller_unchecked`]). + /// + /// A return into no lane hands nothing that needs holding: what the transaction's own frame + /// keeps goes to the transaction, which has no budget of its own and whose total the return + /// does not grow, and no frame runs on after it. + pub(crate) fn hands_unchecked(&self, returned: &Lane, success: bool) -> bool { + !self.lanes.is_empty() && returned.hands_caller_unchecked(success) + } + /// [`net`](Self::net) recomputed from the lanes, for checking the cache. #[cfg(test)] pub(crate) fn net_uncached(&self) -> LimitUsage { @@ -236,14 +380,34 @@ mod tests { LimitUsage { data_size, write_records: 0 } } + /// The depth and the running lane follow the frame stack: a push adds a lane and a pop takes + /// the running one away, whatever the frame's outcome. + #[test] + fn test_depth_and_the_running_lane_follow_the_frame_stack() { + let mut t = FrameLimitTracker::default(); + assert_eq!(t.depth(), 0); + assert!(t.current().is_none(), "no frame has started"); + t.push(Lane::new(Some(ADDR), false, 7, 0)); + t.push(Lane::empty(0)); + assert_eq!(t.depth(), 2); + assert_eq!(t.current().unwrap().address, None, "the empty lane is the running one"); + assert!(t.pop(false).is_some()); + assert_eq!(t.depth(), 1); + assert_eq!(t.current().unwrap().budget, 7); + assert!(t.pop(true).is_some()); + assert_eq!(t.depth(), 0); + assert!(t.current().is_none()); + assert!(t.pop(true).is_none(), "there is nothing left to pop"); + } + /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. #[test] fn test_record_caller_without_a_caller_lane_is_noop() { let mut t = FrameLimitTracker::default(); - t.record_caller(true); + t.record_caller(true, 0); assert_eq!(t.net(), LimitUsage::ZERO); - t.push(Lane::new(Some(ADDR), false, u64::MAX)); - t.record_caller(true); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.record_caller(true, 0); assert_eq!(t.net(), LimitUsage::ZERO); assert!(!t.current().unwrap().holds_caller_record); } @@ -252,12 +416,12 @@ mod tests { #[test] fn test_record_caller_records_a_caller_once() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX)); - t.push(Lane::new(None, true, u64::MAX)); - t.record_caller(true); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(true, 0); assert!(t.pop(true).is_some()); - t.push(Lane::new(None, true, u64::MAX)); - t.record_caller(true); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(true, 0); assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); assert_eq!(t.net(), WRITE_RECORD); } @@ -276,19 +440,19 @@ mod tests { assert_eq!(t.net(), bytes(100)); // Frame 1. - t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); t.record(bytes(30)); t.refund(bytes(10)); assert_eq!(t.net(), t.net_uncached()); // Frame 2, nested. - t.push(Lane::new(None, false, u64::MAX)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(15)); t.refund(bytes(3)); assert_eq!(t.net(), t.net_uncached()); // Frame 3 fails: its usage and refund leave the totals. - t.push(Lane::new(None, false, u64::MAX)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(11)); t.refund(bytes(2)); let before_revert = t.net(); @@ -298,7 +462,7 @@ mod tests { assert_eq!(t.net(), bytes(before_revert.data_size - 9)); // Frame 3 again, succeeding: merging moves usage, the totals do not change. - t.push(Lane::new(None, false, u64::MAX)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(6)); t.refund(bytes(1)); let before_success = t.net(); @@ -320,11 +484,50 @@ mod tests { assert_eq!(t.depth(), 0); } + /// Log and code bytes follow the frame that appended them: a running frame counts as if it + /// succeeds, a success hands them to its caller, a failure discards them, and what was + /// counted outside any frame is the transaction's. + #[test] + fn test_log_and_code_bytes_follow_their_frame() { + let mut t = FrameLimitTracker::default(); + t.record_log_and_code_bytes(5); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.record_log_and_code_bytes(10); + t.push(Lane::new(None, false, u64::MAX, 0)); + t.record_log_and_code_bytes(100); + assert_eq!(t.log_and_code_bytes(), 115); + + let failed = t.pop(false).expect("the child popped"); + assert_eq!(failed.log_and_code_bytes, 100); + assert_eq!(t.log_and_code_bytes(), 15, "the failed child's bytes are gone"); + + t.push(Lane::new(None, false, u64::MAX, 0)); + t.record_log_and_code_bytes(20); + t.pop(true); + assert_eq!(t.log_and_code_bytes(), 35); + assert_eq!( + t.current().unwrap().log_and_code_bytes, + 30, + "the kept child's are its caller's" + ); + + t.pop(false); + assert_eq!(t.log_and_code_bytes(), 5, "only what was outside the outermost frame is left"); + + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.record_log_and_code_bytes(7); + t.pop(true); + assert_eq!(t.log_and_code_bytes(), 12, "the outermost frame's success keeps its bytes"); + + t.reset(); + assert_eq!(t.log_and_code_bytes(), 0); + } + /// A refund larger than the usage clamps the net at zero. #[test] fn test_net_usage_saturates_when_refund_exceeds_used() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(None, false, u64::MAX)); + t.push(Lane::new(None, false, u64::MAX, 0)); t.record(bytes(10)); t.refund(bytes(100)); assert_eq!(t.net(), LimitUsage::ZERO); @@ -339,17 +542,17 @@ mod tests { #[test] fn test_failed_child_discards_sender_record_but_keeps_creator_record() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, u64::MAX)); - t.record_caller(false); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(false, 0); t.record(WRITE_RECORD); t.pop(false); assert_eq!(t.net(), LimitUsage::ZERO); assert!(!t.current().unwrap().account_recorded, "the sender record died with the child"); - t.push(Lane::new(None, true, u64::MAX)); - t.record_caller(true); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(true, 0); t.record(WRITE_RECORD); t.pop(false); assert_eq!(t.net(), WRITE_RECORD, "the creator's nonce outlives the creation"); @@ -357,19 +560,122 @@ mod tests { assert_eq!(t.net(), t.net_uncached()); } - /// A creation that fails before bumping the nonce takes the creator record back. + /// A return hands its caller what no check held the caller to in two cases: the nonce record + /// a failed creation leaves its creator, and a success past the frame's own budget. A success + /// within its budget hands over no more than that budget, and any other failure hands over + /// nothing. + #[test] + fn test_what_a_return_hands_its_caller_unchecked() { + let budget = 200; + // The record of the caller's account the child holds (a creator's or a sender's), the + // bytes it counted beside it, and whether it succeeded. + for (creator, counted, success, unchecked) in [ + (false, 160, true, false), + (true, 160, true, false), + (false, 161, true, true), + (false, 161, false, false), + (false, 0, false, false), + (true, 0, false, true), + ] { + let case = format!("creator {creator}, {counted} bytes, success {success}"); + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.push(Lane::new(None, true, budget, 0)); + t.record_caller(creator, 0); + t.record(bytes(counted)); + let lane = t.pop(success).unwrap(); + assert_eq!(lane.hands_caller_unchecked(success), unchecked, "{case}"); + let handed = t.net(); + let past_budget = handed.exceeds_data_size(budget); + if success { + assert_eq!(past_budget, unchecked, "{case}: a success hands over what it kept"); + } else { + assert_eq!(handed != LimitUsage::ZERO, unchecked, "{case}: a failure, the record"); + } + } + } + + /// The return of the transaction's own frame hands nothing unchecked, whatever it kept: there + /// is no lane left to hand it to. With a frame below it, the same return does. + #[test] + fn test_a_return_into_no_lane_hands_nothing_unchecked() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, 200, 0)); + t.record(bytes(201)); + let lane = t.pop(true).unwrap(); + assert!(lane.hands_caller_unchecked(true), "it kept more than its budget"); + assert!(!t.hands_unchecked(&lane, true), "but no frame is left to hand it to"); + + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + assert!(t.hands_unchecked(&lane, true), "a caller is"); + assert!(!t.hands_unchecked(&lane, false), "which a failure hands nothing"); + } + + /// A lane discarded before its frame returns keeps nothing, whatever it is popped with: what + /// it counted leaves the totals, its caller's account stops counting as recorded, and the + /// empty lane in its place hands the caller back what the failure gives back — here the + /// charges for the lane's record and for the caller's own. + #[test] + fn test_a_discarded_lane_keeps_nothing_and_gives_the_failures_history_back() { + let mut t = FrameLimitTracker::default(); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.record(bytes(10)); + t.push(Lane::new(None, false, 100, 7)); + t.record_caller(false, 3); + t.record(WRITE_RECORD); + t.record_log_and_code_bytes(5); + t.discard_running_lane(); + + assert_eq!(t.depth(), 2, "an empty lane stands in for the frame"); + let lane = *t.current().unwrap(); + assert!(!lane.records_made); + assert_eq!(lane.used, LimitUsage::ZERO); + assert_eq!(lane.address, None); + assert_eq!(lane.budget, u64::MAX); + assert_eq!(t.net(), bytes(10), "only the caller's count is left"); + assert_eq!(t.net(), t.net_uncached()); + assert_eq!(t.log_and_code_bytes(), 0); + assert!(!t.lanes[0].account_recorded, "the caller's record went with the frame"); + + let popped = t.pop(true).unwrap(); + assert_eq!(popped.history_refund(true), 7 + 3, "the lane's record and the caller's"); + assert!(!t.hands_unchecked(&popped, true), "it hands nothing"); + assert_eq!(t.net(), bytes(10)); + + // A creator's nonce record outlives the creation: the discard lands it on the creator, + // and the history the creator paid for it is not given back. + t.push(Lane::new(None, false, u64::MAX, 0)); + t.record_caller(true, 4); + t.discard_running_lane(); + assert_eq!(t.net(), bytes(10).saturating_add(WRITE_RECORD)); + let popped = t.pop(true).unwrap(); + assert_eq!(popped.history_refund(true), 0); + assert!(t.hands_unchecked(&popped, true), "the creator is held to its budget with it"); + + // With no lane to discard, nothing happens. + let mut empty = FrameLimitTracker::default(); + empty.discard_running_lane(); + assert_eq!(empty.depth(), 0); + } + + /// The creator record a failed creation left its creator is taken back once, and a lane with + /// no record of its own account has nothing to take. #[test] - fn test_drop_caller_record_rearms_the_caller() { + fn test_take_back_own_record_takes_the_creator_record_once() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX)); - t.push(Lane::new(None, true, u64::MAX)); - t.record_caller(true); - t.drop_caller_record(); - t.drop_caller_record(); - assert_eq!(t.net(), LimitUsage::ZERO); - assert!(!t.lanes[0].account_recorded); + assert!(!t.take_back_own_record(), "no lane"); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.record(bytes(7)); + t.push(Lane::new(None, true, u64::MAX, 0)); + t.record_caller(true, 0); t.pop(false); - assert_eq!(t.net(), LimitUsage::ZERO); + assert_eq!(t.net(), bytes(7).saturating_add(WRITE_RECORD)); + + assert!(t.take_back_own_record()); + assert_eq!(t.net(), bytes(7), "the record, and nothing else, is gone"); + assert!(!t.current().unwrap().account_recorded); + assert!(!t.take_back_own_record(), "taken once"); + assert_eq!(t.net(), bytes(7)); assert_eq!(t.net(), t.net_uncached()); } @@ -377,23 +683,23 @@ mod tests { #[test] fn test_same_account_child_merges_the_recorded_flag() { let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX)); - t.push(Lane::new(Some(ADDR), true, u64::MAX)); + t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); + t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); t.pop(true); assert!(t.current().unwrap().account_recorded); let other = address!("0000000000000000000000000000000000005678"); - t.push(Lane::new(Some(other), false, u64::MAX)); - t.push(Lane::new(Some(other), false, u64::MAX)); + t.push(Lane::new(Some(other), false, u64::MAX, 0)); + t.push(Lane::new(Some(other), false, u64::MAX, 0)); t.current_mut().unwrap().account_recorded = true; t.pop(false); assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); - t.push(Lane::new(Some(ADDR), true, u64::MAX)); + t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); assert_eq!(t.depth(), 3); t.pop(true); assert!(!t.current().unwrap().account_recorded, "another account's flag is its own"); - t.push(Lane::new(None, true, u64::MAX)); + t.push(Lane::new(None, true, u64::MAX, 0)); t.pop(true); assert!(!t.current().unwrap().account_recorded, "an unknown account is not the caller's"); } diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index d6622c6ff..6cc04a504 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,43 +1,69 @@ //! The per-transaction state of the common execution layer. -use alloy_primitives::Address; +use alloy_primitives::{Address, Bytes}; use revm::{ + context_interface::context::CodeDeposit, handler::FrameResult, - interpreter::{FrameInput, InstructionResult}, + interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, }; use super::{ frame_limit::{FrameLimitTracker, Lane}, - record::{RecordEffect, StagedRecord}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, WRITE_RECORD, + record::{HistoryBytes, RecordEffect, StagedRecord}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, }; +use crate::storage_call_stipend; /// What the common execution layer tracks for the running transaction: the per-frame lanes of -/// data-size bytes and write records, the record the Host staged for the running opcode, and the -/// latch of a transaction a limit stopped. +/// data-size bytes and write records, the record the Host staged for the running opcode, the stops +/// its frames return, and whether it is exempt from every limit. /// /// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and /// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) -/// and the frame lifecycle (lanes, the latch). +/// and the frame lifecycle (lanes, stops). /// -/// # The abort protocol +/// # The stop /// -/// A transaction-level limit stops the transaction with a revert, not a halt. The frame that -/// crosses the limit reverts with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output -/// and the transaction is latched ([`latch`](Self::latch)). From then on no frame runs another -/// instruction: a caller that gets the reverted result back returns the same revert instead of -/// resuming, a frame about to start is answered with it, and every result returned above is -/// rewritten to it. The outermost frame settles like any EIP-8037 revert: its unspent regular gas -/// and the reservoir go back to the sender, who pays only for what ran. A frame budget crossed -/// reverts that frame alone, without a latch, and its caller resumes. Exceptional halts (a real -/// out-of-gas, an invalid opcode) are not limit stops and still burn the frame's gas. +/// A limit crossed stops the frame that crossed it with a revert, not a halt: the frame reverts +/// with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output, whether it crossed the +/// transaction's limit or its own frame budget, and its caller resumes as after any revert. What +/// the frame counted goes with it, so a caller that resumes is back within the limits, and a +/// transaction never keeps more than its limit: a caller that carries on is held to what is left, +/// and a charge that crosses again stops the frame that makes it. A crossing the transaction's +/// own frame makes is the transaction's result, which settles like any EIP-8037 revert: its +/// unspent regular gas and the reservoir go back to the sender, who pays only for what ran. +/// Exceptional halts (a real out-of-gas, an invalid opcode) are not limit stops and still burn the +/// frame's gas. +/// +/// # The exemption +/// +/// The protocol's own work is held to none of the per-transaction limits: a system-originated +/// transaction and a system call are marked exempt before their body is counted, and the mark is +/// sticky for the transaction ([`is_exempt`](Self::is_exempt)). Every stop the layer hands out +/// comes from one place ([`crossed`](Self::crossed)), which answers an exempt transaction with +/// [`LimitCheck::WithinLimit`] whatever it crossed — a transaction limit or a frame budget, in +/// any dimension. +/// What the transaction uses is counted all the same, so its usage is reported as any other +/// transaction's is. #[derive(Clone, Debug, Default)] pub struct AdditionalLimit { pub(crate) tracker: FrameLimitTracker, staged: Option, limits: EvmTxRuntimeLimits, - /// The transaction-level stop, once a limit latched one. - latched: Option, + /// Whether the transaction is exempt from every per-transaction limit, sticky for the + /// transaction. See [`exempt`](Self::exempt). + exempt: bool, + /// The stop the frame a child returned into must return instead of running on, when what the + /// child left it put it over a limit. See [`on_frame_return`](Self::on_frame_return). + resume_stop: Option, + /// The crossing the result of the frame returning next was made of, noted where the stop + /// became that result ([`note_frame_stop`](Self::note_frame_stop)) and taken when the frame + /// returns. + frame_stop: Option, + /// The crossing that produced the result of the transaction's own frame, if one did. See + /// [`limit_exceeded`](Self::limit_exceeded). + limit_exceeded: Option, /// Whether the transaction's call target is an applied EIP-7702 authority, whose account /// write the transaction's lane already counts. target_is_authority: bool, @@ -45,10 +71,42 @@ pub struct AdditionalLimit { /// running as the sender never records it. sender: Address, /// Whether the transaction's first frame reached frame init. When it did not, the runtime - /// phase before it ran out of gas and took back everything counted before it. + /// phase before it ran out of gas and took back the authorizations applied before it. The + /// body stays; see [`on_last_frame_return`](Self::on_last_frame_return). frame_began: bool, + /// Data-size bytes of the transaction's body. Recorded before any frame and kept on every + /// path, including an out-of-gas before the first frame, which clears the rest of the tracker. + body_bytes: u64, + /// The history gas validation charged for the transaction's body, part of + /// [`history_gas_spent`](Self::history_gas_spent). + intrinsic_history_gas: u64, + /// The bytes of the transaction's body that + /// [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid for, part of + /// [`history_bytes`](Self::history_bytes). + intrinsic_history_bytes: u64, + /// The history gas of the write record the transaction's own frame makes — its value's + /// recipient, or the account it creates — charged before the first frame and given back when + /// that frame fails. + top_level_write_record_gas: u64, + /// The write records the transaction's own frame makes, as the charge of their history before + /// execution found them, for [`push_lane`](Self::push_lane) to check its own count against. + /// See [`stage_top_level_records`](Self::stage_top_level_records). + pending_top_level_records: Option, + /// The history gas the running opcode charged its own frame for the records the frame it is + /// starting will make, waiting for that frame's lane to be pushed. + pending_frame_charge: FrameCharge, + /// Whether revm refuses, on its caller's account, the start of the frame the last + /// frame-starting opcode suspended on — or, before the first frame, the transaction's own + /// frame — as that opcode, or the charge of the transaction's record, found it. See + /// [`stage_start_refused`](Self::stage_start_refused). + pending_start_refused: Option, /// The history gas the settled transaction spent. history_gas_spent: u64, + /// The history bytes the settled transaction appended. + history_bytes: u64, + /// Whether the running transaction's value movements journal EIP-7708 transfer logs, which + /// revm emits itself and the data size counts where the value moves. + transfer_logs: bool, } impl AdditionalLimit { @@ -71,62 +129,123 @@ impl AdditionalLimit { pub(crate) fn reset(&mut self) { self.tracker.reset(); self.staged = None; - self.latched = None; + self.exempt = false; + self.resume_stop = None; + self.frame_stop = None; + self.limit_exceeded = None; self.target_is_authority = false; self.sender = Address::ZERO; self.frame_began = false; + self.body_bytes = 0; + self.intrinsic_history_gas = 0; + self.intrinsic_history_bytes = 0; + self.top_level_write_record_gas = 0; + self.pending_top_level_records = None; + self.pending_frame_charge = FrameCharge::NONE; + self.pending_start_refused = None; self.history_gas_spent = 0; + self.history_bytes = 0; + self.transfer_logs = false; } - /* The latch */ + /// Records whether the running transaction's value movements journal EIP-7708 transfer logs. + /// Called for every transaction, after the reset, from the configuration revm emits them by. + pub(crate) const fn set_transfer_logs(&mut self, emitted: bool) { + self.transfer_logs = emitted; + } - /// The stop a transaction-level limit latched, if any. - pub const fn latched(&self) -> Option<&LimitCheck> { - self.latched.as_ref() + /// Whether starting `input` journals an EIP-7708 transfer log in the running transaction. + /// See [`moves_value`]. + pub(crate) fn frame_start_transfer_log(&self, input: &FrameInput) -> bool { + self.transfer_logs && moves_value(input) } - /// Latches the transaction: `kind`'s transaction-level `limit` was crossed at `used`. The - /// running frame must stop with [`LimitCheck::revert_data`]; the frame lifecycle stops every - /// frame above it. A later latch does not replace the first. - pub fn latch(&mut self, kind: LimitKind, limit: u64, used: u64) -> LimitCheck { - *self.latched.get_or_insert(LimitCheck::ExceedsLimit { - kind, - limit, - used, - frame_local: false, - }) + /* The stops and the exemption */ + + /// The crossing that produced the result of the transaction's own frame, if one did: what + /// [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome) reports. + /// + /// It is a crossing the transaction's own frame made, of the transaction's limit or of its own + /// budget. A crossing below that frame produced the result of the frame that crossed, which its + /// caller caught: a caller that then reverts with the same bytes made its own result, and is no + /// stop. Neither is a stop an inspector rewrote into another result: the frame's result must + /// still be the stop's revert. + /// + /// It is the running transaction's, or the last one's until the next transaction or system + /// call starts: each resets it first. + pub const fn limit_exceeded(&self) -> Option<&LimitCheck> { + self.limit_exceeded.as_ref() + } + + /// Notes `stop` as the crossing the result of the frame returning next is made of, and gives + /// the [`MegaLimitExceeded`](crate::MegaLimitExceeded) revert data that frame stops with. + /// + /// Every site that turns a crossing into a frame's result takes the revert data from here, and + /// the frame returns before any other does: so the stop is the returning frame's when + /// [`on_frame_return`](Self::on_frame_return) takes it, and the transaction's when that frame + /// is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). + pub(crate) fn note_frame_stop(&mut self, stop: &LimitCheck) -> Bytes { + debug_assert!(stop.exceeded_limit(), "only a crossing stops a frame"); + self.frame_stop = Some(*stop); + stop.revert_data() + } + + /// Whether the running transaction is exempt from every per-transaction limit. + pub const fn is_exempt(&self) -> bool { + self.exempt + } + + /// Exempts the running transaction from every per-transaction limit, until the next + /// transaction resets the layer. + /// + /// Called for the protocol's own work — a system-originated transaction and a system call — + /// before its body is counted. See the type's documentation. + pub(crate) const fn exempt(&mut self) { + self.exempt = true; + } + + /// The verdict on `used` crossing `kind`'s `limit`, a frame budget when `frame_local` and a + /// transaction-level limit otherwise: the stop the running frame reverts with, alone, its + /// [`LimitCheck::revert_data`] naming the limit crossed. + /// + /// Every stop the layer hands out comes from here, gas detention's included, so this is where + /// the exemption applies: an exempt transaction's verdict is [`LimitCheck::WithinLimit`], + /// whatever it crossed. + pub(crate) const fn crossed( + &self, + kind: LimitKind, + limit: u64, + used: u64, + frame_local: bool, + ) -> LimitCheck { + if self.exempt { + return LimitCheck::WithinLimit; + } + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Checks the limits after the running frame counted something: the transaction's data size - /// against its limit (latching on a crossing), then the running frame's against its budget. - fn check(&mut self) -> LimitCheck { - let used = self.tracker.net().data_size; - if used > self.limits.tx_data_size_limit { - return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); + /// Checks the data-size limit after the running frame counted something: what the + /// transaction keeps against its limit, then what the running frame keeps against its budget. + /// A record that crosses both names the transaction's limit. + fn check(&self) -> LimitCheck { + let (kept, limit) = (self.tracker.net(), self.limits.tx_data_size_limit); + if kept.exceeds_data_size(limit) { + return self.crossed(LimitKind::DataSize, limit, kept.data_size, false); } if let Some(lane) = self.tracker.current() { - let used = lane.net().data_size; - if used > lane.budget { - return LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: lane.budget, - used, - frame_local: true, - }; + let (kept, budget) = (lane.net(), lane.budget); + if kept.exceeds_data_size(budget) { + return self.crossed(LimitKind::DataSize, budget, kept.data_size, true); } } LimitCheck::WithinLimit } - /// Rewrites `result` to the latched stop, when the transaction is latched: a success or a - /// revert becomes the latched revert. A halt stays what it is. - fn apply_latch(&self, result: &mut FrameResult) { - let Some(latched) = &self.latched else { return }; - let interpreter_result = result.interpreter_result_mut(); - if interpreter_result.result.is_ok_or_revert() { - interpreter_result.result = InstructionResult::Revert; - interpreter_result.output = latched.revert_data(); - } + /// The stop the running frame returns instead of running another instruction: the one + /// [`on_frame_return`](Self::on_frame_return) left for a caller its child put over a limit. + /// Taking it clears it, which stops one frame. + pub(crate) const fn stop_before_run(&mut self) -> Option { + self.resume_stop.take() } /// What the transaction keeps so far: its data-size bytes and write records, with every @@ -140,6 +259,127 @@ impl AdditionalLimit { self.history_gas_spent } + /// The history gas validation charged for the transaction's body: the bytes the transaction + /// carries and the write records its inclusion makes, which are known before it runs. + /// + /// It rides in the EIP-8037 intrinsic state-gas slot, so the reservoir pays it first, and the + /// settled result takes it back out of the state gas it reports: it is history, not state. + pub const fn intrinsic_history_gas(&self) -> u64 { + self.intrinsic_history_gas + } + + /// Records the history gas validation charged for the transaction's body, and the `bytes` of + /// the body it paid for. + pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { + self.intrinsic_history_gas = gas; + self.intrinsic_history_bytes = bytes; + } + + /// The history bytes the last settled transaction appended, whoever paid for them, which a + /// transaction reports as [`MegaGasUsage::history_bytes`](crate::MegaGasUsage::history_bytes); + /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of + /// their price. + pub const fn history_bytes(&self) -> u64 { + self.history_bytes + } + + /// Settles [`history_bytes`](Self::history_bytes) from what the transaction kept: `priced` is + /// whether it pays history at all. Called once the outermost frame's lane is popped, when + /// everything the transaction kept sits on its own lane. + pub(crate) fn settle_history_bytes(&mut self, priced: bool) { + self.history_bytes = if priced { + self.intrinsic_history_bytes + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.tracker.net().write_records)) + .saturating_add(self.tracker.log_and_code_bytes()) + } else { + 0 + }; + } + + /// The history gas charged before the first frame for the write record that frame makes: the + /// recipient of the transaction's value, or the account it creates. + /// + /// A first frame that fails keeps no such write, so the charge is given back with the rest of + /// what the failure discards. + pub(crate) const fn top_level_write_record_gas(&self) -> u64 { + self.top_level_write_record_gas + } + + /// Records the history gas charged for the transaction's own write record. + pub(crate) const fn set_top_level_write_record_gas(&mut self, gas: u64) { + self.top_level_write_record_gas = gas; + } + + /// Leaves the write records the transaction's own frame makes, as the charge of their history + /// before execution found them, for [`push_lane`](Self::push_lane) to check its own count + /// against when it pushes that frame's lane + /// ([`check_top_level_records`](Self::check_top_level_records)). + /// + /// Only a transaction that pays history is charged, and so leaves one. A first frame answered + /// or refused before its lane is pushed leaves it for the next transaction's reset to clear. + pub(crate) const fn stage_top_level_records(&mut self, records: u64) { + self.pending_top_level_records = Some(records); + } + + /// Draws up to `amount` from the running frame's history allowance and reports what it gave; + /// the caller pays the rest out of the frame's own gas. + /// + /// Only a history charge may draw, and only the one a log makes: a write record, a state + /// charge and a unit of computation are all paid for by the frame's gas alone. See + /// [`storage_call_stipend`](crate::storage_call_stipend). + #[inline] + pub(crate) fn try_consume_stipend(&mut self, amount: u64) -> u64 { + self.tracker.consume_stipend(amount) + } + + /// Whether the transaction's call target is an applied EIP-7702 authority, whose account + /// write the transaction's own lane already counts, so its first frame writes no recipient. + pub(crate) const fn target_is_authority(&self) -> bool { + self.target_is_authority + } + + /// Leaves the history gas the running opcode just charged its frame for the records the frame + /// it starts will make: `on_lane` for the records that frame's failure discards, `caller` for + /// the record of the caller's own account, and `records`, the answer the charge was computed + /// from, for [`push_lane`](Self::push_lane) to check its own against. + /// + /// The next lane pushed takes it, whether that is the frame's own or the empty one of a frame + /// answered without running. + #[inline] + pub(crate) const fn stage_frame_charge( + &mut self, + records: FrameStartRecords, + on_lane: u64, + caller: u64, + ) { + self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; + } + + /// Leaves whether revm refuses the start of the frame about to start on its caller's account, + /// for the frame's init to take ([`take_start_refused`](Self::take_start_refused)) rather than + /// read the caller's account again: found by the opcode starting the frame, or, for the + /// transaction's own frame, by the charge of its record before execution. + /// + /// Only a start revm can refuse there — a call that transfers value, a creation — takes it. + /// One an opcode makes finds the answer that opcode staged, which stages one for every frame + /// it starts and so replaces whatever an earlier start left. The transaction's own frame finds + /// the one its record's charge staged, or none: the reset cleared what the transaction before + /// it left. A start answered before its init leaves its answer for no other start to take. + /// The one start past the first frame no opcode makes, a keyless deployment's creation, is + /// cleared for ([`set_frame_creator`](Self::set_frame_creator)), and so is every start on the + /// inspected path, whose inspector may rewrite the input. + #[inline] + pub(crate) const fn stage_start_refused(&mut self, refused: bool) { + self.pending_start_refused = Some(refused); + } + + /// Takes what [`stage_start_refused`](Self::stage_start_refused) left for the frame about to + /// start, if anything. + #[inline] + pub(crate) const fn take_start_refused(&mut self) -> Option { + self.pending_start_refused.take() + } + /// Records the history gas the settled transaction spent. pub(crate) const fn set_history_gas_spent(&mut self, history_gas_spent: u64) { self.history_gas_spent = history_gas_spent; @@ -158,75 +398,140 @@ impl AdditionalLimit { self.staged = Some(record); } - /// Commits the staged record to the running frame's lane. Called by an opcode's wrapper once - /// the opcode completed; a crossed limit in the verdict stops the opcode's frame. + /// Commits the staged record to the running frame's lane, and reports the history bytes it + /// appends or takes back. Called by an opcode's wrapper once the opcode completed; a crossed + /// limit in the verdict stops the opcode's frame, and the wrapper charges the history. + /// + /// A `SELFDESTRUCT` that moved value to another account also counts the EIP-7708 transfer log + /// revm journaled for the move, with the beneficiary's record and in the same check. The log + /// is the running frame's, as the move is: the frame's own journal checkpoint takes both back + /// when the frame fails, and its lane the bytes. It is data size and nothing else — no write + /// record, and no history: the bytes reported are the record's alone. #[inline] - pub(crate) fn commit_staged_record(&mut self) -> LimitCheck { - let Some(record) = self.staged.take() else { return LimitCheck::WithinLimit }; - match record.effect(self.sender) { - RecordEffect::None => LimitCheck::WithinLimit, - RecordEffect::Record(usage) => { - self.tracker.record(usage); - self.check() - } + pub(crate) fn commit_staged_record(&mut self) -> (LimitCheck, HistoryBytes) { + let Some(record) = self.staged.take() else { + return (LimitCheck::WithinLimit, HistoryBytes::None); + }; + let effect = record.effect(self.sender); + let history = effect.history_bytes(); + // A log's bytes are history beside the write records; a record's are counted as one. + if let (StagedRecord::Log { .. }, HistoryBytes::Appended(bytes)) = (&record, history) { + self.tracker.record_log_and_code_bytes(bytes); + } + let counted = match effect { + RecordEffect::None => LimitUsage::ZERO, + RecordEffect::Record(usage) => usage, RecordEffect::Refund(usage) => { self.tracker.refund(usage); - LimitCheck::WithinLimit + return (LimitCheck::WithinLimit, history); } + }; + let counted = if self.transfer_logs && record.moves_value() { + counted.saturating_add(TRANSFER_LOG) + } else { + counted + }; + if counted == LimitUsage::ZERO { + return (LimitCheck::WithinLimit, history); } + self.tracker.record(counted); + (self.check(), history) } - /// Discards the staged record. Called by an opcode's wrapper when the opcode failed, which - /// takes the observed write back with it. + /// Discards the staged record. Called by an opcode's wrapper on entry, so a record staged + /// outside a wrapper cannot be committed for the wrong opcode, and when the opcode failed, + /// which takes the observed write back with it. #[inline] pub(crate) fn discard_staged_record(&mut self) { self.staged = None; } - /// Discards a record staged outside an opcode's wrapper. Called by each wrapper on entry, so - /// a record nobody committed cannot be committed for the wrong opcode. - #[inline] - pub(crate) fn discard_stale_record(&mut self) { - self.staged = None; + /* Transaction-level records */ + + /// Counts the transaction's body: its envelope, the writes its inclusion makes, its calldata, + /// its authorizations and its access list. + /// + /// The bytes are the transaction's, recorded before any frame, so a revert does not take them + /// back, and neither does an out-of-gas before the first frame. The count is all it does: + /// validation holds the body to the limit ([`admits_tx_body`](Self::admits_tx_body)) on this + /// same count, and refuses a transaction it does not admit, so a transaction that runs never + /// crosses the limit with its body. + pub(crate) fn record_tx_body(&mut self, bytes: u64) { + self.body_bytes = bytes; + if bytes != 0 { + self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); + } } - /* Transaction-level records */ + /// The data-size bytes of the running transaction's body, as + /// [`record_tx_body`](Self::record_tx_body) counted them. + pub(crate) const fn body_bytes(&self) -> u64 { + self.body_bytes + } + + /// Whether the running transaction's body, with one write record for each of its + /// `authorizations`, fits its data-size limit: what validation holds a transaction to. + /// + /// Every entry of the authorization list counts, whether it will apply or not, so the figure is + /// an upper bound on what the transaction counts before its first frame — the body, then one + /// record for each distinct authority that applies — and a transaction validation admits + /// cannot cross the limit there. An exempt transaction is held to nothing. + pub(crate) fn admits_tx_body(&self, authorizations: u64) -> bool { + self.exempt || + !LimitUsage { data_size: self.body_bytes, write_records: 0 } + .saturating_add(WRITE_RECORD.times(authorizations)) + .exceeds_data_size(self.limits.tx_data_size_limit) + } /// Counts the `bytes` of an Oracle hint, the payload a `sendHint` call hands to the node's /// oracle service. /// /// The bytes are counted before the payload is decoded, so a caller cannot make the node /// materialise a payload for free by appending bytes an ABI decoder ignores. They are the - /// transaction's, not the calling frame's: the hint has left the machine by the time the - /// frame could fail, so nothing takes it back. A crossing latches the transaction, and the - /// hint is not forwarded. + /// transaction's, not the calling frame's, and no frame's budget holds them. Nothing the frame + /// or the transaction does afterwards takes them back, not even for a payload that fails to + /// decode and is never forwarded, for two separate reasons: a payload forwarded to the oracle + /// service cannot be taken back, and admitting a payload and decoding it is work done whether + /// or not it decodes. + /// + /// The limit is checked before the bytes are counted. A hint that would cross it is the stop, + /// with the usage it would have reached, and is neither forwarded nor counted: its payload + /// never left the machine, so the transaction keeps none of it, as it keeps nothing of a log + /// that crossed the limit. pub(crate) fn record_hint_bytes(&mut self, bytes: u64) -> LimitCheck { - self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); - self.check() + let hint = LimitUsage { data_size: bytes, write_records: 0 }; + let (reached, limit) = + (self.tracker.net().saturating_add(hint), self.limits.tx_data_size_limit); + if reached.exceeds_data_size(limit) { + let stop = self.crossed(LimitKind::DataSize, limit, reached.data_size, false); + if stop.exceeded_limit() { + return stop; + } + } + self.tracker.record_tx(hint); + LimitCheck::WithinLimit } /// Records the account writes of the applied EIP-7702 authorities other than the sender: /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is /// one of them, from the transaction's `sender`. /// - /// The limit is checked before the records are made: a crossing latches the transaction and - /// records nothing, and the caller takes the authorizations back, so the writes the limit - /// guards never happen. The first frame is then answered with the stop without running. + /// The records cannot cross the data-size limit: validation admitted the body with a record for + /// every entry of the authorization list ([`admits_tx_body`](Self::admits_tx_body)), and only + /// an entry can apply. A debug build asserts it. pub(crate) fn record_applied_authorities( &mut self, sender: Address, authorities: u64, target_is_authority: bool, - ) -> LimitCheck { + ) { self.sender = sender; - let records = WRITE_RECORD.times(authorities); - let used = self.tracker.net().saturating_add(records).data_size; - if used > self.limits.tx_data_size_limit { - return self.latch(LimitKind::DataSize, self.limits.tx_data_size_limit, used); - } self.target_is_authority = target_is_authority; - self.tracker.record(records); - LimitCheck::WithinLimit + self.tracker.record(WRITE_RECORD.times(authorities)); + debug_assert!( + self.exempt || !self.tracker.net().exceeds_data_size(self.limits.tx_data_size_limit), + "validation admits no body whose authority records cross the data-size limit" + ); } /* Frame lanes */ @@ -242,23 +547,87 @@ impl AdditionalLimit { /// running as the sender (reached through an EIP-7702 delegation) counts it as recorded, and /// a value transfer to the sender records no recipient. /// + /// A frame whose start moves value to another account also counts the EIP-7708 transfer log + /// revm journals for the move, on the frame's own lane and in the same check as its records. + /// revm moves the value, and emits the log, only once it builds the frame, inside the journal + /// checkpoint it makes for it; the count comes before that, so a crossing answers the frame + /// with the stop before any value moves. After the checkpoint it could not: a frame revm + /// answers without running — a call to an account with no code, a precompile — has committed + /// its checkpoint by the time its answer returns, and rewriting the answer would not take the + /// move back. The lane follows the checkpoint from then on: a frame that fails discards both + /// the log and its bytes. + /// + /// So the count is a prediction of what revm will do ([module documentation](super)), and it + /// is called only for a start revm makes as far as the caller's account decides it: a start + /// revm refuses there, and one past the call-stack limit, which the depth guard answers before + /// it is counted, get an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)). + /// /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. - /// So is every frame of a latched transaction, whose lane stays empty. pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { self.frame_began = true; - if let Some(latched) = self.latched { - self.push_empty_frame(); - return latched; - } self.push_lane(input, depth); + if self.frame_start_transfer_log(input) { + self.tracker.record(TRANSFER_LOG); + } self.check() } - fn push_lane(&mut self, input: &FrameInput, depth: usize) { - let budget = match self.tracker.current() { - Some(caller) => caller.remaining_budget().min(self.limits.frame_data_size_limit), - None => self.limits.frame_data_size_limit, + /// Holds the code a creation deposits to the data-size limit, and names the stop when it + /// crosses it: the bytes are counted on the creation's own lane. + /// + /// Called through + /// [`ContextTr::admit_code_deposit`](revm::context::ContextTr::admit_code_deposit), which + /// `return_create` asks once it decided to deposit the code — the code passed every check + /// and every deposit charge is recorded — and before it commits the creation's journal + /// checkpoint. A stop refuses the deposit: `return_create` reverts the checkpoint, so the code + /// is not written, puts the frame's gas back to what it had before the deposit's charges, and + /// ends the creation as a revert carrying the stop. The bytes stay on the lane until the frame + /// returns; a success merges them into the caller, and the failure — the stop included — + /// discards them. + /// + /// A creation `return_create` fails itself is never offered: a revert or a halt of the init + /// code, code it refuses, and a creation that cannot pay one of the deposit's charges, which + /// runs out of gas whatever the limit. Empty code deposits nothing and is held to nothing. + /// + /// The same bytes are history beside the write records, counted here on the same lane, so the + /// history a transaction reports it appended and the data size it kept move together: a + /// creation that deposits nothing, or whose deposit fails, appends neither. + pub(crate) fn on_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { + let bytes = deposit.code.len() as u64; + if bytes == 0 { + return Ok(()); + } + debug_assert!(self.tracker.current().is_some(), "a creation returns on its own lane"); + self.tracker.record(LimitUsage { data_size: bytes, write_records: 0 }); + self.tracker.record_log_and_code_bytes(bytes); + let check = self.check(); + if check.exceeded_limit() { + return Err(self.note_frame_stop(&check)); + } + Ok(()) + } + + /// The data-size budget of the frame about to start. + /// + /// The transaction's own frame gets what the transaction has left, and never more than the + /// frame cap ([`frame_data_size_limit`](EvmTxRuntimeLimits::frame_data_size_limit)). A child + /// gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent + /// has left, under the same cap. What the parent has left is its budget minus what it has + /// already kept, so a parent that has spent part of its budget forwards a smaller share. + fn frame_budget(&self) -> u64 { + let forwarded = match self.tracker.current() { + Some(caller) => share_of_remaining(caller.remaining_budget()), + None => self.limits.tx_data_size_limit.saturating_sub(self.tracker.net().data_size), }; + forwarded.min(self.limits.frame_data_size_limit) + } + + fn push_lane(&mut self, input: &FrameInput, depth: usize) { + let budget = self.frame_budget(); + // What the caller paid for these records at its opcode. The transaction's own frame has + // no such caller: its record is charged before execution and given back by the settlement + // ([`top_level_write_record_gas`](Self::top_level_write_record_gas)). + let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); match input { FrameInput::Call(inputs) => { let target = inputs.target_address; @@ -266,16 +635,18 @@ impl AdditionalLimit { if depth == 0 { self.sender = inputs.caller; let written_outside = target == inputs.caller || self.target_is_authority; + let records = u64::from(transfers_value && !written_outside); + self.check_top_level_records(records); self.tracker.push(Lane::new( Some(target), written_outside || transfers_value, budget, + 0, )); - if transfers_value && !written_outside { - self.tracker.record(WRITE_RECORD); - } + self.tracker.record(WRITE_RECORD.times(records)); return; } + let records = self.records_the_caller_paid_for(input, charge.records); let inherited = self.tracker.current().is_some_and(|caller| { caller.address == Some(target) && caller.account_recorded }); @@ -284,24 +655,102 @@ impl AdditionalLimit { Some(target), inherited || is_sender || transfers_value, budget, + charge.on_lane, )); - if transfers_value { - self.tracker.record_caller(false); - if target != inputs.caller && !is_sender { - self.tracker.record(WRITE_RECORD); - } + if records.caller { + self.tracker.record_caller(false, charge.caller); + } + self.tracker.record(WRITE_RECORD.times(records.on_lane)); + if grants_stipend(inputs) { + self.tracker.grant_stipend(storage_call_stipend()); } } FrameInput::Create(inputs) => { - self.tracker.push(Lane::new(None, true, budget)); - self.tracker.record(WRITE_RECORD); + let records = self.records_the_caller_paid_for(input, charge.records); + self.tracker.push(Lane::new(None, true, budget, charge.on_lane)); + self.tracker.record(WRITE_RECORD.times(records.on_lane)); if depth == 0 { self.sender = inputs.caller(); - } else { - self.tracker.record_caller(true); + self.check_top_level_records(records.on_lane); + } else if records.caller { + self.tracker.record_caller(true, charge.caller); } } - FrameInput::Empty => self.push_empty_frame(), + // No frame starts from an empty input: revm's own frame init is `unreachable!` on + // one. + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), + } + } + + /// The records starting `input` makes, checked against the answer the caller's charge was + /// computed from. + /// + /// The two are separate answers to the same question, asked at two points: the charge at the + /// opcode, on the input revm's instruction built, or at a `keylessDeploy` call's first run, on + /// the creation it starts; and the count here, on the input that survived interception. They + /// agree because nothing between the two changes the input: an interceptor answers a frame or + /// lets it start as it is, and a creation reaches none. A divergence trips here in every debug + /// build rather than mis-charging the caller and mis-splitting the refund its failure gets + /// back. + fn records_the_caller_paid_for( + &self, + input: &FrameInput, + charged: Option, + ) -> FrameStartRecords { + let records = self.frame_start_records(input); + if let Some(charged) = charged { + debug_assert_eq!( + charged, records, + "the records a frame's start makes changed after its caller was charged for them", + ); + } + records + } + + /// Checks the write records the transaction's own frame makes on its lane, `counted` here, + /// against the ones its history was charged for before execution + /// ([`stage_top_level_records`](Self::stage_top_level_records)). + /// + /// The two are separate answers to the same question: the charge, on the transaction, and the + /// count here, on the frame input revm built from it. They agree because that input carries + /// the transaction's own caller, target and value, and both read the same answer to whether + /// the target is an applied authority. An inspector that rewrites the input so that the answer + /// changes splits them, as it does for a frame an opcode starts + /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). A divergence trips + /// here in every debug build rather than charging history for a record the data size does not + /// count, or counting one no history paid for. + fn check_top_level_records(&mut self, counted: u64) { + if let Some(charged) = self.pending_top_level_records.take() { + debug_assert_eq!( + charged, counted, + "the transaction's own frame makes other write records than its history was \ + charged for", + ); + } + } + + /// The write records starting `input` makes at a depth above the transaction's own frame, for + /// the opcode that starts it: `on_lane` are the records the frame's failure discards, `caller` + /// whether its start also writes the caller's own account. + /// + /// The caller pays for both at the opcode, before it forwards gas, so the frame's own budget + /// carries none of them — which is what lets a value transfer's allowance pay for what the + /// recipient does with it. + pub(crate) fn frame_start_records(&self, input: &FrameInput) -> FrameStartRecords { + let caller_recorded = self.tracker.current().is_some_and(|lane| lane.account_recorded); + match input { + FrameInput::Call(inputs) => { + if !inputs.transfers_value() { + return FrameStartRecords::NONE; + } + let target = inputs.target_address; + let writes_target = target != inputs.caller && target != self.sender; + FrameStartRecords { on_lane: u64::from(writes_target), caller: !caller_recorded } + } + FrameInput::Create(_) => FrameStartRecords { on_lane: 1, caller: !caller_recorded }, + FrameInput::Empty => FrameStartRecords::NONE, } } @@ -312,44 +761,942 @@ impl AdditionalLimit { } } - /// Takes a creation's creator record back: the creation failed before bumping the nonce. - pub(crate) fn creation_did_not_bump_nonce(&mut self) { - self.tracker.drop_caller_record(); + /// Makes the running frame start its creation as `creator`: the frame of a `keylessDeploy` + /// call, which runs no code of its own and starts the creation its signer signed. + /// + /// The creation's start writes the creator's nonce, so the frame's lane runs as the creator: + /// the creation records that write as its creator's, on the frame's lane once the creation + /// fails, unless the creator is the transaction's sender, whose account the body counts. + /// + /// No opcode starts the creation, so nothing staged the answer to whether its creator's + /// account refuses it. Clearing the staged answer is defensive: the only answer staged for the + /// call's own start is that of a call carrying value, which is answered before its frame is + /// built and so never starts a creation. Nothing staged can reach the creation; the clear is + /// kept so that none ever does. + pub(crate) fn set_frame_creator(&mut self, creator: Address) { + self.pending_start_refused = None; + let sender = self.sender; + if let Some(lane) = self.tracker.current_mut() { + lane.address = Some(creator); + lane.account_recorded = creator == sender; + } + } + + /// Takes back the nonce record a failed creation left its creator, when the nonce bump it + /// stands for is taken back: the running frame is a `keylessDeploy` call whose lane runs as + /// the signer ([`set_frame_creator`](Self::set_frame_creator)). A signer that is the + /// transaction's sender has no such record, its account being the body's. + /// + /// A stop the record left the frame, by putting it over a limit, goes with it: the frame is + /// held to its limits again without the record. Returns whether a record was taken back. + pub(crate) fn take_back_creator_record(&mut self) -> bool { + let sender = self.sender; + if self.tracker.current().is_none_or(|lane| lane.address == Some(sender)) || + !self.tracker.take_back_own_record() + { + return false; + } + let check = self.check(); + self.resume_stop = check.exceeded_limit().then_some(check); + true + } + + /// Discards the lane of the frame about to return as its failure would, and stands an empty + /// lane in for it, which gives the caller back, when it is popped, the history the failure + /// gives back. + /// + /// For a frame whose journal checkpoint was reverted and whose result an inspector then + /// rewrote into a success: nothing the frame counted was kept, so none of it reaches its + /// caller, whatever the result says. + pub(crate) fn discard_returning_lane(&mut self) { + self.tracker.discard_running_lane(); } /// Pushes the lane of a frame answered without running: a result built without an /// interpreter keeps the lanes aligned with the frames revm returns. + /// + /// Such a frame records none of the writes its caller paid for, so the whole charge sits on + /// the lane and comes back when it is popped, whatever the answer was. pub(crate) fn push_empty_frame(&mut self) { self.frame_began = true; - self.tracker.push(Lane::empty()); + let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); + self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); } /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, - /// a failure discards it. Under a latch the result is first rewritten to the latched stop, - /// whatever produced it (an interceptor, an inspector's rewrite), so no success passes it. - pub(crate) fn on_frame_return(&mut self, result: &mut FrameResult) { - self.apply_latch(result); - self.tracker.pop(result.instruction_result().is_ok()); + /// a failure discards it, a stop's included, so the caller resumes within its limits. + /// + /// Two returns would add to a caller what no check has held it to, and after them the caller is + /// held to its limits with what it now holds; a crossing is the stop it returns before it runs + /// on ([`stop_before_run`](Self::stop_before_run)), naming its budget or the transaction's + /// limit. + /// + /// - A failed creation leaves its creator the nonce record. The creation counted that record on + /// its own lane, against its own share, and a creation stopped for crossing that share still + /// bumps the nonce — so a creator with fewer bytes left than a record would keep one it may + /// not. + /// - A success past the frame's own budget would hand the caller more than the share it gave. + /// No frame returns one: a frame past its budget failed, and a failure an inspector rewrites + /// into a success has its lane discarded before it returns + /// ([`discard_returning_lane`](Self::discard_returning_lane)). It is held all the same. + /// + /// Any other return leaves the caller within its limits, and is not checked: a failure hands + /// it nothing, and a success hands it no more than the share it gave. Neither is the return of + /// the transaction's own frame, which has no caller to hold. A debug build asserts that the + /// check would have found nothing to stop. + /// + /// The crossing the result is made of, the stop noted for the frame + /// ([`note_frame_stop`](Self::note_frame_stop)), is the transaction's + /// [`limit_exceeded`](Self::limit_exceeded) when the frame is the transaction's own and its + /// result is still the stop's revert. + /// + /// Returns the history gas the caller paid for records this frame did not keep, which the + /// caller gets back once the frame has merged into it. + #[must_use = "the history of the records the frame did not keep goes back to its caller"] + pub(crate) fn on_frame_return(&mut self, result: &FrameResult) -> u64 { + let noted = self.frame_stop.take(); + if self.tracker.depth() == 1 { + self.limit_exceeded = noted.filter(|stop| is_the_revert_of(result, stop)); + } + // A charge an opcode of this frame made for a child that never started died with that + // opcode, which failed after making it. + self.pending_frame_charge = FrameCharge::NONE; + let success = result.instruction_result().is_ok(); + let lane = self.tracker.pop(success); + let refund = lane.as_ref().map_or(0, |lane| lane.history_refund(success)); + let unchecked = lane.is_some_and(|lane| self.tracker.hands_unchecked(&lane, success)); + self.resume_stop = if unchecked { + let check = self.check(); + check.exceeded_limit().then_some(check) + } else { + debug_assert!( + self.check().within_limit(), + "a frame's return put its caller over a limit no check held it to" + ); + None + }; + refund } /// Settles the transaction's outermost frame: pops its lane unless the frame already /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever - /// it ran, and rewrites the result to the latched stop. + /// it ran. /// /// A transaction whose first frame never reached frame init ran out of gas in the runtime /// phase before it: the out-of-gas took back the authorizations applied before it, so their - /// records and any latch they set go too, and the halt stays a halt. - pub(crate) fn on_last_frame_return(&mut self, result: &mut FrameResult) { + /// records go too, and the halt stays a halt. The body is not one of those records. It is put + /// back after the reset. Nothing counted before the first frame can have crossed a limit, + /// validation having held the body and the authorities' records to it, so the halt is what the + /// transaction reports. An exemption stays: it is the transaction's, not its frames'. + pub(crate) fn on_last_frame_return(&mut self, result: &FrameResult) { if !self.frame_began { + let body = self.body_bytes; self.tracker.reset(); - self.latched = None; + self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); return; } debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); if self.tracker.depth() == 1 { - self.on_frame_return(result); - } else { - self.apply_latch(result); + // The outermost frame has no caller that paid for its records: the transaction did, + // before execution, and the settlement gives that charge back. + let refund = self.on_frame_return(result); + debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); + } + } +} + +/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`], rounded down. +/// +/// The share is `N / D = 1 − 1 / K` with `K = D / (D − N)` a whole number, so the floor of the +/// product is `remaining − ⌈remaining / K⌉`, which stays in `u64` and never wraps. A `u128` +/// product would call the 128-bit division routine on every frame start, where a division of a +/// `u64` by a constant compiles to a multiplication. +const fn share_of_remaining(remaining: u64) -> u64 { + const N: u64 = FRAME_DATA_SHARE_NUMERATOR; + const D: u64 = FRAME_DATA_SHARE_DENOMINATOR; + const _: () = assert!(N < D && D.is_multiple_of(D - N)); + const K: u64 = D / (D - N); + remaining - remaining.div_ceil(K) +} + +/// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the +/// stop's [`MegaLimitExceeded`](crate::MegaLimitExceeded). +fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { + let result = result.interpreter_result(); + result.result == InstructionResult::Revert && result.output == stop.revert_data() +} + +/// Whether starting `input` moves value from one account to another, which is what revm journals +/// an EIP-7708 transfer log for: a call that transfers value to an account other than its caller — +/// the transaction's own value, a value `CALL` — and a creation with an endowment, the +/// transaction's own or a `CREATE`'s or a `CREATE2`'s. +/// +/// A `CALLCODE` transfers its value from the calling account to itself, as a `CALL` to itself does, +/// and revm moves nothing and emits nothing for either. `DELEGATECALL` and `STATICCALL` transfer +/// no value at all. +fn moves_value(input: &FrameInput) -> bool { + match input { + FrameInput::Call(inputs) => { + inputs.transfers_value() && inputs.target_address != inputs.caller + } + FrameInput::Create(inputs) => !inputs.value().is_zero(), + FrameInput::Empty => false, + } +} + +/// Whether the frame `inputs` starts is granted a history allowance: a value-transferring `CALL` +/// or `CALLCODE` below the transaction's own frame. +/// +/// `DELEGATECALL` and `STATICCALL` carry no value, and the transaction's own frame is not a call +/// anybody made — its sender chose the gas limit. +fn grants_stipend(inputs: &CallInputs) -> bool { + matches!(inputs.scheme, CallScheme::Call | CallScheme::CallCode) && inputs.transfers_value() +} + +/// The write records a frame's start makes, split by whose failure takes them back. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct FrameStartRecords { + /// Records on the frame's own lane, which its failure discards. + pub(crate) on_lane: u64, + /// Whether the frame's start also writes its caller's account. + pub(crate) caller: bool, +} + +impl FrameStartRecords { + /// No record at all. + pub(crate) const NONE: Self = Self { on_lane: 0, caller: false }; +} + +/// The history gas a caller paid for the records the frame it starts makes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct FrameCharge { + /// The records the charge was computed from, when an opcode made one. The transaction's own + /// frame has no such opcode, and neither has a frame of a transaction that prices no history. + records: Option, + /// What the records on the frame's own lane cost. + on_lane: u64, + /// What the record of the caller's own account cost. + caller: u64, +} + +impl FrameCharge { + /// Nothing charged. + const NONE: Self = Self { records: None, on_lane: 0, caller: 0 }; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; + use alloy_primitives::{address, Address, Bytes, U256}; + use revm::interpreter::{CallInput, CallValue}; + + const SENDER: Address = address!("00000000000000000000000000000000000f0001"); + const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); + const TARGET: Address = address!("00000000000000000000000000000000000f0003"); + + #[test] + fn test_share_of_remaining_is_the_floor_of_the_exact_product() { + let exact = |x: u64| { + (u128::from(x) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / + u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 + }; + let mut x = 0x9e37_79b9_7f4a_7c15_u64; + let edges = [0, 1, 49, 50, 51, 99, 100, 101, u64::MAX, u64::MAX - 1, u64::MAX / 100 * 100]; + for v in edges.into_iter().chain((0..100_000).map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x >> (x % 64) + })) { + assert_eq!(share_of_remaining(v), exact(v), "{v}"); + } + } + + fn call_inputs(scheme: CallScheme, value: U256) -> CallInputs { + CallInputs { + input: CallInput::Bytes(Bytes::new()), + return_memory_offset: 0..0, + gas_limit: 100_000, + bytecode_address: Address::ZERO, + known_bytecode: Default::default(), + target_address: Address::ZERO, + caller: Address::ZERO, + value: CallValue::Transfer(value), + scheme, + is_static: false, + reservoir: 0, + charged_new_account_state_gas: false, + } + } + + /// A `CALL` from `caller` to `target` carrying `value`. + fn call_from_to(caller: Address, target: Address, value: U256) -> FrameInput { + FrameInput::Call(Box::new(CallInputs { + caller, + target_address: target, + ..call_inputs(CallScheme::Call, value) + })) + } + + /// A hint is held to the transaction's data-size limit before it is counted: one that fits is + /// counted, one that would cross is the stop at the usage it would have reached and leaves the + /// count as it was, and a later one that fits is counted, the crossing having stopped nothing + /// but its own call. An exempt transaction's is counted whatever it crosses. + #[test] + fn test_a_hint_that_would_cross_the_limit_is_not_counted() { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100); + let kept = |limit: &AdditionalLimit| limit.usage().data_size; + + let mut limit = AdditionalLimit::new(limits); + limit.record_tx_body(40); + assert_eq!(limit.record_hint_bytes(59), LimitCheck::WithinLimit); + assert_eq!(kept(&limit), 99); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 101, + frame_local: false, + }; + assert_eq!(limit.record_hint_bytes(2), stop, "two more bytes cross"); + assert_eq!(kept(&limit), 99, "the hint that crossed is not counted"); + assert_eq!(limit.record_hint_bytes(1), LimitCheck::WithinLimit, "one more fits exactly"); + assert_eq!(kept(&limit), 100, "and is counted"); + + let mut exempt = AdditionalLimit::new(limits); + exempt.exempt(); + exempt.record_tx_body(40); + assert_eq!(exempt.record_hint_bytes(61), LimitCheck::WithinLimit); + assert_eq!(kept(&exempt), 101, "an exempt transaction's hint is counted"); + } + + /// A layer with the transaction's own frame started: `SENDER` calling `CALLEE`, which has + /// recorded nothing of its own yet. + fn with_the_transactions_frame() -> AdditionalLimit { + let mut limit = AdditionalLimit::default(); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit + } + + /// The records a frame's start makes are counted from the answer its caller was charged for: + /// a value transfer records the caller's account and the recipient's, the two the charge was + /// computed from. + #[test] + fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { + let mut limit = with_the_transactions_frame(); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + let records = limit.frame_start_records(&inner); + assert_eq!(records, FrameStartRecords { on_lane: 1, caller: true }); + + limit.stage_frame_charge(records, 1, 1); + limit.on_frame_init(&inner, 1); + assert_eq!( + limit.usage(), + LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }, + ); + } + + /// A frame answered without running — by the depth guard, a stop, an interceptor or an + /// inspector — keeps none of the records its caller paid for, whatever its answer: its lane is + /// empty, the whole charge comes back, and the transaction's history bytes are its body alone. + /// + /// The depth guard's answer is reached here rather than through a transaction: under the + /// execution cap no call chain reaches the call-stack limit, because each call forwards at most + /// sixty-three sixty-fourths of what its caller has left, and 200,000,000 gas leaves about + /// twenty at depth 1,024. A stop's and an interceptor's answers are also reached through + /// transactions, in the history-byte tests. + #[test] + fn test_a_frame_answered_without_running_keeps_nothing_whatever_the_answer() { + const BODY: u64 = crate::TX_BODY_SIZE; + for answer in + [InstructionResult::CallTooDeep, InstructionResult::Revert, InstructionResult::Stop] + { + let mut limit = with_the_transactions_frame(); + limit.set_intrinsic_history(1, BODY); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); + limit.push_empty_frame(); + + let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); + assert_eq!(limit.on_frame_return(&result), 3_000, "{answer:?}: all of it back"); + assert_eq!(limit.usage(), LimitUsage::ZERO, "{answer:?}: nothing kept"); + + let outer = call_from_to(SENDER, CALLEE, U256::ZERO); + let result = + crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); + limit.on_last_frame_return(&result); + limit.settle_history_bytes(true); + assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); + } + } + + /// A charge computed from a different answer than the count is what a rewrite that turns one + /// kind of frame into another would make. It trips rather than passing silently, because the + /// charge and the refund its failure gets back would both be wrong. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "changed after its caller was charged for them")] + fn test_a_charge_computed_from_another_answer_trips() { + let mut limit = with_the_transactions_frame(); + limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + } + + /// The transaction's own frame counts on its lane the write records its history was charged + /// for before execution: its value's recipient, unless that is the sender or an applied + /// authority, and the account a creation makes. + #[test] + fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { + let one = U256::from(1); + let rows = [ + ("a value call", call_from_to(SENDER, CALLEE, one), false, 1), + ("a call without value", call_from_to(SENDER, CALLEE, U256::ZERO), false, 0), + ("a value call to the sender", call_from_to(SENDER, SENDER, one), false, 0), + ("a value call to an applied authority", call_from_to(SENDER, CALLEE, one), true, 0), + ("a creation", creation(SENDER, U256::ZERO), false, 1), + ("an endowed creation", creation(SENDER, one), false, 1), + ]; + for (name, input, target_is_authority, records) in rows { + let authority = u64::from(target_is_authority); + let mut limit = AdditionalLimit::default(); + limit.record_applied_authorities(SENDER, authority, target_is_authority); + limit.stage_top_level_records(records); + limit.on_frame_init(&input, 0); + assert_eq!(limit.usage().write_records, authority + records, "{name}"); + assert_eq!(limit.pending_top_level_records, None, "{name}: taken once"); + } + } + + /// A transaction's own frame that would count a record its history did not pay for trips the + /// check, rather than counting data size no history matches. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "other write records than its history was charged for")] + fn test_a_top_level_record_its_history_did_not_pay_for_trips() { + let mut limit = AdditionalLimit::default(); + limit.stage_top_level_records(0); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + } + + /// A transaction's own frame that makes no record its history was charged for trips the check, + /// rather than keeping history no data size matches. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "other write records than its history was charged for")] + fn test_a_top_level_charge_for_a_record_the_frame_does_not_make_trips() { + let mut limit = AdditionalLimit::default(); + limit.stage_top_level_records(1); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + } + + /// A creation as the transaction's own frame is checked too: one whose history paid for no + /// record of the account it creates trips. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "other write records than its history was charged for")] + fn test_a_top_level_creation_its_history_did_not_pay_for_trips() { + let mut limit = AdditionalLimit::default(); + limit.stage_top_level_records(0); + limit.on_frame_init(&creation(SENDER, U256::ZERO), 0); + } + + /// A child frame's budget is 98% of what its parent has left, three frames down, and the + /// transaction's own frame gets what the transaction has left. + #[test] + fn test_a_child_frame_gets_98_percent_of_what_its_parent_has_left() { + let mut limit = + AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(10_000)); + limit.tracker.record_tx(LimitUsage { data_size: 310, write_records: 0 }); + + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let first = 10_000 - 310; + assert_eq!(limit.tracker.current().unwrap().budget, first); + + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); + let child = share_of_remaining(first); + assert_eq!(child, 9_496); + assert_eq!(limit.tracker.current().unwrap().budget, child); + + limit.on_frame_init(&call_from_to(TARGET, SENDER, U256::ZERO), 2); + let grandchild = share_of_remaining(child); + assert_eq!(limit.tracker.current().unwrap().budget, grandchild); + + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 3); + assert_eq!( + limit.tracker.current().unwrap().budget, + share_of_remaining(grandchild), + "the fourth frame, at depth 3, still takes 98% of what is left" + ); + } + + /// The frame cap binds when it is tighter than the share of what the parent has left. + #[test] + fn test_the_frame_cap_binds_when_it_is_tighter_than_the_share() { + let mut limit = AdditionalLimit::new( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(u64::MAX) + .with_frame_data_size_limit(100), + ); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + assert_eq!(limit.tracker.current().unwrap().budget, 100); + limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); + assert_eq!(limit.tracker.current().unwrap().budget, 98); + } + + /// A layer with a frame cap of 100 bytes and the transaction's own frame started, which is + /// what the cap gives it; `CALLEE`'s call to `TARGET`, the child, is started below it with + /// 98 of them. + fn with_a_child_of_a_capped_frame() -> (AdditionalLimit, FrameInput) { + let mut limit = + AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100)); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let child = call_from_to(CALLEE, TARGET, U256::ZERO); + limit.on_frame_init(&child, 1); + assert_eq!(limit.tracker.current().unwrap().budget, 98); + (limit, child) + } + + /// A success is checked on its return only when it kept more than its own budget, which no + /// frame returns and the check guards against all the same. Within its budget it hands the + /// caller no more than the caller's share, and the caller runs on unchecked; past it, the + /// caller is held to its own budget with what it now keeps, and stops when that crosses it. + #[test] + fn test_a_success_past_its_budget_holds_its_caller_to_the_caller_budget() { + for (kept, caller_stopped) in [(98, false), (99, false), (100, false), (101, true)] { + let (mut limit, child) = with_a_child_of_a_capped_frame(); + limit.tracker.record(LimitUsage { data_size: kept, write_records: 0 }); + let result = + crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&result); + let stop = limit.stop_before_run(); + let expected = caller_stopped.then_some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: kept, + frame_local: true, + }); + assert_eq!(stop, expected, "a child that kept {kept} bytes"); + assert_eq!(limit.usage().data_size, kept, "the success merged what it kept"); + } + } + + /// The premise the unchecked returns rest on is asserted in a debug build. A success within a + /// budget wider than the share its caller gave it — what a share computed wrong would give — + /// puts the caller over its own budget with no check to catch it, and trips. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "no check held it to")] + fn test_a_success_that_hands_its_caller_more_than_its_share_trips() { + let (mut limit, child) = with_a_child_of_a_capped_frame(); + limit.tracker.current_mut().unwrap().budget = u64::MAX; + limit.tracker.record(LimitUsage { data_size: 101, write_records: 0 }); + let result = crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&result); + } + + /// Whether a start's caller refuses it is staged by the opcode that found it and taken once, + /// by the frame's init. Nothing is left for a later start: a reset drops what the transaction + /// before it left, and a keyless deployment's creation, which no opcode starts, drops what was + /// staged for its call. + #[test] + fn test_a_staged_start_answer_is_taken_once() { + let mut limit = with_the_transactions_frame(); + assert_eq!(limit.take_start_refused(), None, "nothing staged"); + for refused in [false, true] { + limit.stage_start_refused(refused); + assert_eq!(limit.take_start_refused(), Some(refused)); + assert_eq!(limit.take_start_refused(), None, "taken once"); + } + + limit.stage_start_refused(true); + limit.set_frame_creator(TARGET); + assert_eq!(limit.take_start_refused(), None, "the creation's is not the call's"); + + limit.stage_start_refused(true); + limit.reset(); + assert_eq!(limit.take_start_refused(), None, "the next transaction's is not this one's"); + } + + /// Limits every dimension holds at zero: anything a transaction counts crosses one. + fn zero_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0) + } + + /// Counts a body, then starts the transaction's frame and a value call's, and reports the + /// verdicts of the two starts. + fn count_a_transaction(limit: &mut AdditionalLimit) -> [LimitCheck; 2] { + limit.record_tx_body(crate::TX_BODY_SIZE); + let first = limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let records = limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + [first, records] + } + + /// A transaction that is not exempt is stopped wherever it crosses a limit: counting the + /// body checks nothing, the first check, at its frame's start, is the stop, and a later start + /// that crosses again is a stop of its own, with the usage it reached, not the first one's. + #[test] + fn test_a_transaction_that_is_not_exempt_is_stopped() { + let mut limit = AdditionalLimit::new(zero_limits()); + let [first, records] = count_a_transaction(&mut limit); + let stop = |used| LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 0, + used, + frame_local: false, + }; + assert_eq!(first, stop(crate::TX_BODY_SIZE), "the body crosses at the first check"); + assert_eq!(records, stop(crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE)); + assert!(!limit.is_exempt()); + } + + /// Validation admits a body whose bytes, with one record for each entry of the authorization + /// list, are within the transaction's limit, and nothing over it; an exempt transaction + /// whatever it carries. + #[test] + fn test_validation_admits_a_body_and_its_authority_records_within_the_limit() { + let body = crate::TX_BODY_SIZE + 2 * crate::AUTHORIZATION_SIZE; + let at = body + 2 * WRITE_RECORD_SIZE; + let layer = |limit: u64, exempt: bool| { + let mut layer = AdditionalLimit::new( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + if exempt { + layer.exempt(); + } + layer.record_tx_body(body); + layer + }; + assert!(layer(at, false).admits_tx_body(2), "at the limit"); + assert!(!layer(at - 1, false).admits_tx_body(2), "one byte over it"); + assert!(layer(at - 1, false).admits_tx_body(1), "one record fewer"); + assert!(!layer(body - 1, false).admits_tx_body(0), "the body alone over it"); + assert!(layer(0, true).admits_tx_body(2), "an exempt transaction"); + assert_eq!(layer(at, false).body_bytes(), body); + assert_eq!(layer(at, false).usage().data_size, body, "the body is counted"); + } + + /// An exempt transaction is stopped by no limit, in any dimension, at the transaction or at a + /// frame: every verdict is within the limits and no caller is stopped. What it uses is counted + /// all the same. + #[test] + fn test_an_exempt_transaction_is_stopped_by_no_limit() { + let mut limit = AdditionalLimit::new(zero_limits()); + limit.exempt(); + assert_eq!(count_a_transaction(&mut limit), [LimitCheck::WithinLimit; 2]); + for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { + for frame_local in [false, true] { + let verdict = limit.crossed(kind, 0, 1, frame_local); + assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); + } + } + assert_eq!(limit.stop_before_run(), None); + assert_eq!( + limit.usage(), + LimitUsage { data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 }, + ); + + let result = crate::synthetic_frame_result( + &call_from_to(CALLEE, TARGET, U256::from(1)), + InstructionResult::Stop, + Bytes::new(), + ); + let _ = limit.on_frame_return(&result); + assert_eq!(limit.stop_before_run(), None, "the caller runs on"); + } + + /// Validation admits no body whose authority records cross the data-size limit, so a debug + /// build trips on records that do: under a limit lowered to the body and one record, two + /// applied authorities cross it. + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "validation admits no body whose authority records cross")] + fn test_authority_records_that_cross_the_limit_trip() { + let mut limit = AdditionalLimit::new( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE), + ); + limit.record_tx_body(crate::TX_BODY_SIZE); + limit.record_applied_authorities(SENDER, 2, false); + } + + /// Applied authorities are recorded for an exempt transaction, whatever they cross. + #[test] + fn test_an_exempt_transaction_records_its_authorities() { + let mut limit = AdditionalLimit::new(zero_limits()); + limit.exempt(); + limit.record_applied_authorities(SENDER, 2, false); + assert_eq!(limit.usage(), WRITE_RECORD.times(2)); + } + + /// The exemption is the transaction's: a reset clears it, and the next transaction is held to + /// its limits again. An out-of-gas before the first frame keeps it. + #[test] + fn test_the_exemption_lasts_one_transaction() { + let mut limit = AdditionalLimit::new(zero_limits()); + limit.exempt(); + let result = crate::synthetic_frame_result( + &call_from_to(SENDER, CALLEE, U256::ZERO), + InstructionResult::OutOfGas, + Bytes::new(), + ); + limit.on_last_frame_return(&result); + assert!(limit.is_exempt(), "an out-of-gas before the first frame keeps the exemption"); + + limit.reset(); + assert!(!limit.is_exempt()); + let [first, ..] = count_a_transaction(&mut limit); + assert!(first.exceeded_limit(), "after a reset the transaction is held to its limits"); + } + + /// A layer whose transaction's value movements journal transfer logs, under `limits`. + fn logging(limits: EvmTxRuntimeLimits) -> AdditionalLimit { + let mut limit = AdditionalLimit::new(limits); + limit.set_transfer_logs(true); + limit + } + + /// A creation from `caller` endowing the account it creates with `value`. + fn creation(caller: Address, value: U256) -> FrameInput { + FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( + caller, + revm::interpreter::CreateScheme::Create, + value, + Bytes::new(), + 100_000, + 0, + ))) + } + + /// Exactly the frame starts that move value to another account count a transfer log: a value + /// call to another account and an endowed creation, at the transaction's own frame and below + /// it. A call to itself, a `CALLCODE`, a valueless call of any scheme, a `DELEGATECALL`, a + /// `STATICCALL` and a creation without an endowment count none; and nothing counts one when + /// the transaction's value movements journal no log. + #[test] + fn test_a_frame_start_counts_a_transfer_log_where_value_moves() { + let one = U256::from(1); + let scheme = |scheme, value| { + FrameInput::Call(Box::new(CallInputs { + caller: CALLEE, + target_address: if scheme == CallScheme::CallCode { CALLEE } else { TARGET }, + ..call_inputs(scheme, value) + })) + }; + for (input, moves) in [ + (call_from_to(CALLEE, TARGET, one), true), + (call_from_to(CALLEE, CALLEE, one), false), + (call_from_to(CALLEE, TARGET, U256::ZERO), false), + (scheme(CallScheme::CallCode, one), false), + (scheme(CallScheme::StaticCall, U256::ZERO), false), + (creation(CALLEE, one), true), + (creation(CALLEE, U256::ZERO), false), + ] { + assert_eq!(moves_value(&input), moves, "{input:?}"); + assert!(!with_the_transactions_frame().frame_start_transfer_log(&input), "off"); + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + assert_eq!(limit.frame_start_transfer_log(&input), moves, "{input:?}"); + let before = limit.usage(); + limit.on_frame_init(&input, 1); + let records = limit.usage().write_records - before.write_records; + assert_eq!( + limit.usage().data_size - before.data_size, + WRITE_RECORD_SIZE * records + if moves { TRANSFER_LOG_SIZE } else { 0 }, + "{input:?}", + ); + } + let delegate = FrameInput::Call(Box::new(CallInputs { + value: CallValue::Apparent(one), + ..call_inputs(CallScheme::DelegateCall, one) + })); + assert!(!moves_value(&delegate), "a delegate call carries its caller's value, no transfer"); + + // The transaction's own frame: its value to another account, and its endowed creation. + for (input, moves) in [ + (call_from_to(SENDER, CALLEE, one), true), + (call_from_to(SENDER, SENDER, one), false), + (creation(SENDER, one), true), + ] { + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.on_frame_init(&input, 0); + let log = limit.usage().data_size - WRITE_RECORD_SIZE * limit.usage().write_records; + assert_eq!(log, if moves { TRANSFER_LOG_SIZE } else { 0 }, "{input:?}"); + } + } + + /// A transfer log is data size and nothing else: no write record, and no history byte — the + /// transaction's history is its body and its records, whatever it moved. + #[test] + fn test_a_transfer_log_is_data_size_and_never_history() { + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.set_intrinsic_history(1, crate::TX_BODY_SIZE); + limit.record_tx_body(crate::TX_BODY_SIZE); + let outer = call_from_to(SENDER, CALLEE, U256::from(1)); + limit.on_frame_init(&outer, 0); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + limit.stage_frame_charge(limit.frame_start_records(&inner), 0, 0); + limit.on_frame_init(&inner, 1); + assert_eq!( + limit.usage(), + LimitUsage { + data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE, + write_records: 2, + }, + "the recipient of each move — the inner one's caller is the outer one's — and two logs", + ); + + let result = crate::synthetic_frame_result(&inner, InstructionResult::Stop, Bytes::new()); + let _ = limit.on_frame_return(&result); + let result = crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); + limit.on_last_frame_return(&result); + limit.settle_history_bytes(true); + assert_eq!(limit.history_bytes(), crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE); + } + + /// A frame that fails takes its transfer log back with its records, as revm's checkpoint + /// takes back the move and the log. + #[test] + fn test_a_failed_frame_gives_its_transfer_log_back() { + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + limit.on_frame_init(&inner, 1); + assert_eq!(limit.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + + let result = crate::synthetic_frame_result(&inner, InstructionResult::Revert, Bytes::new()); + let _ = limit.on_frame_return(&result); + assert_eq!(limit.usage(), LimitUsage::ZERO); + } + + /// A frame start whose transfer log crosses a limit is stopped there, before revm moves the + /// value, with a stop that names the limit it crossed, its own budget or the transaction's + /// limit. The records alone + /// fit, so it is the log that crosses; at exactly the limit it holds. + #[test] + fn test_a_frame_start_whose_transfer_log_crosses_is_stopped() { + let records = 2 * WRITE_RECORD_SIZE; + let needs = records + TRANSFER_LOG_SIZE; + let inner = call_from_to(CALLEE, TARGET, U256::from(1)); + // The smallest frame cap whose share, the budget of a child of the first frame, holds it. + let cap = (needs..).find(|cap| share_of_remaining(*cap) >= needs).unwrap(); + assert_eq!(share_of_remaining(cap), needs); + for (cap, fits) in [(cap, true), (cap - 1, false)] { + let mut limit = + logging(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap)); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + let check = limit.on_frame_init(&inner, 1); + if fits { + assert_eq!(check, LimitCheck::WithinLimit, "exactly the budget"); + } else { + assert_eq!( + check, + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: needs - 1, + used: needs, + frame_local: true, + }, + ); + } + } + + // The transaction's own value: one record, the recipient's, and the log. + let first = call_from_to(SENDER, CALLEE, U256::from(1)); + let needs = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { + let mut limit = + logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit)); + let check = limit.on_frame_init(&first, 0); + if fits { + assert_eq!(check, LimitCheck::WithinLimit, "exactly the limit"); + continue; + } + assert_eq!( + check, + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: tx_limit, + used: needs, + frame_local: false, + }, + ); + } + } + + /// A `SELFDESTRUCT` that moved value to another account counts its transfer log with the + /// beneficiary's record, in one check, and reports the record's history alone. To the sender, + /// whose account the body counts, it is the log alone, and the log alone can cross. + #[test] + fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { + let destruction = |beneficiary| StagedRecord::SelfDestruct { + had_value: true, + to_other_account: true, + beneficiary, + }; + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_record(destruction(TARGET)); + let (check, history) = limit.commit_staged_record(); + assert_eq!(check, LimitCheck::WithinLimit); + assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); + assert_eq!( + limit.usage(), + LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + ); + + let mut limit = + logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1)); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_record(destruction(SENDER)); + let (check, history) = limit.commit_staged_record(); + assert_eq!(history, HistoryBytes::None); + assert_eq!( + check, + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: TRANSFER_LOG_SIZE - 1, + used: TRANSFER_LOG_SIZE, + frame_local: false, + }, + "the log alone crosses", + ); + + let mut limit = AdditionalLimit::default(); + limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); + limit.stage_record(destruction(TARGET)); + let _ = limit.commit_staged_record(); + assert_eq!(limit.usage(), WRITE_RECORD, "no log, no bytes"); + } + + /// The transfer logs are the transaction's to set: a reset turns them off until the next + /// transaction sets them again. + #[test] + fn test_a_reset_turns_the_transfer_logs_off() { + let mut limit = logging(EvmTxRuntimeLimits::no_limits()); + let input = call_from_to(SENDER, CALLEE, U256::from(1)); + assert!(limit.frame_start_transfer_log(&input)); + limit.reset(); + assert!(!limit.frame_start_transfer_log(&input)); + } + + /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` + /// or a `CALLCODE` that moves value is granted one, and nothing else is — a valueless call of + /// either scheme, and `DELEGATECALL` and `STATICCALL`, which take no value word at all. + #[test] + fn test_only_a_value_call_or_callcode_is_granted_an_allowance() { + for scheme in [ + CallScheme::Call, + CallScheme::CallCode, + CallScheme::DelegateCall, + CallScheme::StaticCall, + ] { + let carries_value = matches!(scheme, CallScheme::Call | CallScheme::CallCode); + assert_eq!( + grants_stipend(&call_inputs(scheme, U256::from(1))), + carries_value, + "{scheme:?} with value", + ); + assert!(!grants_stipend(&call_inputs(scheme, U256::ZERO)), "{scheme:?} without value"); } } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 4b15f1d45..226bf53c8 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -2,12 +2,131 @@ //! //! The common execution layer defines what a limit reports when it is crossed: the dimension //! ([`LimitKind`]), the verdict of a check ([`LimitCheck`]) and the revert data a stopped frame -//! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension (the data-size limit, -//! detention, the state-growth and KV limits) fill these in. +//! returns ([`MegaLimitExceeded`]). The mechanisms that meter a dimension fill these in: the +//! data-size limit below, and detention for compute gas. //! -//! It also counts what those limits meter at the sites the data-size limit counts: data-size +//! Gas detention caps compute, [`LimitKind::ComputeGas`]: its state lives beside this module, in +//! [`Detention`](crate::Detention), because what it meters is gas rather than anything the lanes +//! count, and it holds a frame to the cap with the gas the frame may spend. It stops the frame that +//! crosses the cap with the same revert ([`AdditionalLimit`]), with the compute the transaction may +//! reach as the limit, and its compute at the crossing as what was used +//! ([`LimitCheck::ExceedsLimit`]). +//! +//! It also counts what the data-size limit meters, at the sites the bytes are made: data-size //! bytes and write records, on a lane per frame ([`AdditionalLimit`]). The Host stages what it //! observes ([`StagedRecord`]) and the opcode commits it once it completed. +//! +//! # The data-size limit +//! +//! A transaction is held to [`EvmTxRuntimeLimits::tx_data_size_limit`] and every frame to a +//! budget. The transaction's own frame gets what the transaction has left once its body is +//! counted, and a child gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of +//! what its parent has left, under [`EvmTxRuntimeLimits::frame_data_size_limit`]. A frame that +//! crosses either reverts alone, its caller resumes, and what the frame counted goes with it, so +//! the caller is back within both ([`AdditionalLimit`]). The budget is what keeps a caller's own +//! work safe from what it calls: a child inherits its caller's whole reservoir, so gas does not +//! bound the bytes it can append, and without a budget a callee could take the transaction to its +//! limit and leave its caller nothing to carry on with once it catches the stop. A creation +//! stopped at its start still bumps its creator's nonce, and the record of that write lands on the +//! creator: the creator is held to its limits with it before it runs on, and reverts alone if it +//! crossed one. +//! +//! What is counted, and when: +//! +//! - the body, before any frame; neither a revert nor an out-of-gas takes it back; +//! - the records of the applied EIP-7702 authorities, before the first frame; +//! - the records a frame's start makes, when the frame starts; +//! - a storage write's record, a log's bytes and the record of a `SELFDESTRUCT`'s beneficiary, once +//! the opcode completed; +//! - deployed code, on the creation's lane before the creation is committed, so a crossing leaves +//! no code behind. Only code revm would deposit counts: code starting with `0xEF` or over the +//! code-size limit, and a creation that cannot pay for its deposit, fail the creation alone and +//! are not counted; +//! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded; +//! - an EIP-7708 transfer log, which revm journals itself for every value movement, where the value +//! moves: with the records of the frame start that moves it — the transaction's own value, a +//! value `CALL`, a creation's endowment — before revm builds the frame, so a crossing answers the +//! frame with the stop before any value moves; and with a `SELFDESTRUCT`'s beneficiary once the +//! opcode completed. Each is counted by the rule a `LOG3` of one word is ([`TRANSFER_LOG_SIZE`]), +//! on the lane of the frame whose journal checkpoint holds the move, so the failure that takes +//! the move back takes the bytes back. +//! +//! A frame start is counted before revm decides it, so what it counts is a prediction of what revm +//! will do. As far as the caller's account decides it, the prediction is revm's own: a start revm +//! refuses there — a value its caller cannot fund, a creation whose creator's nonce cannot be +//! bumped — moves and writes nothing, so it counts nothing and is charged nothing, and no limit +//! stops it. The caller's account is read from the journal without loading anything. The one +//! refusal decided after the count is a creation onto an occupied address, which revm reads off +//! the created address's account only once it builds the frame: its records and transfer log are +//! counted, so a crossing they cause stops the creation where revm would have failed it, and +//! without a crossing the failure discards them. +//! +//! A record is checked against the limits before its history is charged: a record the limit +//! rejects is not kept, so it is not charged, and the stop is what its frame reports. At a frame +//! start the order is the other way round — the caller pays for the records at its opcode, before +//! the frame starts and its records are counted — so a caller that cannot pay runs out of gas +//! first. +//! +//! Nothing counted before the first frame crosses the limit: validation refuses a transaction +//! whose body, with a record for each entry of its authorization list, exceeds it +//! ([`TX_BODY_OVER_DATA_SIZE_LIMIT`]), and those are all a transaction counts before its first +//! frame — the body, and one record for each distinct authority that applies. A deposit refused +//! that way is included as a failed deposit, which keeps its body counted. +//! +//! # Write records +//! +//! The write-record count the lanes keep is the KV count a node reports: one record per account +//! or storage write the transaction keeps, deduplicated per frame, taken back with a slot written +//! back to its original value and with the frame that fails. The sender's account and the accounts +//! fees are credited to are the body's, not records. No limit holds the count: a record weighs +//! [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so the data-size +//! limit bounds the records, and history gas prices each of them. +//! +//! # State growth +//! +//! No limit holds the state a transaction adds. EIP-8037 charges state gas for exactly that state, +//! at the SALT price of the bucket it lands in, so state growth is bounded by what it costs: the +//! transaction's gas limit and the block's. +//! +//! # The limits +//! +//! They are the per-transaction half of +//! [`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec), which for Satin holds a +//! transaction to [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, every frame to +//! its share of it, and a detained transaction to detention's caps. +//! +//! # The exemption +//! +//! The protocol's own work is held to none of these per-transaction limits: a system-originated +//! transaction ([`crate::system::is_system_originated`]) and a system call — the pre-block calls +//! among them — are exempt ([`AdditionalLimit::is_exempt`]), sticky for the transaction, and the +//! one place every stop comes from answers that they are within the limits whatever they cross: +//! the data size and the frame budgets. It is the set that pays no history gas, exempt for the +//! same reason: the protocol's maintenance must not fail on a resource limit. What such a +//! transaction uses is counted all the same and reported in its usage and in the block's counters, +//! as a deposit's is. A user's deposit is not in the set and is held to every limit. +//! +//! # The byte table +//! +//! The sizes below are what one of those things weighs, and they are the whole byte table of the +//! engine. The data-size limit meters a transaction against them and history gas prices the same +//! counts, and the pairing is **per record**: a record's history bytes are its own data size, so +//! a log costs history for exactly the bytes the limit counts it at. A mechanism that needs a +//! size takes it from here rather than writing its own number. +//! +//! Per transaction the two totals are not the same number, and are not meant to be. Three sites +//! part them, each by decision: +//! +//! - an Oracle hint's payload is data size the transaction counts and history it does not pay. The +//! bytes go to the node's oracle service, not into a block, so there is nothing to price; +//! - an EIP-7708 transfer log is data size and never history. The protocol writes it for every +//! value movement and Ethereum prices it at nothing: it is not a byte the transaction chose to +//! append. It is no write record either — the accounts the move writes are recorded as they are +//! without it; +//! - [`TX_FIXED_WRITE_RECORDS`] is an upper bound on the accounts a transaction's inclusion writes, +//! and nothing checks afterwards which of them something else wrote again. A transfer whose +//! recipient is the block beneficiary or a fee vault pays a record the body already bound. It is +//! an over-charge, never an under-charge. mod frame_limit; #[allow(clippy::module_inception)] @@ -15,10 +134,13 @@ mod limit; mod record; pub use limit::AdditionalLimit; +pub(crate) use limit::FrameStartRecords; +pub(crate) use record::HistoryBytes; pub use record::StagedRecord; use alloy_primitives::Bytes; use alloy_sol_types::SolError; +use revm::context::result::ExecutionResult; /// Bytes of one write record: the key and value delta one account or storage write leaves in /// the state diff. @@ -30,40 +152,151 @@ pub const LOG_BASE_SIZE: u64 = 32; /// Bytes every log topic counts. pub const LOG_TOPIC_SIZE: u64 = 32; +/// The bytes a `LOG` with `topics` topics and `data_len` bytes of data counts, which are the +/// history bytes it appends: its own record for the address that emitted it, one per topic, and +/// the data. +#[inline] +pub const fn log_history_bytes(topics: u64, data_len: u64) -> u64 { + LOG_BASE_SIZE.saturating_add(LOG_TOPIC_SIZE.saturating_mul(topics)).saturating_add(data_len) +} + +/// Bytes an EIP-7708 transfer log counts: its address, its three topics — the event, the sender +/// and the recipient — and one word of data, the amount. It is what a `LOG3` carrying one word +/// counts, by the same rule. +pub const TRANSFER_LOG_SIZE: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; + +/// Bytes every transaction counts for its envelope: the fields a transaction carries beside its +/// calldata, its access list and its authorizations. +pub const TX_BASE_SIZE: u64 = 110; + +/// Write records every transaction makes whatever it runs, counted in its body rather than at the +/// site that makes them: the sender's account, and the four accounts a transaction's fees are +/// credited to — the block beneficiary, the L1 fee vault, the base fee vault and the operator fee +/// vault. +/// +/// It is an upper bound. The reward credits fewer accounts when a fee is zero or when the +/// beneficiary is one of the vaults, but the body is priced before the transaction runs, so it +/// carries the bound rather than the count. +pub const TX_FIXED_WRITE_RECORDS: u64 = 5; + +/// Bytes every transaction's body counts: its envelope and the records of the writes it makes +/// whatever it runs. +pub const TX_BODY_SIZE: u64 = TX_BASE_SIZE + WRITE_RECORD_SIZE * TX_FIXED_WRITE_RECORDS; + +/// Bytes one EIP-7702 authorization counts: the authorization tuple and its signature. +pub const AUTHORIZATION_SIZE: u64 = 101; + +/// The message of the [`InvalidTransaction::Str`](revm::context::result::InvalidTransaction::Str) +/// a transaction is refused with when its body, with one [`WRITE_RECORD_SIZE`] record for each +/// entry of its authorization list, exceeds the transaction's data-size limit. +/// +/// A transaction other than a deposit is rejected with it, by a pool as by block execution; a +/// deposit, which op-revm does not refuse for a transaction error, is included as a failed deposit +/// instead. +pub const TX_BODY_OVER_DATA_SIZE_LIMIT: &str = + "transaction body and authorization records exceed the transaction data-size limit"; + +/// Bytes one access-list address counts: the address itself. +pub const ACCESS_LIST_ADDRESS_SIZE: u64 = 20; + +/// Bytes one access-list storage key counts: the key itself. +pub const ACCESS_LIST_SLOT_SIZE: u64 = 32; + +/// Numerator of the share of its parent's remaining data-size budget a child frame receives. +/// +/// A child gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its +/// parent has left. The fraction is what keeps a deep call from spending the whole transaction +/// on its innermost frame. +pub const FRAME_DATA_SHARE_NUMERATOR: u64 = 98; + +/// Denominator of [`FRAME_DATA_SHARE_NUMERATOR`]. +pub const FRAME_DATA_SHARE_DENOMINATOR: u64 = 100; + /// What a transaction or a frame counts: data-size bytes and write records. /// -/// The KV count a node reports is the write-record count; it has no tracker of its own. +/// The write-record count is the KV count a node reports; no limit holds it. Every record weighs +/// [`WRITE_RECORD_SIZE`] bytes of data size and is taken back with them, so +/// `write_records × WRITE_RECORD_SIZE` never exceeds `data_size`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct LimitUsage { /// Data-size bytes. pub data_size: u64, - /// Account and storage write records. + /// Account and storage write records: the KV count. pub write_records: u64, } -/// Limits the common execution layer enforces on one transaction, for exercising the abort -/// protocol before the mechanisms that own the limits land. Both default to unlimited. +/// Limits one transaction's data size and its compute after a read of volatile data. /// -/// The data-size limit replaces them with its own limit and per-frame budget rule. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +/// [`tx_data_size_limit`](Self::tx_data_size_limit) is what the transaction may keep: a frame +/// whose count crosses it reverts alone. A frame's own budget is derived from it: the transaction's +/// frame gets what the transaction has left, and each child gets [`FRAME_DATA_SHARE_NUMERATOR`] / +/// [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent has left. Crossing a frame budget reverts +/// that frame alone. +/// +/// [`frame_data_size_limit`](Self::frame_data_size_limit) is a further cap on every frame's budget. +/// +/// [`block_env_access_compute_gas_limit`](Self::block_env_access_compute_gas_limit) and +/// [`oracle_access_compute_gas_limit`](Self::oracle_access_compute_gas_limit) are gas detention's +/// caps: the compute a transaction may still spend once it read volatile data. +/// [`no_limits`](Self::no_limits) leaves every limit unlimited, the caps included, and a +/// transaction whose caps are both unlimited is not detained: limits built from it do not execute +/// the chain. +/// +/// The chain's values are the per-transaction half of +/// [`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec), and [`Default`] is the default +/// spec's; other values are a tool's or a test's counterfactual. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EvmTxRuntimeLimits { - /// The most data-size bytes the transaction may keep. Crossing it stops the transaction. + /// The most data-size bytes the transaction may keep. Crossing it reverts the frame that + /// crosses it. pub tx_data_size_limit: u64, - /// The most data-size bytes one frame may keep, children included, and never more than - /// what its caller has left. Crossing it reverts the frame alone. + /// A cap on every frame's data-size budget, applied after the share of what its parent has + /// left. Crossing it reverts the frame alone. pub frame_data_size_limit: u64, + /// The compute a transaction may still spend once it read the block environment or the block + /// beneficiary's account: its compute at the read plus this. Crossing it reverts the frame + /// that crosses it. + /// + /// `u64::MAX` caps nothing, and with the Oracle's cap unlimited too the transaction is not + /// detained at all, as under [`no_limits`](Self::no_limits): that is for equivalence runs and + /// tests, not for executing the chain, which runs on the spec's cap, the default. + pub block_env_access_compute_gas_limit: u64, + /// The compute a transaction may still spend once it read the Oracle's storage: its compute + /// at the read plus this. Crossing it reverts the frame that crosses it. + /// + /// `u64::MAX` caps nothing, and with the block-environment cap unlimited too the transaction + /// is not detained at all, as under [`no_limits`](Self::no_limits): that is for equivalence + /// runs and tests, not for executing the chain, which runs on the spec's cap, the default. + pub oracle_access_compute_gas_limit: u64, } impl Default for EvmTxRuntimeLimits { + /// The limits of the default spec's table: what a [`MegaContext`](crate::MegaContext) of that + /// spec runs under. fn default() -> Self { - Self::no_limits() + crate::ProtocolLimits::for_spec(crate::MegaSpecId::default()).tx_runtime_limits } } impl EvmTxRuntimeLimits { - /// No limit at all. + /// No limit at all: gas detention's caps are unlimited too, so no read of volatile data caps + /// anything, and no transaction is detained. + /// + /// It turns detention off together with every other per-transaction limit. It is what the + /// execution-spec gate's equivalence mode installs, and what tests use to take the limits + /// out; the chain executes on its spec's ([`ProtocolLimits::for_spec`]), whose detention caps + /// are below [`MAX_TX_COMPUTE_GAS`](crate::constants::MAX_TX_COMPUTE_GAS), the most compute a + /// transaction can spend. + /// + /// [`ProtocolLimits::for_spec`]: crate::ProtocolLimits::for_spec pub const fn no_limits() -> Self { - Self { tx_data_size_limit: u64::MAX, frame_data_size_limit: u64::MAX } + Self { + tx_data_size_limit: u64::MAX, + frame_data_size_limit: u64::MAX, + block_env_access_compute_gas_limit: u64::MAX, + oracle_access_compute_gas_limit: u64::MAX, + } } /// Sets the transaction's data-size limit. @@ -72,21 +305,43 @@ impl EvmTxRuntimeLimits { self } - /// Sets the per-frame data-size budget. + /// Caps every frame's data-size budget at `limit`. pub const fn with_frame_data_size_limit(mut self, limit: u64) -> Self { self.frame_data_size_limit = limit; self } + + /// Sets the compute a transaction may still spend once it read the block environment or the + /// block beneficiary's account. + pub const fn with_block_env_access_compute_gas_limit(mut self, limit: u64) -> Self { + self.block_env_access_compute_gas_limit = limit; + self + } + + /// Sets the compute a transaction may still spend once it read the Oracle's storage. + pub const fn with_oracle_access_compute_gas_limit(mut self, limit: u64) -> Self { + self.oracle_access_compute_gas_limit = limit; + self + } } /// One write record. pub(crate) const WRITE_RECORD: LimitUsage = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; +/// One EIP-7708 transfer log: data size, and no write record. +pub(crate) const TRANSFER_LOG: LimitUsage = + LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }; + impl LimitUsage { /// Nothing counted. pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + /// Whether `self` keeps more data-size bytes than `limit`, the one dimension a limit holds. + pub(crate) const fn exceeds_data_size(self, limit: u64) -> bool { + self.data_size > limit + } + /// Both counters added, saturating. pub const fn saturating_add(self, other: Self) -> Self { Self { @@ -125,17 +380,15 @@ alloy_sol_types::sol! { /// A resource dimension a limit meters. /// /// The discriminants are the `kind` of [`MegaLimitExceeded`] and keep the values the legacy engine -/// encoded, so a contract that decodes the legacy revert data decodes Satin's. +/// encoded, so a contract that decodes the legacy revert data decodes Satin's. The legacy engine's +/// key-value updates, `1`, and state growth, `3`, name no dimension: no limit holds the write +/// records or the state a transaction adds. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LimitKind { /// Bytes of data a transaction produces; metered by the data-size limit. DataSize, - /// Key-value updates; metered by the state-growth and KV limits. - KVUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, - /// Net new state; metered by the state-growth and KV limits. - StateGrowth, } impl LimitKind { @@ -143,9 +396,7 @@ impl LimitKind { pub const fn as_u8(&self) -> u8 { match self { Self::DataSize => 0, - Self::KVUpdate => 1, Self::ComputeGas => 2, - Self::StateGrowth => 3, } } @@ -153,9 +404,7 @@ impl LimitKind { pub const fn from_u8(kind: u8) -> Option { match kind { 0 => Some(Self::DataSize), - 1 => Some(Self::KVUpdate), 2 => Some(Self::ComputeGas), - 3 => Some(Self::StateGrowth), _ => None, } } @@ -163,10 +412,10 @@ impl LimitKind { /// The verdict of a limit check. /// -/// A transaction-level exceed stops the transaction: the frame that crosses it reverts, the -/// transaction is latched and every frame above reverts in turn. A frame-local exceed (a frame -/// budget) reverts the frame alone and its caller resumes. `Exempt` is sticky for the -/// transaction: nothing it does is stopped by a limit. +/// An exceed reverts the frame that crossed the limit, alone, and its caller resumes: a +/// transaction-level exceed and a frame-local one (a frame budget) alike, which the revert data +/// tell apart by the limit they name. A transaction exempt from the limits +/// ([`AdditionalLimit::is_exempt`]) is within them whatever it crosses. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum LimitCheck { /// Every limit holds. @@ -179,33 +428,32 @@ pub enum LimitCheck { /// The limit crossed. limit: u64, /// The usage that crossed it. + /// + /// For [`LimitKind::ComputeGas`] it is the transaction's compute before the charge that + /// would have crossed the limit, which the regular ledger bills: gas detention stops a + /// frame on a regular charge its spendable gas could not pay, does not make it, and puts + /// the frame's gas back to what it had before it. The charge's size is not kept, so this + /// is at most the limit, unless a halting frame's leftover, counted as compute, took the + /// transaction past it before the charge. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, }, - /// The transaction is exempt from metering. - Exempt, } impl LimitCheck { - /// Whether a limit was crossed. `Exempt` is not. + /// Whether a limit was crossed. #[inline] pub const fn exceeded_limit(&self) -> bool { matches!(self, Self::ExceedsLimit { .. }) } - /// Whether the check passed. `Exempt` is a state of its own, not a pass. + /// Whether the check passed. #[inline] pub const fn within_limit(&self) -> bool { matches!(self, Self::WithinLimit) } - /// Whether the transaction is exempt from metering. - #[inline] - pub const fn is_exempt(&self) -> bool { - matches!(self, Self::Exempt) - } - /// Whether a frame budget, rather than a transaction-level limit, was crossed. #[inline] pub const fn is_frame_local(&self) -> bool { @@ -218,15 +466,127 @@ impl LimitCheck { Self::ExceedsLimit { kind, limit, .. } => { MegaLimitExceeded { kind: kind.as_u8(), limit: *limit }.abi_encode().into() } - Self::WithinLimit | Self::Exempt => Bytes::new(), + Self::WithinLimit => Bytes::new(), } } } +/// A limit that stopped a transaction: the dimension, the limit and the usage that crossed it, of +/// the crossing that produced the result of the transaction's own frame — a transaction-level +/// limit, or that frame's own data-size budget. It is what an RPC maps a limit stop to, in place of +/// the halt reasons the legacy engine reported one with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LimitStop { + /// The dimension crossed. + pub kind: LimitKind, + /// The limit crossed, in the dimension's unit: bytes or gas. + pub limit: u64, + /// The usage that crossed it (see [`LimitCheck::ExceedsLimit`]). + pub used: u64, +} + +impl LimitStop { + /// The stop a transaction ended with, read off its `result` and the `limit_exceeded` it + /// reports: [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome), or, + /// for a transaction run through another entry point, + /// [`AdditionalLimit::limit_exceeded`] on the EVM's context, read after the transaction ran + /// and before the next transaction or system call starts on the EVM, which resets it. + /// + /// `Some` when both say so: `limit_exceeded` names a crossing, and `result` is a revert whose + /// output is that limit's [`MegaLimitExceeded`]. The output alone never makes a stop. A + /// contract can revert with the same bytes, and a frame a limit stopped below the + /// transaction's own reverts with them while its caller runs on and may re-raise them: + /// `limit_exceeded` is then `None`, and so is this. + pub fn from_result( + result: &ExecutionResult, + limit_exceeded: Option<&LimitCheck>, + ) -> Option { + let stop = limit_exceeded?; + let &LimitCheck::ExceedsLimit { kind, limit, used, .. } = stop else { return None }; + let ExecutionResult::Revert { output, .. } = result else { return None }; + (*output == stop.revert_data()).then_some(Self { kind, limit, used }) + } +} + +/// The dimension and the limit the revert data of a limit stop names: `MegaLimitExceeded(kind, +/// limit)`, exactly as the engine encodes it, with a `kind` a [`LimitKind`] has. `None` for any +/// other bytes, an out-of-range word and trailing data included. +/// +/// Bytes that decode are not a stop by themselves: see [`LimitStop::from_result`]. +pub fn decode_mega_limit_exceeded(revert_data: &[u8]) -> Option<(LimitKind, u64)> { + let decoded = MegaLimitExceeded::abi_decode(revert_data).ok()?; + if decoded.abi_encode() != revert_data { + return None; + } + Some((LimitKind::from_u8(decoded.kind)?, decoded.limit)) +} + #[cfg(test)] mod tests { use super::*; + /// The byte table, written out so a change to one of the sizes is a visible diff. + #[test] + fn test_the_byte_table_is_written_out() { + assert_eq!(WRITE_RECORD_SIZE, 40); + assert_eq!(LOG_BASE_SIZE, 32); + assert_eq!(LOG_TOPIC_SIZE, 32); + assert_eq!(TRANSFER_LOG_SIZE, 160); + assert_eq!(TX_BASE_SIZE, 110); + assert_eq!(TX_FIXED_WRITE_RECORDS, 5); + assert_eq!(TX_BODY_SIZE, 310); + assert_eq!(AUTHORIZATION_SIZE, 101); + assert_eq!(ACCESS_LIST_ADDRESS_SIZE, 20); + assert_eq!(ACCESS_LIST_SLOT_SIZE, 32); + // A storage write and an account write are the same record. + assert_eq!(WRITE_RECORD, LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }); + } + + /// `no_limits` leaves every dimension unlimited: it is what the execution-spec gate installs + /// in equivalence mode. Every field is named, so a limit added later cannot be left out of it. + #[test] + fn test_no_limits_leaves_every_dimension_unlimited() { + let EvmTxRuntimeLimits { + tx_data_size_limit, + frame_data_size_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, + } = EvmTxRuntimeLimits::no_limits(); + for limit in [ + tx_data_size_limit, + frame_data_size_limit, + block_env_access_compute_gas_limit, + oracle_access_compute_gas_limit, + ] { + assert_eq!(limit, u64::MAX); + } + } + + /// The default is the default spec's table, Satin's: the data-size limit and detention's two + /// caps; a caller's limits change a cap alone. + #[test] + fn test_the_default_is_the_specs_table() { + let default = EvmTxRuntimeLimits::default(); + assert_eq!( + default, + crate::ProtocolLimits::for_spec(crate::MegaSpecId::SATIN).tx_runtime_limits + ); + assert_eq!( + default + .with_tx_data_size_limit(u64::MAX) + .with_block_env_access_compute_gas_limit(u64::MAX) + .with_oracle_access_compute_gas_limit(u64::MAX), + EvmTxRuntimeLimits::no_limits() + ); + let limits = EvmTxRuntimeLimits::no_limits() + .with_block_env_access_compute_gas_limit(3) + .with_oracle_access_compute_gas_limit(4); + assert_eq!( + (limits.block_env_access_compute_gas_limit, limits.oracle_access_compute_gas_limit), + (3, 4) + ); + } + #[test] fn test_limit_usage_arithmetic_saturates() { let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; @@ -240,18 +600,7 @@ mod tests { ); } - /// `Exempt` passes no predicate that would stop a frame, and has no revert data. - #[test] - fn test_limit_check_exempt_predicate_truth_table() { - let exempt = LimitCheck::Exempt; - assert!(!exempt.exceeded_limit()); - assert!(!exempt.within_limit()); - assert!(exempt.is_exempt()); - assert!(!exempt.is_frame_local()); - assert!(exempt.revert_data().is_empty()); - } - - /// `within_limit` follows the variant. + /// `within_limit` follows the variant, and is the exact complement of `exceeded_limit`. #[test] fn test_within_limit_reflects_variant() { assert!(LimitCheck::WithinLimit.within_limit()); @@ -264,9 +613,8 @@ mod tests { assert!(!exceeded.within_limit()); assert!(exceeded.exceeded_limit()); assert!(!exceeded.is_frame_local()); - assert!(!exceeded.is_exempt()); - assert!(!LimitCheck::WithinLimit.is_exempt()); assert!(!LimitCheck::WithinLimit.exceeded_limit()); + assert!(!LimitCheck::WithinLimit.is_frame_local()); assert!(LimitCheck::WithinLimit.revert_data().is_empty()); let frame_local = LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, @@ -278,15 +626,12 @@ mod tests { assert!(frame_local.exceeded_limit()); } - /// Every discriminant survives the round trip, and an unknown one maps to nothing. + /// The kinds keep the legacy engine's wire encoding: every discriminant survives the round + /// trip, and the legacy engine's key-value updates, `1`, and state growth, `3`, name no + /// dimension, nor does an unknown kind. #[test] - fn test_limit_kind_u8_roundtrip() { - for (kind, expected) in [ - (LimitKind::DataSize, 0), - (LimitKind::KVUpdate, 1), - (LimitKind::ComputeGas, 2), - (LimitKind::StateGrowth, 3), - ] { + fn test_limit_kind_keeps_its_wire_encoding() { + for (kind, expected) in [(LimitKind::DataSize, 0), (LimitKind::ComputeGas, 2)] { assert_eq!(kind.as_u8(), expected, "{kind:?}"); assert_eq!( LimitKind::from_u8(kind.as_u8()), @@ -294,14 +639,115 @@ mod tests { "round-trip failed for {kind:?}" ); } - assert_eq!(LimitKind::from_u8(4), None); + for retired in [1, 3, 4, u8::MAX] { + assert_eq!(LimitKind::from_u8(retired), None, "{retired}"); + } + } + + /// Every kind's revert data decodes to its kind and limit, and nothing else decodes: another + /// selector, a kind no dimension has, a `uint8` word with high bits set, trailing or missing + /// bytes. + #[test] + fn test_decode_mega_limit_exceeded_accepts_exactly_the_stops_encoding() { + let kinds = [LimitKind::DataSize, LimitKind::ComputeGas]; + for kind in kinds { + let stop = LimitCheck::ExceedsLimit { kind, limit: 7, used: 8, frame_local: false }; + assert_eq!(decode_mega_limit_exceeded(&stop.revert_data()), Some((kind, 7))); + } + + let encoded = |kind: u8| MegaLimitExceeded { kind, limit: 7 }.abi_encode(); + assert_eq!(decode_mega_limit_exceeded(&encoded(1)), None, "a kind no dimension has"); + assert_eq!(decode_mega_limit_exceeded(&encoded(3)), None, "a kind no dimension has"); + assert_eq!(decode_mega_limit_exceeded(&encoded(4)), None, "a kind no dimension has"); + assert_eq!(decode_mega_limit_exceeded(&encoded(u8::MAX)), None); + let mut wide = encoded(0); + wide[4 + 30] = 1; + assert_eq!(decode_mega_limit_exceeded(&wide), None, "a uint8 word with high bits set"); + let mut trailing = encoded(0); + trailing.push(0); + assert_eq!(decode_mega_limit_exceeded(&trailing), None, "trailing bytes"); + let short = encoded(0); + assert_eq!(decode_mega_limit_exceeded(&short[..short.len() - 1]), None, "missing bytes"); + let mut selector = encoded(0); + selector[0] ^= 1; + assert_eq!(decode_mega_limit_exceeded(&selector), None, "another selector"); + assert_eq!(decode_mega_limit_exceeded(&[]), None); + } + + /// A stop is read off the result and `limit_exceeded` together: the revert carrying the + /// limit's data and a check naming it, a frame budget's as well as a transaction-level + /// limit's. Either alone is no stop. + #[test] + fn test_limit_stop_needs_the_revert_and_the_check_to_agree() { + use crate::MegaHaltReason; + use revm::context::result::{HaltReason, ResultGas, SuccessReason}; + + let check = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 3, + used: 4, + frame_local: false, + }; + let revert = |output: Bytes| ExecutionResult::::Revert { + gas: ResultGas::default(), + logs: Default::default(), + output, + }; + let stop = LimitStop { kind: LimitKind::DataSize, limit: 3, used: 4 }; + + assert_eq!(LimitStop::from_result(&revert(check.revert_data()), Some(&check)), Some(stop)); + assert_eq!( + LimitStop::from_result(&revert(check.revert_data()), None), + None, + "the same bytes without the check: a contract's own revert" + ); + let frame_local = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 3, + used: 4, + frame_local: true, + }; + assert_eq!( + LimitStop::from_result(&revert(check.revert_data()), Some(&frame_local)), + Some(stop), + "the transaction's own frame stopped by its budget" + ); + let other_limit = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 9, + used: 10, + frame_local: false, + }; + assert_eq!( + LimitStop::from_result(&revert(check.revert_data()), Some(&other_limit)), + None, + "revert data naming another limit" + ); + assert_eq!(LimitStop::from_result(&revert(Bytes::new()), Some(&check)), None); + assert_eq!( + LimitStop::from_result(&revert(check.revert_data()), Some(&LimitCheck::WithinLimit)), + None + ); + let success = ExecutionResult::::Success { + reason: SuccessReason::Stop, + gas: ResultGas::default(), + logs: Default::default(), + output: revm::context::result::Output::Call(check.revert_data()), + }; + assert_eq!(LimitStop::from_result(&success, Some(&check)), None, "a stop is a revert"); + let halt = ExecutionResult::::Halt { + reason: HaltReason::OutOfGas(revm::context::result::OutOfGasError::Basic).into(), + gas: ResultGas::default(), + logs: Default::default(), + }; + assert_eq!(LimitStop::from_result(&halt, Some(&check)), None); } /// The revert data is the ABI encoding of `MegaLimitExceeded(uint8,uint64)`. #[test] fn test_revert_data_encodes_mega_limit_exceeded() { let check = LimitCheck::ExceedsLimit { - kind: LimitKind::StateGrowth, + kind: LimitKind::ComputeGas, limit: 7, used: 9, frame_local: true, @@ -309,7 +755,7 @@ mod tests { let data = check.revert_data(); assert_eq!(&data[..4], MegaLimitExceeded::SELECTOR.as_slice()); let decoded = MegaLimitExceeded::abi_decode(&data).unwrap(); - assert_eq!(decoded, MegaLimitExceeded { kind: 3, limit: 7 }); + assert_eq!(decoded, MegaLimitExceeded { kind: 2, limit: 7 }); assert_eq!(MegaLimitExceeded::SIGNATURE, "MegaLimitExceeded(uint8,uint64)"); } } diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 93eb729e7..fe980e280 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -3,7 +3,7 @@ use alloy_primitives::Address; use revm::interpreter::SStoreResult; -use super::{LimitUsage, LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD}; +use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; /// What the Host saw an opcode do, staged until the opcode completes. /// @@ -27,8 +27,6 @@ pub enum StagedRecord { SelfDestruct { /// Whether the destructed account had a balance to move. had_value: bool, - /// Whether the beneficiary existed before. - target_exists: bool, /// Whether the beneficiary is another account than the destructed one. to_other_account: bool, /// The beneficiary. @@ -47,6 +45,33 @@ pub(crate) enum RecordEffect { Refund(LimitUsage), } +/// The history bytes a committed record appends, or takes back. +/// +/// They are the record's data size and nothing else: what a log or a write record weighs in a +/// block is what the data-size limit meters it at, so the two cannot drift apart. That is the +/// pairing, and it holds per record; a transaction's two totals part where the byte table says +/// they do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HistoryBytes { + /// Nothing to charge. + None, + /// Bytes the record appends. + Appended(u64), + /// Bytes a record that was taken back no longer appends. + Taken(u64), +} + +impl RecordEffect { + /// The history bytes this effect appends or takes back. + pub(crate) const fn history_bytes(self) -> HistoryBytes { + match self { + Self::None => HistoryBytes::None, + Self::Record(usage) => HistoryBytes::Appended(usage.data_size), + Self::Refund(usage) => HistoryBytes::Taken(usage.data_size), + } + } +} + impl StagedRecord { /// What committing the record counts, per site: /// @@ -72,9 +97,7 @@ impl StagedRecord { } } Self::Log { topics, data_len } => RecordEffect::Record(LimitUsage { - data_size: LOG_BASE_SIZE - .saturating_add(LOG_TOPIC_SIZE.saturating_mul(*topics as u64)) - .saturating_add(*data_len), + data_size: log_history_bytes(u64::from(*topics), *data_len), write_records: 0, }), Self::SelfDestruct { had_value, to_other_account, beneficiary, .. } => { @@ -86,11 +109,20 @@ impl StagedRecord { } } } + + /// Whether the opcode moved value to another account: a `SELFDESTRUCT` of an account that had + /// a balance, to a beneficiary other than itself. revm journals an EIP-7708 transfer log for + /// exactly that move, whoever the beneficiary is — the sender included — and none for a + /// destruction to itself, which burns the balance on Satin's base spec. + pub(crate) const fn moves_value(&self) -> bool { + matches!(self, Self::SelfDestruct { had_value: true, to_other_account: true, .. }) + } } #[cfg(test)] mod tests { use super::*; + use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; use alloy_primitives::{address, U256}; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); @@ -131,18 +163,40 @@ mod tests { ); } + /// A record's history bytes are its data size, at every site: a log's own bytes, a write + /// record's forty, and nothing for a write that leaves no record. + #[test] + fn test_history_bytes_are_the_records_data_size() { + assert_eq!( + sstore(0, 0, 1).effect(SENDER).history_bytes(), + HistoryBytes::Appended(WRITE_RECORD_SIZE) + ); + assert_eq!( + sstore(0, 1, 0).effect(SENDER).history_bytes(), + HistoryBytes::Taken(WRITE_RECORD_SIZE) + ); + assert_eq!(sstore(3, 3, 3).effect(SENDER).history_bytes(), HistoryBytes::None); + assert_eq!( + StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER).history_bytes(), + HistoryBytes::Appended(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32) + ); + let to_other = StagedRecord::SelfDestruct { + had_value: true, + to_other_account: true, + beneficiary: OTHER, + }; + assert_eq!( + to_other.effect(SENDER).history_bytes(), + HistoryBytes::Appended(WRITE_RECORD_SIZE) + ); + } + /// Only value that moves to another account is a beneficiary write. #[test] fn test_selfdestruct_record_rules() { let sd = |had_value, to_other_account| { let beneficiary = OTHER; - StagedRecord::SelfDestruct { - had_value, - target_exists: true, - to_other_account, - beneficiary, - } - .effect(SENDER) + StagedRecord::SelfDestruct { had_value, to_other_account, beneficiary }.effect(SENDER) }; assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); assert_eq!(sd(true, false), RecordEffect::None); @@ -150,10 +204,36 @@ mod tests { assert_eq!(sd(false, false), RecordEffect::None); let to_sender = StagedRecord::SelfDestruct { had_value: true, - target_exists: true, to_other_account: true, beneficiary: SENDER, }; assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); } + + /// Value moves to another account only when a destructed account had a balance and a + /// beneficiary other than itself, the sender included; a write or a log moves none. + #[test] + fn test_only_a_destruction_to_another_account_moves_value() { + let sd = |had_value, to_other_account, beneficiary| StagedRecord::SelfDestruct { + had_value, + to_other_account, + beneficiary, + }; + assert!(sd(true, true, OTHER).moves_value()); + assert!(sd(true, true, SENDER).moves_value(), "the body's record is not the log"); + assert!(!sd(true, false, OTHER).moves_value(), "a destruction to itself burns"); + assert!(!sd(false, true, OTHER).moves_value(), "nothing to move"); + assert!(!sstore(0, 0, 1).moves_value()); + assert!(!StagedRecord::Log { topics: 3, data_len: 32 }.moves_value()); + } + + /// A transfer log counts what a `LOG3` carrying one word counts: the same rule, not a number + /// of its own. + #[test] + fn test_a_transfer_log_counts_what_a_log3_of_one_word_counts() { + assert_eq!( + StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER), + RecordEffect::Record(crate::limit::TRANSFER_LOG) + ); + } } diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 59c78556f..5f450ba7b 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -1,42 +1,78 @@ # AGENTS.md ## OVERVIEW -The six system contracts: their addresses and bytecode, the interceptor dispatch that answers calls to four of them, and the system-address transaction. +The six system contracts: their addresses and bytecode, the interceptor dispatch over four of them (`MegaAccessControl` and `MegaLimitControl` answer, the Oracle's `sendHint` runs a side effect and falls through, and `KeylessDeploy` is routed but left to the keyless dispatch), the system-address transaction, the check Satin's activation block makes of the six and the EIP-7997 factory, which the legacy forks and OP's genesis tooling installed and Satin never deploys, and the registry's pre-block steps: the due-change read and the `applyPendingChanges()` system call. The live system address is read by every transaction when it is validated, not before the block. ## STRUCTURE -- `oracle.rs`: the Oracle's address, code and ABI, and the `sendHint` side effect. +- `oracle.rs`: the Oracle's address, code and ABI, and the `sendHint` side effect. Its storage is read by the Host (`evm/host.rs`), through the oracle environment. - `timestamp.rs`: the High-Precision Timestamp wrapper's address and code. No interceptor. -- `keyless/`: the `KeylessDeploy` address, code and ABI (`mod.rs`), the dispatch of `keylessDeploy` (`dispatch.rs`), and the data-only helpers of the pre-EIP-155 transaction (`tx.rs`, `error.rs`). -- `control.rs`: `MegaAccessControl`'s address, code, ABI and revert payloads, and its interceptor. -- `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor. -- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI. No interceptor. +- `keyless/`: native keyless deployment. The `KeylessDeploy` address, code and ABI and the semantics of a deployment (`mod.rs`); the dispatch, the call's frame and its first run — the overhead, the nine rules, the charges of the creation's start and the creation it starts (`dispatch.rs`); the creation's return into its call and the ABI answer on the call's resume (`settle.rs`); the pre-EIP-155 transaction format and the error ABI (`tx.rs`, `error.rs`). +- `control.rs`: `MegaAccessControl`'s address, code, ABI and revert payloads, `SLOT_NUM_ACCESS_TYPE`, and its interceptor, which steers gas detention's switch. +- `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor, which answers the compute the calling frame could still spend. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its two pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness) and `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) — and `load_system_address`, the warming journal read of the registry's account and `_currentSystemAddress` every transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. +- `predeploys.rs`: the list of the seven predeploys (`system_contract_specs`: address, code, code hash), the EIP-7997 factory's constants, and `check_system_contract`, the read Satin's activation block makes of each: exactly the expected code, whatever the nonce, balance and storage, or `SystemContractCheckError::UnexpectedCode` naming the address and both hashes. - `intercept.rs`: the dispatch — the address test, the selector peek, the value policy and the shape of an answer. -- `tx.rs`: the system-address transaction, its whitelist and the validation that precedes its promotion to a deposit. +- `tx.rs`: the system-address transaction, its whitelist and shape, the per-transaction decision and the refusal of another shape from the system address (`classify_system_transaction`), and the validation that precedes its promotion to a deposit. ## KEY PATTERNS - The dispatch order is: the scheme guard (`MegaEvm::intercept`), the address, the selector, then the method's value policy. Each step is cheaper than the next; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes. +- `keylessDeploy` is not intercepted: a call a transaction makes is taken by the keyless dispatch, which runs before interception in `frame_init`, and is built as a frame on the contract in which no code runs; its first run starts a native `CREATE` of its signer. Its test costs one comparison on every frame: the depth, then the address and the selector. - A selector is admitted on its four bytes alone. Trailing bytes are accepted; an input shorter than four bytes is not a selector and is not admitted. -- An unknown selector is never intercepted: the call falls through to the deployed bytecode, and what that bytecode answers is the contract's own. The two control contracts revert with `NotIntercepted()` from their fallback; `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data while a `keylessDeploy` call reaches the method body's `NotIntercepted()`; the Oracle runs its other methods, and reverts with empty data on a selector it does not declare. +- An unknown selector is never intercepted: the call falls through to the deployed bytecode, and what that bytecode answers is the contract's own. The two control contracts revert with `NotIntercepted()` from their fallback; `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data while a `keylessDeploy` call a contract makes reaches the method body's `NotIntercepted()`; the Oracle runs its other methods, and reverts with empty data on a selector it does not declare. - `CALL` and `STATICCALL` reach the dispatch. `CALLCODE` and `DELEGATECALL` run the callee's code in the caller's context, so they are refused by the scheme guard before any interceptor. - A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names (`KeylessDeploy` answers `NoEtherTransfer()`). The policy is per method and is applied after the selector matched, so a value-bearing call to an unknown selector still falls through. - An answer is a `synthetic_call_result`: the forwarded gas untouched, the caller's reservoir carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. -- An interceptor that lets the frame run may charge it instead of answering it, by taking gas off the frame's limit (`KeylessDeploy`'s fixed overhead). That is why the dispatch takes the call inputs mutably. -- The Oracle's `sendHint` is a side effect, not an answer: it forwards the hint and returns `None`, so the contract's own bytecode runs. It forwards only for a call that could deliver it — no value, some gas — and the payload is counted on the transaction's data size before it is decoded. -- The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The whitelist, the chain id, the nonce and EIP-3607 are checked there, each under the configuration switch a user transaction obeys. -- Accounts read during validation are read without warming them, so the transaction pays what any other transaction would pay for its first touch. +- An interceptor that lets the frame run charges nothing: the frame starts as it was built. +- A keyless deployment's call is a real frame at depth 0 in which no code runs: revm builds it on the contract, with its journal checkpoint, its gas and the lane a depth-0 call pushes, and `frame_run` makes its actions by hand (`keyless::run`, keyed on `MegaContext::keyless_frame`). Its first run, held by gas detention as any frame's, pays the overhead and what the `CREATE` opcode charges its frame, runs its lane as the signer, and returns the creation as its child at depth 1, or a refusal. The creation returns into it through `frame_return_result`, which reads the creation's outcome before revm's merge (`keyless::returning`) and applies the nonce take-back after (`keyless::settle`); on its resume the call answers in the ABI, unless it has a stop to return. The contract's account is touched as any call's target is, and its code never runs for a dispatched call. +- What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps what the creation's start wrote, a signer's nonce spent from 0 to 1, its account and its record; a call that reverts with a stop takes the whole deployment back through its checkpoint. A creation that never started (one an inspector answered) gives the signer's account back. A deployment from nonce 1 keeps no bump when the bump is the last nonce change it made, whether it deployed or failed: the settlement sets the nonce back, so the signer stays at 1, nobody can use up its attempts, and a resubmission of one that deployed is refused `ContractAlreadyExists()`, as in the legacy engine. It takes the record and its history back with the bump, unless the creation succeeded and moved value out of the signer, whose account then keeps a write of its own. A signer whose own code spends a nonce in the constructor that survives it — on a default configuration, a delegated signer's `CREATE` or `CREATE2`, successful or not — keeps every bump, because a later bump may stand for an account and the nonce is never moved back under it; that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. +- The Oracle's `sendHint` is a side effect, not an answer: it forwards the hint and returns `None`, so the contract's own bytecode runs. It forwards only for a call that could deliver it — no value, some gas, a calling frame whose volatile-data access is on — and the payload is counted on the transaction's data size before it is decoded. A hint that fails one of those conditions is neither forwarded nor counted, and neither is one whose payload would cross the transaction's data-size limit: the limit is checked before the bytes are counted, the call is answered with the stop, a revert of the call alone, and the transaction keeps none of the hint's bytes. A payload that is admitted and does not decode is counted and forwards nothing. +- An interceptor that acts for its caller takes the caller as the frame one level above the frame the call would start (`depth - 1`). A transaction that calls a system contract directly has no calling frame: `MegaAccessControl` then switches nothing off, enables without refusal and answers `false`, and `remainingComputeGas()` answers the transaction's own frame's regular gas, or detention's cap when it is detained from its start (its sender is the block beneficiary). +- `remainingComputeGas()` is read when the call reaches the dispatch, after the calling opcode charged its own costs: the lesser of the caller's regular gas with the forward counted back (`MegaEvm::intercept` passes what the caller has left; the answer returns the forward untouched) and gas detention's allowance at the call. That is the caller's spendable regular gas before the forward, which detention caps. This departs from the legacy engine's figure, which came from a separate compute ledger, with per-frame budgets of 98/100 of the caller's remaining compute under the transaction's compute limit, so it could exceed the caller's gas; here compute is regular gas, and the answer is at most the caller's own. The one property carried over is that forwarded gas is not counted. +- `VolatileDataAccessDisabled`'s argument is a `uint8` on the wire. A refused `SLOTNUM` names 12 (`SLOT_NUM_ACCESS_TYPE`), past the contract's enum, so Solidity handlers decode the argument as `uint8`; the contracts are not changed for it, and their code hashes stay. +- A transaction is a system-address transaction when it has the system shape (a legacy call to a whitelisted contract) and its caller is the address the registry names. Every transaction reads the registry when it is validated, whatever its shape, and the read leaves the registry's account and `_currentSystemAddress` warm for the rest of the transaction, as EIP-3651 leaves the block beneficiary, so what a transaction pays never depends on its envelope. A transaction from the system address without the shape is invalid (`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`), a deposit from it a failed deposit; every other sender is an ordinary one. +- The system-address transaction is validated before it is promoted to a deposit, because the deposit path validates nothing. The chain id is checked there always, as the spec checks every transaction's, and must be present; the nonce and EIP-3607 each under the configuration switch a user transaction obeys. +- Accounts and slots read during validation are read with revm's own loads, which warm them: the registry's account and slot, warm for every transaction by rule, and the system address's account, the transaction's caller, which the transaction starts warm anyway. + +## PRE-BLOCK STATE CHANGE CONTRACT + +Pre-block helpers in this module participate in `apply_pre_execution_changes` on `MegaBlockExecutor`. +The contract for a new or modified helper: + +- Never call `db.commit(...)` inside the helper. + Return the prepared state; let the executor commit. +- On a read that changes nothing (a predeploy holding the expected code, the registry's due check), return `EvmState` that carries the observed account as a read-only entry: neither `touched` nor `created`. + Returning nothing here is a bug — the account disappears from the stateless witness read set. +- On a step that writes (`applyPendingChanges()`), include every account and storage slot the helper touched. +- A predeploy holding other code is an error, never an overwrite or an upgrade: Satin's activation block refuses a chain that does not hold the seven at the versions it runs. + +The returned `EvmState` is both the commit and the witness record of that step. +The executor commits it on its own, in the order the steps run: a commit hook on the block's state receives each committed state whole, read-only entries included, and that sequence is the witness a stateless client needs. ## ANTI-PATTERNS - Do not answer an unknown selector with a synthetic revert: the on-chain bytecode is the fall-through, and what it answers is the contract's own business. - Do not materialise calldata before the address and the selector matched. `peek_selector` borrows four bytes; `CallInput::bytes` copies the whole payload. - Do not build an answer from a bare gas limit. Use `synthetic_call_result`, which carries the reservoir and the upfront-charge flags. +- Do not charge a keyless deployment's start out of the creation's gas, and do not read the creation's result anywhere but where it returns into the call (`frame_return_result`, before revm's merge, which keeps nothing of it but its gas): the call pays the start as a `CREATE`'s frame does, and every creation's result, one answered at its start included, returns there. +- Do not rebuild a step of the frame lifecycle by hand for a keyless deployment's call: its start, its suspension on the creation, the merge of the creation's gas, its checkpoint and its stops are revm's and the engine's frame wrappers'. Only its two actions are hand-made. +- Do not turn a failed read or SALT lookup of a keyless deployment into an ABI error: it fails the transaction with its cause, as it does at every other site. - Do not add a length check to a selector match. Admission is the four bytes. - Do not accept value on a read-only or control method without saying why in the interceptor and pinning it with a test. - Do not deploy system bytecode from a literal in this crate; the `mega-system-contracts` crate ships the code and its hash. The timestamp wrapper is the one exception, because the Oracle's address is baked into its code. -- Do not read the system address from a constant in new code once the `SequencerRegistry` is read: the address can be rotated. +- Do not read the system address from a constant or hold it on the context: the address can be rotated, and the registry in the state the EVM runs on is the one source. +- Do not skip the registry read for a transaction of some shape: every transaction starts with the registry warm, and a read that depends on the envelope makes the gas depend on it too. +- Do not call `db.commit(...)` inside a helper that participates in `apply_pre_execution_changes`. + It takes the step out of the executor's sequence: the executor commits each step's state on its own, in order, and only once the step succeeded, and that sequence is the witness. +- Do not return nothing from a helper on a "no change needed" path. + Return the account entries observed, even when nothing is written. +- Do not create, overwrite or upgrade a predeploy from the engine: the legacy forks installed them, and Satin's activation block only checks them. ## WHERE TO LOOK - Add a method to an intercepted contract: the contract's own module, next to the selectors it already answers, and a boundary test per `tests/system/`. - Change what a call to a system contract costs: `intercept.rs` for the dispatch, the contract's module for what its own method charges. -- Change the system transaction's validation: `tx.rs::validate_and_promote`, which `MegaHandler::validate_env` calls. +- Change a keyless deployment: `keyless/dispatch.rs` for what is dispatched, the rules and the charges of the creation's start; `keyless/settle.rs` for the creation's return into the call and the answer; `evm/execution.rs` for where they are called — `frame_init`, `frame_run` and `frame_return_result`; `tests/system/keyless/` for the tests. +- Change the system transaction's validation: `tx.rs::validate_and_promote`, which `MegaHandler::validate_env_as` calls for both the handler's `validate_env` and the stateless pool validation (`evm/validation.rs`, which leaves the system address's nonce and code to the state). - Change what a deposit-like transaction pays for the account it creates: `evm/execution.rs`, where the charge is made in the pre-execution phase. -- Deploy the contracts at a fork, read the rotated system address, or run the pre-block calls: not here yet — system contract deployment and the pre-block system calls own those. +- Add a predeploy: a spec in `predeploys.rs::system_contract_specs`, which Satin's activation block then checks; a contract Satin itself would install needs a mechanism of its own, which the engine no longer has. +- Change how the activation block checks the predeploys: `block/executor.rs::apply_pre_execution_changes` iterates the spec list when `MegaBlockExecutionCtx::satin_activation_block` is set, commits each read as a state of its own, and refuses the block on the first unexpected code. +- Change when a role change is applied: `sequencer_registry.rs`, whose two pre-block helpers `block/executor.rs::apply_pre_execution_changes` calls after the predeploy check, in that order. +- Change how the live system address is read: `sequencer_registry.rs::load_system_address`, which `MegaHandler::validate_env` calls, and `MegaHandler::validate_env_as`, which decides from the address whether the transaction is a system-address transaction; the answer lives on the context as the transaction's system-originated flag (`MegaContext::is_system_originated`). `sequencer_registry.rs::live_system_address` makes the same read off a database, for a pool. diff --git a/crates/mega-evm/src/system/control.rs b/crates/mega-evm/src/system/control.rs index 21043b806..23d017262 100644 --- a/crates/mega-evm/src/system/control.rs +++ b/crates/mega-evm/src/system/control.rs @@ -40,38 +40,101 @@ pub const DISABLED_BY_PARENT_REVERT_DATA: [u8; 4] = IMegaAccessControl::Disabled pub const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; +/// The access type a refused `SLOTNUM` names in `VolatileDataAccessDisabled`: 12, one past the +/// last variant of the contract's `VolatileDataAccessType`. +/// +/// The enum was written before the block's slot number became volatile data, and the system +/// contracts are deployed as they are, so it has no variant for it. The error's argument is +/// encoded as the `uint8` an enum encodes as, so a refused `SLOTNUM` carries 12 like any other +/// kind carries its variant. A handler that decodes the argument as `VolatileDataAccessType` +/// cannot name 12: Solidity's ABI decoder reverts on an enum value out of range, and this crate's +/// `IMegaAccessControl` binding decodes it to the placeholder `__Invalid`. Solidity handlers must +/// decode the argument as `uint8`. +/// [`decode_volatile_data_access_disabled`](crate::decode_volatile_data_access_disabled) is the +/// Rust side's decoder, and maps every access type the engine names, 12 included. +pub const SLOT_NUM_ACCESS_TYPE: u8 = 12; + /// Answers a call to `MegaAccessControl`, or `None` when the selector is not one of its three -/// and the deployed bytecode runs. +/// and the deployed bytecode runs. `depth` is the depth of the frame the call would start. +/// +/// # The switch +/// +/// The three methods steer and read gas detention's switch ([`Detention`](crate::Detention)), +/// for the frame that made the call — the caller, one level above the frame the call would start: /// -/// # What the three methods do today +/// - `disableVolatileDataAccess()` switches volatile-data access off for the caller and every frame +/// below it, once its answer settles without crossing gas detention's compute limit: an answer +/// that becomes the stop leaves the switch as it was. A switch already off from a frame above +/// stays as it is. +/// - `enableVolatileDataAccess()` switches it back on, and reverts with `DisabledByParent()` when a +/// frame above the caller switched it off: a frame cannot lift a restriction its caller placed. +/// Switching on what is not off succeeds and changes nothing. +/// - `isVolatileDataAccessDisabled()` answers whether the switch is off for the caller. /// -/// The switch itself belongs to detention, which brings the tracker that remembers a frame's -/// answer and the volatile reads that consult it. Until then the interceptor is the dispatch -/// and the value policy: `disableVolatileDataAccess` and `enableVolatileDataAccess` succeed and -/// change nothing, and `isVolatileDataAccessDisabled` answers `false`, which is what the common -/// execution layer knows — no frame has ever switched access off. `DisabledByParent()`, the -/// answer to a frame that re-enables what a frame above it disabled, is the tracker's to give. +/// While the switch is off, the Host refuses every volatile read of the caller's subtree and the +/// reading frame reverts with `VolatileDataAccessDisabled`. The caller reads the switch as it +/// resumes after the call, and it turns back on when the frame that switched it off returns, +/// whatever it returns with, so a sibling called afterwards is not restricted. /// -/// All three take no value: they read or steer execution, and the contract holds no balance. +/// A transaction that calls the contract directly has no frame of its own above the one the call +/// starts: nothing runs after the answer, so disabling changes nothing, enabling succeeds and the +/// query answers `false`. +/// +/// All three take no value: they read or steer execution, and the contract holds no balance. A +/// `STATICCALL` reaches them too, because the switch is not state: it lives for the transaction +/// and leaves nothing behind. pub(crate) fn intercept( - ctx: &MegaContext, + ctx: &mut MegaContext, inputs: &CallInputs, + depth: usize, ) -> Option { let selector = peek_selector(&inputs.input, ctx)?; // Selector-only admission: the four bytes decide, whatever follows them. - let output = if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR || - selector == IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR - { - Bytes::new() + let method = if selector == IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR { + Method::Disable + } else if selector == IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR { + Method::Enable } else if selector == IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR { - Bytes::from(IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns( - &false, - )) + Method::IsDisabled } else { return None; }; if let Some(rejected) = reject_non_zero_transfer(inputs) { return Some(rejected); } - Some(synthetic_call_result(inputs, InstructionResult::Return, output)) + let caller = depth.checked_sub(1); + let detention = &mut ctx.detention; + let (result, output) = match method { + Method::Disable => { + if let Some(caller) = caller { + detention.disable_access_on_answer(caller); + } + (InstructionResult::Return, Bytes::new()) + } + Method::Enable => { + if caller.is_none_or(|caller| detention.enable_access(caller)) { + (InstructionResult::Return, Bytes::new()) + } else { + (InstructionResult::Revert, Bytes::from_static(&DISABLED_BY_PARENT_REVERT_DATA)) + } + } + Method::IsDisabled => { + let disabled = caller.is_some_and(|caller| detention.is_access_disabled(caller)); + let output = + IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&disabled); + (InstructionResult::Return, Bytes::from(output)) + } + }; + Some(synthetic_call_result(inputs, result, output)) +} + +/// The three methods `MegaAccessControl` intercepts. +#[derive(Clone, Copy, Debug)] +enum Method { + /// `disableVolatileDataAccess()`. + Disable, + /// `enableVolatileDataAccess()`. + Enable, + /// `isVolatileDataAccessDisabled()`. + IsDisabled, } diff --git a/crates/mega-evm/src/system/intercept.rs b/crates/mega-evm/src/system/intercept.rs index a2b5c40d6..1dd165d30 100644 --- a/crates/mega-evm/src/system/intercept.rs +++ b/crates/mega-evm/src/system/intercept.rs @@ -20,8 +20,8 @@ //! - the two control contracts have a fallback that reverts with `NotIntercepted()`, so every //! selector they do not intercept ends there; //! - `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data; -//! a `keylessDeploy` call the dispatch did not take — one a contract makes — reaches the -//! method body and its own `NotIntercepted()`, as a dispatched one does after its charge; +//! a `keylessDeploy` call the keyless dispatch did not take — one a contract makes — reaches +//! the method body and its own `NotIntercepted()`; //! - the Oracle's other selectors are methods it runs (`getSlot`, `version`), and one it does //! not declare reverts with empty data. //! @@ -70,19 +70,21 @@ const SYSTEM_CONTRACT_PREFIX: [u8; 19] = { prefix }; -/// A system contract whose calls an interceptor answers. +/// A system contract whose calls the engine answers or rewrites. /// /// The High-Precision Timestamp wrapper and the `SequencerRegistry` are not here: they have no -/// interceptor and run their bytecode. +/// interceptor and run their bytecode. `KeylessDeploy` is, but its `keylessDeploy` calls are taken +/// by the keyless dispatch before interception (see [`crate::system::keyless`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum InterceptedContract { /// The Oracle: `sendHint` reaches the node's oracle service. Oracle, - /// `KeylessDeploy`: `keylessDeploy` deploys a pre-EIP-155 transaction. + /// `KeylessDeploy`: `keylessDeploy` deploys a pre-EIP-155 transaction, through the keyless + /// rewrite rather than an interceptor. KeylessDeploy, /// `MegaAccessControl`: the volatile-data access switch. AccessControl, - /// `MegaLimitControl`: what the running call has left. + /// `MegaLimitControl`: what the calling frame has left. LimitControl, } @@ -109,22 +111,28 @@ pub(crate) fn intercepted_contract(address: &Address) -> Option( ctx: &mut MegaContext, - inputs: &mut CallInputs, + inputs: &CallInputs, depth: usize, + caller_remaining: u64, ) -> Option { match intercepted_contract(&inputs.target_address)? { - InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs), - InterceptedContract::KeylessDeploy => crate::system::keyless::intercept(ctx, inputs, depth), - InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs), - InterceptedContract::LimitControl => crate::system::limit_control::intercept(ctx, inputs), + InterceptedContract::Oracle => crate::system::oracle::intercept(ctx, inputs, depth), + InterceptedContract::KeylessDeploy => None, + InterceptedContract::AccessControl => crate::system::control::intercept(ctx, inputs, depth), + InterceptedContract::LimitControl => { + crate::system::limit_control::intercept(ctx, inputs, depth, caller_remaining) + } } } diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index 133643156..ccc65c088 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -1,75 +1,478 @@ -//! The dispatch of `KeylessDeploy` calls. -//! -//! A `keylessDeploy(bytes,uint256)` call is recognised here, charged the fixed overhead, and -//! handed to the keyless rewrite hook, which turns it into the creation it stands for. The -//! rewrite is native keyless deployment's; until it lands the recognised call runs the deployed -//! bytecode, which reverts with `NotIntercepted()`, and the overhead is charged all the same. +//! The dispatch of `KeylessDeploy` calls: which calls are keyless deployments, what such a call +//! pays before its creation starts, the rules it is held to, and the creation it starts. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::boxed::Box; use alloy_evm::Database; -use alloy_primitives::Bytes; -use alloy_sol_types::{SolCall, SolError}; +use alloy_primitives::{Address, Bytes, U256}; +use alloy_sol_types::SolCall; use revm::{ - handler::FrameResult, - interpreter::{CallInputs, InstructionResult}, + context::{Cfg, ContextError, ContextTr, JournalTr, Transaction}, + context_interface::{ + cfg::{GasId, StateGasCharge, StateGasSite}, + Host, + }, + handler::{EthFrame, FrameResult}, + interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInputs, CallScheme, + CreateInputs, CreateScheme, FrameInput, Gas, InstructionResult, InterpreterAction, + }, + primitives::KECCAK_EMPTY, + state::Bytecode, }; use crate::{ + charge_write_records_history, + limit::FrameStartRecords, synthetic_call_result, system::{ intercept::peek_selector, - keyless::{IKeylessDeploy, KEYLESS_DEPLOY_OVERHEAD_GAS}, + keyless::{ + calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, + recover_signer, settle, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, }, - ExternalEnvTypes, MegaContext, + untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -/// Recognises a `keylessDeploy` call and charges it, or answers it when it cannot go on. +/// Where a `keylessDeploy` call's frame stands, from its start to its answer: what its first run +/// and its resume need of each other, kept on the context while the frame is on revm's stack. +#[derive(Debug)] +pub(crate) enum KeylessFrame { + /// revm built the call's frame, which has not run. + Built, + /// The call's first run started its creation, which runs. + Deploying(Started), + /// The creation returned into the call, which answers on its resume. + Returned(settle::Returned), +} + +/// What a `keylessDeploy` call's creation is settled into the call with. +#[derive(Debug)] +pub(crate) struct Started { + /// The address the creation deploys at. + pub(super) deploy_address: Address, + /// The signer, and its nonce before the creation's start bumped it. + pub(super) signer: Address, + pub(super) signer_nonce: u64, + /// What the call was charged for the signer's account, which the creation's start creates: + /// zero when the signer had one. + pub(super) signer_account_charge: u64, + /// The history the call paid for the signer's nonce record: zero when the signer is the + /// transaction's sender, which makes no record, or when the transaction pays no history. + pub(super) signer_record_charge: u64, + /// Whether the creation moves value out of the signer's account. + pub(super) moves_value: bool, + /// Whether the deposit of empty code at the deploy address was refused, which reverts the + /// creation ([`refuses_empty_deposit`](settle::refuses_empty_deposit)). + pub(super) empty_deposit_refused: bool, +} + +/// Whether `frame_init` starts a `keylessDeploy` call the dispatch takes: a `CALL` at depth 0 to +/// [`KEYLESS_DEPLOY_ADDRESS`] carrying the `keylessDeploy` selector. +/// +/// Only a transaction deploys, so the deployment's answer is never something an inner caller can +/// read off its own return data. A call a contract makes, and a selector the contract does not +/// declare, run the deployed bytecode: a `keylessDeploy` call reaches the method body and its +/// `NotIntercepted()`, and an undeclared selector finds no function and no fallback, so it reverts +/// with empty data. +/// +/// The depth is tested first: every frame below the transaction's own leaves after one +/// comparison. +#[inline] +pub(crate) fn is_dispatched( + ctx: &MegaContext, + frame_init: &FrameInit, +) -> bool { + let FrameInput::Call(inputs) = &frame_init.frame_input else { return false }; + frame_init.depth == 0 && + inputs.target_address == KEYLESS_DEPLOY_ADDRESS && + inputs.scheme == CallScheme::Call && + peek_selector(&inputs.input, ctx) == Some(IKeylessDeploy::keylessDeployCall::SELECTOR) +} + +/// Readies the frame of a call [`is_dispatched`] took for revm to build, or answers it. +/// +/// A call carrying value is answered before revm builds its frame, which would move the value and +/// journal its transfer log: it pays the overhead, and is refused `NoEtherTransfer()` — rules 1 +/// and 2 of [`start`] — on its gas as its caller forwarded it, held by gas detention as the frame +/// would be. +/// +/// Any other call is built as a call to the contract, whose code it never runs: its actions are +/// made by [`run`]. The dispatch is by address and selector, whatever the address holds, so where +/// the state holds no contract code the frame is built on the contract's own. A chain Satin runs +/// on holds it, as Rex2 deployed it, and Satin's activation block checks it. +#[inline(never)] +pub(crate) fn ready( + ctx: &mut MegaContext, + frame_init: &mut FrameInit, +) -> Result, ContextError> { + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return Ok(None) }; + if inputs.call_value().is_zero() { + if inputs.known_bytecode.1.is_empty() { + inputs.known_bytecode = + (KEYLESS_DEPLOY_CODE_HASH, Bytecode::new_raw(KEYLESS_DEPLOY_CODE)); + } + return Ok(None); + } + let mut gas = untouched_call_gas(inputs); + ctx.detention.hold(&mut gas); + let Err(refusal) = prepare(ctx, inputs, &mut gas)? else { + unreachable!("a call carrying value is refused at rule 2") + }; + Ok(Some(refusal.answer(inputs, gas))) +} + +/// Whether `frame` is a `keylessDeploy` call's, whose actions [`run`] makes in place of an +/// interpreter: the transaction's own frame, while the dispatch keeps its state. +#[inline] +pub(crate) fn runs( + ctx: &MegaContext, + frame: &EthFrame, +) -> bool { + frame.depth == 0 && ctx.keyless_frame.is_some() +} + +/// The next action of a `keylessDeploy` call's frame, made by hand: on its first run, the refusal +/// or the creation [`start`] makes; on its resume, once its creation returned into it, its answer +/// ([`settle::answer`]). /// -/// # What is dispatched +/// A frame with a stop to return — a limit the nonce record a failed creation leaves the call +/// crosses — returns it before this runs, as any frame does. +#[inline(never)] +pub(crate) fn run( + ctx: &mut MegaContext, + frame: &mut EthFrame, +) -> Result> { + match ctx.keyless_frame.take() { + Some(KeylessFrame::Built) => start(ctx, frame), + Some(KeylessFrame::Returned(returned)) => { + Ok(settle::answer(ctx, &returned, frame.interpreter.gas)) + } + state => unreachable!("a keylessDeploy call runs when built or returned into: {state:?}"), + } +} + +/// The first run of a `keylessDeploy` call's frame: charges its gas and holds it to the rules, in +/// the order below, then starts the creation it stands for. /// -/// Only a transaction reaches the deployment: `depth` is the depth of the frame the call would -/// start, and a call a contract makes (`depth > 0`) is not dispatched, so the deployment's -/// answer is never something an inner caller can read off its own return data. A call whose -/// selector is not `keylessDeploy` is not dispatched either. Both run the deployed bytecode, -/// which answers them differently: a `keylessDeploy` call reaches the method body and its -/// `NotIntercepted()`, while a selector the contract does not declare finds no function and no -/// fallback, so it reverts with empty data. +/// # What the call pays, and what it is held to /// -/// # What it charges +/// In this order, each refusal the frame's return with its gas as it stands: /// -/// A dispatched call pays [`KEYLESS_DEPLOY_OVERHEAD_GAS`] of regular gas before anything else: -/// the frame is handed that much less gas, so the caller pays it whatever the deployment does. -/// A call that was not forwarded enough gas to pay it is answered out of gas, as a frame that -/// ran out is. +/// 1. [`KEYLESS_DEPLOY_OVERHEAD_GAS`] of regular gas, whatever the deployment does: decoding the +/// transaction and recovering its signer. A call that cannot pay it runs out of gas. +/// 2. The call carries no value (`NoEtherTransfer()`). A call carrying value is refused before revm +/// builds its frame ([`ready`]). +/// 3. Its arguments decode, and so does the transaction they carry: a signed legacy creation, no +/// chain id, no trailing bytes (`MalformedEncoding()`, `NotContractCreation()`, +/// `NotPreEIP155()`), signed at nonce 0 (`NonZeroTxNonce`). +/// 4. The init code is within the configured initcode size limit (`InitCodeTooLarge`). +/// 5. `gasLimitOverride` covers the signed gas limit (`GasLimitTooLow`). +/// 6. The signer can be recovered (`InvalidSignature()`). +/// 7. The signer's nonce is at most 1 (`SignerNonceTooHigh`). A signer that is the block +/// beneficiary makes this read a read of the beneficiary's account, which gas detention caps as +/// it caps a sender that is the beneficiary. +/// 8. Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation +/// (`SignerHasCode()`). +/// 9. The signer's account, when the creation's nonce bump is what creates it: state gas, priced by +/// the signer's SALT bucket. A call that cannot pay runs out of gas. +/// 10. `gasLimitOverride`, capped to what the call has left, still covers the signed gas limit +/// (`GasLimitTooLow`). +/// 11. The deploy address holds no code (`ContractAlreadyExists()`), read without its code, so the +/// address is in the transaction's state and in a witness without its bytecode. +/// 12. The signer can fund the transaction's value (`InsufficientBalance()`). +/// 13. What the `CREATE` opcode charges its frame for the creation's start, in the opcode's order: +/// its regular gas — the schedule's `create` entry and EIP-3860's cost per word of init code — +/// the created account when the deploy address is empty — state gas, priced by the deploy +/// address's SALT bucket — and the write records of the two accounts, as history. A call that +/// cannot pay runs out of gas. +/// 14. The gas the creation is forwarded is `gasLimitOverride`, capped to what the call has left, +/// and must still cover the signed gas limit (`GasLimitTooLow`). /// -/// # What it refuses +/// The order is the legacy engine's, so a call several rules refuse is refused with the error the +/// legacy engine reported: it charged the signer's account at step 9 and re-checked the forward +/// right after, before the deploy address and the balance. The charges of step 13 are this +/// engine's, made after every rule, and step 14 holds the forward to them. /// -/// A `keylessDeploy` call carries no value: the deployment is made by the transaction's signer, -/// not by the caller, and the contract holds no balance. A call that carries one is answered -/// with the ABI's own `NoEtherTransfer()`, after the overhead was charged. -pub(crate) fn intercept( - ctx: &MegaContext, - inputs: &mut CallInputs, - depth: usize, -) -> Option { - if depth != 0 { - return None; - } - let selector = peek_selector(&inputs.input, ctx)?; - if selector != IKeylessDeploy::keylessDeployCall::SELECTOR { - return None; - } - let Some(charged) = inputs.gas_limit.checked_sub(KEYLESS_DEPLOY_OVERHEAD_GAS) else { - let mut result = synthetic_call_result(inputs, InstructionResult::OutOfGas, Bytes::new()); - result.gas_mut().spend_all(); - return Some(result); +/// A refusal writes nothing, so its return takes back the state and history gas the call was +/// charged; the regular gas it spent stays spent, as a frame's does — the overhead, and, for the +/// refusal at step 14, the `CREATE` opcode's regular gas. A database read or a SALT lookup that +/// fails fails the transaction with its cause, as it does at every other site. +/// +/// # The creation +/// +/// The creation is started as the signer's, at the signer's Nick's-Method address +/// (`CreateScheme::Custom`), as the call's child: its share of the data-size budget, its records, +/// its forward and the reservoir it inherits. The call's lane runs as the signer, whose +/// nonce the creation's start writes. The call's journal checkpoint was taken when revm built its +/// frame, so a call that is stopped takes that write back with the rest. +fn start( + ctx: &mut MegaContext, + frame: &mut EthFrame, +) -> Result> { + let FrameInput::Call(inputs) = &frame.input else { + unreachable!("a keylessDeploy call's frame is a call") + }; + let gas = &mut frame.interpreter.gas; + let deployment = match prepare(ctx, inputs, gas)? { + Ok(deployment) => deployment, + Err(refusal) => { + let (result, output) = refusal.result(gas); + return Ok(InterpreterAction::new_return(result, output, *gas)); + } }; - inputs.gas_limit = charged; + ctx.additional_limit.set_frame_creator(deployment.signer); + if let Some((on_lane, caller)) = deployment.record_charges { + ctx.additional_limit.stage_frame_charge(deployment.records, on_lane, caller); + } + let mut create = CreateInputs::new( + deployment.signer, + CreateScheme::Custom { address: deployment.deploy_address }, + deployment.value, + deployment.init_code, + deployment.gas_limit, + gas.reservoir(), + ); + create.set_charged_create_state_gas(deployment.charged_create_state_gas); + create.set_charged_state_gas_address(deployment.deploy_address); + ctx.keyless_frame = Some(KeylessFrame::Deploying(Started { + deploy_address: deployment.deploy_address, + signer: deployment.signer, + signer_nonce: deployment.signer_nonce, + signer_account_charge: deployment.signer_account_charge, + signer_record_charge: deployment.record_charges.map_or(0, |(_, caller)| caller), + moves_value: !deployment.value.is_zero(), + empty_deposit_refused: false, + })); + Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) +} + +/// A creation the call passed every rule for and paid the start of. +struct Deployment { + signer: Address, + signer_nonce: u64, + /// What the call was charged for the signer's account, when the signer has none. + signer_account_charge: u64, + deploy_address: Address, + value: U256, + init_code: Bytes, + /// The gas forwarded to the creation, already taken off the call's gas. + gas_limit: u64, + /// Whether the call was charged the created account. + charged_create_state_gas: bool, + /// The records the creation's start makes. + records: FrameStartRecords, + /// What the call paid for them: the created account's, and the signer's. `None` when the + /// transaction pays no history. + record_charges: Option<(u64, u64)>, +} + +/// Why a call is refused. +enum Refusal { + /// A rule refused it: a revert with the rule's error. + Rule(KeylessDeployError), + /// It could not pay: an out-of-gas that spends what it has. + OutOfGas, +} + +impl Refusal { + /// What the call returns, on `gas`: a revert with the rule's error, or an out-of-gas, which + /// spends it all. + fn result(self, gas: &mut Gas) -> (InstructionResult, Bytes) { + match self { + Self::Rule(error) => (InstructionResult::Revert, encode_error_result(error)), + Self::OutOfGas => { + gas.spend_all(); + (InstructionResult::OutOfGas, Bytes::new()) + } + } + } + + /// The answer to the call `inputs` start, carrying `gas`: the call's gas as the refusal left + /// it, with the reservoir it inherited. + fn answer(self, inputs: &CallInputs, mut gas: Gas) -> FrameResult { + let (result, output) = self.result(&mut gas); + let mut answer = synthetic_call_result(inputs, result, output); + *answer.gas_mut() = gas; + answer + } +} + +/// Holds the call `inputs` to the rules and charges `gas` for what the creation's start makes, in +/// the order [`start`] lists; the deployment to start, or why the call is refused. +fn prepare( + ctx: &mut MegaContext, + inputs: &CallInputs, + gas: &mut Gas, +) -> Result, ContextError> { + macro_rules! refuse { + ($error:expr) => { + return Ok(Err(Refusal::Rule($error))) + }; + } + if !gas.record_regular_cost(KEYLESS_DEPLOY_OVERHEAD_GAS) { + return Ok(Err(Refusal::OutOfGas)); + } if !inputs.call_value().is_zero() { - return Some(synthetic_call_result( - inputs, - InstructionResult::Revert, - Bytes::from_static(&IKeylessDeploy::NoEtherTransfer::SELECTOR), - )); + refuse!(KeylessDeployError::NoEtherTransfer); + } + let input = inputs.input.bytes(ctx); + let Ok(call) = IKeylessDeploy::keylessDeployCall::abi_decode(&input) else { + refuse!(KeylessDeployError::MalformedEncoding); + }; + let signed = match decode_keyless_tx(&call.keylessDeploymentTransaction) { + Ok(signed) => signed, + Err(error) => refuse!(error), + }; + let tx = signed.tx(); + if tx.nonce != 0 { + refuse!(KeylessDeployError::NonZeroTxNonce { tx_nonce: tx.nonce }); + } + let max = ctx.cfg().max_initcode_size(); + if tx.input.len() > max { + refuse!(KeylessDeployError::InitCodeTooLarge { + size: tx.input.len() as u64, + max: max as u64, + }); + } + let override_gas_limit = u64::try_from(call.gasLimitOverride).unwrap_or(u64::MAX); + if override_gas_limit < tx.gas_limit { + refuse!(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: tx.gas_limit, + provided_gas_limit: override_gas_limit, + }); + } + // The forward: `gasLimitOverride`, capped to what the call has left, which must still cover + // the signed gas limit. + macro_rules! forward { + () => {{ + let gas_limit = override_gas_limit.min(gas.remaining()); + if gas_limit < tx.gas_limit { + refuse!(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: tx.gas_limit, + provided_gas_limit: gas_limit, + }); + } + gas_limit + }}; + } + let signer = match recover_signer(&signed) { + Ok(signer) => signer, + Err(error) => refuse!(error), + }; + let deploy_address = calculate_keyless_deploy_address(signer); + + let checks_code = !ctx.cfg().is_eip3607_disabled(); + let journal = ctx.journal_mut(); + let signer_info = if checks_code { + journal.load_account_with_code(signer)? + } else { + journal.load_account(signer)? + } + .data + .info + .clone(); + // A signer that is the block beneficiary: the rules read the beneficiary's account through + // the journal, where the Host marks nothing, and the creation runs for it as a `CREATE` runs + // in a frame of it, which a read of the account started. The call is the transaction's own + // frame, at depth 0. + if signer == ctx.block().beneficiary { + ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas, 0); + } + if signer_info.nonce > 1 { + refuse!(KeylessDeployError::SignerNonceTooHigh { signer_nonce: signer_info.nonce }); + } + if checks_code && + signer_info.code.as_ref().is_some_and(|code| !code.is_empty() && !code.is_eip7702()) + { + refuse!(KeylessDeployError::SignerHasCode); + } + + // The signer's nonce bump is what creates an empty signer's account: a caller the `CREATE` + // opcode starts from exists already. It is charged where the legacy engine charged it, and + // the forward checked right after, before the deploy address and the balance are. + let mut signer_account_charge = 0; + if signer_info.is_empty() { + let charge = + StateGasCharge::one(GasId::new_account_state_gas(), StateGasSite::account(signer)); + signer_account_charge = state_gas(ctx, charge)?; + if !gas.record_state_cost(signer_account_charge) { + return Ok(Err(Refusal::OutOfGas)); + } + } + forward!(); + if ctx.journal_mut().load_account(deploy_address)?.data.info.code_hash != KECCAK_EMPTY { + refuse!(KeylessDeployError::ContractAlreadyExists); + } + if signer_info.balance < tx.value { + refuse!(KeylessDeployError::InsufficientBalance); + } + + // What the `CREATE` opcode charges its frame for the creation's start, in the opcode's order + // and after every rule: its regular gas, the created account, then the records. + let params = ctx.cfg().gas_params(); + let regular = params.create_cost().saturating_add(params.initcode_cost(tx.input.len())); + if !gas.record_regular_cost(regular) { + return Ok(Err(Refusal::OutOfGas)); + } + let charged_create_state_gas = + ctx.journal_ref().state.get(&deploy_address).is_none_or(|account| account.info.is_empty()); + if charged_create_state_gas { + let charge = + StateGasCharge::one(GasId::create_state_gas(), StateGasSite::account(deploy_address)); + if !gas.record_state_cost(state_gas(ctx, charge)?) { + return Ok(Err(Refusal::OutOfGas)); + } + } + let records = FrameStartRecords { on_lane: 1, caller: signer != ctx.tx().caller() }; + let record_charges = if ctx.prices_history() { + let charged = charge_write_records_history( + gas.tracker_mut(), + records.on_lane, + u64::from(records.caller), + ); + if charged.is_none() { + return Ok(Err(Refusal::OutOfGas)); + } + charged + } else { + None + }; + + // The forward is not the call's own work: it draws the part detention withholds first, as a + // `CREATE` opcode's forward does. + let gas_limit = forward!(); + let forwarded = gas.record_withheld_first_cost(gas_limit); + debug_assert!(forwarded, "the forward is capped to what the call has left"); + + Ok(Ok(Deployment { + signer, + signer_nonce: signer_info.nonce, + signer_account_charge, + deploy_address, + value: tx.value, + init_code: tx.input.clone(), + gas_limit, + charged_create_state_gas, + records, + record_charges, + })) +} + +/// Prices `charge` through the SALT pricing hook. A failed lookup is the error the hook recorded, +/// which fails the transaction. +fn state_gas( + ctx: &mut MegaContext, + charge: StateGasCharge, +) -> Result> { + if let Some(price) = ctx.state_gas_charge(charge) { + return Ok(price); } - None + Err(core::mem::replace(ctx.error(), Ok(())) + .err() + .unwrap_or_else(|| ContextError::Custom("state gas price lookup failed".into()))) } diff --git a/crates/mega-evm/src/system/keyless/error.rs b/crates/mega-evm/src/system/keyless/error.rs index de7925f21..aea10665e 100644 --- a/crates/mega-evm/src/system/keyless/error.rs +++ b/crates/mega-evm/src/system/keyless/error.rs @@ -8,8 +8,8 @@ use crate::MegaHaltReason; /// Error types for keyless deployment operations. /// -/// Most variants map directly to Solidity errors defined in `IKeylessDeploy`. -/// Internal-only variants are mapped at the ABI boundary by `encode_error_result`. +/// Every variant maps to the Solidity error of the same name in `IKeylessDeploy`; +/// [`encode_error_result`] and [`decode_error_result`] convert at the ABI boundary. #[derive(Debug, Clone, PartialEq, Eq)] pub enum KeylessDeployError { /// The transaction data is malformed (invalid RLP encoding) @@ -27,9 +27,8 @@ pub enum KeylessDeployError { NoEtherTransfer, /// Failed to recover signer from signature (invalid signature) InvalidSignature, - /// The signer does not have enough balance to cover the sandbox tx's pre-execution - /// debit: `gas_limit × gas_price + value` on pre-Rex5 specs, `value` only on Rex5+ - /// (where the sandbox tx is fee-free and only the `value` transfer needs funding). + /// The signer cannot fund the deployment's value. The deployment pays no gas out of the + /// signer's balance, so the value is all it must hold. InsufficientBalance, /// The deploy address already has code (contract already exists) ContractAlreadyExists, @@ -38,31 +37,21 @@ pub enum KeylessDeployError { /// The on-chain nonce of the recovered signer signer_nonce: u64, }, - /// The sandbox execution reverted + /// The deployment's creation reverted. ExecutionReverted { /// The gas used gas_used: u64, /// The output output: Bytes, }, - /// The sandbox execution halted (out of gas, stack overflow, etc.) + /// The deployment's creation halted (out of gas, an invalid opcode, code the creation + /// refuses). ExecutionHalted { /// The gas used gas_used: u64, /// The reason reason: MegaHaltReason, }, - /// The call's remaining budget in some resource dimension was below the deployment's - /// known upfront usage, so the deployment was not started. - ParentBudgetExceeded { - /// The resource dimension, as the raw `kind` code of the `IKeylessDeploy` error. The - /// Satin resource dimensions and their codes are not defined yet. - kind: u8, - /// The remaining budget in that dimension. - limit: u64, - /// The deployment's known upfront usage in that dimension. - used: u64, - }, /// Contract creation succeeded but returned empty bytecode EmptyCodeDeployed { /// The gas used @@ -79,41 +68,17 @@ pub enum KeylessDeployError { /// The gas limit override provided by the caller provided_gas_limit: u64, }, - /// The remaining compute gas is insufficient to pay for the keyless deploy overhead. - InsufficientComputeGas { - /// The configured compute gas limit - limit: u64, - /// The actual compute gas usage - used: u64, - }, - /// The keyless transaction's init code exceeds the configured maximum init code size. - /// - /// Rex5+ only: the sandbox runs as an OP deposit-like transaction which bypasses - /// op-revm's `validate_env` (where revm's EIP-3860 size check lives), so the sandbox - /// must re-enforce the limit itself against `cfg().max_initcode_size()`. + /// The keyless transaction's init code exceeds the configured maximum init code size + /// (EIP-3860), which no validation of the outer transaction holds it to. InitCodeTooLarge { /// The init code length in bytes. size: u64, /// The configured max init code size. max: u64, }, - /// The recovered signer has non-empty, non-EIP-7702 bytecode in parent state. - /// - /// Rex5+ only: the deposit-style sandbox bypasses op-revm's EIP-3607 check (which - /// normally lives in `validate_account_nonce_and_code`), so the sandbox enforces it - /// itself before constructing the sandbox transaction. + /// The recovered signer has non-empty, non-EIP-7702 bytecode: EIP-3607 for a creator that + /// is not the transaction's sender, which no validation of the outer transaction checks. SignerHasCode, - /// Internal sandbox failure (DB I/O, header validation, etc.). - /// Selector-only so the top-level error ABI stays stable and does not depend on - /// upstream revm/op-revm `Display` text. The interceptor only runs at call depth 0, - /// so this returndata has no inner caller to read it and never reaches a consensus - /// root; the selector-only shape is for off-chain decoder/tooling stability. - InternalError, - /// Sandbox rejected the inner transaction as a tx-validation error - /// (`IsTxError::is_tx_error() == true`). A dedicated selector lets relayer-side - /// decoders distinguish this from a genuine internal failure. Selector-only for the - /// same ABI-stability reason as `InternalError`. - InvalidTransaction, /// The keylessDeploy call was not intercepted (only returned by Solidity contract for inner /// calls) NotIntercepted, @@ -155,9 +120,6 @@ pub fn encode_error_result(error: KeylessDeployError) -> Bytes { KeylessDeployError::ExecutionHalted { gas_used, .. } => { IKeylessDeploy::ExecutionHalted { gasUsed: gas_used }.abi_encode().into() } - KeylessDeployError::ParentBudgetExceeded { kind, limit, used } => { - IKeylessDeploy::ParentBudgetExceeded { kind, limit, used }.abi_encode().into() - } KeylessDeployError::EmptyCodeDeployed { gas_used } => { IKeylessDeploy::EmptyCodeDeployed { gasUsed: gas_used }.abi_encode().into() } @@ -175,17 +137,10 @@ pub fn encode_error_result(error: KeylessDeployError) -> Bytes { .abi_encode() .into() } - KeylessDeployError::InsufficientComputeGas { limit, used } => { - IKeylessDeploy::InsufficientComputeGas { limit, used }.abi_encode().into() - } KeylessDeployError::InitCodeTooLarge { size, max } => { IKeylessDeploy::InitCodeTooLarge { size, max }.abi_encode().into() } KeylessDeployError::SignerHasCode => IKeylessDeploy::SignerHasCode {}.abi_encode().into(), - KeylessDeployError::InternalError => IKeylessDeploy::InternalError {}.abi_encode().into(), - KeylessDeployError::InvalidTransaction => { - IKeylessDeploy::InvalidTransaction {}.abi_encode().into() - } KeylessDeployError::NotIntercepted => IKeylessDeploy::NotIntercepted {}.abi_encode().into(), } } @@ -239,13 +194,6 @@ pub fn decode_error_result(output: &[u8]) -> Option { )), }); } - if let Ok(e) = IKeylessDeploy::ParentBudgetExceeded::abi_decode(output) { - return Some(KeylessDeployError::ParentBudgetExceeded { - kind: e.kind, - limit: e.limit, - used: e.used, - }); - } if let Ok(e) = IKeylessDeploy::EmptyCodeDeployed::abi_decode(output) { return Some(KeylessDeployError::EmptyCodeDeployed { gas_used: e.gasUsed }); } @@ -267,12 +215,6 @@ pub fn decode_error_result(output: &[u8]) -> Option { if IKeylessDeploy::SignerHasCode::abi_decode(output).is_ok() { return Some(KeylessDeployError::SignerHasCode); } - if IKeylessDeploy::InvalidTransaction::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InvalidTransaction); - } - if IKeylessDeploy::InternalError::abi_decode(output).is_ok() { - return Some(KeylessDeployError::InternalError); - } if IKeylessDeploy::NotIntercepted::abi_decode(output).is_ok() { return Some(KeylessDeployError::NotIntercepted); } @@ -283,28 +225,6 @@ pub fn decode_error_result(output: &[u8]) -> Option { mod tests { use super::*; - /// `InternalError` and `InvalidTransaction` carry no payload on the wire, so a - /// roundtrip MUST produce the same variant. Pinned because these selectors are the - /// off-chain error ABI (RPC, traces, relayer decoders); a divergence between - /// `encode_error_result` and `decode_error_result` would silently break those decoders. - #[test] - fn test_internal_error_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InternalError); - // Selector-only: the encoded form is exactly the 4-byte Solidity selector. - assert_eq!(encoded.len(), 4, "InternalError must be selector-only"); - assert!(matches!(decode_error_result(&encoded), Some(KeylessDeployError::InternalError))); - } - - #[test] - fn test_invalid_transaction_roundtrip_is_selector_only() { - let encoded = encode_error_result(KeylessDeployError::InvalidTransaction); - assert_eq!(encoded.len(), 4, "InvalidTransaction must be selector-only"); - assert!(matches!( - decode_error_result(&encoded), - Some(KeylessDeployError::InvalidTransaction) - )); - } - /// `InitCodeTooLarge { size, max }` is an externally visible ABI selector. Pinning the /// round-trip catches any drift between the Solidity error definition and the Rust /// encode/decode (e.g. forgotten arm in `encode_error_result` or `decode_error_result`, @@ -317,16 +237,6 @@ mod tests { assert_eq!(decoded, original); } - /// `ParentBudgetExceeded` keeps every field of the ABI error through a round-trip. - #[test] - fn test_parent_budget_exceeded_roundtrip_preserves_fields() { - let original = - KeylessDeployError::ParentBudgetExceeded { kind: 3, limit: 1_000, used: 1_001 }; - let encoded = encode_error_result(original.clone()); - assert_eq!(encoded[..4], IKeylessDeploy::ParentBudgetExceeded::SELECTOR); - assert_eq!(decode_error_result(&encoded), Some(original)); - } - /// `SignerHasCode` is selector-only; pinning the round-trip catches arm drift. #[test] fn test_signer_has_code_roundtrip_is_selector_only() { diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index ce8237db0..e121e7df4 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -1,23 +1,115 @@ -//! The `KeylessDeploy` system contract, and keyless deployment (Nick's Method): the transaction -//! format, its validation rules and the error ABI. +//! The `KeylessDeploy` system contract, and keyless deployment (Nick's Method): a pre-EIP-155 +//! signed creation, deployed at the address its signer's first creation gets on every chain, with +//! the gas limit the caller chooses. //! -//! `keylessDeploy(bytes,uint256)` is intercepted; every other selector falls through to the -//! deployed bytecode, which carries no fallback and reverts with empty data. What the interceptor -//! does today is the dispatch and the fixed compute charge; turning the deployment into a native -//! creation belongs to native keyless deployment, so a dispatched call still runs the method body -//! and its `NotIntercepted()`. +//! # A native creation //! -//! The rest of the module is data-only: decoding the pre-EIP-155 transaction, recovering its -//! signer, deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. +//! A `keylessDeploy(bytes,uint256)` call a transaction makes is dispatched before any interceptor +//! sees it ([`is_dispatched`]), and its frame is built as any call's is, but runs no code: its +//! actions are made by hand ([`run`]). On its first run it pays the fixed overhead and what the +//! `CREATE` opcode charges its frame, then starts the creation as its child — as the signer, at +//! the signer's Nick's-Method address, with `gasLimitOverride` capped to what the call has left. +//! From there the creation is an ordinary `CREATE` frame: priced, limited and journaled as one, +//! and returned into the call as one returns into the frame that started it ([`settle`]). On its +//! resume the call answers in the `IKeylessDeploy` ABI. An inspector sees both frames: the call, +//! and the creation as its child. There is no second EVM and no state to merge. +//! +//! What the native frame means for a deployment: +//! +//! - The call is a frame on revm's stack, built on the contract as any call to it is: at depth 0, +//! with its own journal checkpoint and gas. No code runs in it, and the contract's bytecode never +//! runs for a call the dispatch takes. The contract's account and code are loaded to start the +//! transaction's first frame, as for any transaction to the contract, so a witness holds them +//! either way; the frame touches the account, as a call touches its target, and a call that +//! reverts takes the touch back. An inspector sees one call frame, started and ended as any +//! call's, with no interpreter initialized and no step in it. +//! - A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm +//! builds its frame: no value moves, and nothing its start would write is counted. +//! - The dispatch is by address and selector, whatever the address holds: where the state holds no +//! contract code, the frame is built on the contract's own. A chain Satin runs on holds it, as +//! Rex2 deployed it, and Satin's activation block checks it. +//! - `ORIGIN` and `GASPRICE` in the init code are the transaction's own. +//! - The creation runs at depth 1, as the call's child: one level below the same init code sent as +//! a creation transaction, which runs at depth 0. Its frames reach the call-stack limit one frame +//! earlier. The call is the frame above the constructor, and its charges — the overhead and the +//! `CREATE` opcode's regular gas — are compute the transaction spent before the constructor ran: +//! a detained constructor has spent them already, and one detained from the transaction's start +//! hears `remainingComputeGas()` answer the cap less them. +//! - The signer's nonce is bumped by the creation, as any creator's is, and a deployment is refused +//! once the signer's nonce is above 1 (`SignerNonceTooHigh`). A deployment from nonce 0 keeps the +//! bump, which is the replay barrier. From nonce 1 the creation's bump is taken back, whether the +//! deployment succeeds or fails, only when it is the last nonce change the deployment made: the +//! signer stays at 1, as in the legacy engine. The call is permissionless and the signed +//! transaction public, so no number of failing calls, whoever makes them, gets such a signer's +//! deployment refused, and a deployment that succeeded answers a resubmission with +//! `ContractAlreadyExists()`. The bump goes with its write record and that record's history, +//! unless the creation succeeded and moved value out of the signer, whose account then keeps a +//! write of its own. A signer whose own code spends a nonce in the constructor that survives it +//! keeps every bump, the creation's included: it ends above 1, and every later deployment of it +//! is refused `SignerNonceTooHigh`. On a default configuration only a delegated signer's code can +//! do that, with a `CREATE` or `CREATE2`, successful or not: a signer with other code is refused +//! `SignerHasCode()` unless EIP-3607 is disabled. The nonce is never moved back under a later +//! bump, because a later bump may stand for an account. +//! - A constructor that returns empty code for the deploy address is refused its empty deposit: the +//! creation reverts, taking its logs and writes with it, and the call answers +//! `EmptyCodeDeployed()`, so the address stays deployable. A constructor that destroys its own +//! account (EIP-6780) is left as it is and gets the same answer, since the account keeps no code. +//! A creation the constructor makes itself may return empty code. Whoever submits the signed +//! bytes chooses the forward through `gasLimitOverride`, so an init code that branches on its gas +//! cannot be made to occupy the address without code. +//! - A signer with no account is charged its account as state gas, once, by the call: the nonce +//! bump creates it, and no other charge does. +//! - The call pays what the `CREATE` opcode charges its frame: its regular gas, which stays spent, +//! and the deployed contract's account, given back when the deployment fails, at the price it was +//! charged. +//! - `gasUsed` is what the creation spent, with no transaction intrinsic: the sandbox of the legacy +//! engine ran the deployment as a transaction of its own, this engine does not. It is counted +//! before refunds: a refund the creation earns goes to the transaction, as any frame's does. +//! - A limit the deployment crosses stops the frame that crosses it, as it stops any frame. The +//! creation crossing a limit — its budget or the transaction's, its start's records or its init +//! code's work — reverts with the stop, and the call returns `ExecutionReverted` with the stop's +//! revert data, keeping what the creation's start wrote. The call crossing one itself — its own +//! charges past gas detention's limit, or a limit the nonce record a failed creation leaves it +//! crosses — reverts with the stop, taking back the signer's nonce with everything else. +//! +//! A creation an inspector revives — a tool's `create_end` that turns a failed creation into a +//! success at an address of its own, as Foundry's `expectRevert` does — settles as a frame that +//! kept nothing, and the call answers `AddressMismatch()` when that address is not the deploy +//! address. +//! +//! # The error ABI +//! +//! The rules that produce the contract's errors are the legacy engine's, and so is the order they +//! are checked in, so a call several rules refuse reports the legacy engine's error. The interface +//! no longer declares the four errors only the legacy engine produced: `ParentBudgetExceeded` and +//! `InvalidTransaction` were the sandbox's, which had a budget of its own to preflight and a +//! transaction of its own to validate; `InsufficientComputeGas` was the compute-gas limit's, which +//! is the execution cap on the regular pool here, so a call that cannot pay the overhead runs out +//! of gas; and `InternalError` was a failed read, which fails the transaction with its cause here, +//! as it does at every other site. Dropping them changes no deployed byte: the contract's bytecode +//! never names them. `AddressMismatch` and `NoContractCreated` stay as the answers to a creation +//! revm reports at an address other than the pinned one, which no deployment reaches. +//! +//! # The contract +//! +//! Every selector but `keylessDeploy` runs the deployed bytecode: a method the contract declares, +//! such as `version()`, answers, and a selector it does not declare finds no fallback and reverts +//! with empty data. A `keylessDeploy` call a contract makes runs the bytecode too, and its method +//! body reverts with `NotIntercepted()`. +//! +//! The rest of the module is data: decoding the pre-EIP-155 transaction, recovering its signer, +//! deriving the deploy address, and mapping errors to and from the `IKeylessDeploy` ABI. mod dispatch; mod error; +mod settle; mod tx; pub use error::*; pub use tx::*; -pub(crate) use dispatch::intercept; +pub(crate) use dispatch::{is_dispatched, ready, run, runs, KeylessFrame}; +pub(crate) use settle::{refuses_empty_deposit, returning, settle}; use alloy_primitives::{address, Address}; @@ -32,7 +124,7 @@ pub use mega_system_contracts::keyless_deploy::LATEST_CODE_HASH as KEYLESS_DEPLO pub use mega_system_contracts::keyless_deploy::IKeylessDeploy; -/// The regular gas a `keylessDeploy` call pays before the deployment runs: the fixed cost of +/// The regular gas a `keylessDeploy` call pays before its deployment starts: the fixed cost of /// decoding the transaction, recovering its signer and preparing the deployment. Provisional, /// as the rest of the engine's numbers are. pub const KEYLESS_DEPLOY_OVERHEAD_GAS: u64 = 100_000; diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs new file mode 100644 index 000000000..6ee7de062 --- /dev/null +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -0,0 +1,383 @@ +//! The settlement of a keyless deployment: the creation's result returned into the +//! `keylessDeploy` call that started it, and the call's answer in the `IKeylessDeploy` ABI. + +use alloy_evm::Database; +use alloy_primitives::{Address, Bytes}; +use alloy_sol_types::SolCall; +use revm::{ + context::{ + result::{HaltReason, OutOfGasError}, + ContextError, ContextTr, FrameStack, JournalTr, + }, + context_interface::{ + cfg::gas::GasTracker, context::CodeDeposit, journaled_state::account::JournaledAccountTr, + }, + handler::{handle_reservoir_remaining_gas, EthFrame, FrameResult}, + interpreter::{ + interpreter::EthInterpreter, Gas, InstructionResult, InterpreterAction, SuccessOrHalt, + }, + primitives::KECCAK_EMPTY, +}; + +use crate::{ + system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, + ExternalEnvTypes, MegaContext, MegaHaltReason, +}; + +use super::dispatch::{KeylessFrame, Started}; + +/// What a `keylessDeploy` call answers from, once its creation returned into it. +#[derive(Debug)] +pub(crate) struct Returned { + started: Started, + creation: Creation, +} + +/// What the creation a `keylessDeploy` call started returned. +#[derive(Debug)] +pub(crate) struct Creation { + result: InstructionResult, + output: Bytes, + /// What the creation spent ([`creation_gas_used`]). + gas_used: u64, + /// The address revm reports the creation at. + created: Option
, +} + +/// The creation a `keylessDeploy` call started, when `result`, about to be returned to the frame +/// that waits for it, is that creation's, returning into the call; `None` for every other result. +/// +/// It is read here, before revm merges it into the call, which keeps nothing of it but its gas and +/// whether it succeeded. The frame stack says whether the result lands in the call +/// ([`returns_into_the_call`]). +pub(crate) fn returning( + ctx: &MegaContext, + stack: &mut FrameStack>, + result: &FrameResult, +) -> Option { + if !matches!(ctx.keyless_frame, Some(KeylessFrame::Deploying(_))) { + return None; + } + if !returns_into_the_call(stack) { + return None; + } + let result_code = result.instruction_result(); + // The creation's gas as revm's settlement leaves it before the merge: a creation that failed + // rolls its state and history gas back, and one that halted spends its regular gas. + let mut gas = *result.gas(); + handle_reservoir_remaining_gas(result_code, &mut GasTracker::default(), gas.tracker_mut()); + Some(Creation { + result: result_code, + output: result.interpreter_result().output.clone(), + gas_used: creation_gas_used(&gas), + created: match result { + FrameResult::Create(outcome) => outcome.address, + FrameResult::Call(_) => None, + }, + }) +} + +/// Whether the result about to be returned lands in the frame at the bottom of the stack, which in +/// a keyless deployment is the `keylessDeploy` call. +/// +/// It does in two cases: the top of the stack is the creation, at index 1 and finished, which revm +/// pops before it hands the result to the frame below; or the top is the call itself, at index 0 +/// and not finished, which a creation answered without a frame of its own returns into directly. +/// A frame the creation started returning (index 2, finished) or answered while the creation runs +/// (index 1, not finished) lands in the creation instead. +fn returns_into_the_call(stack: &mut FrameStack>) -> bool { + let Some(top) = stack.index() else { return false }; + top == usize::from(stack.get().is_finished()) +} + +/// Whether the code `deposit` makes is the empty code a keyless deployment's constructor returned +/// for the deploy address, which the deployment refuses: the creation reverts and the call answers +/// `EmptyCodeDeployed`, leaving the address deployable. +/// +/// Only the deposit at the deploy address while the creation runs is refused. A creation the +/// constructor makes itself, which may return empty code, deposits at another address, and a +/// constructor that destroyed its own account (`destroyed`) is left as it is: the account does not +/// keep what it returned, and the answer reads that off the journal ([`holds_code`]). +pub(crate) fn refuses_empty_deposit( + frame: &mut Option, + deposit: &CodeDeposit<'_>, + destroyed: bool, +) -> bool { + match frame { + Some(KeylessFrame::Deploying(started)) + if deposit.code.is_empty() && + deposit.address == started.deploy_address && + !destroyed => + { + started.empty_deposit_refused = true; + true + } + _ => false, + } +} + +/// Settles `creation`, which revm has just merged into the `keylessDeploy` call whose gas is +/// `gas`, and keeps what the call answers from on its resume ([`answer`]). +/// +/// The merge is revm's own, as for a `CREATE`'s frame: the unspent forward, the reservoir, the +/// creation's state and history gas when it succeeded, and the created account's charge when it +/// did not — priced through the same hook it was charged through — with the history of the records +/// the creation did not keep given back after it. +/// +/// What is left is what a `CREATE` has no counterpart for. The signer's account comes back when +/// the creation's start never created it. And a deployment from nonce 0 keeps the creation's nonce +/// bump, while from nonce 1 the bump is taken back, whether the deployment succeeded or failed, +/// only when it is the last nonce change the deployment made ([`take_back_bump`]), leaving the +/// nonce at 1, as the legacy engine did; its write record and that record's history go with it, +/// unless the creation succeeded and moved value out of the signer. The call is permissionless +/// and the signed transaction public, so a nonce every failure spent would let anybody make a +/// signer's address undeployable with two failing calls; and a success that spent it would answer +/// a resubmission with `SignerNonceTooHigh` rather than `ContractAlreadyExists`. When the signer's +/// own code spent a nonce in the constructor that survived it — on a default configuration, a +/// delegated signer's `CREATE` or `CREATE2`, successful or not — nothing is taken back: a later +/// bump may stand for an account, so the nonce is never moved back under one. That signer ends +/// above 1, and a resubmission is refused `SignerNonceTooHigh`. +/// +/// It runs before the call resumes, because the record it takes back may be what put the call +/// over a limit: the call is held to its limits again without it, and the stop it returns on +/// its resume, if any, is the one that stands then. +pub(crate) fn settle( + ctx: &mut MegaContext, + gas: &mut Gas, + creation: Creation, +) -> Result<(), ContextError> { + let Some(KeylessFrame::Deploying(started)) = ctx.keyless_frame.take() else { + unreachable!("a creation returns into a keylessDeploy call that started it") + }; + // The creation's start is what creates an empty signer's account. revm bumps the nonce of + // every creation it is asked to build, and a creation the limits stop at its start is bumped + // all the same; one an inspector answered in its place never started, and adds no account. + // A signer that had an account was charged nothing, and gets nothing back. + let nonce = account_nonce(ctx, started.signer); + if nonce == started.signer_nonce { + gas.refill_reservoir(started.signer_account_charge); + } + // A deployment from nonce 1 keeps no bump of its own: a failure leaves the address + // deployable, a success leaves it occupied. The creation's bump is the one above the nonce + // the call started from, and it is taken back only when it is the last one: a later bump the + // signer's own code made may stand for an account, so the nonce is never moved back under it. + if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { + take_back_bump(ctx, gas, &started, creation.result)?; + } + ctx.keyless_frame = Some(KeylessFrame::Returned(Returned { started, creation })); + Ok(()) +} + +/// The action of a `keylessDeploy` call resuming on `gas` once its creation `returned` into it, a +/// stop aside: `keylessDeploy`'s return — the deployed address when the creation left code at it, +/// or the zero address and the error the creation failed with, `ExecutionReverted`, +/// `ExecutionHalted`, or `EmptyCodeDeployed` for a creation that left no code, having deployed none +/// or destroyed itself. The call succeeds, and keeps what the creation's start wrote: a signer at +/// nonce 0 whose deployment failed has spent its nonce all the same. +/// +/// `gasUsed` is what the creation spent: its regular gas and the state and history gas it kept, +/// from whichever pool paid it. It is the same whether the transaction has a state-gas reservoir +/// or not, and it counts nothing the call paid for the creation's start. +/// +/// A creation revm reports as a success at another address than the pinned one, or at none, is a +/// broken engine rather than a failed deployment: the call reverts with `AddressMismatch()` or +/// `NoContractCreated()`, which no deployment reaches. +pub(crate) fn answer( + ctx: &MegaContext, + returned: &Returned, + gas: Gas, +) -> InterpreterAction { + let (result, output) = answer_of(ctx, returned); + InterpreterAction::new_return(result, output, gas) +} + +/// The result and output of [`answer`]. +fn answer_of( + ctx: &MegaContext, + returned: &Returned, +) -> (InstructionResult, Bytes) { + let Returned { started, creation } = returned; + let gas_used = creation.gas_used; + if started.empty_deposit_refused { + return failed(KeylessDeployError::EmptyCodeDeployed { gas_used }, gas_used); + } + if creation.result.is_revert() { + let output = creation.output.clone(); + return failed(KeylessDeployError::ExecutionReverted { gas_used, output }, gas_used); + } + if !creation.result.is_ok() { + let reason = halt_reason(creation.result); + return failed(KeylessDeployError::ExecutionHalted { gas_used, reason }, gas_used); + } + if creation.created != Some(started.deploy_address) { + let error = if creation.created.is_some() { + KeylessDeployError::AddressMismatch + } else { + KeylessDeployError::NoContractCreated + }; + return (InstructionResult::Revert, encode_error_result(error)); + } + if !holds_code(ctx, started.deploy_address) { + return failed(KeylessDeployError::EmptyCodeDeployed { gas_used }, gas_used); + } + returned_value(gas_used, started.deploy_address, Bytes::new()) +} + +/// Whether the deployment left code at `address`. The code the journal holds, not the code the +/// constructor returned: a constructor that destroyed its own account (EIP-6780) returned code +/// the account does not keep. +fn holds_code( + ctx: &MegaContext, + address: Address, +) -> bool { + ctx.journal_ref().state.get(&address).is_some_and(|account| { + account.info.code_hash != KECCAK_EMPTY && !account.is_selfdestructed() + }) +} + +/// Takes back the creation's nonce bump of a signer whose nonce was already 1, with its write +/// record and that record's history, so what stands is what would stand had the creation's start +/// not bumped the nonce: the signer stays at 1, however many deployments it makes. +/// +/// The record goes unless the signer's account keeps another write it stands for: the value a +/// creation that succeeded moved out of it. A creation that failed took its value transfer back +/// with the rest of its writes. +fn take_back_bump( + ctx: &mut MegaContext, + gas: &mut Gas, + started: &Started, + result: InstructionResult, +) -> Result<(), ContextError> { + ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); + let moved_value = started.moves_value && result.is_ok(); + if !moved_value && ctx.additional_limit.take_back_creator_record() { + gas.refill_history(started.signer_record_charge); + } + Ok(()) +} + +/// The nonce of an account the journal holds; zero for one it does not. +fn account_nonce( + ctx: &MegaContext, + address: Address, +) -> u64 { + ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// `keylessDeploy`'s return for a deployment that failed with `error`. +fn failed(error: KeylessDeployError, gas_used: u64) -> (InstructionResult, Bytes) { + returned_value(gas_used, Address::ZERO, encode_error_result(error)) +} + +/// `keylessDeploy`'s return: a success, whatever the deployment did. +fn returned_value( + gas_used: u64, + deployed_address: Address, + error_data: Bytes, +) -> (InstructionResult, Bytes) { + let output = IKeylessDeploy::keylessDeployCall::abi_encode_returns( + &IKeylessDeploy::keylessDeployReturn { + gasUsed: gas_used, + deployedAddress: deployed_address, + errorData: error_data, + }, + ); + (InstructionResult::Return, output.into()) +} + +/// Why a creation that ended with `result` halted. The ABI's `ExecutionHalted` carries no reason, +/// so this is what the error value, and whoever handles it off-chain, is told. +fn halt_reason(result: InstructionResult) -> MegaHaltReason { + match SuccessOrHalt::::from(result) { + SuccessOrHalt::Halt(reason) => reason, + _ => MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic)), + } +} + +/// What a creation whose gas settled into `gas` spent, from either pool: its regular gas, and the +/// state and history gas it kept that the reservoir paid. +/// +/// Regular gas spent includes the state and history charges that spilled onto it once the +/// reservoir was empty, and nothing the reservoir paid. Adding back what the reservoir paid makes +/// the figure the same whether the transaction was funded above the execution cap or not. A +/// creation that failed kept no state or history gas: its settlement rolled both back, and a +/// halt spent its regular gas. +fn creation_gas_used(gas: &Gas) -> u64 { + let kept = gas.state_gas_spent().saturating_add(gas.history_gas_spent()); + let from_reservoir = kept.saturating_sub_unsigned(gas.state_gas_spilled()); + gas.total_gas_spent().saturating_add(u64::try_from(from_reservoir).unwrap_or_default()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A halt is reported with its own reason. + #[test] + fn test_a_halt_keeps_its_reason() { + assert_eq!( + halt_reason(InstructionResult::InvalidFEOpcode), + MegaHaltReason::Base(HaltReason::InvalidFEOpcode), + ); + assert_eq!( + halt_reason(InstructionResult::CreateContractStartingWithEF), + MegaHaltReason::Base(HaltReason::CreateContractStartingWithEF), + ); + assert_eq!( + halt_reason(InstructionResult::Return), + MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Basic)), + "what is not a halt is reported as running out of gas", + ); + } + + /// The creation's spend is the same figure whichever pool paid its state and history gas. + #[test] + fn test_the_creation_gas_used_does_not_depend_on_the_pool() { + // No reservoir: every state and history charge spills onto regular gas. + let mut narrow = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); + assert!(narrow.record_regular_cost(30_000)); + assert!(narrow.record_state_cost(200_000)); + assert!(narrow.record_history_cost(4_000)); + + // A reservoir that pays for all of it. + let mut wide = Gas::new_with_regular_gas_and_reservoir(1_000_000, 10_000_000); + assert!(wide.record_regular_cost(30_000)); + assert!(wide.record_state_cost(200_000)); + assert!(wide.record_history_cost(4_000)); + + // Half and half: the reservoir runs dry in the middle of the state charge. + let mut split = Gas::new_with_regular_gas_and_reservoir(1_000_000, 100_000); + assert!(split.record_regular_cost(30_000)); + assert!(split.record_state_cost(200_000)); + assert!(split.record_history_cost(4_000)); + + for gas in [narrow, wide, split] { + assert_eq!(creation_gas_used(&gas), 234_000, "{gas:?}"); + } + } + + /// A creation that failed kept nothing but the regular gas it spent: a revert gives back the + /// spill with the rollback, a halt spends the whole forward. + #[test] + fn test_a_failed_creation_spent_its_regular_gas_alone() { + for reservoir in [0, 10_000_000] { + let mut gas = Gas::new_with_regular_gas_and_reservoir(1_000_000, reservoir); + assert!(gas.record_regular_cost(30_000)); + assert!(gas.record_state_cost(200_000)); + gas.rollback_state_gas(); + assert_eq!(creation_gas_used(&gas), 30_000, "a revert, reservoir {reservoir}"); + gas.spend_all(); + assert_eq!(creation_gas_used(&gas), 1_000_000, "a halt, reservoir {reservoir}"); + } + } + + /// A creation that refilled more than it charged — a slot written back that its caller had + /// filled — does not report less than the regular gas it spent. + #[test] + fn test_a_net_refill_does_not_lower_the_regular_spend() { + let mut gas = Gas::new_with_regular_gas_and_reservoir(1_000_000, 0); + assert!(gas.record_regular_cost(30_000)); + gas.refill_reservoir(50_000); + assert_eq!(creation_gas_used(&gas), 30_000); + } +} diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 608185a75..10276934a 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -1,9 +1,9 @@ //! The `MegaLimitControl` system contract. //! -//! It answers what the running call has left of the resources `MegaETH` meters; today that is -//! `remainingComputeGas()`. Its methods are intercepted: the deployed bytecode only carries the -//! ABI and reverts with `NotIntercepted()`. Its Solidity source is -//! `crates/system-contracts/contracts/MegaLimitControl.sol`. +//! It answers what the calling frame has left of the resources `MegaETH` meters; today that is +//! `remainingComputeGas()`, the compute it could still spend. Its methods are intercepted: the +//! deployed bytecode only carries the ABI and reverts with `NotIntercepted()`. Its Solidity source +//! is `crates/system-contracts/contracts/MegaLimitControl.sol`. use alloy_evm::Database; use alloy_primitives::{address, Address, Bytes}; @@ -33,18 +33,52 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// Answers a call to `MegaLimitControl`, or `None` when the selector is not `remainingComputeGas` /// and the deployed bytecode runs. /// -/// # What `remainingComputeGas` answers today +/// `depth` is the depth of the frame the call would start, and `caller_remaining` the regular gas +/// the calling frame has left once the call deducted the gas it forwards, the part gas detention +/// withholds included: [`Gas::remaining`](revm::interpreter::Gas::remaining). A transaction that +/// calls the contract directly has no calling frame, and passes zero. /// -/// The compute ledger belongs to compute gas, which is what will make this the compute gas the -/// transaction has left. Until then the interceptor answers what the common execution layer -/// knows: the regular gas the intercepted call was forwarded, which is the regular gas its frame -/// could still spend. Regular gas is capped at the execution cap, so the answer never counts the -/// state-gas reservoir. +/// # What `remainingComputeGas()` answers +/// +/// The compute the caller could still spend: the regular gas a regular charge of the calling frame +/// could draw once the call returns. That is the lesser of two figures, both read when the call +/// reaches the interceptor — after the `CALL` or `STATICCALL` charged its own costs, and with the +/// gas it forwarded counted back: +/// +/// - the caller's own regular gas, `caller_remaining` plus what the call forwarded. The answer +/// gives the forward back untouched, so this is what the caller holds when the call returns; +/// - the compute gas detention leaves the transaction, once a read of volatile data set a limit: +/// the limit less the transaction's compute at the call, the forward not counted +/// ([`Detention::allowance`](crate::Detention)). A transaction that read nothing, or that +/// detention does not hold, has no such limit. +/// +/// Detention holds a frame's spendable gas at the lesser of the two at all times, so the answer is +/// the caller's spendable regular gas before the forward, which detention caps. For a transaction +/// that calls the contract directly, the caller's own gas is the regular gas its frame was given; +/// a transaction whose sender is the block beneficiary is detained from its start, so it hears +/// what a block-environment read's cap leaves it when its frame holds more. +/// +/// The figure is taken before the forward: taken after it, a caller that forwards what `GAS` +/// reports would hear back one sixty-fourth of its gas. That is the one property carried over +/// from the legacy engine, whose compute never counted the gas a call forwarded. The figure +/// itself departs from the legacy engine's, which came from a separate compute ledger, with +/// per-frame budgets of 98/100 of the caller's remaining compute under the transaction's compute +/// limit, so it could exceed the caller's gas. Here compute is regular gas, and the answer is at +/// most the caller's own. +/// +/// It is regular gas only, capped at the execution cap: the state-gas reservoir is not compute, +/// and a transaction above the cap hears the cap's share at most. It is not a promise of compute +/// either: state or history gas the caller later pays out of its regular gas comes out of the +/// same figure. A frame a value call started holds its stipend in its own regular gas, and +/// detention counts the stipend outside compute, so the frame hears it counted whether or not it +/// is detained. /// /// The method reads and takes no value. pub(crate) fn intercept( ctx: &MegaContext, inputs: &CallInputs, + depth: usize, + caller_remaining: u64, ) -> Option { let selector = peek_selector(&inputs.input, ctx)?; // Selector-only admission: the four bytes decide, whatever follows them. @@ -54,6 +88,11 @@ pub(crate) fn intercept( if let Some(rejected) = reject_non_zero_transfer(inputs) { return Some(rejected); } - let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&inputs.gas_limit); + let own = caller_remaining.saturating_add(inputs.gas_limit); + let remaining = ctx + .detention + .allowance(depth, inputs.gas_limit) + .map_or(own, |allowance| own.min(allowance)); + let output = IMegaLimitControl::remainingComputeGasCall::abi_encode_returns(&remaining); Some(synthetic_call_result(inputs, InstructionResult::Return, Bytes::from(output))) } diff --git a/crates/mega-evm/src/system/mod.rs b/crates/mega-evm/src/system/mod.rs index d72eec85f..a062c4c1c 100644 --- a/crates/mega-evm/src/system/mod.rs +++ b/crates/mega-evm/src/system/mod.rs @@ -4,7 +4,9 @@ //! the [`High-Precision Timestamp`](timestamp) wrapper, [`KeylessDeploy`](keyless), //! [`MegaAccessControl`](control), [`MegaLimitControl`](limit_control) and the //! [`SequencerRegistry`](sequencer_registry). Each module carries its address, the code and code -//! hash the `mega-system-contracts` crate ships, and its ABI. +//! hash the `mega-system-contracts` crate ships, and its ABI. The EIP-7997 `CREATE2` factory +//! lives at its canonical address beside them; [`predeploys`] is the single list of all seven, +//! with the check Satin's activation block makes of them. //! //! Four of them have an interceptor: a `CALL` or `STATICCALL` to one of their intercepted //! selectors is answered by the engine instead of by the contract's code (see the `intercept` @@ -13,9 +15,6 @@ //! //! [`tx`](tx) holds the system-address transaction: the deposit-like transaction the sequencer //! maintains the protocol's own state with. -//! -//! Deploying the contracts at the fork that activates them belongs to system contract -//! deployment; it is not here. pub mod keyless; @@ -23,6 +22,7 @@ mod control; mod intercept; mod limit_control; mod oracle; +mod predeploys; mod sequencer_registry; mod timestamp; mod tx; @@ -31,12 +31,13 @@ pub use control::*; pub use intercept::NON_ZERO_TRANSFER_REVERT_DATA; pub use limit_control::*; pub use oracle::*; +pub use predeploys::*; pub use sequencer_registry::*; pub use timestamp::*; pub use tx::*; pub(crate) use intercept::intercept; -pub(crate) use tx::validate_and_promote; +pub(crate) use tx::{classify_system_transaction, validate_and_promote}; #[cfg(test)] mod tests { @@ -59,8 +60,8 @@ mod tests { ] } - /// The code hash of every contract is the hash of the code it ships with: Satin deploys the - /// contracts as they are, so a Solidity change that moved a hash shows up here. + /// The code hash of every contract is the hash of the code it ships with: Satin's activation + /// block checks the hash a chain holds, so a Solidity change that moved a hash shows up here. #[test] fn test_every_system_contract_code_hashes_to_its_pinned_hash() { for (address, code, hash) in system_contracts() { diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index c7fd6f4e6..c4ab0bc23 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -4,13 +4,25 @@ //! through which a contract reaches the node's oracle service: `sendHint` carries a message to //! the service backend. Its Solidity source is //! `crates/system-contracts/contracts/Oracle.sol`. +//! +//! Its storage is read through the service too, by the Host: an `SLOAD` in the Oracle's own frame +//! loads the slot through the journal and answers the service's value when it has one, the loaded +//! value otherwise. A node that replays a block without the service must price and witness it as +//! the node that built it did, so the read is always priced cold and the slot is loaded whichever +//! source answered. use alloy_evm::Database; use alloy_primitives::{address, Address}; use alloy_sol_types::SolCall; -use revm::{handler::FrameResult, interpreter::CallInputs}; +use revm::{ + handler::FrameResult, + interpreter::{CallInputs, InstructionResult}, +}; -use crate::{system::intercept::peek_selector, ExternalEnvTypes, MegaContext, OracleEnv}; +use crate::{ + synthetic_call_result, system::intercept::peek_selector, ExternalEnvTypes, MegaContext, + OracleEnv, +}; /// The address of the Oracle system contract. pub const ORACLE_CONTRACT_ADDRESS: Address = address!("0x6342000000000000000000000000000000000001"); @@ -23,48 +35,66 @@ pub use mega_system_contracts::oracle::LATEST_CODE_HASH as ORACLE_CONTRACT_CODE_ pub use mega_system_contracts::oracle::IOracle; -/// Forwards the hint of a `sendHint(bytes32,bytes)` call to the node's oracle service, and -/// never answers the call: the deployed bytecode runs, whatever the interceptor did. +/// Forwards the hint of a `sendHint(bytes32,bytes)` call to the node's oracle service, and lets +/// the deployed bytecode run; it answers the call only with the stop of a hint that would cross +/// the transaction's data-size limit. /// /// `sendHint` is the one intercepted selector of the Oracle, and the only one that is a side /// effect rather than an answer. The Oracle's storage methods are ordinary code, and reading /// its storage through the node's oracle service is the Host's business. /// -/// Two conditions admit a hint, and neither is a statement about the frame that runs afterwards: +/// Three conditions admit a hint, and none is a statement about the frame that runs afterwards: /// /// - the call was forwarded gas. A call with none cannot run the dispatcher of the bytecode at all, /// so its hint would be a free message to the service; /// - the call carries no value. `sendHint` is not payable, so a value-bearing call reverts in the -/// bytecode and its hint would be one the caller never sent. +/// bytecode and its hint would be one the caller never sent; +/// - the calling frame may read volatile data. A hint is how a contract asks the oracle service for +/// what it will read from the Oracle's storage, and a frame whose volatile-data access +/// `MegaAccessControl` switched off — its own switch, or one a frame above it set — cannot read +/// it. Its hint is dropped, not refused: the call runs the bytecode as any other, because a hint +/// is a message to the service, not state, and dropping it changes nothing the call returns. /// -/// The gas condition is the legacy engine's, carried over; the value condition is new. +/// The gas and switch conditions are the legacy engine's, carried over; the value condition is +/// new. A hint that fails any of them is neither forwarded nor counted. /// /// Gas above zero does not promise that the bytecode succeeds: a hint forwarded with one gas -/// reaches the service and the frame it was sent from then runs out of gas. An admitted hint is a +/// reaches the service and the frame it was sent from then runs out of gas. A forwarded hint is a /// synchronous, irreversible side effect — the service holds it whatever the frame, or the -/// transaction, does next. That is also why its bytes are counted on the transaction rather than -/// on the frame. +/// transaction, does next. That is one reason its bytes are counted on the transaction rather than +/// on the frame; the other, which holds as well for an admitted payload that fails to decode and +/// is never forwarded, is that admitting it and decoding it is work done either way. /// /// A `STATICCALL` does forward: `sendHint` is a view method and writes nothing. /// /// The payload is counted toward the transaction's data size before it is decoded /// ([`AdditionalLimit::record_hint_bytes`](crate::AdditionalLimit)), so trailing bytes an ABI -/// decoder ignores are paid for; a payload that crosses the transaction's limit is not -/// forwarded, and the limit stops the transaction at the frame the call would have started. +/// decoder ignores are paid for; a payload that would cross the transaction's limit is neither +/// forwarded nor counted, and the call is answered with the stop: a revert carrying +/// `MegaLimitExceeded`, on the gas it was forwarded, as the frame it would have started. So the +/// data size a transaction keeps holds exactly the hints that were admitted. +/// +/// `depth` is the depth of the frame the call would start; the calling frame is one level above +/// it, and a transaction that calls the Oracle directly has no frame above it, so nothing it +/// switched off can withhold its hint. pub(crate) fn intercept( ctx: &mut MegaContext, inputs: &CallInputs, + depth: usize, ) -> Option { let selector = peek_selector(&inputs.input, ctx)?; if selector != IOracle::sendHintCall::SELECTOR || inputs.transfers_value() || - inputs.gas_limit == 0 + inputs.gas_limit == 0 || + depth.checked_sub(1).is_some_and(|caller| ctx.detention.is_access_disabled(caller)) { return None; } let payload = inputs.input.bytes(&*ctx); - if ctx.additional_limit.record_hint_bytes(payload.len() as u64).exceeded_limit() { - return None; + let check = ctx.additional_limit.record_hint_bytes(payload.len() as u64); + if check.exceeded_limit() { + let output = ctx.additional_limit.note_frame_stop(&check); + return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); } // Trailing bytes after a valid envelope are dropped by the decoder and a malformed envelope // is refused; either way the payload is paid for above. @@ -72,3 +102,84 @@ pub(crate) fn intercept( ctx.external_envs().oracle_env.on_hint(inputs.caller, call.topic, call.data); None } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + test_utils::MemoryDatabase, EvmTxRuntimeLimits, ExternalEnvs, LimitCheck, LimitKind, + MegaSpecId, TestExternalEnvs, + }; + use alloy_primitives::{Bytes, B256, U256}; + use core::convert::Infallible; + use revm::interpreter::{CallInput, CallScheme, CallValue}; + + const CONTRACT: Address = address!("00000000000000000000000000000000000c0001"); + const FORWARD: u64 = 100_000; + + /// A context recording the hints its oracle service receives, under a transaction data-size + /// limit of `limit` bytes and no other limit. + fn recording( + limit: u64, + ) -> (MegaContext>, TestExternalEnvs) + { + let envs = TestExternalEnvs::::new(); + let ctx = MegaContext::new_with_external_envs( + MemoryDatabase::default(), + MegaSpecId::SATIN, + ExternalEnvs::from(envs.clone()), + ) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + (ctx, envs) + } + + /// A `CALL` from [`CONTRACT`] to the Oracle carrying `sendHint(topic, data)`. + fn send_hint(data: &[u8]) -> CallInputs { + let input = IOracle::sendHintCall { topic: B256::ZERO, data: Bytes::copy_from_slice(data) } + .abi_encode(); + CallInputs { + input: CallInput::Bytes(input.into()), + return_memory_offset: 0..0, + gas_limit: FORWARD, + reservoir: 0, + bytecode_address: ORACLE_CONTRACT_ADDRESS, + known_bytecode: Default::default(), + target_address: ORACLE_CONTRACT_ADDRESS, + caller: CONTRACT, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: false, + } + } + + /// A hint whose payload would cross the transaction's data-size limit answers the call it was + /// sent with with the stop itself: a revert carrying `MegaLimitExceeded` on the gas the call + /// was forwarded, untouched. Nothing is forwarded and nothing is counted. A payload exactly at + /// the limit is forwarded and counted, and the bytecode runs. + #[test] + fn test_a_hint_that_would_cross_the_limit_answers_its_call_with_the_stop() { + let inputs = send_hint(&[7_u8; 64]); + let payload = inputs.input.len() as u64; + + let (mut ctx, envs) = recording(payload - 1); + let answer = intercept(&mut ctx, &inputs, 1).expect("the call is answered"); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: payload - 1, + used: payload, + frame_local: false, + }; + let result = answer.interpreter_result(); + assert_eq!(result.result, InstructionResult::Revert); + assert_eq!(result.output, stop.revert_data()); + assert_eq!(result.gas.remaining(), FORWARD, "the forward is untouched"); + assert!(envs.recorded_hints().is_empty(), "nothing is forwarded"); + assert_eq!(ctx.additional_limit.usage().data_size, 0, "nothing is counted"); + + let (mut ctx, envs) = recording(payload); + assert!(intercept(&mut ctx, &inputs, 1).is_none(), "the bytecode runs"); + assert_eq!(envs.recorded_hints().len(), 1); + assert_eq!(ctx.additional_limit.usage().data_size, payload); + } +} diff --git a/crates/mega-evm/src/system/predeploys.rs b/crates/mega-evm/src/system/predeploys.rs new file mode 100644 index 000000000..6fb13e090 --- /dev/null +++ b/crates/mega-evm/src/system/predeploys.rs @@ -0,0 +1,206 @@ +//! The predeploys Satin runs on, and the check its activation block makes of them. +//! +//! [`system_contract_specs`] lists them: the six `MegaETH` system contracts in address order, then +//! the EIP-7997 `CREATE2` factory, each with the code Satin expects (the bytecode +//! `mega-system-contracts` ships; the Oracle and the `SequencerRegistry` are their v2.0.0). A chain +//! reaches Satin through the legacy forks, which install the six, and OP's genesis tooling, which +//! preinstalls the factory, so Satin deploys none of them. +//! +//! The block in which Satin activates checks once that each address holds that code +//! ([`check_system_contract`]); no other block reads them. The check returns its read as a state +//! and never commits; the block executor commits it as a read-only state of its own, so the +//! activation block's witness, built from the committed states, carries the seven accounts. + +use core::fmt; + +use alloy_primitives::{address, b256, bytes, Address, Bytes, B256}; +use revm::{ + primitives::KECCAK_EMPTY, + state::{Account, EvmState}, + Database, +}; + +use super::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH}, + ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ACCESS_CONTROL_CODE_HASH, + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + LIMIT_CONTROL_CODE_HASH, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, + SEQUENCER_REGISTRY_CODE_HASH, +}; + +/// How many predeploys [`system_contract_specs`] returns: the six `MegaETH` system contracts and +/// the EIP-7997 factory. +pub const SYSTEM_CONTRACT_COUNT: usize = 7; + +/// The EIP-7997 `CREATE2` factory address (Arachnid's deterministic deployment proxy). +pub const CREATE2_FACTORY_ADDRESS: Address = address!("0x4e59b44847b379578588920cA78FbF26c0B4956C"); + +/// Runtime bytecode of the EIP-7997 factory. +pub const CREATE2_FACTORY_CODE: Bytes = + bytes!("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"); + +/// Keccak-256 hash of [`CREATE2_FACTORY_CODE`]. +pub const CREATE2_FACTORY_CODE_HASH: B256 = + b256!("0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989"); + +/// A predeploy: the address and the code Satin expects there. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SystemContractSpec { + /// The predeploy's address. + pub address: Address, + /// The runtime bytecode the address holds, which a test or a tool installs for a state of + /// its own. + pub code: Bytes, + /// Keccak-256 hash of [`code`](Self::code): what the activation check compares. + pub code_hash: B256, +} + +impl SystemContractSpec { + /// The predeploy at `address` holding `code`, whose hash is `code_hash`. + pub const fn new(address: Address, code: Bytes, code_hash: B256) -> Self { + Self { address, code, code_hash } + } +} + +/// Why [`check_system_contract`] refused a predeploy. +#[derive(Debug)] +pub enum SystemContractCheckError { + /// The database could not load the account at the predeploy's address. + Database(DbError), + /// The address does not hold the code Satin expects: it holds other code, an older version + /// of the contract, no code, or no account. + UnexpectedCode { + /// The predeploy's address. + address: Address, + /// The code hash Satin expects there. + expected: B256, + /// The code hash the address holds: the empty code's for no code or no account. + found: B256, + }, +} + +impl From for SystemContractCheckError { + fn from(error: DbError) -> Self { + Self::Database(error) + } +} + +impl fmt::Display for SystemContractCheckError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Database(error) => write!(f, "{error}"), + Self::UnexpectedCode { address, expected, found } => { + write_unexpected_code(f, *address, *expected, *found) + } + } + } +} + +/// The refusal of a predeploy at `address` that holds the code hash `found` where `expected` must +/// be when Satin activates. +pub(crate) fn write_unexpected_code( + f: &mut fmt::Formatter<'_>, + address: Address, + expected: B256, + found: B256, +) -> fmt::Result { + write!(f, "the predeploy at {address} must hold code hash {expected} when Satin activates; ")?; + if found == KECCAK_EMPTY { + f.write_str("it holds no code") + } else { + write!(f, "it holds code hash {found}") + } +} + +impl core::error::Error + for SystemContractCheckError +{ + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Database(error) => Some(error), + Self::UnexpectedCode { .. } => None, + } + } +} + +/// Checks that `spec.address` holds `spec.code_hash`, returning the account as a read-only entry +/// (neither touched nor created, no storage) for the witness. Nothing is written or committed. +/// +/// The code alone is checked: the nonce, the balance and the storage are whatever the chain holds. +/// +/// # Errors +/// +/// [`SystemContractCheckError::Database`] when the account cannot be loaded, and +/// [`SystemContractCheckError::UnexpectedCode`] when the address holds no account, no code, or +/// any other code than the expected one. +pub fn check_system_contract( + db: &mut DB, + spec: &SystemContractSpec, +) -> Result> { + let existing = db.basic(spec.address).map_err(SystemContractCheckError::Database)?; + match existing { + // `Account::from` copies the info and leaves the status empty: neither touched nor + // created, which is the read-only witness entry. + Some(info) if info.code_hash == spec.code_hash => { + Ok(EvmState::from_iter([(spec.address, Account::from(info))])) + } + existing => Err(SystemContractCheckError::UnexpectedCode { + address: spec.address, + expected: spec.code_hash, + found: existing.map_or(KECCAK_EMPTY, |info| info.code_hash), + }), + } +} + +/// The seven predeploys in the order the activation block checks them: Oracle, high-precision +/// timestamp, `KeylessDeploy`, `MegaAccessControl`, `MegaLimitControl`, `SequencerRegistry`, then +/// the EIP-7997 factory. +pub fn system_contract_specs() -> [SystemContractSpec; SYSTEM_CONTRACT_COUNT] { + [ + SystemContractSpec::new( + ORACLE_CONTRACT_ADDRESS, + ORACLE_CONTRACT_CODE, + ORACLE_CONTRACT_CODE_HASH, + ), + SystemContractSpec::new( + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, + ), + SystemContractSpec::new( + KEYLESS_DEPLOY_ADDRESS, + KEYLESS_DEPLOY_CODE, + KEYLESS_DEPLOY_CODE_HASH, + ), + SystemContractSpec::new( + ACCESS_CONTROL_ADDRESS, + ACCESS_CONTROL_CODE, + ACCESS_CONTROL_CODE_HASH, + ), + SystemContractSpec::new(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, LIMIT_CONTROL_CODE_HASH), + SystemContractSpec::new( + SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE, + SEQUENCER_REGISTRY_CODE_HASH, + ), + SystemContractSpec::new( + CREATE2_FACTORY_ADDRESS, + CREATE2_FACTORY_CODE, + CREATE2_FACTORY_CODE_HASH, + ), + ] +} + +/// The addresses of [`system_contract_specs`], in its order: the six `MegaETH` contracts, then the +/// EIP-7997 factory. +pub const SYSTEM_CONTRACT_ADDRESSES: [Address; SYSTEM_CONTRACT_COUNT] = [ + ORACLE_CONTRACT_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + KEYLESS_DEPLOY_ADDRESS, + ACCESS_CONTROL_ADDRESS, + LIMIT_CONTROL_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + CREATE2_FACTORY_ADDRESS, +]; diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index 83dfa20a6..f7cda377b 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -5,10 +5,39 @@ //! to it is an ordinary call. Its Solidity source is //! `crates/system-contracts/contracts/SequencerRegistry.sol`. //! -//! Reading the rotated system address out of its storage, and the pre-block call that applies a -//! due change, belong to system contract deployment and the pre-block system calls. +//! The legacy forks deployed it (Rex5) and upgraded it to v2.0.0 (Rex6); Satin neither creates nor +//! upgrades it. The block in which Satin activates checks that it holds v2.0.0 +//! ([`check_system_contract`](crate::system::check_system_contract)), and is invalid +//! otherwise. A role change the registry schedules takes effect at its activation block through a +//! pre-block call: the block executor reads whether one is due +//! ([`is_apply_pending_changes_due`]) and, when one is, calls `applyPendingChanges()` +//! ([`transact_apply_pending_changes`]). The call is permissionless and applies only what is due, +//! so a block that makes it applies the same changes whoever calls. +//! +//! The live system address, which a system-address transaction must be sent from, is read out of +//! the registry by every transaction when it is validated ([`load_system_address`]): the read +//! loads the registry's account and `_currentSystemAddress` into the transaction's journal, warm, +//! as EIP-3651 starts the block beneficiary warm, so what a transaction pays never depends on its +//! envelope. Nothing inside a block can change the address after the pre-block call — a change can +//! only be scheduled for a later block — so every transaction of a block reads the address the +//! block's pre-block step left, and an EVM a node builds outside block execution reads the one in +//! the state it runs on without being told. + +use alloy_evm::block::BlockExecutionError; +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use op_revm::OpHaltReason; +use revm::{ + context::{result::ResultAndState, JournalTr}, + primitives::KECCAK_EMPTY, + state::{Account, EvmState, EvmStorageSlot, TransactionId}, +}; -use alloy_primitives::{address, Address}; +use crate::{transact_pre_block_call, ExternalEnvTypes, MegaBlockExecutionError, MegaEvm}; +use storage_slots::{ + CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, +}; /// The address of the `SequencerRegistry` system contract. pub const SEQUENCER_REGISTRY_ADDRESS: Address = @@ -20,4 +49,533 @@ pub use mega_system_contracts::sequencer_registry::LATEST_CODE as SEQUENCER_REGI /// The code hash of the `SequencerRegistry` contract. pub use mega_system_contracts::sequencer_registry::LATEST_CODE_HASH as SEQUENCER_REGISTRY_CODE_HASH; -pub use mega_system_contracts::sequencer_registry::ISequencerRegistry; +pub use mega_system_contracts::sequencer_registry::{storage_slots, ISequencerRegistry}; + +/// Whether a role change the registry holds is due at `block_number`: a pending system address +/// or sequencer whose activation block has come. +/// +/// Also answers the reads that decided it, as read-only entries of the registry's account: the +/// witness a stateless client replays the decision from, which the caller commits whether or +/// not a change is due. Both roles' pending slots are read, and a role's activation block only +/// when it has a change pending. A registry that does not exist has nothing due, and its absence +/// is what the witness records; no chain Satin runs on lacks it, its activation block refusing +/// one without the registry's code, so only a state built apart from a chain, such as a test's, +/// reaches that answer. +/// +/// # Errors +/// +/// The database's, when the registry's account or one of its slots cannot be read. +pub fn is_apply_pending_changes_due( + db: &mut DB, + block_number: u64, +) -> Result<(bool, EvmState), DB::Error> { + let Some(info) = db.basic(SEQUENCER_REGISTRY_ADDRESS)? else { + let absent = Account::new_not_existing(TransactionId::ZERO); + return Ok((false, EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, absent)]))); + }; + let mut registry = Account::from(info); + let mut due = false; + for (pending, activation) in [ + (PENDING_SYSTEM_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK), + (PENDING_SEQUENCER, SEQUENCER_ACTIVATION_BLOCK), + ] { + due |= is_role_due(db, &mut registry, pending, activation, block_number)?; + } + Ok((due, EvmState::from_iter([(SEQUENCER_REGISTRY_ADDRESS, registry)]))) +} + +/// Whether the role whose pending value lives at `pending` is due at `block_number`, recording +/// each slot it reads into `registry` as a read-only entry. +fn is_role_due( + db: &mut DB, + registry: &mut Account, + pending: U256, + activation: U256, + block_number: u64, +) -> Result { + let pending_value = read_slot(db, registry, pending)?; + if pending_value.is_zero() { + return Ok(false); + } + let activation_block = read_slot(db, registry, activation)?; + Ok(U256::from(block_number) >= activation_block) +} + +/// Reads the registry's `slot` and records it into `registry` without marking it changed. +fn read_slot( + db: &mut DB, + registry: &mut Account, + slot: U256, +) -> Result { + let value = db.storage(SEQUENCER_REGISTRY_ADDRESS, slot)?; + registry.storage.insert(slot, EvmStorageSlot::new(value, TransactionId::ZERO)); + Ok(value) +} + +/// Runs the pre-block `applyPendingChanges()` call on the registry and answers its result and +/// state. Nothing is committed. +/// +/// It is a system call from the EIP-4788 system address on the pre-block budget +/// ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)): at most 30M of regular gas, +/// the rest reservoir, its state priced at the minimum SALT bucket. One call applies whichever of +/// the two roles is due; the block executor makes it only when [`is_apply_pending_changes_due`] +/// says one is. +/// +/// # Errors +/// +/// [`MegaBlockExecutionError::ApplyPendingChangesFailed`] when the call reverts or halts, or an +/// error other than a fatal database error stops it: a change the registry scheduled for this +/// block must be applied in it. A fatal database error is an internal error, as for every +/// pre-block call: it says nothing about the block. +pub fn transact_apply_pending_changes( + evm: &mut MegaEvm, +) -> Result, BlockExecutionError> +where + DB: alloy_evm::Database, + ExtEnvs: ExternalEnvTypes, +{ + let data = Bytes::from(ISequencerRegistry::applyPendingChangesCall {}.abi_encode()); + let refused = |message| MegaBlockExecutionError::ApplyPendingChangesFailed { message }.into(); + transact_pre_block_call(evm, "applyPendingChanges()", SEQUENCER_REGISTRY_ADDRESS, data, refused) +} + +/// The live system address in the state `db` holds: the address a system-address transaction +/// must be sent from, as every transaction reads it when it is validated. +/// +/// It is what a transaction pool gives +/// [`validate_transaction_stateless`](crate::validate_transaction_stateless), read off the state +/// the pool validates against, and it holds for the block whose pre-block changes made that +/// state: a later block's pre-block step may change it, so a pool reads it again for every block. +/// `None` when the registry names no address this engine trusts: it has no account, it holds +/// other code than [`SEQUENCER_REGISTRY_CODE`], or its `_currentSystemAddress` is zero. +/// +/// It reads the registry's account and, when it holds this engine's code, the one slot, and +/// writes nothing, so any database serves: pass `&mut db` for a [`Database`](revm::Database) the +/// caller keeps, and `WrapDatabaseRef(&db)` ([`revm::database_interface::WrapDatabaseRef`]) for a +/// [`DatabaseRef`](revm::DatabaseRef), such as a read-only view of a block's state. +/// +/// # Errors +/// +/// The database's, when the registry's account or its slot cannot be read. +pub fn live_system_address(mut db: DB) -> Result, DB::Error> { + let code_hash = + db.basic(SEQUENCER_REGISTRY_ADDRESS)?.map_or(KECCAK_EMPTY, |info| info.code_hash); + if code_hash != SEQUENCER_REGISTRY_CODE_HASH { + return Ok(None); + } + let current = db.storage(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)?; + Ok(system_address_named_by(code_hash, current)) +} + +/// The live system address, read out of the registry in the running transaction's journal: the +/// address a system-address transaction must be sent from. +/// +/// Every transaction makes the read when it is validated, whatever its shape and whoever sends it, +/// so the registry's account and its `_currentSystemAddress` slot are loaded into the journal warm, +/// as EIP-3651 starts the block beneficiary warm: a transaction's own access to either pays the +/// warm price, whatever its envelope. Both are in the transaction's state, so a stateless witness +/// carries the read; neither is written, so committing the transaction leaves the registry as it +/// was. The registry's code is not loaded: its code hash is compared, not its code. +/// +/// `None` when the registry names no address this engine trusts: it has no account, it holds other +/// code than [`SEQUENCER_REGISTRY_CODE`], or its `_currentSystemAddress` is zero. A chain Satin +/// runs on never holds such a registry — Satin's activation block refuses a chain whose registry +/// does not hold this code, nothing in Satin replaces a contract's code, and the contract writes no +/// zero address — so these are states an EVM run outside block execution, or a block a tool or a +/// test runs on a state of its own, may meet, and in none of them is any transaction a +/// system-address transaction. The slot is loaded in each of +/// them all the same, so the transaction's gas does not depend on them. +/// +/// # Errors +/// +/// The database's, when the account or the slot cannot be read. +pub(crate) fn load_system_address( + journal: &mut J, +) -> Result, ::Error> { + let code_hash = journal.load_account(SEQUENCER_REGISTRY_ADDRESS)?.data.info.code_hash; + let current = journal.sload(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)?.data; + Ok(system_address_named_by(code_hash, current)) +} + +/// The system address a registry whose code hash is `code_hash` names when its +/// `_currentSystemAddress` holds `current`: none unless the registry holds this engine's code and +/// a non-zero address. +fn system_address_named_by(code_hash: B256, current: U256) -> Option
{ + // The expected hash is the registry code this engine requires, the latest version. When the + // registry is next upgraded under a later spec, the hash compared here must be chosen per + // spec: compared with the newer code alone, a block of this spec replayed by the newer binary + // finds no system address, and its system transactions are silently demoted to ordinary ones. + (code_hash == SEQUENCER_REGISTRY_CODE_HASH && !current.is_zero()) + .then(|| Address::from_word(current.into())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId}; + use alloy_primitives::address; + use revm::{ + context::{BlockEnv, ContextTr, JournalTr, Transaction}, + database::{InMemoryDB, State}, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, + state::{AccountInfo, Bytecode}, + Database, DatabaseCommit, + }; + use storage_slots::CURRENT_SEQUENCER; + + const NEXT_SYSTEM_ADDRESS: Address = address!("0x1111111111111111111111111111111111111111"); + const NEXT_SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); + const CURRENT_SEQUENCER_ADDRESS: Address = + address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); + + fn word(address: Address) -> U256 { + U256::from_be_bytes(address.into_word().0) + } + + /// A database holding the registry's code and `slots`. + fn registry_with(slots: &[(U256, U256)]) -> InMemoryDB { + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { + code_hash: SEQUENCER_REGISTRY_CODE_HASH, + code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), + ..Default::default() + }, + ); + for &(slot, value) in slots { + db.insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, slot, value).unwrap(); + } + db + } + + /// Asks whether a change is due at `block_number`, over a fresh cache of `db`. + fn due_at(db: &mut InMemoryDB, block_number: u64) -> (bool, Account) { + let mut state = State::builder().with_database(db).build(); + let (due, witness) = is_apply_pending_changes_due(&mut state, block_number).unwrap(); + assert_eq!(witness.len(), 1, "the registry is the only account read"); + (due, witness[&SEQUENCER_REGISTRY_ADDRESS].clone()) + } + + /// An EVM over `db` in a block at 1,000 whose gas limit is `gas_limit`. + fn evm( + db: &mut InMemoryDB, + gas_limit: u64, + ) -> MegaEvm<&mut InMemoryDB, revm::inspector::NoOpInspector> { + let block = BlockEnv { number: U256::from(1_000), gas_limit, ..Default::default() }; + MegaEvm::new(MegaContext::new(db, MegaSpecId::SATIN).with_block(block)) + } + + /// No registry, nothing due: the witness records the account's absence and no slot. + #[test] + fn test_is_apply_pending_changes_due_no_registry() { + let (due, registry) = due_at(&mut InMemoryDB::default(), 1_000); + assert!(!due); + assert!(registry.is_loaded_as_not_existing()); + assert!(registry.storage.is_empty(), "no slot of an absent registry is read"); + } + + /// A registry with nothing pending: both pending slots are read, and no activation block. + #[test] + fn test_is_apply_pending_changes_due_no_pending() { + let (due, registry) = due_at(&mut registry_with(&[]), 1_000); + assert!(!due); + assert_eq!(registry.storage.len(), 2, "{:?}", registry.storage); + assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(registry.storage.contains_key(&PENDING_SEQUENCER)); + } + + /// A pending system address is due from its activation block on, not before. + #[test] + fn test_is_apply_pending_changes_due_system_address_due() { + let mut db = registry_with(&[ + (PENDING_SYSTEM_ADDRESS, word(NEXT_SYSTEM_ADDRESS)), + (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(1_000)), + ]); + + let (due, registry) = due_at(&mut db, 999); + assert!(!due, "not yet due"); + assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(registry.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + + let (due, registry) = due_at(&mut db, 1_000); + assert!(due, "due at its activation block"); + assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(registry.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); + assert!(registry.storage.contains_key(&PENDING_SEQUENCER), "both roles are read"); + } + + /// A pending sequencer is due alone; the system address, with nothing pending, costs one read. + #[test] + fn test_is_apply_pending_changes_due_sequencer_due() { + let mut db = registry_with(&[ + (PENDING_SEQUENCER, word(NEXT_SEQUENCER)), + (SEQUENCER_ACTIVATION_BLOCK, U256::from(500)), + ]); + let (due, registry) = due_at(&mut db, 500); + assert!(due); + assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(registry.storage.contains_key(&PENDING_SEQUENCER)); + assert!(registry.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); + assert_eq!(registry.storage.len(), 3); + } + + /// A sequencer change due in this block makes the call whether or not the system address's + /// is, and every slot either role read is in the witness, read-only. + #[test] + fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { + let mut db = registry_with(&[ + (PENDING_SYSTEM_ADDRESS, word(NEXT_SYSTEM_ADDRESS)), + (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(1_001)), + (PENDING_SEQUENCER, word(NEXT_SEQUENCER)), + (SEQUENCER_ACTIVATION_BLOCK, U256::from(1_000)), + ]); + let (due, registry) = due_at(&mut db, 1_000); + assert!(due, "the sequencer's change is due though the system address's is not"); + assert_eq!(registry.storage.len(), 4, "both roles' slots are in the witness"); + assert!(!registry.is_touched(), "a read-only entry"); + for slot in [ + PENDING_SYSTEM_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + PENDING_SEQUENCER, + SEQUENCER_ACTIVATION_BLOCK, + ] { + let slot = ®istry.storage[&slot]; + assert!(!slot.is_changed(), "a read-only slot is not marked changed"); + assert_eq!(slot.original_value(), slot.present_value()); + } + } + + /// The call applies both due roles: the pending values become current, and the pending and + /// activation slots are cleared. + #[test] + fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { + let mut db = registry_with(&[ + (CURRENT_SYSTEM_ADDRESS, word(MEGA_SYSTEM_ADDRESS)), + (CURRENT_SEQUENCER, word(CURRENT_SEQUENCER_ADDRESS)), + (PENDING_SYSTEM_ADDRESS, word(NEXT_SYSTEM_ADDRESS)), + (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(1_000)), + (PENDING_SEQUENCER, word(NEXT_SEQUENCER)), + (SEQUENCER_ACTIVATION_BLOCK, U256::from(1_000)), + ]); + let state = transact_apply_pending_changes(&mut evm(&mut db, 30_000_000)) + .expect("applyPendingChanges() succeeds") + .state; + db.commit(state); + + let mut slot = |slot| db.storage(SEQUENCER_REGISTRY_ADDRESS, slot).unwrap(); + assert_eq!(slot(CURRENT_SYSTEM_ADDRESS), word(NEXT_SYSTEM_ADDRESS)); + assert_eq!(slot(CURRENT_SEQUENCER), word(NEXT_SEQUENCER)); + for cleared in [ + PENDING_SYSTEM_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + PENDING_SEQUENCER, + SEQUENCER_ACTIVATION_BLOCK, + ] { + assert_eq!(slot(cleared), U256::ZERO); + } + } + + /// The call runs on the block's gas limit, of which 30M is regular gas and the rest the + /// reservoir: a registry with nothing due writes nothing, and all of the reservoir is left. + #[test] + fn test_transact_apply_pending_changes_uses_block_gas_limit() { + let mut db = registry_with(&[]); + let mut evm = evm(&mut db, 250_000_000); + let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); + assert_eq!(evm.ctx().tx().gas_limit(), 250_000_000); + assert_eq!( + outcome.result.gas().reservoir_remaining(), + 250_000_000 - SYSTEM_CALL_REGULAR_GAS_LIMIT + ); + } + + /// A block whose gas limit is below 30M still gives the call 30M, all of it regular gas. + #[test] + fn test_transact_apply_pending_changes_respects_30m_floor() { + let mut db = registry_with(&[]); + let mut evm = evm(&mut db, 1_000_000); + let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); + assert_eq!(evm.ctx().tx().gas_limit(), SYSTEM_CALL_REGULAR_GAS_LIMIT); + assert_eq!(outcome.result.gas().reservoir_remaining(), 0); + } + + /// A read the database cannot serve during the call is the database's error, not a verdict on + /// the block. + #[test] + fn test_transact_apply_pending_changes_reports_a_database_error_as_one() { + use crate::test_utils::{ErrorInjectingDatabase, MemoryDatabase}; + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + let block = + BlockEnv { number: U256::from(1_000), gas_limit: 30_000_000, ..Default::default() }; + let mut evm = MegaEvm::new(MegaContext::new(&mut db, MegaSpecId::SATIN).with_block(block)); + let err = transact_apply_pending_changes(&mut evm).expect_err("the read fails"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("injected basic() error"), "{err}"); + } + + /// A registry whose code reverts fails the call, and the block with it: the refusal is a + /// validation error, a verdict on the block, and not an internal one a node would retry. + #[test] + fn test_transact_apply_pending_changes_errors_when_registry_reverts() { + let revert = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { code_hash: revert.hash_slow(), code: Some(revert), ..Default::default() }, + ); + let err = transact_apply_pending_changes(&mut evm(&mut db, 30_000_000)) + .expect_err("a reverting registry fails closed"); + let BlockExecutionError::Validation(alloy_evm::block::BlockValidationError::Other(error)) = + &err + else { + panic!("a reverting registry refuses the block: {err:?}"); + }; + assert!( + matches!( + error.downcast_ref(), + Some(MegaBlockExecutionError::ApplyPendingChangesFailed { .. }) + ), + "{err:?}" + ); + assert!( + err.to_string().starts_with( + "the SequencerRegistry's pending changes could not be applied: \ + the applyPendingChanges() pre-block call did not succeed: Revert {" + ), + "{err}" + ); + } + + /// A database whose registry holds `code` and `current` as its system address. + fn registry_holding(code: Bytes, current: Option
) -> InMemoryDB { + let code = Bytecode::new_raw(code); + let mut db = InMemoryDB::default(); + db.insert_account_info( + SEQUENCER_REGISTRY_ADDRESS, + AccountInfo { code_hash: code.hash_slow(), code: Some(code), ..Default::default() }, + ); + if let Some(current) = current { + db.insert_account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + word(current), + ) + .unwrap(); + } + db + } + + /// Reads the live system address out of `db` through a fresh journal, and answers it with the + /// journal the read left behind. + fn load(db: InMemoryDB) -> (Option
, revm::Journal) { + let mut journal = revm::Journal::new(db); + let address = load_system_address(&mut journal).expect("the read succeeds"); + (address, journal) + } + + /// Asserts the read left the registry's account and its system-address slot in `journal`, + /// warm, untouched and unchanged, the slot holding `current`: a witness of the read, and what + /// the transaction's own access to either finds warm. + fn assert_warm_and_unchanged(journal: &revm::Journal, current: U256) { + let registry = &journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_cold_transaction_id(journal.transaction_id), "the account is warm"); + assert!(!registry.is_touched(), "a read-only entry"); + assert_eq!(registry.storage.len(), 1, "exactly the one slot read"); + let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; + assert!(!slot.is_cold, "the slot is warm"); + assert!(!slot.is_changed()); + assert_eq!(slot.present_value(), current); + } + + /// A registry holding the code this engine requires names the address it stores, and the read + /// leaves the account and the slot warm, without loading the code. + #[test] + fn test_the_read_answers_the_stored_system_address_and_warms_the_registry() { + let db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + let (address, journal) = load(db); + assert_eq!(address, Some(NEXT_SYSTEM_ADDRESS)); + assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); + assert_eq!( + journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].info.code_hash, + SEQUENCER_REGISTRY_CODE_HASH + ); + } + + /// A registry still holding the legacy engine's first bytecode is not the one this engine + /// requires: it names no address. Its slot is read all the same, so what a transaction pays + /// does not depend on the registry's code. + #[test] + fn test_the_read_refuses_the_v1_code_hash() { + use mega_system_contracts::sequencer_registry::V1_0_0_CODE; + let (address, journal) = load(registry_holding(V1_0_0_CODE, Some(NEXT_SYSTEM_ADDRESS))); + assert_eq!(address, None); + assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); + } + + /// A registry holding foreign code names no address, whatever it stores. + #[test] + fn test_the_read_refuses_foreign_code() { + let db = registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS)); + let (address, journal) = load(db); + assert_eq!(address, None); + assert_warm_and_unchanged(&journal, word(NEXT_SYSTEM_ADDRESS)); + } + + /// A registry whose system address is zero names none: no caller, the zero address included, + /// is the system address of an empty registry. + #[test] + fn test_the_read_answers_no_address_for_a_zero_slot() { + let (address, journal) = load(registry_holding(SEQUENCER_REGISTRY_CODE, None)); + assert_eq!(address, None); + assert_warm_and_unchanged(&journal, U256::ZERO); + } + + /// A state without the registry names no address, and the read records the account's + /// absence and the slot it would hold, zero. + #[test] + fn test_the_read_answers_no_address_without_a_registry() { + let (address, journal) = load(InMemoryDB::default()); + assert_eq!(address, None); + assert!(journal.inner.state[&SEQUENCER_REGISTRY_ADDRESS].is_loaded_as_not_existing()); + assert_warm_and_unchanged(&journal, U256::ZERO); + } + + /// Read off a database, the live system address is what a transaction's validation reads: + /// the address the registry stores when it holds this engine's code, and none otherwise. + #[test] + fn test_live_system_address_reads_what_validation_reads() { + let read = |db: InMemoryDB| live_system_address(db).expect("the read succeeds"); + assert_eq!( + read(registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS))), + Some(NEXT_SYSTEM_ADDRESS) + ); + assert_eq!(read(registry_holding(SEQUENCER_REGISTRY_CODE, None)), None); + assert_eq!( + read(registry_holding(Bytes::from_static(&[0x60, 0x00]), Some(NEXT_SYSTEM_ADDRESS))), + None + ); + assert_eq!(read(InMemoryDB::default()), None); + + // A database the caller keeps, and one it can only read through `DatabaseRef`. + let mut db = registry_holding(SEQUENCER_REGISTRY_CODE, Some(NEXT_SYSTEM_ADDRESS)); + assert_eq!(live_system_address(&mut db).unwrap(), Some(NEXT_SYSTEM_ADDRESS)); + let wrapped = revm::database_interface::WrapDatabaseRef(&db); + assert_eq!(live_system_address(wrapped).unwrap(), Some(NEXT_SYSTEM_ADDRESS)); + } + + /// A read the database cannot serve is the database's error, not an absent address. + #[test] + fn test_the_read_reports_a_database_error() { + use crate::test_utils::{ErrorInjectingDatabase, MemoryDatabase}; + let mut db = ErrorInjectingDatabase::new( + MemoryDatabase::default() + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE), + ); + db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + let mut journal: revm::Journal<_> = revm::Journal::new(db); + let err = load_system_address(&mut journal).expect_err("the read fails"); + assert!(err.to_string().contains("injected storage() error"), "{err}"); + } +} diff --git a/crates/mega-evm/src/system/tx.rs b/crates/mega-evm/src/system/tx.rs index d6e620440..a5c613f7c 100644 --- a/crates/mega-evm/src/system/tx.rs +++ b/crates/mega-evm/src/system/tx.rs @@ -1,53 +1,70 @@ //! The system-address transaction: how the protocol maintains its own state. //! //! The sequencer writes what the protocol owes the chain — the oracle values it served, for one -//! — through transactions sent from [`MEGA_SYSTEM_ADDRESS`]. They carry no signature and pay no -//! fee, so they are executed as deposit transactions: the engine stamps -//! [`MEGA_SYSTEM_TRANSACTION_SOURCE_HASH`] on one before it validates it, and op-revm's deposit -//! path takes it from there. +//! — through transactions sent from the system address the `SequencerRegistry` names. They pay +//! no fee, so they are executed as deposit transactions: the engine stamps +//! [`MEGA_SYSTEM_TRANSACTION_SOURCE_HASH`] on one before op-revm validates it, and op-revm's +//! deposit path takes it from there. +//! +//! A system-address transaction has a fixed shape +//! ([`has_system_transaction_shape`]): a legacy transaction calling a contract on +//! [`MEGA_SYSTEM_TX_WHITELIST`]. Every transaction reads the live system address out of the +//! registry when it is validated +//! ([`load_system_address`](crate::system::load_system_address)), and one of the system shape +//! whose caller is that address is a system-address transaction. A transaction from that address +//! of any other shape is invalid ([`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`]): the Oracle's +//! `onlySystemAddress` tests the sender alone, so the system key must send nothing the Oracle +//! would accept as an ordinary transaction. A deposit is never of the system shape, so a deposit +//! from the address is invalid too, and op-revm includes it as a failed deposit, which runs no +//! call. Every other sender is an ordinary one, an address a rotation retired included. //! //! A deposit is unvalidated by construction, so the engine validates what still matters itself //! before promoting the transaction ([`validate_and_promote`]): //! -//! - it may only call a contract on [`MEGA_SYSTEM_TX_WHITELIST`], never create one; //! - its chain id must be the chain's, so a transaction cannot be replayed on another chain; //! - its nonce must be the system address's, so it cannot be replayed on this one; //! - the system address must have no code of its own (EIP-3607). //! -//! The configuration switches that turn those checks off for a user transaction -//! (`tx_chain_id_check`, `disable_nonce_check`, `disable_eip3607`) turn them off here too: a -//! caller simulating a transaction sees one shape of validation, not two. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::string::ToString; +//! The chain id is checked whatever the configuration says, as it is for a user transaction: the +//! spec fixes the check on. A system-address transaction must carry one, which a user's legacy +//! transaction need not. The configuration switches that turn the other two checks off for a user +//! transaction (`disable_nonce_check`, `disable_eip3607`) turn them off here too: a caller +//! simulating a transaction sees one shape of validation, not two. use alloy_evm::Database; use alloy_primitives::{address, b256, Address, TxKind, B256}; -use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; use revm::{ - context::{result::FromStringError, ContextTr, Transaction}, + context::{ContextTr, JournalTr, Transaction}, context_interface::{cfg::Cfg, result::InvalidTransaction}, handler::pre_execution::validate_account_nonce_and_code, }; use crate::{ - system::ORACLE_CONTRACT_ADDRESS, types::MegaTransaction, ExternalEnvTypes, JournalInspectTr, - MegaContext, + system::ORACLE_CONTRACT_ADDRESS, types::MegaTransaction, ExternalEnvTypes, MegaContext, }; -/// The address the sequencer sends the protocol's own transactions from. +/// The initial system address of the `SequencerRegistry`: the one Rex5 created it naming, which a +/// chain's registry holds until a rotation. /// -/// A transaction from it is executed as a deposit: no signature, no nonce check of op-revm's own -/// and no fee. Which address it is can be rotated through the `SequencerRegistry`; reading the -/// rotated one out of the registry's storage belongs to system contract deployment, and until -/// then this is the address. +/// A system-address transaction is executed as a deposit: no nonce check of op-revm's own and no +/// fee. Which address sends them is the registry's to say, and it can be rotated through the +/// registry: the engine reads the live one out of the registry for every transaction, and never +/// falls back to this address. pub const MEGA_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); /// The contracts a system-address transaction may call. It may call nothing else and create /// nothing. pub const MEGA_SYSTEM_TX_WHITELIST: &[Address] = &[ORACLE_CONTRACT_ADDRESS]; +/// The message of the [`InvalidTransaction::Str`] a transaction is refused with when it is sent +/// from the live system address without the system shape ([`has_system_transaction_shape`]). +/// +/// A transaction other than a deposit is rejected with it, by a pool as by block execution; a +/// deposit, which op-revm does not refuse for a transaction error, is included as a failed +/// deposit instead, which bumps its sender's nonce, keeps its mint and runs nothing. +pub const SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE: &str = + "a transaction from the system address must be a legacy call to a whitelisted contract"; + /// The `source_hash` of a promoted system-address transaction, /// `keccak256("MEGA_SYSTEM_TRANSACTION")`. /// @@ -56,118 +73,136 @@ pub const MEGA_SYSTEM_TX_WHITELIST: &[Address] = &[ORACLE_CONTRACT_ADDRESS]; pub const MEGA_SYSTEM_TRANSACTION_SOURCE_HASH: B256 = b256!("852c082c0faff590c6300c2c34815d1f79882552fa95ba413cd5aeb1dba84957"); -/// Whether `tx` was sent from `system_address`. -pub fn sent_from_system_address(tx: &MegaTransaction, system_address: Address) -> bool { - tx.caller() == system_address -} - -/// Whether `tx` is a system-address transaction: a legacy transaction from `system_address` to a -/// contract on [`MEGA_SYSTEM_TX_WHITELIST`]. +/// Whether `tx` is a system-address transaction when `system_address` is the live system +/// address: a legacy transaction from it to a contract on [`MEGA_SYSTEM_TX_WHITELIST`]. pub fn is_mega_system_transaction_with(tx: &MegaTransaction, system_address: Address) -> bool { check_if_mega_system_transaction(tx.caller(), tx.tx_type(), tx.kind(), system_address) } -/// Whether a transaction with these fields is a system-address transaction. -/// -/// It is one when it was sent from `system_address` as a legacy transaction (type `0x0`, the -/// shape the sequencer builds) and calls a contract on [`MEGA_SYSTEM_TX_WHITELIST`]. A creation -/// is never one: the protocol maintains the contracts it deployed, it does not deploy new ones -/// this way. +/// Whether a transaction with these fields is a system-address transaction when `system_address` +/// is the live system address: it was sent from it and has the system shape +/// ([`has_system_transaction_shape`]). pub fn check_if_mega_system_transaction( tx_signer: Address, tx_type: u8, tx_kind: TxKind, system_address: Address, ) -> bool { - if tx_type != 0x0 || tx_signer != system_address { - return false; - } - match tx_kind { - TxKind::Create => false, - TxKind::Call(address) => MEGA_SYSTEM_TX_WHITELIST.contains(&address), - } + tx_signer == system_address && has_system_transaction_shape(tx_type, tx_kind) } -/// Whether `tx` is executed on the deposit path: a deposit transaction, or a system-address -/// transaction, which is promoted to one. -pub fn is_deposit_like_transaction(tx: &MegaTransaction, system_address: Address) -> bool { - tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || is_mega_system_transaction_with(tx, system_address) +/// Whether a transaction with these fields has the shape every system-address transaction has: a +/// legacy transaction (type `0x0`, the shape the sequencer builds) calling a contract on +/// [`MEGA_SYSTEM_TX_WHITELIST`]. A creation never has it: the protocol maintains the contracts it +/// deployed, it does not deploy new ones this way. +/// +/// It looks at the transaction's own fields only: the type, then the destination against the +/// one-entry whitelist. +pub fn has_system_transaction_shape(tx_type: u8, tx_kind: TxKind) -> bool { + tx_type == 0x0 && + match tx_kind { + TxKind::Create => false, + TxKind::Call(address) => MEGA_SYSTEM_TX_WHITELIST.contains(&address), + } } -/// Whether `tx` was produced by the protocol itself rather than by a user. +/// Whether `tx` is a system-address transaction when `system_address` is the live system address, +/// or the error it is refused with when it is sent from the live system address without the +/// system shape ([`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`]). +/// +/// The system key sends the system shape and nothing else: whatever else it signs — a typed +/// transaction, a call off the whitelist, a creation — is invalid, and so is a deposit from the +/// address, which is never of the system shape, and which op-revm then includes as a failed +/// deposit. An address the registry no longer names, or never named, is an ordinary sender. +pub(crate) fn classify_system_transaction( + tx: &MegaTransaction, + system_address: Option
, +) -> Result { + if system_address != Some(tx.caller()) { + return Ok(false); + } + if !has_system_transaction_shape(tx.tx_type(), tx.kind()) { + return Err(InvalidTransaction::Str(SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE.into())); + } + Ok(true) +} + +/// Whether `tx` was produced by the protocol itself rather than by a user, when `system_address` +/// is the live system address. /// /// That is the case for a call the engine makes on the chain's behalf (the EIP-2935 and EIP-4788 /// pre-block calls, whose caller is the EIP-4788 system address) and for a system-address /// transaction, before or after it was promoted. A user's deposit transaction is not /// system-originated, however deposit-like it is: it carries another source hash and another -/// caller. +/// caller. A deposit that carries the promotion's source hash is system-originated whoever sends +/// it; from the live system address it is also invalid, as every deposit from that address is +/// ([`SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE`]), so a transaction handed to the engine already +/// promoted is a failed deposit. +/// +/// Only a deposit carries a source hash: op-revm reads a transaction's type off it, so a +/// transaction that carries one is a deposit, and is executed as one, whatever type its other +/// fields declare. Testing the source hash is therefore testing for a deposit that carries it. /// /// It is what exempts the protocol's own work from the metering `MegaETH` holds users to — the -/// history gas of a system transaction is not charged, so the protocol's maintenance cannot fail -/// on a resource limit. The mechanisms that meter read it as they land. +/// history gas of a system transaction is not charged, and no per-transaction limit stops it, so +/// the protocol's maintenance cannot fail on a resource limit. The engine makes the same decision +/// for the running transaction with the address it read itself +/// ([`MegaContext::is_system_originated`]). pub fn is_system_originated(tx: &MegaTransaction, system_address: Address) -> bool { - tx.caller() == alloy_eips::eip4788::SYSTEM_ADDRESS || - tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH || - is_mega_system_transaction_with(tx, system_address) + originates_from_the_protocol(tx, is_mega_system_transaction_with(tx, system_address)) +} + +/// [`is_system_originated`], given whether `tx` is a system-address transaction. +pub(crate) fn originates_from_the_protocol(tx: &MegaTransaction, system_transaction: bool) -> bool { + system_transaction || + tx.caller() == alloy_eips::eip4788::SYSTEM_ADDRESS || + // A source hash makes the transaction a deposit, whatever type its fields declare. + tx.deposit.source_hash == MEGA_SYSTEM_TRANSACTION_SOURCE_HASH } -/// Validates a transaction sent from the system address and promotes it to a deposit; does -/// nothing to any other transaction. +/// Validates a system-address transaction and promotes it to a deposit. /// -/// Runs before op-revm validates the transaction, so op-revm sees the promoted shape: a deposit, -/// whose signature, nonce and fee it does not check. The checks the deposit path drops and this -/// chain still wants are made here (see the module documentation), each under the configuration -/// switch a user transaction obeys. +/// Called for the running transaction once validation found it is one, before +/// op-revm validates it, so op-revm sees the promoted shape: a deposit, whose signature, nonce and +/// fee it does not check. The checks the deposit path drops and this chain still wants are made +/// here (see the module documentation): the chain id always, the nonce and the code each under +/// the configuration switch a user transaction obeys. /// -/// A transaction from the system address that is not a system transaction is rejected outright: -/// the sequencer has no business sending it, and promoting it would give it the deposit path's -/// exemptions. That covers a creation, a call to a contract that is not on the whitelist, and -/// any shape that is not a legacy transaction — an EIP-1559 one, or one that already carries a -/// source hash, which has skipped the validation the promotion runs. +/// The system address's nonce and code are the state's: they are checked when `check_account` +/// says so, which is always in execution. Validation without state leaves them to the state, as +/// it leaves every sender's. pub(crate) fn validate_and_promote( ctx: &mut MegaContext, - system_address: Address, + check_account: bool, ) -> Result<(), ERROR> where DB: Database, ExtEnvs: ExternalEnvTypes, - ERROR: From + From + FromStringError, + ERROR: From + From, { - if !sent_from_system_address(ctx.tx(), system_address) { - return Ok(()); - } - if !is_mega_system_transaction_with(ctx.tx(), system_address) { - return Err(ERROR::from_string( - "a transaction from the system address must be a legacy call to a whitelisted \ - contract" - .to_string(), - )); - } - let cfg = ctx.cfg(); - let (chain_id, chain_id_check) = (cfg.chain_id(), cfg.tx_chain_id_check); + let chain_id = cfg.chain_id(); let (eip3607_disabled, nonce_check_disabled) = (cfg.is_eip3607_disabled(), cfg.is_nonce_check_disabled()); - if chain_id_check { - match ctx.tx().chain_id() { - None => return Err(InvalidTransaction::MissingChainId.into()), - Some(id) if id != chain_id => return Err(InvalidTransaction::InvalidChainId.into()), - Some(_) => {} - } + match ctx.tx().chain_id() { + None => return Err(InvalidTransaction::MissingChainId.into()), + Some(id) if id != chain_id => return Err(InvalidTransaction::InvalidChainId.into()), + Some(_) => {} } - // Read the system address without warming it: validation must not leave the account in the - // EIP-2929 access list, which would make the transaction's first touch of it cheaper than - // the same transaction from anyone else. Its code is loaded, so EIP-3607 sees a lazy - // database's code too. - let tx_nonce = ctx.tx().nonce(); - let account = ctx.journal_mut().inspect_account(system_address, true)?; - validate_account_nonce_and_code( - &account.info, - tx_nonce, - eip3607_disabled, - nonce_check_disabled, - )?; + // The system address is the transaction's caller, which the transaction starts warm, so the + // load changes nothing it pays. Its code is loaded, so EIP-3607 sees a lazy database's code + // too. + if check_account { + let (system_address, tx_nonce) = (ctx.tx().caller(), ctx.tx().nonce()); + let account = ctx.journal_mut().load_account_with_code(system_address)?.data; + validate_account_nonce_and_code( + &account.info, + tx_nonce, + eip3607_disabled, + nonce_check_disabled, + )?; + } // The deposit shape: op-revm skips the signature, the nonce and every fee for it. The gas // price goes to zero with it, so the fee accounting of the block degenerates to nothing. @@ -181,6 +216,7 @@ where mod tests { use super::*; use alloy_primitives::TxKind; + use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; const EIP_SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; const USER: Address = address!("0x0000000000000000000000000000000000009999"); @@ -210,12 +246,6 @@ mod tests { assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); } - #[test] - fn test_is_system_originated_rejects_system_caller_to_non_whitelist() { - let tx = legacy_call_tx(MEGA_SYSTEM_ADDRESS, NOT_WHITELISTED); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); - } - /// The promotion stamps the source hash and flips the transaction's type to a deposit; the /// promoted shape is still system-originated, through the source hash. #[test] @@ -230,20 +260,27 @@ mod tests { assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "the source hash does"); } + /// A transaction that carries the promotion's source hash is a deposit whatever type it + /// declares, so it is system-originated as the deposit it is, whoever sends it: no transaction + /// of another type carries the hash. #[test] - fn test_is_system_originated_rejects_user_tx() { - let tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); - assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + fn test_a_transaction_carrying_the_source_hash_is_a_deposit_whatever_type_it_declares() { + for declared in [0, 1, 2, 4] { + let mut tx = legacy_call_tx(USER, NOT_WHITELISTED); + tx.base.tx_type = declared; + tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE, "declared {declared}"); + assert!(is_system_originated(&tx, MEGA_SYSTEM_ADDRESS), "declared {declared}"); + } } - /// A user's deposit transaction is deposit-like but not system-originated: otherwise a user - /// could buy the protocol's exemptions by sending one. + /// A user's deposit transaction is not system-originated: otherwise a user could buy the + /// protocol's exemptions by sending one. #[test] fn test_is_system_originated_rejects_user_deposit_tx() { let mut tx = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); tx.deposit.source_hash = B256::repeat_byte(0x11); assert_eq!(tx.tx_type(), DEPOSIT_TRANSACTION_TYPE); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); assert!(!is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); } @@ -282,6 +319,23 @@ mod tests { ); } + /// The shape is the transaction's own fields alone: a legacy call to a whitelisted contract, + /// whoever sends it. A creation, another type and a promoted transaction (a deposit by type) + /// do not have it. + #[test] + fn test_the_system_shape_is_a_legacy_call_to_a_whitelisted_contract() { + let oracle = TxKind::Call(ORACLE_CONTRACT_ADDRESS); + assert!(has_system_transaction_shape(0, oracle)); + assert!(!has_system_transaction_shape(0, TxKind::Call(NOT_WHITELISTED))); + assert!(!has_system_transaction_shape(0, TxKind::Create)); + for tx_type in [1, 2, 3, 4, DEPOSIT_TRANSACTION_TYPE] { + assert!(!has_system_transaction_shape(tx_type, oracle), "type {tx_type}"); + } + let mut promoted = legacy_call_tx(USER, ORACLE_CONTRACT_ADDRESS); + promoted.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + assert!(!has_system_transaction_shape(promoted.tx_type(), promoted.kind())); + } + /// The source hash is the hash of the name it stands for. #[test] fn test_the_source_hash_is_the_hash_of_its_name() { diff --git a/crates/mega-evm/src/test_utils/bytes.rs b/crates/mega-evm/src/test_utils/bytes.rs index 1432aca19..2c99fada4 100644 --- a/crates/mega-evm/src/test_utils/bytes.rs +++ b/crates/mega-evm/src/test_utils/bytes.rs @@ -3,8 +3,30 @@ use alloc as std; use std::vec::Vec; /// Pads the bytes to the right with 0s to make it a multiple of the length. +/// +/// A multiple of zero is not a width, so the bytes are returned unchanged. pub fn right_pad_bytes(bytes: impl AsRef<[u8]>, multiple_of: usize) -> Vec { let bytes = bytes.as_ref().to_vec(); + if multiple_of == 0 { + return bytes; + } let padding = (multiple_of - (bytes.len() % multiple_of)) % multiple_of; [bytes, vec![0u8; padding]].concat() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_right_pad_bytes_leaves_a_zero_multiple_unchanged() { + assert_eq!(right_pad_bytes([1, 2, 3], 0), vec![1, 2, 3]); + assert_eq!(right_pad_bytes([1u8; 0], 0), Vec::::new()); + } + + #[test] + fn test_right_pad_bytes_pads_up_to_the_multiple() { + assert_eq!(right_pad_bytes([1, 2], 4), vec![1, 2, 0, 0]); + assert_eq!(right_pad_bytes([1, 2, 3, 4], 4), vec![1, 2, 3, 4]); + } +} diff --git a/crates/mega-evm/src/test_utils/database.rs b/crates/mega-evm/src/test_utils/database.rs index 47afb46ca..aeda79c25 100644 --- a/crates/mega-evm/src/test_utils/database.rs +++ b/crates/mega-evm/src/test_utils/database.rs @@ -8,6 +8,93 @@ use revm::{ state::{AccountInfo, Bytecode, EvmState}, }; +use crate::system::{ + storage_slots::{ + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, INITIAL_FROM_BLOCK, INITIAL_SEQUENCER, + INITIAL_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, + }, + system_contract_specs, CREATE2_FACTORY_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_CONTRACT_COUNT, +}; + +/// The nonce of the EIP-7997 factory in a Rex6-shaped state: the one OP's genesis tooling gives it. +/// Any nonzero nonce is one a chain holds; mainnet's is in the thousands. +const REX6_FACTORY_NONCE: u64 = 1; + +/// One predeploy as a state holds it: its address, its account and its storage slots. +pub type PredeployAccount = (Address, AccountInfo, Vec<(U256, U256)>); + +/// The seven predeploys as a chain that ran Rex6 holds them, which is what Satin's activation +/// block finds on mainnet and testnet, in [`system_contract_specs`] order. +/// +/// Each holds the code Satin expects. The six `MegaETH` system contracts are at nonce 0, which the +/// legacy engine never moved; the EIP-7997 factory is at a nonzero nonce, as OP's genesis tooling +/// leaves it; and the `SequencerRegistry` holds `roles` in its storage. Test and tool support for +/// a state of one's own, installed by [`MemoryDatabase::rex6_predeploys`]. +pub fn rex6_predeploys( + roles: impl Into, +) -> [PredeployAccount; SYSTEM_CONTRACT_COUNT] { + let roles = roles.into(); + system_contract_specs().map(|spec| { + let nonce = if spec.address == CREATE2_FACTORY_ADDRESS { REX6_FACTORY_NONCE } else { 0 }; + let storage = if spec.address == SEQUENCER_REGISTRY_ADDRESS { + roles.storage().to_vec() + } else { + Vec::new() + }; + let info = AccountInfo { + nonce, + code_hash: spec.code_hash, + code: Some(Bytecode::new_raw(spec.code)), + ..Default::default() + }; + (spec.address, info, storage) + }) +} + +/// The roles of a `SequencerRegistry` a test or a tool puts in a state, with +/// [`rex6_predeploys`] or [`MemoryDatabase::sequencer_registry`]. +/// +/// Test and tool support, not a chain parameter: the legacy forks deploy the registry (Rex5) and +/// upgrade it to v2.0.0 (Rex6), and Satin neither creates nor seeds it, so a state Satin runs a +/// block on must already hold it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SequencerRegistryRoles { + /// The live system address, and the initial one. + pub system_address: Address, + /// The current sequencer, and the initial one. + pub sequencer: Address, + /// The admin. + pub admin: Address, + /// The minimum delay between scheduling a rotation and its activation, in blocks. + pub min_rotation_delay: u64, +} + +impl From
for SequencerRegistryRoles { + /// `address` in every role, and a rotation delay of one block. + fn from(address: Address) -> Self { + Self { system_address: address, sequencer: address, admin: address, min_rotation_delay: 1 } + } +} + +impl SequencerRegistryRoles { + /// The storage of a v2.0.0 registry holding these roles, as the legacy forks leave it on a + /// chain that never rotated one: the seven slots its bootstrap writes, `_initialFromBlock` + /// zero. + pub fn storage(&self) -> [(U256, U256); 7] { + let word = |address: Address| U256::from_be_bytes(address.into_word().0); + [ + (CURRENT_SYSTEM_ADDRESS, word(self.system_address)), + (CURRENT_SEQUENCER, word(self.sequencer)), + (ADMIN, word(self.admin)), + (INITIAL_SYSTEM_ADDRESS, word(self.system_address)), + (INITIAL_SEQUENCER, word(self.sequencer)), + (INITIAL_FROM_BLOCK, U256::ZERO), + (MIN_ROTATION_DELAY, U256::from(self.min_rotation_delay)), + ] + } +} + /// A memory database for testing purposes. #[derive(Debug, Default, Clone, derive_more::Deref, derive_more::DerefMut)] pub struct MemoryDatabase { @@ -23,9 +110,15 @@ impl MemoryDatabase { } /// Sets the code for an account in the database. + /// + /// The bytecode is also stored under its hash. `code_by_hash` reads that map, and a miss falls + /// through to empty bytecode. pub fn set_account_code(&mut self, address: Address, code: Bytes) { let bytecode = Bytecode::new_legacy(code); let code_hash = bytecode.hash_slow(); + if !bytecode.is_empty() { + self.db.cache.contracts.entry(code_hash).or_insert_with(|| bytecode.clone()); + } let account_info = self.db.load_account(address).unwrap(); account_info.info.code = Some(bytecode); account_info.info.code_hash = code_hash; @@ -98,6 +191,33 @@ impl MemoryDatabase { self.set_account_storage(address, storage_key, value); self } + + /// Installs the seven predeploys as a chain that ran Rex6 holds them ([`rex6_predeploys`]), + /// the `SequencerRegistry` holding `roles` — an address names it in every role. Satin's + /// activation block finds what it checks, and a legacy call from the system address to a + /// whitelisted contract is a system-address transaction. + pub fn rex6_predeploys(self, roles: impl Into) -> Self { + rex6_predeploys(roles).into_iter().fold(self, Self::install) + } + + /// Installs the `SequencerRegistry` alone, as [`rex6_predeploys`](Self::rex6_predeploys) + /// does: a state whose system address a test names, without the other predeploys. + pub fn sequencer_registry(self, roles: impl Into) -> Self { + let registry = rex6_predeploys(roles) + .into_iter() + .find(|(address, ..)| *address == SEQUENCER_REGISTRY_ADDRESS) + .expect("the registry is a predeploy"); + self.install(registry) + } + + /// Installs `account` over whatever the database holds at its address. + fn install(mut self, (address, info, storage): PredeployAccount) -> Self { + self.db.insert_account_info(address, info); + for (slot, value) in storage { + self.set_account_storage(address, slot, value); + } + self + } } impl revm::Database for MemoryDatabase { @@ -146,12 +266,20 @@ pub struct ErrorInjectingDatabase { /// independently of `basic()` (mirrors a node missing a contract's code), to exercise the /// `load_code = true` inspect paths in isolation. pub fail_on_code_by_hash: Option, + /// When set, `block_hash()` calls for this block number return an error. + pub fail_on_block_hash: Option, } impl ErrorInjectingDatabase { /// Creates a new `ErrorInjectingDatabase` wrapping the given [`MemoryDatabase`]. pub fn new(inner: MemoryDatabase) -> Self { - Self { inner, fail_on_account: None, fail_on_storage: None, fail_on_code_by_hash: None } + Self { + inner, + fail_on_account: None, + fail_on_storage: None, + fail_on_code_by_hash: None, + fail_on_block_hash: None, + } } } @@ -184,6 +312,9 @@ impl revm::Database for ErrorInjectingDatabase { } fn block_hash(&mut self, number: u64) -> Result { + if self.fail_on_block_hash == Some(number) { + return Err(InjectedDbError(format!("injected block_hash() error for {number}"))); + } self.inner.block_hash(number).map_err(|e| match e {}) } } @@ -193,3 +324,35 @@ impl revm::DatabaseCommit for ErrorInjectingDatabase { self.inner.commit(changes); } } + +#[cfg(test)] +mod tests { + use alloy_primitives::{address, Bytes}; + use revm::Database; + + use super::*; + + #[test] + fn test_set_account_code_is_served_by_code_by_hash() { + let address = address!("00000000000000000000000000000000000000aa"); + let code = Bytes::from_static(&[0x00]); + let mut db = MemoryDatabase::default().account_balance(address, U256::from(5)); + db.set_account_code(address, code.clone()); + + let info = db.basic(address).unwrap().expect("the account is present"); + assert_eq!(info.balance, U256::from(5)); + let hash = info.code_hash; + assert_eq!(info.code.expect("code is stored on the account").original_bytes(), code); + assert_eq!(db.code_by_hash(hash).unwrap().original_bytes(), code); + } + + #[test] + fn test_block_hash_can_fail_for_one_number() { + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + let served = db.block_hash(1).unwrap(); + db.fail_on_block_hash = Some(7); + let err = db.block_hash(7).unwrap_err(); + assert!(err.to_string().contains("injected block_hash() error for 7"), "{err}"); + assert_eq!(db.block_hash(1).unwrap(), served); + } +} diff --git a/crates/mega-evm/src/test_utils/inspectors.rs b/crates/mega-evm/src/test_utils/inspectors.rs index b1e40a1df..a28e97560 100644 --- a/crates/mega-evm/src/test_utils/inspectors.rs +++ b/crates/mega-evm/src/test_utils/inspectors.rs @@ -1,6 +1,9 @@ #[cfg(not(feature = "std"))] use alloc as std; -use std::{rc::Rc, vec::Vec}; +use std::{ + rc::{Rc, Weak}, + vec::Vec, +}; use core::cell::RefCell; use revm::{ @@ -42,29 +45,6 @@ impl Pointer { } } -/// A path to a specific node in the trace tree. -/// -/// Each element represents the child index at that level of the tree. -/// For example, `vec![0, 2, 1]` means: first child -> third child -> second child. -pub type NodeLocation = Vec; - -/// A location of an item within a node's sections. -/// -/// `(section_index, item_index)` where sections are interleaved with child calls. -pub type ItemLocation = (usize, usize); - -/// A complete location representing a specific item in the trace tree. -/// -/// Combines a node location (path through call tree) with an item location -/// (position within that node's items). -#[derive(Debug)] -pub struct TraceLocation { - /// Path to the node containing the item. - pub call: NodeLocation, - /// Position of the item within the node. - pub item: ItemLocation, -} - /// A node in a hierarchical trace tree structure. /// /// This represents a call frame (either a message call or contract creation) and maintains @@ -86,8 +66,8 @@ pub struct TraceLocation { pub struct TraceNode { /// Metadata about this call (e.g., call inputs, creation inputs). pub meta: META, - /// Reference to the parent node, if any. - pub parent: Option>, + /// The parent node, if any. Weak, so a node and its parent do not keep each other alive. + pub parent: Option>>, /// Sections of items. There is always one more section than children. /// Sections are interleaved with children to maintain chronological order. pub sections: Vec>>, @@ -100,15 +80,24 @@ impl TraceNode { /// /// If a parent is provided, this node is automatically added as a child of the parent. pub fn new(meta: META, parent: Option>) -> Pointer { - let this: Pointer = - Self { meta, parent: parent.clone(), sections: vec![Vec::new()], childrens: vec![] } - .into(); + let this: Pointer = Self { + meta, + parent: parent.as_ref().map(|parent| Rc::downgrade(&parent.0)), + sections: vec![Vec::new()], + childrens: vec![], + } + .into(); if let Some(p) = parent { p.borrow_mut().add_child(this.clone()); } this } + /// The parent node, when it is still alive. + pub fn parent_node(&self) -> Option> { + self.parent.as_ref().and_then(Weak::upgrade).map(Pointer) + } + /// Returns the last item added to this node across all sections. pub fn last_item(&self) -> Option> { self.sections.iter().flatten().last().cloned() @@ -137,70 +126,17 @@ impl Pointer> { items.extend(self.borrow().sections[self.borrow().childrens.len()].iter().cloned()); items } - - /// Retrieves a node at the specified location in the tree. - /// - /// Returns `None` if the location is invalid (out of bounds). - pub fn get_node(&self, location: NodeLocation) -> Option { - if location.is_empty() { - Some(self.clone()) - } else { - self.borrow().childrens[location[0]].get_node(location[1..].to_vec()) - } - } - - /// Retrieves an item at the specified location within this node. - /// - /// Returns `None` if the location is invalid (out of bounds). - pub fn get_item(&self, location: ItemLocation) -> Option> { - self.borrow().sections.get(location.0).and_then(|section| section.get(location.1)).cloned() - } - - /// Retrieves an item using a complete trace location (node path + item position). - /// - /// Returns `None` if either the node location or item location is invalid. - pub fn get_item_nested(&self, location: TraceLocation) -> Option> { - self.get_node(location.call).and_then(|n| n.get_item(location.item)) - } - - /// Iterates over all items in the tree in chronological order. - /// - /// For each item, calls the provided function with: - /// - The node location (path to the node containing the item) - /// - The node itself - /// - The item location within the node - /// - The item - pub fn iterate_with(&self, mut f: F) - where - F: FnMut(NodeLocation, Self, ItemLocation, Pointer), - { - self.iterate_with_inner(&mut f, vec![]); - } - - /// Internal helper for recursive iteration maintaining the current node location. - fn iterate_with_inner(&self, f: &mut F, node_location: NodeLocation) - where - F: FnMut(NodeLocation, Self, ItemLocation, Pointer), - { - let sections = &self.borrow().sections; - for (section_idx, section) in sections.iter().enumerate() { - for (item_idx, item) in section.iter().enumerate() { - f(node_location.clone(), self.clone(), (section_idx, item_idx), item.clone()); - } - if section_idx < sections.len() - 1 { - let mut child_node_location = node_location.clone(); - child_node_location.push(section_idx); - self.borrow().childrens[section_idx].iterate_with_inner(f, child_node_location); - } - } - } } /// Represents gas information for a single opcode execution. #[derive(Clone)] pub struct OpcodeGasInfo { - /// The opcode executed. + /// The opcode executed. A byte no opcode is defined for, which halts the frame with + /// `OpcodeNotFound`, is recorded as `INVALID`; [`byte`](Self::byte) tells it from the + /// designated invalid opcode `0xFE`. pub opcode: OpCode, + /// The byte executed: the opcode's own, or the undefined byte the frame halted on. + pub byte: u8, /// Gas remaining before the opcode execution. pub gas_before: u64, /// Gas remaining after the opcode execution. @@ -211,10 +147,14 @@ pub struct OpcodeGasInfo { impl core::fmt::Debug for OpcodeGasInfo { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if self.is_undefined() { + write!(f, "UNDEFINED(0x{:02x})", self.byte)?; + } else { + f.write_str(self.opcode.as_str())?; + } write!( f, - "{}[depth={}] gas: {} -> {} (cost: {})", - self.opcode.as_str(), + "[depth={}] gas: {} -> {} (cost: {})", self.depth, self.gas_before, self.gas_after, @@ -228,6 +168,11 @@ impl OpcodeGasInfo { pub fn gas_cost(&self) -> u64 { self.gas_before.saturating_sub(self.gas_after) } + + /// Whether the byte executed is one no opcode is defined for. + pub fn is_undefined(&self) -> bool { + self.byte != self.opcode.get() + } } /// Metadata for a trace node representing either a call or create operation. @@ -254,12 +199,6 @@ impl GasInspector { Self::default() } - /// Clears all recorded gas information. - pub fn clear(&mut self) { - self.trace = None; - self.stack = vec![]; - } - /// Returns a flattened view of all opcode records in chronological order. /// This traverses the call tree and collects all opcodes in execution order. pub fn records(&self) -> Vec { @@ -320,7 +259,8 @@ impl Inspector for GasInspect let opcode = interp.bytecode.opcode(); let depth = context.journal().depth(); let step = OpcodeGasInfo { - opcode: OpCode::new(opcode).unwrap(), + opcode: OpCode::new(opcode).unwrap_or(OpCode::INVALID), + byte: opcode, gas_before, gas_after: gas_before, // Will be updated in step_end depth: depth as u64, @@ -331,13 +271,67 @@ impl Inspector for GasInspect } fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { - // Update the gas_after field with the actual gas remaining after execution - let current = self - .stack - .last() - .as_ref() - .and_then(|c| c.borrow_mut().last_item()) - .expect("current is not None"); + // A step that recorded nothing — an empty stack, or a frame with no item — has no gas to + // update. Recording starts in `step`, so a `step_end` that arrives without one is skipped. + let Some(current) = self.stack.last().and_then(|frame| frame.borrow().last_item()) else { + return; + }; current.borrow_mut().gas_after = interp.gas.remaining(); } } + +#[cfg(test)] +mod tests { + use revm::{ + context::Context, + interpreter::{CreateInputs, Interpreter}, + Inspector, MainContext, + }; + + use super::*; + + fn interpreter() -> Interpreter { + Interpreter::default_ext() + } + + #[test] + fn test_step_end_skips_a_missing_item() { + let mut inspector = GasInspector::new(); + let mut interp = interpreter(); + let mut context = Context::mainnet(); + Inspector::<_, _>::step_end(&mut inspector, &mut interp, &mut context); + + inspector.stack.push(TraceNode::new(MsgCallMeta::Create(CreateInputs::default()), None)); + Inspector::<_, _>::step_end(&mut inspector, &mut interp, &mut context); + assert!(inspector.records().is_empty()); + } + + #[test] + fn test_step_end_writes_the_gas_left_on_the_current_item() { + let mut inspector = GasInspector::new(); + let node = TraceNode::new(MsgCallMeta::Create(CreateInputs::default()), None); + node.borrow_mut().add_item(OpcodeGasInfo { + opcode: OpCode::STOP, + byte: OpCode::STOP.get(), + gas_before: 50, + gas_after: 50, + depth: 0, + }); + inspector.stack.push(node.clone()); + inspector.trace = Some(node); + let mut interp = interpreter(); + let mut context = Context::mainnet(); + Inspector::<_, _>::step_end(&mut inspector, &mut interp, &mut context); + assert_eq!(inspector.records()[0].gas_after, interp.gas.remaining()); + assert_eq!(inspector.records()[0].gas_before, 50); + } + + #[test] + fn test_a_trace_parent_drops_with_the_parent() { + let parent = TraceNode::<(), u8>::new(1, None); + let child = TraceNode::<(), u8>::new(2, Some(parent.clone())); + assert_eq!(child.borrow().parent_node().expect("the parent is alive").borrow().meta, 1); + drop(parent); + assert!(child.borrow().parent_node().is_none()); + } +} diff --git a/crates/mega-evm/src/test_utils/logs.rs b/crates/mega-evm/src/test_utils/logs.rs new file mode 100644 index 000000000..640d69327 --- /dev/null +++ b/crates/mega-evm/src/test_utils/logs.rs @@ -0,0 +1,51 @@ +//! The EIP-7708 transfer log revm journals for a value movement, as a test expects it. + +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec; + +use alloy_primitives::{Address, Bytes, Log, LogData, U256}; +use revm::primitives::eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}; + +/// The EIP-7708 transfer log of `value` wei moving from `from` to `to`: a `LOG3` from the +/// system address `0xff…fe`, carrying ERC-20's `Transfer` event with the two accounts as its +/// topics and the amount as its one word of data. +pub fn transfer_log(from: Address, to: Address, value: U256) -> Log { + Log { + address: ETH_TRANSFER_LOG_ADDRESS, + data: LogData::new_unchecked( + vec![ETH_TRANSFER_LOG_TOPIC, from.into_word(), to.into_word()], + Bytes::copy_from_slice(&value.to_be_bytes::<32>()), + ), + } +} + +/// Whether `log` is an EIP-7708 transfer log, rather than one a contract emitted. +pub fn is_transfer_log(log: &Log) -> bool { + log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics().first() == Some(Ð_TRANSFER_LOG_TOPIC) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::TRANSFER_LOG_SIZE; + use alloy_primitives::address; + + /// The expected log is a `LOG3` of one word, which is what the data size counts it at. + #[test] + fn test_a_transfer_log_is_a_log3_of_one_word() { + let log = transfer_log( + address!("0000000000000000000000000000000000000001"), + address!("0000000000000000000000000000000000000002"), + U256::from(7), + ); + assert!(is_transfer_log(&log)); + assert_eq!(log.topics().len(), 3); + assert_eq!(log.data.data.len(), 32); + assert_eq!( + 32 + 32 * log.topics().len() as u64 + log.data.data.len() as u64, + TRANSFER_LOG_SIZE + ); + assert_eq!(U256::from_be_slice(&log.data.data), U256::from(7)); + } +} diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index cd9b7c74e..f3f3de534 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -4,12 +4,20 @@ mod bytes; mod database; mod evm; mod inspectors; +mod logs; +mod neutral; mod opcode_gen; +mod price_guard; mod scenario; +mod witness; pub use bytes::*; pub use database::*; pub use evm::*; pub use inspectors::*; +pub use logs::*; +pub use neutral::*; pub use opcode_gen::*; +pub use price_guard::*; pub use scenario::*; +pub use witness::*; diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs new file mode 100644 index 000000000..2306bee31 --- /dev/null +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -0,0 +1,292 @@ +//! The neutral configuration: an Ethereum fork's own pricing on Satin's machinery. +//! +//! The execution-spec gate runs Ethereum's fixtures through `MegaEvm` with every dimension of +//! pricing only `MegaETH` has turned off, so that a fixture fails on what the machinery does and +//! not on what `MegaETH` charges for. [`MegaContext::with_neutral_cfg`] is the switch; this module +//! builds what it is switched to for a fixture fork: the fork's gas schedule, its EIP switches, +//! its execution cap and code-size limits ([`neutral_cfg`]); and the two parts of its pricing the +//! EVM carries rather than the context ([`neutralize_evm`]): its precompile set +//! ([`neutral_precompiles`]) and its static opcode prices ([`neutral_gas_table`]). +//! +//! The resource limits `MegaETH` sets are not part of the configuration: they live on the EVM's +//! common execution layer, and the gate's runner installs +//! [`EvmTxRuntimeLimits::no_limits`](crate::EvmTxRuntimeLimits::no_limits) in equivalence mode, +//! under which the data-size limit binds at neither the transaction nor a frame, and gas +//! detention's caps are unlimited, so no transaction is detained. A limit added later is unlimited +//! there as long as `no_limits` leaves it unlimited, which the limit module's own test pins field +//! by field. +//! +//! Every Satin transaction reads the live system address when it is validated, under the neutral +//! configuration too, which leaves the `SequencerRegistry`'s account and one slot in its returned +//! state, read-only: an engine that makes no such read returns no such entry, and a comparison +//! with one takes it out first ([`take_system_address_read`]). A commit skips an account nothing +//! touched, so the entry parts no committed state. +//! +//! Satin's base spec is Osaka, and a configuration cannot take a rule the base spec gates on its +//! own id away or add one: an Osaka rule stays on under an older fork's fixtures, and an +//! Amsterdam rule gated on the spec id stays off under Amsterdam's. So only Osaka and the fork +//! after it have a neutral configuration; what Amsterdam's cannot express is the gate's to +//! register, not this module's to hide. + +use alloy_evm::{precompiles::PrecompilesMap, Database}; +use revm::{ + context::CfgEnv, + context_interface::cfg::GasParams, + handler::EvmTr, + interpreter::instructions::{gas_table_spec, GasTable}, + precompile::{PrecompileSpecId, Precompiles}, + primitives::eip7954, + state::{Account, EvmState}, +}; + +use crate::{ + system::{storage_slots::CURRENT_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS}, + EthSpecId, ExternalEnvTypes, MegaEvm, MegaSpecId, +}; + +/// The configuration `fork`'s fixtures run under on Satin's machinery, or `None` for a fork +/// Satin's Osaka base cannot be configured to. +/// +/// The fields [`MegaContext::with_cfg`](crate::MegaContext::with_cfg) fixes from the spec are +/// the fork's here, as the fixtures' reference runner has them (revm's +/// `CfgEnv::set_spec_and_mainnet_gas_params`): +/// +/// - **Osaka**: Osaka's schedule; EIP-8037, EIP-2780 and EIP-7708 off; EIP-7825's execution cap and +/// the EIP-170 / EIP-3860 code-size limits, which revm derives from the base spec when the +/// configuration names none. +/// - **Amsterdam**: Amsterdam's schedule; EIP-8037 and EIP-2780 on; EIP-7708 on, which revm +/// otherwise keys on the spec id; EIP-7825's execution cap; the EIP-7954 code-size limits, set +/// explicitly for the same reason. +/// +/// On both, a system call's whole gas limit is regular gas, as revm's runner has it: the switch +/// that makes the part above 30,000,000 a state-gas reservoir, which Satin sets, is off. Under +/// Osaka it would do nothing, EIP-8037 being off. Under Amsterdam upstream revm splits no system +/// call's gas, and no state fixture makes a system call, so neither release the gate runs can +/// tell the two apart. +/// +/// Every other field is revm's default: chain id 1, which a caller replaces with the fixture's. +pub fn neutral_cfg(fork: EthSpecId) -> Option> { + let amsterdam = match fork { + EthSpecId::OSAKA => false, + EthSpecId::AMSTERDAM => true, + _ => return None, + }; + let mut cfg = + CfgEnv::new_with_spec_and_gas_params(MegaSpecId::SATIN, GasParams::new_spec(fork)); + cfg.enable_amsterdam_eip8037 = amsterdam; + cfg.enable_amsterdam_eip2780 = amsterdam; + cfg.enable_amsterdam_eip7708 = amsterdam; + cfg.tx_gas_limit_cap = None; + cfg.system_call_state_gas_margin_in_reservoir = false; + if amsterdam { + cfg.limit_contract_code_size = Some(eip7954::MAX_CODE_SIZE); + cfg.limit_contract_initcode_size = Some(eip7954::MAX_INITCODE_SIZE); + } else { + cfg.limit_contract_code_size = None; + cfg.limit_contract_initcode_size = None; + } + Some(cfg) +} + +/// `fork`'s own precompile set — Ethereum's, not op-revm's Karst set with `MegaETH`'s KZG price +/// — as the map a [`MegaEvm`](crate::MegaEvm) carries, or `None` where [`neutral_cfg`] has none. +pub fn neutral_precompiles(fork: EthSpecId) -> Option { + neutral_cfg(fork)?; + Some(PrecompilesMap::from_static(Precompiles::new(PrecompileSpecId::from_spec_id(fork)))) +} + +/// `fork`'s static opcode prices, or `None` where [`neutral_cfg`] has none. +/// +/// revm keeps part of a fork's gas table out of the schedule: the static price every opcode pays +/// before its dynamic cost lives in the instruction table, keyed on the spec id. Amsterdam's +/// differs from Osaka's in EIP-8038's two-read base for `EXTCODESIZE` and `EXTCODECOPY`; Satin's +/// instruction table carries Amsterdam's. +pub fn neutral_gas_table(fork: EthSpecId) -> Option { + neutral_cfg(fork)?; + Some(gas_table_spec(fork)) +} + +/// Gives `evm` the parts of `fork`'s pricing an EVM carries: its precompile set and its static +/// opcode prices. The instructions stay Satin's. Returns `None`, changing nothing, where +/// [`neutral_cfg`] has no configuration for `fork`. +/// +/// The neutral configuration of the context is +/// [`MegaContext::with_neutral_cfg`](crate::MegaContext::with_neutral_cfg)'s. +pub fn neutralize_evm( + evm: &mut MegaEvm, + fork: EthSpecId, +) -> Option<()> { + let (precompiles, gas_table) = (neutral_precompiles(fork)?, neutral_gas_table(fork)?); + evm.replace_precompile_set(precompiles); + let (_, instructions, _, _) = evm.all_mut(); + *instructions.gas_table_mut() = gas_table; + Some(()) +} + +/// Takes out of a Satin transaction's returned `state` the entry its validation's read of the live +/// system address left, and answers it: the `SequencerRegistry`'s account and its +/// `_currentSystemAddress` slot, loaded and never written. What is left is what an engine that +/// makes no such read returns for the same transaction, op-revm's or Ethereum's. +/// +/// # Panics +/// +/// When `state` holds no entry for the registry, or one that is more than the read: the account +/// touched, another slot loaded, or the slot changed. Each is a difference of its own, which a +/// comparison must not take out with the read. +pub fn take_system_address_read(state: &mut EvmState) -> Account { + let registry = + state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("every transaction reads the registry"); + assert!(!registry.is_touched(), "the registry was written, not only read: {registry:?}"); + assert!( + registry.storage.keys().eq([&CURRENT_SYSTEM_ADDRESS]), + "the registry holds more than the system address's slot: {registry:?}" + ); + assert!(!registry.storage[&CURRENT_SYSTEM_ADDRESS].is_changed(), "the slot was written"); + registry +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{satin_gas_params, satin_precompiles, MegaContext}; + use revm::{ + context::{Cfg, ContextTr}, + database::EmptyDB, + precompile::kzg_point_evaluation, + primitives::{eip170, eip3860, eip7825}, + }; + use std::collections::BTreeSet; + + fn context(fork: EthSpecId) -> MegaContext { + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + } + + /// What revm's own runner configures a fork's fixtures with, on the Ethereum spec. + fn reference(fork: EthSpecId) -> CfgEnv { + let mut cfg = CfgEnv::new(); + cfg.set_spec_and_mainnet_gas_params(fork); + cfg + } + + /// Osaka's configuration on the Karst base resolves every limit to what revm's runner + /// resolves on Osaka. + #[test] + fn test_neutral_osaka_resolves_like_revm_on_osaka() { + let ctx = context(EthSpecId::OSAKA); + let (cfg, osaka) = (ctx.cfg(), reference(EthSpecId::OSAKA)); + assert_eq!(cfg.gas_params.table(), osaka.gas_params.table()); + assert!(!cfg.is_amsterdam_eip8037_enabled()); + assert!(!cfg.is_amsterdam_eip2780_enabled()); + assert!(!cfg.enable_amsterdam_eip7708); + assert_eq!(cfg.tx_gas_limit_cap(), eip7825::TX_GAS_LIMIT_CAP); + assert_eq!(cfg.tx_gas_limit_cap(), osaka.tx_gas_limit_cap()); + assert_eq!(cfg.max_code_size(), eip170::MAX_CODE_SIZE); + assert_eq!(cfg.max_initcode_size(), eip3860::MAX_INITCODE_SIZE); + assert_eq!(cfg.max_code_size(), osaka.max_code_size()); + assert_eq!(cfg.max_initcode_size(), osaka.max_initcode_size()); + assert!(!cfg.system_call_state_gas_margin_in_reservoir()); + assert!(!osaka.system_call_state_gas_margin_in_reservoir()); + } + + /// Amsterdam's configuration carries what revm's runner derives from the Amsterdam spec id, + /// set explicitly because the Karst base does not derive it. + #[test] + fn test_neutral_amsterdam_resolves_like_revm_on_amsterdam() { + let ctx = context(EthSpecId::AMSTERDAM); + let (cfg, amsterdam) = (ctx.cfg(), reference(EthSpecId::AMSTERDAM)); + assert_eq!(cfg.gas_params.table(), amsterdam.gas_params.table()); + assert!(cfg.is_amsterdam_eip8037_enabled() && amsterdam.is_amsterdam_eip8037_enabled()); + assert!(cfg.is_amsterdam_eip2780_enabled() && amsterdam.is_amsterdam_eip2780_enabled()); + assert!(cfg.enable_amsterdam_eip7708); + assert_eq!(cfg.tx_gas_limit_cap(), amsterdam.tx_gas_limit_cap()); + assert_eq!(cfg.max_code_size(), amsterdam.max_code_size()); + assert_eq!(cfg.max_initcode_size(), amsterdam.max_initcode_size()); + assert_eq!(cfg.max_code_size(), eip7954::MAX_CODE_SIZE); + assert!(!cfg.system_call_state_gas_margin_in_reservoir()); + assert!(!amsterdam.system_call_state_gas_margin_in_reservoir()); + } + + /// Neither configuration is Satin's, and both run Satin's spec. + #[test] + fn test_neutral_configurations_are_not_satin_s() { + for fork in [EthSpecId::OSAKA, EthSpecId::AMSTERDAM] { + let ctx = context(fork); + assert_eq!(ctx.spec(), MegaSpecId::SATIN); + assert!(ctx.is_neutral()); + assert_ne!(ctx.cfg().gas_params.table(), satin_gas_params().table()); + assert_ne!(ctx.cfg().tx_gas_limit_cap, Some(crate::constants::TX_GAS_LIMIT_CAP)); + } + } + + /// A fork before Osaka, or one Satin does not know, has no neutral configuration: the Osaka + /// base cannot be configured back to it. + #[test] + fn test_only_osaka_and_amsterdam_are_neutral_forks() { + for fork in [EthSpecId::FRONTIER, EthSpecId::CANCUN, EthSpecId::PRAGUE] { + assert!(neutral_cfg(fork).is_none(), "{fork:?}"); + assert!(neutral_precompiles(fork).is_none(), "{fork:?}"); + } + } + + /// The fork's precompile set is Ethereum's: the same addresses as the Satin set, with KZG + /// point evaluation at upstream's 50,000 rather than `MegaETH`'s price. + #[test] + fn test_neutral_precompiles_are_ethereum_s() { + let addresses = |p: &Precompiles| p.addresses().copied().collect::>(); + // Garbage input of the right length: upstream prices it before it fails to verify. + let input = [0u8; 192]; + for fork in [EthSpecId::OSAKA, EthSpecId::AMSTERDAM] { + let map = neutral_precompiles(fork).expect("a neutral fork"); + assert_eq!( + map.addresses().copied().collect::>(), + addresses(Precompiles::osaka()) + ); + assert_eq!(addresses(satin_precompiles()), addresses(Precompiles::osaka())); + + let out_of_gas = |set: &Precompiles| { + let output = set + .get(&kzg_point_evaluation::ADDRESS) + .expect("KZG point evaluation") + .execute(&input, 60_000, 0) + .expect("no fatal error"); + output.status.halt_reason().is_some_and(|halt| halt.is_oog()) + }; + assert!(!out_of_gas(Precompiles::osaka()), "upstream's price fits in 60,000"); + assert!(out_of_gas(satin_precompiles()), "MegaETH's does not"); + } + } + + /// Satin's instruction table prices opcodes as Amsterdam does, so Amsterdam's static prices + /// change nothing; Osaka's differ in EIP-8038's two-read base for `EXTCODESIZE` and + /// `EXTCODECOPY` alone, which the neutral configuration puts back for an Osaka fixture. + #[test] + fn test_neutral_gas_tables() { + use revm::bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}; + let mut evm = MegaEvm::new(context(EthSpecId::AMSTERDAM)); + let satin = *evm.all_mut().1.gas_table(); + assert_eq!(neutral_gas_table(EthSpecId::AMSTERDAM), Some(satin)); + + let osaka = neutral_gas_table(EthSpecId::OSAKA).expect("a neutral fork"); + let changed: Vec<_> = + (0..=u8::MAX).filter(|&op| osaka[op as usize] != satin[op as usize]).collect(); + assert_eq!(changed, vec![EXTCODESIZE, EXTCODECOPY]); + assert_eq!(osaka[EXTCODESIZE as usize], 100); + assert_eq!(satin[EXTCODESIZE as usize], 200); + assert!(neutral_gas_table(EthSpecId::PRAGUE).is_none()); + } + + /// `neutralize_evm` installs the fork's static prices, and changes nothing for a fork + /// without a neutral configuration. That it installs the precompile set is shown by a call + /// (`tests/satin/neutral.rs`). + #[test] + fn test_neutralize_evm_installs_the_fork_s_static_prices() { + use revm::bytecode::opcode::EXTCODESIZE; + let mut evm = MegaEvm::new(context(EthSpecId::OSAKA)); + assert!(neutralize_evm(&mut evm, EthSpecId::PRAGUE).is_none()); + assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 200); + + assert!(neutralize_evm(&mut evm, EthSpecId::OSAKA).is_some()); + assert_eq!(evm.all_mut().1.gas_table()[EXTCODESIZE as usize], 100); + } +} diff --git a/crates/mega-evm/src/test_utils/opcode_gen.rs b/crates/mega-evm/src/test_utils/opcode_gen.rs index a5dca8e55..0b288cf31 100644 --- a/crates/mega-evm/src/test_utils/opcode_gen.rs +++ b/crates/mega-evm/src/test_utils/opcode_gen.rs @@ -6,7 +6,8 @@ use std::vec::Vec; use alloy_primitives::{Address, Bytes, U256}; use revm::bytecode::opcode::{ - DUP1, EQ, INVALID, JUMPDEST, JUMPI, MSTORE, PUSH0, RETURN, REVERT, SSTORE, STOP, + CALL, CALLCODE, CREATE, CREATE2, DUP1, EQ, GAS, INVALID, JUMPDEST, JUMPI, LOG3, MSTORE, PUSH0, + RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SSTORE, STOP, }; use crate::test_utils::right_pad_bytes; @@ -141,6 +142,7 @@ impl BytecodeBuilder { /// /// This snippet will left the stack unchanged after execution. pub fn assert_stack_value(mut self, stack_position: usize, value: U256) -> Self { + assert!(stack_position < 16, "stack position {stack_position} is past DUP16"); self = self .append(DUP1 + stack_position as u8) // duplicate the value at the given stack position to check .push_u256(value) @@ -156,14 +158,89 @@ impl BytecodeBuilder { self = self.append(STOP); self } + + /// Append a `CALL` to `target` carrying `value` wei with all the gas left, no calldata and no + /// return area, leaving the success flag on the stack. + pub fn call(self, target: Address, value: U256) -> Self { + self.call_by(CALL, target, value) + } + + /// Append a `CALLCODE` of `target`'s code carrying `value` wei with all the gas left, no + /// calldata and no return area, leaving the success flag on the stack. + pub fn callcode(self, target: Address, value: U256) -> Self { + self.call_by(CALLCODE, target, value) + } + + fn call_by(self, opcode: u8, target: Address, value: U256) -> Self { + self.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_u256(value) + .push_address(target) + .append(GAS) + .append(opcode) + } + + /// Append a `CREATE` of `init_code`, stored at memory offset 0, endowing the account it + /// creates with `value` wei, and leaving its address — zero when the creation failed. + pub fn create(self, value: U256, init_code: impl AsRef<[u8]>) -> Self { + let len = init_code.as_ref().len() as u64; + self.mstore(0, init_code) + .push_number(len) + .push_number(0_u64) + .push_u256(value) + .append(CREATE) + } + + /// Append a `CREATE2` of `init_code` with `salt`, as [`create`](Self::create) does. + pub fn create2(self, value: U256, init_code: impl AsRef<[u8]>, salt: U256) -> Self { + let len = init_code.as_ref().len() as u64; + self.mstore(0, init_code) + .push_u256(salt) + .push_number(len) + .push_number(0_u64) + .push_u256(value) + .append(CREATE2) + } + + /// Append a `SELFDESTRUCT` to `beneficiary`. + pub fn selfdestruct(self, beneficiary: Address) -> Self { + self.push_address(beneficiary).append(SELFDESTRUCT) + } + + /// Append a `LOG3` of one word of memory: the shape of an EIP-7708 transfer log, and what the + /// data size counts one at. + pub fn log3_word(self) -> Self { + self.append_many([PUSH0, PUSH0, PUSH0]).push_number(32_u8).append_many([PUSH0, LOG3]) + } + + /// Append a copy of the last call's return data to memory offset 0 and a `RETURN` of it. + pub fn return_returndata(self) -> Self { + self.copy_returndata().append_many([RETURNDATASIZE, PUSH0, RETURN]) + } + + /// Append a copy of the last call's return data to memory offset 0 and a `REVERT` with it. + pub fn revert_with_returndata(self) -> Self { + self.copy_returndata().append_many([RETURNDATASIZE, PUSH0, REVERT]) + } + + fn copy_returndata(self) -> Self { + self.append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + } + + /// Append a `RETURN` of the word on top of the stack, stored at memory offset 0. + pub fn return_top(self) -> Self { + self.append_many([PUSH0, MSTORE]).push_number(32_u8).append_many([PUSH0, RETURN]) + } } #[cfg(test)] mod tests { use core::convert::Infallible; - use alloy_primitives::address; - use revm::context::result::{EVMError, ResultAndState}; + use alloy_primitives::{address, B256}; + use revm::{ + bytecode::opcode::POP, + context::result::{EVMError, ResultAndState}, + }; use crate::{ test_utils::{transact, MemoryDatabase}, @@ -199,6 +276,57 @@ mod tests { assert!(result.unwrap().result.is_success(), "Transaction should succeed"); } + /// The value helpers move what they say: a call, a `CALLCODE`, the two creations' endowments + /// and a destruction's balance, each leaving its transfer log in order; the return helpers + /// return the top word and the last call's return data. + #[test] + fn test_the_value_helpers_move_value() { + use crate::test_utils::transfer_log; + let caller = address!("0000000000000000000000000000000000100000"); + let contract = address!("0000000000000000000000000000000000100001"); + let receiver = address!("0000000000000000000000000000000000100002"); + let one = U256::from(1); + let code = BytecodeBuilder::default() + .call(receiver, one) + .callcode(receiver, one) + .create(one, []) + .create2(one, [], U256::ZERO) + .append_many([POP, POP, POP, POP]) + .selfdestruct(receiver) + .build(); + let mut db = MemoryDatabase::default().account_balance(contract, U256::from(100)); + db.set_account_code(contract, code); + let result = transact( + MegaSpecId::SATIN, + &mut db, + caller, + Some(contract), + Bytes::new(), + U256::ZERO, + 10_000_000, + ) + .unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + let nonce = result.state[&contract].info.nonce - 2; + let created = contract.create(nonce); + let created2 = contract.create2(B256::ZERO, alloy_primitives::keccak256([])); + assert_eq!( + result.result.logs(), + [ + transfer_log(contract, receiver, one), + transfer_log(contract, created, one), + transfer_log(contract, created2, one), + transfer_log(contract, receiver, U256::from(97)), + ], + "the call's, the two endowments' and the destruction's; the `CALLCODE` moves nothing", + ); + assert_eq!(result.state[&receiver].info.balance, U256::from(98)); + + let top = BytecodeBuilder::default().push_number(42_u8).return_top().build(); + let output = execute_bytecode(top).unwrap().result.into_output().unwrap(); + assert_eq!(U256::from_be_slice(&output), U256::from(42)); + } + #[test] fn test_assert_stack_value_failure() { let mut builder = BytecodeBuilder::default().push_number(0x2333u64); @@ -207,4 +335,16 @@ mod tests { let result = execute_bytecode(bytecode); assert!(result.unwrap().result.is_halt(), "Transaction should fail"); } + + #[test] + fn test_assert_stack_value_reaches_the_sixteenth_slot() { + let code = BytecodeBuilder::default().assert_stack_value(15, U256::ZERO).build(); + assert_eq!(code[0], DUP1 + 15); + } + + #[test] + #[should_panic(expected = "stack position 16 is past DUP16")] + fn test_assert_stack_value_rejects_a_position_past_dup16() { + let _ = BytecodeBuilder::default().assert_stack_value(16, U256::ZERO); + } } diff --git a/crates/mega-evm/src/test_utils/price_guard.rs b/crates/mega-evm/src/test_utils/price_guard.rs new file mode 100644 index 000000000..5eed4b57b --- /dev/null +++ b/crates/mega-evm/src/test_utils/price_guard.rs @@ -0,0 +1,61 @@ +//! The notes a test leaves when the byte prices in effect leave it something it does not run. + +/// The variable naming the file [`note_price_guard`] and [`note_snapshot_skipped`] append their +/// notes to. The byte-price grid sets it for each point and counts the lines, so a point at which +/// tests returned early is told from one at which they ran, and both from one at which tests ran +/// whole and only left their snapshots uncompared. +pub const PRICE_GUARD_LOG_ENV_VAR: &str = "MEGA_PRICE_GUARD_LOG"; + +/// The reason [`note_snapshot_skipped`] notes. The byte-price grid counts the lines that start +/// with it apart from the price guards'. +pub const SNAPSHOT_SKIPPED: &str = "snapshot comparison skipped"; + +/// Notes that the running test took a price guard: it returned early, or left out the cases the +/// byte prices in effect leave nothing to run for, because of `reason`. +/// +/// The first note of a reason goes to stderr, written straight to it: the harness captures the +/// print macros of a test that passes, so a line written with them would never be read. Every +/// test and reason is appended once, as `: `, to the file +/// [`PRICE_GUARD_LOG_ENV_VAR`] names, when it names one; a file of its own, since a line written +/// into the harness's output can land inside a test's result line. +#[cfg(feature = "std")] +pub fn note_price_guard(reason: &str) { + note(reason, &format!("some tests return early, because {reason}")); +} + +/// Notes that the running test skipped a snapshot comparison, as [`note_price_guard`] notes a +/// guard, under the reason [`SNAPSHOT_SKIPPED`]. +/// +/// It is not a price guard: snapshots are pinned at the spec's byte prices, so at other prices a +/// test leaves its snapshot uncompared and runs every assertion it makes, as it does at the +/// spec's prices. +#[cfg(feature = "std")] +pub fn note_snapshot_skipped() { + note( + SNAPSHOT_SKIPPED, + "some snapshot comparisons are skipped, because snapshots are pinned at the spec's byte \ + prices; the tests run every assertion", + ); +} + +/// Writes `first` to stderr the first time `reason` is noted, and `: ` to the log +/// once per test and reason. +#[cfg(feature = "std")] +fn note(reason: &str, first: &str) { + use std::{collections::BTreeSet, io::Write, sync::Mutex}; + + static NOTED: Mutex> = Mutex::new(BTreeSet::new()); + let test = std::thread::current().name().unwrap_or("").to_owned(); + let mut noted = NOTED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if !noted.iter().any(|(_, noted_reason)| noted_reason == reason) { + let _ = writeln!(std::io::stderr(), "note: {first}"); + } + if !noted.insert((test.clone(), reason.to_owned())) { + return; + } + let Some(path) = std::env::var_os(PRICE_GUARD_LOG_ENV_VAR) else { return }; + // One appending write per line, so the test threads' lines do not interleave. + if let Ok(mut log) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = log.write_all(format!("{reason}: {test}\n").as_bytes()); + } +} diff --git a/crates/mega-evm/src/test_utils/scenario.rs b/crates/mega-evm/src/test_utils/scenario.rs index 0aeb64f67..1d9fb7d66 100644 --- a/crates/mega-evm/src/test_utils/scenario.rs +++ b/crates/mega-evm/src/test_utils/scenario.rs @@ -12,6 +12,9 @@ //! - the configuration is what [`MegaContext`] fixes for the spec; //! - the L1 fees are zero ([`zero_fee_l1_block_info`], [`op_transaction`]), and the gas price is //! the transaction's own (zero unless it sets one). +//! +//! A scenario is one block: its transactions run in order on one EVM ([`Scenario::evm`]), each +//! committed before the next, as a block executor runs a block. #[cfg(not(feature = "std"))] use alloc as std; @@ -30,6 +33,7 @@ use revm::{ }, BlockEnv, TxEnv, }, + inspector::NoOpInspector, state::{AccountInfo, Bytecode}, Database, DatabaseCommit, }; @@ -239,19 +243,30 @@ impl Scenario { } } - /// Runs every transaction on a fresh [`MegaEvm`] over `db`, committing the state of each - /// successful one before the next. Returns the outcomes in order and the final database. + /// The [`MegaEvm`] the scenario runs on, over `db`: the scenario's block, the spec's + /// configuration and zero L1 fees. + /// + /// A scenario is one block, and a block executor builds one EVM for a block and runs every + /// transaction on it, so this is built once per scenario, not per transaction. + pub fn evm(&self, db: MemoryDatabase) -> MegaEvm { + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_block(self.block()) + .with_chain(zero_fee_l1_block_info()); + MegaEvm::new(ctx) + } + + /// Runs every transaction on `evm`, committing the state of each successful one to its + /// database before the next, as a block executor runs a block. Returns the outcomes in order. /// /// # Panics /// /// If the scenario does not [`validate`](Self::validate). - pub fn run(&self, mut db: MemoryDatabase) -> (Vec, MemoryDatabase) { + pub fn run_on( + &self, + evm: &mut MegaEvm, + ) -> Vec { let mut outcomes = Vec::with_capacity(self.txs.len()); for tx in &self.txs { - let ctx = MegaContext::new(&mut db, MegaSpecId::SATIN) - .with_block(self.block()) - .with_chain(zero_fee_l1_block_info()); - let mut evm = MegaEvm::new(ctx); let outcome = match tx.kind { ScenarioTxKind::SystemCall => evm.transact_system_call( tx.caller, @@ -263,12 +278,24 @@ impl Scenario { evm.transact_raw(OpTx(op_transaction(tx.tx_env(nonce)))) } }; - drop(evm); if let Ok(outcome) = &outcome { - db.commit(outcome.state.clone()); + evm.db_mut().commit(outcome.state.clone()); } outcomes.push(outcome); } + outcomes + } + + /// Runs every transaction on one [`MegaEvm`] over `db` ([`evm`](Self::evm), + /// [`run_on`](Self::run_on)). Returns the outcomes in order and the final database. + /// + /// # Panics + /// + /// If the scenario does not [`validate`](Self::validate). + pub fn run(&self, db: MemoryDatabase) -> (Vec, MemoryDatabase) { + let mut evm = self.evm(db); + let outcomes = self.run_on(&mut evm); + let (db, _) = evm.finish(); (outcomes, db) } } @@ -358,6 +385,16 @@ mod tests { } } + /// Room for what the first transaction pays — its regular gas, its body's history, and its + /// new slot's state gas and record — at the prices the engine runs. + fn room_for_a_new_slot() -> u64 { + let slot = crate::satin_gas_params() + .get(revm::context_interface::cfg::GasId::sstore_set_state_gas()); + let history = crate::history_gas(crate::TX_BODY_SIZE + crate::WRITE_RECORD_SIZE) + .expect("the bytes have a price"); + 100_000 + slot + history + } + fn scenario(txs: Vec) -> Scenario { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(7)).stop().build(); Scenario { @@ -457,8 +494,8 @@ mod tests { /// current nonce. #[test] fn test_run_commits_each_transaction_before_the_next() { - // Room for the state gas the first transaction's new slot draws. - let scenario = scenario(vec![call(Some(200_000)), call(Some(200_000))]); + let scenario = + scenario(vec![call(Some(room_for_a_new_slot())), call(Some(room_for_a_new_slot()))]); let (outcomes, mut db) = scenario.run(scenario.database()); assert_eq!(outcomes.len(), 2); @@ -467,6 +504,60 @@ mod tests { assert_eq!(db.storage(CALLEE, U256::ZERO).unwrap(), U256::from(7)); } + /// The outcomes as a comparable value: the validation error type has no equality, so an error + /// compares by its rendering. + fn comparable( + outcomes: &[ScenarioTxOutcome], + ) -> Vec, String>> { + outcomes.iter().map(|o| o.as_ref().map_err(|e| format!("{e:?}"))).collect() + } + + /// `run` is `run_on` over the scenario's EVM, which carries the scenario's block and zero L1 + /// fees; the EVM goes on from what it committed, as the next transaction of a block does. + #[test] + fn test_run_is_run_on_the_scenario_s_evm() { + let scenario = scenario(vec![call(Some(room_for_a_new_slot()))]); + let mut evm = scenario.evm(scenario.database()); + assert_eq!(evm.block(), &scenario.block()); + assert_eq!(revm::context::ContextTr::chain(evm.ctx()), &zero_fee_l1_block_info()); + + let first = scenario.run_on(&mut evm); + assert_eq!(comparable(&first), comparable(&scenario.run(scenario.database()).0)); + let second = scenario.run_on(&mut evm); + assert!(second[0].as_ref().unwrap().result.is_success()); + assert_eq!(evm.db_mut().basic(CALLER).unwrap().unwrap().nonce, 2); + } + + /// One EVM for the whole scenario gives every bench scenario exactly what a fresh EVM per + /// transaction gives: the outcomes and the final state. The engine resets what one + /// transaction leaves behind before the next, which is what a block executor relies on. + #[test] + fn test_one_evm_per_scenario_is_one_evm_per_transaction() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("benches/scenarios"); + let mut ran = 0; + for entry in std::fs::read_dir(dir).unwrap() { + let text = std::fs::read_to_string(entry.unwrap().path()).unwrap(); + let scenario: Scenario = serde_json::from_str(&text).unwrap(); + scenario.validate().unwrap(); + + let mut db = scenario.database(); + let mut fresh = Vec::new(); + for tx in &scenario.txs { + let one = Scenario { txs: vec![tx.clone()], ..scenario.clone() }; + let mut evm = one.evm(db); + fresh.extend(one.run_on(&mut evm)); + db = evm.finish().0; + } + let (shared, mut shared_db) = scenario.run(scenario.database()); + assert_eq!(comparable(&shared), comparable(&fresh), "{}", scenario.name); + for address in scenario.pre.keys() { + assert_eq!(shared_db.basic(*address).unwrap(), db.basic(*address).unwrap()); + } + ran += 1; + } + assert!(ran >= 13, "the bench scenarios are all here"); + } + /// The database holds every field of every pre-state account. #[test] fn test_database_holds_the_pre_state() { diff --git a/crates/mega-evm/src/test_utils/witness.rs b/crates/mega-evm/src/test_utils/witness.rs new file mode 100644 index 000000000..cf1a54c11 --- /dev/null +++ b/crates/mega-evm/src/test_utils/witness.rs @@ -0,0 +1,702 @@ +//! A witness of what execution read, and the databases and environments that record one and +//! replay from one. +//! +//! A stateless validator re-executes a block from a witness: the accounts, slots, code and block +//! hashes the block read, as the chain held them, and the SALT bucket capacities its state charges +//! were priced with. [`WitnessRecord`] is that set, and a [`StrictDatabase`] and a +//! [`StrictEnvFactory`] serve it back and nothing else: a replay that asks for a key the record +//! does not hold fails with a [`WitnessError`], the way a validator's database fails on a missing +//! code or bucket, and the way it must not silently answer a missing account or slot. +//! +//! A record is built two ways, and the two are different checks. +//! +//! - **From the channels a node has**, with [`WitnessRecord::from_channels`]: the accounts and +//! slots the states the block committed name — each pre-block step's, read-only entries included, +//! and each included transaction's, as a node's commit hook receives them ([`CommittedStates`]) — +//! collected by [`WitnessKeys`] and resolved against the state the block ran on; the code the +//! chain holds for those accounts; the block hashes and buckets the engine exported; and the +//! oracle reads the included transactions recorded. That is the witness a node builds, and a +//! replay on it is the check a validator's witness must pass: a read the engine makes outside +//! every committed state and export is a key the record lacks, and the replay fails on it. The +//! code a committed state carries is not taken: it is what the transaction left the account with, +//! which for an account whose code the transaction replaced — an EIP-7702 authority delegated +//! anew — is not the code the engine loaded from the chain. +//! - **From every read the database served**, with a [`RecordingDatabase`] and the +//! [`RecordingEnvFactory`]'s environments around the block: what a recorder at the database level +//! sees. A replay on it shows the block reads nothing outside its database and environments and +//! computes the same block twice; it cannot show a read is missing from the channels, because the +//! recorder sees every read wherever it lands. +//! +//! The recording database serves code lazily, as a node's database does: an account comes back +//! without its bytecode, and the bytecode is served by hash on request. So every code the engine +//! needs travels through `code_by_hash`, and both records hold what a validator, which serves +//! code by hash, must be given. +//! +//! The oracle service is the one source a replay cannot take from the chain: the recording +//! environment keeps every answer the service gave, in order, the engine records each +//! transaction's own on its outcome, and the [`ReplayingOracleEnv`] answers the same reads the +//! same way — or answers nothing, as a validator without an oracle service does, to show what a +//! replay then depends on. + +#[cfg(not(feature = "std"))] +use alloc as std; +use core::{ + cell::{Cell, RefCell}, + marker::PhantomData, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + format, + rc::Rc, + string::{String, ToString}, + vec::Vec, +}; + +use alloy_primitives::{Address, BlockNumber, Bytes, B256, U256}; +#[cfg(feature = "std")] +use revm::database::State; +use revm::{ + database::DBErrorMarker, + primitives::{HashMap, StorageKey, StorageValue, KECCAK_EMPTY}, + state::{AccountInfo, Bytecode, EvmState}, + Database, DatabaseCommit, +}; + +use crate::{ + BucketId, ExternalEnvFactory, ExternalEnvTypes, ExternalEnvs, OracleEnv, OracleRead, + RecordedHint, SaltEnv, +}; + +/// What execution read outside the transactions and the header, as the sources answered it. +/// +/// An absent account is recorded as `None` and a zero slot as zero, so a replay that asks for +/// either is answered as the original run was, and one that asks for a key not here is refused. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WitnessRecord { + /// Every account asked for, with the answer: `None` for one the database does not hold. The + /// bytecode is not carried here; it is served by hash from [`codes`](Self::codes). + pub accounts: BTreeMap>, + /// Every slot asked for, with its value, zeroes included. + pub storage: BTreeMap<(Address, StorageKey), StorageValue>, + /// Every code asked for, by hash. + pub codes: BTreeMap, + /// Every block hash asked for, by number. + pub block_hashes: BTreeMap, + /// Every SALT bucket asked for, with the capacity the environment answered or the message it + /// failed with. + pub buckets: BTreeMap>, + /// Every read of the oracle service, in order: the slot and what the service answered. + pub oracle_reads: Vec, + /// Every hint the oracle service received, in order. + pub hints: Vec, +} + +/// The keys a node's witness builder collects from its channels: every account and slot the +/// states the block committed name, the pre-block steps' and the included transactions'. +/// +/// The keys are all it takes from a state. The values a state carries are what the block made of +/// them; the witness holds what the chain held before the block, which the builder resolves the +/// keys against ([`WitnessRecord::from_channels`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WitnessKeys { + /// Every account a state names. + pub accounts: BTreeSet
, + /// Every slot a state names, with its account. + pub slots: BTreeSet<(Address, StorageKey)>, +} + +impl WitnessKeys { + /// Adds every account and slot `state` names. + pub fn add_state(&mut self, state: &EvmState) { + for (address, account) in state { + self.accounts.insert(*address); + for key in account.storage.keys() { + self.slots.insert((*address, *key)); + } + } + } +} + +/// The states committed to a [`State`], in commit order, as a node's commit hook receives them. +/// +/// A node builds a block's witness from what the block commits: a hook on its [`State`] +/// ([`State::set_state_hook`]) is handed each state whole when it is committed, before the cache +/// drops the accounts the state did not touch, so it receives every pre-block step's state, +/// read-only entries included, and every committed transaction's. [`install`](Self::install) +/// installs such a hook and keeps what it receives. +#[cfg(feature = "std")] +#[derive(Clone, Debug, Default)] +pub struct CommittedStates(std::sync::Arc>>); + +#[cfg(feature = "std")] +impl CommittedStates { + /// Installs on `state` a hook that keeps every state committed to it from now on, in place of + /// the hook it had, and answers what the hook keeps. + pub fn install(state: &mut State) -> Self { + let committed = Self::default(); + let kept = committed.clone(); + state.set_state_hook(Some(std::boxed::Box::new(move |changes: &EvmState| { + kept.0.lock().expect("the committed states").push(changes.clone()); + }))); + committed + } + + /// The states committed so far, in commit order. + pub fn states(&self) -> Vec { + self.0.lock().expect("the committed states").clone() + } +} + +impl WitnessRecord { + /// The witness a node builds from its channels, resolved against `chain`, the state the block + /// ran on: every account `keys` names as the chain holds it, an absent one recorded as absent, + /// with the code the chain holds for it; every slot `keys` names of an account the chain + /// holds, zeroes included — the slots of an absent account are zero without a read, so none + /// is recorded; and the block hashes, the buckets and the included transactions' oracle reads + /// as given. Nothing else is in it: no code but the chain's for a named account, and no hint, + /// a validator having no service to hand one to. + /// + /// # Errors + /// + /// The chain's, when a read fails. + pub fn from_channels( + chain: &mut DB, + keys: &WitnessKeys, + block_hashes: BTreeMap, + buckets: BTreeMap>, + oracle_reads: Vec, + ) -> Result { + let mut record = Self { block_hashes, buckets, oracle_reads, ..Self::default() }; + for address in &keys.accounts { + let mut info = chain.basic(*address)?; + if let Some(info) = &mut info { + // The chain's code for the account: handed over with the account, or, by a chain + // that serves code by hash, on request. + let code = match info.code.take() { + Some(code) => code, + None if info.code_hash == KECCAK_EMPTY => Bytecode::default(), + None => chain.code_by_hash(info.code_hash)?, + }; + if !code.is_empty() { + record.codes.insert(info.code_hash, code); + } + } + record.accounts.insert(*address, info); + } + for (address, key) in &keys.slots { + if record.accounts.get(address).is_some_and(Option::is_some) { + let value = chain.storage(*address, *key)?; + record.storage.insert((*address, *key), value); + } + } + Ok(record) + } + + /// Whether every key `other` holds is in this record with the same answer: what a replay + /// read is what the original run read. + pub fn covers(&self, other: &Self) -> bool { + self.missing_from(other).is_empty() + } + + /// The keys `other` holds that this record does not hold with the same answer, described. + pub fn missing_from(&self, other: &Self) -> Vec { + let mut missing = Vec::new(); + for (address, info) in &other.accounts { + if self.accounts.get(address) != Some(info) { + missing.push(format!("account {address}")); + } + } + for ((address, key), value) in &other.storage { + if self.storage.get(&(*address, *key)) != Some(value) { + missing.push(format!("slot {key} of {address}")); + } + } + for (hash, code) in &other.codes { + if self.codes.get(hash) != Some(code) { + missing.push(format!("code {hash}")); + } + } + for (number, hash) in &other.block_hashes { + if self.block_hashes.get(number) != Some(hash) { + missing.push(format!("hash of block {number}")); + } + } + for (bucket, answer) in &other.buckets { + if self.buckets.get(bucket) != Some(answer) { + missing.push(format!("bucket {bucket}")); + } + } + missing + } +} + +/// A record several recorders write into. +pub type SharedWitnessRecord = Rc>; + +/// A witness that does not hold what execution asked for. +#[derive(Clone, Debug, PartialEq, Eq, derive_more::Display, derive_more::Error)] +pub enum WitnessError { + /// No account was recorded at this address. + #[display("the witness holds no account {_0}")] + Account(#[error(not(source))] Address), + /// No slot was recorded at this key of this address. + #[display("the witness holds no slot {_1} of {_0}")] + Slot(Address, StorageKey), + /// No code was recorded under this hash. + #[display("the witness holds no code {_0}")] + Code(#[error(not(source))] B256), + /// No hash was recorded for this block. + #[display("the witness holds no hash of block {_0}")] + BlockHash(#[error(not(source))] u64), + /// No capacity was recorded for this bucket. + #[display("the witness holds no bucket {_0}")] + Bucket(#[error(not(source))] BucketId), + /// The recorded lookup of this bucket failed, with this message. + #[display("the witness recorded bucket {_0} failing: {_1}")] + BucketFailed(BucketId, String), +} + +impl DBErrorMarker for WitnessError {} + +/// A database that records every read it serves, answering from the database it wraps. +/// +/// Code is served lazily: `basic` answers without the bytecode and keeps the bytecode the wrapped +/// database handed it with the account, and `code_by_hash` serves it from there, or from the +/// wrapped database for a hash it never saw. Every code the engine loads is then a recorded +/// `code_by_hash` read, as it is on a node whose database serves code by hash. +#[derive(Debug)] +pub struct RecordingDatabase { + inner: DB, + record: SharedWitnessRecord, + /// The bytecode the wrapped database handed out with its accounts, by hash. + codes: HashMap, +} + +impl RecordingDatabase { + /// Wraps `inner`, recording into `record`. + pub fn new(inner: DB, record: SharedWitnessRecord) -> Self { + Self { inner, record, codes: HashMap::default() } + } + + /// The wrapped database. + pub const fn inner(&self) -> &DB { + &self.inner + } + + /// The record this database writes into. + pub const fn record(&self) -> &SharedWitnessRecord { + &self.record + } +} + +impl Database for RecordingDatabase { + type Error = DB::Error; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + let info = self.inner.basic(address)?.map(|mut info| { + if let Some(code) = info.code.take() { + self.codes.insert(info.code_hash, code); + } + info + }); + self.record.borrow_mut().accounts.insert(address, info.clone()); + Ok(info) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + let code = match self.codes.get(&code_hash) { + Some(code) => code.clone(), + None => self.inner.code_by_hash(code_hash)?, + }; + self.record.borrow_mut().codes.insert(code_hash, code.clone()); + Ok(code) + } + + fn storage( + &mut self, + address: Address, + index: StorageKey, + ) -> Result { + let value = self.inner.storage(address, index)?; + self.record.borrow_mut().storage.insert((address, index), value); + Ok(value) + } + + fn block_hash(&mut self, number: u64) -> Result { + let hash = self.inner.block_hash(number)?; + self.record.borrow_mut().block_hashes.insert(number, hash); + Ok(hash) + } +} + +impl DatabaseCommit for RecordingDatabase { + fn commit(&mut self, changes: EvmState) { + self.inner.commit(changes); + } +} + +/// A database that serves exactly a recorded witness and refuses every other key. +/// +/// It is what a validator's database is, made strict: an account the record holds as absent is +/// answered `None` and a slot it holds as zero is answered zero, as recorded, and a key the record +/// does not hold at all is an error rather than an answer nobody recorded. +#[derive(Clone, Debug)] +pub struct StrictDatabase { + record: WitnessRecord, +} + +impl StrictDatabase { + /// A database serving `record`. + pub const fn new(record: WitnessRecord) -> Self { + Self { record } + } +} + +impl Database for StrictDatabase { + type Error = WitnessError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + self.record.accounts.get(&address).cloned().ok_or(WitnessError::Account(address)) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + self.record.codes.get(&code_hash).cloned().ok_or(WitnessError::Code(code_hash)) + } + + fn storage( + &mut self, + address: Address, + index: StorageKey, + ) -> Result { + self.record + .storage + .get(&(address, index)) + .copied() + .ok_or(WitnessError::Slot(address, index)) + } + + fn block_hash(&mut self, number: u64) -> Result { + self.record.block_hashes.get(&number).copied().ok_or(WitnessError::BlockHash(number)) + } +} + +/// A SALT environment that records every capacity it is asked for, answering from the +/// environment it wraps. +#[derive(Clone, Debug)] +pub struct RecordingSaltEnv { + inner: S, + record: SharedWitnessRecord, +} + +impl SaltEnv for RecordingSaltEnv { + type Error = S::Error; + + fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result { + let answer = self.inner.get_bucket_capacity(bucket_id); + let recorded = answer.as_ref().map(|capacity| *capacity).map_err(ToString::to_string); + self.record.borrow_mut().buckets.insert(bucket_id, recorded); + answer + } + + fn bucket_id_for_account(account: Address) -> BucketId { + S::bucket_id_for_account(account) + } + + fn bucket_id_for_slot(address: Address, key: U256) -> BucketId { + S::bucket_id_for_slot(address, key) + } +} + +/// An oracle environment that records every read and hint, answering from the environment it +/// wraps. +#[derive(Clone, Debug)] +pub struct RecordingOracleEnv { + inner: O, + record: SharedWitnessRecord, +} + +impl OracleEnv for RecordingOracleEnv { + fn get_oracle_storage(&self, slot: U256) -> Option { + let answer = self.inner.get_oracle_storage(slot); + self.record.borrow_mut().oracle_reads.push(OracleRead { slot, answer }); + answer + } + + fn on_hint(&self, from: Address, topic: B256, data: Bytes) { + self.record.borrow_mut().hints.push(RecordedHint { from, topic, data: data.clone() }); + self.inner.on_hint(from, topic, data); + } +} + +/// A factory whose environments record what they answer into one record. +#[derive(Clone, Debug)] +pub struct RecordingEnvFactory { + inner: F, + record: SharedWitnessRecord, +} + +impl RecordingEnvFactory { + /// Wraps `inner`, recording into `record`. + pub const fn new(inner: F, record: SharedWitnessRecord) -> Self { + Self { inner, record } + } +} + +impl ExternalEnvFactory for RecordingEnvFactory { + type EnvTypes = ( + RecordingSaltEnv<::SaltEnv>, + RecordingOracleEnv<::OracleEnv>, + ); + + fn external_envs(&self, block: BlockNumber) -> ExternalEnvs { + let ExternalEnvs { salt_env, oracle_env } = self.inner.external_envs(block); + ExternalEnvs { + salt_env: RecordingSaltEnv { inner: salt_env, record: self.record.clone() }, + oracle_env: RecordingOracleEnv { inner: oracle_env, record: self.record.clone() }, + } + } +} + +/// A SALT environment serving exactly the recorded buckets, with the hashing of `S`, and refusing +/// every other: what a validator's environment does with the bucket proofs it was given. +#[derive(Clone, Debug)] +pub struct StrictSaltEnv { + buckets: BTreeMap>, + hasher: PhantomData, +} + +impl SaltEnv for StrictSaltEnv { + type Error = WitnessError; + + fn get_bucket_capacity(&self, bucket_id: BucketId) -> Result { + match self.buckets.get(&bucket_id) { + Some(Ok(capacity)) => Ok(*capacity), + Some(Err(message)) => Err(WitnessError::BucketFailed(bucket_id, message.clone())), + None => Err(WitnessError::Bucket(bucket_id)), + } + } + + fn bucket_id_for_account(account: Address) -> BucketId { + S::bucket_id_for_account(account) + } + + fn bucket_id_for_slot(address: Address, key: U256) -> BucketId { + S::bucket_id_for_slot(address, key) + } +} + +/// An oracle service replaying recorded answers: the n-th read gets the n-th recorded answer when +/// it asks for the recorded slot, and `None` otherwise, which is noted as a mismatch. Hints are +/// taken and dropped, as a validator has no service to hand them to. +/// +/// [`absent`](Self::absent) is the service a validator without one runs: every read is answered +/// `None`, and none is a mismatch. +#[derive(Clone, Debug)] +pub struct ReplayingOracleEnv { + reads: Rc>, + next: Rc>, + mismatched: Rc>, + absent: bool, +} + +impl ReplayingOracleEnv { + /// A service replaying `reads` in order. + pub fn new(reads: Vec) -> Self { + Self { + reads: Rc::new(reads), + next: Rc::new(Cell::new(0)), + mismatched: Rc::new(Cell::new(false)), + absent: false, + } + } + + /// The service a validator without an oracle service runs: it answers nothing. + pub fn absent() -> Self { + Self { absent: true, ..Self::new(Vec::new()) } + } + + /// Whether every recorded read was replayed, in order, and none was answered out of order or + /// past the record. Always true for an absent service. + pub fn replayed_exactly(&self) -> bool { + self.absent || (!self.mismatched.get() && self.next.get() == self.reads.len()) + } +} + +impl OracleEnv for ReplayingOracleEnv { + fn get_oracle_storage(&self, slot: U256) -> Option { + if self.absent { + return None; + } + let index = self.next.get(); + self.next.set(index + 1); + match self.reads.get(index) { + Some(read) if read.slot == slot => read.answer, + _ => { + self.mismatched.set(true); + None + } + } + } +} + +/// A factory whose environments serve exactly a recorded witness: the buckets it holds and the +/// oracle answers it holds, in order, or an absent oracle service. +#[derive(Clone, Debug)] +pub struct StrictEnvFactory { + salt: StrictSaltEnv, + oracle: ReplayingOracleEnv, +} + +impl StrictEnvFactory { + /// Serves `record`'s buckets and replays its oracle answers. + pub fn replaying(record: &WitnessRecord) -> Self { + Self { + salt: StrictSaltEnv { buckets: record.buckets.clone(), hasher: PhantomData }, + oracle: ReplayingOracleEnv::new(record.oracle_reads.clone()), + } + } + + /// Serves `record`'s buckets with no oracle service, as today's validator runs. + pub fn without_oracle(record: &WitnessRecord) -> Self { + Self { + salt: StrictSaltEnv { buckets: record.buckets.clone(), hasher: PhantomData }, + oracle: ReplayingOracleEnv::absent(), + } + } + + /// The oracle service the environments share, to ask whether it replayed exactly. + pub const fn oracle(&self) -> &ReplayingOracleEnv { + &self.oracle + } +} + +impl ExternalEnvFactory for StrictEnvFactory { + type EnvTypes = (StrictSaltEnv, ReplayingOracleEnv); + + fn external_envs(&self, _block: BlockNumber) -> ExternalEnvs { + ExternalEnvs { salt_env: self.salt.clone(), oracle_env: self.oracle.clone() } + } +} + +#[cfg(test)] +mod tests { + use alloy_primitives::{address, keccak256}; + use revm::state::{Account, EvmStorageSlot, TransactionId}; + + use super::*; + use crate::test_utils::MemoryDatabase; + + /// An account the chain holds, with code and a slot. + const HELD: Address = address!("0x00000000000000000000000000000000000000a1"); + /// An account the chain holds, whose code the chain serves by hash alone. + const LAZY: Address = address!("0x00000000000000000000000000000000000000a2"); + /// An account the chain does not hold. + const ABSENT: Address = address!("0x00000000000000000000000000000000000000a3"); + /// An account the chain holds and no state names. + const UNNAMED: Address = address!("0x00000000000000000000000000000000000000a4"); + + /// The code the chain holds for [`HELD`], and the code a transaction left it with. + const CHAIN_CODE: [u8; 2] = [0x60, 0x00]; + const WRITTEN_CODE: [u8; 1] = [0x5f]; + /// The code the chain holds for [`LAZY`]. + const LAZY_CODE: [u8; 3] = [0x60, 0x01, 0x50]; + + /// A chain holding the three accounts: [`HELD`] with a slot, [`LAZY`] with its code behind + /// its hash, and [`UNNAMED`]. + fn chain() -> MemoryDatabase { + let mut chain = MemoryDatabase::default() + .account_code(HELD, Bytes::from_static(&CHAIN_CODE)) + .account_nonce(HELD, 3) + .account_storage(HELD, U256::from(1), U256::from(11)) + .account_lazy_code(LAZY, keccak256(LAZY_CODE)) + .account_code(UNNAMED, Bytes::from_static(&[0xfe])) + .account_storage(UNNAMED, U256::from(1), U256::from(77)); + chain.insert_contract(&mut AccountInfo { + code_hash: keccak256(LAZY_CODE), + code: Some(Bytecode::new_legacy(Bytes::from_static(&LAZY_CODE))), + ..Default::default() + }); + chain + } + + /// A returned state naming [`HELD`], as a transaction that replaced its code, bumped its + /// nonce, rewrote slot 1 and read the empty slot 2 left it; [`LAZY`], untouched; and + /// [`ABSENT`] with a slot. + fn state() -> EvmState { + let mut held = Account::default(); + held.info.nonce = 4; + held.info.code_hash = keccak256(WRITTEN_CODE); + held.info.code = Some(Bytecode::new_legacy(Bytes::from_static(&WRITTEN_CODE))); + let mut written = EvmStorageSlot::new(U256::from(11), TransactionId::ZERO); + written.present_value = U256::from(99); + held.storage.insert(U256::from(1), written); + held.storage.insert(U256::from(2), EvmStorageSlot::new(U256::ZERO, TransactionId::ZERO)); + + let mut absent = Account::new_not_existing(TransactionId::ZERO); + absent.storage.insert(U256::from(5), EvmStorageSlot::new(U256::ZERO, TransactionId::ZERO)); + + EvmState::from_iter([(HELD, held), (LAZY, Account::default()), (ABSENT, absent)]) + } + + /// The keys are every account and slot the states name, each once, and nothing a state + /// carries beside them. + #[test] + fn test_the_keys_are_the_accounts_and_slots_the_states_name() { + let mut keys = WitnessKeys::default(); + keys.add_state(&state()); + keys.add_state(&state()); + assert_eq!(keys.accounts, BTreeSet::from([HELD, LAZY, ABSENT])); + assert_eq!( + keys.slots, + BTreeSet::from([(HELD, U256::from(1)), (HELD, U256::from(2)), (ABSENT, U256::from(5))]) + ); + } + + /// The channel witness holds what the chain held for the keys, not what the states carry: + /// the chain's account, its code — served with the account or by hash — and its slots, + /// zeroes included; an absent account as absent, with no slot; nothing of an account no state + /// names; and the exports and oracle reads as given. + #[test] + fn test_the_channel_witness_holds_the_chains_values_for_the_named_keys() { + let mut keys = WitnessKeys::default(); + keys.add_state(&state()); + let block_hashes = BTreeMap::from([(7, B256::repeat_byte(7))]); + let buckets = BTreeMap::from([(9, Ok(512))]); + let reads = Vec::from([OracleRead { slot: U256::from(42), answer: Some(U256::from(1)) }]); + let Ok(record) = WitnessRecord::from_channels( + &mut chain(), + &keys, + block_hashes.clone(), + buckets.clone(), + reads.clone(), + ); + + assert_eq!(record.accounts.keys().copied().collect::>(), [HELD, LAZY, ABSENT]); + let held = record.accounts[&HELD].as_ref().expect("the chain holds it"); + assert_eq!(held.nonce, 3, "the chain's nonce, not the transaction's"); + assert_eq!(held.code_hash, keccak256(CHAIN_CODE), "the chain's code hash"); + assert!(held.code.is_none(), "code travels by hash"); + assert!(record.accounts[&ABSENT].is_none(), "an absent account is recorded absent"); + + assert_eq!( + record.codes.keys().copied().collect::>(), + BTreeSet::from([keccak256(CHAIN_CODE), keccak256(LAZY_CODE)]), + "the chain's code for the named accounts, and not the code a state carries" + ); + assert_eq!(record.codes[&keccak256(CHAIN_CODE)].original_byte_slice(), CHAIN_CODE); + assert_eq!(record.codes[&keccak256(LAZY_CODE)].original_byte_slice(), LAZY_CODE); + + assert_eq!( + record.storage, + BTreeMap::from([ + ((HELD, U256::from(1)), U256::from(11)), + ((HELD, U256::from(2)), U256::ZERO) + ]), + "the chain's values, a zero included, and no slot of an absent account" + ); + assert_eq!(record.block_hashes, block_hashes); + assert_eq!(record.buckets, buckets); + assert_eq!(record.oracle_reads, reads); + assert!(record.hints.is_empty()); + } +} diff --git a/crates/mega-evm/src/types.rs b/crates/mega-evm/src/types.rs index 636adb107..9232a88a3 100644 --- a/crates/mega-evm/src/types.rs +++ b/crates/mega-evm/src/types.rs @@ -3,9 +3,9 @@ //! These stay aliases of the OP types, because Satin adds nothing to them: //! //! - [`MegaTransaction`], [`MegaTxType`] and [`MegaTxEnvelope`]: Satin executes OP transactions. -//! - [`MegaHaltReason`]: Satin halts only where the EVM does. A resource limit stops a transaction -//! with a revert whose output is [`MegaLimitExceeded`](crate::MegaLimitExceeded), not with a -//! halt, so the halt set is op-revm's. +//! - [`MegaHaltReason`]: Satin halts only where the EVM does. A resource limit stops the frame that +//! crosses it with a revert whose output is [`MegaLimitExceeded`](crate::MegaLimitExceeded), not +//! with a halt, so the halt set is op-revm's. //! - [`MegaTransactionError`]: Satin validates transactions as op-revm does. //! //! What Satin does add has types of its own: the gas a transaction spent by ledger diff --git a/crates/mega-evm/tests/_pending/README.md b/crates/mega-evm/tests/_pending/README.md deleted file mode 100644 index 4c4ea6455..000000000 --- a/crates/mega-evm/tests/_pending/README.md +++ /dev/null @@ -1,293 +0,0 @@ -# Pending tests - -Tests of the legacy engine that survive into Satin but cannot run until the mechanism that owns them lands. -The dispositions come from the test inventory made for the engine rewrite and were applied mechanically when the Satin skeleton replaced the legacy core. -Every test the inventory marks `legacy-only` or `retired` was deleted; every other test is marked `keep`, `rewrite` or `undecided` and was moved here unchanged. -Decision ids (`Dnn`) index the Satin decision table, the numbered list of design decisions behind this engine; it is published with the engine's specification. - -## How this directory is excluded from the build - -Cargo discovers integration tests only as `tests/*.rs` and `tests/*/main.rs`. -`_pending/` has no `main.rs`, so nothing below it is compiled, formatted or linted. -Do not add a `_pending/main.rs`. - -## Rules for porting - -- Port the rows your mechanism owns into a real test target, adapting them to the Satin API and the decision cited in the table. -- `keep` rows keep their scenario and expectation; `rewrite` rows keep the scenario and take the new expectation from the cited decision; `undecided` rows wait for their decision. -- Delete a row from its file here in the same commit that ports it, and delete the file once it holds no rows. -- A row whose owning mechanism has landed and left it nothing to pin is retired rather than kept parked: it moves to "Tests retired after the inventory" with the reason, and its row is deleted from the file here in the same commit. -- The 44 legacy mutant killers the inventory kept (`tests/mutation/`) are not here: each was keyed to a surviving mutant of the legacy sources, and the test gates found no survivor in the Satin sources to regenerate one for. - A mechanism whose code leaves a survivor gets a new killer from the mutation gate, next to the code or as a system test under `tests/mutation/`; what the retired rows cited is kept in "Retired mutant killers" below. -- Files under `src/` are the inline unit-test modules of the legacy core, extracted when the Satin skeleton replaced `crates/mega-evm/src`. - The code they test is at `git show a8f8c7c9:crates/mega-evm/src/`. -- Helper functions and `main.rs` / `common.rs` harness files were moved as they were; the owner decides what to keep. - -## Tests per owning mechanism - -| Owning mechanism | Tests | From `tests/` | From `src/` | Keep | Rewrite | Undecided | -|---|---:|---:|---:|---:|---:|---:| -| the common execution layer | 21 | 21 | 0 | 21 | 0 | 0 | -| history gas | 28 | 24 | 4 | 4 | 24 | 0 | -| compute gas | 26 | 26 | 0 | 0 | 26 | 0 | -| the data-size limit | 47 | 45 | 2 | 40 | 7 | 0 | -| detention | 81 | 76 | 5 | 73 | 8 | 0 | -| the state-growth and KV limits | 56 | 55 | 1 | 0 | 35 | 21 | -| revert-class aborts | 17 | 17 | 0 | 0 | 17 | 0 | -| the pre-block system calls | 18 | 15 | 3 | 14 | 4 | 0 | -| system contract deployment | 67 | 17 | 50 | 62 | 5 | 0 | -| the oracle and control contracts | 77 | 77 | 0 | 67 | 10 | 0 | -| native keyless deployment | 75 | 73 | 2 | 29 | 46 | 0 | -| inspector support | 4 | 4 | 0 | 1 | 3 | 0 | -| — (undecided: D57 preload-warm cold charging, D58 98/100 forwarding) | 7 | 7 | 0 | 0 | 0 | 7 | -| **Total** | **524** | **457** | **67** | **311** | **185** | **28** | - -## Tests ported in place - -These rows came back with the code they test and run in `crates/mega-evm/src`, so the counts above are lower than the inventory's per-mechanism totals by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `src/evm/context.rs` | the Satin skeleton (3) | 3 | `src/evm/context.rs` | -| `src/evm/factory.rs` | the Satin skeleton (1) | 1 | `src/evm/factory.rs` | -| `src/evm/mod.rs` | the Satin skeleton (6) | 6 | `src/evm/mod.rs` | -| `src/evm/spec.rs` | the Satin skeleton (3) | 3 | `src/evm/spec.rs` | -| `src/external/hasher/mod.rs` | SALT pricing (5) | 5 | `src/external/hasher/mod.rs` | -| `src/external/mod.rs` | the Satin skeleton (1) | 1 | `src/external/mod.rs` | -| `src/external/test_utils.rs` | the Satin skeleton (1) | 1 | `src/external/test_utils.rs` | -| `src/sandbox/error.rs` | native keyless deployment (4) | 4 | `src/system/keyless/error.rs` | -| `src/sandbox/tx.rs` | native keyless deployment (10) | 10 | `src/system/keyless/tx.rs` | -| `src/test_utils/opcode_gen.rs` | the Satin skeleton (2) | 2 | `src/test_utils/opcode_gen.rs` | -| **Total** | | **36** | | - -## Retired mutant killers - -What the retired `tests/mutation/` rows cited, for the mechanisms that own them. - -| Owning mechanism | Tests | Disposition | Decision | -|---|---:|---|---| -| the Satin gas table | 2 | rewrite | D04 | -| the Satin gas table | 1 | rewrite | D11 | -| SALT pricing | 8 | keep | the test gates regenerate | -| compute gas | 1 | rewrite | D53 | -| the data-size limit | 2 | keep | 13,107,200 unchanged | -| detention | 6 | keep | the test gates regenerate | -| the state-growth and KV limits | 1 | undecided | D46 | -| the state-growth and KV limits | 1 | rewrite | D45 | -| the block executor | 17 | keep | the test gates regenerate | -| the block executor | 5 | rewrite | single spec / Satin schedule | - -## Tests parked under the common execution layer - -These 21 rows belong to the test gates in the inventory and pin canonical CREATE and CREATE2 behavior. -The test gates had turned them into scenarios of a differential harness against revm 43; that harness is maintained outside this repository now, so the rows are parked here again, owed to the common execution layer, and counted under it above. -6 of them also assert the halt reason of a creation in a static callee: those assertions already run in `tests/satin/static_callee.rs`, under the same test names, and a port of one of those rows carries the rest of its assertions. - -| Legacy file | Test | Static-callee halt reason | -|---|---|---| -| `rex4/create_safety.rs` | `test_create2_with_oversize_initcode_len_does_not_panic` | — | -| `rex5/create2_empty_initcode.rs` | `test_create2_len_zero_offset_zero_succeeds_on_both_specs` | — | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_nonzero_offset_max_still_halts` | — | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_large_offset_skips_memory_expansion` | — | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_max_succeeds` | — | -| `rex5/create2_empty_initcode.rs` | `test_rex5_create2_len_zero_offset_zero_succeeds` | — | -| `rex5/create2_resize_gas_metering.rs` | `test_create2_missing_salt_halts_consistently_across_specs` | — | -| `rex5/create2_resize_gas_metering.rs` | `test_rex5_create2_with_non_trivial_resize_succeeds` | — | -| `rex6/create2_metering_order.rs` | `test_create2_exact_boundary_initcode_length` | — | -| `rex6/create2_metering_order.rs` | `test_create2_missing_salt_consistent_rex5_rex6` | — | -| `rex6/create2_metering_order.rs` | `test_create2_moderately_oversized_initcode_same_reason_both_specs` | — | -| `rex6/create2_metering_order.rs` | `test_create2_oversized_initcode_halts_before_prework_rex6` | — | -| `rex6/create2_metering_order.rs` | `test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6` | — | -| `rex6/create2_metering_order.rs` | `test_create2_static_hugely_oversized_initcode_halt_reason` | `tests/satin/static_callee.rs` | -| `rex6/create2_metering_order.rs` | `test_create2_static_missing_operands_halt_reason` | `tests/satin/static_callee.rs` | -| `rex6/create2_metering_order.rs` | `test_create2_static_oversized_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | -| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_initcode_reports_static_rejection` | `tests/satin/static_callee.rs` | -| `rex6/create2_metering_order.rs` | `test_create2_static_zero_length_low_gas_halt_reason` | `tests/satin/static_callee.rs` | -| `rex6/create2_metering_order.rs` | `test_create_static_low_gas_halt_reason` | `tests/satin/static_callee.rs` | -| `rex6/error_paths.rs` | `test_rex6_create2_missing_length_stack_underflow` | — | -| `rex6/error_paths.rs` | `test_rex6_create2_missing_offset_stack_underflow` | — | - -## Tests ported by the common execution layer - -These 45 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `equivalence/evm_state.rs` | the common execution layer (3) | 3 | `tests/satin/state.rs` | -| `mini_rex/db_error.rs` | the common execution layer (4) | 4 | `tests/satin/db_error.rs` | -| `rex4/eip7702_delegation_cycle.rs` | the common execution layer (1) | 1 | `tests/satin/state.rs` | -| `rex5/call_too_deep_guard.rs` | the system contract interceptors (4) | 4 | `tests/satin/synthetic_frame_gas.rs` | -| `rex5/frame_target_updated_dedup.rs` | the common execution layer (5) | 5 | `tests/satin/write_records.rs` | -| `rex6/create_frame_accounting.rs` | the common execution layer (2) | 2 | `tests/satin/write_records.rs` | -| `rex6/self_transfer_account_dedup.rs` | the common execution layer (4) | 4 | `tests/satin/write_records.rs` | -| `src/evm/host.rs` | the common execution layer (10) | 10 | `src/evm/host.rs` | -| `src/evm/mod.rs` | the common execution layer (1) | 1 | `tests/satin/outcome.rs` | -| `src/evm/result.rs` | the common execution layer (4) | 4 | `src/evm/result.rs` | -| `src/limit/frame_limit.rs` | the common execution layer (4) | 4 | `src/limit/frame_limit.rs` | -| `src/limit/mod.rs` | the common execution layer (3) | 3 | `src/limit/mod.rs` | -| **Total** | | **45** | | - -## Tests ported by the Satin gas table - -These 34 rows run in a real test target now, adapted to the Satin API and to the schedule the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `compute_gas/claims.rs` | the Satin gas table (4) | 4 | `tests/satin/precompile_gas.rs`, `tests/satin/schedule.rs` | -| `mini_rex/contract_size_limit.rs` | the Satin gas table (12) | 12 | `tests/satin/contract_size.rs` | -| `mini_rex/gas.rs` | the Satin gas table (4) | 4 | `tests/satin/intrinsic.rs` | -| `rex5/gas_validation.rs` | the Satin gas table (4) | 4 | `tests/satin/intrinsic.rs` | -| `rex5/precompile_compute_gas.rs` | the Satin gas table (3) | 3 | `tests/satin/precompile_gas.rs` | -| `src/evm/factory.rs` | the Satin gas table (1) | 1 | `src/evm/factory.rs` | -| `src/evm/precompiles.rs` | the Satin gas table (6) | 6 | `src/evm/precompiles.rs` | -| **Total** | | **34** | | - -## Tests ported by the block executor - -These 53 rows run in a real test target now, adapted to the Satin API, so the counts above are lower than the inventory's by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `block_executor/accessed_block_hashes.rs` | the block executor (1) | 1 | `tests/block/block_hashes.rs` | -| `block_executor/block_limits.rs` | the block executor (12) | 12 | `tests/block/limits.rs` | -| `block_executor/canonical_schedule.rs` | the block executor (1) | 1 | `tests/block/schedule.rs` | -| `block_executor/deposit_da_exemption.rs` | the block executor (4) | 4 | `tests/block/limits.rs` | -| `block_executor/trait_factory_runtime_limits.rs` | the block executor (4) | 4 | `tests/block/factory.rs` | -| `rex6/sequencer_registry_rotation.rs` | the block executor (1) | 1 | `tests/block/schedule.rs` | -| `src/block/chain.rs` | the block executor (5) | 5 | `src/block/chain.rs` | -| `src/block/eips.rs` | the block executor (1) | 1 | `src/block/eips.rs` | -| `src/block/hardfork.rs` | the block executor (12) | 12 | `src/block/hardfork.rs` | -| `src/block/helpers.rs` | the block executor (3) | 3 | `src/block/helpers.rs` | -| `src/block/limit.rs` | the block executor (5) | 5 | `src/block/limit.rs` | -| `src/block/result.rs` | the block executor (2) | 2 | `src/block/result.rs` | -| `src/evm/mod.rs` | the block executor (1) | 1 | `src/evm/mod.rs` | -| `src/evm/state.rs` | the block executor (1) | 1 | `src/evm/state.rs` | -| **Total** | | **53** | | - -## Tests ported by SALT pricing - -These 67 rows run in a real test target now, adapted to the Satin API and to the pricing hook the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `mini_rex/gas.rs` | SALT pricing (20) | 20 | `tests/satin/salt.rs` | -| `rex/storage_gas.rs` | SALT pricing (15) | 15 | `tests/satin/salt.rs` | -| `rex4/eip7702_delegation_cycle.rs` | SALT pricing (8) | 8 | `tests/satin/salt_delegation.rs` | -| `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | `tests/satin/salt_delegation.rs` | -| `rex5/deposit_create_storage_gas.rs` | SALT pricing (4) | 4 | `tests/satin/salt_deposit.rs` | -| `rex5/eip7702_metering.rs` | SALT pricing (4) | 4 | `tests/satin/salt_delegation.rs` | -| `rex5/sstore_storage_gas_error.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | -| `rex6/create_frame_accounting.rs` | SALT pricing (1) | 1 | `tests/satin/salt_failure.rs` | -| `rex6/error_paths.rs` | SALT pricing (2) | 2 | `tests/satin/salt_failure.rs` | -| `rex6/system_tx_metering_exemption.rs` | SALT pricing (3) | 3 | `tests/block/salt.rs`, `tests/satin/salt.rs` | -| `src/evm/context.rs` | SALT pricing (1) | 1 | `src/evm/context.rs` | -| `src/external/gas.rs` | SALT pricing (5) | 5 | `src/external/gas.rs`, `tests/satin/salt.rs` | -| **Total** | | **67** | | - -## Tests ported by the system contract interceptors - -These 61 rows run in a real test target now, adapted to the Satin API and to the dispatch the decision they cite fixes, so the counts above are lower than the inventory's by exactly these rows. - -| Legacy file | Owner in the inventory | Tests | Now in | -|---|---|---:|---| -| `compute_gas/claims.rs` | the system contract interceptors (2) | 2 | `tests/system/dispatch.rs` | -| `mini_rex/mega_system_transaction.rs` | the system contract interceptors (15) | 15 | `src/system/tx.rs`, `tests/system/system_tx.rs` | -| `rex3/keyless_deploy.rs` | the system contract interceptors (2) | 2 | `tests/system/keyless.rs` | -| `rex4/limit_control.rs` | the system contract interceptors (5) | 5 | `tests/system/dispatch.rs`, `tests/system/limit_control.rs` | -| `rex5/db_error.rs` | the system contract interceptors (1) | 1 | `tests/system/dispatch.rs` | -| `rex5/deposit_caller_accounting.rs` | the system contract interceptors (7) | 7 | `tests/system/system_tx.rs` | -| `rex5/interceptor_selector_probe.rs` | the system contract interceptors (6) | 6 | `tests/system/dispatch.rs`, `tests/system/oracle.rs` | -| `rex5/keyless_deploy_dispatch_parity.rs` | the system contract interceptors (3) | 3 | `tests/system/keyless.rs` | -| `rex5/system_tx_replay.rs` | the system contract interceptors (12) | 12 | `tests/system/system_tx.rs` | -| `src/system/intercept.rs` | the system contract interceptors (2) | 2 | `tests/system/dispatch.rs`, `tests/system/limit_control.rs` | -| `src/system/tx.rs` | the system contract interceptors (6) | 6 | `src/system/tx.rs` | -| **Total** | | **61** | | - -## Tests retired after the inventory - -These 8 rows were parked when the inventory was applied and have since been retired: the mechanism that owns them landed and left them nothing to pin, so no later mechanism will port them. -They are not counted above. - -| Legacy file | Owner in the inventory | Tests | Why | -|---|---|---:|---| -| `rex5/callcode_storage_gas.rs` | SALT pricing (3) | 3 | Satin's `CALLCODE` cannot reach a state gas pricing site: it sends value to the frame's own account, which exists, so it adds no account leaf and asks for no price. There is no pricing-path account inspection left to fail | -| `src/evm/host.rs` | SALT pricing (1) | 1 | the pricing hook inspects no account: the fork decides whether a target exists and the hook only prices what it is told to, so there is no delegation walk on the pricing path to guard | -| `src/external/gas.rs` | SALT pricing (4) | 4 | these pin a helper at a legacy spec boundary: it is served from one rung and asserts below it. Satin is a single spec and has no gate of its own, so there is no boundary left for them to pin | -| **Total** | | **8** | | - -## Tests the inventory assigns to the Satin skeleton that are parked under another mechanism - -| File | Test | Parked under | Reason | -|---|---|---|---| - -## Files - -Each cell lists `disposition count (mechanism · decision)`. - -| File | Tests | Owners | -|---|---:|---| -| `block_executor/block_limits.rs` | 2 | undecided 2 (the state-growth and KV limits · D46) | -| `block_executor/inspector.rs` | 3 | keep 1 (inspector support); rewrite 2 (inspector support · D39/D41) | -| `block_executor/sequencer_registry.rs` | 8 | keep 8 (system contract deployment) | -| `compute_gas/claims.rs` | 8 | rewrite 2 (compute gas · D53 (compute = regular spent; state spill excluded)); undecided 5 (— · D57, open: whether preload-warm addresses (precompile / beneficiary / access-list) are charged cold); rewrite 1 (the data-size limit · D33/D48) | -| `compute_gas/main.rs` | 1 | rewrite 1 (compute gas · D53) | -| `mini_rex/access_beneficiary_balance.rs` | 10 | keep 9 (detention · D08); rewrite 1 (revert-class aborts · D48) | -| `mini_rex/block_env_access_tracking.rs` | 3 | keep 3 (detention) | -| `mini_rex/block_env_gas_limit.rs` | 16 | keep 13 (detention · D08 cap 20M/1M unchanged); rewrite 3 (revert-class aborts · D48 (detention halt -> revert-class)) | -| `mini_rex/compute_gas_limit.rs` | 25 | rewrite 23 (compute gas · D10/D40/D53 (compute derived from Gas; 200M cap)); rewrite 2 (detention · D48) | -| `mini_rex/gas.rs` | 2 | undecided 2 (— · D58, open: 98/100 forwarding, while the design has frames follow EIP-8037 (63/64)) | -| `mini_rex/oracle.rs` | 13 | rewrite 3 (revert-class aborts · D48); keep 5 (detention); keep 4 (the oracle and control contracts); rewrite 1 (system contract deployment · deploy at Satin activation) | -| `mini_rex/state_growth_limit.rs` | 4 | rewrite 4 (the state-growth and KV limits · D45 (state-gas limit)) | -| `mini_rex/tx_data_and_kv_update_limit.rs` | 28 | keep 18 (the data-size limit · data-size numbers unchanged); rewrite 4 (revert-class aborts · D48); undecided 6 (the state-growth and KV limits · D46 (the KV count stays as an output because the node consumes it; the limit semantics are undecided)) | -| `rex/oracle.rs` | 3 | rewrite 3 (detention · D08 (mark at actual load: same outcome via SLOAD)) | -| `rex2/keyless_deploy.rs` | 37 | rewrite 13 (native keyless deployment · native CREATE sub-frame; D37/D38); keep 19 (native keyless deployment · validation rules 1-9 unchanged); keep 1 (native keyless deployment · rule 4 (tx nonce == 0) unchanged); rewrite 3 (native keyless deployment · D36); rewrite 1 (system contract deployment · deploy at Satin activation) | -| `rex2/oracle_hint.rs` | 6 | keep 6 (the oracle and control contracts) | -| `rex3/oracle_gas_limit.rs` | 8 | keep 7 (detention · D08); rewrite 1 (revert-class aborts · D48) | -| `rex3/system_address.rs` | 2 | keep 2 (detention · D51) | -| `rex4/access_control.rs` | 48 | keep 46 (the oracle and control contracts); rewrite 2 (detention · D07 (rejected volatile read pays static gas)) | -| `rex4/beneficiary_detention.rs` | 13 | keep 12 (detention · D08); rewrite 1 (revert-class aborts · D48) | -| `rex4/create_safety.rs` | 1 | keep 1 (the common execution layer · canonical revm behaviour) | -| `rex4/deployment.rs` | 2 | rewrite 2 (system contract deployment · deploy at Satin activation) | -| `rex4/frame_limits.rs` | 20 | keep 10 (the data-size limit · data-size per-frame 98% kept); rewrite 1 (revert-class aborts · D48); undecided 9 (the state-growth and KV limits · D46) | -| `rex4/gas_detention.rs` | 5 | keep 3 (detention); rewrite 2 (revert-class aborts · D48/D53) | -| `rex4/intrinsic_limit_bypass.rs` | 13 | rewrite 6 (the data-size limit · D48/D49 (overflow outcome shape)); undecided 3 (the state-growth and KV limits · D46); keep 3 (the data-size limit); rewrite 1 (inspector support · D41) | -| `rex4/keyless_deploy.rs` | 2 | keep 2 (native keyless deployment · native sub-frame inherits env) | -| `rex4/limit_control.rs` | 9 | rewrite 9 (the oracle and control contracts · D40 (remaining compute derived from Gas)) | -| `rex4/storage_call_stipend.rs` | 12 | rewrite 12 (history gas · D14 (separated history-only allowance 160 x CPHB; three leak paths)) | -| `rex5/apply_pending_changes_gas_budget.rs` | 4 | rewrite 4 (the pre-block system calls · D51 (system source m = 1; the system-call reservoir split)) | -| `rex5/create2_empty_initcode.rs` | 5 | keep 5 (the common execution layer · canonical revm behaviour) | -| `rex5/create2_resize_gas_metering.rs` | 2 | keep 2 (the common execution layer · canonical behaviour) | -| `rex5/db_error.rs` | 3 | rewrite 3 (native keyless deployment · native path surfaces DB errors) | -| `rex5/eip7702_state_growth.rs` | 8 | rewrite 8 (the state-growth and KV limits · D28/D31/D45 (7702 authorization matrix)) | -| `rex5/keyless_empty_code_logs.rs` | 2 | rewrite 2 (native keyless deployment · native sub-frame keeps logs inherently) | -| `rex5/keyless_fee_free.rs` | 12 | rewrite 8 (native keyless deployment · D16/D37/D38 (GASPRICE native; materialisation explicit)); keep 4 (native keyless deployment · rules unchanged) | -| `rex5/keyless_gas_cap_postcap_recheck.rs` | 3 | rewrite 3 (native keyless deployment · native sub-frame gas handling) | -| `rex5/keyless_replay_barrier.rs` | 3 | rewrite 3 (native keyless deployment · D36 (real nonce increment)) | -| `rex5/oracle_hint_metering.rs` | 9 | keep 7 (the oracle and control contracts · D50 (hint not charged history; data-size metering kept)); rewrite 1 (the oracle and control contracts · D11 intrinsic number); rewrite 1 (revert-class aborts · D48) | -| `rex5/pre_block_system_calls.rs` | 11 | keep 11 (the pre-block system calls) | -| `rex5/sandbox_accounting.rs` | 9 | rewrite 9 (native keyless deployment · native sub-frame: parent tracker sees child directly) | -| `rex5/selfdestruct_beneficiary.rs` | 7 | rewrite 4 (the state-growth and KV limits · D45 (state gas via new-account site)); keep 2 (detention); keep 1 (the data-size limit) | -| `rex5/stipend_accounting.rs` | 6 | rewrite 6 (history gas · D14 (history-only allowance lifecycle)) | -| `rex6/beneficiary_detention.rs` | 16 | keep 13 (detention · D08); keep 2 (the data-size limit · D50 write record 40 B); rewrite 1 (the state-growth and KV limits · D45) | -| `rex6/create2_metering_order.rs` | 11 | keep 11 (the common execution layer · canonical halt reasons; D04 512 KiB boundary) | -| `rex6/eip7702_authority_accounting.rs` | 18 | rewrite 18 (the state-growth and KV limits · D12/D28/D31/D45 (7702 matrix; SALT pricing for the SALT half)) | -| `rex6/error_paths.rs` | 2 | keep 2 (the common execution layer · canonical) | -| `rex6/fee_reward_accounting.rs` | 6 | rewrite 6 (history gas · D50/D56 (tx body constant 310 = 110 + 40 x 5) / D45) | -| `rex6/frame_local_accounting.rs` | 3 | keep 3 (the data-size limit · LOG base 32 unchanged) | -| `rex6/keyless_sandbox_hardening.rs` | 3 | rewrite 1 (native keyless deployment · D44 / EIP-6780 native); keep 2 (native keyless deployment · canonical CREATE rules) | -| `rex6/oracle_hint_volatile_access.rs` | 4 | keep 4 (the oracle and control contracts) | -| `rex6/self_transfer_account_dedup.rs` | 1 | keep 1 (the data-size limit) | -| `rex6/sequencer_registry_rotation.rs` | 5 | keep 5 (system contract deployment) | -| `src/access/volatile.rs` | 4 | keep 4 (detention) | -| `src/evm/mod.rs` | 3 | keep 3 (the pre-block system calls) | -| `src/limit/compute_gas.rs` | 1 | rewrite 1 (detention · D40/D48) | -| `src/limit/data_size.rs` | 2 | keep 2 (the data-size limit) | -| `src/limit/kv_update.rs` | 1 | undecided 1 (the state-growth and KV limits · D46) | -| `src/limit/limit.rs` | 4 | keep 4 (history gas · D51) | -| `src/sandbox/execution.rs` | 2 | keep 1 (native keyless deployment · rule); rewrite 1 (native keyless deployment · D16) | -| `src/system/control.rs` | 8 | keep 8 (system contract deployment · the system contract interceptors for selector/revert-data tests) | -| `src/system/deploy.rs` | 4 | keep 3 (system contract deployment); rewrite 1 (system contract deployment · single version) | -| `src/system/keyless_deploy.rs` | 2 | keep 2 (system contract deployment) | -| `src/system/limit_control.rs` | 5 | keep 5 (system contract deployment) | -| `src/system/oracle.rs` | 7 | keep 7 (system contract deployment · v2.0.0 only) | -| `src/system/sequencer_registry.rs` | 24 | keep 24 (system contract deployment · the pre-block system calls for transact_apply_pending_changes) | diff --git a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs b/crates/mega-evm/tests/_pending/block_executor/block_limits.rs deleted file mode 100644 index 824d84eb1..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/block_limits.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! Tests for block-level limit enforcement in `MegaBlockExecutor`. -//! -//! These tests verify that the block executor properly enforces block-level data -//! and KV-update limits across multiple transactions within a block. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, Transaction, TxLegacy}; -use alloy_eips::eip2718::Encodable2718; -use alloy_evm::{block::BlockExecutor, Evm, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, EnrichedMegaTx, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, - MegaHardforkConfig, MegaSpecId, MegaTransactionExt, MegaTxEnvelope, TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{ADD, DUP1, LOG0, PUSH0, SLOAD, SSTORE}, - context::BlockEnv, - database::{Database, State}, -}; - -const CALLER: alloy_primitives::Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); - -/// Helper function to create a recovered transaction. -fn create_transaction( - nonce: u64, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), // Base mainnet - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Creates a contract that generates a log with specified data size. -/// -/// The contract will emit LOG0 with the specified number of zero bytes. -fn create_log_generating_contract(data_size: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - // Push data size - if data_size <= 0xFF { - builder = builder.push_number(data_size as u8); - } else if data_size <= 0xFFFF { - builder = builder.push_number(data_size as u16); - } else { - builder = builder.push_number(data_size as u32); - } - - // Push memory offset (0) - builder = builder.append(PUSH0); - - // LOG0(offset, size) - builder = builder.append(LOG0); - - // Stop - builder.stop().build() -} - -/// Creates a contract that performs N SSTORE operations. -/// -/// Each SSTORE loads from storage slot i, increments it, and stores it back. -fn create_sstore_contract(num_writes: usize) -> Bytes { - let mut builder = BytecodeBuilder::default(); - - for i in 1..=num_writes { - // Push key (slot number) for SLOAD - if i <= 0xFF { - builder = builder.push_number(i as u8); - } else if i <= 0xFFFF { - builder = builder.push_number(i as u16); - } else { - builder = builder.push_number(i as u32); - } - - // Duplicate key on stack for SSTORE later - // DUP1 duplicates the top stack item - builder = builder.append(DUP1); - - // SLOAD - load current value from slot - // Stack: [key, value] - builder = builder.append(SLOAD); - - // Push 1 to increment - // Stack: [key, value, 1] - builder = builder.push_number(1u8); - - // ADD - increment the loaded value - // Stack: [key, incremented_value] - builder = builder.append(ADD); - - // SSTORE - store incremented value back to slot - // Stack: [] - builder = builder.append(SSTORE); - } - - builder.stop().build() -} - -#[test] -fn test_block_custom_kv_update_limit() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_sstore_contract(50); // 50 storage writes - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with custom KV update limit - // Set limit to 1 to test the new behavior where the first transaction that - // exceeds the limit is allowed, but subsequent transactions are rejected - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_kv_update_limit(1), - ); // Very low limit - first tx will exceed it - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute first transaction (should succeed even though it will exceed the limit) - let result1 = executor.execute_transaction(&create_transaction(0, 10_000_000)); - assert!(result1.is_ok(), "First transaction should succeed (last tx can exceed limit)"); - - // Execute second transaction (should fail due to KV limit already exceeded) - let result2 = executor.execute_transaction(&create_transaction(1, 10_000_000)); - assert!(result2.is_err(), "Second transaction should fail due to block KV update limit"); - let err_msg = format!("{:?}", result2.unwrap_err()); - assert!( - err_msg.contains("KVUpdateLimit"), - "Error should mention KVUpdateLimit, got: {}", - err_msg - ); -} - -#[test] -fn test_block_kv_limit_exceeded_mid_block() { - // Create database and deploy contract with minimal SSTORE operations - let mut db = MemoryDatabase::default(); - let bytecode = create_sstore_contract(1); // Just 1 SSTORE - db.set_account_code(CONTRACT, bytecode); - // Fund the caller account - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - // Create state - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create EVM - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block context with limit of 1 KV update - // New behavior: The transaction that causes the block to exceed the limit is allowed, - // but the next transaction is rejected - // Each transaction induces 2 KV updates (sender account info and storage slot) - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - None, - Bytes::new(), - BlockLimits::no_limits().with_block_kv_update_limit(1), - ); // 1 KV update limit - first tx will exceed it - - // Create block executor with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec, receipt_builder); - - // Execute first transaction (should succeed with 2 KV updates, exceeding the limit) - let tx1 = create_transaction(0, 10_000_000); - let result1 = executor.execute_transaction(&tx1); - assert!(result1.is_ok(), "First transaction should succeed (last tx can exceed limit)"); - assert!(result1.unwrap() < tx1.gas_limit(), "Gas used should be less than gas limit"); - - // Execute second transaction (should fail due to KV limit already exceeded) - let tx2 = create_transaction(1, 10_000_000); - let result2 = executor.execute_transaction(&tx2); - assert!(result2.is_err(), "Second transaction should fail due to block KV update limit"); - - // Finish the block - should have 1 receipt - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt (2nd tx failed)"); -} - -const CALLER2: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); -const CALLER3: alloy_primitives::Address = address!("4000000000000000000000000000000000000004"); diff --git a/crates/mega-evm/tests/_pending/block_executor/inspector.rs b/crates/mega-evm/tests/_pending/block_executor/inspector.rs deleted file mode 100644 index 945bc6b72..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/inspector.rs +++ /dev/null @@ -1,424 +0,0 @@ -//! Tests for inspector integration with `MegaBlockExecutor`. -//! -//! These tests verify that inspectors work correctly when executing transactions -//! using `MegaBlockExecutor`. - -use std::{cell::Cell, convert::Infallible}; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, - MegaHardforkConfig, MegaSpecId, MegaTxEnvelope, TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{ADD, CALL, GAS, PUSH0, SLOAD, SSTORE}, - context::{BlockEnv, ContextTr, JournalTr}, - database::State, - interpreter::{ - CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, InstructionResult, - InterpreterResult, InterpreterTypes, - }, - Inspector, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); - -/// Helper function to create a recovered call transaction. -fn create_transaction( - nonce: u64, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), // Base mainnet - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(CONTRACT), - value: U256::ZERO, - input: Bytes::new(), - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Helper function to create a contract creation transaction. -fn create_deploy_transaction( - nonce: u64, - gas_limit: u64, - init_code: Bytes, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, CALLER) -} - -/// Creates a contract that performs SSTORE operations. -fn create_test_contract() -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // key (slot 0) - .append(SLOAD) // load value from slot 0 - .push_number(1u8) // push 1 to increment - .append(ADD) // add 1 to loaded value - .append(PUSH0) // key for SSTORE - .append(SSTORE) // store incremented value - .stop() - .build() -} - -#[test] -fn test_inspector_works_with_block_executor() { - // Create database and deploy contract - let mut db = MemoryDatabase::default(); - let bytecode = create_test_contract(); - db.set_account_code(CONTRACT, bytecode); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory and block executor factory with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create block context - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - - // Create inspector - let inspector = GasInspector::new(); - - // Create block executor with inspector - let mut executor = block_executor_factory - .create_executor_with_inspector(&mut state, block_ctx, evm_env, inspector); - - // Execute transaction - let tx = create_transaction(0, 1_000_000); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction should succeed: {:?}", result.err()); - - // Get inspector records via evm - let records = executor.evm().inspector.records(); - - // Verify that inspector recorded opcodes - assert!(!records.is_empty(), "Inspector should have recorded opcodes"); - - // Verify that we recorded the expected opcodes - let opcodes: Vec<_> = records.iter().map(|r| r.opcode.as_str()).collect(); - assert!(opcodes.contains(&"SLOAD"), "Should record SLOAD opcode"); - assert!(opcodes.contains(&"ADD"), "Should record ADD opcode"); - assert!(opcodes.contains(&"SSTORE"), "Should record SSTORE opcode"); - - // Verify that gas costs are being tracked - for record in &records { - assert!( - record.gas_before >= record.gas_after, - "Gas should decrease or stay the same after opcode execution" - ); - } - - // Finish the block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt"); -} - -/// An inspector that returns early for nested calls, skipping frame execution. -/// -/// This is used to test the fix for the additional limit frame stack maintenance bug. -/// When an inspector returns `Some(CallOutcome)` from its `call` hook, the `frame_init` -/// is skipped, but `frame_return_result` is still called. Without the fix, this would -/// cause a panic due to frame stack misalignment. -#[derive(Default)] -struct SkipNestedCallInspector { - /// Number of nested calls that were intercepted and skipped. - calls_intercepted: Cell, - /// Number of `call_end` hooks that were invoked. - call_ends: Cell, -} - -impl Inspector for SkipNestedCallInspector { - #[allow(clippy::if_then_some_else_none)] // if-else is clearer here - fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { - let depth = context.journal().depth(); - if depth > 0 { - // Return early for nested calls - this triggers the bug scenario where - // inspector skips `frame_init` but `frame_return_result` is still called - self.calls_intercepted.set(self.calls_intercepted.get() + 1); - Some(CallOutcome { - result: InterpreterResult { - result: InstructionResult::Stop, - output: Bytes::new(), - gas: Gas::new(inputs.gas_limit), - }, - memory_offset: 0..0, - }) - } else { - None - } - } - - fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.call_ends.set(self.call_ends.get() + 1); - } -} - -const CONTRACT_B: Address = address!("3000000000000000000000000000000000000003"); - -/// Creates a contract that makes a CALL to another contract. -fn create_caller_contract() -> Bytes { - // Contract that calls CONTRACT_B with 0 value, empty calldata - // PUSH1 0 - retSize - // PUSH1 0 - retOffset - // PUSH1 0 - argsSize - // PUSH1 0 - argsOffset - // PUSH1 0 - value - // PUSH20 addr - address - // GAS - gas - // CALL - // STOP - BytecodeBuilder::default() - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8) // value - .push_address(CONTRACT_B) // address - .append(GAS) // gas (use all available) - .append(CALL) - .stop() - .build() -} - -/// Creates a simple contract that just stops. -fn create_target_contract() -> Bytes { - BytecodeBuilder::default().stop().build() -} - -/// Test that inspector early return works correctly with additional limit tracking. -/// -/// This test validates the fix for the bug where inspector's call hook returning early -/// would cause frame stack misalignment in the additional limit trackers. -/// -/// Before the fix, this test would panic with "frame stack is empty" because: -/// 1. Inspector's call hook returns `Some(CallOutcome)` for the nested call -/// 2. `frame_init` is skipped (no frame pushed to additional limit trackers) -/// 3. `frame_return_result` is still called (tries to pop a frame that doesn't exist) -/// -/// After the fix, we push a dummy frame when inspector returns early, so the pop works. -#[test] -fn test_inspector_early_return_with_additional_limits() { - // Create database and deploy contracts - let mut db = MemoryDatabase::default(); - db.set_account_code(CONTRACT, create_caller_contract()); - db.set_account_code(CONTRACT_B, create_target_contract()); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory and block executor factory with MiniRex hardfork activated - // MiniRex enables the additional limit tracking that was affected by the bug - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create block context - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - - // Create inspector that skips nested calls - let inspector = SkipNestedCallInspector::default(); - - // Create block executor with inspector - let mut executor = block_executor_factory - .create_executor_with_inspector(&mut state, block_ctx, evm_env, inspector); - - // Execute transaction - this triggers a nested CALL that the inspector intercepts - let tx = create_transaction(0, 1_000_000); - - // Before the fix, this would panic with "frame stack is empty" - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction should succeed: {:?}", result.err()); - - // Verify the inspector intercepted the nested call - assert_eq!( - executor.evm().inspector.calls_intercepted.get(), - 1, - "Inspector should have intercepted 1 nested call" - ); - - // Verify call_end was still invoked (inspector hooks work correctly) - assert_eq!( - executor.evm().inspector.call_ends.get(), - 2, - "call_end should be invoked for both the main call and the intercepted nested call" - ); - - // Finish the block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt"); -} - -/// An inspector that returns early for create operations, skipping frame execution. -/// -/// Similar to `SkipNestedCallInspector` but for CREATE/CREATE2 operations. -#[derive(Default)] -struct SkipCreateInspector { - /// Number of create operations that were intercepted and skipped. - creates_intercepted: Cell, - /// Number of `create_end` hooks that were invoked. - create_ends: Cell, -} - -impl Inspector for SkipCreateInspector { - fn create(&mut self, _context: &mut CTX, inputs: &mut CreateInputs) -> Option { - // Always intercept create operations - this triggers the bug scenario - self.creates_intercepted.set(self.creates_intercepted.get() + 1); - Some(CreateOutcome { - result: InterpreterResult { - result: InstructionResult::Stop, - output: Bytes::new(), - gas: Gas::new(inputs.gas_limit), - }, - address: None, - }) - } - - fn create_end( - &mut self, - _context: &mut CTX, - _inputs: &CreateInputs, - _outcome: &mut CreateOutcome, - ) { - self.create_ends.set(self.create_ends.get() + 1); - } -} - -/// Test that inspector early return works correctly for CREATE operations. -/// -/// This test validates the fix for CREATE operations using a contract creation transaction. -#[test] -fn test_inspector_early_return_create_with_additional_limits() { - // Create database with funded caller - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory and block executor factory with MiniRex hardfork activated - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - // Create EVM environment - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create block context - let block_ctx = - MegaBlockExecutionCtx::new(B256::ZERO, None, Bytes::new(), BlockLimits::no_limits()); - - // Create inspector that skips create operations - let inspector = SkipCreateInspector::default(); - - // Create block executor with inspector - let mut executor = block_executor_factory - .create_executor_with_inspector(&mut state, block_ctx, evm_env, inspector); - - // Execute contract creation transaction - this triggers the CREATE that the inspector - // intercepts Init code is just STOP (0x00) - // Use higher gas limit to cover MiniRex initial gas costs for CREATE transactions - let init_code = Bytes::from(vec![0x00]); - let tx = create_deploy_transaction(0, 10_000_000, init_code); - - // Before the fix, this would panic with "frame stack is empty" - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "Transaction should succeed: {:?}", result.err()); - - // Verify the inspector intercepted the create operation - assert_eq!( - executor.evm().inspector.creates_intercepted.get(), - 1, - "Inspector should have intercepted 1 create operation" - ); - - // Verify create_end was still invoked (inspector hooks work correctly) - assert_eq!( - executor.evm().inspector.create_ends.get(), - 1, - "create_end should be invoked for the intercepted create" - ); - - // Finish the block - let block_result = executor.finish(); - assert!(block_result.is_ok(), "Block should finish successfully"); - - let (_, receipts) = block_result.unwrap(); - assert_eq!(receipts.receipts.len(), 1, "Should have 1 receipt"); -} diff --git a/crates/mega-evm/tests/_pending/block_executor/main.rs b/crates/mega-evm/tests/_pending/block_executor/main.rs deleted file mode 100644 index 693e3735f..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! Tests for block executor functionality. - -mod block_limits; -mod inspector; -mod sequencer_registry; diff --git a/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs b/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs deleted file mode 100644 index 9723b0c8b..000000000 --- a/crates/mega-evm/tests/_pending/block_executor/sequencer_registry.rs +++ /dev/null @@ -1,620 +0,0 @@ -//! End-to-end tests for `SequencerRegistry` and dynamic system address. -//! -//! These tests verify the full pipeline: `apply_pre_execution_changes()` deploys -//! `SequencerRegistry`, resolves system address, and then transaction execution -//! correctly uses the resolved system address for system tx identification. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_evm::{block::BlockExecutor, EvmEnv}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, IOracle, ISequencerRegistry, MegaBlockExecutionCtx, - MegaBlockExecutorFactory, MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, - MegaTxEnvelope, SequencerRegistryConfig, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, - SEQUENCER_REGISTRY_CODE_HASH, -}; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_ADMIN, PENDING_SEQUENCER, - PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, -}; -use revm::{ - context::BlockEnv, - database::State, - handler::EvmTr, - state::{AccountInfo, Bytecode}, -}; - -const NEW_SYSTEM_ADDRESS: Address = address!("3000000000000000000000000000000000000003"); -const BOOTSTRAP_SEQUENCER: Address = address!("0x4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("0x5000000000000000000000000000000000000005"); -const NEW_ADMIN: Address = address!("0x6000000000000000000000000000000000000006"); - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -fn create_evm_env() -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX5; - cfg_env.chain_id = 8453; - let block_env = BlockEnv { - number: U256::from(1000), - timestamp: U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn create_tx_from( - sender: Address, - nonce: u64, - target: Address, - data: Bytes, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 0, - gas_limit: 1_000_000_000, - to: TxKind::Call(target), - value: U256::ZERO, - input: data, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, sender) -} - -/// Like [`create_tx_from`] but with an explicit `gas_limit`. System-address senders bypass -/// block gas-limit validation, so existing tests can use the very-large 1B figure; -/// regular-EOA tests must respect the block gas limit (30M in `create_evm_env`). -fn create_tx_from_with_gas_limit( - sender: Address, - nonce: u64, - target: Address, - data: Bytes, - gas_limit: u64, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(8453), - nonce, - gas_price: 0, - gas_limit, - to: TxKind::Call(target), - value: U256::ZERO, - input: data, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - let tx = MegaTxEnvelope::Legacy(signed); - alloy_consensus::transaction::Recovered::new_unchecked(tx, sender) -} - -/// After `apply_pre_execution_changes()`, the context's `system_address` should be -/// `MEGA_SYSTEM_ADDRESS` because `SequencerRegistry` is deployed at genesis with the -/// initial system address hardcoded to that constant. -#[test] -fn test_bootstrap_block_resolves_system_address() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let system_address = executor.evm().ctx_ref().system_address(); - assert_eq!( - system_address, MEGA_SYSTEM_ADDRESS, - "Bootstrap block should resolve system_address to MEGA_SYSTEM_ADDRESS \ - (the genesis-hardcoded initial system address)" - ); -} - -/// A system transaction from the resolved `system_address` to Oracle should succeed. -#[test] -fn test_system_tx_uses_resolved_system_address() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let calldata = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - let tx = create_tx_from(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, Bytes::from(calldata)); - - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "System tx should succeed: {:?}", result.err()); -} - -/// Pre-populate a pending system address change, run `apply_pre_execution_changes()`, -/// verify `system_address` switches to the new address, and confirm the old address is rejected. -#[test] -fn test_system_address_change() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(NEW_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - // Pre-deploy SequencerRegistry with seeded storage + pending system address change - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - // Seed current system address - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - // Seed pending change: new system address at block 1000 - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - NEW_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - // Block 1000 — change should be applied - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - // 1. Verify system_address switched - let system_address = executor.evm().ctx_ref().system_address(); - assert_eq!(system_address, NEW_SYSTEM_ADDRESS, "system_address should switch after change"); - - // 2. New system address can send system tx to Oracle - let calldata = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - let tx = create_tx_from(NEW_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, Bytes::from(calldata)); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "System tx from new system address should succeed: {:?}", result.err()); - - // 3. Old system address is rejected (not recognized as system tx → validation fails) - let calldata = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - let tx = create_tx_from(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, Bytes::from(calldata)); - let result = executor.execute_transaction(&tx); - assert!(result.is_err(), "Tx from old system address should fail after change"); -} - -/// Sequencer change does NOT affect `system_address`. -#[test] -fn test_sequencer_change_does_not_affect_system_address() { - let new_sequencer = address!("4000000000000000000000000000000000000004"); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - // Pre-deploy with seeded storage + pending sequencer change - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - // Pending sequencer change at block 1000 - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - // system_address should NOT change — only the sequencer changed - let system_address = executor.evm().ctx_ref().system_address(); - assert_eq!( - system_address, MEGA_SYSTEM_ADDRESS, - "Sequencer change should not affect system_address" - ); - - // System tx from the original system address should still work - let calldata = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - let tx = create_tx_from(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, Bytes::from(calldata)); - let result = executor.execute_transaction(&tx); - assert!( - result.is_ok(), - "System tx from original system address should still work after sequencer change" - ); -} - -/// Both system address and sequencer change in the same block. -/// Verify `system_address` switches to the new system address (not the new sequencer). -#[test] -fn test_dual_change_in_same_block() { - let new_sequencer = address!("4000000000000000000000000000000000000004"); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(NEW_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - // Seed current values - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - // Pending system address change at block 1000 - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - NEW_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - // Pending sequencer change at block 1000 (same block) - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - // system_address should be the NEW system address, not the new sequencer - let system_address = executor.evm().ctx_ref().system_address(); - assert_eq!( - system_address, NEW_SYSTEM_ADDRESS, - "Dual change: system_address should be NEW_SYSTEM_ADDRESS" - ); - - // New system address can send system tx - let calldata = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); - let tx = create_tx_from(NEW_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, Bytes::from(calldata)); - let result = executor.execute_transaction(&tx); - assert!(result.is_ok(), "New system address should work after dual change"); -} - -/// Pending change exists but activation block is in the future — no-op. -#[test] -fn test_pending_not_yet_due_is_noop() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - // Pending at block 9999 — our test block is 1000 - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - NEW_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(9999), - ) - .unwrap(); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - // system_address should still be the original — change not yet due - let system_address = executor.evm().ctx_ref().system_address(); - assert_eq!( - system_address, MEGA_SYSTEM_ADDRESS, - "Pending not-yet-due change should not change system_address" - ); -} - -/// Rex5 activated but `SequencerRegistryConfig` not configured — `apply_pre_execution_changes` must -/// fail. -#[test] -fn test_missing_sequencer_sequencer_registry_config_errors() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - // Activate Rex5 but deliberately omit .with_params(SequencerRegistryConfig { ... }). - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - let err = executor - .apply_pre_execution_changes() - .expect_err("Rex5 without SequencerRegistryConfig must fail"); - assert!( - err.to_string().contains("SequencerRegistryConfig not configured"), - "unexpected error: {err}" - ); -} - -/// End-to-end exercise of the two-step admin handoff through the block executor: the current -/// admin submits `transferAdmin`, the new admin submits `acceptAdmin`, and the registry's -/// `_admin` slot is promoted while `_pendingAdmin` is cleared. Mirrors the pattern used by -/// `test_system_address_change` for the system-address rotation flow. -#[test] -fn test_admin_handoff_via_block_executor() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(BOOTSTRAP_ADMIN, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(NEW_ADMIN, U256::from(1_000_000_000_000_000u64)); - - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - // Seed the slots the handoff path actually reads/writes (slot 0 keeps Oracle/system-address - // resolution happy across `apply_pre_execution_changes`; slot 2 is the modifier guard). - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - ADMIN, - BOOTSTRAP_ADMIN.into_word().into(), - ) - .unwrap(); - - let mut state = State::builder().with_database(&mut db).build(); - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = - block_executor_factory.create_executor(&mut state, block_ctx, create_evm_env()); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - // tx#1: current admin schedules a transfer to NEW_ADMIN. - let calldata = ISequencerRegistry::transferAdminCall { newAdmin: NEW_ADMIN }.abi_encode(); - let tx = create_tx_from_with_gas_limit( - BOOTSTRAP_ADMIN, - 0, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - 1_000_000, - ); - let receipt = executor - .execute_transaction(&tx) - .expect("transferAdmin tx should be accepted by the executor"); - assert!(receipt > 0, "transferAdmin tx should report non-zero gas used"); - - // tx#2: NEW_ADMIN completes the handoff. - let calldata = ISequencerRegistry::acceptAdminCall {}.abi_encode(); - let tx = create_tx_from_with_gas_limit( - NEW_ADMIN, - 0, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - 1_000_000, - ); - let receipt = executor - .execute_transaction(&tx) - .expect("acceptAdmin tx should be accepted by the executor"); - assert!(receipt > 0, "acceptAdmin tx should report non-zero gas used"); - - // Drop the executor to release the &mut borrow on `state`, then read the post-state. - drop(executor); - - let admin_slot = revm::Database::storage(&mut state, SEQUENCER_REGISTRY_ADDRESS, ADMIN) - .expect("read ADMIN slot"); - assert_eq!( - admin_slot, - U256::from_be_bytes(NEW_ADMIN.into_word().0), - "_admin must be promoted to NEW_ADMIN after acceptAdmin", - ); - - let pending_slot = - revm::Database::storage(&mut state, SEQUENCER_REGISTRY_ADDRESS, PENDING_ADMIN) - .expect("read PENDING_ADMIN slot"); - assert_eq!(pending_slot, U256::ZERO, "_pendingAdmin must be cleared after acceptAdmin"); -} diff --git a/crates/mega-evm/tests/_pending/compute_gas/claims.rs b/crates/mega-evm/tests/_pending/compute_gas/claims.rs deleted file mode 100644 index 79285d884..000000000 --- a/crates/mega-evm/tests/_pending/compute_gas/claims.rs +++ /dev/null @@ -1,568 +0,0 @@ -//! Direct assertions for the normative claims in `docs/spec/evm/compute-gas.md` that the -//! cross-spec snapshot cannot pin on its own. -//! -//! The snapshot in [`super`] records *numbers*; it detects that a value moved but does not state -//! why the value is what it is. These tests assert the rules behind the numbers, so a refactor -//! that happens to preserve a snapshot value while breaking the underlying rule still fails. -//! -//! Each test names the spec section it pins. - -use std::convert::Infallible; - -use alloy_eips::eip2930::{AccessList, AccessListItem}; -use alloy_primitives::{Address, Bytes, B256, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaLimitControl, LimitKind, MegaLimitExceeded, MegaSpecId, SaltEnv, - TestExternalEnvs, LIMIT_CONTROL_ADDRESS, MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::{ - CALL, CALLCODE, CREATE, GAS, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, SELFDESTRUCT, - STATICCALL, - }, - context::result::ExecutionResult, -}; - -use crate::{ - base_db, push_call_operands, push_valueless_call_operands, transact, transact_output, - transact_with_access_list, transact_with_envs, transact_with_limits, Outcome, CALLEE, CALLER, - CONTRACT, EMPTY_TARGET, EXISTING_TARGET, ONE_ETH, PRECOMPILE_IDENTITY, PRECOMPILE_KZG, -}; - -/// `remainingComputeGas()` — the `MegaLimitControl` selector the interceptor recognizes. -const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; - -/// Builds a program that CALLs `remainingComputeGas()` on `MegaLimitControl`, forwarding -/// `forwarded_gas`. The return data is discarded (`retSize = 0`) so the measurement is not -/// perturbed by memory expansion. -fn intercepted_call(forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(forwarded_gas) - .append(CALL) - .append(POP) - .stop() - .build() -} - -/// Spec: [Refund Exclusion] — "A node MUST NOT subtract EVM gas refunds from compute gas usage. -/// Refunds affect final gas settlement but do not reduce the compute gas recorded during -/// execution." -/// -/// Two programs that perform one `SSTORE` each on a slot holding a non-zero value. Clearing the -/// slot earns the EVM's `SSTORE_CLEARS_SCHEDULE` refund; overwriting it with another non-zero value -/// does not. Both charge the same `SSTORE_RESET` cost and encode to the same push width, so the -/// pair isolates the refund exactly: it must lower `gas_used` and leave `compute_gas` untouched. -#[test] -fn test_refunds_do_not_reduce_compute_gas() { - /// The inherited EVM's refund for clearing a storage slot (EIP-3529). - const SSTORE_CLEARS_SCHEDULE: u64 = 4_800; - - let program = |new_value: U256| { - move || { - base_db(BytecodeBuilder::default().sstore(U256::from(7), new_value).stop().build()) - .account_storage(CONTRACT, U256::from(7), U256::from(1)) - } - }; - let clearing = program(U256::ZERO); // 1 -> 0: earns the refund - let overwriting = program(U256::from(2)); // 1 -> 2: no refund - - for spec in [ - MegaSpecId::MINI_REX, - MegaSpecId::REX, - MegaSpecId::REX2, - MegaSpecId::REX4, - MegaSpecId::REX5, - MegaSpecId::REX6, - ] { - let cleared = transact(spec, clearing()); - let overwritten = transact(spec, overwriting()); - assert_eq!(cleared.outcome, "success", "{spec:?}: slot clear should succeed"); - assert_eq!(overwritten.outcome, "success", "{spec:?}: slot overwrite should succeed"); - - assert_eq!( - overwritten.gas_used.checked_sub(cleared.gas_used).unwrap_or_else(|| panic!( - "{spec:?}: clearing must not cost more than overwriting \ - (cleared={} overwritten={})", - cleared.gas_used, overwritten.gas_used - )), - SSTORE_CLEARS_SCHEDULE, - "{spec:?}: the refund must be settled out of gas_used \ - (cleared={} overwritten={})", - cleared.gas_used, - overwritten.gas_used - ); - assert_eq!( - cleared.compute_gas, overwritten.compute_gas, - "{spec:?}: the refund must NOT be subtracted from compute gas \ - (cleared={} overwritten={})", - cleared.compute_gas, overwritten.compute_gas - ); - } -} - -/// Spec: [Storage Gas Exclusion], at the one surcharge site the snapshot corpus cannot reach. -/// -/// Rex5 charges dynamic new-account storage gas when `SELFDESTRUCT` materializes an empty -/// beneficiary. That charge is `base × (multiplier − 1)`, and the corpus runs against the empty -/// external environment where every bucket sits at `MIN_BUCKET_SIZE` — so the multiplier is 1, the -/// surcharge is zero, and the corpus's Rex4 and Rex5 rows are identical. A regression that let the -/// surcharge leak into compute gas would leave the snapshot unchanged. -/// -/// This test puts the beneficiary's bucket above the minimum so the surcharge is non-zero, then -/// asserts the split: `gas_used` rises by exactly the surcharge while `compute_gas` does not move. -#[test] -fn test_selfdestruct_storage_surcharge_stays_out_of_compute_gas() { - /// Rex's base cost for materializing an account, scaled by `multiplier − 1`. - const NEW_ACCOUNT_STORAGE_GAS_BASE: u64 = 25_000; - /// Bucket capacity multiplier for the beneficiary's bucket. - const MULTIPLIER: u64 = 4; - - let envs = || { - let bucket = TestExternalEnvs::::bucket_id_for_account(EMPTY_TARGET); - TestExternalEnvs::::new() - .with_bucket_capacity(bucket, MIN_BUCKET_SIZE as u64 * MULTIPLIER) - }; - let build = || { - base_db(BytecodeBuilder::default().push_address(EMPTY_TARGET).append(SELFDESTRUCT).build()) - }; - - let rex4 = transact_with_envs(MegaSpecId::REX4, build(), envs()); - let rex5 = transact_with_envs(MegaSpecId::REX5, build(), envs()); - - let surcharge = NEW_ACCOUNT_STORAGE_GAS_BASE * (MULTIPLIER - 1); - assert!(surcharge > 0, "the fixture must produce a non-zero surcharge"); - - assert_eq!( - rex5.gas_used.checked_sub(rex4.gas_used).unwrap_or_else(|| panic!( - "Rex5 must not charge less total gas than Rex4 (Rex4={} Rex5={})", - rex4.gas_used, rex5.gas_used - )), - surcharge, - "Rex5 must charge the empty-beneficiary storage surcharge that Rex4 does not \ - (Rex4={} Rex5={})", - rex4.gas_used, - rex5.gas_used - ); - assert_eq!( - rex4.compute_gas, rex5.compute_gas, - "the surcharge is storage gas and MUST NOT enter compute gas (Rex4={} Rex5={})", - rex4.compute_gas, rex5.compute_gas - ); -} - -/// Looks up a corpus program by name so a claim test and the snapshot exercise the same bytecode. -fn corpus_program(name: &str) -> crate::Program { - crate::corpus() - .into_iter() - .find(|p| p.name == name) - .unwrap_or_else(|| panic!("corpus must contain {name}")) -} - -/// Builds a caller that STATICCALLs `callee`, forwarding all available gas (`GAS`), and returns the -/// callee's reported remaining gas as the transaction output. -fn forwarding_probe() -> (Bytes, Bytes) { - // Callee: report the gas it was given. - let callee = BytecodeBuilder::default() - .append_many([GAS, PUSH0, MSTORE]) - .push_number(32_u64) - .append(PUSH0) - .append(RETURN) - .build(); - - // Caller: STATICCALL(gas=GAS, to=callee, in=0/0, out=0/0), then copy and return the result. - let caller = BytecodeBuilder::default() - .push_number(0_u64) // retSize — read via RETURNDATACOPY instead - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(CALLEE) - .append(GAS) - .append(STATICCALL) - .append(POP) - .push_number(32_u64) // size - .push_number(0_u64) // returndata offset - .push_number(0_u64) // memory offset - .append(RETURNDATACOPY) - .push_number(32_u64) - .append(PUSH0) - .append(RETURN) - .build(); - - (caller, callee) -} - -/// The inherited EVM's cold account access cost (EIP-2929). -const COLD_ACCOUNT_ACCESS_COST: u64 = 2_600; -/// The inherited EVM's warm account access cost (EIP-2929 `WARM_STORAGE_READ_COST`). -const WARM_ACCOUNT_ACCESS_COST: u64 = 100; -/// The observable cost of a defeated warm preload: the first touch pays the cold account access -/// cost where the inherited EVM charges the warm cost, so the first call to such an address costs -/// exactly 2,600 − 100 = 2,500 more than the second. -const COLD_IN_PLACE_OF_WARM: i64 = (COLD_ACCOUNT_ACCESS_COST - WARM_ACCOUNT_ACCESS_COST) as i64; - -/// A program of `n` identical CALL units targeting `to` with no value, each unit being the seven -/// operand pushes, the CALL, and a POP of the status flag. -fn repeated_call(to: Address, n: usize) -> Bytes { - let mut b = BytecodeBuilder::default(); - for _ in 0..n { - b = push_call_operands(b, to, 0, 50_000).append(CALL).append(POP); - } - b.stop().build() -} - -/// Same as [`repeated_call`] but with STATICCALL units (six operands, no value word). -fn repeated_staticcall(to: Address, n: usize) -> Bytes { - let mut b = BytecodeBuilder::default(); - for _ in 0..n { - b = push_valueless_call_operands(b, to, 50_000).append(STATICCALL).append(POP); - } - b.stop().build() -} - -/// Same as [`repeated_call`] but with CALLCODE units (seven operands, like CALL). -fn repeated_callcode(to: Address, n: usize) -> Bytes { - let mut b = BytecodeBuilder::default(); - for _ in 0..n { - b = push_call_operands(b, to, 0, 50_000).append(CALLCODE).append(POP); - } - b.stop().build() -} - -/// Measures how much more the first call in a transaction costs than the second call to the same -/// target. -/// -/// Runs the 0-, 1-, and 2-unit variants of `program` through `run` and differences the chosen -/// `metric` between consecutive variants. The call units are byte-identical, so the per-unit push -/// and POP bookkeeping cancels exactly, leaving `cost(first call) − cost(second call)`. The second -/// call always observes a warm target (the first call loaded it), so the result is -/// [`COLD_IN_PLACE_OF_WARM`] when the first touch was charged cold and `0` when the target's -/// preloaded warmth was honored. -fn first_call_extra_cost( - run: impl Fn(Bytes) -> Outcome, - program: impl Fn(usize) -> Bytes, - metric: impl Fn(&Outcome) -> u64, -) -> i64 { - let [c0, c1, c2] = [0_usize, 1, 2].map(|n| { - let outcome = run(program(n)); - assert_eq!(outcome.outcome, "success", "the {n}-call program should succeed"); - metric(&outcome) as i64 - }); - (c1 - c0) - (c2 - c1) -} - -/// Spec: [Inherited-Cost Exception: Preload-Warm Addresses] — "When the first access to such an -/// address in a transaction is made by one of the opcodes below, the opcode MUST charge the cold -/// account access cost in place of the warm cost", with `CALL` charged cold since `MiniRex`. -/// -/// The inherited EVM treats precompile addresses as warm from the start of every transaction -/// without loading them. From `MiniRex`, the first CALL to a precompile is charged cold anyway: -/// the first-vs-second-call difference is exactly 2,500 on every metering spec. Under Equivalence -/// the difference — measured on `gas_used`, since Equivalence records no compute gas — is zero, -/// pinning that the departure is `MegaETH`'s and not inherited. -#[test] -fn test_first_call_to_a_precompile_is_charged_cold_from_minirex() { - let program = |n| repeated_call(PRECOMPILE_IDENTITY, n); - - let equivalence = first_call_extra_cost( - |code| transact(MegaSpecId::EQUIVALENCE, base_db(code)), - program, - |o| o.gas_used, - ); - assert_eq!( - equivalence, 0, - "Equivalence: the inherited EVM honors the precompile's preloaded warmth, so the first \ - and second CALL must cost the same" - ); - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; - } - let extra = - first_call_extra_cost(|code| transact(spec, base_db(code)), program, |o| o.compute_gas); - assert_eq!( - extra, COLD_IN_PLACE_OF_WARM, - "{spec_name}: the first CALL to a precompile must be charged cold in place of warm" - ); - } -} - -/// Spec: [Inherited-Cost Exception: Preload-Warm Addresses] — the opcode table's second row: -/// `DELEGATECALL` and `STATICCALL` charge preload-warm addresses cold from Rex, not from -/// `MiniRex`. -/// -/// Under `MiniRex` these opcodes run without the account-inspecting wrapper, so the precompile's -/// preloaded warmth is honored and the first-vs-second-call difference is zero — a frozen quirk -/// this test pins: wiring the wrapper into `MiniRex` would break replay of MiniRex-era blocks and -/// fail here. From Rex onward the difference is the full cold-for-warm charge. -#[test] -fn test_staticcall_charges_preload_warm_addresses_cold_from_rex_only() { - let program = |n| repeated_staticcall(PRECOMPILE_IDENTITY, n); - let extra = |spec| { - first_call_extra_cost(|code| transact(spec, base_db(code)), program, |o| o.compute_gas) - }; - - assert_eq!( - extra(MegaSpecId::MINI_REX), - 0, - "MiniRex: STATICCALL must honor the precompile's preloaded warmth" - ); - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::REX) { - continue; - } - assert_eq!( - extra(spec), - COLD_IN_PLACE_OF_WARM, - "{spec_name}: the first STATICCALL to a precompile must be charged cold in place of \ - warm" - ); - } -} - -/// Spec: [Inherited-Cost Exception: Preload-Warm Addresses] — the access-list split: an address -/// "listed without storage keys" is preload-warm and its first CALL is charged cold, while an -/// address "listed with storage keys" is *loaded* rather than merely preloaded and keeps the -/// inherited warm pricing. -/// -/// The sender pays the EIP-2930 per-address cost for the entry either way; without storage keys -/// the first CALL still pays the cold account access cost on top. -#[test] -fn test_access_list_address_without_storage_keys_is_charged_cold() { - let program = |n| repeated_call(EXISTING_TARGET, n); - let without_keys = - || AccessList(vec![AccessListItem { address: EXISTING_TARGET, storage_keys: vec![] }]); - let with_key = || { - AccessList(vec![AccessListItem { - address: EXISTING_TARGET, - storage_keys: vec![B256::ZERO], - }]) - }; - - let equivalence = first_call_extra_cost( - |code| transact_with_access_list(MegaSpecId::EQUIVALENCE, base_db(code), without_keys()), - program, - |o| o.gas_used, - ); - assert_eq!( - equivalence, 0, - "Equivalence: the inherited EVM honors the access-list preload, so the first and second \ - CALL must cost the same" - ); - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; - } - let extra_without_keys = first_call_extra_cost( - |code| transact_with_access_list(spec, base_db(code), without_keys()), - program, - |o| o.compute_gas, - ); - assert_eq!( - extra_without_keys, COLD_IN_PLACE_OF_WARM, - "{spec_name}: the first CALL to an access-list address without storage keys must be \ - charged cold in place of warm" - ); - - let extra_with_key = first_call_extra_cost( - |code| transact_with_access_list(spec, base_db(code), with_key()), - program, - |o| o.compute_gas, - ); - assert_eq!( - extra_with_key, 0, - "{spec_name}: an access-list address with storage keys is loaded, not merely \ - preloaded, so its warmth must be honored" - ); - } -} - -/// Spec: [Inherited-Cost Exception: Preload-Warm Addresses] — the opcode table's `CALLCODE` arc -/// across specs: no charge under `MiniRex` (no pre-execution inspection), charged cold from Rex -/// through Rex4 (the inspection targets the call target), restored to inherited warm pricing at -/// Rex5 (the inspection targets the executing account, which is already warm), and charged cold -/// again under Rex6 (the delegation-aware beneficiary detection materializes the call target -/// ahead of the inherited load). -/// -/// The target is an access-list address listed without storage keys, so its warmth exists only -/// as a preload and the first-vs-second-call difference isolates the first-touch pricing. -#[test] -fn test_callcode_cold_first_touch_follows_the_spec_arc() { - let program = |n| repeated_callcode(EXISTING_TARGET, n); - let access_list = - || AccessList(vec![AccessListItem { address: EXISTING_TARGET, storage_keys: vec![] }]); - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; - } - let extra = first_call_extra_cost( - |code| transact_with_access_list(spec, base_db(code), access_list()), - program, - |o| o.compute_gas, - ); - let expected = if spec.is_enabled(MegaSpecId::REX6) { - COLD_IN_PLACE_OF_WARM - } else if spec.is_enabled(MegaSpecId::REX5) { - 0 - } else if spec.is_enabled(MegaSpecId::REX) { - COLD_IN_PLACE_OF_WARM - } else { - 0 - }; - assert_eq!( - extra, expected, - "{spec_name}: CALLCODE first-touch pricing must follow the documented spec arc" - ); - } -} - -/// Spec: [Inherited-Cost Exception: Preload-Warm Addresses] — the third preload-warm address -/// category: the block beneficiary (warmed by the inherited EIP-3651). -/// -/// The harness leaves the block environment at its default, so the beneficiary is the zero -/// address. Under Equivalence the first and second CALL to it cost the same (`gas_used` metric — -/// the inherited coinbase warming). From `MiniRex` the first CALL is charged cold in place of -/// warm on every metering spec. -#[test] -fn test_first_call_to_the_beneficiary_is_charged_cold_from_minirex() { - /// The default `BlockEnv` beneficiary every `transact` run executes under. - const BENEFICIARY: Address = Address::ZERO; - let program = |n| repeated_call(BENEFICIARY, n); - - let equivalence = first_call_extra_cost( - |code| transact(MegaSpecId::EQUIVALENCE, base_db(code)), - program, - |o| o.gas_used, - ); - assert_eq!( - equivalence, 0, - "Equivalence: the inherited EVM warms the beneficiary (EIP-3651), so the first and \ - second CALL must cost the same" - ); - - for (spec, spec_name) in crate::ALL_SPECS { - if !spec.is_enabled(MegaSpecId::MINI_REX) { - continue; - } - let extra = - first_call_extra_cost(|code| transact(spec, base_db(code)), program, |o| o.compute_gas); - assert_eq!( - extra, COLD_IN_PLACE_OF_WARM, - "{spec_name}: the first CALL to the beneficiary must be charged cold in place of warm" - ); - } -} - -/// Spec: [Opcode Metering Classes], the `SelfDestruct` class — "When that check finds more than one -/// dimension over its limit, the reported dimension follows the fixed priority" (data size, -/// key-value updates, compute gas, state growth). -/// -/// `SELFDESTRUCT` is the one opcode where two dimensions can cross in the same check: it records -/// the empty beneficiary's data-size / KV / state-growth usage before its inner instruction runs -/// and evaluates all four dimensions only in the trailing all-dimension check, together with its -/// compute gas. Tuning both the data-size and the compute-gas limit to be crossed exactly at that -/// opcode therefore makes the priority observable. -/// -/// The limits are calibrated from a control program that is byte-identical except that -/// `SELFDESTRUCT` is replaced by `STOP`: setting a dimension's transaction limit to the control's -/// final usage leaves that dimension zero headroom, so whatever `SELFDESTRUCT` adds crosses it. -/// Two single-dimension runs prove each tuned limit alone is crossed at that opcode and reports -/// its own kind; the combined run then must report data size, not compute gas. -/// -/// The exceed is frame-local — the top-level frame's budget is the remaining transaction budget — -/// so per "Exceed Behavior" it surfaces as a revert carrying the ABI-encoded -/// `MegaLimitExceeded(uint8 kind, uint64 limit)` payload, whose `kind` is the observable. -#[test] -fn test_data_size_exceed_is_reported_before_compute_gas_at_selfdestruct() { - let control_db = - || base_db(BytecodeBuilder::default().push_address(EMPTY_TARGET).stop().build()); - let selfdestruct_db = || { - base_db(BytecodeBuilder::default().push_address(EMPTY_TARGET).append(SELFDESTRUCT).build()) - }; - - // The beneficiary's pre-inner record exists from Rex5. - for spec in [MegaSpecId::REX5, MegaSpecId::REX6] { - // Calibration: the control's final usage is the usage standing right before SELFDESTRUCT - // executes, because the two programs are byte-identical up to that opcode, the control - // ends in a zero-cost STOP that records nothing further, and the harness charges no fees, - // so no post-execution fee-recipient accounting is merged into the reported totals either. - let (control, at_opcode) = - transact_with_limits(spec, control_db(), CONTRACT, EvmTxRuntimeLimits::from_spec(spec)); - assert!(control.is_success(), "{spec:?}: control program should succeed"); - - // Under the spec's default limits the SELFDESTRUCT run succeeds and consumes more of both - // dimensions, so each tuned limit below is crossed exactly at that opcode. - let (relaxed, sd_usage) = transact_with_limits( - spec, - selfdestruct_db(), - CONTRACT, - EvmTxRuntimeLimits::from_spec(spec), - ); - assert!(relaxed.is_success(), "{spec:?}: SELFDESTRUCT under default limits should succeed"); - assert!( - sd_usage.data_size > at_opcode.data_size && - sd_usage.compute_gas > at_opcode.compute_gas, - "{spec:?}: SELFDESTRUCT must add usage in both dimensions (data {} -> {}, compute \ - {} -> {})", - at_opcode.data_size, - sd_usage.data_size, - at_opcode.compute_gas, - sd_usage.compute_gas - ); - - let reported_kind = |limits: EvmTxRuntimeLimits| { - let (result, _) = transact_with_limits(spec, selfdestruct_db(), CONTRACT, limits); - let ExecutionResult::Revert { output, .. } = result else { - panic!("{spec:?}: expected a frame-local limit revert, got {result:?}") - }; - MegaLimitExceeded::abi_decode(&output) - .unwrap_or_else(|e| { - panic!("{spec:?}: revert payload should decode as MegaLimitExceeded: {e}") - }) - .kind - }; - - // Each tuned limit alone is crossed at SELFDESTRUCT and reports its own dimension. - assert_eq!( - reported_kind( - EvmTxRuntimeLimits::from_spec(spec).with_tx_data_size_limit(at_opcode.data_size) - ), - LimitKind::DataSize.as_u8(), - "{spec:?}: the tuned data-size limit alone must be crossed at SELFDESTRUCT" - ); - assert_eq!( - reported_kind( - EvmTxRuntimeLimits::from_spec(spec) - .with_tx_compute_gas_limit(at_opcode.compute_gas) - ), - LimitKind::ComputeGas.as_u8(), - "{spec:?}: the tuned compute-gas limit alone must be crossed at SELFDESTRUCT" - ); - - // Both dimensions cross in the same all-dimension check: the fixed priority puts data - // size before compute gas, so data size must be the reported dimension. - assert_eq!( - reported_kind( - EvmTxRuntimeLimits::from_spec(spec) - .with_tx_data_size_limit(at_opcode.data_size) - .with_tx_compute_gas_limit(at_opcode.compute_gas) - ), - LimitKind::DataSize.as_u8(), - "{spec:?}: when the data-size and compute-gas limits are both crossed at the same \ - opcode, the data-size exceed must be the one reported" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/compute_gas/main.rs b/crates/mega-evm/tests/_pending/compute_gas/main.rs deleted file mode 100644 index 970fb979d..000000000 --- a/crates/mega-evm/tests/_pending/compute_gas/main.rs +++ /dev/null @@ -1,853 +0,0 @@ -//! Cross-spec compute-gas snapshot. -//! -//! [`docs/spec/evm/compute-gas.md`] defines compute gas as a *derived measurement* of inherited EVM -//! gas: a measurement window opens, the operation runs, and the recorded amount is the EVM gas -//! consumed inside the window minus storage gas and minus gas forwarded to a child frame. Where -//! that window opens and closes is consensus-visible, because the amount recorded when an opcode -//! halts determines which limit is reached first. -//! -//! That makes the recorded amount — not the instruction-table wiring — the thing a refactor of the -//! per-opcode metering layer must preserve. This suite pins it: a corpus covering every metering -//! class, and every non-opcode recording site reachable from a plain transaction, is executed under -//! every spec, and the resulting compute-gas readings are compared against a checked-in snapshot. -//! -//! The one recording site the corpus does not reach is `KeylessDeploy` — its dispatch overhead and -//! the Rex5 sandbox-usage merge. Driving it needs a signed RLP payload, and it is already pinned by -//! `tests/rex5/sandbox_accounting.rs`, so it is covered there rather than duplicated here. -//! -//! Within that corpus, any change to a recorded amount on any spec surfaces as a snapshot diff. -//! The corpus runs against minimum-capacity SALT buckets throughout, so recorded amounts that only -//! move once a bucket grows are pinned by the claim tests in `claims.rs` rather than here. -//! Frozen specs (Equivalence through Rex6) must never move; a diff there is a replay-breaking -//! regression. Only the unstable spec's rows may change. -//! -//! Regenerate after an intentional change: -//! -//! ```text -//! UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas -//! ``` - -mod claims; - -use std::{convert::Infallible, fmt::Write as _, path::Path}; - -use alloy_eips::eip2930::AccessList; -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{ - CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, LOG0, LOG1, LOG2, LOG3, LOG4, SELFDESTRUCT, - STATICCALL, TIMESTAMP, - }, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -/// Transaction sender. -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -/// Contract invoked by the transaction; its code exercises the operation under test. -const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); -/// An address with no code and no balance — the "empty account" CALL / SELFDESTRUCT target. -const EMPTY_TARGET: Address = address!("0000000000000000000000000000000000200002"); -/// An address that already exists (non-zero balance) but has no code. -const EXISTING_TARGET: Address = address!("0000000000000000000000000000000000200003"); -/// A contract that simply stops — a CALL target with code, so the callee runs a real frame. -const CALLEE: Address = address!("0000000000000000000000000000000000200004"); - -/// The identity precompile. -const PRECOMPILE_IDENTITY: Address = address!("0000000000000000000000000000000000000004"); -/// The SHA-256 precompile. -const PRECOMPILE_SHA256: Address = address!("0000000000000000000000000000000000000002"); -/// The KZG point-evaluation precompile. `MegaETH` replaces it with a fixed-cost variant from -/// `MiniRex` onward, and Rex5 gives it a dedicated compute-gas recording case. -const PRECOMPILE_KZG: Address = address!("000000000000000000000000000000000000000a"); - -/// Initcode that returns 32 zero bytes as the deployed runtime code: `PUSH1 0x20; PUSH0; RETURN`. -/// Memory in a fresh frame is zero-initialized, so `RETURN(0, 32)` yields 32 bytes of `STOP`. -/// Used to exercise a non-zero code-deposit charge; every other CREATE case deploys empty code. -const INITCODE_RETURNING_32_BYTES: [u8; 4] = [0x60, 0x20, 0x5f, 0xf3]; - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// Every spec in the progression, oldest first. The alias rungs are included: their columns -/// must stay byte-identical to their behavior targets' (`MiniRex1` = `Equivalence`, -/// `MiniRex2` = `MiniRex`), so an alias diverging from its target surfaces as a snapshot diff. -const ALL_SPECS: [(MegaSpecId, &str); 12] = [ - (MegaSpecId::EQUIVALENCE, "Equivalence"), - (MegaSpecId::MINI_REX, "MiniRex"), - (MegaSpecId::MINI_REX_1, "MiniRex1"), - (MegaSpecId::MINI_REX_2, "MiniRex2"), - (MegaSpecId::REX, "Rex"), - (MegaSpecId::REX1, "Rex1"), - (MegaSpecId::REX2, "Rex2"), - (MegaSpecId::REX3, "Rex3"), - (MegaSpecId::REX4, "Rex4"), - (MegaSpecId::REX5, "Rex5"), - (MegaSpecId::REX6, "Rex6"), - (MegaSpecId::REX7, "Rex7"), -]; - -/// A single corpus entry: a label and the world state it runs against. -pub(crate) struct Program { - name: &'static str, - /// Rebuilt per spec so each run starts from identical state. - build_db: fn() -> MemoryDatabase, -} - -/// Post-transaction readings recorded in the snapshot. -struct Outcome { - compute_gas: u64, - gas_used: u64, - outcome: String, -} - -/// Runs one transaction calling [`CONTRACT`] under `spec` with the spec's default runtime limits. -fn transact(spec: MegaSpecId, mut db: MemoryDatabase) -> Outcome { - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - let gas_used = result.result.gas_used(); - - let outcome = match &result.result { - ExecutionResult::Success { .. } => "success".to_string(), - ExecutionResult::Revert { .. } => "revert".to_string(), - ExecutionResult::Halt { reason, .. } => format!("halt {reason:?}"), - }; - - Outcome { compute_gas, gas_used, outcome } -} - -/// Runs the same transaction as [`transact`] but against a caller-supplied external environment, -/// so a test can raise a SALT bucket above `MIN_BUCKET_SIZE` and make dynamic storage gas non-zero. -fn transact_with_envs( - spec: MegaSpecId, - mut db: MemoryDatabase, - envs: TestExternalEnvs, -) -> Outcome { - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - let gas_used = result.result.gas_used(); - - let outcome = match &result.result { - ExecutionResult::Success { .. } => "success".to_string(), - ExecutionResult::Revert { .. } => "revert".to_string(), - ExecutionResult::Halt { reason, .. } => format!("halt {reason:?}"), - }; - - Outcome { compute_gas, gas_used, outcome } -} - -/// Runs the same transaction as [`transact`] but attaches an EIP-2930 access list, so a claim -/// test can observe how the transaction-level warm preload interacts with the first CALL-family -/// touch of a listed address. -fn transact_with_access_list( - spec: MegaSpecId, - mut db: MemoryDatabase, - access_list: AccessList, -) -> Outcome { - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CONTRACT) - .access_list(access_list) - .gas_limit(100_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - let gas_used = result.result.gas_used(); - - let outcome = match &result.result { - ExecutionResult::Success { .. } => "success".to_string(), - ExecutionResult::Revert { .. } => "revert".to_string(), - ExecutionResult::Halt { reason, .. } => format!("halt {reason:?}"), - }; - - Outcome { compute_gas, gas_used, outcome } -} - -/// Runs the same transaction as [`transact`] but under caller-supplied runtime limits and an -/// explicit call target, returning the full execution result — so revert payloads and halt -/// reasons stay observable — together with the post-transaction tracker usage across all four -/// resource dimensions. -fn transact_with_limits( - spec: MegaSpecId, - mut db: MemoryDatabase, - to: Address, - limits: EvmTxRuntimeLimits, -) -> (ExecutionResult, LimitUsage) { - let mut context = MegaContext::new(&mut db, spec).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (result.result, usage) -} - -/// Runs the same transaction as [`transact`] and returns the transaction's output bytes. -/// Used by the claim tests that read a value the contract computed (e.g. forwarded gas). -fn transact_output(spec: MegaSpecId, mut db: MemoryDatabase) -> Bytes { - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - result.result.output().cloned().unwrap_or_default() -} - -/// Runs a **contract-creation** transaction carrying `initcode`, rather than the call transaction -/// every other helper here sends. -/// -/// The intrinsic-gas rules for a creation transaction differ from those for a call: it carries the -/// inherited creation surcharge and the EIP-3860 per-initcode-word charge on top of the base cost. -/// Those two additions are unreachable through a call transaction, so they need their own entry -/// point to be observable at all. -fn transact_create(spec: MegaSpecId, initcode: Bytes) -> Outcome { - let mut db = base_db(Bytes::new()); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .create() - .data(initcode) - .gas_limit(100_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - let gas_used = result.result.gas_used(); - - let outcome = match &result.result { - ExecutionResult::Success { .. } => "success".to_string(), - ExecutionResult::Revert { .. } => "revert".to_string(), - ExecutionResult::Halt { reason, .. } => format!("halt {reason:?}"), - }; - - Outcome { compute_gas, gas_used, outcome } -} - -/// Base world: funded caller, the contract under test with `code`, and the CALL fixtures. -fn base_db(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) - .account_balance(EXISTING_TARGET, U256::from(ONE_ETH)) - .account_code(CALLEE, BytecodeBuilder::default().stop().build()) -} - -/// Emits the seven CALL operands (retSize, retOffset, argsSize, argsOffset, value, to, gas), -/// leaving `gas` on top as CALL expects. -fn push_call_operands(b: BytecodeBuilder, to: Address, value: u64, gas: u64) -> BytecodeBuilder { - b.push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(value) - .push_address(to) - .push_number(gas) -} - -/// Emits the six DELEGATECALL / STATICCALL operands (no value word). -fn push_valueless_call_operands(b: BytecodeBuilder, to: Address, gas: u64) -> BytecodeBuilder { - b.push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(to) - .push_number(gas) -} - -/// The corpus. One entry per metering class and per non-opcode recording site in the spec. -pub(crate) fn corpus() -> Vec { - vec![ - // ---- Non-opcode recording site: transaction intrinsic gas ---- - Program { - // No code at CONTRACT: the only compute gas recorded is the transaction intrinsic. - name: "intrinsic_only", - build_db: || { - MemoryDatabase::default().account_balance(CALLER, U256::from(10 * ONE_ETH)) - }, - }, - // ---- Plain class ---- - Program { - name: "plain_arithmetic", - build_db: || { - let mut b = BytecodeBuilder::default(); - for i in 0..32u64 { - b = b.push_number(i).push_number(i + 1).append(0x01).append(0x50); // ADD, POP - } - base_db(b.stop().build()) - }, - }, - Program { - name: "plain_memory_expansion", - build_db: || { - base_db( - BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .mstore(4096, [0x22u8; 32]) - .stop() - .build(), - ) - }, - }, - // ---- Volatile class ---- - Program { - name: "volatile_timestamp", - build_db: || { - base_db( - BytecodeBuilder::default() - .append(TIMESTAMP) - .append(0x50) // POP - .stop() - .build(), - ) - }, - }, - // ---- Storage class ---- - Program { - name: "sstore_zero_to_nonzero", - build_db: || { - base_db( - BytecodeBuilder::default().sstore(U256::from(7), U256::from(99)).stop().build(), - ) - }, - }, - Program { - name: "sstore_nonzero_to_nonzero", - build_db: || { - base_db( - BytecodeBuilder::default().sstore(U256::from(7), U256::from(99)).stop().build(), - ) - .account_storage(CONTRACT, U256::from(7), U256::from(1)) - }, - }, - Program { - name: "sstore_nonzero_to_zero", - build_db: || { - base_db(BytecodeBuilder::default().sstore(U256::from(7), U256::ZERO).stop().build()) - .account_storage(CONTRACT, U256::from(7), U256::from(1)) - }, - }, - Program { - name: "log0_empty", - build_db: || { - base_db( - BytecodeBuilder::default() - .push_number(0u64) // len - .push_number(0u64) // offset - .append(LOG0) - .stop() - .build(), - ) - }, - }, - Program { - name: "log1_32bytes", - build_db: || { - base_db( - BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .push_number(0xabcu64) // topic0 - .push_number(32u64) // len - .push_number(0u64) // offset - .append(LOG1) - .stop() - .build(), - ) - }, - }, - Program { - name: "log4_128bytes", - build_db: || { - base_db( - BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .mstore(32, [0x22u8; 32]) - .mstore(64, [0x33u8; 32]) - .mstore(96, [0x44u8; 32]) - .push_number(4u64) - .push_number(3u64) - .push_number(2u64) - .push_number(1u64) - .push_number(128u64) // len - .push_number(0u64) // offset - .append(LOG4) - .stop() - .build(), - ) - }, - }, - Program { - name: "log2_log3_sequence", - build_db: || { - base_db( - BytecodeBuilder::default() - .mstore(0, [0x55u8; 32]) - .push_number(2u64) - .push_number(1u64) - .push_number(32u64) - .push_number(0u64) - .append(LOG2) - .push_number(3u64) - .push_number(2u64) - .push_number(1u64) - .push_number(32u64) - .push_number(0u64) - .append(LOG3) - .stop() - .build(), - ) - }, - }, - // ---- Call class ---- - Program { - name: "call_no_value_to_code", - build_db: || { - let b = push_call_operands(BytecodeBuilder::default(), CALLEE, 0, 1_000_000); - base_db(b.append(CALL).stop().build()) - }, - }, - Program { - name: "call_value_to_empty", - build_db: || { - let b = push_call_operands(BytecodeBuilder::default(), EMPTY_TARGET, 1, 1_000_000); - base_db(b.append(CALL).stop().build()) - }, - }, - Program { - name: "call_value_to_existing", - build_db: || { - let b = - push_call_operands(BytecodeBuilder::default(), EXISTING_TARGET, 1, 1_000_000); - base_db(b.append(CALL).stop().build()) - }, - }, - Program { - name: "callcode_value", - build_db: || { - let b = push_call_operands(BytecodeBuilder::default(), CALLEE, 1, 1_000_000); - base_db(b.append(CALLCODE).stop().build()) - }, - }, - Program { - name: "delegatecall", - build_db: || { - let b = push_valueless_call_operands(BytecodeBuilder::default(), CALLEE, 1_000_000); - base_db(b.append(DELEGATECALL).stop().build()) - }, - }, - Program { - name: "staticcall", - build_db: || { - let b = push_valueless_call_operands(BytecodeBuilder::default(), CALLEE, 1_000_000); - base_db(b.append(STATICCALL).stop().build()) - }, - }, - Program { - name: "nested_calls_depth3", - build_db: || { - // CONTRACT calls CALLEE_A, which calls CALLEE_B, which stops. - // Exercises the forwarded-gas exclusion across three frames plus, on Rex4+, the - // per-frame budget forwarding. - let inner = push_valueless_call_operands( - BytecodeBuilder::default(), - EXISTING_TARGET, - 100_000, - ) - .append(STATICCALL) - .stop() - .build(); - let outer = - push_valueless_call_operands(BytecodeBuilder::default(), CALLEE, 1_000_000) - .append(STATICCALL) - .stop() - .build(); - base_db(outer).account_code(CALLEE, inner) - }, - }, - // ---- Create class ---- - Program { - name: "create_empty_initcode", - build_db: || { - base_db( - BytecodeBuilder::default() - .push_number(0u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .stop() - .build(), - ) - }, - }, - Program { - name: "create2_empty_initcode", - build_db: || { - base_db( - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(0u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .stop() - .build(), - ) - }, - }, - Program { - name: "create2_with_initcode", - build_db: || { - // 32 bytes of initcode forces the wrapper-side memory expansion whose recording - // window moves across MiniRex / Rex5 / Rex6. - base_db( - BytecodeBuilder::default() - .mstore(0, [0x00u8; 32]) - .push_number(0u64) // salt - .push_number(32u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .stop() - .build(), - ) - }, - }, - Program { - name: "create_deploying_runtime_code", - build_db: || { - // The only corpus case that deploys non-empty runtime code, so the only one that - // exercises the code-deposit recording site (`code_length × CODEDEPOSIT`). Every - // other CREATE case returns empty code, making that charge zero. - base_db( - BytecodeBuilder::default() - .mstore(0, INITCODE_RETURNING_32_BYTES) - .push_number(INITCODE_RETURNING_32_BYTES.len() as u64) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .stop() - .build(), - ) - }, - }, - Program { - name: "create2_far_memory_offset", - build_db: || { - // A large offset makes the memory-expansion gas dominant, so a shift in which - // window records it is unmistakable in the snapshot. - base_db( - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(32u64) // length - .push_number(65_536u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .stop() - .build(), - ) - }, - }, - Program { - name: "create2_oversized_initcode", - build_db: || { - // Initcode longer than the max initcode size. Rex5 expands memory and records that - // gas eagerly, before the inner opcode rejects the size. MiniRex-Rex4 expand too - // but skip their trailing record once the inner opcode fails, and Rex6 halts on the - // size check before expanding at all. This is the failure path on which the CREATE2 - // window divergence is observable. - base_db( - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(600_000u64) // length — above MAX_INITCODE_SIZE - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .stop() - .build(), - ) - }, - }, - // ---- SelfDestruct class ---- - Program { - name: "selfdestruct_to_empty", - build_db: || { - base_db( - BytecodeBuilder::default() - .push_address(EMPTY_TARGET) - .append(SELFDESTRUCT) - .build(), - ) - }, - }, - Program { - name: "selfdestruct_to_existing", - build_db: || { - base_db( - BytecodeBuilder::default() - .push_address(EXISTING_TARGET) - .append(SELFDESTRUCT) - .build(), - ) - }, - }, - Program { - name: "selfdestruct_to_self", - build_db: || { - base_db( - BytecodeBuilder::default().push_address(CONTRACT).append(SELFDESTRUCT).build(), - ) - }, - }, - // ---- Non-opcode recording site: precompiles ---- - Program { - name: "precompile_identity", - build_db: || { - let b = BytecodeBuilder::default().mstore(0, [0x77u8; 32]); - base_db( - b.push_number(32u64) // retSize - .push_number(64u64) // retOffset - .push_number(32u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(PRECOMPILE_IDENTITY) - .push_number(100_000u64) - .append(CALL) - .stop() - .build(), - ) - }, - }, - Program { - name: "precompile_sha256", - build_db: || { - let b = BytecodeBuilder::default().mstore(0, [0x77u8; 32]); - base_db( - b.push_number(32u64) // retSize - .push_number(64u64) // retOffset - .push_number(32u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(PRECOMPILE_SHA256) - .push_number(100_000u64) - .append(CALL) - .stop() - .build(), - ) - }, - }, - Program { - name: "precompile_kzg_invalid_input", - build_db: || { - // KZG point evaluation with a 32-byte argument (it requires exactly 192), - // forwarding well above the fixed cost. The precompile reaches its - // verification step and returns a non-out-of-gas error — the Rex5 KZG branch, which - // records the fixed `KZG_POINT_EVALUATION_GAS_COST` rather than the spent amount - // (zero). - // - // This is the corpus case that makes MegaETH's KZG override visible: the recorded - // value must be the MegaETH 100,000, not the inherited EVM 50,000. - let b = BytecodeBuilder::default().mstore(0, [0x01u8; 32]); - base_db( - b.push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(32u64) // argsSize — wrong length on purpose - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(PRECOMPILE_KZG) - .push_number(200_000u64) // comfortably above the fixed cost - .append(CALL) - .stop() - .build(), - ) - }, - }, - Program { - name: "precompile_underfunded", - build_db: || { - // Forwarding less than the precompile's minimum cost: the error path where the - // recorded amount is the effective gas limit, not the spent amount. - let b = BytecodeBuilder::default().mstore(0, [0x77u8; 32]); - base_db( - b.push_number(32u64) - .push_number(64u64) - .push_number(32u64) - .push_number(0u64) - .push_number(0u64) - .push_address(PRECOMPILE_SHA256) - .push_number(1u64) // far below the SHA-256 minimum - .append(CALL) - .stop() - .build(), - ) - }, - }, - // ---- Revert behavior: compute gas must survive a reverted frame ---- - Program { - name: "reverting_subcall", - build_db: || { - // The callee burns gas and reverts. Compute gas is non-revertible, so the caller's - // total must still include the callee's consumption. - let mut inner = BytecodeBuilder::default(); - for i in 0..64u64 { - inner = inner.push_number(i).push_number(i + 1).append(0x01).append(0x50); - } - let inner = inner.revert().build(); - let outer = - push_valueless_call_operands(BytecodeBuilder::default(), CALLEE, 1_000_000) - .append(STATICCALL) - .stop() - .build(); - base_db(outer).account_code(CALLEE, inner) - }, - }, - ] -} - -/// Renders the full corpus × spec matrix as the snapshot text. -fn render_snapshot() -> String { - let mut out = String::new(); - out.push_str("# Cross-spec compute-gas snapshot.\n"); - out.push_str("#\n"); - out.push_str("# Generated by `crates/mega-evm/tests/compute_gas`. Do not edit by hand.\n"); - out.push_str( - "# Regenerate: UPDATE_COMPUTE_GAS_SNAPSHOT=1 cargo test -p mega-evm --test compute_gas\n", - ); - out.push_str("#\n"); - out.push_str( - "# `compute_gas` is the post-transaction compute-gas tracker reading; `gas_used` is the\n", - ); - out.push_str( - "# receipt value, which is neither counter nor their sum: refunds lower it, gas consumed\n", - ); - out.push_str( - "# outside a completed window raises it, and the calldata floor can raise it further.\n", - ); - out.push_str("#\n"); - out.push_str( - "# Frozen specs (Equivalence through Rex6) must never change: a diff there is a\n", - ); - out.push_str("# replay-breaking regression.\n"); - out.push_str("#\n"); - out.push_str(&format!( - "# {:<30}{:<13}{:>13}{:>13} {}\n", - "program", "spec", "compute_gas", "gas_used", "outcome" - )); - - for program in corpus() { - out.push('\n'); - for (spec, spec_name) in ALL_SPECS { - let o = transact(spec, (program.build_db)()); - let _ = writeln!( - out, - "{:<32}{:<13}{:>13}{:>13} {}", - program.name, spec_name, o.compute_gas, o.gas_used, o.outcome - ); - } - } - out -} - -fn snapshot_path() -> std::path::PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/compute_gas/snapshot.txt") -} - -/// Compute gas is the sole non-revertible resource dimension: a child frame that reverts still -/// contributes its consumption to the transaction total. -#[test] -fn test_compute_gas_survives_reverted_frame() { - let program = corpus() - .into_iter() - .find(|p| p.name == "reverting_subcall") - .expect("corpus must contain reverting_subcall"); - - // A caller-only baseline: same outer code, but the callee returns immediately. - let baseline_db = || { - let outer = push_valueless_call_operands(BytecodeBuilder::default(), CALLEE, 1_000_000) - .append(STATICCALL) - .stop() - .build(); - base_db(outer).account_code(CALLEE, BytecodeBuilder::default().stop().build()) - }; - - for (spec, spec_name) in ALL_SPECS { - if spec.behavior() == MegaSpecId::EQUIVALENCE { - continue; // no metering (covers the `MiniRex1` alias, which executes Equivalence) - } - let with_revert = transact(spec, (program.build_db)()); - let baseline = transact(spec, baseline_db()); - assert!( - with_revert.compute_gas > baseline.compute_gas, - "{spec_name}: a reverted subcall's compute gas must still be counted \ - (reverting={} baseline={})", - with_revert.compute_gas, - baseline.compute_gas - ); - } -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs b/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs deleted file mode 100644 index cc3ee8854..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/access_beneficiary_balance.rs +++ /dev/null @@ -1,558 +0,0 @@ -//! Simplified tests for beneficiary balance access tracking functionality. -//! -//! When the block beneficiary is accessed, gas is immediately detained (limited to 10,000). -//! Any action which causes `ResultAndState` to contain the beneficiary should mark beneficiary -//! access and trigger gas detention. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - test_utils::{BytecodeBuilder, GasInspector, MsgCallMeta}, - EmptyExternalEnv, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{BALANCE, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, POP, PUSH0, STOP}, - context::{result::ResultAndState, BlockEnv, ContextSetters, ContextTr, TxEnv}, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - primitives::TxKind, - state::{AccountInfo, Bytecode}, -}; - -const BENEFICIARY: Address = address!("0000000000000000000000000000000000BEEF01"); -const CALLER_ADDR: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT_ADDR: Address = address!("0000000000000000000000000000000000100001"); -const NESTED_CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -fn create_evm() -> MegaEvm, GasInspector, EmptyExternalEnv> { - let db = CacheDB::::default(); - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - - let block_env = - BlockEnv { beneficiary: BENEFICIARY, number: U256::from(10), ..Default::default() }; - context.set_block(block_env); - - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - - MegaEvm::new(context).with_inspector(GasInspector::new()) -} - -fn set_account_code(db: &mut CacheDB, address: Address, code: Bytes) { - let bytecode = Bytecode::new_legacy(code); - let code_hash = bytecode.hash_slow(); - let account_info = AccountInfo { code: Some(bytecode), code_hash, ..Default::default() }; - db.insert_account_info(address, account_info); -} - -fn execute_tx( - evm: &mut MegaEvm, GasInspector, EmptyExternalEnv>, - caller: Address, - to: Option
, - value: U256, - disable_beneficiary: bool, -) -> ResultAndState { - if disable_beneficiary { - evm.disable_beneficiary(); - } - - let tx = MegaTransaction { - base: TxEnv { - caller, - kind: match to { - Some(addr) => TxKind::Call(addr), - None => TxKind::Create, - }, - data: Bytes::default(), - value, - gas_limit: 10000000, - ..Default::default() - }, - ..Default::default() - }; - - alloy_evm::Evm::transact_raw(evm, tx).unwrap() -} - -fn assert_beneficiary_detection( - evm: &MegaEvm, GasInspector, EmptyExternalEnv>, - result_and_state: &ResultAndState, -) { - // Transaction should succeed - assert!(result_and_state.result.is_success()); - - // If state contains beneficiary, should have detection - if result_and_state.state.contains_key(&BENEFICIARY) { - assert!(evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance()); - } -} - -/// Test that verifies beneficiary balance access detection when the beneficiary is the transaction -/// caller. This test ensures that when the beneficiary address is used as the caller in a -/// transaction, the system correctly detects and tracks beneficiary balance access. -/// -/// When beneficiary is the caller, access is detected but gas is not immediately limited. -/// This test primarily verifies that beneficiary access is correctly tracked. -#[test] -fn test_beneficiary_caller() { - let mut evm = create_evm(); - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, vec![STOP].into()); - - let result_and_state = - execute_tx(&mut evm, BENEFICIARY, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Beneficiary balance access should be detected - assert!(evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance()); -} - -/// Test that verifies beneficiary balance access detection when the beneficiary is the transaction -/// recipient. This test ensures that when a transaction sends value to the beneficiary address, -/// the system correctly detects and tracks beneficiary balance access. -/// -/// When beneficiary is the recipient, access is detected but gas is not immediately limited. -/// This test primarily verifies that beneficiary access is correctly tracked. -#[test] -fn test_beneficiary_recipient() { - let mut evm = create_evm(); - - // Give caller some balance - evm.ctx().db_mut().insert_account_info( - CALLER_ADDR, - AccountInfo { balance: U256::from(1_000_000_000_000_000_000u64), ..Default::default() }, - ); - - let result_and_state = execute_tx( - &mut evm, - CALLER_ADDR, - Some(BENEFICIARY), - U256::from(500_000_000_000_000_000u64), - false, - ); - assert_beneficiary_detection(&evm, &result_and_state); - - // Beneficiary balance access should be detected - assert!(evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance()); -} - -/// Test that verifies beneficiary balance access detection when a contract uses the BALANCE opcode -/// on the beneficiary address. This test ensures that when a contract reads the balance of the -/// beneficiary address using the BALANCE opcode, the system correctly detects and tracks -/// beneficiary balance access. -/// -/// Gas should be > 10k before BALANCE opcode, then ≤ 10k after. -#[test] -fn test_balance_opcode() { - let mut evm = create_evm(); - - // Contract that reads beneficiary balance - let code = BytecodeBuilder::default() - .push_address(BENEFICIARY) - .append(BALANCE) - .append(POP) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after BALANCE opcode, all subsequent opcodes have gas ≤ 10k - let mut after_balance = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, _node, _item_location, item| { - let opcode_info = item.borrow(); - if after_balance { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after BALANCE should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - if opcode_info.opcode.as_str() == "BALANCE" { - after_balance = true; - } - }, - ); -} - -/// Test that verifies beneficiary balance access detection when a contract uses the EXTCODESIZE -/// opcode on the beneficiary address. This test ensures that when a contract checks the code size -/// of the beneficiary address using the EXTCODESIZE opcode, the system correctly detects and tracks -/// beneficiary balance access. -/// -/// Gas should be > 10k before EXTCODESIZE opcode, then ≤ 10k after. -#[test] -fn test_extcodesize_opcode() { - let mut evm = create_evm(); - - // Give beneficiary some code - set_account_code(evm.ctx().db_mut(), BENEFICIARY, vec![STOP].into()); - - // Contract that checks beneficiary code size - let code = BytecodeBuilder::default() - .push_address(BENEFICIARY) - .append(EXTCODESIZE) - .append(POP) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after EXTCODESIZE opcode, all subsequent opcodes have gas ≤ 10k - let mut after_extcodesize = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, _node, _item_location, item| { - let opcode_info = item.borrow(); - if after_extcodesize { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after EXTCODESIZE should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - if opcode_info.opcode.as_str() == "EXTCODESIZE" { - after_extcodesize = true; - } - }, - ); -} - -/// Test that verifies beneficiary balance access detection when a contract uses the EXTCODECOPY -/// opcode on the beneficiary address. This test ensures that when a contract copies code from the -/// beneficiary address using the EXTCODECOPY opcode, the system correctly detects and tracks -/// beneficiary balance access. -/// -/// Gas should be > 10k before EXTCODECOPY opcode, then ≤ 10k after. -#[test] -fn test_extcodecopy_opcode() { - let mut evm = create_evm(); - - // Give beneficiary some code - set_account_code(evm.ctx().db_mut(), BENEFICIARY, vec![STOP, STOP, STOP, STOP].into()); - - // Contract that copies beneficiary code: EXTCODECOPY(beneficiary, 0, 0, 4) - let code = BytecodeBuilder::default() - .push_number(4u8) // size = 4 - .push_number(0u8) // offset = 0 - .push_number(0u8) // destOffset = 0 - .push_address(BENEFICIARY) // beneficiary address - .append(EXTCODECOPY) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after EXTCODECOPY opcode, all subsequent opcodes have gas ≤ 10k - let mut after_extcodecopy = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, _node, _item_location, item| { - let opcode_info = item.borrow(); - if after_extcodecopy { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after EXTCODECOPY should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - if opcode_info.opcode.as_str() == "EXTCODECOPY" { - after_extcodecopy = true; - } - }, - ); -} - -/// Test that verifies beneficiary balance access detection when a contract uses the EXTCODEHASH -/// opcode on the beneficiary address. This test ensures that when a contract reads the code hash -/// of the beneficiary address using the EXTCODEHASH opcode, the system correctly detects and tracks -/// beneficiary balance access. -/// -/// Gas should be > 10k before EXTCODEHASH opcode, then ≤ 10k after. -#[test] -fn test_extcodehash_opcode() { - let mut evm = create_evm(); - - // Give beneficiary some code - set_account_code(evm.ctx().db_mut(), BENEFICIARY, vec![STOP].into()); - - // Contract that reads beneficiary code hash - let code = BytecodeBuilder::default() - .push_address(BENEFICIARY) - .append(EXTCODEHASH) - .append(POP) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after EXTCODEHASH opcode, all subsequent opcodes have gas ≤ 10k - let mut after_extcodehash = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, _node, _item_location, item| { - let opcode_info = item.borrow(); - if after_extcodehash { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after EXTCODEHASH should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - if opcode_info.opcode.as_str() == "EXTCODEHASH" { - after_extcodehash = true; - } - }, - ); -} - -/// Test that verifies beneficiary balance access detection when a contract performs a CALL -/// to the beneficiary address. This test ensures that making a call to the beneficiary triggers -/// gas detention. -/// -/// Gas should be > 10k before the CALL, then ≤ 10k after. -#[test] -fn test_call_to_beneficiary() { - let mut evm = create_evm(); - - // Give beneficiary some code to execute - set_account_code(evm.ctx().db_mut(), BENEFICIARY, vec![PUSH0, PUSH0, STOP].into()); - - // Contract that calls beneficiary: CALL(gas, beneficiary, 0, 0, 0, 0, 0) - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // retSize, retOffset, argSize, argOffset, value - .push_address(BENEFICIARY) // address - .append(revm::bytecode::opcode::GAS) // gas - .append(revm::bytecode::opcode::CALL) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after the CALL, gas is limited - let mut after_call_to_beneficiary = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, node, _item_location, item| { - let opcode_info = item.borrow(); - - // Check if we just completed a CALL to beneficiary - if opcode_info.opcode.as_str() == "CALL" { - if let MsgCallMeta::Call(call_inputs) = &node.borrow().meta { - if call_inputs.target_address == BENEFICIARY { - after_call_to_beneficiary = true; - } - } - } - - if after_call_to_beneficiary { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after CALL to beneficiary should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - }, - ); -} - -/// Test that verifies beneficiary balance access detection when a contract performs a STATICCALL -/// to the beneficiary address. This test ensures that making a static call to the beneficiary -/// triggers gas detention. -/// -/// Gas should be > 10k before the STATICCALL, then ≤ 10k after. -#[test] -fn test_staticcall_to_beneficiary() { - let mut evm = create_evm(); - - // Give beneficiary some code to execute - set_account_code(evm.ctx().db_mut(), BENEFICIARY, vec![PUSH0, PUSH0, STOP].into()); - - // Contract that static calls beneficiary: STATICCALL(gas, beneficiary, 0, 0, 0, 0) - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retSize, retOffset, argSize, argOffset - .push_address(BENEFICIARY) // address - .append(revm::bytecode::opcode::GAS) // gas - .append(revm::bytecode::opcode::STATICCALL) - .stop() - .build(); - - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after the STATICCALL, gas is limited - let mut after_staticcall_to_beneficiary = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, node, _item_location, item| { - let opcode_info = item.borrow(); - - // Check if we just completed a STATICCALL to beneficiary - if opcode_info.opcode.as_str() == "STATICCALL" { - if let MsgCallMeta::Call(call_inputs) = &node.borrow().meta { - if call_inputs.target_address == BENEFICIARY { - after_staticcall_to_beneficiary = true; - } - } - } - - if after_staticcall_to_beneficiary { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after STATICCALL to beneficiary should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - }, - ); -} - -/// Test that verifies gas limiting propagates correctly through nested calls when a nested -/// contract accesses the beneficiary. This test ensures that when a child call accesses the -/// beneficiary, both the child and parent frames get gas limited. -/// -/// Parent calls Child, Child accesses beneficiary → both should have gas ≤ 10k after. -#[test] -fn test_nested_call_beneficiary_access() { - let mut evm = create_evm(); - - // Nested contract that reads beneficiary balance - let nested_code = BytecodeBuilder::default() - .push_address(BENEFICIARY) - .append(BALANCE) - .append(POP) - .stop() - .build(); - set_account_code(evm.ctx().db_mut(), NESTED_CONTRACT, nested_code); - - // Main contract that calls nested contract - let main_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // retSize, retOffset, argSize, argOffset, value - .push_address(NESTED_CONTRACT) // address - .append(revm::bytecode::opcode::GAS) // gas - .append(revm::bytecode::opcode::CALL) - .append(POP) // Pop the return value - .stop() - .build(); - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, main_code); - - let result_and_state = - execute_tx(&mut evm, CALLER_ADDR, Some(CONTRACT_ADDR), U256::ZERO, false); - assert_beneficiary_detection(&evm, &result_and_state); - - // Verify that after the nested call accesses beneficiary, all subsequent opcodes have gas ≤ 10k - let mut accessed_beneficiary_in_nested = false; - let gas_inspector = &evm.inspector; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, node, _item_location, item| { - let opcode_info = item.borrow(); - - // Check if we're in the nested contract and hit BALANCE on beneficiary - if opcode_info.opcode.as_str() == "BALANCE" { - if let MsgCallMeta::Call(call_inputs) = &node.borrow().meta { - if call_inputs.target_address == NESTED_CONTRACT { - accessed_beneficiary_in_nested = true; - } - } - } - - if accessed_beneficiary_in_nested { - assert!( - opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "Gas after nested beneficiary access should be ≤ {}, got {}", - BLOCK_ENV_ACCESS_COMPUTE_GAS, - opcode_info.gas_after - ); - } - }, - ); -} - -/// Test that verifies detained gas is restored (refunded) at the end of the transaction. -/// This ensures that users are not charged for the gas that was temporarily detained during -/// beneficiary access. -/// -/// The transaction should start with high gas, detain most of it when beneficiary is accessed, -/// but the detained gas should be refunded so the final `gas_used` is reasonable. -#[test] -fn test_detained_gas_is_restored() { - let mut evm = create_evm(); - - // Simple contract that accesses beneficiary balance - let code = BytecodeBuilder::default() - .push_address(BENEFICIARY) - .append(BALANCE) - .append(POP) - .stop() - .build(); - set_account_code(evm.ctx().db_mut(), CONTRACT_ADDR, code); - - // Execute with a large gas limit - let gas_limit = 1_000_000u64; - let tx = MegaTransaction { - base: TxEnv { - caller: CALLER_ADDR, - kind: TxKind::Call(CONTRACT_ADDR), - data: Bytes::default(), - value: U256::ZERO, - gas_limit, - ..Default::default() - }, - ..Default::default() - }; - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success()); - assert!(evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance()); - - // The gas_used should be much less than the gas_limit because detained gas is refunded. - // We expect gas_used to be only a few thousand (for the actual work done), not close to 1M. - let gas_used = result.result.gas_used(); - assert!( - gas_used < 50_000, - "Gas used should be low after detained gas restoration, got {}", - gas_used - ); - - // Verify that gas was actually limited during execution - let gas_inspector = &evm.inspector; - let mut saw_limited_gas = false; - gas_inspector.trace.as_ref().unwrap().iterate_with( - |_node_location, _node, _item_location, item| { - let opcode_info = item.borrow(); - if opcode_info.gas_after <= BLOCK_ENV_ACCESS_COMPUTE_GAS { - saw_limited_gas = true; - } - }, - ); - assert!(saw_limited_gas, "Should have seen gas limited to 10k during execution"); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs deleted file mode 100644 index 972e3fce9..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/block_env_access_tracking.rs +++ /dev/null @@ -1,271 +0,0 @@ -//! Tests for the block environment access tracking functionality. - -use ::revm::{context::BlockEnv, ExecuteEvm}; -use alloy_primitives::{address, Bytes, U256}; -use mega_evm::{ - revm::{ - bytecode::opcode::{ - BASEFEE, BLOCKHASH, CALLER, CHAINID, COINBASE, DIFFICULTY, GASLIMIT, GASPRICE, NUMBER, - ORIGIN, POP, PUSH1, STOP, TIMESTAMP, - }, - context::{ContextSetters, ContextTr}, - }, - test_utils::MemoryDatabase, - *, -}; - -/// Test that verifies the EVM correctly tracks block environment access for various opcodes. -/// This comprehensive test checks that the system properly detects and tracks access to different -/// block environment values (NUMBER, TIMESTAMP, COINBASE, DIFFICULTY, GASLIMIT, BASEFEE, BLOCKHASH) -/// while correctly ignoring non-block environment opcodes (CALLER, ORIGIN, GASPRICE, CHAINID). -/// It also verifies the reset functionality works correctly. -#[test] -fn test_block_env_tracking_with_evm() { - let test_cases = vec![ - ("NUMBER", vec![NUMBER, STOP], Some(VolatileDataAccess::BLOCK_NUMBER)), - ("TIMESTAMP", vec![TIMESTAMP, STOP], Some(VolatileDataAccess::TIMESTAMP)), - ("COINBASE", vec![COINBASE, STOP], Some(VolatileDataAccess::COINBASE)), - ("DIFFICULTY", vec![DIFFICULTY, STOP], Some(VolatileDataAccess::PREV_RANDAO)), - ("GASLIMIT", vec![GASLIMIT, STOP], Some(VolatileDataAccess::GAS_LIMIT)), - ("BASEFEE", vec![BASEFEE, STOP], Some(VolatileDataAccess::BASE_FEE)), - ("BLOCKHASH", vec![PUSH1, 0x05, BLOCKHASH, STOP], Some(VolatileDataAccess::BLOCK_HASH)), - // Non-block env opcodes - ("CALLER", vec![CALLER, STOP], None), - ("ORIGIN", vec![ORIGIN, STOP], None), - ("GASPRICE", vec![GASPRICE, STOP], None), - ("CHAINID", vec![CHAINID, STOP], None), - ]; - - for (opcode_name, bytecode, expected_access_type) in test_cases { - println!("Testing opcode: {}", opcode_name); - - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - db.set_account_code(contract_address, bytecode.into()); - - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - // Configure L1BlockInfo to avoid operator fee scalar panic - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - - // Set block number to allow BLOCKHASH to work properly - let block_env = BlockEnv { number: U256::from(10), ..Default::default() }; - context.set_block(block_env); - - let mut evm = MegaEvm::new(context); - - // Ensure we start with no block env access - assert!( - evm.get_block_env_accesses().is_empty(), - "EVM should start with no block env access for {}", - opcode_name - ); - assert_eq!( - evm.get_block_env_accesses().count_block_env_accessed(), - 0, - "EVM should start with no access count for {}", - opcode_name - ); - - // Create transaction - let tx = MegaTransaction { - base: revm::context::TxEnv { - caller: address!("0000000000000000000000000000000000100000"), - kind: revm::primitives::TxKind::Call(contract_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000000000000000u64, - ..Default::default() - }, - ..Default::default() - }; - - // Execute transaction - let result = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(result.is_ok(), "Transaction should succeed for {}", opcode_name); - - // Check if block env was accessed - match expected_access_type { - Some(access_type) => { - assert!( - !evm.get_block_env_accesses().is_empty(), - "Transaction should have accessed block env for {}", - opcode_name - ); - assert!( - evm.get_block_env_accesses().contains(access_type), - "Transaction should have accessed {:?} for {}", - access_type, - opcode_name - ); - - let accesses = evm.get_block_env_accesses(); - if opcode_name == "BLOCKHASH" { - // BLOCKHASH accesses both BlockNumber (to validate range) and BlockHash - assert_eq!( - accesses.count_block_env_accessed(), - 2, - "BLOCKHASH should access exactly two items: BlockNumber and BlockHash" - ); - assert!( - accesses.contains(VolatileDataAccess::BLOCK_NUMBER), - "BLOCKHASH should access BlockNumber for validation" - ); - assert!(accesses.contains(access_type), "BLOCKHASH should access BlockHash"); - } else { - assert_eq!( - accesses.count_block_env_accessed(), - 1, - "Should have exactly one access for {}", - opcode_name - ); - assert!( - accesses.contains(access_type), - "Should have accessed {:?} for {}", - access_type, - opcode_name - ); - } - } - None => { - assert!( - evm.get_block_env_accesses().is_empty(), - "Transaction should NOT have accessed block env for {}", - opcode_name - ); - assert_eq!( - evm.get_block_env_accesses().count_block_env_accessed(), - 0, - "Access count should be zero for {}", - opcode_name - ); - } - } - - // Test reset functionality - evm.reset_volatile_data_access(); - assert!( - evm.get_block_env_accesses().is_empty(), - "Block env access should be reset for {}", - opcode_name - ); - assert_eq!( - evm.get_block_env_accesses().count_block_env_accessed(), - 0, - "Access count should be zero after reset for {}", - opcode_name - ); - } -} - -/// Test that verifies the EVM correctly tracks multiple block environment accesses within a single -/// transaction. This test ensures that when a contract accesses multiple different block -/// environment values (NUMBER, TIMESTAMP, BASEFEE) in one execution, the system correctly tracks -/// all of them and maintains an accurate count of accessed block environment types. -#[test] -fn test_multiple_block_env_accesses() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - - // Contract that accesses multiple block env values: NUMBER, TIMESTAMP, BASEFEE - let contract_code = vec![ - NUMBER, POP, // Access block number, then pop - TIMESTAMP, POP, // Access timestamp, then pop - BASEFEE, POP, // Access basefee, then pop - STOP, - ]; - db.set_account_code(contract_address, contract_code.into()); - - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - // Configure L1BlockInfo to avoid operator fee scalar panic - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - let mut evm = MegaEvm::new(context); - - // Execute transaction - let tx = MegaTransaction { - base: revm::context::TxEnv { - caller: address!("0000000000000000000000000000000000100000"), - kind: revm::primitives::TxKind::Call(contract_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000000000000000u64, - ..Default::default() - }, - ..Default::default() - }; - - let result = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(result.is_ok()); - - // Should have accessed 3 different types - let accesses = evm.get_block_env_accesses(); - assert!(!accesses.is_empty()); - assert_eq!( - accesses.count_block_env_accessed(), - 3, - "Should have accessed 3 different block env types" - ); - - // Check specific accesses - assert!(accesses.contains(VolatileDataAccess::BLOCK_NUMBER)); - assert!(accesses.contains(VolatileDataAccess::TIMESTAMP)); - assert!(accesses.contains(VolatileDataAccess::BASE_FEE)); -} - -/// Test that verifies the block environment access tracking is properly reset between transactions. -/// This test ensures that when a new transaction is executed, the block environment access tracking -/// is correctly reset and can track new accesses for the subsequent transaction, maintaining proper -/// isolation between different transaction executions. -#[test] -fn test_block_env_reset_between_transactions() { - let mut db = MemoryDatabase::default(); - let contract_address = address!("0000000000000000000000000000000000100001"); - db.set_account_code(contract_address, vec![NUMBER, STOP].into()); - - let mut context = MegaContext::new(db, MegaSpecId::MINI_REX); - // Configure L1BlockInfo to avoid operator fee scalar panic - context.chain_mut().operator_fee_scalar = Some(U256::from(0)); - context.chain_mut().operator_fee_constant = Some(U256::from(0)); - let mut evm = MegaEvm::new(context); - - // First transaction - accesses block env - let tx1 = MegaTransaction { - base: revm::context::TxEnv { - caller: address!("0000000000000000000000000000000000100000"), - kind: revm::primitives::TxKind::Call(contract_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000000000000000u64, - ..Default::default() - }, - ..Default::default() - }; - - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1); - assert!(result1.is_ok()); - assert!(!evm.get_block_env_accesses().is_empty(), "First transaction should access block env"); - - // Simulate setting up for a new transaction - let tx2_env = revm::context::TxEnv { - caller: address!("0000000000000000000000000000000000100000"), - kind: revm::primitives::TxKind::Call(contract_address), - data: Bytes::default(), - value: U256::ZERO, - gas_limit: 1000000000000000000u64, - nonce: 0, // Same account should continue with correct nonce - ..Default::default() - }; - let tx2 = MegaTransaction { base: tx2_env, ..Default::default() }; - - // This simulates how the EVM would be used for a new transaction - // Setting tx should automatically reset the block env access - evm.transact_one(tx2).unwrap(); - - // After setting new transaction, flag should be reset automatically - // But since we executed the same contract (NUMBER opcode), it should be accessed again - assert!( - !evm.get_block_env_accesses().is_empty(), - "Block env should be accessed again for second transaction" - ); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs deleted file mode 100644 index fbb69594b..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/block_env_gas_limit.rs +++ /dev/null @@ -1,713 +0,0 @@ -//! Tests for gas limiting after block environment access. -//! -//! These tests verify that accessing block environment data (TIMESTAMP, NUMBER, etc.) -//! immediately limits remaining gas to prevent `DoS` attacks. -//! -//! Key properties tested: -//! 1. Block env opcodes trigger gas limiting (`gas_used` should be small) -//! 2. Detained gas is restored before tx finishes (users only pay for real work) -//! 3. Gas limiting propagates through nested calls -//! 4. Without block env access, no limiting occurs (`gas_used` reflects full work) - -use alloy_evm::Evm; -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - constants::mini_rex::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_COMPUTE_GAS_LIMIT}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ExecutionResult, TxEnv}, - handler::EvmTr, - inspector::NoOpInspector, - Inspector, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CONTRACT: Address = address!("1000000000000000000000000000000000000001"); -const NESTED_CONTRACT: Address = address!("1000000000000000000000000000000000000003"); - -/// Helper to create and execute a transaction with given bytecode -fn execute_bytecode( - db: &mut MemoryDatabase, - gas_limit: u64, -) -> (ExecutionResult, MegaEvm<&mut MemoryDatabase, NoOpInspector, TestExternalEnvs>) -{ - execute_bytecode_with_inspector::(db, gas_limit, NoOpInspector) -} - -/// Helper to create and execute a transaction with given bytecode and gas inspector -/// Helper to create and execute a transaction with given bytecode and gas price, committing state -fn execute_bytecode_with_inspector< - 'a, - INSP: Inspector>, ->( - db: &'a mut MemoryDatabase, - gas_limit: u64, - inspector: INSP, -) -> (ExecutionResult, MegaEvm<&'a mut MemoryDatabase, INSP, TestExternalEnvs>) { - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(db, MegaSpecId::MINI_REX).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - data: Default::default(), - value: U256::ZERO, - gas_limit, - gas_price: 0, - ..Default::default() - }; - - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(inspector); - let result = Evm::transact_commit(&mut evm, tx).unwrap(); - - (result, evm) -} - -/// Checks if the result is a volatile data access out of gas error. -fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool { - matches!( - result, - &ExecutionResult::Halt { reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, .. } - ) -} - -#[test] -fn test_timestamp_limits_gas() { - // TIMESTAMP opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(TIMESTAMP) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(result.is_success(), "Transaction should succeed"); - // With detained gas restoration, gas_used should be much less than gas_limit - // The contract does minimal work (TIMESTAMP, MSTORE, RETURN), so should use < 30K gas - // If detained gas wasn't restored, gas_used would be ~29M - let gas_used = result.gas_used(); - assert!( - gas_used < 30_000, - "gas_used should only reflect real work after TIMESTAMP limiting, but got {}. \ - If > 25M, detained gas was not restored.", - gas_used - ); -} - -#[test] -fn test_number_limits_gas() { - // NUMBER opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(NUMBER) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(result.is_success(), "Transaction should succeed"); - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after NUMBER limiting, got {}", - gas_used - ); -} - -#[test] -fn test_coinbase_limits_gas() { - // COINBASE opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(COINBASE) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after COINBASE limiting, got {}", - gas_used - ); -} - -#[test] -fn test_difficulty_limits_gas() { - // DIFFICULTY/PREVRANDAO opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(DIFFICULTY) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after DIFFICULTY limiting, got {}", - gas_used - ); -} - -#[test] -fn test_gaslimit_limits_gas() { - // GASLIMIT opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(GASLIMIT) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after GASLIMIT limiting, got {}", - gas_used - ); -} - -#[test] -fn test_basefee_limits_gas() { - // BASEFEE opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0u8) - .append(BASEFEE) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let gas_used = result.gas_used(); - - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after BASEFEE limiting, got {}", - gas_used - ); -} - -#[test] -fn test_blockhash_limits_gas() { - // BLOCKHASH opcode should limit remaining gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(0x01u8) // block number - .append(BLOCKHASH) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - assert!(result.is_success(), "Transaction should succeed"); - - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should only reflect real work after BLOCKHASH limiting, got {}", - gas_used - ); -} - -#[test] -fn test_multiple_block_env_accesses() { - // Multiple block env accesses should still limit gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .append(TIMESTAMP) - .append(POP) - .append(NUMBER) - .append(POP) - .append(COINBASE) - .append(POP) - .append(GASLIMIT) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(result.is_success()); - let gas_used = result.gas_used(); - // After first block env access, gas should be limited (verified by small gas_used) - assert!( - gas_used < 100_000, - "Multiple block env accesses should maintain gas limit. gas_used: {}", - gas_used - ); -} - -#[test] -fn test_block_env_access_with_nested_calls() { - // Create a contract that accesses block env and then does more work - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .append(TIMESTAMP) // limits gas immediately - .push_number(0u8) - .append(MSTORE) - // Try to do lots of work after gas is limited (simple loop) - .push_number(100u8) // loop counter - .append(JUMPDEST) // loop start at position ~6 - .push_number(1u8) - .append(SWAP1) - .append(SUB) - .append(DUP1) - .push_number(6u8) // jump back to JUMPDEST - .append(JUMPI) - .append(POP) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let gas_used = result.gas_used(); - assert!( - gas_used < 100_000, - "gas_used should be small after block env access limiting, got {}", - gas_used - ); -} - -#[test] -fn test_no_gas_limit_without_block_env_access() { - // Regular opcodes should NOT limit gas - let mut db = MemoryDatabase::default(); - let bytecode = BytecodeBuilder::default() - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, bytecode); - - let gas_limit = 2_000_000; - let (result, evm) = execute_bytecode(&mut db, gas_limit); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - TX_COMPUTE_GAS_LIMIT, - "Compute gas limit should be the same as the transaction compute gas limit" - ); - - assert!(result.is_success()); - // Without block env access, gas should NOT be limited - let gas_used = result.gas_used(); - assert!( - gas_used < 50_000, - "Regular opcodes should use minimal gas, expected < 50000, got {}", - gas_used - ); -} - -#[test] -fn test_out_of_gas_after_block_env_access() { - // Try to do expensive work after block env access with limited gas - let mut db = MemoryDatabase::default(); - let mut builder = BytecodeBuilder::default() - .append(TIMESTAMP) // limits compute gas to 20M - .append(POP); - // Try to use more than 20M compute gas doing storage writes to unique slots - // Each SSTORE (zero → non-zero, unique slot) costs ~22,100 gas in compute gas - // To exceed 20M: need ~906 SSTOREs. Use 1000 to safely exceed the limit. - // 1000 SSTOREs × 22,100 = 22.1M compute gas (exceeds 20M limit) - for i in 1..=1000 { - builder = builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let bytecode = builder.append(STOP).build(); - db.set_account_code(CONTRACT, bytecode); - - let total_gas = 1_000_000_000_000; - let (result, _) = execute_bytecode(&mut db, total_gas); - - // Should run out of gas - 1000 SSTOREs cost 22.1M compute gas, but only 20M available after - // limiting - assert!( - !result.is_success(), - "Should run out of gas when attempting 1000 SSTOREs (22.1M compute gas) after block env access \ - (20M compute gas limit).", - ); - assert!( - is_volatile_data_access_oog(&result), - "Should run out of gas due to volatile data access" - ); - assert!( - result.gas_used() < total_gas, - "gas_used should be less than {total_gas}, got {}", - result.gas_used() - ); -} - -#[test] -fn test_nested_call_block_env_access_child_oog() { - // Test that child contract runs out of gas when it accesses block env with limited gas - let mut db = MemoryDatabase::default(); - - // Nested contract that accesses TIMESTAMP then tries expensive work - let mut nested_builder = BytecodeBuilder::default() - .append(TIMESTAMP) // limits compute gas immediately to 20M - .append(POP); - // Try to do expensive compute work after block env access (should OOG) - // Each SSTORE (zero → non-zero, unique slot) costs ~22,100 gas in compute gas - // Use 1000 SSTOREs to exceed 20M compute gas limit: 1000 × 22,100 = 22.1M - for i in 1..=1000 { - nested_builder = nested_builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let nested_bytecode = nested_builder.push_number(0u8).push_number(0u8).append(RETURN).build(); - db.set_account_code(NESTED_CONTRACT, nested_bytecode); - - // Parent contract that calls nested contract - let parent_bytecode = BytecodeBuilder::default() - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argSize - .push_number(0u8) // argOffset - .push_number(0u8) // value - .push_address(NESTED_CONTRACT) - .append(GAS) - .append(CALL) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, parent_bytecode); - - let total_gas = 1_000_000_000_000; - let (result, evm) = execute_bytecode(&mut db, total_gas); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(!result.is_success(), "Parent should succeed even if child runs out of gas"); - assert!( - is_volatile_data_access_oog(&result), - "Parent should run out of gas due to volatile data access" - ); - assert!( - result.gas_used() < total_gas, - "gas_used should be less than {total_gas}, got {}", - result.gas_used() - ); -} - -#[test] -fn test_deeply_nested_call_block_env_access() { - // Test multiple levels of nesting: CALLER -> CONTRACT -> NESTED_CONTRACT - // When the deepest contract accesses block env through multiple call frames, - // the gas limit propagates back through all parent frames - let mut db = MemoryDatabase::default(); - - // Deepest nested contract that accesses TIMESTAMP - let nested_bytecode = BytecodeBuilder::default() - .append(TIMESTAMP) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(NESTED_CONTRACT, nested_bytecode); - - // Middle contract that calls NESTED_CONTRACT - let middle_bytecode = BytecodeBuilder::default() - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_address(NESTED_CONTRACT) - .append(GAS) - .append(CALL) - .append(POP) - // Try to do some work after nested call - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, middle_bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - let success = result.is_success(); - let gas_used = result.gas_used(); - assert!(success, "Transaction should succeed"); - // With multiple call frames (2+ levels deep), the gas limit DOES propagate correctly - assert!( - gas_used < 100_000, - "All parent calls should be limited when deeply nested call accesses block env. gas_used: {}", - gas_used - ); - - // Note: We no longer check interpreter gas values via GasInspector. - // The new compute gas limit system doesn't directly modify interpreter gas. - // Instead, compute gas is tracked separately and enforced via AdditionalLimit. -} - -#[test] -fn test_parent_block_env_access_oog_after_nested_call() { - // Test that parent accessing block env runs out of gas when trying expensive work - // even after making a nested call - let mut db = MemoryDatabase::default(); - - // Nested contract that does simple work (no block env access) - let nested_bytecode = BytecodeBuilder::default() - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(NESTED_CONTRACT, nested_bytecode); - - // Parent contract that accesses block env FIRST, then calls nested, then tries expensive work - let mut parent_builder = BytecodeBuilder::default() - .append(TIMESTAMP) // Parent accesses block env - limits parent's compute gas to 20M - .append(POP) - // Make a nested call (should succeed, child is not limited) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_address(NESTED_CONTRACT) - .append(GAS) - .append(CALL) - .append(POP); - // Try to do expensive compute work in parent (should OOG due to parent's own 20M compute limit) - // Each SSTORE (zero → non-zero, unique slot) costs ~22,100 gas in compute gas - // Use 1000 SSTOREs to exceed 20M: 1000 × 22,100 = 22.1M compute gas - for i in 1..=1000 { - parent_builder = parent_builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let parent_bytecode = parent_builder.push_number(0u8).push_number(0u8).append(RETURN).build(); - db.set_account_code(CONTRACT, parent_bytecode); - - let total_gas = 1_000_000_000_000; - let (result, evm) = execute_bytecode(&mut db, total_gas); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(!result.is_success(), "Parent should run out of gas when attempting 1000 SSTOREs (22.1M compute gas) after accessing block env itself (20M compute limit)."); - assert!( - is_volatile_data_access_oog(&result), - "Parent should run out of gas due to volatile data access" - ); - assert!( - result.gas_used() < total_gas, - "gas_used should be less than {total_gas}, got {}", - result.gas_used() - ); -} - -#[test] -fn test_nested_call_already_limited_no_further_restriction() { - // Test that if parent already accessed block env, nested call doesn't make it worse - let mut db = MemoryDatabase::default(); - - // Nested contract that also accesses TIMESTAMP - let nested_bytecode = BytecodeBuilder::default() - .append(NUMBER) - .push_number(0u8) - .append(MSTORE) - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(NESTED_CONTRACT, nested_bytecode); - - // Parent contract that accesses block env FIRST, then calls nested - let parent_bytecode = BytecodeBuilder::default() - .append(TIMESTAMP) // Parent accesses block env first - .append(POP) - // Now make nested call - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_number(0u8) - .push_address(NESTED_CONTRACT) - .append(GAS) - .append(CALL) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - db.set_account_code(CONTRACT, parent_bytecode); - - let (result, evm) = execute_bytecode(&mut db, 30_000_000); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(result.is_success(), "Transaction should succeed"); -} - -#[test] -fn test_volatile_data_access_oog_does_not_consume_all_gas() { - // This test verifies that when a transaction runs out of gas due to volatile data access - // (VolatileDataAccessOutOfGas), it does NOT consume all gas like a regular OutOfGas. - // Instead, detained gas is refunded and gas_used reflects only actual work performed. - let mut db = MemoryDatabase::default(); - - // Contract that accesses TIMESTAMP then tries expensive work that exceeds the limit - let mut builder = BytecodeBuilder::default() - .append(TIMESTAMP) // Limits compute gas to 20M - .append(POP); - // Try to do 1000 SSTOREs (22.1M compute gas needed, but only 20M available after limiting) - // Each SSTORE (zero → non-zero, unique slot) costs ~22,100 gas in compute gas - // Note: Using push_number(i as u8) means we only get 256 unique slots (0-255), - // so slots wrap around. But this is still sufficient for the test. - // 1000 SSTOREs × 22,100 = 22.1M compute gas (exceeds 20M limit) - for i in 1..=1000 { - builder = builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let bytecode = builder.push_number(0u8).push_number(0u8).append(RETURN).build(); - db.set_account_code(CONTRACT, bytecode); - - let total_gas = 1_000_000_000_000; - let (result, evm) = execute_bytecode(&mut db, total_gas); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - BLOCK_ENV_ACCESS_COMPUTE_GAS - ); - - assert!(!result.is_success(), "Transaction should fail due to exceeding compute gas limit."); - assert!( - is_volatile_data_access_oog(&result), - "Transaction should fail due to volatile data access" - ); - - let gas_used = result.gas_used(); - assert!(gas_used < total_gas, "gas_used should be less than {total_gas}, got {}", gas_used); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs deleted file mode 100644 index 59a0a1598..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/compute_gas_limit.rs +++ /dev/null @@ -1,1161 +0,0 @@ -//! Tests for the compute gas limit feature of the `MegaETH` EVM. -//! -//! Tests the compute gas limit functionality that tracks computational work -//! separately from storage and data costs. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - precompile::{ - bn128::pair, - hash::{RIPEMD160, SHA256}, - secp256k1::ECRECOVER, - }, -}; - -// ============================================================================ -// CONSTANTS -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100002"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified compute gas limit. -fn transact( - spec: MegaSpecId, - db: &mut CacheDB, - compute_gas_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(compute_gas_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let compute_gas_used = ctx.additional_limit.borrow().get_usage().compute_gas; - - Ok((r, compute_gas_used)) -} - -/// Helper to check if the result is a compute gas limit exceeded halt. -fn is_compute_gas_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::ComputeGasLimitExceeded { .. }, .. } - ) -} - -/// Helper to extract compute gas limit info from halt reason. -fn get_compute_gas_limit_info(result: &ResultAndState) -> Option<(u64, u64)> { - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::ComputeGasLimitExceeded { limit, actual }, - .. - } => Some((*limit, *actual)), - _ => None, - } -} - -// ============================================================================ -// BASIC TRACKING TESTS -// ============================================================================ - -#[test] -fn test_empty_contract_compute_gas() { - let bytecode = BytecodeBuilder::default().append(PUSH0).append(STOP).build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, 1_000_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Should have some gas from transaction intrinsic cost and opcodes - assert!(compute_gas_used > 0); - assert!(compute_gas_used < 50_000); // Should be small for simple operations - assert_eq!(compute_gas_used, result.result.gas_used()); -} - -#[test] -fn test_simple_arithmetic_compute_gas() { - let bytecode = BytecodeBuilder::default() - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .append(POP) - .push_number(3u8) - .push_number(4u8) - .append(MUL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, 1_000_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Should track gas for all arithmetic operations - assert!(compute_gas_used > 0); - assert_eq!(compute_gas_used, result.result.gas_used()); -} - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -#[test] -fn test_compute_gas_limit_not_exceeded() { - // Need enough operations so execution gas > 21,000 for meaningful test - let mut bytecode = BytecodeBuilder::default(); - for _ in 0..2000 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(1_000_000) // High tx gas limit for validation - .build_fill(); - - // First, measure the actual gas used - let (_r, actual_gas) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Now set limit to exactly the actual gas used - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, actual_gas, tx).unwrap(); - - // Should succeed since we're exactly at the limit (uses > not >=) - assert!( - result.result.is_success(), - "Transaction should succeed with gas_used={} and limit={}", - compute_gas_used, - actual_gas - ); - assert_eq!(compute_gas_used, actual_gas); -} - -#[test] -fn test_compute_gas_limit_exceeded() { - let mut bytecode = BytecodeBuilder::default(); - // Add many operations to ensure execution gas > 21,000 (validation requirement) - // Need ~2000 iterations × 11 gas = 22,000 gas for execution - for _ in 0..2000 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(1_000_000) // High tx gas limit for validation - .build_fill(); - - // First measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Compute gas tracks only opcode execution gas (intrinsic gas is reset after validation) - // 2000 iterations of (PUSH1 + PUSH1 + ADD + POP) = 2000 × 11 = 22,000 gas - assert!(actual_usage >= 22_000, "Expected at least 22,000 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Set compute gas limit below execution needs (will pass 21,000 validation) - let limit = actual_usage - 1000; - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded - assert!( - is_compute_gas_limit_exceeded(&result), - "Expected compute gas limit exceeded, actual gas: {}, limit: {}, measured: {}", - compute_gas_used, - limit, - actual_usage - ); - assert!(compute_gas_used > limit); - - // Verify the halt reason contains correct info - let (halt_limit, halt_actual) = get_compute_gas_limit_info(&result).unwrap(); - assert_eq!(halt_limit, limit); - assert!(halt_actual > halt_limit); -} - -// ============================================================================ -// INSTRUCTION COVERAGE TESTS -// ============================================================================ - -#[test] -fn test_compute_gas_storage_operations() { - let bytecode = BytecodeBuilder::default() - .push_number(0xFFu8) - .append(PUSH0) // key - .append(SSTORE) - .append(PUSH0) // key - .append(SLOAD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000_000).build_fill(); - - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, 100_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Storage operations are expensive - assert!(compute_gas_used > 20_000); - assert!(compute_gas_used < 100_000); -} - -#[test] -fn test_compute_gas_memory_operations() { - let bytecode = BytecodeBuilder::default() - .mstore(0x40, vec![0xFFu8]) - .push_number(0x40u8) - .append(MLOAD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000_000).build_fill(); - - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, 100_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Memory operations including expansion cost - assert!(compute_gas_used > 0); - assert!(compute_gas_used < 100_000); -} - -#[test] -fn test_compute_gas_log_operations() { - let bytecode = BytecodeBuilder::default() - .push_number(0x20u8) - .append(PUSH0) // offset - .append(LOG0) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, 30_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Should track gas (intrinsic + log operations) - assert!(compute_gas_used > 0); - assert!(compute_gas_used < 30_000); -} - -// ============================================================================ -// NESTED CALL TESTS -// ============================================================================ - -#[test] -fn test_nested_call_compute_gas_accumulation() { - // Callee does some work - let mut callee_bytecode = BytecodeBuilder::default(); - for _ in 0..100 { - callee_bytecode = callee_bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let callee_bytecode = callee_bytecode.append(STOP).build(); - - // Caller does work and calls callee - let mut caller_bytecode = BytecodeBuilder::default(); - // Do some work - for _ in 0..10 { - caller_bytecode = caller_bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - // CALL callee: gas, address, value, argsOffset, argsSize, retOffset, retSize - caller_bytecode = caller_bytecode - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - caller_bytecode = caller_bytecode.push_address(CONTRACT2); // address - caller_bytecode = caller_bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP); - - let caller_bytecode = caller_bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, caller_bytecode) - .account_code(CONTRACT2, callee_bytecode); - - // Get baseline gas for just calling callee - let tx_callee = TxEnvBuilder::new().caller(CALLER).call(CONTRACT2).build_fill(); - let (_, callee_gas) = transact(MegaSpecId::MINI_REX, &mut db, 10_000_000, tx_callee).unwrap(); - - // Call with nested call - let tx_caller = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - let (result, total_gas) = - transact(MegaSpecId::MINI_REX, &mut db, 10_000_000, tx_caller).unwrap(); - - assert!(result.result.is_success()); - // Total gas should be more than just callee gas - assert!(total_gas > callee_gas); -} - -#[test] -fn test_compute_gas_limit_exceed_in_nested_call() { - // Callee with many operations (need execution gas > 21,000 for validation) - let mut callee_bytecode = BytecodeBuilder::default(); - for _ in 0..2000 { - callee_bytecode = callee_bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let callee_bytecode = callee_bytecode.append(STOP).build(); - - // Caller that calls callee - let mut caller_bytecode = BytecodeBuilder::default() - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - caller_bytecode = caller_bytecode.push_address(CONTRACT2); - let caller_bytecode = - caller_bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, caller_bytecode.clone()) - .account_code(CONTRACT2, callee_bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(10_000_000) // High tx gas limit for validation - .build_fill(); - - // First measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Compute gas includes call overhead + callee operations - assert!(actual_usage >= 22_000, "Expected at least 22,000 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, caller_bytecode) - .account_code(CONTRACT2, callee_bytecode); - - // Set low compute gas limit - should exceed in nested call - let limit = actual_usage - 1000; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded - assert!(is_compute_gas_limit_exceeded(&result)); - assert!(result.result.gas_used() < 1_000_000); -} - -// ============================================================================ -// MULTI-DIMENSIONAL LIMIT TESTS -// ============================================================================ - -#[test] -fn test_correct_halt_reason_compute_gas() { - let mut bytecode = BytecodeBuilder::default(); - // Need execution gas > 21,000 for validation - for _ in 0..2000 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(10_000_000) // High tx gas limit for validation - .build_fill(); - - // First measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Compute gas tracks only opcode execution gas (intrinsic gas is reset after validation) - // 2000 iterations of (PUSH1 + PUSH1 + ADD + POP) = 2000 × 11 = 22,000 gas - assert!(actual_usage >= 22_000, "Expected at least 22,000 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Set limit just below actual - let set_limit = actual_usage - 1000; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, set_limit, tx).unwrap(); - - // Verify correct halt reason - assert!(is_compute_gas_limit_exceeded(&result)); - - let (limit, actual) = get_compute_gas_limit_info(&result).unwrap(); - assert_eq!(limit, set_limit); - assert!(actual > limit); -} - -// ============================================================================ -// TRANSACTION RESET TESTS -// ============================================================================ - -#[test] -fn test_compute_gas_resets_across_transactions() { - let bytecode = BytecodeBuilder::default() - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // First transaction - let tx1 = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - let (result1, gas1) = transact(MegaSpecId::MINI_REX, &mut db, 10_000_000, tx1).unwrap(); - - assert!(result1.result.is_success()); - - // Second transaction - gas should reset, not accumulate - let tx2 = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - let (result2, gas2) = transact(MegaSpecId::MINI_REX, &mut db, 10_000_000, tx2).unwrap(); - - assert!(result2.result.is_success()); - - // Gas should be similar for both transactions (reset between) - // Allow some variance due to warm/cold storage access - let variance = gas1.max(gas2) - gas1.min(gas2); - assert!(variance < gas1 / 10, "Gas variance too large: {} vs {}", gas1, gas2); -} - -/// Test that compute gas limit is reset between transactions after volatile data access in Rex1. -/// -/// Starting from Rex1, the compute gas limit is reset between transactions. This verifies the -/// fix for the bug where `set_compute_gas_limit()` would lower the limit when volatile data -/// (like oracle) was accessed, but the lowered limit would persist incorrectly to subsequent -/// transactions on the SAME EVM instance. -/// -/// The test uses a contract that consumes >1M compute gas for TX2. Without the fix (i.e., -/// pre-Rex1), TX2 would fail with `ComputeGasLimitExceeded` because the limit would be stuck at 1M -/// from the oracle access in TX1. -#[test] -fn test_compute_gas_limit_resets_after_volatile_access_rex1() { - use mega_evm::{ - constants::mini_rex::ORACLE_ACCESS_COMPUTE_GAS, MegaTransaction, ORACLE_CONTRACT_ADDRESS, - }; - use revm::ExecuteEvm; - - // Contract 1: Calls the oracle, which lowers compute_gas_limit to 1M - let oracle_caller = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - // Contract 2: Expensive contract that uses >1M compute gas via SHA3 operations. - // Each SHA3 with 32 bytes costs 36 gas + 6 per word = 42 gas. But the memory expansion - // and iterations add up. We use a loop of 30000 SHA3 operations to exceed 1M compute gas. - // Without the fix, this would fail because the limit would be stuck at 1M. - let mut expensive_builder = BytecodeBuilder::default(); - // Store a value in memory first - expensive_builder = - expensive_builder.push_number(0xdeadbeefu32).push_number(0u8).append(MSTORE); - // Do many SHA3 operations on the same memory region - for _ in 0..30000 { - expensive_builder = expensive_builder - .push_number(32u8) // size - .push_number(0u8) // offset - .append(KECCAK256) - .append(POP); // discard result - } - let expensive_contract = expensive_builder.append(STOP).build(); - - let compute_gas_limit: u64 = 10_000_000; // 10M - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_code(CONTRACT, oracle_caller) - .account_code(CONTRACT2, expensive_contract); - - // Create a SINGLE EVM instance that will be used for both transactions - // Use REX1 spec where limits are reset between transactions - let mut context = MegaContext::new(db, MegaSpecId::REX1).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(compute_gas_limit) - .with_oracle_access_compute_gas_limit(ORACLE_ACCESS_COMPUTE_GAS), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - - // TX1: Call oracle contract - this lowers compute_gas_limit to 1M - let tx1 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result1 = alloy_evm::Evm::transact_raw(&mut evm, tx1).unwrap(); - assert!(result1.result.is_success(), "TX1 should succeed"); - - // Verify TX1 lowered the compute_gas_limit to oracle limit - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "TX1 should have lowered compute_gas_limit to oracle access limit" - ); - - // TX2: Expensive contract that uses >1M compute gas on the SAME EVM instance. - // If the limit wasn't reset, this would fail with ComputeGasLimitExceeded. - let tx2 = MegaTransaction { - base: TxEnvBuilder::new().caller(CALLER).call(CONTRACT2).build_fill(), - enveloped_tx: Some(Bytes::new()), - ..Default::default() - }; - let result2 = evm.transact_one(tx2).unwrap(); - - // Get the compute gas used by TX2 - let compute_gas_used = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - - // Verify TX2 used more than the oracle limit (1M) - assert!( - compute_gas_used > ORACLE_ACCESS_COMPUTE_GAS, - "TX2 should use more compute gas than oracle limit: {} > {}", - compute_gas_used, - ORACLE_ACCESS_COMPUTE_GAS - ); - - // TX2 should succeed because the limit was reset to 10M (Rex1 behavior) - assert!( - result2.is_success(), - "TX2 should succeed because compute_gas_limit was reset to {}. Used {} gas. \ - Without Rex1, it would fail because the limit would be stuck at {}", - compute_gas_limit, - compute_gas_used, - ORACLE_ACCESS_COMPUTE_GAS - ); - - // Verify the limit is at the original value (not stuck at oracle limit) - let actual_limit = evm.ctx_ref().additional_limit.borrow().compute_gas_limit(); - assert_eq!( - actual_limit, compute_gas_limit, - "compute_gas_limit should be reset to original value ({}), not stuck at oracle limit ({})", - compute_gas_limit, ORACLE_ACCESS_COMPUTE_GAS - ); -} - -// ============================================================================ -// SPEC COMPARISON TESTS -// ============================================================================ - -#[test] -fn test_compute_gas_tracked_in_mini_rex() { - let bytecode = BytecodeBuilder::default() - .push_number(1u8) - .push_number(2u8) - .append(ADD) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, 10_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // In MINI_REX, compute gas should be tracked - assert!(compute_gas_used > 0); -} - -// ============================================================================ -// PRECOMPILE TESTS -// ============================================================================ - -#[test] -fn test_precompile_compute_gas_limit_exceeded() { - // SHA256 precompile at address 0x02 - // Gas cost: 60 + 12 * (data_size / 32) for SHA256 - // With 32 bytes: 60 + 12 = 72 gas for precompile - // Plus call overhead and setup opcodes - - // Contract that calls SHA256 precompile - let mut bytecode = BytecodeBuilder::default() - // Push call parameters: gas, addr, value, argsOffset, argsSize, retOffset, retSize - .push_number(32u8) // retSize (32 bytes for SHA256 output) - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize (32 bytes input) - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*SHA256.address()); // address - bytecode = bytecode - .push_number(0xFFFFu16) // gas for call - .append(CALL) - .append(POP) - .append(STOP); - - let bytecode = bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(1_000_000) // High tx gas limit - .build_fill(); - - // First measure actual compute gas usage with unlimited compute gas - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Should have some compute gas usage (intrinsic + opcodes + precompile) - assert!(actual_usage > 100, "Expected at least 100 gas, got {}", actual_usage); - - // Reset db to ensure consistent state - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Set compute gas limit below what's needed - should exceed - let limit = actual_usage - 50; - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded - assert!( - is_compute_gas_limit_exceeded(&result), - "Expected compute gas limit exceeded, actual gas: {}, limit: {}", - compute_gas_used, - limit - ); - assert!(compute_gas_used > limit); -} - -#[test] -fn test_multiple_precompiles_accumulate_compute_gas() { - // Test calling multiple precompiles in sequence - // ECRECOVER (0x01), SHA256 (0x02), RIPEMD160 (0x03) - - // Contract that calls multiple precompiles - let mut bytecode = BytecodeBuilder::default(); - - // Call SHA256 first - bytecode = bytecode - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*SHA256.address()); - bytecode = bytecode.push_number(0xFFFFu16).append(CALL).append(POP); - - // Call RIPEMD160 second - bytecode = bytecode - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*RIPEMD160.address()); - bytecode = bytecode.push_number(0xFFFFu16).append(CALL).append(POP); - - // Call ECRECOVER third (more expensive) - bytecode = bytecode - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(128u8) // argsSize (ECRECOVER needs 128 bytes) - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*ECRECOVER.address()); - bytecode = bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP); - - let bytecode = bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // Measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Should have significant gas from multiple precompiles - assert!( - actual_usage > 500, - "Expected at least 500 gas for multiple precompiles, got {}", - actual_usage - ); - - // Reset db - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Set limit to fail mid-sequence (after first precompile but before all complete) - // Need to ensure limit is high enough to pass validation (> 21,000) - let limit = actual_usage - 200; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded - assert!(is_compute_gas_limit_exceeded(&result)); -} - -#[test] -fn test_expensive_precompile_near_limit() { - // ECPAIRING (0x08) is very expensive - // Gas cost: 45000 * k + 34000 where k is number of pairs - // With minimal input (k=1): 45000 + 34000 = 79000 gas - - // Contract that calls ECPAIRING - let mut bytecode = BytecodeBuilder::default() - .push_number(32u8) // retSize (returns 32 bytes: 0 or 1) - .push_number(0u8) // retOffset - .push_number(192u8) // argsSize (192 bytes for one pair: 64 + 128) - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(pair::ADDRESS); - bytecode = bytecode - .push_number(0xFFFFFFu32) // Need high gas for expensive precompile - .append(CALL) - .append(POP) - .append(STOP); - - let bytecode = bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(10_000_000).build_fill(); - - // Measure actual usage - let (r, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Should use significant gas for expensive precompile - assert!( - actual_usage > 50_000 || !r.result.is_success(), - "Expected at least 50,000 gas for ECPAIRING, got {}", - actual_usage - ); - - // Reset db - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CONTRACT, bytecode); - - // Set limit just below what one call needs - let limit = if actual_usage > 10_000 { actual_usage - 5_000 } else { 30_000 }; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded if the precompile succeeded in measurement - if r.result.is_success() { - assert!(is_compute_gas_limit_exceeded(&result)); - } -} - -#[test] -fn test_precompile_in_nested_call_with_compute_limit() { - // Callee calls SHA256 precompile - let mut callee_bytecode = BytecodeBuilder::default() - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - callee_bytecode = callee_bytecode.push_address(*SHA256.address()); - callee_bytecode = callee_bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP); - - let callee_bytecode = callee_bytecode.build(); - - // Caller does some work then calls callee - let mut caller_bytecode = BytecodeBuilder::default(); - for _ in 0..10 { - caller_bytecode = caller_bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - - // Call callee - caller_bytecode = caller_bytecode - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - caller_bytecode = caller_bytecode.push_address(CONTRACT2); - caller_bytecode = caller_bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP); - - let caller_bytecode = caller_bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, caller_bytecode.clone()) - .account_code(CONTRACT2, callee_bytecode.clone()); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // Measure actual usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Should track gas through nested call with precompile - assert!(actual_usage > 200, "Expected at least 200 gas, got {}", actual_usage); - - // Reset db - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, caller_bytecode) - .account_code(CONTRACT2, callee_bytecode); - - // Set limit to fail during precompile in nested call - let limit = actual_usage - 50; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, limit, tx).unwrap(); - - // Should halt with compute gas limit exceeded - assert!(is_compute_gas_limit_exceeded(&result)); -} - -#[test] -fn test_mixed_opcodes_and_precompiles_compute_gas() { - // Mix arithmetic operations with precompile calls - let mut bytecode = BytecodeBuilder::default(); - - // Do some arithmetic - for _ in 0..100 { - bytecode = bytecode.push_number(1u8).push_number(2u8).append(ADD).append(POP); - } - - // Call SHA256 - bytecode = bytecode - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*SHA256.address()); - bytecode = bytecode.push_number(0xFFFFu16).append(CALL).append(POP); - - // Do more arithmetic - for _ in 0..100 { - bytecode = bytecode.push_number(3u8).push_number(4u8).append(MUL).append(POP); - } - - bytecode = bytecode.append(STOP); - let bytecode = bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // Should successfully track both opcodes and precompile - let (result, compute_gas_used) = transact(MegaSpecId::MINI_REX, &mut db, 100_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Should track gas from both arithmetic and precompile - // 200 iterations of simple ops + precompile call - assert!(compute_gas_used > 2_000, "Expected at least 2,000 gas, got {}", compute_gas_used); - assert!(compute_gas_used < 100_000); -} - -#[test] -fn test_precompile_exact_compute_gas_limit() { - // Test that precompile succeeds with exact compute gas limit - let mut bytecode = BytecodeBuilder::default() - .push_number(32u8) // retSize - .push_number(0u8) // retOffset - .push_number(32u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8); // value - bytecode = bytecode.push_address(*SHA256.address()); - bytecode = bytecode.push_number(0xFFFFu16).append(CALL).append(POP).append(STOP); - - let bytecode = bytecode.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // Measure exact usage - let (_, actual_usage) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Reset db - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Set limit to exactly what's needed (should succeed since check uses > not >=) - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, actual_usage, tx).unwrap(); - - assert!( - result.result.is_success(), - "Should succeed with exact limit. Used: {}, Limit: {}", - compute_gas_used, - actual_usage - ); - assert_eq!(compute_gas_used, actual_usage); -} - -// ============================================================================ -// INITIAL GAS LIMIT TESTS -// ============================================================================ - -#[test] -fn test_initial_gas_exceeds_compute_gas_limit() { - // Test that a transaction with sufficient tx gas limit but whose initial gas - // (intrinsic gas) alone exceeds the compute gas limit is halted (not rejected). - // This should produce a receipt with status=0. - - let bytecode = BytecodeBuilder::default().append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - // Transaction with high tx gas limit - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(100_000) // Enough for tx validation - .build_fill(); - - // Set compute gas limit to less than intrinsic gas (21,000) - // This should cause the transaction to halt during first frame init - let compute_gas_limit = 20_000; - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, compute_gas_limit, tx).unwrap(); - - // Should halt (not reject), producing a receipt - assert!(is_compute_gas_limit_exceeded(&result)); - - // Verify the halt reason contains correct info - let (halt_limit, halt_actual) = get_compute_gas_limit_info(&result).unwrap(); - assert_eq!(halt_limit, compute_gas_limit); - assert!(halt_actual > halt_limit); - assert_eq!(compute_gas_used, halt_actual); -} - -#[test] -fn test_initial_gas_with_calldata_exceeds_compute_gas_limit() { - // Test transaction where initial gas with calldata costs exceeds compute limit - - let bytecode = BytecodeBuilder::default().append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CONTRACT, bytecode.clone()); - - // Transaction with large calldata to increase initial gas - // 1000 bytes of non-zero data - let calldata = Bytes::from(vec![1u8; 1000]); - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CONTRACT) - .data(calldata) - .gas_limit(10_000_000) // Enough for tx validation - .build_fill(); - - // First, measure actual initial gas with unlimited compute limit - let (_, actual_initial_gas) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, tx.clone()).unwrap(); - - // Reset db - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CONTRACT, bytecode); - - // Set compute gas limit to less than initial gas - let compute_gas_limit = actual_initial_gas - 10_000; - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, compute_gas_limit, tx).unwrap(); - - // Should halt (not reject), producing a receipt - assert!(is_compute_gas_limit_exceeded(&result)); - - // Verify the halt reason contains correct info - let (halt_limit, halt_actual) = get_compute_gas_limit_info(&result).unwrap(); - assert_eq!(halt_limit, compute_gas_limit); - assert!(halt_actual > halt_limit); - assert_eq!(compute_gas_used, halt_actual); -} - -// ============================================================================ -// EDGE CASE TESTS -// ============================================================================ - -#[test] -fn test_compute_gas_limit_zero() { - let bytecode = BytecodeBuilder::default().append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - // With zero compute gas limit, should halt (not reject) because initial gas exceeds limit - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, 0, tx).unwrap(); - assert!(is_compute_gas_limit_exceeded(&result)); -} - -#[test] -fn test_compute_gas_limit_one() { - let bytecode = BytecodeBuilder::default().append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).build_fill(); - - // With limit of 1, should halt (not reject) because initial gas exceeds limit - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, 1, tx).unwrap(); - assert!(is_compute_gas_limit_exceeded(&result)); -} - -#[test] -fn test_compute_gas_high_usage() { - let mut bytecode = BytecodeBuilder::default(); - // Add many operations - for _ in 0..1000 { - bytecode = bytecode.append(PUSH1).append(1).append(PUSH1).append(2).append(ADD).append(POP); - } - let bytecode = bytecode.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(100_000_000)) - .account_code(CONTRACT, bytecode); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - - let (result, compute_gas_used) = - transact(MegaSpecId::MINI_REX, &mut db, 1_000_000_000, tx).unwrap(); - - assert!(result.result.is_success()); - // Should use substantial compute gas (intrinsic gas is reset after validation) - // 1000 iterations × 11 gas = 11,000 gas - assert!(compute_gas_used >= 21_000, "Expected at least 10,000 gas, got {}", compute_gas_used); -} - -#[test] -fn test_volatile_data_access_with_non_restrictive_detention_reports_compute_gas_limit() { - // When volatile data is accessed but the detention limit is NOT more restrictive than the - // per-tx compute gas limit, exceeding the per-tx compute gas limit should report - // ComputeGasLimitExceeded, NOT VolatileDataAccessOutOfGas. - // - // The `transact` helper uses `EvmTxRuntimeLimits::no_limits()` which sets volatile access - // limits to u64::MAX, so detention is never restrictive. - - // Contract that accesses TIMESTAMP (volatile data) then does expensive work - let mut builder = BytecodeBuilder::default() - .append(TIMESTAMP) // Access volatile data - .append(POP); - // Do enough SSTOREs to exceed the compute gas limit - // Each SSTORE (zero -> non-zero) costs ~22,100 compute gas - // 1000 SSTOREs x 22,100 = 22.1M compute gas - for i in 1..=1000u32 { - builder = builder.push_number(i).push_number(i).append(SSTORE); - } - let bytecode = builder.append(STOP).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000u64)) - .account_code(CONTRACT, bytecode); - - let tx = - TxEnvBuilder::new().caller(CALLER).call(CONTRACT).gas_limit(1_000_000_000_000).build_fill(); - - // Set compute gas limit to 20M (will be exceeded by 22.1M of SSTOREs) - let compute_gas_limit = 19_000_000; - let (result, _) = transact(MegaSpecId::MINI_REX, &mut db, compute_gas_limit, tx).unwrap(); - - // Should halt with ComputeGasLimitExceeded, NOT VolatileDataAccessOutOfGas - assert!( - is_compute_gas_limit_exceeded(&result), - "Expected ComputeGasLimitExceeded when detention is not restrictive, got {:?}", - result.result - ); - - let (limit, actual) = get_compute_gas_limit_info(&result).unwrap(); - assert_eq!(limit, compute_gas_limit); - assert!(actual > limit); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/gas.rs b/crates/mega-evm/tests/_pending/mini_rex/gas.rs deleted file mode 100644 index 9b93e3158..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/gas.rs +++ /dev/null @@ -1,536 +0,0 @@ -//! Tests for gas costs in the Mega EVM. - -use std::convert::Infallible; - -use alloy_primitives::{address, keccak256, Bytes, TxKind, U256}; -use mega_evm::{ - constants::{self, mini_rex::SSTORE_SET_STORAGE_GAS}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EVMError, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use revm::{ - bytecode::opcode::{CALL, CREATE, CREATE2, GAS, LOG0, PUSH0}, - context::{result::ResultAndState, ContextTr, JournalTr, TxEnv}, - interpreter::{CallInputs, CallOutcome}, - primitives::Address, - Inspector, -}; - -const CALLER: Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: Address = address!("1000000000000000000000000000000000000001"); -const NESTED_CALLEE: Address = address!("1000000000000000000000000000000000000002"); - -/// Executes a transaction on the EVM. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - caller: Address, - callee: Option
, - data: Bytes, - value: U256, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.clone().into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller, - kind: callee.map_or(TxKind::Create, TxKind::Call), - data, - value, - gas_limit: 1000000000000000000, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -enum UpdateMode { - /// Set a non-zero value when the original value is zero - Set, - /// Set a non-zero value when the original value is non-zero - Reset, - /// Set a zero value when the original value is non-zero - Clear, -} - -/// Executes an SSTORE operation test case, verifying gas usage for different storage write -/// scenarios. -/// -/// # Arguments -/// -/// * `spec` - The `MegaSpecId` specifying the EVM spec to use. -/// * `mode` - The `UpdateMode` indicating the type of storage operation: -/// - `Set`: Set a non-zero value to an originally zero storage slot. -/// - `Reset`: Set a non-zero value to a non-zero storage slot. -/// - `Clear`: Set a zero value to a non-zero storage slot. -/// * `expansion_times` - The number of times the storage bucket should be expanded (affects gas -/// cost). -/// * `expected_gas_used` - The expected amount of gas that should be used by the transaction. -/// -/// This function sets up a contract that performs an SSTORE operation, configures the storage -/// and bucket meta as needed, executes the transaction, and asserts that the gas used matches -/// the expected value. -fn sstore_test_case( - spec: MegaSpecId, - mode: UpdateMode, - expansion_times: u64, - expected_gas_used: u64, -) { - let mut db = MemoryDatabase::default(); - - // Test address and storage slot - let storage_key = U256::from(0); - let storage_value = match mode { - UpdateMode::Set | UpdateMode::Reset => U256::from(6342), - UpdateMode::Clear => U256::from(0), - }; - let bucket_id = TestExternalEnvs::::bucket_id_for_slot(CALLEE, storage_key); - // An external envs with the given bucket capacity - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * (expansion_times + 1)); - - // a contract that stores a value to the storage slot - let bytecode = BytecodeBuilder::default().sstore(storage_key, storage_value).stop().build(); - db.set_account_code(CALLEE, bytecode); - if matches!(mode, UpdateMode::Clear | UpdateMode::Reset) { - db.set_account_storage(CALLEE, storage_key, U256::from(2333)); - } - - let res = transact( - spec, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Default::default(), - U256::ZERO, - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes an ether transfer test case, verifying gas usage for account creation and bucket -/// expansion scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `mode`: The `UpdateMode` indicating whether the transfer is to a new account (`Set`) or an -/// existing one (`Reset`). -/// - `expansion_times`: Number of times to expand the storage bucket (affects gas cost for new -/// account creation). -/// - `expected_gas_used`: The expected gas usage for the transfer, including any additional costs. -/// -/// # Panics -/// Panics if `mode` is not `Set` or `Reset`. -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn ether_transfer_test_case( - spec: MegaSpecId, - mode: UpdateMode, - expansion_times: u64, - expected_gas_used: u64, -) { - assert!(matches!(mode, UpdateMode::Set | UpdateMode::Reset), "Mode must be Set or Reset"); - - let mut db = MemoryDatabase::default(); - - // Determine the bucket for the callee and set up the external envs with the required capacity. - let bucket_id = TestExternalEnvs::::bucket_id_for_account(CALLEE); - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * (expansion_times + 1)); - - // Allocate initial balance to the caller. - db.set_account_balance(CALLER, U256::from(1000)); - // If testing transfer to an existing account, allocate balance to the callee as well. - if matches!(mode, UpdateMode::Reset) { - db.set_account_balance(CALLEE, U256::from(2333)); - } - - // Perform the ether transfer (1 wei) from caller to callee. - let res = transact( - spec, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Default::default(), - U256::from(1), - ) - .unwrap(); - - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a nested ether transfer test case, verifying gas usage for account creation and bucket -/// expansion scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `mode`: The `UpdateMode` indicating whether the transfer is to a new account (`Set`) or an -/// existing one (`Reset`). -/// - `expansion_times`: Number of times to expand the storage bucket (affects gas cost for new -/// account creation). -/// - `expected_gas_used`: The expected gas usage for the transfer, including any additional costs. -/// -/// # Panics -/// Panics if `mode` is not `Set` or `Reset`. -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn nested_ether_transfer_test_case( - spec: MegaSpecId, - mode: UpdateMode, - expansion_times: u64, - expected_gas_used: u64, -) { - assert!(matches!(mode, UpdateMode::Set | UpdateMode::Reset), "Mode must be Set or Reset"); - - let mut db = MemoryDatabase::default(); - - // Test address and storage slot - let bucket_id = TestExternalEnvs::::bucket_id_for_account(NESTED_CALLEE); - // An external envs with the given bucket capacity - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * (expansion_times + 1)); - - // allocate some balance to callee, which will transfer the ether to the nested callee - db.set_account_balance(CALLEE, U256::from(1000)); - if matches!(mode, UpdateMode::Reset) { - db.set_account_balance(NESTED_CALLEE, U256::from(2333)); - } - - // set the code of the calee that transfers ether to the nested callee - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // args and returns memory - .push_number(1_u8) // value: 1 wei - .push_address(NESTED_CALLEE) // callee - .append(GAS) - .append(CALL) - .stop() - .build(); - db.set_account_code(CALLEE, bytecode); - - // transfer 1 wei from caller to callee - let res = transact( - spec, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Default::default(), - Default::default(), - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a create contract test case, verifying gas usage for account creation and bucket -/// expansion scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `expansion_times`: Number of times to expand the storage bucket (affects gas cost for new -/// account creation). -/// - `expected_gas_used`: The expected gas usage for the contract creation, including any -/// additional costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn create_contract_test_case(spec: MegaSpecId, expansion_times: u64, expected_gas_used: u64) { - let mut db = MemoryDatabase::default(); - - // Test address and storage slot - let callee = CALLER.create(0); - let bucket_id = TestExternalEnvs::::bucket_id_for_account(callee); - // An external envs with the given bucket capacity - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * (expansion_times + 1)); - - // constructor code - let constructor_code = BytecodeBuilder::default().return_with_data([0x00]).build(); - // let tokens = revm::interpreter::gas::get_tokens_in_calldata(&constructor_code, true); - // println!("calldata_tokens: {:?}", tokens); - - // create contract - let res = transact(spec, &mut db, &external_envs, CALLER, None, constructor_code, U256::ZERO) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a nested create contract test case, verifying gas usage for account creation and bucket -/// expansion scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `is_create2`: Whether to use CREATE2 for the contract creation. -/// - `expansion_times`: Number of times to expand the storage bucket (affects gas cost for new -/// account creation). -/// - `expected_gas_used`: The expected gas usage for the contract creation, including any -/// additional costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn nested_create_contract_test_case( - spec: MegaSpecId, - is_create2: bool, - expansion_times: u64, - expected_gas_used: u64, -) { - let mut db = MemoryDatabase::default(); - let create2_salt = U256::from(6342); - // constructor code - let constructor_code = BytecodeBuilder::default().return_with_data([0x00]).build(); - let constructor_len = constructor_code.len(); - - // Test address and storage slot - let nested_callee = if is_create2 { - CALLEE.create2(create2_salt.to_be_bytes(), keccak256(&constructor_code)) - } else { - CALLEE.create(0) - }; - let bucket_id = TestExternalEnvs::::bucket_id_for_account(nested_callee); - // An external envs with the given bucket capacity - let external_envs = TestExternalEnvs::new() - .with_bucket_capacity(bucket_id, MIN_BUCKET_SIZE as u64 * (expansion_times + 1)); - - // set the code of the calee that transfers ether to the nested callee - let mut bytecode = BytecodeBuilder::default(); - if is_create2 { - bytecode = bytecode.push_u256(create2_salt); - } - let bytecode = bytecode - .mstore(0, constructor_code) - .push_number(constructor_len as u64) // call data - .push_number(0u8) - .push_number(0u8) // 0 value - .append(if is_create2 { CREATE2 } else { CREATE }) - .stop() - .build(); - db.set_account_code(CALLEE, bytecode); - - // transfer 1 wei from caller to callee - let res = transact( - spec, - &mut db, - &external_envs, - CALLER, - Some(CALLEE), - Default::default(), - Default::default(), - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a calldata test case, verifying gas usage for calldata scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `expected_gas_used`: The expected gas usage for the calldata, including any additional costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn calldata_test_case(spec: MegaSpecId, expected_gas_used: u64) { - // calldata - let calldata = Bytes::from([0x00; CALLDATA_LEN]); - - let mut db = MemoryDatabase::default(); - let res = transact( - spec, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::ZERO, - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a log test case, verifying gas usage for log scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `expected_gas_used`: The expected gas usage for the log, including any additional costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn log_test_case( - spec: MegaSpecId, - expected_gas_used: u64, -) { - assert!(TOPIC_COUNT <= 4, "Topic count must be less than or equal to 4"); - let mut db = MemoryDatabase::default(); - - // contract code that log some data - let mut bytecode = BytecodeBuilder::default(); - for _ in 0..TOPIC_COUNT { - bytecode = bytecode.push_number(1u8); // topic - } - bytecode = bytecode.push_number(DATA_LEN as u64); // data length - bytecode = bytecode.push_number(0u8); // data offset - let bytecode = bytecode.append(LOG0 + TOPIC_COUNT as u8).stop().build(); - db.set_account_code(CALLEE, bytecode); - - let res = transact( - spec, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - Default::default(), - U256::ZERO, - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} - -/// Executes a gas forward test case, verifying gas usage for gas forwarding scenarios. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `is_create`: Whether to use CREATE for the contract creation. -/// - `approx_expected_forwarded_gas`: The expected gas usage for the gas forwarding, including any -/// additional costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn gas_forward_test_case(spec: MegaSpecId, is_create: bool, approx_expected_forwarded_gas: u64) { - let mut db = MemoryDatabase::default(); - - struct CallGasInspector { - approx_expected_forwarded_gas: u64, - reached: bool, - } - - impl Inspector for CallGasInspector { - fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { - let depth = context.journal().depth(); - if depth == 1 { - self.reached = true; - // inner call - assert!( - inputs.gas_limit >= self.approx_expected_forwarded_gas * 99 / 100 && - inputs.gas_limit <= self.approx_expected_forwarded_gas * 101 / 100, - "expected forwarded gas is not correct" - ); - } - None - } - fn create( - &mut self, - context: &mut CTX, - inputs: &mut revm::interpreter::CreateInputs, - ) -> Option { - let depth = context.journal().depth(); - if depth == 1 { - self.reached = true; - // inner create - assert!( - inputs.gas_limit >= self.approx_expected_forwarded_gas * 99 / 100 && - inputs.gas_limit <= self.approx_expected_forwarded_gas * 101 / 100, - "expected forwarded gas is not correct" - ); - } - None - } - } - - let bytecode = if is_create { - BytecodeBuilder::default() - .push_number(10u8) - .append_many([PUSH0, PUSH0, CREATE]) - .stop() - .build() - } else { - BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(NESTED_CALLEE) - .append(GAS) - .append(CALL) - .stop() - .build() - }; - db.set_account_code(CALLEE, bytecode); - - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut inspector = CallGasInspector { approx_expected_forwarded_gas, reached: false }; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CALLEE), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_024_000_000, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!(res.is_ok()); - assert!(inspector.reached); -} - -/// Tests gas forwarding to CALL uses 98/100 rule in `MegaETH` (instead of 63/64). -#[test] -fn test_gas_forward_to_call_in_mini_rex() { - gas_forward_test_case(MegaSpecId::MINI_REX, false, 1_003_520_000); -} - -/// Tests gas forwarding to CREATE uses 98/100 rule in `MegaETH` (instead of 63/64). -#[test] -fn test_gas_forward_to_create_in_mini_rex() { - gas_forward_test_case(MegaSpecId::MINI_REX, true, 1_003_520_000); -} - -/// Executes a floor gas test case, verifying gas usage includes additional floor gas costs. -/// -/// # Arguments -/// - `spec`: The `MegaSpecId` specifying the EVM spec to use (e.g., `MINI_REX`, `EQUIVALENCE`). -/// - `calldata_size`: Size of calldata in bytes to test floor gas calculation. -/// - `expected_gas_used`: The expected gas usage including floor gas costs. -/// -/// # Panics -/// Panics if the transaction fails or if the actual gas used does not match `expected_gas_used`. -fn floor_gas_test_case(spec: MegaSpecId, calldata_size: usize, expected_gas_used: u64) { - let mut db = MemoryDatabase::default(); - - // Create calldata of specified size - let calldata = Bytes::from(vec![0x42; calldata_size]); - - let res = transact( - spec, - &mut db, - &TestExternalEnvs::new(), - CALLER, - Some(CALLEE), - calldata, - U256::ZERO, - ) - .unwrap(); - assert!(res.result.is_success()); - let gas_used = res.result.gas_used(); - assert_eq!(gas_used, expected_gas_used); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/main.rs b/crates/mega-evm/tests/_pending/mini_rex/main.rs deleted file mode 100644 index 0a4e5ed7c..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/main.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Tests for `MiniRex` hardfork features. - -mod access_beneficiary_balance; -mod block_env_access_tracking; -mod block_env_gas_limit; -mod compute_gas_limit; -mod gas; -mod oracle; -mod state_growth_limit; -mod tx_data_and_kv_update_limit; diff --git a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs b/crates/mega-evm/tests/_pending/mini_rex/oracle.rs deleted file mode 100644 index 5d80ffc90..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/oracle.rs +++ /dev/null @@ -1,844 +0,0 @@ -//! Tests for oracle contract access detection. -#![allow(clippy::doc_markdown)] - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - constants::mini_rex::{ORACLE_ACCESS_COMPUTE_GAS, TX_COMPUTE_GAS_LIMIT}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaContext, MegaEvm, MegaHaltReason, MegaHardforkConfig, MegaSpecId, - MegaTransaction, TestExternalEnvs, ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::{ - CALL, CALLCODE, DELEGATECALL, GAS, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, - RETURNDATASIZE, SLOAD, SSTORE, STATICCALL, TIMESTAMP, - }, - context::{result::ExecutionResult, TxEnv}, - handler::EvmTr, - inspector::NoOpInspector, - Inspector, -}; - -const CALLER: alloy_primitives::Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); - -/// Helper function to execute a transaction with the given database. -/// Returns a tuple of `(ExecutionResult, MegaEvm, oracle_accessed: bool)`. -fn execute_transaction< - 'a, - INSP: Inspector>>, ->( - spec: MegaSpecId, - db: &'a mut MemoryDatabase, - external_envs: &'a TestExternalEnvs, - inspector: INSP, - target: alloy_primitives::Address, -) -> ( - ExecutionResult, - MegaEvm<&'a mut MemoryDatabase, INSP, &'a TestExternalEnvs>, - bool, -) { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(target), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(inspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - // Get oracle_accessed before returning to avoid RefCell borrow conflicts - let oracle_accessed = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.has_accessed_oracle()) - .unwrap_or(false); - - (result, evm, oracle_accessed) -} - -/// Checks if the result is a volatile data access out of gas error. -fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool { - matches!( - result, - &ExecutionResult::Halt { reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, .. } - ) -} - -/// Test that contract runs out of gas when trying to execute expensive operations after oracle -/// access. -#[test] -fn test_parent_runs_out_of_gas_after_oracle_access() { - const INTERMEDIATE_CONTRACT: alloy_primitives::Address = - address!("3000000000000000000000000000000000000003"); - - // Create intermediate contract that calls the oracle - let mut builder = BytecodeBuilder::default(); - builder = builder - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL); - // After the call returns, the left gas is limited to 10k - // Try to execute 1000000 SSTORE operations (each costs 5000 gas minimum) - // This should run out of gas partway through - for i in 1..=1000 { - builder = builder - .push_number(i as u32) // offset: varying offset to avoid optimization - .push_number(i as u32) // size: 32 bytes - .append(SSTORE); - } - let intermediate_code = builder.stop().build(); - - // Create main contract that: - // 1. Calls intermediate contract (which accesses oracle) - // 2. After return, tries to execute many expensive KECCAK256 operations - // Expected: Parent gas is limited to 10k after oracle access, can't complete all operations - let mut builder = BytecodeBuilder::default(); - // Call intermediate contract - builder = builder - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(INTERMEDIATE_CONTRACT) - .append(GAS) - .append(CALL); - let main_code = builder.append_many([SLOAD, SLOAD, SLOAD, SLOAD, SLOAD, SLOAD]).stop().build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_storage(INTERMEDIATE_CONTRACT, U256::ZERO, U256::from(0x2333u64)); - db.set_account_code(INTERMEDIATE_CONTRACT, intermediate_code); - - let external_envs = TestExternalEnvs::::new(); - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - // Verify oracle was accessed - assert!(oracle_accessed, "Oracle should have been accessed"); - - // The transaction runs out of gas - the parent frame couldn't complete all expensive operations - // because its gas was limited to 10k after oracle access - assert!(!result.is_success(), "Transaction should run out of gas"); - assert!( - is_volatile_data_access_oog(&result), - "Transaction should fail due to volatile data access out of gas" - ); -} - -/// Test that gas is NOT limited when oracle is not accessed in nested calls. -#[test] -fn test_no_gas_limiting_without_oracle_access() { - const INTERMEDIATE_CONTRACT: alloy_primitives::Address = - address!("3000000000000000000000000000000000000003"); - const OTHER_CONTRACT: alloy_primitives::Address = - address!("4000000000000000000000000000000000000004"); - - // Create intermediate contract that calls a non-oracle contract - let intermediate_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(OTHER_CONTRACT) // NOT the oracle - .append(GAS) - .append(CALL) - .stop() - .build(); - - // Create main contract that calls intermediate contract - let main_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(INTERMEDIATE_CONTRACT) - .append(GAS) - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_code(INTERMEDIATE_CONTRACT, intermediate_code); - db.set_account_code(OTHER_CONTRACT, Bytes::new()); // Empty contract - - let external_envs = TestExternalEnvs::::new(); - let (result, evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - assert!(result.is_success(), "Transaction should succeed"); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - TX_COMPUTE_GAS_LIMIT, - "Compute gas limit should be the same as the transaction compute gas limit" - ); - - // Verify oracle was NOT accessed - assert!(!oracle_accessed, "Oracle should not have been accessed"); -} - -/// Test that when the oracle contract has code, that code is also subject to the gas limit. -#[test] -fn test_oracle_contract_code_subject_to_gas_limit() { - // Create oracle contract code that tries to execute many expensive operations - // Since calling the oracle immediately limits gas to 10k, the oracle's own code - // should run out of gas when trying to execute too many operations - let mut builder = BytecodeBuilder::default(); - // Try to execute 1000000 SSTORE operations (each costs 100 gas minimum) - // With only 10k gas limit, this should run out of gas partway through - for i in 1..=1000 { - builder = builder - .push_number(i as u32) // offset: varying offset to avoid optimization - .push_number(i as u32) // size: 32 bytes - .append(SSTORE); - } - let oracle_code = builder.stop().build(); - - // Create main contract that calls the oracle - let main_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // return memory args - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) - .append(CALL) - .append_many([SLOAD, SLOAD, SLOAD, SLOAD, SLOAD, SLOAD]) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_storage(ORACLE_CONTRACT_ADDRESS, U256::ZERO, U256::from(0x2333u64)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new(); - let (result, _, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - // Verify oracle was accessed - assert!(oracle_accessed, "Oracle should have been accessed"); - - // The transaction should run out of gas because the oracle contract's code - // tries to execute too many expensive operations with only 10k gas available - assert!( - !result.is_success(), - "Transaction should run out of gas due to oracle contract code exceeding gas limit" - ); - assert!( - is_volatile_data_access_oog(&result), - "Transaction should fail due to volatile data access out of gas" - ); -} - -/// Test that SLOAD operations on the oracle contract use the OracleEnv to provide storage values. -#[test] -fn test_oracle_storage_sload_uses_oracle_env() { - // Storage slot and value to test with - let test_slot = U256::from(42); - let oracle_value = U256::from(0x1234567890abcdef_u64); - - // Create oracle contract code that performs SLOAD on the test slot and returns the value - let oracle_code = BytecodeBuilder::default() - .push_u256(test_slot) // push the slot number - .append(SLOAD) // load from storage (value is now on stack) - .push_number(0u8) // push memory offset to stack - .append(MSTORE) // store value to memory at offset 0 - .push_number(32u8) // push return size to stack - .push_number(0u8) // push return offset to stack - .append(RETURN) // return 32 bytes from memory offset 0 - .build(); - - // Create main contract that calls the oracle, captures return data, and returns it - let main_code = BytecodeBuilder::default() - .push_number(32u8) // retSize for CALL - .push_number(0u8) // retOffset for CALL - .push_number(0u8) // argsSize for CALL - .push_number(0u8) // argsOffset for CALL - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) // gas - .append(CALL) // execute the call - .append(PUSH0) // pop the call result (success/fail) - // Now return data from oracle call is available via RETURNDATASIZE/RETURNDATACOPY - .append(RETURNDATASIZE) // get size of return data - .push_number(0u8) // destOffset in memory - .push_number(0u8) // offset in returndata - .append(RETURNDATASIZE) // size to copy - .append(RETURNDATACOPY) // copy return data to memory - .append(RETURNDATASIZE) // push size for RETURN - .push_number(0u8) // push offset for RETURN - .append(RETURN) // return the data we got from oracle - .build(); - - // Set up the oracle environment with the test storage value - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new() - .with_oracle_storage(test_slot, oracle_value); - - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - // Verify the transaction succeeded - assert!(result.is_success(), "Transaction should succeed"); - - // Verify oracle was accessed - assert!(oracle_accessed, "Oracle should have been accessed"); -} - -/// Test that SLOAD on oracle contract falls back to database when OracleEnv returns None. -#[test] -fn test_oracle_storage_sload_fallback_to_database() { - // Storage slot to test with - let test_slot = U256::from(99); - let db_value = U256::from(0xfedcba9876543210_u64); - - // Create oracle contract code that performs SLOAD on the test slot and returns the value - let oracle_code = BytecodeBuilder::default() - .push_u256(test_slot) // push the slot number - .append(SLOAD) // load from storage (value is now on stack) - .push_number(0u8) // push memory offset to stack - .append(MSTORE) // store value to memory at offset 0 - .push_number(32u8) // push return size to stack - .push_number(0u8) // push return offset to stack - .append(RETURN) // return 32 bytes from memory offset 0 - .build(); - - // Create main contract that calls the oracle, captures return data, and returns it - let main_code = BytecodeBuilder::default() - .push_number(32u8) // retSize for CALL - .push_number(0u8) // retOffset for CALL - .push_number(0u8) // argsSize for CALL - .push_number(0u8) // argsOffset for CALL - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) // callee: oracle contract - .append(GAS) // gas - .append(CALL) // execute the call - .append(PUSH0) // pop the call result (success/fail) - // Now return data from oracle call is available via RETURNDATASIZE/RETURNDATACOPY - .append(RETURNDATASIZE) // get size of return data - .push_number(0u8) // destOffset in memory - .push_number(0u8) // offset in returndata - .append(RETURNDATASIZE) // size to copy - .append(RETURNDATACOPY) // copy return data to memory - .append(RETURNDATASIZE) // push size for RETURN - .push_number(0u8) // push offset for RETURN - .append(RETURN) // return the data we got from oracle - .build(); - - // Set up database with a storage value for the oracle contract - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_storage(ORACLE_CONTRACT_ADDRESS, test_slot, db_value); - - // Create external envs WITHOUT setting oracle storage (so it returns None) - let external_envs = TestExternalEnvs::::new(); - - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - // Verify the transaction succeeded - assert!(result.is_success(), "Transaction should succeed"); - - // Verify oracle was accessed - assert!(oracle_accessed, "Oracle should have been accessed"); -} - -/// Test that SLOAD works correctly when transaction directly calls the oracle contract. -/// Oracle access tracking now occurs for both CALL instructions and direct transaction calls. -#[test] -fn test_oracle_storage_sload_direct_call() { - // Storage slot and value to test with - let test_slot = U256::from(123); - let oracle_value = U256::from(0xabcdef1234567890_u64); - - // Create oracle contract code that performs SLOAD on the test slot and returns the value - let oracle_code = BytecodeBuilder::default() - .push_u256(test_slot) // push the slot number - .append(SLOAD) // load from storage (value is now on stack) - .push_number(0u8) // push memory offset to stack - .append(MSTORE) // store value to memory at offset 0 - .push_number(32u8) // push return size to stack - .push_number(0u8) // push return offset to stack - .append(RETURN) // return 32 bytes from memory offset 0 - .build(); - - // Set up the oracle environment with the test storage value - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new() - .with_oracle_storage(test_slot, oracle_value); - - // Call the oracle contract DIRECTLY as the transaction target - let (result, _evm, oracle_accessed) = execute_transaction( - MegaSpecId::MINI_REX, - &mut db, - &external_envs, - NoOpInspector, - ORACLE_CONTRACT_ADDRESS, - ); - - // Verify the transaction succeeded - assert!(result.is_success(), "Transaction should succeed"); - - // Verify oracle WAS accessed (oracle access tracking now happens at frame level) - assert!(oracle_accessed, "Oracle access should be tracked for direct transaction calls"); -} - -/// Test that the oracle contract is deployed when mini-rex activates via block executor. -/// This exercises the deployment logic in block.rs:284-292. -#[test] -fn test_oracle_contract_deployed_on_mini_rex_activation() { - use alloy_evm::{block::BlockExecutor, Evm, EvmEnv, EvmFactory}; - use alloy_primitives::B256; - use mega_evm::{ - MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaSpecId, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, ORACLE_CONTRACT_CODE_HASH, - }; - use revm::database::State; - - // Create a fresh in-memory database - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory and environment - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment with MiniRex spec - use revm::context::BlockEnv; - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::MINI_REX; - let block_env = BlockEnv { - number: revm::primitives::U256::from(1000), // Set non-zero block number to avoid overflow - timestamp: revm::primitives::U256::from(1_800_000_000), /* High timestamp to ensure - * Isthmus is active */ - gas_limit: 30_000_000, // Set reasonable gas limit - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create the EVM instance - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block execution context with first_mini_rex_block = true - // This triggers oracle deployment - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), // Set a beacon block root - Default::default(), - BlockLimits::no_limits(), - ); - - // Configure hardforks with MiniRex activated at timestamp 0 - use alloy_hardforks::ForkCondition; - use mega_evm::MegaHardfork; - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - - // Create receipt builder (use concrete OpAlloyReceiptBuilder type) - use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; - let receipt_builder = OpAlloyReceiptBuilder::default(); - - // Create block executor - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec.clone(), receipt_builder); - - // Call apply_pre_execution_changes which triggers oracle deployment in block.rs:284-292 - executor.apply_pre_execution_changes().expect("Pre-execution changes should succeed"); - - // The oracle deployment changes should be committed to the database - // Verify the oracle contract is actually deployed in the database - let db_ref = executor.evm_mut().db_mut(); - - // Load the oracle contract account from the cache - let cache_acc = - db_ref.load_cache_account(ORACLE_CONTRACT_ADDRESS).expect("Should be able to load account"); - let acc_info = cache_acc.account_info().expect("Oracle contract account should exist"); - - // Verify code hash matches - assert_eq!( - acc_info.code_hash, ORACLE_CONTRACT_CODE_HASH, - "Oracle contract code hash should match" - ); - - // Verify code is set and matches - assert!(acc_info.code.is_some(), "Code should be set on the account"); - let deployed_code = acc_info.code.as_ref().unwrap(); - assert_eq!( - deployed_code.original_bytes(), - ORACLE_CONTRACT_CODE, - "Deployed code should match original code" - ); - - // Verify that calling deploy_oracle_contract again returns state with account marked as read - // (proving the contract is already deployed) - use mega_evm::transact_deploy_oracle_contract; - let result = - transact_deploy_oracle_contract(&chain_spec, 0, db_ref).expect("Should not error").unwrap(); - assert_eq!( - result.len(), - 1, - "Oracle should already be deployed, so deploy_oracle_contract should return state with account marked as read" - ); -} - -/// Test that SLOAD on oracle contract produces identical gas costs whether the value -/// comes from oracle_env or from state. This verifies the fix that forces all oracle -/// storage reads to be cold access for determinism in replay scenarios. -#[test] -fn test_oracle_sload_determinism_between_oracle_env_and_state() { - let test_slot = U256::from(42); - let test_value = U256::from(0x1234567890abcdef_u64); - - // Contract that SLOADs oracle storage multiple times - let bytecode = BytecodeBuilder::default() - .push_u256(test_slot) - .append(SLOAD) - .push_u256(test_slot) - .append(SLOAD) - .push_u256(test_slot) - .append(SLOAD) - .stop() - .build(); - - // === Execution 1: Read from oracle_env === - let mut db1 = MemoryDatabase::default(); - db1.set_account_code(ORACLE_CONTRACT_ADDRESS, bytecode.clone()); - - let external_envs_with_oracle = TestExternalEnvs::::new() - .with_oracle_storage(test_slot, test_value); - - let (result1, _, oracle_accessed1) = execute_transaction( - MegaSpecId::MINI_REX, - &mut db1, - &external_envs_with_oracle, - NoOpInspector, - ORACLE_CONTRACT_ADDRESS, - ); - - // === Execution 2: Read from state (no oracle_env) === - let mut db2 = MemoryDatabase::default(); - db2.set_account_code(ORACLE_CONTRACT_ADDRESS, bytecode); - db2.set_account_storage(ORACLE_CONTRACT_ADDRESS, test_slot, test_value); - - let external_envs_empty = TestExternalEnvs::::new(); - - let (result2, _, oracle_accessed2) = execute_transaction( - MegaSpecId::MINI_REX, - &mut db2, - &external_envs_empty, - NoOpInspector, - ORACLE_CONTRACT_ADDRESS, - ); - - // === Assert receipts are identical === - assert!(result1.is_success(), "Execution 1 (oracle_env) should succeed"); - assert!(result2.is_success(), "Execution 2 (state) should succeed"); - assert_eq!( - result1.gas_used(), - result2.gas_used(), - "Gas used should be identical regardless of data source (oracle_env vs state)" - ); - - // Both should have accessed the oracle contract - assert!(oracle_accessed1, "Execution 1 should access oracle"); - assert!(oracle_accessed2, "Execution 2 should access oracle"); -} - -/// Test progressive restriction: accessing block env (20M limit) then oracle (1M limit) -/// should further restrict gas to 1M. -#[test] -fn test_progressive_restriction_block_env_then_oracle() { - // Create a simple oracle contract that returns success - let oracle_code = - BytecodeBuilder::default().push_number(0u8).push_number(0u8).append(RETURN).build(); - - // Main contract that: - // 1. Accesses TIMESTAMP (limits gas to 20M) - // 2. Calls oracle (should further limit to 1M) - // 3. Records gas before and after - let main_code = BytecodeBuilder::default() - // Record gas before TIMESTAMP - .append(GAS) - .push_number(0u8) - .append(MSTORE) - // Access block env - limits to 20M - .append(TIMESTAMP) - .append(POP) - // Record gas after TIMESTAMP (should be ≤ 20M) - .append(GAS) - .push_number(0x20u8) - .append(MSTORE) - // Call oracle - should further limit to 1M - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) // pass all available gas - .append(CALL) - .append(POP) - // Record gas after oracle call (should be ≤ 1M) - .append(GAS) - .push_number(0x40u8) - .append(MSTORE) - // Return all recorded gas values - .push_number(0x60u8) - .push_number(0u8) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new(); - - let (result, evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "Compute gas limit should be set to oracle access limit" - ); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle should have been accessed"); -} - -/// Test order independence: accessing oracle (1M limit) then block env (20M limit) -/// should result in the same 1M final limit. -#[test] -fn test_order_independent_oracle_then_block_env() { - // Create a simple oracle contract that accesses TIMESTAMP before returning - let oracle_code = BytecodeBuilder::default() - .append(TIMESTAMP) // Oracle accesses block env (20M limit) - .append(POP) - .push_number(0u8) - .push_number(0u8) - .append(RETURN) - .build(); - - // Main contract that calls oracle first (which will access TIMESTAMP internally) - let main_code = BytecodeBuilder::default() - // Call oracle - this will establish 1M limit AND oracle will access TIMESTAMP (20M) - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argsSize - .push_number(0u8) // argsOffset - .push_number(0u8) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) // pass all available gas - .append(CALL) - .append(POP) - // Record gas after oracle call - should be ≤ 1M (not 20M) - .append(GAS) - .push_number(0u8) - .append(MSTORE) - // Return recorded gas value - .push_number(0x20u8) - .push_number(0u8) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new(); - let (result, evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert_eq!( - evm.ctx_ref().additional_limit.borrow().compute_gas_limit(), - ORACLE_ACCESS_COMPUTE_GAS, - "Compute gas limit should be set to oracle access limit" - ); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "Oracle should have been accessed"); -} - -#[test] -fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { - // This test verifies that when a transaction runs out of gas due to oracle access - // (VolatileDataAccessOutOfGas with Oracle type), it does NOT consume all gas. - // Instead, detained gas is refunded and gas_used reflects only actual work performed. - let mut db = MemoryDatabase::default(); - let external_envs = TestExternalEnvs::::new(); - - // Contract that calls the oracle then tries expensive work that exceeds the 1M oracle limit - let mut builder = BytecodeBuilder::default() - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argSize - .push_number(0u8) // argOffset - .push_number(0u8) // value - .push_address(ORACLE_CONTRACT_ADDRESS) // oracle address - .push_number(0xffffu16) // gas - .append(CALL) // Call oracle - limits gas to 1M - .append(POP); // pop result - - // Try to do 1000 SSTOREs (2M gas needed, but only 1M available after oracle limiting) - for i in 1..=1000 { - builder = builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let bytecode = builder.stop().build(); - db.set_account_code(CALLEE, bytecode); - - let (result, _, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(oracle_accessed, "Oracle should have been accessed"); - // Should fail with VolatileDataAccessOutOfGas - assert!(!result.is_success(), "Transaction should fail due to oracle volatile data access OOG"); - assert!( - is_volatile_data_access_oog(&result), - "Transaction should fail due to volatile data access out of gas" - ); - - let gas_used = result.gas_used(); - - // Key assertion: gas_used should be much less than gas_limit - assert!( - gas_used < 1_000_000_000, - "gas_used should be much less than gas_limit, proving detained gas was refunded. Got: {}", - gas_used - ); -} - -#[test] -fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { - // This test verifies that when BOTH block env and oracle are accessed, and the transaction - // runs out of gas, the halt reason correctly identifies "Both" type with the most restrictive - // limit (1M from oracle), and detained gas is properly refunded. - - let mut db = MemoryDatabase::default(); - let external_envs = TestExternalEnvs::::new(); - - // Contract that accesses TIMESTAMP (20M limit), then calls oracle (1M limit), - // then tries expensive work that exceeds the 1M limit - let mut builder = BytecodeBuilder::default() - .append(TIMESTAMP) // Limits gas to 20M - .append(POP) - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(0u8) // argSize - .push_number(0u8) // argOffset - .push_number(0u8) // value - .push_address(ORACLE_CONTRACT_ADDRESS) // oracle address - .push_number(0xffffu16) // gas - .append(CALL) // Call oracle - further limits gas to 1M - .append(POP); // pop result - - // Try to do 1000 SSTOREs (2M gas needed, but only 1M available) - for i in 1..=1000 { - builder = builder.push_number(i as u32).push_number(i as u32).append(SSTORE); - } - let bytecode = builder.stop().build(); - db.set_account_code(CALLEE, bytecode); - - let (result, _evm, oracle_accessed) = - execute_transaction(MegaSpecId::MINI_REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - // Should fail with VolatileDataAccessOutOfGas - assert!(oracle_accessed, "Oracle should have been accessed"); - assert!(!result.is_success(), "Transaction should fail due to volatile data access OOG"); - assert!( - is_volatile_data_access_oog(&result), - "Transaction should fail due to volatile data access out of gas" - ); - - let gas_used = result.gas_used(); - // Key assertion: gas_used should be much less than gas_limit - assert!( - gas_used < 1_000_000_000, - "gas_used should be much less than gas_limit, proving detained gas was refunded. Got: {}", - gas_used - ); -} - -/// Test that transactions from the mega system address are exempted from oracle access tracking. -/// This ensures system operations can call the oracle without gas detention. -#[test] -fn test_mega_system_address_exempted_from_oracle_tracking() { - use mega_evm::MEGA_SYSTEM_ADDRESS; - - // Create oracle contract code that performs some operations - let oracle_code = - BytecodeBuilder::default().push_number(0u8).push_number(0u8).append(RETURN).build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new(); - - // Create a transaction from MEGA_SYSTEM_ADDRESS directly calling the oracle - let mut context = - MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), - data: Default::default(), - value: U256::ZERO, - gas_limit: TX_COMPUTE_GAS_LIMIT + 100_000, // More than compute limit - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - - // Get oracle_accessed flag - let oracle_accessed = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.has_accessed_oracle()) - .unwrap_or(false); - - // Verify transaction succeeded - assert!(result.is_success(), "Transaction from mega system address should succeed"); - - // Key assertion: Oracle access should NOT be tracked for mega system address - assert!( - !oracle_accessed, - "Oracle access should NOT be tracked for transactions from MEGA_SYSTEM_ADDRESS" - ); - - // Verify compute gas limit was NOT applied (gas should not be limited to 1M) - let compute_gas_limit = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.get_compute_gas_limit()) - .unwrap_or(None); - - assert!( - compute_gas_limit.is_none(), - "Compute gas limit should NOT be set for mega system address transactions" - ); -} diff --git a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs deleted file mode 100644 index 4e1f5934e..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/state_growth_limit.rs +++ /dev/null @@ -1,220 +0,0 @@ -//! Tests for the state growth limit feature of the `MegaETH` EVM. -//! -//! These tests verify that the state growth limit functionality correctly tracks and limits -//! the creation of new accounts and storage slots during transaction execution. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, DatabaseCommit, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const NEW_ACCOUNT: Address = address!("0000000000000000000000000000000000100003"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified state growth limit. -/// -/// Returns the execution result and the actual state growth used. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - state_growth_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(state_growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let state_growth = ctx.additional_limit.borrow().get_usage().state_growth; - Ok((r, state_growth)) -} - -/// Checks if the execution result indicates that the state growth limit was exceeded. -fn is_state_growth_limit_exceeded(result: &ResultAndState) -> bool { - matches!( - &result.result, - ExecutionResult::Halt { reason: MegaHaltReason::StateGrowthLimitExceeded { .. }, .. } - ) -} - -/// Creates a default transaction builder calling a contract. -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -// ============================================================================ -// BASIC STATE GROWTH TRACKING TESTS -// ============================================================================ - -// ============================================================================ -// NET GROWTH MODEL TESTS -// ============================================================================ - -// ============================================================================ -// FRAME-BASED TRACKING TESTS -// ============================================================================ - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -#[test] -fn test_limit_exactly_at_limit() { - // Create exactly 3 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(state_growth, 3, "Exactly at limit should succeed"); -} - -#[test] -fn test_limit_exceeded_by_one() { - // Try to create 4 slots with limit of 3 - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .sstore(U256::from(2), U256::from(3)) // +1 - .sstore(U256::from(3), U256::from(4)) // +1 (exceeds limit) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // Verify the halt reason details - the actual growth is preserved in the halt reason - match &result.result { - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit, actual }, - .. - } => { - assert_eq!(*limit, 3); - assert_eq!(*actual, 4, "Should report actual growth that exceeded limit"); - } - _ => panic!("Expected StateGrowthLimitExceeded halt"), - } -} - -#[test] -fn test_limit_exceeded_in_nested_call() { - // Child creates 2 slots - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .stop() - .build(); - - // Parent creates 2 slots, then calls child (total would be 4, limit is 3) - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // +1 - .sstore(U256::from(1), U256::from(2)) // +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 3, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); -} - -#[test] -fn test_state_reverted_when_exceeding_limit() { - // Create 2 slots, then exceed limit on 3rd (with limit of 2) - let code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(100)) // +1 - .sstore(U256::from(1), U256::from(200)) // +1 - .sstore(U256::from(2), U256::from(300)) // +1 (exceeds) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _state_growth) = transact(MegaSpecId::MINI_REX, &mut db, 2, tx).unwrap(); - - assert!(result.result.is_halt()); - assert!(is_state_growth_limit_exceeded(&result)); - - // State should not be committed - db.commit(result.state); - - // Verify the storage was not persisted - let storage_0 = db.storage(CALLEE, U256::from(0)).unwrap(); - let storage_1 = db.storage(CALLEE, U256::from(1)).unwrap(); - let storage_2 = db.storage(CALLEE, U256::from(2)).unwrap(); - - assert_eq!(storage_0, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_1, U256::ZERO, "Storage should be reverted"); - assert_eq!(storage_2, U256::ZERO, "Storage should be reverted"); -} - -// ============================================================================ -// COMPLEX SCENARIOS TESTS -// ============================================================================ - -// ============================================================================ -// TRACKER MIGRATION COVERAGE TESTS -// ============================================================================ diff --git a/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs b/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs deleted file mode 100644 index fb18534ff..000000000 --- a/crates/mega-evm/tests/_pending/mini_rex/tx_data_and_kv_update_limit.rs +++ /dev/null @@ -1,1164 +0,0 @@ -//! Tests for the data limit feature of the `MegaETH` EVM. -//! -//! Tests the data limit functionality that prevents spam attacks by limiting the amount -//! of data generated during transaction execution. - -use std::convert::Infallible; - -use alloy_eips::{ - eip2930::{AccessList, AccessListItem}, - eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}, -}; -use alloy_primitives::{address, bytes, Address, Bytes, B256, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, STORAGE_SLOT_WRITE_SIZE, -}; -use revm::{ - bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, INVALID, PUSH0, PUSH1, SLOAD, SSTORE, STOP, - }, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - ContextTr, TxEnv, - }, - database::{CacheDB, EmptyDB}, - handler::EvmTr, - interpreter::{CallInputs, CallOutcome}, - DatabaseCommit, Inspector, -}; - -/// Executes a transaction on the `MegaETH` EVM with configurable data limits. -/// -/// Returns the execution result, generated data size, and number of key-value updates. -fn transact( - spec: MegaSpecId, - db: &mut CacheDB, - data_limit: u64, - kv_update_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(data_limit) - .with_tx_kv_updates_limit(kv_update_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - Ok((r, ctx.generated_data_size(), ctx.kv_update_count())) -} - -/// Checks if the execution result indicates that the data limit was exceeded. -#[allow(unused)] -fn is_data_limit_exceeded(result: &ResultAndState) -> bool { - match &result.result { - ExecutionResult::Halt { reason, .. } => { - matches!(reason, MegaHaltReason::DataLimitExceeded { .. }) - } - _ => false, - } -} - -/// Checks if the execution result indicates that the KV update limit was exceeded. -#[allow(unused)] -fn is_kv_update_limit_exceeded(result: &ResultAndState) -> bool { - match &result.result { - ExecutionResult::Halt { reason, .. } => { - matches!(reason, MegaHaltReason::KVUpdateLimitExceeded { .. }) - } - _ => false, - } -} - -const FACTORY: Address = address!("0000000000000000000000000000000000200001"); -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const LIBRARY: Address = address!("0000000000000000000000000000000000100002"); - -/// The factory code of a contract that dumps a log. -/// -/// The code: -/// ```yul -/// { -/// // Read first uint256 (number of topics) from calldata offset 0 -/// let numTopics := calldataload(0) -/// -/// // Read second uint256 (length of log data) from calldata offset 32 -/// let dataLength := calldataload(0x20) -/// -/// switch numTopics -/// case 0 { -/// // LOG0: log(offset, length) -/// log0(0x0, dataLength) -/// } -/// case 1 { -/// log1(0x0, dataLength, 0x0) -/// } -/// case 2 { -/// log2(0x0, dataLength, 0x0, 0x0) -/// } -/// case 3 { -/// log3(0x0, dataLength, 0x0, 0x0, 0x0) -/// } -/// case 4 { -/// log4(0x0, dataLength, 0x0, 0x0, 0x0, 0x0) -/// } -/// default { -/// invalid() -/// } -/// -/// stop() -/// } -/// ``` -const LOG_FACTORY_CODE: Bytes = bytes!("5f3560203590805f146050578060011460475780600214603d5780600314603257600414602857fe5b5f8080809381a45b005b505f80809281a36030565b505f809181a26030565b505f9081a16030565b505fa0603056"); - -/// The factory code of a contract that creates a contract. -/// -/// The code: -/// ```yul -/// { -/// // the last 32 bytes is uint256 argument -/// codecopy(0x0, sub(codesize(), 0x20), 0x20) -/// let codeLen := mload(0x0) -/// // the created contract code is returned -/// return(0x0, codeLen) -/// } -/// ``` -/// -/// There is one required argument, the contract size, which is a uint256 and should be appended by -/// the end of the creation code. -const CONTRACT_CONSTRUCTOR_CODE: Bytes = bytes!("60208038035f395f515ff3"); - -/// The factory code of a contract that creates a contract. -/// -/// The code: -/// ```yul -/// { -/// // The contract constructor -/// let constructorLen := 11 -/// let constructorCode := 0x60208038035f395f515ff3 -/// mstore(0x0, constructorCode) -/// let constructorCodeStart := sub(0x20, constructorLen) -/// -/// // The first 32 bytes of calldata is codeLen -/// let codeLen := calldataload(0x0) -/// // Append codeLen to the end of constructor -/// mstore(0x20, codeLen) -/// -/// let created := create(0x0, constructorCodeStart, add(constructorLen, 0x20)) -/// if iszero(created) { -/// invalid() -/// } -/// } -/// ``` -/// -/// There is one required argument, the contract size, which is a uint256 and should be appended by -/// the end of the creation code. -const CONTRACT_FACTORY_CODE: Bytes = - bytes!("600b6a60208038035f395f515ff35f526020818103915f35825201905ff015602357005bfe"); - -/// Generates the input for the contract factory contract. -fn gen_contract_factory_input(contract_size: u64) -> Bytes { - let mut input = vec![]; - input.extend_from_slice(&U256::from(contract_size).to_be_bytes_vec()); - input.into() -} - -/// Generates the input for the contract create transaction. It uses the constructor code as the -/// input and append the contract size at the end. -fn gen_contract_create_tx_input(contract_size: u64) -> Bytes { - let mut input = CONTRACT_CONSTRUCTOR_CODE.to_vec(); - input.extend_from_slice(&U256::from(contract_size).to_be_bytes_vec()); - input.into() -} - -/// Generates the input for the log factory contract. -fn gen_log_factory_input(num_topics: u64, data_length: u64) -> Bytes { - let mut input = vec![]; - input.extend_from_slice(&U256::from(num_topics).to_be_bytes_vec()); - input.extend_from_slice(&U256::from(data_length).to_be_bytes_vec()); - input.into() -} - -// ============================================================================ -// BASIC TRANSACTION TESTS -// ============================================================================ - -/// Test data size and KV update count for empty transaction execution. -/// -/// This test verifies the baseline data size and KV update counts for the simplest -/// possible transaction - a call to an existing account with no value or data. -/// It establishes the minimum data size (base transaction + sender account write) -/// and KV update count (sender nonce increment) for all transactions. -#[test] -fn test_empty_tx() { - let mut db = CacheDB::::default(); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(!res.result.is_halt()); - // 1 kv update for the caller account (nonce increase) - assert_eq!(kv_update_count, 1); - // 110 bytes for the intrinsic data of a transaction + 312 bytes for the caller account info - // update - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - +ACCOUNT_INFO_WRITE_SIZE // sender write - ); -} - -/// Test calling a non-existing account with zero value and verify data size/KV update counts. -/// -/// This test verifies that making a call to an account that doesn't exist yet -/// works correctly and generates the expected amount of data and key-value updates. -/// Unlike ether transfers, this call doesn't create the account since no value is transferred, -/// resulting in fewer KV updates and data size compared to value transfers. -#[test] -fn test_call_non_existing_account() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv updates for the caller info update - assert_eq!(kv_update_count, 1); - // base tx + sender account info read + sender account info write - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - ); -} - -/// Test call with data, access list, and EIP-7702 authorization list. -/// -/// This test verifies that a call transaction with additional data components -/// (call data, access list, and EIP-7702 authorization list) works correctly -/// and generates the expected amount of data and key-value updates. It tests -/// the data limit functionality with more complex transaction structures, -/// including EIP-7702 delegation which requires additional account updates. -#[test] -fn test_call_with_data() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - let delegate = address!("0000000000000000000000000000000000100002"); - let data = bytes!("01020304"); // 4 bytes of call data - let mut access_list = AccessList::default(); - access_list.0.push(AccessListItem { address: CALLER, storage_keys: vec![B256::ZERO] }); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(CALLER), - )]; - let tx = TxEnvBuilder::new() - .caller(CALLER) - .call(CALLEE) - .data(data) - .access_list(access_list) - .authorization_list_recovered(authorization_list) - .build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 2 kv update for the caller account (tx nonce increase and 7702 code change) - assert_eq!(kv_update_count, 2); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + 101 + ACCOUNT_INFO_WRITE_SIZE // 7702 authorization & account read & write - + 4 + 52 // call data & access list - ); -} - -// ============================================================================ -// ETHER TRANSFER TESTS -// ============================================================================ - -/// Test ether transfer between existing accounts and verify data size/KV update counts. -/// -/// This test verifies that a simple ether transfer from one existing account to another -/// works correctly and generates the expected amount of data and key-value updates. -/// It sets up two accounts with initial balances and transfers 1 wei from caller to callee. -/// The test verifies that both accounts are updated (sender nonce, receiver balance) -/// and that the data size includes both account writes. -#[test] -fn test_ether_transfer_to_existing_account() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1000)) - .account_balance(CALLEE, U256::from(100)); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(1)).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (nonce increase), and one for the callee account (balance - // increase) - assert_eq!(kv_update_count, 2); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + ACCOUNT_INFO_WRITE_SIZE // callee write - ); -} - -/// Test ether transfer to a non-existing account and verify data size/KV update counts. -/// -/// This test verifies that transferring ether to an account that doesn't exist yet -/// works correctly and generates the expected amount of data and key-value updates. -/// It creates a new account for the callee during the transfer operation, which -/// results in the same data size and KV update counts as transferring to an existing -/// account since both require updating the receiver's balance. -#[test] -fn test_ether_transfer_to_non_existing_account() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(1)).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 2 kv updates for the caller and callee account info updates - assert_eq!(kv_update_count, 2); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + ACCOUNT_INFO_WRITE_SIZE // callee write - ); -} - -// ============================================================================ -// CONTRACT CREATION TESTS -// ============================================================================ - -/// Test contract creation and verify data size/KV update counts. -/// -/// This test verifies that creating a new contract works correctly and generates -/// the expected amount of data and key-value updates. It creates a contract with -/// 10 bytes of code and verifies the data size includes the transaction data, -/// account updates, and the created contract code. The test ensures that both -/// the sender and the newly created contract account are properly tracked. -#[test] -fn test_create_contract() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - let input = gen_contract_create_tx_input(10); - let input_len = input.len() as u64; - let tx = TxEnvBuilder::new().caller(CALLER).create().data(input).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase), 1 kv update for the created account - assert_eq!(kv_update_count, 2); - // 110 bytes for the intrinsic data of a transaction, 2*312 bytes for the caller and created - // account info update, 10 bytes for the created contract code, bytes for the - // input data - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + ACCOUNT_INFO_WRITE_SIZE // callee write - + 10 // created contract code - + input_len // input data - ); -} - -/// Test contract creation through a factory contract and verify data size/KV update counts. -/// -/// This test verifies that creating a contract through a factory contract works correctly -/// and generates the expected amount of data and key-value updates. It uses a factory -/// contract that creates another contract with 10 bytes of code, testing the data limit -/// functionality in a more complex contract creation scenario. The test ensures that -/// all three accounts (sender, factory, created contract) are properly tracked. -#[test] -fn test_create_contract_with_factory() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - db.set_account_code(FACTORY, CONTRACT_FACTORY_CODE); - let input = gen_contract_factory_input(10); - let input_len = input.len() as u64; - let tx = TxEnvBuilder::new().caller(CALLER).call(FACTORY).data(input).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase), 1 kv update for the created account - assert_eq!(kv_update_count, 3); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + ACCOUNT_INFO_WRITE_SIZE // factory nonce change - + ACCOUNT_INFO_WRITE_SIZE // created contract write - + 10 // contract code - + input_len // input data - ); -} - -// ============================================================================ -// STORAGE OPERATION TESTS -// ============================================================================ - -/// Test storage write operations and verify data size/KV update counts. -/// -/// This test verifies that storage write operations (SSTORE) work correctly and generate -/// the expected amount of data and key-value updates. It uses a simple contract that -/// stores 0x1 to storage slot 0, testing the data limit functionality for storage -/// operations. Storage writes create both data size and KV update counts. -#[test] -fn test_sstore_data() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - // a simple contract that stores 0x0 to slot 0 - let code: Bytes = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SSTORE, STOP]).build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase), 1 kv update for the callee storage - assert_eq!(kv_update_count, 2); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + STORAGE_SLOT_WRITE_SIZE // storage write - ); -} - -/// Test storage read operations and verify data size/KV update counts. -/// -/// This test verifies that storage read operations (SLOAD) work correctly and generate -/// the expected amount of data and key-value updates. It uses a simple contract that -/// loads from storage slot 0, testing the data limit functionality for storage -/// read operations. Storage reads contribute to data size but don't create KV updates -/// since they don't modify state. -#[test] -fn test_sload_data() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - // a simple contract that loads slot 0 - let code: Bytes = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_update_count, 1); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - ); -} - -// ============================================================================ -// LOG OPERATION TESTS -// ============================================================================ - -/// Test log data generation and verify data size/KV update counts. -/// -/// This test verifies that generating log data works correctly and generates -/// the expected amount of data and key-value updates. It uses a log factory -/// contract that creates logs with 1 topic and 10 bytes of data, testing -/// the data limit functionality for log operations. Log data contributes to -/// the total data size but doesn't create additional KV updates. -#[test] -fn test_log_data() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1000)); - db.set_account_code(CALLEE, LOG_FACTORY_CODE); - let input = gen_log_factory_input(1, 10); - let input_len = input.len() as u64; - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).data(input).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_update_count, 1); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + 32 + 10 // log topics and data - + input_len // input data - ); -} - -// ============================================================================ -// CALL OPERATION TESTS -// ============================================================================ - -/// Test delegated call operations and verify data size/KV update counts. -/// -/// This test verifies that delegated call operations work correctly and generate -/// the expected amount of data and key-value updates. It uses a contract that -/// performs a delegated call to a library contract, testing the data limit -/// functionality for delegated calls. Delegated calls don't create additional -/// account updates since they execute in the caller's context. -#[test] -fn test_delegated_call() { - let mut db = MemoryDatabase::default(); - // a contract that calls a library contract - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // argOffset, argLen, returnOffset, returnLen - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(DELEGATECALL) - .build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_updates, 1); - assert_eq!(data_size, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); // no update on either contract - // or library -} - -/// Test that caller account updates are not double-counted in nested transfers. -/// -/// This test verifies that when a contract performs a nested call with value transfer, -/// the caller account is not double-counted for data size and KV update purposes. -/// It uses a contract that transfers value to a library contract, ensuring that -/// account updates are properly deduplicated across call boundaries. -#[test] -fn test_updated_caller_should_not_be_double_counted_for_nested_transfer() { - let mut db = MemoryDatabase::default(); - // a contract that transfers value to a library contract - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // argOffset, argLen, returnOffset, returnLen - .push_number(1u8) // value to transfer - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, code); - db.set_account_balance(CALLEE, U256::from(10000)); - db.set_account_balance(CALLER, U256::from(10000)); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(100)).build_fill(); - let (res, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase), 1 kv update for the callee account - // (balance increase and decrease), 1 kv update for the library account (balance increase) - // (balance decrease) - assert_eq!(kv_updates, 3); - assert_eq!( - data_size, - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE // base tx + sender write - + ACCOUNT_INFO_WRITE_SIZE // callee write (count only once) - + ACCOUNT_INFO_WRITE_SIZE // library write - ); -} - -// ============================================================================ -// NESTED CALL TESTS -// ============================================================================ - -/// Test that data size tracking correctly handles reverted nested calls. -/// -/// This test verifies that when a nested call fails (reverts), the data size -/// tracking still correctly accounts for storage reads that occurred before the -/// revert. It uses a contract that calls a library contract, where the library -/// performs storage operations and then reverts, ensuring that storage reads -/// are still included in the witness data even when the call fails. The test -/// demonstrates that read operations are tracked even in failed calls. -#[test] -fn test_nested_call_data_size_are_reverted_on_failure() { - let mut db = MemoryDatabase::default(); - // a simple contract that calls a library contract - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // value, argOffset, argLen, returnOffset, returnLen - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - // a library that sload and sstore and then revert - let library_code = - BytecodeBuilder::default().append_many([PUSH0, PUSH0, SLOAD, SSTORE, INVALID]).build(); - db.set_account_code(LIBRARY, library_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - // although the nested call is reverted, the outer call still succeeds - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_update_count, 1); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - ); -} - -/// Test that data size tracking correctly handles reverted nested contract creation. -/// -/// This test verifies that when a nested contract creation fails (reverts), the data size -/// tracking still works correctly. It uses a contract that attempts to create another -/// contract with a constructor that always reverts, ensuring that the outer call succeeds -/// but the nested creation fails without affecting the data size calculations. -#[test] -fn test_nested_creation_revert() { - let mut db = MemoryDatabase::default(); - // a contract constructor code that always revert - let constructor_code = BytecodeBuilder::default().revert().build(); - let constructor_code_len = constructor_code.len() as u64; - // a simple contract that creates a contract - let contract_code = BytecodeBuilder::default() - .mstore(0x0, constructor_code) - .push_number(constructor_code_len) // init code len - .push_number(0x0_u64) // init code offset in memory - .push_number(0x0_u64) // value to transfer - .append(CREATE) - .build(); - db.set_account_code(CALLEE, contract_code); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_update_count) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - // the outer call should succeed, even though the nested creation reverts - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_update_count, 1); - assert_eq!( - data_size, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - ); -} - -// ============================================================================ -// SPEC COMPARISON TESTS -// ============================================================================ - -// ============================================================================ -// LIMIT ENFORCEMENT TESTS -// ============================================================================ - -/// Test that data limit enforcement works correctly when the limit is not exceeded. -/// -/// This test verifies that transactions succeed when the generated data size is exactly -/// at the data limit threshold. It uses a simple call transaction that generates -/// the minimum data size (base transaction + sender account write) and sets the data -/// limit to that exact amount, ensuring the transaction completes successfully. -#[test] -fn test_data_limit_just_not_exceed() { - let mut db = MemoryDatabase::default(); - // the data size is 110 bytes for the intrinsic data of a transaction, 312 bytes for the caller - // account info update - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, _, _) = transact( - MegaSpecId::MINI_REX, - &mut db, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE, // sender write - u64::MAX, - tx, - ) - .unwrap(); - assert!(res.result.is_success()); -} - -/// Test that data limit enforcement correctly halts transactions when the limit is exceeded. -/// -/// This test verifies that transactions are halted when the generated data size exceeds -/// the data limit threshold. It uses a simple call transaction that generates -/// the minimum data size but sets the data limit to one byte less, ensuring -/// the transaction is halted with a `DataLimitExceeded` reason. -#[test] -fn test_data_limit_just_exceed() { - let mut db = MemoryDatabase::default(); - // the data size is 110 bytes for the intrinsic data of a transaction, 40 bytes for the caller - // account info update - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, _) = transact( - MegaSpecId::MINI_REX, - &mut db, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - -1, // minus one byte data size - u64::MAX, - tx, - ) - .expect("should succeed with halt"); - - // Should halt (not error) with DataLimitExceeded - assert!(matches!( - res.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); - - // Verify the data size tracked - assert_eq!(data_size, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); -} - -/// Test that KV update limit enforcement works correctly when the limit is not exceeded. -/// -/// This test verifies that transactions succeed when the number of key-value updates -/// is exactly at the KV update limit threshold. It uses an ether transfer transaction -/// that generates exactly 2 KV updates (caller and callee account updates) and sets -/// the KV update limit to 2, ensuring the transaction completes successfully. -#[test] -fn test_kv_update_limit_just_not_exceed() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - // 2 kv updates for the caller and callee account info updates - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(1)).build_fill(); - let (res, _, _) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, 2, tx).unwrap(); - assert!(res.result.is_success()); -} - -/// Test that KV update limit enforcement correctly halts transactions when the limit is exceeded. -/// -/// This test verifies that transactions are halted when the number of key-value updates -/// exceeds the KV update limit threshold. It uses an ether transfer transaction that -/// generates 2 KV updates (caller and callee account updates) but sets the KV update -/// limit to 1, ensuring the transaction is halted with a `KVUpdateLimitExceeded` reason. -#[test] -fn test_kv_update_limit_just_exceed() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(100)); - // 2 kv updates for the caller and callee account info updates - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(1)).build_fill(); - let (res, _, _) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, 2 - 1, tx).unwrap(); - assert!(res.result.is_halt()); - assert!(is_kv_update_limit_exceeded(&res)); -} - -/// Test that data limit enforcement correctly halts transactions in nested calls. -/// -/// This test verifies that when a nested call would exceed the data limit, the transaction -/// is properly halted with a `DataLimitExceeded` reason. It uses a contract that calls a -/// library contract, where the library performs storage operations that would exceed the -/// data limit, ensuring that the limit enforcement works correctly across call boundaries. -/// The test demonstrates that limits are enforced even in complex call scenarios. -#[test] -fn test_data_limit_exceed_in_nested_call() { - let mut db = MemoryDatabase::default(); - // a simple contract that calls a library contract - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // value, argOffset, argLen, returnOffset, returnLen - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - // a library that sload and sstore and then revert - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SLOAD, SSTORE, STOP]).build(); - db.set_account_code(LIBRARY, library_code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, _, _) = transact( - MegaSpecId::MINI_REX, - &mut db, - BASE_TX_SIZE // base tx - + ACCOUNT_INFO_WRITE_SIZE // sender write - + 1, // one additional data size - u64::MAX, - tx, - ) - .unwrap(); - assert!(res.result.is_halt()); - assert!(is_data_limit_exceeded(&res)); -} - -/// Test that KV update limit enforcement correctly halts transactions in nested calls. -/// -/// This test verifies that when a nested call would exceed the KV update limit, the transaction -/// is properly halted with a `KVUpdateLimitExceeded` reason. It uses a contract that calls a -/// library contract with value transfer, where the combined KV updates from the root call, -/// nested call, and library operations exceed the limit, ensuring that the limit enforcement -/// works correctly across call boundaries. The test demonstrates that KV update limits -/// are enforced even in complex nested call scenarios. -#[test] -fn test_kv_update_limit_exceed_in_nested_call() { - let mut db = MemoryDatabase::default(); - // a simple contract that sloads and then call a library - let contract_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // argOffset, argLen, returnOffset, returnLen - .push_number(1u8) // call value - .push_address(LIBRARY) // callee address - .append(GAS) // gas to forward - .append(CALL) - .build(); - db.set_account_code(CALLEE, contract_code); - db.set_account_balance(CALLEE, U256::from(10000)); - // a library that sstore and then revert - let library_code = - BytecodeBuilder::default().append_many([PUSH1, 0x1u8, PUSH0, SSTORE, INVALID]).build(); - db.set_account_code(LIBRARY, library_code); - // The tx makes 1 kv update in the root call for the caller account info update, 1 kv update in - // the nested call for value transfer, and 1 kv update in the library for storage write. We set - // the KV update limit to 2, so that the transaction is halted in the nested call with a - // `KVUpdateLimitExceeded` reason. - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, _, _) = transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, 3 - 1, tx).unwrap(); - assert!(res.result.is_halt()); - assert!(is_kv_update_limit_exceeded(&res)); -} - -// ============================================================================ -// STORAGE DEDUPLICATION TESTS -// ============================================================================ - -/// Test that writing zero to a storage slot should not be counted for data size/KV updates. -/// -/// This test verifies that writing zero to a storage slot (which effectively deletes -/// the slot) is not counted towards data size or KV update limits. This is important -/// for gas optimization and ensures that storage cleanup operations don't consume -/// unnecessary resources. The test writes 0x0 to slot 0 and verifies that only -/// the base transaction and sender account update are counted. -#[test] -fn test_writing_zero_to_slot_should_not_be_counted() { - let mut db = MemoryDatabase::default(); - // a contract writing 0x0 to slot 0 - let code: Bytes = BytecodeBuilder::default().append_many([PUSH0, PUSH0, SSTORE, STOP]).build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - assert_eq!(kv_updates, 1); - assert_eq!(data_size, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); // no storage slot write -} - -/// Test that writing twice to the same storage slot should be counted only once. -/// -/// This test verifies that multiple writes to the same storage slot within a single -/// transaction are deduplicated and counted only once for data size and KV update -/// purposes. This prevents abuse where contracts could write to the same slot -/// multiple times to artificially inflate their data usage. The test writes 0x1 -/// then 0x2 to slot 0 and verifies that only one storage write is counted. -#[test] -fn test_writing_twice_to_same_slot_should_be_counted_once() { - let mut db = MemoryDatabase::default(); - // a contract writing 0x1 to slot 0 and then 0x2 to slot 0 - let code: Bytes = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(0), U256::from(2)) - .build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase), 1 kv update for the storage slot - // write - assert_eq!(kv_updates, 2); - assert_eq!( - data_size, - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE // base tx + sender write - + STORAGE_SLOT_WRITE_SIZE // only one storage slot write - ); -} - -/// Test that eventually no change to a storage slot should not be counted. -/// -/// This test verifies that when a storage slot is modified and then reset to its -/// original value within the same transaction, the net effect is no change and -/// therefore no data size or KV update should be counted. This prevents contracts -/// from artificially inflating their resource usage by performing operations that -/// ultimately cancel out. The test writes 0x1 then 0x0 to slot 0 and verifies -/// that no storage write is counted since the final state is unchanged. -#[test] -fn test_eventually_no_change_to_slot_should_not_be_counted() { - let mut db = MemoryDatabase::default(); - // a contract writing 0x1 to slot 0 and then reset slot 0 to 0x0 - let code: Bytes = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(0), U256::from(0)) - .build(); - db.set_account_code(CALLEE, code); - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let (res, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - assert!(res.result.is_success()); - // 1 kv update for the caller account (tx nonce increase) - assert_eq!(kv_updates, 1); - assert_eq!(data_size, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); // no storage slot write -} - -// ============================================================================ -// STATE REVERT TESTS -// ============================================================================ - -/// Test that state is properly reverted when data limit is exceeded. -/// -/// This test verifies that when a transaction exceeds the data limit, the entire -/// state is properly reverted to its original state before the transaction. -/// It uses a contract that performs storage operations and value transfers, -/// ensuring that all changes are rolled back when the limit is exceeded. -#[test] -fn test_state_revert_when_exceeding_limit() { - let mut db = MemoryDatabase::default(); - // a contract that writes 0x1 to slot 0 - let code = BytecodeBuilder::default().sstore(U256::from(0), U256::from(1)).build(); - db.set_account_code(CALLEE, code); - db.set_account_balance(CALLER, U256::from(10000)); - // the tx also transfers value to the callee - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).value(U256::from(100)).build_fill(); - let (res, data_size, kv_updates) = transact( - MegaSpecId::MINI_REX, - &mut db, - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE // base tx + sender write - + 1, // one additional data size - u64::MAX, - tx, - ) - .unwrap(); - // the tx should be halted with a `DataLimitExceeded` reason, and the state should be reverted - assert!(res.result.is_halt()); - assert!(is_data_limit_exceeded(&res)); - assert_eq!(kv_updates, 1); // only 1 kv update for the caller account (tx nonce increase) - // base tx + sender write, no update on the contract - assert_eq!(data_size, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); - // the contract should not be changed (touched) - assert!(res.state.get(&CALLEE).is_none_or(|contract| !contract.is_touched())); - // the caller balance should not be changed (tx reverts) - assert!(res.state.get(&CALLER).is_some_and(|caller| caller.info.balance == U256::from(10000))); -} - -// ============================================================================ -// MULTIPLE TRANSACTION TESTS -// ============================================================================ - -/// Test that data limit and KV update limits reset for each transaction. -/// -/// This test verifies that when executing multiple transactions sequentially with the same -/// context (like when building a block), the data size and KV update counters properly -/// reset for each new transaction instead of accumulating across transactions. -#[test] -fn test_limits_reset_across_multiple_transactions() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(10000)); - - // Create context once and reuse it for multiple transactions - let mut context = MegaContext::new(&mut db, MegaSpecId::MINI_REX).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - context.modify_cfg(|cfg| { - cfg.disable_nonce_check = true; - }); - let mut evm = MegaEvm::new(context); - - // Execute first transaction - let tx1 = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let mut mega_tx1 = MegaTransaction::new(tx1); - mega_tx1.enveloped_tx = Some(Bytes::new()); - let res1 = alloy_evm::Evm::transact_raw(&mut evm, mega_tx1).unwrap(); - let data_size_after_tx1 = evm.ctx_ref().generated_data_size(); - let kv_updates_after_tx1 = evm.ctx_ref().kv_update_count(); - - // Verify first transaction generated some data and KV updates - assert_eq!(data_size_after_tx1, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); - assert_eq!(kv_updates_after_tx1, 1); - - // Commit the first transaction's state changes - evm.ctx_mut().db_mut().commit(res1.state); - - // Execute second transaction with same context - let tx2 = TxEnvBuilder::new().caller(CALLER).call(CALLEE).build_fill(); - let mut mega_tx2 = MegaTransaction::new(tx2); - mega_tx2.enveloped_tx = Some(Bytes::new()); - let _ = alloy_evm::Evm::transact_raw(&mut evm, mega_tx2).unwrap(); - let data_size_after_tx2 = evm.ctx_ref().generated_data_size(); - let kv_updates_after_tx2 = evm.ctx_ref().kv_update_count(); - - // Verify counters reset and show only second transaction's data - // Without reset, these would be 2x the single transaction values - assert_eq!(data_size_after_tx2, BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE); - assert_eq!(kv_updates_after_tx2, 1); -} - -// ============================================================================ -// GAS PRESERVATION TESTS -// ============================================================================ - -// ============================================================================ -// TRACKER MIGRATION COVERAGE TESTS -// ============================================================================ - -/// Tests that when a child frame both writes a storage slot (+1) and resets it back to original -/// (-1 refund), then reverts, BOTH the write and the refund are discarded. -/// -/// This exercises the new tracker's separate `discardable_usage` and `refund` fields -/// (vs the old tracker's single `i64 discardable`), ensuring they are both dropped on revert. -#[test] -fn test_child_write_and_refund_both_discarded_on_revert() { - // Child: write slot 0 from 0→1 (+1 write), then reset slot 0 from 1→0 (-1 refund), then REVERT - let child_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(1)) // write: +1 - .sstore(U256::from(0), U256::from(0)) // refund: -1 - .revert() - .build(); - - // Parent: write slot 5 from 0→1 (+1 write), CALL child, STOP - let parent_code = BytecodeBuilder::default() - .sstore(U256::from(5), U256::from(1)) // write: +1 - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIBRARY) // child address - .push_number(10_000_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - - let mut db = CacheDB::new(EmptyDB::new()); - db.insert_account_info( - CALLER, - revm::state::AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - db.insert_account_info( - CALLEE, - revm::state::AccountInfo { - code: Some(revm::bytecode::Bytecode::new_raw(parent_code)), - ..Default::default() - }, - ); - db.insert_account_info( - LIBRARY, - revm::state::AccountInfo { - code: Some(revm::bytecode::Bytecode::new_raw(child_code)), - ..Default::default() - }, - ); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(100_000_000).build_fill(); - - // Expected data_size: - // base tx (110) + caller account update (40) = 150 (non-discardable) - // + parent's SSTORE slot 5 write (40) = 190 - // Child's write (+40) and refund (-40) should both be discarded on revert. - let expected_data_size = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + STORAGE_SLOT_WRITE_SIZE; - - // Expected kv_updates: - // caller account update (1) + parent's SSTORE slot 5 write (1) = 2 - // Child's write (+1) and refund (-1) should both be discarded on revert. - let expected_kv_updates = 2; - - let (result, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - data_size, expected_data_size, - "Child's write and refund should both be discarded on revert" - ); - assert_eq!( - kv_updates, expected_kv_updates, - "Child's KV write and refund should both be discarded on revert" - ); -} - -/// Tests that TX intrinsic data (base tx size + caller account update) persists even when -/// the top-level frame reverts. This exercises the new tracker's `persistent_usage` field -/// at the TX entry level. -#[test] -fn test_tx_intrinsic_data_survives_top_level_revert() { - // CALLEE code: immediately REVERT - let code = BytecodeBuilder::default().revert().build(); - - let mut db = CacheDB::new(EmptyDB::new()); - db.insert_account_info( - CALLER, - revm::state::AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - db.insert_account_info( - CALLEE, - revm::state::AccountInfo { - code: Some(revm::bytecode::Bytecode::new_raw(code)), - ..Default::default() - }, - ); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(100_000_000).build_fill(); - - let (result, data_size, kv_updates) = - transact(MegaSpecId::MINI_REX, &mut db, u64::MAX, u64::MAX, tx).unwrap(); - - // Transaction should be reverted (not success, not halt) - assert!( - matches!(result.result, ExecutionResult::Revert { .. }), - "Expected top-level revert, got {:?}", - result.result - ); - - // TX intrinsic data should persist despite the revert: - // base tx size (110) + caller account update (40) = 150 - let expected_data_size = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE; - assert_eq!( - data_size, expected_data_size, - "TX intrinsic data (base + caller) should survive top-level revert" - ); - - // Caller account update should persist - assert_eq!(kv_updates, 1, "Caller account KV update should survive top-level revert"); -} - -/// Tests the `check_limit` priority order: `data_size` is checked before `kv_update`. -/// When both limits are exceeded simultaneously, the `data_size` error should be reported. -#[test] -fn test_check_limit_priority_data_size_before_kv_update() { - // Simple code that STOPs immediately — the intrinsic TX data already exceeds limits - let code = BytecodeBuilder::default().append(STOP).build(); - - let mut db = CacheDB::new(EmptyDB::new()); - db.insert_account_info( - CALLER, - revm::state::AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - db.insert_account_info( - CALLEE, - revm::state::AccountInfo { - code: Some(revm::bytecode::Bytecode::new_raw(code)), - ..Default::default() - }, - ); - - let tx = TxEnvBuilder::new().caller(CALLER).call(CALLEE).gas_limit(100_000_000).build_fill(); - - // Set both limits very low so both are exceeded by TX intrinsics: - // data_size will be 150 (110 base + 40 caller), exceeds limit=1 - // kv_updates will be 1 (caller), exceeds limit=0 - let (result, _, _) = transact(MegaSpecId::MINI_REX, &mut db, 1, 0, tx).unwrap(); - - assert!(result.result.is_halt(), "Expected halt, got {:?}", result.result); - - // data_size is checked before kv_update in the check_limit() order, - // so DataLimitExceeded should be reported - assert!( - is_data_limit_exceeded(&result), - "Expected DataLimitExceeded (checked first), got {:?}", - result.result - ); -} - -/// An inspector that mimics `TracerEip3155`'s `GasInspector` behavior: -/// calls `Gas::spend_all()` on error results in `call_end`. -/// -/// This reproduces the scenario where an inspector zeros `gas.remaining()` -/// which could interfere with `rescue_gas` if called in the wrong order. -struct GasSpendingInspector; - -impl Inspector for GasSpendingInspector { - fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, outcome: &mut CallOutcome) { - if !outcome.result.result.is_ok() { - outcome.result.gas.spend_all(); - } - } -} diff --git a/crates/mega-evm/tests/_pending/rex/main.rs b/crates/mega-evm/tests/_pending/rex/main.rs deleted file mode 100644 index f474f301d..000000000 --- a/crates/mega-evm/tests/_pending/rex/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Tests for Rex hardfork features. -mod oracle; -mod storage_gas; diff --git a/crates/mega-evm/tests/_pending/rex/oracle.rs b/crates/mega-evm/tests/_pending/rex/oracle.rs deleted file mode 100644 index 93c476f0a..000000000 --- a/crates/mega-evm/tests/_pending/rex/oracle.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! Tests for oracle contract access detection in Rex spec. -//! -//! Rex fixes STATICCALL oracle access detection that was bypassed in `MiniRex`. -//! CALLCODE and DELEGATECALL remain undetected because they execute in the caller's -//! state context (not the oracle's), so they don't constitute oracle access. - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, TestExternalEnvs, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::{CALLCODE, DELEGATECALL, GAS, PUSH0, STATICCALL}, - context::{result::ExecutionResult, TxEnv}, - inspector::NoOpInspector, - Inspector, -}; - -const CALLER: alloy_primitives::Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); - -/// Helper function to execute a transaction with the given spec and database. -/// Returns a tuple of `(ExecutionResult, oracle_accessed: bool)`. -fn execute_transaction< - 'a, - INSP: Inspector>>, ->( - spec: MegaSpecId, - db: &'a mut MemoryDatabase, - external_envs: &'a TestExternalEnvs, - inspector: INSP, - target: alloy_primitives::Address, -) -> (ExecutionResult, bool) { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(target), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(inspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - let oracle_accessed = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.has_accessed_oracle()) - .unwrap_or(false); - - (result, oracle_accessed) -} - -/// Test that STATICCALL to oracle IS detected in Rex. -/// -/// Rex fixes the `MiniRex` bypass: STATICCALL to oracle now triggers oracle access detection. -#[test] -fn test_rex_staticcall_oracle_access_detected() { - // STATICCALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(STATICCALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, oracle_accessed) = - execute_transaction(MegaSpecId::REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(oracle_accessed, "STATICCALL to oracle should be detected in Rex"); -} - -/// Test that DELEGATECALL to oracle is NOT detected in Rex. -/// -/// DELEGATECALL executes in the caller's state context, not the oracle's, so it does not -/// constitute oracle access. -#[test] -fn test_rex_delegatecall_oracle_access_not_detected() { - // DELEGATECALL: gas, addr, argsOff, argsLen, retOff, retLen (6 args, no value) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(DELEGATECALL) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, oracle_accessed) = - execute_transaction(MegaSpecId::REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "DELEGATECALL to oracle should not be detected in Rex"); -} - -/// Test that CALLCODE to oracle is NOT detected in Rex. -/// -/// CALLCODE executes in the caller's state context, not the oracle's, so it does not -/// constitute oracle access. -#[test] -fn test_rex_callcode_oracle_access_not_detected() { - // CALLCODE: gas, addr, value, argsOff, argsLen, retOff, retLen (7 args) - let bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) // retLen, retOff, argsLen, argsOff, value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALLCODE) - .stop() - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, bytecode); - - let external_envs = TestExternalEnvs::::new(); - let (result, oracle_accessed) = - execute_transaction(MegaSpecId::REX, &mut db, &external_envs, NoOpInspector, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - assert!(!oracle_accessed, "CALLCODE to oracle should not be detected in Rex"); -} diff --git a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs deleted file mode 100644 index cf4024147..000000000 --- a/crates/mega-evm/tests/_pending/rex2/keyless_deploy.rs +++ /dev/null @@ -1,1824 +0,0 @@ -//! Tests for keyless deployment. -//! -//! This module provides comprehensive tests for the keyless deployment system contract, -//! including success cases, error conditions, and edge cases. - -use alloy_primitives::{address, hex, keccak256, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxEip1559, TxLegacy}, - revm::context::result::{ExecutionResult, ResultAndState}, - sandbox::{ - decode_error_result, - tests::{ - CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, - CREATE2_FACTORY_TX, EIP1820_CODE_HASH, EIP1820_CONTRACT, EIP1820_DEPLOYER, EIP1820_TX, - NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX, - }, - KeylessDeployError, - }, - test_utils::{transact, BytecodeBuilder, MemoryDatabase}, - IKeylessDeploy, MegaSpecId, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, -}; -use revm::{ - bytecode::opcode::{ - CALL, CALLDATACOPY, CALLDATASIZE, CODECOPY, CREATE, GAS, ISZERO, JUMPDEST, JUMPI, LOG0, - MLOAD, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, - SSTORE, STATICCALL, STOP, - }, - Database, DatabaseCommit, -}; - -// ============================================================================= -// Test Constants -// ============================================================================= - -/// Standard test caller address. -const TEST_CALLER: Address = address!("0000000000000000000000000000000000100000"); - -/// Large gas limit override for tests (10 billion gas). -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -// ============================================================================= -// Helper Functions -// ============================================================================= - -/// Calls the keyless deploy precompile and returns the result. -fn call_keyless_deploy( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx_bytes: Bytes, - gas_limit_override: u64, - value: U256, -) -> ResultAndState { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - transact(spec, db, TEST_CALLER, Some(KEYLESS_DEPLOY_ADDRESS), call_data.into(), value).unwrap() -} - -/// Checks if two `KeylessDeployErrors` match, ignoring the halt reason for `ExecutionHalted`. -fn errors_match(a: &KeylessDeployError, b: &KeylessDeployError) -> bool { - match (a, b) { - // For ExecutionHalted, only compare gas_used (reason can't be recovered from ABI) - ( - KeylessDeployError::ExecutionHalted { gas_used: a_gas, .. }, - KeylessDeployError::ExecutionHalted { gas_used: b_gas, .. }, - ) => a_gas == b_gas, - // For all other variants, use standard equality - _ => a == b, - } -} - -/// Asserts that the result is a revert with the expected error. -fn assert_revert_with_error( - result: &ResultAndState, - expected: KeylessDeployError, -) { - match &result.result { - ExecutionResult::Revert { output, .. } => { - let error = decode_error_result(output) - .unwrap_or_else(|| panic!("Failed to decode error from output: {:?}", output)); - assert!(errors_match(&error, &expected), "Expected {:?}, got {:?}", expected, error); - } - other => panic!("Expected Revert, got {:?}", other), - } -} - -/// Creates a pre-EIP-155 signed transaction with custom nonce, init code and value. -/// -/// Uses a deterministic signature (r=s=0x2222...2222, v=27) similar to Nick's Method. -/// The recovered signer address will be deterministic based on the transaction content. -fn create_pre_eip155_deploy_tx_with_nonce_and_value( - nonce: u64, - init_code: Bytes, - value: U256, -) -> (Bytes, Address) { - let tx = TxLegacy { - nonce, - gas_price: 100_000_000_000, // 100 gwei - gas_limit: 1_000_000, // 1M gas for more complex init codes - to: TxKind::Create, - value, - input: init_code, - chain_id: None, // Pre-EIP-155 - }; - - // Use the same deterministic signature as Nick's Method (r=s=0x2222...2222) - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); // v=27 means y_parity=false for pre-EIP-155 - - // Create signed transaction - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - // RLP encode the signed transaction - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - - // Recover the signer address - let signer = signed.recover_signer().expect("should recover signer"); - - (tx_bytes, signer) -} - -/// Creates a pre-EIP-155 signed transaction with custom init code and value (nonce=0). -fn create_pre_eip155_deploy_tx_with_value(init_code: Bytes, value: U256) -> (Bytes, Address) { - create_pre_eip155_deploy_tx_with_nonce_and_value(0, init_code, value) -} - -/// Creates a pre-EIP-155 signed transaction with custom init code (nonce=0, value=0). -fn create_pre_eip155_deploy_tx(init_code: Bytes) -> (Bytes, Address) { - create_pre_eip155_deploy_tx_with_nonce_and_value(0, init_code, U256::ZERO) -} - -/// Calculate the deployed contract address for a keyless deploy transaction. -fn calculate_deploy_address_for_tx(tx_bytes: &[u8]) -> Address { - use mega_evm::{ - sandbox::{calculate_keyless_deploy_address, decode_keyless_tx, recover_signer}, - MegaSpecId, - }; - let signed = decode_keyless_tx(tx_bytes, MegaSpecId::REX2).expect("should decode tx"); - let signer = recover_signer(&signed).expect("should recover signer"); - calculate_keyless_deploy_address(signer) -} - -// ============================================================================= -// Success Tests -// ============================================================================= - -#[test] -fn test_keyless_deploy_eip1820() { - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH for gas (100 gwei * 10B gas = 1000 ETH) - db.set_account_balance(EIP1820_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from(EIP1820_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Decode return value - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify deployed address matches expected EIP-1820 address - assert_eq!(ret.deployedAddress, EIP1820_CONTRACT); - assert!(ret.gasUsed > 0, "Expected non-zero gas usage"); - - // Verify contract code exists at deployed address - let contract = state.get(&EIP1820_CONTRACT).expect("contract should exist in state"); - assert!( - contract.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "contract should have non-empty code" - ); - assert_eq!(contract.info.code_hash, EIP1820_CODE_HASH, "contract code hash should match"); -} - -#[test] -fn test_keyless_deploy_create2_factory() { - // Deploy the canonical CREATE2 factory - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH (100 gwei * 10B gas = 1000 ETH) - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Decode return value - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify deployed address matches expected CREATE2 factory address - assert_eq!(ret.deployedAddress, CREATE2_FACTORY_CONTRACT); - assert!(ret.gasUsed > 0, "Expected non-zero gas usage"); - - // Verify contract code exists at deployed address - let contract = state.get(&CREATE2_FACTORY_CONTRACT).expect("contract should exist in state"); - assert!( - contract.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "contract should have non-empty code" - ); - assert_eq!( - contract.info.code_hash, CREATE2_FACTORY_CODE_HASH, - "contract code hash should match" - ); -} - -// ============================================================================= -// Error Condition Tests -// ============================================================================= - -#[test] -fn test_keyless_deploy_rejects_ether_transfer() { - // Calling with value > 0 should revert with NoEtherTransfer - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - // Fund caller so they can send ether - db.set_account_balance(TEST_CALLER, U256::from(1_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::from(1), // Non-zero value - ); - - assert_revert_with_error(&result, KeylessDeployError::NoEtherTransfer); -} - -#[test] -fn test_keyless_deploy_gas_limit_too_low() { - // Using gasLimitOverride < tx.gas_limit should revert with GasLimitTooLow - // CREATE2 factory tx has gas_limit = 100,000 - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let too_low_gas_limit = 99_999; // < 100,000 - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - too_low_gas_limit, - U256::ZERO, - ); - - assert_revert_with_error( - &result, - KeylessDeployError::GasLimitTooLow { - tx_gas_limit: 100_000, - provided_gas_limit: too_low_gas_limit, - }, - ); -} - -#[test] -fn test_keyless_deploy_insufficient_balance_zero() { - // Signer has zero balance - should revert with InsufficientBalance - let mut db = MemoryDatabase::default(); - // Don't fund the deployer at all - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::InsufficientBalance); -} - -#[test] -fn test_keyless_deploy_insufficient_balance_partial() { - // Signer has some balance but not enough for gas cost - let mut db = MemoryDatabase::default(); - // Required: gas_price * gas_limit_override = 100 gwei * 10B = 1000 ETH - // Fund with just 1 ETH (way less than needed) - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::InsufficientBalance); -} - -#[test] -fn test_keyless_deploy_contract_already_exists() { - // Pre-deploy code at target address - should revert with ContractAlreadyExists - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Pre-deploy some code at the target address - db.set_account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::ContractAlreadyExists); -} - -/// REX6 only: the deploy-address occupancy check must read through the journal -/// (`JournalInspectTr::inspect_account`), not a raw `database.basic` call, so the deploy address -/// is present in the returned `EvmState` / witness — even though the transaction as a whole -/// reverts. A stateless verifier replaying this transaction needs the deploy address's pre-state -/// in its witness to independently confirm the `ContractAlreadyExists` revert was warranted; -/// before this fix the raw DB read bypassed the journal entirely and the address never appeared -/// in `result.state`. -/// -/// REX6-only: review found that journaling this read pre-REX5 corrupts the legacy sandbox-state -/// merge (`apply_sandbox_state_legacy`), which does not carry account status through an -/// already-`Occupied` journal entry — see -/// `test_keyless_deploy_pre_rex6_success_still_commits_deployed_code` below for the regression -/// this would cause if ever ungated. -#[test] -fn test_keyless_deploy_contract_already_exists_deploy_address_in_witness_rex6() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); - - let result = call_keyless_deploy( - MegaSpecId::REX6, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::ContractAlreadyExists); - assert!( - result.state.contains_key(&CREATE2_FACTORY_CONTRACT), - "the deploy address's occupancy read must appear in the returned EvmState \ - (witness) under REX6, even on the ContractAlreadyExists revert path", - ); -} - -/// REX6 twin of the test above: under REX6 the step-7 occupancy check journals the deploy -/// address (cold, via `inspect_account_code_hash`) *before* the sandbox runs, so at merge time -/// the address is already an occupied journal entry rather than a fresh one. The merge must -/// still carry the `Created|Touched` status through that occupied entry so `commit()` keeps the -/// account — this is the same `db.commit()` round trip as the pre-REX6 sibling, run under REX6. -#[test] -fn test_keyless_deploy_rex6_success_still_commits_deployed_code() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX6, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - assert!(result.result.is_success(), "keyless deploy should succeed: {:?}", result.result); - - db.commit(result.state); - let deployed = db.basic(CREATE2_FACTORY_CONTRACT).unwrap(); - assert!( - deployed.is_some_and(|info| info.code_hash == CREATE2_FACTORY_CODE_HASH), - "the deployed contract must survive a commit() round trip on REX6 — a regression here \ - means the occupancy-check journal read is dropping AccountStatus through the already- \ - occupied journal entry it creates", - ); -} - -#[test] -fn test_keyless_deploy_invalid_signature() { - // Corrupt the signature's r value - should revert with InvalidSignature - let mut db = MemoryDatabase::default(); - - // CREATE2_FACTORY_TX structure: - // Total length: 167 bytes - // r value is at bytes 102-133 (32 bytes, after a0 prefix at byte 101) - // s value is at bytes 135-166 (32 bytes, after a0 prefix at byte 134) - // - // Set r to all 0xFF to make signature recovery fail while keeping valid RLP - let mut corrupted_tx = CREATE2_FACTORY_TX.to_vec(); - // r value is at offset 102, 32 bytes - corrupted_tx[102..134].fill(0xff); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from(corrupted_tx), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::InvalidSignature); -} - -#[test] -fn test_keyless_deploy_malformed_encoding() { - // Pass invalid RLP bytes - should revert with MalformedEncoding - let mut db = MemoryDatabase::default(); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(&hex!("deadbeef")), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::MalformedEncoding); -} - -#[test] -fn test_keyless_deploy_not_contract_creation() { - // Use tx with `to` address - should revert with NotContractCreation - let mut db = MemoryDatabase::default(); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(NON_CONTRACT_CREATION_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::NotContractCreation); -} - -#[test] -fn test_keyless_deploy_not_pre_eip155() { - // Use post-EIP-155 tx with chain_id - should revert with NotPreEIP155 - let mut db = MemoryDatabase::default(); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(POST_EIP155_CHAIN_1_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::NotPreEIP155); -} - -#[test] -fn test_keyless_deploy_non_zero_tx_nonce() { - // Transaction with non-zero nonce should revert with NonZeroTxNonce. - // Nick's Method requires nonce=0 to ensure the deployed address is deterministic: - // contract_address = keccak256(rlp([signer, 0]))[12:] - let mut db = MemoryDatabase::default(); - - // Create a valid pre-EIP-155 transaction but with nonce=1 instead of 0 - let init_code = Bytes::from_static(&hex!("6000")); // PUSH1 0x00 (minimal init code) - let (tx_bytes, signer) = - create_pre_eip155_deploy_tx_with_nonce_and_value(1, init_code, U256::ZERO); - - // Fund the signer - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result, KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); -} - -#[test] -fn test_keyless_deploy_rejects_corrupted_signature() { - // Corrupted signatures (invalid curve points) should be rejected. - // This tests that signature recovery properly validates the signature. - let mut db = MemoryDatabase::default(); - - // Take the CREATE2 factory tx and corrupt the r value to make recovery fail. - // Setting r to all 0xFF values creates an invalid curve point. - let mut corrupted_tx = CREATE2_FACTORY_TX.to_vec(); - - // In CREATE2_FACTORY_TX, r is at offset 102-134 (32 bytes after 0xa0 prefix at 101) - corrupted_tx[102..134].fill(0xff); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from(corrupted_tx), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Invalid signature components fail during recovery - assert_revert_with_error(&result, KeylessDeployError::InvalidSignature); -} - -#[test] -fn test_keyless_deploy_modified_s_changes_signer() { - // Modifying the s value changes the recovered signer address. - // This demonstrates that signature manipulation produces a different identity. - // Note: Alloy does NOT reject high-s signatures; it recovers a different signer. - let mut db = MemoryDatabase::default(); - - // Take the CREATE2 factory tx and modify s. - // The recovered signer will be different and have no funds. - let mut modified_tx = CREATE2_FACTORY_TX.to_vec(); - - // Modify s (at offset 135-167) to a different value - modified_tx[135..167].fill(0x33); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from(modified_tx), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // The modified signature recovers a different signer who has no funds - assert_revert_with_error(&result, KeylessDeployError::InsufficientBalance); -} - -#[test] -fn test_keyless_deploy_rejects_eip2718_typed_envelope() { - // EIP-2718 typed transaction envelopes (0x01, 0x02, etc.) should be rejected. - // These are not valid pre-EIP-155 legacy transactions. - let mut db = MemoryDatabase::default(); - - // Create an EIP-1559 (type 0x02) transaction using alloy types - let eip1559_tx = TxEip1559 { - chain_id: 1, - nonce: 0, - gas_limit: 100_000, - max_fee_per_gas: 100_000_000_000, - max_priority_fee_per_gas: 1_000_000_000, - to: TxKind::Create, - value: U256::ZERO, - input: Bytes::from_static(&[0x60, 0x80, 0x60, 0x40, 0x52]), // Simple init code - access_list: Default::default(), - }; - - // Sign with a dummy signature - let sig = Signature::new(U256::from(0x1234u64), U256::from(0x5678u64), false); - let signed = Signed::new_unchecked(eip1559_tx, sig, B256::ZERO); - - // Encode as EIP-2718 typed envelope (0x02 || RLP(...)) - // RLP encode the signed transaction - let mut rlp_encoded = Vec::new(); - signed.rlp_encode(&mut rlp_encoded); - - // Prepend the EIP-1559 type byte (0x02) to create the typed envelope - let mut encoded = vec![0x02]; - encoded.extend_from_slice(&rlp_encoded); - - // Verify it starts with 0x02 (EIP-1559 type) - assert_eq!(encoded[0], 0x02, "EIP-1559 tx should start with type byte 0x02"); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from(encoded), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // EIP-2718 envelopes don't start with RLP list header, so decoding as legacy fails - assert_revert_with_error(&result, KeylessDeployError::MalformedEncoding); -} - -#[test] -fn test_keyless_deploy_empty_initcode() { - // Empty initcode creates a contract with empty runtime code. - // This triggers EmptyCodeDeployed error (returns success with error data). - let mut db = MemoryDatabase::default(); - - // Create a pre-EIP-155 tx with empty data (empty initcode) - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(Bytes::new()); - - // Fund the signer - let initial_balance = U256::from(1_000_000_000_000_000_000_000u128); - db.set_account_balance(signer, initial_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Empty initcode triggers EmptyCodeDeployed (returns success with error data) - assert!( - matches!(result.result, ExecutionResult::Success { .. }), - "Expected Success with EmptyCodeDeployed error, got {:?}", - result.result - ); - - let output = result.result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output) - .expect("should decode return value"); - - assert_eq!(ret.deployedAddress, Address::ZERO, "Should return zero address"); - assert!(!ret.errorData.is_empty(), "Should have error data"); - - let error = decode_error_result(&ret.errorData).expect("Should decode error"); - assert!( - matches!(error, KeylessDeployError::EmptyCodeDeployed { .. }), - "Expected EmptyCodeDeployed, got {:?}", - error - ); - - // Signer should be charged for gas (state changes persist) - let signer_account = result.state.get(&signer).expect("signer should exist"); - assert!(signer_account.info.balance < initial_balance, "Signer should be charged"); -} - -#[test] -fn test_keyless_deploy_execution_reverted() { - // Init code that calls REVERT - returns success with ExecutionReverted error data - // This allows state changes to persist and the signer to be charged for gas - let mut db = MemoryDatabase::default(); - - // Init code: PUSH1 0x00 PUSH1 0x00 REVERT - // Bytecode: 60 00 60 00 fd (offset=0, size=0, REVERT) - let init_code = Bytes::from_static(&hex!("60006000fd")); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - // Fund the recovered signer - let initial_balance = U256::from(1_000_000_000_000_000_000_000u128); - db.set_account_balance(signer, initial_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify it returns success with error data (not revert) - assert!( - matches!(result.result, ExecutionResult::Success { .. }), - "Expected Success with error data, got {:?}", - result.result - ); - - // Decode the 3-value return type - let output = result.result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output) - .expect("should decode return value"); - - // Failed deploy should return zero address - assert_eq!(ret.deployedAddress, Address::ZERO, "Failed deploy should return zero address"); - - // Error data should be populated - assert!(!ret.errorData.is_empty(), "Failed deploy should have error data"); - - // Decode and verify the error - let error = decode_error_result(&ret.errorData) - .unwrap_or_else(|| panic!("Failed to decode error from errorData")); - match error { - KeylessDeployError::ExecutionReverted { gas_used, .. } => { - assert!(gas_used > 0, "Expected non-zero gas usage"); - assert_eq!(ret.gasUsed, gas_used, "gasUsed in return should match error"); - - // Verify signer was charged for gas (state changes persisted) - let signer_account = result.state.get(&signer).expect("signer should exist in state"); - let expected_charge = U256::from(gas_used) * U256::from(100_000_000_000u64); - assert_eq!(signer_account.info.balance, initial_balance - expected_charge); - } - other => panic!("Expected ExecutionReverted, got {:?}", other), - } -} - -#[test] -fn test_keyless_deploy_execution_halted_invalid_opcode() { - // Init code with INVALID (0xfe) opcode - returns success with ExecutionHalted error data - // This allows state changes to persist and the signer to be charged for gas - let mut db = MemoryDatabase::default(); - - // Init code: INVALID - // Bytecode: fe - let init_code = Bytes::from_static(&hex!("fe")); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - // Fund the recovered signer - let initial_balance = U256::from(1_000_000_000_000_000_000_000u128); - db.set_account_balance(signer, initial_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify it returns success with error data (not revert) - assert!( - matches!(result.result, ExecutionResult::Success { .. }), - "Expected Success with error data, got {:?}", - result.result - ); - - // Decode the 3-value return type - let output = result.result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output) - .expect("should decode return value"); - - // Failed deploy should return zero address - assert_eq!(ret.deployedAddress, Address::ZERO, "Failed deploy should return zero address"); - - // Error data should be populated - assert!(!ret.errorData.is_empty(), "Failed deploy should have error data"); - - // Decode and verify the error - let error = decode_error_result(&ret.errorData) - .unwrap_or_else(|| panic!("Failed to decode error from errorData")); - match error { - KeylessDeployError::ExecutionHalted { gas_used, .. } => { - assert!(gas_used > 0, "Expected non-zero gas usage"); - assert_eq!(ret.gasUsed, gas_used, "gasUsed in return should match error"); - - // Verify signer was charged for gas (state changes persisted) - let signer_account = result.state.get(&signer).expect("signer should exist in state"); - let expected_charge = U256::from(gas_used) * U256::from(100_000_000_000u64); - assert_eq!(signer_account.info.balance, initial_balance - expected_charge); - } - other => panic!("Expected ExecutionHalted, got {:?}", other), - } -} - -// ============================================================================= -// Edge Case / Boundary Tests -// ============================================================================= - -#[test] -fn test_keyless_deploy_gas_limit_exactly_equal() { - // gasLimitOverride == tx.gas_limit should succeed (boundary case) - // CREATE2 factory tx has gas_limit = 100,000 - let mut db = MemoryDatabase::default(); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Use exactly the tx gas limit (100,000) - // Note: This test may still fail if MegaETH's gas model needs more gas, - // but at least we verify the gas limit check passes - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - 100_000, // Exactly matches tx gas_limit - U256::ZERO, - ); - - // Should NOT be GasLimitTooLow error - may be ExecutionHalted if gas runs out - // Success is also acceptable - if let ExecutionResult::Revert { output, .. } = &result.result { - let error = decode_error_result(output) - .unwrap_or_else(|| panic!("Failed to decode error from output: {:?}", output)); - assert!( - !matches!(error, KeylessDeployError::GasLimitTooLow { .. }), - "Should not get GasLimitTooLow with exact gas limit, got: {:?}", - error - ); - } -} - -#[test] -fn test_keyless_deploy_balance_exactly_sufficient() { - // Signer balance = exact cost needed - should succeed - // CREATE2 factory tx has gas_price = 100 gwei (100_000_000_000 wei) - let mut db = MemoryDatabase::default(); - - // Calculate exact required balance: gas_price * gas_limit_override - // For CREATE2 factory: 100 gwei * 10B gas = 1000 ETH - let gas_price = 100_000_000_000u64; // 100 gwei - let exact_balance = U256::from(gas_price) * U256::from(LARGE_GAS_LIMIT_OVERRIDE); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, exact_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Should succeed with exact balance - let ResultAndState { result, .. } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success with exact balance, got: {:?}", - result - ); -} - -#[test] -fn test_keyless_deploy_increments_nonce_from_zero() { - // Verify that when the signer's initial nonce is 0, it becomes 1 after successful deployment. - // This is critical for replay protection - the nonce change marks the signer as "used". - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH (nonce defaults to 0) - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Note: initial nonce is 0 by default (not explicitly set) - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Verify signer's nonce is now 1 - let deployer = state.get(&CREATE2_FACTORY_DEPLOYER).expect("deployer should exist in state"); - assert_eq!(deployer.info.nonce, 1, "deployer nonce should be incremented from 0 to 1"); - - // Verify the contract was deployed at the correct address - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - assert_eq!(ret.deployedAddress, CREATE2_FACTORY_CONTRACT); -} - -#[test] -fn test_keyless_deploy_nonce_override_to_zero() { - // Even if the signer has a non-zero nonce (up to 1), keyless deploy should override it to 0 - // so the contract deploys at the expected address (CREATE address depends on nonce). - // Note: Signers with nonce > 1 are rejected to prevent replay attacks. - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Set nonce to 1 for the deployer - this is the maximum allowed for keyless deploy. - // If nonce isn't overridden, the contract would deploy at a different address. - db.set_account_nonce(CREATE2_FACTORY_DEPLOYER, 1); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Decode return value and verify the address matches the expected one - // (which is computed with nonce=0) - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - assert_eq!( - ret.deployedAddress, CREATE2_FACTORY_CONTRACT, - "Contract should deploy at expected address (nonce=0)" - ); - - // Verify contract code exists at the expected address - let contract = state.get(&CREATE2_FACTORY_CONTRACT).expect("contract should exist in state"); - assert!( - contract.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "contract should have non-empty code" - ); - assert_eq!(contract.info.code_hash, CREATE2_FACTORY_CODE_HASH); - - let deployer = state.get(&CREATE2_FACTORY_DEPLOYER).expect("deployer should exist in state"); - assert_eq!(deployer.info.nonce, 1, "deployer nonce should be left unchanged"); -} - -#[test] -fn test_keyless_deploy_signer_nonce_too_high() { - // Signers with nonce > 1 should be rejected to prevent replay attacks. - // This ensures keyless deploy can only be used for fresh or nearly-fresh signers. - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Set nonce to 2 (one above the allowed maximum of 1) - db.set_account_nonce(CREATE2_FACTORY_DEPLOYER, 2); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Should revert with SignerNonceTooHigh (validation error, not execution error) - assert_revert_with_error(&result, KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); -} - -// ============================================================================= -// Spec Version Tests -// ============================================================================= - -#[test] -fn test_keyless_deploy_not_intercepted_for_inner_calls() { - // Keyless deploy should only work for top-level calls (depth == 0). - // When a contract calls keylessDeploy, it should NOT be intercepted and - // the actual Solidity contract should execute, reverting with NotIntercepted. - let mut db = MemoryDatabase::default(); - - // Deploy the keyless deploy contract code at KEYLESS_DEPLOY_ADDRESS. - // This is normally done by the system during block processing, but test_utils::transact - // doesn't do this. For inner calls, the actual Solidity contract needs to exist. - assert!(!KEYLESS_DEPLOY_CODE.is_empty(), "KEYLESS_DEPLOY_CODE should not be empty"); - db.set_account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); - - // Create a proxy contract that calls KEYLESS_DEPLOY_ADDRESS and propagates the revert - // using BytecodeBuilder for cleaner code generation. - // - // The proxy: - // 1. Copies calldata to memory - // 2. CALLs KEYLESS_DEPLOY_ADDRESS - // 3. If call succeeds: returns the return data - // 4. If call fails: reverts with the revert data - let proxy_code = BytecodeBuilder::default() - // Copy calldata to memory at offset 0 - .append(CALLDATASIZE) - .append(PUSH0) // srcOffset - .append(PUSH0) // destOffset - .append(CALLDATACOPY) - // CALL args: retSize=0, retOffset=0, argsSize=CALLDATASIZE, argsOffset=0, value=0, addr, - // gas - .append(PUSH0) // retSize - .append(PUSH0) // retOffset - .append(CALLDATASIZE) // argsSize - .append(PUSH0) // argsOffset - .append(PUSH0) // value - .push_address(KEYLESS_DEPLOY_ADDRESS) - .append(GAS) - .append(CALL) - // Stack now has: [success (0 or 1)] - // If success == 0 (call failed), propagate the revert - .append(ISZERO) - .push_number(0x2b_u8) // jump to revert if failed (JUMPDEST is at offset 43 = 0x2b) - .append(JUMPI) - // Success path: copy return data and return (7 bytes: 0x26-0x2c) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(PUSH0) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(RETURN) - // Revert path (at offset 0x2d): copy return data and revert - .append(JUMPDEST) // JUMPDEST - .append(RETURNDATASIZE) - .append(PUSH0) - .append(PUSH0) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .append(PUSH0) - .append(REVERT) - .build(); - - // Set up the proxy contract - let proxy_address = address!("0000000000000000000000000000000000300000"); - db.set_account_code(proxy_address, proxy_code); - - // Fund accounts - db.set_account_balance(TEST_CALLER, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - // Create the keylessDeploy calldata - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), - gasLimitOverride: U256::from(LARGE_GAS_LIMIT_OVERRIDE), - } - .abi_encode(); - - // Call the proxy contract - the proxy will make an INNER call to keylessDeploy - // Since depth > 0, it should NOT be intercepted, and the Solidity contract - // should execute and revert with NotIntercepted - let result = transact( - MegaSpecId::REX2, - &mut db, - TEST_CALLER, - Some(proxy_address), - call_data.into(), - U256::ZERO, - ) - .unwrap(); - - // The proxy should revert because the inner call to keylessDeploy reverted with NotIntercepted - assert_revert_with_error(&result, KeylessDeployError::NotIntercepted); -} - -/// Test that the keyless deploy contract is deployed when Rex2 activates via block executor. -/// This exercises the deployment logic in block/executor.rs `pre_execution_changes`. -#[test] -fn test_keyless_deploy_contract_deployed_on_rex2_activation() { - use alloy_evm::{block::BlockExecutor, Evm, EvmEnv, EvmFactory}; - use alloy_hardforks::ForkCondition; - use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; - use alloy_primitives::B256; - use mega_evm::{ - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardfork, - MegaHardforkConfig, TestExternalEnvs, KEYLESS_DEPLOY_CODE_HASH, - }; - use revm::{context::BlockEnv, database::State}; - - // Create a fresh in-memory database - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - // Create EVM factory and environment - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - - // Create EVM environment with Rex2 spec - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX2; - let block_env = BlockEnv { - number: revm::primitives::U256::from(1000), - timestamp: revm::primitives::U256::from(1_800_000_000), - gas_limit: 30_000_000, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - // Create the EVM instance - let evm = evm_factory.create_evm(&mut state, evm_env); - - // Create block execution context - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Default::default(), - BlockLimits::no_limits(), - ); - - // Configure hardforks with Rex2 activated at timestamp 0 - let chain_spec = - MegaHardforkConfig::default().with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - - // Create receipt builder - let receipt_builder = OpAlloyReceiptBuilder::default(); - - // Create block executor - let mut executor = MegaBlockExecutor::new(evm, block_ctx, chain_spec.clone(), receipt_builder); - - // Call apply_pre_execution_changes which triggers keyless deploy contract deployment - executor.apply_pre_execution_changes().expect("Pre-execution changes should succeed"); - - // Verify the keyless deploy contract is deployed in the database - let db_ref = executor.evm_mut().db_mut(); - - // Load the keyless deploy contract account from the cache - let cache_acc = - db_ref.load_cache_account(KEYLESS_DEPLOY_ADDRESS).expect("Should be able to load account"); - let acc_info = cache_acc.account_info().expect("Keyless deploy contract account should exist"); - - // Verify code hash matches - assert_eq!( - acc_info.code_hash, KEYLESS_DEPLOY_CODE_HASH, - "Keyless deploy contract code hash should match" - ); - - // Verify code is set and matches - assert!(acc_info.code.is_some(), "Code should be set on the account"); - let deployed_code = acc_info.code.as_ref().unwrap(); - assert_eq!( - deployed_code.original_bytes(), - KEYLESS_DEPLOY_CODE, - "Deployed code should match original code" - ); - - // Verify that calling transact_deploy_keyless_deploy_contract again returns state - // with account marked as read (proving the contract is already deployed) - use mega_evm::transact_deploy_keyless_deploy_contract; - let result = transact_deploy_keyless_deploy_contract(&chain_spec, 0, db_ref) - .expect("Should not error") - .unwrap(); - assert_eq!( - result.len(), - 1, - "Keyless deploy should already be deployed, so function should return state with account marked as read" - ); -} - -// ============================================================================= -// Corner Case Tests -// ============================================================================= - -#[test] -fn test_keyless_deploy_address_with_existing_balance() { - // Test: Deploy address has ETH balance but no code - should succeed - let mut db = MemoryDatabase::default(); - - // Calculate expected deploy address for CREATE2_FACTORY_TX - let deploy_address = calculate_deploy_address_for_tx(CREATE2_FACTORY_TX); - assert_eq!(deploy_address, CREATE2_FACTORY_CONTRACT); - - // Pre-fund the deploy address with 1 ETH (no code) - let pre_existing_balance = U256::from(1_000_000_000_000_000_000u128); // 1 ETH - db.set_account_balance(deploy_address, pre_existing_balance); - - // Fund deployer with enough ETH for gas - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Decode return value - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - assert_eq!(ret.deployedAddress, CREATE2_FACTORY_CONTRACT); - - // Verify contract code exists and balance is preserved - let contract = state.get(&CREATE2_FACTORY_CONTRACT).expect("contract should exist in state"); - assert!( - contract.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "contract should have non-empty code" - ); - assert_eq!( - contract.info.code_hash, CREATE2_FACTORY_CODE_HASH, - "contract code hash should match" - ); - assert_eq!(contract.info.balance, pre_existing_balance, "balance should be preserved"); -} - -#[test] -fn test_keyless_deploy_init_code_selfdestructs() { - // Test: Init code calls SELFDESTRUCT - // - // EIP-6780 (Cancun): SELFDESTRUCT destroys the account only if it was created in - // the same transaction. Since we're self-destructing during CREATE (same tx), - // the account will be destroyed at the end of the transaction. - // - // Key behavior: - // - SELFDESTRUCT results in empty bytecode after creation - // - Empty bytecode triggers EmptyCodeDeployed error (prevents replay attacks) - // - EmptyCodeDeployed returns success with zero address (not revert) - // - State changes persist: beneficiary receives ETH, signer is charged gas - let mut db = MemoryDatabase::default(); - - let beneficiary = address!("0000000000000000000000000000000000beeef1"); - let contract_value = U256::from(1_000_000_000_000_000_000u128); // 1 ETH - - // Init code that: - // 1. SELFDESTRUCTs to beneficiary (sends contract's ETH) - // 2. Execution continues (post-Cancun SELFDESTRUCT doesn't halt) - // 3. Returns minimal runtime code - // - // Note: Even though init code returns runtime code, SELFDESTRUCT in same-tx - // causes the account to be destroyed, so the code becomes empty. - let init_code = BytecodeBuilder::default() - .push_address(beneficiary) - .append(SELFDESTRUCT) - // Runtime code comes after SELFDESTRUCT + return sequence = 22 bytes (0x16) - .push_number(1_u8) // size = 1 - .push_number(0x1a_u8) // offset of runtime code - .push_number(0_u8) // dest offset - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append(STOP) // runtime code: STOP - .build(); - - // Create tx with value so the contract has ETH to send via SELFDESTRUCT - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, contract_value); - - // Fund signer with enough for gas + value - let initial_balance = U256::from(1_001_000_000_000_000_000_000u128); - db.set_account_balance(signer, initial_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify it returns success with EmptyCodeDeployed error (not revert) - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success with EmptyCodeDeployed error, got: {:?}", - result - ); - - // Decode return value - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // EmptyCodeDeployed returns zero address - assert_eq!(ret.deployedAddress, Address::ZERO, "EmptyCodeDeployed should return zero address"); - - // Error data should contain EmptyCodeDeployed - assert!(!ret.errorData.is_empty(), "Should have error data"); - let error = decode_error_result(&ret.errorData) - .unwrap_or_else(|| panic!("Failed to decode error from errorData")); - assert!( - matches!(error, KeylessDeployError::EmptyCodeDeployed { .. }), - "Expected EmptyCodeDeployed, got {:?}", - error - ); - - // EIP-6780: Beneficiary receives the contract's ETH via SELFDESTRUCT - // State changes persist even though deploy "failed" with EmptyCodeDeployed - let beneficiary_acc = state.get(&beneficiary).expect("beneficiary should be in state"); - assert_eq!( - beneficiary_acc.info.balance, contract_value, - "beneficiary should receive the contract's ETH via SELFDESTRUCT" - ); - - // Signer should be charged for gas (state changes persist) - let signer_account = state.get(&signer).expect("signer should exist in state"); - let gas_cost = U256::from(ret.gasUsed) * U256::from(100_000_000_000u64); - let expected_balance = initial_balance - gas_cost - contract_value; - assert_eq!( - signer_account.info.balance, expected_balance, - "signer should be charged gas + value" - ); -} - -#[test] -fn test_keyless_deploy_modifies_other_contract_state() { - // Test: Init code writes to another contract's storage via CALL - let mut db = MemoryDatabase::default(); - - // Deploy a "storage" contract that stores calldata[0:32] to slot 0 - // Bytecode: - // PUSH1 0x20 PUSH1 0x00 PUSH1 0x00 CALLDATACOPY ; copy 32 bytes from calldata to memory - // PUSH1 0x00 MLOAD ; load value from memory - // PUSH1 0x00 SSTORE ; store to slot 0 - // STOP - let storage_contract_code = BytecodeBuilder::default() - .push_number(0x20_u8) // size - .push_number(0_u8) // srcOffset - .push_number(0_u8) // destOffset - .append(CALLDATACOPY) - .push_number(0_u8) // offset - .append(MLOAD) - .push_number(0_u8) // slot - .append(SSTORE) - .stop() - .build(); - - let storage_contract = address!("0000000000000000000000000000000000500000"); - db.set_account_code(storage_contract, storage_contract_code); - - // Value to store - let test_value = U256::from(0x1234_5678_9abc_def0u64); - - // Init code that: - // 1. Stores test_value to memory at offset 0 - // 2. CALLs storage_contract with the value as calldata - // 3. Returns minimal runtime code - let init_code = BytecodeBuilder::default() - .mstore(0, test_value.to_be_bytes_vec()) - .push_number(0_u8) // retSize - .push_number(0_u8) // retOffset - .push_number(0x20_u8) // argsSize = 32 - .push_number(0_u8) // argsOffset - .push_number(0_u8) // value - .push_address(storage_contract) - .append(GAS) - .append(CALL) - .append(POP) - // Return minimal runtime code: just return a constant 0x42 - .push_number(1_u8) // size = 1 - .push_number(0x49_u8) // offset of runtime code (0x49 = 73) - .push_number(0_u8) // dest offset - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append(STOP) // runtime code: STOP - .build(); - - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, U256::ZERO); - - // Fund signer - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Decode return value - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify deployed contract code and code hash - let contract = state.get(&ret.deployedAddress).expect("contract should exist in state"); - let code = contract.info.code.as_ref().expect("contract should have code"); - assert!(!code.is_empty(), "contract should have non-empty code"); - - // Verify storage contract's slot 0 contains the test value - let storage_acc = state.get(&storage_contract).expect("storage contract should be in state"); - let stored_value = storage_acc.storage.get(&U256::ZERO).expect("slot 0 should exist"); - assert_eq!(stored_value.present_value, test_value, "storage should contain test value"); -} - -#[test] -fn test_keyless_deploy_creates_child_contract() { - // Test: Init code deploys a child contract via CREATE - let mut db = MemoryDatabase::default(); - - // Child contract runtime code: just STOP - let child_runtime_code: &[u8] = &[0x00]; // STOP - - // Child init code that returns the runtime code - let child_init_code = BytecodeBuilder::default() - .push_number(1_u8) // size = 1 (runtime code size) - .push_number(0x0c_u8) // offset of runtime code - .push_number(0_u8) // dest = 0 - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append_many(child_runtime_code.iter().copied()) - .build(); - - let child_init_len = child_init_code.len(); - - // Parent init code: - // 1. Store child init code to memory - // 2. CREATE child contract with value=0 - // 3. Store child address to storage slot 0 (so we can verify it) - // 4. Return parent runtime code - let mut parent_init = BytecodeBuilder::default(); - - // Store child init code to memory at offset 0 using mstore utility - parent_init = parent_init.mstore(0, &child_init_code); - - // CREATE: value=0, offset=0, size=child_init_len - parent_init = parent_init.push_number(child_init_len as u8); // size - parent_init = parent_init.push_number(0_u8); // offset - parent_init = parent_init.push_number(0_u8); // value - parent_init = parent_init.append(CREATE); - - // Stack now has child address, store to slot 0 - parent_init = parent_init.push_number(0_u8); // slot - parent_init = parent_init.append(SSTORE); - - // Now calculate offset for runtime code - let current_len = parent_init.len(); - // We'll add: PUSH1 0x01, PUSH1 , PUSH1 0x00, CODECOPY, PUSH1 0x01, PUSH1 0x00, RETURN - // That's 2 + 2 + 2 + 1 + 2 + 2 + 1 = 12 bytes, then 1 byte for runtime code - let runtime_offset = current_len + 12; - - parent_init = parent_init - .push_number(1_u8) // size = 1 - .push_number(runtime_offset as u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .append(STOP); // runtime code: STOP - - let init_code = parent_init.build(); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, U256::ZERO); - - // Fund signer - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Get parent address - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - let parent_address = ret.deployedAddress; - - // Both parent and child have runtime code 0x00 (STOP) - let runtime_code: &[u8] = &[0x00]; - let expected_code_hash = keccak256(runtime_code); - - // Verify parent contract code and code hash - let parent = state.get(&parent_address).expect("parent contract should exist"); - assert!( - parent.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "parent should have code" - ); - assert_eq!(parent.info.code_hash, expected_code_hash, "parent code hash should match"); - - // Get child address from parent's storage slot 0 - let child_address_slot = parent.storage.get(&U256::ZERO).expect("slot 0 should exist"); - let child_address = Address::from_word(child_address_slot.present_value.into()); - - // Verify child contract code and code hash - let child = state.get(&child_address).expect("child contract should exist in state"); - assert!( - child.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "child should have code" - ); - assert_eq!(child.info.code_hash, expected_code_hash, "child code hash should match"); -} - -#[test] -fn test_keyless_deploy_with_value_transfer() { - // Test: Keyless tx with non-zero value transfers to contract - let mut db = MemoryDatabase::default(); - - // Simple init code that just returns minimal runtime code - let init_code = BytecodeBuilder::default() - .push_number(1_u8) // size = 1 - .push_number(0x0c_u8) // offset of runtime code - .push_number(0_u8) // dest = 0 - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append(STOP) // runtime code: STOP - .build(); - - // Create tx with 0.5 ETH value - let transfer_value = U256::from(500_000_000_000_000_000u128); // 0.5 ETH - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, transfer_value); - - // Fund signer with enough for gas + value - // gas_price * gas_limit_override + value = 100 gwei * 10B + 0.5 ETH = 1000 ETH + 0.5 ETH - let signer_balance = U256::from(1_000_500_000_000_000_000_000u128); - db.set_account_balance(signer, signer_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Get deployed address - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify deployed contract has code, code hash, and balance - let runtime_code: &[u8] = &[0x00]; // STOP - let expected_code_hash = keccak256(runtime_code); - let contract = state.get(&ret.deployedAddress).expect("contract should exist"); - assert!( - contract.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false), - "contract should have non-empty code" - ); - assert_eq!(contract.info.code_hash, expected_code_hash, "contract code hash should match"); - assert_eq!(contract.info.balance, transfer_value, "contract should have transferred value"); -} - -#[test] -fn test_keyless_deploy_emits_logs() { - // Test that logs emitted during sandbox execution are propagated to the parent context - let mut db = MemoryDatabase::default(); - - // Init code that: - // 1. Stores some data to memory - // 2. Emits LOG0 with that data - // 3. Returns minimal runtime code - let log_data = 0xdeadbeef_u32; - - let init_code = BytecodeBuilder::default() - // Store log data to memory (left-padded in 32 bytes via push_bytes + MSTORE) - .push_bytes(log_data.to_be_bytes()) - .push_number(0_u8) - .append(MSTORE) - // LOG0(offset=28, size=4) - read the last 4 bytes of the 32-byte word - .push_number(4_u8) // size = 4 - .push_number(0x1c_u8) // offset = 28 (32 - 4) - .append(LOG0) - // Return minimal runtime code - .push_number(1_u8) // size = 1 - .push_number(0x14_u8) // offset of runtime code - .push_number(0_u8) // dest = 0 - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append(STOP) // runtime code: STOP - .build(); - - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, U256::ZERO); - - // Fund signer - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify deployment succeeds - let ResultAndState { result, state: _ } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Verify logs are propagated from sandbox - let logs = result.logs(); - assert_eq!(logs.len(), 1, "Expected exactly one log from sandbox"); - - // Verify log data matches what init code emitted - let log = &logs[0]; - assert_eq!(log.data.data.as_ref(), &log_data.to_be_bytes(), "Log data should match"); - assert!(log.data.topics().is_empty(), "LOG0 should have no topics"); -} - -#[test] -fn test_keyless_deploy_reads_existing_contract() { - // Test: Init code reads from a pre-deployed contract via STATICCALL - let mut db = MemoryDatabase::default(); - - // Deploy a "getter" contract that returns a constant value when called - // The value is left-padded to 32 bytes (standard EVM word format) - let return_value = 0x12345678_u32; - let getter_code = BytecodeBuilder::default() - .push_bytes(return_value.to_be_bytes()) - .push_number(0_u8) - .append(MSTORE) - .push_number(0x20_u8) // return 32 bytes - .push_number(0_u8) - .append(RETURN) - .build(); - - let getter_contract = address!("0000000000000000000000000000000000600000"); - db.set_account_code(getter_contract, getter_code); - - // Init code that: - // 1. STATICCALLs getter contract - // 2. Stores the return value to slot 0 - // 3. Returns minimal runtime code - let init_code = BytecodeBuilder::default() - // STATICCALL: gas, addr, argsOffset, argsSize, retOffset, retSize - .push_number(0x20_u8) // retSize = 32 - .push_number(0_u8) // retOffset = 0 - .push_number(0_u8) // argsSize = 0 - .push_number(0_u8) // argsOffset = 0 - .push_address(getter_contract) - .append(GAS) - .append(STATICCALL) - .append(POP) // POP success flag - // Load return value from memory and store to slot 0 - .push_number(0_u8) - .append(MLOAD) - .push_number(0_u8) // slot - .append(SSTORE) - // Return minimal runtime code - .push_number(1_u8) // size = 1 - .push_number(0x2a_u8) // offset of runtime code - .push_number(0_u8) // dest = 0 - .append(CODECOPY) - .push_number(1_u8) // return size - .push_number(0_u8) // return offset - .append(RETURN) - .append(STOP) // runtime code: STOP - .build(); - - let (tx_bytes, signer) = create_pre_eip155_deploy_tx_with_value(init_code, U256::ZERO); - - // Fund signer - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "Expected success, got: {:?}", - result - ); - - // Get deployed address - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify deployed contract's code and code hash - let contract = state.get(&ret.deployedAddress).expect("contract should exist"); - let code = contract.info.code.as_ref().expect("contract should have code"); - assert!(!code.is_empty(), "contract should have non-empty code"); - - // Verify deployed contract's storage slot 0 has the value from getter - let stored = contract.storage.get(&U256::ZERO).expect("slot 0 should exist"); - // The getter returns a 32-byte value with our u32 right-justified (standard EVM behavior) - let expected = U256::from(return_value); - assert_eq!(stored.present_value, expected, "storage should have value from getter"); -} - -#[test] -fn test_keyless_deploy_twice_fails_second_time() { - // Test: Deploy same tx twice - second fails with ContractAlreadyExists - let mut db = MemoryDatabase::default(); - - // Fund deployer with enough ETH for multiple deployments - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(2_000_000_000_000_000_000_000u128)); - - // First deployment should succeed - let result1 = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - let ResultAndState { result, state } = result1; - assert!( - matches!(result, ExecutionResult::Success { .. }), - "First deployment should succeed, got: {:?}", - result - ); - - // Verify the first deployment produced correct code and code hash - let contract = state.get(&CREATE2_FACTORY_CONTRACT).expect("contract should exist"); - let code = contract.info.code.as_ref().expect("contract should have code"); - assert!(!code.is_empty(), "contract should have non-empty code"); - assert_eq!( - contract.info.code_hash, CREATE2_FACTORY_CODE_HASH, - "contract code hash should match" - ); - - // Apply only the contract code from first deployment to the database. - // We specifically apply the code at CREATE2_FACTORY_CONTRACT to simulate - // the contract existing, without modifying nonce which would cause NonceTooLow. - db.set_account_code(CREATE2_FACTORY_CONTRACT, code.original_bytes()); - - // Second deployment should fail with ContractAlreadyExists - let result2 = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - assert_revert_with_error(&result2, KeylessDeployError::ContractAlreadyExists); -} - -// ============================================================================= -// Beneficiary Fee Collection Tests -// ============================================================================= - -/// Default beneficiary address (block.coinbase) - receives transaction fees -const DEFAULT_BENEFICIARY: Address = Address::ZERO; - -#[test] -fn test_beneficiary_receives_fees_on_success() { - let mut db = MemoryDatabase::default(); - - // Fund signer with enough ETH for gas - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, U256::from(1_000_000_000_000_000_000_000u128)); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify success - let ResultAndState { result, state } = result; - assert!(matches!(result, ExecutionResult::Success { .. })); - - // Decode return value to get gasUsed - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - - // Verify beneficiary (Address::ZERO) received fees: gas_used × gas_price (100 gwei) - let expected_fee = U256::from(ret.gasUsed) * U256::from(100_000_000_000u64); - let beneficiary_account = - state.get(&DEFAULT_BENEFICIARY).expect("beneficiary should exist in state"); - assert_eq!( - beneficiary_account.info.balance, expected_fee, - "beneficiary should receive tx fees from keyless deploy sandbox" - ); -} - -#[test] -fn test_beneficiary_receives_fees_on_execution_failure() { - let mut db = MemoryDatabase::default(); - - // Create tx with reverting init code: PUSH1 0x00 PUSH1 0x00 REVERT - let init_code = Bytes::from_static(&hex!("60006000fd")); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - // Fund signer - let initial_balance = U256::from(1_000_000_000_000_000_000_000u128); - db.set_account_balance(signer, initial_balance); - - let result = call_keyless_deploy( - MegaSpecId::REX2, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - U256::ZERO, - ); - - // Verify it returns success with error data (ExecutionReverted is wrapped as success) - let ResultAndState { result, state } = result; - assert!(matches!(result, ExecutionResult::Success { .. })); - - // Decode return value to get gasUsed - let output = result.output().unwrap(); - let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output).unwrap(); - assert!(!ret.errorData.is_empty(), "Should have ExecutionReverted error"); - - // Even though execution reverted, beneficiary should receive fees - let expected_fee = U256::from(ret.gasUsed) * U256::from(100_000_000_000u64); - let beneficiary_account = - state.get(&DEFAULT_BENEFICIARY).expect("beneficiary should exist in state"); - assert_eq!( - beneficiary_account.info.balance, expected_fee, - "beneficiary should receive fees even when sandbox execution fails" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex2/main.rs b/crates/mega-evm/tests/_pending/rex2/main.rs deleted file mode 100644 index af70245a9..000000000 --- a/crates/mega-evm/tests/_pending/rex2/main.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Tests for Rex2 hardfork features. - -mod keyless_deploy; -mod oracle_hint; diff --git a/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs b/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs deleted file mode 100644 index 908d73b3d..000000000 --- a/crates/mega-evm/tests/_pending/rex2/oracle_hint.rs +++ /dev/null @@ -1,347 +0,0 @@ -//! Tests for the oracle hint mechanism introduced in Rex2. -//! -//! The hint mechanism allows on-chain contracts to send signals to the off-chain oracle -//! service backend via the `sendHint(bytes32 topic, bytes data)` function on the oracle -//! contract. The EVM intercepts these calls and forwards them to the oracle service via -//! `OracleEnv::on_hint`. - -use alloy_primitives::{address, bytes, Bytes, TxKind, B256, U256}; -use alloy_sol_types::{sol, SolCall}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, ORACLE_CONTRACT_ADDRESS, - ORACLE_CONTRACT_CODE_REX2, -}; -use revm::{ - bytecode::opcode::{CALL, GAS, MSTORE, PUSH0}, - context::TxEnv, - inspector::NoOpInspector, -}; - -sol! { - function sendHint(bytes32 topic, bytes calldata data) external; -} - -const CALLER: alloy_primitives::Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); - -/// Helper function to execute a transaction and return the result along with recorded hints. -fn execute_transaction( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - target: alloy_primitives::Address, -) -> revm::context::result::ExecutionResult { - execute_transaction_with_data(spec, db, external_envs, target, Bytes::new()) -} - -/// Helper function to execute a transaction with calldata. -fn execute_transaction_with_data( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - target: alloy_primitives::Address, - data: Bytes, -) -> revm::context::result::ExecutionResult { - execute_transaction_with_data_and_value(spec, db, external_envs, target, data, U256::ZERO) -} - -/// Helper function to execute a transaction with calldata and value. -fn execute_transaction_with_data_and_value( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - target: alloy_primitives::Address, - data: Bytes, - value: U256, -) -> revm::context::result::ExecutionResult { - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(target), - data, - value, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - result_envelope.result -} - -/// Encodes calldata for `sendHint(bytes32 topic, bytes calldata data)`. -fn encode_send_hint_calldata(topic: B256, data: &[u8]) -> Vec { - sendHintCall { topic, data: Bytes::copy_from_slice(data) }.abi_encode() -} - -/// Creates bytecode for a contract that calls `sendHint` on the oracle contract. -fn create_call_send_hint_bytecode(topic: B256, data: &[u8]) -> Bytes { - let calldata = encode_send_hint_calldata(topic, data); - let mut builder = BytecodeBuilder::default(); - - // Store calldata in memory at offset 0 - for (i, chunk) in calldata.chunks(32).enumerate() { - let mut padded = [0u8; 32]; - padded[..chunk.len()].copy_from_slice(chunk); - builder = builder.push_bytes(padded).push_number((i * 32) as u8).append(MSTORE); - } - - // CALL(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - builder - .append(PUSH0) // retSize: 0 - .append(PUSH0) // retOffset: 0 - .push_number(calldata.len() as u16) // argsSize - .append(PUSH0) // argsOffset: 0 - .append(PUSH0) // value: 0 - .push_address(ORACLE_CONTRACT_ADDRESS) // addr: oracle contract - .append(GAS) // gas: all available - .append(CALL) - .stop() - .build() -} - -/// Creates bytecode for a contract that calls `sendHint` twice on the oracle contract. -fn create_call_send_hint_twice_bytecode( - topic1: B256, - data1: &[u8], - topic2: B256, - data2: &[u8], -) -> Bytes { - let calldata1 = encode_send_hint_calldata(topic1, data1); - let calldata2 = encode_send_hint_calldata(topic2, data2); - let mut builder = BytecodeBuilder::default(); - - // First call: Store calldata1 in memory at offset 0 - for (i, chunk) in calldata1.chunks(32).enumerate() { - let mut padded = [0u8; 32]; - padded[..chunk.len()].copy_from_slice(chunk); - builder = builder.push_bytes(padded).push_number((i * 32) as u8).append(MSTORE); - } - - // First CALL - builder = builder - .append(PUSH0) // retSize: 0 - .append(PUSH0) // retOffset: 0 - .push_number(calldata1.len() as u16) // argsSize - .append(PUSH0) // argsOffset: 0 - .append(PUSH0) // value: 0 - .push_address(ORACLE_CONTRACT_ADDRESS) // addr: oracle contract - .append(GAS) // gas: all available - .append(CALL); - - // Second call: Store calldata2 in memory at offset 0 (overwrite) - for (i, chunk) in calldata2.chunks(32).enumerate() { - let mut padded = [0u8; 32]; - padded[..chunk.len()].copy_from_slice(chunk); - builder = builder.push_bytes(padded).push_number((i * 32) as u8).append(MSTORE); - } - - // Second CALL - builder - .append(PUSH0) // retSize: 0 - .append(PUSH0) // retOffset: 0 - .push_number(calldata2.len() as u16) // argsSize - .append(PUSH0) // argsOffset: 0 - .append(PUSH0) // value: 0 - .push_address(ORACLE_CONTRACT_ADDRESS) // addr: oracle contract - .append(GAS) // gas: all available - .append(CALL) - .stop() - .build() -} - -/// Test that `on_hint` is called when Rex2 is enabled and oracle contract emits a Hint event. -#[test] -fn test_on_hint_called_on_rex2() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - // Main contract that calls sendHint on the oracle contract - let main_code = create_call_send_hint_bytecode(user_topic, &hint_data); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - // Deploy the actual v1.1.0 oracle contract - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let result = execute_transaction(MegaSpecId::REX2, &mut db, &external_envs, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that on_hint was called with the correct from, topic and data - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 1, "Should have recorded exactly one hint"); - assert_eq!(hints[0].from, CALLEE, "Hint from should be the caller contract"); - assert_eq!(hints[0].topic, user_topic, "Hint topic should match"); - assert_eq!(hints[0].data, hint_data, "Hint data should match"); -} - -/// Test that `on_hint` is NOT called for calls to non-oracle contracts. -/// Even if a contract has a sendHint function, it must be the oracle contract -/// for the hint to be intercepted. -#[test] -fn test_on_hint_not_called_for_non_oracle_contract() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - let fake_oracle = address!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"); - - // Deploy the oracle contract bytecode at a non-oracle address - // This fake oracle has the same sendHint function, but is not at ORACLE_CONTRACT_ADDRESS - let mut db = MemoryDatabase::default(); - db.set_account_code(fake_oracle, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - // Call sendHint on the fake oracle contract directly - let calldata = encode_send_hint_calldata(user_topic, &hint_data); - let result = execute_transaction_with_data( - MegaSpecId::REX2, - &mut db, - &external_envs, - fake_oracle, - Bytes::from(calldata), - ); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that on_hint was NOT called (call was not to the oracle contract address) - let hints = external_envs.recorded_hints(); - assert!(hints.is_empty(), "Should NOT have recorded hints from non-oracle contract address"); -} - -/// Test that multiple hints can be recorded from a single transaction. -#[test] -fn test_multiple_hints_recorded() { - let topic1 = B256::from_slice(&[0x11u8; 32]); - let topic2 = B256::from_slice(&[0x22u8; 32]); - let data1 = bytes!("aabb"); - let data2 = bytes!("ccdd"); - - // Main contract that calls sendHint twice on the oracle contract - let main_code = create_call_send_hint_twice_bytecode(topic1, &data1, topic2, &data2); - - let mut db = MemoryDatabase::default(); - db.set_account_code(CALLEE, main_code); - // Deploy the actual v1.1.0 oracle contract - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let result = execute_transaction(MegaSpecId::REX2, &mut db, &external_envs, CALLEE); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that both hints were recorded with correct from addresses - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 2, "Should have recorded two hints"); - assert_eq!(hints[0].from, CALLEE, "First hint from should be the caller contract"); - assert_eq!(hints[0].topic, topic1, "First hint topic should match"); - assert_eq!(hints[0].data, data1, "First hint data should match"); - assert_eq!(hints[1].from, CALLEE, "Second hint from should be the caller contract"); - assert_eq!(hints[1].topic, topic2, "Second hint topic should match"); - assert_eq!(hints[1].data, data2, "Second hint data should match"); -} - -/// Test that `on_hint` is called when transaction directly targets the oracle contract. -#[test] -fn test_on_hint_direct_oracle_call() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - let mut db = MemoryDatabase::default(); - // Deploy the actual v1.1.0 oracle contract - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - // Call sendHint on the oracle contract directly - let calldata = encode_send_hint_calldata(user_topic, &hint_data); - let result = execute_transaction_with_data( - MegaSpecId::REX2, - &mut db, - &external_envs, - ORACLE_CONTRACT_ADDRESS, - Bytes::from(calldata), - ); - - assert!(result.is_success(), "Transaction should succeed"); - - // Verify that on_hint was called with CALLER as the from address (direct call) - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 1, "Should have recorded exactly one hint"); - assert_eq!(hints[0].from, CALLER, "Hint from should be the transaction caller"); - assert_eq!(hints[0].topic, user_topic, "Hint topic should match"); - assert_eq!(hints[0].data, hint_data, "Hint data should match"); -} - -/// In Rex2, value-bearing `sendHint` still triggers `on_hint`. -/// The transaction later reverts because the Solidity function is non-payable. -#[test] -fn test_on_hint_with_non_zero_value_on_rex2_still_calls_hint() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let calldata = encode_send_hint_calldata(user_topic, &hint_data); - let result = execute_transaction_with_data_and_value( - MegaSpecId::REX2, - &mut db, - &external_envs, - ORACLE_CONTRACT_ADDRESS, - Bytes::from(calldata), - U256::from(1_u64), - ); - - assert!(!result.is_success(), "sendHint with non-zero value should revert, got: {:?}", result); - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 1, "Rex2 should still call on_hint for value-bearing sendHint"); - assert_eq!(hints[0].from, CALLER, "Hint from should be the transaction caller"); - assert_eq!(hints[0].topic, user_topic, "Hint topic should match"); - assert_eq!(hints[0].data, hint_data, "Hint data should match"); -} - -/// In Rex4, value-bearing `sendHint` keeps historical behavior and still triggers `on_hint`. -#[test] -fn test_on_hint_with_non_zero_value_on_rex4_still_calls_hint() { - let user_topic = B256::from_slice(&[0x42u8; 32]); - let hint_data = bytes!("deadbeef"); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(1_000_000)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - - let calldata = encode_send_hint_calldata(user_topic, &hint_data); - let result = execute_transaction_with_data_and_value( - MegaSpecId::REX4, - &mut db, - &external_envs, - ORACLE_CONTRACT_ADDRESS, - Bytes::from(calldata), - U256::from(1_u64), - ); - - assert!(!result.is_success(), "sendHint with non-zero value should revert, got: {:?}", result); - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 1, "Rex4 should still call on_hint for value-bearing sendHint"); - assert_eq!(hints[0].from, CALLER, "Hint from should be the transaction caller"); - assert_eq!(hints[0].topic, user_topic, "Hint topic should match"); - assert_eq!(hints[0].data, hint_data, "Hint data should match"); -} diff --git a/crates/mega-evm/tests/_pending/rex3/main.rs b/crates/mega-evm/tests/_pending/rex3/main.rs deleted file mode 100644 index e197703b0..000000000 --- a/crates/mega-evm/tests/_pending/rex3/main.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Tests for Rex3 hardfork features. - -mod oracle_gas_limit; -mod system_address; diff --git a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs b/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs deleted file mode 100644 index 327f491c8..000000000 --- a/crates/mega-evm/tests/_pending/rex3/oracle_gas_limit.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! Tests for the Rex3 oracle access compute gas limit (1M -> 20M) and -//! the Rex3 change to trigger oracle gas detention on SLOAD instead of CALL. - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, TestExternalEnvs, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::{CALL, GAS, POP, PUSH0, SLOAD, SSTORE, STOP, TIMESTAMP}, - context::{result::ExecutionResult, TxEnv}, - handler::EvmTr, - inspector::NoOpInspector, -}; - -const CALLER: alloy_primitives::Address = address!("2000000000000000000000000000000000000002"); -const CALLEE: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); -const CONTRACT_B: alloy_primitives::Address = address!("3000000000000000000000000000000000000003"); -const REGULAR_CONTRACT: alloy_primitives::Address = - address!("4000000000000000000000000000000000000004"); - -/// Helper function to execute a transaction with the given spec and database. -fn execute_transaction( - spec: MegaSpecId, - db: &mut MemoryDatabase, - target: alloy_primitives::Address, -) -> (ExecutionResult, u64) { - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(target), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - let compute_gas_limit = evm.ctx_ref().additional_limit.borrow().compute_gas_limit(); - - (result, compute_gas_limit) -} - -/// Checks if the result is a volatile data access out of gas error. -fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool { - matches!( - result, - &ExecutionResult::Halt { reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, .. } - ) -} - -/// Build bytecode that CALLs the oracle contract and then STOPs. -fn build_call_oracle_bytecode() -> Bytes { - BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build() -} - -/// Build bytecode for oracle contract that performs SLOAD(0) and returns. -/// Deployed at `ORACLE_CONTRACT_ADDRESS` so that SLOAD reads oracle storage. -fn build_oracle_sload_code() -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // key = 0 - .append(SLOAD) // SLOAD from oracle storage (triggers Rex3 oracle access) - .append(POP) - .append(STOP) - .build() -} - -// ============================================================================= -// Rex3: Oracle access via SLOAD tests -// ============================================================================= - -/// Test that the compute gas limit is set to 20M after oracle SLOAD under REX3. -#[test] -fn test_rex3_oracle_sload_sets_20m_compute_gas_limit() { - // Deploy oracle contract code that does SLOAD - let oracle_code = build_oracle_sload_code(); - let callee_bytecode = build_call_oracle_bytecode(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - "REX3 compute gas limit should be 20M after oracle SLOAD" - ); -} - -/// Test that REX3 CALL to oracle contract WITHOUT reading storage does NOT trigger gas detention. -#[test] -fn test_rex3_call_oracle_without_sload_no_detention() { - // Oracle contract has code that just STOPs (no SLOAD) - let oracle_code = BytecodeBuilder::default().append(STOP).build(); - - let callee_bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - // Compute gas limit should remain at the default (200M), NOT the oracle detention limit. - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex::TX_COMPUTE_GAS_LIMIT, - "REX3: CALL to oracle without SLOAD should NOT trigger gas detention" - ); -} - -/// Test that REX3 still enforces the 20M limit (not unlimited). -/// A transaction consuming >20M compute gas after oracle SLOAD should still fail. -#[test] -fn test_rex3_oracle_access_still_enforces_20m_limit() { - // Oracle contract code for Rex3 - performs SLOAD to trigger detention - let oracle_code = build_oracle_sload_code(); - - // Build bytecode: call oracle (with SLOAD), then do ~1000 SSTOREs (~22M compute gas) - let mut builder = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP); - - // 1000 SSTOREs to unique slots: ~1000 * 22,100 = ~22M compute gas - for i in 1..=1000u32 { - builder = builder.push_number(i).push_number(i).append(SSTORE); - } - let bytecode = builder.append(STOP).build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, bytecode); - let (result, _) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!( - !result.is_success(), - "REX3 transaction should fail: ~22M compute gas exceeds the 20M oracle access limit" - ); - assert!(is_volatile_data_access_oog(&result), "Should fail with VolatileDataAccessOutOfGas"); -} - -/// Test that SLOAD from oracle contract triggers gas detention in Rex3 -/// (direct SLOAD test without CALL wrapper). -#[test] -fn test_rex3_direct_oracle_sload_triggers_detention() { - // The callee IS the oracle contract itself. - // Code: SLOAD(0) + POP + STOP - let oracle_code = build_oracle_sload_code(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let (result, compute_gas_limit) = - execute_transaction(MegaSpecId::REX3, &mut db, ORACLE_CONTRACT_ADDRESS); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - "REX3: SLOAD from oracle contract should trigger 20M gas detention" - ); -} - -// ============================================================================= -// Rex3: Additional oracle SLOAD detention tests -// ============================================================================= - -/// Test that SLOAD from a regular (non-oracle) contract does NOT trigger gas detention. -/// Only SLOAD from oracle contract storage should trigger detention. -#[test] -fn test_rex3_sload_from_non_oracle_contract_no_detention() { - // Regular contract does SLOAD(0) - this should NOT trigger oracle detention - let regular_code = BytecodeBuilder::default() - .append(PUSH0) // key = 0 - .append(SLOAD) // SLOAD from regular contract's own storage - .append(POP) - .append(STOP) - .build(); - - // Callee calls the regular contract - let callee_bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(REGULAR_CONTRACT) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(REGULAR_CONTRACT, regular_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - // Compute gas limit should remain at the default (200M) - no detention triggered - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex::TX_COMPUTE_GAS_LIMIT, - "SLOAD from non-oracle contract should NOT trigger gas detention" - ); -} - -/// Test that nested calls through an intermediate contract still trigger detention when -/// the oracle's SLOAD is reached. -/// Call chain: CALLEE -> `CONTRACT_B` -> ORACLE (SLOAD) -> detention at 20M -#[test] -fn test_rex3_nested_call_oracle_sload_triggers_detention() { - // Oracle contract code: SLOAD(0) + POP + STOP - let oracle_code = build_oracle_sload_code(); - - // Contract B: calls oracle contract - let contract_b_code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - // Callee: calls Contract B - let callee_bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(CONTRACT_B) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CONTRACT_B, contract_b_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - "Nested call through intermediate contract should still trigger 20M oracle detention" - ); -} - -/// Test that accessing both block env (TIMESTAMP) and oracle SLOAD results in the combined -/// (minimum) compute gas limit. In Rex3, both limits are 20M, so the combined limit is 20M. -#[test] -fn test_rex3_block_env_and_oracle_sload_combined_limit() { - // Oracle contract code: SLOAD(0) + POP + STOP - let oracle_code = build_oracle_sload_code(); - - // Callee: TIMESTAMP (block env access) + CALL oracle (SLOAD access) - let callee_bytecode = BytecodeBuilder::default() - .append(TIMESTAMP) // Block env access -> 20M limit - .append(POP) - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) // Oracle SLOAD access -> 20M limit - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - // Both block env (20M) and oracle (20M) limits are equal, so combined = min(20M, 20M) = 20M - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - "Combined block env + oracle access should result in 20M limit in Rex3" - ); -} - -/// Test that calling oracle with sendHint (intercepted in `frame_init`) does NOT trigger -/// SLOAD-based detention in Rex3, since sendHint is intercepted before the oracle code -/// executes any SLOAD. -#[test] -fn test_rex3_send_hint_call_no_detention() { - // Oracle contract code that has sendHint ABI entry but no SLOAD. - // In practice, sendHint calls are intercepted in frame_init before the oracle code runs, - // so the oracle bytecode doesn't matter. We deploy an oracle with just STOP to confirm. - let oracle_code = BytecodeBuilder::default().append(STOP).build(); - - // Build sendHint(bytes32,bytes) calldata - use alloy_sol_types::SolCall; - let hint_call = - mega_evm::IOracle::sendHintCall { topic: alloy_primitives::B256::ZERO, data: Bytes::new() }; - let hint_calldata: Vec = hint_call.abi_encode(); - - // Callee: store sendHint calldata in memory, then CALL oracle with it - let callee_bytecode = BytecodeBuilder::default() - .mstore(0, &hint_calldata) - .push_number(0u8) // retSize - .push_number(0u8) // retOffset - .push_number(hint_calldata.len() as u64) // argsLength - .push_number(0u8) // argsOffset - .push_number(0u8) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) // gas - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, callee_bytecode); - - let (result, compute_gas_limit) = execute_transaction(MegaSpecId::REX3, &mut db, CALLEE); - - assert!(result.is_success(), "Transaction should succeed, got: {:?}", result); - // sendHint is intercepted before oracle code runs, so no SLOAD -> no detention - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex::TX_COMPUTE_GAS_LIMIT, - "sendHint call should NOT trigger SLOAD-based gas detention in Rex3" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex3/system_address.rs b/crates/mega-evm/tests/_pending/rex3/system_address.rs deleted file mode 100644 index 1f6be33f0..000000000 --- a/crates/mega-evm/tests/_pending/rex3/system_address.rs +++ /dev/null @@ -1,164 +0,0 @@ -//! Tests for `MEGA_SYSTEM_ADDRESS` exemption from Rex3 SLOAD-based oracle gas detention. - -use alloy_primitives::{address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::{CALL, GAS, POP, PUSH0, SLOAD, STOP}, - context::TxEnv, - handler::EvmTr, - inspector::NoOpInspector, -}; - -const CALLEE: alloy_primitives::Address = address!("1000000000000000000000000000000000000001"); - -/// Build bytecode for oracle contract that performs SLOAD(0) and returns. -fn build_oracle_sload_code() -> Bytes { - BytecodeBuilder::default() - .append(PUSH0) // key = 0 - .append(SLOAD) // SLOAD from oracle storage - .append(POP) - .append(STOP) - .build() -} - -/// Test that transactions from `MEGA_SYSTEM_ADDRESS` are exempted from Rex3 SLOAD-based -/// oracle gas detention. -/// -/// In Rex3, oracle gas detention triggers on SLOAD from oracle storage. However, -/// system address transactions should be exempted. This test verifies that the -/// volatile data tracker does not record oracle access for `MEGA_SYSTEM_ADDRESS` transactions. -/// -/// The `MEGA_SYSTEM_ADDRESS` must call the oracle contract directly (it's in the whitelist). -#[test] -fn test_mega_system_address_exempted_from_rex3_sload_detention() { - // Deploy oracle contract code that does SLOAD (this would normally trigger detention) - let oracle_code = build_oracle_sload_code(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX3).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - // MEGA_SYSTEM_ADDRESS calls oracle directly (oracle is in the whitelist) - let tx = TxEnv { - caller: MEGA_SYSTEM_ADDRESS, - kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - - // Verify transaction succeeded - assert!(result.is_success(), "Transaction from mega system address should succeed"); - - // Key assertion: Oracle access should NOT be tracked for mega system address - let oracle_accessed = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.has_accessed_oracle()) - .unwrap_or(false); - assert!( - !oracle_accessed, - "Oracle access should NOT be tracked for transactions from MEGA_SYSTEM_ADDRESS in Rex3" - ); - - // Verify compute gas limit was NOT set (no gas detention) - let compute_gas_limit = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.get_compute_gas_limit()) - .unwrap_or(None); - assert!( - compute_gas_limit.is_none(), - "Compute gas limit should NOT be set for mega system address transactions" - ); -} - -/// Test that a non-system address transaction IS subject to Rex3 SLOAD-based oracle -/// gas detention (contrast with the system address exemption). -#[test] -fn test_non_system_address_subject_to_rex3_sload_detention() { - let oracle_code = build_oracle_sload_code(); - - // Callee calls oracle which does SLOAD - let callee_bytecode = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_number(0u8) // value: 0 wei - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default(); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - db.set_account_code(CALLEE, callee_bytecode); - - let external_envs = TestExternalEnvs::::new(); - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX3).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let regular_caller = address!("2000000000000000000000000000000000000002"); - let tx = TxEnv { - caller: regular_caller, - kind: TxKind::Call(CALLEE), - data: Default::default(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - - assert!(result.is_success(), "Transaction should succeed"); - - // Oracle access SHOULD be tracked for non-system address - let oracle_accessed = evm - .ctx - .volatile_data_tracker - .try_borrow() - .map(|tracker| tracker.has_accessed_oracle()) - .unwrap_or(false); - assert!( - oracle_accessed, - "Oracle access SHOULD be tracked for regular address transactions in Rex3" - ); - - // Compute gas limit should be set to 20M - let compute_gas_limit = evm.ctx_ref().additional_limit.borrow().compute_gas_limit(); - assert_eq!( - compute_gas_limit, - mega_evm::constants::rex3::ORACLE_ACCESS_COMPUTE_GAS, - "Compute gas limit should be 20M for regular transactions accessing oracle in Rex3" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/access_control.rs b/crates/mega-evm/tests/_pending/rex4/access_control.rs deleted file mode 100644 index 976f8ab06..000000000 --- a/crates/mega-evm/tests/_pending/rex4/access_control.rs +++ /dev/null @@ -1,1996 +0,0 @@ -//! Tests for the `MegaAccessControl` system contract. -//! -//! When a contract calls `ACCESS_CONTROL_ADDRESS.disableVolatileDataAccess()`, the caller's -//! frame and all inner calls that access volatile data will revert with -//! `VolatileDataAccessDisabled()` error. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, TestExternalEnvs, VolatileDataAccessType, ACCESS_CONTROL_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - ContextTr, TxEnv, - }, - interpreter::{CallInputs, CallOutcome, InterpreterTypes}, - Inspector, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -const PARENT: Address = address!("0000000000000000000000000000000000200001"); -const CHILD: Address = address!("0000000000000000000000000000000000200002"); -const GRANDCHILD: Address = address!("0000000000000000000000000000000000200003"); -const SIBLING: Address = address!("0000000000000000000000000000000000200004"); - -/// The 4-byte selector for `disableVolatileDataAccess()`. -const DISABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -/// The 4-byte selector for `enableVolatileDataAccess()`. -const ENABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; - -/// The 4-byte selector for `isVolatileDataAccessDisabled()`. -const IS_VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; - -/// The 4-byte selector for `VolatileDataAccessDisabled()` error. -const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; - -/// The 4-byte selector for `DisabledByParent()` error. -const DISABLED_BY_PARENT_SELECTOR: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; - -/// The 4-byte selector for `NotIntercepted()` error. -const NOT_INTERCEPTED_SELECTOR: [u8; 4] = IMegaAccessControl::NotIntercepted::SELECTOR; -/// The 4-byte selector for `NonZeroTransfer()` error. -const NON_ZERO_TRANSFER_SELECTOR: [u8; 4] = IMegaAccessControl::NonZeroTransfer::SELECTOR; - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Decodes `VolatileDataAccessDisabled(uint8 accessType)` from revert data. -fn decode_volatile_data_access_disabled( - data: &[u8], -) -> IMegaAccessControl::VolatileDataAccessDisabled { - ::abi_decode(data) - .expect("valid VolatileDataAccessDisabled revert data") -} - -/// Executes a transaction on Rex4 spec. -fn transact( - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Builds a default transaction calling a contract. -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Builds bytecode that calls `disableVolatileDataAccess()` on the access control contract. -fn call_disable_volatile_data_access(builder: BytecodeBuilder) -> BytecodeBuilder { - // Store selector in memory - let builder = builder.mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR); - // CALL(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize (4-byte selector) - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) // discard success flag -} - -/// Builds bytecode that calls `enableVolatileDataAccess()` on the access control contract. -fn call_enable_volatile_data_access(builder: BytecodeBuilder) -> BytecodeBuilder { - let builder = builder.mstore(0x0, ENABLE_VOLATILE_DATA_ACCESS_SELECTOR); - builder - .push_number(0_u64) - .push_number(0_u64) - .push_number(4_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) - .append(CALL) - .append(POP) -} - -/// Builds bytecode that calls `isVolatileDataAccessDisabled()` and returns the bool result. -/// The CALL return data (32-byte ABI-encoded bool) is returned as the frame output. -fn call_is_volatile_data_access_disabled(builder: BytecodeBuilder) -> BytecodeBuilder { - let builder = builder.mstore(0x0, IS_VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - builder - .push_number(32_u64) // retSize (32-byte bool) - .push_number(0x20_u64) // retOffset (put return data at 0x20 to not overwrite calldata) - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) - .append(CALL) - .append(POP) // discard success flag - // Return the 32-byte bool output - .push_number(32_u64) // size - .push_number(0x20_u64) // offset - .append(RETURN) -} - -/// Builds bytecode that CALLs a target address with the given gas. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Builds bytecode that STATICCALLs a target address with the given gas. -fn append_staticcall(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(target) - .push_number(gas) - .append(STATICCALL) -} - -/// Builds bytecode that STATICCALLs the access control contract with the given selector. -fn append_access_control_staticcall( - builder: BytecodeBuilder, - selector: [u8; 4], - gas: u64, -) -> BytecodeBuilder { - let builder = builder.mstore(0x0, selector); - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(gas) - .append(STATICCALL) -} - -/// Builds bytecode that DELEGATECALLs a target address with the given gas. -fn append_delegatecall(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(target) - .push_number(gas) - .append(DELEGATECALL) -} - -/// Appends bytecode that emits a LOG0 with the top-of-stack value (expected: CALL success flag). -/// Consumes the top stack value. -fn append_log_call_status(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .push_number(0_u64) // memory offset - .append(MSTORE) // MSTORE(0, success_flag) - .push_number(32_u64) // size (32 bytes, the full word) - .push_number(0_u64) // offset - .append(LOG0) -} - -/// Asserts that the log at the given index contains the expected CALL success flag. -fn assert_log_call_status( - result: &ResultAndState, - log_index: usize, - expected_success: bool, -) { - let logs = result.result.logs(); - assert!( - logs.len() > log_index, - "Expected at least {} log(s), got {}", - log_index + 1, - logs.len() - ); - let value = U256::from_be_slice(logs[log_index].data.data.as_ref()); - let expected = if expected_success { U256::from(1) } else { U256::ZERO }; - assert_eq!(value, expected, "Log[{log_index}] call status: expected {expected}, got {value}"); -} - -/// Appends CALL that captures return data, then returns it. -fn append_call_and_return_data( - builder: BytecodeBuilder, - target: Address, - gas: u64, -) -> BytecodeBuilder { - append_call(builder, target, gas) - .append(POP) // discard CALL success flag - // Copy return data to memory - .append(RETURNDATASIZE) // size - .push_number(0_u64) // dataOffset - .push_number(0_u64) // destOffset - .append(RETURNDATACOPY) - // Return the return data - .append(RETURNDATASIZE) - .push_number(0_u64) // offset - .append(RETURN) -} - -// ============================================================================ -// 1. BASIC disableVolatileDataAccess() BEHAVIOR -// ============================================================================ - -/// Inner call that accesses TIMESTAMP should revert when volatile access is disabled. -#[test] -fn test_inner_call_timestamp_reverts() { - // Child bytecode: just reads TIMESTAMP - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent bytecode: call disableVolatileDataAccess(), then call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); -} - -/// Caller's own frame IS restricted after calling `disableVolatileDataAccess()`. -#[test] -fn test_caller_frame_is_restricted() { - // Parent bytecode: call disableVolatileDataAccess(), then read TIMESTAMP itself - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = parent_code.append(TIMESTAMP).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - // The parent should revert because its own frame is restricted after disabling. - assert!( - !result.result.is_success(), - "Caller should revert when accessing TIMESTAMP after disabling, got: {:?}", - result.result - ); -} - -/// Inner call that does NOT access volatile data should succeed. -#[test] -fn test_inner_call_without_volatile_access_succeeds() { - // Child bytecode: just does some arithmetic and stops - let child_code = BytecodeBuilder::default() - .push_number(1_u64) - .push_number(2_u64) - .append(ADD) - .append(POP) - .stop() - .build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Inner call without volatile access should succeed"); - assert_log_call_status(&result, 0, true); -} - -// ============================================================================ -// 2. VOLATILE OPCODE COVERAGE -// ============================================================================ - -/// Test that multiple volatile opcodes each trigger revert in inner calls. -#[test] -fn test_volatile_opcodes_all_revert_in_inner_call() { - let volatile_opcodes: &[(u8, &str)] = &[ - (TIMESTAMP, "TIMESTAMP"), - (NUMBER, "NUMBER"), - (COINBASE, "COINBASE"), - (DIFFICULTY, "DIFFICULTY"), - (GASLIMIT, "GASLIMIT"), - (BASEFEE, "BASEFEE"), - (BLOCKHASH, "BLOCKHASH"), - (BLOBBASEFEE, "BLOBBASEFEE"), - (BLOBHASH, "BLOBHASH"), - ]; - - for &(opcode, name) in volatile_opcodes { - // Child code: execute the volatile opcode, then POP and STOP - let child_code = if opcode == BLOCKHASH || opcode == BLOBHASH { - // BLOCKHASH and BLOBHASH need an argument on the stack - BytecodeBuilder::default().push_number(0_u64).append(opcode).append(POP).stop().build() - } else { - BytecodeBuilder::default().append(opcode).append(POP).stop().build() - }; - - // Parent: disable volatile access, call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed for opcode {name}"); - assert_log_call_status(&result, 0, false); - } -} - -// ============================================================================ -// 3. REVERT DATA CONTAINS ABI-ENCODED ERROR -// ============================================================================ - -/// The revert data from an inner call that accesses volatile data should contain -/// the `VolatileDataAccessDisabled(uint8)` error with the correct access type. -#[test] -fn test_revert_data_contains_error_with_access_type() { - // Child: reads TIMESTAMP (will revert) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: disable volatile access, call child, capture revert data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, "Selector mismatch"); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Timestamp, - "Access type should be Timestamp (1)" - ); -} - -// ============================================================================ -// 4. NESTED CALLS -// ============================================================================ - -/// Volatile access restriction propagates through nested calls. -/// A → B (disableVolatileDataAccess) → C → D (reads TIMESTAMP) → reverts. -#[test] -fn test_nested_call_volatile_access_reverts() { - // Grandchild: reads TIMESTAMP - let grandchild_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Child: calls grandchild and logs grandchild's call status - let child_code = append_call(BytecodeBuilder::default(), GRANDCHILD, 40_000_000); - let child_code = append_log_call_status(child_code).stop().build(); - - // Parent: disable volatile access, call child, log child's call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code) - .account_code(GRANDCHILD, grandchild_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed even though grandchild reverted"); - // Child succeeded (returned to parent), but grandchild reverted. - // Log[0] is from child logging grandchild's call status (0 = reverted). - // Log[1] is from parent logging child's call status (1 = succeeded). - assert_log_call_status(&result, 0, false); - assert_log_call_status(&result, 1, true); -} - -// ============================================================================ -// 5. GAS ACCOUNTING -// ============================================================================ - -/// Reverted inner call returns gas to parent. -#[test] -fn test_reverted_inner_call_returns_gas() { - // Child: reads TIMESTAMP (will revert immediately) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: disable volatile access, call child with limited gas, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 10_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The gas used should be relatively small since child reverted immediately - // and gas was returned to parent - let gas_used = result.result.gas_used(); - assert!(gas_used < 5_000_000, "Gas used ({gas_used}) should be relatively small"); -} - -// ============================================================================ -// 6. CALL VARIANTS -// ============================================================================ - -/// STATICCALL inner call that accesses volatile data also reverts. -#[test] -fn test_staticcall_also_restricted() { - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_staticcall(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed with STATICCALL"); - assert_log_call_status(&result, 0, false); -} - -/// DELEGATECALL inner call that accesses volatile data also reverts. -#[test] -fn test_delegatecall_also_restricted() { - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_delegatecall(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed with DELEGATECALL"); - assert_log_call_status(&result, 0, false); -} - -// ============================================================================ -// 7. BACKWARD COMPATIBILITY -// ============================================================================ - -// ============================================================================ -// 8. CONDITIONAL VOLATILE OPCODES -// ============================================================================ - -/// BALANCE on a non-beneficiary address should NOT revert when volatile access is disabled, -/// because it does not actually access volatile data. -#[test] -fn test_balance_non_beneficiary_not_restricted() { - // Child: BALANCE of a non-beneficiary address (CHILD itself) - let child_code = BytecodeBuilder::default() - .push_address(CHILD) // non-beneficiary address - .append(BALANCE) - .append(POP) - .stop() - .build(); - - // Parent: disable volatile access, then call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "BALANCE on non-beneficiary should not be restricted"); - assert_log_call_status(&result, 0, true); -} - -/// BALANCE on the beneficiary address SHOULD revert when volatile access is disabled. -#[test] -fn test_balance_beneficiary_restricted() { - // The default beneficiary is Address::ZERO in tests. - let beneficiary = Address::ZERO; - - // Child: BALANCE of the beneficiary address - let child_code = BytecodeBuilder::default() - .push_address(beneficiary) - .append(BALANCE) - .append(POP) - .stop() - .build(); - - // Parent: disable volatile access, call child, capture revert data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // The inner call should have reverted with VolatileDataAccessDisabled(Beneficiary) - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "Access type should be Beneficiary (10)" - ); -} - -/// EXTCODESIZE on a non-beneficiary address should NOT revert when volatile access is disabled. -#[test] -fn test_extcodesize_non_beneficiary_not_restricted() { - // Child: EXTCODESIZE of a non-beneficiary address - let child_code = BytecodeBuilder::default() - .push_address(CHILD) - .append(EXTCODESIZE) - .append(POP) - .stop() - .build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "EXTCODESIZE on non-beneficiary should not be restricted"); - assert_log_call_status(&result, 0, true); -} - -/// When parent accesses volatile data (TIMESTAMP) before calling `disableVolatileDataAccess()`, -/// the child should still be restricted when accessing the same volatile data type. -/// The pre-execution check in the instruction handler detects the disabled state regardless of -/// whether the bitmap bit is already set. -#[test] -fn test_parent_accesses_volatile_then_child_restricted() { - // Child: reads TIMESTAMP (should revert because volatile access is disabled) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: read TIMESTAMP first, then disable volatile access, then call child - let parent_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP); - let parent_code = call_disable_volatile_data_access(parent_code); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // The inner call should have reverted with VolatileDataAccessDisabled(Timestamp) - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Timestamp, - "Child should revert with access type Timestamp even though parent already accessed it" - ); -} - -// ============================================================================ -// 9. SIBLING CALL SCOPING -// ============================================================================ - -/// When C1 calls `disableVolatileDataAccess()` and returns, sibling C2's children should NOT be -/// restricted. The disable flag should be deactivated when C1's frame returns. -/// -/// ```text -/// PARENT (depth 2) → C1 (depth 3) → disableVolatileDataAccess() → return -/// → C2 (depth 3) → GRANDCHILD (depth 4) reads TIMESTAMP → should succeed -/// ``` -#[test] -fn test_sibling_call_not_restricted() { - // C1: calls disableVolatileDataAccess() and returns - let c1_code = call_disable_volatile_data_access(BytecodeBuilder::default()).stop().build(); - - // GRANDCHILD: reads TIMESTAMP (should succeed because C2 never disabled volatile access) - let grandchild_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // C2 (SIBLING): calls GRANDCHILD and propagates the call result - // CALL returns 1 on success, 0 on failure. Store to memory and return it. - let c2_code = append_call(BytecodeBuilder::default(), GRANDCHILD, 40_000_000) - // Stack: [success_flag] - .push_number(0_u64) // memory offset - .append(MSTORE) // MSTORE(offset=0, value=success_flag) - .push_number(32_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build(); - - // PARENT: call C1, then call C2 and return C2's output - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000) - .append(POP) // discard C1's success flag - // Now call C2 and capture its return data - .push_number(32_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(SIBLING) - .push_number(50_000_000_u64) // gas - .append(CALL) - .append(POP) // discard C2's success flag - // Return C2's return data (the GRANDCHILD call result stored at memory[0]) - .push_number(32_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, c1_code) // C1 - .account_code(SIBLING, c2_code) // C2 - .account_code(GRANDCHILD, grandchild_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // The return data should contain the GRANDCHILD call success flag (1 = success). - let output = result.result.output().expect("Should have output"); - let grandchild_success = U256::from_be_slice(output.as_ref()); - assert_eq!( - grandchild_success, - U256::from(1), - "GRANDCHILD should succeed: C2's child should NOT be restricted by C1's disableVolatileDataAccess()" - ); -} - -// ============================================================================ -// 10. enableVolatileDataAccess() -// ============================================================================ - -/// Same frame disables then enables, child can access volatile data. -#[test] -fn test_enable_after_disable_succeeds() { - // Child: reads TIMESTAMP (should succeed because parent re-enabled) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: disable, then enable, then call child - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = call_enable_volatile_data_access(parent_code); - let parent_code = append_call(parent_code, CHILD, 50_000_000) - // CALL returns 1 on success, 0 on failure. Store and return. - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - let child_success = U256::from_be_slice(output.as_ref()); - assert_eq!( - child_success, - U256::from(1), - "Child should succeed after parent re-enabled volatile data access" - ); -} - -/// Parent disables, child tries to enable → reverts with `DisabledByParent()`. -#[test] -fn test_enable_by_child_reverts_when_parent_disabled() { - // Child: tries to call enableVolatileDataAccess(), captures return data - let child_code = call_enable_volatile_data_access(BytecodeBuilder::default()); - // enableVolatileDataAccess() call will have reverted. Capture the return data from it. - // The enable CALL returns 0 on failure. Let's just return the enable call's return data. - let child_code = child_code - .append(RETURNDATASIZE) - .push_number(0_u64) - .push_number(0_u64) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .push_number(0_u64) - .append(RETURN) - .build(); - - // Parent: disable volatile access, call child, capture child's return data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!( - output.as_ref(), - &DISABLED_BY_PARENT_SELECTOR, - "Child's enable call should revert with DisabledByParent()" - ); -} - -/// Calling `enableVolatileDataAccess()` when not disabled is a no-op (succeeds). -#[test] -fn test_enable_when_not_disabled_is_noop() { - // Parent: just call enableVolatileDataAccess() without prior disable - let parent_code = call_enable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = parent_code.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!( - result.result.is_success(), - "enableVolatileDataAccess() when not disabled should succeed" - ); -} - -/// STATICCALL to `disableVolatileDataAccess()` should apply the same restriction as CALL. -#[test] -fn test_staticcall_disable_volatile_data_access_is_intercepted() { - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - let parent_code = append_access_control_staticcall( - BytecodeBuilder::default(), - DISABLE_VOLATILE_DATA_ACCESS_SELECTOR, - 100_000, - ); - let parent_code = append_log_call_status(parent_code); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, true); - assert_log_call_status(&result, 1, false); -} - -/// STATICCALL to `enableVolatileDataAccess()` should re-enable access when the caller disabled it. -#[test] -fn test_staticcall_enable_volatile_data_access_is_intercepted() { - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_access_control_staticcall( - parent_code, - ENABLE_VOLATILE_DATA_ACCESS_SELECTOR, - 100_000, - ); - let parent_code = append_log_call_status(parent_code); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, true); - assert_log_call_status(&result, 1, true); -} - -// ============================================================================ -// 11. isVolatileDataAccessDisabled() -// ============================================================================ - -/// Query returns false when no disable is active. -#[test] -fn test_query_returns_false_when_not_disabled() { - // Parent: call isVolatileDataAccessDisabled() and return the result - let parent_code = call_is_volatile_data_access_disabled(BytecodeBuilder::default()).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - let disabled = U256::from_be_slice(output.as_ref()); - assert_eq!(disabled, U256::ZERO, "Should return false when not disabled"); -} - -/// Query returns true when a parent disabled volatile data access. -#[test] -fn test_query_returns_true_when_parent_disabled() { - // Child: call isVolatileDataAccessDisabled() and return the result - let child_code = call_is_volatile_data_access_disabled(BytecodeBuilder::default()).build(); - - // Parent: disable, then call child that queries - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - let disabled = U256::from_be_slice(output.as_ref()); - assert_eq!(disabled, U256::from(1), "Should return true when parent disabled"); -} - -/// Query returns true for the frame that called disable (caller IS now restricted). -#[test] -fn test_query_returns_true_for_disabling_frame() { - // Parent: disable, then query isVolatileDataAccessDisabled() in same frame - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = call_is_volatile_data_access_disabled(parent_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - let disabled = U256::from_be_slice(output.as_ref()); - assert_eq!( - disabled, - U256::from(1), - "Should return true when queried in the frame that called disable" - ); -} - -// ============================================================================ -// 12. DIRECT TX CALLS TO ACCESS CONTROL CONTRACT -// ============================================================================ - -/// Helper to build a TX that calls the access control contract directly with the given selector. -fn direct_access_control_tx(selector: &[u8; 4]) -> TxEnv { - direct_access_control_tx_with_value(selector, U256::ZERO) -} - -/// Helper to build a TX that calls the access control contract directly with selector and value. -fn direct_access_control_tx_with_value(selector: &[u8; 4], value: U256) -> TxEnv { - TxEnvBuilder::default() - .caller(CALLER) - .call(ACCESS_CONTROL_ADDRESS) - .value(value) - .gas_limit(100_000_000) - .data(Bytes::copy_from_slice(selector)) - .build_fill() -} - -/// Direct TX calling `disableVolatileDataAccess()` should succeed without frame stack underflow. -#[test] -fn test_direct_tx_disable_volatile_data_access() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(&mut db, direct_access_control_tx(&DISABLE_VOLATILE_DATA_ACCESS_SELECTOR)) - .unwrap(); - assert!( - result.result.is_success(), - "Direct TX to disableVolatileDataAccess should succeed, got: {:?}", - result.result - ); -} - -/// Direct TX calling `disableVolatileDataAccess()` with non-zero value should revert. -#[test] -fn test_direct_tx_disable_volatile_data_access_with_value_reverts() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = transact( - &mut db, - direct_access_control_tx_with_value( - &DISABLE_VOLATILE_DATA_ACCESS_SELECTOR, - U256::from(1_u64), - ), - ) - .unwrap(); - assert!( - !result.result.is_success(), - "Direct TX with non-zero value should revert, got: {:?}", - result.result - ); - let output = result.result.output().expect("Should have output"); - assert_eq!(output.len(), 4, "non-zero transfer revert should return selector only"); - assert_eq!( - &output[..4], - &NON_ZERO_TRANSFER_SELECTOR, - "non-zero transfer should revert with NonZeroTransfer()" - ); -} - -/// Direct TX calling `enableVolatileDataAccess()` should succeed without frame stack underflow. -#[test] -fn test_direct_tx_enable_volatile_data_access() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(&mut db, direct_access_control_tx(&ENABLE_VOLATILE_DATA_ACCESS_SELECTOR)).unwrap(); - assert!( - result.result.is_success(), - "Direct TX to enableVolatileDataAccess should succeed, got: {:?}", - result.result - ); -} - -/// Direct TX calling `isVolatileDataAccessDisabled()` should succeed and return false. -#[test] -fn test_direct_tx_is_volatile_data_access_disabled() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(&mut db, direct_access_control_tx(&IS_VOLATILE_DATA_ACCESS_DISABLED_SELECTOR)) - .unwrap(); - assert!( - result.result.is_success(), - "Direct TX to isVolatileDataAccessDisabled should succeed, got: {:?}", - result.result - ); - - let output = result.result.output().expect("Should have output"); - let disabled = U256::from_be_slice(output.as_ref()); - assert_eq!(disabled, U256::ZERO, "Should return false when called directly by TX"); -} - -/// Direct TX with unknown selector should fall through and revert with `NotIntercepted()`. -#[test] -fn test_direct_tx_unknown_selector_falls_through_and_reverts_not_intercepted() { - let unknown_selector = [0xde, 0xad, 0xbe, 0xef]; - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(ACCESS_CONTROL_ADDRESS, mega_evm::ACCESS_CONTROL_CODE); - - let result = transact(&mut db, direct_access_control_tx(&unknown_selector)).unwrap(); - assert!( - !result.result.is_success(), - "Unknown selector should fall through and revert, got: {:?}", - result.result - ); - - let output = result.result.output().expect("Should have output"); - assert_eq!( - output.len(), - 4, - "Fallback should return only NotIntercepted selector, got {} bytes", - output.len() - ); - assert_eq!( - &output[..4], - &NOT_INTERCEPTED_SELECTOR, - "Unknown selector should revert with NotIntercepted()" - ); -} - -// ============================================================================ -// 13. INSPECTOR VISIBILITY FOR SYSTEM CONTRACT CALLS -// ============================================================================ - -/// An inspector that records all `call` and `call_end` invocations. -#[derive(Default)] -struct CallTrackingInspector { - /// Target addresses seen in `call` hooks, in order. - calls: Vec
, - /// Target addresses seen in `call_end` hooks, in order. - call_ends: Vec
, -} - -impl Inspector for CallTrackingInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - self.calls.push(inputs.target_address); - None - } - - fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.call_ends.push(inputs.target_address); - } -} - -/// When an inspector is attached, it should see `call` and `call_end` for system contract -/// calls that are intercepted in `frame_init`, even though no interpreter frame is created. -#[test] -fn test_inspector_sees_system_contract_call() { - // Child: simple arithmetic, no volatile access - let child_code = BytecodeBuilder::default() - .push_number(1_u64) - .push_number(2_u64) - .append(ADD) - .append(POP) - .stop() - .build(); - - // Parent: call disableVolatileDataAccess(), then call CHILD, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut inspector = CallTrackingInspector::default(); - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Transaction should succeed"); - - // Inspector should have seen 3 calls: - // 1. Top-level call to PARENT - // 2. PARENT -> ACCESS_CONTROL_ADDRESS (intercepted in frame_init) - // 3. PARENT -> CHILD (normal call) - assert_eq!( - inspector.calls.len(), - 3, - "Inspector should see 3 call hooks: top-level + access control + child, got: {:?}", - inspector.calls - ); - assert_eq!(inspector.calls[0], PARENT, "First call should be to PARENT"); - assert_eq!( - inspector.calls[1], ACCESS_CONTROL_ADDRESS, - "Second call should be to ACCESS_CONTROL_ADDRESS" - ); - assert_eq!(inspector.calls[2], CHILD, "Third call should be to CHILD"); - - // call_end should be invoked for all 3 calls, in reverse order - assert_eq!( - inspector.call_ends.len(), - 3, - "Inspector should see 3 call_end hooks, got: {:?}", - inspector.call_ends - ); - assert_eq!( - inspector.call_ends[0], ACCESS_CONTROL_ADDRESS, - "First call_end should be ACCESS_CONTROL_ADDRESS (innermost, returned first)" - ); - assert_eq!(inspector.call_ends[1], CHILD, "Second call_end should be CHILD"); - assert_eq!(inspector.call_ends[2], PARENT, "Third call_end should be PARENT (outermost)"); - - assert_log_call_status(&result, 0, true); -} - -// ============================================================================ -// 14. GAS COST OF SYSTEM CONTRACT CALL -// ============================================================================ - -/// The system contract call intercepted in `frame_init` should only consume the CALL opcode -/// overhead (warm account access = 100 gas), not the `gas_limit` forwarded to the child frame. -/// The child frame's gas is fully refunded since the interception returns `Gas::new(gas_limit)`. -#[test] -fn test_system_contract_call_gas_cost() { - // Parent bytecode: - // 1. GAS — push gas_before - // 2. CALL(100_000, ACCESS_CONTROL, 0, disableVolatileDataAccess selector) - // 3. POP — discard CALL success flag - // 4. GAS — push gas_after - // 5. SWAP1 — [gas_after, gas_before] -> [gas_before, gas_after] - // 6. SUB — gas_before - gas_after = gas_consumed - // 7. MSTORE at 0x20 — store gas_consumed - // 8. RETURN 32 bytes from 0x20 - // - // Note: the GAS opcode itself costs 2 gas. The measured delta includes the cost of - // setting up the CALL arguments (pushes), the CALL opcode overhead, POP, and one GAS. - // The CALL forwards 100,000 gas to the child frame, which should all come back. - - // First, store the selector in memory (needed for CALL input) - let parent_code = BytecodeBuilder::default().mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR); - - let parent_code = parent_code - .append(GAS) // gas_before (costs 2 gas, measured AFTER this) - // Set up CALL arguments - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas to forward - .append(CALL) - .append(POP) // discard success flag - .append(GAS) // gas_after - // gas_before is below gas_after on the stack: [gas_before, gas_after] - // SWAP1 to get [gas_after, gas_before], then SUB = gas_before - gas_after - .append(SWAP1) - .append(SUB) // gas_consumed = gas_before - gas_after - // Store and return - .push_number(0x20_u64) - .append(MSTORE) - .push_number(32_u64) // size - .push_number(0x20_u64) // offset - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Transaction should succeed"); - - let output = result.result.output().expect("Should have output"); - let gas_consumed = U256::from_be_slice(output.as_ref()).to::(); - - // The gas consumed by the measured region includes: - // - 7 PUSH instructions (3 gas each = 21 gas) for CALL arguments - // - 1 PUSH20 for address (3 gas) - // - CALL cold account access (2600 gas, since ACCESS_CONTROL_ADDRESS is first accessed here) - // - POP (2 gas) - // - GAS (2 gas) - // - SWAP1 (3 gas) - // Total overhead ≈ 2631 gas - // - // Critically, it should NOT include the 100,000 gas forwarded to the child frame, - // because the intercepted call returns all gas. - assert!( - gas_consumed < 3000, - "System contract call gas delta should be small (CALL overhead only), got: {gas_consumed}. \ - If this is close to 100,000, the child frame gas was not refunded." - ); - - // Sanity check: it should at least include the cold CALL cost (2600) - assert!( - gas_consumed >= 2600, - "Gas consumed ({gas_consumed}) should be at least 2600 (cold CALL cost)" - ); -} - -// ============================================================================ -// 15. BLOCKED VOLATILE ACCESS DOES NOT POLLUTE TRACKER -// ============================================================================ - -/// When volatile data access is disabled and a child frame attempts to read volatile data -/// (causing it to revert), the `volatile_data_accessed` bitmap and `compute_gas_limit` -/// should NOT be modified. -/// The instruction handler reverts before the opcode executes, so no tracker state is changed. -#[test] -fn test_blocked_volatile_access_does_not_set_bitmap() { - // Child: reads TIMESTAMP (will revert because volatile access is disabled) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: disable volatile access, call child (which reverts), log call status, then stop. - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The blocked TIMESTAMP access should NOT have set the volatile_data_accessed bitmap. - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "volatile_data_accessed should be empty after blocked access, got: {:?}", - tracker.get_volatile_data_accessed() - ); - assert!( - tracker.get_compute_gas_limit().is_none(), - "compute_gas_limit should not be set after blocked access, got: {:?}", - tracker.get_compute_gas_limit() - ); -} - -/// When volatile data access is disabled, BALANCE on the beneficiary should revert -/// and NOT pollute the `volatile_data_accessed` bitmap or `compute_gas_limit`. -#[test] -fn test_blocked_beneficiary_balance_does_not_set_bitmap() { - let beneficiary = Address::ZERO; - - // Child: BALANCE of the beneficiary (will revert because volatile access is disabled) - let child_code = BytecodeBuilder::default() - .push_address(beneficiary) - .append(BALANCE) - .append(POP) - .stop() - .build(); - - // Parent: disable volatile access, call child (which reverts), log call status, then stop. - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The blocked BALANCE(beneficiary) access should NOT have set the bitmap. - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "volatile_data_accessed should be empty after blocked beneficiary BALANCE, got: {:?}", - tracker.get_volatile_data_accessed() - ); - assert!( - tracker.get_compute_gas_limit().is_none(), - "compute_gas_limit should not be set after blocked beneficiary BALANCE, got: {:?}", - tracker.get_compute_gas_limit() - ); -} - -/// When volatile data access is disabled, SLOAD on the oracle contract should revert -/// and NOT pollute the `volatile_data_accessed` bitmap or `compute_gas_limit`. -#[test] -fn test_blocked_oracle_sload_does_not_set_bitmap() { - // Oracle contract code: SLOAD(0) and return. - // When called by an inner frame with volatile access disabled, this triggers the - // pre-execution check in the SLOAD instruction handler and reverts. - let oracle_code = BytecodeBuilder::default() - .push_number(0_u64) // key = 0 - .append(SLOAD) - .append(POP) - .stop() - .build(); - - // Parent: disable volatile access, then call the oracle contract (which will revert), - // log call status, then stop. - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, ORACLE_CONTRACT_ADDRESS, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The blocked oracle SLOAD should NOT have set the bitmap. - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "volatile_data_accessed should be empty after blocked oracle SLOAD, got: {:?}", - tracker.get_volatile_data_accessed() - ); - assert!( - tracker.get_compute_gas_limit().is_none(), - "compute_gas_limit should not be set after blocked oracle SLOAD, got: {:?}", - tracker.get_compute_gas_limit() - ); -} - -// ============================================================================ -// 16. DELEGATECALL / CALLCODE TO ACCESS CONTROL CONTRACT -// ============================================================================ - -/// Builds bytecode that CALLCODEs a target address with the given gas and no calldata. -fn append_callcode(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALLCODE) -} - -/// Executes a transaction on Rex4 spec with oracle external environment. -fn transact_with_oracle( - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let external_envs = TestExternalEnvs::::new() - .with_oracle_storage(U256::from(0), U256::from(0x1234)); - let mut context = - MegaContext::new(db, MegaSpecId::REX4).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// DELEGATECALL to the access control contract should NOT be intercepted. -/// The underlying contract code executes and reverts with `NotIntercepted()`. -/// Subsequent inner calls that access volatile data should succeed. -#[test] -fn test_delegatecall_to_access_control_not_intercepted() { - // Child: reads TIMESTAMP (should succeed — disable was never activated) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: DELEGATECALL access control with disableVolatileDataAccess selector, - // then CALL child which reads TIMESTAMP. - let parent_code = BytecodeBuilder::default().mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR); - // DELEGATECALL(gas, addr, argsOffset, argsSize, retOffset, retSize) - let parent_code = parent_code - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(DELEGATECALL) - .append(POP); // discard success flag (should be 0 = failure due to NotIntercepted revert) - let parent_code = append_call(parent_code, CHILD, 50_000_000) - // Stack: [call_success]. Store and return. - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code) - .account_code(ACCESS_CONTROL_ADDRESS, mega_evm::ACCESS_CONTROL_CODE); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // Child CALL should have succeeded (returned 1) - let output = result.result.output().expect("Should have output"); - let child_success = U256::from_be_slice(output.as_ref()); - assert_eq!( - child_success, - U256::from(1), - "Child should succeed because DELEGATECALL to access control was not intercepted" - ); -} - -/// CALLCODE to the access control contract should NOT be intercepted. -/// The underlying contract code executes and reverts with `NotIntercepted()`. -/// Subsequent inner calls that access volatile data should succeed. -#[test] -fn test_callcode_to_access_control_not_intercepted() { - // Child: reads TIMESTAMP (should succeed — disable was never activated) - let child_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // Parent: CALLCODE access control with disableVolatileDataAccess selector, - // then CALL child which reads TIMESTAMP. - let parent_code = BytecodeBuilder::default().mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR); - // CALLCODE(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - let parent_code = parent_code - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize (4-byte selector) - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALLCODE) - .append(POP); // discard success flag (should be 0 = failure due to NotIntercepted revert) - let parent_code = append_call(parent_code, CHILD, 50_000_000) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code) - .account_code(ACCESS_CONTROL_ADDRESS, mega_evm::ACCESS_CONTROL_CODE); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // Child CALL should have succeeded (returned 1) - let output = result.result.output().expect("Should have output"); - let child_success = U256::from_be_slice(output.as_ref()); - assert_eq!( - child_success, - U256::from(1), - "Child should succeed because CALLCODE to access control was not intercepted" - ); -} - -// ============================================================================ -// 17. DISABLE IN REVERTED CHILD DOES NOT AFFECT SIBLING -// ============================================================================ - -/// When a child frame calls `disableVolatileDataAccess()` and then reverts, the disable -/// should be cleared when the child's frame returns (via `enable_access_if_returning`). -/// A sibling call should NOT be restricted. -/// -/// ```text -/// PARENT → CHILD (calls disable, then REVERTs) -/// → SIBLING (reads TIMESTAMP) → should succeed -/// ``` -#[test] -fn test_disable_in_reverted_child_does_not_affect_sibling() { - // CHILD: calls disableVolatileDataAccess(), then immediately reverts - let child_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) // size - .push_number(0_u64) // offset - .append(REVERT) - .build(); - - // SIBLING: reads TIMESTAMP (should succeed) - let sibling_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).stop().build(); - - // PARENT: call CHILD (which reverts), log child call status, then call SIBLING, - // return SIBLING's success flag - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code); - let parent_code = append_call(parent_code, SIBLING, 50_000_000) - // Stack: [sibling_success]. Store and return. - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code) - .account_code(SIBLING, sibling_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - assert_log_call_status(&result, 0, false); - - let output = result.result.output().expect("Should have output"); - let sibling_success = U256::from_be_slice(output.as_ref()); - assert_eq!( - sibling_success, - U256::from(1), - "SIBLING should succeed: CHILD's disable was cleared when CHILD's frame reverted" - ); -} - -// ============================================================================ -// 18. ORACLE SLOAD WITH DISABLED VOLATILE ACCESS -// ============================================================================ - -/// Oracle SLOAD should revert with VolatileDataAccessDisabled(Oracle) when volatile -/// data access is disabled. -#[test] -fn test_oracle_sload_reverts_when_volatile_access_disabled() { - // Oracle contract code: SLOAD(0) - let oracle_code = BytecodeBuilder::default() - .push_number(0_u64) // key = 0 - .append(SLOAD) - .append(POP) - .stop() - .build(); - - // Parent: disable volatile access, call oracle, capture return data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = - append_call_and_return_data(parent_code, ORACLE_CONTRACT_ADDRESS, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(ORACLE_CONTRACT_ADDRESS, oracle_code); - - let result = transact_with_oracle(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // The oracle SLOAD should have reverted with VolatileDataAccessDisabled(Oracle) - let output = result.result.output().expect("Should have output"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "Oracle SLOAD should revert with VolatileDataAccessDisabled error" - ); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!(decoded.accessType, VolatileDataAccessType::Oracle, "Access type should be Oracle"); -} - -// ============================================================================ -// 19. CREATE WITH DISABLED VOLATILE ACCESS -// ============================================================================ - -/// CREATE whose init code accesses TIMESTAMP should fail when volatile access is disabled. -/// The CREATE returns address 0 (failure), but the parent transaction itself succeeds. -#[test] -fn test_create_reverts_when_volatile_access_disabled() { - // Init code that accesses TIMESTAMP, then returns empty deployed code. - // TIMESTAMP -> POP -> PUSH1(0) -> PUSH1(0) -> RETURN (deploy zero-length code) - let init_code = BytecodeBuilder::default() - .append(TIMESTAMP) - .append(POP) - .push_number(0_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build(); - - // Parent: disable volatile access, then CREATE with the init code, return created address. - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - // Store init code in memory at offset 0x40 (after selector storage area) - let parent_code = parent_code - .mstore(0x40, init_code.clone()) - .push_number(init_code.len() as u64) // size - .push_number(0x40_u64) // offset - .push_number(0_u64) // value - .append(CREATE) - // Stack: [created_address]. Store and return. - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - // CREATE should have failed (returned address 0) because init code's TIMESTAMP reverted - let output = result.result.output().expect("Should have output"); - let created_address = U256::from_be_slice(output.as_ref()); - assert_eq!( - created_address, - U256::ZERO, - "CREATE should fail (return 0) because init code accessed volatile data" - ); -} - -// ============================================================================ -// 20. CALL-LIKE OPCODES TARGETING BENEFICIARY -// ============================================================================ - -/// CALL to the beneficiary address should revert when volatile access is disabled. -/// The child contract CALLs the beneficiary; the parent captures the child's revert data. -#[test] -fn test_call_beneficiary_restricted() { - let beneficiary = Address::ZERO; - - // Child: CALL the beneficiary address - let child_code = append_call(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - // Parent: disable volatile access, call child, capture revert data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "CALL to beneficiary should revert with Beneficiary access type" - ); -} - -/// STATICCALL to the beneficiary address should revert when volatile access is disabled. -#[test] -fn test_staticcall_beneficiary_restricted() { - let beneficiary = Address::ZERO; - - // Child: STATICCALL the beneficiary address - let child_code = - append_staticcall(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "STATICCALL to beneficiary should revert with Beneficiary access type" - ); -} - -/// DELEGATECALL to the beneficiary address should revert when volatile access is disabled. -#[test] -fn test_delegatecall_beneficiary_restricted() { - let beneficiary = Address::ZERO; - - // Child: DELEGATECALL the beneficiary address - let child_code = - append_delegatecall(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "DELEGATECALL to beneficiary should revert with Beneficiary access type" - ); -} - -/// CALLCODE to the beneficiary address should revert when volatile access is disabled. -#[test] -fn test_callcode_beneficiary_restricted() { - let beneficiary = Address::ZERO; - - // Child: CALLCODE the beneficiary address - let child_code = - append_callcode(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - - let output = result.result.output().expect("Should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "CALLCODE to beneficiary should revert with Beneficiary access type" - ); -} - -/// CALL to a non-beneficiary address should NOT revert when volatile access is disabled. -#[test] -fn test_call_non_beneficiary_not_restricted() { - // Child: CALL a non-beneficiary address (GRANDCHILD) - let grandchild_code = BytecodeBuilder::default().stop().build(); - let child_code = append_call(BytecodeBuilder::default(), GRANDCHILD, 100_000).stop().build(); - - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code) - .account_code(GRANDCHILD, grandchild_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "CALL to non-beneficiary should not be restricted"); - assert_log_call_status(&result, 0, true); -} - -/// CALL to beneficiary should work normally (with gas detention) when volatile access is NOT -/// disabled. -#[test] -fn test_call_beneficiary_not_restricted_without_disable() { - let beneficiary = Address::ZERO; - - // Child: CALL beneficiary without disabling volatile access. - let child_code = append_call(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!( - result.result.is_success(), - "CALL to beneficiary should succeed when volatile access is not disabled" - ); - assert_log_call_status(&result, 0, true); -} - -/// Blocked CALL to beneficiary should NOT pollute the volatile data tracker. -#[test] -fn test_blocked_call_beneficiary_does_not_pollute_tracker() { - let beneficiary = Address::ZERO; - - // Child: CALL beneficiary (will be blocked by volatile access disable) - let child_code = append_call(BytecodeBuilder::default(), beneficiary, 100_000).stop().build(); - - // Parent: disable volatile access, call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The blocked CALL to beneficiary should NOT have set the volatile_data_accessed bitmap. - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "volatile_data_accessed should be empty after blocked CALL to beneficiary" - ); - assert!( - tracker.get_compute_gas_limit().is_none(), - "compute_gas_limit should not be set after blocked CALL to beneficiary" - ); -} - -// ============================================================================ -// 21. SELFDESTRUCT TARGETING BENEFICIARY -// ============================================================================ - -/// SELFDESTRUCT targeting the beneficiary should revert when volatile access is disabled. -#[test] -fn test_selfdestruct_beneficiary_restricted() { - let beneficiary = Address::ZERO; - - // Child: SELFDESTRUCT targeting the beneficiary address - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // Parent: disable volatile access, call child, capture revert data - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_data(parent_code, CHILD, 50_000_000).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - let output = result.result.output().expect("should have output"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "SELFDESTRUCT to beneficiary should revert with Beneficiary access type" - ); -} - -/// SELFDESTRUCT targeting a non-beneficiary address should NOT revert when volatile access -/// is disabled. -#[test] -fn test_selfdestruct_non_beneficiary_not_restricted() { - // Child: SELFDESTRUCT targeting a non-beneficiary address (GRANDCHILD) - let child_code = - BytecodeBuilder::default().push_address(GRANDCHILD).append(SELFDESTRUCT).build(); - - // Parent: disable volatile access, call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!(result.result.is_success(), "SELFDESTRUCT to non-beneficiary should not be restricted"); - assert_log_call_status(&result, 0, true); -} - -/// SELFDESTRUCT targeting the beneficiary should work (with gas detention) when volatile -/// access is NOT disabled. -#[test] -fn test_selfdestruct_beneficiary_not_restricted_without_disable() { - let beneficiary = Address::ZERO; - - // Child: SELFDESTRUCT targeting the beneficiary - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // Parent: call child without disabling volatile access, log call status - let parent_code = append_call(BytecodeBuilder::default(), CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let result = transact(&mut db, default_tx(PARENT)).unwrap(); - assert!( - result.result.is_success(), - "SELFDESTRUCT to beneficiary should succeed when volatile access is not disabled" - ); - assert_log_call_status(&result, 0, true); -} - -/// Blocked SELFDESTRUCT to beneficiary should NOT pollute the volatile data tracker. -#[test] -fn test_blocked_selfdestruct_beneficiary_does_not_pollute_tracker() { - let beneficiary = Address::ZERO; - - // Child: SELFDESTRUCT targeting the beneficiary (will be blocked) - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // Parent: disable volatile access, call child, log call status - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 50_000_000); - let parent_code = append_log_call_status(parent_code).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(PARENT, parent_code) - .account_code(CHILD, child_code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let volatile_data_tracker = context.volatile_data_tracker.clone(); - - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(PARENT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - assert!(result.result.is_success(), "Parent tx should succeed"); - assert_log_call_status(&result, 0, false); - - // The blocked SELFDESTRUCT to beneficiary should NOT have set the bitmap. - let tracker = volatile_data_tracker.borrow(); - assert!( - !tracker.accessed(), - "volatile_data_accessed should be empty after blocked SELFDESTRUCT to beneficiary" - ); - assert!( - tracker.get_compute_gas_limit().is_none(), - "compute_gas_limit should not be set after blocked SELFDESTRUCT to beneficiary" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs deleted file mode 100644 index 5944b95e9..000000000 --- a/crates/mega-evm/tests/_pending/rex4/beneficiary_detention.rs +++ /dev/null @@ -1,749 +0,0 @@ -//! Regression tests for Finding 2: Gas Detention Enforcement Gap via CALL to Beneficiary. -//! -//! Before the fix: -//! - `wrap_call_volatile_check` never called `apply_compute_gas_limit!`, so CALL/STATICCALL/ -//! DELEGATECALL/CALLCODE to the beneficiary marked the tracker but never propagated the detained -//! limit into `AdditionalLimit`. -//! - `on_new_tx()` called `check_tx_beneficiary_access()` before `additional_limit.reset()`, so -//! eager beneficiary detention was immediately cleared. -//! - SELFBALANCE had no volatile detention wrapper, so a beneficiary contract executing SELFBALANCE -//! never triggered gas detention. -//! -//! ## Beneficiary Detention Path Checklist -//! -//! | Path | Trigger | Wrapper / Hook | Test | -//! |---|---|---|---| -//! | CALL to beneficiary | `load_account_delegated` | `wrap_call_volatile_check!` + `apply_compute_gas_limit!` | test 1, 1b | -//! | STATICCALL to beneficiary | `load_account_delegated` | `wrap_call_volatile_check!` + `apply_compute_gas_limit!` | test 2 | -//! | DELEGATECALL to beneficiary | `load_account_delegated` | `wrap_call_volatile_check!` + `apply_compute_gas_limit!` | test 3 | -//! | CALLCODE to beneficiary | `load_account_delegated` | `wrap_call_volatile_check!` + `apply_compute_gas_limit!` | test 4 | -//! | TX sender = beneficiary | `on_new_tx` eager | `check_tx_beneficiary_access` + sync (REX4) | test 5, 5b | -//! | TX recipient = beneficiary | `on_new_tx` eager | `check_tx_beneficiary_access` + sync (REX4) | test 6, 6b | -//! | SELFBALANCE in beneficiary | `host.balance()` | `volatile_data_ext::selfbalance` | test 7 (integration), 9 (address sensitivity) | -//! | BALANCE(beneficiary) | `host.balance()` | `wrap_op_detain_gas_conditional!` | (covered in `block_env_gas_limit.rs`) | -//! | CALL to non-beneficiary | — | no trigger | test 8 (negative) | -//! | SELFBALANCE in non-beneficiary | — | no trigger | test 9 (negative) | -//! | Child reverts after CALL to beneficiary | `load_account_delegated` | detention persists | test 1b | -//! | disableVolatileDataAccess + CALL beneficiary | — | CALL blocked by `wrap_call_volatile_check` | (covered in `access_control.rs`) | -//! | disableVolatileDataAccess + SELFBALANCE beneficiary | — | revert before exec | test 10 | -//! | Detention + intrinsic DataSize overflow | `on_new_tx` eager | halt with DataLimitExceeded | test 11 | -//! | Detention + execution data limit | `wrap_call_volatile_check` | data limit independent of detention | test 12 | - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaAccessControl, IMegaLimitControl, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, ACCESS_CONTROL_ADDRESS, - LIMIT_CONTROL_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - tx::TxEnvBuilder, - BlockEnv, TxEnv, - }, - handler::EvmTr, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000400000"); -const CALLEE: Address = address!("0000000000000000000000000000000000400001"); -/// Used as the block beneficiary in these tests. -const BENEFICIARY: Address = address!("0000000000000000000000000000000000400099"); - -/// The gas detention cap for beneficiary access (same as block env access: 20M). -const DETENTION_CAP: u64 = 20_000_000; - -// ============================================================================ -// HELPERS -// ============================================================================ - -/// Executes a transaction with the given spec, database, beneficiary, and limits. -fn transact_with_spec( - spec: MegaSpecId, - db: &mut MemoryDatabase, - beneficiary: Address, - compute_gas_limit: u64, - block_env_access_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let block = BlockEnv { beneficiary, ..Default::default() }; - - let mut context = MegaContext::new(db, spec).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(compute_gas_limit) - .with_block_env_access_compute_gas_limit(block_env_access_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let detained_limit = evm.ctx_ref().additional_limit.borrow().detained_compute_gas_limit(); - Ok((r, detained_limit)) -} - -/// Shorthand: executes with REX4 spec. -fn transact( - db: &mut MemoryDatabase, - beneficiary: Address, - compute_gas_limit: u64, - block_env_access_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - transact_with_spec( - MegaSpecId::REX4, - db, - beneficiary, - compute_gas_limit, - block_env_access_limit, - tx, - ) -} - -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(1_000_000_000).build_fill() -} - -/// The 4-byte selector for `remainingComputeGas()`. -const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; - -/// Builds bytecode that CALLs `remainingComputeGas()` on `MegaLimitControl` and RETURNs the result. -fn query_remaining_compute_gas(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(32_u64) // retSize - .push_number(0x20_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .push_number(32_u64) - .push_number(0x20_u64) - .append(RETURN) -} - -/// Decodes `remainingComputeGas()` return data. -fn decode_remaining(result: &ResultAndState) -> u64 { - let output = match &result.result { - revm::context::result::ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("expected success, got: {:?}", result.result), - }; - IMegaLimitControl::remainingComputeGasCall::abi_decode_returns(&output) - .expect("should decode remainingComputeGas output") -} - -/// Builds bytecode for a CALL to `target` with given gas. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Builds bytecode for a STATICCALL to `target`. -fn append_staticcall(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(target) - .push_number(gas) - .append(STATICCALL) -} - -/// Builds bytecode for a DELEGATECALL to `target`. -fn append_delegatecall(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(target) - .push_number(gas) - .append(DELEGATECALL) -} - -/// Builds bytecode for a CALLCODE to `target`. -fn append_callcode(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALLCODE) -} - -// ============================================================================ -// TEST 1: CALL to beneficiary triggers detention -// ============================================================================ - -/// After a CALL to the beneficiary, `remainingComputeGas()` should be capped. -#[test] -fn test_call_to_beneficiary_triggers_detention() { - // Callee: CALL beneficiary (empty account, immediate return), then query remaining gas. - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let callee_code = append_call(BytecodeBuilder::default(), BENEFICIARY, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "After CALL to beneficiary, remaining compute gas should be ≤ {DETENTION_CAP}, got {remaining}" - ); - assert!( - detained_limit < 200_000_000, - "Detained limit should be lowered from TX limit, got {detained_limit}" - ); -} - -// ============================================================================ -// TEST 1b: CALL to beneficiary where child reverts — detention persists -// ============================================================================ - -/// The tracker is marked during CALL setup (before child execution), so even if -/// the child frame reverts, the detained limit must remain in effect for the parent. -#[test] -fn test_call_to_beneficiary_child_reverts_detention_persists() { - // Beneficiary contract: immediately reverts. - let beneficiary_code = BytecodeBuilder::default().append(REVERT).build(); - // Callee: CALL beneficiary (will revert), POP result, then query remaining gas. - let callee_code = append_call(BytecodeBuilder::default(), BENEFICIARY, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success(), "Parent should succeed despite child revert"); - assert!( - remaining <= DETENTION_CAP, - "After reverted CALL to beneficiary, detention should persist, remaining={remaining}" - ); - assert!( - detained_limit < 200_000_000, - "Detained limit should be active after child revert, got {detained_limit}" - ); -} - -// ============================================================================ -// TEST 2: STATICCALL to beneficiary triggers detention -// ============================================================================ - -#[test] -fn test_staticcall_to_beneficiary_triggers_detention() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let callee_code = - append_staticcall(BytecodeBuilder::default(), BENEFICIARY, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, _) = transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "After STATICCALL to beneficiary, remaining should be ≤ {DETENTION_CAP}, got {remaining}" - ); -} - -// ============================================================================ -// TEST 3: DELEGATECALL to beneficiary triggers detention -// ============================================================================ - -#[test] -fn test_delegatecall_to_beneficiary_triggers_detention() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let callee_code = - append_delegatecall(BytecodeBuilder::default(), BENEFICIARY, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, _) = transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "After DELEGATECALL to beneficiary, remaining should be ≤ {DETENTION_CAP}, got {remaining}" - ); -} - -// ============================================================================ -// TEST 4: CALLCODE to beneficiary triggers detention -// ============================================================================ - -#[test] -fn test_callcode_to_beneficiary_triggers_detention() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let callee_code = append_callcode(BytecodeBuilder::default(), BENEFICIARY, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, _) = transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "After CALLCODE to beneficiary, remaining should be ≤ {DETENTION_CAP}, got {remaining}" - ); -} - -// ============================================================================ -// TEST 5: Caller is beneficiary — eager detention from TX start -// ============================================================================ - -/// When the TX sender is the beneficiary, detention should be active from the start. -/// No volatile opcode is needed; `on_new_tx` handles it eagerly. -#[test] -fn test_caller_is_beneficiary_eager_detention() { - // Callee: query remaining compute gas immediately (no volatile opcodes). - let callee_code = query_remaining_compute_gas(BytecodeBuilder::default()).build(); - - let mut db = MemoryDatabase::default() - .account_balance(BENEFICIARY, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - // TX sender = BENEFICIARY - let tx = TxEnvBuilder::default() - .caller(BENEFICIARY) - .call(CALLEE) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "Caller=beneficiary: remaining should be ≤ {DETENTION_CAP} from start, got {remaining}" - ); - assert!( - detained_limit < 200_000_000, - "Caller=beneficiary: detained limit should be active, got {detained_limit}" - ); -} - -// ============================================================================ -// TEST 5b: Caller is beneficiary — pre-REX4 no eager detention -// ============================================================================ - -// ============================================================================ -// TEST 6: Recipient is beneficiary — eager detention from TX start -// ============================================================================ - -/// When the TX recipient is the beneficiary, detention should be active from the start. -#[test] -fn test_recipient_is_beneficiary_eager_detention() { - // BENEFICIARY itself is the callee. Its code queries remaining compute gas. - let beneficiary_code = query_remaining_compute_gas(BytecodeBuilder::default()).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(BENEFICIARY, beneficiary_code); - - // TX recipient = BENEFICIARY - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "Recipient=beneficiary: remaining should be ≤ {DETENTION_CAP} from start, got {remaining}" - ); - assert!( - detained_limit < 200_000_000, - "Recipient=beneficiary: detained limit should be active, got {detained_limit}" - ); -} - -// ============================================================================ -// TEST 6b: Recipient is beneficiary — pre-REX4 no eager detention -// ============================================================================ - -// ============================================================================ -// TEST 7: SELFBALANCE in beneficiary contract triggers detention (integration) -// ============================================================================ - -/// Integration test: CALL to beneficiary whose code executes SELFBALANCE. -/// -/// NOTE: The outer CALL to the beneficiary already triggers detention through -/// `wrap_call_volatile_check`, so this test does not isolate the SELFBALANCE -/// wrapper. It verifies that the combination works correctly. -/// See `test_selfbalance_in_non_beneficiary_no_detention` for address sensitivity. -#[test] -fn test_selfbalance_in_beneficiary_triggers_detention() { - // Beneficiary contract: SELFBALANCE, POP, then query remaining compute gas. - let beneficiary_code = BytecodeBuilder::default().append(SELFBALANCE).append(POP); - let beneficiary_code = query_remaining_compute_gas(beneficiary_code).build(); - - // Callee: CALL beneficiary, capture return data, RETURN it. - let callee_code = BytecodeBuilder::default() - .push_number(32_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(BENEFICIARY) - .push_number(500_000_u64) // gas - .append(CALL) - .append(POP) - // Copy return data - .append(RETURNDATASIZE) // size - .push_number(0_u64) // srcOffset - .push_number(0_u64) // destOffset - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .push_number(0_u64) - .append(RETURN); - let callee_code = callee_code.build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining <= DETENTION_CAP, - "SELFBALANCE in beneficiary: remaining should be ≤ {DETENTION_CAP}, got {remaining}" - ); - assert!( - detained_limit < 200_000_000, - "SELFBALANCE in beneficiary: detained limit should be active, got {detained_limit}" - ); -} - -// ============================================================================ -// TEST 8: CALL to non-beneficiary does NOT trigger detention -// ============================================================================ - -/// Sanity check: CALL to a non-beneficiary address should not trigger gas detention. -#[test] -fn test_call_to_non_beneficiary_no_detention() { - let target = address!("0000000000000000000000000000000000400002"); - let target_code = BytecodeBuilder::default().stop().build(); - let callee_code = append_call(BytecodeBuilder::default(), target, 10_000).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(target, target_code); - - let tx = default_tx(CALLEE); - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining > DETENTION_CAP, - "CALL to non-beneficiary should NOT trigger detention, remaining={remaining}" - ); - assert_eq!( - detained_limit, 200_000_000, - "Detained limit should remain at TX limit when no volatile access" - ); -} - -// ============================================================================ -// TEST 9: SELFBALANCE in non-beneficiary contract does NOT trigger detention -// ============================================================================ - -/// Proves that the SELFBALANCE volatile wrapper is address-sensitive: -/// SELFBALANCE at a non-beneficiary address must not trigger gas detention. -/// Combined with test 7 (which shows detention IS triggered when the beneficiary -/// executes SELFBALANCE), this pair confirms the wrapper's address check. -#[test] -fn test_selfbalance_in_non_beneficiary_no_detention() { - // CALLEE (not the beneficiary) executes SELFBALANCE, then queries remaining gas. - let callee_code = BytecodeBuilder::default().append(SELFBALANCE).append(POP); - let callee_code = query_remaining_compute_gas(callee_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - let tx = default_tx(CALLEE); - let (result, detained_limit) = - transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - let remaining = decode_remaining(&result); - - assert!(result.result.is_success()); - assert!( - remaining > DETENTION_CAP, - "SELFBALANCE in non-beneficiary should NOT trigger detention, remaining={remaining}" - ); - assert_eq!( - detained_limit, 200_000_000, - "Detained limit should remain at TX limit when SELFBALANCE is at non-beneficiary" - ); -} - -// ============================================================================ -// TEST 10: disableVolatileDataAccess + SELFBALANCE at beneficiary reverts -// ============================================================================ - -/// When volatile data access is disabled, SELFBALANCE at the beneficiary address -/// must revert. This tests the revert branch of `volatile_data_ext::selfbalance`. -/// -/// Approach: TX sends to BENEFICIARY directly (so code runs at beneficiary address). -/// The beneficiary code disables volatile access, then executes SELFBALANCE. -/// SELFBALANCE should revert the frame because the wrapper detects target == beneficiary -/// with volatile access disabled. -#[test] -fn test_selfbalance_at_beneficiary_reverts_when_volatile_disabled() { - let disable_selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - - // Beneficiary code: - // 1. disableVolatileDataAccess() - // 2. SELFBALANCE (should revert because volatile access is disabled) - // 3. STOP (unreachable if SELFBALANCE reverts the frame) - let beneficiary_code = BytecodeBuilder::default() - .mstore(0x0, disable_selector) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) - .append(CALL) - .append(POP) - // SELFBALANCE — should revert the frame - .append(SELFBALANCE) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(BENEFICIARY, beneficiary_code); - - // TX directly to BENEFICIARY so code executes at beneficiary address. - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(1_000_000_000) - .build_fill(); - - let (result, _) = transact(&mut db, BENEFICIARY, 200_000_000, DETENTION_CAP, tx).unwrap(); - - // The frame should revert because SELFBALANCE at beneficiary is blocked. - assert!( - matches!(result.result, revm::context::result::ExecutionResult::Revert { .. }), - "SELFBALANCE at beneficiary with volatile access disabled should revert, got {:?}", - result.result - ); -} - -// ============================================================================ -// TEST 11: Detention + intrinsic DataSize overflow interaction -// ============================================================================ - -/// Cross-concern test: when both gas detention (via beneficiary sender) and -/// intrinsic `DataSize` overflow are active, the TX must still fail with the -/// correct halt reason (`DataLimitExceeded`), not succeed or produce a -/// gas rescue that incorrectly reflects the detained cap. -#[test] -fn test_detention_plus_intrinsic_data_size_overflow() { - // Set data size limit to something too small for even intrinsic data. - // Also configure beneficiary detention by making CALLER == BENEFICIARY. - let data_limit = 100_u64; // Less than BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE (~150) - - let callee_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(BENEFICIARY, U256::from(1_000_000)) - .account_code(CALLEE, callee_code); - - // TX sender = BENEFICIARY → triggers eager detention in on_new_tx. - let tx = TxEnvBuilder::default() - .caller(BENEFICIARY) - .call(CALLEE) - .gas_limit(1_000_000_000) - .build_fill(); - - let block = revm::context::BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX4).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(200_000_000) - .with_block_env_access_compute_gas_limit(DETENTION_CAP) - .with_tx_data_size_limit(data_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Must halt with DataLimitExceeded despite detention being active. - assert!( - result.result.is_halt(), - "Detention + intrinsic DataSize overflow should halt, got {:?}", - result.result - ); - assert!( - matches!( - result.result, - revm::context::result::ExecutionResult::Halt { - reason: MegaHaltReason::DataLimitExceeded { .. }, - .. - } - ), - "Should halt with DataLimitExceeded, got {:?}", - result.result - ); - - // Gas rescue should have returned most gas since no execution happened. - let gas_remaining = 1_000_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 900_000_000, - "Expected >900M gas remaining from rescue (not inflated by detention), got {gas_remaining}" - ); -} - -// ============================================================================ -// TEST 12: Detention + execution data limit — detained compute gas does not -// interfere with data size enforcement -// ============================================================================ - -/// When detention caps compute gas, data size enforcement must still function -/// independently. This tests that a TX under the detained compute gas cap -/// can still fail on data size limits. -#[test] -fn test_detention_does_not_interfere_with_data_size_limit() { - // Set up: beneficiary detention active, compute gas limit generous, - // but data size limit tight. Callee CALLs beneficiary to trigger detention, - // then writes SSTOREs that exceed data limit. - let data_limit = 200_u64; // ~intrinsic(150) + 1 SSTORE(40) = 190, fits 1, not 2. - - // Callee: CALL beneficiary (triggers detention), then do SSTOREs that exceed data limit. - let callee_code = BytecodeBuilder::default() - // CALL beneficiary to trigger detention - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(BENEFICIARY) - .push_number(10_000_u64) - .append(CALL) - .append(POP) - // Now do SSTOREs that exceed data limit - .sstore(U256::from(0), U256::from(1)) - .sstore(U256::from(1), U256::from(2)) - .stop() - .build(); - - let beneficiary_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, callee_code) - .account_code(BENEFICIARY, beneficiary_code); - - let tx = default_tx(CALLEE); - - let block = revm::context::BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX4).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(200_000_000) - .with_block_env_access_compute_gas_limit(DETENTION_CAP) - .with_tx_data_size_limit(data_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - // Detained compute gas cap is active, but the TX should fail on data size. - assert!( - !result.result.is_success(), - "Detention active but data size exceeded should not succeed, got {:?}", - result.result - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/create_safety.rs b/crates/mega-evm/tests/_pending/rex4/create_safety.rs deleted file mode 100644 index 363729117..000000000 --- a/crates/mega-evm/tests/_pending/rex4/create_safety.rs +++ /dev/null @@ -1,150 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! Regression tests for CREATE2 wrapper safety and compute-gas accounting. -//! -//! 1. CREATE2 with an out-of-bounds initcode slice must never trigger an interpreter panic. The -//! wrapper expands memory before reading the initcode slice; if memory expansion OOGs, the -//! canonical reject path runs without ever calling `slice_len` on unallocated memory. -//! 2. The expansion gas consumed by the wrapper's `resize_memory!` must be recorded into the -//! compute gas tracker. Otherwise the per-tx compute gas limit is undercounted by the initcode -//! memory-expansion cost, since the canonical CREATE2 path's own `resize_memory!` becomes a -//! no-op once memory is already sized. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ExecutionResult, TxEnv}, - handler::EvmTr, - state::{AccountInfo, Bytecode}, -}; - -const CALLER: Address = address!("1111111111111111111111111111111111111111"); -const CONTRACT_WITH_BAD_CREATE2: Address = address!("2222222222222222222222222222222222222222"); - -/// Runtime that performs CREATE2 with a length large enough to OOG the -/// canonical `resize_memory!` under a tight per-call gas budget, but -/// still under `MAX_INITCODE_SIZE` so the size check passes first. -/// -/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. -fn memory_oog_create2_runtime() -> Bytes { - BytecodeBuilder::default() - .push_number(0u8) // salt - .push_number(500_000u32) // length — large enough to OOG memory expansion - .push_number(0u8) // offset - .push_number(0u8) // value - .append(CREATE2) - .append(STOP) - .build() -} - -#[test] -fn test_create2_with_oversize_initcode_len_does_not_panic() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - let runtime = memory_oog_create2_runtime(); - let bytecode = Bytecode::new_raw(runtime); - db.insert_account_info( - CONTRACT_WITH_BAD_CREATE2, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - - let envs = TestExternalEnvs::::new(); - let limits = EvmTxRuntimeLimits::no_limits(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT_WITH_BAD_CREATE2), - gas_limit: 200_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - let res = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not surface EVMError"); - - assert!( - matches!( - res.result, - ExecutionResult::Success { .. } | - ExecutionResult::Halt { .. } | - ExecutionResult::Revert { .. } - ), - "got: {:?}", - res.result - ); -} - -const COMPUTE_GAS_TEST_CONTRACT: Address = address!("3333333333333333333333333333333333333333"); - -/// Build runtime bytecode that issues a single CREATE2 over a memory window of -/// `initcode_len` bytes starting at offset 0, then STOPs. The initcode memory is left -/// zero-initialized; CREATE2 will deploy an empty contract, which is fine for measuring -/// gas accounting (we only care that the wrapper ran and metered the memory expansion). -/// -/// Stack at CREATE2 (top → bottom): [value, offset, length, salt]. -fn create2_bytecode(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(initcode_len) // length - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// EVM memory expansion gas: `3*words + words*words/512`. -fn memory_expansion_gas(len: u64) -> u64 { - let words = len.div_ceil(32); - 3 * words + words * words / 512 -} - -/// Run a single CREATE2 transaction at the REX4 spec and return the recorded compute gas. -fn run_create2_and_get_compute_gas( - initcode_len: u64, - gas_limit: u64, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default(); - db.set_account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)); - let bytecode = Bytecode::new_raw(create2_bytecode(initcode_len)); - db.insert_account_info( - COMPUTE_GAS_TEST_CONTRACT, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - - let envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4) - .with_external_envs(envs.into()) - .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx_env = TxEnv { - caller: CALLER, - kind: TxKind::Call(COMPUTE_GAS_TEST_CONTRACT), - gas_limit, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx_env); - tx.enveloped_tx = Some(Bytes::new()); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact should not fail"); - let compute_gas = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (res.result, compute_gas) -} diff --git a/crates/mega-evm/tests/_pending/rex4/deployment.rs b/crates/mega-evm/tests/_pending/rex4/deployment.rs deleted file mode 100644 index de45f65ff..000000000 --- a/crates/mega-evm/tests/_pending/rex4/deployment.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! Tests for Rex4 system contract deployment wiring. - -use alloy_evm::{block::BlockExecutor, Database, Evm, EvmEnv, EvmFactory}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{Address, Bytes, B256}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, - MegaBlockExecutor, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, - ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, ACCESS_CONTROL_CODE_HASH, LIMIT_CONTROL_ADDRESS, - LIMIT_CONTROL_CODE, LIMIT_CONTROL_CODE_HASH, -}; -use revm::{ - context::BlockEnv, - database::State, - inspector::NoOpInspector, - primitives::{KECCAK_EMPTY, U256}, -}; - -type TestState<'db> = State<&'db mut MemoryDatabase>; -type TestEvm<'a, 'db> = MegaEvm<&'a mut TestState<'db>, NoOpInspector, EmptyExternalEnv>; -type TestExecutor<'a, 'db> = - MegaBlockExecutor, OpAlloyReceiptBuilder>; - -// Complete ladders topping out at the target fork. Expressing these as -// `with_all_activated().without(Rex5)` instead would leave Rex6 activated, and pre-block setup -// gates compare rung positions — which would still report REX6 and open every lower gate. -fn rex4_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX4) -} - -fn rex3_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default().with_all_activated_through(MegaSpecId::REX3) -} - -fn make_block_env(timestamp: u64) -> BlockEnv { - BlockEnv { - number: U256::from(1_u64), - timestamp: U256::from(timestamp), - gas_limit: 30_000_000, - ..Default::default() - } -} - -fn with_executor( - spec: MegaSpecId, - hardforks: MegaHardforkConfig, - f: impl for<'a, 'db> FnOnce(&mut TestExecutor<'a, 'db>) -> R, -) -> R { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let evm_env = EvmEnv::new(cfg_env, make_block_env(0)); - - let evm_factory = MegaEvmFactory::new(); - let evm = evm_factory.create_evm(&mut state, evm_env); - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Default::default(), - BlockLimits::no_limits(), - ); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let mut executor = MegaBlockExecutor::new(evm, block_ctx, hardforks, receipt_builder); - - f(&mut executor) -} - -fn assert_contract_deployed( - db: &mut State, - address: Address, - expected_code_hash: B256, - expected_code: Bytes, - name: &str, -) { - let cache_acc = db.load_cache_account(address).expect("should load cache account"); - let acc_info = cache_acc.account_info().expect("system contract account should exist"); - - assert_eq!( - acc_info.code_hash, expected_code_hash, - "{name} code hash should match expected bytecode" - ); - assert!(acc_info.code.is_some(), "{name} code should be set"); - let deployed_code = acc_info.code.as_ref().expect("code should be present"); - assert_eq!( - deployed_code.original_bytes(), - expected_code, - "{name} bytecode should match the embedded system contract code" - ); -} - -fn assert_contract_not_deployed(db: &mut State, address: Address, name: &str) { - let cache_acc = db.load_cache_account(address).expect("should load cache account"); - let code_hash = cache_acc.account_info().map_or(KECCAK_EMPTY, |info| info.code_hash); - assert_eq!(code_hash, KECCAK_EMPTY, "{name} should not have deployed code for this spec"); -} - -#[test] -fn test_rex4_system_contracts_deployed_on_activation() { - with_executor(MegaSpecId::REX4, rex4_chain_spec(), |executor| { - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let db_ref = executor.evm_mut().db_mut(); - assert_contract_deployed( - db_ref, - ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE_HASH, - ACCESS_CONTROL_CODE, - "MegaAccessControl", - ); - assert_contract_deployed( - db_ref, - LIMIT_CONTROL_ADDRESS, - LIMIT_CONTROL_CODE_HASH, - LIMIT_CONTROL_CODE, - "MegaLimitControl", - ); - }); -} - -#[test] -fn test_rex4_system_contract_deployment_is_idempotent() { - with_executor(MegaSpecId::REX4, rex4_chain_spec(), |executor| { - executor.apply_pre_execution_changes().expect("first pre-execution changes should succeed"); - - { - let db_ref = executor.evm_mut().db_mut(); - assert_contract_deployed( - db_ref, - ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE_HASH, - ACCESS_CONTROL_CODE, - "MegaAccessControl", - ); - assert_contract_deployed( - db_ref, - LIMIT_CONTROL_ADDRESS, - LIMIT_CONTROL_CODE_HASH, - LIMIT_CONTROL_CODE, - "MegaLimitControl", - ); - } - - executor - .apply_pre_execution_changes() - .expect("second pre-execution changes should also succeed"); - - let db_ref = executor.evm_mut().db_mut(); - assert_contract_deployed( - db_ref, - ACCESS_CONTROL_ADDRESS, - ACCESS_CONTROL_CODE_HASH, - ACCESS_CONTROL_CODE, - "MegaAccessControl after second apply", - ); - assert_contract_deployed( - db_ref, - LIMIT_CONTROL_ADDRESS, - LIMIT_CONTROL_CODE_HASH, - LIMIT_CONTROL_CODE, - "MegaLimitControl after second apply", - ); - }); -} diff --git a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs b/crates/mega-evm/tests/_pending/rex4/frame_limits.rs deleted file mode 100644 index 83bdcc404..000000000 --- a/crates/mega-evm/tests/_pending/rex4/frame_limits.rs +++ /dev/null @@ -1,707 +0,0 @@ -//! Tests for Rex4 per-frame limits on `DataSize`, `KVUpdate`, and `ComputeGas`. -//! -//! Rex4 extends per-frame budgets to all four resource dimensions (`DataSize`, `KVUpdate`, -//! `ComputeGas`, and `StateGrowth` — the last already tested in `frame_state_growth.rs`). -//! -//! Each inner call frame receives `remaining * 98 / 100` of the parent's remaining budget. -//! When a frame exceeds its per-frame budget, it reverts (not halts) with ABI-encoded -//! `MegaLimitExceeded(uint8 kind, uint64 limit)` revert data. -//! -//! Behavior differences from `StateGrowth`: -//! - **`DataSize` / `KVUpdate`**: The reverted child's discardable usage is dropped, protecting the -//! parent's budget (same semantics as `StateGrowth`). -//! - **`ComputeGas`**: Gas is always persistent — even after a child frame reverts due to exceeding -//! its per-frame compute gas budget, the parent's total compute gas still increases by the -//! child's actual gas used. Per-frame limits act as "early termination guardrails", not budget -//! protection. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolError; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaSpecId, - MegaTransaction, MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, - STORAGE_SLOT_WRITE_SIZE, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - DatabaseCommit, DatabaseRef, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction with specified data size and KV update limits (compute gas unlimited). -fn transact_data_kv( - spec: MegaSpecId, - db: &mut MemoryDatabase, - data_limit: u64, - kv_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(data_limit) - .with_tx_kv_updates_limit(kv_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let usage = ctx.additional_limit.borrow().get_usage(); - Ok((r, usage.data_size, usage.kv_updates)) -} - -/// Executes a transaction with specified compute gas limit only (data/kv unlimited). -fn transact_compute( - spec: MegaSpecId, - db: &mut MemoryDatabase, - compute_gas_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64), EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(compute_gas_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let compute_gas = ctx.additional_limit.borrow().get_usage().compute_gas; - Ok((r, compute_gas)) -} - -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -/// Builds bytecode that writes `n` distinct storage slots to non-zero values. -fn write_n_slots(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - builder -} - -/// Appends a CALL to `target` with the given gas amount. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Appends a CALL that captures the revert data and RETURNs it. -fn append_call_and_return_revert_data( - builder: BytecodeBuilder, - target: Address, - gas: u64, -) -> BytecodeBuilder { - append_call(builder, target, gas) - .append(POP) // discard CALL success flag - .append(RETURNDATASIZE) - .push_number(0_u64) - .push_number(0_u64) - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) - .push_number(0_u64) - .append(RETURN) -} - -// ============================================================================ -// DATA SIZE PER-FRAME LIMITS -// ============================================================================ - -/// Each SSTORE that writes a new slot costs `STORAGE_SLOT_WRITE_SIZE` (40) bytes of data size. -/// This helper computes n SSTORE intrinsic data cost. -fn n_sstore_data(n: u64) -> u64 { - n * STORAGE_SLOT_WRITE_SIZE -} - -fn tx_intrinsic_data_size() -> u64 { - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE -} - -#[test] -fn test_data_size_child_gets_98_percent_budget() { - // TX data limit must account for intrinsic usage. The first frame budget is - // tx_limit - intrinsic; child budget = (tx_limit - intrinsic) * 98/100. - // With intrinsic + n_sstore_data(100), the first frame gets n_sstore_data(100), - // and child gets n_sstore_data(98). Child writes 98 slots → succeeds. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - // intrinsic tx data + child's 98 slots - assert_eq!( - data_size, - tx_intrinsic_data_size() + n_sstore_data(98), - "Child should succeed within 98% budget" - ); -} - -#[test] -fn test_data_size_child_exceeds_budget_frame_local_revert() { - // Child budget = n_sstore_data(98), child writes 99 slots → exceeds → frame-local Revert. - // Parent succeeds, child's discardable data is dropped. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child frame-local revert"); - assert_eq!(data_size, tx_intrinsic_data_size(), "Child's discardable data dropped on revert"); -} - -#[test] -fn test_data_size_child_exceed_reverts_not_halts() { - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "TX should succeed, not halt"); - assert!(!result.result.is_halt()); -} - -#[test] -fn test_data_size_parent_budget_protected_after_child_revert() { - // Child exceeds budget (data dropped), parent then writes own slots successfully. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .append(POP) - .sstore(U256::from(0), U256::from(42)) // parent writes after child revert - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - data_size, - tx_intrinsic_data_size() + n_sstore_data(1), - "Only parent's 1 slot should persist" - ); - - db.commit(result.state); - let parent_val = db.storage_ref(CALLEE, U256::from(0)).unwrap(); - assert_eq!(parent_val, U256::from(42), "Parent storage should persist"); - let child_val = db.storage_ref(CONTRACT, U256::from(0)).unwrap(); - assert_eq!(child_val, U256::ZERO, "Child storage should be reverted"); -} - -#[test] -fn test_data_size_revert_data_encodes_mega_limit_exceeded() { - // kind=0 (DataSize), limit=frame_budget - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 0, "kind should be 0 (DataSize)"); - // child budget = (limit - intrinsic) * 98/100 = n_sstore_data(100) * 98/100 - assert_eq!( - decoded.limit, - n_sstore_data(100) * 98 / 100, - "limit should be child's per-frame budget" - ); -} - -#[test] -fn test_data_size_top_level_exceed_is_frame_local_revert() { - // Top-level frame exceeds its own frame budget in Rex4: should Revert, not Halt. - let limit = n_sstore_data(100); - let code = write_n_slots(BytecodeBuilder::default(), 101).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(matches!(result.result, ExecutionResult::Revert { .. })); - assert!(!result.result.is_halt()); - assert_eq!(data_size, tx_intrinsic_data_size(), "Top-level discardable data should be dropped"); -} - -#[test] -fn test_data_size_child_budget_accounts_for_parent_usage() { - // TX data limit = intrinsic + 100 slots. - // First frame budget = n_sstore_data(100). Parent writes 20 slots, remaining = 80 slots. - // Child budget = 80 * 98/100 = 78 slots. Child writes 78 slots → succeeds. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 78).stop().build(); - let parent_code = write_n_slots(BytecodeBuilder::default(), 20); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - data_size, - tx_intrinsic_data_size() + n_sstore_data(20 + 78), - "Child budget should be computed from parent's remaining budget" - ); -} - -#[test] -fn test_data_size_child_exceeds_budget_after_parent_usage() { - // TX data limit = intrinsic + 100 slots. - // First frame budget = n_sstore_data(100). Parent writes 20 slots, remaining = 80 slots. - // Child budget = 80 * 98/100 = 78 slots. Child writes 79 → exceeds and reverts. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_code = write_n_slots(BytecodeBuilder::default(), 79).stop().build(); - let parent_code = write_n_slots(BytecodeBuilder::default(), 20); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!( - data_size, - tx_intrinsic_data_size() + n_sstore_data(20), - "Exceeded child frame should be discarded; parent usage should remain" - ); -} - -#[test] -fn test_data_size_grandchild_budget_progressive_reduction() { - // TX limit = intrinsic + n_sstore_data(100). - // First frame = n_sstore_data(100). Child = 100*98/100 = 98 slots. - // Grandchild = 98*98/100 = 96 slots. - // Grandchild writes 96 slots → succeeds. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 96).stop().build(); - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 50_000_000).append(POP).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(96)); -} - -#[test] -fn test_data_size_grandchild_exceeds_progressive_budget() { - // TX limit = intrinsic + n_sstore_data(100). - // First frame = n_sstore_data(100). Child = 98 slots. Grandchild = 96 slots. - // Grandchild writes 97 slots → exceeds and reverts. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 97).stop().build(); - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 50_000_000).append(POP).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(data_size, tx_intrinsic_data_size()); -} - -#[test] -fn test_data_size_child_exceed_followed_by_sibling_success() { - // Child A exceeds and reverts, Child B should still get fresh budget and succeed. - let limit = tx_intrinsic_data_size() + n_sstore_data(100); - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .append(POP) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(CONTRACT2) - .push_number(50_000_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(data_size, tx_intrinsic_data_size() + n_sstore_data(98)); -} - -// ============================================================================ -// KV UPDATE PER-FRAME LIMITS -// ============================================================================ - -#[test] -fn test_kv_update_child_gets_98_percent_budget() { - // TX KV limit = 101 (1 intrinsic + 100 execution budget). - // First frame budget = 100. Child budget = 100 * 98/100 = 98. - // Child writes 98 slots → succeeds. - let child_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - // 1 (caller nonce from before_tx_start) + 98 sstores - assert_eq!(kv_updates, 1 + 98, "Caller (1) + child's 98 sstores"); -} - -#[test] -fn test_kv_update_child_exceeds_budget_frame_local_revert() { - // TX KV limit = 101 (1 intrinsic + 100 execution budget). - // Child budget = 98. Child writes 99 slots → exceeds → Revert. Parent succeeds. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child frame-local revert"); - // Only the persistent caller nonce update remains; child's discardable ops dropped. - assert_eq!(kv_updates, 1, "Only caller nonce KV update persists"); -} - -#[test] -fn test_kv_update_revert_data_encodes_mega_limit_exceeded() { - // kind=1 (KVUpdate), limit=child's frame budget - let kv_limit = 101_u64; - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let parent_code = - append_call_and_return_revert_data(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, kv_limit, tx).unwrap(); - - assert!(result.result.is_success()); - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("Expected success"), - }; - - let decoded = MegaLimitExceeded::abi_decode(&output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 1, "kind should be 1 (KVUpdate)"); - // child budget = (kv_limit - 1 intrinsic) * 98/100 = 100 * 98/100 = 98 - assert_eq!( - decoded.limit, - (kv_limit - 1) * 98 / 100, - "limit should be child's per-frame budget" - ); -} - -#[test] -fn test_kv_update_top_level_exceed_is_frame_local_revert() { - // Top-level frame exceeds in Rex4: should Revert, not Halt. - let code = write_n_slots(BytecodeBuilder::default(), 101).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 100, tx).unwrap(); - - assert!(matches!(result.result, ExecutionResult::Revert { .. })); - assert!(!result.result.is_halt()); - assert_eq!(kv_updates, 1, "Top-level discardable KV updates should be dropped"); -} - -#[test] -fn test_kv_update_child_budget_accounts_for_parent_usage() { - // TX KV limit = 101 (1 intrinsic + 100 execution budget). - // First frame = 100. Parent writes 20, remaining = 80. Child budget = 78. - // Child writes 78 → succeeds. - let child_code = write_n_slots(BytecodeBuilder::default(), 78).stop().build(); - let parent_code = write_n_slots(BytecodeBuilder::default(), 20); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(kv_updates, 1 + 20 + 78); -} - -#[test] -fn test_kv_update_child_exceeds_budget_after_parent_usage() { - // TX KV limit = 101 (1 intrinsic + 100 execution budget). - // First frame = 100. Parent writes 20, remaining = 80. Child budget = 78. - // Child writes 79 → exceeds and reverts. - let child_code = write_n_slots(BytecodeBuilder::default(), 79).stop().build(); - let parent_code = write_n_slots(BytecodeBuilder::default(), 20); - let parent_code = append_call(parent_code, CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(kv_updates, 1 + 20); -} - -#[test] -fn test_kv_update_grandchild_budget_progressive_reduction() { - // TX limit = 101 (1 intrinsic + 100 execution). - // First frame = 100. Child = 98. Grandchild = 96. - // Grandchild writes 96 → succeeds. - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 96).stop().build(); - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 50_000_000).append(POP).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(kv_updates, 1 + 96); -} - -#[test] -fn test_kv_update_grandchild_exceeds_progressive_budget() { - // TX limit = 101 (1 intrinsic + 100 execution). - // First frame = 100. Child = 98. Grandchild = 96. - // Grandchild writes 97 → exceeds and reverts. - let grandchild_code = write_n_slots(BytecodeBuilder::default(), 97).stop().build(); - let child_code = - append_call(BytecodeBuilder::default(), CONTRACT2, 50_000_000).append(POP).stop().build(); - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code) - .account_code(CONTRACT2, grandchild_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(kv_updates, 1); -} - -#[test] -fn test_kv_update_child_exceed_followed_by_sibling_success() { - // Child A exceeds and reverts, Child B should still get fresh budget and succeed. - let child_a_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - let child_b_code = write_n_slots(BytecodeBuilder::default(), 98).stop().build(); - let parent_code = append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000) - .append(POP) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(CONTRACT2) - .push_number(50_000_000_u64) - .append(CALL) - .append(POP) - .stop() - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_a_code) - .account_code(CONTRACT2, child_b_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = - transact_data_kv(MegaSpecId::REX4, &mut db, u64::MAX, 101, tx).unwrap(); - - assert!(result.result.is_success()); - assert_eq!(kv_updates, 1 + 98); -} - -// ============================================================================ -// COMPUTE GAS PER-FRAME LIMITS -// ============================================================================ -// -// Note: -// Unlike `DataSize` / `KVUpdate`, reverted compute gas remains persistent. -// But in Rex4 the top-level compute frame still uses the remaining TX budget after intrinsic -// charges, so top-level compute-budget exhaustion is also surfaced as frame-local `Revert`. - -/// Burns approximately `target_gas` of compute gas via repeated PUSH1/POP sequences. -/// Each PUSH1+POP pair costs 3+2=5 gas. -/// Returns raw bytecode as `Bytes`. -fn burn_gas_code(target_gas: u64) -> Bytes { - let iterations = target_gas / 5; - let mut code = Vec::new(); - for _ in 0..iterations { - code.push(PUSH1); - code.push(0x00); - code.push(POP); - } - code.push(STOP); - Bytes::from(code) -} diff --git a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs b/crates/mega-evm/tests/_pending/rex4/gas_detention.rs deleted file mode 100644 index 463179592..000000000 --- a/crates/mega-evm/tests/_pending/rex4/gas_detention.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! Tests for Rex4 relative gas detention cap. -//! -//! Rex4 changes gas detention (volatile data compute gas limiting) from an **absolute** cap to a -//! **relative** cap. The effective limit becomes `current_usage + cap` at the point of access, -//! rather than just `cap`. -//! -//! This means a transaction that has already used >20M compute gas before accessing TIMESTAMP -//! will not halt immediately — instead it gets 20M more compute gas after the access. -//! -//! Key properties tested: -//! 1. REX4: Volatile access after heavy compute succeeds (relative cap allows more gas) -//! 2. REX4: Post-access cap is still enforced (can't use unlimited gas after access) -//! 3. REX4: Pre-access usage is not counted against the cap -//! 4. REX4: ordinary compute-budget enforcement still wins when detention is not more restrictive -//! 5. REX4: Multiple volatile accesses — first access anchors the cap -//! 6. Pre-REX4: Absolute cap behavior is preserved (backward compatibility) - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolError; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaSpecId, - MegaTransaction, MegaTransactionError, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000300000"); -const CALLEE: Address = address!("0000000000000000000000000000000000300001"); - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// The gas detention cap for block env access (20M). -const BLOCK_ENV_CAP: u64 = 20_000_000; - -/// Appends approximately `target_gas` worth of compute gas burn via repeated PUSH1/POP sequences. -/// Each PUSH1+POP pair costs 3+2=5 gas. -fn append_burn_gas(mut builder: BytecodeBuilder, target_gas: u64) -> BytecodeBuilder { - let iterations = target_gas / 5; - for _ in 0..iterations { - builder = builder.push_number(0_u8).append(POP); - } - builder -} - -/// Executes a transaction with the given spec and compute gas / detention limits. -fn transact_with_spec( - spec: MegaSpecId, - db: &mut MemoryDatabase, - compute_gas_limit: u64, - block_env_access_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(compute_gas_limit) - .with_block_env_access_compute_gas_limit(block_env_access_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let additional_limit = ctx.additional_limit.borrow(); - let compute_gas = additional_limit.get_usage().compute_gas; - let detained_limit = additional_limit.detained_compute_gas_limit(); - Ok((r, compute_gas, detained_limit)) -} - -fn default_tx() -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(CALLEE).gas_limit(1_000_000_000).build_fill() -} - -/// Checks if the result is a volatile data access out of gas error. -fn is_volatile_data_access_oog(result: &ExecutionResult) -> bool { - matches!( - result, - &ExecutionResult::Halt { reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, .. } - ) -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// REX4: Transaction uses >20M compute gas before accessing TIMESTAMP, then does minimal work. -/// With relative cap, the effective limit becomes `usage_at_access` + 20M, so the TX succeeds. -/// Pre-REX4 would halt immediately because absolute 20M cap < actual usage. -#[test] -fn test_rex4_volatile_access_after_heavy_compute_succeeds() { - // Burn 25M compute gas, then access TIMESTAMP, then STOP. - // With relative cap: effective limit = 25M + 20M = 45M. Actual usage ~25M. Succeeds. - let builder = append_burn_gas(BytecodeBuilder::default(), 25_000_000); - let code = builder.append(TIMESTAMP).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::REX4, &mut db, 200_000_000, BLOCK_ENV_CAP, tx).unwrap(); - - assert!(result.result.is_success(), "Should succeed with relative cap: {compute_gas} used"); - // Detained limit should be anchored at ~25M + 20M = ~45M - assert!( - detained_limit > BLOCK_ENV_CAP, - "Detained limit should be > absolute 20M cap, got {detained_limit}" - ); -} - -/// REX4: Transaction accesses TIMESTAMP early, then tries to use >20M compute gas after. -/// The post-access cap (20M) should still be enforced. -#[test] -fn test_rex4_volatile_access_post_access_cap_enforced() { - // Access TIMESTAMP first (low usage), then try to burn 25M compute gas. - // Effective limit = ~0 + 20M = ~20M. Trying to burn 25M after -> halts. - let builder = BytecodeBuilder::default().append(TIMESTAMP).append(POP); - let builder = append_burn_gas(builder, 25_000_000); - let code = builder.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, _compute_gas, _detained_limit) = - transact_with_spec(MegaSpecId::REX4, &mut db, 200_000_000, BLOCK_ENV_CAP, tx).unwrap(); - - assert!( - is_volatile_data_access_oog(&result.result), - "Should halt with VolatileDataAccessOutOfGas when exceeding post-access cap" - ); -} - -/// REX4: Transaction uses X compute gas before TIMESTAMP, then uses <20M after. -/// Total usage is X + <20M which exceeds the old absolute 20M cap, but should succeed. -#[test] -fn test_rex4_pre_access_usage_not_counted_against_cap() { - // Burn 15M compute gas, then access TIMESTAMP, then burn 15M more. - // Total = ~30M > absolute 20M cap. But relative cap = 15M + 20M = 35M. Actual ~30M. Succeeds. - let builder = append_burn_gas(BytecodeBuilder::default(), 15_000_000); - let builder = builder.append(TIMESTAMP).append(POP); - let builder = append_burn_gas(builder, 15_000_000); - let code = builder.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::REX4, &mut db, 200_000_000, BLOCK_ENV_CAP, tx).unwrap(); - - assert!( - result.result.is_success(), - "Should succeed: pre-access usage not counted against cap. \ - Compute gas: {compute_gas}, detained limit: {detained_limit}" - ); - assert!( - compute_gas > BLOCK_ENV_CAP, - "Total compute gas ({compute_gas}) should exceed absolute 20M cap" - ); -} - -/// REX4: If `usage_at_access + cap` is greater than or equal to the TX compute gas limit, -/// detention is not the binding constraint. -/// Exceeding the ordinary compute budget should therefore resolve as a normal compute-limit -/// failure, not `VolatileDataAccessOutOfGas`. -#[test] -fn test_rex4_non_binding_detention_reports_normal_compute_limit() { - // Burn 10M compute gas, access TIMESTAMP, then burn 16M more. - // Relative detention computes ~10M + 20M = ~30M, but the TX limit is only 25M, so the - // effective detained limit is clamped to 25M and detention is not more restrictive. - let tx_compute_gas_limit = 25_000_000; - let builder = append_burn_gas(BytecodeBuilder::default(), 10_000_000); - let builder = builder.append(TIMESTAMP).append(POP); - let builder = append_burn_gas(builder, 16_000_000); - let code = builder.stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, _compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::REX4, &mut db, tx_compute_gas_limit, BLOCK_ENV_CAP, tx) - .unwrap(); - - let limit = match &result.result { - ExecutionResult::Revert { output, .. } => { - let decoded = - MegaLimitExceeded::abi_decode(output).expect("should decode MegaLimitExceeded"); - assert_eq!(decoded.kind, 2, "kind should be 2 (ComputeGas)"); - decoded.limit - } - _ => { - panic!( - "Expected normal compute-limit revert when detention is clamped by TX limit, got {:?}", - result.result - ) - } - }; - - assert_eq!( - detained_limit, tx_compute_gas_limit, - "Detained limit should be clamped to the TX compute gas limit when detention is not binding" - ); - assert!( - limit < tx_compute_gas_limit, - "Per-frame root budget should be smaller than the TX limit after intrinsic charges" - ); - assert!( - !is_volatile_data_access_oog(&result.result), - "Should resolve as normal compute-limit failure, not volatile-data OOG" - ); -} - -/// REX4: Multiple volatile accesses — first access anchors the cap. -/// TX accesses TIMESTAMP at usage=5M, then NUMBER at usage=10M. -/// Cap should be anchored at first access: 5M + 20M = 25M. -#[test] -fn test_rex4_multiple_volatile_accesses_first_wins() { - // Burn 5M, access TIMESTAMP, burn 5M more, access NUMBER, then STOP. - let builder = append_burn_gas(BytecodeBuilder::default(), 5_000_000); - let builder = builder.append(TIMESTAMP).append(POP); - let builder = append_burn_gas(builder, 5_000_000); - let code = builder.append(NUMBER).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx(); - let (result, _compute_gas, detained_limit) = - transact_with_spec(MegaSpecId::REX4, &mut db, 200_000_000, BLOCK_ENV_CAP, tx).unwrap(); - - assert!(result.result.is_success(), "Should succeed with both accesses within cap"); - // First access at ~5M: limit = 5M + 20M = 25M - // Second access at ~10M: limit = min(25M, 10M + 20M) = min(25M, 30M) = 25M - // First access wins. - assert!( - detained_limit < 30_000_000, - "Detained limit should be anchored at first access (~25M), got {detained_limit}" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs b/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs deleted file mode 100644 index b1c0bd78e..000000000 --- a/crates/mega-evm/tests/_pending/rex4/intrinsic_limit_bypass.rs +++ /dev/null @@ -1,602 +0,0 @@ -//! Regression tests for Finding 1: REX4 per-transaction resource limit bypass -//! via intrinsic usage inflation. -//! -//! Before the fix, `FrameLimitTracker::max_forward_limit()` returned `tx_entry.limit` -//! when the frame stack was empty, giving the first frame the full raw budget -//! instead of the remaining budget after intrinsic charges. This allowed a transaction -//! to exceed the configured limit while still succeeding. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaLimitControl, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, - LIMIT_CONTROL_ADDRESS, STORAGE_SLOT_WRITE_SIZE, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - ContextTr, TxEnv, - }, - handler::EvmTr, - inspector::Inspector, - interpreter::{interpreter_types::InterpreterTypes, CallInputs, CallOutcome, Gas}, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000100000"); -const CALLEE: Address = address!("0000000000000000000000000000000000100001"); -const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact_data_kv( - db: &mut MemoryDatabase, - data_limit: u64, - kv_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, MegaSpecId::REX4).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(data_limit) - .with_tx_kv_updates_limit(kv_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - - let ctx = evm.ctx_ref(); - let usage = ctx.additional_limit.borrow().get_usage(); - Ok((r, usage.data_size, usage.kv_updates)) -} - -fn default_tx_builder(to: Address) -> TxEnvBuilder { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000) -} - -fn write_n_slots(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { - for i in 0..n { - builder = builder.sstore(U256::from(i), U256::from(i + 1)); - } - builder -} - -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Intrinsic data size of a simple transaction: base TX + caller account update. -fn tx_intrinsic_data_size() -> u64 { - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE -} - -/// Intrinsic data size of a transaction with `n` bytes of calldata. -fn tx_intrinsic_data_size_with_calldata(n: u64) -> u64 { - BASE_TX_SIZE + n + ACCOUNT_INFO_WRITE_SIZE -} - -// ============================================================================ -// TEST 1: Intrinsic + execution overflow (DataSize) -// ============================================================================ - -/// A REX4 transaction whose intrinsic data size plus execution-generated data -/// exceeds the configured `tx_data_size_limit` must not succeed. -/// -/// Before the fix, the first frame received the full raw budget, ignoring -/// intrinsic charges already applied to `tx_entry`. The frame-local check -/// in Rex4 would pass even though total TX data exceeded the limit. -#[test] -fn test_intrinsic_plus_execution_data_size_overflow() { - // Set tx_data_size_limit just above the intrinsic so that a few SSTOREs push it over. - // intrinsic = BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE = 150 - // Each SSTORE writes STORAGE_SLOT_WRITE_SIZE = 40 bytes. - // Allow room for exactly 2 SSTOREs: limit = intrinsic + 2 * 40 = 230 - let intrinsic = tx_intrinsic_data_size(); - let limit = intrinsic + 2 * STORAGE_SLOT_WRITE_SIZE; - - // Callee writes 3 SSTOREs (120 bytes) — intrinsic(150) + 120 = 270 > 230. - let code = write_n_slots(BytecodeBuilder::default(), 3).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - // The transaction must not succeed: total data would be 270 > 230. - assert!( - !result.result.is_success(), - "TX with intrinsic + execution data exceeding limit should not succeed, \ - data_size_used={data_size}, limit={limit}" - ); -} - -// ============================================================================ -// TEST 2: Intrinsic + execution overflow (KVUpdate) -// ============================================================================ - -/// A REX4 transaction whose intrinsic KV count plus execution KV writes -/// exceeds the configured `tx_kv_updates_limit` must not succeed. -/// -/// Intrinsic KV = 1 (caller account update). Writing N storage slots adds N KVs. -#[test] -fn test_intrinsic_plus_execution_kv_update_overflow() { - // Intrinsic KV = 1 (caller update). Allow 3 total → execution budget = 2. - let kv_limit = 3; - - // Callee writes 3 SSTOREs → intrinsic(1) + 3 = 4 > 3. - let code = write_n_slots(BytecodeBuilder::default(), 3).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, kv_updates) = transact_data_kv(&mut db, u64::MAX, kv_limit, tx).unwrap(); - - assert!( - !result.result.is_success(), - "TX with intrinsic + execution KV exceeding limit should not succeed, \ - kv_updates_used={kv_updates}, limit={kv_limit}" - ); -} - -// ============================================================================ -// TEST 3: Intrinsic-only overflow (DataSize) -// ============================================================================ - -/// A transaction whose intrinsic data size alone exceeds the configured limit -/// should produce a normal execution failure (Halt with `DataLimitExceeded`), -/// not a top-level EVM error. -#[test] -fn test_intrinsic_only_data_size_overflow() { - // Set limit to something smaller than intrinsic data size. - // Even a minimal transaction with empty calldata has intrinsic = 150. - let limit = 100; // Less than BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE - - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - // Should be a normal execution failure on the additional-limit path. - assert!( - result.result.is_halt(), - "Intrinsic-only DataSize overflow should halt, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 4: Intrinsic-only overflow (KVUpdate) -// ============================================================================ - -/// A transaction whose intrinsic KV count exceeds the configured limit -/// should produce a normal execution failure (Halt with `KVUpdateLimitExceeded`), -/// not a top-level EVM error. -#[test] -fn test_intrinsic_only_kv_update_overflow() { - // Intrinsic KV = 1 (caller update). Set limit to 0. - let kv_limit = 0; - - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(&mut db, u64::MAX, kv_limit, tx).unwrap(); - - assert!( - result.result.is_halt(), - "Intrinsic-only KVUpdate overflow should halt, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 5: Correct first-frame budget (positive test) -// ============================================================================ - -/// After the fix, the first frame should receive exactly `tx_limit - intrinsic` -/// as its budget, not the full `tx_limit`. -/// -/// We set the limit so that intrinsic + exactly N SSTOREs fits, and verify -/// that N SSTOREs succeed but N+1 would fail (via frame-local revert in child). -#[test] -fn test_first_frame_budget_accounts_for_intrinsic() { - let intrinsic = tx_intrinsic_data_size(); - // Allow exactly 5 SSTOREs after intrinsic. - let limit = intrinsic + 5 * STORAGE_SLOT_WRITE_SIZE; - - // Callee writes 5 SSTOREs — should exactly fit. - let code = write_n_slots(BytecodeBuilder::default(), 5).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "5 SSTOREs should fit in first frame budget"); - assert_eq!( - data_size, - intrinsic + 5 * STORAGE_SLOT_WRITE_SIZE, - "Total data should be intrinsic + 5 SSTOREs" - ); - - // Now try 6 SSTOREs — should exceed the first frame budget. - let code = write_n_slots(BytecodeBuilder::default(), 6).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, _, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - !result.result.is_success(), - "6 SSTOREs should exceed first frame budget after intrinsic deduction" - ); -} - -// ============================================================================ -// TEST 6: Nested frame non-regression -// ============================================================================ - -/// A child frame that exceeds its own budget should revert frame-locally, -/// allowing the parent to continue when the parent budget permits it. -/// This ensures the fix did not break nested frame behavior. -#[test] -fn test_nested_frame_local_revert_non_regression() { - let intrinsic = tx_intrinsic_data_size(); - // Set limit large enough that parent has plenty of budget. - // Parent budget = limit - intrinsic. Child gets 98% of that. - // We pick limit so child gets ~98 SSTORE slots of budget. - let limit = intrinsic + 100 * STORAGE_SLOT_WRITE_SIZE; - - // Child writes 99 SSTOREs — exceeds child's 98% budget → frame-local revert. - let child_code = write_n_slots(BytecodeBuilder::default(), 99).stop().build(); - // Parent calls child, pops result (ignores revert), then stops. - let parent_code = - append_call(BytecodeBuilder::default(), CONTRACT, 50_000_000).append(POP).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, parent_code) - .account_code(CONTRACT, child_code); - - let tx = default_tx_builder(CALLEE).build_fill(); - let (result, data_size, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!(result.result.is_success(), "Parent should succeed after child frame-local revert"); - // Child's discardable data should be dropped on revert. - assert_eq!( - data_size, intrinsic, - "Child's discardable data dropped on revert, only intrinsic remains" - ); -} - -// ============================================================================ -// TEST 7: Intrinsic-only DataSize overflow + intercepted system contract -// ============================================================================ - -/// When a TX targets an intercepted system contract (e.g., `MegaLimitControl`) -/// and intrinsic data size exceeds the limit, the TX must still fail. -/// This tests that the pending exceeded limit is checked before the -/// interceptor dispatch in `frame_init()`. -#[test] -fn test_intrinsic_data_size_overflow_with_intercepted_system_contract() { - let limit = 100; // Less than intrinsic data size (~150) - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - // Direct TX to MegaLimitControl.remainingComputeGas() - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(LIMIT_CONTROL_ADDRESS) - .gas_limit(100_000_000) - .data(Bytes::copy_from_slice(&IMegaLimitControl::remainingComputeGasCall::SELECTOR)) - .build_fill(); - - let (result, _, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - !result.result.is_success(), - "Intrinsic DataSize overflow must not succeed even when targeting intercepted system contract, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 8: Intrinsic-only KVUpdate overflow + intercepted system contract -// ============================================================================ - -/// When a TX targets an intercepted system contract and intrinsic KV count -/// exceeds the limit, the TX must still fail. -#[test] -fn test_intrinsic_kv_update_overflow_with_intercepted_system_contract() { - let kv_limit = 0; // Intrinsic KV = 1 (caller update), exceeds limit of 0 - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(LIMIT_CONTROL_ADDRESS) - .gas_limit(100_000_000) - .data(Bytes::copy_from_slice(&IMegaLimitControl::remainingComputeGasCall::SELECTOR)) - .build_fill(); - - let (result, _, _) = transact_data_kv(&mut db, u64::MAX, kv_limit, tx).unwrap(); - - assert!( - !result.result.is_success(), - "Intrinsic KVUpdate overflow must not succeed even when targeting intercepted system contract, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 9: Inspector early-return + intrinsic overflow (DataSize) -// ============================================================================ - -/// An inspector that unconditionally intercepts every CALL, returning early -/// with a successful synthetic result. This triggers `inspect_frame_init`'s -/// early-return path, skipping both `check_pending_exceeded_limit` and -/// `before_frame_init`. -struct SkipAllCallsInspector; - -impl Inspector for SkipAllCallsInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - Some(CallOutcome { - result: revm::interpreter::InterpreterResult { - result: revm::interpreter::InstructionResult::Stop, - output: Bytes::new(), - gas: Gas::new(inputs.gas_limit), - }, - memory_offset: 0..0, - }) - } -} - -/// When an inspector intercepts the top-level call and intrinsic data size -/// exceeds the limit, the TX must still fail. Without the -/// `check_pending_exceeded_limit` check in `inspect_frame_init`, the pending -/// exceeded limit would be silently ignored and gas rescue would be missed. -#[test] -fn test_intrinsic_data_size_overflow_with_inspector_early_return() { - let limit = 100; // Less than intrinsic data size (~150) - - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(limit) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut inspector = SkipAllCallsInspector; - let mut evm = MegaEvm::new(context).with_inspector(&mut inspector); - let mut tx = MegaTransaction::new(default_tx_builder(CALLEE).build_fill()); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!( - result.result.is_halt(), - "Intrinsic DataSize overflow must halt even with inspector early-return, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); - - // Verify gas rescue: most gas should be refunded since no execution happened. - let gas_remaining = 100_000_000 - result.result.gas_used(); - assert!( - gas_remaining > 99_000_000, - "Expected >99M gas remaining from rescue, got {gas_remaining}" - ); -} - -// ============================================================================ -// TEST 10: Intrinsic-only DataSize overflow + contract creation TX -// ============================================================================ - -/// When a contract creation TX has intrinsic data size exceeding the limit, -/// the TX must fail. This exercises the `FrameInput::Create` branch of -/// `check_pending_exceeded_limit()`. -#[test] -fn test_intrinsic_data_size_overflow_contract_creation() { - let limit = 100; // Less than intrinsic data size (~150) - - // Simple init code that just STOPs. - let init_code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .create() - .data(init_code) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - result.result.is_halt(), - "Intrinsic DataSize overflow on CREATE TX should halt, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 11: Calldata-inflated intrinsic DataSize overflow -// ============================================================================ - -/// A transaction with a large calldata whose intrinsic data size (`BASE_TX_SIZE` + -/// `calldata.len()` + `ACCOUNT_INFO_WRITE_SIZE`) exceeds the configured limit. -/// This exercises the `tx.input().len()` path in `DataSizeTracker::before_tx_start`. -#[test] -fn test_calldata_inflated_intrinsic_data_size_overflow() { - // 500 bytes of calldata. Intrinsic = 110 + 500 + 40 = 650. - // Set limit to 600 → intrinsic alone exceeds. - let calldata = vec![0xAB; 500]; - let intrinsic = tx_intrinsic_data_size_with_calldata(500); - assert!(intrinsic > 600, "sanity: intrinsic({intrinsic}) should exceed 600"); - let limit = 600; - - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(100_000_000) - .data(Bytes::from(calldata)) - .build_fill(); - - let (result, _, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - result.result.is_halt(), - "Calldata-inflated intrinsic DataSize overflow should halt, got {:?}", - result.result - ); - assert!(matches!( - result.result, - ExecutionResult::Halt { reason: MegaHaltReason::DataLimitExceeded { .. }, .. } - )); -} - -// ============================================================================ -// TEST 12: Calldata-inflated intrinsic — within limit succeeds -// ============================================================================ - -/// Positive test: same large calldata but limit is sufficient. Verifies that -/// calldata is correctly accounted in the intrinsic without false overflow. -#[test] -fn test_calldata_inflated_intrinsic_within_limit_succeeds() { - let calldata = vec![0xAB; 500]; - let intrinsic = tx_intrinsic_data_size_with_calldata(500); - // Set limit to exactly intrinsic — should succeed (no execution data generated). - let limit = intrinsic; - - let code = BytecodeBuilder::default().stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(100_000_000) - .data(Bytes::from(calldata)) - .build_fill(); - - let (result, data_size, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - result.result.is_success(), - "Calldata-inflated intrinsic within limit should succeed, got {:?}", - result.result - ); - assert_eq!(data_size, intrinsic, "Total data should equal intrinsic with calldata"); -} - -// ============================================================================ -// TEST 13: Calldata-inflated intrinsic + execution overflow -// ============================================================================ - -/// A transaction with large calldata whose intrinsic is within the limit, but -/// additional execution data pushes total usage over the limit. -#[test] -fn test_calldata_inflated_intrinsic_plus_execution_overflow() { - let calldata = vec![0xAB; 200]; - let intrinsic = tx_intrinsic_data_size_with_calldata(200); - // Allow room for exactly 1 SSTORE after intrinsic. - let limit = intrinsic + STORAGE_SLOT_WRITE_SIZE; - - // Callee writes 2 SSTOREs → exceeds. - let code = write_n_slots(BytecodeBuilder::default(), 2).stop().build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, code); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(100_000_000) - .data(Bytes::from(calldata)) - .build_fill(); - - let (result, data_size, _) = transact_data_kv(&mut db, limit, u64::MAX, tx).unwrap(); - - assert!( - !result.result.is_success(), - "Calldata-inflated intrinsic + execution data exceeding limit should not succeed, \ - data_size_used={data_size}, limit={limit}" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs b/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs deleted file mode 100644 index b746a8277..000000000 --- a/crates/mega-evm/tests/_pending/rex4/keyless_deploy.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! Tests for keyless deploy salt environment fix in Rex4. -//! -//! Rex4 fixes the keyless deploy sandbox to share the parent's salt env and oracle env, -//! ensuring correct dynamic gas pricing for storage operations in keyless deploy constructors. -//! Pre-Rex4 specs retain the `EmptyExternalEnv` behavior for backward compatibility. - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::{sol, SolCall}; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{ - calculate_keyless_deploy_address, - tests::{CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX}, - }, - test_utils::{BytecodeBuilder, MemoryDatabase}, - IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, - TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, MIN_BUCKET_SIZE, ORACLE_CONTRACT_ADDRESS, - ORACLE_CONTRACT_CODE_REX2, -}; -use revm::{ - bytecode::opcode::{CALL, GAS, MSTORE, POP, PUSH0, RETURN}, - context::TxEnv, - inspector::NoOpInspector, -}; - -sol! { - function sendHint(bytes32 topic, bytes calldata data) external; -} - -// ============================================================================ -// TEST CONSTANTS -// ============================================================================ - -/// Standard test caller address. -const TEST_CALLER: Address = address!("0000000000000000000000000000000000100000"); - -/// Large gas limit override for tests (10 billion gas). -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a keyless deploy with the given spec and external envs. -/// -/// Returns the execution result and the sandbox `gas_used` (from the ABI-encoded return data). -fn execute_keyless_deploy_with_envs( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: &TestExternalEnvs, - keyless_deployment_transaction: Bytes, -) -> (ExecutionResult, u64) { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_deployment_transaction, - gasLimitOverride: U256::from(LARGE_GAS_LIMIT_OVERRIDE), - } - .abi_encode(); - - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnv { - caller: TEST_CALLER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let result = result_envelope.result; - - // Extract sandbox gas_used from the ABI-encoded return data - let sandbox_gas_used = match &result { - ExecutionResult::Success { output, .. } => { - let output_data = output.data(); - let decoded = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output_data) - .expect("decode return data"); - decoded.gasUsed - } - _ => 0, - }; - - (result, sandbox_gas_used) -} - -/// Computes the bucket ID for the CREATE2 factory contract (the deployed address). -fn contract_bucket_id() -> u32 { - ::bucket_id_for_account(CREATE2_FACTORY_CONTRACT) -} - -/// Computes the bucket ID for the CREATE2 factory deployer signer. -fn deployer_bucket_id() -> u32 { - ::bucket_id_for_account(CREATE2_FACTORY_DEPLOYER) -} - -/// Creates a pre-EIP-155 keyless deploy transaction with deterministic signature. -fn create_pre_eip155_deploy_tx(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: 100_000_000_000, - gas_limit: 1_000_000, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - - (tx_bytes, signer) -} - -/// Encodes calldata for `sendHint(bytes32 topic, bytes data)`. -fn encode_send_hint_calldata(topic: B256, data: &[u8]) -> Vec { - sendHintCall { topic, data: Bytes::copy_from_slice(data) }.abi_encode() -} - -/// Creates init code that emits an oracle hint during construction, then returns `STOP`. -fn create_constructor_send_hint_init_code(topic: B256, data: &[u8]) -> Bytes { - let calldata = encode_send_hint_calldata(topic, data); - let mut builder = BytecodeBuilder::default(); - - for (i, chunk) in calldata.chunks(32).enumerate() { - let mut padded = [0u8; 32]; - padded[..chunk.len()].copy_from_slice(chunk); - builder = builder.push_bytes(padded).push_number((i * 32) as u8).append(MSTORE); - } - - builder = builder - .append(PUSH0) - .append(PUSH0) - .push_number(calldata.len() as u16) - .append(PUSH0) - .append(PUSH0) - .push_address(ORACLE_CONTRACT_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP); - - let runtime_offset = (builder.len() + 12) as u8; - builder - .push_number(1_u8) - .push_number(runtime_offset) - .push_number(0_u8) - .append(revm::bytecode::opcode::CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .stop() - .build() -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// Rex4 keyless deploy sandbox uses the parent's salt env. -/// -/// With a high bucket capacity, the salt multiplier increases, causing higher gas for the -/// contract creation inside the sandbox. -/// We compare sandbox `gas_used` with default (1x) vs elevated bucket capacity to verify -/// the sandbox actually uses the salt env. -#[test] -fn test_rex4_keyless_deploy_uses_salt_env() { - // Run with default bucket capacity (1x multiplier) - let mut db_default = MemoryDatabase::default(); - db_default.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let env_default = TestExternalEnvs::::new(); - let (result_default, gas_default) = execute_keyless_deploy_with_envs( - MegaSpecId::REX4, - &mut db_default, - &env_default, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_default.is_success(), - "Default deploy should succeed, got: {:?}", - result_default - ); - - // Run with elevated bucket capacity (2x multiplier) for both deployer and contract buckets - let mut db_high = MemoryDatabase::default(); - db_high.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - let high_capacity = (MIN_BUCKET_SIZE as u64) * 2; - let env_high = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket_id(), high_capacity) - .with_bucket_capacity(deployer_bucket_id(), high_capacity); - let (result_high, gas_high) = execute_keyless_deploy_with_envs( - MegaSpecId::REX4, - &mut db_high, - &env_high, - Bytes::from_static(CREATE2_FACTORY_TX), - ); - assert!( - result_high.is_success(), - "High-capacity deploy should succeed, got: {:?}", - result_high - ); - - // REX4 sandbox shares salt env, so elevated bucket capacity should increase gas - assert!( - gas_high > gas_default, - "REX4 with higher bucket capacity should use more sandbox gas: default={}, high={}", - gas_default, - gas_high, - ); -} - -/// Rex4 keyless deploy sandbox forwards oracle hints emitted in constructors. -#[test] -fn test_rex4_keyless_deploy_constructor_uses_oracle_env() { - let topic = B256::repeat_byte(0x11); - let hint_data = b"rex4-sandbox-hint"; - let init_code = create_constructor_send_hint_init_code(topic, hint_data); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(signer, U256::from(1_000_000_000_000_000_000_000u128)); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - - let external_envs = TestExternalEnvs::::new(); - let (result, _) = - execute_keyless_deploy_with_envs(MegaSpecId::REX4, &mut db, &external_envs, tx_bytes); - - assert!(result.is_success(), "keyless deploy should succeed, got: {:?}", result); - - let hints = external_envs.recorded_hints(); - let deploy_address = calculate_keyless_deploy_address(signer); - assert_eq!(hints.len(), 1, "constructor should emit exactly one oracle hint"); - assert_eq!(hints[0].from, deploy_address, "hint sender should be the constructor address"); - assert_eq!(hints[0].topic, topic, "hint topic should match constructor input"); - assert_eq!(hints[0].data, Bytes::copy_from_slice(hint_data), "hint data should match"); -} diff --git a/crates/mega-evm/tests/_pending/rex4/limit_control.rs b/crates/mega-evm/tests/_pending/rex4/limit_control.rs deleted file mode 100644 index 4acfb1133..000000000 --- a/crates/mega-evm/tests/_pending/rex4/limit_control.rs +++ /dev/null @@ -1,579 +0,0 @@ -//! Tests for the `MegaLimitControl` system contract. -//! -//! When a contract calls `LIMIT_CONTROL_ADDRESS.remainingComputeGas()`, -//! the interceptor returns the remaining compute gas for the current call. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - constants::mini_rex::BLOCK_ENV_ACCESS_COMPUTE_GAS, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaLimitControl, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, -}; -use revm::{ - bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, MSTORE, POP, RETURN, STATICCALL, TIMESTAMP}, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - ContextTr, TxEnv, - }, - handler::EvmTr, - interpreter::{CallInputs, CallOutcome, InterpreterTypes}, - Inspector, -}; - -// Test addresses -const CALLER: Address = address!("0000000000000000000000000000000000300000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000300001"); -const CONTRACT2: Address = address!("0000000000000000000000000000000000300002"); -const CONTRACT3: Address = address!("0000000000000000000000000000000000300003"); - -/// The 4-byte selector for `remainingComputeGas()`. -const REMAINING_COMPUTE_GAS_SELECTOR: [u8; 4] = - IMegaLimitControl::remainingComputeGasCall::SELECTOR; -const NOT_INTERCEPTED_SELECTOR: [u8; 4] = IMegaLimitControl::NotIntercepted::SELECTOR; -const NON_ZERO_TRANSFER_SELECTOR: [u8; 4] = IMegaLimitControl::NonZeroTransfer::SELECTOR; - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction on the given spec. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Builds a default transaction calling a contract. -fn default_tx(to: Address) -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(to).gas_limit(100_000_000).build_fill() -} - -/// Builds a direct transaction calling `remainingComputeGas()` on the target. -fn direct_query_tx(to: Address) -> TxEnv { - direct_query_tx_with_value(to, U256::ZERO) -} - -/// Builds a direct transaction calling `remainingComputeGas()` with a custom call value. -fn direct_query_tx_with_value(to: Address, value: U256) -> TxEnv { - TxEnvBuilder::default() - .caller(CALLER) - .call(to) - .value(value) - .gas_limit(100_000_000) - .data(Bytes::copy_from_slice(&REMAINING_COMPUTE_GAS_SELECTOR)) - .build_fill() -} - -/// Builds a direct transaction calling `to` with custom calldata. -fn direct_tx_with_data(to: Address, data: &[u8]) -> TxEnv { - TxEnvBuilder::default() - .caller(CALLER) - .call(to) - .gas_limit(100_000_000) - .data(Bytes::copy_from_slice(data)) - .build_fill() -} - -/// Executes a transaction on the given spec with custom tx compute gas limit. -fn transact_with_compute_limit( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx_compute_gas_limit: u64, - tx: TxEnv, -) -> Result<(ResultAndState, u64, u64), EVMError> -{ - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(tx_compute_gas_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - let additional_limit = evm.ctx_ref().additional_limit.borrow(); - let usage = additional_limit.get_usage().compute_gas; - let effective_limit = additional_limit.compute_gas_limit(); - Ok((result, usage, effective_limit)) -} - -/// Decodes return data as `remainingComputeGas()` output. -fn decode_remaining_compute_gas(result: &ResultAndState) -> u64 { - let output = match &result.result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("expected success output, got: {:?}", result.result), - }; - - IMegaLimitControl::remainingComputeGasCall::abi_decode_returns(&output) - .expect("should decode remainingComputeGas output") -} - -/// Builds bytecode that calls `remainingComputeGas()` and returns the ABI result. -fn call_remaining_compute_gas_and_return(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(32_u64) // retSize - .push_number(0x20_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) - .push_number(32_u64) - .push_number(0x20_u64) - .append(RETURN) -} - -/// Builds bytecode that STATICCALLs `remainingComputeGas()` and returns the ABI result. -fn staticcall_remaining_compute_gas_and_return(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(32_u64) // retSize - .push_number(0x20_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(STATICCALL) - .append(POP) - .push_number(32_u64) - .push_number(0x20_u64) - .append(RETURN) -} - -/// Builds bytecode that CALLs a target address with the given gas. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Builds bytecode that DELEGATECALLs a target address with the given gas. -fn append_delegatecall(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(target) - .push_number(gas) - .append(DELEGATECALL) -} - -/// Builds bytecode that CALLCODEs a target address with the given gas. -fn append_callcode(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALLCODE) -} - -/// Appends a configurable amount of pure compute work (`PUSH1; POP`). -fn burn_compute(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { - for _ in 0..n { - builder = builder.push_number(1_u64).append(POP); - } - builder -} - -// ============================================================================ -// 1. BASIC remainingComputeGas() BEHAVIOR -// ============================================================================ - -/// Direct transaction call to system contract should return a positive remaining value. -#[test] -fn test_direct_tx_remaining_compute_gas() { - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let result = - transact(MegaSpecId::REX4, &mut db, direct_query_tx(LIMIT_CONTROL_ADDRESS)).unwrap(); - assert!(result.result.is_success()); - - let remaining = decode_remaining_compute_gas(&result); - assert!(remaining > 0, "remaining compute gas should be positive"); -} - -/// STATICCALL query should also return a positive remaining value. -#[test] -fn test_remaining_compute_gas_staticcall() { - let code = staticcall_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, code); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - assert!(result.result.is_success()); - - let remaining = decode_remaining_compute_gas(&result); - assert!(remaining > 0, "remaining compute gas should be positive for STATICCALL query"); -} - -// ============================================================================ -// 2. COMPUTE ACCOUNTING -// ============================================================================ - -/// More compute work should reduce `remainingComputeGas()`. -#[test] -fn test_remaining_compute_gas_decreases_after_compute_work() { - let base_contract_code = - call_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - - let heavy_contract_code = - call_remaining_compute_gas_and_return(burn_compute(BytecodeBuilder::default(), 20_000)) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, base_contract_code) - .account_code(CONTRACT2, heavy_contract_code); - - let base_result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - let heavy_result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT2)).unwrap(); - - assert!(base_result.result.is_success()); - assert!(heavy_result.result.is_success()); - - let base_remaining = decode_remaining_compute_gas(&base_result); - let heavy_remaining = decode_remaining_compute_gas(&heavy_result); - assert!( - heavy_remaining < base_remaining, - "remaining compute gas should decrease after more compute work: heavy={}, base={}", - heavy_remaining, - base_remaining - ); -} - -/// Two sequential queries in the same frame should return decreasing values, -/// and the difference should be small (only the overhead of the query + glue instructions). -#[test] -fn test_remaining_compute_gas_sequential_queries_decrease() { - // Contract: query remainingComputeGas twice, return both values as (first, second). - // First query result stored at 0x20, second at 0x40, return 64 bytes from 0x20. - let code = BytecodeBuilder::default() - // First query - .mstore(0x0, REMAINING_COMPUTE_GAS_SELECTOR) - .push_number(32_u64) // retSize - .push_number(0x20_u64) // retOffset — store first result at 0x20 - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) - .append(CALL) - .append(POP) - // Second query (selector still at 0x00) - .push_number(32_u64) // retSize - .push_number(0x40_u64) // retOffset — store second result at 0x40 - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .push_number(100_000_u64) - .append(CALL) - .append(POP) - // Return both (64 bytes from 0x20) - .push_number(64_u64) - .push_number(0x20_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, code); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - assert!(result.result.is_success()); - - let output = result.result.output().expect("should have output"); - assert_eq!(output.len(), 64, "should return two 32-byte values"); - - let first = U256::from_be_slice(&output[..32]).saturating_to::(); - let second = U256::from_be_slice(&output[32..64]).saturating_to::(); - - assert!( - second < first, - "second query should return less than first (first={first}, second={second})" - ); - - // The difference should be small — only the overhead of the glue instructions - // between the two queries (a few PUSHes + CALL + POP ≈ tens of gas). - let diff = first - second; - assert!( - diff < 1000, - "difference between sequential queries should be small (diff={diff}), \ - confirming the query itself doesn't consume significant compute gas" - ); -} - -/// Direct top-level query should return `tx_limit` minus intrinsic compute gas. -#[test] -fn test_remaining_compute_gas_exact_value_matches_tracker() { - let tx_limit = 1_000_000_u64; - let mut db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); - - let (result, used_compute, _effective_limit) = transact_with_compute_limit( - MegaSpecId::REX4, - &mut db, - tx_limit, - direct_query_tx(LIMIT_CONTROL_ADDRESS), - ) - .unwrap(); - assert!(result.result.is_success(), "direct query should succeed"); - - let remaining = decode_remaining_compute_gas(&result); - assert!( - remaining < tx_limit, - "top-level remaining should be less than tx_limit due to intrinsic compute gas \ - (remaining={remaining}, tx_limit={tx_limit})" - ); - assert_eq!( - remaining, - tx_limit - used_compute, - "top-level remaining should equal tx_limit minus intrinsic compute gas \ - (tx_limit={tx_limit}, used={used_compute})" - ); -} - -/// Inner-call query returns the caller's frame remaining, not the 98/100 forwarded child budget. -/// -/// A contract calling `remainingComputeGas()` with minimal overhead should get a value -/// above `tx_limit * 98/100`. If the implementation mistakenly used `max_forward_limit()` -/// (which applies the 98/100 forwarding ratio), the returned value would be at most -/// `tx_limit * 98/100`, and this assertion would catch it. -#[test] -fn test_remaining_compute_gas_inner_call_returns_frame_remaining() { - let tx_limit = 100_000_000_u64; - let forwarded_budget = tx_limit / 100 * 98; // 98_000_000 - - // Contract with minimal bytecode: just query remainingComputeGas and return. - // The small instruction overhead (MSTORE, PUSH, CALL, POP, RETURN) is negligible - // compared to the 2% margin between frame remaining and forwarded budget. - let contract_code = call_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, contract_code); - - let (result, _, _) = - transact_with_compute_limit(MegaSpecId::REX4, &mut db, tx_limit, default_tx(CONTRACT)) - .unwrap(); - - assert!(result.result.is_success()); - - let remaining = decode_remaining_compute_gas(&result); - - // The returned value must be strictly above the forwarded budget. - // A correct implementation returns frame.remaining() ≈ tx_limit - small_overhead, - // while a wrong implementation (max_forward_limit) would return ≈ forwarded_budget - overhead. - assert!( - remaining > forwarded_budget, - "inner-call remaining ({remaining}) should exceed forwarded budget ({forwarded_budget}); \ - if not, the implementation is likely returning max_forward_limit (98/100) instead of frame remaining" - ); - assert!( - remaining < tx_limit, - "inner-call remaining ({remaining}) should be less than tx_limit ({tx_limit}) due to instruction overhead" - ); -} - -/// Two-level nesting: TX → A → B → `remainingComputeGas()`. -/// -/// A burns significant compute before calling B. B queries `remainingComputeGas()`. -/// The returned value should reflect B's frame remaining (derived from A's remaining at -/// call time, with the 98/100 forwarding ratio applied), NOT A's frame remaining. -#[test] -fn test_remaining_compute_gas_two_level_nesting_returns_inner_frame() { - let tx_limit = 100_000_000_u64; - - // B: minimal contract that queries remainingComputeGas and returns it. - let b_code = call_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - - // A: burns significant compute, then CALLs B, then returns B's result. - // After burning compute, A's frame remaining is reduced. B gets 98/100 of A's remaining. - let a_code = burn_compute(BytecodeBuilder::default(), 50_000); - // CALL B with retSize=32, retOffset=0x20 - let a_code = a_code - .push_number(32_u64) // retSize - .push_number(0x20_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(CONTRACT2) - .push_number(50_000_000_u64) // gas - .append(CALL) - .append(POP) - // Return B's result - .push_number(32_u64) - .push_number(0x20_u64) - .append(RETURN) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, a_code) - .account_code(CONTRACT2, b_code); - - let (result, _, _) = - transact_with_compute_limit(MegaSpecId::REX4, &mut db, tx_limit, default_tx(CONTRACT)) - .unwrap(); - assert!(result.result.is_success()); - - let remaining = decode_remaining_compute_gas(&result); - - // B's frame budget = 98/100 of (A's frame remaining at call time). - // A's frame remaining ≈ tx_limit - overhead - burn_compute_cost. - // If the implementation incorrectly returned A's frame remaining, we'd see a value - // much higher than B's budget (close to A's remaining ≈ tx_limit - burn overhead). - // B's budget should be strictly less than 98/100 of tx_limit due to A's compute overhead. - let max_b_budget = tx_limit / 100 * 98; // 98_000_000 - assert!( - remaining < max_b_budget, - "B's frame remaining ({remaining}) should be less than max possible B budget \ - ({max_b_budget}), proving it reflects B's frame, not A's" - ); - assert!(remaining > 0, "B's frame remaining should be positive"); -} - -/// Compute gas in reverted inner calls is still persistent and should reduce remaining value. -#[test] -fn test_remaining_compute_gas_persistent_after_inner_revert() { - // Base contract: just queries remainingComputeGas and returns it. - let base_contract_code = - call_remaining_compute_gas_and_return(BytecodeBuilder::default()).build(); - - // Reverting child: burns compute then reverts. - let reverting_child_code = burn_compute(BytecodeBuilder::default(), 20_000).revert().build(); - - // CONTRACT3: call reverting child, then query remainingComputeGas. - let caller_code = append_call(BytecodeBuilder::default(), CONTRACT2, 50_000_000).append(POP); - let caller_code = call_remaining_compute_gas_and_return(caller_code).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, base_contract_code) - .account_code(CONTRACT2, reverting_child_code) - .account_code(CONTRACT3, caller_code); - - let base_result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT)).unwrap(); - let after_revert_result = transact(MegaSpecId::REX4, &mut db, default_tx(CONTRACT3)).unwrap(); - - assert!(base_result.result.is_success()); - assert!(after_revert_result.result.is_success()); - - let base_remaining = decode_remaining_compute_gas(&base_result); - let after_revert_remaining = decode_remaining_compute_gas(&after_revert_result); - - assert!( - after_revert_remaining < base_remaining, - "remaining should be lower after reverted inner call (compute gas is persistent): \ - after_revert={}, base={}", - after_revert_remaining, - base_remaining - ); -} - -// ============================================================================ -// 3. DETENTION INTERACTION -// ============================================================================ - -/// After volatile data access (TIMESTAMP), the returned value should be capped by the TX -/// detained limit, reflecting the actual compute gas available before execution halts. -#[test] -fn test_remaining_compute_gas_clamped_by_detention_limit() { - let tx_limit = 100_000_000_u64; - let contract_code = call_remaining_compute_gas_and_return( - BytecodeBuilder::default().append(TIMESTAMP).append(POP), - ) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CONTRACT, contract_code); - - let limits = EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(tx_limit); - // Set the block env access detention cap so TIMESTAMP triggers detention. - let limits = EvmTxRuntimeLimits { - block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, - ..limits - }; - - let mut context = MegaContext::new(&mut db, MegaSpecId::REX4).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(default_tx(CONTRACT)); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - - assert!(result.result.is_success(), "query transaction should succeed"); - - let remaining = decode_remaining_compute_gas(&result); - assert!(remaining > 0, "remaining compute gas should be positive"); - assert!( - remaining <= BLOCK_ENV_ACCESS_COMPUTE_GAS, - "remaining should be capped by detained limit after TIMESTAMP access \ - (remaining={remaining}, cap={BLOCK_ENV_ACCESS_COMPUTE_GAS})" - ); -} - -// ============================================================================ -// 4. INSPECTOR VISIBILITY -// ============================================================================ - -/// An inspector that records all `call` and `call_end` invocations. -#[derive(Default)] -struct CallTrackingInspector { - calls: Vec
, - call_ends: Vec
, -} - -impl Inspector for CallTrackingInspector { - fn call(&mut self, _context: &mut CTX, inputs: &mut CallInputs) -> Option { - self.calls.push(inputs.target_address); - None - } - - fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, _outcome: &mut CallOutcome) { - self.call_ends.push(inputs.target_address); - } -} - -// ============================================================================ -// 5. CALL VARIANTS -// ============================================================================ - -// ============================================================================ -// 6. BACKWARD COMPATIBILITY -// ============================================================================ diff --git a/crates/mega-evm/tests/_pending/rex4/main.rs b/crates/mega-evm/tests/_pending/rex4/main.rs deleted file mode 100644 index b75668583..000000000 --- a/crates/mega-evm/tests/_pending/rex4/main.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Tests for `Rex4` hardfork features. - -mod access_control; -mod beneficiary_detention; -mod create_safety; -mod deployment; -mod eip7702_delegation_cycle; -mod frame_limits; -mod gas_detention; -mod intrinsic_limit_bypass; -mod keyless_deploy; -mod limit_control; -mod storage_call_stipend; diff --git a/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs b/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs deleted file mode 100644 index c629ec73d..000000000 --- a/crates/mega-evm/tests/_pending/rex4/storage_call_stipend.rs +++ /dev/null @@ -1,687 +0,0 @@ -//! Tests for the `STORAGE_CALL_STIPEND` feature introduced in REX4. -//! -//! `MegaETH`'s 10x storage gas multiplier on LOG opcodes causes `LOG1` to cost 4,500 gas -//! (750 compute + 3,750 storage), exceeding the EVM's `CALL_STIPEND` of 2,300. -//! This breaks `transfer()` / `send()` to contracts that emit events in `receive()`. -//! -//! REX4 introduces `STORAGE_CALL_STIPEND` (23,000 gas) that is added to the callee's gas -//! when CALL/CALLCODE transfers value. -//! The callee's compute gas limit remains at the original level, so the extra gas can only -//! be consumed by storage gas operations. -//! On return, unused `STORAGE_CALL_STIPEND` is burned. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IKeylessDeploy, IMegaAccessControl, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, MegaTransactionError, ACCESS_CONTROL_ADDRESS, - KEYLESS_DEPLOY_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -/// A contract that performs CALL with value to RECEIVER. -const SENDER_CONTRACT: Address = address!("0000000000000000000000000000000000200001"); -/// A contract that emits events when receiving ETH (simulates `receive()`). -const RECEIVER: Address = address!("0000000000000000000000000000000000200002"); -/// An empty contract (STOP immediately). -const EMPTY_RECEIVER: Address = address!("0000000000000000000000000000000000200003"); -/// An intermediate contract for nested value-transfer tests. -const MIDDLE_CONTRACT: Address = address!("0000000000000000000000000000000000200005"); -/// A fresh address not in the database (triggers state growth when receiving value). -const NEW_EMPTY_ADDR: Address = address!("0000000000000000000000000000000000300001"); -/// An EOA in the database with balance but no code. -const EOA_RECEIVER: Address = address!("0000000000000000000000000000000000200008"); -/// The 4-byte selector for `disableVolatileDataAccess()`. -const DISABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Executes a transaction and returns the result. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - transact_with_limits(spec, db, tx, EvmTxRuntimeLimits::no_limits()) -} - -/// Executes a transaction with custom runtime limits. -fn transact_with_limits( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, - limits: EvmTxRuntimeLimits, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Builds bytecode for a contract that does CALL(gas=0, to, value=1 wei, ...) to simulate -/// `address.transfer(1)`. -/// The CALL forwards 0 gas explicitly — the callee only gets the `CALL_STIPEND` (+ any -/// `STORAGE_CALL_STIPEND` under REX4). -fn build_transfer_contract(to: Address) -> Bytes { - BytecodeBuilder::default() - // CALL(gas, addr, value, argsOffset, argsSize, retOffset, retSize) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(to) - .push_number(0_u64) // gas = 0 (rely on stipend) - .append(CALL) - // Return the success flag (1 = success, 0 = revert) - .push_number(0_u64) // offset - .append(MSTORE) - .push_number(32_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build() -} - -/// Builds bytecode for a contract that does CALLCODE(gas=0, to, value=1 wei, ...) to simulate -/// a stipend-limited CALLCODE with value transfer. -fn build_callcode_transfer_contract(to: Address) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(to) - .push_number(0_u64) // gas = 0 (rely on stipend) - .append(CALLCODE) - .push_number(0_u64) // offset - .append(MSTORE) - .push_number(32_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build() -} - -/// Builds bytecode for a contract that does `CALL(gas=forwarded_gas`, to, value=1 wei, ...). -/// This is used when the child needs more compute gas than a plain transfer stipend provides. -fn build_value_call_contract(to: Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(to) - .push_number(forwarded_gas) - .append(CALL) - .append(STOP) - .build() -} - -/// Builds bytecode for a contract that CALLs a system contract with value and 4 bytes calldata. -/// This exercises the `frame_init` interception path, which uses `push_empty_frame()`. -fn build_value_call_with_selector(to: Address, selector: [u8; 4]) -> Bytes { - BytecodeBuilder::default() - .mstore(0, selector) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(to) - .push_number(0_u64) // gas = 0 (rely on stipend) - .append(CALL) - .push_number(0_u64) // offset - .append(MSTORE) - .push_number(32_u64) // size - .push_number(0_u64) // offset - .append(RETURN) - .build() -} - -/// Builds bytecode that measures gas consumed by an intercepted CALL carrying the given value. -/// -/// The returned 32-byte word is `gas_before - gas_after` measured around the CALL region. -fn build_measured_call_with_selector(to: Address, selector: [u8; 4], value: u64) -> Bytes { - BytecodeBuilder::default() - .mstore(0, selector) - .append(GAS) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(value) - .push_address(to) - .push_number(0_u64) // gas = 0 - .append(CALL) - .append(POP) // discard success flag - .append(GAS) - .append(SWAP1) - .append(SUB) - .push_number(0x20_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0x20_u64) - .append(RETURN) - .build() -} - -/// Builds bytecode for a contract that emits LOG1 with 0 bytes data. -/// Total cost: 750 compute + 3,750 storage = 4,500 gas. -fn build_log1_receiver() -> Bytes { - BytecodeBuilder::default() - // LOG1(offset, size, topic1) - .push_number(0xdeadbeef_u64) // topic1 - .push_number(0_u64) // size = 0 - .push_number(0_u64) // offset = 0 - .append(LOG1) - .append(STOP) - .build() -} - -/// Builds bytecode for a contract that emits LOG2 with 32 bytes data. -/// Compute: 375 + 375*2 + 8*32 = 1,381 -/// Storage: 3,750*2 + 80*32 = 10,060 -/// Total: 11,441 gas. -fn build_log2_receiver() -> Bytes { - BytecodeBuilder::default() - // Store 32 bytes of data in memory first - .push_u256(U256::from(0x1234)) - .push_number(0_u64) - .append(MSTORE) - // LOG2(offset, size, topic1, topic2) - .push_number(0xcafe_u64) // topic2 - .push_number(0xbeef_u64) // topic1 - .push_number(32_u64) // size = 32 bytes - .push_number(0_u64) // offset = 0 - .append(LOG2) - .append(STOP) - .build() -} - -/// Appends approximately `target_gas` worth of compute gas burn via repeated PUSH1/POP pairs. -fn append_burn_gas(mut builder: BytecodeBuilder, target_gas: u64) -> BytecodeBuilder { - let iterations = target_gas / 5; - for _ in 0..iterations { - builder = builder.push_number(0_u8).append(POP); - } - builder -} - -/// Sets up a database with CALLER having enough ETH and the given contracts deployed. -fn setup_db(contracts: &[(Address, Bytes)]) -> MemoryDatabase { - let mut db = - MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_000u128)); - for (addr, bytecode) in contracts { - db = db.account_code(*addr, bytecode.clone()); - } - // Ensure SENDER_CONTRACT has balance for value transfers (set after code). - db.set_account_balance(SENDER_CONTRACT, U256::from(1_000_000_000u128)); - db -} - -fn default_tx() -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(SENDER_CONTRACT).gas_limit(100_000_000).build_fill() -} - -fn direct_value_transfer_tx(to: Address, gas_limit: u64) -> TxEnv { - TxEnvBuilder::default() - .caller(CALLER) - .call(to) - .gas_limit(gas_limit) - .value(U256::from(1_u64)) - .build_fill() -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// Under REX4, CALL with value transfer to a contract that emits LOG1 should succeed. -/// The callee gets `CALL_STIPEND` (2,300) + `STORAGE_CALL_STIPEND` (23,000) = 25,300 total gas. -/// LOG1 costs 4,500 total (750 compute + 3,750 storage), which fits within 25,300. -#[test] -fn test_log1_in_receive_succeeds_under_rex4() { - let sender_code = build_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - // The return data contains the CALL success flag. - // 1 = inner CALL succeeded. - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!(success_flag, U256::from(1), "inner CALL should succeed under REX4"); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// The storage-call stipend only applies to internal `CALL`/`CALLCODE`, not to the -/// top-level transaction frame. -#[test] -fn test_top_level_value_transfer_does_not_get_storage_call_stipend() { - let receiver_code = build_log1_receiver(); - let tx = direct_value_transfer_tx(RECEIVER, 63_000); - - let mut rex3_db = setup_db(&[(RECEIVER, receiver_code.clone())]); - let rex3_result = transact(MegaSpecId::REX3, &mut rex3_db, tx.clone()).unwrap(); - assert!( - matches!(rex3_result.result, ExecutionResult::Halt { .. }), - "top-level value transfer should still halt under REX3" - ); - - let mut rex4_db = setup_db(&[(RECEIVER, receiver_code)]); - let rex4_result = transact(MegaSpecId::REX4, &mut rex4_db, tx).unwrap(); - assert!( - matches!(rex4_result.result, ExecutionResult::Halt { .. }), - "top-level value transfer must NOT receive STORAGE_CALL_STIPEND under REX4" - ); -} - -/// Under REX4, LOG2 with 32 bytes data (11,441 total gas) should also succeed in a -/// stipend-limited call. -#[test] -fn test_log2_in_receive_succeeds_under_rex4() { - let sender_code = build_transfer_contract(RECEIVER); - let receiver_code = build_log2_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!(success_flag, U256::from(1), "inner CALL with LOG2 should succeed"); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// Under REX4, CALLCODE with value transfer should also receive `STORAGE_CALL_STIPEND`. -/// The callee code executes in the caller's context, but the gas semantics still include -/// the extra storage-only stipend. -#[test] -fn test_callcode_gets_storage_call_stipend() { - let sender_code = build_callcode_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::from(1), - "inner CALLCODE should succeed under REX4 with STORAGE_CALL_STIPEND" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// CALL without value transfer should NOT receive `STORAGE_CALL_STIPEND`. -#[test] -fn test_no_stipend_without_value_transfer() { - // Contract that CALLs RECEIVER with value=0 - let sender_no_value = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value = 0 - .push_address(RECEIVER) - .push_number(0_u64) // gas = 0 - .append(CALL) - // Return success flag - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_no_value), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - // Without value transfer, no stipend at all (not even CALL_STIPEND). - // The callee gets 0 gas and can't execute LOG1. - assert_eq!( - success_flag, - U256::ZERO, - "CALL without value should NOT get STORAGE_CALL_STIPEND" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// DELEGATECALL should NOT receive `STORAGE_CALL_STIPEND` (no value transfer possible). -#[test] -fn test_delegatecall_no_storage_call_stipend() { - // Contract that does DELEGATECALL to RECEIVER - let sender_code = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(RECEIVER) - .push_number(0_u64) // gas = 0 - .append(DELEGATECALL) - // Return success flag - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "DELEGATECALL should NOT get STORAGE_CALL_STIPEND" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// STATICCALL should NOT receive `STORAGE_CALL_STIPEND` (no value transfer, no state changes). -#[test] -fn test_staticcall_no_storage_call_stipend() { - // Contract that does STATICCALL to a contract that tries LOG1 (will fail due to static) - // Use a simple contract that just does ADD to avoid the static violation - let callee_code = BytecodeBuilder::default() - .push_number(1_u64) - .push_number(2_u64) - .append(ADD) - .append(POP) - .append(STOP) - .build(); - let sender_code = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_address(RECEIVER) - .push_number(0_u64) // gas = 0 - .append(STATICCALL) - .append(STOP) - .build(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, callee_code)]); - - // Just verify it runs without issues — STATICCALL has no value transfer so no stipend. - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - assert!(matches!(result.result, ExecutionResult::Success { .. }), "STATICCALL should succeed"); -} - -/// `STORAGE_CALL_STIPEND` must NOT be usable for pure computation. -/// A callee that only does compute (PUSH/POP loops, no LOG or storage ops) should still -/// be limited to `CALL_STIPEND` (2,300) worth of compute gas. -/// This is the core reentrancy safety property. -#[test] -fn test_storage_call_stipend_cannot_be_used_for_compute() { - // Receiver that does ~1000 iterations of PUSH1/POP (pure compute, ~6000 compute gas). - // This exceeds CALL_STIPEND (2,300) but fits within CALL_STIPEND + STORAGE_CALL_STIPEND - // (25,300). It MUST fail because the compute gas cap is enforced at CALL_STIPEND (2,300). - let mut builder = BytecodeBuilder::default(); - for _ in 0..1000 { - builder = builder.push_number(1_u64).append(POP); - } - let receiver_code = builder.append(STOP).build(); - - let sender_code = build_transfer_contract(RECEIVER); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "callee doing pure compute (>2300 gas) should fail even with STORAGE_CALL_STIPEND" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// Calls intercepted in `frame_init` should still push an empty tracking frame so the -/// additional-limit stacks remain aligned even though no EVM frame executes. -#[test] -fn test_intercepted_call_keeps_limit_tracker_stack_aligned() { - let sender_code = build_value_call_with_selector( - ACCESS_CONTROL_ADDRESS, - DISABLE_VOLATILE_DATA_ACCESS_SELECTOR, - ); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "intercepted CALL with non-zero value should revert via system contract interceptor" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// A synthetic intercepted value-bearing call should not leak `STORAGE_CALL_STIPEND` gas back -/// to the caller. -/// -/// We compare the gas delta of the same intercepted call with and without value transfer. -/// The value-bearing case should still cost materially more because the CALLVALUE cost remains, -/// while no storage-call stipend is granted on the synthetic interception path. -#[test] -fn test_intercepted_value_call_does_not_leak_storage_call_stipend() { - let sender_with_value_addr = address!("0000000000000000000000000000000000200006"); - let sender_no_value_addr = address!("0000000000000000000000000000000000200007"); - let sender_with_value = build_measured_call_with_selector( - ACCESS_CONTROL_ADDRESS, - DISABLE_VOLATILE_DATA_ACCESS_SELECTOR, - 1, - ); - let sender_no_value = build_measured_call_with_selector( - ACCESS_CONTROL_ADDRESS, - DISABLE_VOLATILE_DATA_ACCESS_SELECTOR, - 0, - ); - - let mut db = setup_db(&[ - (sender_with_value_addr, sender_with_value), - (sender_no_value_addr, sender_no_value), - ]); - db.set_account_balance(sender_with_value_addr, U256::from(1_000_000_000u128)); - db.set_account_balance(sender_no_value_addr, U256::from(1_000_000_000u128)); - - let tx_with_value = TxEnvBuilder::default() - .caller(CALLER) - .call(sender_with_value_addr) - .gas_limit(100_000_000) - .build_fill(); - let result_with_value = transact(MegaSpecId::REX4, &mut db, tx_with_value).unwrap(); - let gas_delta_with_value = match &result_with_value.result { - ExecutionResult::Success { output, .. } => { - U256::from_be_slice(&output.data()[..32]).to::() - } - other => panic!("expected Success, got {other:?}"), - }; - - let tx_no_value = TxEnvBuilder::default() - .caller(CALLER) - .call(sender_no_value_addr) - .gas_limit(100_000_000) - .build_fill(); - let result_no_value = transact(MegaSpecId::REX4, &mut db, tx_no_value).unwrap(); - let gas_delta_no_value = match &result_no_value.result { - ExecutionResult::Success { output, .. } => { - U256::from_be_slice(&output.data()[..32]).to::() - } - other => panic!("expected Success, got {other:?}"), - }; - - let diff = gas_delta_with_value.saturating_sub(gas_delta_no_value); - assert!( - diff >= 6000, - "synthetic intercepted value call should not leak STORAGE_CALL_STIPEND. \ - gas_delta_with_value={gas_delta_with_value}, gas_delta_no_value={gas_delta_no_value}, diff={diff}" - ); -} - -/// Nested value-transferring calls: A calls B with value, B calls C with value. -/// Both B and C should independently receive and burn their own `STORAGE_CALL_STIPEND`, -/// exercising the stipend stack push/pop alignment across multiple depth levels. -#[test] -fn test_nested_value_transfer_stipend_stack() { - // MIDDLE_CONTRACT: emits LOG1, then CALLs RECEIVER with value=1 wei - let middle_code = BytecodeBuilder::default() - // Emit LOG1 first (uses storage gas from B's stipend) - .push_number(0xaaaa_u64) // topic1 - .push_number(0_u64) // size - .push_number(0_u64) // offset - .append(LOG1) - // Then CALL RECEIVER with value=1 (C gets its own stipend) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(RECEIVER) - .push_number(100_000_u64) // gas (enough for the nested call) - .append(CALL) - .append(POP) // discard success flag - .append(STOP) - .build(); - - // RECEIVER: emits LOG1 (uses storage gas from C's stipend) - let receiver_code = build_log1_receiver(); - - // SENDER_CONTRACT: CALLs MIDDLE_CONTRACT with value=1 - let sender_code = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value = 1 wei - .push_address(MIDDLE_CONTRACT) - .push_number(1_000_000_u64) // gas (enough for nested calls) - .append(CALL) - // Return success flag - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build(); - - let mut db = setup_db(&[ - (SENDER_CONTRACT, sender_code), - (MIDDLE_CONTRACT, middle_code), - (RECEIVER, receiver_code), - ]); - // MIDDLE_CONTRACT needs balance to forward value to RECEIVER - db.set_account_balance(MIDDLE_CONTRACT, U256::from(1_000_000_000u128)); - - let result = transact(MegaSpecId::REX4, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::from(1), - "nested value-transfer calls should both succeed with independent stipends" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -/// When a frame-local state growth limit is exceeded during a value-transferring CALL to a -/// new address, the `STORAGE_CALL_STIPEND` must not leak to the parent. -/// -/// Under REX4, per-frame budgets make this a frame-local revert (not a TX halt). -/// The stipend is burned via `before_frame_return_result`; this test verifies the burn -/// is correct even when the child frame never actually executes (early-return from -/// `before_frame_init`). -/// -/// `rescue_gas` also caps rescued gas at the pre-stipend limit (via -/// `current_frame_stipend`), which covers the TX-level rescue paths in -/// `before_frame_init` and `after_frame_run`. Those paths are difficult to trigger in -/// integration tests because Rex4 per-frame budgets fire before TX-level checks. -#[test] -fn test_stipend_not_leaked_on_frame_local_limit_exceed() { - // SENDER_CONTRACT does CALL(gas=0, to=NEW_EMPTY_ADDR, value=1). - // NEW_EMPTY_ADDR is not in the DB, so state_growth records +1 in before_frame_init. - // With state_growth_limit=1, the child's frame-local budget is floor(1 * 98/100) = 0, - // so the +1 growth exceeds the child's budget and it reverts. - let sender_code = build_transfer_contract(NEW_EMPTY_ADDR); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - - let tx = default_tx(); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(1); - let result = transact_with_limits(MegaSpecId::REX4, &mut db, tx, limits).unwrap(); - - // Parent catches the child's frame-local revert; TX succeeds. - match &result.result { - ExecutionResult::Success { output, .. } => { - let success_flag = U256::from_be_slice(&output.data()[..32]); - assert_eq!( - success_flag, - U256::ZERO, - "inner CALL should revert due to frame-local state growth exceed" - ); - } - other => panic!("expected Success (inner revert), got {other:?}"), - } - - // Verify gas accounting: if the 23,000 stipend leaked, gas_used would be ~23,000 lower. - let gas_used = match &result.result { - ExecutionResult::Success { gas_used, .. } => *gas_used, - _ => unreachable!(), - }; - // Intrinsic gas (~21,000) + CALL costs (cold access 2,600 + new account 25,000 + - // value transfer 9,000 + gas_stipend deduction 2,300) + parent opcodes. - // Total should be well above 50,000. If stipend leaked, gas_used would drop by ~23,000. - assert!( - gas_used > 50_000, - "gas_used {gas_used} is too low — STORAGE_CALL_STIPEND may have leaked to parent" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs b/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs deleted file mode 100644 index a55e63e9c..000000000 --- a/crates/mega-evm/tests/_pending/rex5/apply_pending_changes_gas_budget.rs +++ /dev/null @@ -1,325 +0,0 @@ -//! End-to-end regression tests for the REX5 `applyPendingChanges()` system -//! call gas budget. -//! -//! Pre-fix: the pre-block `applyPendingChanges()` call ran with revm's -//! hard-coded 30M default. On a REX5 activation block where SALT bucket -//! capacity inflates the role-rotation `SSTORE`s past 30M, the call would OOG -//! and the rotation would never apply. -//! -//! Post-fix: `transact_apply_pending_changes` issues the call with -//! `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)`, so any block whose -//! live budget covers the role-rotation cost succeeds. -//! -//! The apply-pending-change tests pin both halves of the invariant under one shared -//! heavy-SALT scenario: -//! -//! - [`test_rex5_apply_pending_changes_succeeds_under_heavy_storage_gas`] exercises the production -//! path end-to-end via the block executor and asserts the rotation commits. A regression that -//! routes the call back through the upstream `transact_system_call` (30M cap) fails here even -//! though the unit tests in `system/sequencer_registry.rs` still pass. -//! - [`test_rex5_apply_pending_changes_oogs_under_upstream_30m_cap`] pins the *baseline* — that the -//! upstream 30M cap really is insufficient under this scenario — by invoking the system call -//! directly with the upstream default. If that test ever starts to pass (e.g. because role -//! rotation becomes cheap), the fix above no longer protects anything and the scenario itself -//! needs to be re-tuned. -//! -//! The EIP-2935 and EIP-4788 tests pin the isolation invariant: REX5 widens only -//! `SequencerRegistry.applyPendingChanges()`. The default `transact_system_call` -//! path used by the upstream EIP pre-block helpers must keep the historical 30M -//! budget, even when the live block gas limit is higher. - -use std::convert::Infallible; - -use alloy_evm::{block::BlockExecutor, Evm, EvmEnv}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, BucketHasher, BucketId, EthHaltReason, - MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaContext, MegaEvm, MegaEvmFactory, - MegaHaltReason, MegaHardfork, MegaHardforkConfig, MegaSpecId, OpHaltReason, - SequencerRegistryConfig, TestExternalEnvs, MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_REGISTRY_CODE, SEQUENCER_REGISTRY_CODE_HASH, -}; -use mega_system_contracts::sequencer_registry::{ - storage_slots::{ - CURRENT_SYSTEM_ADDRESS, PENDING_SYSTEM_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK, - }, - ISequencerRegistry, -}; -use revm::{ - context::{result::ExecutionResult, BlockEnv}, - database::{Database as _, State}, - handler::EvmTr, - state::{AccountInfo, Bytecode}, -}; - -const NEW_SYSTEM_ADDRESS: Address = address!("3000000000000000000000000000000000000003"); -const BOOTSTRAP_SEQUENCER: Address = address!("4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("5000000000000000000000000000000000000005"); - -const ACTIVATION_BLOCK: u64 = 1000; - -/// Bucket that every SALT lookup is routed to under [`SingleBucketHasher`]. -const HEAVY_BUCKET_ID: BucketId = 100_000; -/// Capacity = 2000 × `MIN_BUCKET_SIZE` (256). Yields a 2000× multiplier, so each -/// zero→nonzero `SSTORE` charges ≈ `20_000 × 1999` ≈ 40M of dynamic storage gas -/// (REX `SSTORE_SET_STORAGE_GAS_BASE × (multiplier - 1)`). `applyPendingChanges()` -/// triggers two such writes (history-length slot and the first history element), -/// totaling ≈ 80M — well above the upstream 30M cap and well below the 250M -/// block budget below. -const HEAVY_BUCKET_CAPACITY: u64 = 512_000; -/// Block gas limit chosen high enough to cover the inflated rotation cost. -const BLOCK_GAS_LIMIT: u64 = 250_000_000; - -/// Routes every account/slot to a single bucket so that one -/// `with_bucket_capacity()` call deterministically inflates every `SSTORE` -/// the system call performs, regardless of the slot keys involved. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - HEAVY_BUCKET_ID - } -} - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -fn create_evm_env(gas_limit: u64) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX5; - let block_env = BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -/// Pre-deploys `SequencerRegistry` with a pending system address change due -/// at [`ACTIVATION_BLOCK`] and funds both system addresses. Deploy is skipped -/// during pre-execution because the account already has the registry code, so -/// the heavy SALT setup only bites the SSTOREs from `applyPendingChanges()`. -fn seed_db_with_pending_change() -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(NEW_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - MEGA_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - NEW_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(ACTIVATION_BLOCK), - ) - .unwrap(); - - db -} - -/// Heavy SALT environment: the single bucket is configured with a 2000× -/// multiplier, so any zero→nonzero `SSTORE` performed by -/// `applyPendingChanges()` costs ≈ 40M dynamic storage gas. -fn heavy_external_envs() -> TestExternalEnvs { - TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET_ID, HEAVY_BUCKET_CAPACITY) -} - -fn assert_30m_system_call_oog(result: &ExecutionResult, system_call_name: &str) { - assert!( - matches!( - result, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(OpHaltReason::Base(EthHaltReason::OutOfGas(_))), - .. - } - ), - "{system_call_name} must halt with OOG under the upstream 30M cap with heavy SALT. \ - Result: {result:?}", - ); -} - -/// Without the fix, `applyPendingChanges()` would OOG on the first -/// zero→nonzero `SSTORE` (≈ 40M storage gas alone, > the upstream 30M cap) -/// and `apply_pre_execution_changes()` would error. With the fix, the live -/// 250M block budget is used and the rotation commits. -#[test] -fn test_rex5_apply_pending_changes_succeeds_under_heavy_storage_gas() { - let mut db = seed_db_with_pending_change(); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let chain_spec = MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()); - let receipt_builder = OpAlloyReceiptBuilder::default(); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, receipt_builder); - - let block_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx, - create_evm_env(BLOCK_GAS_LIMIT), - ); - executor.apply_pre_execution_changes().expect( - "applyPendingChanges() must succeed under the live block gas budget — \ - a regression here means the system call was capped at the upstream 30M default", - ); - - // The system address rotation only takes effect if `applyPendingChanges()` ran - // to completion. This proves the inflated SSTOREs were actually charged and - // committed, not that the call simply early-returned. - let resolved = executor.evm().ctx_ref().system_address(); - assert_eq!(resolved, NEW_SYSTEM_ADDRESS, "Pending system address change must be applied"); - - assert_eq!( - executor - .evm_mut() - .db_mut() - .storage(SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) - .unwrap(), - U256::ZERO, - "Pending system address slot must be cleared after applyPendingChanges() commits", - ); - assert_eq!( - executor - .evm_mut() - .db_mut() - .storage(SEQUENCER_REGISTRY_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK) - .unwrap(), - U256::ZERO, - "System address activation slot must be cleared after applyPendingChanges() commits", - ); -} - -/// Pins the regression *baseline*: under the same heavy-SALT scenario, a -/// system call issued with the upstream-fixed 30M cap MUST fail. If this test -/// ever starts to pass, role rotation has become cheap enough for the -/// upstream default and the success test above no longer proves the fix is -/// load-bearing — the SALT setup needs to be re-tuned (or the fix retired). -/// -/// The literal `30_000_000` here is intentional: it mirrors revm's -/// hard-coded `SystemCallTx::new_system_tx_with_caller` gas limit and the -/// constant in [`mega_evm::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR`]. -/// We don't import the constant so that this assertion is a structural -/// check on the upstream literal, not a circular check on our floor. -#[test] -fn test_rex5_apply_pending_changes_oogs_under_upstream_30m_cap() { - let mut db = seed_db_with_pending_change(); - - let context = MegaContext::new(&mut db, MegaSpecId::REX5) - .with_external_envs(heavy_external_envs().into()) - .with_block(BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }); - let mut evm = MegaEvm::new(context); - - let calldata = ISequencerRegistry::applyPendingChangesCall {}.abi_encode(); - let result = evm - .transact_system_call_with_gas_limit( - alloy_eips::eip4788::SYSTEM_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, - Bytes::from(calldata), - 30_000_000, // revm upstream's hard-coded system-call gas limit. - ) - .expect("system call should not surface an EVMError"); - - assert_30m_system_call_oog(&result.result, "applyPendingChanges()"); -} - -/// REX5 only widens `SequencerRegistry.applyPendingChanges()`. The EIP-2935 -/// default system-call path must keep using revm's 30M budget, even when the -/// live block gas limit is larger. -#[test] -fn test_rex5_eip2935_blockhashes_keeps_upstream_30m_cap_under_heavy_storage_gas() { - let mut db = MemoryDatabase::default(); - let bytecode = Bytecode::new_raw(alloy_eips::eip2935::HISTORY_STORAGE_CODE.clone()); - db.insert_account_info( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - let context = MegaContext::new(&mut db, MegaSpecId::REX5) - .with_external_envs(heavy_external_envs().into()) - .with_block(BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }); - let mut evm = MegaEvm::new(context); - let result = evm - .transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - B256::from([0x29; 32]).0.into(), - ) - .expect("EIP-2935 system call should not surface an EVMError"); - - assert_30m_system_call_oog(&result.result, "EIP-2935 blockhashes system call"); -} - -/// Same invariant for EIP-4788: REX5's widened budget must not leak into the -/// default beacon-roots system-call path. -#[test] -fn test_rex5_eip4788_beacon_root_keeps_upstream_30m_cap_under_heavy_storage_gas() { - let mut db = MemoryDatabase::default(); - let bytecode = Bytecode::new_raw(alloy_eips::eip4788::BEACON_ROOTS_CODE.clone()); - db.insert_account_info( - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); - let context = MegaContext::new(&mut db, MegaSpecId::REX5) - .with_external_envs(heavy_external_envs().into()) - .with_block(BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }); - let mut evm = MegaEvm::new(context); - let result = evm - .transact_system_call( - alloy_eips::eip4788::SYSTEM_ADDRESS, - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - B256::from([0x47; 32]).0.into(), - ) - .expect("EIP-4788 system call should not surface an EVMError"); - - assert_30m_system_call_oog(&result.result, "EIP-4788 beacon-roots system call"); -} diff --git a/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs b/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs deleted file mode 100644 index 01457e980..000000000 --- a/crates/mega-evm/tests/_pending/rex5/create2_empty_initcode.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! Regression suite for the REX5+ CREATE2 wrapper `len == 0` short-circuit. -//! -//! Canonical revm CREATE2 ignores the `offset` operand when `initcode_len == 0`: -//! no offset conversion, no memory expansion, no slice, no keccak. The initcode -//! hash is `KECCAK_EMPTY` and the deploy address is derived from -//! `creator.create2(salt, KECCAK_EMPTY)`. -//! -//! The Mega CREATE2 wrapper used to observe `offset` unconditionally, which -//! diverged from canonical revm in two ways: -//! -//! - A valid `CREATE2(value=0, offset=U256::MAX, len=0, salt=0)` halted inside -//! `as_usize_or_fail!(offset)` instead of succeeding with empty initcode. -//! - A `CREATE2(_, offset=large_finite, len=0, _)` over-charged memory-expansion EVM gas and (under -//! REX5+) recorded `resize_gas` into the `compute_gas` tracker even though canonical revm did -//! neither. -//! -//! REX5+ short-circuits `len == 0` before offset conversion / `resize_memory!` -//! / slice / `keccak256`, using the pre-computed `KECCAK_EMPTY`. Pre-REX5 keeps -//! the "observe offset, resize, slice, hash" sequence verbatim for replay -//! parity. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{CREATE2, STOP}, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); - -/// Runs a tx that invokes a CREATE2 contract built from raw bytecode and returns -/// the execution result plus the post-tx `compute_gas` tracker reading. -fn transact_create2_with_code( - spec: MegaSpecId, - code: Bytes, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// Builds bytecode that runs `CREATE2(value=0, offset, size=0, salt=0)`. -/// `offset` is pushed as a full 32-byte value so callers can exercise non-canonical -/// values such as `U256::MAX` or `1 << 30` that the short-circuit must tolerate. -fn build_create2_empty_initcode_at_offset(offset: U256) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // salt (depth 3) - .push_number(0_u64) // size = 0 (depth 2) - .push_u256(offset) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build() -} - -/// REX5: `CREATE2(len=0, offset=U256::MAX)` MUST succeed. -/// -/// Pins that the wrapper short-circuits before offset conversion when -/// `len == 0` — without the short-circuit, `as_usize_or_fail!(U256::MAX)` -/// would halt with `InvalidOperandOOG`. Post-short-circuit the initcode hash -/// is `KECCAK_EMPTY` and the inner CREATE2 deploys empty code at the -/// deterministic address `creator.create2(0, KECCAK_EMPTY)`. -#[test] -fn test_rex5_create2_len_zero_offset_max_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::MAX); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - result.is_success(), - "REX5 CREATE2(len=0, offset=U256::MAX) must succeed; got {result:?}", - ); -} - -/// REX5: the `len == 0` short-circuit MUST NOT engage when `len > 0`. -/// `CREATE2(len=1, offset=U256::MAX, ...)` must halt inside -/// `as_usize_or_fail!(offset)`, not silently succeed with `KECCAK_EMPTY` as -/// the initcode hash. Pins the `initcode_len.is_zero()` guard against a -/// regression that broadens it (e.g. an accidental `<=` comparison). -#[test] -fn test_rex5_create2_len_nonzero_offset_max_still_halts() { - let code = BytecodeBuilder::default() - .push_number(0_u64) // salt (depth 3) - .push_number(1_u64) // size = 1 (NON-zero) - .push_u256(U256::MAX) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - matches!(result, ExecutionResult::Halt { .. }), - "REX5 CREATE2(len=1, offset=U256::MAX) must halt — the len==0 short-circuit \ - must not engage for nonzero len; got {result:?}", - ); -} - -/// REX5: `CREATE2(len=0, offset=large_finite)` MUST succeed without paying for -/// memory expansion. Without the short-circuit, `resize_memory!(1<<30, 0)` -/// quadratically prices the implied range — pricing canonical revm explicitly -/// skips when `len == 0`. With the short-circuit the `compute_gas` reading -/// sits near the TX intrinsic baseline rather than balloon to MB-scale. -#[test] -fn test_rex5_create2_len_zero_large_offset_skips_memory_expansion() { - let offset = U256::from(1u64 << 30); - let code = build_create2_empty_initcode_at_offset(offset); - let (result, compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!( - result.is_success(), - "REX5 CREATE2(len=0, offset={offset}) must succeed; got {result:?}", - ); - // The wrapper short-circuit means no `resize_gas` is recorded under REX5, - // so the compute_gas tracker only holds the TX intrinsic (~21k base + a - // handful of bytes of calldata) plus the CREATE2 frame setup (~32k storage - // gas drained from stipend on REX5 — does NOT count against compute_gas). - // A regression that observes the offset would push compute_gas into the - // millions on a `1 << 30` byte range. - assert!( - compute < 100_000, - "REX5 CREATE2(len=0) should not record memory-expansion compute_gas; got {compute}", - ); -} - -/// REX5: `CREATE2(len=0, offset=0)` happy path — the short-circuit must not -/// break the canonical "small offset, empty initcode" success case. -#[test] -fn test_rex5_create2_len_zero_offset_zero_succeeds() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result, _compute) = transact_create2_with_code(MegaSpecId::REX5, code); - assert!(result.is_success(), "REX5 CREATE2(len=0, offset=0) must succeed; got {result:?}",); -} - -/// REX5 vs REX4 deployed-address parity for `len=0, offset=0`. Both must derive -/// the same address `creator.create2(0, KECCAK_EMPTY)` — REX5 via the -/// short-circuit, REX4 via `keccak256(slice_len(0, 0))` which equals -/// `KECCAK_EMPTY`. Equality of `is_success` is a weaker form of address parity; -/// pinning the spec on it would require reading the deployed address out of the -/// execution result, which requires more plumbing. The success-only check is -/// sufficient for the wrapper-level invariant — if the REX5 short-circuit -/// produced a wrong hash, the inner CREATE2 would deploy to a different -/// address but `STOP` would still succeed at that other address. Direct -/// address-equality assertion is left as a follow-up. -#[test] -fn test_create2_len_zero_offset_zero_succeeds_on_both_specs() { - let code = build_create2_empty_initcode_at_offset(U256::ZERO); - let (result_rex5, _) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); - let (result_rex4, _) = transact_create2_with_code(MegaSpecId::REX4, code); - assert!(result_rex5.is_success(), "REX5 must succeed; got {result_rex5:?}"); - assert!(result_rex4.is_success(), "REX4 must succeed; got {result_rex4:?}"); -} diff --git a/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs b/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs deleted file mode 100644 index ed1c754ee..000000000 --- a/crates/mega-evm/tests/_pending/rex5/create2_resize_gas_metering.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Regression suite for the REX5+ CREATE2 wrapper `resize_gas` recording rule. -//! -//! REX5+ validates the salt operand before `resize_memory!` / copy / keccak, -//! and records the memory-expansion gas (`resize_gas`) into the `compute_gas` -//! tracker immediately after `resize_memory!`. Pre-REX5 keeps the original -//! "resize first, salt last, record after inner CREATE2 returns" order -//! verbatim for replay parity. -//! -//! Coverage: -//! - Happy-path CREATE2 with measurable memory expansion succeeds under both specs. -//! - Cross-spec parity: the post-tx `compute_gas` tracker agrees within a small tolerance, pinning -//! that REX5 records `resize_gas` exactly once (no double-count from the trailing late-record -//! block, no miss-count from the early-record path being skipped). -//! - Stack-underflow consistency: a CREATE2 dispatched with only three operands halts with -//! `StackUnderflow` under both specs and leaks no `resize_gas` into the tracker. -//! -//! Failure-path verification (storage-gas OOG / inner CREATE2 halt under REX5 -//! retaining `resize_gas`, pre-REX5 skipping via the trailing block) is -//! delicate to engineer with stable gas tuning and is left to a follow-up. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, -}; -use revm::{ - bytecode::opcode::{CREATE2, STOP}, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); - -/// Builds bytecode that runs `CREATE2(value=0, offset=0, size=initcode_len, salt=0)`. -/// The initcode region is zero-initialized; the canonical CREATE2 keccak256-hashes -/// the bytes and runs the resulting `STOP`-only constructor, deploying empty code. -/// Memory expansion gas inside the wrapper is a function of `initcode_len`. -fn build_create2_contract(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // salt - .push_number(initcode_len) // size - .push_number(0_u64) // offset - .push_number(0_u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// Runs a tx that invokes the CREATE2 contract and returns the execution result and -/// the post-tx `compute_gas` tracker reading. -fn transact_create2(spec: MegaSpecId, initcode_len: u64) -> (ExecutionResult, u64) { - let code = build_create2_contract(initcode_len); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// 32 KiB initcode: memory expansion gas inside the wrapper is in the ~5 K range, -/// large enough that a double-count or miss-count of `resize_gas` would be -/// visible against the cross-spec parity tolerance. -const INITCODE_LEN: u64 = 32 * 1024; - -/// REX5 happy path: CREATE2 with non-trivial memory expansion succeeds. The -/// `compute_gas` tracker registers usage that includes the `resize_gas` recorded -/// in the early-record path. -#[test] -fn test_rex5_create2_with_non_trivial_resize_succeeds() { - let (result, compute) = transact_create2(MegaSpecId::REX5, INITCODE_LEN); - assert!(result.is_success(), "REX5 CREATE2 happy path must succeed; got {result:?}"); - assert!( - compute > 0, - "REX5 compute_gas tracker must register usage including resize_gas; got {compute}", - ); -} - -/// Runs a CREATE2 contract built from raw bytecode (used to construct stack-underflow -/// scenarios that `build_create2_contract` cannot express). Mirrors `transact_create2`. -fn transact_create2_with_code( - spec: MegaSpecId, - code: Bytes, -) -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000_000_000_000_000u128)) - .account_code(CONTRACT, code); - let mut context = - MegaContext::new(&mut db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// CREATE2 dispatched with only three stack operands (value, offset, length; salt -/// absent) must halt with `StackUnderflow` under both specs, and neither spec may -/// leak `resize_gas` into the `compute_gas` tracker on the halt path: -/// -/// - REX5: the wrapper inspects salt at position 3 BEFORE `resize_memory!`, so the early-record -/// block is unreachable when salt is missing. -/// - REX4: the wrapper inspects salt AFTER `resize_memory!`, but the trailing `if resize_gas > 0 { -/// ... }` block is skipped on the `StackUnderflow` halt. -/// -/// Equality of the post-tx `compute_gas` reading across REX4 and REX5 pins this -/// invariant — a regression that records `resize_gas` on either halt path would -/// produce a spec-asymmetric reading. -#[test] -fn test_create2_missing_salt_halts_consistently_across_specs() { - // Three CREATE2 args, salt OMITTED. Stack order from top (depth 0) at the - // CREATE2 instruction: - // depth 0: value - // depth 1: offset - // depth 2: length - // depth 3: → wrapper's `stack.inspect::<3>()` fails → StackUnderflow. - let code = BytecodeBuilder::default() - .push_number(INITCODE_LEN) // length (depth 2) - .push_number(0_u64) // offset (depth 1) - .push_number(0_u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - - let (result_rex5, compute_rex5) = transact_create2_with_code(MegaSpecId::REX5, code.clone()); - let (result_rex4, compute_rex4) = transact_create2_with_code(MegaSpecId::REX4, code); - - // Both specs must halt with StackUnderflow. (Compare via Debug to avoid pinning the - // exact OpHaltReason → EthHaltReason wrapper path.) - let is_stack_underflow = |r: &ExecutionResult| -> bool { - matches!(r, ExecutionResult::Halt { reason, .. } if format!("{reason:?}").contains("StackUnderflow")) - }; - assert!( - is_stack_underflow(&result_rex5), - "REX5 must halt with StackUnderflow; got {result_rex5:?}", - ); - assert!( - is_stack_underflow(&result_rex4), - "REX4 must halt with StackUnderflow; got {result_rex4:?}", - ); - - // Neither spec leaks `resize_gas` into the compute_gas tracker on the - // stack-underflow path. The expected baseline for both specs is the TX - // intrinsic recorded by `validate()` (`record_compute_gas(initial_gas)`) and - // nothing more: - // - // - REX5: salt inspect at position 3 halts BEFORE `resize_memory!`, so the early-record block - // (`if is_rex5_enabled && resize_gas > 0 { ... }`) is never reached. - // - REX4: `resize_memory!` runs and burns EVM gas, but the late-record block at the wrapper's - // tail is skipped when the frame halts on the position-3 salt inspect. - // - // Equality between the two specs pins this consistency: any regression that - // records `resize_gas` on a halted CREATE2 (whether by moving the REX5 early - // record ahead of the salt check, or by running the REX4 late-record despite - // the halt) would produce a spec-asymmetric compute_gas reading exceeding the - // shared intrinsic baseline. - assert_eq!( - compute_rex5, compute_rex4, - "compute_gas must be identical across REX4 ({compute_rex4}) and REX5 ({compute_rex5}) \ - when CREATE2 halts on salt underflow — any divergence indicates resize_gas leaked into \ - the tracker on the halt path", - ); - // Sanity check that what's recorded is just the TX intrinsic (≈21k base + ~9 calldata - // bytes for the CREATE2 contract code). A multi-KiB reading would indicate that the - // wrapper recorded `resize_gas` despite the halt. - assert!( - compute_rex5 < 25_000, - "compute_gas reading should be near the TX intrinsic (~21k) on the halt path, \ - not include the {INITCODE_LEN}-byte resize_gas; got {compute_rex5}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/db_error.rs b/crates/mega-evm/tests/_pending/rex5/db_error.rs deleted file mode 100644 index ec195d2a4..000000000 --- a/crates/mega-evm/tests/_pending/rex5/db_error.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! REX5 DB-error paths added by the system-tx validation and the keyless deploy -//! sandbox rework. -//! -//! Two failure modes need pinning: -//! -//! - **System-tx validate** (`evm/execution.rs`): the new pre-deposit `inspect_account` on -//! `MEGA_SYSTEM_ADDRESS` can surface a database error. The `map_err` must wrap it as -//! `EVMError::Custom` so OP handler returns the canonical fatal-external shape rather than -//! silently dropping the system tx. -//! - **Keyless deploy step 7** (`sandbox/execution.rs`): the deploy-address occupancy read before -//! sandbox setup can surface a database error — pre-REX6 via `basic(deploy_address)`, REX6 via -//! the journaled, cold `inspect_account_code_hash(ctx.journal_mut(), deploy_address)`, which -//! reads only `code_hash` and never hydrates `info.code`. Both arms' `map_err` must wrap it as -//! the selector-only `KeylessDeployError::InternalError` and surface as `Revert` (validation- -//! style — no sandbox state to merge). - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, TxKind, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - revm::context::result::ExecutionResult, - sandbox::{ - decode_error_result, - tests::{CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX}, - KeylessDeployError, - }, - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - EVMError, IKeylessDeploy, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, - KEYLESS_DEPLOY_ADDRESS, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, -}; -use revm::{context::TxEnv, inspector::NoOpInspector}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); - -/// REX5+ keyless deploy must reject with `InternalError` (selector-only revert) when the -/// pre-sandbox `basic(deploy_address)` DB read fails. The signer MUST NOT be charged -/// and no replay barrier may be installed, because the sandbox never ran. -#[test] -fn test_keyless_deploy_address_db_error_maps_to_internal_error_revert() { - let mut inner = MemoryDatabase::default(); - inner.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - inner.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let mut db = ErrorInjectingDatabase::new(inner); - // Step 7 of `execute_keyless_deploy_call` does `journal.database.basic(deploy_address)` - // to ensure the deploy address has no code. Fail that specific read. - db.fail_on_account = Some(CREATE2_FACTORY_CONTRACT); - - let external_envs = TestExternalEnvs::::new(); - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), - gasLimitOverride: U256::from(10_000_000u64), - } - .abi_encode(); - - let mut context = - MegaContext::new(db, MegaSpecId::REX5).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 30_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let res = alloy_evm::Evm::transact(&mut evm, tx).expect("outer EVM error not expected"); - - let revert_output = match res.result { - ExecutionResult::Revert { output, .. } => output, - other => panic!("expected outer Revert, got {other:?}"), - }; - let decoded = decode_error_result(&revert_output) - .expect("revert payload must decode to a known KeylessDeployError"); - assert!( - matches!(decoded, KeylessDeployError::InternalError), - "DB read failure on deploy address must surface as selector-only InternalError, got {decoded:?}", - ); - - // Signer untouched: the pre-sandbox failure path is validation-shaped, so the signer - // must not be fee-debited and the nonce must remain 0. - let signer_after = - res.state.get(&CREATE2_FACTORY_DEPLOYER).cloned().map(|acc| acc.info).unwrap_or_default(); - assert_eq!( - signer_after.nonce, 0, - "DB error before sandbox must not bump signer nonce (no replay barrier)", - ); -} - -/// REX6 twin of the test above: under REX6 the step-7 occupancy check reads the deploy address -/// through the journaled, cold `inspect_account_code_hash`, not the raw `basic`. That read's -/// `map_err` DB-error arm must still surface as the selector-only `InternalError` revert, signer -/// untouched. Without this the REX6 branch's error path is never exercised (the raw-`basic` test -/// above only covers the pre-REX6 arm). -#[test] -fn test_keyless_deploy_address_db_error_maps_to_internal_error_revert_rex6() { - let mut inner = MemoryDatabase::default(); - inner.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - inner.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let mut db = ErrorInjectingDatabase::new(inner); - // Step 7 under REX6 does `inspect_account_code_hash(ctx.journal_mut(), deploy_address)`; fail - // that read. - db.fail_on_account = Some(CREATE2_FACTORY_CONTRACT); - - let external_envs = TestExternalEnvs::::new(); - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), - gasLimitOverride: U256::from(10_000_000u64), - } - .abi_encode(); - - let mut context = - MegaContext::new(db, MegaSpecId::REX6).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 30_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let res = alloy_evm::Evm::transact(&mut evm, tx).expect("outer EVM error not expected"); - - let revert_output = match res.result { - ExecutionResult::Revert { output, .. } => output, - other => panic!("expected outer Revert, got {other:?}"), - }; - let decoded = decode_error_result(&revert_output) - .expect("revert payload must decode to a known KeylessDeployError"); - assert!( - matches!(decoded, KeylessDeployError::InternalError), - "REX6 inspect_account_code_hash DB failure on deploy address must surface as InternalError, got {decoded:?}", - ); - - let signer_after = - res.state.get(&CREATE2_FACTORY_DEPLOYER).cloned().map(|acc| acc.info).unwrap_or_default(); - assert_eq!( - signer_after.nonce, 0, - "DB error before sandbox must not bump signer nonce (no replay barrier)", - ); -} - -/// REX5+ keyless deploy must reject with `InternalError` (selector-only revert) when the -/// pre-sandbox signer nonce read fails. `get_account_nonce` is the first DB read against -/// the deploy signer, and its DB-fallback `map_err` is the only place this failure can be -/// classified before the sandbox is even constructed. -#[test] -fn test_keyless_signer_nonce_db_error_maps_to_internal_error_revert() { - let mut inner = MemoryDatabase::default(); - inner.set_account_balance( - CREATE2_FACTORY_DEPLOYER, - U256::from(1_000_000_000_000_000_000_000u128), - ); - inner.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let mut db = ErrorInjectingDatabase::new(inner); - // Step 5 of `execute_keyless_deploy_call` reads the signer's nonce via - // `get_account_nonce` (journal cache → `journal.database.basic(signer)` fallback). - // Fail that fallback path. - db.fail_on_account = Some(CREATE2_FACTORY_DEPLOYER); - - let external_envs = TestExternalEnvs::::new(); - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(CREATE2_FACTORY_TX), - gasLimitOverride: U256::from(10_000_000u64), - } - .abi_encode(); - - let mut context = - MegaContext::new(db, MegaSpecId::REX5).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 30_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let res = alloy_evm::Evm::transact(&mut evm, tx).expect("outer EVM error not expected"); - - let revert_output = match res.result { - ExecutionResult::Revert { output, .. } => output, - other => panic!("expected outer Revert, got {other:?}"), - }; - let decoded = decode_error_result(&revert_output) - .expect("revert payload must decode to a known KeylessDeployError"); - assert!( - matches!(decoded, KeylessDeployError::InternalError), - "signer nonce DB read failure must surface as InternalError, got {decoded:?}", - ); - - // Pre-sandbox failure: signer must not be touched, no replay barrier. - let signer_after = - res.state.get(&CREATE2_FACTORY_DEPLOYER).cloned().map(|acc| acc.info).unwrap_or_default(); - assert_eq!( - signer_after.nonce, 0, - "DB error before sandbox must not bump signer nonce (no replay barrier)", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs b/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs deleted file mode 100644 index 189fbfb49..000000000 --- a/crates/mega-evm/tests/_pending/rex5/eip7702_state_growth.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! Tests for EIP-7702 authority state-growth tracking. -//! -//! REX5 adds state-growth accounting for EIP-7702 authority accounts during pre-execution. -//! Only valid authorizations whose authority account was not already present count as state growth. -//! -//! Pre-REX5, EIP-7702 authority accounts are not counted toward state growth. - -use alloy_eips::eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}; -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, -}; -use revm::{ - context::{ - result::{ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - state::Bytecode, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000800000"); -const CALLEE: Address = address!("0000000000000000000000000000000000800001"); -const AUTHORITY_A: Address = address!("0000000000000000000000000000000000800010"); -const AUTHORITY_B: Address = address!("0000000000000000000000000000000000800011"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact_with_limits( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, - limits: EvmTxRuntimeLimits, -) -> (ResultAndState, LimitUsage) { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (r, usage) -} - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> (ResultAndState, LimitUsage) { - transact_with_limits(spec, db, tx, EvmTxRuntimeLimits::from_spec(spec)) -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// A type-4 transaction with one new authority should count +1 state growth in REX5. -/// -/// The authorization is valid and the authority account does not exist before auth processing. -#[test] -fn test_rex5_new_authority_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 1, "state growth should include the new authority account"); - - let authority_account = result.state.get(&AUTHORITY_A).expect("authority should be updated"); - assert_eq!(authority_account.info.nonce, 1, "successful auth should increment authority nonce"); - assert_eq!( - authority_account.info.code_hash, - Bytecode::new_eip7702(delegate).hash_slow(), - "successful auth should install EIP-7702 delegation code", - ); - assert!( - authority_account.info.code.as_ref().is_some_and(|code| code.is_eip7702()), - "successful auth should write EIP-7702 bytecode", - ); -} - -/// REX5 with two new authorities should count +2 state growth. -#[test] -fn test_rex5_two_new_authorities_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![ - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - ), - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_B), - ), - ]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 2, "state growth should include both new authority accounts"); -} - -/// Repeated authorizations for the same new authority should only count the authority once. -/// -/// The first authorization creates the authority account and increments its nonce. -/// The second authorization has the original nonce, so it is skipped by EIP-7702 auth processing. -#[test] -fn test_rex5_duplicate_new_authority_counts_once() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![ - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - ), - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - ), - ]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 1, "duplicate authority must only count once"); -} - -/// REX5 should not count state growth when a valid EIP-7702 authority already exists. -/// -/// Delegating an existing authority modifies that account but does not create a net-new state -/// entry. -#[test] -fn test_rex5_existing_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)) - .account_balance(AUTHORITY_A, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 0, "existing authority must not count as state growth"); - - let authority_account = - result.state.get(&AUTHORITY_A).expect("authority should still be updated"); - assert_eq!( - authority_account.info.nonce, 1, - "valid authorization should increment the existing authority nonce", - ); - assert_eq!( - authority_account.info.code_hash, - Bytecode::new_eip7702(delegate).hash_slow(), - "valid authorization should still install delegation code on an existing authority", - ); -} - -/// REX5 should not count state growth for a resolved authority whose authorization is invalid. -#[test] -fn test_rex5_nonce_mismatch_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 1 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 0, "invalid authorization must not count as state growth"); - assert!( - result.state.get(&AUTHORITY_A).is_none_or(|account| !account.is_touched()), - "nonce-mismatched authority should not be modified", - ); -} - -/// An authorization with an invalid (unrecoverable) authority should NOT count -/// toward state growth, since `authority()` returns `None`. -#[test] -fn test_rex5_invalid_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Invalid, - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!( - usage.state_growth, 0, - "invalid authority should not count toward state growth: {}", - usage.state_growth - ); - assert!(!result.state.contains_key(&AUTHORITY_A), "invalid authority should not touch state"); -} - -/// A valid authority with non-EIP-7702 code should be skipped and should not count as state -/// growth. -#[test] -fn test_rex5_non_eip7702_authority_no_state_growth() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - db.set_account_code(AUTHORITY_A, BytecodeBuilder::default().stop().build()); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - assert_eq!(usage.state_growth, 0, "non-EIP-7702 authority code must not count as state growth"); - assert!( - result.state.get(&AUTHORITY_A).is_none_or(|account| !account.is_touched()), - "non-EIP-7702 authority should not be modified", - ); -} - -/// A new authority can overflow the state-growth limit before the first frame starts. -/// -/// The EIP-7702 auth list is still applied during pre-execution, but the outer call halts before -/// the first frame is initialized. -#[test] -fn test_rex5_new_authority_state_growth_limit_exceeded_before_first_frame() { - let delegate = address!("0000000000000000000000000000000000900001"); - let authorization_list = vec![RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(1), address: delegate, nonce: 0 }, - RecoveredAuthority::Valid(AUTHORITY_A), - )]; - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(1_000_000) - .authorization_list_recovered(authorization_list) - .build_fill(); - - let (result, usage) = transact_with_limits( - MegaSpecId::REX5, - &mut db, - tx, - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0), - ); - - assert!(matches!( - &result.result, - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit: 0, actual: 1 }, - .. - } - )); - assert_eq!(usage.state_growth, 1, "authority creation should still be recorded before halt"); - assert!( - result.state.get(&CALLEE).is_none_or(|account| !account.is_touched()), - "first frame should not start once pre-execution state growth already exceeds the limit", - ); - - let authority_account = - result.state.get(&AUTHORITY_A).expect("pre-execution authority update should be preserved"); - assert_eq!( - authority_account.info.nonce, 1, - "auth-list processing should still increment the authority nonce before the halt", - ); - assert_eq!( - authority_account.info.code_hash, - Bytecode::new_eip7702(delegate).hash_slow(), - "auth-list processing should still write the delegation code before the halt", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs b/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs deleted file mode 100644 index c70e692e0..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_empty_code_logs.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! Regression suite for the REX5+ `KeylessDeploy` empty-code log preservation. -//! -//! When a `KeylessDeploy` sandbox CREATE succeeds with empty runtime bytecode, -//! `process_sandbox_transact_result` used to bucket the outcome with revert / -//! halt failures and drop the constructor's emitted logs. Sandbox state (signer -//! nonce bump, journal writes) still persisted, so the parent receipt's logs -//! disagreed with the on-chain state. -//! -//! REX5+ now routes this through `SandboxCompletion::EmptyCode { logs, .. }`, -//! which the outer `execute_keyless_deploy_call` forwards via `ctx.log(log)` -//! before returning success-style with `EmptyCodeDeployed` errorData. The -//! Solidity ABI shape `EmptyCodeDeployed(uint64 gasUsed)` is intentionally -//! unchanged — only the in-band log forwarding is fixed. -//! -//! Pre-REX5 collapses empty-code into -//! `SandboxCompletion::ExecutionFailed { error: EmptyCodeDeployed, .. }` so -//! logs are dropped, preserving the frozen replay behavior. - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{calculate_keyless_deploy_address, decode_error_result, KeylessDeployError}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, -}; -use revm::{ - bytecode::opcode::{LOG1, MSTORE, RETURN, STOP}, - context::TxEnv, - inspector::NoOpInspector, -}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); -const SIGNED_GAS_PRICE: u128 = 100_000_000_000; -const SIGNED_GAS_LIMIT: u64 = 100_000; -const OUTER_GAS_LIMIT: u64 = 30_000_000; -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -/// Constructor that emits a single `LOG1` with a fixed topic and `data = [0xde, -/// 0xad, 0xbe, 0xef]` then RETURNs empty runtime bytecode. The empty RETURN -/// triggers the `EmptyCodeDeployed` reclassification inside the sandbox. -/// -/// Layout (annotated PUSH-immediates so the offsets are auditable): -/// -/// ```text -/// PUSH4 0xdeadbeef // log data word -/// PUSH1 0x00 // memory offset (store at slot 0) -/// MSTORE // mem[0..32] = 0x...deadbeef (right-aligned in word) -/// -/// PUSH32 // topic for LOG1 -/// PUSH1 0x04 // log data size (4 bytes) -/// PUSH1 0x1c // log data offset (32 - 4 = 28) -/// LOG1 -/// -/// PUSH1 0x00 // RETURN size = 0 (empty runtime code) -/// PUSH1 0x00 // RETURN offset = 0 -/// RETURN -/// ``` -fn build_log1_then_empty_return_init_code(topic: B256) -> Bytes { - let log_data_word: u32 = 0xdead_beef; - BytecodeBuilder::default() - // mem[0..32] = log data, right-aligned in the 32-byte word - .push_bytes(log_data_word.to_be_bytes()) - .push_number(0_u8) - .append(MSTORE) - // LOG1(offset=28, size=4, topic) - .push_bytes(topic.as_slice()) - .push_number(4_u8) - .push_number(0x1c_u8) - .append(LOG1) - // RETURN(offset=0, size=0) - .push_number(0_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Constructor that emits no logs and RETURNs empty runtime bytecode. Used to -/// confirm the `SandboxCompletion::EmptyCode` wiring does not synthesize spurious -/// logs. -fn build_no_logs_empty_return_init_code() -> Bytes { - BytecodeBuilder::default() - .push_number(0_u8) // RETURN size - .push_number(0_u8) // RETURN offset - .append(RETURN) - .append(STOP) // unreachable; defensive - .build() -} - -/// Builds a deterministic pre-EIP-155 keyless tx with the given init code. -/// Copy of `keyless_fee_free.rs`'s helper — the keyless test files are -/// intentionally self-contained. -fn build_keyless_tx_with_init_code(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - (tx_bytes, signer) -} - -/// Runs the outer `keylessDeployCall` and returns the parent `ExecutionResult`. -/// -/// `gas_limit_override` matters under pre-REX5: the sandbox runs as a normal -/// fee-paying tx and debits `gas_limit_override × signed_gas_price` from the -/// signer at pre-execution. REX5 makes the sandbox fee-free, so the override -/// can be arbitrarily large there. Tests that exercise REX4 need a modest -/// override so the funded signer balance covers the upfront debit. -fn run_keyless_outer( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, -) -> ExecutionResult { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: OUTER_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not fail at the EVM-error level") -} - -/// Decode the `IKeylessDeploy::keylessDeployReturn` payload from the outer Success -/// output and return the contained `errorData` bytes. -fn extract_error_data(result: &ExecutionResult) -> Bytes { - let output = match result { - ExecutionResult::Success { output, .. } => output.data().clone(), - other => panic!( - "keyless empty-code path must return Success-style (errorData carries the failure); \ - got {other:?}", - ), - }; - let decoded = IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output) - .expect("outer Success output must decode as keylessDeployReturn"); - decoded.errorData -} - -/// REX5: keyless init code that emits `LOG1` and then RETURNs empty runtime bytecode -/// MUST surface the log in the parent receipt, and the outer `errorData` MUST decode -/// as `EmptyCodeDeployed(gasUsed)`. Replay barrier (signer nonce bump) MUST still -/// persist. -#[test] -fn test_rex5_keyless_empty_code_forwards_log_to_parent_receipt() { - let topic = - B256::from_slice(&hex!("ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11ee11")); - let init_code = build_log1_then_empty_return_init_code(topic); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // signer is intentionally unfunded — REX5 fee-free sandbox needs no signer balance. - - let result = - run_keyless_outer(MegaSpecId::REX5, &mut db, keyless_tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - - // The wire shape is success-style with errorData = EmptyCodeDeployed. - let error_data = extract_error_data(&result); - let decoded_err = decode_error_result(&error_data); - assert!( - matches!(decoded_err, Some(KeylessDeployError::EmptyCodeDeployed { .. })), - "REX5 empty-code path must surface EmptyCodeDeployed in errorData; got {decoded_err:?}", - ); - - // Replay barrier: the signer nonce must have advanced even on the empty-code path, - // because state still merges into the parent. - let signer_after = { - use revm::Database as _; - db.basic(signer).expect("db read should succeed").unwrap_or_default() - }; - assert_eq!( - signer_after.nonce, 1, - "REX5 empty-code path must consume the replay barrier (signer nonce bump)", - ); - - // The parent receipt MUST contain the constructor's LOG1 with the expected topic and - // emitter address. Pre-fix behavior dropped the log entirely. - let logs = result.logs(); - assert_eq!( - logs.len(), - 1, - "REX5 empty-code path must forward the constructor's LOG1 into the parent receipt; \ - got logs = {logs:?}", - ); - let log = &logs[0]; - assert_eq!( - log.address, deploy_address, - "forwarded log must carry the deploy address as emitter", - ); - let topics = log.data.topics(); - assert_eq!(topics.len(), 1, "LOG1 must have exactly one topic; got {topics:?}"); - assert_eq!(topics[0], topic, "LOG1 topic must match the value pushed in init code"); - let expected_data = 0xdead_beef_u32.to_be_bytes(); - assert_eq!( - log.data.data.as_ref(), - &expected_data, - "LOG1 data must match the 4-byte word the init code emitted", - ); -} - -/// REX5 with an empty-code constructor that emits NO logs MUST report -/// `EmptyCodeDeployed` AND a zero-length receipt log list. Pins that the -/// `SandboxCompletion::EmptyCode` wiring forwards exactly the logs the sandbox emitted, not -/// anything more. -#[test] -fn test_rex5_keyless_empty_code_no_logs_emitted_no_logs_forwarded() { - let init_code = build_no_logs_empty_return_init_code(); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let result = - run_keyless_outer(MegaSpecId::REX5, &mut db, keyless_tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - - let error_data = extract_error_data(&result); - let decoded_err = decode_error_result(&error_data); - assert!( - matches!(decoded_err, Some(KeylessDeployError::EmptyCodeDeployed { .. })), - "REX5 empty-code path must surface EmptyCodeDeployed in errorData; got {decoded_err:?}", - ); - - let logs = result.logs(); - assert!( - logs.is_empty(), - "REX5 empty-code path with no LOG opcodes must forward zero logs; got logs = {logs:?}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs b/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs deleted file mode 100644 index 3c8bf8483..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_fee_free.rs +++ /dev/null @@ -1,931 +0,0 @@ -//! REX5 keyless deploy fee-free invariants. -//! -//! Pin the post-REX5-fee-free contract: -//! -//! - sandbox tx runs as an OP deposit-like transaction (`gas_price = 0`, `source_hash` set), so the -//! inner signer is never debited for sandbox gas; -//! - configured init code size limit is enforced by the sandbox itself, since the deposit path -//! bypasses revm's `validate_env`; -//! - GASPRICE inside the sandbox is observable as `0`; -//! - deposit-caller materialization gas is charged BEFORE the sandbox runs (alongside -//! `KEYLESS_DEPLOY_OVERHEAD_GAS`) based on parent journal-visible state, and is retained even -//! when the sandbox subsequently validate-rejects. - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{calculate_keyless_deploy_address, decode_error_result, KeylessDeployError}, - test_utils::MemoryDatabase, - IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, - TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, MIN_BUCKET_SIZE, -}; -use revm::{ - context::{ - result::{HaltReason, OutOfGasError}, - TxEnv, - }, - database::AccountState, - inspector::NoOpInspector, - state::Bytecode, - Database as _, -}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); -const SIGNED_GAS_PRICE: u128 = 100_000_000_000; // 100 gwei -const SIGNED_GAS_LIMIT: u64 = 100_000; -const OUTER_GAS_LIMIT: u64 = 30_000_000; -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -fn run_keyless_outer( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, -) -> ExecutionResult { - run_keyless_outer_with(spec, db, external_envs, keyless_tx_bytes, gas_limit_override, |_| {}) -} - -/// Variant that lets a test set a custom outer-tx `gas_limit`, used to force the -/// keylessDeploy interceptor's incoming `call_inputs.gas_limit` below thresholds like -/// `KEYLESS_DEPLOY_OVERHEAD_GAS`. -fn run_keyless_outer_with_gas_limit( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, - outer_gas_limit: u64, -) -> ExecutionResult { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: outer_gas_limit, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not fail at the EVM-error level") -} - -/// Variant that lets a test tweak the outer `MegaContext` (e.g., `cfg`) before the -/// keylessDeploy call runs. -fn run_keyless_outer_with( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, - customize: F, -) -> ExecutionResult -where - F: FnOnce(&mut MegaContext<&mut MemoryDatabase, TestExternalEnvs>), -{ - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - customize(&mut context); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: OUTER_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not fail at the EVM-error level") -} - -fn account_info(db: &mut MemoryDatabase, addr: Address) -> revm::state::AccountInfo { - db.basic(addr).expect("db read should succeed").unwrap_or_default() -} - -fn has_code(db: &mut MemoryDatabase, addr: Address) -> bool { - let info = account_info(db, addr); - if let Some(code) = info.code { - !code.is_empty() - } else { - info.code_hash != revm::primitives::KECCAK_EMPTY - } -} - -/// Builds a deterministic pre-EIP-155 keyless tx with the given init code. -fn build_keyless_tx_with_init_code(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - (tx_bytes, signer) -} - -/// Returns the runtime code committed at `addr`. -fn deployed_code(db: &mut MemoryDatabase, addr: Address) -> Bytes { - account_info(db, addr) - .code - .map(|code| Bytes::copy_from_slice(code.bytes_slice())) - .unwrap_or_default() -} - -/// Reads a storage slot from the committed parent state. -fn storage_slot(db: &mut MemoryDatabase, addr: Address, slot: U256) -> U256 { - db.storage(addr, slot).expect("db storage read should succeed") -} - -/// Constructor that returns 1-byte STOP runtime code (so it survives the -/// `EmptyCodeDeployed` check). -const STOP_RUNTIME_INIT_CODE: &[u8] = &[ - 0x60, 0x00, // PUSH1 0x00 - 0x60, 0x00, // PUSH1 0x00 - 0x52, // MSTORE - 0x60, 0x01, // PUSH1 0x01 - 0x60, 0x1f, // PUSH1 0x1f - 0xf3, // RETURN -]; - -// ============================================================================ -// 1. value = 0 + signer balance = 0 deploys successfully under REX5 -// ============================================================================ - -/// REX5 fee-free: the inner signer needs no balance to deploy when value = 0. -/// Pre-Rex5 required `gas_limit × gas_price + value` of balance; REX5 drops the -/// gas portion because the sandbox runs as a deposit-like fee-free tx. -#[test] -fn test_rex5_value_zero_signer_zero_balance_deploys_successfully() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // signer is intentionally NOT funded. - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!(result.is_success(), "fee-free deploy with empty signer must succeed; got {result:?}"); - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.balance, U256::ZERO, "fee-free: signer balance must remain 0"); - assert_eq!(signer_after.nonce, 1, "replay barrier: signer nonce must advance to 1"); - assert!(has_code(&mut db, deploy_address), "deploy address must have non-empty code"); -} - -// ============================================================================ -// 2. REX4 keeps the `gas_cost + value` balance precheck -// ============================================================================ - -// ============================================================================ -// 3. value > 0 still requires the signer to fund the transfer (REX5) -// ============================================================================ - -/// REX5 fee-free still requires `signer.balance >= value`. Only the gas portion -/// is dropped — value transfer is real EVM semantics that needs funding. -#[test] -fn test_rex5_value_positive_with_insufficient_signer_balance_rejected() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - // build a value-bearing keyless tx (value=1 wei requires 1 wei in signer balance). - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::from(1u64), - input: init_code, - chain_id: None, - }; - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let keyless_tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("recover"); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // signer has 0 balance — cannot cover `value = 1`. - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - _ => panic!("REX5 value-precheck rejection must revert; got {result:?}"), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - assert!( - matches!(err, KeylessDeployError::InsufficientBalance), - "value > 0 must be pre-checked under REX5; got {err:?}", - ); - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 0, "pre-check must not bump signer nonce"); - assert!(!has_code(&mut db, calculate_keyless_deploy_address(signer))); -} - -/// REX5: triggering the sandbox-side initcode size check end-to-end with the production -/// `cfg.max_initcode_size = MAX_INITCODE_SIZE` (~536 KiB) would require a calldata payload -/// that trips `GasFloorMoreThanGasLimit` at the outer-tx validation layer first. To exercise -/// the sandbox's own pre-check, this test lowers `cfg.limit_contract_initcode_size` to a -/// tiny value so a 2-byte initcode is enough to overflow the configured cap. -/// -/// Asserts: -/// - outer call reverts with `InitCodeTooLarge { size, max }`, -/// - `size` is the keyless tx's actual initcode length, -/// - `max` is the lowered configured cap, -/// - signer nonce stays at 0 (pre-check rejection), -/// - deploy address has no code. -#[test] -fn test_rex5_oversized_initcode_rejected_with_init_code_too_large() { - // 2-byte init code: PUSH1 0x00 + STOP. Smaller than our lowered cap of 1 byte. - let init_code = Bytes::from_static(&[0x60, 0x00]); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer_with( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - |ctx| { - ctx.modify_cfg(|cfg| { - cfg.limit_contract_initcode_size = Some(1); - }); - }, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("oversized init code must revert; got {other:?}"), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - let (size, cap) = match err { - KeylessDeployError::InitCodeTooLarge { size, max } => (size, max), - other => panic!("expected InitCodeTooLarge, got {other:?}"), - }; - assert_eq!(size, 2, "selector must report the actual init code length"); - assert_eq!(cap, 1, "selector must report the lowered cfg().max_initcode_size()"); - - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 0, "pre-check rejection must not bump signer nonce"); - assert!(!has_code(&mut db, deploy_address), "no deployment on InitCodeTooLarge"); -} - -// ============================================================================ -// 5. Caller materialization is charged on first deploy, not on retry -// ============================================================================ - -/// REX5: when the deploy signer is unmaterialized in the parent state, -/// `charge_caller_materialization_pre_sandbox` charges `new_account_storage_gas(signer)` -/// against the outer Gas counter and records a deposit-caller state-growth -/// event. A second deploy (parent signer already nonce=1) must not re-charge, -/// even though `SandboxDb::with_nonce_override` makes the sandbox-internal view -/// see nonce=0. -/// -/// First-deploy charge is observable as a difference in outer `gasUsed` between -/// two scenarios that differ only in whether the signer is materialized -/// pre-sandbox. To make the difference visible we put the signer's bucket in a -/// hot configuration so `new_account_storage_gas(signer)` is non-zero (REX -/// formula gives `25_000 × (multiplier - 1)`; the default multiplier of 1 -/// would yield 0 and hide the difference). -#[test] -fn test_rex5_caller_materialization_first_deploy_charged_retry_not_recharged() { - // Init code that REVERTS, so the deploy address never gets code and we can run - // a second keylessDeploy call against the same signer. - let revert_init_code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd]); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(revert_init_code); - - let signer_bucket = ::bucket_id_for_account(signer); - let make_envs = || { - TestExternalEnvs::::new() - .with_bucket_capacity(signer_bucket, MIN_BUCKET_SIZE as u64 * 2) - }; - - // First call: parent state has empty signer. - let mut db1 = MemoryDatabase::default(); - db1.set_account_balance(RELAYER, U256::from(1_000_000_000_000_000_000u128)); - let first = run_keyless_outer( - MegaSpecId::REX5, - &mut db1, - make_envs(), - keyless_tx_bytes.clone(), - LARGE_GAS_LIMIT_OVERRIDE, - ); - let first_signer_after = account_info(&mut db1, signer); - assert_eq!(first_signer_after.nonce, 1, "first call must bump signer nonce"); - - let first_gas_used = match &first { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("first call must return success-style; got {other:?}"), - }; - - // Second call: same signer, but already materialized in the parent state. - // We seed parent state directly to avoid running the first sandbox a second time. - let mut db2 = MemoryDatabase::default(); - db2.set_account_balance(RELAYER, U256::from(1_000_000_000_000_000_000u128)); - db2.set_account_nonce(signer, 1); - let second = run_keyless_outer( - MegaSpecId::REX5, - &mut db2, - make_envs(), - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - let second_signer_after = account_info(&mut db2, signer); - assert_eq!(second_signer_after.nonce, 1, "retry: signer nonce must remain 1 (already used)"); - - let second_gas_used = match &second { - ExecutionResult::Success { gas_used, .. } => *gas_used, - other => panic!("second call must return success-style; got {other:?}"), - }; - - // The first call paid for caller materialization; the second did not. - // With hot bucket × 2, `new_account_storage_gas(signer) = 25_000 × 1 = 25_000`, - // so first_gas_used must exceed second_gas_used by exactly that amount. - let expected_diff: u64 = mega_evm::constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE; - assert_eq!( - first_gas_used.checked_sub(second_gas_used), - Some(expected_diff), - "first deploy must include exactly one caller materialization gas charge; \ - first={first_gas_used} second={second_gas_used}", - ); -} - -// ============================================================================ -// 6. GASPRICE inside the REX5 sandbox returns 0 (consensus-observable) -// ============================================================================ - -/// REX5 deposit-style sandbox sets `tx.gas_price = 0`. As a consequence, the -/// `GASPRICE` opcode executed inside the constructor returns 0, even though -/// the keyless transaction's signed gas price is non-zero (100 gwei here). -/// This test pins the spec choice so future "restore raw `gas_price`" attempts -/// fail loudly. -#[test] -fn test_rex5_sandbox_gasprice_opcode_returns_zero() { - // Constructor: - // slot 0x42 ← 1 (marker; proves SSTORE ran) - // slot 0x43 ← GASPRICE (the assertion) - // RETURN single-byte STOP (avoid EmptyCodeDeployed) - // - // Bytecode: - // 60 01 60 42 55 PUSH1 1, PUSH1 0x42, SSTORE - // 3a 60 43 55 GASPRICE, PUSH1 0x43, SSTORE - // 60 00 60 00 52 PUSH1 0, PUSH1 0, MSTORE - // 60 01 60 1f f3 PUSH1 1, PUSH1 0x1f, RETURN - let init_code = Bytes::from_static(&[ - 0x60, 0x01, 0x60, 0x42, 0x55, // SSTORE(0x42, 1) - 0x3a, 0x60, 0x43, 0x55, // SSTORE(0x43, GASPRICE) - 0x60, 0x00, 0x60, 0x00, 0x52, // mem[0:32] = 0 - 0x60, 0x01, 0x60, 0x1f, 0xf3, // return mem[0x1f:0x20] = 0x00 (STOP) - ]); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "deploy must succeed; got {result:?}"); - assert!(has_code(&mut db, deploy_address), "deploy address must have runtime code"); - - let marker = storage_slot(&mut db, deploy_address, U256::from(0x42u64)); - assert_eq!(marker, U256::from(1u64), "marker proves the constructor's SSTORE actually ran"); - - let observed_gas_price = storage_slot(&mut db, deploy_address, U256::from(0x43u64)); - assert_eq!( - observed_gas_price, - U256::ZERO, - "REX5 sandbox: GASPRICE opcode must return 0 even though the signed gas_price is {SIGNED_GAS_PRICE} wei", - ); - - // Sanity: deployed code is the 1-byte STOP we returned. - let code = deployed_code(&mut db, deploy_address); - assert_eq!(code.as_ref(), &[0x00u8]); -} - -// ============================================================================ -// 7. Runtime halt under REX5 deposit-style sandbox returns success-style errorData -// ============================================================================ - -/// REX5: when the inner constructor halts (INVALID opcode here), the outer call MUST -/// still return success-style with `errorData = ExecutionHalted(...)` — NOT revert with -/// `InvalidTransaction`. The signer nonce MUST be bumped (replay barrier consumed). The -/// outer Gas counter MUST be debited for the sandbox's actual `gas_used` (not the -/// inflated `gas_limit` that op-revm's `FailedDeposit` path would have produced). -#[test] -fn test_rex5_runtime_halt_returns_execution_halted_with_replay_barrier_consumed() { - // Constructor: `INVALID` opcode — halts immediately, no gas refund. - let invalid_init_code = Bytes::from_static(&[0xfe]); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(invalid_init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000_000_000_000u128)); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - // Outer call MUST surface as success-style (the keyless interceptor returns - // success-with-errorData on inner failure); a `Revert(InvalidTransaction)` here - // would mean the runtime halt was misclassified as a validation rejection. - let (gas_used, output) = match &result { - ExecutionResult::Success { gas_used, output, .. } => (*gas_used, output.data().clone()), - other => panic!("runtime halt must surface as outer Success; got {other:?}"), - }; - let decoded = IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output) - .expect("decode keylessDeploy return data"); - let inner_err = decode_error_result(&decoded.errorData).expect("errorData must decode"); - assert!( - matches!(inner_err, KeylessDeployError::ExecutionHalted { .. }), - "runtime halt must surface as ExecutionHalted, NOT InvalidTransaction; got {inner_err:?}", - ); - - // The outer Gas debit MUST reflect the sandbox's actual gas usage. A `FailedDeposit` - // misclassification would have inflated this to ~gas_limit_override. - assert!( - gas_used < LARGE_GAS_LIMIT_OVERRIDE, - "outer gas_used must NOT equal the inflated FailedDeposit gas_limit; got {gas_used}", - ); - - // Replay barrier consumed: signer nonce = 1. - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 1, "runtime halt must bump signer nonce via make_create_frame"); - assert_eq!(signer_after.balance, U256::ZERO, "fee-free: signer balance must be unchanged"); - assert!( - !has_code(&mut db, deploy_address), - "halted constructor must leave deploy address empty" - ); -} - -// ============================================================================ -// 8. EIP-3607: signer with non-empty, non-EIP-7702 bytecode must be rejected -// ============================================================================ - -/// REX5: when the recovered signer already has non-empty bytecode in parent state that is -/// NOT an EIP-7702 delegation, the sandbox MUST reject with `SignerHasCode` before -/// constructing the deposit-style sandbox tx (which would otherwise bypass op-revm's -/// `validate_account_nonce_and_code` check). -#[test] -fn test_rex5_signer_with_contract_code_rejected_with_signer_has_code() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Place real (non-EIP-7702) contract code at the signer address. - db.set_account_code(signer, Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3])); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("signer-with-code must revert with SignerHasCode; got {other:?}"), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - assert!( - matches!(err, KeylessDeployError::SignerHasCode), - "REX5 must reject signer with contract code; got {err:?}", - ); - // Pre-check rejection: signer untouched, no deployment. - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 0, "pre-check rejection must not bump signer nonce"); - assert!(!has_code(&mut db, deploy_address), "no deployment on pre-check rejection"); -} - -/// REX5: `cfg.disable_eip3607 = true` MUST bypass the `SignerHasCode` pre-check, matching -/// the canonical revm `validate_account_nonce_and_code` semantics. Pinned so the keyless -/// sandbox path stays consistent with the system-tx validation path and ordinary tx -/// validation under the same cfg flag. -#[test] -fn test_rex5_signer_has_code_check_respects_disable_eip3607() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Same setup as the rejection test: signer has contract code. - db.set_account_code(signer, Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3])); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer_with( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - |ctx| { - ctx.modify_cfg(|cfg| { - cfg.disable_eip3607 = true; - }); - }, - ); - - // With EIP-3607 disabled, the SignerHasCode pre-check is bypassed. The keyless deploy - // then fails downstream because the deploy address would collide with already-existing - // code at the signer (CREATE address vs signer are different, but the sandbox proceeds - // past the SignerHasCode gate). The exact downstream outcome isn't the focus here — - // what matters is that we do NOT revert with SignerHasCode. - if let ExecutionResult::Revert { output, .. } = &result { - if let Some(err) = decode_error_result(output) { - assert!( - !matches!(err, KeylessDeployError::SignerHasCode), - "disable_eip3607=true must bypass SignerHasCode; got {err:?}", - ); - } - } - // Direct positive: also exercise the non-code signer path with the same cfg flag to - // confirm the override doesn't break the normal flow. - let (clean_tx_bytes, clean_signer) = - build_keyless_tx_with_init_code(Bytes::from_static(STOP_RUNTIME_INIT_CODE)); - let mut db2 = MemoryDatabase::default(); - db2.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - let clean_result = run_keyless_outer_with( - MegaSpecId::REX5, - &mut db2, - TestExternalEnvs::::new(), - clean_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - |ctx| { - ctx.modify_cfg(|cfg| { - cfg.disable_eip3607 = true; - }); - }, - ); - assert!( - clean_result.is_success(), - "disable_eip3607=true on a clean signer must still deploy successfully; got {clean_result:?}", - ); - assert_eq!(account_info(&mut db2, clean_signer).nonce, 1, "clean signer nonce must bump"); -} - -/// Installs an EIP-7702 delegation designator (`0xef0100 || delegate_to`) at `address`, -/// matching what revm's `apply_eip7702_auth_list` writes during Type-4 tx processing. -/// `MemoryDatabase::set_account_code` only writes `Bytecode::new_legacy(..)`, which would -/// not satisfy `Bytecode::is_eip7702()` even if the bytes match the EIP-7702 magic, so -/// the test wires the proper variant directly. -fn set_eip7702_delegation_at(db: &mut MemoryDatabase, address: Address, delegate_to: Address) { - let bytecode = Bytecode::new_eip7702(delegate_to); - let code_hash = bytecode.hash_slow(); - let account = db.load_account(address).unwrap(); - account.info.code = Some(bytecode); - account.info.code_hash = code_hash; - account.account_state = AccountState::None; -} - -// ============================================================================ -// 10. EIP-7702 delegated signer is allowed through the EIP-3607 pre-check -// ============================================================================ - -/// REX5: a signer carrying only an EIP-7702 delegation designator (not real contract code) -/// MUST pass `validate_signer_code` and proceed to deploy. The `code.is_eip7702()` arm in -/// the EIP-3607 helper is the only thing keeping 7702-delegated EOAs eligible — without -/// it, every account that has accepted an authorization would lose access to keyless -/// deploy. -#[test] -fn test_rex5_signer_with_eip7702_delegation_passes_eip3607_check() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - let delegate_to = address!("dddddddddddddddddddddddddddddddddddd0001"); - set_eip7702_delegation_at(&mut db, signer, delegate_to); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!( - result.is_success(), - "EIP-7702 delegated signer must be allowed to deploy; got {result:?}", - ); - if let ExecutionResult::Revert { output, .. } = &result { - if let Some(err) = decode_error_result(output) { - assert!( - !matches!(err, KeylessDeployError::SignerHasCode), - "EIP-7702 delegation must NOT trip SignerHasCode; got {err:?}", - ); - } - } - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 1, "deploy must bump signer nonce"); - assert!(has_code(&mut db, deploy_address), "deploy address must have runtime code"); -} - -// ============================================================================ -// 11. Pre-sandbox materialization OOG halts before the sandbox ever runs -// ============================================================================ - -/// REX5: when the deploy signer is unmaterialized in parent state and the signer's -/// SALT bucket multiplier inflates `new_account_storage_gas` past the outer call's -/// remaining gas envelope, `charge_caller_materialization_pre_sandbox` MUST halt the -/// outer call with plain OOG (no rescue) BEFORE the sandbox is constructed — so the -/// signer nonce bump (the Nick's-Method replay barrier) never even appears, and the -/// deploy address stays empty. The halt is symmetric across what the constructor -/// *would* have done (success / runtime-revert) because no sandbox frame is ever -/// created. -#[test] -fn test_rex5_pre_sandbox_materialization_oog_halts_before_sandbox_runs() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let signer_bucket = ::bucket_id_for_account(signer); - // Multiplier ≈ 1_000_000 → `new_account_storage_gas(signer) ≈ 25_000 × 999_999`, - // far above the outer call's remaining gas envelope. - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(signer_bucket, MIN_BUCKET_SIZE as u64 * 1_000_000); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000_000_000_000u128)); - - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - let halt_reason = match &result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - other => { - panic!("pre-sandbox materialization OOG must surface as outer Halt; got {other:?}") - } - }; - assert!( - matches!( - halt_reason, - MegaHaltReason::Base(op_revm::OpHaltReason::Base(HaltReason::OutOfGas( - OutOfGasError::Basic - ))) - ), - "pre-sandbox materialization halt MUST be plain OOG (no rescue); got {halt_reason:?}", - ); - - let signer_after = account_info(&mut db, signer); - assert_eq!( - signer_after.nonce, 0, - "pre-sandbox materialization OOG must halt before the sandbox can bump the signer nonce", - ); - assert!( - !has_code(&mut db, deploy_address), - "no deployment when materialization fails before the sandbox runs", - ); -} - -// ============================================================================ -// 12. Sandbox-validate-reject still pays the upfront materialization charge -// ============================================================================ - -/// REX5: pinning the new failure-surface contract — materialization is charged -/// upfront (alongside `KEYLESS_DEPLOY_OVERHEAD_GAS`), so a sandbox-validate-reject -/// (`FailedDeposit → InvalidTransaction`) MUST still debit the outer gas counter for -/// the materialization amount, even though the sandbox state is dropped and no -/// replay barrier is installed. The relayer pays for the parent-state read + -/// SALT-multiplier work it asked for, just like the dispatch overhead. -/// -/// Proof technique: two runs that differ only in the signer's bucket multiplier -/// (1 vs 2). With multiplier 1, `new_account_storage_gas = 0`; with multiplier 2, -/// it equals `NEW_ACCOUNT_STORAGE_GAS_BASE`. The delta in outer `gas_used` between -/// the two runs MUST equal that amount — proving materialization rode along on the -/// validate-reject path. -#[test] -fn test_rex5_pre_sandbox_materialization_charged_even_on_sandbox_validate_reject() { - // Sandbox-validate-reject: the keyless tx's `gas_limit` is far below the sandbox - // EVM's actual intrinsic + floor gas requirement, so `MegaHandler::validate` - // inside the sandbox surfaces `CallGasCostMoreThanGasLimit`, which op-revm's - // deposit `catch_error` wraps into `Ok(Halt(FailedDeposit, gas_limit))` → - // `process_sandbox_transact_result` maps to `KeylessDeployError::InvalidTransaction`. - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let low_gas_limit: u64 = 50_000; - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: low_gas_limit, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let keyless_tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("recover"); - let signer_bucket = ::bucket_id_for_account(signer); - - // Run with the same low gas_limit_override (forces sandbox-validate to reject), - // varying only the signer's bucket multiplier between runs. - let run = |bucket_capacity: u64| -> (ExecutionResult, u64) { - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000_000_000_000u128)); - let envs = TestExternalEnvs::::new() - .with_bucket_capacity(signer_bucket, bucket_capacity); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - envs, - keyless_tx_bytes.clone(), - low_gas_limit, - ); - let gas_used = result.gas_used(); - (result, gas_used) - }; - - // Scenario A: bucket multiplier 1 → materialization gas = 0. - let (result_a, gas_used_a) = run(MIN_BUCKET_SIZE as u64); - let revert_a = match &result_a { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("validate-reject must surface as outer Revert; got {other:?}"), - }; - let err_a = decode_error_result(&revert_a).expect("revert output must decode"); - assert!( - matches!(err_a, KeylessDeployError::InvalidTransaction), - "low gas_limit_override must trigger sandbox-validate-reject → InvalidTransaction; got {err_a:?}", - ); - - // Scenario B: bucket multiplier 2 → materialization gas = NEW_ACCOUNT_STORAGE_GAS_BASE. - let (result_b, gas_used_b) = run(MIN_BUCKET_SIZE as u64 * 2); - let revert_b = match &result_b { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("validate-reject must surface as outer Revert (scenario B); got {other:?}"), - }; - let err_b = decode_error_result(&revert_b).expect("revert output must decode"); - assert!(matches!(err_b, KeylessDeployError::InvalidTransaction), "got {err_b:?}"); - - // The materialization gas was charged upfront and retained on the validate-reject - // path: outer gas_used differs by exactly `NEW_ACCOUNT_STORAGE_GAS_BASE`. - let expected_diff: u64 = mega_evm::constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE; - assert_eq!( - gas_used_b.checked_sub(gas_used_a), - Some(expected_diff), - "validate-reject MUST retain the upfront materialization charge; \ - scenario A (mult=1, mat=0)={gas_used_a} B (mult=2, mat={expected_diff})={gas_used_b}", - ); -} - -// ============================================================================ -// 13. Step-1 dispatch-overhead OOG when the call's gas_limit is below the fixed cost -// ============================================================================ - -/// REX5: the very first step of `execute_keyless_deploy_call` charges -/// `KEYLESS_DEPLOY_OVERHEAD_GAS` (100K) against the inbound `Gas` object. When the outer -/// caller forwards less than that, the call must halt with plain OOG at line 1 of the -/// interceptor and never reach the decode / signer / sandbox steps — so neither the -/// signer nonce nor the parent state may be touched. -#[test] -fn test_rex5_outer_call_gas_below_dispatch_overhead_halts_at_step_one() { - let init_code = Bytes::from_static(STOP_RUNTIME_INIT_CODE); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - // Outer tx gas_limit sized so initial+floor gas validation passes (REX5 base intrinsic - // is ~60K) but the leftover forwarded to the keylessDeploy frame is well under - // `KEYLESS_DEPLOY_OVERHEAD_GAS = 100_000`. - let outer_gas_limit = 130_000; - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer_with_gas_limit( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - outer_gas_limit, - ); - - let halt_reason = match &result { - ExecutionResult::Halt { reason, .. } => reason.clone(), - other => panic!("step-1 OOG must surface as outer Halt; got {other:?}"), - }; - assert!( - matches!( - halt_reason, - MegaHaltReason::Base(op_revm::OpHaltReason::Base(HaltReason::OutOfGas( - OutOfGasError::Basic - ))) - ), - "step-1 dispatch-overhead halt MUST be plain OOG; got {halt_reason:?}", - ); - - // The interceptor halted before signer recovery, so the signer must remain - // untouched and no deployment may have happened. - let signer_after = account_info(&mut db, signer); - assert_eq!(signer_after.nonce, 0, "step-1 OOG must not bump signer nonce"); - assert_eq!(signer_after.balance, U256::ZERO, "step-1 OOG must not debit signer"); - assert!(!has_code(&mut db, deploy_address), "no deployment when step-1 halts"); -} diff --git a/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs b/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs deleted file mode 100644 index f8181ede7..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_gas_cap_postcap_recheck.rs +++ /dev/null @@ -1,302 +0,0 @@ -//! Regression suite for the REX5+ `KeylessDeploy` post-cap gas-limit recheck. -//! -//! In Step 4b of `execute_keyless_deploy_call`, REX5 caps `gas_limit_override` -//! to the outer's `gas.remaining()`. After the cap, the wrapper re-enforces -//! the signer's "execute with at least `tx_gas_limit`" guarantee: if the -//! relayer's outer envelope shrinks the override below the signed minimum, -//! the call rejects with `KeylessDeployError::GasLimitTooLow` reporting the -//! capped value. Pre-REX5 does not apply the cap, so this recheck never -//! fires under pre-REX5 specs. - -use std::{convert::Infallible, vec::Vec}; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{calculate_keyless_deploy_address, decode_error_result, KeylessDeployError}, - test_utils::MemoryDatabase, - BucketHasher, IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, SimpleBucketHasher, TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, MIN_BUCKET_SIZE, -}; -use revm::{context::TxEnv, inspector::NoOpInspector, Database as _}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); -const SIGNED_GAS_PRICE: u128 = 100_000_000_000; // 100 gwei -const SIGNED_GAS_LIMIT: u64 = 100_000; -/// Large enough that the Step 4 pre-cap check (`override >= tx_gas_limit`) passes. -const LARGE_OVERRIDE: u64 = 10_000_000_000; -/// Outer envelope sized so that, after the intrinsic charge and the -/// `KEYLESS_DEPLOY_OVERHEAD_GAS = 100_000` Step-1 debit, the remaining gas at -/// Step 4b lands below `SIGNED_GAS_LIMIT`. Pre-funding the signer keeps the -/// materialization charge at zero so the math stays predictable. -const TIGHT_OUTER_GAS: u64 = 200_000; -/// Outer envelope big enough that the Step 4b cap does not shrink the override -/// below `tx_gas_limit`. Used by the happy-path assertion. -const NORMAL_OUTER_GAS: u64 = 30_000_000; - -/// Init code that returns a single-byte `STOP` runtime (so the deploy survives -/// the post-execution `EmptyCodeDeployed` check). -const STOP_RUNTIME_INIT_CODE: &[u8] = &[ - 0x60, 0x00, // PUSH1 0x00 - 0x60, 0x00, // PUSH1 0x00 - 0x52, // MSTORE - 0x60, 0x01, // PUSH1 0x01 - 0x60, 0x1f, // PUSH1 0x1f - 0xf3, // RETURN -]; - -fn build_keyless_tx() -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::ZERO, - input: Bytes::from_static(STOP_RUNTIME_INIT_CODE), - chain_id: None, - }; - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let signer = signed.recover_signer().expect("signer recovery"); - (Bytes::from(buf), signer) -} - -fn run_keyless_outer( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, - outer_gas_limit: u64, -) -> ExecutionResult { - run_keyless_outer_with_envs( - spec, - db, - TestExternalEnvs::::new(), - keyless_tx_bytes, - gas_limit_override, - outer_gas_limit, - ) -} - -fn run_keyless_outer_with_envs( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, - outer_gas_limit: u64, -) -> ExecutionResult { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: outer_gas_limit, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not surface EVMError") -} - -/// REX5: a tight outer envelope drops `gas.remaining()` below the signed -/// `tx_gas_limit` at Step 4b. The Step-4 pre-cap check passes (the relayer -/// supplied a large override), the Step-4b cap shrinks the override to -/// `gas.remaining()`, and the post-cap recheck must reject with -/// `GasLimitTooLow` reporting the capped (smaller) value. -#[test] -fn test_rex5_envelope_shrinks_below_signed_min_returns_gas_limit_too_low() { - let (keyless_tx_bytes, signer) = build_keyless_tx(); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Pre-fund signer (non-empty) so `charge_caller_materialization_pre_sandbox` - // is a no-op and the outer-gas math is dominated by intrinsic + - // KEYLESS_DEPLOY_OVERHEAD_GAS. - db.set_account_balance(signer, U256::from(1)); - - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - keyless_tx_bytes, - LARGE_OVERRIDE, - TIGHT_OUTER_GAS, - ); - - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("expected Revert(GasLimitTooLow), got {other:?}"), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - match err { - KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } => { - assert_eq!( - tx_gas_limit, SIGNED_GAS_LIMIT, - "tx_gas_limit must echo the signed keyless tx's gas_limit", - ); - assert!( - provided_gas_limit < tx_gas_limit, - "post-cap recheck must report the capped value (< tx_gas_limit); got \ - provided_gas_limit = {provided_gas_limit}", - ); - assert!( - provided_gas_limit < LARGE_OVERRIDE, - "post-cap recheck must report the capped value, not the relayer-supplied \ - override; got provided_gas_limit = {provided_gas_limit}", - ); - } - other => panic!("expected GasLimitTooLow, got {other:?}"), - } - - // Signer untouched, no deploy. - let signer_info = db.basic(signer).unwrap().unwrap_or_default(); - assert_eq!(signer_info.nonce, 0, "signer nonce must remain 0"); - let deploy_info = db.basic(deploy_address).unwrap(); - assert!( - deploy_info.is_none() || - deploy_info.as_ref().unwrap().code_hash == revm::primitives::KECCAK_EMPTY, - "no deployment must happen", - ); -} - -/// REX5: a normal-sized outer envelope leaves `gas.remaining()` above -/// `tx_gas_limit` after the Step-4b cap, so the post-cap recheck does not -/// fire and the deploy proceeds normally. -#[test] -fn test_rex5_envelope_above_signed_min_proceeds_normally() { - let (keyless_tx_bytes, signer) = build_keyless_tx(); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - db.set_account_balance(signer, U256::from(1)); - - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - keyless_tx_bytes, - LARGE_OVERRIDE, - NORMAL_OUTER_GAS, - ); - - assert!( - result.is_success(), - "with a normal outer envelope the deploy must succeed; got {result:?}", - ); -} - -/// Post-cap recheck must fire on the materialization-drain shape: outer envelope is -/// fat enough to clear intrinsic + `KEYLESS_DEPLOY_OVERHEAD_GAS` without dipping below -/// `tx_gas_limit`, but `charge_caller_materialization_pre_sandbox` for an unfunded -/// signer drains the remaining gas under the signed minimum at Step 4b. -/// -/// Setup: -/// 1. Outer envelope is fat — comfortably above intrinsic + overhead. With a pre-funded signer the -/// deploy would succeed (verified by the control case below). -/// 2. Signer is un-funded (`AccountInfo::is_empty()` → true), so -/// `charge_caller_materialization_pre_sandbox` debits `new_account_gas`. -/// 3. Signer's SALT bucket carries a heavy multiplier so `new_account_gas` is large enough to push -/// `gas.remaining()` below `SIGNED_GAS_LIMIT` at Step 4b. -/// -/// The recheck must surface as `GasLimitTooLow` with the capped value. A control with -/// the same envelope but a pre-funded signer must succeed — isolating materialization -/// as the cause of the drain. -#[test] -fn test_rex5_materialization_drains_gas_below_signed_min_triggers_recheck() { - /// `NEW_ACCOUNT_STORAGE_GAS_BASE * (multiplier - 1)` = `25_000 * 19 = 475_000`. - /// Picked so that the gap between "post intrinsic + overhead remaining" and - /// `tx_gas_limit` (100k) is bridged by materialization across a wide intrinsic - /// window — the `MegaETH` outer intrinsic for this ~200-byte calldata lands near - /// 90k (EIP-2028 + `CALLDATA_STANDARD_TOKEN_STORAGE_GAS` + - /// `TX_INTRINSIC_STORAGE_GAS`), not the bare 21k EIP-2028 base, so the test - /// uses a generous margin to stay robust against any minor calldata change. - const HEAVY_MULTIPLIER: u64 = 20; - const HEAVY_CAPACITY: u64 = (MIN_BUCKET_SIZE as u64) * HEAVY_MULTIPLIER; - /// Fat enough that intrinsic (≈90k) + `KEYLESS_DEPLOY_OVERHEAD_GAS` (100k) - /// alone leaves remaining gas well above `tx_gas_limit` (100k). The recheck - /// only fires once materialization piles on the additional 475k. - const FAT_OUTER_GAS: u64 = 700_000; - - let (keyless_tx_bytes, signer) = build_keyless_tx(); - let signer_bucket = SimpleBucketHasher::bucket_id(signer.as_slice()); - - // Materialization-drain leg: signer unfunded → empty signer_info → materialization fires. - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - // Do NOT fund signer here. - let envs = - TestExternalEnvs::::new().with_bucket_capacity(signer_bucket, HEAVY_CAPACITY); - let result = run_keyless_outer_with_envs( - MegaSpecId::REX5, - &mut db, - envs, - keyless_tx_bytes.clone(), - LARGE_OVERRIDE, - FAT_OUTER_GAS, - ); - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - other => panic!("expected Revert(GasLimitTooLow), got {other:?}"), - }; - let err = decode_error_result(&revert_output).expect("revert output must decode"); - match err { - KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } => { - assert_eq!(tx_gas_limit, SIGNED_GAS_LIMIT); - assert!( - provided_gas_limit < tx_gas_limit, - "post-cap recheck must report a capped value below tx_gas_limit; \ - got provided_gas_limit = {provided_gas_limit}", - ); - assert!( - provided_gas_limit < LARGE_OVERRIDE, - "must report the Step-4b-capped value, not the relayer-supplied override", - ); - } - other => panic!("expected GasLimitTooLow, got {other:?}"), - } - - // Control leg: same envelope and same heavy bucket, but signer pre-funded so the - // materialization charge is a no-op. The deploy must succeed, isolating - // materialization as the cause of the drain in the case above. - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - db.set_account_balance(signer, U256::from(1)); - let envs = - TestExternalEnvs::::new().with_bucket_capacity(signer_bucket, HEAVY_CAPACITY); - let control = run_keyless_outer_with_envs( - MegaSpecId::REX5, - &mut db, - envs, - keyless_tx_bytes, - LARGE_OVERRIDE, - FAT_OUTER_GAS, - ); - assert!( - control.is_success(), - "control with pre-funded signer at the same fat envelope must succeed — \ - isolates materialization as the cause of the drain in the failing leg; got {control:?}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs b/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs deleted file mode 100644 index cc0dc2cce..000000000 --- a/crates/mega-evm/tests/_pending/rex5/keyless_replay_barrier.rs +++ /dev/null @@ -1,319 +0,0 @@ -//! REX5 keyless deploy replay-barrier invariant. -//! -//! Pin the property that `KeylessDeploy` never produces a parent-visible signer fee -//! deduction without also producing a parent-visible durable replay barrier (signer -//! nonce bump *or* deploy-address code). Combined with the REX5+ final Mega-side gas -//! validation, the failure paths inside the sandbox split into: -//! -//! - **`validate()` rejects** (e.g. final intrinsic / floor gas overrun): the sandbox returns -//! `Err(...)` before `pre_execution()` runs, no signer mutation occurs, and the outer -//! keyless-deploy call surfaces as `ExecutionResult::Revert`. -//! - **`pre_execution()` runs** and the inner CREATE either succeeds or reverts in the constructor: -//! in either case `make_create_frame` reaches the post-pre-bump nonce bump, so the signer nonce -//! is bumped. The parent journal merges the bump via `merge_evm_state_optional_status`. - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{ - calculate_keyless_deploy_address, decode_error_result, - tests::{CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX}, - KeylessDeployError, - }, - test_utils::MemoryDatabase, - IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, SaltEnv, - TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, MIN_BUCKET_SIZE, -}; -use revm::{context::TxEnv, inspector::NoOpInspector, Database as _}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); -const SIGNED_GAS_PRICE: u128 = 100_000_000_000; // 100 gwei, matches CREATE2_FACTORY_TX -const SIGNED_GAS_LIMIT: u64 = 100_000; // matches CREATE2_FACTORY_TX - -// Rex5 caps `gasLimitOverride` to the outer call's remaining gas, so the happy-path -// sandbox tx needs enough headroom for the CREATE2 factory deploy's storage gas, not -// just for its raw EVM gas. 30M matches the standard block budget used elsewhere. -const OUTER_GAS_LIMIT: u64 = 30_000_000; - -// Big enough to cover all sandbox costs in the happy path / runtime-revert path. -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -/// Drives a keyless-deploy outer call and returns the outer execution result. -/// Funds RELAYER for the outer-call gas. Funds `signer` separately so the sandbox -/// fee-debit can succeed (when it runs). -fn run_keyless_outer( - spec: MegaSpecId, - db: &mut MemoryDatabase, - external_envs: TestExternalEnvs, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, -) -> ExecutionResult { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: OUTER_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - // Use `transact_commit` (not `transact_raw`) so the result's state is committed back into - // the database — that lets the test query parent-visible state via `db.basic(...)` after - // the call. `transact_raw` returns state without committing. - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not fail at the EVM-error level") -} - -/// Reads the current account info for `addr`. -fn account_info(db: &mut MemoryDatabase, addr: Address) -> revm::state::AccountInfo { - db.basic(addr).expect("db read should succeed").unwrap_or_default() -} - -/// Returns whether the address has non-empty contract code committed. -fn has_code(db: &mut MemoryDatabase, addr: Address) -> bool { - let info = account_info(db, addr); - if let Some(code) = info.code { - !code.is_empty() - } else { - info.code_hash != revm::primitives::KECCAK_EMPTY - } -} - -/// Builds a deterministic pre-EIP-155 keyless-deploy transaction with the given init code. -/// Returns `(tx_bytes, recovered_signer)`. Mirrors the helper in -/// `tests/rex4/keyless_deploy.rs::create_pre_eip155_deploy_tx`. -fn build_keyless_tx_with_init_code(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - (tx_bytes, signer) -} - -// ============================================================================ -// 1. Validate-reject path: outer call MUST revert AND signer MUST be untouched -// ============================================================================ - -/// REX5: a keyless-deploy attempt whose sandbox `validate()` rejects (final Mega-side -/// gas check overrun) must not charge the signer, must not bump the signer nonce, -/// must not install code at the deploy address, AND must surface as outer -/// `ExecutionResult::Revert`. Flipping any one of the four assertions indicates the -/// invariant has slipped: either the signer is being charged without a barrier, or -/// the validation rejection has been silently translated into an outer success. -#[test] -fn test_keyless_signer_charge_implies_replay_barrier() { - let mut db = MemoryDatabase::default(); - - // Fund the signer enough to cover several full-override fees so the sandbox's pre-check - // (signer.balance >= gas_cost + value) doesn't trip *before* validate(). Validate must be - // the layer that rejects. - let signer_starting_balance = U256::from(1_000_000_000_000_000_000_000u128); // 1000 ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, signer_starting_balance); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - // Hot bucket on the deploy address blows the CREATE storage gas past gas_limit_override. - let contract_bucket = - ::bucket_id_for_account(CREATE2_FACTORY_CONTRACT); - let external_envs = TestExternalEnvs::::new() - .with_bucket_capacity(contract_bucket, MIN_BUCKET_SIZE as u64 * 2); - - // gasLimitOverride covers signed-tx gas (100k) but not the inflated CREATE storage gas. - let gas_limit_override = 120_000; - - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - Bytes::from_static(CREATE2_FACTORY_TX), - gas_limit_override, - ); - - // (a) outer call result is Revert. - let revert_output = match &result { - ExecutionResult::Revert { output, .. } => output.clone(), - _ => panic!( - "outer keyless-deploy call MUST revert when sandbox validate() rejects under REX5; got {result:?}", - ), - }; - - // (a') the revert payload distinguishes a sandbox tx-validation rejection from a - // genuine internal failure: the dedicated `IKeylessDeploy::InvalidTransaction` - // selector decodes to `KeylessDeployError::InvalidTransaction`. A regression that - // re-collapses the err arm back into `InternalError` would fail this assertion. - let decoded = - decode_error_result(&revert_output).expect("revert output must decode to a known error"); - assert!( - matches!(decoded, KeylessDeployError::InvalidTransaction), - "sandbox tx-validation rejection must surface as InvalidTransaction, got {decoded:?}", - ); - - // (b) signer balance unchanged - let signer_after = account_info(&mut db, CREATE2_FACTORY_DEPLOYER); - assert_eq!( - signer_after.balance, signer_starting_balance, - "signer must not be fee-debited when sandbox validate() rejects", - ); - // (c) signer nonce unchanged at 0 (no CREATE frame ran, no nonce bump) - assert_eq!(signer_after.nonce, 0, "signer nonce must not advance"); - // (d) deploy-address has no code - assert!( - !has_code(&mut db, CREATE2_FACTORY_CONTRACT), - "deploy address must not be created when sandbox validate() rejects", - ); -} - -// ============================================================================ -// 2. Runtime-revert path: signer charge AND nonce bump (barrier consumed) -// ============================================================================ - -/// REX5: a keyless-deploy whose constructor reverts at runtime *does* charge the -/// signer, because `make_create_frame` reaches the post-pre-bump nonce bump before -/// the constructor runs. The signer nonce is bumped in the sandbox state and merged -/// into the parent. If a future change ever skips the nonce bump on this path, this -/// test catches it immediately. -#[test] -fn test_keyless_signer_charge_consumes_replay_barrier_on_runtime_failure() { - // Init code = `PUSH1 0x00 PUSH1 0x00 REVERT` → constructor reverts unconditionally. - let revert_init_code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd]); - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(revert_init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let mut db = MemoryDatabase::default(); - - // Signer has enough to pay the full sandbox gas budget even if the constructor fails. - // 1000 ETH — large enough to cover `gas_limit_override × gas_price` (≈100 ETH) plus the - // sandbox's pre-check headroom. Same convention as `tests/rex4/keyless_deploy.rs`. - let signer_starting_balance = U256::from(1_000_000_000_000_000_000_000u128); // 1000 ETH - db.set_account_balance(signer, signer_starting_balance); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - // No hot bucket — validate() must accept so make_create_frame is reached. - let external_envs = TestExternalEnvs::::new(); - - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - - // Outer call must SUCCEED (the keyless deploy interceptor returns success-with-error-data - // so the relayer is not penalized when the inner constructor reverts; the signer is the - // one who paid for the inner gas). - assert!( - result.is_success(), - "outer call must succeed even when inner constructor reverts; got {result:?}" - ); - - // Decode the keylessDeploy return value to confirm the inner constructor actually reverted. - let output = match &result { - ExecutionResult::Success { output, .. } => output.data().clone(), - _ => panic!("expected success result"), - }; - let decoded = IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output) - .expect("decode keylessDeploy return data"); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "deployedAddress must be zero when the inner constructor reverts", - ); - assert!(!decoded.errorData.is_empty(), "errorData must carry the constructor revert payload",); - - // Replay-barrier assertion: signer nonce advanced. Under REX5 the sandbox is fee-free - // (deposit-style gas_price = 0), so the signer balance is NOT debited for gas — only - // the nonce bump remains as the replay barrier. - let signer_after = account_info(&mut db, signer); - assert_eq!( - signer_after.nonce, 1, - "signer nonce must advance to 1 after make_create_frame's nonce bump", - ); - assert_eq!( - signer_after.balance, signer_starting_balance, - "REX5 sandbox is fee-free, signer balance must be unchanged (only -value, which is 0 here)", - ); - - // Deploy address must not have code (constructor reverted). - assert!( - !has_code(&mut db, deploy_address), - "constructor reverted, so deploy address must not have code", - ); -} - -// ============================================================================ -// 3. Happy path under REX5 (sanity) -// ============================================================================ - -/// REX5: the canonical CREATE2 factory deploy still succeeds end-to-end and persists the -/// expected replay barriers (signer nonce + deploy-address code). -#[test] -fn test_keyless_successful_deploy_still_charges_and_advances_nonce() { - let mut db = MemoryDatabase::default(); - // 1000 ETH — large enough to cover `gas_limit_override × gas_price` (≈100 ETH) plus the - // sandbox's pre-check headroom. Same convention as `tests/rex4/keyless_deploy.rs`. - let signer_starting_balance = U256::from(1_000_000_000_000_000_000_000u128); // 1000 ETH - db.set_account_balance(CREATE2_FACTORY_DEPLOYER, signer_starting_balance); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let external_envs = TestExternalEnvs::::new(); - let result = run_keyless_outer( - MegaSpecId::REX5, - &mut db, - external_envs, - Bytes::from_static(CREATE2_FACTORY_TX), - LARGE_GAS_LIMIT_OVERRIDE, - ); - - assert!(result.is_success(), "happy-path keyless deploy must succeed; got {result:?}"); - - let signer_after = account_info(&mut db, CREATE2_FACTORY_DEPLOYER); - assert_eq!(signer_after.nonce, 1, "signer nonce must advance to 1 on successful deploy"); - assert_eq!( - signer_after.balance, signer_starting_balance, - "REX5 sandbox is fee-free, signer balance must be unchanged on successful deploy \ - (value = 0 for canonical CREATE2 factory)", - ); - assert!( - has_code(&mut db, CREATE2_FACTORY_CONTRACT), - "deploy address must have contract code after a successful deploy", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/main.rs b/crates/mega-evm/tests/_pending/rex5/main.rs deleted file mode 100644 index 7db9edbf5..000000000 --- a/crates/mega-evm/tests/_pending/rex5/main.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Tests for `Rex5` hardfork features. - -mod apply_pending_changes_gas_budget; -mod callcode_storage_gas; -mod create2_empty_initcode; -mod create2_resize_gas_metering; -mod db_error; -mod eip7702_metering; -mod eip7702_state_growth; -mod keyless_empty_code_logs; -mod keyless_fee_free; -mod keyless_gas_cap_postcap_recheck; -mod keyless_replay_barrier; -mod oracle_hint_metering; -mod pre_block_system_calls; -mod sandbox_accounting; -mod selfdestruct_beneficiary; -mod sstore_storage_gas_error; -mod stipend_accounting; diff --git a/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs b/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs deleted file mode 100644 index e64e732cd..000000000 --- a/crates/mega-evm/tests/_pending/rex5/oracle_hint_metering.rs +++ /dev/null @@ -1,527 +0,0 @@ -//! Tests for the REX5+ oracle hint admission and metering rule. -//! -//! Pre-REX5: `OracleHintInterceptor` invokes `OracleEnv::on_hint` **before** the inner -//! Oracle frame runs, regardless of whether the caller provided gas. A contract can -//! call `sendHint(topic, bigPayload)` with `gas_limit = 0` to forward arbitrary bytes -//! to the off-chain backend while paying nothing — the inner Oracle frame OOGs but the -//! hint has already flowed out. The payload is also not charged against the -//! transaction's data-size budget. -//! -//! Under REX5: -//! 1. Zero-gas `sendHint` falls through to the on-chain Oracle bytecode (no forwarding). -//! 2. The raw `input_bytes.len()` of the inner CALL's calldata — the exact buffer the host just -//! materialized — is recorded against the TX data-size budget via -//! `AdditionalLimit::record_oracle_hint_bytes` **before** `abi_decode` runs. This charges both -//! the legitimate envelope and any trailing junk silently dropped by -//! `alloy_sol_types::abi_decode`, and it covers the malformed-payload case identically. -//! 3. If recording overflows, `on_hint` is NOT invoked; the next `before_frame_init` step produces -//! the canonical TX-level `OutOfGas` halt via `create_exceeded_limit_result`. - -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use alloy_sol_types::{sol, SolCall}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, - ACCOUNT_INFO_WRITE_SIZE, BASE_TX_SIZE, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - inspector::NoOpInspector, -}; - -sol! { - function sendHint(bytes32 topic, bytes calldata data) external; -} - -const CALLER: Address = address!("0000000000000000000000000000000000500000"); -const CALLER_CONTRACT: Address = address!("0000000000000000000000000000000000500001"); - -/// Builds bytecode that: -/// 1. ABI-encodes a `sendHint(topic, data)` call where `data` is `data_size` bytes of zeros (the -/// actual byte values don't matter for the metering test). -/// 2. Stores the calldata in memory. -/// 3. CALLs `ORACLE_CONTRACT_ADDRESS` with the supplied `forward_gas` and the encoded calldata as -/// args. -/// 4. RETURNs the 32-byte CALL success flag. -fn build_send_hint_bytecode(topic: B256, data_size: usize, forward_gas: u64) -> Bytes { - let calldata = sendHintCall { topic, data: Bytes::from(vec![0u8; data_size]) }.abi_encode(); - let calldata_len = calldata.len(); - - let mut builder = BytecodeBuilder::default(); - // Write each 32-byte word of the encoded calldata into memory[0..calldata_len]. - let mut offset = 0; - let calldata_padded_len = calldata_len.div_ceil(32) * 32; - let mut padded = calldata; - padded.resize(calldata_padded_len, 0); - while offset < calldata_padded_len { - let mut word = [0u8; 32]; - word.copy_from_slice(&padded[offset..offset + 32]); - builder = builder.mstore(offset, word); - offset += 32; - } - // Truncate memory expansion to the actual calldata length by marking the last byte - // (no-op write to grow memory if odd-length, otherwise MSTORE above already did). - builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(calldata_len as u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(forward_gas) // gas forwarded - .append(CALL) - // Store success flag at memory[0..32] and RETURN it - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build() -} - -/// Runs a TX that deploys `CALLER_CONTRACT` with `code` and calls into it. Returns -/// (`execution_result`, `recorded_hints`, `final_data_size_usage`). -fn run_with_oracle( - spec: MegaSpecId, - code: Bytes, - data_size_limit: u64, -) -> (ExecutionResult, Vec, u64) { - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CALLER_CONTRACT, code) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits( - EvmTxRuntimeLimits::from_spec(spec).with_tx_data_size_limit(data_size_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLER_CONTRACT) - .gas_limit(100_000_000) - .build_fill(); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - use revm::handler::EvmTr; - let data_size = evm.ctx_ref().additional_limit.borrow().get_usage().data_size; - (envelope.result, external_envs.recorded_hints(), data_size) -} - -/// Runs a TX that directly targets the Oracle contract with `calldata`. -fn run_direct_oracle_tx( - spec: MegaSpecId, - calldata: Bytes, - data_size_limit: u64, -) -> (ExecutionResult, Vec, u64) { - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits( - EvmTxRuntimeLimits::from_spec(spec).with_tx_data_size_limit(data_size_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(ORACLE_CONTRACT_ADDRESS) - .data(calldata) - .gas_limit(100_000_000) - .build_fill(); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - use revm::handler::EvmTr; - let data_size = evm.ctx_ref().additional_limit.borrow().get_usage().data_size; - (envelope.result, external_envs.recorded_hints(), data_size) -} - -const TOPIC: B256 = B256::ZERO; - -/// REX5 invariant 1: a CALL to `sendHint` with `gas_limit = 0` must NOT forward the -/// hint. Pre-REX5 the interceptor would forward regardless of gas, exposing a free -/// side-channel into the off-chain oracle backend. -#[test] -fn test_rex5_zero_gas_send_hint_does_not_forward() { - let code = build_send_hint_bytecode(TOPIC, 64, 0); // 64-byte payload, gas=0 - let (result, hints, _) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - assert!(result.is_success(), "outer tx must succeed (only the inner CALL OOGs)"); - assert!(hints.is_empty(), "zero-gas sendHint must not forward to on_hint (REX5)",); -} - -/// REX5 invariant 2: a normal sendHint with positive gas still forwards to `on_hint` -/// (parity with the pre-REX5 happy path). -#[test] -fn test_rex5_non_zero_gas_send_hint_forwards() { - let code = build_send_hint_bytecode(TOPIC, 128, 100_000); // 128-byte payload - let (result, hints, data_size) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "non-zero-gas sendHint must still forward (REX5)"); - assert_eq!(hints[0].data.len(), 128, "forwarded data length must match"); - // Sanity: the hint payload was counted into the TX data-size lane. - assert!(data_size >= 128, "hint payload ({}) must contribute to data_size", data_size); -} - -/// REX5 direct-to-Oracle transactions intentionally pay for the calldata twice in -/// `data_size`: once as normal intrinsic transaction calldata, and once as the Oracle -/// hint side-channel payload forwarded to the off-chain backend. -#[test] -fn test_rex5_direct_oracle_send_hint_charges_intrinsic_and_hint_payload() { - let calldata = sendHintCall { topic: TOPIC, data: Bytes::from(vec![0u8; 128]) }.abi_encode(); - let calldata_len = calldata.len() as u64; - - let (result, hints, data_size) = - run_direct_oracle_tx(MegaSpecId::REX5, Bytes::from(calldata), u64::MAX); - - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "direct Oracle sendHint must still forward"); - assert_eq!(hints[0].from, CALLER, "direct hint sender must be the tx caller"); - assert_eq!( - data_size, - BASE_TX_SIZE + ACCOUNT_INFO_WRITE_SIZE + calldata_len + calldata_len, - "direct Oracle sendHint must include intrinsic tx calldata plus hint-side-channel bytes", - ); -} - -/// REX5 invariant 3: when the hint payload pushes `data_size_used` past the TX -/// limit, the interceptor must NOT forward the hint, AND the transaction must halt -/// via the canonical TX-level `OutOfGas` path (not a synthetic Revert). -#[test] -fn test_rex5_data_size_overflow_blocks_forwarding_and_halts_canonically() { - // Choose data_size large enough that recording it overflows a tight TX data-size limit. - // Intrinsic usage (BASE_TX + calldata + caller account update) eats some budget already. - let payload_size = 4096; - let limit = 2048; // far below payload_size, guarantees overflow on recording - let code = build_send_hint_bytecode(TOPIC, payload_size, 1_000_000); - let (result, hints, _) = run_with_oracle(MegaSpecId::REX5, code, limit); - - assert!(hints.is_empty(), "overflowing sendHint must NOT forward to on_hint",); - // The TX halts via the canonical exceeded-limit path. The exact halt reason is one of - // the data-size variants emitted by `create_exceeded_limit_result` — accept any non-success - // outcome as long as no hint was forwarded. - assert!( - !result.is_success(), - "tx must halt when sendHint payload overflows the data-size budget", - ); -} - -/// REX5: a wrong selector to `ORACLE_CONTRACT_ADDRESS` does not trigger metering. We -/// verify by sending an unknown selector and asserting `data_size` does not include -/// any hint payload — the call falls through to on-chain bytecode and the hint -/// interceptor never reaches the metering hook. -#[test] -fn test_rex5_wrong_selector_does_not_meter() { - // Construct a CALL with a 4-byte unknown selector + 256 zero bytes. The interceptor - // peek_selector check fails the equality test, returns None without metering. The - // canonical Oracle bytecode then reverts NotIntercepted, so the CALL success flag is 0. - let unknown_selector = [0xde, 0xad, 0xbe, 0xef]; - let payload_size = 256; - let code = BytecodeBuilder::default() - .mstore(0, unknown_selector) - .push_number(0u64) - .push_number((4 + payload_size - 1) as u64) - .append(MSTORE8) // grow memory - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number((4 + payload_size) as u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - let (_result, hints, data_size_after) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - assert!(hints.is_empty(), "wrong selector must not invoke on_hint"); - // Baseline data_size without any hint payload: BASE_TX_SIZE + caller account info + - // empty tx input. The exact value depends on intrinsic accounting; what we pin is - // that the 256-byte payload is NOT included. - assert!( - data_size_after < 256, - "wrong selector must not record hint payload bytes (data_size = {})", - data_size_after, - ); -} - -/// Builds bytecode that writes `calldata` into memory, CALLs the oracle contract with -/// `forward_gas` and `calldata.len()` argsSize, and RETURNs the 32-byte CALL success flag. -fn build_oracle_call_with_raw_calldata(calldata: Vec, forward_gas: u64) -> Bytes { - let calldata_len = calldata.len(); - let padded_len = calldata_len.div_ceil(32) * 32; - let mut padded = calldata; - padded.resize(padded_len, 0); - - let mut builder = BytecodeBuilder::default(); - let mut offset = 0; - while offset < padded_len { - let mut word = [0u8; 32]; - word.copy_from_slice(&padded[offset..offset + 32]); - builder = builder.mstore(offset, word); - offset += 32; - } - builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(calldata_len as u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(forward_gas) // gas forwarded - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build() -} - -/// A `sendHint` call whose payload is the selector followed by raw garbage fails to -/// ABI-decode, but the host has already materialized `input_bytes`. REX5 charges the -/// raw `input_bytes.len()` against the TX data-size budget before `abi_decode`, so a -/// caller cannot force unmetered host work by sending malformed `sendHint` calldata. -#[test] -fn test_rex5_malformed_send_hint_is_metered() { - // 4-byte selector + 1024 bytes of garbage. `abi_decode` rejects it. - let garbage_len = 1024usize; - let mut calldata: Vec = sendHintCall::SELECTOR.to_vec(); - calldata.extend(core::iter::repeat_n(0xab, garbage_len)); - let total = calldata.len() as u64; - - // Generous budget: confirm the malformed payload is metered to its full length and - // no hint is forwarded. - let code = build_oracle_call_with_raw_calldata(calldata.clone(), 1_000_000); - let (result, hints, data_size) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - assert!(result.is_success(), "outer tx must succeed under a generous budget"); - assert!(hints.is_empty(), "malformed sendHint must NOT forward to on_hint"); - assert!( - data_size >= total, - "input_bytes.len()={total} must be fully charged against data_size (got {data_size})", - ); - - // Tight budget below `total`: malformed payload must trigger canonical OOG halt. - let code = build_oracle_call_with_raw_calldata(calldata, 1_000_000); - let (result, hints, _) = run_with_oracle(MegaSpecId::REX5, code, total / 2); - assert!(!result.is_success(), "tight budget must trigger canonical OOG halt"); - assert!(hints.is_empty(), "malformed sendHint must NOT forward under overflow"); -} - -/// A valid `sendHint` ABI envelope followed by huge trailing junk: `abi_decode` -/// silently drops the trailing bytes (pinned by -/// `test_alloy_abi_decode_accepts_selector_plus_trailing_bytes_on_zero_arg_calls` in -/// `crates/mega-evm/src/system/intercept.rs`). Charging only `data.len() + 32` would -/// let a caller forward unmetered megabytes of trailing junk; charging -/// `input_bytes.len()` before `abi_decode` closes that gap. -#[test] -fn test_rex5_trailing_junk_after_valid_send_hint_is_metered() { - // Valid abi_encode of sendHint(topic, empty data), then a large run of trailing junk. - let valid = sendHintCall { topic: TOPIC, data: Bytes::new() }.abi_encode(); - let junk_len = 4096usize; - let mut calldata = valid; - calldata.extend(core::iter::repeat_n(0xcd, junk_len)); - let total = calldata.len() as u64; - - // Generous budget: the envelope is valid, the hint is forwarded with decoded - // (empty) data, but the full `input_bytes.len()` (envelope + trailing junk) is - // charged against the data-size lane. - let code = build_oracle_call_with_raw_calldata(calldata.clone(), 1_000_000); - let (result, hints, data_size) = run_with_oracle(MegaSpecId::REX5, code, u64::MAX); - assert!(result.is_success()); - assert_eq!(hints.len(), 1, "valid envelope still forwards under REX5"); - assert_eq!(hints[0].data.len(), 0, "decoded data must drop the trailing junk"); - assert!( - data_size >= total, - "full input length {total} (incl. {junk_len} trailing junk bytes) must be metered \ - (got {data_size})", - ); - - // Tight budget below `total`: trailing junk must NOT be allowed to forward. - let code = build_oracle_call_with_raw_calldata(calldata, 1_000_000); - let (result, hints, _) = run_with_oracle(MegaSpecId::REX5, code, total / 2); - assert!(!result.is_success(), "tight budget must trigger canonical OOG halt"); - assert!(hints.is_empty(), "trailing junk must NOT forward when over budget"); -} - -/// REX5 invariant: consecutive `sendHint` calls in the same TX accumulate their -/// `input_bytes.len()` charges into the TX `persistent_usage` lane. With a budget sized -/// for one call but not two, the first sendHint must forward and the second must be -/// blocked by the accumulated overflow — TX halts via canonical OOG. Pins that hint -/// metering is TX-scoped, not per-call. -#[test] -fn test_rex5_consecutive_send_hints_accumulate_into_tx_lane() { - let payload = 256; - let calldata = - sendHintCall { topic: TOPIC, data: Bytes::from(vec![0u8; payload]) }.abi_encode(); - let calldata_len = calldata.len(); - let padded_len = calldata_len.div_ceil(32) * 32; - let mut padded = calldata; - padded.resize(padded_len, 0); - - let mut builder = BytecodeBuilder::default(); - let mut offset = 0; - while offset < padded_len { - let mut word = [0u8; 32]; - word.copy_from_slice(&padded[offset..offset + 32]); - builder = builder.mstore(offset, word); - offset += 32; - } - // First CALL: sendHint. - builder = builder - .push_number(0u64) - .push_number(0u64) - .push_number(calldata_len as u64) - .push_number(0u64) - .push_number(0u64) - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .append(POP); - // Second CALL: sendHint (same calldata, memory still holds it). - let code = builder - .push_number(0u64) - .push_number(0u64) - .push_number(calldata_len as u64) - .push_number(0u64) - .push_number(0u64) - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - - // Budget allows one `input_bytes.len()` (plus a small intrinsic head-room) but not two. - let limit = (calldata_len as u64) + (calldata_len as u64) / 2; - let (result, hints, _) = run_with_oracle(MegaSpecId::REX5, code, limit); - - assert!( - !result.is_success(), - "tx must halt when the second sendHint's input_bytes.len() pushes the accumulator over", - ); - assert_eq!( - hints.len(), - 1, - "first sendHint forwards; second must be blocked by the accumulated TX budget", - ); -} - -/// REX5 invariant: hint bytes recorded by the interceptor enter the TX-persistent -/// data-size lane (`tx_entry.persistent_usage`), not the per-frame discardable lane. -/// Even when the call frame that initiated the `sendHint` reverts, the charge persists -/// and the hint stays forwarded. Pins the docstring claim in -/// `data_size.rs::record_oracle_hint_bytes` — a regression that routed the charge -/// through the discardable frame lane would let callers spam hints from a doomed-to- -/// revert frame for free. -#[test] -fn test_rex5_hint_charge_persists_across_initiating_frame_revert() { - const INNER: Address = address!("0000000000000000000000000000000000500002"); - - let payload = 256; - let calldata = - sendHintCall { topic: TOPIC, data: Bytes::from(vec![0u8; payload]) }.abi_encode(); - let calldata_len = calldata.len(); - let padded_len = calldata_len.div_ceil(32) * 32; - let mut padded = calldata; - padded.resize(padded_len, 0); - - // INNER: MSTORE the sendHint calldata, CALL oracle, then REVERT(0, 0). - let mut inner = BytecodeBuilder::default(); - let mut offset = 0; - while offset < padded_len { - let mut word = [0u8; 32]; - word.copy_from_slice(&padded[offset..offset + 32]); - inner = inner.mstore(offset, word); - offset += 32; - } - let inner_code = inner - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(calldata_len as u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(1_000_000u64) - .append(CALL) - .append(POP) - .push_number(0u64) // REVERT size - .push_number(0u64) // REVERT offset - .append(REVERT) - .build(); - - // CALLER_CONTRACT: CALL INNER, store success flag, RETURN. - let outer_code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(INNER) - .push_number(10_000_000u64) - .append(CALL) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(CALLER_CONTRACT, outer_code) - .account_code(INNER, inner_code) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX2); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits( - EvmTxRuntimeLimits::from_spec(MegaSpecId::REX5).with_tx_data_size_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLER_CONTRACT) - .gas_limit(100_000_000) - .build_fill(); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - use revm::handler::EvmTr; - let data_size = evm.ctx_ref().additional_limit.borrow().get_usage().data_size; - - assert!( - envelope.result.is_success(), - "outer TX must succeed (only the INNER frame reverts after its sendHint)", - ); - let hints = external_envs.recorded_hints(); - assert_eq!(hints.len(), 1, "hint must be forwarded before INNER's REVERT"); - assert!( - data_size >= calldata_len as u64, - "hint bytes ({calldata_len}) must persist across initiating frame REVERT (got {data_size})", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs b/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs deleted file mode 100644 index bd52867ca..000000000 --- a/crates/mega-evm/tests/_pending/rex5/pre_block_system_calls.rs +++ /dev/null @@ -1,672 +0,0 @@ -#![allow(clippy::doc_markdown)] -//! End-to-end tests for REX5 pre-block system call result handling. -//! -//! Under `MegaSpecId::REX5`, a non-`Success` result from the EIP-2935 or -//! EIP-4788 pre-block system call must reject the block before any state -//! delta is committed or observed by the on-state hook. Pre-REX5 chains -//! keep their existing accept-and-commit-empty behavior. - -use std::{ - convert::Infallible, - sync::{Arc, Mutex}, -}; - -use alloy_evm::{ - block::{BlockExecutor, BlockValidationError, OnStateHook, StateChangeSource}, - Evm, EvmEnv, -}; -use alloy_hardforks::{EthereumHardfork, ForkCondition}; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{Address, Bytes, B256, U256}; -use mega_evm::{ - test_utils::{ErrorInjectingDatabase, MemoryDatabase}, - BlockLimits, BucketHasher, BucketId, MegaBlockExecutionCtx, MegaBlockExecutorFactory, - MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, SequencerRegistryConfig, - TestExternalEnvs, -}; -use revm::{ - context::BlockEnv, - database::{Database as _, State}, - state::{AccountInfo, Bytecode, EvmState}, -}; - -const ACTIVATION_BLOCK: u64 = 1000; - -/// Bucket that every SALT lookup is routed to under [`SingleBucketHasher`]. -const HEAVY_BUCKET_ID: BucketId = 100_000; -/// Capacity = 100,000 × `MIN_BUCKET_SIZE` (256). Yields a 100,000× multiplier, -/// so each zero→nonzero `SSTORE` charges ≈ 2G of dynamic storage gas. EIP-2935 -/// performs at least one such write per pre-block call, which exceeds the -/// REX5 `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` budget for any -/// reasonable block gas limit and forces a Halt. -const HEAVY_BUCKET_CAPACITY: u64 = 25_600_000; -/// Capacity = 5000 × `MIN_BUCKET_SIZE` (256). Yields a 5000× multiplier, so -/// each zero→nonzero `SSTORE` charges ≈ 100M of dynamic storage gas — above -/// revm's upstream-fixed 30M default but inside the REX5 block-aware budget -/// at [`BLOCK_GAS_LIMIT`]. Used to demonstrate that the REX5 gas-limit floor -/// unlocks pre-block writes that would have OOG'd under the 30M default. -const MEDIUM_BUCKET_CAPACITY: u64 = 1_280_000; -const BLOCK_GAS_LIMIT: u64 = 250_000_000; - -const BOOTSTRAP_SEQUENCER: Address = - alloy_primitives::address!("4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = - alloy_primitives::address!("5000000000000000000000000000000000000005"); - -/// Routes every account / slot to a single bucket so the heavy capacity bites -/// every `SSTORE` performed by the pre-block helpers, regardless of the slot. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - HEAVY_BUCKET_ID - } -} - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -fn create_evm_env(spec: MegaSpecId, gas_limit: u64) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = spec; - let block_env = BlockEnv { - number: U256::from(ACTIVATION_BLOCK), - timestamp: U256::from(1_800_000_000), - gas_limit, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn rex5_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()) -} - -fn rex4_chain_spec() -> MegaHardforkConfig { - // Activate up to Rex4 only — Rex5 stays at `ForkCondition::Never`, so the - // activated-spec floor stays below REX5 and the Rex5 fail-closed check is - // skipped. Sequencer registry is not needed because its deploy is gated - // on the same floor. - MegaHardforkConfig::default().with(MegaHardfork::Rex4, ForkCondition::Timestamp(0)) -} - -fn install_eip2935_history_storage(db: &mut MemoryDatabase) { - let bytecode = Bytecode::new_raw(alloy_eips::eip2935::HISTORY_STORAGE_CODE.clone()); - db.insert_account_info( - alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -fn install_eip4788_beacon_roots(db: &mut MemoryDatabase) { - let bytecode = Bytecode::new_raw(alloy_eips::eip4788::BEACON_ROOTS_CODE.clone()); - db.insert_account_info( - alloy_eips::eip4788::BEACON_ROOTS_ADDRESS, - AccountInfo { code_hash: bytecode.hash_slow(), code: Some(bytecode), ..Default::default() }, - ); -} - -fn heavy_external_envs() -> TestExternalEnvs { - TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET_ID, HEAVY_BUCKET_CAPACITY) -} - -fn medium_external_envs() -> TestExternalEnvs { - TestExternalEnvs::::new() - .with_bucket_capacity(HEAVY_BUCKET_ID, MEDIUM_BUCKET_CAPACITY) -} - -fn light_external_envs() -> TestExternalEnvs { - // Default capacity for the heavy bucket → 1× multiplier, normal gas cost. - TestExternalEnvs::::new() -} - -/// Recording state hook that captures every `(StateChangeSource, EvmState)` -/// pair the block executor reports, so a test can assert that a failed -/// pre-block call's state delta did NOT enter the witness path. -#[derive(Debug, Default, Clone)] -struct RecordingStateHook { - events: Arc>>, -} - -impl OnStateHook for RecordingStateHook { - fn on_state(&mut self, source: StateChangeSource, _state: &EvmState) { - self.events.lock().unwrap().push(source); - } -} - -/// Block setup with parent_hash = nonzero (so EIP-2935 actually runs the -/// SSTORE) and parent_beacon_block_root = nonzero. The non-genesis block -/// number means the helpers don't take the genesis-skip early-return. -fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), // parent_hash - Some(B256::from([0x47; 32])), // parent_beacon_block_root - Bytes::new(), - BlockLimits::no_limits(), - ) -} - -/// Heavy SALT makes the EIP-2935 history-storage SSTORE OOG inside the -/// REX5 `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` budget. Under -/// REX5+, the block executor must reject the block, and the failed call's -/// state delta must not reach the on-state hook. -#[test] -fn test_rex5_block_rejected_when_blockhashes_pre_block_call_halts() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - // Recording state hook so we can also pin the witness-path invariant. - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - let err = executor - .apply_pre_execution_changes() - .expect_err("REX5 must reject a halted EIP-2935 pre-block system call"); - - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "Expected BlockHashContractCall, got: {validation_err:?}" - ); - - // The failed pre-block call's state delta must not reach the on-state hook. - let recorded = events.lock().unwrap(); - let saw_block_hashes = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BlockHashesContract - ) - ) - }); - assert!( - !saw_block_hashes, - "Failed EIP-2935 pre-block call's state delta must NOT enter the on-state \ - witness path; recorded sources: {recorded:?}" - ); -} - -/// Symmetric to `..._blockhashes_...`: heavy SALT makes the EIP-4788 -/// beacon-roots SSTORE OOG; REX5+ must reject the block. -#[test] -fn test_rex5_block_rejected_when_beacon_root_pre_block_call_halts() { - let mut db = MemoryDatabase::default(); - // No EIP-2935 bytecode → its system call returns Ok(Success) trivially. - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("REX5 must reject a halted EIP-4788 pre-block system call"); - - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BeaconRootContractCall { .. }), - "Expected BeaconRootContractCall, got: {validation_err:?}" - ); -} - -/// Medium SALT makes each EIP-2935 / EIP-4788 SSTORE cost ≈ 100M of -/// dynamic storage gas — above revm's upstream-fixed 30M default but -/// within the REX5 `max(block.gas_limit, SYSTEM_CALL_GAS_LIMIT_FLOOR)` -/// budget at [`BLOCK_GAS_LIMIT`]. Asserts the block-aware budget unlocks -/// pre-block writes that would have OOG'd under the upstream default, -/// so both pre-block calls succeed and reach the on-state hook. -#[test] -fn test_rex5_block_aware_budget_accepts_pre_block_call_above_30m() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(medium_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - executor - .apply_pre_execution_changes() - .expect("REX5 block-aware budget must accept pre-block SSTORE costs above the 30M floor"); - - let recorded = events.lock().unwrap(); - let saw_block_hashes = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BlockHashesContract - ) - ) - }); - let saw_beacon_root = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BeaconRootContract - ) - ) - }); - assert!( - saw_block_hashes, - "EIP-2935 pre-block call must succeed at ≈100M cost under the block-aware \ - REX5 budget; sources: {recorded:?}", - ); - assert!( - saw_beacon_root, - "EIP-4788 pre-block call must succeed at ≈100M cost under the block-aware \ - REX5 budget; sources: {recorded:?}", - ); -} - -/// Successful pre-block system calls under REX5 commit normally and -/// reach the on-state hook. -#[test] -fn test_rex5_successful_pre_block_call_commits_normally() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - executor - .apply_pre_execution_changes() - .expect("REX5 must accept successful pre-block system calls"); - - // Both EIP-2935 and EIP-4788 outcomes appear in the witness path. - let recorded = events.lock().unwrap(); - let saw_block_hashes = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BlockHashesContract - ) - ) - }); - let saw_beacon_root = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BeaconRootContract - ) - ) - }); - assert!( - saw_block_hashes, - "Successful EIP-2935 pre-block call must reach the on-state hook; sources: {recorded:?}" - ); - assert!( - saw_beacon_root, - "Successful EIP-4788 pre-block call must reach the on-state hook; sources: {recorded:?}" - ); -} - -/// At block number 0 both pre-block helpers return `None` (no system -/// call attempted); the REX5 check is a no-op on this path. -#[test] -fn test_rex5_genesis_block_pre_block_call_skip_unaffected() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(heavy_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - - // Block number 0 — genesis-skip in both helpers. - let genesis_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::ZERO), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX5; - let block_env = BlockEnv { - number: U256::ZERO, - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let mut executor = block_executor_factory.create_executor(&mut state, genesis_ctx, evm_env); - - executor.apply_pre_execution_changes().expect( - "Genesis block must skip pre-block system calls (helpers return None) and the \ - REX5 check must be a no-op on this path", - ); -} - -/// Prague inactive: `transact_blockhashes_contract_call` returns `Ok(None)` -/// without firing the EIP-2935 system call. The on-state hook should record -/// the EIP-4788 beacon-roots delta (Cancun stays active) but never observe -/// a `BlockHashesContract` event. -#[test] -fn test_prague_inactive_skips_blockhashes_pre_block_call() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - // Start from the REX5 spec but override Prague to `Never` so the EIP-2935 - // helper takes its `is_prague_active_at_timestamp == false` early return. - let chain_spec = rex5_chain_spec().with(EthereumHardfork::Prague, ForkCondition::Never); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - executor - .apply_pre_execution_changes() - .expect("Prague-inactive helper must skip silently, not error the block"); - - let recorded = events.lock().unwrap(); - let saw_block_hashes = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BlockHashesContract - ) - ) - }); - assert!( - !saw_block_hashes, - "Prague-inactive helper must NOT enter the witness path; sources: {recorded:?}", - ); -} - -/// Cancun inactive: `transact_beacon_root_contract_call` returns `Ok(None)` -/// without firing the EIP-4788 system call. Symmetric to the Prague test. -#[test] -fn test_cancun_inactive_skips_beacon_root_pre_block_call() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let chain_spec = rex5_chain_spec().with(EthereumHardfork::Cancun, ForkCondition::Never); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let recorder = RecordingStateHook::default(); - let events = recorder.events.clone(); - BlockExecutor::set_state_hook(&mut executor, Some(Box::new(recorder))); - - executor - .apply_pre_execution_changes() - .expect("Cancun-inactive helper must skip silently, not error the block"); - - let recorded = events.lock().unwrap(); - let saw_beacon_root = recorded.iter().any(|s| { - matches!( - s, - StateChangeSource::PreBlock( - alloy_evm::block::StateChangePreBlockSource::BeaconRootContract - ) - ) - }); - assert!( - !saw_beacon_root, - "Cancun-inactive helper must NOT enter the witness path; sources: {recorded:?}", - ); -} - -/// Non-genesis block with `parent_beacon_block_root = None`: -/// `transact_beacon_root_contract_call` rejects with -/// `BlockValidationError::MissingParentBeaconBlockRoot`. EIP-2935 fires -/// successfully first (light SALT) so the failure path is the beacon helper. -#[test] -fn test_missing_parent_beacon_block_root_rejects_block() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - - // Same block as block_ctx() but with parent_beacon_block_root = None. - let ctx_missing = MegaBlockExecutionCtx::new( - B256::from([0x29; 32]), - None, - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - ctx_missing, - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("missing parent_beacon_block_root at a non-genesis block must reject"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::MissingParentBeaconBlockRoot), - "Expected MissingParentBeaconBlockRoot, got: {validation_err:?}", - ); -} - -/// Genesis block (`block.number == 0`) with a non-zero `parent_beacon_block_root`: -/// `transact_beacon_root_contract_call` rejects with -/// `BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero`. EIP-2935 -/// returns `Ok(None)` early on genesis, so the failure is from the beacon helper. -#[test] -fn test_genesis_non_zero_parent_beacon_block_root_rejects_block() { - let mut db = MemoryDatabase::default(); - install_eip2935_history_storage(&mut db); - install_eip4788_beacon_roots(&mut db); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - - // Genesis context with a non-zero parent_beacon_block_root. - let genesis_ctx = MegaBlockExecutionCtx::new( - B256::ZERO, - Some(B256::from([0x47; 32])), - Bytes::new(), - BlockLimits::no_limits(), - ); - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX5; - let block_env = BlockEnv { - number: U256::ZERO, - timestamp: U256::from(1_800_000_000), - gas_limit: BLOCK_GAS_LIMIT, - ..Default::default() - }; - let evm_env = EvmEnv::new(cfg_env, block_env); - - let mut executor = block_executor_factory.create_executor(&mut state, genesis_ctx, evm_env); - - let err = executor - .apply_pre_execution_changes() - .expect_err("genesis with non-zero parent_beacon_block_root must reject"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!( - validation_err, - BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { .. } - ), - "Expected CancunGenesisParentBeaconBlockRootNotZero, got: {validation_err:?}", - ); -} - -/// DB-level error during the EIP-2935 system call: the wrapped database returns -/// an injected error on the first read of the history-storage contract, so -/// `transact_system_call` propagates an `EVMError` and the eips.rs helper must -/// map it to `BlockValidationError::BlockHashContractCall { message: ... }`. -#[test] -fn test_blockhashes_pre_block_call_db_error_returns_validation_error() { - let mut inner = MemoryDatabase::default(); - install_eip2935_history_storage(&mut inner); - install_eip4788_beacon_roots(&mut inner); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("DB error during EIP-2935 system call must reject the block"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BlockHashContractCall { .. }), - "Expected BlockHashContractCall, got: {validation_err:?}", - ); -} - -/// DB-level error during the EIP-4788 system call: EIP-2935 fires successfully -/// first (light SALT, history-storage contract reads fine), then the wrapped -/// database fails on the beacon-roots contract read, so `transact_system_call` -/// propagates an `EVMError` and the eips.rs helper maps it to -/// `BlockValidationError::BeaconRootContractCall { message: ... }`. -#[test] -fn test_beacon_root_pre_block_call_db_error_returns_validation_error() { - let mut inner = MemoryDatabase::default(); - install_eip2935_history_storage(&mut inner); - install_eip4788_beacon_roots(&mut inner); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(alloy_eips::eip4788::BEACON_ROOTS_ADDRESS); - let mut state = State::builder().with_database(&mut db).build(); - - let evm_factory = MegaEvmFactory::new().with_external_env_factory(light_external_envs()); - let block_executor_factory = MegaBlockExecutorFactory::new( - rex5_chain_spec(), - evm_factory, - OpAlloyReceiptBuilder::default(), - ); - let mut executor = block_executor_factory.create_executor( - &mut state, - block_ctx(), - create_evm_env(MegaSpecId::REX5, BLOCK_GAS_LIMIT), - ); - - let err = executor - .apply_pre_execution_changes() - .expect_err("DB error during EIP-4788 system call must reject the block"); - let validation_err = match &err { - alloy_evm::block::BlockExecutionError::Validation(v) => v, - other => panic!("Expected Validation error, got: {other:?}"), - }; - assert!( - matches!(validation_err, BlockValidationError::BeaconRootContractCall { .. }), - "Expected BeaconRootContractCall, got: {validation_err:?}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs b/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs deleted file mode 100644 index d9e13f7cd..000000000 --- a/crates/mega-evm/tests/_pending/rex5/sandbox_accounting.rs +++ /dev/null @@ -1,777 +0,0 @@ -//! Tests for sandbox resource usage propagation. -//! -//! REX5 propagates resource usage (compute gas, data size, KV updates, state growth) -//! from sandbox execution (e.g., keyless deploy) back to the parent transaction. -//! Pre-REX5 specs do not propagate sandbox resource usage. - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - constants, - revm::context::result::{ExecutionResult, ResultAndState}, - sandbox::{calculate_keyless_deploy_address, decode_error_result, KeylessDeployError}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IKeylessDeploy, IOracle, LimitKind, LimitUsage, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, TestExternalEnvs, VolatileDataAccess, - ACCOUNT_INFO_WRITE_SIZE, AUTHORIZATION_SIZE, BASE_TX_SIZE, KEYLESS_DEPLOY_ADDRESS, - ORACLE_CONTRACT_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{transaction::AuthorizationTr, Transaction, TxEnv}, - handler::EvmTr, - inspector::NoOpInspector, -}; - -// ============================================================================ -// TEST CONSTANTS -// ============================================================================ - -/// Standard test caller address. -const TEST_CALLER: Address = address!("0000000000000000000000000000000000100000"); - -/// Large gas limit override for tests (10 billion gas). -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; - -/// Signer balance large enough that tests never hit `InsufficientBalance` on their own. -const LARGE_SIGNER_BALANCE: u128 = 1_000_000_000_000_000_000_000; - -/// Outer transaction's gas limit for tests; matches `keyless_deploy_call_tx`. -const OUTER_TX_GAS_LIMIT: u64 = 1_000_000_000_000; - -// ============================================================================ -// HELPER FUNCTIONS -// ============================================================================ - -/// Builds a minimal constructor that SSTOREs a single slot and returns 1 byte of runtime -/// code. The exact stored value is arbitrary — callers pass any non-zero byte just to -/// give the constructor observable compute / state-growth work. -fn minimal_1byte_constructor(storage_value: u8) -> Bytes { - BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(storage_value)) - .push_number(1_u8) - .push_number(0_u8) // CODECOPY offset - .push_number(0_u8) // memory dest - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Builds a fresh `MemoryDatabase` with `signer` funded to `LARGE_SIGNER_BALANCE`. -fn funded_signer_db(signer: Address) -> MemoryDatabase { - let mut db = MemoryDatabase::default(); - db.set_account_balance(signer, U256::from(LARGE_SIGNER_BALANCE)); - db -} - -/// Runs a baseline Rex5 keyless deploy to measure the resource usage a successful -/// deployment consumes. Returns `(tx_bytes, signer, deploy_address, baseline_usage)`, -/// asserting the baseline succeeds. Tests use this to derive tight cap / overflow values -/// without hardcoding constants. -fn rex5_baseline(init_code: Bytes) -> (Bytes, Address, Address, LimitUsage) { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - let mut db = funded_signer_db(signer); - let (result, usage) = execute_keyless_deploy( - MegaSpecId::REX5, - &mut db, - tx_bytes.clone(), - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "baseline keyless deploy should succeed: {result:?}"); - (tx_bytes, signer, deploy_address, usage) -} - -/// Creates a pre-EIP-155 keyless deploy transaction with deterministic signature. -fn create_pre_eip155_deploy_tx(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: 100_000_000_000, - gas_limit: 1_000_000, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - - let r = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let s = U256::from_be_bytes(hex!( - "2222222222222222222222222222222222222222222222222222222222222222" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - - (tx_bytes, signer) -} - -/// Builds the outer `KeylessDeploy` transaction used by the test helpers. -fn keyless_deploy_call_tx( - keyless_deployment_tx: Bytes, - gas_limit_override: u64, -) -> MegaTransaction { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_deployment_tx, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let tx = TxEnv { - caller: TEST_CALLER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: 1_000_000_000_000, - gas_price: 0, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Builds the sandbox create transaction shape used by `KeylessDeploy`. -fn sandbox_create_tx_for_intrinsic(init_code: Bytes, signer: Address) -> MegaTransaction { - let tx = TxEnv { - caller: signer, - kind: TxKind::Create, - data: init_code, - value: U256::ZERO, - gas_limit: LARGE_GAS_LIMIT_OVERRIDE, - gas_price: 100_000_000_000, - nonce: 0, - ..Default::default() - }; - MegaTransaction::new(tx) -} - -/// Computes the intrinsic compute gas that Rex5 records during transaction validation. -/// -/// Must match the value `MegaHandler::validate` feeds into `record_compute_gas`, which is -/// the raw revm `initial_gas`. This helper calls the same revm routine, so it stays in -/// lock-step with production without replicating logic. -fn intrinsic_compute_gas(tx: &MegaTransaction) -> u64 { - mega_evm::revm::interpreter::gas::calculate_initial_tx_gas_for_tx( - tx, - MegaSpecId::REX5.into_eth_spec(), - ) - .initial_gas -} - -/// Computes the intrinsic data-size usage recorded before the first frame. -/// -/// Mirrors `DataSizeTracker::before_tx_start` in `src/limit/data_size.rs`. If that -/// function grows a new contribution, update this helper in sync — otherwise this test -/// will understate the sandbox intrinsic and the "preflight rejects intrinsic overflow" -/// cases can silently fall through to the `merge_and_reject_if_overflow` safety net path -/// instead of exercising the preflight fast-path they are meant to cover. -fn intrinsic_data_size(tx: &MegaTransaction) -> u64 { - let access_list_size = tx - .access_list() - .map(|item| item.map(|access| access.size() as u64).sum::()) - .unwrap_or_default(); - let authority_updates = - tx.authorization_list().filter(|authorization| authorization.authority().is_some()).count() - as u64 * - ACCOUNT_INFO_WRITE_SIZE; - - BASE_TX_SIZE + - tx.input().len() as u64 + - access_list_size + - tx.authorization_list_len() as u64 * AUTHORIZATION_SIZE + - authority_updates + - ACCOUNT_INFO_WRITE_SIZE -} - -/// Computes the intrinsic KV updates recorded before the first frame. -/// -/// Mirrors `KVUpdateTracker::before_tx_start`: the transaction caller update plus one -/// account update per valid EIP-7702 authority. -fn intrinsic_kv_updates(tx: &MegaTransaction) -> u64 { - tx.authorization_list().filter(|authorization| authorization.authority().is_some()).count() - as u64 + - 1 -} - -/// Executes a keyless deploy and returns the execution result and resource usage. -fn execute_keyless_deploy( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_deployment_tx: Bytes, - gas_limit_override: u64, -) -> (ExecutionResult, LimitUsage) { - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let tx = keyless_deploy_call_tx(keyless_deployment_tx, gas_limit_override); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (result_envelope.result, usage) -} - -/// Variant of [`execute_keyless_deploy`] that also returns the parent's -/// `VolatileDataAccess` bitmap after the call returns. -fn execute_keyless_deploy_with_volatile( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_deployment_tx: Bytes, - gas_limit_override: u64, -) -> (ExecutionResult, LimitUsage, VolatileDataAccess) { - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let tx = keyless_deploy_call_tx(keyless_deployment_tx, gas_limit_override); - let result_envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - let volatile = evm.ctx_ref().volatile_data_tracker.borrow().get_volatile_data_accessed(); - (result_envelope.result, usage, volatile) -} - -/// Constructor that reads `block.timestamp` (TIMESTAMP opcode), then deploys a -/// 1-byte runtime contract. Sets `VolatileDataAccess::TIMESTAMP` in the -/// sandbox tracker. -fn constructor_reads_timestamp() -> Bytes { - BytecodeBuilder::default() - .append(TIMESTAMP) - .append(POP) - .sstore(U256::from(0), U256::from(1)) - .push_number(1_u8) - .push_number(0_u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Constructor that reads `block.coinbase` (COINBASE opcode), then deploys. -/// Sets `VolatileDataAccess::COINBASE` only (NOT `BENEFICIARY_BALANCE`; that -/// bit requires `BALANCE` against the coinbase address). -fn constructor_reads_coinbase() -> Bytes { - BytecodeBuilder::default() - .append(COINBASE) - .append(POP) - .sstore(U256::from(0), U256::from(1)) - .push_number(1_u8) - .push_number(0_u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Constructor: `COINBASE; BALANCE; POP; ...deploy...`. Reads the beneficiary -/// balance via the BALANCE opcode, which sets -/// `VolatileDataAccess::BENEFICIARY_BALANCE` via `mark_beneficiary_balance_accessed`. -fn constructor_reads_coinbase_balance() -> Bytes { - BytecodeBuilder::default() - .append(COINBASE) - .append(BALANCE) - .append(POP) - .sstore(U256::from(0), U256::from(1)) - .push_number(1_u8) - .push_number(0_u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Constructor that STATICCALLs `IOracle::getSlot(0)` on the oracle contract. -/// The oracle's bytecode executes SLOAD on its own storage to fetch the slot, -/// which goes through the host `sload` wrapper and sets -/// `VolatileDataAccess::ORACLE` on the sandbox tracker (Rex3+ marks oracle -/// access on SLOAD inside the oracle frame, not on the outer CALL). -fn constructor_calls_oracle() -> Bytes { - // Build the calldata for `getSlot(0)` as a single 32-byte word: the - // 4-byte selector in the high bytes, followed by 28 zero bytes which - // overlap with the high 28 bytes of the (zero) key word. After MSTORE, - // memory[0..4] = selector, memory[4..32] = 0, and the auto-zero memory - // extension at offset 32..36 supplies the remaining 4 bytes of the - // key argument. - use alloy_sol_types::SolCall; - let mut selector_word_bytes = [0u8; 32]; - selector_word_bytes[0..4].copy_from_slice(&IOracle::getSlotCall::SELECTOR); - let selector_word = U256::from_be_bytes(selector_word_bytes); - - BytecodeBuilder::default() - .push_u256(selector_word) - .push_number(0_u8) // memory dest offset - .append(MSTORE) - // STATICCALL stack (top is last push): gas, address, argsOff, argsSize, retOff, retSize - .push_number(0_u8) // retSize - .push_number(0_u8) // retOffset - .push_number(36_u8) // argsSize (4 selector + 32 key) - .push_number(0_u8) // argsOffset - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(100_000_u128) // forwarded gas - .append(STATICCALL) - .append(POP) - .sstore(U256::from(0), U256::from(1)) - .push_number(1_u8) - .push_number(0_u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build() -} - -/// Decodes the ABI-encoded `KeylessDeploy` return payload. -fn decode_keyless_deploy_return( - result: &ExecutionResult, -) -> IKeylessDeploy::keylessDeployReturn { - let output = result.output().expect("keyless deploy should return ABI-encoded output"); - IKeylessDeploy::keylessDeployCall::abi_decode_returns(output) - .expect("keyless deploy return should decode") -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// REX5 sandbox success propagates resource usage to the parent transaction. -/// -/// A keyless deploy constructor that writes storage slots should have its resource usage -/// (compute gas, data size, KV updates, state growth) reflected in the parent transaction. -#[test] -fn test_rex5_sandbox_success_propagates_resource_usage() { - // Constructor that writes two storage slots, then returns 1 byte of runtime code. - // Two-slot variant (vs the shared `minimal_1byte_constructor`) exercises multiple KV - // updates so the kv_updates assertion below is non-trivial. - let init_code = BytecodeBuilder::default() - .sstore(U256::from(0), U256::from(42)) - .sstore(U256::from(1), U256::from(43)) - .push_number(1_u8) - .push_number(0_u8) - .push_number(0_u8) - .append(CODECOPY) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build(); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - - let (result, usage) = - execute_keyless_deploy(MegaSpecId::REX5, &mut db, tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - assert!(result.is_success(), "keyless deploy should succeed: {result:?}"); - - // REX5 should propagate sandbox resource usage to parent. - assert!(usage.compute_gas > 0, "compute gas should include sandbox execution"); - assert!(usage.data_size > 0, "data size should include sandbox storage writes"); - assert!(usage.kv_updates > 0, "KV updates should include sandbox storage writes"); - assert!(usage.state_growth > 0, "state growth should include new account from sandbox"); -} - -/// Executes a keyless deploy with custom runtime limits, returning the full `ResultAndState`. -fn execute_keyless_deploy_with_limits( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_deployment_tx: Bytes, - gas_limit_override: u64, - tx_limits: EvmTxRuntimeLimits, -) -> ResultAndState { - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits(tx_limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let tx = keyless_deploy_call_tx(keyless_deployment_tx, gas_limit_override); - alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap() -} - -fn assert_preflight_failure_without_sandbox_state( - result_and_state: &ResultAndState, - deploy_address: Address, - signer: Address, -) -> KeylessDeployError { - // Preflight failures revert (like other validation errors) since no sandbox ran. - let revert_output = match &result_and_state.result { - ExecutionResult::Revert { output, .. } => output, - other => panic!("preflight failure should revert, got: {other:?}"), - }; - let error = decode_error_result(revert_output) - .expect("preflight revert should contain encoded ParentBudgetExceeded"); - assert!( - matches!(error, KeylessDeployError::ParentBudgetExceeded { .. }), - "preflight should revert with ParentBudgetExceeded, got: {error:?}" - ); - - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "deployed contract must not survive preflight failure"); - - let signer_nonce = result_and_state.state.get(&signer).map(|acc| acc.info.nonce).unwrap_or(0); - assert_eq!( - signer_nonce, 0, - "signer nonce must not be bumped when sandbox is not started, got: {signer_nonce}" - ); - - error -} - -/// Shared assertion: the outer tx succeeds, returns the expected deploy address with -/// empty `errorData`, and the deployed bytecode survives in the finalized state. -/// Used by both exact-remaining-budget boundary tests. -fn assert_exact_fit_success( - result_and_state: &ResultAndState, - deploy_address: Address, -) { - assert!( - result_and_state.result.is_success(), - "outer transaction should succeed when sandbox exactly fits the remaining budget: {:?}", - result_and_state.result, - ); - let decoded = decode_keyless_deploy_return(&result_and_state.result); - assert_eq!( - decoded.deployedAddress, deploy_address, - "successful deploy should keep expected address" - ); - assert!(decoded.errorData.is_empty(), "successful deploy should not return error data"); - - let deployed_account = result_and_state - .state - .get(&deploy_address) - .expect("deployed contract should exist in finalized state"); - assert!( - deployed_account.info.code.as_ref().is_some_and(|code| !code.is_empty()), - "deployed contract code should survive when the sandbox fits exactly in the remaining budget" - ); -} - -// ============================================================================ -// VOLATILE-ACCESS FOOTPRINT MERGE (REX5+) -// ============================================================================ - -/// REX5 sandbox: a constructor that reads TIMESTAMP propagates the bit into -/// the parent `volatile_data_tracker` via the footprint merge. -#[test] -fn test_rex5_sandbox_block_env_access_merged_into_parent_volatile_tracker() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(constructor_reads_timestamp()); - let mut db = funded_signer_db(signer); - let (result, _usage, volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "sandbox should succeed: {result:?}"); - assert!( - volatile.contains(VolatileDataAccess::TIMESTAMP), - "parent tracker should include sandbox TIMESTAMP read; got {:?}", - volatile, - ); -} - -/// REX5 sandbox: COINBASE opcode marks the COINBASE block-env bit only. Pins -/// the separation between COINBASE (block-env bitfield) and `BENEFICIARY_BALANCE` -/// (set only when BALANCE is read against the coinbase address). -#[test] -fn test_rex5_sandbox_coinbase_access_merged_into_parent_volatile_tracker() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(constructor_reads_coinbase()); - let mut db = funded_signer_db(signer); - let (result, _usage, volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "sandbox should succeed: {result:?}"); - assert!( - volatile.contains(VolatileDataAccess::COINBASE), - "parent tracker should include COINBASE bit; got {:?}", - volatile, - ); - assert!( - !volatile.contains(VolatileDataAccess::BENEFICIARY_BALANCE), - "COINBASE alone must NOT set BENEFICIARY_BALANCE; got {:?}", - volatile, - ); -} - -/// REX5 sandbox: BALANCE-on-coinbase reads the beneficiary balance via the -/// beneficiary-aware host wrapper, which calls `mark_beneficiary_balance_accessed`. -/// The `BENEFICIARY_BALANCE` bit must propagate to the parent — separate path from -/// the plain COINBASE block-env bit covered above. -#[test] -fn test_rex5_sandbox_beneficiary_balance_access_merged_into_parent_volatile_tracker() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(constructor_reads_coinbase_balance()); - let mut db = funded_signer_db(signer); - let (result, _usage, volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "sandbox should succeed: {result:?}"); - assert!( - volatile.contains(VolatileDataAccess::BENEFICIARY_BALANCE), - "parent tracker should include BENEFICIARY_BALANCE; got {:?}", - volatile, - ); -} - -/// REX5 sandbox: STATICCALL `IOracle::getSlot(0)` runs the oracle bytecode -/// which SLOADs slot 0; the host's `sload` wrapper sets -/// `VolatileDataAccess::ORACLE` on the sandbox tracker. The bit must -/// propagate to the parent. -/// -/// The oracle contract bytecode is predeployed in the test database because -/// `MegaContext::new` does not run the block-level system-contract -/// deployment that production does. -#[test] -fn test_rex5_sandbox_oracle_access_merged_into_parent_volatile_tracker() { - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(constructor_calls_oracle()); - let mut db = funded_signer_db(signer); - db.set_account_code(ORACLE_CONTRACT_ADDRESS, mega_evm::ORACLE_CONTRACT_CODE_REX5); - let (result, _usage, volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!(result.is_success(), "sandbox should succeed: {result:?}"); - assert!( - volatile.contains(VolatileDataAccess::ORACLE), - "parent tracker should include ORACLE access; got {:?}", - volatile, - ); -} - -/// REX5 sandbox: a constructor that returns empty code triggers the in-sandbox -/// `EmptyCodeDeployed` failure. The volatile bits set during constructor -/// execution must still propagate — the user code ran and accessed the data -/// regardless of the final outcome. -#[test] -fn test_rex5_sandbox_volatile_merge_runs_on_in_sandbox_failure_empty_code() { - let init_code = BytecodeBuilder::default().append(TIMESTAMP).append(POP).append(STOP).build(); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - let (result, _usage, volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - assert!( - result.is_success(), - "outer call returns Success with errorData for in-sandbox failure: {result:?}" - ); - let decoded = decode_keyless_deploy_return(&result); - assert!( - !decoded.errorData.is_empty(), - "errorData should encode the in-sandbox EmptyCodeDeployed failure" - ); - assert!( - volatile.contains(VolatileDataAccess::TIMESTAMP), - "parent tracker should include sandbox TIMESTAMP read even on in-sandbox \ - failure; got {:?}", - volatile, - ); -} - -// ============================================================================ -// OUTER EVM GAS DEBIT (REX5+) -// ============================================================================ - -/// REX5 sandbox: the outer keyless-deploy call's `gas_used` must include the -/// sandbox's `gas_used`; otherwise only the 100K dispatch overhead is counted. -#[test] -fn test_rex5_sandbox_outer_gas_used_includes_sandbox_gas_used_on_success() { - let init_code = minimal_1byte_constructor(42); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - let (result, _usage, _volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - let outer_gas_used = result.gas_used(); - let decoded = decode_keyless_deploy_return(&result); - let sandbox_gas_used = decoded.gasUsed; - - assert!( - outer_gas_used >= constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + sandbox_gas_used, - "outer gas_used ({}) must be >= overhead ({}) + sandbox gas_used ({})", - outer_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - sandbox_gas_used, - ); -} - -/// REX5 sandbox: on in-sandbox failure (`EmptyCodeDeployed` via STOP-only -/// constructor), the outer `gas_used` must still include `sandbox_gas_used`. -#[test] -fn test_rex5_sandbox_outer_gas_used_includes_sandbox_gas_used_on_in_sandbox_failure() { - let init_code = BytecodeBuilder::default().append(STOP).build(); - let (tx_bytes, signer) = create_pre_eip155_deploy_tx(init_code); - let mut db = funded_signer_db(signer); - let (result, _usage, _volatile) = execute_keyless_deploy_with_volatile( - MegaSpecId::REX5, - &mut db, - tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - ); - let outer_gas_used = result.gas_used(); - let decoded = decode_keyless_deploy_return(&result); - let sandbox_gas_used = decoded.gasUsed; - assert!(!decoded.errorData.is_empty(), "in-sandbox failure should be encoded"); - assert!( - outer_gas_used >= constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS + sandbox_gas_used, - "in-sandbox failure: outer gas_used ({}) must include sandbox gas_used \ - ({}) + overhead ({})", - outer_gas_used, - sandbox_gas_used, - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - ); -} - -/// REX5 sandbox: when the merged sandbox usage pushes the parent over a -/// TX-level compute-gas cap, `reject_if_tx_limit_overflow` halts the outer -/// call. Per the halt invariant the tx footprint side effects survive while -/// the state diff does not: -/// - Sandbox state diff NOT merged (deploy address has no code). -/// - Parent volatile bitmap IS merged (footprint survives halt). -/// - Parent multidim usage IS merged (footprint survives halt). -/// -/// Uses `constructor_reads_timestamp` so the sandbox actually accesses -/// volatile data — without that the volatile assertion would be a no-op. -/// The tight `tx_compute_gas_limit` is derived from a successful baseline -/// of the same constructor, then shaved by 1 so the merged usage overshoots -/// by exactly one opcode. -/// -/// Note: the alternative outer-OOG path (where the outer `Gas` cannot absorb the -/// sandbox's eventual cost) is unreachable under REX5. The sandbox enters under a -/// `gas.record_cost(gas_limit_override)` reservation that is capped to the outer's -/// remaining gas, so `sandbox_gas_used ≤ reservation` is structural — the post-frame -/// step is a pure `erase_cost` refund of the unused tail, never a `record_cost`. -#[test] -fn test_rex5_sandbox_volatile_bitmap_survives_residual_overflow_halt() { - let init_code = constructor_reads_timestamp(); - // Get baseline usage for the same constructor on a successful deploy. - let (tx_bytes, signer, deploy_address, baseline_usage) = rex5_baseline(init_code); - assert!(baseline_usage.compute_gas > 0, "baseline should consume compute gas"); - - // Tighten the parent's compute_gas budget so the sandbox's merged usage - // overshoots by a single opcode, forcing the residual-overflow safety net - // to halt the outer call after the sandbox has already merged its - // multidim usage and volatile bitmap. - let tx_limits = EvmTxRuntimeLimits::no_limits() - .with_tx_compute_gas_limit(baseline_usage.compute_gas.saturating_sub(1)); - - // Run the keyless deploy with the tight limits AND extract the parent's - // volatile tracker bitmap after the call returns. (`execute_keyless_deploy_with_limits` - // drops the EVM internally, so we inline the EVM construction here to keep - // the tracker reachable.) - let mut db = funded_signer_db(signer); - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits(tx_limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let outer_tx = keyless_deploy_call_tx(tx_bytes, LARGE_GAS_LIMIT_OVERRIDE); - let result_and_state = alloy_evm::Evm::transact_raw(&mut evm, outer_tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - let volatile = evm.ctx_ref().volatile_data_tracker.borrow().get_volatile_data_accessed(); - let result = result_and_state.result; - - // Outer halts at `reject_if_tx_limit_overflow` because the parent's - // compute-gas cap was overshot by the merged sandbox usage. - assert!( - result.is_halt(), - "outer should halt on residual compute-gas overflow, got: {result:?}" - ); - - // The halt reason must be the generic `ComputeGasLimitExceeded`, NOT the - // volatile-specific `VolatileDataAccessOutOfGas`. The footprint merge - // propagates the bitmap into the parent's volatile tracker but does NOT - // call `set_compute_gas_limit` on the parent's `AdditionalLimit`; the - // halt-reason classifier at `MegaHandler::execution_result` therefore - // takes the generic `check_limit().maybe_halt_reason()` branch rather - // than the `detained_compute_gas_halt_reason` branch. See the doc comment - // on `VolatileDataAccessTracker::merge_accesses_from_bitmap` for the - // intentional footprint-only scoping. - match &result { - ExecutionResult::Halt { reason, .. } => { - assert!( - matches!(reason, MegaHaltReason::ComputeGasLimitExceeded { .. }), - "halt reason should be generic ComputeGasLimitExceeded; got {reason:?}" - ); - assert!( - !matches!(reason, MegaHaltReason::VolatileDataAccessOutOfGas { .. }), - "halt reason MUST NOT be remapped to volatile-specific variant for \ - a sandbox-only volatile access — detention state is not merged; \ - got {reason:?}" - ); - } - other => panic!("expected Halt, got: {other:?}"), - } - - // (1) State diff NOT merged — deployed account must not survive. - let deployed_account = result_and_state.state.get(&deploy_address); - let has_code = deployed_account - .map(|acc| acc.info.code.as_ref().map(|c| !c.is_empty()).unwrap_or(false)) - .unwrap_or(false); - assert!(!has_code, "sandbox state must NOT be merged on residual overflow halt"); - - // (2) Parent volatile bitmap IS merged — footprint survives the halt. - assert!( - volatile.contains(VolatileDataAccess::TIMESTAMP), - "parent volatile tracker MUST include sandbox TIMESTAMP read on \ - residual overflow halt; got {:?}", - volatile, - ); - - // (3) Parent's multidim usage IS merged. The dispatch path records the - // fixed overhead into compute_gas BEFORE entering the sandbox, so any - // proof that the sandbox's contribution survived must show compute_gas - // strictly greater than that overhead alone. - assert!( - usage.compute_gas > constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - "parent additional_limit.compute_gas must include sandbox contribution \ - on top of the {} dispatch overhead; got {} (multidim merge should \ - survive halt)", - constants::rex2::KEYLESS_DEPLOY_OVERHEAD_GAS, - usage.compute_gas, - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs b/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs deleted file mode 100644 index e45281c84..000000000 --- a/crates/mega-evm/tests/_pending/rex5/selfdestruct_beneficiary.rs +++ /dev/null @@ -1,442 +0,0 @@ -//! Tests for SELFDESTRUCT beneficiary new-account metering. -//! -//! REX5 adds resource limit tracking for SELFDESTRUCT beneficiary account creation. -//! When a contract selfdestructs and sends its balance to a non-existent address, -//! the resulting new account creation should be metered for state growth, data size, -//! and KV updates. - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaAccessControl, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, VolatileDataAccessType, ACCESS_CONTROL_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ResultAndState, tx::TxEnvBuilder, TxEnv}, - handler::EvmTr, -}; - -/// The 4-byte selector for `disableVolatileDataAccess()`. -const DISABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -/// The 4-byte selector for `VolatileDataAccessDisabled(uint8 accessType)` error. -const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000700000"); -const CONTRACT: Address = address!("0000000000000000000000000000000000700001"); -const PARENT: Address = address!("0000000000000000000000000000000000700002"); -const EMPTY_BENEFICIARY: Address = address!("0000000000000000000000000000000000700099"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> (ResultAndState, LimitUsage) { - let mut context = MegaContext::new(db, spec); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (r, usage) -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// SELFDESTRUCT to an empty beneficiary should record state growth in REX5. -/// -/// When a pre-existing contract with balance selfdestructs to a non-existent address, -/// the beneficiary account is created. REX5 meters this as state growth, data size, -/// and KV updates. -#[test] -fn test_rex5_selfdestruct_to_empty_beneficiary_records_state_growth() { - let code = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - - // Contract must have balance for the value transfer to create the beneficiary account. - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // REX5 should record state growth for the new beneficiary account. - assert!( - usage.state_growth > 0, - "state growth should include new beneficiary: {}", - usage.state_growth - ); - assert!(usage.data_size > 0, "data size should include account write: {}", usage.data_size); - assert!( - usage.kv_updates > 0, - "KV updates should include account creation: {}", - usage.kv_updates - ); -} - -/// SELFDESTRUCT with zero balance should NOT charge new-account fees. -/// -/// When a contract has zero balance and selfdestructs to an empty address, -/// no value transfer occurs, so no new account is created and no extra metering -/// should apply. -#[test] -fn test_rex5_selfdestruct_zero_balance_no_extra_charges() { - let code = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - - // Contract has ZERO balance — no value transfer to beneficiary. - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code); - // Do NOT set CONTRACT balance — it will be 0. - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // With zero balance, SELFDESTRUCT does not transfer value, so no new account is created. - // The fix checks `has_value` — should not trigger for zero-balance selfdestructs. - // state_growth should not include beneficiary (no value transfer means no account creation). - assert_eq!( - usage.state_growth, 0, - "zero-balance SELFDESTRUCT should not create new account, state_growth: {}", - usage.state_growth - ); -} - -/// SELFDESTRUCT to self (caller == beneficiary) should NOT charge new-account fees. -/// -/// The contract targets itself as the beneficiary. Since the contract has code, it is -/// non-empty (`state_clear_aware_is_empty()` returns false), so no new account is created -/// and no new-account storage-gas premium, data size, KV update, or state growth should -/// be recorded for the beneficiary. -#[test] -fn test_rex5_selfdestruct_to_self_no_new_account_charges() { - // CONTRACT selfdestructs to itself: PUSH20 SELFDESTRUCT - let code = BytecodeBuilder::default().push_address(CONTRACT).append(SELFDESTRUCT).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // The beneficiary is the contract itself, which has code and is non-empty. - // No new-account charges should apply. - assert_eq!( - usage.state_growth, 0, - "SELFDESTRUCT to self should not record new-account state growth: {}", - usage.state_growth - ); -} - -// ============================================================================ -// HOISTED-GUARD HELPERS -// ============================================================================ - -/// Decodes `VolatileDataAccessDisabled(uint8 accessType)` from revert data. -fn decode_volatile_data_access_disabled( - data: &[u8], -) -> IMegaAccessControl::VolatileDataAccessDisabled { - ::abi_decode(data) - .expect("valid VolatileDataAccessDisabled revert data") -} - -/// Builds bytecode that calls `disableVolatileDataAccess()` on the access-control contract. -fn call_disable_volatile_data_access(builder: BytecodeBuilder) -> BytecodeBuilder { - let builder = builder.mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR); - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) -} - -/// Builds bytecode that CALLs `target` with `gas`, then copies the child's -/// return data into memory and returns it as the parent's frame output. -fn append_call_and_return_child_data( - builder: BytecodeBuilder, - target: Address, - gas: u64, -) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) - .append(POP) // discard CALL success flag - .append(RETURNDATASIZE) // size - .push_number(0_u64) // dataOffset - .push_number(0_u64) // destOffset - .append(RETURNDATACOPY) - .append(RETURNDATASIZE) // size - .push_number(0_u64) // offset - .append(RETURN) -} - -/// Rex5: SELFDESTRUCT to the block beneficiary inside a disabled-volatile frame -/// must short-circuit ahead of the new-account storage-gas charge and the -/// `on_selfdestruct_new_account` resource-limit record. -/// -/// Setup: parent disables volatile access, CALLs child; child's only opcodes are -/// `PUSH20 ; SELFDESTRUCT`. CONTRACT (child) has balance, so the -/// `is_empty && has_value` branch in `storage_gas_ext::selfdestruct` would fire -/// `on_selfdestruct_new_account` (`state_growth` += 1, `kv_updates` += 1) if the -/// guard didn't short-circuit first. Asserts: -/// 1. Child reverts with `VolatileDataAccessDisabled(Beneficiary)`. -/// 2. `state_growth` stays at 0, proving the new-account hook never ran — the guard fired *before* -/// any of `inspect_account`, the storage-gas charge, or `on_selfdestruct_new_account`. -#[test] -fn test_rex5_selfdestruct_to_beneficiary_with_volatile_disabled_short_circuits() { - // Block beneficiary defaults to `Address::ZERO` in `BlockEnv::default()`, - // matching the `MegaContext::new(db, spec)` setup used by `transact()`. - let beneficiary = Address::ZERO; - - let child_code = - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call_and_return_child_data(parent_code, CONTRACT, 50_000_000).build(); - - // CONTRACT has balance so `has_value` is true under the guard's branch. - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(PARENT, parent_code) - .account_code(CONTRACT, child_code) - .account_balance(CONTRACT, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!( - result.result.is_success(), - "parent should succeed and return child revert data: {result:?}" - ); - - let output = result.result.output().expect("parent returns child's revert data"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "child should revert with VolatileDataAccessDisabled selector", - ); - let decoded = decode_volatile_data_access_disabled(output); - assert_eq!( - decoded.accessType, - VolatileDataAccessType::Beneficiary, - "SELFDESTRUCT to beneficiary with disabled volatile access must revert with Beneficiary", - ); - - // The hoisted guard short-circuits before any new-account resource record. - // If the storage-gas charge / `on_selfdestruct_new_account` had run, - // state_growth would be ≥ 1. - assert_eq!( - usage.state_growth, 0, - "guard short-circuit must skip on_selfdestruct_new_account; state_growth: {}", - usage.state_growth, - ); -} - -/// Rex5: SELFDESTRUCT to the block beneficiary when volatile access is NOT disabled. -/// The outer `volatile_data_ext::selfdestruct_with_beneficiary_guard` guard's `target == -/// beneficiary` arm short-circuits the AND on the second operand (`volatile_access_disabled()` -/// returns false), so the guard does NOT fire and the call falls through to the -/// storage layer. With CONTRACT holding balance and the beneficiary empty, the -/// storage layer charges new-account gas and records `on_selfdestruct_new_account`. -/// -/// Covers the `target == beneficiary && !volatile_disabled` branch of the macro- -/// generated outer wrapper, which is the partial branch the volatile-disabled -/// test alone cannot exercise. -#[test] -fn test_rex5_selfdestruct_to_beneficiary_without_volatile_disabled() { - // Block beneficiary defaults to `Address::ZERO` in `BlockEnv::default()`, - // matching the `MegaContext::new(db, spec)` setup used by `transact()`. - let beneficiary = Address::ZERO; - - let code = BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); - - // CONTRACT has balance so the value transfer to the empty beneficiary - // triggers the new-account path inside `storage_gas_ext::selfdestruct`. - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(1_000_000u64)); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(1_000_000).build_fill(); - - let (result, usage) = transact(MegaSpecId::REX5, &mut db, tx); - assert!(result.result.is_success(), "should succeed: {result:?}"); - - // Guard did not fire — control reached the storage layer, which charged - // new-account gas and recorded `on_selfdestruct_new_account`. - assert!( - usage.state_growth > 0, - "fall-through to storage layer must record new-account growth: {}", - usage.state_growth, - ); -} - -// ============================================================================ -// SELFDESTRUCT attempted inside a STATICCALL frame -// ============================================================================ - -/// A parent that STATICCALLs `target` once (forwarding `gas_each`), discards the -/// result, and STOPs successfully. -fn staticcall_once_parent(target: Address, gas_each: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(target) - .push_number(gas_each) // forwarded gas (top of stack) - .append(STATICCALL) - .append(POP) - .append(STOP) - .build() -} - -/// SELFDESTRUCT attempted inside a STATICCALL frame must halt on revm's -/// static-context check and leak NO resource usage for the (reverted) -/// beneficiary creation. The `is_static` early-exit guard in -/// `storage_gas_ext::selfdestruct` skips the host work; the frame revert would -/// discard it regardless, so the tracked usage is identical to a STATICCALL that -/// merely STOPs — and specifically records zero state growth even though the -/// child is funded and the beneficiary is empty (the value branch that would -/// charge new-account creation never commits). -#[test] -fn test_rex5_selfdestruct_in_staticcall_leaks_no_usage() { - let gas_each = 200_000u64; - let parent_code = staticcall_once_parent(CONTRACT, gas_each); - let sd_child = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - let stop_child = BytecodeBuilder::default().append(STOP).build(); - - let run = |spec: MegaSpecId, child: Bytes| { - let mut db = MemoryDatabase::default() - .account_code(PARENT, parent_code.clone()) - .account_code(CONTRACT, child) - // fund the child so the SELFDESTRUCT has_value / SALT branch would trigger - .account_balance(CONTRACT, U256::from(1_000u64)) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(10_000_000).build_fill(); - transact(spec, &mut db, tx) - }; - - let (sd_res, sd_usage) = run(MegaSpecId::REX5, sd_child.clone()); - let (stop_res, stop_usage) = run(MegaSpecId::REX5, stop_child); - - // The parent swallows the inner STATICCALL failure and completes. - assert!(sd_res.result.is_success(), "parent tx should succeed: {:?}", sd_res.result); - assert!(stop_res.result.is_success(), "control tx should succeed: {:?}", stop_res.result); - - // No beneficiary creation leaks into committed usage: identical to the STOP - // control on every lane, and zero state growth. - assert_eq!( - sd_usage.state_growth, stop_usage.state_growth, - "static SELFDESTRUCT leaked state growth vs STOP control", - ); - assert_eq!( - sd_usage.kv_updates, stop_usage.kv_updates, - "static SELFDESTRUCT leaked KV updates vs STOP control", - ); - assert_eq!( - sd_usage.data_size, stop_usage.data_size, - "static SELFDESTRUCT leaked data size vs STOP control", - ); - assert_eq!(sd_usage.state_growth, 0, "no beneficiary account should be created"); - - // Pre-REX5 control: the same scenario under REX4 also completes with no - // leaked growth, confirming the REX5 guard did not diverge the two specs. - let (sd_res_rex4, sd_usage_rex4) = run(MegaSpecId::REX4, sd_child); - assert!(sd_res_rex4.result.is_success(), "rex4 parent tx should succeed"); - assert_eq!(sd_usage_rex4.state_growth, 0, "rex4 static SELFDESTRUCT must not grow state"); -} - -/// SELFDESTRUCT whose beneficiary creation exceeds the state-growth budget must fail at -/// the SELFDESTRUCT itself via the trailing all-dimension check: the usage is recorded -/// before the inner instruction runs, but only latched once the inner instruction has -/// succeeded. -#[test] -fn test_rex5_selfdestruct_beneficiary_creation_fails_on_state_growth_limit() { - let sd_code = - BytecodeBuilder::default().push_address(EMPTY_BENEFICIARY).append(SELFDESTRUCT).build(); - - let run = |growth_limit: u64| { - let mut db = MemoryDatabase::default() - .account_code(CONTRACT, sd_code.clone()) - .account_balance(CONTRACT, U256::from(1_000u64)) - .account_balance(CALLER, U256::from(10).pow(U256::from(18))); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(growth_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CONTRACT) - .gas_limit(10_000_000) - .build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (r, usage) - }; - - // Control: a budget of 1 admits the single new beneficiary account. - let (ok_res, ok_usage) = run(1); - assert!(ok_res.result.is_success(), "control should succeed: {:?}", ok_res.result); - assert_eq!(ok_usage.state_growth, 1, "beneficiary creation should count as growth"); - - // Budget 0: the beneficiary creation trips the limit at the SELFDESTRUCT. - let (res, _) = run(0); - assert!( - !res.result.is_success(), - "zero state-growth budget must fail the SELFDESTRUCT, got {:?}", - res.result, - ); -} diff --git a/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs b/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs deleted file mode 100644 index 0fe4872f0..000000000 --- a/crates/mega-evm/tests/_pending/rex5/stipend_accounting.rs +++ /dev/null @@ -1,565 +0,0 @@ -//! REX5 stipend-accounting regression suite. -//! -//! Covers two corrections sharing the `STORAGE_CALL_STIPEND` lifecycle surface. -//! REX5 subtracts only the parent-contributed portion of `call_inputs.gas_limit` from -//! parent compute gas (pre-REX5 under-counts by `CALL_STIPEND = 2,300` per value-transfer -//! CALL/CALLCODE; preserved byte-for-byte for replay). REX5 also tracks -//! `STORAGE_CALL_STIPEND` as an internal allowance drained at five `storage_gas_ext` -//! sites (CALL, CREATE, SSTORE, LOG, SELFDESTRUCT) instead of inflating `gas.limit()`; -//! pre-REX5 retains the legacy inflation byte-for-byte. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaAccessControl, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, MegaTransactionError, ACCESS_CONTROL_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - TxEnv, - }, - handler::EvmTr, - Database, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000200000"); -/// A contract that performs CALL with value to RECEIVER. -const SENDER_CONTRACT: Address = address!("0000000000000000000000000000000000200001"); -/// A contract that emits events / SSTOREs / SELFDESTRUCTs when receiving ETH. -const RECEIVER: Address = address!("0000000000000000000000000000000000200002"); -/// An EOA-style fresh empty address used as a CALL target inside `receive()`. -const FRESH_TARGET: Address = address!("0000000000000000000000000000000000300001"); -/// The 4-byte selector for `disableVolatileDataAccess()` on `MegaAccessControl`. -/// Calling this synthetic-system-contract method short-circuits `frame_init` and -/// exercises the `push_empty_frame` path in `StorageCallStipendTracker`. -const DISABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -// ============================================================================ -// HELPERS -// ============================================================================ - -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = - MegaContext::new(db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// Returns `(execution_result, tx_compute_gas_used)` from a successful tx. -fn transact_with_compute( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> (ExecutionResult, u64) { - let mut context = - MegaContext::new(db, spec).with_tx_runtime_limits(EvmTxRuntimeLimits::from_spec(spec)); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let compute = evm.ctx_ref().additional_limit.borrow().get_usage().compute_gas; - (result.result, compute) -} - -/// Run a tx with a custom `EvmTxRuntimeLimits` override. Used to force TX-level -/// compute-gas detention inside the child for rescue-path tests. -fn transact_with_limits( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, - limits: EvmTxRuntimeLimits, -) -> Result, EVMError> { - let mut context = MegaContext::new(db, spec).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -fn setup_db(contracts: &[(Address, Bytes)]) -> MemoryDatabase { - let mut db = - MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_000u128)); - for (addr, bytecode) in contracts { - db = db.account_code(*addr, bytecode.clone()); - } - db.set_account_balance(SENDER_CONTRACT, U256::from(1_000_000_000u128)); - db -} - -fn default_tx() -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(SENDER_CONTRACT).gas_limit(100_000_000).build_fill() -} - -fn inner_call_success_flag(output: &[u8]) -> U256 { - U256::from_be_slice(&output[..32]) -} - -// ============================================================================ -// CONTRACT BUILDERS -// ============================================================================ - -/// `CALL(gas=0, RECEIVER, value=1, ...)` then RETURN the 32-byte success flag. -/// Forwarded gas is 0; the child relies entirely on the stipend. -fn build_zero_gas_transfer_contract(to: Address) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(to) - .push_number(0_u64) // gas = 0 - .append(CALL) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// `CALL(gas=forwarded_gas, RECEIVER, value=1, ...)` then RETURN the success flag. -fn build_value_transfer_with_gas(to: Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(to) - .push_number(forwarded_gas) - .append(CALL) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// `CALLCODE(gas=0, RECEIVER, value=1, ...)` — mirrors the zero-gas CALL variant. -fn build_zero_gas_callcode_contract(to: Address) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(1_u64) - .push_address(to) - .push_number(0_u64) - .append(CALLCODE) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// `DELEGATECALL(gas=forwarded_gas, to, ...)` — no value transfer, no stipend. -fn build_delegatecall_contract(to: Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(to) - .push_number(forwarded_gas) - .append(DELEGATECALL) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// `STATICCALL(gas=forwarded_gas, to, ...)` — no value transfer, no stipend. -fn build_staticcall_contract(to: Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(to) - .push_number(forwarded_gas) - .append(STATICCALL) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// Receiver that emits LOG1 with 0 bytes and STOPs. Standard EVM cost ~750. -fn build_log1_receiver() -> Bytes { - BytecodeBuilder::default() - .push_number(0xdeadbeef_u64) - .push_number(0_u64) - .push_number(0_u64) - .append(LOG1) - .append(STOP) - .build() -} - -/// Receiver that SSTOREs slot 0 = 1 (first-time-write zero-to-nonzero) and STOPs. -/// Standard EIP-2200 cost ≈ 22,100. -fn build_sstore_receiver() -> Bytes { - BytecodeBuilder::default() - .push_number(1_u64) // value - .push_number(0_u64) // slot - .append(SSTORE) - .append(STOP) - .build() -} - -/// Receiver that CALLs a fresh empty address with value=1. -/// Triggers the CALL/CALLCODE new-account surcharge inside the stipend-receiving frame. -fn build_nested_value_call_receiver(target: Address, forwarded_gas: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(target) - .push_number(forwarded_gas) - .append(CALL) - .append(STOP) - .build() -} - -/// Receiver that SELFDESTRUCTs to a fresh empty beneficiary. Standard EVM cost -/// for SELFDESTRUCT to a cold, empty, value-receiving account ≈ 32,500. -fn build_selfdestruct_receiver(beneficiary: Address) -> Bytes { - BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() -} - -/// Receiver that executes `CREATE2(value=0, offset=0, size=2, salt=0)` over -/// in-memory initcode `PUSH1 0x00 STOP` (just two bytes: 0x60 0x00 -- actually -/// the bytecode here writes `STOP STOP` into memory, immediately stops on -/// invocation). Returns the 32-byte `created_address` from CREATE2. -fn build_create2_receiver() -> Bytes { - BytecodeBuilder::default() - // Write a single STOP byte at memory[0]. STOP = 0x00, push as a 32-byte word. - .push_number(0_u64) - .push_number(0_u64) - .append(MSTORE) - // CREATE2(value, offset, size, salt) - .push_number(0_u64) // salt - .push_number(1_u64) // size = 1 byte initcode (STOP) - .push_number(31_u64) // offset (so the STOP byte from MSTORE is at memory[31]) - .push_number(0_u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// Appends ~`target_gas` worth of compute burn via repeated PUSH0/POP pairs. -fn append_burn_gas(mut builder: BytecodeBuilder, target_gas: u64) -> BytecodeBuilder { - let iterations = target_gas / 5; - for _ in 0..iterations { - builder = builder.push_number(0_u8).append(POP); - } - builder -} - -/// Receiver that accesses TIMESTAMP (triggering volatile-data detention), then burns -/// ~`burn_target` compute gas. Used by the TX-level rescue test to force a TX-level -/// `VolatileDataAccessOutOfGas` halt inside a stipend-receiving child. -fn build_timestamp_detention_receiver(burn_target: u64) -> Bytes { - let builder = BytecodeBuilder::default().append(TIMESTAMP).append(POP); - append_burn_gas(builder, burn_target).append(STOP).build() -} - -/// Receiver that does a first-time-write SSTORE (drains stipend allowance + charges -/// the EVM residual + standard SSTORE EVM gas) and then explicitly REVERTs. Used by -/// the consume-then-revert test to pin that the drained allowance does not leak -/// gas back to the caller across a revert. -fn build_sstore_then_revert_receiver() -> Bytes { - BytecodeBuilder::default() - .push_number(1_u64) // value - .push_number(0_u64) // slot - .append(SSTORE) - // REVERT(offset=0, size=0) - .push_number(0_u64) - .push_number(0_u64) - .append(REVERT) - .build() -} - -/// `CALL(gas=0, ACCESS_CONTROL_ADDRESS, value=1, selector=disable...)`. Sends 1 wei -/// to the system contract. The interceptor short-circuits `frame_init`, exercising -/// the `push_empty_frame` path in `StorageCallStipendTracker`. -fn build_intercepted_value_call() -> Bytes { - BytecodeBuilder::default() - .mstore(0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(1_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(0_u64) // gas = 0 - .append(CALL) - .push_number(0_u64) - .append(MSTORE) - .push_number(32_u64) - .push_number(0_u64) - .append(RETURN) - .build() -} - -/// Receiver that does `KECCAK256(offset=0, len=32_768)` — 1,024 words of hash -/// cost (6 × 1024 = 6,144) plus memory expansion for 32 KiB -/// (`3 × 1024 + 1024² / 512 = 3,072 + 2,048 = 5,120`) plus base 30 — total ≈ -/// 11,294 gas. Comfortably inside (2,300, 25,300) — proves REX5 prevents the -/// leak by OOG'ing inside KECCAK256 while REX4 absorbs the full cost into -/// parent compute via the legacy inflation path. -fn build_keccak256_leaky_receiver() -> Bytes { - BytecodeBuilder::default() - .push_number(32_768_u64) - .push_number(0_u64) - .append(KECCAK256) - .append(POP) - .append(STOP) - .build() -} - -// ============================================================================ -// Parent compute-gas attribution: +CALL_STIPEND delta on value-transfer CALL -// ============================================================================ - -// ============================================================================ -// Storage allowance coverage per charging site -// ============================================================================ - -/// LOG1 in `receive()` at `gas = 0` succeeds on REX5: the standard LOG1 EVM cost -/// (~750) fits inside `CALL_STIPEND = 2,300`, and the Mega LOG storage surcharge -/// drains from the allowance. -#[test] -fn test_log1_value_transfer_succeeds_at_zero_gas_rex5() { - let sender_code = build_zero_gas_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - match &result.result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::from(1), - "REX5: inner LOG1 CALL with gas=0 must succeed via separated allowance" - ); - } - other => panic!("expected Success, got {other:?}"), - } -} - -// ============================================================================ -// Compute-leak isolation: stipend cannot fund compute-only opcodes -// ============================================================================ - -/// REX5 must not let `STORAGE_CALL_STIPEND` be spent on a compute-only opcode -/// inside the (2,300, 25,300) envelope. Fixture: child receives 1 wei with gas=0 -/// then runs `KECCAK256(offset=0, len=32_768)` (~11,294 EVM gas — above -/// `CALL_STIPEND` and below `CALL_STIPEND + STORAGE_CALL_STIPEND`). REX4's legacy -/// inflation lets KECCAK256 run and records the full cost into parent compute -/// before the per-frame cap revert fires; REX5's un-inflated child OOGs inside -/// revm's standard `gas!` before any compute attribution lands on the parent. -/// REX4 parent compute-gas therefore exceeds REX5's by roughly the KECCAK256 -/// opcode cost (minus the +2,300 parent-attribution correction). -#[test] -fn test_storage_stipend_cannot_cover_compute_only_opcode_rex5() { - let sender_code = build_zero_gas_transfer_contract(RECEIVER); - let receiver_code = build_keccak256_leaky_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (_rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (_rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - // REX4 path absorbs the KECCAK256 cost into parent compute via the legacy leak. - // REX5 path stops the KECCAK256 before any compute is recorded to parent. - // Even after REX5's +2,300 CALL_STIPEND parent-attribution correction (§1), - // REX4 must still be substantially larger for this fixture. - assert!( - rex4_compute > rex5_compute + 5_000, - "REX4 must record substantially more parent compute-gas than REX5 because \ - the legacy inflation lets KECCAK256 leak through. REX4={rex4_compute}, REX5={rex5_compute}" - ); -} - -/// REX5 does not refund unused allowance to the caller: the allowance never -/// enters `gas.limit()`, so the LOG1-in-receive fixture's REX5 vs REX4 parent -/// compute-gas delta equals exactly `+CALL_STIPEND` (the §1 correction). A -/// refund leak would shift this delta downward. -#[test] -fn test_storage_stipend_unused_portion_does_not_inflate_caller_gas_rex5() { - let sender_code = build_zero_gas_transfer_contract(RECEIVER); - let receiver_code = build_log1_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut rex4_db = setup_db(&contracts); - let (_rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - let mut rex5_db = setup_db(&contracts); - let (_rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut rex5_db, default_tx()); - - // REX5 = REX4 + 2,300 (§1) — and the +2,300 also implicitly proves the unused - // stipend was not refunded back (refunded gas would shrink parent's recorded - // CALL cost via revm's gas accounting). - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "Parent compute-gas delta must be exactly +CALL_STIPEND; any unused-stipend \ - refund leaking back would shift this delta" - ); -} - -// ============================================================================ -// Negative controls -// ============================================================================ - -// ============================================================================ -// Synthetic interceptor frame stack alignment -// ============================================================================ - -/// Value-transferring CALL to a system contract is short-circuited by -/// `frame_init` interception, which uses `push_empty_frame` to keep tracker -/// stacks aligned. The stipend tracker must push a zero-allowance entry on the -/// interception path so subsequent pops match — passes if no panic fires in the -/// per-frame stack-non-empty assertion on either spec. -#[test] -fn test_intercepted_value_call_stack_alignment_rex5() { - let sender_code = build_intercepted_value_call(); - let mut db = setup_db(&[(SENDER_CONTRACT, sender_code)]); - - let result = transact(MegaSpecId::REX5, &mut db, default_tx()).unwrap(); - // The interceptor may succeed or revert depending on the system contract - // state; what matters is that no panic occurred and the tx completed. - assert!( - matches!(result.result, ExecutionResult::Success { .. } | ExecutionResult::Revert { .. }), - "REX5: intercepted value CALL must not panic stack alignment" - ); -} - -/// The stipend is granted only to internal (depth > 0) value-transferring -/// CALL/CALLCODE. A top-level value-transfer transaction must NOT receive -/// the stipend on either spec; LOG1 in the receiver should fail under both -/// REX4 and REX5 when the tx `gas_limit` is too tight (no stipend to cover the -/// 4,500-gas Mega LOG cost). -#[test] -fn test_top_level_value_transfer_does_not_get_stipend_rex5() { - let receiver_code = build_log1_receiver(); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(RECEIVER) - .gas_limit(60_000) - .value(U256::from(1_u64)) - .build_fill(); - - let mut rex5_db = setup_db(&[(RECEIVER, receiver_code)]); - let rex5_result = transact(MegaSpecId::REX5, &mut rex5_db, tx).unwrap(); - assert!( - matches!(rex5_result.result, ExecutionResult::Halt { .. }), - "REX5 top-level value transfer must NOT receive STORAGE_CALL_STIPEND; \ - the tight tx gas_limit must cause a Halt" - ); -} - -// ============================================================================ -// TX-level rescue + revert path inside a stipend-receiving child -// ============================================================================ - -/// Stipend-receiving child drains its allowance via SSTORE then REVERTs. The -/// drained allowance is consumed — it does not refund across the revert. Outer -/// tx succeeds, inner CALL flag is 0, SSTORE state is rolled back, and the -/// parent compute-gas delta `REX5 = REX4 + 2,300` is unchanged by the revert. -#[test] -fn test_stipend_drained_then_revert_no_refund_rex5() { - let sender_code = build_value_transfer_with_gas(RECEIVER, 50_000); - let receiver_code = build_sstore_then_revert_receiver(); - let contracts = vec![(SENDER_CONTRACT, sender_code), (RECEIVER, receiver_code)]; - - let mut db = setup_db(&contracts); - let (rex5_result, rex5_compute) = - transact_with_compute(MegaSpecId::REX5, &mut db, default_tx()); - - match &rex5_result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX5: inner CALL must return success=0 because child REVERTed" - ); - } - other => panic!("expected outer Success, got {other:?}"), - } - - // The receiver's slot 0 must remain zero — SSTORE was rolled back by the revert. - let slot_zero = db.storage(RECEIVER, U256::from(0)).unwrap(); - assert_eq!(slot_zero, U256::ZERO, "REX5: revert must roll back the SSTORE side-effect"); - - // Parity guard: REX4 fixture must also produce inner-call success=0 and zero slot. - let mut rex4_db = setup_db(&contracts); - let (rex4_result, rex4_compute) = - transact_with_compute(MegaSpecId::REX4, &mut rex4_db, default_tx()); - match &rex4_result { - ExecutionResult::Success { output, .. } => { - assert_eq!( - inner_call_success_flag(output.data()), - U256::ZERO, - "REX4 parity guard: inner CALL must return success=0" - ); - } - other => panic!("expected REX4 outer Success, got {other:?}"), - } - let rex4_slot_zero = rex4_db.storage(RECEIVER, U256::from(0)).unwrap(); - assert_eq!(rex4_slot_zero, U256::ZERO, "REX4 parity guard"); - - // REX5 records exactly +CALL_STIPEND (2,300) more parent compute-gas than REX4 - // (the §1 fix). The child's revert path doesn't perturb this delta, proving the - // drained allowance and the revert interact correctly with the §1 attribution. - assert_eq!( - rex5_compute, - rex4_compute + 2_300, - "REX5 parent compute-gas must be exactly REX4 + CALL_STIPEND even when the \ - stipend-receiving child REVERTs after draining allowance. Any deviation \ - indicates a refund leak through the revert path" - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs b/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs deleted file mode 100644 index 4b448da87..000000000 --- a/crates/mega-evm/tests/_pending/rex6/beneficiary_detention.rs +++ /dev/null @@ -1,799 +0,0 @@ -//! REX6 beneficiary detention / volatile-access coverage tests. -//! -//! Covers three scenarios whose root cause is "REX4+ beneficiary detention + -//! `disableVolatileDataAccess` only saw part of the surface": -//! -//! - **Source-side SELFDESTRUCT** — `volatile_data_ext::selfdestruct_with_beneficiary_guard` peeks -//! the stack target on every spec, and REX6 additionally compares the source (executing contract -//! whose balance is read and zeroed) against the beneficiary. Pre-REX6 source-side behavior is -//! frozen. -//! -//! - **EIP-7702-delegated CALL** — REX5 `wrap_call_volatile_check!` compared the raw stack operand; -//! a CALL to delegator `A` whose EIP-7702 code points at `B == beneficiary` slipped past both the -//! `disableVolatileDataAccess` revert and the detention mark. That wrapper now resolves the -//! EIP-7702 delegate one hop before the comparison under REX6 (raw operand <= REX5); -//! `MegaContext::load_account_delegated` also marks the resolved delegate. -//! -//! - **Existing-target SELFDESTRUCT** — REX5 `storage_gas_ext::selfdestruct` only charged -//! DataSize/KV/StateGrowth for SELFDESTRUCT to a *new* beneficiary. When the target already -//! exists, the balance update went through `host.selfdestruct` without flowing through any -//! frame-init or `target_updated` path, so DataSize/KV stayed at zero. Under REX6 the REX6-gated -//! arm inside `storage_gas_ext::selfdestruct` records `DataSize` +40 / KV +1 (no `StateGrowth` — -//! the target already exists) for the existing-target balance credit. -//! -//! Each scenario is paired with a REX5 baseline that freeze-guards the pre-REX6 behavior. -//! Pre-REX6 dispatch tables are unchanged. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use alloy_sol_types::{SolCall, SolError}; -use mega_evm::{ - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, - EvmTxRuntimeLimits, IMegaAccessControl, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, MegaTransactionError, VolatileDataAccessType, - ACCESS_CONTROL_ADDRESS, -}; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ExecutionResult, ResultAndState}, - tx::TxEnvBuilder, - BlockEnv, TxEnv, - }, - database::AccountState, - handler::EvmTr, - state::Bytecode, -}; - -/// 4-byte selector for `disableVolatileDataAccess()`. -const DISABLE_VOLATILE_DATA_ACCESS_SELECTOR: [u8; 4] = - IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -/// 4-byte selector for the `VolatileDataAccessDisabled(uint8)` error. -const VOLATILE_DATA_ACCESS_DISABLED_SELECTOR: [u8; 4] = - IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -/// Externally-owned tx sender. Never the beneficiary. -const CALLER: Address = address!("0000000000000000000000000000000000600000"); -/// Non-beneficiary intermediary used to keep the top-level tx target distinct -/// from the beneficiary (avoids `on_new_tx`'s eager beneficiary-recipient mark -/// muddying the detention assertions). -const MIDDLE: Address = address!("0000000000000000000000000000000000600001"); -/// Block beneficiary used throughout. Set via the `BlockEnv` in -/// `transact_with_beneficiary`. -const BENEFICIARY: Address = address!("0000000000000000000000000000000000600099"); -/// SELFDESTRUCT destination for the source-side cases — empty and *not* the beneficiary. -const EMPTY_NON_BENEFICIARY: Address = address!("0000000000000000000000000000000000600002"); -/// SELFDESTRUCT destination for the existing-target case — pre-existing and *not* -/// the beneficiary. -const EXISTING_NON_BENEFICIARY: Address = address!("0000000000000000000000000000000000600003"); -/// EIP-7702 delegator used in the delegated-CALL tests — its bytecode is `0xef0100 || -/// BENEFICIARY`, so a CALL to it should ultimately observe beneficiary state. -const DELEGATOR_TO_BENEFICIARY: Address = address!("0000000000000000000000000000000000600004"); - -/// Synthetic finite block-env-access compute-gas cap. Any value strictly less -/// than `u64::MAX` makes `detained_compute_gas_limit()` drop below `u64::MAX` -/// once `mark_beneficiary_balance_accessed()` fires; the exact value doesn't -/// matter as long as it doesn't saturate. -const DETENTION_CAP: u64 = 20_000_000; - -// ============================================================================ -// HELPERS -// ============================================================================ - -/// `(execution result, recorded limit usage, detained block-env-access compute-gas -/// limit, whether the beneficiary balance was marked accessed)`. -type BeneficiaryTransactResult = Result< - (ResultAndState, LimitUsage, u64, bool), - EVMError, ->; - -/// Executes `tx` under `spec` with the block beneficiary set to `BENEFICIARY` -/// and a finite block-env-access compute-gas limit so detention is observable -/// via `detained_compute_gas_limit()`. -fn transact_with_beneficiary( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx: TxEnv, -) -> BeneficiaryTransactResult { - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = MegaContext::new(db, spec).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(DETENTION_CAP), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let result = alloy_evm::Evm::transact_raw(&mut evm, tx)?; - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - let detained = evm.ctx_ref().additional_limit.borrow().detained_compute_gas_limit(); - let beneficiary_marked = - evm.ctx_ref().volatile_data_tracker.borrow().has_accessed_beneficiary_balance(); - Ok((result, usage, detained, beneficiary_marked)) -} - -/// Installs `0xef0100 || delegate_to` at `address`, mirroring what revm's -/// `apply_eip7702_auth_list` does for Type 4 transactions. -fn set_eip7702_delegation(db: &mut MemoryDatabase, address: Address, delegate_to: Address) { - let bytecode = Bytecode::new_eip7702(delegate_to); - let code_hash = bytecode.hash_slow(); - let account = db.load_account(address).unwrap(); - account.info.code = Some(bytecode); - account.info.code_hash = code_hash; - account.account_state = AccountState::None; -} - -/// Builds bytecode that calls `disableVolatileDataAccess()` on the -/// `MegaAccessControl` system contract. -fn call_disable_volatile_data_access(builder: BytecodeBuilder) -> BytecodeBuilder { - builder - .mstore(0x0, DISABLE_VOLATILE_DATA_ACCESS_SELECTOR) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) -} - -/// Decodes `VolatileDataAccessDisabled(uint8 accessType)` from revert data. -fn decode_volatile_data_access_disabled( - data: &[u8], -) -> IMegaAccessControl::VolatileDataAccessDisabled { - ::abi_decode(data) - .expect("valid VolatileDataAccessDisabled revert data") -} - -// ============================================================================ -// SELFDESTRUCT source-side coverage -// ============================================================================ - -/// REX6: When the executing contract IS the block beneficiary and disables -/// volatile access mid-frame, then SELFDESTRUCT to a non-beneficiary target, -/// the outer wrapper's source-side check must revert with -/// `VolatileDataAccessDisabled(Beneficiary)`. REX5 only inspected the stack -/// target — non-beneficiary destination, no revert. -/// -/// Setup: deploy `SELFDESTRUCTing` code at `BENEFICIARY`. Top-level tx is from -/// `CALLER` → `BENEFICIARY` (recipient == beneficiary). The disable-volatile -/// call happens INSIDE `BENEFICIARY`'s frame (so the outer call to `ACCESS_CONTROL` -/// is not itself blocked by the existing REX5 CALL wrapper). -#[test] -fn test_rex6_selfdestruct_source_eq_beneficiary_disabled_reverts() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(EMPTY_NON_BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, usage, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - // The SELFDESTRUCT's source-side guard reverts the beneficiary frame - // directly — the top-level tx surfaces as Revert. - let output = result.result.output().expect("revert with VolatileDataAccessDisabled payload"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "REX6 must revert with VolatileDataAccessDisabled (source-side check); got {output:?}", - ); - assert_eq!( - decode_volatile_data_access_disabled(output).accessType, - VolatileDataAccessType::Beneficiary, - ); - // Source-side guard short-circuits before any storage-layer side effect. - assert_eq!(usage.state_growth, 0, "no on_selfdestruct_new_account: {}", usage.state_growth); -} - -/// REX6: SELFDESTRUCT with the stack target == beneficiary, volatile disabled. -/// Same target-side case that REX5 already covers: the REX6 wrapper must still -/// revert here. The source-side check is additive, and the target-side check is -/// retained. -#[test] -fn test_rex6_selfdestruct_target_eq_beneficiary_disabled_still_reverts() { - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, usage, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - let output = result.result.output().expect("revert with VolatileDataAccessDisabled"); - assert_eq!(&output[..4], &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR); - assert_eq!( - decode_volatile_data_access_disabled(output).accessType, - VolatileDataAccessType::Beneficiary, - ); - assert_eq!(usage.state_growth, 0, "guard short-circuits"); -} - -// ============================================================================ -// CALL family EIP-7702 delegate resolution -// ============================================================================ - -/// REX6: A CALL to an EIP-7702 delegator whose code points at the beneficiary, -/// inside a disabled-volatile frame, must revert with -/// `VolatileDataAccessDisabled(Beneficiary)`. REX5 only compared the raw stack -/// operand and let the CALL through. -/// -/// Setup: top-level tx → `MIDDLE`. `MIDDLE`'s code disables volatile access -/// then CALLs the delegator. In REX6 the wrapper resolves DELEGATOR → -/// BENEFICIARY and reverts the `MIDDLE` frame; in REX5 the CALL completes. -#[test] -fn test_rex6_call_to_eip7702_delegator_to_beneficiary_disabled_reverts() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(DELEGATOR_TO_BENEFICIARY) - .push_number(100_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code) - .account_code(BENEFICIARY, beneficiary_code); - set_eip7702_delegation(&mut db, DELEGATOR_TO_BENEFICIARY, BENEFICIARY); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - let output = result.result.output().expect("revert with VolatileDataAccessDisabled"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "REX6 wrapper must resolve DELEGATOR → BENEFICIARY and revert: {output:?}", - ); - assert_eq!( - decode_volatile_data_access_disabled(output).accessType, - VolatileDataAccessType::Beneficiary, - ); -} - -/// REX6: A CALL to an EIP-7702 delegator pointing at the beneficiary, with -/// volatile access enabled, must engage beneficiary detention via -/// `MegaContext::load_account_delegated`'s resolved-delegate mark. -/// -/// REX5 only marks the raw input (`DELEGATOR_TO_BENEFICIARY`), which is not the -/// block beneficiary, so detention never engages. -/// -/// We compare both volatile-access marking and the detained compute-gas limit -/// to make the assertion self-explanatory. -#[test] -fn test_rex6_call_to_eip7702_delegator_to_beneficiary_enabled_marks_beneficiary() { - let beneficiary_code = BytecodeBuilder::default().stop().build(); - let middle_code = BytecodeBuilder::default() - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_number(0_u64) - .push_address(DELEGATOR_TO_BENEFICIARY) - .push_number(100_000_u64) - .append(CALL) - .append(STOP) - .build(); - - let build_db = || { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code.clone()) - .account_code(BENEFICIARY, beneficiary_code.clone()); - set_eip7702_delegation(&mut db, DELEGATOR_TO_BENEFICIARY, BENEFICIARY); - db - }; - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result_rex5, _, detained_rex5, marked_rex5) = - transact_with_beneficiary(MegaSpecId::REX5, &mut build_db(), tx.clone()).unwrap(); - assert!(result_rex5.result.is_success(), "REX5 tx should succeed: {result_rex5:?}"); - assert!(!marked_rex5, "REX5 must not mark beneficiary (raw target = DELEGATOR != BENEFICIARY)"); - assert_eq!(detained_rex5, u64::MAX, "REX5 must not engage detention: {detained_rex5}"); - - let (result_rex6, _, detained_rex6, marked_rex6) = - transact_with_beneficiary(MegaSpecId::REX6, &mut build_db(), tx).unwrap(); - assert!(result_rex6.result.is_success(), "REX6 tx should succeed: {result_rex6:?}"); - assert!(marked_rex6, "REX6 must mark beneficiary via resolved delegate"); - assert!(detained_rex6 < u64::MAX, "REX6 must engage detention: {detained_rex6}"); -} - -// ============================================================================ -// Existing-target SELFDESTRUCT accounting -// ============================================================================ - -/// REX6: SELFDESTRUCT to an *existing* non-beneficiary target with value must -/// record `DataSize` +40 and KV +1 for the balance update, but no `StateGrowth` -/// (the target already exists). REX5 left all three at zero. -/// -/// Driver contract is not the beneficiary, target is not the beneficiary; -/// keeps the detention and beneficiary marks out of the way of the accounting -/// assertion. -#[test] -fn test_rex6_selfdestruct_to_existing_target_records_data_size_and_kv() { - let code = BytecodeBuilder::default() - .push_address(EXISTING_NON_BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, code.clone()) - .account_balance(MIDDLE, U256::from(1_000_000u64)) - // Pre-fund EXISTING_NON_BENEFICIARY so it is *not* empty. - .account_balance(EXISTING_NON_BENEFICIARY, U256::from(1u64)) - }; - let tx = TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(1_000_000).build_fill(); - - // REX5 records nothing for an existing-target balance update. - let (result_rex5, usage_rex5, _, _) = - transact_with_beneficiary(MegaSpecId::REX5, &mut build_db(), tx.clone()).unwrap(); - assert!(result_rex5.result.is_success(), "REX5 tx should succeed: {result_rex5:?}"); - assert_eq!(usage_rex5.state_growth, 0, "REX5 must not record state growth (target exists)"); - let baseline_data_size = usage_rex5.data_size; - let baseline_kv = usage_rex5.kv_updates; - - // REX6: existing-target arm records DataSize/KV but not StateGrowth. - let (result_rex6, usage_rex6, _, _) = - transact_with_beneficiary(MegaSpecId::REX6, &mut build_db(), tx).unwrap(); - assert!(result_rex6.result.is_success(), "REX6 tx should succeed: {result_rex6:?}"); - assert_eq!( - usage_rex6.state_growth, 0, - "REX6 existing-target SELFDESTRUCT must NOT record state growth: {}", - usage_rex6.state_growth, - ); - assert!( - usage_rex6.data_size > baseline_data_size, - "REX6 must record DataSize delta vs REX5 baseline ({} > {})", - usage_rex6.data_size, - baseline_data_size, - ); - assert!( - usage_rex6.kv_updates > baseline_kv, - "REX6 must record KV update delta vs REX5 baseline ({} > {})", - usage_rex6.kv_updates, - baseline_kv, - ); -} - -/// REX6 regression guard: SELFDESTRUCT to an *empty* non-beneficiary target -/// must still go through the new-target arm (state growth + `DataSize` + KV + -/// new-account storage gas), matching REX5's behavior for the same case. -#[test] -fn test_rex6_selfdestruct_to_empty_target_still_records_state_growth() { - let code = - BytecodeBuilder::default().push_address(EMPTY_NON_BENEFICIARY).append(SELFDESTRUCT).build(); - - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, code) - .account_balance(MIDDLE, U256::from(1_000_000u64)); - let tx = TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(1_000_000).build_fill(); - - let (result, usage, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - assert!(result.result.is_success(), "REX6 tx should succeed: {result:?}"); - assert!( - usage.state_growth > 0, - "REX6 new-target SELFDESTRUCT must still record state growth: {}", - usage.state_growth, - ); -} - -// ============================================================================ -// SELFDESTRUCT target-side freeze, enabled-path detention, self-target, DB-error -// ============================================================================ - -/// With volatile access enabled, a SELFDESTRUCT whose source is the beneficiary engages detention -/// purely via the entry mark: reaching beneficiary-as-executor requires entering its frame (here -/// the tx recipient is the beneficiary, so `on_new_tx` eagerly marks the beneficiary balance), so -/// detention already engages under REX5 and REX6 identically — no SELFDESTRUCT-specific source hook -/// is needed on the enabled path. -#[test] -fn test_selfdestruct_source_eq_beneficiary_enabled_detention_via_entry_mark_rex5_eq_rex6() { - let beneficiary_code = - BytecodeBuilder::default().push_address(EMPTY_NON_BENEFICIARY).append(SELFDESTRUCT).build(); - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code.clone()) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)) - }; - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (r5, _, d5, m5) = - transact_with_beneficiary(MegaSpecId::REX5, &mut build_db(), tx.clone()).unwrap(); - let (r6, _, d6, m6) = transact_with_beneficiary(MegaSpecId::REX6, &mut build_db(), tx).unwrap(); - assert!(r5.result.is_success() && r6.result.is_success()); - // The entry mark (recipient == beneficiary) engages detention on BOTH specs, so the enabled - // path needs no SELFDESTRUCT-specific source hook. - assert!(m5 && m6, "entry-mark engages detention on both specs (m5={m5} m6={m6})"); - assert!(d5 < u64::MAX && d6 < u64::MAX, "both detained (d5={d5} d6={d6})"); - assert_eq!( - d5, d6, - "enabled-path detention is identical on REX5/REX6 (entry-mark): {d5} == {d6}" - ); -} - -// ============================================================================ -// DB-error coverage for the REX6 `selfdestruct_rex6` inspect paths -// ============================================================================ - -/// REX6: a DB failure while resolving the SELFDESTRUCT target must SURFACE (as an `EVMError` or a -/// non-success halt) — never a silent success. `MemoryDatabase` is infallible, so this is only -/// reachable by injecting a `basic()` failure on the target. The error surfaces as an `EVMError` -/// (the journal records the DB failure and returns it at the transaction boundary), the robust -/// outcome the SELFDESTRUCT accounting path must preserve. -#[test] -fn test_rex6_selfdestruct_db_error_on_target_surfaces() { - let code = BytecodeBuilder::default() - .push_address(EXISTING_NON_BENEFICIARY) - .append(SELFDESTRUCT) - .build(); - let inner = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, code) - .account_balance(MIDDLE, U256::from(1_000_000u64)) - .account_balance(EXISTING_NON_BENEFICIARY, U256::from(1u64)); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(EXISTING_NON_BENEFICIARY); - - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = - MegaContext::new(&mut db, MegaSpecId::REX6).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(DETENTION_CAP), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(1_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let surfaced = match alloy_evm::Evm::transact_raw(&mut evm, tx) { - Err(_) => true, // propagated as EVMError - Ok(result) => !result.result.is_success(), // or a non-success halt - }; - assert!(surfaced, "a DB error on the SELFDESTRUCT target must surface, not be swallowed"); -} - -/// REX6: SELFDESTRUCT to SELF on a non-same-tx-created account is an EIP-6780 balance no-op -/// (self → self transfer, no account-info write, account not deleted), so the existing-target -/// accounting arm must record NOTHING — same as REX5. Guards against over-recording `DataSize` -/// +40 / KV +1 (and a spurious additional-limit revert) for a write that never happens. -#[test] -fn test_rex6_selfdestruct_to_self_records_no_existing_target_accounting() { - let code = BytecodeBuilder::default().push_address(MIDDLE).append(SELFDESTRUCT).build(); - let build_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, code.clone()) - .account_balance(MIDDLE, U256::from(1_000_000u64)) - }; - let tx = TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(1_000_000).build_fill(); - - let (r5, u5, _, _) = - transact_with_beneficiary(MegaSpecId::REX5, &mut build_db(), tx.clone()).unwrap(); - let (r6, u6, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut build_db(), tx).unwrap(); - assert!(r5.result.is_success() && r6.result.is_success()); - assert_eq!( - u6.data_size, u5.data_size, - "SELFDESTRUCT to self is a no-op; REX6 must not over-record DataSize (rex6={} rex5={})", - u6.data_size, u5.data_size, - ); - assert_eq!( - u6.kv_updates, u5.kv_updates, - "SELFDESTRUCT to self is a no-op; REX6 must not over-record KV (rex6={} rex5={})", - u6.kv_updates, u5.kv_updates, - ); -} - -/// REX6: a malformed SELFDESTRUCT (stack underflow) executed by the beneficiary with volatile -/// access disabled must still halt with `StackUnderflow`. The source-side beneficiary guard must -/// not pre-empt the missing-operand check — it only applies once the SELFDESTRUCT has a target to -/// act on. Pre-REX6 already produced `StackUnderflow` here (the source guard is REX6-only). -#[test] -fn test_rex6_selfdestruct_stack_underflow_keeps_stack_underflow_under_source_guard() { - // BENEFICIARY disables volatile access, then runs SELFDESTRUCT with an EMPTY stack (underflow). - let beneficiary_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .append(SELFDESTRUCT) // no beneficiary operand pushed -> stack underflow - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(BENEFICIARY, beneficiary_code) - .account_balance(BENEFICIARY, U256::from(1_000_000u64)); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(BENEFICIARY) - .gas_limit(100_000_000) - .build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - // The malformed SELFDESTRUCT must surface as a Halt (StackUnderflow), NOT a - // VolatileDataAccessDisabled Revert pre-empting the operand check. - assert!( - matches!(&result.result, ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")), - "stack-underflow SELFDESTRUCT must keep its StackUnderflow halt, not be pre-empted by the \ - beneficiary revert; got: {:?}", - result.result, - ); -} - -/// REX6: with volatile access disabled, a CALL whose effective target is NOT the beneficiary -/// (no EIP-7702 delegation to it) passes the beneficiary-volatile check and runs normally — the -/// guard reverts only when the resolved target is the beneficiary. -#[test] -fn test_rex6_call_to_non_beneficiary_under_disabled_volatile_proceeds() { - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(EMPTY_NON_BENEFICIARY) // target — not the beneficiary, no delegation - .push_number(100_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code); - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - assert!( - result.result.is_success(), - "a CALL to a non-beneficiary target under disabled volatile access must proceed: {:?}", - result.result, - ); -} - -/// REX6: a DB failure while `load_account_delegated` resolves a CALL target's EIP-7702 delegate -/// must SURFACE (as an `EVMError` or a non-success halt), never a silent success. The resolve error -/// is swallowed by the side-mark (best-effort), and the inner `load_account_delegated` then -/// surfaces the failure. `MemoryDatabase` is infallible, so this is only reachable by injecting a -/// `basic()` failure on the CALL target. -#[test] -fn test_rex6_call_db_error_on_target_surfaces() { - let middle_code = BytecodeBuilder::default() - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(EMPTY_NON_BENEFICIARY) // target whose account read will fail - .push_number(100_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - let inner = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(EMPTY_NON_BENEFICIARY); - - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX6).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let surfaced = match alloy_evm::Evm::transact_raw(&mut evm, tx) { - Err(_) => true, - Ok(result) => !result.result.is_success(), - }; - assert!(surfaced, "a DB error on the CALL target must surface, not be swallowed"); -} - -/// REX6: a malformed CALL (stack underflow) under disabled volatile access must keep its -/// `StackUnderflow` halt — the volatile wrapper's operand peek finds nothing and falls through, -/// so the missing-operand check is not pre-empted by a beneficiary revert. -#[test] -fn test_rex6_call_stack_underflow_under_disabled_volatile_keeps_stack_underflow() { - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .append(CALL) // no operands pushed -> stack underflow - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code); - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - - let (result, _, _, _) = transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx).unwrap(); - assert!( - matches!(&result.result, ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")), - "stack-underflow CALL under disabled volatile must keep its StackUnderflow halt, not be \ - pre-empted by a beneficiary revert: {:?}", - result.result, - ); -} - -/// A partial-stack CALL — operands `[gas, target]` present but the remaining operands missing — -/// whose target's account read fails surfaces the DB error identically on REX5 and REX6 under -/// disabled volatile access, i.e. the REX6 beneficiary-delegate resolve does NOT uniquely mask -/// anything. `storage_gas_ext::call` must read the target's account (for new-account storage gas) -/// before the opcode validates its later operands, so a failing target surfaces there regardless of -/// the volatile wrapper; the wrapper's resolve reads the same account. Pins that subsumption so a -/// future change to the wrapper's resolve placement cannot silently diverge REX6 from the frozen -/// REX5 behavior. The target is not the beneficiary (the raw-target check misses). -#[test] -fn test_call_partial_stack_db_error_on_target_surfaces_rex5_eq_rex6() { - let surfaces = |spec: MegaSpecId| { - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(EMPTY_NON_BENEFICIARY) // target (position 1) — not the beneficiary - .push_number(100_000_u64) // gas (position 0); remaining CALL operands missing - .append(CALL) - .append(STOP) - .build(); - let inner = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_account = Some(EMPTY_NON_BENEFICIARY); - - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = MegaContext::new(&mut db, spec).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - match alloy_evm::Evm::transact_raw(&mut evm, tx) { - Err(_) => true, - Ok(result) => !result.result.is_success(), - } - }; - assert!(surfaces(MegaSpecId::REX5), "REX5: failing target must surface"); - assert!( - surfaces(MegaSpecId::REX6), - "REX6 must surface identically to REX5 — the delegate resolve masks nothing the mandatory \ - storage-gas target read would not already surface", - ); -} - -/// REX6: a malformed (partial-stack) CALL whose target's *code* fails to load must keep its -/// `StackUnderflow` halt under disabled volatile access. The beneficiary-volatile precheck resolves -/// the target's EIP-7702 delegate on a best-effort basis, which loads the target's code -/// (`load_code = true`); that read must NOT stash a `ctx.error`. Here the target's `basic()` -/// succeeds — so the mandatory storage-gas inspect (`load_code = false`) does not touch the code -/// and the CALL reaches the operand check and underflows — but the target's code load fails, a -/// failure only the precheck touches. Without a non-stashing (best-effort) resolve the underflow is -/// masked by a spurious `EVMError`. -#[test] -fn test_rex6_call_partial_stack_code_load_failure_keeps_stack_underflow() { - // `to` is a non-beneficiary target whose code is lazy and whose `code_by_hash` is injected - // to fail (so only the `load_code = true` precheck touches the failure). - let to = EXISTING_NON_BENEFICIARY; - let to_code_hash: B256 = Bytecode::new_eip7702(BENEFICIARY).hash_slow(); - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_address(to) // target (position 1) - .push_number(100_000_u64) // gas (position 0); remaining CALL operands missing - .append(CALL) - .append(STOP) - .build(); - let inner = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code) - .account_lazy_code(to, to_code_hash); - let mut db = ErrorInjectingDatabase::new(inner); - db.fail_on_code_by_hash = Some(to_code_hash); - - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = MegaContext::new(&mut db, MegaSpecId::REX6).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - match alloy_evm::Evm::transact_raw(&mut evm, tx) { - Ok(result) => assert!( - matches!(&result.result, ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")), - "partial-stack CALL whose target code fails to load must keep its StackUnderflow halt: \ - {:?}", - result.result, - ), - Err(e) => panic!( - "partial-stack CALL must keep StackUnderflow; the precheck's code-load failure was \ - stashed and surfaced as EVMError instead: {e:?}" - ), - } -} - -/// REX6: a CALL to a beneficiary that is *itself* an EIP-7702 delegator must still revert under -/// disabled volatile access. The raw target is the beneficiary, so loading it observes beneficiary -/// state regardless of where it delegates — the guard must match on the raw target before resolving -/// the delegate (resolving first would yield the delegate `!= beneficiary` and miss the revert). -#[test] -fn test_rex6_call_to_beneficiary_that_delegates_elsewhere_still_reverts() { - let middle_code = call_disable_volatile_data_access(BytecodeBuilder::default()) - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(BENEFICIARY) // raw target IS the beneficiary - .push_number(100_000_u64) // gas - .append(CALL) - .append(STOP) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000u64)) - .account_code(MIDDLE, middle_code); - // The beneficiary itself delegates to a non-beneficiary address. - set_eip7702_delegation(&mut db, BENEFICIARY, EMPTY_NON_BENEFICIARY); - - let (result, _, _, _) = - transact_with_beneficiary(MegaSpecId::REX6, &mut db, tx_to_middle()).unwrap(); - let output = result.result.output().expect("a VolatileDataAccessDisabled revert payload"); - assert_eq!( - &output[..4], - &VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, - "a CALL to a beneficiary that delegates elsewhere must still revert (raw target matches): {:?}", - result.result, - ); -} - -/// Small helper: the standard `CALLER -> MIDDLE` transaction used across the CALL tests. -fn tx_to_middle() -> TxEnv { - TxEnvBuilder::default().caller(CALLER).call(MIDDLE).gas_limit(100_000_000).build_fill() -} diff --git a/crates/mega-evm/tests/_pending/rex6/common.rs b/crates/mega-evm/tests/_pending/rex6/common.rs deleted file mode 100644 index 691e7dbf0..000000000 --- a/crates/mega-evm/tests/_pending/rex6/common.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Shared helpers for the REX6 gas-metering-order test suite. - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::MemoryDatabase, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, - MegaSpecId, MegaTransaction, -}; -use revm::{ - context::{result::ExecutionResult, tx::TxEnvBuilder}, - handler::EvmTr, -}; - -/// Transaction sender. -pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000200000"); -/// Contract invoked by the transaction; its code exercises the opcode under test. -pub(crate) const CONTRACT: Address = address!("0000000000000000000000000000000000200001"); -/// A spare empty address used as a CALL / SELFDESTRUCT target. -pub(crate) const EMPTY_TARGET: Address = address!("0000000000000000000000000000000000200002"); - -/// The post-transaction readings compared across specs. -pub(crate) struct Outcome { - pub(crate) result: ExecutionResult, - /// Post-tx compute-gas tracker reading (`get_usage().compute_gas`). - pub(crate) compute_gas: u64, - /// Post-tx data-size tracker reading (`get_usage().data_size`). - pub(crate) data_size: u64, - /// Receipt `gas_used` (combined compute + storage EVM gas). - pub(crate) gas_used: u64, -} - -impl Outcome { - pub(crate) fn is_success(&self) -> bool { - self.result.is_success() - } -} - -/// Runs a single transaction that calls [`CONTRACT`] under `spec` with the given DB and runtime -/// limits, returning the execution result plus the post-tx compute-gas reading and `gas_used`. -pub(crate) fn transact( - spec: MegaSpecId, - mut db: MemoryDatabase, - limits: EvmTxRuntimeLimits, -) -> Outcome { - let mut context = MegaContext::new(&mut db, spec).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context); - let result = - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - let gas_used = result.result.gas_used(); - Outcome { - result: result.result, - compute_gas: usage.compute_gas, - data_size: usage.data_size, - gas_used, - } -} - -/// Runs [`transact`] with the spec's default runtime limits. -pub(crate) fn transact_default(spec: MegaSpecId, db: MemoryDatabase) -> Outcome { - transact(spec, db, EvmTxRuntimeLimits::from_spec(spec)) -} diff --git a/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs b/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs deleted file mode 100644 index f411f4d41..000000000 --- a/crates/mega-evm/tests/_pending/rex6/create2_metering_order.rs +++ /dev/null @@ -1,568 +0,0 @@ -//! REX6 CREATE2 gas-metering order. -//! -//! REX6 folds the CREATE2 memory-expansion (`resize_memory!`) gas into the single compute-gas -//! recording taken after the inner opcode completes, instead of the pre-REX6 split recording (REX5 -//! recorded it eagerly before the storage charge; pre-REX5 recorded it after the inner op). -//! -//! Coverage: -//! - **Happy path**: REX6 records the same total compute gas as REX5 (and identical `gas_used`), -//! proving the single recording equals the REX5 eager-resize + inner sum with no double/miss -//! count. -//! - **Missing salt**: a CREATE2 with the salt operand absent halts with `StackUnderflow` under -//! both specs without leaking any `resize_gas` into the compute tracker. -//! - **Failure-path divergence**: under a compute-gas limit tight enough that the memory-expansion -//! gas crosses it, REX5 halts at the eager resize record (before the inner opcode runs) while -//! REX6 defers recording until after the inner opcode has executed — so REX6 records strictly -//! more compute gas. This is the intended, spec-defined behavior change of the canonical order. - -use std::{cell::RefCell, convert::Infallible, rc::Rc}; - -use crate::common::{transact, transact_default, CALLER, CONTRACT, EMPTY_TARGET}; -use alloy_primitives::{Bytes, U256}; -use mega_evm::{ - constants::mini_rex::MAX_INITCODE_SIZE, - test_utils::{BytecodeBuilder, MemoryDatabase}, - BucketHasher, BucketId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - TestExternalEnvs, -}; -use revm::{ - bytecode::opcode::{CREATE, CREATE2, STATICCALL, STOP}, - context::{tx::TxEnvBuilder, ContextTr}, - inspector::Inspector, - interpreter::{ - interpreter_types::InterpreterTypes, CallInputs, CallOutcome, InstructionResult, - }, -}; - -/// Records the `InstructionResult` an inner call to [`EMPTY_TARGET`] halted with. Used to observe -/// the halt reason of a `CREATE2` executed inside a `STATICCALL` frame, which is otherwise not -/// visible in the outer transaction result. -#[derive(Clone, Default)] -struct InnerHaltCapture(Rc>>); - -impl Inspector for InnerHaltCapture { - fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { - if inputs.target_address == EMPTY_TARGET { - *self.0.borrow_mut() = Some(outcome.result.result); - } - } -} - -/// Routes every SALT lookup to [`STATIC_TEST_BUCKET_ID`] so a raised capacity scales the -/// contract-creation storage charge inside the static callee. -#[derive(Debug, Clone, Copy)] -struct SingleBucketHasher; - -impl BucketHasher for SingleBucketHasher { - fn bucket_id(_key: &[u8]) -> BucketId { - STATIC_TEST_BUCKET_ID - } -} - -/// Bucket every SALT lookup is routed to under [`SingleBucketHasher`]. -const STATIC_TEST_BUCKET_ID: BucketId = 7; - -/// 2 × `MIN_BUCKET_SIZE` (256) → a 2× multiplier, so the REX-family contract-creation charge -/// `CONTRACT_CREATION_STORAGE_GAS_BASE × (multiplier − 1)` is 32,000 gas instead of the 0 a -/// minimum-capacity bucket yields. -const DOUBLED_BUCKET_CAPACITY: u64 = 512; - -/// Runs a tx to a contract that `STATICCALL`s [`EMPTY_TARGET`] (whose code is `inner_bytecode`) -/// with `forward_gas`, and returns the halt reason the static callee produced. A -/// `bucket_capacity` of `Some(DOUBLED_BUCKET_CAPACITY)` makes the contract-creation storage -/// charge nonzero (32,000 gas); `None` leaves every bucket at minimum capacity (charge = 0). -fn static_halt_reason_for_bytecode( - spec: MegaSpecId, - inner_bytecode: Bytes, - forward_gas: u64, - bucket_capacity: Option, -) -> Option { - let outer_staticcall = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_address(EMPTY_TARGET) // to - .push_number(forward_gas) // gas - .append(STATICCALL) - .append(STOP) - .build(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, outer_staticcall) - .account_code(EMPTY_TARGET, inner_bytecode); - - let mut external_envs = TestExternalEnvs::::new(); - if let Some(capacity) = bucket_capacity { - external_envs = external_envs.with_bucket_capacity(STATIC_TEST_BUCKET_ID, capacity); - } - - let capture = InnerHaltCapture::default(); - let mut context = MegaContext::new(&mut db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let tx = - TxEnvBuilder::default().caller(CALLER).call(CONTRACT).gas_limit(100_000_000).build_fill(); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let mut evm = MegaEvm::new(context).with_inspector(capture.clone()); - alloy_evm::Evm::transact_raw(&mut evm, tx).expect("tx should not surface EVMError"); - let reason = *capture.0.borrow(); - reason -} - -/// `CREATE2(value=0, offset=0, size=initcode_len, salt=0)` then `STOP`, as the static callee. -fn static_create2_bytecode(initcode_len: u64) -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(initcode_len) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// Runs a static `CREATE2` with the given initcode length, ample forwarded gas, and -/// minimum-capacity buckets, returning its halt reason. -fn static_create2_halt_reason(spec: MegaSpecId, initcode_len: u64) -> Option { - static_halt_reason_for_bytecode(spec, static_create2_bytecode(initcode_len), 50_000_000, None) -} - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// 32 KiB initcode: the wrapper-side memory expansion gas is in the multi-KiB range, large enough -/// that a double-count or miss-count of the resize gas is visible, yet under the configured -/// initcode size limit (548,864 bytes — see `constants::mini_rex::MAX_INITCODE_SIZE`, well above -/// the vanilla EIP-3860 default) so the inner CREATE2 sets up a child frame rather than erroring. -const INITCODE_LEN: u64 = 32 * 1024; - -/// `CREATE2(value=0, offset=0, size=INITCODE_LEN, salt=0)` then `STOP`. The zero-initialized -/// initcode region keccak-hashes to a `STOP`-only constructor that deploys empty code. -fn build_create2_contract() -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(INITCODE_LEN) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build() -} - -/// The same four operand pushes as [`build_create2_contract`] followed by `STOP` (no CREATE2). -/// Running this measures the compute-gas usage accumulated *before* the CREATE2 opcode, used to -/// place a compute-gas limit precisely inside the CREATE2 memory-expansion window. -fn build_pushes_only_contract() -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) - .push_number(INITCODE_LEN) - .push_number(0u64) - .push_number(0u64) - .stop() - .build() -} - -fn db_with(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) -} - -#[test] -fn test_create2_missing_salt_consistent_rex5_rex6() { - // Three CREATE2 operands, salt OMITTED: the wrapper's `stack.inspect::<3>()` fails, halting - // with `StackUnderflow` before any memory expansion under both specs. - let code = BytecodeBuilder::default() - .push_number(INITCODE_LEN) // length (depth 2) - .push_number(0u64) // offset (depth 1) - .push_number(0u64) // value (depth 0) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - let is_stack_underflow = |o: &crate::common::Outcome| { - matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")) - }; - assert!(is_stack_underflow(&r5), "REX5 must halt with StackUnderflow; got {:?}", r5.result); - assert!(is_stack_underflow(&r6), "REX6 must halt with StackUnderflow; got {:?}", r6.result); - - // Neither spec records any resize gas on the salt-underflow halt path: both readings equal the - // shared TX intrinsic baseline. - assert_eq!( - r5.compute_gas, r6.compute_gas, - "compute_gas must be identical on the salt-underflow halt path; REX5={} REX6={}", - r5.compute_gas, r6.compute_gas - ); -} - -/// An oversized CREATE2 initcode must halt with `CreateInitCodeSizeLimit` under REX6 -/// BEFORE any memory-expansion/copy/keccak256 prework runs, not after. -/// -/// A 10 MiB initcode is chosen so the memory-expansion gas would be enormous (quadratic word -/// cost, ~210M gas — far past the 100M tx gas limit) if `resize_memory!` ran. Without the fix, -/// `resize_memory!` itself would exhaust the gas limit first and halt with `MemoryOOG` — the -/// canonical EIP-3860 check inside the inner opcode is never reached. With the fix, the halt -/// fires immediately with `CreateInitCodeSizeLimit`, before `resize_memory!` is ever called. -/// `gas_used` is NOT a useful signal here: any non-revert exceptional halt (both `MemoryOOG` and -/// `CreateInitCodeSizeLimit`) consumes the full remaining gas regardless of when it fires — this -/// matches the finding's own claim that committed gas/state is identical under REX6 either way; -/// only the halt-reason label (and the avoided node CPU work) differ. -#[test] -fn test_create2_oversized_initcode_halts_before_prework_rex6() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, far past the 548,864-byte cap - - let code = BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(HUGE_INITCODE_LEN) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - assert!( - matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "REX6 must halt with CreateInitCodeSizeLimit (not MemoryOOG) for a 10 MiB initcode — \ - the halt must fire before resize_memory! ever runs, got {:?}", - r6.result, - ); -} - -/// Halt-reason parity for a "moderately" oversized initcode (bigger than the 548,864-byte cap, -/// but small enough that `resize_memory!`'s own gas cost stays well within the 100M tx gas -/// limit). Both specs reach `CreateInitCodeSizeLimit` — REX5 via the slower prework-then-inner- -/// check path (frozen, unpatched), REX6 via the immediate early check. -/// -/// `gas_used` is deliberately NOT compared here: both specs consume the tx's full gas limit -/// regardless (any non-revert exceptional halt does), so equality there is a trivial artifact of -/// halt semantics, not a meaningful check. What genuinely differs — and is asserted below — is -/// the internal `compute_gas` tracker: REX5 still eagerly records the ~742,895-gas memory -/// expansion for this length before it ever reaches the inner opcode's check, while REX6's early -/// halt never reaches that recording at all. This divergence is pre-existing REX6 metering-order -/// behavior (`create_rex6`'s single post-body recording), not something this fix changes — it is -/// asserted here only to document that "same halt reason" does not imply "identical internal -/// accounting," and so a future change collapsing this gap doesn't silently look like a -/// regression. -#[test] -fn test_create2_moderately_oversized_initcode_same_reason_both_specs() { - const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost is negligible - - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MODERATELY_OVERSIZED_LEN) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - - let r5 = transact_default(MegaSpecId::REX5, db_with(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, db_with(code)); - - let is_create_initcode_size_limit = |o: &crate::common::Outcome| { - matches!(&o.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")) - }; - assert!( - is_create_initcode_size_limit(&r5), - "REX5 must reach CreateInitCodeSizeLimit via the slower prework-then-inner-check path: {:?}", - r5.result, - ); - assert!( - is_create_initcode_size_limit(&r6), - "REX6 must reach CreateInitCodeSizeLimit via the immediate early check: {:?}", - r6.result, - ); - assert!( - r5.compute_gas > r6.compute_gas + 500_000, - "REX5 must still eagerly record the memory-expansion compute gas that REX6's early halt \ - skips; REX5={} REX6={}", - r5.compute_gas, - r6.compute_gas, - ); -} - -/// Exact-boundary test: `initcode_len == max_initcode_size()` must NOT halt (the -/// comparator is strict `>`, matching revm's own canonical check), and -/// `max_initcode_size() + 1` MUST halt with `CreateInitCodeSizeLimit`. Pins the comparator -/// itself — a future `>` → `>=` regression would make the boundary length halt on REX6 while -/// still succeeding pre-REX6, a real spec divergence that the "moderately oversized" test above -/// (600,000 bytes, well clear of the boundary) cannot catch. -#[test] -fn test_create2_exact_boundary_initcode_length() { - let at_limit = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MAX_INITCODE_SIZE as u64) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - let r6_at_limit = transact_default(MegaSpecId::REX6, db_with(at_limit)); - assert!( - r6_at_limit.is_success(), - "an initcode exactly at max_initcode_size must succeed (strict `>`, not `>=`): {:?}", - r6_at_limit.result, - ); - - let over_limit = BytecodeBuilder::default() - .push_number(0u64) - .push_number(MAX_INITCODE_SIZE as u64 + 1) - .push_number(0u64) - .push_number(0u64) - .append(CREATE2) - .append(STOP) - .build(); - let r6_over_limit = transact_default(MegaSpecId::REX6, db_with(over_limit)); - assert!( - matches!(&r6_over_limit.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "one byte over max_initcode_size must halt with CreateInitCodeSizeLimit: {:?}", - r6_over_limit.result, - ); -} - -/// Operand-order test: an oversized `initcode_len` combined with an `initcode_offset` -/// that does not fit in a `usize` must still halt with `CreateInitCodeSizeLimit` on REX6 — the -/// size check runs before the offset is ever converted. -/// -/// The wrapper converts `initcode_len` first, then runs the REX6 size check, then converts -/// `initcode_offset`. If the conversion order were the reverse (offset first, as it was before -/// this fix), the unrepresentable offset would halt with `InvalidOperandOOG` -/// (`OutOfGas(InvalidOperand)`) and mask the intended EIP-3860 halt. Pre-REX6 has no early size -/// check, so it correctly halts on the offset overflow — the same `InvalidOperandOOG` reason both -/// operands share, which is why reordering their conversion is inert on sealed specs. -#[test] -fn test_create2_oversized_len_unrepresentable_offset_halts_initcode_limit_rex6() { - // `len` is oversized but representable as `usize`; `offset` is > `usize::MAX`. - let code = BytecodeBuilder::default() - .push_number(0u64) // salt - .push_number(MAX_INITCODE_SIZE as u64 + 1) // size: oversized, but fits usize - .push_u256(U256::from(u128::MAX)) // offset: > usize::MAX (unrepresentable) - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let r6 = transact_default(MegaSpecId::REX6, db_with(code.clone())); - assert!( - matches!(&r6.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("CreateInitCodeSizeLimit")), - "REX6 must halt with CreateInitCodeSizeLimit even when the offset is unrepresentable — \ - the size check must run before the offset is converted; got {:?}", - r6.result, - ); - - // Pre-REX6 (sealed) has no early size check, so the unrepresentable offset is what halts, with - // OutOfGas(InvalidOperand). It must NOT surface CreateInitCodeSizeLimit — this pins that the - // reorder did not change sealed-spec behavior. - let r5 = transact_default(MegaSpecId::REX5, db_with(code)); - assert!( - matches!(&r5.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("InvalidOperand")), - "REX5 (sealed) must halt on the offset overflow (OutOfGas(InvalidOperand)), not the REX6 \ - size check; got {:?}", - r5.result, - ); -} - -/// Static-call precedence: a `CREATE2` inside a `STATICCALL` with oversized initcode must report -/// the static-context rejection (`StateChangeDuringStaticCall`), NOT `CreateInitCodeSizeLimit`. -/// REX6 halts with `StateChangeDuringStaticCall` at the top of the REX6 create handler, before -/// any operand read, the size check, or any resize/copy/keccak256 prework runs. REX5 (sealed) has -/// no such hoist, so it reaches the same halt reason only after running that prework and falling -/// through to the inner opcode's own static guard. A "moderately" oversized length (over the cap, -/// but cheap to resize) is used so REX5's prework-then-inner-guard path stays affordable rather -/// than running out of gas on the resize. -#[test] -fn test_create2_static_oversized_initcode_reports_static_rejection() { - const MODERATELY_OVERSIZED_LEN: u64 = 600_000; // > 548,864 cap, resize cost negligible vs. gas - - let is_static_reject = |r: Option| { - matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) - }; - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, MODERATELY_OVERSIZED_LEN); - let r5 = static_create2_halt_reason(MegaSpecId::REX5, MODERATELY_OVERSIZED_LEN); - - assert!( - is_static_reject(r6), - "REX6 static oversized CREATE2 must halt with StateChangeDuringStaticCall, not \ - CreateInitCodeSizeLimit; got {r6:?}", - ); - assert!( - is_static_reject(r5), - "REX5 (sealed) static oversized CREATE2 halts with StateChangeDuringStaticCall; got {r5:?}", - ); - assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static-CREATE2 halt reason"); -} - -/// Static-call precedence at an unaffordable initcode length: a static `CREATE2` whose initcode -/// length would make `resize_memory!` prohibitively expensive must still halt with -/// `StateChangeDuringStaticCall` on REX6 — the hoisted guard fires before any operand conversion -/// or memory work is attempted, so the halt reason does not depend on whether the resize could -/// have been afforded. REX5 (sealed) has no such hoist: it attempts the resize, cannot afford it -/// out of the gas forwarded to the inner frame, and halts with a memory out-of-gas reason instead -/// — mirroring the non-static divergence pinned above, now shown to hold inside a static frame. -#[test] -fn test_create2_static_hugely_oversized_initcode_halt_reason() { - const HUGE_INITCODE_LEN: u64 = 10 * 1024 * 1024; // 10 MiB, resize cost far exceeds forwarded gas - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, HUGE_INITCODE_LEN); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE2 with a hugely oversized initcode must halt with \ - StateChangeDuringStaticCall before resize_memory! is ever attempted; got {r6:?}", - ); - - let r5 = static_create2_halt_reason(MegaSpecId::REX5, HUGE_INITCODE_LEN); - assert_eq!( - r5, - Some(InstructionResult::MemoryOOG), - "REX5 (sealed) static CREATE2 must still attempt resize_memory! for a hugely oversized \ - initcode and halt with a memory out-of-gas reason, never reaching the static-call \ - rejection; got {r5:?}", - ); -} - -/// Zero-length boundary: a static `CREATE2` with `initcode_len == 0` reports the static rejection -/// on both specs. REX6 halts at the top of the create handler, before the zero-length shortcut -/// runs; REX5 (sealed) takes the shortcut, derives the address, attempts the contract-creation -/// storage charge, and only then reaches the inner opcode's static guard — same reason, different -/// path. The low-gas variant below distinguishes the two paths observably. -#[test] -fn test_create2_static_zero_length_initcode_reports_static_rejection() { - let is_static_reject = |r: Option| { - matches!(r, Some(InstructionResult::StateChangeDuringStaticCall)) - }; - - let r6 = static_create2_halt_reason(MegaSpecId::REX6, 0); - let r5 = static_create2_halt_reason(MegaSpecId::REX5, 0); - - assert!( - is_static_reject(r6), - "REX6 static zero-length CREATE2 must halt with StateChangeDuringStaticCall via the \ - inner opcode's static guard; got {r6:?}", - ); - assert!( - is_static_reject(r5), - "REX5 (sealed) static zero-length CREATE2 halts with StateChangeDuringStaticCall; \ - got {r5:?}", - ); - assert_eq!(r6, r5, "REX6 must match sealed REX5 on the static zero-length CREATE2 halt reason"); -} - -/// Observable split on the zero-length path: with the contract-creation storage charge made -/// nonzero (2× bucket capacity → 32,000 gas) and forwarded gas below it, REX5 (sealed) attempts -/// the charge on its way to the inner opcode and halts out-of-gas — while REX6 halts -/// `StateChangeDuringStaticCall` at the top of the create handler, before the address is derived -/// or the charge is attempted. Pins that the static rejection covers the zero-length shortcut -/// path. -#[test] -fn test_create2_static_zero_length_low_gas_halt_reason() { - let r6 = static_halt_reason_for_bytecode( - MegaSpecId::REX6, - static_create2_bytecode(0), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static zero-length CREATE2 must halt before the contract-creation storage charge; \ - got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode( - MegaSpecId::REX5, - static_create2_bytecode(0), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r5, - Some(InstructionResult::OutOfGas), - "REX5 (sealed) static zero-length CREATE2 must still attempt the contract-creation \ - storage charge first and halt out-of-gas when it cannot afford it; got {r5:?}", - ); -} - -/// The static rejection covers plain `CREATE`, not just `CREATE2`: same low-gas setup as the -/// zero-length test but with a `CREATE(value=0, offset=0, size=0)` callee. REX6 halts -/// `StateChangeDuringStaticCall` before the contract-creation storage charge; REX5 (sealed) -/// derives the address from the creator nonce, attempts the charge, and halts out-of-gas. -#[test] -fn test_create_static_low_gas_halt_reason() { - let create_bytecode = BytecodeBuilder::default() - .push_number(0u64) // size - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE) - .append(STOP) - .build(); - - let r6 = static_halt_reason_for_bytecode( - MegaSpecId::REX6, - create_bytecode.clone(), - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE must halt before the contract-creation storage charge; got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode( - MegaSpecId::REX5, - create_bytecode, - 10_000, - Some(DOUBLED_BUCKET_CAPACITY), - ); - assert_eq!( - r5, - Some(InstructionResult::OutOfGas), - "REX5 (sealed) static CREATE must still attempt the contract-creation storage charge \ - first and halt out-of-gas when it cannot afford it; got {r5:?}", - ); -} - -/// The static rejection precedes operand inspection: a bare `CREATE2` on an empty stack halts -/// `StackUnderflow` on REX5 (sealed — operand inspection runs first) but -/// `StateChangeDuringStaticCall` on REX6, matching canonical revm, whose -/// `require_non_staticcall!` runs before the operand pops. -#[test] -fn test_create2_static_missing_operands_halt_reason() { - let bare_create2 = BytecodeBuilder::default().append(CREATE2).append(STOP).build(); - - let r6 = - static_halt_reason_for_bytecode(MegaSpecId::REX6, bare_create2.clone(), 50_000_000, None); - assert_eq!( - r6, - Some(InstructionResult::StateChangeDuringStaticCall), - "REX6 static CREATE2 with missing operands must halt with the static rejection, not \ - StackUnderflow; got {r6:?}", - ); - - let r5 = static_halt_reason_for_bytecode(MegaSpecId::REX5, bare_create2, 50_000_000, None); - assert_eq!( - r5, - Some(InstructionResult::StackUnderflow), - "REX5 (sealed) static CREATE2 with missing operands halts with StackUnderflow; got {r5:?}", - ); -} - -// Not covered: static + `initcode_len` unrepresentable in `usize`. `static_create2_halt_reason` -// takes a `u64` length, which always fits in `usize` on the 64-bit targets the tests run on, so -// the case cannot be expressed without a raw-`U256` variant of the shared helper. diff --git a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs b/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs deleted file mode 100644 index 00069636d..000000000 --- a/crates/mega-evm/tests/_pending/rex6/eip7702_authority_accounting.rs +++ /dev/null @@ -1,981 +0,0 @@ -//! REX6 regression: consolidated EIP-7702 authorization accounting. -//! -//! REX6 routes every per-authorization effect through one journal-aware scan in `validate`: -//! - net-new authorities are charged dynamic SALT account-creation gas, so a type-4 tx that creates -//! an authority in a heavy SALT bucket consumes more gas than it did pre-REX6; -//! - DataSize/KV are charged only for *applied* authorities (passed the chain-id/nonce/code gates), -//! not every recoverable one, so a skipped authorization no longer inflates resource usage. -//! -//! Pre-REX6 keeps the old split (ungated `before_tx_start` DataSize/KV + pre-execution -//! state-growth scan, no authority SALT gas), frozen for replay parity — the REX5 arms pin it. - -use std::convert::Infallible; - -use alloy_eips::eip7702::{Authorization, RecoveredAuthority, RecoveredAuthorization}; -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - constants, test_utils::MemoryDatabase, BucketHasher, EVMError, EvmTxRuntimeLimits, LimitUsage, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, - SimpleBucketHasher, TestExternalEnvs, ACCOUNT_INFO_WRITE_SIZE, MIN_BUCKET_SIZE, -}; -use revm::{ - context::{ - result::{ExecutionResult, InvalidTransaction, ResultAndState}, - tx::TxEnvBuilder, - BlockEnv, TxEnv, - }, - handler::EvmTr, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -const CALLER: Address = address!("0000000000000000000000000000000000800000"); -const CALLEE: Address = address!("0000000000000000000000000000000000800001"); -const AUTHORITY_A: Address = address!("0000000000000000000000000000000000800010"); -const AUTHORITY_B: Address = address!("0000000000000000000000000000000000800011"); -const DELEGATE: Address = address!("0000000000000000000000000000000000900001"); -/// Used as the block beneficiary in the detention test. -const BENEFICIARY: Address = address!("0000000000000000000000000000000000800099"); - -// ============================================================================ -// TEST CONSTANTS -// ============================================================================ - -/// Multiplier 100 → a net-new account in this bucket costs `base * 99` storage gas; the default -/// bucket has multiplier 1 → 0. The spread is what the SALT-gas test observes. -const HEAVY_MULTIPLIER: u64 = 100; -const HEAVY_CAPACITY: u64 = (MIN_BUCKET_SIZE as u64) * HEAVY_MULTIPLIER; - -// ============================================================================ -// HELPERS -// ============================================================================ - -type Envs = TestExternalEnvs; - -fn no_heavy_buckets() -> Envs { - TestExternalEnvs::new() -} - -fn heavy_bucket_for(address: Address) -> Envs { - let bucket = SimpleBucketHasher::bucket_id(address.as_slice()); - TestExternalEnvs::new().with_bucket_capacity(bucket, HEAVY_CAPACITY) -} - -fn transact_with_limits( - spec: MegaSpecId, - db: &mut MemoryDatabase, - envs: &Envs, - limits: EvmTxRuntimeLimits, - tx: TxEnv, -) -> (ResultAndState, LimitUsage) { - let mut context = - MegaContext::new(db, spec).with_external_envs(envs.into()).with_tx_runtime_limits(limits); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - (r, usage) -} - -/// Runs with the resource limits effectively disabled, so a test observes raw usage / gas rather -/// than a limit halt. -fn transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - envs: &Envs, - tx: TxEnv, -) -> (ResultAndState, LimitUsage) { - let limits = EvmTxRuntimeLimits::from_spec(spec) - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX) - .with_tx_state_growth_limit(u64::MAX); - transact_with_limits(spec, db, envs, limits, tx) -} - -/// Like [`transact`] but returns the raw result, so a validation rejection (e.g. an unaffordable -/// gas requirement) is observable as an `Err` instead of panicking on unwrap. -fn try_transact( - spec: MegaSpecId, - db: &mut MemoryDatabase, - envs: &Envs, - tx: TxEnv, -) -> Result, EVMError> { - let mut context = - MegaContext::new(db, spec).with_external_envs(envs.into()).with_tx_runtime_limits( - EvmTxRuntimeLimits::from_spec(spec) - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX) - .with_tx_state_growth_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -/// A recoverable authorization for `authority` delegating to `DELEGATE`. A nonzero mismatching -/// `chain_id` makes it recoverable but un-appliable (the application gate rejects it). -fn auth(authority: Address, chain_id: u64, nonce: u64) -> RecoveredAuthorization { - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(chain_id), address: DELEGATE, nonce }, - RecoveredAuthority::Valid(authority), - ) -} - -/// An authorization whose signature does not recover to any authority. Skipped by every -/// downstream pass because the recovery gate fails before any account read. -fn auth_unrecoverable(chain_id: u64, nonce: u64) -> RecoveredAuthorization { - RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::from(chain_id), address: DELEGATE, nonce }, - RecoveredAuthority::Invalid, - ) -} - -fn tx_with_auths(auths: Vec) -> TxEnv { - TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(10_000_000) - .authorization_list_recovered(auths) - .build_fill() -} - -fn funded_db() -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000_000_000_000_000u64)) - .account_balance(CALLEE, U256::from(1u64)) -} - -/// Runs `tx` with `BENEFICIARY` as the block beneficiary and a beneficiary-detention compute-gas -/// cap, returning the result and the detained compute-gas limit. -fn transact_detention( - spec: MegaSpecId, - db: &mut MemoryDatabase, - tx_compute_limit: u64, - detention_cap: u64, - tx: TxEnv, -) -> (ResultAndState, u64) { - let block = BlockEnv { beneficiary: BENEFICIARY, ..Default::default() }; - let mut context = MegaContext::new(db, spec).with_block(block).with_tx_runtime_limits( - EvmTxRuntimeLimits::from_spec(spec) - .with_tx_compute_gas_limit(tx_compute_limit) - .with_block_env_access_compute_gas_limit(detention_cap), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); - let detained = evm.ctx_ref().additional_limit.borrow().detained_compute_gas_limit(); - (r, detained) -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// A net-new authority in a heavy SALT bucket costs more gas than one in the default bucket. -/// -/// Both REX6 runs apply the same valid net-new authorization (`chain_id` 1 = tx chain, nonce 0), so -/// they differ only by the dynamic SALT account-creation gas — which only the heavy-bucket run -/// charges. The SALT gas must not bleed into the data-size or KV dimensions. -#[test] -fn test_rex6_new_authority_charges_salt_gas() { - let auths = vec![auth(AUTHORITY_A, 1, 0)]; - - let (res_heavy, u_heavy) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &heavy_bucket_for(AUTHORITY_A), - tx_with_auths(auths.clone()), - ); - let (res_default, u_default) = - transact(MegaSpecId::REX6, &mut funded_db(), &no_heavy_buckets(), tx_with_auths(auths)); - assert!(res_heavy.result.is_success(), "heavy-bucket tx should succeed: {res_heavy:?}"); - assert!(res_default.result.is_success(), "default-bucket tx should succeed: {res_default:?}"); - - // The heavy bucket charges exactly `base * (multiplier - 1)` extra new-account gas. - let expected_salt = constants::rex::NEW_ACCOUNT_STORAGE_GAS_BASE * (HEAVY_MULTIPLIER - 1); - assert_eq!( - res_heavy.result.gas_used() - res_default.result.gas_used(), - expected_salt, - "REX6 must charge exactly the heavy-bucket SALT gas for the new authority", - ); - - // One applied net-new authority is one state-growth unit, and the SALT gas touches neither - // the data-size nor the KV dimension. - assert_eq!(u_heavy.state_growth, 1, "one net-new authority = one state-growth unit"); - assert_eq!(u_heavy.data_size, u_default.data_size, "SALT gas must not affect data size"); - assert_eq!(u_heavy.kv_updates, u_default.kv_updates, "SALT gas must not affect KV"); -} - -/// REX6 *enforces* the net-new authority SALT gas against `gas_limit`, not just accounts for it. -/// -/// The SALT account-creation gas is folded into `initial_gas` before the gas-limit check, so a -/// type-4 tx that cannot afford it is rejected at validation (an `Err`, fees/nonce untouched), not -/// run with a gas-burn halt. A budget that comfortably runs the same authorization in the default -/// bucket is too small once the heavy-bucket SALT (~2.475M) is added. -#[test] -fn test_rex6_authority_salt_gas_enforced_against_gas_limit() { - let auths = vec![auth(AUTHORITY_A, 1, 0)]; - - // Default bucket (SALT = 0): its total gas_used is the budget handed to the heavy run below. It - // sits just above the shared intrinsic and far below intrinsic + heavy SALT. - let (res_default, _) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - tx_with_auths(auths.clone()), - ); - assert!(res_default.result.is_success(), "default-bucket run should succeed: {res_default:?}"); - let default_budget = res_default.result.gas_used(); - - // Same authorization, heavy bucket, but only the default run's budget: the heavy SALT pushes - // initial_gas past gas_limit, so validation rejects before execution. - let tight_tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(default_budget) - .authorization_list_recovered(auths.clone()) - .build_fill(); - let err = - try_transact(MegaSpecId::REX6, &mut funded_db(), &heavy_bucket_for(AUTHORITY_A), tight_tx) - .expect_err("heavy-bucket run under the default budget must be rejected"); - assert!( - matches!( - err, - EVMError::Transaction(MegaTransactionError::Base( - InvalidTransaction::CallGasCostMoreThanGasLimit { .. } - )) - ), - "expected CallGasCostMoreThanGasLimit from the unaffordable SALT gas, got {err:?}", - ); - - // The same heavy run with a budget that covers the SALT succeeds — proving the rejection was - // the SALT gas, not an unrelated shortfall. - let (res_ok, _) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &heavy_bucket_for(AUTHORITY_A), - tx_with_auths(auths), - ); - assert!( - res_ok.result.is_success(), - "heavy-bucket run with enough gas should succeed: {res_ok:?}" - ); -} - -/// A recoverable-but-unapplied authorization writes nothing; only applied authorities are charged. -/// -/// The skipped authorization's `chain_id` (999) mismatches the tx chain (1), so the application -/// gate rejects it. Compared against the same authority with a matching chain id (applied), the -/// applied run charges exactly one account write more: data +40, KV +1, state-growth +1. -#[test] -fn test_rex6_skipped_authority_not_charged_datasize_kv() { - let envs = no_heavy_buckets(); - - let (res_skip, u_skip) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_B, 999, 0)]), - ); - let (res_applied, u_applied) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_B, 1, 0)]), - ); - assert!(res_skip.result.is_success(), "skipped-auth tx should succeed: {res_skip:?}"); - assert!(res_applied.result.is_success(), "applied-auth tx should succeed: {res_applied:?}"); - - assert_eq!(u_skip.state_growth, 0, "a skipped authority creates no state growth"); - assert_eq!(u_applied.state_growth, 1, "an applied net-new authority creates one"); - assert_eq!( - u_applied.data_size - u_skip.data_size, - ACCOUNT_INFO_WRITE_SIZE, - "an applied authority charges exactly one account write more than a skipped one", - ); - assert_eq!( - u_applied.kv_updates - u_skip.kv_updates, - 1, - "an applied authority charges exactly one more KV update than a skipped one", - ); -} - -/// Two sequential-nonce authorizations for the same authority both apply, but create it only once. -/// -/// `[auth(A, nonce 0), auth(A, nonce 1)]`: the first creates A (net-new), the second matches A's -/// simulated nonce and re-delegates it (not net-new). Both are applied, so each charges one account -/// write (data +40, KV +1) — but only the first is state growth. Contrasted with a run whose second -/// authorization is skipped (stale nonce), holding the authorization-record size constant, the -/// duplicate's extra applied write is isolated to exactly one account write and no extra growth. -#[test] -fn test_rex6_duplicate_authority_applies_twice_grows_once() { - let envs = no_heavy_buckets(); - - // Second auth applies: nonce 1 == A's simulated nonce after the first application. - let (res_dup, u_dup) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_A, 1, 1)]), - ); - // Same two-record shape, but the second auth is skipped: stale nonce 99 != simulated nonce 1. - let (res_skip2, u_skip2) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_A, 1, 99)]), - ); - assert!(res_dup.result.is_success(), "duplicate-auth tx should succeed: {res_dup:?}"); - assert!(res_skip2.result.is_success(), "second-skipped tx should succeed: {res_skip2:?}"); - - // The duplicate second application is not new state growth — A is created exactly once either - // way. - assert_eq!(u_dup.state_growth, 1, "a duplicated authority is created once"); - assert_eq!(u_skip2.state_growth, 1, "the applied first authority is created once"); - - // The applied second authorization charges exactly one more account write than the skipped one; - // both lists are length 2, so the authorization-record data size cancels. - assert_eq!( - u_dup.data_size - u_skip2.data_size, - ACCOUNT_INFO_WRITE_SIZE, - "the duplicate's second applied authorization charges one more account write", - ); - assert_eq!( - u_dup.kv_updates - u_skip2.kv_updates, - 1, - "the duplicate's second applied authorization charges one more KV update", - ); - - // Both applications bumped A's nonce; the skipped run applied only the first. - let authority_nonce = |r: &ResultAndState| { - r.state.get(&AUTHORITY_A).map(|a| a.info.nonce).unwrap_or_default() - }; - assert_eq!(authority_nonce(&res_dup), 2, "both authorizations applied: nonce bumped twice"); - assert_eq!(authority_nonce(&res_skip2), 1, "only the first authorization applied: nonce once"); -} - -/// An applied authority that already exists is charged DataSize/KV but is not state growth. -/// -/// Delegating an account that already exists writes it (data +40, KV +1) but creates no net-new -/// state entry. Against a net-new authority — same single applied write — the existing one differs -/// only in the state-growth dimension (0 vs 1). -#[test] -fn test_rex6_existing_authority_charged_but_not_state_growth() { - let envs = no_heavy_buckets(); - - // AUTHORITY_A is pre-funded, so it already exists; AUTHORITY_B does not (net-new). - let mut db_existing = funded_db().account_balance(AUTHORITY_A, U256::from(1u64)); - let (res_existing, u_existing) = transact( - MegaSpecId::REX6, - &mut db_existing, - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - let (res_new, u_new) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_B, 1, 0)]), - ); - assert!( - res_existing.result.is_success(), - "existing-authority tx should succeed: {res_existing:?}" - ); - assert!(res_new.result.is_success(), "net-new-authority tx should succeed: {res_new:?}"); - - // Both applied authorities write their account exactly once: identical DataSize / KV. - assert_eq!( - u_existing.data_size, u_new.data_size, - "an applied authority writes one account either way" - ); - assert_eq!( - u_existing.kv_updates, u_new.kv_updates, - "an applied authority charges one KV update either way" - ); - // Only the net-new authority grows state. - assert_eq!(u_existing.state_growth, 0, "delegating an existing account is not state growth"); - assert_eq!(u_new.state_growth, 1, "delegating a net-new account is state growth"); -} - -/// A net-new authority that overflows the state-growth limit halts the REX6 tx AND is never -/// applied. The halt is a HALT (not `Err`), so `apply_eip7702_auth_list`'s pre-frame `mark_touch` -/// would otherwise persist; the guard skips applying the list. Pins: halt fires, and `AUTHORITY_A` -/// is neither nonce-bumped nor delegated. -#[test] -fn test_rex6_authority_state_growth_overflow_still_halts() { - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - - assert!( - matches!( - &res.result, - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit: 0, actual: 1 }, - .. - } - ), - "REX6 must halt when an applied authority overflows the state-growth limit: {res:?}", - ); - assert_eq!( - usage.state_growth, 1, - "validate()'s accounting still records the attempted authority creation", - ); - assert!( - res.state.get(&CALLEE).is_none_or(|a| !a.is_touched()), - "the first frame must not start once pre-frame state growth already exceeds the limit", - ); - // The account may still show up in `res.state` as a cold LoadedAsNotExisting read-touch from - // `validate()`'s accounting scan — that's not a delegation. The invariant is: not delegated - // (no EIP-7702 code) and not nonce-bumped. - let authority_after = res.state.get(&AUTHORITY_A); - assert!( - authority_after.is_none_or( - |a| a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - ), - "the authorization must NOT be applied once state growth is already known to \ - exceed the limit, got {authority_after:?}", - ); -} - -/// The skip is all-or-nothing: once the tx's authority creations exceed `TX_STATE_GROWTH_LIMIT`, -/// the ENTIRE list is skipped, not just the authority that crossed it. Two net-new authorities, -/// limit 1: both must be left untouched (nonce 0, no delegation), not only the second. -#[test] -fn test_rex6_authority_state_growth_overflow_skips_all_authorities() { - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(1), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_B, 1, 0)]), - ); - - assert!( - matches!( - &res.result, - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit: 1, actual: 2 }, - .. - } - ), - "REX6 must halt when applied authorities overflow the state-growth limit: {res:?}", - ); - assert_eq!( - usage.state_growth, 2, - "validate()'s accounting still records both attempted authority creations", - ); - for authority in [AUTHORITY_A, AUTHORITY_B] { - let after = res.state.get(&authority); - assert!( - after.is_none_or(|a| { - a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - }), - "authority {authority} must not be materialized once state growth already \ - exceeds the limit, got {after:?}", - ); - } -} - -/// Sibling of the overflow tests: a tx whose authority creations stay within the state-growth -/// budget must still apply normally (the state-growth guard must not fire on a non-overflowing tx). -#[test] -fn test_rex6_authority_state_growth_within_limit_still_applies() { - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(1), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - - assert!(res.result.is_success(), "a tx within the state-growth budget must succeed: {res:?}"); - assert_eq!(usage.state_growth, 1, "the single net-new authority is recorded"); - let authority = res.state.get(&AUTHORITY_A).expect("authority update should be preserved"); - assert_eq!(authority.info.nonce, 1, "the authorization must still apply when within budget"); - assert!(authority.info.code.as_ref().is_some_and(|c| c.is_eip7702()), "delegation must be set"); -} - -/// When several dimensions overflow at once, the skip fires regardless of which one the halt -/// reports. Here KV (limit 0) and state growth (limit 1, two net-new authorities) both exceed; KV -/// is checked first so `KVUpdateLimitExceeded` is the reported reason, but the guard — reading the -/// aggregate `has_exceeded_limit` — still skips the whole list and materializes neither authority. -#[test] -fn test_rex6_authority_state_growth_overflow_detected_even_when_kv_limit_reported() { - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(0).with_tx_state_growth_limit(1), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_B, 1, 0)]), - ); - - // KV is checked before StateGrowth in the priority order and its limit (0) is exceeded by - // intrinsic usage alone, so the reported halt reason is KVUpdateLimitExceeded, not - // StateGrowthLimitExceeded — even though state growth (2) also exceeds its own limit (1). - assert!( - matches!( - &res.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - ), - "expected the KV dimension to be the reported halt reason: {res:?}", - ); - assert_eq!(usage.state_growth, 2, "both authority creations are still recorded"); - for authority in [AUTHORITY_A, AUTHORITY_B] { - let after = res.state.get(&authority); - assert!( - after.is_none_or(|a| { - a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - }), - "authority {authority} must not be materialized even though a DIFFERENT \ - dimension (KV) is the reported halt reason, got {after:?}", - ); - } -} - -/// The skip must fire for ANY pre-frame authority-accounting overflow, not just state growth. -/// `on_rex6_eip7702_authority_applied` records a KV + `DataSize` write for *every* applied -/// authority but state growth only for net-new ones — so a tx full of *existing* authorities grows -/// state by 0 yet exceeds a tight `tx_kv_updates_limit`. The guard must still skip the whole list; -/// otherwise those authorities are applied and their pre-frame writes persist past the KV HALT, -/// breaking the per-tx KV limit exactly like the state-growth case. A state-growth-only guard -/// misses this. -#[test] -fn test_rex6_authority_kv_overflow_skips_all_authorities() { - // Both authorities already exist → applying each is 0 state growth but +1 KV update. Two of - // them exceed a KV limit of 1 with no state growth at all. - let mut db = funded_db() - .account_balance(AUTHORITY_A, U256::from(1u64)) - .account_balance(AUTHORITY_B, U256::from(1u64)); - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut db, - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_kv_updates_limit(1), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_B, 1, 0)]), - ); - - assert!( - matches!( - &res.result, - ExecutionResult::Halt { reason: MegaHaltReason::KVUpdateLimitExceeded { .. }, .. } - ), - "existing authorities exceeding the KV limit must halt on KV: {res:?}", - ); - assert_eq!(usage.state_growth, 0, "existing authorities grow no state — only the KV dimension"); - for authority in [AUTHORITY_A, AUTHORITY_B] { - let after = res.state.get(&authority); - assert!( - after.is_none_or(|a| { - a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - }), - "authority {authority} must not be applied on a KV overflow with 0 state growth (the \ - guard must cover KV/DataSize, not just state growth), got {after:?}", - ); - } -} - -/// The fourth pre-frame dimension: `compute_gas`. An applied authority that is the block -/// beneficiary lowers the compute-gas cap (REX4 beneficiary detention) inside -/// `record_rex6_eip7702_authority_accounting`, and the tx's own EIP-7702 intrinsic compute -/// (recorded via `record_compute_gas(initial_gas)` right after) then exceeds that cap — a pre-frame -/// compute overflow with no DataSize/KV/state-growth overflow. The guard must still skip the whole -/// list; a check that enumerated only DataSize/KV/state-growth (or only state-growth) would miss it -/// and let the beneficiary authority persist past the `ComputeGasLimitExceeded` HALT. -#[test] -fn test_rex6_authority_compute_overflow_skips_authorities() { - const TX_COMPUTE_LIMIT: u64 = 200_000_000; - // Detention cap far below the tx's EIP-7702 intrinsic compute (~46k for one authorization). - const TINY_DETENTION_CAP: u64 = 1_000; - - // BENEFICIARY is funded (exists), so `auth(BENEFICIARY, 1, 0)` applies and — being the block - // beneficiary — triggers detention. - let mut db = funded_db().account_balance(BENEFICIARY, U256::from(1u64)); - let tx = TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(10_000_000) - .authorization_list_recovered(vec![auth(BENEFICIARY, 1, 0)]) - .build_fill(); - - let (res, _detained) = - transact_detention(MegaSpecId::REX6, &mut db, TX_COMPUTE_LIMIT, TINY_DETENTION_CAP, tx); - - // The intrinsic compute (~46k) exceeds the detained cap (1k). In this beneficiary-detention - // context that surfaces as `VolatileDataAccessOutOfGas`, but it is the same pre-frame - // compute-over-cap that latches `has_exceeded_limit` — which is what the guard reads. - assert!( - matches!( - &res.result, - ExecutionResult::Halt { reason: MegaHaltReason::VolatileDataAccessOutOfGas { .. }, .. } - ), - "the beneficiary-detention compute overflow must halt: {res:?}", - ); - let after = res.state.get(&BENEFICIARY); - assert!( - after.is_none_or(|a| { - a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - }), - "the beneficiary authority must not be applied on a compute overflow (the guard must cover \ - compute_gas too), got {after:?}", - ); -} - -/// The fourth pre-frame dimension: `data_size`. `on_rex6_eip7702_authority_applied` charges the -/// applied authority's account write (+40) to `data_size` on top of the intrinsic TX base + -/// calldata + authorization-record size that `before_tx_start` already recorded, so a single -/// net-new authority against a tight `tx_data_size_limit` overflows before any frame is pushed — -/// with state growth and KV both comfortably within their (unset) limits. The guard must still -/// skip the whole list; a check that missed the data-size lane would let the authority persist -/// past the `DataLimitExceeded` HALT. -#[test] -fn test_rex6_authority_data_size_overflow_skips_authorities() { - // One applied, net-new authorization: `before_tx_start` records BASE_TX_SIZE (110) + one - // AUTHORIZATION_SIZE record (101) + the caller account update (40) = 251, then - // `on_rex6_eip7702_authority_applied` adds the authority's own account write (40) = 291. A - // limit of 290 makes data size the exceeded dimension. - let (res, usage) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(290), - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - - assert!( - matches!( - &res.result, - ExecutionResult::Halt { - reason: MegaHaltReason::DataLimitExceeded { limit: 290, actual: 291 }, - .. - } - ), - "REX6 must halt when an applied authority overflows the data-size limit: {res:?}", - ); - assert_eq!( - usage.data_size, 291, - "validate()'s accounting still records the attempted authority write", - ); - let authority_after = res.state.get(&AUTHORITY_A); - assert!( - authority_after.is_none_or( - |a| a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - ), - "the authorization must NOT be applied once data size is already known to exceed the \ - limit, got {authority_after:?}", - ); -} - -/// Fee semantics: skipping the whole auth list forgoes the EIP-7702 refund an already-existing -/// authority would have earned (`PER_EMPTY_ACCOUNT_COST - PER_AUTH_BASE_COST` = `12_500`, recorded -/// unconditionally by `post_execution::refund` and subtracted from `gas_used`). -/// -/// Differential: two runs, same two-authority list, both overflow and skip — differing ONLY in -/// whether `AUTHORITY_A` pre-exists (i.e. would be refund-eligible). `gas_used` must be identical; -/// applying the pre-existing authority would drop the existing-`A` run by `12_500`. (Absolute -/// `gas_used` isn't hardcoded — the soft frame-boundary halt charges only spent gas.) -#[test] -fn test_rex6_authority_state_growth_overflow_forgoes_refund() { - let auths = vec![auth(AUTHORITY_A, 1, 0), auth(AUTHORITY_B, 1, 0)]; - let overflow_limits = || EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(0); - - // Run 1: AUTHORITY_A already exists (its application would earn the existing-account refund). - let mut db_existing = funded_db().account_balance(AUTHORITY_A, U256::from(1u64)); - let (res_existing, _) = transact_with_limits( - MegaSpecId::REX6, - &mut db_existing, - &no_heavy_buckets(), - overflow_limits(), - tx_with_auths(auths.clone()), - ); - - // Run 2: AUTHORITY_A does not exist (never refund-eligible). - let (res_fresh, _) = transact_with_limits( - MegaSpecId::REX6, - &mut funded_db(), - &no_heavy_buckets(), - overflow_limits(), - tx_with_auths(auths), - ); - - // Both overflow the zero state-growth limit and halt (existing-A grows by 1 via B; fresh-A by 2 - // via A and B) — the `actual` differs but both exceed the limit. - for (label, res) in [("existing-A", &res_existing), ("fresh-A", &res_fresh)] { - assert!( - matches!( - &res.result, - ExecutionResult::Halt { - reason: MegaHaltReason::StateGrowthLimitExceeded { limit: 0, .. }, - .. - } - ), - "{label} run must halt on the state-growth overflow: {res:?}", - ); - } - - // The whole list is skipped in both, so the pre-existing authority's 12_500 refund is forgone: - // gas_used is identical. Were it applied, only the existing-A run would drop by 12_500. - assert_eq!( - res_existing.result.gas_used(), - res_fresh.result.gas_used(), - "skipping the whole auth list forgoes the pre-existing authority's EIP-7702 refund, so \ - gas_used must not differ on account of A's pre-existence", - ); - - // And the existing authority is not delegated either — the skip is total. - let a_after = res_existing.state.get(&AUTHORITY_A); - assert!( - a_after.is_none_or( - |a| a.info.nonce == 0 && a.info.code.as_ref().is_none_or(|c| !c.is_eip7702()) - ), - "the existing authority must not be delegated, got {a_after:?}", - ); -} - -/// An authority that is also the value-transfer recipient is charged its SALT gas once, not twice. -/// -/// Without REX6's recipient exclusion, both the value-transfer new-account charge and the authority -/// SALT charge would bill the same heavy account creation, doubling a ~3.17M-gas SALT charge. A -/// heavy-bucket value transfer with an authorization that materializes the same recipient is -/// compared against the same transfer without one: the delta stays well under one heavy SALT. -#[test] -fn test_rex6_recipient_authority_not_double_charged() { - let envs = heavy_bucket_for(AUTHORITY_A); - - // Baseline: value transfer to the empty heavy-bucket account, no authorization → the recipient - // new-account branch bills its heavy SALT once. - let no_auth = TxEnvBuilder::default() - .caller(CALLER) - .call(AUTHORITY_A) - .value(U256::from(1)) - .gas_limit(10_000_000) - .build_fill(); - let (res_no_auth, _) = transact(MegaSpecId::REX6, &mut funded_db(), &envs, no_auth); - assert!(res_no_auth.result.is_success(), "no-auth transfer should succeed: {res_no_auth:?}"); - - // Same transfer, but with an authorization that materializes the recipient: REX6 excludes it - // from the value-transfer new-account charge and bills the heavy SALT once via the authority. - let with_auth = TxEnvBuilder::default() - .caller(CALLER) - .call(AUTHORITY_A) - .value(U256::from(1)) - .gas_limit(10_000_000) - .authorization_list_recovered(vec![auth(AUTHORITY_A, 1, 0)]) - .build_fill(); - let (res_with_auth, _) = transact(MegaSpecId::REX6, &mut funded_db(), &envs, with_auth); - assert!( - res_with_auth.result.is_success(), - "with-auth transfer should succeed: {res_with_auth:?}" - ); - - // The with-auth tx adds only authorization overhead (intrinsic + per-auth), well under one - // heavy SALT (~3.17M). A double charge would inflate gas_used by roughly a full heavy SALT. - let delta = res_with_auth.result.gas_used().saturating_sub(res_no_auth.result.gas_used()); - assert!( - delta < 1_000_000, - "the recipient authority's heavy SALT must be charged once, not twice (delta={delta})", - ); -} - -/// An applied authority that is the block beneficiary triggers beneficiary gas detention in REX6. -/// -/// The authority — and neither the caller nor the recipient (`CALLEE`) — is the beneficiary, so -/// only the authority-side marking can detain. REX6 lowers the compute-gas limit to the detention -/// cap; REX5 has no authority-side beneficiary marking, so it does not detain. -#[test] -fn test_rex6_authority_beneficiary_triggers_detention() { - const TX_COMPUTE_LIMIT: u64 = 200_000_000; - const DETENTION_CAP: u64 = 20_000_000; - - // The authority IS the block beneficiary; the caller and recipient (`CALLEE`) are not. - let auths = vec![auth(BENEFICIARY, 1, 0)]; - let tx = || { - TxEnvBuilder::default() - .caller(CALLER) - .call(CALLEE) - .gas_limit(10_000_000) - .authorization_list_recovered(auths.clone()) - .build_fill() - }; - - let (res6, detained6) = transact_detention( - MegaSpecId::REX6, - &mut funded_db(), - TX_COMPUTE_LIMIT, - DETENTION_CAP, - tx(), - ); - let (res5, detained5) = transact_detention( - MegaSpecId::REX5, - &mut funded_db(), - TX_COMPUTE_LIMIT, - DETENTION_CAP, - tx(), - ); - assert!(res6.result.is_success(), "REX6 should succeed: {res6:?}"); - assert!(res5.result.is_success(), "REX5 should succeed: {res5:?}"); - - // REX6 marks beneficiary detention for the applied `authority == beneficiary`, lowering the - // compute-gas limit to the detention cap. - assert!( - detained6 <= DETENTION_CAP, - "REX6 must detain compute gas when an applied authority is the beneficiary (detained6={detained6})", - ); - // REX5 has no authority-side beneficiary marking, so it does not detain. - assert!( - detained5 > DETENTION_CAP, - "REX5 must not detain from an authority (detained5={detained5})", - ); -} - -/// The validate-time scan mirrors the caller-nonce bump, so a self-authorization is accounted -/// exactly as it is applied. -/// -/// On a call tx the caller's nonce is bumped to `tx.nonce + 1` before `apply_eip7702_auth_list` -/// runs, so a self-authorization (`authority == caller`) applies iff its nonce == tx.nonce + 1. The -/// validate-time scan runs before that bump and must mirror it; otherwise the applied/skipped -/// decision and its DataSize/KV accounting diverge from the real application by one. CALLER's -/// account nonce is 0, and `tx_with_auths` builds a tx with nonce 0. -#[test] -fn test_rex6_self_authorization_nonce_matches_application() { - let envs = no_heavy_buckets(); - - let caller_delegated = |res: &ResultAndState| -> bool { - res.state.get(&CALLER).and_then(|a| a.info.code.as_ref()).is_some_and(|c| c.is_eip7702()) - }; - - // auth.nonce == tx.nonce (0) → must NOT apply (the bumped caller nonce is 1). - let (res_skip, u_skip) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(CALLER, 1, 0)]), - ); - assert!(res_skip.result.is_success(), "skip-case tx should succeed: {res_skip:?}"); - assert!(!caller_delegated(&res_skip), "auth.nonce == tx.nonce must NOT apply a self-auth"); - - // auth.nonce == tx.nonce + 1 (1) → must apply. - let (res_apply, u_apply) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(CALLER, 1, 1)]), - ); - assert!(res_apply.result.is_success(), "apply-case tx should succeed: {res_apply:?}"); - assert!(caller_delegated(&res_apply), "auth.nonce == tx.nonce+1 must apply a self-auth"); - - // The scan's accounting must match the application: the applied case charges exactly one more - // authority account write than the skipped case (a mismatched scan would invert the two). - assert_eq!( - u_apply.data_size - u_skip.data_size, - ACCOUNT_INFO_WRITE_SIZE, - "applied self-auth must charge exactly one account write more than the skipped case (apply={} skip={})", - u_apply.data_size, - u_skip.data_size, - ); - assert_eq!( - u_apply.kv_updates - u_skip.kv_updates, - 1, - "applied self-auth charges exactly one more KV update than the skipped case", - ); -} - -/// An authorization whose nonce is `u64::MAX` is skipped by the application gate and charges no -/// per-applied resources, mirroring revm's `2**64 - 1` reject. -/// -/// Compared against the same authority with a matching nonce (applied), the applied run charges -/// exactly one more account write — data +40, KV +1, state-growth +1. Both runs carry the same -/// authorization-record count, so the per-record `AUTHORIZATION_DATA_SIZE` contribution cancels in -/// the diff. -#[test] -fn test_rex6_u64_max_nonce_authority_skipped() { - let envs = no_heavy_buckets(); - - let (res_skip, u_skip) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, u64::MAX)]), - ); - let (res_applied, u_applied) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - assert!(res_skip.result.is_success(), "u64::MAX-nonce tx should succeed: {res_skip:?}"); - assert!(res_applied.result.is_success(), "applied-auth tx should succeed: {res_applied:?}"); - - assert_eq!(u_skip.state_growth, 0, "a u64::MAX-nonce authority creates no state growth"); - assert_eq!(u_applied.state_growth, 1, "an applied net-new authority creates one"); - assert_eq!( - u_applied.data_size - u_skip.data_size, - ACCOUNT_INFO_WRITE_SIZE, - "an applied authority charges exactly one account write more than a u64::MAX-nonce one", - ); - assert_eq!( - u_applied.kv_updates - u_skip.kv_updates, - 1, - "an applied authority charges exactly one more KV update than a u64::MAX-nonce one", - ); -} - -/// An authorization whose signature does not recover to any authority is skipped before any -/// account read and charges no per-applied resources. -/// -/// Compared against an applied authorization (same record count), the applied run charges exactly -/// one more account write. This exercises the recoverability gate independently of the chain-id, -/// nonce, and code gates. -#[test] -fn test_rex6_unrecoverable_authority_skipped() { - let envs = no_heavy_buckets(); - - let (res_skip, u_skip) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth_unrecoverable(1, 0)]), - ); - let (res_applied, u_applied) = transact( - MegaSpecId::REX6, - &mut funded_db(), - &envs, - tx_with_auths(vec![auth(AUTHORITY_A, 1, 0)]), - ); - assert!(res_skip.result.is_success(), "unrecoverable-auth tx should succeed: {res_skip:?}"); - assert!(res_applied.result.is_success(), "applied-auth tx should succeed: {res_applied:?}"); - - assert_eq!(u_skip.state_growth, 0, "an unrecoverable authority creates no state growth"); - assert_eq!(u_applied.state_growth, 1, "an applied net-new authority creates one"); - assert_eq!( - u_applied.data_size - u_skip.data_size, - ACCOUNT_INFO_WRITE_SIZE, - "an applied authority charges exactly one account write more than an unrecoverable one", - ); - assert_eq!( - u_applied.kv_updates - u_skip.kv_updates, - 1, - "an applied authority charges exactly one more KV update than an unrecoverable one", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/error_paths.rs b/crates/mega-evm/tests/_pending/rex6/error_paths.rs deleted file mode 100644 index deb3192f6..000000000 --- a/crates/mega-evm/tests/_pending/rex6/error_paths.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! REX6 CREATE/CREATE2/SSTORE error-path coverage for the unified-metering refactor. -//! -//! The REX6 canonical-metering rewrite of `storage_gas_ext` moved the storage-gas charge of -//! CREATE (`create_rex6`) and SSTORE behind fresh early-return guards, and split CREATE2 operand -//! validation into the shared `compute_created_address` helper. These tests pin the early-return -//! branches that the happy-path parity tests do not reach: -//! -//! - **CREATE storage-gas DB error** (`create_rex6`): `create_contract_storage_gas` returning -//! `None` (a SALT-env failure) must halt with `FatalExternalError` and surface as -//! `EVMError::Custom`, not silently charge zero storage gas. -//! - **SSTORE storage-gas DB error** (`sstore`): the zero→non-zero `sstore_set_storage_gas` failure -//! must do the same. -//! - **CREATE2 operand underflow** (`compute_created_address`): a CREATE2 missing its `offset` or -//! `length` operand must halt with `StackUnderflow` from the wrapper's own `stack.inspect::<1>()` -//! / `inspect::<2>()`, before any memory expansion. - -use std::convert::Infallible; - -use alloy_primitives::{Address, Bytes, TxKind, U256}; -use mega_evm::{ - revm::context::result::ResultAndState, - test_utils::{BytecodeBuilder, MemoryDatabase}, - BucketId, EVMError, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, - MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionError, SaltEnv, -}; -use revm::{ - bytecode::opcode::{CREATE, CREATE2, SSTORE, STOP}, - context::TxEnv, -}; - -use crate::common::{transact_default, CALLER, CONTRACT}; - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// A SALT environment whose `get_bucket_capacity` always fails, so any dynamic storage-gas lookup -/// (`create_contract_storage_gas`, `sstore_set_storage_gas`, …) returns `None` and drives the -/// `FatalExternalError` early-return branch under test. -#[derive(Debug)] -struct FailingSaltEnv; - -impl SaltEnv for FailingSaltEnv { - type Error = String; - - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err("injected salt error".into()) - } - - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } -} - -/// Runs `code` at [`CONTRACT`] under `spec` with a SALT env that fails every bucket lookup, so the -/// first dynamic storage-gas charge surfaces as `EVMError::Custom`. -fn transact_with_failing_salt( - spec: MegaSpecId, - code: Bytes, -) -> Result, EVMError> { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code); - - let envs: ExternalEnvs<(FailingSaltEnv, EmptyExternalEnv)> = - ExternalEnvs { salt_env: FailingSaltEnv, oracle_env: EmptyExternalEnv }; - let mut context = - MegaContext::new(&mut db, spec).with_external_envs(envs).with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_tx_kv_updates_limit(u64::MAX), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let tx = TxEnv { - caller: CALLER, - kind: TxKind::Call(CONTRACT), - data: Bytes::new(), - value: U256::ZERO, - gas_limit: 100_000_000, - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - alloy_evm::Evm::transact_raw(&mut evm, tx) -} - -fn assert_injected_salt_custom_error( - result: Result, EVMError>, -) { - match result { - Err(EVMError::Custom(msg)) => { - assert!( - msg.contains("injected salt error"), - "error should carry the injected SALT failure, got: {msg}" - ); - } - Err(other) => panic!("expected EVMError::Custom, got: {other:?}"), - Ok(result) => panic!("expected a fatal DB-error halt, got success: {:?}", result.result), - } -} - -fn is_stack_underflow(result: &crate::common::Outcome) -> bool { - matches!(&result.result, revm::context::result::ExecutionResult::Halt { reason, .. } - if format!("{reason:?}").contains("StackUnderflow")) -} - -/// CREATE2 with only the `value` operand on the stack must halt with `StackUnderflow` from the -/// wrapper's `stack.inspect::<1>()` (the `offset` operand) inside `compute_created_address`, -/// before any memory expansion. -#[test] -fn test_rex6_create2_missing_offset_stack_underflow() { - // One operand on the stack (value); `offset` is absent. - let code = BytecodeBuilder::default().push_number(0u64).append(CREATE2).append(STOP).build(); - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code); - let outcome = transact_default(MegaSpecId::REX6, db); - - assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); -} - -/// CREATE2 with only `value` and `offset` on the stack must halt with `StackUnderflow` from the -/// wrapper's `stack.inspect::<2>()` (the `length` operand) inside `compute_created_address`. -#[test] -fn test_rex6_create2_missing_length_stack_underflow() { - // Two operands on the stack (offset, value); `length` is absent. - let code = BytecodeBuilder::default() - .push_number(0u64) // offset - .push_number(0u64) // value - .append(CREATE2) - .append(STOP) - .build(); - - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code); - let outcome = transact_default(MegaSpecId::REX6, db); - - assert!(is_stack_underflow(&outcome), "expected StackUnderflow, got {:?}", outcome.result); -} diff --git a/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs b/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs deleted file mode 100644 index e6442557c..000000000 --- a/crates/mega-evm/tests/_pending/rex6/fee_reward_accounting.rs +++ /dev/null @@ -1,567 +0,0 @@ -//! REX6 post-execution fee-reward accounting tests. -//! -//! `op_revm`'s `reward_beneficiary` runs AFTER the `MegaETH` `AdditionalLimit` -//! trackers are finalised at the end of each transaction. It credits up to four -//! accounts: -//! -//! - block beneficiary (coinbase) — priority fee -//! - `BASE_FEE_RECIPIENT` — basefee × `gas_used` -//! - `L1_FEE_RECIPIENT` — L1 data fee -//! - `OPERATOR_FEE_RECIPIENT` — operator fee -//! -//! Each credit that changes a recipient's balance is an account-info write, and a -//! credit to a not-yet-existing recipient materialises the account. Because these -//! writes happen after the per-frame limit accounting is finalised, REX6 records -//! them directly on the transaction-level lane: `data_size` gains one account-info -//! write and `kv_updates` gains 1 for every recipient whose balance changes, plus -//! `state_growth` gains 1 for every recipient that is newly materialised. Pre-REX6 -//! specs record none of this (frozen for replay parity). -//! -//! These tests pin each half of that behaviour and the pre-REX6 freeze. - -use std::convert::Infallible; - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, - EmptyExternalEnv, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, ACCOUNT_INFO_WRITE_SIZE, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, -}; -use op_revm::constants::BASE_FEE_RECIPIENT; -use revm::{ - bytecode::opcode::*, - context::{ - result::{EVMError, ResultAndState}, - BlockEnv, ContextSetters, TxEnv, - }, - handler::EvmTr, - primitives::TxKind, -}; - -// ============================================================================ -// TEST ADDRESSES -// ============================================================================ - -/// A well-funded EOA sender for the normal (non-deposit) transaction. -const CALLER: Address = address!("00000000000000000000000000000000C0DE0001"); - -/// A simple callee contract that just RETURNs immediately. -const TARGET_CONTRACT: Address = address!("00000000000000000000000000000000C0DE0002"); - -/// Coinbase / block beneficiary address. -const COINBASE: Address = address!("00000000000000000000000000000000C0FFEE01"); - -// ============================================================================ -// CONSTANTS -// ============================================================================ - -/// Block base-fee (in wei). Setting `gas_price == BASEFEE` means the priority -/// fee to the coinbase is zero, so the only fee-vault credit on this path is -/// `BASE_FEE_RECIPIENT ← basefee × gas_used`. -const BASEFEE: u64 = 1_000_000; - -/// Gas limit for the test transaction — large enough to comfortably cover the -/// `MegaETH` REX intrinsic (60 k) plus the trivial RETURN contract execution. -const TX_GAS_LIMIT: u64 = 1_000_000; - -/// Caller starting balance (1 ETH) — enough to cover `gas_limit × gas_price`. -const CALLER_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH - -// ============================================================================ -// HARNESS HELPERS -// ============================================================================ - -type TestEvm = MegaEvm; -type TestEvmResult = - Result, EVMError>; - -/// Deploys a trivial `RETURN` bytecode at `TARGET_CONTRACT`. -fn simple_return_contract() -> Bytes { - BytecodeBuilder::default().push_number(0u64).push_number(0u64).append(RETURN).build() -} - -/// Builds a `MegaEvm` for the given `spec` with the given database and `basefee`. -/// -/// - Block: `gas_limit = 1_000_000_000`, `basefee = basefee`, `beneficiary = COINBASE`. -/// - Chain: operator-fee scalar and constant zeroed so `OPERATOR_FEE_RECIPIENT` receives no credit -/// and cannot accidentally materialise. -fn build_evm(spec: MegaSpecId, db: MemoryDatabase, basefee: u64) -> TestEvm { - let mut context = MegaContext::new(db, spec); - context.set_block(BlockEnv { - gas_limit: 1_000_000_000, - basefee, - beneficiary: COINBASE, - ..Default::default() - }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -/// Constructs the normal (non-deposit) `Call` transaction used in both runs. -/// -/// `gas_price == BASEFEE`: the priority-fee tip to coinbase is zero, but -/// `BASE_FEE_RECIPIENT` is credited `basefee × gas_used > 0` — which -/// materialises it when the account is absent from the DB. -fn make_call_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: CALLER, - kind: TxKind::Call(TARGET_CONTRACT), - gas_limit: TX_GAS_LIMIT, - gas_price: BASEFEE as u128, - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Executes `tx` against `db`, pinned to REX6 + BASEFEE. Delegates to `transact_with_spec`. -fn transact_with(db: MemoryDatabase, tx: MegaTransaction) -> (TestEvmResult, TestEvm) { - transact_with_spec(MegaSpecId::REX6, db, BASEFEE, tx) -} - -/// Generic variant: executes `tx` against `db` under the given `spec` and `basefee`. -fn transact_with_spec( - spec: MegaSpecId, - db: MemoryDatabase, - basefee: u64, - tx: MegaTransaction, -) -> (TestEvmResult, TestEvm) { - let mut evm = build_evm(spec, db, basefee); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx); - (r, evm) -} - -/// A transaction with a 1-wei priority fee so the block beneficiary receives a non-zero -/// credit: `effective_gas_price = BASEFEE + 1` → `coinbase_gas_price = 1` → `1 × gas_used`. -fn make_tip_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: CALLER, - kind: TxKind::Call(TARGET_CONTRACT), - gas_limit: TX_GAS_LIMIT, - gas_price: BASEFEE as u128 + 1, - gas_priority_fee: Some(1), - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// An OP deposit-style transaction. A non-zero `source_hash` flips `tx_type` to deposit, and -/// op-revm's `reward_beneficiary` early-returns for deposits — so no fee recipient is credited. -fn make_deposit_tx() -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: CALLER, - kind: TxKind::Call(TARGET_CONTRACT), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - ..Default::default() - }, - ..Default::default() - }; - tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - tx.deposit.mint = Some(0); - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Builds a REX6 EVM with a custom block `beneficiary` (the standard `build_evm` hardcodes -/// `COINBASE`), runs `tx`, asserts success, and returns the EVM for usage inspection. Used to -/// exercise the recipient dedup when the beneficiary coincides with a fee vault. -fn transact_rex6_with_beneficiary( - db: MemoryDatabase, - beneficiary: Address, - tx: MegaTransaction, -) -> TestEvm { - let mut context = MegaContext::new(db, MegaSpecId::REX6); - context.set_block(BlockEnv { - gas_limit: 1_000_000_000, - basefee: BASEFEE, - beneficiary, - ..Default::default() - }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - let mut evm = MegaEvm::new(context); - let res = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!( - res.expect("tx must not produce a validation error").result.is_success(), - "tx must succeed", - ); - evm -} - -// ============================================================================ -// TESTS -// ============================================================================ - -/// REX6: materialising `BASE_FEE_RECIPIENT` inside `reward_beneficiary` records -/// exactly +1 `state_growth` compared with a run where the account already exists. -/// The credit runs after the `AdditionalLimit` snapshot, so the new-account event -/// is recorded on the transaction-level lane rather than via a frame. -#[test] -fn test_rex6_fee_recipient_materialization_records_state_growth() { - // --- Run A: BASE_FEE_RECIPIENT absent from the DB --------------------------- - // The first basefee credit will materialise an empty account → should record - // +1 state_growth under REX6. - let db_empty = MemoryDatabase::default() - // Fund CALLER enough to pay gas: gas_limit × gas_price - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - // Install the trivial RETURN contract - .account_code(TARGET_CONTRACT, simple_return_contract()); - - let tx_empty = make_call_tx(); - let (res_empty, evm_empty) = transact_with(db_empty, tx_empty); - assert!( - res_empty.expect("run A must not produce a validation error").result.is_success(), - "run A (empty BASE_FEE_RECIPIENT): tx must succeed", - ); - let growth_empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - // --- Run B: BASE_FEE_RECIPIENT pre-funded (already exists) ------------------ - // The basefee credit lands on an existing account → no new account created → - // state_growth should be one less than run A (once the fix is in). - let db_funded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - // Pre-seed BASE_FEE_RECIPIENT so it already exists before the tx runs. - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)); - - let tx_funded = make_call_tx(); - let (res_funded, evm_funded) = transact_with(db_funded, tx_funded); - assert!( - res_funded.expect("run B must not produce a validation error").result.is_success(), - "run B (pre-funded BASE_FEE_RECIPIENT): tx must succeed", - ); - let growth_funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage().state_growth; - - // The empty run must record exactly +1 more state_growth than the funded run. - // Before the REX6 fix this FAILS with: left=0, right=1 - assert_eq!( - growth_empty.saturating_sub(growth_funded), - 1, - "materialising BASE_FEE_RECIPIENT in reward_beneficiary must record exactly \ - +1 state_growth vs the pre-funded baseline \ - (empty={growth_empty}, funded={growth_funded})", - ); -} - -// ============================================================================ -// DataSize / KV account-info-write isolation -// ============================================================================ - -/// REX6: every time a fee recipient's balance changes, `reward_beneficiary` -/// must record an account-info write of `+40` `data_size` and `+1` `kv_updates`. -/// -/// Strategy: hold `state_growth` constant by pre-funding `BASE_FEE_RECIPIENT` in -/// both runs, then vary only whether the recipient *receives* a non-zero credit: -/// -/// - **Credited run**: `basefee = BASEFEE`, `gas_price = BASEFEE` → base-fee credit is `> 0`, so -/// `BASE_FEE_RECIPIENT`'s balance changes → account-info write is charged. -/// - **Baseline run**: `basefee = 0`, `gas_price = 0` → base-fee credit is `0`, balance unchanged → -/// no account-info write. -/// -/// Expected delta: `credited.data_size - baseline.data_size == 40` and -/// `credited.kv_updates - baseline.kv_updates == 1`. -#[test] -fn test_rex6_fee_recipient_records_data_size_and_kv() { - // Common DB builder that pre-funds BASE_FEE_RECIPIENT so state_growth is equal - // in both runs (no new-account materialisation either way). - let funded_db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)) - }; - - // --- Credited run: basefee = BASEFEE, gas_price = BASEFEE → base-fee credit > 0 --- - let (res_credited, evm_credited) = - transact_with_spec(MegaSpecId::REX6, funded_db(), BASEFEE, make_call_tx()); - assert!( - res_credited.expect("credited run must not produce a validation error").result.is_success(), - "credited run: tx must succeed", - ); - let credited = evm_credited.ctx_ref().additional_limit.borrow().get_usage(); - - // --- Baseline run: basefee = 0, gas_price = 0 → base-fee credit is 0, no write --- - let mut tx_zero_price = make_call_tx(); - tx_zero_price.base.gas_price = 0; - let (res_baseline, evm_baseline) = - transact_with_spec(MegaSpecId::REX6, funded_db(), 0, tx_zero_price); - assert!( - res_baseline.expect("baseline run must not produce a validation error").result.is_success(), - "baseline run: tx must succeed", - ); - let baseline = evm_baseline.ctx_ref().additional_limit.borrow().get_usage(); - - assert_eq!( - credited.data_size.saturating_sub(baseline.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "crediting BASE_FEE_RECIPIENT must add exactly {ACCOUNT_INFO_WRITE_SIZE} data_size \ - (credited={}, baseline={})", - credited.data_size, - baseline.data_size, - ); - assert_eq!( - credited.kv_updates.saturating_sub(baseline.kv_updates), - 1, - "crediting BASE_FEE_RECIPIENT must add exactly 1 kv_update \ - (credited={}, baseline={})", - credited.kv_updates, - baseline.kv_updates, - ); -} - -// ============================================================================ -// Beneficiary (priority-fee) materialisation -// ============================================================================ - -/// REX6: when the block beneficiary (coinbase) receives a non-zero -/// priority-fee tip and its account did not previously exist, `reward_beneficiary` -/// must record `+1 state_growth` (new-account materialisation) while -/// `data_size` stays equal between the empty and pre-funded cases (both runs -/// credit the coinbase, so both incur the `+40` account-info write; only the -/// first-time materialisation differs). -/// -/// Tx config: EIP-1559 style with `gas_price = BASEFEE + 1` and -/// `gas_priority_fee = Some(1)` → `effective_gas_price = BASEFEE + 1` → -/// `coinbase_gas_price = 1` → coinbase receives `1 × gas_used > 0`. -/// -/// `BASE_FEE_RECIPIENT` is pre-funded in both runs so it does not contribute -/// differing `state_growth`. -#[test] -fn test_rex6_beneficiary_tip_materialization_records_accounting() { - // Pre-fund BASE_FEE_RECIPIENT in both runs so it never contributes differing - // state_growth. The only variable is whether COINBASE is empty or pre-funded. - let base_db_funded_bfr = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)) - }; - - // --- Empty COINBASE run: COINBASE does not yet exist → materialised on credit --- - let (res_empty, evm_empty) = - transact_with_spec(MegaSpecId::REX6, base_db_funded_bfr(), BASEFEE, make_tip_tx()); - assert!( - res_empty - .expect("empty-coinbase run must not produce a validation error") - .result - .is_success(), - "empty-coinbase run: tx must succeed", - ); - let empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - // --- Pre-funded COINBASE run: COINBASE already exists → no materialisation --- - let db_funded_coinbase = base_db_funded_bfr().account_balance(COINBASE, U256::from(1u64)); - let (res_funded, evm_funded) = - transact_with_spec(MegaSpecId::REX6, db_funded_coinbase, BASEFEE, make_tip_tx()); - assert!( - res_funded - .expect("funded-coinbase run must not produce a validation error") - .result - .is_success(), - "funded-coinbase run: tx must succeed", - ); - let funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - // Materialising COINBASE adds exactly +1 state_growth. - assert_eq!( - empty.state_growth.saturating_sub(funded.state_growth), - 1, - "materialising COINBASE must add exactly +1 state_growth \ - (empty={}, funded={})", - empty.state_growth, - funded.state_growth, - ); - - // Both runs credit COINBASE a non-zero tip, so both charge the +40 account-info - // write; data_size must be identical (the materialisation delta is captured by - // state_growth, not an extra data_size charge). - assert_eq!( - empty.data_size, funded.data_size, - "data_size must be equal when only COINBASE materialisation differs \ - (empty={}, funded={})", - empty.data_size, funded.data_size, - ); - assert_eq!( - empty.kv_updates, funded.kv_updates, - "both runs credit the coinbase a non-zero tip → both charge +1 kv_update; only state_growth differs", - ); -} - -// ============================================================================ -// REX5 freeze guard -// ============================================================================ - -// ============================================================================ -// Recipient dedup (beneficiary coincides with a fee vault) -// ============================================================================ - -/// REX6: when the block beneficiary coincides with a fee vault, op-revm issues two -/// `balance_incr`s to the SAME on-chain account (the tip as beneficiary + the base fee as -/// vault) — but that is still a single account write. The recipient dedup must collapse it to -/// one charge, not double-count. -/// -/// Strategy: compare a collision run (beneficiary == `BASE_FEE_RECIPIENT`) against a distinct -/// run (beneficiary == `COINBASE`). Both use a tip tx under `basefee > 0` with both accounts -/// empty, so the distinct run materialises TWO accounts while the collision run materialises -/// ONE. The distinct run must therefore record exactly one more account write. Without dedup, -/// the collision run would also count two and these deltas would be zero. -#[test] -fn test_rex6_beneficiary_equal_to_fee_vault_is_counted_once() { - let db = || { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - }; - - // Collision: beneficiary == BASE_FEE_RECIPIENT → both credits hit one empty account. - let collide = transact_rex6_with_beneficiary(db(), BASE_FEE_RECIPIENT, make_tip_tx()) - .ctx_ref() - .additional_limit - .borrow() - .get_usage(); - - // Distinct: beneficiary == COINBASE (≠ BASE_FEE_RECIPIENT) → two empty accounts credited. - let distinct = transact_rex6_with_beneficiary(db(), COINBASE, make_tip_tx()) - .ctx_ref() - .additional_limit - .borrow() - .get_usage(); - - assert_eq!( - distinct.state_growth.saturating_sub(collide.state_growth), - 1, - "beneficiary == fee vault must materialise one account, not two \ - (collide={}, distinct={})", - collide.state_growth, - distinct.state_growth, - ); - assert_eq!( - distinct.data_size.saturating_sub(collide.data_size), - ACCOUNT_INFO_WRITE_SIZE, - "collision must record one account-info write, not two (collide={}, distinct={})", - collide.data_size, - distinct.data_size, - ); - assert_eq!( - distinct.kv_updates.saturating_sub(collide.kv_updates), - 1, - "collision must record one kv_update, not two (collide={}, distinct={})", - collide.kv_updates, - distinct.kv_updates, - ); -} - -// ============================================================================ -// Deposit transactions record no fee-recipient accounting -// ============================================================================ - -/// REX6: deposit transactions credit no fee recipient — op-revm's `reward_beneficiary` -/// early-returns for deposits — so the fee-reward accounting records nothing. An empty vs -/// pre-funded `BASE_FEE_RECIPIENT` must produce identical usage even with `basefee > 0`. This -/// pins the "no special-casing needed" property against op-revm behavior drift. -#[test] -fn test_rex6_deposit_tx_records_no_fee_recipient_accounting() { - // CALLER is pre-funded (non-empty) in both runs so the deposit-caller path contributes no - // differing state growth; the only variable is BASE_FEE_RECIPIENT presence. - let db_empty = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let (res_empty, evm_empty) = - transact_with_spec(MegaSpecId::REX6, db_empty, BASEFEE, make_deposit_tx()); - assert!( - res_empty - .expect("deposit empty run must not produce a validation error") - .result - .is_success(), - "deposit empty run: tx must succeed", - ); - let empty = evm_empty.ctx_ref().additional_limit.borrow().get_usage(); - - let db_funded = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()) - .account_balance(BASE_FEE_RECIPIENT, U256::from(1u64)); - let (res_funded, evm_funded) = - transact_with_spec(MegaSpecId::REX6, db_funded, BASEFEE, make_deposit_tx()); - assert!( - res_funded - .expect("deposit funded run must not produce a validation error") - .result - .is_success(), - "deposit funded run: tx must succeed", - ); - let funded = evm_funded.ctx_ref().additional_limit.borrow().get_usage(); - - assert_eq!( - empty.state_growth, funded.state_growth, - "deposit tx must record no fee-recipient state_growth (empty={}, funded={})", - empty.state_growth, funded.state_growth, - ); - assert_eq!( - empty.data_size, funded.data_size, - "deposit tx must record no fee-recipient data_size (empty={}, funded={})", - empty.data_size, funded.data_size, - ); - assert_eq!( - empty.kv_updates, funded.kv_updates, - "deposit tx must record no fee-recipient kv_updates (empty={}, funded={})", - empty.kv_updates, funded.kv_updates, - ); -} - -// ============================================================================ -// DB-error path on a fee-recipient read -// ============================================================================ - -/// REX6: a database failure while reading a fee recipient in `reward_beneficiary` must -/// surface as `EVMError::Custom` (the `inspect_account` `map_err` wrap), not be silently -/// dropped. The pre-reward snapshot reads `BASE_FEE_RECIPIENT`; injecting a DB failure there -/// exercises the error path. -#[test] -fn test_rex6_fee_recipient_db_error_surfaces_as_custom() { - let inner = MemoryDatabase::default() - .account_balance(CALLER, U256::from(CALLER_BALANCE)) - .account_code(TARGET_CONTRACT, simple_return_contract()); - let mut db = ErrorInjectingDatabase::new(inner); - // The reward snapshot's `inspect_account(BASE_FEE_RECIPIENT)` read fails. - db.fail_on_account = Some(BASE_FEE_RECIPIENT); - - let mut context = MegaContext::new(db, MegaSpecId::REX6); - context.set_block(BlockEnv { - gas_limit: 1_000_000_000, - basefee: BASEFEE, - beneficiary: COINBASE, - ..Default::default() - }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let mut evm = MegaEvm::new(context); - let res = alloy_evm::Evm::transact_raw(&mut evm, make_call_tx()); - - match res { - Err(EVMError::Custom(msg)) => assert!( - msg.contains("Failed to inspect fee recipient"), - "expected the fee-recipient inspect_account DB error to be wrapped, got: {msg}", - ), - other => panic!( - "expected EVMError::Custom for fee-recipient inspect_account DB error, got {other:?}", - ), - } -} diff --git a/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs b/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs deleted file mode 100644 index 1a9e95c14..000000000 --- a/crates/mega-evm/tests/_pending/rex6/frame_local_accounting.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! REX6 frame-local accounting fixes, each with a REX5 freeze guard: -//! -//! - per-log base overhead in `after_log`: an empty `LOG0` is no longer free in the `data_size` -//! lane (pre-REX6 charges no per-log base); -//! - a compute-limit halt at a CALL/CREATE — whether the frame-local `Revert` or the tx-level -//! detained `OutOfGas` branch — returns the forwarded gas to the parent instead of swallowing it -//! into `gas_used` (pre-REX6 leaves it swallowed). - -use crate::common::{transact, transact_default, CALLER, CONTRACT}; -use alloy_primitives::{Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, MegaSpecId, -}; -use revm::{ - bytecode::opcode::{CALL, CREATE, LOG0, LOG1, POP, TIMESTAMP}, - context::result::ExecutionResult, -}; - -const ONE_ETH: u128 = 1_000_000_000_000_000_000; - -/// The per-log base overhead added under REX6: one 32-byte value unit for the log address -/// persisted in every receipt log object regardless of topic count or data length. Mirrors the -/// `mega_evm::limit::data_size::LOG_BASE_SIZE` constant introduced by the fix. -const LOG_BASE_SIZE: u64 = 32; - -fn base_db(code: Bytes) -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) -} - -// --------------------------------------------------------------------------- -// Per-log base overhead -// --------------------------------------------------------------------------- - -/// `LOG0(0,0)` bytecode: push len=0, push offset=0, LOG0, STOP. -fn log0_empty_code() -> Bytes { - BytecodeBuilder::default() - .push_number(0u64) // len - .push_number(0u64) // offset - .append(LOG0) - .stop() - .build() -} - -#[test] -fn test_rex6_log0_empty_charges_base_overhead_vs_rex5() { - let code = log0_empty_code(); - let r5 = transact_default(MegaSpecId::REX5, base_db(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, base_db(code)); - assert!(r5.is_success() && r6.is_success(), "both must succeed"); - // REX6 charges exactly one per-log base overhead more than the frozen REX5 reading. - assert_eq!( - r6.data_size, - r5.data_size + LOG_BASE_SIZE, - "REX6 LOG0(0,0) must add LOG_BASE_SIZE ({LOG_BASE_SIZE}) over REX5; r5={} r6={}", - r5.data_size, - r6.data_size, - ); -} - -#[test] -fn test_rex6_log1_with_data_base_plus_topics_plus_data() { - // LOG1 with 32 bytes of data: REX6 = REX5 + LOG_BASE_SIZE (one log → one base overhead); the - // topic (32) + data (32) component is identical across specs. - let code = BytecodeBuilder::default() - .mstore(0, [0x11u8; 32]) - .push_number(0xabcu64) // topic0 - .push_number(32u64) // len - .push_number(0u64) // offset - .append(LOG1) - .stop() - .build(); - let r5 = transact_default(MegaSpecId::REX5, base_db(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, base_db(code)); - assert!(r5.is_success() && r6.is_success(), "both must succeed"); - assert_eq!( - r6.data_size, - r5.data_size + LOG_BASE_SIZE, - "REX6 LOG1 must add exactly one LOG_BASE_SIZE over REX5; r5={} r6={}", - r5.data_size, - r6.data_size, - ); -} - -// --------------------------------------------------------------------------- -// Forwarded gas returned on a frame-local compute-limit abort at a CALL -// --------------------------------------------------------------------------- - -/// A CALL target that has code (a bare STOP) so revm builds a child `NewFrame` and forwards gas -/// to it — the precondition for the gas swallow. Distinct from `EMPTY_TARGET` (no code), which -/// resolves immediately with no pending frame. -const CALL_TARGET: alloy_primitives::Address = - alloy_primitives::address!("0000000000000000000000000000000000200003"); - -/// DB where [`CONTRACT`] performs a value-free CALL to a code-bearing target, forwarding (almost) -/// all remaining gas. The CALL is the first compute-significant opcode. -fn compute_abort_db() -> MemoryDatabase { - let call_code = BytecodeBuilder::default() - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(CALL_TARGET) // to - .push_number(100_000_000u64) // gas (revm caps to 98/100 of remaining) - .append(CALL) - .stop() - .build(); - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, call_code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) - .account_code(CALL_TARGET, BytecodeBuilder::default().stop().build()) -} - -/// `no_limits()` except a tight compute-gas budget that the CALL's own compute overhead (cold -/// account access) overruns — firing a frame-local compute-limit halt while the child `NewFrame` -/// is pending and its forwarded gas already deducted. -fn tight_compute_limits() -> EvmTxRuntimeLimits { - let mut limits = EvmTxRuntimeLimits::no_limits(); - limits.tx_compute_gas_limit = 22_000; - limits -} - -/// DB where [`CONTRACT`] performs a `CREATE` with a one-byte init code, forwarding gas to the init -/// frame. The `CREATE` is the first compute-significant opcode, so its compute overhead overruns -/// the tight budget while the child `NewFrame(Create)` is pending and its forwarded gas deducted. -fn compute_abort_create_db() -> MemoryDatabase { - // memory[0] = 0x00 (STOP) → a one-byte init code that deploys empty runtime. - let create_code = BytecodeBuilder::default() - .mstore(0, [0x00u8; 32]) - .push_number(1u64) // init code size - .push_number(0u64) // init code offset - .push_number(0u64) // value - .append(CREATE) - .stop() - .build(); - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, create_code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) -} - -/// DB where [`CONTRACT`] accesses volatile block env (`TIMESTAMP`) to arm a relative compute-gas -/// detention cap, then performs a gas-forwarding CALL to a code-bearing target. With a tight -/// detention cap and a large per-frame budget, the CALL's own compute overshoots the *tx-level* -/// (detained) compute limit while the frame-local budget still has room — so the compute halt is -/// the tx-level `OutOfGas` branch, not the frame-local `Revert` branch exercised above. -fn tx_level_detained_abort_db() -> MemoryDatabase { - let code = BytecodeBuilder::default() - .append(TIMESTAMP) // volatile access → arms the relative detention cap - .append(POP) - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(0u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(CALL_TARGET) // to - .push_number(100_000_000u64) // gas (revm caps to 98/100 of remaining) - .append(CALL) - .stop() - .build(); - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10 * ONE_ETH)) - .account_code(CONTRACT, code) - .account_balance(CONTRACT, U256::from(ONE_ETH)) - .account_code(CALL_TARGET, BytecodeBuilder::default().stop().build()) -} - -/// A huge per-frame compute budget (so the frame-local limit never binds) paired with a tight -/// detention cap (so after the volatile access the tx-level detained limit is what the CALL trips). -fn tx_level_detention_limits() -> EvmTxRuntimeLimits { - let mut limits = EvmTxRuntimeLimits::no_limits(); - limits.tx_compute_gas_limit = 100_000_000; - limits.block_env_access_compute_gas_limit = 1_000; - limits -} - -#[test] -fn test_rex6_two_logs_charge_two_base_overheads() { - // Two LOG0(0,0) → two per-log base overheads under REX6. - let code = BytecodeBuilder::default() - .push_number(0u64) - .push_number(0u64) - .append(LOG0) - .push_number(0u64) - .push_number(0u64) - .append(LOG0) - .stop() - .build(); - let r5 = transact_default(MegaSpecId::REX5, base_db(code.clone())); - let r6 = transact_default(MegaSpecId::REX6, base_db(code)); - assert!(r5.is_success() && r6.is_success(), "both must succeed"); - assert_eq!( - r6.data_size, - r5.data_size + 2 * LOG_BASE_SIZE, - "REX6 two LOG0 must add 2*LOG_BASE_SIZE over REX5; r5={} r6={}", - r5.data_size, - r6.data_size, - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs b/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs deleted file mode 100644 index 2191f405c..000000000 --- a/crates/mega-evm/tests/_pending/rex6/keyless_sandbox_hardening.rs +++ /dev/null @@ -1,383 +0,0 @@ -//! REX6 `KeylessDeploy` sandbox hardening tests. -//! -//! Covers two behavioral changes in `sandbox/execution.rs`: -//! -//! - **Keyless overhead OOG rescue.** When the keyless dispatch overhead -//! (`KEYLESS_DEPLOY_OVERHEAD_GAS`) pushes the `AdditionalLimit` compute-gas tracker over its -//! tx-level cap, `execute_keyless_deploy_call` halts with a full-spend OOG. REX6+ routes through -//! `AdditionalLimit::try_rescue_gas` so the unused outer-gas remainder is refunded; pre-REX6 -//! leaves it fully spent. -//! -//! - **Create-then-SELFDESTRUCT detection.** Pre-REX6 `process_sandbox_transact_result` treats -//! non-empty `Output::Create(bytecode, addr)` as a successful deploy without checking whether the -//! sandbox-state account at `addr` was marked `SelfDestructed`. -//! `apply_sandbox_created_selfdestruct` then zeroes that account on merge, so the wire-reported -//! `deployedAddress` points at an account with no on-chain code. REX6+ folds the -//! create-then-selfdestruct case onto the same empty-code branch as `bytecode.is_empty()`. -//! -//! REX5 baselines are included so each fix is shown to actually move -//! behavior. Pre-REX6 dispatch paths are unchanged (REX5 204-test suite -//! freezes them). - -use std::vec::Vec; - -use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::SolCall; -use mega_evm::{ - alloy_consensus::{Signed, TxLegacy}, - revm::context::result::ExecutionResult, - sandbox::{calculate_keyless_deploy_address, decode_error_result, KeylessDeployError}, - test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, IKeylessDeploy, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - MegaTransaction, TestExternalEnvs, KEYLESS_DEPLOY_ADDRESS, -}; -use revm::{ - bytecode::opcode::{DELEGATECALL, MSTORE8, POP, RETURN, SELFDESTRUCT}, - context::TxEnv, - inspector::NoOpInspector, -}; - -const RELAYER: Address = address!("0000000000000000000000000000000000990000"); -const SIGNED_GAS_PRICE: u128 = 100_000_000_000; -const SIGNED_GAS_LIMIT: u64 = 100_000; -const OUTER_GAS_LIMIT: u64 = 30_000_000; -const LARGE_GAS_LIMIT_OVERRIDE: u64 = 10_000_000_000; -/// Helper contract used by the create-then-SELFDESTRUCT test — -/// invokes `SELFDESTRUCT(0)` so a DELEGATECALL from a constructor -/// destroys the constructor's own (being-created) account. -const SELFDESTRUCT_HELPER: Address = address!("00000000000000000000000000000000000abcde"); - -// ============================================================================ -// HELPERS -// ============================================================================ - -/// Builds a deterministic pre-EIP-155 keyless tx with the given init code. -/// Mirrors the helper in `tests/rex5/keyless_empty_code_logs.rs`. -fn build_keyless_tx_with_init_code(init_code: Bytes) -> (Bytes, Address) { - let tx = TxLegacy { - nonce: 0, - gas_price: SIGNED_GAS_PRICE, - gas_limit: SIGNED_GAS_LIMIT, - to: TxKind::Create, - value: U256::ZERO, - input: init_code, - chain_id: None, - }; - let r = U256::from_be_bytes(hex!( - "3333333333333333333333333333333333333333333333333333333333333333" - )); - let s = U256::from_be_bytes(hex!( - "3333333333333333333333333333333333333333333333333333333333333333" - )); - let sig = Signature::new(r, s, false); - let signed = Signed::new_unchecked(tx, sig, B256::ZERO); - let mut buf = Vec::new(); - signed.rlp_encode(&mut buf); - let tx_bytes = Bytes::from(buf); - let signer = signed.recover_signer().expect("should recover signer"); - (tx_bytes, signer) -} - -/// Runs the outer `keylessDeployCall` and returns the parent `ExecutionResult`. -/// -/// `tx_compute_gas_limit` lets the overhead-OOG test squeeze the -/// `AdditionalLimit` compute-gas tracker below `KEYLESS_DEPLOY_OVERHEAD_GAS` -/// so the tx-level exceed path fires inside `execute_keyless_deploy_call`'s -/// dispatch-overhead charge. -/// -/// `outer_gas_limit_override` lets tests that need to exercise behavior past -/// the default `OUTER_GAS_LIMIT` (e.g., the EIP-170 size-limit invariant test -/// which needs enough gas for a 512KB+ `CODE_DEPOSIT_COST` charge) widen the -/// envelope. `None` defaults to `OUTER_GAS_LIMIT`. -fn run_keyless_outer( - spec: MegaSpecId, - db: &mut MemoryDatabase, - keyless_tx_bytes: Bytes, - gas_limit_override: u64, - tx_compute_gas_limit: Option, - outer_gas_limit_override: Option, -) -> ExecutionResult { - let call_data = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: keyless_tx_bytes, - gasLimitOverride: U256::from(gas_limit_override), - } - .abi_encode(); - - let external_envs = TestExternalEnvs::::new(); - let mut context = MegaContext::new(db, spec).with_external_envs(external_envs.into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - - if let Some(limit) = tx_compute_gas_limit { - context = context.with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_compute_gas_limit(limit), - ); - } - - let tx = TxEnv { - caller: RELAYER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: call_data.into(), - value: U256::ZERO, - gas_limit: outer_gas_limit_override.unwrap_or(OUTER_GAS_LIMIT), - gas_price: 0, - chain_id: Some(1), - ..Default::default() - }; - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - alloy_evm::Evm::transact_commit(&mut evm, tx) - .expect("outer keyless call should not fail at the EVM-error level") -} - -/// Extract `IKeylessDeploy::keylessDeployReturn` payload from a Success-style outer result. -fn decode_keyless_return( - result: &ExecutionResult, -) -> IKeylessDeploy::keylessDeployReturn { - let output = match result { - ExecutionResult::Success { output, .. } => output.data().clone(), - other => panic!("expected Success-style outer result; got {other:?}"), - }; - IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output) - .expect("Success output must decode as keylessDeployReturn") -} - -// ============================================================================ -// Sandbox success that selfdestructed during the constructor -// ============================================================================ - -/// REX6: a constructor that DELEGATECALLs a helper which SELFDESTRUCTs (so the -/// being-created account is marked `SelfDestructed`) but RETURNs non-empty -/// bytecode must surface as `EmptyCodeDeployed` with -/// `deployedAddress = 0x0` — matching what the parent-merged state actually -/// shows. REX5 reports `Deployed { deployedAddress = }` even though -/// the merged account has no code on-chain. -/// -/// The DELEGATECALL-into-`SELFDESTRUCT(0)` shape is the minimal construction; -/// the same surface is reachable by any constructor that selfdestructs the -/// being-created account via an indirect call before `RETURN`-ing non-empty -/// bytecode. The attacker payoff: integrators that check -/// `deployedAddress != 0x0` and stop there (without re-fetching code at the -/// reported address) see a "successful deploy" for an account that has no -/// on-chain code, with the signer's Nick's-Method replay barrier consumed. -#[test] -fn test_rex6_create_then_selfdestruct_surfaces_as_empty_code() { - // Init code: - // PUSH1 0x00 (retSize=0) PUSH1 0x00 (retOff=0) PUSH1 0x00 (argsSize=0) - // PUSH1 0x00 (argsOff=0) PUSH20 helper PUSH1 0x64 (gas=100) DELEGATECALL POP - // // After DELEGATECALL: the executing account has been SELFDESTRUCTed. - // PUSH1 0xff (some non-zero byte) - // PUSH1 0x00 MSTORE8 - // PUSH1 0x01 PUSH1 0x00 RETURN - let init_code = BytecodeBuilder::default() - .push_number(0_u8) // retSize - .push_number(0_u8) // retOffset - .push_number(0_u8) // argsSize - .push_number(0_u8) // argsOffset - .push_address(SELFDESTRUCT_HELPER) - .push_number(100_000_u64) // gas - .append(DELEGATECALL) - .append(POP) - // Now selfdestructed via DELEGATECALL — but still return non-empty bytecode. - .push_number(0xff_u8) - .push_number(0_u8) - .append(MSTORE8) - .push_number(1_u8) // size - .push_number(0_u8) // offset - .append(RETURN) - .build(); - - // Helper at SELFDESTRUCT_HELPER does: - // PUSH1 0x00 SELFDESTRUCT - let helper_code = BytecodeBuilder::default().push_number(0_u8).append(SELFDESTRUCT).build(); - - let (keyless_tx_bytes, signer) = build_keyless_tx_with_init_code(init_code); - let deploy_address = calculate_keyless_deploy_address(signer); - - let build_db = || { - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - db.set_account_code(SELFDESTRUCT_HELPER, helper_code.clone()); - db - }; - - // REX5 baseline: reports Deployed at `deploy_address`, but the on-chain - // code at `deploy_address` is empty (the bug). - let mut db_rex5 = build_db(); - let result_rex5 = run_keyless_outer( - MegaSpecId::REX5, - &mut db_rex5, - keyless_tx_bytes.clone(), - LARGE_GAS_LIMIT_OVERRIDE, - None, - None, - ); - let decoded_rex5 = decode_keyless_return(&result_rex5); - assert_eq!( - decoded_rex5.deployedAddress, deploy_address, - "REX5 surface: sandbox reports a non-zero deployedAddress even though the \ - constructor selfdestructed the account", - ); - let rex5_code_hash = { - use revm::Database as _; - db_rex5.basic(deploy_address).unwrap().map(|info| info.code_hash).unwrap_or_default() - }; - // REX5: the wire reports Deployed but the merged on-chain account has no code. - let rex5_code = { - use revm::Database as _; - if rex5_code_hash == revm::primitives::KECCAK_EMPTY { - Vec::new() - } else { - db_rex5.code_by_hash(rex5_code_hash).unwrap().bytes_slice().to_vec() - } - }; - assert!( - rex5_code.is_empty(), - "REX5 baseline: merged account at deployedAddress has no code — the divergence \ - REX6 fixes; got {rex5_code:?}", - ); - - // REX6: same setup, but the wire now matches the chain — EmptyCodeDeployed - // with `deployedAddress = 0x0`. - let mut db_rex6 = build_db(); - let result_rex6 = run_keyless_outer( - MegaSpecId::REX6, - &mut db_rex6, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - None, - None, - ); - let decoded_rex6 = decode_keyless_return(&result_rex6); - assert_eq!( - decoded_rex6.deployedAddress, - Address::ZERO, - "REX6 must report deployedAddress=0x0 for create+SELFDESTRUCT", - ); - let decoded_err = decode_error_result(&decoded_rex6.errorData); - assert!( - matches!(decoded_err, Some(KeylessDeployError::EmptyCodeDeployed { .. })), - "REX6 errorData must decode as EmptyCodeDeployed; got {decoded_err:?}", - ); -} - -// ============================================================================ -// Keyless dispatch-overhead OOG rescues parent gas -// ============================================================================ - -// ============================================================================ -// Bytecode invariant pins (EIP-3541 / EIP-170 enforcement reaches the -// sandbox dispatch path) -// ============================================================================ - -/// Constructors that return runtime bytecode beginning with `0xEF` must be -/// rejected by the sandbox (EIP-3541). The wire-level outcome is a -/// Halt-shaped `ExecutionHalted` failure, NOT a `Deployed` or -/// `EmptyCodeDeployed` result. -/// -/// This is an invariant pin, not a fix for a finding. revm has enforced -/// EIP-3541 since Berlin, and the sandbox tx goes through revm's normal -/// CREATE handler, so the rejection happens upstream of any MegaETH-specific -/// logic. The test guards against a future REX6+ refactor that accidentally -/// bypasses revm's CREATE validation or short-circuits it in the sandbox -/// dispatch. -#[test] -fn test_rex6_keyless_constructor_returning_ef_prefix_is_rejected() { - // Init code: - // PUSH1 0xef // first byte of returned runtime bytecode - // PUSH1 0x00 MSTORE8 - // PUSH1 0x01 // size = 1 - // PUSH1 0x00 // offset = 0 - // RETURN - let init_code = BytecodeBuilder::default() - .push_number(0xef_u8) - .push_number(0_u8) - .append(MSTORE8) - .push_number(1_u8) - .push_number(0_u8) - .append(RETURN) - .build(); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let result = run_keyless_outer( - MegaSpecId::REX6, - &mut db, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - None, - None, - ); - let decoded = decode_keyless_return(&result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "EIP-3541 violation must not surface as a successful Deploy", - ); - let decoded_err = decode_error_result(&decoded.errorData); - assert!( - matches!(decoded_err, Some(KeylessDeployError::ExecutionHalted { .. })), - "EIP-3541 violation must surface as ExecutionHalted, not EmptyCodeDeployed or \ - a missing errorData; got {decoded_err:?}", - ); -} - -/// Constructors that return runtime bytecode exceeding the configured -/// `limit_contract_code_size` (`MegaETH`'s `MAX_CONTRACT_SIZE = 512 KB` under -/// `MINI_REX`+) must be rejected by the sandbox (EIP-170-equivalent). The -/// wire-level outcome is `ExecutionHalted`, NOT `Deployed`. -/// -/// This is an invariant pin. The size check is enforced inside revm's CREATE -/// handler; the test guards against a future REX6+ refactor that bypasses or -/// short-circuits revm's check from the sandbox dispatch. -/// -/// The outer gas envelope is widened to 200M to comfortably accommodate the -/// `CODE_DEPOSIT_COST` charge that revm would attempt before failing the -/// size check (~200 × 512 KB ≈ 105M gas in the worst-case ordering); the -/// envelope size is irrelevant to what we're testing, only that it's large -/// enough not to OOG before the size check fires. -#[test] -fn test_rex6_keyless_constructor_returning_oversized_bytecode_is_rejected() { - // MegaETH `MAX_CONTRACT_SIZE = 512 * 1024`; return one byte past it. - let oversize: u64 = 512 * 1024 + 1; - - // Init code: - // PUSH3 oversize // size > MAX_CONTRACT_SIZE - // PUSH1 0x00 // offset = 0 (memory is auto-zero) - // RETURN - let init_code = BytecodeBuilder::default() - .push_number(oversize as u32) - .push_number(0_u8) - .append(RETURN) - .build(); - let (keyless_tx_bytes, _signer) = build_keyless_tx_with_init_code(init_code); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(RELAYER, U256::from(1_000_000_000u64)); - - let result = run_keyless_outer( - MegaSpecId::REX6, - &mut db, - keyless_tx_bytes, - LARGE_GAS_LIMIT_OVERRIDE, - None, - Some(200_000_000), - ); - let decoded = decode_keyless_return(&result); - assert_eq!( - decoded.deployedAddress, - Address::ZERO, - "oversized-bytecode constructor must not surface as a successful Deploy", - ); - let decoded_err = decode_error_result(&decoded.errorData); - assert!( - matches!(decoded_err, Some(KeylessDeployError::ExecutionHalted { .. })), - "oversized-bytecode constructor must surface as ExecutionHalted; got {decoded_err:?}", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/main.rs b/crates/mega-evm/tests/_pending/rex6/main.rs deleted file mode 100644 index 54d1f6c42..000000000 --- a/crates/mega-evm/tests/_pending/rex6/main.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Tests for `Rex6` hardfork features. -//! -//! - `eip7702_authority_accounting` — consolidated per-authorization accounting: dynamic SALT -//! account-creation gas for net-new authorities, and DataSize/KV charged only for *applied* -//! authorities (not every recoverable one). - -mod beneficiary_detention; -mod common; -mod create2_metering_order; -mod create_frame_accounting; -mod eip7702_authority_accounting; -mod error_paths; -mod fee_reward_accounting; -mod frame_local_accounting; -mod keyless_sandbox_hardening; -mod oracle_hint_volatile_access; -mod self_transfer_account_dedup; -mod sequencer_registry_rotation; diff --git a/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs b/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs deleted file mode 100644 index 2f946ee1f..000000000 --- a/crates/mega-evm/tests/_pending/rex6/oracle_hint_volatile_access.rs +++ /dev/null @@ -1,224 +0,0 @@ -//! REX6 regression: Oracle hint interceptor consults the volatile-access tracker. -//! -//! `OracleHintInterceptor::intercept` forwards `sendHint` payloads to the off-chain oracle -//! backend as a side effect during `frame_init`, before any interpreter frame runs. Unlike the -//! SLOAD volatile guard (`instructions::sload`), it is not gated on the disabled-subtree -//! tracker (`disableVolatileDataAccess`) on pre-REX6 specs — so a caller could disable volatile -//! access for its own subtree (or a child's) and still leak a hint through a `sendHint` call made -//! inside that disabled subtree. REX6 closes this by consulting the tracker before forwarding — -//! skipping forwarding (not reverting, since the hint is an off-chain side-channel, not consensus -//! state). REX5 and earlier keep forwarding regardless of disabled state, preserving replay -//! determinism on sealed specs. - -use alloy_primitives::{address, Address, Bytes, B256, U256}; -use alloy_sol_types::{sol, SolCall}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - IMegaAccessControl, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, RecordedHint, - TestExternalEnvs, ACCESS_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX5, -}; -use revm::{ - bytecode::opcode::*, - context::{result::ExecutionResult, tx::TxEnvBuilder}, - inspector::NoOpInspector, -}; - -sol! { - function sendHint(bytes32 topic, bytes calldata data) external; -} - -const CALLER: Address = address!("0000000000000000000000000000000000600000"); -const PARENT: Address = address!("0000000000000000000000000000000000600001"); -const CHILD: Address = address!("0000000000000000000000000000000000600002"); - -const TOPIC: B256 = B256::ZERO; - -const DISABLE_SELECTOR: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; - -/// Appends bytecode that calls `disableVolatileDataAccess()` on the access control contract. -fn call_disable_volatile_data_access(builder: BytecodeBuilder) -> BytecodeBuilder { - let builder = builder.mstore(0x0, DISABLE_SELECTOR); - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(ACCESS_CONTROL_ADDRESS) - .push_number(100_000_u64) // gas - .append(CALL) - .append(POP) // discard success flag -} - -/// Appends bytecode that writes a `sendHint(TOPIC, data_size zero bytes)` payload into memory -/// and CALLs `ORACLE_CONTRACT_ADDRESS` with it, leaving the CALL success flag on the stack. -fn call_send_hint(builder: BytecodeBuilder, data_size: usize, forward_gas: u64) -> BytecodeBuilder { - let calldata = - sendHintCall { topic: TOPIC, data: Bytes::from(vec![0u8; data_size]) }.abi_encode(); - let calldata_len = calldata.len(); - let padded_len = calldata_len.div_ceil(32) * 32; - let mut padded = calldata; - padded.resize(padded_len, 0); - - let mut builder = builder; - let mut offset = 0; - while offset < padded_len { - let mut word = [0u8; 32]; - word.copy_from_slice(&padded[offset..offset + 32]); - builder = builder.mstore(offset, word); - offset += 32; - } - builder - .push_number(0u64) // retSize - .push_number(0u64) // retOffset - .push_number(calldata_len as u64) // argsSize - .push_number(0u64) // argsOffset - .push_number(0u64) // value - .push_address(ORACLE_CONTRACT_ADDRESS) - .push_number(forward_gas) - .append(CALL) -} - -/// Appends bytecode that CALLs a target address with the given gas, discarding retdata. -fn append_call(builder: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { - builder - .push_number(0_u64) // retSize - .push_number(0_u64) // retOffset - .push_number(0_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(target) - .push_number(gas) - .append(CALL) -} - -/// Runs a TX calling `PARENT` (with the given code, and optionally `CHILD` with its own code) and -/// returns (`execution_result`, `recorded_hints`). -fn run_with_oracle( - spec: MegaSpecId, - parent_code: Bytes, - child_code: Option, -) -> (ExecutionResult, Vec) { - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(PARENT, parent_code) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX5); - if let Some(child_code) = child_code { - db = db.account_code(CHILD, child_code); - } - let mut context = MegaContext::new(&mut db, spec).with_external_envs((&external_envs).into()); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - (envelope.result, external_envs.recorded_hints()) -} - -/// Like [`run_with_oracle`] but with an explicit TX data-size limit, so a test can observe -/// whether a `sendHint` payload was charged against it. -fn run_with_oracle_and_data_size_limit( - spec: MegaSpecId, - parent_code: Bytes, - data_size_limit: u64, -) -> (ExecutionResult, Vec) { - let external_envs = TestExternalEnvs::::new(); - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10_000_000)) - .account_code(PARENT, parent_code) - .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_REX5); - let mut context = MegaContext::new(&mut db, spec) - .with_external_envs((&external_envs).into()) - .with_tx_runtime_limits( - mega_evm::EvmTxRuntimeLimits::from_spec(spec).with_tx_data_size_limit(data_size_limit), - ); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - - let tx = - TxEnvBuilder::default().caller(CALLER).call(PARENT).gas_limit(100_000_000).build_fill(); - let mut evm = MegaEvm::new(context).with_inspector(NoOpInspector); - let mut tx = MegaTransaction::new(tx); - tx.enveloped_tx = Some(Bytes::new()); - let envelope = alloy_evm::Evm::transact_raw(&mut evm, tx).expect("transact ok"); - (envelope.result, external_envs.recorded_hints()) -} - -/// REX6: a frame that disabled its own volatile access and then calls `sendHint` in the same -/// frame must NOT have the hint forwarded. -#[test] -fn test_rex6_disabled_frame_blocks_own_send_hint() { - let code = - call_send_hint(call_disable_volatile_data_access(BytecodeBuilder::default()), 64, 100_000) - .stop() - .build(); - let (result, hints) = run_with_oracle(MegaSpecId::REX6, code, None); - assert!(result.is_success(), "outer tx must succeed: {result:?}"); - assert!(hints.is_empty(), "sendHint from a volatile-disabled frame must not forward on REX6",); -} - -/// REX6 baseline: when volatile access is NOT disabled, `sendHint` still forwards normally — the -/// new guard must not over-block. -#[test] -fn test_rex6_enabled_frame_still_forwards_send_hint() { - let code = call_send_hint(BytecodeBuilder::default(), 64, 100_000).stop().build(); - let (result, hints) = run_with_oracle(MegaSpecId::REX6, code, None); - assert!(result.is_success(), "outer tx must succeed: {result:?}"); - assert_eq!(hints.len(), 1, "REX6 sendHint must still forward when volatile access is enabled"); -} - -/// REX6: PARENT disables volatile access and calls CHILD, which calls `sendHint`. The hint must -/// not forward even though CHILD itself never called `disableVolatileDataAccess` — this is the -/// exact "disabled child subtree" scenario the finding reports (mirrors the existing SLOAD guard's -/// nested-call coverage in `rex4/access_control.rs::test_nested_call_volatile_access_reverts`). -#[test] -fn test_rex6_disabled_by_parent_blocks_child_send_hint() { - let child_code = call_send_hint(BytecodeBuilder::default(), 64, 100_000).stop().build(); - let parent_code = call_disable_volatile_data_access(BytecodeBuilder::default()); - let parent_code = append_call(parent_code, CHILD, 90_000_000).stop().build(); - - let (result, hints) = run_with_oracle(MegaSpecId::REX6, parent_code, Some(child_code)); - assert!(result.is_success(), "outer tx must succeed: {result:?}"); - assert!( - hints.is_empty(), - "a child call inside a parent-disabled subtree must not forward sendHint", - ); -} - -/// REX6 spec/impl consistency: a disabled-frame `sendHint` call must NOT be charged against the -/// transaction's data-size budget. The volatile-access-disabled check runs before the -/// `record_oracle_hint_bytes` charge, so it groups with the zero-gas-limit and selector-mismatch -/// admission failures (uncharged) — not with a decode failure (charged, per -/// `oracle_hint_metering.rs::test_rex5_malformed_send_hint_is_metered`). Uses a payload large -/// enough that, if metered, would overflow a tight data-size limit; with the fix, the tx must -/// succeed (no halt) precisely because the charge never happens. -#[test] -fn test_rex6_disabled_send_hint_is_not_metered_against_data_size() { - let payload_size = 4096; - let limit = 2048; // far below payload_size: would overflow if the call were metered - let code = call_send_hint( - call_disable_volatile_data_access(BytecodeBuilder::default()), - payload_size, - 1_000_000, - ) - .stop() - .build(); - - let (result, hints) = run_with_oracle_and_data_size_limit(MegaSpecId::REX6, code, limit); - - assert!( - result.is_success(), - "a disabled sendHint call must not be charged against data-size, so a tight limit must \ - not halt the tx: {result:?}", - ); - assert!(hints.is_empty(), "a disabled sendHint call must not forward"); -} diff --git a/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs b/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs deleted file mode 100644 index ce6adfd2b..000000000 --- a/crates/mega-evm/tests/_pending/rex6/self_transfer_account_dedup.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! REX6 value self-transfer account-info dedup for `DataSize` / KV. -//! -//! A value transfer whose target equals the caller touches a single account. The caller-side -//! account-info write (or, at the top level, the `before_tx_start` caller record) already accounts -//! for it, so the target-side write would double-count the same account on the block -//! `DataSize` / KV-update limiter lanes. Under REX6 the redundant target-side write is suppressed -//! when `target == caller`; non-self transfers (`A -> B`) and zero-value calls are unchanged, and -//! pre-REX6 specs keep the frozen double-count. -//! -//! The tests measure the *value-transfer-induced delta* (a `value > 0` run minus an otherwise -//! identical `value == 0` run). That delta isolates exactly the target-side account-info write: -//! -//! - `A -> B`, `value=1`: target write records B → delta = one account-info write on every spec. -//! - `A -> A`, `value=1` (REX6): target write suppressed → delta = 0. -//! - `A -> A`, `value=1` (REX5): target write recorded → delta = one account-info write (frozen). - -use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - EmptyExternalEnv, LimitUsage, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - ACCOUNT_INFO_WRITE_SIZE, -}; -use revm::{ - bytecode::opcode::*, - context::{BlockEnv, ContextSetters, TxEnv}, - handler::EvmTr, - primitives::TxKind, -}; - -/// EOA sender / self-transfer target. -const A: Address = address!("00000000000000000000000000000000A0000001"); -/// Distinct non-self transfer target. -const B: Address = address!("00000000000000000000000000000000B0000002"); -/// A pure-EOA sender used for the nested cases, so the tx caller has no code (EIP-3607). -const EOA: Address = address!("00000000000000000000000000000000E0A00003"); -/// A self-calling contract used in the nested cases (its frame CALLs itself with value). -const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004"); -/// Pre-funded coinbase so beneficiary materialisation never adds noise. -const COINBASE: Address = address!("00000000000000000000000000000000C0FFEE01"); - -const TX_GAS_LIMIT: u64 = 1_000_000; -const A_BALANCE: u128 = 1_000_000_000_000_000_000; // 1 ETH - -type TestEvm = MegaEvm; - -/// Builds a fee-free EVM (`gas_price` = basefee = 0, operator fees zeroed, coinbase pre-funded) so -/// the post-execution fee-reward writes never perturb the `DataSize` / KV measurement. -fn build_evm(spec: MegaSpecId, db: MemoryDatabase) -> TestEvm { - let mut context = MegaContext::new(db, spec); - context.set_block(BlockEnv { - gas_limit: 1_000_000_000, - basefee: 0, - beneficiary: COINBASE, - ..Default::default() - }); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::from(0)); - chain.operator_fee_constant = Some(U256::from(0)); - }); - MegaEvm::new(context) -} - -fn base_db() -> MemoryDatabase { - MemoryDatabase::default() - .account_balance(A, U256::from(A_BALANCE)) - .account_balance(EOA, U256::from(A_BALANCE)) - .account_balance(COINBASE, U256::from(1u64)) -} - -/// A top-level call `A -> to` with the given `value`. -fn call_tx(to: Address, value: u128) -> MegaTransaction { - let mut tx = MegaTransaction { - base: TxEnv { - caller: A, - kind: TxKind::Call(to), - gas_limit: TX_GAS_LIMIT, - gas_price: 0, - value: U256::from(value), - ..Default::default() - }, - ..Default::default() - }; - tx.enveloped_tx = Some(Bytes::new()); - tx -} - -/// Runs `tx` under `spec` against a fresh `db`, asserts success, and returns the limiter usage. -fn usage_of(spec: MegaSpecId, db: MemoryDatabase, tx: MegaTransaction) -> LimitUsage { - let mut evm = build_evm(spec, db); - let r = alloy_evm::Evm::transact_raw(&mut evm, tx); - assert!( - r.expect("no validation error").result.is_success(), - "tx must succeed for a clean usage reading", - ); - let usage = evm.ctx_ref().additional_limit.borrow().get_usage(); - usage -} - -// ============================================================================ -// Top-level self-transfer: A -> A -// ============================================================================ - -// ============================================================================ -// Non-self transfer: A -> B (unchanged on every spec) -// ============================================================================ - -// ============================================================================ -// Nested self-call with value: A's code CALLs A with value -// ============================================================================ - -// ============================================================================ -// Nested self-call where the parent frame already did a value transfer -// (`parent_needs_update == false` arm of the dedup predicate) -// ============================================================================ - -// ============================================================================ -// Zero-value call records no account-info write (unchanged) -// ============================================================================ - -/// A zero-value top-level call records no target-side account-info write on either spec, so the -/// `value=1` vs `value=0` comparison is the only thing that moves — already asserted above. This -/// test pins that REX6 and REX5 agree on the zero-value absolute usage (no behaviour change for the -/// non-transfer path). -#[test] -fn test_zero_value_call_unchanged_across_specs() { - let rex6 = usage_of(MegaSpecId::REX6, base_db(), call_tx(B, 0)); - let rex5 = usage_of(MegaSpecId::REX5, base_db(), call_tx(B, 0)); - assert_eq!( - rex6.data_size, rex5.data_size, - "zero-value A->B call data_size must be identical across specs", - ); - assert_eq!( - rex6.kv_updates, rex5.kv_updates, - "zero-value A->B call kv_updates must be identical across specs", - ); -} diff --git a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs b/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs deleted file mode 100644 index 46277678c..000000000 --- a/crates/mega-evm/tests/_pending/rex6/sequencer_registry_rotation.rs +++ /dev/null @@ -1,398 +0,0 @@ -//! End-to-end tests for the Rex6 `SequencerRegistry` rotation hardening. -//! -//! Covers the block-executor-level scenarios the unit tests in -//! `system/sequencer_registry.rs` cannot: -//! -//! - Fresh Rex6 bootstrap deploys v2.0.0 with the seeded minimum rotation delay and system address -//! resolution keeps working. -//! - The in-place v1.0.0 → v2.0.0 upgrade preserves live storage, and a rotation scheduled under -//! v1.0.0 (no possession proof existed back then) whose activation lands exactly on the Rex6 -//! activation block still flips normally in that same block. -//! - A full v2.0.0 rotation round trip: the admin schedules with a real EIP-712 possession proof -//! via a normal transaction, and the rotation activates in a later block. The digest is built in -//! Rust, independently of the contract's Solidity implementation, so the test also cross-checks -//! the EIP-712 domain against the deployed bytecode. - -use std::convert::Infallible; - -use alloy_consensus::{Signed, TxLegacy}; -use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; -use alloy_evm::{block::BlockExecutor, EvmEnv}; -use alloy_hardforks::ForkCondition; -use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; -use alloy_primitives::{address, keccak256, Address, Bytes, Signature, TxKind, B256, U256}; -use alloy_sol_types::{SolCall, SolValue}; -use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, ISequencerRegistry, MegaBlockExecutionCtx, - MegaBlockExecutorFactory, MegaEvmFactory, MegaHardfork, MegaHardforkConfig, MegaSpecId, - MegaTxEnvelope, SequencerRegistryConfig, SequencerRegistryRex6Config, TestExternalEnvs, - MEGA_SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, - SEQUENCER_REGISTRY_CODE_HASH, SEQUENCER_REGISTRY_CODE_HASH_REX6, -}; -use mega_system_contracts::sequencer_registry::storage_slots::{ - ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, MIN_ROTATION_DELAY, PENDING_SEQUENCER, - SEQUENCER_ACTIVATION_BLOCK, -}; -use revm::{ - context::BlockEnv, - database::State, - state::{AccountInfo, Bytecode}, -}; - -const CHAIN_ID: u64 = 8453; -const BOOTSTRAP_SEQUENCER: Address = address!("0x4000000000000000000000000000000000000004"); -const BOOTSTRAP_ADMIN: Address = address!("0x5000000000000000000000000000000000000005"); -const MIN_ROTATION_DELAY_BLOCKS: u64 = 100; - -fn sequencer_registry_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: BOOTSTRAP_SEQUENCER, - rex5_initial_admin: BOOTSTRAP_ADMIN, - } -} - -fn rex6_chain_spec() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(sequencer_registry_config()) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }) -} - -/// Like [`rex6_chain_spec`] but omits the Rex5 [`SequencerRegistryConfig`], so the pre-block -/// pipeline reaches the sequencer-registry deploy with the config unset and must fail closed. -fn rex6_chain_spec_missing_registry_config() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with(MegaHardfork::Rex5, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex6, ForkCondition::Timestamp(0)) - .with_params(SequencerRegistryRex6Config { - rex6_min_rotation_delay: MIN_ROTATION_DELAY_BLOCKS, - }) -} - -fn evm_env_at_block(block_number: u64) -> EvmEnv { - let mut cfg_env = revm::context::CfgEnv::default(); - cfg_env.spec = MegaSpecId::REX6; - cfg_env.chain_id = CHAIN_ID; - let block_env = BlockEnv { - number: U256::from(block_number), - timestamp: U256::from(1_800_000_000u64), - gas_limit: 30_000_000, - ..Default::default() - }; - EvmEnv::new(cfg_env, block_env) -} - -fn block_ctx() -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), BlockLimits::no_limits()) -} - -fn executor_factory() -> MegaBlockExecutorFactory< - MegaHardforkConfig, - MegaEvmFactory>, - OpAlloyReceiptBuilder, -> { - executor_factory_with(rex6_chain_spec()) -} - -fn executor_factory_with( - chain_spec: MegaHardforkConfig, -) -> MegaBlockExecutorFactory< - MegaHardforkConfig, - MegaEvmFactory>, - OpAlloyReceiptBuilder, -> { - let external_envs = TestExternalEnvs::::new(); - let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - MegaBlockExecutorFactory::new(chain_spec, evm_factory, OpAlloyReceiptBuilder::default()) -} - -/// Plants always-reverting bytecode (`PUSH1 0 PUSH1 0 REVERT`) at `addr` so a pre-block system -/// call targeting it returns a non-success result. -fn plant_reverting_code(db: &mut MemoryDatabase, addr: Address) { - let code = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd]); - db.insert_account_info( - addr, - AccountInfo { - code_hash: keccak256(&code), - code: Some(Bytecode::new_raw(code)), - ..Default::default() - }, - ); -} - -fn create_tx_from( - sender: Address, - nonce: u64, - target: Address, - data: Bytes, -) -> alloy_consensus::transaction::Recovered { - let tx_legacy = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce, - gas_price: 0, - gas_limit: 1_000_000, - to: TxKind::Call(target), - value: U256::ZERO, - input: data, - }; - let signed = Signed::new_unchecked(tx_legacy, Signature::test_signature(), Default::default()); - alloy_consensus::transaction::Recovered::new_unchecked(MegaTxEnvelope::Legacy(signed), sender) -} - -fn read_registry_slot(state: &mut State<&mut MemoryDatabase>, slot: U256) -> U256 { - revm::Database::storage(state, SEQUENCER_REGISTRY_ADDRESS, slot).expect("read registry slot") -} - -fn registry_code_hash(state: &mut State<&mut MemoryDatabase>) -> B256 { - revm::Database::basic(state, SEQUENCER_REGISTRY_ADDRESS) - .expect("read registry account") - .expect("registry account must exist") - .code_hash -} - -/// Builds the EIP-712 digest for `SequencerRotation(address newSequencer,uint256 -/// activationBlock)` against the registry's domain, mirroring the Solidity computation -/// independently so the test cross-checks the deployed bytecode. -fn rotation_digest(new_sequencer: Address, activation_block: U256) -> B256 { - let domain_typehash = keccak256( - b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", - ); - let rotation_typehash = - keccak256(b"SequencerRotation(address newSequencer,uint256 activationBlock)"); - let domain_separator = keccak256( - ( - domain_typehash, - keccak256(b"MegaETH SequencerRegistry"), - keccak256(b"1"), - U256::from(CHAIN_ID), - SEQUENCER_REGISTRY_ADDRESS, - ) - .abi_encode(), - ); - let struct_hash = keccak256((rotation_typehash, new_sequencer, activation_block).abi_encode()); - - let mut preimage = Vec::with_capacity(2 + 32 + 32); - preimage.extend_from_slice(b"\x19\x01"); - preimage.extend_from_slice(domain_separator.as_slice()); - preimage.extend_from_slice(struct_hash.as_slice()); - keccak256(&preimage) -} - -/// A fixed secp256k1 keypair for the rotated-in sequencer; the address is recovered from a -/// probe signature so no extra signing-crate dev-dependency is needed. -fn new_sequencer_keypair() -> (Address, B256) { - let secret = B256::from(U256::from(0x5ec5ec5ec5ecu64)); - (recover_probe_address(secret), secret) -} - -fn recover_probe_address(secret: B256) -> Address { - let probe = B256::from(U256::from(1)); - let sig = alloy_consensus::crypto::secp256k1::sign_message(secret, probe) - .expect("probe signing must succeed"); - alloy_consensus::crypto::secp256k1::recover_signer(&sig, probe) - .expect("probe recovery must succeed") -} - -/// Signs the rotation digest with `secret` and returns the 65-byte `(r, s, v)` blob the -/// contract expects. -fn sign_rotation(secret: B256, new_sequencer: Address, activation_block: U256) -> Bytes { - let digest = rotation_digest(new_sequencer, activation_block); - let sig = alloy_consensus::crypto::secp256k1::sign_message(secret, digest) - .expect("rotation signing must succeed"); - let mut blob = Vec::with_capacity(65); - blob.extend_from_slice(&sig.r().to_be_bytes::<32>()); - blob.extend_from_slice(&sig.s().to_be_bytes::<32>()); - blob.push(27 + sig.v() as u8); - Bytes::from(blob) -} - -/// Seeds a live v1.0.0 registry as it would exist on a Rex5 chain right before the Rex6 -/// upgrade: bootstrap roles plus a pending sequencer rotation scheduled without any proof. -fn seed_v1_registry_with_pending_rotation( - db: &mut MemoryDatabase, - pending_sequencer: Address, - activation_block: u64, -) { - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - for (slot, value) in [ - (CURRENT_SYSTEM_ADDRESS, U256::from_be_bytes(MEGA_SYSTEM_ADDRESS.into_word().0)), - (CURRENT_SEQUENCER, U256::from_be_bytes(BOOTSTRAP_SEQUENCER.into_word().0)), - (ADMIN, U256::from_be_bytes(BOOTSTRAP_ADMIN.into_word().0)), - (PENDING_SEQUENCER, U256::from_be_bytes(pending_sequencer.into_word().0)), - (SEQUENCER_ACTIVATION_BLOCK, U256::from(activation_block)), - ] { - db.insert_account_storage(SEQUENCER_REGISTRY_ADDRESS, slot, value).unwrap(); - } -} - -/// Fresh chain at Rex6: the pre-block deploy installs v2.0.0 directly with the full seed -/// (including `_minRotationDelay`), and system-address resolution succeeds against the v2 -/// code hash. -#[test] -fn test_rex6_bootstrap_deploys_v2_and_resolves_system_address() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = - executor_factory().create_executor(&mut state, block_ctx(), evm_env_at_block(1000)); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - drop(executor); - - assert_eq!(registry_code_hash(&mut state), SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - read_registry_slot(&mut state, MIN_ROTATION_DELAY), - U256::from(MIN_ROTATION_DELAY_BLOCKS), - "_minRotationDelay must be seeded on the fresh Rex6 bootstrap" - ); - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(BOOTSTRAP_SEQUENCER.into_word().0), - ); -} - -/// Full v2.0.0 round trip through normal transactions: the admin schedules a rotation with -/// the new key's EIP-712 possession proof in one block, and the rotation activates in a -/// later block's pre-execution phase. -#[test] -fn test_rex6_rotation_with_valid_proof_end_to_end() { - let (new_sequencer, secret) = new_sequencer_keypair(); - let schedule_block = 1000u64; - let activation_block = schedule_block + MIN_ROTATION_DELAY_BLOCKS; - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(BOOTSTRAP_ADMIN, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let factory = executor_factory(); - - // Block 1000: bootstrap deploy + admin schedules the rotation with a valid proof. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(schedule_block)); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let calldata = ISequencerRegistry::scheduleNextSequencerChangeCall { - newSequencer: new_sequencer, - activationBlock: U256::from(activation_block), - newSequencerSignature: sign_rotation(secret, new_sequencer, U256::from(activation_block)), - } - .abi_encode(); - let tx = create_tx_from(BOOTSTRAP_ADMIN, 0, SEQUENCER_REGISTRY_ADDRESS, Bytes::from(calldata)); - executor.execute_transaction(&tx).expect("schedule tx should be accepted"); - drop(executor); - - assert_eq!( - read_registry_slot(&mut state, PENDING_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the proof-carrying schedule call must record the pending rotation" - ); - assert_eq!( - read_registry_slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), - U256::from(activation_block), - ); - - // Activation block: the pre-execution system call applies the rotation. - let mut executor = - factory.create_executor(&mut state, block_ctx(), evm_env_at_block(activation_block)); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - drop(executor); - - assert_eq!( - read_registry_slot(&mut state, CURRENT_SEQUENCER), - U256::from_be_bytes(new_sequencer.into_word().0), - "the rotation must flip at its activation block" - ); - assert_eq!(read_registry_slot(&mut state, PENDING_SEQUENCER), U256::ZERO); -} - -/// The hardened entry point rejects a schedule without a possession proof: the transaction -/// executes but the call reverts and no pending rotation is recorded. -#[test] -fn test_rex6_schedule_without_proof_reverts() { - let (new_sequencer, _) = new_sequencer_keypair(); - - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - db.set_account_balance(BOOTSTRAP_ADMIN, U256::from(1_000_000_000_000_000u64)); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = - executor_factory().create_executor(&mut state, block_ctx(), evm_env_at_block(1000)); - executor.apply_pre_execution_changes().expect("pre-execution changes should succeed"); - - let calldata = ISequencerRegistry::scheduleNextSequencerChangeCall { - newSequencer: new_sequencer, - activationBlock: U256::from(1000 + MIN_ROTATION_DELAY_BLOCKS), - newSequencerSignature: Bytes::new(), - } - .abi_encode(); - let tx = create_tx_from(BOOTSTRAP_ADMIN, 0, SEQUENCER_REGISTRY_ADDRESS, Bytes::from(calldata)); - // The executor accepts the transaction; the contract call itself reverts, so the pending - // rotation must remain unset. - executor.execute_transaction(&tx).expect("tx should be accepted even though the call reverts"); - drop(executor); - - assert_eq!( - read_registry_slot(&mut state, PENDING_SEQUENCER), - U256::ZERO, - "a schedule without a possession proof must not record a pending rotation" - ); -} - -/// Fail-closed guard: a Rex5+ EIP-2935 (blockhash) pre-block system call that does not succeed -/// must abort block execution instead of silently committing the failed outcome. Reverting -/// bytecode is planted at the history-storage contract so the system call reverts. -#[test] -fn test_rex6_eip2935_pre_block_call_failure_aborts_block() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - plant_reverting_code(&mut db, HISTORY_STORAGE_ADDRESS); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = - executor_factory().create_executor(&mut state, block_ctx(), evm_env_at_block(1000)); - let err = executor - .apply_pre_execution_changes() - .expect_err("a failed EIP-2935 pre-block call must abort the block"); - - let msg = std::format!("{err}"); - assert!( - msg.contains("EIP-2935 pre-block system call did not succeed"), - "expected an EIP-2935 pre-block failure, got: {msg}" - ); -} - -/// Fail-closed guard: same as the EIP-2935 case but for the Rex5+ EIP-4788 (beacon-root) -/// pre-block system call. Reverting bytecode is planted at the beacon-roots contract; the -/// EIP-2935 call still succeeds (no code planted there), so the EIP-4788 guard is the one that -/// fires. -#[test] -fn test_rex6_eip4788_pre_block_call_failure_aborts_block() { - let mut db = MemoryDatabase::default(); - db.set_account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000_000_000_000_000u64)); - plant_reverting_code(&mut db, BEACON_ROOTS_ADDRESS); - - let mut state = State::builder().with_database(&mut db).build(); - let mut executor = - executor_factory().create_executor(&mut state, block_ctx(), evm_env_at_block(1000)); - let err = executor - .apply_pre_execution_changes() - .expect_err("a failed EIP-4788 pre-block call must abort the block"); - - let msg = std::format!("{err}"); - assert!( - msg.contains("EIP-4788 pre-block system call did not succeed"), - "expected an EIP-4788 pre-block failure, got: {msg}" - ); -} diff --git a/crates/mega-evm/tests/_pending/src/access/volatile.rs b/crates/mega-evm/tests/_pending/src/access/volatile.rs deleted file mode 100644 index 7aa7e6405..000000000 --- a/crates/mega-evm/tests/_pending/src/access/volatile.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/access/volatile.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/access/volatile.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::VolatileDataAccessType; - - #[test] - fn test_empty_access_has_no_flags() { - let access = VolatileDataAccess::empty(); - - assert!(!access.has_block_env_access()); - assert!(!access.has_beneficiary_balance_access()); - assert!(!access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 0); - assert_eq!(access.count_accessed(), 0); - assert_eq!(access.block_env_only(), VolatileDataAccess::empty()); - assert_eq!(access.raw(), 0); - } - - #[test] - fn test_block_env_helpers_ignore_non_block_flags() { - let access = VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::BLOB_HASH | - VolatileDataAccess::BENEFICIARY_BALANCE | - VolatileDataAccess::ORACLE; - - assert!(access.has_block_env_access()); - assert!(access.has_beneficiary_balance_access()); - assert!(access.has_oracle_access()); - assert_eq!(access.count_block_env_accessed(), 2); - assert_eq!(access.count_accessed(), 2); - assert_eq!( - access.block_env_only(), - VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOB_HASH - ); - assert_eq!(access.raw(), access.bits()); - } - - #[test] - fn test_from_volatile_data_access_type_covers_all_variants() { - let expected: &[(VolatileDataAccessType, VolatileDataAccess)] = &[ - (VolatileDataAccessType::BlockNumber, VolatileDataAccess::BLOCK_NUMBER), - (VolatileDataAccessType::Timestamp, VolatileDataAccess::TIMESTAMP), - (VolatileDataAccessType::Coinbase, VolatileDataAccess::COINBASE), - (VolatileDataAccessType::Difficulty, VolatileDataAccess::DIFFICULTY), - (VolatileDataAccessType::GasLimit, VolatileDataAccess::GAS_LIMIT), - (VolatileDataAccessType::BaseFee, VolatileDataAccess::BASE_FEE), - (VolatileDataAccessType::PrevRandao, VolatileDataAccess::PREV_RANDAO), - (VolatileDataAccessType::BlockHash, VolatileDataAccess::BLOCK_HASH), - (VolatileDataAccessType::BlobBaseFee, VolatileDataAccess::BLOB_BASE_FEE), - (VolatileDataAccessType::BlobHash, VolatileDataAccess::BLOB_HASH), - (VolatileDataAccessType::Beneficiary, VolatileDataAccess::BENEFICIARY_BALANCE), - (VolatileDataAccessType::Oracle, VolatileDataAccess::ORACLE), - ]; - - for &(access_type, expected_flag) in expected { - let converted = VolatileDataAccess::from(access_type); - assert_eq!(converted, expected_flag); - assert_eq!(converted.as_u8(), expected_flag.as_u8()); - } - } - - #[test] - fn test_all_block_env_flags_counted_correctly() { - let all_block_env = VolatileDataAccess::BLOCK_NUMBER | - VolatileDataAccess::TIMESTAMP | - VolatileDataAccess::COINBASE | - VolatileDataAccess::DIFFICULTY | - VolatileDataAccess::GAS_LIMIT | - VolatileDataAccess::BASE_FEE | - VolatileDataAccess::PREV_RANDAO | - VolatileDataAccess::BLOCK_HASH | - VolatileDataAccess::BLOB_BASE_FEE | - VolatileDataAccess::BLOB_HASH; - - assert_eq!(all_block_env.count_block_env_accessed(), 10); - assert!(all_block_env.has_block_env_access()); - assert!(!all_block_env.has_beneficiary_balance_access()); - assert!(!all_block_env.has_oracle_access()); - assert_eq!(all_block_env.block_env_only(), all_block_env); - } -} diff --git a/crates/mega-evm/tests/_pending/src/evm/mod.rs b/crates/mega-evm/tests/_pending/src/evm/mod.rs deleted file mode 100644 index e0f5e2abd..000000000 --- a/crates/mega-evm/tests/_pending/src/evm/mod.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/evm/mod.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/evm/mod.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use alloy_primitives::{address, Bytes, U256}; - use revm::{ - context::{ - result::{ExecResultAndState, ExecutionResult}, - ContextSetters, TxEnv, - }, - database::State, - inspector::NoOpInspector, - state::EvmState, - ExecuteCommitEvm, ExecuteEvm, InspectEvm, SystemCallEvm, - }; - - const CALLER: Address = address!("4000000000000000000000000000000000000001"); - const CALLEE: Address = address!("5000000000000000000000000000000000000001"); - - fn configure_context(db: DB) -> MegaContext { - let mut context = MegaContext::new(db, MegaSpecId::REX4); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context - } - - fn tx_env() -> TxEnv { - TxEnv { - caller: CALLER, - gas_limit: 100_000, - kind: alloy_primitives::TxKind::Call(CALLEE), - value: U256::ZERO, - data: Bytes::new(), - ..Default::default() - } - } - - fn mega_tx() -> MegaTransaction { - let mut tx = MegaTransaction::new(tx_env()); - tx.enveloped_tx = Some(Bytes::new()); - tx - } - - #[test] - fn test_revm_system_call_with_caller_works() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - let system_call: ExecutionResult = - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - assert!(system_call.is_success()); - } - - #[test] - fn test_transact_system_call_with_gas_limit_uses_passed_value() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut evm = MegaEvm::new(configure_context(&mut db)); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) - .unwrap(); - assert!(result.result.is_success()); - // The custom gas limit must be applied to the underlying tx. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 123_456_789); - } - - #[test] - fn test_default_system_call_keeps_upstream_30m_gas_limit() { - let mut db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(1_000_000)) - .account_code(CALLEE, Bytes::new()); - let mut context = MegaContext::new(&mut db, MegaSpecId::REX5); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - context.block.gas_limit = 100_000_000; - let mut evm = MegaEvm::new(context); - - // The default system-call entry point must NOT be widened by REX5 — only the - // explicit `transact_system_call_with_gas_limit` path should pick up the live - // block budget. This preserves byte-level behavior of EIP-2935 / EIP-4788 - // pre-block calls across all specs. - SystemCallEvm::transact_system_call_with_caller(&mut evm, CALLER, CALLEE, Bytes::new()) - .unwrap(); - // Literal, not `SYSTEM_CALL_GAS_LIMIT_FLOOR`: this assertion verifies revm's - // upstream hardcoded default. If upstream ever drifts from our floor, this - // test should fail loudly rather than be auto-aligned by our constant. - assert_eq!(evm.inner.ctx.tx.base.gas_limit, 30_000_000); - } - - #[test] - fn test_mega_evm_exposes_state_wrapper_block_hashes() { - let mut db = MemoryDatabase::default(); - let mut state = State::builder().with_database(&mut db).build(); - state.block_hashes.insert(7, B256::from([7_u8; 32])); - - let evm = MegaEvm::new(configure_context(&mut state)); - assert_eq!(evm.get_accessed_block_hashes().get(&7), Some(&B256::from([7_u8; 32]))); - } -} diff --git a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs b/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs deleted file mode 100644 index 8696695dc..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/compute_gas.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/compute_gas.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/compute_gas.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// Usage exactly equal to the detained limit must NOT count as a detained exceed: - /// the predicate is strictly-greater-than (`used > detained_limit`), not `>=`. - #[test] - fn test_is_detained_exceed_is_strict_at_boundary() { - // tx_limit = 100, detained lowered to 50 (< tx_limit, so detention is binding). - let mut tracker = ComputeGasTracker::new(MegaSpecId::MINI_REX, 100); - tracker.set_detained_limit(50); - - // Usage exactly at the detained limit: not exceeded. - tracker.record_gas_used(50); - assert!( - !tracker.is_detained_exceed(), - "usage == detained_limit must not be a detained exceed" - ); - - // One unit over the limit: exceeded. - tracker.record_gas_used(1); - assert!(tracker.is_detained_exceed(), "usage > detained_limit must be a detained exceed"); - } -} diff --git a/crates/mega-evm/tests/_pending/src/limit/data_size.rs b/crates/mega-evm/tests/_pending/src/limit/data_size.rs deleted file mode 100644 index e7a8ba712..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/data_size.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/data_size.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/data_size.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// The originated data-size constants are *sums* of their salt key/value components, - /// not products. Pin the values against independent literals so an arithmetic slip - /// (e.g. `+` -> `*`) is caught (8 + 32 = 40, not 8 * 32 = 256). - #[test] - fn test_originated_data_size_constants() { - assert_eq!(STORAGE_SLOT_WRITE_SIZE, 40); - assert_eq!(ACCOUNT_INFO_WRITE_SIZE, 40); - } - - /// `has_active_frame` must reflect the underlying frame stack, not a constant. - #[test] - fn test_has_active_frame_reflects_frame_stack() { - let mut tracker = DataSizeTracker::new(MegaSpecId::MINI_REX, u64::MAX); - assert!(!tracker.has_active_frame(), "no frame pushed yet"); - tracker.push_empty_frame(); - assert!(tracker.has_active_frame(), "a frame is on the stack"); - } -} diff --git a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs b/crates/mega-evm/tests/_pending/src/limit/kv_update.rs deleted file mode 100644 index f7d03325d..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/kv_update.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/kv_update.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/kv_update.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - - /// `record_account_update` must charge exactly one KV update against the current frame - /// (used by REX5+ SELFDESTRUCT-beneficiary metering); it must not be a no-op. - #[test] - fn test_record_account_update_charges_one_kv() { - let mut tracker = KVUpdateTracker::new(MegaSpecId::MINI_REX, u64::MAX); - tracker.push_empty_frame(); - assert_eq!(tracker.tx_usage(), 0); - tracker.record_account_update(); - assert_eq!(tracker.tx_usage(), 1, "record_account_update must add exactly 1 KV update"); - } -} diff --git a/crates/mega-evm/tests/_pending/src/limit/limit.rs b/crates/mega-evm/tests/_pending/src/limit/limit.rs deleted file mode 100644 index 8a2bdf354..000000000 --- a/crates/mega-evm/tests/_pending/src/limit/limit.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/limit/limit.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/limit/limit.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod metering_exemption_tests { - use super::*; - - /// Tiny per-dimension limits so a single recording trivially exceeds them. - fn tiny_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 1, - tx_kv_updates_limit: 1, - tx_compute_gas_limit: 1, - tx_state_growth_limit: 1, - block_env_access_compute_gas_limit: u64::MAX, - oracle_access_compute_gas_limit: u64::MAX, - } - } - - #[test] - fn test_metering_enforced_when_not_exempt() { - // Default (non-exempt): halted once compute gas exceeds the (tiny) limit. The REX6 × - // system-origin gate that would stamp `Exempt` lives in `MegaContext::on_new_tx`; here we - // exercise the tracker directly. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - assert!(!al.record_compute_gas(1_000_000), "non-exempt tx must report exceeded limit"); - assert!(al.check_limit().exceeded_limit()); - } - - #[test] - fn test_metering_bypassed_when_exempt() { - // When the system-tx exemption is stamped, `check_limit` short-circuits on the sticky - // `Exempt` state, covering the four dimensions *and* gas detention, so the same - // over-limit usage never halts. Usage is still recorded (only the halt decision is - // suppressed). - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.record_compute_gas(1_000_000), "exempt tx must not report exceeded limit"); - assert!(!al.check_limit().exceeded_limit()); - assert!(al.check_limit().is_exempt(), "check_limit must surface the sticky Exempt state"); - assert!(al.get_usage().compute_gas >= 1_000_000, "usage is still accumulated while exempt"); - } - - #[test] - fn test_detained_compute_gas_does_not_halt_when_exempt() { - // Gas detention lowers the detained compute-gas limit; enforcement runs through the same - // `check_limit` chokepoint, so the exemption neutralizes detention too. - let mut al = - AdditionalLimit::new(MegaSpecId::REX6, EvmTxRuntimeLimits::from_spec(MegaSpecId::REX6)); - al.mark_exempt(); - al.set_compute_gas_limit(1); // detain hard - assert!(al.record_compute_gas(10_000_000), "exempt tx must ignore gas detention"); - assert!(!al.check_limit().exceeded_limit()); - } - - #[test] - fn test_reset_clears_exempt() { - // The sticky `Exempt` state must not leak to the next transaction reusing the same tracker. - let mut al = AdditionalLimit::new(MegaSpecId::REX6, tiny_limits()); - al.mark_exempt(); - assert!(al.has_exceeded_limit.is_exempt()); - al.reset(); - assert!(!al.has_exceeded_limit.is_exempt(), "reset must clear the sticky Exempt state"); - assert!( - al.has_exceeded_limit.within_limit(), - "reset must restore the WithinLimit baseline" - ); - assert!(!al.record_compute_gas(1_000_000), "after reset, metering is enforced again"); - } -} - -#[cfg(test)] -mod tests { - use revm::context::tx::TxEnvBuilder; - - use super::{super::LimitKind, *}; - - fn test_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits { - tx_data_size_limit: 100, - tx_kv_updates_limit: 1_000, - tx_compute_gas_limit: 1_000_000, - tx_state_growth_limit: 1_000, - block_env_access_compute_gas_limit: 1_000_000, - oracle_access_compute_gas_limit: 1_000_000, - } - } - - /// Returns the latched limit kind, or `None` when within limit. - fn latched_kind(limit: &AdditionalLimit) -> Option { - match limit.has_exceeded_limit { - LimitCheck::ExceedsLimit { kind, .. } => Some(kind), - LimitCheck::WithinLimit | LimitCheck::Exempt => None, - } - } - -} diff --git a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs b/crates/mega-evm/tests/_pending/src/sandbox/execution.rs deleted file mode 100644 index 10b913932..000000000 --- a/crates/mega-evm/tests/_pending/src/sandbox/execution.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/sandbox/execution.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/sandbox/execution.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use revm::context::result::Output; - - /// Test error type that lets us drive `process_sandbox_transact_result`'s - /// `Err` arms (which map to `SandboxOutcome::Rejected`) directly without - /// standing up a full sandbox EVM. The two arms differ only by - /// `IsTxError::is_tx_error()`, so a single struct with a configurable flag - /// covers both selector mappings. - struct FakeTxErr { - is_tx: bool, - msg: &'static str, - } - - impl core::fmt::Display for FakeTxErr { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(self.msg) - } - } - - impl IsTxError for FakeTxErr { - fn is_tx_error(&self) -> bool { - self.is_tx - } - } - - /// `validate_signer_code` MUST be a no-op when `cfg.disable_eip3607 = true`, even - /// when the provided `AccountInfo` has bytecode that would otherwise trip the - /// caller-with-code check. Mirrors the canonical revm `validate_account_nonce_and_code` - /// semantics and pins the early-return contract. - #[test] - fn test_validate_signer_code_disable_eip3607_short_circuits() { - use crate::{test_utils::MemoryDatabase, EmptyExternalEnv}; - use revm::{ - bytecode::Bytecode, - primitives::{keccak256, Bytes as PrimitivesBytes}, - }; - - let code_bytes = PrimitivesBytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); - let code_hash = keccak256(&code_bytes); - let signer_info = AccountInfo { - nonce: 0, - balance: U256::ZERO, - code_hash, - code: Some(Bytecode::new_raw(code_bytes)), - }; - - let mut ctx = - MegaContext::<_, EmptyExternalEnv>::new(MemoryDatabase::default(), MegaSpecId::REX5); - ctx.modify_cfg(|cfg| cfg.disable_eip3607 = true); - - let out = validate_signer_code(&ctx, &signer_info); - assert!( - matches!(out, Ok(())), - "disable_eip3607 must short-circuit before the code inspection; got {out:?}", - ); - } - - /// `charge_caller_materialization_pre_sandbox` MUST surface a SALT/dynamic-gas failure - /// as `Err(KeylessDeployError::InternalError)` without writing to `ctx.error()`. - /// - /// The contract is load-bearing: op-revm's `Handler::execution_result` drains - /// `ctx.error()` and converts any non-empty `ContextError` into an EVM-level - /// `Err(Custom(...))`. Routing a SALT failure through the - /// `HostExt::new_account_storage_gas` helper — which stashes the error into - /// `ctx.error()` — would promote an interceptor-level failure into a whole-transaction - /// execution error and break the `InternalError()` selector contract. The - /// pre-sandbox charge path must therefore call `DynamicGasCost::new_account_gas` - /// directly and keep the error local. - #[test] - fn test_charge_caller_materialization_salt_failure_returns_internal_error_without_ctx_pollution( - ) { - use crate::{test_utils::MemoryDatabase, BucketId, OracleEnv, SaltEnv}; - use alloy_primitives::{address, B256}; - use core::fmt::{self, Display, Formatter}; - - // Minimal `SaltEnv` whose `get_bucket_capacity` always fails. This drives - // `DynamicGasCost::new_account_gas` (called from - // `charge_caller_materialization_pre_sandbox`) to return `Err`, exercising the - // failure-handling path under test. - #[derive(Debug, Clone, Copy)] - struct AlwaysFailSalt; - - #[derive(Debug, Clone)] - struct InjectedSaltError; - impl Display for InjectedSaltError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.write_str("injected SALT failure") - } - } - - impl SaltEnv for AlwaysFailSalt { - type Error = InjectedSaltError; - fn get_bucket_capacity(&self, _bucket_id: BucketId) -> Result { - Err(InjectedSaltError) - } - fn bucket_id_for_account(_account: Address) -> BucketId { - 0 - } - fn bucket_id_for_slot(_address: Address, _key: U256) -> BucketId { - 0 - } - } - - #[derive(Debug, Clone, Copy)] - struct NoopOracle; - impl OracleEnv for NoopOracle { - fn get_oracle_storage(&self, _slot: U256) -> Option { - None - } - fn on_hint(&self, _from: Address, _topic: B256, _data: Bytes) {} - } - - let signer = address!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0001"); - let db = MemoryDatabase::default(); - let envs: crate::ExternalEnvs<(AlwaysFailSalt, NoopOracle)> = - crate::ExternalEnvs { salt_env: AlwaysFailSalt, oracle_env: NoopOracle }; - let mut ctx = MegaContext::new(db, MegaSpecId::REX5).with_external_envs(envs); - - let mut gas = Gas::new(10_000_000); - let return_memory_offset = 0..0; - - // Signer is unmaterialized (default `AccountInfo` is `is_empty()` == true) - // → the materialization branch fires. - let signer_info = AccountInfo::default(); - let out = charge_caller_materialization_pre_sandbox( - &ctx, - &mut gas, - signer, - &signer_info, - &return_memory_offset, - ); - assert!( - matches!(out, Err(KeylessDeployError::InternalError)), - "SALT failure must surface as InternalError, got {out:?}", - ); - - // The whole point of the fix: ctx.error() must NOT have been polluted, so the outer - // transaction's `execution_result` doesn't drain it into `Err(Custom)`. - let ctx_error = core::mem::replace(ctx.error(), Ok(())); - assert!( - matches!(ctx_error, Ok(())), - "ctx.error() must remain Ok after a SALT failure in the pre-sandbox charge; \ - got {ctx_error:?}", - ); - - // record_deposit_caller_creation must NOT have fired either. - assert_eq!( - ctx.additional_limit.borrow().get_usage().state_growth, - 0, - "deposit-caller state-growth must not be recorded when the storage gas computation fails", - ); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/control.rs b/crates/mega-evm/tests/_pending/src/system/control.rs deleted file mode 100644 index 97b91a79f..000000000 --- a/crates/mega-evm/tests/_pending/src/system/control.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/control.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/control.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{keccak256, B256}; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - use crate::{MegaHardfork, MegaHardforkConfig}; - use alloy_hardforks::ForkCondition; - - #[test] - fn test_volatile_data_access_disabled_selector() { - let expected: [u8; 4] = - keccak256("VolatileDataAccessDisabled(uint8)")[..4].try_into().unwrap(); - assert_eq!( - VOLATILE_DATA_ACCESS_DISABLED_SELECTOR, expected, - "Selector must match keccak256(\"VolatileDataAccessDisabled(uint8)\")[0..4]" - ); - } - - #[test] - fn test_disabled_by_parent_revert_data() { - let expected: [u8; 4] = keccak256("DisabledByParent()")[..4].try_into().unwrap(); - assert_eq!( - DISABLED_BY_PARENT_REVERT_DATA, expected, - "Selector must match keccak256(\"DisabledByParent()\")[0..4]" - ); - } - - #[test] - fn test_access_control_contract_code_hash_matches() { - let computed_hash = keccak256(&ACCESS_CONTROL_CODE); - assert_eq!(computed_hash, ACCESS_CONTROL_CODE_HASH); - } - - #[test] - fn test_volatile_data_access_disabled_revert_data_encodes_error() { - let revert_data = volatile_data_access_disabled_revert_data(VolatileDataAccessType::Oracle); - let decoded = - ::abi_decode(&revert_data) - .unwrap(); - - assert_eq!(decoded.accessType, VolatileDataAccessType::Oracle); - } - - #[test] - fn test_deploy_access_control_contract_on_fresh_db() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_access_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&ACCESS_CONTROL_ADDRESS).unwrap(); - - assert!(account.is_touched()); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, ACCESS_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), ACCESS_CONTROL_CODE); - } - - #[test] - fn test_deploy_access_control_contract_is_idempotent() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ACCESS_CONTROL_ADDRESS, - AccountInfo { - balance: Default::default(), - nonce: 0, - code_hash: ACCESS_CONTROL_CODE_HASH, - code: Some(Bytecode::new_raw(ACCESS_CONTROL_CODE)), - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_access_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&ACCESS_CONTROL_ADDRESS).unwrap(); - - assert_eq!(account.info.code_hash, ACCESS_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), ACCESS_CONTROL_CODE); - assert!(!account.is_created(), "idempotent deploy should not re-create the account"); - } - - #[test] - fn test_deploy_access_control_contract_at_later_timestamp() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = - MegaHardforkConfig::default().with(MegaHardfork::Rex4, ForkCondition::Timestamp(50)); - - assert_eq!( - transact_deploy_access_control_contract(&hardforks, 49, &mut state).unwrap(), - None, - "should not deploy before Rex4 activation" - ); - - let result = - transact_deploy_access_control_contract(&hardforks, 50, &mut state).unwrap().unwrap(); - let account = result.get(&ACCESS_CONTROL_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, ACCESS_CONTROL_CODE_HASH); - } - - #[test] - fn test_deploy_access_control_contract_overwrites_wrong_existing_code_hash() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - ACCESS_CONTROL_ADDRESS, - AccountInfo { - balance: Default::default(), - nonce: 0, - code_hash: B256::ZERO, - code: Some(Bytecode::new_raw(alloy_primitives::Bytes::from_static(&[0x60, 0x00]))), - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_access_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&ACCESS_CONTROL_ADDRESS).unwrap(); - - assert_eq!(account.info.code_hash, ACCESS_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), ACCESS_CONTROL_CODE); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "in-place bytecode update of an existing account must not mark it as created" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/deploy.rs b/crates/mega-evm/tests/_pending/src/system/deploy.rs deleted file mode 100644 index b8c6f6ee1..000000000 --- a/crates/mega-evm/tests/_pending/src/system/deploy.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/deploy.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/deploy.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - MegaHardfork, MegaHardforkConfig, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, ORACLE_CONTRACT_CODE_HASH_REX2, - ORACLE_CONTRACT_CODE_HASH_REX5, - }; - use alloy_hardforks::ForkCondition; - use alloy_primitives::address; - use revm::{database::InMemoryDB, state::AccountInfo, Database as _, DatabaseCommit}; - - fn addrs(specs: &[SystemContractSpec]) -> Vec
{ - specs.iter().map(|s| s.address).collect() - } - - const SEEDED_ADDR: Address = address!("0x6342000000000000000000000000000000000099"); - const SEED_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); - const UNRELATED_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); - - /// Builds a spec whose code hash differs from any pre-existing account, so - /// `transact_deploy` takes the bytecode-upgrade path rather than the - /// idempotent early return. - fn seeded_spec(force_create_on_upgrade: bool) -> SystemContractSpec { - let code = Bytes::from_static(&[0x60, 0x00]); - let code_hash = keccak256(&code); - SystemContractSpec::new(SEEDED_ADDR, code, code_hash) - .with_seed(Vec::from([(SEED_SLOT, U256::from(42))])) - .with_force_create_on_upgrade(force_create_on_upgrade) - } - - /// An in-place upgrade that does NOT recreate the account must not write seed - /// slots: doing so would mix genesis storage into preserved live storage and - /// record a wrong `original_value`. Guards the `force_create_on_upgrade = - /// false` + non-empty `seed` configuration that no current contract uses. - #[test] - fn test_seed_skipped_on_storage_preserving_upgrade() { - let mut db = InMemoryDB::default(); - // Pre-existing account with different bytecode (so the upgrade path runs) - // and a live value at the slot the spec would otherwise seed. - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - db.insert_account_storage(SEEDED_ADDR, SEED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_touched()); - assert!(!account.is_created(), "storage-preserving upgrade must not recreate"); - assert!( - !account.storage.contains_key(&SEED_SLOT), - "seed must not be written when storage is preserved" - ); - - // Committing the upgrade must leave the pre-existing slot at its old value. - state.commit(result); - assert_eq!( - state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), - U256::from(99), - "preserved storage must keep its pre-upgrade value after commit" - ); - } - - /// The same spec with `force_create_on_upgrade = true` recreates the account - /// and therefore does seed — the path the `SequencerRegistry` relies on. - #[test] - fn test_seed_written_on_force_created_upgrade() { - let mut db = InMemoryDB::default(); - let existing_code = Bytes::from_static(&[0xfe]); - db.insert_account_info( - SEEDED_ADDR, - AccountInfo { - balance: U256::from(1), - nonce: 1, - code_hash: keccak256(&existing_code), - code: Some(Bytecode::new_raw(existing_code)), - }, - ); - // An unrelated live slot that recreation must clear. - db.insert_account_storage(SEEDED_ADDR, UNRELATED_SLOT, U256::from(99)).unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(true)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "force_create_on_upgrade must recreate"); - let slot = account.storage.get(&SEED_SLOT).expect("seed slot must be written"); - assert_eq!(slot.present_value, U256::from(42)); - assert_eq!(slot.original_value, U256::ZERO); - - // Recreation clears prior storage: after commit the seed slot holds its - // value and the unrelated pre-existing slot reads back as zero. - state.commit(result); - assert_eq!(state.storage(SEEDED_ADDR, SEED_SLOT).unwrap(), U256::from(42)); - assert_eq!( - state.storage(SEEDED_ADDR, UNRELATED_SLOT).unwrap(), - U256::ZERO, - "recreation must clear unrelated pre-existing storage" - ); - } - - /// A fresh deploy seeds regardless of `force_create_on_upgrade`. - #[test] - fn test_seed_written_on_fresh_deploy() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy(&mut state, &seeded_spec(false)).unwrap(); - let account = result.get(&SEEDED_ADDR).unwrap(); - - assert!(account.is_created(), "fresh deploy creates the account"); - assert_eq!( - account.storage.get(&SEED_SLOT).expect("seed slot must be written").present_value, - U256::from(42) - ); - } - - #[test] - fn test_registry_oracle_version_by_spec() { - // Only MiniRex active: Oracle v1.0.0, force-created on upgrade (pre-Rex5), - // and just Oracle + high-precision Oracle. - let mini = - MegaHardforkConfig::default().with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)); - let mini = flat_system_contract_specs(&mini, 0); - assert_eq!(mini.len(), 2); - assert_eq!(mini[0].code_hash, ORACLE_CONTRACT_CODE_HASH); - assert!(mini[0].force_create_on_upgrade); - - // Rex2 active but not Rex5: Oracle v1.1.0, still force-created on upgrade. - let rex2 = MegaHardforkConfig::default() - .with(MegaHardfork::MiniRex, ForkCondition::Timestamp(0)) - .with(MegaHardfork::Rex2, ForkCondition::Timestamp(0)); - let rex2 = flat_system_contract_specs(&rex2, 0); - assert_eq!(rex2[0].code_hash, ORACLE_CONTRACT_CODE_HASH_REX2); - assert!(rex2[0].force_create_on_upgrade); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs b/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs deleted file mode 100644 index a87f1be64..000000000 --- a/crates/mega-evm/tests/_pending/src/system/keyless_deploy.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/keyless_deploy.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/keyless_deploy.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use crate::MegaHardforkConfig; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_deploy_keyless_deploy_contract_on_fresh_db() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert!(account.is_touched()); - assert!(account.is_created(), "fresh deploy must mark account as created"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - } - - /// Covers the `account_existed = true` branch: an account already exists with wrong code, - /// so the deploy updates the code without marking the account as created. - #[test] - fn test_deploy_keyless_deploy_contract_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - KEYLESS_DEPLOY_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_keyless_deploy_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&KEYLESS_DEPLOY_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, KEYLESS_DEPLOY_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "in-place bytecode update of an existing account must not mark it as created" - ); - } - -} diff --git a/crates/mega-evm/tests/_pending/src/system/limit_control.rs b/crates/mega-evm/tests/_pending/src/system/limit_control.rs deleted file mode 100644 index b0e5cf5ce..000000000 --- a/crates/mega-evm/tests/_pending/src/system/limit_control.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/limit_control.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/limit_control.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{keccak256, B256}; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - use crate::{MegaHardfork, MegaHardforkConfig}; - use alloy_hardforks::ForkCondition; - - #[test] - fn test_limit_control_contract_code_hash_matches() { - let computed_hash = keccak256(&LIMIT_CONTROL_CODE); - assert_eq!(computed_hash, LIMIT_CONTROL_CODE_HASH); - } - - #[test] - fn test_deploy_limit_control_contract_on_fresh_db() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_limit_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&LIMIT_CONTROL_ADDRESS).unwrap(); - - assert!(account.is_touched()); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, LIMIT_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), LIMIT_CONTROL_CODE); - } - - #[test] - fn test_deploy_limit_control_contract_is_idempotent() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - LIMIT_CONTROL_ADDRESS, - AccountInfo { - balance: Default::default(), - nonce: 0, - code_hash: LIMIT_CONTROL_CODE_HASH, - code: Some(Bytecode::new_raw(LIMIT_CONTROL_CODE)), - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_limit_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&LIMIT_CONTROL_ADDRESS).unwrap(); - - assert_eq!(account.info.code_hash, LIMIT_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), LIMIT_CONTROL_CODE); - assert!(!account.is_created(), "idempotent deploy should not re-create the account"); - } - - #[test] - fn test_deploy_limit_control_contract_at_later_timestamp() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = - MegaHardforkConfig::default().with(MegaHardfork::Rex4, ForkCondition::Timestamp(50)); - - assert_eq!( - transact_deploy_limit_control_contract(&hardforks, 49, &mut state).unwrap(), - None, - "should not deploy before Rex4 activation" - ); - - let result = - transact_deploy_limit_control_contract(&hardforks, 50, &mut state).unwrap().unwrap(); - let account = result.get(&LIMIT_CONTROL_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, LIMIT_CONTROL_CODE_HASH); - } - - #[test] - fn test_deploy_limit_control_contract_overwrites_wrong_existing_code_hash() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - LIMIT_CONTROL_ADDRESS, - AccountInfo { - balance: Default::default(), - nonce: 0, - code_hash: B256::ZERO, - code: Some(Bytecode::new_raw(alloy_primitives::Bytes::from_static(&[0x60, 0x00]))), - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = - transact_deploy_limit_control_contract(&hardforks, 0, &mut state).unwrap().unwrap(); - let account = result.get(&LIMIT_CONTROL_ADDRESS).unwrap(); - - assert_eq!(account.info.code_hash, LIMIT_CONTROL_CODE_HASH); - assert_eq!(account.info.code.as_ref().unwrap().original_bytes(), LIMIT_CONTROL_CODE); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "in-place bytecode update of an existing account must not mark it as created" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/oracle.rs b/crates/mega-evm/tests/_pending/src/system/oracle.rs deleted file mode 100644 index c85499e48..000000000 --- a/crates/mega-evm/tests/_pending/src/system/oracle.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/oracle.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/oracle.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use crate::MegaHardforkConfig; - - use super::*; - use alloy_primitives::keccak256; - use revm::{ - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - #[test] - fn test_deploy_oracle_contract_on_fresh_db() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5, so we expect Rex5 (v2.0.0) bytecode - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&ORACLE_CONTRACT_ADDRESS), - "State changes should contain oracle contract address" - ); - - // Verify the account in the state changes - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info (Rex5 = v2.0.0 bytecode) - let info = &account.info; - assert_eq!( - info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match the v2.0.0 value" - ); - assert!(info.code.is_some(), "Code should be set"); - - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - ORACLE_CONTRACT_CODE_REX5, - "Code bytes should match the v2.0.0 value" - ); - } - - #[test] - fn test_deploy_oracle_contract_idempotent() { - // Create a database with the oracle contract already deployed correctly (Rex5 = v2.0.0) - let mut db = InMemoryDB::default(); - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: ORACLE_CONTRACT_CODE_HASH_REX5, - code: Some(Bytecode::new_raw(ORACLE_CONTRACT_CODE_REX5)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should return state with the account marked as read (no update needed) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - assert_eq!( - result.len(), - 1, - "Deployment should return state with account marked as read when contract is already correctly deployed" - ); - - // Verify the account is in the result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should match v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_with_wrong_code_hash() { - // Create a database with the oracle address already having different code - let mut db = InMemoryDB::default(); - - // Insert an account with wrong code hash at the oracle address - let wrong_code = bytes!("0x6000"); - let wrong_code_hash = keccak256(&wrong_code); - - db.insert_account_info( - ORACLE_CONTRACT_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - // with_all_activated() includes Rex2 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy should update the contract with correct code (Rex5 = v2.0.0 bytecode) - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned (contract was updated) - assert_eq!(result.len(), 1, "Should have state changes to update the contract"); - - // Verify the updated account has the correct code hash - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Code hash should be updated to v2.0.0 bytecode" - ); - } - - #[test] - fn test_deploy_oracle_contract_marks_account_as_touched() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the oracle contract - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Get the account from result - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist in result"); - - // Verify the account is marked as touched (required for state changes to be committed) - assert!( - account.is_touched(), - "Deployed account must be marked as touched for state changes to take effect" - ); - assert!(account.is_created(), "Account should be marked as created"); - } - - #[test] - fn test_deploy_oracle_contract_rex5() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - // Activate all including Rex5 - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_oracle_contract(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = result.get(&ORACLE_CONTRACT_ADDRESS).expect("Account should exist"); - assert_eq!( - account.info.code_hash, ORACLE_CONTRACT_CODE_HASH_REX5, - "Should deploy v2.0.0 bytecode on Rex5" - ); - } - - #[test] - fn test_high_precision_timestamp_oracle_deployment() { - // Create a fresh in-memory database - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - // Deploy the high precision timestamp oracle contract - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - // Verify that state changes were returned - assert_eq!(result.len(), 1, "Should have state changes for one account"); - assert!( - result.contains_key(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS), - "State changes should contain high precision timestamp oracle address" - ); - - // Verify the account in the state changes - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert!(account.is_touched(), "Account should be marked as touched"); - assert!(account.is_created(), "Account should be marked as created"); - - // Verify the account info - let info = &account.info; - assert_eq!( - info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash should match the expected value" - ); - assert!(info.code.is_some(), "Code should be set"); - - // Verify code matches - let code = info.code.as_ref().unwrap(); - assert_eq!( - code.original_bytes(), - HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, - "Code bytes should match the expected value" - ); - - // Verify code hash matches computed hash - let computed_hash = keccak256(&HIGH_PRECISION_TIMESTAMP_ORACLE_CODE); - assert_eq!( - computed_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, - "Code hash constant should match computed hash" - ); - } - - /// Covers the `account_existed = true` branch in - /// `transact_deploy_high_precision_timestamp_oracle`: when the account already exists with - /// wrong code, the deploy updates the code without marking the account as created. - #[test] - fn test_high_precision_timestamp_oracle_existing_account_not_marked_created() { - let wrong_code = alloy_primitives::bytes!("0x6000"); - let wrong_code_hash = alloy_primitives::keccak256(&wrong_code); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, - AccountInfo { - balance: revm::primitives::U256::ZERO, - nonce: 0, - code_hash: wrong_code_hash, - code: Some(Bytecode::new_raw(wrong_code)), - }, - ); - - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = MegaHardforkConfig::default().with_all_activated(); - - let result = transact_deploy_high_precision_timestamp_oracle(&hardforks, 0, &mut state) - .expect("Deployment should succeed") - .expect("Should return state"); - - let account = - result.get(&HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS).expect("Account should exist"); - assert_eq!(account.info.code_hash, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH); - assert!(account.is_touched()); - assert!( - !account.is_created(), - "existing account must not be marked as created on code update" - ); - } -} diff --git a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs b/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs deleted file mode 100644 index 8c7612abb..000000000 --- a/crates/mega-evm/tests/_pending/src/system/sequencer_registry.rs +++ /dev/null @@ -1,778 +0,0 @@ -//! Unit tests extracted from `crates/mega-evm/src/system/sequencer_registry.rs` when the Satin skeleton replaced the legacy core. -//! The code they test is at `git show a8f8c7c9:crates/mega-evm/src/system/sequencer_registry.rs`. -//! Owning mechanisms are listed in `tests/_pending/README.md`. - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::{address, keccak256, B256}; - use mega_system_contracts::sequencer_registry::storage_slots::PENDING_ADMIN; - use revm::{ - context::BlockEnv, - database::InMemoryDB, - state::{AccountInfo, Bytecode}, - }; - - use crate::{MegaHardforkConfig, MegaSpecId}; - - const TEST_SEQUENCER: Address = address!("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); - const TEST_ADMIN: Address = address!("0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); - /// A non-system test address, used as a stand-in for a `_currentSystemAddress` that has - /// already been rotated away from the genesis `MEGA_SYSTEM_ADDRESS`. Distinct from - /// genesis so tests can tell the two apart. - const TEST_SYSTEM_ADDRESS: Address = address!("0xA887dCB9D5f39Ef79272801d05Abdf707CFBbD1d"); - - const TEST_MIN_ROTATION_DELAY: u64 = 100; - - fn test_config() -> SequencerRegistryConfig { - SequencerRegistryConfig { - rex5_initial_sequencer: TEST_SEQUENCER, - rex5_initial_admin: TEST_ADMIN, - } - } - - fn test_rex6_config() -> SequencerRegistryRex6Config { - SequencerRegistryRex6Config { rex6_min_rotation_delay: TEST_MIN_ROTATION_DELAY } - } - - /// A chain running Rex5: the pre-upgrade world where the registry runs v1.0.0. - fn rex5_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX5) - .with_params(test_config()) - } - - /// All hardforks including Rex6, with both registry param sets attached. - fn rex6_hardforks() -> MegaHardforkConfig { - MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()) - .with_params(test_rex6_config()) - } - - /// Verifies that Rust slot constants match the Solidity storage layout. - /// These values come from `forge inspect SequencerRegistry storage-layout`. - /// If the Solidity field order changes, this test MUST be updated. - #[test] - fn test_slot_constants_match_solidity_layout() { - assert_eq!(CURRENT_SYSTEM_ADDRESS, U256::from(0), "_currentSystemAddress = slot 0"); - assert_eq!(CURRENT_SEQUENCER, U256::from(1), "_currentSequencer = slot 1"); - assert_eq!(ADMIN, U256::from(2), "_admin = slot 2"); - assert_eq!(PENDING_ADMIN, U256::from(3), "_pendingAdmin = slot 3"); - assert_eq!(INITIAL_SYSTEM_ADDRESS, U256::from(4), "_initialSystemAddress = slot 4"); - assert_eq!(INITIAL_SEQUENCER, U256::from(5), "_initialSequencer = slot 5"); - assert_eq!(INITIAL_FROM_BLOCK, U256::from(6), "_initialFromBlock = slot 6"); - assert_eq!(PENDING_SYSTEM_ADDRESS, U256::from(7), "_pendingSystemAddress = slot 7"); - assert_eq!( - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(8), - "_systemAddressActivationBlock = slot 8" - ); - assert_eq!(PENDING_SEQUENCER, U256::from(9), "_pendingSequencer = slot 9"); - assert_eq!( - SEQUENCER_ACTIVATION_BLOCK, - U256::from(10), - "_sequencerActivationBlock = slot 10" - ); - // Slots 11 (_systemAddressHistory) and 12 (_sequencerHistory) are dynamic arrays. - assert_eq!(MIN_ROTATION_DELAY, U256::from(13), "_minRotationDelay = slot 13 (v2.0.0+)"); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_sequencer() { - let mut config = test_config(); - config.rex5_initial_sequencer = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_sequencer must be rejected"); - assert!( - err.message.contains("rex5_initial_sequencer must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_validate_rejects_zero_rex5_initial_admin() { - let mut config = test_config(); - config.rex5_initial_admin = Address::ZERO; - let err = config.validate().expect_err("zero rex5_initial_admin must be rejected"); - assert!( - err.message.contains("rex5_initial_admin must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_validate_rejects_zero_min_rotation_delay() { - let config = SequencerRegistryRex6Config { rex6_min_rotation_delay: 0 }; - let err = config.validate().expect_err("zero rex6_min_rotation_delay must be rejected"); - assert!( - err.message.contains("rex6_min_rotation_delay must not be zero"), - "unexpected message: {}", - err.message, - ); - } - - #[test] - fn test_deploy_fresh_at_rex6_seeds_v2_with_min_rotation_delay() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!( - account.storage.len(), - 7, - "fresh Rex6 deploy writes the 6 bootstrap slots plus _minRotationDelay" - ); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - assert_eq!( - account.storage.get(&ADMIN).unwrap().present_value(), - U256::from_be_bytes(TEST_ADMIN.into_word().0), - ); - assert_eq!( - account.storage.get(&INITIAL_FROM_BLOCK).unwrap().present_value(), - U256::from(1000), - ); - } - - #[test] - fn test_deploy_rex6_is_idempotent_when_v2_present() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(!account.is_created(), "idempotent deploy should not re-create"); - assert!(!account.is_touched(), "idempotent deploy should not touch the account"); - assert!(account.storage.is_empty(), "idempotent deploy should not write storage"); - } - - #[test] - fn test_deploy_rex6_missing_config_errors() { - // Rex6 active but only the Rex5 params attached: deploy must fail fast instead of - // installing a v2.0.0 registry with an unseeded _minRotationDelay. - let hardforks = MegaHardforkConfig::default() - .with_all_activated_through(MegaSpecId::REX6) - .with_params(test_config()); - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = - transact_deploy_sequencer_registry(&hardforks, 0, 1000, &mut state, &test_config()) - .expect_err("missing Rex6 params must fail closed"); - assert!( - err.to_string().contains("SequencerRegistryRex6Config not configured"), - "unexpected message: {err}" - ); - } - - #[test] - fn test_deploy_rex6_on_top_of_eoa_with_balance() { - let mut db = InMemoryDB::default(); - // Simulate an EOA that received ETH before the registry was ever deployed. Even at - // Rex6 this is a fresh bootstrap, not a storage-preserving upgrade: the full seed - // (including _minRotationDelay) must be written. - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { balance: U256::from(1_000_000), ..Default::default() }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 1000, - &mut state, - &test_config(), - ) - .unwrap() - .unwrap(); - - let account = result.get(&SEQUENCER_REGISTRY_ADDRESS).unwrap(); - assert!(account.is_created()); - assert_eq!(account.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH_REX6); - assert_eq!(account.info.balance, U256::from(1_000_000)); - assert_eq!(account.storage.len(), 7); - assert_eq!( - account.storage.get(&MIN_ROTATION_DELAY).unwrap().present_value(), - U256::from(TEST_MIN_ROTATION_DELAY), - ); - } - - #[test] - fn test_deploy_rex6_wrong_existing_code_hash_errors() { - let wrong_code = Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00])); - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: wrong_code.hash_slow(), - code: Some(wrong_code), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = transact_deploy_sequencer_registry( - &rex6_hardforks(), - 0, - 2000, - &mut state, - &test_config(), - ) - .expect_err("wrong code hash must fail closed"); - - let msg = err.to_string(); - assert!(msg.contains("unexpected code hash"), "unexpected message: {msg}"); - assert!(msg.contains("refusing to overwrite"), "unexpected message: {msg}"); - } - - #[test] - fn test_resolve_rex6_expects_v2_code_hash() { - // A V2 registry resolves normally at REX6. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH_REX6, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE_REX6)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - assert!(witness.is_some()); - } - - #[test] - fn test_resolve_rex6_rejects_v1_code_hash() { - // At REX6 the pre-block deploy has already upgraded the bytecode, so a V1 code hash at - // resolve time is a broken pipeline and must fail closed. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex6_hardforks(), MegaSpecId::REX6, &mut state) - .expect_err("V1 code hash at REX6 must fail closed"); - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_resolve_rex5_returns_stored_system_address_with_witness() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (addr, witness) = - resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state).unwrap(); - assert_eq!(addr, TEST_SYSTEM_ADDRESS); - - // Witness must capture the registry account and the CURRENT_SYSTEM_ADDRESS slot. - let witness = witness.expect("post-deploy resolve must produce witness"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("registry account in witness"); - assert_eq!(acc.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); - assert!( - acc.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), - "witness must include CURRENT_SYSTEM_ADDRESS slot" - ); - assert_eq!(acc.storage.len(), 1, "witness should contain exactly one slot"); - let slot = acc.storage.get(&CURRENT_SYSTEM_ADDRESS).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - - #[test] - fn test_resolve_rex5_zero_slot_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let result = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state); - assert!(result.is_err(), "zero _currentSystemAddress should be an error"); - } - - #[test] - fn test_resolve_rex5_missing_registry_errors() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - let hardforks = rex5_hardforks(); - - let err = resolve_system_address(&hardforks, MegaSpecId::REX5, &mut state) - .expect_err("missing registry at Rex5 must fail closed"); - assert!(err.to_string().contains("does not exist")); - } - - #[test] - fn test_resolve_rex5_wrong_code_hash_errors() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: B256::ZERO, - code: Some(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let err = resolve_system_address(&rex5_hardforks(), MegaSpecId::REX5, &mut state) - .expect_err("wrong code hash must fail closed"); - - assert!(err.to_string().contains("code hash mismatch")); - } - - #[test] - fn test_is_apply_pending_changes_due_no_registry() { - let mut db = InMemoryDB::default(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must contain a not-existing account entry. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert_eq!(acc.status, revm::state::AccountStatus::LoadedAsNotExisting); - assert!(acc.storage.is_empty(), "no-registry witness should have no slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_no_pending() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(!due); - // Witness must include both PENDING_* slots (both zero = no change pending). - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness should exist"); - assert!( - acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS), - "witness must include PENDING_SYSTEM_ADDRESS" - ); - assert!( - acc.storage.contains_key(&PENDING_SEQUENCER), - "witness must include PENDING_SEQUENCER" - ); - // No activation slots needed because both pending values are zero. - assert_eq!(acc.storage.len(), 2, "no-pending witness should have exactly 2 slots"); - } - - #[test] - fn test_is_apply_pending_changes_due_system_address_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_addr = address!("0x1111111111111111111111111111111111111111"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_addr.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - // Not yet due at block 999. - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 999).unwrap(); - assert!(!due, "not yet due"); - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - - // Exactly due at block 1000 (fresh State to avoid cache from prior call). - let mut state = State::builder().with_database(&mut db).build(); - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!(due, "exactly due"); - // Both roles' pending slots are always read into the witness. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - } - - #[test] - fn test_is_apply_pending_changes_due_sequencer_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(500), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 500).unwrap(); - assert!(due); - // System address has no pending change (slot is zero) so only PENDING_SYSTEM_ADDRESS - // is read. Then sequencer path reads PENDING_SEQUENCER + SEQUENCER_ACTIVATION_BLOCK. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 3); - } - - #[test] - fn test_is_apply_pending_changes_due_checks_sequencer_when_system_not_due() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - let new_sys = address!("0x1111111111111111111111111111111111111111"); - let new_seq = address!("0x2222222222222222222222222222222222222222"); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - new_sys.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1001), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - new_seq.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - let mut state = State::builder().with_database(&mut db).build(); - - let (due, witness) = is_apply_pending_changes_due(&mut state, 1000).unwrap(); - assert!( - due, - "sequencer change should still trigger the pre-block call when the system address is not due yet" - ); - // System address is not due (activation at 1001) but its pending slot + activation - // slot are still read. Then the sequencer path reads its own pending + activation. - let acc = witness.get(&SEQUENCER_REGISTRY_ADDRESS).expect("witness"); - assert!(acc.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); - assert!(acc.storage.contains_key(&SYSTEM_ADDRESS_ACTIVATION_BLOCK)); - assert!(acc.storage.contains_key(&PENDING_SEQUENCER)); - assert!(acc.storage.contains_key(&SEQUENCER_ACTIVATION_BLOCK)); - assert_eq!(acc.storage.len(), 4, "both roles' slots should be in the witness"); - for slot_key in [ - PENDING_SYSTEM_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - PENDING_SEQUENCER, - SEQUENCER_ACTIVATION_BLOCK, - ] { - let slot = acc.storage.get(&slot_key).expect("slot must exist"); - assert!(!slot.is_changed(), "read-only witness slot must not be marked changed"); - assert_eq!(slot.original_value(), slot.present_value()); - } - } - - #[test] - fn test_transact_apply_pending_changes_updates_and_clears_due_roles() { - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let next_system_address = address!("0x1111111111111111111111111111111111111111"); - let next_sequencer = address!("0x2222222222222222222222222222222222222222"); - - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - TEST_SYSTEM_ADDRESS.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SEQUENCER, - TEST_SEQUENCER.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SYSTEM_ADDRESS, - next_system_address.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - PENDING_SEQUENCER, - next_sequencer.into_word().into(), - ) - .unwrap(); - db.insert_account_storage( - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - U256::from(1000), - ) - .unwrap(); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let result = - transact_apply_pending_changes(&mut evm).expect("applyPendingChanges() should succeed"); - let state = result.state; - drop(evm); - - revm::DatabaseCommit::commit(&mut db, state); - - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS) - .unwrap(), - address_to_storage_value(next_system_address), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, CURRENT_SEQUENCER) - .unwrap(), - address_to_storage_value(next_sequencer), - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage(&mut db, SEQUENCER_REGISTRY_ADDRESS, PENDING_SEQUENCER) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SYSTEM_ADDRESS_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - assert_eq!( - revm::Database::storage( - &mut db, - SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_ACTIVATION_BLOCK, - ) - .unwrap(), - U256::ZERO, - ); - } - - #[test] - fn test_transact_apply_pending_changes_uses_block_gas_limit() { - // Block gas_limit > 30M must be passed through to the system call so that - // applyPendingChanges() can absorb the variable cost from REX dynamic - // storage gas instead of being capped at the upstream-fixed 30M. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 250_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!(revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, 250_000_000); - } - - #[test] - fn test_transact_apply_pending_changes_respects_30m_floor() { - // When the block gas limit is below the 30M floor, the system call must - // still receive at least the historical default budget. - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: SEQUENCER_REGISTRY_CODE_HASH, - code: Some(Bytecode::new_raw(SEQUENCER_REGISTRY_CODE)), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 1_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - transact_apply_pending_changes(&mut evm).expect("system call should succeed"); - assert_eq!( - revm::handler::EvmTr::ctx_ref(&evm).tx.base.gas_limit, - crate::constants::rex5::SYSTEM_CALL_GAS_LIMIT_FLOOR, - ); - } - - #[test] - fn test_transact_apply_pending_changes_errors_when_registry_reverts() { - let revert_code = Bytecode::new_legacy(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd])); - - let mut db = InMemoryDB::default(); - db.insert_account_info( - SEQUENCER_REGISTRY_ADDRESS, - AccountInfo { - code_hash: revert_code.hash_slow(), - code: Some(revert_code), - ..Default::default() - }, - ); - - let block = - BlockEnv { number: U256::from(1000), gas_limit: 30_000_000, ..Default::default() }; - let mut context = crate::MegaContext::new(&mut db, MegaSpecId::REX5).with_block(block); - context.modify_chain(|chain| { - chain.operator_fee_scalar = Some(U256::ZERO); - chain.operator_fee_constant = Some(U256::ZERO); - }); - let mut evm = crate::MegaEvm::new(context); - - let err = transact_apply_pending_changes(&mut evm) - .expect_err("reverting registry bytecode must fail closed"); - - assert!(err.to_string().contains("reverted or halted")); - } -} diff --git a/crates/mega-evm/tests/block/activation.rs b/crates/mega-evm/tests/block/activation.rs new file mode 100644 index 000000000..d3ddf5e54 --- /dev/null +++ b/crates/mega-evm/tests/block/activation.rs @@ -0,0 +1,229 @@ +//! The activation-block rule as a node applies it. +//! +//! Block execution does not work out whether a block admits only deposits: it is told, through +//! [`MegaBlockExecutionCtx::no_user_tx_activation_block`]. A node works it out from its schedule +//! and the parent block's timestamp ([`MegaHardforks::admits_only_deposits`]) for every block it +//! builds or validates. The tests here build each block's context that way, from a schedule, and +//! run the block: a user transaction is refused exactly in the blocks the rule names, and a +//! deposit runs in every block. + +use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; +use alloy_hardforks::{EthereumHardfork, ForkCondition}; +use alloy_op_hardforks::OpHardfork; +use alloy_primitives::{Bytes, U256}; +use mega_evm::{ + system::SYSTEM_CONTRACT_COUNT, test_utils::CommittedStates, BlockLimits, MegaBlockExecutionCtx, + MegaBlockExecutionError, MegaHardfork, MegaHardforkConfig, MegaHardforks, +}; + +use crate::common::{ + self, block_ctx, deposit_tx, empty_call_gas, executor_with_env_and_spec, user_tx, +}; + +/// The timestamp the fork each case schedules activates at. +const ACTIVATION: u64 = common::BLOCK_TIMESTAMP; + +/// A timestamp after [`ACTIVATION`] that a case moves a later fork to, so the schedule keeps the +/// forks in their order without that fork activating in the blocks the case runs. +const LATER: u64 = ACTIVATION + 1_000; + +/// A schedule with every Ethereum and Optimism fork up to Karst at genesis and Satin at `satin`. +fn schedule(satin: u64) -> MegaHardforkConfig { + MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(satin)) +} + +/// The context of the block at `timestamp`, whose parent is at `parent_timestamp`, as a node +/// builds it: both switches come from the schedule and the parent's timestamp. +fn node_ctx( + spec: &MegaHardforkConfig, + parent_timestamp: u64, + timestamp: u64, +) -> MegaBlockExecutionCtx { + block_ctx(BlockLimits::no_limits()) + .with_no_user_tx_activation_block(spec.admits_only_deposits(parent_timestamp, timestamp)) + .with_satin_activation_block(spec.is_satin_activation_block(parent_timestamp, timestamp)) +} + +/// Whether `error` is the activation-block refusal. +fn is_activation_refusal(error: &BlockExecutionError) -> bool { + matches!( + error.as_validation(), + Some(BlockValidationError::Other(error)) + if error.downcast_ref::() + == Some(&MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock) + ) +} + +/// Runs the block at `timestamp` on the chain `spec` describes, its parent at +/// `parent_timestamp`: a user transaction, then a deposit. Answers whether the user transaction +/// was refused by the activation-block rule, having checked that the deposit runs either way and +/// that a user transaction the rule admits runs. +fn refuses_a_user_transaction( + name: &str, + spec: MegaHardforkConfig, + parent_timestamp: u64, + timestamp: u64, +) -> bool { + let mut env = common::evm_env(); + env.block_env.timestamp = U256::from(timestamp); + let ctx = node_ctx(&spec, parent_timestamp, timestamp); + let mut state = common::state(); + let mut executor = executor_with_env_and_spec(&mut state, ctx, env, spec); + executor.apply_pre_execution_changes().unwrap_or_else(|e| panic!("{name}: starts: {e}")); + + let refused = match executor.execute_transaction(&user_tx(0, empty_call_gas())) { + Ok(_) => false, + Err(error) => { + assert!(is_activation_refusal(&error), "{name}: refused for another reason: {error}"); + true + } + }; + executor + .execute_transaction(&deposit_tx(Bytes::new(), empty_call_gas())) + .unwrap_or_else(|e| panic!("{name}: a deposit runs in every block: {e}")); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + let packed = if refused { 1 } else { 2 }; + assert_eq!(result.receipts().len(), packed, "{name}: what the block packed"); + assert!(result.receipts().iter().all(|receipt| receipt.status()), "{name}: both succeed"); + refused +} + +/// [S1.8] [S21.12] [S1] A node's context, built from its schedule and the parent's timestamp, +/// refuses a user transaction in the block in which Satin or an Optimism fork at or after Jovian +/// activates, and in no other block; a deposit runs in all of them. +/// +/// A fork activates in a block when it is active at the block's timestamp and not at the +/// parent's: the first block at the activation, and the first block after a gap over it, but +/// not the block after the activation block. Isthmus, the Optimism fork before Jovian, and an +/// Ethereum fork are not in the rule. Each case keeps the Optimism forks in their order, moving +/// the ones after the activating fork to a later timestamp. +/// +/// Expected values: independent (the rule's clauses, case by case). +#[test] +fn test_a_node_context_refuses_a_user_transaction_where_a_fork_activates() { + let at = ACTIVATION; + let satin_at_genesis = || schedule(0); + let cases = [ + ("Satin's activation block", schedule(at), at - 1, at, true), + ( + "the first block after a gap over Satin's activation", + schedule(at), + at - 10, + at + 5, + true, + ), + ("the block after Satin's activation block", schedule(at), at, at + 1, false), + ( + "Jovian's activation block", + satin_at_genesis() + .with(OpHardfork::Jovian, ForkCondition::Timestamp(at)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), + at - 1, + at, + true, + ), + ( + "the block after Jovian's activation block", + satin_at_genesis() + .with(OpHardfork::Jovian, ForkCondition::Timestamp(at)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), + at, + at + 1, + false, + ), + ( + "Isthmus's activation block", + satin_at_genesis() + .with(OpHardfork::Isthmus, ForkCondition::Timestamp(at)) + .with(OpHardfork::Jovian, ForkCondition::Timestamp(LATER)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), + at - 1, + at, + false, + ), + ( + "Osaka's activation block", + satin_at_genesis() + .with(EthereumHardfork::Osaka, ForkCondition::Timestamp(at)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), + at - 1, + at, + false, + ), + ]; + for (name, spec, parent, timestamp, expected) in cases { + assert_eq!(refuses_a_user_transaction(name, spec, parent, timestamp), expected, "{name}"); + } +} + +/// [S1] The rule follows the Optimism fork order the dependency exports: on a chain running Satin +/// from genesis, the block in which an Optimism fork activates refuses a user transaction exactly +/// when the fork is Jovian or comes after it in [`OpHardfork::VARIANTS`], and every fork the +/// dependency lists after Jovian is one. +/// +/// The expected value is the fork's position against Jovian's, not the dependency's own +/// predicate. Expected values: independent. +#[test] +fn test_the_activation_rule_follows_the_optimism_fork_order() { + let jovian = OpHardfork::VARIANTS + .iter() + .position(|fork| *fork == OpHardfork::Jovian) + .expect("the dependency lists Jovian"); + let later = &OpHardfork::VARIANTS[jovian + 1..]; + assert!(!later.is_empty(), "the dependency lists a fork after Jovian"); + assert!(later.contains(&OpHardfork::Karst), "Karst, Satin's base, comes after Jovian"); + + for (position, fork) in OpHardfork::VARIANTS.iter().enumerate() { + let spec = schedule(0).with(*fork, ForkCondition::Timestamp(ACTIVATION)); + let name = fork.name(); + let refused = refuses_a_user_transaction(name, spec.clone(), ACTIVATION - 1, ACTIVATION); + assert_eq!(refused, position >= jovian, "{name}'s activation block"); + assert!( + !refuses_a_user_transaction(name, spec, ACTIVATION, ACTIVATION + 1), + "{name}: the block after its activation block admits a user transaction" + ); + } +} + +/// The predeploys a node's context has the block check, from its schedule and the parent's +/// timestamp: how many of the states the pre-block steps committed are reads of a predeploy. +fn predeploys_checked(spec: MegaHardforkConfig, parent_timestamp: u64, timestamp: u64) -> usize { + let mut env = common::evm_env(); + env.block_env.timestamp = U256::from(timestamp); + let ctx = node_ctx(&spec, parent_timestamp, timestamp); + let mut state = common::state(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env_and_spec(&mut state, ctx, env, spec); + executor.apply_pre_execution_changes().expect("the block starts"); + committed.states().iter().filter(|state| common::is_predeploy_check(state)).count() +} + +/// [S18] A node's context has the predeploys checked in Satin's activation block and in no other: +/// the first block at the activation and the first after a gap over it read all seven; the block +/// after the activation block, every block of a chain with Satin from genesis, and Jovian's +/// activation block on such a chain, which admits only deposits, read none. +/// +/// Expected values: independent (the schedule's own timestamps and the rule). +#[test] +fn test_a_node_context_checks_the_predeploys_where_satin_activates() { + let at = ACTIVATION; + let cases = [ + ("Satin's activation block", schedule(at), at - 1, at, SYSTEM_CONTRACT_COUNT), + ("the first block after a gap", schedule(at), at - 10, at + 5, SYSTEM_CONTRACT_COUNT), + ("the block after Satin's activation block", schedule(at), at, at + 1, 0), + ("a block of a chain with Satin from genesis", schedule(0), at - 1, at, 0), + ( + "Jovian's activation block", + schedule(0) + .with(OpHardfork::Jovian, ForkCondition::Timestamp(at)) + .with(OpHardfork::Karst, ForkCondition::Timestamp(LATER)), + at - 1, + at, + 0, + ), + ]; + for (name, spec, parent, timestamp, expected) in cases { + assert_eq!(predeploys_checked(spec, parent, timestamp), expected, "{name}"); + } +} diff --git a/crates/mega-evm/tests/block/bucket_ids.rs b/crates/mega-evm/tests/block/bucket_ids.rs new file mode 100644 index 000000000..6e671a910 --- /dev/null +++ b/crates/mega-evm/tests/block/bucket_ids.rs @@ -0,0 +1,295 @@ +//! The SALT buckets a block's execution asks about, which a stateless witness needs. +//! +//! A bucket's capacity is read through the SALT environment, a side channel no database sees, and +//! a validator that lacks a bucket's proof cannot price the charge that landed in it. The block +//! executor exports every bucket the block asked about, across all of its transactions: the +//! per-transaction multiplier cache is forgotten before every transaction, so a record that lived +//! there would lose every transaction's buckets but the last one's. + +use alloy_consensus::Sealed; +use alloy_eips::eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}; +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor, InternalBlockExecutionError}, + EvmFactory, +}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + test_utils::{CommittedStates, MemoryDatabase}, + BlockLimits, BucketId, LimitUsage, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvm, + MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, SaltEnv, TestExternalEnvs, +}; +use op_alloy_consensus::TxDeposit; +use revm::{context::ContextTr, database::State, inspector::NoOpInspector, Database}; + +use crate::common::{self, system_tx, CALLER, CONTRACT}; + +/// The contract whose slots the block's transactions write. +const WRITER: Address = address!("0x1000000000000000000000000000000000000b1d"); + +/// Room for a slot's first write at the byte prices in effect, and for a keyless-sized body. +const TX_GAS_LIMIT: u64 = 10_000_000; + +/// The external environments of these tests, which can make a bucket's lookup fail. +type Envs = TestExternalEnvs; + +/// The executor these tests drive. +type Executor<'a> = MegaBlockExecutor< + MegaEvm<&'a mut State, NoOpInspector, Envs>, + OpAlloyReceiptBuilder, + MegaHardforkConfig, +>; + +/// The bucket the slot `slot` of [`WRITER`] lives in. +fn slot_bucket(slot: u8) -> BucketId { + ::bucket_id_for_slot(WRITER, U256::from(slot)) +} + +/// A state holding the writer, the empty callee and the caller's balance. +fn state() -> State { + let mut db = common::database(); + db.set_account_code(WRITER, common::writer()); + State::builder().with_database(db).build() +} + +/// An executor over `state` reading `envs`. +fn executor(state: &mut State, envs: Envs) -> Executor<'_> { + let evm = + MegaEvmFactory::new().with_external_env_factory(envs).create_evm(state, common::evm_env()); + MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ) +} + +/// The transaction of `nonce` that writes the fresh slot `slot` of [`WRITER`]. +fn write( + nonce: u64, + slot: u8, +) -> alloy_consensus::transaction::Recovered { + common::recovered(common::tx(nonce, WRITER, vec![slot].into(), TX_GAS_LIMIT)) +} + +/// The record accumulates over the block's transactions where the per-transaction cache does +/// not, holds each bucket once, and can be cleared between transactions to attribute the asks. +/// Clearing changes no execution result. +#[test] +fn test_accessed_bucket_ids_accumulate_over_the_block() { + // Where a state byte is free the engine prices no charge and asks about no bucket. + if common::state_is_free() { + return; + } + let envs = Envs::new(); + let mut state = state(); + let mut executor = executor(&mut state, envs.clone()); + executor.apply_pre_execution_changes().expect("the block starts"); + assert!(executor.get_accessed_bucket_ids().is_empty(), "the pre-block phase asked nothing"); + + let mut expected = vec![]; + for (nonce, slot) in [(0, 1), (1, 2), (2, 3)] { + let outcome = executor.run_transaction(&write(nonce, slot)).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, common::slot_state_gas(), "a fresh slot, priced"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + expected.push(slot_bucket(slot)); + expected.sort_unstable(); + assert_eq!( + executor.get_accessed_bucket_ids(), + expected, + "after the write of slot {slot}: every bucket the block asked about so far" + ); + assert_eq!( + executor.evm().ctx().bucket_multipliers().cached_buckets().collect::>(), + vec![slot_bucket(slot)], + "the cache holds the running transaction's bucket alone" + ); + } + for slot in [1, 2, 3] { + assert_eq!(envs.bucket_queries(slot_bucket(slot)), 1, "the environment was asked once"); + } + + // Clearing attributes the asks that follow to one transaction. + executor.clear_accessed_bucket_ids(); + assert!(executor.get_accessed_bucket_ids().is_empty()); + let outcome = executor.run_transaction(&write(3, 7)).expect("it executes"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + assert_eq!(executor.get_accessed_bucket_ids(), vec![slot_bucket(7)]); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 4, "clearing packed nothing differently"); +} + +/// The record covers one block: an EVM carried over to the next block reports that block's +/// buckets and not the ones before it. +#[test] +fn test_two_blocks_over_the_same_evm_report_only_their_own_buckets() { + if common::state_is_free() { + return; + } + let mut state = state(); + let mut executor = executor(&mut state, Envs::new()); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor.run_transaction(&write(0, 1)).expect("it executes"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + assert_eq!(executor.get_accessed_bucket_ids(), vec![slot_bucket(1)]); + + let (evm, _) = executor.finish_with_counters().expect("the block finishes"); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ); + executor.apply_pre_execution_changes().expect("the next block starts"); + assert!(executor.get_accessed_bucket_ids().is_empty(), "the next block starts empty"); + let outcome = executor.run_transaction(&write(1, 2)).expect("it executes"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + assert_eq!( + executor.get_accessed_bucket_ids(), + vec![slot_bucket(2)], + "what the block before asked about is not this block's set" + ); +} + +/// The protocol's own work reads no bucket: a block whose EIP-2935 pre-block call writes a fresh +/// slot of the history contract and whose system transaction creates its caller leaves the +/// record empty, and the environment was never asked. +#[test] +fn test_the_pre_block_calls_and_a_system_transaction_add_no_bucket() { + let envs = Envs::new(); + let mut db = common::database(); + db = db.sequencer_registry(mega_evm::system::MEGA_SYSTEM_ADDRESS); + db.set_account_code( + mega_evm::system::ORACLE_CONTRACT_ADDRESS, + mega_evm::system::ORACLE_CONTRACT_CODE, + ); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + // A non-zero parent hash, so the EIP-2935 call's write changes the ring slot it lands in. + let evm = MegaEvmFactory::new() + .with_external_env_factory(envs.clone()) + .create_evm(&mut state, common::evm_env()); + let ctx = MegaBlockExecutionCtx::new( + B256::repeat_byte(0x11), + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + let mut executor = + MegaBlockExecutor::new(evm, ctx, common::chain_spec(), OpAlloyReceiptBuilder::default()); + executor.apply_pre_execution_changes().expect("the block starts"); + let call = common::call_state(&committed.states(), HISTORY_STORAGE_ADDRESS).clone(); + let changed = call[&HISTORY_STORAGE_ADDRESS].changed_storage_slots().count(); + assert!(changed > 0, "the EIP-2935 call wrote a slot"); + assert!(executor.get_accessed_bucket_ids().is_empty(), "priced at the minimum bucket"); + let outcome = executor.run_transaction(&system_tx()).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(executor.evm().ctx().is_system_originated()); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + assert!(executor.get_accessed_bucket_ids().is_empty()); + assert_eq!(envs.total_bucket_queries(), 0); +} + +/// What a block has committed: its receipts, its counters, the caller's nonce and balance, the +/// first slot of [`WRITER`] and the buckets it recorded. +fn committed(executor: &mut Executor<'_>) -> (usize, [u64; 6], LimitUsage, u64, U256, U256, usize) { + let limiter = executor.limiter(); + let counters = [ + limiter.block_gas_used, + limiter.gas.execution, + limiter.gas.state, + limiter.gas.history, + limiter.block_tx_size_used, + limiter.block_da_size_used, + ]; + let usage = limiter.usage; + let receipts = executor.receipts().len(); + let buckets = executor.get_accessed_bucket_ids().len(); + let db = executor.evm_mut().ctx_mut().db_mut(); + let caller = db.basic(CALLER).expect("readable").expect("the caller exists"); + let slot = db.storage(WRITER, U256::from(1)).expect("readable"); + (receipts, counters, usage, caller.nonce, caller.balance, slot, buckets) +} + +/// The internal error a transaction whose execution the node could not finish returns, with the +/// hash it names. +fn internal_evm_error(error: &BlockExecutionError) -> B256 { + match error { + BlockExecutionError::Internal(InternalBlockExecutionError::EVM { hash, .. }) => *hash, + other => panic!("not an internal error of the transaction's execution: {other:?}"), + } +} + +/// [S21.17] [S21] [S6.7] A failed bucket read is a fault of the node and gives the transaction no +/// outcome, for a deposit as for a user transaction: through the executor's own commit, each +/// returns an internal error that names the transaction and the cause, and the block commits +/// nothing for it — no receipt, nothing on the block's counters, no nonce bump, no mint, no write, +/// no bucket. A failed deposit would have bumped its sender's nonce and credited its mint; this +/// one is not settled at all. The block goes on with the next transaction once the user +/// transaction is left out. +/// +/// Expected values: independent (nothing changes). +#[test] +fn test_a_failed_bucket_read_commits_nothing_for_a_deposit_or_a_user_transaction() { + // Where a state byte is free no charge reads a bucket, so no read can fail. + if common::state_is_free() { + return; + } + let envs = Envs::new().with_failing_bucket(slot_bucket(1), "salt backend unreachable".into()); + let mut state = state(); + let mut executor = executor(&mut state, envs); + executor.apply_pre_execution_changes().expect("the block starts"); + let before = committed(&mut executor); + assert_eq!(before.0, 0, "no receipt yet"); + + let deposit_hash = B256::repeat_byte(0xd1); + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0xd0), + from: CALLER, + to: TxKind::Call(WRITER), + mint: 1_000, + value: U256::ZERO, + gas_limit: TX_GAS_LIMIT, + is_system_transaction: false, + input: vec![1].into(), + }; + let deposit = + common::recovered(MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, deposit_hash))); + let user = write(0, 1); + let user_hash = user.inner().tx_hash(); + for (name, tx, hash) in + [("the deposit", deposit, deposit_hash), ("the user's", user, user_hash)] + { + let error = executor.execute_transaction(&tx).expect_err("the bucket read fails"); + assert_eq!(internal_evm_error(&error), hash, "{name}: the error names the transaction"); + assert!(error.to_string().contains("salt backend unreachable"), "{name}: {error}"); + assert_eq!(committed(&mut executor), before, "{name}: the block committed nothing"); + } + + // The node leaves the user's transaction out, and the block goes on. + executor.execute_transaction(&write(0, 2)).expect("the next transaction executes"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "only the transaction that ran is in the block"); +} + +/// A transaction that adds no state — a call to an empty account — asks about no bucket, so a +/// block of such transactions exports an empty set. +#[test] +fn test_a_transaction_without_state_charges_asks_about_no_bucket() { + let envs = Envs::new(); + let mut state = state(); + let mut executor = executor(&mut state, envs.clone()); + executor.apply_pre_execution_changes().expect("the block starts"); + let tx = common::recovered(common::tx(0, CONTRACT, Bytes::new(), common::empty_call_gas())); + let outcome = executor.run_transaction(&tx).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "{CALLER} adds no state"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + assert!(executor.get_accessed_bucket_ids().is_empty()); + assert_eq!(envs.total_bucket_queries(), 0); +} diff --git a/crates/mega-evm/tests/block/building_policy.rs b/crates/mega-evm/tests/block/building_policy.rs new file mode 100644 index 000000000..e663d833a --- /dev/null +++ b/crates/mega-evm/tests/block/building_policy.rs @@ -0,0 +1,310 @@ +//! The builder's policy against the protocol's limits: a builder's policy changes which +//! transactions it packs, never what a packed block computes, and what a block counts of its +//! data size is what its transactions kept. + +use alloy_consensus::transaction::Recovered; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + BlockLimits, LimitCheck, LimitKind, MegaSpecId, MegaTransactionExt, MegaTxEnvelope, + ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use op_alloy_consensus::OpReceiptEnvelope; +use revm::{ + bytecode::opcode::{CALLDATALOAD, SSTORE}, + database::State, + Database as _, +}; + +use crate::common::{self, incompressible}; + +/// A contract that writes one fresh slot. +const WRITES_ONE: Address = address!("0x1000000000000000000000000000000000000011"); + +/// A contract that writes two fresh slots. +const WRITES_TWO: Address = address!("0x1000000000000000000000000000000000000012"); + +/// A contract that writes the slot its calldata names. +const WRITES_NAMED: Address = address!("0x1000000000000000000000000000000000000013"); + +/// The gas limit of the transactions here: enough for two writes at any byte price a measurement +/// build runs, so what stops or refuses them is a limit, never their gas. +const GAS_LIMIT: u64 = 2_000_000; + +/// Senders, one per transaction, so a transaction a builder leaves out does not stall the nonces +/// of the ones after it. +const SENDERS: [Address; 5] = [ + address!("0x3000000000000000000000000000000000000001"), + address!("0x3000000000000000000000000000000000000002"), + address!("0x3000000000000000000000000000000000000003"), + address!("0x3000000000000000000000000000000000000004"), + address!("0x3000000000000000000000000000000000000005"), +]; + +/// The database every block here runs on: the three contracts, and every sender funded. +fn database() -> MemoryDatabase { + let mut db = common::database(); + db.set_account_code( + WRITES_ONE, + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(), + ); + db.set_account_code( + WRITES_TWO, + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(), + ); + db.set_account_code( + WRITES_NAMED, + BytecodeBuilder::default() + .push_number(1_u8) + .push_number(0_u8) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build(), + ); + for sender in SENDERS { + db.set_account_balance(sender, U256::from(1_000_000_000_000_000_u64)); + } + db +} + +/// A transaction from `sender`, its first, to `to` carrying `input`. +fn tx_from( + sender: Address, + to: Address, + input: Bytes, + gas_limit: u64, +) -> Recovered { + Recovered::new_unchecked(common::tx(0, to, input, gas_limit), sender) +} + +/// An executor over `state`, for a block packed under `policy` and held to `limits`: the spec's, +/// or another set a test holds a block to in their place. +fn executor_under( + state: &mut State, + policy: BlockLimits, + limits: ProtocolLimits, +) -> common::TestExecutor<'_> { + common::executor_with_spec(state, common::block_ctx(policy), common::chain_spec()) + .with_protocol_limits(limits) +} + +/// An Oracle hint that would cross the transaction's data-size limit is not forwarded, and +/// the block's data-size counter takes nothing for it: the stopped transaction is included with +/// its body alone. A hint that fits is forwarded and stays in the counter. +#[test] +fn test_a_hint_that_crosses_the_limit_adds_nothing_to_the_block_s_data_size() { + use alloy_sol_types::SolCall; + use mega_evm::system::{IOracle, ORACLE_CONTRACT_ADDRESS}; + + let hint = |data: &'static [u8]| -> Bytes { + IOracle::sendHintCall { + topic: alloy_primitives::B256::repeat_byte(0x7a), + data: Bytes::from_static(data), + } + .abi_encode() + .into() + }; + let (small, large) = (hint(b""), hint(&[0x5a; 64])); + let (small_len, large_len) = (small.len() as u64, large.len() as u64); + // A transaction that calls `sendHint` counts its calldata in its body and again as the hint. + // The limit holds the small one twice and the large one once. + let tx_data_size_limit = TX_BODY_SIZE + 2 * large_len - 1; + assert!(TX_BODY_SIZE + 2 * small_len <= tx_data_size_limit); + let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let limits = satin.with_tx_runtime_limits( + satin.tx_runtime_limits.with_tx_data_size_limit(tx_data_size_limit), + ); + + let mut state = State::builder().with_database(database()).build(); + let mut executor = executor_under(&mut state, BlockLimits::no_limits(), limits); + executor.apply_pre_execution_changes().expect("the block starts"); + + let outcome = executor + .run_transaction(&tx_from(SENDERS[0], ORACLE_CONTRACT_ADDRESS, large, GAS_LIMIT)) + .expect("the transaction runs"); + assert_eq!( + outcome.inner.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: tx_data_size_limit, + used: TX_BODY_SIZE + 2 * large_len, + frame_local: false, + }), + "the hint crosses the transaction's limit" + ); + assert_eq!(outcome.inner.usage.data_size, TX_BODY_SIZE + large_len); + executor.commit_transaction_outcome(outcome).expect("the stopped transaction is included"); + assert_eq!( + executor.limiter().usage.data_size, + TX_BODY_SIZE + large_len, + "the block counts the stopped transaction's body and nothing for the hint" + ); + + let outcome = executor + .run_transaction(&tx_from(SENDERS[1], ORACLE_CONTRACT_ADDRESS, small, GAS_LIMIT)) + .expect("the transaction runs"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + executor.commit_transaction_outcome(outcome).expect("it is included"); + assert_eq!( + executor.limiter().usage.data_size, + (TX_BODY_SIZE + large_len) + (TX_BODY_SIZE + 2 * small_len), + "a forwarded hint is counted beside its transaction's body" + ); +} + +/// What a block produced, with the state it left behind: the receipts, the counters and every +/// account and slot the candidates could have touched. +#[derive(Debug, PartialEq)] +struct Block { + receipts: Vec, + gas_used: u64, + blob_gas_used: u64, + counters: (mega_evm::BlockGasCounters, mega_evm::LimitUsage), + accounts: Vec<(Address, Option<(U256, u64)>)>, + slots: Vec, +} + +/// Executes `candidates` in order on a fresh block held to `limits`, packed under +/// `policy`: a candidate the block refuses is left out, as a builder leaves it out. Returns the +/// block, and for each candidate whether it was packed or the refusal that left it out. +fn build( + limits: ProtocolLimits, + policy: BlockLimits, + candidates: &[Recovered], +) -> (Block, Vec>) { + let mut state = State::builder().with_database(database()).build(); + let result = { + let mut executor = executor_under(&mut state, policy, limits); + executor.apply_pre_execution_changes().expect("the block starts"); + let packed: Vec<_> = candidates + .iter() + .map(|candidate| { + executor.execute_transaction(candidate).map(drop).map_err(|err| err.to_string()) + }) + .collect(); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + (result, packed) + }; + let (result, packed) = result; + let block = Block { + receipts: result.inner.receipts, + gas_used: result.inner.gas_used, + blob_gas_used: result.inner.blob_gas_used, + counters: (result.gas, result.usage), + accounts: SENDERS + .iter() + .chain([&Address::ZERO]) + .map(|address| { + let info = state.basic(*address).expect("readable"); + (*address, info.map(|info| (info.balance, info.nonce))) + }) + .collect(), + slots: (0..6_u64) + .map(|slot| state.storage(WRITES_NAMED, U256::from(slot)).expect("readable")) + .collect(), + }; + (block, packed) +} + +/// A builder packs under its own policy — a data-availability cap on one transaction, a cap on a +/// transaction's declared gas, and a block data-size cap below the protocol's — and leaves out +/// what it refuses. A validator re-executing the block it packed, under no policy or under a +/// policy of its own that differs, computes the same block: the same receipts, counters and +/// state. One holding the block to other limits does not, which is why the limits are fixed per +/// spec rather than any node's to choose. +#[test] +fn test_a_builder_and_a_validator_that_differ_on_building_policy_agree_on_the_block() { + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); + let writes = |sender, slot: u8, input_len: usize, gas_limit| { + let mut input = vec![0_u8; 32]; + input[31] = slot; + input.extend_from_slice(&incompressible(input_len)); + tx_from(sender, WRITES_NAMED, input.into(), gas_limit) + }; + // The builder's cap on a transaction's declared gas is the candidates' own, so only the one + // candidate above it is refused for gas. + let gas = GAS_LIMIT; + let candidates = [ + writes(SENDERS[0], 1, 0, gas), + // Refused by the builder's data-availability cap on one transaction. + writes(SENDERS[1], 2, 4_000, gas), + // Refused by the builder's cap on a transaction's declared gas. + writes(SENDERS[2], 3, 0, gas + 1), + // Packed: it is the transaction that reaches the builder's data-size cap. + writes(SENDERS[3], 4, 0, gas), + // Refused: the block has reached the builder's data-size cap, not the protocol's. + writes(SENDERS[4], 5, 0, gas), + ]; + let da_size = |index: usize| MegaTransactionExt::estimated_da_size(&candidates[index]); + assert!(da_size(1) > 2_000 && da_size(0) < 1_000, "{} {}", da_size(0), da_size(1)); + + // What one small write keeps of data size, so the builder's cap lands after two of them. + let (probe, _) = build(limits, BlockLimits::default(), &candidates[..1]); + let one_write = probe.counters.1.data_size; + assert_eq!(one_write, TX_BODY_SIZE + 32 + WRITE_RECORD_SIZE); + + let builder_policy = BlockLimits::no_limits() + .with_tx_da_size_limit(2_000) + .with_tx_gas_limit(gas) + .with_block_txs_data_limit(2 * one_write); + let (built, outcomes) = build(limits, builder_policy, &candidates); + let refusal = |index: usize| outcomes[index].clone().expect_err("the builder refused it"); + assert!( + refusal(1).contains("Transaction data availability size limit exceeded"), + "{}", + refusal(1) + ); + assert!( + refusal(2).contains(&format!( + "Transaction gas limit exceeded: tx_gas_limit={} > limit={gas}", + gas + 1 + )), + "{}", + refusal(2) + ); + assert!( + refusal(4).contains(&format!( + "Block transactions data limit reached: block_used={0} >= limit={0}", + 2 * one_write + )), + "{}", + refusal(4) + ); + let packed: Vec<_> = (0..candidates.len()).filter(|index| outcomes[*index].is_ok()).collect(); + assert_eq!(packed, [0, 3], "the builder's policy decided what it packed"); + assert_eq!(built.receipts.len(), 2); + assert!(built.receipts.iter().all(|receipt| receipt.status())); + assert!( + limits.block_txs_data_limit > built.counters.1.data_size, + "the block is well inside the protocol's own data-size budget" + ); + + let block: Vec<_> = packed.iter().map(|index| candidates[*index].clone()).collect(); + let validator_policies = [ + BlockLimits::default(), + // A validator whose node was given a policy of its own, looser than the builder's. + BlockLimits::no_limits().with_tx_da_size_limit(8_000).with_block_txs_data_limit(10_000), + ]; + for policy in validator_policies { + let (validated, outcomes) = build(limits, policy, &block); + assert_eq!(outcomes, [Ok(()), Ok(())], "{policy:?}: the validator packs the whole block"); + assert_eq!(validated, built, "{policy:?}: the validator computes the builder's block"); + } + + // The same block under other limits computes a different result: the first transaction's + // write crosses that data-size limit and is stopped. + let stricter = limits.with_tx_runtime_limits( + limits.tx_runtime_limits.with_tx_data_size_limit(TX_BODY_SIZE + 32), + ); + let (elsewhere, outcomes) = build(stricter, BlockLimits::default(), &block); + assert_eq!(outcomes, [Ok(()), Ok(())], "the stopped transactions are packed all the same"); + assert_ne!(elsewhere.receipts, built.receipts); + assert!(!elsewhere.receipts[0].status(), "the stop is a failed receipt"); + assert!(elsewhere.slots[1].is_zero(), "and its write is not kept"); +} diff --git a/crates/mega-evm/tests/block/common.rs b/crates/mega-evm/tests/block/common.rs index e882d2115..f4358c7a2 100644 --- a/crates/mega-evm/tests/block/common.rs +++ b/crates/mega-evm/tests/block/common.rs @@ -1,23 +1,33 @@ //! Shared setup of the block-executor tests. //! -//! A block on a chain whose schedule activates Satin at genesis, over an in-memory database with -//! an empty L1 block contract — so the L1 fees, the operator fee and the data-availability -//! footprint scalar all read as zero unless a test writes them. +//! A block on a chain whose schedule activates Satin at genesis, over an in-memory database holding +//! the seven predeploys as a chain that ran Rex6 holds them, and no L1 block contract — so the L1 +//! fees, the operator fee and the data-availability footprint scalar all read as zero unless a test +//! writes them. Satin activates at genesis, so no block of these tests is its activation block. use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxLegacy}; +use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; use alloy_evm::{EvmEnv, EvmFactory}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ - test_utils::MemoryDatabase, BlockLimits, EmptyExternalEnv, MegaBlockExecutionCtx, - MegaBlockExecutor, MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, MegaTxEnvelope, + system::{ + system_contract_specs, IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + }, + test_utils::{BytecodeBuilder, MemoryDatabase, SequencerRegistryRoles}, + BlockLimits, EmptyExternalEnv, EvmTxRuntimeLimits, MegaBlockExecutionCtx, MegaBlockExecutor, + MegaBlockExecutorFactory, MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaSpecId, + MegaTxEnvelope, ProtocolLimits, }; use op_alloy_consensus::TxDeposit; use revm::{ context::{BlockEnv, CfgEnv}, + context_interface::cfg::GasId, database::State, inspector::NoOpInspector, + state::EvmState, }; /// The sender every test transaction comes from. @@ -38,9 +48,10 @@ pub(crate) const BLOCK_GAS_LIMIT: u64 = 30_000_000; /// The chain id the test transactions carry. pub(crate) const CHAIN_ID: u64 = 4_326; -/// The database a block runs on: the caller is funded and the callee has empty code. +/// The database a block runs on: the seven predeploys as a chain that ran Rex6 holds them, the +/// registry holding [`registry_roles`]; the caller is funded and the callee has empty code. pub(crate) fn database() -> MemoryDatabase { - let mut db = MemoryDatabase::default(); + let mut db = MemoryDatabase::default().rex6_predeploys(registry_roles()); db.set_account_code(CONTRACT, Bytes::new()); db.set_account_balance(CALLER, U256::from(1_000_000_000_000_000_u64)); db @@ -64,20 +75,73 @@ pub(crate) fn evm_env() -> EvmEnv { EvmEnv::new(cfg_env, block_env) } +/// The sequencer the tests' registry names, distinct from the system address and admin. +pub(crate) const SEQUENCER: Address = address!("0x2222222222222222222222222222222222222222"); + +/// The admin the tests' registry names, distinct from the system address and sequencer. +pub(crate) const ADMIN: Address = address!("0x3333333333333333333333333333333333333333"); + +/// An address as the word the registry stores it as. +pub(crate) fn word(address: Address) -> U256 { + U256::from_be_bytes(address.into_word().0) +} + +/// Code that writes 1 into the slot named by the first byte of its calldata. +pub(crate) fn writer() -> Bytes { + use revm::bytecode::opcode::{CALLDATALOAD, PUSH0, SHR, SSTORE, STOP}; + BytecodeBuilder::default() + .push_number(1_u8) + .append_many([PUSH0, CALLDATALOAD]) + .push_number(248_u8) + .append_many([SHR, SSTORE, STOP]) + .build() +} + +/// The roles the registry of [`database`] holds: the default system address, and a sequencer and +/// an admin of their own. +pub(crate) fn registry_roles() -> SequencerRegistryRoles { + SequencerRegistryRoles { + system_address: MEGA_SYSTEM_ADDRESS, + sequencer: SEQUENCER, + admin: ADMIN, + min_rotation_delay: 100, + } +} + /// A schedule that activates Satin at genesis. +/// +/// Its blocks are held to the spec's limits ([`ProtocolLimits::for_spec`]), which no block this +/// size reaches but gas detention's caps; a test that holds a block or a transaction to another +/// limit replaces them ([`executor_with_limits`]). pub(crate) fn chain_spec() -> MegaHardforkConfig { MegaHardforkConfig::default().with_all_activated() } -/// The context of a block held to `limits`. +/// The loosest limits a block could be held to while a read of volatile data still detains: +/// every limit unlimited, and gas detention's caps one below the most compute a transaction can +/// spend, which no transaction of a block this size reaches. For a test that holds a block to +/// one limit and no other. +pub(crate) const fn loosest() -> ProtocolLimits { + ProtocolLimits::no_limits().with_tx_runtime_limits(loosest_tx()) +} + +/// The per-transaction half of [`loosest`]. +pub(crate) const fn loosest_tx() -> EvmTxRuntimeLimits { + let cap = mega_evm::constants::MAX_TX_COMPUTE_GAS - 1; + EvmTxRuntimeLimits::no_limits() + .with_block_env_access_compute_gas_limit(cap) + .with_oracle_access_compute_gas_limit(cap) +} + +/// The context of a block the builder packs under `policy`. /// /// Cancun is active, so the block carries a parent beacon block root; without one the EIP-4788 /// pre-block call refuses the block. -pub(crate) fn block_ctx(limits: BlockLimits) -> MegaBlockExecutionCtx { - MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), limits) +pub(crate) fn block_ctx(policy: BlockLimits) -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy) } -/// The context of a block with no limits at all. +/// The context of a block packed under no building policy, as a validator executes one. pub(crate) fn unlimited_ctx() -> MegaBlockExecutionCtx { block_ctx(BlockLimits::no_limits()) } @@ -91,16 +155,20 @@ pub(crate) type TestExecutor<'a> = MegaBlockExecutor, OpAlloyReceiptBuilder, MegaHardforkConfig>; /// The factory the tests build executors from. -pub(crate) fn factory() -> MegaBlockExecutorFactory< +pub(crate) type TestFactory = MegaBlockExecutorFactory< OpAlloyReceiptBuilder, MegaHardforkConfig, MegaEvmFactory, -> { - MegaBlockExecutorFactory::new( - OpAlloyReceiptBuilder::default(), - chain_spec(), - MegaEvmFactory::new(), - ) +>; + +/// The factory the tests build executors from. +pub(crate) fn factory() -> TestFactory { + factory_on(chain_spec()) +} + +/// A factory of executors for blocks on the chain `spec` describes. +pub(crate) fn factory_on(spec: MegaHardforkConfig) -> TestFactory { + MegaBlockExecutorFactory::new(OpAlloyReceiptBuilder::default(), spec, MegaEvmFactory::new()) } /// An executor over `state`, for a block held to `ctx`. @@ -120,6 +188,15 @@ pub(crate) fn executor_with_env( build(state, ctx, env, chain_spec()) } +/// An executor over `state`, for a block held to `limits` in place of the spec's, packed under no +/// building policy. +pub(crate) fn executor_with_limits( + state: &mut State, + limits: ProtocolLimits, +) -> TestExecutor<'_> { + build(state, unlimited_ctx(), evm_env(), chain_spec()).with_protocol_limits(limits) +} + /// An executor over `state`, for a block on the chain `spec` describes. pub(crate) fn executor_with_spec( state: &mut State, @@ -150,22 +227,112 @@ fn build( MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) } +/// The one account each of `states` names, in commit order: what each pre-block step committed +/// is about. A pre-block call names its target, the activation block's check the predeploy it +/// read, the read of the registry's pending changes and the call that applies them the registry, +/// and the read of the L1 block info the L1 block contract. +/// +/// # Panics +/// +/// On a state that names more than one account, as a pre-block call whose code reaches another +/// contract does. +pub(crate) fn named_accounts(states: &[EvmState]) -> Vec
{ + states + .iter() + .map(|state| { + assert_eq!(state.len(), 1, "a pre-block step names one account: {state:?}"); + *state.keys().next().expect("one account") + }) + .collect() +} + +/// The committed state of the pre-block call to `target` among `states`: the first that names it. +/// +/// # Panics +/// +/// When no state names `target`. +pub(crate) fn call_state(states: &[EvmState], target: Address) -> &EvmState { + states + .iter() + .find(|state| state.contains_key(&target)) + .unwrap_or_else(|| panic!("no committed state names {target}")) +} + +/// The contracts the EIP-2935 and EIP-4788 calls committed in `states` targeted, in commit order: +/// a call's state names its target. +pub(crate) fn eip_calls(states: &[EvmState]) -> Vec
{ + states + .iter() + .filter_map(|state| { + [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS] + .into_iter() + .find(|target| state.contains_key(target)) + }) + .collect() +} + +/// Whether `state` is the activation block's check of a predeploy: one of the seven accounts +/// alone, read only, with no slot. The read of the registry's pending changes names the registry +/// alone too, with the slots it read. +pub(crate) fn is_predeploy_check(state: &EvmState) -> bool { + state.len() == 1 && + system_contract_specs().iter().any(|spec| { + state.get(&spec.address).is_some_and(|account| { + !account.is_touched() && !account.is_created() && account.storage.is_empty() + }) + }) +} + +/// Whether one of `states` is the `applyPendingChanges()` call: a state that touched the +/// registry. The read of its pending changes leaves the registry untouched. +pub(crate) fn applies_pending_changes(states: &[EvmState]) -> bool { + states.iter().any(|state| { + state.get(&SEQUENCER_REGISTRY_ADDRESS).is_some_and(|registry| registry.is_touched()) + }) +} + +/// The history gas the body of a legacy transaction carrying `calldata_len` bytes of calldata +/// pays, at the byte prices in effect. +pub(crate) fn body_history(calldata_len: u64) -> u64 { + mega_evm::history_gas(mega_evm::tx_body_history_bytes(calldata_len, 0, 0, 0)) + .expect("the body has a price") +} + +/// A gas limit for a call to the empty [`CONTRACT`]: 100,000 of regular gas on top of the +/// history its body pays, so the call has the same room whatever a history byte costs. +pub(crate) fn empty_call_gas() -> u64 { + 100_000 + body_history(0) +} + +/// A legacy transaction from `sender`. +/// +/// The hash is derived from the sender and the nonce. Nothing in these tests pins it: a receipt +/// carries none, and a block that executes two transactions from one sender at one nonce tells +/// them apart by the sender's account, which is what the stale-outcome check reads. +pub(crate) fn legacy_from( + sender: Address, + nonce: u64, + kind: TxKind, + value: U256, + input: Bytes, + gas_limit: u64, + gas_price: u128, +) -> Recovered { + let tx = + TxLegacy { chain_id: Some(CHAIN_ID), nonce, gas_price, gas_limit, to: kind, value, input }; + let hash = B256::from(alloy_primitives::keccak256( + [sender.as_slice(), &nonce.to_be_bytes(), &[0u8]].concat(), + )); + Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), hash)), + sender, + ) +} + /// A legacy transaction from [`CALLER`]. pub(crate) fn tx(nonce: u64, to: Address, input: Bytes, gas_limit: u64) -> MegaTxEnvelope { - let tx_legacy = TxLegacy { - chain_id: Some(CHAIN_ID), - nonce, - gas_price: 1_000_000, - gas_limit, - to: TxKind::Call(to), - value: U256::ZERO, - input, - }; - MegaTxEnvelope::Legacy(Signed::new_unchecked( - tx_legacy, - Signature::test_signature(), - B256::repeat_byte(nonce as u8 + 1), - )) + legacy_from(CALLER, nonce, TxKind::Call(to), U256::ZERO, input, gas_limit, 1_000_000) + .into_inner() } /// A legacy transaction from [`CALLER`], with its sender recovered. @@ -173,6 +340,46 @@ pub(crate) fn user_tx(nonce: u64, gas_limit: u64) -> Recovered { recovered(tx(nonce, CONTRACT, Bytes::new(), gas_limit)) } +/// The state gas one fresh storage slot costs at the byte prices in effect, in the minimum +/// bucket the tests' environment prices every slot in. +pub(crate) fn slot_state_gas() -> u64 { + mega_evm::satin_gas_params().get(GasId::sstore_set_state_gas()) +} + +/// Whether a state byte costs nothing at the prices in effect: every state-gas entry of the +/// schedule is zero. +/// +/// Only a measurement build arranges that, with `MEGA_SATIN_CPSB` at 0 or at a price every entry +/// rounds to nothing. A case whose scenario is state gas to cross a limit with has nothing to run +/// then, and is skipped; each test that skips one leaves a note (`note_price_guard`), +/// which the byte-price grid counts. +pub(crate) fn state_is_free() -> bool { + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + mega_evm::test_utils::note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); + true +} + +/// The state gas one new account costs at the byte prices in effect. +pub(crate) fn new_account_state_gas() -> u64 { + mega_evm::satin_gas_params().get(GasId::new_account_state_gas()) +} + +/// A Mega System Transaction: a legacy call from the system address the registry names to the +/// Oracle's `getSlot(0)`. +/// +/// Its gas is 1,000,000 on top of the account the engine creates for its caller, which the +/// tests' state does not hold, so it runs the same whatever a state byte costs. +pub(crate) fn system_tx() -> Recovered { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + Recovered::new_unchecked( + tx(0, ORACLE_CONTRACT_ADDRESS, input.into(), 1_000_000 + new_account_state_gas()), + MEGA_SYSTEM_ADDRESS, + ) +} + /// A legacy transaction carrying `input`. pub(crate) fn user_tx_with_input( nonce: u64, diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index b2183ea81..9c6557888 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -3,14 +3,23 @@ use alloy_consensus::transaction::Recovered; use alloy_evm::block::BlockExecutor; use alloy_primitives::{address, Address, Bytes, U256}; -use mega_evm::{test_utils::BytecodeBuilder, BlockGasCounters, BlockLimits, MegaTxEnvelope}; -use revm::{bytecode::opcode::LOG0, database::State}; +use mega_evm::{ + test_utils::{transfer_log, BytecodeBuilder}, + BlockGasCounters, MegaTxEnvelope, +}; +use revm::{ + bytecode::opcode::{CALL, LOG0, LOG3, POP, PUSH0}, + database::State, +}; use crate::common::{self, executor, user_tx, CONTRACT}; /// An account with no code, to transfer to. const RECIPIENT: Address = address!("0x3000000000000000000000000000000000000003"); +/// An account whose code emits an event when it is paid. +const RECEIVER: Address = address!("0x3000000000000000000000000000000000000004"); + /// Code that writes a slot and emits a log, so a transaction touching it spends on more than /// plain execution once the mechanisms that price those land. fn writing_contract() -> Bytes { @@ -23,6 +32,17 @@ fn writing_contract() -> Bytes { .build() } +/// A gas limit for a call to the writing contract: 1,000,000 of regular gas on top of what its +/// slot, its write record, its log and its body cost at the byte prices in effect. +fn writer_gas() -> u64 { + 1_000_000 + + common::slot_state_gas() + + mega_evm::history_gas( + mega_evm::TX_BODY_SIZE + mega_evm::WRITE_RECORD_SIZE + mega_evm::LOG_BASE_SIZE + 64, + ) + .expect("the bytes have a price") +} + fn state_with_writer() -> State { let mut db = common::database(); db.set_account_code(CONTRACT, writing_contract()); @@ -31,7 +51,7 @@ fn state_with_writer() -> State { /// A transfer to an account with no code. fn transfer(nonce: u64) -> Recovered { - common::recovered(common::tx(nonce, RECIPIENT, Bytes::new(), 100_000)) + common::recovered(common::tx(nonce, RECIPIENT, Bytes::new(), common::empty_call_gas())) } /// The block's three ledgers are the sum of its transactions', each on its own ledger, and the @@ -44,7 +64,7 @@ fn test_a_block_sums_each_ledger_of_its_transactions() { let mut expected = BlockGasCounters::default(); let mut expected_gas_used = 0; - for tx in [transfer(0), user_tx(1, 1_000_000), transfer(2)] { + for tx in [transfer(0), user_tx(1, writer_gas()), transfer(2)] { let outcome = executor.run_transaction(&tx).expect("the transaction executes"); expected.record(&outcome.gas); expected_gas_used += outcome.gas.gas_used; @@ -70,7 +90,7 @@ fn test_the_result_carries_the_counters_and_the_footprint() { let mut state = state_with_writer(); let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + executor.execute_transaction(&user_tx(0, writer_gas())).expect("the transaction executes"); let usage = executor.limiter().usage; let gas = *executor.gas(); @@ -84,56 +104,212 @@ fn test_the_result_carries_the_counters_and_the_footprint() { assert!(result.usage.write_records > 0, "the transaction wrote to state"); } -/// The execution-gas dimension of the block: the transaction that crosses the limit is packed, -/// and the next one is refused before it runs. +/// The state and history ledgers are counted, and with no limit configured nothing refuses a +/// transaction on them: history has no block limit, and the state ledger's is unlimited unless a +/// node sets one. +/// +/// The history a block counts is the sum of its transactions', which is what makes the block's +/// column readable: three transactions carrying the same body count three bodies. #[test] -fn test_the_execution_limit_packs_the_crossing_transaction_and_skips_the_next() { +fn test_the_state_and_history_ledgers_refuse_nothing() { let mut state = state_with_writer(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); - // What one of these transactions spends on the execution ledger, so the block below has room - // for exactly one of them. - let spent = { - let mut probe_state = state_with_writer(); - let mut probe = executor(&mut probe_state, common::unlimited_ctx()); - probe.apply_pre_execution_changes().expect("the block starts"); - probe.execute_transaction(&user_tx(0, 1_000_000)).expect("the probe executes"); - probe.gas().execution - }; - assert!(spent > 0); + for nonce in 0..3 { + executor.execute_transaction(&user_tx(nonce, writer_gas())).expect("nothing refuses these"); + } - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_execution_gas_limit(spent - 1)), + let counters = *executor.gas(); + assert_eq!(counters.state, common::slot_state_gas(), "the one fresh slot's state gas"); + // Each transaction carries its body and emits a log over 64 bytes. Only the first writes the + // slot: the two after it find it already holding the value, which is no write and no record. + let bytes = 3 * mega_evm::TX_BODY_SIZE + + mega_evm::WRITE_RECORD_SIZE + + 3 * (mega_evm::LOG_BASE_SIZE + 64); + // Each is charged where it is made, so the gas is the sum of the three prices. + let priced = |bytes| mega_evm::history_gas(bytes).expect("the bytes have a price"); + assert_eq!( + counters.history, + 3 * priced(mega_evm::TX_BODY_SIZE) + + priced(mega_evm::WRITE_RECORD_SIZE) + + 3 * priced(mega_evm::LOG_BASE_SIZE + 64), + "three bodies, three logs and the one write record", ); + assert_eq!(counters.history_bytes, bytes, "and the block reports the bytes beside the gas"); +} + +/// A contract that sends one wei to [`RECEIVER`] with the gas a `transfer()` forwards, and a +/// receiver that emits the one three-topic event a history allowance pays for. +fn state_with_allowance() -> State { + let sender = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(RECEIVER) + .push_number(2_300_u32) + .append(CALL) + .append(POP) + .stop() + .build(); + let receiver = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(2_u8) + .push_number(3_u8) + .push_number(32_u8) + .push_number(0_u8) + .append(LOG3) + .stop() + .build(); + let mut db = common::database(); + db.set_account_code(CONTRACT, sender); + db.set_account_balance(CONTRACT, U256::from(1_000)); + db.set_account_code(RECEIVER, receiver); + State::builder().with_database(db).build() +} + +/// A block reports the history bytes its transactions appended beside the history gas they paid, +/// and the two columns part by what the history allowances paid: here one event per transaction, +/// which the receiver's allowance paid in full. The transfer log each transfer leaves is in the +/// receipt and in the block's data size, and in neither history column. +#[test] +fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { + if !mega_evm::active_satin_prices().is_constants() { + return; + } + let mut state = state_with_allowance(); + let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - executor - .execute_transaction(&user_tx(0, 1_000_000)) - .expect("the transaction that crosses the limit is still packed"); - assert!(executor.gas().execution > spent - 1, "the block has crossed its limit"); + for nonce in 0..2 { + let outcome = executor.run_transaction(&user_tx(nonce, 1_000_000)).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 2, "the transfer's log and the receiver's event"); + assert_eq!(logs[0], transfer_log(CONTRACT, RECEIVER, U256::from(1))); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + } - let err = executor - .execute_transaction(&user_tx(1, 1_000_000)) - .expect_err("the block has no execution gas left"); - assert!(format!("{err}").contains("Block execution gas limit reached"), "{err}"); + let counters = *executor.gas(); + // Each transaction: its body, the transfer's two records and the receiver's event. + let per_tx = mega_evm::TX_BODY_SIZE + + 2 * mega_evm::WRITE_RECORD_SIZE + + mega_evm::STORAGE_CALL_STIPEND_BYTES; + assert_eq!(counters.history_bytes, 2 * per_tx); + assert_eq!( + counters.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE - counters.history, + 2 * mega_evm::storage_call_stipend(), + "the allowances paid for both events, and no gas ledger has them", + ); let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1); + assert_eq!(result.gas, counters, "the result carries both columns"); + assert_eq!( + result.usage.data_size, + 2 * (per_tx + mega_evm::TRANSFER_LOG_SIZE), + "the data size counts the transfer logs the history columns leave out", + ); } -/// The state and history ledgers are counted, and nothing refuses a transaction on them: their -/// block limits belong to the mechanisms that bring those ledgers. +/// A transaction bound by its floor adds its floor to the block's execution gas. Its history comes +/// out before the floor applies, so what the block counts is neither the fork's figure, which +/// carries history, nor that figure less history, which falls below the floor. #[test] -fn test_the_state_and_history_ledgers_refuse_nothing() { - let mut state = state_with_writer(); +fn test_a_floor_bound_transaction_adds_its_floor_to_the_block() { + if !mega_evm::active_satin_prices().is_constants() { + return; + } + let mut state = common::state(); let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - for nonce in 0..3 { - executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("nothing refuses these"); + let tx = common::user_tx_with_input(0, Bytes::from(vec![0; 1_000]), 1_000_000); + let outcome = executor.run_transaction(&tx).expect("the transaction executes"); + let gas = outcome.gas; + let fork_figure = outcome.result.gas().block_regular_gas_used(); + assert!(gas.floor > gas.regular, "{gas:?}: a kilobyte of calldata and nothing run"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + assert_eq!(executor.gas().execution, gas.floor); + assert!(fork_figure > gas.floor, "the fork's figure carries the history"); + assert!(fork_figure - gas.history < gas.floor, "and less history it falls below the floor"); +} + +/// A transaction that runs out of gas before its first frame, here on EIP-2780's charge for the +/// account its value would create, is billed its whole gas limit everywhere the limit is counted: +/// the sender pays it at the gas price, the fee recipients are credited the same amount, the +/// receipt's cumulative gas and the block's gas used are the gas limit, and the block's history +/// ledger takes the body's history and nothing for the record the frame never made. +#[test] +fn test_an_out_of_gas_before_the_first_frame_bills_the_whole_gas_limit_to_the_block() { + use alloy_primitives::TxKind; + use op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}; + use revm::Database as _; + + // With a state byte at nothing the phase has no charge of its own to fall short of. + if common::state_is_free() { + return; } + const FRESH: Address = address!("0x3000000000000000000000000000000000000005"); + const GAS_PRICE: u128 = 1_000_000; + let transfer = |gas_limit: u64| { + common::legacy_from( + common::CALLER, + 0, + TxKind::Call(FRESH), + U256::from(1), + Bytes::new(), + gas_limit, + GAS_PRICE, + ) + }; - let counters = *executor.gas(); - assert!(counters.state > 0, "the Satin gas table prices state gas, and these writes draw it"); - assert_eq!(counters.history, 0, "history gas arrives with the mechanism that meters it"); + // What the transfer spends when it has room, on a block of its own: one gas less falls short + // on the last charge of the runtime gas phase. + let mut state = common::state(); + let mut measuring = executor(&mut state, common::unlimited_ctx()); + measuring.apply_pre_execution_changes().expect("the block starts"); + let room = 1_000_000 + common::new_account_state_gas() + common::body_history(0); + let outcome = measuring.run_transaction(&transfer(room)).expect("the transfer runs"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + let gas_limit = outcome.inner.gas.gas_used - 1; + drop(measuring); + + let mut state = common::state(); + let fee_recipients = + [Address::ZERO, BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT]; + let balance = |state: &mut State, address| { + state.basic(address).expect("the account is read").map_or(U256::ZERO, |info| info.balance) + }; + let sender_before = balance(&mut state, common::CALLER); + let recipients_before: U256 = fee_recipients.iter().map(|a| balance(&mut state, *a)).sum(); + + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor.run_transaction(&transfer(gas_limit)).expect("it is included"); + assert!(outcome.inner.result.is_halt(), "{:?}", outcome.inner.result); + let gas = outcome.inner.gas; + assert_eq!(gas.gas_used, gas_limit, "the whole gas limit burns"); + assert_eq!(gas.reservoir_remaining, 0, "nothing comes back from a reservoir"); + assert_eq!(gas.history, common::body_history(0), "the history ledger reads the body"); + assert_eq!(gas.history_bytes, mega_evm::TX_BODY_SIZE); + assert_eq!(gas.state, 0, "the account was not created"); + executor.commit_transaction_outcome(outcome).expect("the halt is included"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.gas_used, gas_limit, "the block's gas used"); + assert_eq!(result.receipts()[0].cumulative_gas_used(), gas_limit, "the receipt"); + let mut counters = BlockGasCounters::default(); + counters.record(&gas); + assert_eq!(result.gas, counters); + assert_eq!(result.gas.history, common::body_history(0), "the block's history ledger"); + + let paid = U256::from(gas_limit) * U256::from(GAS_PRICE); + assert_eq!( + sender_before - balance(&mut state, common::CALLER), + paid, + "the sender pays its whole gas limit, and its value does not move" + ); + let recipients_after: U256 = fee_recipients.iter().map(|a| balance(&mut state, *a)).sum(); + assert_eq!(recipients_after - recipients_before, paid, "the fee recipients are credited it"); + assert_eq!(balance(&mut state, FRESH), U256::ZERO, "the recipient was not created"); } diff --git a/crates/mega-evm/tests/block/deposits.rs b/crates/mega-evm/tests/block/deposits.rs new file mode 100644 index 000000000..847284bac --- /dev/null +++ b/crates/mega-evm/tests/block/deposits.rs @@ -0,0 +1,209 @@ +//! A deposit is never refused by a block's packing budget. +//! +//! The data-size limit of a block budgets the transactions its builder chooses. A deposit is not +//! chosen: the block derived from L1 must include it. So it never refuses a deposit — not before it +//! executes, and not when an outcome executed earlier is committed through either commit path — +//! and every deposit still counts towards it, so the ordinary transactions after the deposits find +//! the room they used. + +use alloy_consensus::{transaction::Recovered, Sealed}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + test_utils::BytecodeBuilder, BlockGasCounters, BlockLimits, LimitUsage, MegaTxEnvelope, +}; +use op_alloy_consensus::TxDeposit; +use revm::{ + bytecode::opcode::{CALLDATALOAD, PUSH0, SSTORE}, + database::State, +}; + +use crate::common::{self, executor}; + +/// Sets the slot the first calldata word names to one. +const WRITER: Address = address!("0x1000000000000000000000000000000000000d01"); + +/// The sender of the ordinary transaction, so its nonce does not depend on the deposits'. +const SENDER: Address = address!("0x2000000000000000000000000000000000000d02"); + +/// Calldata past the slot word, so each deposit carries data size well beyond its body. +const PADDING: usize = 1_000; + +/// 1,000,000 of regular gas on top of what the slot, its write record and the body of an +/// ordinary transaction cost at the byte prices in effect. +fn gas_limit() -> u64 { + 1_000_000 + + common::slot_state_gas() + + common::body_history(32 + PADDING as u64) + + mega_evm::write_record_history_gas(1).expect("a record has a price") +} + +fn state() -> State { + let mut db = common::database(); + let writer = BytecodeBuilder::default() + .push_number(1_u8) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build(); + db.set_account_code(WRITER, writer); + db.set_account_balance(SENDER, U256::from(1_000_000_000_000_000_u64)); + for slot in 1..=3 { + db.set_account_balance(depositor(slot), U256::from(1)); + } + State::builder().with_database(db).build() +} + +/// Calldata that names `slot`, padded with [`PADDING`] bytes. +fn input(slot: u64) -> Bytes { + let mut input = U256::from(slot).to_be_bytes::<32>().to_vec(); + input.resize(32 + PADDING, 0xab); + Bytes::from(input) +} + +/// The depositor of the deposit that fills `slot`, an account the state holds: one per deposit, +/// so deposits executed as candidates before any of them commits do not depend on each other's +/// commit, which the checked commit would refuse. +fn depositor(slot: u64) -> Address { + Address::with_last_byte(0xd0 + slot as u8) +} + +/// A deposit that fills the fresh `slot`: execution gas, state gas, data size and a write record. +fn deposit(slot: u64) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::ZERO, + from: depositor(slot), + to: TxKind::Call(WRITER), + mint: 0, + value: U256::ZERO, + gas_limit: gas_limit(), + is_system_transaction: false, + input: input(slot), + }; + let sealed = Sealed::new_unchecked(deposit, B256::repeat_byte(0xd0 + slot as u8)); + Recovered::new_unchecked(MegaTxEnvelope::Deposit(sealed), depositor(slot)) +} + +/// An ordinary transaction that fills the fresh `slot`, so the data-size limit has something to +/// refuse it on. +fn ordinary(slot: u64) -> Recovered { + common::legacy_from( + SENDER, + 0, + TxKind::Call(WRITER), + U256::ZERO, + input(slot), + gas_limit(), + 1_000_000, + ) +} + +/// What one deposit adds to a block, read off a probe block with no limits. +fn one_deposit() -> (BlockGasCounters, LimitUsage) { + let mut state = state(); + let mut probe = executor(&mut state, common::unlimited_ctx()); + probe.apply_pre_execution_changes().expect("the block starts"); + probe.execute_transaction(&deposit(1)).expect("the probe executes"); + let (gas, usage) = (*probe.gas(), probe.limiter().usage); + assert!(gas.execution > 0 && usage.data_size > 0, "{gas:?} {usage:?}"); + assert_eq!(gas.state, common::slot_state_gas(), "the slot's state gas"); + assert_eq!(usage.write_records, 1, "the slot"); + (gas, usage) +} + +/// How the deposits reach the block. +#[derive(Clone, Copy, Debug)] +enum Route { + /// Executed and committed one at a time, so the third executes in a block past its limits. + OneByOne, + /// Executed as candidates before any commits, then committed through the checked commit, + /// which checks the block's counters again: the third commits past the limits. + CheckedCommit, + /// The same candidates committed through alloy-evm's commit, which a debug build holds to the + /// same check. + TraitCommit, +} + +/// Deposits cross the block's data-size limit and are included all the same, through every route; +/// each one counts towards it, towards the gas ledgers and towards the write records; and an +/// ordinary transaction after them is refused — before it executes, and, as a candidate executed +/// before the deposits committed, at its commit. +#[test] +fn test_no_block_limit_refuses_a_deposit_and_every_deposit_counts() { + const REFUSAL: &str = "Block transactions data limit reached"; + let (gas, usage) = one_deposit(); + // Room for a deposit and a half, so the second deposit crosses it. + let limits = + BlockLimits::no_limits().with_block_txs_data_limit(usage.data_size + usage.data_size / 2); + for route in [Route::OneByOne, Route::CheckedCommit, Route::TraitCommit] { + let name = format!("{route:?}"); + let mut state = state(); + let mut executor = executor(&mut state, common::block_ctx(limits)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let mut late_candidate = None; + match route { + Route::OneByOne => { + for slot in 1..=3 { + executor + .execute_transaction(&deposit(slot)) + .unwrap_or_else(|err| panic!("{name}: deposit {slot}: {err}")); + } + } + Route::CheckedCommit | Route::TraitCommit => { + let deposits: Vec<_> = (1..=3) + .map(|slot| { + executor + .run_transaction(&deposit(slot)) + .unwrap_or_else(|err| panic!("{name}: deposit {slot}: {err}")) + }) + .collect(); + late_candidate = Some( + executor + .run_transaction(&ordinary(100)) + .unwrap_or_else(|err| panic!("{name}: nothing has committed: {err}")), + ); + for (slot, outcome) in (1..).zip(deposits) { + assert_eq!(outcome.gas.state, gas.state, "{name}: deposit {slot}"); + if matches!(route, Route::CheckedCommit) { + executor + .commit_transaction_outcome(outcome) + .unwrap_or_else(|err| panic!("{name}: deposit {slot}: {err}")); + } else { + BlockExecutor::commit_transaction(&mut executor, outcome); + } + } + } + } + + assert_eq!(executor.gas().execution, 3 * gas.execution, "{name}: execution counted"); + assert_eq!(executor.gas().state, 3 * gas.state, "{name}: state counted"); + assert_eq!( + executor.limiter().usage.data_size, + 3 * usage.data_size, + "{name}: data size counted" + ); + assert_eq!(executor.limiter().usage.write_records, 3, "{name}: write records counted"); + assert!( + executor.limiter().usage.data_size > limits.block_txs_data_limit, + "{name}: the deposits crossed the limit", + ); + + let err = executor + .execute_transaction(&ordinary(101)) + .expect_err("an ordinary transaction finds the room the deposits used"); + assert!(format!("{err}").contains(REFUSAL), "{name}: {err}"); + if let Some(candidate) = late_candidate { + let err = executor + .commit_transaction_outcome(candidate) + .expect_err("a candidate executed before the deposits committed"); + assert!(format!("{err}").contains(REFUSAL), "{name}: at commit: {err}"); + } + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3, "{name}: the three deposits and nothing else"); + assert_eq!(result.gas.execution, 3 * gas.execution, "{name}"); + assert_eq!(result.gas.state, 3 * gas.state, "{name}"); + } +} diff --git a/crates/mega-evm/tests/block/detention.rs b/crates/mega-evm/tests/block/detention.rs new file mode 100644 index 000000000..7a67dd985 --- /dev/null +++ b/crates/mega-evm/tests/block/detention.rs @@ -0,0 +1,83 @@ +//! Gas detention in a block: a stopped transaction is included with a failed receipt that bills +//! what ran, and every transaction starts detention afresh. + +use alloy_evm::block::BlockExecutor; +use alloy_primitives::Bytes; +use mega_evm::{ + constants::BLOCK_ENV_ACCESS_COMPUTE_GAS, test_utils::BytecodeBuilder, LimitCheck, LimitKind, +}; +use revm::{ + bytecode::opcode::{JUMP, JUMPDEST, MCOPY, POP, PUSH0, TIMESTAMP}, + context::result::ExecutionResult, + database::State, +}; + +use crate::common::{self, executor_with_env_and_spec, user_tx}; + +/// Reads the block's timestamp, then copies memory forever. +fn read_then_spin() -> Bytes { + let code = BytecodeBuilder::default().append_many([TIMESTAMP, POP]); + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(0x8000_u16) + .append_many([PUSH0, PUSH0, MCOPY]) + .push_number(dest) + .append(JUMP) + .build() +} + +/// The stop is a failed receipt with no log, billed for the transaction's intrinsic gas, the +/// compute it spent up to the cap and its body's history, not for the gas it was given; the +/// block counts the same. The next transaction, which reads again, is held to a cap of its own +/// and stops the same way. +#[test] +fn test_a_stopped_transaction_is_included_with_a_failed_receipt_that_bills_what_ran() { + let mut db = common::database(); + db.set_account_code(common::CONTRACT, read_then_spin()); + let mut state = State::builder().with_database(db).build(); + let mut env = common::evm_env(); + env.block_env.gas_limit = 100_000_000; + // The production limits: the spec's detention caps. + let mut executor = + executor_with_env_and_spec(&mut state, common::unlimited_ctx(), env, common::chain_spec()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let gas_limit = 29_000_000; + let mut used = Vec::new(); + for nonce in 0..2 { + let outcome = executor.run_transaction(&user_tx(nonce, gas_limit)).expect("it executes"); + assert!( + matches!(outcome.inner.result, ExecutionResult::Revert { .. }), + "{:?}", + outcome.inner.result + ); + assert!( + matches!( + outcome.inner.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "{:?}", + outcome.inner.limit_exceeded + ); + let gas = outcome.inner.gas; + assert!(gas.regular > BLOCK_ENV_ACCESS_COMPUTE_GAS); + assert!(gas.regular < BLOCK_ENV_ACCESS_COMPUTE_GAS + 100_000, "{}", gas.regular); + assert!(gas.gas_used < gas_limit, "the stop does not burn the gas"); + used.push(gas); + executor.commit_transaction_outcome(outcome).expect("the stop is included"); + } + assert_eq!(used[0], used[1], "each transaction is held to its own cap"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + let receipts = result.receipts(); + assert_eq!(receipts.len(), 2); + let mut cumulative = 0; + for (receipt, gas) in receipts.iter().zip(&used) { + cumulative += gas.gas_used; + assert!(!receipt.status(), "a stop is a failed receipt"); + assert!(receipt.logs().is_empty()); + assert_eq!(receipt.cumulative_gas_used(), cumulative); + } + assert_eq!(result.gas.execution, used[0].regular + used[1].regular); + assert_eq!(result.gas.history, used[0].history + used[1].history); +} diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 1cf9fda80..6a72eb556 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -2,26 +2,40 @@ //! //! Every helper hands its state back rather than committing it, and the executor is what commits: //! a call the fork makes is in the state the block's transactions run on, and a call it does not -//! make leaves that state alone. +//! make leaves that state alone. A call that does not succeed refuses the block, and its state is +//! never committed: neither a commit hook nor the database sees it. +//! +//! Each call runs on the pre-block budget: the block's gas limit, and never less than 30M, of +//! which at most 30M is regular gas and the rest the call's state-gas reservoir. -use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; +use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, +}; use alloy_evm::{ block::{BlockExecutionError, BlockExecutor, BlockValidationError}, - EvmEnv, + EvmEnv, EvmFactory, }; use alloy_hardforks::{EthereumHardfork, ForkCondition}; -use alloy_primitives::{Bytes, B256, U256}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{Address, Bytes, B256, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - BlockLimits, MegaBlockExecutionCtx, MegaHardforkConfig, MegaSpecId, + constants::SLOT_STATE_GAS, + pre_block_call_gas_limit, + test_utils::{BytecodeBuilder, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, }; use revm::{ - bytecode::opcode::{CALLDATALOAD, SSTORE}, + bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, database::State, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, Database, }; -use crate::common::{self, executor_with_env, executor_with_env_and_spec, BLOCK_NUMBER}; +use crate::common::{ + self, call_state, eip_calls, executor_with_env, executor_with_env_and_spec, BLOCK_NUMBER, +}; /// The parent hash the EIP-2935 call records. const PARENT_HASH: B256 = B256::repeat_byte(0xab); @@ -41,6 +55,19 @@ fn recorder() -> Bytes { .build() } +/// Code that stores the word it was called with in slot zero, as [`recorder`] does, and one in slot +/// one: two writes, so two write records. +fn recorder_writing_twice() -> Bytes { + BytecodeBuilder::default() + .push_number(0_u32) + .append(CALLDATALOAD) + .push_number(0_u32) + .append(SSTORE) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build() +} + /// A state whose two pre-block system contracts record what they are called with. fn state_with_recorders() -> State { let mut db = common::database(); @@ -94,6 +121,54 @@ fn pre_block_calls( recorded(&mut state) } +/// The contracts the pre-block calls a block at `number` on the chain `spec` describes committed +/// a state for, in order, and whether the block started. +fn committed_calls( + spec: MegaHardforkConfig, + number: u64, + ctx: MegaBlockExecutionCtx, +) -> (Vec
, Result<(), BlockExecutionError>) { + let mut state = state_with_recorders(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env_and_spec(&mut state, ctx, env_at_block(number), spec); + let started = executor.apply_pre_execution_changes(); + (eip_calls(&committed.states()), started) +} + +/// The environment of a block at [`BLOCK_NUMBER`] whose gas limit is `gas_limit`. +fn env_with_gas_limit(gas_limit: u64) -> EvmEnv { + let mut env = env_at_block(BLOCK_NUMBER); + env.block_env.gas_limit = gas_limit; + env +} + +/// Code whose one instruction expands memory past what 30M of regular gas pays for: it halts out +/// of gas on the regular budget, however much reservoir the call carries. +fn memory_hog() -> Bytes { + BytecodeBuilder::default().push_number(0x40_0000_u32).append(MLOAD).stop().build() +} + +/// Code that writes `slots` fresh storage slots, `SSTORE(i, 1)` for each. +fn fresh_writes(slots: u16) -> Bytes { + (0..slots) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .stop() + .build() +} + +/// Starts a block at [`BLOCK_NUMBER`] in `env` over `db` and reports the contracts the pre-block +/// calls committed a state for, and how the block's start ended. +fn start_block( + db: MemoryDatabase, + env: EvmEnv, +) -> (Vec
, Result<(), BlockExecutionError>) { + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env(&mut state, ctx(), env); + let started = executor.apply_pre_execution_changes(); + (eip_calls(&committed.states()), started) +} + /// Both calls run on a block of a chain past Prague and Cancun, and the executor commits what /// they produced: the block's transactions see the parent hash and the parent beacon root. #[test] @@ -104,6 +179,100 @@ fn test_the_pre_block_calls_record_the_parent_hash_and_the_beacon_root() { ); } +/// The pre-block calls are the protocol's own work, held to no per-transaction limit: under the +/// smallest value a chain may carry for each limit, which their bodies and their writes cross, both +/// calls still record. +/// +/// Each contract writes two slots, so each call keeps two write records: the body (`TX_BODY_SIZE` +/// and 32 bytes of calldata) crosses the transaction's data size, and a record the frame's. The +/// states the block commits show the two writes. Each limit is set alone as well as both +/// together. +/// +/// Rule [S19.3]. Expected values `independent`: the parent hash and the beacon root are the +/// block's own inputs, and the crossings are counted here from the writes the calls made. +#[test] +fn test_the_pre_block_calls_are_held_to_no_limit() { + let loosest = common::loosest_tx(); + let every = + loosest.with_tx_data_size_limit(mega_evm::TX_BODY_SIZE).with_frame_data_size_limit(1); + for (name, limits) in [ + ("the transaction's data size", loosest.with_tx_data_size_limit(mega_evm::TX_BODY_SIZE)), + ("a frame's data size", loosest.with_frame_data_size_limit(1)), + ("both limits at once", every), + ] { + let limits = common::loosest().with_tx_runtime_limits(limits); + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, recorder_writing_twice()); + db.set_account_code(BEACON_ROOTS_ADDRESS, recorder_writing_twice()); + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + { + let mut executor = executor_with_env_and_spec( + &mut state, + ctx(), + env_at_block(BLOCK_NUMBER), + common::chain_spec(), + ) + .with_protocol_limits(limits); + executor + .apply_pre_execution_changes() + .unwrap_or_else(|error| panic!("{name}: the block starts: {error}")); + } + let states = committed.states(); + + assert_eq!(eip_calls(&states), [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS], "{name}"); + for address in [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS] { + let call = call_state(&states, address); + let writes = call[&address].storage.values().filter(|slot| slot.is_changed()).count(); + assert_eq!(writes, 2, "{name}: the call to {address} made two writes, two records"); + } + assert_eq!(recorded(&mut state), (PARENT_HASH, PARENT_BEACON_ROOT), "{name}"); + } +} + +/// The pre-block calls count towards none of the block's counters or budgets. With the EIP-2935 +/// and EIP-4788 contracts' own code in state, both calls write their contracts' storage; after the +/// pre-block phase every counter of the block is still zero, and a block whose data-size budget is +/// one byte — reached by anything counted — still admits its first transaction. +/// +/// Rule [S19.7]. Expected values `independent`: zeros, and the first transaction admitted. +#[test] +fn test_the_pre_block_calls_count_towards_no_counter_or_budget() { + let policy = BlockLimits::no_limits().with_block_txs_data_limit(1); + let ctx = + MegaBlockExecutionCtx::new(PARENT_HASH, Some(PARENT_BEACON_ROOT), Bytes::new(), policy); + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env(&mut state, ctx, env_at_block(BLOCK_NUMBER)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let states = committed.states(); + assert_eq!(eip_calls(&states), [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]); + for address in [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS] { + let call = call_state(&states, address); + let writes = call[&address].storage.values().filter(|slot| slot.is_changed()).count(); + assert!(writes > 0, "the call to {address} wrote its contract's storage"); + } + let limiter = executor.limiter(); + assert_eq!( + (limiter.gas.execution, limiter.gas.state, limiter.gas.history, limiter.gas.history_bytes), + (0, 0, 0, 0), + "no gas ledger of the block counts the calls", + ); + assert_eq!( + (limiter.usage.data_size, limiter.usage.write_records), + (0, 0), + "nor its data size or writes" + ); + assert_eq!(limiter.block_gas_used, 0, "nor the gas its receipts report"); + executor + .execute_transaction(&common::user_tx(0, common::empty_call_gas())) + .expect("the first transaction is admitted under budgets of one"); +} + /// A chain that has not reached Prague makes no block hashes call; the beacon root call is /// unaffected. #[test] @@ -111,10 +280,14 @@ fn test_the_block_hashes_call_waits_for_prague() { let before_prague = common::chain_spec().with(EthereumHardfork::Prague, ForkCondition::Never); assert_eq!( - pre_block_calls(before_prague, BLOCK_NUMBER, ctx()), + pre_block_calls(before_prague.clone(), BLOCK_NUMBER, ctx()), (B256::ZERO, PARENT_BEACON_ROOT), "nothing was recorded for the parent hash" ); + + let (calls, started) = committed_calls(before_prague, BLOCK_NUMBER, ctx()); + started.expect("a block before Prague starts"); + assert_eq!(calls, [BEACON_ROOTS_ADDRESS], "no block hashes call was committed"); } /// A chain that has not reached Cancun makes no beacon root call, and needs no root; the block @@ -124,10 +297,14 @@ fn test_the_beacon_root_call_waits_for_cancun() { let before_cancun = common::chain_spec().with(EthereumHardfork::Cancun, ForkCondition::Never); assert_eq!( - pre_block_calls(before_cancun, BLOCK_NUMBER, ctx_without_beacon_root()), + pre_block_calls(before_cancun.clone(), BLOCK_NUMBER, ctx_without_beacon_root()), (PARENT_HASH, B256::ZERO), "nothing was recorded for the beacon root" ); + + let (calls, started) = committed_calls(before_cancun, BLOCK_NUMBER, ctx_without_beacon_root()); + started.expect("a block before Cancun starts"); + assert_eq!(calls, [HISTORY_STORAGE_ADDRESS], "no beacon root call was committed"); } /// The genesis block makes neither call: it has no parent to record. Its parent beacon root is @@ -142,22 +319,23 @@ fn test_the_genesis_block_makes_no_pre_block_call() { ); assert_eq!( - pre_block_calls(common::chain_spec(), 0, genesis), + pre_block_calls(common::chain_spec(), 0, genesis.clone()), (B256::ZERO, B256::ZERO), "neither contract was called" ); + + let (calls, started) = committed_calls(common::chain_spec(), 0, genesis); + started.expect("the genesis block starts"); + assert!(calls.is_empty(), "no pre-block call was committed: {calls:?}"); } /// A genesis block carrying a non-zero parent beacon block root is refused, as EIP-4788 -/// requires. +/// requires. The block hashes call makes no call at genesis, so no call was committed. #[test] fn test_the_genesis_block_refuses_a_non_zero_beacon_root() { - let mut state = state_with_recorders(); - let mut executor = executor_with_env(&mut state, ctx(), env_at_block(0)); - - let err = executor - .apply_pre_execution_changes() - .expect_err("the genesis block's parent beacon block root must be zero"); + let (calls, started) = committed_calls(common::chain_spec(), 0, ctx()); + let err = started.expect_err("the genesis block's parent beacon block root must be zero"); + assert!(calls.is_empty(), "{calls:?}"); assert!( matches!( @@ -172,16 +350,14 @@ fn test_the_genesis_block_refuses_a_non_zero_beacon_root() { ); } -/// A block of a chain past Cancun that carries no parent beacon block root is refused. +/// A block of a chain past Cancun that carries no parent beacon block root is refused. The block +/// hashes call ran first, and succeeded. #[test] fn test_a_block_without_a_parent_beacon_root_is_refused() { - let mut state = state_with_recorders(); - let mut executor = - executor_with_env(&mut state, ctx_without_beacon_root(), env_at_block(BLOCK_NUMBER)); - - let err = executor - .apply_pre_execution_changes() - .expect_err("a Cancun block carries a parent beacon block root"); + let (calls, started) = + committed_calls(common::chain_spec(), BLOCK_NUMBER, ctx_without_beacon_root()); + let err = started.expect_err("a Cancun block carries a parent beacon block root"); + assert_eq!(calls, [HISTORY_STORAGE_ADDRESS]); assert!( matches!( @@ -191,3 +367,231 @@ fn test_a_block_without_a_parent_beacon_root_is_refused() { "{err}" ); } + +/// With the contracts' own code, both calls succeed and are committed, in order and each on its +/// own: the parent hash in the EIP-2935 ring buffer, the timestamp and the root in the EIP-4788 +/// one. +#[test] +fn test_the_successful_pre_block_calls_commit_normally() { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env(&mut state, ctx(), env_at_block(BLOCK_NUMBER)); + executor.apply_pre_execution_changes().expect("both calls succeed"); + let calls = common::named_accounts(&committed.states()); + assert_eq!(&calls[..2], [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]); + drop(executor); + + let ring = 8191; + let parent = state.storage(HISTORY_STORAGE_ADDRESS, U256::from(BLOCK_NUMBER - 1)).unwrap(); + assert_eq!(B256::from(parent.to_be_bytes()), PARENT_HASH); + let timestamp_slot = U256::from(common::BLOCK_TIMESTAMP % ring); + let root_slot = timestamp_slot + U256::from(ring); + assert_eq!( + state.storage(BEACON_ROOTS_ADDRESS, timestamp_slot).unwrap(), + U256::from(common::BLOCK_TIMESTAMP) + ); + assert_eq!( + B256::from(state.storage(BEACON_ROOTS_ADDRESS, root_slot).unwrap().to_be_bytes()), + PARENT_BEACON_ROOT + ); +} + +/// A block hashes call that halts refuses the block with the EIP-2935 error, and its state is +/// never committed; the beacon root call after it never runs. It +/// halts on regular gas, which is at most 30M however large the block: the pre-block budget's +/// part above 30M is reservoir, and no regular charge draws it. +#[test] +fn test_a_block_is_refused_when_its_block_hashes_call_halts() { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, memory_hog()); + db.set_account_code(BEACON_ROOTS_ADDRESS, recorder()); + let (calls, started) = start_block(db, env_with_gas_limit(250_000_000)); + + let err = started.expect_err("a halted block hashes call refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) + if message.contains("did not succeed") && message.contains("OutOfGas") + ), + "{err}" + ); + assert!(calls.is_empty(), "{calls:?}"); +} + +/// A beacon root call that halts refuses the block with the EIP-4788 error, naming the root. The +/// block hashes call before it succeeded: its contract has no code. +#[test] +fn test_a_block_is_refused_when_its_beacon_root_call_halts() { + let mut db = common::database(); + db.set_account_code(BEACON_ROOTS_ADDRESS, memory_hog()); + let (calls, started) = start_block(db, env_with_gas_limit(250_000_000)); + + let err = started.expect_err("a halted beacon root call refuses the block"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BeaconRootContractCall { + parent_beacon_block_root, + message, + }) if **parent_beacon_block_root == PARENT_BEACON_ROOT + && message.contains("did not succeed") + ), + "{err}" + ); + assert_eq!(calls, [HISTORY_STORAGE_ADDRESS]); +} + +/// The pre-block budget follows the block's gas limit, so a pre-block call that costs more than +/// 30M in all still succeeds in a block that can hold it: 400 fresh slots are 39M of state gas, +/// which the reservoir above 30M pays. In a block of 30M the call has no reservoir, the state +/// gas spills onto the 30M of regular gas, and the call runs out of it. +#[test] +fn test_the_block_aware_budget_accepts_a_pre_block_call_above_30m() { + const SLOTS: u16 = 400; + assert_eq!(pre_block_call_gas_limit(250_000_000), 250_000_000); + assert_eq!(pre_block_call_gas_limit(1_000_000), SYSTEM_CALL_REGULAR_GAS_LIMIT); + // The slot count is sized at Satin's own price; other byte prices move the 30M boundary. + if !mega_evm::active_satin_prices().is_constants() { + return; + } + assert!(u64::from(SLOTS) * SLOT_STATE_GAS > SYSTEM_CALL_REGULAR_GAS_LIMIT); + + let database = || { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, fresh_writes(SLOTS)); + db.set_account_code(BEACON_ROOTS_ADDRESS, fresh_writes(SLOTS)); + db + }; + + let mut state = State::builder().with_database(database()).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); + executor.apply_pre_execution_changes().expect("a 250M block holds both calls"); + let states = committed.states(); + assert_eq!(states[0][&HISTORY_STORAGE_ADDRESS].storage.len(), usize::from(SLOTS)); + assert_eq!(states[1][&BEACON_ROOTS_ADDRESS].storage.len(), usize::from(SLOTS)); + drop(executor); + + let (calls, started) = start_block(database(), common::evm_env()); + assert_eq!(common::BLOCK_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT); + let err = started.expect_err("a 30M block gives the call no reservoir"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) + if message.contains("OutOfGas") + ), + "{err}" + ); + assert!(calls.is_empty(), "{calls:?}"); +} + +/// Starts a block at [`BLOCK_NUMBER`] over `db`. +fn start_block_over(db: ErrorInjectingDatabase) -> Result<(), BlockExecutionError> { + let mut state = State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, env_at_block(BLOCK_NUMBER)); + let mut executor = + MegaBlockExecutor::new(evm, ctx(), common::chain_spec(), OpAlloyReceiptBuilder::default()); + executor.apply_pre_execution_changes() +} + +/// A database that fails to load `address`, over contracts that record what they are called +/// with. +fn failing_on(address: Address) -> ErrorInjectingDatabase { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, recorder()); + db.set_account_code(BEACON_ROOTS_ADDRESS, recorder()); + let mut db = ErrorInjectingDatabase::new(db); + db.fail_on_account = Some(address); + db +} + +/// A database error in the block hashes call is an internal error carrying the database's +/// message, not a verdict on the block: the block is not refused as invalid. +#[test] +fn test_a_database_error_in_the_block_hashes_call_is_internal() { + let err = start_block_over(failing_on(HISTORY_STORAGE_ADDRESS)) + .expect_err("a failed read stops the block"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("injected basic() error"), "{err}"); +} + +/// A database error in the beacon root call is an internal error carrying the database's +/// message, not a verdict on the block; the block hashes call before it read what it needed. +#[test] +fn test_a_database_error_in_the_beacon_root_call_is_internal() { + let err = start_block_over(failing_on(BEACON_ROOTS_ADDRESS)) + .expect_err("a failed read stops the block"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("injected basic() error"), "{err}"); +} + +/// What the block commits for a pre-block call is the state op-revm's own system call produces +/// for it: the same call from the same state, on the same configuration — the split +/// switched on — and the same pre-block budget. The contract stores the regular gas it had, which +/// is 30M of the 250M budget, and the word it was called with. +#[test] +fn test_a_pre_block_call_commits_the_state_op_revm_produces() { + use op_revm::{handler::OpHandler, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; + use revm::{ + bytecode::opcode::{GAS, PUSH0, PUSH1, STOP}, + context::{result::EVMError, BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, TxEnv}, + handler::{EthFrame, ExecuteEvm, Handler, SystemCallTx}, + inspector::NoOpInspector, + interpreter::interpreter::EthInterpreter, + Journal, + }; + type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, + >; + + let code = BytecodeBuilder::default() + .append_many([GAS, PUSH0, SSTORE]) + .append_many([PUSH0, CALLDATALOAD, PUSH1, 1, SSTORE, STOP]) + .build(); + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, code); + db.set_account_code(BEACON_ROOTS_ADDRESS, recorder()); + + let mut state = State::builder().with_database(db.clone()).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); + executor.apply_pre_execution_changes().expect("the block starts"); + let delivered = committed.states().into_iter().next().expect("a first step"); + assert!(delivered.contains_key(&HISTORY_STORAGE_ADDRESS), "the block hashes call is first"); + let (cfg, block) = (executor.evm().ctx().cfg().clone(), executor.evm().ctx().block().clone()); + assert!(cfg.system_call_state_gas_margin_in_reservoir); + drop(executor); + + let mut op = OpEvm::new( + OpContext::new(db, OpSpecId::KARST).with_cfg(cfg).with_block(block), + NoOpInspector, + ); + let mut tx = OpTransaction::::new_system_tx_with_caller( + mega_evm::SYSTEM_ADDRESS, + HISTORY_STORAGE_ADDRESS, + PARENT_HASH.0.into(), + ); + tx.base.gas_limit = pre_block_call_gas_limit(250_000_000); + op.0.ctx.set_tx(tx); + let result: Result<_, EVMError> = + OpHandler::<_, _, EthFrame>::new().run_system_call(&mut op); + assert!(result.expect("op-revm runs the call").is_success()); + let expected = op.finalize(); + + assert_eq!(delivered, expected, "the block commits op-revm's state"); + let stored = &delivered[&HISTORY_STORAGE_ADDRESS].storage; + let gas = stored[&U256::ZERO].present_value(); + assert!(gas < U256::from(SYSTEM_CALL_REGULAR_GAS_LIMIT), "30M of regular gas: {gas}"); + assert!(gas > U256::from(SYSTEM_CALL_REGULAR_GAS_LIMIT - 10), "all of it: {gas}"); + assert_eq!(B256::from(stored[&U256::from(1)].present_value().to_be_bytes()), PARENT_HASH); +} diff --git a/crates/mega-evm/tests/block/external_envs.rs b/crates/mega-evm/tests/block/external_envs.rs new file mode 100644 index 000000000..42e8b91e7 --- /dev/null +++ b/crates/mega-evm/tests/block/external_envs.rs @@ -0,0 +1,108 @@ +//! The external environments of a block, through `ExternalEnvFactory`: the node's factory is +//! asked once for the environments of the block it executes, by that block's number, and every +//! transaction of the block prices its state gas by the SALT buckets those environments report and +//! reads the Oracle's storage through their oracle service. + +use std::{cell::RefCell, rc::Rc}; + +use alloy_evm::{ + block::{BlockExecutor, BlockExecutorFactory}, + EvmFactory, +}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, BlockNumber, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + satin_gas_params, + system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + BucketId, ExternalEnvFactory, ExternalEnvs, MegaBlockExecutorFactory, MegaEvmFactory, SaltEnv, + TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{context_interface::cfg::GasId, database::State}; + +use crate::common::{self, BLOCK_NUMBER}; + +/// The contract whose three slots the block's transactions write. +const WRITER: Address = address!("0x1000000000000000000000000000000000000abc"); + +/// The slot of the Oracle a transaction reads, and what the oracle service answers for it. +const ORACLE_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); +const ORACLE_VALUE: U256 = U256::from_limbs([0xabc, 0, 0, 0]); + +/// Room for a slot's first write at eight times the minimum bucket, at the spec's byte prices and +/// at the higher ones a measurement build may run. +const TX_GAS_LIMIT: u64 = 10_000_000; + +/// A node's factory: it hands every block the same environments and records which blocks asked. +#[derive(Clone, Debug)] +struct Factory { + envs: TestExternalEnvs, + asked: Rc>>, +} + +impl ExternalEnvFactory for Factory { + type EnvTypes = TestExternalEnvs; + + fn external_envs(&self, block: BlockNumber) -> ExternalEnvs { + self.asked.borrow_mut().push(block); + ExternalEnvs { salt_env: self.envs.clone(), oracle_env: self.envs.clone() } + } +} + +/// The bucket the slot `slot` of [`WRITER`] lives in. +fn bucket(slot: u64) -> BucketId { + ::bucket_id_for_slot(WRITER, U256::from(slot)) +} + +/// A block with three fresh slots written — one in a bucket at the minimum capacity, one at twice +/// it, one at eight times it — and a read of the Oracle's storage the oracle service answers: +/// every state gas charge is the schedule's entry times the bucket's multiplier, and the regular +/// gas does not move. +#[test] +fn test_a_blocks_environments_come_from_the_factory() { + let envs = TestExternalEnvs::new() + .with_bucket_capacity(bucket(2), MIN_BUCKET_SIZE as u64 * 2) + .with_bucket_capacity(bucket(8), MIN_BUCKET_SIZE as u64 * 8) + .with_oracle_storage(ORACLE_SLOT, ORACLE_VALUE); + let asked = Rc::new(RefCell::new(vec![])); + let factory = MegaBlockExecutorFactory::new( + OpAlloyReceiptBuilder::default(), + common::chain_spec(), + MegaEvmFactory::new().with_external_env_factory(Factory { envs, asked: asked.clone() }), + ); + + let mut db = common::database(); + db.set_account_code(WRITER, common::writer()); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + let mut state = State::builder().with_database(db).build(); + let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(*asked.borrow(), vec![BLOCK_NUMBER], "one block, one set of environments"); + + let entry = satin_gas_params().get(GasId::sstore_set_state_gas()); + let mut regular = vec![]; + for (nonce, m) in [(0, 1), (1, 2), (2, 8)] { + let tx = common::recovered(common::tx(nonce, WRITER, vec![m as u8].into(), TX_GAS_LIMIT)); + let outcome = executor.run_transaction(&tx).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, entry * m, "the slot's bucket at m = {m}"); + regular.push(outcome.gas.regular); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + } + assert!( + regular.iter().all(|gas| *gas == regular[0]), + "regular gas does not scale: {regular:?}" + ); + + let read = IOracle::getSlotCall { slot: ORACLE_SLOT }.abi_encode(); + let tx = common::recovered(common::tx(3, ORACLE_CONTRACT_ADDRESS, read.into(), TX_GAS_LIMIT)); + let outcome = executor.run_transaction(&tx).expect("it executes"); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(outcome.result.output().unwrap()).unwrap(), + B256::from(ORACLE_VALUE), + "the oracle service answered the read", + ); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + assert_eq!(*asked.borrow(), vec![BLOCK_NUMBER], "the environments served the whole block"); +} diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 807119ce3..0a2aa1ddc 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -1,10 +1,10 @@ //! The two ways to reach a block executor, and the limits both install. //! -//! A block's transaction-level limits live in its execution context, and the EVM is what -//! enforces them. Whichever route builds the executor — the constructor a node calls directly, -//! the factory trait its block-building and reorg paths call with an EVM they built, or the -//! trusted-inspector constructor — installs them, so a caller that did not pre-apply them does -//! not run a block under whatever limits the EVM happened to carry. +//! The limits a block's transactions run under are the spec's ([`ProtocolLimits::for_spec`]), and +//! the EVM is what enforces them. Whichever route builds the executor — the constructor a node +//! calls directly, the factory trait its block-building and reorg paths call with an EVM they +//! built, or the trusted-inspector constructor — installs them, so a caller that applied others +//! to the EVM does not run a block under whatever limits the EVM happened to carry. use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, @@ -15,56 +15,45 @@ use alloy_primitives::U256; use alloy_sol_types::SolError; use mega_evm::{ test_utils::{BytecodeBuilder, GasInspector}, - BlockLimits, DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, - MegaEvmFactory, MegaLimitExceeded, + DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, + MegaLimitExceeded, MegaSpecId, ProtocolLimits, }; use revm::{context::result::ExecutionResult, database::State}; use crate::common::{self, user_tx}; -/// A limit no default carries, so seeing it proves it travelled from the block context. -const TX_DATA_SIZE_LIMIT: u64 = 1_234_567; - -/// A second one, so a route that installs only the first is caught. -const FRAME_DATA_SIZE_LIMIT: u64 = 7_654_321; - -fn limits() -> BlockLimits { - BlockLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(TX_DATA_SIZE_LIMIT) - .with_frame_data_size_limit(FRAME_DATA_SIZE_LIMIT), - ) +/// The limits every route installs: Satin's. +fn limits() -> ProtocolLimits { + ProtocolLimits::for_spec(MegaSpecId::SATIN) } -/// The factory trait installs the block context's limits on an EVM the caller built without -/// them. -#[test] -fn test_trait_path_applies_block_context_runtime_limits() { - let mut state = common::state(); - let factory = common::factory(); - // Built without any caller-side limits: the case a caller that forgot them produces. - let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); - - let executor = factory.create_executor(evm, common::block_ctx(limits())); - - assert_eq!(executor.evm().tx_runtime_limits().tx_data_size_limit, TX_DATA_SIZE_LIMIT); +/// Limits a caller applied to the EVM, which are not the spec's: every field differs. +fn others() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(1_234_567) + .with_frame_data_size_limit(7_654_321) + .with_block_env_access_compute_gas_limit(1) + .with_oracle_access_compute_gas_limit(2) } -/// Every field travels, not just the one a test happens to look at. +/// The factory trait installs the spec's limits, every field of them, on an EVM the caller built +/// with others. An EVM the EVM factory creates runs under them before any executor installs them. #[test] -fn test_trait_path_applies_every_runtime_limit_field() { +fn test_trait_path_applies_the_specs_runtime_limits() { let mut state = common::state(); let factory = common::factory(); let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); + assert_eq!(*evm.tx_runtime_limits(), limits().tx_runtime_limits, "before any executor"); + let evm = evm.with_tx_runtime_limits(others()); - let executor = factory.create_executor(evm, common::block_ctx(limits())); + let executor = factory.create_executor(evm, common::unlimited_ctx()); assert_eq!( *executor.evm().tx_runtime_limits(), - limits().to_evm_tx_runtime_limits(), - "the EVM runs under exactly the block's limits" + limits().tx_runtime_limits, + "the EVM runs under exactly the spec's limits" ); + assert_eq!(executor.protocol_limits(), &limits()); } /// The two routes to an executor install the same limits, so neither is a way around them. @@ -73,8 +62,11 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let trait_path = { let mut state = common::state(); let factory = common::factory(); - let evm = factory.evm_factory().create_evm(&mut state, common::evm_env()); - let executor = factory.create_executor(evm, common::block_ctx(limits())); + let evm = factory + .evm_factory() + .create_evm(&mut state, common::evm_env()) + .with_tx_runtime_limits(others()); + let executor = factory.create_executor(evm, common::unlimited_ctx()); *executor.evm().tx_runtime_limits() }; @@ -84,61 +76,46 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let executor = factory.create_executor_with_trusted_inspector( &mut state, common::evm_env(), - common::block_ctx(limits()), + common::unlimited_ctx(), DeclaredObserver::new(GasInspector::new()), ); *executor.evm().tx_runtime_limits() }; - assert_eq!(trait_path, limits().to_evm_tx_runtime_limits()); - assert_eq!(inspector_path, limits().to_evm_tx_runtime_limits()); - assert_eq!(trait_path, inspector_path); -} - -/// Installing them again over the same values changes nothing, so a caller that did pre-apply -/// them is not penalised for it. -#[test] -fn test_trait_path_idempotent_when_caller_pre_applied_runtime_limits() { - let mut state = common::state(); - let factory = common::factory(); - let evm = factory - .evm_factory() - .create_evm(&mut state, common::evm_env()) - .with_tx_runtime_limits(limits().to_evm_tx_runtime_limits()); - - let executor = factory.create_executor(evm, common::block_ctx(limits())); - - assert_eq!(*executor.evm().tx_runtime_limits(), limits().to_evm_tx_runtime_limits()); + assert_eq!(trait_path, limits().tx_runtime_limits); + assert_eq!(inspector_path, limits().tx_runtime_limits); } -/// The constructor a node calls directly installs the block's limits, so it and the factory +/// The constructor a node calls directly installs the spec's limits, so it and the factory /// routes agree. #[test] -fn test_direct_construction_applies_block_context_runtime_limits() { +fn test_direct_construction_applies_the_specs_runtime_limits() { let mut state = common::state(); - // Built without any caller-side limits: the case a caller that forgot them produces. - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - assert_eq!(evm.tx_runtime_limits().tx_data_size_limit, u64::MAX); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_tx_runtime_limits(others()); let executor = MegaBlockExecutor::new( evm, - common::block_ctx(limits()), + common::unlimited_ctx(), common::chain_spec(), OpAlloyReceiptBuilder::default(), ); assert_eq!( *executor.evm().tx_runtime_limits(), - limits().to_evm_tx_runtime_limits(), - "the EVM runs under exactly the block's limits" + limits().tx_runtime_limits, + "the EVM runs under exactly the spec's limits" ); } -/// And they are enforced, not only carried: a transaction that keeps more data-size bytes than -/// the block allows is stopped with `MegaLimitExceeded`. +/// And they are enforced, not only carried: a transaction that keeps more data-size bytes than the +/// block's limits allow is stopped with `MegaLimitExceeded`, even when the caller loosened the +/// EVM's limits after building the executor — every transaction runs under the block's. #[test] -fn test_direct_construction_stops_a_transaction_over_the_block_data_size_limit() { - const DATA_SIZE_LIMIT: u64 = 40; +fn test_direct_construction_stops_a_transaction_over_the_blocks_data_size_limit() { + // The body is 310 bytes. One storage write fits; the second crosses. + const DATA_SIZE_LIMIT: u64 = mega_evm::TX_BODY_SIZE + 40; let mut db = common::database(); db.set_account_code( @@ -150,16 +127,24 @@ fn test_direct_construction_stops_a_transaction_over_the_block_data_size_limit() .build(), ); let mut state = State::builder().with_database(db).build(); - let block_limits = BlockLimits::no_limits().with_tx_runtime_limits( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(DATA_SIZE_LIMIT), + // `common::executor_with_limits` builds the executor with `MegaBlockExecutor::new`, and + // holds the block to these limits in place of the spec's. + let mut executor = common::executor_with_limits( + &mut state, + common::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_data_size_limit(DATA_SIZE_LIMIT)), ); - // `common::executor` builds the executor with `MegaBlockExecutor::new` and an EVM that - // carries no limits of its own. - let mut executor = common::executor(&mut state, common::block_ctx(block_limits)); executor.apply_pre_execution_changes().expect("the block starts"); - + executor.evm_mut().set_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + + // The second write is counted once its opcode completed, so the gas covers both slots, their + // records and the body at the byte prices in effect. + let gas_limit = 1_000_000 + + 2 * common::slot_state_gas() + + common::body_history(0) + + mega_evm::write_record_history_gas(2).expect("two records have a price"); let outcome = executor - .execute_transaction_without_commit(&user_tx(0, 1_000_000)) + .execute_transaction_without_commit(&user_tx(0, gas_limit)) .expect("the transaction runs"); assert_eq!( @@ -167,7 +152,7 @@ fn test_direct_construction_stops_a_transaction_over_the_block_data_size_limit() Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: DATA_SIZE_LIMIT, - used: 2 * DATA_SIZE_LIMIT, + used: mega_evm::TX_BODY_SIZE + 2 * 40, frame_local: false, }) ); diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index bf94da4ce..82a3430ca 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,13 +1,37 @@ -//! The admission gate: which inspectors reach block execution. +//! The admission gate: which inspectors reach block execution, and what a declared observer sees +//! of a block's phases. +use alloy_consensus::transaction::Recovered; +use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, +}; use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, - Evm, EvmFactory, + Evm, EvmFactory, FromRecoveredTx, +}; +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase}, + transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, + MegaBlockExecutionError, MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, + MegaTxEnvelope, +}; +use revm::{ + bytecode::opcode::{ADD, POP, PUSH0, SLOAD, SSTORE}, + context::{ContextTr, JournalTr}, + database::State, + handler::FrameResult, + inspector::NoOpInspector, + interpreter::{ + CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, Interpreter, + InterpreterResult, InterpreterTypes, + }, + Inspector, }; -use mega_evm::{test_utils::GasInspector, DeclaredObserver, MegaEvmFactory}; -use revm::inspector::NoOpInspector; +use std::cell::Cell; -use crate::common::{self, user_tx}; +use crate::common::{self, empty_call_gas, system_tx, user_tx}; /// A declared observer reaches a block: its type says it writes nothing back, so what the block /// executes is what the chain executes. @@ -26,14 +50,16 @@ fn test_a_declared_observer_reaches_block_execution() { assert!(executor.evm().is_inspecting(), "the inspector runs"); assert!(!executor.evm().has_rewriting_inspector(), "and is admitted"); executor.apply_pre_execution_changes().expect("a declared observer is admitted"); - executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 1); } /// An inspector that arrived without the declaration does not: block execution refuses it before -/// the block's first call. +/// the block's first call. The refusal is an internal error, not a verdict on the block: the +/// inspector is the node's own choice and says nothing about the block, so a validator that runs +/// one must not mark a valid block invalid. #[test] fn test_a_rewriting_inspector_cannot_reach_block_execution() { let mut state = common::state(); @@ -52,6 +78,12 @@ fn test_a_rewriting_inspector_cannot_reach_block_execution() { format!("{err}").contains("does not admit an inspector that may rewrite execution"), "{err}" ); + assert!(err.as_validation().is_none(), "not a verdict on the block: {err:?}"); + assert_eq!( + err.as_internal().and_then(|error| error.downcast_other::()), + Some(&MegaBlockExecutionError::RewritingInspector), + "an internal error of the node: {err:?}" + ); } /// An EVM with no inspector at all is admitted, which is the ordinary case. @@ -84,8 +116,8 @@ fn test_a_disabled_inspector_is_admitted() { } /// The gate is checked at every entry point, not once: an inspector enabled after the block was -/// set up is refused by the transaction that would run under it, by a commit and by the end of -/// the block. +/// set up is refused by the transaction that would run under it, by the checked commit and by the +/// end of the block. #[test] fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { let mut state = common::state(); @@ -100,17 +132,49 @@ fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { // The one transaction that ran before the inspector was enabled is admitted. let outcome = executor - .execute_transaction_without_commit(&user_tx(0, 100_000)) + .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) .expect("the block is still clean"); executor.evm_mut().set_inspector_enabled(true); - assert!(is_refused(executor.execute_transaction(&user_tx(1, 100_000))), "no transaction runs"); + assert!( + is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), + "no transaction runs" + ); assert!(is_refused(executor.commit_transaction_outcome(outcome)), "nothing commits"); assert!(executor.receipts().is_empty(), "the block packed nothing"); assert!(is_refused(executor.finish_with_counters()), "and the block does not finish"); } +/// alloy-evm's `commit_transaction` cannot fail and checks nothing: it commits the outcome the +/// last execution produced, which passed the gate before it ran, so an inspector enabled since +/// cannot reach it. The next execution is the one the gate refuses. +#[test] +fn test_the_unchecked_commit_commits_what_ran_under_the_gate() { + let mut state = common::state(); + let factory = common::factory(); + let mut evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(GasInspector::new()); + evm.set_inspector_enabled(false); + + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); + let outcome = executor + .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) + .expect("the block is still clean"); + + executor.evm_mut().set_inspector_enabled(true); + + executor.commit_transaction(outcome); + assert_eq!(executor.receipts().len(), 1, "the outcome that ran under the gate is committed"); + assert!( + is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), + "nothing runs after" + ); + assert_eq!(executor.receipts().len(), 1); +} + /// The gate holds for a caller that never runs the block's pre-execution changes: the check is on /// the path that runs code, not only on the block's setup. #[test] @@ -124,7 +188,7 @@ fn test_a_rewriting_inspector_is_refused_without_the_pre_execution_changes() { let mut executor = factory.create_executor(evm, common::unlimited_ctx()); assert!( - is_refused(executor.execute_transaction_without_commit(&user_tx(0, 100_000))), + is_refused(executor.execute_transaction_without_commit(&user_tx(0, empty_call_gas()))), "skipping the setup is not a way past the gate" ); assert!(is_refused(executor.finish_with_counters()), "and neither is finishing the block"); @@ -137,3 +201,232 @@ fn is_refused(result: Result) -> bo Err(err) => format!("{err}").contains("does not admit an inspector that may rewrite"), } } + +/// Counts the frames an inspector sees start and the instructions it sees run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Seen { + frames: usize, + steps: usize, +} + +impl Inspector for Seen { + fn step(&mut self, _: &mut Interpreter, _: &mut CTX) { + self.steps += 1; + } + + fn frame_start(&mut self, _: &mut CTX, _: &mut FrameInput) -> Option { + self.frames += 1; + None + } +} + +/// The state a block runs on, with the EIP-2935 and EIP-4788 contracts' own code, so the +/// pre-block calls run instructions, and a contract that writes a slot. +fn state_with_code() -> State { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + db.set_account_code( + common::CONTRACT, + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(), + ); + State::builder().with_database(db).build() +} + +/// A block whose parent hash and beacon root the pre-block calls record. +fn recording_ctx() -> MegaBlockExecutionCtx { + MegaBlockExecutionCtx::new( + B256::repeat_byte(0xab), + Some(B256::repeat_byte(0xcd)), + Bytes::new(), + BlockLimits::no_limits(), + ) +} + +/// A declared observer sees each phase of a block as the inspector contract says: nothing of the +/// pre-block calls, which run code of their own, the frames of a system transaction and of a user +/// one, and nothing of the block's end, after which the EVM hands the inspector back with what it +/// saw. +#[test] +fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() { + let mut state = state_with_code(); + let committed = CommittedStates::install(&mut state); + let factory = common::factory(); + let mut executor = factory.create_executor_with_trusted_inspector( + &mut state, + common::evm_env(), + recording_ctx(), + DeclaredObserver::new(Seen::default()), + ); + + executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + let states = committed.states(); + assert_eq!( + common::eip_calls(&states), + [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS], + "both pre-block calls ran" + ); + for target in [HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS] { + let wrote = common::call_state(&states, target) + .values() + .any(|account| account.storage.values().any(|slot| slot.is_changed())); + assert!(wrote, "the call to {target} wrote"); + } + assert_eq!(executor.evm().inspector().0, Seen::default(), "and the observer saw none of it"); + + let outcome = executor.run_transaction(&system_tx()).expect("a system transaction"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + assert!(executor.evm().ctx().is_system_originated(), "it is the protocol's own"); + let after_system = executor.evm().inspector().0; + assert_eq!(after_system.frames, 1, "the system transaction's call"); + assert!(after_system.steps > 0, "and the Oracle's code"); + executor.commit_transaction(outcome); + + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("a user transaction"); + let after_user = executor.evm().inspector().0; + assert_eq!(after_user.frames, 2, "the user transaction's call"); + assert!(after_user.steps > after_system.steps); + + let (evm, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.inner.receipts.len(), 2); + assert_eq!(evm.inspector().0, after_user, "the block's end ran no code"); +} + +/// A rewriting inspector is refused at a system transaction as at a user one: the gate is the +/// entry point's, and the system transaction does not run. +#[test] +fn test_a_rewriting_inspector_is_refused_at_a_system_transaction() { + let mut state = state_with_code(); + let factory = common::factory(); + let mut evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(Seen::default()); + evm.set_inspector_enabled(false); + let mut executor = factory.create_executor(evm, recording_ctx()); + executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); + + executor.evm_mut().set_inspector_enabled(true); + assert!(is_refused(executor.run_transaction(&system_tx())), "the system transaction"); + assert_eq!(*executor.evm().inspector(), Seen::default(), "ran nothing"); +} + +/// An inspector works with the block executor: declared an observer, it reaches block execution and +/// sees the transaction's instructions — `CONTRACT` loads a slot, adds one and stores it — each +/// taking gas or none, and the block finishes with the transaction's receipt. +#[test] +fn test_inspector_works_with_block_executor() { + let increment = BytecodeBuilder::default() + .append_many([PUSH0, SLOAD]) + .push_number(1_u8) + .append(ADD) + .append_many([PUSH0, SSTORE]) + .stop() + .build(); + let mut db = common::database(); + db.set_account_code(common::CONTRACT, increment); + let mut state = State::builder().with_database(db).build(); + let factory = common::factory(); + let mut executor = factory.create_executor_with_trusted_inspector( + &mut state, + common::evm_env(), + common::unlimited_ctx(), + DeclaredObserver::new(GasInspector::new()), + ); + + executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); + + let records = executor.evm().inspector().0.records(); + let opcodes: Vec<_> = records.iter().map(|record| record.opcode.as_str()).collect(); + for opcode in ["SLOAD", "ADD", "SSTORE"] { + assert!(opcodes.contains(&opcode), "{opcode} ran: {opcodes:?}"); + } + for record in &records { + assert!(record.gas_before >= record.gas_after, "no instruction gives gas: {record:?}"); + } + let (_, result) = executor.finish().expect("the block finishes"); + assert_eq!(result.receipts.len(), 1); +} + +/// The contract `CONTRACT` calls in the early-return rows. +const CONTRACT_B: Address = address!("0x3000000000000000000000000000000000000003"); + +/// Answers every call below the transaction's own frame itself with a success, and counts those +/// answers and every call's end. +#[derive(Default)] +struct SkipNestedCallInspector { + calls_intercepted: Cell, + call_ends: Cell, +} + +impl Inspector for SkipNestedCallInspector { + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + (context.journal().depth() > 0).then(|| { + self.calls_intercepted.set(self.calls_intercepted.get() + 1); + CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + 0..0, + ) + }) + } + + fn call_end(&mut self, _: &mut CTX, _: &CallInputs, _: &mut CallOutcome) { + self.call_ends.set(self.call_ends.get() + 1); + } +} + +/// Runs `tx` on an EVM over `state` under `inspector`, outside block execution: the route a tool +/// takes. +fn run_as_a_tool<'a, I>( + state: &'a mut State, + tx: &Recovered, + inspector: &mut I, +) -> (MegaTransaction, MegaTransactionOutcome) +where + I: Inspector>>, +{ + let tx = MegaTransaction::from_recovered_tx(tx.inner(), tx.signer()); + let mut evm = + MegaEvmFactory::new().create_evm(state, common::evm_env()).with_inspector(inspector); + let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); + (tx, outcome) +} + +/// An inspector that answers the calls below the transaction's own frame rewrites what execution +/// produces, so block execution refuses it before the transaction runs. On the EVM, the route a +/// tool takes, its answer stands in for the frame: an empty lane keeps the lanes aligned with the +/// frames, the answered call ends as every call does, and the transaction settles as one whose +/// nested call never ran. +#[test] +fn test_inspector_early_return_with_additional_limits() { + let caller = BytecodeBuilder::default().call(CONTRACT_B, U256::ZERO).append(POP).stop().build(); + let database = || { + let mut db = common::database(); + db.set_account_code(common::CONTRACT, caller.clone()); + db.set_account_code(CONTRACT_B, BytecodeBuilder::default().stop().build()); + State::builder().with_database(db).build() + }; + let tx = user_tx(0, 1_000_000); + + let mut state = database(); + let evm = MegaEvmFactory::new() + .create_evm(&mut state, common::evm_env()) + .with_inspector(SkipNestedCallInspector::default()); + let factory = common::factory(); + let mut executor = factory.create_executor(evm, common::unlimited_ctx()); + assert!(is_refused(executor.execute_transaction(&tx)), "no route to a block"); + assert_eq!(executor.evm().inspector().calls_intercepted.get(), 0, "nothing ran"); + + let mut state = database(); + let mut inspector = SkipNestedCallInspector::default(); + let (tx, outcome) = run_as_a_tool(&mut state, &tx, &mut inspector); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(inspector.calls_intercepted.get(), 1, "the nested call was answered"); + assert_eq!(inspector.call_ends.get(), 2, "and both calls ended"); + let body = transaction_body_bytes(&tx); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.gas.state, 0); +} diff --git a/crates/mega-evm/tests/block/l1_attributes.rs b/crates/mega-evm/tests/block/l1_attributes.rs new file mode 100644 index 000000000..d3fe02d78 --- /dev/null +++ b/crates/mega-evm/tests/block/l1_attributes.rs @@ -0,0 +1,144 @@ +//! The block's L1 attributes deposit fits Satin's limits. +//! +//! The deposit is not the protocol's own transaction in the engine's sense: it is held to every +//! per-transaction limit, as any deposit is. A limit it crossed would stop it in every block — +//! every block would stay valid, and the L1 block contract would stop updating. Satin's limits are +//! fixed per spec, so no chain can set one that low; these tests hold the deposit to them. +//! +//! The deposit's data size is its body, its calldata, and one write record for each slot of the +//! L1 block contract it changes. Within one L1 origin it changes the sequence number alone; the +//! deposit that starts an origin changes every value that differs from the last origin's. + +use alloy_consensus::{transaction::Recovered, Sealed}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, bytes, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + test_utils::MemoryDatabase, MegaSpecId, MegaTransactionOutcome, MegaTxEnvelope, ProtocolLimits, + TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use op_alloy_consensus::TxDeposit; +use op_revm::constants::L1_BLOCK_CONTRACT; +use revm::database::State; + +use crate::common::{self, unlimited_ctx, BLOCK_NUMBER}; + +/// The account the L1 attributes deposit comes from, which only the protocol sends from. +const DEPOSITOR: Address = address!("0xdeaddeaddeaddeaddeaddeaddeaddeaddead0001"); + +/// The runtime of OP's `L1Block` 1.6.0, the Isthmus version, as `MegaETH` mainnet holds it at +/// the L1 block contract's address: read from the recorded mainnet state of `mega-evme`'s replay +/// fixtures. +const L1_BLOCK_RUNTIME: Bytes = bytes!("0x608060405234801561001057600080fd5b50600436106101825760003560e01c806364ca23ef116100d8578063b80777ea1161008c578063e591b28211610066578063e591b282146103b0578063e81b2c6d146103d2578063f8206140146103db57600080fd5b8063b80777ea14610337578063c598591814610357578063d84447151461037757600080fd5b80638381f58a116100bd5780638381f58a146103115780638b239f73146103255780639e8c49661461032e57600080fd5b806364ca23ef146102e157806368d5dca6146102f557600080fd5b80634397dfef1161013a57806354fd4d501161011457806354fd4d501461025d578063550fcdc91461029f5780635cf24969146102d857600080fd5b80634397dfef146101fc578063440a5e20146102245780634d5d9a2a1461022c57600080fd5b806309bd5a601161016b57806309bd5a60146101a457806316d3bc7f146101c057806321326849146101ed57600080fd5b8063015d8eb914610187578063098999be1461019c575b600080fd5b61019a6101953660046105bc565b6103e4565b005b61019a610523565b6101ad60025481565b6040519081526020015b60405180910390f35b6008546101d49067ffffffffffffffff1681565b60405167ffffffffffffffff90911681526020016101b7565b604051600081526020016101b7565b6040805173eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee815260126020820152016101b7565b61019a61052d565b6008546102489068010000000000000000900463ffffffff1681565b60405163ffffffff90911681526020016101b7565b60408051808201909152600581527f312e362e3000000000000000000000000000000000000000000000000000000060208201525b6040516101b7919061062e565b60408051808201909152600381527f45544800000000000000000000000000000000000000000000000000000000006020820152610292565b6101ad60015481565b6003546101d49067ffffffffffffffff1681565b6003546102489068010000000000000000900463ffffffff1681565b6000546101d49067ffffffffffffffff1681565b6101ad60055481565b6101ad60065481565b6000546101d49068010000000000000000900467ffffffffffffffff1681565b600354610248906c01000000000000000000000000900463ffffffff1681565b60408051808201909152600581527f45746865720000000000000000000000000000000000000000000000000000006020820152610292565b60405173deaddeaddeaddeaddeaddeaddeaddeaddead000181526020016101b7565b6101ad60045481565b6101ad60075481565b3373deaddeaddeaddeaddeaddeaddeaddeaddead00011461048b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603b60248201527f4c31426c6f636b3a206f6e6c7920746865206465706f7369746f72206163636f60448201527f756e742063616e20736574204c3120626c6f636b2076616c7565730000000000606482015260840160405180910390fd5b6000805467ffffffffffffffff98891668010000000000000000027fffffffffffffffffffffffffffffffff00000000000000000000000000000000909116998916999099179890981790975560019490945560029290925560038054919094167fffffffffffffffffffffffffffffffffffffffffffffffff00000000000000009190911617909255600491909155600555600655565b61052b610535565b565b61052b610548565b61053d610548565b60a43560a01c600855565b73deaddeaddeaddeaddeaddeaddeaddeaddead000133811461057257633cc50b456000526004601cfd5b60043560801c60035560143560801c60005560243560015560443560075560643560025560843560045550565b803567ffffffffffffffff811681146105b757600080fd5b919050565b600080600080600080600080610100898b0312156105d957600080fd5b6105e28961059f565b97506105f060208a0161059f565b9650604089013595506060890135945061060c60808a0161059f565b979a969950949793969560a0850135955060c08501359460e001359350915050565b600060208083528351808285015260005b8181101561065b5785810183015185820160400152820161063f565b8181111561066d576000604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01692909201604001939250505056fea164736f6c634300080f000a"); + +/// The calldata of a recorded mainnet L1 attributes deposit: `setL1BlockValuesIsthmus()` and its +/// packed values, 176 bytes. Bytes 12 to 19 are the sequence number. +const L1_ATTRIBUTES_CALLDATA: Bytes = bytes!("0x098999be000005580000000000000000000000eb000000006a276d57000000000181b0bf0000000000000000000000000000000000000000000000000000000006e4978900000000000000000000000000000000000000000000000000227b46f61450dd10d3420bcc480eb9d4f97cdd4a77c165ba667381f60898af8a4ee999cf538e39000000000000000000000000b98c6b1a805b96707a43e1f1acfa163b68098fa6000000000000000000000000"); + +/// The storage slots `L1Block` 1.6.0 holds, 0 to 8: the most records a deposit can keep. +const L1_BLOCK_SLOTS: u64 = 9; + +/// The deposit's calldata with `delta` added to the sequence number's last byte. +fn calldata(delta: u8) -> Bytes { + let mut calldata = L1_ATTRIBUTES_CALLDATA.to_vec(); + calldata[19] = calldata[19].wrapping_add(delta); + calldata.into() +} + +/// The L1 attributes deposit carrying `calldata`, on a gas limit that writes every slot of the +/// contract with 1,000,000 of regular gas to spare at the byte prices in effect. +fn l1_attributes_deposit(calldata: Bytes) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0x1a), + from: DEPOSITOR, + to: TxKind::Call(L1_BLOCK_CONTRACT), + mint: 0, + value: U256::ZERO, + gas_limit: 1_000_000 + L1_BLOCK_SLOTS * common::slot_state_gas(), + is_system_transaction: false, + input: calldata, + }; + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0x1b))), + DEPOSITOR, + ) +} + +/// What the deposit carrying `calldata(delta)` produced, run as the first transaction of block +/// `number` on `state` and committed: under the spec's limits, or `limits` in their place. +fn run_in_block( + state: &mut State, + number: u64, + delta: u8, + limits: Option, +) -> MegaTransactionOutcome { + let mut env = common::evm_env(); + env.block_env.number = U256::from(number); + let mut executor = common::executor_with_env(state, unlimited_ctx(), env); + assert_eq!(executor.protocol_limits(), &ProtocolLimits::for_spec(MegaSpecId::SATIN)); + if let Some(limits) = limits { + executor = executor.with_protocol_limits(limits); + } + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor + .run_transaction(&l1_attributes_deposit(calldata(delta))) + .expect("the deposit runs"); + let inner = outcome.inner.clone(); + executor.commit_transaction_outcome(outcome).expect("the deposit is included"); + inner +} + +/// What the deposit kept under the spec's limits — its data size and write records — which it +/// must run to a success that no limit stopped. +fn kept_under_the_spec(state: &mut State, number: u64, delta: u8) -> (u64, u64) { + let outcome = run_in_block(state, number, delta, None); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "no limit stops the deposit"); + (outcome.usage.data_size, outcome.usage.write_records) +} + +/// A deposit within one L1 origin changes the sequence number alone and keeps 526 bytes and one +/// write record, the figures measured on recorded mainnet blocks: its 310-byte body, its 176 bytes +/// of calldata and the record. Satin's transaction data-size limit holds it with room to spare. A +/// limit one byte short of it, which no chain can set, would stop it in every block. +/// +/// Expected values: independent (measured on recorded blocks of one L1 origin). +#[test] +fn test_an_l1_attributes_deposit_within_an_origin_fits_the_satin_limits() { + let mut db = common::database(); + db.set_account_code(L1_BLOCK_CONTRACT, L1_BLOCK_RUNTIME); + let mut state = State::builder().with_database(db).build(); + kept_under_the_spec(&mut state, BLOCK_NUMBER, 0); + + let (data_size, write_records) = kept_under_the_spec(&mut state, BLOCK_NUMBER + 1, 1); + assert_eq!((data_size, write_records), (526, 1)); + assert_eq!(data_size, TX_BODY_SIZE + 176 + WRITE_RECORD_SIZE); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert!(data_size <= limits.tx_runtime_limits.tx_data_size_limit); + assert!(data_size <= limits.block_txs_data_limit); + + let short = limits + .with_tx_runtime_limits(limits.tx_runtime_limits.with_tx_data_size_limit(data_size - 1)); + let stopped = run_in_block(&mut state, BLOCK_NUMBER + 2, 2, Some(short)); + assert!(stopped.limit_exceeded.is_some(), "{:?}", stopped.result); +} + +/// The deposit that starts an L1 origin, on a contract that holds nothing yet, changes every slot +/// it sets: one record each, at most one per slot of the contract. That is still far inside +/// Satin's limits. +/// +/// Expected values: independent (the contract's storage layout bounds the records). +#[test] +fn test_an_l1_attributes_deposit_that_starts_an_origin_fits_the_satin_limits() { + let mut db = common::database(); + db.set_account_code(L1_BLOCK_CONTRACT, L1_BLOCK_RUNTIME); + let mut state = State::builder().with_database(db).build(); + + let (data_size, write_records) = kept_under_the_spec(&mut state, BLOCK_NUMBER, 0); + assert!((1..=L1_BLOCK_SLOTS).contains(&write_records), "{write_records}"); + assert_eq!(data_size, TX_BODY_SIZE + 176 + write_records * WRITE_RECORD_SIZE); + let most = TX_BODY_SIZE + 176 + L1_BLOCK_SLOTS * WRITE_RECORD_SIZE; + assert_eq!(most, 846); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert!(most <= limits.tx_runtime_limits.tx_data_size_limit); + assert!(most <= limits.block_txs_data_limit); +} diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index 3df9fa232..c29782cec 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -10,8 +10,8 @@ use op_revm::constants::{ DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, }; use revm::{ - bytecode::opcode::LOG0, - context::{BlockEnv, ContextTr}, + bytecode::opcode::{ADD, DUP1, LOG0, SLOAD, SSTORE}, + context::{result::ExecutionResult, BlockEnv, ContextTr}, Database as _, }; @@ -30,6 +30,15 @@ fn log_generating_contract(data_size: usize) -> Bytes { .build() } +/// A gas limit for a call to the contract that logs `data_size` bytes: 1,000,000 of regular gas on +/// top of what the log and the body cost at the byte prices in effect. +fn log_call_gas(data_size: usize) -> u64 { + 1_000_000 + + common::body_history(0) + + mega_evm::history_gas(mega_evm::log_history_bytes(0, data_size as u64)) + .expect("the log has a price") +} + /// A state whose callee emits a log of `data_size` bytes on every call. fn state_with_log_contract( data_size: usize, @@ -60,11 +69,11 @@ fn test_block_custom_data_limit() { ); executor.apply_pre_execution_changes().expect("the block starts"); - let first = user_tx(0, 1_000_000); + let first = user_tx(0, log_call_gas(2_000)); let gas = executor.execute_transaction(&first).expect("the first transaction is packed"); assert!(gas.tx_gas_used() < first.gas_limit()); - let second = user_tx(1, 1_000_000); + let second = user_tx(1, log_call_gas(2_000)); let gas = executor .execute_transaction(&second) .expect("the transaction that crosses the limit is packed too"); @@ -72,52 +81,69 @@ fn test_block_custom_data_limit() { assert!(executor.limiter().usage.data_size >= 2_500, "the block has crossed its limit"); let err = executor - .execute_transaction(&user_tx(2, 1_000_000)) + .execute_transaction(&user_tx(2, log_call_gas(2_000))) .expect_err("the block has no data-size left"); assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); } -/// Transactions that stay inside the block's limits are all packed. -#[test] -fn test_block_multiple_transactions_within_limits() { - let mut state = state_with_log_contract(100); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(10_000)), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - for nonce in 0..5 { - let tx = user_tx(nonce, 1_000_000); - let gas = executor.execute_transaction(&tx).expect("the transaction is packed"); - assert!(gas.tx_gas_used() < tx.gas_limit(), "transaction {nonce}"); +/// Code that adds one to each of the slots `1..=writes`, so every call keeps `writes` write +/// records whatever the calls before it wrote. +fn incrementing_contract(writes: u64) -> Bytes { + let mut code = BytecodeBuilder::default(); + for slot in 1..=writes { + code = code + .push_number(slot) + .append(DUP1) + .append(SLOAD) + .push_number(1_u8) + .append(ADD) + .append(revm::bytecode::opcode::SWAP1) + .append(SSTORE); } + code.stop().build() +} - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 5); +/// A gas limit for a call to the contract that increments `writes` fresh slots: 10,000,000 of +/// regular gas on top of what the slots, their records and the body cost at the byte prices in +/// effect. +fn incrementing_gas(writes: u64) -> u64 { + 10_000_000 + + writes * common::slot_state_gas() + + common::body_history(0) + + mega_evm::write_record_history_gas(writes).expect("the records have a price") } -/// The same limit mid-block: the transactions before the crossing are packed, the crossing one -/// is packed, and the block ends there. +/// A state whose callee keeps `writes` write records on every call. +fn state_with_incrementing_contract( + writes: u64, +) -> revm::database::State { + let mut db = common::database(); + db.set_account_code(CONTRACT, incrementing_contract(writes)); + revm::database::State::builder().with_database(db).build() +} + +/// The block's KV count is the write records its transactions kept, summed, and no limit refuses a +/// transaction on it: three transactions that keep fifty records each are all packed. #[test] -fn test_block_data_limit_exceeded_mid_block() { - let mut state = state_with_log_contract(2_000); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(6_000)), - ); +fn test_the_block_reports_its_kv_count_and_refuses_nothing_on_it() { + let mut state = state_with_incrementing_contract(50); + // Room in the block's gas for every transaction whatever fifty slots cost. + let mut env = common::evm_env(); + env.block_env.gas_limit = 10_000_000_000; + let mut executor = + common::executor_with_env(&mut state, common::block_ctx(BlockLimits::no_limits()), env); executor.apply_pre_execution_changes().expect("the block starts"); for nonce in 0..3 { - executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("packed"); + executor + .execute_transaction(&user_tx(nonce, incrementing_gas(50))) + .unwrap_or_else(|err| panic!("transaction {nonce} is packed: {err}")); } - assert!( - executor.execute_transaction(&user_tx(3, 1_000_000)).is_err(), - "the block has no data-size left" - ); + assert_eq!(executor.limiter().usage.write_records, 150); let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 3, "the fourth transaction never ran"); + assert_eq!(result.receipts().len(), 3); + assert_eq!(result.usage.write_records, 150, "the block reports its KV count"); } /// A transaction refused before it runs changes nothing: no receipt, and no state. @@ -152,34 +178,51 @@ fn test_block_no_state_commit_on_limit_exceeded() { assert!(result.receipts().is_empty()); } -/// With no size limit configured, a transaction of any size is admitted. +/// The per-transaction data-size limit is not a block limit: a deposit whose body crosses it fails +/// validation, as any transaction with that body does, and is included as a failed deposit with a +/// failed receipt. #[test] -fn test_block_tx_size_limit_default_unlimited() { - let mut state = state_with_log_contract(100); - let mut executor = executor(&mut state, common::unlimited_ctx()); +fn test_a_deposit_over_the_transaction_data_size_limit_is_still_included() { + let limit = mega_evm::TX_BODY_SIZE + 10; + let mut state = common::state(); + let mut executor = common::executor_with_limits( + &mut state, + common::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_data_size_limit(limit)), + ); executor.apply_pre_execution_changes().expect("the block starts"); - let big = common::user_tx_with_input(0, incompressible(20_000), 3_000_000); - assert!(MegaTransactionExt::tx_size(&big) > 20_000); + let deposit = common::deposit_tx(Bytes::from(vec![0xab; 11]), 1_000_000); + let outcome = executor.run_transaction(&deposit).expect("a deposit is not refused"); + assert!( + matches!( + outcome.inner.result, + ExecutionResult::Halt { reason: op_revm::OpHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.inner.result + ); + assert_eq!(outcome.inner.limit_exceeded, None, "the failure is what the deposit reports"); + assert_eq!(outcome.inner.usage.data_size, limit + 1, "its body stays counted"); + executor.commit_transaction_outcome(outcome).expect("the deposit is included"); - executor.execute_transaction(&big).expect("no limit, no refusal"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); + assert!(!result.receipts()[0].status(), "the failed deposit's receipt reports a failure"); } -/// Several transactions fit while their bodies together stay under the block's limit. +/// With no size limit configured, a transaction of any size is admitted. #[test] -fn test_block_tx_size_limit_allows_multiple_transactions() { +fn test_block_tx_size_limit_default_unlimited() { let mut state = state_with_log_contract(100); - let one = MegaTransactionExt::tx_size(&user_tx(0, 1_000_000)); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_encode_size_limit(one * 3)), - ); + let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - for nonce in 0..3 { - executor.execute_transaction(&user_tx(nonce, 1_000_000)).expect("the body fits"); - } - assert_eq!(executor.limiter().block_tx_size_used, one * 3); + let gas_limit = 3_000_000 + common::body_history(20_000) + log_call_gas(100); + let big = common::user_tx_with_input(0, incompressible(20_000), gas_limit); + assert!(MegaTransactionExt::tx_size(&big) > 20_000); + + executor.execute_transaction(&big).expect("no limit, no refusal"); } /// A first transaction whose body is larger than the block's limit is refused, and the block @@ -228,8 +271,12 @@ fn test_block_tx_size_limit_exceeded_mid_block() { #[test] fn test_block_tx_size_limit_with_varying_sizes() { let mut state = state_with_log_contract(100); - let small = user_tx(0, 1_000_000); - let large = common::user_tx_with_input(1, incompressible(4_096), 3_000_000); + let small = user_tx(0, log_call_gas(100)); + let large = common::user_tx_with_input( + 1, + incompressible(4_096), + 3_000_000 + common::body_history(4_096) + log_call_gas(100), + ); let (small_size, large_size) = (MegaTransactionExt::tx_size(&small), MegaTransactionExt::tx_size(&large)); assert!(large_size > small_size); @@ -247,7 +294,50 @@ fn test_block_tx_size_limit_with_varying_sizes() { executor.execute_transaction(&large).expect("the large body fits exactly"); assert_eq!(executor.limiter().block_tx_size_used, small_size + large_size); - executor.execute_transaction(&user_tx(2, 1_000_000)).expect_err("nothing fits any more"); + executor + .execute_transaction(&user_tx(2, log_call_gas(100))) + .expect_err("nothing fits any more"); +} + +/// alloy-evm's commit cannot refuse, and its contract is that an outcome commits before the next +/// transaction executes. A builder that breaks it — two candidates executed against the same +/// pre-state, then both committed through the trait — would pack what the checked commit refuses. +/// The trait's commit makes the same check in a debug build and trips on it: here the block's +/// data-size budget has room for one of the two. +#[cfg(debug_assertions)] +#[test] +fn test_the_trait_commit_trips_on_an_outcome_the_block_has_no_room_for() { + // The body and a log of 100 bytes: what each candidate keeps. + let kept = mega_evm::TX_BODY_SIZE + mega_evm::LOG_BASE_SIZE + 100; + let tx_gas_limit = log_call_gas(100); + let mut db = common::database(); + db.set_account_code(CONTRACT, log_generating_contract(100)); + db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); + let mut state = revm::database::State::builder().with_database(db).build(); + let limits = BlockLimits::no_limits().with_block_txs_data_limit(kept); + let mut executor = executor(&mut state, common::block_ctx(limits)); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = executor + .execute_transaction_without_commit(&tx_from(CALLER, 0, tx_gas_limit)) + .expect("the block has room"); + let second = executor + .execute_transaction_without_commit(&tx_from(CALLER2, 0, tx_gas_limit)) + .expect("nothing has committed yet"); + assert_eq!(second.usage.data_size, kept); + + BlockExecutor::commit_transaction(&mut executor, first); + assert_eq!(executor.limiter().usage.data_size, kept, "the block has kept exactly its limit"); + let tripped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + BlockExecutor::commit_transaction(&mut executor, second); + })) + .expect_err("the commit trips"); + let message = tripped + .downcast_ref::() + .map(String::as_str) + .or_else(|| tripped.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!(message.contains("an outcome the block no longer has room for"), "{message}"); } /// The block's counters may move between a transaction executing and its commit, so what it @@ -257,7 +347,10 @@ fn test_block_tx_size_limit_with_varying_sizes() { /// commit and fill the block, and the third is refused at commit. #[test] fn test_commit_time_pre_execution_check_parallel_simulation() { - const TX_GAS_LIMIT: u64 = 100_000; + // 100,000 of regular gas on top of the history the body and the log cost. + let tx_gas_limit = 100_000 + + common::body_history(0) + + mega_evm::history_gas(mega_evm::log_history_bytes(0, 100)).expect("the log has a price"); let db = || { let mut db = common::database(); @@ -274,11 +367,11 @@ fn test_commit_time_pre_execution_check_parallel_simulation() { let mut probe = executor(&mut state, common::unlimited_ctx()); probe.apply_pre_execution_changes().expect("the block starts"); probe - .execute_transaction(&tx_from(CALLER, 0, TX_GAS_LIMIT)) + .execute_transaction(&tx_from(CALLER, 0, tx_gas_limit)) .expect("the probe transaction executes") .tx_gas_used() }; - let block_gas_limit = spent + TX_GAS_LIMIT; + let block_gas_limit = spent + tx_gas_limit; let mut state = db(); let mut env = common::evm_env(); @@ -286,9 +379,9 @@ fn test_commit_time_pre_execution_check_parallel_simulation() { let mut executor = common::executor_with_env(&mut state, common::unlimited_ctx(), env); executor.apply_pre_execution_changes().expect("the block starts"); - let first = tx_from(CALLER, 0, TX_GAS_LIMIT); - let second = tx_from(CALLER2, 0, TX_GAS_LIMIT); - let third = tx_from(CALLER3, 0, TX_GAS_LIMIT); + let first = tx_from(CALLER, 0, tx_gas_limit); + let second = tx_from(CALLER2, 0, tx_gas_limit); + let third = tx_from(CALLER3, 0, tx_gas_limit); let first = executor.run_transaction(&first).expect("the block has room"); let second = executor.run_transaction(&second).expect("nothing has committed yet"); @@ -348,7 +441,7 @@ fn test_run_transaction_rejects_understated_cached_da_size() { /// The common case of the same path: figures that agree with the transaction are used as they /// are, and the outcome carries them. #[test] -fn test_execute_mega_transaction_succeeds_with_accurate_cache() { +fn test_run_transaction_succeeds_with_accurate_cache() { let mut state = common::state(); let mut executor = executor(&mut state, common::unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); @@ -359,7 +452,7 @@ fn test_execute_mega_transaction_succeeds_with_accurate_cache() { let enriched = EnrichedMegaTx::new_slow(Recovered::new_unchecked(&envelope, CALLER)); let outcome = executor - .execute_mega_transaction(&enriched) + .run_transaction(&enriched) .expect("figures that agree with the transaction are used as they are"); assert_eq!(outcome.da_size, expected_da_size); @@ -415,56 +508,42 @@ fn test_regular_transaction_rejected_by_single_tx_da_limit() { ); } -/// A deposit is exempt from the block's data-availability size too, and adds nothing to it. +/// No building policy refuses a deposit, which the block derived from L1 must include: a builder +/// holding transactions to a declared gas, an encoded size and a block encoded size that one +/// deposit is over on each packs it, and counts its encoding towards the block's. A user +/// transaction over the same policy is refused. #[test] -fn test_deposit_exempt_from_block_da_limit() { - const DA_SIZE_LIMIT: u64 = 100; +fn test_no_building_policy_refuses_a_deposit() { + const GAS_LIMIT: u64 = 3_000_000; + const CALLDATA: usize = 1_000; + let policy = BlockLimits::no_limits() + .with_tx_gas_limit(GAS_LIMIT - 1) + .with_tx_encode_size_limit(CALLDATA as u64) + .with_block_txs_encode_size_limit(CALLDATA as u64); let mut state = common::state(); - let mut executor = executor( - &mut state, - common::block_ctx( - BlockLimits::no_limits() - .with_tx_da_size_limit(DA_SIZE_LIMIT * 10_000) - .with_block_da_size_limit(DA_SIZE_LIMIT), - ), - ); + let mut executor = executor(&mut state, common::block_ctx(policy)); executor.apply_pre_execution_changes().expect("the block starts"); - executor - .execute_transaction(&common::deposit_tx(incompressible(100_000), 3_000_000)) - .expect("a deposit is exempt"); - - assert_eq!(executor.limiter().block_da_size_used, 0, "and adds nothing to the block's"); - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1); -} - -/// The three cases in one block: a small user transaction, a large deposit, a large user -/// transaction. -#[test] -fn test_mixed_deposit_and_regular_transactions() { - const DA_SIZE_LIMIT: u64 = 100; - let mut state = common::state(); - let mut executor = executor( - &mut state, - common::block_ctx( - BlockLimits::no_limits() - .with_tx_da_size_limit(DA_SIZE_LIMIT) - .with_block_da_size_limit(DA_SIZE_LIMIT * 10), + let deposit = common::deposit_tx(Bytes::from(vec![0xab; CALLDATA]), GAS_LIMIT); + let tx_size = MegaTransactionExt::tx_size(&deposit); + assert!(tx_size > CALLDATA as u64, "the deposit's encoding is over both size limits"); + executor.execute_transaction(&deposit).expect("no building policy refuses a deposit"); + assert_eq!(executor.limiter().block_tx_size_used, tx_size, "and it counts its encoding"); + + for (tx, refusal) in [ + (common::user_tx_with_input(0, Bytes::new(), GAS_LIMIT), "Transaction gas limit exceeded"), + ( + common::user_tx_with_input(0, Bytes::from(vec![0xab; CALLDATA]), GAS_LIMIT - 1), + "Transaction encode size limit exceeded", ), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor.execute_transaction(&user_tx(0, 100_000)).expect("a small user transaction fits"); - executor - .execute_transaction(&common::deposit_tx(incompressible(100_000), 3_000_000)) - .expect("a deposit is exempt"); - executor - .execute_transaction(&common::user_tx_with_input(1, incompressible(100_000), 3_000_000)) - .expect_err("a large user transaction is not"); + (common::user_tx_with_input(0, Bytes::new(), GAS_LIMIT - 1), "block_used="), + ] { + let err = executor.execute_transaction(&tx).expect_err("the policy binds a transaction"); + assert!(format!("{err}").contains(refusal), "{refusal}: {err}"); + } let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 2); + assert_eq!(result.receipts().len(), 1, "the deposit alone is packed"); } /// The data-availability footprint is re-checked at commit too: two candidates that each fit the @@ -476,16 +555,18 @@ fn test_mixed_deposit_and_regular_transactions() { #[test] fn test_commit_time_da_footprint_check_parallel_simulation() { const SCALAR: u16 = u16::MAX; - const TX_GAS_LIMIT: u64 = 200_000; + // Above what two thousand calldata bytes cost: the body's history at the byte prices in + // effect, and 64 gas a calldata byte, which covers both its intrinsic charge and its floor. + let tx_gas_limit = common::body_history(2_000) + 15_000 + 64 * 2_000; - let first = tx_with_input(CALLER, incompressible(2_000), TX_GAS_LIMIT); - let second = tx_with_input(CALLER2, incompressible(1_999), TX_GAS_LIMIT); + let first = tx_with_input(CALLER, incompressible(2_000), tx_gas_limit); + let second = tx_with_input(CALLER2, incompressible(1_999), tx_gas_limit); let footprint = |tx: &Recovered| { MegaTransactionExt::estimated_da_size(tx) * u64::from(SCALAR) }; // The block holds exactly the larger of the two, so each fits alone and the two do not. let budget = footprint(&first).max(footprint(&second)); - assert!(budget >= TX_GAS_LIMIT, "the budget is the block's gas limit, which must fit a tx"); + assert!(budget >= tx_gas_limit, "the budget is the block's gas limit, which must fit a tx"); let mut db = common::database(); db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index 8e51e26b1..f4d0c9747 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -1,13 +1,31 @@ //! Tests of the block executor. +mod activation; mod block_hashes; +mod bucket_ids; +mod building_policy; mod common; mod counters; +mod deposits; +mod detention; mod eips; +mod external_envs; mod factory; mod inspector; +mod l1_attributes; mod limits; +mod predeploys; +mod receipt_goldens; mod receipts; mod rules; mod salt; mod schedule; +mod sequencer_registry; +mod sequences; +#[path = "../shared/snapshot.rs"] +mod snapshot; +mod stale; +mod state_gas; +mod system_tx_budgets; +mod transfer_logs; +mod witness; diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs new file mode 100644 index 000000000..9986d2c2d --- /dev/null +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -0,0 +1,274 @@ +//! The check Satin's activation block makes of the predeploys, and the EIP-7997 factory round +//! trip. +//! +//! The block in which Satin activates reads the six system contracts and the factory, which a chain +//! that ran Rex6 holds, and is invalid when one of them does not hold the code Satin expects; no +//! other block reads them, and no block deploys or upgrades them. + +use alloy_eips::{eip2935::HISTORY_STORAGE_ADDRESS, eip4788::BEACON_ROOTS_ADDRESS}; +use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; +use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; +use mega_evm::{ + system::{ + storage_slots::{PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS}, + system_contract_specs, CREATE2_FACTORY_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + }, + test_utils::{rex6_predeploys, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, + MegaBlockExecutionCtx, MegaBlockExecutionError, +}; +use op_revm::constants::L1_BLOCK_CONTRACT; +use revm::{ + context::result::ExecutionResult, database::State, primitives::KECCAK_EMPTY, state::EvmState, +}; + +use crate::common::{self, executor, named_accounts, recovered, tx, unlimited_ctx}; + +/// The context of the block in which Satin activates, as a node sets it from the schedule and +/// the parent's timestamp: deposit-only, and the check of the predeploys. +fn activation_ctx() -> MegaBlockExecutionCtx { + unlimited_ctx().with_no_user_tx_activation_block(true).with_satin_activation_block(true) +} + +/// The states the pre-block steps of a block over `state` held to `ctx` committed, in order, as a +/// commit hook on `state` receives them. +fn start( + state: &mut State, + ctx: MegaBlockExecutionCtx, +) -> Result, BlockExecutionError> { + let committed = CommittedStates::install(state); + let mut executor = executor(state, ctx); + executor.apply_pre_execution_changes()?; + assert_eq!(executor.gas().execution, 0); + assert_eq!(executor.gas().state, 0); + assert_eq!(executor.gas().history, 0); + Ok(committed.states()) +} + +/// The account each pre-block state of a block names, in commit order: the two EIP calls' targets, +/// in the activation block the seven predeploys in order, the registry, whose pending changes are +/// read and found none due on these blocks, and the L1 block contract, whose info is read. +fn expected_accounts(activation: bool) -> Vec
{ + let mut expected = vec![HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]; + if activation { + expected.extend(system_contract_specs().map(|spec| spec.address)); + } + expected.extend([SEQUENCER_REGISTRY_ADDRESS, L1_BLOCK_CONTRACT]); + expected +} + +/// [S18] Satin's activation block over a state shaped as Rex6 leaves it finds every predeploy with +/// Satin's code. Each pre-block step commits a state of its own, and a commit hook receives them in +/// order, read-only entries included: the two EIP calls, which touch their contracts; the seven +/// accounts, each a read-only entry as the chain holds it — no write, no created mark, the six at +/// nonce 0 and the factory at its own; the registry's two pending slots, read only; and the L1 +/// block contract, read only. The block after it, on the committed state, reads none of the +/// predeploys, and neither block changes one. +/// +/// Expected values: independent (the Rex6-shaped accounts the test puts in the state). +#[test] +fn test_the_activation_block_reads_the_seven_predeploys_once() { + let mut state = common::state(); + let activation = start(&mut state, activation_ctx()).expect("the activation block starts"); + assert_eq!(named_accounts(&activation), expected_accounts(true)); + for (call, target) in activation.iter().zip([HISTORY_STORAGE_ADDRESS, BEACON_ROOTS_ADDRESS]) { + assert!(call[&target].is_touched(), "the call to {target} touches it"); + } + let held = rex6_predeploys(common::registry_roles()); + for (i, (address, info, _)) in held.iter().enumerate() { + let account = &activation[2 + i][address]; + assert!(!account.is_touched() && !account.is_created(), "{address} is read only"); + assert!(account.storage.is_empty(), "{address}: no slot is written"); + assert_eq!((account.info.code_hash, account.info.nonce), (info.code_hash, info.nonce)); + } + let registry = &activation[2 + held.len()][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched() && !registry.is_created(), "the registry is read only"); + assert_eq!( + registry.storage.keys().copied().collect::>(), + [PENDING_SYSTEM_ADDRESS, PENDING_SEQUENCER].into(), + "the read of its pending changes" + ); + assert!(registry.storage.values().all(|slot| !slot.is_changed())); + let l1_block = &activation[3 + held.len()][&L1_BLOCK_CONTRACT]; + assert!(!l1_block.is_touched() && !l1_block.is_created(), "the L1 block info is read only"); + + let next = start(&mut state, unlimited_ctx()).expect("the next block starts"); + assert_eq!(named_accounts(&next), expected_accounts(false), "no other block reads them"); + for (address, info, _) in held { + let now = revm::Database::basic(&mut state, address).unwrap().expect("still there"); + assert_eq!((now.code_hash, now.nonce), (info.code_hash, info.nonce), "{address}"); + } +} + +/// [S18] A block that is not Satin's activation block reads no predeploy: over a database that +/// fails every load of the Oracle's account, it starts, where the activation block fails on the +/// load as an internal error, the database's and no verdict on the block. +/// +/// Expected values: independent (the injected failure). +#[test] +fn test_no_other_block_reads_a_predeploy() { + let failing = || { + let mut db = ErrorInjectingDatabase::new(common::database()); + db.fail_on_account = Some(ORACLE_CONTRACT_ADDRESS); + State::builder().with_database(db).build() + }; + let start_on = |ctx: MegaBlockExecutionCtx| { + let mut state = failing(); + let evm = alloy_evm::EvmFactory::create_evm( + &mega_evm::MegaEvmFactory::new(), + &mut state, + common::evm_env(), + ); + mega_evm::MegaBlockExecutor::new( + evm, + ctx, + common::chain_spec(), + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder::default(), + ) + .apply_pre_execution_changes() + }; + start_on(unlimited_ctx()).expect("an ordinary block reads no predeploy"); + let error = start_on(activation_ctx()).expect_err("the activation block reads the Oracle"); + assert!(matches!(error, BlockExecutionError::Internal(_)), "{error:?}"); + assert!(error.to_string().contains("injected basic() error"), "{error}"); +} + +/// The refusal of Satin's activation block over `db`: a verdict on the block, before the refused +/// predeploy's state is committed, so the last state committed is the predeploy before it. +fn refused(db: MemoryDatabase, at: Address) -> MegaBlockExecutionError { + let mut state = State::builder().with_database(db).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor(&mut state, activation_ctx()); + let error = executor.apply_pre_execution_changes().expect_err("the block is refused"); + let delivered = named_accounts(&committed.states()); + let position = system_contract_specs().iter().position(|spec| spec.address == at).unwrap(); + assert_eq!(delivered, expected_accounts(true)[..2 + position], "refused at {at}"); + let Some(BlockValidationError::Other(inner)) = error.as_validation() else { + panic!("a verdict on the block: {error:?}"); + }; + inner.downcast_ref::().expect("the engine's refusal").clone() +} + +/// [S18] The activation block is invalid when a predeploy does not hold Satin's code, with one +/// error naming the address, the expected hash and the one held: other code at any of the seven, +/// no account, an account without code — funded, or at a used nonce — the Oracle at 1.0.0 or +/// 1.1.0, and the registry at 1.0.0. Nothing is created or upgraded. +/// +/// Expected values: independent (the code hash each state holds). +#[test] +fn test_an_activation_block_without_the_expected_code_is_refused() { + use mega_system_contracts::{oracle, sequencer_registry}; + let with = |edit: &dyn Fn(&mut MemoryDatabase)| { + let mut db = common::database(); + edit(&mut db); + db + }; + let mut cases: Vec<(String, Address, MemoryDatabase, B256)> = system_contract_specs() + .into_iter() + .map(|spec| { + let db = with(&|db| db.set_account_code(spec.address, Bytes::from_static(&[0xfe]))); + (format!("other code at {}", spec.address), spec.address, db, keccak256([0xfe])) + }) + .collect(); + cases.extend([ + ( + "no account at the Oracle's address".to_string(), + ORACLE_CONTRACT_ADDRESS, + with(&|db| { + db.cache.accounts.remove(&ORACLE_CONTRACT_ADDRESS); + }), + KECCAK_EMPTY, + ), + ( + "a funded registry without code".to_string(), + SEQUENCER_REGISTRY_ADDRESS, + with(&|db| { + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, Bytes::new()); + db.set_account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1)); + }), + KECCAK_EMPTY, + ), + ( + "a factory without code at a used nonce".to_string(), + CREATE2_FACTORY_ADDRESS, + with(&|db| db.set_account_code(CREATE2_FACTORY_ADDRESS, Bytes::new())), + KECCAK_EMPTY, + ), + ( + "the Oracle at 1.0.0".to_string(), + ORACLE_CONTRACT_ADDRESS, + with(&|db| db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_0_0_CODE)), + oracle::V1_0_0_CODE_HASH, + ), + ( + "the Oracle at 1.1.0".to_string(), + ORACLE_CONTRACT_ADDRESS, + with(&|db| db.set_account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_1_0_CODE)), + oracle::V1_1_0_CODE_HASH, + ), + ( + "the registry at 1.0.0".to_string(), + SEQUENCER_REGISTRY_ADDRESS, + with(&|db| { + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, sequencer_registry::V1_0_0_CODE) + }), + sequencer_registry::V1_0_0_CODE_HASH, + ), + ]); + for (name, address, db, found) in cases { + let expected = system_contract_specs() + .into_iter() + .find(|spec| spec.address == address) + .expect("a predeploy") + .code_hash; + let refusal = refused(db, address); + assert_eq!( + refusal, + MegaBlockExecutionError::UnexpectedSystemContractCode { address, expected, found }, + "{name}" + ); + let message = refusal.to_string(); + assert!(message.contains(&address.to_string()), "{name}: {message}"); + assert!(message.contains("when Satin activates"), "{name}: {message}"); + } +} + +/// Calling the factory with salt || initcode returns the CREATE2 address as 20 bytes. +#[test] +fn test_a_create2_round_trip_through_the_factory() { + let mut state = common::state(); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let salt = B256::repeat_byte(0x11); + // Constructor: RETURN empty runtime. + let init = Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]); + let mut input = salt.to_vec(); + input.extend_from_slice(&init); + let expected = CREATE2_FACTORY_ADDRESS.create2_from_code(salt, init.as_ref()); + // 1,000,000 of regular gas on top of the account the creation adds, the history of the body, + // and 64 times the history of the creation's two write records, at the byte prices in effect: + // the factory forwards all but a 64th of its gas to the creation and pays the records from + // the 64th it keeps. + let gas_limit = 1_000_000 + + common::new_account_state_gas() + + common::body_history(input.len() as u64) + + 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + + let outcome = executor + .execute_transaction_without_commit(&recovered(tx( + 0, + CREATE2_FACTORY_ADDRESS, + Bytes::from(input), + gas_limit, + ))) + .expect("the factory call runs"); + match &outcome.result { + ExecutionResult::Success { output, .. } => { + let data = output.data(); + assert_eq!(data.len(), 20, "the factory returns 20 bytes"); + assert_eq!(Address::from_slice(data), expected); + } + other => panic!("the factory call should succeed, got {other:?}"), + } +} diff --git a/crates/mega-evm/tests/block/receipt_goldens.rs b/crates/mega-evm/tests/block/receipt_goldens.rs new file mode 100644 index 000000000..db9727e75 --- /dev/null +++ b/crates/mega-evm/tests/block/receipt_goldens.rs @@ -0,0 +1,321 @@ +//! One block's receipts, pinned as the bytes a node hashes into the receipts root. +//! +//! A receipt's `cumulative_gas_used` is the running sum of [`mega_evm::MegaGasUsage::gas_used`]. +//! That figure is what the transaction spent from both pools — regular, state and history gas +//! together — after the refund, and at least the EIP-7623 floor. It is also the block header's +//! gas used. The execution ledger the block counts, `max(regular, floor)`, is not it. +//! +//! The encoded receipt carries the status, that cumulative gas, the logs bloom and the logs. +//! It does not carry revert data. The limit stop's `MegaLimitExceeded` payload is on the +//! execution outcome, and this test pins that payload beside the failed receipt. +//! +//! The exact bytes are the spec's own byte prices. At any other price the same block is still +//! checked: each bloom is its logs', each cumulative step is that transaction's `gas_used`, and +//! the receipts root is the ordered trie of the encodings. + +use alloy_consensus::{transaction::Recovered, Sealed, TxReceipt}; +use alloy_eips::eip2718::Encodable2718; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, hex, logs_bloom, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::is_transfer_log, LimitCheck, LimitKind, MegaLimitExceeded, MegaTxEnvelope, + TX_BODY_SIZE, +}; +use op_alloy_consensus::{OpReceiptEnvelope, TxDeposit}; +use revm::{context::result::ExecutionResult, database::State}; + +use crate::common::{self, body_history, new_account_state_gas, system_tx, CALLER, CONTRACT}; + +/// The data-size limit the block holds every transaction to. +/// +/// Above what the other five transactions keep, and above the stop transaction's body, which +/// validation holds to it, but below that body with what its first frame's start makes. +const DATA_SIZE_LIMIT: u64 = 2_000; + +/// Calldata long enough that the stop transaction's body fits [`DATA_SIZE_LIMIT`] and its first +/// frame's start — its value's record and transfer log — crosses it, before anything runs. +const STOP_CALLDATA: usize = 1_600; + +/// What the stop transaction's first frame's start counts: the record of the account its value +/// writes, and the transfer log of the value. +const STOP_START: u64 = mega_evm::WRITE_RECORD_SIZE + mega_evm::TRANSFER_LOG_SIZE; + +/// The account the value transfer pays, absent from the pre-state so the transfer creates it. +const PAYEE: Address = address!("0x1000000000000000000000000000000000000003"); + +/// The account whose code reverts, so one receipt is a failed transaction. +const REVERTER: Address = address!("0x1000000000000000000000000000000000000004"); + +/// The depositor, distinct from [`CALLER`], so the deposit does not spend the caller's nonce. +const DEPOSITOR: Address = address!("0x2000000000000000000000000000000000000003"); + +/// Init code that deploys empty runtime code: `PUSH0 PUSH0 RETURN`. +const EMPTY_INIT: &[u8] = &[0x5f, 0x5f, 0xf3]; + +/// Code that reverts with empty data: `PUSH0 PUSH0 REVERT`. +const REVERT_CODE: &[u8] = &[0x5f, 0x5f, 0xfd]; + +/// Whether this process prices bytes at the constants the spec fixes. +/// +/// The exact receipt bytes move with those prices. A measurement build still runs the block and +/// checks the shape of the receipts; it does not compare the spec's bytes. +fn at_spec_prices() -> bool { + if mega_evm::active_satin_prices().is_constants() { + return true; + } + mega_evm::test_utils::note_price_guard( + "receipt byte goldens are pinned at the spec's byte prices", + ); + false +} + +/// Gas for a legacy call or creation that keeps `records` write records and pays `state_gas`, +/// with `calldata` bytes of calldata, at the byte prices in effect. +fn room(calldata: u64, records: u64, state_gas: u64) -> u64 { + 1_000_000 + + body_history(calldata) + + mega_evm::write_record_history_gas(records).expect("the records have a price") + + state_gas +} + +/// A legacy transaction from [`CALLER`] with its own value and calldata. +fn legacy( + nonce: u64, + to: TxKind, + value: u64, + input: Bytes, + gas_limit: u64, +) -> Recovered { + common::legacy_from(CALLER, nonce, to, U256::from(value), input, gas_limit, 1_000_000) +} + +/// A deposit from [`DEPOSITOR`] to [`CONTRACT`]. +fn depositor_tx() -> Recovered { + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0xd1), + from: DEPOSITOR, + to: TxKind::Call(CONTRACT), + mint: 0, + value: U256::ZERO, + gas_limit: room(0, 2, 0), + is_system_transaction: false, + input: Bytes::new(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0xd1))), + DEPOSITOR, + ) +} + +/// The state the block runs on: a funded depositor and a contract that reverts. +fn state() -> State { + let mut db = common::database(); + db.set_account_balance(DEPOSITOR, U256::from(1_000_000_000_000_000_u64)); + db.set_account_code(REVERTER, Bytes::from_static(REVERT_CODE)); + State::builder().with_database(db).build() +} + +/// What one included transaction contributed, read before its receipt is built. +struct Kept { + /// [`mega_evm::MegaGasUsage::gas_used`], the figure the receipt adds. + gas_used: u64, + /// The limit stop's revert data, when this transaction is the stop. + stop: Option, +} + +/// The receipts root of the six encodings at the spec's byte prices. +const RECEIPTS_ROOT: &str = "93b0c0565033f73a5b75072f5ba52e4586a3fdee75a5fbc99109cc0a16ae07b7"; + +/// `cumulative_gas_used` of each receipt at the spec's byte prices. +const CUMULATIVE_GAS: [u64; 6] = [15_000, 250_400, 465_080, 507_364, 746_082, 947_264]; + +/// The logs bloom of a receipt that carries no logs. +const EMPTY_BLOOM: &str = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + +/// The logs bloom of the value transfer, whose one log is the EIP-7708 transfer. +const TRANSFER_BLOOM: &str = "00000000000000000000080000000000000000000000000004000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000008000000000000000000000000000000000000001000400000000000000004000000000000000000000002000000000000000000000000"; + +/// Each receipt's logs bloom at the spec's byte prices. +const BLOOMS: [&str; 6] = + [EMPTY_BLOOM, TRANSFER_BLOOM, EMPTY_BLOOM, EMPTY_BLOOM, EMPTY_BLOOM, EMPTY_BLOOM]; + +/// Each receipt's EIP-2718 encoding at the spec's byte prices. +const ENCODINGS: [&str; 6] = [ + // the deposit + "7ef9010a01823a98b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c08001", + // the value transfer + "f901a7018303d220b9010000000000000000000000080000000000000000000000000004000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000008000000000000000000000000000000000000001000400000000000000004000000000000000000000002000000000000000000000000f89df89b94fffffffffffffffffffffffffffffffffffffffef863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa00000000000000000000000002000000000000000000000000000000000000002a00000000000000000000000001000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000001", + // the limit stop + "f9010980830718b8b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + // the failed call + "f90109808307bde4b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + // the creation + "f9010901830b6262b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + // the system-address transaction + "f9010901830e7440b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", +]; + +/// The six receipts of one block, and the receipts root of their encodings. +#[test] +fn test_a_blocks_receipts_pin_their_bytes_bloom_and_cumulative_gas() { + let mut state = state(); + let mut executor = common::executor_with_limits( + &mut state, + common::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_data_size_limit(DATA_SIZE_LIMIT)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let stop_input = Bytes::from(vec![0xab; STOP_CALLDATA]); + let stop_body = TX_BODY_SIZE + STOP_CALLDATA as u64; + assert!( + stop_body <= DATA_SIZE_LIMIT && stop_body + STOP_START > DATA_SIZE_LIMIT, + "the stop's body fits the limit, and its first frame's start crosses it", + ); + let txs = [ + depositor_tx(), + legacy(0, TxKind::Call(PAYEE), 1, Bytes::new(), room(0, 4, new_account_state_gas())), + // The first frame's input charges the account the value would create in the empty + // `CONTRACT` before the stop gives it back. + legacy( + 1, + TxKind::Call(CONTRACT), + 1, + stop_input, + room(STOP_CALLDATA as u64, 1, new_account_state_gas()), + ), + legacy(2, TxKind::Call(REVERTER), 0, Bytes::new(), room(0, 2, 0)), + legacy( + 3, + TxKind::Create, + 0, + Bytes::from_static(EMPTY_INIT), + room(EMPTY_INIT.len() as u64, 4, new_account_state_gas()), + ), + system_tx(), + ]; + + let mut kept = Vec::with_capacity(txs.len()); + for (index, tx) in txs.iter().enumerate() { + let outcome = executor + .run_transaction(tx) + .unwrap_or_else(|err| panic!("transaction {index} executes: {err}")); + let stop = match &outcome.inner.result { + ExecutionResult::Revert { output, .. } => Some(output.clone()), + ExecutionResult::Success { .. } => None, + other => panic!("transaction {index} halted: {other:?}"), + }; + if index == 2 { + assert_eq!( + outcome.inner.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: DATA_SIZE_LIMIT, + used: stop_body + STOP_START, + frame_local: false, + }), + "the first frame's start crossed the data-size limit", + ); + let output = stop.clone().expect("the stop reverts"); + assert_eq!( + output.as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } + .abi_encode(), + "the stop's revert data is MegaLimitExceeded", + ); + } else { + assert!( + outcome.inner.limit_exceeded.is_none(), + "transaction {index} is not a limit stop: {:?}", + outcome.inner.limit_exceeded, + ); + } + kept.push(Kept { gas_used: outcome.inner.gas.gas_used, stop }); + executor + .commit_transaction_outcome(outcome) + .unwrap_or_else(|err| panic!("transaction {index} is included: {err}")); + } + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + let receipts = result.receipts(); + assert_eq!(receipts.len(), 6); + + let mut cumulative = 0_u64; + let mut encoded = Vec::with_capacity(receipts.len()); + for (index, (receipt, kept)) in receipts.iter().zip(&kept).enumerate() { + cumulative += kept.gas_used; + assert_eq!( + receipt.cumulative_gas_used(), + cumulative, + "receipt {index} adds this transaction's gas_used", + ); + assert_eq!( + receipt.bloom(), + logs_bloom(receipt.logs()), + "receipt {index}'s bloom is its logs'", + ); + encoded.push(receipt.encoded_2718()); + } + + assert!(receipts[0].status(), "the deposit succeeds"); + match &receipts[0] { + OpReceiptEnvelope::Deposit(deposit) => { + assert_eq!( + deposit.receipt.deposit_nonce, + Some(0), + "the depositor's nonce before the deposit", + ); + assert_eq!( + deposit.receipt.deposit_receipt_version, + Some(1), + "Canyon's receipt version", + ); + assert!(deposit.receipt.inner.logs.is_empty(), "a zero-value deposit emits no log"); + } + other => panic!("the deposit's receipt is a deposit receipt, got {other:?}"), + } + + assert!(receipts[1].status(), "the value transfer succeeds"); + let transfer_logs = receipts[1].logs(); + assert_eq!(transfer_logs.len(), 1, "the value transfer emits its EIP-7708 log"); + assert!(is_transfer_log(&transfer_logs[0]), "that log is a transfer"); + + assert!(!receipts[2].status(), "the limit stop is a failed receipt"); + assert!(receipts[2].logs().is_empty(), "the stop reverts before any log, its value's included"); + assert!(kept[2].stop.is_some(), "the outcome carried MegaLimitExceeded"); + + assert!(!receipts[3].status(), "the reverting call is a failed receipt"); + assert!(receipts[3].logs().is_empty()); + assert!( + kept[3].stop.as_ref().is_some_and(|data| data.is_empty()), + "the contract reverted with no data", + ); + + assert!(receipts[4].status(), "the creation succeeds"); + assert!(receipts[4].logs().is_empty(), "a zero-value creation emits no transfer log"); + + assert!(receipts[5].status(), "the system-address transaction succeeds"); + assert!( + !matches!(receipts[5], OpReceiptEnvelope::Deposit(_)), + "the block receipt follows the legacy envelope, before the engine promotes it", + ); + + let root = alloy_trie::root::ordered_trie_root_with_encoder(&encoded, |receipt, buf| { + buf.extend_from_slice(receipt); + }); + + if !at_spec_prices() { + return; + } + assert_eq!(hex::encode(root), RECEIPTS_ROOT, "the receipts root"); + for (index, (receipt, bytes)) in receipts.iter().zip(&encoded).enumerate() { + assert_eq!( + receipt.cumulative_gas_used(), + CUMULATIVE_GAS[index], + "receipt {index} cumulative gas", + ); + assert_eq!(hex::encode(receipt.bloom()), BLOOMS[index], "receipt {index} bloom"); + assert_eq!(hex::encode(bytes), ENCODINGS[index], "receipt {index} bytes"); + } +} diff --git a/crates/mega-evm/tests/block/receipts.rs b/crates/mega-evm/tests/block/receipts.rs index 868dd4f40..773c81d99 100644 --- a/crates/mega-evm/tests/block/receipts.rs +++ b/crates/mega-evm/tests/block/receipts.rs @@ -1,20 +1,8 @@ //! The receipts a block builds, which go through an OP receipt builder. use alloy_evm::block::BlockExecutor; -use alloy_hardforks::ForkCondition; -use alloy_op_hardforks::OpHardfork; -use alloy_primitives::Bytes; -use op_alloy_consensus::OpReceiptEnvelope; -use crate::common::{self, deposit_tx, executor, executor_with_spec, unlimited_ctx, user_tx}; - -/// The deposit receipt of the block's only transaction. -fn deposit_receipt(receipts: &[OpReceiptEnvelope]) -> &op_alloy_consensus::OpDepositReceipt { - match receipts { - [OpReceiptEnvelope::Deposit(deposit)] => &deposit.receipt, - other => panic!("one deposit receipt, got {other:?}"), - } -} +use crate::common::{self, empty_call_gas, executor, unlimited_ctx, user_tx}; /// A block's receipts are readable while it is still being built, and they leave with its /// result. @@ -25,45 +13,13 @@ fn test_the_receipts_are_readable_during_the_block_and_leave_with_its_result() { executor.apply_pre_execution_changes().expect("the block starts"); assert!(executor.receipts().is_empty(), "nothing is packed yet"); - executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); assert_eq!(executor.receipts().len(), 1, "the committed transaction has its receipt"); - executor.execute_transaction(&user_tx(1, 100_000)).expect("the transaction executes"); + executor.execute_transaction(&user_tx(1, empty_call_gas())).expect("the transaction executes"); assert_eq!(executor.receipts().len(), 2); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 2); assert_eq!(result.into_receipts().len(), 2, "the receipts leave with the result"); } - -/// A deposit's receipt carries the depositor's nonce and the receipt version, each from the fork -/// that introduced it: Regolith for the nonce, Canyon for the version. -#[test] -fn test_a_deposit_receipt_reports_the_nonce_and_the_version_the_schedule_activated() { - let mut state = common::state(); - let mut executor = executor(&mut state, unlimited_ctx()); - executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&deposit_tx(Bytes::new(), 100_000)).expect("the deposit executes"); - - let receipt = deposit_receipt(executor.receipts()); - assert_eq!(receipt.deposit_nonce, Some(0), "the depositor's nonce before the deposit ran"); - assert_eq!(receipt.deposit_receipt_version, Some(1), "Canyon's receipt version"); -} - -/// The same deposit on a chain that has reached neither fork: no nonce and no version. The two -/// fields follow the chain's schedule, not the transaction. -#[test] -fn test_a_deposit_receipt_omits_what_the_schedule_has_not_activated() { - let before_both = common::chain_spec() - .with(OpHardfork::Regolith, ForkCondition::Never) - .with(OpHardfork::Canyon, ForkCondition::Never); - - let mut state = common::state(); - let mut executor = executor_with_spec(&mut state, unlimited_ctx(), before_both); - executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&deposit_tx(Bytes::new(), 100_000)).expect("the deposit executes"); - - let receipt = deposit_receipt(executor.receipts()); - assert_eq!(receipt.deposit_nonce, None, "Regolith brought the nonce"); - assert_eq!(receipt.deposit_receipt_version, None, "Canyon brought the version"); -} diff --git a/crates/mega-evm/tests/block/rules.rs b/crates/mega-evm/tests/block/rules.rs index d9c12c9fe..fcadeae17 100644 --- a/crates/mega-evm/tests/block/rules.rs +++ b/crates/mega-evm/tests/block/rules.rs @@ -18,13 +18,18 @@ use revm::{ }; use crate::common::{ - self, deposit_tx, executor, unlimited_ctx, user_tx, TestExecutor, BLOCK_GAS_LIMIT, BLOCK_NUMBER, + self, deposit_tx, empty_call_gas, executor, system_tx, unlimited_ctx, user_tx, TestExecutor, + BLOCK_GAS_LIMIT, BLOCK_NUMBER, }; /// The word the L1 block contract holds at its scalars slot: the data-availability footprint /// gas scalar, the operator fee scalar and the operator fee constant, at the offsets the fork /// reads them from. -fn scalars_word(da_footprint: u16, operator_fee_scalar: u32, operator_fee_constant: u64) -> U256 { +pub(crate) fn scalars_word( + da_footprint: u16, + operator_fee_scalar: u32, + operator_fee_constant: u64, +) -> U256 { let mut word = [0_u8; 32]; word[DA_FOOTPRINT_GAS_SCALAR_OFFSET..DA_FOOTPRINT_GAS_SCALAR_OFFSET + 2] .copy_from_slice(&da_footprint.to_be_bytes()); @@ -44,7 +49,7 @@ fn state_with_scalars(word: U256) -> State /// Code that writes its 32 bytes of calldata to the scalars slot, which is what the L1 info /// deposit's setter does for the fields this test reads. -fn l1_block_setter() -> Bytes { +pub(crate) fn l1_block_setter() -> Bytes { BytecodeBuilder::default() .push_number(0_u64) .append(CALLDATALOAD) @@ -79,37 +84,23 @@ fn operator_fee_paid(executor: TestExecutor<'_>) -> U256 { .unwrap_or_default() } -/// Rule 1, alloy-op-evm's `no_user_tx_activation_block`: the block a fork activates in carries -/// the chain's own transactions only, and a user transaction in it is refused before it runs. +/// Rule 1 decides on the envelope: a Mega System Transaction is a legacy transaction in the block, +/// so an activation block refuses it before it runs, as it refuses a user's, although the engine +/// would promote it to a deposit as it ran it. #[test] -fn test_activation_block_rejects_a_user_transaction() { +fn test_activation_block_rejects_a_mega_system_transaction() { let mut state = common::state(); let mut executor = executor(&mut state, unlimited_ctx().with_no_user_tx_activation_block(true)); executor.apply_pre_execution_changes().expect("the block starts"); let err = executor - .execute_transaction(&user_tx(0, 100_000)) - .expect_err("a user transaction has no place in an activation block"); + .execute_transaction(&system_tx()) + .expect_err("a legacy envelope has no place in an activation block"); assert!(format!("{err}").contains("non-deposit transaction in fork activation block"), "{err}"); assert!(executor.receipts().is_empty(), "nothing was packed"); } -/// Rule 1, the other half: the same block executes deposits. -#[test] -fn test_activation_block_executes_deposits() { - let mut state = common::state(); - let mut executor = executor(&mut state, unlimited_ctx().with_no_user_tx_activation_block(true)); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor - .execute_transaction(&deposit_tx(Bytes::new(), 100_000)) - .expect("a deposit is what an activation block is for"); - - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1); -} - /// Rule 2, alloy-op-evm's Jovian DA footprint block limit: with no scalar in state the rule /// costs nothing and the block reports no blob gas. #[test] @@ -118,7 +109,7 @@ fn test_da_footprint_is_inert_without_a_scalar() { let mut executor = executor(&mut state, unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.blob_gas_used, 0, "no scalar, no footprint"); @@ -133,8 +124,8 @@ fn test_da_footprint_within_the_block_budget_is_reported_as_blob_gas() { let mut executor = executor(&mut state, unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - let first = user_tx(0, 100_000); - let second = user_tx(1, 100_000); + let first = user_tx(0, empty_call_gas()); + let second = user_tx(1, empty_call_gas()); let expected = (mega_evm::MegaTransactionExt::estimated_da_size(&first) + mega_evm::MegaTransactionExt::estimated_da_size(&second)) * u64::from(SCALAR); @@ -147,6 +138,29 @@ fn test_da_footprint_within_the_block_budget_is_reported_as_blob_gas() { assert_eq!(result.blob_gas_used, expected, "the block reports its footprint as blob gas"); } +/// Rule 2 decides on the envelope too: a Mega System Transaction, which the engine runs as the +/// protocol's own, costs the block the data-availability footprint of the legacy transaction it +/// is, and counts towards the block's data-availability size, where a deposit costs neither. The +/// packing budgets read the same envelope. +#[test] +fn test_a_mega_system_transaction_costs_its_da_footprint() { + const SCALAR: u16 = 3; + let mut state = state_with_scalars(scalars_word(SCALAR, 0, 0)); + let mut executor = executor(&mut state, unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let system = system_tx(); + let da_size = mega_evm::MegaTransactionExt::estimated_da_size(&system); + let outcome = executor.run_transaction(&system).expect("the system transaction executes"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + assert!(executor.evm().ctx().is_system_originated(), "the engine ran it as the protocol's own"); + assert!(!outcome.is_deposit, "the block did not: its envelope is legacy"); + executor.commit_transaction(outcome); + + assert_eq!(executor.limiter().block_da_footprint_used, da_size * u64::from(SCALAR)); + assert_eq!(executor.limiter().block_da_size_used, da_size); +} + /// Rule 2: a transaction whose footprint does not fit in the block's budget — the block's gas /// limit — is refused, and the block keeps the footprint it had. #[test] @@ -173,21 +187,29 @@ fn test_da_footprint_over_the_block_budget_refuses_the_transaction() { /// is admitted, and the block has nothing left for the next transaction. #[test] fn test_da_footprint_that_exactly_fills_the_block_budget_is_admitted() { - const SCALAR: u16 = 128; - // Above the transaction's calldata floor under the Satin gas table, and below the footprint - // the scalar yields, so the block's gas limit still fits the transaction's gas. - const GAS_LIMIT: u64 = 1_300_000; - - let tx = common::user_tx_with_input(0, common::incompressible(20_000), GAS_LIMIT); - let footprint = mega_evm::MegaTransactionExt::estimated_da_size(&tx) * u64::from(SCALAR); - assert!(footprint >= GAS_LIMIT, "the block's gas limit must also fit the transaction's gas"); + const CALLDATA: u64 = 20_000; + // Above what the transaction has to pay under the Satin gas table: its body's history, at the + // price the engine runs, and 64 gas a calldata byte, which covers both its intrinsic charge and + // its floor. + let gas_limit = mega_evm::history_gas(mega_evm::TX_BODY_SIZE + CALLDATA) + .expect("the body has a price") + + 15_000 + + 64 * CALLDATA; + + let tx = common::user_tx_with_input(0, common::incompressible(CALLDATA as usize), gas_limit); + let da_size = mega_evm::MegaTransactionExt::estimated_da_size(&tx); + // The smallest scalar whose footprint fits the transaction's gas, so the block's gas limit — + // the footprint's budget — still fits it too. + let scalar = u16::try_from(gas_limit.div_ceil(da_size)).expect("the scalar fits its field"); + let footprint = da_size * u64::from(scalar); + assert!(footprint >= gas_limit, "the block's gas limit must also fit the transaction's gas"); // The block's gas limit is the footprint's budget, so a block with exactly this gas limit // has exactly this transaction's footprint. let mut env = common::evm_env(); env.block_env.gas_limit = footprint; - let mut state = state_with_scalars(scalars_word(SCALAR, 0, 0)); + let mut state = state_with_scalars(scalars_word(scalar, 0, 0)); let mut executor = common::executor_with_env(&mut state, unlimited_ctx(), env); executor.apply_pre_execution_changes().expect("the block starts"); @@ -223,7 +245,7 @@ fn test_l1_block_info_is_read_by_the_first_transaction_that_prices_against_it() assert_eq!(executor.evm().ctx().chain().l2_block, None, "the block starts with no info"); executor - .execute_transaction(&user_tx(0, 100_000)) + .execute_transaction(&user_tx(0, empty_call_gas())) .expect("an empty L1 block contract is not an error"); let chain = executor.evm().ctx().chain(); @@ -251,7 +273,9 @@ fn test_l1_block_info_of_this_block_is_not_overwritten() { }); executor.apply_pre_execution_changes().expect("the block starts"); - let gas = executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + let gas = executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect("the transaction executes"); let chain = executor.evm().ctx().chain(); assert_eq!( @@ -298,7 +322,9 @@ fn test_the_l1_info_deposit_prices_the_transactions_after_it() { assert_eq!(state_scalars(&mut executor), word, "the deposit wrote the block's scalars"); // The deposit bumped the sender's nonce, so the user transaction after it carries nonce 1. - let gas = executor.execute_transaction(&user_tx(1, 100_000)).expect("the transaction executes"); + let gas = executor + .execute_transaction(&user_tx(1, empty_call_gas())) + .expect("the transaction executes"); let paid = operator_fee_paid(executor); assert_eq!( @@ -322,7 +348,9 @@ fn test_operator_fee_is_charged_on_the_karst_formula() { let mut executor = executor(&mut state, unlimited_ctx()); executor.apply_pre_execution_changes().expect("the block starts"); - let gas = executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); + let gas = executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect("the transaction executes"); assert_eq!( operator_fee_paid(executor), @@ -331,14 +359,15 @@ fn test_operator_fee_is_charged_on_the_karst_formula() { ); } -/// The block's gas limit is the block environment's, whatever the context carries: it is the -/// number consensus holds the block to, and the budget the footprint is held to. +/// The block's gas limit is the block environment's: it is the number consensus holds the block +/// to, and the budget the footprint is held to. It is the executor's state, not building policy, +/// so no context can carry another. #[test] fn test_block_gas_limit_comes_from_the_block_environment() { let mut state = common::state(); - let ctx = common::block_ctx(BlockLimits::no_limits().with_block_gas_limit(1)); - let executor = executor(&mut state, ctx); + let executor = executor(&mut state, common::block_ctx(BlockLimits::no_limits())); - assert_eq!(executor.limiter().limits.block_gas_limit, BLOCK_GAS_LIMIT); + assert_eq!(executor.limiter().block_gas_limit, BLOCK_GAS_LIMIT); + assert_eq!(executor.limiter().available_gas(), BLOCK_GAS_LIMIT); assert_eq!(executor.limiter().available_da_footprint(), BLOCK_GAS_LIMIT); } diff --git a/crates/mega-evm/tests/block/salt.rs b/crates/mega-evm/tests/block/salt.rs index f0eef5620..03d9508fa 100644 --- a/crates/mega-evm/tests/block/salt.rs +++ b/crates/mega-evm/tests/block/salt.rs @@ -40,8 +40,14 @@ const BEACON_ROOTS_BUFFER_LENGTH: u64 = 8191; const HEAVY: u64 = 100_000; /// The gas limit the control arm's user transaction carries: plenty at the minimum bucket, and -/// nowhere near enough at [`HEAVY`]. -const USER_GAS_LIMIT: u64 = 1_000_000; +/// nowhere near enough at [`HEAVY`]. 1,000,000 of regular gas on top of what the slot, its record +/// and the body cost at the minimum bucket and the byte prices in effect. +fn user_gas_limit() -> u64 { + 1_000_000 + + common::slot_state_gas() + + common::body_history(0) + + mega_evm::write_record_history_gas(1).expect("a record has a price") +} /// The external environments of these tests: every bucket at `m` times the minimum, so the /// capacity bites wherever a charge lands. @@ -154,21 +160,25 @@ fn test_the_pre_block_calls_commit_at_any_capacity() { /// passing because the environment was never crowded. #[test] fn test_a_user_transaction_in_the_crowded_block_pays_the_crowded_price() { + // A slot that costs nothing costs nothing in a crowded bucket either. + if common::state_is_free() { + return; + } let affordable = { let mut state = state_with_contracts(); let mut executor = executor(&mut state, envs_at(1)); executor.apply_pre_execution_changes().expect("the block starts"); - executor.run_transaction(&common::user_tx(0, USER_GAS_LIMIT)).expect("it executes") + executor.run_transaction(&common::user_tx(0, user_gas_limit())).expect("it executes") }; assert!(affordable.result.is_success(), "{:?}", affordable.result); - assert!(affordable.gas.state > 0, "the write is charged state gas"); + assert_eq!(affordable.gas.state, common::slot_state_gas(), "the write is charged state gas"); let envs = envs_at(HEAVY); let crowded = { let mut state = state_with_contracts(); let mut executor = executor(&mut state, envs.clone()); executor.apply_pre_execution_changes().expect("the block starts"); - executor.run_transaction(&common::user_tx(0, USER_GAS_LIMIT)).expect("it executes") + executor.run_transaction(&common::user_tx(0, user_gas_limit())).expect("it executes") }; assert!( crowded.result.is_halt(), diff --git a/crates/mega-evm/tests/block/schedule.rs b/crates/mega-evm/tests/block/schedule.rs index c7644301f..e39fbaf8e 100644 --- a/crates/mega-evm/tests/block/schedule.rs +++ b/crates/mega-evm/tests/block/schedule.rs @@ -1,38 +1,14 @@ //! The schedule a block runs on, and what is checked of it before the block starts. use alloy_evm::block::BlockExecutor; -use alloy_hardforks::ForkCondition; -use alloy_primitives::{address, Address}; +use alloy_hardforks::{EthereumHardfork, ForkCondition, Hardfork}; +use alloy_op_hardforks::OpHardfork; use mega_evm::{ - chain_activation, mainnet_hardforks, testnet_hardforks, HardforkParams, HardforkParamsError, - MegaHardfork, MegaHardforkConfig, MegaHardforks, ScheduleError, MAINNET_CHAIN_ID, - TESTNET_CHAIN_ID, + chain_activation, mainnet_hardforks, testnet_hardforks, ChainActivation, MegaHardfork, + MegaHardforkConfig, MegaHardforks, ScheduleError, MAINNET_CHAIN_ID, TESTNET_CHAIN_ID, }; -use crate::common::{self, user_tx}; - -/// Parameters a fork requires from the chain configuration. Satin requires none yet, so this -/// stands in for the ones the mechanisms that bring the system contracts will register. -#[derive(Debug, Clone, PartialEq, Eq)] -struct RegistryParams { - sequencer: Address, -} - -impl HardforkParams for RegistryParams { - const FORK: MegaHardfork = MegaHardfork::Satin; - const NAME: &'static str = "RegistryParams"; - - fn validate(&self) -> Result<(), HardforkParamsError> { - if self.sequencer.is_zero() { - return Err(HardforkParamsError { message: "sequencer must be set".into() }); - } - Ok(()) - } -} - -fn params() -> RegistryParams { - RegistryParams { sequencer: address!("0x4444444444444444444444444444444444444444") } -} +use crate::common::{self, empty_call_gas, user_tx}; /// The canonical schedules are the chain activation table: the two are one source, so a /// timestamp cannot be right in one and wrong in the other. What the published upgrade pages @@ -50,7 +26,7 @@ fn test_canonical_schedules_match_the_chain_activation_table() { "{fork:?} on chain {chain_id}" ); // The schedule carries an entry for every fork, including the ones the chain has not - // scheduled: attaching a fork's parameters needs its entry to be there. + // scheduled. assert_eq!( schedule.get(*fork), Some(&activation.condition(*fork)), @@ -65,36 +41,157 @@ fn test_canonical_schedules_match_the_chain_activation_table() { assert_eq!(testnet_hardforks().spec_id(u64::MAX), None); } -/// A schedule that activates a fork without the parameters it requires fails when the chain -/// configuration is loaded, not at the fork's first block: the block executor is never built -/// from one. +/// Satin carries no parameter: a schedule that activates it alone loads, and a block runs on it, +/// over a state holding the registry the legacy forks left. The limits are the spec's, not a +/// parameter either. #[test] -fn test_a_schedule_missing_its_fork_params_is_refused_at_load() { - let missing = +fn test_a_schedule_activating_satin_alone_loads_and_runs() { + let satin = MegaHardforkConfig::default().with(MegaHardfork::Satin, ForkCondition::Timestamp(0)); + assert_eq!(satin.validate_schedule(), Ok(())); + + let mut state = common::state(); + let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), satin); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); +} + +/// When Satin activates on the schedules of [`base_fork_case`]. +const SATIN_TIME: u64 = 1_800_000_000; + +/// The forks Satin runs on that a schedule activates by timestamp: the Ethereum forks from +/// Shanghai to Osaka and the Optimism forks from Regolith to Karst. +const ETHEREUM_BASE_FORKS: [EthereumHardfork; 4] = [ + EthereumHardfork::Shanghai, + EthereumHardfork::Cancun, + EthereumHardfork::Prague, + EthereumHardfork::Osaka, +]; +const OP_BASE_FORKS: [OpHardfork; 9] = [ + OpHardfork::Regolith, + OpHardfork::Canyon, + OpHardfork::Ecotone, + OpHardfork::Fjord, + OpHardfork::Granite, + OpHardfork::Holocene, + OpHardfork::Isthmus, + OpHardfork::Jovian, + OpHardfork::Karst, +]; + +/// A schedule that activates Satin at [`SATIN_TIME`], every base fork at genesis but `base`, which +/// activates on `condition`. +fn base_fork_case(base: impl Hardfork, condition: ForkCondition) -> MegaHardforkConfig { + MegaHardforkConfig::new() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(SATIN_TIME)) + .with(base, condition) +} + +/// The refusal of a schedule whose `base` fork is not active when Satin activates. +fn inactive(base: impl Hardfork) -> Result<(), ScheduleError> { + Err(ScheduleError::InactiveBaseFork { + fork: MegaHardfork::Satin, + activation: SATIN_TIME, + base: base.name(), + }) +} + +/// A schedule that activates Karst after Satin fails when it is loaded: every Satin block runs on +/// Karst's rules, which the rest of the node would not apply to the blocks in between. So does +/// one that delays any other fork Satin runs on, by one second. +#[test] +fn test_a_base_fork_after_satin_is_refused_at_load() { + let late = ForkCondition::Timestamp(SATIN_TIME + 1); + let schedule = base_fork_case(OpHardfork::Karst, late); + assert_eq!(schedule.validate_schedule(), inactive(OpHardfork::Karst)); assert_eq!( - missing.require_params::(), - Err(ScheduleError::MissingParams { fork: MegaHardfork::Satin, params: "RegistryParams" }), - "the load refuses it" + schedule.validate_schedule().unwrap_err().to_string(), + "hardfork Satin activates at timestamp 1800000000, where the Karst fork it runs on is \ + not active", ); - // With the parameters attached the schedule loads, and a block runs on it. - let loaded = missing.with_params(params()); - assert_eq!(loaded.require_params::(), Ok(())); - assert_eq!(loaded.validate_schedule(), Ok(())); - assert_eq!(loaded.fork_params::(), Some(¶ms())); + for fork in ETHEREUM_BASE_FORKS { + assert_eq!(base_fork_case(fork, late).validate_schedule(), inactive(fork), "{fork:?}"); + } + for fork in OP_BASE_FORKS { + assert_eq!(base_fork_case(fork, late).validate_schedule(), inactive(fork), "{fork:?}"); + } +} + +/// A base fork the schedule never activates, or activates by block number, is not active at any +/// timestamp, which is how block execution reads it, and is refused as a late one is. +#[test] +fn test_a_base_fork_not_scheduled_by_timestamp_is_refused_at_load() { + for condition in [ForkCondition::Never, ForkCondition::Block(0)] { + for fork in ETHEREUM_BASE_FORKS { + let schedule = base_fork_case(fork, condition); + assert_eq!(schedule.validate_schedule(), inactive(fork), "{fork:?} at {condition:?}"); + } + for fork in OP_BASE_FORKS { + let schedule = base_fork_case(fork, condition); + assert_eq!(schedule.validate_schedule(), inactive(fork), "{fork:?} at {condition:?}"); + } + } +} - let mut state = common::state(); - let mut executor = common::executor_with_spec(&mut state, common::unlimited_ctx(), loaded); - executor.apply_pre_execution_changes().expect("the block starts"); - executor.execute_transaction(&user_tx(0, 100_000)).expect("the transaction executes"); +/// A base fork that activates with Satin is active at its activation, and the schedule loads: +/// that is the timing a node's own configuration gives Jovian, Karst and Osaka. So does one +/// that activates every base fork with Satin. +#[test] +fn test_a_base_fork_at_satin_time_is_accepted() { + let at_satin = ForkCondition::Timestamp(SATIN_TIME); + assert_eq!(base_fork_case(OpHardfork::Karst, at_satin).validate_schedule(), Ok(())); + for fork in ETHEREUM_BASE_FORKS { + assert_eq!(base_fork_case(fork, at_satin).validate_schedule(), Ok(()), "{fork:?}"); + } + for fork in OP_BASE_FORKS { + assert_eq!(base_fork_case(fork, at_satin).validate_schedule(), Ok(()), "{fork:?}"); + } + + let mut all_at_satin = base_fork_case(OpHardfork::Karst, at_satin); + for fork in ETHEREUM_BASE_FORKS { + all_at_satin.insert(fork, at_satin); + } + for fork in OP_BASE_FORKS { + all_at_satin.insert(fork, at_satin); + } + assert_eq!(all_at_satin.validate_schedule(), Ok(())); } -/// A fork the schedule does not activate needs no parameters. +/// The schedules the engine builds itself put every base fork at genesis, so they load whenever +/// Satin activates. #[test] -fn test_an_unscheduled_fork_needs_no_params() { - let unscheduled = MegaHardforkConfig::default(); +fn test_engine_built_schedules_keep_their_base_forks_at_genesis() { + for satin_time in [0, 1, SATIN_TIME] { + let schedule = MegaHardforkConfig::new() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(satin_time)); + assert_eq!(schedule.validate_schedule(), Ok(()), "Satin at {satin_time}"); + + let activation = ChainActivation { chain_id: MAINNET_CHAIN_ID, satin: Some(satin_time) }; + let schedule = activation.hardforks(); + assert_eq!(schedule.validate_schedule(), Ok(()), "the table's Satin at {satin_time}"); + } +} - assert_eq!(unscheduled.require_params::(), Ok(())); - assert_eq!(unscheduled.validate_schedule(), Ok(())); +/// Only Satin's activation is checked against: a schedule that does not activate Satin loads +/// whatever it times its base forks at. +#[test] +fn test_base_forks_are_not_checked_without_satin() { + let schedule = MegaHardforkConfig::new() + .with(OpHardfork::Karst, ForkCondition::Never) + .with(EthereumHardfork::Osaka, ForkCondition::Timestamp(SATIN_TIME)); + assert_eq!(schedule.mega_fork_activation(MegaHardfork::Satin), ForkCondition::Never); + assert_eq!(schedule.validate_schedule(), Ok(())); +} + +/// The forks up to the Merge, and Bedrock, are scheduled by block number or total difficulty, +/// which a timestamp says nothing about: they are not checked against Satin's activation. +#[test] +fn test_forks_scheduled_by_block_are_not_checked() { + for fork in [EthereumHardfork::London, EthereumHardfork::Paris] { + let schedule = base_fork_case(fork, ForkCondition::Never); + assert_eq!(schedule.validate_schedule(), Ok(()), "{fork:?}"); + } + let schedule = base_fork_case(OpHardfork::Bedrock, ForkCondition::Block(u64::MAX)); + assert_eq!(schedule.validate_schedule(), Ok(())); } diff --git a/crates/mega-evm/tests/block/sequencer_registry.rs b/crates/mega-evm/tests/block/sequencer_registry.rs new file mode 100644 index 000000000..a21e470ee --- /dev/null +++ b/crates/mega-evm/tests/block/sequencer_registry.rs @@ -0,0 +1,807 @@ +//! The `SequencerRegistry`'s role changes, applied before a block's transactions, and the live +//! system address read out of it. +//! +//! The registry the legacy forks left is checked once, by Satin's activation block, which refuses +//! a chain without it. Before every block's transactions the executor reads whether a role change +//! is due in the block and, when one is, makes the `applyPendingChanges()` system call. Each step +//! commits a state of its own, which a commit hook on the block's state receives, the read as a +//! read-only entry. The executor's pre-block steps do not read the system address: every +//! transaction reads it out of the registry when it is validated, so every EVM — the block's, or +//! one a node builds outside block execution — promotes the address the state names. + +use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxEip1559}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory, ToTxEnv}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, keccak256, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolValue}; +use mega_evm::{ + system::{ + storage_slots::{ + ADMIN, CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_ADMIN, PENDING_SEQUENCER, + PENDING_SYSTEM_ADDRESS, SEQUENCER_ACTIVATION_BLOCK, SYSTEM_ADDRESS_ACTIVATION_BLOCK, + }, + IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH, + SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE, + }, + test_utils::{CommittedStates, MemoryDatabase, SequencerRegistryRoles}, + BlockLimits, ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaContext, + MegaEvm, MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use op_alloy_consensus::TxDeposit; +use op_revm::OpHaltReason; +use revm::{ + context::result::ExecutionResult, database::State, inspector::NoOpInspector, state::EvmState, + Database, +}; + +use crate::common::{self, applies_pending_changes, BLOCK_NUMBER}; + +/// The outcome of a transaction the tests run. +type Outcome = mega_evm::MegaBlockTxResult; + +/// The system address a pending change rotates to. +const NEXT_SYSTEM_ADDRESS: Address = address!("0x3000000000000000000000000000000000000003"); + +/// The sequencer a pending change rotates to. +const NEXT_SEQUENCER: Address = address!("0x4000000000000000000000000000000000000004"); + +/// The capacity a crowded arm puts every bucket at, in minimum buckets: a fresh slot would cost +/// 2,000 times the schedule's entry, far past what a 30M call could pay. +const CROWDED: u64 = 2_000; + +/// A gas limit large enough for the crowded price, had the call paid it. +const LARGE_BLOCK_GAS_LIMIT: u64 = 250_000_000; + +/// The external environments of these tests: every bucket at `m` times the minimum. +type Envs = TestExternalEnvs; + +/// The executor these tests drive. +type Executor<'a> = MegaBlockExecutor< + MegaEvm<&'a mut State, NoOpInspector, Envs>, + OpAlloyReceiptBuilder, + MegaHardforkConfig, +>; + +/// A database holding the registry with `slots` on top of its roles, and the accounts the tests' +/// transactions come from. +fn registry_with(slots: &[(U256, U256)]) -> MemoryDatabase { + let mut db = common::database(); + for &(slot, value) in slots { + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, slot, value); + } + db +} + +/// The slots of a system-address change due at `activation`. +fn system_address_change(activation: u64) -> [(U256, U256); 2] { + [ + (PENDING_SYSTEM_ADDRESS, common::word(NEXT_SYSTEM_ADDRESS)), + (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(activation)), + ] +} + +/// The slots of a sequencer change due at `activation`. +fn sequencer_change(activation: u64) -> [(U256, U256); 2] { + [ + (PENDING_SEQUENCER, common::word(NEXT_SEQUENCER)), + (SEQUENCER_ACTIVATION_BLOCK, U256::from(activation)), + ] +} + +/// Every bucket at `m` times the minimum capacity. +fn envs_at(m: u64) -> Envs { + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * m) +} + +/// An executor over `state` reading `envs`, in a block at [`BLOCK_NUMBER`] whose gas limit is +/// `gas_limit`. +fn executor(state: &mut State, envs: Envs, gas_limit: u64) -> Executor<'_> { + executor_on(state, envs, gas_limit, common::chain_spec()) +} + +/// [`executor`] on the chain `spec` describes. +fn executor_on( + state: &mut State, + envs: Envs, + gas_limit: u64, + spec: MegaHardforkConfig, +) -> Executor<'_> { + let mut env = common::evm_env(); + env.block_env.gas_limit = gas_limit; + let evm = MegaEvmFactory::new().with_external_env_factory(envs).create_evm(state, env); + let ctx = MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + MegaBlockExecutor::new(evm, ctx, spec, OpAlloyReceiptBuilder::default()) +} + +/// Starts a block at [`BLOCK_NUMBER`] over `state` and answers the registry's own steps, the +/// committed states that name it, in order: the read of its pending changes and the call that +/// applies them. The blocks here are not Satin's activation block, so no step checks the +/// registry's code. +fn start_block(state: &mut State, envs: Envs, gas_limit: u64) -> Vec { + let committed = CommittedStates::install(state); + let mut executor = executor(state, envs, gas_limit); + executor.apply_pre_execution_changes().expect("the block starts"); + committed + .states() + .into_iter() + .filter(|state| state.contains_key(&SEQUENCER_REGISTRY_ADDRESS)) + .collect() +} + +/// The registry's `slot`, as the block left it. +fn slot(state: &mut State, slot: U256) -> U256 { + state.storage(SEQUENCER_REGISTRY_ADDRESS, slot).expect("the registry is readable") +} + +/// A system-address change due in this block is applied before the block's transactions, in a +/// block whose every bucket is crowded: the call is the protocol's own, priced at the minimum +/// bucket, so the crowding neither halts it nor makes it read a capacity. The block commits the +/// read that found the change due, then the call's state. +#[test] +fn test_a_due_change_is_applied_under_a_crowded_bucket() { + let envs = envs_at(CROWDED); + let mut state = + State::builder().with_database(registry_with(&system_address_change(BLOCK_NUMBER))).build(); + let steps = start_block(&mut state, envs.clone(), LARGE_BLOCK_GAS_LIMIT); + + assert_eq!(steps.len(), 2, "the read and the call"); + assert!(!applies_pending_changes(&steps[..1]), "the read leaves the registry untouched"); + assert!(applies_pending_changes(&steps[1..]), "the call touches it"); + assert_eq!(envs.total_bucket_queries(), 0, "no pre-block step read a capacity"); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), common::word(NEXT_SYSTEM_ADDRESS)); + assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), U256::ZERO, "the pending slot is cleared"); + assert_eq!(slot(&mut state, SYSTEM_ADDRESS_ACTIVATION_BLOCK), U256::ZERO); +} + +/// A block with nothing due makes no call: the block commits the read that found nothing due, +/// both pending slots and nothing else, read-only. +#[test] +fn test_a_block_with_nothing_due_makes_no_call() { + let mut state = State::builder().with_database(registry_with(&[])).build(); + let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + assert_eq!(steps.len(), 1, "the read alone"); + let registry = &steps[0][&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "a read-only entry"); + assert_eq!(registry.storage.len(), 2); + assert!(registry.storage.contains_key(&PENDING_SYSTEM_ADDRESS)); + assert!(registry.storage.contains_key(&PENDING_SEQUENCER)); +} + +/// A change scheduled for a later block is left pending: nothing is due, and no call is made. +#[test] +fn test_a_change_not_yet_due_makes_no_call() { + let db = registry_with(&system_address_change(BLOCK_NUMBER + 1)); + let mut state = State::builder().with_database(db).build(); + let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + assert!(!applies_pending_changes(&steps)); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), common::word(MEGA_SYSTEM_ADDRESS)); + assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), common::word(NEXT_SYSTEM_ADDRESS)); +} + +/// A sequencer change due in this block is applied by the same call, and leaves the system +/// address as it was. +#[test] +fn test_a_due_sequencer_change_is_applied() { + let mut state = + State::builder().with_database(registry_with(&sequencer_change(BLOCK_NUMBER))).build(); + let steps = start_block(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + assert!(applies_pending_changes(&steps)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(NEXT_SEQUENCER)); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO); + assert_eq!(slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), U256::ZERO); + assert_eq!(slot(&mut state, CURRENT_SYSTEM_ADDRESS), common::word(MEGA_SYSTEM_ADDRESS)); +} + +/// A system address a chain's registry names, distinct from [`MEGA_SYSTEM_ADDRESS`], so a test can +/// tell the one read out of the registry from the default. +const CHAIN_SYSTEM_ADDRESS: Address = address!("0x5000000000000000000000000000000000000005"); + +/// The admin a handoff moves the registry to. +const NEXT_ADMIN: Address = address!("0x6000000000000000000000000000000000000006"); + +/// A gas limit for a call carrying `input_len` bytes to the Oracle or the registry: 1,000,000 of +/// regular gas on top of the account the engine creates for a system-address caller, up to four +/// fresh slots, their records and the body, at the byte prices in effect. +fn gas_limit(input_len: usize) -> u64 { + 1_000_000 + + common::new_account_state_gas() + + 4 * common::slot_state_gas() + + common::body_history(input_len as u64) + + mega_evm::write_record_history_gas(5).expect("the records have a price") +} + +/// A legacy call from `sender` to the Oracle's `getSlot(0)`: a system-address transaction when +/// `sender` is the system address the registry names, an ordinary one otherwise. It carries a +/// gas price, so an ordinary one needs a balance its sender does not have here. `getSlot` does not +/// read the registry itself, so what the transaction's state holds of the registry is what its +/// validation read. +fn oracle_call_from(sender: Address, nonce: u64) -> Recovered { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let gas_limit = gas_limit(input.len()); + Recovered::new_unchecked( + common::tx(nonce, ORACLE_CONTRACT_ADDRESS, input.into(), gas_limit), + sender, + ) +} + +/// A transaction from `sender` to the registry carrying `input`. +fn registry_call_from(sender: Address, input: Vec) -> Recovered { + let gas_limit = gas_limit(input.len()); + Recovered::new_unchecked( + common::tx(0, SEQUENCER_REGISTRY_ADDRESS, input.into(), gas_limit), + sender, + ) +} + +/// Asserts `sender` is the block's system address: its Oracle call runs as the protocol's own +/// transaction, with no fee and no history gas, from an account holding nothing. Answers the +/// outcome, not committed. +fn assert_is_the_system_address(executor: &mut Executor<'_>, sender: Address) -> Outcome { + let outcome = executor + .run_transaction(&oracle_call_from(sender, 0)) + .expect("a system-address transaction is accepted without a balance"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history"); + assert!(executor.evm().ctx().is_system_originated(), "it is the protocol's own transaction"); + outcome +} + +/// Asserts `sender` is not the block's system address: the same call is an ordinary transaction +/// from an account that cannot pay its fee. +fn assert_is_not_the_system_address(executor: &mut Executor<'_>, sender: Address) { + let err = executor + .run_transaction(&oracle_call_from(sender, 0)) + .expect_err("an ordinary transaction from an empty account is refused"); + assert!(err.to_string().contains("lack of funds"), "{err}"); +} + +/// Asserts `state` holds what a system-address transaction's validation read: the registry's +/// account, untouched, with the one slot naming `system_address`, unchanged. +fn assert_carries_the_system_address_read(state: &EvmState, system_address: Address) { + let registry = &state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "a read-only entry"); + assert_eq!(registry.info.code_hash, SEQUENCER_REGISTRY_CODE_HASH); + assert_eq!(registry.storage.len(), 1, "exactly the one slot read"); + let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; + assert!(!slot.is_changed()); + assert_eq!(slot.present_value(), common::word(system_address)); +} + +/// No pre-block step carries the system address's slot: the read of the pending changes reads the +/// pending slots alone, and the activation block's check, which reads the registry's account +/// without storage, is not made here. The slot is in the system-address transaction's own state +/// instead, read-only and warm, as its validation read it. +#[test] +fn test_the_slot_is_in_the_system_transactions_state_not_the_pre_block_witness() { + let mut state = State::builder().with_database(registry_with(&[])).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + for (step, state) in committed.states().iter().enumerate() { + let slot = state + .get(&SEQUENCER_REGISTRY_ADDRESS) + .and_then(|registry| registry.storage.get(&CURRENT_SYSTEM_ADDRESS)); + assert!(slot.is_none(), "pre-block step {step} carries the system address's slot"); + } + + let outcome = assert_is_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); + assert_carries_the_system_address_read(&outcome.inner.state, MEGA_SYSTEM_ADDRESS); + let registry = &outcome.inner.state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.storage[&CURRENT_SYSTEM_ADDRESS].is_cold, "the read warmed the slot"); +} + +/// A system-address transaction is recognised by the address read out of the registry: from it, +/// the Oracle call is the protocol's own; from the engine's default, which is not this chain's +/// system address, it is an ordinary transaction. +#[test] +fn test_system_tx_uses_resolved_system_address() { + let roles = + SequencerRegistryRoles { system_address: CHAIN_SYSTEM_ADDRESS, ..common::registry_roles() }; + let mut state = + State::builder().with_database(common::database().sequencer_registry(roles)).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = assert_is_the_system_address(&mut executor, CHAIN_SYSTEM_ADDRESS); + assert_carries_the_system_address_read(&outcome.inner.state, CHAIN_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); +} + +/// A rotation governs every block from its activation block on, and no block before it: the +/// block before promotes the old address and not the new one, the activation block and the block +/// after it the new one and not the old. +#[test] +fn test_a_rotation_governs_the_blocks_from_its_activation_block() { + let activation = BLOCK_NUMBER + 1; + let mut state = + State::builder().with_database(registry_with(&system_address_change(activation))).build(); + + let mut before = started_block_at(&mut state, activation - 1); + assert_is_the_system_address(&mut before, MEGA_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut before, NEXT_SYSTEM_ADDRESS); + drop(before); + + for number in [activation, activation + 1] { + let mut block = started_block_at(&mut state, number); + let outcome = assert_is_the_system_address(&mut block, NEXT_SYSTEM_ADDRESS); + assert_carries_the_system_address_read(&outcome.inner.state, NEXT_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut block, MEGA_SYSTEM_ADDRESS); + } + assert_eq!(slot(&mut state, PENDING_SYSTEM_ADDRESS), U256::ZERO, "applied once"); +} + +/// An EVM a node builds outside block execution, over the state these tests run on. +type OutsideEvm<'a> = MegaEvm<&'a mut State, NoOpInspector, Envs>; + +/// A context over `state` for the block [`executor`] runs, as a node builds one outside block +/// execution: no block is started on it and nothing tells it the system address. +fn context_outside_block<'a>( + state: &'a mut State, + envs: &Envs, +) -> MegaContext<&'a mut State, Envs> { + let EvmEnv { cfg_env, block_env } = common::evm_env(); + MegaContext::new_with_external_envs(state, cfg_env.spec, envs.external_envs(BLOCK_NUMBER)) + .with_cfg(cfg_env) + .with_block(block_env) +} + +/// An EVM a node builds outside block execution — for an RPC call, or to replay a block's +/// transactions for a trace — starts no block and is told nothing, and on a state after a +/// rotation it promotes the rotated address's Oracle transaction exactly as the block executor +/// does: the same result, state, gas and usage, whether it was built from a context or by the +/// factory. The address the rotation retired sends an ordinary transaction, which its empty +/// account cannot pay for. +#[test] +fn test_an_evm_outside_block_execution_promotes_the_rotated_address() { + let envs = envs_at(1); + let mut state = + State::builder().with_database(registry_with(&system_address_change(BLOCK_NUMBER))).build(); + let tx = oracle_call_from(NEXT_SYSTEM_ADDRESS, 0); + + let mut executor = executor(&mut state, envs.clone(), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + let in_block = assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS).inner; + drop(executor); + + // The state now holds the rotation the block applied, as the one a node's EVM runs on does. + let assert_as_in_block = |evm: &mut OutsideEvm<'_>| { + let outside = evm.execute_transaction(tx.to_tx_env()).expect("promoted"); + assert!(evm.ctx().is_system_originated(), "it is the protocol's own transaction"); + assert_eq!(outside.result, in_block.result); + assert_eq!(outside.state, in_block.state); + assert_eq!(outside.gas, in_block.gas); + assert_eq!(outside.usage, in_block.usage); + assert_eq!(outside.limit_exceeded, in_block.limit_exceeded); + + let retired = oracle_call_from(MEGA_SYSTEM_ADDRESS, 0); + let err = evm + .execute_transaction(retired.to_tx_env()) + .expect_err("an ordinary transaction from an empty account is refused"); + assert!(err.to_string().contains("lack of funds"), "{err}"); + assert!(!evm.ctx().is_system_originated()); + }; + assert_as_in_block(&mut MegaEvm::new(context_outside_block(&mut state, &envs))); + assert_as_in_block( + &mut MegaEvmFactory::new() + .with_external_env_factory(envs.clone()) + .create_evm(&mut state, common::evm_env()), + ); +} + +/// A deposit from `sender` to the Oracle's `setSlots`, minting `mint` to it: a write the Oracle +/// accepts from the live system address, if the call ran. +fn oracle_write_deposit_from(sender: Address, mint: u128) -> Recovered { + let input = + IOracle::setSlotsCall { slots: vec![U256::ZERO], values: vec![B256::repeat_byte(7)] } + .abi_encode(); + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0xd0), + from: sender, + to: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + mint, + value: U256::ZERO, + gas_limit: gas_limit(input.len()), + is_system_transaction: false, + input: input.into(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0xd1))), + sender, + ) +} + +/// An EIP-1559 call from `sender` to the Oracle's `getSlot(0)`, which has no system shape. It +/// tips its whole fee cap, so it pays a fee on a block with no base fee. +fn typed_oracle_call_from(sender: Address) -> Recovered { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let tx = TxEip1559 { + chain_id: common::CHAIN_ID, + nonce: 0, + gas_limit: gas_limit(input.len()), + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 1_000_000, + to: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + value: U256::ZERO, + access_list: Default::default(), + input: input.into(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Eip1559(Signed::new_unchecked( + tx, + Signature::test_signature(), + B256::repeat_byte(0xe1), + )), + sender, + ) +} + +/// A deposit is never of the system shape, so one from the live system address is invalid, and +/// the block includes it as a failed deposit: its sender's nonce moves by one and its mint is +/// credited, and its call, a write the Oracle accepts from the system address, never runs. That +/// holds for the address the registry names and for the one a rotation due in the block names. +#[test] +fn test_a_deposit_from_the_live_system_address_is_a_failed_deposit() { + const MINT: u128 = 9_000; + let cases = [ + ("the registry's address", Vec::new(), MEGA_SYSTEM_ADDRESS), + ("after a rotation", system_address_change(BLOCK_NUMBER).to_vec(), NEXT_SYSTEM_ADDRESS), + ]; + for (case, slots, sender) in cases { + let mut state = State::builder().with_database(registry_with(&slots)).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + let outcome = executor + .run_transaction(&oracle_write_deposit_from(sender, MINT)) + .expect("a deposit is included"); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: OpHaltReason::FailedDeposit, .. } + ), + "{case}: {:?}", + outcome.result + ); + executor.commit_transaction(outcome); + drop(executor); + + let account = state.basic(sender).unwrap().expect("the deposit created its sender"); + assert_eq!(account.nonce, 1, "{case}: the nonce moves by one"); + assert_eq!(account.balance, U256::from(MINT), "{case}: the mint is credited"); + let oracle = state.storage(ORACLE_CONTRACT_ADDRESS, U256::ZERO).unwrap(); + assert_eq!(oracle, U256::ZERO, "{case}: the Oracle is not written"); + } +} + +/// A transaction from the live system address without the system shape is invalid: the block +/// refuses an EIP-1559 call from it, before or after a rotation, however much the address holds. +/// The address a rotation retired is an ordinary sender: the same call from it runs, and pays its +/// fee. +#[test] +fn test_a_typed_transaction_from_the_live_system_address_is_invalid() { + let funds = U256::from(10u64.pow(18)); + let cases = [ + ("the registry's address", Vec::new(), MEGA_SYSTEM_ADDRESS, None), + ( + "after a rotation", + system_address_change(BLOCK_NUMBER).to_vec(), + NEXT_SYSTEM_ADDRESS, + Some(MEGA_SYSTEM_ADDRESS), + ), + ]; + for (case, slots, live, retired) in cases { + let db = registry_with(&slots) + .account_balance(MEGA_SYSTEM_ADDRESS, funds) + .account_balance(NEXT_SYSTEM_ADDRESS, funds); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + + let error = executor + .run_transaction(&typed_oracle_call_from(live)) + .expect_err("the live system address sends the system shape alone"); + assert!(error.to_string().contains(SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE), "{case}: {error}"); + + if let Some(retired) = retired { + let outcome = executor + .run_transaction(&typed_oracle_call_from(retired)) + .expect("the retired address is an ordinary sender"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert!(!executor.evm().ctx().is_system_originated(), "{case}"); + assert!(outcome.inner.state[&retired].info.balance < funds, "{case}: it pays its fee"); + } + } +} + +/// A sequencer rotation leaves the system address as it was. +#[test] +fn test_sequencer_change_does_not_affect_system_address() { + let mut state = + State::builder().with_database(registry_with(&sequencer_change(BLOCK_NUMBER))).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_is_the_system_address(&mut executor, MEGA_SYSTEM_ADDRESS); + assert_is_not_the_system_address(&mut executor, NEXT_SEQUENCER); +} + +/// Both rotations due in one block: the system address is the new system address, not the new +/// sequencer. +#[test] +fn test_dual_change_in_same_block() { + let slots: Vec<_> = system_address_change(BLOCK_NUMBER) + .into_iter() + .chain(sequencer_change(BLOCK_NUMBER)) + .collect(); + let mut state = State::builder().with_database(registry_with(&slots)).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_is_the_system_address(&mut executor, NEXT_SYSTEM_ADDRESS); + drop(executor); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(NEXT_SEQUENCER)); +} + +/// The two-step admin handoff through ordinary transactions: the admin names the next one, the +/// next one accepts, and the registry's admin slot moves while the pending one is cleared. +#[test] +fn test_admin_handoff_via_block_executor() { + let mut db = registry_with(&[]); + db.set_account_balance(common::ADMIN, U256::from(10_u64.pow(18))); + db.set_account_balance(NEXT_ADMIN, U256::from(10_u64.pow(18))); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, envs_at(1), common::BLOCK_GAS_LIMIT); + executor.apply_pre_execution_changes().expect("the block starts"); + + for (sender, input) in [ + ( + common::ADMIN, + ISequencerRegistry::transferAdminCall { newAdmin: NEXT_ADMIN }.abi_encode(), + ), + (NEXT_ADMIN, ISequencerRegistry::acceptAdminCall {}.abi_encode()), + ] { + let outcome = + executor.run_transaction(®istry_call_from(sender, input)).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + executor.commit_transaction(outcome); + } + drop(executor); + + assert_eq!(slot(&mut state, ADMIN), common::word(NEXT_ADMIN)); + assert_eq!(slot(&mut state, PENDING_ADMIN), U256::ZERO); +} + +/// The EIP-712 digest of a rotation to `new_sequencer` at `activation_block`, built here from the +/// contract's domain and type strings rather than asked of the contract, so a test that the +/// contract accepts a proof over it cross-checks the deployed bytecode. +fn rotation_digest(new_sequencer: Address, activation_block: U256) -> B256 { + let domain_typehash = keccak256( + b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", + ); + let rotation_typehash = + keccak256(b"SequencerRotation(address newSequencer,uint256 activationBlock)"); + let domain_separator = keccak256( + ( + domain_typehash, + keccak256(b"MegaETH SequencerRegistry"), + keccak256(b"1"), + U256::from(common::CHAIN_ID), + SEQUENCER_REGISTRY_ADDRESS, + ) + .abi_encode(), + ); + let struct_hash = keccak256((rotation_typehash, new_sequencer, activation_block).abi_encode()); + let mut preimage = Vec::with_capacity(66); + preimage.extend_from_slice(b"\x19\x01"); + preimage.extend_from_slice(domain_separator.as_slice()); + preimage.extend_from_slice(struct_hash.as_slice()); + keccak256(&preimage) +} + +/// The key of the sequencer a rotation brings in, and its address. +fn next_sequencer_key() -> (Address, B256) { + use alloy_consensus::crypto::secp256k1::{recover_signer, sign_message}; + let secret = B256::from(U256::from(0x5ec5_ec5e_c5ec_u64)); + let probe = B256::from(U256::from(1)); + let signature = sign_message(secret, probe).expect("the key signs"); + (recover_signer(&signature, probe).expect("the signer recovers"), secret) +} + +/// The 65-byte `(r, s, v)` proof, signed by `secret`, that its key takes over at +/// `activation_block`. +fn rotation_proof(secret: B256, new_sequencer: Address, activation_block: U256) -> Bytes { + let digest = rotation_digest(new_sequencer, activation_block); + let signature = + alloy_consensus::crypto::secp256k1::sign_message(secret, digest).expect("the key signs"); + let mut proof = Vec::with_capacity(65); + proof.extend_from_slice(&signature.r().to_be_bytes::<32>()); + proof.extend_from_slice(&signature.s().to_be_bytes::<32>()); + proof.push(27 + u8::from(signature.v())); + proof.into() +} + +/// A block at `number` over `state`, its pre-block changes applied. +fn started_block_at(state: &mut State, number: u64) -> Executor<'_> { + let mut env = common::evm_env(); + env.block_env.number = U256::from(number); + let evm = MegaEvmFactory::new().with_external_env_factory(envs_at(1)).create_evm(state, env); + let ctx = MegaBlockExecutionCtx::new( + B256::ZERO, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + let mut executor = + MegaBlockExecutor::new(evm, ctx, common::chain_spec(), OpAlloyReceiptBuilder::default()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor +} + +/// The admin's `scheduleNextSequencerChange` call, carrying `proof`, run and committed in a +/// block at [`BLOCK_NUMBER`] over `state`. Answers whether the call succeeded. +fn schedule( + state: &mut State, + next: Address, + activation: u64, + proof: Bytes, +) -> bool { + let mut executor = started_block_at(state, BLOCK_NUMBER); + let input = ISequencerRegistry::scheduleNextSequencerChangeCall { + newSequencer: next, + activationBlock: U256::from(activation), + newSequencerSignature: proof, + } + .abi_encode(); + let outcome = + executor.run_transaction(®istry_call_from(common::ADMIN, input)).expect("it executes"); + let succeeded = outcome.result.is_success(); + executor.commit_transaction(outcome); + succeeded +} + +/// A state holding the registry, with a funded admin. +fn state_with_funded_admin() -> State { + let mut db = common::database(); + db.set_account_balance(common::ADMIN, U256::from(10_u64.pow(18))); + State::builder().with_database(db).build() +} + +/// A sequencer rotation end to end: the admin schedules it in one block with the new key's +/// EIP-712 proof of possession, through an ordinary transaction, and the block at its activation +/// block applies it before its transactions; the block before does not. +#[test] +fn test_a_rotation_with_a_valid_proof_activates_at_its_block() { + let (next, secret) = next_sequencer_key(); + let activation = BLOCK_NUMBER + common::registry_roles().min_rotation_delay; + let mut state = state_with_funded_admin(); + + let proof = rotation_proof(secret, next, U256::from(activation)); + assert!(schedule(&mut state, next, activation, proof), "the proof is accepted"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), common::word(next)); + assert_eq!(slot(&mut state, SEQUENCER_ACTIVATION_BLOCK), U256::from(activation)); + + drop(started_block_at(&mut state, activation - 1)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(common::SEQUENCER), "not before"); + + drop(started_block_at(&mut state, activation)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(next), "applied at its block"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO); +} + +/// A sequencer rotation scheduled in one block takes effect at its activation block and stays +/// in force in the block after it. +/// +/// The block before the activation block still names the sequencer the registry held, and the +/// change is still pending. The activation block applies it and clears the pending +/// change. The next block names the new sequencer and applies nothing again. +#[test] +fn test_a_sequencer_rotation_takes_effect_across_blocks() { + let (next, secret) = next_sequencer_key(); + let activation = BLOCK_NUMBER + common::registry_roles().min_rotation_delay; + let mut state = state_with_funded_admin(); + + let proof = rotation_proof(secret, next, U256::from(activation)); + assert!(schedule(&mut state, next, activation, proof), "the proof is accepted"); + + drop(started_block_at(&mut state, activation - 1)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(common::SEQUENCER), "not yet"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), common::word(next), "still pending"); + + drop(started_block_at(&mut state, activation)); + assert_eq!(slot(&mut state, CURRENT_SEQUENCER), common::word(next), "applied at its block"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO, "the pending change is cleared"); + + drop(started_block_at(&mut state, activation + 1)); + assert_eq!( + slot(&mut state, CURRENT_SEQUENCER), + common::word(next), + "the next block still names it" + ); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO, "nothing is applied again"); +} + +/// A schedule without a proof of possession is refused by the contract: the transaction is +/// included, its call reverts, and nothing is pending. +#[test] +fn test_a_schedule_without_a_proof_reverts() { + let (next, _) = next_sequencer_key(); + let activation = BLOCK_NUMBER + common::registry_roles().min_rotation_delay; + let mut state = state_with_funded_admin(); + + assert!(!schedule(&mut state, next, activation, Bytes::new()), "the call reverts"); + assert_eq!(slot(&mut state, PENDING_SEQUENCER), U256::ZERO); +} + +/// A database error that is not fatal, as an EIP-7928 block access list that does not cover a +/// read would raise. +#[derive(Debug)] +struct NonFatalError; + +impl core::fmt::Display for NonFatalError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "the pending slot is not covered") + } +} + +impl core::error::Error for NonFatalError {} + +impl revm::context::DBErrorMarker for NonFatalError { + fn is_fatal(&self) -> bool { + false + } +} + +/// A database that refuses to read the registry's pending system address, with an error that is +/// not fatal. +#[derive(Debug)] +struct RefusesThePendingRead(MemoryDatabase); + +impl Database for RefusesThePendingRead { + type Error = NonFatalError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + Ok(self.0.basic(address).expect("the memory database serves")) + } + + fn code_by_hash(&mut self, code_hash: B256) -> Result { + Ok(self.0.code_by_hash(code_hash).expect("the memory database serves")) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + if (address, index) == (SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS) { + return Err(NonFatalError); + } + Ok(self.0.storage(address, index).expect("the memory database serves")) + } + + fn block_hash(&mut self, number: u64) -> Result { + Ok(self.0.block_hash(number).expect("the memory database serves")) + } +} + +/// The due check is a direct read of the block's state, as the other direct reads of the executor +/// are: a database error there, fatal or not, is an internal error, not a verdict on the block. +/// The same chain starts when the read is served. +#[test] +fn test_a_non_fatal_error_on_the_due_read_is_an_internal_error() { + fn start(db: DB) -> Result<(), alloy_evm::block::BlockExecutionError> { + let mut state = State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ) + .apply_pre_execution_changes() + } + let chain = common::database; + + start(chain()).expect("the chain starts when the pending slot is served"); + + let err = start(RefusesThePendingRead(chain())).expect_err("the due read fails"); + assert!(matches!(err, alloy_evm::block::BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("the pending slot is not covered"), "{err}"); +} diff --git a/crates/mega-evm/tests/block/sequences.rs b/crates/mega-evm/tests/block/sequences.rs new file mode 100644 index 000000000..96252e500 --- /dev/null +++ b/crates/mega-evm/tests/block/sequences.rs @@ -0,0 +1,139 @@ +//! Blocks that follow one another on one state. +//! +//! A rotation, the block-hash ring and an activation block are each settled inside a single +//! block elsewhere. These tests run the blocks around that one, on the state the earlier block +//! committed. + +use alloy_eips::eip2935::{HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}; +use alloy_evm::{block::BlockExecutor, EvmEnv}; +use alloy_primitives::{Bytes, B256, U256}; +use mega_evm::{test_utils::rex6_predeploys, BlockLimits, MegaBlockExecutionCtx, MegaSpecId}; +use revm::{database::State, Database}; + +use crate::common::{ + self, deposit_tx, empty_call_gas, executor, executor_with_env, unlimited_ctx, user_tx, + BLOCK_NUMBER, CALLER, +}; + +/// The seven predeploys are as the state held them before the blocks: the code and the nonce. +fn assert_predeploys_unchanged(state: &mut State) { + for (address, held, _) in rex6_predeploys(common::registry_roles()) { + let info = state.basic(address).expect("readable").expect("still there"); + assert_eq!((info.code_hash, info.nonce), (held.code_hash, held.nonce), "{address}"); + } +} + +/// The ring slot EIP-2935 writes the parent hash of block `number` into. +fn ring_slot(number: u64) -> u64 { + (number - 1) % (HISTORY_SERVE_WINDOW as u64) +} + +/// The parent hash the history contract holds at `slot`. +fn stored_parent(state: &mut State, slot: u64) -> B256 { + let word = state.storage(HISTORY_STORAGE_ADDRESS, U256::from(slot)).expect("readable"); + B256::from(word.to_be_bytes()) +} + +/// Starts block `number` and commits its pre-block calls, recording `parent` in the history ring. +fn record_parent( + state: &mut State, + number: u64, + parent: B256, +) { + let mut env = common::evm_env(); + env.block_env.number = U256::from(number); + let ctx = MegaBlockExecutionCtx::new( + parent, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + ); + let mut executor = executor_with_env(state, ctx, env); + executor.apply_pre_execution_changes().expect("the block starts"); +} + +/// The EIP-2935 ring stores one parent hash per block, and a later block that lands on a used +/// slot replaces that hash and leaves the slot beside it. +/// +/// Block 1 writes slot 0. The block at the window writes the last slot. The next block wraps +/// onto slot 0. One window later the last slot is written again, and slot 0 still holds the +/// hash the wrap stored. +#[test] +fn test_the_block_hash_ring_wraps_and_keeps_the_slot_beside_it() { + let window = HISTORY_SERVE_WINDOW as u64; + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + + let first = B256::repeat_byte(0x11); + let edge = B256::repeat_byte(0x22); + let wrapped = B256::repeat_byte(0x33); + let again = B256::repeat_byte(0x44); + + record_parent(&mut state, 1, first); + assert_eq!(ring_slot(1), 0); + assert_eq!(stored_parent(&mut state, 0), first); + + record_parent(&mut state, window, edge); + assert_eq!(ring_slot(window), window - 1); + assert_eq!(stored_parent(&mut state, window - 1), edge); + assert_eq!(stored_parent(&mut state, 0), first, "the earlier slot survives"); + + record_parent(&mut state, window + 1, wrapped); + assert_eq!(ring_slot(window + 1), 0); + assert_eq!(stored_parent(&mut state, 0), wrapped, "the next block wraps onto slot 0"); + assert_eq!(stored_parent(&mut state, window - 1), edge, "the slot beside the wrap survives"); + + record_parent(&mut state, window * 2, again); + assert_eq!(ring_slot(window * 2), window - 1); + assert_eq!(stored_parent(&mut state, window - 1), again, "a later turn overwrites the edge"); + assert_eq!(stored_parent(&mut state, 0), wrapped, "the wrapped slot stands"); +} + +/// The environment of the block after the one the shared helpers build. +fn next_block_env() -> EvmEnv { + let mut env = common::evm_env(); + env.block_env.number = U256::from(BLOCK_NUMBER + 1); + env +} + +/// Satin's activation block packs a deposit and refuses a user transaction. The next block, on +/// the state that block committed, packs the user transaction, and the predeploys the activation +/// block checked are as they were. +#[test] +fn test_the_block_after_an_activation_block_packs_a_user_transaction() { + let mut state = common::state(); + let nonce = { + let ctx = unlimited_ctx() + .with_no_user_tx_activation_block(true) + .with_satin_activation_block(true); + let mut executor = executor(&mut state, ctx); + executor.apply_pre_execution_changes().expect("the activation block starts"); + executor + .execute_transaction(&deposit_tx(Bytes::new(), empty_call_gas())) + .expect("a deposit is what an activation block packs"); + let err = executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("a user transaction has no place in an activation block"); + assert!( + format!("{err}").contains("non-deposit transaction in fork activation block"), + "{err}", + ); + + let (_, result) = executor.finish_with_counters().expect("the activation block finishes"); + assert_eq!(result.receipts().len(), 1, "only the deposit was packed"); + assert!(result.receipts()[0].status(), "the deposit succeeds"); + state.basic(CALLER).expect("readable").expect("the caller").nonce + }; + assert_predeploys_unchanged(&mut state); + + let mut executor = executor_with_env(&mut state, unlimited_ctx(), next_block_env()); + executor.apply_pre_execution_changes().expect("the next block starts"); + executor + .execute_transaction(&user_tx(nonce, empty_call_gas())) + .expect("the block after an activation block packs a user transaction"); + let (_, result) = executor.finish_with_counters().expect("the next block finishes"); + assert_eq!(result.receipts().len(), 1); + assert!(result.receipts()[0].status(), "the user transaction succeeds"); + assert_predeploys_unchanged(&mut state); +} diff --git a/crates/mega-evm/tests/block/stale.rs b/crates/mega-evm/tests/block/stale.rs new file mode 100644 index 000000000..1da7c312f --- /dev/null +++ b/crates/mega-evm/tests/block/stale.rs @@ -0,0 +1,186 @@ +//! A delayed commit holds an outcome to the state its sender had when it executed. +//! +//! `commit_transaction_outcome` commits an outcome a builder executed earlier, after other +//! commits may have moved the state it read. A commit writes the sender's account as the +//! transaction left it, so an outcome whose sender's nonce or balance moved since it executed would +//! write over what the other commit did: the commit refuses it. Any other read the outcome made is +//! the builder's to keep fresh, which the flow a sequencer builds with — an Oracle-reading +//! transaction executed, then the system-address transaction that writes the Oracle executed and +//! committed first — relies on. + +use alloy_consensus::transaction::Recovered; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + MegaTxEnvelope, +}; +use revm::Database; + +use crate::common::{self, body_history, new_account_state_gas, CALLER}; + +/// A second funded sender. +const SENDER: Address = address!("0x2000000000000000000000000000000000000005"); + +/// A recipient of value, absent from the pre-state. +const PAYEE_B: Address = address!("0x1000000000000000000000000000000000000006"); + +/// Another recipient of value, absent from the pre-state. +const PAYEE_C: Address = address!("0x1000000000000000000000000000000000000007"); + +/// What every test transaction is given: room for a new account and its records on top of the +/// body's history, at the byte prices in effect. +fn gas_limit(calldata: u64) -> u64 { + 1_000_000 + + new_account_state_gas() + + body_history(calldata) + + mega_evm::write_record_history_gas(4).expect("the records have a price") +} + +/// A legacy transaction from `sender` at `nonce` to `to`, carrying `value` and `input`. +fn legacy( + sender: Address, + nonce: u64, + to: Address, + value: u64, + input: Bytes, +) -> Recovered { + let limit = gas_limit(input.len() as u64); + common::legacy_from(sender, nonce, TxKind::Call(to), U256::from(value), input, limit, 1_000_000) +} + +/// A system-address transaction at `nonce` writing `value` into the Oracle's slot 0. +fn oracle_write(nonce: u64, value: u8) -> Recovered { + let input = IOracle::setSlotsCall { + slots: vec![U256::ZERO], + values: vec![B256::with_last_byte(value)], + } + .abi_encode(); + legacy(MEGA_SYSTEM_ADDRESS, nonce, ORACLE_CONTRACT_ADDRESS, 0, input.into()) +} + +/// The block's state: the test callers funded. +fn state() -> revm::database::State { + let mut db = common::database(); + db.set_account_balance(SENDER, U256::from(1_000_000_000_000_000_u64)); + revm::database::State::builder().with_database(db).build() +} + +/// Asserts `err` is the refusal of an outcome its sender's state moved under. +fn assert_stale(err: &alloy_evm::block::BlockExecutionError, sender: Address) { + let message = err.to_string(); + assert!(message.contains("stale"), "{message}"); + assert!(message.contains(&sender.to_string()), "{message}"); +} + +/// Two candidates from one sender at one nonce: the first commits, and the second, which executed +/// against the nonce and balance the first then moved, is refused. Committed, it would debit the +/// sender once and credit both recipients. +#[test] +fn test_a_second_outcome_at_the_same_nonce_is_refused() { + let mut state = state(); + let mut executor = common::executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let to_b = executor.run_transaction(&legacy(CALLER, 0, PAYEE_B, 7, Bytes::new())); + let to_c = executor.run_transaction(&legacy(CALLER, 0, PAYEE_C, 9, Bytes::new())); + let (to_b, to_c) = (to_b.expect("executes"), to_c.expect("executes")); + executor.commit_transaction_outcome(to_b).expect("fresh"); + let err = executor.commit_transaction_outcome(to_c).expect_err("stale"); + assert_stale(&err, CALLER); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "the refused outcome is not in the block"); + drop(result); + assert_eq!(state.basic(CALLER).unwrap().unwrap().nonce, 1); + assert_eq!(state.basic(PAYEE_B).unwrap().unwrap().balance, U256::from(7)); + assert!(state.basic(PAYEE_C).unwrap().is_none_or(|payee| payee.balance.is_zero())); +} + +/// A candidate whose sender received value from a transaction committed since it executed is +/// refused: committing it would write back the balance it read, and lose what the other commit +/// credited. +#[test] +fn test_an_outcome_whose_senders_balance_moved_is_refused() { + let mut state = state(); + let mut executor = common::executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let waiting = executor.run_transaction(&legacy(SENDER, 0, PAYEE_B, 1, Bytes::new())).unwrap(); + let pays_the_sender = + executor.run_transaction(&legacy(CALLER, 0, SENDER, 5, Bytes::new())).unwrap(); + executor.commit_transaction_outcome(pays_the_sender).expect("fresh"); + let err = executor.commit_transaction_outcome(waiting).expect_err("stale"); + assert_stale(&err, SENDER); +} + +/// The system-address transaction is held to the system address's state: of two executed at the +/// same nonce, the one committed second is refused. +#[test] +fn test_a_second_system_transaction_at_the_same_nonce_is_refused() { + let mut state = state(); + let mut executor = common::executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = executor.run_transaction(&oracle_write(0, 1)).unwrap(); + let second = executor.run_transaction(&oracle_write(0, 2)).unwrap(); + assert!(first.result.is_success() && second.result.is_success()); + executor.commit_transaction_outcome(first).expect("fresh"); + let err = executor.commit_transaction_outcome(second).expect_err("stale"); + assert_stale(&err, MEGA_SYSTEM_ADDRESS); +} + +/// The flow a sequencer builds with: a user transaction that reads the Oracle executes first, the +/// system-address transaction that writes the Oracle executes after it and commits before it, and +/// the user transaction then commits. Neither commit moved the other's sender, so both are +/// included, in commit order; that the user transaction read the Oracle before the write is the +/// builder's to arrange. +#[test] +fn test_the_system_transaction_first_flow_commits() { + let mut state = state(); + let mut executor = common::executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let read = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let reads = legacy(CALLER, 0, ORACLE_CONTRACT_ADDRESS, 0, read.into()); + let reads = executor.run_transaction(&reads).expect("executes"); + let writes = executor.run_transaction(&oracle_write(0, 3)).expect("executes"); + assert!(reads.result.is_success() && writes.result.is_success()); + executor.commit_transaction_outcome(writes).expect("the system transaction commits first"); + executor.commit_transaction_outcome(reads).expect("and the reading transaction after it"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); + drop(result); + assert_eq!( + state.storage(ORACLE_CONTRACT_ADDRESS, U256::ZERO).unwrap(), + U256::from(3), + "the system transaction's write is in the block" + ); +} + +/// The trait's commit cannot refuse, and its contract is that an outcome commits before the next +/// transaction executes: a debug build checks a stale outcome there too, and trips on it. +#[cfg(debug_assertions)] +#[test] +fn test_the_trait_commit_trips_on_a_stale_outcome() { + let mut state = state(); + let mut executor = common::executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let to_b = executor.run_transaction(&legacy(CALLER, 0, PAYEE_B, 7, Bytes::new())); + let to_c = executor.run_transaction(&legacy(CALLER, 0, PAYEE_C, 9, Bytes::new())); + BlockExecutor::commit_transaction(&mut executor, to_b.unwrap()); + let to_c = to_c.unwrap(); + let tripped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + BlockExecutor::commit_transaction(&mut executor, to_c); + })) + .expect_err("the commit trips"); + let message = tripped + .downcast_ref::() + .map(String::as_str) + .or_else(|| tripped.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!(message.contains("stale"), "{message}"); +} diff --git a/crates/mega-evm/tests/block/state_gas.rs b/crates/mega-evm/tests/block/state_gas.rs new file mode 100644 index 000000000..a1c4549c3 --- /dev/null +++ b/crates/mega-evm/tests/block/state_gas.rs @@ -0,0 +1,77 @@ +//! The block's state gas: what its transactions spent on the state ledger, from either pool. No +//! block limit holds it: state gas prices the state a block adds, so the block's gas limit bounds +//! it. + +use alloy_consensus::transaction::Recovered; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{Bytes, TxKind, U256}; +use mega_evm::{constants::TX_GAS_LIMIT_CAP, test_utils::BytecodeBuilder, MegaTxEnvelope}; +use revm::{ + bytecode::opcode::{CALLDATALOAD, PUSH0, SSTORE}, + context::BlockEnv, + database::State, +}; + +use crate::common::{self, CALLER, CONTRACT}; + +/// Above the execution cap, where the reservoir pays state gas first. +const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + 100_000_000; + +/// Code that sets the slot the first calldata word names to one. +fn slot_writer() -> Bytes { + BytecodeBuilder::default() + .push_number(1_u8) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build() +} + +fn state() -> State { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + State::builder().with_database(db).build() +} + +/// A transaction from [`CALLER`] that fills `slot`, or leaves it as it is when it is already set. +fn writes(nonce: u64, slot: u64, gas_limit: u64) -> Recovered { + common::legacy_from( + CALLER, + nonce, + TxKind::Call(CONTRACT), + U256::ZERO, + Bytes::from(U256::from(slot).to_be_bytes::<32>()), + gas_limit, + 1_000_000, + ) +} + +/// Above the execution cap the reservoir pays the state gas, and the block counts it all the same: +/// the ledger is the state gas spent, whichever pool paid it. No limit refuses a transaction for +/// the state gas the block has spent. +#[test] +fn test_the_blocks_state_gas_counts_what_the_reservoir_paid() { + let slot = common::slot_state_gas(); + let mut state = state(); + let mut env = common::evm_env(); + env.block_env = BlockEnv { gas_limit: 10_000_000_000, ..env.block_env }; + let mut executor = common::executor_with_env(&mut state, common::unlimited_ctx(), env); + executor.apply_pre_execution_changes().expect("the block starts"); + + for (nonce, slot_index) in [(0, 1), (1, 2), (2, 3)] { + let outcome = + executor.run_transaction(&writes(nonce, slot_index, ABOVE_CAP)).expect("it executes"); + assert_eq!(outcome.gas.state, slot, "the same state gas as below the cap"); + assert!(outcome.gas.reservoir_remaining > 0, "the reservoir paid it"); + assert_eq!( + outcome.gas.reservoir_remaining, + ABOVE_CAP - TX_GAS_LIMIT_CAP - outcome.gas.state - outcome.gas.history, + ); + executor.commit_transaction_outcome(outcome).expect("no block limit refuses it"); + } + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 3); + assert_eq!(result.gas.state, 3 * slot); +} diff --git a/crates/mega-evm/tests/block/system_tx_budgets.rs b/crates/mega-evm/tests/block/system_tx_budgets.rs new file mode 100644 index 000000000..c647fc124 --- /dev/null +++ b/crates/mega-evm/tests/block/system_tx_budgets.rs @@ -0,0 +1,189 @@ +//! A Mega System Transaction against the block's packing budgets: like a deposit, no data-size +//! budget and no building policy refuses it, and it counts towards both; the header's gas limit and +//! the data-availability footprint still hold it. + +use alloy_consensus::transaction::Recovered; +use alloy_eips::Encodable2718; +use alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}; +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + BlockLimits, MegaTransactionExt, MegaTxEnvelope, +}; +use op_revm::constants::{ + DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, +}; +use revm::database::State; + +use crate::common::{ + self, empty_call_gas, executor, system_tx, user_tx, BLOCK_GAS_LIMIT, CONTRACT, +}; + +/// A second funded sender, so two ordinary transactions can execute against the same state. +const CALLER2: Address = address!("0x2000000000000000000000000000000000000003"); + +/// A legacy call from the live system address to the Oracle that declares `gas_limit`, with +/// `input` as calldata. +fn system_call(input: Bytes, gas_limit: u64) -> Recovered { + Recovered::new_unchecked( + common::tx(0, ORACLE_CONTRACT_ADDRESS, input, gas_limit), + MEGA_SYSTEM_ADDRESS, + ) +} + +/// The whole of the policy a builder could tighten, at its tightest. +fn tightest_policy() -> BlockLimits { + BlockLimits::no_limits() + .with_tx_gas_limit(1) + .with_tx_encode_size_limit(1) + .with_block_txs_encode_size_limit(1) + .with_tx_da_size_limit(0) + .with_block_da_size_limit(0) + .with_block_txs_data_limit(0) +} + +/// A block whose data-size budget is spent before it starts refuses an ordinary transaction and +/// admits a Mega System Transaction, which counts towards the budget all the same. +#[test] +fn test_a_mega_system_transaction_is_admitted_at_a_full_data_size_budget() { + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(0)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("an ordinary transaction finds the budget spent"); + + let outcome = + executor.run_transaction(&system_tx()).expect("the system transaction is admitted"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + let data_size = outcome.inner.usage.data_size; + assert!(data_size > 0); + executor.commit_transaction_outcome(outcome).expect("and committed"); + + assert_eq!(executor.limiter().usage.data_size, data_size, "it counts towards the budget"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1); +} + +/// A building policy at its tightest refuses an ordinary transaction and no system transaction: +/// the system transaction's size counts towards the block's encoded and data-availability sizes. +#[test] +fn test_a_mega_system_transaction_is_admitted_under_a_tightened_building_policy() { + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("the policy refuses an ordinary transaction"); + + let system = system_tx(); + let outcome = executor.run_transaction(&system).expect("the policy does not refuse it"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + executor.commit_transaction_outcome(outcome).expect("and it commits"); + + assert_eq!(executor.limiter().block_tx_size_used, system.inner().encode_2718_len() as u64); + assert_eq!( + executor.limiter().block_da_size_used, + MegaTransactionExt::estimated_da_size(&system) + ); +} + +/// The commit-time check reads the same decision: an outcome executed while the budget had room +/// still commits after another commit spent it, where an ordinary transaction's outcome does not. +#[test] +fn test_a_delayed_commit_of_a_mega_system_transaction_ignores_the_spent_budget() { + let mut db = common::database(); + db.set_account_balance(CALLER2, U256::from(1_000_000_000_000_000_u64)); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(1)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let first = executor.run_transaction(&user_tx(0, empty_call_gas())).expect("room"); + let second = executor + .run_transaction(&Recovered::new_unchecked( + common::tx(0, CONTRACT, Bytes::new(), empty_call_gas()), + CALLER2, + )) + .expect("room"); + let system = executor.run_transaction(&system_tx()).expect("room"); + + executor.commit_transaction_outcome(first).expect("the first fills the budget"); + executor.commit_transaction_outcome(system).expect("a system transaction does not need room"); + executor.commit_transaction_outcome(second).expect_err("an ordinary transaction does"); +} + +/// The header's gas limit still holds a Mega System Transaction. +#[test] +fn test_a_mega_system_transaction_is_still_refused_by_the_header_gas_limit() { + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); + executor.apply_pre_execution_changes().expect("the block starts"); + + let err = executor + .execute_transaction(&system_call(Bytes::new(), BLOCK_GAS_LIMIT + 1)) + .expect_err("it declares more gas than the header allows"); + assert!( + matches!( + err, + BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. } + ) + ), + "{err}" + ); + assert!(executor.receipts().is_empty()); +} + +/// The data-availability footprint still holds a Mega System Transaction, as it holds any +/// transaction of a legacy envelope. +#[test] +fn test_a_mega_system_transaction_is_still_refused_by_the_da_footprint() { + let mut db = common::database(); + let mut word = [0_u8; 32]; + word[DA_FOOTPRINT_GAS_SCALAR_OFFSET..DA_FOOTPRINT_GAS_SCALAR_OFFSET + 2] + .copy_from_slice(&u16::MAX.to_be_bytes()); + db.set_account_storage( + L1_BLOCK_CONTRACT, + DA_FOOTPRINT_GAS_SCALAR_SLOT, + U256::from_be_bytes(word), + ); + let mut state = State::builder().with_database(db).build(); + let mut executor = executor(&mut state, common::block_ctx(tightest_policy())); + executor.apply_pre_execution_changes().expect("the block starts"); + + let big = system_call(common::incompressible(100_000), 3_000_000); + let err = executor.execute_transaction(&big).expect_err("the footprint does not fit"); + assert!( + format!("{err}").contains("DA footprint exceeds available block DA footprint"), + "{err}" + ); +} + +/// The live system address sends the system shape or nothing: a transaction from it to a contract +/// off the whitelist is no Mega System Transaction, so the budget refuses it before it runs. +#[test] +fn test_an_unshaped_transaction_from_the_system_address_is_no_system_transaction() { + let mut state = common::state(); + let mut executor = executor( + &mut state, + common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(0)), + ); + executor.apply_pre_execution_changes().expect("the block starts"); + + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let off_whitelist = Recovered::new_unchecked( + common::tx(0, CONTRACT, input.into(), 1_000_000), + MEGA_SYSTEM_ADDRESS, + ); + let err = executor.execute_transaction(&off_whitelist).expect_err("not a system transaction"); + assert!(format!("{err}").contains("Block transactions data limit reached"), "{err}"); +} diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs new file mode 100644 index 000000000..1276242de --- /dev/null +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -0,0 +1,317 @@ +//! The EIP-7708 transfer logs in a block's receipts. +//! +//! Every value movement is logged where it happens, so a receipt carries its transaction's +//! transfer logs in execution order among the logs contracts emit, and its bloom includes them. +//! The block's data size counts them; its history columns do not. A deposit's value is logged and +//! its mint is not; a system transaction, as the sequencer builds it, moves no value and logs no +//! transfer. + +use alloy_consensus::{transaction::Recovered, Sealed, TxReceipt}; +use alloy_evm::block::BlockExecutor; +use alloy_primitives::{ + address, keccak256, logs_bloom, Address, BloomInput, Bytes, Log, TxKind, B256, U256, +}; +use alloy_sol_types::SolCall; +use mega_evm::{ + revm::primitives::eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}, + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{is_transfer_log, transfer_log, BytecodeBuilder}, + MegaTxEnvelope, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, +}; +use op_alloy_consensus::{OpReceiptEnvelope, TxDeposit}; +use revm::{ + bytecode::opcode::{LOG1, POP}, + context::ContextTr, + database::State, + Database, +}; + +use crate::common::{self, executor, CALLER}; + +/// An account with no code. +const PAYEE: Address = address!("0x7000000000000000000000000000000000000001"); +/// A contract that emits an event, then passes three wei on to [`PAYEE`]. +const FORWARDER: Address = address!("0x7000000000000000000000000000000000000002"); +/// A contract holding [`DESTRUCTOR_BALANCE`] that destructs to [`PAYEE`]. +const DESTRUCTOR: Address = address!("0x7000000000000000000000000000000000000003"); +/// The account a deposit comes from. +const DEPOSITOR: Address = address!("0x7000000000000000000000000000000000000004"); + +const DESTRUCTOR_BALANCE: u64 = 13; + +/// The event [`FORWARDER`] emits between the value it receives and the value it passes on. +const MARKER: B256 = B256::repeat_byte(0x4d); + +fn state() -> State { + let forwarder = BytecodeBuilder::default() + .push_bytes(MARKER) + .append_many([0x5f, 0x5f]) // PUSH0 PUSH0: no data at offset 0 + .append(LOG1) + .call(PAYEE, U256::from(3)) + .stop() + .build(); + let mut db = common::database(); + db.set_account_code(FORWARDER, forwarder); + db.set_account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(PAYEE).build()); + db.set_account_balance(DESTRUCTOR, U256::from(DESTRUCTOR_BALANCE)); + State::builder().with_database(db).build() +} + +/// A gas limit for any transaction here: 1,000,000 of regular gas on top of the state of two new +/// accounts and a fresh slot, a kilobyte of history beyond the body, and 64 times the history of +/// two write records, at the byte prices in effect: [`FORWARDER`] forwards all but a 64th of its +/// gas with the value it passes on, and pays the records of the frame it starts from the 64th it +/// keeps. +fn gas_limit() -> u64 { + 1_000_000 + + 2 * common::new_account_state_gas() + + common::slot_state_gas() + + common::body_history(1_000) + + 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") +} + +/// A legacy transaction from `signer` with `value`. +fn legacy( + signer: Address, + nonce: u64, + to: TxKind, + value: u64, + input: Bytes, +) -> Recovered { + common::legacy_from(signer, nonce, to, U256::from(value), input, gas_limit(), 1_000_000) +} + +/// A deposit from [`DEPOSITOR`] to [`PAYEE`] minting `mint` and moving `value`. +fn deposit(mint: u128, value: u64) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0xd0), + from: DEPOSITOR, + to: TxKind::Call(PAYEE), + mint, + value: U256::from(value), + // Room for the state gas of the two accounts it creates: its depositor's and its payee's. + gas_limit: gas_limit(), + is_system_transaction: false, + input: Bytes::new(), + }; + let sealed = Sealed::new_unchecked(deposit, B256::repeat_byte(mint as u8)); + Recovered::new_unchecked(MegaTxEnvelope::Deposit(sealed), DEPOSITOR) +} + +/// The logs a receipt carries, having checked its bloom is theirs, with the transfer logs in it. +fn logs_of(receipt: &OpReceiptEnvelope) -> &[Log] { + let logs = receipt.logs(); + assert_eq!(receipt.bloom(), logs_bloom(logs), "the bloom is the receipt's logs'"); + if logs.iter().any(is_transfer_log) { + let bloom = receipt.bloom(); + assert!(bloom.contains_input(BloomInput::Raw(ETH_TRANSFER_LOG_ADDRESS.as_slice()))); + assert!(bloom.contains_input(BloomInput::Raw(ETH_TRANSFER_LOG_TOPIC.as_slice()))); + } + logs +} + +/// A block with a value transfer, a value call passed on by a contract that emits an event +/// between the two moves, a creation with an endowment and a destruction. Each receipt carries its +/// transfer logs in execution order, its bloom includes them, and the block's data size counts +/// each at 160 bytes while its history bytes leave them out. +#[test] +fn test_a_blocks_receipts_carry_its_transfer_logs_in_execution_order() { + let mut state = state(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + + let txs = [ + legacy(CALLER, 0, TxKind::Call(PAYEE), 5, Bytes::new()), + legacy(CALLER, 1, TxKind::Call(FORWARDER), 7, Bytes::new()), + legacy(CALLER, 2, TxKind::Create, 11, Bytes::new()), + legacy(CALLER, 3, TxKind::Call(DESTRUCTOR), 0, Bytes::new()), + ]; + let expected: [Vec; 4] = [ + vec![transfer_log(CALLER, PAYEE, U256::from(5))], + vec![ + transfer_log(CALLER, FORWARDER, U256::from(7)), + Log::new_unchecked(FORWARDER, vec![MARKER], Bytes::new()), + transfer_log(FORWARDER, PAYEE, U256::from(3)), + ], + vec![transfer_log(CALLER, CALLER.create(2), U256::from(11))], + vec![transfer_log(DESTRUCTOR, PAYEE, U256::from(DESTRUCTOR_BALANCE))], + ]; + // The records each keeps: the recipient; the forwarder and the payee; the created account; + // the destruction's beneficiary. + let records = [1, 2, 1, 1]; + + let mut data_size = 0; + let mut history_bytes = 0; + for (i, tx) in txs.iter().enumerate() { + let outcome = executor.run_transaction(tx).expect("it executes"); + assert!(outcome.result.is_success(), "transaction {i}: {:?}", outcome.result); + // No transaction here carries calldata, an access list or an authorization. + let (transfers, events): (Vec<&Log>, Vec<&Log>) = + expected[i].iter().partition(|log| is_transfer_log(log)); + let event_bytes: u64 = events + .iter() + .map(|log| { + LOG_BASE_SIZE + + LOG_TOPIC_SIZE * log.topics().len() as u64 + + log.data.data.len() as u64 + }) + .sum(); + let kept = TX_BODY_SIZE + records[i] * WRITE_RECORD_SIZE + event_bytes; + assert_eq!( + outcome.usage.data_size, + kept + transfers.len() as u64 * TRANSFER_LOG_SIZE, + "transaction {i}: the transfer logs are data size", + ); + assert_eq!(outcome.gas.history_bytes, kept, "transaction {i}: and not history"); + data_size += outcome.usage.data_size; + history_bytes += outcome.gas.history_bytes; + executor.commit_transaction_outcome(outcome).expect("the block has room"); + } + + for (i, receipt) in executor.receipts().iter().enumerate() { + assert_eq!(logs_of(receipt), expected[i].as_slice(), "receipt {i}"); + } + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.usage.data_size, data_size, "the block counts every transfer log"); + assert_eq!(result.gas.history_bytes, history_bytes, "and its history bytes none of them"); +} + +/// A deposit's mint is credited before it runs and is logged nowhere; its value moves in its +/// first frame and is logged there, into the deposit's receipt. A deposit that only mints logs +/// nothing. +#[test] +fn test_a_deposit_receipt_logs_its_value_and_not_its_mint() { + let mut state = state(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction(&deposit(1_000, 400)).expect("the deposit executes"); + executor.execute_transaction(&deposit(1_000, 0)).expect("the deposit executes"); + + let [OpReceiptEnvelope::Deposit(moved), OpReceiptEnvelope::Deposit(minted)] = + executor.receipts() + else { + panic!("two deposit receipts, got {:?}", executor.receipts()); + }; + assert!( + moved.receipt.inner.status.coerce_status() && minted.receipt.inner.status.coerce_status() + ); + assert_eq!( + logs_of(&OpReceiptEnvelope::Deposit(moved.clone())), + [transfer_log(DEPOSITOR, PAYEE, U256::from(400))], + "the value's log, and none for the mint", + ); + assert!(minted.receipt.inner.logs.is_empty(), "a mint alone is logged nowhere"); +} + +/// A system transaction writes the protocol's state and moves no value, so its receipt carries no +/// transfer log. +#[test] +fn test_a_system_transaction_receipt_logs_no_transfer() { + let mut state = state(); + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + let set_slot = IOracle::setSlotCall { slot: U256::from(1), value: B256::repeat_byte(1) }; + let tx = legacy( + MEGA_SYSTEM_ADDRESS, + 0, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + 0, + set_slot.abi_encode().into(), + ); + let outcome = executor.run_transaction(&tx).expect("the system transaction executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + let [receipt] = executor.receipts() else { panic!("one receipt") }; + assert!(!logs_of(receipt).iter().any(is_transfer_log), "no value moved, nothing logged"); +} + +/// [S14.9] [S14] The balance of an account destroyed earlier in the transaction is burned at its +/// end without a log. A factory creates a child endowed with 17 wei whose constructor destructs to +/// [`PAYEE`], moving the 17 on, then sends the destroyed child 5 wei. The receipt carries exactly +/// the three transfers — the endowment, the destruction's move and the late value — and nothing +/// for the burn, no `Burn` log of any EIP-7708 revision either. The 5 wei are no account's: across +/// every account the transaction touched, the fees included, the balances add up to 5 less than +/// before, and once the block finishes the child is gone, the payee holds the 17 and the factory +/// nothing. +/// +/// Expected values: independent. +#[test] +fn test_a_value_left_on_a_destroyed_account_is_burned_without_a_log() { + const FACTORY: Address = address!("0x7000000000000000000000000000000000000005"); + const ENDOWMENT: u64 = 17; + const LATE: u64 = 5; + let child = FACTORY.create(1); + let constructor = BytecodeBuilder::default().selfdestruct(PAYEE).build(); + let factory = BytecodeBuilder::default() + .create(U256::from(ENDOWMENT), &constructor) + .append(POP) + .call(child, U256::from(LATE)) + .append(POP) + .stop() + .build(); + let mut db = common::database(); + db.set_account_code(FACTORY, factory); + db.set_account_nonce(FACTORY, 1); + db.set_account_balance(FACTORY, U256::from(ENDOWMENT + LATE)); + let mut state = State::builder().with_database(db).build(); + + let mut executor = executor(&mut state, common::unlimited_ctx()); + executor.apply_pre_execution_changes().expect("the block starts"); + // 1,000,000 of regular gas on top of what the byte prices in effect charge: the state of up + // to three new accounts — the child, the payee, the child again for the late value — the + // history of the body, and 64 times the history of the creation's two start records, because + // the factory forwards all but a 64th of its gas and pays a start's records from the 64th it + // keeps. The creation returns its unused gas before the late value call, whose single record + // costs less: the factory's is already written in this frame. + let gas_limit = 1_000_000 + + 3 * common::new_account_state_gas() + + common::body_history(0) + + 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + let tx = common::legacy_from( + CALLER, + 0, + TxKind::Call(FACTORY), + U256::ZERO, + Bytes::new(), + gas_limit, + 1_000_000, + ); + let outcome = executor.run_transaction(&tx).expect("it executes"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + // Value is conserved across every account the transaction touched, its fees included, but + // for the late value: a destroyed account holds nothing once the transaction ends. + let (mut before, mut after) = (U256::ZERO, U256::ZERO); + for (address, account) in &outcome.state { + let db = executor.evm_mut().ctx_mut().db_mut(); + before += db.basic(*address).expect("readable").map_or(U256::ZERO, |info| info.balance); + if !account.is_selfdestructed() { + after += account.info.balance; + } + } + assert_eq!(before - after, U256::from(LATE), "the late value is no account's"); + executor.commit_transaction_outcome(outcome).expect("the block has room"); + + let [receipt] = executor.receipts() else { panic!("one receipt") }; + let logs = logs_of(receipt); + assert_eq!( + logs, + [ + transfer_log(FACTORY, child, U256::from(ENDOWMENT)), + transfer_log(child, PAYEE, U256::from(ENDOWMENT)), + transfer_log(FACTORY, child, U256::from(LATE)), + ], + "the three transfers, and nothing for the burn" + ); + let burn = keccak256("Burn(address,uint256)"); + assert!(logs.iter().all(|log| !log.topics().contains(&burn)), "no Burn log"); + + executor.finish_with_counters().expect("the block finishes"); + let balance = |state: &mut State, address| { + state.basic(address).expect("readable").map(|account| account.balance) + }; + assert_eq!(balance(&mut state, child), None, "the destroyed child is gone"); + assert_eq!(balance(&mut state, PAYEE), Some(U256::from(ENDOWMENT))); + assert_eq!(balance(&mut state, FACTORY), Some(U256::ZERO), "the factory sent everything"); +} diff --git a/crates/mega-evm/tests/block/witness/basics.rs b/crates/mega-evm/tests/block/witness/basics.rs new file mode 100644 index 000000000..f31d7a4c3 --- /dev/null +++ b/crates/mega-evm/tests/block/witness/basics.rs @@ -0,0 +1,276 @@ +//! The harness on ordinary blocks: writes, an empty block, a refused transaction, a dropped +//! candidate, the reads of a frame that failed and of a deposit that failed, a SALT lookup that +//! fails and one answered below the minimum bucket. + +use alloy_primitives::{address, Bytes, TxKind, U256}; +use mega_evm::{test_utils::BytecodeBuilder, MegaHaltReason, SaltEnv, MIN_BUCKET_SIZE}; +use revm::{ + bytecode::opcode::{ + BALANCE, CALL, CALLDATALOAD, GAS, INVALID, POP, PUSH0, REVERT, SLOAD, SSTORE, + }, + context::result::ExecutionResult, +}; + +use super::harness::{call, deposit, Case, Envs}; +use crate::common::{self, CONTRACT}; + +/// Code that sets the slot the first calldata word names to one. +pub(crate) fn slot_writer() -> Bytes { + BytecodeBuilder::default() + .push_number(1_u8) + .append(PUSH0) + .append(CALLDATALOAD) + .append(SSTORE) + .stop() + .build() +} + +/// Calldata naming `slot`. +pub(crate) fn slot(slot: u64) -> Bytes { + U256::from(slot).to_be_bytes::<32>().to_vec().into() +} + +/// A gas limit for one fresh slot's write with 32 bytes of calldata, at the byte prices in +/// effect. +pub(crate) fn write_gas() -> u64 { + 1_000_000 + + common::slot_state_gas() + + common::body_history(32) + + mega_evm::write_record_history_gas(1).expect("a record has a price") +} + +/// A block whose transactions write two fresh slots: the replay reads only the record and +/// produces the same block, and the exported buckets are the two slots'. The block is not Satin's +/// activation block, so its pre-block phase reads no predeploy and the record holds none that no +/// transaction reached. +#[test] +fn test_a_block_of_writes_replays_from_its_witness() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let replay = Case::new("writes", db) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .tx(call(1, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert_eq!(run.receipts.len(), 2); + if !common::state_is_free() { + assert_eq!(run.bucket_ids.len(), 2, "one bucket per fresh slot"); + } + assert_eq!( + run.record.accounts.get(&mega_evm::system::ORACLE_CONTRACT_ADDRESS), + None, + "nothing asked about the Oracle's account" + ); + assert!(run.record.codes.values().all(|code| !code.is_empty()), "code travels by hash"); + assert_eq!( + replay.replayed.record, run.record, + "the replay read exactly what the recording read, nothing less" + ); +} + +/// An empty block: the pre-block phase alone, whose reads the record holds. +#[test] +fn test_an_empty_block_replays_from_its_witness() { + let replay = Case::new("empty", common::database()).run(); + assert!(replay.recorded.txs.is_empty()); + assert!(replay.recorded.bucket_ids.is_empty()); + assert!(!replay.recorded.record.accounts.is_empty(), "the pre-block phase reads accounts"); +} + +/// A transaction the block refuses before it runs — its declared gas above the block's gas +/// limit — reads nothing, is in no state, and is not run on replay. +#[test] +fn test_a_refused_transaction_reads_nothing_and_is_not_replayed() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let replay = Case::new("refused", db) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .tx(call(1, CONTRACT, slot(2), common::BLOCK_GAS_LIMIT + 1)) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success()); + assert!(run.refusal(1).contains("gas limit"), "{}", run.refusal(1)); + assert_eq!(run.receipts.len(), 1); + assert!( + !run.record.storage.contains_key(&(CONTRACT, U256::from(2))), + "the refused transaction read no slot" + ); + assert!(!run.keys.slots.contains(&(CONTRACT, U256::from(2))), "and no state names it"); + assert!(replay.replayed.txs[1].is_err() && replay.channel.txs[1].is_err(), "not replayed"); +} + +/// A candidate the builder executes and drops reads like any transaction — its reads are in the +/// database-level record — and is in no state, no receipt and no replay; the block's other +/// transaction replays on a witness that holds nothing of it. +#[test] +fn test_a_dropped_candidate_is_in_no_state_and_no_replay() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let replay = Case::new("dropped candidate", db) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .dropped(0) + .tx(call(0, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.txs[0].is_err(), "dropped"); + assert!(run.tx(1).result.is_success()); + assert_eq!(run.receipts.len(), 1); + assert!(run.record.storage.contains_key(&(CONTRACT, U256::from(1))), "executed, so read"); + assert!(!run.keys.slots.contains(&(CONTRACT, U256::from(1))), "in no state"); + assert!(run.keys.slots.contains(&(CONTRACT, U256::from(2)))); + assert!(replay.channel.txs[0].is_err() && replay.channel.tx(1).result.is_success()); + if !common::state_is_free() { + assert_eq!(run.bucket_ids.len(), 2, "the export holds the dropped candidate's bucket too"); + } +} + +/// A SALT lookup that fails fails its transaction, which is in no block: the failure is in the +/// environment's record, the bucket is not exported, and the block's other transaction replays +/// on a witness that proves the answered bucket alone. +#[test] +fn test_a_failed_salt_lookup_fails_its_transaction_and_is_not_exported() { + if common::state_is_free() { + return; + } + let failing = ::bucket_id_for_slot(CONTRACT, U256::from(1)); + let answered = ::bucket_id_for_slot(CONTRACT, U256::from(2)); + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let replay = Case::new("failed lookup", db) + .envs(Envs::new().with_failing_bucket(failing, "salt backend unreachable".into())) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .tx(call(0, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.refusal(0).contains("salt backend unreachable"), "{}", run.refusal(0)); + assert!(run.tx(1).result.is_success()); + assert_eq!(run.receipts.len(), 1); + assert_eq!( + run.record.buckets.get(&failing), + Some(&Err("salt backend unreachable".into())), + "the environment recorded the failure" + ); + assert_eq!(run.bucket_ids, vec![answered], "the export holds the answered bucket alone"); +} + +/// A SALT environment that answers a capacity below the minimum bucket has answered nothing a +/// bucket can hold: the lookup fails its transaction as an error does, so the bucket is not +/// exported although the environment's record holds its answer, and the block's other +/// transaction replays on a witness that proves the valid bucket alone. +#[test] +fn test_a_capacity_below_the_minimum_fails_its_transaction_and_is_not_exported() { + if common::state_is_free() { + return; + } + let below = ::bucket_id_for_slot(CONTRACT, U256::from(1)); + let valid = ::bucket_id_for_slot(CONTRACT, U256::from(2)); + let capacity = MIN_BUCKET_SIZE as u64 - 1; + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let replay = Case::new("capacity below the minimum", db) + .envs(Envs::new().with_bucket_capacity(below, capacity)) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .tx(call(0, CONTRACT, slot(2), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.refusal(0).contains("below the minimum bucket"), "{}", run.refusal(0)); + assert!(run.tx(1).result.is_success()); + assert_eq!(run.receipts.len(), 1); + assert_eq!(run.record.buckets.get(&below), Some(&Ok(capacity)), "the environment answered"); + assert_eq!(run.bucket_ids, vec![valid], "the export holds the valid bucket alone"); +} + +/// A frame that failed has loaded what it read: its failure takes back its writes, not its +/// reads. A call into a contract that reads one of its slots and another account's balance, then +/// reverts or halts, leaves the transaction a success whose state names the slot and the account, +/// so the channel witness holds them and the block replays from it — a validator re-executing the +/// transaction makes the same reads in the same frame. +#[test] +fn test_the_reads_of_a_frame_that_failed_are_in_the_witness() { + let reader = address!("0x4000000000000000000000000000000000000007"); + let read = address!("0x4000000000000000000000000000000000000008"); + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(reader) + .append_many([GAS, CALL, POP]) + .stop() + .build(); + for (how, ending) in [("reverts", vec![PUSH0, PUSH0, REVERT]), ("halts", vec![INVALID])] { + let code = BytecodeBuilder::default() + .push_number(7_u8) + .append_many([SLOAD, POP]) + .push_address(read) + .append_many([BALANCE, POP]) + .append_many(ending) + .build(); + let db = common::database() + .account_code(CONTRACT, caller.clone()) + .account_code(reader, code) + .account_storage(reader, U256::from(7), U256::from(70)) + .account_balance(read, U256::from(80)); + let replay = Case::new(&format!("a frame that {how}"), db) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{how}: {:?}", run.tx(0).result); + let state = &run.tx(0).state; + assert!(state[&reader].storage.contains_key(&U256::from(7)), "{how}: the slot is named"); + assert!(state.contains_key(&read), "{how}: the account is named"); + assert!(run.keys.slots.contains(&(reader, U256::from(7))), "{how}: and is a key"); + assert!(run.keys.accounts.contains(&read), "{how}: as is the account"); + } +} + +/// A deposit that failed has loaded what its frames read, as a frame that failed has: the +/// failure takes back everything but the sender's nonce bump and mint, not the reads. A deposit +/// from a sender that does not exist into a contract that reads one of its slots and another +/// account's balance, then halts, is included as a failed deposit whose state names the slot and +/// the account beside the sender it created, so the channel witness holds them and the block +/// replays from it — a validator re-executing the deposit makes the same reads in the same frame. +/// The failed deposit uses its whole gas limit, all of it regular gas: the account it creates for +/// its sender carries no state gas on any ledger, and it pays no history. +#[test] +fn test_the_reads_of_a_deposit_that_failed_are_in_the_witness() { + let depositor = address!("0x4000000000000000000000000000000000000009"); + let reader = address!("0x4000000000000000000000000000000000000007"); + let read = address!("0x4000000000000000000000000000000000000008"); + let code = BytecodeBuilder::default() + .push_number(7_u8) + .append_many([SLOAD, POP]) + .push_address(read) + .append_many([BALANCE, POP]) + .append(INVALID) + .build(); + let db = common::database() + .account_code(reader, code) + .account_storage(reader, U256::from(7), U256::from(70)) + .account_balance(read, U256::from(80)); + let (mint, gas_limit) = (1_000_000_000, 1_000_000 + common::new_account_state_gas()); + let replay = Case::new("a deposit that failed", db) + .tx(deposit(depositor, TxKind::Call(reader), mint, U256::ZERO, Bytes::new(), gas_limit)) + .run(); + let run = &replay.recorded; + let tx = run.tx(0); + assert!( + matches!(tx.result, ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. }), + "{:?}", + tx.result + ); + assert!(tx.state[&reader].storage.contains_key(&U256::from(7)), "the slot is named"); + assert!(tx.state.contains_key(&read), "the account is named"); + assert!(run.keys.slots.contains(&(reader, U256::from(7))), "and is a key"); + assert!(run.keys.accounts.contains(&read), "as is the account"); + + assert_eq!(run.record.accounts.get(&depositor), Some(&None), "the sender did not exist"); + let sender = &tx.state[&depositor].info; + assert_eq!(sender.nonce, 1, "the failure keeps the nonce bump"); + assert_eq!(sender.balance, U256::from(mint), "and the mint"); + assert_eq!(tx.gas.gas_used, gas_limit, "a failed deposit uses its whole gas limit"); + assert_eq!( + (tx.gas.regular, tx.gas.state, tx.gas.history, tx.gas.history_bytes), + (gas_limit, 0, 0, 0), + "all of it regular gas: the account it created carries no state gas" + ); + assert_eq!((run.gas.state, run.gas.history), (0, 0), "nor does the block count any"); +} diff --git a/crates/mega-evm/tests/block/witness/harness.rs b/crates/mega-evm/tests/block/witness/harness.rs new file mode 100644 index 000000000..f368935ac --- /dev/null +++ b/crates/mega-evm/tests/block/witness/harness.rs @@ -0,0 +1,676 @@ +//! The witness-replay harness: a block is executed once on a database and environments that +//! record every read, then twice more on a strict database and environments that serve exactly a +//! witness and refuse everything else — once on the record of every database read, once on the +//! witness a node builds from its channels — and every replay must produce the block the +//! recording produced. +//! +//! The channel witness is the check a validator's witness must pass: its keys are what the states +//! the block committed name — the pre-block steps', read-only entries included, and the included +//! transactions' — as a node's commit hook on the block's `State` receives them, its values the +//! chain's, its block hashes and buckets the engine's exports, and its oracle answers the included +//! transactions' own records. The database-level replay is a different check: that the block +//! reads nothing outside its database and environments and computes the same block twice. Both +//! replays run the transactions the recorded block included, and only those: a candidate the +//! builder executed and dropped, or a transaction the block refused, is no validator's to run. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt::Debug, +}; + +use alloy_consensus::{transaction::Recovered, Signed, TxEip7702}; +use alloy_eips::eip7702::{Authorization, SignedAuthorization}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; +use alloy_op_evm::block::receipt_builder::{OpAlloyReceiptBuilder, OpReceiptBuilder}; +use alloy_primitives::{Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + test_utils::{ + CommittedStates, MemoryDatabase, RecordingDatabase, RecordingEnvFactory, + SharedWitnessRecord, StrictDatabase, StrictEnvFactory, WitnessKeys, WitnessRecord, + }, + BlockGasCounters, BucketId, ExternalEnvFactory, LimitCheck, LimitUsage, MegaBlockExecutionCtx, + MegaBlockExecutor, MegaEvmFactory, MegaGasUsage, MegaHaltReason, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, OracleRead, ProtocolLimits, SaltEnv, TestExternalEnvs, + MIN_BUCKET_SIZE, +}; +use op_alloy_consensus::TxDeposit; +use revm::{ + context::result::ExecutionResult, + database::{states::bundle_state::BundleRetention, BundleState, CacheState, State}, + state::EvmState, + Database, +}; + +use crate::common::{self, CALLER, CHAIN_ID}; + +/// A transaction of a block the harness runs. +pub(crate) type Tx = Recovered; + +/// The receipt the executor builds. +pub(crate) type Receipt = ::Receipt; + +/// The environments a case's block runs against: configurable buckets, oracle answers and hint +/// recording, and buckets whose lookup fails. +pub(crate) type Envs = TestExternalEnvs; + +/// Which oracle service a replay runs against. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Oracle { + /// The recorded answers, replayed in order: what a validator given the answers would run. + Recorded, + /// No service at all: what a validator runs today. Every read is answered from the chain. + Absent, +} + +/// A block to run: its pre-state, environments, schedule, context, block environment and +/// candidate transactions, some of which the builder executes and drops. +pub(crate) struct Case { + pub name: String, + pub db: MemoryDatabase, + pub envs: Envs, + pub spec: MegaHardforkConfig, + /// The limits the block is held to in place of the spec's, if any. + pub limits: Option, + pub ctx: MegaBlockExecutionCtx, + pub env: EvmEnv, + pub txs: Vec, + /// The candidates the builder executes and then does not commit. + pub dropped: BTreeSet, + /// The answers the oracle service moves on to while the block is built: `(index, slot, + /// value)` has it answer `value` for `slot` once the candidate at `index` was executed. + pub service_updates: Vec<(usize, U256, U256)>, +} + +/// Why a candidate is not in the recorded block. +const DROPPED: &str = "executed and dropped by the builder"; + +/// Why a replay did not run a candidate. +const NOT_INCLUDED: &str = "not in the recorded block"; + +impl Case { + /// A block over `db` on the tests' chain, with no building policy and no transactions. + pub(crate) fn new(name: &str, db: MemoryDatabase) -> Self { + Self { + name: name.into(), + db, + envs: Envs::new(), + spec: common::chain_spec(), + limits: None, + ctx: common::unlimited_ctx(), + env: common::evm_env(), + txs: Vec::new(), + dropped: BTreeSet::new(), + service_updates: Vec::new(), + } + } + + /// Adds a transaction. + pub(crate) fn tx(mut self, tx: Tx) -> Self { + self.txs.push(tx); + self + } + + /// Has the builder execute the candidate at `index` and drop it: its outcome is not + /// committed, and it is not in the block. + pub(crate) fn dropped(mut self, index: usize) -> Self { + self.dropped.insert(index); + self + } + + /// Has the oracle service answer `value` for `slot` from the moment the candidate at `index` + /// was executed: the service moves on while the builder works, so two executions that read + /// one slot may be answered differently. + pub(crate) fn service_answers_after(mut self, index: usize, slot: U256, value: U256) -> Self { + self.service_updates.push((index, slot, value)); + self + } + + /// Sets the oracle service's answer for `slot`. The environments a recording runs against + /// share their answers with the case's, so the running block sees the change. + fn set_service_answer(&self, slot: U256, value: U256) { + drop(self.envs.clone().with_oracle_storage(slot, value)); + } + + /// Runs against `envs`. + pub(crate) fn envs(mut self, envs: Envs) -> Self { + self.envs = envs; + self + } + + /// Holds the block to `limits` in place of the spec's. + pub(crate) fn limits(mut self, limits: ProtocolLimits) -> Self { + self.limits = Some(limits); + self + } + + /// Runs under `ctx`. + pub(crate) fn ctx(mut self, ctx: MegaBlockExecutionCtx) -> Self { + self.ctx = ctx; + self + } + + /// Runs in the block environment `env`. + pub(crate) fn env(mut self, env: EvmEnv) -> Self { + self.env = env; + self + } + + /// Runs the block, recording every read: every candidate is executed, and the ones the + /// builder drops are not committed. The oracle service moves on to its later answers as the + /// candidates are executed, and is put back where the block found it afterwards, so another + /// recording of the case meets the same service. + pub(crate) fn record(&self) -> Run { + let record = SharedWitnessRecord::default(); + let state = State::builder() + .with_database(RecordingDatabase::new(self.db.clone(), record.clone())) + .with_bundle_update() + .build(); + let factory = RecordingEnvFactory::new(self.envs.clone(), record.clone()); + let answers = self.envs.oracle_storage(); + let mut run = self.drive( + state, + factory, + |_| true, + |executed| { + for (index, slot, value) in &self.service_updates { + if *index == executed { + self.set_service_answer(*slot, *value); + } + } + }, + ); + self.envs.clear_oracle_storage(); + for (slot, value) in answers { + self.set_service_answer(slot, value); + } + run.record = record.take(); + run + } + + /// Runs the transactions `included` names again on exactly what `witness` holds, against + /// `oracle`: the recorded answers are the witness's, in order. + pub(crate) fn replay(&self, witness: &WitnessRecord, included: &[bool], oracle: Oracle) -> Run { + let reads = SharedWitnessRecord::default(); + let state = State::builder() + .with_database(RecordingDatabase::new( + StrictDatabase::new(witness.clone()), + reads.clone(), + )) + .with_bundle_update() + .build(); + let strict = match oracle { + Oracle::Recorded => StrictEnvFactory::::replaying(witness), + Oracle::Absent => StrictEnvFactory::::without_oracle(witness), + }; + let factory = RecordingEnvFactory::new(strict.clone(), reads.clone()); + let mut run = self.drive(state, factory, |index| included[index], |_| {}); + run.record = reads.take(); + run.oracle_replayed_exactly = strict.oracle().replayed_exactly(); + run + } + + /// The witness a node builds from `recorded`'s channels: the keys the states it committed + /// name, resolved against the case's pre-state; the exported block hashes; the exported + /// buckets with the capacities the case's environments hold; and the included transactions' + /// own oracle reads, in block order. + pub(crate) fn channel_witness(&self, recorded: &Run) -> WitnessRecord { + let buckets = recorded + .bucket_ids + .iter() + .map(|id| (*id, self.envs.get_bucket_capacity(*id))) + .collect(); + WitnessRecord::from_channels( + &mut self.db.clone(), + &recorded.keys, + recorded.block_hashes.clone(), + buckets, + recorded.included_oracle_reads(), + ) + .expect("the pre-state is readable") + } + + /// Replays the transactions `recorded` included on the channel witness, against `oracle`. + pub(crate) fn replay_channels(&self, recorded: &Run, oracle: Oracle) -> Run { + self.replay(&self.channel_witness(recorded), &recorded.included(), oracle) + } + + /// Records the block, replays its included transactions on the record of every database + /// read and on the channel witness, against the included transactions' recorded oracle + /// answers, and asserts every replay produced the block the recording produced; that each run + /// committed its pre-block states, then its included transactions' states; that the engine's + /// oracle records are the service's own view of the block; and that the executor's exports + /// are the recorded side-channel reads, a bucket only where the environment answered it with + /// a valid capacity. + /// + /// A replay that asks for a key its witness does not hold is refused the read, and the + /// transaction or the block that asked fails with it, so the comparison with the recording is + /// what catches a missing key; a replay's own record holds only the reads its witness served, + /// and cannot show one. + pub(crate) fn run(self) -> Replay { + let recorded = self.record(); + let included = recorded.included(); + assert_commits_the_block(&self.name, &recorded); + + let mut record = recorded.record.clone(); + record.oracle_reads = recorded.included_oracle_reads(); + let replayed = self.replay(&record, &included, Oracle::Recorded); + assert_same_run(&self.name, &recorded, &replayed); + assert!(replayed.oracle_replayed_exactly, "{}: the oracle reads were replayed", self.name); + + let channel = self.replay_channels(&recorded, Oracle::Recorded); + let name = format!("{} (channel witness)", self.name); + assert_same_run(&name, &recorded, &channel); + assert!(channel.oracle_replayed_exactly, "{name}: the oracle reads were replayed"); + assert_commits_the_block(&format!("{} (replay)", self.name), &replayed); + assert_commits_the_block(&name, &channel); + + assert_eq!( + recorded.executed_oracle_reads, recorded.record.oracle_reads, + "{}: the engine's oracle records are the service's view of every execution", + self.name + ); + // A capacity below the minimum bucket fails its lookup as an error does. + let valid = |answer: &Result| { + answer.as_ref().is_ok_and(|capacity| *capacity >= MIN_BUCKET_SIZE as u64) + }; + assert_eq!( + recorded.bucket_ids, + recorded + .record + .buckets + .iter() + .filter_map(|(id, answer)| valid(answer).then_some(*id)) + .collect::>(), + "{}: the exported buckets are the SALT lookups the environment answered with a valid \ + capacity", + self.name + ); + assert_eq!( + recorded.block_hashes, recorded.record.block_hashes, + "{}: the exported block hashes are the block-hash reads the block made", + self.name + ); + Replay { recorded, replayed, channel } + } + + /// Runs the block on `state` with the environments `factory` makes, executing the candidates + /// `include` admits and committing those the builder does not drop; `executed` is told each + /// candidate's index once its execution returned, whatever it returned. + fn drive( + &self, + mut state: State, + factory: F, + include: impl Fn(usize) -> bool, + executed: impl Fn(usize), + ) -> Run + where + DB: Database + Debug, + F: ExternalEnvFactory, + { + let committed = CommittedStates::install(&mut state); + let evm = MegaEvmFactory::new() + .with_external_env_factory(factory) + .create_evm(&mut state, self.env.clone()); + let mut executor = MegaBlockExecutor::new( + evm, + self.ctx.clone(), + self.spec.clone(), + OpAlloyReceiptBuilder::default(), + ); + if let Some(limits) = self.limits { + executor = executor.with_protocol_limits(limits); + } + executor.apply_pre_execution_changes().expect("the block starts"); + let pre_block = committed.states(); + let mut txs = Vec::new(); + let mut executed_oracle_reads = Vec::new(); + for (index, tx) in self.txs.iter().enumerate() { + if !include(index) { + txs.push(Err(NOT_INCLUDED.into())); + continue; + } + let outcome = executor.run_transaction(tx); + executed(index); + let outcome = match outcome { + Ok(outcome) => outcome, + Err(error) => { + txs.push(Err(error.to_string())); + continue; + } + }; + executed_oracle_reads.extend(outcome.inner.oracle_reads.iter().copied()); + if self.dropped.contains(&index) { + txs.push(Err(DROPPED.into())); + continue; + } + let snapshot = TxSnapshot { + tx_hash: outcome.tx_hash, + gas_limit: outcome.gas_limit, + tx_size: outcome.tx_size, + da_size: outcome.da_size, + da_footprint: outcome.da_footprint, + is_deposit: outcome.is_deposit, + depositor_nonce: outcome.depositor_nonce, + result: outcome.inner.result.clone(), + state: outcome.inner.state.clone(), + gas: outcome.inner.gas, + usage: outcome.inner.usage, + limit_exceeded: outcome.inner.limit_exceeded, + oracle_reads: outcome.inner.oracle_reads.clone(), + }; + match executor.commit_transaction_outcome(outcome) { + Ok(_) => txs.push(Ok(snapshot)), + Err(error) => txs.push(Err(error.to_string())), + } + } + let block_hashes = executor.get_accessed_block_hashes(); + let bucket_ids = executor.get_accessed_bucket_ids(); + let (evm, result) = executor.finish_with_counters().expect("the block finishes"); + drop(evm); + state.merge_transitions(BundleRetention::Reverts); + let committed = committed.states(); + let mut keys = WitnessKeys::default(); + for state in &committed { + keys.add_state(state); + } + Run { + pre_block, + committed, + txs, + receipts: result.inner.receipts, + gas_used: result.inner.gas_used, + blob_gas_used: result.inner.blob_gas_used, + gas: result.gas, + usage: result.usage, + bundle: state.take_bundle(), + cache: state.cache, + block_hashes, + bucket_ids, + keys, + executed_oracle_reads, + record: WitnessRecord::default(), + oracle_replayed_exactly: true, + } + } +} + +/// What one transaction of a run produced. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TxSnapshot { + pub tx_hash: B256, + pub gas_limit: u64, + pub tx_size: u64, + pub da_size: u64, + pub da_footprint: u64, + pub is_deposit: bool, + pub depositor_nonce: Option, + pub result: ExecutionResult, + pub state: EvmState, + pub gas: MegaGasUsage, + pub usage: LimitUsage, + pub limit_exceeded: Option, + /// The reads of the Oracle's storage the transaction recorded, with the service's answers. + pub oracle_reads: Vec, +} + +/// What one run of a block produced, and what it read. +#[derive(Clone, Debug)] +pub(crate) struct Run { + /// The states the pre-block steps committed, in order. + pub pre_block: Vec, + /// Every state the block committed, in order, as a node's commit hook receives them. + pub committed: Vec, + /// Each candidate's outcome when the block includes it, or why it does not: the refusal the + /// block answered it with, that the builder dropped it, or that a replay did not run it. + pub txs: Vec>, + pub receipts: Vec, + pub gas_used: u64, + pub blob_gas_used: u64, + pub gas: BlockGasCounters, + pub usage: LimitUsage, + /// The state changes the block committed, as a bundle. + pub bundle: BundleState, + /// The state cache after the block: everything loaded and committed. + pub cache: CacheState, + /// What the executor exported. + pub block_hashes: BTreeMap, + pub bucket_ids: Vec, + /// The keys the committed states name: a node's channel witness, before its values are + /// resolved. + pub keys: WitnessKeys, + /// The oracle reads every executed candidate recorded, dropped ones included, in execution + /// order: what the service saw. + pub executed_oracle_reads: Vec, + /// What the run read. + pub record: WitnessRecord, + /// Whether the replay's oracle service answered every recorded read in order. + pub oracle_replayed_exactly: bool, +} + +impl Run { + /// Which candidates the block included. + pub(crate) fn included(&self) -> Vec { + self.txs.iter().map(Result::is_ok).collect() + } + + /// The oracle reads the included transactions recorded, in block order: what a validator is + /// given in place of the service. + pub(crate) fn included_oracle_reads(&self) -> Vec { + self.txs.iter().flatten().flat_map(|tx| tx.oracle_reads.iter().copied()).collect() + } + + /// The outcomes of the included transactions, in block order. + fn included_outcomes(&self) -> Vec<&TxSnapshot> { + self.txs.iter().flatten().collect() + } + + /// The outcome of the transaction at `index`, which the block did not refuse. + pub(crate) fn tx(&self, index: usize) -> &TxSnapshot { + self.txs[index] + .as_ref() + .unwrap_or_else(|error| panic!("transaction {index} refused: {error}")) + } + + /// Why the transaction at `index` is not in the block. + pub(crate) fn refusal(&self, index: usize) -> &str { + match &self.txs[index] { + Ok(_) => panic!("transaction {index} was not refused"), + Err(error) => error, + } + } +} + +/// A recorded run and its two replays. +pub(crate) struct Replay { + pub recorded: Run, + /// The replay on the record of every database read. + pub replayed: Run, + /// The replay on the channel witness. + pub channel: Run, +} + +/// Asserts a replay `b` produced the block the recording `a` produced: the same pre-block +/// states, the same outcome for every included transaction, and the same receipts, header +/// figures, counters, state changes and exports. +/// +/// A candidate the block did not include was not run by the replay, so the two agree on which +/// those are and nothing more is compared for them. The recording's state cache and exports hold +/// what every execution loaded and asked about, dropped candidates' included, so they are equal +/// only when the block included every candidate; otherwise the replay's exports must be among +/// the recording's. The oracle reads a transaction recorded are the same reads on both runs, and +/// their answers are the service's, which a replay without a service does not have. +pub(crate) fn assert_same_run(name: &str, a: &Run, b: &Run) { + assert_eq!(a.pre_block, b.pre_block, "{name}: the pre-block states"); + assert_eq!(a.txs.len(), b.txs.len(), "{name}: the candidate count"); + for (index, (x, y)) in a.txs.iter().zip(&b.txs).enumerate() { + match (x, y) { + (Ok(x), Ok(y)) => { + assert_eq!(x.result, y.result, "{name}: transaction {index}'s result"); + assert_eq!(x.gas, y.gas, "{name}: transaction {index}'s gas ledgers"); + assert_eq!(x.usage, y.usage, "{name}: transaction {index}'s usage"); + assert_eq!( + x.limit_exceeded, y.limit_exceeded, + "{name}: transaction {index}'s stop" + ); + assert_eq!(x.state, y.state, "{name}: transaction {index}'s state"); + let slots = + |tx: &TxSnapshot| tx.oracle_reads.iter().map(|r| r.slot).collect::>(); + assert_eq!(slots(x), slots(y), "{name}: transaction {index}'s oracle reads"); + let (mut x, mut y) = (x.clone(), y.clone()); + x.oracle_reads.clear(); + y.oracle_reads.clear(); + assert_eq!(x, y, "{name}: transaction {index}"); + } + (Err(_), Err(_)) => {} + (x, y) => panic!("{name}: transaction {index}: {x:?} against {y:?}"), + } + } + assert_eq!(a.receipts, b.receipts, "{name}: the receipts"); + assert_eq!(a.gas_used, b.gas_used, "{name}: the block's gas used"); + assert_eq!(a.blob_gas_used, b.blob_gas_used, "{name}: the block's blob gas used"); + assert_eq!(a.gas, b.gas, "{name}: the block's ledgers"); + assert_eq!(a.usage, b.usage, "{name}: the block's usage"); + assert_eq!(a.bundle, b.bundle, "{name}: the state changes"); + if a.included().iter().all(|included| *included) { + assert_eq!(a.cache, b.cache, "{name}: the state cache"); + assert_eq!(a.block_hashes, b.block_hashes, "{name}: the exported block hashes"); + assert_eq!(a.bucket_ids, b.bucket_ids, "{name}: the exported buckets"); + } else { + assert!( + b.block_hashes.iter().all(|(number, hash)| a.block_hashes.get(number) == Some(hash)), + "{name}: the replay exported a block hash the recording did not" + ); + assert!( + b.bucket_ids.iter().all(|id| a.bucket_ids.contains(id)), + "{name}: the replay exported a bucket the recording did not" + ); + } +} + +/// Asserts what the run `a` committed, in order, is the block: its pre-block states, then each +/// included transaction's returned state, then the end of the block, whose balance increments +/// name no account on this chain. +fn assert_commits_the_block(name: &str, a: &Run) { + let mut expected = a.pre_block.clone(); + expected.extend(a.included_outcomes().into_iter().map(|tx| tx.state.clone())); + expected.push(EvmState::default()); + assert_eq!(a.committed, expected, "{name}: the committed states"); +} + +/// Asserts a replay differs from its recording somewhere in what the block produced: an included +/// transaction's outcome, the receipts, the gas used or the state changes. +pub(crate) fn assert_differs(name: &str, a: &Run, b: &Run) { + let same = a.pre_block == b.pre_block && + a.included_outcomes() == b.included_outcomes() && + a.receipts == b.receipts && + a.gas_used == b.gas_used && + a.bundle == b.bundle; + assert!(!same, "{name}: the replay produced the same block"); +} + +/* ---------- transactions ---------- */ + +/// A legacy transaction from `sender` at `nonce`, to `kind`, carrying `value` and `input`. +pub(crate) fn legacy_from( + sender: Address, + nonce: u64, + kind: TxKind, + value: U256, + input: Bytes, + gas_limit: u64, +) -> Tx { + common::legacy_from(sender, nonce, kind, value, input, gas_limit, 1_000_000) +} + +/// A legacy call from [`CALLER`] at `nonce` to `to` carrying `input`. +pub(crate) fn call(nonce: u64, to: Address, input: Bytes, gas_limit: u64) -> Tx { + legacy_from(CALLER, nonce, TxKind::Call(to), U256::ZERO, input, gas_limit) +} + +/// A legacy call from [`CALLER`] at `nonce` to `to` carrying `value` and `input`. +pub(crate) fn call_with_value( + nonce: u64, + to: Address, + value: U256, + input: Bytes, + gas_limit: u64, +) -> Tx { + legacy_from(CALLER, nonce, TxKind::Call(to), value, input, gas_limit) +} + +/// A creation from [`CALLER`] at `nonce` running `init_code`. +pub(crate) fn create(nonce: u64, init_code: Bytes, gas_limit: u64) -> Tx { + legacy_from(CALLER, nonce, TxKind::Create, U256::ZERO, init_code, gas_limit) +} + +/// A deposit from `from` to `to`, minting `mint` and carrying `value` and `input`. +pub(crate) fn deposit( + from: Address, + to: TxKind, + mint: u128, + value: U256, + input: Bytes, + gas_limit: u64, +) -> Tx { + let deposit = TxDeposit { + source_hash: B256::from(alloy_primitives::keccak256( + [from.as_slice(), &mint.to_be_bytes(), input.as_ref()].concat(), + )), + from, + to, + mint, + value, + gas_limit, + is_system_transaction: false, + input, + }; + let hash = B256::from(alloy_primitives::keccak256(deposit.source_hash)); + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(alloy_consensus::Sealed::new_unchecked(deposit, hash)), + from, + ) +} + +/// An EIP-7702 call from [`CALLER`] at `nonce` to `to` carrying `authorizations`. +pub(crate) fn eip7702( + nonce: u64, + to: Address, + input: Bytes, + authorizations: Vec, + gas_limit: u64, +) -> Tx { + let tx = TxEip7702 { + chain_id: CHAIN_ID, + nonce, + gas_limit, + max_fee_per_gas: 1_000_000, + max_priority_fee_per_gas: 0, + to, + value: U256::ZERO, + access_list: Default::default(), + authorization_list: authorizations, + input, + }; + let hash = B256::from(alloy_primitives::keccak256( + [CALLER.as_slice(), &nonce.to_be_bytes(), &[4u8]].concat(), + )); + Recovered::new_unchecked( + MegaTxEnvelope::Eip7702(Signed::new_unchecked(tx, Signature::test_signature(), hash)), + CALLER, + ) +} + +/// An authorization delegating whoever a fixed signature recovers to — the authority, answered +/// beside it — to `delegate` at `nonce`, valid on any chain. The signature is Nick's Method's: +/// `r = s = 0x2222…22`, over contents nobody holds the key of. +pub(crate) fn authorization(delegate: Address, nonce: u64) -> (SignedAuthorization, Address) { + let word = U256::from_be_bytes([0x22; 32]); + let signed = SignedAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: delegate, nonce }, + 0, + word, + word, + ); + let authority = signed.recover_authority().expect("a Nick's-Method signature recovers"); + (signed, authority) +} diff --git a/crates/mega-evm/tests/block/witness/history.rs b/crates/mega-evm/tests/block/witness/history.rs new file mode 100644 index 000000000..0e1874600 --- /dev/null +++ b/crates/mega-evm/tests/block/witness/history.rs @@ -0,0 +1,60 @@ +//! EIP-2935 and `BLOCKHASH` through the harness: the pre-block call writes the parent hash into +//! the history contract, a transaction reads two hashes inside the window and two outside it, and +//! the record and the executor's export hold exactly the two the database served. + +use alloy_eips::eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}; +use alloy_primitives::{Bytes, B256, U256}; +use mega_evm::{test_utils::BytecodeBuilder, BlockLimits, MegaBlockExecutionCtx}; +use revm::bytecode::opcode::{BLOCKHASH, POP}; + +use super::harness::{call, Case}; +use crate::common::{self, BLOCK_NUMBER, CONTRACT}; + +/// Code that reads the hashes of the four `numbers` and discards them. +fn reads(numbers: [u64; 4]) -> Bytes { + let mut code = BytecodeBuilder::default(); + for number in numbers { + code = code.push_number(number).append(BLOCKHASH).append(POP); + } + code.stop().build() +} + +/// The two reads inside the window are served and recorded; the current block and one 300 +/// blocks back are answered zero without a read; the EIP-2935 call's write is in the state +/// changes. +#[test] +fn test_block_hash_reads_replay() { + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code( + CONTRACT, + reads([BLOCK_NUMBER - 1, BLOCK_NUMBER - 2, BLOCK_NUMBER, BLOCK_NUMBER - 300]), + ); + let parent = B256::repeat_byte(0x29); + let replay = Case::new("block hashes", db) + .ctx(MegaBlockExecutionCtx::new( + parent, + Some(B256::ZERO), + Bytes::new(), + BlockLimits::no_limits(), + )) + .tx(call(0, CONTRACT, Bytes::new(), common::empty_call_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!( + run.record.block_hashes.keys().copied().collect::>(), + vec![BLOCK_NUMBER - 2, BLOCK_NUMBER - 1], + "only the reads inside the window reach the database" + ); + assert_eq!(run.block_hashes, run.record.block_hashes); + let ring_slot = + U256::from(BLOCK_NUMBER - 1) % U256::from(alloy_eips::eip2935::HISTORY_SERVE_WINDOW); + let written = run + .bundle + .state + .get(&HISTORY_STORAGE_ADDRESS) + .and_then(|account| account.storage.get(&ring_slot)) + .map(|slot| slot.present_value); + assert_eq!(written, Some(U256::from_be_bytes(parent.0)), "the parent hash was written"); +} diff --git a/crates/mega-evm/tests/block/witness/keyless.rs b/crates/mega-evm/tests/block/witness/keyless.rs new file mode 100644 index 000000000..01bf9a873 --- /dev/null +++ b/crates/mega-evm/tests/block/witness/keyless.rs @@ -0,0 +1,233 @@ +//! Keyless deployments through the harness: a deployment that succeeds, and one refused by each +//! rule that reads state — or refused before any read — replay from the witness, and the record +//! holds exactly the accounts each rule reached. + +use alloy_primitives::{hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + alloy_consensus::{Signed, TxLegacy}, + system::keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + test_utils::MemoryDatabase, +}; +use revm::{ + bytecode::opcode::{CODECOPY, PUSH0, RETURN, REVERT}, + context::result::ExecutionResult, +}; + +use super::harness::{call, call_with_value, Case, Run}; +use crate::common; + +/// A gas limit with room for the overhead, the creation, two new accounts and a small runtime's +/// deposit at any byte price the suite runs at. +const GAS: u64 = 20_000_000; + +/// A `gasLimitOverride` above what any transaction here can forward. +const LARGE_OVERRIDE: u64 = 10_000_000_000; + +/// A pre-EIP-155 signed creation, as Nick's Method makes one: a fixed signature over a +/// transaction nobody holds the key of, so the signer is whatever the contents recover to. +struct Deployment { + tx: Bytes, + signer: Address, + address: Address, +} + +impl Deployment { + /// A deployment of `init_code` carrying `value`, signed at nonce 0 with gas limit 1,000,000. + fn new(init_code: Bytes, value: U256) -> Self { + let tx = TxLegacy { + nonce: 0, + gas_price: 100_000_000_000, + gas_limit: 1_000_000, + to: TxKind::Create, + value, + input: init_code, + chain_id: None, + }; + let word = U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )); + let signed = Signed::new_unchecked(tx, Signature::new(word, word, false), B256::ZERO); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + let signer = signed.recover_signer().expect("a Nick's-Method signature recovers"); + Self { tx: encoded.into(), signer, address: signer.create(0) } + } + + /// The calldata of a `keylessDeploy` call deploying this. + fn call_data(&self) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: self.tx.clone(), + gasLimitOverride: U256::from(LARGE_OVERRIDE), + } + .abi_encode() + .into() + } +} + +/// Init code that runs `prefix`, then deploys `runtime`, which it copies from its own tail. +fn constructor(prefix: &[u8], runtime: &[u8]) -> Bytes { + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let tail = u16::try_from(prefix.len() + 11).expect("a short prefix").to_be_bytes(); + let mut code = prefix.to_vec(); + code.extend_from_slice(&[0x60, len, 0x61, tail[0], tail[1], PUSH0, CODECOPY]); + code.extend_from_slice(&[0x60, len, PUSH0, RETURN]); + code.extend_from_slice(runtime); + code.into() +} + +/// A runtime of five bytes that stops. +fn runtime() -> Vec { + vec![0x00; 5] +} + +/// The database every case starts from: the caller funded, and the predeploys as a chain that ran +/// Rex6 holds them. +fn db() -> MemoryDatabase { + common::database() +} + +/// What the `keylessDeploy` call at `index` returned, which the deployment succeeded or failed +/// in. +fn returned(run: &Run, index: usize) -> IKeylessDeploy::keylessDeployReturn { + let ExecutionResult::Success { output, .. } = &run.tx(index).result else { + panic!("the call did not succeed: {:?}", run.tx(index).result); + }; + IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()).expect("a return") +} + +/// The error the `keylessDeploy` call at `index` reverted with. +fn refused(run: &Run, index: usize) -> KeylessDeployError { + let ExecutionResult::Revert { output, .. } = &run.tx(index).result else { + panic!("the call did not revert: {:?}", run.tx(index).result); + }; + decode_error_result(output).expect("a keyless deploy error") +} + +/// A deployment that succeeds: the signer's and the deploy address's accounts are in the record +/// as absent, both buckets are exported, and the deployed code is in the block's state. +#[test] +fn test_a_keyless_deployment_replays() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::ZERO); + let replay = Case::new("keyless deployment", db()) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + let ret = returned(run, 0); + assert_eq!(ret.deployedAddress, deployment.address, "{:?}", ret.errorData); + assert_eq!(run.record.accounts.get(&deployment.signer), Some(&None), "the signer was read"); + assert_eq!(run.record.accounts.get(&deployment.address), Some(&None), "the address was read"); + if !common::state_is_free() { + assert_eq!(run.bucket_ids.len(), 2, "the signer's bucket and the deploy address's"); + } + assert!( + run.tx(0) + .state + .get(&deployment.address) + .is_some_and(|account| !account.info.is_empty_code_hash()), + "the code was deployed" + ); +} + +/// A call carrying value is refused before any read: neither the signer nor the deploy address +/// is in the record. +#[test] +fn test_a_value_bearing_keyless_call_reads_no_account() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::ZERO); + let replay = Case::new("keyless value", db()) + .tx(call_with_value(0, KEYLESS_DEPLOY_ADDRESS, U256::from(1), deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + assert_eq!(refused(run, 0), KeylessDeployError::NoEtherTransfer); + assert!(!run.record.accounts.contains_key(&deployment.signer), "no signer read"); + assert!(!run.record.accounts.contains_key(&deployment.address), "no deploy-address read"); + assert!(run.bucket_ids.is_empty(), "no charge was priced"); +} + +/// A signer whose nonce is too high is refused after the signer's account was read and before +/// the deploy address's is. +#[test] +fn test_a_signer_nonce_refusal_reads_the_signer_alone() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::ZERO); + let replay = Case::new("keyless signer nonce", db().account_nonce(deployment.signer, 2)) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + assert_eq!(refused(run, 0), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + assert!(run.record.accounts.contains_key(&deployment.signer), "the signer was read"); + assert!(!run.record.accounts.contains_key(&deployment.address), "the address was not"); + assert!(run.bucket_ids.is_empty(), "an existing signer's account is not charged"); +} + +/// A deploy address that holds code is refused after both accounts were read. +#[test] +fn test_an_occupied_deploy_address_refusal_reads_both_accounts() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::ZERO); + let db = db().account_code(deployment.address, Bytes::from(vec![0x00])); + let replay = Case::new("keyless occupied", db) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + assert_eq!(refused(run, 0), KeylessDeployError::ContractAlreadyExists); + assert!(run.record.accounts.contains_key(&deployment.signer)); + assert!(run.record.accounts.contains_key(&deployment.address)); +} + +/// A signer that cannot fund the deployment's value is refused after both accounts were read. +#[test] +fn test_an_insufficient_balance_refusal_replays() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::from(10)); + let replay = Case::new("keyless balance", db()) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + assert_eq!(refused(run, 0), KeylessDeployError::InsufficientBalance); + assert!(run.record.accounts.contains_key(&deployment.signer)); + assert!(run.record.accounts.contains_key(&deployment.address)); +} + +/// A constructor that reverts: the call succeeds with the failure in its return, and the signer's +/// nonce bump stands from 0 to 1. +#[test] +fn test_a_reverting_constructor_replays() { + let deployment = Deployment::new(constructor(&[PUSH0, PUSH0, REVERT], &runtime()), U256::ZERO); + let replay = Case::new("keyless revert", db()) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + let ret = returned(run, 0); + assert_eq!(ret.deployedAddress, Address::ZERO); + assert!(matches!( + decode_error_result(&ret.errorData), + Some(KeylessDeployError::ExecutionReverted { .. }) + )); + assert_eq!(run.tx(0).state[&deployment.signer].info.nonce, 1, "the bump stands"); +} + +/// Two deployments of one signer in one block: the second finds the address taken, having read +/// the state the first left in the block's cache rather than the witness. +#[test] +fn test_a_resubmission_in_the_same_block_is_refused() { + let deployment = Deployment::new(constructor(&[], &runtime()), U256::ZERO); + let replay = Case::new("keyless twice", db()) + .tx(call(0, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .tx(call(1, KEYLESS_DEPLOY_ADDRESS, deployment.call_data(), GAS)) + .run(); + let run = &replay.recorded; + assert_eq!(returned(run, 0).deployedAddress, deployment.address); + assert_eq!(refused(run, 1), KeylessDeployError::ContractAlreadyExists); +} + +/// A malformed call is refused before any read. +#[test] +fn test_a_malformed_keyless_call_reads_nothing() { + let data: Bytes = + IKeylessDeploy::keylessDeployCall::SELECTOR.iter().copied().chain([0xff_u8; 8]).collect(); + let replay = + Case::new("keyless malformed", db()).tx(call(0, KEYLESS_DEPLOY_ADDRESS, data, GAS)).run(); + let run = &replay.recorded; + assert_eq!(refused(run, 0), KeylessDeployError::MalformedEncoding); + assert!(run.bucket_ids.is_empty()); +} diff --git a/crates/mega-evm/tests/block/witness/mod.rs b/crates/mega-evm/tests/block/witness/mod.rs new file mode 100644 index 000000000..76b8c469f --- /dev/null +++ b/crates/mega-evm/tests/block/witness/mod.rs @@ -0,0 +1,16 @@ +//! A stateless validator re-executes a Satin block from a witness: what the block read, as the +//! chain held it. These tests execute blocks on a recorder of every read, replay them on a strict +//! database and environments that serve exactly the record, and hold the replay to the original +//! run — receipts, state changes, gas ledgers, logs, block counters and the executor's exports — +//! for each mechanism that reads, and for each read that gas or a limit can skip. + +mod basics; +mod harness; +mod history; +mod keyless; +mod oracle; +mod predeploys; +mod skips; +mod state; +mod stops; +mod system; diff --git a/crates/mega-evm/tests/block/witness/oracle.rs b/crates/mega-evm/tests/block/witness/oracle.rs new file mode 100644 index 000000000..e782230fc --- /dev/null +++ b/crates/mega-evm/tests/block/witness/oracle.rs @@ -0,0 +1,478 @@ +//! Oracle reads, hints and the high-precision timestamp through the harness. +//! +//! An oracle read loads the chain's slot, then takes the service's answer over it. The chain's +//! slot is in the record like any slot; the service's answer is not in any database, so a replay +//! matches only when it is given the answer — the included transactions' own records, in block +//! order — or when the chain holds it at the read, which is what a node must arrange for a +//! validator that runs no service, and can arrange only when every answer a transaction was given +//! is a value the slot can hold at that read: a transaction answered two values for one slot +//! replays from its record alone. + +use alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS; +use alloy_primitives::{address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{ + IOracle, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + }, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaHaltReason, OracleRead, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, INVALID, MLOAD, POP, PUSH0, SSTORE}, + context::result::ExecutionResult, +}; + +use super::harness::{ + assert_differs, assert_same_run, call, deposit, legacy_from, Case, Envs, Oracle, +}; +use crate::common::{self, CONTRACT}; + +/// The slot the tests read, the value the service answers, and the value the chain holds. +const SLOT: U256 = U256::from_limbs([42, 0, 0, 0]); +const SERVICE_VALUE: U256 = U256::from_limbs([0x1234_5678, 0, 0, 0]); +const STATE_VALUE: U256 = U256::from_limbs([0xfedc_ba98, 0, 0, 0]); + +/// A second slot, which a dropped candidate reads, and the value the service answers for it — +/// and answers a dropped candidate for [`SLOT`] before it moves on to [`SERVICE_VALUE`]. +const OTHER_SLOT: U256 = U256::from_limbs([43, 0, 0, 0]); +const OTHER_VALUE: U256 = U256::from_limbs([0x0bad_cafe, 0, 0, 0]); + +/// The service's read of [`SLOT`], as the engine records it. +const SLOT_READ: OracleRead = OracleRead { slot: SLOT, answer: Some(SERVICE_VALUE) }; + +/// The selector of the timestamp contract's `timestamp()`. +const TIMESTAMP_SELECTOR: [u8; 4] = [0xb8, 0x07, 0x77, 0xea]; + +/// A microsecond timestamp the service holds in the Oracle's slot 0. +const MICROSECONDS: U256 = U256::from_limbs([1_800_000_000_000_000, 0, 0, 0]); + +/// A chain holding the Oracle, as every chain does after its first Satin block: a block that +/// creates the Oracle clears its storage, and a created account's slots are known to be zero +/// without a read, so only a chain that already holds it reads the Oracle's slots. +pub(super) fn db() -> MemoryDatabase { + common::database().account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) +} + +/// A gas limit with room for a call into the Oracle carrying `calldata` bytes. +fn gas(calldata: u64) -> u64 { + 1_000_000 + common::body_history(calldata) +} + +/// The calldata of `getSlot(SLOT)`. +fn get_slot() -> Bytes { + get_slot_of(SLOT) +} + +/// The calldata of `getSlot(slot)`. +fn get_slot_of(slot: U256) -> Bytes { + IOracle::getSlotCall { slot }.abi_encode().into() +} + +/// A system transaction writing `value` into `slot` of the Oracle: a legacy call from the live +/// system address to `setSlot`, which the engine promotes to a deposit. Its gas is regular room +/// on top of the account the engine creates for its caller and the history its body would pay. +fn oracle_update(slot: U256, value: U256) -> super::harness::Tx { + let input = IOracle::setSlotCall { slot, value: B256::from(value) }.abi_encode(); + let gas = + 1_000_000 + common::new_account_state_gas() + common::body_history(input.len() as u64); + legacy_from( + MEGA_SYSTEM_ADDRESS, + 0, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + U256::ZERO, + input.into(), + gas, + ) +} + +/// The word a successful call returned. +fn returned(run: &super::harness::Run, index: usize) -> U256 { + let output = run.tx(index).result.output().cloned().unwrap_or_default(); + U256::from_be_slice(&output) +} + +/// A read the service answers over the chain's value: the read and its answer are in the record, +/// and so is the chain's slot; a replay given the answers matches, and one without a service +/// answers the chain's value and produces another block. +#[test] +fn test_an_oracle_read_replays_with_its_answer_and_not_without() { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE); + let case = Case::new("oracle read", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))); + let recorded = case.record(); + assert_eq!(returned(&recorded, 0), SERVICE_VALUE, "the service answered"); + assert_eq!(recorded.record.oracle_reads, vec![SLOT_READ]); + assert_eq!(recorded.tx(0).oracle_reads, vec![SLOT_READ], "and the transaction recorded it"); + assert_eq!( + recorded.record.storage.get(&(ORACLE_CONTRACT_ADDRESS, SLOT)), + Some(&STATE_VALUE), + "the chain's slot was loaded all the same" + ); + + let given = case.replay_channels(&recorded, Oracle::Recorded); + assert_same_run("oracle read, answers given", &recorded, &given); + + let without = case.replay_channels(&recorded, Oracle::Absent); + assert_eq!(returned(&without, 0), STATE_VALUE, "the chain's value stands in"); + assert_differs("oracle read, no service", &recorded, &without); + assert!(recorded.record.covers(&without.record), "it read nothing else"); +} + +/// When the chain holds what the service answers — the node wrote it before the read — a replay +/// without a service produces the same block: the read is priced cold on both paths and the slot +/// is loaded on both. +#[test] +fn test_an_oracle_read_the_chain_holds_replays_without_a_service() { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, SERVICE_VALUE); + let case = Case::new("oracle read on chain", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))); + let recorded = case.record(); + assert_eq!(recorded.record.oracle_reads, vec![SLOT_READ]); + let without = case.replay_channels(&recorded, Oracle::Absent); + assert_same_run("oracle read on chain, no service", &recorded, &without); +} + +/// A read the service does not answer takes the chain's value on both runs. +#[test] +fn test_an_unanswered_oracle_read_replays() { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE); + let replay = Case::new("oracle unanswered", db) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))) + .run(); + assert_eq!(returned(&replay.recorded, 0), STATE_VALUE); + assert_eq!(replay.recorded.record.oracle_reads, vec![OracleRead { slot: SLOT, answer: None }]); +} + +/// A deposit that failed keeps on its outcome the oracle reads its frames made: the failure takes +/// back everything but the sender's nonce bump and mint, not what the service answered, and a +/// validator re-executing the deposit makes the same reads. A deposit into a contract that reads +/// [`SLOT`] through the Oracle and then halts is included as a failed deposit that recorded the +/// read and its answer; the chain's slot is a key, and the channel replay is answered exactly +/// from the record. +#[test] +fn test_a_failed_deposits_oracle_read_is_recorded_and_replayed() { + let depositor = address!("0x4000000000000000000000000000000000000009"); + let read = get_slot(); + let read_then_halt = BytecodeBuilder::default() + .mstore(0, &read) + .append_many([PUSH0, PUSH0]) + .push_number(read.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP, INVALID]) + .build(); + let db = db().account_code(CONTRACT, read_then_halt).account_storage( + ORACLE_CONTRACT_ADDRESS, + SLOT, + STATE_VALUE, + ); + let replay = Case::new("a failed deposit that read the oracle", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(deposit( + depositor, + TxKind::Call(CONTRACT), + 1_000_000_000, + U256::ZERO, + Bytes::new(), + 1_000_000 + common::new_account_state_gas(), + )) + .run(); + let run = &replay.recorded; + assert!( + matches!( + run.tx(0).result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + run.tx(0).result + ); + assert_eq!(run.tx(0).oracle_reads, vec![SLOT_READ], "the read is on the failed deposit"); + assert!(run.keys.slots.contains(&(ORACLE_CONTRACT_ADDRESS, SLOT)), "the chain's slot is a key"); + assert!(replay.channel.oracle_replayed_exactly, "the replay was answered from the record"); +} + +/// The answers a validator replays are the included transactions' own, in block order, not the +/// service's view of every candidate: a candidate that read another slot and was dropped leaves +/// its read in the service's log and in no transaction's record. Given the included +/// transaction's record the replay matches; given the service's log it answers the wrong read +/// and computes another block. +#[test] +fn test_the_replayed_answers_are_the_included_transactions_own() { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE).account_storage( + ORACLE_CONTRACT_ADDRESS, + OTHER_SLOT, + STATE_VALUE, + ); + let case = Case::new("oracle read after a dropped candidate", db) + .envs( + Envs::new() + .with_oracle_storage(SLOT, SERVICE_VALUE) + .with_oracle_storage(OTHER_SLOT, OTHER_VALUE), + ) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot_of(OTHER_SLOT), gas(36))) + .dropped(0) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))); + let recorded = case.record(); + assert!(recorded.txs[0].is_err(), "the candidate was dropped"); + assert_eq!(returned(&recorded, 1), SERVICE_VALUE); + let other_read = OracleRead { slot: OTHER_SLOT, answer: Some(OTHER_VALUE) }; + assert_eq!(recorded.record.oracle_reads, vec![other_read, SLOT_READ], "the service saw both"); + assert_eq!(recorded.tx(1).oracle_reads, vec![SLOT_READ], "the included one recorded its own"); + assert_eq!(recorded.included_oracle_reads(), vec![SLOT_READ]); + + let own = case.replay_channels(&recorded, Oracle::Recorded); + assert_same_run("the included transaction's record", &recorded, &own); + assert!(own.oracle_replayed_exactly); + + // The service's log, replayed in order, answers the included transaction's read with the + // candidate's: a mismatch, which leaves the chain's value standing. + let log = case.replay(&recorded.record, &recorded.included(), Oracle::Recorded); + assert!(!log.oracle_replayed_exactly, "the log's first read is not the transaction's"); + assert_eq!(returned(&log, 1), STATE_VALUE); + assert_differs("the service's log", &recorded, &log); +} + +/// A dropped candidate that read the same slot as an included transaction, the service having +/// moved on between the two: its log holds both answers for the slot, in execution order, and +/// the included transaction's record holds its own. +/// +/// A validator given the included transaction's record replays the block. One handed the +/// service's log answers the included read with the candidate's answer — the slot is the same, so +/// no read is out of place, and only the answer left over tells — and computes another block. A +/// validator without a service depends on the slot alone: it computes the block when the journal +/// holds the included read's answer at the read, whatever the service answered before, and +/// another block when it holds the candidate's. +#[test] +fn test_a_dropped_read_of_the_same_slot_leaves_the_included_read_its_own_answer() { + let case = |chain_value: U256| { + Case::new( + "oracle read after a dropped read of the same slot", + db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, chain_value), + ) + .envs(Envs::new().with_oracle_storage(SLOT, OTHER_VALUE)) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))) + .dropped(0) + .service_answers_after(0, SLOT, SERVICE_VALUE) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))) + }; + let dropped_read = OracleRead { slot: SLOT, answer: Some(OTHER_VALUE) }; + + // The chain holds the answer the dropped candidate was given. + let stale = case(OTHER_VALUE); + let recorded = stale.record(); + assert!(recorded.txs[0].is_err(), "the candidate was dropped"); + assert_eq!(returned(&recorded, 1), SERVICE_VALUE, "the service had moved on"); + assert_eq!(recorded.record.oracle_reads, vec![dropped_read, SLOT_READ], "one slot, twice"); + assert_eq!(recorded.tx(1).oracle_reads, vec![SLOT_READ], "the included one recorded its own"); + assert_eq!(recorded.included_oracle_reads(), vec![SLOT_READ]); + + let own = stale.replay_channels(&recorded, Oracle::Recorded); + assert_same_run("the included transaction's record", &recorded, &own); + assert!(own.oracle_replayed_exactly); + + let mut witness = stale.channel_witness(&recorded); + witness.oracle_reads.clone_from(&recorded.record.oracle_reads); + let log = stale.replay(&witness, &recorded.included(), Oracle::Recorded); + assert_eq!(returned(&log, 1), OTHER_VALUE, "the candidate's answer, for the same slot"); + assert_eq!(log.tx(1).oracle_reads, vec![dropped_read]); + assert!(!log.oracle_replayed_exactly, "an answer was left over"); + assert_differs("the service's log", &recorded, &log); + + let without = stale.replay_channels(&recorded, Oracle::Absent); + assert_eq!(returned(&without, 1), OTHER_VALUE, "the slot holds the candidate's answer"); + assert_differs("no service, the candidate's answer in the slot", &recorded, &without); + + // The chain holds the answer the included transaction was given. + let held = case(SERVICE_VALUE); + let recorded = held.record(); + assert_eq!(recorded.record.oracle_reads, vec![dropped_read, SLOT_READ]); + assert_eq!(returned(&recorded, 1), SERVICE_VALUE); + let without = held.replay_channels(&recorded, Oracle::Absent); + assert_same_run("no service, the included answer in the slot", &recorded, &without); +} + +/// A validator without a service finds the answer in the slot only if an included transaction +/// wrote it there before the read: the node's oracle update, included, makes the replay match; +/// the same update executed and dropped leaves the chain's old value at the read, and the replay +/// without a service computes another block, while a replay given the read's record still +/// matches. +#[test] +fn test_a_validator_without_a_service_needs_the_included_update() { + let case = |dropped: bool| { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE); + let case = + Case::new(if dropped { "oracle update dropped" } else { "oracle update included" }, db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(oracle_update(SLOT, SERVICE_VALUE)) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))); + if dropped { + case.dropped(0) + } else { + case + } + }; + + let included = case(false); + let recorded = included.record(); + assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); + assert_eq!(returned(&recorded, 1), SERVICE_VALUE); + let written = &recorded.tx(0).state[&ORACLE_CONTRACT_ADDRESS].storage[&SLOT]; + assert_eq!(written.present_value, SERVICE_VALUE, "the update wrote the answer"); + let without = included.replay_channels(&recorded, Oracle::Absent); + assert_same_run("oracle update included, no service", &recorded, &without); + + let dropped = case(true); + let recorded = dropped.record(); + assert!(recorded.txs[0].is_err(), "the update was dropped"); + assert_eq!(returned(&recorded, 1), SERVICE_VALUE, "the service answered all the same"); + assert_eq!(recorded.tx(1).oracle_reads, vec![SLOT_READ]); + let given = dropped.replay_channels(&recorded, Oracle::Recorded); + assert_same_run("oracle update dropped, answers given", &recorded, &given); + let without = dropped.replay_channels(&recorded, Oracle::Absent); + assert_eq!(returned(&without, 1), STATE_VALUE, "the chain never held the answer"); + assert_differs("oracle update dropped, no service", &recorded, &without); +} + +/// Code that sends a hint naming `SLOT`, then reads `SLOT` through the Oracle and returns it. +fn hint_then_read() -> Bytes { + let hint = IOracle::sendHintCall { + topic: SLOT.into(), + data: Bytes::from(SERVICE_VALUE.to_be_bytes::<32>()), + } + .abi_encode(); + let read = get_slot(); + let mut code = BytecodeBuilder::default().mstore(0, &hint); + code = code + .append_many([PUSH0, PUSH0]) + .push_number(hint.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]); + code = code.mstore(0x100, &read); + code.push_number(32_u8) + .push_number(0x200_u16) + .push_number(read.len() as u64) + .push_number(0x100_u16) + .append(PUSH0) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + .push_number(32_u8) + .push_number(0x200_u16) + .append(revm::bytecode::opcode::RETURN) + .build() +} + +/// A hint followed by a read: the hint reaches the service and is in the record, in order before +/// the read, and the read's answer replays. +#[test] +fn test_a_hint_and_a_read_replay() { + let mut db = db(); + db.set_account_code(CONTRACT, hint_then_read()); + let replay = Case::new("hint then read", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(call(0, CONTRACT, Bytes::new(), 2_000_000 + common::body_history(0))) + .run(); + let run = &replay.recorded; + assert_eq!(returned(run, 0), SERVICE_VALUE); + assert_eq!(run.record.hints.len(), 1, "the hint reached the service"); + assert_eq!(run.record.hints[0].topic, B256::from(SLOT)); + assert_eq!(run.record.oracle_reads, vec![SLOT_READ]); +} + +/// The high-precision timestamp is an Oracle read of slot 0 through the wrapper's own bytecode: +/// the read is in the record, and the value the service answers replays. +#[test] +fn test_the_high_precision_timestamp_replays() { + let replay = Case::new("timestamp", db()) + .envs(Envs::new().with_oracle_storage(U256::ZERO, MICROSECONDS)) + .tx(call(0, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, TIMESTAMP_SELECTOR.into(), gas(4))) + .run(); + let run = &replay.recorded; + assert_eq!(returned(run, 0), MICROSECONDS, "{:?}", run.tx(0).result); + assert_eq!( + run.record.oracle_reads, + vec![OracleRead { slot: U256::ZERO, answer: Some(MICROSECONDS) }] + ); + assert!( + run.record.storage.contains_key(&(ORACLE_CONTRACT_ADDRESS, U256::ZERO)), + "the Oracle's slot 0 is loaded from the chain" + ); +} + +/// Code for the EIP-2935 address that reads the Oracle's [`SLOT`] and stores what it was told in +/// its own slot 0, so the pre-block call leaves the value it read in the state. +fn reads_the_oracle_and_stores_it() -> Bytes { + let read = get_slot(); + BytecodeBuilder::default() + .mstore(0, &read) + .push_number(32_u8) + .push_number(0x200_u16) + .push_number(read.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + .push_number(0x200_u16) + .append(MLOAD) + .append(PUSH0) + .append(SSTORE) + .stop() + .build() +} + +/// A pre-block system call is a function of the chain's state: an Oracle read it makes takes the +/// chain's slot and never asks the oracle service, whose answer no witness would carry. The block +/// replays from its witness with and without a service, and the service is never asked. +#[test] +fn test_a_pre_block_oracle_read_takes_chain_storage_and_replays() { + let case = || { + let mut db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE); + db.set_account_code(HISTORY_STORAGE_ADDRESS, reads_the_oracle_and_stores_it()); + Case::new("pre-block oracle read", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + }; + let replay = case().run(); + let run = &replay.recorded; + + let state = common::call_state(&run.pre_block, HISTORY_STORAGE_ADDRESS); + let stored = + state.get(&HISTORY_STORAGE_ADDRESS).expect("the contract wrote").storage.get(&U256::ZERO); + assert_eq!( + stored.map(|slot| slot.present_value), + Some(STATE_VALUE), + "chain storage, not the service" + ); + assert!(run.executed_oracle_reads.is_empty(), "the service was not asked"); + assert!(run.record.oracle_reads.is_empty()); + assert_eq!( + run.record.storage.get(&(ORACLE_CONTRACT_ADDRESS, SLOT)), + Some(&STATE_VALUE), + "the chain's slot is read, so it is in the witness" + ); + + let without = case().replay_channels(run, Oracle::Absent); + assert_same_run("pre-block oracle read, no service", run, &without); +} + +/// The system call's rule does not outlive it: a transaction of the same block that reads the +/// Oracle is answered by the service and records the read. +#[test] +fn test_a_pre_block_oracle_read_leaves_the_blocks_transactions_unchanged() { + let mut db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE); + db.set_account_code(HISTORY_STORAGE_ADDRESS, reads_the_oracle_and_stores_it()); + let replay = Case::new("pre-block read, then a transaction's", db) + .envs(Envs::new().with_oracle_storage(SLOT, SERVICE_VALUE)) + .tx(call(0, ORACLE_CONTRACT_ADDRESS, get_slot(), gas(36))) + .run(); + let run = &replay.recorded; + assert_eq!(returned(run, 0), SERVICE_VALUE, "the transaction is answered by the service"); + assert_eq!(run.tx(0).oracle_reads, vec![SLOT_READ]); + assert_eq!( + run.executed_oracle_reads, + vec![SLOT_READ], + "and it is the only read the service saw" + ); +} diff --git a/crates/mega-evm/tests/block/witness/predeploys.rs b/crates/mega-evm/tests/block/witness/predeploys.rs new file mode 100644 index 000000000..d56fb77cc --- /dev/null +++ b/crates/mega-evm/tests/block/witness/predeploys.rs @@ -0,0 +1,117 @@ +//! Satin's activation block, its check of the predeploys, and the EIP-7997 factory through the +//! harness. + +use alloy_primitives::{keccak256, Address, Bytes, U256}; +use mega_evm::system::{system_contract_specs, CREATE2_FACTORY_ADDRESS}; +use revm::{ + bytecode::opcode::{CODECOPY, PUSH0, RETURN}, + state::Account, +}; + +use super::{ + basics::{slot, slot_writer, write_gas}, + harness::{call, deposit, Case, Run}, + state::creation_gas, +}; +use crate::common::{self, CALLER, CONTRACT}; + +/// Init code that deploys a runtime of five bytes that stops. +fn init_code() -> Bytes { + let runtime = [0x00_u8; 5]; + let tail = 11_u16.to_be_bytes(); + let mut code = vec![0x60, 5, 0x61, tail[0], tail[1], PUSH0, CODECOPY, 0x60, 5, PUSH0, RETURN]; + code.extend_from_slice(&runtime); + code.into() +} + +/// The state the activation block's check committed for the predeploy at `address`. +fn check_state(run: &Run, address: Address) -> &Account { + let state = run + .pre_block + .iter() + .find(|state| common::is_predeploy_check(state) && state.contains_key(&address)) + .unwrap_or_else(|| panic!("{address} has a check state")); + &state[&address] +} + +/// A `CREATE2` through the EIP-7997 factory: the factory's code travels by hash, the created +/// account is priced through SALT, and the deployment replays. +#[test] +fn test_a_deployment_through_the_factory_replays() { + let mut input = vec![0x11_u8; 32]; + input.extend_from_slice(&init_code()); + let replay = Case::new("factory", common::database()) + .tx(call(0, CREATE2_FACTORY_ADDRESS, input.into(), creation_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + let output = run.tx(0).result.output().cloned().unwrap_or_default(); + let created = alloy_primitives::Address::from_slice(&output[output.len() - 20..]); + assert!(run.tx(0).state[&created].info.code.as_ref().is_some_and(|code| !code.is_empty())); + assert!(run.record.codes.contains_key(&mega_evm::system::CREATE2_FACTORY_CODE_HASH)); + if !common::state_is_free() { + assert!(!run.bucket_ids.is_empty(), "the created account was priced"); + } +} + +/// Satin's activation block over a chain shaped as Rex6 leaves it replays on both witnesses: it +/// admits deposits alone, so the deposit runs and the user transaction is refused, and its check +/// reads the seven predeploys, each with the chain's code hash, loads none of their code, and +/// commits each as a read-only entry. The witness built from those entries holds, for every +/// predeploy, the code the chain held, under its hash: no check loaded it, so it is there because +/// the account was named, resolved against the chain. +/// +/// An ordinary block over the same chain reads none of the predeploys the transactions do not +/// reach: no check state, and no record of their accounts. +/// +/// Rule [S22.4]. Expected values `independent`: the code is the bytecode the test put in the chain, +/// and its hash is computed here. +#[test] +fn test_an_activation_block_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let activation = || { + Case::new("activation block", db.clone()) + .ctx( + common::unlimited_ctx() + .with_no_user_tx_activation_block(true) + .with_satin_activation_block(true), + ) + .tx(deposit( + CALLER, + alloy_primitives::TxKind::Call(CONTRACT), + 0, + U256::ZERO, + slot(1), + write_gas(), + )) + .tx(call(0, CONTRACT, slot(2), write_gas())) + }; + let replay = activation().run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert!(run.refusal(1).contains("activation block"), "{}", run.refusal(1)); + let witness = activation().channel_witness(run); + for spec in system_contract_specs() { + let hash = keccak256(&spec.code); + let info = run.record.accounts.get(&spec.address).expect("read").as_ref().expect("held"); + assert_eq!(info.code_hash, hash, "{} was read with the chain's code hash", spec.address); + let entry = check_state(run, spec.address); + assert!(!entry.is_touched() && !entry.is_created(), "{} was only read", spec.address); + assert!(!run.record.codes.contains_key(&hash), "{}: the check loads no code", spec.address); + assert!( + witness.codes.get(&hash).is_some_and(|carried| carried.original_bytes() == spec.code), + "{}: the witness carries the code the chain held", + spec.address, + ); + } + + let replay = Case::new("ordinary block", db).tx(call(0, CONTRACT, slot(2), write_gas())).run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert!(!run.pre_block.iter().any(common::is_predeploy_check), "no check state"); + for spec in &system_contract_specs()[1..5] { + assert!(!run.record.accounts.contains_key(&spec.address), "{} was read", spec.address); + } + assert!(!run.record.accounts.contains_key(&CREATE2_FACTORY_ADDRESS), "the factory was read"); +} diff --git a/crates/mega-evm/tests/block/witness/skips.rs b/crates/mega-evm/tests/block/witness/skips.rs new file mode 100644 index 000000000..197c8350f --- /dev/null +++ b/crates/mega-evm/tests/block/witness/skips.rs @@ -0,0 +1,233 @@ +//! Reads that gas or a switch skips, through the harness: a cold `SLOAD` and a cold account load +//! with less gas than the cold surcharge, an oracle read the frame cannot pay, and reads a frame +//! that switched its volatile-data access off is refused. None reaches the database, none is in +//! the record, and the replay skips them the same way. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::BytecodeBuilder, + OracleRead, +}; +use revm::{ + bytecode::opcode::{BALANCE, BLOCKHASH, CALL, GAS, MSTORE, POP, PUSH0, RETURN, SLOAD}, + context::result::ExecutionResult, + context_interface::cfg::GasId, +}; + +use super::{ + harness::{call, Case}, + oracle::db as chain_with_oracle, +}; +use crate::common::{self, BLOCK_NUMBER, CONTRACT}; + +/// An account no transaction here funds or reads unless a cold load is made. +const STRANGER: Address = address!("0x5000000000000000000000000000000000000005"); + +/// The regular gas an empty call spends before its first instruction, at the byte prices in +/// effect: what a transaction to [`CONTRACT`] with empty code is billed on the regular ledger. +fn intrinsic() -> u64 { + let replay = Case::new("intrinsic probe", common::database()) + .tx(call(0, CONTRACT, Bytes::new(), common::empty_call_gas())) + .run(); + replay.recorded.tx(0).gas.regular +} + +/// A gas limit leaving the frame `room` of regular gas after the intrinsic cost and the body. +fn gas_with_room(room: u64) -> u64 { + intrinsic() + common::body_history(0) + room +} + +/// A cold `SLOAD` with less gas than its cold surcharge is skipped before the database is asked: +/// the slot is not in the record, the transaction runs out of gas, and the replay does the same. +#[test] +fn test_a_cold_sload_short_of_gas_reads_no_slot() { + let mut db = common::database(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().push_number(7_u8).append(SLOAD).stop().build(), + ); + let replay = Case::new("cold sload skipped", db) + .tx(call(0, CONTRACT, Bytes::new(), gas_with_room(3 + 2_000))) + .run(); + let run = &replay.recorded; + assert!(matches!(run.tx(0).result, ExecutionResult::Halt { .. }), "{:?}", run.tx(0).result); + assert!(!run.record.storage.contains_key(&(CONTRACT, U256::from(7)))); +} + +/// The same slot with the gas to pay for it is read and recorded. +#[test] +fn test_a_cold_sload_with_gas_reads_the_slot() { + let mut db = common::database(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().push_number(7_u8).append(SLOAD).stop().build(), + ); + let replay = Case::new("cold sload", db) + .tx(call(0, CONTRACT, Bytes::new(), gas_with_room(3 + 2_200))) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!(run.record.storage.get(&(CONTRACT, U256::from(7))), Some(&U256::ZERO)); +} + +/// A cold `BALANCE` with less gas than its cold surcharge loads no account. +#[test] +fn test_a_cold_account_load_short_of_gas_reads_no_account() { + // The push, and `BALANCE`'s static 100 leaves the cold surcharge short by that 100. + let cold = mega_evm::satin_gas_params().get(GasId::cold_account_additional_cost()); + let mut db = common::database(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().push_address(STRANGER).append(BALANCE).stop().build(), + ); + let replay = Case::new("cold balance skipped", db) + .tx(call(0, CONTRACT, Bytes::new(), gas_with_room(3 + cold))) + .run(); + let run = &replay.recorded; + assert!(matches!(run.tx(0).result, ExecutionResult::Halt { .. }), "{:?}", run.tx(0).result); + assert!(!run.record.accounts.contains_key(&STRANGER)); + + let mut db = common::database(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().push_address(STRANGER).append(BALANCE).stop().build(), + ); + let replay = Case::new("cold balance", db) + .tx(call(0, CONTRACT, Bytes::new(), gas_with_room(3 + 100 + cold + 100))) + .run(); + assert_eq!(replay.recorded.record.accounts.get(&STRANGER), Some(&None)); +} + +/// Code that calls the Oracle's `getSlot(42)` forwarding `gas` and returns whether the call +/// succeeded, as a word. +fn oracle_read_forwarding(gas: u64) -> Bytes { + let input = IOracle::getSlotCall { slot: U256::from(42) }.abi_encode(); + BytecodeBuilder::default() + .mstore(0, &input) + .append_many([PUSH0, PUSH0]) + .push_number(input.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(gas) + .append_many([CALL, PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// An oracle read the frame cannot pay is neither loaded nor asked: a call into the Oracle +/// forwarded less gas than a cold access fails, leaving the slot out of the record and the +/// service unasked, on a chain that holds the Oracle, so the slot would have been read from the +/// database otherwise. The gas is the call's own, set by its caller, so the frame is short of the +/// cold access whatever a byte costs. +#[test] +fn test_an_oracle_read_short_of_gas_asks_nothing() { + let case = |forwarded: u64| { + let mut db = chain_with_oracle(); + db.set_account_code(CONTRACT, oracle_read_forwarding(forwarded)); + Case::new("oracle short of gas", db) + .envs(super::harness::Envs::new().with_oracle_storage(U256::from(42), U256::from(1))) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + }; + let succeeded = |run: &super::harness::Run| { + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + U256::from_be_slice(run.tx(0).result.output().expect("the flag")) == U256::from(1) + }; + + let short = case(2_000).run(); + assert!(!succeeded(&short.recorded), "the call into the Oracle ran out of gas"); + assert!(short.recorded.record.oracle_reads.is_empty(), "the service was not asked"); + assert!(short.recorded.tx(0).oracle_reads.is_empty(), "and the transaction recorded no read"); + assert!(!short + .recorded + .record + .storage + .contains_key(&(ORACLE_CONTRACT_ADDRESS, U256::from(42)))); + + let enough = case(50_000).run(); + assert!(succeeded(&enough.recorded)); + assert_eq!( + enough.recorded.record.oracle_reads, + vec![OracleRead { slot: U256::from(42), answer: Some(U256::from(1)) }] + ); + assert!( + enough.recorded.record.storage.contains_key(&(ORACLE_CONTRACT_ADDRESS, U256::from(42))), + "with the gas, the slot is read from the database" + ); +} + +/// Code that switches its volatile-data access off, then runs `then`. +fn disabled_then(then: BytecodeBuilder) -> Bytes { + let disable = IMegaAccessControl::disableVolatileDataAccessCall {}.abi_encode(); + let code = BytecodeBuilder::default().mstore(0, &disable); + let code = code + .append_many([PUSH0, PUSH0]) + .push_number(disable.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ACCESS_CONTROL_ADDRESS) + .append_many([GAS, CALL, POP]); + let mut out = code.build().to_vec(); + out.extend_from_slice(&then.build()); + out.into() +} + +/// A refused `BLOCKHASH` reads no hash: the frame reverts, the record holds none and the export +/// is empty. +#[test] +fn test_a_refused_block_hash_read_reads_nothing() { + let mut db = common::database(); + let then = BytecodeBuilder::default() + .push_number(BLOCK_NUMBER - 1) + .append(BLOCKHASH) + .append(POP) + .stop(); + db.set_account_code(CONTRACT, disabled_then(then)); + let replay = Case::new("refused blockhash", db) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + .run(); + let run = &replay.recorded; + assert!(matches!(run.tx(0).result, ExecutionResult::Revert { .. }), "{:?}", run.tx(0).result); + assert!(run.record.block_hashes.is_empty()); + assert!(run.block_hashes.is_empty()); +} + +/// Code that reads slot 42 through the Oracle and stops. +fn read_slot_then_stop() -> BytecodeBuilder { + let read = IOracle::getSlotCall { slot: U256::from(42) }.abi_encode(); + let code = BytecodeBuilder::default().mstore(0, &read); + code.append_many([PUSH0, PUSH0]) + .push_number(read.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + .stop() +} + +/// A refused oracle read loads nothing and asks nothing, on a chain that holds the Oracle: the +/// same read with the frame's access on is loaded from the database and asked. +#[test] +fn test_a_refused_oracle_read_reads_nothing() { + let slot = (ORACLE_CONTRACT_ADDRESS, U256::from(42)); + let case = |name: &str, code: Bytes| { + let mut db = chain_with_oracle(); + db.set_account_code(CONTRACT, code); + Case::new(name, db) + .envs(super::harness::Envs::new().with_oracle_storage(U256::from(42), U256::from(1))) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000 + common::body_history(0))) + .run() + }; + + let refused = case("refused oracle read", disabled_then(read_slot_then_stop())); + let run = &refused.recorded; + assert!(run.tx(0).result.is_success(), "the outer frame survives the Oracle's revert"); + assert!(run.record.oracle_reads.is_empty()); + assert!(!run.record.storage.contains_key(&slot)); + + let allowed = case("allowed oracle read", read_slot_then_stop().build()); + let run = &allowed.recorded; + assert!(run.tx(0).result.is_success()); + assert_eq!(run.record.oracle_reads.len(), 1, "with access on, the service is asked"); + assert!(run.record.storage.contains_key(&slot), "and the slot is read from the database"); +} diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs new file mode 100644 index 000000000..f8300bc5c --- /dev/null +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -0,0 +1,552 @@ +//! State-changing mechanisms through the harness: an EIP-7702 delegation and its replacement, a +//! creation, the two shapes of `SELFDESTRUCT`, a value transfer that creates its recipient, and +//! deposits — with the L1 block info a user transaction is priced against, which the pre-block +//! phase carries, and which a block cannot start without. + +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor}, + EvmFactory, +}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + MegaBlockExecutor, MegaEvmFactory, +}; +use op_revm::constants::{ + BASE_FEE_SCALAR_OFFSET, BLOB_BASE_FEE_SCALAR_OFFSET, ECOTONE_L1_BLOB_BASE_FEE_SLOT, + ECOTONE_L1_FEE_SCALARS_SLOT, L1_BASE_FEE_SLOT, L1_BLOCK_CONTRACT, L1_FEE_RECIPIENT, + L1_OVERHEAD_SLOT, OPERATOR_FEE_RECIPIENT, OPERATOR_FEE_SCALARS_SLOT, +}; +use revm::{ + bytecode::opcode::{CODECOPY, PUSH0, RETURN}, + context_interface::cfg::GasId, + database::State, + state::{Account, AccountInfo, Bytecode}, +}; + +use super::{ + basics::{slot, slot_writer, write_gas}, + harness::{ + assert_same_run, authorization, call, call_with_value, create, deposit, eip7702, Case, + Oracle, Run, + }, +}; +use crate::{ + common::{self, CALLER, CONTRACT}, + rules::{l1_block_setter, scalars_word}, +}; + +/// An account that holds nothing. +const EMPTY: Address = address!("0x4000000000000000000000000000000000000004"); + +/// A contract that destroys itself to [`EMPTY`]. +const DESTROYER: Address = address!("0x4000000000000000000000000000000000000005"); + +/// A fresh depositor. +const DEPOSITOR: Address = address!("0x4000000000000000000000000000000000000006"); + +/// Init code that deploys `runtime`. +fn deploying(runtime: &[u8]) -> Bytes { + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let tail = 11_u16.to_be_bytes(); + let mut code = + vec![0x60, len, 0x61, tail[0], tail[1], PUSH0, CODECOPY, 0x60, len, PUSH0, RETURN]; + code.extend_from_slice(runtime); + code.into() +} + +/// A gas limit with room for a creation and two new accounts at the byte prices in effect: +/// 1,000,000 of regular gas on top of the state of two new accounts, a fresh slot and a short +/// runtime's deposit, a kilobyte of history beyond the body, and 64 times the history of two +/// write records — a contract that creates, or a factory that forwards all but a 64th of its gas +/// to the creation, pays the records of the frame it starts from the 64th it keeps. +pub(super) fn creation_gas() -> u64 { + 1_000_000 + + 2 * common::new_account_state_gas() + + common::slot_state_gas() + + 64 * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + + common::body_history(1_000) + + 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") +} + +/// An EIP-7702 call to an authority delegating to the slot writer: the authority's absent account +/// is in the record, it is created with its delegation, and its slot is written. +#[test] +fn test_a_delegation_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let (signed, authority) = authorization(CONTRACT, 0); + let replay = Case::new("delegation", db) + .tx(eip7702(0, authority, slot(5), vec![signed], creation_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!(run.record.accounts.get(&authority), Some(&None), "the authority was absent"); + let account = &run.tx(0).state[&authority]; + assert_eq!(account.info.nonce, 1, "the authorization bumped it"); + assert!(account.info.code.as_ref().is_some_and(|code| code.is_eip7702())); + assert!(account.storage.get(&U256::from(5)).is_some_and(|slot| slot.is_changed())); + if !common::state_is_free() { + assert!(!run.bucket_ids.is_empty(), "the authority's account and the slot were priced"); + } +} + +/// An authority the chain holds delegated to one contract is delegated anew: the engine loads +/// the delegation the chain holds to admit the authorization, and the returned state carries the +/// one the transaction wrote over it. The witness holds the authority's code as the chain held +/// it, which a witness built from the code the returned states carry would lack. +#[test] +fn test_a_replaced_delegation_replays_from_the_code_the_chain_held() { + let (signed, authority) = authorization(CONTRACT, 1); + let held = Bytecode::new_eip7702(EMPTY); + let written = Bytecode::new_eip7702(CONTRACT); + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + db.insert_account_info( + authority, + AccountInfo { + nonce: 1, + code_hash: held.hash_slow(), + code: Some(held.clone()), + ..Default::default() + }, + ); + let case = Case::new("replaced delegation", db).tx(eip7702( + 0, + authority, + slot(5), + vec![signed], + creation_gas(), + )); + + let recorded = case.record(); + assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); + let account = &recorded.tx(0).state[&authority]; + assert_eq!(account.info.nonce, 2, "the authorization was applied"); + assert_eq!(account.info.code.as_ref(), Some(&written), "the state carries the new delegation"); + assert!(account.storage.get(&U256::from(5)).is_some_and(|slot| slot.is_changed())); + assert_eq!( + recorded.record.codes.get(&held.hash_slow()), + Some(&held), + "the engine loaded the delegation the chain held" + ); + let witness = case.channel_witness(&recorded); + assert_eq!(witness.codes.get(&held.hash_slow()), Some(&held), "which the witness holds"); + assert!(!witness.codes.contains_key(&written.hash_slow()), "and not the one the block wrote"); + + case.run(); +} + +/// A creation transaction, then a call to what it created. +#[test] +fn test_a_creation_replays() { + let created = CALLER.create(0); + let replay = Case::new("creation", common::database()) + .tx(create(0, deploying(&[0x00; 5]), creation_gas())) + .tx(call(1, created, Bytes::new(), common::empty_call_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert!(run.tx(1).result.is_success(), "{:?}", run.tx(1).result); + assert_eq!(run.record.accounts.get(&created), Some(&None), "the created address was read"); + assert!( + !run.record.codes.values().any(|code| code.original_bytes() == vec![0x00; 5]), + "the created code came from the block, not the witness" + ); +} + +/// A `SELFDESTRUCT` of a pre-existing contract moves its balance to an empty account, which is +/// created and priced; and a contract created and destroyed in one transaction leaves nothing. +#[test] +fn test_selfdestructs_replay() { + let mut db = common::database(); + db.set_account_code(DESTROYER, BytecodeBuilder::default().selfdestruct(EMPTY).build()); + db.set_account_balance(DESTROYER, U256::from(1_000)); + let init = BytecodeBuilder::default().selfdestruct(EMPTY).build(); + db.set_account_code( + CONTRACT, + BytecodeBuilder::default().create(U256::ZERO, init).stop().build(), + ); + db.set_account_nonce(CONTRACT, 1); + let replay = Case::new("selfdestruct", db) + .tx(call(0, DESTROYER, Bytes::new(), creation_gas())) + .tx(call(1, CONTRACT, Bytes::new(), creation_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert_eq!(run.record.accounts.get(&EMPTY), Some(&None)); + assert_eq!(run.tx(0).state[&EMPTY].info.balance, U256::from(1_000)); + assert_eq!(run.tx(0).result.logs().len(), 1, "the transfer log"); + let created = CONTRACT.create(1); + assert!(run.tx(1).state[&created].is_selfdestructed()); +} + +/// A value transfer that creates its recipient: the recipient is absent in the record, created +/// in the state, priced through SALT, and its transfer log is in the receipt. +#[test] +fn test_a_transfer_creating_its_recipient_replays() { + let replay = Case::new("transfer", common::database()) + .tx(call_with_value(0, EMPTY, U256::from(7), Bytes::new(), creation_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!(run.record.accounts.get(&EMPTY), Some(&None)); + assert_eq!(run.receipts[0].logs().len(), 1, "the transfer log"); + if !common::state_is_free() { + assert_eq!(run.bucket_ids.len(), 1, "the recipient's bucket"); + } +} + +/// The L1 attributes depositor, whose deposit sets the L1 block info every block. +const L1_ATTRIBUTES_DEPOSITOR: Address = address!("0xDeaDDEaDDeAdDeAdDEAdDEaddeAddEAdDEAd0001"); + +/// The DA footprint gas scalar the chain holds before the block, and the one the block's L1 +/// attributes deposit writes. +const PARENT_FOOTPRINT_SCALAR: u16 = 400; +const BLOCK_FOOTPRINT_SCALAR: u16 = 800; + +/// The word the L1 block contract holds at its Ecotone fee-scalars slot: the base fee scalar and +/// the blob base fee scalar at the offsets the fork reads them from. +fn fee_scalars_word(base_fee_scalar: u32, blob_base_fee_scalar: u32) -> U256 { + let mut word = [0_u8; 32]; + word[BASE_FEE_SCALAR_OFFSET..BASE_FEE_SCALAR_OFFSET + 4] + .copy_from_slice(&base_fee_scalar.to_be_bytes()); + word[BLOB_BASE_FEE_SCALAR_OFFSET..BLOB_BASE_FEE_SCALAR_OFFSET + 4] + .copy_from_slice(&blob_base_fee_scalar.to_be_bytes()); + U256::from_be_bytes(word) +} + +/// The operator fee scalars word the chain holds before the block. +fn parent_scalars_word() -> U256 { + scalars_word(PARENT_FOOTPRINT_SCALAR, 5, 7) +} + +/// The L1 block info the chain holds before the block: a distinct non-zero value in every slot +/// the transactions are priced against, so a slot a witness answered with zero would show in the +/// L1 fee, the operator fee or the footprint. The Ecotone scalars are set, so the pricing does not +/// read the overhead, which the chain holds beside them ([`OVERHEAD`]). +fn l1_info() -> [(U256, U256); 4] { + [ + (L1_BASE_FEE_SLOT, U256::from(1_000_000_000_u64)), + (ECOTONE_L1_FEE_SCALARS_SLOT, fee_scalars_word(1_000_000, 1_000_000)), + (ECOTONE_L1_BLOB_BASE_FEE_SLOT, U256::from(1_000_000_000_u64)), + (OPERATOR_FEE_SCALARS_SLOT, parent_scalars_word()), + ] +} + +/// The L1 fee overhead the chain holds, which the pricing reads only when the scalars it finds +/// are empty, and the pre-block entry carries whatever they hold. +const OVERHEAD: U256 = U256::from_limbs([188, 0, 0, 0]); + +/// A chain holding the L1 block contract with `code`, the info of [`l1_info`] and the overhead, +/// and the slot writer at [`CONTRACT`]. +fn chain_with_l1_info(code: Bytes) -> MemoryDatabase { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + db.set_account_code(L1_BLOCK_CONTRACT, code); + for (slot, value) in l1_info() { + db.set_account_storage(L1_BLOCK_CONTRACT, slot, value); + } + db.set_account_storage(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, OVERHEAD); + db +} + +/// The L1 block info entry of a run's pre-block states: the last state the pre-block steps +/// committed, and the one entry in it. +fn l1_entry(run: &Run) -> &Account { + let state = run.pre_block.last().expect("a pre-block state"); + assert_eq!(state.len(), 1, "the L1 block contract alone"); + state.get(&L1_BLOCK_CONTRACT).expect("the L1 block info is the last state") +} + +/// A deposit minting to a fresh depositor: the depositor's absent account is read (for the +/// receipt's nonce and as the caller), created and priced, and the deposit writes its slot. A +/// block of deposits alone prices no transaction against the L1 block info; the pre-block phase +/// reads it all the same, here from a chain that does not hold the contract, which the entry +/// records as not existing without a slot read. +#[test] +fn test_a_deposit_only_block_replays_and_reads_no_l1_slot() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + // The first deposit also pays for the account the engine creates for its caller. + let replay = Case::new("deposits", db) + .tx(deposit( + DEPOSITOR, + TxKind::Call(CONTRACT), + 1_000_000_000, + U256::ZERO, + slot(9), + write_gas() + common::new_account_state_gas(), + )) + .tx(deposit(DEPOSITOR, TxKind::Call(CONTRACT), 0, U256::ZERO, slot(10), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert_eq!(run.tx(0).depositor_nonce, Some(0)); + assert_eq!(run.tx(1).depositor_nonce, Some(1), "the nonce the first deposit left"); + assert_eq!(run.record.accounts.get(&DEPOSITOR), Some(&None)); + assert!(l1_entry(run).is_loaded_as_not_existing(), "the chain holds no L1 block contract"); + assert_eq!(run.record.accounts.get(&L1_BLOCK_CONTRACT), Some(&None), "read once, pre-block"); + assert!( + !run.record.storage.keys().any(|(address, _)| *address == L1_BLOCK_CONTRACT), + "no slot of an absent contract is read" + ); + if !common::state_is_free() { + assert!(run.bucket_ids.len() >= 2, "the depositor's bucket and the slots'"); + } +} + +/// A user transaction is priced against the L1 block info, which is read on the database itself +/// and not through the transaction's journal: the L1 block contract is in no transaction's state, +/// and the pre-block phase carries its account and slots as read-only entries with the chain's +/// values, so a witness built from the states holds what the transaction's L1 fee, operator fee +/// and footprint were computed from. The entry holds the overhead beside them, which the pricing +/// does not read while the scalars are set: the pre-block read is the one read of it. +#[test] +fn test_a_user_transaction_is_priced_against_the_l1_info_the_pre_block_state_carries() { + let db = chain_with_l1_info(Bytes::from(vec![0x00])); + let replay = Case::new("l1 info", db).tx(call(0, CONTRACT, slot(1), write_gas())).run(); + let run = &replay.recorded; + let tx = run.tx(0); + assert!(tx.result.is_success(), "{:?}", tx.result); + assert!(!tx.state.contains_key(&L1_BLOCK_CONTRACT), "in no transaction's state"); + + let account = l1_entry(run); + assert!(!account.is_touched() && !account.is_created(), "a read-only entry"); + assert_eq!(account.info.code_hash, alloy_primitives::keccak256([0x00])); + let held = l1_info().into_iter().chain([(L1_OVERHEAD_SLOT, OVERHEAD)]); + assert_eq!(account.storage.len(), held.clone().count(), "the slots the pricing can read"); + for (slot, value) in held { + let entry = account.storage.get(&slot).expect("every slot of the set"); + assert_eq!(entry.present_value, value, "{slot}"); + assert!(!entry.is_changed(), "{slot} is unchanged"); + assert_eq!( + run.record.storage.get(&(L1_BLOCK_CONTRACT, slot)), + Some(&value), + "{slot} was read from the database, before the transactions" + ); + } + + let footprint_scalar = u64::from(PARENT_FOOTPRINT_SCALAR); + assert_eq!( + tx.da_footprint, + tx.da_size * footprint_scalar, + "the footprint the chain's scalar gives" + ); + let credited = |vault: Address| tx.state.get(&vault).map_or(U256::ZERO, |a| a.info.balance); + assert!(!credited(L1_FEE_RECIPIENT).is_zero(), "an L1 fee was paid from the info"); + assert!(!credited(OPERATOR_FEE_RECIPIENT).is_zero(), "an operator fee was paid from the info"); +} + +/// With the Ecotone scalars empty before the block the pricing reads the overhead at the first +/// transaction it prices; the pre-block entry holds the same five slots as with set scalars, the +/// overhead among them, and the block replays. +#[test] +fn test_the_overhead_is_in_the_entry_when_the_scalars_are_empty() { + let mut db = chain_with_l1_info(Bytes::from(vec![0x00])); + db.set_account_storage(L1_BLOCK_CONTRACT, ECOTONE_L1_FEE_SCALARS_SLOT, U256::ZERO); + let replay = Case::new("l1 overhead", db).tx(call(0, CONTRACT, slot(1), write_gas())).run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + let account = l1_entry(run); + assert_eq!(account.storage.len(), l1_info().len() + 1, "the same set as with set scalars"); + let overhead = account.storage.get(&L1_OVERHEAD_SLOT).expect("in the entry"); + assert_eq!(overhead.present_value, OVERHEAD); + assert!(!overhead.is_changed()); + assert_eq!(run.record.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), Some(&OVERHEAD)); +} + +/// The production shape: the L1 attributes deposit comes first and writes the block's info over +/// the parent's. The pre-block entry holds the parent's values, the deposit's own returned state +/// holds the write, and the transaction after the deposit is priced against the write; so +/// everything its footprint was computed from is in one of the block's states. +#[test] +fn test_the_l1_attributes_deposit_first_prices_the_transactions_after_it() { + let db = chain_with_l1_info(l1_block_setter()); + let word = scalars_word(BLOCK_FOOTPRINT_SCALAR, 9, 11); + let replay = Case::new("l1 attributes deposit first", db) + .tx(deposit( + L1_ATTRIBUTES_DEPOSITOR, + TxKind::Call(L1_BLOCK_CONTRACT), + 0, + U256::ZERO, + Bytes::from(word.to_be_bytes::<32>()), + 200_000 + common::new_account_state_gas(), + )) + .tx(call(0, CONTRACT, slot(1), write_gas())) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert!(run.tx(1).result.is_success(), "{:?}", run.tx(1).result); + + let before = l1_entry(run).storage.get(&OPERATOR_FEE_SCALARS_SLOT).expect("in the entry"); + assert_eq!(before.present_value, parent_scalars_word(), "the parent's info, pre-block"); + let written = &run.tx(0).state[&L1_BLOCK_CONTRACT].storage[&OPERATOR_FEE_SCALARS_SLOT]; + assert_eq!(written.original_value, parent_scalars_word()); + assert_eq!(written.present_value, word, "the deposit's state carries the write"); + assert_eq!(run.tx(0).da_footprint, 0, "a deposit has no footprint"); + + let tx = run.tx(1); + assert_eq!( + tx.da_footprint, + tx.da_size * u64::from(BLOCK_FOOTPRINT_SCALAR), + "priced against the deposit's write" + ); + assert_ne!(tx.da_footprint, tx.da_size * u64::from(PARENT_FOOTPRINT_SCALAR)); +} + +/// Code that empties the Ecotone fee scalars: a write to the L1 block contract, which the engine +/// accepts from a deposit like any other. +fn scalars_emptier() -> Bytes { + BytecodeBuilder::default().sstore(ECOTONE_L1_FEE_SCALARS_SLOT, U256::ZERO).stop().build() +} + +/// A block whose first transaction is a deposit that empties the Ecotone scalars, on a chain +/// that holds them set and holds `overhead`, followed by a user transaction. +fn scalars_emptied_in_the_block(overhead: U256) -> Case { + let mut db = chain_with_l1_info(scalars_emptier()); + db.set_account_storage(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT, overhead); + Case::new("scalars emptied in the block", db) + .tx(deposit( + L1_ATTRIBUTES_DEPOSITOR, + TxKind::Call(L1_BLOCK_CONTRACT), + 0, + U256::ZERO, + Bytes::new(), + 200_000 + common::new_account_state_gas(), + )) + .tx(call(0, CONTRACT, slot(1), write_gas())) +} + +/// The scalars are set before the block and a deposit empties them, so the L1 info the next +/// transaction is priced against is fetched with empty scalars and reads the overhead. No +/// transaction's state names that slot: the deposit wrote the scalars alone, and the fetch is not +/// in the user transaction's journal. The pre-block entry carries the overhead whatever the +/// scalars hold before the block, so the channel witness holds it and the block replays. +#[test] +fn test_a_deposit_emptying_the_scalars_leaves_the_overhead_in_the_witness() { + let case = scalars_emptied_in_the_block(OVERHEAD); + let recorded = case.record(); + assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); + assert!(recorded.tx(1).result.is_success(), "{:?}", recorded.tx(1).result); + + let written = &recorded.tx(0).state[&L1_BLOCK_CONTRACT].storage; + let scalars = &written[&ECOTONE_L1_FEE_SCALARS_SLOT]; + assert_eq!(scalars.original_value, fee_scalars_word(1_000_000, 1_000_000), "set before"); + assert_eq!(scalars.present_value, U256::ZERO, "the deposit emptied the scalars"); + assert!(!written.contains_key(&L1_OVERHEAD_SLOT), "the deposit's state names no overhead"); + let tx = recorded.tx(1); + assert!(!tx.state.contains_key(&L1_BLOCK_CONTRACT), "nor does the transaction after it"); + assert!( + tx.state.get(&L1_FEE_RECIPIENT).is_none_or(|vault| vault.info.balance.is_zero()), + "priced against the scalars the deposit left: no L1 fee" + ); + assert_eq!( + recorded.record.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), + Some(&OVERHEAD), + "the block read the overhead from the database" + ); + + let witness = case.channel_witness(&recorded); + let channel = case.replay(&witness, &recorded.included(), Oracle::Recorded); + assert!( + channel.txs[1].is_ok(), + "the transaction after the deposit replays from the channel witness: {:?}", + channel.txs[1].as_ref().err() + ); + assert_eq!( + witness.storage.get(&(L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT)), + Some(&OVERHEAD), + "which holds the overhead" + ); + let entry = l1_entry(&recorded).storage.get(&L1_OVERHEAD_SLOT).expect("in the entry"); + assert_eq!(entry.present_value, OVERHEAD, "named by the pre-block entry, with set scalars"); + + case.run(); +} + +/// The overhead is a slot the block must be able to read, and nothing more: the fee of a +/// transaction priced with empty scalars does not take it in, so the same block on a chain that +/// holds another overhead produces the same transactions, receipts and state changes. +#[test] +fn test_the_overhead_a_block_reads_decides_no_result() { + let held = scalars_emptied_in_the_block(OVERHEAD).run().recorded; + let zero = scalars_emptied_in_the_block(U256::ZERO).run().recorded; + assert_eq!(l1_entry(&held).storage[&L1_OVERHEAD_SLOT].present_value, OVERHEAD); + assert_eq!(l1_entry(&zero).storage[&L1_OVERHEAD_SLOT].present_value, U256::ZERO); + assert_eq!(held.txs, zero.txs, "the transactions"); + assert_eq!(held.receipts, zero.receipts, "the receipts"); + assert_eq!(held.bundle, zero.bundle, "the state changes"); + assert_eq!((held.gas_used, held.blob_gas_used), (zero.gas_used, zero.blob_gas_used)); +} + +/// The entry's other condition: a chain that does not hold the L1 block contract has it recorded +/// as not existing, with no slot. A deposit that creates the account in the block does not turn +/// its slots into database reads: the slots of an account the block created are the block's own, +/// so the transaction priced after the deposit reads none from the chain, and the witness, which +/// holds the account as absent and no slot of it, replays the block. +#[test] +fn test_a_deposit_creating_the_l1_block_contract_adds_no_slot_read() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let case = Case::new("L1 block contract created in the block", db) + .tx(deposit( + DEPOSITOR, + TxKind::Call(L1_BLOCK_CONTRACT), + 1_000, + U256::from(1_000), + Bytes::new(), + 200_000 + 2 * common::new_account_state_gas(), + )) + .tx(call(0, CONTRACT, slot(1), write_gas())); + let recorded = case.record(); + assert!(recorded.tx(0).result.is_success(), "{:?}", recorded.tx(0).result); + assert!(recorded.tx(1).result.is_success(), "{:?}", recorded.tx(1).result); + assert!(l1_entry(&recorded).is_loaded_as_not_existing(), "absent before the block"); + let created = &recorded.tx(0).state[&L1_BLOCK_CONTRACT]; + assert_eq!(created.info.balance, U256::from(1_000), "the deposit created the account"); + assert!( + !recorded.record.storage.keys().any(|(address, _)| *address == L1_BLOCK_CONTRACT), + "no slot of it is read from the database, before the deposit or after" + ); + + let witness = case.channel_witness(&recorded); + assert_eq!(witness.accounts.get(&L1_BLOCK_CONTRACT), Some(&None), "held as absent"); + assert!(!witness.storage.keys().any(|(address, _)| *address == L1_BLOCK_CONTRACT)); + let channel = case.replay(&witness, &recorded.included(), Oracle::Recorded); + assert_same_run("L1 block contract created in the block", &recorded, &channel); + + case.run(); +} + +/// The pre-block read of the L1 block info is made for every block, so a database that cannot +/// serve the contract's account, or one of the five slots of a contract the chain holds, cannot +/// start the block: the read fails before the first transaction, whatever the block holds — a +/// block of deposits alone, which prices nothing against the contract, included — and so does a +/// read of the overhead beside set scalars, which no transaction of the block would make. The +/// failure is the node's database's, not a verdict on the block: an internal error. +#[test] +fn test_a_database_that_cannot_serve_the_l1_entry_fails_the_block_as_internal() { + let refusals = [ + ("the account", Some(L1_BLOCK_CONTRACT), None), + ("the L1 base fee", None, Some((L1_BLOCK_CONTRACT, L1_BASE_FEE_SLOT))), + ("the overhead beside set scalars", None, Some((L1_BLOCK_CONTRACT, L1_OVERHEAD_SLOT))), + ]; + for (what, account, slot) in refusals { + let mut db = ErrorInjectingDatabase::new(chain_with_l1_info(Bytes::from(vec![0x00]))); + db.fail_on_account = account; + db.fail_on_storage = slot; + let mut state = State::builder().with_database(db).with_bundle_update().build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ); + let err = executor.apply_pre_execution_changes().expect_err(what); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{what}: {err:?}"); + assert!(err.to_string().contains(&L1_BLOCK_CONTRACT.to_string()), "{what}: {err}"); + } +} diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs new file mode 100644 index 000000000..388e1b066 --- /dev/null +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -0,0 +1,197 @@ +//! Every stop class through the harness: a transaction stopped by the data-size and compute +//! limits, a crossing at a precompile's price, which its caller catches, a crossing in an answer, +//! and a block budget refusing a later transaction. A stop is what the block records, so a +//! validator must produce the same stop from the same witness. + +use alloy_primitives::{Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + system::keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS}, + test_utils::BytecodeBuilder, + LimitCheck, LimitKind, TX_BODY_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, GAS, JUMP, JUMPDEST, LOG0, MCOPY, MSTORE, POP, PUSH0, RETURN, TIMESTAMP, + }, + context::result::ExecutionResult, +}; + +use super::{ + basics::{slot, slot_writer}, + harness::{call, call_with_value, Case, Run}, +}; +use crate::common::{self, loosest_tx, CALLER, CONTRACT}; + +/// Code that emits one log of `data_size` zero bytes. +fn logger(data_size: usize) -> Bytes { + BytecodeBuilder::default() + .push_number(data_size as u32) + .push_number(0_u8) + .append(LOG0) + .stop() + .build() +} + +/// A gas limit for a call to the logger of `data_size` bytes. +fn log_gas(data_size: usize) -> u64 { + 1_000_000 + + common::body_history(0) + + mega_evm::history_gas(mega_evm::log_history_bytes(0, data_size as u64)) + .expect("the log has a price") +} + +/// Code that reads the block's timestamp, then copies memory forever. +fn read_then_spin() -> Bytes { + let code = BytecodeBuilder::default().append_many([TIMESTAMP, POP]); + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(0x8000_u16) + .append_many([PUSH0, PUSH0, MCOPY]) + .push_number(dest) + .append(JUMP) + .build() +} + +/// Code that reads the block's timestamp, then calls `ecrecover` on 128 bytes of memory with +/// all its gas — a precompile priced at 3,000, more than a small cap leaves — and returns the +/// call's status. +fn read_then_ecrecover() -> Bytes { + BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .append_many([PUSH0, PUSH0]) + .push_number(128_u8) + .append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append_many([GAS, CALL, PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// The calldata of a `keylessDeploy` call the dispatch takes: its selector and bytes the value +/// rule refuses before they are decoded. +fn keyless_call() -> Bytes { + IKeylessDeploy::keylessDeployCall::SELECTOR.iter().copied().chain([0_u8; 8]).collect() +} + +/// The stop `kind` reports. +fn stop_kind(run: &Run, index: usize) -> LimitKind { + match run.tx(index).limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, .. }) => kind, + other => panic!("transaction {index} was not stopped: {other:?}"), + } +} + +/// The transaction at `index` is a stop of `kind`: a revert carrying the stop. +fn assert_stopped(run: &Run, index: usize, kind: LimitKind) { + assert!( + matches!(run.tx(index).result, ExecutionResult::Revert { .. }), + "{:?}", + run.tx(index).result + ); + assert_eq!(stop_kind(run, index), kind); +} + +/// A transaction stopped by the data-size limit. +#[test] +fn test_a_data_size_stop_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, logger(2_000)); + let limits = common::loosest() + .with_tx_runtime_limits(loosest_tx().with_tx_data_size_limit(TX_BODY_SIZE + 1_000)); + let replay = Case::new("data-size stop", db) + .limits(limits) + .tx(call(0, CONTRACT, Bytes::new(), log_gas(2_000))) + .run(); + assert_stopped(&replay.recorded, 0, LimitKind::DataSize); +} + +/// A transaction stopped by gas detention at the compute cap: a regular charge crossed the +/// withheld part. +#[test] +fn test_a_compute_stop_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, read_then_spin()); + let replay = + Case::new("compute stop", db).tx(call(0, CONTRACT, Bytes::new(), 29_000_000)).run(); + assert_stopped(&replay.recorded, 0, LimitKind::ComputeGas); +} + +/// A crossing decided at a precompile's price: after a read of the block's timestamp under a cap +/// of 1,000, `ecrecover`'s 3,000 is past the allowance and within the forward, so the call is +/// answered without running, with the stop, which its caller catches and returns as a failed +/// call's status. +#[test] +fn test_a_precompile_price_crossing_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, read_then_ecrecover()); + let limits = common::loosest() + .with_tx_runtime_limits(loosest_tx().with_block_env_access_compute_gas_limit(1_000)); + let replay = Case::new("precompile crossing", db) + .limits(limits) + .tx(call(0, CONTRACT, Bytes::new(), 1_000_000)) + .run(); + let caught = replay.recorded.tx(0); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&Bytes::from([0_u8; 32])), "the call was stopped"); + assert_eq!(caught.limit_exceeded, None); +} + +/// A crossing in an answer: a `keylessDeploy` call carrying value from the block beneficiary, +/// detained from its start under a cap of 1,000, spends the call's overhead in its refusal and +/// crosses there. +#[test] +fn test_an_answer_crossing_replays() { + let mut env = common::evm_env(); + env.block_env.beneficiary = CALLER; + let limits = common::loosest() + .with_tx_runtime_limits(loosest_tx().with_block_env_access_compute_gas_limit(1_000)); + let replay = Case::new("answer crossing", common::database()) + .env(env) + .limits(limits) + .tx(call_with_value(0, KEYLESS_DEPLOY_ADDRESS, U256::from(1), keyless_call(), 1_000_000)) + .run(); + assert_stopped(&replay.recorded, 0, LimitKind::ComputeGas); +} + +/// A block budget: the transaction that crosses the block's data-size limit is packed, and the +/// one after it is refused before it runs, on both runs alike. +#[test] +fn test_a_block_budget_refusal_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, logger(2_000)); + let limits = common::loosest().with_block_txs_data_limit(2_500); + let replay = Case::new("block budget", db) + .limits(limits) + .tx(call(0, CONTRACT, Bytes::new(), log_gas(2_000))) + .tx(call(1, CONTRACT, Bytes::new(), log_gas(2_000))) + .tx(call(2, CONTRACT, Bytes::new(), log_gas(2_000))) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success() && run.tx(1).result.is_success()); + assert!(run.refusal(2).contains("Block transactions data limit reached"), "{}", run.refusal(2)); + assert_eq!(run.receipts.len(), 2); +} + +/// A stop above the execution cap, where the reservoir paid the body: the same stop, the same +/// ledgers on replay. +#[test] +fn test_a_stop_above_the_execution_cap_replays() { + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + // Room for the calldata but not for the slot's write record. + let limits = common::loosest() + .with_tx_runtime_limits(loosest_tx().with_tx_data_size_limit(TX_BODY_SIZE + 32 + 10)); + let mut env = common::evm_env(); + env.block_env.gas_limit = TX_GAS_LIMIT_CAP + 100_000_000; + let replay = Case::new("stop above the cap", db) + .env(env) + .limits(limits) + .tx(call(0, CONTRACT, slot(1), TX_GAS_LIMIT_CAP + 50_000_000)) + .run(); + let run = &replay.recorded; + assert_stopped(run, 0, LimitKind::DataSize); + assert!(run.tx(0).gas.reservoir_remaining > 0, "the reservoir came back"); +} diff --git a/crates/mega-evm/tests/block/witness/system.rs b/crates/mega-evm/tests/block/witness/system.rs new file mode 100644 index 000000000..4bffa79be --- /dev/null +++ b/crates/mega-evm/tests/block/witness/system.rs @@ -0,0 +1,114 @@ +//! System transactions and the registry's rotation through the harness: a block that applies a +//! system-address change before its transactions, then runs a system transaction from the new +//! address and refuses one from the old, replays from its witness. + +use alloy_primitives::{address, keccak256, Address, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{ + storage_slots::{ + CURRENT_SEQUENCER, CURRENT_SYSTEM_ADDRESS, PENDING_SEQUENCER, PENDING_SYSTEM_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + }, + IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE, + }, + test_utils::MemoryDatabase, +}; + +use super::harness::{legacy_from, Case}; +use crate::common::{self, applies_pending_changes, BLOCK_NUMBER}; + +/// The system address a pending change rotates to. +const NEXT_SYSTEM_ADDRESS: Address = address!("0x3000000000000000000000000000000000000003"); + +/// A database holding a deployed registry naming [`MEGA_SYSTEM_ADDRESS`], with a system-address +/// change to [`NEXT_SYSTEM_ADDRESS`] due at `activation`. +fn registry_rotating_at(activation: u64) -> MemoryDatabase { + let mut db = common::database(); + db.set_account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE); + for (slot, value) in [ + (CURRENT_SYSTEM_ADDRESS, common::word(MEGA_SYSTEM_ADDRESS)), + (CURRENT_SEQUENCER, common::word(common::SEQUENCER)), + (PENDING_SYSTEM_ADDRESS, common::word(NEXT_SYSTEM_ADDRESS)), + (SYSTEM_ADDRESS_ACTIVATION_BLOCK, U256::from(activation)), + ] { + db.set_account_storage(SEQUENCER_REGISTRY_ADDRESS, slot, value); + } + db +} + +/// A legacy call from `sender` to the Oracle's `getSlot(0)`: a system transaction when `sender` +/// is the live system address, an ordinary one — from an account holding nothing — otherwise. +fn oracle_call_from(sender: Address) -> super::harness::Tx { + let input = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let gas = + 1_000_000 + common::new_account_state_gas() + common::body_history(input.len() as u64); + legacy_from( + sender, + 0, + alloy_primitives::TxKind::Call(ORACLE_CONTRACT_ADDRESS), + U256::ZERO, + input.into(), + gas, + ) +} + +/// The rotation is applied before the block's transactions, the new address's transaction runs +/// as the protocol's own, the old address's is refused, and the whole block replays: the +/// pending slots the decision read are in the record, and the live address the transaction read +/// is the one the block's own pre-block call wrote. +#[test] +fn test_a_rotation_and_a_system_transaction_replay() { + let replay = Case::new("rotation", registry_rotating_at(BLOCK_NUMBER)) + .tx(oracle_call_from(NEXT_SYSTEM_ADDRESS)) + .tx(oracle_call_from(MEGA_SYSTEM_ADDRESS)) + .run(); + let run = &replay.recorded; + assert!(applies_pending_changes(&run.pre_block), "the change was applied"); + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert_eq!(run.tx(0).gas.history, 0, "the protocol's own transaction pays no history"); + assert!(run.refusal(1).contains("lack of funds"), "{}", run.refusal(1)); + assert_eq!(run.receipts.len(), 1); + assert!(run.bucket_ids.is_empty(), "a system transaction prices at the minimum bucket"); + + let registry_slots = + |slot| run.record.storage.contains_key(&(SEQUENCER_REGISTRY_ADDRESS, slot)); + assert!(registry_slots(PENDING_SYSTEM_ADDRESS) && registry_slots(PENDING_SEQUENCER)); + assert!(registry_slots(SYSTEM_ADDRESS_ACTIVATION_BLOCK), "the due role's activation block"); + assert_eq!( + run.record.storage.get(&(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)), + Some(&common::word(MEGA_SYSTEM_ADDRESS)), + "the chain's live address, read by the call that rotated it; the transaction read the \ + rotated one from the block's own writes" + ); +} + +/// A system transaction in a block with nothing due reads the live address out of the witness: +/// the registry's account and its one slot are in the record and in the transaction's own state, +/// and the registry's code is not among the block's reads: the slot is read without it, so no +/// load the block made asked for it. That is what execution loads, not what a witness holds: a +/// witness holds the code the chain held for every account the block loads, the registry's +/// included, and this test asserts only the loads. +/// +/// Rule [S17.4]. Expected values `independent`: the registry's code hash is computed here from the +/// bytecode the test put in the chain. +#[test] +fn test_a_system_transaction_reads_the_live_address_from_the_witness() { + let replay = Case::new("system transaction", registry_rotating_at(BLOCK_NUMBER + 1)) + .tx(oracle_call_from(MEGA_SYSTEM_ADDRESS)) + .run(); + let run = &replay.recorded; + assert!(run.tx(0).result.is_success(), "{:?}", run.tx(0).result); + assert!(run.record.storage.contains_key(&(SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS))); + let registry = run.tx(0).state.get(&SEQUENCER_REGISTRY_ADDRESS).expect("the registry is read"); + assert!( + registry.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), + "the slot is in the transaction's state" + ); + assert!( + !run.record.codes.contains_key(&keccak256(SEQUENCER_REGISTRY_CODE)), + "the registry's code was never loaded" + ); + assert!(!applies_pending_changes(&run.pre_block), "nothing was due"); +} diff --git a/crates/mega-evm/tests/fuzz/blocks.rs b/crates/mega-evm/tests/fuzz/blocks.rs new file mode 100644 index 000000000..5adf9a2b0 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/blocks.rs @@ -0,0 +1,534 @@ +//! Blocks: several random transactions through `MegaBlockExecutor`, under random `ProtocolLimits` +//! in place of the spec's and a random building policy, with the block's admission rules restated +//! and its counters summed. +//! +//! Every transaction is built right before it runs, with its sender's live nonce, so a refusal +//! comes from the block's rules or the transaction's own validity and not from a stale nonce. + +use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxEip1559, TxEip2930, TxLegacy}; +use alloy_eips::eip2718::Encodable2718; +use alloy_evm::{ + block::{BlockExecutionError, BlockExecutor, BlockValidationError}, + Evm, EvmEnv, EvmFactory, +}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{keccak256, Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + test_utils::MemoryDatabase, BlockGasCounters, BlockLimiter, BlockLimits, LimitUsage, + MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, MegaTxEnvelope, + ProtocolLimits, WRITE_RECORD_SIZE, +}; +use op_alloy_consensus::TxDeposit; +use proptest::prelude::*; +use revm::{ + context::{transaction::AccessList, BlockEnv}, + database::State, + Database, +}; + +use crate::{ + gen::{ + case::{case, Case, Envs}, + tx::{GasTier, Price}, + value, who, Flavor, Value, Who, CALLER, CALLER2, CHAIN_ID, + }, + harness::{check, fail, prop_check, prop_eq}, +}; + +/// The number of cases the block properties run in the bounded mode. +const CASES: u32 = 256; + +/// The header's gas limit: room for an above-cap transaction and a few more. +const BLOCK_GAS_LIMIT: u64 = 300_000_000; + +/// Who sends a block's transaction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sender { + Caller, + Caller2, +} + +impl Sender { + const fn address(self) -> Address { + match self { + Self::Caller => CALLER, + Self::Caller2 => CALLER2, + } + } +} + +/// The envelope a block transaction takes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Envelope { + Legacy { to: Who }, + Eip1559 { to: Who }, + Eip2930 { to: Who, slots: u8 }, + Create, + Deposit { to: Who, mint: Value, create: bool }, +} + +/// One transaction of a block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BlockTx { + pub(crate) sender: Sender, + pub(crate) envelope: Envelope, + pub(crate) value: Value, + pub(crate) gas: GasTier, + pub(crate) price: Price, + pub(crate) data_len: u16, +} + +fn block_tx() -> impl Strategy { + let envelope = prop_oneof![ + 5 => who().prop_map(|to| Envelope::Legacy { to }), + 3 => who().prop_map(|to| Envelope::Eip1559 { to }), + 2 => (who(), 0u8..=3).prop_map(|(to, slots)| Envelope::Eip2930 { to, slots }), + 2 => Just(Envelope::Create), + 3 => (who(), value(), prop_oneof![4 => Just(false), 1 => Just(true)]) + .prop_map(|(to, mint, create)| Envelope::Deposit { to, mint, create }), + ]; + ( + prop_oneof![3 => Just(Sender::Caller), 1 => Just(Sender::Caller2)], + envelope, + value(), + prop_oneof![ + 1 => Just(GasTier::Tiny), + 4 => Just(GasTier::Small), + 4 => Just(GasTier::Medium), + 2 => Just(GasTier::Large), + 1 => Just(GasTier::AboveCap), + ], + prop_oneof![5 => Just(Price::Free), 2 => Just(Price::One), 1 => Just(Price::Dear)], + 0u16..=100, + ) + .prop_map(|(sender, envelope, value, gas, price, data_len)| BlockTx { + sender, + envelope, + value, + gas, + price, + data_len, + }) +} + +/// The block's protocol budget. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Budget { + Unlimited, + /// Crossed by the first transaction that spends anything on the dimension. + One, + /// A small number in the dimension's unit. + Small(u32), + /// A number a few transactions fit under. + Medium(u32), +} + +impl Budget { + fn value(self) -> u64 { + match self { + Self::Unlimited => u64::MAX, + Self::One => 1, + Self::Small(v) | Self::Medium(v) => u64::from(v), + } + } +} + +fn budget( + small: std::ops::RangeInclusive, + medium: std::ops::RangeInclusive, +) -> impl Strategy { + prop_oneof![ + 4 => Just(Budget::Unlimited), + 1 => Just(Budget::One), + 2 => small.prop_map(Budget::Small), + 2 => medium.prop_map(Budget::Medium), + ] +} + +/// The block's protocol budget and the builder's policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Budgets { + pub(crate) data: Budget, + /// The policy's cap on the same, which only tightens. + pub(crate) policy_data: Budget, + /// The policy's cap on a transaction's declared gas. + pub(crate) policy_tx_gas: Option, + /// The policy's cap on a transaction's encoded size, in bytes. + pub(crate) policy_tx_size: Option, + /// The policy's cap on the block's encoded size, in bytes. + pub(crate) policy_block_size: Option, +} + +fn budgets() -> impl Strategy { + ( + budget(300..=600, 1_000..=5_000), + budget(300..=600, 1_000..=5_000), + proptest::option::weighted( + 0.3, + prop_oneof![Just(100_000u32), Just(1_000_000), Just(50_000_000)], + ), + proptest::option::weighted(0.3, prop_oneof![Just(80u16), Just(150), Just(2_000)]), + proptest::option::weighted(0.3, prop_oneof![Just(200u16), Just(500), Just(5_000)]), + ) + .prop_map(|(data, pd, tx_gas, tx_size, block_size)| Budgets { + data, + policy_data: pd, + policy_tx_gas: tx_gas, + policy_tx_size: tx_size, + policy_block_size: block_size, + }) +} + +/// A block: a world with its programs (the case's transaction is not used), the transactions, the +/// budgets and the policy. +#[derive(Clone, Debug)] +pub(crate) struct BlockCase { + pub(crate) base: Case, + pub(crate) txs: Vec, + pub(crate) budgets: Budgets, +} + +pub(crate) fn block_case() -> impl Strategy { + (case(Flavor::Satin), proptest::collection::vec(block_tx(), 1..=6), budgets()) + .prop_map(|(base, txs, budgets)| BlockCase { base, txs, budgets }) +} + +impl BlockCase { + fn protocol(&self) -> ProtocolLimits { + ProtocolLimits { + tx_runtime_limits: self.base.world.limits.runtime(), + block_txs_data_limit: self.budgets.data.value(), + } + } + + fn policy(&self) -> BlockLimits { + let b = &self.budgets; + BlockLimits { + tx_gas_limit: b.policy_tx_gas.map_or(u64::MAX, u64::from), + tx_encode_size_limit: b.policy_tx_size.map_or(u64::MAX, u64::from), + block_txs_encode_size_limit: b.policy_block_size.map_or(u64::MAX, u64::from), + block_txs_data_limit: b.policy_data.value(), + ..BlockLimits::no_limits() + } + } + + fn spec(&self) -> MegaHardforkConfig { + MegaHardforkConfig::default().with_all_activated() + } + + fn block_env(&self) -> BlockEnv { + BlockEnv { gas_limit: BLOCK_GAS_LIMIT, ..self.base.block() } + } + + /// The state the block runs on: the case's pre-state with the second sender funded. + fn state(&self) -> State { + let mut db = self.base.database(); + db.set_account_balance(CALLER2, U256::from(10u64.pow(18))); + State::builder().with_database(db).build() + } + + /// The `index`th transaction as an envelope with its sender recovered, at `nonce`. + fn envelope(&self, index: usize, nonce: u64) -> Recovered { + let tx = &self.txs[index]; + let hash = keccak256((index as u64).to_be_bytes()); + let input: Bytes = vec![0xab; tx.data_len as usize].into(); + let init: Bytes = self.base.main.assemble().into(); + let gas_limit = tx.gas.limit(); + let value = tx.value.wei(); + let signature = Signature::test_signature(); + let envelope = match tx.envelope { + Envelope::Legacy { to } => MegaTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: tx.price.wei(), + gas_limit, + to: TxKind::Call(to.address()), + value, + input, + }, + signature, + hash, + )), + Envelope::Eip1559 { to } => MegaTxEnvelope::Eip1559(Signed::new_unchecked( + TxEip1559 { + chain_id: CHAIN_ID, + nonce, + gas_limit, + max_fee_per_gas: tx.price.wei(), + max_priority_fee_per_gas: tx.price.wei(), + to: TxKind::Call(to.address()), + value, + access_list: AccessList::default(), + input, + }, + signature, + hash, + )), + Envelope::Eip2930 { to, slots } => MegaTxEnvelope::Eip2930(Signed::new_unchecked( + TxEip2930 { + chain_id: CHAIN_ID, + nonce, + gas_price: tx.price.wei(), + gas_limit, + to: TxKind::Call(to.address()), + value, + access_list: AccessList(vec![alloy_eips::eip2930::AccessListItem { + address: to.address(), + storage_keys: (0..slots).map(B256::with_last_byte).collect(), + }]), + input, + }, + signature, + hash, + )), + Envelope::Create => MegaTxEnvelope::Legacy(Signed::new_unchecked( + TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: tx.price.wei(), + gas_limit, + to: TxKind::Create, + value, + input: init, + }, + signature, + hash, + )), + Envelope::Deposit { to, mint, create } => { + MegaTxEnvelope::Deposit(Sealed::new_unchecked( + TxDeposit { + source_hash: hash, + from: tx.sender.address(), + to: if create { TxKind::Create } else { TxKind::Call(to.address()) }, + mint: mint.wei().saturating_to(), + value, + gas_limit, + is_system_transaction: false, + input: if create { init } else { input }, + }, + hash, + )) + } + }; + Recovered::new_unchecked(envelope, tx.sender.address()) + } +} + +/// Whether the block admits a transaction of `gas_limit` and `tx_size` before it runs, by the +/// limiter's rules: a deposit is held to the header's gas limit alone; any other transaction to +/// the policy's per-transaction caps and to the data-size packing budget, which refuses the next +/// transaction once reached. +fn admits_before(limiter: &BlockLimiter, gas_limit: u64, tx_size: u64, is_deposit: bool) -> bool { + let limits = &limiter.limits; + if !is_deposit && gas_limit > limits.tx_gas_limit { + return false; + } + if limiter.block_gas_used.saturating_add(gas_limit) > limiter.block_gas_limit { + return false; + } + if is_deposit { + return true; + } + tx_size <= limits.tx_encode_size_limit && + tx_size.saturating_add(limiter.block_tx_size_used) <= limits.block_txs_encode_size_limit && + limiter.usage.data_size < limits.block_txs_data_limit +} + +/// Whether a refusal names a block or transaction limit rather than the transaction's validity: +/// `MegaETH`'s limit errors have no upstream `InvalidTransaction` counterpart, and the header's +/// gas limit has its own variant. +fn is_limit_refusal(error: &BlockExecutionError) -> bool { + match error { + BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) => { + error.as_invalid_tx_err().is_none() + } + BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. }, + ) => true, + _ => false, + } +} + +/// What running a block produced, rendered so two runs compare. +#[derive(Debug, Default)] +struct BlockRun { + committed: Vec, + refused: Vec<(usize, String)>, + gas: BlockGasCounters, + gas_used: u64, + usage: LimitUsage, + receipts: String, + accounts: String, +} + +/// Runs the block and checks the admission rules, the counters and the receipts along the way. +fn run_block(case: &BlockCase) -> Result { + let protocol = case.protocol(); + let envs: Envs = case.base.envs(); + let mut state = case.state(); + let mut cfg = revm::context::CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + let evm = MegaEvmFactory::new() + .with_external_env_factory(envs) + .create_evm(&mut state, EvmEnv::new(cfg, case.block_env())); + let ctx = MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), case.policy()); + let mut executor = + MegaBlockExecutor::new(evm, ctx, case.spec(), OpAlloyReceiptBuilder::default()) + .with_protocol_limits(protocol); + executor + .apply_pre_execution_changes() + .map_err(|error| fail(format!("the block does not start: {error:?}")))?; + + let mut run = BlockRun::default(); + let mut expected = BlockGasCounters::default(); + let mut expected_gas_used = 0u64; + let mut expected_usage = LimitUsage::default(); + for index in 0..case.txs.len() { + let sender = case.txs[index].sender.address(); + let nonce = executor + .evm_mut() + .db_mut() + .basic(sender) + .map_err(|error| fail(format!("{error:?}")))? + .map_or(0, |info| info.nonce); + let tx = case.envelope(index, nonce); + let is_deposit = matches!(case.txs[index].envelope, Envelope::Deposit { .. }); + let tx_size = tx.inner().encode_2718_len() as u64; + let gas_limit = case.txs[index].gas.limit(); + let admitted = admits_before(executor.limiter(), gas_limit, tx_size, is_deposit); + match executor.run_transaction(&tx) { + Ok(outcome) => { + prop_check!( + admitted, + "tx {index} ran though the block's rules refuse it\n{:?}", + executor.limiter() + ); + let gas = outcome.gas; + prop_check!( + outcome.usage.write_records * WRITE_RECORD_SIZE <= outcome.usage.data_size, + "tx {index}: KV x 40 within the data size" + ); + let logs = outcome.result.logs().to_vec(); + // What the transaction itself reports it kept, taken before the commit: the + // block's usage must be the sum of these, not a figure read back from the block. + let usage = outcome.usage; + match executor.commit_transaction_outcome(outcome) { + Ok(_) => { + expected.record(&gas); + expected_gas_used += gas.gas_used; + expected_usage.data_size += usage.data_size; + expected_usage.write_records += usage.write_records; + let receipt = executor + .receipts() + .last() + .expect("the committed transaction has a receipt"); + prop_eq!( + alloy_consensus::TxReceipt::cumulative_gas_used(receipt), + expected_gas_used, + "tx {index}: the receipt's cumulative gas is the running sum" + ); + prop_eq!( + alloy_consensus::TxReceipt::logs(receipt).to_vec(), + logs, + "tx {index}: the receipt's logs" + ); + run.committed.push(index); + } + Err(error) => { + // Nothing committed since it ran, so the block's counters are the ones it + // was admitted against. + return Err(fail(format!( + "tx {index} was refused at commit though it fits: {error:?}" + ))); + } + } + } + Err(error) => { + let message = format!("{error:?}"); + let on_a_limit = is_limit_refusal(&error); + if admitted { + prop_check!( + !on_a_limit, + "tx {index} was refused on a limit the rules do not name: {message}\n{:?}", + executor.limiter() + ); + } else { + prop_check!( + on_a_limit, + "tx {index} was refused for another reason than the rule: {message}" + ); + } + if is_deposit { + prop_check!( + !on_a_limit || message.contains("MoreThanAvailableBlockGas"), + "a deposit refused on a packing budget: {message}" + ); + } + run.refused.push((index, message)); + } + } + } + prop_eq!(*executor.gas(), expected, "the block's counters are the sum of its transactions'"); + prop_eq!( + executor.limiter().block_gas_used, + expected_gas_used, + "the block's gas used is its receipts' sum" + ); + prop_eq!( + executor.limiter().usage, + expected_usage, + "the block's usage is the sum of its transactions'" + ); + prop_eq!( + executor.receipts().len(), + run.committed.len(), + "one receipt per committed transaction" + ); + run.gas = *executor.gas(); + run.gas_used = executor.limiter().block_gas_used; + run.usage = executor.limiter().usage; + run.receipts = format!("{:?}", executor.receipts()); + let (_, result) = executor + .finish_with_counters() + .map_err(|error| fail(format!("the block does not finish: {error:?}")))?; + prop_eq!(result.gas, expected, "the finished block carries the counters"); + prop_eq!(result.gas_used, expected_gas_used, "the finished block carries the gas used"); + prop_eq!(result.usage, expected_usage, "the finished block carries the usage"); + for address in [ + CALLER, + CALLER2, + Who::Contract.address(), + Who::A.address(), + Who::B.address(), + Who::Fresh.address(), + case.base.world.beneficiary_address(), + ] { + let info = state.basic(address).map_err(|error| fail(format!("{error:?}")))?; + run.accounts.push_str(&format!("{address}: {info:?}\n")); + } + Ok(run) +} + +/// A block's counters are the sum of its committed transactions', its gas used the sum of its +/// receipts', and every budget holds as the block executor states it: a transaction runs only if +/// the packing budgets and the policy admit it, it commits once it ran, and a deposit is refused by +/// the header's gas limit alone. +#[test] +fn test_property_block_counters_and_budgets() { + check("block_counters_and_budgets", CASES, block_case, |case| { + run_block(case)?; + Ok(()) + }); +} + +/// The same block twice gives the same committed set, refusals, counters, receipts and accounts. +#[test] +fn test_property_block_determinism() { + check("block_determinism", CASES / 2, block_case, |case| { + let first = format!("{:?}", run_block(case)?); + let second = format!("{:?}", run_block(case)?); + prop_eq!(first, second, "two runs of the same block differ"); + Ok(()) + }); +} diff --git a/crates/mega-evm/tests/fuzz/differential.rs b/crates/mega-evm/tests/fuzz/differential.rs new file mode 100644 index 000000000..776bef5ff --- /dev/null +++ b/crates/mega-evm/tests/fuzz/differential.rs @@ -0,0 +1,252 @@ +//! The neutral differential: under the neutral configuration, `MegaEvm` must agree exactly with +//! the fork's op-revm on the same configuration, for priced transactions, and with revm's mainnet +//! EVM on the fork's spec, for unpriced ones, on random programs. +//! +//! The cases are the generators' in the neutral flavor: what only `MegaETH` has — the system +//! contracts and their interceptors, the Oracle's answers, the `SLOTNUM` opcode on the Osaka base +//! (a registered deviation of the execution-spec gate), keyless deployments and system-address +//! transactions — is replaced by its plain counterpart, because the references cannot express it. +//! The SALT environment is left out too, so every bucket is minimal, as the gate's runner has it. +//! Everything else is drawn from the same space as the properties. +//! +//! One thing more is taken out, for one arm on one fork. A contract destroyed in the transaction +//! that created it is settled on Amsterdam by EIP-8246, which Satin's Osaka base does not have: +//! the gate's other registered deviation. op-revm shares that base, and Ethereum on Osaka has the +//! same rule, so both are compared on the case as drawn. Ethereum on Amsterdam is compared on the +//! case with every self-destruction inside init code taken out +//! (`Case::without_destruction_in_creation`): the ending of a creation transaction's own init +//! code, of the init code a `CREATE` or `CREATE2` runs, and of the code either borrows through +//! `CALLCODE` or `DELEGATECALL`, which runs as the account being created. No case is skipped for +//! it, and the test prints how many it rewrote. +//! +//! op-revm's arm takes every transaction but a deposit from an account that does not exist yet: +//! Satin charges the account such a deposit creates for its caller, op-revm does not, and the +//! op-revm baseline (`tests/satin/equivalence.rs`) pins that divergence; under Amsterdam's +//! configuration, where state gas is on, the charge is there too. Ethereum has no deposits and +//! routes fees differently, so its arm takes the other transactions at a gas price of zero in a +//! block with no base fee, and op-revm's three fee vaults, touched empty, are taken out of +//! `MegaEvm`'s state before the two are compared, as `tests/satin/neutral.rs` does. +//! +//! Neither reference reads the live system address, which every Satin transaction does when it is +//! validated: the read-only entry it leaves in `MegaEvm`'s state is taken out before either +//! comparison, and taking it out fails when it is anything but the read. + +use std::sync::atomic::{AtomicU32, Ordering}; + +use alloy_op_evm::OpTx; +use mega_evm::{ + test_utils::{ + neutral_cfg, neutral_gas_table, neutralize_evm, take_system_address_read, + zero_fee_l1_block_info, MemoryDatabase, + }, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, +}; +use op_revm::{ + constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + L1BlockInfo, OpEvm, OpHaltReason, OpSpecId, OpTransaction, +}; +use revm::{ + context::{ + result::{ExecResultAndState, ExecutionResult}, + BlockEnv, CfgEnv, Context, ContextTr, TxEnv, + }, + handler::EvmTr, + inspector::NoOpInspector, + state::EvmState, + ExecuteEvm, Journal, MainBuilder, MainContext, +}; + +use crate::{ + gen::{ + case::{case, Case}, + Flavor, + }, + harness::{check, prop_eq, runs_at_measurement_prices}, + render::render_state, +}; + +type Outcome = ExecResultAndState, EvmState>; +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +const FORKS: [EthSpecId; 2] = [EthSpecId::OSAKA, EthSpecId::AMSTERDAM]; + +/// The number of cases each differential runs in the bounded mode, each on both forks. +const CASES: u32 = 512; + +/// An outcome or a refusal, rendered so two engines' compare: the result with its gas, logs and +/// output, and the state sorted. +fn render(outcome: &Result) -> String { + match outcome { + Ok(outcome) => { + format!("result: {:?}\nstate:\n{}", outcome.result, render_state(&outcome.state)) + } + Err(error) => format!("refused: {error}\n"), + } +} + +/// Runs `case` through a neutral `MegaEvm` for `fork`, in `block`, without a SALT environment, +/// and returns the outcome and the configuration it ran on. +fn run_mega( + fork: EthSpecId, + case: &Case, + block: BlockEnv, + tx: OpTransaction, +) -> (Result, CfgEnv) { + let ctx = MegaContext::new(case.database(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block) + .with_chain(zero_fee_l1_block_info()); + let cfg = ctx.cfg().clone(); + let mut mega = MegaEvm::new(ctx); + neutralize_evm(&mut mega, fork).expect("a neutral fork"); + let outcome = mega + .execute_transaction(OpTx(tx)) + .map(|outcome| { + let mut state = outcome.result_and_state.state; + take_system_address_read(&mut state); + ExecResultAndState::new(outcome.result_and_state.result, state) + }) + .map_err(|error| format!("{error}")); + (outcome, cfg) +} + +/// Runs `tx` through op-revm's `OpEvm` on `cfg`, the configuration the neutral `MegaEvm` ran on, +/// with `fork`'s static opcode prices installed: op-revm's Karst base carries Osaka's, and +/// Amsterdam raises `EXTCODESIZE`'s and `EXTCODECOPY`'s, which the neutral `MegaEvm` carries as +/// Ethereum does. +fn run_op( + case: &Case, + fork: EthSpecId, + cfg: CfgEnv, + block: BlockEnv, + tx: OpTransaction, +) -> Result { + let op_ctx = OpContext::new(case.database(), OpSpecId::KARST) + .with_cfg(cfg) + .with_block(block) + .with_chain(zero_fee_l1_block_info()); + let mut op = OpEvm::new(op_ctx, NoOpInspector); + let (_, instructions, _, _) = op.0.all_mut(); + *instructions.gas_table_mut() = neutral_gas_table(fork).expect("a neutral fork"); + op.transact(tx).map_err(|error| format!("{error}")) +} + +/// Runs `tx` through revm's mainnet EVM on `fork`'s spec. +fn run_eth(case: &Case, fork: EthSpecId, block: BlockEnv, tx: TxEnv) -> Result { + let mut cfg = CfgEnv::new(); + cfg.set_spec_and_mainnet_gas_params(fork); + Context::mainnet() + .with_db(case.database()) + .with_cfg(cfg) + .with_block(block) + .build_mainnet() + .transact(tx) + .map(|outcome| { + ExecResultAndState::new( + outcome.result.map_haltreason(OpHaltReason::Base), + outcome.state, + ) + }) + .map_err(|error| format!("{error}")) +} + +/// Under the neutral configuration of each fork, `MegaEvm` and op-revm produce byte-identical +/// outcomes — the result, its gas, logs and output, and the state — or the same refusal, for +/// every transaction but a deposit that creates its caller's account. +#[test] +fn test_differential_neutral_mega_evm_matches_op_revm() { + let compared = AtomicU32::new(0); + check( + "differential_op_revm", + CASES, + || case(Flavor::Neutral), + |case| { + let caller = &case.world.caller; + let caller_is_empty = caller.nonce == 0 && + caller.balance == crate::gen::world::Balance::Zero && + case.world.delegation.is_none_or(|d| d.delegator != crate::gen::Who::Caller); + if case.tx.is_deposit() && caller_is_empty { + return Ok(()); + } + compared.fetch_add(1, Ordering::Relaxed); + for fork in FORKS { + let block = case.block(); + let tx = case.transaction().0; + let (mega, cfg) = run_mega(fork, case, block.clone(), tx.clone()); + let op = run_op(case, fork, cfg, block, tx); + prop_eq!(render(&mega), render(&op), "{fork:?}: MegaEvm and op-revm differ"); + } + Ok(()) + }, + ); + let compared = compared.load(Ordering::Relaxed); + // The coverage minimum binds at the spec's byte prices. A measurement build leaves it out: + // the count still stands, and a class those prices leave unreachable is allowed. + if !runs_at_measurement_prices() { + assert!(compared > 0, "no case was compared with op-revm"); + } +} + +/// Under the neutral configuration of each fork, an unpriced transaction that is not a deposit +/// produces on `MegaEvm` what revm's mainnet EVM produces on the fork, but for the three fee vaults +/// op-revm touches. On Amsterdam the case runs without the self-destructions its init codes held, +/// which EIP-8246 settles there and Satin's Osaka base does not have; on Osaka it runs as drawn. +#[test] +fn test_differential_neutral_mega_evm_matches_ethereum() { + let compared = AtomicU32::new(0); + let rewritten = AtomicU32::new(0); + check( + "differential_ethereum", + CASES, + || case(Flavor::Neutral), + |case| { + if case.tx.is_deposit() { + return Ok(()); + } + let on_amsterdam = case.without_destruction_in_creation(); + compared.fetch_add(1, Ordering::Relaxed); + if on_amsterdam != *case { + rewritten.fetch_add(1, Ordering::Relaxed); + } + for fork in FORKS { + let case = if fork == EthSpecId::AMSTERDAM { &on_amsterdam } else { case }; + let block = BlockEnv { basefee: 0, ..case.block() }; + let mut tx = case.transaction().0; + tx.base.gas_price = 0; + tx.base.gas_priority_fee = tx.base.gas_priority_fee.map(|_| 0); + let (mega, _) = run_mega(fork, case, block.clone(), tx.clone()); + let mega = mega.map(|mut outcome| { + for vault in [BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + if outcome.state.get(&vault).is_some_and(|account| account.is_empty()) { + outcome.state.remove(&vault); + } + } + outcome + }); + let eth = run_eth(case, fork, block, tx.base); + prop_eq!(render(&mega), render(ð), "{fork:?}: MegaEvm and Ethereum differ"); + } + Ok(()) + }, + ); + let compared = compared.load(Ordering::Relaxed); + let rewritten = rewritten.load(Ordering::Relaxed); + println!( + "differential_ethereum: {compared} cases compared on both forks, {rewritten} of them on \ + Amsterdam without the self-destruction their init code held" + ); + // The coverage minimums bind at the spec's byte prices. A measurement build leaves them out: + // the counts above still stand, and a class those prices leave unreachable is allowed. + if !runs_at_measurement_prices() { + assert!(compared > 0, "no case was compared with Ethereum"); + assert!(rewritten > 0, "no case was rewritten for Amsterdam"); + } +} diff --git a/crates/mega-evm/tests/fuzz/gen/case.rs b/crates/mega-evm/tests/fuzz/gen/case.rs new file mode 100644 index 000000000..7219172b9 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/gen/case.rs @@ -0,0 +1,328 @@ +//! A case: a world, a transaction into it and the programs of its contracts, and how it runs. + +use alloy_primitives::{Address, Bytes, B256, U256}; +use mega_evm::{ + test_utils::{zero_fee_l1_block_info, MemoryDatabase}, + ExternalEnvs, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, SaltEnv, + TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use proptest::prelude::*; +use revm::{ + context::{BlockEnv, CfgEnv}, + context_interface::block::BlobExcessGasAndPrice, + inspector::NoOpInspector, + interpreter::interpreter::EthInterpreter, + state::{AccountInfo, Bytecode}, + Inspector, +}; + +use super::{ + program::{program, Program}, + tx::{keyless_tx, tx, DeployAddress, Shape, SignerCode, Tx}, + world::{world, AccountShape, World}, + Flavor, Who, CHAIN_ID, SYSTEM_ADDRESS, +}; + +/// The external environments a case runs with: the SALT capacities and the Oracle's answers, +/// with an error type so a bucket can fail. +pub(crate) type Envs = TestExternalEnvs; + +/// A case. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Case { + pub(crate) world: World, + pub(crate) tx: Tx, + /// The program of the contract the transaction calls, or its init code. + pub(crate) main: Program, + /// `A`'s program. + pub(crate) a: Program, + /// `B`'s program. + pub(crate) b: Program, +} + +pub(crate) fn case(flavor: Flavor) -> impl Strategy { + (world(), tx(flavor), program(flavor), program(flavor), program(flavor)) + .prop_map(|(world, tx, main, a, b)| Case { world, tx, main, a, b }) +} + +/// A case whose transaction is a keyless deployment, for the property that holds one to its +/// rules: among every shape a bounded run draws too few of them to reach each rule. +pub(crate) fn keyless_case() -> impl Strategy { + let flavor = Flavor::Satin; + (world(), keyless_tx(), program(flavor), program(flavor), program(flavor)) + .prop_map(|(world, tx, main, a, b)| Case { world, tx, main, a, b }) +} + +/// How a case ran: the outcome, or the error the engine refused the transaction with. +pub(crate) type Execution = Result; + +impl Case { + /// The pre-state: the predeploys as a chain that ran Rex6 holds them, the registry naming the + /// system address, the fixed accounts with their programs, the delegation, and, for a keyless + /// deployment, its signer's account and what its deploy address holds. + pub(crate) fn database(&self) -> MemoryDatabase { + let mut db = MemoryDatabase::default().rex6_predeploys(SYSTEM_ADDRESS); + let world = &self.world; + install(&mut db, Who::Caller.address(), &world.caller, None); + install(&mut db, Who::Contract.address(), &world.contract, Some(self.main.assemble())); + install(&mut db, Who::A.address(), &world.a, Some(self.a.assemble())); + install(&mut db, Who::B.address(), &world.b, Some(self.b.assemble())); + db.set_account_balance(Who::Beneficiary.address(), world.beneficiary_balance.wei()); + if let Some(delegation) = world.delegation { + let address = delegation.delegator.address(); + let balance = db.basic_ref_balance(address); + let nonce = world.nonce_of(address); + let code = Bytecode::new_eip7702(delegation.delegate.address()); + db.insert_account_info( + address, + AccountInfo { + balance, + nonce, + code_hash: code.hash_slow(), + code: Some(code), + ..Default::default() + }, + ); + } + if world.system_nonce > 0 { + db.set_account_nonce(SYSTEM_ADDRESS, world.system_nonce as u64); + } + if let (Some(deployment), Shape::Keyless { signer, deploy_address, .. }) = + (self.tx.deployment(), &self.tx.shape) + { + if let Some(address) = deployment.signer.filter(|_| !signer.is_empty()) { + let code = match signer.code { + SignerCode::None => None, + SignerCode::Plain => Some(Bytecode::new_legacy(Bytes::from_static(&[0x00]))), + SignerCode::Delegates(who) => Some(Bytecode::new_eip7702(who.address())), + }; + db.insert_account_info( + address, + AccountInfo { + balance: if signer.funded { U256::from(10u64.pow(18)) } else { U256::ZERO }, + nonce: signer.nonce as u64, + code_hash: code + .as_ref() + .map_or(alloy_primitives::KECCAK256_EMPTY, Bytecode::hash_slow), + code, + ..Default::default() + }, + ); + } + if let Some(address) = deployment.deploy_address() { + match deploy_address { + DeployAddress::Empty => {} + DeployAddress::Code => { + db.set_account_code(address, Bytes::from_static(&[0x00])); + } + DeployAddress::Balance => db.set_account_balance(address, U256::from(1)), + DeployAddress::Nonce => db.set_account_nonce(address, 1), + } + } + } + db + } + + /// The SALT capacities and the Oracle's answers. + pub(crate) fn envs(&self) -> Envs { + let salt = &self.world.salt; + let mut envs = Envs::new() + .with_default_bucket_capacity(salt.default_multiplier as u64 * MIN_BUCKET_SIZE as u64); + for (who, m) in &salt.crowded_accounts { + envs = envs.with_bucket_capacity( + Envs::bucket_id_for_account(who.address()), + *m as u64 * MIN_BUCKET_SIZE as u64, + ); + } + for (who, slot, m) in &salt.crowded_slots { + envs = envs.with_bucket_capacity( + Envs::bucket_id_for_slot(who.address(), U256::from(*slot)), + *m as u64 * MIN_BUCKET_SIZE as u64, + ); + } + if let Some(who) = salt.failing_account { + envs = envs.with_failing_bucket( + Envs::bucket_id_for_account(who.address()), + "the bucket cannot be read".to_string(), + ); + } + for (slot, value) in &self.world.oracle { + envs = envs.with_oracle_storage(U256::from(*slot), value.u256()); + } + envs + } + + /// The block. + pub(crate) fn block(&self) -> BlockEnv { + let shape = self.world.block; + BlockEnv { + number: U256::from(300), + beneficiary: self.world.beneficiary_address(), + timestamp: U256::from(1_700_000_000u64), + gas_limit: 10_000_000_000, + basefee: shape.basefee, + prevrandao: Some(B256::repeat_byte(7)), + blob_excess_gas_and_price: shape + .blob + .then_some(BlobExcessGasAndPrice { excess_blob_gas: 0, blob_gasprice: 3 }), + slot_num: shape.slot_num, + ..Default::default() + } + } + + /// The configuration: the spec's, on the chain every case runs on. + pub(crate) fn cfg(&self) -> CfgEnv { + let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + cfg + } + + /// The transaction. + pub(crate) fn transaction(&self) -> MegaTransaction { + self.tx.build(&self.world, &self.main.assemble()) + } + + /// A Satin context over `db` with the case's environments, block, chain and limits. + pub(crate) fn context(&self, db: MemoryDatabase) -> MegaContext { + let envs = self.envs(); + MegaContext::new_with_external_envs( + db, + mega_evm::MegaSpecId::SATIN, + ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, + ) + .with_cfg(self.cfg()) + .with_block(self.block()) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(self.world.limits.runtime()) + } + + /// A fresh EVM over the case's pre-state. + pub(crate) fn evm(&self) -> MegaEvm { + MegaEvm::new(self.context(self.database())) + } + + /// Runs the transaction on a fresh EVM, without committing. + pub(crate) fn execute(&self) -> Execution { + Self::execute_on(&mut self.evm(), self.transaction()) + } + + /// Runs the transaction on a fresh EVM and hands the EVM back, for what its context and + /// environments recorded. + pub(crate) fn execute_with_evm( + &self, + ) -> (Execution, MegaEvm) { + let mut evm = self.evm(); + let execution = Self::execute_on(&mut evm, self.transaction()); + (execution, evm) + } + + /// Runs the transaction on a fresh EVM under `inspector`, and hands the EVM back with what + /// the inspector recorded. + pub(crate) fn execute_inspected( + &self, + inspector: I, + ) -> (Execution, MegaEvm) + where + I: Inspector, EthInterpreter>, + { + let mut evm = self.evm().with_inspector(inspector); + let execution = Self::execute_on(&mut evm, self.transaction()); + (execution, evm) + } + + /// Runs `tx` on `evm`, without committing: the next transaction on it runs over the same + /// pre-state. + pub(crate) fn execute_on( + evm: &mut MegaEvm, + tx: MegaTransaction, + ) -> Execution + where + I: Inspector, EthInterpreter>, + { + evm.execute_transaction(tx).map_err(|error| format!("{error:?}")) + } + + /// The case with no self-destruction left inside init code: the init code of a creation + /// transaction, of a keyless deployment and of every creation the programs make can no longer + /// destroy the account it is creating, in its own code or in code it borrows through + /// `CALLCODE` or `DELEGATECALL` (see [`Program::into_init_without_destruction`]). A contract + /// that existed before the transaction still destroys itself. + /// + /// For the comparison with Ethereum on Amsterdam, where a contract destroyed in the + /// transaction that created it is settled by EIP-8246, which Satin's Osaka base does not have. + pub(crate) fn without_destruction_in_creation(&self) -> Self { + let is_creation = + matches!(self.tx.shape, Shape::Create | Shape::Deposit { create: true, .. }); + let main = self.main.clone(); + let mut tx = self.tx.clone(); + if let Shape::Keyless { init, .. } = &mut tx.shape { + *init = init.clone().without_destruction(); + } + Self { + world: self.world.clone(), + tx, + main: if is_creation { + main.into_init_without_destruction() + } else { + main.without_destruction_in_creations() + }, + a: self.a.clone().without_destruction_in_creations(), + b: self.b.clone().without_destruction_in_creations(), + } + } + + /// Whether a program of the case can send the Oracle a hint that is admitted and does not + /// decode ([`Program::calls_the_oracle_with_memory`]): counted as data size, as every admitted + /// hint is before it is decoded, and never forwarded. + pub(crate) fn may_send_a_hint_that_does_not_decode(&self) -> bool { + self.main.calls_the_oracle_with_memory() || + self.a.calls_the_oracle_with_memory() || + self.b.calls_the_oracle_with_memory() || + matches!(&self.tx.shape, Shape::Keyless { init: super::program::InitCode::Runs(program), .. } + if program.calls_the_oracle_with_memory()) + } + + /// Whether any program of the case, or any init code in them, destroys an account. + pub(crate) fn destroys(&self) -> bool { + self.main.destroys() || + self.a.destroys() || + self.b.destroys() || + matches!(&self.tx.shape, Shape::Keyless { init, .. } if init_destroys(init)) + } +} + +fn init_destroys(init: &super::program::InitCode) -> bool { + match init { + super::program::InitCode::Selfdestructs { .. } => true, + super::program::InitCode::Runs(program) => program.destroys(), + _ => false, + } +} + +/// Installs `account` at `address`, with `code` when it has any. +fn install( + db: &mut MemoryDatabase, + address: Address, + account: &AccountShape, + code: Option>, +) { + if let Some(code) = code.filter(|code| !code.is_empty()) { + db.set_account_code(address, Bytes::from(code)); + } + db.set_account_balance(address, account.balance.wei()); + db.set_account_nonce(address, account.nonce as u64); + for (slot, value) in &account.slots { + db.set_account_storage(address, U256::from(*slot), value.u256()); + } +} + +/// Reads a balance out of the cache database without loading it as a read. +trait BalanceRef { + fn basic_ref_balance(&mut self, address: Address) -> U256; +} + +impl BalanceRef for MemoryDatabase { + fn basic_ref_balance(&mut self, address: Address) -> U256 { + revm::Database::basic(self, address).unwrap_or_default().map_or(U256::ZERO, |a| a.balance) + } +} diff --git a/crates/mega-evm/tests/fuzz/gen/mod.rs b/crates/mega-evm/tests/fuzz/gen/mod.rs new file mode 100644 index 000000000..b0c224da9 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/gen/mod.rs @@ -0,0 +1,153 @@ +//! The generators every property draws its cases from. +//! +//! A case is a small world — a handful of accounts at fixed addresses, the system contracts, a +//! SALT environment, the Oracle's answers, a block and a set of runtime limits — a transaction +//! into it, and the programs of the three contracts the transaction can reach. Every part is a +//! plain value with a `Debug` rendering, so a minimal failing case prints as something a +//! regression test can be written from. +//! +//! The address universe is fixed on purpose: with the same few accounts in every case a random +//! program hits the interesting collisions — a call to the block beneficiary, a value transfer to +//! an account another frame destroyed, a creation onto an address a delegation points at — far +//! more often than random addresses would. +//! +//! [`Flavor`] narrows the space for the neutral differential, which compares `MegaEvm` with +//! op-revm and revm's mainnet EVM: what only `MegaETH` has — the system contracts, the Oracle's +//! answers, the `SLOTNUM` opcode on the Osaka base — is left out there, because the references +//! cannot express it. Nothing else is narrowed. + +pub(crate) mod case; +pub(crate) mod program; +pub(crate) mod tx; +pub(crate) mod world; + +use alloy_primitives::{address, Address, U256}; +use mega_evm::system::MEGA_SYSTEM_ADDRESS; +use proptest::prelude::*; + +/// Which space the generators draw from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Flavor { + /// Everything Satin runs: the whole space. + Satin, + /// What op-revm and revm's mainnet EVM run too: no system contract, no Oracle read, no + /// `SLOTNUM` (see the neutral differential). A self-destruction inside init code stays: the + /// differential takes it out where the reference settles it otherwise + /// (`Case::without_destruction_in_creation`). + Neutral, +} + +/// The sender of every user transaction. +pub(crate) const CALLER: Address = address!("00000000000000000000000000000000000fc000"); +/// A second sender, for blocks. +pub(crate) const CALLER2: Address = address!("00000000000000000000000000000000000fc002"); +/// The contract a call transaction targets: it runs the case's main program. +pub(crate) const CONTRACT: Address = address!("00000000000000000000000000000000000fc001"); +/// A contract the programs can call, running its own program. +pub(crate) const A: Address = address!("00000000000000000000000000000000000fca01"); +/// Another. +pub(crate) const B: Address = address!("00000000000000000000000000000000000fcb01"); +/// An address no account exists at before the transaction. +pub(crate) const FRESH: Address = address!("00000000000000000000000000000000000fcf01"); +/// The block beneficiary of a case that names a distinct one. +pub(crate) const BENEFICIARY: Address = address!("00000000000000000000000000000000000fbef0"); + +/// An account of the fixed universe. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Who { + Caller, + Contract, + A, + B, + Fresh, + Beneficiary, +} + +impl Who { + pub(crate) const ALL: [Self; 6] = + [Self::Caller, Self::Contract, Self::A, Self::B, Self::Fresh, Self::Beneficiary]; + + /// The account's address; the beneficiary's is the distinct one, whoever the case's block + /// names (see `World::beneficiary_address`). + pub(crate) const fn address(self) -> Address { + match self { + Self::Caller => CALLER, + Self::Contract => CONTRACT, + Self::A => A, + Self::B => B, + Self::Fresh => FRESH, + Self::Beneficiary => BENEFICIARY, + } + } +} + +pub(crate) fn who() -> impl Strategy { + proptest::sample::select(Who::ALL.as_slice()) +} + +/// An amount of wei a case moves. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Value { + Zero, + One, + /// A billion wei: below every funded balance. + Some, + /// More than any account holds. + Huge, +} + +impl Value { + pub(crate) fn wei(self) -> U256 { + match self { + Self::Zero => U256::ZERO, + Self::One => U256::from(1), + Self::Some => U256::from(1_000_000_000u64), + Self::Huge => U256::from(10u128.pow(30)), + } + } +} + +pub(crate) fn value() -> impl Strategy { + // More than any account holds refuses a transaction and fails a call: one in twenty-two. + prop_oneof![ + 10 => Just(Value::Zero), + 6 => Just(Value::One), + 5 => Just(Value::Some), + 1 => Just(Value::Huge), + ] +} + +/// A storage word. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Word { + Zero, + One, + Max, + Other(u64), +} + +impl Word { + pub(crate) fn u256(self) -> U256 { + match self { + Self::Zero => U256::ZERO, + Self::One => U256::from(1), + Self::Max => U256::MAX, + Self::Other(v) => U256::from(v), + } + } +} + +pub(crate) fn word() -> impl Strategy { + prop_oneof![ + 3 => Just(Word::Zero), + 3 => Just(Word::One), + 1 => Just(Word::Max), + 2 => (2u64..1_000_000).prop_map(Word::Other), + ] +} + +/// The live system address every case's registry names. +pub(crate) const SYSTEM_ADDRESS: Address = MEGA_SYSTEM_ADDRESS; + +/// The chain id every case runs on: revm's default, so a transaction that names none is valid. +pub(crate) const CHAIN_ID: u64 = 1; diff --git a/crates/mega-evm/tests/fuzz/gen/program.rs b/crates/mega-evm/tests/fuzz/gen/program.rs new file mode 100644 index 000000000..5a1fa45d5 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/gen/program.rs @@ -0,0 +1,932 @@ +//! Random programs, biased towards what the engine meters: storage writes, logs, the call family +//! with value, creations, self-destruction, reads of volatile data, the Oracle's storage, the +//! system contracts and the precompiles. +//! +//! A program is a list of [`Op`]s and an [`End`]. Every op is a self-contained snippet that leaves +//! the stack as it found it, so any list assembles to valid bytecode, and a program shrinks by +//! dropping ops. The assembly is [`BytecodeBuilder`]'s. + +use alloy_primitives::{Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{ + keyless::KEYLESS_DEPLOY_ADDRESS, IMegaAccessControl, IMegaLimitControl, IOracle, + ISequencerRegistry, ACCESS_CONTROL_ADDRESS, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + }, + test_utils::BytecodeBuilder, +}; +use proptest::prelude::*; +use revm::{bytecode::opcode::*, precompile::u64_to_address}; + +use super::{value, who, word, Flavor, Value, Who, Word}; + +/// Which call opcode a call uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Scheme { + Call, + CallCode, + DelegateCall, + StaticCall, +} + +impl Scheme { + const fn opcode(self) -> u8 { + match self { + Self::Call => CALL, + Self::CallCode => CALLCODE, + Self::DelegateCall => DELEGATECALL, + Self::StaticCall => STATICCALL, + } + } + + /// Whether the scheme carries a value operand. + const fn carries_value(self) -> bool { + matches!(self, Self::Call | Self::CallCode) + } +} + +fn scheme() -> impl Strategy { + prop_oneof![ + 6 => Just(Scheme::Call), + 1 => Just(Scheme::CallCode), + 2 => Just(Scheme::DelegateCall), + 2 => Just(Scheme::StaticCall), + ] +} + +/// Where a call goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Target { + /// One of the fixed accounts. + Who(Who), + /// The running contract itself (`ADDRESS`). + SelfAddress, + /// The block beneficiary (`COINBASE`): a volatile read of its account. + Coinbase, + /// The frame's caller (`CALLER`): the contract that called this one, the transaction's + /// sender, or, in the init code of a keyless deployment, the signer. + Caller, + /// A system contract, by address; a call runs its bytecode or its interceptor. + System(SystemContract), + /// A precompile. + Precompile(Precompile), +} + +impl Target { + /// The target with what only `MegaETH` has replaced: a system contract becomes `A`. + const fn neutralized(self) -> Self { + match self { + Self::System(_) => Self::Who(Who::A), + other => other, + } + } +} + +/// Pushes the target's address. +fn push_target(code: BytecodeBuilder, target: Target) -> BytecodeBuilder { + match target { + Target::Who(who) => code.push_address(who.address()), + Target::SelfAddress => code.append(ADDRESS), + Target::Coinbase => code.append(COINBASE), + Target::Caller => code.append(CALLER), + Target::System(contract) => code.push_address(contract.address()), + Target::Precompile(precompile) => code.push_address(precompile.address()), + } +} + +fn target() -> impl Strategy { + prop_oneof![ + 8 => who().prop_map(Target::Who), + 1 => Just(Target::SelfAddress), + 2 => Just(Target::Coinbase), + 1 => Just(Target::Caller), + 3 => system_contract().prop_map(Target::System), + 2 => precompile().prop_map(Target::Precompile), + ] +} + +/// One of the system contracts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemContract { + Oracle, + AccessControl, + LimitControl, + KeylessDeploy, + Registry, +} + +impl SystemContract { + pub(crate) const fn address(self) -> Address { + match self { + Self::Oracle => ORACLE_CONTRACT_ADDRESS, + Self::AccessControl => ACCESS_CONTROL_ADDRESS, + Self::LimitControl => LIMIT_CONTROL_ADDRESS, + Self::KeylessDeploy => KEYLESS_DEPLOY_ADDRESS, + Self::Registry => SEQUENCER_REGISTRY_ADDRESS, + } + } +} + +fn system_contract() -> impl Strategy { + prop_oneof![ + Just(SystemContract::Oracle), + Just(SystemContract::AccessControl), + Just(SystemContract::LimitControl), + Just(SystemContract::KeylessDeploy), + Just(SystemContract::Registry), + ] +} + +/// A method of a system contract, with the calldata that calls it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SystemMethod { + /// `MegaAccessControl.disableVolatileDataAccess()`. + Disable, + /// `MegaAccessControl.enableVolatileDataAccess()`. + Enable, + /// `MegaAccessControl.isVolatileDataAccessDisabled()`. + IsDisabled, + /// `MegaLimitControl.remainingComputeGas()`. + RemainingCompute, + /// `Oracle.sendHint(topic, data)` with `len` bytes of data. + SendHint { len: u8 }, + /// `Oracle.getSlot(slot)`: a volatile read of the Oracle's storage. + GetSlot { slot: u8 }, + /// `Oracle.setSlot(slot, value)`: refused by the contract unless the caller is the system + /// address. + SetSlot { slot: u8 }, + /// `SequencerRegistry.currentSystemAddress()`: bytecode, not intercepted. + RegistryCurrent, + /// `KeylessDeploy.keylessDeploy(...)` from a contract, which the dispatch does not take. + KeylessFromContract, + /// A selector no contract declares. + Unknown, +} + +impl SystemMethod { + pub(crate) fn target(self) -> SystemContract { + match self { + Self::Disable | Self::Enable | Self::IsDisabled | Self::Unknown => { + SystemContract::AccessControl + } + Self::RemainingCompute => SystemContract::LimitControl, + Self::SendHint { .. } | Self::GetSlot { .. } | Self::SetSlot { .. } => { + SystemContract::Oracle + } + Self::RegistryCurrent => SystemContract::Registry, + Self::KeylessFromContract => SystemContract::KeylessDeploy, + } + } + + pub(crate) fn calldata(self) -> Vec { + match self { + Self::Disable => IMegaAccessControl::disableVolatileDataAccessCall {}.abi_encode(), + Self::Enable => IMegaAccessControl::enableVolatileDataAccessCall {}.abi_encode(), + Self::IsDisabled => { + IMegaAccessControl::isVolatileDataAccessDisabledCall {}.abi_encode() + } + Self::RemainingCompute => IMegaLimitControl::remainingComputeGasCall {}.abi_encode(), + Self::SendHint { len } => IOracle::sendHintCall { + topic: alloy_primitives::B256::repeat_byte(0x11), + data: vec![0x22; len as usize].into(), + } + .abi_encode(), + Self::GetSlot { slot } => IOracle::getSlotCall { slot: U256::from(slot) }.abi_encode(), + Self::SetSlot { slot } => IOracle::setSlotCall { + slot: U256::from(slot), + value: alloy_primitives::B256::repeat_byte(0x33), + } + .abi_encode(), + Self::RegistryCurrent => ISequencerRegistry::currentSystemAddressCall {}.abi_encode(), + Self::KeylessFromContract => { + mega_evm::system::keyless::IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::from_static(&[0xf8, 0x01]), + gasLimitOverride: U256::ZERO, + } + .abi_encode() + } + Self::Unknown => vec![0xde, 0xad, 0xbe, 0xef], + } + } +} + +fn system_method() -> impl Strategy { + prop_oneof![ + 3 => Just(SystemMethod::Disable), + 2 => Just(SystemMethod::Enable), + 1 => Just(SystemMethod::IsDisabled), + 2 => Just(SystemMethod::RemainingCompute), + 2 => (0u8..=64).prop_map(|len| SystemMethod::SendHint { len }), + 3 => (0u8..4).prop_map(|slot| SystemMethod::GetSlot { slot }), + 1 => (0u8..4).prop_map(|slot| SystemMethod::SetSlot { slot }), + 1 => Just(SystemMethod::RegistryCurrent), + 1 => Just(SystemMethod::KeylessFromContract), + 1 => Just(SystemMethod::Unknown), + ] +} + +/// A precompile of the Satin set. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Precompile { + EcRecover, + Sha256, + Ripemd160, + Identity, + ModExp, + Bn254Add, + Bn254Mul, + Bn254Pairing, + Blake2f, + KzgPointEvaluation, + BlsG1Add, + BlsG1Msm, + BlsPairing, + P256Verify, +} + +impl Precompile { + pub(crate) fn address(self) -> Address { + u64_to_address(match self { + Self::EcRecover => 1, + Self::Sha256 => 2, + Self::Ripemd160 => 3, + Self::Identity => 4, + Self::ModExp => 5, + Self::Bn254Add => 6, + Self::Bn254Mul => 7, + Self::Bn254Pairing => 8, + Self::Blake2f => 9, + Self::KzgPointEvaluation => 0x0a, + Self::BlsG1Add => 0x0b, + Self::BlsG1Msm => 0x0c, + Self::BlsPairing => 0x0f, + Self::P256Verify => 0x100, + }) + } + + /// An input of the length the precompile accepts, cheap where the precompile has a cheap + /// valid input and failing its own checks where it has none. + pub(crate) fn canonical_input(self) -> Vec { + match self { + Self::EcRecover => { + let mut input = vec![0u8; 128]; + input[63] = 27; + input + } + Self::Sha256 | Self::Ripemd160 | Self::Identity => vec![0x5a; 40], + Self::ModExp => { + let mut input = vec![0u8; 99]; + input[31] = 1; + input[63] = 1; + input[95] = 1; + input[96..99].copy_from_slice(&[3, 5, 7]); + input + } + Self::Bn254Add => vec![0u8; 128], + Self::Bn254Mul => vec![0u8; 96], + Self::Bn254Pairing => Vec::new(), + Self::Blake2f => { + let mut input = vec![0u8; 213]; + input[3] = 1; + input[212] = 1; + input + } + Self::KzgPointEvaluation => vec![0u8; 192], + Self::BlsG1Add => vec![0u8; 256], + Self::BlsG1Msm | Self::P256Verify => vec![0u8; 160], + Self::BlsPairing => vec![0u8; 384], + } + } +} + +fn precompile() -> impl Strategy { + prop_oneof![ + Just(Precompile::EcRecover), + Just(Precompile::Sha256), + Just(Precompile::Ripemd160), + Just(Precompile::Identity), + Just(Precompile::ModExp), + Just(Precompile::Bn254Add), + Just(Precompile::Bn254Mul), + Just(Precompile::Bn254Pairing), + Just(Precompile::Blake2f), + Just(Precompile::KzgPointEvaluation), + Just(Precompile::BlsG1Add), + Just(Precompile::BlsG1Msm), + Just(Precompile::BlsPairing), + Just(Precompile::P256Verify), + ] +} + +/// What a precompile call carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PrecompileInput { + /// [`Precompile::canonical_input`]. + Canonical, + /// `len` zero bytes. + Zeros { len: u16 }, +} + +fn precompile_input() -> impl Strategy { + prop_oneof![ + 3 => Just(PrecompileInput::Canonical), + 1 => (0u16..=300).prop_map(|len| PrecompileInput::Zeros { len }), + ] +} + +/// How much gas a call forwards. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Forward { + /// Everything (`GAS`), which the 63/64 rule caps. + All, + /// A fixed amount, which the 63/64 rule may cap lower. + Gas(u32), +} + +fn forward() -> impl Strategy { + prop_oneof![ + 4 => Just(Forward::All), + 1 => Just(Forward::Gas(0)), + 1 => Just(Forward::Gas(2_300)), + 2 => Just(Forward::Gas(30_000)), + 2 => Just(Forward::Gas(200_000)), + 1 => Just(Forward::Gas(2_000_000)), + ] +} + +fn push_forward(code: BytecodeBuilder, forward: Forward) -> BytecodeBuilder { + match forward { + Forward::All => code.append(GAS), + Forward::Gas(gas) => code.push_number(gas), + } +} + +/// A read of volatile data, which gas detention caps the transaction on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum VolatileRead { + Timestamp, + Number, + Coinbase, + PrevRandao, + GasLimit, + BaseFee, + BlobBaseFee, + /// An Amsterdam opcode Satin runs on its Osaka base. + SlotNum, + /// `BLOCKHASH` of the previous block. + BlockHash, + /// The beneficiary's balance. + CoinbaseBalance, + /// The beneficiary's code size. + CoinbaseCodeSize, + /// The beneficiary's code hash. + CoinbaseCodeHash, +} + +impl VolatileRead { + fn assemble(self, code: BytecodeBuilder) -> BytecodeBuilder { + match self { + Self::Timestamp => code.append_many([TIMESTAMP, POP]), + Self::Number => code.append_many([NUMBER, POP]), + Self::Coinbase => code.append_many([COINBASE, POP]), + Self::PrevRandao => code.append_many([DIFFICULTY, POP]), + Self::GasLimit => code.append_many([GASLIMIT, POP]), + Self::BaseFee => code.append_many([BASEFEE, POP]), + Self::BlobBaseFee => code.append_many([BLOBBASEFEE, POP]), + Self::SlotNum => code.append_many([SLOTNUM, POP]), + Self::BlockHash => code.push_number(1u8).append_many([NUMBER, SUB, BLOCKHASH, POP]), + Self::CoinbaseBalance => code.append_many([COINBASE, BALANCE, POP]), + Self::CoinbaseCodeSize => code.append_many([COINBASE, EXTCODESIZE, POP]), + Self::CoinbaseCodeHash => code.append_many([COINBASE, EXTCODEHASH, POP]), + } + } +} + +fn volatile_read() -> impl Strategy { + prop_oneof![ + 2 => Just(VolatileRead::Timestamp), + 2 => Just(VolatileRead::Number), + 1 => Just(VolatileRead::Coinbase), + 1 => Just(VolatileRead::PrevRandao), + 1 => Just(VolatileRead::GasLimit), + 1 => Just(VolatileRead::BaseFee), + 1 => Just(VolatileRead::BlobBaseFee), + 1 => Just(VolatileRead::SlotNum), + 1 => Just(VolatileRead::BlockHash), + 2 => Just(VolatileRead::CoinbaseBalance), + 1 => Just(VolatileRead::CoinbaseCodeSize), + 1 => Just(VolatileRead::CoinbaseCodeHash), + ] +} + +/// An account read that is not volatile unless its target is the beneficiary. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AccountRead { + Balance, + CodeSize, + CodeHash, + /// `EXTCODECOPY` of 32 bytes. + CodeCopy, +} + +fn account_read() -> impl Strategy { + prop_oneof![ + Just(AccountRead::Balance), + Just(AccountRead::CodeSize), + Just(AccountRead::CodeHash), + Just(AccountRead::CodeCopy), + ] +} + +/// The init code of a creation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum InitCode { + /// Returns nothing: an account with no code. + Empty, + /// Deploys `len` bytes of `STOP`. + Deploys { len: u8 }, + /// Deploys code starting with `0xEF`, which the deposit refuses. + DeploysEf, + /// Writes a slot and emits a log, then deploys a byte. + WritesThenDeploys, + /// Reverts. + Reverts, + /// Halts on `INVALID`. + Invalid, + /// Destroys the account it is creating, to `to`. + Selfdestructs { to: Who }, + /// Calls its caller with two million gas, then deploys a byte: the creator's own code runs + /// again under its creation, and may create again, a few levels deep before the gas is gone. + /// In a keyless deployment the caller is the signer, whose code is its delegate's. + CallsCaller, + /// Runs a program of its own; what it returns is deployed. + Runs(Box), +} + +impl InitCode { + pub(crate) fn assemble(&self) -> Vec { + match self { + Self::Empty => vec![STOP], + Self::Deploys { len } => constructor(&[], &vec![STOP; *len as usize]), + Self::DeploysEf => constructor(&[], &[0xEF, 0x00]), + Self::WritesThenDeploys => { + let prefix = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(7)) + .push_number(32u8) + .append_many([PUSH0, LOG0]) + .build_vec(); + constructor(&prefix, &[STOP]) + } + Self::Reverts => BytecodeBuilder::default().revert().build_vec(), + Self::Invalid => vec![INVALID], + Self::Selfdestructs { to } => { + BytecodeBuilder::default().selfdestruct(to.address()).build_vec() + } + Self::CallsCaller => { + let prefix = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, CALLER]) + .push_number(2_000_000_u32) + .append_many([CALL, POP]) + .build_vec(); + constructor(&prefix, &[STOP]) + } + Self::Runs(program) => program.assemble(), + } + } + + /// Whether the init code, or a program inside it, destroys an account. + fn destroys(&self) -> bool { + match self { + Self::Selfdestructs { .. } => true, + Self::Runs(program) => program.destroys(), + _ => false, + } + } + + /// The init code with what only `MegaETH` has replaced: a program inside is neutralized. + fn neutralized(self) -> Self { + match self { + Self::Runs(program) => Self::Runs(Box::new(program.neutralized())), + other => other, + } + } + + /// The init code with no way left to destroy the account it is creating: a self-destruction + /// becomes an empty deployment, and a program inside is rewritten by + /// [`Program::into_init_without_destruction`]. + pub(crate) fn without_destruction(self) -> Self { + match self { + Self::Selfdestructs { .. } => Self::Empty, + Self::Runs(program) => Self::Runs(Box::new(program.into_init_without_destruction())), + other => other, + } + } +} + +/// Init code that runs `prefix`, then deploys `runtime`, copied from its own tail. +fn constructor(prefix: &[u8], runtime: &[u8]) -> Vec { + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let tail = u16::try_from(prefix.len() + 11).expect("a short prefix").to_be_bytes(); + let mut code = prefix.to_vec(); + code.extend_from_slice(&[PUSH1, len, PUSH2, tail[0], tail[1], PUSH0, CODECOPY]); + code.extend_from_slice(&[PUSH1, len, PUSH0, RETURN]); + code.extend_from_slice(runtime); + code +} + +fn init_code() -> impl Strategy { + let leaf = program_with(Flavor::Satin, 0, 6); + prop_oneof![ + 3 => Just(InitCode::Empty), + 3 => (0u8..=200).prop_map(|len| InitCode::Deploys { len }), + 1 => Just(InitCode::DeploysEf), + 2 => Just(InitCode::WritesThenDeploys), + 1 => Just(InitCode::Reverts), + 1 => Just(InitCode::Invalid), + 2 => who().prop_map(|to| InitCode::Selfdestructs { to }), + 1 => Just(InitCode::CallsCaller), + 3 => leaf.prop_map(|program| InitCode::Runs(Box::new(program))), + ] +} + +/// One self-contained snippet of a program. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Op { + /// `SSTORE`. + Sstore { slot: u8, value: Word }, + /// `SLOAD`. + Sload { slot: u8 }, + /// `TSTORE`. + Tstore { slot: u8, value: Word }, + /// `LOGn` of `len` bytes of memory. + Log { topics: u8, len: u16 }, + /// A call. + Call { scheme: Scheme, target: Target, value: Value, forward: Forward, args_len: u8 }, + /// A call to a system contract's method, by its calldata. + System { method: SystemMethod, scheme: Scheme, value: Value }, + /// A call to a precompile. + Precompile { which: Precompile, input: PrecompileInput, forward: Forward }, + /// `CREATE`, or `CREATE2` with a salt. + Create { value: Value, salt: Option, init: InitCode }, + /// A read of volatile data. + Volatile(VolatileRead), + /// A read of an account. + Account { target: Target, read: AccountRead }, + /// A loop of `rounds` rounds copying 32 KiB of memory: about 3,100 gas a round, cheap to run. + Work { rounds: u16 }, + /// A loop of `rounds` counting rounds: 26 gas a round. + Burn { rounds: u16 }, + /// `KECCAK256` of `len` bytes of memory. + Keccak { len: u32 }, + /// An `MSTORE` at `offset`: memory expansion, or an out-of-gas for a large one. + Mstore { offset: u32 }, + /// A copy of return data past its end, which halts the frame. + ReturnDataCopyPastEnd, + /// An opcode that reads the frame's environment. + Env(u8), +} + +/// How a program ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum End { + Stop, + Return { + len: u16, + }, + Revert { + len: u16, + }, + Invalid, + Selfdestruct { + to: Target, + }, + /// Loops until the frame runs out of gas. + Spin, + /// No terminator: the code runs off its end. + Fallthrough, +} + +fn end() -> impl Strategy { + prop_oneof![ + 6 => Just(End::Stop), + 3 => (0u16..=100).prop_map(|len| End::Return { len }), + 3 => (0u16..=100).prop_map(|len| End::Revert { len }), + 1 => Just(End::Invalid), + 2 => target().prop_map(|to| End::Selfdestruct { to }), + 1 => Just(End::Spin), + 1 => Just(End::Fallthrough), + ] +} + +/// A program: its ops, in order, and how it ends. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Program { + pub(crate) ops: Vec, + pub(crate) end: End, +} + +impl Program { + /// The program's bytecode. + pub(crate) fn assemble(&self) -> Vec { + let mut code = BytecodeBuilder::default(); + for op in &self.ops { + code = op.assemble(code); + } + match self.end { + End::Stop => code.stop(), + End::Return { len } => code.push_number(len).append_many([PUSH0, RETURN]), + End::Revert { len } => code.push_number(len).append_many([PUSH0, REVERT]), + End::Invalid => code.append(INVALID), + End::Selfdestruct { to } => push_target(code, to).append(SELFDESTRUCT), + End::Spin => { + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(0x8000_u16) + .append_many([PUSH0, PUSH0, MCOPY]) + .push_number(dest) + .append(JUMP) + } + End::Fallthrough => code, + } + .build_vec() + } + + /// Whether the program, or any init code it creates with, destroys an account. + pub(crate) fn destroys(&self) -> bool { + matches!(self.end, End::Selfdestruct { .. }) || + self.ops.iter().any(|op| match op { + Op::Create { init, .. } => init.destroys(), + _ => false, + }) + } + + /// Whether the program, or any init code it creates with, calls the Oracle with calldata + /// taken from memory as it stands: at least a selector's worth of bytes, which may be the + /// `sendHint` selector an earlier op left there, with a payload that does not decode. + pub(crate) fn calls_the_oracle_with_memory(&self) -> bool { + self.ops.iter().any(|op| match op { + Op::Call { + scheme: Scheme::Call | Scheme::StaticCall, + target: Target::System(SystemContract::Oracle), + args_len, + .. + } => *args_len >= 4, + Op::Create { init: InitCode::Runs(program), .. } => { + program.calls_the_oracle_with_memory() + } + _ => false, + }) + } + + /// The program with every init code it creates with rewritten so that it cannot destroy the + /// account it is creating ([`InitCode::without_destruction`]). The program's own ending + /// stands: run as a contract's code it destroys an account that existed before the + /// transaction. + pub(crate) fn without_destruction_in_creations(self) -> Self { + let ops = self + .ops + .into_iter() + .map(|op| match op { + Op::Create { value, salt, init } => { + Op::Create { value, salt, init: init.without_destruction() } + } + other => other, + }) + .collect(); + Self { ops, end: self.end } + } + + /// The program as init code that cannot destroy the account it is creating: an ending + /// `SELFDESTRUCT` becomes a `STOP`, and a `CALLCODE` or `DELEGATECALL`, which would run + /// another contract's code, and its ending, as the account being created, becomes a `CALL`. + /// The init codes it creates with are rewritten the same way. + pub(crate) fn into_init_without_destruction(self) -> Self { + let end = match self.end { + End::Selfdestruct { .. } => End::Stop, + other => other, + }; + let ops = self + .ops + .into_iter() + .map(|op| match op { + Op::Call { + scheme: Scheme::CallCode | Scheme::DelegateCall, + target, + value, + forward, + args_len, + } => Op::Call { scheme: Scheme::Call, target, value, forward, args_len }, + other => other, + }) + .collect(); + Self { ops, end }.without_destruction_in_creations() + } + + /// The program with what only `MegaETH` has replaced, op by op ([`Op::neutralized`]), so that + /// op-revm and revm's mainnet EVM run the same thing. + pub(crate) fn neutralized(self) -> Self { + let end = match self.end { + End::Selfdestruct { to } => End::Selfdestruct { to: to.neutralized() }, + other => other, + }; + Self { ops: self.ops.into_iter().map(Op::neutralized).collect(), end } + } +} + +impl Op { + /// The op with what only `MegaETH` has replaced: a system contract call becomes a load, a + /// system contract target becomes `A`, `SLOTNUM` becomes `NUMBER`, and init code is + /// neutralized. + fn neutralized(self) -> Self { + match self { + Self::System { .. } => Self::Sload { slot: 0 }, + Self::Call { scheme, target, value, forward, args_len } => { + Self::Call { scheme, target: target.neutralized(), value, forward, args_len } + } + Self::Account { target, read } => Self::Account { target: target.neutralized(), read }, + Self::Volatile(VolatileRead::SlotNum) => Self::Volatile(VolatileRead::Number), + Self::Create { value, salt, init } => { + Self::Create { value, salt, init: init.neutralized() } + } + other => other, + } + } + + fn assemble(&self, code: BytecodeBuilder) -> BytecodeBuilder { + match self { + Self::Sstore { slot, value } => code.sstore(U256::from(*slot), value.u256()), + Self::Sload { slot } => code.push_number(*slot).append_many([SLOAD, POP]), + Self::Tstore { slot, value } => { + code.push_u256(value.u256()).push_number(*slot).append(TSTORE) + } + Self::Log { topics, len } => { + let mut code = code; + for topic in (1..=*topics).rev() { + code = code.push_number(topic); + } + code.push_number(*len).append_many([PUSH0, LOG0 + topics]) + } + Self::Call { scheme, target, value, forward, args_len } => { + let code = code.append_many([PUSH0, PUSH0]).push_number(*args_len).append(PUSH0); + let code = if scheme.carries_value() { code.push_u256(value.wei()) } else { code }; + push_forward(push_target(code, *target), *forward) + .append_many([scheme.opcode(), POP]) + } + Self::System { method, scheme, value } => { + let data = method.calldata(); + let code = code + .mstore(0, &data) + .append_many([PUSH0, PUSH0]) + .push_number(data.len() as u64) + .append(PUSH0); + let code = if scheme.carries_value() { code.push_u256(value.wei()) } else { code }; + code.push_address(method.target().address()) + .append(GAS) + .append_many([scheme.opcode(), POP]) + } + Self::Precompile { which, input, forward } => { + let data = match input { + PrecompileInput::Canonical => which.canonical_input(), + PrecompileInput::Zeros { len } => vec![0u8; *len as usize], + }; + let code = if data.is_empty() { code } else { code.mstore(0, &data) }; + let code = code + .append_many([PUSH0, PUSH0]) + .push_number(data.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(which.address()); + push_forward(code, *forward).append_many([CALL, POP]) + } + Self::Create { value, salt, init } => { + let init = init.assemble(); + match salt { + None => code.create(value.wei(), &init), + Some(salt) => code.create2(value.wei(), &init, U256::from(*salt)), + } + .append(POP) + } + Self::Volatile(read) => read.assemble(code), + Self::Account { target, read } => { + let code = push_target(code, *target); + match read { + AccountRead::Balance => code.append_many([BALANCE, POP]), + AccountRead::CodeSize => code.append_many([EXTCODESIZE, POP]), + AccountRead::CodeHash => code.append_many([EXTCODEHASH, POP]), + AccountRead::CodeCopy => { + // EXTCODECOPY pops address, destOffset, offset, size. + code.append_many([PUSH0, PUSH0]) + .push_number(32u8) + .append_many([SWAP3, EXTCODECOPY]) + } + } + } + Self::Work { rounds } => { + let code = code.push_number(*rounds); + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(0x8000_u16) + .append_many([PUSH0, PUSH0, MCOPY]) + .push_number(1u8) + .append_many([SWAP1, SUB, DUP1]) + .push_number(dest) + .append_many([JUMPI, POP]) + } + Self::Burn { rounds } => { + let code = code.push_number(*rounds); + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(1u8) + .append_many([SWAP1, SUB, DUP1]) + .push_number(dest) + .append_many([JUMPI, POP]) + } + Self::Keccak { len } => code.push_number(*len).append_many([PUSH0, KECCAK256, POP]), + Self::Mstore { offset } => code.append(PUSH0).push_number(*offset).append(MSTORE), + Self::ReturnDataCopyPastEnd => { + code.push_number(1u8).append_many([RETURNDATASIZE, PUSH0, RETURNDATACOPY]) + } + Self::Env(opcode) => code.append_many([*opcode, POP]), + } + } +} + +/// Opcodes that push one word about the frame and read nothing volatile. +const ENV_OPCODES: [u8; 12] = [ + ADDRESS, + ORIGIN, + CALLER, + CALLVALUE, + CALLDATASIZE, + CODESIZE, + GASPRICE, + RETURNDATASIZE, + CHAINID, + SELFBALANCE, + GAS, + MSIZE, +]; + +/// One op at `depth`: a leaf (depth 0) creates nothing, so init code nests only so deep. +fn op(depth: u32) -> impl Strategy { + // A leaf creates nothing, so init code nests only so deep: the strategy of a creation + // builds the init code's, which builds a leaf's, and a leaf must not build another. + let creates: BoxedStrategy = if depth == 0 { + Just(Op::Sstore { slot: 3, value: Word::One }).boxed() + } else { + (value(), proptest::option::of(0u8..4), init_code()) + .prop_map(|(value, salt, init)| Op::Create { value, salt, init }) + .boxed() + }; + prop_oneof![ + 8 => (0u8..4, word()).prop_map(|(slot, value)| Op::Sstore { slot, value }), + 2 => (0u8..4).prop_map(|slot| Op::Sload { slot }), + 1 => (0u8..4, word()).prop_map(|(slot, value)| Op::Tstore { slot, value }), + 4 => (0u8..=4, 0u16..=200).prop_map(|(topics, len)| Op::Log { topics, len }), + 8 => (scheme(), target(), value(), forward(), 0u8..=64).prop_map( + |(scheme, target, value, forward, args_len)| Op::Call { + scheme, + target, + value, + forward, + args_len, + } + ), + 3 => (system_method(), prop_oneof![3 => Just(Scheme::Call), 1 => Just(Scheme::StaticCall)], value()) + .prop_map(|(method, scheme, value)| Op::System { method, scheme, value }), + 2 => (precompile(), precompile_input(), forward()) + .prop_map(|(which, input, forward)| Op::Precompile { which, input, forward }), + 4 => creates, + 5 => volatile_read().prop_map(Op::Volatile), + 2 => (target(), account_read()).prop_map(|(target, read)| Op::Account { target, read }), + 3 => (1u16..=8_000).prop_map(|rounds| Op::Work { rounds }), + 3 => (1u16..=5_000).prop_map(|rounds| Op::Burn { rounds }), + 1 => prop_oneof![Just(0u32), Just(32), Just(1_000), Just(100_000), Just(50_000_000)] + .prop_map(|len| Op::Keccak { len }), + 1 => prop_oneof![Just(0u32), Just(1_000), Just(100_000), Just(1 << 24), Just(u32::MAX)] + .prop_map(|offset| Op::Mstore { offset }), + 1 => Just(Op::ReturnDataCopyPastEnd), + 2 => proptest::sample::select(ENV_OPCODES.as_slice()).prop_map(Op::Env), + ] +} + +/// A program of at most `max_ops` ops at `depth`. +pub(crate) fn program_with( + flavor: Flavor, + depth: u32, + max_ops: usize, +) -> impl Strategy { + (proptest::collection::vec(op(depth), 0..=max_ops), end()).prop_map(move |(ops, end)| { + let program = Program { ops, end }; + match flavor { + Flavor::Satin => program, + Flavor::Neutral => program.neutralized(), + } + }) +} + +/// A program of the size a case's contracts run: up to twelve ops, whose init codes may run a +/// leaf program of their own. +pub(crate) fn program(flavor: Flavor) -> impl Strategy { + program_with(flavor, 1, 12) +} diff --git a/crates/mega-evm/tests/fuzz/gen/tx.rs b/crates/mega-evm/tests/fuzz/gen/tx.rs new file mode 100644 index 000000000..89c6ca99d --- /dev/null +++ b/crates/mega-evm/tests/fuzz/gen/tx.rs @@ -0,0 +1,790 @@ +//! Random transactions: a call, a creation, an EIP-7702 transaction with its authorizations, an +//! access-list transaction, a deposit, a system-address transaction and a keyless deployment, +//! each at a gas limit below or above the execution cap. + +use std::cell::RefCell; + +use alloy_op_evm::OpTx; +use alloy_primitives::{hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + alloy_consensus::{Signed, TxLegacy}, + constants::{MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, + system::{ + keyless::{IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS}, + IOracle, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::op_transaction, + MegaTransaction, +}; +use proptest::prelude::*; +use revm::{ + context::{ + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, +}; + +use super::{ + program::InitCode, value, who, world::World, Flavor, Value, Who, CALLER, CHAIN_ID, + SYSTEM_ADDRESS, +}; + +/// A gas limit, by where it stands to the execution cap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GasTier { + /// 60,000: room for little beyond the intrinsic cost. + Tiny, + /// 400,000. + Small, + /// 4,000,000. + Medium, + /// 30,000,000: past gas detention's default cap. + Large, + /// 50,000,000 above the execution cap: a reservoir of that much. + AboveCap, +} + +impl GasTier { + pub(crate) const fn limit(self) -> u64 { + match self { + Self::Tiny => 60_000, + Self::Small => 400_000, + Self::Medium => 4_000_000, + Self::Large => 30_000_000, + Self::AboveCap => TX_GAS_LIMIT_CAP + 50_000_000, + } + } +} + +fn gas_tier() -> impl Strategy { + prop_oneof![ + 1 => Just(GasTier::Tiny), + 3 => Just(GasTier::Small), + 4 => Just(GasTier::Medium), + 2 => Just(GasTier::Large), + 1 => Just(GasTier::AboveCap), + ] +} + +/// A gas price. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Price { + Free, + One, + Dear, +} + +impl Price { + pub(crate) const fn wei(self) -> u128 { + match self { + Self::Free => 0, + Self::One => 1, + Self::Dear => 1_000, + } + } +} + +fn price() -> impl Strategy { + prop_oneof![5 => Just(Price::Free), 2 => Just(Price::One), 1 => Just(Price::Dear)] +} + +/// Where an authority delegates to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Delegate { + Contract, + A, + B, + /// Clears the delegation. + Zero, + Beneficiary, +} + +impl Delegate { + fn address(self) -> Address { + match self { + Self::Contract => Who::Contract.address(), + Self::A => Who::A.address(), + Self::B => Who::B.address(), + Self::Zero => Address::ZERO, + Self::Beneficiary => Who::Beneficiary.address(), + } + } +} + +/// One EIP-7702 authorization. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Auth { + pub(crate) authority: Who, + /// Whether the nonce is the authority's; otherwise one too high. + pub(crate) nonce_ok: bool, + /// Whether the chain id is this chain's or zero; otherwise another chain's. + pub(crate) chain_ok: bool, + /// Whether the signature recovers; otherwise the authorization is skipped. + pub(crate) recovers: bool, + pub(crate) delegate: Delegate, +} + +fn auth() -> impl Strategy { + ( + who(), + prop_oneof![4 => Just(true), 1 => Just(false)], + prop_oneof![5 => Just(true), 1 => Just(false)], + prop_oneof![5 => Just(true), 1 => Just(false)], + prop_oneof![ + 3 => Just(Delegate::Contract), + 3 => Just(Delegate::A), + 2 => Just(Delegate::B), + 1 => Just(Delegate::Zero), + 1 => Just(Delegate::Beneficiary), + ], + ) + .prop_map(|(authority, nonce_ok, chain_ok, recovers, delegate)| Auth { + authority, + nonce_ok, + chain_ok, + recovers, + delegate, + }) +} + +/// What a system-address transaction calls on the Oracle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SysCall { + SetSlot { slot: u8 }, + GetSlot { slot: u8 }, + EmitLog { len: u8 }, + MultiCallEmpty, +} + +impl SysCall { + fn calldata(self) -> Bytes { + match self { + Self::SetSlot { slot } => IOracle::setSlotsCall { + slots: vec![U256::from(slot)], + values: vec![B256::repeat_byte(0x55)], + } + .abi_encode(), + Self::GetSlot { slot } => IOracle::getSlotCall { slot: U256::from(slot) }.abi_encode(), + Self::EmitLog { len } => IOracle::emitLogCall { + topic: B256::repeat_byte(0x66), + data: vec![0x77; len as usize].into(), + } + .abi_encode(), + Self::MultiCallEmpty => IOracle::multiCallCall { data: vec![] }.abi_encode(), + } + .into() + } +} + +fn sys_call() -> impl Strategy { + prop_oneof![ + 3 => (0u8..4).prop_map(|slot| SysCall::SetSlot { slot }), + 2 => (0u8..4).prop_map(|slot| SysCall::GetSlot { slot }), + 2 => (0u8..=64).prop_map(|len| SysCall::EmitLog { len }), + 1 => Just(SysCall::MultiCallEmpty), + ] +} + +/// The `gasLimitOverride` of a keyless deployment, which must cover the signed gas limit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Override { + /// Zero, which covers no signed gas limit. + Zero, + /// The signed gas limit. + Signed, + /// Above what the call can forward. + Large, + /// Half the signed gas limit. + Short, +} + +/// How the transaction a keyless deployment carries is encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Encoding { + /// A pre-EIP-155 signed creation, as the rules want it. + Valid, + /// The same bytes cut short: not a transaction. + Truncated, + /// The same bytes with one more after them. + Trailing, + /// A signed call, not a creation. + NotCreation, + /// Signed with a chain id. + Eip155, + /// A signature no signer recovers from. + BadSignature, +} + +/// The gas limit a keyless deployment is signed with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SignedGas { + /// 100,000: a call of 400,000 gas can still forward it. + Low, + /// 1,000,000. + High, +} + +impl SignedGas { + pub(crate) const fn limit(self) -> u64 { + match self { + Self::Low => 100_000, + Self::High => 1_000_000, + } + } +} + +/// The code a keyless signer's account holds before the transaction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SignerCode { + None, + /// A contract's code, which EIP-3607 refuses as a creator's. + Plain, + /// An EIP-7702 delegation, which the rule admits: the signer's code is the delegate's, and it + /// runs when the init code calls its caller. + Delegates(Who), +} + +/// A keyless signer's account before the transaction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Signer { + /// Whether it holds an ether; otherwise nothing. + pub(crate) funded: bool, + /// Its nonce: the rules admit 0 and 1, and take the creation's bump back from 1. + pub(crate) nonce: u8, + pub(crate) code: SignerCode, +} + +impl Signer { + /// Whether the account does not exist, as EIP-161 has it. + pub(crate) fn is_empty(self) -> bool { + !self.funded && self.nonce == 0 && self.code == SignerCode::None + } +} + +fn signer() -> impl Strategy { + ( + prop_oneof![5 => Just(true), 1 => Just(false)], + prop_oneof![5 => Just(0u8), 4 => Just(1), 1 => Just(2)], + prop_oneof![ + 9 => Just(SignerCode::None), + 1 => Just(SignerCode::Plain), + 2 => prop_oneof![Just(Who::Contract), Just(Who::A), Just(Who::B)] + .prop_map(SignerCode::Delegates), + ], + ) + .prop_map(|(funded, nonce, code)| Signer { funded, nonce, code }) +} + +/// What a keyless deployment's deploy address holds before the transaction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DeployAddress { + /// No account. + Empty, + /// A contract: the deployment is there already. + Code, + /// A balance and nothing else, which a creation deploys onto. + Balance, + /// A nonce and no code: the rules pass, and the creation collides. + Nonce, +} + +/// The size of a keyless deployment's init code: as drawn, or padded with zero bytes to the +/// initcode size limit or past it. The padding never runs, since a frame that runs off the end of +/// its code stops as it does on a zero byte, so the init code does what it did unpadded; only its +/// size, and what the size costs, change. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum InitSize { + /// As drawn: a few hundred bytes at most. + Drawn, + /// The initcode size limit exactly, which the rule admits. + AtLimit, + /// One byte over the limit. + JustOver, + /// Twice the limit. + TwiceOver, +} + +impl InitSize { + /// The size of init code drawn at `drawn` bytes. + pub(crate) const fn size(self, drawn: usize) -> usize { + match self { + Self::Drawn => drawn, + Self::AtLimit => MAX_INITCODE_SIZE, + Self::JustOver => MAX_INITCODE_SIZE + 1, + Self::TwiceOver => 2 * MAX_INITCODE_SIZE, + } + } + + /// `code` at this size. + fn pad(self, mut code: Vec) -> Vec { + let size = self.size(code.len()); + assert!(code.len() <= size, "init code is drawn below the size it is padded to"); + code.resize(size, 0); + code + } +} + +/// The size of the init code the keyless property draws: as drawn mostly, and in one case in eight +/// at the boundary of the initcode size limit or far past it. +fn init_size() -> impl Strategy { + prop_oneof![ + 21 => Just(InitSize::Drawn), + 1 => Just(InitSize::AtLimit), + 1 => Just(InitSize::JustOver), + 1 => Just(InitSize::TwiceOver), + ] +} + +/// The shape of a transaction. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Shape { + /// A call to `to` carrying `data_len` bytes, with an access list of `(account, slots)`. + Call { to: Who, data_len: u16, access_list: Vec<(Who, u8)> }, + /// A creation transaction whose init code is the case's main program. + Create, + /// An EIP-7702 transaction to `to`. + Eip7702 { to: Who, auths: Vec }, + /// A deposit to `to` (or a creation, with `create`), minting `mint` to its caller. A + /// `system` deposit is one Regolith refuses, which halts as a failed deposit. + Deposit { to: Who, mint: Value, data_len: u16, system: bool, create: bool }, + /// A legacy call from the system address to the Oracle: promoted to a deposit by the + /// engine when the registry names its caller. Off the whitelist it is an ordinary + /// transaction. + SystemAddress { call: SysCall, nonce_ok: bool, chain_ok: bool, off_whitelist: bool }, + /// A `keylessDeploy` call deploying `init` at `init_size`, signed at `signed_nonce` for + /// `signed_gas` and carrying `signed_value`, into a world where the signer and the deploy + /// address are as given. + Keyless { + init: InitCode, + init_size: InitSize, + encoding: Encoding, + signed_nonce: u8, + signed_value: Value, + signed_gas: SignedGas, + gas_override: Override, + signer: Signer, + deploy_address: DeployAddress, + }, +} + +fn access_list() -> impl Strategy> { + proptest::collection::vec((who(), 0u8..=3), 0..=2) +} + +/// A keyless deployment, its init code at a size `init_size` draws. +fn keyless_shape(init_size: impl Strategy) -> impl Strategy { + let init = super::program::program_with(Flavor::Satin, 0, 6); + // Most keyless cases pass every rule and start their creation; each rule's refusal is drawn + // often enough to be hit in a bounded run of the keyless property, the initcode size limit's + // through the sizes that property draws. + ( + prop_oneof![ + 4 => init.prop_map(|p| InitCode::Runs(Box::new(p))), + 3 => (0u8..=100).prop_map(|len| InitCode::Deploys { len }), + 1 => Just(InitCode::Empty), + 1 => Just(InitCode::Reverts), + 1 => Just(InitCode::Invalid), + 2 => Just(InitCode::WritesThenDeploys), + 1 => who().prop_map(|to| InitCode::Selfdestructs { to }), + 2 => Just(InitCode::CallsCaller), + ], + prop_oneof![ + 14 => Just(Encoding::Valid), + 1 => Just(Encoding::Truncated), + 1 => Just(Encoding::Trailing), + 1 => Just(Encoding::NotCreation), + 1 => Just(Encoding::Eip155), + 1 => Just(Encoding::BadSignature), + ], + prop_oneof![14 => Just(0u8), 1 => Just(1), 1 => Just(2)], + prop_oneof![ + 8 => Just(Value::Zero), + 2 => Just(Value::One), + 1 => Just(Value::Some), + 1 => Just(Value::Huge), + ], + prop_oneof![3 => Just(SignedGas::Low), 1 => Just(SignedGas::High)], + prop_oneof![ + 1 => Just(Override::Zero), + 5 => Just(Override::Signed), + 5 => Just(Override::Large), + 1 => Just(Override::Short), + ], + signer(), + prop_oneof![ + 9 => Just(DeployAddress::Empty), + 1 => Just(DeployAddress::Code), + 1 => Just(DeployAddress::Balance), + 1 => Just(DeployAddress::Nonce), + ], + init_size, + ) + .prop_map( + |( + init, + encoding, + signed_nonce, + signed_value, + signed_gas, + gas_override, + signer, + deploy_address, + init_size, + )| Shape::Keyless { + init, + init_size, + encoding, + signed_nonce, + signed_value, + signed_gas, + gas_override, + signer, + deploy_address, + }, + ) +} + +fn shape(flavor: Flavor) -> impl Strategy { + let mega_only = match flavor { + Flavor::Satin => 2, + Flavor::Neutral => 1, + }; + // Init code at the size limit is a mebibyte of calldata, which would cost every property for + // a rule only the keyless property holds the engine to: here it is always as drawn. + let keyless = keyless_shape(Just(InitSize::Drawn)); + let system_address = ( + sys_call(), + prop_oneof![9 => Just(true), 1 => Just(false)], + prop_oneof![9 => Just(true), 1 => Just(false)], + prop_oneof![5 => Just(false), 1 => Just(true)], + ) + .prop_map(|(call, nonce_ok, chain_ok, off_whitelist)| Shape::SystemAddress { + call, + nonce_ok, + chain_ok, + off_whitelist, + }); + let shapes = prop_oneof![ + 10 => (who(), 0u16..=200, access_list()) + .prop_map(|(to, data_len, access_list)| Shape::Call { to, data_len, access_list }), + 3 => Just(Shape::Create), + // An empty authorization list refuses the transaction: one in sixteen covers it. + 3 => ( + who(), + prop_oneof![ + 1 => Just(Vec::new()), + 15 => proptest::collection::vec(auth(), 1..=3), + ], + ) + .prop_map(|(to, auths)| Shape::Eip7702 { to, auths }), + 3 => (who(), value(), 0u16..=100, prop_oneof![7 => Just(false), 1 => Just(true)], prop_oneof![4 => Just(false), 1 => Just(true)]) + .prop_map(|(to, mint, data_len, system, create)| Shape::Deposit { to, mint, data_len, system, create }), + mega_only => system_address, + mega_only => keyless, + ]; + shapes.prop_map(move |shape| match flavor { + Flavor::Satin => shape, + Flavor::Neutral => shape.neutralized(), + }) +} + +impl Shape { + /// The shape with what only `MegaETH` has replaced by a plain call. + fn neutralized(self) -> Self { + match self { + Self::SystemAddress { .. } | Self::Keyless { .. } => { + Self::Call { to: Who::Contract, data_len: 4, access_list: Vec::new() } + } + other => other, + } + } +} + +/// A transaction. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Tx { + pub(crate) shape: Shape, + pub(crate) value: Value, + pub(crate) gas: GasTier, + pub(crate) price: Price, + /// Whether the nonce is the sender's; otherwise one too high. + pub(crate) nonce_ok: bool, +} + +pub(crate) fn tx(flavor: Flavor) -> impl Strategy { + tx_of(shape(flavor)) +} + +/// A keyless deployment, and nothing else, its init code sometimes at the initcode size limit or +/// past it. +pub(crate) fn keyless_tx() -> impl Strategy { + tx_of(keyless_shape(init_size())) +} + +/// A transaction of a shape `shape` draws. +fn tx_of(shape: impl Strategy) -> impl Strategy { + // A keyless deployment draws its call's value and gas from generators of its own: the call + // takes no value, so any is one refusal, and its creation needs room to start. A + // system-address transaction draws the same value: its sender holds nothing to send. + let own_value = prop_oneof![12 => Just(Value::Zero), 1 => Just(Value::One)]; + let keyless_gas = prop_oneof![ + 1 => Just(GasTier::Small), + 6 => Just(GasTier::Medium), + 2 => Just(GasTier::Large), + 1 => Just(GasTier::AboveCap), + ]; + ( + shape, + (value(), own_value), + (gas_tier(), keyless_gas), + price(), + // A nonce one too high refuses the transaction: one case in twenty-four covers it. + prop_oneof![23 => Just(true), 1 => Just(false)], + ) + .prop_map(|(shape, (value, own_value), (gas, keyless_gas), price, nonce_ok)| { + let (value, gas) = match shape { + // Init code at the size limit is a mebibyte of calldata, whose history only the + // tier above the execution cap covers at the spec's byte prices. + Shape::Keyless { init_size: InitSize::Drawn, .. } => (own_value, keyless_gas), + Shape::Keyless { .. } => (own_value, GasTier::AboveCap), + Shape::SystemAddress { .. } => (own_value, gas), + _ => (value, gas), + }; + Tx { shape, value, gas, price, nonce_ok } + }) +} + +/// The transaction a keyless deployment carries: a pre-EIP-155 signed creation as Nick's Method +/// makes one — a fixed signature over a transaction nobody holds the key of, so the signer is +/// whatever the contents recover to — or one of the encodings the rules refuse. +#[derive(Clone, Debug)] +pub(crate) struct Deployment { + /// The signed transaction, RLP-encoded. + pub(crate) encoded: Bytes, + /// The signer the rules recover, when the transaction decodes and its signature recovers. + pub(crate) signer: Option
, + pub(crate) gas_limit: u64, +} + +impl Deployment { + pub(crate) fn new( + encoding: Encoding, + nonce: u64, + gas_limit: u64, + value: U256, + init_code: Bytes, + ) -> Self { + let tx = TxLegacy { + nonce, + gas_price: 100_000_000_000, + gas_limit, + to: match encoding { + Encoding::NotCreation => TxKind::Call(Who::A.address()), + _ => TxKind::Create, + }, + value, + input: init_code, + chain_id: (encoding == Encoding::Eip155).then_some(CHAIN_ID), + }; + let word = match encoding { + Encoding::BadSignature => U256::ZERO, + _ => U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )), + }; + let signed = Signed::new_unchecked(tx, Signature::new(word, word, false), B256::ZERO); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + match encoding { + Encoding::Truncated => encoded.truncate(encoded.len() / 2), + Encoding::Trailing => encoded.push(0), + _ => {} + } + let signer = match encoding { + Encoding::Valid => { + Some(signed.recover_signer().expect("a Nick's-Method signature recovers")) + } + _ => None, + }; + Self { encoded: encoded.into(), signer, gas_limit } + } + + /// The address the deployment deploys at: the signer's first creation. + pub(crate) fn deploy_address(&self) -> Option
{ + self.signer.map(|signer| signer.create(0)) + } +} + +impl Tx { + /// The deployment a keyless transaction carries, if it is one. + /// + /// A case asks for it three times — for its database, its transaction and the property — and + /// init code at the size limit is a mebibyte or two, which a debug build takes tens of + /// milliseconds to encode and recover the signer of, so the last one built on the thread is + /// kept. + pub(crate) fn deployment(&self) -> Option { + thread_local! { + static LAST: RefCell> = const { RefCell::new(None) }; + } + let Shape::Keyless { + init, + init_size, + encoding, + signed_nonce, + signed_value, + signed_gas, + .. + } = &self.shape + else { + return None; + }; + LAST.with_borrow_mut(|last| { + if let Some((_, deployment)) = last.as_ref().filter(|(shape, _)| *shape == self.shape) { + return Some(deployment.clone()); + } + let deployment = Deployment::new( + *encoding, + *signed_nonce as u64, + signed_gas.limit(), + signed_value.wei(), + init_size.pad(init.assemble()).into(), + ); + *last = Some((self.shape.clone(), deployment.clone())); + Some(deployment) + }) + } + + /// Whether the transaction is a deposit at the envelope level. + pub(crate) fn is_deposit(&self) -> bool { + matches!(self.shape, Shape::Deposit { .. }) + } + + /// The sender. + pub(crate) fn sender(&self) -> Address { + match self.shape { + Shape::SystemAddress { .. } => SYSTEM_ADDRESS, + _ => CALLER, + } + } + + /// The transaction as the engine takes it, over `world`, whose main program is `main`. + pub(crate) fn build(&self, world: &World, main: &[u8]) -> MegaTransaction { + let sender_nonce = world.nonce_of(self.sender()); + let nonce = if self.nonce_ok { sender_nonce } else { sender_nonce + 1 }; + let base = TxEnv { + caller: self.sender(), + gas_limit: self.gas.limit(), + gas_price: self.price.wei(), + value: self.value.wei(), + nonce, + chain_id: Some(CHAIN_ID), + ..Default::default() + }; + let env = match &self.shape { + Shape::Call { to, data_len, access_list } => { + let list = AccessList( + access_list + .iter() + .map(|(who, slots)| AccessListItem { + address: who.address(), + storage_keys: (0..*slots).map(B256::with_last_byte).collect(), + }) + .collect(), + ); + TxEnv { + tx_type: if list.0.is_empty() { + TransactionType::Legacy as u8 + } else { + TransactionType::Eip2930 as u8 + }, + kind: TxKind::Call(to.address()), + data: vec![0xab; *data_len as usize].into(), + access_list: list, + ..base + } + } + Shape::Create => TxEnv { kind: TxKind::Create, data: main.to_vec().into(), ..base }, + Shape::Eip7702 { to, auths } => TxEnv { + tx_type: TransactionType::Eip7702 as u8, + kind: TxKind::Call(to.address()), + gas_priority_fee: Some(self.price.wei()), + authorization_list: auths + .iter() + .map(|auth| { + let nonce = + world.nonce_of(auth.authority.address()) + u64::from(!auth.nonce_ok); + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: U256::from(if auth.chain_ok { CHAIN_ID } else { 9 }), + address: auth.delegate.address(), + nonce, + }, + if auth.recovers { + RecoveredAuthority::Valid(auth.authority.address()) + } else { + RecoveredAuthority::Invalid + }, + )) + }) + .collect(), + ..base + }, + Shape::Deposit { to, data_len, create, .. } => TxEnv { + tx_type: op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE, + kind: if *create { TxKind::Create } else { TxKind::Call(to.address()) }, + data: if *create { + main.to_vec().into() + } else { + vec![0xcd; *data_len as usize].into() + }, + gas_price: 0, + ..base + }, + Shape::SystemAddress { call, nonce_ok, chain_ok, off_whitelist } => { + let system_nonce = world.nonce_of(SYSTEM_ADDRESS); + TxEnv { + kind: TxKind::Call(if *off_whitelist { + Who::Contract.address() + } else { + ORACLE_CONTRACT_ADDRESS + }), + data: call.calldata(), + nonce: if *nonce_ok { system_nonce } else { system_nonce + 1 }, + chain_id: if *chain_ok { Some(CHAIN_ID) } else { Some(CHAIN_ID + 1) }, + ..base + } + } + Shape::Keyless { gas_override, .. } => { + let deployment = self.deployment().expect("a keyless shape"); + let gas_override = match gas_override { + Override::Zero => U256::ZERO, + Override::Signed => U256::from(deployment.gas_limit), + Override::Large => U256::from(10_000_000_000u64), + Override::Short => U256::from(deployment.gas_limit / 2), + }; + TxEnv { + kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), + data: IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: deployment.encoded, + gasLimitOverride: gas_override, + } + .abi_encode() + .into(), + ..base + } + } + }; + let mut tx = op_transaction(env); + if let Shape::Deposit { mint, system, .. } = &self.shape { + tx.deposit.source_hash = B256::repeat_byte(0x22); + tx.deposit.mint = Some(mint.wei().saturating_to()); + tx.deposit.is_system_transaction = *system; + } + OpTx(tx) + } +} diff --git a/crates/mega-evm/tests/fuzz/gen/world.rs b/crates/mega-evm/tests/fuzz/gen/world.rs new file mode 100644 index 000000000..4c2a14b61 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/gen/world.rs @@ -0,0 +1,366 @@ +//! The world a transaction runs in: the accounts, the SALT capacities, the Oracle's answers, the +//! block and the runtime limits. + +use alloy_primitives::{Address, U256}; +use mega_evm::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, MAX_TX_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, + EvmTxRuntimeLimits, MegaSpecId, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use proptest::prelude::*; + +use super::{word, Who, Word, BENEFICIARY, SYSTEM_ADDRESS}; + +/// A balance. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Balance { + Zero, + /// Ten million wei: a few values, no fees. + Small, + /// An ether: any fee the cases charge. + Rich, +} + +impl Balance { + pub(crate) fn wei(self) -> U256 { + match self { + Self::Zero => U256::ZERO, + Self::Small => U256::from(10_000_000u64), + Self::Rich => U256::from(10u64.pow(18)), + } + } +} + +fn balance() -> impl Strategy { + prop_oneof![2 => Just(Balance::Zero), 2 => Just(Balance::Small), 4 => Just(Balance::Rich)] +} + +/// An account of the pre-state. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct AccountShape { + pub(crate) balance: Balance, + pub(crate) nonce: u8, + /// Slots set before the transaction, so a write can restore one to its original value. + pub(crate) slots: Vec<(u8, Word)>, +} + +fn account() -> impl Strategy { + account_with(balance()) +} + +/// The sender's account: rich nearly always, so most transactions pay their way in. +fn sender() -> impl Strategy { + account_with( + prop_oneof![1 => Just(Balance::Zero), 2 => Just(Balance::Small), 21 => Just(Balance::Rich)], + ) +} + +fn account_with(balance: impl Strategy) -> impl Strategy { + (balance, 0u8..3, proptest::collection::vec((0u8..4, word()), 0..=2)) + .prop_map(|(balance, nonce, slots)| AccountShape { balance, nonce, slots }) +} + +/// Who the block beneficiary is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BeneficiaryIs { + /// The distinct beneficiary account. + Distinct, + /// `A`, so a call to `A` reads the beneficiary's account. + A, + /// The sender, so the transaction is detained from its start. + Caller, + /// The contract the transaction calls. + Contract, + /// An address with no account. + Fresh, +} + +fn beneficiary() -> impl Strategy { + prop_oneof![ + 4 => Just(BeneficiaryIs::Distinct), + 2 => Just(BeneficiaryIs::A), + 1 => Just(BeneficiaryIs::Caller), + 1 => Just(BeneficiaryIs::Contract), + 1 => Just(BeneficiaryIs::Fresh), + ] +} + +/// An EIP-7702 delegation in the pre-state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Delegation { + pub(crate) delegator: Who, + pub(crate) delegate: Who, +} + +fn delegation() -> impl Strategy> { + proptest::option::weighted( + 0.25, + ( + prop_oneof![Just(Who::Caller), Just(Who::A), Just(Who::B)], + prop_oneof![Just(Who::Contract), Just(Who::A), Just(Who::B), Just(Who::Beneficiary)], + ) + .prop_map(|(delegator, delegate)| Delegation { delegator, delegate }), + ) +} + +/// The SALT capacities: a default multiplier for every bucket, and the buckets of a few accounts +/// and slots crowded further. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Salt { + /// The multiplier of every bucket not named below, in minimum buckets. + pub(crate) default_multiplier: u8, + /// Accounts whose own bucket is crowded to the multiplier. + pub(crate) crowded_accounts: Vec<(Who, u8)>, + /// Slots whose bucket is crowded to the multiplier. + pub(crate) crowded_slots: Vec<(Who, u8, u8)>, + /// An account whose bucket cannot be read: a charge landing in it fails the transaction. + pub(crate) failing_account: Option, +} + +fn salt() -> impl Strategy { + ( + prop_oneof![6 => Just(1u8), 2 => Just(2), 1 => Just(3), 1 => Just(7)], + proptest::collection::vec((super::who(), 2u8..=9), 0..=2), + proptest::collection::vec((super::who(), 0u8..4, 2u8..=9), 0..=2), + proptest::option::weighted(0.1, super::who()), + ) + .prop_map(|(default_multiplier, crowded_accounts, crowded_slots, failing_account)| { + Salt { default_multiplier, crowded_accounts, crowded_slots, failing_account } + }) +} + +/// The transaction's data-size limit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DataLimit { + /// Exactly the body: the least a chain may set. + Body, + /// The body and one record. + BodyPlusRecord, + /// A few hundred bytes past the body. + Small(u16), + /// 100,000 bytes. + Medium, + Unlimited, +} + +impl DataLimit { + fn value(self) -> u64 { + match self { + Self::Body => TX_BODY_SIZE, + Self::BodyPlusRecord => TX_BODY_SIZE + WRITE_RECORD_SIZE, + Self::Small(extra) => TX_BODY_SIZE + extra as u64, + Self::Medium => 100_000, + Self::Unlimited => u64::MAX, + } + } +} + +/// A gas detention cap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DetentionCap { + /// 50,000: crossed by a few thousand instructions after the read. + Tiny, + /// 300,000. + Small, + /// 2,000,000. + Medium, + /// The spec's. + Default, + /// The most that still binds: one below what no transaction's compute reaches. + Max, +} + +impl DetentionCap { + fn value(self, spec: u64) -> u64 { + match self { + Self::Tiny => 50_000, + Self::Small => 300_000, + Self::Medium => 2_000_000, + Self::Default => spec, + Self::Max => MAX_TX_COMPUTE_GAS - 1, + } + } +} + +fn detention_cap() -> impl Strategy { + prop_oneof![ + 3 => Just(DetentionCap::Tiny), + 2 => Just(DetentionCap::Small), + 1 => Just(DetentionCap::Medium), + 3 => Just(DetentionCap::Default), + 1 => Just(DetentionCap::Max), + ] +} + +/// The runtime limits a transaction is held to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Limits { + /// The spec's: `ProtocolLimits::for_spec`. + Default, + /// Every limit unlimited, and detention's caps one below what no transaction's compute + /// reaches, so a read of volatile data still detains. + Loosest, + /// A valid set of tight limits. + Custom { + data: DataLimit, + frame_data: Option, + block_env_cap: DetentionCap, + oracle_cap: DetentionCap, + }, +} + +impl Limits { + /// The limits: none is zero, a transaction's data size holds its body, and detention's caps + /// bind. + pub(crate) fn runtime(self) -> EvmTxRuntimeLimits { + match self { + Self::Default => ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits, + Self::Loosest => EvmTxRuntimeLimits::no_limits() + .with_block_env_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1) + .with_oracle_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1), + Self::Custom { data, frame_data, block_env_cap, oracle_cap } => EvmTxRuntimeLimits { + tx_data_size_limit: data.value(), + frame_data_size_limit: frame_data.map_or(u64::MAX, u64::from), + block_env_access_compute_gas_limit: block_env_cap + .value(BLOCK_ENV_ACCESS_COMPUTE_GAS), + oracle_access_compute_gas_limit: oracle_cap.value(ORACLE_ACCESS_COMPUTE_GAS), + }, + } + } +} + +pub(crate) fn limits() -> impl Strategy { + let custom = ( + // The roomy data-size limits are drawn as often as the tight ones, so the compute stop is + // reached too. + prop_oneof![ + 1 => Just(DataLimit::Body), + 2 => Just(DataLimit::BodyPlusRecord), + 3 => (1u16..=2_000).prop_map(DataLimit::Small), + 3 => Just(DataLimit::Medium), + 3 => Just(DataLimit::Unlimited), + ], + proptest::option::weighted(0.3, prop_oneof![Just(1u16), Just(40), Just(200), Just(2_000)]), + detention_cap(), + detention_cap(), + ) + .prop_map(|(data, frame_data, block_env_cap, oracle_cap)| Limits::Custom { + data, + frame_data, + block_env_cap, + oracle_cap, + }); + prop_oneof![3 => Just(Limits::Default), 2 => Just(Limits::Loosest), 5 => custom] +} + +/// The block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BlockShape { + /// The base fee: zero, or seven, which a free transaction is refused under. + pub(crate) basefee: u64, + /// The slot number `SLOTNUM` reads, zero for a block that leaves it unset. + pub(crate) slot_num: u64, + /// Whether the block carries a blob price; one that does not refuses every transaction but a + /// deposit on its header. + pub(crate) blob: bool, +} + +fn block() -> impl Strategy { + // A base fee refuses every transaction priced below it, and a block with no blob price every + // transaction but a deposit: each is drawn often enough to be covered and no more. + ( + prop_oneof![15 => Just(0u64), 1 => Just(7)], + prop_oneof![1 => Just(0u64), 1 => Just(9)], + prop_oneof![31 => Just(true), 1 => Just(false)], + ) + .prop_map(|(basefee, slot_num, blob)| BlockShape { basefee, slot_num, blob }) +} + +/// The world a case runs in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct World { + pub(crate) caller: AccountShape, + pub(crate) contract: AccountShape, + pub(crate) a: AccountShape, + pub(crate) b: AccountShape, + /// The distinct beneficiary's balance. + pub(crate) beneficiary_balance: Balance, + pub(crate) beneficiary: BeneficiaryIs, + pub(crate) delegation: Option, + pub(crate) salt: Salt, + /// The Oracle's answers, by slot. + pub(crate) oracle: Vec<(u8, Word)>, + pub(crate) limits: Limits, + pub(crate) block: BlockShape, + /// The system address's nonce. + pub(crate) system_nonce: u8, +} + +impl World { + /// The nonce `address` has before the transaction. + pub(crate) fn nonce_of(&self, address: Address) -> u64 { + if address == Who::Caller.address() { + self.caller.nonce as u64 + } else if address == Who::Contract.address() { + self.contract.nonce as u64 + } else if address == Who::A.address() { + self.a.nonce as u64 + } else if address == Who::B.address() { + self.b.nonce as u64 + } else if address == SYSTEM_ADDRESS { + self.system_nonce as u64 + } else { + 0 + } + } + + /// The block beneficiary's address. + pub(crate) fn beneficiary_address(&self) -> Address { + match self.beneficiary { + BeneficiaryIs::Distinct => BENEFICIARY, + BeneficiaryIs::A => Who::A.address(), + BeneficiaryIs::Caller => Who::Caller.address(), + BeneficiaryIs::Contract => Who::Contract.address(), + BeneficiaryIs::Fresh => Who::Fresh.address(), + } + } +} + +pub(crate) fn world() -> impl Strategy { + ( + (sender(), account(), account(), account()), + balance(), + beneficiary(), + delegation(), + salt(), + proptest::collection::vec((0u8..4, word()), 0..=2), + limits(), + block(), + 0u8..2, + ) + .prop_map( + |( + (caller, contract, a, b), + beneficiary_balance, + beneficiary, + delegation, + salt, + oracle, + limits, + block, + system_nonce, + )| World { + caller, + contract, + a, + b, + beneficiary_balance, + beneficiary, + delegation, + salt, + oracle, + limits, + block, + system_nonce, + }, + ) +} diff --git a/crates/mega-evm/tests/fuzz/harness.rs b/crates/mega-evm/tests/fuzz/harness.rs new file mode 100644 index 000000000..befa05f50 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/harness.rs @@ -0,0 +1,401 @@ +//! The runner every property runs on: a seeded, bounded proptest run whose failure names the seed +//! that reproduces it and prints the case it shrank to, within the shrink limits below. +//! +//! Two modes, chosen by the environment: +//! +//! - **bounded** (the default): a fixed seed and a small number of cases per property, so the run +//! is deterministic and finishes in seconds for the whole target, in debug and in release; +//! - **long** (`MEGA_FUZZ_LONG=1`): many more cases and a seed drawn from the clock unless +//! `MEGA_FUZZ_SEED` names one; the seed is printed at the start of every property so a failure of +//! a long run is reproducible. +//! +//! `MEGA_FUZZ_CASES` replaces a property's case count in either mode: every property then runs +//! exactly that many cases, and the long mode's multiplier does not apply. A count of zero is +//! refused. `MEGA_FUZZ_SEED` names the seed in either mode. Either variable set to the empty +//! string counts as unset, so a caller that always exports them, as a workflow input does, need +//! not unset them. A failure panics with +//! the property's name, the reason, the seed and case count that reproduce the run and the minimal +//! failing case, as `Debug` renders it. + +use std::{fmt::Debug, time::SystemTime}; + +use proptest::{ + strategy::Strategy, + test_runner::{Config, RngAlgorithm, TestCaseError, TestError, TestRng, TestRunner}, +}; + +/// Names the number of cases each property runs. +pub(crate) const CASES_ENV_VAR: &str = "MEGA_FUZZ_CASES"; +/// Names the seed the cases are drawn from. +pub(crate) const SEED_ENV_VAR: &str = "MEGA_FUZZ_SEED"; +/// Set to anything but `0`, `false` or empty, switches the long mode on. +pub(crate) const LONG_ENV_VAR: &str = "MEGA_FUZZ_LONG"; + +/// How many times the long mode multiplies a property's bounded case count. +const LONG_MULTIPLIER: u32 = 50; + +/// The seed of a bounded run, when the environment names none. +const DEFAULT_SEED: u64 = 0; + +/// The stack of the thread a property runs on. +const STACK_SIZE: usize = 256 << 20; + +/// How a property runs: its case count, its seed and which mode chose them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct FuzzConfig { + /// Cases to run. + pub(crate) cases: u32, + /// The RNG seed. + pub(crate) seed: u64, + /// Whether the long mode is on. + pub(crate) long: bool, + /// Whether this is the reproducible default run: the bounded mode, the default seed and the + /// property's own bounded case count. + default_run: bool, +} + +impl FuzzConfig { + /// Reads the mode from the environment; `bounded_cases` is the property's case count in the + /// bounded mode. + pub(crate) fn from_env(bounded_cases: u32) -> Self { + let var = |name: &str| std::env::var(name).ok(); + Self::from_vars( + bounded_cases, + var(LONG_ENV_VAR).as_deref(), + var(CASES_ENV_VAR).as_deref(), + var(SEED_ENV_VAR).as_deref(), + || { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(DEFAULT_SEED) + }, + ) + } + + /// The mode the three variables choose, each `None` when unset; `clock` draws the long mode's + /// seed when none is named. + /// + /// - The long mode is on when its variable is anything but empty, `0` or `false`. + /// - A case count, when named, is the count: it replaces the bounded count and the long mode's + /// multiple of it alike. Unnamed, the count is the bounded one, times [`LONG_MULTIPLIER`] in + /// the long mode. Zero is refused: a property that runs no case passes without checking. + /// - A seed, when named, is the seed. Unnamed, the bounded mode's is [`DEFAULT_SEED`] and the + /// long mode's comes from the clock. + /// - An empty value is an unnamed one. + /// + /// # Panics + /// + /// When a case count or a seed is named and is not a number, or the case count is zero. + fn from_vars( + bounded_cases: u32, + long: Option<&str>, + cases: Option<&str>, + seed: Option<&str>, + clock: impl FnOnce() -> u64, + ) -> Self { + fn named(value: Option<&str>) -> Option<&str> { + value.map(str::trim).filter(|v| !v.is_empty()) + } + let long = named(long).is_some_and(|v| !matches!(v, "0" | "false")); + let cases = match named(cases) { + Some(v) => { + let cases: u32 = + v.parse().unwrap_or_else(|_| panic!("{CASES_ENV_VAR}={v:?} is not a number")); + assert!(cases != 0, "{CASES_ENV_VAR} must name at least one case"); + cases + } + None if long => bounded_cases.saturating_mul(LONG_MULTIPLIER), + None => bounded_cases, + }; + let seed = match named(seed) { + Some(v) => v.parse().unwrap_or_else(|_| panic!("{SEED_ENV_VAR}={v:?} is not a number")), + None if long => clock(), + None => DEFAULT_SEED, + }; + let default_run = !long && seed == DEFAULT_SEED && cases == bounded_cases; + Self { cases, seed, long, default_run } + } + + /// Whether a coverage claim ("the generators reach every class") is checkable on this run. + /// + /// Only the default run draws the same cases on every machine, so only there can a claim about + /// what the generators reach be verified once and then held; any other seed or count draws + /// cases nobody has checked, and a class may legitimately be missed. + pub(crate) fn requires_coverage(&self) -> bool { + self.default_run + } + + /// The RNG the cases are drawn from: `ChaCha` seeded from the seed, so the same seed draws the + /// same cases on every platform. + fn rng(&self) -> TestRng { + let mut bytes = [0u8; 32]; + bytes[..8].copy_from_slice(&self.seed.to_le_bytes()); + TestRng::from_seed(RngAlgorithm::ChaCha, &bytes) + } + + fn proptest_config(&self) -> Config { + Config { + cases: self.cases, + // Failures are reproduced from the printed seed, not from a regressions file. + failure_persistence: None, + source_file: None, + // Shrinking re-executes the property on every candidate; cap the time so a failing + // run in CI still reports a case, minimal or not, well within the job's timeout. + max_shrink_time: 120_000, + max_shrink_iters: 4_096, + ..Config::default() + } + } +} + +/// Runs `property` on cases drawn from the strategy `strategy` builds, in the mode the environment +/// chooses, and panics with a reproducible report on the first failure. The strategy is built on +/// the property's own thread, because a boxed strategy cannot be sent to one. +/// +/// `bounded_cases` is the property's case count in the bounded mode: enough to hit every arm of +/// the generators, few enough for the whole target to finish well within a minute in debug. +pub(crate) fn check( + name: &str, + bounded_cases: u32, + strategy: impl FnOnce() -> S + Send, + property: impl Fn(&S::Value) -> Result<(), TestCaseError> + Send, +) where + S: Strategy, + S::Value: Debug + Send, +{ + let config = FuzzConfig::from_env(bounded_cases); + if config.long { + eprintln!( + "{name}: long mode, {} cases; reproduce with {SEED_ENV_VAR}={} {CASES_ENV_VAR}={}", + config.cases, config.seed, config.cases + ); + } + // A case can nest creations and calls deep, and a minimal case is rendered whole: run on a + // thread with a stack the harness's default does not give. + let outcome = std::thread::scope(|scope| { + std::thread::Builder::new() + .name(format!("fuzz-{name}")) + .stack_size(STACK_SIZE) + .spawn_scoped(scope, move || { + let strategy = strategy(); + let mut runner = TestRunner::new_with_rng(config.proptest_config(), config.rng()); + runner.run(&strategy, |case| property(&case)) + }) + .expect("the property's thread starts") + .join() + .unwrap_or_else(|_| panic!("property `{name}` panicked outside a case")) + }); + match outcome { + Ok(()) => {} + Err(TestError::Fail(reason, minimal)) => panic!( + "property `{name}` failed: {reason}\n\ + reproduce with {SEED_ENV_VAR}={} {CASES_ENV_VAR}={}\n\ + minimal failing case:\n{minimal:#?}", + config.seed, config.cases + ), + Err(TestError::Abort(reason)) => panic!( + "property `{name}` aborted: {reason}\n\ + reproduce with {SEED_ENV_VAR}={} {CASES_ENV_VAR}={}", + config.seed, config.cases + ), + } +} + +/// Whether this process prices bytes at something other than the constants. +/// +/// Only a measurement build can arrange that, through the `satin-price-override` feature. A +/// coverage minimum that a bounded run meets at the spec's prices, and a minimal case pinned at +/// those prices, belongs to the constants: the caller leaves it out here, and this leaves the note +/// the byte-price grid counts. +pub(crate) fn runs_at_measurement_prices() -> bool { + if mega_evm::active_satin_prices().is_constants() { + return false; + } + mega_evm::test_utils::note_price_guard(&format!( + "{} or {} fixed prices other than the spec's", + mega_evm::CPSB_ENV_VAR, + mega_evm::CPHB_ENV_VAR + )); + true +} + +/// Holds a property's coverage claim: `missing` lists the classes its run did not reach. +/// +/// On the default run (see [`FuzzConfig::requires_coverage`]) and at the spec's byte prices a +/// missing class panics. On any other run, and at other byte prices, where a class can be +/// unreachable, the classes are printed as a note and the property passes. +pub(crate) fn require_coverage(name: &str, bounded_cases: u32, missing: &[String]) { + // Called first so a measurement build always leaves its price-guard note. + let measurement_prices = runs_at_measurement_prices(); + if missing.is_empty() { + return; + } + let config = FuzzConfig::from_env(bounded_cases); + assert!( + !config.requires_coverage() || measurement_prices, + "{name}: not reached: {}", + missing.join("; ") + ); + eprintln!( + "{name}: note: not reached on this run (seed {}, {} cases): {}", + config.seed, + config.cases, + missing.join("; ") + ); +} + +/// Prints what a property counted along its run, one line per class under the property's name, +/// in one write, so the tallies of properties running side by side do not interleave. +pub(crate) fn print_tally( + name: &str, + tally: impl IntoIterator, +) { + let mut out = format!("{name}:\n"); + for (class, n) in tally { + out.push_str(&format!("{n:7} {class}\n")); + } + print!("{out}"); +} + +/// Fails the running case with `message`, as a property does when it finds a counterexample. +pub(crate) fn fail(message: impl Into) -> TestCaseError { + TestCaseError::fail(message.into()) +} + +/// Asserts `left == right` inside a property, failing the case with `what` and both sides. +macro_rules! prop_eq { + ($left:expr, $right:expr, $($what:tt)+) => {{ + let (left, right) = (&$left, &$right); + if left != right { + return Err($crate::harness::fail(format!( + "{}\n left: {left:?}\n right: {right:?}", + format_args!($($what)+) + ))); + } + }}; +} + +/// Asserts `cond` inside a property, failing the case with `what`. +macro_rules! prop_check { + ($cond:expr, $($what:tt)+) => {{ + if !$cond { + return Err($crate::harness::fail(format!($($what)+))); + } + }}; +} + +pub(crate) use prop_check; +pub(crate) use prop_eq; + +#[cfg(test)] +mod tests { + use super::*; + + const BOUNDED: u32 = 256; + const CLOCK: u64 = 77; + + fn config(long: Option<&str>, cases: Option<&str>, seed: Option<&str>) -> FuzzConfig { + FuzzConfig::from_vars(BOUNDED, long, cases, seed, || CLOCK) + } + + /// Every combination of the three variables unset, empty and set: the mode, the case count + /// and the seed each chooses. + #[test] + fn test_the_mode_the_environment_chooses() { + let unset_or_empty = [None, Some(""), Some(" ")]; + for long_off in [None, Some(""), Some("0"), Some("false")] { + for cases in unset_or_empty { + for seed in unset_or_empty { + assert_eq!( + config(long_off, cases, seed), + FuzzConfig { + cases: BOUNDED, + seed: DEFAULT_SEED, + long: false, + default_run: true + }, + "the bounded mode: {long_off:?} {cases:?} {seed:?}" + ); + } + } + assert_eq!( + config(long_off, Some("5000"), Some("9")), + FuzzConfig { cases: 5_000, seed: 9, long: false, default_run: false }, + "the bounded mode takes a case count and a seed" + ); + } + for long_on in [Some("1"), Some("true"), Some("yes")] { + for cases in unset_or_empty { + for seed in unset_or_empty { + assert_eq!( + config(long_on, cases, seed), + FuzzConfig { + cases: BOUNDED * LONG_MULTIPLIER, + seed: CLOCK, + long: true, + default_run: false + }, + "the long mode: {long_on:?} {cases:?} {seed:?}" + ); + } + assert_eq!( + config(long_on, cases, Some("9")), + FuzzConfig { + cases: BOUNDED * LONG_MULTIPLIER, + seed: 9, + long: true, + default_run: false + }, + "a named seed replaces the clock's" + ); + } + assert_eq!( + config(long_on, Some("20000"), None), + FuzzConfig { cases: 20_000, seed: CLOCK, long: true, default_run: false }, + "a named case count is the count: the multiplier does not apply to it" + ); + assert_eq!( + config(long_on, Some(" 20000 "), Some(" 9 ")), + FuzzConfig { cases: 20_000, seed: 9, long: true, default_run: false }, + "surrounding blanks are ignored" + ); + } + } + + /// Coverage is required only for the default bounded run. + #[test] + fn test_coverage_is_required_only_on_the_default_run() { + assert!(config(None, None, None).requires_coverage()); + assert!(config(Some("0"), Some(""), Some("")).requires_coverage()); + assert!(config(None, Some("256"), Some("0")).requires_coverage(), "named, but the default"); + assert!(!config(None, None, Some("5")).requires_coverage(), "a named seed"); + assert!(!config(None, Some("10"), None).requires_coverage(), "a named count"); + assert!(!config(Some("1"), None, None).requires_coverage(), "the long mode"); + assert!(!config(Some("1"), None, Some("0")).requires_coverage(), "long, seed 0"); + } + + #[test] + #[should_panic(expected = "MEGA_FUZZ_CASES=\"many\" is not a number")] + fn test_a_case_count_that_is_not_a_number_is_refused() { + config(None, Some("many"), None); + } + + #[test] + #[should_panic(expected = "MEGA_FUZZ_CASES must name at least one case")] + fn test_a_case_count_of_zero_is_refused() { + config(None, Some("0"), None); + } + + #[test] + #[should_panic(expected = "MEGA_FUZZ_CASES must name at least one case")] + fn test_a_blank_padded_case_count_of_zero_is_refused() { + config(Some("1"), Some(" 0 "), Some("9")); + } + + #[test] + #[should_panic(expected = "MEGA_FUZZ_SEED=\"lucky\" is not a number")] + fn test_a_seed_that_is_not_a_number_is_refused() { + config(Some("1"), None, Some("lucky")); + } +} diff --git a/crates/mega-evm/tests/fuzz/keyless.rs b/crates/mega-evm/tests/fuzz/keyless.rs new file mode 100644 index 000000000..9f5a4d876 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/keyless.rs @@ -0,0 +1,342 @@ +//! Keyless deployments held to their rules. +//! +//! Among every shape a transaction can take, a bounded run draws too few keyless deployments to +//! reach each rule, so this property draws nothing else: a `keylessDeploy` call over a signer and +//! a deploy address the generators set up — the signer's nonce, funds and code, a contract, a +//! balance or a nonce at the deploy address — carrying a transaction that may be encoded as the +//! rules want it or not, signed at a nonce and for a gas limit that may or may not pass, with init +//! code that may be at the initcode size limit or past it. +//! +//! The rules are restated here from the generator's own fields, in the order the spec gives them, +//! so the property holds the engine to the order as well as to each rule. + +use std::{collections::BTreeMap, sync::Mutex}; + +use alloy_primitives::{Address, KECCAK256_EMPTY, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{constants::MAX_INITCODE_SIZE, system::keyless::IKeylessDeploy, MegaLimitExceeded}; +use revm::context::result::{ExecutionResult, HaltReason}; + +use crate::{ + gen::{ + case::{keyless_case, Case}, + tx::{DeployAddress, Encoding, InitSize, Override, Shape, SignerCode}, + Value, + }, + harness::{check, fail, print_tally, prop_check, prop_eq, require_coverage}, + render::render_outcome, +}; + +/// The number of keyless cases the property runs in the bounded mode. +const CASES: u32 = 512; + +/// The contract's errors, by selector. +fn error_name(data: &[u8]) -> &'static str { + macro_rules! names { + ($($error:ident),* $(,)?) => { + match data.get(..4) { + $(Some(selector) if selector == IKeylessDeploy::$error::SELECTOR => { + stringify!($error) + })* + Some(selector) if selector == MegaLimitExceeded::SELECTOR => "MegaLimitExceeded", + _ => "an unknown error", + } + }; + } + names!( + MalformedEncoding, + NotContractCreation, + NotPreEIP155, + NonZeroTxNonce, + NoEtherTransfer, + InvalidSignature, + InsufficientBalance, + ContractAlreadyExists, + SignerNonceTooHigh, + ExecutionReverted, + ExecutionHalted, + EmptyCodeDeployed, + NoContractCreated, + AddressMismatch, + GasLimitTooLow, + InitCodeTooLarge, + SignerHasCode, + NotIntercepted, + ) +} + +/// The errors the spec says no deployment produces. +const NEVER_PRODUCED: [&str; 3] = ["AddressMismatch", "NoContractCreated", "NotIntercepted"]; + +/// What the generator's fields say of a keyless call, rule by rule. +struct Rules { + /// The first rule that refuses the call whatever gas it has, in the spec's order: the call's + /// value, the encoding, the signed nonce, the init code's size, the override against the + /// signed gas limit, the signature, the signer's nonce, the signer's code. `None` when each + /// admits it. + refused: Option<&'static str>, + /// The size of the init code the carried transaction holds. + init_size: usize, + /// Whether the deploy address holds a contract, which refuses the call once the rules above + /// and the gas admit it. + exists: bool, + /// Whether the signer cannot fund the carried value, which refuses it after that. + underfunded: bool, +} + +fn rules(case: &Case) -> Rules { + let Shape::Keyless { + init, + init_size, + encoding, + signed_nonce, + signed_value, + gas_override, + signer, + deploy_address, + .. + } = &case.tx.shape + else { + unreachable!("a keyless case") + }; + let init_size = init_size.size(init.assemble().len()); + let refused = if case.tx.value != Value::Zero { + Some("NoEtherTransfer") + } else if matches!(encoding, Encoding::Truncated | Encoding::Trailing) { + Some("MalformedEncoding") + } else if *encoding == Encoding::NotCreation { + Some("NotContractCreation") + } else if *encoding == Encoding::Eip155 { + Some("NotPreEIP155") + } else if *signed_nonce != 0 { + Some("NonZeroTxNonce") + } else if init_size > MAX_INITCODE_SIZE { + Some("InitCodeTooLarge") + } else if matches!(gas_override, Override::Zero | Override::Short) { + Some("GasLimitTooLow") + } else if *encoding == Encoding::BadSignature { + Some("InvalidSignature") + } else if signer.nonce > 1 { + Some("SignerNonceTooHigh") + } else if signer.code == SignerCode::Plain { + Some("SignerHasCode") + } else { + None + }; + let balance = if signer.funded { U256::from(10u64.pow(18)) } else { U256::ZERO }; + Rules { + refused, + init_size, + exists: *deploy_address == DeployAddress::Code, + underfunded: balance < signed_value.wei(), + } +} + +/// A `keylessDeploy` call follows its rules, in their order, and settles its signer: +/// +/// - a call a rule refuses whatever its gas reverts with that rule's error, the first in the spec's +/// order, unless it ran out of gas before or a limit stopped it, and init code over the initcode +/// size limit is refused naming its size and the limit; +/// - a call those rules admit reverts only with `GasLimitTooLow`, when what it has left no longer +/// covers the signed gas limit, with `ContractAlreadyExists` when the deploy address holds a +/// contract, with `InsufficientBalance` when the signer cannot fund the carried value, or with a +/// stop of its own frame — its budget, or a limit its own charges cross — which is the +/// transaction's own frame's and so the limit stop the transaction reports, its revert data the +/// stop's; a limit its creation crosses is the creation's stop, which the call answers; +/// - a call that succeeds started its creation, so no rule refused it, and answers the deploy +/// address with no error when the address holds code afterwards, and otherwise the zero address +/// with `ExecutionReverted`, `ExecutionHalted` or `EmptyCodeDeployed`, the address then holding +/// the code it held before; +/// - the signer's nonce is 1 after a call that succeeds, from 0 by the creation's bump and from 1 +/// by taking the bump back, or above when the signer delegates, since its code may then spend +/// nonces of its own; and it is unchanged after a call that does not succeed; +/// - the errors the spec says no deployment produces never appear, in the revert data or in the +/// answer. +/// +/// The tally of outcomes is printed, so a run shows which rules the generators reached. +#[test] +fn test_property_a_keyless_deployment_follows_its_rules() { + let tally: Mutex> = Mutex::new(BTreeMap::new()); + check("keyless_deployment_follows_its_rules", CASES, keyless_case, |case| { + let count = |class: String| *tally.lock().unwrap().entry(class).or_default() += 1; + let Shape::Keyless { signer, init_size, .. } = &case.tx.shape else { + unreachable!("a keyless case") + }; + let Ok(outcome) = case.execute() else { + count("the transaction is refused".to_string()); + return Ok(()); + }; + let rendered = render_outcome(&outcome); + let rules = rules(case); + let deployment = case.tx.deployment().expect("a keyless case"); + let nonce_of = |address: Option
| { + address.and_then(|address| outcome.state.get(&address)).map(|a| a.info.nonce) + }; + // The code the deploy address holds once the transaction's state is committed: an account + // its constructor destroyed is removed then, whatever code the creation deposited. + let code_at_deploy_address = deployment + .deploy_address() + .and_then(|address| outcome.state.get(&address)) + .map(|account| match account.is_selfdestructed() { + true => KECCAK256_EMPTY, + false => account.info.code_hash, + }); + + if !outcome.result.is_success() { + prop_check!( + nonce_of(deployment.signer).is_none_or(|nonce| nonce == u64::from(signer.nonce)), + "a call that does not succeed leaves the signer's nonce\n{rendered}" + ); + } + match &outcome.result { + ExecutionResult::Halt { reason, .. } => { + prop_check!( + matches!(reason, mega_evm::MegaHaltReason::Base(HaltReason::OutOfGas(_))), + "a keyless call halts only out of gas: {reason:?}\n{rendered}" + ); + count("the call runs out of gas".to_string()); + } + ExecutionResult::Revert { output, .. } + if outcome.limit_exceeded.is_some_and(|stop| stop.is_frame_local()) => + { + prop_eq!(error_name(output), "MegaLimitExceeded", "its budget's stop\n{rendered}"); + prop_eq!( + rules.refused, + None, + "the call's own budget stops only a call no rule refuses\n{rendered}" + ); + count("the call's own frame budget stops it".to_string()); + } + ExecutionResult::Revert { output, .. } if outcome.limit_exceeded.is_some() => { + let stop = outcome.limit_exceeded.expect("a stop"); + prop_eq!(*output, stop.revert_data(), "the call's own stop\n{rendered}"); + count("a limit stops the call".to_string()); + } + ExecutionResult::Revert { output, .. } => { + let error = error_name(output); + prop_check!( + !NEVER_PRODUCED.contains(&error) && error != "an unknown error", + "the call reverts with {error}\n{rendered}" + ); + if error == "InitCodeTooLarge" { + let Ok(refusal) = IKeylessDeploy::InitCodeTooLarge::abi_decode(output) else { + return Err(fail(format!("the refusal does not decode\n{rendered}"))); + }; + prop_eq!( + (refusal.size, refusal.max), + (rules.init_size as u64, MAX_INITCODE_SIZE as u64), + "the refusal names the init code's size and the limit\n{rendered}" + ); + } + match rules.refused { + Some(rule) => prop_eq!( + error, + rule, + "the call is refused by the first rule in order\n{rendered}" + ), + None => prop_check!( + error == "GasLimitTooLow" || + (error == "ContractAlreadyExists" && rules.exists) || + (error == "InsufficientBalance" && rules.underfunded), + "the call is refused {error}, which no rule gives it\n{rendered}" + ), + } + count(format!("refused {error}")); + } + ExecutionResult::Success { output, .. } => { + prop_eq!( + (rules.refused, rules.exists, rules.underfunded), + (None, false, false), + "a call a rule refuses succeeded\n{rendered}" + ); + let Ok(answer) = + IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + else { + return Err(fail(format!("the answer does not decode\n{rendered}"))); + }; + let deploy_address = deployment.deploy_address().expect("a signer was recovered"); + if answer.deployedAddress == Address::ZERO { + let error = error_name(&answer.errorData); + prop_check!( + matches!( + error, + "ExecutionReverted" | "ExecutionHalted" | "EmptyCodeDeployed" + ), + "a failed deployment answers {error}\n{rendered}" + ); + prop_check!( + code_at_deploy_address.is_none_or(|hash| hash == KECCAK256_EMPTY), + "a failed deployment leaves no code\n{rendered}" + ); + count(format!("the creation fails: {error}")); + } else { + prop_eq!(answer.deployedAddress, deploy_address, "the address\n{rendered}"); + prop_check!( + answer.errorData.is_empty(), + "a deployment answers no error\n{rendered}" + ); + prop_check!( + code_at_deploy_address.is_some_and(|hash| hash != KECCAK256_EMPTY), + "a deployment leaves code at the deploy address\n{rendered}" + ); + count("deployed".to_string()); + } + let nonce = nonce_of(deployment.signer); + if matches!(signer.code, SignerCode::Delegates(_)) { + prop_check!( + nonce.is_some_and(|nonce| nonce >= 1), + "a delegating signer's nonce is at least 1\n{rendered}" + ); + if nonce.is_some_and(|nonce| nonce > 1) { + count(" the signer's own code spent a nonce".to_string()); + } + } else { + prop_eq!(nonce, Some(1), "the signer's nonce is 1\n{rendered}"); + } + if signer.nonce == 1 && nonce == Some(1) { + count(" the creation's bump is taken back from nonce 1".to_string()); + } + if *init_size == InitSize::AtLimit { + count( + " init code at the initcode size limit started its creation".to_string(), + ); + } + } + } + Ok(()) + }); + let tally = tally.into_inner().unwrap(); + print_tally("keyless_deployment_follows_its_rules", tally.iter().map(|(k, n)| (k, *n))); + // The default bounded run at the spec's byte prices reaches every class below, and fails if + // one is missed. Any other run (a named seed or count, the long mode) draws cases nobody has + // checked, so a missed class is printed as a note; at another byte price a class can be + // unreachable — a large initcode is refused before `InitCodeTooLarge`. The signer's own code + // spending a nonce needs a delegated signer whose code bumps a nonce, which these cases do + // not draw, so that class is checked when a case reaches it and is not required here. + let missing: Vec = [ + "refused NoEtherTransfer", + "refused MalformedEncoding", + "refused NotContractCreation", + "refused NotPreEIP155", + "refused NonZeroTxNonce", + "refused InitCodeTooLarge", + "refused GasLimitTooLow", + "refused InvalidSignature", + "refused SignerNonceTooHigh", + "refused SignerHasCode", + "refused ContractAlreadyExists", + "refused InsufficientBalance", + "the call's own frame budget stops it", + "deployed", + "the creation fails: ExecutionReverted", + "the creation fails: ExecutionHalted", + "the creation fails: EmptyCodeDeployed", + " the creation's bump is taken back from nonce 1", + " init code at the initcode size limit started its creation", + ] + .into_iter() + .filter(|class| tally.get(*class).copied().unwrap_or(0) == 0) + .map(str::to_string) + .collect(); + require_coverage("keyless_deployment_follows_its_rules", CASES, &missing); +} diff --git a/crates/mega-evm/tests/fuzz/main.rs b/crates/mega-evm/tests/fuzz/main.rs new file mode 100644 index 000000000..03b66832d --- /dev/null +++ b/crates/mega-evm/tests/fuzz/main.rs @@ -0,0 +1,17 @@ +//! Randomized tests of the Satin engine: properties it must hold on any input, and a differential +//! under the neutral configuration against the fork's op-revm and revm's mainnet EVM. +//! +//! The generators are in `gen`, the runner in `harness`; each property is one test. See the +//! module docs of `harness` for the two modes and how a failure is reproduced. + +mod blocks; +mod differential; +mod gen; +mod harness; +mod keyless; +mod prices; +mod properties; +mod regressions; +mod render; +#[path = "../shared/snapshot.rs"] +mod snapshot; diff --git a/crates/mega-evm/tests/fuzz/prices.rs b/crates/mega-evm/tests/fuzz/prices.rs new file mode 100644 index 000000000..7f26a1bda --- /dev/null +++ b/crates/mega-evm/tests/fuzz/prices.rs @@ -0,0 +1,199 @@ +//! The byte prices as an axis. +//! +//! The prices are fixed once per process, so a transaction cannot be run at two prices in one +//! test. Two things can be checked all the same: +//! +//! - the schedule built from the prices is monotone in them, in the process, through the pure +//! builder `satin_gas_params_at`: every state-gas entry grows with the cost per state byte, the +//! deposited code's history entry with the cost per history byte, nothing else moves, and the gas +//! a byte count costs grows with the price and with the count; +//! - the outcome of a transaction at one price against the same transaction at another, across two +//! processes: under the `satin-price-override` feature, the record test writes what every case +//! spent to the file `MEGA_FUZZ_PRICE_RECORD` names, and `scripts/fuzz_price_monotonic.py` +//! compares two records. Where the two runs followed the same path — the same result kind, logs, +//! output and state but for balances — the state gas is monotone in the cost per state byte and +//! the history gas in the cost per history byte. Where the path differs (a limit stopped one run, +//! an out-of-gas came sooner), nothing is implied: a dearer byte can make a transaction spend +//! less in total by stopping it earlier, so total gas is not monotone and is not asserted. + +use mega_evm::{ + satin_gas_params_at, BytePrice, SatinPrices, HISTORY_GAS_PRICED, STATE_GAS_REPRICED, +}; +use proptest::prelude::*; +use revm::context_interface::cfg::GasId; + +use crate::harness::{check, prop_check, prop_eq}; + +/// A price in milli-gas per byte, up to twenty times the dearest candidate. +fn milli_price() -> impl Strategy { + prop_oneof![ + 1 => Just(0u64), + 1 => Just(1), + 2 => 1u64..=1_000, + 4 => 1_000u64..=200_000_000, + ] +} + +/// The schedule is monotone in the byte prices: every state-gas entry grows with the cost per +/// state byte, the deposited code's history entry with the cost per history byte, and every other +/// entry stands; and the gas a byte count costs grows with the price and with the count. +#[test] +fn test_property_schedule_is_monotone_in_the_byte_prices() { + check( + "schedule_is_monotone_in_the_byte_prices", + 256, + || (milli_price(), milli_price(), milli_price(), milli_price(), 0u64..=100_000), + |&(a, b, cphb, cphb2, bytes)| { + let (low, high) = (a.min(b), a.max(b)); + let at = |cpsb: u64, cphb: u64| { + satin_gas_params_at(SatinPrices { + cpsb: BytePrice::from_milli_gas(cpsb), + cphb: BytePrice::from_milli_gas(cphb), + }) + }; + let state_entries: Vec = + STATE_GAS_REPRICED.iter().map(|(id, _)| id().as_usize()).collect(); + let history_entries: Vec = + HISTORY_GAS_PRICED.iter().map(|(id, _)| id().as_usize()).collect(); + // Along the cost per state byte: the state-gas entries grow, everything else stands. + let (lower, higher) = (at(low, cphb), at(high, cphb)); + for (index, (l, h)) in lower.table().iter().zip(higher.table().iter()).enumerate() { + if state_entries.contains(&index) { + prop_check!( + l <= h, + "a state-gas entry falls as the cost per state byte rises: {index}" + ); + } else { + prop_eq!( + l, + h, + "an entry the cost per state byte does not set moved: {:?}", + GasId::new(index as u8) + ); + } + } + // Along the cost per history byte: the one history entry revm charges itself, the + // deposited code's, grows, and everything else stands. + let (lo_h, hi_h) = (cphb.min(cphb2), cphb.max(cphb2)); + let (lower, higher) = (at(low, lo_h), at(low, hi_h)); + for (index, (l, h)) in lower.table().iter().zip(higher.table().iter()).enumerate() { + if history_entries.contains(&index) { + prop_check!( + l <= h, + "a history entry falls as the cost per history byte rises: {index}" + ); + } else { + prop_eq!( + l, + h, + "an entry the cost per history byte does not set moved: {:?}", + GasId::new(index as u8) + ); + } + } + + let (cheap, dear) = ( + BytePrice::from_milli_gas(cphb.min(cphb2)), + BytePrice::from_milli_gas(cphb.max(cphb2)), + ); + prop_check!( + cheap.gas_for(bytes).unwrap_or(u64::MAX) <= dear.gas_for(bytes).unwrap_or(u64::MAX), + "the gas a byte count costs falls as the price rises" + ); + prop_check!( + dear.gas_for(bytes).unwrap_or(u64::MAX) <= + dear.gas_for(bytes.saturating_add(1)).unwrap_or(u64::MAX), + "the gas a byte count costs falls as the count grows" + ); + // A fixed-size item is a record or a body: the helper takes at most a thousand bytes. + let fixed = bytes.min(1_000); + prop_check!( + cheap.fixed_size_gas(fixed) <= dear.fixed_size_gas(fixed), + "the fixed-size gas falls as the price rises" + ); + Ok(()) + }, + ); +} + +/// Under the `satin-price-override` feature, when `MEGA_FUZZ_PRICE_RECORD` names a file, writes +/// one line per case — its index, the prices in effect, the result kind, the state and history +/// gas, the history bytes, the gas used, and a hash of the path the transaction followed — so two +/// runs at two prices can be compared with `scripts/fuzz_price_monotonic.py`. +#[cfg(feature = "satin-price-override")] +#[test] +fn test_property_price_record() { + use std::io::Write as _; + + use crate::{ + gen::{case::case, Flavor}, + render::render_state, + }; + use revm::context::result::ExecutionResult; + + let Ok(path) = std::env::var("MEGA_FUZZ_PRICE_RECORD") else { return }; + let prices = mega_evm::active_satin_prices(); + let lines = std::sync::Mutex::new(Vec::new()); + let index = std::sync::atomic::AtomicU64::new(0); + check( + "price_record", + 512, + || case(Flavor::Satin), + |case| { + let i = index.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let line = match case.execute() { + Ok(outcome) => { + let kind = match &outcome.result { + ExecutionResult::Success { .. } => "success", + ExecutionResult::Revert { .. } => "revert", + ExecutionResult::Halt { .. } => "halt", + }; + let mut path = String::new(); + path.push_str(&format!( + "{:?}|{:?}|", + outcome.result.logs(), + outcome.result.output() + )); + let mut state = render_state(&outcome.state); + // Balances move with the fees, which move with the prices: they are not the + // path. + state = state + .lines() + .map(|line| match line.find(" balance=") { + Some(start) => { + let end = line[start + 1..] + .find(' ') + .map_or(line.len(), |e| start + 1 + e); + format!("{}{}", &line[..start], &line[end..]) + } + None => line.to_string(), + }) + .collect::>() + .join("\n"); + path.push_str(&state); + format!( + "{i} {} {} {kind} {} {} {} {} {}", + prices.cpsb.milli_gas(), + prices.cphb.milli_gas(), + outcome.gas.state, + outcome.gas.history, + outcome.gas.history_bytes, + outcome.gas.gas_used, + alloy_primitives::keccak256(path.as_bytes()) + ) + } + Err(_) => format!( + "{i} {} {} refused 0 0 0 0 0x", + prices.cpsb.milli_gas(), + prices.cphb.milli_gas() + ), + }; + lines.lock().unwrap().push(line); + Ok(()) + }, + ); + let mut file = std::fs::File::create(&path).expect("the record is written"); + for line in lines.lock().unwrap().iter() { + writeln!(file, "{line}").expect("the record is written"); + } +} diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs new file mode 100644 index 000000000..a712a150d --- /dev/null +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -0,0 +1,633 @@ +//! The properties a single transaction must hold, one test each. +//! +//! Every property draws its cases from the same generators, runs the case on a fresh EVM and +//! states what the spec says of the outcome. A property that does not hold by design is stated +//! as what does hold, and says so. + +use std::{collections::BTreeMap, sync::Mutex}; + +use alloy_primitives::{Address, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + system::is_system_originated, + test_utils::{GasInspector, MemoryDatabase}, + transaction_body_bytes, LimitCheck, LimitKind, MegaContext, MegaTransaction, + MegaTransactionOutcome, WRITE_RECORD_SIZE, +}; +use revm::{ + context::{result::ExecutionResult, Transaction}, + interpreter::{interpreter::EthInterpreter, Interpreter}, + state::Bytecode, + Database, Inspector, +}; +use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; + +use crate::{ + gen::{ + case::{case, Case, Envs}, + tx::{tx, Delegate, Shape}, + Flavor, Who, SYSTEM_ADDRESS, + }, + harness::{check, print_tally, prop_check, prop_eq}, + render::{render, render_outcome}, +}; + +/// The number of cases each property runs in the bounded mode. +const CASES: u32 = 768; + +/// The same input twice gives byte-identical outcomes: the result, its gas, logs and output, the +/// gas by ledger, the usage, the stop and the state, or the same refusal. +#[test] +fn test_property_determinism() { + check( + "determinism", + CASES, + || case(Flavor::Satin), + |case| { + let first = render(&case.execute()); + let second = render(&case.execute()); + prop_eq!(first, second, "two runs of the same case differ"); + Ok(()) + }, + ); +} + +/// A transaction's outcome does not depend on what its EVM ran before: on an EVM that already ran +/// another transaction over the same pre-state it is byte-identical to its outcome on a fresh +/// one, whether that transaction succeeded, reverted, halted, was stopped by a limit or was +/// refused with an error, and running it once more gives the same again. +/// +/// Nothing is committed between the runs, so the state is the same each time; what could differ +/// is what the engine keeps for one transaction and must reset for the next: the limits layer and +/// the stop it reported, gas detention, the SALT multipliers it read, the keyless frame. A +/// transaction that ends in an error leaves through no settlement, so the reset is all that stands +/// between it and the next. The tally of how the previous transaction ended is printed. +#[test] +fn test_property_a_reused_evm_runs_a_transaction_as_a_fresh_one_does() { + let tally: Mutex> = Mutex::new(BTreeMap::new()); + check( + "reused_evm", + CASES, + || (case(Flavor::Satin), tx(Flavor::Satin)), + |(case, previous)| { + let fresh = render(&case.execute()); + let mut evm = case.evm(); + let previous = previous.build(&case.world, &case.main.assemble()); + let ended = match Case::execute_on(&mut evm, previous) { + // A SALT bucket that cannot be read fails the transaction where the charge is + // made, in the middle of its run; every other error refuses it before it runs. + Err(error) if error.contains("the bucket cannot be read") => { + "the previous transaction ended in an error while it ran" + } + Err(_) => "the previous transaction was refused with an error", + Ok(outcome) if outcome.limit_exceeded.is_some() => { + "the previous transaction was stopped by a limit" + } + Ok(outcome) if outcome.result.is_success() => "the previous transaction succeeded", + Ok(_) => "the previous transaction reverted or halted", + }; + *tally.lock().unwrap().entry(ended).or_default() += 1; + let reused = render(&Case::execute_on(&mut evm, case.transaction())); + prop_eq!(fresh, reused, "the outcome on a reused EVM differs: {ended}"); + let again = render(&Case::execute_on(&mut evm, case.transaction())); + prop_eq!(fresh, again, "the outcome of a second run on the same EVM differs"); + Ok(()) + }, + ); + print_tally("reused_evm", tally.into_inner().unwrap()); +} + +/// An inspector that only records changes nothing: without one, under the gas inspector of the +/// test utilities and under revm-inspectors' tracer, the outcome is byte-identical. +#[test] +fn test_property_inspector_transparency() { + check( + "inspector_transparency", + CASES, + || case(Flavor::Satin), + |case| { + let plain = render(&case.execute()); + let (recorded, _) = case.execute_inspected(GasInspector::new()); + prop_eq!(plain, render(&recorded), "the gas inspector changed the outcome"); + let (traced, _) = + case.execute_inspected(TracingInspector::new(TracingInspectorConfig::all())); + prop_eq!(plain, render(&traced), "the tracing inspector changed the outcome"); + Ok(()) + }, + ); +} + +/// Whether the transaction is exempt from history gas and the per-transaction limits: a deposit, +/// a transaction the protocol sent, or one the engine promotes to a deposit. +fn is_exempt(tx: &MegaTransaction) -> bool { + tx.0.deposit.source_hash != alloy_primitives::B256::ZERO || + is_system_originated(tx, SYSTEM_ADDRESS) +} + +/// The account `address` had before the transaction, if any: an empty one is none, as the +/// engine sees it. +fn pre_account(db: &mut MemoryDatabase, address: Address) -> Option { + db.basic(address).unwrap_or_default().filter(|info| !info.is_empty()) +} + +/// The gas ledgers, as the spec defines them: +/// +/// - the three ledgers add up to the raw spend: the regular ledger is defined as the spend less the +/// two others, so what is checked is that the spend covers them; +/// - the receipt's figure is the raw spend less the refund, at least the floor, at most the gas +/// limit; +/// - the refund is within its cap, a fifth of the raw spend; +/// - the reservoir is the gas above the execution cap, and it pays the state and history gas before +/// the regular budget does and nothing else: what is gone from it is exactly the state and +/// history ledgers, or all of it when they exceed it. Two rules bill it otherwise and are left +/// out: the EIP-7623 floor, when it is the receipt's figure, and op-revm's failed deposit, which +/// bills the whole gas limit; +/// - an exempt transaction pays no history and reports no history bytes; any other reports at least +/// its body and pays at most what its bytes cost, the allowances paying the rest; +/// - value is conserved: the balances change by what a deposit minted, less what a self-destruction +/// burned; +/// - the sender's nonce moves by one, or by more when its own code creates. +#[test] +fn test_property_gas_ledgers() { + check( + "gas_ledgers", + CASES, + || case(Flavor::Satin), + |case| { + let tx = case.transaction(); + let Ok(outcome) = case.execute() else { return Ok(()) }; + let result_gas = outcome.result.gas(); + let gas = outcome.gas; + let total = result_gas.total_gas_spent(); + let gas_limit = tx.gas_limit(); + let failed_deposit = matches!( + &outcome.result, + ExecutionResult::Halt { reason: mega_evm::MegaHaltReason::FailedDeposit, .. } + ); + if failed_deposit { + // op-revm's rule: a deposit that halts or is refused after Regolith bills its whole + // gas limit, the reservoir included, and everything it did is discarded. + prop_eq!(total, gas_limit, "a failed deposit bills its whole gas limit"); + prop_eq!(gas.reservoir_remaining, 0, "a failed deposit keeps no reservoir"); + prop_eq!( + (gas.state, gas.history), + (0, 0), + "a failed deposit reports no state or history gas" + ); + } + + // The regular ledger is by definition the spend less the two others, so the three + // add up unless that subtraction saturates: this is the check that it does not. + prop_check!( + total >= gas.state + gas.history, + "the spend covers the state and history ledgers, so the three add up" + ); + prop_eq!( + gas.gas_used, + total.saturating_sub(result_gas.inner_refunded()).max(gas.floor), + "the receipt figure is the spend less the refund, at least the floor" + ); + prop_check!(gas.gas_used <= gas_limit, "the receipt figure is within the gas limit"); + prop_check!(result_gas.inner_refunded() * 5 <= total, "the refund is within a fifth"); + + let reservoir = gas_limit.saturating_sub(gas_limit.min(TX_GAS_LIMIT_CAP)); + prop_check!( + gas.reservoir_remaining <= reservoir, + "no more comes back than was in the reservoir" + ); + if !failed_deposit && gas.gas_used != gas.floor { + prop_eq!( + reservoir - gas.reservoir_remaining, + reservoir.min(gas.state + gas.history), + "the reservoir pays the state and history gas first, and nothing else" + ); + } + + if is_exempt(&tx) { + prop_eq!( + (gas.history, gas.history_bytes), + (0, 0), + "an exempt transaction pays no history" + ); + } else { + prop_check!( + gas.history_bytes >= transaction_body_bytes(&tx), + "the body is in the history bytes" + ); + let worth = + mega_evm::history_gas(gas.history_bytes).expect("the bytes have a price"); + prop_check!(gas.history <= worth, "the history gas is at most what the bytes cost"); + } + + let mut pre = case.database(); + let mut delta = alloy_primitives::I256::ZERO; + for (address, account) in &outcome.state { + let before = pre_account(&mut pre, *address).map_or(U256::ZERO, |a| a.balance); + let after = account.info.balance; + let signed = |v: U256| alloy_primitives::I256::try_from(v).expect("a balance fits"); + delta += signed(after) - signed(before); + } + let mint = alloy_primitives::I256::try_from(U256::from(tx.0.deposit.mint.unwrap_or(0))) + .expect("a mint fits"); + if case.destroys() { + prop_check!( + delta <= mint, + "value is conserved but for what a destruction burned: {delta} vs {mint}" + ); + } else { + prop_eq!(delta, mint, "value is conserved"); + } + + let sender = tx.caller(); + let before = pre_account(&mut pre, sender).map_or(0, |a| a.nonce); + let after = outcome.state.get(&sender).map_or(before, |a| a.info.nonce); + // A sender that runs code, through a delegation or as an applied authority, may create + // and so bump its nonce further. + let runs_code = case.world.delegation.is_some_and(|d| d.delegator == Who::Caller) || + matches!(&case.tx.shape, Shape::Eip7702 { auths, .. } if auths.iter().any(|a| a.authority == Who::Caller)); + if runs_code { + prop_check!( + after > before, + "the sender's nonce moves by at least one: {before} -> {after}" + ); + } else { + prop_eq!(after, before + 1, "the sender's nonce moves by one"); + } + Ok(()) + }, + ); +} + +/// After every instruction the KV count never weighs more than the data size, `KV × 40 ≤ data +/// size`; at the end the same holds, the history bytes are within the data size, every +/// transaction keeps at least its body and the Oracle hints it forwarded, and a user's +/// transaction keeps no more than its data-size limit: a frame that crossed the limit took what +/// it counted back with it, whether its caller caught the stop or not. Deposits and the protocol's +/// transactions are left out of the last: the protocol's are held to no limit, and a deposit whose +/// body is over the limit keeps it as a failed deposit. +#[test] +fn test_property_kv_weighs_no_more_than_data_size() { + #[derive(Default)] + struct Probe { + steps: u64, + over: Option<(mega_evm::LimitUsage, u64)>, + } + impl Inspector, EthInterpreter> for Probe { + fn step_end( + &mut self, + _: &mut Interpreter, + context: &mut MegaContext, + ) { + self.steps += 1; + let usage = context.additional_limit().usage(); + if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { + self.over.get_or_insert((usage, self.steps)); + } + } + } + check( + "kv_weighs_no_more_than_data_size", + CASES, + || case(Flavor::Satin), + |case| { + let tx = case.transaction(); + let (execution, evm) = case.execute_inspected(Probe::default()); + prop_eq!( + evm.inspector().over, + None, + "KV x 40 exceeded the data size after an instruction" + ); + let Ok(outcome) = execution else { return Ok(()) }; + let usage = outcome.usage; + prop_check!( + usage.write_records * WRITE_RECORD_SIZE <= usage.data_size, + "KV x 40 exceeded the data size at the end: {usage:?}" + ); + prop_check!( + outcome.gas.history_bytes <= usage.data_size, + "the history bytes are within the data size: {:?} vs {usage:?}", + outcome.gas + ); + // What left the machine stays counted, whatever became of the transaction, an exempt + // one and a failed deposit included: the body, which is in the block, and the hints + // forwarded to the oracle service. + let hints = forwarded_hint_bytes(&evm); + prop_check!( + usage.data_size >= transaction_body_bytes(&tx) + hints, + "the body and the {hints} bytes of hints forwarded are counted: {usage:?}" + ); + if !is_exempt(&tx) { + let limit = case.world.limits.runtime().tx_data_size_limit; + prop_check!( + usage.data_size <= limit, + "a user's transaction keeps more than its limit of {limit}: {usage:?}" + ); + } + Ok(()) + }, + ); +} + +/// What the Oracle hints `evm`'s transaction forwarded weigh as data size. A forwarded hint's +/// payload is its call's whole input: the selector, the topic, the offset and length of the data, +/// and the data padded to a word. +fn forwarded_hint_bytes(evm: &mega_evm::MegaEvm) -> u64 { + evm.ctx() + .external_envs() + .oracle_env + .recorded_hints() + .iter() + .map(|hint| 4 + 3 * 32 + (hint.data.len() as u64).div_ceil(32) * 32) + .sum() +} + +/// A stopped transaction keeps only what the spec says survives: the stop is the crossing of its +/// own frame, which names a limit the case runs under — the transaction's data-size limit, that +/// frame's budget, which is below it, or a compute limit, which no frame budget is — and reverts +/// that frame and so everything below it; it is a revert carrying `MegaLimitExceeded`, with no +/// log; no storage write stands; no account changes but the sender's +/// nonce and fee, the fee recipients' credit, an applied EIP-7702 authority's nonce and +/// delegation, and a deposit's mint; the records kept are the applied authorities', and the data +/// size is the body, those records and the payloads of the Oracle hints it forwarded, which have +/// left the machine and are counted whatever the frame that sent them did, and nothing of a hint +/// that crossed the limit, which was not forwarded (a hint that was admitted and did not decode +/// is counted too, so where a program can send one the hints forwarded are a lower bound); the +/// state gas kept is the applied +/// authorizations', the sender's own delegation included, and that of the caller account a deposit +/// created, which is the body's account and no record. An authority that is also a fee recipient +/// is credited the fee, as any fee recipient is. +#[test] +fn test_property_a_stop_keeps_only_what_survives() { + check( + "a_stop_keeps_only_what_survives", + CASES, + || case(Flavor::Satin), + |case| { + let tx = case.transaction(); + let (execution, evm) = case.execute_with_evm(); + let Ok(outcome) = execution else { return Ok(()) }; + let Some(stop) = outcome.limit_exceeded else { return Ok(()) }; + check_survivors(case, &tx, &outcome, stop, forwarded_hint_bytes(&evm)) + }, + ); +} + +/// What [`test_property_a_stop_keeps_only_what_survives`] checks of a stopped transaction; +/// `hint_bytes` is what the Oracle hints it forwarded weigh. +pub(crate) fn check_survivors( + case: &Case, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, + stop: LimitCheck, + hint_bytes: u64, +) -> Result<(), proptest::test_runner::TestCaseError> { + let rendered = render_outcome(outcome); + let LimitCheck::ExceedsLimit { kind, limit, frame_local, .. } = stop else { + return Err(crate::harness::fail(format!( + "a reported stop that is within the limit\n{rendered}" + ))); + }; + let tx_limit = case.world.limits.runtime().tx_data_size_limit; + match (kind, frame_local) { + (LimitKind::DataSize, false) => { + prop_eq!(limit, tx_limit, "the stop names the transaction's limit\n{rendered}"); + } + (LimitKind::DataSize, true) => { + prop_check!(limit < tx_limit, "a frame budget is below the limit\n{rendered}"); + } + (LimitKind::ComputeGas, frame_local) => { + prop_check!(!frame_local, "a compute stop is no frame budget\n{rendered}"); + } + } + match &outcome.result { + ExecutionResult::Revert { output, .. } => { + prop_eq!(*output, stop.revert_data(), "the stop's revert data\n{rendered}"); + } + other => { + return Err(crate::harness::fail(format!( + "a stop that is not a revert: {other:?}\n{rendered}" + ))) + } + } + prop_check!(outcome.result.logs().is_empty(), "a stop keeps no log\n{rendered}"); + + let sender = tx.caller(); + let mut pre = case.database(); + let is_deposit = tx.0.deposit.source_hash != alloy_primitives::B256::ZERO; + let fee_recipients = [ + case.world.beneficiary_address(), + op_revm::constants::BASE_FEE_RECIPIENT, + op_revm::constants::L1_FEE_RECIPIENT, + op_revm::constants::OPERATOR_FEE_RECIPIENT, + ]; + // The authorizations that apply, by revm's rules, and what the state says of them: either + // every one applied, or the runtime phase before the first frame took them all back. + let simulated = applied_authorizations(case); + let mut expected: BTreeMap = BTreeMap::new(); + for (authority, delegate) in &simulated { + let entry = expected.entry(*authority).or_insert((0, *delegate)); + entry.0 += 1; + entry.1 = *delegate; + } + let bumped = |address: Address, state_nonce: u64| { + let before = pre_account(&mut case.database(), address).map_or(0, |a| a.nonce); + state_nonce > before + u64::from(address == sender) + }; + let taken_back = !expected.is_empty() && + expected + .keys() + .all(|a| outcome.state.get(a).is_none_or(|acc| !bumped(*a, acc.info.nonce))); + if taken_back { + expected.clear(); + } + let applied = expected.keys().filter(|a| **a != sender).count() as u64; + let mut created_caller = 0u64; + for (address, account) in &outcome.state { + let before = pre_account(&mut pre, *address); + let before_nonce = before.as_ref().map_or(0, |a| a.nonce); + let before_balance = before.as_ref().map_or(U256::ZERO, |a| a.balance); + let before_code = + before.as_ref().map_or(alloy_primitives::KECCAK256_EMPTY, |a| a.code_hash); + for (key, slot) in &account.storage { + prop_eq!( + slot.present_value, + slot.original_value, + "a stop keeps no storage write: {address} slot {key}\n{rendered}" + ); + } + let is_sender = *address == sender; + if let Some((bumps, delegate)) = expected.get(address) { + prop_eq!( + account.info.nonce, + before_nonce + u64::from(is_sender) + bumps, + "an applied authority's nonce moves once per authorization: {address}\n{rendered}" + ); + let expected_code = match delegate { + Delegate::Zero => alloy_primitives::KECCAK256_EMPTY, + other => Bytecode::new_eip7702(match other { + Delegate::Contract => Who::Contract.address(), + Delegate::A => Who::A.address(), + Delegate::B => Who::B.address(), + Delegate::Beneficiary => Who::Beneficiary.address(), + Delegate::Zero => unreachable!(), + }) + .hash_slow(), + }; + prop_eq!( + account.info.code_hash, + expected_code, + "an applied authority delegates: {address}\n{rendered}" + ); + if is_sender { + prop_check!( + account.info.balance <= before_balance, + "the sender pays and receives nothing\n{rendered}" + ); + } else if fee_recipients.contains(address) { + // An authority may be the block beneficiary, which the transaction's fee is + // credited to whatever stopped it. + prop_check!( + account.info.balance >= before_balance, + "an authority that is a fee recipient is credited: {address}\n{rendered}" + ); + } else { + prop_eq!( + account.info.balance, + before_balance, + "an authority's balance stands: {address}\n{rendered}" + ); + } + continue; + } + if is_sender { + prop_eq!( + account.info.nonce, + before_nonce + 1, + "the sender's nonce moves by one\n{rendered}" + ); + prop_eq!(account.info.code_hash, before_code, "the sender's code stands\n{rendered}"); + if is_deposit { + let mint = U256::from(tx.0.deposit.mint.unwrap_or(0)); + prop_eq!( + account.info.balance, + before_balance + mint, + "a deposit keeps its mint\n{rendered}" + ); + if before.is_none() { + created_caller = 1; + } + } else { + prop_check!( + account.info.balance <= before_balance, + "the sender pays and receives nothing\n{rendered}" + ); + } + continue; + } + if fee_recipients.contains(address) { + prop_eq!( + account.info.nonce, + before_nonce, + "a fee recipient's nonce stands: {address}\n{rendered}" + ); + prop_eq!( + account.info.code_hash, + before_code, + "a fee recipient's code stands: {address}\n{rendered}" + ); + prop_check!( + account.info.balance >= before_balance, + "a fee recipient is credited: {address}\n{rendered}" + ); + continue; + } + prop_eq!( + (account.info.nonce, account.info.balance, account.info.code_hash), + (before_nonce, before_balance, before_code), + "an account a stop touched stands as before: {address}\n{rendered}" + ); + } + + let usage = outcome.usage; + prop_eq!( + usage.write_records, + applied, + "the records kept are the distinct applied authorities' but the sender's\n{rendered}" + ); + // The hints counted: what the data size holds beside the body and the records. Every hint + // forwarded is in it. A hint that was admitted and did not decode is in it too, and reached + // nobody: only a raw call of the Oracle, whose calldata is whatever memory holds, sends one. + let priced = transaction_body_bytes(tx) + usage.write_records * WRITE_RECORD_SIZE; + let Some(hints_counted) = usage.data_size.checked_sub(priced) else { + return Err(crate::harness::fail(format!( + "the data size kept is below the body and the records\n{rendered}" + ))); + }; + prop_check!( + hints_counted >= hint_bytes, + "a forwarded hint stays counted: {hints_counted} < {hint_bytes}\n{rendered}" + ); + if !case.may_send_a_hint_that_does_not_decode() { + prop_eq!( + hints_counted, + hint_bytes, + "the data size kept is the body, the records and the hints forwarded\n{rendered}" + ); + } + if !is_exempt(tx) { + prop_eq!( + outcome.gas.history_bytes, + priced, + "the history bytes are the data size kept but the hints\n{rendered}" + ); + let worth = mega_evm::history_gas(priced).expect("the bytes have a price"); + prop_eq!( + outcome.gas.history, + worth, + "the history gas is the body's and the records'\n{rendered}" + ); + } + // Every applied authorization keeps the state gas of its delegation, the sender's own + // included: a sender that delegates itself makes no record, its account being the body's, and + // pays the state gas of the designator all the same. + if expected.is_empty() && created_caller == 0 { + prop_eq!(outcome.gas.state, 0, "a stop keeps no state gas\n{rendered}"); + } + Ok(()) +} + +/// The EIP-7702 authorizations of `case` that revm applies, in order, each with its delegate: the +/// signature recovers, the chain id is this chain's, the nonce is the authority's at that point +/// (the sender's after its own bump), and the authority has no code but a delegation. +fn applied_authorizations(case: &Case) -> Vec<(Address, Delegate)> { + let Shape::Eip7702 { auths, .. } = &case.tx.shape else { return Vec::new() }; + let world = &case.world; + let sender = Who::Caller.address(); + let mut nonces: BTreeMap = BTreeMap::new(); + nonces.insert(sender, world.nonce_of(sender) + 1); + let has_plain_code = |address: Address| { + let program = [(Who::Contract, &case.main), (Who::A, &case.a), (Who::B, &case.b)] + .into_iter() + .find(|(who, _)| who.address() == address) + .map(|(_, program)| program); + let delegates = world.delegation.is_some_and(|d| d.delegator.address() == address); + !delegates && program.is_some_and(|p| !p.assemble().is_empty()) + }; + let mut applied = Vec::new(); + for auth in auths { + if !auth.recovers || !auth.chain_ok { + continue; + } + let authority = auth.authority.address(); + let nonce = world.nonce_of(authority) + u64::from(!auth.nonce_ok); + if nonce != nonces.get(&authority).copied().unwrap_or_else(|| world.nonce_of(authority)) { + continue; + } + if has_plain_code(authority) { + continue; + } + nonces.insert(authority, nonce + 1); + applied.push((authority, auth.delegate)); + } + applied +} diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs new file mode 100644 index 000000000..518c5f445 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -0,0 +1,147 @@ +//! The minimal cases the properties found, and the ones a review of them found, one named test +//! each, so a finding is pinned without its seed. +//! +//! Four findings first pinned here now live as deterministic tests: +//! +//! - `test_an_out_of_gas_before_the_first_frame_matches_op_revm` pins the out-of-gas before the +//! first frame. Found by the gas-ledgers property: the fork drops the runtime phase's partial +//! charges by rebuilding the transaction's gas, and the settlement gave the recipient record's +//! history back a second time, into the reservoir, which the halt does not burn. +//! - `test_a_system_deposit_over_the_limit_reports_the_failed_deposit` pins a failed deposit that +//! reports no stop. Found by the survivors property: the stop the body's count set, before +//! op-revm validated the deposit, was reported beside the halt. +//! - `test_an_out_of_gas_creation_before_the_first_frame_matches_op_revm` pins the nonce bump of an +//! out-of-gas creation. Found by the gas-ledgers property: Satin's pre-execution bailed out with +//! a plain checkpoint revert, which took the bump the creation frame makes back and made none of +//! its own. +//! - `test_a_failed_deposit_keeps_the_hints_it_forwarded` pins a failed deposit that keeps a +//! forwarded hint. Found by comparing every case's outcome before and after the failed deposit's +//! settlement was added: that settlement reset the whole count to the body, the forwarded hint +//! with it. +//! +//! A case whose gas limit falls short of a charge is pinned at the spec's byte prices, where it +//! was found: its gas limit is the one the minimal case carries, and the charge moves with the +//! prices. At other prices those tests return early, with the note the byte-price grid counts; the +//! properties themselves hold at any price and run there. + +use crate::{ + gen::{ + case::Case, + program::{End, Program}, + tx::{GasTier, Price, Shape, Tx}, + world::{AccountShape, Balance, BeneficiaryIs, BlockShape, Limits, Salt, World}, + Value, Who, + }, + harness::runs_at_measurement_prices, + render::render, +}; + +/// A world of empty programs, with the sender funded and nothing else. +fn plain_world() -> World { + let account = |balance| AccountShape { balance, nonce: 0, slots: vec![] }; + World { + caller: account(Balance::Rich), + contract: account(Balance::Zero), + a: account(Balance::Zero), + b: account(Balance::Zero), + beneficiary_balance: Balance::Zero, + beneficiary: BeneficiaryIs::Distinct, + delegation: None, + salt: Salt { + default_multiplier: 1, + crowded_accounts: vec![], + crowded_slots: vec![], + failing_account: None, + }, + oracle: vec![], + limits: Limits::Default, + block: BlockShape { basefee: 0, slot_num: 0, blob: true }, + system_nonce: 0, + } +} + +fn stop() -> Program { + Program { ops: vec![], end: End::Stop } +} + +/// A value transfer that runs out of gas before its first frame, with a non-zero operator fee +/// scalar and constant, pays that fee on the whole gas limit. +/// +/// The fee is `gas × scalar × 100 + constant` on the gas the receipt counts, less any reservoir. +/// Handing the first frame's record history back a second time leaves that gas in the reservoir, +/// and the fee is then computed on less than the gas the halt burned. An empty envelope pays no +/// operator fee whatever the parameters, so the transaction carries one byte that is not a deposit. +/// The recipient account is created empty: the frame never runs, so the value does not move. +#[test] +fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_gas_limit() { + if runs_at_measurement_prices() { + return; + } + use alloy_primitives::{Bytes, U256}; + use op_revm::constants::{OPERATOR_FEE_JOVIAN_MULTIPLIER, OPERATOR_FEE_RECIPIENT}; + + const SCALAR: u64 = 2; + const CONSTANT: u64 = 50; + + let case = Case { + world: plain_world(), + tx: Tx { + shape: Shape::Call { to: Who::Fresh, data_len: 0, access_list: vec![] }, + value: Value::One, + gas: GasTier::Tiny, + price: Price::Free, + nonce_ok: true, + }, + main: stop(), + a: stop(), + b: stop(), + }; + let mut evm = case.evm(); + evm.ctx_mut().modify_chain(|chain| { + // A block number the info does not name makes op-revm load the info from the database, + // which has no scalars, and the parameters above would not be the ones the fee uses. + chain.l2_block = Some(case.block().number); + chain.operator_fee_scalar = Some(U256::from(SCALAR)); + chain.operator_fee_constant = Some(U256::from(CONSTANT)); + }); + let mut tx = case.transaction(); + tx.0.enveloped_tx = Some(Bytes::from_static(&[0x01])); + + let execution = Case::execute_on(&mut evm, tx); + let outcome = execution.as_ref().expect("the transaction is valid"); + let rendered = render(&execution); + assert!(outcome.result.is_halt(), "{rendered}"); + let gas = outcome.result.gas(); + let gas_limit = GasTier::Tiny.limit(); + assert_eq!(gas.total_gas_spent(), gas_limit, "the whole gas limit burns\n{rendered}"); + assert_eq!(gas.reservoir_remaining(), 0, "nothing comes back from a reservoir\n{rendered}"); + assert_eq!(outcome.gas.gas_used, gas_limit, "{rendered}"); + let body = mega_evm::transaction_body_bytes(&case.transaction()); + assert_eq!(outcome.gas.history_bytes, body, "the body alone is kept\n{rendered}"); + assert_eq!( + outcome.gas.history, + mega_evm::history_gas(body).expect("the body has a price"), + "the history ledger reads the body\n{rendered}" + ); + assert_eq!(outcome.usage.write_records, 0, "{rendered}"); + + let fee = + U256::from(gas_limit) * U256::from(SCALAR) * U256::from(OPERATOR_FEE_JOVIAN_MULTIPLIER) + + U256::from(CONSTANT); + let caller = case.tx.sender(); + assert_eq!( + outcome.state[&caller].info.balance, + case.world.caller.balance.wei() - fee, + "the sender pays the operator fee on the whole gas limit, and the value does not move\n{rendered}" + ); + assert_eq!( + outcome.state[&OPERATOR_FEE_RECIPIENT].info.balance, fee, + "the operator fee recipient is paid that fee\n{rendered}" + ); + let fresh = outcome.state.get(&Who::Fresh.address()).expect("the recipient account is created"); + assert_eq!( + fresh.info.balance, + U256::ZERO, + "the recipient is created empty: the frame never runs, so the value does not move\n{rendered}" + ); +} diff --git a/crates/mega-evm/tests/fuzz/render.rs b/crates/mega-evm/tests/fuzz/render.rs new file mode 100644 index 000000000..c004f8aa5 --- /dev/null +++ b/crates/mega-evm/tests/fuzz/render.rs @@ -0,0 +1,56 @@ +//! A canonical rendering of what a transaction produced, so two runs are compared byte for byte +//! and a difference reads as a diff. + +use std::{collections::BTreeMap, fmt::Write as _}; + +use alloy_primitives::{Address, U256}; +use mega_evm::MegaTransactionOutcome; +use revm::state::{Account, EvmState}; + +use crate::gen::case::Execution; + +/// The state sorted by address, each account's storage sorted by key, so two equal states render +/// the same whatever their maps' iteration order. +pub(crate) fn render_state(state: &EvmState) -> String { + let mut out = String::new(); + let sorted: BTreeMap = state.iter().map(|(a, acc)| (*a, acc)).collect(); + for (address, account) in sorted { + let _ = writeln!( + out, + " {address}: nonce={} balance={} code_hash={} status={:?}", + account.info.nonce, account.info.balance, account.info.code_hash, account.status + ); + let slots: BTreeMap = account.storage.iter().map(|(k, v)| (*k, v)).collect(); + for (key, slot) in slots { + let _ = writeln!( + out, + " slot {key}: {} -> {}{}", + slot.original_value, + slot.present_value, + if slot.is_cold { " (cold)" } else { "" } + ); + } + } + out +} + +/// Everything an outcome carries, rendered canonically: the result with its gas, logs and output, +/// the gas by ledger, the usage, the stop and the state. +pub(crate) fn render_outcome(outcome: &MegaTransactionOutcome) -> String { + let mut out = String::new(); + let _ = writeln!(out, "result: {:?}", outcome.result); + let _ = writeln!(out, "gas: {:?}", outcome.gas); + let _ = writeln!(out, "usage: {:?}", outcome.usage); + let _ = writeln!(out, "limit_exceeded: {:?}", outcome.limit_exceeded); + let _ = writeln!(out, "state:"); + out.push_str(&render_state(&outcome.state)); + out +} + +/// An execution rendered canonically: the outcome, or the error. +pub(crate) fn render(execution: &Execution) -> String { + match execution { + Ok(outcome) => render_outcome(outcome), + Err(error) => format!("refused: {error}\n"), + } +} diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index 054d77f6e..e70acfc35 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -2,13 +2,15 @@ use alloy_evm::Evm; use alloy_op_evm::OpTx; -use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_primitives::{Address, Bytes, TxKind, B256, U256}; use mega_evm::{ active_satin_prices, - test_utils::{op_transaction, zero_fee_l1_block_info}, - LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + test_utils::{note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, + EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, }; use revm::{ + bytecode::opcode::{PUSH0, RETURN}, context::{result::ResultAndState, BlockEnv, TxEnv}, Database, }; @@ -47,6 +49,44 @@ fn tx(caller: Address, kind: TxKind, data: Bytes, value: U256, gas_limit: u64) - OpTx(op_transaction(TxEnv { caller, kind, data, value, gas_limit, ..Default::default() })) } +/// A type-4 call from `caller` to `to` carrying `value`, with one authorization per +/// `(authority, nonce)` delegating the authority to `delegate`, valid on any chain. +pub(crate) fn authorizing_call( + caller: Address, + to: Address, + value: U256, + gas_limit: u64, + delegate: Address, + authorizations: &[(Address, u64)], +) -> MegaTransaction { + use revm::{ + context::transaction::TransactionType, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + let authorization_list = authorizations + .iter() + .map(|(authority, nonce)| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: delegate, nonce: *nonce }, + RecoveredAuthority::Valid(*authority), + )) + }) + .collect(); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller, + kind: TxKind::Call(to), + value, + gas_limit, + gas_priority_fee: Some(0), + authorization_list, + ..Default::default() + })) +} + /// Runs `tx` on a fresh Satin EVM over `db` and returns its result and what the common execution /// layer counted. pub(crate) fn run( @@ -59,6 +99,49 @@ pub(crate) fn run( (result, usage) } +/// Runs `tx` on a fresh Satin EVM over `db` and returns its outcome: the result and state, the +/// gas by ledger and what the common execution layer counted. +pub(crate) fn execute( + db: DB, + tx: MegaTransaction, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db)).execute_transaction(tx).expect("the transaction is valid") +} + +/// Runs `tx` on a fresh Satin EVM over `db` held to `limits` and returns its outcome. +pub(crate) fn execute_under( + db: DB, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid") +} + +/// 98% of `remaining`, the share a child frame is given. +pub(crate) fn share(remaining: u64) -> u64 { + (u128::from(remaining) * u128::from(mega_evm::FRAME_DATA_SHARE_NUMERATOR) / + u128::from(mega_evm::FRAME_DATA_SHARE_DENOMINATOR)) as u64 +} + +/// `tx` as a user's deposit: no fee, and a source hash a user's transaction could carry. +pub(crate) fn deposit(mut tx: MegaTransaction) -> MegaTransaction { + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.base.gas_price = 0; + tx +} + +/// Init code that returns `len` bytes of zeros as the deployed code. +pub(crate) fn deploying(len: u64) -> Bytes { + BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() +} + +/// Init code that returns `size` zero bytes as the deployed contract. +pub(crate) fn constructor_returning(size: u64) -> Bytes { + BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() +} + /// Whether this process prices bytes at something other than the constants the spec fixes. /// /// Only a measurement build can arrange that — the `satin-price-override` feature, through @@ -66,21 +149,90 @@ pub(crate) fn run( /// every state-gas number. A test that asserts one of those numbers returns early instead of /// failing on a price the developer asked for. /// -/// The notice goes straight to stderr and only once: the harness captures the print macros of a -/// test that passes, so a message written with them would never be read. +/// Each test that returns early leaves a note (`note_price_guard`), which the byte-price +/// grid counts. pub(crate) fn runs_at_measurement_prices() -> bool { - use std::io::Write; - if active_satin_prices().is_constants() { return false; } - static NOTICE: std::sync::Once = std::sync::Once::new(); - NOTICE.call_once(|| { - let _ = writeln!( - std::io::stderr(), - "note: skipping the tests that assert the spec's byte prices, because \ - MEGA_SATIN_CPSB or MEGA_SATIN_CPHB fixed other ones; unset them to run those tests" - ); - }); + note_price_guard("MEGA_SATIN_CPSB or MEGA_SATIN_CPHB fixed prices other than the spec's"); true } + +/// Whether a state byte costs nothing at the prices in effect: every state-gas entry of the +/// schedule is zero. +/// +/// Only a measurement build arranges that, with `MEGA_SATIN_CPSB` at 0 or at a price every entry +/// rounds to nothing. A test whose scenario is state gas — a limit to cross with it, a bucket to +/// scale it, a charge to give back — has nothing to run then, and returns early, with a note like +/// [`runs_at_measurement_prices`]'s. +pub(crate) fn state_is_free() -> bool { + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); + true +} + +/// Whether a history byte costs nothing at the prices in effect. +/// +/// Only a measurement build arranges that, with `MEGA_SATIN_CPHB` at 0. A test whose scenario is +/// history gas has nothing to run then, and returns early, with a notice like +/// [`state_is_free`]'s. +pub(crate) fn history_is_free() -> bool { + if active_satin_prices().cphb.milli_gas() != 0 { + return false; + } + note_price_guard("MEGA_SATIN_CPHB prices a history byte at nothing"); + true +} + +/// Whether a history byte costs a fraction of a gas at the prices in effect. +/// +/// Only a measurement build arranges that, as the grid's 0.001 does. Each history charge is then +/// rounded to the nearest gas on its own, so a small charge — a body, a record — can cost nothing, +/// and the history of bytes charged apart is not the history of their sum. No test is held to +/// its history figures there: a test whose figures add history over several charges, or need a +/// record to cost something, returns early, or leaves those figures out, with a note like +/// [`history_is_free`]'s. +pub(crate) fn history_rounds() -> bool { + if active_satin_prices().cphb.milli_gas().is_multiple_of(1_000) { + return false; + } + note_price_guard("MEGA_SATIN_CPHB prices a history byte at a fraction of a gas"); + true +} + +/// The state gas one fresh storage slot costs at the byte prices in effect, in the minimum +/// bucket. +pub(crate) fn slot_state_gas() -> u64 { + mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::sstore_set_state_gas()) +} + +/// The state gas one new account costs at the byte prices in effect, in the minimum bucket. +pub(crate) fn account_state_gas() -> u64 { + mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::new_account_state_gas()) +} + +/// The history gas `bytes` bytes cost at the byte prices in effect, by hand rather than through +/// the engine's pricing: the bytes times `COST_PER_HISTORY_BYTE`, 88 gas, at the spec's price. +/// +/// A measurement build may price a history byte with a fraction of a gas, kept in thousandths of +/// a gas; the charge for the bytes is then rounded to the nearest gas, halves up. +pub(crate) fn history(bytes: u64) -> u64 { + use mega_evm::constants::COST_PER_HISTORY_BYTE; + let milli_gas = mega_evm::active_satin_prices().cphb.milli_gas(); + if milli_gas == COST_PER_HISTORY_BYTE * 1_000 { + return bytes * COST_PER_HISTORY_BYTE; + } + let milli_gas = u128::from(bytes) * u128::from(milli_gas); + u64::try_from((milli_gas + 500) / 1_000).expect("the history of the bytes fits a u64") +} + +/// The history gas the body of a transaction carrying `calldata_len` bytes of calldata, and no +/// access list or authorization, pays at the byte prices in effect, by hand: `TX_BODY_SIZE`, 310 +/// bytes, and one byte per byte of calldata. +pub(crate) fn body_history(calldata_len: u64) -> u64 { + history(mega_evm::TX_BODY_SIZE + calldata_len) +} diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs new file mode 100644 index 000000000..279485668 --- /dev/null +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -0,0 +1,705 @@ +//! The compute figure: the regular gas a transaction spent, read off its `Gas` and nothing else. +//! +//! A transaction's raw spend splits into three ledgers — regular, state and history — and the +//! regular one is the compute every limit reads. It is `total − state − history`, from the result +//! revm's `Gas` settled into; there is no counter of its own beside it. The figure a block counts +//! is that ledger at least the EIP-7623 floor, with history taken out *before* the floor is +//! applied: the fork's own `block_regular_gas_used` is `max(total − state, floor)`, which carries +//! history, and taking history out of it afterwards could land below the floor. +//! +//! Every case runs below the execution cap, where the reservoir is empty and state and history +//! spill onto regular gas, and above it, where the reservoir pays them first; every outcome is held +//! to the ledger identities, and above the cap to the reservoir's. The cases about the budget +//! itself run on the side where it binds, and say so. + +use alloy_evm::{Evm as _, EvmError, InvalidTxError}; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + constants::{ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + BlockGasCounters, MegaContext, MegaEvm, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome, + TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADD, CALL, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, MSTORE, MUL, POP, PUSH0, PUSH1, PUSH3, + SELFDESTRUCT, SLOAD, SUB, SWAP1, + }, + context::{ + result::{ExecutionResult, HaltReason, InvalidTransaction, OutOfGasError}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + context_interface::cfg::GasId, + interpreter::{interpreter::EthInterpreter, Interpreter}, + precompile::{ + bn254::pair, + hash::{RIPEMD160, SHA256}, + secp256k1::ECRECOVER, + }, + Inspector, +}; + +use crate::{ + common::{call, call_with_data, context, execute, runs_at_measurement_prices}, + salt::{crowded_account, entry, minimal_envs}, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000c00000"); +const CALLEE: Address = address!("0000000000000000000000000000000000c00001"); +const CHILD: Address = address!("0000000000000000000000000000000000c00002"); +/// An account nothing has touched. +const FRESH: Address = address!("0000000000000000000000000000000000c00003"); + +/// The intrinsic gas of a plain call to an existing account: EIP-2780's sender base of 12,000 and +/// 3,000 for reaching the recipient. +const EMPTY_CALL: u64 = 15_000; + +/// The two gas limits every case runs at: below the execution cap and above it. +const GAS_LIMITS: [u64; 2] = [10_000_000, TX_GAS_LIMIT_CAP + 100_000_000]; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(1)) +} + +/// `count` rounds of `PUSH1 1; PUSH1 2; ADD; POP`, eleven gas each, then `STOP`. +fn arithmetic(count: usize) -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..count { + code = code.push_number(1_u8).push_number(2_u8).append(ADD).append(POP); + } + code.stop().build() +} + +/// The three ledgers split the raw spend, the regular one is what is neither state nor history, +/// and the figure a block counts is that ledger at least the floor. Above the execution cap the +/// reservoir paid the state and history ledgers, and nothing else. +fn assert_ledgers(name: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { + let gas = &outcome.gas; + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + gas.reservoir_remaining, + gas_limit - TX_GAS_LIMIT_CAP - gas.state - gas.history, + "{name}: the reservoir paid the state and history ledgers", + ); + } + let result = outcome.result.gas(); + assert_eq!( + gas.regular + gas.state + gas.history, + result.total_gas_spent(), + "{name}: the three ledgers split the raw spend", + ); + assert_eq!(gas.block_execution_gas(), gas.regular.max(gas.floor), "{name}"); + let mut block = BlockGasCounters::default(); + block.record(gas); + assert_eq!(block.execution, gas.block_execution_gas(), "{name}: the block counts that figure"); +} + +/* ---------- the floor ---------- */ + +/// A transaction that carries a kilobyte of calldata and runs nothing is bound by its floor: its +/// regular ledger is the intrinsic gas, far below the floor's sixty-four gas a byte. The block +/// counts the floor. +/// +/// Its history — the body and the kilobyte, at the cost per history byte — is larger still, so +/// the order the two are taken out in decides the figure. History comes out first and the floor +/// applies to what is left: the block counts the floor. The fork's own figure keeps the history +/// in and lands far above the floor; taking the history out of that afterwards lands far below +/// it. Neither is what a block counts. +#[test] +fn test_a_floor_bound_transaction_counts_its_floor_and_history_comes_out_first() { + if runs_at_measurement_prices() { + return; + } + const CALLDATA: u64 = 1_000; + for gas_limit in GAS_LIMITS { + let tx = call_with_data(CALLER, CALLEE, Bytes::from(vec![0; CALLDATA as usize]), gas_limit); + let outcome = execute(funded(), tx); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("floor-bound", gas_limit, &outcome); + + let gas = outcome.gas; + assert_eq!(gas.history, (TX_BODY_SIZE + CALLDATA) * COST_PER_HISTORY_BYTE); + assert!(gas.floor > gas.regular, "{gas:?}: the floor binds the regular ledger"); + assert_eq!(gas.block_execution_gas(), gas.floor, "the block counts the floor"); + + let fork_figure = outcome.result.gas().block_regular_gas_used(); + assert_eq!(fork_figure, gas.regular + gas.history, "the fork's figure carries history"); + assert!(fork_figure > gas.floor); + assert!( + fork_figure - gas.history < gas.floor, + "taking history out after the floor would count less than the floor", + ); + assert_eq!(gas.gas_used, gas.regular + gas.history, "the receipt is above its floor"); + } +} + +/* ---------- an inspector that edits gas ---------- */ + +/// Charges `charge` and hands back `give_back` once, after the first instruction. +struct EditsGas { + charge: u64, + give_back: u64, + done: bool, +} + +impl EditsGas { + const fn new(charge: u64, give_back: u64) -> Self { + Self { charge, give_back, done: false } + } +} + +impl Inspector, EthInterpreter> for EditsGas { + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if !self.done { + self.done = true; + assert!(interp.gas.record_regular_cost(self.charge)); + interp.gas.erase_cost(self.give_back); + } + } +} + +/// An inspector that charges gas between two instructions, or hands some back, moves the receipt; +/// the compute figure moves with it, by the same amount, because both are read off the same +/// `Gas`. A counter kept beside `Gas` would not have seen the edit at all. +#[test] +fn test_gas_an_inspector_edits_moves_the_compute_figure_with_the_receipt() { + let run = |inspector: EditsGas, gas_limit: u64| -> MegaGasUsage { + let outcome = MegaEvm::new(context(funded().account_code(CALLEE, arithmetic(20)))) + .with_inspector(inspector) + .execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("edited", gas_limit, &outcome); + outcome.gas + }; + + for gas_limit in GAS_LIMITS { + let baseline = run(EditsGas::new(0, 0), gas_limit); + assert!(baseline.regular > baseline.floor + 86, "the floor is out of the way"); + + for (charge, give_back) in [(126, 0), (0, 86)] { + let edited = run(EditsGas::new(charge, give_back), gas_limit); + let moved = |figure: fn(&MegaGasUsage) -> u64| { + i128::from(figure(&edited)) - i128::from(figure(&baseline)) + }; + let expected = i128::from(charge) - i128::from(give_back); + assert_eq!(moved(|gas| gas.gas_used), expected, "the receipt moves"); + assert_eq!(moved(|gas| gas.regular), expected, "the regular ledger moves with it"); + assert_eq!(moved(MegaGasUsage::block_execution_gas), expected, "and the block figure"); + assert_eq!((edited.state, edited.history), (baseline.state, baseline.history)); + } + } +} + +/* ---------- what the figure counts ---------- */ + +/// Runs `code` at [`CALLEE`] under a plain call at `gas_limit` and requires it to succeed. +fn computes(code: Bytes, gas_limit: u64) -> MegaGasUsage { + let outcome = + execute(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("computes", gas_limit, &outcome); + outcome.gas +} + +/// What `code` computes beyond an empty contract, at both gas limits, which agree: state and +/// history that spilled onto regular gas below the cap are not computation. +fn computed_beyond_empty(code: Bytes) -> u64 { + let [below, above] = GAS_LIMITS.map(|gas_limit| { + computes(code.clone(), gas_limit).regular - computes(Bytes::new(), gas_limit).regular + }); + assert_eq!(below, above, "below and above the execution cap"); + below +} + +/// A call to a contract that does nothing computes its intrinsic gas: the regular ledger is the +/// receipt less the history the body cost. +#[test] +fn test_an_empty_call_computes_its_intrinsic_gas() { + if runs_at_measurement_prices() { + return; + } + for gas_limit in GAS_LIMITS { + let gas = computes(Bytes::from_static(&[PUSH0, 0x00]), gas_limit); + assert_eq!(gas.regular, EMPTY_CALL + 2, "the intrinsic gas and one PUSH0"); + assert_eq!(gas.regular, gas.gas_used - gas.history); + assert_eq!(gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE); + } +} + +/// Arithmetic is computed opcode by opcode: four pushes, an `ADD`, a `MUL` and two pops. +#[test] +fn test_arithmetic_is_computed_opcode_by_opcode() { + let code = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(2_u8) + .append(ADD) + .append(POP) + .push_number(3_u8) + .push_number(4_u8) + .append(MUL) + .append(POP) + .stop() + .build(); + assert_eq!(computed_beyond_empty(code), 4 * 3 + 3 + 5 + 2 * 2); +} + +/// Memory expansion is computation: an `MSTORE` of a word at `0x40` grows memory to three words, +/// and an `MLOAD` of the same word grows it no further. +#[test] +fn test_memory_expansion_is_computed() { + let code = BytecodeBuilder::default() + .mstore(0x40, [0xff]) + .push_number(0x40_u8) + .append(MLOAD) + .append(POP) + .stop() + .build(); + // `PUSH32` the word, `PUSH1` the offset, `MSTORE` and three words of memory; `PUSH1`, `MLOAD`, + // `POP`. + assert_eq!(computed_beyond_empty(code), 3 + 3 + (3 + 3 * 3) + 3 + 3 + 2); +} + +/// A fresh slot's state gas and its write record's history are not computation: what is left of +/// the `SSTORE` and the `SLOAD` after them is. +#[test] +fn test_storage_computes_what_is_neither_state_nor_history() { + if runs_at_measurement_prices() { + return; + } + let code = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(0xff)) + .append(PUSH0) + .append(SLOAD) + .append(POP) + .stop() + .build(); + let computed = computed_beyond_empty(code.clone()); + for gas_limit in GAS_LIMITS { + let gas = computes(code.clone(), gas_limit); + assert_eq!(gas.state, SLOT_STATE_GAS, "the fresh slot"); + assert_eq!(gas.history, (TX_BODY_SIZE + WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE); + assert_eq!(gas.regular, gas.gas_used - gas.state - gas.history); + assert_eq!(gas.regular, EMPTY_CALL + computed); + } + // Two pushes; a cold `SSTORE` of a fresh slot — its warm base, the cold surcharge and the + // storage write, the regular gas the schedule charges beside the state gas; `PUSH0`; a warm + // `SLOAD`; `POP`. + let fresh_sstore = entry(GasId::sstore_static()) + + entry(GasId::cold_storage_cost()) + + entry(GasId::sstore_set_without_load_cost()); + assert_eq!(computed, 3 + 3 + fresh_sstore + 2 + 100 + 2); +} + +/// A refund lowers the receipt and never the compute figure: clearing a slot and overwriting it +/// compute the same, and the receipt of the clearing one is lower by the refund. +#[test] +fn test_a_refund_does_not_lower_the_compute_figure() { + // The refund for clearing a storage slot. + let clears_schedule = entry(GasId::sstore_clearing_slot_refund()); + let writes = |value: u64, gas_limit: u64| { + let code = BytecodeBuilder::default().sstore(U256::from(7), U256::from(value)).stop(); + let db = funded().account_code(CALLEE, code.build()).account_storage( + CALLEE, + U256::from(7), + U256::from(1), + ); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("a slot written with a refund", gas_limit, &outcome); + outcome.gas + }; + for gas_limit in GAS_LIMITS { + let cleared = writes(0, gas_limit); + let overwritten = writes(2, gas_limit); + // EIP-3529 caps the refund at a fifth of what the transaction spent, which the two spend + // alike before it. + let cap = overwritten.gas_used / entry(GasId::max_refund_quotient()); + assert_eq!(overwritten.gas_used - cleared.gas_used, clears_schedule.min(cap)); + assert_eq!(cleared.regular, overwritten.regular, "the refund is not taken off compute"); + assert_eq!(cleared.block_execution_gas(), overwritten.block_execution_gas()); + } +} + +/// State gas is not computation whichever pool paid it and whatever the bucket charged: a +/// `SELFDESTRUCT` that moves a balance to a new account computes the same with the account's +/// bucket at the minimum and crowded four times over, below the cap and above it. +#[test] +fn test_state_gas_stays_off_the_compute_figure_whatever_it_costs() { + if runs_at_measurement_prices() { + return; + } + let code = BytecodeBuilder::default().push_address(FRESH).append(SELFDESTRUCT).build(); + let destructs = |m: u64, gas_limit: u64| { + let db = funded().account_code(CALLEE, code.clone()).account_balance(CALLEE, U256::from(5)); + let envs = crowded_account(minimal_envs(), FRESH, m); + let outcome = crate::salt::run(db, envs, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert_ledgers("a SELFDESTRUCT to a new account", gas_limit, &outcome); + outcome.gas + }; + let regular = destructs(1, GAS_LIMITS[0]).regular; + for gas_limit in GAS_LIMITS { + let minimal = destructs(1, gas_limit); + let crowded = destructs(4, gas_limit); + assert_eq!(minimal.state, ACCOUNT_STATE_GAS); + assert_eq!(crowded.state, 4 * ACCOUNT_STATE_GAS); + assert_eq!((minimal.regular, crowded.regular), (regular, regular)); + } +} + +/// `CALL(gas, target, 0, 0, 0, 0, 0)`, discarding the flag. +fn calls(code: BytecodeBuilder, target: Address, gas: u64) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(target) + .push_number(gas) + .append(CALL) + .append(POP) +} + +/// A callee running `rounds` rounds of arithmetic, then stopping or reverting. +fn child(rounds: usize, reverts: bool) -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..rounds { + code = code.push_number(1_u8).push_number(2_u8).append(ADD).append(POP); + } + if reverts { code.revert() } else { code.stop() }.build() +} + +/// What a caller computes when its child runs `rounds` rounds and stops or reverts. +fn with_child(rounds: usize, reverts: bool, gas_limit: u64) -> MegaGasUsage { + let caller = calls(BytecodeBuilder::default(), CHILD, 1_000_000).stop().build(); + let db = funded().account_code(CALLEE, caller).account_code(CHILD, child(rounds, reverts)); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("a caller and its child", gas_limit, &outcome); + outcome.gas +} + +/// A nested call's computation is the transaction's: a hundred rounds in the callee are a hundred +/// rounds on the compute figure. +#[test] +fn test_a_nested_call_s_computation_is_the_transaction_s() { + for gas_limit in GAS_LIMITS { + let delta = + with_child(100, false, gas_limit).regular - with_child(0, false, gas_limit).regular; + assert_eq!(delta, 100 * 11); + } +} + +/// A reverted frame gives its state and history back, never its computation: the hundred rounds a +/// callee ran before it reverted stay on the compute figure. +#[test] +fn test_a_reverted_frame_s_computation_stays_on_the_figure() { + for gas_limit in GAS_LIMITS { + let delta = + with_child(100, true, gas_limit).regular - with_child(0, true, gas_limit).regular; + assert_eq!(delta, 100 * 11); + } +} + +/// The figure belongs to its transaction: the same transaction twice on the same EVM computes the +/// same, whatever ran before it. +#[test] +fn test_each_transaction_computes_its_own() { + for gas_limit in GAS_LIMITS { + let db = funded().account_code(CALLEE, arithmetic(100)); + let mut evm = MegaEvm::new(context(db)); + let first = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); + let second = evm.execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); + assert!(first.result.is_success() && second.result.is_success()); + assert_ledgers("the first transaction", gas_limit, &first); + assert_ledgers("the second transaction", gas_limit, &second); + assert_eq!(first.gas.regular, second.gas.regular); + } +} + +/// A loop of `iterations` turns, twenty-six gas a turn: `PUSH3 n; JUMPDEST; PUSH1 1; SWAP1; SUB; +/// DUP1; PUSH1 4; JUMPI; POP; STOP`. +fn looping(iterations: u32) -> Bytes { + let [_, a, b, c] = iterations.to_be_bytes(); + Bytes::from(vec![PUSH3, a, b, c, JUMPDEST, PUSH1, 1, SWAP1, SUB, DUP1, PUSH1, 4, JUMPI, POP, 0]) +} + +/// A transaction that computes for millions of gas reports every one of them. +#[test] +fn test_millions_of_gas_of_computation_are_all_on_the_figure() { + for gas_limit in GAS_LIMITS { + let long = computes(looping(100_000), gas_limit); + let short = computes(looping(1), gas_limit); + assert_eq!(long.regular - short.regular, 26 * 99_999); + assert!(long.regular > 2_000_000); + } +} + +/* ---------- the execution cap ---------- */ + +/// Code that grows memory to a little over eleven megabytes, which costs some 240,000,000 gas +/// in one `MSTORE`: more than the execution cap, less than the gas limits above it. +fn past_the_cap() -> Bytes { + BytecodeBuilder::default() + .push_number(1_u8) + .push_number(11_199_968_u64) + .append(MSTORE) + .stop() + .build() +} + +/// Below the cap the gas limit is the compute budget, to the gas: a transaction whose limit is +/// exactly what it spends succeeds, and one gas less runs out. +/// +/// Only below the cap: above it the gas limit is not the budget, the cap is, and running out of +/// the reservoir spills onto regular gas rather than halting — which the history-byte tests hold +/// to the ledgers with reservoirs that run out. +#[test] +fn test_below_the_cap_the_gas_limit_is_the_compute_budget() { + let run = |gas_limit: u64| { + let outcome = execute( + funded().account_code(CALLEE, arithmetic(2_000)), + call(CALLER, CALLEE, U256::ZERO, gas_limit), + ); + assert_ledgers("the compute budget", gas_limit, &outcome); + outcome + }; + let spent = run(GAS_LIMITS[0]).gas.gas_used; + let exact = run(spent); + assert!(exact.result.is_success(), "{:?}", exact.result); + assert_eq!(exact.gas.gas_used, spent); + assert!(run(spent - 1).result.is_halt()); +} + +/// Above the gas limit's own reach, the execution cap is the compute budget: work that needs more +/// than 200,000,000 regular gas runs out of gas at the cap, even with a gas limit that could have +/// paid for it. It is an ordinary out-of-gas — a halt, not a limit stop — the regular ledger is the +/// cap exactly, and the reservoir above the cap comes back less the body's history it paid. +#[test] +fn test_computation_past_the_execution_cap_is_an_ordinary_out_of_gas() { + if runs_at_measurement_prices() { + return; + } + for reservoir in [50_000_000, 100_000_000] { + let gas_limit = TX_GAS_LIMIT_CAP + reservoir; + let outcome = execute( + funded().account_code(CALLEE, past_the_cap()), + call(CALLER, CALLEE, U256::ZERO, gas_limit), + ); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Memory)), + .. + } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None, "no limit of this engine stopped it"); + assert_ledgers("past the cap", gas_limit, &outcome); + assert_eq!(outcome.gas.regular, TX_GAS_LIMIT_CAP, "the whole execution budget, no more"); + assert_eq!(outcome.gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE); + assert_eq!(outcome.gas.reservoir_remaining, reservoir - outcome.gas.history); + assert_eq!(outcome.gas.gas_used, TX_GAS_LIMIT_CAP + outcome.gas.history); + } +} + +/// A nested call cannot compute past the cap either. Its callee is forwarded what the cap leaves, +/// runs out of gas and fails; its caller resumes on the sixty-fourth it kept, and the transaction +/// computes less than the cap. +/// +/// Only above the cap: below it the gas limit bounds the callee long before the cap does. +#[test] +fn test_a_nested_call_cannot_compute_past_the_cap() { + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .append(GAS) + .append(CALL) + .append(PUSH0) + .append(revm::bytecode::opcode::SSTORE) + .stop() + .build(); + let db = funded().account_code(CALLEE, caller).account_code(CHILD, past_the_cap()); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMITS[1])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("a nested call past the cap", GAS_LIMITS[1], &outcome); + assert_eq!( + outcome.state[&CALLEE].storage[&U256::ZERO].present_value, + U256::ZERO, + "the call failed, and its flag says so", + ); + assert!(outcome.gas.regular < TX_GAS_LIMIT_CAP, "{:?}", outcome.gas); + assert!(outcome.gas.regular > TX_GAS_LIMIT_CAP / 64 * 63, "the callee burned its share"); +} + +/// A transaction whose intrinsic gas alone is more computation than the cap allows is rejected +/// before it runs, not included as a failure: an access list of 47,844 addresses is 4,180 gas each +/// on top of the call, just past the cap, and one address fewer is admitted. +#[test] +fn test_intrinsic_gas_past_the_execution_cap_is_rejected_before_it_runs() { + if runs_at_measurement_prices() { + return; + } + let with_addresses = |addresses: usize| { + let access_list = + AccessList(vec![AccessListItem { address: CALLEE, storage_keys: vec![] }; addresses]); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: TX_GAS_LIMIT_CAP + 200_000_000, + access_list, + ..Default::default() + })) + }; + let rejection = |tx| { + let err = MegaEvm::new(context(funded())).transact_raw(tx).expect_err("rejected"); + err.as_invalid_tx_err().and_then(InvalidTxError::as_invalid_tx_err).cloned() + }; + + let address = entry(GasId::tx_access_list_address_cost()); + let inside = (TX_GAS_LIMIT_CAP - EMPTY_CALL) / address; + let admitted = execute(funded(), with_addresses(inside as usize)); + assert!(admitted.result.is_success(), "{:?}", admitted.result); + assert_ledgers("an access list just inside the cap", TX_GAS_LIMIT_CAP + 200_000_000, &admitted); + assert_eq!(admitted.gas.regular, EMPTY_CALL + address * inside); + assert_eq!( + rejection(with_addresses(inside as usize + 1)), + Some(InvalidTransaction::GasFloorMoreThanGasLimit { + gas_floor: EMPTY_CALL + address * (inside + 1), + gas_limit: TX_GAS_LIMIT_CAP, + }), + ); +} + +/* ---------- precompiles ---------- */ + +/// `CALL(gas, precompile, 0, 0, input_len, 0, 32)`, discarding the flag. +fn calls_precompile( + code: BytecodeBuilder, + precompile: Address, + input_len: u8, + gas: u64, +) -> BytecodeBuilder { + code.push_number(32_u8) + .append(PUSH0) + .push_number(input_len) + .append_many([PUSH0, PUSH0]) + .push_address(precompile) + .push_number(gas) + .append(CALL) + .append(POP) +} + +/// What a contract making `calls` computes beyond the same contract forwarding each call no gas at +/// all, which runs no precompile: exactly what the precompiles themselves cost. +fn precompiles_compute(calls: &[(Address, u8, u64)]) -> u64 { + let program = |forward: bool| { + let mut code = BytecodeBuilder::default(); + for &(precompile, input_len, gas) in calls { + code = calls_precompile(code, precompile, input_len, if forward { gas } else { 0 }); + } + code.stop().build() + }; + let [below, above] = GAS_LIMITS.map(|gas_limit| { + computes(program(true), gas_limit).regular - computes(program(false), gas_limit).regular + }); + assert_eq!(below, above, "below and above the execution cap"); + below +} + +/// SHA-256 of one word: 60 and 12 a word. +const SHA256_WORD: u64 = 72; +/// RIPEMD-160 of one word: 600 and 120 a word. +const RIPEMD160_WORD: u64 = 720; +/// ECRECOVER, whatever its input. +const ECRECOVER_COST: u64 = 3_000; +/// The BN254 pairing check of one pair: 45,000 for the call and 34,000 a pair. +const PAIRING_ONE_PAIR: u64 = 79_000; + +/// A precompile is computed at its price, and precompiles one after another add up. +#[test] +fn test_precompiles_are_computed_at_their_price_and_add_up() { + let sha = (*SHA256.address(), 32, 100_000); + let ripemd = (*RIPEMD160.address(), 32, 100_000); + let ecrecover = (*ECRECOVER.address(), 128, 100_000); + assert_eq!(precompiles_compute(&[sha]), SHA256_WORD); + assert_eq!( + precompiles_compute(&[sha, ripemd, ecrecover]), + SHA256_WORD + RIPEMD160_WORD + ECRECOVER_COST + ); +} + +/// A precompile runs on exactly its price and not one gas less; forwarded less, it fails and +/// burns everything it was forwarded, which is computation too. The expensive pairing check +/// holds to the same rule as a hash. +#[test] +fn test_a_precompile_runs_on_exactly_its_price() { + for (precompile, input_len, price) in + [(*SHA256.address(), 32, SHA256_WORD), (pair::ADDRESS, 192, PAIRING_ONE_PAIR)] + { + assert_eq!(precompiles_compute(&[(precompile, input_len, price)]), price); + assert_eq!(precompiles_compute(&[(precompile, input_len, price - 1)]), price - 1); + } +} + +/// A precompile a nested frame calls is computed where it runs, and the transaction counts it: +/// the same hash costs the same from the callee as from the transaction's own frame. +#[test] +fn test_a_precompile_in_a_nested_call_is_computed() { + let child = |gas: u64| calls_precompile(BytecodeBuilder::default(), *SHA256.address(), 32, gas); + let [below, above] = GAS_LIMITS.map(|gas_limit| { + let run = |gas: u64| { + let caller = calls(BytecodeBuilder::default(), CHILD, 1_000_000).stop().build(); + let db = funded() + .account_code(CALLEE, caller) + .account_code(CHILD, child(gas).stop().build()); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_ledgers("a precompile in a nested call", gas_limit, &outcome); + outcome.gas.regular + }; + run(100_000) - run(0) + }); + assert_eq!(below, SHA256_WORD, "below the execution cap"); + assert_eq!(above, SHA256_WORD, "above it"); +} + +/// Opcodes and precompiles in one frame add up: a hundred rounds of arithmetic, a hash and a +/// hundred more rounds compute the rounds and the hash. +#[test] +fn test_opcodes_and_precompiles_add_up() { + let program = |gas: u64| { + let mut code = BytecodeBuilder::default(); + for _ in 0..100 { + code = code.push_number(1_u8).push_number(2_u8).append(ADD).append(POP); + } + code = calls_precompile(code, *SHA256.address(), 32, gas); + for _ in 0..100 { + code = code.push_number(3_u8).push_number(4_u8).append(MUL).append(POP); + } + code.stop().build() + }; + for gas_limit in GAS_LIMITS { + let mixed = computes(program(100_000), gas_limit).regular; + let without_the_hash = computes(program(0), gas_limit).regular; + let bare = computes( + calls_precompile(BytecodeBuilder::default(), *SHA256.address(), 32, 0).stop().build(), + gas_limit, + ) + .regular; + assert_eq!(mixed - without_the_hash, SHA256_WORD); + assert_eq!( + without_the_hash - bare, + 100 * 11 + 100 * 13, + "the rounds, eleven and thirteen gas" + ); + } +} diff --git a/crates/mega-evm/tests/satin/contract_size.rs b/crates/mega-evm/tests/satin/contract_size.rs index c8e9c136c..22c935f7b 100644 --- a/crates/mega-evm/tests/satin/contract_size.rs +++ b/crates/mega-evm/tests/satin/contract_size.rs @@ -8,24 +8,31 @@ use alloy_evm::{Evm, EvmError, InvalidTxError}; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE}, + constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, test_utils::{right_pad_bytes, BytecodeBuilder, MemoryDatabase}, MegaEvm, MegaHaltReason, MegaTransaction, }; use revm::{ bytecode::opcode::{CREATE, INVALID, ISZERO, JUMPDEST, JUMPI, PUSH1, RETURN, STOP}, context::result::{ExecutionResult, HaltReason, InvalidTransaction}, - primitives::{eip170, eip3860}, }; -use crate::common::{call, context, create}; +use crate::common::{call, context, create, history}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); const FACTORY: Address = address!("0000000000000000000000000000000000100001"); -/// Room for the state gas a megabyte of deployed code draws, all of it above the execution cap so -/// it comes out of the reservoir. -const GAS_LIMIT: u64 = 4_000_000_000; +/// Room for everything a creation here draws, all of it above the execution cap so it comes out of +/// the reservoir: the state gas of the largest deployable code, the history of that code and of a +/// body carrying twice the largest init code, and a billion more, at the byte prices in effect. +fn gas_limit() -> u64 { + TX_GAS_LIMIT_CAP + + MAX_CONTRACT_SIZE as u64 * + mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::code_deposit_state_gas()) + + history((MAX_CONTRACT_SIZE + 2 * MAX_INITCODE_SIZE) as u64) + + 1_000_000_000 +} /// Runs `tx` from `CALLER` and returns its result, or the validation error that rejected it. fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result, String> { @@ -45,7 +52,7 @@ fn run(tx: MegaTransaction, db: MemoryDatabase) -> Result Result, String> { let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - run(create(CALLER, init_code, GAS_LIMIT), db) + run(create(CALLER, init_code, gas_limit()), db) } /// Init code of `size` bytes that does nothing. @@ -84,12 +91,6 @@ fn assert_code_size_limit(result: Result, String /* ---------- the initcode bound ---------- */ -/// An initcode of EIP-3860's size is far below the Satin bound and goes through. -#[test] -fn test_the_eip3860_initcode_size_is_accepted() { - assert!(deploy(initcode_of(eip3860::MAX_INITCODE_SIZE)).unwrap().is_success()); -} - /// The Satin bound itself is accepted. #[test] fn test_the_satin_initcode_size_is_accepted() { @@ -102,27 +103,8 @@ fn test_one_byte_past_the_satin_initcode_size_is_rejected() { assert_initcode_limit(deploy(initcode_of(MAX_INITCODE_SIZE + 1))); } -/// So is twice it. -#[test] -fn test_double_the_satin_initcode_size_is_rejected() { - assert_initcode_limit(deploy(initcode_of(2 * MAX_INITCODE_SIZE))); -} - -/// The initcode bound is twice the contract bound, which is the ratio EIP-3860 sets. -#[test] -fn test_the_initcode_bound_is_twice_the_contract_bound() { - assert_eq!(MAX_INITCODE_SIZE, 2 * MAX_CONTRACT_SIZE); - assert_eq!(MAX_CONTRACT_SIZE, 512 * 1024); -} - /* ---------- the deployed-code bound, from a creation transaction ---------- */ -/// Code of EIP-170's size deploys. -#[test] -fn test_the_eip170_code_size_deploys() { - assert!(deploy(constructor_returning(eip170::MAX_CODE_SIZE)).unwrap().is_success()); -} - /// Code of the Satin size deploys. #[test] fn test_the_satin_code_size_deploys() { @@ -135,12 +117,6 @@ fn test_one_byte_past_the_satin_code_size_halts() { assert_code_size_limit(deploy(constructor_returning(MAX_CONTRACT_SIZE + 1))); } -/// So does twice it. -#[test] -fn test_double_the_satin_code_size_halts() { - assert_code_size_limit(deploy(constructor_returning(2 * MAX_CONTRACT_SIZE))); -} - /* ---------- the deployed-code bound, from a CREATE ---------- */ /// A contract that `CREATE`s a contract of `size` bytes and runs `INVALID` if the creation failed, @@ -169,7 +145,7 @@ fn create_through_factory(size: usize) -> bool { .account_balance(CALLER, U256::from(10u64.pow(18))) .account_code(FACTORY, factory_creating(size)); let result = - run(call(CALLER, FACTORY, U256::ZERO, GAS_LIMIT), db).expect("the transaction is valid"); + run(call(CALLER, FACTORY, U256::ZERO, gas_limit()), db).expect("the transaction is valid"); match result { ExecutionResult::Success { .. } => true, ExecutionResult::Halt { @@ -179,14 +155,6 @@ fn create_through_factory(size: usize) -> bool { } } -/// A `CREATE` of EIP-170's size succeeds, and so does one byte past it: EIP-170 is not the bound -/// here. -#[test] -fn test_create_of_the_eip170_code_size_succeeds() { - assert!(create_through_factory(eip170::MAX_CODE_SIZE)); - assert!(create_through_factory(eip170::MAX_CODE_SIZE + 1)); -} - /// A `CREATE` of the Satin size succeeds. #[test] fn test_create_of_the_satin_code_size_succeeds() { diff --git a/crates/mega-evm/tests/satin/corpus.rs b/crates/mega-evm/tests/satin/corpus.rs new file mode 100644 index 000000000..c9cc5a99d --- /dev/null +++ b/crates/mega-evm/tests/satin/corpus.rs @@ -0,0 +1,59 @@ +//! The corpus bench's scenarios keep their outcome and gas. +//! +//! `benches/corpus.rs` times the JSON scenarios under `benches/scenarios`. A change that sends a +//! transaction of one down a shorter path would be timed without notice, so every transaction of +//! every scenario file is pinned here: its outcome class and its gas used. +//! The scenarios fix their gas limits, so at dearer byte prices a transaction can run out of gas; +//! the pins hold at the spec's byte prices only, and the snapshot is skipped at other ones. + +use std::{collections::BTreeMap, path::Path}; + +use mega_evm::{revm::context::result::ExecutionResult, test_utils::Scenario}; +use serde::Serialize; + +/// One transaction's outcome class: `success`, `revert` or `halt()`. +fn class(result: &ExecutionResult) -> String { + match result { + ExecutionResult::Success { .. } => "success".to_owned(), + ExecutionResult::Revert { .. } => "revert".to_owned(), + ExecutionResult::Halt { reason, .. } => format!("halt({reason:?})"), + } +} + +#[derive(Serialize)] +struct Tx { + outcome: String, + gas_used: u64, +} + +#[test] +fn test_corpus_scenarios_keep_their_outcome_and_gas() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("benches/scenarios"); + let mut gas: BTreeMap> = BTreeMap::new(); + for entry in std::fs::read_dir(&dir).unwrap() { + let path = entry.unwrap().path(); + assert_eq!( + path.extension().and_then(|ext| ext.to_str()), + Some("json"), + "{path:?}: the scenarios directory holds only scenario json" + ); + let name = path.file_stem().unwrap().to_str().unwrap().to_owned(); + let text = std::fs::read_to_string(&path).unwrap(); + let scenario: Scenario = + serde_json::from_str(&text).unwrap_or_else(|err| panic!("{path:?}: {err}")); + scenario.validate().unwrap_or_else(|err| panic!("{path:?}: {err}")); + let (outcomes, _) = scenario.run(scenario.database()); + let mut scenario_gas = Vec::new(); + for (i, outcome) in outcomes.iter().enumerate() { + let executed = outcome.as_ref().unwrap_or_else(|err| { + panic!("{name}: tx[{i}] is rejected: {err:?}"); + }); + let outcome = class(&executed.result); + scenario_gas.push(Tx { outcome, gas_used: executed.result.tx_gas_used() }); + } + gas.insert(name, scenario_gas); + } + assert_eq!(gas.len(), 13, "the corpus has 13 scenarios"); + + crate::assert_sorted_json_snapshot!("corpus_outcomes_and_gas", gas); +} diff --git a/crates/mega-evm/tests/satin/count_order.rs b/crates/mega-evm/tests/satin/count_order.rs new file mode 100644 index 000000000..569baeae1 --- /dev/null +++ b/crates/mega-evm/tests/satin/count_order.rs @@ -0,0 +1,83 @@ +//! The order the two data-size counts are checked in, when one record crosses both at once. +//! +//! A record is counted on the transaction and on the frame that makes it: the transaction against +//! its limit, the frame against its budget. The transaction is checked first, and the first count +//! crossed is the one the stop names. Either reverts the frame that crossed it alone, and the +//! caller goes on. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitKind, LimitUsage, MegaLimitExceeded, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{CALL, GAS, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE}; + +use crate::common::{call, execute_under}; + +const CALLER: Address = address!("0000000000000000000000000000000000f20000"); +/// The transaction's own frame: two fresh slots, then a call to [`B`], whose output it returns. +const A: Address = address!("0000000000000000000000000000000000f20001"); +/// A frame one call down: one fresh slot. +const B: Address = address!("0000000000000000000000000000000000f20002"); + +/// Room for three fresh slots and the calls around them, at any byte price the grid reaches. +const GAS_LIMIT: u64 = 100_000_000; + +/// One record that crosses the transaction's data-size limit and its frame's budget at once is +/// stopped with the transaction's limit, which is checked first. +/// +/// [`A`] keeps two records, so the transaction has 310 + 2 × 40 = 390 bytes when [`B`] makes the +/// record that crosses, which brings it to 430 bytes, and [`B`]'s own count to 40 bytes. `A`'s +/// budget is what the transaction has left, under the per-frame cap; `B`'s is 98/100 of what `A` +/// has left, rounded down. With a per-frame cap of 120, `A` has 120 − 80 = 40 bytes left and `B` +/// gets 39. A transaction limit of 390 leaves `A` 80 bytes, and `B` none. +/// +/// Either way [`B`] reverts alone with `MegaLimitExceeded(kind, limit)` and [`A`] returns what it +/// reverted with: the limit named is the one the order picks. The row that crosses the frame's +/// budget alone shows that the count the first row ranks second is crossed. +/// +/// Rules: [S10.48], [S10.31], [S10.33], [S10.34], [S10]. Independence: constants — the usages and +/// budgets are hand arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE` and the 98/100 share. +#[test] +fn test_a_record_crossing_both_counts_is_reported_for_the_transaction() { + let unlimited = EvmTxRuntimeLimits::no_limits(); + let before = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE; + let rows: [(&str, EvmTxRuntimeLimits, u64); 2] = [ + ( + "the transaction's limit and the frame's budget: the transaction's limit", + unlimited.with_tx_data_size_limit(before).with_frame_data_size_limit(120), + before, + ), + ("the frame's budget alone", unlimited.with_frame_data_size_limit(120), 39), + ]; + let a = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append_many([GAS, CALL, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, RETURNDATASIZE]) + .append_many([PUSH0, RETURN]) + .build(); + let b = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); + for (row, limits, named) in rows { + let db = MemoryDatabase::default().account_code(A, a.clone()).account_code(B, b.clone()); + let outcome = execute_under(db, call(CALLER, A, U256::ZERO, GAS_LIMIT), limits); + let revert_data: Bytes = + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: named } + .abi_encode() + .into(); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + assert_eq!( + outcome.result.output(), + Some(&revert_data), + "{row}: B reverted alone, and A returned what it reverted with" + ); + assert_eq!(outcome.limit_exceeded, None, "{row}: no stop of the transaction's own frame"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: before, write_records: 2 }, + "{row}: A's two records, none of B's" + ); + } +} diff --git a/crates/mega-evm/tests/satin/create_opcodes.rs b/crates/mega-evm/tests/satin/create_opcodes.rs new file mode 100644 index 000000000..e75882763 --- /dev/null +++ b/crates/mega-evm/tests/satin/create_opcodes.rs @@ -0,0 +1,231 @@ +//! What a `CREATE2` does with its operands before it starts a frame, as revm does it. +//! +//! Satin runs revm's own `CREATE2` and charges the records of the frame it starts afterwards, so +//! everything up to the frame's start is canonical: a missing operand is a `StackUnderflow`; an +//! init code over the limit is refused before its offset is read or memory is touched; an empty +//! init code reads no offset, touches no memory and hashes to `KECCAK_EMPTY`; and a non-empty one +//! pays for its words — the memory it expands, EIP-3860's cost and the hash — before the creation +//! starts. +//! +//! An inner frame's memory is not visible in the transaction's result, so [`CreateMemory`] reads it +//! after the `CREATE2` instruction ran, halted or not. + +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use mega_evm::{ + constants::MAX_INITCODE_SIZE, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaHaltReason, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{CREATE2, STOP}, + context::result::{ExecutionResult, HaltReason, OutOfGasError}, + interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, + primitives::KECCAK_EMPTY, + Database, Inspector, +}; + +use crate::common::{body_history, call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000e10000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000e10001"); + +/// The memory size of the frame that ran a `CREATE2`, read after the instruction. +#[derive(Default)] +struct CreateMemory { + opcode: u8, + after_create2: Option, +} + +impl Inspector, EthInterpreter> for CreateMemory { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.opcode == CREATE2 && self.after_create2.is_none() { + self.after_create2 = Some(interp.memory.len()); + } + } +} + +/// `CREATE2` with the operands given, `value` last, then `STOP`. +fn create2(salt: Option, len: Option, offset: Option) -> Bytes { + let mut code = BytecodeBuilder::default(); + for operand in [salt, len, offset].into_iter().flatten() { + code = code.push_u256(operand); + } + code.push_u256(U256::ZERO).append(CREATE2).append(STOP).build() +} + +/// `CREATE2(value = 0, offset, len, salt = 0)`. +fn create2_of(len: U256, offset: U256) -> Bytes { + create2(Some(U256::ZERO), Some(len), Some(offset)) +} + +/// Runs `CONTRACT` holding `code` at `gas_limit`, and what the frame's memory held after the +/// `CREATE2`. +fn run(code: Bytes, gas_limit: u64) -> (MegaTransactionOutcome, Option) { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db)).with_inspector(CreateMemory::default()); + let outcome = evm + .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + (outcome, evm.inspector().after_create2) +} + +/// A gas limit with room for any creation here: 100,000,000, on top of what the created account +/// and its records cost at the byte prices in effect, and below the execution cap. +fn roomy() -> u64 { + 100_000_000 + crate::common::account_state_gas() + body_history(0) +} + +fn halted_with(outcome: &MegaTransactionOutcome) -> Option { + match &outcome.result { + ExecutionResult::Halt { reason: MegaHaltReason::Base(reason), .. } => Some(reason.clone()), + _ => None, + } +} + +/// A `CREATE2` missing an operand halts with `StackUnderflow`: only `value`; `value` and `offset`; +/// and every operand but the salt, with a 32 KiB length. revm pops the salt last, after it sized +/// the init code, so that frame's memory is expanded before it halts, as in revm; the halt burns +/// the frame's gas either way, so the order shows in no result. +#[test] +fn test_create2_with_missing_operands_halts_with_stack_underflow() { + let len = U256::from(32 * 1024); + let cases = [ + ("the offset missing", create2(None, None, None), 0), + ("the length missing", create2(None, None, Some(U256::ZERO)), 0), + ("the salt missing", create2(None, Some(len), Some(U256::ZERO)), 32 * 1024), + ]; + for (name, code, expanded) in cases { + let (outcome, memory) = run(code, roomy()); + assert_eq!(halted_with(&outcome), Some(HaltReason::StackUnderflow), "{name}"); + assert_eq!(memory, Some(expanded), "{name}: the memory at the halt"); + } +} + +/// An empty init code reads no offset: at an offset no `usize` holds the creation succeeds, +/// deploying the empty code at the address `KECCAK_EMPTY` derives. +#[test] +fn test_create2_len_zero_offset_max_succeeds() { + let (outcome, memory) = run(create2_of(U256::ZERO, U256::MAX), roomy()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(memory, Some(0)); + assert!(outcome.state.contains_key(&CONTRACT.create2(B256::ZERO, KECCAK_EMPTY))); +} + +/// The shortcut is for an empty init code alone: one byte at an offset no `usize` holds halts on +/// the offset. +#[test] +fn test_create2_len_nonzero_offset_max_halts() { + let (outcome, _) = run(create2_of(U256::from(1), U256::MAX), roomy()); + assert_eq!( + halted_with(&outcome), + Some(HaltReason::OutOfGas(OutOfGasError::InvalidOperand)), + "{:?}", + outcome.result + ); +} + +/// An empty init code at a large offset expands no memory and pays for none: the creation +/// succeeds, the frame's memory stays empty, and its regular gas is that of a small program. +#[test] +fn test_create2_len_zero_large_offset_skips_memory_expansion() { + let (outcome, memory) = run(create2_of(U256::ZERO, U256::from(1u64 << 30)), roomy()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(memory, Some(0), "no memory was expanded"); + assert!( + outcome.gas.regular < 100_000, + "{}: no gigabyte of memory paid for", + outcome.gas.regular + ); +} + +/// An empty init code at offset zero deploys the empty code at the address `KECCAK_EMPTY` +/// derives, which is the hash of the empty slice revm would otherwise have read. +#[test] +fn test_create2_len_zero_offset_zero_succeeds() { + assert_eq!(KECCAK_EMPTY, keccak256([])); + let (outcome, _) = run(create2_of(U256::ZERO, U256::ZERO), roomy()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let created = CONTRACT.create2(B256::ZERO, KECCAK_EMPTY); + assert_eq!(outcome.state[&created].info.nonce, 1, "the empty code is deployed there"); +} + +/// A 32 KiB init code pays for its words before the creation starts: the memory it expands +/// (`3w + w²/512`), EIP-3860's two gas a word and the hash's six. Against a one-word init code the +/// regular gas differs by exactly those; everything else, the created account and its records +/// included, is the same. +#[test] +fn test_create2_with_a_32_kib_init_code_pays_its_words() { + let memory = |words: u64| 3 * words + words * words / 512; + let words = 1_024; + let expected = memory(words) - memory(1) + (2 + 6) * (words - 1); + let small = run(create2_of(U256::from(32), U256::ZERO), roomy()).0; + let (large, memory_size) = run(create2_of(U256::from(32 * words), U256::ZERO), roomy()); + assert!(small.result.is_success() && large.result.is_success(), "{:?}", large.result); + assert_eq!(memory_size, Some(32 * 1_024)); + assert_eq!(large.gas.regular - small.gas.regular, expected); + assert_eq!(large.gas.state, small.gas.state); + assert_eq!(large.gas.history, small.gas.history); +} + +/// Init code of exactly the Satin limit is created; one byte more halts with +/// `CreateInitCodeSizeLimit`. +#[test] +fn test_create2_init_code_at_the_limit_succeeds_and_one_byte_more_halts() { + let at = run(create2_of(U256::from(MAX_INITCODE_SIZE), U256::ZERO), roomy()).0; + assert!(at.result.is_success(), "{:?}", at.result); + let over = run(create2_of(U256::from(MAX_INITCODE_SIZE + 1), U256::ZERO), roomy()).0; + assert_eq!(halted_with(&over), Some(HaltReason::CreateInitCodeSizeLimit), "{:?}", over.result); +} + +/// An init code over the limit halts with `CreateInitCodeSizeLimit` before memory is touched, +/// whether expanding memory to it would be affordable (just over the limit) or not (10 MiB). +#[test] +fn test_create2_oversized_init_code_halts_before_touching_memory() { + for len in [MAX_INITCODE_SIZE as u64 + 1, 10 * 1_024 * 1_024] { + let (outcome, memory) = run(create2_of(U256::from(len), U256::ZERO), roomy()); + assert_eq!( + halted_with(&outcome), + Some(HaltReason::CreateInitCodeSizeLimit), + "{len} bytes: {:?}", + outcome.result + ); + assert_eq!(memory, Some(0), "{len} bytes: no memory was expanded"); + } +} + +/// The size is checked before the offset is read: an oversized length at an offset no `usize` +/// holds halts with `CreateInitCodeSizeLimit`, not on the offset. +#[test] +fn test_create2_oversized_init_code_halts_before_its_offset_is_read() { + let code = create2_of(U256::from(MAX_INITCODE_SIZE + 1), U256::from(u128::MAX)); + let (outcome, _) = run(code, roomy()); + assert_eq!( + halted_with(&outcome), + Some(HaltReason::CreateInitCodeSizeLimit), + "{:?}", + outcome.result + ); +} + +/// A length within the limit whose memory the frame cannot afford halts on the memory, and the +/// transaction reports the halt: 500,000 bytes of init code on 200,000 of regular gas. +#[test] +fn test_create2_whose_init_code_memory_cannot_be_paid_halts_on_the_memory() { + let (outcome, _) = run(create2_of(U256::from(500_000), U256::ZERO), 200_000 + body_history(0)); + assert_eq!( + halted_with(&outcome), + Some(HaltReason::OutOfGas(OutOfGasError::Memory)), + "{:?}", + outcome.result + ); +} diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs new file mode 100644 index 000000000..8188ca906 --- /dev/null +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -0,0 +1,1518 @@ +//! The data-size limit: the 98% a child frame receives, the transaction body, and deployed code. +//! +//! A child frame's budget is 98% of what its parent has left. Crossing that budget, or the +//! transaction's own limit, reverts the frame that crossed it alone, and its parent resumes with +//! what the frame counted taken back. +//! +//! The body is counted before any frame and kept on every path; validation rejects a transaction +//! whose body, with a record for each authorization it carries, exceeds the limit. Deployed code is +//! counted on the creation's lane, one byte per byte, before the creation is committed, and only +//! when revm would deposit it. + +use alloy_evm::Evm; +use alloy_primitives::{address, keccak256, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, + MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADD, CALL, CREATE, CREATE2, GAS, ISZERO, LOG0, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, + RETURNDATASIZE, SELFDESTRUCT, SSTORE, STOP, + }, + context::result::{ExecutionResult, HaltReason}, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{ + account_state_gas, body_history, call, call_with_data, constructor_returning, context, create, + execute_under, history, history_is_free, history_rounds, share, slot_state_gas, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000300000"); +const A: Address = address!("0000000000000000000000000000000000300001"); +const B: Address = address!("0000000000000000000000000000000000300002"); +const C: Address = address!("0000000000000000000000000000000000300003"); +const D: Address = address!("0000000000000000000000000000000000300004"); + +const GAS_LIMIT: u64 = 20_000_000; + +/// [`GAS_LIMIT`] on top of twice the history of `bytes` at the byte prices in effect: enough for +/// the frame three calls down to keep `bytes`, after each caller kept a 64th of what it forwards. +fn gas_for_history(bytes: u64) -> u64 { + GAS_LIMIT + 2 * history(bytes) +} + +/// The least a parent must have left for the child's share of it to hold `bytes`: a limit that +/// fits a child's write by exactly its bytes still reverts the child on its own budget, which is +/// 98% of the parent's room, rounded down. +fn child_room(bytes: u64) -> u64 { + let room = (bytes * FRAME_DATA_SHARE_DENOMINATOR).div_ceil(FRAME_DATA_SHARE_NUMERATOR); + assert!(share(room) >= bytes && share(room - 1) < bytes, "the least room for {bytes} bytes"); + room +} + +/// Calls `next` with no value, then writes slot 2: the write is what a resumed caller runs. +fn call_then_store(next: Address) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(next) + .append(GAS) + .append(CALL) + .append(POP) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build() +} + +/// `LOG0` of `data_len` bytes at memory offset 0. +fn log0(data_len: u64) -> Bytes { + BytecodeBuilder::default() + .push_number(data_len) + .push_number(0_u64) + .append(LOG0) + .append(STOP) + .build() +} + +/// `A -> B -> C -> D`. `D` is at depth 3. +fn chain(innermost: Bytes) -> mega_evm::test_utils::MemoryDatabase { + mega_evm::test_utils::MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(A, call_then_store(B)) + .account_code(B, call_then_store(C)) + .account_code(C, call_then_store(D)) + .account_code(D, innermost) +} + +fn stored(state: &revm::state::EvmState, address: Address) -> bool { + state.get(&address).is_some_and(|account| { + account.storage.get(&U256::from(2)).is_some_and(|slot| slot.is_changed()) + }) +} + +/// The budget at depth 3 when every frame cap is `cap` and no frame has spent any of it before +/// the call that starts the next one. +fn budget_at_depth_3(cap: u64) -> u64 { + share(share(share(cap))) +} + +/// A log that fills `D`'s budget is kept, and `A`, `B` and `C` resume. One byte more reverts +/// `D` alone: the three callers still write the slot after the call, and the transaction reports +/// no stop. +#[test] +fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { + const CAP: u64 = 20_000; + let budget = budget_at_depth_3(CAP); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(CAP); + let run = |data_len: u64| { + let db = chain(log0(data_len)); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let gas_limit = gas_for_history(budget); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + ( + result, + evm.ctx().additional_limit().limit_exceeded().copied(), + evm.ctx().additional_limit().usage(), + ) + }; + + // 32 bytes for the log's address, and the data. Exactly the budget. + let (fits, stop, usage) = run(budget - 32); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(stop, None); + assert!(stored(&fits.state, A) && stored(&fits.state, B) && stored(&fits.state, C)); + assert_eq!(fits.result.logs().len(), 1); + assert_eq!(usage.write_records, 3, "one slot in each caller"); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + budget + 3 * 40); + + let (over, stop, usage) = run(budget - 31); + assert!(over.result.is_success(), "the callers resume: {:?}", over.result); + assert_eq!(stop, None, "a frame budget below the transaction's own frame is no stop of it"); + assert!(stored(&over.state, A) && stored(&over.state, B) && stored(&over.state, C)); + assert!(over.result.logs().is_empty(), "the log died with D"); + assert_eq!( + usage, + mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 3 * 40, write_records: 3 } + ); +} + +/// The same depth, with the transaction's limit tighter than the frame budgets. `D`'s log crosses +/// the transaction limit, which reverts `D` alone, with the revert data naming the transaction +/// limit: `C`, `B` and `A` resume, each writes its slot within what the transaction has left, and +/// the transaction succeeds. What it keeps is what the same chain keeps without the log: the log +/// went with `D`, and the transaction never kept more than its limit. +#[test] +fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { + const TX_LIMIT: u64 = 8_000; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_LIMIT); + let mut evm = MegaEvm::new(context(chain(log0(TX_LIMIT))).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + + assert!(outcome.result.is_success(), "the callers resume: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "a stop below the transaction's own frame is no stop"); + // `D` reverted with the transaction limit's stop: nothing was written before its log, so the + // log crossed it alone, and the transaction limit is checked before `D`'s budget. + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: TX_LIMIT }; + assert_eq!( + evm.inspector().calls.first(), + Some(&(D, InstructionResult::Revert, Bytes::from(stop.abi_encode()))), + "D returned the stop" + ); + assert!(stored(&outcome.state, A) && stored(&outcome.state, B) && stored(&outcome.state, C)); + assert!(outcome.result.logs().is_empty(), "the log went with D"); + let three_records = mega_evm::TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE; + assert_eq!(outcome.usage, LimitUsage { data_size: three_records, write_records: 3 }); + assert!(outcome.usage.data_size <= TX_LIMIT); + + // The same chain without the log keeps exactly as much. + let kept = MegaEvm::new( + context(chain(BytecodeBuilder::default().append(STOP).build())) + .with_tx_runtime_limits(limits), + ) + .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(kept.result.is_success(), "{:?}", kept.result); + assert_eq!(kept.limit_exceeded, None); + assert_eq!(kept.usage, outcome.usage); + assert!(stored(&kept.state, A) && stored(&kept.state, B) && stored(&kept.state, C)); +} + +/// Counts steps, so a frame answered without running is visible, and the result of each creation +/// and each call, the deepest first. +#[derive(Clone, Default)] +struct Probe { + steps: u32, + creates: Vec<(InstructionResult, Bytes)>, + calls: Vec<(Address, InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for Probe { + fn step(&mut self, _: &mut Interpreter, _: &mut MegaContext) { + self.steps += 1; + } + + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + let result = &outcome.result; + self.calls.push((inputs.target_address, result.result, result.output.clone())); + } + + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.creates.push((outcome.result.result, outcome.result.output.clone())); + } +} + +/// A contract that `CREATE`s `deployed` bytes and stops. +fn factory_deploying(deployed: u64) -> Bytes { + let init = constructor_returning(deployed); + BytecodeBuilder::default() + .mstore(0, &init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(POP) + .append(STOP) + .build() +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) +} + +/// Runs a creation transaction of `init` under `limits`, with the inspector on when `inspect` is. +fn run_create( + init: Bytes, + limits: EvmTxRuntimeLimits, + inspect: bool, +) -> (MegaTransactionOutcome, Probe) { + let mut evm = MegaEvm::new(context(funded()).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(create(CALLER, init, GAS_LIMIT)).unwrap(); + let probe = evm.inspector().clone(); + (outcome, probe) +} + +/// Calldata is part of the body, and a zero byte counts the same as any other. +#[test] +fn test_calldata_counts_in_the_body() { + let db = || funded().account_code(A, BytecodeBuilder::default().append(STOP).build()); + let run = |byte: u8| { + let outcome = MegaEvm::new(context(db())) + .execute_transaction(call_with_data(CALLER, A, Bytes::from(vec![byte; 50]), GAS_LIMIT)) + .unwrap(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome.usage + }; + let expected = LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 50, write_records: 0 }; + assert_eq!(run(0), expected, "a zero byte"); + assert_eq!(run(0xff), expected, "a non-zero byte"); +} + +/// Asserts `error` is the refusal of a body whose bytes and authorization records exceed the +/// transaction's data-size limit. +fn assert_body_refused(error: &str) { + assert!(error.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{error}"); +} + +/// Deployed code is one byte per byte on the creation, on top of the body and the created +/// account. One byte over the transaction limit reverts the creation and leaves no code. +#[test] +fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() { + const DEPLOYED: u64 = 32; + let init = constructor_returning(DEPLOYED); + let body = mega_evm::TX_BODY_SIZE + init.len() as u64; + let full = body + WRITE_RECORD_SIZE + DEPLOYED; + let created = CALLER.create(0); + let code_hash = keccak256(vec![0_u8; DEPLOYED as usize]); + + for inspect in [false, true] { + let (kept, _) = run_create( + init.clone(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(full), + inspect, + ); + assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); + assert_eq!(kept.limit_exceeded, None); + assert_eq!(kept.usage, LimitUsage { data_size: full, write_records: 1 }); + assert_eq!(kept.state[&created].info.code_hash, code_hash, "inspect {inspect}"); + + let (over, probe) = run_create( + init.clone(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(full - 1), + inspect, + ); + assert!(!over.result.is_success() && !over.result.is_halt(), "{:?}", over.result); + assert_eq!( + over.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: full - 1, + used: full, + frame_local: false, + }) + ); + assert_eq!( + over.usage, + LimitUsage { data_size: body, write_records: 0 }, + "the stop drops the code and the created account; the body stays" + ); + assert!( + over.state.get(&created).is_none_or(|account| account.info.is_empty_code_hash()), + "inspect {inspect}: the code was not deployed: {:?}", + over.state.get(&created).map(|account| account.info.code_hash), + ); + assert_eq!(over.state[&CALLER].info.nonce, 1, "the creator's nonce was bumped"); + if inspect { + assert_eq!(probe.creates.len(), 1); + assert_eq!(probe.creates[0].0, InstructionResult::Revert); + assert_eq!( + probe.creates[0].1.as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: full - 1 } + .abi_encode() + ); + } + } +} + +/// A child creation that crosses its own budget reverts alone. The code is not deployed, the +/// creator's nonce record stays, and the caller resumes. +#[test] +fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { + const CAP: u64 = 1_000; + // The transaction's frame is capped at `CAP` and has spent nothing, so the creation gets 98% + // of that. Its start records the created account and the creator's nonce before the code. + let child_budget = share(CAP); + let at_start = 2 * WRITE_RECORD_SIZE; + let fits = child_budget - at_start; + let db = |deployed| funded().account_code(A, factory_deploying(deployed)); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(CAP); + let created = A.create(0); + + let run = |deployed, inspect| { + let mut evm = MegaEvm::new(context(db(deployed)).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + ( + result, + evm.ctx().additional_limit().usage(), + evm.ctx().additional_limit().limit_exceeded().copied(), + evm.inspector().clone(), + ) + }; + + for inspect in [false, true] { + let (kept, usage, stop, _) = run(fits, inspect); + assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); + assert_eq!(stop, None); + assert_eq!( + usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + child_budget, write_records: 2 } + ); + assert_eq!(kept.state[&created].info.code_hash, keccak256(vec![0_u8; fits as usize])); + + let (over, usage, stop, probe) = run(fits + 1, inspect); + assert!(over.result.is_success(), "the caller resumes: {:?}", over.result); + assert_eq!(stop, None, "a frame budget below the transaction's own frame is no stop of it"); + assert_eq!( + usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + "the creator's nonce stays; the code and the created account do not" + ); + assert!( + over.state.get(&created).is_none_or(|account| account.info.is_empty_code_hash()), + "inspect {inspect}: {:?}", + over.state.get(&created).map(|account| account.info.code_hash), + ); + assert_eq!(over.state[&A].info.nonce, 1); + if inspect { + assert_eq!(probe.creates.len(), 1); + assert_eq!(probe.creates[0].0, InstructionResult::Revert); + assert_eq!( + probe.creates[0].1.as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: child_budget } + .abi_encode() + ); + } + } +} + +/// Init code that returns `len` bytes as the deployed contract, the first of them `first` and +/// the rest zeros. +fn constructor_returning_from(first: u8, len: u64) -> Bytes { + BytecodeBuilder::default() + .mstore(0, [first]) + .push_number(len) + .push_number(0_u8) + .append(RETURN) + .build() +} + +/// A contract that runs `init` through `CREATE`, then writes whether the creation failed to slot +/// 1, and stops. +fn factory_noting_failure(init: &Bytes) -> Bytes { + BytecodeBuilder::default() + .mstore(0, init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(ISZERO) + .push_number(1_u64) + .append(SSTORE) + .append(STOP) + .build() +} + +/// Only code `return_create` would deposit is counted. Code it refuses — starting with `0xEF` +/// (EIP-3541), or over the code-size limit — fails the creation alone, as it would with no limit: +/// the caller catches the failure and the transaction succeeds. The same number of bytes it would +/// deposit, with the gas to pay for them, is counted and crosses the transaction's limit, which +/// stops the creation with the limit's revert: the caller catches that failure too, and the code +/// goes with the creation. The reservoir of a gas limit far above the execution cap pays the state +/// gas and the history of a contract of the largest size. +/// +/// `A` has 100 bytes left: the creation's start records the created account and `A`'s nonce, and +/// the output comes on top. Afterwards `A` writes a slot to note the failure: the transaction +/// keeps the nonce record and that slot's. +#[test] +fn test_code_return_create_refuses_is_not_counted() { + let limit = mega_evm::TX_BODY_SIZE + 100; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let at_start = 2 * WRITE_RECORD_SIZE; + let max = MAX_CONTRACT_SIZE as u64; + let cases = [ + ("0xEF first", 0xEF, 21, InstructionResult::CreateContractStartingWithEF), + ("over the code-size limit", 0x00, max + 1, InstructionResult::CreateContractSizeLimit), + ]; + let run = |init: &Bytes, inspect: bool, gas_limit: u64| { + let db = funded().account_code(A, factory_noting_failure(init)); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + (outcome, evm.inspector().clone()) + }; + let failure_noted = |outcome: &MegaTransactionOutcome| { + outcome.state[&A].storage.get(&U256::from(1)).map(|slot| slot.present_value) + }; + + for (name, first, len, refusal) in cases { + for inspect in [false, true] { + let case = format!("{name}, inspect {inspect}"); + let (refused, probe) = run(&constructor_returning_from(first, len), inspect, GAS_LIMIT); + assert!(refused.result.is_success(), "{case}: {:?}", refused.result); + assert_eq!(refused.limit_exceeded, None, "{case}: the refused code is not counted"); + assert_eq!(failure_noted(&refused), Some(U256::from(1)), "{case}: A caught it"); + assert_eq!( + refused.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, + "{case}: the nonce record and the slot", + ); + assert_eq!( + refused.gas.history, + mega_evm::history_gas(refused.usage.data_size).unwrap(), + "{case}: history prices the same bytes", + ); + assert_eq!(refused.state[&A].info.nonce, 1, "{case}"); + if inspect { + assert_eq!(probe.creates.len(), 1, "{case}"); + assert_eq!(probe.creates[0].0, refusal, "{case}: revm's own refusal"); + } + + // The same length, deployable and paid for: counted, and it crosses. + let deployable = constructor_returning_from(0x00, len.min(max)); + // The reservoir pays the state gas and the history of the largest contract, and a + // billion more, at the byte prices in effect. + let roomy = TX_GAS_LIMIT_CAP + + max * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + + history(max) + + 1_000_000_000; + let (caught, probe) = run(&deployable, inspect, roomy); + assert!(caught.result.is_success(), "{case}: {:?}", caught.result); + assert_eq!(caught.limit_exceeded, None, "{case}: A caught the creation's stop"); + assert_eq!(failure_noted(&caught), Some(U256::from(1)), "{case}"); + assert_eq!( + caught.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, + "{case}: the code went with the creation", + ); + if inspect { + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + assert_eq!( + probe.creates, + [(InstructionResult::Revert, Bytes::from(stop.abi_encode()))], + "{case}: the code was counted, and crossed the limit", + ); + } + } + } +} + +fn run_at(db: MemoryDatabase, tx: mega_evm::MegaTransaction, limit: u64) -> MegaTransactionOutcome { + MegaEvm::new( + context(db) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), + ) + .execute_transaction(tx) + .unwrap() +} + +fn assert_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { + assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used, + frame_local: false, + }) + ); +} + +/// A log is 32 bytes for its address plus its data. One byte over that stops on the log: the +/// store after it is not in the crossing figure. +#[test] +fn test_a_log_one_byte_over_stops_on_the_log() { + let data_len = 10u64; + let log_bytes = 32 + data_len; + let code = BytecodeBuilder::default() + .push_number(data_len) + .push_number(0_u64) + .append(LOG0) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + let db = || funded().account_code(A, code.clone()); + let body = mega_evm::TX_BODY_SIZE; + + let fits = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + log_bytes + 40); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.result.logs().len(), 1); + assert_eq!(fits.result.logs()[0].data.data.len(), data_len as usize); + assert_eq!(fits.usage, LimitUsage { data_size: body + log_bytes + 40, write_records: 1 }); + + let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + log_bytes - 1); + assert_stopped(&over, body + log_bytes - 1, body + log_bytes); + assert!(over.result.logs().is_empty(), "the log that crossed was dropped"); + assert_eq!(over.usage.data_size, body, "the store after the log never counted"); +} + +/// A storage write is one 40-byte record. One byte over that stops on the write: the log after +/// it is not in the crossing figure. +#[test] +fn test_a_storage_write_one_byte_over_stops_on_the_write() { + let code = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .push_number(10_u64) + .push_number(0_u64) + .append(LOG0) + .stop() + .build(); + let db = || funded().account_code(A, code.clone()); + let body = mega_evm::TX_BODY_SIZE; + let record = 40; + + let fits = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record + 32 + 10); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.result.logs().len(), 1); + assert_eq!(fits.usage, LimitUsage { data_size: body + record + 42, write_records: 1 }); + + let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record - 1); + assert_stopped(&over, body + record - 1, body + record); + assert!(over.result.logs().is_empty(), "the log after the write never ran"); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); +} + +/// A value transfer's recipient is one 40-byte record, and the move leaves a transfer log; both are +/// counted when the transaction's frame starts. A limit either of them crosses stops the frame +/// there, before any value moves and before the recipient's code runs. +#[test] +fn test_an_account_write_one_byte_over_stops_on_the_recipient() { + let db = || { + funded().account_code( + B, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ) + }; + let body = mega_evm::TX_BODY_SIZE; + let record = 40; + let start = record + TRANSFER_LOG_SIZE; + + let fits = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + start + record); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.state[&B].info.balance, U256::from(1)); + assert_eq!(fits.usage, LimitUsage { data_size: body + start + record, write_records: 2 }); + + for limit in [body + record - 1, body + start - 1] { + let over = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), limit); + assert_stopped(&over, limit, body + start); + assert!(over.result.logs().is_empty(), "limit {limit}: no transfer log"); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + over.state.get(&B).map(|account| account.info.balance).unwrap_or_default(), + U256::ZERO + ); + assert!(over.state.get(&B).is_none_or(|account| { + account.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) + })); + } +} + +/// What one gas limit did with a transaction whose data size approaches the limit. +enum Bound { + /// The gas limit did not cover the intrinsic cost, so the transaction was not included. + Rejected, + /// The transaction ran out of gas before the write that approaches the limit was counted. + OutOfGas, + /// The write was counted, and the data-size stop is what the frame that made it returned: + /// the transaction's result when the frame is the transaction's own, a failed call that + /// returned the stop to the frame that made it otherwise. + DataSize, + /// The write was counted inside the data-size limit and the transaction succeeded. + Success, +} + +/// `A`'s code for the store sweep: one fresh slot. +fn fresh_slot() -> Bytes { + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build() +} + +/// `A`'s code for the frame-start sweep: a value `CALL` of one wei to [`FRESH`], which writes +/// two accounts, `A`'s and [`FRESH`]'s, answering as [`answer_the_call`] does. +fn value_call_to_fresh() -> Bytes { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(FRESH) + .append(GAS) + .append(CALL); + answer_the_call(code) +} + +/// Appends the answer to the call just made: its flag, the size of what it returned and what it +/// returned, `PUSH0; MSTORE; RETURNDATASIZE; PUSH1 32; MSTORE; RETURNDATASIZE; PUSH0; PUSH1 64; +/// RETURNDATACOPY; RETURNDATASIZE; PUSH1 64; ADD; PUSH0; RETURN`, so a reader of the output tells +/// a halt (a flag of zero and no return data) from a stop (the stop's revert data) and from a +/// success. +fn answer_the_call(code: BytecodeBuilder) -> Bytes { + code.append(PUSH0) + .append(MSTORE) + .append(RETURNDATASIZE) + .push_number(32_u8) + .append(MSTORE) + .append_many([RETURNDATASIZE, PUSH0]) + .push_number(64_u8) + .append_many([RETURNDATACOPY, RETURNDATASIZE]) + .push_number(64_u8) + .append_many([ADD, PUSH0, RETURN]) + .build() +} + +/// What a call [`answer_the_call`] answered for did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Answer { + /// The call succeeded. + Success, + /// The call failed with no return data: its frame halted. + Halt, + /// The call failed with a limit's stop: its dimension and limit. + Stop(LimitKind, u64), +} + +/// The [`Answer`] `answer` is, as [`answer_the_call`] wrote it: the call's flag, the size of what +/// it returned, and what it returned. +fn read_the_answer(answer: &[u8]) -> Answer { + let flag = U256::from_be_slice(&answer[..32]); + let returned = U256::from_be_slice(&answer[32..64]); + if flag == U256::ONE { + return Answer::Success; + } + assert!(flag.is_zero(), "a CALL's flag"); + assert_eq!(returned, U256::from(answer.len() - 64), "the return data follows"); + if returned.is_zero() { + return Answer::Halt; + } + let (kind, limit) = mega_evm::decode_mega_limit_exceeded(&answer[64..]) + .unwrap_or_else(|| panic!("the call failed with something other than a stop: {answer:?}")); + Answer::Stop(kind, limit) +} + +/// A call from `CALLER` to `A` running `code`, at `gas_limit`, under a transaction data-size limit +/// of `data_limit`. +fn bound_at(code: &Bytes, gas_limit: u64, data_limit: u64) -> Bound { + let db = funded().account_code(A, code.clone()).account_balance(A, U256::from(1)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data_limit); + match MegaEvm::new(context(db).with_tx_runtime_limits(limits)).execute_transaction(call( + CALLER, + A, + U256::ZERO, + gas_limit, + )) { + Err(_) => Bound::Rejected, + Ok(outcome) => match &outcome.result { + ExecutionResult::Halt { reason, .. } => { + assert!( + matches!(reason, MegaHaltReason::Base(HaltReason::OutOfGas(_))), + "a halt below the write is out of gas, got {reason:?}" + ); + assert_eq!(outcome.limit_exceeded, None, "an out-of-gas is not a data-size stop"); + Bound::OutOfGas + } + ExecutionResult::Revert { .. } => { + assert!(outcome.limit_exceeded.is_some(), "{:?}", outcome.result); + Bound::DataSize + } + ExecutionResult::Success { output, .. } => { + assert_eq!(outcome.limit_exceeded, None); + // A frame start the limit stopped: `A` answers the call it returned the stop to; + // code that answers nothing ran to its success. + if output.data().is_empty() { + return Bound::Success; + } + match read_the_answer(output.data()) { + Answer::Stop(..) => Bound::DataSize, + Answer::Halt => panic!("the call halted: {output:?}"), + Answer::Success => Bound::Success, + } + } + }, + } +} + +/// A gas limit above what any write here needs to be counted, at the byte prices in effect: +/// 1,000,000 on top of a new account, a fresh slot and the body, and 64 times the history of two +/// records, which a value call that forwards all but a 64th of its gas pays from the 64th it keeps. +fn high_bound() -> u64 { + 1_000_000 + + account_state_gas() + + slot_state_gas() + + body_history(0) + + 64 * history(2 * WRITE_RECORD_SIZE) +} + +/// The smallest gas limit at which `code`'s write is counted rather than run out of gas. +fn gas_where_the_write_is_counted(code: &Bytes, data_limit: u64) -> u64 { + smallest_gas_limit(high_bound(), |gas| { + !matches!(bound_at(code, gas, data_limit), Bound::Rejected | Bound::OutOfGas) + }) +} + +/// The smallest gas limit at which a top-level fresh `SSTORE` is counted at the spec's byte +/// prices. +/// +/// It is what the transaction pays up to and including the store, and nothing after it: +/// +/// | Part | Gas | +/// |---|---:| +/// | the call's intrinsic regular gas | 15,000 | +/// | the body's history: 310 bytes at 88 | 27,280 | +/// | two `PUSH32` | 6 | +/// | the `SSTORE`'s regular gas: 100 static, 2,000 cold, 10,000 set | 12,100 | +/// | the `SSTORE`'s state gas: a slot's 64 bytes at 1,530 | 97,920 | +/// | **total** | **152,306** | +/// +/// Below it the transaction runs out of gas before the store completes, whatever the data-size +/// limit. The record's history — 40 bytes at 88, 3,520 — is not part of it: it is charged after +/// the record is counted, and only for a record the limit keeps. +const FRESH_SLOT_COUNTED_AT: u64 = 152_306; + +/// A write meets two limits, and the one that binds first is the one reported. +/// +/// The opcode has to finish before its record exists: short of that it is an out-of-gas, and the +/// record is not counted. Once it finishes the record is counted, and a data-size limit it +/// crosses stops the transaction; the record's history is not charged, because the record is not +/// kept. A limit the record fits costs that history on top, and the write succeeds only once the +/// history is paid. Short of it, the same write halts out of gas. So a crossing limit moves the +/// out-of-gas boundary down by exactly the record's history, at a storage write, a log and a +/// `SELFDESTRUCT` alike. +/// +/// A `SELFDESTRUCT` that moves value counts its transfer log with its beneficiary's record, in one +/// check, so the two cross together; the log is data size and not history, so the boundary moves +/// by the record's history alone. +#[test] +fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { + let selfdestruct = BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(); + let sites = [ + ("a fresh slot", fresh_slot(), WRITE_RECORD_SIZE, WRITE_RECORD_SIZE), + ("a log of one byte", log0(1), mega_evm::LOG_BASE_SIZE + 1, mega_evm::LOG_BASE_SIZE + 1), + ( + "a SELFDESTRUCT that moves value", + selfdestruct, + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + WRITE_RECORD_SIZE, + ), + ]; + for (name, code, bytes, history_bytes) in sites { + // One byte under the record, the record itself crosses. + let crosses = mega_evm::TX_BODY_SIZE + bytes - 1; + let fits = mega_evm::TX_BODY_SIZE + bytes; + let counted_at = gas_where_the_write_is_counted(&code, crosses); + let kept_at = gas_where_the_write_is_counted(&code, fits); + let history = mega_evm::history_gas(history_bytes).expect("the record has a price"); + + assert_eq!(kept_at - counted_at, history, "{name}: a kept record costs its history"); + assert!(matches!(bound_at(&code, counted_at - 1, crosses), Bound::OutOfGas), "{name}"); + assert!(matches!(bound_at(&code, counted_at, crosses), Bound::DataSize), "{name}"); + assert!(matches!(bound_at(&code, kept_at, crosses), Bound::DataSize), "{name}"); + // A record whose history costs nothing, where a history byte is free, moves no boundary: + // the write the limit counts is the write that succeeds. + if history > 0 { + assert!(matches!(bound_at(&code, counted_at, fits), Bound::OutOfGas), "{name}"); + assert!(matches!(bound_at(&code, kept_at - 1, fits), Bound::OutOfGas), "{name}"); + } + assert!(matches!(bound_at(&code, kept_at, fits), Bound::Success), "{name}"); + } +} + +/// The fresh slot's figure, [`FRESH_SLOT_COUNTED_AT`], taken apart: what the call pays before its +/// code runs — the gas an empty call spends — then the two pushes and the store's regular and +/// state gas, all read from the schedule in force. The record's history comes on top only when +/// the record is kept. +#[test] +fn test_the_fresh_slot_boundary_is_the_sum_of_its_parts() { + let code = fresh_slot(); + let counted_at = + gas_where_the_write_is_counted(&code, mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE - 1); + let kept_at = gas_where_the_write_is_counted(&code, mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE); + let record_history = mega_evm::write_record_history_gas(1).expect("one record has a price"); + + let empty_call = MegaEvm::new(context(funded().account_code(A, Bytes::from_static(&[STOP])))) + .execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)) + .unwrap(); + assert!(empty_call.result.is_success()); + let params = mega_evm::satin_gas_params(); + let pushes = 2 * 3; + let store_regular = params.get(GasId::sstore_static()) + + params.get(GasId::cold_storage_cost()) + + params.get(GasId::sstore_set_without_load_cost()); + let store_state = params.get(GasId::sstore_set_state_gas()); + assert_eq!(counted_at, empty_call.gas.gas_used + pushes + store_regular + store_state); + assert_eq!(kept_at, counted_at + record_history); + + if crate::common::runs_at_measurement_prices() { + return; + } + assert_eq!(counted_at, FRESH_SLOT_COUNTED_AT); + assert_eq!(empty_call.gas.gas_used, 15_000 + 310 * 88); + assert_eq!((store_regular, store_state), (12_100, 97_920)); + assert_eq!(store_state, mega_evm::constants::SLOT_STATE_GAS); + assert_eq!(record_history, WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE); +} + +/// The bytes a value call's start counts on the caller's lane, its own account's record, and on +/// the frame's lane, the recipient's record and the transfer log. +const START_ON_THE_CALLER: u64 = WRITE_RECORD_SIZE; +const START_ON_THE_FRAME: u64 = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + +/// A transaction limit the start of [`value_call_to_fresh`] fits: the caller's record, and room +/// for the frame's lane under the 98% share the new frame is given of what the caller has left. +fn start_fits() -> u64 { + mega_evm::TX_BODY_SIZE + START_ON_THE_CALLER + child_room(START_ON_THE_FRAME) +} + +/// At a frame start the order is the other way round, and so is the rule's outcome: the caller +/// pays for the records the frame's start makes at its opcode, before the frame is started and +/// its records are counted. So the data-size limit does not move the out-of-gas boundary of a +/// value `CALL`: the smallest gas limit that is not an out-of-gas is the same whether the two +/// records and the transfer log cross the limit or fit it, and one gas below it is an out-of-gas +/// under either. The log is charged nothing at all. Under the limit they cross, the frame is +/// answered with the stop, which `A` catches; under the limit they fit, the frame starts and the +/// records are kept. +/// +/// Rules: [S7.28], [S10.10]. +#[test] +fn test_a_frame_start_is_charged_before_its_records_are_counted() { + let code = value_call_to_fresh(); + // `A`'s account and `FRESH`'s, and the transfer log: 240 bytes on top of the body. + let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let crosses = mega_evm::TX_BODY_SIZE + start - 1; + let fits = start_fits(); + let charged_at = gas_where_the_write_is_counted(&code, crosses); + + assert_eq!(gas_where_the_write_is_counted(&code, fits), charged_at); + assert!(matches!(bound_at(&code, charged_at - 1, crosses), Bound::OutOfGas)); + assert!(matches!(bound_at(&code, charged_at, crosses), Bound::DataSize)); + assert!(matches!(bound_at(&code, charged_at - 1, fits), Bound::OutOfGas)); + assert!(matches!(bound_at(&code, charged_at, fits), Bound::Success)); + let started = run_at( + funded().account_code(A, code).account_balance(A, U256::from(1)), + call(CALLER, A, U256::ZERO, charged_at), + fits, + ); + assert_eq!( + started.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 }, + "the frame started and its records were kept, not refused on the frame's budget", + ); +} + +/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but a 64th +/// keeps a 64th one gas short of the price of the two records its value call makes, under a +/// limit those records would cross. The caller pays for the records before they are counted, so +/// it runs out of gas first — a halt, no stop, nothing counted beyond the body — and the limit +/// never sees the start. One gas more, the 64th pays the records, they are counted, and the same +/// limit answers the start with the stop, which the caller catches; under a limit they fit, the +/// frame starts. +/// +/// The gas limit is the call's intrinsic 15,000, the body's history, the caller's sixteen gas of +/// pushes, the `CALL`'s regular gas — the value transfer, the cold recipient and the new account, +/// 11,300, 3,000 and nothing at the schedule's prices — the recipient's state gas (charged before +/// the split), and what the caller must hold at the split for its 64th to be the records' price +/// less one: `64 (price − 1) + 63` (`constants`: the two byte prices in effect; 690,755 at the +/// spec's prices). +#[test] +fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they_would_cross() { + // Records that cost nothing leave no price to be short of, and records priced at a fraction + // of a gas may round to nothing. + if history_is_free() || history_rounds() { + return; + } + let records = history(2 * WRITE_RECORD_SIZE); + let held_at_the_split = 64 * (records - 1) + 63; + let params = mega_evm::satin_gas_params(); + let value_call = params.get(GasId::transfer_value_cost()) + + params.get(GasId::warm_storage_read_cost()) + + params.get(GasId::cold_account_additional_cost()) + + params.get(GasId::new_account_cost()); + let gas_limit = + 15_000 + body_history(0) + 16 + value_call + account_state_gas() + held_at_the_split; + let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let crosses = mega_evm::TX_BODY_SIZE + start - 1; + let fits = start_fits(); + let db = || funded().account_code(A, value_call_to_fresh()).account_balance(A, U256::from(1)); + + for limit in [crosses, fits] { + let short = run_at(db(), call(CALLER, A, U256::ZERO, gas_limit), limit); + assert!( + matches!( + short.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ), + "under a limit of {limit}: the caller runs out of gas paying for the records: {:?}", + short.result, + ); + assert_eq!(short.limit_exceeded, None, "under a limit of {limit}: no limit saw the start"); + assert_eq!( + short.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "under a limit of {limit}: nothing was counted beyond the body", + ); + assert_eq!(short.gas.history, body_history(0), "under a limit of {limit}"); + assert_eq!(short.gas.state, 0, "under a limit of {limit}: the new account came back"); + assert_eq!(short.gas.gas_used, gas_limit, "under a limit of {limit}: the halt consumes it"); + } + + let stopped = run_at(db(), call(CALLER, A, U256::ZERO, gas_limit + 1), crosses); + assert!(stopped.result.is_success(), "the caller catches the stop: {:?}", stopped.result); + assert_eq!( + read_the_answer(stopped.result.output().expect("A answers")), + Answer::Stop(LimitKind::DataSize, crosses), + "the start was answered with the stop", + ); + assert_eq!(stopped.usage, LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }); + + let started = run_at(db(), call(CALLER, A, U256::ZERO, gas_limit + 1), fits); + assert!(started.result.is_success(), "one gas more, the frame starts: {:?}", started.result); + assert_eq!( + started.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 } + ); + assert_eq!(started.gas.history, body_history(0) + records); + assert_eq!(started.gas.state, account_state_gas()); + + if crate::common::runs_at_measurement_prices() { + return; + } + assert_eq!(records, 2 * 40 * 88); + assert_eq!(gas_limit, 690_755); +} + +/* ---------- a child frame's write, and the order where the reservoir runs out ---------- */ + +/// `A`'s code when the write is a child's: a `CALL` to `B` with `forward` gas and no value, +/// `PUSH0 ×4; PUSH0; PUSH20 B; PUSH4 forward; CALL`, answering as [`answer_the_call`] does. +fn calls_b_with(forward: u64) -> Bytes { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(u32::try_from(forward).expect("the forward fits a PUSH4")) + .append(CALL); + answer_the_call(code) +} + +/// A call from `CALLER` to `A`, which calls `B` running `code` with `forward` gas, at `gas_limit`, +/// under a transaction data-size limit of `data_limit`. `B` holds one wei, so a `SELFDESTRUCT` +/// of its moves value. +fn child_outcome( + code: &Bytes, + forward: u64, + gas_limit: u64, + data_limit: u64, +) -> MegaTransactionOutcome { + let db = funded() + .account_code(A, calls_b_with(forward)) + .account_code(B, code.clone()) + .account_balance(B, U256::from(1)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data_limit); + execute_under(db, call(CALLER, A, U256::ZERO, gas_limit), limits) +} + +/// What `B`'s write did, read off `A`'s answer: a stop of `B`, a halt of `B`, or a success. `A` +/// itself has gas to spare and room for nothing it keeps, so it always answers. +fn child_bound(outcome: &MegaTransactionOutcome) -> Bound { + assert!(outcome.result.is_success(), "A answers: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + match read_the_answer(outcome.result.output().expect("A answers")) { + Answer::Stop(..) => Bound::DataSize, + Answer::Halt => Bound::OutOfGas, + Answer::Success => Bound::Success, + } +} + +/// The smallest forward at which `code`'s write in `B` is counted rather than run out of gas, +/// below the cap. +fn forward_where_the_write_is_counted(code: &Bytes, data_limit: u64) -> u64 { + smallest_gas_limit(high_bound(), |forward| { + !matches!( + child_bound(&child_outcome(code, forward, GAS_LIMIT, data_limit)), + Bound::OutOfGas + ) + }) +} + +/// `B`'s code for a `SELFDESTRUCT` that moves its wei to `C`, which nobody has touched. +fn selfdestruct_to_c() -> Bytes { + BytecodeBuilder::default().push_address(C).append(SELFDESTRUCT).build() +} + +/// The same rule at a child frame's write [S7.27]: the record's history is the child's to pay, +/// out of the gas it was forwarded, so the forward where the write is counted and the forward +/// where it is kept are exactly the record's history apart, with the caller's gas out of the +/// picture. The fresh slot's forward is also the sum of its parts by hand: two pushes, the +/// store's regular gas and its state gas (`constants`). +#[test] +fn test_whichever_of_gas_and_data_size_binds_first_is_reported_at_a_childs_write() { + let sites = [ + ("a fresh slot", fresh_slot(), WRITE_RECORD_SIZE, WRITE_RECORD_SIZE), + ("a log of one byte", log0(1), mega_evm::LOG_BASE_SIZE + 1, mega_evm::LOG_BASE_SIZE + 1), + ( + "a SELFDESTRUCT that moves value", + selfdestruct_to_c(), + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + WRITE_RECORD_SIZE, + ), + ]; + for (name, code, bytes, history_bytes) in sites { + let crosses = mega_evm::TX_BODY_SIZE + bytes - 1; + let fits = mega_evm::TX_BODY_SIZE + child_room(bytes); + let counted_at = forward_where_the_write_is_counted(&code, crosses); + let kept_at = forward_where_the_write_is_counted(&code, fits); + let history = history(history_bytes); + let bound = |forward, limit| child_bound(&child_outcome(&code, forward, GAS_LIMIT, limit)); + + assert_eq!(kept_at - counted_at, history, "{name}: a kept record costs its history"); + assert!(matches!(bound(counted_at - 1, crosses), Bound::OutOfGas), "{name}"); + assert!(matches!(bound(counted_at, crosses), Bound::DataSize), "{name}"); + assert!(matches!(bound(kept_at, crosses), Bound::DataSize), "{name}"); + if history > 0 { + assert!(matches!(bound(counted_at, fits), Bound::OutOfGas), "{name}"); + assert!(matches!(bound(kept_at - 1, fits), Bound::OutOfGas), "{name}"); + } + assert!(matches!(bound(kept_at, fits), Bound::Success), "{name}"); + } + + let params = mega_evm::satin_gas_params(); + let store_regular = params.get(GasId::sstore_static()) + + params.get(GasId::cold_storage_cost()) + + params.get(GasId::sstore_set_without_load_cost()); + assert_eq!( + forward_where_the_write_is_counted( + &fresh_slot(), + mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE - 1 + ), + 2 * 3 + store_regular + slot_state_gas(), + "the fresh slot's forward is two pushes, the store's regular gas and its state gas", + ); +} + +/// Above the cap, where a reservoir one gas short of a record's history makes the order visible +/// [S7.27]: the record's history draws the reservoir first and spills its last gas onto the +/// child, which was forwarded exactly the gas of its write and has none left. Counted under a +/// limit it crosses, the record is refused and nothing is charged — the transaction stops, and +/// the spill the child could not pay is never asked of it. A charge made before the check would +/// have run the child out of gas instead, and the limit would have reported nothing. Under a +/// limit the record fits, the spill is asked, the child runs out, and one gas more pays it with +/// the reservoir spent to the last gas. +/// +/// Every forward is by hand — pushes, the opcode's regular gas, and the state gas it adds, drawn +/// from the reservoir (`constants`: the schedule in effect for the store, the byte prices for the +/// state gas and the record). +#[test] +fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_too_few() { + // A record that costs nothing leaves no gas for the reservoir to be short of, and one priced + // at a fraction of a gas may round to nothing. + if history_is_free() || history_rounds() { + return; + } + let params = mega_evm::satin_gas_params(); + let store_regular = params.get(GasId::sstore_static()) + + params.get(GasId::cold_storage_cost()) + + params.get(GasId::sstore_set_without_load_cost()); + // (site, code, the child's regular gas up to and including the write, the state gas the write + // adds, the bytes the limit counts, the record's history bytes, the records kept) + let sites = [ + ( + "a fresh slot", + fresh_slot(), + 2 * 3 + store_regular, + slot_state_gas(), + WRITE_RECORD_SIZE, + WRITE_RECORD_SIZE, + 1, + ), + ( + "a log of one byte", + log0(1), + 2 * 3 + (375 + 8 + 3), + 0, + mega_evm::LOG_BASE_SIZE + 1, + mega_evm::LOG_BASE_SIZE + 1, + 0, + ), + ( + "a SELFDESTRUCT that moves value", + selfdestruct_to_c(), + 3 + (5_000 + params.selfdestruct_cost(true, true)), + account_state_gas(), + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + WRITE_RECORD_SIZE, + 1, + ), + ]; + let body = body_history(0); + for (name, code, counted_at, state, bytes, history_bytes, records) in sites { + let record = history(history_bytes); + let reservoir = body + state + record - 1; + let gas_limit = TX_GAS_LIMIT_CAP + reservoir; + let crosses = mega_evm::TX_BODY_SIZE + bytes - 1; + let fits = mega_evm::TX_BODY_SIZE + child_room(bytes); + let run = |forward, limit| child_outcome(&code, forward, gas_limit, limit); + let body_only = LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }; + + // One gas short of the write itself: an out-of-gas before any record exists, under either + // limit, with the reservoir untouched beyond the body. + for limit in [crosses, fits] { + let short = run(counted_at - 1, limit); + assert!(matches!(child_bound(&short), Bound::OutOfGas), "{name} under {limit}"); + assert_eq!(short.usage, body_only, "{name} under {limit}"); + assert_eq!(short.gas.reservoir_remaining, reservoir - body, "{name} under {limit}"); + } + + // The record refused: counted, the limit crosses, the child stops. Nothing was charged + // for it, so the one gas it would spill was never asked of the child. + let refused = run(counted_at, crosses); + assert!(matches!(child_bound(&refused), Bound::DataSize), "{name}: {:?}", refused.result); + assert_eq!( + read_the_answer(refused.result.output().expect("A answers")), + Answer::Stop(LimitKind::DataSize, crosses), + "{name}: the record crossed the transaction's limit", + ); + assert_eq!(refused.gas.history, body, "{name}: the refused record was not charged"); + assert_eq!(refused.gas.state, 0, "{name}: the stop gave the state gas back"); + assert_eq!(refused.usage, body_only, "{name}: the record went with the child"); + assert_eq!(refused.gas.reservoir_remaining, reservoir - body, "{name}: the reservoir"); + + // The record kept: its history draws the reservoir's last `record - 1` and spills one gas + // the child does not have, so the child runs out, and its write comes back. + let kept = run(counted_at, fits); + assert!(matches!(child_bound(&kept), Bound::OutOfGas), "{name}: {:?}", kept.result); + assert_eq!(kept.usage, body_only, "{name}: the child's write came back with it"); + assert_eq!(kept.gas.history, body, "{name}"); + assert_eq!(kept.gas.state, 0, "{name}"); + assert_eq!(kept.gas.reservoir_remaining, reservoir - body, "{name}"); + + // One gas more pays the spill: the write is kept, and the reservoir is spent to the last + // gas. + let paid = run(counted_at + 1, fits); + assert!(matches!(child_bound(&paid), Bound::Success), "{name}: {:?}", paid.result); + assert_eq!(paid.gas.reservoir_remaining, 0, "{name}: the reservoir spent to the last gas"); + assert_eq!(paid.gas.history, body + record, "{name}: the body and the record"); + assert_eq!(paid.gas.state, state, "{name}: the state the write added"); + assert_eq!( + paid.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + bytes, write_records: records }, + "{name}", + ); + } +} + +/* ---------- a body over the limit, at the smallest gas limit validation accepts ---------- */ + +/// A fresh account nobody has touched. +const FRESH: Address = address!("0000000000000000000000000000000000300005"); + +/// The account an EIP-7702 authorization of [`authorizing_call`] delegates. +const AUTHORITY: Address = address!("0000000000000000000000000000000000300006"); + +/// A type-4 call from `CALLER` to `A`, carrying one authorization of [`AUTHORITY`] to `B`. +fn authorizing_call(gas_limit: u64) -> mega_evm::MegaTransaction { + crate::common::authorizing_call(CALLER, A, U256::ZERO, gas_limit, B, &[(AUTHORITY, 0)]) +} + +/// Runs `tx` over [`funded`] under a transaction data-size limit of `limit`; `None` when +/// validation rejects it. +fn outcome_at(tx: mega_evm::MegaTransaction, limit: u64) -> Option { + MegaEvm::new( + context(funded()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), + ) + .execute_transaction(tx) + .ok() +} + +/// The smallest gas limit at which `accepted` holds, knowing it holds at `high` and at every +/// limit above the smallest. +fn smallest_gas_limit(high: u64, accepted: impl Fn(u64) -> bool) -> u64 { + assert!(accepted(high), "the high bound must be accepted"); + let (mut low, mut high) = (0_u64, high); + while low + 1 < high { + let middle = low + (high - low) / 2; + if accepted(middle) { + high = middle; + } else { + low = middle; + } + } + high +} + +/// A body over the limit is rejected whatever the gas limit, before its gas is looked at: at a +/// gas limit validation would otherwise accept, below it, and above it. A body at the limit leaves +/// validation where it is without one: the smallest gas limit it accepts is the same. +#[test] +fn test_a_body_over_the_limit_is_rejected_at_every_gas_limit() { + type Tx = fn(u64) -> mega_evm::MegaTransaction; + let cases: [(&str, Tx, u64); 3] = [ + ("a value transfer to a fresh account", |gas| call(CALLER, FRESH, U256::from(1), gas), 0), + ("a creation", |gas| create(CALLER, constructor_returning(1), gas), 12), + // The authorization's record counts beside its tuple. + ("an authorization", authorizing_call, mega_evm::AUTHORIZATION_SIZE + WRITE_RECORD_SIZE), + ]; + assert_eq!(constructor_returning(1).len(), 12); + for (name, tx, extra) in cases { + let at = mega_evm::TX_BODY_SIZE + extra; + let valid = smallest_gas_limit(GAS_LIMIT, |gas| outcome_at(tx(gas), u64::MAX).is_some()); + assert_eq!( + smallest_gas_limit(GAS_LIMIT, |gas| outcome_at(tx(gas), at).is_some()), + valid, + "{name}: a limit the transaction fits does not move validation" + ); + for gas in [0, valid - 1, valid, valid + 10_000] { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(at - 1); + let error = MegaEvm::new(context(funded()).with_tx_runtime_limits(limits)) + .execute_transaction(tx(gas)) + .expect_err("rejected"); + assert_body_refused(&format!("{name} at {gas}: {error:?}")); + } + } +} + +/* ---------- the 98% share, measured in slots ---------- */ + +/// Enough gas for a hundred fresh slots and a call or two around them. +const SLOTS_GAS_LIMIT: u64 = 100_000_000; + +/// Appends writes of the fresh slots `0..n`. +fn write_slots(mut builder: BytecodeBuilder, n: u64) -> BytecodeBuilder { + for slot in 0..n { + builder = builder.sstore(U256::from(slot), U256::from(slot + 1)); + } + builder +} + +/// Appends a valueless `CALL` to `target` with all the gas, dropping its success flag. +fn then_call(builder: BytecodeBuilder, target: Address) -> BytecodeBuilder { + builder + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(target) + .append(GAS) + .append(CALL) + .append(POP) +} + +/// A transaction limit that leaves the transaction's own frame room for `slots` fresh slots. +const fn room_for(slots: u64) -> u64 { + mega_evm::TX_BODY_SIZE + slots * WRITE_RECORD_SIZE +} + +/// Runs a call from `CALLER` to `A` over `db` under a transaction limit of `limit`. +fn run_slots(db: MemoryDatabase, limit: u64) -> MegaTransactionOutcome { + MegaEvm::new( + context(db) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)), + ) + .execute_transaction(call(CALLER, A, U256::ZERO, SLOTS_GAS_LIMIT)) + .unwrap() +} + +/// With room for 100 slots, a child may keep 98 and a grandchild 96; a parent that kept 20 leaves +/// its child 78. A frame that crosses its share reverts alone: the transaction succeeds with what +/// the other frames kept, and a sibling started after it gets its full share. +#[test] +fn test_a_child_gets_98_percent_of_what_its_parent_has_left_in_slots() { + assert_eq!(share(100 * WRITE_RECORD_SIZE), 98 * WRITE_RECORD_SIZE); + assert_eq!(share(98 * WRITE_RECORD_SIZE) / WRITE_RECORD_SIZE, 96); + assert_eq!(share(80 * WRITE_RECORD_SIZE) / WRITE_RECORD_SIZE, 78); + let stop = || BytecodeBuilder::default().stop().build(); + let slots = |n| write_slots(BytecodeBuilder::default(), n).stop().build(); + let calls = |target| then_call(BytecodeBuilder::default(), target).stop().build(); + let cases: [(&str, Bytes, Bytes, Bytes, u64); 8] = [ + ("a child that fills its share", calls(B), slots(98), stop(), 98), + ("a child one slot over its share", calls(B), slots(99), stop(), 0), + ( + "a child that fills what a parent of 20 slots left", + then_call(write_slots(BytecodeBuilder::default(), 20), B).stop().build(), + slots(78), + stop(), + 20 + 78, + ), + ( + "a child one slot over what a parent of 20 slots left", + then_call(write_slots(BytecodeBuilder::default(), 20), B).stop().build(), + slots(79), + stop(), + 20, + ), + ("a grandchild that fills its share", calls(B), calls(C), slots(96), 96), + ("a grandchild one slot over its share", calls(B), calls(C), slots(97), 0), + ( + "a sibling after a child that crossed its share", + then_call(then_call(BytecodeBuilder::default(), B), C).stop().build(), + slots(99), + slots(98), + 98, + ), + ( + "a parent that writes after its child crossed", + then_call(BytecodeBuilder::default(), B) + .sstore(U256::ZERO, U256::from(42)) + .stop() + .build(), + slots(99), + stop(), + 1, + ), + ]; + for (name, a, b, c, kept) in cases { + let db = funded().account_code(A, a).account_code(B, b).account_code(C, c); + let outcome = run_slots(db, room_for(100)); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); + assert_eq!(outcome.usage, LimitUsage { data_size: room_for(kept), write_records: kept }); + if name == "a parent that writes after its child crossed" { + let written = |address: Address| { + outcome.state.get(&address).is_some_and(|account| { + account.storage.get(&U256::ZERO).is_some_and(|slot| slot.is_changed()) + }) + }; + assert!(written(A), "the parent's write is kept"); + assert!(!written(B), "the child's writes went with its revert"); + } + } +} + +/// A body and the execution after it add up: a limit the body fits stops the transaction at the +/// write that crosses it, calldata or no calldata. +#[test] +fn test_the_body_and_the_execution_add_up_to_the_stop() { + for calldata in [0_u64, 200] { + let limit = mega_evm::TX_BODY_SIZE + calldata + WRITE_RECORD_SIZE; + let db = + funded().account_code(A, write_slots(BytecodeBuilder::default(), 3).stop().build()); + let outcome = run_at( + db, + call_with_data(CALLER, A, Bytes::from(vec![0xab; calldata as usize]), SLOTS_GAS_LIMIT), + limit, + ); + assert_stopped(&outcome, limit, limit + WRITE_RECORD_SIZE); + } +} + +/// A body over the limit is rejected before an interceptor could answer the transaction's own +/// call, whatever the frame's target. +#[test] +fn test_a_body_over_the_limit_is_rejected_before_an_interceptor() { + use alloy_sol_types::SolCall; + use mega_evm::system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS}; + let selector = IMegaLimitControl::remainingComputeGasCall::SELECTOR; + let body = mega_evm::TX_BODY_SIZE + selector.len() as u64; + let tx = + || call_with_data(CALLER, LIMIT_CONTROL_ADDRESS, Bytes::from(selector.to_vec()), GAS_LIMIT); + let answered = run_at(funded(), tx(), body); + assert!(answered.result.is_success(), "the interceptor answers: {:?}", answered.result); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body - 1); + let error = MegaEvm::new(context(funded()).with_tx_runtime_limits(limits)) + .execute_transaction(tx()) + .expect_err("rejected"); + assert_body_refused(&format!("{error:?}")); +} + +/* ---------- the nonce record a failed creation leaves its creator ---------- */ + +/// Logs `data_len` bytes, then attempts an empty creation — `CREATE2` when `create2` — and stops. +fn log_then_create(data_len: u64, create2: bool) -> Bytes { + let builder = BytecodeBuilder::default().push_number(data_len).push_number(0_u64).append(LOG0); + let builder = if create2 { + builder.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).append(CREATE2) + } else { + builder.append_many([PUSH0, PUSH0, PUSH0]).append(CREATE) + }; + builder.append(POP).append(STOP).build() +} + +/// Calls `target` with no value and returns whatever it returned or reverted with. +fn call_and_return_its_output(target: Address) -> Bytes { + then_call(BytecodeBuilder::default(), target) + .append(RETURNDATASIZE) + .append_many([PUSH0, PUSH0]) + .append(RETURNDATACOPY) + .append(RETURNDATASIZE) + .append(PUSH0) + .append(RETURN) + .build() +} + +/// A creation too big for its share still bumps its creator's nonce, and the creator's record of +/// that write outlives the creation: it lands on the creator's own lane. The creator is held to +/// its budget with it before it runs on. +/// +/// `A` calls `B` with 4,000 bytes left, so `B` may keep 3,920. `B` logs, then creates: the +/// creation's start records the created account and `B`'s nonce, 80 bytes against a share below +/// 80, so it is stopped with room to spare in the transaction. When the log left `B` 40 bytes, +/// `B` keeps the nonce record at exactly its budget and succeeds. When it left 39, the record puts +/// `B` one byte over: `B` reverts alone, its log and its nonce with it, and `A` resumes and +/// returns `B`'s revert. Either way the history the transaction pays is that of the bytes it +/// keeps. +#[test] +fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { + const A_BUDGET: u64 = 4_000; + let b_budget = share(A_BUDGET); + let limit = mega_evm::TX_BODY_SIZE + A_BUDGET; + let history_of = |usage: LimitUsage| mega_evm::history_gas(usage.data_size).unwrap(); + let run = |left: u64, create2: bool, inspect: bool| { + let logged = b_budget - left - 32; + let db = funded() + .account_code(A, call_and_return_its_output(B)) + .account_code(B, log_then_create(logged, create2)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + (outcome, evm.inspector().clone()) + }; + + for create2 in [false, true] { + for inspect in [false, true] { + let case = format!("create2 {create2}, inspect {inspect}"); + let (fits, probe) = run(WRITE_RECORD_SIZE, create2, inspect); + assert!(fits.result.is_success(), "{case}: {:?}", fits.result); + assert_eq!(fits.limit_exceeded, None, "{case}"); + assert_eq!( + fits.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + b_budget, write_records: 1 }, + "{case}: B keeps the nonce record at exactly its budget", + ); + assert_eq!(fits.gas.history, history_of(fits.usage), "{case}"); + assert_eq!(fits.result.logs().len(), 1, "{case}"); + assert_eq!(fits.state[&B].info.nonce, 1, "{case}"); + assert_eq!(fits.result.output().unwrap(), &Bytes::new(), "{case}: B stopped"); + if inspect { + assert_eq!(probe.creates.len(), 1, "{case}"); + assert_eq!(probe.creates[0].0, InstructionResult::Revert, "{case}"); + } + + let (over, _) = run(WRITE_RECORD_SIZE - 1, create2, inspect); + assert!(over.result.is_success(), "{case}: A resumes: {:?}", over.result); + assert_eq!(over.limit_exceeded, None, "{case}: a frame budget below is no stop"); + assert_eq!( + over.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "{case}: B's log and nonce record went with its revert", + ); + assert_eq!(over.gas.history, history_of(over.usage), "{case}: and their history"); + assert!(over.result.logs().is_empty(), "{case}"); + assert!(over.state.get(&B).is_none_or(|b| b.info.nonce == 0), "{case}"); + assert_eq!( + over.result.output().unwrap().as_ref(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: b_budget } + .abi_encode(), + "{case}: B reverted on its own budget", + ); + } + } +} diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs new file mode 100644 index 000000000..24c041faf --- /dev/null +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -0,0 +1,406 @@ +//! What the data-size limit counts: the bytes and write records each kind of transaction keeps. +//! +//! Every transaction keeps its body: the envelope, the five records of the writes its inclusion +//! makes, its calldata, its access list and its authorizations. What its execution keeps comes on +//! top: a 40-byte record per account or storage write, a log's 32 bytes plus 32 per topic plus its +//! data, the transfer log every value movement leaves — a log of three topics and one word, 160 +//! bytes — and the code a creation deploys. A frame that fails keeps nothing, except a creator's +//! nonce record once the nonce was bumped. + +use alloy_evm::Evm; +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, AUTHORIZATION_SIZE, LOG_BASE_SIZE, + LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CREATE, DELEGATECALL, GAS, INVALID, LOG0, LOG1, POP, PUSH0, SELFDESTRUCT, SLOAD, + SSTORE, STATICCALL, STOP, + }, + context::result::ExecutionResult, +}; + +use crate::common::{ + call, call_with_data, constructor_returning, context, create, execute, execute_under, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000400000"); +const CALLEE: Address = address!("0000000000000000000000000000000000400001"); +const LIBRARY: Address = address!("0000000000000000000000000000000000400002"); +const EXISTING: Address = address!("0000000000000000000000000000000000400003"); + +const GAS_LIMIT: u64 = 20_000_000; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) +} + +/// What a transaction keeps: its body with `extra` body bytes, `bytes` more from its execution, +/// and `records` write records among those. +const fn kept(extra: u64, bytes: u64, records: u64) -> LimitUsage { + LimitUsage { data_size: TX_BODY_SIZE + extra + bytes, write_records: records } +} + +/// `records` write records and nothing else. +const fn records(records: u64) -> LimitUsage { + kept(0, records * WRITE_RECORD_SIZE, records) +} + +/// `records` write records and the transfer logs of `moves` value movements. +const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { + kept(0, records * WRITE_RECORD_SIZE + moves * TRANSFER_LOG_SIZE, records) +} + +/// A contract that `CREATE`s `init` and stops. +fn factory(init: &Bytes) -> Bytes { + BytecodeBuilder::default() + .mstore(0, init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(POP) + .stop() + .build() +} + +/// A call from the running frame to `target` with `value` and all its gas, by `opcode`. +fn call_to(opcode: u8, target: Address, value: u8) -> BytecodeBuilder { + let builder = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let builder = if opcode == CALL { builder.push_number(value) } else { builder }; + builder.push_address(target).append(GAS).append(opcode).append(POP) +} + +/// `LOG0` of `len` zero bytes. +fn log0(builder: BytecodeBuilder, len: u64) -> BytecodeBuilder { + builder.push_number(len).push_number(0_u64).append(LOG0) +} + +/// A type-4 call from [`CALLER`] to [`CALLEE`] carrying `data`, an access list of one address +/// with one key, and an authorization that delegates the sender's own account to [`LIBRARY`]. +fn call_with_body(data: Bytes) -> MegaTransaction { + use revm::{ + context::{transaction::TransactionType, TxEnv}, + context_interface::{ + either::Either, + transaction::{ + AccessList, AccessListItem, Authorization, RecoveredAuthority, + RecoveredAuthorization, + }, + }, + }; + // The sender's nonce is bumped before its authorizations apply, so its own authorization + // names the nonce after the bump. + let authorization = Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: LIBRARY, nonce: 1 }, + RecoveredAuthority::Valid(CALLER), + )); + alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: alloy_primitives::TxKind::Call(CALLEE), + data, + gas_limit: GAS_LIMIT, + gas_priority_fee: Some(0), + access_list: AccessList(vec![AccessListItem { + address: CALLER, + storage_keys: vec![B256::ZERO], + }]), + authorization_list: vec![authorization], + ..Default::default() + })) +} + +/// Each kind of transaction keeps its body and exactly the bytes and records its execution +/// makes. +#[test] +fn test_what_each_transaction_keeps() { + let with_code = |code: Bytes| funded().account_code(CALLEE, code); + let init = constructor_returning(10); + let reverting_init = BytecodeBuilder::default().revert().build(); + let one_topic_and_ten_bytes = BytecodeBuilder::default() + .push_number(0_u64) + .push_number(10_u64) + .push_number(0_u64) + .append(LOG1) + .stop() + .build(); + let thirty_two_bytes_one_topic = BytecodeBuilder::default() + .mstore(0, [0x11_u8; 32]) + .push_number(0xabc_u64) + .push_number(32_u64) + .push_number(0_u64) + .append(LOG1) + .stop() + .build(); + let access_list = 20 + 32; + + let cases: Vec<(&str, MemoryDatabase, MegaTransaction, LimitUsage)> = vec![ + ( + "a call to an existing account without code", + funded().account_balance(CALLEE, U256::from(1)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "a call to an account that does not exist", + funded(), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "calldata, an access list and the sender's own authorization", + funded(), + call_with_body(Bytes::from_static(&[1, 2, 3, 4])), + kept(4 + access_list + AUTHORIZATION_SIZE, 0, 0), + ), + ( + "a value transfer to an existing account", + funded().account_balance(CALLEE, U256::from(100)), + call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), + records_and_moves(1, 1), + ), + ( + "a value transfer to an account that does not exist", + funded(), + call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), + records_and_moves(1, 1), + ), + ( + "a value transfer to the sender itself, which moves nothing", + funded(), + call(CALLER, CALLER, U256::from(1), GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "a creation deploying 10 bytes", + funded(), + create(CALLER, init.clone(), GAS_LIMIT), + kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 1), + ), + ( + "a creation endowing the account it creates", + funded(), + { + let mut tx = create(CALLER, Bytes::new(), GAS_LIMIT); + tx.0.base.value = U256::from(1); + tx + }, + records_and_moves(1, 1), + ), + ( + "a factory creating a contract of 10 bytes", + with_code(factory(&init)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 2 * WRITE_RECORD_SIZE + 10, 2), + ), + ( + "a storage write", + with_code(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build()), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + records(1), + ), + ( + "a storage read", + with_code(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build()), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "a log with one topic and 10 bytes of data", + with_code(one_topic_and_ten_bytes), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, LOG_BASE_SIZE + LOG_TOPIC_SIZE + 10, 0), + ), + ( + "an empty LOG0", + with_code(log0(BytecodeBuilder::default(), 0).stop().build()), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, LOG_BASE_SIZE, 0), + ), + ( + "a LOG1 of 32 bytes", + with_code(thirty_two_bytes_one_topic), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32, 0), + ), + ( + "two empty LOG0s", + with_code(log0(log0(BytecodeBuilder::default(), 0), 0).stop().build()), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 2 * LOG_BASE_SIZE, 0), + ), + ( + "a DELEGATECALL", + with_code(call_to(DELEGATECALL, LIBRARY, 0).stop().build()) + .account_code(LIBRARY, BytecodeBuilder::default().stop().build()), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "a value transfer the recipient passes on: its account is recorded once", + with_code(call_to(CALL, LIBRARY, 1).stop().build()), + call(CALLER, CALLEE, U256::from(100), GAS_LIMIT), + records_and_moves(2, 2), + ), + ( + "a child that writes a slot and halts", + with_code(call_to(CALL, LIBRARY, 0).stop().build()).account_code( + LIBRARY, + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, SLOAD, SSTORE, INVALID]) + .build(), + ), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ( + "a creation whose constructor reverts: the creator's bumped nonce stays", + with_code(factory(&reverting_init)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + records(1), + ), + ( + "a SELFDESTRUCT that moves value to an existing account", + with_code( + BytecodeBuilder::default().push_address(EXISTING).append(SELFDESTRUCT).build(), + ) + .account_balance(CALLEE, U256::from(1_000)) + .account_balance(EXISTING, U256::from(1)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + records_and_moves(1, 1), + ), + ( + "a SELFDESTRUCT that moves value to the sender: the body counts the sender", + with_code(BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build()) + .account_balance(CALLEE, U256::from(1_000)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + records_and_moves(0, 1), + ), + ( + "a SELFDESTRUCT to itself, which moves nothing", + with_code(BytecodeBuilder::default().push_address(CALLEE).append(SELFDESTRUCT).build()) + .account_balance(CALLEE, U256::from(1_000)), + call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), + kept(0, 0, 0), + ), + ]; + + for (name, db, tx, expected) in cases { + let outcome = execute(db, tx); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{name}"); + } +} + +/// A child that writes a slot, writes it back and reverts runs under a caller that already wrote +/// one. The child's write and its write-back both go with its revert, so neither reaches the +/// caller: the caller keeps its own write and that write's record, no more and no less. +#[test] +fn test_a_reverted_childs_write_and_write_back_leave_its_callers_write() { + const CALLER_SLOT: U256 = U256::from_limbs([5, 0, 0, 0]); + let parent = BytecodeBuilder::default() + .sstore(CALLER_SLOT, U256::from(1)) + .append_many(call_to(CALL, LIBRARY, 0).build_vec()) + .stop() + .build(); + let child = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .sstore(U256::ZERO, U256::ZERO) + .revert() + .build(); + let db = funded().account_code(CALLEE, parent).account_code(LIBRARY, child); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage, records(1)); + assert_eq!( + outcome.state[&CALLEE].storage.get(&CALLER_SLOT).map(|slot| slot.present_value), + Some(U256::from(1)), + "the caller's write survives the child's revert", + ); + assert!( + outcome.state.get(&LIBRARY).is_none_or(|library| { + library.storage.get(&U256::ZERO).is_none_or(|slot| !slot.is_changed()) + }), + "the child's write went with its revert", + ); +} + +/// The sender's own authorization in [`call_with_body`] applies: its bytes are the body's, and +/// the account it writes is the sender's, which the body already records. +#[test] +fn test_the_senders_own_authorization_applies_and_records_nothing() { + let outcome = execute(funded(), call_with_body(Bytes::new())); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let code = outcome.state[&CALLER].info.code.clone().expect("the sender is delegated"); + assert_eq!(code.eip7702_address(), Some(LIBRARY)); + assert_eq!(outcome.usage, kept(20 + 32 + AUTHORIZATION_SIZE, 0, 0)); +} + +/// A `SELFDESTRUCT` in a static frame halts before it moves anything, so the frame keeps what a +/// frame that stops keeps: nothing. +#[test] +fn test_a_selfdestruct_in_a_static_frame_keeps_nothing() { + let run = |child: Bytes| { + let db = funded() + .account_code(CALLEE, call_to(STATICCALL, LIBRARY, 0).stop().build()) + .account_code(LIBRARY, child) + .account_balance(LIBRARY, U256::from(1_000)); + execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + }; + let selfdestruct = + run(BytecodeBuilder::default().push_address(EXISTING).append(SELFDESTRUCT).build()); + let stop = run(BytecodeBuilder::default().stop().build()); + assert!(selfdestruct.result.is_success() && stop.result.is_success()); + assert_eq!(selfdestruct.usage, stop.usage); + assert_eq!(selfdestruct.usage, kept(0, 0, 0)); + assert!(selfdestruct.state.get(&EXISTING).is_none_or(|a| a.info.balance.is_zero())); +} + +/// A transaction whose own frame reverts keeps its body: the body is the transaction's, not the +/// frame's. +#[test] +fn test_a_top_level_revert_keeps_the_body() { + let db = funded().account_code(CALLEE, BytecodeBuilder::default().revert().build()); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + assert!(matches!(outcome.result, ExecutionResult::Revert { .. }), "{:?}", outcome.result); + assert_eq!(outcome.usage, kept(0, 0, 0)); + assert_eq!(outcome.limit_exceeded, None); +} + +/// A transaction limit equal to what the transaction keeps does not stop it, however much of it +/// is calldata. +#[test] +fn test_a_limit_equal_to_what_is_kept_does_not_stop() { + let db = || funded().account_code(CALLEE, BytecodeBuilder::default().stop().build()); + for calldata in [0_usize, 500] { + let limit = TX_BODY_SIZE + calldata as u64; + let outcome = execute_under( + db(), + call_with_data(CALLER, CALLEE, Bytes::from(vec![0xab; calldata]), GAS_LIMIT), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert!(outcome.result.is_success(), "{calldata} bytes: {:?}", outcome.result); + assert_eq!(outcome.usage.data_size, limit); + assert_eq!(outcome.limit_exceeded, None); + } +} + +/// Every transaction counts from zero: what one EVM ran before does not add to the next. +/// +/// The EVM does not commit what it runs, so the same transaction runs twice on the same state. +#[test] +fn test_each_transaction_counts_from_zero() { + let db = funded().account_code( + CALLEE, + BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), + ); + let mut evm = MegaEvm::new(context(db)); + for run in 0..2 { + let result = evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(evm.ctx().additional_limit().usage(), records(1), "run {run}"); + } +} diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs new file mode 100644 index 000000000..3f05874bc --- /dev/null +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -0,0 +1,623 @@ +//! Deployed code is charged in the spec's order — the regular per-byte cost (zero), the hash at 6 +//! gas per word, the state gas at the cost per state byte, the history at the cost per history +//! byte — and held to the limits only once every part of its deposit is charged. +//! +//! A creation that cannot pay one of the four runs out of gas there, alone, and the chain keeps +//! none of its code [S5.14]. Which charge it runs out on follows from where the gas comes from. +//! Above the execution cap the reservoir pays the code's state gas and history, so the only +//! regular charge at the deposit is the hash. Below it there is no reservoir, and the state gas +//! and then the history are paid out of regular gas after the hash [S5.13]. The regular deposit +//! cost is zero under EIP-8037, so it binds only on a configuration without it: the neutral one +//! of Osaka, where no state gas is charged and the data-size limit is the one that holds the +//! code. +//! +//! Every gas figure here is built by hand from the spec and the schedule, never read off a run +//! of the engine. The creation's regular budget is set exactly: `A` calls the creator `B` with an +//! explicit gas, `B` spends a known amount before its `CREATE`, and the EIP-150 split forwards all +//! but a 64th of what `B` holds, which [`holding_for`] inverts. Each case is one gas short of a +//! charge, or exactly enough, and reads every ledger against its derivation. The data-size limit +//! holds the deposit after the last of those charges and before `return_create` commits it: with +//! exactly enough gas a limit the deposit crosses stops the creation, and one gas short the +//! creation runs out of gas under the limit exactly as without it. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{neutral_cfg, neutralize_evm, note_price_guard, BytecodeBuilder, MemoryDatabase}, + EthSpecId, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, + MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, MLOAD, POP, PUSH0, RETURN, STOP}, + context_interface::cfg::GasId, + inspector::NoOpInspector, + interpreter::{ + interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, + InterpreterResult, + }, + Database, Inspector, +}; + +use crate::{ + common::{call, context, history, history_rounds, runs_at_measurement_prices, state_is_free}, + salt::entry, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000a00000"); +/// Calls `B` with a chosen gas and stops. +const A: Address = address!("0000000000000000000000000000000000a00001"); +/// Creates the code with all but a 64th of what it has, and stops. +const B: Address = address!("0000000000000000000000000000000000a00002"); + +/// The words of zeros the creation deploys, and their bytes. +const DEPLOYED_WORDS: u64 = 100; +const CODE_LEN: u64 = DEPLOYED_WORDS * 32; + +/// The words of memory the init code touches before it returns, so that the creation is forwarded +/// millions of gas at any byte price: below the execution cap `B` pays the history of the +/// creation's two write records out of the 64th it keeps, which must cover them whatever a +/// history byte costs — at the dearest price the grid runs, 1,000 a byte, the two records are +/// 80,000 gas, and a 64th of the memory's cost alone is 82,400. [`call_gas`] asserts it. +const BURNT_WORDS: u64 = 51_200; + +/// The reservoir the runs above the execution cap carry: ample for every charge here. +const RESERVOIR: u64 = 100_000_000; + +/// A frame cap below what the creation keeps with its code, and above what any other frame keeps. +const FRAME_CAP: u64 = 1_000; + +/// Where the transaction runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Pool { + /// Satin above the execution cap: the reservoir pays every state and history charge, and the + /// hash is the only regular charge of the deposit. + AboveCap, + /// Satin below the execution cap: there is no reservoir, and every charge is regular gas. + BelowCap, + /// The neutral configuration of Osaka, which has no EIP-8037 and charges the regular deposit + /// cost. + NeutralOsaka, +} + +impl Pool { + /// The transaction's gas limit: above the cap by [`RESERVOIR`]; below it, room for `A` to + /// forward the largest gas any case calls `B` with — a 64th more than the forward, and a + /// million of slack — which stays below the cap at any byte price the grid runs; or Osaka's + /// own ceiling (EIP-7825 holds a transaction to 2^24 gas). + fn gas_limit(self) -> u64 { + match self { + Self::AboveCap => TX_GAS_LIMIT_CAP + RESERVOIR, + Self::BelowCap => { + let largest = call_gas(Self::BelowCap, deposits_at(Self::BelowCap)); + let limit = (largest * 64).div_ceil(63) + 1_000_000; + assert!(limit <= TX_GAS_LIMIT_CAP, "below the cap at these prices: {limit}"); + limit + } + Self::NeutralOsaka => 10_000_000, + } + } + + /// The intrinsic regular gas of the call to `A`: `TX_BASE_COST` 12,000 and 3,000 for the + /// recipient's access under EIP-2780; 21,000 before it. + const fn intrinsic(self) -> u64 { + match self { + Self::AboveCap | Self::BelowCap => 12_000 + 3_000, + Self::NeutralOsaka => 21_000, + } + } + + /// What `A` spends on its own: five `PUSH0`, a `PUSH20`, a `PUSH4`, a `CALL` to a cold + /// account carrying no value (100 warm plus the cold surcharge, Amsterdam's 2,900 under Satin + /// and 2,500 under Osaka), and a `POP`. + const fn a_regular(self) -> u64 { + let cold = match self { + Self::AboveCap | Self::BelowCap => 2_900, + Self::NeutralOsaka => 2_500, + }; + 5 * 2 + 3 + 3 + (100 + cold) + 2 + } + + /// What `B` spends before its `CREATE` splits the gas: a `PUSH32` and a `PUSH8` and the + /// `MSTORE` that puts the init code in memory, with the first word of memory; three `PUSH8`; + /// EIP-3860's 2 gas for the one word of init code; and `CREATE`'s own charge, Amsterdam's + /// 12,000 under Satin and 32,000 under Osaka. + const fn b_before_the_split(self) -> u64 { + let create = match self { + Self::AboveCap | Self::BelowCap => 12_000, + Self::NeutralOsaka => 32_000, + }; + 3 + 3 + (3 + 3) + 3 * 3 + 2 + create + } +} + +/* ---------- the figures by hand ---------- */ + +/// What `B` spends after the creation returns: the `POP` of its answer. +const B_AFTER: u64 = 2; + +/// What the init code spends: a `PUSH4`, the `MLOAD` that expands memory to [`BURNT_WORDS`] +/// words at `3 w + w² / 512`, a `POP`, a `PUSH2`, a `PUSH0`, and a `RETURN` of the first +/// [`CODE_LEN`] bytes, which expands nothing further. +const INIT_EXECUTION: u64 = 3 + (3 + 3 * BURNT_WORDS + BURNT_WORDS * BURNT_WORDS / 512) + 2 + 3 + 2; +const _: () = assert!(INIT_EXECUTION == 5_273_613, "the init code's cost, written out"); + +/// The hashing cost of the deposit: 6 gas per 32-byte word [S5.13]. +const HASH: u64 = 6 * DEPLOYED_WORDS; + +/// Osaka's regular deposit cost: 200 gas per byte. +const OSAKA_DEPOSIT: u64 = 200 * CODE_LEN; + +/// The state gas of the deposited code at the cost per state byte in effect: 1,530 per byte at +/// the spec's price. +fn code_state_gas() -> u64 { + entry(GasId::code_deposit_state_gas()) * CODE_LEN +} + +/// The history of the deposited code at the cost per history byte in effect: 88 per byte at the +/// spec's price. +fn code_history_gas() -> u64 { + entry(GasId::code_deposit_history_gas()) * CODE_LEN +} + +/// Whether the deposit charges its code no history at the prices in effect: a history byte +/// priced at nothing, or at less than half a gas, which the schedule's per-byte entry rounds to +/// nothing. +/// +/// Only a measurement build arranges that. The deposit's state gas is then its last charge, so a +/// case built on a history charge after it has nothing to run, and notes so. +fn code_history_is_free() -> bool { + if code_history_gas() > 0 { + return false; + } + note_price_guard("the deposit's history per byte rounds to nothing at these prices"); + true +} + +/// The state gas of the account the creation adds, charged to `B` by its `CREATE`: 183,600 at +/// the spec's price. +fn created_account_state_gas() -> u64 { + entry(GasId::create_state_gas()) +} + +/// The regular gas the creation needs to deposit its code with nothing left: its init code, then +/// the charges of the deposit that regular gas pays in `pool`. +fn deposits_at(pool: Pool) -> u64 { + match pool { + Pool::AboveCap => INIT_EXECUTION + HASH, + Pool::BelowCap => INIT_EXECUTION + HASH + code_state_gas() + code_history_gas(), + Pool::NeutralOsaka => INIT_EXECUTION + OSAKA_DEPOSIT, + } +} + +/// The least gas `B` can hold at its `CREATE`'s split for the creation to be forwarded exactly +/// `forward`: EIP-150 forwards all but a 64th, `r - r / 64`, which `64 (f / 63) + f mod 63` +/// inverts. +fn holding_for(forward: u64) -> u64 { + let holding = 64 * (forward / 63) + forward % 63; + assert_eq!(holding - holding / 64, forward, "the split inverted"); + holding +} + +/// The gas `A` calls `B` with for the creation to be forwarded exactly `forward` in `pool`: what +/// `B` must hold at the split, plus what it spends before it. Below the cap the created account's +/// state gas spills onto `B`'s regular gas before the split too; above it the reservoir pays it, +/// and Osaka charges none. +fn call_gas(pool: Pool, forward: u64) -> u64 { + let spilled = match pool { + Pool::BelowCap => created_account_state_gas(), + Pool::AboveCap | Pool::NeutralOsaka => 0, + }; + let holding = holding_for(forward); + if pool == Pool::BelowCap { + assert!( + holding / 64 >= history(2 * WRITE_RECORD_SIZE) + B_AFTER, + "B's 64th pays the creation's two records and B's POP at these prices", + ); + } + holding + pool.b_before_the_split() + spilled +} + +/// The regular gas a deposited creation spent as regular gas: its init code and the deposit's +/// regular charges. The state gas and history that spilled onto its regular budget below the cap +/// stay on their own ledgers. +fn regular_deposit(pool: Pool) -> u64 { + match pool { + Pool::AboveCap | Pool::BelowCap => INIT_EXECUTION + HASH, + Pool::NeutralOsaka => INIT_EXECUTION + OSAKA_DEPOSIT, + } +} + +/// The regular ledger of a run whose creation spent `spent` of its forward as regular gas: the +/// whole forward when it halted (what was charged and given back comes back as regular gas, and +/// the halt consumes it), or [`regular_deposit`] when it deposited with nothing left. +fn regular(pool: Pool, spent: u64) -> u64 { + pool.intrinsic() + pool.a_regular() + pool.b_before_the_split() + B_AFTER + spent +} + +/* ---------- the world ---------- */ + +/// The creation's init code: `PUSH4 offset; MLOAD; POP; PUSH2 CODE_LEN; PUSH0; RETURN`, twelve +/// bytes: it touches the last of [`BURNT_WORDS`] words of memory, then deploys [`CODE_LEN`] zero +/// bytes. +fn init_code() -> Bytes { + let last_word = u32::try_from((BURNT_WORDS - 1) * 32).expect("the offset fits a PUSH4"); + BytecodeBuilder::default() + .push_number(last_word) + .append_many([MLOAD, POP]) + .push_number(CODE_LEN as u16) + .append_many([PUSH0, RETURN]) + .build() +} + +/// `A` calling `B` with `gas`, and `B` creating [`init_code`]. +fn world(gas: u64) -> MemoryDatabase { + let init = init_code(); + let creator = BytecodeBuilder::default() + .mstore(0, &init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(POP) + .append(STOP) + .build(); + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(u32::try_from(gas).expect("the forward fits a PUSH4")) + .append(CALL) + .append(POP) + .append(STOP) + .build(); + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, caller) + .account_code(B, creator) +} + +fn evm( + pool: Pool, + forward: u64, + limits: EvmTxRuntimeLimits, +) -> MegaEvm { + let ctx = context(world(call_gas(pool, forward))); + match pool { + Pool::AboveCap | Pool::BelowCap => MegaEvm::new(ctx.with_tx_runtime_limits(limits)), + Pool::NeutralOsaka => { + let cfg = neutral_cfg(EthSpecId::OSAKA).expect("a neutral fork"); + let mut evm = MegaEvm::new(ctx.with_neutral_cfg(cfg).with_tx_runtime_limits(limits)); + neutralize_evm(&mut evm, EthSpecId::OSAKA).expect("a neutral fork"); + evm + } + } +} + +/// Runs the transaction with the creation forwarded `forward`, under `limits`. +fn run(pool: Pool, forward: u64, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + evm(pool, forward, limits) + .execute_transaction(call(CALLER, A, U256::ZERO, pool.gas_limit())) + .expect("the transaction is valid") +} + +/// The code at the creation's address, if any. +fn deployed_code(outcome: &MegaTransactionOutcome) -> Option { + outcome.state.get(&B.create(0)).filter(|account| !account.info.is_empty_code_hash()).map( + |account| account.info.code.clone().expect("the account's code is loaded").original_bytes(), + ) +} + +/// Whether the creation's code is at its address. +fn deployed(outcome: &MegaTransactionOutcome) -> bool { + deployed_code(outcome).is_some() +} + +/// The creation's frame once `return_create` is done with it. +#[derive(Clone, Debug, Default)] +struct CreationEnd { + /// How the creation ended, as its caller sees it. + result: Option, + /// Whether the creation deposited its code. + deposited: bool, + /// Whether `return_create` charged the code's state gas: the only state charge made on the + /// creation's own frame. A charge made and then undone by a later out-of-gas still shows. + charged_state_gas: bool, + /// The regular gas the creation had left. + remaining: u64, + /// What the creation reverted with, if it reverted. + reverted_with: Option, +} + +impl CreationEnd { + fn of(result: &InterpreterResult) -> Self { + Self { + result: Some(result.result), + deposited: result.is_ok(), + charged_state_gas: result.gas.state_gas_spent() > 0, + remaining: result.gas.remaining(), + reverted_with: result.is_revert().then(|| result.output.clone()), + } + } +} + +impl Inspector, EthInterpreter> for CreationEnd { + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + *self = Self::of(&outcome.result); + } +} + +/// How the creation ends when forwarded `forward` and no limit is set. +fn creation_end(pool: Pool, forward: u64) -> CreationEnd { + creation_end_under(pool, forward, EvmTxRuntimeLimits::no_limits()) +} + +/// How the creation ends when forwarded `forward`, under `limits`. +fn creation_end_under(pool: Pool, forward: u64, limits: EvmTxRuntimeLimits) -> CreationEnd { + let mut evm = evm(pool, forward, limits).with_inspector(CreationEnd::default()); + evm.execute_transaction(call(CALLER, A, U256::ZERO, pool.gas_limit())).unwrap(); + evm.inspector().clone() +} + +/* ---------- what each outcome looks like, by hand ---------- */ + +/// The history a transaction pays in `pool` for `bytes`: the cost per history byte in effect, or +/// nothing on the neutral configuration, which prices no history. +fn history_in(pool: Pool, bytes: u64) -> u64 { + match pool { + Pool::AboveCap | Pool::BelowCap => history(bytes), + Pool::NeutralOsaka => 0, + } +} + +/// Holds a run to the ledgers of a creation that spent `spent` of its forward as regular gas, and +/// to the receipt and the reservoir those ledgers imply. +/// +/// The history ledger is the body's, the records' and the code's charges, each priced on its own. +/// Where a history byte costs a fraction of a gas each charge rounds on its own, so the history of +/// their bytes together is not the ledger, and the figures that read it — the history ledger, the +/// receipt and the reservoir above the cap — are left out, with a note; the regular and state +/// ledgers are held all the same. +#[track_caller] +fn assert_ledgers( + name: &str, + pool: Pool, + spent: u64, + outcome: &MegaTransactionOutcome, + state: u64, + history_bytes: u64, +) { + let history = history_in(pool, history_bytes); + assert_eq!(outcome.gas.regular, regular(pool, spent), "{name}: the regular ledger"); + assert_eq!(outcome.gas.state, state, "{name}: the state ledger"); + if history_rounds() { + return; + } + assert_eq!(outcome.gas.history, history, "{name}: the history ledger"); + assert_eq!( + outcome.gas.gas_used, + regular(pool, spent) + state + history, + "{name}: the receipt is the three ledgers, with nothing refunded and no floor binding", + ); + let reservoir = match pool { + Pool::AboveCap => RESERVOIR - state - history, + Pool::BelowCap | Pool::NeutralOsaka => 0, + }; + assert_eq!(outcome.gas.reservoir_remaining, reservoir, "{name}: the reservoir"); +} + +/// A creation forwarded `forward` in `pool` runs out of gas at its deposit and leaves no code: +/// its caller goes on, the creator's nonce record is all the transaction keeps beyond its body, +/// and every ledger is what the halt leaves — the forward consumed, no state gas, the body and +/// one record of history [S5.14]. +/// +/// `left` is what the creation held when the charge it cannot pay was attempted — one gas less +/// than that charge, or nothing — which the creation's frame still shows at its end, and which +/// prices the charge; `state_charged` says whether the deposit's state gas was charged before +/// the halt, which tells a creation short of its history from one short of its state gas +/// [S5.13]. +#[track_caller] +fn assert_runs_out(name: &str, pool: Pool, forward: u64, left: u64, state_charged: bool) { + let end = creation_end(pool, forward); + assert_eq!( + end.result, + Some(InstructionResult::OutOfGas), + "{name}: the creation halts: {end:?}" + ); + assert!(!end.deposited, "{name}: {end:?}"); + assert_eq!(end.remaining, left, "{name}: what it held at the charge it cannot pay: {end:?}"); + assert_eq!(end.charged_state_gas, state_charged, "{name}: {end:?}"); + + let outcome = run(pool, forward, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "{name}: the caller survives: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}"); + assert!(!deployed(&outcome), "{name}: no code is left"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + "{name}: the creator's nonce record outlives the creation, nothing else does", + ); + assert_ledgers(name, pool, forward, &outcome, 0, TX_BODY_SIZE + WRITE_RECORD_SIZE); +} + +/// A creation forwarded `forward` in `pool` deposits its code with nothing left: the transaction +/// keeps the creation's two records and the code, the state ledger holds the created account and +/// the code, and the history ledger the body, the two records and the code. +#[track_caller] +fn assert_deposits(name: &str, pool: Pool, forward: u64) { + let end = creation_end(pool, forward); + assert_eq!(end.result, Some(InstructionResult::Return), "{name}: {end:?}"); + assert!(end.deposited, "{name}: {end:?}"); + assert_eq!(end.remaining, 0, "{name}: exactly enough: {end:?}"); + let state = match pool { + Pool::AboveCap | Pool::BelowCap => created_account_state_gas() + code_state_gas(), + Pool::NeutralOsaka => 0, + }; + assert_eq!(end.charged_state_gas, state > 0, "{name}: {end:?}"); + + let outcome = run(pool, forward, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}"); + assert_eq!( + deployed_code(&outcome).map(|code| code.len() as u64), + Some(CODE_LEN), + "{name}: the code is at its address", + ); + let bytes = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + CODE_LEN; + assert_eq!( + outcome.usage, + LimitUsage { data_size: bytes, write_records: 2 }, + "{name}: the creator's nonce, the created account, and the code", + ); + assert_ledgers(name, pool, regular_deposit(pool), &outcome, state, bytes); +} + +/* ---------- the four charges, one gas short of each ---------- */ + +/// Above the execution cap the reservoir pays the code's state gas and history, so the hash is +/// the only regular charge of the deposit: one gas short of it the creation runs out of gas with +/// no state gas charged, and one gas more deposits the code with nothing left. The boundary is +/// the init code's cost plus 6 gas per word of code, by hand (`independent`) [S5.13] [S5.14]. +#[test] +fn test_a_creation_one_gas_short_of_the_hash_runs_out_of_gas_above_the_cap() { + let enough = deposits_at(Pool::AboveCap); + assert_runs_out("one gas short of the hash", Pool::AboveCap, enough - 1, HASH - 1, false); + assert_deposits("the hash paid exactly", Pool::AboveCap, enough); + if runs_at_measurement_prices() { + return; + } + assert_eq!(enough, INIT_EXECUTION + 600, "the init code and the hash of 100 words"); +} + +/// Below the execution cap the code's state gas is paid out of regular gas right after the hash: +/// one gas short of it the creation runs out of gas with the hash paid and no state gas charged, +/// and one gas more charges the state gas and runs out on the history instead — or, where the +/// deposit's history per byte is nothing and no history charge follows, deposits the code with +/// nothing left. The boundary is the init code, the hash and 1,530 per byte of code, by hand +/// (`constants`: the cost per state byte in effect) [S5.13] [S5.14]. +#[test] +fn test_a_creation_one_gas_short_of_its_state_gas_runs_out_of_gas_with_the_hash_paid() { + // A deposit that adds no state gas has no state gas to be short of. + if state_is_free() { + return; + } + let state_paid = INIT_EXECUTION + HASH + code_state_gas(); + assert_runs_out( + "one gas short of the state gas", + Pool::BelowCap, + state_paid - 1, + code_state_gas() - 1, + false, + ); + if code_history_is_free() { + // The state gas is the deposit's last charge: paying it exactly is the whole deposit. + assert_eq!(state_paid, deposits_at(Pool::BelowCap), "no history follows the state gas"); + assert_deposits("the state gas paid exactly", Pool::BelowCap, state_paid); + } else { + assert_runs_out("the state gas paid exactly", Pool::BelowCap, state_paid, 0, true); + } + if runs_at_measurement_prices() { + return; + } + assert_eq!(code_state_gas(), 3_200 * 1_530, "the state gas of 3,200 bytes"); +} + +/// Below the execution cap the history is the last charge of the deposit: one gas short of it +/// the creation runs out of gas with its state gas charged, and one gas more deposits the code +/// with nothing left. The boundary is the init code, the hash, the state gas and 88 per byte of +/// code, by hand (`constants`: the two byte prices in effect) [S5.13] [S5.14]. +#[test] +fn test_a_creation_one_gas_short_of_its_history_runs_out_of_gas_with_the_state_gas_paid() { + // A deposit that pays no history has no history to be short of, and one that adds no state + // gas has no state charge to show. + if code_history_is_free() || state_is_free() { + return; + } + let enough = deposits_at(Pool::BelowCap); + assert_runs_out( + "one gas short of the history", + Pool::BelowCap, + enough - 1, + code_history_gas() - 1, + true, + ); + assert_deposits("the history paid exactly", Pool::BelowCap, enough); + if runs_at_measurement_prices() { + return; + } + assert_eq!(code_history_gas(), 3_200 * 88, "the history of 3,200 bytes"); + assert_eq!(enough, INIT_EXECUTION + 600 + 4_896_000 + 281_600); +} + +/* ---------- the limit stands aside ---------- */ + +/// Under a frame cap the creation's code crosses, the creation forwarded exactly enough is +/// stopped alone — it reverts with the stop's revert data, and its caller goes on — and the one +/// forwarded one gas less runs out of gas as it does without the cap. +fn assert_data_size_limit_stands_aside(pool: Pool) { + let enough = deposits_at(pool); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(FRAME_CAP); + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 0, + used: 0, + frame_local: true, + }; + + let stopped = run(pool, enough, limits); + assert!(stopped.result.is_success(), "{pool:?}: {:?}", stopped.result); + assert_eq!(stopped.limit_exceeded, None, "{pool:?}: a frame budget below is no stop"); + assert!(!deployed(&stopped), "{pool:?}"); + let end = creation_end_under(pool, enough, limits); + assert!(!end.deposited, "{pool:?}: {end:?}"); + assert_eq!( + end.reverted_with.as_ref().map(|data| data.len()), + Some(stop.revert_data().len()), + "{pool:?}: exactly enough, the check fires and the creation reverts with the stop: {end:?}", + ); + + let short = run(pool, enough - 1, EvmTxRuntimeLimits::no_limits()); + let ran_out = run(pool, enough - 1, limits); + assert!(ran_out.result.is_success(), "{pool:?}: {:?}", ran_out.result); + assert_eq!( + creation_end_under(pool, enough - 1, limits).result, + Some(InstructionResult::OutOfGas), + "{pool:?}: one gas short, it stands aside", + ); + assert!(!deployed(&ran_out), "{pool:?}"); + assert_eq!(ran_out.gas, short.gas, "{pool:?}: as without the limit"); + assert_eq!(ran_out.usage, short.usage, "{pool:?}: and it keeps what it keeps without it"); +} + +/// The data-size limit counts deployed code behind the same check: a creation that cannot pay the +/// hash of its code, or its history, runs out of gas whatever the limit. +/// +/// Rules: [S5.14], [S7.25], [S10.12], [S10.33]. +#[test] +fn test_a_creation_that_cannot_pay_for_its_code_runs_out_of_gas_under_the_data_size_limit() { + assert_data_size_limit_stands_aside(Pool::AboveCap); + assert_data_size_limit_stands_aside(Pool::BelowCap); +} + +/// Without EIP-8037 the deposit's only charge is the regular deposit cost, 200 gas per byte: a +/// creation one gas short of it runs out of gas, one gas more deposits the code with nothing +/// left, and a creation that cannot pay it runs out of gas whatever the data-size limit. +/// +/// Rules: [S5.13], [S5.14], [S10.12]. +#[test] +fn test_a_creation_that_cannot_pay_the_deposit_cost_runs_out_of_gas_under_the_data_size_limit() { + let pool = Pool::NeutralOsaka; + let enough = deposits_at(pool); + assert_runs_out( + "one gas short of the deposit cost", + pool, + enough - 1, + OSAKA_DEPOSIT - 1, + false, + ); + assert_deposits("the deposit cost paid exactly", pool, enough); + assert_data_size_limit_stands_aside(pool); +} diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs new file mode 100644 index 000000000..4b0a209e6 --- /dev/null +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -0,0 +1,580 @@ +//! Gas detention against EIP-7708 transfer logs: value that moves after a read of volatile data. +//! +//! The two meet where a frame starts and at `SELFDESTRUCT`. A frame start counts its transfer log +//! with its records before revm decides the frame — revm then moves the value, answers the frame +//! or refuses it on the caller's account — and a precompile started after a read runs on what the +//! compute limit leaves its frame. A `SELFDESTRUCT` counts its log with its beneficiary's record +//! once the opcode completed, and revm journals the move before the opcode's last charge, which +//! the cap can fail. +//! +//! Whatever detention does to the movement, the transfer logs a receipt carries are the ones the +//! data size kept: a transaction keeps its body, forty bytes a write record and 160 a transfer +//! log, and a frame the cap stops keeps nothing, its movement and its log included. A debug build +//! also asserts at every frame start that revm refused exactly the start predicted and journaled +//! exactly the log counted, so every case below runs that check too. +//! +//! Each case runs with a read of the block's timestamp first, and with `PUSH0`, which costs the +//! same two gas and reads nothing, in its place. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{is_transfer_log, op_transaction, transfer_log, BytecodeBuilder, MemoryDatabase}, + transaction_body_bytes, EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, + TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::*, context::TxEnv, context_interface::cfg::GasId, + interpreter::InstructionResult, +}; + +use crate::{ + detention::{ + assert_caught, assert_stopped, cold_access, context, failed_status_store, intrinsic, + memory_cost, op, run_on, spin, value_transfer, Calls, Charges, Run, BENEFICIARY, CALLER, + CAP, CHILD, CONTRACT, TIERS, + }, + withheld_gas::{costly_modexp_input, intrinsic_with}, +}; + +/// A contract whose code stops. +const RECEIVER: Address = address!("0000000000000000000000000000000000d00020"); +/// An account with no code. +const PAYEE: Address = address!("0000000000000000000000000000000000d00021"); +/// A contract that destructs to [`RECEIVER`], holding [`VALUE`]. +const DESTRUCTOR: Address = address!("0000000000000000000000000000000000d00022"); + +/// The identity precompile. +const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); +/// The modexp precompile. +const MODEXP: Address = address!("0000000000000000000000000000000000000005"); +/// The BN254 pairing precompile. +const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + +/// What every movement moves. +const VALUE: u64 = 1_000; + +/// A contract that copies its calldata into memory, then, after `first`, calls `to` with it, +/// [`VALUE`] and `gas` (all of it when `None`), and stores the call's status in slot 0. +fn calls_with_value(first: u8, to: Address, gas: Option) -> Bytes { + let code = op(BytecodeBuilder::default(), first) + .append_many([CALLDATASIZE, PUSH0, PUSH0, CALLDATACOPY]) + .append_many([PUSH0, PUSH0, CALLDATASIZE, PUSH0]) + .push_number(VALUE) + .push_address(to); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code.append(CALL).push_number(0_u8).append(SSTORE).stop().build() +} + +/// The regular charges [`calls_with_value`] makes after its first instruction reads, with calldata +/// of `len` bytes, up to the call: the read's `POP`; `CALLDATASIZE`, two `PUSH0` and +/// `CALLDATACOPY` — its static gas, the copy and the memory it expands — the call's four pushes, +/// the value's and the address's, and `GAS`; and the call's own charges, `call`, less the stipend +/// the callee is given, which nobody paid and is not compute. +fn charges_to_the_call(len: u64, call: u64) -> Charges { + let words = len.div_ceil(32); + Charges::default().then(&[ + 2, + 2, + 2, + 2, + 3, + 3 * words, + memory_cost(words), + 2, + 2, + 2, + 2, + 3, + 3, + 2, + call - 2_300, + ]) +} + +/// A value call's own charges to a cold contract: the cold access and the transfer. +fn call_to_a_contract() -> u64 { + cold_access() + value_transfer() +} + +/// A value call's own charges to a precompile whose account is empty: the warm access, the +/// transfer, and the regular price of the account the transfer adds, which is nothing at the +/// schedule's prices: the account is paid for in state gas. +fn call_to_an_empty_precompile() -> u64 { + 100 + value_transfer() + crate::salt::entry(GasId::new_account_cost()) +} + +/// The accounts every case runs against: [`CONTRACT`] running `code` and holding `held`, a +/// [`RECEIVER`] and a [`DESTRUCTOR`]. +fn accounts(code: Bytes, held: u64) -> MemoryDatabase { + MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(held)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(RECEIVER).build()) + .account_balance(DESTRUCTOR, U256::from(VALUE)) +} + +/// A transaction from `caller` to `to` carrying `input` and `value`. +fn tx_to( + caller: Address, + to: Address, + input: &[u8], + value: u64, + gas_limit: u64, +) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(to), + gas_limit, + data: input.to_vec().into(), + value: U256::from(value), + ..Default::default() + })) +} + +/// A call's target, how it ended, and the gas it spent as its caller got it back. +type Ended = (Address, InstructionResult, u64); + +/// Runs `tx` against `db` under `limits`, with the recording inspector when `inspected`, whose +/// entry point starts frames through the same frame start: what the transaction did, and every +/// call the inspector saw end, in the order they ended. +fn run_tx( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, + inspected: bool, +) -> (Run, Vec) { + let evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + if !inspected { + return (run_on(&mut { evm }, tx), Vec::new()); + } + let mut evm = evm.with_inspector(Calls::default()); + let run = run_on(&mut evm, tx); + let ended = evm.inspector().calls.iter().map(|call| (call.target, call.result, call.spent)); + (run, ended.collect()) +} + +/// How the call to `target` ended, and what it spent. +fn ended(calls: &[Ended], target: Address) -> (InstructionResult, u64) { + let (_, result, spent) = calls.iter().find(|call| call.0 == target).expect("the call ended"); + (*result, *spent) +} + +/// Asserts that the data size `run` kept is its body, its write records and the transfer logs its +/// receipt carries, and nothing else, and returns those logs. +fn assert_counts_its_transfer_logs(run: &Run, body: u64, case: &str) -> Vec { + let logs = run.outcome.result.logs().to_vec(); + assert!(logs.iter().all(is_transfer_log), "{case}: no contract emits a log here"); + let usage = run.outcome.usage; + assert_eq!( + usage.data_size, + body + WRITE_RECORD_SIZE * usage.write_records + TRANSFER_LOG_SIZE * logs.len() as u64, + "{case}: the data size kept is the body, the records and the receipt's transfer logs" + ); + logs +} + +/// Asserts the detained run is the plain one: its result, logs included, every ledger of its bill +/// and what it kept. +fn assert_as_without_read(detained: &Run, plain: &Run, case: &str) { + assert!(detained.limit.is_some(), "{case}: the read set a limit"); + assert_eq!(plain.limit, None, "{case}: the push read nothing"); + assert_eq!(detained.outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(detained.outcome.result, plain.outcome.result, "{case}: the result"); + assert_eq!(detained.outcome.gas, plain.outcome.gas, "{case}: the bill"); + assert_eq!(detained.outcome.usage, plain.outcome.usage, "{case}: what it kept"); +} + +/// The balance `address` holds after the transaction: zero for an account it did not touch. +fn balance(run: &Run, address: Address) -> U256 { + run.outcome.state.get(&address).map(|account| account.info.balance).unwrap_or_default() +} + +/* ---------- a value call to a precompile ---------- */ + +/// A value `CALL` to modexp after a read, with all the gas: the call counts its transfer log +/// before revm runs the precompile, and the precompile runs on the allowance. +/// +/// - Priced within the allowance, modexp computes, the value moves, and the receipt carries the log +/// the data size counted, as without the read. +/// - Priced past the allowance but within the forward, modexp is answered without running, with the +/// stop: nothing moves and no log is journaled. The contract catches it and stores the failed +/// call's status on what the limit leaves it, ending within the limit or crossing it at the +/// store, and the transaction keeps its body alone either way. Without the read the call +/// succeeds, and its log is kept. +/// - Sent with value by the beneficiary straight to modexp, the transaction's own frame is detained +/// from its start with the cap as its allowance: priced past it, the same stop, billed its +/// intrinsic gas alone, and the value the transaction carries does not move. +#[test] +fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { + let (within, above) = (costly_modexp_input(32, 32), costly_modexp_input(64, 0)); + for gas_limit in TIERS { + let exec = |first, input: &[u8]| { + let db = accounts(calls_with_value(first, MODEXP, None), VALUE); + let tx = tx_to(CALLER, CONTRACT, input, 0, gas_limit); + let body = transaction_body_bytes(&tx); + (run_tx(db, tx, EvmTxRuntimeLimits::default(), true), body) + }; + + let ((detained, calls), body) = exec(TIMESTAMP, &within); + let ((plain, _), _) = exec(PUSH0, &within); + assert_as_without_read(&detained, &plain, "priced within the allowance"); + assert_eq!(ended(&calls, MODEXP).0, InstructionResult::Return, "modexp computed"); + let logs = assert_counts_its_transfer_logs(&detained, body, "priced within the allowance"); + assert_eq!(logs, [transfer_log(CONTRACT, MODEXP, U256::from(VALUE))]); + assert_eq!(detained.outcome.usage.write_records, 3, "the two ends and the status"); + assert_eq!(balance(&detained, MODEXP), U256::from(VALUE)); + + let ((detained, calls), body) = exec(TIMESTAMP, &above); + let ((plain, _), _) = exec(PUSH0, &above); + // The price is the charge past what the limit leaves the call, a precompile's warm access. + let price = mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&above); + let charges = charges_to_the_call(above.len() as u64, call_to_an_empty_precompile()) + .then(&[price.unwrap()]); + let intrinsic = intrinsic_with(&above, gas_limit); + assert_caught(&detained, intrinsic, charges.left(CAP), &failed_status_store()); + // The answer is the stop, having spent nothing. + assert_eq!(ended(&calls, MODEXP), (InstructionResult::Revert, 0)); + assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_counts_its_transfer_logs(&detained, body, "priced past the allowance"); + assert_eq!(balance(&detained, MODEXP), U256::ZERO, "nothing moved"); + assert!(plain.outcome.result.is_success()); + let logs = assert_counts_its_transfer_logs(&plain, body, "without the read"); + assert_eq!(logs, [transfer_log(CONTRACT, MODEXP, U256::from(VALUE))]); + + // The transaction's own frame: its value is counted with its start, before revm runs the + // precompile on the cap. + let sent = |caller| { + let db = MemoryDatabase::default().account_balance(caller, U256::from(VALUE)); + let tx = tx_to(caller, MODEXP, &above, VALUE, gas_limit); + let body = transaction_body_bytes(&tx); + (run_tx(db, tx, EvmTxRuntimeLimits::default(), true), body) + }; + let ((plain, calls), body) = sent(CALLER); + assert!(plain.outcome.result.is_success()); + let logs = assert_counts_its_transfer_logs(&plain, body, "a transaction to modexp"); + assert_eq!(logs, [transfer_log(CALLER, MODEXP, U256::from(VALUE))]); + let price = ended(&calls, MODEXP).1; + let ((detained, calls), body) = sent(BENEFICIARY); + assert_eq!(detained.limit, Some(CAP), "the sender is the beneficiary"); + assert_eq!(ended(&calls, MODEXP), (InstructionResult::Revert, 0)); + // Nothing is charged before the call: all the cap is left when its price does not fit it. + let left = Charges::default().then(&[price]).left(CAP); + assert_eq!(left, CAP); + assert_stopped(&detained, plain.outcome.gas.regular - price, left); + assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(balance(&detained, MODEXP), U256::ZERO, "the transaction's value did not move"); + } +} + +/* ---------- a value call its caller cannot fund ---------- */ + +/// A value call its caller cannot fund, after a read: revm refuses it on the caller's account +/// before anything moves, so its start counts no record and no log and is charged nothing, and +/// detention settles the refusal as it settles any answer. A precompile forwarded more than the +/// allowance, run on the allowance, gets the rest of its forward back. The transaction runs as +/// without the read: the call fails with the whole forward back, nothing moves, no log, and the +/// transaction keeps its body alone. +#[test] +fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { + let cases: [(&str, Address, Option); 4] = [ + ("a contract", RECEIVER, None), + ("an account with no code", PAYEE, None), + ("a precompile forwarded more than the allowance", MODEXP, None), + ("a precompile forwarded less than the allowance", IDENTITY, Some(100_000)), + ]; + for gas_limit in TIERS { + for (case, to, gas) in cases { + for inspected in [false, true] { + let exec = |first| { + let db = accounts(calls_with_value(first, to, gas), VALUE - 1); + let tx = tx_to(CALLER, CONTRACT, &[0xab; 64], 0, gas_limit); + run_tx(db, tx, EvmTxRuntimeLimits::default(), inspected) + }; + let ((detained, calls), (plain, plain_calls)) = (exec(TIMESTAMP), exec(PUSH0)); + assert_as_without_read(&detained, &plain, case); + let body = transaction_body_bytes(&tx_to(CALLER, CONTRACT, &[0xab; 64], 0, 0)); + assert_eq!( + detained.outcome.usage, + LimitUsage { data_size: body, write_records: 0 }, + "{case}: the refused start counted nothing" + ); + assert!(detained.outcome.result.logs().is_empty(), "{case}"); + assert_eq!(balance(&detained, CONTRACT), U256::from(VALUE - 1), "{case}"); + if inspected { + let (call, twin) = (ended(&calls, to), ended(&plain_calls, to)); + assert_eq!(call.0, InstructionResult::OutOfFunds, "{case}"); + assert_eq!((call.1, twin.1), (0, 0), "{case}: the forward came back"); + } + } + } + } +} + +/* ---------- a SELFDESTRUCT ---------- */ + +/// What a frame computes from a timestamp read to a completed `SELFDESTRUCT` of its balance to a +/// cold contract: the read's `POP`, the beneficiary's `PUSH20`, the opcode's 5,000 and the cold +/// access, which revm charges after it journaled the move and its transfer log. +fn destruct_after_read() -> u64 { + 2 + 3 + 5_000 + cold_access() +} + +/// A `SELFDESTRUCT` of a balance, after a read, whose frame the cap stops. +/// +/// - Destructing in the transaction's own frame under a cap that pays exactly the opcode, the +/// balance moves and the receipt carries the log the data size counted with the beneficiary's +/// record, as without the read. A unit less and the cold access, charged after revm journaled the +/// move and the log, crosses the cap: the opcode failed, so nothing is counted, and the stop +/// takes the move and the log back. Less than the opcode's own price, and its static charge +/// crosses before revm moves anything: the same stop. +/// - Destructing in a child, the record and the log land on the child's lane and merge into its +/// caller's. The caller then computes past the cap: the stop takes back the child's move and log +/// with the caller's lane, and the transaction keeps its body alone. Without the spin, the same +/// call keeps the log and the bytes, read or not. +#[test] +fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { + let own = |first| BytecodeBuilder::default().append_many([first, POP]).selfdestruct(RECEIVER); + let calls_destructor = + |first| crate::detention::call(op(BytecodeBuilder::default(), first), CALL, DESTRUCTOR); + for gas_limit in TIERS { + let tx = tx_to(CALLER, CONTRACT, &[], 0, gas_limit); + let body = transaction_body_bytes(&tx); + let under = + |cap| EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + + // In the transaction's own frame. + let run_own = |first, cap| { + run_tx(accounts(own(first).build(), VALUE), tx.clone(), under(cap), false).0 + }; + let (detained, plain) = + (run_own(TIMESTAMP, destruct_after_read()), run_own(PUSH0, destruct_after_read())); + assert_as_without_read(&detained, &plain, "a cap that pays the destruction"); + let logs = assert_counts_its_transfer_logs(&detained, body, "a destruction the cap pays"); + assert_eq!(logs, [transfer_log(CONTRACT, RECEIVER, U256::from(VALUE))]); + assert_eq!(detained.outcome.usage.write_records, 1, "the beneficiary's record"); + for cap in [destruct_after_read() - 1, destruct_after_read() - cold_access() - 1] { + let stopped = run_own(TIMESTAMP, cap); + let left = Charges::default().then(&[2, 3, 5_000, cold_access()]).left(cap); + assert_stopped(&stopped, intrinsic(gas_limit), left); + assert_eq!(stopped.limit, Some(2 + cap)); + assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "under {cap}, nothing moved"); + } + + // In a child, whose caller the cap stops afterwards. + let run_child = |code: BytecodeBuilder| { + run_tx(accounts(code.build(), 0), tx.clone(), EvmTxRuntimeLimits::default(), false).0 + }; + let (detained, plain) = ( + run_child(calls_destructor(TIMESTAMP).stop()), + run_child(calls_destructor(PUSH0).stop()), + ); + assert_as_without_read(&detained, &plain, "a child's destruction"); + let logs = assert_counts_its_transfer_logs(&detained, body, "a child's destruction"); + assert_eq!(logs, [transfer_log(DESTRUCTOR, RECEIVER, U256::from(VALUE))]); + let stopped = run_tx( + accounts(spin(calls_destructor(TIMESTAMP)), 0), + tx.clone(), + EvmTxRuntimeLimits::default(), + false, + ) + .0; + // The read's `POP`, the call's five pushes, its address, `GAS` and cold access, the child's + // `PUSH20` and destruction to a cold account, the caller's `POP`, then its loop. + let left = Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 2, cold_access(), 3, 5_000, cold_access(), 2]) + .spin(0) + .left(CAP); + assert_stopped(&stopped, intrinsic(gas_limit), left); + assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "the child's move was taken back"); + } +} + +/* ---------- every detained frame start ---------- */ + +/// A frame start after a read, as one case of +/// [`test_every_detained_frame_start_keeps_the_log_it_counted`]. +struct Start { + name: &'static str, + /// [`CONTRACT`]'s code after `first`. + code: fn(u8) -> Bytes, + /// The transaction's calldata. + input: fn() -> Vec, + /// What [`CONTRACT`] holds. + held: u64, + /// When the cap stops the call: the regular charges the transaction makes after the read up to + /// the one that crosses, with calldata of the given length. + stops: Option Charges>, +} + +/// Every path a frame start takes through detention, each moving value or refused on its caller's +/// account, after a read: a built frame, one the cap then stops, an answer without code, a +/// precompile run on its forward and on the allowance — computing, running out of the allowance, or +/// failing on its input past its gas check — a refused call and a refused creation, and the +/// creations and a destruction. Each runs at both tiers, with and without an inspector, whose +/// entry point reaches the same frame start. +/// +/// Every transaction keeps the data size of the transfer logs its receipt carries: a debug build +/// asserts at each start that revm journaled exactly the log counted, and the receipt shows what +/// that means for the transaction. Every case the cap does not stop runs as without the read; in +/// one it stops, the call is the stop, which the contract catches before it stores the call's +/// status. +#[test] +fn test_every_detained_frame_start_keeps_the_log_it_counted() { + let none = Vec::new; + let starts = [ + Start { + name: "a value call to a contract", + code: |first| calls_with_value(first, RECEIVER, None), + input: none, + held: VALUE, + stops: None, + }, + Start { + name: "a value call to a contract the cap then stops", + code: |first| calls_with_value(first, CHILD, None), + input: none, + held: VALUE, + // The call to the child's cold account, then the child's loop. + stops: Some(|len| charges_to_the_call(len, call_to_a_contract()).spin(0)), + }, + Start { + name: "a value call to an account with no code", + code: |first| calls_with_value(first, PAYEE, None), + input: none, + held: VALUE, + stops: None, + }, + Start { + name: "a value call to a precompile forwarded less than the allowance", + code: |first| calls_with_value(first, IDENTITY, Some(100_000)), + input: || vec![0xab; 64], + held: VALUE, + stops: None, + }, + Start { + name: "a value call to a precompile the allowance pays", + code: |first| calls_with_value(first, IDENTITY, None), + input: || vec![0xab; 64], + held: VALUE, + stops: None, + }, + Start { + name: "a value call to a precompile priced past the allowance", + code: |first| calls_with_value(first, MODEXP, None), + input: || costly_modexp_input(64, 0), + held: VALUE, + // The call to the precompile's warm account, then its price. + stops: Some(|len| { + let input = costly_modexp_input(64, 0); + let price = + mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&input); + charges_to_the_call(len, call_to_an_empty_precompile()).then(&[price.unwrap()]) + }), + }, + Start { + name: "a value call to a precompile whose input fails past its gas check", + code: |first| calls_with_value(first, EC_PAIRING, None), + input: || vec![0; 3 * 192 + 1], + held: VALUE, + stops: None, + }, + Start { + name: "a value call its caller cannot fund", + code: |first| calls_with_value(first, RECEIVER, None), + input: none, + held: VALUE - 1, + stops: None, + }, + Start { + name: "a value call to a precompile its caller cannot fund", + code: |first| calls_with_value(first, MODEXP, None), + input: || costly_modexp_input(64, 0), + held: VALUE - 1, + stops: None, + }, + Start { + name: "a CREATE with an endowment", + code: |first| { + op(BytecodeBuilder::default(), first) + .create(U256::from(VALUE), [STOP]) + .append(POP) + .stop() + .build() + }, + input: none, + held: VALUE, + stops: None, + }, + Start { + name: "a CREATE2 with an endowment", + code: |first| { + op(BytecodeBuilder::default(), first) + .create2(U256::from(VALUE), [STOP], U256::from(7)) + .append(POP) + .stop() + .build() + }, + input: none, + held: VALUE, + stops: None, + }, + Start { + name: "a CREATE its creator cannot fund", + code: |first| { + op(BytecodeBuilder::default(), first) + .create(U256::from(VALUE), [STOP]) + .append(POP) + .stop() + .build() + }, + input: none, + held: VALUE - 1, + stops: None, + }, + Start { + name: "a call to a contract that destructs", + code: |first| { + crate::detention::call(op(BytecodeBuilder::default(), first), CALL, DESTRUCTOR) + .stop() + .build() + }, + input: none, + held: VALUE, + stops: None, + }, + ]; + for gas_limit in TIERS { + for start in &starts { + let input = (start.input)(); + let tx = tx_to(CALLER, CONTRACT, &input, 0, gas_limit); + let body = transaction_body_bytes(&tx); + for inspected in [false, true] { + let case = format!("{} at {gas_limit}, inspected: {inspected}", start.name); + let exec = |first| { + let db = accounts((start.code)(first), start.held) + .account_code(CHILD, spin(BytecodeBuilder::default())); + run_tx(db, tx.clone(), EvmTxRuntimeLimits::default(), inspected).0 + }; + let detained = exec(TIMESTAMP); + assert_counts_its_transfer_logs(&detained, body, &case); + if let Some(charges) = start.stops { + let left = charges(input.len() as u64).left(CAP); + let intrinsic = intrinsic_with(&input, gas_limit); + assert_caught(&detained, intrinsic, left, &failed_status_store()); + assert_eq!(detained.outcome.usage.write_records, 0, "{case}"); + } else { + let plain = exec(PUSH0); + assert_counts_its_transfer_logs(&plain, body, &case); + assert_as_without_read(&detained, &plain, &case); + } + } + } + } +} diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs new file mode 100644 index 000000000..32ad40f7c --- /dev/null +++ b/crates/mega-evm/tests/satin/detention.rs @@ -0,0 +1,1751 @@ +//! Gas detention: a read of volatile data caps the compute the transaction may still spend. +//! +//! The cap is relative: at the read, the transaction's compute — its regular gas, without state +//! and history gas that spilled onto it — may grow by at most the cap. Crossing it stops the +//! transaction with the revert-class stop every transaction-level limit uses. The limit a read +//! sets is its compute then plus the cap, so a transaction that stops has spent its intrinsic gas +//! and its compute up to the charge that would have crossed the limit on the regular ledger: that +//! charge is not made, and the frame keeps what it had before it, the spendable part and the part +//! detention withheld. Where a stop lands follows from the charges a program makes after its read +//! ([`Charges`]). +//! +//! Every case runs below the execution cap, without a reservoir, and above it, with one. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + history_gas, + system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + volatile_data_access_disabled_revert_data, write_record_history_gas, EvmTxRuntimeLimits, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, OracleRead, ProtocolLimits, VolatileDataAccess, + TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::*, + context::{result::ExecutionResult, BlockEnv, TxEnv}, + context_interface::{block::BlobExcessGasAndPrice, cfg::GasId}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000d00000"); +pub(crate) const CONTRACT: Address = address!("0000000000000000000000000000000000d00001"); +pub(crate) const CHILD: Address = address!("0000000000000000000000000000000000d00002"); +pub(crate) const DELEGATOR: Address = address!("0000000000000000000000000000000000d00003"); +pub(crate) const BENEFICIARY: Address = address!("0000000000000000000000000000000000bef000"); + +pub(crate) const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; + +/// Below the execution cap: no reservoir. +pub(crate) const BELOW: u64 = 100_000_000; +/// Above it: a reservoir of 100,000,000. +pub(crate) const ABOVE: u64 = TX_GAS_LIMIT_CAP + 100_000_000; +pub(crate) const TIERS: [u64; 2] = [BELOW, ABOVE]; + +/// The compute of a write to a fresh, cold slot as [`BytecodeBuilder::sstore`] makes it: its two +/// pushes and `SSTORE`'s static and dynamic gas, 12,106 at the schedule's prices. +pub(crate) fn fresh_write() -> u64 { + 3 + 3 + sstore_static() + fresh_sstore() +} + +/// `SSTORE`'s static gas, which it charges before its dynamic gas. +pub(crate) fn sstore_static() -> u64 { + crate::salt::entry(GasId::sstore_static()) +} + +/// `SSTORE`'s dynamic gas on a fresh, cold slot: the cold access and the storage write. +pub(crate) fn fresh_sstore() -> u64 { + crate::salt::entry(GasId::cold_storage_cost()) + + crate::salt::entry(GasId::sstore_set_without_load_cost()) +} + +/// What the store of a failed call's status charges once the call returned: the push of the slot, +/// then `SSTORE`'s static gas and the cold access of a slot that holds zero, which the status, +/// zero, leaves as it is. +pub(crate) fn failed_status_store() -> Charges { + Charges::default().then(&[3, sstore_static(), crate::salt::entry(GasId::cold_storage_cost())]) +} + +/// What a call reaching a cold account pays for the access: the warm base and the cold surcharge, +/// 3,000 at the schedule's prices. +pub(crate) fn cold_access() -> u64 { + crate::salt::entry(GasId::warm_storage_read_cost()) + + crate::salt::entry(GasId::cold_account_additional_cost()) +} + +/// What a call carrying value pays for the transfer, the callee's stipend included. +pub(crate) fn value_transfer() -> u64 { + crate::salt::entry(GasId::transfer_value_cost()) +} + +/// What a write to a fresh slot costs beside its compute: the slot's state gas and its record's +/// history, at the prices the schedule was built with. +pub(crate) fn fresh_write_spill() -> u64 { + crate::salt::entry(GasId::sstore_set_state_gas()) + + write_record_history_gas(1).expect("a record has a price") +} + +/// Rounds of [`work`] spent before a read: 5,283,600 of compute. +pub(crate) const WORK: u32 = 1_700; + +/// The compute one round of [`work`] spends once its memory is expanded. +pub(crate) const WORK_ROUND: u64 = 3_108; + +/// Appends a copy of 32 KiB within memory: 3,075 gas, and 5,120 more to expand the memory the +/// first time. A round of it costs the interpreter little, whatever it costs in gas. +pub(crate) fn copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(0x8000_u16).append_many([PUSH0, PUSH0, MCOPY]) +} + +pub(crate) fn block() -> BlockEnv { + BlockEnv { + number: U256::from(300), + beneficiary: BENEFICIARY, + timestamp: U256::from(1_700_000_000), + gas_limit: 10_000_000_000, + basefee: 0, + prevrandao: Some(B256::repeat_byte(7)), + blob_excess_gas_and_price: Some(BlobExcessGasAndPrice { + excess_blob_gas: 0, + blob_gasprice: 3, + }), + slot_num: 9, + ..Default::default() + } +} + +pub(crate) fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +pub(crate) fn tx(caller: Address, to: Address, gas_limit: u64) -> MegaTransaction { + OpTx(op_transaction(TxEnv { caller, kind: TxKind::Call(to), gas_limit, ..Default::default() })) +} + +/// What a transaction did, and what detention made of it. +pub(crate) struct Run { + pub(crate) outcome: MegaTransactionOutcome, + pub(crate) limit: Option, + pub(crate) accessed: VolatileDataAccess, + pub(crate) detains: bool, +} + +pub(crate) fn run_on(evm: &mut MegaEvm, tx: MegaTransaction) -> Run +where + INSP: Inspector, EthInterpreter>, +{ + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let detention = evm.ctx().detention(); + Run { + outcome, + limit: detention.compute_limit(), + accessed: detention.accessed(), + detains: detention.detains(), + } +} + +pub(crate) fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { + run_on(&mut MegaEvm::new(context(db)), tx) +} + +/// The regular gas a call from `CALLER` spends before its first instruction. +pub(crate) fn intrinsic(gas_limit: u64) -> u64 { + let db = + MemoryDatabase::default().account_code(CONTRACT, BytecodeBuilder::default().stop().build()); + execute(db, tx(CALLER, CONTRACT, gas_limit)).outcome.gas.regular +} + +/// Appends a loop that never ends, 3,094 gas a round. +pub(crate) fn spin(code: BytecodeBuilder) -> Bytes { + let dest = code.len() as u32; + copy(code.append(JUMPDEST)).push_number(dest).append(JUMP).build() +} + +/// Appends `rounds` rounds of a counting loop that also copies memory, [`WORK_ROUND`] gas a +/// round. +pub(crate) fn work(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { + let code = code.push_number(rounds); + let dest = code.len() as u32; + copy(code.append(JUMPDEST)) + .push_number(1_u8) + .append_many([SWAP1, SUB, DUP1]) + .push_number(dest) + .append_many([JUMPI, POP]) +} + +/// Appends `rounds` rounds of a counting loop, twenty-six gas a round. +pub(crate) fn burn(code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { + let code = code.push_number(rounds); + let dest = code.len() as u32; + code.append(JUMPDEST) + .push_number(1_u8) + .append_many([SWAP1, SUB, DUP1]) + .push_number(dest) + .append_many([JUMPI, POP]) +} + +/// Appends a call of `scheme` to `to` forwarding all gas, dropping its status. +pub(crate) fn call(code: BytecodeBuilder, scheme: u8, to: Address) -> BytecodeBuilder { + let code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let code = if matches!(scheme, CALL | CALLCODE) { code.append(PUSH0) } else { code }; + code.push_address(to).append(GAS).append(scheme).append(POP) +} + +/// The revert data of the detention stop at `limit`. +pub(crate) fn stop_data(limit: u64) -> Bytes { + MegaLimitExceeded { kind: LimitKind::ComputeGas.as_u8(), limit }.abi_encode().into() +} + +/// Asserts the transaction was stopped by detention, having computed up to the charge that +/// crossed its limit and not one unit past it: the stopped frame keeps what it had before that +/// charge, `left` short of the limit, so the transaction's compute, which the stop reports and its +/// regular ledger bills, is the limit less `left`. Returns the limit. +pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { + let limit = run.limit.expect("a read set a limit"); + match &run.outcome.result { + ExecutionResult::Revert { output, .. } => assert_eq!(output, &stop_data(limit)), + other => panic!("expected the detention stop, got {other:?}"), + } + let used = limit - left; + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used, + frame_local: false + }) + ); + assert_eq!( + run.outcome.gas.regular, + intrinsic + used, + "the transaction computed up to the charge that crossed its limit and not one unit past it" + ); + assert_eq!(run.outcome.gas.state, 0, "a stop keeps no state"); + assert!(run.outcome.result.logs().is_empty(), "a stop keeps no log"); + limit +} + +/// Asserts that a frame below the transaction's own crossed the limit `left` short of it, and that +/// the transaction's own frame, its caller, caught the stop and ran `after` on what the limit left +/// it, the `left` the crossing charge was not made from. +/// +/// When `after` ends within it, the transaction succeeds, billed its compute at the crossing and +/// `after` on top: within the limit, which reports no stop. When it does not, the caller's own +/// charge crosses the limit again, and that is the stop the transaction reports +/// ([`assert_stopped`]). Returns the limit. +pub(crate) fn assert_caught(run: &Run, intrinsic: u64, left: u64, after: &Charges) -> u64 { + if let Some(left) = after.crossing(left) { + return assert_stopped(run, intrinsic, left); + } + let limit = run.limit.expect("a read set a limit"); + assert!( + run.outcome.result.is_success(), + "the caller caught the stop: {:?}", + run.outcome.result + ); + assert_eq!(run.outcome.limit_exceeded, None, "a stop below the transaction's own frame"); + assert_eq!( + run.outcome.gas.regular, + intrinsic + limit - left + after.total(), + "the transaction computed up to the charge that crossed, then what its caller ran" + ); + assert!(run.outcome.gas.regular <= intrinsic + limit, "within the limit"); + limit +} + +/* ---------- where a stop lands ---------- */ + +/// The regular charges a program makes after its read, in the order the interpreter makes them: +/// each instruction's static gas, then its dynamic charges. Each part is a run of charges made +/// some number of times, or forever. +/// +/// The stop lands on the first charge the limit leaves no room for: that charge is not made, and +/// the stopped frame keeps what it had before it ([`left`](Self::left)). +#[derive(Clone, Debug, Default)] +pub(crate) struct Charges(Vec<(Vec, Option)>); + +impl Charges { + /// `charges`, once. + pub(crate) fn then(self, charges: &[u64]) -> Self { + self.repeat(charges, 1) + } + + /// `charges`, `times` times over. + pub(crate) fn repeat(mut self, charges: &[u64], times: u64) -> Self { + self.0.push((charges.to_vec(), Some(times))); + self + } + + /// `charges`, over and over. + pub(crate) fn forever(mut self, charges: &[u64]) -> Self { + self.0.push((charges.to_vec(), None)); + self + } + + /// What the charges add up to, for a program that ends. + pub(crate) fn total(&self) -> u64 { + self.0 + .iter() + .map(|(charges, times)| { + charges.iter().sum::() * times.expect("a program that ends") + }) + .sum() + } + + /// What `allowance` has left when the first charge it cannot pay comes: what a frame the limit + /// left `allowance` at the read has when it crosses the limit. + pub(crate) fn left(&self, allowance: u64) -> u64 { + self.crossing(allowance).expect("the program ends within the allowance") + } + + /// [`left`](Self::left), or `None` when the program ends within `allowance`. + pub(crate) fn crossing(&self, mut allowance: u64) -> Option { + for (charges, times) in &self.0 { + let round: u64 = charges.iter().sum(); + if round == 0 { + continue; + } + let rounds = allowance / round; + if times.is_some_and(|times| rounds >= times) { + allowance -= round * times.unwrap(); + continue; + } + allowance -= round * rounds; + for charge in charges { + if *charge > allowance { + return Some(allowance); + } + allowance -= charge; + } + unreachable!("a round the allowance cannot pay whole has a charge it cannot pay"); + } + None + } + + /// The charges of [`spin`]'s loop in a frame whose memory holds `words` words: `JUMPDEST`, the + /// copy — a push, two `PUSH0`, and `MCOPY`'s static gas, then its copy, then the memory it + /// expands to the 32 KiB it copies ([`expansion`]) — then the push of the loop's start and + /// `JUMP`. + pub(crate) fn spin(self, words: u64) -> Self { + self.then(&[1, 3, 2, 2, 3, 3_072, expansion(words), 3, 8]) + .forever(&[1, 3, 2, 2, 3, 3_072, 3, 8]) + } + + /// The charges of [`work`]'s `rounds` rounds in a frame whose memory holds `words` words: the + /// push of the counter, then each round — `JUMPDEST`, the copy as [`spin`](Self::spin) makes + /// it, `PUSH1`, `SWAP1`, `SUB`, `DUP1`, the push of the loop's start and `JUMPI` — then the + /// `POP` of the counter. + pub(crate) fn work(self, rounds: u32, words: u64) -> Self { + let round = [1, 3, 2, 2, 3, 3_072, 3, 3, 3, 3, 3, 10]; + let charges = self.then(&[3]); + let charges = match rounds { + 0 => charges, + rounds => charges + .then(&[1, 3, 2, 2, 3, 3_072, expansion(words), 3, 3, 3, 3, 3, 10]) + .repeat(&round, u64::from(rounds) - 1), + }; + charges.then(&[2]) + } + + /// The charges of [`burn`]'s `rounds` rounds: the push of the counter, then each round — + /// `JUMPDEST`, `PUSH1`, `SWAP1`, `SUB`, `DUP1`, the push of the loop's start and `JUMPI` — + /// then the `POP` of the counter. + pub(crate) fn burn(self, rounds: u32) -> Self { + self.then(&[3]).repeat(&[1, 3, 3, 3, 3, 3, 10], u64::from(rounds)).then(&[2]) + } + + /// The charges of `count` writes of a fresh, cold slot, each pushing its value and its slot: + /// two pushes, then `SSTORE`'s static gas and its dynamic gas, the cold access and the set. + /// Their state and history gas are not compute. + pub(crate) fn fresh_writes(self, count: u64) -> Self { + self.repeat(&[3, 3, sstore_static(), fresh_sstore()], count) + } +} + +/// What a frame's memory of `words` words costs: `3 w + w² / 512`. +pub(crate) const fn memory_cost(words: u64) -> u64 { + 3 * words + words * words / 512 +} + +/// What expanding a frame's memory from `words` words to the 1,024 words of [`copy`] costs. +pub(crate) const fn expansion(words: u64) -> u64 { + if words >= 1_024 { + 0 + } else { + memory_cost(1_024) - memory_cost(words) + } +} + +/* ---------- every read ---------- */ + +/// A piece of code appended to a program. +type Append = fn(BytecodeBuilder) -> BytecodeBuilder; + +/// One volatile read: the code that makes it, what else the database needs, the kind it records, +/// and the regular charges its code makes after the read is committed. +struct Read { + name: &'static str, + code: Append, + db: fn(MemoryDatabase) -> MemoryDatabase, + access: VolatileDataAccess, + after: &'static [u64], +} + +fn no_setup(db: MemoryDatabase) -> MemoryDatabase { + db +} + +pub(crate) fn op(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { + code.append(opcode).append(POP) +} + +pub(crate) fn on_beneficiary(code: BytecodeBuilder, opcode: u8) -> BytecodeBuilder { + code.push_address(BENEFICIARY).append(opcode).append(POP) +} + +/// Every opcode read of volatile data. +fn reads() -> Vec { + vec![ + Read { + name: "NUMBER", + code: |c| op(c, NUMBER), + db: no_setup, + access: VolatileDataAccess::BLOCK_NUMBER, + after: &[2], + }, + Read { + name: "TIMESTAMP", + code: |c| op(c, TIMESTAMP), + db: no_setup, + access: VolatileDataAccess::TIMESTAMP, + after: &[2], + }, + Read { + name: "COINBASE", + code: |c| op(c, COINBASE), + db: no_setup, + access: VolatileDataAccess::COINBASE, + after: &[2], + }, + Read { + name: "PREVRANDAO", + code: |c| op(c, DIFFICULTY), + db: no_setup, + access: VolatileDataAccess::PREV_RANDAO, + after: &[2], + }, + Read { + name: "GASLIMIT", + code: |c| op(c, GASLIMIT), + db: no_setup, + access: VolatileDataAccess::GAS_LIMIT, + after: &[2], + }, + Read { + name: "BASEFEE", + code: |c| op(c, BASEFEE), + db: no_setup, + access: VolatileDataAccess::BASE_FEE, + after: &[2], + }, + Read { + name: "BLOBBASEFEE", + code: |c| op(c, BLOBBASEFEE), + db: no_setup, + access: VolatileDataAccess::BLOB_BASE_FEE, + after: &[2], + }, + Read { + name: "SLOTNUM", + code: |c| op(c, SLOTNUM), + db: no_setup, + access: VolatileDataAccess::SLOT_NUM, + after: &[2], + }, + Read { + name: "BLOCKHASH", + code: |c| c.push_number(299_u16).append(BLOCKHASH).append(POP), + db: no_setup, + access: VolatileDataAccess::BLOCK_NUMBER | VolatileDataAccess::BLOCK_HASH, + after: &[2], + }, + Read { + name: "BALANCE", + code: |c| on_beneficiary(c, BALANCE), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "EXTCODESIZE", + code: |c| on_beneficiary(c, EXTCODESIZE), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "EXTCODEHASH", + code: |c| on_beneficiary(c, EXTCODEHASH), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "EXTCODECOPY", + code: |c| { + c.push_number(32_u8) + .append_many([PUSH0, PUSH0]) + .push_address(BENEFICIARY) + .append(EXTCODECOPY) + }, + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + // The copy leaves nothing on the stack. + after: &[], + }, + Read { + name: "CALL", + code: |c| call(c, CALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "CALLCODE", + code: |c| call(c, CALLCODE, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "DELEGATECALL", + code: |c| call(c, DELEGATECALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "STATICCALL", + code: |c| call(c, STATICCALL, BENEFICIARY), + db: no_setup, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "CALL to an EIP-7702 delegator of the beneficiary", + code: |c| call(c, CALL, DELEGATOR), + db: |db| with_delegation(db, DELEGATOR, BENEFICIARY), + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "SELFDESTRUCT to the beneficiary", + code: |c| call(c, CALL, CHILD), + db: |db| { + db.account_code( + CHILD, + BytecodeBuilder::default() + .push_address(BENEFICIARY) + .append(SELFDESTRUCT) + .build(), + ) + }, + access: VolatileDataAccess::BENEFICIARY_BALANCE, + after: &[2], + }, + Read { + name: "SLOAD of the Oracle's storage", + code: |c| call(c, CALL, ORACLE_CONTRACT_ADDRESS), + db: |db| { + db.account_code( + ORACLE_CONTRACT_ADDRESS, + BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(), + ) + }, + access: VolatileDataAccess::ORACLE, + // The Oracle's `POP`, then its caller's. + after: &[2, 2], + }, + ] +} + +/// Gives `address` the `0xef0100 || to` designator an applied EIP-7702 authorization leaves. +pub(crate) fn with_delegation( + mut db: MemoryDatabase, + address: Address, + to: Address, +) -> MemoryDatabase { + use revm::{database::AccountState, state::Bytecode}; + let bytecode = Bytecode::new_eip7702(to); + let code_hash = bytecode.hash_slow(); + let account = db.load_account(address).expect("the account is in memory"); + account.info.code = Some(bytecode); + account.info.code_hash = code_hash; + account.account_state = AccountState::None; + db +} + +/// Every read caps the transaction from where it read, not from its start: the transaction first +/// spends [`WORK`] rounds of work, less compute than the cap, then reads, then computes forever, +/// and it stops at the first charge past its compute at the read plus the cap, having spent +/// everything before it. A spend larger than the cap before the read is the next test's. +#[test] +fn test_every_volatile_read_caps_the_transaction_from_where_it_read() { + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + for read in reads() { + let code = spin((read.code)(work(BytecodeBuilder::default(), WORK))); + let db = (read.db)(MemoryDatabase::default().account_code(CONTRACT, code)); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + // The work expanded the memory the loop copies. + let left = Charges::default().then(read.after).spin(1_024).left(CAP); + let limit = assert_stopped(&run, intrinsic, left); + let at_read = limit - CAP; + assert!( + at_read > u64::from(WORK) * WORK_ROUND && + at_read < u64::from(WORK) * WORK_ROUND + 20_000, + "{}: the cap counts from the read, which came after {at_read} of compute", + read.name + ); + assert_eq!(run.accessed, read.access, "{}", read.name); + // Only a read of the Oracle's storage goes through the oracle service: its slot zero, + // which the service, absent from this context, does not answer. + let oracle_reads: &[OracleRead] = if read.access == VolatileDataAccess::ORACLE { + &[OracleRead { slot: U256::ZERO, answer: None }] + } else { + &[] + }; + assert_eq!(run.outcome.oracle_reads, oracle_reads, "{}: the oracle reads", read.name); + } + } +} + +/// The cap is relative: a transaction that spent more than the cap before it read may still +/// spend the cap after, and one that stops soon after the read completes. +#[test] +fn test_the_cap_counts_from_a_spend_larger_than_itself() { + let before = 7_000_u32; + for gas_limit in TIERS { + let code = spin(op(work(BytecodeBuilder::default(), before), TIMESTAMP)); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + let left = Charges::default().then(&[2]).spin(1_024).left(CAP); + let limit = assert_stopped(&run, intrinsic(gas_limit), left); + assert!(limit - CAP > u64::from(before) * WORK_ROUND, "{limit}"); + assert!(limit - CAP > CAP); + + let code = op(work(BytecodeBuilder::default(), before), TIMESTAMP).stop().build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.limit, Some(limit), "the same read at the same compute"); + } +} + +/// Without the read, the same computation is not capped: it runs until the frame's own gas is +/// gone, and halts. +#[test] +fn test_without_a_read_nothing_is_capped() { + for gas_limit in TIERS { + let code = spin(work(BytecodeBuilder::default(), WORK)); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert!( + matches!( + run.outcome.result, + ExecutionResult::Halt { reason: mega_evm::MegaHaltReason::Base(_), .. } + ), + "{:?}", + run.outcome.result + ); + assert_eq!(run.limit, None); + assert_eq!(run.outcome.limit_exceeded, None); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + } +} + +/// A transaction whose sender is the beneficiary is detained from its first instruction: its limit +/// is the cap. +#[test] +fn test_a_transaction_from_the_beneficiary_is_detained_from_the_start() { + for gas_limit in TIERS { + // Detained before its first instruction: the whole program runs after the read. + let left = Charges::default().spin(0).left(CAP); + let db = MemoryDatabase::default().account_code(CONTRACT, spin(BytecodeBuilder::default())); + let run = execute(db, tx(BENEFICIARY, CONTRACT, gas_limit)); + // A sender's intrinsic gas is the same whoever it is. + assert_eq!(assert_stopped(&run, intrinsic(gas_limit), left), CAP, "the sender"); + } +} + +/// An account read of anything but the beneficiary, and a storage read of anything but the +/// Oracle, are not volatile. +#[test] +fn test_other_accounts_and_storage_are_not_volatile() { + let code = BytecodeBuilder::default() + .push_address(CHILD) + .append(BALANCE) + .append(POP) + .append_many([PUSH0, SLOAD, POP]); + let code = call(call(code, CALL, CHILD), STATICCALL, CHILD).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_code(CHILD, BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]).build()); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success()); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + assert_eq!(run.limit, None); +} + +/// `BLOBHASH` reads the transaction's own blob hashes, which nothing but the transaction decides: +/// it is not volatile. +#[test] +fn test_blobhash_is_not_volatile() { + let code = BytecodeBuilder::default().append_many([PUSH0, BLOBHASH, POP, STOP]).build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, BELOW), + ); + assert!(run.outcome.result.is_success()); + assert_eq!(run.accessed, VolatileDataAccess::empty()); +} + +/// A read answers with the block's own field: the Host marks the read and serves the value it +/// loaded, whether or not the read caps anything. +#[test] +fn test_a_read_answers_with_the_blocks_field() { + let reads = [ + (NUMBER, U256::from(300)), + (TIMESTAMP, U256::from(1_700_000_000)), + (COINBASE, U256::from_be_slice(BENEFICIARY.as_slice())), + (DIFFICULTY, U256::from_be_bytes(B256::repeat_byte(7).0)), + (GASLIMIT, U256::from(10_000_000_000_u64)), + (BASEFEE, U256::from(1)), + (BLOBBASEFEE, U256::from(3)), + (SLOTNUM, U256::from(9)), + ]; + let mut code = BytecodeBuilder::default(); + for (slot, (opcode, _)) in reads.iter().enumerate() { + code = code.append(*opcode).push_number(slot as u8).append(SSTORE); + } + // BLOCKHASH of the parent, and the beneficiary's balance. + let code = code + .push_number(299_u16) + .append(BLOCKHASH) + .push_number(8_u8) + .append(SSTORE) + .push_address(BENEFICIARY) + .append(BALANCE) + .push_number(9_u8) + .append(SSTORE) + .stop() + .build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(BENEFICIARY, U256::from(42)) + .account_balance(CALLER, U256::from(1_000_000_000_000_u64)); + let mut ctx = context(db).with_block(BlockEnv { basefee: 1, ..block() }); + ctx.modify_chain(|chain| chain.l1_base_fee = U256::ZERO); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit: BELOW, + gas_price: 1, + ..Default::default() + })); + let run = run_on(&mut MegaEvm::new(ctx), tx); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let storage = &run.outcome.state[&CONTRACT].storage; + for (slot, (opcode, value)) in reads.iter().enumerate() { + assert_eq!(storage[&U256::from(slot)].present_value, *value, "{opcode:#04x}"); + } + let hash = revm::Database::block_hash(&mut MemoryDatabase::default(), 299).unwrap(); + assert_eq!(storage[&U256::from(8)].present_value, U256::from_be_bytes(hash.0), "BLOCKHASH"); + assert_eq!(storage[&U256::from(9)].present_value, U256::from(42), "BALANCE"); + assert!(run.limit.is_some()); +} + +/* ---------- the limit ---------- */ + +/// A later read lowers the limit only when its own is lower: with equal caps the first read +/// binds, in either order of block environment and Oracle. +#[test] +fn test_the_most_restrictive_limit_binds_whatever_the_order() { + assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, CAP, "the two caps are equal today"); + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + for block_env_first in [true, false] { + let first = |c| { + if block_env_first { + op(c, TIMESTAMP) + } else { + call(c, CALL, ORACLE_CONTRACT_ADDRESS) + } + }; + let second = |c| { + if block_env_first { + call(c, CALL, ORACLE_CONTRACT_ADDRESS) + } else { + op(c, TIMESTAMP) + } + }; + // The first read, 1,000,000 of compute, the second read, then forever. + let code = spin(second(work(first(BytecodeBuilder::default()), 300))); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + // What the program charges after the first read, which sets the limit: the loop + // expands the memory its work copies first. + let charges = if block_env_first { + // The `POP`, the work, then the call to the Oracle — five pushes, its address, + // `GAS` and the cold access — the Oracle's push, cold `SLOAD` and `POP`, and the + // caller's `POP`. + Charges::default().then(&[2]).work(300, 0).then(&[ + 2, + 2, + 2, + 2, + 2, + 3, + 2, + cold_access(), + 2, + 2_100, + 2, + 2, + ]) + } else { + // The Oracle's `POP` and its caller's, the work, then `TIMESTAMP` and its `POP`. + Charges::default().then(&[2, 2]).work(300, 0).then(&[2, 2]) + }; + let limit = assert_stopped(&run, intrinsic, charges.spin(1_024).left(CAP)); + assert!(limit < CAP + 100_000, "the first read set the limit: {limit}"); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP | VolatileDataAccess::ORACLE); + } + } +} + +/// The caps are runtime limits: a caller's limits set either one, and each kind of read is held +/// to its own. Under `no_limits` both are unlimited and a transaction that reads is not detained: +/// it computes on until its own gas is gone, and halts. +#[test] +fn test_a_callers_limits_set_the_caps() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + let limits = EvmTxRuntimeLimits::default() + .with_block_env_access_compute_gas_limit(1_000_000) + .with_oracle_access_compute_gas_limit(2_000_000); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let run_under = |limits: EvmTxRuntimeLimits, code: Bytes| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)) + }; + + // `TIMESTAMP` is the first instruction: 2 of compute at the read. Its `POP` and the loop + // come after it. + let run = run_under(limits, spin(op(BytecodeBuilder::default(), TIMESTAMP))); + let left = Charges::default().then(&[2]).spin(0).left(1_000_000); + assert_eq!(assert_stopped(&run, intrinsic, left), 2 + 1_000_000); + + let run = run_under( + limits, + spin(call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS)), + ); + // The Oracle's `POP` and its caller's, then the loop. + let left = Charges::default().then(&[2, 2]).spin(0).left(2_000_000); + let limit = assert_stopped(&run, intrinsic, left); + assert!((2_000_000..2_100_000).contains(&limit), "the Oracle's own cap: {limit}"); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); + + let run = run_under( + EvmTxRuntimeLimits::no_limits(), + spin(op(work(BytecodeBuilder::default(), WORK), TIMESTAMP)), + ); + assert!(!run.detains); + assert_eq!(run.limit, None); + assert_eq!(run.outcome.limit_exceeded, None); + assert!( + matches!(run.outcome.result, ExecutionResult::Halt { .. }), + "{:?}", + run.outcome.result + ); + } +} + +/// The default runtime limits detain: [`EvmTxRuntimeLimits::default`], and the transaction half +/// of [`ProtocolLimits::for_spec`] that a context starts with and a block executor installs, hold +/// each kind of read to the spec's cap. +#[test] +fn test_the_default_limits_detain() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + let timestamp = op(BytecodeBuilder::default(), TIMESTAMP).stop().build(); + let reads_oracle = + call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS).stop().build(); + for limits in [ + EvmTxRuntimeLimits::default(), + ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits, + ] { + let run_under = |limits: EvmTxRuntimeLimits, code: &Bytes| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.clone()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)) + }; + let run = run_under(limits, ×tamp); + assert!(run.detains); + assert_eq!(run.limit, Some(2 + BLOCK_ENV_ACCESS_COMPUTE_GAS), "TIMESTAMP was the first"); + let run = run_under(limits, &reads_oracle); + let limit = run.limit.unwrap(); + assert!( + (ORACLE_ACCESS_COMPUTE_GAS..ORACLE_ACCESS_COMPUTE_GAS + 100_000).contains(&limit), + "{limit}" + ); + } +} + +/// Spending exactly the cap after the read is within it; the limit is strict. +#[test] +fn test_spending_exactly_the_cap_completes() { + // TIMESTAMP (2) and POP (2) leave 19,999,998 of the cap; the loop spends 26 a round after + // the three gas its counter's push costs, and its last round ends in POP (2) and STOP. + let rounds = (CAP - 2 - 2 - 3 - 2) / 26; + let spent = 2 + 2 + 3 + u64::from(u32::try_from(rounds).unwrap()) * 26 + 2; + assert!(spent <= CAP + 2, "{spent}"); + for gas_limit in TIERS { + let code = burn(op(BytecodeBuilder::default(), TIMESTAMP), u32::try_from(rounds).unwrap()) + .stop() + .build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.outcome.gas.regular, intrinsic(gas_limit) + spent); + + // One more round crosses it. + let more = u32::try_from(rounds).unwrap() + 1; + let code = burn(op(BytecodeBuilder::default(), TIMESTAMP), more).stop().build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + let left = Charges::default().then(&[2]).burn(more).left(CAP); + assert_stopped(&run, intrinsic(gas_limit), left); + } +} + +/// A value call's stipend is gas nobody paid, so what the callee runs on it is not compute beyond +/// what its caller's ledger shows: a value-carrying child that reads and spins stops with the +/// regular ledger at its compute before the charge that crossed, which its caller catches and +/// ends on, and so does a transaction carrying value, whose own frame is given what the +/// transaction has left and no stipend. +#[test] +fn test_a_stipend_is_not_compute() { + let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(CHILD) + .append_many([GAS, CALL, STOP]) + .build(); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + // Either way the reading frame's `POP` and its loop come after the read. + let left = Charges::default().then(&[2]).spin(0).left(CAP); + assert_caught(&run, intrinsic(gas_limit), left, &Charges::default()); + + let db = MemoryDatabase::default() + .account_code(CONTRACT, spin(op(BytecodeBuilder::default(), TIMESTAMP))) + .account_balance(CALLER, U256::from(1)); + let mut valued = tx(CALLER, CONTRACT, gas_limit); + valued.0.base.value = U256::from(1); + let run = execute(db, valued); + let limit = assert_stopped(&run, intrinsic_of_a_value_call(gas_limit), left); + assert_eq!(limit, CAP + 2, "TIMESTAMP was the first opcode"); + } +} + +/// A read made by a call is counted from the compute the caller paid at it: its pushes, its +/// static and dynamic gas, and the gas it forwards to the callee less a value call's stipend, +/// which nobody paid. The limit is exact for a plain call and for one carrying value. +#[test] +fn test_a_call_that_reads_counts_from_what_its_caller_paid() { + for (value, compute) in [ + // PUSH0 x4, PUSH0, PUSH20, GAS and a warm CALL. + (false, 2 * 4 + 2 + 3 + 2 + 100), + // PUSH0 x4, PUSH1, PUSH20, GAS, a warm CALL and the value transfer. + (true, 2 * 4 + 3 + 3 + 2 + 100 + value_transfer()), + ] { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let code = if value { code.push_number(1_u8) } else { code.append(PUSH0) }; + let code = code.push_address(BENEFICIARY).append_many([GAS, CALL, POP, STOP]).build(); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_balance(BENEFICIARY, U256::from(1)); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "value {value}: {:?}", run.outcome.result); + assert_eq!(run.limit, Some(compute + CAP), "value {value}"); + } + } +} + +/// The regular gas a call from `CALLER` carrying one wei spends before its first instruction. +fn intrinsic_of_a_value_call(gas_limit: u64) -> u64 { + let db = MemoryDatabase::default() + .account_code(CONTRACT, BytecodeBuilder::default().stop().build()) + .account_balance(CALLER, U256::from(1)); + let mut valued = tx(CALLER, CONTRACT, gas_limit); + valued.0.base.value = U256::from(1); + execute(db, valued).outcome.gas.regular +} + +/* ---------- across frames ---------- */ + +/// A child's read caps its caller after the child returns: the caller resumes on what the limit +/// leaves the transaction, and stops there. +#[test] +fn test_a_childs_read_caps_its_caller() { + let child = work(op(BytecodeBuilder::default(), TIMESTAMP), 500).stop().build(); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let parent = spin(call(BytecodeBuilder::default(), CALL, CHILD)); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + // The child's `POP` and work, then its caller's `POP` and loop, each in its own memory. + let left = Charges::default().then(&[2]).work(500, 0).then(&[2]).spin(0).left(CAP); + let limit = assert_stopped(&run, intrinsic, left); + assert!(limit < CAP + 100_000, "the child read near the start: {limit}"); + } +} + +/// When a child crosses the cap, it reverts alone and its caller resumes, held to what the limit +/// leaves the transaction, which is less than the charge that crossed: the caller's code after +/// the call — a write and a log — runs until one of its charges crosses the limit again, and the +/// caller returns the same stop, keeping nothing. The caller runs the last step. +#[test] +fn test_a_caller_resumes_after_the_stop_held_to_what_is_left() { + let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); + let parent = call(BytecodeBuilder::default(), CALL, CHILD) + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, LOG0]) + .stop() + .build(); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + let left = Charges::default().then(&[2]).spin(0).left(CAP); + // The caller's `POP`, then its write, which the room the spin left cannot pay. + let after = Charges::default().then(&[2]).fresh_writes(1); + assert!(after.crossing(left).is_some(), "the write crosses the limit again"); + let limit = assert_caught(&run, intrinsic, left, &after); + assert!(run.outcome.state[&CONTRACT].storage.values().all(|slot| !slot.is_changed())); + let calls = &evm.inspector().calls; + assert_eq!( + calls.iter().map(|c| (c.target, c.result, c.output.clone())).collect::>(), + vec![ + (CHILD, InstructionResult::Revert, stop_data(limit)), + (CONTRACT, InstructionResult::Revert, stop_data(limit)), + ] + ); + assert!(evm.inspector().opcodes.contains(&SSTORE), "the caller resumed"); + assert!(!evm.inspector().opcodes.contains(&LOG0), "and stopped at its write"); + assert_eq!(evm.inspector().last_frame, Some(CONTRACT), "the caller ran the last step"); + } +} + +/// The stop settles like an EIP-8037 revert: what the sender pays does not depend on whether +/// the transaction had a reservoir, because the reservoir and everything detention withheld go +/// back to it. Above the execution cap the reservoir comes back whole, less the body's history, +/// which it paid first. +#[test] +fn test_the_stop_bills_the_same_above_and_below_the_execution_cap() { + let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); + let parent = spin(call(BytecodeBuilder::default(), CALL, CHILD)); + let used: Vec<_> = TIERS + .iter() + .map(|gas_limit| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, *gas_limit)); + // The child's `POP` and spin, then its caller's, which resumes on what is left. + let left = Charges::default().then(&[2]).spin(0).left(CAP); + assert_caught( + &run, + intrinsic(*gas_limit), + left, + &Charges::default().then(&[2]).spin(0), + ); + let body_history = run.outcome.gas.history; + let reservoir = gas_limit.saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(body_history); + assert_eq!(run.outcome.gas.reservoir_remaining, reservoir, "the reservoir came back"); + let gas = run.outcome.gas; + (gas.gas_used, gas.regular, gas.state, gas.history) + }) + .collect(); + assert_eq!(used[0], used[1]); + assert!(used[0].0 < CAP + 1_000_000, "the stop does not burn the gas: {}", used[0].0); +} + +/* ---------- real out-of-gas ---------- */ + +/// A frame detention withheld nothing from runs out of its own gas: it halts and burns what it +/// was given, below and above the execution cap. +#[test] +fn test_running_out_of_the_frames_own_gas_still_halts() { + // The transaction has less than the cap: nothing is withheld. + let code = spin(op(BytecodeBuilder::default(), TIMESTAMP)); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, 1_000_000), + ); + assert!(matches!(run.outcome.result, ExecutionResult::Halt { .. }), "{:?}", run.outcome.result); + assert_eq!(run.outcome.result.gas().tx_gas_used(), 1_000_000, "a halt burns the gas"); + assert_eq!(run.outcome.limit_exceeded, None); + assert!(run.limit.is_some(), "the read still set a limit"); + + // A child given less than the limit leaves halts on its own, and its caller resumes. + let child = spin(BytecodeBuilder::default()); + let parent = op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(100_000_u32) + .append(CALL) + .push_number(0_u8) + .append(SSTORE) + .stop() + .build(); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let slot = run.outcome.state[&CONTRACT].storage.get(&U256::ZERO).unwrap(); + assert_eq!(slot.present_value, U256::ZERO, "the call failed: the child halted"); + assert!(slot.is_changed() || slot.original_value.is_zero()); + } +} + +/// Writes after a read are held to the cap by the regular gas they spend. With room in the +/// reservoir for their state and history gas, one fresh slot more than the cap's compute pays for +/// — 1,653 at the schedule's prices, 20,011,218 of compute — crosses it and stops the transaction, +/// at the first write's charge past it. Without a reservoir, +/// and with less gas than the writes spend before their compute reaches the cap, the writes drain +/// the withheld gas first and the frame runs out of its own gas where it would have undetained: it +/// halts. +#[test] +fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { + let slots = CAP / fresh_write() + 1; + let mut code = op(BytecodeBuilder::default(), TIMESTAMP); + for slot in 1..=slots { + code = code.sstore(U256::from(slot), U256::from(1)); + } + let code = code.stop().build(); + + // A reservoir that pays every write's state gas and history. + let gas_limit = TX_GAS_LIMIT_CAP + slots * fresh_write_spill(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + tx(CALLER, CONTRACT, gas_limit), + ); + let left = Charges::default().then(&[2]).fresh_writes(slots).left(CAP); + assert_stopped(&run, intrinsic(gas_limit), left); + + // The cap, and half of what the writes that fit in it spill: more than the cap, so the read + // withholds gas, and less than those writes spend, so the gas runs out before the compute + // reaches the cap. Below the execution cap either way. + let gas_limit = BELOW.min(CAP + CAP / fresh_write() * fresh_write_spill() / 2); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(matches!(run.outcome.result, ExecutionResult::Halt { .. }), "{:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None); + assert_eq!(run.outcome.result.gas().tx_gas_used(), gas_limit, "a halt burns the gas"); +} + +/* ---------- what is not marked ---------- */ + +/// A read that does not happen marks nothing, and neither does one whose opcode fails after it: +/// the frame halts, and the caller it halts back into computes on uncapped. +/// +/// - The Oracle's slot is cold and the frame cannot pay the cold access, so the Host does not load +/// it. (The block beneficiary is always warm, so its load cannot be skipped this way.) +/// - A value transfer to the empty beneficiary loads it, then cannot pay the transfer, and the +/// `CALL` fails. +#[test] +fn test_a_failed_load_caps_nothing() { + // The push and SLOAD's static 100 leave less than the 2,000 more a cold slot costs. + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); + // The child's pushes and the warm access leave less than the value transfer. + let child = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(BENEFICIARY) + .append_many([PUSH0, CALL, STOP]) + .build(); + let transfer = u32::try_from(value_transfer()).expect("the transfer's price fits a PUSH4"); + for (callee, gas) in [(ORACLE_CONTRACT_ADDRESS, 2_000_u32), (CHILD, transfer)] { + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(callee) + .push_number(gas) + .append(CALL) + .push_number(0_u8) + .append(SSTORE); + // More compute than the cap. + let parent = work(parent, 7_000).stop().build(); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_balance(CHILD, U256::from(10)) + .account_code(CONTRACT, parent.clone()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{callee}: {:?}", run.outcome.result); + let slot = run.outcome.state[&CONTRACT].storage.get(&U256::ZERO); + assert!( + slot.is_none_or(|slot| slot.present_value.is_zero()), + "{callee}: the call failed" + ); + assert!(run.outcome.gas.regular > CAP, "{callee}: the caller computed past the cap"); + assert_eq!(run.limit, None, "{callee}"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{callee}"); + } + } +} + +/// Reads the block's timestamp through the Host before every step, as a tracer might. +struct ReadsTheTimestamp; + +impl Inspector, EthInterpreter> for ReadsTheTimestamp { + fn step(&mut self, _interp: &mut Interpreter, context: &mut MegaContext) { + let _ = revm::context_interface::Host::timestamp(context); + } +} + +/// What an inspector reads through the Host is the inspector's, not the transaction's: it is +/// neither committed as the next opcode's read nor refused as one. A transaction that loads a +/// slot and computes past the cap under a tracer reading the timestamp at every step is not +/// detained, and with volatile-data access off it still loads its slot. +#[test] +fn test_an_inspectors_reads_are_not_the_transactions() { + let code = work(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]), 7_000); + let code = code.stop().build(); + for disabled in [false, true] { + let db = MemoryDatabase::default().account_code(CONTRACT, code.clone()); + let mut ctx = context(db); + if disabled { + ctx = ctx.with_volatile_access_disabled_from(0); + } + let mut evm = MegaEvm::new(ctx).with_inspector(ReadsTheTimestamp); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "disabled {disabled}: {:?}", run.outcome.result); + assert_eq!(run.limit, None, "disabled {disabled}"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "disabled {disabled}"); + assert!(run.detains, "a user's transaction is detained when it reads"); + } +} + +/* ---------- refused reads ---------- */ + +/// Records every call's result and the gas it spent, every opcode that ran, and the frame the +/// last one ran in. +#[derive(Default)] +pub(crate) struct Calls { + pub(crate) calls: Vec, + pub(crate) opcodes: Vec, + pub(crate) last_frame: Option
, +} + +pub(crate) struct CallRecord { + pub(crate) target: Address, + pub(crate) result: InstructionResult, + pub(crate) output: Bytes, + pub(crate) spent: u64, + /// The gas the caller forwarded. + pub(crate) forward: u64, + /// Whether revm ran a precompile for the call. + pub(crate) precompile_ran: bool, +} + +impl Inspector, EthInterpreter> for Calls { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + use revm::interpreter::interpreter_types::Jumps; + self.opcodes.push(interp.bytecode.opcode()); + self.last_frame = Some(interp.input.target_address); + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + let gas = outcome.result.gas; + self.calls.push(CallRecord { + target: inputs.target_address, + result: outcome.result.result, + output: outcome.result.output.clone(), + spent: gas.limit() - gas.remaining(), + forward: inputs.gas_limit, + precompile_ran: outcome.was_precompile_called, + }); + } +} + +/// While volatile-data access is off, every read is refused: the frame reverts with +/// `VolatileDataAccessDisabled(accessType)`, having paid the static gas of what ran and nothing +/// more — not a cold access, not a copy's memory, not a call's value transfer — and the refused +/// read caps nothing. +#[test] +fn test_a_refused_read_reverts_the_frame_and_charges_its_static_gas() { + // (code, the static gas of everything in it, the refused kind) + let cases: Vec<(&str, Bytes, u64, VolatileDataAccess)> = vec![ + ( + "TIMESTAMP", + BytecodeBuilder::default().append(TIMESTAMP).build(), + 2, + VolatileDataAccess::TIMESTAMP, + ), + ( + "SLOTNUM", + BytecodeBuilder::default().append(SLOTNUM).build(), + 2, + VolatileDataAccess::SLOT_NUM, + ), + ( + "BLOCKHASH", + BytecodeBuilder::default().push_number(299_u16).append(BLOCKHASH).build(), + 3 + 20, + VolatileDataAccess::BLOCK_HASH, + ), + ( + "BALANCE", + on_beneficiary(BytecodeBuilder::default(), BALANCE).build(), + 3 + 100, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "EXTCODECOPY", + BytecodeBuilder::default() + .push_number(1024_u16) + .append_many([PUSH0, PUSH0]) + .push_address(BENEFICIARY) + .append(EXTCODECOPY) + .build(), + // `EXTCODECOPY`'s static gas is EIP-8038's two warm reads, the account and its code. + 3 + 2 + 2 + 3 + 200, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "CALL with value", + BytecodeBuilder::default() + .push_number(64_u8) + .append_many([PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(BENEFICIARY) + .append(GAS) + .append(CALL) + .build(), + 3 + 2 + 2 + 2 + 3 + 3 + 2 + 100, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "SELFDESTRUCT", + on_beneficiary(BytecodeBuilder::default(), SELFDESTRUCT).build(), + 3 + 5_000, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ( + "SELFBALANCE of the beneficiary's own frame", + BytecodeBuilder::default().append(SELFBALANCE).build(), + 5, + VolatileDataAccess::BENEFICIARY_BALANCE, + ), + ]; + for gas_limit in TIERS { + for (name, code, static_gas, refused) in &cases { + // The beneficiary runs its own SELFBALANCE; every other read runs in the child. + let target = if name.starts_with("SELFBALANCE") { BENEFICIARY } else { CHILD }; + let parent = call(BytecodeBuilder::default(), CALL, target).stop().build(); + let db = MemoryDatabase::default() + .account_balance(CHILD, U256::from(10)) + .account_code(CONTRACT, parent) + .account_code(target, code.clone()); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{name}: the caller resumes"); + let record = &evm.inspector().calls[0]; + assert_eq!(record.target, target); + assert_eq!(record.result, InstructionResult::Revert, "{name}"); + assert_eq!( + record.output, + volatile_data_access_disabled_revert_data(*refused), + "{name}" + ); + assert_eq!(record.spent, *static_gas, "{name}: the static gas of what ran"); + // Only the calls a transaction to the beneficiary makes read it; the refusal did not. + if target == CHILD { + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{name}"); + assert_eq!(run.limit, None, "{name}"); + } + } + } +} + +/// The refusal names its enum variant, `BLOCKHASH`'s the hash it reads (7), as on the legacy +/// engine, although revm's instruction loads the block number first. The `SLOTNUM` refusal, access +/// type 12, one past the contract's enum, is pinned by the access-control tests and the decoder's +/// unit test. +#[test] +fn test_the_refusal_names_the_access_type() { + use mega_evm::system::{IMegaAccessControl, VolatileDataAccessType}; + for (access, variant) in [ + (VolatileDataAccess::ORACLE, VolatileDataAccessType::Oracle), + (VolatileDataAccess::BLOCK_HASH, VolatileDataAccessType::BlockHash), + (VolatileDataAccess::BLOCK_NUMBER, VolatileDataAccessType::BlockNumber), + ] { + assert_eq!( + volatile_data_access_disabled_revert_data(access), + Bytes::from( + IMegaAccessControl::VolatileDataAccessDisabled { accessType: variant }.abi_encode() + ) + ); + } + assert_eq!(VolatileDataAccessType::BlockHash as u8, 7); +} + +/// The switch holds for the frame it is off from and every frame below, and a frame above it +/// reads as usual once that frame returned. +#[test] +fn test_the_switch_is_scoped_to_its_subtree() { + let child = op(BytecodeBuilder::default(), TIMESTAMP).stop().build(); + // The top frame calls the child twice, then reads itself. + let parent = call(call(BytecodeBuilder::default(), CALL, CHILD), CALL, CHILD); + let parent = op(parent, NUMBER).stop().build(); + let db = MemoryDatabase::default().account_code(CONTRACT, parent).account_code(CHILD, child); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success()); + let results: Vec<_> = evm.inspector().calls.iter().map(|c| c.result).collect(); + assert_eq!( + results, + vec![InstructionResult::Revert, InstructionResult::Stop, InstructionResult::Stop], + "the first child is refused; the switch was its own, so the second child reads" + ); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP | VolatileDataAccess::BLOCK_NUMBER); + + // Off from the top: the transaction's own frame is refused. + let code = op(BytecodeBuilder::default(), TIMESTAMP).stop().build(); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(0)); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + match &run.outcome.result { + ExecutionResult::Revert { output, .. } => assert_eq!( + output, + &volatile_data_access_disabled_revert_data(VolatileDataAccess::TIMESTAMP) + ), + other => panic!("{other:?}"), + } + assert_eq!(run.outcome.limit_exceeded, None, "a refusal is the frame's revert, not a stop"); +} + +/* ---------- withheld gas does not leak ---------- */ + +/// An interceptor's answer carries the forwarded gas back without running a frame: the caller +/// is held to the limit as it resumes. The call forwards what it forwards without the read — the +/// withheld part of the caller's gas is part of the 63/64 — and gets all of it back, so the +/// caller holds the same gas after the call with the read and without it. +/// +/// What `remainingComputeGas()` answers is what the caller could still spend: without the read, +/// its own regular gas with the forward counted back, the gas `GAS` reads after the call plus the +/// `POP` and the `GAS` it costs to read it; after the read, the cap less what the caller spent +/// since the read — the read's `POP`, the calldata's `MSTORE` with its push and its memory, the +/// call's five pushes and its `GAS`, and the cold access to the contract: 3,031. +#[test] +fn test_an_interceptors_answer_does_not_lift_the_cap() { + let calldata = IMegaLimitControl::remainingComputeGasCall {}.abi_encode(); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let code = op(BytecodeBuilder::default(), TIMESTAMP) + .mstore(0, &calldata) + .push_number(32_u8) + .push_number(0_u8) + .push_number(4_u8) + .push_number(0_u8) + .push_address(LIMIT_CONTROL_ADDRESS) + .append(GAS) + .append(STATICCALL) + .append(POP) + .push_number(0_u8) + .append(MLOAD) + .push_number(0_u8) + .append(SSTORE); + let code = spin(code); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + // What is spent up to the call's cold access, 31 and the access itself; the answer, which + // spends nothing; the `POP`, the push, `MLOAD`, the push and a fresh, cold slot's write; + // then the loop, in a memory of one word. + let left = Charges::default() + .then(&[31 + cold_access(), 2, 3, 3, 3, sstore_static(), fresh_sstore()]) + .spin(1) + .left(CAP); + assert_stopped(&run, intrinsic, left); + + // The answer and the gas the caller holds after the call, read without the loop, after + // the read and after a push in its place. + let answer = |first: u8| { + let code = op(BytecodeBuilder::default(), first) + .mstore(0, &calldata) + .push_number(32_u8) + .push_number(0_u8) + .push_number(4_u8) + .push_number(0_u8) + .push_address(LIMIT_CONTROL_ADDRESS) + .append(GAS) + .append(STATICCALL) + .append(POP) + .append(GAS) + .push_number(32_u8) + .append(MSTORE) + .push_number(64_u8) + .push_number(0_u8) + .append(RETURN) + .build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let output = run.outcome.result.output().unwrap().clone(); + (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])) + }; + let (detained, held) = answer(TIMESTAMP); + let (undetained, held_without_the_read) = answer(PUSH0); + assert_eq!(held, held_without_the_read, "the forward came back whole"); + assert_eq!(undetained, held + U256::from(2 + 2), "the caller's own gas: POP and GAS"); + assert_eq!(detained, U256::from(CAP - 31 - cold_access()), "what the cap leaves"); + } +} + +/// A frame's return hands back what detention withheld, on success, revert and halt alike: the +/// transaction spends exactly what it spends without the read, which a child that stays within +/// the cap does not notice. +#[test] +fn test_a_frames_return_hands_back_what_was_withheld() { + // The child reads (or pushes a word, for the same two gas), computes a little, then ends. + let ends: [(&str, Append); 3] = + [("success", |c| c.stop()), ("revert", |c| c.revert()), ("halt", |c| c.append(INVALID))]; + for gas_limit in TIERS { + for (name, end) in ends { + let used = |read: u8| { + let child = end(work(op(BytecodeBuilder::default(), read), 50)).build(); + let parent = call(BytecodeBuilder::default(), CALL, CHILD).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent) + .account_code(CHILD, child); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.outcome.result.is_success(), "{name}: {:?}", run.outcome.result); + (run.outcome.result.gas().tx_gas_used(), run.limit.is_some()) + }; + let (detained, limited) = used(TIMESTAMP); + let (plain, unlimited) = used(PUSH0); + assert!(limited && !unlimited); + assert_eq!(detained, plain, "{name}: nothing withheld stays behind"); + } + } +} + +/// State and history gas are not compute, whether they come out of the reservoir or spill onto +/// regular gas: after the read, a frame spends more than the cap on fresh slots and still +/// completes, its compute within the cap and their state and history gas past it. +#[test] +fn test_state_and_history_gas_are_not_compute() { + // As many fresh slots as the cap leaves compute for, and as a gas limit below the execution + // cap pays for with a million to spare: at the spec's prices, more state gas than the cap. + let spill = fresh_write_spill(); + // A write that spills nothing, where a state byte and a record's history are both free, has + // nothing beside its compute to leave out of it. + if spill == 0 { + return; + } + let slots = (CAP / fresh_write()).min((BELOW - 1_000_000) / (fresh_write() + spill)); + assert!(slots * (fresh_write() + spill) > CAP, "counted as compute, the writes cross the cap"); + let mut code = op(BytecodeBuilder::default(), TIMESTAMP); + for slot in 1..=slots { + code = code.sstore(U256::from(slot), U256::from(1)); + } + let code = code.stop().build(); + // What the run must report, from the schedule at the prices in effect: each slot's state gas; + // the body's history bytes and one record a slot; and the compute of TIMESTAMP and its POP, + // two each, then the writes, on top of the intrinsic gas. + let state = slots * crate::salt::entry(GasId::sstore_set_state_gas()); + let history_bytes = TX_BODY_SIZE + slots * WRITE_RECORD_SIZE; + // The body and each slot's record are charges of their own, each priced on its own. + let history = history_gas(TX_BODY_SIZE).expect("the body has a price") + + slots * history_gas(WRITE_RECORD_SIZE).expect("a record has a price"); + let compute = 2 + 2 + slots * fresh_write(); + assert!(compute < CAP, "the writes' compute fits under the cap"); + // Each slot as (slot, original, present), by slot. + let written: Vec<_> = + (1..=slots).map(|slot| (U256::from(slot), U256::ZERO, U256::from(1))).collect(); + for gas_limit in TIERS { + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let case = format!("gas limit {gas_limit}"); + let contract = &run.outcome.state[&CONTRACT]; + assert!(contract.is_touched(), "{case}: the contract wrote its slots"); + let mut storage: Vec<_> = contract + .changed_storage_slots() + .map(|(slot, value)| (*slot, value.original_value, value.present_value)) + .collect(); + storage.sort_unstable(); + assert_eq!(storage, written, "{case}: each of the {slots} slots went from 0 to 1"); + let gas = run.outcome.gas; + assert_eq!(gas.state, state, "{case}: each fresh slot's state gas"); + assert_eq!(gas.history_bytes, history_bytes, "{case}: the body and a record a slot"); + assert_eq!(gas.history, history, "{case}: the history of those bytes"); + assert_eq!(gas.regular, intrinsic(gas_limit) + compute, "{case}: the compute alone"); + assert_eq!(run.limit, Some(2 + CAP), "{case}: TIMESTAMP set the limit, first"); + assert_eq!( + run.outcome.usage, + LimitUsage { data_size: history_bytes, write_records: slots }, + "{case}: one write record a slot", + ); + } +} + +/// State and history gas that spilled onto regular gas before the read are not compute either. +/// Below the execution cap there is no reservoir, so every fresh slot's state gas and its record's +/// history spill; above it the reservoir pays them. The limit is the same: the compute before the +/// read is the writes' regular gas alone. +#[test] +fn test_gas_spilled_before_the_read_is_not_compute() { + let mut code = BytecodeBuilder::default(); + for slot in 1..=100_u64 { + code = code.sstore(U256::from(slot), U256::from(1)); + } + let code = spin(op(code, TIMESTAMP)); + for gas_limit in TIERS { + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + tx(CALLER, CONTRACT, gas_limit), + ); + let left = Charges::default().then(&[2]).spin(0).left(CAP); + let limit = assert_stopped(&run, intrinsic(gas_limit), left); + // Two pushes and a fresh slot's regular gas, a hundred times, then TIMESTAMP. + assert_eq!(limit - CAP, 100 * fresh_write() + 2, "{gas_limit}"); + } +} + +/// A slot restored to its original value refills the state gas it spilled onto regular gas; the +/// spill here predates the read, and the refill must not give the frame compute past the cap. +#[test] +fn test_a_refill_after_the_read_does_not_lift_the_cap() { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + let code = op(code, TIMESTAMP).sstore(U256::from(1), U256::ZERO); + let code = spin(code); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, BELOW), + ); + // The `POP`, then the restoring write — two pushes and `SSTORE`'s static gas, the whole of a + // warm write that restores its slot's original value — then the loop. + let left = Charges::default().then(&[2, 3, 3, 100]).spin(0).left(CAP); + assert_stopped(&run, intrinsic(BELOW), left); +} + +/// A chain's caps must be below [`MAX_TX_COMPUTE_GAS`], the most compute a transaction can +/// spend. The transaction that can spend it pays the least a frame that runs code can before its +/// first instruction — a call to its own sender, which EIP-2780 charges its base cost alone, whose +/// delegate, the block beneficiary, is warm — and is detained from its start, since its recipient +/// delegates to the beneficiary; above the execution cap its body's history is the reservoir's. +/// Its frame holds exactly the most compute, so a cap there never stops it, and it runs out of its +/// own gas; a cap below what it holds by more than any one charge of its loop stops it. +#[test] +fn test_the_most_compute_a_transaction_can_spend_bounds_the_caps() { + use mega_evm::constants::MAX_TX_COMPUTE_GAS; + let intrinsic = TX_GAS_LIMIT_CAP - MAX_TX_COMPUTE_GAS; + let run_under = |cap: u64, code: Bytes| { + let db = with_delegation( + MemoryDatabase::default() + .account_code(BENEFICIARY, code) + .account_balance(DELEGATOR, U256::from(1_u64 << 60)), + DELEGATOR, + BENEFICIARY, + ); + let limits = EvmTxRuntimeLimits::default() + .with_block_env_access_compute_gas_limit(cap) + .with_oracle_access_compute_gas_limit(cap); + run_on( + &mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), + tx(DELEGATOR, DELEGATOR, ABOVE), + ) + }; + + // `GAS` answers what the frame holds, less its own 2. + let answers_gas = BytecodeBuilder::default() + .append(GAS) + .append_many([PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build(); + let run = run_under(MAX_TX_COMPUTE_GAS, answers_gas); + assert_eq!(run.limit, Some(MAX_TX_COMPUTE_GAS), "detained from the start"); + let output = run.outcome.result.output().expect("the frame returns"); + assert_eq!(U256::from_be_slice(output), U256::from(MAX_TX_COMPUTE_GAS - 2)); + assert_eq!(run.outcome.gas.regular, intrinsic + 15, "the program's 15 is its only compute"); + + let spinner = spin(BytecodeBuilder::default()); + let run = run_under(MAX_TX_COMPUTE_GAS, spinner.clone()); + assert_eq!(run.limit, Some(MAX_TX_COMPUTE_GAS)); + assert_eq!(run.outcome.limit_exceeded, None, "a cap at the most compute never stops it"); + assert!( + matches!(run.outcome.result, ExecutionResult::Halt { .. }), + "it runs out of its own gas: {:?}", + run.outcome.result + ); + + let cap = MAX_TX_COMPUTE_GAS - 10_000; + let run = run_under(cap, spinner); + assert_eq!(assert_stopped(&run, intrinsic, Charges::default().spin(0).left(cap)), cap); +} diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 69debde23..39e1dc3dc 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -1,12 +1,27 @@ //! What `MegaEvm` on Satin adds to op-revm, and what it does not. //! //! An ordinary transaction on the same `CfgEnv`, block and L1 info must produce the same result -//! through `MegaEvm` and through op-revm's `OpEvm`, down to every `ResultGas` field, the logs and -//! the resulting state. The five cases at the end are the ones that diverge on purpose — the -//! system contract interceptors, the `KeylessDeploy` overhead, the system-address transaction, -//! the account a deposit creates for its sender and a crowded SALT bucket — and they pin both -//! sides, so a divergence is never silently absorbed. Later changes (history gas, limits) add -//! their own. +//! through `MegaEvm` and through op-revm's `OpEvm` — the same state, the same logs, the same +//! refund and floor — and the same gas but for the history gas Satin charges, which op-revm has +//! no ledger for. That is the one divergence every transaction has: +//! [`assert_same_but_history`] holds each baseline case to `op-revm's total + the history ledger` +//! and to op-revm's state gas exactly, and +//! [`test_the_history_ledger_is_what_satin_adds_to_every_transaction`] pins what that ledger is +//! made of. One baseline case runs above the execution cap, because a transaction that has an +//! EIP-8037 reservoir pays its history out of it, and a charge that is given back behind the +//! ledger's back shows up nowhere else. The six cases at the end are the ones that diverge for a +//! reason of their own — the +//! system contract interceptors, keyless deployment, the system-address transaction, +//! the account a deposit creates for its sender, a crowded SALT bucket and the history ledger — +//! and they pin both sides, so a divergence is never silently absorbed. Later changes (the +//! limits) add their own. +//! +//! Every Satin transaction also reads the live system address when it is validated, which leaves +//! the `SequencerRegistry`'s account and its system-address slot in its returned state as a +//! read-only entry that op-revm's has no counterpart for. A commit skips an account nothing +//! touched, so the entry changes no committed state; each comparison of the two states takes it +//! out first ([`take_system_address_read`]), which fails when the entry is missing or is more than +//! the read, so the difference is pinned on every case rather than absorbed. //! //! SALT pricing multiplies a state gas charge by the capacity of the bucket it lands in, and //! op-revm has no SALT to read. Every baseline case runs without a SALT environment, where every @@ -14,26 +29,36 @@ //! bucket and pins what the difference is and how large. use alloy_op_evm::OpTx; -use alloy_primitives::{address, Address, TxKind, U256}; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - constants::{MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + constants::{ + COST_PER_HISTORY_BYTE, MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, SLOT_STATE_GAS, + TX_GAS_LIMIT_CAP, + }, satin_gas_params, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + test_utils::{ + note_price_guard, op_transaction, take_system_address_read, transfer_log, + zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; -use op_revm::{L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use op_revm::{constants::BASE_FEE_RECIPIENT, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; use revm::{ + bytecode::opcode::{CALL, GAS, POP, PUSH0, PUSH1}, context::{ result::{ExecResultAndState, ExecutionResult}, BlockEnv, CfgEnv, Context, ContextTr, TxEnv, }, - context_interface::cfg::gas_params::Eip2780TxInfo, + context_interface::cfg::GasId, inspector::NoOpInspector, state::EvmState, ExecuteEvm, Journal, }; -use crate::common::runs_at_measurement_prices; +use crate::common::{ + account_state_gas, body_history, history, runs_at_measurement_prices, slot_state_gas, +}; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); @@ -58,19 +83,28 @@ fn block() -> BlockEnv { } /// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the -/// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes and that `CfgEnv`. -fn run_both(db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, CfgEnv) { +/// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes — the `MegaEvm` one with its gas +/// by ledger — and that `CfgEnv`. +fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Outcome, CfgEnv) { run_both_in(db, tx, block()) } +/// Runs `tx` on `db` through op-revm's `OpEvm` alone, on the `CfgEnv` a `MegaEvm` context holds: +/// for a gas limit that is op-revm's own, which Satin, charging the body's history on top, may +/// refuse at validation. +fn run_op_alone(db: MemoryDatabase, tx: TxEnv) -> Outcome { + let (_, mut op, _) = both_evms(db, block()); + op.transact(op_transaction(tx)).unwrap() +} + /// [`run_both`] in `block`. fn run_both_in( db: MemoryDatabase, tx: TxEnv, block: BlockEnv, -) -> (Outcome, Outcome, CfgEnv) { +) -> (MegaTransactionOutcome, Outcome, CfgEnv) { let (mut mega, mut op, cfg) = both_evms(db, block); - let mega_outcome = mega.transact(OpTx(op_transaction(tx.clone()))).unwrap(); + let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); let op_outcome = op.transact(op_transaction(tx)).unwrap(); (mega_outcome, op_outcome, cfg) } @@ -91,8 +125,63 @@ fn both_evms( (MegaEvm::new(ctx), OpEvm::new(op_ctx, NoOpInspector), cfg) } +/// Asserts the two outcomes agree on everything but the history gas Satin charges: `mega` spends +/// exactly its history ledger more than `op` and nothing else moves. The whole `ResultGas` is +/// compared against op-revm's with the two fields history touches rebuilt, so a field added later +/// is covered too. +/// +/// The reservoir pays history first and the regular budget pays what it cannot, which is why the +/// reservoir left over saturates at zero rather than going negative. +/// +/// Two derived figures follow the larger total rather than staying put, and neither is a second +/// divergence. The EIP-3529 refund cap is a fraction of what the transaction spent, so a Satin +/// transaction can keep a refund op-revm has to cap — EIP-8037 state gas already raises the cap +/// the same way, which is why the refund is compared as `at least op-revm's` and pinned exactly +/// where it matters ([`test_refund_matches_op_revm`]). The receipt's gas used is the spend +/// against the EIP-7623 floor, so a floor that binds op-revm's receipt need not bind Satin's; +/// the whole `ResultGas` is still compared, with the two fields history moves rebuilt. +/// +/// The state is compared with the read of the live system address taken out, which holds because +/// these transactions carry no gas price: a priced transaction pays the extra gas out of the +/// sender's balance ([`test_fees_match_op_revm`]). +fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { + let history = mega.gas.history; + assert!(history >= body_history(0), "every Satin transaction pays for its own body"); + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(m.total_gas_spent(), o.total_gas_spent() + history, "total gas spent"); + assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); + assert_eq!(mega.gas.state, o.state_gas_spent_final(), "the state ledger"); + assert!(m.inner_refunded() >= o.inner_refunded(), "refund"); + assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); + assert_eq!( + m.reservoir_remaining(), + o.reservoir_remaining().saturating_sub(history), + "reservoir remaining" + ); + assert_eq!( + m, + &(*o) + .with_total_gas_spent(o.total_gas_spent() + history) + .with_reservoir_remaining(o.reservoir_remaining().saturating_sub(history)) + .with_refunded(m.inner_refunded()), + "ResultGas" + ); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result.output(), op.result.output(), "output"); + assert_eq!(mega.result.is_success(), op.result.is_success(), "success"); + assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); +} + +/// `state` with the read of the live system address every Satin transaction makes taken out. +fn but_the_system_address_read(state: &EvmState) -> EvmState { + let mut state = state.clone(); + take_system_address_read(&mut state); + state +} + /// Asserts the two outcomes agree field by field, then as a whole so a field added later is -/// covered too. +/// covered too. For the paths that charge no history: a system call, which the protocol pays +/// nothing for. fn assert_same(mega: &Outcome, op: &Outcome) { let (m, o) = (mega.result.gas(), op.result.gas()); assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); @@ -107,9 +196,11 @@ fn assert_same(mega: &Outcome, op: &Outcome) { assert_eq!(mega.state, op.state, "state"); } -/// Both engines run on the Satin configuration: Karst on the Satin gas schedule, EIP-8037 and -/// EIP-2780 switched on, the 200M execution cap, `MegaETH`'s code-size limits, EIP-7708 and the -/// system-call reservoir margin off. +/// Both engines run on the Satin configuration: Karst on the Satin gas schedule, EIP-8037, +/// EIP-2780 and EIP-7708 switched on, the 200M execution cap, `MegaETH`'s code-size limits, and a +/// system call's gas above 30M in its reservoir. So op-revm journals the same transfer logs, and +/// the logs of the two are compared as they are, and op-revm splits a system call's gas as Satin +/// does. fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); assert_eq!(cfg.gas_params.table(), satin_gas_params().table()); @@ -118,8 +209,9 @@ fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.tx_gas_limit_cap, Some(TX_GAS_LIMIT_CAP)); assert_eq!(cfg.limit_contract_code_size, Some(MAX_CONTRACT_SIZE)); assert_eq!(cfg.limit_contract_initcode_size, Some(MAX_INITCODE_SIZE)); - assert!(!cfg.enable_amsterdam_eip7708); - assert!(!cfg.system_call_state_gas_margin_in_reservoir); + assert!(cfg.enable_amsterdam_eip7708); + assert!(!cfg.amsterdam_eip7708_disabled); + assert!(cfg.system_call_state_gas_margin_in_reservoir); } #[test] @@ -137,8 +229,13 @@ fn test_empty_transaction_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); - assert_eq!(mega.result.gas().reservoir_remaining(), reservoir); - assert_same(&mega, &op); + assert_eq!( + mega.result.gas().reservoir_remaining(), + reservoir - mega.gas.history, + "the reservoir paid for the body", + ); + assert_eq!(op.result.gas().reservoir_remaining(), reservoir, "op-revm has nothing to pay"); + assert_same_but_history(&mega, &op); } #[test] @@ -148,7 +245,8 @@ fn test_value_transfer_matches_op_revm() { caller: CALLER, kind: TxKind::Call(CALLEE), value: U256::from(1_000), - gas_limit: 1_000_000, + // Room for the account the transfer creates, at the byte prices in effect. + gas_limit: 1_000_000 + account_state_gas(), ..Default::default() }; let (mega, op, cfg) = run_both(db, tx); @@ -156,7 +254,72 @@ fn test_value_transfer_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); assert_eq!(mega.state[&CALLEE].info.balance, U256::from(1_000)); - assert_same(&mega, &op); + assert_eq!(mega.result.logs(), [transfer_log(CALLER, CALLEE, U256::from(1_000))]); + assert_same_but_history(&mega, &op); + // The transfer log is in the receipt and costs no history: the ledger is the body and the + // recipient's record, as it is for the same transfer without the log. + assert_eq!(mega.gas.history, history(TX_BODY_SIZE) + history(WRITE_RECORD_SIZE)); +} + +/// A nested value call above the execution cap, where the reservoir is what pays the history. +/// +/// The frame-start write records are the one history charge made from outside the frame it +/// belongs to, and the frame carries its caller's reservoir, so a baseline without a reservoir +/// cannot see whether the charge survived the frame it started. This one runs the same program +/// above the cap: op-revm charges nothing for the records, and Satin's total must exceed +/// op-revm's by exactly the history ledger here too. +/// +/// The reservoir left at the end holds the child to inheriting its caller's: a caller takes back +/// the reservoir its child returns as its own, so a child handed none would hand none back, and +/// the transaction would end with no reservoir rather than what the state and history left. The +/// child here is answered without running and spends nothing, so this does not show that a child +/// can spend the whole reservoir it inherits; a child that does is held in the data-size tests. +/// +/// Rule [S4.10]. Expected values: the history ledger is `constants`, the byte table at the cost +/// per history byte; the reservoir is an identity against the run's own state and history +/// ledgers, not a figure of its own; the rest is op-revm's run (`external`). +#[test] +fn test_a_nested_value_call_with_a_reservoir_matches_op_revm() { + if runs_at_measurement_prices() { + return; + } + let inner = address!("0x5000000000000000000000000000000000000002"); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(inner) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(10_000_000)) + .account_code(CALLEE, code); + let reservoir = 100_000_000; + let tx = TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: TX_GAS_LIMIT_CAP + reservoir, + ..Default::default() + }; + let (mega, op, cfg) = run_both(db, tx); + + assert_satin_cfg(&cfg); + assert!(mega.result.is_success(), "{:?}", mega.result); + assert_eq!( + mega.gas.history, + (TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE, + "the body, the caller's account and the recipient's", + ); + assert_eq!( + mega.gas.reservoir_remaining, + reservoir - mega.gas.state - mega.gas.history, + "the reservoir paid the state and the history, and nothing came back", + ); + assert_same_but_history(&mega, &op); } #[test] @@ -180,7 +343,7 @@ fn test_sstore_matches_op_revm() { // The new slot draws the Satin schedule's state gas, which op-revm on the same schedule // draws too: the schedule is configuration, not engine behavior. assert_eq!(mega.result.gas().state_gas_spent_final(), SLOT_STATE_GAS); - assert_same(&mega, &op); + assert_same_but_history(&mega, &op); } const COINBASE: Address = address!("0x00000000000000000000000000000000000c0ffe"); @@ -195,22 +358,48 @@ fn test_fees_match_op_revm() { BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(), ); let block = BlockEnv { basefee: 7, beneficiary: COINBASE, ..block() }; + // Room for the slot the callee fills, and for the body's and the two records' history, at the + // byte prices in effect. + let gas_limit = 1_000_000 + + slot_state_gas() + + body_history(0) + + history(WRITE_RECORD_SIZE) + + history(WRITE_RECORD_SIZE); let tx = TxEnv { caller: CALLER, kind: TxKind::Call(CALLEE), value: U256::from(1_000), gas_price: 10, - gas_limit: 1_000_000, + gas_limit, ..Default::default() }; let (mega, op, _) = run_both_in(db, tx, block); assert!(mega.result.is_success()); assert!(mega.state[&COINBASE].info.balance > U256::ZERO, "the beneficiary was paid"); assert!( - mega.state[&CALLER].info.balance > U256::from(10u64.pow(18) - 10 * 1_000_000 - 1_000), + mega.state[&CALLER].info.balance > U256::from(10u64.pow(18) - 10 * gas_limit - 1_000), "the unused gas came back" ); - assert_same(&mega, &op); + assert_eq!( + mega.result.gas().total_gas_spent(), + op.result.gas().total_gas_spent() + mega.gas.history, + "the history ledger is the whole of the extra spend", + ); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + + // The extra gas is paid for at the block's prices: the sender is out all ten wei of it, the + // base fee's seven go to the fee vault and the priority fee's three to the beneficiary. + let history = U256::from(mega.gas.history); + let balance = |state: &EvmState, address: Address| state[&address].info.balance; + assert_eq!(balance(&op.state, CALLER) - balance(&mega.state, CALLER), history * U256::from(10),); + assert_eq!( + balance(&mega.state, BASE_FEE_RECIPIENT) - balance(&op.state, BASE_FEE_RECIPIENT), + history * U256::from(7), + ); + assert_eq!( + balance(&mega.state, COINBASE) - balance(&op.state, COINBASE), + history * U256::from(3), + ); } /// A storage refund is applied exactly as op-revm has it. @@ -231,19 +420,46 @@ fn test_refund_matches_op_revm() { let (mega, op, _) = run_both(db, tx); assert!(mega.result.is_success()); assert!(mega.result.gas().inner_refunded() > 0, "the clear is refunded"); - assert_same(&mega, &op); + + // The EIP-3529 cap is a fifth of what the transaction spent, so the history ledger raises it: + // op-revm has to cap the clearing refund here and Satin, spending more, keeps all of it once + // the history it pays lifts the cap past the refund, as it does at the spec's prices. EIP-8037 + // state gas raises the same cap; this is that rule applied to the third ledger. + let quotient = satin_gas_params().get(GasId::max_refund_quotient()); + let clearing = satin_gas_params().get(GasId::sstore_clearing_slot_refund()); + assert_eq!( + op.result.gas().inner_refunded(), + op.result.gas().total_gas_spent() / quotient, + "op-revm is at the cap", + ); + assert_eq!( + mega.result.gas().inner_refunded(), + clearing.min(mega.result.gas().total_gas_spent() / quotient), + "Satin keeps the whole clearing refund, where its history lifts the cap past it", + ); + assert_same_but_history(&mega, &op); } -/// A system call runs exactly as op-revm runs it. +/// A system call runs exactly as op-revm runs it, its gas above 30M in the reservoir on both: the +/// fresh slot it writes is paid out of the reservoir, and what is left of it is reported. #[test] fn test_system_call_matches_op_revm() { - use revm::handler::system_call::SystemCallEvm; + use revm::handler::{ + system_call::SystemCallEvm, SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT, + }; let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(3)).stop().build(); - let (mut mega, mut op, _) = + let (mut mega, mut op, cfg) = both_evms(MemoryDatabase::default().account_code(CALLEE, code), block()); + assert_satin_cfg(&cfg); let mega_outcome = mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); let op_outcome = op.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); assert!(mega_outcome.result.is_success()); + assert_eq!( + mega_outcome.result.gas().reservoir_remaining(), + SYSTEM_CALL_GAS_LIMIT - + SYSTEM_CALL_REGULAR_GAS_LIMIT - + satin_gas_params().get(GasId::sstore_set_state_gas()), + ); assert_same(&mega_outcome, &op_outcome); } @@ -313,19 +529,25 @@ fn test_an_intercepted_call_diverges_from_op_revm() { } /// A legacy transaction from the system address is a fee-free deposit on Satin, where op-revm -/// sees an ordinary transaction and refuses it for want of a balance to pay with. +/// sees an ordinary transaction and refuses it for want of a balance to pay with. Satin knows +/// the address from the `SequencerRegistry`, which the transaction's validation reads: its state +/// carries the read, which op-revm has no reason to make. #[test] fn test_a_system_address_transaction_diverges_from_op_revm() { - use mega_evm::system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}; + use mega_evm::system::{ + IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + }; let db = MemoryDatabase::default() - .account_code(ORACLE_CONTRACT_ADDRESS, mega_evm::system::ORACLE_CONTRACT_CODE); + .account_code(ORACLE_CONTRACT_ADDRESS, mega_evm::system::ORACLE_CONTRACT_CODE) + .sequencer_registry(MEGA_SYSTEM_ADDRESS); let tx = TxEnv { caller: MEGA_SYSTEM_ADDRESS, kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), data: alloy_sol_types::SolCall::abi_encode(&IOracle::getSlotCall { slot: U256::ZERO }) .into(), - gas_limit: 1_000_000, + // Room for the account the engine creates for the sender, at the byte prices in effect. + gas_limit: 1_000_000 + account_state_gas(), gas_price: 1_000, chain_id: Some(1), ..Default::default() @@ -342,6 +564,10 @@ fn test_a_system_address_transaction_diverges_from_op_revm() { .is_none_or(|account| account.info.balance.is_zero()), "the sender pays no fee and needed no balance", ); + assert!( + mega_outcome.state.get(&SEQUENCER_REGISTRY_ADDRESS).is_some_and(|a| !a.is_touched()), + "the read of the live system address is a read-only entry of the transaction's state", + ); let error = op.transact(op_transaction(tx)).expect_err("op-revm wants a fee"); assert!(format!("{error:?}").contains("LackOfFundForMaxFee"), "{error:?}"); @@ -357,7 +583,7 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { let tx = TxEnv { caller: sender, kind: TxKind::Call(CALLEE), - gas_limit: 1_000_000, + gas_limit: 1_000_000 + account_state_gas(), gas_price: 0, ..Default::default() }; @@ -373,8 +599,9 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { let op_outcome = op.transact(deposit(tx)).unwrap(); assert!(mega_outcome.result.is_success() && op_outcome.result.is_success()); - assert!( - mega_outcome.result.gas().state_gas_spent_final() > 0, + assert_eq!( + mega_outcome.result.gas().state_gas_spent_final(), + account_state_gas(), "Satin charges the account the deposit creates for its sender", ); assert_eq!( @@ -384,79 +611,125 @@ fn test_the_created_deposit_caller_diverges_from_op_revm() { ); } -/// A `keylessDeploy` transaction is charged the fixed overhead before its frame runs, where -/// op-revm charges nothing for it. Both engines then run the contract's bytecode and get its -/// `NotIntercepted()` revert, because the rewrite that turns the call into a deployment is not -/// here yet; the whole divergence is the overhead. +/// A `keylessDeploy` transaction is a deployment in Satin and a call to the contract's bytecode in +/// op-revm, which has no keyless dispatch: Satin deploys the canonical `CREATE2` factory at its +/// canonical address, while op-revm runs the method body, which reverts with `NotIntercepted()` +/// and deploys nothing. +/// +/// What a deployment costs beyond op-revm is pinned charge by charge in the system tests. Here the +/// divergence of a call the rules refuse is pinned exactly: Satin charges the fixed overhead, +/// runs no bytecode and keeps nothing else, so it spends what op-revm spends on the same calldata +/// sent to an account with no code, plus the overhead and the history ledger. #[test] -fn test_the_keyless_deploy_overhead_diverges_from_op_revm() { - use alloy_primitives::Bytes; +fn test_a_keyless_deployment_diverges_from_op_revm() { use alloy_sol_types::{SolCall, SolError}; use mega_evm::system::keyless::{ + tests::{CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_TX}, IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_OVERHEAD_GAS, }; let db = MemoryDatabase::default() .account_balance(CALLER, U256::from(10u64.pow(18))) .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); - let data: Bytes = IKeylessDeploy::keylessDeployCall { - keylessDeploymentTransaction: Bytes::from_static(b"a transaction"), - gasLimitOverride: U256::from(1_000_000), - } - .abi_encode() - .into(); - let tx = TxEnv { + let keyless_deploy = |tx: &[u8]| -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::copy_from_slice(tx), + gasLimitOverride: U256::from(1_000_000), + } + .abi_encode() + .into() + }; + let call = |to: Address, data: Bytes| TxEnv { caller: CALLER, - kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), - data: data.clone(), - gas_limit: 1_000_000, + kind: TxKind::Call(to), + data, + gas_limit: 10_000_000, ..Default::default() }; - let (mega, op, cfg) = run_both(db, tx); + let (mega, op, cfg) = + run_both(db.clone(), call(KEYLESS_DEPLOY_ADDRESS, keyless_deploy(CREATE2_FACTORY_TX))); assert_satin_cfg(&cfg); - let revert_data = Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR); + let output = mega.result.output().cloned().unwrap_or_default(); + let deployed = IKeylessDeploy::keylessDeployCall::abi_decode_returns(&output).unwrap(); + assert_eq!(deployed.deployedAddress, CREATE2_FACTORY_CONTRACT, "Satin deploys"); assert_eq!( - mega.result.output().cloned().unwrap_or_default(), - revert_data, - "the bytecode runs after the charge", + mega.state.get(&CREATE2_FACTORY_CONTRACT).map(|account| account.info.code_hash), + Some(CREATE2_FACTORY_CODE_HASH), + ); + assert_eq!( + op.result.output().cloned().unwrap_or_default(), + Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR), + "op-revm runs the method body", + ); + assert!( + op.state.get(&CREATE2_FACTORY_CONTRACT).is_none_or(|account| account.info.is_empty()), + "op-revm deploys nothing", ); - assert_eq!(op.result.output().cloned().unwrap_or_default(), revert_data); - // What each transaction spent, not what its receipt reports: op-revm spends less than the - // EIP-7623 calldata floor here, so its receipt is lifted to the floor and Satin's is not. - // The two run the same bytecode on the same input, so the whole difference is the charge. - let charged = mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(); + // A call the rules refuse: bytes that are not a signed transaction. + let refused = keyless_deploy(b"a transaction"); + let (mut mega_evm, mut op_evm, _) = both_evms(db, block()); + let mega = mega_evm + .execute_transaction(OpTx(op_transaction(call(KEYLESS_DEPLOY_ADDRESS, refused.clone())))) + .unwrap(); + let op = op_evm.transact(op_transaction(call(CALLEE, refused))).unwrap(); + assert_eq!( + mega.result.output().cloned().unwrap_or_default(), + Bytes::from_static(&IKeylessDeploy::MalformedEncoding::SELECTOR), + ); + assert!(op.result.is_success(), "the reference call runs no code"); + // What each transaction spent, not what its receipt reports: the EIP-7623 calldata floor + // lifts op-revm's receipt above what it spent. + let charged = + mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent() - mega.gas.history; assert_eq!(charged, KEYLESS_DEPLOY_OVERHEAD_GAS, "the divergence is the overhead, exactly"); +} - // Which floor, exactly: the one this transaction's own calldata buys, computed by revm from - // the schedule both engines run on. Satin is above it and reports what it spent; op-revm is - // below it and reports the floor, so the receipts differ by less than the charge. - let floor = cfg - .gas_params - .initial_tx_gas( - &data, - false, - 0, - 0, - 0, - Some(Eip2780TxInfo { value: U256::ZERO, is_self_transfer: false }), - ) - .floor_gas(); +/// Where Satin leaves op-revm on every transaction: the history gas of the bytes it appends to +/// the chain. +/// +/// op-revm charges nothing for them, so Satin's total is op-revm's plus the history ledger, to +/// the gas — the divergence [`assert_same_but_history`] holds every baseline case to. This pins +/// what the ledger is made of: an empty call carries its body and nothing else, and a byte of +/// calldata adds a byte of history on top of the token rate both engines charge for it. +#[test] +fn test_the_history_ledger_is_what_satin_adds_to_every_transaction() { + if runs_at_measurement_prices() { + return; + } + let tx = |data: Bytes| TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + data, + gas_limit: 1_000_000, + ..Default::default() + }; + let (empty, op_empty, cfg) = run_both(MemoryDatabase::default(), tx(Bytes::new())); + let (with_data, op_with_data) = { + let (m, o, _) = run_both(MemoryDatabase::default(), tx(vec![0xab_u8; 100].into())); + (m, o) + }; + + assert_satin_cfg(&cfg); + assert_eq!(empty.gas.history, TX_BODY_SIZE * COST_PER_HISTORY_BYTE, "the body alone"); assert_eq!( - mega.result.gas().tx_gas_used(), - mega.result.gas().total_gas_spent(), - "Satin spends past the floor, so its receipt is its own spend", + with_data.gas.history, + (TX_BODY_SIZE + 100) * COST_PER_HISTORY_BYTE, + "the body and one history byte per calldata byte", ); + assert_eq!(empty.gas.state, 0, "the body is history, not state"); + assert_eq!(empty.result.gas().state_gas_spent_final(), 0); assert_eq!( - op.result.gas().tx_gas_used(), - floor, - "op-revm spends below the floor, so its receipt is the floor", + with_data.result.gas().total_gas_spent() - op_with_data.result.gas().total_gas_spent(), + with_data.gas.history, ); - assert!( - mega.result.gas().tx_gas_used() - op.result.gas().tx_gas_used() < charged, - "the floor lifts the cheaper receipt, so the receipts differ by less than the charge", + assert_eq!( + empty.result.gas().total_gas_spent() - op_empty.result.gas().total_gas_spent(), + empty.gas.history, ); + assert_same_but_history(&empty, &op_empty); + assert_same_but_history(&with_data, &op_with_data); } /// Where Satin leaves op-revm on purpose: a state gas charge in a crowded SALT bucket. @@ -486,7 +759,7 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { let envs = crowded_slot(minimal_envs(), CALLEE, U256::ZERO, MULTIPLIER); let ctx = salt_context(db.clone(), envs).with_block(block()); let cfg = ctx.cfg().clone(); - let mega = MegaEvm::new(ctx).transact(OpTx(op_transaction(tx.clone()))).unwrap(); + let mega = MegaEvm::new(ctx).execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); let op_ctx = OpContext::new(db, OpSpecId::KARST) .with_cfg(cfg.clone()) .with_block(block()) @@ -500,14 +773,131 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { assert_eq!(op.result.gas().state_gas_spent_final(), SLOT_STATE_GAS); assert_eq!(mega.result.gas().state_gas_spent_final(), SLOT_STATE_GAS * MULTIPLIER); assert_eq!( - mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent(), + mega.result.gas().total_gas_spent() - op.result.gas().total_gas_spent() - mega.gas.history, SLOT_STATE_GAS * (MULTIPLIER - 1), - "the extra state gas is the whole of the extra spend", + "beside the history ledger, the extra state gas is the whole of the extra spend", ); // Everything the transaction did is the same: the fees are zero here, so the multiplier // moves the gas ledgers and nothing else. assert_eq!(mega.result.logs(), op.result.logs(), "logs"); assert_eq!(mega.result.output(), op.result.output(), "output"); - assert_eq!(mega.state, op.state, "state"); + assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); +} + +/// A transaction that runs out of gas in the runtime gas phase, before its first frame — here on +/// EIP-2780's charge for the account its value creates — burns its whole gas limit on both +/// engines and keeps nothing but its sender's nonce: no reservoir comes back from a transaction +/// below the execution cap, and Satin's history ledger reads the body, the record its frame +/// would have made given back. +/// +/// Each engine runs one gas short of what the same transfer spends on it when it succeeds, so +/// each falls short on the last charge of the phase at any byte price: op-revm has no history to +/// charge and needs less by exactly the body's history and the record's, each a charge priced on +/// its own — nothing where a history byte costs nothing, or so little that both round to nothing. +/// Where a state byte costs nothing there is no such charge on op-revm, and the case returns +/// early. +#[test] +fn test_an_out_of_gas_before_the_first_frame_matches_op_revm() { + if crate::common::state_is_free() { + return; + } + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let transfer = |gas_limit| TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + value: U256::from(1_000), + gas_limit, + ..Default::default() + }; + let (mega_success, op_success, _) = run_both(db(), transfer(1_000_000 + account_state_gas())); + assert!(mega_success.result.is_success() && op_success.result.is_success()); + let mega_limit = mega_success.result.gas().total_gas_spent() - 1; + let op_limit = op_success.result.gas().total_gas_spent() - 1; + assert_eq!( + mega_limit - op_limit, + body_history(0) + history(WRITE_RECORD_SIZE), + "Satin charges the body's and the record's history on top", + ); + + let (mega, _, cfg) = run_both(db(), transfer(mega_limit)); + let op = run_op_alone(db(), transfer(op_limit)); + assert_satin_cfg(&cfg); + for (engine, result, gas_limit) in + [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] + { + assert!(result.is_halt(), "{engine}: {result:?}"); + let gas = result.gas(); + assert_eq!(gas.total_gas_spent(), gas_limit, "{engine}: the whole gas limit burns"); + assert_eq!(gas.reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + assert_eq!(gas.tx_gas_used(), gas_limit, "{engine}: the receipt bills the gas limit"); + } + assert_eq!(mega.gas.history, body_history(0), "the history ledger reads the body"); + assert_eq!(mega.gas.history_bytes, TX_BODY_SIZE); + assert_eq!(mega.gas.state, 0, "the account was not created"); + // With no gas price the fee is nothing, so the two states are the same: the sender's nonce + // moved and nothing else. + assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); + assert_eq!(mega.state[&CALLER].info.nonce, 1); +} + +/// A creation transaction that runs out of gas in the runtime gas phase bumps its sender's nonce +/// on both engines, so an included out-of-gas creation cannot be replayed, and burns its whole gas +/// limit. Satin runs out on the history of the record its own frame would make, the one charge of +/// the phase it adds; op-revm on EIP-2780's charge for the created account, its last. +/// +/// Where a record's history is nothing — a history byte that costs nothing, or so little that a +/// record rounds to nothing — Satin's phase has nothing of its own left to charge, and the case +/// returns early with a note. +#[test] +fn test_an_out_of_gas_creation_before_the_first_frame_matches_op_revm() { + if crate::common::state_is_free() { + return; + } + if history(WRITE_RECORD_SIZE) == 0 { + note_price_guard("a write record's history rounds to nothing at these prices"); + return; + } + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); + let init_code = BytecodeBuilder::default().stop().build(); + let creation = |gas_limit| TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: init_code.clone(), + gas_limit, + ..Default::default() + }; + // A creation whose init code stops spends its intrinsic gas and nothing else on the regular + // ledger; the body and the created account's record are its history, the account its state. + let (success, op_success, _) = run_both(db(), creation(1_000_000 + account_state_gas())); + assert!(success.result.is_success() && op_success.result.is_success()); + let intrinsic = success.gas.regular; + let mega_limit = + intrinsic + body_history(init_code.len() as u64) + history(WRITE_RECORD_SIZE) - 1; + let op_limit = op_success.result.gas().total_gas_spent() - 1; + + let (mega, _, cfg) = run_both(db(), creation(mega_limit)); + let op = run_op_alone(db(), creation(op_limit)); + assert_satin_cfg(&cfg); + for (engine, result, gas_limit) in + [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] + { + assert!(result.is_halt(), "{engine}: {result:?}"); + assert_eq!( + result.gas().total_gas_spent(), + gas_limit, + "{engine}: the whole gas limit burns" + ); + assert_eq!(result.gas().reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + } + assert_eq!(mega.gas.history, body_history(init_code.len() as u64), "the ledger reads the body"); + // op-revm reaches the charge for the created account and loads its address; Satin falls short + // before it, so only the sender is compared: its nonce moved and nothing else. + assert_eq!(mega.state[&CALLER], op.state[&CALLER], "the sender's account"); + assert_eq!(mega.state[&CALLER].info.nonce, 1, "the sender's nonce moves by one"); + assert!( + mega.state.values().all(|account| !account.is_created()), + "nothing was created: {:?}", + mega.state.keys().collect::>() + ); } diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs new file mode 100644 index 000000000..34fed03a6 --- /dev/null +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -0,0 +1,286 @@ +//! A deposit op-revm fails reports the failure, and keeps what it counted. +//! +//! op-revm answers a deposit's transaction error with a `FailedDeposit` halt that bills the whole +//! gas limit and discards everything the deposit did, and validation's refusal of a body over the +//! data-size limit is one such error. The halt is what the outcome reports. What the deposit +//! counted stands: its body, and the Oracle hints it forwarded before it halted, which have left +//! the machine as they have for any other transaction that halts. + +use core::convert::Infallible; + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, ExternalEnvs, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, TestExternalEnvs, TX_BODY_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, INVALID, POP}, + context::{result::ExecutionResult, TxEnv}, +}; + +use crate::common::{account_state_gas, block, call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000f00000"); +const CALLEE: Address = address!("0000000000000000000000000000000000f00001"); + +/// A deposit of `data` to the callee, as a system transaction when `system`, which Regolith +/// refuses. +fn deposit(data: Bytes, system: bool) -> MegaTransaction { + let mut tx = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + data, + gas_limit: 100_000, + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x22); + tx.deposit.is_system_transaction = system; + OpTx(tx) +} + +/// A system deposit whose body crosses the data-size limit is refused by the inherited rules, +/// which refuse every system deposit under Regolith, and op-revm includes it as a failed deposit: +/// the outcome reports the failure, no stop, and the body as what was kept. +#[test] +fn test_a_system_deposit_over_the_limit_reports_the_failed_deposit() { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); + let mut evm = MegaEvm::new(context(db)).with_tx_runtime_limits(limits); + let tx = deposit(Bytes::from_static(&[0xab]), true); + let body = mega_evm::transaction_body_bytes(&tx); + assert!(body > TX_BODY_SIZE, "the body crosses the limit"); + + let outcome = evm.execute_transaction(tx).expect("the deposit is included"); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.gas.gas_used, 100_000, "a failed deposit bills its gas limit"); + assert_eq!(outcome.limit_exceeded, None, "the halt is what the deposit reports"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.state[&CALLER].info.nonce, 1, "a failed deposit bumps its sender's nonce"); +} + +/// A deposit whose body exceeds the data-size limit fails validation, as any transaction with that +/// body does, and op-revm includes it as a failed deposit: it bills its gas limit, bumps its +/// sender's nonce, runs nothing, reports no stop, and keeps its body as its data size. +/// +/// At the spec's limit no deposit carries such a body and passes the gas checks, the floor alone +/// being past the execution cap; under a limit one byte below its body, a user deposit whose gas +/// covers it is refused for the body itself. +#[test] +fn test_a_deposit_whose_body_is_over_the_limit_is_a_failed_deposit() { + let spec_limit = + mega_evm::ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits.tx_data_size_limit; + let spec_body = vec![0xab; (spec_limit - TX_BODY_SIZE + 1) as usize]; + let lowered = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); + let cases = [ + ("the spec's limit", Bytes::from(spec_body), None), + ("a lowered limit", Bytes::from_static(&[0xab]), Some(lowered)), + ]; + for (case, data, limits) in cases { + let tx = deposit(data, false); + let body = mega_evm::transaction_body_bytes(&tx); + let limit = limits.map_or(spec_limit, |limits| limits.tx_data_size_limit); + assert_eq!(body, limit + 1, "{case}"); + + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1)); + let mut ctx = context(db); + if let Some(limits) = limits { + ctx = ctx.with_tx_runtime_limits(limits); + } + let outcome = MegaEvm::new(ctx).execute_transaction(tx).expect("the deposit is included"); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{case}: {:?}", + outcome.result + ); + assert_eq!(outcome.gas.gas_used, 100_000, "{case}: a failed deposit bills its gas limit"); + assert_eq!(outcome.limit_exceeded, None, "{case}: the failure is what it reports"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!(outcome.state[&CALLER].info.nonce, 1, "{case}: the sender's nonce is bumped"); + } +} + +/// A sender that does not exist before its deposit, which the deposit creates. +const ABSENT: Address = address!("0000000000000000000000000000000000f00002"); + +/// A deposit whose body crosses the data-size limit is a failed deposit at every gas limit, +/// whether or not it would also fail another check, and whether or not its gas could pay for the +/// account it creates for its caller: validation refuses it before anything runs or is charged. +/// +/// The failed deposit bills its whole gas limit as regular gas and nothing on the state or history +/// ledgers — the caller account a failed deposit creates carries no state gas — bumps its +/// sender's nonce, credits its mint, reports no stop, and keeps its body as its data size. Every +/// deposit here calls an account without code, with no value and no calldata, so its intrinsic gas +/// is 15,000: EIP-2780's base of 12,000 and 3,000 for the recipient; the data-size limit is one +/// byte below the 310-byte body. +/// +/// The rows: +/// +/// - a user deposit whose gas limit is one below its intrinsic gas, and one whose gas limit covers +/// it; +/// - a system deposit, which the inherited rules refuse under Regolith as well, with a gas limit +/// below its intrinsic gas and from an absent sender with 10,000,000; +/// - a user deposit from an absent sender whose gas limit covers its intrinsic gas and all but one +/// gas of its caller's account, and one whose gas limit covers that account too. +/// +/// Rules: [S10.15], [S11], [S5], [S4], [S21.5], [S21.7], [S5.12]. Independence: constants — the +/// intrinsic gas and the body are hand arithmetic from EIP-2780 and `TX_BODY_SIZE`; the caller +/// account's state gas is the schedule's entry at the price in effect. +#[test] +fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { + const INTRINSIC: u64 = 12_000 + 3_000; + const MINT: u64 = 7; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); + let body = LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }; + let run = |sender: Address, gas_limit: u64, system: bool| { + let mut tx = op_transaction(TxEnv { + caller: sender, + kind: TxKind::Call(CALLEE), + gas_limit, + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x22); + tx.deposit.mint = Some(u128::from(MINT)); + tx.deposit.is_system_transaction = system; + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1)); + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(OpTx(tx)) + .expect("the deposit is included") + }; + + // (row, a system deposit, the sender, its balance before, the gas limit) + let rows = [ + ("a user deposit short of its intrinsic gas", false, CALLER, 1, INTRINSIC - 1), + ("a user deposit that covers it", false, CALLER, 1, INTRINSIC), + ("a system deposit", true, CALLER, 1, INTRINSIC - 1), + ("a system deposit from an absent sender", true, ABSENT, 0, 10_000_000), + ( + "a user deposit short of its caller's account", + false, + ABSENT, + 0, + INTRINSIC + account_state_gas() - 1, + ), + ("a user deposit that covers it", false, ABSENT, 0, INTRINSIC + account_state_gas()), + ]; + for (row, system, sender, balance_before, gas_limit) in rows { + let outcome = run(sender, gas_limit, system); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{row}: {:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None, "{row}: no stop is reported"); + assert_eq!(outcome.gas.gas_used, gas_limit, "{row}: the whole gas limit"); + assert_eq!( + (outcome.gas.regular, outcome.gas.state, outcome.gas.history), + (gas_limit, 0, 0), + "{row}: all of it regular gas" + ); + assert_eq!(outcome.usage, body, "{row}: the body stays counted"); + let sender = &outcome.state[&sender].info; + assert_eq!(sender.nonce, 1, "{row}: the sender's nonce is bumped"); + assert_eq!(sender.balance, U256::from(balance_before + MINT), "{row}: the mint"); + } +} + +/// Runs `tx` against a callee that sends the Oracle a hint of `payload` and then halts on +/// `INVALID`, and returns the outcome with the number of hints the oracle service received. +fn run_hint_then_halt(tx: MegaTransaction, payload: &[u8]) -> (MegaTransactionOutcome, usize) { + let code = BytecodeBuilder::default() + .mstore(0, payload) + .push_number(0_u8) // retSize + .push_number(0_u8) // retOffset + .push_number(payload.len() as u64) // argsSize + .push_number(0_u8) // argsOffset + .push_number(0_u8) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(100_000_u32) + .append_many([CALL, POP, INVALID]) + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1)) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .account_code(CALLEE, code); + let envs = TestExternalEnvs::::new(); + let ctx = MegaContext::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs::from(envs.clone()), + ) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let outcome = MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is included"); + (outcome, envs.recorded_hints().len()) +} + +/// A deposit that forwards an Oracle hint and then halts is a failed deposit that keeps its body +/// and the hint's payload as data size: the hint reached the oracle service before the halt, and +/// nothing takes it back. The same program reached by an ordinary transaction halts and keeps the +/// same bytes. +#[test] +fn test_a_failed_deposit_keeps_the_hints_it_forwarded() { + let payload = IOracle::sendHintCall { + topic: B256::repeat_byte(0x7a), + data: Bytes::from_static(b"a hint sent before the halt"), + } + .abi_encode(); + let mut deposit = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit: 1_000_000, + ..Default::default() + }); + deposit.deposit.source_hash = B256::repeat_byte(0x22); + let deposit = OpTx(deposit); + let kept = LimitUsage { + data_size: mega_evm::transaction_body_bytes(&deposit) + payload.len() as u64, + write_records: 0, + }; + + let (outcome, hints) = run_hint_then_halt(deposit, &payload); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(hints, 1, "the hint reached the oracle service before the halt"); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.usage, kept, "the body and the forwarded hint stay counted"); + + let ordinary = call(CALLER, CALLEE, U256::ZERO, 1_000_000); + assert_eq!( + mega_evm::transaction_body_bytes(&ordinary), + kept.data_size - payload.len() as u64, + "the two transactions have the same body" + ); + let (outcome, hints) = run_hint_then_halt(ordinary, &payload); + assert!( + matches!(&outcome.result, ExecutionResult::Halt { reason, .. } + if *reason != MegaHaltReason::FailedDeposit), + "{:?}", + outcome.result + ); + assert_eq!(hints, 1); + assert_eq!(outcome.usage, kept, "an ordinary transaction that halts keeps the same bytes"); +} diff --git a/crates/mega-evm/tests/satin/floor_exempt.rs b/crates/mega-evm/tests/satin/floor_exempt.rs new file mode 100644 index 000000000..863a6691d --- /dev/null +++ b/crates/mega-evm/tests/satin/floor_exempt.rs @@ -0,0 +1,216 @@ +//! The EIP-7623 calldata floor of a transaction exempt from history gas. +//! +//! At the spec's prices a transaction that pays history gas pays every byte it carries at 88 gas, +//! above the floor's 64, so the floor never decides what it uses. A transaction exempt from history +//! gas — a deposit, and the protocol's own — pays its calldata only at the intrinsic token rate, +//! four gas a zero byte and sixteen a non-zero one, so once its calldata outweighs what it runs and +//! the state it adds, its gas used is the floor. +//! +//! The floor's base is the transaction's own EIP-2780 base without its calldata, access-list, +//! authorization and initcode costs: 12,000 for a transfer to the sender itself, 15,000 for a call +//! to another account without value, 21,000 with value, 24,000 for a creation. On top of it, every +//! byte of calldata costs 64 gas, zero or not, a creation's initcode included. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + system::{MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS}, + test_utils::{op_transaction, MemoryDatabase}, + MegaEvm, MegaTransaction, +}; +use revm::context::TxEnv; + +use crate::common::{account_state_gas, context}; + +/// A depositor whose own code is [`SINK`], so that a transfer to itself runs it. +const DEPOSITOR: Address = address!("0000000000000000000000000000000000f10000"); +/// A contract whose code is [`SINK`]. +const TARGET: Address = address!("0000000000000000000000000000000000f10001"); + +/// `PUSH2 0x7fe0; MLOAD; POP; STOP`: a load of the word at 32,736, which expands the frame's +/// memory to 1,024 words. Six bytes, five of them non-zero. +const SINK: [u8; 6] = [0x61, 0x7f, 0xe0, 0x51, 0x50, 0x00]; + +/// What [`SINK`] costs, all of it regular gas: `PUSH2` 3, `MLOAD` 3 and the memory of 1,024 words, +/// `3 × 1,024 + 1,024² / 512`, then `POP` 2; `STOP` costs nothing. +const SINK_GAS: u64 = 3 + 3 + (3 * 1_024 + 1_024 * 1_024 / 512) + 2; + +/// The calldata of every case: [`SINK`] padded with zero bytes to `len` bytes. A creation runs it +/// as its initcode, which stops on [`SINK`]'s `STOP` and deploys nothing; a call ignores it. +fn calldata(len: u64) -> Bytes { + let mut data = SINK.to_vec(); + data.resize(len as usize, 0); + data.into() +} + +/// The intrinsic regular gas of `len` bytes of [`calldata`]: sixteen for each of [`SINK`]'s five +/// non-zero bytes and four for each zero byte. +const fn calldata_gas(len: u64) -> u64 { + 16 * 5 + 4 * (len - 5) +} + +/// What a transaction is, as far as the floor and the exemption are concerned. +#[derive(Clone, Copy, Debug)] +enum Class { + /// A deposit a user's L1 transaction made: history-exempt, priced by bucket. + UserDeposit, + /// A Mega System Transaction: a legacy call from the live system address to the Oracle, which + /// the engine promotes to a deposit. + MegaSystemTransaction, + /// The promoted form of the protocol's own transaction: a deposit carrying the promotion's + /// source hash, which is the protocol's whoever its caller. A Mega System Transaction can only + /// be a call to the Oracle; this is the shape a self-transfer or a creation of the protocol's + /// takes. + SystemDeposit, +} + +/// What the transaction does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Shape { + /// A call without value to another account, which runs [`SINK`]. + Call, + /// The same call carrying one wei. + ValueCall, + /// One wei sent to the sender itself, whose code is [`SINK`]. + SelfTransfer, + /// A creation whose initcode is the calldata. + Creation, +} + +impl Shape { + /// The floor's base: the shape's EIP-2780 base without its calldata and initcode costs. + const fn floor_base(self) -> u64 { + match self { + Self::SelfTransfer => 12_000, + Self::Call => 12_000 + 3_000, + Self::ValueCall => 12_000 + 3_000 + 6_000, + Self::Creation => 12_000 + 12_000, + } + } + + /// What a transaction of this shape carrying `len` bytes spends, by hand: its EIP-2780 + /// intrinsic regular gas — the base, plus EIP-3860's two gas per initcode word for a creation, + /// plus the calldata — then [`SINK`], and for a creation the created account's state gas. An + /// exempt transaction pays no history gas, so that is all of it. + fn spend(self, len: u64) -> u64 { + let initcode_words = if self == Self::Creation { len.div_ceil(32) } else { 0 }; + let created_account = if self == Self::Creation { account_state_gas() } else { 0 }; + self.floor_base() + 2 * initcode_words + calldata_gas(len) + SINK_GAS + created_account + } +} + +/// The database every case runs on: the depositor and the target run [`SINK`], the Oracle's +/// address holds it too — a Mega System Transaction is told by its own fields and the registry's +/// word, not by the code at the Oracle — and every sender exists and can send one wei. +fn db() -> MemoryDatabase { + MemoryDatabase::default() + .account_code(DEPOSITOR, Bytes::from_static(&SINK)) + .account_balance(DEPOSITOR, U256::from(1_000)) + .account_code(TARGET, Bytes::from_static(&SINK)) + .account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&SINK)) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1_000)) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) +} + +/// The transaction of `class` and `shape` carrying `len` bytes, with `gas_limit`. +fn transaction(class: Class, shape: Shape, len: u64, gas_limit: u64) -> MegaTransaction { + let (caller, to) = match class { + Class::MegaSystemTransaction => (MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS), + Class::UserDeposit | Class::SystemDeposit => (DEPOSITOR, TARGET), + }; + let (kind, value) = match shape { + Shape::Call => (TxKind::Call(to), U256::ZERO), + Shape::ValueCall => (TxKind::Call(to), U256::from(1)), + Shape::SelfTransfer => (TxKind::Call(caller), U256::from(1)), + Shape::Creation => (TxKind::Create, U256::ZERO), + }; + let mut tx = op_transaction(TxEnv { + caller, + kind, + value, + data: calldata(len), + gas_limit, + ..Default::default() + }); + match class { + Class::UserDeposit => tx.deposit.source_hash = B256::repeat_byte(0x11), + Class::SystemDeposit => tx.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, + Class::MegaSystemTransaction => {} + } + OpTx(tx) +} + +/// Calldata short enough that the floor stays below the spend: 32 bytes put 64 × 32 − (16 × 5 + +/// 4 × 27) = 1,860 gas more in the floor than in the intrinsic charge, under what [`SINK`] costs. +const SHORT: u64 = 32; + +/// Calldata long enough that the floor binds: 40,000 bytes put 2,560,000 gas in the floor, more +/// than the intrinsic charge, [`SINK`] and a created account at any byte price the grid reaches +/// together. +const LONG: u64 = 40_000; + +/// An exempt transaction's gas used is the larger of what it spent and its floor, and both are +/// the spec's figures: the floor is the shape's base — 12,000 for a transfer to the sender itself, +/// 15,000 for a call without value, 21,000 with value, 24,000 for a creation — plus 64 gas a byte +/// of calldata, zero or not, a creation's initcode included; the spend is the intrinsic regular +/// gas, what the transaction ran and the state it added, and no history. +/// +/// Each case runs with [`SHORT`] calldata, where the spend is above the floor and is the gas used, +/// and with [`LONG`] calldata, where the floor binds and is the gas used. Each runs below the +/// execution cap and above it: where the floor binds it is drawn from the whole gas limit, the +/// reservoir included, so the gas used is the floor at either gas limit. The figure the block +/// counts on its execution ledger is the regular ledger at least the floor. +/// +/// Rules: [S4.19], [S4.22], [S4.23], [S5.5], [S7.34], [S7.36], [S7.37], [S5], [S7]. Independence: +/// independent — the floor's base and rate, the intrinsic costs and the memory the code expands +/// are written out; the created account's state gas is the schedule's entry at the price in +/// effect. +#[test] +fn test_the_floor_of_an_exempt_transaction() { + use Class::{MegaSystemTransaction, SystemDeposit, UserDeposit}; + use Shape::{Call, Creation, SelfTransfer, ValueCall}; + + let cases: [(Class, Shape); 10] = [ + (UserDeposit, Call), + (UserDeposit, ValueCall), + (UserDeposit, SelfTransfer), + (UserDeposit, Creation), + (MegaSystemTransaction, Call), + (MegaSystemTransaction, ValueCall), + (SystemDeposit, Call), + (SystemDeposit, ValueCall), + (SystemDeposit, SelfTransfer), + (SystemDeposit, Creation), + ]; + for gas_limit in [10_000_000, TX_GAS_LIMIT_CAP + 100_000_000] { + for (class, shape) in cases { + for (len, binds) in [(SHORT, false), (LONG, true)] { + let case = format!("{class:?}, {shape:?}, {len} bytes, gas limit {gas_limit}"); + let tx = transaction(class, shape, len, gas_limit); + let outcome = MegaEvm::new(context(db())) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let gas = outcome.gas; + + let floor = shape.floor_base() + 64 * len; + let spend = shape.spend(len); + assert_eq!(gas.floor, floor, "{case}: the floor"); + assert_eq!(binds, floor > spend, "{case}: whether the floor binds"); + assert_eq!(gas.history, 0, "{case}: an exempt transaction pays no history"); + assert_eq!( + gas.regular + gas.state, + spend, + "{case}: what it spent, the intrinsic charge, the code and the state" + ); + assert_eq!(gas.gas_used, spend.max(floor), "{case}: the gas used"); + assert_eq!( + gas.block_execution_gas(), + gas.regular.max(floor), + "{case}: what the block counts on its execution ledger" + ); + } + } + } +} diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs new file mode 100644 index 000000000..4bf3bce20 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -0,0 +1,983 @@ +//! The history bytes a transaction appended, reported beside the history gas it paid. +//! +//! Every history charge is a byte count at the cost per history byte, and the transaction reports +//! the count as well as the gas. Without a history allowance the two are a price apart. A value +//! transfer's allowance pays for its callee's first event before the callee's gas does, and what +//! it pays for is on no gas ledger, so the byte count is larger than the gas says — by exactly +//! what the allowances paid. +//! +//! Every case runs twice: below the execution cap, where the reservoir is empty and every charge +//! spills onto regular gas, and above it, where the reservoir pays first. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{COST_PER_HISTORY_BYTE, MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + }, + test_utils::{is_transfer_log, op_transaction, BytecodeBuilder, MemoryDatabase}, + untouched_create_gas, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaTransaction, + MegaTransactionOutcome, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLDATASIZE, CREATE, DELEGATECALL, GAS, JUMPDEST, JUMPI, LOG0, MSTORE8, POP, PUSH0, + PUSH1, RETURN, REVERT, SELFDESTRUCT, + }, + context::{ + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + interpreter::{ + interpreter::EthInterpreter, CreateInputs, CreateOutcome, InstructionResult, + InterpreterResult, + }, + Inspector, +}; + +use crate::common::{call, call_with_data, context, create, execute, runs_at_measurement_prices}; + +const CALLER: Address = address!("0000000000000000000000000000000000a00000"); +const CALLEE: Address = address!("0000000000000000000000000000000000a00001"); +const CHILD: Address = address!("0000000000000000000000000000000000a00002"); +const RECEIVER: Address = address!("0000000000000000000000000000000000a00003"); +const OTHER_RECEIVER: Address = address!("0000000000000000000000000000000000a00004"); +/// An account nothing has touched. +const FRESH: Address = address!("0000000000000000000000000000000000a00005"); +/// An account that exists and has no code. +const PAYEE: Address = address!("0000000000000000000000000000000000a00006"); + +const CPHB: u64 = COST_PER_HISTORY_BYTE; + +/// The reservoir the runs above the execution cap carry. +const RESERVOIR: u64 = 100_000_000; + +/// The two gas limits every case runs at: below the execution cap and above it. +const GAS_LIMITS: [u64; 2] = [50_000_000, TX_GAS_LIMIT_CAP + RESERVOIR]; + +/// Bytes the deployments here leave behind. +const DEPLOYED: u64 = 32; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(10u64.pow(9))) + .account_balance(PAYEE, U256::from(1)) +} + +/// A log with `topics` topics over the first `len` bytes of memory. +fn log(code: BytecodeBuilder, topics: u8, len: u64) -> BytecodeBuilder { + let mut code = code; + for topic in 0..topics { + code = code.push_number(u64::from(topic) + 1); + } + code.push_number(len).push_number(0u64).append(LOG0 + topics) +} + +/// The bytes a log with `topics` topics and `len` bytes of data appends. +const fn log_bytes(topics: u64, len: u64) -> u64 { + LOG_BASE_SIZE + topics * LOG_TOPIC_SIZE + len +} + +/// Init code that deploys [`DEPLOYED`] zero bytes: `PUSH1 32; PUSH0; RETURN`. +fn deploying() -> Bytes { + BytecodeBuilder::default().push_number(DEPLOYED).append_many([PUSH0, RETURN]).build() +} + +/// `CREATE` over `init_code` placed in memory, discarding the address. +fn creating(code: BytecodeBuilder, init_code: &[u8]) -> BytecodeBuilder { + code.mstore(0, init_code) + .push_number(init_code.len() as u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(POP) +} + +/// `CALL(gas, target, value, 0, 0, 0, 0)`, discarding the flag. +fn calling(code: BytecodeBuilder, target: Address, value: u64, gas: u64) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(target) + .push_number(gas) + .append(CALL) + .append(POP) +} + +/// `funded()` with `code` at [`CALLEE`]. +fn callee_running(code: BytecodeBuilder) -> MemoryDatabase { + funded().account_code(CALLEE, code.stop().build()) +} + +/// Asserts what the reservoir of a run above the execution cap says about its two ledgers: what +/// the transaction spent on state and history came out of it, and nothing else did. +fn assert_reservoir_paid(name: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { + if gas_limit <= TX_GAS_LIMIT_CAP { + return; + } + let reservoir = gas_limit - TX_GAS_LIMIT_CAP; + assert!(outcome.gas.reservoir_remaining > 0, "{name}: the reservoir is not exhausted"); + assert_eq!( + outcome.gas.reservoir_remaining, + reservoir - outcome.gas.state - outcome.gas.history, + "{name}: the reservoir paid the state and history ledgers and nothing else", + ); +} + +/// A callee that writes a slot, logs, pays an account it creates and deploys code: every history +/// site a frame reaches, and state gas beside it. +fn every_site() -> MemoryDatabase { + let code = creating( + calling( + log(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), 3, 64), + FRESH, + 1, + 1_000_000, + ), + &deploying(), + ); + callee_running(code) +} + +/// A call to [`every_site`]'s callee carrying ten bytes of calldata. +fn every_site_called(gas_limit: u64) -> MegaTransaction { + call_with_data(CALLER, CALLEE, Bytes::from(vec![1; 10]), gas_limit) +} + +/// A reservoir too small for what a transaction spends on state and history runs out, and the +/// rest spills onto regular gas. That changes who paid and nothing else: the bytes, the history +/// gas and the state gas are the ones an ample reservoir leaves, the regular ledger is too — a +/// spilled charge stays on its own ledger — and the reservoir is spent to the last gas. +#[test] +fn test_a_reservoir_that_runs_out_changes_only_who_paid() { + if runs_at_measurement_prices() { + return; + } + let ample = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + RESERVOIR)); + assert!(ample.result.is_success(), "{:?}", ample.result); + assert_reservoir_paid("an ample reservoir", TX_GAS_LIMIT_CAP + RESERVOIR, &le); + let spent = ample.gas.state + ample.gas.history; + + // Short of the body; short of everything but the body; short by one gas. + for reservoir in [1, TX_BODY_SIZE * CPHB - 1, TX_BODY_SIZE * CPHB + 1, spent - 1] { + let outcome = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + reservoir)); + let name = format!("a reservoir of {reservoir}"); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.gas.reservoir_remaining, 0, "{name}: spent to the last gas"); + assert_eq!(outcome.gas.history_bytes, ample.gas.history_bytes, "{name}: the bytes"); + assert_eq!(outcome.gas.history, ample.gas.history, "{name}: the history gas"); + assert_eq!(outcome.gas.state, ample.gas.state, "{name}: the state gas"); + assert_eq!(outcome.gas.regular, ample.gas.regular, "{name}: the regular ledger"); + assert_eq!( + outcome.gas.regular + outcome.gas.state + outcome.gas.history, + outcome.result.gas().total_gas_spent(), + "{name}: the three ledgers split the raw spend", + ); + } + + let exact = execute(every_site(), every_site_called(TX_GAS_LIMIT_CAP + spent)); + assert_eq!(exact.gas.reservoir_remaining, 0, "a reservoir of exactly what is spent"); + assert_eq!(exact.gas.regular, ample.gas.regular); +} + +/// A transaction whose gas cannot pay for the record its own frame makes runs out of gas before +/// that frame, and the record is not made: it reports its body alone, in bytes and in gas. +#[test] +fn test_a_transaction_that_cannot_pay_its_first_record_reports_its_body_alone() { + if runs_at_measurement_prices() { + return; + } + let transfer = |gas| call(CALLER, PAYEE, U256::from(1), gas); + // What the transfer spends is its intrinsic gas and the one record, nothing else: that is the + // least gas limit that pays for all of it. + let ample = execute(funded(), transfer(GAS_LIMITS[0])); + assert!(ample.result.is_success(), "{:?}", ample.result); + let fits = ample.gas.gas_used; + + let exact = execute(funded(), transfer(fits)); + assert!(exact.result.is_success(), "{:?}", exact.result); + assert_eq!(exact.gas.history_bytes, TX_BODY_SIZE + WRITE_RECORD_SIZE); + assert_eq!(exact.gas.history, exact.gas.history_bytes * CPHB); + + let short = execute(funded(), transfer(fits - 1)); + assert!(short.result.is_halt(), "{:?}", short.result); + assert_eq!(short.usage.write_records, 0, "no frame ran, so no record was made"); + assert_eq!(short.gas.history_bytes, TX_BODY_SIZE, "the body alone"); + assert_eq!(short.gas.history, TX_BODY_SIZE * CPHB); +} + +/// Answers every creation itself with a success whose output is a word of bytes, so no frame runs +/// and nothing is deposited. +/// +/// The answer's gas is the creation's, untouched, with the reservoir it inherited, as the +/// engine's own answers build it: a `Gas::new` of the forwarded limit would carry no reservoir, +/// and the caller that adopts it would lose its own. +struct AnswersCreations; + +impl Inspector, EthInterpreter> for AnswersCreations { + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + Some(CreateOutcome::new( + InterpreterResult::new( + InstructionResult::Return, + Bytes::from(vec![0xfe; 32]), + untouched_create_gas(inputs), + ), + Some(CHILD), + )) + } +} + +/// A creation answered without running deposits nothing, whatever the answer's output: the bytes +/// the transaction reports are what the history ledger charged for, and the charge its caller made +/// for the creation's records comes back with the creation that never made them. +#[test] +fn test_a_creation_answered_without_running_appends_no_code() { + if runs_at_measurement_prices() { + return; + } + for gas_limit in GAS_LIMITS { + let db = callee_running(creating(BytecodeBuilder::default(), &deploying())); + let outcome = MegaEvm::new(context(db)) + .with_inspector(AnswersCreations) + .execute_transaction(call(CALLER, CALLEE, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0, "the creation that never ran wrote nothing"); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "and appended nothing: its body"); + assert_eq!(outcome.gas.history, TX_BODY_SIZE * CPHB); + assert_reservoir_paid("a creation answered without running", gas_limit, &outcome); + } +} + +/* ---------- the edge paths ---------- */ + +/// Two authorities, and the account an applied authorization delegates to. +const AUTHORITY: Address = address!("0000000000000000000000000000000000a00007"); +const OTHER_AUTHORITY: Address = address!("0000000000000000000000000000000000a00008"); +const DELEGATE: Address = address!("0000000000000000000000000000000000a00009"); + +/// A type-1 call from [`CALLER`] to [`CALLEE`] whose access list names each `(address, keys)` +/// with that many storage keys. +fn with_access_list(entries: &[(Address, u64)], gas_limit: u64) -> MegaTransaction { + let items = entries.iter().map(|&(address, keys)| AccessListItem { + address, + storage_keys: (0..keys).map(|key| B256::from(U256::from(key))).collect(), + }); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit, + access_list: AccessList(items.collect()), + ..Default::default() + })) +} + +/// A type-4 call from [`CALLER`] to [`CALLEE`] carrying authorizations `(authority, nonce)` that +/// delegate to [`DELEGATE`]. +fn with_authorizations(authorizations: &[(Address, u64)], gas_limit: u64) -> MegaTransaction { + let authorization_list = authorizations + .iter() + .map(|&(authority, nonce)| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: DELEGATE, nonce }, + RecoveredAuthority::Valid(authority), + )) + }) + .collect(); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: TxKind::Call(CALLEE), + gas_limit, + gas_priority_fee: Some(0), + authorization_list, + ..Default::default() + })) +} + +/// `SELFDESTRUCT` to `beneficiary`. +fn destructs_to(beneficiary: Address) -> Bytes { + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() +} + +/// `CALL(GAS, MegaAccessControl, value, isVolatileDataAccessDisabled())`, discarding the flag. The +/// interceptor answers it without a frame, and refuses it when it carries value. +fn asks_access_control(code: BytecodeBuilder, value: u64) -> BytecodeBuilder { + code.mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append(PUSH0) + .push_number(value) + .push_address(ACCESS_CONTROL_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP) +} + +/// `funded()` with `code` at [`CALLEE`] and `MegaAccessControl` deployed. +fn beside_access_control(code: BytecodeBuilder) -> MemoryDatabase { + callee_running(code) + .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) +} + +/// Init code that returns one byte, `0xEF`, which EIP-3541 refuses to deposit. +fn refused_code() -> Bytes { + Bytes::from_static(&[PUSH1, 0xef, PUSH0, MSTORE8, PUSH1, 1, PUSH0, RETURN]) +} + +/// Init code that returns one byte more than a contract may hold. +fn oversized_code() -> Bytes { + BytecodeBuilder::default() + .push_number(MAX_CONTRACT_SIZE as u64 + 1) + .append_many([PUSH0, RETURN]) + .build() +} + +/// `DELEGATECALL(GAS, CHILD, 0, 0, 0, 0)`, discarding the flag: [`CHILD`]'s code runs on +/// [`CALLEE`]'s storage, in a frame of its own. +fn delegating(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .append(GAS) + .append(DELEGATECALL) + .append(POP) +} + +/// Code for [`CALLEE`] that sets slot 1 and calls itself with a byte of calldata; called with +/// calldata, it writes the slot back. +fn writes_then_calls_itself_to_write_back() -> Bytes { + let outer = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0]) + .push_number(1u64) + .append_many([PUSH0, PUSH0]) + .push_address(CALLEE) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + let inner = BytecodeBuilder::default() + .append(JUMPDEST) + .sstore(U256::from(1), U256::ZERO) + .stop() + .build(); + // `CALLDATASIZE; PUSH1 inner; JUMPI` takes four bytes ahead of the outer path. + let inner_at = u8::try_from(4 + outer.len()).expect("the outer path is short"); + let mut code = vec![CALLDATASIZE, PUSH1, inner_at, JUMPI]; + code.extend_from_slice(&outer); + code.extend_from_slice(&inner); + Bytes::from(code) +} + +/// A transaction-level data-size limit of `bytes`, or none at all. The body counts towards it, so +/// a limit that stops a write the transaction makes is the body's bytes and more. +fn limited_to(bytes: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) +} + +/// A write-back takes the record back only if the frame that made it is kept: a delegate that +/// writes the slot back and then reverts takes its write-back with it, and the record stands. +#[test] +fn test_a_write_back_dies_with_the_frame_that_made_it() { + if runs_at_measurement_prices() { + return; + } + for gas_limit in GAS_LIMITS { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + let db = callee_running(delegating(code)).account_code( + CHILD, + BytecodeBuilder::default().sstore(U256::from(1), U256::ZERO).revert().build(), + ); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE + WRITE_RECORD_SIZE); + assert_eq!(outcome.gas.history, outcome.gas.history_bytes * CPHB); + assert_reservoir_paid("a write-back that reverts", gas_limit, &outcome); + } +} + +/* ---------- where an allowance pays ---------- */ + +/// One three-topic event over one word: the event the allowance is sized for. +fn event() -> BytecodeBuilder { + log(BytecodeBuilder::default(), 3, 32) +} + +/// A value call's history allowance pays for bytes its callee appends, and those bytes are on no +/// gas ledger: the byte count exceeds the history gas by exactly what the allowances paid, at +/// most one allowance per value call, and nothing for an event its frame did not keep. +#[test] +fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { + if runs_at_measurement_prices() { + return; + } + // The two records every transfer below writes: the sender's account and the receiver's. + let transfer = 2 * WRITE_RECORD_SIZE; + + type Case = (&'static str, fn() -> MemoryDatabase, u64, u64); + let cases: [Case; 5] = [ + ( + "a transfer's receiver emits the event, and the allowance pays all of it", + || { + callee_running(calling(BytecodeBuilder::default(), RECEIVER, 1, 2_300)) + .account_code(RECEIVER, event().stop().build()) + }, + TX_BODY_SIZE + transfer + log_bytes(3, 32), + STORAGE_CALL_STIPEND_BYTES, + ), + ( + "an event larger than the allowance: the receiver's gas pays the rest", + || { + callee_running(calling(BytecodeBuilder::default(), RECEIVER, 1, 100_000)) + .account_code(RECEIVER, log(BytecodeBuilder::default(), 3, 64).stop().build()) + }, + TX_BODY_SIZE + transfer + log_bytes(3, 64), + STORAGE_CALL_STIPEND_BYTES, + ), + ( + "two events: the allowance pays the first", + || { + let code = log(event(), 3, 32).stop().build(); + callee_running(calling(BytecodeBuilder::default(), RECEIVER, 1, 100_000)) + .account_code(RECEIVER, code) + }, + TX_BODY_SIZE + transfer + 2 * log_bytes(3, 32), + STORAGE_CALL_STIPEND_BYTES, + ), + ( + "the receiver reverts: the event is not appended, and the transfer's records neither", + || { + callee_running(calling(BytecodeBuilder::default(), RECEIVER, 1, 100_000)) + .account_code(RECEIVER, event().revert().build()) + }, + TX_BODY_SIZE, + 0, + ), + ( + "two receivers, two allowances", + || { + let code = calling( + calling(BytecodeBuilder::default(), RECEIVER, 1, 2_300), + OTHER_RECEIVER, + 1, + 2_300, + ); + callee_running(code) + .account_code(RECEIVER, event().stop().build()) + .account_code(OTHER_RECEIVER, event().stop().build()) + }, + // The sender's account is written once; each receiver's once. + TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 2 * log_bytes(3, 32), + 2 * STORAGE_CALL_STIPEND_BYTES, + ), + ]; + + for (name, db, bytes, paid_by_allowances) in cases { + for gas_limit in GAS_LIMITS { + let outcome = execute(db(), call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.gas.history_bytes, bytes, "{name} at {gas_limit}: the bytes"); + assert_eq!( + outcome.gas.history_bytes * CPHB - outcome.gas.history, + paid_by_allowances * CPHB, + "{name} at {gas_limit}: the gap is what the allowances paid", + ); + assert_reservoir_paid(name, gas_limit, &outcome); + } + } +} + +/* ---------- the bytes and the data size ---------- */ + +/// The calldata of `sendHint(topic, payload)`. +fn hint_call() -> Bytes { + let call = + IOracle::sendHintCall { topic: B256::repeat_byte(0x7a), data: Bytes::from(vec![7; 40]) }; + Bytes::from(call.abi_encode()) +} + +/// `CALL(GAS, Oracle, 0, hint_call())`, discarding the flag: a hint sent from a frame. +fn hinting(code: BytecodeBuilder) -> BytecodeBuilder { + let data = hint_call(); + code.mstore(0, &data) + .append_many([PUSH0, PUSH0]) + .push_number(data.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP) +} + +/// `funded()` with the Oracle deployed. +fn beside_the_oracle() -> MemoryDatabase { + funded().account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) +} + +/// How a case of [`test_the_history_bytes_are_the_data_size_every_record_kept`] runs. +#[derive(Clone, Copy)] +enum Run { + /// With no limit. + Plain, + /// Under a transaction data-size limit of this many bytes, which the transaction's own frame + /// crosses. + Limited(u64), + /// Under a transaction data-size limit of this many bytes, which a frame below the + /// transaction's own crosses, whose caller catches the stop. + Caught(u64), + /// With an inspector that answers every creation without running it. + AnsweringCreations, +} + +/// The history bytes a transaction reports and the data size it kept are counted from one byte +/// table, record by record, so they move together at every site both count — the body, calldata, +/// the access list, authorizations, logs, write records and deployed code — and on every path +/// that takes a record back: a failed creation, output revm does not deposit, a frame answered +/// without running, a stop. They part at two sites: an Oracle hint, whose payload is data size and +/// never history, and the transfer log a kept value movement leaves, which is data size and never +/// history either — the history columns stay where they are, and the receipt carries the log. None +/// of these cases draws on an allowance, so the history gas is the bytes at the price as well. +#[test] +fn test_the_history_bytes_are_the_data_size_every_record_kept() { + if runs_at_measurement_prices() { + return; + } + let hint = hint_call().len() as u64; + type Case = + (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64); + let cases: [Case; 35] = [ + ( + "the body", + || callee_running(BytecodeBuilder::default()), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "calldata", + || callee_running(BytecodeBuilder::default()), + |gas| call_with_data(CALLER, CALLEE, Bytes::from(vec![0; 100]), gas), + Run::Plain, + TX_BODY_SIZE + 100, + 0, + 0, + ), + ( + "an access list", + || callee_running(BytecodeBuilder::default()), + |gas| with_access_list(&[(CALLEE, 2), (PAYEE, 1), (FRESH, 0)], gas), + Run::Plain, + TX_BODY_SIZE + 3 * ACCESS_LIST_ADDRESS_SIZE + 3 * ACCESS_LIST_SLOT_SIZE, + 0, + 0, + ), + ( + "authorizations, one applied", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(AUTHORITY, 0), (OTHER_AUTHORITY, 7)], gas), + Run::Plain, + TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "a log", + || callee_running(log(BytecodeBuilder::default(), 2, 50)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + log_bytes(2, 50), + 0, + 0, + ), + ( + "a log a reverted child emitted", + || { + callee_running(calling(BytecodeBuilder::default(), CHILD, 0, 1_000_000)) + .account_code(CHILD, log(BytecodeBuilder::default(), 1, 32).revert().build()) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a storage write", + || callee_running(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1))), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "a storage write written back", + || { + callee_running( + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO), + ) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a value transfer's two records", + || callee_running(calling(BytecodeBuilder::default(), PAYEE, 1, 100_000)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, + 0, + 1, + ), + ( + "a SELFDESTRUCT's beneficiary", + || funded().account_code(CALLEE, destructs_to(PAYEE)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 1, + ), + ( + "a creation transaction's code", + funded, + |gas| create(CALLER, deploying(), gas), + Run::Plain, + TX_BODY_SIZE + deploying().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, + 0, + 0, + ), + ( + "a nested creation's code", + || callee_running(creating(BytecodeBuilder::default(), &deploying())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + DEPLOYED, + 0, + 0, + ), + ( + "a failed creation: its creator's nonce, and no code", + || callee_running(creating(BytecodeBuilder::default(), &[PUSH1, 32, PUSH0, REVERT])), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "output EIP-3541 refuses to deposit", + || callee_running(creating(BytecodeBuilder::default(), &refused_code())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "output past the code-size limit", + || callee_running(creating(BytecodeBuilder::default(), &oversized_code())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "a creation transaction whose output EIP-3541 refuses", + funded, + |gas| create(CALLER, refused_code(), gas), + Run::Plain, + TX_BODY_SIZE + refused_code().len() as u64, + 0, + 0, + ), + ( + "a call an interceptor answers without a frame", + || { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + beside_access_control(asks_access_control(code, 0)) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "a value call an interceptor refuses without a frame", + || beside_access_control(asks_access_control(BytecodeBuilder::default(), 1)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a creation an inspector answers without running it", + || callee_running(creating(BytecodeBuilder::default(), &deploying())), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::AnsweringCreations, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a first frame answered with the stop", + funded, + |gas| call(CALLER, FRESH, U256::from(1), gas), + Run::Limited(TX_BODY_SIZE + WRITE_RECORD_SIZE - 1), + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a stop at a child's write, which its caller catches: its log is kept", + || { + callee_running(calling(log(BytecodeBuilder::default(), 0, 0), CHILD, 0, 1_000_000)) + .account_code( + CHILD, + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).build(), + ) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Caught(TX_BODY_SIZE + LOG_BASE_SIZE + WRITE_RECORD_SIZE - 1), + TX_BODY_SIZE + LOG_BASE_SIZE, + 0, + 0, + ), + ( + "a hint sent by the transaction: its calldata is history, its payload is not", + beside_the_oracle, + |gas| call_with_data(CALLER, ORACLE_CONTRACT_ADDRESS, hint_call(), gas), + Run::Plain, + TX_BODY_SIZE + hint_call().len() as u64, + 1, + 0, + ), + ( + "a hint sent from a frame", + || { + beside_the_oracle() + .account_code(CALLEE, hinting(BytecodeBuilder::default()).stop().build()) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 1, + 0, + ), + ( + "a transfer that creates its recipient", + funded, + |gas| call(CALLER, FRESH, U256::from(1), gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 1, + ), + ( + "a transaction whose own frame writes, logs, deploys and reverts", + || { + let code = creating( + log(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), 1, 32), + &deploying(), + ); + funded().account_code(CALLEE, code.revert().build()) + }, + |gas| call(CALLER, CALLEE, U256::from(1), gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "every site at once", + every_site, + every_site_called, + Run::Plain, + // The body and its calldata; the slot; the log; the transfer's two records (the + // callee's account and the recipient's), which leave the creation none of its own + // for the callee's nonce; the created account and its code. + TX_BODY_SIZE + + 10 + + WRITE_RECORD_SIZE + + log_bytes(3, 64) + + 2 * WRITE_RECORD_SIZE + + WRITE_RECORD_SIZE + + DEPLOYED, + 0, + 1, + ), + ( + "an authority applied twice is one record", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(AUTHORITY, 0), (AUTHORITY, 1)], gas), + Run::Plain, + TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "the sender's own authorization: in the body, and no record beside it", + || callee_running(BytecodeBuilder::default()), + |gas| with_authorizations(&[(CALLER, 1)], gas), + Run::Plain, + TX_BODY_SIZE + AUTHORIZATION_SIZE, + 0, + 0, + ), + ( + "a SELFDESTRUCT's beneficiary the destruction creates", + || funded().account_code(CALLEE, destructs_to(FRESH)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 1, + ), + ( + "a SELFDESTRUCT to the sender records nothing: the body carries the sender", + || funded().account_code(CALLEE, destructs_to(CALLER)), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 1, + ), + ( + "a SELFDESTRUCT that moves nothing records nothing", + || funded().account_code(RECEIVER, destructs_to(PAYEE)), + |gas| call(CALLER, RECEIVER, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a stop at a value call before its frame is built: nothing its start would write is \ + kept, and its caller, which catches the stop, keeps its own write", + || { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + callee_running(calling(code, PAYEE, 1, 100_000)) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Caught(TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE - 1), + TX_BODY_SIZE + WRITE_RECORD_SIZE, + 0, + 0, + ), + ( + "a slot written, then written back by a delegate: the record is taken back", + || { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + callee_running(delegating(code)).account_code( + CHILD, + BytecodeBuilder::default().sstore(U256::from(1), U256::ZERO).build(), + ) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a slot a delegate wrote, written back by its caller", + || { + let code = delegating(BytecodeBuilder::default()); + callee_running(code.sstore(U256::from(1), U256::ZERO)).account_code( + CHILD, + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).build(), + ) + }, + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ( + "a slot written, then written back by a call to itself", + || funded().account_code(CALLEE, writes_then_calls_itself_to_write_back()), + |gas| call(CALLER, CALLEE, U256::ZERO, gas), + Run::Plain, + TX_BODY_SIZE, + 0, + 0, + ), + ]; + + for (name, db, tx, run, bytes, hints, moves) in cases { + for gas_limit in GAS_LIMITS { + let limit = match run { + Run::Limited(limit) | Run::Caught(limit) => limit, + Run::Plain | Run::AnsweringCreations => u64::MAX, + }; + // A limit the body alone crosses would stop every case before its first write, and the + // case would pin the body's stop rather than its own. + assert!(limit > TX_BODY_SIZE, "{name}: the body fits under the limit"); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limited_to(limit))); + let outcome = match run { + Run::AnsweringCreations => { + evm.with_inspector(AnswersCreations).execute_transaction(tx(gas_limit)) + } + Run::Plain | Run::Limited(_) | Run::Caught(_) => { + evm.execute_transaction(tx(gas_limit)) + } + } + .expect("the transaction is valid"); + assert_eq!( + outcome.limit_exceeded.is_some(), + matches!(run, Run::Limited(_)), + "{name} at {gas_limit}: {:?}", + outcome.result, + ); + assert_eq!( + outcome.gas.history_bytes, bytes, + "{name} at {gas_limit}: the history bytes" + ); + assert_eq!( + outcome.result.logs().iter().filter(|log| is_transfer_log(log)).count() as u64, + moves, + "{name} at {gas_limit}: the transfer logs kept", + ); + assert_eq!( + outcome.usage.data_size, + bytes + hints * hint + moves * TRANSFER_LOG_SIZE, + "{name} at {gas_limit}: the data size is the history bytes, the hints' payloads \ + and the transfer logs", + ); + assert_eq!( + outcome.gas.history, + bytes * CPHB, + "{name} at {gas_limit}: the history gas is the bytes at the price", + ); + assert_reservoir_paid(name, gas_limit, &outcome); + } + } +} diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs new file mode 100644 index 000000000..099c248a1 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -0,0 +1,328 @@ +//! Who pays no history gas at all: a deposit, a transaction the protocol itself sent, and a +//! system call. +//! +//! What those three append to the chain is the chain carrying its own weight — a deposit the +//! sequencer relays and that was paid for on L1, the maintenance a system transaction performs, +//! the calls the protocol makes before a block's transactions — and there is no sender to charge +//! for it. Every one of them runs the same program as the control transaction below, which pays +//! for every byte of it. +//! +//! The exemption is history's alone. State gas is charged as usual, which each test asserts, so an +//! exempt transaction cannot grow the state for free. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{ + ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, SLOT_STATE_GAS, + TX_GAS_LIMIT_CAP, + }, + system::{IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + transaction_body_bytes, LimitUsage, MegaEvm, MegaTransaction, MegaTransactionOutcome, + LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, LOG0, POP}, + context::TxEnv, +}; + +use crate::common::{context, deposit, runs_at_measurement_prices}; + +const CALLER: Address = address!("0000000000000000000000000000000000400000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000400001"); +const PAYEE: Address = address!("0000000000000000000000000000000000400002"); + +/// Room for the state gas of a new slot, a new account and a deployment. +const GAS_LIMIT: u64 = 50_000_000; + +/// The program every transaction here runs: a new slot, a log, a transfer that creates its +/// recipient, and a deployment of [`DEPLOYED_BYTES`] bytes — one of each history site the engine +/// charges, including the one revm charges itself out of the schedule. +fn program() -> Bytes { + program_deploying(DEPLOYED_BYTES) +} + +/// The same program with a creation that deploys `len` bytes. +fn program_deploying(len: u64) -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .push_number(0u64) + .push_number(32u64) + .push_number(0u64) + .append(LOG0) + // CALL(gas, PAYEE, 1, 0, 0, 0, 0) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(0u64) + .push_number(1u64) + .push_address(PAYEE) + .push_number(1_000_000u64) + .append(CALL) + .append(POP) + // `PUSH1 len; PUSH0; RETURN` in memory, then a CREATE over those four bytes. + .mstore(0, [0x60, len as u8, 0x5f, 0xf3]) + .push_number(4u64) + .push_number(0u64) + .push_number(0u64) + .append(CREATE) + .append(POP) + .stop() + .build() +} + +/// Bytes the program's creation deploys, which the schedule prices at a history byte each. +const DEPLOYED_BYTES: u64 = 32; + +/// The history bytes a user transaction running the program from [`CALLER`] appends: its body +/// with no calldata; the program's four write records — the new slot, then `CONTRACT` (the +/// transfer's sender and the creator, recorded once in its frame), `PAYEE` and the created +/// account; its log of one word with no topic; and the deployed code. The transfer's log is data +/// size and appends no history. +const PROGRAM_HISTORY_BYTES: u64 = + TX_BODY_SIZE + 4 * WRITE_RECORD_SIZE + (LOG_BASE_SIZE + 32) + DEPLOYED_BYTES; + +/// The state gas the program adds, exempt or not: the new slot, `PAYEE`'s account, the created +/// account and the code it deploys, in minimum-size buckets. +const PROGRAM_STATE_GAS: u64 = + SLOT_STATE_GAS + 2 * ACCOUNT_STATE_GAS + DEPLOYED_BYTES * COST_PER_STATE_BYTE; + +fn db() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::ZERO) + .account_balance(CONTRACT, U256::from(10u64.pow(9))) + .account_code(CONTRACT, program()) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) +} + +/// A call to `to` from `caller`. +fn call_from(caller: Address, to: Address) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(to), + gas_limit: GAS_LIMIT, + ..Default::default() + })) +} + +/// The slot of the Oracle the system transaction sets, and the value it sets it to. +const ORACLE_SLOT: U256 = U256::from_limbs([7, 0, 0, 0]); +const ORACLE_VALUE: B256 = B256::repeat_byte(0x5a); + +/// The protocol's own transaction: the system address setting [`ORACLE_SLOT`] of the Oracle, a +/// contract it may call, through `setSlot`, which only the system address may call. +fn system_tx() -> MegaTransaction { + let mut tx = call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.0.base.data = + IOracle::setSlotCall { slot: ORACLE_SLOT, value: ORACLE_VALUE }.abi_encode().into(); + tx +} + +/// The value `outcome` left in the Oracle's [`ORACLE_SLOT`], if it changed the slot. +fn written_oracle_slot(outcome: &MegaTransactionOutcome) -> Option { + let slot = outcome.state.get(&ORACLE_CONTRACT_ADDRESS)?.storage.get(&ORACLE_SLOT)?; + slot.is_changed().then(|| B256::from(slot.present_value)) +} + +/// Runs `tx` and reports its history and state ledgers, and the outcome they are read from. +fn ledgers(tx: MegaTransaction) -> (u64, u64, MegaTransactionOutcome) { + let outcome = + MegaEvm::new(context(db())).execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + (outcome.gas.history, outcome.gas.state, outcome) +} + +/// The control: a user transaction running the program pays for every byte of it, on top of its +/// own body. +#[test] +fn test_a_user_transaction_pays_history_for_the_program() { + if runs_at_measurement_prices() { + return; + } + let (history, state, outcome) = ledgers(call_from(CALLER, CONTRACT)); + assert!(history > 0, "a user transaction pays for the bytes it appends"); + assert!(state > 0, "and for the state it adds"); + assert_eq!(history, PROGRAM_HISTORY_BYTES * COST_PER_HISTORY_BYTE, "every byte of the program"); + assert_eq!(outcome.gas.history_bytes, PROGRAM_HISTORY_BYTES); + assert_eq!(state, PROGRAM_STATE_GAS, "the slot, the two accounts and the code"); +} + +/// The one history charge revm makes itself is the deployed code's, out of the schedule; the +/// exemption reaches it too, by handing an exempt transaction a schedule that prices a deposited +/// byte at zero. +/// +/// The program above deploys thirty-two bytes. A user transaction pays for them and a deposit +/// running the same program pays for nothing at all, so the difference the schedule makes is +/// visible where a ledger comparison alone would only show two zeroes. +#[test] +fn test_the_exempt_schedule_prices_a_deposited_byte_at_zero() { + if runs_at_measurement_prices() { + return; + } + let deployed = |code: Bytes| { + let db = db().account_code(CONTRACT, code); + let outcome = MegaEvm::new(context(db)) + .execute_transaction(call_from(CALLER, CONTRACT)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome.gas.history + }; + let thirty_two = deployed(program()); + let nothing = deployed(program_deploying(0)); + + assert_eq!( + thirty_two - nothing, + DEPLOYED_BYTES * mega_evm::constants::COST_PER_HISTORY_BYTE, + "a user transaction pays a history byte per deployed byte", + ); + assert_eq!(ledgers(deposit(call_from(CALLER, CONTRACT))).0, 0, "a deposit pays none of it"); +} + +/// A deposit pays no history gas: the bytes it carries were paid for on L1. +#[test] +fn test_a_deposit_pays_no_history_gas() { + if runs_at_measurement_prices() { + return; + } + let (history, state, outcome) = ledgers(deposit(call_from(CALLER, CONTRACT))); + assert_eq!(history, 0, "a deposit pays no history gas"); + assert!(state > 0, "the exemption is history's alone"); + assert_eq!(state, PROGRAM_STATE_GAS, "the state a user transaction pays"); + assert_eq!(outcome.gas.history_bytes, 0); +} + +/// A transaction from the system address pays no history gas: the protocol is maintaining its own +/// state, and a resource charge it cannot pay would stop it. +#[test] +fn test_a_system_transaction_pays_no_history_gas() { + if runs_at_measurement_prices() { + return; + } + // The system address may only call a whitelisted contract, so the program runs there: the + // Oracle's own code is what a system transaction reaches, and `setSlot` writes a slot of its + // own. + let tx = system_tx(); + let outcome = + MegaEvm::new(context(db())).execute_transaction(tx).expect("the transaction is valid"); + assert_eq!(outcome.gas.history, 0, "the protocol's own transaction pays no history gas"); + assert_eq!(outcome.gas.history_bytes, 0, "and appends no history byte, its body included"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(written_oracle_slot(&outcome), Some(ORACLE_VALUE), "it wrote the Oracle's slot"); + assert_eq!( + outcome.usage, + LimitUsage { + data_size: transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE, + write_records: 1, + }, + "the body and the slot's record are counted, though neither pays history", + ); + // The state is charged as usual: the new slot, and the system address's own account, which + // the database leaves empty, so the transaction creates it, as it does a deposit's caller. + assert_eq!(outcome.gas.state, SLOT_STATE_GAS + ACCOUNT_STATE_GAS); +} + +/// A system call pays no history gas either: it is the protocol running, not a transaction +/// anybody sent, and it has no sender to charge. +#[test] +fn test_a_system_call_pays_no_history_gas() { + if runs_at_measurement_prices() { + return; + } + let mut evm = MegaEvm::new(context(db())); + let result = Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()) + .expect("the system call runs"); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + evm.ctx().additional_limit().history_gas_spent(), + 0, + "a system call pays no history gas", + ); + assert!(result.result.gas().state_gas_spent_final() > 0, "the exemption is history's alone"); + assert_eq!(result.result.gas().state_gas_spent_final(), PROGRAM_STATE_GAS); + assert_eq!(evm.ctx().additional_limit().history_bytes(), 0); +} + +/// The bytes a transaction appended are reported beside its history gas, and they are the bytes +/// that gas priced: the control reports every byte of the program, each at the price, and an +/// exempt transaction, which prices none of them, reports none. +/// +/// Each transaction runs below the execution cap and above it. Above it the reservoir pays the +/// state gas, which the exemption leaves in place, and no history. +/// +/// A system call runs at the gas limit its entry point fixes, below the cap. +#[test] +fn test_an_exempt_transaction_reports_no_history_bytes() { + if runs_at_measurement_prices() { + return; + } + const RESERVOIR: u64 = 100_000_000; + for gas_limit in [GAS_LIMIT, TX_GAS_LIMIT_CAP + RESERVOIR] { + let run = |mut tx: MegaTransaction| { + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(db())) + .execute_transaction(tx) + .expect("the transaction is valid"); + let gas = outcome.gas; + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + gas.reservoir_remaining, + RESERVOIR - gas.state - gas.history, + "the reservoir paid the state and history ledgers", + ); + } + outcome + }; + + let paying = run(call_from(CALLER, CONTRACT)).gas; + assert!(paying.history_bytes > 0); + assert_eq!( + paying.history, + paying.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE, + "at {gas_limit}: the control pays for every byte it reports", + ); + + let deposit = run(deposit(call_from(CALLER, CONTRACT))).gas; + assert_eq!((deposit.history, deposit.history_bytes), (0, 0), "at {gas_limit}: a deposit"); + assert!(deposit.state > 0, "at {gas_limit}: the exemption is history's alone"); + let system = run(system_tx()); + assert!(system.result.is_success(), "at {gas_limit}: {:?}", system.result); + assert_eq!(written_oracle_slot(&system), Some(ORACLE_VALUE), "at {gas_limit}"); + let system = system.gas; + assert_eq!( + (system.history, system.history_bytes), + (0, 0), + "at {gas_limit}: a system transaction", + ); + } + + let mut evm = MegaEvm::new(context(db())); + Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()) + .expect("the system call runs"); + assert_eq!(evm.ctx().additional_limit().history_bytes(), 0, "a system call"); +} + +/// The exemption belongs to one transaction: the next transaction on the same EVM pays again. +#[test] +fn test_the_exemption_does_not_outlive_its_transaction() { + if runs_at_measurement_prices() { + return; + } + let mut evm = MegaEvm::new(context(db())); + + let exempt = evm + .execute_transaction(deposit(call_from(CALLER, CONTRACT))) + .expect("the deposit is valid"); + assert_eq!(exempt.gas.history, 0); + + // Nothing was committed, so the sender's nonce is where it was. + let paying = + evm.execute_transaction(call_from(CALLER, CONTRACT)).expect("the transaction is valid"); + assert!(paying.result.is_success(), "{:?}", paying.result); + assert!(paying.gas.history > 0, "the next transaction pays for its own bytes"); + assert_eq!(paying.gas.history, PROGRAM_HISTORY_BYTES * COST_PER_HISTORY_BYTE, "all of them"); +} diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs new file mode 100644 index 000000000..0012dc7aa --- /dev/null +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -0,0 +1,345 @@ +//! History gas: what a Satin transaction pays for the bytes it appends to the chain's history. +//! +//! Every charge is a byte count at the cost per history byte, and every assertion here writes the +//! count out, so a repricing moves the numbers without rewriting the test. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, TX_GAS_LIMIT_CAP}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STOP}, + context_interface::cfg::GasId, +}; + +use crate::common::{call, call_with_data, create, deploying, execute, runs_at_measurement_prices}; + +const CALLER: Address = address!("0000000000000000000000000000000000200000"); +const CALLEE: Address = address!("0000000000000000000000000000000000200001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000200002"); + +/// Room for the state gas of a new account and the code it deposits. +const GAS_LIMIT: u64 = 50_000_000; + +/// The cost per history byte, spelled as the constant the tests price against. +const CPHB: u64 = COST_PER_HISTORY_BYTE; + +/// The history a transaction's body costs when it carries `bytes` bytes beside its envelope. +const fn body(bytes: u64) -> u64 { + (TX_BODY_SIZE + bytes) * CPHB +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) +} + +/// Init code that reverts without deploying anything. +fn reverting() -> Bytes { + BytecodeBuilder::default().append_many([PUSH0, PUSH0, REVERT]).build() +} + +/// Deployed code is both state and history: its bytes enter the world state and the chain's +/// history, so a deployment pays the per-byte state rate and the per-byte history rate on the +/// same length. +#[test] +fn test_deployed_code_pays_history_for_every_byte() { + if runs_at_measurement_prices() { + return; + } + let short = execute(funded(), create(CALLER, deploying(32), GAS_LIMIT)); + let long = execute(funded(), create(CALLER, deploying(64), GAS_LIMIT)); + + assert!(short.result.is_success(), "{:?}", short.result); + assert!(long.result.is_success(), "{:?}", long.result); + assert_eq!(long.gas.history - short.gas.history, 32 * CPHB, "32 more bytes of history"); + assert_eq!(long.gas.state - short.gas.state, 32 * COST_PER_STATE_BYTE, "and of state"); +} + +/// A deployment that reverts appends no code, so it pays no code-deposit history at all. +#[test] +fn test_a_reverted_deployment_pays_no_code_deposit_history() { + if runs_at_measurement_prices() { + return; + } + let deployed = execute(funded(), create(CALLER, deploying(32), GAS_LIMIT)); + let reverted = execute(funded(), create(CALLER, reverting(), GAS_LIMIT)); + + assert!(deployed.result.is_success(), "{:?}", deployed.result); + assert!(!reverted.result.is_success(), "the creation reverts"); + assert_eq!( + deployed.gas.history, + body(deploying(32).len() as u64) + WRITE_RECORD_SIZE * CPHB + 32 * CPHB, + "the body the init code travels in, the created account's record, the deployed bytes", + ); + assert_eq!( + reverted.gas.history, + body(reverting().len() as u64), + "the body alone: nothing was deployed, and the account's record went with the failure", + ); +} + +/* ---------- the transaction body ---------- */ + +/// Calldata is part of the body, one history byte per byte, whatever the bytes are: a zero byte +/// takes the same space in a block as a non-zero one. +#[test] +fn test_calldata_costs_one_history_byte_per_byte() { + if runs_at_measurement_prices() { + return; + } + let run = |len: usize, byte: u8| { + let db = funded().account_code(CALLEE, Bytes::new()); + let data = Bytes::from(vec![byte; len]); + execute(db, call_with_data(CALLER, CALLEE, data, GAS_LIMIT)) + }; + let zeros = run(100, 0x00); + let non_zeros = run(100, 0xff); + let longer = run(200, 0x00); + + assert_eq!(zeros.gas.history, body(100)); + assert_eq!(non_zeros.gas.history, zeros.gas.history, "the value of a byte is not its size"); + assert_eq!(longer.gas.history - zeros.gas.history, 100 * CPHB, "a hundred bytes more"); +} + +/* ---------- the sites the Host stages ---------- */ + +/// The body of a `LOG` with `topics` topics over `data_len` bytes of memory, without the `STOP` +/// that ends a program. +fn log_body(topics: u8, data_len: u64) -> BytecodeBuilder { + let mut code = BytecodeBuilder::default(); + for topic in 0..topics { + code = code.push_number(u64::from(topic) + 1); + } + code.push_number(data_len).push_number(0u64).append(LOG0 + topics) +} + +/// A program that emits one such log and stops. +fn logging(topics: u8, data_len: u64) -> Bytes { + log_body(topics, data_len).stop().build() +} + +/// A log costs history on top of what the EVM itself charges for the opcode: the schedule's own +/// price is untouched, and the history is the bytes. +#[test] +fn test_a_log_pays_history_on_top_of_the_schedules_price() { + if runs_at_measurement_prices() { + return; + } + let run = |code: Bytes| { + let db = funded().account_code(CALLEE, code); + execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + }; + let quiet = run(BytecodeBuilder::default().stop().build()); + let logging = run(logging(1, 32)); + + // The EVM's own price for the opcode: two pushes for the offset and length, one for the + // topic, the `LOG` base, the per-topic and per-byte rates, and one word of memory. + let params = mega_evm::satin_gas_params(); + let native = + 3 * 3 + 375 + params.get(GasId::logtopic()) + 32 * params.get(GasId::logdata()) + 3; + assert_eq!( + logging.gas.regular - quiet.gas.regular, + native, + "the schedule charges what it always did", + ); + assert_eq!( + logging.gas.history - quiet.gas.history, + (LOG_BASE_SIZE + LOG_TOPIC_SIZE + 32) * CPHB + ); +} + +/* ---------- a frame-start charge the caller cannot pay ---------- */ + +/// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`: a value transfer that +/// forwards everything the caller may forward, so the caller keeps a sixty-fourth of what it held. +fn transfers_everything_to(target: Address) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(target) + .append(GAS) + .append(CALL) + .append(POP) + .append(STOP) + .build() +} + +/// `CREATE` of empty init code carrying one wei, discarding the address, then `STOP`. +fn creates_everything() -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .append(CREATE) + .append(POP) + .append(STOP) + .build() +} + +/// A funded caller holding `code`, with a balance to transfer. +fn caller_running(code: Bytes) -> MemoryDatabase { + funded().account_balance(CALLEE, U256::from(10_000_000)).account_code(CALLEE, code) +} + +/// The two records a value call's start makes cost more than a caller under roughly 450,000 gas +/// keeps after the sixty-fourth it may not forward. Such a caller pays for none of them by +/// halting: the frame it was starting does not run. +#[test] +fn test_a_call_whose_caller_cannot_pay_its_records_starts_no_frame() { + if runs_at_measurement_prices() { + return; + } + let code = transfers_everything_to(CONTRACT); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); + + assert!(!short.result.is_success(), "the caller halts rather than starting the frame"); + assert_eq!(short.usage.write_records, 0, "the frame that never ran wrote nothing"); + assert_eq!(short.gas.history, body(0), "and the transaction pays for its body alone"); + + assert!(ample.result.is_success(), "{:?}", ample.result); + assert_eq!(ample.usage.write_records, 2, "the caller's account and the recipient's"); + assert_eq!(ample.gas.history, body(0) + 2 * WRITE_RECORD_SIZE * CPHB); +} + +/// The same for a creation, whose start records the created account and the creator's nonce. +#[test] +fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { + if runs_at_measurement_prices() { + return; + } + let code = creates_everything(); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); + + assert!(!short.result.is_success(), "the creator halts rather than starting the creation"); + assert_eq!(short.usage.write_records, 0, "the creation that never ran wrote nothing"); + assert_eq!(short.gas.history, body(0), "and the transaction pays for its body alone"); + + assert!(ample.result.is_success(), "{:?}", ample.result); + assert_eq!(ample.usage.write_records, 2, "the created account and the creator's nonce"); + assert_eq!(ample.gas.history, body(0) + 2 * WRITE_RECORD_SIZE * CPHB); +} + +/// Whether a write record is paid for may not depend on how much gas its frame's caller had +/// left. Across the gas limits that straddle the point where a caller can no longer pay for the +/// records of the frame it starts, the history a transaction pays beyond its body is exactly the +/// records it kept. +/// +/// Above the execution cap the same holds whatever the reservoir: one that runs out before the +/// body is paid for, one that runs out partway through the records, and ample ones. Each pays +/// what it can of the state and history ledgers and spills the rest onto regular gas. +#[test] +fn test_no_gas_limit_buys_a_write_record_for_nothing() { + if runs_at_measurement_prices() { + return; + } + let reservoirs = [1, body(0) / 2, body(0) + WRITE_RECORD_SIZE * CPHB, 1_000_000, 100_000_000]; + let above_the_cap = reservoirs.map(|reservoir| TX_GAS_LIMIT_CAP + reservoir); + for code in [transfers_everything_to(CONTRACT), creates_everything()] { + for limit in [300_000, 400_000, 600_000, 800_000, 1_000_000, 5_000_000] + .into_iter() + .chain(above_the_cap) + { + let outcome = + execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, limit)); + if let Some(reservoir) = limit.checked_sub(TX_GAS_LIMIT_CAP) { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.reservoir_remaining, + reservoir.saturating_sub(outcome.gas.state + outcome.gas.history), + "at a {limit} gas limit: the reservoir paid what it could of state and history", + ); + } + assert_eq!( + outcome.gas.history, + body(0) + outcome.usage.write_records * WRITE_RECORD_SIZE * CPHB, + "at a {limit} gas limit: the records kept are the history paid", + ); + assert_eq!( + outcome.gas.history_bytes, + TX_BODY_SIZE + outcome.usage.write_records * WRITE_RECORD_SIZE, + "at a {limit} gas limit: and the bytes reported", + ); + } + } +} + +/* ---------- the writes every transaction makes ---------- */ + +/// The transaction body carries the writes every transaction makes whatever it runs: the sender's +/// account, and the four accounts its fees are credited to. +/// +/// They are in the body rather than charged where they happen because the body is priced before +/// the transaction runs, when how many of the four are actually credited is not yet known — a +/// zero fee credits none, and a beneficiary that is one of the vaults is one account, not two. +/// The body carries the bound; nothing counts them again afterwards. +#[test] +fn test_the_body_carries_the_writes_every_transaction_makes() { + if runs_at_measurement_prices() { + return; + } + assert_eq!(TX_BODY_SIZE, TX_BASE_SIZE + TX_FIXED_WRITE_RECORDS * WRITE_RECORD_SIZE); + assert_eq!(TX_BODY_SIZE, 110 + 5 * 40); + + // A transaction that actually pays a fee credits the beneficiary and the fee vaults, and + // records none of them: what it pays is what a fee-free transaction pays. + let db = || funded().account_code(CALLEE, Bytes::new()); + let free = execute(db(), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let paid = execute(db(), { + let mut tx = call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); + tx.0.base.gas_price = 10; + tx + }); + + assert!(free.result.is_success() && paid.result.is_success()); + assert_eq!(free.gas.history, body(0), "the body, and the body alone"); + assert_eq!(paid.gas.history, free.gas.history, "the fee recipients are already in the body"); + assert_eq!(paid.usage.write_records, 0, "and none of them is recorded again"); +} + +/// A deposit credits no fee recipient at all, and is exempt from history besides: it pays for +/// neither the body nor anything the body carries. +#[test] +fn test_a_deposit_pays_for_none_of_the_bodys_writes() { + if runs_at_measurement_prices() { + return; + } + let mut tx = call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); + tx.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); + let outcome = execute(funded().account_code(CALLEE, Bytes::new()), tx); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history, 0); + assert_eq!(outcome.usage.write_records, 0); +} + +/// The body carries a bound on the fee recipients, not a count of them, so a beneficiary that is +/// one of the fee vaults is not something anything has to notice: the two transactions pay the +/// same history, and neither reads a recipient to find out. +#[test] +fn test_a_beneficiary_that_is_a_fee_vault_changes_nothing() { + if runs_at_measurement_prices() { + return; + } + use op_revm::constants::BASE_FEE_RECIPIENT; + let db = || funded().account_code(CALLEE, Bytes::new()); + let paying = |beneficiary| { + let mut tx = call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT); + tx.0.base.gas_price = 10; + let ctx = crate::common::context(db()) + .with_block(revm::context::BlockEnv { beneficiary, ..crate::common::block() }); + mega_evm::MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is valid") + }; + let distinct = paying(address!("00000000000000000000000000000000000c0ffe")); + let a_vault = paying(BASE_FEE_RECIPIENT); + + assert!(distinct.result.is_success() && a_vault.result.is_success()); + assert_eq!(distinct.gas.history, body(0)); + assert_eq!(a_vault.gas.history, distinct.gas.history); + assert_eq!(a_vault.usage.write_records, 0); +} diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs new file mode 100644 index 000000000..9de582130 --- /dev/null +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -0,0 +1,308 @@ +//! The ledgers above the EIP-8037 execution cap, where the reservoir is what pays. +//! +//! A transaction whose gas limit exceeds the 200,000,000 execution cap carries the excess as an +//! EIP-8037 reservoir, and every state and history charge draws on it before it touches regular +//! gas. Below the cap the reservoir is empty, every charge spills straight onto regular gas, and +//! a charge that is silently given back looks exactly like a charge that was made and kept. +//! +//! So the rule this lane carries, and the next mechanism inherits: **every ledger invariant gets +//! at least one case above the cap**. Each holds its transaction to +//! +//! ```text +//! reservoir_remaining == gas_limit - TX_GAS_LIMIT_CAP - state - history +//! ``` +//! +//! and to the same regular ledger as the same program run below the cap. A charge undone behind +//! the ledger's back is reservoir the transaction never paid for, and this identity is the only +//! place it shows. +//! +//! The four cases here are the ones the frame-start charge needs, because it is the one site that +//! charges history from outside the frame the charge belongs to: a value call, a nested creation, +//! a child that reverts, and a call an interceptor answers without a frame. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + LimitUsage, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{CALL, CREATE, GAS, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}; + +use crate::common::{ + body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000700000"); +const CALLEE: Address = address!("0000000000000000000000000000000000700001"); +const CONTRACT: Address = address!("0000000000000000000000000000000000700002"); + +/// The gas limit above the execution cap, and the reservoir it leaves. +const RESERVOIR: u64 = 100_000_000; +const ABOVE_CAP: u64 = TX_GAS_LIMIT_CAP + RESERVOIR; + +/// A gas limit below the execution cap, where the reservoir is empty and every charge spills onto +/// regular gas. +const BELOW_CAP: u64 = 50_000_000; + +const CPHB: u64 = COST_PER_HISTORY_BYTE; + +/// The history a transaction's body costs. +const BODY: u64 = TX_BODY_SIZE * CPHB; + +/// The history one write record costs. +const RECORD: u64 = WRITE_RECORD_SIZE * CPHB; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(CALLEE, U256::from(10_000_000)) +} + +/// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`. +fn transfers_to(target: Address) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(target) + .append(GAS) + .append(CALL) + .append(POP) + .append(STOP) + .build() +} + +/// `CREATE` of empty init code carrying one wei, discarding the address, then `STOP`. +fn creates() -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .append(CREATE) + .append(POP) + .append(STOP) + .build() +} + +/// A one-wei call to `MegaAccessControl`, which its interceptor refuses before any frame runs. +fn calls_a_refusing_interceptor() -> Bytes { + BytecodeBuilder::default() + .mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append(PUSH0) + .append(PUSH1) + .append(1u8) + .push_address(ACCESS_CONTROL_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP) + .append(STOP) + .build() +} + +/// Runs the same transaction above and below the execution cap and holds the two to the same +/// ledgers: above the cap the reservoir pays what regular gas pays below it, and the reservoir +/// left over is the gas limit above the cap less the state and history the ledgers report. +/// +/// Returns the above-the-cap outcome, for a case that has more to say about it. +#[track_caller] +fn assert_the_reservoir_pays_what_regular_gas_pays( + name: &str, + db: impl Fn() -> MemoryDatabase, +) -> MegaTransactionOutcome { + let above = execute(db(), call(CALLER, CALLEE, U256::ZERO, ABOVE_CAP)); + let below = execute(db(), call(CALLER, CALLEE, U256::ZERO, BELOW_CAP)); + + assert_eq!(above.result.is_success(), below.result.is_success(), "{name}: success"); + assert_eq!(above.usage, below.usage, "{name}: what the transaction kept"); + assert_eq!(above.gas.history, below.gas.history, "{name}: the history ledger"); + assert_eq!(above.gas.state, below.gas.state, "{name}: the state ledger"); + assert_eq!(above.gas.regular, below.gas.regular, "{name}: the regular ledger"); + assert_eq!(below.gas.reservoir_remaining, 0, "{name}: below the cap there is no reservoir"); + assert_eq!( + above.gas.reservoir_remaining, + ABOVE_CAP - TX_GAS_LIMIT_CAP - above.gas.state - above.gas.history, + "{name}: the reservoir paid exactly the state and the history the ledgers report", + ); + above +} + +/// A value `CALL` charges its caller for two write records. Above the cap the reservoir pays +/// them, and the frame it starts inherits the reservoir the charge left — not the one the caller +/// held before it, which the frame would hand back on return. +#[test] +fn test_a_value_call_pays_its_records_out_of_the_reservoir() { + if runs_at_measurement_prices() { + return; + } + let code = transfers_to(CONTRACT); + let outcome = assert_the_reservoir_pays_what_regular_gas_pays("a value call", || { + funded().account_code(CALLEE, code.clone()) + }); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 2, "the caller's account and the recipient's"); + assert_eq!(outcome.gas.history, BODY + 2 * RECORD); + assert_eq!(outcome.gas.state, ACCOUNT_STATE_GAS, "the recipient is a new account"); +} + +/// A nested creation charges its creator for the created account and for its own nonce, and the +/// creation frame inherits the reservoir that charge left. +#[test] +fn test_a_nested_creation_pays_its_records_out_of_the_reservoir() { + if runs_at_measurement_prices() { + return; + } + let code = creates(); + let outcome = assert_the_reservoir_pays_what_regular_gas_pays("a nested creation", || { + funded().account_code(CALLEE, code.clone()) + }); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 2, "the created account and the creator's nonce"); + assert_eq!(outcome.gas.history, BODY + 2 * RECORD); +} + +/// A child that reverts keeps none of the records its caller paid for, so the charge goes back to +/// the reservoir it came from — and goes back once. The net history is the body alone. +#[test] +fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { + if runs_at_measurement_prices() { + return; + } + let code = transfers_to(CONTRACT); + let outcome = + assert_the_reservoir_pays_what_regular_gas_pays("a value call whose child reverts", || { + funded() + .account_code(CALLEE, code.clone()) + .account_code(CONTRACT, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + }); + + assert!(outcome.result.is_success(), "the caller survives its child's revert"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "the reverted transfer kept nothing but the body" + ); + assert_eq!(outcome.gas.history, BODY, "the body alone"); + assert_eq!( + outcome.gas.reservoir_remaining, + RESERVOIR - BODY, + "the transfer's records cost the reservoir nothing in the end", + ); +} + +/// A value call a system contract's interceptor refuses never starts a frame: its lane is empty +/// and the whole charge comes back. It is the path where the caller is paid back twice if the +/// frame inherited the caller's reservoir from before the charge, because the empty lane refills +/// what the adoption already restored. +#[test] +fn test_an_intercepted_value_call_gives_its_records_back_once() { + if runs_at_measurement_prices() { + return; + } + let code = calls_a_refusing_interceptor(); + let outcome = assert_the_reservoir_pays_what_regular_gas_pays( + "a value call an interceptor refuses", + || { + funded() + .account_code(CALLEE, code.clone()) + .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + }, + ); + + assert!(outcome.result.is_success(), "the caller survives the refusal"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "the refused call wrote nothing but the body" + ); + assert_eq!(outcome.gas.history, BODY, "the body alone"); + assert_eq!( + outcome.gas.reservoir_remaining, + RESERVOIR - BODY, + "the refused call's records cost the reservoir nothing in the end", + ); +} + +/* ---------- the body, drawn from the reservoir first ---------- */ + +/// `GAS; PUSH0; MSTORE; PUSH1 32; PUSH0; RETURN`: answers with the regular gas the frame has +/// left after the `GAS` itself, and charges nothing else — no record, no log, no state. +fn answers_its_gas() -> Bytes { + BytecodeBuilder::default() + .append(GAS) + .append(PUSH0) + .append(MSTORE) + .push_number(32_u8) + .append(PUSH0) + .append(RETURN) + .build() +} + +/// What [`answers_its_gas`] spends: `GAS` 2, `PUSH0` 2, `MSTORE` 3 and the first word of memory +/// 3, `PUSH1` 3, `PUSH0` 2, `RETURN` 0. +const ANSWERING: u64 = 2 + 2 + 3 + 3 + 3 + 2; + +/// The intrinsic regular gas of a call carrying no data: `TX_BASE_COST` 12,000 and 3,000 for the +/// recipient's access. +const INTRINSIC: u64 = 12_000 + 3_000; + +/// The body's history gas is taken from the reservoir first, and only its excess from the regular +/// budget [S4.4]; a reservoir short of the body is spent to the last gas, one of exactly the body +/// too, and one a gas larger keeps that gas [S4.7]. A body-only transaction shows it: the first +/// frame's `GAS` is the regular budget — the execution cap less the intrinsic gas, less the +/// excess the reservoir did not cover, less the `GAS` itself — and not the reservoir [S4.8]. +/// +/// Every figure is by hand (`constants`: the execution cap and the body's history at the price in +/// effect, which is 310 × 88 at the spec's price): the regular ledger is the intrinsic gas and +/// the program, whichever pool paid the body, because a charge that spilled stays on its own +/// ledger; the receipt adds the body. +#[test] +fn test_the_body_draws_the_reservoir_first_and_only_its_excess_from_regular_gas() { + // A body that costs nothing leaves the reservoir nothing to draw, and one priced at a fraction + // of a gas may round to nothing. + if history_is_free() || history_rounds() { + return; + } + let body = body_history(0); + let db = || funded().account_code(CALLEE, answers_its_gas()); + + for reservoir in [1, body - 1, body, body + 1] { + let name = format!("a reservoir of {reservoir} against a body of {body}"); + let excess = body.saturating_sub(reservoir); + let outcome = execute(db(), call(CALLER, CALLEE, U256::ZERO, TX_GAS_LIMIT_CAP + reservoir)); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + + let gas_seen = U256::from_be_slice(outcome.result.output().expect("the answer")); + assert_eq!( + gas_seen, + U256::from(TX_GAS_LIMIT_CAP - INTRINSIC - excess - 2), + "{name}: GAS is the regular budget less the excess, not the reservoir", + ); + assert_eq!( + outcome.gas.reservoir_remaining, + reservoir.saturating_sub(body), + "{name}: the reservoir paid the body as far as it went", + ); + assert_eq!(outcome.gas.history, body, "{name}: the history ledger is the body"); + assert_eq!(outcome.gas.state, 0, "{name}: no state"); + assert_eq!( + outcome.gas.regular, + INTRINSIC + ANSWERING, + "{name}: the regular ledger is the intrinsic gas and the program, whoever paid the body", + ); + assert_eq!(outcome.gas.gas_used, INTRINSIC + ANSWERING + body, "{name}: the receipt"); + assert_eq!(outcome.usage.write_records, 0, "{name}: body only"); + } + + if runs_at_measurement_prices() { + return; + } + assert_eq!(body, 310 * 88, "the body at the spec's price"); + assert_eq!(INTRINSIC + ANSWERING + body, 42_295, "the empty call's 42,280 and the program"); +} diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs new file mode 100644 index 000000000..7a3ff1e39 --- /dev/null +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -0,0 +1,240 @@ +//! Two costs Satin inherits from Ethereum where the legacy engine departed from it. +//! +//! - **A preload-warm address is charged warm.** The precompiles, the block beneficiary and an +//! access-list address are warm from the transaction's start, and the first call to one costs +//! what the second does. The legacy engine's pricing inspected the callee's account before the +//! opcode's own access and charged that first touch cold; Satin's pricing hook inspects no +//! account, so the warmth revm preloads is what the opcode sees. +//! - **A call or creation forwards all but a 64th of its gas**, as EIP-150 has it, where the legacy +//! engine forwarded 98/100. The 98% share lives on in the data-size and KV frame budgets, which +//! are not gas. +//! +//! Both are read off the regular ledger, which is the gas the opcodes charge. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{CALL, CALLCODE, CREATE, GAS, POP, PUSH0, STATICCALL, STOP}, + context::{ + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + Database, Inspector, +}; + +use crate::{ + common::{block, call, context, execute}, + salt::entry, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000e20000"); +const CONTRACT: Address = address!("0000000000000000000000000000000000e20001"); +/// An account that exists and holds no code, never warmed by anything but an access list. +const EXISTING: Address = address!("0000000000000000000000000000000000e20002"); +/// The identity precompile. +const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); + +/// What the first touch of an address costs over a warm one: the schedule's cold account access +/// less its warm read. +fn cold_over_warm() -> u64 { + entry(GasId::cold_account_additional_cost()) +} + +/* ---------- preload-warm addresses ---------- */ + +/// `units` identical calls of `opcode` to `to`, each forwarding 50,000 and dropping its status. +fn calls(opcode: u8, to: Address, units: usize) -> Bytes { + let mut code = BytecodeBuilder::default(); + for _ in 0..units { + code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + if opcode != STATICCALL { + code = code.append(PUSH0); + } + code = code.push_address(to).push_number(50_000_u32).append(opcode).append(POP); + } + code.append(STOP).build() +} + +/// A call from `CALLER` to `CONTRACT` carrying `access_list`, as an EIP-2930 transaction. +fn with_access_list(access_list: AccessList) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit: 10_000_000 + crate::common::body_history(100), + access_list, + ..Default::default() + })) +} + +/// How much more the first of the calls `opcode` makes to `to` costs than the second, on the +/// regular ledger: the 0-, 1- and 2-call programs are run and differenced, so what every call +/// costs alike cancels, and what is left is the first touch's price over a warm touch's. +fn first_call_over_second(opcode: u8, to: Address, tx: impl Fn() -> MegaTransaction) -> i64 { + let [none, one, two] = [0, 1, 2].map(|units| { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(EXISTING, U256::from(1)) + .account_code(CONTRACT, calls(opcode, to, units)); + let outcome = execute(db, tx()); + assert!(outcome.result.is_success(), "{units} calls: {:?}", outcome.result); + outcome.gas.regular as i64 + }); + (one - none) - (two - one) +} + +fn plain() -> MegaTransaction { + call(CALLER, CONTRACT, U256::ZERO, 10_000_000 + crate::common::body_history(0)) +} + +/// The control the other cases are measured against: an address nothing preloads costs the cold +/// price on its first touch, so the measurement sees a cold touch where there is one. +#[test] +fn test_the_first_call_to_an_address_nothing_warmed_is_charged_cold() { + assert_eq!(first_call_over_second(CALL, EXISTING, plain), cold_over_warm() as i64); +} + +/// A precompile is warm from the transaction's start: the first `CALL` to one costs what the +/// second does. +#[test] +fn test_the_first_call_to_a_precompile_is_charged_warm() { + assert_eq!(first_call_over_second(CALL, IDENTITY, plain), 0); +} + +/// So does the first `STATICCALL`. +#[test] +fn test_the_first_staticcall_to_a_precompile_is_charged_warm() { + assert_eq!(first_call_over_second(STATICCALL, IDENTITY, plain), 0); +} + +/// An access-list address is warm from the start whether it is listed with storage keys or +/// without: the first `CALL` to it costs what the second does, where without the list it pays the +/// cold price. +#[test] +fn test_the_first_call_to_an_access_list_address_is_charged_warm() { + let listed = |keys: Vec| { + move || { + with_access_list(AccessList(vec![AccessListItem { + address: EXISTING, + storage_keys: keys.clone(), + }])) + } + }; + assert_eq!(first_call_over_second(CALL, EXISTING, listed(vec![])), 0, "without keys"); + assert_eq!(first_call_over_second(CALL, EXISTING, listed(vec![B256::ZERO])), 0, "with a key"); +} + +/// The same for `CALLCODE`: its first touch of an access-list address listed without keys costs +/// what the second does. +#[test] +fn test_the_first_callcode_to_an_access_list_address_is_charged_warm() { + let listed = || { + with_access_list(AccessList(vec![AccessListItem { + address: EXISTING, + storage_keys: vec![], + }])) + }; + assert_eq!(first_call_over_second(CALLCODE, EXISTING, listed), 0); +} + +/// The block beneficiary is warm from the start (EIP-3651): the first `CALL` to it costs what the +/// second does. The call reads the beneficiary's account, which gas detention marks, but a mark +/// charges nothing. +#[test] +fn test_the_first_call_to_the_beneficiary_is_charged_warm() { + let beneficiary = block().beneficiary; + assert_eq!(first_call_over_second(CALL, beneficiary, plain), 0); +} + +/* ---------- forwarding ---------- */ + +/// The regular gas a frame holds as its call or creation starts, and what it forwards. +#[derive(Default)] +struct Forward { + opcode: u8, + held: Option, + forwarded: Option, +} + +impl Inspector, EthInterpreter> for Forward { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.opcode = interp.bytecode.opcode(); + if matches!(self.opcode, CALL | CREATE) { + self.held = Some(interp.gas.remaining()); + } + } + + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + if inputs.target_address == EXISTING { + self.forwarded = Some(inputs.gas_limit); + } + None + } + + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.forwarded = Some(inputs.gas_limit()); + None + } +} + +/// Runs `CONTRACT` holding `code` above the execution cap, where the reservoir pays every state +/// and history charge, and returns the regular gas held at the opcode and the gas forwarded. +fn forward_of(code: Bytes) -> (u64, u64, MegaTransactionOutcome) { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db)).with_inspector(Forward::default()); + let outcome = evm + .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 5 * TX_GAS_LIMIT_CAP)) + .expect("the transaction is valid"); + let forward = evm.inspector(); + (forward.held.expect("the opcode ran"), forward.forwarded.expect("a frame started"), outcome) +} + +/// A `CALL` given all the gas forwards all but a 64th of what its caller holds once the call's own +/// charge — the cold access to its target — is paid. +#[test] +fn test_a_call_forwards_all_but_a_64th_of_its_gas() { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(EXISTING) + .append_many([GAS, CALL, STOP]) + .build(); + let (held, forwarded, outcome) = forward_of(code); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let left = held - entry(GasId::warm_storage_read_cost()) - cold_over_warm(); + assert_eq!(forwarded, left - left / 64); +} + +/// A `CREATE` forwards all but a 64th of what its creator holds once the creation's own charges — +/// the `create` entry, EIP-3860's word and the memory the init code occupies — are paid; the +/// created account's state gas comes out of the reservoir. +#[test] +fn test_a_creation_forwards_all_but_a_64th_of_its_gas() { + let code = BytecodeBuilder::default() + .push_number(10_u8) + .append_many([PUSH0, PUSH0, CREATE, STOP]) + .build(); + let (held, forwarded, outcome) = forward_of(code); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let left = held - entry(GasId::create()) - entry(GasId::initcode_per_word()) - 3; + assert_eq!(forwarded, left - left / 64); +} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index b80a5ad8c..bfe002245 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -4,8 +4,8 @@ use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, GasInspector, MemoryDatabase}, - DeclaredObserver, MegaContext, MegaEvm, FORBIDDEN_CREATE_REVIVAL, + test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase}, + DeclaredObserver, MegaContext, MegaEvm, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, @@ -19,13 +19,27 @@ use revm::{ }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; -use crate::common::{call, context}; +use crate::common::{ + account_state_gas, body_history, call, context, execute_under, history, slot_state_gas, +}; const CALLER: Address = address!("0000000000000000000000000000000000400000"); const A: Address = address!("00000000000000000000000000000000000000A1"); const B: Address = address!("00000000000000000000000000000000000000B1"); const FAKE: Address = address!("00000000000000000000000000000000000FA4E0"); -const GAS_LIMIT: u64 = 1_000_000; + +/// 1,000,000 of regular gas on top of what these scenarios add at the byte prices in effect: two +/// fresh slots and a new account, the body and four records, and 64 times the history of two +/// records, which a call or a creation that forwards all but a 64th of its gas pays for the frame +/// it starts from the 64th it keeps. +fn gas_limit() -> u64 { + 1_000_000 + + 2 * slot_state_gas() + + account_state_gas() + + body_history(0) + + history(4 * WRITE_RECORD_SIZE) + + 64 * history(2 * WRITE_RECORD_SIZE) +} /// Calls `B` with `value` and stores the call's success flag in slot 0. fn call_b_and_store_flag(value: u64) -> Bytes { @@ -143,7 +157,7 @@ fn run_with, EthInterpreter>>( EVMError, > { let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); - evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)) + evm.transact_raw(call(CALLER, A, U256::from(value), gas_limit())) } fn writes_two_slots() -> MemoryDatabase { @@ -197,7 +211,7 @@ fn test_short_circuited_value_call_moves_no_value() { .account_balance(A, U256::from(100)); let mut evm = MegaEvm::new(context(db)) .with_inspector(Rewriter { answer_calls: true, ..Default::default() }); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let result = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); assert!(result.result.is_success()); assert_eq!( result.state[&A].storage[&U256::ZERO].present_value(), @@ -226,27 +240,63 @@ fn test_create_end_address_rewrite_reaches_the_caller_not_the_code() { assert!(result.state.get(&FAKE).is_none_or(|fake| fake.info.is_empty_code_hash())); } -/// A failed creation rewritten into a success is refused: the transaction fails with the -/// refusal. +/// A creation its own frame budget stops, revived by an inspector: the stop is the creation's alone +/// and no stop of the transaction, so the creation failed as any failed creation does and its +/// revival settles as the failure — the transaction is not refused. Under a data-size limit of the +/// body and 122 bytes, the creator may keep 122 and the creation 98% of them, 119: the creation's +/// start makes two records, 80 bytes, and the write in its init code is a third, 40 more, over its +/// budget, which the transaction's limit still holds. Under the body and 160 bytes the budget holds +/// it, and so does the transaction's limit once the creator stores the address, a fourth record: +/// the same creation succeeds. #[test] -fn test_create_revival_is_refused() { - let db = MemoryDatabase::default() - .account_code(A, create_and_store_address(&[PUSH0, PUSH0, REVERT])); - let result = run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0); - match result { - Err(EVMError::Custom(message)) => { - assert!(message.starts_with(FORBIDDEN_CREATE_REVIVAL), "{message}") - } - other => panic!("expected the refusal, got {other:?}"), - } - - // A creation that succeeded may be rewritten freely; the refusal is for revivals only. - let db = MemoryDatabase::default() - .account_code(A, create_and_store_address(&[0x60, 0x01, 0x60, 0x00, 0xf3])); - assert!(run_with(db, Rewriter { create_succeeds: true, ..Default::default() }, 0) - .unwrap() - .result - .is_success()); +fn test_a_creation_its_frame_budget_stops_may_be_revived() { + // A write of 1 to slot 1, short enough for `create_and_store_address`. + let init_code = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(1_u8) + .append(SSTORE) + .stop() + .build(); + let db = || MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); + let under = |bytes: u64| { + mega_evm::EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + bytes) + }; + let plain = + |bytes: u64| execute_under(db(), call(CALLER, A, U256::ZERO, gas_limit()), under(bytes)); + let created = |outcome: &mega_evm::MegaTransactionOutcome| { + outcome.state[&A] + .storage + .get(&U256::ZERO) + .is_some_and(|slot| !slot.present_value().is_zero()) + }; + let roomy = plain(160); + assert!(roomy.result.is_success() && created(&roomy), "{:?}", roomy.result); + + // Without the inspector the creation fails alone: its creator stores no address and succeeds, + // and the transaction is not stopped. + let stopped = plain(122); + assert!(stopped.result.is_success(), "{:?}", stopped.result); + assert_eq!(stopped.limit_exceeded, None, "a frame budget below is no stop"); + assert!(!created(&stopped), "the creation failed"); + + let limits = under(122); + let revived = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())) + .unwrap(); + assert!(revived.result.is_success(), "{:?}", revived.result); + assert_eq!(revived.limit_exceeded, None, "and the revival is no stop either"); + let stored = revived.state[&A].storage[&U256::ZERO].present_value(); + assert_eq!(Address::from_word(stored.into()), FAKE, "the creator got the revived address"); + let created_address = A.create(0); + assert!( + revived + .state + .get(&created_address) + .is_none_or(|account| account.info.is_empty_code_hash() && + account.storage.values().all(|slot| slot.present_value().is_zero())), + "the creation kept none of its writes" + ); } /// A declared observer that writes back fails its declaration in a debug build. @@ -257,7 +307,7 @@ fn test_false_declaration_fails_in_debug() { let rewriter = Rewriter { charge_after_sstore: 1, ..Default::default() }; let mut evm = MegaEvm::new(context(writes_two_slots())) .with_trusted_inspector(DeclaredObserver(rewriter)); - let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } /// A declared call rewrite fails too. @@ -270,7 +320,7 @@ fn test_false_declaration_of_a_call_rewrite_fails_in_debug() { .account_code(B, Bytes::from_static(&[INVALID])); let rewriter = Rewriter { call_succeeds: true, ..Default::default() }; let mut evm = MegaEvm::new(context(db)).with_trusted_inspector(DeclaredObserver(rewriter)); - let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } /// A declared observer that only reads produces the transaction no inspector produces. @@ -282,15 +332,41 @@ fn test_declared_tracer_changes_nothing() { .account_code(B, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) }; let plain = - MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); let mut evm = MegaEvm::new(context(db())).with_trusted_inspector(DeclaredObserver(tracer)); - let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); assert_eq!(plain.result, traced.result); assert_eq!(plain.state, traced.state); assert_eq!(evm.inspector().0.traces().nodes().len(), 2, "the tracer saw both frames"); } +/// The gas inspector of the test utilities records a byte no opcode is defined for as `INVALID`, +/// and keeps the byte, so the undefined byte is told from the designated invalid opcode. +#[test] +fn test_the_gas_inspector_keeps_the_byte_of_an_undefined_opcode() { + const UNDEFINED: u8 = 0x21; + assert!(revm::bytecode::opcode::OpCode::new(UNDEFINED).is_none(), "no opcode is defined"); + for (code, undefined) in [(UNDEFINED, true), (INVALID, false)] { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(A, Bytes::from(vec![PUSH0, code])); + let mut evm = MegaEvm::new(context(db)).with_inspector(GasInspector::new()); + let outcome = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); + assert!(outcome.result.is_halt(), "{:?}", outcome.result); + let records = evm.inspector().records(); + let last = records.last().expect("the frame ran"); + assert_eq!((last.opcode.get(), last.byte), (INVALID, code)); + assert_eq!(last.is_undefined(), undefined); + assert!(!records[0].is_undefined(), "a defined opcode carries its own byte"); + assert_eq!( + format!("{last:?}").starts_with("UNDEFINED(0x21)"), + undefined, + "the rendering names the byte: {last:?}" + ); + } +} + /// The admission gate: only an enabled inspector that did not arrive declared is a rewriting one. #[test] fn test_has_rewriting_inspector_truth_table() { @@ -344,14 +420,14 @@ impl Inspector for Pairs { } /// Every frame the inspector sees start, it sees end: a frame that ran, one answered before it -/// ran (a value transfer the sender cannot fund, a latched transaction's first frame), and a -/// creation. +/// ran (a value transfer the sender cannot fund, a first frame whose start crosses the data-size +/// limit), and a creation. #[test] fn test_frame_start_and_end_stay_paired() { let pairs = |db: MemoryDatabase, limits: mega_evm::EvmTxRuntimeLimits, value: u64| { let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) .with_inspector(Pairs::default()); - let _ = evm.transact_raw(call(CALLER, A, U256::from(value), GAS_LIMIT)).unwrap(); + let _ = evm.transact_raw(call(CALLER, A, U256::from(value), gas_limit())).unwrap(); let pairs = evm.inspector(); (pairs.calls, pairs.call_ends, pairs.creates, pairs.create_ends) }; @@ -361,8 +437,9 @@ fn test_frame_start_and_end_stay_paired() { let creates = MemoryDatabase::default().account_code(A, create_and_store_address(&[0x00])); assert_eq!(pairs(creates, no_limits, 0), (1, 1, 1, 1)); let funded = MemoryDatabase::default().account_balance(CALLER, U256::from(10)); - let latched = no_limits.with_tx_data_size_limit(0); - assert_eq!(pairs(funded, latched, 1), (1, 1, 0, 0), "the stopped first frame ends too"); + // The body fits; the record and the transfer log of the first frame's value do not. + let stopped_at_its_start = no_limits.with_tx_data_size_limit(mega_evm::TX_BODY_SIZE); + assert_eq!(pairs(funded, stopped_at_its_start, 1), (1, 1, 0, 0), "the stopped frame ends too"); } /// Counts every callback it gets. @@ -457,10 +534,10 @@ fn busy_contract() -> MemoryDatabase { #[test] fn test_declared_observer_forwards_every_callback() { let mut plain = MegaEvm::new(context(busy_contract())).with_inspector(Recorder::default()); - plain.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + plain.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let mut declared = MegaEvm::new(context(busy_contract())) .with_trusted_inspector(DeclaredObserver::new(Recorder::default())); - declared.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + declared.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let seen = plain.inspector().clone(); assert_eq!(declared.inspector().0, seen); @@ -481,7 +558,39 @@ fn test_declared_observer_forwards_every_callback() { assert_eq!(DeclaredObserver::new(Recorder::default()).into_inner(), Recorder::default()); } +/// Keeps every log handed to `Inspector::log`, the callback for a log journaled outside an +/// instruction. +#[derive(Debug, Default)] +struct FrameStartLogs(Vec); + +impl Inspector, EthInterpreter> for FrameStartLogs { + fn log(&mut self, _: &mut MegaContext, log: Log) { + self.0.push(log); + } +} + +/// A declared observer forwards the EIP-7708 transfer logs a frame's start journals: the +/// transaction's value into `A`, whose frame runs, and `A`'s value into `B`, an account with no +/// code, whose frame is answered without running. +#[test] +fn test_declared_observer_forwards_the_transfer_logs_of_frame_starts() { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(5)) + .account_code(A, call_b_and_store_flag(2)); + let mut evm = MegaEvm::new(context(db)) + .with_trusted_inspector(DeclaredObserver::new(FrameStartLogs::default())); + let outcome = evm.transact_raw(call(CALLER, A, U256::from(5), gas_limit())).unwrap(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + evm.inspector().0 .0, + vec![transfer_log(CALLER, A, U256::from(5)), transfer_log(A, B, U256::from(2))] + ); +} + /// Edits a frame's inputs, writes to the journal, or rewrites a frame result, one per flag. +/// +/// Only the debug-build tests below use it: a release build does not check declarations. +#[cfg(debug_assertions)] #[derive(Default)] struct Writer { edit_inputs: bool, @@ -489,6 +598,7 @@ struct Writer { rewrite_frame_end: bool, } +#[cfg(debug_assertions)] impl Inspector, EthInterpreter> for Writer { fn step(&mut self, _interp: &mut Interpreter, context: &mut MegaContext) { if self.log_in_step { @@ -521,10 +631,11 @@ impl Inspector, EthInterpreter> for Writer { } } +#[cfg(debug_assertions)] fn run_declared(writer: Writer) { let mut evm = MegaEvm::new(context(writes_two_slots())).with_trusted_inspector(DeclaredObserver(writer)); - let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } /// A declared observer that edits a frame's inputs fails its declaration in a debug build. @@ -551,3 +662,112 @@ fn test_false_declaration_of_a_journal_write_fails_in_debug() { fn test_false_declaration_of_a_frame_end_rewrite_fails_in_debug() { run_declared(Writer { rewrite_frame_end: true, ..Default::default() }); } + +/// Counts the frames an inspector sees start and the instructions it sees run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Seen { + frames: usize, + steps: usize, +} + +impl Inspector for Seen { + fn step(&mut self, _: &mut Interpreter, _: &mut CTX) { + self.steps += 1; + } + + fn frame_start( + &mut self, + _: &mut CTX, + _: &mut revm::interpreter::FrameInput, + ) -> Option { + self.frames += 1; + None + } +} + +/// A system call runs on the handler's plain system-call path wherever the engine and alloy-evm +/// make one — the pre-block calls' entry point, alloy-evm's and revm's — so the EVM's inspector +/// sees nothing of it, as alloy-evm's own EVMs have it. revm's inspecting entry point is the one +/// that hands it to the inspector, and there the call keeps every exemption a system call has: a +/// data-size limit of zero, which would stop a transaction before its first frame, stops nothing. +#[test] +fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { + use revm::{InspectSystemCallEvm, SystemCallEvm}; + let code = BytecodeBuilder::default().append_many([PUSH0, revm::bytecode::opcode::POP]).stop(); + let db = MemoryDatabase::default().account_code(A, code.build()); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0); + let mut evm = + MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(Seen::default()); + + let result = evm.transact_system_call_with_gas_limit(CALLER, A, Bytes::new(), 30_000_000); + assert!(result.unwrap().result.is_success()); + assert!(Evm::transact_system_call(&mut evm, CALLER, A, Bytes::new()) + .unwrap() + .result + .is_success()); + assert!(SystemCallEvm::system_call_one_with_caller(&mut evm, CALLER, A, Bytes::new()) + .unwrap() + .is_success()); + assert_eq!(*evm.inspector(), Seen::default(), "none of them ran the inspector"); + + let inspected = InspectSystemCallEvm::inspect_one_system_call_with_caller( + &mut evm, + CALLER, + A, + Bytes::new(), + ) + .unwrap(); + assert!(inspected.is_success(), "{inspected:?}"); + assert_eq!(*evm.inspector(), Seen { frames: 1, steps: 3 }, "PUSH0, POP, STOP"); + assert!( + evm.ctx().additional_limit().limit_exceeded().is_none(), + "no limit holds a system call" + ); +} + +/// Answers every call itself with a success, and counts the answers. +#[derive(Default)] +struct SkipAllCallsInspector { + answered: usize, +} + +impl Inspector for SkipAllCallsInspector { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + self.answered += 1; + Some(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + } +} + +/// A body over the data-size limit is rejected at validation whether or not an inspector would +/// answer the transaction's first frame: the inspector is never asked, and the refusal is the one +/// the transaction gets without it. +#[test] +fn test_intrinsic_data_size_overflow_with_inspector_early_return() { + const LIMIT: u64 = 100; + const TX_GAS_LIMIT: u64 = 100_000_000; + let db = || { + MemoryDatabase::default() + .account_code(A, Bytes::from_static(&[revm::bytecode::opcode::STOP])) + }; + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(LIMIT); + let tx = call(CALLER, A, U256::ZERO, TX_GAS_LIMIT); + assert!(mega_evm::transaction_body_bytes(&tx) > LIMIT, "the body alone crosses the limit"); + + let plain = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx.clone()) + .expect_err("rejected"); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(SkipAllCallsInspector::default()); + let inspected = evm.execute_transaction(tx).expect_err("rejected"); + + assert_eq!(evm.inspector().answered, 0, "the inspector never saw a frame"); + assert_eq!(format!("{inspected:?}"), format!("{plain:?}")); + assert!(format!("{plain:?}").contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{plain:?}"); +} diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs new file mode 100644 index 000000000..7bec7ef3a --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -0,0 +1,423 @@ +//! Four of Foundry's cheatcodes, driven the way Foundry's inspector drives an EVM, on Satin. +//! +//! A test contract calls the cheatcode address with the cheatcode's ABI call; the inspector's +//! `call` hook answers that call itself, on the gas it was forwarded, as Foundry's does — no frame +//! is built — and does what the cheatcode says through the surfaces every inspector has: +//! +//! - `deal(address,uint256)` sets a balance through the journal; +//! - `store(address,bytes32,bytes32)` writes a slot through the journal; +//! - `pauseGasMetering()` / `resumeGasMetering()` hold the calling frame's gas where it was, in +//! `step`, by putting the whole of it back before each instruction, memory expansion aside; +//! - `expectRevert()` rewrites the next call's result in `call_end`: a failure into a success that +//! keeps its revert data, a success into the failure Foundry reports. +//! +//! What each does to Satin's ledgers follows from the inspector contract: a journal write from a +//! callback is on no gas ledger and in no count, a paused region spends no gas of any kind while +//! what it writes is still counted, a failed call `expectRevert` turns into a success settles as +//! the failure on every ledger, and a success it turns into a failure keeps none of its writes. +//! `expectRevert` is honored on a result revm answers without running a frame — a precompile's, a +//! call to an account with no code — as on a frame's. + +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use alloy_sol_types::{sol, SolCall}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + LimitUsage, MegaContext, MegaEvm, MegaTransactionOutcome, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + BALANCE, CALL, GAS, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, SLOAD, SSTORE, + }, + context::{ContextTr, JournalTr}, + context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, + InterpreterResult, + }, + Database, Inspector, +}; + +use crate::{ + common::{call, context}, + salt::entry, +}; + +sol! { + /// The cheatcodes these tests drive, as Foundry's `Vm` interface declares them. + interface Vm { + function deal(address who, uint256 newBalance) external; + function store(address target, bytes32 slot, bytes32 value) external; + function pauseGasMetering() external; + function resumeGasMetering() external; + function expectRevert() external; + } +} + +/// Foundry's cheatcode address. +const CHEATCODES: Address = address!("7109709ecfa91a80626ff3989d68f67f5b1dd12d"); +const CALLER: Address = address!("0000000000000000000000000000000000f00000"); +/// The test contract. +const TEST: Address = address!("0000000000000000000000000000000000f00001"); +/// An account the cheatcodes and calls target. +const TARGET: Address = address!("0000000000000000000000000000000000f00002"); +/// The BN254 addition precompile, which a point off the curve fails. +const ADDITION: Address = address!("0000000000000000000000000000000000000006"); +/// Below the execution cap, where a transaction has no reservoir. +const GAS_LIMIT: u64 = 10_000_000; +/// Foundry's default gas limit for a test, 2^30: above the execution cap, so a test transaction +/// runs with a reservoir. +const FOUNDRY_GAS_LIMIT: u64 = 1 << 30; + +/// The revert data Foundry's `expectRevert` gives a call that did not revert. +const DID_NOT_REVERT: &[u8] = b"call did not revert as expected"; + +/// Foundry's cheatcode handler, cut down to the four cheatcodes these tests use. +#[derive(Default)] +struct Cheatcodes { + /// Whether gas metering is paused. + paused: bool, + /// The gas the paused frame is held at, once its first step after the pause took it. + paused_gas: Option, + /// The journal depth of the frame whose next call `expectRevert` rewrites. + expect_revert_at: Option, + /// How many cheatcode calls were answered. + answered: usize, +} + +impl Inspector, EthInterpreter> for Cheatcodes { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if !self.paused { + return; + } + match self.paused_gas { + None => self.paused_gas = Some(interp.gas), + Some(paused) => { + let memory = *interp.gas.memory(); + interp.gas = paused; + *interp.gas.memory_mut() = memory; + } + } + } + + fn call(&mut self, ctx: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if inputs.target_address != CHEATCODES { + return None; + } + let input = inputs.input.bytes(ctx); + let selector: [u8; 4] = input[..4].try_into().expect("a selector"); + match selector { + Vm::dealCall::SELECTOR => { + let deal = Vm::dealCall::abi_decode(&input).expect("deal's arguments"); + let mut account = ctx.journal_mut().load_account_mut(deal.who).expect("loads"); + account.data.set_balance(deal.newBalance); + } + Vm::storeCall::SELECTOR => { + let store = Vm::storeCall::abi_decode(&input).expect("store's arguments"); + let journal = ctx.journal_mut(); + journal.load_account(store.target).expect("loads"); + let slot = U256::from_be_bytes(store.slot.0); + let value = U256::from_be_bytes(store.value.0); + journal.sstore(store.target, slot, value).expect("stores"); + } + Vm::pauseGasMeteringCall::SELECTOR => self.paused = true, + Vm::resumeGasMeteringCall::SELECTOR => { + self.paused = false; + self.paused_gas = None; + } + Vm::expectRevertCall::SELECTOR => { + self.expect_revert_at = Some(ctx.journal_ref().depth()) + } + _ => panic!("not a cheatcode these tests use"), + } + self.answered += 1; + Some(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Return, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + } + + fn call_end( + &mut self, + ctx: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == CHEATCODES || + self.expect_revert_at != Some(ctx.journal_ref().depth()) + { + return; + } + self.expect_revert_at = None; + let result = &mut outcome.result; + if result.result.is_ok() { + result.result = InstructionResult::Revert; + result.output = Bytes::from_static(DID_NOT_REVERT); + } else { + result.result = InstructionResult::Return; + } + } +} + +/// `code` then a call of the cheatcode `cheat`, its calldata written to memory at offset 0, its +/// success flag dropped. +fn cheat(code: BytecodeBuilder, cheat: impl SolCall) -> BytecodeBuilder { + let calldata = cheat.abi_encode(); + code.mstore(0, &calldata) + .append_many([PUSH0, PUSH0]) + .push_number(calldata.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(CHEATCODES) + .append(GAS) + .append(CALL) + .append(POP) +} + +/// `code` then a call of `target` carrying `input`, written to memory at offset 0, on a million +/// gas — a failure that burns what it was forwarded leaves the rest; the success flag plus one is +/// stored in slot 0 — a fresh slot whichever way the call goes — and the first word of its return +/// data in slot 1. +fn call_and_note(code: BytecodeBuilder, target: Address, input: &[u8]) -> BytecodeBuilder { + code.mstore(0, input) + .append_many([PUSH0, PUSH0]) + .push_number(input.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(target) + .push_number(1_000_000_u64) + .append(CALL) + .push_number(1_u8) + .append(revm::bytecode::opcode::ADD) + .append(PUSH0) + .append(SSTORE) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([PUSH0, revm::bytecode::opcode::MLOAD]) + .push_number(1_u8) + .append(SSTORE) +} + +/// Runs a call from `CALLER` to `TEST` over `db`, under the cheatcode handler when `cheats` is set. +fn run(db: MemoryDatabase, cheats: bool) -> (MegaTransactionOutcome, usize) { + run_with_gas_limit(db, cheats, GAS_LIMIT) +} + +/// [`run`] with the transaction's gas limit `gas_limit`. +fn run_with_gas_limit( + db: MemoryDatabase, + cheats: bool, + gas_limit: u64, +) -> (MegaTransactionOutcome, usize) { + let tx = call(CALLER, TEST, U256::ZERO, gas_limit); + if !cheats { + return (MegaEvm::new(context(db)).execute_transaction(tx).expect("valid"), 0); + } + let mut evm = MegaEvm::new(context(db)).with_inspector(Cheatcodes::default()); + let outcome = evm.execute_transaction(tx).expect("valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + (outcome, evm.inspector().answered) +} + +/// The value of `address`'s `slot` in `outcome`'s state. +fn slot(outcome: &MegaTransactionOutcome, address: Address, slot: u64) -> U256 { + outcome.state[&address].storage[&U256::from(slot)].present_value() +} + +/// `deal` sets a balance — up from nothing, creating the account, and down — and the program reads +/// it back with `BALANCE`. The journal write is on no ledger: the account `deal` creates costs no +/// state gas and makes no write record, and the transaction's state gas and records are the slots +/// the program itself writes. +#[test] +fn test_deal_sets_a_balance() { + let rich = address!("0000000000000000000000000000000000f00003"); + let code = cheat( + BytecodeBuilder::default(), + Vm::dealCall { who: TARGET, newBalance: U256::from(1_234) }, + ); + let code = cheat(code, Vm::dealCall { who: rich, newBalance: U256::from(7) }); + let code = code + .push_address(TARGET) + .append(BALANCE) + .append(PUSH0) + .append(SSTORE) + .push_address(rich) + .append(BALANCE) + .push_number(1_u8) + .append(SSTORE) + .stop(); + let db = MemoryDatabase::default() + .account_code(TEST, code.build()) + .account_balance(rich, U256::from(10_000)); + let (outcome, answered) = run(db, true); + assert_eq!(answered, 2); + assert_eq!(outcome.state[&TARGET].info.balance, U256::from(1_234), "up, from nothing"); + assert_eq!(outcome.state[&rich].info.balance, U256::from(7), "and down"); + assert_eq!( + (slot(&outcome, TEST, 0), slot(&outcome, TEST, 1)), + (U256::from(1_234), U256::from(7)) + ); + assert_eq!(outcome.gas.state, 2 * entry(GasId::sstore_set_state_gas()), "the two slots alone"); + assert_eq!(outcome.usage.write_records, 2, "the two slots alone"); +} + +/// `store` writes a slot, and the program reads it back with `SLOAD`. The journal write is on no +/// ledger: the transaction's state gas and records are the slot the program itself writes. +#[test] +fn test_store_writes_a_slot() { + let value = B256::from(U256::from(0x42)); + let code = cheat( + BytecodeBuilder::default(), + Vm::storeCall { target: TARGET, slot: B256::from(U256::from(5)), value }, + ); + // `TEST` reads the slot through a call to `TARGET`, whose code returns it. + let reader = BytecodeBuilder::default().push_number(5_u8).append(SLOAD).return_top(); + let code = call_and_note(code, TARGET, &[]).stop(); + let db = MemoryDatabase::default() + .account_code(TEST, code.build()) + .account_code(TARGET, reader.build()); + let (outcome, answered) = run(db, true); + assert_eq!(answered, 1); + assert_eq!(slot(&outcome, TARGET, 5), U256::from(0x42), "the slot is in the state"); + assert_eq!(slot(&outcome, TEST, 1), U256::from(0x42), "and the program read it"); + assert_eq!(outcome.gas.state, 2 * entry(GasId::sstore_set_state_gas()), "TEST's two slots"); + assert_eq!(outcome.usage.write_records, 2, "TEST's two slots"); +} + +/// Paused, gas metering stands still: a region that runs instructions and fills a fresh slot +/// spends nothing on any gas ledger — the state and history ledgers included, the whole gas being +/// put back before each instruction — so the transaction costs exactly what it costs with nothing +/// between the pause and the resume. The write is still a write: it is in the state, and its record +/// in the counts the limits hold and in the history bytes. Unpaused, the same region costs gas. +#[test] +fn test_pause_and_resume_gas_metering_hold_the_gas() { + let region = |code: BytecodeBuilder| { + (0..10) + .fold(code, |code, _| code.append_many([PUSH0, POP])) + .sstore(U256::from(9), U256::from(1)) + }; + let paused = |work: bool| { + let code = cheat(BytecodeBuilder::default(), Vm::pauseGasMeteringCall {}); + let code = if work { region(code) } else { code }; + cheat(code, Vm::resumeGasMeteringCall {}).stop().build() + }; + let db = |code: Bytes| MemoryDatabase::default().account_code(TEST, code); + + let (worked, answered) = run(db(paused(true)), true); + assert_eq!(answered, 2); + let (idle, _) = run(db(paused(false)), true); + assert_eq!(slot(&worked, TEST, 9), U256::from(1), "the slot was written"); + let ledgers = |o: &MegaTransactionOutcome| { + (o.gas.regular, o.gas.state, o.gas.history, o.gas.gas_used, o.gas.reservoir_remaining) + }; + assert_eq!(ledgers(&worked), ledgers(&idle), "the region spent nothing"); + assert_eq!(worked.gas.state, 0, "not even the slot's state gas"); + assert_eq!( + worked.usage, + LimitUsage { + data_size: idle.usage.data_size + WRITE_RECORD_SIZE, + write_records: idle.usage.write_records + 1, + }, + "the record is counted" + ); + assert_eq!(worked.gas.history_bytes, idle.gas.history_bytes + WRITE_RECORD_SIZE); + + let unpaused = region(BytecodeBuilder::default()).stop().build(); + let (metered, _) = run(db(unpaused), false); + assert!(metered.gas.gas_used > 0, "unpaused, the region pays"); + assert_eq!( + metered.gas.state, + entry(GasId::sstore_set_state_gas()), + "the slot's state gas included" + ); +} + +/// `expectRevert` turns the next call's revert into a success that keeps the revert data. `TARGET` +/// fills a fresh slot and reverts with a word; the program notes the flag and the word. The +/// failed call settles as the failure it was on every ledger — the transaction is billed and +/// counted as it is without the cheatcode — and only the flag the program noted differs. +#[test] +fn test_expect_revert_turns_a_revert_into_a_success_that_keeps_its_reason() { + let reason = keccak256(b"reason"); + let target = BytecodeBuilder::default() + .sstore(U256::from(3), U256::from(1)) + .revert_with_data(reason) + .build(); + let program = |expect: bool| { + let code = BytecodeBuilder::default(); + let code = if expect { cheat(code, Vm::expectRevertCall {}) } else { code }; + call_and_note(code, TARGET, &[]).stop().build() + }; + let db = |expect| { + MemoryDatabase::default() + .account_code(TEST, program(expect)) + .account_code(TARGET, target.clone()) + }; + let (expected, answered) = run(db(true), true); + assert_eq!(answered, 1); + assert_eq!(slot(&expected, TEST, 0), U256::from(2), "the caller saw a success"); + assert_eq!(slot(&expected, TEST, 1), U256::from_be_bytes(reason.0), "with the reason"); + assert!(!expected.state[&TARGET].storage.get(&U256::from(3)).is_some_and(|s| s.is_changed())); + + // Without the handler the same program runs: the cheatcode's call is a call to an account with + // no code, which costs what the answered one does, and `TARGET`'s call reverts. + let (reverted, _) = run(db(true), false); + assert_eq!(slot(&reverted, TEST, 0), U256::from(1), "the caller saw the revert"); + assert_eq!(slot(&reverted, TEST, 1), U256::from_be_bytes(reason.0)); + assert_eq!(expected.gas, reverted.gas, "every ledger"); + assert_eq!(expected.usage, reverted.usage, "every count"); +} + +/// `expectRevert` is honored on a result revm answers without running a frame. A point off the +/// curve fails the BN254 addition precompile, and the cheatcode turns the failure into a success; +/// a call to an account with no code succeeds, and the cheatcode turns the success into the failure +/// Foundry reports, whose data the program notes. +#[test] +fn test_expect_revert_is_honored_on_a_result_no_frame_ran_to_produce() { + let mut off_the_curve = [0_u8; 128]; + off_the_curve[31] = 1; + off_the_curve[63] = 1; + let program = |target: Address, input: &[u8]| { + call_and_note(cheat(BytecodeBuilder::default(), Vm::expectRevertCall {}), target, input) + .stop() + .build() + }; + + let db = MemoryDatabase::default().account_code(TEST, program(ADDITION, &off_the_curve)); + let (precompile, _) = run(db, true); + assert_eq!(slot(&precompile, TEST, 0), U256::from(2), "the failure became a success"); + + let db = MemoryDatabase::default().account_code(TEST, program(TARGET, &[])); + let (no_code, _) = run(db, true); + assert_eq!(slot(&no_code, TEST, 0), U256::from(1), "the success became a failure"); + let mut word = [0_u8; 32]; + word[..DID_NOT_REVERT.len()].copy_from_slice(DID_NOT_REVERT); + assert_eq!(slot(&no_code, TEST, 1), U256::from_be_bytes(word), "with Foundry's reason"); +} + +/// At Foundry's default gas limit a test transaction runs above the execution cap, with a +/// reservoir, and Foundry answers every cheatcode call on `Gas::new`, which carries none. The +/// answered frame never ran, so its caller merges back the reservoir it forwarded: a program that +/// calls `deal`, fills a fresh slot and notes `GAS` costs, on every ledger, what it costs where the +/// cheatcode's call reaches an account with no code — its state gas drawn from the reservoir rather +/// than spilled onto regular gas — reads the same `GAS`, and ends with the same reservoir. +#[test] +fn test_a_cheatcode_keeps_the_reservoir_at_foundrys_default_gas_limit() { + let code = + cheat(BytecodeBuilder::default(), Vm::dealCall { who: TARGET, newBalance: U256::ONE }) + .sstore(U256::ZERO, U256::ONE) + .append(GAS) + .push_number(1_u8) + .append(SSTORE) + .stop() + .build(); + let db = || MemoryDatabase::default().account_code(TEST, code.clone()); + let (cheated, answered) = run_with_gas_limit(db(), true, FOUNDRY_GAS_LIMIT); + assert_eq!(answered, 1); + assert_eq!(cheated.state[&TARGET].info.balance, U256::ONE, "the cheatcode ran"); + let (plain, _) = run_with_gas_limit(db(), false, FOUNDRY_GAS_LIMIT); + assert!(plain.gas.reservoir_remaining > 0, "the transaction runs with a reservoir"); + assert_eq!(cheated.gas, plain.gas, "every ledger, the reservoir included"); + assert_eq!(cheated.usage, plain.usage, "every count"); + assert_eq!(slot(&cheated, TEST, 1), slot(&plain, TEST, 1), "the same `GAS`"); +} diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs new file mode 100644 index 000000000..86c7d8fef --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -0,0 +1,305 @@ +//! What an inspector's writes to gas cannot do. +//! +//! - Gas changed at a frame's end has no effect: the instruction that ends a frame copies the +//! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas +//! after it reaches nobody. What a frame returns is changed on its result, in `call_end`. +//! - An inspector cannot overdraw a frame: a charge the frame's spendable gas cannot pay is refused +//! and takes nothing, the frame runs on, and nothing is left behind to classify its end — not +//! even under gas detention, where the same refusal of an opcode's charge is the crossing. +//! - An answer carries only the regular gas its inspector chose: the frame never ran, so its caller +//! merges back the reservoir it forwarded, whatever `Gas` the answer was built on. + +use alloy_primitives::{address, Address, Bytes, Log, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + untouched_call_gas, with_pools_of, EvmTxRuntimeLimits, MegaContext, MegaEvm, + MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{LOG0, POP, PUSH0, TIMESTAMP}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, + InstructionResult, Interpreter, InterpreterAction, InterpreterResult, + }, + Database, Inspector, +}; + +use crate::common::{call, context}; + +const CALLER: Address = address!("0000000000000000000000000000000000e00000"); +const A: Address = address!("0000000000000000000000000000000000e00001"); +const B: Address = address!("0000000000000000000000000000000000e00002"); +const GAS_LIMIT: u64 = 1_000_000; + +/// `A` calls `B` and stops; `B` pushes and pops a word and stops. +fn a_calls_b() -> MemoryDatabase { + let a = BytecodeBuilder::default().call(B, U256::ZERO).append(POP).stop().build(); + let b = BytecodeBuilder::default().append_many([PUSH0, POP]).stop().build(); + MemoryDatabase::default().account_code(A, a).account_code(B, b) +} + +/// Runs a call from `CALLER` to `A` under `limits`, under `inspector` when there is one, and +/// hands the inspector back as the run left it. +fn run, EthInterpreter> + Clone>( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + gas_limit: u64, + inspector: Option, +) -> (MegaTransactionOutcome, Option) { + let tx = call(CALLER, A, U256::ZERO, gas_limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let Some(inspector) = inspector else { + return (evm.execute_transaction(tx).expect("a valid transaction"), None); + }; + let mut evm = evm.with_inspector(inspector); + let outcome = evm.execute_transaction(tx).expect("a valid transaction"); + (outcome, Some(evm.inspector().clone())) +} + +/// Where [`Charges`] charges. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum At { + /// In the `step_end` of every instruction that ended its frame. + FramesEnd, + /// In the `step_end` of every other instruction that left no action pending. + Elsewhere, + /// On the result of every call, in `call_end`. + CallResult, +} + +/// Charges `amount` of regular gas at every place `at` names, and counts the charges it made. +#[derive(Clone)] +struct Charges { + at: At, + amount: u64, + made: u64, +} + +impl Charges { + const fn new(at: At, amount: u64) -> Self { + Self { at, amount, made: 0 } + } +} + +impl Inspector, EthInterpreter> for Charges { + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + let at = match interp.bytecode.action() { + Some(InterpreterAction::Return(_)) => At::FramesEnd, + None => At::Elsewhere, + Some(_) => return, + }; + if at == self.at { + assert!(interp.gas.record_regular_cost(self.amount), "the frame can pay"); + self.made += 1; + } + } + + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + if self.at == At::CallResult { + assert!(outcome.result.gas.record_regular_cost(self.amount), "the result can pay"); + self.made += 1; + } + } +} + +/// Gas an inspector charges in the `step_end` of the instruction that ended a frame — `B`'s +/// `STOP`, and `A`'s — is taken from an interpreter whose gas the instruction already copied into +/// the frame's result: neither `A` nor the transaction sees it. The same charge after any other +/// instruction lands on the receipt, once per instruction; and charged on a frame's result, in +/// `call_end`, it reaches whoever settles that result — `B`'s reaches `A`, `A`'s the transaction. +#[test] +fn test_gas_changed_at_a_frames_end_has_no_effect() { + const AMOUNT: u64 = 1_000; + let limits = EvmTxRuntimeLimits::no_limits(); + let (plain, _) = run::(a_calls_b(), limits, GAS_LIMIT, None); + assert!(plain.result.is_success(), "{:?}", plain.result); + + let (at_end, charges) = + run(a_calls_b(), limits, GAS_LIMIT, Some(Charges::new(At::FramesEnd, AMOUNT))); + assert_eq!(charges.unwrap().made, 2, "B's STOP and A's"); + assert_eq!(at_end.result, plain.result, "no charge reached the receipt"); + assert_eq!(at_end.gas, plain.gas); + + let (elsewhere, charges) = + run(a_calls_b(), limits, GAS_LIMIT, Some(Charges::new(At::Elsewhere, AMOUNT))); + let made = charges.unwrap().made; + assert!(made > 2, "every other instruction but the CALL: {made}"); + assert_eq!(elsewhere.gas.gas_used, plain.gas.gas_used + made * AMOUNT, "each one lands"); + + let (on_result, charges) = + run(a_calls_b(), limits, GAS_LIMIT, Some(Charges::new(At::CallResult, AMOUNT))); + assert_eq!(charges.unwrap().made, 2, "B's result and A's"); + assert_eq!( + on_result.gas.gas_used, + plain.gas.gas_used + 2 * AMOUNT, + "B's reaches A, and A's the transaction" + ); +} + +/// The callbacks holding the interpreter that [`Overdraws`] charges from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Callback { + Step, + StepEnd, + LogFull, +} + +/// Charges, once, one more gas than the running frame's spendable gas from the callback `from`, +/// the first time it runs while part of the frame's gas is withheld — or at all, when +/// `detained_only` is off — and records whether the charge was refused. +#[derive(Clone)] +struct Overdraws { + from: Callback, + detained_only: bool, + refused: Option, +} + +impl Overdraws { + const fn new(from: Callback, detained_only: bool) -> Self { + Self { from, detained_only, refused: None } + } + + fn charge(&mut self, from: Callback, interp: &mut Interpreter) { + let gas = interp.gas.tracker(); + if from != self.from || + self.refused.is_some() || + (self.detained_only && gas.withheld() == 0) + { + return; + } + let over = gas.spendable() + 1; + self.refused = Some(!interp.gas.record_regular_cost(over)); + } +} + +impl Inspector, EthInterpreter> for Overdraws { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.charge(Callback::Step, interp); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.charge(Callback::StepEnd, interp); + } + + fn log_full( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + _: Log, + ) { + self.charge(Callback::LogFull, interp); + } +} + +/// A charge the frame cannot pay is refused: the interpreter's gas is left as it was, the frame is +/// not halted and runs to its end, and the transaction is the one no inspector runs. +/// +/// Under gas detention the same holds for a charge only the withheld part could pay, from each +/// callback that holds the interpreter. An opcode's charge there is the crossing, which stops the +/// transaction when its frame ends; the inspector's is none of the frame's, so it classifies +/// nothing. `A` reads the block's timestamp, which caps its compute a thousand gas past the read, +/// then logs and runs a few more instructions. +#[test] +fn test_an_inspector_cannot_overdraw_a_frame() { + let limits = EvmTxRuntimeLimits::no_limits(); + let (plain, _) = run::(a_calls_b(), limits, GAS_LIMIT, None); + let overdraws = Overdraws::new(Callback::StepEnd, false); + let (overdrawn, inspector) = run(a_calls_b(), limits, GAS_LIMIT, Some(overdraws)); + assert_eq!(inspector.unwrap().refused, Some(true), "the charge was refused"); + assert_eq!(overdrawn.result, plain.result, "nothing was taken, and nothing halted"); + assert_eq!(overdrawn.gas, plain.gas); + assert_eq!(overdrawn.state, plain.state); + + let reads = BytecodeBuilder::default() + .append(TIMESTAMP) + .append(POP) + .append_many([PUSH0, PUSH0, LOG0]) + .append_many([PUSH0, POP, PUSH0, POP, PUSH0, POP]) + .stop() + .build(); + let db = || MemoryDatabase::default().account_code(A, reads.clone()); + let detained = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(1_000); + let (plain, _) = run::(db(), detained, GAS_LIMIT, None); + assert!(plain.result.is_success(), "{:?}", plain.result); + for from in [Callback::Step, Callback::StepEnd, Callback::LogFull] { + let (overdrawn, inspector) = + run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, true))); + assert_eq!(inspector.unwrap().refused, Some(true), "{from:?}: the withheld part"); + assert_eq!(overdrawn.limit_exceeded, None, "{from:?}: no crossing"); + assert_eq!(overdrawn.result, plain.result, "{from:?}"); + assert_eq!(overdrawn.gas, plain.gas, "{from:?}: everything the frame ran is billed"); + } +} + +/// How [`AnswersB`] builds the gas of its answer. +#[derive(Clone, Copy, Debug)] +enum AnswerGas { + /// The call's untouched gas, which carries the reservoir the frame inherited. + Untouched, + /// `Gas::new` of the call's gas limit, as Foundry answers a cheatcode: no reservoir. + Fresh, + /// Fresh regular gas carrying the pools of the untouched gas after a state and a history + /// charge ([`with_pools_of`]): charges the frame, which never ran, did not make. + Charged, +} + +/// Answers every call to `B` with `result`, on gas built as `gas` says. +#[derive(Clone)] +struct AnswersB { + result: InstructionResult, + gas: AnswerGas, +} + +impl Inspector, EthInterpreter> for AnswersB { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + (inputs.target_address == B).then(|| { + let gas = match self.gas { + AnswerGas::Untouched => untouched_call_gas(inputs), + AnswerGas::Fresh => Gas::new(inputs.gas_limit), + AnswerGas::Charged => { + let mut charged = untouched_call_gas(inputs); + assert!( + charged.record_state_cost(40_000) && charged.record_history_cost(3_000) + ); + with_pools_of(inputs.gas_limit, &charged) + } + }; + CallOutcome::new( + InterpreterResult::new(self.result, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// An answered frame never ran, so its gas carries nothing but the regular gas its inspector +/// chose: its caller merges back the reservoir it forwarded, whatever `Gas` the answer was built +/// on. Above the execution cap, an answer on the frame's untouched gas, one on `Gas::new` — which +/// carries no reservoir — and one carrying charges the frame never made settle alike, a success, a +/// revert and a halt each, and the transaction keeps the reservoir it keeps when `B` runs. The +/// charges are rolled back against the answer's own reservoir before the inherited one replaces +/// it, so neither the reservoir nor a ledger counts them. +#[test] +fn test_an_answer_carries_the_reservoir_its_caller_merges() { + let gas_limit = TX_GAS_LIMIT_CAP + 100_000_000; + let limits = EvmTxRuntimeLimits::no_limits(); + let (plain, _) = run::(a_calls_b(), limits, gas_limit, None); + assert!(plain.gas.reservoir_remaining > 0, "the reservoir comes back"); + + for result in [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] + { + let answer = |gas| { + let inspector = AnswersB { result, gas }; + run(a_calls_b(), limits, gas_limit, Some(inspector)).0 + }; + let untouched = answer(AnswerGas::Untouched); + assert_eq!(untouched.gas.reservoir_remaining, plain.gas.reservoir_remaining, "{result:?}"); + for gas in [AnswerGas::Fresh, AnswerGas::Charged] { + let answered = answer(gas); + assert!(answered.result.is_success(), "{result:?}, {gas:?}: `A` ignores the answer"); + assert_eq!(answered.gas, untouched.gas, "{result:?}, {gas:?}: every ledger"); + assert_eq!(answered.usage, untouched.usage, "{result:?}, {gas:?}: every count"); + } + } +} diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs new file mode 100644 index 000000000..0464dce67 --- /dev/null +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -0,0 +1,862 @@ +//! What a frame that kept nothing settles into its caller, whatever an inspector made of its +//! result, and what a success an inspector rewrites into a failure keeps: nothing, the journal +//! following the result as it follows a frame that fails. +//! +//! Two frames keep nothing in the journal: one that failed, whose checkpoint was reverted before +//! the inspector saw its result, and one the inspector answered in place of running, which never +//! started. An inspector may still hand the caller a success for either — Foundry's `expectRevert` +//! turns a failed call into a success, and a mocked call is answered without running — and the +//! caller sees the success, the output and the regular gas the inspector left. Nothing else of the +//! frame reaches it: no state gas or history gas for writes the journal does not hold, no refund, +//! no write record, and no upfront charge for an account that was never added. +//! +//! Every expectation here is the rule's: a caller that drops the flag cannot tell a rewritten +//! failure from the failure, and a frame answered without running adds no account and writes +//! nothing, so the transaction's state gas is zero and its history is its body's. An answer +//! carries nothing but the regular gas the inspector chose, so every answer is given twice — on +//! the gas the frame was forwarded, untouched, and on `Gas::new` of it, as Foundry answers, which +//! carries no reservoir — and the two settle alike. Where a new +//! account is charged, its bucket is crowded (`m = 3`), so the charge that comes back is the one +//! that was made, priced at the account it was made for. + +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + history_gas, + test_utils::{BytecodeBuilder, MemoryDatabase}, + transaction_body_bytes, untouched_call_gas, untouched_create_gas, LimitUsage, MegaContext, + MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::{ + opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, + Bytecode, + }, + context::{ContextTr, JournalTr}, + context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr, Transaction}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, + InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, + }, + state::{AccountStatus, EvmStorageSlot}, + Inspector, +}; + +use crate::salt::{ + create_with, crowded_account, db, entry, minimal_envs, salt_context, tx_with_gas, value_call, + SaltEnvs, CALLER, CONTRACT, EMPTY, +}; + +/// A contract `CONTRACT` calls. +const CALLEE: Address = address!("0000000000000000000000000000000000c00010"); +/// The BN254 pairing precompile, which an empty input with too little gas runs out of gas on. +const PAIRING: Address = address!("0000000000000000000000000000000000000008"); +/// The BN254 addition precompile, which a point off the curve fails. +const ADDITION: Address = address!("0000000000000000000000000000000000000006"); +/// The address an answered creation reports. +const ANSWERED: Address = address!("0000000000000000000000000000000000c000aa"); + +/// A gas limit below the execution cap, where state gas spills onto regular gas, and one above it, +/// where a reservoir pays it. +const GAS_LIMITS: [u64; 2] = [30_000_000, TX_GAS_LIMIT_CAP + 100_000_000]; + +/// Turns every failed call result into a success and leaves the rest of it as it is: the shape of +/// Foundry's `expectRevert`. +struct Revives; + +impl Inspector for Revives { + fn call_end(&mut self, _: &mut CTX, _: &CallInputs, outcome: &mut CallOutcome) { + if !outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Return; + } + } +} + +/// Answers every call to `target`, and every creation, itself with `result`, on the gas the frame +/// was forwarded, untouched, or, when `fresh`, on `Gas::new` of it: the frame never starts. An +/// answered creation reports `address`. +#[derive(Clone, Copy, Debug)] +struct Answers { + target: Address, + result: InstructionResult, + address: Option
, + fresh: bool, +} + +impl Answers { + const fn call(target: Address, result: InstructionResult) -> Self { + Self { target, result, address: None, fresh: false } + } + + const fn creation(result: InstructionResult, address: Option
) -> Self { + Self { target: Address::ZERO, result, address, fresh: false } + } + + /// The same answers, built on `Gas::new` of the gas the frame was forwarded, as Foundry + /// answers a cheatcode: gas that carries no reservoir. + const fn on_fresh_gas(self) -> Self { + Self { fresh: true, ..self } + } +} + +impl Inspector for Answers { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + (inputs.target_address == self.target).then(|| { + let gas = + if self.fresh { Gas::new(inputs.gas_limit) } else { untouched_call_gas(inputs) }; + CallOutcome::new( + InterpreterResult::new(self.result, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + (self.target == Address::ZERO).then(|| { + let gas = if self.fresh { + Gas::new(inputs.gas_limit()) + } else { + untouched_create_gas(inputs) + }; + CreateOutcome::new(InterpreterResult::new(self.result, Bytes::new(), gas), self.address) + }) + } +} + +/// Runs `tx` over `db` reading `envs`, without an inspector. +fn plain(db: MemoryDatabase, envs: SaltEnvs, tx: MegaTransaction) -> MegaTransactionOutcome { + MegaEvm::new(salt_context(db, envs)).execute_transaction(tx).expect("a valid transaction") +} + +/// Runs `tx` over `db` reading `envs`, under `inspector`. +fn inspected( + db: MemoryDatabase, + envs: SaltEnvs, + tx: MegaTransaction, + inspector: I, +) -> MegaTransactionOutcome +where + I: Inspector, EthInterpreter>, +{ + MegaEvm::new(salt_context(db, envs)) + .with_inspector(inspector) + .execute_transaction(tx) + .expect("a valid transaction") +} + +/// Runs `tx` over `db()` reading `envs()` under `answers`, on the gas the answered frame was +/// forwarded, untouched, and again on `Gas::new` of it; hands back the first once the second +/// settled alike. The frame never ran, so its answer carries nothing but the regular gas the +/// inspector chose, and its caller merges back the reservoir it forwarded whatever the answer was +/// built on. +fn answered( + db: impl Fn() -> MemoryDatabase, + envs: impl Fn() -> SaltEnvs, + tx: &MegaTransaction, + answers: Answers, +) -> MegaTransactionOutcome { + let untouched = inspected(db(), envs(), tx.clone(), answers); + let fresh = inspected(db(), envs(), tx.clone(), answers.on_fresh_gas()); + assert_eq!(fresh.result, untouched.result, "{answers:?}: on fresh gas"); + assert_eq!(fresh.gas, untouched.gas, "{answers:?}: every ledger, on fresh gas"); + assert_eq!(fresh.usage, untouched.usage, "{answers:?}: every count, on fresh gas"); + assert_eq!(fresh.state, untouched.state, "{answers:?}: the state, on fresh gas"); + untouched +} + +/// A call from `CALLER` to `to` carrying `value` and `data`, at `gas_limit`. +fn to(to: Address, value: u64, data: Bytes, gas_limit: u64) -> MegaTransaction { + tx_with_gas(TxKind::Call(to), data, U256::from(value), gas_limit) +} + +/// A transaction that keeps nothing but its body: no state gas, its body's history alone, and its +/// body's bytes alone on the data size. Above the execution cap the reservoir paid for the body and +/// nothing else, so what is left of it comes back. +fn assert_keeps_only_its_body(case: &str, tx: &MegaTransaction, outcome: &MegaTransactionOutcome) { + let body = transaction_body_bytes(tx); + assert_eq!(outcome.gas.state, 0, "{case}: no state gas"); + assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "{case}: the body's history"); + assert_eq!( + outcome.gas.reservoir_remaining, + tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(outcome.gas.history), + "{case}: the reservoir less the body's history" + ); + assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); +} + +/// Whether `account` holds anything in `outcome`'s state. +fn holds_something(outcome: &MegaTransactionOutcome, account: Address) -> bool { + outcome.state.get(&account).is_some_and(|account| !account.info.is_empty()) +} + +/// `CALLEE` fills a fresh slot, clears a slot it held (a refund), logs a word, then reverts; +/// `CONTRACT` calls it and drops the flag. Rewritten into a success, the call is the revert it was +/// to everything but the flag `CONTRACT` drops: the transaction is the one no inspector runs, on +/// every ledger. Kept, the same writes cost state gas, history and a refund — what the rewrite +/// would otherwise have merged. +#[test] +fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { + let writes = || { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::ZERO) + .log3_word() + }; + let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); + let setup = |code: Bytes| { + db(caller.clone()).account_code(CALLEE, code).account_storage( + CALLEE, + U256::from(2), + U256::from(1), + ) + }; + let reverting = setup(writes().revert().build()); + let stopping = setup(writes().stop().build()); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let kept = plain(stopping.clone(), minimal_envs(), tx.clone()); + assert!(kept.result.is_success(), "{:?}", kept.result); + assert_eq!( + kept.gas.state, + entry(GasId::sstore_set_state_gas()), + "kept, the fresh slot costs state gas" + ); + assert_eq!(kept.usage.write_records, 2, "and both slots are records"); + + let failed = plain(reverting.clone(), minimal_envs(), tx.clone()); + let rewritten = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); + assert!(failed.result.is_success(), "CONTRACT drops the flag: {:?}", failed.result); + assert_keeps_only_its_body("the failed call", &tx, &failed); + assert_eq!(rewritten.result, failed.result, "no log, and the same bill"); + assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); + assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); + assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + } +} + +/// `CONTRACT` sends a wei to the BN254 pairing precompile with no gas of its own: the stipend is +/// short of the pairing's price, so the call runs out of gas, and the account its value would add +/// — the upfront new-account charge its `CALL` made — goes with it. Rewritten into a success, the +/// call gives that charge back all the same: the transaction is the one no inspector runs. With the +/// gas to run, the same call adds the account and keeps the charge. +#[test] +fn test_a_failed_value_call_rewritten_into_a_success_gives_the_new_account_charge_back() { + let caller = |gas: u64| { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(PAIRING) + .push_number(gas) + .append(CALL) + .append(POP) + .stop() + .build() + }; + let envs = || crowded_account(minimal_envs(), PAIRING, 3); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(caller(1_000_000)), envs(), tx.clone()); + assert!(holds_something(&ran, PAIRING), "the pairing ran and kept the wei"); + assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); + + let failed = plain(db(caller(0)), envs(), tx.clone()); + let rewritten = inspected(db(caller(0)), envs(), tx.clone(), Revives); + assert_keeps_only_its_body("the failed call", &tx, &failed); + assert!(!holds_something(&rewritten, PAIRING), "no wei moved"); + assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); + assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); + assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + } +} + +/// The transaction's own frame: a wei sent to the BN254 addition precompile with a point off the +/// curve fails, and takes back the account EIP-2780 charged its start for and the write record +/// charged before execution. Rewritten into a success, the transaction reports the success and +/// keeps only its body, as the failure does. With a point on the curve, the same transaction adds +/// the account and keeps both charges. +#[test] +fn test_the_transactions_own_failed_frame_rewritten_into_a_success_keeps_nothing() { + let point_off_the_curve = { + let mut input = [0_u8; 128]; + input[31] = 1; + input[63] = 1; + Bytes::from(input.to_vec()) + }; + let envs = || crowded_account(minimal_envs(), ADDITION, 3); + for gas_limit in GAS_LIMITS { + let valid = to(ADDITION, 1, Bytes::from(vec![0_u8; 128]), gas_limit); + let ran = plain(db(Bytes::new()), envs(), valid.clone()); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); + let body = transaction_body_bytes(&valid); + assert_eq!(ran.gas.history_bytes, body + WRITE_RECORD_SIZE, "the body and the record"); + + let tx = to(ADDITION, 1, point_off_the_curve.clone(), gas_limit); + let failed = plain(db(Bytes::new()), envs(), tx.clone()); + assert!(failed.result.is_halt(), "{:?}", failed.result); + assert_keeps_only_its_body("the failed transaction", &tx, &failed); + + let rewritten = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); + assert!(rewritten.result.is_success(), "the inspector's: {:?}", rewritten.result); + assert_keeps_only_its_body("the rewritten transaction", &tx, &rewritten); + assert!(!holds_something(&rewritten, ADDITION), "no wei moved"); + assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + } +} + +/// A value call to an account that does not exist, answered by an inspector with a success, a +/// revert or a halt: the frame never started, so no wei moved and no account was added, and the +/// new-account charge its `CALL` made comes back whatever the answer. The three answers cost the +/// same, and the transaction keeps only its body. Run, the call adds the account in its bucket. +#[test] +fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { + let caller = || value_call(EMPTY).append(POP).stop().build(); + let envs = || crowded_account(minimal_envs(), EMPTY, 3); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(caller()), envs(), tx.clone()); + assert!(holds_something(&ran, EMPTY), "the call added the account"); + assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); + + let answers = + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas].map( + |result| { + let answered = + answered(|| db(caller()), envs, &tx, Answers::call(EMPTY, result)); + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert_keeps_only_its_body(&case, &tx, &answered); + assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + (answered.gas, answered.state.clone()) + }, + ); + assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: a success costs a revert's"); + } +} + +/// The transaction's own value transfer to an account that does not exist, answered by an +/// inspector: the account EIP-2780 charged the frame's start for is not added, and neither is the +/// write record charged before execution, whatever the answer. +#[test] +fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_nothing() { + let envs = || crowded_account(minimal_envs(), EMPTY, 3); + for gas_limit in GAS_LIMITS { + let tx = to(EMPTY, 1, Bytes::new(), gas_limit); + let ran = plain(db(Bytes::new()), envs(), tx.clone()); + assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); + + for result in [InstructionResult::Stop, InstructionResult::Revert] { + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answered = answered(|| db(Bytes::new()), envs, &tx, Answers::call(EMPTY, result)); + assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); + assert_keeps_only_its_body(&case, &tx, &answered); + assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + } + } +} + +/// A creation an inspector answers adds no account, whatever the answer — a success with an +/// address, a success with none, a revert — so the creation's upfront charge comes back once, and +/// the three answers cost the same. Run, the creation adds its account in its bucket. +#[test] +fn test_a_creation_an_inspector_answers_gives_its_charge_back() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let created = CONTRACT.create(0); + let envs = || crowded_account(minimal_envs(), created, 3); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(caller()), envs(), tx.clone()); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(ran.gas.state, 3 * entry(GasId::create_state_gas()), "in its bucket"); + + let answers = [ + (InstructionResult::Return, Some(ANSWERED)), + (InstructionResult::Stop, None), + (InstructionResult::Revert, None), + ] + .map(|(result, address)| { + let answered = answered(|| db(caller()), envs, &tx, Answers::creation(result, address)); + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert_keeps_only_its_body(&case, &tx, &answered); + assert!(!holds_something(&answered, created), "{case}: no account"); + answered.gas + }); + assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: with an address or without"); + assert_eq!(answers[0], answers[2], "gas limit {gas_limit}: a success costs a revert's"); + } +} + +/// The transaction's own creation, answered by an inspector: the account EIP-2780 charged the +/// frame's start for is not added, and neither is the write record charged before execution, +/// whatever the answer. Run, the creation adds its account in its bucket. +#[test] +fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { + let created = CALLER.create(0); + let envs = || crowded_account(minimal_envs(), created, 3); + for gas_limit in GAS_LIMITS { + let tx = tx_with_gas(TxKind::Create, Bytes::from_static(&[STOP]), U256::ZERO, gas_limit); + let ran = plain(db(Bytes::new()), envs(), tx.clone()); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(ran.gas.state, 3 * entry(GasId::create_state_gas()), "in its bucket"); + + for (result, address) in [ + (InstructionResult::Return, Some(ANSWERED)), + (InstructionResult::Stop, None), + (InstructionResult::Revert, None), + ] { + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answered = + answered(|| db(Bytes::new()), envs, &tx, Answers::creation(result, address)); + assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); + assert_keeps_only_its_body(&case, &tx, &answered); + assert!(!holds_something(&answered, created), "{case}: no account"); + } + } +} + +/// A value call an inspector answers leaves its caller holding none of the state gas its `CALL` +/// was charged for the account: the charge came back. The caller then fills a slot, and holds the +/// slot alone, where the caller whose call ran holds the slot and the account. +#[test] +fn test_an_answered_call_leaves_its_caller_none_of_the_accounts_state_gas() { + let caller = + || value_call(EMPTY).append(POP).sstore(U256::from(1), U256::from(1)).stop().build(); + let slot = entry(GasId::sstore_set_state_gas()); + let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); + let context = || salt_context(db(caller()), minimal_envs()); + + let ran = MegaEvm::new(context()).execute_transaction(tx.clone()).unwrap(); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!( + ran.gas.state, + slot + entry(GasId::new_account_state_gas()), + "the slot and the account" + ); + + let answered = MegaEvm::new(context()) + .with_inspector(Answers::call(EMPTY, InstructionResult::Stop)) + .execute_transaction(tx) + .unwrap(); + assert!(answered.result.is_success(), "{:?}", answered.result); + assert_eq!(answered.gas.state, slot, "the slot alone"); +} + +/* ---------- a call an inspector retargets ---------- */ + +/// The address `Retargets` sends a call to. +const RETARGET: Address = address!("0000000000000000000000000000000000c00020"); + +/// Rewrites every call to `from` into a call to `RETARGET`, whose code it supplies, in the +/// inspector's `call` hook, and answers it with `answer` when it has one: a tool that redirects a +/// call after the opcode charged for the account it was made to. +struct Retargets { + from: Address, + code: Bytecode, + answer: Option, +} + +impl Inspector for Retargets { + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + if inputs.target_address != self.from { + return None; + } + // The new target is loaded before the frame starts, as a hook that redirects a call must. + context.journal_mut().load_account(RETARGET).expect("in memory"); + inputs.target_address = RETARGET; + inputs.bytecode_address = RETARGET; + inputs.known_bytecode = (self.code.hash_slow(), self.code.clone()); + self.answer.map(|result| { + CallOutcome::new( + InterpreterResult::new(result, Bytes::new(), untouched_call_gas(inputs)), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// A value call to an account that does not exist charges that account's state gas upfront, in its +/// SALT bucket. An inspector that redirects the call to another account, whose bucket is priced +/// otherwise, changes which account the charge comes back for: it comes back at the price it was +/// made at, the original account's, whatever the new target costs. Both ways — the account dearer +/// than the new target (`m` = 8 and 1) and cheaper (1 and 8) — the call answered in place of +/// running, and the call that runs and reverts, keep nothing: no state gas, the body's history +/// alone, and the reservoir back where it started. A refund at the new target's price would leave +/// state gas behind in one direction and drive the state ledger negative, growing the reservoir, +/// in the other. +#[test] +fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_price_it_was_made_at() { + let caller = || value_call(EMPTY).append(POP).stop().build(); + let reverts = Bytecode::new_raw(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for (account_m, retarget_m) in [(8, 1), (1, 8)] { + let envs = || { + crowded_account(crowded_account(minimal_envs(), EMPTY, account_m), RETARGET, retarget_m) + }; + let db = || db(caller()).account_code(RETARGET, reverts.original_bytes()); + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(), envs(), tx.clone()); + assert_eq!( + ran.gas.state, + account_m * entry(GasId::new_account_state_gas()), + "{account_m}/{retarget_m}: run, the call adds the account in its bucket" + ); + for (name, answer) in + [("answered", Some(InstructionResult::Stop)), ("running and reverting", None)] + { + let case = format!("{name}, m {account_m}/{retarget_m}, gas limit {gas_limit}"); + let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; + let outcome = inspected(db(), envs(), tx.clone(), inspector); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_keeps_only_its_body(&case, &tx, &outcome); + assert!(!holds_something(&outcome, EMPTY), "{case}: no account"); + } + } + } +} + +/* ---------- a failed creation rewritten into a success ---------- */ + +/// Turns every failed creation result into a success at `0x…01`, as Foundry's `expectRevert` on a +/// creation does: the revert's output and gas stay as they are, and the address is one the +/// creation never made. +struct RevivesCreations; + +impl Inspector for RevivesCreations { + fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { + if !outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(Address::with_last_byte(1)); + } + } +} + +/// A creation whose init code fills a fresh slot, logs a word and reverts, rewritten into a +/// success, is the failure it was to everything but the address its creator is handed: every +/// ledger, the counts and the state are those of the run no inspector touches. The upfront charge +/// the `CREATE` made for the account comes back, priced at the account it was made for — its bucket +/// is crowded (`m = 3`) — and the slot, the log and the account are not kept. At the transaction's +/// own frame and one call down, carrying no value and one wei, below and above the execution cap; +/// run, the creation adds its account. +#[test] +fn test_a_failed_creation_rewritten_into_a_success_settles_as_the_failure() { + let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); + let (reverting, stopping) = (writes().revert().build(), writes().stop().build()); + for (gas_limit, value) in GAS_LIMITS.into_iter().flat_map(|limit| [(limit, 0), (limit, 1)]) { + let creates = |init: &[u8]| { + BytecodeBuilder::default().create(U256::from(value), init).append(POP).stop().build() + }; + let own = |init: &[u8]| { + let data = Bytes::copy_from_slice(init); + (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(value), gas_limit)) + }; + let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); + let cases: [(&str, Address, CreationSetup<'_>); 2] = [ + ("the transaction's own", CALLER.create(0), &own), + ("one call down", CONTRACT.create(0), &down), + ]; + for (at, created, setup) in cases { + let envs = || crowded_account(minimal_envs(), created, 3); + let case = format!("{at}, value {value}, gas limit {gas_limit}"); + let (code, tx) = setup(&stopping[..]); + let ran = plain(db(code), envs(), tx); + assert!(holds_something(&ran, created), "{case}: run, the creation adds its account"); + assert_eq!( + ran.gas.state, + 3 * entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()), + "{case}: the account in its bucket and the slot" + ); + + let (code, tx) = setup(&reverting[..]); + let failed = plain(db(code.clone()), envs(), tx.clone()); + assert!(!holds_something(&failed, created), "{case}: reverting, it adds none"); + let rewritten = inspected(db(code), envs(), tx.clone(), RevivesCreations); + assert!(rewritten.result.is_success(), "{case}: {:?}", rewritten.result); + assert!(!holds_something(&rewritten, created), "{case}: no account"); + assert!(rewritten.result.logs().is_empty(), "{case}: no log"); + assert_eq!(rewritten.gas, failed.gas, "{case}: every ledger"); + assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); + assert_eq!(rewritten.state, failed.state, "{case}: the state"); + } + } +} + +/* ---------- a success rewritten into a failure ---------- */ + +/// The data Foundry's `expectRevert` gives a call that did not revert. +const DID_NOT_REVERT: &[u8] = b"call did not revert as expected"; + +/// Turns every successful result of a call to `target`, and of every creation when `target` is +/// zero, into `result` carrying Foundry's "did not revert" data — the shape of `expectRevert` on a +/// call that did not revert — or, with no `result`, rewrites nothing. Records the journal's depth +/// at every instruction, which Foundry's `expectRevert` compares. +#[derive(Clone)] +struct Fails { + target: Address, + result: Option, + depths: Vec, +} + +impl Fails { + const fn call(target: Address, result: InstructionResult) -> Self { + Self { target, result: Some(result), depths: Vec::new() } + } + + const fn creation(result: InstructionResult) -> Self { + Self::call(Address::ZERO, result) + } + + /// The same inspector, rewriting nothing. + fn recording(&self) -> Self { + Self { result: None, ..self.clone() } + } + + fn fail(&self, result: &mut InterpreterResult) { + if let Some(failure) = self.result.filter(|_| result.result.is_ok()) { + result.result = failure; + result.output = Bytes::from_static(DID_NOT_REVERT); + } + } +} + +impl Inspector for Fails { + fn step(&mut self, _: &mut Interpreter, context: &mut CTX) { + self.depths.push(context.journal_ref().depth()); + } + + fn call_end(&mut self, _: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address == self.target { + self.fail(&mut outcome.result); + } + } + + fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { + if self.target == Address::ZERO { + self.fail(&mut outcome.result); + } + } +} + +/// Runs `tx` over `db()` reading `envs()` under `fails`, and again under the same inspector +/// rewriting nothing; hands back the first once the journal's depth was the same at every +/// instruction of both: taking a frame's journal back leaves the depth as it was. +fn rewritten( + db: impl Fn() -> MemoryDatabase, + envs: impl Fn() -> SaltEnvs, + tx: &MegaTransaction, + fails: Fails, +) -> MegaTransactionOutcome { + let run = |inspector: Fails| { + let mut evm = MegaEvm::new(salt_context(db(), envs())).with_inspector(inspector); + let outcome = evm.execute_transaction(tx.clone()).expect("a valid transaction"); + (outcome, evm.inspector().depths.clone()) + }; + let (_, recorded) = run(fails.recording()); + let (outcome, depths) = run(fails); + assert_eq!(depths, recorded, "the journal's depth at every instruction"); + outcome +} + +/// The failures a success is rewritten into: Foundry's revert, and a halt. +const FAILURES: [InstructionResult; 2] = [InstructionResult::Revert, InstructionResult::OutOfGas]; + +/// An account as a state is compared on without its code: status, balance, nonce and storage. +type AccountBesideCode = (Address, AccountStatus, U256, u64, Vec<(U256, EvmStorageSlot)>); + +/// `outcome`'s state without the code of its accounts, in address order: what two runs whose +/// programs differ in their last opcodes are compared on. +fn state_without_code(outcome: &MegaTransactionOutcome) -> Vec { + let mut accounts: Vec<_> = outcome + .state + .iter() + .map(|(address, account)| { + let mut storage: Vec<_> = + account.storage.iter().map(|(key, slot)| (*key, slot.clone())).collect(); + storage.sort_by_key(|(key, _)| *key); + (*address, account.status, account.info.balance, account.info.nonce, storage) + }) + .collect(); + accounts.sort_by_key(|(address, ..)| *address); + accounts +} + +/// A value call that adds an account, rewritten into a failure, keeps nothing. `EMPTY` has no code, +/// so revm answers the call without building a frame, and what its start journaled — the value's +/// move, the account it touched, the transfer log — is taken back to where the start began: the +/// value stays with its sender and no account is added. The failure then settles as the same +/// failure an inspector answers in place of the call does, on every ledger and in the state: no +/// state gas, the body's history alone. At the transaction's own frame and one call down, below +/// and above the execution cap; run, the call adds the account and logs the transfer. +#[test] +fn test_a_value_call_rewritten_into_a_failure_keeps_nothing() { + let envs = || crowded_account(minimal_envs(), EMPTY, 3); + let caller = value_call(EMPTY).append(POP).stop().build(); + for gas_limit in GAS_LIMITS { + let cases = [ + ("the transaction's own", Bytes::new(), to(EMPTY, 1, Bytes::new(), gas_limit)), + ("one call down", caller.clone(), to(CONTRACT, 0, Bytes::new(), gas_limit)), + ]; + for (at, code, tx) in cases { + let db = || db(code.clone()); + let ran = plain(db(), envs(), tx.clone()); + assert!(holds_something(&ran, EMPTY), "{at}: run, the call adds the account"); + assert_eq!(ran.result.logs().len(), 1, "{at}: and logs the transfer"); + for result in FAILURES { + let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); + let rewritten = rewritten(db, envs, &tx, Fails::call(EMPTY, result)); + let answered = inspected(db(), envs(), tx.clone(), Answers::call(EMPTY, result)); + assert_keeps_only_its_body(&case, &tx, &rewritten); + assert!(!holds_something(&rewritten, EMPTY), "{case}: no account"); + assert!(rewritten.result.logs().is_empty(), "{case}: no transfer log"); + assert_eq!(rewritten.gas, answered.gas, "{case}: every ledger"); + assert_eq!(rewritten.usage, answered.usage, "{case}: every count"); + assert_eq!(rewritten.state, answered.state, "{case}: the state"); + } + } + } +} + +/// Where a creation case runs one init code: the code of `CONTRACT` and the transaction. +type CreationSetup<'a> = &'a dyn Fn(&[u8]) -> (Bytes, MegaTransaction); + +/// A creation rewritten into a failure keeps what a creation that fails keeps: its creator's nonce +/// bump, which revm makes before the creation's checkpoint, and its record — nothing after the +/// checkpoint: no account, no code, no endowment. It settles as a creation whose init code reverts +/// in place of returning does, on the state beside the code, state and history gas and the counts; +/// a revert keeps the regular gas the run spent. At the transaction's own frame and one call down, +/// below and above the execution cap; run, the creation adds its account. +#[test] +fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() { + let (deploys, reverts) = (&[PUSH0, PUSH0, RETURN][..], &[PUSH0, PUSH0, REVERT][..]); + let creates = |init: &[u8]| { + BytecodeBuilder::default().create(U256::from(1), init).append(POP).stop().build() + }; + for gas_limit in GAS_LIMITS { + let own = |init: &[u8]| { + let data = Bytes::copy_from_slice(init); + (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(1), gas_limit)) + }; + let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); + let cases: [(&str, Address, CreationSetup<'_>); 2] = [ + ("the transaction's own", CALLER.create(0), &own), + ("one call down", CONTRACT.create(0), &down), + ]; + for (at, created, setup) in cases { + let envs = || crowded_account(minimal_envs(), created, 3); + let ((deploying, tx), (reverting, reverting_tx)) = (setup(deploys), setup(reverts)); + let ran = plain(db(deploying.clone()), envs(), tx.clone()); + assert!(holds_something(&ran, created), "{at}: run, the creation adds its account"); + let failed = plain(db(reverting), envs(), reverting_tx); + assert!(!holds_something(&failed, created), "{at}: reverting, it adds none"); + for result in FAILURES { + let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); + let rewritten = + rewritten(|| db(deploying.clone()), envs, &tx, Fails::creation(result)); + assert!(!holds_something(&rewritten, created), "{case}: no account"); + let state = state_without_code(&rewritten); + assert_eq!(state, state_without_code(&failed), "{case}: the state"); + assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); + assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); + assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); + assert_eq!(rewritten.gas.history_bytes, failed.gas.history_bytes, "{case}"); + if result == InstructionResult::Revert { + assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); + } + } + } + } +} + +/// Where a call case runs one program: the database holding it. +type CallSetup<'a> = &'a dyn Fn(&Bytes) -> MemoryDatabase; + +/// A call whose frame ran and wrote — a fresh slot filled and a word logged — rewritten into a +/// failure keeps none of it: the frame's journal is taken back to its checkpoint, so the slot is +/// not in the state and the log is not in the receipt. It settles as the same writes reverting do, +/// on the state beside the code, state and history gas and the counts; a revert keeps the regular +/// gas the run spent. At the transaction's own frame and one call down, below and above the +/// execution cap; run, the slot and the log are kept. +#[test] +fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_none_of_it() { + let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); + let (stopping, reverting) = (writes().stop().build(), writes().revert().build()); + let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); + let own = |code: &Bytes| db(code.clone()); + let down = |code: &Bytes| db(caller.clone()).account_code(CALLEE, code.clone()); + let cases: [(&str, Address, CallSetup<'_>); 2] = + [("the transaction's own", CONTRACT, &own), ("one call down", CALLEE, &down)]; + for gas_limit in GAS_LIMITS { + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + for (at, writer, setup) in cases { + let slot = |outcome: &MegaTransactionOutcome| { + outcome.state[&writer].storage.get(&U256::from(1)).is_some_and(|s| s.is_changed()) + }; + let ran = plain(setup(&stopping), minimal_envs(), tx.clone()); + assert!(slot(&ran) && !ran.result.logs().is_empty(), "{at}: run, the writes are kept"); + let failed = plain(setup(&reverting), minimal_envs(), tx.clone()); + for result in FAILURES { + let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); + let fails = Fails::call(writer, result); + let rewritten = rewritten(|| setup(&stopping), minimal_envs, &tx, fails); + assert!(!slot(&rewritten), "{case}: no slot"); + assert!(rewritten.result.logs().is_empty(), "{case}: no log"); + let state = state_without_code(&rewritten); + assert_eq!(state, state_without_code(&failed), "{case}: the state"); + assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); + assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); + assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); + if result == InstructionResult::Revert { + assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); + } + } + } + } +} + +/// An account the inspector of [`WritesAtTheEnd`] writes to. +const NOTE: Address = address!("0000000000000000000000000000000000c000bb"); + +/// Writes a balance to `NOTE` in the `call_end` of every call to `CALLEE`, and, when `fails`, turns +/// a success into a revert there. +struct WritesAtTheEnd { + fails: bool, +} + +impl Inspector, EthInterpreter> for WritesAtTheEnd { + fn call_end( + &mut self, + context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address != CALLEE { + return; + } + let mut account = context.journal_mut().load_account_mut(NOTE).expect("loads"); + account.data.set_balance(U256::from(7)); + if self.fails && outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Revert; + } + } +} + +/// What an inspector writes to the journal in the callback that turns a success into a failure is +/// journaled after the frame's checkpoint, and goes with the frame's writes; written in a callback +/// that leaves the success alone, it stays. Where revm fails the frame itself, the checkpoint is +/// gone before `call_end`, so a write made there stays: the one place the rewrite and a real +/// failure part. +#[test] +fn test_a_write_an_inspector_makes_as_it_fails_a_frame_goes_with_the_frame() { + let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); + let db = |callee: Bytes| db(caller.clone()).account_code(CALLEE, callee); + let stopping = BytecodeBuilder::default().stop().build(); + let reverting = BytecodeBuilder::default().revert().build(); + let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); + let run = |callee: &Bytes, fails: bool| { + inspected(db(callee.clone()), minimal_envs(), tx.clone(), WritesAtTheEnd { fails }) + }; + assert!(holds_something(&run(&stopping, false), NOTE), "left a success, the write stays"); + assert!(!holds_something(&run(&stopping, true), NOTE), "failing it, the write goes"); + assert!(holds_something(&run(&reverting, false), NOTE), "revm failed it: the write stays"); +} diff --git a/crates/mega-evm/tests/satin/intrinsic.rs b/crates/mega-evm/tests/satin/intrinsic.rs index 4b9d75581..41dff06eb 100644 --- a/crates/mega-evm/tests/satin/intrinsic.rs +++ b/crates/mega-evm/tests/satin/intrinsic.rs @@ -1,28 +1,36 @@ -//! The intrinsic phase: the EIP-7976 calldata floor, the EIP-7981 access-list data charge, and -//! what the execution cap admits. +//! The intrinsic phase: the EIP-7976 calldata floor, the EIP-7981 access-list data charge, the +//! history gas of the transaction's body, and what the execution cap admits. //! //! Satin keeps Amsterdam's floor: a base of 12,000 with the recipient and value charges on top, //! and every calldata byte at 64 gas whether it is zero or not. EIP-7981 puts the access list's -//! own bytes in the floor at the same rate, while the per-item intrinsic charge stays at its -//! pre-EIP-8038 value. A transaction whose floor is above the 200M execution cap is rejected -//! before it runs, which is what bounds the calldata a transaction may carry. +//! own bytes in the floor at the same rate, and its per-item intrinsic charge is Amsterdam's: +//! EIP-8038's cold premium with those bytes at 64 gas each on top. A transaction whose floor is +//! above the 200M execution cap is rejected before it runs, which is what bounds the calldata a +//! transaction may carry. +//! +//! The floor is still computed and still validated, and it no longer decides what anyone pays: +//! history gas charges the same bytes at a higher rate, so a Satin transaction is always above +//! its own floor ([`test_the_calldata_floor_never_binds_once_history_is_charged`]). The floor +//! tests below read the floor off the result rather than off the bill. use alloy_evm::{Evm, EvmError, InvalidTxError}; use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - constants::{ACCOUNT_STATE_GAS, TX_GAS_LIMIT_CAP}, + constants::{ACCOUNT_STATE_GAS, COST_PER_HISTORY_BYTE, TX_GAS_LIMIT_CAP}, test_utils::{op_transaction, MemoryDatabase}, - MegaEvm, MegaTransaction, + MegaEvm, MegaTransaction, TX_BODY_SIZE, }; +use op_revm::OpTransactionError; use revm::{ context::{ - result::{ExecutionResult, InvalidTransaction}, + result::{EVMError, ExecutionResult, InvalidTransaction}, transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, + context_interface::cfg::GasId, primitives::B256, - Database, + Database, ExecuteCommitEvm, ExecuteEvm, }; use crate::common::{call, context, create, runs_at_measurement_prices}; @@ -33,15 +41,25 @@ const CALLEE: Address = address!("0000000000000000000000000000000000800001"); /// The intrinsic gas of a plain call to an account that is not the sender: the EIP-2780 sender /// base of 12,000 plus 3,000 for reaching the recipient. /// -/// The 3,000 is EIP-2780's own fixed charge, not the schedule's cold-account entry: inside -/// execution the schedule prices a cold account access at 2,600 — 100 for the read and 2,500 for -/// the cold surcharge — so repricing that entry would leave this number where it is. +/// The 3,000 is EIP-2780's own fixed charge, EIP-8038's cold account access, not the schedule's +/// cold-account entry: inside execution the schedule prices the same access as 100 for the read +/// and 2,900 for the cold surcharge, so repricing that entry would leave this number where it is. const EMPTY_CALL: u64 = 15_000; /// What one byte of anything a transaction carries costs in the EIP-7976 / EIP-7981 floor: four /// floor tokens at 16 gas each. const FLOOR_PER_BYTE: u64 = 64; +/// What one byte of anything a transaction carries costs on the history ledger, at the spec's own +/// price. +const HISTORY_PER_BYTE: u64 = COST_PER_HISTORY_BYTE; + +/// The history gas a transaction carrying `bytes` bytes beside its envelope pays for its body, at +/// the price the engine runs. +fn body_history(bytes: u64) -> u64 { + mega_evm::history_gas(TX_BODY_SIZE + bytes).expect("a body has a price") +} + /// A database where the sender can pay and `CALLEE` exists. fn funded() -> MemoryDatabase { MemoryDatabase::default() @@ -51,11 +69,29 @@ fn funded() -> MemoryDatabase { /// Runs `tx` and returns the gas it used, or the validation error that rejected it. fn gas_used(db: MemoryDatabase, tx: MegaTransaction) -> Result { + charged(db, tx).map(|charged| charged.gas_used) +} + +/// Runs `tx` and returns the EIP-7623 floor it was measured against, or the validation error +/// that rejected it. +fn floor(db: MemoryDatabase, tx: MegaTransaction) -> Result { + charged(db, tx).map(|charged| charged.floor) +} + +/// What a transaction was charged: the receipt's figure and the floor it was measured against. +struct Charged { + gas_used: u64, + floor: u64, +} + +/// Runs `tx` and reports what it was charged, or the validation error that rejected it. +fn charged(db: MemoryDatabase, tx: MegaTransaction) -> Result { let mut evm = MegaEvm::new(context(db)); match evm.transact_raw(tx) { Ok(outcome) => { assert!(outcome.result.is_success(), "{:?}", outcome.result); - Ok(outcome.result.gas().tx_gas_used()) + let gas = outcome.result.gas(); + Ok(Charged { gas_used: gas.tx_gas_used(), floor: gas.floor_gas() }) } Err(err) => { let invalid = err @@ -74,18 +110,17 @@ fn with_calldata(len: usize, byte: u8) -> MegaTransaction { crate::common::call_with_data(CALLER, CALLEE, Bytes::from(vec![byte; len]), 10_000_000) } -/// Empty calldata pays the intrinsic gas alone: the floor is the same number, so neither is the -/// binding one. +/// Empty calldata's floor is the intrinsic gas itself, so neither is the binding one. #[test] fn test_the_floor_of_empty_calldata_is_the_intrinsic_gas() { - assert_eq!(gas_used(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL)); + assert_eq!(floor(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL)); + assert_eq!(gas_used(funded(), with_calldata(0, 0)), Ok(EMPTY_CALL + body_history(0))); } -/// One byte of calldata costs 64 gas in the floor, which is above what the intrinsic phase -/// charges for it, so the floor is what the transaction pays. +/// One byte of calldata costs 64 gas in the floor. #[test] fn test_one_calldata_byte_costs_sixty_four_gas() { - assert_eq!(gas_used(funded(), with_calldata(1, 0x42)), Ok(EMPTY_CALL + FLOOR_PER_BYTE)); + assert_eq!(floor(funded(), with_calldata(1, 0x42)), Ok(EMPTY_CALL + FLOOR_PER_BYTE)); } /// A hundred bytes, and a kilobyte: the floor is linear in the byte count at the same rate. @@ -93,7 +128,7 @@ fn test_one_calldata_byte_costs_sixty_four_gas() { fn test_the_floor_is_sixty_four_gas_for_every_calldata_byte() { for len in [100u64, 1_024, 4_096] { assert_eq!( - gas_used(funded(), with_calldata(len as usize, 0x42)), + floor(funded(), with_calldata(len as usize, 0x42)), Ok(EMPTY_CALL + FLOOR_PER_BYTE * len), "{len} bytes" ); @@ -101,13 +136,45 @@ fn test_the_floor_is_sixty_four_gas_for_every_calldata_byte() { } /// A zero byte costs the same as a non-zero one in the floor: EIP-7976 prices the space a byte -/// takes in a block, not its value. +/// takes in a block, not its value. On the history ledger it costs the same too, and for the same +/// reason; only the intrinsic token rate tells the two apart, which is why the bill does. The bill +/// is the larger of the intrinsic charge with the body's history and the floor, so where a history +/// byte is cheap enough for the floor to bind, it binds both alike. #[test] fn test_a_zero_calldata_byte_costs_the_same_as_a_non_zero_one() { - let zeros = gas_used(funded(), with_calldata(1_024, 0x00)); - let non_zeros = gas_used(funded(), with_calldata(1_024, 0xff)); - assert_eq!(zeros, non_zeros); - assert_eq!(zeros, Ok(EMPTY_CALL + FLOOR_PER_BYTE * 1_024)); + let zeros = charged(funded(), with_calldata(1_024, 0x00)).expect("valid"); + let non_zeros = charged(funded(), with_calldata(1_024, 0xff)).expect("valid"); + assert_eq!(zeros.floor, non_zeros.floor); + assert_eq!(zeros.floor, EMPTY_CALL + FLOOR_PER_BYTE * 1_024); + let bill = + |per_byte: u64| (EMPTY_CALL + per_byte * 1_024 + body_history(1_024)).max(zeros.floor); + assert_eq!(zeros.gas_used, bill(4), "a zero byte: four gas and its history"); + assert_eq!( + non_zeros.gas_used, + bill(16), + "only the intrinsic token rate, four against sixteen, tells them apart", + ); +} + +/// The floor is computed and validated as it always was, and it never decides the bill: history +/// gas charges every calldata byte 88 where the floor charges it 64, on a base that is already +/// larger, so a Satin transaction is above its own floor from the first byte on. +#[test] +fn test_the_calldata_floor_never_binds_once_history_is_charged() { + if runs_at_measurement_prices() { + return; + } + const { assert!(HISTORY_PER_BYTE > FLOOR_PER_BYTE) }; + for len in [0u64, 1, 100, 4_096] { + let charged = charged(funded(), with_calldata(len as usize, 0x00)).expect("valid"); + assert_eq!(charged.floor, EMPTY_CALL + FLOOR_PER_BYTE * len, "{len} bytes: the floor"); + assert_eq!( + charged.gas_used, + EMPTY_CALL + 4 * len + body_history(len), + "{len} bytes: the intrinsic charge and the body, both above the floor", + ); + assert!(charged.gas_used > charged.floor, "{len} bytes: the floor does not bind"); + } } /* ---------- the EIP-7981 access-list data charge ---------- */ @@ -129,56 +196,80 @@ fn with_access_list(keys: usize) -> MegaTransaction { })) } -/// An access-list address costs 2,400 in the intrinsic phase — its pre-EIP-8038 price — and its -/// twenty bytes cost 64 each in the floor. With one address alone the intrinsic charge is the -/// larger of the two, so that is what the transaction pays. +/// An access-list address costs the schedule's entry in the intrinsic phase — 4,180, EIP-8038's +/// cold premium of 2,900 with its twenty bytes at 64 gas each on top — and its twenty bytes cost +/// 64 each in the floor. The intrinsic charge carries the floor's bytes and more, so it is what +/// the transaction pays. #[test] -fn test_an_access_list_address_is_priced_at_the_pre_eip8038_rate() { - assert_eq!(gas_used(funded(), with_access_list(0)), Ok(EMPTY_CALL + 2_400)); +fn test_an_access_list_address_pays_its_cold_premium_and_its_bytes() { + assert_eq!(floor(funded(), with_access_list(0)), Ok(EMPTY_CALL + 20 * FLOOR_PER_BYTE)); + assert_eq!( + gas_used(funded(), with_access_list(0)), + Ok(EMPTY_CALL + address_entry() + body_history(20)), + "the intrinsic charge and the address's twenty bytes of history", + ); } -/// A storage key costs 1,900 in the intrinsic phase and its thirty-two bytes cost 2,048 in the -/// floor, so every key pushes the floor further above the intrinsic sum. Past the address's -/// 1,120-gas head start the floor takes over, and from there the transaction pays the bytes. +/// A storage key costs the schedule's entry in the intrinsic phase — 4,048, EIP-8038's cold +/// premium of 2,000 with its thirty-two bytes at 64 gas each on top — and those bytes cost 2,048 +/// in the floor. The bytes are in both, and the intrinsic charge has the premium besides, so +/// however many keys there are the floor stays below what the transaction pays. #[test] fn test_access_list_bytes_are_counted_in_the_floor_at_sixty_four_each() { let address_bytes = 20 * FLOOR_PER_BYTE; let key_bytes = 32 * FLOOR_PER_BYTE; - for keys in [0u64, 1, 7] { + for keys in [0u64, 1, 7, 8, 16, 64] { assert_eq!( - gas_used(funded(), with_access_list(keys as usize)), - Ok(EMPTY_CALL + 2_400 + 1_900 * keys), - "{keys} keys: the intrinsic charge is still the larger" + floor(funded(), with_access_list(keys as usize)), + Ok(EMPTY_CALL + address_bytes + key_bytes * keys), + "{keys} keys: the floor counts every byte at the same rate" ); - } - for keys in [8u64, 16, 64] { + let floor = EMPTY_CALL + address_bytes + key_bytes * keys; + let intrinsic = EMPTY_CALL + address_entry() + key_entry() * keys; + assert!(intrinsic > floor, "{keys} keys: the intrinsic charge carries the floor's bytes"); assert_eq!( gas_used(funded(), with_access_list(keys as usize)), - Ok(EMPTY_CALL + address_bytes + key_bytes * keys), - "{keys} keys: the floor is the larger" + Ok(intrinsic + body_history(20 + 32 * keys)), + "{keys} keys: the intrinsic charge and the entry's bytes of history" ); } } +/// The intrinsic charge of an access-list address, at the schedule's price. +fn address_entry() -> u64 { + mega_evm::satin_gas_params().get(GasId::tx_access_list_address_cost()) +} + +/// The intrinsic charge of an access-list storage key, at the schedule's price. +fn key_entry() -> u64 { + mega_evm::satin_gas_params().get(GasId::tx_access_list_storage_key_cost()) +} + /* ---------- the execution cap ---------- */ /// The largest calldata the execution cap admits: its floor is the cap's own number rounded down /// to a whole byte. const LARGEST_CALLDATA: u64 = 3_124_765; -/// A call carrying `len` calldata bytes with a gas limit above the execution cap, so the cap is -/// what the floor is measured against. +/// A call carrying `len` calldata bytes with a gas limit that covers everything it has to pay, +/// above the execution cap, so the cap is what the floor is measured against. +/// +/// The body's history is not held to the cap — it comes out of the reservoir — so the limit has +/// to be above the cap by more than the body costs. fn with_calldata_over_the_cap(len: u64) -> MegaTransaction { crate::common::call_with_data( CALLER, CALLEE, Bytes::from(vec![0u8; len as usize]), - TX_GAS_LIMIT_CAP + 1_000_000, + TX_GAS_LIMIT_CAP + body_history(len) + 1_000_000, ) } -/// At the bound the transaction is admitted and pays its floor; one byte more and the floor is -/// above the execution cap, which rejects it before it runs. +/// At the bound the transaction is admitted; one byte more and the floor is above the execution +/// cap, which rejects it before it runs. +/// +/// The bound is the floor's, not the bill's: history gas is charged on top of it and neither the +/// floor nor the cap counts it, so what the transaction pays is far above the cap. #[test] fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { let floor = EMPTY_CALL + FLOOR_PER_BYTE * LARGEST_CALLDATA; @@ -189,7 +280,14 @@ fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { ); let db = funded().account_balance(CALLER, U256::from(10u128.pow(24))); - assert_eq!(gas_used(db.clone(), with_calldata_over_the_cap(LARGEST_CALLDATA)), Ok(floor)); + let charged = charged(db.clone(), with_calldata_over_the_cap(LARGEST_CALLDATA)).expect("valid"); + assert_eq!(charged.floor, floor); + // The floor binds where a history byte is cheaper than the floor's rate less the intrinsic + // one: the bill is the larger of the two. + assert_eq!( + charged.gas_used, + (EMPTY_CALL + 4 * LARGEST_CALLDATA + body_history(LARGEST_CALLDATA)).max(floor) + ); let expected = format!( "{:?}", @@ -202,7 +300,10 @@ fn test_the_execution_cap_bounds_the_calldata_a_transaction_may_carry() { } /// A floor above the transaction's own gas limit is rejected too, below the cap: the floor is -/// measured against whichever of the two is smaller. +/// measured against whichever of the two is smaller. The rejection leaves the sender as it was. +/// +/// Rules: [S4.26], [S21.1], [S21.2]. Independence: independent — the base, the floor's rate and the +/// sender's funding are written out. #[test] fn test_a_floor_above_the_gas_limit_is_rejected() { let gas_limit = 100_000; @@ -213,47 +314,49 @@ fn test_a_floor_above_the_gas_limit_is_rejected() { Bytes::from(vec![0u8; len as usize]), gas_limit, ); - let expected = format!( - "{:?}", + assert_rejected_and_sender_untouched( + tx, InvalidTransaction::GasFloorMoreThanGasLimit { gas_floor: EMPTY_CALL + FLOOR_PER_BYTE * len, gas_limit, - } + }, ); - assert_eq!(gas_used(funded(), tx), Err(expected)); - assert_sender_untouched(); -} - -/// The sender's nonce and balance are untouched by a transaction validation rejected. -fn assert_sender_untouched() { - let mut db = funded(); - let info = db.basic(CALLER).unwrap().unwrap(); - assert_eq!(info.nonce, 0); - assert_eq!(info.balance, U256::from(10u64.pow(18))); } -/* ---------- the state component is charged where it happens ---------- */ - -/// A transfer whose recipient must be created needs the account's state gas on top of the -/// intrinsic charge. The state gas is not part of the intrinsic phase, so a gas limit that covers -/// the intrinsic charge alone is accepted and then runs out of gas, charging the sender. -#[test] -fn test_a_transfer_that_cannot_pay_the_new_account_runs_out_of_gas() { - if runs_at_measurement_prices() { - return; +/// Validation rejects `tx` with `expected` on an EVM over [`funded`], through alloy-evm and through +/// revm's own entry point, and the sender is untouched in the database the second EVM ran on. +/// +/// That EVM runs `tx` as a block builder runs one transaction after another, without finalizing +/// it, and then commits what its journal holds: whatever the rejection left behind for the next +/// transaction reaches the database, where [`assert_sender_untouched`] reads the sender. +fn assert_rejected_and_sender_untouched(tx: MegaTransaction, expected: InvalidTransaction) { + assert_eq!(gas_used(funded(), tx.clone()), Err(format!("{expected:?}")), "through alloy-evm"); + let mut evm = MegaEvm::new(context(funded())); + match ExecuteEvm::transact_one(&mut evm, tx) { + Err(EVMError::Transaction(invalid)) => assert_eq!( + format!("{invalid:?}"), + format!("{:?}", OpTransactionError::Base(expected)), + "the rejection" + ), + other => panic!("expected the rejection {expected:?}, got {other:?}"), } - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let mut evm = MegaEvm::new(context(db)); - let outcome = evm - .transact_raw(call(CALLER, CALLEE, U256::from(1), 21_000 + ACCOUNT_STATE_GAS - 1)) - .expect("the transaction is admitted"); + ExecuteCommitEvm::commit_inner(&mut evm); + assert_sender_untouched(evm.db_mut()); +} - assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); - assert_eq!(outcome.state[&CALLER].info.nonce, 1, "the sender paid for the attempt"); +/// The sender's nonce and balance in `db`, the database a rejected transaction ran on, are what +/// [`funded`] gave it. +fn assert_sender_untouched(db: &mut MemoryDatabase) { + let info = db.basic(CALLER).expect("the database reads").expect("the sender exists"); + assert_eq!(info.nonce, 0, "the sender's nonce"); + assert_eq!(info.balance, U256::from(10u64.pow(18)), "the sender's balance"); } -/// The same for a creation: the created account's state gas is charged as the frame starts, not -/// at validation. +/* ---------- the state component is charged where it happens ---------- */ + +/// A creation transaction's created account's state gas is charged as the frame starts, not at +/// validation: a gas limit that covers the intrinsic charge alone is accepted and then runs out of +/// gas, charging the sender. #[test] fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { if runs_at_measurement_prices() { @@ -262,30 +365,74 @@ fn test_a_creation_that_cannot_pay_its_account_runs_out_of_gas() { let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); let mut evm = MegaEvm::new(context(db)); let outcome = evm - .transact_raw(create(CALLER, Bytes::new(), 24_000 + ACCOUNT_STATE_GAS - 1)) + .execute_transaction(create(CALLER, Bytes::new(), 24_000 + ACCOUNT_STATE_GAS - 1)) .expect("the transaction is admitted"); assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); assert_eq!(outcome.state[&CALLER].info.nonce, 1, "the sender paid for the attempt"); + assert_eq!(outcome.gas.gas_used, 24_000 + ACCOUNT_STATE_GAS - 1, "its whole gas limit"); + assert_eq!(outcome.gas.state, 0, "and the account it could not pay for is not created"); } /// A gas limit below the intrinsic charge itself is a validation rejection, which leaves the /// sender untouched. +/// +/// The figure the error carries is one reading of a point the spec leaves open. The spec fixes +/// the rejection and its error, `CallGasCostMoreThanGasLimit`, for a gas limit below the intrinsic +/// regular gas plus the body's history, but not which figure the error names. Here, below the +/// intrinsic regular gas alone, it names that charge without the body's history; a gas limit that +/// covers the intrinsic charge but not the body is named with the whole minimum (the next test). +/// Whether the error should name one figure in both cases is undecided, so a change to it is not +/// a change of the rules this test holds: the rejection, and a sender left untouched. +/// +/// Rules: [S4.25], [S21.1]. Independence: independent — the intrinsic charge and the sender's +/// funding are written out. #[test] fn test_a_gas_limit_below_the_intrinsic_charge_is_rejected() { - let expected = format!( - "{:?}", + assert_rejected_and_sender_untouched( + call(CALLER, CALLEE, U256::ZERO, EMPTY_CALL - 1), InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit: EMPTY_CALL - 1, initial_gas: EMPTY_CALL, - } + }, ); - assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, EMPTY_CALL - 1)), Err(expected)); - assert_sender_untouched(); } /// A plain call within its limits still goes through, so the checks above are not too eager. #[test] fn test_a_valid_call_still_passes() { - assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, 1_000_000)), Ok(EMPTY_CALL)); + assert_eq!( + gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, 1_000_000)), + Ok(EMPTY_CALL + body_history(0)), + ); +} + +/// A gas limit that covers the intrinsic charge but not the body's history is a validation +/// rejection too, naming the whole figure: the bytes a transaction carries are part of what makes +/// it valid, so a transaction that cannot pay for them is never included, and leaves the sender +/// untouched. +/// +/// The figure the error carries — the whole minimum, the intrinsic charge and the body's history +/// together — is one reading of a point the spec leaves open: the spec fixes the rejection and its +/// error, not which figure the error names, and below the intrinsic charge alone the error names +/// that charge without the body (the test above). Whether it should name one figure in both cases +/// is undecided, so a change to it is not a change of the rules this test holds: the rejection, a +/// sender left untouched, and a gas limit of the whole minimum admitted. +/// +/// Rules: [S4.25], [S7.17], [S21.1]. Independence: independent for the intrinsic charge and the +/// sender's funding, which are written out; the body's history is priced by the production +/// helper. +#[test] +fn test_a_gas_limit_short_of_the_body_is_rejected() { + if runs_at_measurement_prices() { + return; + } + let minimum = EMPTY_CALL + body_history(0); + for gas_limit in [EMPTY_CALL, EMPTY_CALL + 1, minimum - 1] { + assert_rejected_and_sender_untouched( + call(CALLER, CALLEE, U256::ZERO, gas_limit), + InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas: minimum }, + ); + } + assert_eq!(gas_used(funded(), call(CALLER, CALLEE, U256::ZERO, minimum)), Ok(minimum)); } diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs new file mode 100644 index 000000000..efe41c39e --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -0,0 +1,164 @@ +//! Who is held to no per-transaction limit: a transaction the protocol itself sent, and a system +//! call. +//! +//! The data-size limit and its frame budgets hold what users do. The protocol's own work — the +//! maintenance a system transaction performs, the calls the protocol makes before a block's +//! transactions — must not fail on them, as it pays no history gas for the same reason. What it +//! uses is counted all the same, and reported. +//! +//! A user's deposit is not the protocol's work: it is held to every limit, and so is a user's +//! transaction that calls a system contract. + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0}, + context::TxEnv, +}; + +use crate::common::{context, deposit, execute_under, slot_state_gas}; + +const CALLER: Address = address!("0000000000000000000000000000000000b00000"); +/// A contract the program calls, which writes a slot of its own. +const HELPER: Address = address!("0000000000000000000000000000000000b00001"); +/// A contract that runs the program, for the transactions that are not the system's. +const CONTRACT: Address = address!("0000000000000000000000000000000000b00002"); + +const GAS_LIMIT: u64 = 50_000_000; + +/// Two fresh slots, a log of 64 bytes, and a call to [`HELPER`], which writes a third slot in a +/// frame of its own: state gas, write records and data size in the transaction's own frame and in +/// a child. +fn program() -> Bytes { + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(2)) + .push_number(64_u64) + .push_number(0_u64) + .append(LOG0) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(HELPER) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build() +} + +/// The program at the whitelisted contract a system transaction may call, and at [`CONTRACT`]. +/// +/// A call with no calldata carries no selector, so the Oracle's interceptor lets it through to the +/// code at its address. +fn db() -> MemoryDatabase { + let helper = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::ZERO) + .account_code(ORACLE_CONTRACT_ADDRESS, program()) + .account_code(CONTRACT, program()) + .account_code(HELPER, helper) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) +} + +/// A call to `to` from `caller`. +fn call_from(caller: Address, to: Address) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(to), + gas_limit: GAS_LIMIT, + ..Default::default() + })) +} + +/// Every per-transaction limit the program crosses, one at a time, and all of them together. +fn limits() -> [(&'static str, EvmTxRuntimeLimits); 3] { + let none = EvmTxRuntimeLimits::no_limits(); + [ + ("the transaction's data size", none.with_tx_data_size_limit(TX_BODY_SIZE)), + ("a frame's data size", none.with_frame_data_size_limit(WRITE_RECORD_SIZE)), + ("every limit at zero", none.with_tx_data_size_limit(0).with_frame_data_size_limit(0)), + ] +} + +/// A system transaction over any of the limits, or all of them, runs as it does without one, and +/// reports what it used: its body, three slots' records and state gas, and the log. +#[test] +fn test_a_system_transaction_is_held_to_no_limit() { + let tx = || call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + let free = execute_under(db(), tx(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{:?}", free.result); + assert_eq!(free.usage.write_records, 3, "three slots"); + assert_eq!(free.usage.data_size, TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 32 + 64); + assert!(free.gas.state >= 3 * slot_state_gas(), "at least its three slots' state gas"); + + for (name, limits) in limits() { + let outcome = execute_under(db(), tx(), limits); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}"); + assert_eq!(outcome.usage, free.usage, "{name}: its usage is counted all the same"); + assert_eq!(outcome.gas, free.gas, "{name}"); + assert_eq!(outcome.state, free.state, "{name}"); + } +} + +/// A system call over any of the limits runs as it does without one, whatever caller it names, +/// and the layer reports what it used: its body, three slots' records and the log, in data size, +/// and the three records in the KV count. +/// +/// Rule [S19.5]. Expected values `independent`: the spec's byte table by hand — a body of 310 +/// bytes, 40 a record, and a log's 32 bytes of base and its 64 bytes of data. +#[test] +fn test_a_system_call_is_held_to_no_limit() { + let run = |limits| { + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)); + let result = Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()) + .expect("the system call runs"); + ( + result, + evm.ctx().additional_limit().usage(), + evm.ctx().additional_limit().limit_exceeded().copied(), + ) + }; + let (free, free_usage, _) = run(EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{:?}", free.result); + assert_eq!(free_usage.write_records, 3); + assert_eq!(free_usage.data_size, 310 + 3 * 40 + 32 + 64, "its body, records and log"); + + for (name, limits) in limits() { + let (result, usage, stop) = run(limits); + assert!(result.result.is_success(), "{name}: {:?}", result.result); + assert_eq!(stop, None, "{name}"); + assert_eq!(usage, free_usage, "{name}: its usage is counted all the same"); + assert_eq!(result.result, free.result, "{name}"); + } +} + +/// A user's deposit is held to the limits: over the data size, it is stopped. So is a user's +/// transaction to the contract a system transaction may call. +#[test] +fn test_a_deposit_and_a_user_call_to_a_system_contract_are_held_to_the_limits() { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); + let cases = [ + ("a deposit", deposit(call_from(CALLER, CONTRACT))), + ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), + ]; + for (name, tx) in cases { + let outcome = execute_under(db(), tx, limits); + let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}: stopped")); + assert!( + matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }), + "{name}: {stop:?}" + ); + assert!( + !outcome.result.is_success() && !outcome.result.is_halt(), + "{name}: {:?}", + outcome.result + ); + } +} diff --git a/crates/mega-evm/tests/satin/limit_stop.rs b/crates/mega-evm/tests/satin/limit_stop.rs new file mode 100644 index 000000000..5d313ba85 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_stop.rs @@ -0,0 +1,187 @@ +//! Reading a limit stop off a transaction's result, as an RPC maps it. +//! +//! Every limit stopping a transaction is the stops matrix's (`stops.rs`), which reads each stop +//! through [`MegaTransactionOutcome::limit_stop`] too. Here: revert data that only looks like a +//! stop, and which crossing the outcome names. The outcome's `limit_exceeded` decides: it names the +//! crossing that produced the result of the transaction's own frame, a frame budget's included, +//! and a revert carrying a stop's bytes without it is no stop. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + decode_mega_limit_exceeded, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitStop, MegaEvm, MegaTransactionOutcome, + LOG_BASE_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{LOG0, POP, PUSH0}, + context::{result::ExecutionResult, ContextTr}, + context_interface::cfg::GasId, + interpreter::{CallInputs, CallOutcome, InstructionResult, InterpreterTypes}, + Inspector, +}; + +use crate::common::{call, context, create, execute_under, history}; + +const CALLER: Address = address!("0000000000000000000000000000000000570000"); +const A: Address = address!("0000000000000000000000000000000000570001"); +const B: Address = address!("0000000000000000000000000000000000570002"); + +/// Runs a call from `CALLER` to `A` over `db` under `limits`. +fn execute(db: MemoryDatabase, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + execute_under(db, call(CALLER, A, U256::ZERO, 10_000_000), limits) +} + +/// The output of a transaction that reverted. +fn reverted_with(outcome: &MegaTransactionOutcome) -> &Bytes { + match &outcome.result { + ExecutionResult::Revert { output, .. } => output, + other => panic!("expected a revert, got {other:?}"), + } +} + +/// A contract that reverts with a stop's exact bytes, of every kind: the output decodes as the +/// stop's, the outcome names no limit, and no stop is read. +#[test] +fn test_a_contract_reverting_with_a_stops_bytes_is_no_stop() { + let kinds = [LimitKind::DataSize, LimitKind::ComputeGas]; + for kind in kinds { + let data = + LimitCheck::ExceedsLimit { kind, limit: 7, used: 8, frame_local: false }.revert_data(); + let code = BytecodeBuilder::default().revert_with_data(&data).build(); + let outcome = + execute(MemoryDatabase::default().account_code(A, code), EvmTxRuntimeLimits::default()); + + let output = reverted_with(&outcome); + assert_eq!(output, &data, "{kind:?}"); + assert_eq!(decode_mega_limit_exceeded(output), Some((kind, 7)), "{kind:?}: it decodes"); + assert_eq!(outcome.limit_exceeded, None, "{kind:?}"); + assert_eq!(outcome.limit_stop(), None, "{kind:?}: and it is no stop"); + } +} + +/// A frame its data-size budget stopped reverts alone with a stop's bytes, and its caller runs +/// on. A caller that re-raises them ends the transaction on them, and the transaction was not +/// stopped: no limit of its own was crossed. +#[test] +fn test_a_frame_budget_re_raised_by_its_caller_is_no_stop() { + const FRAME_CAP: u64 = 1_000; + let logs_past_the_cap = + BytecodeBuilder::default().push_number(2 * FRAME_CAP).append_many([PUSH0, LOG0]).stop(); + let re_raises = + BytecodeBuilder::default().call(B, U256::ZERO).append(POP).revert_with_returndata(); + let db = MemoryDatabase::default() + .account_code(A, re_raises.build()) + .account_code(B, logs_past_the_cap.build()); + let outcome = + execute(db, EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(FRAME_CAP)); + + let decoded = decode_mega_limit_exceeded(reverted_with(&outcome)); + assert!( + matches!(decoded, Some((LimitKind::DataSize, budget)) if budget <= FRAME_CAP), + "the output is the frame budget's stop: {decoded:?}" + ); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.limit_stop(), None); +} + +/// Limits holding nothing but every frame's data size, to `cap` bytes. +fn frame_capped(cap: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap) +} + +/// `A` logging `FRAME_CAP` bytes, which with the log's own 32 cross its frame cap of as many. +const FRAME_CAP: u64 = 1_000; + +/// A database where `A` logs past [`FRAME_CAP`]. +fn logging_past_the_cap() -> MemoryDatabase { + let code = BytecodeBuilder::default().push_number(FRAME_CAP).append_many([PUSH0, LOG0]).stop(); + MemoryDatabase::default().account_code(A, code.build()) +} + +/// The transaction's own frame stopped by its own data-size budget ends the transaction on that +/// crossing: the outcome names it, a frame budget though it is, and the stop is read off the +/// result. +#[test] +fn test_the_transactions_own_frame_stopped_by_its_budget_is_a_stop() { + let outcome = execute(logging_past_the_cap(), frame_capped(FRAME_CAP)); + + let used = LOG_BASE_SIZE + FRAME_CAP; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: FRAME_CAP, + used, + frame_local: true, + }; + assert_eq!(reverted_with(&outcome), &stop.revert_data()); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!( + outcome.limit_stop(), + Some(LimitStop { kind: LimitKind::DataSize, limit: FRAME_CAP, used }) + ); +} + +/// A creation transaction whose deposit crosses its own frame's budget is stopped by it: the +/// creation's frame records the account it creates, then the code it would deposit, one byte more +/// than its budget holds. The reservoir of a gas limit far above the execution cap pays the +/// deposit's state gas and history at the byte prices in effect, so the budget is what refuses it. +#[test] +fn test_a_creation_whose_deposit_crosses_its_budget_is_a_stop() { + const CODE: u64 = 100; + let init = BytecodeBuilder::default().return_with_data([0_u8; CODE as usize]).build(); + let used = WRITE_RECORD_SIZE + CODE; + let cap = used - 1; + let roomy = TX_GAS_LIMIT_CAP + + CODE * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + + history(CODE) + + 1_000_000_000; + let outcome = + MegaEvm::new(context(MemoryDatabase::default()).with_tx_runtime_limits(frame_capped(cap))) + .execute_transaction(create(CALLER, init, roomy)) + .expect("the transaction is valid"); + + let stop = + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: cap, used, frame_local: true }; + assert_eq!(reverted_with(&outcome), &stop.revert_data()); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!( + outcome.limit_stop(), + Some(LimitStop { kind: LimitKind::DataSize, limit: cap, used }) + ); +} + +/// Rewrites every call's result into a success, keeping its output. +#[derive(Debug, Default)] +struct Revives; + +impl Inspector for Revives { + fn call_end(&mut self, _context: &mut CTX, _inputs: &CallInputs, outcome: &mut CallOutcome) { + outcome.result.result = InstructionResult::Return; + } +} + +/// The transaction's own frame stopped by its budget and turned into a success by an inspector +/// ends on the success, the stop's bytes for its output: the crossing no longer produced the +/// result, which is no revert, so the outcome names none. +#[test] +fn test_a_stop_an_inspector_turns_into_a_success_is_no_stop() { + let ctx = context(logging_past_the_cap()).with_tx_runtime_limits(frame_capped(FRAME_CAP)); + let outcome = MegaEvm::new(ctx) + .with_inspector(Revives) + .execute_transaction(call(CALLER, A, U256::ZERO, 10_000_000)) + .expect("the transaction is valid"); + + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: FRAME_CAP, + used: LOG_BASE_SIZE + FRAME_CAP, + frame_local: true, + }; + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("expected a success, got {:?}", outcome.result) + }; + assert_eq!(output.data(), &stop.revert_data(), "the stop's bytes, in a success"); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.limit_stop(), None); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index 6c6ddbe74..dd2ee96c2 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -1,12 +1,35 @@ //! Tests of the Satin engine. mod common; +mod compute_gas; mod contract_size; +mod corpus; +mod count_order; +mod create_opcodes; +mod data_size; +mod data_size_counts; mod db_error; +mod deposit_charge; +mod detained_transfers; +mod detention; mod equivalence; +mod failed_deposit; +mod floor_exempt; +mod history_bytes; +mod history_exemption; +mod history_gas; +mod history_reservoir; +mod inherited_costs; mod inspector; +mod inspector_cheatcodes; +mod inspector_limits; +mod inspector_settlement; mod intrinsic; +mod limit_exemption; +mod limit_stop; +mod neutral; mod outcome; +mod pool_validation; mod precompile_gas; mod pricing_table; mod salt; @@ -15,8 +38,18 @@ mod salt_deposit; mod salt_failure; mod salt_refund; mod schedule; +#[path = "../shared/snapshot.rs"] +mod snapshot; +mod spec_numbers; mod state; +mod state_growth; mod static_callee; +mod stops; +mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; +mod system_call; +mod transfer_logs; +mod volatile_access; +mod withheld_gas; mod write_records; diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs new file mode 100644 index 000000000..da8f4d79b --- /dev/null +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -0,0 +1,374 @@ +//! The neutral configuration the execution-spec gate runs Ethereum's fixtures under. +//! +//! Under it, `MegaEvm` must agree exactly — gas, refund, logs, output and state — with two +//! references, where on Satin's own configuration it spends the history ledger more +//! (`equivalence.rs`): +//! +//! - op-revm's `OpEvm` on the same configuration, which routes fees the way Satin does, for priced +//! transactions: a transfer that creates its recipient, a fresh slot, a log, a creation and a +//! nested value call, whose two write records Satin charges its caller for; +//! - revm's own mainnet EVM on the fork's spec, which is Ethereum, for unpriced ones: the same +//! programs, plus the two parts of a fork's pricing the EVM rather than the context carries — an +//! `EXTCODESIZE`, whose static price Amsterdam raises, and a KZG point evaluation, which +//! `MegaETH` prices at twice upstream's. +//! +//! Each case runs on Osaka's configuration and on Amsterdam's. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use mega_evm::{ + test_utils::{ + neutral_cfg, neutralize_evm, op_transaction, take_system_address_read, + zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + EthSpecId, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + VolatileDataAccess, +}; +use op_revm::{ + constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + L1BlockInfo, OpEvm, OpHaltReason, OpSpecId, OpTransaction, +}; +use revm::{ + bytecode::opcode::{ + ADDRESS, BALANCE, CALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, PUSH1, SSTORE, + TIMESTAMP, + }, + context::{ + result::{ExecResultAndState, ExecutionResult}, + BlockEnv, CfgEnv, Context, ContextTr, TxEnv, + }, + inspector::NoOpInspector, + state::EvmState, + ExecuteEvm, Journal, MainBuilder, MainContext, +}; + +use crate::precompile_gas::kzg_input; + +const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); +const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); +const COINBASE: Address = address!("0x00000000000000000000000000000000000c0ffe"); + +type Outcome = ExecResultAndState, EvmState>; +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +const FORKS: [EthSpecId; 2] = [EthSpecId::OSAKA, EthSpecId::AMSTERDAM]; + +fn block() -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1_800_000_000u64), + gas_limit: 100_000_000, + basefee: 7, + beneficiary: COINBASE, + ..Default::default() + } +} + +/// Runs `tx` on `db` through a neutral `MegaEvm` for `fork` and through op-revm's `OpEvm` on the +/// configuration that context holds, and returns both outcomes and the history ledger `MegaEvm` +/// reported. The read of the live system address, which op-revm does not make, is taken out of +/// `MegaEvm`'s state. +fn run_both(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, u64) { + let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let op_ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(ctx.cfg().clone()) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + + let mut mega = MegaEvm::new(ctx); + neutralize_evm(&mut mega, fork).expect("a neutral fork"); + let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); + let mut state = outcome.result_and_state.state; + take_system_address_read(&mut state); + let mega = ExecResultAndState::new(outcome.result_and_state.result, state); + + let op = OpEvm::new(op_ctx, NoOpInspector).transact(op_transaction(tx)).unwrap(); + (mega, op, outcome.gas.history) +} + +/// Asserts the two outcomes agree field by field, then as a whole, and that nothing was priced +/// as history. +fn assert_same(fork: EthSpecId, (mega, op, history): (Outcome, Outcome, u64)) { + assert_eq!(history, 0, "{fork:?}: no history gas"); + assert_eq!(mega.result.gas(), op.result.gas(), "{fork:?}: ResultGas"); + assert_eq!(mega.result.logs(), op.result.logs(), "{fork:?}: logs"); + assert_eq!(mega.result, op.result, "{fork:?}: execution result"); + assert_eq!(mega.state, op.state, "{fork:?}: state"); +} + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))) +} + +fn call(data: Bytes, value: U256) -> TxEnv { + TxEnv { + caller: CALLER, + kind: TxKind::Call(CALLEE), + data, + value, + gas_price: 10, + gas_limit: 1_000_000, + ..Default::default() + } +} + +/// A priced transfer that creates its recipient: the fees go where op-revm sends them, and the +/// new account costs what the fork's schedule says. +#[test] +fn test_neutral_transfer_matches_op_revm() { + for fork in FORKS { + let outcome = run_both(fork, funded(), call(Bytes::new(), U256::from(1_000))); + assert!(outcome.0.result.is_success()); + assert_same(fork, outcome); + } +} + +#[test] +fn test_neutral_sstore_matches_op_revm() { + let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build(); + for fork in FORKS { + let outcome = run_both( + fork, + funded().account_code(CALLEE, code.clone()), + call(Bytes::new(), U256::ZERO), + ); + assert!(outcome.0.result.is_success()); + assert_same(fork, outcome); + } +} + +#[test] +fn test_neutral_log_matches_op_revm() { + // LOG3 of the 32-byte word 7 under topics 1, 2 and 3. + let code = BytecodeBuilder::default() + .mstore(0, U256::from(7).to_be_bytes::<32>()) + .push_number(3u8) + .push_number(2u8) + .push_number(1u8) + .push_number(32u8) + .append(PUSH0) + .append(LOG3) + .stop() + .build(); + for fork in FORKS { + let outcome = run_both( + fork, + funded().account_code(CALLEE, code.clone()), + call(Bytes::new(), U256::ZERO), + ); + assert_eq!(outcome.0.result.logs().len(), 1); + assert_same(fork, outcome); + } +} + +#[test] +fn test_neutral_creation_matches_op_revm() { + let init_code = + BytecodeBuilder::default().return_with_data([0x60, 0x00, 0x60, 0x00, 0xf3]).build(); + for fork in FORKS { + let tx = TxEnv { + kind: TxKind::Create, + data: init_code.clone(), + ..call(Bytes::new(), U256::ZERO) + }; + let outcome = run_both(fork, funded(), tx); + assert!(outcome.0.result.is_success(), "{:?}", outcome.0.result); + assert_same(fork, outcome); + } +} + +/// A nested value call: on Satin's configuration its caller pays for the two write records the +/// callee's frame makes, and the callee gets a history allowance. Neither shows here. +#[test] +fn test_neutral_nested_value_call_matches_op_revm() { + let inner = address!("0x5000000000000000000000000000000000000002"); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(inner) + .append(GAS) + .append(CALL) + .append(POP) + .stop() + .build(); + for fork in FORKS { + let db = + funded().account_balance(CALLEE, U256::from(10_000)).account_code(CALLEE, code.clone()); + let outcome = run_both(fork, db, call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success()); + assert_same(fork, outcome); + } +} + +/// Runs `tx` on `db`, unpriced, through a neutral `MegaEvm` for `fork` and through revm's mainnet +/// EVM on `fork`'s spec, and returns both outcomes and the history ledger `MegaEvm` reported. +/// +/// op-revm credits the three fee vaults with nothing here and so touches them; the touched, empty +/// accounts it leaves are not Ethereum's, and are taken out of `MegaEvm`'s state before the two +/// are compared, with the read of the live system address. +fn run_against_ethereum(fork: EthSpecId, db: MemoryDatabase, tx: TxEnv) -> (Outcome, Outcome, u64) { + let block = BlockEnv { basefee: 0, ..block() }; + let tx = TxEnv { gas_price: 0, ..tx }; + let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block.clone()) + .with_chain(zero_fee_l1_block_info()); + let mut mega = MegaEvm::new(ctx); + neutralize_evm(&mut mega, fork).expect("a neutral fork"); + let outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); + let mut state = outcome.result_and_state.state; + take_system_address_read(&mut state); + for vault in [BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + if state.get(&vault).is_some_and(|account| account.is_empty()) { + state.remove(&vault); + } + } + let mega = ExecResultAndState::new(outcome.result_and_state.result, state); + + let mut cfg = CfgEnv::new(); + cfg.set_spec_and_mainnet_gas_params(fork); + let eth = Context::mainnet() + .with_db(db) + .with_cfg(cfg) + .with_block(block) + .build_mainnet() + .transact(tx) + .unwrap(); + let eth = ExecResultAndState::new(eth.result.map_haltreason(OpHaltReason::Base), eth.state); + (mega, eth, outcome.gas.history) +} + +/// A caller whose code is `code`, funded, with an empty callee. +fn with_code(code: Bytes) -> MemoryDatabase { + funded().account_code(CALLEE, code) +} + +#[test] +fn test_neutral_programs_match_ethereum() { + let log = BytecodeBuilder::default() + .mstore(0, U256::from(7).to_be_bytes::<32>()) + .push_number(1u8) + .push_number(32u8) + .append(PUSH0) + .append(LOG1) + .stop() + .build(); + let cases = [ + ("transfer", funded(), call(Bytes::new(), U256::from(1_000))), + ( + "sstore", + with_code(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(42)).stop().build()), + call(Bytes::new(), U256::ZERO), + ), + ("log", with_code(log), call(Bytes::new(), U256::ZERO)), + ( + "creation", + funded(), + TxEnv { + kind: TxKind::Create, + data: BytecodeBuilder::default() + .return_with_data([0x60, 0x00, 0x60, 0x00, 0xf3]) + .build(), + ..call(Bytes::new(), U256::ZERO) + }, + ), + ]; + for fork in FORKS { + for (name, db, tx) in cases.clone() { + let outcome = run_against_ethereum(fork, db, tx); + assert!(outcome.1.result.is_success(), "{name}: {:?}", outcome.1.result); + assert_same(fork, outcome); + } + } +} + +/// The neutral configuration, under the limits the gate's runner installs with it, detains +/// nothing: `no_limits` leaves detention's caps unlimited, so a program that reads the block +/// environment and the block beneficiary's account records no read and sets no compute limit, and +/// matches Ethereum. +#[test] +fn test_neutral_reads_of_volatile_data_detain_nothing() { + let code = BytecodeBuilder::default() + .append_many([TIMESTAMP, NUMBER, revm::bytecode::opcode::COINBASE, BALANCE, POP, POP, POP]) + .sstore(U256::ZERO, U256::from(1)) + .stop() + .build(); + let block = BlockEnv { basefee: 0, ..block() }; + for fork in FORKS { + let ctx = MegaContext::new(with_code(code.clone()), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block.clone()) + .with_chain(zero_fee_l1_block_info()); + let mut mega = MegaEvm::new(ctx); + neutralize_evm(&mut mega, fork).expect("a neutral fork"); + let tx = TxEnv { gas_price: 0, ..call(Bytes::new(), U256::ZERO) }; + let outcome = mega.execute_transaction(OpTx(op_transaction(tx))).unwrap(); + assert!(outcome.result.is_success(), "{fork:?}"); + assert!(!mega.ctx().detention().detains(), "{fork:?}"); + assert_eq!(mega.ctx().detention().accessed(), VolatileDataAccess::empty(), "{fork:?}"); + assert_eq!(mega.ctx().detention().compute_limit(), None, "{fork:?}"); + + let outcome = + run_against_ethereum(fork, with_code(code.clone()), call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success()); + assert_same(fork, outcome); + } +} + +/// `EXTCODESIZE` pays Amsterdam's static price under Amsterdam's configuration, which Satin's +/// instruction table, on its Osaka base, does not carry. +#[test] +fn test_neutral_extcodesize_matches_ethereum() { + let code = + BytecodeBuilder::default().append(ADDRESS).append(EXTCODESIZE).append(POP).stop().build(); + for fork in FORKS { + let outcome = + run_against_ethereum(fork, with_code(code.clone()), call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success()); + assert_same(fork, outcome); + } +} + +/// A KZG point evaluation forwarded 60,000 gas succeeds, as upstream prices it at 50,000: the +/// fork's precompile set, not Satin's, which prices it at 100,000. +#[test] +fn test_neutral_kzg_call_matches_ethereum() { + let code = BytecodeBuilder::default() + .mstore(0, kzg_input()) + .push_number(64u8) + .append(PUSH0) + .push_number(192u8) + .append(PUSH0) + .append(PUSH0) + .push_address(revm::precompile::kzg_point_evaluation::ADDRESS) + .push_number(60_000u32) + .append(CALL) + .append(PUSH0) + .append(SSTORE) + .stop() + .build(); + for fork in FORKS { + let outcome = + run_against_ethereum(fork, with_code(code.clone()), call(Bytes::new(), U256::ZERO)); + assert_eq!( + outcome.0.state[&CALLEE].storage[&U256::ZERO].present_value, + U256::from(1), + "{fork:?}: the evaluation succeeded" + ); + assert_same(fork, outcome); + } +} diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index 95fd050d9..d65b69196 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -3,13 +3,15 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolError; use mega_evm::{ - constants::{SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + constants::{COST_PER_HISTORY_BYTE, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, BlockGasCounters, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, - MegaLimitExceeded, MegaTransactionOutcome, WRITE_RECORD_SIZE, + MegaLimitExceeded, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use crate::common::{call, context, runs_at_measurement_prices}; +use crate::common::{ + body_history, call, context, execute_under, history, runs_at_measurement_prices, slot_state_gas, +}; const CALLER: Address = address!("0000000000000000000000000000000000600000"); const CONTRACT: Address = address!("0000000000000000000000000000000000600001"); @@ -23,14 +25,18 @@ fn writer() -> MemoryDatabase { MemoryDatabase::default().account_code(CONTRACT, code) } +/// A gas limit for a call to [`writer`]: 1,000,000 of regular gas on top of what its two slots, +/// their records and the body cost at the byte prices in effect. +fn writer_gas() -> u64 { + 1_000_000 + 2 * slot_state_gas() + body_history(0) + history(2 * WRITE_RECORD_SIZE) +} + fn execute( db: MemoryDatabase, limits: EvmTxRuntimeLimits, gas_limit: u64, ) -> MegaTransactionOutcome { - MegaEvm::new(context(db).with_tx_runtime_limits(limits)) - .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, gas_limit)) - .unwrap() + execute_under(db, call(CALLER, CONTRACT, U256::ZERO, gas_limit), limits) } /// The ledgers split the raw spend, the receipt reports revm's gas used, and the reservoir the @@ -48,9 +54,21 @@ fn test_outcome_reports_the_ledgers() { assert_eq!(gas.gas_used, result_gas.tx_gas_used()); // Both slots are new, so both draw state gas, and the reservoir is what pays it. assert_eq!(gas.state, 2 * SLOT_STATE_GAS); - assert_eq!(gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * SLOT_STATE_GAS); - assert_eq!(gas.history, 0, "nothing prices history bytes yet"); - assert_eq!(outcome.usage, LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }); + // The body's history comes out of the same reservoir, before the state gas does, and each of + // the two new slots leaves a write record that is history too. + assert_eq!( + gas.history, + (TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) * COST_PER_HISTORY_BYTE, + "the transaction's body and the two write records", + ); + assert_eq!( + gas.reservoir_remaining, + 1_000_000_000 - TX_GAS_LIMIT_CAP - 2 * SLOT_STATE_GAS - gas.history, + ); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 } + ); assert_eq!(outcome.limit_exceeded, None); let mut block = BlockGasCounters::default(); @@ -58,24 +76,32 @@ fn test_outcome_reports_the_ledgers() { block.record(&gas); assert_eq!(block.execution, 2 * gas.block_execution_gas()); assert_eq!(block.state, 2 * gas.state); + assert_eq!(block.history, 2 * gas.history); } /// A stopped transaction reports the stop. #[test] fn test_outcome_reports_the_stop() { - let outcome = - execute(writer(), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(40), 1_000_000); + let outcome = execute( + writer(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + 40), + writer_gas(), + ); assert!(!outcome.result.is_success()); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: 40, - used: 80, + limit: TX_BODY_SIZE + 40, + used: TX_BODY_SIZE + 80, frame_local: false }) ); - assert_eq!(outcome.usage, LimitUsage::ZERO, "the stopped transaction keeps nothing"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + "the stop drops the writes and keeps the body" + ); } /// A contract reverting with `MegaLimitExceeded`'s bytes on its own is not a stop. @@ -112,12 +138,14 @@ impl revm::Inspector f #[test] fn test_convenience_execution_methods_work() { let mut evm = MegaEvm::new(context(writer())).with_inspector(Steps::default()); - let inspected = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + let inspected = + evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, writer_gas())).unwrap(); assert!(inspected.result.is_success()); let steps = evm.inspector().0; assert!(steps > 0, "the enabled inspector ran"); alloy_evm::Evm::set_inspector_enabled(&mut evm, false); - let executed = evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 1_000_000)).unwrap(); + let executed = + evm.execute_transaction(call(CALLER, CONTRACT, U256::ZERO, writer_gas())).unwrap(); assert!(executed.result.is_success()); assert_eq!(evm.inspector().0, steps, "the disabled inspector did not run"); assert_eq!(inspected.gas, executed.gas); diff --git a/crates/mega-evm/tests/satin/pool_validation.rs b/crates/mega-evm/tests/satin/pool_validation.rs new file mode 100644 index 000000000..9158a408e --- /dev/null +++ b/crates/mega-evm/tests/satin/pool_validation.rs @@ -0,0 +1,634 @@ +//! What a transaction pool decides without state agrees with what the EVM decides with it. +//! +//! [`validate_transaction_stateless`] runs the handler's own validation phases on an EVM over an +//! empty database. Every row below is run through it and through a Satin EVM over a database that +//! holds the accounts the transaction touches, at the gas limit the helper names as the least one +//! and one gas below it: the helper admits exactly what the EVM admits, refuses with the error the +//! EVM refuses with, and the intrinsic gas it reports is what the EVM charged — the floor on the +//! result, and the body's history on the common execution layer. + +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + history_gas, + revm::primitives::eip2780::TX_BASE_COST, + satin_gas_params, + system::{live_system_address, ORACLE_CONTRACT_ADDRESS, SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE}, + test_utils::{op_transaction, MemoryDatabase}, + transaction_body_bytes, validate_transaction_stateless, IntrinsicGas, MegaEvm, MegaSpecId, + MegaTransaction, ProtocolLimits, AUTHORIZATION_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, + TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use op_revm::{OpHaltReason, OpTransactionError}; +use revm::{ + context::{ + result::{EVMError, ExecutionResult, HaltReason, InvalidTransaction}, + transaction::{AccessList, AccessListItem, TransactionType}, + CfgEnv, TxEnv, + }, + ExecuteEvm, +}; + +use crate::common::{ + account_state_gas, authorizing_call, block, context, history_is_free, history_rounds, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000c00000"); +const EXISTING: Address = address!("0000000000000000000000000000000000c00001"); +const NEW: Address = address!("0000000000000000000000000000000000c00002"); +const DELEGATE: Address = address!("0000000000000000000000000000000000c00003"); +const AUTHORITY: Address = address!("0000000000000000000000000000000000c00004"); +const SYSTEM: Address = address!("0000000000000000000000000000000000c0ffee"); + +/// A gas limit every row's intrinsic gas fits in, below the execution cap. +const ROOMY: u64 = 10_000_000; + +/// A transaction the rows build, on the gas limit they are given. +type Build = fn(u64) -> MegaTransaction; + +/// A transaction from `caller` of type `tx_type`, on `gas_limit`. +fn tx(tx_type: TransactionType, caller: Address, kind: TxKind, gas_limit: u64) -> TxEnv { + TxEnv { tx_type: tx_type as u8, caller, kind, gas_limit, ..Default::default() } +} + +fn wrap(tx: TxEnv) -> MegaTransaction { + alloy_op_evm::OpTx(op_transaction(tx)) +} + +fn call(gas_limit: u64) -> MegaTransaction { + wrap(tx(TransactionType::Legacy, CALLER, TxKind::Call(EXISTING), gas_limit)) +} + +fn call_with_calldata(gas_limit: u64) -> MegaTransaction { + let mut call = tx(TransactionType::Legacy, CALLER, TxKind::Call(EXISTING), gas_limit); + call.data = Bytes::from(vec![0x5a; 100]); + wrap(call) +} + +fn value_to_existing(gas_limit: u64) -> MegaTransaction { + let mut call = tx(TransactionType::Legacy, CALLER, TxKind::Call(EXISTING), gas_limit); + call.value = U256::from(1); + wrap(call) +} + +fn value_to_new(gas_limit: u64) -> MegaTransaction { + let mut call = tx(TransactionType::Legacy, CALLER, TxKind::Call(NEW), gas_limit); + call.value = U256::from(1); + wrap(call) +} + +fn value_to_self(gas_limit: u64) -> MegaTransaction { + let mut call = tx(TransactionType::Legacy, CALLER, TxKind::Call(CALLER), gas_limit); + call.value = U256::from(1); + wrap(call) +} + +fn create(gas_limit: u64) -> MegaTransaction { + let mut create = tx(TransactionType::Legacy, CALLER, TxKind::Create, gas_limit); + // PUSH1 0 PUSH1 0 RETURN, padded to 64 bytes: two init-code words. + let mut init_code = vec![0x60, 0x00, 0x60, 0x00, 0xf3]; + init_code.resize(64, 0); + create.data = Bytes::from(init_code); + wrap(create) +} + +fn authorizations(gas_limit: u64) -> MegaTransaction { + authorizing_call(CALLER, EXISTING, U256::ZERO, gas_limit, DELEGATE, &[(AUTHORITY, 0), (NEW, 0)]) +} + +fn access_list(gas_limit: u64) -> MegaTransaction { + let mut call = tx(TransactionType::Eip2930, CALLER, TxKind::Call(EXISTING), gas_limit); + call.access_list = AccessList(vec![AccessListItem { + address: EXISTING, + storage_keys: (0..3).map(B256::with_last_byte).collect(), + }]); + wrap(call) +} + +/// A deposit carrying a kilobyte of calldata: it pays no history gas, so the floor, which prices +/// every byte at 64 gas where the intrinsic charge prices it at 16, is what the gas limit must +/// cover. +fn deposit_with_calldata(gas_limit: u64) -> MegaTransaction { + let mut deposit = call(gas_limit); + deposit.0.base.data = Bytes::from(vec![0x5a; 1_024]); + deposit.0.deposit.source_hash = B256::repeat_byte(0x11); + deposit +} + +/// A call to the Oracle from `caller`, of type `tx_type`: of the system shape when it is legacy. +fn to_the_oracle(caller: Address, tx_type: TransactionType, gas_limit: u64) -> MegaTransaction { + let mut call = tx(tx_type, caller, TxKind::Call(ORACLE_CONTRACT_ADDRESS), gas_limit); + call.data = Bytes::from(vec![0x5a; 36]); + if tx_type != TransactionType::Legacy { + call.gas_priority_fee = Some(0); + } + wrap(call) +} + +fn system_transaction(gas_limit: u64) -> MegaTransaction { + to_the_oracle(SYSTEM, TransactionType::Legacy, gas_limit) +} + +fn system_shape_from_a_user(gas_limit: u64) -> MegaTransaction { + to_the_oracle(CALLER, TransactionType::Legacy, gas_limit) +} + +fn another_shape_from_the_system_address(gas_limit: u64) -> MegaTransaction { + to_the_oracle(SYSTEM, TransactionType::Eip1559, gas_limit) +} + +fn off_the_whitelist_from_the_system_address(gas_limit: u64) -> MegaTransaction { + wrap(tx(TransactionType::Legacy, SYSTEM, TxKind::Call(EXISTING), gas_limit)) +} + +fn creation_from_the_system_address(gas_limit: u64) -> MegaTransaction { + let mut creation = create(gas_limit); + creation.0.base.caller = SYSTEM; + creation +} + +fn deposit_from_the_system_address(gas_limit: u64) -> MegaTransaction { + let mut deposit = deposit_with_calldata(gas_limit); + deposit.0.base.caller = SYSTEM; + deposit +} + +/// A database holding what the transactions touch: a funded caller, an existing recipient, the +/// system address's account, and, when `system_address` names one, a `SequencerRegistry` naming +/// it. +/// +/// The system address exists so that its transaction runs on what the helper names: a deposit-like +/// transaction whose caller does not exist is charged for creating it when it runs, which only the +/// state can tell. +fn db(system_address: Option
) -> MemoryDatabase { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(EXISTING, U256::from(1)) + .account_balance(SYSTEM, U256::from(1)); + match system_address { + Some(address) => db.sequencer_registry(address), + None => db, + } +} + +/// The error an EVM reported, whatever its database: the transaction's or the header's. +fn describe(err: EVMError) -> String { + match err { + EVMError::Transaction(invalid) => format!("{invalid:?}"), + EVMError::Header(invalid) => format!("{invalid:?}"), + other => panic!("not a validation error: {other:?}"), + } +} + +/// What the helper decides for `tx`, given the live system address a pool reads off the state +/// [`db`] holds for `system_address`. +fn helper(tx: MegaTransaction, system_address: Option
) -> Result { + let live = live_system_address(db(system_address)).expect("the read succeeds"); + assert_eq!(live, system_address, "the state names the system address the row gives"); + validate_transaction_stateless(CfgEnv::new_with_spec(MegaSpecId::SATIN), block(), tx, live) + .map_err(describe) +} + +/// What a Satin EVM decided for a transaction. +#[derive(Debug, PartialEq, Eq)] +enum Verdict { + /// Admitted, and charged this floor and this history for the body: the floor on the result, + /// the body's history on the common execution layer. + Admitted { floor: u64, history: u64 }, + /// Included as a failed deposit: op-revm does not refuse a deposit that fails validation, it + /// bumps the sender's nonce and reports the whole gas limit used. + FailedDeposit, + /// Refused with this error. + Refused(String), +} + +/// What a Satin EVM over [`db`] decides for `tx`. +fn evm(tx: MegaTransaction, system_address: Option
) -> Verdict { + let mut evm = MegaEvm::new(context(db(system_address))); + match ExecuteEvm::transact(&mut evm, tx) { + Err(err) => Verdict::Refused(describe(err)), + Ok(outcome) => match outcome.result { + ExecutionResult::Halt { reason: OpHaltReason::FailedDeposit, .. } => { + Verdict::FailedDeposit + } + result => Verdict::Admitted { + floor: result.gas().floor_gas(), + history: evm.ctx().additional_limit().intrinsic_history_gas(), + }, + }, + } +} + +/// The error a gas limit below `gas` is refused with. +fn below(gas: IntrinsicGas, gas_limit: u64) -> String { + let invalid = if gas.total() >= gas.floor { + InvalidTransaction::CallGasCostMoreThanGasLimit { initial_gas: gas.total(), gas_limit } + } else { + InvalidTransaction::GasFloorMoreThanGasLimit { gas_floor: gas.floor, gas_limit } + }; + format!("{:?}", OpTransactionError::Base(invalid)) +} + +/// One row: a transaction, the live system address the helper is given and the database's +/// registry names, and whether the transaction is executed as a deposit. +struct Row { + name: &'static str, + build: Build, + system_address: Option
, + deposit_like: bool, +} + +impl Row { + const fn new(name: &'static str, build: Build, system_address: Option
) -> Self { + Self { name, build, system_address, deposit_like: false } + } + + const fn deposit_like(mut self) -> Self { + self.deposit_like = true; + self + } + + /// The helper's intrinsic gas, then the least gas limit and the one below it through both. + /// Below the least one the helper reports the error; the EVM refuses with it, or, for a + /// transaction executed as a deposit, includes it as a failed deposit. + fn agree(&self) -> IntrinsicGas { + let Self { name, build, system_address, deposit_like } = *self; + let gas = + helper(build(ROOMY), system_address).unwrap_or_else(|err| panic!("{name}: {err}")); + let least = gas.min_gas_limit(); + assert_eq!( + helper(build(least), system_address), + Ok(gas), + "{name}: the gas limit moves nothing" + ); + assert_eq!( + evm(build(least), system_address), + Verdict::Admitted { floor: gas.floor, history: gas.history }, + "{name}: the EVM admits the least gas limit and charges what the helper reports", + ); + let error = below(gas, least - 1); + assert_eq!( + helper(build(least - 1), system_address), + Err(error.clone()), + "{name}: the helper" + ); + let expected = if deposit_like { Verdict::FailedDeposit } else { Verdict::Refused(error) }; + assert_eq!(evm(build(least - 1), system_address), expected, "{name}: the EVM"); + gas + } +} + +/// Every row the helper admits, against the EVM. +#[test] +fn test_the_helper_and_the_evm_agree_on_what_they_admit() { + let rows = [ + Row::new("a call", call, None), + Row::new("a call with calldata", call_with_calldata, None), + Row::new("value to an existing account", value_to_existing, None), + Row::new("value to a new account", value_to_new, None), + Row::new("value to the sender itself", value_to_self, None), + Row::new("a creation", create, None), + Row::new("EIP-7702 authorizations", authorizations, None), + Row::new("an access list", access_list, None), + Row::new("a deposit whose floor binds", deposit_with_calldata, None).deposit_like(), + Row::new("a system-address transaction", system_transaction, Some(SYSTEM)).deposit_like(), + Row::new("the system shape from a user", system_shape_from_a_user, Some(SYSTEM)), + Row::new("the system shape with no registry", system_transaction, None), + Row::new( + "another shape from an address no registry names", + another_shape_from_the_system_address, + None, + ), + ]; + for row in rows { + let gas = row.agree(); + let name = row.name; + assert_eq!( + gas.state, 0, + "{name}: EIP-2780 charges the state a transaction adds when it runs" + ); + // The transactions executed as deposits are the ones exempt from history gas. + let body = if row.deposit_like { + 0 + } else { + history_gas(transaction_body_bytes(&(row.build)(ROOMY))).unwrap() + }; + assert_eq!( + gas.history, body, + "{name}: the body's history, or none for an exempt transaction" + ); + } +} + +/// What a pool reads off the helper's numbers. +#[test] +fn test_what_the_intrinsic_gas_is_made_of() { + let helper = |build: Build, system_address| helper(build(ROOMY), system_address).unwrap(); + + // Whether a recipient is new is the state's to say: the intrinsic gas of a value transfer is + // the same either way, and the new account is charged when the transaction runs. + assert_eq!(helper(value_to_new, None), helper(value_to_existing, None)); + // A self-transfer pays EIP-2780's base alone; a transfer to another account pays for reaching + // it and for the value on top. + assert!(helper(value_to_self, None).regular < helper(call, None).regular); + assert!(helper(call, None).regular < helper(value_to_existing, None).regular); + + // A deposit and a system-address transaction pay no history; the same transaction from + // anyone else, or with no registry naming its sender, does. + assert_eq!(helper(deposit_with_calldata, None).history, 0); + assert_eq!(helper(system_transaction, Some(SYSTEM)).history, 0); + // A body priced at a fraction of a gas may round to nothing. + if !history_is_free() && !history_rounds() { + assert!(helper(system_shape_from_a_user, Some(SYSTEM)).history > 0); + assert!(helper(system_transaction, None).history > 0); + } + + // The floor binds a transaction that pays no history, and it is what its gas limit must + // cover. + let deposit = helper(deposit_with_calldata, None); + assert!(deposit.floor > deposit.total()); + assert_eq!(deposit.min_gas_limit(), deposit.floor); +} + +fn on_another_chain() -> MegaTransaction { + let mut tx = call(ROOMY); + tx.0.base.chain_id = Some(4326); + tx +} + +fn without_authorizations() -> MegaTransaction { + authorizing_call(CALLER, EXISTING, U256::ZERO, ROOMY, DELEGATE, &[]) +} + +fn above_the_block_gas_limit() -> MegaTransaction { + call(block().gas_limit + 1) +} + +fn init_code_over_the_limit() -> MegaTransaction { + let mut tx = create(ROOMY); + tx.0.base.data = Bytes::from(vec![0; mega_evm::constants::MAX_INITCODE_SIZE + 1]); + tx +} + +fn nonce_at_the_maximum() -> MegaTransaction { + let mut tx = call(ROOMY); + tx.0.base.nonce = u64::MAX; + tx +} + +fn priority_fee_above_the_fee_cap() -> MegaTransaction { + let mut tx = call(ROOMY); + tx.0.base.tx_type = TransactionType::Eip1559 as u8; + tx.0.base.gas_price = 1; + tx.0.base.gas_priority_fee = Some(2); + tx +} + +/// A transaction the EVM refuses without reading state, and the error it refuses it with. +type Refusal = (fn() -> MegaTransaction, InvalidTransaction); + +/// Every row the EVM refuses without reading state, the helper refuses alike. +#[test] +fn test_the_helper_and_the_evm_agree_on_what_they_refuse() { + let refusals: [Refusal; 6] = [ + (on_another_chain, InvalidTransaction::InvalidChainId), + (without_authorizations, InvalidTransaction::EmptyAuthorizationList), + (above_the_block_gas_limit, InvalidTransaction::CallerGasLimitMoreThanBlock), + (init_code_over_the_limit, InvalidTransaction::CreateInitCodeSizeLimit), + (nonce_at_the_maximum, InvalidTransaction::NonceOverflowInTransaction), + (priority_fee_above_the_fee_cap, InvalidTransaction::PriorityFeeGreaterThanMaxFee), + ]; + for (build, invalid) in refusals { + let error = format!("{:?}", OpTransactionError::Base(invalid)); + assert_eq!(helper(build(), None), Err(error.clone()), "the helper"); + assert_eq!(evm(build(), None), Verdict::Refused(error), "the EVM"); + } +} + +/// A transaction from the live system address without the system shape is refused by the helper +/// and the EVM alike, with the same error; a deposit from it is one the helper says would fail and +/// the EVM includes as a failed deposit. The same transactions from an address no registry names +/// are ordinary ones, which the helper admits. +#[test] +fn test_the_helper_and_the_evm_refuse_another_shape_from_the_system_address() { + let error = format!( + "{:?}", + OpTransactionError::Base(InvalidTransaction::Str( + SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE.into() + )) + ); + let rows: [(&str, Build); 3] = [ + ("an EIP-1559 call to the Oracle", another_shape_from_the_system_address), + ("a legacy call off the whitelist", off_the_whitelist_from_the_system_address), + ("a legacy creation", creation_from_the_system_address), + ]; + for (name, build) in rows { + assert_eq!(helper(build(ROOMY), Some(SYSTEM)), Err(error.clone()), "{name}: the helper"); + assert_eq!(evm(build(ROOMY), Some(SYSTEM)), Verdict::Refused(error.clone()), "{name}"); + assert!(helper(build(ROOMY), None).is_ok(), "{name}: from an address no registry names"); + } + let deposit = deposit_from_the_system_address; + assert_eq!(helper(deposit(ROOMY), Some(SYSTEM)), Err(error), "a deposit: the helper"); + assert_eq!(evm(deposit(ROOMY), Some(SYSTEM)), Verdict::FailedDeposit, "a deposit: the EVM"); + assert!(helper(deposit(ROOMY), None).is_ok(), "a deposit from an address no registry names"); +} + +/// The chain id is checked whatever the configuration a pool hands the helper says, as it is +/// whatever the configuration an EVM is built with says: the spec fixes the check on, and both +/// refuse a transaction of another chain alike. +#[test] +fn test_the_chain_id_is_checked_whatever_the_configuration_says() { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.tx_chain_id_check = false; + let error = format!("{:?}", OpTransactionError::Base(InvalidTransaction::InvalidChainId)); + let helper = validate_transaction_stateless(cfg.clone(), block(), on_another_chain(), None) + .map_err(describe); + assert_eq!(helper, Err(error.clone()), "the helper"); + let mut evm = MegaEvm::new(context(db(None)).with_cfg(cfg)); + let refused = ExecuteEvm::transact(&mut evm, on_another_chain()).map_err(describe); + assert_eq!(refused.map(|_| ()), Err(error), "the EVM"); +} + +/// The error a transaction whose body and authorization records exceed the data-size limit is +/// refused with. +fn over_the_data_size_limit() -> String { + format!( + "{:?}", + OpTransactionError::Base(InvalidTransaction::Str(TX_BODY_OVER_DATA_SIZE_LIMIT.into())) + ) +} + +/// The data-size limit of the spec the helper validates under. +fn spec_data_size_limit() -> u64 { + ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits.tx_data_size_limit +} + +/// `build` carrying `len` bytes of calldata, at the block's gas limit. +fn with_calldata(build: Build, len: u64) -> MegaTransaction { + let mut tx = build(block().gas_limit); + tx.0.base.data = Bytes::from(vec![0x5a; len as usize]); + tx +} + +/// A call with one authorization. +fn one_authorization(gas_limit: u64) -> MegaTransaction { + authorizing_call(CALLER, EXISTING, U256::ZERO, gas_limit, DELEGATE, &[(AUTHORITY, 0)]) +} + +/// A transaction whose body, with a record for each entry of its authorization list, exceeds the +/// spec's data-size limit is refused by the helper and by the EVM alike, with the same error, +/// before its gas is looked at: no gas limit the execution cap admits carries that many bytes, so +/// only this check can name it. At the limit the check passes and the floor refuses the +/// transaction instead. The authorization's record counts beside its tuple: a body one record +/// short of the limit with one authorization crosses it. +#[test] +fn test_the_helper_and_the_evm_refuse_a_body_over_the_limit_alike() { + let limit = spec_data_size_limit(); + let error = over_the_data_size_limit(); + let calldata_reaching = |build: Build, total: u64| { + let fixed = transaction_body_bytes(&build(0)) + + WRITE_RECORD_SIZE * build(0).0.base.authorization_list.len() as u64; + with_calldata(build, total - fixed) + }; + for (name, build) in [("a call", call as Build), ("an authorization", one_authorization)] { + let over = calldata_reaching(build, limit + 1); + assert_eq!(helper(over.clone(), None), Err(error.clone()), "{name}: the helper"); + assert_eq!(evm(over, None), Verdict::Refused(error.clone()), "{name}: the EVM"); + + let at = calldata_reaching(build, limit); + let refused = helper(at.clone(), None).expect_err("the floor is past the cap"); + assert!(refused.starts_with("Base(GasFloorMoreThanGasLimit"), "{name}: {refused}"); + assert_eq!(evm(at, None), Verdict::Refused(refused), "{name}: the EVM"); + } +} + +/// What validation's gas checks leave a transaction's body, at the spec's numbers, against the +/// data-size limit. +/// +/// The EIP-7623 floor, as EIP-7976 and EIP-7981 amend it, charges 64 gas for every calldata byte +/// and every access-list byte on top of the transaction's EIP-2780 base, which is 12,000 at least; +/// validation refuses a floor above the execution cap. So calldata and access list together are +/// at most `(200,000,000 − 12,000) / 64 = 3,124,812` bytes, and the body counts each of those bytes +/// once. Each authorization costs 7,816 of intrinsic regular gas on the same base, which the cap +/// also holds: at most `(200,000,000 − 12,000) / 7,816 = 25,587` of them, each 101 bytes of the +/// body. The body is then at most `310 + 3,124,812 + 101 × 25,587 = 5,709,409` bytes, and with a +/// 40-byte record for each authorization at most `6,732,889`, about half the 13,107,200-byte limit. +/// Validation's own check of the body and those records against the limit therefore refuses no +/// transaction the gas checks admit; it binds only a limit set below that bound. +/// +/// The bound is computed from the schedule and the byte table, and the two edges of each gas +/// check are run through validation: the largest calldata and authorization list it admits, and +/// one byte or one authorization more. +#[test] +fn test_validation_bounds_the_body_below_the_data_size_limit() { + let params = satin_gas_params(); + let room = TX_GAS_LIMIT_CAP - TX_BASE_COST; + let floor_per_byte = + params.tx_floor_cost_per_token() * params.tx_token_non_zero_byte_multiplier(); + assert_eq!( + floor_per_byte, + params.tx_floor_cost_per_token() * params.tx_floor_token_zero_byte_multiplier() + ); + assert_eq!( + floor_per_byte, + params.tx_floor_cost_per_token() * params.tx_access_list_floor_byte_multiplier() + ); + let per_authorization = params.tx_eip7702_per_empty_account_cost(); + let bytes = room / floor_per_byte; + let authorizations = room / per_authorization; + let body = TX_BODY_SIZE + bytes + AUTHORIZATION_SIZE * authorizations; + let with_records = body + WRITE_RECORD_SIZE * authorizations; + assert_eq!((TX_BASE_COST, floor_per_byte, per_authorization), (12_000, 64, 7_816)); + assert_eq!((bytes, authorizations), (3_124_812, 25_587)); + assert_eq!((body, with_records), (5_709_409, 6_732_889)); + assert!(with_records < spec_data_size_limit()); + assert_eq!(spec_data_size_limit(), 13_107_200); + + // A transfer to the sender itself pays the 12,000 base alone, so it reaches each edge. + let to_itself = + |gas_limit| wrap(tx(TransactionType::Legacy, CALLER, TxKind::Call(CALLER), gas_limit)); + assert!(helper(with_calldata(to_itself, bytes), None).is_ok(), "the largest calldata"); + let refused = helper(with_calldata(to_itself, bytes + 1), None).unwrap_err(); + assert!(refused.starts_with("Base(GasFloorMoreThanGasLimit"), "{refused}"); + + let authorizing = |count: u64| { + let authorities: Vec<(Address, u64)> = + (0..count).map(|i| (Address::with_last_byte(1).create(i), 0)).collect(); + authorizing_call(CALLER, CALLER, U256::ZERO, block().gas_limit, DELEGATE, &authorities) + }; + assert!(helper(authorizing(authorizations), None).is_ok(), "the largest authorization list"); + let refused = helper(authorizing(authorizations + 1), None).unwrap_err(); + assert!(refused.starts_with("Base(GasFloorMoreThanGasLimit"), "{refused}"); +} + +/// Above the execution cap the gas limit is valid when the regular part and the floor fit under +/// the cap, the rest going to the reservoir; a floor above the cap is refused, by both. +#[test] +fn test_the_execution_cap_is_held_alike() { + let above_the_cap = |len: usize| { + let mut tx = call(block().gas_limit); + tx.0.base.data = Bytes::from(vec![0x5a; len]); + tx + }; + let admitted = helper(above_the_cap(1_024), None).expect("a floor under the cap"); + assert!(admitted.floor < TX_GAS_LIMIT_CAP); + assert!(matches!(evm(above_the_cap(1_024), None), Verdict::Admitted { .. })); + + // 64 gas a byte in the floor: enough bytes to take it past the cap. + let len = (TX_GAS_LIMIT_CAP / 64) as usize + 1; + let refused = helper(above_the_cap(len), None); + assert!( + refused.as_ref().is_err_and(|err| err.starts_with("Base(GasFloorMoreThanGasLimit")), + "{refused:?}", + ); + assert_eq!(evm(above_the_cap(len), None), Verdict::Refused(refused.unwrap_err())); +} + +/// The least gas limit is what validation requires, not what a transaction's start costs: the +/// history of the write record a value transfer makes for its recipient, and the state gas of a +/// recipient that is new, are charged once the transaction is admitted. At the least gas limit a +/// call without value and a transfer to the sender run; a value transfer runs out of gas unless +/// its record's history is on top, and one to a new account unless that account's state gas is +/// too: it is included, and halts out of gas. It holds at any byte price: a price of nothing +/// leaves nothing to pay on top. +#[test] +fn test_the_least_gas_limit_leaves_out_what_the_start_adds() { + let succeeds = |build: Build, gas_limit| { + let mut evm = MegaEvm::new(context(db(None))); + let result = ExecuteEvm::transact(&mut evm, build(gas_limit)).expect("admitted").result; + if !result.is_success() { + assert!( + matches!( + result, + ExecutionResult::Halt { + reason: OpHaltReason::Base(HaltReason::OutOfGas(_)), + .. + } + ), + "{result:?}" + ); + } + result.is_success() + }; + let least = |build: Build| helper(build(ROOMY), None).unwrap().min_gas_limit(); + let record = history_gas(WRITE_RECORD_SIZE).unwrap(); + let account = account_state_gas(); + + assert!(succeeds(call, least(call))); + assert!(succeeds(value_to_self, least(value_to_self))); + + let existing = least(value_to_existing); + assert_eq!(succeeds(value_to_existing, existing), record == 0); + assert!(succeeds(value_to_existing, existing + record)); + if record > 0 { + assert!(!succeeds(value_to_existing, existing + record - 1)); + } + + let new = least(value_to_new); + assert_eq!(new, existing, "the intrinsic gas does not say whether the recipient is new"); + assert_eq!(succeeds(value_to_new, new + record), account == 0); + assert!(succeeds(value_to_new, new + record + account)); + if record + account > 0 { + assert!(!succeeds(value_to_new, new + record + account - 1)); + } +} diff --git a/crates/mega-evm/tests/satin/precompile_gas.rs b/crates/mega-evm/tests/satin/precompile_gas.rs index 7510c138b..8dc37d807 100644 --- a/crates/mega-evm/tests/satin/precompile_gas.rs +++ b/crates/mega-evm/tests/satin/precompile_gas.rs @@ -15,11 +15,15 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{MSTORE, POP, PUSH0, RETURN, STATICCALL}, + context_interface::cfg::GasId, precompile::kzg_point_evaluation::kzg_to_versioned_hash, primitives::hex, }; -use crate::common::{call, context}; +use crate::{ + common::{call, context}, + salt::entry, +}; const CALLER: Address = address!("0000000000000000000000000000000000a00000"); const CONTRACT: Address = address!("0000000000000000000000000000000000a00001"); @@ -39,7 +43,7 @@ const PROOF: [u8; 48] = hex!( ); /// The precompile's input: `versioned_hash ++ z ++ y ++ commitment ++ proof`. -fn kzg_input() -> Vec { +pub(crate) fn kzg_input() -> Vec { let mut input = kzg_to_versioned_hash(&COMMITMENT).to_vec(); input.extend_from_slice(&Z); input.extend_from_slice(&Y); @@ -193,7 +197,7 @@ fn test_the_precompile_addresses_are_warm() { // The cold surcharge the plain address pays and the precompile does not, less the 15 gas the // identity precompile charges for an empty input. - assert_eq!(gas_of(PLAIN) - gas_of(IDENTITY), 2_500 - 15); + assert_eq!(gas_of(PLAIN) - gas_of(IDENTITY), entry(GasId::cold_account_additional_cost()) - 15); } /// A caller that forwards less than the price is out of gas before verification runs, so the diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index ff4f1592b..a73acf4fa 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -4,7 +4,7 @@ Generated by `cargo test -p mega-evm --test satin`; the test compares this file ## Schedule entries -Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8038 repricing pressed back to Osaka and the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those two applies. +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those two applies. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -18,34 +18,34 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | memory_linear_cost | 3 | 3 | 3 | | memory_quadratic_reduction | 512 | 512 | 512 | | initcode_per_word | 2 | 2 | 2 | -| create | 32000 | 12000 | 32000 | +| create | 32000 | 12000 | 12000 | | call_stipend_reduction | 64 | 64 | 64 | -| transfer_value_cost | 9000 | 11300 | 9000 | -| cold_account_additional_cost | 2500 | 2900 | 2500 | -| new_account_cost | 25000 | 0 | 25000 | +| transfer_value_cost | 9000 | 11300 | 11300 | +| cold_account_additional_cost | 2500 | 2900 | 2900 | +| new_account_cost | 25000 | 0 | 0 | | warm_storage_read_cost | 100 | 100 | 100 | | sstore_static | 100 | 100 | 100 | -| sstore_set_without_load_cost | 19900 | 10000 | 19900 | -| sstore_reset_without_cold_load_cost | 2800 | 10000 | 2800 | -| sstore_clearing_slot_refund | 4800 | 11616 | 4800 | +| sstore_set_without_load_cost | 19900 | 10000 | 10000 | +| sstore_reset_without_cold_load_cost | 2800 | 10000 | 10000 | +| sstore_clearing_slot_refund | 4800 | 11616 | 11616 | | selfdestruct_refund | 0 | 0 | 0 | | call_stipend | 2300 | 2300 | 2300 | | cold_storage_additional_cost | 2000 | 2000 | 2000 | -| cold_storage_cost | 2100 | 2000 | 2100 | -| new_account_cost_for_selfdestruct | 25000 | 9000 | 25000 | +| cold_storage_cost | 2100 | 2000 | 2000 | +| new_account_cost_for_selfdestruct | 25000 | 9000 | 9000 | | code_deposit_cost | 200 | 0 | 0 | | tx_eip7702_regular_gas | 25000 | 7816 | 7816 | | tx_token_non_zero_byte_multiplier | 4 | 4 | 4 | | tx_token_cost | 4 | 4 | 4 | | tx_floor_cost_per_token | 10 | 16 | 16 | | tx_floor_cost_base_gas | 21000 | 12000 | 12000 | -| tx_access_list_address_cost | 2400 | 4180 | 2400 | -| tx_access_list_storage_key_cost | 1900 | 4048 | 1900 | +| tx_access_list_address_cost | 2400 | 4180 | 4180 | +| tx_access_list_storage_key_cost | 1900 | 4048 | 4048 | | tx_base_stipend | 21000 | 21000 | 21000 | -| tx_create_cost | 32000 | 12000 | 32000 | +| tx_create_cost | 32000 | 12000 | 12000 | | tx_initcode_cost | 2 | 2 | 2 | -| sstore_set_refund | 19900 | 10000 | 19900 | -| sstore_reset_refund | 2800 | 10000 | 2800 | +| sstore_set_refund | 19900 | 10000 | 10000 | +| sstore_reset_refund | 2800 | 10000 | 10000 | | tx_eip7702_regular_refund | 12500 | 0 | 0 | | sstore_set_state_gas | 0 | 97920 | 97920 | | new_account_state_gas | 0 | 183600 | 183600 | @@ -57,7 +57,7 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | max_refund_quotient | 5 | 5 | 5 | | tx_account_write_cost | 0 | 9000 | 9000 | | tx_create_access_cost | 0 | 12000 | 12000 | -| code_deposit_history_gas | 0 | 0 | 0 | +| code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions @@ -65,28 +65,28 @@ One probe transaction each, at a 5000000 gas limit. `gas used` is the receipt's | Probe | gas used | regular | state | history | |---|---:|---:|---:|---:| -| empty call | 15000 | 15000 | 0 | 0 | -| value transfer to an existing account | 21000 | 21000 | 0 | 0 | -| self-transfer | 12000 | 12000 | 0 | 0 | -| SSTORE 0 -> 1 | 135026 | 37106 | 97920 | 0 | -| SSTORE 0 -> 1 -> 0 | 29770 | 37212 | 0 | 0 | -| value CALL to an empty account | 232921 | 49321 | 183600 | 0 | -| LOG1 with 32 data bytes | 16018 | 16018 | 0 | 0 | -| create transaction deploying 0 bytes | 207687 | 24087 | 183600 | 0 | -| create transaction deploying 32 bytes | 256668 | 24108 | 232560 | 0 | +| empty call | 42280 | 15000 | 0 | 27280 | +| value transfer to an existing account | 51800 | 21000 | 0 | 30800 | +| self-transfer | 39280 | 12000 | 0 | 27280 | +| SSTORE 0 -> 1 | 155826 | 27106 | 97920 | 30800 | +| SSTORE 0 -> 1 -> 0 | 44492 | 27212 | 0 | 27280 | +| value CALL to an empty account | 244941 | 27021 | 183600 | 34320 | +| LOG1 with 32 data bytes | 51746 | 16018 | 0 | 35728 | +| create transaction deploying 0 bytes | 239455 | 24087 | 183600 | 31768 | +| create transaction deploying 32 bytes | 291252 | 24108 | 232560 | 34584 | ## SALT scaling -The same probes again, with the SALT bucket the state charge lands in at `m` times the minimum capacity. `m` multiplies the state ledger and nothing else: the regular column is the same on all three rows of a probe, and `gas used` grows by exactly the state column's growth, because these probes run below the execution cap and every state charge spills onto the regular budget. +The same probes again, with the SALT bucket the state charge lands in at `m` times the minimum capacity. `m` multiplies the state ledger and nothing else: the regular and the history columns are the same on all three rows of a probe, and `gas used` grows by exactly the state column's growth, because these probes run below the execution cap and every state charge spills onto the regular budget. | Probe | m | gas used | regular | state | history | |---|---:|---:|---:|---:|---:| -| SSTORE 0 -> 1 | 1 | 135026 | 37106 | 97920 | 0 | -| SSTORE 0 -> 1 | 2 | 232946 | 37106 | 195840 | 0 | -| SSTORE 0 -> 1 | 8 | 820466 | 37106 | 783360 | 0 | -| value CALL to an empty account | 1 | 232921 | 49321 | 183600 | 0 | -| value CALL to an empty account | 2 | 416521 | 49321 | 367200 | 0 | -| value CALL to an empty account | 8 | 1518121 | 49321 | 1468800 | 0 | +| SSTORE 0 -> 1 | 1 | 155826 | 27106 | 97920 | 30800 | +| SSTORE 0 -> 1 | 2 | 253746 | 27106 | 195840 | 30800 | +| SSTORE 0 -> 1 | 8 | 841266 | 27106 | 783360 | 30800 | +| value CALL to an empty account | 1 | 244941 | 27021 | 183600 | 34320 | +| value CALL to an empty account | 2 | 428541 | 27021 | 367200 | 34320 | +| value CALL to an empty account | 8 | 1530141 | 27021 | 1468800 | 34320 | ## The execution cap diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 9389ff4ba..83a524df5 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -140,10 +140,10 @@ fn render() -> String { out.push_str("## Schedule entries\n\n"); out.push_str( "Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam \ - devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8038 repricing \ - pressed back to Osaka and the EIP-8037 state entries rebuilt at `MegaETH`'s cost per \ - state byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one \ - of those two applies.\n\n", + devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state \ + entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at \ + `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in \ + exactly the entries where one of those two applies.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -179,10 +179,10 @@ fn render() -> String { out.push_str("\n## SALT scaling\n\n"); out.push_str( "The same probes again, with the SALT bucket the state charge lands in at `m` times the \ - minimum capacity. `m` multiplies the state ledger and nothing else: the regular column \ - is the same on all three rows of a probe, and `gas used` grows by exactly the state \ - column's growth, because these probes run below the execution cap and every state \ - charge spills onto the regular budget.\n\n", + minimum capacity. `m` multiplies the state ledger and nothing else: the regular and the \ + history columns are the same on all three rows of a probe, and `gas used` grows by \ + exactly the state column's growth, because these probes run below the execution cap \ + and every state charge spills onto the regular budget.\n\n", ); out.push_str( "| Probe | m | gas used | regular | state | history |\n|---|---:|---:|---:|---:|---:|\n", @@ -305,36 +305,22 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { }) .collect(); - // The pressed-back entries whose Osaka and Amsterdam prices are not the same number. The - // other three of the seventeen — `warm_storage_read_cost`, `sstore_static` and - // `cold_storage_additional_cost` — EIP-8038 left where they were, so pressing them back - // moves nothing. The state entries are rebuilt rather than copied, and land on Amsterdam's - // numbers because the provisional cost per state byte is the one Glamsterdam uses. + // Every regular entry is Amsterdam's. The state entries are rebuilt rather than copied, and + // land on Amsterdam's numbers because the provisional cost per state byte is the one + // Glamsterdam uses. The history entry is the one Satin adds: upstream prices no history byte + // at all. assert_eq!( differing, - [ - "create", - "transfer_value_cost", - "cold_account_additional_cost", - "new_account_cost", - "sstore_set_without_load_cost", - "sstore_reset_without_cold_load_cost", - "sstore_clearing_slot_refund", - "cold_storage_cost", - "new_account_cost_for_selfdestruct", - "tx_access_list_address_cost", - "tx_access_list_storage_key_cost", - "tx_create_cost", - "sstore_set_refund", - "sstore_reset_refund", - ], + ["code_deposit_history_gas"], "the entries Satin prices differently from Amsterdam" ); } -/// The SALT scaling section says what it claims: on each probe the regular ledger is the same at -/// every multiplier and the state ledger is the minimum bucket's times the multiplier. Read off -/// the rendered table rather than the engine, so the table cannot drift from the claim above it. +/// The SALT scaling section says what it claims: on each probe the regular ledger and the +/// history ledger are the same at every multiplier [S6.5] — history gas is not scaled by SALT +/// [S7.2] — and the state ledger is the minimum bucket's times the multiplier. Read off the +/// rendered table rather than the engine, so the table cannot drift from the claim above it +/// (`constants`: the relation across `m` is the spec's; the `m` = 1 row is the table's own). #[test] fn test_the_table_shows_the_multiplier_on_the_state_ledger_alone() { if runs_at_measurement_prices() { @@ -344,7 +330,7 @@ fn test_the_table_shows_the_multiplier_on_the_state_ledger_alone() { let section = rendered.split("## SALT scaling").nth(1).expect("the scaling section"); let section = section.split("\n## ").next().expect("the section ends at the next heading"); - let mut baselines: Vec<(String, u64, u64)> = Vec::new(); + let mut baselines: Vec<(String, u64, u64, u64)> = Vec::new(); for line in section.lines().filter(|l| l.starts_with("| ") && l.matches('|').count() == 7) { let mut cells = line.split('|').map(str::trim).skip(1); let probe = cells.next().expect("probe").to_string(); @@ -356,18 +342,24 @@ fn test_the_table_shows_the_multiplier_on_the_state_ledger_alone() { let _gas_used = cells.next(); let regular: u64 = cells.next().expect("regular").parse().expect("a number"); let state: u64 = cells.next().expect("state").parse().expect("a number"); + let history: u64 = cells.next().expect("history").parse().expect("a number"); match baselines.iter().find(|(name, ..)| *name == probe) { None => { assert_eq!(m, 1, "{probe}: the first row of a probe is the minimum bucket"); - baselines.push((probe, regular, state)); + baselines.push((probe, regular, state, history)); } - Some((_, base_regular, base_state)) => { + Some((_, base_regular, base_state, base_history)) => { assert_eq!(regular, *base_regular, "{probe} at m = {m}: regular gas moved"); assert_eq!(state, base_state * m, "{probe} at m = {m}: state gas"); + assert_eq!(history, *base_history, "{probe} at m = {m}: history gas moved"); } } } assert_eq!(baselines.len(), 2, "one slot-scoped probe and one account-scoped probe"); - assert!(baselines.iter().all(|(_, _, state)| *state > 0), "a probe must charge state gas"); + assert!(baselines.iter().all(|(_, _, state, _)| *state > 0), "a probe must charge state gas"); + assert!( + baselines.iter().all(|(_, _, _, history)| *history > 0), + "a probe must pay history gas, or the column would hold constant for nothing" + ); } diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index 86c64fc14..f7e3511d0 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -6,8 +6,10 @@ //! one where the bucket is at the minimum, one twice as large, one eight times as large — and //! reading the ledgers the transaction reports: //! -//! - the state ledger is the schedule's entry times `m`, and -//! - the regular ledger does not move: `m` scales the state dimension and nothing else. +//! - the state ledger is the schedule's entry times `m`, +//! - the regular ledger does not move, and +//! - the history ledger does not move either, and is the site's bytes at the cost per history byte: +//! `m` scales the state dimension and nothing else. //! //! The refund side is in `salt_refund`, the failed-lookup side in `salt_failure`. @@ -19,6 +21,7 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, satin_gas_params, system::{ IOracle, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, @@ -26,7 +29,8 @@ use mega_evm::{ }, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, BucketId, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, - MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, + MegaTransactionError, MegaTransactionOutcome, SaltEnv, TestExternalEnvs, AUTHORIZATION_SIZE, + MIN_BUCKET_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; use revm::{ @@ -35,7 +39,7 @@ use revm::{ context_interface::cfg::GasId, }; -use crate::common::{block, runs_at_measurement_prices}; +use crate::common::{block, history, state_is_free}; /// The sender of every probe. pub(crate) const CALLER: Address = address!("0000000000000000000000000000000000c00000"); @@ -235,47 +239,63 @@ pub(crate) fn entry(id: GasId) -> u64 { satin_gas_params().get(id) } -/// What a probe spent on state gas at each of the three multipliers, with the regular ledger -/// checked to be the same at all three: `m` scales the state dimension and nothing else. +/// What a probe spent on each ledger — `(state, regular, history)` — with the bucket the probe +/// charges in at multiplier `m`. /// /// `probe` builds the transaction and the database; `crowd` puts the bucket the probe charges in /// at multiplier `m`. -pub(crate) fn state_gas_at( +pub(crate) fn ledgers_at( m: u64, crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs, probe: impl Fn() -> (MemoryDatabase, MegaTransaction), -) -> (u64, u64) { +) -> (u64, u64, u64) { let (db, tx) = probe(); let outcome = run(db, crowd(minimal_envs(), m), tx); - (outcome.gas.state, outcome.gas.regular) + (outcome.gas.state, outcome.gas.regular, outcome.gas.history) } -/// Pins one charge site: the state ledger is `unit_price x units x m` at every multiplier, and -/// the regular ledger does not move. +/// Pins one charge site at the minimum bucket and at `m` = 2 and 8 [S6.4]: the state ledger is +/// `unscaled × m` at every multiplier, and neither the regular ledger nor the history ledger +/// moves [S6.5] — history gas is not scaled by SALT [S7.2]. +/// +/// The history ledger is anchored at `m` = 1 to `history_bytes`, the site's bytes from the byte +/// table by hand, at the cost per history byte in effect (`constants`); at `m` = 2 and 8 it is +/// the `m` = 1 figure again. pub(crate) fn assert_scales( site: &str, unscaled: u64, + history_bytes: u64, crowd: impl Fn(SaltEnvs, u64) -> SaltEnvs + Copy, probe: impl Fn() -> (MemoryDatabase, MegaTransaction) + Copy, ) { - let (state_at_one, regular_at_one) = state_gas_at(1, crowd, probe); + let (state_at_one, regular_at_one, history_at_one) = ledgers_at(1, crowd, probe); assert_eq!(state_at_one, unscaled, "{site}: the minimum bucket pays the schedule's entry"); + assert_eq!( + history_at_one, + history(history_bytes), + "{site}: the history ledger is the site's bytes at the cost per history byte", + ); for m in [2, 8] { - let (state, regular) = state_gas_at(m, crowd, probe); + let (state, regular, history) = ledgers_at(m, crowd, probe); assert_eq!(state, unscaled * m, "{site}: state gas at m = {m}"); assert_eq!(regular, regular_at_one, "{site}: regular gas must not scale with m"); + assert_eq!(history, history_at_one, "{site}: history gas must not scale with m"); } } /* The seven sites a state gas charge is made at. */ -/// `SSTORE` onto a slot that was zero: the slot's own bucket prices it. +/// `SSTORE` onto a slot that was zero: the slot's own bucket prices it. The history is the body +/// and the slot's record. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_sstore_set_charge_scales_with_the_slot_s_bucket() { const SLOT: u64 = 7; assert_scales( "SSTORE set", entry(GasId::sstore_set_state_gas()), + TX_BODY_SIZE + WRITE_RECORD_SIZE, |envs, m| crowded_slot(envs, CONTRACT, U256::from(SLOT), m), || { let code = @@ -285,12 +305,16 @@ fn test_the_sstore_set_charge_scales_with_the_slot_s_bucket() { ); } -/// A `CALL` carrying value to an account that does not exist: the account's bucket prices it. +/// A `CALL` carrying value to an account that does not exist: the account's bucket prices it. The +/// history is the body and the transfer's two records, the sender's and the recipient's. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { assert_scales( "CALL to a new account", entry(GasId::new_account_state_gas()), + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, EMPTY, m), || (db(value_call(EMPTY).stop().build()), call_contract()), ); @@ -298,102 +322,110 @@ fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { /// A `SELFDESTRUCT` moving a balance to an account that does not exist adds that account's leaf, /// and the beneficiary's own bucket prices it — the same entry and the same site a value `CALL` -/// pays, reached from the opcode that empties an account rather than the one that funds it. +/// pays, reached from the opcode that empties an account rather than the one that funds it. The +/// history is the body and the beneficiary's record. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket() { assert_scales( "SELFDESTRUCT to a new account", entry(GasId::new_account_state_gas()), + TX_BODY_SIZE + WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, EMPTY, m), || (db(selfdestruct_to(EMPTY).build()), call_contract()), ); } -/// `CREATE`: the bucket of the address it deploys to prices the account it adds. +/// `CREATE`: the bucket of the address it deploys to prices the account it adds. The history is +/// the body and the creation's two records, the creator's nonce and the created account; the +/// deployed code is empty. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create_charge_scales_with_the_created_address_s_bucket() { let created = CONTRACT.create(0); assert_scales( "CREATE", entry(GasId::create_state_gas()), + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, move |envs, m| crowded_account(envs, created, m), || (db(create_empty_contract().stop().build()), call_contract()), ); } /// The EIP-2780 runtime phase charges the transaction's own recipient before the first frame, -/// and reads the recipient's bucket to price it. +/// and reads the recipient's bucket to price it. The history is the body and the recipient's +/// record; the sender is in the body. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_top_level_recipient_charge_scales_with_the_recipient_s_bucket() { assert_scales( "the transaction's recipient", entry(GasId::new_account_state_gas()), + TX_BODY_SIZE + WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, EMPTY, m), || (db(Bytes::new()), tx(TxKind::Call(EMPTY), Bytes::new(), U256::from(1))), ); } -/// The same phase charges a creation transaction's target, in the target's own bucket. +/// The same phase charges a creation transaction's target, in the target's own bucket. The +/// history is the body, the three bytes of init code it carries as calldata, and the created +/// account's record. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create_transaction_target_charge_scales_with_its_bucket() { + const INIT: [u8; 3] = [PUSH0, PUSH0, RETURN]; let created = CALLER.create(0); assert_scales( "a creation transaction's target", entry(GasId::create_state_gas()), + TX_BODY_SIZE + INIT.len() as u64 + WRITE_RECORD_SIZE, move |envs, m| crowded_account(envs, created, m), - || { - let init = Bytes::from_static(&[PUSH0, PUSH0, RETURN]); - (db(Bytes::new()), tx(TxKind::Create, init, U256::ZERO)) - }, + || (db(Bytes::new()), tx(TxKind::Create, Bytes::from_static(&INIT), U256::ZERO)), ); } /// An EIP-7702 authorization on an authority that does not exist pays for the account leaf it -/// adds and for the delegation bytes it writes, both in the authority's bucket. +/// adds and for the delegation bytes it writes, both in the authority's bucket. The history is +/// the body, the authorization it carries, and the applied authority's record. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_eip7702_authority_charges_scale_with_the_authority_s_bucket() { assert_scales( "an EIP-7702 authority", entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()), + TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, AUTHORITY, m), || (db(Bytes::new()), authorization_tx(CONTRACT)), ); } /// Deployed code is charged per byte, in the bucket of the address it is deployed to — the same -/// bucket that priced the creation itself. +/// bucket that priced the creation itself. The history is the body, the init code it carries as +/// calldata, the created account's record and the deployed bytes. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_code_deposit_charge_scales_with_the_deployed_address_s_bucket() { const DEPLOYED: u64 = 32; + /// `PUSH8 32; PUSH0; RETURN`: deploys [`DEPLOYED`] zero bytes. + fn init() -> Bytes { + BytecodeBuilder::default().push_number(DEPLOYED).append_many([PUSH0, RETURN]).build() + } let created = CALLER.create(0); assert_scales( "a code deposit", entry(GasId::create_state_gas()) + entry(GasId::code_deposit_state_gas()) * DEPLOYED, + TX_BODY_SIZE + init().len() as u64 + WRITE_RECORD_SIZE + DEPLOYED, move |envs, m| crowded_account(envs, created, m), - || { - let init = BytecodeBuilder::default() - .push_number(DEPLOYED) - .append_many([PUSH0, RETURN]) - .build(); - (db(Bytes::new()), tx(TxKind::Create, init, U256::ZERO)) - }, + || (db(Bytes::new()), tx(TxKind::Create, init(), U256::ZERO)), ); } -/// The numbers the sites above pay at the minimum bucket, written out: the schedule's state -/// entries at `MegaETH`'s cost per state byte. -#[test] -fn test_the_minimum_bucket_pays_the_spec_s_own_state_gas() { - if runs_at_measurement_prices() { - return; - } - assert_eq!(entry(GasId::sstore_set_state_gas()), 97_920); - assert_eq!(entry(GasId::new_account_state_gas()), 183_600); - assert_eq!(entry(GasId::create_state_gas()), 183_600); - assert_eq!(entry(GasId::code_deposit_state_gas()), 1_530); - assert_eq!(entry(GasId::tx_eip7702_state_gas_bytecode()), 35_190); -} - /* What the multiplier does not touch. */ /// A crowded bucket somewhere else changes nothing: the charge reads the bucket of the account @@ -418,6 +450,10 @@ fn test_a_crowded_bucket_elsewhere_does_not_change_the_price() { /// asks the SALT environment for its capacity a single time. #[test] fn test_a_bucket_is_read_once_per_transaction() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } const SLOTS: u64 = 16; // Put every slot this program writes in one bucket, so one capacity query serves them all. let mut code = BytecodeBuilder::default(); @@ -429,8 +465,17 @@ fn test_a_bucket_is_read_once_per_transaction() { let buckets: Vec = (0..SLOTS).map(|slot| slot_bucket(CONTRACT, U256::from(slot))).collect(); + // Room for every slot at the crowded price on top of what the other probes have. + let gas_limit = GAS_LIMIT + entry(GasId::sstore_set_state_gas()) * 4 * SLOTS; let mut evm = MegaEvm::new(salt_context(db(code.stop().build()), envs.clone())); - let outcome = evm.execute_transaction(call_contract()).expect("the probe is valid"); + let outcome = evm + .execute_transaction(tx_with_gas( + TxKind::Call(CONTRACT), + Bytes::new(), + U256::ZERO, + gas_limit, + )) + .expect("the probe is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( @@ -452,6 +497,10 @@ fn test_a_bucket_is_read_once_per_transaction() { /// capacity makes a charge unaffordable, never free. #[test] fn test_an_absurd_capacity_saturates_rather_than_wrapping() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } const SLOT: u64 = 7; let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); let envs = @@ -469,47 +518,35 @@ fn test_an_absurd_capacity_saturates_rather_than_wrapping() { /// The pre-block system calls and every other system call price at the minimum bucket, whatever /// the bucket they write into actually holds: a state change the protocol mandates cannot be -/// priced out by the growth of a region it does not control. +/// priced out by the growth of a region it does not control. A system call is system-originated +/// whatever caller it names: it is the protocol running, not a transaction anybody sent. #[test] fn test_a_system_call_prices_at_the_minimum_bucket() { use alloy_evm::Evm; const SLOT: u64 = 7; let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); - let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); - - let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); - let result = evm - .transact_system_call(SYSTEM_ADDRESS, CONTRACT, Bytes::new()) - .expect("the system call is valid"); - assert!(result.result.is_success(), "{:?}", result.result); - - assert_eq!( - result.result.gas().state_gas_spent_final(), - entry(GasId::sstore_set_state_gas()), - "a system call pays the schedule's own entry", - ); - assert_eq!(envs.total_bucket_queries(), 0, "and never reads the SALT environment"); - assert!(evm.ctx().is_system_originated()); -} - -/// A system call is system-originated whatever caller it names: it is the protocol running, not -/// a transaction anybody sent. -#[test] -fn test_a_system_call_with_another_caller_is_still_system_originated() { - use alloy_evm::Evm; + for caller in [SYSTEM_ADDRESS, CALLER] { + let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); - const SLOT: u64 = 7; - let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); - let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); - - let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); - let result = - evm.transact_system_call(CALLER, CONTRACT, Bytes::new()).expect("the system call is valid"); - assert!(result.result.is_success(), "{:?}", result.result); + let mut evm = MegaEvm::new(salt_context(db(code.clone()), envs.clone())); + let result = evm + .transact_system_call(caller, CONTRACT, Bytes::new()) + .expect("the system call is valid"); + assert!(result.result.is_success(), "{caller}: {:?}", result.result); - assert_eq!(result.result.gas().state_gas_spent_final(), entry(GasId::sstore_set_state_gas())); - assert_eq!(envs.total_bucket_queries(), 0); + assert_eq!( + result.result.gas().state_gas_spent_final(), + entry(GasId::sstore_set_state_gas()), + "{caller}: a system call pays the schedule's own entry", + ); + assert_eq!( + envs.total_bucket_queries(), + 0, + "{caller}: and never reads the SALT environment" + ); + assert!(evm.ctx().is_system_originated(), "{caller}"); + } } /// A transaction the system address sends prices at the minimum bucket too: that address has no @@ -531,22 +568,6 @@ fn test_a_transaction_from_the_system_address_prices_at_the_minimum_bucket() { assert_eq!(envs.total_bucket_queries(), 0); } -/// The control arm of the rule: the very same write, sent by a user, pays the crowded price. -/// Without this the exemption above could be passing for the wrong reason. -#[test] -fn test_a_user_transaction_into_the_same_bucket_pays_the_crowded_price() { - const SLOT: u64 = 7; - let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); - let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); - - let mut evm = MegaEvm::new(salt_context(db(code), envs.clone())); - let outcome = evm.execute_transaction(call_contract()).expect("the probe is valid"); - - assert_eq!(outcome.gas.state, entry(GasId::sstore_set_state_gas()) * 8); - assert_eq!(envs.total_bucket_queries(), 1); - assert!(!evm.ctx().is_system_originated()); -} - /* The sequencer's own system transaction. */ /// The Oracle slot the system transactions write. `setSlot` writes the raw slot number, so the @@ -679,6 +700,10 @@ fn test_the_system_call_entry_point_prices_the_same_at_any_capacity() { /// to the block they run in. #[test] fn test_a_user_transaction_in_the_same_block_still_pays_the_crowded_price() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let set = entry(GasId::sstore_set_state_gas()); let envs = crowded_slot( crowded_oracle_slot(SYSTEM_TX_MULTIPLIER), @@ -709,6 +734,10 @@ fn test_a_user_transaction_in_the_same_block_still_pays_the_crowded_price() { /// here would be a way around the scaling. #[test] fn test_a_deposit_transaction_pays_the_crowded_price() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } const SLOT: u64 = 7; let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); @@ -730,6 +759,10 @@ fn test_a_deposit_transaction_pays_the_crowded_price() { /// being system-originated cuts both ways. #[test] fn test_an_unpriceable_deposit_transaction_fails() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } const SLOT: u64 = 7; let code = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); let envs = minimal_envs() @@ -833,13 +866,16 @@ fn test_clearing_a_slot_charges_no_state_gas() { } /// A slot is one leaf however many times the transaction writes it: the first write off zero -/// pays, the rest pay nothing. +/// pays, the rest pay nothing. It is one record too. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_a_slot_written_twice_pays_for_one_leaf() { let set = entry(GasId::sstore_set_state_gas()); assert_scales( "a slot written twice", set, + TX_BODY_SIZE + WRITE_RECORD_SIZE, |envs, m| crowded_slot(envs, CONTRACT, U256::ZERO, m), || { let code = BytecodeBuilder::default() @@ -910,7 +946,10 @@ fn test_a_selfdestruct_that_adds_no_account_charges_no_state_gas() { /* The remaining creation sites. */ /// `CREATE2` reaches its deployment address by hashing rather than by nonce, and is priced in -/// that address's bucket just as `CREATE` is. +/// that address's bucket just as `CREATE` is. Its history is `CREATE`'s: the body and the two +/// records of the creation. +/// +/// Rules: [S6.4], [S6.5], [S7.2]. #[test] fn test_the_create2_charge_scales_with_the_created_address_s_bucket() { const SALT: U256 = U256::ZERO; @@ -920,6 +959,7 @@ fn test_the_create2_charge_scales_with_the_created_address_s_bucket() { assert_scales( "CREATE2", entry(GasId::create_state_gas()), + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, move |envs, m| crowded_account(envs, created, m), move || { let code = BytecodeBuilder::default() @@ -936,27 +976,6 @@ fn test_the_create2_charge_scales_with_the_created_address_s_bucket() { ); } -/// An account leaf costs the same however it comes about: the entry a creation pays and the one -/// a value transfer pays are the same number, because they buy the same leaf. -#[test] -fn test_an_account_leaf_costs_the_same_however_it_is_added() { - assert_eq!(entry(GasId::create_state_gas()), entry(GasId::new_account_state_gas())); - - let created = CONTRACT.create(0); - let creation = run( - db(create_empty_contract().stop().build()), - crowded_account(minimal_envs(), created, 8), - call_contract(), - ); - let transfer = run( - db(value_call(EMPTY).stop().build()), - crowded_account(minimal_envs(), EMPTY, 8), - call_contract(), - ); - - assert_eq!(creation.gas.state, transfer.gas.state); -} - /// A creation that also writes a slot pays for both leaves, each in the bucket it lands in: the /// account in the created address's, the slot in its own. #[test] @@ -987,13 +1006,15 @@ fn test_a_creation_that_writes_a_slot_pays_both_in_their_own_buckets() { /// which is where a charge this size is meant to be paid from. #[test] fn test_the_multiplier_is_linear_over_a_wide_range() { - const WIDE_GAS_LIMIT: u64 = 400_000_000; let set = entry(GasId::sstore_set_state_gas()); + // Above the execution cap by the slot at the widest multiplier and 200,000,000 more, so the + // reservoir pays for the slot at every multiplier. + let wide_gas_limit = TX_GAS_LIMIT_CAP + 1_000 * set + 200_000_000; let code = || BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); for m in [1, 2, 10, 1_000] { let envs = crowded_slot(minimal_envs(), CONTRACT, U256::ZERO, m); - let probe = tx_with_gas(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO, WIDE_GAS_LIMIT); + let probe = tx_with_gas(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO, wide_gas_limit); let outcome = run(db(code()), envs, probe); assert_eq!(outcome.gas.state, set * m, "at m = {m}"); } diff --git a/crates/mega-evm/tests/satin/salt_delegation.rs b/crates/mega-evm/tests/satin/salt_delegation.rs index 7684a4b87..a1761960b 100644 --- a/crates/mega-evm/tests/satin/salt_delegation.rs +++ b/crates/mega-evm/tests/satin/salt_delegation.rs @@ -28,9 +28,12 @@ use revm::{ state::Bytecode, }; -use crate::salt::{ - account_bucket, call_contract, crowded_account, db, entry, minimal_envs, run, try_run, - SaltEnvs, EMPTY, +use crate::{ + common::state_is_free, + salt::{ + account_bucket, call_contract, crowded_account, db, entry, minimal_envs, run, try_run, + SaltEnvs, EMPTY, + }, }; /// An account whose code is a delegation designator pointing at itself. @@ -195,15 +198,6 @@ fn test_a_value_call_to_a_delegated_account_charges_no_state_gas() { } } -/// The control arm: the same call to an address that really is empty pays for the leaf it adds, -/// at the crowded price. -#[test] -fn test_a_value_call_to_a_truly_empty_address_pays_the_crowded_price() { - let envs = crowded_account(minimal_envs(), EMPTY, 8); - let outcome = run(db(crate::salt::value_call(EMPTY).stop().build()), envs, call_contract()); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas()) * 8); -} - /// A `CREATE` executed inside a delegated frame deploys from the delegating account, so the /// charge lands in the bucket of the address *that* account's nonce derives — not the delegate's. /// @@ -215,6 +209,10 @@ fn test_a_value_call_to_a_truly_empty_address_pays_the_crowded_price() { /// guards — the delegate's nonce used with the authority's address — cannot be seen. #[test] fn test_a_create_inside_a_delegated_frame_is_priced_at_the_authority_s_address() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } const AUTHORITY: Address = address!("0000000000000000000000000000000000c00013"); const CODE: Address = address!("0000000000000000000000000000000000c00014"); /// The nonce the authority carries, which derives the address the frame deploys at. @@ -285,15 +283,6 @@ fn test_a_callcode_to_a_delegated_account_charges_no_state_gas() { assert_eq!(run(db, envs, call_contract()).gas.state, 0); } -/// And the control arm again: a `CALL` to the same empty address does add a leaf, and pays for -/// it. Without this the two above could be passing because nothing was charged anywhere. -#[test] -fn test_a_call_to_the_same_empty_account_still_pays() { - let envs = crowded_account(minimal_envs(), EMPTY, 8); - let outcome = run(db(crate::salt::value_call(EMPTY).stop().build()), envs, call_contract()); - assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas()) * 8); -} - /// `CALLCODE(gas, target, 1, 0, 0, 0, 0)` followed by `STOP`. fn callcode_with_value(target: Address) -> Bytes { BytecodeBuilder::default() diff --git a/crates/mega-evm/tests/satin/salt_deposit.rs b/crates/mega-evm/tests/satin/salt_deposit.rs index c2cc87c0e..62c707b3c 100644 --- a/crates/mega-evm/tests/satin/salt_deposit.rs +++ b/crates/mega-evm/tests/satin/salt_deposit.rs @@ -28,9 +28,12 @@ use revm::{ context_interface::cfg::GasId, }; -use crate::salt::{ - account_bucket, crowded_account, db, entry, minimal_envs, run, try_run, SaltEnvs, CALLER, - GAS_LIMIT, +use crate::{ + common::state_is_free, + salt::{ + account_bucket, crowded_account, db, entry, minimal_envs, run, try_run, SaltEnvs, CALLER, + GAS_LIMIT, + }, }; /// The sender's own nonce. The contract deploys at `CALLER.create(STATE_NONCE)`. @@ -103,6 +106,10 @@ fn failing_account(envs: SaltEnvs, account: Address) -> SaltEnvs { /// envelope nonce derives is never priced, never written and never read. #[test] fn test_a_deposit_creation_is_priced_where_it_deploys() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let (deployed, envelope) = candidates(); let envs = crowded_account(minimal_envs(), deployed, M); @@ -129,6 +136,10 @@ fn test_a_deposit_creation_is_priced_where_it_deploys() { /// base price, and that bucket's capacity is never asked for. #[test] fn test_crowding_the_envelope_nonce_s_address_changes_no_price() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let (deployed, envelope) = candidates(); let envs = crowded_account(minimal_envs(), envelope, M); @@ -144,6 +155,10 @@ fn test_crowding_the_envelope_nonce_s_address_changes_no_price() { /// the SALT environment gave, like any other charge that cannot be priced. #[test] fn test_an_unpriceable_deposit_creation_fails_with_its_cause() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let (deployed, _) = candidates(); let envs = failing_account(minimal_envs(), deployed); @@ -159,6 +174,10 @@ fn test_an_unpriceable_deposit_creation_fails_with_its_cause() { /// bucket nothing is charged in is a bucket nothing asks about. #[test] fn test_a_failure_at_the_envelope_nonce_s_address_is_never_asked_for() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let (deployed, envelope) = candidates(); let envs = failing_account(minimal_envs(), envelope); @@ -175,6 +194,10 @@ fn test_a_failure_at_the_envelope_nonce_s_address_is_never_asked_for() { /// eight times the minimum, and one capacity read priced both halves. #[test] fn test_a_reverting_deposit_creation_gives_the_charge_back_where_it_was_made() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let (deployed, envelope) = candidates(); let envs = crowded_account(minimal_envs(), deployed, M); @@ -201,6 +224,10 @@ fn test_a_reverting_deposit_creation_gives_the_charge_back_where_it_was_made() { /// suite, and the site it is charged at did not move. #[test] fn test_at_equal_nonces_a_deposit_and_an_ordinary_creation_agree() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } // Both nonces are `STATE_NONCE` here, so the two candidate addresses of the tests above // are this one address, and no arrangement of buckets can tell them apart. let deployed = CALLER.create(STATE_NONCE); diff --git a/crates/mega-evm/tests/satin/salt_failure.rs b/crates/mega-evm/tests/satin/salt_failure.rs index 96d39da90..2e3d8bfa8 100644 --- a/crates/mega-evm/tests/satin/salt_failure.rs +++ b/crates/mega-evm/tests/satin/salt_failure.rs @@ -18,10 +18,13 @@ use revm::{ context_interface::cfg::GasId, }; -use crate::salt::{ - account_bucket, authorization_tx, call_contract, create_empty_contract, crowded_account, db, - entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, try_run, tx, value_call, - SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, +use crate::{ + common::state_is_free, + salt::{ + account_bucket, authorization_tx, call_contract, create_empty_contract, crowded_account, + db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, try_run, tx, + value_call, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, + }, }; /// What a broken SALT backend reports. @@ -46,6 +49,9 @@ fn assert_fails(site: &str, db: MemoryDatabase, envs: SaltEnvs, tx: MegaTransact } /// Runs the probe and requires it to fail with a cause naming `cause`. +/// +/// Where a state byte costs nothing, a charge costs nothing at any capacity and the engine asks +/// for none, so no probe can fail on a bucket and there is nothing to run. fn assert_fails_with( site: &str, cause: &str, @@ -53,6 +59,9 @@ fn assert_fails_with( envs: SaltEnvs, tx: MegaTransaction, ) { + if state_is_free() { + return; + } match try_run(db, envs, tx) { Err(EVMError::Custom(message)) => assert!( message.contains(cause), diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 98a6a8e58..0d6bad039 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -25,7 +25,7 @@ use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ settle_frame_result, synthetic_frame_result, test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaEvm, MegaTransaction, MegaTransactionOutcome, + MegaTransaction, }; use revm::{ bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, @@ -39,10 +39,13 @@ use revm::{ }, }; -use crate::salt::{ - account_bucket, authorization_tx, call_contract, capacity, create_with, crowded_account, - crowded_slot, db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, - try_run, tx, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, +use crate::{ + common::{history, state_is_free}, + salt::{ + account_bucket, authorization_tx, call_contract, create_with, crowded_account, + crowded_slot, db, entry, minimal_envs, run, salt_context, selfdestruct_to, slot_bucket, + try_run, tx, tx_with_gas, SaltEnvs, AUTHORITY, CALLER, CONTRACT, EMPTY, GAS_LIMIT, + }, }; /// The contract a probe's inner frame runs in. @@ -51,6 +54,13 @@ const SUB: Address = alloy_primitives::address!("0000000000000000000000000000000 /// The slot every probe that writes storage uses. const SLOT: u64 = 7; +/// The gas a probe's inner call forwards: 2,000,000 on top of `unit` of state gas at the largest +/// multiplier the probes crowd a bucket to, so the inner frame can pay for what it adds at every +/// multiplier and byte price. +fn inner_gas(unit: u64) -> u64 { + 2_000_000 + 8 * unit +} + /// Runs `probe` at each multiplier and returns the state gas it netted, requiring the regular /// ledger to be the same at all of them. fn net_state_at( @@ -75,6 +85,10 @@ fn net_state_at( /// is — and the bucket is read once for both. #[test] fn test_a_slot_written_and_restored_nets_nothing_at_every_multiplier() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let code = || { BytecodeBuilder::default() .sstore(U256::from(SLOT), U256::from(1)) @@ -152,6 +166,7 @@ fn test_a_failed_value_call_gives_its_new_account_charge_back() { /// frame wrote a slot in a crowded bucket and reverted. #[test] fn test_a_charge_in_a_reverting_inner_frame_comes_back_whole() { + let forwarded = inner_gas(entry(GasId::sstore_set_state_gas())); let probe = || { let sub = BytecodeBuilder::default() .sstore(U256::from(SLOT), U256::from(1)) @@ -164,7 +179,7 @@ fn test_a_charge_in_a_reverting_inner_frame_comes_back_whole() { .push_number(0u64) .push_number(0u64) .push_address(SUB) - .push_number(2_000_000u64) + .push_number(forwarded) .append(CALL) .stop() .build(); @@ -182,6 +197,7 @@ fn test_a_charge_in_a_reverting_inner_frame_comes_back_whole() { /// pays the crowded price, so the arms above are not passing because nothing was charged. #[test] fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { + let forwarded = inner_gas(entry(GasId::sstore_set_state_gas())); let probe = || { let sub = BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build(); let code = BytecodeBuilder::default() @@ -191,7 +207,7 @@ fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { .push_number(0u64) .push_number(0u64) .push_address(SUB) - .push_number(2_000_000u64) + .push_number(forwarded) .append(CALL) .stop() .build(); @@ -210,6 +226,7 @@ fn test_a_charge_an_inner_frame_keeps_scales_with_its_bucket() { /// one reverted, and the beneficiary was never created after all. #[test] fn test_a_selfdestruct_whose_caller_reverts_gives_its_charge_back() { + let forwarded = inner_gas(entry(GasId::new_account_state_gas())); let probe = |outer_reverts: bool| { move || { let sub = selfdestruct_to(EMPTY).build(); @@ -220,7 +237,7 @@ fn test_a_selfdestruct_whose_caller_reverts_gives_its_charge_back() { .push_number(0u64) .push_number(0u64) .push_address(SUB) - .push_number(2_000_000u64) + .push_number(forwarded) .append(CALL); code = if outer_reverts { code.revert_with_data([0xaa]) } else { code.stop() }; let db = db(code.build()) @@ -346,89 +363,6 @@ fn test_a_kept_charge_and_a_restored_one_settle_independently() { assert_eq!(net_state_at([1, 2, 8], crowd, probe), [set, set * 2, set * 8]); } -/// A crowded bucket cannot make a transaction owe more than it charged: the refill of a charge -/// is the charge, so a restore never leaves the state ledger negative or the reservoir richer -/// than the sender's budget. -#[test] -fn test_a_restore_never_gives_back_more_than_it_charged() { - let code = BytecodeBuilder::default() - .sstore(U256::from(SLOT), U256::from(1)) - .sstore(U256::from(SLOT), U256::ZERO) - .stop() - .build(); - let envs = crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8); - - let outcome: MegaTransactionOutcome = - MegaEvm::new(salt_context(db(code), envs)).execute_transaction(call_contract()).unwrap(); - - assert_eq!(outcome.gas.state, 0, "the state ledger nets to zero, not below it"); - assert!( - outcome.gas.reservoir_remaining <= GAS_LIMIT, - "a refill cannot put more in the reservoir than the transaction brought", - ); - assert!(outcome.gas.gas_used > 0 && outcome.gas.gas_used <= GAS_LIMIT); -} - -/// The whole matrix at one multiplier, side by side, so the three refund classes are readable in -/// one place: a rollback gives the charge back, an authorization keeps it, and a bucket is read -/// once whatever happens to the charge afterwards. -#[test] -fn test_the_refund_classes_side_by_side() { - let set = entry(GasId::sstore_set_state_gas()); - let authority_charges = - entry(GasId::new_account_state_gas()) + entry(GasId::tx_eip7702_state_gas_bytecode()); - - let kept = run( - db(BytecodeBuilder::default().sstore(U256::from(SLOT), U256::from(1)).stop().build()), - crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8), - call_contract(), - ); - assert_eq!(kept.gas.state, set * 8, "a write that stays pays the crowded price"); - - let rolled_back = try_run( - db(BytecodeBuilder::default() - .sstore(U256::from(SLOT), U256::from(1)) - .revert_with_data([0xaa]) - .build()), - crowded_slot(minimal_envs(), CONTRACT, U256::from(SLOT), 8), - call_contract(), - ) - .expect("the transaction is valid"); - assert_eq!(rolled_back.gas.state, 0, "a write that is rolled back pays nothing"); - - let authorized = try_run( - db(BytecodeBuilder::default().revert_with_data([0xaa]).build()), - crowded_account(minimal_envs(), AUTHORITY, 8), - authorization_tx(CONTRACT), - ) - .expect("the transaction is valid"); - assert_eq!( - authorized.gas.state, - authority_charges * 8, - "an applied authorization pays even though the frame reverted", - ); -} - -/// The capacity a bucket is read at is fixed for the transaction: one read serves the charge and -/// the refill, so the two cannot disagree even if the environment's answer would. -#[test] -fn test_the_capacity_behind_a_charge_and_its_refill_is_read_once() { - let bucket = slot_bucket(CONTRACT, U256::from(SLOT)); - let envs = minimal_envs().with_bucket_capacity(bucket, capacity(8)); - let code = BytecodeBuilder::default() - .sstore(U256::from(SLOT), U256::from(1)) - .sstore(U256::from(SLOT), U256::ZERO) - .sstore(U256::from(SLOT), U256::from(2)) - .sstore(U256::from(SLOT), U256::ZERO) - .stop() - .build(); - - let outcome = run(db(code), envs.clone(), call_contract()); - - assert_eq!(outcome.gas.state, 0, "every set was restored"); - assert_eq!(envs.bucket_queries(bucket), 1, "two charges and two refills, one capacity read"); -} - /* The refund route that runs without a frame. */ /// The address a synthetic frame would have added a leaf at. @@ -438,8 +372,10 @@ const SYNTHETIC_TARGET: Address = address!("0000000000000000000000000000000000c0 const FORWARDED: u64 = 9_000; /// The caller's own regular gas limit in those probes, wide enough for a crowded charge to spill -/// onto it in full. -const CALLER_LIMIT: u64 = 5_000_000; +/// onto it in full: 5,000,000 on top of a new account at the crowded price. +fn caller_limit() -> u64 { + 5_000_000 + entry(GasId::new_account_state_gas()) * SYNTHETIC_MULTIPLIER +} /// The capacity the synthetic-settlement probes crowd their site to. const SYNTHETIC_MULTIPLIER: u64 = 8; @@ -464,7 +400,7 @@ fn settle_a_synthetic_failure( let mut ctx = salt_context(db(Bytes::new()), envs.clone()); let price = ctx.state_gas_charge(charge).expect("the bucket is readable"); - let mut caller = GasTracker::new(CALLER_LIMIT, CALLER_LIMIT - FORWARDED, reservoir); + let mut caller = GasTracker::new(caller_limit(), caller_limit() - FORWARDED, reservoir); assert!(caller.record_state_cost(price), "the caller can pay the crowded charge"); let spilled = caller.state_gas_spilled(); @@ -520,7 +456,7 @@ fn charged_create_input(reservoir: u64) -> FrameInput { /// alike. fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settled: &Settled) { let caller = &settled.caller; - assert_eq!(caller.remaining(), CALLER_LIMIT, "{site}: the regular pool comes back whole"); + assert_eq!(caller.remaining(), caller_limit(), "{site}: the regular pool comes back whole"); assert_eq!(caller.reservoir(), reservoir, "{site}: and the reservoir is where it started"); assert_eq!(caller.state_gas_spent(), 0, "{site}: the state ledger nets zero"); assert_eq!(caller.state_gas_spilled(), 0, "{site}: nothing is left spilled"); @@ -535,6 +471,10 @@ fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settl /// charge, both when the reservoir paid for it and when it spilled onto regular gas. #[test] fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let crowded = entry(GasId::new_account_state_gas()) * SYNTHETIC_MULTIPLIER; let charge = StateGasCharge::one( GasId::new_account_state_gas(), @@ -543,10 +483,10 @@ fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { // The reservoir covers the whole charge. let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); - let settled = settle_a_synthetic_failure(&envs, CALLER_LIMIT, charge, charged_call_input); + let settled = settle_a_synthetic_failure(&envs, caller_limit(), charge, charged_call_input); assert_eq!(settled.price, crowded, "the charge was priced at the crowded bucket"); assert_eq!(settled.spilled, 0, "and the reservoir paid for all of it"); - assert_restores_both_pools("a call from the reservoir", &envs, CALLER_LIMIT, &settled); + assert_restores_both_pools("a call from the reservoir", &envs, caller_limit(), &settled); // The reservoir covers part of it and the rest spills onto regular gas. let reservoir = crowded / 4; @@ -561,15 +501,19 @@ fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { /// address the frame would have deployed to. #[test] fn test_a_synthetic_creation_failure_refunds_the_crowded_upfront_charge() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let crowded = entry(GasId::create_state_gas()) * SYNTHETIC_MULTIPLIER; let charge = StateGasCharge::one(GasId::create_state_gas(), StateGasSite::account(SYNTHETIC_TARGET)); let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); - let settled = settle_a_synthetic_failure(&envs, CALLER_LIMIT, charge, charged_create_input); + let settled = settle_a_synthetic_failure(&envs, caller_limit(), charge, charged_create_input); assert_eq!(settled.price, crowded, "the charge was priced at the crowded bucket"); assert_eq!(settled.spilled, 0); - assert_restores_both_pools("a creation from the reservoir", &envs, CALLER_LIMIT, &settled); + assert_restores_both_pools("a creation from the reservoir", &envs, caller_limit(), &settled); let reservoir = crowded / 4; let envs = crowded_account(minimal_envs(), SYNTHETIC_TARGET, SYNTHETIC_MULTIPLIER); @@ -582,8 +526,8 @@ fn test_a_synthetic_creation_failure_refunds_the_crowded_upfront_charge() { /* A deposit charge that is made and then rolled back. */ /// How many bytes of runtime code the creation below deploys when its deposit is meant to fail. -/// At the crowded price a byte costs `code_deposit_state_gas x 8`, so this many bytes is far -/// beyond what the transaction brought. +/// At the crowded price a byte costs `code_deposit_state_gas x 8` and its history; at the spec's +/// prices this many bytes is far beyond what [`GAS_LIMIT`] brings. const UNAFFORDABLE_CODE: u64 = 20_000; /// How many it deploys when the deposit is meant to go through. @@ -607,14 +551,34 @@ fn creation_depositing(deployed: u64) -> MemoryDatabase { /// the transaction settles and reports what it kept. #[test] fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } let created = CONTRACT.create(0); let crowd = |envs| { let envs = crowded_account(envs, created, SYNTHETIC_MULTIPLIER); crowded_slot(envs, created, U256::from(SLOT), SYNTHETIC_MULTIPLIER) }; + // What the program spends with nothing to deposit, and at least what the deposit costs: its + // state gas at the crowded price and its history. + let without_the_deposit = + run(creation_depositing(0), crowd(minimal_envs()), call_contract()).gas.gas_used; + let deposit = entry(GasId::code_deposit_state_gas()) * SYNTHETIC_MULTIPLIER * UNAFFORDABLE_CODE + + history(UNAFFORDABLE_CODE); + // A deposit that costs less than the rest of the transaction leaves no gas limit at which the + // creation runs its init code and then cannot pay for the deposit. + if deposit < without_the_deposit { + return; + } + // The deposit's price on top of the rest, below the execution cap as every probe here runs: + // forwarded 63/64 of it, the creation runs its init code and falls short of the deposit. + let gas_limit = (without_the_deposit + deposit).min(GAS_LIMIT); + let envs = crowd(minimal_envs()); - let outcome = run(creation_depositing(UNAFFORDABLE_CODE), envs.clone(), call_contract()); + let call = tx_with_gas(TxKind::Call(CONTRACT), Bytes::new(), U256::ZERO, gas_limit); + let outcome = run(creation_depositing(UNAFFORDABLE_CODE), envs.clone(), call); assert_eq!(outcome.gas.state, 0, "the failed creation kept neither charge"); assert_eq!( envs.bucket_queries(slot_bucket(created, U256::from(SLOT))), @@ -643,3 +607,48 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { "the creation, the slot its init code wrote and the bytes it deposited", ); } + +/// A `CREATE` whose init code `SELFDESTRUCT`s the account it is creating, in the same transaction. +/// +/// EIP-8037's gas refills for `SELFDESTRUCT` say that destruction leaves the account, its code +/// and its storage out of the trie, and still produces no state-gas refill and no change to the +/// state gas the transaction has spent. The created-account charge therefore stands, priced in +/// the created address's bucket, at the minimum multiplier and above it. +#[test] +fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state_gas() { + // A charge that costs nothing is the same number whether or not it is given back. + if state_is_free() { + return; + } + // `ADDRESS SELFDESTRUCT`: the init code destroys the account being created. The beneficiary + // is that account, which the creation itself just added, so no second account is charged. + let init = selfdestruct_to_self(); + let created = CONTRACT.create(0); + let account = entry(GasId::create_state_gas()); + + assert_eq!( + net_state_at( + [1, 2, 8], + move |envs, m| crowded_account(envs, created, m), + || (db(create_with(&init).stop().build()), call_contract()), + ), + [account, account * 2, account * 8], + "the created account's state gas is not refilled", + ); + + let outcome = run( + db(create_with(&init).stop().build()), + crowded_account(minimal_envs(), created, 8), + call_contract(), + ); + assert!( + outcome.state.get(&created).is_some_and(|account| account.is_selfdestructed()), + "the same-transaction destruction removes the account from the trie", + ); +} + +/// Init code that self-destructs the account being created: `ADDRESS SELFDESTRUCT`. +fn selfdestruct_to_self() -> Vec { + use revm::bytecode::opcode::{ADDRESS, SELFDESTRUCT}; + vec![ADDRESS, SELFDESTRUCT] +} diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 3a2e1c780..9f5dd5078 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -3,38 +3,70 @@ //! The intrinsic numbers, the state gas a new slot and a new account draw, and the Amsterdam //! opcodes the schedule brings with it. Each number is read off a transaction the engine ran, not //! computed from the schedule, so a change to either side shows up here. +//! +//! Every transaction also pays the history gas of its body, which is not a schedule entry and is +//! priced by the history mechanism. The numbers below are what is left once that ledger is taken +//! out ([`Spend::schedule_gas`]); what the body costs is pinned in `history_gas.rs`. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ - constants::{ACCOUNT_STATE_GAS, SLOT_STATE_GAS}, + constants::ACCOUNT_STATE_GAS, test_utils::{BytecodeBuilder, MemoryDatabase}, - MegaEvm, MegaHaltReason, + MegaEvm, }; use revm::{ bytecode::opcode::{CLZ, CREATE, DUPN, EXCHANGE, MSTORE, PUSH0, PUSH1, RETURN, SLOTNUM, SWAPN}, - context::result::{ExecutionResult, HaltReason}, + context::result::ExecutionResult, }; -use crate::common::{call, call_with_data, context, create, runs_at_measurement_prices}; +use crate::common::{ + account_state_gas, call, call_with_data, context, create, history, runs_at_measurement_prices, + slot_state_gas, +}; const CALLER: Address = address!("0000000000000000000000000000000000900000"); const CALLEE: Address = address!("0000000000000000000000000000000000900001"); -const GAS_LIMIT: u64 = 1_000_000; +/// 1,000,000 of regular gas on top of what the transactions here add at the byte prices in effect: +/// a new account and a fresh slot, a kilobyte of history, and 64 times the history of two records, +/// which a `CREATE` that forwards all but a 64th of its gas pays for the frame it starts from the +/// 64th it keeps. +fn gas_limit() -> u64 { + 1_000_000 + + account_state_gas() + + slot_state_gas() + + history(1_000) + + 64 * history(2 * mega_evm::WRITE_RECORD_SIZE) +} -/// The gas a transaction used and the state gas inside it. +/// The gas a transaction used, the state gas inside it, the history gas the schedule does not +/// price, and the EIP-7623 floor the receipt is held to. struct Spend { gas_used: u64, state: u64, + history: u64, + floor: u64, +} + +impl Spend { + /// What the schedule charged: everything the transaction used but the history ledger. + const fn schedule_gas(&self) -> u64 { + self.gas_used - self.history + } } /// Runs `tx` on `db` and returns what it spent. The transaction must succeed. fn spend(db: MemoryDatabase, tx: mega_evm::MegaTransaction) -> Spend { - let mut evm = MegaEvm::new(context(db)); - let result = evm.transact_raw(tx).expect("the transaction is valid").result; - assert!(result.is_success(), "{result:?}"); - Spend { gas_used: result.gas().tx_gas_used(), state: result.gas().state_gas_spent_final() } + let outcome = + MegaEvm::new(context(db)).execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + Spend { + gas_used: outcome.gas.gas_used, + state: outcome.gas.state, + history: outcome.gas.history, + floor: outcome.result.gas().floor_gas(), + } } /// A database where `CALLEE` exists and runs `code`. @@ -53,8 +85,8 @@ fn with_code(code: Bytes) -> MemoryDatabase { /// prices an access inside execution at 2,600. #[test] fn test_an_empty_call_costs_fifteen_thousand() { - let spent = spend(with_code(Bytes::new()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - assert_eq!(spent.gas_used, 15_000); + let spent = spend(with_code(Bytes::new()), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + assert_eq!(spent.schedule_gas(), 15_000); assert_eq!(spent.state, 0); } @@ -63,8 +95,8 @@ fn test_an_empty_call_costs_fifteen_thousand() { #[test] fn test_a_value_transfer_to_an_existing_account_costs_twenty_one_thousand() { let db = with_code(Bytes::new()).account_balance(CALLEE, U256::from(1)); - let spent = spend(db, call(CALLER, CALLEE, U256::from(7), GAS_LIMIT)); - assert_eq!(spent.gas_used, 21_000); + let spent = spend(db, call(CALLER, CALLEE, U256::from(7), gas_limit())); + assert_eq!(spent.schedule_gas(), 21_000); assert_eq!(spent.state, 0); } @@ -76,9 +108,9 @@ fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas( return; } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, call(CALLER, CALLEE, U256::from(7), GAS_LIMIT)); + let spent = spend(db, call(CALLER, CALLEE, U256::from(7), gas_limit())); assert_eq!(spent.state, ACCOUNT_STATE_GAS); - assert_eq!(spent.gas_used, 21_000 + ACCOUNT_STATE_GAS); + assert_eq!(spent.schedule_gas(), 21_000 + ACCOUNT_STATE_GAS); } /// A transfer to the sender itself pays the sender base alone: neither the recipient charge nor @@ -86,8 +118,8 @@ fn test_a_value_transfer_that_creates_the_recipient_draws_the_account_state_gas( #[test] fn test_a_self_transfer_costs_twelve_thousand() { let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, call(CALLER, CALLER, U256::from(7), GAS_LIMIT)); - assert_eq!(spent.gas_used, 12_000); + let spent = spend(db, call(CALLER, CALLER, U256::from(7), gas_limit())); + assert_eq!(spent.schedule_gas(), 12_000); assert_eq!(spent.state, 0); } @@ -100,14 +132,17 @@ fn test_a_create_transaction_costs_twenty_four_thousand_plus_the_account_state_g return; } let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, create(CALLER, Bytes::new(), GAS_LIMIT)); + let spent = spend(db, create(CALLER, Bytes::new(), gas_limit())); assert_eq!(spent.state, ACCOUNT_STATE_GAS, "the created account"); - assert_eq!(spent.gas_used - spent.state, 24_000, "the fixed part"); + assert_eq!(spent.schedule_gas() - spent.state, 24_000, "the fixed part"); } /// Init code is transaction data twice over: every byte is a calldata token, and EIP-3860 charges /// two gas for each 32-byte word of it. Sixty-four bytes of zeros is two words; sixty-five is /// three, so the word charge steps by two where the token charge steps by four. +/// +/// The receipt is held to the EIP-7623 floor, which the body's history lifts the bill past at the +/// spec's prices; where a history byte is cheap enough, the floor is the bill. #[test] fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { let fixed = 24_000; @@ -116,10 +151,11 @@ fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { for (len, words) in [(64u64, 2u64), (65, 3)] { let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); // Every byte is `STOP`, so the init code deposits nothing and costs nothing to run. - let spent = spend(db, create(CALLER, Bytes::from(vec![0u8; len as usize]), GAS_LIMIT)); + let spent = spend(db, create(CALLER, Bytes::from(vec![0u8; len as usize]), gas_limit())); + let charged = fixed + token * len + word * words; assert_eq!( - spent.gas_used - spent.state, - fixed + token * len + word * words, + spent.gas_used, + (charged + spent.state + spent.history).max(spent.floor), "{len} bytes of init code" ); } @@ -127,41 +163,6 @@ fn test_init_code_costs_its_calldata_tokens_and_an_eip3860_word() { /* ---------- the state entries ---------- */ -/// A slot's first write to a non-zero value draws the slot's state gas; writing it again does -/// not, because the slot is no longer new. -#[test] -fn test_a_new_slot_draws_the_slot_state_gas() { - if runs_at_measurement_prices() { - return; - } - let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let new = spend(with_code(code.clone()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - assert_eq!(new.state, SLOT_STATE_GAS); - - let db = with_code(code).account_storage(CALLEE, U256::ZERO, U256::from(1)); - let again = spend(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); - assert_eq!(again.state, 0, "the slot already holds the value"); -} - -/// Deployed code is priced by the byte on the state dimension, on top of the created account. -#[test] -fn test_deployed_code_draws_state_gas_by_the_byte() { - if runs_at_measurement_prices() { - return; - } - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let empty = spend(db(), create(CALLER, Bytes::new(), GAS_LIMIT)); - let thirty_two = spend(db(), create(CALLER, deploying(32), GAS_LIMIT)); - - assert_eq!(empty.state, ACCOUNT_STATE_GAS); - assert_eq!(thirty_two.state - empty.state, 32 * 1_530, "32 bytes at the state byte price"); -} - -/// Init code that returns `len` bytes of zeros as the deployed code. -fn deploying(len: u64) -> Bytes { - BytecodeBuilder::default().push_number(len).append_many([PUSH0, RETURN]).build() -} - /// A creation that reverts deposits nothing, so it draws no state gas at all: neither the /// created account's nor the code's. The state gas a creation draws is charged on the deposit, /// not on the attempt. @@ -171,7 +172,7 @@ fn test_a_reverted_creation_draws_no_state_gas() { let mut evm = MegaEvm::new(context(db)); let init_code = BytecodeBuilder::default().mstore(0, [0u8; 32]).revert().build(); let result = evm - .transact_raw(create(CALLER, init_code, GAS_LIMIT)) + .transact_raw(create(CALLER, init_code, gas_limit())) .expect("the transaction is valid") .result; @@ -188,31 +189,6 @@ fn depositing_an_ef_byte() -> Bytes { .build() } -/// EIP-3541 rejects deployed code whose first byte is `0xEF`, and the rejection lands before the -/// deposit is charged: the creation halts and draws no state gas, neither the account's nor the -/// byte's. -#[test] -fn test_a_creation_rejected_for_its_first_byte_draws_no_state_gas() { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let mut evm = MegaEvm::new(context(db)); - let result = evm - .transact_raw(create(CALLER, depositing_an_ef_byte(), GAS_LIMIT)) - .expect("the transaction is valid") - .result; - - assert!( - matches!( - result, - ExecutionResult::Halt { - reason: MegaHaltReason::Base(HaltReason::CreateContractStartingWithEF), - .. - } - ), - "{result:?}" - ); - assert_eq!(result.gas().state_gas_spent_final(), 0); -} - /// The same from a `CREATE` frame: the frame fails and returns the zero address, the transaction /// around it goes through, and the state gas the frame took upfront is back. #[test] @@ -229,29 +205,17 @@ fn test_a_create_frame_rejected_for_its_first_byte_draws_no_state_gas() { .assert_stack_value(0, U256::ZERO) .stop() .build(); - let spent = spend(with_code(factory), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let spent = spend(with_code(factory), call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert_eq!(spent.state, 0, "the created account and its byte are both taken back"); } -/// A creation that deposits nothing — empty runtime code — still pays for the account it -/// created, and nothing for code. -#[test] -fn test_a_creation_depositing_no_code_pays_for_the_account_alone() { - if runs_at_measurement_prices() { - return; - } - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))); - let spent = spend(db, create(CALLER, deploying(0), GAS_LIMIT)); - assert_eq!(spent.state, ACCOUNT_STATE_GAS); -} - /* ---------- the Amsterdam opcodes ---------- */ /// Runs `code` in `CALLEE` and returns the result, so a gated opcode shows up as a halt. fn run_code(code: Vec) -> ExecutionResult { let mut evm = MegaEvm::new(context(with_code(Bytes::from(code)))); - evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, gas_limit())) .expect("the transaction is valid") .result } @@ -282,22 +246,24 @@ fn test_clz_runs_on_the_base_spec() { assert!(result.is_success(), "{result:?}"); } -/// `SLOTNUM` pushes what the host reports, which is zero until the block executor sets it. +/// `SLOTNUM` pushes the block's slot number, `BlockEnv::slot_num`, which the node supplies, and +/// zero for a block that does not set it. #[test] -fn test_slotnum_pushes_the_host_slot_number() { - let code = BytecodeBuilder::default() - .append(SLOTNUM) - .push_number(0u64) - .append(MSTORE) - .push_number(32u64) - .push_number(0u64) - .append(RETURN) - .build(); - let mut evm = MegaEvm::new(context(with_code(code))); - let result = evm - .transact_raw(call_with_data(CALLER, CALLEE, Bytes::new(), GAS_LIMIT)) - .expect("the transaction is valid") - .result; - assert!(result.is_success(), "{result:?}"); - assert_eq!(result.output().map(Bytes::as_ref), Some([0u8; 32].as_slice())); +fn test_slotnum_pushes_the_blocks_slot_number() { + let code = BytecodeBuilder::default().append(SLOTNUM).return_top().build(); + for (slot_num, name) in [(0x0123_4567_89ab_u64, "a slot the node set"), (0, "no slot set")] { + let block = revm::context::BlockEnv { slot_num, ..crate::common::block() }; + let mut evm = MegaEvm::new(context(with_code(code.clone())).with_block(block)); + let result = evm + .transact_raw(call_with_data(CALLER, CALLEE, Bytes::new(), gas_limit())) + .expect("the transaction is valid") + .result; + assert!(result.is_success(), "{name}: {result:?}"); + assert_eq!( + result.output().map(|output| U256::from_be_slice(output)), + Some(U256::from(slot_num)), + "{name}", + ); + } + assert_eq!(crate::common::block().slot_num, 0, "the tests' block leaves it unset"); } diff --git a/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap new file mode 100644 index 000000000..6c7df5b53 --- /dev/null +++ b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap @@ -0,0 +1,96 @@ +--- +source: crates/mega-evm/tests/satin/corpus.rs +expression: gas +--- +{ + "access_list_warm_slots_and_account": [ + { + "outcome": "success", + "gas_used": 181749 + } + ], + "create_success": [ + { + "outcome": "success", + "gas_used": 363381 + } + ], + "eip7702_delegate_new_authority": [ + { + "outcome": "success", + "gas_used": 520385 + } + ], + "logs_all_topic_counts": [ + { + "outcome": "success", + "gas_used": 98665 + } + ], + "nested_call_revert_with_spill": [ + { + "outcome": "success", + "gas_used": 183060 + } + ], + "precompile_ecrecover": [ + { + "outcome": "success", + "gas_used": 399062 + }, + { + "outcome": "success", + "gas_used": 80157 + } + ], + "precompile_modexp": [ + { + "outcome": "success", + "gas_used": 392802 + }, + { + "outcome": "success", + "gas_used": 90338 + } + ], + "selfdestruct_created_in_same_tx_to_existing_account": [ + { + "outcome": "success", + "gas_used": 372085 + } + ], + "sstore_set_spills": [ + { + "outcome": "success", + "gas_used": 382917 + } + ], + "system_call": [ + { + "outcome": "success", + "gas_used": 220051 + } + ], + "test_calldata_floor_with_sstore_fork_Amsterdam_state_test": [ + { + "outcome": "success", + "gas_used": 182450 + } + ], + "test_nested_state_gas_refund_consumed_at_depth_fork_Amsterdam_state_test_consume_deepest_depth_10_sstore_restoration": [ + { + "outcome": "success", + "gas_used": 305844 + } + ], + "two_txs_sequential": [ + { + "outcome": "success", + "gas_used": 382917 + }, + { + "outcome": "success", + "gas_used": 62117 + } + ] +} diff --git a/crates/mega-evm/tests/satin/spec_numbers.rs b/crates/mega-evm/tests/satin/spec_numbers.rs new file mode 100644 index 000000000..38551315b --- /dev/null +++ b/crates/mega-evm/tests/satin/spec_numbers.rs @@ -0,0 +1,499 @@ +//! The numbers `docs/spec/upgrades/satin.md` states for Satin, against the constants and the +//! schedule. +//! +//! The page states the spec's own prices. The schedule compared with it is built at those prices, +//! so a measurement build's byte prices do not move the check. The developer-impact paragraph is a +//! measurement of a few transactions and is not part of this check. + +use mega_evm::{ + alloy_primitives::Address, + constants::{ + ACCOUNT_STATE_GAS, BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, COST_PER_HISTORY_BYTE, + COST_PER_STATE_BYTE, MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, MAX_TX_COMPUTE_GAS, + ORACLE_ACCESS_COMPUTE_GAS, SLOT_STATE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + }, + kzg_point_evaluation, + op_revm::precompiles::{ + bls12_381::{ + JOVIAN_G1_MSM, JOVIAN_G1_MSM_MAX_INPUT_SIZE, JOVIAN_G2_MSM, + JOVIAN_G2_MSM_MAX_INPUT_SIZE, JOVIAN_PAIRING, JOVIAN_PAIRING_MAX_INPUT_SIZE, + }, + bn254_pair::{KARST, KARST_MAX_INPUT_SIZE}, + }, + revm::{ + bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}, + context_interface::cfg::{gas::WARM_STORAGE_READ_COST, GasId, GasParams}, + handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, + interpreter::instructions::gas_table_spec, + precompile::secp256r1::{P256VERIFY_BASE_GAS_FEE_OSAKA, P256VERIFY_OSAKA}, + primitives::{ + eip2780::{TX_BASE_COST, TX_VALUE_COST}, + eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}, + eip8037::{ + AUTH_BASE_BYTES, CODE_DEPOSIT_PER_BYTE, NEW_ACCOUNT_BYTES, SSTORE_SET_BYTES, + }, + eip8038::COLD_ACCOUNT_ACCESS, + hardfork::SpecId, + }, + }, + satin_gas_params, satin_gas_params_at, satin_precompiles, + system::{ + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS}, + VolatileDataAccessType, CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE_HASH, + SLOT_NUM_ACCESS_TYPE, + }, + LimitKind, MegaSpecId, ProtocolLimits, SatinPrices, VolatileDataAccess, + ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, HISTORY_GAS_PRICED, LOG_BASE_SIZE, + LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, + SYSTEM_ADDRESS, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, + WRITE_RECORD_SIZE, +}; + +const SATIN_MD: &str = include_str!("../../../../docs/spec/upgrades/satin.md"); + +/// Every number the Satin upgrade page states, read back from the code it describes. +#[test] +fn test_satin_md_matches_the_constants() { + let doc = SATIN_MD; + named_constants(doc); + schedule(doc); + state_and_history(doc); + limits(doc); + precompiles(doc); + addresses(doc); + detention_and_stops(doc); +} + +fn named_constants(doc: &str) { + require_eq(doc, "COST_PER_STATE_BYTE", COST_PER_STATE_BYTE); + require_eq(doc, "COST_PER_HISTORY_BYTE", COST_PER_HISTORY_BYTE); + require_eq(doc, "EXECUTION_CAP", TX_GAS_LIMIT_CAP); + require_eq(doc, "MAX_CONTRACT_SIZE", MAX_CONTRACT_SIZE as u64); + require_eq(doc, "MAX_INITCODE_SIZE", MAX_INITCODE_SIZE as u64); + require_eq(doc, "TX_DATA_LIMIT", TX_DATA_LIMIT); + require_eq(doc, "TX_BODY_SIZE", TX_BODY_SIZE); + require_eq(doc, "TX_BASE_SIZE", TX_BASE_SIZE); + require_eq(doc, "TX_FIXED_WRITE_RECORDS", TX_FIXED_WRITE_RECORDS); + require_eq(doc, "ACCESS_LIST_ADDRESS_SIZE", ACCESS_LIST_ADDRESS_SIZE); + require_eq(doc, "ACCESS_LIST_SLOT_SIZE", ACCESS_LIST_SLOT_SIZE); + require_eq(doc, "AUTHORIZATION_SIZE", AUTHORIZATION_SIZE); + require_eq(doc, "WRITE_RECORD_SIZE", WRITE_RECORD_SIZE); + require_eq(doc, "TRANSFER_LOG_SIZE", TRANSFER_LOG_SIZE); + require_eq(doc, "HISTORY_ALLOWANCE_BYTES", STORAGE_CALL_STIPEND_BYTES); + require_eq(doc, "MIN_BUCKET_SIZE", MIN_BUCKET_SIZE as u64); + require_eq(doc, "KEYLESS_DEPLOY_OVERHEAD_GAS", KEYLESS_DEPLOY_OVERHEAD_GAS); + require_eq(doc, "BLOCK_ENV_ACCESS_COMPUTE_GAS", BLOCK_ENV_ACCESS_COMPUTE_GAS); + require_eq(doc, "ORACLE_ACCESS_COMPUTE_GAS", ORACLE_ACCESS_COMPUTE_GAS); + require_eq(doc, "SYSTEM_CALL_REGULAR_GAS_LIMIT", SYSTEM_CALL_REGULAR_GAS_LIMIT); + require_eq(doc, "TX_BASE_COST", TX_BASE_COST); + + require( + doc, + &format!( + "`LOG_BASE_SIZE` = {}, plus {} per topic", + grouped(LOG_BASE_SIZE), + grouped(LOG_TOPIC_SIZE) + ), + ); + require(doc, &format!("({} gas)", grouped(STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE))); + require(doc, &format!("capped at {} per transaction", grouped(TX_GAS_LIMIT_CAP))); + require(doc, &format!("at most {} of regular gas", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); + require(doc, &format!("max(block_gas_limit, {})", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); + require(doc, &format!("A {}-byte allowance", STORAGE_CALL_STIPEND_BYTES)); + require( + doc, + &format!( + "`FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = {}/{}", + FRAME_DATA_SHARE_NUMERATOR, FRAME_DATA_SHARE_DENOMINATOR + ), + ); + require(doc, &format!("KV × {WRITE_RECORD_SIZE} ≤ data size")); + let records = TX_DATA_LIMIT / WRITE_RECORD_SIZE; + require( + doc, + &format!( + "fewer than {} write records ({} / {})", + grouped(records), + grouped(TX_DATA_LIMIT), + WRITE_RECORD_SIZE + ), + ); +} + +fn schedule(doc: &str) { + let spec = satin_gas_params_at(SatinPrices::CONSTANTS); + let page = section(doc, "### 5. Gas Schedule", "### 6. State Gas"); + let rows = [ + ("Warm storage read", GasId::warm_storage_read_cost()), + ("Cold account access, additional", GasId::cold_account_additional_cost()), + ("Cold storage access of an `SLOAD`, additional", GasId::cold_storage_additional_cost()), + ("Cold storage access of an `SSTORE`", GasId::cold_storage_cost()), + ("Value transfer of a call", GasId::transfer_value_cost()), + ("New account of a call", GasId::new_account_cost()), + ("New account of `SELFDESTRUCT`", GasId::new_account_cost_for_selfdestruct()), + ("`SSTORE` static cost", GasId::sstore_static()), + ("`SSTORE` of a fresh slot, before the load cost", GasId::sstore_set_without_load_cost()), + ("`SSTORE` reset, before the cold load", GasId::sstore_reset_without_cold_load_cost()), + ("`SSTORE` refund of a restored fresh slot", GasId::sstore_set_refund()), + ("`SSTORE` refund of a restored reset", GasId::sstore_reset_refund()), + ("`SSTORE` refund of a cleared slot", GasId::sstore_clearing_slot_refund()), + ("`CREATE` and `CREATE2`", GasId::create()), + ("Creation transaction (unused under EIP-2780)", GasId::tx_create_cost()), + ("Access-list address", GasId::tx_access_list_address_cost()), + ("Access-list storage key", GasId::tx_access_list_storage_key_cost()), + ("Code deposit, regular gas per byte", GasId::code_deposit_cost()), + ("Code deposit, state gas per byte", GasId::code_deposit_state_gas()), + ("Code deposit, history gas per byte", GasId::code_deposit_history_gas()), + ("Fresh-slot `SSTORE`, state gas", GasId::sstore_set_state_gas()), + ("New account, state gas", GasId::new_account_state_gas()), + ("Created account, state gas", GasId::create_state_gas()), + ("EIP-7702 delegation indicator, state gas", GasId::tx_eip7702_state_gas_bytecode()), + ("EIP-7702 authorization, intrinsic regular gas", GasId::tx_eip7702_regular_gas()), + ("EIP-7702 refund for an existing authority", GasId::tx_eip7702_regular_refund()), + ("Account write (EIP-2780)", GasId::tx_account_write_cost()), + ("Creation access (EIP-2780)", GasId::tx_create_access_cost()), + ("Floor cost per token", GasId::tx_floor_cost_per_token()), + ("Floor base", GasId::tx_floor_cost_base_gas()), + ("Floor tokens per zero calldata byte", GasId::tx_floor_token_zero_byte_multiplier()), + ("Floor tokens per access-list byte", GasId::tx_access_list_floor_byte_multiplier()), + ]; + let osaka = GasParams::new_spec(SpecId::OSAKA); + for (label, id) in rows { + let row = table_row(page, label); + let [.., before, shown] = row[..] else { panic!("{label}: an Osaka and a Satin cell") }; + assert_eq!(before, grouped(osaka.get(id)), "{label} at Osaka"); + assert_eq!(shown, grouped(spec.get(id)), "{label}"); + if !byte_priced(id) { + assert_eq!(satin_gas_params().get(id), spec.get(id), "{label} is not a byte price"); + } + } + if !crate::common::runs_at_measurement_prices() { + let live = satin_gas_params(); + for (label, id) in rows { + assert_eq!(live.get(id), spec.get(id), "{label} at the prices in effect"); + } + } + + // The static gas of the two opcodes EIP-8038 gives two reads, which revm keeps in the + // instruction table rather than the schedule; the engine's table is Amsterdam's (a unit test of + // `evm/schedule.rs` holds it to that). + let row = table_row(page, "`EXTCODESIZE` and `EXTCODECOPY`, static gas"); + let [.., before, shown] = row[..] else { panic!("an Osaka and a Satin cell") }; + for opcode in [EXTCODESIZE, EXTCODECOPY] { + assert_eq!(before, grouped(gas_table_spec(SpecId::OSAKA)[opcode as usize].into())); + assert_eq!(shown, grouped(gas_table_spec(SpecId::AMSTERDAM)[opcode as usize].into())); + } + + let base = TX_BASE_COST; + let access = COLD_ACCOUNT_ACCESS; + let value = TX_VALUE_COST; + let creation = spec.get(GasId::tx_create_access_cost()); + require( + page, + &format!( + "MUST be `TX_BASE_COST` = {}, plus, for a call to another account, {} for the \ + recipient's access and {} more when it carries value; plus, for a creation, {}", + grouped(base), + grouped(access), + grouped(value), + grouped(creation) + ), + ); +} + +fn state_and_history(doc: &str) { + let spec = satin_gas_params_at(SatinPrices::CONSTANTS); + let bytes = SSTORE_SET_BYTES; + assert_eq!(spec.get(GasId::sstore_set_state_gas()), bytes * COST_PER_STATE_BYTE); + assert_eq!(spec.get(GasId::sstore_set_state_gas()), SLOT_STATE_GAS); + let account = NEW_ACCOUNT_BYTES; + assert_eq!(spec.get(GasId::new_account_state_gas()), account * COST_PER_STATE_BYTE); + assert_eq!(spec.get(GasId::new_account_state_gas()), ACCOUNT_STATE_GAS); + assert_eq!(spec.get(GasId::create_state_gas()), ACCOUNT_STATE_GAS); + let code = CODE_DEPOSIT_PER_BYTE; + assert_eq!(spec.get(GasId::code_deposit_state_gas()), code * COST_PER_STATE_BYTE); + let indicator = AUTH_BASE_BYTES; + assert_eq!(spec.get(GasId::tx_eip7702_state_gas_bytecode()), indicator * COST_PER_STATE_BYTE); + assert_eq!(spec.get(GasId::code_deposit_history_gas()), COST_PER_HISTORY_BYTE); + + let page = section(doc, "### 6. State Gas", "### 7. History Gas"); + assert_state_row(page, "Fresh storage slot", bytes, SLOT_STATE_GAS); + assert_state_row(page, "| New account ", account, ACCOUNT_STATE_GAS); + assert_state_row(page, "Created contract account", account, ACCOUNT_STATE_GAS); + assert_state_row(page, "Deployed code, per byte", code, code * COST_PER_STATE_BYTE); + assert_state_row( + page, + "EIP-7702 delegation indicator", + indicator, + indicator * COST_PER_STATE_BYTE, + ); + require(doc, &format!("`{} × m`", grouped(ACCOUNT_STATE_GAS))); +} + +fn limits(doc: &str) { + let defaults = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert_eq!(defaults.tx_runtime_limits.tx_data_size_limit, TX_DATA_LIMIT); + assert_eq!(defaults.block_txs_data_limit, BLOCK_DATA_LIMIT); + assert_eq!(TX_DATA_LIMIT, BLOCK_DATA_LIMIT, "the page states one data-size number for both"); + assert_eq!( + defaults.tx_runtime_limits.block_env_access_compute_gas_limit, + BLOCK_ENV_ACCESS_COMPUTE_GAS + ); + assert_eq!( + defaults.tx_runtime_limits.oracle_access_compute_gas_limit, + ORACLE_ACCESS_COMPUTE_GAS + ); + assert_eq!( + BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, + "the page states one detention cap for both" + ); + + // Data size is the one dimension limited per transaction and per block: no table row names a + // limit on KV updates, state gas or execution gas. + let resources = section(doc, "### 10. Resource Limits", "### 11. The Revert-Class"); + assert!( + table_row(resources, "Data size")[2].contains(&grouped(TX_DATA_LIMIT)), + "the transaction's data-size limit" + ); + let blocks = section(doc, "### 20. Block Limits", "### 21. Transaction and Block"); + for (page, removed) in [ + (resources, "KV updates"), + (resources, "State growth"), + (blocks, "Execution gas"), + (blocks, "State gas"), + (blocks, "KV updates"), + ] { + assert!( + !page.lines().any(|line| line.contains(removed) && line.contains('|')), + "no table row limits {removed}" + ); + } + assert_eq!( + *table_row(blocks, "Data size").last().unwrap(), + format!("{} bytes", grouped(BLOCK_DATA_LIMIT)) + ); + + let safety = section(doc, "## Safety and Compatibility", "## References"); + require( + safety, + &format!( + "the data-size limits at {} bytes and the detention caps at {} each", + grouped(TX_DATA_LIMIT), + grouped(BLOCK_ENV_ACCESS_COMPUTE_GAS) + ), + ); +} + +fn precompiles(doc: &str) { + let page = section(doc, "### 2. Precompiles", "### 3. Contract Size"); + let kzg = kzg_point_evaluation::ADDRESS; + assert_precompile( + page, + "KZG point evaluation", + kzg, + &format!("Fixed {} gas", grouped(kzg_point_evaluation::GAS_COST)), + ); + require(doc, &format!("exactly {}", grouped(kzg_point_evaluation::GAS_COST))); + require(doc, &format!("still at {}", grouped(kzg_point_evaluation::GAS_COST))); + + let p256_gas = P256VERIFY_BASE_GAS_FEE_OSAKA; + assert_precompile( + page, + "P256VERIFY", + *P256VERIFY_OSAKA.address(), + &format!("{} gas", grouped(p256_gas)), + ); + + let bn_bound = KARST_MAX_INPUT_SIZE as u64; + assert_precompile( + page, + "BN254 pairing", + *KARST.address(), + &format!("at most {} bytes", grouped(bn_bound)), + ); + + assert_precompile( + page, + "BLS12-381 G1 MSM", + *JOVIAN_G1_MSM.address(), + &format!("at most {} bytes", grouped(JOVIAN_G1_MSM_MAX_INPUT_SIZE as u64)), + ); + assert_precompile( + page, + "BLS12-381 G2 MSM", + *JOVIAN_G2_MSM.address(), + &format!("at most {} bytes", grouped(JOVIAN_G2_MSM_MAX_INPUT_SIZE as u64)), + ); + assert_precompile( + page, + "BLS12-381 pairing", + *JOVIAN_PAIRING.address(), + &format!("at most {} bytes", grouped(JOVIAN_PAIRING_MAX_INPUT_SIZE as u64)), + ); + let installed = satin_precompiles(); + for address in [ + kzg, + *P256VERIFY_OSAKA.address(), + *KARST.address(), + *JOVIAN_G1_MSM.address(), + *JOVIAN_G2_MSM.address(), + *JOVIAN_PAIRING.address(), + ] { + assert!(installed.contains(&address), "{address} is in the Satin set"); + } +} + +fn addresses(doc: &str) { + require_addr(doc, &format!("`KEYLESS_DEPLOY_ADDRESS` = `{KEYLESS_DEPLOY_ADDRESS}`")); + require_addr(doc, &CREATE2_FACTORY_ADDRESS.to_string()); + require_addr(doc, &CREATE2_FACTORY_CODE_HASH.to_string()); + assert_eq!( + ETH_TRANSFER_LOG_ADDRESS, SYSTEM_ADDRESS, + "the transfer log and the pre-block caller are the address the page names once" + ); + require_addr(doc, &SYSTEM_ADDRESS.to_string()); + require_addr(doc, Ð_TRANSFER_LOG_TOPIC.to_string()); +} + +fn detention_and_stops(doc: &str) { + let base = TX_BASE_COST; + assert_eq!(MAX_TX_COMPUTE_GAS, TX_GAS_LIMIT_CAP - base - WARM_STORAGE_READ_COST); + let detention = section(doc, "### 12. Gas Detention", "### 13. Volatile-Data"); + require(detention, &format!("below {}", grouped(MAX_TX_COMPUTE_GAS))); + require( + detention, + &format!( + "base cost of {}, which every transaction pays, and the {} of a warm account access", + grouped(base), + WARM_STORAGE_READ_COST + ), + ); + + let stops = section(doc, "### 11. The Revert-Class", "### 12. Gas Detention"); + let kinds = + [(LimitKind::DataSize, "Data size"), (LimitKind::ComputeGas, "Compute (gas detention)")]; + for (kind, name) in kinds { + let cells = row_with_first(stops, &kind.as_u8().to_string()); + assert_eq!(cells[1], name, "kind {}", kind.as_u8()); + } + for retired in [1_u8, 3] { + assert_eq!(LimitKind::from_u8(retired), None, "kind {retired} names no dimension"); + let first = retired.to_string(); + assert!( + stops.lines().map(cells).all(|cells| cells.first() != Some(&first.as_str())), + "the page lists no kind {retired}" + ); + } + + let access = section(doc, "### 13. Volatile-Data", "### 14. EIP-7708"); + let reads = [ + (VolatileDataAccess::BLOCK_NUMBER, "`NUMBER`"), + (VolatileDataAccess::TIMESTAMP, "`TIMESTAMP`"), + (VolatileDataAccess::COINBASE, "`COINBASE`"), + (VolatileDataAccess::GAS_LIMIT, "`GASLIMIT`"), + (VolatileDataAccess::BASE_FEE, "`BASEFEE`"), + (VolatileDataAccess::PREV_RANDAO, "`PREVRANDAO`"), + (VolatileDataAccess::BLOCK_HASH, "`BLOCKHASH`"), + (VolatileDataAccess::BLOB_BASE_FEE, "`BLOBBASEFEE`"), + (VolatileDataAccess::BENEFICIARY_BALANCE, "block beneficiary's account"), + (VolatileDataAccess::ORACLE, "Oracle's storage"), + (VolatileDataAccess::SLOT_NUM, "`SLOTNUM`"), + ]; + for (kind, name) in reads { + let cells = row_with_first(access, &kind.as_u8().to_string()); + assert!(cells[1].contains(name), "access {} is {name}, row {cells:?}", kind.as_u8()); + } + assert_eq!(VolatileDataAccess::SLOT_NUM.as_u8(), SLOT_NUM_ACCESS_TYPE); + require( + access, + &format!( + "Values {} (`Difficulty`) and {} (`BlobHash`) are not produced.", + VolatileDataAccessType::Difficulty as u8, + VolatileDataAccessType::BlobHash as u8 + ), + ); +} + +fn byte_priced(id: GasId) -> bool { + STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || + HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) +} + +fn require_eq(doc: &str, name: &str, value: u64) { + require(doc, &format!("`{name}` = {}", grouped(value))); +} + +fn require(doc: &str, phrase: &str) { + assert!(doc.contains(phrase), "satin.md is missing {phrase}"); +} + +fn require_addr(doc: &str, phrase: &str) { + assert!( + doc.to_ascii_lowercase().contains(&phrase.to_ascii_lowercase()), + "satin.md is missing {phrase}" + ); +} + +fn section<'a>(doc: &'a str, start: &str, end: &str) -> &'a str { + let at = doc.find(start).unwrap_or_else(|| panic!("satin.md is missing {start}")); + let rest = &doc[at..]; + let stop = rest[start.len()..] + .find(end) + .map(|index| index + start.len()) + .unwrap_or_else(|| panic!("satin.md is missing {end}")); + &rest[..stop] +} + +fn table_row<'a>(doc: &'a str, label: &str) -> Vec<&'a str> { + let line = doc + .lines() + .find(|line| line.contains(label) && line.contains('|')) + .unwrap_or_else(|| panic!("satin.md has no table row containing {label}")); + cells(line) +} + +fn row_with_first<'a>(doc: &'a str, first: &str) -> Vec<&'a str> { + doc.lines() + .map(cells) + .find(|cells| cells.first() == Some(&first)) + .unwrap_or_else(|| panic!("satin.md has no table row starting with {first}")) +} + +fn cells(line: &str) -> Vec<&str> { + line.split('|').map(str::trim).filter(|cell| !cell.is_empty()).collect() +} + +fn assert_state_row(doc: &str, label: &str, bytes: u64, entry: u64) { + let cells = table_row(doc, label); + assert_eq!(cells[1], grouped(bytes), "{label} bytes"); + assert_eq!(cells[2], grouped(entry), "{label} entry"); +} + +fn assert_precompile(doc: &str, label: &str, address: Address, tail: &str) { + let cells = table_row(doc, label); + let shown = cells[1].trim_matches('`'); + let parsed = short_address(shown); + assert_eq!(parsed, address, "{label}"); + assert!(cells[2].contains(tail), "{label} should state {tail}, row says {}", cells[2]); +} + +/// A precompile address as the page writes it (`0x0A`, `0x100`), left-padded to 20 bytes. +fn short_address(shown: &str) -> Address { + let hex = shown.trim().trim_start_matches("0x").trim_start_matches("0X"); + let value = + u64::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("not a short address: {shown}")); + Address::left_padding_from(&value.to_be_bytes()) +} + +fn grouped(value: u64) -> String { + let digits = value.to_string(); + let mut out = String::new(); + for (index, digit) in digits.chars().rev().enumerate() { + if index > 0 && index % 3 == 0 { + out.push(','); + } + out.push(digit); + } + out.chars().rev().collect() +} diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs new file mode 100644 index 000000000..2c4439f10 --- /dev/null +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -0,0 +1,638 @@ +//! The state a transaction adds, which no limit holds: EIP-8037 charges state gas for exactly that +//! state, and the transaction's own gas pays for it. +//! +//! What each site charges — a fresh slot, an account a value transfer, a creation or a destruction +//! adds, an applied EIP-7702 authority — is the schedule's state-gas entry, at the minimum bucket, +//! where the test database puts every state, net of what a write back or a failed frame gives back. +//! A charge the transaction cannot pay is an out-of-gas. What was applied before the first frame — +//! an admitted authority, a deposit's created caller — outlives a stop, as through any failed first +//! frame. +//! +//! No figure is read off a run. They move with the byte prices a measurement build sets; where a +//! state byte costs nothing, which only a measurement build arranges, no transaction adds state +//! gas, so the cases that need a state charge return early. + +use alloy_primitives::{address, Address, Bytes, B256, U256}; +use mega_evm::{ + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, + WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{ + CALL, CREATE, DELEGATECALL, GAS, INVALID, POP, PUSH0, SELFDESTRUCT, STOP, +}; + +use crate::common::{ + account_state_gas, authorizing_call, body_history, call, context, execute_under, history, + slot_state_gas, state_is_free, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000600000"); +const A: Address = address!("0000000000000000000000000000000000600001"); +const B: Address = address!("0000000000000000000000000000000000600002"); +const BURNER: Address = address!("0000000000000000000000000000000000600004"); +/// An account that does not exist, so reaching it with value creates it. +const EMPTY: Address = address!("0000000000000000000000000000000000600005"); +const DELEGATE: Address = address!("0000000000000000000000000000000000600006"); +const AUTHORITY_1: Address = address!("0000000000000000000000000000000000600007"); +const AUTHORITY_2: Address = address!("0000000000000000000000000000000000600008"); + +/// Below the execution cap: the reservoir is empty and every state charge spills onto regular gas. +const BELOW_CAP: u64 = 50_000_000; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(A, U256::from(1_000)) + .account_code(BURNER, Bytes::from_static(&[INVALID])) +} + +/// Runs `tx` over `db` under no limit. +fn run(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + execute_under(db, tx, EvmTxRuntimeLimits::no_limits()) +} + +/// Runs `tx` over `db` under a transaction data-size limit of `limit`. +fn run_under_data_size( + db: MemoryDatabase, + tx: MegaTransaction, + limit: u64, +) -> MegaTransactionOutcome { + execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)) +} + +/// The outcome was stopped by the transaction's data-size limit `limit`, crossed at `used`: a +/// revert carrying `MegaLimitExceeded(0, limit)`, never a halt. +fn assert_data_size_stopped(what: &str, outcome: &MegaTransactionOutcome, limit: u64, used: u64) { + assert!( + !outcome.result.is_success() && !outcome.result.is_halt(), + "{what}: {:?}", + outcome.result + ); + let stop = + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local: false }; + assert_eq!(outcome.limit_exceeded, Some(stop), "{what}"); + assert_eq!(outcome.result.output().unwrap(), &stop.revert_data(), "{what}"); +} + +/// Appends writes of the fresh slots `from..to`. +fn write_slots(mut builder: BytecodeBuilder, from: u64, to: u64) -> BytecodeBuilder { + for slot in from..to { + builder = builder.sstore(U256::from(slot), U256::from(slot + 1)); + } + builder +} + +/// The schedule's state gas for the account a creation adds. +fn created_account_state_gas() -> u64 { + crate::salt::entry(revm::context_interface::cfg::GasId::create_state_gas()) +} + +/// A slot a delegate writes back, from a frame of its own, gives its state gas back, and the +/// transaction keeps the one slot the delegate writes after it. The other ways a charge is given +/// back — a slot written back in its own frame, a failed child, a failed creation — are held at +/// every multiplier with the SALT pricing. +/// +/// Independence: constants — the slot is the schedule's entry. +#[test] +fn test_a_delegate_that_writes_a_slot_back_gives_its_state_gas_back() { + let delegate_to_b = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append(GAS) + .append(DELEGATECALL) + .append(POP) + .stop() + .build(); + let restores_then_writes = BytecodeBuilder::default() + .sstore(U256::ZERO, U256::ZERO) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + let db = funded().account_code(A, delegate_to_b).account_code(B, restores_then_writes); + let outcome = run(db, call(CALLER, A, U256::ZERO, BELOW_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, slot_state_gas()); +} + +/// One authorization: its authority — `None` for a signature that recovers to nobody — its chain +/// id and its nonce. +type Authorization = (Option
, u64, u64); + +/// A type-4 call from `CALLER` to `to` carrying `value` and `authorizations`, each delegating its +/// authority to `DELEGATE`. +fn authorizing(to: Address, value: U256, authorizations: &[Authorization]) -> MegaTransaction { + use revm::context_interface::{ + either::Either, + transaction::{RecoveredAuthority, RecoveredAuthorization}, + }; + let mut tx = authorizing_call(CALLER, to, value, BELOW_CAP, DELEGATE, &[]); + tx.0.base.authorization_list = authorizations + .iter() + .map(|(authority, chain_id, nonce)| { + Either::Right(RecoveredAuthorization::new_unchecked( + revm::context_interface::transaction::Authorization { + chain_id: U256::from(*chain_id), + address: DELEGATE, + nonce: *nonce, + }, + authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + )) + }) + .collect(); + tx +} + +/// The schedule's state gas for a new account and for a delegation's bytes. +fn account_and_delegation() -> (u64, u64) { + use crate::salt::entry; + use revm::context_interface::cfg::GasId; + (entry(GasId::new_account_state_gas()), entry(GasId::tx_eip7702_state_gas_bytecode())) +} + +/// An authorization adds state only when it applies: a new account for an authority that did not +/// exist, and the delegation's bytes once for an authority that was not delegated. Each authority +/// it applies to is one write record, however many of its authorizations applied, except the +/// sender, whose account is the body's. An authorization that does not apply — a wrong nonce, a +/// wrong chain, a nonce that cannot be bumped, an account with code, a signature that recovers to +/// nobody — adds nothing and leaves its authority as it was. +#[test] +fn test_an_authorization_adds_state_only_when_it_applies() { + if state_is_free() { + return; + } + let (account, delegation) = account_and_delegation(); + let a1 = Some(AUTHORITY_1); + let a2 = Some(AUTHORITY_2); + let with_code = || funded().account_code(AUTHORITY_1, Bytes::from_static(&[STOP])); + // (case, database, authorizations, state gas, records, AUTHORITY_1's nonce after) + type Case = (&'static str, MemoryDatabase, Vec, u64, u64, u64); + let cases: Vec = vec![ + ("a new authority", funded(), vec![(a1, 0, 0)], account + delegation, 1, 1), + ( + "two new authorities", + funded(), + vec![(a1, 0, 0), (a2, 0, 0)], + 2 * (account + delegation), + 2, + 1, + ), + ( + "one new authority authorized twice at its first nonce", + funded(), + vec![(a1, 0, 0), (a1, 0, 0)], + account + delegation, + 1, + 1, + ), + ( + "one new authority authorized twice in sequence", + funded(), + vec![(a1, 0, 0), (a1, 0, 1)], + account + delegation, + 1, + 2, + ), + ( + "an authority that exists", + funded().account_balance(AUTHORITY_1, U256::from(1)), + vec![(a1, 0, 0)], + delegation, + 1, + 1, + ), + ( + "an authority on the transaction's chain", + funded(), + vec![(a1, 1, 0)], + account + delegation, + 1, + 1, + ), + ("an authority on another chain", funded(), vec![(a1, 999, 0)], 0, 0, 0), + ("a wrong nonce", funded(), vec![(a1, 0, 1)], 0, 0, 0), + ("a nonce that cannot be bumped", funded(), vec![(a1, 0, u64::MAX)], 0, 0, 0), + ("an authority with code", with_code(), vec![(a1, 0, 0)], 0, 0, 0), + ("a signature that recovers to nobody", funded(), vec![(None, 0, 0)], 0, 0, 0), + ( + "the sender, at the nonce its transaction leaves it", + funded(), + vec![(Some(CALLER), 0, 1)], + delegation, + 0, + 0, + ), + ( + "the sender, at its transaction's own nonce", + funded(), + vec![(Some(CALLER), 0, 0)], + 0, + 0, + 0, + ), + ]; + for (name, db, authorizations, state_gas, records, nonce) in cases { + let tuples = authorizations.len() as u64 * mega_evm::AUTHORIZATION_SIZE; + let outcome = run( + db.account_code(A, Bytes::from_static(&[STOP])), + authorizing(A, U256::ZERO, &authorizations), + ); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.gas.state, state_gas, "{name}: the state gas"); + assert_eq!(outcome.usage.write_records, records, "{name}: the records"); + assert_eq!( + outcome.usage.data_size, + TX_BODY_SIZE + tuples + records * WRITE_RECORD_SIZE, + "{name}: the data size", + ); + let authority = outcome.state.get(&AUTHORITY_1); + assert_eq!(authority.map_or(0, |a| a.info.nonce), nonce, "{name}: the authority's nonce"); + let delegated = + outcome.state.values().any(|a| a.info.code.as_ref().is_some_and(|c| c.is_eip7702())); + assert_eq!(delegated, state_gas >= delegation, "{name}: whether anything was delegated"); + } +} + +/// The state gas an authority costs is charged before the first frame, from the transaction's +/// gas. A gas limit that covers it in a minimal bucket but not in a crowded one is not refused at +/// validation: the transaction runs out of gas before its first frame, and the out-of-gas takes +/// the authorization back. +#[test] +fn test_an_authority_the_transaction_cannot_pay_for_is_not_applied() { + if state_is_free() { + return; + } + use crate::salt::{crowded_account, minimal_envs, salt_context}; + let tx = |gas_limit| { + let mut tx = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + tx.0.base.gas_limit = gas_limit; + tx + }; + let run = |envs, gas_limit| { + MegaEvm::new(salt_context(funded().account_code(A, Bytes::from_static(&[STOP])), envs)) + .execute_transaction(tx(gas_limit)) + .expect("the transaction is valid") + }; + let minimal = run(minimal_envs(), BELOW_CAP); + assert!(minimal.result.is_success()); + let budget = minimal.gas.gas_used; + + let crowded = run(crowded_account(minimal_envs(), AUTHORITY_1, 100), budget); + assert!(crowded.result.is_halt(), "an out-of-gas, not a refusal: {:?}", crowded.result); + let authority = crowded.state.get(&AUTHORITY_1); + assert!( + authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), + "the authorization was taken back: {authority:?}" + ); + // And a gas limit that covers the authority at the crowded price applies it. + let (account, delegation) = account_and_delegation(); + let roomy = BELOW_CAP + 100 * (account + delegation); + assert!(run(crowded_account(minimal_envs(), AUTHORITY_1, 100), roomy).result.is_success()); +} + +/// A value transaction to an authority it creates pays for one new account, not two: by the time +/// EIP-2780 looks at the recipient the authorization has created it. It is one record too. +#[test] +fn test_an_authority_that_is_the_recipient_pays_for_one_account() { + let (account, delegation) = account_and_delegation(); + let outcome = + run(funded(), authorizing(AUTHORITY_1, U256::from(1), &[(Some(AUTHORITY_1), 0, 0)])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, account + delegation); + assert_eq!(outcome.usage.write_records, 1); + + let unauthorized = run(funded(), call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP)); + assert_eq!(unauthorized.gas.state, account, "the same transfer without it pays the account"); +} + +/// A transaction whose authorities' records would cross the data-size limit is rejected at +/// validation, whether the authorities are new or exist already: validation holds the body and a +/// record for each entry of the authorization list to the limit, before anything is applied or +/// charged. At the limit, both apply. +#[test] +fn test_authorities_whose_records_would_cross_the_data_size_limit_reject_the_transaction() { + let both = [(Some(AUTHORITY_1), 0, 0), (Some(AUTHORITY_2), 0, 0)]; + let fresh = || funded().account_code(A, Bytes::from_static(&[STOP])); + let existing = || { + fresh() + .account_balance(AUTHORITY_1, U256::from(1)) + .account_balance(AUTHORITY_2, U256::from(1)) + }; + let body = TX_BODY_SIZE + 2 * AUTHORIZATION_SIZE; + let at = body + 2 * WRITE_RECORD_SIZE; + for (name, db) in [("two existing authorities", existing()), ("two new authorities", fresh())] { + for limit in [body, at - 1] { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let error = MegaEvm::new(context(db.clone()).with_tx_runtime_limits(limits)) + .execute_transaction(authorizing(A, U256::ZERO, &both)) + .expect_err("rejected at validation"); + let error = format!("{error:?}"); + assert!(error.contains(TX_BODY_OVER_DATA_SIZE_LIMIT), "{name} at {limit}: {error}"); + } + let applied = run_under_data_size(db, authorizing(A, U256::ZERO, &both), at); + assert!(applied.result.is_success(), "{name}: {:?}", applied.result); + assert_eq!(applied.usage.write_records, 2, "{name}: both apply at the limit"); + } +} + +/// A stop takes back what the frames did and keeps what was applied before the first frame. An +/// admitted authority keeps its nonce, its delegation, its state gas, its write record and the +/// history that record cost, as it does when its frame does nothing; the value the first frame +/// carried and that frame's own record come back with the frame. The stop is the data-size limit, +/// crossed by the record of the slot the frame writes after the authority's record and, with value, +/// after its own start's record and transfer log. +/// +/// Rules: [S11.8], [S11.14]. Independence: constants — the limit is the byte table's sizes; what +/// the authority keeps is compared with a run whose frame does nothing. +#[test] +fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { + let delegation = |outcome: &MegaTransactionOutcome| { + outcome.state[&AUTHORITY_1].info.code.as_ref().map(|code| code.original_bytes()) + }; + let (account, delegation_state_gas) = account_and_delegation(); + let authority = account + delegation_state_gas; + for value in [U256::ZERO, U256::from(1)] { + let writes = + funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + let idle = funded().account_code(A, BytecodeBuilder::default().stop().build()); + let tx = authorizing_call(CALLER, A, value, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]); + let start = if value.is_zero() { 0 } else { WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE }; + let limit = TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE + start; + let stopped = run_under_data_size(writes, tx.clone(), limit); + assert_data_size_stopped("the slot", &stopped, limit, limit + WRITE_RECORD_SIZE); + let applied = run(idle, tx); + assert!(applied.result.is_success(), "{:?}", applied.result); + + assert_eq!(stopped.state[&AUTHORITY_1].info.nonce, 1, "value {value}"); + assert!(delegation(&stopped).is_some_and(|code| !code.is_empty()), "value {value}"); + assert_eq!(delegation(&stopped), delegation(&applied), "value {value}"); + assert_eq!(stopped.gas.state, authority, "value {value}: the authority's state gas"); + assert_eq!(stopped.gas.state, applied.gas.state, "value {value}"); + assert_eq!(stopped.usage.write_records, 1, "value {value}: the authority's record alone"); + assert_eq!( + stopped.gas.history_bytes, + TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE, + "value {value}: the body, its authorization and the authority's record" + ); + if value.is_zero() { + assert_eq!(stopped.gas.history, applied.gas.history); + } else { + assert_eq!( + applied.gas.history_bytes - stopped.gas.history_bytes, + WRITE_RECORD_SIZE, + "the recipient's record comes back with the frame" + ); + } + assert_eq!(stopped.state[&A].info.balance, U256::from(1_000), "value {value}"); + } +} + +/// A deposit-like transaction's caller, created before the first frame, outlives a stop with the +/// deposit's mint and the state gas charged for the account. The stop is the data-size limit, +/// crossed by the record of the slot the deposit's frame writes. +/// +/// Rules: [S11.13]. Independence: constants — the limit is the byte table's sizes, the caller's +/// account the schedule's entry. +#[test] +fn test_a_stopped_deposit_keeps_the_caller_it_created() { + let fresh = address!("00000000000000000000000000000000006000ff"); + let deposit = |code: Bytes| { + let mut tx = call(fresh, A, U256::ZERO, BELOW_CAP); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.deposit.mint = Some(5); + tx.0.base.gas_price = 0; + (funded().account_code(A, code), tx) + }; + let (writes, tx) = deposit(write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); + let stopped = run_under_data_size(writes, tx, TX_BODY_SIZE); + assert_data_size_stopped("the slot", &stopped, TX_BODY_SIZE, TX_BODY_SIZE + WRITE_RECORD_SIZE); + let (idle, tx) = deposit(BytecodeBuilder::default().stop().build()); + let created = run(idle, tx); + assert!(created.result.is_success(), "{:?}", created.result); + + let caller = &stopped.state[&fresh].info; + assert_eq!((caller.balance, caller.nonce), (U256::from(5), 1), "the mint and the nonce stay"); + assert_eq!(stopped.gas.state, created.gas.state, "the caller's state gas stays with it"); + assert_eq!(stopped.gas.state, account_state_gas(), "the caller's account"); +} + +/// A `SELFDESTRUCT` of value to itself grows no state and records nothing. The destructions that +/// move value to another account are held with the SALT pricing and the write records. +#[test] +fn test_a_destruction_to_itself_grows_no_state() { + let db = funded() + .account_code(A, BytecodeBuilder::default().push_address(A).append(SELFDESTRUCT).build()); + let outcome = run(db, call(CALLER, A, U256::ZERO, BELOW_CAP)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "the state gas"); + assert_eq!(outcome.usage.write_records, 0, "the records"); +} + +/// A state charge the frame cannot pay is an out-of-gas, which no limit turns into a stop. +/// +/// Each case is a transaction below the execution cap, so there is no reservoir, whose gas limit +/// pays everything before its state charge and leaves it one gas short of that charge: a fresh +/// slot's `SSTORE`, a `SELFDESTRUCT` that moves a balance to an account that does not exist, a +/// value transaction to an account that does not exist, whose start EIP-2780 charges for the new +/// account, and, from `A`, a value `CALL` to an account that does not exist and a `CREATE`, whose +/// opcodes charge the account the frame they start adds. It halts out of gas, consumes its whole +/// gas limit, keeps no state gas, and reports no stop: not a stop that would give the unspent gas +/// back. +/// +/// Once the state charge is paid, a frame start still charges the caller the history of the two +/// records the frame makes, after the gas it forwards is computed [S7.23]; one gas short of what +/// the start costs in all is an out-of-gas too, and the frame does not start [S7.24]. A `CREATE` +/// charges the created account before its 63/64 split, as EIP-8037 has it, so the records come out +/// of the 64th the creator keeps, and the creator must hold 64 times their price after the state +/// charge. EIP-8037 states that order for a creation alone — of a value `CALL` it says only that +/// the charge comes right before the child frame is entered — so, though the engine charges a +/// `CALL`'s new account before its split too, that order is not pinned here: the `CALL` forwards +/// an explicit nothing — the same forward in any order — and its rows hold whatever the order: a +/// gas limit short of the state charge, and one gas short of the whole start, runs out of gas. +/// +/// Every case runs under a data-size limit of the body alone, which the record made right after +/// the state charge crosses — the slot's, the beneficiary's, the new account's — and which a charge +/// the transaction cannot pay never reaches. With exactly what the transaction needs to the end of +/// its state charge — and of the start's records — it is that limit that stops the frame that +/// makes the record, which pins each gas limit as one gas short of the charge, or of the start, +/// and nothing else. A value `CALL`'s start is answered with the stop, which its caller catches +/// and ends on; a `CREATE`'s still bumps its creator's nonce, whose record then stops the creator, +/// the transaction's own frame. +/// +/// Independence: constants. Each gas limit is written out from the spec's numbers — the EIP-2780 +/// base of 12,000, 3,000 for the recipient and 6,000 for its value, two gas per `PUSH0` and three +/// per other push, 5,000 for `SELFDESTRUCT` — and the schedule's entries for the opcodes' regular +/// gas, the state charges and the history price; none is read off a run. +#[test] +fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() { + use mega_evm::{satin_gas_params, MegaHaltReason}; + use revm::{ + context::result::{ExecutionResult, HaltReason}, + context_interface::cfg::GasId, + }; + + // Where a state byte is free there is no state charge to fall short of. + if state_is_free() { + return; + } + let params = satin_gas_params(); + let entry = |id: GasId| params.get(id); + // A call to an account that exists, before its code runs: the EIP-2780 base and the + // recipient, then the body's history. + let call_intrinsic = 12_000 + 3_000 + body_history(0); + // The history of the two records a frame start makes: a value transfer's sender and + // recipient, or a creation's creator nonce and created account. + let start_records = history(2 * WRITE_RECORD_SIZE); + // (case, database, the transaction at a gas limit, what it pays before the state charge, the + // state charge, what it pays after the state charge for the stop to be reached, whether the + // transaction's own frame catches the stop) + type Case = (&'static str, MemoryDatabase, fn(u64) -> MegaTransaction, u64, u64, u64, bool); + let to_a = |gas_limit| call(CALLER, A, U256::ZERO, gas_limit); + let cases: [Case; 5] = [ + ( + "a fresh slot", + funded().account_code(A, write_slots(BytecodeBuilder::default(), 0, 1).stop().build()), + to_a, + // Two pushes, then the store's static, cold and set gas. + call_intrinsic + + 2 * 3 + + entry(GasId::sstore_static()) + + entry(GasId::cold_storage_cost()) + + entry(GasId::sstore_set_without_load_cost()), + slot_state_gas(), + // The slot's record is held before its history is charged. + 0, + false, + ), + ( + "a SELFDESTRUCT that creates its beneficiary", + funded().account_code( + A, + BytecodeBuilder::default().push_address(EMPTY).append(SELFDESTRUCT).build(), + ), + to_a, + // The push, the opcode's 5,000, its new account's regular gas, and the cold access to + // the beneficiary. + call_intrinsic + + 3 + + 5_000 + + entry(GasId::new_account_cost_for_selfdestruct()) + + entry(GasId::cold_account_additional_cost()) + + entry(GasId::warm_storage_read_cost()), + account_state_gas(), + // The beneficiary's record is held before its history is charged. + 0, + false, + ), + ( + "a value transaction to an account that does not exist", + funded(), + |gas_limit| call(CALLER, EMPTY, U256::from(1), gas_limit), + // The base, the recipient and its value, the body's history, then the history of the + // recipient's write record, which is charged before the account. + 12_000 + 3_000 + 6_000 + body_history(0) + history(WRITE_RECORD_SIZE), + account_state_gas(), + 0, + false, + ), + ( + "a value CALL to an account that does not exist", + funded().account_code( + A, + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(EMPTY) + .append(PUSH0) + .append(CALL) + .stop() + .build(), + ), + to_a, + // Four `PUSH0` for the empty input and output, the value's and the address's pushes, + // a `PUSH0` for a forward of nothing, then the call's warm access, the cold surcharge + // on the recipient, the value transfer and the new account's regular gas. + call_intrinsic + + 4 * 2 + + 3 + + 3 + + 2 + + entry(GasId::warm_storage_read_cost()) + + entry(GasId::cold_account_additional_cost()) + + entry(GasId::transfer_value_cost()) + + entry(GasId::new_account_cost()), + account_state_gas(), + // The two records, which a forward of nothing leaves to the caller. + start_records, + true, + ), + ( + "a CREATE", + funded().account_code( + A, + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, CREATE]) + .stop() + .build(), + ), + to_a, + // Three `PUSH0` for an empty init code carrying no value, then the creation's 32,000. + call_intrinsic + 3 * 2 + entry(GasId::create()), + created_account_state_gas(), + // The two records, out of the 64th the creator keeps after its forward. + 64 * start_records, + false, + ), + ]; + for (name, db, tx, before, charge, then, caught) in cases { + let short = before + charge - 1; + let start = before + charge + then; + let mut rows = vec![(format!("{name}, one gas short of the state charge"), short)]; + if then > 0 { + rows.push((format!("{name}, one gas short of the frame start"), start - 1)); + } + for (row, gas_limit) in rows { + let ran_out = run_under_data_size(db.clone(), tx(gas_limit), TX_BODY_SIZE); + assert!( + matches!( + &ran_out.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), + .. + } + ), + "{row}: an out-of-gas: {:?}", + ran_out.result + ); + assert_eq!(ran_out.limit_exceeded, None, "{row}: no stop"); + assert_eq!(ran_out.gas.gas_used, gas_limit, "{row}: the whole gas limit is consumed"); + assert_eq!(ran_out.gas.state, 0, "{row}: no state gas is kept"); + } + + let paid = run_under_data_size(db.clone(), tx(start), TX_BODY_SIZE); + if caught { + assert!(paid.result.is_success(), "{name}: the caller catches the stop"); + assert_eq!( + paid.limit_exceeded, None, + "{name}: a stop below the transaction's own frame" + ); + assert_eq!(paid.usage.data_size, TX_BODY_SIZE, "{name}: the start's records went"); + continue; + } + assert!( + matches!( + paid.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: TX_BODY_SIZE, + frame_local: false, + .. + }) + ), + "{name}, everything paid: the record after the charge is the stop, {:?}", + paid.limit_exceeded + ); + } +} diff --git a/crates/mega-evm/tests/satin/static_callee.rs b/crates/mega-evm/tests/satin/static_callee.rs index daa8b4379..ebdcd1dab 100644 --- a/crates/mega-evm/tests/satin/static_callee.rs +++ b/crates/mega-evm/tests/satin/static_callee.rs @@ -3,8 +3,8 @@ //! A `CREATE` or `CREATE2` in a static frame halts with `StateChangeDuringStaticCall` before it //! reads an operand, sizes its init code or charges anything, as in canonical revm. The //! transaction does not expose an inner frame's halt reason, so these read it off the frame's -//! outcome as the caller receives it. The transactions are those of the parked tests of the same -//! names (`tests/_pending/rex6/create2_metering_order.rs`). +//! outcome as the caller receives it. The transactions are those of the legacy tests of the same +//! names, which compared the halt reason with an earlier spec's. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs new file mode 100644 index 000000000..781397192 --- /dev/null +++ b/crates/mega-evm/tests/satin/stops.rs @@ -0,0 +1,1636 @@ +//! The revert-class stop, pinned as a matrix. +//! +//! A limit — data size or gas detention's compute limit — stops the frame that crosses it with a +//! revert: the frame reverts with `MegaLimitExceeded(kind, limit)` and keeps nothing it did, and +//! its caller resumes as after any revert. A crossing the transaction's own frame makes is the +//! transaction's result, which settles like an EIP-8037 revert: the sender pays for what ran, and +//! its unspent regular gas and the reservoir come back. A frame budget stops its frame the same +//! way. A real out-of-gas and a precompile given less than its price still halt, and burn what +//! their frame was given. +//! +//! The matrix crosses each limit in the transaction's own frame and in a frame three calls below +//! it, below the execution cap and above it, where a reservoir pays the body first, without an +//! inspector and under one that records every frame's end. The callers of a frame three calls +//! down catch its stop and end at no cost, which is how a caller finishes within a compute limit +//! its callee crossed: the transaction succeeds, keeping what the callers did and nothing of the +//! frame that crossed. What ran is read off a twin of each transaction: the same frames without +//! limits, the one that crossed reverting where it crossed. The twin settles its revert itself, so +//! it bills exactly what the stop should, plus the two pushes of its revert, and keeps what the +//! stopped transaction keeps. +//! +//! A column of creations revived by an inspector that rewrites every frame result into a success +//! shows that a revived stop settles as a frame that kept nothing, and is no stop. +//! +//! The last cells cross a limit three calls down with a frame answered without running — an +//! answer past what the compute limit leaves it, a precompile run on that allowance, and a start +//! whose records cross the data-size limit before the frame is built — and the callers catch the +//! stop the same way. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{ + BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + }, + system::ORACLE_CONTRACT_ADDRESS, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitStop, LimitUsage, MegaContext, MegaEvm, + MegaHaltReason, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, + FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADD, BALANCE, CALL, GAS, LOG0, MLOAD, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, + SLOAD, SSTORE, TIMESTAMP, + }, + context::result::ExecutionResult, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, + }, + primitives::HashMap, + Database, Inspector, +}; + +use crate::{ + common::{body_history, call, call_with_data, create}, + detention::{cold_access, context, fresh_write, fresh_write_spill, work, Charges, BENEFICIARY}, + withheld_gas::{priced, Runs, PRICED}, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000500000"); +const A: Address = address!("0000000000000000000000000000000000500001"); +const B: Address = address!("0000000000000000000000000000000000500002"); +const C: Address = address!("0000000000000000000000000000000000500003"); +const D: Address = address!("0000000000000000000000000000000000500004"); +/// The frames of a chain, by depth: `A` is the transaction's own frame, `D` is three calls below. +const CHAIN: [Address; 4] = [A, B, C, D]; + +/// Below the execution cap: no reservoir. +const BELOW: u64 = 100_000_000; +/// Above it: a reservoir of 100,000,000, which pays the body's history first. +const ABOVE: u64 = TX_GAS_LIMIT_CAP + 100_000_000; +const TIERS: [u64; 2] = [BELOW, ABOVE]; + +/// Gas detention's cap on a read of the block environment, the spec's. +const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; + +/// The fresh slots the transaction's own frame writes before it calls or crosses. +const OWN_SLOTS: u64 = 2; +/// The fresh slot whose write crosses a limit. +const CROSSING_SLOT: U256 = U256::from_limbs([0x10, 0, 0, 0]); +/// The slot a frame writes once it runs on after its crossing: a write of it is an instruction +/// run after the stop. +const MARKER: U256 = U256::from_limbs([0xaa, 0, 0, 0]); +/// Rounds of the compute loop a frame runs after it read the block's timestamp: over 21,000,000 +/// of compute, past the cap. +const ROUNDS: u32 = 7_000; +/// What the two pushes before the twin's revert cost. +const TWIN_REVERT: u64 = 4; + +/// A limit the matrix crosses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Limit { + DataSize, + Compute, +} + +impl Limit { + const ALL: [Self; 2] = [Self::DataSize, Self::Compute]; + + const fn kind(self) -> LimitKind { + match self { + Self::DataSize => LimitKind::DataSize, + Self::Compute => LimitKind::ComputeGas, + } + } +} + +/// Appends a log with no topic and no data: 32 bytes of data size, and a log a stop must not keep. +fn log(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, LOG0]) +} + +/// Appends a call to `to` with all the gas, leaving its status on the stack. +fn call_all(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]).push_address(to).append(GAS).append(CALL) +} + +/// Appends a revert with no data. +fn revert(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, REVERT]) +} + +/// The code of the frame at `depth` of a chain whose frame at `crossing` crosses `limit`. +/// +/// Every frame logs first, and the transaction's own frame writes [`OWN_SLOTS`] fresh slots. Every +/// frame above the one at `crossing` then calls the next and stops, which costs nothing: it +/// catches what the call returned and ends within any limit. The frame at `crossing` crosses the +/// limit — a fresh slot's write, or a read of the block's timestamp and more compute than the cap +/// — and would then write [`MARKER`] and log again, which a stopped frame never runs; its twin +/// reverts where it crossed, right after the read for the compute limit. +fn frame_code(limit: Limit, depth: usize, crossing: usize, twin: bool) -> Bytes { + let mut code = log(BytecodeBuilder::default()); + if depth == 0 { + for slot in 1..=OWN_SLOTS { + code = code.sstore(U256::from(slot), U256::from(1)); + } + } + if depth < crossing { + return call_all(code, CHAIN[depth + 1]).stop().build(); + } + let code = match limit { + Limit::Compute if twin => code.append(TIMESTAMP), + Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), + Limit::DataSize => code.sstore(CROSSING_SLOT, U256::from(1)), + }; + if twin { + revert(code).build() + } else { + log(code.sstore(MARKER, U256::from(1))).stop().build() + } +} + +/// The chain whose frame at `crossing` crosses `limit`, stopped or its twin. +fn chain(limit: Limit, crossing: usize, twin: bool) -> MemoryDatabase { + (0..=crossing).fold(MemoryDatabase::default(), |db, depth| { + db.account_code(CHAIN[depth], frame_code(limit, depth, crossing, twin)) + }) +} + +/// What a transaction from `CALLER` to `A` with `gas_limit` spends before its first instruction: an +/// `A` that stops at once, without limits. +fn intrinsic(gas_limit: u64) -> MegaTransactionOutcome { + let db = MemoryDatabase::default().account_code(A, BytecodeBuilder::default().stop().build()); + let outcome = execute(db, EvmTxRuntimeLimits::no_limits(), gas_limit); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0); + // The body's history is paid before the first frame, from the reservoir when there is one. + let reservoir = gas_limit.saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(outcome.gas.history); + assert_eq!(outcome.gas.reservoir_remaining, reservoir); + outcome +} + +/// Runs a call from `CALLER` to `A` under `limits`. +fn execute( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + gas_limit: u64, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid") +} + +/// Records every step and the result of every frame it sees end, and, made to rewrite +/// ([`rewriting`](Self::rewriting)), then rewrites that result into a success with no output — a +/// creation's too, which revives a creation that failed: a tool's inspector. +#[derive(Clone, Default)] +struct FrameRecorder { + /// Whether it rewrites the results it records. + rewrites: bool, + /// Every step: the frame it ran in, its opcode, and the slot it named when it was an `SSTORE`. + steps: Vec<(Address, u8, Option)>, + /// The calls that ended, deepest first, with the result each had before any rewrite. + ended: Vec<(Address, InstructionResult, Bytes)>, + /// The creations that ended, with the result each had before any rewrite. + created: Vec<(InstructionResult, Bytes)>, +} + +impl FrameRecorder { + /// One that records and rewrites nothing. + fn recording() -> Self { + Self::default() + } + + /// One that records, then rewrites every result into a success. + fn rewriting() -> Self { + Self { rewrites: true, ..Self::default() } + } + + /// How many writes of [`MARKER`] ran. + fn marker_writes(&self) -> usize { + self.steps.iter().filter(|(_, _, slot)| *slot == Some(MARKER)).count() + } + + /// The last step that ran in `frame`. + fn last_in(&self, frame: Address) -> Option<(u8, Option)> { + self.steps.iter().rev().find(|step| step.0 == frame).map(|step| (step.1, step.2)) + } +} + +impl Inspector, EthInterpreter> for FrameRecorder { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + let slot = (opcode == SSTORE).then(|| interp.stack.peek(0).expect("SSTORE takes a slot")); + self.steps.push((interp.input.target_address, opcode, slot)); + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + let result = &mut outcome.result; + self.ended.push((inputs.target_address, result.result, result.output.clone())); + if self.rewrites { + result.result = InstructionResult::Stop; + result.output = Bytes::new(); + } + } + + fn create_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let result = &mut outcome.result; + self.created.push((result.result, result.output.clone())); + if self.rewrites { + result.result = InstructionResult::Return; + result.output = Bytes::new(); + } + } +} + +/// The slots `account` changed in `outcome`, with the values it left in them. +fn changed(outcome: &MegaTransactionOutcome, account: Address) -> Vec<(U256, U256)> { + let mut changed: Vec<_> = outcome + .state + .get(&account) + .map(|account| { + account + .storage + .iter() + .filter(|(_, slot)| slot.is_changed()) + .map(|(key, slot)| (*key, slot.present_value())) + .collect() + }) + .unwrap_or_default(); + changed.sort(); + changed +} + +/// One row of the matrix, both columns: `limit` crossed by the frame at `crossing` of a +/// transaction with `gas_limit`, without an inspector and under one that records every step and +/// frame end. +fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { + let row = format!("{limit:?} at depth {crossing}, gas limit {gas_limit}"); + let caught = crossing > 0; + let intrinsic = intrinsic(gas_limit); + + // The twin: the same frames, the one that crossed reverting where it crossed, its callers + // catching the revert and ending. + let twin = execute(chain(limit, crossing, true), EvmTxRuntimeLimits::no_limits(), gas_limit); + if caught { + assert!(twin.result.is_success(), "{row}: the twin's callers end: {:?}", twin.result); + } else { + assert!( + matches!(&twin.result, ExecutionResult::Revert { output, .. } if output.is_empty()), + "{row}: the twin reverts: {:?}", + twin.result + ); + } + assert_eq!(twin.limit_exceeded, None, "{row}"); + // The regular gas the frames spent up to the crossing: for the compute limit, up to the read. + let before_crossing = twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT; + + // The limit crossed, and the usage that crossed it: one more byte than the limit. The compute + // limit is set by the read, at the compute it ran to plus the cap, and the stop reports the + // compute up to the charge that crosses it: after the read's `POP`, one of the work's. + let (configured, value) = limits_of(limit, crossing); + let (value, used) = match value { + Some(value) => (value, value + 1), + None => { + let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); + (before_crossing + CAP, before_crossing + CAP - left) + } + }; + let stop = + LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local: false }; + // What ran: up to the crossing, and for the compute limit up to the charge that crosses it. + // The callers that catch the stop end at no cost. + let ran = if limit == Limit::Compute { used } else { before_crossing }; + + let plain = execute(chain(limit, crossing, false), configured, gas_limit); + let mut evm = + MegaEvm::new(context(chain(limit, crossing, false)).with_tx_runtime_limits(configured)) + .with_inspector(FrameRecorder::recording()); + let recorded = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + let recorder = evm.inspector(); + + for (column, outcome) in [("plain", &plain), ("recorded", &recorded)] { + let cell = format!("{row}, {column}"); + if caught { + // The receipt: the callers caught the stop and ended. + assert!(outcome.result.is_success(), "{cell}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{cell}: a stop below is no stop of it"); + assert_eq!(outcome.limit_stop(), None, "{cell}: nothing for an RPC to map"); + } else { + // The receipt: a revert carrying the stop, which the outcome names. + match &outcome.result { + ExecutionResult::Revert { output, .. } => { + assert_eq!(output, &stop.revert_data(), "{cell}: the stop's revert data") + } + other => panic!("{cell}: expected the stop, got {other:?}"), + } + assert_eq!(outcome.limit_exceeded, Some(stop), "{cell}"); + assert_eq!( + outcome.limit_stop(), + Some(LimitStop { kind: limit.kind(), limit: value, used }), + "{cell}: what an RPC maps the stop to" + ); + } + + // The bill: intrinsic gas plus what ran on the regular ledger; on every other ledger what + // the twin keeps, which is what the callers did before the crossing and nothing of the + // frame that crossed: for the transaction's own frame, the body alone. + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); + assert_eq!(outcome.gas.state, twin.gas.state, "{cell}: state"); + assert_eq!(outcome.gas.history, twin.gas.history, "{cell}: history"); + assert_eq!(outcome.gas.history_bytes, twin.gas.history_bytes, "{cell}"); + assert_eq!( + outcome.gas.reservoir_remaining, twin.gas.reservoir_remaining, + "{cell}: the reservoir comes back, less what was kept" + ); + assert_eq!( + outcome.gas.gas_used, + twin.gas.gas_used - TWIN_REVERT - before_crossing + ran, + "{cell}: gas used" + ); + if !caught { + assert_eq!(outcome.gas.state, 0, "{cell}: a stop keeps no state gas"); + assert_eq!(outcome.gas.history, intrinsic.gas.history, "{cell}: the body's history"); + } + + // What the frame that crossed did is not kept; what its callers did is. + assert_eq!(outcome.result.logs(), twin.result.logs(), "{cell}: the callers' logs alone"); + for account in &CHAIN[..=crossing] { + assert_eq!(changed(outcome, *account), changed(&twin, *account), "{cell}: {account}"); + } + assert_eq!(outcome.usage, twin.usage, "{cell}: what is kept"); + match limit { + Limit::DataSize => assert!(outcome.usage.data_size <= value, "{cell}: within it"), + Limit::Compute => { + let compute = outcome.gas.regular - intrinsic.gas.regular; + assert!(compute <= value, "{cell}: within the limit, {compute} of {value}"); + } + } + if !caught { + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + "{cell}: the body stays" + ); + } + } + // The recorder changes nothing. No instruction ran after the crossing in the frame that + // crossed, and every caller resumed and ended. + assert_eq!(recorded.gas, plain.gas, "{row}"); + assert_eq!(recorder.marker_writes(), 0, "{row}: no frame ran on after the crossing"); + if limit == Limit::DataSize { + assert_eq!( + recorder.last_in(CHAIN[crossing]), + Some((SSTORE, Some(CROSSING_SLOT))), + "{row}: the crossing write was the crossing frame's last step" + ); + } + let ended: Vec<_> = CHAIN[..=crossing] + .iter() + .rev() + .map(|frame| { + if *frame == CHAIN[crossing] { + (*frame, InstructionResult::Revert, stop.revert_data()) + } else { + (*frame, InstructionResult::Stop, Bytes::new()) + } + }) + .collect(); + assert_eq!( + recorder.ended, ended, + "{row}: the frame that crossed returned the stop, and every caller ended, deepest first" + ); +} + +/// Every limit, crossed by the transaction's own frame and by a frame three calls below it, stops +/// the frame that crosses it — below the execution cap and above it, with and without an +/// inspector that records every step. Three calls down, the callers catch the stop and end, and +/// the transaction succeeds, keeping what they did and nothing of the frame that crossed; at the +/// transaction's own frame the stop is the transaction's result. +/// +/// Rules: [S11.1], [S11.2], [S11.3], [S11.4], [S11.6], [S11.7], [S11.8]. Independence: constants +/// for every limit and the stop it reports, and engine-derived for the bill, which a twin run sets. +#[test] +fn test_every_limit_stops_the_frame_that_crosses_it_at_every_depth_and_tier() { + for limit in Limit::ALL { + for crossing in [0, 3] { + for gas_limit in TIERS { + assert_cell(limit, crossing, gas_limit); + } + } + } +} + +/// Rewrites every call result it sees end into `into`, and leaves its gas as it is. +struct Halter { + into: InstructionResult, +} + +impl Inspector, EthInterpreter> for Halter { + fn call_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + outcome.result.result = self.into; + } +} + +/// An inspector that rewrites every frame result into a halt gets the halt: a stop is a revert of +/// the frame that crossed, which the rewrite turns into a halt like any other result, so the +/// transaction halts, keeps nothing but its body, and reports no stop, whether the frame that +/// crossed was its own or three calls below, under every limit and at either tier. The stop is +/// in the inspector's hands as every result is. +/// +/// Rules: [S11.1], [S11.6]. Independence: constants — the body is `TX_BODY_SIZE`. +#[test] +fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { + let halts = [ + InstructionResult::OutOfGas, + InstructionResult::PrecompileOOG, + InstructionResult::InvalidFEOpcode, + ]; + for limit in Limit::ALL { + for crossing in [0, 3] { + for gas_limit in TIERS { + let (configured, _) = limits_of(limit, crossing); + for into in halts { + let case = + format!("{limit:?} at depth {crossing}, gas limit {gas_limit}, {into:?}"); + let mut evm = MegaEvm::new( + context(chain(limit, crossing, false)).with_tx_runtime_limits(configured), + ) + .with_inspector(Halter { into }); + let halted = + evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); + assert_eq!(halted.limit_exceeded, None, "{case}: the result is no stop"); + assert!(halted.result.logs().is_empty(), "{case}"); + assert_eq!( + halted.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + "{case}: the body alone" + ); + } + } + } + } +} + +/// The limits a cell runs under, and the stop's limit where it is known before the run: every +/// dimension but the compute limit, which the read sets. +fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { + let frames = crossing as u64 + 1; + match limit { + Limit::DataSize => { + let value = + TX_BODY_SIZE + frames * LOG_BASE_SIZE + (OWN_SLOTS + 1) * WRITE_RECORD_SIZE - 1; + (EvmTxRuntimeLimits::default().with_tx_data_size_limit(value), Some(value)) + } + Limit::Compute => (EvmTxRuntimeLimits::default(), None), + } +} + +/* ---------- creations under an inspector that revives them ---------- */ + +/// Where a creation meets the limit it crosses. +#[derive(Clone, Copy, Debug)] +enum Creation { + /// The transaction is a creation, and its init code crosses the limit. + Transaction, + /// The transaction's own frame creates a contract whose init code crosses the limit. + Nested, + /// The transaction's own frame creates a contract whose start crosses the limit — its write + /// records, or the account it adds — so its init code never runs. + NestedStart, +} + +/// Init code that logs, then crosses `limit`: a fresh slot's write, or a read of the block's +/// timestamp and more compute than the cap. +fn crossing_init_code(limit: Limit) -> Vec { + let code = log(BytecodeBuilder::default()); + let code = match limit { + Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), + _ => code.sstore(CROSSING_SLOT, U256::from(1)), + }; + code.stop().build_vec() +} + +/// The database and the transaction of `creation`, for `limit`. +fn creation_run( + creation: Creation, + limit: Limit, + gas_limit: u64, +) -> (MemoryDatabase, mega_evm::MegaTransaction) { + let init_code = crossing_init_code(limit); + match creation { + Creation::Transaction => { + (MemoryDatabase::default(), create(CALLER, init_code.into(), gas_limit)) + } + Creation::Nested | Creation::NestedStart => { + let code = BytecodeBuilder::default().create(U256::ZERO, init_code).append(POP); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + (db, call(CALLER, A, U256::ZERO, gas_limit)) + } + } +} + +/// The limits under which `creation` crosses `limit` by one unit at the place it names. +/// +/// Where the init code crosses, the limit is one unit below what the whole transaction uses without +/// limits, whose last write is the init code's; the compute limit is the spec's cap. Where the +/// start crosses, the limit is what the transaction used before it. +fn creation_limits(creation: Creation, limit: Limit, gas_limit: u64) -> EvmTxRuntimeLimits { + let limits = EvmTxRuntimeLimits::default(); + if matches!(creation, Creation::NestedStart) { + return match limit { + Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), + Limit::Compute => unreachable!("a start charges no compute past the cap"), + }; + } + let (db, tx) = creation_run(creation, limit, gas_limit); + let unlimited = + MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(unlimited.result.is_success(), "{creation:?}, {limit:?}: {:?}", unlimited.result); + match limit { + Limit::DataSize => limits.with_tx_data_size_limit(unlimited.usage.data_size - 1), + Limit::Compute => limits, + } +} + +/// A creation the limit stopped, revived by an inspector that rewrites every frame result into a +/// success, settles as a frame that kept nothing, as a revived call does, and is no stop: the +/// result of the transaction's own frame is the inspector's success, so the outcome names no stop. +/// A creation transaction whose init code crosses a limit, a nested creation whose init code +/// crosses one, and a nested creation whose start crosses one each end with the stop before their +/// revival, deploy nothing, keep what the run without the inspector keeps, and bill what it bills, +/// below the execution cap and above it. +#[test] +fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { + let cases = [ + (Creation::Transaction, Limit::ALL.as_slice()), + (Creation::Nested, Limit::ALL.as_slice()), + (Creation::NestedStart, [Limit::DataSize].as_slice()), + ]; + for (creation, limits) in cases { + for &limit in limits { + for gas_limit in TIERS { + let case = format!("{creation:?}, {limit:?}, gas limit {gas_limit}"); + let configured = creation_limits(creation, limit, gas_limit); + let (db, tx) = creation_run(creation, limit, gas_limit); + let mut evm = MegaEvm::new(context(db.clone()).with_tx_runtime_limits(configured)) + .with_inspector(FrameRecorder::recording()); + let plain = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); + let [(InstructionResult::Revert, stop)] = evm.inspector().created.as_slice() else { + panic!( + "{case}: the creation ended with a revert: {:?}", + evm.inspector().created + ) + }; + let (kind, _) = mega_evm::decode_mega_limit_exceeded(stop) + .unwrap_or_else(|| panic!("{case}: the creation was stopped: {stop}")); + assert_eq!(kind, limit.kind(), "{case}"); + let stop = stop.clone(); + + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(configured)) + .with_inspector(FrameRecorder::rewriting()); + let revived = evm.execute_transaction(tx).expect("the revival is not refused"); + let rewriter = evm.inspector(); + assert_eq!( + rewriter.created, + [(InstructionResult::Revert, stop)], + "{case}: the creation ended with the stop before its revival" + ); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert_eq!(revived.limit_exceeded, None, "{case}: no stop is the result"); + let created = match creation { + Creation::Transaction => CALLER.create(0), + Creation::Nested | Creation::NestedStart => A.create(0), + }; + assert!( + revived.state.get(&created).is_none_or(|account| account.info.is_empty()), + "{case}: nothing deployed" + ); + assert_eq!(revived.usage, plain.usage, "{case}: what the plain run keeps"); + assert_eq!(revived.gas, plain.gas, "{case}: what the plain run bills"); + } + } + } +} + +/* ---------- the frame the last step ran in ---------- */ + +/// Records the frame the last step ran in. +#[derive(Default)] +struct LastStep(Option
); + +impl Inspector, EthInterpreter> for LastStep { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + self.0 = Some(interp.input.target_address); + } +} + +/// Runs `tx` on `db` under `limits` and a [`LastStep`], and returns the outcome and the frame the +/// last step ran in. +fn run_recording_steps( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + tx: mega_evm::MegaTransaction, +) -> (MegaTransactionOutcome, Option
) { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(LastStep::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + (outcome, evm.inspector().0) +} + +/* ---------- frame budgets ---------- */ + +/// The slot a frame stores its call's status in. +const STATUS: U256 = U256::from_limbs([0xa1, 0, 0, 0]); +/// The slot a frame stores the size of what its call returned in. +const RETURNED: U256 = U256::from_limbs([0xa2, 0, 0, 0]); +/// The slot a frame stores the kind its callee's stop named in. +const STOP_KIND: U256 = U256::from_limbs([0xa3, 0, 0, 0]); +/// The slot a frame stores the limit its callee's stop named in. +const STOP_LIMIT: U256 = U256::from_limbs([0xa4, 0, 0, 0]); + +/// A frame that logs, calls `to` with `gas` (all of it when `None`), and runs on: it stores the +/// call's status and the size of what the call returned, with `decode` the kind and the limit of +/// the `MegaLimitExceeded` it returned, then writes [`MARKER`]. +fn resuming(to: Address, gas: Option, decode: bool) -> Bytes { + let code = log(BytecodeBuilder::default()).append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]); + let code = match gas { + Some(gas) => code.push_address(to).push_number(gas), + None => code.push_address(to).append(GAS), + }; + let mut code = code + .append(CALL) + .push_u256(STATUS) + .append(SSTORE) + .append(RETURNDATASIZE) + .push_u256(RETURNED) + .append(SSTORE); + if decode { + // The two words after the selector: the kind, then the limit. + code = code + .push_number(64_u8) + .push_number(4_u8) + .append_many([PUSH0, RETURNDATACOPY, PUSH0, MLOAD]) + .push_u256(STOP_KIND) + .append(SSTORE) + .push_number(32_u8) + .append(MLOAD) + .push_u256(STOP_LIMIT) + .append(SSTORE); + } + code.sstore(MARKER, U256::from(1)).stop().build() +} + +/// A frame that logs and writes the fresh slots `1..=slots`, then [`MARKER`]. +fn writer(slots: u64) -> Bytes { + (1..=slots) + .fold(log(BytecodeBuilder::default()), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }) + .sstore(MARKER, U256::from(1)) + .stop() + .build() +} + +/// `A -> B -> C -> D`, `D` running `d`: each of `A`, `B` and `C` runs on after its call, and `C` +/// decodes what `D` returned. +fn resuming_chain(d: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_code(A, resuming(B, None, false)) + .account_code(B, resuming(C, None, false)) + .account_code(C, resuming(D, None, true)) + .account_code(D, d) +} + +/// What a child gets of what its parent has left. +const fn share(remaining: u64) -> u64 { + remaining * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR +} + +/// The value `outcome` left in `slot` of `account`. +fn slot_of(outcome: &MegaTransactionOutcome, account: Address, slot: U256) -> U256 { + outcome + .state + .get(&account) + .and_then(|account| account.storage.get(&slot)) + .map_or(U256::ZERO, |slot| slot.present_value()) +} + +/// A frame three calls below the transaction's own that crosses its data-size budget reverts alone +/// with `MegaLimitExceeded(0, budget)`, where the budget is what the shares left it. Its caller +/// resumes and reads the stop, every frame above runs on, the transaction reports no stop and +/// succeeds, below and above the execution cap. +#[test] +fn test_a_frame_budget_crossed_three_calls_down_reverts_that_frame_alone() { + // The transaction's own frame gets the room above the body; each relay logs before it calls, + // which counts 32 bytes and no write record. + const ROOM: u64 = 1_000; + let budget = share(share(share(ROOM - LOG_BASE_SIZE) - LOG_BASE_SIZE) - LOG_BASE_SIZE); + let kind = LimitKind::DataSize; + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + ROOM); + // D's log and its writes cross its budget long before the transaction's limit. + let d = writer(budget / WRITE_RECORD_SIZE + 1); + for gas_limit in TIERS { + let case = format!("gas limit {gas_limit}"); + let outcome = execute(resuming_chain(d.clone()), limits, gas_limit); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}: a frame budget below is no stop"); + + // C read D's stop: a failed call returning `MegaLimitExceeded(kind, budget)`. + assert_eq!(slot_of(&outcome, C, STATUS), U256::ZERO, "{case}: D reverted"); + assert_eq!(slot_of(&outcome, C, RETURNED), U256::from(68), "{case}"); + assert_eq!(slot_of(&outcome, C, STOP_KIND), U256::from(kind.as_u8()), "{case}"); + assert_eq!(slot_of(&outcome, C, STOP_LIMIT), U256::from(budget), "{case}"); + // Every caller ran on, D kept nothing. + for frame in [A, B] { + assert_eq!(slot_of(&outcome, frame, STATUS), U256::from(1), "{case}: {frame}"); + } + for frame in [A, B, C] { + assert_eq!(slot_of(&outcome, frame, MARKER), U256::from(1), "{case}: {frame}"); + } + let d_kept = + outcome.state.get(&D).is_some_and(|d| d.storage.values().any(|slot| slot.is_changed())); + assert!(!d_kept, "{case}: D kept a write"); + let loggers: Vec<_> = outcome.result.logs().iter().map(|log| log.address).collect(); + assert_eq!(loggers, [A, B, C], "{case}: D's log went with its frame"); + } +} + +/* ---------- halts ---------- */ + +/// Every per-transaction limit, armed and never crossed: a halt must stay a halt under them. +fn armed() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_DATA_LIMIT) +} + +/// A loop that never ends. A round copies 32 KiB within memory, which costs 3,075 gas and the +/// interpreter one instruction, so the frame runs out of however much gas it has in few rounds. +fn spin() -> Bytes { + crate::detention::spin(BytecodeBuilder::default()) +} + +/// The ECRECOVER precompile, whose price is 3,000 whatever its input. +const ECRECOVER: Address = address!("0000000000000000000000000000000000000001"); +/// The MODEXP precompile. +const MODEXP: Address = address!("0000000000000000000000000000000000000005"); + +/// A frame three calls below the transaction's own that halts burns what its caller gave it: a +/// frame that runs out of its own gas, and a precompile given less than its price. Its caller +/// resumes and the transaction succeeds, with every limit armed, below and above the execution +/// cap. Two forwards that differ by some gas bill the transaction exactly that much apart. +#[test] +fn test_a_halt_three_calls_down_burns_its_frames_gas_and_its_caller_resumes() { + // (what C calls, and two forwards it may give it, both short of what it needs) + let rows = [(D, 50_000, 80_000), (ECRECOVER, 1_000, 2_999)]; + for (callee, small, large) in rows { + for gas_limit in TIERS { + let case = format!("{callee}, gas limit {gas_limit}"); + let run = |forward: u64| { + let db = MemoryDatabase::default() + .account_code(A, resuming(B, None, false)) + .account_code(B, resuming(C, None, false)) + .account_code(C, resuming(callee, Some(forward), false)) + .account_code(D, spin()); + let outcome = execute(db, armed(), gas_limit); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}"); + assert_eq!(slot_of(&outcome, C, STATUS), U256::ZERO, "{case}: the callee halted"); + assert_eq!( + slot_of(&outcome, C, RETURNED), + U256::ZERO, + "{case}: a halt returns nothing" + ); + for frame in [A, B, C] { + assert_eq!(slot_of(&outcome, frame, MARKER), U256::from(1), "{case}: {frame}"); + } + outcome.gas + }; + let (small_gas, large_gas) = (run(small), run(large)); + assert_eq!( + large_gas.gas_used - small_gas.gas_used, + large - small, + "{case}: the halt burned the whole forward" + ); + assert_eq!(large_gas.regular - small_gas.regular, large - small, "{case}"); + assert_eq!( + (large_gas.state, large_gas.history, large_gas.reservoir_remaining), + (small_gas.state, small_gas.history, small_gas.reservoir_remaining), + "{case}: only regular gas burns" + ); + } + } +} + +/// The transaction's own frame that halts burns all its regular gas, with every limit armed: a +/// frame that runs out of its own gas, and a call straight to a precompile priced above what the +/// transaction has — ECRECOVER one gas short below the execution cap, a MODEXP priced past the cap +/// above it. The reservoir comes back, less the body it paid. +#[test] +fn test_the_transactions_own_frame_that_halts_burns_its_regular_gas() { + use revm::context::result::{HaltReason, OutOfGasError}; + + for gas_limit in TIERS { + let reservoir = intrinsic(gas_limit).gas.reservoir_remaining; + let db = MemoryDatabase::default().account_code(A, spin()); + let outcome = execute(db, armed(), gas_limit); + assert!( + matches!( + &outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.gas.reservoir_remaining, reservoir, "gas limit {gas_limit}"); + assert_eq!(outcome.gas.gas_used + reservoir, gas_limit, "the regular gas burned"); + } + + // ECRECOVER below the cap, given one gas less than its price. + let precompile_tx = |to: Address, input: Vec, gas_limit: u64| { + MegaEvm::new(context(MemoryDatabase::default()).with_tx_runtime_limits(armed())) + .execute_transaction(call_with_data(CALLER, to, input.into(), gas_limit)) + .expect("the transaction is valid") + }; + let paid = precompile_tx(ECRECOVER, Vec::new(), BELOW); + assert!(paid.result.is_success(), "{:?}", paid.result); + let before_frame = paid.gas.gas_used - 3_000; + let short = precompile_tx(ECRECOVER, Vec::new(), before_frame + 2_999); + let modexp_input = crate::withheld_gas::costly_modexp_input(512, 0); + let past_the_cap = precompile_tx(MODEXP, modexp_input, ABOVE); + for (outcome, gas_limit) in [(short, before_frame + 2_999), (past_the_cap, ABOVE)] { + assert!( + matches!( + &outcome.result, + ExecutionResult::Halt { + reason: MegaHaltReason::Base(HaltReason::OutOfGas(OutOfGasError::Precompile)), + .. + } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!( + outcome.gas.gas_used + outcome.gas.reservoir_remaining, + gas_limit, + "the regular gas burned, the reservoir back" + ); + } +} + +/* ---------- the legacy engine's rows ---------- */ + +// The legacy engine halted a transaction a limit stopped, and gave back what detention withheld +// through a rescue of the remaining gas. Here the stop is a revert that settles like any EIP-8037 +// revert, and detention never moves gas out of a frame's tracker, so there is nothing to rescue. +// These rows keep the legacy scenarios and take their expectation from that rule. + +/// A gas limit whose reservoir pays the state and history gas of [`writes_past_the_cap`]'s fresh +/// slots at the prices in effect, so the writes spend nothing but compute from the frame's regular +/// gas. +fn roomy() -> u64 { + TX_GAS_LIMIT_CAP + slots_past_the_cap() * fresh_write_spill() + 100_000_000 +} + +/// The fresh slots these rows write after a read: one more than the cap's compute pays for, 1,653 +/// at the schedule's prices, so their compute is past the cap. +fn slots_past_the_cap() -> u64 { + CAP / fresh_write() + 1 +} + +/// Appends writes of the fresh slots `1..=`[`slots_past_the_cap`]: 20,011,218 of compute at the +/// schedule's prices, past the cap. +fn writes_past_the_cap(code: BytecodeBuilder) -> BytecodeBuilder { + (1..=slots_past_the_cap()) + .fold(code, |code, slot| code.sstore(U256::from(slot), U256::from(slot))) +} + +/// Appends a call to the Oracle with `gas`, dropping its status. The Oracle's code in these rows +/// reads its slot zero, which is the read of its storage detention caps. +fn call_oracle(code: BytecodeBuilder, gas: Option) -> BytecodeBuilder { + let code = + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]).push_address(ORACLE_CONTRACT_ADDRESS); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code.append_many([CALL, POP]) +} + +/// `db` with the Oracle's code a read of its slot zero. +fn with_oracle_read(db: MemoryDatabase) -> MemoryDatabase { + db.account_code( + ORACLE_CONTRACT_ADDRESS, + BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]).stop().build(), + ) +} + +/// Runs `db`'s `A` under `limits` with [`roomy`] gas and asserts the detention stop of the +/// transaction's own frame: a revert carrying `MegaLimitExceeded(2, limit)` for the limit the reads +/// set, billed the intrinsic gas plus the compute up to the charge that crosses that limit, `left` +/// short of it, and nothing of the gas the transaction had left. `A` crossed it, and ran the last +/// step: itself, or after a callee that crossed first returned the stop into it, on what the limit +/// left it. Returns the limit and what the transaction read. +fn assert_detention_stop( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + left: u64, +) -> (u64, mega_evm::VolatileDataAccess) { + let intrinsic = intrinsic(roomy()); + let (recorded, last) = + run_recording_steps(db.clone(), limits, call(CALLER, A, U256::ZERO, roomy())); + assert_eq!(last, Some(A), "the last step ran in the transaction's own frame"); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, roomy())).unwrap(); + assert_eq!( + (&recorded.result, recorded.gas), + (&outcome.result, outcome.gas), + "the recorder changes nothing" + ); + let detention = evm.ctx().detention(); + let limit = detention.compute_limit().expect("a read set a limit"); + let used = limit - left; + let stop = + LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, limit, used, frame_local: false }; + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "a revert carrying the stop: {:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, Some(stop)); + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + used); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + used); + assert_eq!(outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining); + assert!(outcome.result.logs().is_empty()); + (limit, detention.accessed()) +} + +/// The writes after a read: the read's `POP`, then the fresh slots, of which the reservoir pays the +/// state and history gas. +fn pop_then_writes() -> Charges { + Charges::default().then(&[2]).fresh_writes(slots_past_the_cap()) +} + +/// After the Oracle's read: its `POP`, its caller's, then the fresh slots. +fn oracle_pops_then_writes() -> Charges { + Charges::default().then(&[2, 2]).fresh_writes(slots_past_the_cap()) +} + +/// A frame that reads the block's timestamp and then writes the fresh slots stops at the +/// first write's charge past the limit the read set, and bills its compute before it: the +/// transaction's own frame, a child whose caller catches the stop and is held to what is left, +/// and a caller whose child did its work after the read. +#[test] +fn test_volatile_data_access_oog_does_not_consume_all_gas() { + let code = writes_past_the_cap(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + let left = pop_then_writes().left(CAP); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); + assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); +} + +/// A child that reads the block's timestamp and then writes the fresh slots is stopped at the +/// first write past the limit; its caller resumes on what the limit leaves it, and its own write +/// after the call crosses the limit again, which stops the transaction there. +#[test] +fn test_nested_call_block_env_access_child_oog() { + let child = writes_past_the_cap(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); + let parent = call_all(BytecodeBuilder::default(), B).append(POP).sstore(MARKER, U256::from(1)); + let db = MemoryDatabase::default() + .account_code(A, parent.stop().build()) + .account_code(B, child.stop().build()); + // The child's crossing, then the caller's `POP` and write, from the room the child's crossing + // charge was not made from. + let left = pop_then_writes().left(CAP); + let left = Charges::default().then(&[2]).fresh_writes(1).left(left); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); +} + +/// A frame that reads the block's timestamp, calls a child that does some work, then writes the +/// fresh slots stops at the limit its read set: the child's work counts towards it. +#[test] +fn test_parent_block_env_access_oog_after_nested_call() { + let child = + BytecodeBuilder::default().push_number(1_u8).push_number(2_u8).append(ADD).append(POP); + let parent = call_all(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), B).append(POP); + let db = MemoryDatabase::default() + .account_code(A, writes_past_the_cap(parent).stop().build()) + .account_code(B, child.stop().build()); + // The read's `POP`, the call's five pushes, its address, `GAS` and cold access, the child's + // two pushes, `ADD` and `POP`, the caller's `POP`, then the writes. + let left = Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 2, cold_access(), 3, 3, 3, 2, 2]) + .fresh_writes(slots_past_the_cap()) + .left(CAP); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); +} + +/// A call to the Oracle that reads its storage, then the fresh slots: the transaction stops +/// at the first write's charge past its compute at the read plus the Oracle's cap, the spec's +/// 20,000,000, and bills its compute before it. +#[test] +fn test_an_oracle_read_holds_the_transaction_to_its_cap() { + let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), None)); + let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert!(limit - ORACLE_ACCESS_COMPUTE_GAS < 10_000, "{}", limit - ORACLE_ACCESS_COMPUTE_GAS); + assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); +} + +/// The same with the Oracle called on 65,535 gas: the stop bills the compute, not the gas limit. +#[test] +fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { + let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), Some(0xffff))); + let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); +} + +/// A contract that calls one that reads the Oracle's storage and then writes the fresh slots: the +/// middle contract is stopped at the first write past the limit, and the outer contract resumes +/// on what the limit leaves it: its `POP`, then its read of its own slot, whose cold access crosses +/// the limit again and stops the transaction. +#[test] +fn test_parent_runs_out_of_gas_after_oracle_access() { + let middle = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), None)); + let outer = + call_all(BytecodeBuilder::default(), B).append(POP).append_many([PUSH0, SLOAD, POP]); + let db = MemoryDatabase::default() + .account_code(A, outer.stop().build()) + .account_code(B, middle.stop().build()); + // The middle contract's crossing, then the outer one's `POP`, `PUSH0` and cold `SLOAD`: its + // static gas, then the cold surcharge. + let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); + let params = mega_evm::satin_gas_params(); + let sload = [ + 2, + 2, + params.get(GasId::warm_storage_read_cost()), + params.get(GasId::cold_storage_additional_cost()), + 2, + ]; + let left = Charges::default().then(&sload).left(left); + let (_, accessed) = + assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), left); + assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); +} + +/// A read of the block's timestamp, then of the Oracle's storage under a lower cap: the most +/// restrictive limit binds, the Oracle's, and the stop bills the compute up to the charge that +/// crosses it. +#[test] +fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { + const ORACLE_CAP: u64 = 1_000_000; + let code = call_oracle(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), Some(0xffff)); + let db = MemoryDatabase::default().account_code(A, writes_past_the_cap(code).stop().build()); + let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); + let left = oracle_pops_then_writes().left(ORACLE_CAP); + let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, left); + assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); + assert_eq!( + accessed, + mega_evm::VolatileDataAccess::TIMESTAMP | mega_evm::VolatileDataAccess::ORACLE + ); +} + +/// A read of the block's timestamp, then compute past the cap: the stop comes at the work's first +/// charge past the compute at the read plus the cap. +#[test] +fn test_volatile_access_post_access_cap_enforced() { + let code = work(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), ROUNDS); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); + let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert!(limit - CAP < 1_000, "{}", limit - CAP); +} + +/// A read whose limit is past what the transaction's gas reaches does not bind: the frame runs out +/// of its own gas first, and that is an ordinary out-of-gas, which halts and burns the gas, not the +/// stop. Ten million of compute, the read, then sixteen million more, on 25,000,000 of gas. +#[test] +fn test_non_binding_detention_reports_a_normal_out_of_gas() { + use revm::context::result::HaltReason; + + let code = work(BytecodeBuilder::default(), 3_300).append_many([TIMESTAMP, POP]); + let db = MemoryDatabase::default().account_code(A, work(code, 5_200).stop().build()); + let gas_limit = 25_000_000; + let mut evm = MegaEvm::new(context(db)); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); + let limit = evm.ctx().detention().compute_limit().expect("the read set a limit"); + assert!(limit > gas_limit, "the read's limit is past the gas: {limit}"); + assert!( + matches!( + &outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.gas.gas_used, gas_limit, "an out-of-gas burns the gas"); +} + +/// A transaction that reads the beneficiary's balance with far more gas than the cap succeeds and +/// pays for what it ran, the same as with detention off: while it ran, its frame could spend only +/// the cap, and the rest was withheld, never spent. +#[test] +fn test_detained_gas_is_restored() { + /// The spendable and withheld parts of the frame's gas after each step. + #[derive(Default)] + struct Parts(Vec<(u64, u64)>); + impl Inspector, EthInterpreter> for Parts { + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + self.0.push((interp.gas.spendable(), interp.gas.withheld())); + } + } + + let code = BytecodeBuilder::default().push_address(BENEFICIARY).append_many([BALANCE, POP]); + let db = MemoryDatabase::default().account_code(A, code.stop().build()); + let tx = || call(CALLER, A, U256::ZERO, ABOVE); + let mut evm = MegaEvm::new(context(db.clone())).with_inspector(Parts::default()); + let detained = evm.execute_transaction(tx()).unwrap(); + assert_eq!(evm.ctx().detention().accessed(), mega_evm::VolatileDataAccess::BENEFICIARY_BALANCE); + let parts = &evm.inspector().0; + let (spendable, withheld) = parts[1]; + assert!(spendable <= CAP && withheld > TX_GAS_LIMIT_CAP - 2 * CAP, "after the read: {parts:?}"); + + let undetained = + MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .execute_transaction(tx()) + .unwrap(); + assert!(detained.result.is_success(), "{:?}", detained.result); + assert_eq!(detained.gas, undetained.gas, "the withheld gas was never spent"); + assert!( + detained.gas.gas_used < 50_000 + body_history(0), + "what it ran and its body's history: {}", + detained.gas.gas_used + ); +} + +/// A library's write, one call down, crosses a limit one byte above the body: the library is +/// stopped with a revert, which its caller catches before it ends, and the transaction is billed +/// what ran — its intrinsic gas, its body's history, the call, the library up to and including the +/// write, and the caller's `POP` — and nothing more: the unspent regular gas comes back to the +/// sender, and so does the state gas the write spilled onto it, which a revert gives back. +/// +/// What ran, below the execution cap, so the body's history is paid from the regular budget: +/// +/// | Part | Gas | +/// |---|---:| +/// | the call's intrinsic regular gas: the EIP-2780 base and the recipient | 15,000 | +/// | `A`'s five `PUSH0`, its `PUSH20` and its `GAS` | 15 | +/// | `A`'s `CALL`: the warm access and the cold surcharge for `B` | 3,000 | +/// | `B`'s `PUSH1` and `PUSH0` | 5 | +/// | `B`'s cold `SLOAD` | 2,100 | +/// | `B`'s `SSTORE` of the slot it warmed: static and the storage write | 10,100 | +/// | `A`'s `POP` of the call's status | 2 | +/// +/// Rules: [S11.8], [S11.9]. Independence: independent — the parts are written out; the body's +/// history is priced by the production helper. +#[test] +fn test_data_limit_exceed_in_nested_call() { + let limit = TX_BODY_SIZE + 1; + let library = BytecodeBuilder::default().push_number(1_u8).append_many([PUSH0, SLOAD, SSTORE]); + let db = MemoryDatabase::default() + .account_code(A, call_all(BytecodeBuilder::default(), B).append(POP).stop().build()) + .account_code(B, library.stop().build()); + let outcome = execute(db, EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit), BELOW); + assert!(outcome.result.is_success(), "the caller caught the stop: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + let ran = 15_000 + 15 + 3_000 + 5 + 2_100 + 10_100 + 2; + assert_eq!(outcome.gas.regular, ran, "what ran, on the regular ledger"); + assert_eq!(outcome.gas.history, body_history(0), "the body's history alone"); + assert_eq!(outcome.gas.state, 0, "the write's state gas came back"); + assert_eq!(outcome.gas.gas_used, ran + body_history(0), "and nothing more: the rest came back"); +} + +/// A value transfer to a contract that writes a slot, under a limit one byte above the body: the +/// first frame's start crosses it, so the value never moves and the contract never runs. +#[test] +fn test_state_revert_when_exceeding_limit() { + let db = MemoryDatabase::default() + .account_code(A, BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).build()) + .account_balance(CALLER, U256::from(10_000)); + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + 1), + )) + .execute_transaction(call(CALLER, A, U256::from(100), BELOW)) + .unwrap(); + let stop = outcome.limit_exceeded.expect("the transaction is stopped"); + assert!( + matches!( + stop, + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, frame_local: false, .. } + if limit == TX_BODY_SIZE + 1 + ), + "{stop:?}" + ); + assert!( + matches!(&outcome.result, ExecutionResult::Revert { output, .. } + if output == &stop.revert_data()), + "{:?}", + outcome.result + ); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert!(outcome.state.get(&A).is_none_or(|a| a.storage.is_empty() && a.info.balance.is_zero())); + assert_eq!(outcome.state[&CALLER].info.balance, U256::from(10_000), "the value did not move"); +} + +/// A transaction detained from its start — its sender is the block's beneficiary — whose body +/// crosses the data-size limit is rejected at validation, as the same transaction undetained is: +/// detention changes nothing about what validation refuses. +#[test] +fn test_detention_plus_intrinsic_data_size_overflow() { + let db = + || MemoryDatabase::default().account_code(A, BytecodeBuilder::default().stop().build()); + let run = |limits, sender| { + MegaEvm::new(context(db()).with_tx_runtime_limits(limits)).execute_transaction(call( + sender, + A, + U256::ZERO, + roomy(), + )) + }; + let mut evm = MegaEvm::new(context(db())); + let within_limits = evm.execute_transaction(call(BENEFICIARY, A, U256::ZERO, roomy())).unwrap(); + assert_eq!(evm.ctx().detention().compute_limit(), Some(CAP), "detained from its start"); + assert!(within_limits.result.is_success(), "{:?}", within_limits.result); + + let over = EvmTxRuntimeLimits::default().with_tx_data_size_limit(100); + let detained = run(over, BENEFICIARY).expect_err("rejected"); + let undetained = run(over, CALLER).expect_err("rejected"); + assert!(format!("{detained:?}").contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT)); + assert_eq!(format!("{detained:?}"), format!("{undetained:?}")); +} + +/// A call a data-size limit stopped — its own frame budget, or the transaction's limit — revived +/// into a success by an inspector, hands its caller nothing it counted: its checkpoint was reverted +/// before the inspector saw its result, so its log is not kept, and its lane goes the way its log +/// did. Its caller runs on within the limits, and the transaction is the one no inspector runs: the +/// rewrite changed only the flag `A` drops. +/// +/// Under a frame cap of 1,000 bytes `A` gives `B` 98% of it, and `B`'s log of 1,000 bytes counts +/// 1,032, which crosses `B`'s budget, and would cross `A`'s were it handed on. Under a transaction +/// limit of the body and 1,000 bytes the same log crosses the transaction's limit, which is checked +/// first. +#[test] +fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { + const CAP: u64 = 1_000; + const LOGGED: u64 = 1_000; + const { assert!(LOG_BASE_SIZE + LOGGED > CAP, "the log would cross A's budget too") }; + let share = CAP * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let a = call_all(BytecodeBuilder::default(), B) + .append(POP) + .sstore(MARKER, U256::from(1)) + .stop() + .build(); + let b = + BytecodeBuilder::default().push_number(LOGGED).append_many([PUSH0, LOG0]).stop().build(); + let db = MemoryDatabase::default().account_code(A, a).account_code(B, b); + let unlimited = EvmTxRuntimeLimits::no_limits(); + let rows = [ + ("its frame budget", unlimited.with_frame_data_size_limit(CAP), share), + ("the transaction's limit", unlimited.with_tx_data_size_limit(TX_BODY_SIZE + CAP), { + TX_BODY_SIZE + CAP + }), + ]; + for (row, limits, crossed) in rows { + let plain = execute(db.clone(), limits, BELOW); + let mut evm = MegaEvm::new(context(db.clone()).with_tx_runtime_limits(limits)) + .with_inspector(FrameRecorder::rewriting()); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, BELOW)).unwrap(); + let rewriter = evm.inspector(); + + // The revert data names the limit crossed, whatever the usage. + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: crossed, + used: 0, + frame_local: false, + }; + assert_eq!( + rewriter.ended, + vec![ + (B, InstructionResult::Revert, stop.revert_data()), + (A, InstructionResult::Stop, Bytes::new()) + ], + "{row}: B crossed it; A did not" + ); + assert_eq!(rewriter.marker_writes(), 1, "{row}: A ran on after its call returned"); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{row}: a stop below is no stop"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + "{row}: the body and A's marker: none of B's log" + ); + assert!(outcome.result.logs().is_empty(), "{row}: B's log was reverted with B"); + assert!(plain.result.is_success(), "{row}: {:?}", plain.result); + assert_eq!((&outcome.result, &outcome.state), (&plain.result, &plain.state), "{row}"); + assert_eq!((outcome.gas, outcome.usage), (plain.gas, plain.usage), "{row}"); + } +} + +/* ---------- a frame three calls down, answered without running ---------- */ + +/// An account with nothing at it, which a value call adds. +const EMPTY: Address = address!("0000000000000000000000000000000000500005"); + +/// A frame three calls down answered without running, whose answer crosses a limit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Answered { + /// An inspector answers the call to `D` having spent all it was forwarded, past what the + /// compute limit leaves the frame. An interceptor's answer is settled the same way; none of + /// this engine's interceptors spends gas. + PastTheAllowance, + /// `C` calls a precompile priced past the cap, which revm runs on the allowance: it runs out + /// of it without computing. + Precompile, + /// `C` sends a wei to [`EMPTY`], whose start's records and transfer log cross the data-size + /// limit, before revm builds the frame. + StartRecords, +} + +impl Answered { + /// The address the answered call is made to. + const fn target(self) -> Address { + match self { + Self::PastTheAllowance => D, + Self::Precompile => PRICED, + Self::StartRecords => EMPTY, + } + } +} + +/// The chain `A` → `B` → `C` → the answered frame. `A` reads the block's timestamp first, which +/// detains the transaction under the default limits. Each frame calls the next with all its gas, +/// and `C` makes the answered call; then every frame drops the call's status and stops. +fn answered_chain(answered: Answered) -> MemoryDatabase { + let end = |code: BytecodeBuilder| code.append(POP).stop().build(); + let c = match answered { + Answered::PastTheAllowance => call_all(BytecodeBuilder::default(), D), + Answered::Precompile => BytecodeBuilder::default() + .mstore(0, U256::from(CAP + 1).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .append_many([PUSH0, PUSH0]) + .push_address(PRICED) + .append_many([GAS, CALL]), + Answered::StartRecords => BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(EMPTY) + .append_many([GAS, CALL]), + }; + MemoryDatabase::default() + .account_code(A, end(call_all(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), B))) + .account_code(B, end(call_all(BytecodeBuilder::default(), C))) + .account_code(C, end(c)) + .account_code(D, BytecodeBuilder::default().stop().build()) + .account_balance(C, U256::from(1)) +} + +/// The compute `answered`'s chain spends after `A`'s read up to the answered call: `A`'s `POP`, +/// then the three calls down — five pushes, the address, `GAS` and the callee's cold access — +/// `C`'s own being, for the precompile, the price word's `MSTORE` — two pushes, the opcode and a +/// word of memory — the call's five pushes, its address, `GAS` and the precompile's warm access. +fn to_the_answer(answered: Answered) -> u64 { + let call_all = 2 * 5 + 3 + 2 + cold_access(); + let c = match answered { + Answered::Precompile => 3 + 3 + 3 + 3 + 2 * 2 + 3 + 2 * 2 + 3 + 2 + 100, + _ => call_all, + }; + 2 + 2 * call_all + c +} + +/// The limits `answered`'s chain crosses its limit under, and the stop the answered frame returns. +/// The compute limit is set by `A`'s read, at the read's own two gas plus the cap, and the answer +/// is the charge that crosses it: the stop reports the compute when the answered call was made. +fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { + let stop = + |kind, limit, used| LimitCheck::ExceedsLimit { kind, limit, used, frame_local: false }; + match answered { + Answered::PastTheAllowance | Answered::Precompile => ( + EvmTxRuntimeLimits::default(), + stop(LimitKind::ComputeGas, 2 + CAP, 2 + to_the_answer(answered)), + ), + Answered::StartRecords => { + // The body, and one byte short of the start's two records and its transfer log. + let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + ( + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + stop(LimitKind::DataSize, limit, limit + 1), + ) + } + } +} + +/// Answers every call to `D` itself, having spent all the gas it was forwarded, and records every +/// frame it sees end, deepest first, with the result and output it had; with `rewrite`, it then +/// rewrites that result into a success, as [`FrameRecorder`] does. +struct AnswersD { + rewrite: bool, + ended: Vec<(Address, InstructionResult, Bytes)>, +} + +impl Inspector, EthInterpreter> for AnswersD { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + (inputs.target_address == D).then(|| { + let mut gas = + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + gas.spend_all(); + CallOutcome::new( + InterpreterResult::new(InstructionResult::Stop, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } + + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + let result = &mut outcome.result; + self.ended.push((inputs.target_address, result.result, result.output.clone())); + if self.rewrite { + result.result = InstructionResult::Stop; + result.output = Bytes::new(); + } + } +} + +/// A run of an answered chain: its outcome, the frames an inspector saw end, and what the +/// precompile at [`PRICED`] ran on, each with whether its price was within it. +struct AnsweredRun { + outcome: MegaTransactionOutcome, + ended: Vec<(Address, InstructionResult, Bytes)>, + ran_on: Vec<(u64, bool)>, +} + +/// Runs the stopped chain of `answered` under `limits` at `gas_limit`, with the precompile at +/// [`PRICED`] installed. Without `rewrite` it runs without an inspector — an answer past the +/// allowance under one that answers `D` and rewrites nothing — and with `rewrite` under one that +/// rewrites every frame result into a success. +fn run_answered( + answered: Answered, + limits: EvmTxRuntimeLimits, + gas_limit: u64, + rewrite: bool, +) -> AnsweredRun { + let runs = Runs::default(); + let evm = MegaEvm::new(context(answered_chain(answered)).with_tx_runtime_limits(limits)) + .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])); + let tx = call(CALLER, A, U256::ZERO, gas_limit); + let (outcome, ended) = if answered == Answered::PastTheAllowance { + let mut evm = evm.with_inspector(AnswersD { rewrite, ended: Vec::new() }); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + (outcome, evm.inspector().ended.clone()) + } else if rewrite { + let mut evm = evm.with_inspector(FrameRecorder::rewriting()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + (outcome, evm.inspector().ended.clone()) + } else { + let mut evm = evm; + (evm.execute_transaction(tx).expect("the transaction is valid"), Vec::new()) + }; + let ran_on = runs.lock().unwrap().clone(); + AnsweredRun { outcome, ended, ran_on } +} + +/// One answered cell, both columns: `answered`'s chain at `gas_limit`, without the rewrite and +/// with it. +/// +/// The answered frame is the stop, which `C` catches, and every frame then drops the status and +/// stops: the transaction succeeds. A compute stop bills its compute up to the answer past the +/// intrinsic gas, then the three callers' `POP`s. A start's stop bills what the same chain bills +/// without limits, where the start is made: the callers pay the call the same either way, and the +/// start's records and the account it would add are history and state gas, which its stop gives +/// back. That run is on the same engine, so its bill pins that a stop bills what ran and no more; +/// it pins no price, and a charge both runs make, such as `C`'s own `CALL`, would be wrong in both +/// alike. +fn assert_answered_cell(answered: Answered, gas_limit: u64) { + let row = format!("{answered:?}, gas limit {gas_limit}"); + let intrinsic = intrinsic(gas_limit); + let (limits, stop) = answered_limits(answered); + let LimitCheck::ExceedsLimit { kind, used, .. } = stop else { unreachable!() }; + let ran = if kind == LimitKind::ComputeGas { + used + 3 * 2 + } else { + let free = execute(answered_chain(answered), EvmTxRuntimeLimits::no_limits(), gas_limit); + assert!(free.result.is_success(), "{row}: without limits: {:?}", free.result); + assert_eq!(balance_of(&free, EMPTY), U256::from(1), "{row}: the start moves its wei"); + free.gas.regular - intrinsic.gas.regular + }; + + let plain = run_answered(answered, limits, gas_limit, false); + let rewritten = run_answered(answered, limits, gas_limit, true); + for (column, run) in [("not rewritten", &plain), ("rewritten", &rewritten)] { + let cell = format!("{row}, {column}"); + let outcome = &run.outcome; + assert!(outcome.result.is_success(), "{cell}: the callers caught the stop"); + assert_eq!(outcome.limit_exceeded, None, "{cell}: a stop below is no stop of it"); + assert_eq!(outcome.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); + assert_eq!(outcome.gas.state, 0, "{cell}: the stop keeps no state gas"); + assert_eq!(outcome.gas.history, intrinsic.gas.history, "{cell}: the body's history alone"); + assert_eq!(outcome.gas.history_bytes, intrinsic.gas.history_bytes, "{cell}"); + assert_eq!( + outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, + "{cell}: the reservoir comes back, less the body it paid" + ); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran, "{cell}: gas used"); + assert!(outcome.result.logs().is_empty(), "{cell}: no log is kept"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + "{cell}: the body stays" + ); + assert_eq!(balance_of(outcome, EMPTY), U256::ZERO, "{cell}: no value moved"); + if answered == Answered::Precompile { + let allowance = CAP - to_the_answer(answered); + assert_eq!(run.ran_on, [(allowance, false)], "{cell}: run on the allowance"); + } + } + assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); + assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + let ended = vec![ + (answered.target(), InstructionResult::Revert, stop.revert_data()), + (C, InstructionResult::Stop, Bytes::new()), + (B, InstructionResult::Stop, Bytes::new()), + (A, InstructionResult::Stop, Bytes::new()), + ]; + assert_eq!( + rewritten.ended, ended, + "{row}: the answered frame ended stopped, then every caller ended" + ); + if answered == Answered::PastTheAllowance { + // Its answer is an inspector's, which in this column rewrites nothing. + assert_eq!( + plain.ended, ended, + "{row}, not rewritten: the answered frame ended stopped, then every caller ended" + ); + } +} + +/// The balance `address` holds after `outcome`: zero for an account it did not touch. +fn balance_of(outcome: &MegaTransactionOutcome, address: Address) -> U256 { + outcome.state.get(&address).map(|account| account.info.balance).unwrap_or_default() +} + +/// A frame three calls down that is answered without running, and whose answer crosses a limit, is +/// the stop as a frame that ran there would be: an answer past what the compute limit leaves the +/// frame, and a precompile run on that allowance and priced past it. Below the execution cap and +/// above it, with and without an inspector that rewrites every frame result into a success, the +/// answer is the stop, its caller catches it, every frame ends, and the transaction bills what +/// ran, keeps the body's history and nothing else, and gets its reservoir back. +#[test] +fn test_an_answer_three_calls_down_is_the_stop_its_caller_catches_at_either_tier() { + for answered in [Answered::PastTheAllowance, Answered::Precompile] { + for gas_limit in TIERS { + assert_answered_cell(answered, gas_limit); + } + } +} + +/// A frame three calls down whose start's records and transfer log cross the data-size limit is +/// answered with the stop before revm builds it: no value moves and no account is added. Its +/// caller catches the stop, below the execution cap and above it, with and without the rewriting +/// inspector. +#[test] +fn test_a_start_three_calls_down_crossing_the_limit_is_stopped_before_it_is_built() { + for gas_limit in TIERS { + assert_answered_cell(Answered::StartRecords, gas_limit); + } +} diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/storage_call_stipend.rs new file mode 100644 index 000000000..0629017e7 --- /dev/null +++ b/crates/mega-evm/tests/satin/storage_call_stipend.rs @@ -0,0 +1,798 @@ +//! The history allowance a value-transferring call grants its callee, and the three ways it must +//! not leak. +//! +//! EVM's own `CALL_STIPEND` buys the recipient of a transfer enough computation to notice it. +//! On a chain that prices the bytes a log appends it buys no log at all, so a `receive()` hook +//! that emits an event would be unreachable through Solidity's `transfer()`. The allowance is +//! that stipend's counterpart on the history ledger: 160 bytes — one three-topic event carrying +//! one word — at the cost per history byte, and nothing more. +//! +//! What makes it safe is that it is not gas. It never enters the frame's `Gas`, so no settlement +//! can hand it back; it pays history charges and only those, so it cannot buy computation or a +//! write record; and it belongs to the frame it was granted to, so a frame answered without +//! running neither takes one nor leaves one behind. The three leak paths below are the three +//! places where a frame's allowance could escape the frame: an interceptor answering in its +//! place, a transaction-level stop unwinding it, and the frame returning to its caller. +//! +//! The transfer log a value call leaves is not the callee's event and draws nothing from the +//! allowance: it costs no history at all, so the event still has the whole allowance to itself. +//! The events below are counted apart from it. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::COST_PER_HISTORY_BYTE, + storage_call_stipend, + system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, + test_utils::{ + is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, + }, + EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, + STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::bytecode::opcode::{ + ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, + POP, PUSH0, PUSH1, PUSH2, SSTORE, STATICCALL, STOP, SUB, SWAP1, +}; + +use crate::common::{ + body_history, call, context, execute, history, runs_at_measurement_prices, slot_state_gas, + state_is_free, +}; + +const CALLER: Address = address!("0000000000000000000000000000000000500000"); +const SENDER: Address = address!("0000000000000000000000000000000000500001"); +const RECEIVER: Address = address!("0000000000000000000000000000000000500002"); + +const GAS_LIMIT: u64 = 30_000_000; + +/// What Solidity's `transfer()` forwards: the EVM's own `CALL_STIPEND` and not one gas more. +const TRANSFER_GAS: u64 = 2_300; + +/// The history a transaction's body costs, which every transaction here pays. +const fn body() -> u64 { + TX_BODY_SIZE * COST_PER_HISTORY_BYTE +} + +/// The history one write record costs. +const fn record() -> u64 { + WRITE_RECORD_SIZE * COST_PER_HISTORY_BYTE +} + +/// A three-topic event over one word of memory, the event the allowance is sized for. +fn event() -> BytecodeBuilder { + BytecodeBuilder::default() + .push_number(1u64) + .push_number(2u64) + .push_number(3u64) + .push_number(32u64) + .push_number(0u64) + .append(LOG3) +} + +/// `scheme(gas, target, value, 0, 0, 0, 0); POP`, followed by whatever comes next. +/// +/// `DELEGATECALL` and `STATICCALL` take no value word at all, so the stack they are given is one +/// shorter. +fn call_with(scheme: u8, target: Address, value: u64, gas: u64) -> BytecodeBuilder { + let empty_args = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let code = if matches!(scheme, DELEGATECALL | STATICCALL) { + empty_args + } else { + empty_args.push_number(value) + }; + code.push_address(target).push_number(gas).append(scheme).append(POP) +} + +fn db(sender_code: Bytes, receiver_code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(SENDER, U256::from(10u64.pow(9))) + .account_code(SENDER, sender_code) + .account_balance(RECEIVER, U256::from(1)) + .account_code(RECEIVER, receiver_code) +} + +/// The events the contracts emitted: the logs without the transfer logs of the value moved. +fn events(outcome: &MegaTransactionOutcome) -> Vec<&alloy_primitives::Log> { + outcome.result.logs().iter().filter(|log| !is_transfer_log(log)).collect() +} + +fn run_limited( + db: MemoryDatabase, + limits: EvmTxRuntimeLimits, + tx: MegaTransaction, +) -> MegaTransactionOutcome { + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid") +} + +/* ---------- what the allowance is, and what it buys ---------- */ + +/// The allowance is one three-topic event carrying a word, at the price of a history byte. +#[test] +fn test_the_allowance_is_one_three_topic_event_of_history() { + if runs_at_measurement_prices() { + return; + } + assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); + assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); +} + +/// The boundary the allowance exists for: a `transfer()` — 2,300 gas and nothing else — reaches a +/// `receive()` hook that emits one event, and the event's history costs the sender nothing beyond +/// the two write records the transfer itself writes. +/// +/// Without the allowance the event's 160 bytes would have to come out of the 2,300, which does +/// not cover them at any price a history byte is worth. +#[test] +fn test_a_transfer_can_emit_one_event_because_of_the_allowance() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let receiver = event().append(STOP).build(); + let outcome = execute(db(sender, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); + assert_eq!( + outcome.result.logs()[0], + transfer_log(SENDER, RECEIVER, U256::from(1)), + "after the transfer's own log, which took nothing from the allowance", + ); + assert_eq!( + outcome.gas.history, + body() + 2 * record(), + "the body and the transfer's two records; the event's bytes the allowance paid for", + ); +} + +/// One event is all it buys: a second one has to come out of the 2,300 gas, which cannot cover +/// it, so the hook runs out of gas and the transfer fails. +#[test] +fn test_the_allowance_buys_one_event_and_no_more() { + if runs_at_measurement_prices() { + return; + } + // The caller records whether the transfer succeeded, then stops. + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let two_events = event().append_many(event().build().iter().copied()).append(STOP).build(); + let outcome = execute(db(sender, two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "the caller survives the hook's failure"); + assert!(outcome.result.logs().is_empty(), "the hook ran out and kept neither event"); + assert_eq!(outcome.gas.history, body(), "and the transfer's records came back with it"); +} + +/// A sender that makes one value transfer to [`RECEIVER`], forwarding `gas` beside the 2,300 the +/// transfer's stipend adds, and returns the call's success flag. +fn transfer_returning_its_flag(gas: u64) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1u64) + .push_address(RECEIVER) + .push_number(gas) + .append(CALL) + .return_top() + .build() +} + +/// Whether the transfer of [`transfer_returning_its_flag`] succeeded, read off the sender's output. +fn transfer_succeeded(outcome: &MegaTransactionOutcome) -> bool { + assert!(outcome.result.is_success(), "the sender survives its hook: {:?}", outcome.result); + let output = outcome.result.output().expect("the sender returns the flag"); + U256::from_be_slice(output) == U256::from(1) +} + +/// A hook of `gas` gas in all — the forward and the transfer's stipend — running `hook`, with +/// `slot_zero` already in its slot 0. +fn run_hook(hook: Bytes, gas: u64, slot_zero: U256) -> MegaTransactionOutcome { + let forward = gas.checked_sub(TRANSFER_GAS).expect("the hook gets at least the stipend"); + let db = db(transfer_returning_its_flag(forward), hook).account_storage( + RECEIVER, + U256::ZERO, + slot_zero, + ); + execute(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) +} + +/// A hook that counts `n` down to zero and stops: `PUSH2 n`, then `n` turns of `JUMPDEST; PUSH1 1; +/// SWAP1; SUB; DUP1; PUSH1 3; JUMPI`. +fn countdown(n: u16) -> Bytes { + let [high, low] = n.to_be_bytes(); + Bytes::from(vec![PUSH2, high, low, JUMPDEST, PUSH1, 1, SWAP1, SUB, DUP1, PUSH1, 3, JUMPI, STOP]) +} + +/// What [`countdown`] costs, by hand from the Osaka opcode prices: `PUSH2` 3, and per turn +/// `JUMPDEST` 1, `PUSH1` 3, `SWAP1` 3, `SUB` 3, `DUP1` 3, `PUSH1` 3 and `JUMPI` 10. +const fn countdown_gas(n: u64) -> u64 { + 3 + 26 * n +} + +/// The history gas of one write record at the prices in effect, by hand: its 40 bytes at the cost +/// per history byte, 3,520 gas at the spec's price. +fn record_history() -> u64 { + history(WRITE_RECORD_SIZE) +} + +/// The allowance at the prices in effect, by hand: the spec's 160 bytes at the cost per history +/// byte, 14,080 gas at the spec's price. +fn allowance() -> u64 { + history(160) +} + +/// Whether the allowance is worth more than a write record at the prices in effect, which each of +/// the three tests below needs to see the leak it guards against: an allowance of nothing has +/// nothing to leak, a record whose history is nothing has no charge the allowance could pay, and +/// a leaked allowance that a record outweighs could not carry a hook past that record. The 160 +/// bytes are four records' 40, so any price of a gas or more a byte holds it; a history byte +/// priced at nothing, or at a fraction of a gas that rounds a record to nothing, does not, and the +/// test returns early with a note. +fn the_allowance_outweighs_a_record() -> bool { + if record_history() > 0 && allowance() > record_history() { + return true; + } + note_price_guard("the allowance is worth no more than a write record at these prices"); + false +} + +/// The allowance cannot pay for computation: a hook given one gas less than its computation costs +/// runs out of gas, though the allowance beside it would cover that gas many times over, and given +/// exactly the cost it completes. An allowance that entered the frame's gas, or that computation +/// could fall back on, would carry the short hook through. +/// +/// Rule [S8.4]. Expected values `independent`: the hook's cost is summed by hand from the opcode +/// prices, which no byte price moves, and the exact run is the control that the sum is the hook's +/// whole cost; the allowance and a record's history are the spec's 160 and 40 bytes at the cost +/// per history byte in effect (`constants`), and at the spec's prices 14,080 and 3,520, written +/// out. +#[test] +fn test_the_allowance_cannot_be_spent_on_computation() { + if !the_allowance_outweighs_a_record() { + return; + } + assert_eq!(storage_call_stipend(), allowance(), "the allowance the engine grants"); + let turns: u16 = 200; + let cost = countdown_gas(u64::from(turns)); + + let short = run_hook(countdown(turns), cost - 1, U256::ZERO); + assert!(!transfer_succeeded(&short), "one gas short of the computation is out of gas"); + assert_eq!(short.gas.history, body_history(0), "the failed hook's transfer records came back"); + + let exact = run_hook(countdown(turns), cost, U256::ZERO); + assert!(transfer_succeeded(&exact), "the computation's own cost is enough"); + assert_eq!( + exact.gas.history, + body_history(0) + 2 * record_history(), + "the transfer's two records" + ); + + if runs_at_measurement_prices() { + return; + } + assert_eq!((allowance(), record_history()), (14_080, 3_520), "160 and 40 bytes at 88 gas"); +} + +/// The hook's `SSTORE(0, 2)`: `PUSH1 2; PUSH0; SSTORE; STOP`. +fn writes_slot_zero() -> Bytes { + Bytes::from(vec![PUSH1, 2, PUSH0, SSTORE, STOP]) +} + +/// The allowance cannot pay a write record: a hook that changes a slot it already holds, given the +/// write's regular gas and one gas less than its record's history, runs out of gas and keeps no +/// write, though the allowance beside it would cover the record four times over. Given the record +/// in full it keeps the write. +/// +/// The slot is not fresh, so the write charges no state gas: the record's history is the only +/// charge past the regular gas, and the only one the allowance could have paid. +/// +/// Rule [S8.3]. Expected values `independent`: the write's regular gas is the schedule's table by +/// hand — `PUSH1` 3, `PUSH0` 2, and an `SSTORE` that resets a cold slot, 100 static, 10,000 for +/// the reset and 2,000 for the cold load — which no byte price moves; the record's history is 40 +/// bytes at the cost per history byte in effect (`constants`), 3,520 at 88 gas a byte, written +/// out. +#[test] +fn test_the_allowance_cannot_be_spent_on_a_write_record() { + if !the_allowance_outweighs_a_record() { + return; + } + let record = record_history(); + assert_eq!(mega_evm::write_record_history_gas(1), Some(record), "the record the engine prices"); + let regular = 3 + 2 + 100 + 10_000 + 2_000; + + let short = run_hook(writes_slot_zero(), regular + record - 1, U256::from(1)); + assert!(!transfer_succeeded(&short), "one gas short of the record is out of gas"); + assert_eq!(short.usage.write_records, 0, "the hook kept no write"); + assert_eq!(short.gas.history, body_history(0), "and the transfer's records came back with it"); + + let exact = run_hook(writes_slot_zero(), regular + record, U256::from(1)); + assert!(transfer_succeeded(&exact), "the record paid from the hook's own gas"); + assert_eq!(exact.usage.write_records, 3, "the transfer's two accounts and the slot"); + assert_eq!(exact.gas.history, body_history(0) + 3 * record); + + if runs_at_measurement_prices() { + return; + } + assert_eq!(record, 3_520, "40 bytes at 88 gas"); +} + +/// The allowance cannot pay state gas either: a hook that fills a fresh slot, given the write's +/// regular gas and one gas less than the slot's state gas, runs out of gas and keeps no write. +/// An allowance that paid the state gas would carry it through: drawn first, it would pay the +/// smaller of the state gas and itself, and leave the hook that much less one gas of its own to +/// pay the record's history with. Given the state gas and the record in full it keeps the write. +/// +/// So the leak shows only where both the slot's state gas and the allowance outweigh a record. +/// At a price where the state gas does not — a gas or so a state byte against a dear history +/// byte — the short hook would run out on the record whether or not the allowance paid its state +/// gas, and the test returns early with a note. +/// +/// Rule [S8.5]. Expected values `independent`: the write's regular gas is the schedule's table by +/// hand — `PUSH1` 3, `PUSH0` 2, and an `SSTORE` that fills a cold fresh slot, 100 static, 10,000 +/// for the fresh slot and 2,000 for the cold load — which no byte price moves; the slot's state +/// gas at the minimum bucket is the schedule's entry and the record's history 40 bytes at the cost +/// per history byte, both at the prices in effect (`constants`), and at the spec's prices 97,920 +/// and 3,520, written out. +#[test] +fn test_the_allowance_cannot_be_spent_on_state() { + // A slot that costs no state gas has no state charge the allowance could pay. + if state_is_free() || !the_allowance_outweighs_a_record() { + return; + } + let state = slot_state_gas(); + let record = record_history(); + // A leaked allowance leaves the short hook `min(state, allowance) - 1` of its own gas for the + // record, which must cover it for the leak to show. + if state.min(allowance()) - 1 < record { + note_price_guard( + "the slot's state gas is worth no more than a write record at these prices", + ); + return; + } + let regular = 3 + 2 + 100 + 10_000 + 2_000; + + let short = run_hook(writes_slot_zero(), regular + state - 1, U256::ZERO); + assert!(!transfer_succeeded(&short), "one gas short of the state gas is out of gas"); + assert_eq!(short.usage.write_records, 0, "the hook kept no write"); + assert_eq!(short.gas.state, 0, "and no state gas"); + + let exact = run_hook(writes_slot_zero(), regular + state + record, U256::ZERO); + assert!(transfer_succeeded(&exact), "the slot paid from the hook's own gas"); + assert_eq!(exact.gas.state, state); + assert_eq!(exact.usage.write_records, 3, "the transfer's two accounts and the slot"); + + if runs_at_measurement_prices() { + return; + } + assert_eq!((state, record), (97_920, 3_520), "64 bytes at 1,530 gas, 40 bytes at 88 gas"); +} + +/* ---------- who is granted one ---------- */ + +/// A transaction's own frame is granted nothing: its sender chose the gas limit, so a value +/// transaction whose recipient emits an event pays for that event itself. +#[test] +fn test_a_top_level_transfer_gets_no_allowance() { + if runs_at_measurement_prices() { + return; + } + let receiver = event().append(STOP).build(); + let mut tx = call(CALLER, RECEIVER, U256::from(1), GAS_LIMIT); + tx.0.base.value = U256::from(1); + let outcome = execute(db(Bytes::new(), receiver), tx); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.history, + body() + record() + STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE, + "the body, the recipient's record, and the event the transaction paid for itself", + ); +} + +/// A call that carries no value is granted nothing, whatever it forwards: the allowance follows +/// the transfer, not the call. +#[test] +fn test_a_call_without_value_gets_no_allowance() { + if runs_at_measurement_prices() { + return; + } + let receiver = event().append(STOP).build(); + let with_value = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); + let without = call_with(CALL, RECEIVER, 0, 1_000_000).append(STOP).build(); + let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + + let paid = execute(db(without, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + let granted = execute(db(with_value, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(paid.result.is_success() && granted.result.is_success()); + assert_eq!(paid.gas.history, body() + event_history, "no transfer, no allowance"); + assert_eq!(granted.gas.history, body() + 2 * record(), "the allowance paid for the event"); +} + +/// `CALLCODE` transfers value and is granted one; `DELEGATECALL` carries none and is not. +/// `CALLCODE` runs the callee's code in the caller's own account, so its transfer writes one +/// account rather than two. +/// +/// `STATICCALL` carries no value either, and a static frame may not emit a log at all, so there +/// is nothing an allowance could buy it. +#[test] +fn test_callcode_is_granted_one_and_delegatecall_is_not() { + if runs_at_measurement_prices() { + return; + } + let receiver = event().append(STOP).build(); + let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + let at = |scheme, value| { + let sender = call_with(scheme, RECEIVER, value, 1_000_000).append(STOP).build(); + execute(db(sender, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) + }; + + let call_code = at(CALLCODE, 1); + assert!(call_code.result.is_success(), "{:?}", call_code.result); + assert_eq!(call_code.gas.history, body() + record(), "one record, and the allowance paid"); + + let delegate = at(DELEGATECALL, 0); + assert!(delegate.result.is_success(), "{:?}", delegate.result); + assert_eq!( + delegate.gas.history, + body() + event_history, + "no value, no allowance, so the frame pays for its own event", + ); +} + +/* ---------- the three leak paths ---------- */ + +/// A value call a system contract's interceptor answers neither takes the caller's allowance nor +/// leaves one behind: the answer is a frame that never ran, and the allowance stack stays aligned +/// with the frames. +/// +/// The receiver calls `MegaAccessControl`, whose interceptor answers it without a frame, and then +/// emits its one event. It is forwarded far less gas than the event's history costs, so the event +/// is affordable only out of the allowance: if the answer had taken the receiver's allowance the +/// event would be unaffordable, and if it had left a second one behind, a second event would be +/// free. +#[test] +fn test_an_intercepted_call_neither_takes_nor_adds_an_allowance() { + if runs_at_measurement_prices() { + return; + } + // The intercepted call, then one event; the second program adds a second event after it. + let intercepted_then_event = || { + BytecodeBuilder::default() + .mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append(PUSH0) + .push_address(ACCESS_CONTROL_ADDRESS) + .append(GAS) + .append(STATICCALL) + .append(POP) + .append_many(event().build().iter().copied()) + }; + let one_event = intercepted_then_event().append(STOP).build(); + let two_events = + intercepted_then_event().append_many(event().build().iter().copied()).append(STOP).build(); + + // Enough for the intercepted call and the event's computation, and far below the event's + // history, which only the allowance can cover. + const FORWARDED: u64 = 8_000; + assert!(FORWARDED < storage_call_stipend(), "the event's history must need the allowance"); + let sender = call_with(CALL, RECEIVER, 1, FORWARDED).append(STOP).build(); + let with_controls = |receiver: Bytes| { + db(sender.clone(), receiver) + .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + }; + + let one = execute(with_controls(one_event), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + assert!(one.result.is_success(), "{:?}", one.result); + assert_eq!(events(&one).len(), 1, "the receiver still had its allowance"); + assert_eq!(one.gas.history, body() + 2 * record(), "the refusal cost no history"); + + let two = execute(with_controls(two_events), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + assert!(two.result.is_success(), "the caller survives"); + assert!(two.result.logs().is_empty(), "the refusal left no second allowance behind"); +} + +/// A transaction-level stop hands the allowance back to nobody: it was never gas, so the unwind +/// that returns a stopped transaction's regular gas and its reservoir has nothing of it to +/// return. +/// +/// Both transactions below are stopped at the same instruction — the sender's own event, whose +/// thousand bytes cross the transaction's data-size limit on their own — and differ in one thing: +/// one receiver spent its whole allowance on an event, the other spent none of it. The reservoir +/// the stop gives back is the same to the gas; an allowance that unwound into it would leave the +/// spender with a whole allowance more. What the spender does pay beyond the other is the event's +/// computation, which is nothing like what its history costs. +#[test] +fn test_a_transaction_level_stop_does_not_hand_the_allowance_back() { + if runs_at_measurement_prices() { + return; + } + // Above the execution cap, so the transaction has a reservoir for the stop to give back. + let gas_limit = mega_evm::constants::TX_GAS_LIMIT_CAP + 50_000_000; + // The sender's own event is larger than this on its own, so it crosses whatever the receiver + // appended before it. + // 400 bytes above the body: the receiver's event fits, and the sender's log crosses. + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + 400); + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS) + .push_number(1u64) + .push_number(2u64) + .push_number(3u64) + .push_number(1_000u64) + .push_number(0u64) + .append(LOG3) + .append(STOP) + .build(); + let stop_with = |receiver: Bytes| { + let outcome = run_limited( + db(sender.clone(), receiver), + limits, + call(CALLER, SENDER, U256::ZERO, gas_limit), + ); + assert!( + matches!( + outcome.limit_exceeded, + Some(mega_evm::LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }) + ), + "the transaction must be stopped by its data-size limit: {:?}", + outcome.limit_exceeded, + ); + assert_eq!(outcome.gas.history, body(), "the stop took every frame charge back"); + outcome + }; + + let spent = stop_with(event().append(STOP).build()); + let unspent = stop_with(BytecodeBuilder::default().append(STOP).build()); + + assert_eq!( + spent.gas.reservoir_remaining, unspent.gas.reservoir_remaining, + "the allowance is not gas, so the unwind gives back the same pool either way", + ); + assert!(spent.gas.gas_used > unspent.gas.gas_used, "the event still costs what it computes"); + assert!( + spent.gas.gas_used - unspent.gas.gas_used < storage_call_stipend(), + "and nothing like what its history costs", + ); +} + +/// An allowance the frame did not spend does not return to its caller: what the caller pays for a +/// silent transfer is what it pays for one whose receiver is not there at all, beyond the two +/// write records the transfer writes either way. +#[test] +fn test_an_unspent_allowance_does_not_return_to_the_caller() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, TRANSFER_GAS).append(STOP).build(); + let silent = + execute(db(sender.clone(), Bytes::new()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + let logging = execute( + db(sender, event().append(STOP).build()), + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + + assert!(silent.result.is_success() && logging.result.is_success()); + assert_eq!(silent.gas.history, body() + 2 * record(), "no allowance came back as history"); + assert_eq!(logging.gas.history, silent.gas.history, "and the event cost the caller none"); + // The event's own computation is the only difference between the two. + assert!(logging.gas.regular > silent.gas.regular, "the event still costs what it computes"); +} + +/// A chain of value transfers grants each frame its own allowance, and one frame's spending is +/// not another's: three frames each emit their event and the transaction pays for none of them. +/// +/// The allowances are on the frames' lanes, which the frame lifecycle keeps aligned with the +/// frames themselves, so a chain cannot draw on an allowance granted further up. +#[test] +fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { + if runs_at_measurement_prices() { + return; + } + const MIDDLE: Address = address!("0000000000000000000000000000000000500003"); + // Each hop emits its event and then passes a wei on with a `transfer()`'s gas. + let hop = |next: Option
| { + let code = event(); + match next { + Some(next) => code + .append_many(call_with(CALL, next, 1, TRANSFER_GAS).build().iter().copied()) + .append(STOP) + .build(), + None => code.append(STOP).build(), + } + }; + let db = db(call_with(CALL, MIDDLE, 1, 1_000_000).append(STOP).build(), hop(None)) + .account_balance(MIDDLE, U256::from(1)) + .account_code(MIDDLE, hop(Some(RECEIVER))); + let outcome = execute(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 2, "both hops emitted their event"); + assert_eq!(outcome.result.logs().len(), 4, "beside the two transfers' logs"); + // The first transfer writes the sender's account and the middle one's; the second writes the + // receiver's, the middle account being recorded already by the value it received. + assert_eq!( + outcome.gas.history, + body() + 3 * record(), + "the transfers' account writes, and no event on any ledger", + ); +} + +/* ---------- how large the discount is ---------- */ + +/// How many times the self-calling contract below repeats the grant. +const GRANTS: u64 = 32; + +/// `CALLDATASIZE; ISZERO; JUMPI` to the loop, with the event on the fall-through path, and the +/// loop calling this same address with one wei and one byte of calldata. +/// +/// The entry frame is reached with empty calldata and runs the loop; each frame the loop starts +/// is reached with one byte and runs the event. +fn self_calling_loop() -> Bytes { + /// Bytes of the `CALLDATASIZE; ISZERO; PUSH1 ; JUMPI` header. + const HEADER: usize = 5; + + let event = event().append(STOP).build(); + // The `JUMPDEST` the entry jumps to, past the header and the event. + let loop_start = + u8::try_from(HEADER + event.len()).expect("the header and one event fit in a byte"); + let mut code: Vec = + vec![CALLDATASIZE, ISZERO, PUSH1, loop_start, JUMPI].into_iter().collect(); + code.extend_from_slice(&event); + code.push(JUMPDEST); + assert_eq!(code[loop_start as usize], JUMPDEST); + for _ in 0..GRANTS { + // `CALL(GAS, ADDRESS, 1 wei, args = memory[0..1], ret = [])`, discarding the flag. + code.extend_from_slice(&[PUSH0, PUSH0, PUSH1, 1, PUSH0, PUSH1, 1, ADDRESS, GAS, CALL, POP]); + } + code.push(STOP); + Bytes::from(code) +} + +/// How far a transaction's history gas can fall behind the bytes it appended, and the column that +/// reports the bytes regardless. +/// +/// The allowance is drawn before the frame's own gas rather than after it, so it is a discount on +/// the first 160 bytes of every value-transferring call rather than a fallback for a frame that +/// cannot pay. A contract that calls itself pays its own account's record once and nothing after +/// that, so the grant is repeatable for as long as the transaction's gas lasts: the loop below +/// costs about 10,000 gas a turn, which is some twenty thousand turns inside one transaction at +/// the execution cap — around three megabytes of log bytes, and close to 280,000,000 of history +/// gas, on no gas ledger. +/// +/// The allowance keeps paying first. What closes the gap for a reader is the byte column beside +/// the gas: the transaction reports every byte it appended, the block sums them, and the +/// difference between the two columns is what the allowances paid, a number on record rather than +/// a rediscovery. +#[test] +fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { + if runs_at_measurement_prices() { + return; + } + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(SENDER, U256::from(10u64.pow(9))) + .account_code(SENDER, self_calling_loop()); + let outcome = execute(db, call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.logs().len(), GRANTS as usize, "every frame emitted its event"); + // A self-call writes no recipient, and the caller's own account is written once, so the whole + // loop leaves one record behind. + assert_eq!(outcome.usage.write_records, 1); + assert_eq!( + outcome.usage.data_size, + TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + "the body, the record and every event's bytes are counted", + ); + assert_eq!( + outcome.gas.history, + body() + record(), + "and the history gas is the body and that one record: no event is on it", + ); + assert_eq!( + outcome.gas.history_bytes, + TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + "the byte column has every event on it", + ); + + let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE; + assert_eq!( + outcome.gas.history_bytes - bytes_paid_for, + GRANTS * STORAGE_CALL_STIPEND_BYTES, + "one allowance per value call, and every one of them off the gas ledger", + ); +} + +/// A frame budget reverts the frame that crosses it and nothing else; the allowance that frame +/// held does not come back to its caller with the revert. +#[test] +fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { + if runs_at_measurement_prices() { + return; + } + // The receiver spends its allowance on an event and then crosses its own budget with a + // second one; the sender carries on and the transaction succeeds. Its budget is 98% of the + // sender's 500 bytes, 490: its start — the two records and the transfer log — and one event + // fit, a second event does not. + let receiver = event().append_many(event().build().iter().copied()).append(STOP).build(); + let sender = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(500); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + assert!( + start + STORAGE_CALL_STIPEND_BYTES <= 490 && start + 2 * STORAGE_CALL_STIPEND_BYTES > 490 + ); + + let spent = run_limited( + db(sender.clone(), receiver), + limits, + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + let quiet = run_limited( + db(sender, BytecodeBuilder::default().append(STOP).build()), + limits, + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + + assert!(spent.result.is_success(), "the caller resumes past a frame budget"); + assert_eq!(spent.limit_exceeded, None, "a frame budget below is no stop"); + assert_eq!(spent.gas.history, body(), "the reverted frame kept neither event nor record"); + assert_eq!(quiet.gas.history, body() + 2 * record(), "the frame that returned kept its own"); + // The reverting frame's records came back to the caller and its computation did not, which + // is the whole of the difference: no allowance came back with either. + assert!(spent.gas.regular > quiet.gas.regular, "the events still cost what they compute"); + assert!( + spent.gas.regular - quiet.gas.regular < storage_call_stipend(), + "and the difference is that computation, not an allowance", + ); +} + +/// A frame that drained its allowance and then reverted hands nothing back: the caller pays what +/// the frame computed and gets no allowance with it. +#[test] +fn test_a_drained_allowance_is_not_refunded_by_a_revert() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); + let drained_then_reverts = event().append_many([PUSH0, PUSH0]).append(0xFD).build(); + let reverts = BytecodeBuilder::default().append_many([PUSH0, PUSH0]).append(0xFD).build(); + + let drained = execute( + db(sender.clone(), drained_then_reverts), + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + let quiet = execute(db(sender, reverts), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); + + assert!(drained.result.is_success(), "the caller survives the revert"); + assert_eq!(drained.gas.history, body(), "the reverted frame's records went with it"); + assert_eq!(quiet.gas.history, body()); + assert!( + drained.gas.gas_used > quiet.gas.gas_used, + "the caller pays for the event's computation and gets no allowance back", + ); + assert!( + drained.gas.gas_used - quiet.gas.gas_used < storage_call_stipend(), + "and the difference is that computation, not an allowance", + ); +} + +/// A call that forwards no gas at all still reaches a `receive()` hook that emits one event: the +/// EVM's own `CALL_STIPEND` pays for the computation and the allowance for the bytes. +#[test] +fn test_a_transfer_forwarding_no_gas_still_buys_its_event() { + if runs_at_measurement_prices() { + return; + } + let sender = call_with(CALL, RECEIVER, 1, 0).append(STOP).build(); + let outcome = execute( + db(sender, event().append(STOP).build()), + call(CALLER, SENDER, U256::ZERO, GAS_LIMIT), + ); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(events(&outcome).len(), 1, "the hook emitted its event"); + assert_eq!(outcome.gas.history, body() + 2 * record()); +} diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index 50bc64773..c33ef7f6d 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -1,8 +1,10 @@ -//! The abort protocol: a transaction-level limit stops the transaction with a revert. +//! The stop: a limit stops the frame that crosses it with a revert. //! -//! The frame that crosses the limit reverts with `MegaLimitExceeded`, the transaction is latched, -//! no caller resumes, and the transaction settles like an EIP-8037 revert: the sender gets the -//! unspent regular gas and the whole reservoir back. A frame budget reverts only its frame. A real +//! The frame that crosses the limit reverts alone with `MegaLimitExceeded`, whether the limit is +//! the transaction's or the frame's own budget, and its caller resumes with what the frame counted +//! taken back. A caller that carries on is held to what the transaction has left, and a write that +//! crosses again stops it in turn. A transaction whose own frame is stopped settles like an +//! EIP-8037 revert: the sender gets the unspent regular gas and the whole reservoir back. A real //! out-of-gas still halts and burns. The limit here is the configurable data-size cap of //! `EvmTxRuntimeLimits`; a write record is 40 bytes. @@ -13,11 +15,11 @@ use mega_evm::{ constants::{ACCOUNT_STATE_GAS, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, - MegaLimitExceeded, MegaTransaction, + MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, }; use revm::{ bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0, SSTORE}, - context::result::{ExecutionResult, ResultAndState}, + context::result::ExecutionResult, interpreter::{ interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, InstructionResult, Interpreter, @@ -25,7 +27,9 @@ use revm::{ Database, Inspector, }; -use crate::common::{call, context, runs_at_measurement_prices}; +use crate::common::{ + call, context, execute_under, history, runs_at_measurement_prices, slot_state_gas, +}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const A: Address = address!("00000000000000000000000000000000000000A0"); @@ -78,18 +82,30 @@ fn evm_with( MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(inspector) } +/// Runs `tx` over `db` under `limits`. fn run( db: MemoryDatabase, limits: EvmTxRuntimeLimits, tx: MegaTransaction, -) -> (ResultAndState, Option) { - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); - let result = evm.transact_raw(tx).unwrap(); - (result, evm.ctx().additional_limit().latched().copied()) +) -> MegaTransactionOutcome { + execute_under(db, tx, limits) +} + +/// The history gas an empty transaction body costs, which every transaction here pays before its +/// first frame and keeps whatever that frame does, at the price the engine runs. +fn body_history() -> u64 { + mega_evm::history_gas(mega_evm::TX_BODY_SIZE).expect("a body has a price") +} + +/// The same for a creation transaction, whose init code travels as the body's data. +fn create_body_history(init_code_len: u64) -> u64 { + mega_evm::history_gas(mega_evm::TX_BODY_SIZE + init_code_len).expect("a body has a price") } -fn cap(bytes: u64) -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(bytes) +/// A transaction limit that leaves `execution_bytes` above the body. +fn cap(execution_bytes: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(mega_evm::TX_BODY_SIZE.saturating_add(execution_bytes)) } fn limit_exceeded(kind: LimitKind, limit: u64) -> Bytes { @@ -131,131 +147,83 @@ impl Inspector, EthInterpreter> for Probe { } } -/// Crossing the cap at depth 3 reverts the whole transaction with `MegaLimitExceeded`: nothing -/// it wrote or logged stays, no caller runs another instruction, and the transaction is latched. +/// Crossing the cap at depth 3 reverts `D` alone, and every caller resumes, held to what the +/// transaction has left: `C`'s log after its second write crosses the cap again and stops `C`, +/// `B` writes and logs within it, and `A`'s second write crosses it once more and stops the +/// transaction's own frame, which takes back everything below it. Each stop names the cap, and +/// at no point does the transaction keep more than it. +/// +/// What each crossing reached, above the body: `A`, `B`, `C` and `D`'s first writes are four +/// records (160 bytes), and `D`'s second makes 200; `C`'s second write makes 160 again, and its +/// log 192; `B`'s second write and log make 152; `A`'s second write 192. #[test] -fn test_cap_crossed_at_depth_three_stops_the_transaction() { - // A, B, C and D's first write are four records (160 bytes); D's second crosses 180. - let limit = 180; +fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { + let limit = mega_evm::TX_BODY_SIZE + 180; + let stop = limit_exceeded(LimitKind::DataSize, limit); for inspect in [false, true] { - let mut evm = evm_with(chain(), cap(limit), Probe::default()); + let mut evm = evm_with( + chain(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + Probe::default(), + ); alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, limit); - assert!(result.result.logs().is_empty()); - for account in [A, B, C, D] { - let storage = &result.state[&account].storage; - assert!(storage.values().all(|slot| !slot.is_changed()), "{account} kept a write"); - } - let latched = evm.ctx().additional_limit().latched().copied(); + assert_stopped(&outcome.result, LimitKind::DataSize, limit); assert_eq!( - latched, + outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, - used: 200, + used: mega_evm::TX_BODY_SIZE + 192, frame_local: false - }) + }), + "A's own crossing produced its result" ); + assert!(outcome.result.logs().is_empty()); + for account in [A, B, C, D] { + let storage = &outcome.state[&account].storage; + assert!(storage.values().all(|slot| !slot.is_changed()), "{account} kept a write"); + } + assert_eq!(outcome.usage.data_size, mega_evm::TX_BODY_SIZE, "the body alone stays"); if inspect { let probe = evm.inspector(); let sstores = probe.steps.iter().filter(|op| matches!(op, &&SSTORE)).count(); - assert_eq!(sstores, 5, "A, B, C and D's first two writes ran"); - assert_eq!(probe.steps.last(), Some(&SSTORE), "nothing ran after the crossing write"); - assert!(!probe.steps.contains(&LOG0), "no caller resumed"); - let stops = probe.call_results.iter().map(|(target, result, output)| { - assert_eq!(output, &limit_exceeded(LimitKind::DataSize, limit)); - (*target, *result) - }); + assert_eq!(sstores, 8, "D's two writes and every frame's first and second"); + let logs = probe.steps.iter().filter(|op| matches!(op, &&LOG0)).count(); + assert_eq!(logs, 2, "C's and B's"); + assert_eq!(probe.steps.last(), Some(&SSTORE), "A's second write was the last step"); assert_eq!( - stops.collect::>(), + probe.call_results, vec![ - (D, InstructionResult::Revert), - (C, InstructionResult::Revert), - (B, InstructionResult::Revert), - (A, InstructionResult::Revert) + (D, InstructionResult::Revert, stop.clone()), + (C, InstructionResult::Revert, stop.clone()), + (B, InstructionResult::Stop, Bytes::new()), + (A, InstructionResult::Revert, stop.clone()), ], - "every frame returned the stop, the deepest first" + "each frame that crossed returned the stop, the deepest first" ); } } } -/// With and without an inspector the stopped transaction spends the same gas, and the gas does -/// not depend on what the callers would have run after the call: they never resume. -#[test] -fn test_stop_bills_only_what_ran() { - let gas_of = |db: MemoryDatabase, inspect: bool| { - let mut evm = evm_with(db, cap(180), Probe::default()); - alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, 180); - result.result.gas().tx_gas_used() - }; - let plain = gas_of(chain(), false); - assert_eq!(gas_of(chain(), true), plain, "an observing inspector changes nothing"); - assert!(plain < GAS_LIMIT / 2, "the stop does not burn the gas: {plain}"); - - // Callers whose code after the call is far more expensive spend exactly as much. - let heavy = |next: Address| { - let mut code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(next) - .append(GAS) - .append(CALL) - .append(POP); - for slot in 10..30u64 { - code = code.sstore(U256::from(slot), U256::from(1)); - } - code.stop().build() - }; - let db = MemoryDatabase::default() - .account_code(A, heavy(B)) - .account_code(B, heavy(C)) - .account_code(C, heavy(D)) - .account_code(D, writer()); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, 80); - let light = |next: Address| { - BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(next) - .append(GAS) - .append(CALL) - .append(POP) - .stop() - .build() - }; - let db = MemoryDatabase::default() - .account_code(A, light(B)) - .account_code(B, light(C)) - .account_code(C, light(D)) - .account_code(D, writer()); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(80))); - let light_result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&light_result.result, LimitKind::DataSize, 80); - assert_eq!( - result.result.gas().tx_gas_used(), - light_result.result.gas().tx_gas_used(), - "the code after the calls never ran" - ); -} - /// The stopped transaction gives the whole reservoir back, and spends the same gas whatever its /// gas limit, so a limit above the execution cap changes nothing but the refund. #[test] fn test_stop_refills_the_reservoir_at_any_gas_limit() { let at = |gas_limit: u64| { - let (result, _) = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); - assert_stopped(&result.result, LimitKind::DataSize, 180); + let result = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); *result.result.gas() }; let small = at(100_000_000); let large = at(1_000_000_000); assert_eq!(small.reservoir_remaining(), 0, "a limit under the cap has no reservoir"); - assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP, "all of it back"); + assert_eq!( + large.reservoir_remaining(), + 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(), + "all of it back but the body's history, which the stop does not take back", + ); assert_eq!(small.tx_gas_used(), large.tx_gas_used()); assert_eq!(small.total_gas_spent(), large.total_gas_spent()); } @@ -265,8 +233,8 @@ fn test_stop_refills_the_reservoir_at_any_gas_limit() { #[test] fn test_true_out_of_gas_still_halts_and_burns() { let db = MemoryDatabase::default().account_code(A, writer()); - let gas_limit = 21_000 + 5_000; - let (result, latched) = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); + let gas_limit = 21_000 + body_history() + 5_000; + let result = run(db, cap(0), call(CALLER, A, U256::ZERO, gas_limit)); assert!( matches!( result.result, @@ -279,12 +247,12 @@ fn test_true_out_of_gas_still_halts_and_burns() { result.result ); assert_eq!(result.result.gas().tx_gas_used(), gas_limit, "the halt burns the gas"); - assert_eq!(latched, None); + assert_eq!(result.limit_exceeded, None); } /// A child that runs out of gas halts alone; its caller goes on and writes within the cap. #[test] -fn test_child_out_of_gas_under_a_cap_does_not_latch() { +fn test_child_out_of_gas_under_a_cap_is_no_stop() { let parent = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(B) @@ -295,10 +263,22 @@ fn test_child_out_of_gas_under_a_cap_does_not_latch() { .stop() .build(); let db = MemoryDatabase::default().account_code(A, parent).account_code(B, writer()); - let (result, latched) = run(db, cap(40), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let result = run(db, cap(40), call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&A].storage[&U256::from(9)].present_value(), U256::from(1)); - assert_eq!(latched, None); + assert_eq!(result.limit_exceeded, None); + assert!( + result.state[&B].storage.values().all(|slot| !slot.is_changed()), + "B's writes went with its halt" + ); + assert_eq!( + result.usage, + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + mega_evm::WRITE_RECORD_SIZE, + write_records: 1 + }, + "A's record alone, which meets the cap and does not cross it" + ); } /// A cap crossed by the writes the first frame's start makes (a value transfer's recipient) @@ -313,26 +293,36 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, 39); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 39); assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); - assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO, "nothing kept"); + assert_eq!( + evm.ctx().additional_limit().usage(), + mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "the body stays; the recipient record does not" + ); - let (transfer, _) = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); + let transfer = run(funded(), cap(u64::MAX), call(CALLER, B, U256::from(5), GAS_LIMIT)); assert!(transfer.result.is_success()); - assert_eq!(result.result.gas().tx_gas_used(), 21_000, "the transfer's intrinsic gas"); + assert_eq!( + result.result.gas().tx_gas_used(), + 21_000 + body_history(), + "the transfer's intrinsic gas and its body", + ); assert_eq!( transfer.result.gas().tx_gas_used(), - result.result.gas().tx_gas_used() + ACCOUNT_STATE_GAS, - "the transfer that goes through also creates the recipient" + result.result.gas().tx_gas_used() + + ACCOUNT_STATE_GAS + + mega_evm::WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE, + "the transfer that goes through creates the recipient, and keeps its write record" ); } /// A frame budget reverts the frame that crosses it and nothing else: the caller resumes and the -/// transaction is not latched. +/// transaction reports no stop. #[test] -fn test_frame_budget_reverts_the_frame_without_a_latch() { +fn test_frame_budget_reverts_the_frame_alone() { let parent = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(B) @@ -354,43 +344,49 @@ fn test_frame_budget_reverts_the_frame_without_a_latch() { "A resumed" ); assert!(result.state[&B].storage.values().all(|slot| !slot.is_changed()), "B reverted"); - assert_eq!(evm.ctx().additional_limit().latched(), None); + assert_eq!(evm.ctx().additional_limit().limit_exceeded(), None); let (target, outcome, output) = evm.inspector().call_results[0].clone(); assert_eq!((target, outcome), (B, InstructionResult::Revert)); - assert_eq!(output, limit_exceeded(LimitKind::DataSize, 100)); + // B's budget is 98% of the 100 bytes A was capped at, and B had used none of A's own. + assert_eq!(output, limit_exceeded(LimitKind::DataSize, 98)); assert!(evm.inspector().steps.contains(&SSTORE)); } -/// A frame budget crossed by the outermost frame reverts the transaction, still without a latch. +/// A frame budget crossed by the outermost frame reverts the transaction, and the outcome names +/// it: it produced the result of the transaction's own frame. The third write's record crosses +/// the 100 bytes. #[test] fn test_frame_budget_of_the_outermost_frame_reverts_the_transaction() { let db = MemoryDatabase::default().account_code(A, writer()); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); - let (result, latched) = run(db, limits, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let result = run(db, limits, call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert_stopped(&result.result, LimitKind::DataSize, 100); - assert_eq!(latched, None); -} - -/// A later latch does not replace the first. -#[test] -fn test_first_latch_wins() { - let mut layer = mega_evm::AdditionalLimit::default(); - let first = layer.latch(LimitKind::KVUpdate, 1, 2); - let second = layer.latch(LimitKind::DataSize, 3, 4); - assert_eq!(first, second); - assert_eq!(layer.latched(), Some(&first)); - assert!(first.exceeded_limit() && !first.is_frame_local()); + assert_eq!( + result.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 100, + used: 3 * mega_evm::WRITE_RECORD_SIZE, + frame_local: true, + }) + ); + assert_eq!( + result.usage, + mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "the body is all the transaction keeps" + ); } -/// The layer's state belongs to one transaction: a latch and the usage counted do not reach the -/// next transaction or system call, through any entry point. +/// The layer's state belongs to one transaction: the stop it reported and the usage counted do +/// not reach the next transaction or system call, through any entry point. #[test] -fn test_the_latch_does_not_outlive_its_transaction() { +fn test_the_stop_does_not_outlive_its_transaction() { let db = chain().account_code(B, writer()); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(cap(100))).with_inspector(Probe::default()); - let stopped = - |evm: &MegaEvm| evm.ctx().additional_limit().latched().is_some(); + let stopped = |evm: &MegaEvm| { + evm.ctx().additional_limit().limit_exceeded().is_some() + }; // B writes three slots: 120 bytes cross the cap. alloy_evm::Evm::set_inspector_enabled(&mut evm, false); @@ -403,7 +399,11 @@ fn test_the_latch_does_not_outlive_its_transaction() { .result .is_success()); assert!(!stopped(&evm)); - assert_eq!(evm.ctx().additional_limit().usage(), mega_evm::LimitUsage::ZERO); + assert_eq!( + evm.ctx().additional_limit().usage(), + mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "an empty call keeps its body" + ); assert!(!evm.transact_raw(call(CALLER, B, U256::ZERO, GAS_LIMIT)).unwrap().result.is_success()); alloy_evm::Evm::set_inspector_enabled(&mut evm, true); @@ -421,22 +421,28 @@ fn test_the_latch_does_not_outlive_its_transaction() { assert!(!stopped(&evm)); } -/// A creation transaction stopped before its first frame still bumps the sender's nonce, like any -/// included creation transaction: it cannot be replayed. +/// A creation transaction stopped before its first frame runs — its body fits the limit, the record +/// of the account it creates does not — still bumps the sender's nonce, like any included creation +/// transaction: it cannot be replayed. #[test] fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { - let tx = crate::common::create(CALLER, writer(), GAS_LIMIT); - let (result, latched) = run(MemoryDatabase::default(), cap(39), tx); - assert_stopped(&result.result, LimitKind::DataSize, 39); - assert!(latched.is_some()); + let init_code = writer(); + let room = init_code.len() as u64 + mega_evm::WRITE_RECORD_SIZE - 1; + let tx = crate::common::create(CALLER, init_code.clone(), GAS_LIMIT); + let result = run(MemoryDatabase::default(), cap(room), tx); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + room); + assert!(result.limit_exceeded.is_some()); assert_eq!(result.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); assert!(result.state.get(&CALLER.create(0)).is_none_or(|a| a.info.is_empty_code_hash())); assert!(result.result.gas().tx_gas_used() < GAS_LIMIT / 2, "the stop burns nothing"); // The stopped creation's result carries the reservoir back. - let tx = crate::common::create(CALLER, writer(), 1_000_000_000); - let (result, _) = run(MemoryDatabase::default(), cap(39), tx); - assert_eq!(result.result.gas().reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); + let tx = crate::common::create(CALLER, init_code.clone(), 1_000_000_000); + let result = run(MemoryDatabase::default(), cap(room), tx); + assert_eq!( + result.result.gas().reservoir_remaining(), + 1_000_000_000 - TX_GAS_LIMIT_CAP - create_body_history(init_code.len() as u64), + ); } /// A limit is crossed by usage above it: usage equal to the limit does not stop a transaction or @@ -445,17 +451,17 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { fn test_usage_equal_to_the_limit_does_not_stop() { // A writes three slots: 120 bytes. let db = || MemoryDatabase::default().account_code(A, writer()); - let (result, latched) = run(db(), cap(120), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let result = run(db(), cap(120), call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(latched, None); + assert_eq!(result.limit_exceeded, None); let budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(120); - let (result, _) = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); + let result = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert!(result.result.is_success(), "{:?}", result.result); - let (result, _) = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); - assert_stopped(&result.result, LimitKind::DataSize, 119); + let result = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); + assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 119); } -/// A tool's inspector that writes to the running frame's gas or results. +/// A tool's inspector that writes to the running frame's gas. #[derive(Default)] struct Charger { opcode: u8, @@ -464,8 +470,6 @@ struct Charger { /// History gas charged after the first `SSTORE` of the transaction. history_gas: u64, charged: bool, - /// Turns every call result into a success. - calls_succeed: bool, } impl Inspector, EthInterpreter> for Charger { @@ -484,17 +488,6 @@ impl Inspector, EthInterpreter> for Charger { assert!(interp.gas.record_history_cost(self.history_gas)); } } - - fn call_end( - &mut self, - _context: &mut MegaContext, - _inputs: &CallInputs, - outcome: &mut CallOutcome, - ) { - if self.calls_succeed { - outcome.result.result = InstructionResult::Stop; - } - } } fn execute_with( @@ -514,7 +507,8 @@ fn execute_with( #[test] fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { let gas_limit = 1_000_000_000; - let reservoir = gas_limit - TX_GAS_LIMIT_CAP; + // The body's history comes out of the reservoir too, and the stop does not take it back. + let reservoir = gas_limit - TX_GAS_LIMIT_CAP - body_history(); let charger = || Charger { state_gas: 50_000, ..Default::default() }; // The chain's own new slots draw state gas from the same reservoir, so the charger's 50,000 // is measured against a run that charges nothing extra. @@ -528,10 +522,10 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { "the kept charge" ); assert_eq!(kept.gas.state, plain.gas.state + 50_000); - assert!(plain.gas.state > 0, "the chain's slots are state gas of their own"); + assert_eq!(plain.gas.state, 9 * slot_state_gas(), "the chain's nine slots are state gas"); let stopped = execute_with(chain(), cap(180), charger(), gas_limit); - assert_stopped(&stopped.result, LimitKind::DataSize, 180); + assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); assert_eq!(stopped.gas.state, 0); } @@ -545,23 +539,20 @@ fn test_outcome_reports_history_gas() { let plain = execute_with(chain(), EvmTxRuntimeLimits::no_limits(), Charger::default(), GAS_LIMIT); assert!(kept.result.is_success()); - assert_eq!(kept.gas.history, 700); + assert_eq!(kept.gas.history, plain.gas.history + 700); + assert_eq!( + plain.gas.history, + body_history() + + 9 * history(mega_evm::WRITE_RECORD_SIZE) + + 3 * history(mega_evm::LOG_BASE_SIZE), + "the chain's own writes are history too: nine records and three empty logs", + ); assert_eq!(kept.gas.regular, plain.gas.regular, "history is not regular gas"); assert_eq!(kept.gas.gas_used, plain.gas.gas_used + 700); + // The body is charged before the first frame, so the stop keeps it and takes back every + // charge the frames made, the inspector's included. let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); - assert_stopped(&stopped.result, LimitKind::DataSize, 180); - assert_eq!(stopped.gas.history, 0); -} - -/// Under the latch every returned result is the stop, whatever an inspector made of it: rewriting -/// the calls' results into successes neither resumes a caller nor lets the transaction succeed. -#[test] -fn test_latch_overrides_a_rewritten_result() { - let charger = Charger { calls_succeed: true, ..Default::default() }; - let outcome = execute_with(chain(), cap(180), charger, GAS_LIMIT); - assert_stopped(&outcome.result, LimitKind::DataSize, 180); - assert!(outcome.limit_exceeded.is_some()); - assert_eq!(outcome.usage, mega_evm::LimitUsage::ZERO, "every lane failed"); - assert!(outcome.result.logs().is_empty()); + assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); + assert_eq!(stopped.gas.history, body_history()); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index 8e9752edc..cfcbec37c 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -23,7 +23,7 @@ use mega_evm::{ ORACLE_CONTRACT_CODE, }, test_utils::MemoryDatabase, - EvmTxRuntimeLimits, LimitKind, MegaEvm, + EvmTxRuntimeLimits, LimitUsage, MegaEvm, }; use revm::{ context::{result::ExecutionResult, ContextTr, JournalTr}, @@ -32,7 +32,8 @@ use revm::{ interpreter::{ interpreter::SharedMemory, interpreter_action::FrameInit, interpreter_types::InterpreterTypes, CallInput, CallInputs, CallOutcome, CallScheme, - CallValue, FrameInput, Gas, InstructionResult, InterpreterResult, + CallValue, CreateInputs, CreateScheme, FrameInput, Gas, InstructionResult, + InterpreterResult, }, primitives::CALL_STACK_LIMIT, Inspector, @@ -45,6 +46,13 @@ const TARGET: Address = address!("0000000000000000000000000000000000300001"); const GAS_LIMIT: u64 = 100_000; const RESERVOIR: u64 = 7_000_000; +/// The history gas the body of a transaction carrying `calldata_len` bytes costs. It is charged +/// before the first frame and comes out of the reservoir, so a transaction with a pool starts +/// with this much less of one. It is read at the price the engine runs. +fn body_history(calldata_len: u64) -> u64 { + mega_evm::history_gas(mega_evm::TX_BODY_SIZE + calldata_len).expect("a body has a price") +} + fn call_frame_init(depth: usize) -> FrameInit { FrameInit { depth, @@ -97,6 +105,58 @@ fn test_depth_guard_returns_call_too_deep_with_the_inherited_reservoir() { assert_call_too_deep(&result); } +/// Every start past the call-stack limit is answered by the guard as revm answers it — a creation +/// and every call scheme alike — with the forwarded gas untouched and the inherited reservoir +/// carried, before anything reads its caller's account or counts its start: nothing is counted, +/// and the creator's nonce is not bumped, so no nonce record outlives the answer. +#[test] +fn test_depth_guard_answers_a_creation_and_every_call_scheme() { + let past = CALL_STACK_LIMIT as usize + 1; + let creation = FrameInit { + depth: past, + memory: SharedMemory::new(), + frame_input: FrameInput::Create(Box::new(CreateInputs::new( + CALLER, + CreateScheme::Create, + U256::from(1), + Bytes::new(), + GAS_LIMIT, + RESERVOIR, + ))), + }; + let mut inits = vec![creation]; + for (scheme, value) in [ + (CallScheme::Call, CallValue::Transfer(U256::from(1))), + (CallScheme::CallCode, CallValue::Transfer(U256::from(1))), + (CallScheme::DelegateCall, CallValue::Apparent(U256::from(1))), + (CallScheme::StaticCall, CallValue::Transfer(U256::ZERO)), + ] { + let mut init = call_frame_init(past); + if let FrameInput::Call(inputs) = &mut init.frame_input { + inputs.scheme = scheme; + inputs.value = value; + inputs.is_static = scheme == CallScheme::StaticCall; + } + inits.push(init); + } + for init in inits { + let what = format!("{:?}", init.frame_input); + // The caller's account is never loaded: nothing reads it for a start the guard answers. + let mut evm = MegaEvm::new(context(MemoryDatabase::default())); + let result = EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail"); + let ItemOrResult::Result(result) = result else { panic!("{what}: no frame is built") }; + let gas = result.gas(); + assert_eq!(result.instruction_result(), InstructionResult::CallTooDeep, "{what}"); + assert_eq!(gas.remaining(), GAS_LIMIT, "{what}: the forwarded gas is untouched"); + assert_eq!(gas.reservoir(), RESERVOIR, "{what}: the inherited reservoir is carried"); + if let FrameResult::Create(outcome) = &result { + assert_eq!(outcome.address, None, "{what}"); + } + assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO, "{what}: counted"); + assert!(!evm.ctx().journal_ref().state.contains_key(&CALLER), "{what}: no nonce bumped"); + } +} + /// `CALL_STACK_LIMIT` itself is the last permitted depth: the guard does not fire there. #[test] fn test_depth_boundary_allows_call_at_limit() { @@ -158,30 +218,15 @@ fn test_inspect_frame_init_depth_guard_overrides_inspector() { ); } -/// A latched transaction's frame is answered with the stop, even past the call-stack limit: the -/// latch is checked first, and its answer carries the reservoir too. -#[test] -fn test_exceeded_tx_limit_wins_over_call_too_deep() { - let mut evm = MegaEvm::new(context(MemoryDatabase::default())); - let stop = evm.ctx_mut().additional_limit_mut().latch(LimitKind::KVUpdate, 0, 1); - let result = EvmTr::frame_init(&mut evm, call_frame_init(CALL_STACK_LIMIT as usize + 1)) - .expect("frame_init does not fail"); - let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { - panic!("a latched transaction's frame is answered"); - }; - assert_eq!(outcome.result.result, InstructionResult::Revert, "the stop, not CallTooDeep"); - assert_eq!(outcome.result.output, stop.revert_data()); - assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT); - assert_eq!(outcome.result.gas.reservoir(), RESERVOIR); -} - -/// A first frame answered with the stop before it runs gives the whole reservoir back, and costs -/// the same at a gas limit under the execution cap and far above it. +/// A first frame answered with the stop before it runs — its body fits the limit, the record and +/// the transfer log of its value do not — gives the whole reservoir back, and costs the same at a +/// gas limit under the execution cap and far above it. #[test] fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { let at = |gas_limit: u64| { let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let result = alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, TARGET, U256::from(1), gas_limit)) @@ -191,7 +236,7 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { }; let (small, large) = (at(100_000_000), at(1_000_000_000)); assert_eq!(small.reservoir_remaining(), 0); - assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP); + assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(0)); assert_eq!(small.tx_gas_used(), large.tx_gas_used()); assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); } @@ -269,10 +314,12 @@ enum Expected { Answer(Bytes), /// The call reverted with exactly this data. Revert(Bytes), - /// `remainingComputeGas` answers the regular gas its own frame was forwarded, the one answer - /// of the matrix that depends on the transaction's gas limit: under the execution cap it is + /// `remainingComputeGas`, called by the transaction itself, answers the regular gas the + /// transaction's own frame was forwarded, the one answer of the matrix that depends on the + /// transaction's gas limit: under the execution cap it is /// the transaction's limit less what pre-execution took, above the cap it is the cap's. So - /// the two answers differ by exactly what the cap holds back at the wider limit. + /// the two answers differ by what the cap holds back at the wider limit, and by the body's + /// history, which the narrow limit has no reservoir to pay from. ForwardedRegularGas, } @@ -313,15 +360,16 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected }; assert_eq!( forwarded(&wide_answer) - forwarded(&narrow_answer), - TX_GAS_LIMIT_CAP - NARROW, - "the answer is the forwarded regular gas, which the execution cap holds back", + TX_GAS_LIMIT_CAP - NARROW + body_history(data.len() as u64), + "the answer is the forwarded regular gas, which the execution cap holds back; the \ + narrow limit has no reservoir, so its body's history comes off that budget too", ); } assert_eq!(narrow.reservoir_remaining(), 0, "there is no pool below the cap"); assert_eq!( wide.reservoir_remaining(), - WIDE - TX_GAS_LIMIT_CAP, - "the call spends no state gas, so the whole pool comes back", + WIDE - TX_GAS_LIMIT_CAP - body_history(data.len() as u64), + "the call spends no state gas, so the whole pool but the body's history comes back", ); assert_eq!( narrow.tx_gas_used(), @@ -427,16 +475,16 @@ fn test_a_forwarded_hint_keeps_the_reservoir() { } /// A dispatched `keylessDeploy` call is charged its overhead out of regular gas, so it costs the -/// same whether there is a pool or not and the pool comes back whole. The charge is not an -/// answer: the deployed bytecode runs after it and reverts with `NotIntercepted()`, because the -/// rewrite that turns the call into a deployment is not here yet. +/// same whether there is a pool or not and the pool comes back whole. A call the rules refuse — +/// here one whose bytes are not a signed transaction — is answered after the overhead with the +/// rule's error, and the answer carries the reservoir. #[test] fn test_the_keyless_overhead_comes_out_of_regular_gas() { assert_the_reservoir_survives( KEYLESS_DEPLOY_ADDRESS, keyless_deploy_call(), U256::ZERO, - Expected::Revert(Bytes::from_static(&IKeylessDeploy::NotIntercepted::SELECTOR)), + Expected::Revert(Bytes::from_static(&IKeylessDeploy::MalformedEncoding::SELECTOR)), ); } @@ -455,7 +503,9 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { // The same transaction to an account without code spends its intrinsic cost and nothing // else, and the refusal is answered before a frame runs, so what the dispatched call spends - // beyond it is the overhead — once. + // beyond it is the overhead — once — less the one thing the refusal takes back: the history + // of the write record a transfer that goes through leaves on its recipient. + let record = mega_evm::write_record_history_gas(1).expect("a record has a price"); let spent = |to: Address, gas_limit: u64| { let mut tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); tx.0.base.value = U256::from(1); @@ -463,16 +513,16 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { }; for gas_limit in [NARROW, WIDE] { assert_eq!( - spent(KEYLESS_DEPLOY_ADDRESS, gas_limit) - spent(TARGET, gas_limit), + spent(KEYLESS_DEPLOY_ADDRESS, gas_limit) + record - spent(TARGET, gas_limit), KEYLESS_DEPLOY_OVERHEAD_GAS, "at a gas limit of {gas_limit}", ); } } -/// A `keylessDeploy` call forwarded less regular gas than the overhead is answered out of gas, -/// with the reservoir it inherited carried, and that answer settles into a caller exactly as -/// revm's own frame return settles a frame that ran out. +/// A `keylessDeploy` call forwarded less regular gas than the overhead runs out of gas on its +/// first run, with the reservoir it inherited carried, and that result settles into a caller +/// exactly as revm's own frame return settles a frame that ran out. #[test] fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { use core::convert::Infallible; @@ -482,11 +532,19 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { let forwarded = KEYLESS_DEPLOY_OVERHEAD_GAS - 1; let mut evm = MegaEvm::new(context(system_db())); + // The accounts a transaction's validation and its first frame input load. + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + journal.load_account_with_code(KEYLESS_DEPLOY_ADDRESS).unwrap(); let init = call_frame_init_to(0, KEYLESS_DEPLOY_ADDRESS, keyless_deploy_call(), forwarded); - let ItemOrResult::Result(result) = + let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail") else { - panic!("a call that cannot pay the overhead starts no frame"); + panic!("the call's frame is built"); + }; + let ItemOrResult::Result(result) = EvmTr::frame_run(&mut evm).expect("frame_run does not fail") + else { + panic!("a call that cannot pay the overhead starts no creation"); }; let FrameResult::Call(outcome) = &result else { panic!("expected a call result: {result:?}") }; assert_eq!(outcome.result.result, InstructionResult::OutOfGas); diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs new file mode 100644 index 000000000..5a077f0a1 --- /dev/null +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -0,0 +1,509 @@ +//! How a system call's gas is settled: at most 30M of it regular gas, the rest its state-gas +//! reservoir. +//! +//! Every case runs the same system call through `MegaEvm` and through op-revm's `OpEvm` on the +//! `CfgEnv` the `MegaEvm` context holds — so on the fork with the same switch on — and compares +//! the two field by field: the gas, the reservoir left, the result and the state. A system call is +//! the protocol's own work: it pays no history gas, prices its state at the minimum SALT bucket and +//! is held to no per-transaction limit, so nothing Satin adds to a transaction separates the two. +//! +//! A transaction is not a system call. The last cases hold a system-address transaction, which is +//! promoted to a deposit, to the deposit op-revm runs for it, below and above the execution cap: +//! its gas is split by the cap, as every transaction's is, and not by the system-call budget. + +use std::convert::Infallible; + +use alloy_evm::Evm; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + satin_gas_params, + system::{ + storage_slots::{ + CURRENT_SYSTEM_ADDRESS, PENDING_SYSTEM_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK, + }, + IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE, + }, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, + TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use op_revm::{ + handler::OpHandler, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpEvm, + OpSpecId, OpTransaction, OpTransactionError, +}; +use revm::{ + bytecode::opcode::{GAS, INVALID, NUMBER, POP, PUSH0, SSTORE, STOP}, + context::{ + result::{EVMError, ExecResultAndState, ExecutionResult}, + BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, Transaction, TxEnv, + }, + context_interface::cfg::GasId, + handler::{ + EthFrame, ExecuteEvm, Handler, SystemCallTx, SYSTEM_CALL_GAS_LIMIT, + SYSTEM_CALL_REGULAR_GAS_LIMIT, + }, + inspector::NoOpInspector, + interpreter::interpreter::EthInterpreter, + state::EvmState, + Journal, +}; + +use crate::common::{runs_at_measurement_prices, state_is_free}; + +const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); +const CONTRACT: Address = address!("0x5000000000000000000000000000000000000001"); + +/// The caller the protocol's own pre-block calls run as. +const SYSTEM_ADDRESS: Address = alloy_eips::eip4788::SYSTEM_ADDRESS; + +/// The reservoir a system call on revm's default gas limit carries: the margin above 30M. +const DEFAULT_RESERVOIR: u64 = SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT; + +/// The state gas of one fresh slot at the minimum bucket, under the schedule in force: Satin's +/// own, [`SLOT_STATE_GAS`], or the one a measurement build's byte prices built. +fn slot() -> u64 { + satin_gas_params().get(GasId::sstore_set_state_gas()) +} + +type Outcome = ExecResultAndState, EvmState>; +type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; +type Op = OpEvm; + +fn block() -> BlockEnv { + BlockEnv { + number: U256::from(1_000), + timestamp: U256::from(1_800_000_000u64), + gas_limit: 10_000_000_000, + ..Default::default() + } +} + +/// An `OpEvm` over `db` on `cfg`, in [`block`]. +fn op_evm(db: MemoryDatabase, cfg: CfgEnv) -> Op { + let ctx = OpContext::new(db, OpSpecId::KARST) + .with_cfg(cfg) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + OpEvm::new(ctx, NoOpInspector) +} + +/// A `MegaEvm` over `db` reading `envs`, in [`block`], and an `OpEvm` over the same `db` on the +/// `CfgEnv` the `MegaEvm` context holds. +fn both_evms_with( + db: MemoryDatabase, + envs: TestExternalEnvs, +) -> (MegaEvm, Op) { + let ctx = MegaContext::new_with_external_envs( + db.clone(), + MegaSpecId::SATIN, + ExternalEnvs::from(envs), + ) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let cfg = ctx.cfg().clone(); + assert!(cfg.system_call_state_gas_margin_in_reservoir, "both run with the split"); + assert!(cfg.enable_amsterdam_eip8037, "which needs EIP-8037"); + (MegaEvm::new(ctx), op_evm(db, cfg)) +} + +/// [`both_evms_with`], without a SALT environment. +fn both_evms(db: MemoryDatabase) -> (MegaEvm, Op) { + both_evms_with(db, TestExternalEnvs::new()) +} + +/// op-revm's own system call from `caller` to `contract` on `gas_limit`: its system-call +/// transaction with the gas limit replaced, run through its handler's system-call path. +fn op_system_call( + op: &mut Op, + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, +) -> Outcome { + let mut tx = OpTransaction::::new_system_tx_with_caller(caller, contract, data); + tx.base.gas_limit = gas_limit; + op.0.ctx.set_tx(tx); + let result: Result<_, EVMError> = + OpHandler::<_, _, EthFrame>::new().run_system_call(op); + ExecResultAndState::new(result.expect("the system call runs"), op.finalize()) +} + +/// Runs the system call from `caller` to `contract` on `gas_limit` through both engines. +fn run_both( + (mut mega, mut op): (MegaEvm, Op), + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, +) -> (Outcome, Outcome) { + let mega_outcome = mega + .transact_system_call_with_gas_limit(caller, contract, data.clone(), gas_limit) + .expect("the system call runs"); + let op_outcome = op_system_call(&mut op, caller, contract, data, gas_limit); + (mega_outcome, op_outcome) +} + +/// Asserts the two outcomes agree field by field, then as a whole, so a field added later is +/// covered too. +fn assert_same(mega: &Outcome, op: &Outcome) { + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); + assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); + assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); + assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); + assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); + assert_eq!(m, o, "ResultGas"); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result.output(), op.result.output(), "output"); + assert_eq!(mega.result, op.result, "execution result"); + assert_eq!(mega.state, op.state, "state"); +} + +/// Code that stores the regular gas left after `GAS` into slot zero, a fresh slot. +fn gas_to_slot() -> Bytes { + Bytes::from_static(&[GAS, PUSH0, SSTORE, STOP]) +} + +/// What [`gas_to_slot`] stored. +fn stored_gas(outcome: &Outcome) -> u64 { + let slot = outcome.state[&CONTRACT].storage[&U256::ZERO].present_value(); + slot.to::() +} + +/// Code that writes `slots` fresh slots, `SSTORE(i, 1)` for each. +fn fresh_writes(slots: u64) -> BytecodeBuilder { + (0..slots) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) +} + +/// A database whose [`CONTRACT`] runs `code`. +fn db_with(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default().account_code(CONTRACT, code) +} + +/// A system call whose gas limit is at most 30M is regular gas alone: there is no reservoir, and +/// the fresh slot's state gas is paid out of the regular budget. +#[test] +fn test_a_system_call_within_30m_has_no_reservoir() { + for gas_limit in [1_000_000, SYSTEM_CALL_REGULAR_GAS_LIMIT] { + let (mega, op) = + run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); + assert!(mega.result.is_success(), "{:?}", mega.result); + assert_eq!(mega.result.gas().reservoir_remaining(), 0); + assert_eq!(mega.result.gas().state_gas_spent_final(), slot()); + assert!(stored_gas(&mega) > gas_limit - 10, "all {gas_limit} of it is regular gas"); + assert_same(&mega, &op); + } +} + +/// A system call whose gas limit is above 30M runs on 30M of regular gas, which is what `GAS` +/// reads, and carries the rest as its reservoir: the fresh slot is paid out of it, and what is +/// left is reported. So on revm's default limit and on a far larger one. +#[test] +fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { + for gas_limit in [SYSTEM_CALL_GAS_LIMIT, 250_000_000] { + let (mega, op) = + run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); + assert!(mega.result.is_success(), "{:?}", mega.result); + let gas = stored_gas(&mega); + assert!(gas < SYSTEM_CALL_REGULAR_GAS_LIMIT, "GAS reads the regular budget: {gas}"); + assert!(gas > SYSTEM_CALL_REGULAR_GAS_LIMIT - 10, "all of it: {gas}"); + assert_eq!( + mega.result.gas().reservoir_remaining(), + gas_limit - SYSTEM_CALL_REGULAR_GAS_LIMIT - slot(), + "the excess, less the one slot it paid for", + ); + assert_same(&mega, &op); + } +} + +/// The default reservoir holds sixteen fresh slots at Satin's price. That many writes empty it and +/// spend no regular gas on state; the next one spills what the reservoir cannot pay onto the +/// regular budget. `GAS`, read after the writes, shows the spill: the regular gas the next write +/// took is its own regular cost, which the writes before it show, plus the part of its slot the +/// reservoir did not hold. +/// +/// Where a slot is cheaper, the default reservoir holds more fresh slots than the regular budget +/// can write, so the call is given a reservoir of sixteen. +#[test] +fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { + // Slots that cost nothing never empty the reservoir, and there is nothing to spill. + if state_is_free() || slot() == 0 { + return; + } + if !runs_at_measurement_prices() { + assert_eq!(SLOT_STATE_GAS, slot()); + assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); + } + let reservoir = DEFAULT_RESERVOIR.min(16 * slot()); + // The reading is stored into a slot that already holds a value, which writes no new state. + const READING: u64 = 0xff; + let run = |writes| { + let code = + fresh_writes(writes).append(GAS).push_number(READING as u8).append(SSTORE).stop(); + let db = + db_with(code.build()).account_storage(CONTRACT, U256::from(READING), U256::from(1)); + let gas_limit = SYSTEM_CALL_REGULAR_GAS_LIMIT + reservoir; + let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), gas_limit); + assert!(mega.result.is_success(), "{:?}", mega.result); + assert_eq!(mega.result.gas().state_gas_spent_final(), writes * slot()); + assert_same(&mega, &op); + let reading = mega.state[&CONTRACT].storage[&U256::from(READING)].present_value(); + (reading.to::(), mega.result.gas().reservoir_remaining()) + }; + + // The most slots the reservoir holds, and what the one after them spills. + let held = reservoir / slot(); + let spill = (held + 1) * slot() - reservoir; + let (two_short, _) = run(held - 2); + let (one_short, reservoir_one_short) = run(held - 1); + let (at, reservoir_at) = run(held); + let (past, reservoir_past) = run(held + 1); + assert_eq!(reservoir_one_short, reservoir - (held - 1) * slot()); + assert_eq!(reservoir_at, reservoir - held * slot(), "empty at Satin's price"); + assert_eq!(reservoir_past, 0); + // A write the reservoir holds takes regular gas for itself alone, the same for each. + let one_write = one_short - at; + assert_eq!(two_short - one_short, one_write); + assert_eq!(at - past, one_write + spill, "the next one spilled"); +} + +/// What is left of the reservoir is reported, slot by slot, and a call that writes nothing +/// leaves all of it. +#[test] +fn test_reservoir_remaining_is_what_the_writes_left() { + // As many as five writes, and no more than the reservoir holds at the byte prices in effect. + let most = DEFAULT_RESERVOIR.checked_div(slot()).map_or(5, |held| held.min(5)); + for writes in [0, 1, most] { + let code = fresh_writes(writes).stop().build(); + let (mega, op) = run_both( + both_evms(db_with(code)), + CALLER, + CONTRACT, + Bytes::new(), + SYSTEM_CALL_GAS_LIMIT, + ); + assert_eq!( + mega.result.gas().reservoir_remaining(), + DEFAULT_RESERVOIR - writes * slot(), + "{writes} writes", + ); + assert_same(&mega, &op); + } +} + +/// A system call that fails settles as op-revm settles it: a revert gives the state gas of what +/// it wrote back to the reservoir and keeps its regular gas; a halt spends the regular budget and +/// still gives the reservoir back. +#[test] +fn test_a_failing_system_call_settles_like_op_revm() { + let reverting = fresh_writes(3).revert().build(); + let (mega, op) = run_both( + both_evms(db_with(reverting)), + CALLER, + CONTRACT, + Bytes::new(), + SYSTEM_CALL_GAS_LIMIT, + ); + assert!(matches!(mega.result, ExecutionResult::Revert { .. }), "{:?}", mega.result); + assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR, "nothing kept"); + assert_eq!(mega.result.gas().state_gas_spent_final(), 0); + assert_same(&mega, &op); + + let halting = fresh_writes(3).append(INVALID).build(); + let (mega, op) = run_both( + both_evms(db_with(halting)), + CALLER, + CONTRACT, + Bytes::new(), + SYSTEM_CALL_GAS_LIMIT, + ); + assert!(mega.result.is_halt(), "{:?}", mega.result); + assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR); + assert_eq!( + mega.result.gas().total_gas_spent(), + SYSTEM_CALL_REGULAR_GAS_LIMIT, + "a halt burns the regular budget, not the reservoir", + ); + assert_same(&mega, &op); +} + +/// A system call with a reservoir is still the protocol's own work. In a crowded SALT region, +/// under limits every one of which it would cross, and after reading the block number, it prices +/// its state at the minimum bucket — reservoir draws and spills alike — pays no history and is +/// stopped and detained by nothing: it is op-revm's system call, field for field. +#[test] +fn test_a_system_call_with_a_reservoir_stays_exempt() { + let code = BytecodeBuilder::default().append(NUMBER).append(POP); + let code = (0..20_u64).fold(code, |code, slot| code.sstore(U256::from(slot), U256::from(1))); + let crowded = + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 1_000); + let (mut mega, op) = both_evms_with(db_with(code.stop().build()), crowded.clone()); + mega.set_tx_runtime_limits( + EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(0) + .with_frame_data_size_limit(0) + .with_block_env_access_compute_gas_limit(0), + ); + + let (mega_outcome, op_outcome) = + run_both((mega, op), SYSTEM_ADDRESS, CONTRACT, Bytes::new(), 250_000_000); + assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); + assert_eq!(mega_outcome.result.gas().state_gas_spent_final(), 20 * slot(), "m = 1"); + assert_eq!(crowded.total_bucket_queries(), 0, "no capacity was read"); + assert_same(&mega_outcome, &op_outcome); +} + +/// The registry, holding a system-address change due at the block, for the `applyPendingChanges()` +/// call to apply. +fn registry_with_a_due_change() -> MemoryDatabase { + let word = |address: Address| U256::from_be_bytes(address.into_word().0); + MemoryDatabase::default() + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE) + .account_storage( + SEQUENCER_REGISTRY_ADDRESS, + CURRENT_SYSTEM_ADDRESS, + word(MEGA_SYSTEM_ADDRESS), + ) + .account_storage(SEQUENCER_REGISTRY_ADDRESS, PENDING_SYSTEM_ADDRESS, word(CALLER)) + .account_storage( + SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_ACTIVATION_BLOCK, + U256::from(1_000), + ) +} + +/// `applyPendingChanges()` on 30M in a crowded SALT region applies the change at the minimum +/// bucket's price: with no reservoir its state gas is paid out of the 30M, which holds it many +/// times over, and it is what op-revm charges, which has no SALT. +#[test] +fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { + let crowded = + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); + let data = Bytes::from(ISequencerRegistry::applyPendingChangesCall {}.abi_encode()); + let (mega, op) = run_both( + both_evms_with(registry_with_a_due_change(), crowded.clone()), + SYSTEM_ADDRESS, + SEQUENCER_REGISTRY_ADDRESS, + data, + SYSTEM_CALL_REGULAR_GAS_LIMIT, + ); + assert!(mega.result.is_success(), "{:?}", mega.result); + assert_eq!(mega.result.gas().reservoir_remaining(), 0); + // Where a state byte is free the slots cost nothing, at any bucket. + if !state_is_free() { + let state = mega.result.gas().state_gas_spent_final(); + assert!(state > 0, "the change wrote fresh slots"); + assert_eq!(state % slot(), 0, "at m = 1"); + } + assert_eq!(crowded.total_bucket_queries(), 0); + assert_same(&mega, &op); +} + +/// The default system-call entry point runs on revm's default gas limit however large the block, +/// in a crowded region too: 30M of regular gas and the margin as reservoir, the EIP-2935 and +/// EIP-4788 contracts' writes paid out of it at the minimum bucket. The block's own pre-block +/// calls widen the reservoir with the block (see the block tests); this entry point does not. +#[test] +fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_region() { + use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + }; + for (contract, code, slots) in [ + (HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone(), 1), + (BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone(), 2), + ] { + let db = MemoryDatabase::default().account_code(contract, code); + let crowded = + TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); + let (mut mega, mut op) = both_evms_with(db, crowded.clone()); + let data = Bytes::from(B256::repeat_byte(0x29).0); + let mega_outcome = + Evm::transact_system_call(&mut mega, SYSTEM_ADDRESS, contract, data.clone()) + .expect("the system call runs"); + let op_outcome = revm::handler::SystemCallEvm::system_call_with_caller( + &mut op, + SYSTEM_ADDRESS, + contract, + data, + ) + .expect("the system call runs"); + + assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); + assert_eq!(mega.ctx().tx().gas_limit(), SYSTEM_CALL_GAS_LIMIT, "not the block's 10B"); + assert_eq!( + mega_outcome.result.gas().reservoir_remaining(), + DEFAULT_RESERVOIR - slots * slot(), + ); + assert_eq!(crowded.total_bucket_queries(), 0); + assert_same(&mega_outcome, &op_outcome); + } +} + +/// A system-address transaction from [`MEGA_SYSTEM_ADDRESS`] to the Oracle on `gas_limit`, as the +/// sequencer sends it, and the deposit op-revm runs for it: the same fields, with the source hash +/// the promotion stamps and no gas price. +fn system_address_transaction(gas_limit: u64) -> (TxEnv, OpTransaction) { + let tx = TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + data: IOracle::getSlotCall { slot: U256::ZERO }.abi_encode().into(), + gas_limit, + chain_id: Some(1), + ..Default::default() + }; + let mut deposit = OpTransaction::new(TxEnv { tx_type: DEPOSIT_TRANSACTION_TYPE, ..tx.clone() }); + deposit.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; + (tx, deposit) +} + +/// A system-address transaction is a transaction, not a system call: below the execution cap its +/// whole gas limit is regular gas, and above it the reservoir is what exceeds the cap, as for the +/// deposit op-revm runs for it — never the system call's 30M split, which the rows between 30M and +/// the cap would see. +/// +/// The one difference from op-revm's deposit is in the state: Satin's validation read the live +/// system address out of the `SequencerRegistry`, a read-only entry holding the one slot. +#[test] +fn test_a_system_address_transaction_is_split_by_the_execution_cap() { + for (gas_limit, reservoir) in [ + (1_000_000, 0), + (100_000_000, 0), + (TX_GAS_LIMIT_CAP, 0), + (TX_GAS_LIMIT_CAP + 5_000_000, 5_000_000), + ] { + let db = MemoryDatabase::default() + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .sequencer_registry(MEGA_SYSTEM_ADDRESS); + let (mut mega, mut op) = both_evms(db); + let (tx, deposit) = system_address_transaction(gas_limit); + + let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx))).expect("accepted"); + assert!(mega.ctx().is_system_originated(), "it is the protocol's own transaction"); + let op_outcome = op.transact(deposit).expect("accepted"); + + assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); + assert_eq!(mega_outcome.gas.history, 0); + assert_eq!(mega_outcome.result.gas().reservoir_remaining(), reservoir, "{gas_limit}"); + let mut satin = mega_outcome.result_and_state; + let registry = satin.state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("the read"); + assert!(!registry.is_touched(), "a read-only entry"); + assert_eq!(registry.storage.keys().collect::>(), [&CURRENT_SYSTEM_ADDRESS]); + assert_same(&satin, &op_outcome); + } +} diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs new file mode 100644 index 000000000..fd026b07a --- /dev/null +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -0,0 +1,1288 @@ +//! EIP-7708 transfer logs: what the data size counts them at, where, and where they stop. +//! +//! Every value movement emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm +//! journals itself — no `LOG` opcode runs — and the receipt carries. Satin counts it by the rule a +//! `LOG3` carrying one word is counted, 160 bytes, on the lane of the frame whose journal +//! checkpoint holds the move, and charges it nothing: +//! +//! - a frame start that moves value — the transaction's own value, a value `CALL`, a creation's +//! endowment — counts its log with the frame's records, before revm builds the frame, so a +//! crossing answers the frame with the stop before any value moves; +//! - a `SELFDESTRUCT` that moves a balance counts its log with the beneficiary's record, once the +//! opcode completed, and a crossing stops the destructing frame, which takes the move back. +//! +//! Every site runs below the execution cap and above it, and is pinned four ways: the exact bytes +//! it adds and the log the receipt carries; a frame budget one byte short of them, which stops the +//! frame that moves the value and lets its caller resume; the transaction's limit one byte short, +//! which does the same, and stops the transaction when the frame is its own; and a failure above +//! the move, which takes the log and its bytes back. Each stop is the one a `LOG3` of one word +//! makes in the same place, where the same bytes are counted: its twin below. +//! +//! A frame start is counted before revm decides it. A start revm refuses on its caller's account +//! — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — counts +//! nothing, and runs under a limit as it does without one; a creation onto an occupied address is +//! counted, and revm refuses it after the count. + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, keccak256, Address, Bytes, Log, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + history_gas, log_history_bytes, + system::{ + IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{is_transfer_log, op_transaction, transfer_log, BytecodeBuilder, MemoryDatabase}, + transaction_body_bytes, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, + MegaEvm, MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, TRANSFER_LOG_SIZE, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLDATASIZE, DELEGATECALL, GAS, JUMPDEST, JUMPI, LOG1, POP, PUSH0, PUSH1, + REVERT, SELFDESTRUCT, STOP, + }, + context::{ + result::{ExecutionResult, Output}, + TxEnv, + }, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue}, + Database, Inspector, +}; + +use crate::common::{account_state_gas, context, execute_under, history_rounds, share}; + +const CALLER: Address = address!("0000000000000000000000000000000000d00000"); +/// The contract a nested site's transaction calls: it calls [`ACTOR`] and returns what that +/// returned. +const RELAY: Address = address!("0000000000000000000000000000000000d00001"); +/// The contract that moves the value, or starts the frame that does. +const ACTOR: Address = address!("0000000000000000000000000000000000d00002"); +/// A contract whose code stops. +const RECEIVER: Address = address!("0000000000000000000000000000000000d00003"); +/// An account with no code. +const PAYEE: Address = address!("0000000000000000000000000000000000d00004"); +/// A contract that destructs to [`RECEIVER`], holding [`VALUE`]. +const DESTRUCTOR: Address = address!("0000000000000000000000000000000000d00005"); +/// A contract that reverts. +const REVERTER: Address = address!("0000000000000000000000000000000000d00006"); +/// The twin of a moving frame: a contract that writes slots and then emits a `LOG3` of one word. +const TWIN: Address = address!("0000000000000000000000000000000000d00007"); +/// The identity precompile. +const IDENTITY: Address = address!("0000000000000000000000000000000000000004"); +/// The sender of a deposit. +const DEPOSITOR: Address = address!("0000000000000000000000000000000000d000de"); + +/// What every site moves. +const VALUE: u64 = 1_000; + +const GAS_LIMITS: [u64; 2] = [20_000_000, TX_GAS_LIMIT_CAP + 100_000_000]; + +/// Where a value movement happens. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Site { + /// The transaction's own value, to a contract. + TxValue, + /// A creation transaction's endowment. + TxEndowment, + /// A value `CALL` to a contract, which revm builds a frame for. + Call, + /// A value `CALL` to an account with no code, which revm answers without running. + CallWithoutCode, + /// A value `CALL` to a precompile. + CallToPrecompile, + /// A `CREATE`'s endowment. + Create, + /// A `CREATE2`'s endowment. + Create2, + /// A `SELFDESTRUCT` moving its account's balance to another account. + SelfDestruct, +} + +/// How a site's program runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Variant { + /// The move, as it is. + Plain, + /// The same bytes on the same lane with no value moved, the last of them a `LOG3` of one word + /// where the transfer log is. + Twin, + /// The move, then a failure above it that takes it back. + TakenBack, +} + +impl Site { + const ALL: [Self; 8] = [ + Self::TxValue, + Self::TxEndowment, + Self::Call, + Self::CallWithoutCode, + Self::CallToPrecompile, + Self::Create, + Self::Create2, + Self::SelfDestruct, + ]; + + /// The depth of the frame whose lane holds the log: the transaction's own, or the one the + /// actor starts. + const fn depth(self) -> u32 { + match self { + Self::TxValue | Self::TxEndowment => 0, + _ => 2, + } + } + + /// The write records the move makes: the recipient's or the created account's, and the + /// caller's own below the transaction's frame; a destruction's beneficiary alone. + const fn records(self) -> u64 { + match self { + Self::TxValue | Self::TxEndowment | Self::SelfDestruct => 1, + _ => 2, + } + } + + /// The bytes the move counts on its frame's lane: its records and its transfer log. + const fn bytes(self) -> u64 { + self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE + } + + /// What a stop at the move leaves counted beside the body: the nonce record a creation + /// stopped at its start leaves its creator; nothing otherwise. + const fn left_by_a_stop(self) -> LimitUsage { + match self { + Self::Create | Self::Create2 => { + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 } + } + _ => LimitUsage::ZERO, + } + } + + /// The account the value moves to. The sender and the actor start at nonce zero. + fn recipient(self) -> Address { + match self { + Self::TxValue | Self::Call | Self::SelfDestruct => RECEIVER, + Self::TxEndowment => CALLER.create(0), + Self::CallWithoutCode => PAYEE, + Self::CallToPrecompile => IDENTITY, + Self::Create => ACTOR.create(0), + Self::Create2 => ACTOR.create2(B256::ZERO, keccak256([])), + } + } + + /// The log the twin emits where the transfer log is: a `LOG3` of three zero topics and one + /// zero word, from the account whose code ran it — [`TWIN`], or the account the twin creates. + fn twin_log(self) -> Log { + let twin_init = BytecodeBuilder::default().log3_word().stop().build(); + let address = match self { + Self::TxValue | + Self::Call | + Self::CallWithoutCode | + Self::CallToPrecompile | + Self::SelfDestruct => TWIN, + Self::TxEndowment => CALLER.create(0), + Self::Create => ACTOR.create(0), + Self::Create2 => ACTOR.create2(B256::ZERO, keccak256(&twin_init)), + }; + Log::new_unchecked(address, Vec::from([B256::ZERO; 3]), Bytes::from([0; 32])) + } + + /// The account the value moves from. + const fn sender(self) -> Address { + match self { + Self::TxValue | Self::TxEndowment => CALLER, + Self::SelfDestruct => DESTRUCTOR, + _ => ACTOR, + } + } + + /// What the actor does: the move, or its twin. + fn actor(self, variant: Variant) -> BytecodeBuilder { + let code = BytecodeBuilder::default(); + let value = U256::from(VALUE); + let twin_init = BytecodeBuilder::default().log3_word().stop().build(); + match (self, variant) { + ( + Self::Call | Self::CallWithoutCode | Self::CallToPrecompile | Self::SelfDestruct, + Variant::Twin, + ) => code.call(TWIN, U256::ZERO), + (Self::Call, _) => code.call(RECEIVER, value), + (Self::CallWithoutCode, _) => code.call(PAYEE, value), + (Self::CallToPrecompile, _) => code.call(IDENTITY, value), + (Self::Create, Variant::Twin) => code.create(U256::ZERO, twin_init), + (Self::Create, _) => code.create(value, []), + (Self::Create2, Variant::Twin) => code.create2(U256::ZERO, twin_init, U256::ZERO), + (Self::Create2, _) => code.create2(value, [], U256::ZERO), + (Self::SelfDestruct, _) => code.call(DESTRUCTOR, U256::ZERO), + (Self::TxValue | Self::TxEndowment, _) => unreachable!("the transaction moves it"), + } + } + + /// The database and the transaction of `variant`, at `gas_limit`. + fn program(self, variant: Variant, gas_limit: u64) -> (MemoryDatabase, MegaTransaction) { + // The twin a call reaches writes a slot for each record the move makes, then logs; a + // creation's twin makes the move's records by creating, and its init code logs. + let mut twin = BytecodeBuilder::default(); + for slot in 0..self.records() { + twin = twin.sstore(U256::from(slot + 1), U256::from(1)); + } + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(10 * VALUE)) + .account_balance(DESTRUCTOR, U256::from(VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(REVERTER, Bytes::from_static(&[PUSH0, PUSH0, REVERT])) + .account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(RECEIVER).build()) + .account_code(TWIN, twin.log3_word().stop().build()); + let tx = |kind, value: u64, data: Bytes| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind, + value: U256::from(value), + data, + gas_limit, + ..Default::default() + })) + }; + match (self, variant) { + (Self::TxValue, Variant::Plain) => { + (db, tx(TxKind::Call(RECEIVER), VALUE, Bytes::new())) + } + (Self::TxValue, Variant::Twin) => (db, tx(TxKind::Call(TWIN), 0, Bytes::new())), + (Self::TxValue, Variant::TakenBack) => { + (db, tx(TxKind::Call(REVERTER), VALUE, Bytes::new())) + } + (Self::TxEndowment, Variant::Plain) => (db, tx(TxKind::Create, VALUE, Bytes::new())), + (Self::TxEndowment, Variant::Twin) => { + (db, tx(TxKind::Create, 0, BytecodeBuilder::default().log3_word().stop().build())) + } + (Self::TxEndowment, Variant::TakenBack) => { + (db, tx(TxKind::Create, VALUE, Bytes::from_static(&[PUSH0, PUSH0, REVERT]))) + } + (_, variant) => { + let actor = self.actor(variant).append(POP); + let actor = match variant { + Variant::TakenBack => actor.revert_with_returndata(), + Variant::Plain | Variant::Twin => actor.return_returndata(), + }; + let relay = BytecodeBuilder::default() + .call(ACTOR, U256::ZERO) + .append(POP) + .return_returndata() + .build(); + let db = db.account_code(ACTOR, actor.build()).account_code(RELAY, relay); + (db, tx(TxKind::Call(RELAY), 0, Bytes::new())) + } + } + } +} + +/// The budget of a frame at `depth` under a frame cap of `cap`, when no frame above it has kept +/// anything yet. +fn budget(depth: u32, cap: u64) -> u64 { + (0..depth).fold(cap, |budget, _| share(budget)) +} + +/// The smallest frame cap under which the frame at `depth` has exactly `bytes` of budget. +fn cap_for(depth: u32, bytes: u64) -> u64 { + let cap = (bytes..).find(|cap| budget(depth, *cap) >= bytes).unwrap(); + assert_eq!(budget(depth, cap), bytes, "a cap that gives exactly the bytes"); + assert_eq!(budget(depth, cap - 1), bytes - 1, "and one byte less under one less"); + cap +} + +/// A deposit from [`DEPOSITOR`] of `value`, with `mint` credited to it before any frame. +fn deposit(kind: TxKind, mint: u128, value: u64) -> MegaTransaction { + let mut tx = OpTx(op_transaction(TxEnv { + caller: DEPOSITOR, + kind, + value: U256::from(value), + // Room for the depositor's account and the one it creates or pays, at the byte prices in + // effect. + gas_limit: 1_000_000 + 2 * account_state_gas(), + gas_price: 0, + ..Default::default() + })); + tx.0.deposit.source_hash = B256::repeat_byte(0x11); + tx.0.deposit.mint = Some(mint); + tx +} + +/// The transfer logs the receipt carries. +fn transfer_logs(outcome: &MegaTransactionOutcome) -> Vec { + outcome.result.logs().iter().filter(|log| is_transfer_log(log)).cloned().collect() +} + +fn balance(outcome: &MegaTransactionOutcome, address: Address) -> U256 { + outcome.state.get(&address).map(|account| account.info.balance).unwrap_or_default() +} + +/// Asserts what the reservoir of a run above the execution cap says: the state and history it +/// spent came out of it, and nothing else did. +fn assert_reservoir_paid(case: &str, gas_limit: u64, outcome: &MegaTransactionOutcome) { + if gas_limit <= TX_GAS_LIMIT_CAP { + return; + } + let reservoir = gas_limit - TX_GAS_LIMIT_CAP; + assert_eq!( + outcome.gas.reservoir_remaining, + reservoir - outcome.gas.state - outcome.gas.history, + "{case}: the reservoir paid the state and history ledgers and nothing else", + ); +} + +/// Asserts `outcome` is `site`'s `variant` run to its end: the one log the receipt carries — the +/// transfer log, or the twin's `LOG3` of one word — the value at the recipient, the body, the +/// records and that log counted, and the history of the body and the records, with the twin's +/// log on top: a transfer log is charged nothing. +fn assert_completed( + case: &str, + site: Site, + variant: Variant, + outcome: &MegaTransactionOutcome, + body: u64, +) { + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}: no stop"); + let (log, moved, log_history) = match variant { + Variant::Plain => { + let value = U256::from(VALUE); + (transfer_log(site.sender(), site.recipient(), value), value, 0) + } + Variant::Twin => (site.twin_log(), U256::ZERO, log_history_bytes(3, 32)), + Variant::TakenBack => unreachable!("a move taken back does not complete"), + }; + assert_eq!(outcome.result.logs(), [log], "{case}: the receipt's one log"); + assert_eq!(balance(outcome, site.recipient()), moved, "{case}: the value at the recipient"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body + site.bytes(), write_records: site.records() }, + "{case}: the body, the records and one log", + ); + let history_bytes = body + site.records() * WRITE_RECORD_SIZE + log_history; + assert_eq!(outcome.gas.history_bytes, history_bytes, "{case}: the history bytes"); + // The body, the records and the log are charged apart, which a history byte priced at a + // fraction of a gas rounds one by one. + if !history_rounds() { + assert_eq!( + outcome.gas.history, + history_gas(history_bytes).unwrap(), + "{case}: their history" + ); + } +} + +/// Asserts `outcome` is `site` stopped at its move by `stop`, with nothing of the move left: no +/// transfer log, no value moved, and only what a stop leaves beside the body counted. +fn assert_stopped_at_the_move( + case: &str, + site: Site, + outcome: &MegaTransactionOutcome, + body: u64, + stop: MegaLimitExceeded, +) { + assert!(!outcome.result.is_halt(), "{case}: a stop is a revert: {:?}", outcome.result); + assert_eq!( + outcome.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the stop is what the transaction reports", + ); + assert!(transfer_logs(outcome).is_empty(), "{case}: no transfer log"); + assert_eq!(balance(outcome, site.recipient()), U256::ZERO, "{case}: no value moved"); + let left = site.left_by_a_stop(); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body + left.data_size, write_records: left.write_records }, + "{case}: the move's bytes are not counted", + ); +} + +/// Each site adds exactly its records and one transfer log to the data size, and the receipt +/// carries the log: `Transfer(from, to, amount)` from `0xff…fe`. The history the transaction +/// pays, and the history bytes it reports, are its body and its records alone. +#[test] +fn test_each_site_counts_its_transfer_log() { + for site in Site::ALL { + for gas_limit in GAS_LIMITS { + let case = format!("{site:?} at {gas_limit}"); + let (db, tx) = site.program(Variant::Plain, gas_limit); + let body = transaction_body_bytes(&tx); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + + assert_completed(&case, site, Variant::Plain, &outcome, body); + assert_reservoir_paid(&case, gas_limit, &outcome); + } + } +} + +/// A frame budget holds the move at exactly its bytes, and one byte short of them stops the frame +/// that moves the value before anything moves, frame-locally: the caller resumes — the relay and +/// the actor return the stop as their output — and the transaction reports no stop. The +/// transaction's own frame has no caller, so its stop reverts the transaction, and the outcome +/// names it, the crossing that produced that frame's result. +/// +/// A `LOG3` of one word where the transfer log is, after the same bytes of records, stops the +/// same frame at the same budget with the same revert. +#[test] +fn test_each_site_stops_one_byte_short_of_its_frame_budget() { + for site in Site::ALL { + let cap = cap_for(site.depth(), site.bytes()); + for gas_limit in GAS_LIMITS { + for variant in [Variant::Plain, Variant::Twin] { + let case = format!("{site:?} {variant:?} at {gas_limit}"); + let run = |cap| { + let (db, tx) = site.program(variant, gas_limit); + let body = transaction_body_bytes(&tx); + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap); + (execute_under(db, tx, limits), body) + }; + + let (fits, body) = run(cap); + assert_completed(&format!("{case}: at the budget"), site, variant, &fits, body); + assert_reservoir_paid(&case, gas_limit, &fits); + + let (over, body) = run(cap - 1); + let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: site.bytes() - 1, + used: site.bytes(), + frame_local: true, + }); + assert_eq!( + over.limit_exceeded, own_frames, + "{case}: the outcome names the transaction's own frame's stop alone" + ); + assert_eq!( + over.result.is_success(), + site.depth() > 0, + "{case}: the caller resumes: {:?}", + over.result + ); + let stop = MegaLimitExceeded { + kind: LimitKind::DataSize.as_u8(), + limit: site.bytes() - 1, + }; + match variant { + Variant::Plain => assert_stopped_at_the_move(&case, site, &over, body, stop), + Variant::Twin => { + assert_eq!( + over.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the same stop", + ); + let left = site.left_by_a_stop(); + assert_eq!(over.usage.data_size - body, left.data_size, "{case}"); + assert!(over.result.logs().is_empty(), "{case}: the log went"); + } + Variant::TakenBack => unreachable!(), + } + assert_reservoir_paid(&case, gas_limit, &over); + } + } + } +} + +/// The transaction's limit one byte short of the move stops the frame that moves the value there, +/// as its budget does: the stop names the data size and the transaction's limit, the caller +/// resumes — the relay and the actor return the stop as their output — and the move's bytes go +/// with the frame. At the transaction's own frame the stop is the transaction's result, the +/// outcome names it with the move's bytes in the figure that crossed, and a limit of exactly the +/// bytes holds. A `LOG3` of one word where the transfer log is, after the same bytes of records, +/// crosses the same way. +#[test] +fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { + for site in Site::ALL { + for gas_limit in GAS_LIMITS { + for variant in [Variant::Plain, Variant::Twin] { + let case = format!("{site:?} {variant:?} at {gas_limit}"); + let run = |over: u64| { + let (db, tx) = site.program(variant, gas_limit); + let body = transaction_body_bytes(&tx); + let limit = body + site.bytes() - over; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + (execute_under(db, tx, limits), body, limit) + }; + + let (outcome, body, limit) = run(1); + let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: body + site.bytes(), + frame_local: false, + }); + assert_eq!( + outcome.limit_exceeded, own_frames, + "{case}: the outcome names the transaction's own frame's stop alone", + ); + assert_eq!( + outcome.result.is_success(), + site.depth() > 0, + "{case}: the caller resumes: {:?}", + outcome.result + ); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + match variant { + Variant::Plain => { + assert_stopped_at_the_move(&case, site, &outcome, body, stop); + } + Variant::Twin => { + assert_eq!( + outcome.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the same stop", + ); + let left = site.left_by_a_stop(); + assert_eq!(outcome.usage.data_size - body, left.data_size, "{case}"); + assert!(outcome.result.logs().is_empty(), "{case}: the log went"); + } + Variant::TakenBack => unreachable!(), + } + assert_reservoir_paid(&case, gas_limit, &outcome); + + if site.depth() == 0 { + let (fits, body, _) = run(0); + assert_completed(&format!("{case}: at the limit"), site, variant, &fits, body); + assert_reservoir_paid(&case, gas_limit, &fits); + } + } + } + } +} + +/// A failure above the move takes the transfer log back with the move, and its bytes with them: +/// the actor reverting after it, or the transaction's own frame failing. What is left counted is +/// the body. +#[test] +fn test_a_failure_takes_each_sites_transfer_log_back() { + for site in Site::ALL { + for gas_limit in GAS_LIMITS { + let case = format!("{site:?} at {gas_limit}"); + let (db, tx) = site.program(Variant::TakenBack, gas_limit); + let body = transaction_body_bytes(&tx); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + + assert_eq!(outcome.limit_exceeded, None, "{case}"); + assert!(!outcome.result.is_halt(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.result.is_success(), site.depth() > 0, "{case}: the relay resumes"); + assert!(outcome.result.logs().is_empty(), "{case}: the log went with the move"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + if site == Site::SelfDestruct { + assert_eq!(balance(&outcome, DESTRUCTOR), U256::from(VALUE), "{case}"); + } + assert_eq!(balance(&outcome, site.recipient()), U256::ZERO, "{case}"); + assert_reservoir_paid(&case, gas_limit, &outcome); + } + } +} + +/// Nothing moves to another account, so nothing is logged or counted for a log: a `CALLCODE` and a +/// `CALL` to itself move value from an account to itself; a transaction's value to its own sender +/// likewise; a destruction to itself burns the balance of an account created in the transaction +/// — this revm emits no log for a burn — and leaves an older account's balance where it is; a +/// value call a system contract refuses moves nothing at all. +#[test] +fn test_no_transfer_log_where_no_value_moves_to_another_account() { + let value = U256::from(VALUE); + let burner = BytecodeBuilder::default().append(ADDRESS).append(SELFDESTRUCT).build(); + let refused = BytecodeBuilder::default() + .mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append_many([PUSH0, PUSH1, 1]) + .push_address(ACCESS_CONTROL_ADDRESS) + .append(GAS) + .append(CALL); + let db = |actor: BytecodeBuilder| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(10 * VALUE)) + .account_code(ACTOR, actor.append(POP).stop().build()) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_balance(DESTRUCTOR, value) + .account_code(DESTRUCTOR, burner.clone()) + }; + let call = |to, value: u64| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + value: U256::from(value), + gas_limit: 20_000_000, + ..Default::default() + })) + }; + let actor = BytecodeBuilder::default; + // `ACTOR` calling itself once. Without calldata it calls `ACTOR` with `value` and one byte of + // calldata; the frame that call starts sees the byte and jumps past the call. The zero pushed + // first stands in, on that inner frame, for the flag the call leaves on the outer one, for the + // `POP` every actor ends with. + let self_call = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH1, 1, PUSH0]) + .push_u256(value) + .push_address(ACTOR) + .append_many([GAS, CALL]); + // `PUSH0; CALLDATASIZE; PUSH1 end; JUMPI; POP` is six bytes, then the call, then `end`. + let end = u8::try_from(6 + self_call.len()).expect("the call ends before byte 256"); + let calls_itself_once = BytecodeBuilder::default() + .append_many([PUSH0, CALLDATASIZE, PUSH1, end, JUMPI, POP]) + .append_many(self_call.build_vec()) + .append(JUMPDEST); + let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize); 7] = [ + ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 1, 0), + // The move's sender and recipient are one account, recorded once. + ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 1, 0), + ("a zero-value CALL", db(actor().call(RECEIVER, U256::ZERO)), call(ACTOR, 0), 0, 0), + ("a transaction's value to its sender", db(actor()), call(CALLER, VALUE), 0, 0), + ( + "a creation that destructs to itself: its endowment's log alone", + db(actor().create(value, &burner)), + call(ACTOR, 0), + 2, + 1, + ), + ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0), + ("a value call a system contract refuses", db(refused), call(ACTOR, 0), 0, 0), + ]; + for (name, db, tx, records, logs) in cases { + let body = transaction_body_bytes(&tx); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.result.logs().len(), logs, "{name}: the logs"); + assert_eq!(transfer_logs(&outcome).len(), logs, "{name}: the transfer logs"); + assert_eq!( + outcome.usage, + LimitUsage { + data_size: body + records * WRITE_RECORD_SIZE + logs as u64 * TRANSFER_LOG_SIZE, + write_records: records, + }, + "{name}", + ); + } + let burned = execute_under( + db(actor().create(value, &burner)), + call(ACTOR, 0), + EvmTxRuntimeLimits::no_limits(), + ); + let created = ACTOR.create(burned.state[&ACTOR].info.nonce - 1); + assert_eq!(balance(&burned, created), U256::ZERO, "the endowment was burned"); + assert_eq!(balance(&burned, ACTOR), U256::from(9 * VALUE)); + let older = execute_under(db(actor()), call(DESTRUCTOR, 0), EvmTxRuntimeLimits::no_limits()); + assert_eq!(balance(&older, DESTRUCTOR), value, "an older account keeps its balance"); +} + +/// A start revm refuses on its caller's account moves nothing and writes nothing, so nothing is +/// counted for it, and no limit stops it for what it would have counted: it runs as it does with +/// no limit. Here, a value call its caller cannot fund, which revm answers with `OutOfFunds` and no +/// data, which the actor returns: a `CALL`, whose move would count two records and a transfer log, +/// and a `CALLCODE`, whose move to its own account would count the caller's record alone. Neither +/// the transaction's limit nor the frame's budget one byte short of those bytes changes anything. +/// The same call funded to the last wei is made, and both stop it there. +#[test] +fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { + let value = U256::from(VALUE); + let db = |held: u64, actor: &Bytes| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(held)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(ACTOR, actor.clone()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let actor = |call: BytecodeBuilder| call.append(POP).return_returndata().build(); + let cases = [ + ( + "a CALL", + actor(BytecodeBuilder::default().call(RECEIVER, value)), + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + ), + ( + "a CALLCODE", + actor(BytecodeBuilder::default().callcode(RECEIVER, value)), + WRITE_RECORD_SIZE, + ), + ]; + for (name, actor, bytes) in cases { + let tx_limit = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + bytes - 1); + let frame_budget = + EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap_for(1, bytes - 1)); + + let free = + execute_under(db(VALUE - 1, &actor), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{name}: {:?}", free.result); + assert_eq!(free.result.output(), Some(&Bytes::new()), "{name}: the refusal's empty data"); + assert!(free.result.logs().is_empty(), "{name}"); + assert_eq!(free.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + assert_eq!(balance(&free, ACTOR), U256::from(VALUE - 1), "{name}: nothing moved"); + for limits in [tx_limit, frame_budget] { + let limited = execute_under(db(VALUE - 1, &actor), tx.clone(), limits); + assert_eq!(limited.limit_exceeded, None, "{name} under {limits:?}"); + assert_eq!(limited.result, free.result, "{name} under {limits:?}"); + assert_eq!(limited.usage, free.usage, "{name} under {limits:?}"); + assert_eq!(limited.gas, free.gas, "{name} under {limits:?}"); + } + + let stopped = execute_under(db(VALUE, &actor), tx.clone(), tx_limit); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: body + bytes - 1 }; + assert_eq!( + stopped.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{name}: funded to the last wei, the move is counted, and stopped at the limit", + ); + assert_eq!(stopped.limit_exceeded, None, "{name}: the actor caught the stop"); + let stopped = execute_under(db(VALUE, &actor), tx.clone(), frame_budget); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: bytes - 1 }; + assert_eq!( + stopped.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{name}: funded to the last wei, the move is stopped at its frame's budget", + ); + } +} + +/// A value call its caller cannot fund is charged nothing for the records it would make, as it +/// counts none: a caller that keeps less gas, once it has forwarded all it can, than those records' +/// history carries on past the refused call. Funded, the same call runs it out of gas at its +/// opcode, which shows the caller does keep less than that. +#[test] +fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { + let actor = + BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).append(POP).stop().build(); + let db = |held: u64| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(held)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(ACTOR, actor.clone()) + }; + let tx = |gas_limit| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit, + ..Default::default() + })) + }; + // About 150,000 gas for the actor, of which it keeps a sixty-fourth at its `CALL`: less than + // the history of the two records the move would make. Where 64 times that history is not + // above the 20,000 the actor needs to reach its `CALL`, as where a history byte costs + // nothing, no actor both reaches the call and keeps less than the records cost. + let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); + let actor_gas = (64 * records).saturating_sub(1).min(150_000); + if actor_gas < 20_000 { + return; + } + assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); + let gas_limit = 21_000 + history_gas(transaction_body_bytes(&tx(0))).unwrap() + actor_gas; + + let refused = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(refused.result.is_success(), "{:?}", refused.result); + let funded = execute_under(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(funded.result.is_halt(), "{:?}", funded.result); + let body = transaction_body_bytes(&tx(gas_limit)); + assert_eq!( + refused.usage, + LimitUsage { data_size: body, write_records: 0 }, + "the refused call counted nothing", + ); + assert_eq!( + refused.gas.history, + history_gas(body).unwrap(), + "and paid the body's history alone" + ); + assert_eq!(funded.gas.gas_used, gas_limit, "the funded call's halt used the whole gas limit"); +} + +/// Appends a call carrying [`VALUE`] to `MegaAccessControl`, which answers it with +/// `NonZeroTransfer()` before revm looks at the caller's balance, leaving the call's status on the +/// stack. From a caller that holds less, it is a start revm would refuse, answered before its +/// init. +fn call_the_system_contract_answers(code: BytecodeBuilder) -> BytecodeBuilder { + code.mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append(PUSH0) + .push_u256(U256::from(VALUE)) + .push_address(ACCESS_CONTROL_ADDRESS) + .append_many([GAS, CALL]) +} + +/// Whether revm refuses a start on its caller's account is found once, by the opcode starting it, +/// and taken by the frame's init. A start answered before its init leaves that answer behind: +/// here a value call its caller cannot fund, which the system contract answers with +/// `NonZeroTransfer()` before revm could refuse it. The frame the caller starts next takes none +/// of it: a `DELEGATECALL` whose two fresh slots cross its budget by a byte reverts on that +/// budget, as it does with no call before it, and keeps nothing. +#[test] +fn test_a_start_answered_before_its_init_leaves_no_refusal_for_the_next() { + const WRITER: Address = address!("0000000000000000000000000000000000d00008"); + let writer = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + // The `ACTOR` holds nothing, so revm would refuse the value; the system contract answers first. + let answered_call = call_the_system_contract_answers; + let delegate_to_writer = |code: BytecodeBuilder| { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(WRITER) + .append_many([GAS, DELEGATECALL]) + .return_top() + }; + let db = |actor: BytecodeBuilder| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(WRITER, writer.clone()) + .account_code(ACTOR, actor.build()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let limits = EvmTxRuntimeLimits::no_limits() + .with_frame_data_size_limit(cap_for(1, 2 * WRITE_RECORD_SIZE - 1)); + + let answer = execute_under( + db(answered_call(BytecodeBuilder::default()).append(POP).return_returndata()), + tx.clone(), + limits, + ); + assert_eq!( + answer.result.output(), + Some(&Bytes::from(IMegaAccessControl::NonZeroTransfer::SELECTOR.to_vec())), + "the system contract answers the call, not revm" + ); + + let cases = [ + ("alone", delegate_to_writer(BytecodeBuilder::default())), + ( + "after the answered call", + delegate_to_writer(answered_call(BytecodeBuilder::default()).append(POP)), + ), + ]; + for (name, actor) in cases { + let outcome = execute_under(db(actor), tx.clone(), limits); + assert_eq!( + outcome.result.output(), + Some(&Bytes::from(U256::ZERO.to_be_bytes::<32>())), + "{name}: the DELEGATECALL reverted on its budget", + ); + assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + } +} + +/// The answer a transaction's last start left behind is not taken by the next transaction's first +/// frame, whose own answer nothing staged: a deposit pays no history, so no record of its is +/// charged before execution and nothing asks its sender's account before the frame's init. Its +/// value to `RECEIVER` is counted — the recipient's record and the transfer log — as on an EVM +/// that ran nothing before it. +#[test] +fn test_an_answer_a_transaction_leaves_is_not_taken_by_the_next() { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code( + ACTOR, + call_the_system_contract_answers(BytecodeBuilder::default()).stop().build(), + ); + let answered = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + let user_deposit = || deposit(TxKind::Call(RECEIVER), 1_000, 400); + let body = transaction_body_bytes(&user_deposit()); + + let alone = execute_under(db.clone(), user_deposit(), EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())); + let first = evm.execute_transaction(answered).expect("the transaction is valid"); + assert!(first.result.is_success(), "{:?}", first.result); + let next = evm.execute_transaction(user_deposit()).expect("the transaction is valid"); + + assert_eq!( + next.usage, + LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + ); + assert_eq!(next.usage, alone.usage); + assert_eq!(next.result, alone.result); +} + +/// Raises the value of every call to [`RECEIVER`] by one wei as the call starts: an inspector's +/// rewrite of a frame's input after the opcode that starts it ran. +struct RaisesValue; + +impl Inspector, EthInterpreter> for RaisesValue { + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + if inputs.target_address == RECEIVER { + inputs.value = CallValue::Transfer(inputs.call_value() + U256::from(1)); + } + None + } +} + +/// An inspector may rewrite a frame's input after the opcode that starts it found whether revm +/// refuses it, so the inspected start asks again on the input the inspector leaves. The `ACTOR` +/// can fund the value its `CALL` carries and not the one the inspector raises it to: revm refuses +/// the start with `OutOfFunds` and no data, which the actor returns, and nothing is counted for +/// it — under a frame budget one byte short of the records and the transfer log the start would +/// count, which would stop it with the limit's revert data otherwise. +#[test] +fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { + let actor = BytecodeBuilder::default() + .call(RECEIVER, U256::from(VALUE)) + .append(POP) + .return_returndata() + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])) + .account_code(ACTOR, actor); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap_for(1, start - 1)); + + let outcome = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(RaisesValue) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::new()), "the refusal's empty data"); + assert!(transfer_logs(&outcome).is_empty(), "nothing moved"); + assert_eq!(balance(&outcome, ACTOR), U256::from(VALUE)); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.limit_exceeded, None); +} + +/// A creation onto an occupied address is the one refusal decided after its start is counted: +/// revm reads the created address's account only once it builds the frame, and reading it any +/// earlier would load it. Without a limit, the creation fails on the collision after it bumped its +/// creator's nonce, so the creator's record is kept, and the created account's record and the +/// transfer log are not. Under the transaction's limit one byte short of what the start counts, +/// the start's records and transfer log cross it, and the stop comes first: the creation returns +/// the stop rather than the collision's empty data, which the creator returns, and the creator +/// keeps its nonce record either way. +#[test] +fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() { + let occupied = Site::Create2.recipient(); + let actor = BytecodeBuilder::default() + .create2(U256::from(VALUE), [], U256::ZERO) + .append(POP) + .return_returndata() + .build(); + let db = || { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(10 * VALUE)) + .account_code(ACTOR, actor.clone()) + .account_nonce(occupied, 1) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + + let free = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_success(), "{:?}", free.result); + assert_eq!(free.result.output(), Some(&Bytes::new()), "the collision's empty data"); + assert!(free.result.logs().is_empty(), "no transfer log"); + assert_eq!(free.state[&ACTOR].info.nonce, 1, "the collision comes after the bump"); + assert_eq!(balance(&free, occupied), U256::ZERO, "no value moved"); + assert_eq!( + free.usage, + LimitUsage { data_size: body + WRITE_RECORD_SIZE, write_records: 1 }, + "the creator's nonce alone", + ); + + let limit = body + Site::Create2.bytes() - 1; + let stopped = + execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + assert!(stopped.result.is_success(), "the creator catches the stop: {:?}", stopped.result); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop first"); + assert_eq!(stopped.limit_exceeded, None); + assert_eq!(stopped.usage, free.usage, "the creator's nonce alone"); + assert_eq!(stopped.state[&ACTOR].info.nonce, 1, "the stopped creation bumped it too"); +} + +/// A deposit's value moves in its first frame and is logged there, from the depositor to the +/// recipient; its mint is credited before any frame and is logged nowhere. The log is counted in +/// the data size like any other, though a deposit pays no history, and a user's deposit is held +/// to the data-size limit at it. +#[test] +fn test_a_deposits_value_is_logged_and_its_mint_is_not() { + let db = || MemoryDatabase::default().account_code(RECEIVER, Bytes::from_static(&[STOP])); + + let tx = deposit(TxKind::Call(RECEIVER), 1_000, 400); + let body = transaction_body_bytes(&tx); + let outcome = execute_under(db(), tx, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.result.logs(), + [transfer_log(DEPOSITOR, RECEIVER, U256::from(400))], + "the value's log, and none for the mint", + ); + assert_eq!(balance(&outcome, DEPOSITOR), U256::from(600)); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + ); + assert_eq!((outcome.gas.history, outcome.gas.history_bytes), (0, 0), "a deposit pays none"); + + let minted = execute_under( + db(), + deposit(TxKind::Call(RECEIVER), 1_000, 0), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(minted.result.is_success(), "{:?}", minted.result); + assert!(minted.result.logs().is_empty(), "a mint alone is logged nowhere"); + assert_eq!(balance(&minted, DEPOSITOR), U256::from(1_000)); + + let limit = body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + let stopped = execute_under( + db(), + deposit(TxKind::Call(RECEIVER), 1_000, 400), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_eq!( + stopped.limit_exceeded.map(|stop| (stop.exceeded_limit(), stop.is_frame_local())), + Some((true, false)), + "a user's deposit is stopped at its transfer log", + ); + assert!(stopped.result.logs().is_empty()); + assert_eq!(balance(&stopped, DEPOSITOR), U256::from(1_000), "the mint stays, the value not"); +} + +/// A deposit its depositor cannot fund once the mint is credited is refused by revm at its first +/// frame, a call and a creation alike, and fails as a deposit does: the value does not move and +/// the gas limit is spent. Nothing of the move is counted, so the transaction's limit one byte +/// short of what the move would count changes nothing: the receipt is the failed deposit's, not a +/// stop. +#[test] +fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { + let db = || MemoryDatabase::default().account_code(RECEIVER, Bytes::from_static(&[STOP])); + for kind in [TxKind::Call(RECEIVER), TxKind::Create] { + let tx = deposit(kind, 1_000, 5_000); + let body = transaction_body_bytes(&tx); + let free = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(free.result.is_halt(), "{kind:?}: {:?}", free.result); + assert_eq!( + free.result.tx_gas_used(), + tx.0.base.gas_limit, + "{kind:?}: the gas limit is spent" + ); + assert!(free.result.logs().is_empty(), "{kind:?}"); + + let limit = body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + let limited = + execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + assert_eq!(limited.limit_exceeded, None, "{kind:?}"); + assert_eq!(limited.result, free.result, "{kind:?}"); + assert_eq!(limited.usage, free.usage, "{kind:?}"); + } +} + +/// A creation from an account whose nonce cannot be bumped is answered by revm with a success +/// that creates nothing and moves nothing: a `Return` with no address, and no log. It keeps +/// nothing either, and no limit stops it for what it did not do. +/// +/// No account reaches that nonce by executing: a transaction, a creation and an authorization +/// each add one and stop below it. So this takes a state the chain did not produce, as a genesis +/// allocation or a state override does. A deposit runs from it, its nonce being unchecked, and so +/// does a user's creation run with the nonce check off, as a simulation may, which pays history +/// for its body alone. +#[test] +fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { + let created_nothing = |outcome: &MegaTransactionOutcome| { + matches!(outcome.result, ExecutionResult::Success { output: Output::Create(_, None), .. }) && + outcome.result.logs().is_empty() + }; + + let tx = deposit(TxKind::Create, 1_000, 5); + let body = transaction_body_bytes(&tx); + let limit = body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ] { + let db = MemoryDatabase::default().account_nonce(DEPOSITOR, u64::MAX); + let outcome = execute_under(db, tx.clone(), limits); + assert!(created_nothing(&outcome), "{limits:?}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{limits:?}"); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{limits:?}"); + } + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_nonce(CALLER, u64::MAX); + let ctx = context(db); + let mut cfg = ctx.mega_cfg().clone(); + cfg.disable_nonce_check = true; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + value: U256::from(VALUE), + gas_limit: 20_000_000, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let outcome = MegaEvm::new(ctx.with_cfg(cfg)) + .execute_transaction(tx) + .expect("the transaction is valid with the nonce check off"); + assert!(created_nothing(&outcome), "{:?}", outcome.result); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.gas.history_bytes, body, "its body alone"); + assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "and the history of its body"); +} + +/// A system transaction moves no value in the shape the sequencer builds it, so it logs nothing. +/// One that does move value is logged and counted like any other, and — the protocol's own work — +/// no data-size limit stops it at the log. +#[test] +fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { + let db = || { + MemoryDatabase::default() + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(VALUE)) + .account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[STOP])) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) + }; + let system = |value: u64| { + OpTx(op_transaction(TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + value: U256::from(value), + gas_limit: 1_000_000, + ..Default::default() + })) + }; + + let quiet = execute_under(db(), system(0), EvmTxRuntimeLimits::no_limits()); + assert!(quiet.result.is_success(), "{:?}", quiet.result); + assert!(quiet.result.logs().is_empty(), "a valueless system transaction logs nothing"); + + let tx = system(VALUE); + let body = transaction_body_bytes(&tx); + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0), + ] { + let outcome = execute_under(db(), tx.clone(), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!( + outcome.result.logs(), + [transfer_log(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, U256::from(VALUE))], + ); + assert_eq!( + outcome.usage, + LimitUsage { + data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 1 + }, + "counted all the same", + ); + } +} + +/// EIP-7708 logs keep execution order. [S14.3] +/// +/// independent: each expected log is the event the bytecode emits, or the transfer of the wei +/// the program moves, built from those accounts and that amount. +/// +/// A frame that emits `LOG1` and then `SELFDESTRUCT`s to another account journals the event +/// first and the transfer once the opcode has moved the balance, so the receipt is +/// `[event, transfer]`. +/// A `CREATE` that endows the new account journals that transfer with the creation's start, +/// before the init code runs, so an init code that emits `LOG1` leaves `[transfer, event]`. +#[test] +fn test_transfer_logs_keep_execution_order() { + const MOVED: u64 = 7; + let marker = B256::repeat_byte(0x4d); + // Regular room, the new account a creation adds, and sixty-four times the history of a few + // records: the creation is forwarded all but a 64th of the gas, and the caller pays the + // records from the 64th it keeps, at whatever a byte costs. + let gas_limit = 2_000_000 + + 2 * account_state_gas() + + crate::common::body_history(0) + + 64 * mega_evm::write_record_history_gas(4).expect("records have a price"); + + let event = |address| Log::new_unchecked(address, vec![marker], Bytes::new()); + + let destructor = BytecodeBuilder::default() + .push_bytes(marker) + .append_many([PUSH0, PUSH0, LOG1]) + .selfdestruct(RECEIVER) + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(DESTRUCTOR, U256::from(MOVED)) + .account_balance(RECEIVER, U256::from(1)) + .account_code(DESTRUCTOR, destructor); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(DESTRUCTOR), + gas_limit, + ..Default::default() + })); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "SELFDESTRUCT: {:?}", outcome.result); + assert_eq!( + outcome.result.logs(), + [event(DESTRUCTOR), transfer_log(DESTRUCTOR, RECEIVER, U256::from(MOVED)),], + "LOG1 then SELFDESTRUCT", + ); + assert_eq!(balance(&outcome, RECEIVER), U256::from(1 + MOVED)); + + let init = BytecodeBuilder::default() + .push_bytes(marker) + .append_many([PUSH0, PUSH0, LOG1]) + .stop() + .build(); + let actor = + BytecodeBuilder::default().create(U256::from(MOVED), init).append(POP).stop().build(); + let created = ACTOR.create(0); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, U256::from(MOVED)) + .account_nonce(ACTOR, 0) + .account_code(ACTOR, actor); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit, + ..Default::default() + })); + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success(), "CREATE: {:?}", outcome.result); + assert_eq!( + outcome.result.logs(), + [transfer_log(ACTOR, created, U256::from(MOVED)), event(created),], + "an endowed creation's init code", + ); + assert_eq!(balance(&outcome, created), U256::from(MOVED)); +} diff --git a/crates/mega-evm/tests/satin/volatile_access.rs b/crates/mega-evm/tests/satin/volatile_access.rs new file mode 100644 index 000000000..39a429a00 --- /dev/null +++ b/crates/mega-evm/tests/satin/volatile_access.rs @@ -0,0 +1,865 @@ +//! Volatile reads the legacy engine's tests pinned, on Satin's gas detention: what records a +//! read, which read sets the limit, where the Oracle's storage is read and where it is not, who +//! is exempt, and how a refused read keeps the failures an opcode has on its own. +//! +//! The legacy engine's switch was steered through `MegaAccessControl`; here the tests switch it +//! off with `MegaContext::with_volatile_access_disabled_from`, as if the frame at that depth had +//! called `disableVolatileDataAccess()` first. + +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::ORACLE_ACCESS_COMPUTE_GAS, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{op_transaction, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase}, + volatile_data_access_disabled_revert_data, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, + MegaLimitExceeded, MegaTransaction, VolatileDataAccess, +}; +use op_revm::transaction::deposit::DEPOSIT_TRANSACTION_TYPE; +use revm::{ + bytecode::opcode::*, + context::{result::ExecutionResult, Transaction, TxEnv}, + context_interface::cfg::GasId, + interpreter::InstructionResult, + primitives::{eip2780::TX_BASE_COST, eip8038::COLD_ACCOUNT_ACCESS}, + state::Bytecode, +}; + +use crate::{ + common::body_history, + detention::{ + assert_caught, assert_stopped, burn, call, context, execute, intrinsic, on_beneficiary, op, + run_on, spin, stop_data, tx, with_delegation, work, Calls, Charges, BELOW, BENEFICIARY, + CALLER, CAP, CHILD, CONTRACT, DELEGATOR, TIERS, + }, + salt::entry, +}; + +/// A second contract, never the beneficiary. +const OTHER: Address = address!("0000000000000000000000000000000000d00004"); + +/// Rounds of [`work`] that spend more compute than the cap: 21,756,000. +const PAST_THE_CAP: u32 = 7_000; + +/* ---------- what records a read ---------- */ + +/// The transaction's and the chain's own fields, and a contract's own balance, record nothing; the +/// opcodes that read the block environment record their kinds in the matrix of reads. +#[test] +fn test_the_transactions_own_fields_record_nothing() { + for opcode in [ + revm::bytecode::opcode::CALLER, + ORIGIN, + GASPRICE, + CHAINID, + ADDRESS, + CALLVALUE, + SELFBALANCE, + GAS, + ] { + let code = op(BytecodeBuilder::default(), opcode).stop().build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, BELOW), + ); + assert!(run.outcome.result.is_success()); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{opcode:#04x}"); + assert_eq!(run.limit, None, "{opcode:#04x}"); + } +} + +/// Detention belongs to one transaction: the next one on the same EVM starts with nothing read +/// and no limit, and computes past the cap its predecessor was held to. +#[test] +fn test_detention_starts_afresh_for_every_transaction() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + let reader = op(call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS), TIMESTAMP); + let db = MemoryDatabase::default() + .account_code(CONTRACT, reader.stop().build()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle) + .account_code(OTHER, work(BytecodeBuilder::default(), PAST_THE_CAP).stop().build()); + let mut evm = MegaEvm::new(context(db)); + + let first = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(first.outcome.result.is_success()); + assert_eq!(first.accessed, VolatileDataAccess::ORACLE | VolatileDataAccess::TIMESTAMP); + assert!(first.limit.is_some()); + + let second = run_on(&mut evm, tx(CALLER, OTHER, BELOW)); + assert!(second.outcome.result.is_success(), "{:?}", second.outcome.result); + assert_eq!(second.accessed, VolatileDataAccess::empty()); + assert_eq!(second.limit, None); + assert!(second.outcome.gas.regular > CAP); +} + +/* ---------- which read sets the limit ---------- */ + +/// A read two frames down caps every caller: the middle frame and the transaction's own frame +/// resume on what the limit leaves them, and a transaction that stays within it bills what ran. +#[test] +fn test_a_read_two_frames_down_caps_every_caller() { + let nested = on_beneficiary(BytecodeBuilder::default(), BALANCE).stop().build(); + let middle = work(call(BytecodeBuilder::default(), CALL, DELEGATOR), 10).stop().build(); + for gas_limit in TIERS { + let db = |top: Bytes| { + MemoryDatabase::default() + .account_code(CONTRACT, top) + .account_code(CHILD, middle.clone()) + .account_code(DELEGATOR, nested.clone()) + }; + let run = execute( + db(spin(call(BytecodeBuilder::default(), CALL, CHILD))), + tx(CALLER, CONTRACT, gas_limit), + ); + // The reading frame's `POP`, the middle frame's `POP` and work, then the transaction's own + // frame's `POP` and loop, each in its own memory. + let left = Charges::default().then(&[2, 2]).work(10, 0).then(&[2]).spin(0).left(CAP); + let limit = assert_stopped(&run, intrinsic(gas_limit), left); + assert!(limit < CAP + 100_000, "the read was the third frame's first opcode: {limit}"); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + + let run = execute( + db(call(BytecodeBuilder::default(), CALL, CHILD).stop().build()), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success()); + assert!(run.outcome.result.gas().tx_gas_used() < 200_000 + body_history(0)); + } +} + +/// A read in a frame that reverts still happened: the limit it set outlives the frame, and the +/// caller that resumes is held to it. +#[test] +fn test_a_read_in_a_frame_that_reverts_still_caps() { + let beneficiary = BytecodeBuilder::default().revert().build(); + let child = call(BytecodeBuilder::default(), CALL, BENEFICIARY).revert().build(); + let parent = spin(call(BytecodeBuilder::default(), CALL, CHILD)); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child.clone()) + .account_code(BENEFICIARY, beneficiary.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + // The read is the child's call to the beneficiary: the beneficiary's revert — two + // `PUSH0` — the child's `POP` and its own revert, then its caller's `POP` and loop. + let left = Charges::default().then(&[2, 2, 2, 2, 2, 2]).spin(0).left(CAP); + let limit = assert_stopped(&run, intrinsic(gas_limit), left); + assert!(limit < CAP + 100_000, "{limit}"); + } +} + +/// A frame that reads and then crosses another transaction-level limit is stopped by that +/// limit: detention holds compute back and leaves the data size to its own limit. +#[test] +fn test_detention_leaves_a_data_size_stop_to_the_data_size_limit() { + let code = call(BytecodeBuilder::default(), CALL, BENEFICIARY) + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .stop() + .build(); + // Room above the body for one write record, not two. + let data_limit = mega_evm::TX_BODY_SIZE + 60; + for gas_limit in TIERS { + let db = MemoryDatabase::default().account_code(CONTRACT, code.clone()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits( + EvmTxRuntimeLimits::default().with_tx_data_size_limit(data_limit), + )); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + assert!(run.limit.is_some(), "the call read the beneficiary"); + assert!( + matches!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }) + ), + "{:?}", + run.outcome.limit_exceeded + ); + } +} + +/* ---------- the Oracle ---------- */ + +/// A frame reading the Oracle's slot 0, then spinning. +fn oracle_reads_then_spins() -> Bytes { + spin(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP])) +} + +/// Calling the Oracle is not reading its storage: without a load of a slot, nothing is detained, +/// and the caller computes past the cap. +#[test] +fn test_calling_the_oracle_without_reading_its_storage_detains_nothing() { + let oracle = BytecodeBuilder::default().stop().build(); + let code = work(call(BytecodeBuilder::default(), CALL, ORACLE_CONTRACT_ADDRESS), PAST_THE_CAP); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.limit, None); + assert!(run.outcome.gas.regular > CAP); +} + +/// The Oracle's own code is held to the cap once it read its storage, whether the transaction +/// calls it directly or through a frame, which catches its stop and ends on a `POP`, and whether +/// the call is a `CALL` or a `STATICCALL`. +#[test] +fn test_the_oracle_reading_its_own_storage_is_held_to_the_cap() { + assert_eq!(ORACLE_ACCESS_COMPUTE_GAS, CAP); + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + let db = || { + MemoryDatabase::default() + .account_code(ORACLE_CONTRACT_ADDRESS, oracle_reads_then_spins()) + }; + + // Whoever calls it, the Oracle's `POP` and loop come after its read. + let left = Charges::default().then(&[2]).spin(0).left(CAP); + let run = execute(db(), tx(CALLER, ORACLE_CONTRACT_ADDRESS, gas_limit)); + assert_eq!( + assert_stopped(&run, intrinsic, left), + CAP + 2 + 2_100, + "the direct call: PUSH0 and a cold SLOAD" + ); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); + + for scheme in [CALL, STATICCALL] { + let code = + call(BytecodeBuilder::default(), scheme, ORACLE_CONTRACT_ADDRESS).stop().build(); + let run = execute(db().account_code(CONTRACT, code), tx(CALLER, CONTRACT, gas_limit)); + assert_caught(&run, intrinsic, left, &Charges::default().then(&[2])); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE, "{scheme:#04x}"); + } + } +} + +/// `DELEGATECALL` and `CALLCODE` run the Oracle's code on the caller's storage: what they read is +/// the caller's, not the Oracle's, and nothing is detained. +#[test] +fn test_the_oracles_code_on_another_accounts_storage_reads_nothing_volatile() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + for scheme in [DELEGATECALL, CALLCODE] { + let code = + work(call(BytecodeBuilder::default(), scheme, ORACLE_CONTRACT_ADDRESS), PAST_THE_CAP); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{scheme:#04x}: {:?}", run.outcome.result); + assert_eq!(run.limit, None, "{scheme:#04x}"); + } +} + +/// A hint goes to the node's oracle service and reads nothing: `sendHint` detains nothing. +#[test] +fn test_a_hint_detains_nothing() { + let hint = + IOracle::sendHintCall { topic: B256::ZERO, data: Bytes::from_static(b"hint") }.abi_encode(); + let code = BytecodeBuilder::default() + .mstore(0, &hint) + .append_many([PUSH0, PUSH0]) + .push_number(hint.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]); + let db = MemoryDatabase::default() + .account_code(CONTRACT, work(code, PAST_THE_CAP).stop().build()) + .account_code(ORACLE_CONTRACT_ADDRESS, BytecodeBuilder::default().stop().build()); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.limit, None); +} + +/// The system address maintains the Oracle: its transaction reads the Oracle's storage and is not +/// detained. The same code run for anyone else is. +#[test] +fn test_the_system_address_is_not_detained() { + let oracle = work(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]), PAST_THE_CAP) + .stop() + .build(); + let db = || { + MemoryDatabase::default() + .account_code(ORACLE_CONTRACT_ADDRESS, oracle.clone()) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) + }; + + let system = op_transaction(TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + gas_limit: BELOW, + chain_id: Some(1), + ..Default::default() + }); + let run = execute(db(), alloy_op_evm::OpTx(system)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert!(!run.detains); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + assert_eq!(run.limit, None); + assert!(run.outcome.gas.regular > CAP); + + let run = execute(db(), tx(CALLER, ORACLE_CONTRACT_ADDRESS, BELOW)); + assert!(run.detains); + assert!( + matches!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "{:?}", + run.outcome.result + ); +} + +/// A user's deposit is detained. [S12.51] [S19.8] +/// +/// independent: the cap, the compute at the read and the bill are the spec's own numbers. +/// The cap is 20,000,000. +/// `TIMESTAMP` costs 2, `PUSH0` costs 2 and a cold `SLOAD` costs 2,100, so the compute at the +/// read is that opcode's gas. +/// The EIP-2780 intrinsic of a call to an existing account, with no value and no calldata, is +/// `TX_BASE_COST` (12,000) plus the recipient access (3,000). +/// What the loop leaves is the same hand count `Charges` makes: the `POP` after the read, the +/// push of the counter, one round that expands memory to 1,024 words, then rounds of 3,108 until +/// the next round's 3,072-gas copy no longer fits. +/// +/// A deposit pays no history gas, and a user's deposit is not system-originated. +/// The same body, run as a Mega System Transaction, reads the same thing and is not stopped. +#[test] +fn test_a_users_deposit_is_detained() { + // The spec's numbers, held equal to the constants the engine is built with. + const BLOCK_ENV_CAP: u64 = 20_000_000; + const ORACLE_CAP: u64 = 20_000_000; + const TIMESTAMP_GAS: u64 = 2; + const PUSH_GAS: u64 = 2; + const COLD_SLOAD: u64 = 2_100; + const BASE_INTRINSIC: u64 = 12_000; + const RECIPIENT_ACCESS: u64 = 3_000; + assert_eq!(BLOCK_ENV_CAP, CAP); + assert_eq!(BLOCK_ENV_CAP, ORACLE_CAP); + assert_eq!(ORACLE_CAP, ORACLE_ACCESS_COMPUTE_GAS); + assert_eq!(BASE_INTRINSIC, TX_BASE_COST); + assert_eq!(RECIPIENT_ACCESS, COLD_ACCOUNT_ACCESS); + assert_eq!(LimitKind::ComputeGas.as_u8(), 2); + let intrinsic = BASE_INTRINSIC + RECIPIENT_ACCESS; + assert_eq!(intrinsic, 15_000); + + // A source hash a user can carry: not empty, and not the protocol's own. + let source = B256::repeat_byte(0x11); + assert_ne!(source, B256::ZERO); + assert_ne!(source, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH); + assert_ne!(CALLER, MEGA_SYSTEM_ADDRESS); + assert_ne!(CALLER, mega_evm::SYSTEM_ADDRESS); + + // What a 20,000,000 allowance has left when the copy that crosses it is not made. + let left = allowance_after_the_read(BLOCK_ENV_CAP); + assert_eq!(left, 1_100); + assert_eq!(Charges::default().then(&[2]).work(PAST_THE_CAP, 0).left(BLOCK_ENV_CAP), left); + + let timestamp = work(op(BytecodeBuilder::default(), TIMESTAMP), PAST_THE_CAP).stop().build(); + let oracle = work(BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP]), PAST_THE_CAP) + .stop() + .build(); + assert_deposit_stopped( + "TIMESTAMP", + timestamp.clone(), + TIMESTAMP_GAS, + BLOCK_ENV_CAP, + VolatileDataAccess::TIMESTAMP, + intrinsic, + left, + source, + ); + assert_deposit_stopped( + "Oracle", + oracle.clone(), + PUSH_GAS + COLD_SLOAD, + ORACLE_CAP, + VolatileDataAccess::ORACLE, + intrinsic, + left, + source, + ); + assert_system_transaction_is_not_stopped("TIMESTAMP", timestamp, BLOCK_ENV_CAP); + assert_system_transaction_is_not_stopped("Oracle", oracle, ORACLE_CAP); +} + +/// What `allowance` has left after the `POP` that follows a volatile read and `work` of +/// `PAST_THE_CAP` rounds, at the spec's opcode costs. +/// +/// The first round expands memory from nothing to the 1,024 words the copy writes +/// (`3w + w²/512` = 5,120). Each later round costs 3,108. The round that crosses pays +/// `JUMPDEST`, the size push, two `PUSH0` and `MCOPY`'s static gas, and cannot pay the copy. +fn allowance_after_the_read(allowance: u64) -> u64 { + let mut left = allowance; + left -= 2; // the POP of the value the read pushed + left -= 3; // the push of the round counter + let words = 1_024u64; + let expansion = 3 * words + words * words / 512; + assert_eq!(expansion, 5_120); + let before_copy = 1 + 3 + 2 + 2 + 3; // JUMPDEST, PUSH of 0x8000, two PUSH0, MCOPY + let copy = 1_024 * 3; + assert_eq!(copy, 3_072); + let after_copy = 3 + 3 + 3 + 3 + 3 + 10; // PUSH1, SWAP1, SUB, DUP1, the dest push, JUMPI + left -= before_copy + copy + expansion + after_copy; + let round = before_copy + copy + after_copy; + assert_eq!(round, 3_108); + let full = left / round; + left -= full * round; + assert!(full < u64::from(PAST_THE_CAP) - 1, "the loop does not finish"); + left -= before_copy; + assert!(copy > left, "the copy is the charge that crosses"); + left +} + +/// `code` on the Oracle, as a user's deposit from `CALLER`. Both accounts already exist, so +/// the run adds no state. +fn user_deposit(source: B256) -> MegaTransaction { + let mut tx = alloy_op_evm::OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + gas_limit: BELOW, + gas_price: 0, + chain_id: Some(1), + ..Default::default() + })); + tx.0.deposit.source_hash = source; + tx.0.deposit.is_system_transaction = false; + assert_eq!(Transaction::tx_type(&tx.0), DEPOSIT_TRANSACTION_TYPE); + assert!(!mega_evm::system::is_system_originated(&tx, MEGA_SYSTEM_ADDRESS)); + tx +} + +fn deposit_db(code: Bytes) -> MemoryDatabase { + MemoryDatabase::default() + .account_code(ORACLE_CONTRACT_ADDRESS, code) + .account_balance(CALLER, U256::from(1)) + .account_balance(ORACLE_CONTRACT_ADDRESS, U256::from(1)) + .sequencer_registry(MEGA_SYSTEM_ADDRESS) +} + +#[allow(clippy::too_many_arguments)] +fn assert_deposit_stopped( + name: &str, + code: Bytes, + compute_at_read: u64, + cap: u64, + access: VolatileDataAccess, + intrinsic: u64, + left: u64, + source: B256, +) { + let limit = compute_at_read + cap; + let used = limit - left; + let run = execute(deposit_db(code), user_deposit(source)); + assert!(run.detains, "{name}: a user's deposit is detained, got {:?}", run.outcome.result); + assert_eq!(run.accessed, access, "{name}"); + assert_eq!(run.limit, Some(limit), "{name}: the read set compute at the read plus the cap"); + match &run.outcome.result { + ExecutionResult::Revert { output, .. } => { + assert_eq!( + output.as_ref(), + MegaLimitExceeded { kind: 2, limit }.abi_encode(), + "{name}" + ); + } + other => panic!("{name}: expected the detention stop, got {other:?}"), + } + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used, + frame_local: false, + }), + "{name}" + ); + assert_eq!(run.outcome.gas.regular, intrinsic + used, "{name}: billed what ran"); + assert_eq!(run.outcome.gas.gas_used, intrinsic + used, "{name}: the receipt bills the same"); + assert_eq!(run.outcome.gas.state, 0, "{name}"); + assert_eq!(run.outcome.gas.history, 0, "{name}: a deposit pays no history"); + assert_eq!(run.outcome.gas.history_bytes, 0, "{name}"); + assert!(run.outcome.result.logs().is_empty(), "{name}"); +} + +/// The same body as a Mega System Transaction: a legacy call from the system address to the +/// Oracle. It is the protocol's own transaction, so the read does not detain it. +fn assert_system_transaction_is_not_stopped(name: &str, code: Bytes, cap: u64) { + let system = alloy_op_evm::OpTx(op_transaction(TxEnv { + caller: MEGA_SYSTEM_ADDRESS, + kind: TxKind::Call(ORACLE_CONTRACT_ADDRESS), + gas_limit: BELOW, + chain_id: Some(1), + ..Default::default() + })); + assert!(mega_evm::system::is_system_originated(&system, MEGA_SYSTEM_ADDRESS), "{name}"); + let run = execute(deposit_db(code), system); + assert!(run.outcome.result.is_success(), "{name} system: {:?}", run.outcome.result); + assert!(!run.detains, "{name} system"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{name} system"); + assert_eq!(run.limit, None, "{name} system"); + assert!(run.outcome.gas.regular > cap, "{name} system: it ran past the cap"); + assert_eq!(run.outcome.gas.history, 0, "{name} system"); +} + +/* ---------- the beneficiary's own frame ---------- */ + +/// The beneficiary's own frame reads its balance with `SELFBALANCE` and destroys itself with +/// `SELFDESTRUCT`; a transaction that reaches it is detained from its start. Another contract's +/// `SELFBALANCE` reads nothing volatile. +#[test] +fn test_the_beneficiarys_own_frame_is_detained() { + for gas_limit in TIERS { + let code = spin(op(BytecodeBuilder::default(), SELFBALANCE)); + let run = execute( + MemoryDatabase::default().account_code(BENEFICIARY, code), + tx(CALLER, BENEFICIARY, gas_limit), + ); + // Detained from its start: `SELFBALANCE`, its `POP` and the loop all come after the read. + let left = Charges::default().then(&[5, 2]).spin(0).left(CAP); + assert_eq!(assert_stopped(&run, intrinsic(gas_limit), left), CAP); + + let code = BytecodeBuilder::default().push_address(OTHER).append(SELFDESTRUCT).build(); + let db = MemoryDatabase::default() + .account_code(BENEFICIARY, code) + .account_balance(BENEFICIARY, U256::from(7)); + let run = execute(db, tx(CALLER, BENEFICIARY, gas_limit)); + assert!(run.outcome.result.is_success()); + assert_eq!(run.limit, Some(CAP)); + assert_eq!(run.outcome.state[&OTHER].info.balance, U256::from(7)); + + let code = work(op(BytecodeBuilder::default(), SELFBALANCE), PAST_THE_CAP).stop().build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, gas_limit), + ); + assert!(run.outcome.result.is_success()); + assert_eq!(run.limit, None); + } +} + +/// A `SELFDESTRUCT` to the beneficiary moves the balance and detains the transaction. +#[test] +fn test_a_selfdestruct_to_the_beneficiary_moves_the_balance_and_detains() { + let child = on_beneficiary(BytecodeBuilder::default(), SELFDESTRUCT).build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, CHILD).stop().build()) + .account_code(CHILD, child) + .account_balance(CHILD, U256::from(9)); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.outcome.state[&BENEFICIARY].info.balance, U256::from(9)); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + assert!(run.limit.is_some()); +} + +/* ---------- refused reads ---------- */ + +/// Runs `CONTRACT`, which calls `CHILD` with everything it has, with volatile-data access off +/// from the child down, and returns what the child's frame ended with. +fn refused_child(db: MemoryDatabase) -> (InstructionResult, Bytes) { + let db = + db.account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, CHILD).stop().build()); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success(), "the caller resumes: {:?}", run.outcome.result); + let child = + evm.inspector().calls.iter().find(|call| call.target == CHILD).expect("the child ran"); + (child.result, child.output.clone()) +} + +fn refused(access: VolatileDataAccess) -> (InstructionResult, Bytes) { + (InstructionResult::Revert, volatile_data_access_disabled_revert_data(access)) +} + +/// The refusal follows what the Host loads, whichever way the call reaches it: the beneficiary +/// behind an EIP-7702 delegation, the beneficiary with a delegation of its own, and the +/// beneficiary's own frame destroying itself are refused; a call that loads no volatile data +/// proceeds. +#[test] +fn test_a_refusal_follows_what_the_host_loads() { + let beneficiary = refused(VolatileDataAccess::BENEFICIARY_BALANCE); + + // A delegator whose delegate is the beneficiary. + let db = with_delegation(MemoryDatabase::default(), DELEGATOR, BENEFICIARY) + .account_code(CHILD, call(BytecodeBuilder::default(), CALL, DELEGATOR).stop().build()); + assert_eq!(refused_child(db), beneficiary, "the delegate"); + + // The beneficiary, delegating elsewhere. + let db = with_delegation(MemoryDatabase::default(), BENEFICIARY, OTHER) + .account_code(CHILD, call(BytecodeBuilder::default(), CALL, BENEFICIARY).stop().build()); + assert_eq!(refused_child(db), beneficiary, "the beneficiary itself"); + + // Another account. + let db = MemoryDatabase::default() + .account_code(OTHER, BytecodeBuilder::default().stop().build()) + .account_code(CHILD, call(BytecodeBuilder::default(), CALL, OTHER).stop().build()); + assert_eq!(refused_child(db), (InstructionResult::Stop, Bytes::new()), "no volatile load"); +} + +/// The beneficiary's own frame destroying itself reads and clears the beneficiary's balance: +/// with access off from that frame, the destruction is refused. +#[test] +fn test_the_beneficiary_destroying_itself_is_refused() { + let code = BytecodeBuilder::default().push_address(OTHER).append(SELFDESTRUCT).build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, BENEFICIARY).stop().build()) + .account_code(BENEFICIARY, code) + .account_balance(BENEFICIARY, U256::from(7)); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success()); + let frame = &evm.inspector().calls[0]; + assert_eq!(frame.target, BENEFICIARY); + assert_eq!( + (frame.result, frame.output.clone()), + refused(VolatileDataAccess::BENEFICIARY_BALANCE) + ); + assert!(run.outcome.state.get(&OTHER).is_none_or(|account| account.info.balance.is_zero())); +} + +/// An opcode that fails before it loads anything keeps its own failure: a `SELFDESTRUCT` in the +/// beneficiary's own frame or a `CALL` to the beneficiary short of operands halts with a stack +/// underflow, not a refusal. +#[test] +fn test_a_stack_underflow_is_not_a_refusal() { + let db = MemoryDatabase::default() + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, BENEFICIARY).stop().build()) + .account_code(BENEFICIARY, BytecodeBuilder::default().append(SELFDESTRUCT).build()); + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + assert!(run.outcome.result.is_success()); + let frame = &evm.inspector().calls[0]; + assert_eq!((frame.target, frame.result), (BENEFICIARY, InstructionResult::StackUnderflow)); + + let partial_call = BytecodeBuilder::default() + .push_address(BENEFICIARY) + .push_number(100_000_u32) + .append(CALL) + .build(); + let db = MemoryDatabase::default().account_code(CHILD, partial_call); + assert_eq!(refused_child(db).0, InstructionResult::StackUnderflow, "CALL"); +} + +/// A database failure on an account an opcode loads surfaces as an error of the transaction, with +/// access switched off or not; a `CALL` short of operands still fails on its stack first, even +/// when its target's code would fail to load. +#[test] +fn test_a_database_failure_surfaces_and_a_stack_underflow_comes_first() { + let selfdestruct = BytecodeBuilder::default().push_address(OTHER).append(SELFDESTRUCT).build(); + let calls_other = call(BytecodeBuilder::default(), CALL, OTHER).stop().build(); + for (child, disabled) in [(selfdestruct, false), (calls_other, true)] { + let inner = MemoryDatabase::default() + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, CHILD).stop().build()) + .account_code(CHILD, child) + .account_balance(OTHER, U256::from(1)); + let mut db = ErrorInjectingDatabase::new(inner); + db.fail_on_account = Some(OTHER); + let mut ctx = context(db); + if disabled { + ctx = ctx.with_volatile_access_disabled_from(1); + } + let result = MegaEvm::new(ctx).execute_transaction(tx(CALLER, CONTRACT, BELOW)); + assert!(result.is_err(), "disabled {disabled}: {result:?}"); + } + + // The target's account, or its code, fails to load; the partial CALL never gets that far. + let code_hash = Bytecode::new_eip7702(BENEFICIARY).hash_slow(); + let partial_call = BytecodeBuilder::default() + .push_address(OTHER) + .push_number(100_000_u32) + .append(CALL) + .build(); + for fails_on_code in [false, true] { + let inner = MemoryDatabase::default() + .account_code(CONTRACT, call(BytecodeBuilder::default(), CALL, CHILD).stop().build()) + .account_code(CHILD, partial_call.clone()) + .account_lazy_code(OTHER, code_hash); + let mut db = ErrorInjectingDatabase::new(inner); + if fails_on_code { + db.fail_on_code_by_hash = Some(code_hash); + } else { + db.fail_on_account = Some(OTHER); + } + let mut evm = MegaEvm::new(context(db).with_volatile_access_disabled_from(1)) + .with_inspector(Calls::default()); + let outcome = + evm.execute_transaction(tx(CALLER, CONTRACT, BELOW)).expect("no database error"); + assert!(outcome.result.is_success()); + let child = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(child.result, InstructionResult::StackUnderflow, "code {fails_on_code}"); + } +} + +/// Calling `MegaAccessControl` costs the caller its call's overhead alone: the answer carries the +/// forwarded gas back untouched. +#[test] +fn test_a_call_to_the_access_control_contract_costs_its_overhead() { + let selector = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; + let code = BytecodeBuilder::default() + .mstore(0, selector) + .append(GAS) + .append_many([PUSH0, PUSH0]) + .push_number(4_u8) + .append_many([PUSH0, PUSH0]) + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u32) + .append_many([CALL, POP, GAS, SWAP1, SUB]) + .push_number(0_u8) + .append(MSTORE) + .push_number(32_u8) + .push_number(0_u8) + .append(RETURN) + .build(); + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code), + tx(CALLER, CONTRACT, BELOW), + ); + assert!(run.outcome.result.is_success()); + let consumed = U256::from_be_slice(run.outcome.result.output().unwrap()); + // The pushes (2 + 2 + 3 + 2 + 2 + 3 + 3), the cold call, POP and GAS. + let cold_call = + entry(GasId::warm_storage_read_cost()) + entry(GasId::cold_account_additional_cost()); + assert_eq!(consumed, U256::from(17 + cold_call + 2 + 2)); +} + +/* ---------- an applied authority ---------- */ + +/// A transaction authorizing `authority` to delegate to `CHILD`, from `CALLER` to `CONTRACT`. +fn authorizing(authority: Address, gas_limit: u64) -> mega_evm::MegaTransaction { + use alloy_op_evm::OpTx; + use revm::{ + context::transaction::TransactionType, + context_interface::{ + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, + }; + let authorization = Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { chain_id: U256::ZERO, address: CHILD, nonce: 0 }, + RecoveredAuthority::Valid(authority), + )); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip7702 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit, + gas_priority_fee: Some(0), + authorization_list: vec![authorization], + ..Default::default() + })) +} + +/// Whether `account` carries the designator of a delegation to `CHILD` after the run. +fn delegates_to_child(run: &crate::detention::Run, account: Address) -> bool { + run.outcome.state.get(&account).is_some_and(|account| { + account.info.code.as_ref().is_some_and(|code| code == &Bytecode::new_eip7702(CHILD)) + }) +} + +/// An applied EIP-7702 authority that is the block beneficiary writes the beneficiary's account: +/// the transaction is detained from its first frame, its limit the cap, though neither its sender +/// nor its recipient is the beneficiary. An authority that is not the beneficiary detains nothing. +#[test] +fn test_an_applied_authority_that_is_the_beneficiary_detains() { + let code = work(BytecodeBuilder::default(), 10).stop().build(); + for gas_limit in TIERS { + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + authorizing(BENEFICIARY, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert!(delegates_to_child(&run, BENEFICIARY), "the authority applied"); + assert_eq!(run.limit, Some(CAP)); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + + let run = execute( + MemoryDatabase::default().account_code(CONTRACT, code.clone()), + authorizing(OTHER, gas_limit), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert!(delegates_to_child(&run, OTHER), "the authority applied"); + assert_eq!(run.limit, None); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + } +} + +/// A transaction whose recipient is an EIP-7702 delegator of the beneficiary runs the +/// beneficiary's code, as a call a contract makes to that delegator does: it is detained from its +/// first frame, its limit the cap. A delegator of another account detains nothing. +#[test] +fn test_a_transaction_to_a_delegator_of_the_beneficiary_detains() { + let code = work(BytecodeBuilder::default(), 10).stop().build(); + for gas_limit in TIERS { + let db = with_delegation( + MemoryDatabase::default().account_code(BENEFICIARY, code.clone()), + DELEGATOR, + BENEFICIARY, + ); + let run = execute(db, tx(CALLER, DELEGATOR, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.limit, Some(CAP)); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + + let db = with_delegation( + MemoryDatabase::default().account_code(OTHER, code.clone()), + DELEGATOR, + OTHER, + ); + let run = execute(db, tx(CALLER, DELEGATOR, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.limit, None); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + } +} + +/// Compute is what the frames spend, not the transaction's intrinsic gas: under a cap far below +/// what an authorization costs before any frame, an authority that is the beneficiary stops +/// nothing before the first frame, and stays applied. The first frame is held to the cap: a frame +/// within it completes, and one past it stops the transaction, its authorization standing. +#[test] +fn test_a_cap_below_the_intrinsic_gas_stops_nothing_before_the_first_frame() { + let tiny = 1_000; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(tiny); + for gas_limit in TIERS { + let run = |code: Bytes| { + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + run_on(&mut evm, authorizing(BENEFICIARY, gas_limit)) + }; + + // A frame that only stops spends no compute: its bill is the intrinsic gas. + let stops = run(BytecodeBuilder::default().stop().build()); + assert!(stops.outcome.result.is_success(), "{:?}", stops.outcome.result); + let intrinsic = stops.outcome.gas.regular; + assert!(intrinsic > tiny, "the authorization costs more than the cap before any frame"); + assert!(delegates_to_child(&stops, BENEFICIARY)); + assert_eq!(stops.limit, Some(tiny)); + + let within = run(burn(BytecodeBuilder::default(), 10).stop().build()); + assert!(within.outcome.result.is_success(), "{:?}", within.outcome.result); + + // The stop takes back what the frame did, not the authorization or its state gas. The + // frame is detained from its start: the loop's copy is the first charge past the cap. + let past = run(spin(BytecodeBuilder::default())); + let used = tiny - Charges::default().spin(0).left(tiny); + assert_eq!(used, 1 + 3 + 2 + 2 + 3, "the loop up to the copy"); + assert_eq!( + past.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: tiny, + used, + frame_local: false + }) + ); + assert_eq!(past.outcome.result.output(), Some(&stop_data(tiny))); + assert_eq!(past.outcome.gas.regular, intrinsic + used); + assert_eq!(past.outcome.gas.state, stops.outcome.gas.state); + assert!(delegates_to_child(&past, BENEFICIARY), "the authorization stands"); + } +} diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs new file mode 100644 index 000000000..d50e617d9 --- /dev/null +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -0,0 +1,1848 @@ +//! Gas detention against every other reader of a frame's gas, and against every out-of-gas. +//! +//! A detained frame's spendable gas is held at what the limit leaves the transaction, and the rest +//! is withheld: only a regular charge sees the difference. `GAS`, the 63/64 forward, the `SSTORE` +//! sentry, the skip-cold checks and a callee's inheritance see the whole regular gas. So a +//! transaction that reads volatile data runs as it does without the read — the same result and the +//! same bill on every ledger — unless its compute crosses the limit, which is a regular charge the +//! withheld part would have paid. That is the stop, and nothing else is. +//! +//! Each case runs twice: with a read of the block's timestamp, and with `PUSH0`, which costs the +//! same two gas and reads nothing, in its place. + +use std::sync::{Arc, Mutex}; + +use alloy_evm::precompiles::DynPrecompile; +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + history_gas, satin_gas_params, + system::keyless::{ + decode_keyless_tx, + tests::{CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX}, + IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaHaltReason, + VolatileDataAccess, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::*, + context::{ + result::{ExecutionResult, HaltReason, OutOfGasError}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, Gas, InstructionResult, + InterpreterResult, + }, + precompile::{modexp, PrecompileHalt, PrecompileId, PrecompileOutput}, + primitives::HashMap, + Database, Inspector, +}; + +use crate::{ + common::history, + detention::{ + assert_caught, assert_stopped, burn, cold_access, context, execute, failed_status_store, + fresh_write, fresh_write_spill, intrinsic, memory_cost, op, run_on, spin, sstore_static, + stop_data, tx, work, Calls, Charges, Run, ABOVE, BELOW, BENEFICIARY, CALLER, CAP, CHILD, + CONTRACT, TIERS, + }, +}; + +/// A contract between the transaction's frame and `CHILD`. +const MIDDLE: Address = address!("0000000000000000000000000000000000d00010"); + +/// An empty account that is not the beneficiary. +const OTHER: Address = address!("0000000000000000000000000000000000d00011"); + +/// A contract that calls itself with all its gas until the call stack is full. +const RECURSES: Address = address!("0000000000000000000000000000000000d00012"); + +/// The modexp precompile. +const MODEXP: Address = address!("0000000000000000000000000000000000000005"); + +/// The BN254 point addition precompile. +const EC_ADD: Address = address!("0000000000000000000000000000000000000006"); + +/// The BN254 pairing precompile. +const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + +/// The BLS12-381 G1 MSM precompile (EIP-2537). +const BLS12_G1_MSM: Address = address!("000000000000000000000000000000000000000c"); + +/// The BLS12-381 G2 MSM precompile (EIP-2537). +const BLS12_G2_MSM: Address = address!("000000000000000000000000000000000000000e"); + +/// The BLS12-381 pairing precompile (EIP-2537). +const BLS12_PAIRING: Address = address!("000000000000000000000000000000000000000f"); + +/// Runs the transaction `build` makes for a first instruction that reads the timestamp, then for +/// one that pushes a zero at the same price: detained, then not. +fn with_and_without_read(build: impl Fn(u8) -> (MemoryDatabase, u64)) -> (Run, Run) { + let run = |first| { + let (db, gas_limit) = build(first); + execute(db, tx(CALLER, CONTRACT, gas_limit)) + }; + let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); + assert!(detained.limit.is_some(), "the read set a limit"); + assert_eq!(plain.limit, None, "the push read nothing"); + (detained, plain) +} + +/// Asserts the detained run is the plain one: its result, every ledger of its bill, and the +/// transaction's own storage. +fn assert_as_without_read(detained: &Run, plain: &Run, case: &str) { + assert_eq!(detained.outcome.result, plain.outcome.result, "{case}: the result"); + assert_eq!(detained.outcome.gas, plain.outcome.gas, "{case}: the bill"); + assert_eq!(detained.outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(slot(detained, 0), slot(plain, 0), "{case}: what the transaction stored"); +} + +/// What `CONTRACT` holds in slot `index` after the transaction, if it wrote it. +fn slot(run: &Run, index: u64) -> Option { + run.outcome + .state + .get(&CONTRACT) + .and_then(|account| account.storage.get(&U256::from(index))) + .map(|slot| slot.present_value) +} + +/// Appends a call to `to` with `gas` (all of it when `None`) that keeps its status on the stack. +fn call_keeping_status(code: BytecodeBuilder, to: Address, gas: Option) -> BytecodeBuilder { + let code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]).push_address(to); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code.append(CALL) +} + +/// Stores the status a call left on the stack in slot 0, and stops. +fn store_status(code: BytecodeBuilder) -> Bytes { + code.push_number(0_u8).append(SSTORE).stop().build() +} + +/// A piece of code that ends a frame on an out-of-gas, appended to a program. +type Fail = fn(BytecodeBuilder) -> BytecodeBuilder; + +/// An operand above `usize`: the instruction fails before any charge, whatever the gas. +fn invalid_operand(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_u256(U256::MAX).append(MLOAD) +} + +/// A memory expansion to 16 MiB: about 538,000,000 gas, more than any transaction has. +fn huge_memory(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(0x0100_0000_u32).append(MLOAD) +} + +/// A hash of 2^40 bytes, whose word price no transaction can pay: its charge fails before the +/// memory is touched, and the halt zeroes the frame's gas. +fn huge_hash(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40).append_many([PUSH0, KECCAK256]) +} + +/// A copy of 2^40 bytes of calldata, whose word price no transaction can pay. +fn huge_copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40).append_many([PUSH0, PUSH0, CALLDATACOPY]) +} + +/// A copy of 2^40 bytes of code, whose word price no transaction can pay. +fn huge_code_copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40).append_many([PUSH0, PUSH0, CODECOPY]) +} + +/// A copy of 2^40 bytes within memory, whose word price no transaction can pay. +fn huge_memory_copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40).append_many([PUSH0, PUSH0, MCOPY]) +} + +/// A copy of 2^40 bytes of another account's code, whose word price no transaction can pay. +fn huge_account_code_copy(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40) + .append_many([PUSH0, PUSH0]) + .push_address(OTHER) + .append(EXTCODECOPY) +} + +/// A log of 2^40 bytes, whose byte price no transaction can pay. +fn huge_log(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(1_u64 << 40).append_many([PUSH0, LOG0]) +} + +/* ---------- what the frame's other readers see ---------- */ + +/// `GAS` answers the whole regular gas after a read, withheld part included, as it does without +/// one. +#[test] +fn test_gas_answers_the_whole_regular_gas_after_a_read() { + for gas_limit in TIERS { + let (detained, plain) = with_and_without_read(|first| { + let code = op(BytecodeBuilder::default(), first) + .append(GAS) + .push_number(0_u8) + .append(SSTORE) + .stop() + .build(); + (MemoryDatabase::default().account_code(CONTRACT, code), gas_limit) + }); + assert_as_without_read(&detained, &plain, "GAS"); + assert!(slot(&detained, 0).unwrap() > U256::from(CAP), "more than the allowance"); + } +} + +/// A callee started after the caller's read with an explicit gas stays bounded by it: its state +/// writes draw the reservoir the transaction has, not the caller's withheld gas. The bound pays +/// the compute of three fresh slots and what one of them spills: below the execution cap, where +/// every slot's state gas and history spill onto it, the callee runs out of gas before its third +/// write completes — at the spec's prices already on its second write's state gas, which is more +/// than one write's compute; above it the reservoir pays all three — each as without the read. +#[test] +fn test_a_bounded_callee_writes_what_it_writes_without_the_read() { + let child = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(3), U256::from(1)) + .stop() + .build(); + let bound = u32::try_from(3 * fresh_write() + fresh_write_spill()).expect("a bound in a push"); + // Where a write spills nothing, the bound pays all three below the cap too. + let below = u64::from(fresh_write_spill() == 0); + for (gas_limit, status) in [(BELOW, below), (ABOVE, 1)] { + let (detained, plain) = with_and_without_read(|first| { + let parent = + call_keeping_status(op(BytecodeBuilder::default(), first), CHILD, Some(bound)); + let db = MemoryDatabase::default() + .account_code(CONTRACT, store_status(parent)) + .account_code(CHILD, child.clone()); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, "a bounded callee"); + assert_eq!(slot(&detained, 0), Some(U256::from(status)), "{gas_limit}"); + } +} + +/// `SSTORE`'s stipend sentry reads the whole regular gas: a write the frame can pay is not +/// refused because its spendable part is short of 2,300. A fresh slot, the read, 19,998,992 of +/// counting, then a write to the same slot: the compute stays within the limit, and the +/// transaction completes as without the read. +#[test] +fn test_the_sstore_sentry_reads_the_whole_regular_gas() { + for gas_limit in TIERS { + let (detained, plain) = with_and_without_read(|first| { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + let code = + burn(op(code, first), 769_192).sstore(U256::from(1), U256::from(2)).stop().build(); + (MemoryDatabase::default().account_code(CONTRACT, code), gas_limit) + }); + assert!(plain.outcome.result.is_success(), "{:?}", plain.outcome.result); + let limit = detained.limit.unwrap(); + let compute = plain.outcome.gas.regular - intrinsic(gas_limit); + assert!(compute < limit && limit - compute < 2_300, "{compute} of {limit}"); + assert_as_without_read(&detained, &plain, "the sentry"); + } +} + +/// At the settlement the withheld gas is unspent gas: it goes back to the sender with the rest of +/// the unspent gas, and it is not part of the gas used that caps the EIP-3529 refund at a fifth. +/// +/// After its read, under a cap of 1,000,000, the transaction writes sixteen fresh slots, each back +/// to zero at once, so most of its regular gas is withheld when it ends. Each fresh, cold write +/// costs its two pushes and `SSTORE`'s 100, 2,000 cold and 10,000 for the write; each write back, +/// its pushes and the warm 100; the slot's state gas and its record's history come back with the +/// write back. So the transaction spends its intrinsic 15,000, its body's history, the read and +/// its `POP` and sixteen times 12,106 + 106, and its refund counter holds sixteen times the 10,000 +/// a restored fresh slot refunds — more than a fifth of what it spent, at a history byte of up to +/// 1,000 gas, so the refund is that fifth. Counted as used, the withheld gas would lift the cap +/// above the counter. +/// +/// The sender pays what the receipt reports at the gas price, and the beneficiary is credited it; +/// the same transaction without the read settles the same way. +/// +/// Rules: [S12.34], [S12.42], [S12]. Independence: independent — every charge is the opcode's +/// price, the refund and its cap are EIP-3529's, the intrinsic gas is EIP-2780's, and the body's +/// history is `TX_BODY_SIZE` at the cost per history byte in effect. +#[test] +fn test_the_settlement_counts_the_withheld_gas_as_unspent() { + const SETTLED_CAP: u64 = 1_000_000; + const SLOTS: u64 = 16; + const GAS_PRICE: u128 = 2; + let write_back = 3 + 3 + sstore_static(); + let restored_slot_refund = crate::salt::entry(GasId::sstore_set_refund()); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(SETTLED_CAP); + let funds = U256::from(10u64.pow(18)); + for gas_limit in TIERS { + let run = |first| { + let code = (1..=SLOTS).fold(op(BytecodeBuilder::default(), first), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)).sstore(U256::from(slot), U256::ZERO) + }); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_balance(CALLER, funds); + let mut tx = tx(CALLER, CONTRACT, gas_limit); + tx.0.base.gas_price = GAS_PRICE; + run_on(&mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), tx) + }; + let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); + assert_eq!(detained.limit, Some(2 + SETTLED_CAP), "the read set a limit"); + + let spent = CALL_INTRINSIC + + history(mega_evm::TX_BODY_SIZE) + + 2 + + 2 + + SLOTS * (fresh_write() + write_back); + let refund = spent / 5; + assert!(SLOTS * restored_slot_refund > refund, "the cap binds the refund counter"); + let withheld_at_least = gas_limit.min(TX_GAS_LIMIT_CAP) - spent - (2 + SETTLED_CAP); + assert!( + (spent + withheld_at_least) / 5 > SLOTS * restored_slot_refund, + "counted as used, the withheld gas would lift the cap above the counter" + ); + let gas_used = spent - refund; + for (name, run) in [("with the read", &detained), ("without it", &plain)] { + let outcome = &run.outcome; + assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{name}: no stop"); + assert_eq!(outcome.result.gas().total_gas_spent(), spent, "{name}: what it spent"); + assert_eq!(outcome.result.gas().inner_refunded(), refund, "{name}: a fifth of it back"); + assert_eq!(outcome.gas.gas_used, gas_used, "{name}: the receipt"); + assert_eq!( + outcome.state[&CALLER].info.balance, + funds - U256::from(u128::from(gas_used) * GAS_PRICE), + "{name}: the sender pays the receipt's gas, the rest comes back" + ); + assert_eq!( + outcome.state[&BENEFICIARY].info.balance, + U256::from(u128::from(gas_used) * GAS_PRICE), + "{name}: the beneficiary is credited it" + ); + } + } +} + +/* ---------- out-of-gas no gas could pay ---------- */ + +/// An out-of-gas the transaction's whole gas could not pay halts and burns as without the read: +/// an operand above `usize`, and a memory expansion beyond everything the transaction has. +#[test] +fn test_an_out_of_gas_nothing_could_pay_halts_as_without_the_read() { + let cases: [(&str, Fail, OutOfGasError); 3] = [ + ("an operand above usize", invalid_operand, OutOfGasError::InvalidOperand), + ("a 16 MiB memory expansion", huge_memory, OutOfGasError::Memory), + ("a hash of 2^40 bytes", huge_hash, OutOfGasError::Basic), + ]; + for gas_limit in TIERS { + for (name, fail, reason) in cases { + let (detained, plain) = with_and_without_read(|first| { + let code = fail(op(BytecodeBuilder::default(), first)).stop().build(); + (MemoryDatabase::default().account_code(CONTRACT, code), gas_limit) + }); + assert_as_without_read(&detained, &plain, name); + match &detained.outcome.result { + ExecutionResult::Halt { reason: MegaHaltReason::Base(halt), gas, .. } => { + assert_eq!(*halt, HaltReason::OutOfGas(reason), "{name}"); + let burned = gas_limit.min(TX_GAS_LIMIT_CAP); + assert!(gas.tx_gas_used() >= burned, "{name}: a halt burns the regular gas"); + } + other => panic!("{name}: expected a halt, got {other:?}"), + } + } + } +} + +/// A creation whose code costs more state gas and history than the transaction has halts as +/// without the read: a failed state or history charge is never the cap. +#[test] +fn test_a_creation_that_cannot_pay_its_deposit_halts_as_without_the_read() { + // The largest code a creation may deploy, and a gas limit below the execution cap that pays no + // more than that code's state gas and history, and at least twice the cap, so the read + // withholds gas. + let len = MAX_CONTRACT_SIZE as u64; + let deposit = len * satin_gas_params().get(GasId::code_deposit_state_gas()) + + history_gas(len).expect("the code's history has a price"); + let gas_limit = BELOW.min(deposit); + // Where that code costs no more than twice the cap, as where a state byte is free and a + // history byte cheap, no gas limit both withholds gas at the read and falls short of the + // deposit. + if gas_limit <= 2 * CAP { + return; + } + let run = |first| { + let initcode = op(BytecodeBuilder::default(), first) + .push_number(len) + .append_many([PUSH0, RETURN]) + .build(); + let create = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: initcode, + gas_limit, + ..Default::default() + })); + run_on(&mut MegaEvm::new(context(MemoryDatabase::default())), create) + }; + let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); + assert!(detained.limit.is_some()); + assert!(matches!(detained.outcome.result, ExecutionResult::Halt { .. })); + assert_eq!(detained.outcome.result, plain.outcome.result); + assert_eq!(detained.outcome.gas, plain.outcome.gas); + assert_eq!(detained.outcome.limit_exceeded, None); +} + +/// A callee that reads and then runs out of gas nothing could pay halts; its caller catches the +/// failure and completes, as without the read. +#[test] +fn test_a_callees_out_of_gas_is_caught_as_without_the_read() { + let cases: [(&str, Fail); 4] = [ + ("an operand above usize", invalid_operand), + ("a 16 MiB memory expansion", huge_memory), + ("a hash of 2^40 bytes", huge_hash), + ("a copy of 2^40 bytes", huge_copy), + ]; + let parent = store_status(call_keeping_status(BytecodeBuilder::default(), CHILD, None)); + for gas_limit in TIERS { + for (name, fail) in cases { + let (detained, plain) = with_and_without_read(|first| { + let child = fail(op(BytecodeBuilder::default(), first)).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_code(CHILD, child); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, name); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "{name}: the call failed"); + } + } +} + +/// What a halting callee burns is not compute, however the halt ended it: a caller that read and +/// then computed to within about a hundred thousand of its limit, whose callee burns more than +/// that, completes as without the read. +/// +/// The callee's charge fails on an operand, a memory expansion, a hash, four copies, a log and an +/// invalid opcode, all on all the gas; and on the history of the write records a value call makes, +/// after the call forwarded 63/64 of its gas to a frame that never starts. That callee is given +/// 400,000, or less where it would pay that history out of the 64th it keeps, and its caller +/// computes twenty rounds further, so the limit is left less than the callee forwards. Above the +/// execution cap the reservoir pays that history, so that case runs below it. A precompile that +/// rejects its input halts without running a frame, and burns all it was forwarded too. +#[test] +fn test_what_a_halting_callee_burns_is_not_compute() { + let cases: [(&str, Bytes); 10] = [ + ("an operand above usize", invalid_operand(BytecodeBuilder::default()).stop().build()), + ("a 16 MiB memory expansion", huge_memory(BytecodeBuilder::default()).stop().build()), + ("a hash of 2^40 bytes", huge_hash(BytecodeBuilder::default()).stop().build()), + ("a copy of 2^40 bytes", huge_copy(BytecodeBuilder::default()).stop().build()), + ("a code copy of 2^40 bytes", huge_code_copy(BytecodeBuilder::default()).stop().build()), + ( + "a memory copy of 2^40 bytes", + huge_memory_copy(BytecodeBuilder::default()).stop().build(), + ), + ( + "an account's code copy of 2^40 bytes", + huge_account_code_copy(BytecodeBuilder::default()).stop().build(), + ), + ("a log of 2^40 bytes", huge_log(BytecodeBuilder::default()).stop().build()), + ("an invalid opcode", BytecodeBuilder::default().append(INVALID).build()), + ( + "a value call whose records the caller cannot pay", + call_keeping_value(BytecodeBuilder::default(), OTHER).stop().build(), + ), + ]; + // 6,396 rounds: 19,878,768 of compute before the call. + let rounds = 6_396; + // The value call's callee keeps a 64th of what it has at its `CALL`, which has to be less than + // the history of the records the call makes. It spends at most 40,000 before the forward — the + // value transfer, the new account and the cold access. Where 64 times that history is under + // 100,000, as where a history byte costs nothing, the callee cannot also forward past the + // margin its caller leaves, and the case has nothing to show. + let middle_gas = (64 * history(2 * WRITE_RECORD_SIZE)).saturating_sub(1).min(400_000); + for gas_limit in TIERS { + for (name, callee) in &cases { + let records = name.starts_with("a value call"); + if records && (gas_limit == ABOVE || middle_gas < 100_000) { + continue; + } + let (to, gas, rounds) = if records { + (MIDDLE, Some(middle_gas as u32), rounds + 20) + } else { + (CHILD, None, rounds) + }; + let (detained, plain) = with_and_without_read(|first| { + let parent = work(op(BytecodeBuilder::default(), first), rounds); + let parent = store_status(call_keeping_status(parent, to, gas)); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent) + .account_code(to, callee.clone()) + .account_balance(MIDDLE, U256::from(1)); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, name); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "{name}: the call failed"); + if records { + // `MIDDLE` halted on all it was given; the rest of the regular ledger is compute, + // and it leaves the limit less than the 63/64 `MIDDLE` forwarded, so counting that + // forward as compute would have stopped the transaction. + let compute = plain.outcome.gas.regular - intrinsic(gas_limit) - middle_gas; + let margin = detained.limit.unwrap() - compute; + let forwarded = (middle_gas - 40_000) * 63 / 64; + assert!(margin < forwarded, "{name}: {margin} short of the limit"); + } + } + + // `(1, 1)` is not on the curve: the addition fails on it and burns what it was given. + let (detained, plain) = with_and_without_read(|first| { + let point = [U256::from(1).to_be_bytes::<32>(), U256::from(1).to_be_bytes::<32>()]; + let parent = work(op(BytecodeBuilder::default(), first), rounds) + .mstore(0, point.concat()) + .append_many([PUSH0, PUSH0]) + .push_number(128_u8) + .append_many([PUSH0, PUSH0]) + .push_address(EC_ADD) + .append_many([GAS, CALL]); + (MemoryDatabase::default().account_code(CONTRACT, store_status(parent)), gas_limit) + }); + assert_as_without_read(&detained, &plain, "a precompile rejecting its input"); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "the addition failed"); + } +} + +/// Runs the transaction `build` makes, under a block-environment cap of `cap`, for a first +/// instruction that reads the timestamp, then for one that pushes a zero at the same price. +fn with_and_without_read_under( + cap: u64, + build: impl Fn(u8) -> (MemoryDatabase, u64), +) -> (Run, Run) { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let run = |first| { + let (db, gas_limit) = build(first); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)) + }; + (run(TIMESTAMP), run(PUSH0)) +} + +/// Appends `rounds` calls to `CHILD`, each forwarding `gas`, dropping their status. +fn calls_to_child(code: BytecodeBuilder, rounds: u32, gas: u32) -> BytecodeBuilder { + (0..rounds).fold(code, |code, _| { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(gas) + .append_many([CALL, POP]) + }) +} + +/// `EXP`'s exponent charge — fifty gas a byte of the exponent, 1,600 for a full word — is noted +/// when it fails: a hundred children forwarded 1,500 gas each, which halt on an `EXP` of a +/// 32-byte exponent with 1,484 left, burn that, and the caller completes under a cap of 100,000, +/// as without the read. Counted as compute, the hundred burns would pass the cap. +#[test] +fn test_an_exp_that_cannot_pay_its_exponent_burns_what_its_frame_had() { + let child = + BytecodeBuilder::default().push_u256(U256::MAX).push_number(2_u8).append(EXP).build(); + for gas_limit in TIERS { + let (detained, plain) = with_and_without_read_under(100_000, |first| { + let code = calls_to_child(op(BytecodeBuilder::default(), first), 100, 1_500); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_code(CHILD, child.clone()); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, "a hundred halts on EXP"); + let burned = 100 * 1_484; + assert!(plain.outcome.gas.regular - intrinsic(gas_limit) > burned, "the halts burned"); + } +} + +/// A contract that returns 500 words of zeros, the memory of which it pays for. +const RETURNS_WORDS: Address = address!("0000000000000000000000000000000000d00014"); + +/// `RETURNDATACOPY`'s word charge is noted when it fails, as the other copies' are. It copies no +/// more than the return data holds, so each child first gets some: a hundred children forwarded +/// 3,500 gas each call [`RETURNS_WORDS`], which their caller warmed, then copy the 500 words it +/// returned, a charge of 1,500 that the 1,385 they have left cannot pay. Each burns those, and the +/// caller completes under a cap of 300,000, as without the read. Counted as compute, the hundred +/// burns would pass the cap. +#[test] +fn test_a_returndatacopy_that_cannot_pay_its_words_burns_what_its_frame_had() { + const WORDS: u64 = 500; + const FORWARD: u32 = 3_500; + const UNDER: u64 = 300_000; + let returns = + BytecodeBuilder::default().push_number(WORDS * 32).append_many([PUSH0, RETURN]).build(); + let child = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(RETURNS_WORDS) + .append_many([GAS, STATICCALL, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .build(); + // The child's four `PUSH0`, its push of the address, `GAS` and the warm call; what the callee + // spends — its two pushes and its memory; then `RETURNDATASIZE`, two `PUSH0` and + // `RETURNDATACOPY`'s static gas. + let warm = crate::salt::entry(GasId::warm_storage_read_cost()); + let left = u64::from(FORWARD) - (8 + 3 + 2 + warm) - (5 + memory_cost(WORDS)) - (2 + 4 + 3); + assert!(left < 3 * WORDS, "the copy is the charge the child cannot pay"); + for gas_limit in TIERS { + let (detained, plain) = with_and_without_read_under(UNDER, |first| { + let code = op(BytecodeBuilder::default(), first) + .push_address(RETURNS_WORDS) + .append_many([EXTCODEHASH, POP]); + let code = calls_to_child(code, 100, FORWARD); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_code(CHILD, child.clone()) + .account_code(RETURNS_WORDS, returns.clone()); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, "a hundred halts on RETURNDATACOPY"); + let regular = plain.outcome.gas.regular - intrinsic(gas_limit); + assert!(regular - 100 * left <= UNDER, "within the cap, the burns aside"); + assert!(regular > UNDER, "the burns counted as compute would pass the cap"); + } +} + +/// The regular gas a call to an existing contract that is not the sender pays before its first +/// instruction, below the execution cap and above it alike: EIP-2780's base of 12,000 and 3,000 +/// for the recipient. The body's history is on the history ledger, whichever pool paid it. +const CALL_INTRINSIC: u64 = 12_000 + 3_000; + +/// A charge the interpreter's step loop makes before the opcode runs — its static gas — is seen by +/// no wrapper, so what a frame had when it fails counts as compute: burned gas counted as compute, +/// which brings the stop earlier, never later, and by less than the failed charge's price per +/// halting frame. +/// +/// Fifty children forwarded 5,002 gas each run a `PUSH20` and a `SELFDESTRUCT`, whose static +/// charge of 5,000 fails with 4,999 left. Under a cap of 200,000 the caller stops, though about +/// 8,500 gas of instructions ran after its read. The child that took the compute past the limit +/// did so without a charge crossing it, so the stop is its caller's next charge, and the stop's +/// compute, which the regular ledger bills, is the limit and that child's overshoot, under the +/// 5,000 it failed to pay. Under a cap of 300,000, above fifty times the forward and the caller's +/// own work, the caller completes as without the read. +/// +/// Rules: [S12.18], [S12]. Independence: independent — the limit, the walk of the charges to the +/// crossing and the intrinsic gas are hand arithmetic from the opcode prices and EIP-2780. +#[test] +fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { + let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + for gas_limit in TIERS { + let build = |first| { + let code = calls_to_child(op(BytecodeBuilder::default(), first), 50, 5_002); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.stop().build()) + .account_code(CHILD, child.clone()); + (db, gas_limit) + }; + let (detained, plain) = with_and_without_read_under(200_000, build); + let limit = detained.limit.unwrap(); + assert_eq!(limit, 2 + 200_000); + assert_eq!(detained.outcome.result.output(), Some(&stop_data(limit))); + // The compute after the read: its `POP`, then each call — five pushes, the address, the + // forward's push, the access, cold the first time — and the child's whole forward, which + // it computes with or burns counted as compute, and the caller's `POP`. The caller's first + // charge the limit leaves no room for is the stop. + let mut since_read = 2; + let crossing = 'calls: { + for call in 0..50 { + let access = if call == 0 { cold_access() } else { 100 }; + for charge in [2, 2, 2, 2, 2, 3, 3, access] { + if since_read + charge > 200_000 { + break 'calls since_read; + } + since_read += charge; + } + since_read += 5_002; + if since_read + 2 > 200_000 { + break 'calls since_read; + } + since_read += 2; + } + panic!("the calls fit the cap"); + }; + assert!(crossing > 200_000 && crossing - 200_000 < 5_000, "an overshoot: {crossing}"); + let used = 2 + crossing; + assert_eq!( + detained.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used, + frame_local: false + }) + ); + assert_eq!(detained.outcome.gas.regular, CALL_INTRINSIC + used); + assert!(plain.outcome.result.is_success()); + let (detained, plain) = with_and_without_read_under(300_000, build); + assert_as_without_read(&detained, &plain, "fifty halts on a static charge"); + } +} + +/// The contract between [`CONTRACT`] and [`CHILD`] in the chain of two halting frames. +const HALTING_MIDDLE: Address = address!("0000000000000000000000000000000000d00013"); + +/// Appends a `CALL` to `to` forwarding `gas`, with no value and no data: five `PUSH0`, the +/// address, the forward's push, then the `CALL`, whose status stays on the stack. +fn call_forwarding(code: BytecodeBuilder, to: Address, gas: u32) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(to) + .push_number(gas) + .append(CALL) +} + +/// One case of [`test_a_static_gas_halt_takes_the_compute_past_the_limit`]: the transaction's +/// code after its read, the cap, and the bill worked out by hand. +struct Overshoot { + name: &'static str, + /// [`CONTRACT`]'s code after its read: the read's `POP`, a call, and what follows it. + after_read: fn(BytecodeBuilder) -> BytecodeBuilder, + /// The block-environment cap. + cap: u64, + /// The transaction's compute, the read's own two gas included, up to the end of the run or + /// to the charge that crossed. + compute: u64, + /// Whether that compute ends on a stop. + stopped: bool, + /// The compute of the same program without the read, which completes. + plain_compute: u64, +} + +/// A frame that halts because it cannot pay an opcode's static gas counts what it had left as +/// compute, and that can take the transaction's compute past the limit without a crossing: no +/// regular charge crossed the limit, so nothing stopped it. The overshoot is less than the static +/// gas the frame failed to pay. Its caller then resumes with no spendable gas, so its next non-zero +/// regular charge is the crossing; a caller whose whole gas cannot pay its own next static gas +/// halts the same way first and adds what it had left, so the overshoots of a chain of halting +/// frames add up. A transaction that makes no non-zero regular charge after the overshoot is not +/// stopped at all, and ends with its compute past the limit. +/// +/// Every halt here is a `SELFDESTRUCT`, whose static gas of 5,000 is the largest. The charges, +/// from the read on: `TIMESTAMP` 2, which is the compute at the read, then `POP` 2; a call is five +/// `PUSH0` at 2, a `PUSH20` and a `PUSH4` at 3, and its cold access of 3,000; a callee forwarded +/// 5,002 runs a `PUSH20` of 3 and halts on its `SELFDESTRUCT` with 4,999 left, all of which is +/// compute. So a call to a halting callee is 3,016 of compute in its caller and the 5,002 it +/// forwarded. +/// +/// - **One frame.** The callee's halt brings the compute from 3,023 to 8,022; under a cap of 3,400 +/// the limit is 3,402, so the halt overshoots it by 4,620, less than 5,000. The caller's `POP` is +/// its next charge and the crossing: the stop reports 8,022, and the bill is the intrinsic gas +/// and that compute, without the `POP`. +/// - **A chain of two.** [`HALTING_MIDDLE`] is forwarded 12,000, calls [`CHILD`] with 5,002 — +/// compute 6,036 at its `CALL`, 6,039 after the child's `PUSH20` — and keeps 12,000 − 3,016 − +/// 5,002 = 3,982. The child's halt brings the compute to 11,038, 4,996 past a limit of 6,042 (a +/// cap of 6,040); the middle frame's next opcode is a `SELFDESTRUCT` its 3,982 cannot pay, so it +/// halts too and adds them: 15,020, 8,978 past the limit, more than either halt could add alone. +/// The caller's `POP` is the crossing. +/// - **No charge after.** The one-frame case ending on `STOP`, which charges nothing, after the +/// call: the transaction succeeds, its compute 8,022, past the limit of 3,402. +/// +/// Each case runs below the execution cap and above it, and is billed the same in both; without +/// the read the program completes and is billed its whole compute. +/// +/// Rules: [S12.18], [S12.24], [S12.38], [S11], [S12]. Independence: independent — every charge is +/// the opcode's price, the limit is the read's compute plus the cap, and the intrinsic gas is +/// EIP-2780's. +#[test] +fn test_a_static_gas_halt_takes_the_compute_past_the_limit() { + let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + // The middle frame's `SELFDESTRUCT` names the status its call left as the beneficiary. + let middle = + call_forwarding(BytecodeBuilder::default(), CHILD, 5_002).append(SELFDESTRUCT).build(); + // The cold access the call to the first callee pays, which every case's caps are set above. + let call = 2 + 2 + 10 + 3 + 3 + cold_access(); + let cases = [ + Overshoot { + name: "one frame", + after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).append(POP).stop(), + cap: 3_400, + compute: call + 5_002, + stopped: true, + plain_compute: call + 5_002 + 2, + }, + Overshoot { + name: "a chain of two", + after_read: |code| { + call_forwarding(code.append(POP), HALTING_MIDDLE, 12_000).append(POP).stop() + }, + cap: 6_040, + compute: call + 12_000, + stopped: true, + plain_compute: call + 12_000 + 2, + }, + Overshoot { + name: "no charge after", + after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).stop(), + cap: 3_400, + compute: call + 5_002, + stopped: false, + plain_compute: call + 5_002, + }, + ]; + for gas_limit in TIERS { + for case in &cases { + let name = case.name; + let (detained, plain) = with_and_without_read_under(case.cap, |first| { + let code = (case.after_read)(BytecodeBuilder::default().append(first)); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.build()) + .account_code(HALTING_MIDDLE, middle.clone()) + .account_code(CHILD, child.clone()); + (db, gas_limit) + }); + let limit = 2 + case.cap; + assert_eq!(detained.limit, Some(limit), "{name}: the read's compute plus the cap"); + assert!(case.compute > limit, "{name}: the halts took the compute past the limit"); + if case.stopped { + assert_eq!( + detained.outcome.result.output(), + Some(&stop_data(limit)), + "{name}: the stop" + ); + assert_eq!( + detained.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: case.compute, + frame_local: false + }), + "{name}: the stop reports the compute past the limit" + ); + } else { + assert!( + detained.outcome.result.is_success(), + "{name}: {:?}", + detained.outcome.result + ); + assert_eq!(detained.outcome.limit_exceeded, None, "{name}: no stop"); + } + assert_eq!( + detained.outcome.gas.regular, + CALL_INTRINSIC + case.compute, + "{name}: the bill is the intrinsic gas and the compute" + ); + assert!(plain.outcome.result.is_success(), "{name}: {:?}", plain.outcome.result); + assert_eq!( + plain.outcome.gas.regular, + CALL_INTRINSIC + case.plain_compute, + "{name}: without the read" + ); + } + } +} + +/// Appends a call carrying one wei to `to` with all the gas, keeping its status. +fn call_keeping_value(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(to) + .append_many([GAS, CALL]) +} + +/* ---------- crossing the cap ---------- */ + +/// A callee given all the gas after its caller's read, which computes past the cap, crosses it: +/// the callee is stopped at the limit, and its caller resumes on what the limit leaves it, which +/// does not pay the store of the failed call's status: the caller is stopped there in turn, and +/// never stores the status it would have stored without the read. +#[test] +fn test_a_callee_computing_past_the_cap_is_stopped() { + let child = work(BytecodeBuilder::default(), 10_000).stop().build(); + for gas_limit in TIERS { + let (detained, plain) = with_and_without_read(|first| { + let parent = store_status(call_keeping_status( + op(BytecodeBuilder::default(), first), + CHILD, + None, + )); + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent) + .account_code(CHILD, child.clone()); + (db, gas_limit) + }); + assert!(plain.outcome.result.is_success()); + assert_eq!(slot(&plain, 0), Some(U256::from(1)), "the callee completes without the read"); + // The read's `POP`, the call's five pushes, its address, `GAS` and cold access, then the + // callee's work, in its own memory. + let left = Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 2, cold_access()]) + .work(10_000, 0) + .left(CAP); + assert!(failed_status_store().crossing(left).is_some(), "the store crosses again"); + assert_caught(&detained, intrinsic(gas_limit), left, &failed_status_store()); + // The store loads the slot for its price, then crosses: the slot is read and left at zero. + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "the caller stored no status"); + } +} + +/// The stop reports the transaction's compute as what was used, whatever a callee burned before +/// it: a caller that read, called a callee of 5,000,000 that halted, then computed to the stop, is +/// billed its compute up to the charge that crossed the limit and what the callee burned, and +/// nothing past either. +#[test] +fn test_the_stop_reports_its_compute_whatever_a_callee_burned() { + // Each callee, and what it computes before it halts: the pushes and the static gas of the + // instruction whose dynamic charge fails, or nothing before an invalid opcode. + let cases: [(&str, Bytes, u64); 3] = [ + ("out of gas", huge_hash(BytecodeBuilder::default()).stop().build(), 3 + 2 + 30), + ("out of memory gas", huge_memory(BytecodeBuilder::default()).stop().build(), 3 + 3), + ("an invalid opcode", BytecodeBuilder::default().append(INVALID).build(), 0), + ]; + for gas_limit in TIERS { + let intrinsic = intrinsic(gas_limit); + for (name, child, computed) in &cases { + let parent = call_keeping_status( + op(BytecodeBuilder::default(), TIMESTAMP), + CHILD, + Some(5_000_000), + ); + let db = MemoryDatabase::default() + .account_code(CONTRACT, spin(parent.append(POP))) + .account_code(CHILD, child.clone()); + let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); + let limit = run.limit.unwrap(); + // The read's `POP`, the call's five pushes, its address, the forward's push and cold + // access, what the callee computed, the caller's `POP`, then its loop. + let left = Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 3, cold_access(), *computed, 2]) + .spin(0) + .left(CAP); + let used = limit - left; + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used, + frame_local: false + }), + "{name}" + ); + let burned = run.outcome.gas.regular - intrinsic - used; + assert!( + (4_990_000..=5_000_000).contains(&burned), + "{name}: the callee burned {burned}" + ); + } + } +} + +/// What a halting callee burns is what it had when it halted, not what it had at an opcode before +/// it: a callee that hashes, then works through 260,000 gas, then hits an invalid opcode burns +/// what it had at the invalid opcode. The transaction its caller stops after it bills that burn +/// beside its compute, to the gas, so the work between the hash and the halt is compute. +#[test] +fn test_a_halt_burns_what_its_frame_had_when_it_halted() { + let hashes = BytecodeBuilder::default().push_number(32_u8).append_many([PUSH0, KECCAK256, POP]); + let child = burn(hashes, 10_000).append(INVALID).build(); + for gas_limit in TIERS { + let parent = + call_keeping_status(op(BytecodeBuilder::default(), TIMESTAMP), CHILD, Some(5_000_000)); + let db = MemoryDatabase::default() + .account_code(CONTRACT, spin(parent.append(POP))) + .account_code(CHILD, child.clone()); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(call.result, InstructionResult::InvalidFEOpcode); + assert!(call.spent > 260_000, "{}", call.spent); + let limit = run.limit.unwrap(); + assert_eq!(run.outcome.result.output(), Some(&stop_data(limit))); + // The read's `POP`, the call's five pushes, its address, the forward's push and cold + // access; the callee's push, `PUSH0`, hash of a word with the memory it expands, `POP` and + // work; then the caller's `POP` and loop. + let callee = Charges::default().then(&[3, 2, 30 + 6 + 3, 2]).burn(10_000).total(); + assert_eq!(call.spent, callee, "the callee spent its charges before the invalid opcode"); + let left = Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 3, cold_access(), callee, 2]) + .spin(0) + .left(CAP); + let burned = run.outcome.gas.regular - intrinsic(gas_limit) - (limit - left); + assert_eq!(burned, 5_000_000 - call.spent, "the callee burned what it had at the halt"); + } +} + +/* ---------- the same bill ---------- */ + +/// Answers every call to `CHILD` itself, with the gas it was forwarded untouched. +struct AnswersChild; + +impl Inspector, EthInterpreter> for AnswersChild { + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + (inputs.target_address == CHILD).then(|| { + let gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + CallOutcome::new( + InterpreterResult::new(InstructionResult::Stop, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } +} + +/// A transaction whose callee stays within the cap bills the same on every ledger with the read +/// and without it, whatever the callee: one that succeeds, reverts or halts on all the gas or on a +/// little; a value call running on its stipend; a creation; the depth guard; a small callee +/// writing a fresh slot; and a callee an inspector answers. +#[test] +fn test_a_callee_within_the_cap_bills_the_same_as_without_the_read() { + let small = |code| work(code, 50); + type Parent = fn(BytecodeBuilder) -> BytecodeBuilder; + let cases: Vec<(&str, Parent, Bytes)> = vec![ + ( + "success", + |c| call_keeping_status(c, CHILD, None), + small(BytecodeBuilder::default()).stop().build(), + ), + ( + "revert", + |c| call_keeping_status(c, CHILD, None), + small(BytecodeBuilder::default()).revert().build(), + ), + ( + "halt", + |c| call_keeping_status(c, CHILD, None), + small(BytecodeBuilder::default()).append(INVALID).build(), + ), + ( + "success on a little gas", + |c| call_keeping_status(c, CHILD, Some(200_000)), + small(BytecodeBuilder::default()).stop().build(), + ), + ( + "halt on a little gas", + |c| call_keeping_status(c, CHILD, Some(200_000)), + small(BytecodeBuilder::default()).append(INVALID).build(), + ), + ( + "a value call running on its stipend, with a log", + |c| { + c.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(CHILD) + .append_many([PUSH0, CALL]) + }, + BytecodeBuilder::default().append_many([PUSH0, PUSH0, LOG0, STOP]).build(), + ), + ( + "a creation", + |c| { + // The initcode returns 32 zero bytes: `PUSH1 0x20 PUSH0 RETURN`. + c.push_number(0x6020_5ff3_u32) + .push_number(0_u8) + .append(MSTORE) + .push_number(4_u8) + .push_number(28_u8) + .append_many([PUSH0, CREATE]) + }, + BytecodeBuilder::default().stop().build(), + ), + ( + "the depth guard", + |c| call_keeping_status(c, RECURSES, None), + BytecodeBuilder::default().stop().build(), + ), + ( + "a fresh slot on 150,000", + |c| call_keeping_status(c, CHILD, Some(150_000)), + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(), + ), + ]; + let recurses = call_keeping_status(BytecodeBuilder::default(), RECURSES, None).stop().build(); + for gas_limit in TIERS { + for (name, parent, child) in &cases { + let (detained, plain) = with_and_without_read(|first| { + let code = store_status(parent(op(BytecodeBuilder::default(), first))); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(10)) + .account_code(CHILD, child.clone()) + .account_code(RECURSES, recurses.clone()); + (db, gas_limit) + }); + assert_as_without_read(&detained, &plain, name); + } + + let answered = |first| { + let code = store_status(call_keeping_status( + op(BytecodeBuilder::default(), first), + CHILD, + Some(200_000), + )); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersChild); + run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)) + }; + assert_as_without_read(&answered(TIMESTAMP), &answered(PUSH0), "an inspector's answer"); + } +} + +/// A call that reads the beneficiary itself, with a little gas or none, with value or without, +/// costs what the same call to a warm empty account that is not the beneficiary costs, on every +/// ledger, the reservoir included: the read withholds nothing the callee or the caller then lacks. +/// The same holds when an inspector answers the call. +#[test] +fn test_a_call_that_reads_the_beneficiary_costs_what_a_warm_account_costs() { + /// Answers every call to `BENEFICIARY` or `OTHER` itself, with the gas it was forwarded. + struct AnswersTargets; + impl Inspector, EthInterpreter> for AnswersTargets { + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + [BENEFICIARY, OTHER].contains(&inputs.target_address).then(|| { + let gas = + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + CallOutcome::new( + InterpreterResult::new(InstructionResult::Stop, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + ) + }) + } + } + for gas_limit in TIERS { + for gas in [0_u32, 100_000] { + for value in [0_u8, 1] { + for answered in [false, true] { + let run = |to: Address| { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(to) + .push_number(gas) + .append_many([CALL, POP, STOP]) + .build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(10)); + // The beneficiary is warm; the other account is warmed by the access list, + // which both transactions carry. + let tx = OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit, + access_list: AccessList::from(vec![AccessListItem { + address: OTHER, + storage_keys: vec![], + }]), + ..Default::default() + })); + let mut evm = MegaEvm::new(context(db)); + if answered { + let mut evm = evm.with_inspector(AnswersTargets); + run_on(&mut evm, tx) + } else { + run_on(&mut evm, tx) + } + }; + let case = format!("gas {gas}, value {value}, answered {answered}"); + let (read, plain) = (run(BENEFICIARY), run(OTHER)); + assert!(read.limit.is_some(), "{case}"); + assert_eq!(read.accessed, VolatileDataAccess::BENEFICIARY_BALANCE, "{case}"); + assert_eq!(plain.limit, None, "{case}"); + assert!(read.outcome.result.is_success(), "{case}: {:?}", read.outcome.result); + assert_eq!(read.outcome.gas, plain.outcome.gas, "{case}"); + assert_eq!( + read.outcome.result.gas().tx_gas_used(), + plain.outcome.result.gas().tx_gas_used(), + "{case}" + ); + } + } + } + } +} + +/* ---------- answers ---------- */ + +/// A precompile that charges the price its input names, as one big-endian word. +pub(crate) const PRICED: Address = address!("0000000000000000000000000000000000d00013"); + +/// The gas limits a precompile was run on, in order, each with whether its price was within it: +/// a precompile that cannot pay its price answers out of gas without computing anything. +pub(crate) type Runs = Arc>>; + +/// The precompile at [`PRICED`], recording what it runs on into `runs`. +pub(crate) fn priced(runs: &Runs) -> DynPrecompile { + let runs = Arc::clone(runs); + DynPrecompile::new(PrecompileId::Custom("priced".into()), move |input| { + let price = U256::from_be_slice(input.data).saturating_to::(); + let within = price <= input.gas; + runs.lock().unwrap().push((input.gas, within)); + Ok(if within { + PrecompileOutput::new(price, Bytes::new(), input.reservoir) + } else { + PrecompileOutput::halt(PrecompileHalt::OutOfGas, input.reservoir) + }) + }) +} + +/// Modexp as the Satin set runs it, recording what it runs on into `runs`. +fn recording_modexp(runs: &Runs) -> DynPrecompile { + let runs = Arc::clone(runs); + DynPrecompile::new(PrecompileId::ModExp, move |input| { + let result = modexp::osaka_run(input.data, input.gas); + runs.lock().unwrap().push((input.gas, result.is_ok())); + Ok(PrecompileOutput::from_eth_result(result, input.reservoir)) + }) +} + +/// The calldata of a modexp that is costly: a 1,024-byte base with no zero byte, an exponent of +/// `exponent_len` bytes, all ones, and an odd one-byte modulus, then `padding` zero bytes the +/// precompile ignores. Its price grows with the exponent. +/// +/// The price is that of a 1,024-byte modulus: it counts the longer of the base and the modulus. +/// The work is sized by the modulus, so the call computes in a moment what an unoptimized test +/// build takes a second over at 1,024 bytes; nothing here depends on how long it computes. +pub(crate) fn costly_modexp_input(exponent_len: usize, padding: usize) -> Vec { + let mut input = Vec::new(); + for len in [1_024_usize, exponent_len, 1] { + input.extend_from_slice(&U256::from(len).to_be_bytes::<32>()); + } + input.extend((0..1_024_u32).map(|i| (i % 251) as u8 + 1)); + input.extend(core::iter::repeat_n(0xff_u8, exponent_len)); + input.push(0xfb); + input.extend(core::iter::repeat_n(0_u8, padding)); + input +} + +/// A contract that copies its calldata into memory and calls `to` with it and `gas` (all of it +/// when `None`), after `first`, storing the call's status. +fn calls_precompile(first: u8, to: Address, gas: Option) -> Bytes { + let code = op(BytecodeBuilder::default(), first) + .append_many([CALLDATASIZE, PUSH0, PUSH0, CALLDATACOPY]) + .append_many([PUSH0, PUSH0, CALLDATASIZE, PUSH0]) + .push_address(to); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + store_status(code.append(STATICCALL)) +} + +/// The regular charges [`calls_precompile`] makes after its first instruction reads, with +/// calldata of `len` bytes, up to its call: the read's `POP`; `CALLDATASIZE`, two `PUSH0` and +/// `CALLDATACOPY` — its static gas, the copy and the memory it expands; the call's four pushes +/// and its address; the push of `gas`, or `GAS`; and the precompile's warm access. +fn charges_to_the_precompile(len: usize, gas: Option) -> Charges { + let words = (len as u64).div_ceil(32); + let forward = if gas.is_some() { 3 } else { 2 }; + Charges::default().then(&[ + 2, + 2, + 2, + 2, + 3, + 3 * words, + memory_cost(words), + 2, + 2, + 2, + 2, + 3, + forward, + 100, + ]) +} + +/// A transaction from `caller` to `to` carrying `input`. +fn tx_to(caller: Address, to: Address, input: &[u8], gas_limit: u64) -> mega_evm::MegaTransaction { + OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(to), + gas_limit, + data: input.to_vec().into(), + ..Default::default() + })) +} + +/// A transaction from `CALLER` to `CONTRACT` carrying `input`. +fn tx_with(input: &[u8], gas_limit: u64) -> mega_evm::MegaTransaction { + tx_to(CALLER, CONTRACT, input, gas_limit) +} + +/// What a transaction carrying `input` spends before its first instruction. +pub(crate) fn intrinsic_with(input: &[u8], gas_limit: u64) -> u64 { + let stops = + MemoryDatabase::default().account_code(CONTRACT, BytecodeBuilder::default().stop().build()); + execute(stops, tx_with(input, gas_limit)).outcome.gas.regular +} + +/// A precompile's run in a transaction: what the transaction did, what the precompile ran on, +/// and the gas its call spent as the caller got it back. +struct PrecompileRun { + run: Run, + ran_on: Vec<(u64, bool)>, + spent: u64, +} + +/// Runs `tx` against `db` with the precompile `make` builds installed at `at`. +fn run_precompile( + db: MemoryDatabase, + at: Address, + make: fn(&Runs) -> DynPrecompile, + tx: mega_evm::MegaTransaction, +) -> PrecompileRun { + let runs = Runs::default(); + let evm = + MegaEvm::new(context(db)).with_dyn_precompiles(HashMap::from_iter([(at, make(&runs))])); + let mut evm = evm.with_inspector(Calls::default()); + let run = run_on(&mut evm, tx); + let spent = evm.inspector().calls.iter().find(|call| call.target == at).unwrap().spent; + let ran_on = runs.lock().unwrap().clone(); + PrecompileRun { run, ran_on, spent } +} + +/// revm runs a precompile inside the frame's start, against the gas limit of the frame, so after +/// a read a precompile the engine cannot price — here a node's own — is run on the allowance the +/// frame would have — what the limit leaves the transaction — and never on what its caller +/// forwarded past it. Without the read, it runs on the forward. +/// +/// Priced within the allowance, it answers as without the read. Priced at the allowance exactly, +/// it answers, and its caller's next charge — the push of its status's slot — crosses the limit. +/// Priced a unit past it, it answers out of gas without computing, and is the stop, billed nothing +/// of the allowance the precompile ran on, which its caller catches before it stores the failed +/// call's status. +#[test] +fn test_a_precompile_runs_on_the_allowance() { + for gas_limit in TIERS { + let run = |first, price: u64| { + let code = calls_precompile(first, PRICED, None); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let input = U256::from(price).to_be_bytes::<32>(); + run_precompile(db, PRICED, priced, tx_with(&input, gas_limit)) + }; + // The price is the charge after the call, then the push of the status's slot. + let to_the_call = charges_to_the_precompile(32, None); + let allowance = CAP - to_the_call.total(); + let stopped = |run: &PrecompileRun, price: u64| { + let input = U256::from(price).to_be_bytes::<32>(); + let intrinsic = intrinsic_with(&input, gas_limit); + if price > allowance { + // The precompile's price is the crossing: its call is the stop. + assert_caught(&run.run, intrinsic, allowance, &failed_status_store()); + } else { + let left = to_the_call.clone().then(&[price, 3]).left(CAP); + assert_stopped(&run.run, intrinsic, left); + } + }; + + // Priced past every allowance: the stop. + let past = run(TIMESTAMP, CAP + 1); + stopped(&past, CAP + 1); + assert_eq!(past.ran_on, [(allowance, false)], "run on the allowance, computing nothing"); + assert_eq!(past.spent, 0, "the stop gives the precompile its whole forward back"); + + for price in [allowance - 100_000, allowance, allowance + 1] { + let (detained, plain) = (run(TIMESTAMP, price), run(PUSH0, price)); + assert_eq!(detained.ran_on, [(allowance, price <= allowance)], "priced {price}"); + assert!(matches!(plain.ran_on[..], [(forward, true)] if forward > CAP), "{price}"); + assert_eq!(slot(&plain.run, 0), Some(U256::from(1))); + if price < allowance { + assert_as_without_read(&detained.run, &plain.run, "a price the allowance pays"); + } else { + stopped(&detained, price); + } + } + } +} + +/// Modexp on a costly input, replaced by a node's recording copy of it, which the engine does not +/// price, after a read, against the same call without it: +/// +/// - priced within the allowance, it computes on the allowance and answers as without the read; +/// - priced past the allowance but within what its caller forwarded, it runs out of the allowance +/// without computing, and is the stop, which its caller catches — without the read it computes; +/// - forwarded less than its price, within the allowance, it runs out of gas as without the read; +/// - forwarded less than its price, past the allowance, it runs out of the allowance too, and is +/// the stop. Without the read the call fails and burns its forward: with no price, it cannot be +/// told from one priced within the forward. +/// +/// The cheap input is padded to the length of the costly one, so the two calls leave the same +/// allowance, which the stop's bill reads out. +#[test] +fn test_a_precompile_is_held_to_what_the_limit_leaves() { + let (within, above) = (costly_modexp_input(32, 32), costly_modexp_input(64, 0)); + assert_eq!(within.len(), above.len()); + for gas_limit in TIERS { + let run = |first, gas, input: &[u8]| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, gas)); + run_precompile(db, MODEXP, recording_modexp, tx_with(input, gas_limit)) + }; + + let (detained, plain) = (run(TIMESTAMP, None, &above), run(PUSH0, None, &above)); + let allowance = CAP - charges_to_the_precompile(above.len(), None).total(); + let intrinsic = intrinsic_with(&above, gas_limit); + assert_caught(&detained.run, intrinsic, allowance, &failed_status_store()); + assert_eq!(detained.ran_on, [(allowance, false)], "past the allowance, nothing computed"); + let above_price = plain.spent; + assert!(allowance < CAP && CAP < above_price, "{allowance} {above_price}"); + assert!(plain.ran_on[0].1, "without the read it computes"); + assert_eq!(slot(&plain.run, 0), Some(U256::from(1))); + + let (detained, plain) = (run(TIMESTAMP, None, &within), run(PUSH0, None, &within)); + assert_as_without_read(&detained.run, &plain.run, "a price within the allowance"); + assert_eq!(detained.ran_on, [(allowance, true)], "run on the allowance"); + assert_eq!(slot(&detained.run, 0), Some(U256::from(1))); + let within_price = plain.spent; + assert!(within_price < allowance, "{within_price}"); + + // Forwarded less than its price, within the allowance: the call's own out-of-gas. + let short = u32::try_from(within_price).unwrap() - 1; + let (detained, plain) = + (run(TIMESTAMP, Some(short), &within), run(PUSH0, Some(short), &within)); + assert_as_without_read( + &detained.run, + &plain.run, + "a price above a forward the allowance holds", + ); + assert_eq!(detained.ran_on, [(u64::from(short), false)]); + assert_eq!(slot(&detained.run, 0), Some(U256::ZERO)); + + // Forwarded less than its price, past the allowance: the stop, where the call would fail. + let short = u32::try_from(above_price).unwrap() - 1; + let (detained, plain) = + (run(TIMESTAMP, Some(short), &above), run(PUSH0, Some(short), &above)); + let allowance = CAP - charges_to_the_precompile(above.len(), Some(short)).total(); + assert_caught(&detained.run, intrinsic, allowance, &failed_status_store()); + assert_eq!(detained.ran_on, [(allowance, false)], "run on the allowance"); + assert_eq!(plain.ran_on, [(u64::from(short), false)]); + assert!(plain.run.outcome.result.is_success()); + assert_eq!(slot(&plain.run, 0), Some(U256::ZERO), "without the read the call fails"); + } +} + +/// A modexp priced far above the cap, 58,687,488 and 125,796,352 gas, called after a read with all +/// the gas. +/// +/// The built-in set the chain runs prices it before it runs: priced within what its caller +/// forwarded, it needs gas the limit withholds, and is the stop, answered without running, which +/// its caller catches; priced past the forward, it runs out of gas as it does without the read, +/// and its caller goes on. Below +/// the execution cap the forward is under 100,000,000, so the two prices fall on either side of +/// it; above the cap both are within it. +/// +/// A modexp a node replaced is not priced: it is run on the allowance, computes nothing, and is +/// the stop, whatever its price. A transaction the beneficiary sends straight to it is detained +/// from the start, so it runs on the cap itself, and its stop is the transaction's. The same +/// transaction from another sender computes. +#[test] +fn test_a_precompile_priced_past_the_cap_computes_nothing() { + let mut cases = (0, 0); + for (exponent_len, price) in [(128, 58_687_488), (256, 125_796_352)] { + let input = costly_modexp_input(exponent_len, 0); + let builtin = mega_evm::satin_precompiles().get(&MODEXP).unwrap(); + assert_eq!(builtin.required_gas(&input), Some(price), "the built-in's price"); + // Without the read, it computes, and costs its price on top of what the transaction spends + // before its first instruction. + let plain = run_precompile( + MemoryDatabase::default(), + MODEXP, + recording_modexp, + tx_to(CALLER, MODEXP, &input, ABOVE), + ); + assert!(plain.run.outcome.result.is_success()); + assert!(matches!(plain.ran_on[..], [(_, true)]), "{:?}", plain.ran_on); + assert_eq!(plain.spent, price); + let intrinsic = plain.run.outcome.gas.regular - price; + + for gas_limit in TIERS { + let db = |first| { + MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, MODEXP, None)) + }; + let called = + run_precompile(db(TIMESTAMP), MODEXP, recording_modexp, tx_with(&input, gas_limit)); + let allowance = CAP - charges_to_the_precompile(input.len(), None).total(); + let called_intrinsic = intrinsic_with(&input, gas_limit); + assert_caught(&called.run, called_intrinsic, allowance, &failed_status_store()); + assert_eq!(called.ran_on, [(allowance, false)], "run on the allowance"); + + let built_in = |first| { + let mut evm = MegaEvm::new(context(db(first))).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(&input, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == MODEXP).unwrap(); + let (forward, ran) = (call.forward, call.precompile_ran); + (run, forward, ran) + }; + let (detained, forward, ran) = built_in(TIMESTAMP); + let (plain, plain_forward, plain_ran) = built_in(PUSH0); + assert_eq!(forward, plain_forward, "the read leaves the forward as it is"); + assert!(forward > CAP, "{forward}"); + if price <= forward { + assert_caught(&detained, called_intrinsic, allowance, &failed_status_store()); + assert!(!ran, "answered without running"); + assert!(plain_ran && plain.outcome.result.is_success()); + assert_eq!(slot(&plain, 0), Some(U256::from(1)), "without the read it computes"); + cases.0 += 1; + } else { + assert_as_without_read(&detained, &plain, "a price past the forward"); + assert!(ran && plain_ran, "run on the forward, out of gas"); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "the call fails"); + cases.1 += 1; + } + + let tx = tx_to(BENEFICIARY, MODEXP, &input, gas_limit); + let sent = run_precompile(MemoryDatabase::default(), MODEXP, recording_modexp, tx); + assert_eq!(sent.run.limit, Some(CAP), "the sender is the beneficiary"); + assert_eq!(sent.ran_on, [(CAP, false)], "run on the cap, computing nothing"); + assert_eq!(sent.spent, 0, "the stop gives the precompile its whole forward back"); + assert_stopped(&sent.run, intrinsic, CAP); + } + } + assert_eq!(cases, (3, 1), "the stop above the cap for both, and below it for the cheaper"); +} + +/// The built-in modexp, priced from its input, is held from its price as the size-limited wrappers +/// are, below. +#[test] +fn test_the_modexp_is_held_from_its_price() { + let input = costly_modexp_input(32, 32); + let price = mega_evm::satin_precompiles().get(&MODEXP).unwrap().required_gas(&input).unwrap(); + assert_held_from_its_price(MODEXP, &input, price); +} + +/// The KZG point evaluation is priced by the Satin table, so a call forwarded less than its price +/// and more than the allowance — 100,000, forwarded 80,000 under a cap of 50,000 — runs on its +/// forward and runs out of gas as without the read, and its caller goes on, where a node's own +/// precompile, which the engine cannot price, keeps the clamp. +#[test] +fn test_the_kzg_point_evaluation_is_priced_and_keeps_no_clamp() { + let kzg = vec![0_u8; 192]; + let kzg_address = mega_evm::kzg_point_evaluation::ADDRESS; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(50_000); + for gas_limit in TIERS { + let run = |first| { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(first, kzg_address, Some(80_000))); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(&kzg, gas_limit)); + let call = + evm.inspector().calls.iter().find(|call| call.target == kzg_address).unwrap(); + assert_eq!(call.forward, 80_000); + assert!(call.precompile_ran, "{kzg_address}: revm runs it, on its forward"); + run + }; + let (detained, plain) = (run(TIMESTAMP), run(PUSH0)); + assert_as_without_read(&detained, &plain, "a price past the forward"); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "the call fails and its caller goes on"); + } +} + +/// A precompile priced between the allowance and its forward whose input fails a check made after +/// its gas check: the BN254 pairing of three pairs and a stray byte, priced 147,000 for its three +/// whole pairs, which checks the input's length after its gas. Under a cap of 100,000 it is +/// answered without running, before the length check, with the stop, which gives its forward back +/// and which the caller catches before it stores the failure; without the read the length check +/// fails the call, which burns its forward, and the caller goes on to store the failure. Under the +/// default cap the allowance pays the price, and the call fails on its input as without the read. +#[test] +fn test_a_precompile_whose_input_fails_past_its_gas_check_stops_past_the_allowance() { + let input = vec![0_u8; 3 * 192 + 1]; + for gas_limit in TIERS { + let run = |first, cap| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let code = calls_precompile(first, EC_PAIRING, None); + let db = MemoryDatabase::default().account_code(CONTRACT, code); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(&input, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == EC_PAIRING).unwrap(); + (run, call.precompile_ran) + }; + let ((detained, ran), (plain, plain_ran)) = (run(TIMESTAMP, 100_000), run(PUSH0, 100_000)); + let allowance = 100_000 - charges_to_the_precompile(input.len(), None).total(); + let intrinsic = intrinsic_with(&input, gas_limit); + assert_caught(&detained, intrinsic, allowance, &failed_status_store()); + assert!(!ran && plain_ran, "answered without running"); + assert!(plain.outcome.result.is_success()); + assert_eq!(slot(&plain, 0), Some(U256::ZERO), "without the read the call fails"); + let ((detained, _), (plain, _)) = (run(TIMESTAMP, CAP), run(PUSH0, CAP)); + assert_as_without_read(&detained, &plain, "a price the allowance pays"); + assert_eq!(slot(&detained, 0), Some(U256::ZERO), "the call fails on its input"); + } +} + +/// A size-limited precompile of the Satin set called with `input`, which its EIP prices at +/// `price`, after a read, against the same call without it: +/// +/// - forwarded all the gas under a cap that leaves it less than its price, it needs gas the limit +/// withholds: it is answered without running, with the stop, which its caller catches, where +/// without the read it computes; +/// - under the spec's cap, which leaves it its price, revm runs it and it charges its price, as +/// without the read; +/// - forwarded one gas short of its price under a cap that leaves it less still, it runs on its +/// forward and runs out of gas as without the read, and its caller goes on. +fn assert_held_from_its_price(to: Address, input: &[u8], price: u64) { + let entry = mega_evm::satin_precompiles().get(&to).unwrap(); + assert_eq!(entry.required_gas(input), Some(price), "the entry's price is the EIP's"); + let short = u32::try_from(price - 1).unwrap(); + let cap = price / 2; + for gas_limit in TIERS { + let run = |first, cap, gas| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let db = + MemoryDatabase::default().account_code(CONTRACT, calls_precompile(first, to, gas)); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx_with(input, gas_limit)); + let call = evm.inspector().calls.iter().find(|call| call.target == to).unwrap(); + let (forward, spent, ran) = (call.forward, call.spent, call.precompile_ran); + (run, forward, spent, ran) + }; + + // Past the allowance, within the forward: the stop, without running. + let (detained, forward, _, ran) = run(TIMESTAMP, cap, None); + let (plain, _, plain_spent, plain_ran) = run(PUSH0, cap, None); + let allowance = cap - charges_to_the_precompile(input.len(), None).total(); + assert!(allowance < price && price <= forward, "{to}: {allowance} {price} {forward}"); + let intrinsic = intrinsic_with(input, gas_limit); + assert_caught(&detained, intrinsic, allowance, &failed_status_store()); + assert!(!ran, "{to}: answered without running"); + assert!(plain_ran && plain.outcome.result.is_success(), "{to}"); + assert_eq!(plain_spent, price, "{to}: without the read it computes, at its price"); + assert_eq!(slot(&plain, 0), Some(U256::from(1)), "{to}"); + + // Within the allowance: run, at its price, as without the read. + let (detained, _, spent, ran) = run(TIMESTAMP, CAP, None); + let (plain, ..) = run(PUSH0, CAP, None); + assert!(ran, "{to}: revm runs it"); + assert_eq!(spent, price, "{to}: it charges its price"); + assert_as_without_read(&detained, &plain, "a price the allowance pays"); + assert_eq!(slot(&detained, 0), Some(U256::from(1)), "{to}"); + + // Past the whole forward: run on the forward, out of gas, as without the read. + let (detained, forward, _, ran) = run(TIMESTAMP, cap, Some(short)); + let (plain, ..) = run(PUSH0, cap, Some(short)); + let allowance = cap - charges_to_the_precompile(input.len(), Some(short)).total(); + assert!(allowance < forward && forward < price, "{to}: {allowance} {forward} {price}"); + assert!(ran, "{to}: revm runs it"); + assert_as_without_read(&detained, &plain, "a price past the forward"); + assert_eq!( + slot(&detained, 0), + Some(U256::ZERO), + "{to}: the call fails, its caller goes on" + ); + } +} + +/// op-revm's wrapper of the BN254 pairing, two pairs of zeros: 45,000, and 34,000 a pair +/// (EIP-1108). +#[test] +fn test_the_bn254_pairing_is_held_from_its_price() { + assert_held_from_its_price(EC_PAIRING, &[0; 2 * 192], 45_000 + 2 * 34_000); +} + +/// op-revm's wrapper of the BLS12-381 G1 MSM, two pairs of zeros: 12,000 a pair, discounted to +/// 949 per mille for two (EIP-2537). +#[test] +fn test_the_bls12_g1_msm_is_held_from_its_price() { + assert_held_from_its_price(BLS12_G1_MSM, &[0; 2 * 160], 2 * 12_000 * 949 / 1_000); +} + +/// op-revm's wrapper of the BLS12-381 G2 MSM, two pairs of zeros: 22,500 a pair, undiscounted for +/// two (EIP-2537). +#[test] +fn test_the_bls12_g2_msm_is_held_from_its_price() { + assert_held_from_its_price(BLS12_G2_MSM, &[0; 2 * 288], 2 * 22_500 * 1_000 / 1_000); +} + +/// op-revm's wrapper of the BLS12-381 pairing, two pairs of zeros: 37,700, and 32,600 a pair +/// (EIP-2537). +#[test] +fn test_the_bls12_pairing_is_held_from_its_price() { + assert_held_from_its_price(BLS12_PAIRING, &[0; 2 * 384], 37_700 + 2 * 32_600); +} + +/// A keyless deployment's call is the transaction's own frame, and runs no code: its own charges — +/// the overhead of decoding the transaction and recovering its signer, then the `CREATE` opcode's +/// regular gas — are compute, drawn from gas held to what the limit leaves the frame, whether a +/// rule then refuses the call or its creation runs. A `keylessDeploy` call from the beneficiary, +/// detained from its start, carrying value (refused, `NoEtherTransfer()`) or deploying the +/// canonical `CREATE2` factory, against the same call from another sender, plain and inspected: +/// +/// - under a cap below the overhead, the overhead alone crosses the limit, and the refusal stops at +/// it; +/// - under a cap past the overhead and short of the `CREATE` opcode's regular gas, the refusal +/// answers as without the read, and the deployment stops at the opcode's charge. +#[test] +fn test_a_keyless_calls_charges_are_held_to_what_the_limit_leaves() { + let refused = keyless_deploy_call(b"a transaction"); + let deploys = keyless_deploy_call(CREATE2_FACTORY_TX); + let init_code = decode_keyless_tx(CREATE2_FACTORY_TX).unwrap().tx().input.len(); + let create = satin_gas_params().create_cost() + satin_gas_params().initcode_cost(init_code); + for gas_limit in TIERS { + let run = |caller: Address, value: u64, data: &Bytes, cap: u64, inspected: bool| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let db = MemoryDatabase::default() + .account_balance(caller, U256::from(10)) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE); + let tx = OpTx(op_transaction(TxEnv { + caller, + kind: TxKind::Call(KEYLESS_DEPLOY_ADDRESS), + gas_limit, + value: U256::from(value), + data: data.clone(), + ..Default::default() + })); + let evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + if inspected { + run_on(&mut evm.with_inspector(Calls::default()), tx) + } else { + run_on(&mut { evm }, tx) + } + }; + // Each case plain and inspected: the inspected path settles the call as the plain one. + let both = |caller, value, data: &Bytes, cap| { + let plain = run(caller, value, data, cap, false); + let inspected = run(caller, value, data, cap, true); + assert_eq!(inspected.outcome.result, plain.outcome.result, "{caller} under {cap}"); + assert_eq!(inspected.outcome.gas, plain.outcome.gas, "{caller} under {cap}"); + plain + }; + let answered = both(CALLER, 1, &refused, CAP); + assert_eq!( + answered.outcome.result.output(), + Some(&Bytes::from(IKeylessDeploy::NoEtherTransfer::SELECTOR.to_vec())), + "the answer without detention" + ); + let refused_intrinsic = answered.outcome.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; + let deploy_intrinsic = intrinsic_with(&deploys, gas_limit); + + // Detained from its start, the call's overhead is its first charge, then the `CREATE` + // opcode's, then its creation's, whose last is the hash of the code it deposits. + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS / 2; + let detained = both(BENEFICIARY, 1, &refused, cap); + assert_eq!(detained.limit, Some(cap), "the sender is the beneficiary"); + assert_stopped(&detained, refused_intrinsic, cap); + + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + create - 1; + let detained = both(BENEFICIARY, 1, &refused, cap); + assert_eq!(detained.outcome.result, answered.outcome.result, "the overhead fits"); + assert_eq!(detained.outcome.gas, answered.outcome.gas); + let stopped = both(BENEFICIARY, 0, &deploys, cap); + let left = Charges::default().then(&[KEYLESS_DEPLOY_OVERHEAD_GAS, create]).left(cap); + assert_eq!(left, create - 1); + assert_stopped(&stopped, deploy_intrinsic, left); + assert_eq!(nonce_of(&stopped, CREATE2_FACTORY_DEPLOYER), 0, "the creation never started"); + } +} + +/// A refused `keylessDeploy` call is an answer held to the allowance by the regular gas it spent: +/// below the execution cap, the signer's account it was charged spills onto its regular gas, and +/// that is state gas, not compute. The canonical `CREATE2` factory's signer has no account, and +/// its address is taken, so the call pays the overhead and the signer's account and is refused +/// `ContractAlreadyExists()`. From the beneficiary, under a cap past the overhead and short of the +/// two together, it is refused as without the read, below and above the cap. +#[test] +fn test_a_refused_keyless_calls_spilled_state_gas_is_not_compute() { + let data = keyless_deploy_call(CREATE2_FACTORY_TX); + for gas_limit in TIERS { + let run = |caller: Address, cap: u64| { + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let db = MemoryDatabase::default() + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE) + .account_code(CREATE2_FACTORY_CONTRACT, BytecodeBuilder::default().stop().build()); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); + run_on(&mut evm, tx_to(caller, KEYLESS_DEPLOY_ADDRESS, &data, gas_limit)) + }; + let refused = run(CALLER, CAP); + assert_eq!( + refused.outcome.result.output(), + Some(&Bytes::from(IKeylessDeploy::ContractAlreadyExists::SELECTOR.to_vec())), + ); + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS + 1_000; + let detained = run(BENEFICIARY, cap); + assert_eq!(detained.limit, Some(cap), "the sender is the beneficiary"); + assert_eq!(detained.outcome.result, refused.outcome.result, "refused as without the read"); + assert_eq!(detained.outcome.gas, refused.outcome.gas); + assert_eq!(detained.outcome.limit_exceeded, None); + } +} + +/// The calldata of a `keylessDeploy` call carrying `tx`, with a `gasLimitOverride` past any +/// forward. +fn keyless_deploy_call(tx: &[u8]) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::copy_from_slice(tx), + gasLimitOverride: U256::from(u64::MAX), + } + .abi_encode() + .into() +} + +/// The nonce `address` ends the transaction with; zero when the transaction did not touch it. +fn nonce_of(run: &Run, address: Address) -> u64 { + run.outcome.state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// Answers the call to [`CONTRACT`] itself: past the cap in regular gas, and with 1,000 of state or +/// history gas charged on top. +#[derive(Clone, Copy)] +struct AnswersPastTheCapWithASpill { + history: bool, +} + +impl Inspector, EthInterpreter> for AnswersPastTheCapWithASpill { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if inputs.target_address != CONTRACT { + return None; + } + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + assert!(gas.record_regular_cost(CAP + 1)); + if self.history { + assert!(gas.record_history_cost(1_000)); + } else { + assert!(gas.record_state_cost(1_000)); + } + Some(CallOutcome::new( + InterpreterResult::new(InstructionResult::Return, Bytes::new(), gas), + inputs.return_memory_offset.clone(), + )) + } +} + +/// An answer past the allowance is the stop, billed the intrinsic gas alone, whatever state or +/// history gas the answer charged: the answer's spending is the charge that crossed, so none of it +/// is made, and the frame, detained from its start, computed nothing before it. Below the +/// execution cap the state or history gas spills onto regular gas and the stop's revert gives it +/// back; above the cap the reservoir pays it and nothing spills. +#[test] +fn test_an_answer_past_the_allowance_with_a_spill_is_billed_nothing_of_it() { + for gas_limit in TIERS { + for history in [false, true] { + let db = MemoryDatabase::default().account_code(CONTRACT, Bytes::from_static(&[STOP])); + let intrinsic = run_on( + &mut MegaEvm::new(context(db.clone())), + tx(BENEFICIARY, CONTRACT, gas_limit), + ) + .outcome + .gas + .regular; + let mut evm = + MegaEvm::new(context(db)).with_inspector(AnswersPastTheCapWithASpill { history }); + let run = run_on(&mut evm, tx(BENEFICIARY, CONTRACT, gas_limit)); + assert_eq!(run.outcome.result.output(), Some(&stop_data(CAP)), "{gas_limit} {history}"); + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: CAP, + used: 0, + frame_local: false + }), + "{gas_limit}, history {history}" + ); + assert_eq!(run.outcome.gas.regular, intrinsic, "{gas_limit}, history {history}"); + } + } +} diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index 0367cedb4..f2aac4aba 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -7,35 +7,62 @@ //! transaction's own value recipient or created account. The sender's own account is part of the //! transaction body and is not a record. Records are deduplicated per frame and discarded with the //! frame that fails. +//! +//! Every value movement also leaves an EIP-7708 transfer log, which is data size and not a record: +//! the figures below carry [`TRANSFER_LOG_SIZE`] for each one a transaction keeps. use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use alloy_sol_types::SolCall; use mega_evm::{ - test_utils::{BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, StagedRecord, WRITE_RECORD_SIZE, + system::{ + IMegaAccessControl, IOracle, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + }, + test_utils::{is_transfer_log, BytecodeBuilder, MemoryDatabase}, + LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, - SELFDESTRUCT, SSTORE, STOP, + CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, + REVERT, SELFDESTRUCT, SSTORE, STOP, }, interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Database, Inspector, }; -use crate::common::{call, call_with_data, context, create, run}; +use crate::common::{account_state_gas, call, call_with_data, context, create, history, run}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); const CALLEE: Address = address!("0000000000000000000000000000000000100001"); const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); /// Room for the state gas of several new accounts, including in a frame that resumes after a -/// child burned the 63/64 it was forwarded. -const GAS_LIMIT: u64 = 50_000_000; +/// child burned the 63/64 it was forwarded: at least 50,000,000, and 64 times what a value call to +/// a new account costs its caller at the byte prices in effect. +fn gas_limit() -> u64 { + (64 * (account_state_gas() + history(4 * WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) +} +/// The transaction body and nothing else. +const fn body_only() -> LimitUsage { + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } +} + +/// `n` write records on top of the transaction body. const fn records(n: u64) -> LimitUsage { + LimitUsage { data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, write_records: n } +} + +/// `n` write records and no body: the difference between two transactions that carry the same one. +const fn records_only(n: u64) -> LimitUsage { LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } } +fn with_extra(usage: LimitUsage, bytes: u64) -> LimitUsage { + LimitUsage { data_size: usage.data_size + bytes, ..usage } +} + fn funded() -> MemoryDatabase { MemoryDatabase::default() .account_balance(CALLER, U256::from(10_000_000)) @@ -66,9 +93,13 @@ fn test_two_value_calls_record_the_sender_once() { let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(3), "CALLEE once, CONTRACT, CONTRACT2"); + assert_eq!( + usage, + with_extra(records(3), 2 * TRANSFER_LOG_SIZE), + "CALLEE once, CONTRACT, CONTRACT2, and a transfer log for each transfer" + ); } /// A creation and a value transfer from one frame record the frame's account once. @@ -77,9 +108,13 @@ fn test_create_then_call_record_the_frame_account_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_call(code, CONTRACT, 1).append(POP).append(STOP).build(); let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(3), "CALLEE once, the created account, CONTRACT"); + assert_eq!( + usage, + with_extra(records(3), 2 * TRANSFER_LOG_SIZE), + "CALLEE once, the created account, CONTRACT, and a transfer log for each endowment" + ); } /// Two creations from one frame record the creator once and each created account. @@ -88,9 +123,13 @@ fn test_two_creates_record_the_creator_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_create(code).append(POP).append(STOP).build(); let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(3), "CALLEE once, two created accounts"); + assert_eq!( + usage, + with_extra(records(3), 2 * TRANSFER_LOG_SIZE), + "CALLEE once, two created accounts, and a transfer log for each endowment" + ); } /// A value transfer into a child that fails is discarded with the child, sender included. @@ -100,21 +139,38 @@ fn test_failed_child_discards_its_transfer_records() { append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success(), "the outer call succeeds although the child halts"); - assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(usage, body_only()); } /// After a failed transfer the sender can be recorded again by the next one. +/// +/// The first child burns the gas it was forwarded, so the second transfer forwards none: its +/// recipient runs no code, and the records it makes are paid out of what the caller keeps, which +/// then does not depend on the price of the recipient's new account. #[test] fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); - let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let code = code + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(PUSH1) + .append(1u8) + .push_address(CONTRACT2) + .append(PUSH0) + .append(CALL) + .append(POP) + .append(STOP) + .build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(2), "CALLEE and CONTRACT2, from the second transfer"); + assert_eq!( + usage, + with_extra(records(2), TRANSFER_LOG_SIZE), + "CALLEE and CONTRACT2 and the transfer log, from the second transfer" + ); } const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); @@ -130,21 +186,12 @@ fn reverting_creations(n: usize) -> Bytes { code.into() } -/// A reverted creation keeps the creator's nonce record: the nonce bump survives the revert. -#[test] -fn test_reverted_nested_create_keeps_the_creator_nonce_record() { - let db = funded().account_code(OUTER_CREATOR, reverting_creations(1)); - let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); - assert!(result.result.is_success()); - assert_eq!(usage, records(1), "the creator's nonce; the created account is gone"); -} - /// Two reverted creations record the creator once: the first record survives, so the second /// finds the creator recorded. #[test] fn test_reverted_then_retried_create_records_the_creator_once() { let db = funded().account_code(OUTER_CREATOR, reverting_creations(2)); - let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(usage, records(1)); } @@ -161,9 +208,9 @@ fn test_creation_without_funds_records_nothing() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(usage, body_only()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); } @@ -173,8 +220,8 @@ const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004" fn value_delta(to: Address) -> LimitUsage { let db = || MemoryDatabase::default().account_balance(A, U256::from(1_000_000)); - let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), GAS_LIMIT)); - let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, GAS_LIMIT)); + let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), gas_limit())); + let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, gas_limit())); assert!(with_value.result.is_success() && zero_value.result.is_success()); usage_value.saturating_sub(usage_zero) } @@ -188,7 +235,7 @@ fn test_top_level_self_transfer_no_double_count() { /// A top-level transfer to another account records the recipient. #[test] fn test_top_level_transfer_counts_the_recipient() { - assert_eq!(value_delta(B), records(1)); + assert_eq!(value_delta(B), with_extra(records_only(1), TRANSFER_LOG_SIZE), "and its log"); } /// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty @@ -219,7 +266,7 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { .account_balance(SELF_CALLER, U256::from(1_000_000)) .account_code(SELF_CALLER, self_calling_code(targets, value)); let (result, usage) = - run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), GAS_LIMIT)); + run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), gas_limit())); assert!(result.result.is_success()); usage }; @@ -229,14 +276,18 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { /// A nested transfer to the frame's own account is one account write. #[test] fn test_nested_self_call_with_value_counts_once() { - assert_eq!(nested_delta(&[SELF_CALLER]), records(1)); + assert_eq!(nested_delta(&[SELF_CALLER]), records_only(1)); } /// After a transfer to another account recorded the frame's account, a transfer to itself adds /// nothing. #[test] fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { - assert_eq!(nested_delta(&[B, SELF_CALLER]), records(2)); + assert_eq!( + nested_delta(&[B, SELF_CALLER]), + with_extra(records_only(2), TRANSFER_LOG_SIZE), + "the transfer to B and its log" + ); } /* ---------- storage, logs, selfdestruct ---------- */ @@ -248,7 +299,7 @@ fn test_sstore_first_change_records_and_write_back_refunds() { let cases: [(Writes, u64, LimitUsage); 4] = [ (&[(0, 1)], 0, records(1)), (&[(0, 1), (0, 2)], 0, records(1)), - (&[(0, 1), (0, 0)], 0, LimitUsage::ZERO), + (&[(0, 1), (0, 0)], 0, body_only()), (&[(0, 0)], 5, records(1)), ]; for (writes, original, expected) in cases { @@ -259,7 +310,7 @@ fn test_sstore_first_change_records_and_write_back_refunds() { let db = MemoryDatabase::default() .account_code(CALLEE, code.stop().build()) .account_storage(CALLEE, U256::ZERO, U256::from(original)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(usage, expected, "writes {writes:?} over original {original}"); } @@ -272,7 +323,7 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); let failing_child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).append(INVALID).build(); - for (code, expected) in [(child, LimitUsage::ZERO), (failing_child, records(1))] { + for (code, expected) in [(child, body_only()), (failing_child, records(1))] { // CALLEE writes slot 0, then DELEGATECALLs CONTRACT, which writes it back in CALLEE's // storage. let parent = BytecodeBuilder::default() @@ -286,50 +337,31 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(usage, expected); } } -/// A log counts 32 bytes for its address, 32 per topic and its data; no write record. -#[test] -fn test_log_counts_its_bytes() { - let code = BytecodeBuilder::default() - .push_number(0x22_u8) - .push_number(0x11_u8) - .push_number(10_u8) - .append(PUSH0) - .append(LOG2) - .stop() - .build(); - let (result, usage) = run( - MemoryDatabase::default().account_code(CALLEE, code), - call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - ); - assert!(result.result.is_success()); - assert_eq!(result.result.logs().len(), 1); - assert_eq!(usage, LimitUsage { data_size: 32 + 2 * 32 + 10, write_records: 0 }); -} - /// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the -/// destructed one and the sender, whose account the transaction body counts. +/// destructed one and the sender, whose account the transaction body counts. A move to the sender +/// still leaves its transfer log; a destruction to itself burns the balance and leaves none. #[test] fn test_selfdestruct_records_the_beneficiary_when_value_moves() { let destruct_to = |beneficiary: Address| { BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() }; let cases = [ - (U256::from(5), CONTRACT, records(1)), - (U256::from(5), CALLEE, LimitUsage::ZERO), - (U256::from(5), CALLER, LimitUsage::ZERO), - (U256::ZERO, CONTRACT, LimitUsage::ZERO), + (U256::from(5), CONTRACT, with_extra(records(1), TRANSFER_LOG_SIZE)), + (U256::from(5), CALLEE, body_only()), + (U256::from(5), CALLER, with_extra(body_only(), TRANSFER_LOG_SIZE)), + (U256::ZERO, CONTRACT, body_only()), ]; for (balance, beneficiary, expected) in cases { let db = MemoryDatabase::default() .account_code(CALLEE, destruct_to(beneficiary)) .account_balance(CALLEE, balance); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); } @@ -338,15 +370,157 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { /// A top-level creation records the created account, and nothing when it fails. #[test] fn test_top_level_create_records_the_created_account() { + // `STOP` is one byte of init code and deposits nothing. let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), GAS_LIMIT)); + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(1)); + assert_eq!(usage, with_extra(records(1), 1)); let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), GAS_LIMIT)); + run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), gas_limit())); assert!(!result.result.is_success()); - assert_eq!(usage, LimitUsage::ZERO); + assert_eq!(usage, with_extra(body_only(), 1)); +} + +/* ---------- the fee accounts and the sender ---------- */ + +/// The block beneficiary of the fee-account rows: an account of its own, not the zero address. +const COINBASE: Address = address!("00000000000000000000000000000000000C0B00"); + +/// How execution reaches an account in the rows of +/// [`test_execution_writes_to_the_fee_accounts_are_records`]. +#[derive(Clone, Copy, Debug)] +enum FeeRowPath { + /// `CALLEE` sends it one wei with a `CALL`. + ValueTransfer, + /// `CALLEE` destructs itself naming it as beneficiary, which moves `CALLEE`'s balance to it. + SelfDestruct, +} + +/// A write execution makes to one of the four accounts a transaction's fees are credited to is a +/// record like a write to any other account: the body's five fixed records bound the fee credits +/// the settlement makes, not what the transaction's frames write. The sender's account is the +/// converse: the body counts it, so nothing execution writes to it is recorded again, and that +/// holds for a fee account that is the sender too. +/// +/// Every row runs from a contract frame, `CALLEE`, which the transaction calls without value and +/// which holds ten million wei. A value transfer records its sender, `CALLEE`, and its recipient; +/// a `SELFDESTRUCT` of an account the transaction did not create records its beneficiary alone. +/// Each row moves value to another account, so each keeps one EIP-7708 transfer log, which is +/// data size and neither a record nor history. The fee accounts exist before the transaction, so +/// no row adds state; the transaction pays a fee at a gas price of ten over a base fee of one, so +/// the settlement credits the beneficiary and the base fee vault on top of what execution wrote. +/// +/// A record weighs `WRITE_RECORD_SIZE` bytes of data size and history and is one KV update; the +/// history is its bytes at the cost per history byte, on top of the body's `TX_BODY_SIZE`. +/// +/// Rules: [S10.17], [S10.19], [S10.22], [S10.28], [S10.29], [S7], [S10]. Independence: constants — +/// the record counts are written out per row, and the data size, KV count and history are hand +/// arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE`, `TRANSFER_LOG_SIZE` and the cost per +/// history byte in effect. +#[test] +fn test_execution_writes_to_the_fee_accounts_are_records() { + use op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}; + use FeeRowPath::{SelfDestruct, ValueTransfer}; + + // (row, the transaction's sender, the account execution writes, the path, the records kept) + let rows: [(&str, Address, Address, FeeRowPath, u64); 12] = [ + ("the block beneficiary, by a value transfer", CALLER, COINBASE, ValueTransfer, 2), + ("the block beneficiary, by a SELFDESTRUCT", CALLER, COINBASE, SelfDestruct, 1), + ("the L1 fee vault, by a value transfer", CALLER, L1_FEE_RECIPIENT, ValueTransfer, 2), + ("the L1 fee vault, by a SELFDESTRUCT", CALLER, L1_FEE_RECIPIENT, SelfDestruct, 1), + ("the base fee vault, by a value transfer", CALLER, BASE_FEE_RECIPIENT, ValueTransfer, 2), + ("the base fee vault, by a SELFDESTRUCT", CALLER, BASE_FEE_RECIPIENT, SelfDestruct, 1), + ( + "the operator fee vault, by a value transfer", + CALLER, + OPERATOR_FEE_RECIPIENT, + ValueTransfer, + 2, + ), + ( + "the operator fee vault, by a SELFDESTRUCT", + CALLER, + OPERATOR_FEE_RECIPIENT, + SelfDestruct, + 1, + ), + ("the sender, by a value transfer", CALLER, CALLER, ValueTransfer, 1), + ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 0), + ( + "the block beneficiary that is the sender, by a value transfer", + COINBASE, + COINBASE, + ValueTransfer, + 1, + ), + ( + "the block beneficiary that is the sender, by a SELFDESTRUCT", + COINBASE, + COINBASE, + SelfDestruct, + 0, + ), + ]; + for (row, sender, target, path, records) in rows { + let code = match path { + ValueTransfer => append_value_call(BytecodeBuilder::default(), target, 1) + .append(POP) + .append(STOP) + .build(), + SelfDestruct => { + BytecodeBuilder::default().push_address(target).append(SELFDESTRUCT).build() + } + }; + let mut db = funded().account_code(CALLEE, code).account_balance(sender, U256::MAX >> 2); + for account in [COINBASE, L1_FEE_RECIPIENT, BASE_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT] { + if account != sender { + db = db.account_balance(account, U256::from(1)); + } + } + let mut tx = call(sender, CALLEE, U256::ZERO, gas_limit()); + tx.0.base.gas_price = 10; + let block = + revm::context::BlockEnv { beneficiary: COINBASE, basefee: 1, ..crate::common::block() }; + let outcome = MegaEvm::new(context(db).with_block(block)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + assert_eq!(transfer_logs(&outcome.result), 1, "{row}: the transfer log"); + // The settlement credited the fees on top of what execution moved: the priority fee of + // nine a gas to the beneficiary, the base fee of one a gas to the base fee vault. + for (credited, per_gas) in [(COINBASE, 9u64), (BASE_FEE_RECIPIENT, 1)] { + if credited == sender { + continue; + } + let moved = match path { + _ if credited != target => 0, + ValueTransfer => 1, + SelfDestruct => 10_000_000, + }; + assert_eq!( + outcome.state[&credited].info.balance, + U256::from(1 + moved + outcome.gas.gas_used * per_gas), + "{row}: the fee credited to {credited}" + ); + } + + let history_bytes = TX_BODY_SIZE + records * WRITE_RECORD_SIZE; + assert_eq!(outcome.usage.write_records, records, "{row}: the records, the KV count"); + assert_eq!( + outcome.usage.data_size, + history_bytes + TRANSFER_LOG_SIZE, + "{row}: the data size: the body, the records and the transfer log" + ); + assert_eq!(outcome.gas.history_bytes, history_bytes, "{row}: the history bytes"); + if !crate::common::history_rounds() { + assert_eq!( + outcome.gas.history, + history(history_bytes), + "{row}: the history gas: the body and the records at the cost per history byte" + ); + } + } } /* ---------- the commit happens after the opcode ---------- */ @@ -408,7 +582,7 @@ fn after_sstore(steps: &[(u8, bool, LimitUsage)]) -> (bool, LimitUsage) { #[test] fn test_completed_sstore_commits_its_record() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, false); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), false); let (staged, usage) = after_sstore(&steps); assert!(!staged); assert_eq!(usage, records(1)); @@ -429,10 +603,10 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, child); - let steps = probe(db, GAS_LIMIT, false); + let steps = probe(db, gas_limit(), false); let (staged, usage) = after_sstore(&steps); assert!(!staged, "the record is discarded, not left for the next opcode"); - assert_eq!(usage, LimitUsage::ZERO, "a failed opcode's write is not counted"); + assert_eq!(usage, body_only(), "a failed opcode's write is not counted"); } /// A record staged outside an opcode's wrapper is discarded when the next wrapper starts, so it @@ -440,7 +614,7 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { #[test] fn test_wrapper_discards_a_stale_record_on_entry() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), GAS_LIMIT, true); + let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), true); let (staged, usage) = after_sstore(&steps); assert!(!staged); assert_eq!(usage, records(1), "the SSTORE's record, and not the stale log's bytes"); @@ -459,32 +633,14 @@ fn authorizing_call( value: u64, authorizations: &[(Address, u64)], ) -> mega_evm::MegaTransaction { - use revm::{ - context::{transaction::TransactionType, TxEnv}, - context_interface::{ - either::Either, - transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, - }, - }; - let authorization_list = authorizations - .iter() - .map(|(authority, nonce)| { - Either::Right(RecoveredAuthorization::new_unchecked( - Authorization { chain_id: U256::ZERO, address: DELEGATE, nonce: *nonce }, - RecoveredAuthority::Valid(*authority), - )) - }) - .collect(); - alloy_op_evm::OpTx(mega_evm::test_utils::op_transaction(TxEnv { - tx_type: TransactionType::Eip7702 as u8, - caller: CALLER, - kind: alloy_primitives::TxKind::Call(to), - value: U256::from(value), - gas_limit: GAS_LIMIT, - gas_priority_fee: Some(0), - authorization_list, - ..Default::default() - })) + crate::common::authorizing_call( + CALLER, + to, + U256::from(value), + gas_limit(), + DELEGATE, + authorizations, + ) } /// Each distinct applied authority is one record, however many of its authorizations applied; @@ -497,25 +653,55 @@ fn test_applied_authorities_record_once_each() { authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0), (AUTHORITY_2, 0), (AUTHORITY_1, 1)]), ); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(usage, records(2)); + // Three authorization tuples travel in the body; two distinct authorities are applied. + assert_eq!(usage, with_extra(records(2), 3 * mega_evm::AUTHORIZATION_SIZE)); let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 7)])); assert!(result.result.is_success()); - assert_eq!(usage, LimitUsage::ZERO, "a wrong nonce applies nothing"); - - let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(CALLER, 1)])); - assert!(result.result.is_success()); - assert_eq!(usage, LimitUsage::ZERO, "the sender's own account is part of the body"); + assert_eq!( + usage, + with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), + "a wrong nonce applies nothing, and its tuple is still in the body" + ); } /// A value transfer to an applied authority records the authority once, not again as the /// recipient. #[test] fn test_value_to_an_applied_authority_records_it_once() { - let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let (result, usage) = run(db, authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let (result, usage) = run(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(usage, records(1)); + assert_eq!( + usage, + with_extra(records(1), mega_evm::AUTHORIZATION_SIZE + TRANSFER_LOG_SIZE), + "the authority, its authorization and the transfer log" + ); + + // And is charged for once: the transaction's own frame writes no recipient, because the + // authority's account is already written. A transfer to an account that is not an authority + // pays for the recipient on top of the one authority it applied. + if crate::common::runs_at_measurement_prices() { + return; + } + const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; + let to_authority = + crate::common::execute(db(), authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)])); + let to_another = + crate::common::execute(db(), authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)])); + let body = mega_evm::TX_BODY_SIZE + mega_evm::AUTHORIZATION_SIZE; + + assert!(to_another.result.is_success(), "{:?}", to_another.result); + assert_eq!( + to_authority.gas.history, + (body + WRITE_RECORD_SIZE) * CPHB, + "the authority's record, and no recipient record beside it", + ); + assert_eq!( + to_another.gas.history, + (body + 2 * WRITE_RECORD_SIZE) * CPHB, + "the authority's record and the recipient's", + ); } /// A frame running as the transaction's sender (a delegated sender called back) records no @@ -540,10 +726,14 @@ fn test_frames_running_as_the_sender_do_not_record_it() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); - assert_eq!(usage, records(1), "CONTRACT2 only; the sender is part of the body"); + assert_eq!( + usage, + with_extra(records(1), TRANSFER_LOG_SIZE), + "CONTRACT2 and the transfer log only; the sender is part of the body" + ); } /// Raises the endowment of every creation past what the creator holds. @@ -568,11 +758,11 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, code))) .with_inspector(OverfundCreations); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) .unwrap(); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); - assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO); + assert_eq!(evm.ctx().additional_limit().usage(), body_only()); } /// A creation that collides with an existing account fails after bumping the creator's nonce, so @@ -581,7 +771,7 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { fn test_colliding_creation_keeps_the_creator_record() { let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_nonce(CALLEE.create(0), 1); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); assert_eq!(usage, records(1), "the creator's nonce only"); @@ -605,7 +795,7 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) .unwrap(); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the stopped creation bumped the nonce"); @@ -613,65 +803,96 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { assert_eq!(evm.ctx().additional_limit().usage(), records(2), "slot 1 and the creator's nonce"); } -/// Authorities whose records would cross the transaction's data-size limit are not applied: the -/// limit is enforced before the writes it guards, and the transaction is stopped before its first -/// frame. +/// A transaction is held at validation to its body and a record for every entry of its +/// authorization list, against the data-size limit: the largest transaction that fits runs with +/// its authority applied, and with one byte of limit less it is rejected before anything is +/// applied. The bound counts every entry, applied or not: a list naming one authority twice is held +/// to two records, though the one authority makes one. #[test] -fn test_authorities_crossing_the_cap_are_not_applied() { +fn test_authority_records_are_held_to_the_limit_at_validation() { let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); - let with_cap = |cap| { + let with_cap = |cap, authorizations: &[(Address, u64)]| { let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(cap); MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) - .execute_transaction(authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0)])) - .unwrap() + .execute_transaction(authorizing_call(CONTRACT, 0, authorizations)) }; - let at_the_cap = with_cap(40); - assert!(at_the_cap.result.is_success(), "records equal to the cap do not cross it"); - assert_eq!(at_the_cap.usage, records(1)); - - let outcome = with_cap(39); - assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); - assert!(outcome.limit_exceeded.is_some()); - let authority = outcome.state.get(&AUTHORITY_1); - assert!( - authority.is_none_or(|a| a.info.nonce == 0 && a.info.is_empty_code_hash()), - "the delegation was not applied: {authority:?}" - ); - assert_eq!(outcome.usage, LimitUsage::ZERO); + let refused = |cap, authorizations: &[(Address, u64)]| { + let error = with_cap(cap, authorizations).expect_err("rejected at validation"); + format!("{error:?}").contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT) + }; + // The body carries the authorization tuple; the applied authority is one record on top. + let tuple = mega_evm::AUTHORIZATION_SIZE; + let once = [(AUTHORITY_1, 0)]; + let largest = TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE; + let at_the_cap = with_cap(largest, &once).expect("a transaction at the limit is valid"); + assert!(at_the_cap.result.is_success(), "{:?}", at_the_cap.result); + assert_eq!(at_the_cap.usage, with_extra(records(1), tuple)); + let code = at_the_cap.state[&AUTHORITY_1].info.code.as_ref(); + assert_eq!(code.and_then(|code| code.eip7702_address()), Some(DELEGATE), "it is applied"); + assert!(refused(largest - 1, &once), "one byte of limit less rejects it"); + + let twice = [(AUTHORITY_1, 0), (AUTHORITY_1, 1)]; + let bound = TX_BODY_SIZE + 2 * tuple + 2 * WRITE_RECORD_SIZE; + assert!(refused(bound - 1, &twice), "two entries are held to two records"); + let ran = with_cap(bound, &twice).expect("valid at two records"); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(ran.usage, with_extra(records(1), 2 * tuple), "the one authority makes one record"); } -/// A transaction that runs out of gas after its authorities were applied, before its first frame, -/// keeps none of their records: the out-of-gas takes the delegations back. -#[test] -fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { - // The call target is an authority the transaction delegates: calling it pays for the - // delegation target's access after the authorities were applied. Find the gas limit one short - // of the whole runtime phase. - let db = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000)); - let tx = |gas_limit| { - let mut tx = authorizing_call(AUTHORITY_1, 0, &[(AUTHORITY_1, 0)]); - tx.0.base.gas_limit = gas_limit; - tx +/// A funded caller's database, for the runtime out-of-gas tests. +fn runtime_oog_db() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000)) +} + +/// A call to an authority the transaction delegates, at `gas_limit`: calling it pays for the +/// delegation target's access after the authorities were applied. +fn runtime_oog_tx(gas_limit: u64) -> mega_evm::MegaTransaction { + let mut tx = authorizing_call(AUTHORITY_1, 0, &[(AUTHORITY_1, 0)]); + tx.0.base.gas_limit = gas_limit; + tx +} + +/// The gas limit one short of [`runtime_oog_tx`]'s whole runtime phase: the transaction is +/// included, its authorities are applied, and it runs out of gas before its first frame. +fn one_short_of_the_runtime_phase() -> u64 { + let run_at = |gas_limit| { + MegaEvm::new(context(runtime_oog_db())).execute_transaction(runtime_oog_tx(gas_limit)) }; - let run_at = - |gas_limit| MegaEvm::new(context(db())).execute_transaction(tx(gas_limit)).unwrap(); + // A limit below the intrinsic charge is a validation rejection rather than a run, which is a + // failure for the search all the same. + let succeeds_at = |gas_limit| run_at(gas_limit).is_ok_and(|o| o.result.is_success()); // Gas is monotone here: every limit above the smallest one that succeeds succeeds too. Search // for that smallest limit rather than walking up to it, which the delegation's state gas puts // several hundred thousand gas away. - let (mut fails, mut succeeds) = (40_000u64, 1_000_000u64); - assert!(!run_at(fails).result.is_success(), "the low bound must fail"); - assert!(run_at(succeeds).result.is_success(), "the high bound must succeed"); + // 1,000,000 of regular gas on top of the authority's account and delegation and a kilobyte of + // history, at the byte prices in effect. + let high = 1_000_000 + 2 * account_state_gas() + history(1_000); + let (mut fails, mut succeeds) = (0u64, high); + assert!(succeeds_at(succeeds), "the high bound must succeed"); while succeeds - fails > 1 { let middle = fails + (succeeds - fails) / 2; - if run_at(middle).result.is_success() { + if succeeds_at(middle) { succeeds = middle; } else { fails = middle; } } - let outcome = run_at(succeeds - 1); + succeeds - 1 +} + +/// A transaction that runs out of gas after its authorities were applied, before its first frame, +/// keeps none of their records: the out-of-gas takes the delegations back. +#[test] +fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { + let outcome = MegaEvm::new(context(runtime_oog_db())) + .execute_transaction(runtime_oog_tx(one_short_of_the_runtime_phase())) + .expect("one gas short of succeeding is still included"); assert!(outcome.result.is_halt(), "{:?}", outcome.result); - assert_eq!(outcome.usage, LimitUsage::ZERO); + assert_eq!( + outcome.usage, + with_extra(body_only(), mega_evm::AUTHORIZATION_SIZE), + "the out-of-gas takes the authority record back and keeps the body" + ); assert_eq!(outcome.limit_exceeded, None); assert!( outcome.state.get(&AUTHORITY_1).is_none_or(|a| a.info.nonce == 0), @@ -679,6 +900,30 @@ fn test_runtime_out_of_gas_after_authorities_keeps_no_record() { ); } +/// The inspected path unwinds a transaction that runs out of gas before its first frame as the +/// plain one does: the delegation is taken back, and the result, the ledgers, the usage and the +/// state are the same. +#[test] +fn test_an_inspected_runtime_out_of_gas_unwinds_as_a_plain_one() { + let gas_limit = one_short_of_the_runtime_phase(); + let plain = MegaEvm::new(context(runtime_oog_db())) + .execute_transaction(runtime_oog_tx(gas_limit)) + .expect("included"); + let inspected = MegaEvm::new(context(runtime_oog_db())) + .with_inspector(revm::inspector::NoOpInspector) + .execute_transaction(runtime_oog_tx(gas_limit)) + .expect("included"); + assert!(inspected.result.is_halt(), "{:?}", inspected.result); + assert!( + inspected.state.get(&AUTHORITY_1).is_none_or(|a| a.info.nonce == 0), + "the out-of-gas took the delegation back" + ); + assert_eq!(inspected.result, plain.result); + assert_eq!(inspected.gas, plain.gas); + assert_eq!(inspected.usage, plain.usage); + assert_eq!(inspected.state, plain.state); +} + /* ---------- which frame's account counts as recorded ---------- */ const D: Address = address!("00000000000000000000000000000000000000D1"); @@ -694,10 +939,14 @@ fn test_value_receiving_child_records_itself_once() { .append(STOP) .build(); let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - assert_eq!(usage, records(3), "CALLEE, CONTRACT once, CONTRACT2"); + assert_eq!( + usage, + with_extra(records(3), 2 * TRANSFER_LOG_SIZE), + "CALLEE, CONTRACT once, CONTRACT2, and two transfer logs" + ); } /// A child that received nothing starts with its own account unrecorded, whatever its caller's @@ -720,9 +969,13 @@ fn test_zero_value_child_starts_unrecorded() { .account_code(CALLEE, a) .account_code(CONTRACT, b) .account_balance(CONTRACT, U256::from(5)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); assert!(result.result.is_success()); - assert_eq!(usage, records(3), "CALLEE as the recipient, CONTRACT, CONTRACT2"); + assert_eq!( + usage, + with_extra(records(3), 2 * TRANSFER_LOG_SIZE), + "CALLEE as the recipient, CONTRACT, CONTRACT2, and two transfer logs" + ); } /// Calls `D` with `DELEGATECALL`. @@ -745,10 +998,14 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { .append(STOP) .build(); let db = funded().account_code(CALLEE, delegate_to_d()).account_code(D, d); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); - assert_eq!(usage, records(2), "CALLEE as the recipient, CONTRACT2"); + assert_eq!( + usage, + with_extra(records(2), 2 * TRANSFER_LOG_SIZE), + "CALLEE as the recipient, CONTRACT2, and two transfer logs" + ); } /// A created frame's account is recorded by the creation; a `DELEGATECALL` from its init code @@ -761,14 +1018,19 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { .build(); let db = funded().account_code(D, d); let tx = { - let mut tx = create(CALLER, delegate_to_d(), GAS_LIMIT); + let mut tx = create(CALLER, delegate_to_d(), gas_limit()); tx.0.base.value = U256::from(5); tx }; let (result, usage) = run(db, tx); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - assert_eq!(usage, records(2), "the created account, CONTRACT2"); + // The init code travels in the body. `STOP` deploys nothing. + assert_eq!( + usage, + with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), + "the created account, CONTRACT2, and two transfer logs" + ); } /// A transaction calling its own sender (delegated) counts the sender as recorded from the start. @@ -783,10 +1045,10 @@ fn test_top_level_self_call_counts_the_sender_as_recorded() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, GAS_LIMIT)); + let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, gas_limit())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - assert_eq!(usage, records(1), "CONTRACT2 only"); + assert_eq!(usage, with_extra(records(1), TRANSFER_LOG_SIZE), "CONTRACT2 and its log only"); } /// Answers every call to `CONTRACT` itself. @@ -825,8 +1087,432 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, a))).with_inspector(AnswerContract); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) .unwrap(); assert!(result.result.is_success()); - assert_eq!(evm.ctx().additional_limit().usage(), records(2), "CALLEE and CONTRACT2"); + assert_eq!( + evm.ctx().additional_limit().usage(), + with_extra(records(2), TRANSFER_LOG_SIZE), + "CALLEE and CONTRACT2, and the transfer log" + ); +} + +/* ---------- every kept write is paid for, once ---------- */ + +/// One transaction of the corpus below: what it runs, the history bytes it appends beyond its +/// body that are not write records, and the records it keeps. +struct Paired { + name: &'static str, + db: MemoryDatabase, + tx: mega_evm::MegaTransaction, + /// Log and deployed-code bytes. The calldata travels in the body, so it is not counted here. + other_bytes: u64, + /// The write records the transaction keeps, beyond the ones its body already carries. + records: u64, + /// Data-size bytes that are not history: an Oracle hint's payload, which goes to the node's + /// oracle service rather than into a block. Zero for every case but the hint's. + hint_bytes: u64, + /// The EIP-7708 transfer logs the transaction keeps, one per value movement it kept: data + /// size that is not history, and no record. + transfer_logs: u64, + /// The block this case runs in, for a case whose beneficiary is the point of it. + beneficiary: Address, +} + +/// A call to `MegaAccessControl` carrying one wei, which its interceptor refuses before a frame +/// runs, followed by a `STOP`. +fn value_call_a_system_contract_refuses() -> Bytes { + BytecodeBuilder::default() + .mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) + .append_many([PUSH0, PUSH0]) + .push_number(4u64) + .append(PUSH0) + .append(PUSH1) + .append(1u8) + .push_address(ACCESS_CONTROL_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP) + .append(STOP) + .build() +} + +/// Init code that returns `size` zero bytes as the deployed contract. +fn constructor_returning(size: u8) -> Bytes { + BytecodeBuilder::default().push_number(size).push_number(0_u8).append(RETURN).build() +} + +/// Init code that reverts with `len` bytes of data and deploys nothing. +fn reverting_with(len: u8) -> Bytes { + BytecodeBuilder::default().push_number(len).push_number(0_u8).append(REVERT).build() +} + +/// The corpus, one case per rule the record sites follow. +fn paired_corpus() -> Vec { + let case = |name, db: MemoryDatabase, tx, other_bytes, records| Paired { + name, + db, + tx, + other_bytes, + records, + hint_bytes: 0, + transfer_logs: 0, + beneficiary: Address::ZERO, + }; + let to_callee = |code: Bytes| funded().account_code(CALLEE, code); + let plain = || call(CALLER, CALLEE, U256::ZERO, gas_limit()); + let calling = |target, value| { + append_value_call(BytecodeBuilder::default(), target, value) + .append(POP) + .append(STOP) + .build() + }; + let storing = |slots: &[(u64, u64)]| { + let mut code = BytecodeBuilder::default(); + for (slot, value) in slots { + code = code.sstore(U256::from(*slot), U256::from(*value)); + } + code.stop().build() + }; + let reverting = Bytes::from_static(&[PUSH0, PUSH0, 0xFD]); + vec![ + case("an empty call", to_callee(Bytes::new()), plain(), 0, 0), + case("three fresh slots", to_callee(storing(&[(1, 1), (2, 1), (3, 1)])), plain(), 0, 3), + case("a slot written and restored", to_callee(storing(&[(1, 1), (1, 0)])), plain(), 0, 0), + case("zero written to an empty slot", to_callee(storing(&[(1, 0)])), plain(), 0, 0), + case( + "a slot rewritten twice", + to_callee(storing(&[(1, 1), (1, 2), (1, 3)])), + plain(), + 0, + 1, + ), + Paired { + transfer_logs: 1, + ..case("a value transfer", to_callee(calling(CONTRACT, 1)), plain(), 0, 2) + }, + case( + "a value transfer the callee reverts", + to_callee(calling(CONTRACT, 1)).account_code(CONTRACT, reverting.clone()), + plain(), + 0, + 0, + ), + // Its sender is its recipient: one account, one record, and no transfer log. + case( + "a value call to the calling account itself", + to_callee(self_calling_code(&[CALLEE], 1)), + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), gas_limit()), + 0, + 1, + ), + case( + "a log over one word", + to_callee( + BytecodeBuilder::default() + .push_number(1u64) + .push_number(1u64) + .push_number(32u64) + .push_number(0u64) + .append(LOG2) + .append(STOP) + .build(), + ), + plain(), + 32 + 2 * 32 + 32, + 0, + ), + Paired { + transfer_logs: 1, + ..case( + "a nested creation", + to_callee( + append_value_create(BytecodeBuilder::default()) + .append(POP) + .append(STOP) + .build(), + ), + plain(), + 0, + 2, + ) + }, + case( + "a creation whose init code reverts", + funded().account_code(OUTER_CREATOR, reverting_creations(1)), + call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit()), + 0, + 1, + ), + Paired { + transfer_logs: 1, + ..case( + "a destruction that moves value", + to_callee( + BytecodeBuilder::default().push_address(CONTRACT).append(SELFDESTRUCT).build(), + ) + .account_balance(CALLEE, U256::from(1)), + plain(), + 0, + 1, + ) + }, + case( + "a value call a system contract's interceptor refuses", + to_callee(value_call_a_system_contract_refuses()) + .account_balance(ACCESS_CONTROL_ADDRESS, U256::from(1)) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE), + plain(), + 0, + 0, + ), + case( + "a transaction carrying calldata", + to_callee(Bytes::new()), + call_with_data(CALLER, CALLEE, Bytes::from(vec![7u8; 100]), gas_limit()), + 0, + 0, + ), + Paired { + transfer_logs: 1, + ..case( + "a value transaction", + funded(), + call(CALLER, CONTRACT, U256::from(1), gas_limit()), + 0, + 1, + ) + }, + case( + "a value transaction the recipient reverts", + funded().account_code(CONTRACT, reverting), + call(CALLER, CONTRACT, U256::from(1), gas_limit()), + 0, + 0, + ), + case("a creation transaction", funded(), create(CALLER, Bytes::new(), gas_limit()), 0, 1), + case( + "a creation that deploys code", + funded(), + create(CALLER, constructor_returning(32), gas_limit()), + 32, + 1, + ), + case( + "a creation whose revert data is not deployed code", + funded(), + create(CALLER, reverting_with(10), gas_limit()), + 0, + 0, + ), + // Two of the three places where a transaction's data size and its history part company; + // the third is every transfer log a case above keeps. All three are decisions, stated in + // the byte table; each is written out here with the number it pays. + Paired { + hint_bytes: send_hint(b"a hint the transaction pays data size for").len() as u64, + ..case( + "a transaction that sends an Oracle hint", + funded().account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE), + call_with_data( + CALLER, + ORACLE_CONTRACT_ADDRESS, + send_hint(b"a hint the transaction pays data size for"), + gas_limit(), + ), + 0, + 0, + ) + }, + Paired { + beneficiary: CONTRACT, + transfer_logs: 1, + ..case( + "a value transaction whose recipient is the block beneficiary", + MemoryDatabase::default().account_balance(CALLER, U256::from(10u64.pow(18))), + { + // A fee the beneficiary is actually credited, so the account the transfer + // records is one the body's five already bound. + let mut tx = call(CALLER, CONTRACT, U256::from(1), gas_limit()); + tx.0.base.gas_price = 10; + tx + }, + 0, + 1, + ) + }, + ] +} + +/// The EIP-7708 transfer logs `result` carries. +fn transfer_logs(result: &revm::context::result::ExecutionResult) -> u64 { + result.logs().iter().filter(|log| is_transfer_log(log)).count() as u64 +} + +/// The calldata of `sendHint(topic, data)`, whose payload the Oracle's interceptor counts on the +/// transaction's data size before the contract's own bytecode runs. +fn send_hint(data: &[u8]) -> Bytes { + Bytes::from( + IOracle::sendHintCall { + topic: B256::repeat_byte(0x7a), + data: Bytes::copy_from_slice(data), + } + .abi_encode(), + ) +} + +/// Every write a transaction keeps is one forty-byte record of history, and nothing it does not +/// keep is: the history each transaction pays beyond its body, its logs and its deployed code is +/// exactly the write-record count the layer counted, at the history price. +/// +/// This is the pairing itself. The layer counts the records and the engine charges for them at +/// separate sites, on separate rules; the corpus holds the two to the same number, case by case, +/// and to the number the case says. +/// +/// The pairing is per record, and three things part a transaction's two totals: an Oracle hint's +/// payload is data size that is not history, a transfer to the block beneficiary pays a record the +/// transaction body's five already bound, and an EIP-7708 transfer log — which every case that +/// moves value keeps, and its receipt carries — is data size that is neither history nor a record. +/// All three are the byte table's decisions; each is written out with the number it costs so the +/// divergence reads as intended rather than as a defect. +#[test] +fn test_every_kept_write_pays_one_record_of_history() { + if crate::common::runs_at_measurement_prices() { + return; + } + const CPHB: u64 = mega_evm::constants::COST_PER_HISTORY_BYTE; + for case in paired_corpus() { + let ctx = context(case.db).with_block(revm::context::BlockEnv { + beneficiary: case.beneficiary, + ..crate::common::block() + }); + let outcome = MegaEvm::new(ctx) + .execute_transaction(case.tx.clone()) + .expect("the transaction is valid"); + let usage = outcome.usage; + assert_eq!(usage.write_records, case.records, "{}: the records kept", case.name); + assert_eq!( + transfer_logs(&outcome.result), + case.transfer_logs, + "{}: the transfer logs the receipt carries", + case.name + ); + let body = mega_evm::transaction_body_bytes(&case.tx); + let history_bytes = body + case.other_bytes + case.records * WRITE_RECORD_SIZE; + assert_eq!(outcome.gas.history, history_bytes * CPHB, "{}: the history it pays", case.name); + assert_eq!(outcome.gas.history_bytes, history_bytes, "{}: the history bytes", case.name); + assert_eq!( + usage.data_size, + history_bytes + case.hint_bytes + case.transfer_logs * TRANSFER_LOG_SIZE, + "{}: the data size the limit counts", + case.name, + ); + } +} + +/// A value call an inspector answers makes none of the writes its caller paid for, so all of that +/// history comes back — whatever the inspector answered with. +/// +/// A frame answered without running is the one case where a *successful* result must still give +/// the caller its charge back: the records were never made. An interceptor's refusal and the +/// depth guard both fail, so only an inspector reaches this. +#[test] +fn test_an_inspector_answered_value_call_gives_its_history_back() { + if crate::common::runs_at_measurement_prices() { + return; + } + let code = + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); + let run_with = |inspector: Option| { + let db = funded().account_code(CALLEE, code.clone()); + let tx = call(CALLER, CALLEE, U256::ZERO, gas_limit()); + match inspector { + Some(inspector) => { + let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); + let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); + assert!(result.result.is_success(), "{:?}", result.result); + ( + evm.ctx().additional_limit().usage(), + evm.ctx().additional_limit().history_gas_spent(), + ) + } + None => { + let outcome = crate::common::execute(db, tx); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + (outcome.usage, outcome.gas.history) + } + } + }; + let (answered_usage, answered_history) = run_with(Some(AnswerContract)); + let (ran_usage, ran_history) = run_with(None); + let body = mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE; + + assert_eq!(answered_usage, body_only(), "the answered call wrote nothing"); + assert_eq!(answered_history, body, "so its caller pays for nothing beyond its body"); + assert_eq!( + ran_usage, + with_extra(records(2), TRANSFER_LOG_SIZE), + "the transfer that ran wrote two accounts and left its log" + ); + assert_eq!( + ran_history, + body + 2 * WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE + ); +} + +/* ---------- the KV count and the data size ---------- */ + +/// Watches the usage the layer counts after every instruction, and keeps the first one whose +/// write records weigh more than its data size. +#[derive(Default)] +struct KvWeighsNoMore { + steps: usize, + over: Option, +} + +impl Inspector, EthInterpreter> for KvWeighsNoMore { + fn step_end(&mut self, _: &mut Interpreter, context: &mut MegaContext) { + self.steps += 1; + let usage = context.additional_limit().usage(); + if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { + self.over.get_or_insert(usage); + } + } +} + +/// The KV count a node reads is the write-record count, and it never weighs more than the data +/// size: every record is forty bytes of it, counted with it and taken back with it. Across the +/// corpus — slots written back, a slot rewritten, accounts recorded once per frame, failed +/// children, a hint — `KV × 40 ≤ data size` holds after every instruction a transaction runs, and +/// what it keeps parts from the records by exactly the bytes that are not records: the body, the +/// logs — the transfer logs among them — the deployed code and the hint's payload. +/// +/// So the data-size limit bounds the records: at the production data-size caps a transaction keeps +/// at most 327,680 of them. +#[test] +fn test_the_kv_count_never_weighs_more_than_the_data_size() { + assert_eq!(mega_evm::constants::TX_DATA_LIMIT / WRITE_RECORD_SIZE, 327_680); + let mut ran = 0; + for case in paired_corpus() { + let ctx = context(case.db).with_block(revm::context::BlockEnv { + beneficiary: case.beneficiary, + ..crate::common::block() + }); + let mut evm = MegaEvm::new(ctx).with_inspector(KvWeighsNoMore::default()); + let outcome = evm.execute_transaction(case.tx.clone()).expect("the transaction is valid"); + let usage = outcome.usage; + assert_eq!(usage.write_records, case.records, "{}: the KV count", case.name); + assert_eq!( + usage.data_size - usage.write_records * WRITE_RECORD_SIZE, + mega_evm::transaction_body_bytes(&case.tx) + + case.other_bytes + + case.hint_bytes + + case.transfer_logs * TRANSFER_LOG_SIZE, + "{}: what is kept beside the records", + case.name, + ); + let probe = evm.inspector(); + assert_eq!(probe.over, None, "{}: after every instruction", case.name); + ran += probe.steps; + } + assert!(ran > 100, "the corpus runs code: {ran} instructions"); } diff --git a/crates/mega-evm/tests/shared/snapshot.rs b/crates/mega-evm/tests/shared/snapshot.rs new file mode 100644 index 000000000..9e67d1e78 --- /dev/null +++ b/crates/mega-evm/tests/shared/snapshot.rs @@ -0,0 +1,50 @@ +//! The snapshot assertion the integration test targets share. +//! +//! A target includes this file once, from its `main.rs`: +//! +//! ```ignore +//! #[path = "../shared/snapshot.rs"] +//! mod snapshot; +//! ``` +//! +//! and asserts with `crate::assert_sorted_json_snapshot!(value)`. The directory holds no +//! `main.rs`, so Cargo builds no target of its own from it. +//! +//! A snapshot pins only an output no test can compute an expectation for, such as a tracer's +//! format or the digest of a recorded trace. A figure the schedule and the named constants +//! determine is asserted against its derivation, never pinned, and no snapshot is a net over a +//! behaviour test. +//! +//! The snapshot files live in `snapshots/` next to the file that asserts. A mismatch fails the +//! test; outside CI insta also writes the new value beside the old one as a `.snap.new` file, +//! which `cargo insta review` shows and accepts or rejects one by one. + +/// Asserts a JSON snapshot of `value` with every map's keys sorted, so the snapshot does not +/// depend on a hasher's order. An optional first argument names the snapshot; without it insta +/// names it after the test. +/// +/// The snapshots are pinned at the spec's byte prices. At other prices, which only a +/// measurement build fixes (the `satin-price-override` feature), the comparison is skipped and +/// the test leaves a note of the skip (`note_snapshot_skipped`), which the byte-price grid counts +/// apart from the price guards; the rest of the test runs as it does at the spec's prices. +#[macro_export] +macro_rules! assert_sorted_json_snapshot { + ($value:expr $(,)?) => { + if ::mega_evm::active_satin_prices().is_constants() { + ::insta::with_settings!({ sort_maps => true }, { + ::insta::assert_json_snapshot!($value); + }) + } else { + ::mega_evm::test_utils::note_snapshot_skipped(); + } + }; + ($name:expr, $value:expr $(,)?) => { + if ::mega_evm::active_satin_prices().is_constants() { + ::insta::with_settings!({ sort_maps => true }, { + ::insta::assert_json_snapshot!($name, $value); + }) + } else { + ::mega_evm::test_utils::note_snapshot_skipped(); + } + }; +} diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs new file mode 100644 index 000000000..e1eec4ce0 --- /dev/null +++ b/crates/mega-evm/tests/system/access_control.rs @@ -0,0 +1,691 @@ +//! `MegaAccessControl` steering gas detention's switch: a frame that calls +//! `disableVolatileDataAccess()` has every volatile read of its own and of the frames below it +//! refused with `VolatileDataAccessDisabled`, until it switches access back on or returns; a frame +//! below cannot switch back on what a frame above switched off; `isVolatileDataAccessDisabled()` +//! answers for the caller. +//! +//! The legacy engine's rows, on Satin's switch. The beneficiary is the block's, `Address::ZERO` in +//! these tests. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + system::{ + IMegaAccessControl, VolatileDataAccessType, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + volatile_data_access_disabled_revert_data, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, + MegaTransaction, TestExternalEnvs, VolatileDataAccess, +}; +use revm::bytecode::opcode::*; + +use crate::common::{block, call_tx_with_gas, steer, system_db, Run, GAS_LIMIT}; + +const PARENT: Address = address!("0x0000000000000000000000000000000000200001"); +const CHILD: Address = address!("0x0000000000000000000000000000000000200002"); +const GRANDCHILD: Address = address!("0x0000000000000000000000000000000000200003"); +const SIBLING: Address = address!("0x0000000000000000000000000000000000200004"); + +/// The block's beneficiary in these tests. +const BENEFICIARY: Address = Address::ZERO; + +const DISABLE: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; +const ENABLE: [u8; 4] = IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; +const IS_DISABLED: [u8; 4] = IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR; +const DISABLED_BY_PARENT: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECTOR; + +/* ---------- running a transaction ---------- */ + +/// Runs `tx` over `db`, with an oracle service that holds slot 0 of the Oracle. +fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { + let envs = TestExternalEnvs::::new() + .with_oracle_storage(U256::ZERO, U256::from(0x1234)); + let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, ExternalEnvs::from(envs)) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let detention = evm.ctx().detention(); + Run { outcome, accessed: detention.accessed(), limit: detention.compute_limit() } +} + +/// Runs a call to [`PARENT`] with the contracts `code` holds deployed. +fn run(code: &[(Address, Bytes)]) -> Run { + let db = code + .iter() + .fold(system_db(), |db, (address, code)| db.account_code(*address, code.clone())); + execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)) +} + +/* ---------- code ---------- */ + +fn disable(code: BytecodeBuilder) -> BytecodeBuilder { + steer(code, DISABLE) +} + +fn enable(code: BytecodeBuilder) -> BytecodeBuilder { + steer(code, ENABLE) +} + +/// Appends a call of `target` through `scheme` with `gas`, leaving its status on the stack. +fn call(code: BytecodeBuilder, scheme: u8, target: Address, gas: u64) -> BytecodeBuilder { + let code = code.push_number(0_u8).push_number(0_u8).push_number(0_u8).push_number(0_u8); + let code = if scheme == CALL || scheme == CALLCODE { code.push_number(0_u8) } else { code }; + code.push_address(target).push_number(gas).append(scheme) +} + +/// Appends a `LOG0` of the status on the stack. +fn log_status(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, MSTORE]).push_number(32_u8).append_many([PUSH0, LOG0]) +} + +/// Appends a return of the word on the stack. +fn return_word(code: BytecodeBuilder) -> Bytes { + code.append_many([PUSH0, MSTORE]).push_number(32_u8).append_many([PUSH0, RETURN]).build() +} + +/// Appends a call of `target`, then returns what it returned or reverted with. +fn call_and_return_data(code: BytecodeBuilder, target: Address) -> Bytes { + call(code, CALL, target, 50_000_000) + .append(POP) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, RETURNDATASIZE, PUSH0, RETURN]) + .build() +} + +/// Code that runs `opcode` once and stops; `BLOCKHASH` and `BLOBHASH` are given an operand. +fn reads(opcode: u8) -> Bytes { + let code = BytecodeBuilder::default(); + let code = if matches!(opcode, BLOCKHASH | BLOBHASH) { code.append(PUSH0) } else { code }; + code.append_many([opcode, POP, STOP]).build() +} + +/// Code that runs `opcode` on the account at `target` and stops. +fn reads_account(opcode: u8, target: Address) -> Bytes { + BytecodeBuilder::default().push_address(target).append_many([opcode, POP, STOP]).build() +} + +/// The access type a `VolatileDataAccessDisabled` revert names. +fn refused_type(data: &[u8]) -> VolatileDataAccessType { + IMegaAccessControl::VolatileDataAccessDisabled::abi_decode(data) + .expect("a VolatileDataAccessDisabled revert") + .accessType +} + +/// The parent that switches access off, calls [`CHILD`] and logs its status. +fn disables_then_calls_child(scheme: u8) -> Bytes { + log_status(call(disable(BytecodeBuilder::default()), scheme, CHILD, 50_000_000)).stop().build() +} + +/* ---------- 1. disableVolatileDataAccess() ---------- */ + +/// A child that reads `TIMESTAMP` after its caller switched access off reverts. +#[test] +fn test_inner_call_timestamp_reverts() { + let run = run(&[(PARENT, disables_then_calls_child(CALL)), (CHILD, reads(TIMESTAMP))]); + assert!(run.outcome.result.is_success()); + assert!(!run.logged_status(0), "the child's read was refused"); +} + +/// The frame that switched access off is restricted itself. +#[test] +fn test_caller_frame_is_restricted() { + let parent = disable(BytecodeBuilder::default()).append_many([TIMESTAMP, POP, STOP]).build(); + let run = run(&[(PARENT, parent)]); + assert!(!run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!( + run.outcome.result.output().cloned().unwrap_or_default(), + volatile_data_access_disabled_revert_data(VolatileDataAccess::TIMESTAMP), + ); +} + +/// A child that reads nothing volatile is not restricted. +#[test] +fn test_inner_call_without_volatile_access_succeeds() { + let child = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(2_u8) + .append_many([ADD, POP, STOP]) + .build(); + let run = run(&[(PARENT, disables_then_calls_child(CALL)), (CHILD, child)]); + assert!(run.logged_status(0)); +} + +/* ---------- 2. which opcodes are refused ---------- */ + +/// Every block-environment opcode is refused in a child, `SLOTNUM` included; `BLOBHASH` is not, +/// because it reads the transaction's own blob hashes, which Satin does not count as volatile. +#[test] +fn test_volatile_opcodes_all_revert_in_inner_call() { + for (opcode, refused) in [ + (TIMESTAMP, true), + (NUMBER, true), + (COINBASE, true), + (DIFFICULTY, true), + (GASLIMIT, true), + (BASEFEE, true), + (BLOCKHASH, true), + (BLOBBASEFEE, true), + (SLOTNUM, true), + (BLOBHASH, false), + ] { + let run = run(&[(PARENT, disables_then_calls_child(CALL)), (CHILD, reads(opcode))]); + assert!(run.outcome.result.is_success(), "{opcode:#04x}"); + assert_eq!(!run.logged_status(0), refused, "{opcode:#04x}"); + } +} + +/// The refusal reverts with `VolatileDataAccessDisabled(uint8)` naming what the opcode reads. +#[test] +fn test_revert_data_contains_error_with_access_type() { + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, reads(TIMESTAMP))]); + let output = run.output(); + assert_eq!(output[..4], IMegaAccessControl::VolatileDataAccessDisabled::SELECTOR); + assert_eq!(refused_type(&output), VolatileDataAccessType::Timestamp); +} + +/// A refused `SLOTNUM` names access type 12, which the contract's enum does not declare: the +/// engine's decoder names it, and the enum-typed binding cannot. +#[test] +fn test_a_slotnum_refusal_names_access_type_12() { + use mega_evm::{decode_volatile_data_access_disabled, system::SLOT_NUM_ACCESS_TYPE}; + + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, reads(SLOTNUM))]); + let output = run.output(); + assert_eq!(output.len(), 36); + assert_eq!(output[35], SLOT_NUM_ACCESS_TYPE); + assert_eq!(decode_volatile_data_access_disabled(&output), Some(VolatileDataAccess::SLOT_NUM)); + assert_eq!(refused_type(&output), VolatileDataAccessType::__Invalid); +} + +/* ---------- 3. nested calls and call schemes ---------- */ + +/// The restriction reaches every frame below the one that switched it off: a grandchild's read is +/// refused, and the child, which read nothing, returns normally. +#[test] +fn test_nested_call_volatile_access_reverts() { + let child = + log_status(call(BytecodeBuilder::default(), CALL, GRANDCHILD, 40_000_000)).stop().build(); + let run = run(&[ + (PARENT, disables_then_calls_child(CALL)), + (CHILD, child), + (GRANDCHILD, reads(TIMESTAMP)), + ]); + assert!(run.outcome.result.is_success()); + assert!(!run.logged_status(0), "the grandchild was refused"); + assert!(run.logged_status(1), "the child returned"); +} + +/// A child reached with `STATICCALL` or `DELEGATECALL` is restricted too: the switch is by frame, +/// not by scheme. +#[test] +fn test_staticcall_also_restricted() { + let run = run(&[(PARENT, disables_then_calls_child(STATICCALL)), (CHILD, reads(TIMESTAMP))]); + assert!(!run.logged_status(0)); +} + +/// See [`test_staticcall_also_restricted`]. +#[test] +fn test_delegatecall_also_restricted() { + let run = run(&[(PARENT, disables_then_calls_child(DELEGATECALL)), (CHILD, reads(TIMESTAMP))]); + assert!(!run.logged_status(0)); +} + +/* ---------- 4. the beneficiary's account ---------- */ + +/// An account opcode is refused on the beneficiary only: `BALANCE` and `EXTCODESIZE` of another +/// account are not volatile reads. +#[test] +fn test_balance_non_beneficiary_not_restricted() { + let run = + run(&[(PARENT, disables_then_calls_child(CALL)), (CHILD, reads_account(BALANCE, CHILD))]); + assert!(run.logged_status(0)); +} + +/// See [`test_balance_non_beneficiary_not_restricted`]. +#[test] +fn test_extcodesize_non_beneficiary_not_restricted() { + let run = run(&[ + (PARENT, disables_then_calls_child(CALL)), + (CHILD, reads_account(EXTCODESIZE, CHILD)), + ]); + assert!(run.logged_status(0)); +} + +/// `BALANCE` of the beneficiary is refused, naming the beneficiary. +#[test] +fn test_balance_beneficiary_restricted() { + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, reads_account(BALANCE, BENEFICIARY))]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Beneficiary); +} + +/// A call of the beneficiary is refused through each of the four schemes, naming the beneficiary. +#[test] +fn test_call_beneficiary_restricted() { + for scheme in [CALL, STATICCALL, DELEGATECALL, CALLCODE] { + let child = call(BytecodeBuilder::default(), scheme, BENEFICIARY, 100_000).stop().build(); + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, child)]); + assert_eq!( + refused_type(&run.output()), + VolatileDataAccessType::Beneficiary, + "{scheme:#04x}" + ); + } +} + +/// A call of another account is not restricted. +#[test] +fn test_call_non_beneficiary_not_restricted() { + let child = call(BytecodeBuilder::default(), CALL, GRANDCHILD, 100_000).stop().build(); + let run = run(&[ + (PARENT, disables_then_calls_child(CALL)), + (CHILD, child), + (GRANDCHILD, BytecodeBuilder::default().stop().build()), + ]); + assert!(run.logged_status(0)); +} + +/// Without the switch, calling the beneficiary is an ordinary call. +#[test] +fn test_call_beneficiary_not_restricted_without_disable() { + let child = call(BytecodeBuilder::default(), CALL, BENEFICIARY, 100_000).stop().build(); + let parent = + log_status(call(BytecodeBuilder::default(), CALL, CHILD, 50_000_000)).stop().build(); + let run = run(&[(PARENT, parent), (CHILD, child)]); + assert!(run.logged_status(0)); +} + +/// `SELFDESTRUCT` to the beneficiary is refused, naming the beneficiary; to another account it is +/// not, and without the switch neither is. +#[test] +fn test_selfdestruct_beneficiary_restricted() { + let child = reads_account(SELFDESTRUCT, BENEFICIARY); + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, child)]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Beneficiary); +} + +/// See [`test_selfdestruct_beneficiary_restricted`]. +#[test] +fn test_selfdestruct_non_beneficiary_not_restricted() { + let run = run(&[ + (PARENT, disables_then_calls_child(CALL)), + (CHILD, reads_account(SELFDESTRUCT, GRANDCHILD)), + ]); + assert!(run.logged_status(0)); +} + +/// See [`test_selfdestruct_beneficiary_restricted`]. +#[test] +fn test_selfdestruct_beneficiary_not_restricted_without_disable() { + let parent = + log_status(call(BytecodeBuilder::default(), CALL, CHILD, 50_000_000)).stop().build(); + let run = run(&[(PARENT, parent), (CHILD, reads_account(SELFDESTRUCT, BENEFICIARY))]); + assert!(run.logged_status(0)); +} + +/* ---------- 5. a refused read reads nothing ---------- */ + +/// A refused read records nothing and sets no compute limit: the block environment, the +/// beneficiary's balance, a call of the beneficiary, a `SELFDESTRUCT` to it, and the Oracle's +/// storage. +#[test] +fn test_blocked_volatile_access_does_not_set_bitmap() { + let oracle_read = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + for (name, target, child) in [ + ("TIMESTAMP", CHILD, reads(TIMESTAMP)), + ("BALANCE", CHILD, reads_account(BALANCE, BENEFICIARY)), + ( + "CALL", + CHILD, + call(BytecodeBuilder::default(), CALL, BENEFICIARY, 100_000).stop().build(), + ), + ("SELFDESTRUCT", CHILD, reads_account(SELFDESTRUCT, BENEFICIARY)), + ("SLOAD", ORACLE_CONTRACT_ADDRESS, oracle_read), + ] { + let parent = + log_status(call(disable(BytecodeBuilder::default()), CALL, target, 50_000_000)) + .stop() + .build(); + let run = run(&[(PARENT, parent), (target, child)]); + assert!(run.outcome.result.is_success(), "{name}"); + assert!(!run.logged_status(0), "{name}: refused"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{name}"); + assert_eq!(run.limit, None, "{name}"); + } +} + +/// The Oracle's storage is refused in the Oracle's own frame below a frame that switched access +/// off, naming the Oracle. +#[test] +fn test_oracle_sload_reverts_when_volatile_access_disabled() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, POP, STOP]).build(); + let parent = call_and_return_data(disable(BytecodeBuilder::default()), ORACLE_CONTRACT_ADDRESS); + let run = run(&[(PARENT, parent), (ORACLE_CONTRACT_ADDRESS, oracle)]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Oracle); +} + +/// A creation whose init code reads volatile data fails below a frame that switched access off, +/// and it fails on the refusal: the creation reverts with `VolatileDataAccessDisabled` naming the +/// timestamp, which the parent returns. The parent logs the address `CREATE` left, zero for a +/// failed creation. +/// +/// Rule [S13.2]. Expected values `constants`: the revert data is decoded with the contract's own +/// error binding, and the access type is the one the init code reads. +#[test] +fn test_create_reverts_when_volatile_access_disabled() { + let init_code = + BytecodeBuilder::default().append_many([TIMESTAMP, POP, PUSH0, PUSH0, RETURN]).build(); + let parent = log_status( + disable(BytecodeBuilder::default()) + .mstore(0x40, &init_code) + .push_number(init_code.len() as u64) + .push_number(0x40_u8) + .push_number(0_u8) + .append(CREATE), + ) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, RETURNDATASIZE, PUSH0, RETURN]) + .build(); + let run = run(&[(PARENT, parent)]); + assert!(!run.logged_status(0), "the creation failed"); + assert_eq!( + refused_type(&run.output()), + VolatileDataAccessType::Timestamp, + "on the refusal of its read" + ); +} + +/// A parent that read volatile data before switching access off still has its child refused: +/// what the transaction read already does not lift the switch. +#[test] +fn test_parent_accesses_volatile_then_child_restricted() { + let parent = call_and_return_data( + disable(BytecodeBuilder::default().append_many([TIMESTAMP, POP])), + CHILD, + ); + let run = run(&[(PARENT, parent), (CHILD, reads(TIMESTAMP))]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Timestamp); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP, "the parent's own read counts"); +} + +/* ---------- 6. the switch's scope ---------- */ + +/// A sibling called after the frame that switched access off returned is not restricted, and +/// neither is its child. +#[test] +fn test_sibling_call_not_restricted() { + let c1 = disable(BytecodeBuilder::default()).stop().build(); + let c2 = return_word(call(BytecodeBuilder::default(), CALL, GRANDCHILD, 40_000_000)); + let parent = call(BytecodeBuilder::default(), CALL, CHILD, 50_000_000) + .append(POP) + .push_number(32_u8) // retSize + .push_number(0_u8) // retOffset + .push_number(0_u8) // argsSize + .push_number(0_u8) // argsOffset + .push_number(0_u8) // value + .push_address(SIBLING) + .push_number(50_000_000_u32) + .append_many([CALL, POP]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build(); + let run = run(&[(PARENT, parent), (CHILD, c1), (SIBLING, c2), (GRANDCHILD, reads(TIMESTAMP))]); + assert_eq!(run.word(), U256::ONE, "the sibling's child read the timestamp"); +} + +/// A switch set by a child that then reverted goes with the child: a sibling reads. +#[test] +fn test_disable_in_reverted_child_does_not_affect_sibling() { + let child = disable(BytecodeBuilder::default()).revert().build(); + let parent = log_status(call(BytecodeBuilder::default(), CALL, CHILD, 50_000_000)); + let parent = return_word(call(parent, CALL, SIBLING, 50_000_000)); + let run = run(&[(PARENT, parent), (CHILD, child), (SIBLING, reads(TIMESTAMP))]); + assert!(!run.logged_status(0), "the child reverted"); + assert_eq!(run.word(), U256::ONE, "the sibling read"); +} + +/// A switch set by a child that then halted goes with the child, whether the child ran into an +/// invalid opcode or out of gas: a sibling reads. +#[test] +fn test_disable_in_halted_child_does_not_affect_sibling() { + let invalid = disable(BytecodeBuilder::default()).append(INVALID).build(); + // A loop that runs until the child's gas is gone. + let mut out_of_gas = disable(BytecodeBuilder::default()).build_vec(); + let start = u8::try_from(out_of_gas.len()).expect("the loop starts within a PUSH1"); + out_of_gas.extend([JUMPDEST, PUSH1, start, JUMP]); + + for child in [invalid, Bytes::from(out_of_gas)] { + let parent = log_status(call(BytecodeBuilder::default(), CALL, CHILD, 1_000_000)); + let parent = return_word(call(parent, CALL, SIBLING, 1_000_000)); + let run = run(&[(PARENT, parent), (CHILD, child), (SIBLING, reads(TIMESTAMP))]); + assert!(!run.logged_status(0), "the child halted"); + assert_eq!(run.word(), U256::ONE, "the sibling read"); + } +} + +/// A switch does not outlive its transaction: after a transaction whose own frame switched access +/// off, had a child refused, and then stopped or halted, the next transaction on the same EVM +/// reads. +#[test] +fn test_the_switch_does_not_carry_into_the_next_transaction() { + let refused = || log_status(call(disable(BytecodeBuilder::default()), CALL, CHILD, 1_000_000)); + for (first, halts) in + [(refused().stop().build(), false), (refused().append(INVALID).build(), true)] + { + let db = system_db() + .account_code(PARENT, first) + .account_code(CHILD, reads(TIMESTAMP)) + .account_code(SIBLING, reads(TIMESTAMP)); + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + + let one = evm + .execute_transaction(call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + if halts { + assert!(one.result.is_halt(), "{:?}", one.result); + } else { + assert!(one.result.is_success(), "{:?}", one.result); + let status = U256::from_be_slice(&one.result.logs()[0].data.data); + assert_eq!(status, U256::ZERO, "the child was refused"); + } + assert_eq!(evm.ctx().detention().accessed(), VolatileDataAccess::empty()); + + let two = evm + .execute_transaction(call_tx_with_gas(SIBLING, [], U256::ZERO, GAS_LIMIT)) + .expect("the transaction is valid"); + assert!(two.result.is_success(), "halted first: {halts}: {:?}", two.result); + assert_eq!(evm.ctx().detention().accessed(), VolatileDataAccess::TIMESTAMP); + } +} + +/* ---------- 7. enableVolatileDataAccess() ---------- */ + +/// The frame that switched access off can switch it back on, and its child then reads. +#[test] +fn test_enable_after_disable_succeeds() { + let parent = enable(disable(BytecodeBuilder::default())); + let run = run(&[ + (PARENT, return_word(call(parent, CALL, CHILD, 50_000_000))), + (CHILD, reads(TIMESTAMP)), + ]); + assert_eq!(run.word(), U256::ONE); +} + +/// A child cannot switch back on what its caller switched off: its call reverts with +/// `DisabledByParent()`. +#[test] +fn test_enable_by_child_reverts_when_parent_disabled() { + let child = enable(BytecodeBuilder::default()) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, RETURNDATASIZE, PUSH0, RETURN]) + .build(); + let parent = call_and_return_data(disable(BytecodeBuilder::default()), CHILD); + let run = run(&[(PARENT, parent), (CHILD, child)]); + assert_eq!(run.output(), Bytes::from_static(&DISABLED_BY_PARENT)); +} + +/// Switching on what is not off succeeds and changes nothing. +#[test] +fn test_enable_when_not_disabled_is_noop() { + let run = run(&[(PARENT, enable(BytecodeBuilder::default()).append(TIMESTAMP).stop().build())]); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); +} + +/// A `STATICCALL` steers the switch as a `CALL` does: the switch is not state. +#[test] +fn test_staticcall_disable_volatile_data_access_is_intercepted() { + let static_steer = |code: BytecodeBuilder, selector: [u8; 4]| { + code.mstore(0x0, selector) + .append_many([PUSH0, PUSH0]) + .push_number(4_u8) + .append(PUSH0) + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u32) + .append(STATICCALL) + }; + let parent = log_status(static_steer(BytecodeBuilder::default(), DISABLE)); + let parent = log_status(call(parent, CALL, CHILD, 50_000_000)).stop().build(); + let run1 = run(&[(PARENT, parent), (CHILD, reads(TIMESTAMP))]); + assert!(run1.logged_status(0), "the static call succeeded"); + assert!(!run1.logged_status(1), "and switched access off"); + + let parent = log_status(static_steer(disable(BytecodeBuilder::default()), ENABLE)); + let parent = log_status(call(parent, CALL, CHILD, 50_000_000)).stop().build(); + let run2 = run(&[(PARENT, parent), (CHILD, reads(TIMESTAMP))]); + assert!(run2.logged_status(0), "the static call succeeded"); + assert!(run2.logged_status(1), "and switched access back on"); +} + +/* ---------- 8. isVolatileDataAccessDisabled() ---------- */ + +/// The answer at four depths, with the switch set at the second: `false` above it, before it is +/// set and after the frame that set it returned; `true` in that frame and in the two below it. +#[test] +fn test_the_query_answers_for_the_caller_at_every_depth() { + // Each frame queries and keeps its answer in memory at 0x80.. by its own slot, calls the next, + // and returns all the answers it knows of. + let query_into = |code: BytecodeBuilder, slot: u64| { + code.mstore(0x0, IS_DISABLED) + .push_number(32_u8) + .push_number(0x80 + 0x20 * slot) + .push_number(4_u8) + .push_number(0_u8) + .push_number(0_u8) + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u32) + .append_many([CALL, POP]) + }; + // Calls `target`, copying what it returns to 0x80 + 0x20 * `from`. + let call_into = |code: BytecodeBuilder, target: Address, from: u64, words: u64| { + code.push_number(0x20 * words) + .push_number(0x80 + 0x20 * from) + .push_number(0_u8) + .push_number(0_u8) + .push_number(0_u8) + .push_address(target) + .push_number(10_000_000_u32) + .append_many([CALL, POP]) + }; + let returning = |code: BytecodeBuilder, from: u64, words: u64| { + code.push_number(0x20 * words).push_number(0x80 + 0x20 * from).append(RETURN).build() + }; + // Depth 3: queries. + let grandchild_child = returning(query_into(BytecodeBuilder::default(), 3), 3, 1); + // Depth 2: queries, calls depth 3. + let grandchild = + returning(call_into(query_into(BytecodeBuilder::default(), 2), SIBLING, 3, 1), 2, 2); + // Depth 1: queries, switches off, queries, calls depth 2. + let child = query_into(BytecodeBuilder::default(), 0); + let child = call_into(query_into(disable(child), 1), GRANDCHILD, 2, 2); + let child = returning(child, 0, 4); + // Depth 0: queries before and after the child. + let parent = query_into(BytecodeBuilder::default(), 5); + let parent = query_into(call_into(parent, CHILD, 0, 4), 4); + let parent = returning(parent, 0, 6); + + let run = run(&[ + (PARENT, parent), + (CHILD, child), + (GRANDCHILD, grandchild), + (SIBLING, grandchild_child), + ]); + let output = run.output(); + let answers: Vec = + output.chunks(32).map(|word| U256::from_be_slice(word) == U256::ONE).collect(); + assert_eq!( + answers, + vec![ + false, // depth 1, before it switches access off + true, // depth 1, after + true, // depth 2 + true, // depth 3 + false, // depth 0, after depth 1 returned + false, // depth 0, before calling depth 1 + ] + ); +} + +/* ---------- 9. schemes that do not reach the interceptor ---------- */ + +/// `DELEGATECALL` and `CALLCODE` of `disableVolatileDataAccess()` run the contract's bytecode, +/// which reverts with `NotIntercepted()`, and switch nothing off: the child reads. +#[test] +fn test_delegatecall_to_access_control_not_intercepted() { + for scheme in [DELEGATECALL, CALLCODE] { + let parent = BytecodeBuilder::default().mstore(0x0, DISABLE); + let parent = parent.append_many([PUSH0, PUSH0]).push_number(4_u8).append(PUSH0); + let parent = if scheme == CALLCODE { parent.append(PUSH0) } else { parent }; + let parent = + parent.push_address(ACCESS_CONTROL_ADDRESS).push_number(100_000_u32).append(scheme); + let parent = return_word(call(log_status(parent), CALL, CHILD, 50_000_000)); + let run = run(&[ + (PARENT, parent), + (CHILD, reads(TIMESTAMP)), + (ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE), + ]); + assert!(!run.logged_status(0), "{scheme:#04x}: the bytecode reverted"); + assert_eq!(run.word(), U256::ONE, "{scheme:#04x}: and the child read"); + } +} + +/* ---------- 10. below and above the execution cap ---------- */ + +/// The switch behaves the same whether the transaction carries a state-gas reservoir or not, and +/// the transaction costs the same: the answers carry the reservoir back untouched. +#[test] +fn test_the_switch_is_the_same_below_and_above_the_execution_cap() { + let parent = log_status(call(disable(BytecodeBuilder::default()), CALL, CHILD, 50_000_000)); + let parent = log_status(call(enable(parent), CALL, CHILD, 50_000_000)).stop().build(); + let at = |gas_limit: u64| { + let db = + system_db().account_code(PARENT, parent.clone()).account_code(CHILD, reads(TIMESTAMP)); + execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, gas_limit)) + }; + let (below, above) = (at(GAS_LIMIT), at(TX_GAS_LIMIT_CAP + 100_000_000)); + for run in [&below, &above] { + assert!(run.outcome.result.is_success()); + assert!(!run.logged_status(0), "refused while off"); + assert!(run.logged_status(1), "read once on again"); + } + assert_eq!(below.outcome.result.tx_gas_used(), above.outcome.result.tx_gas_used()); + let (below, above) = (below.outcome.gas, above.outcome.gas); + assert_eq!( + (below.regular, below.state, below.history), + (above.regular, above.state, above.history), + "every ledger is the same", + ); + assert_eq!(below.reservoir_remaining, 0, "there is no reservoir below the cap"); + assert_eq!( + above.reservoir_remaining, + 100_000_000 - above.history, + "above it, the reservoir paid the history and the answers carried the rest back", + ); +} diff --git a/crates/mega-evm/tests/system/common.rs b/crates/mega-evm/tests/system/common.rs index 1e734d540..dcd81e511 100644 --- a/crates/mega-evm/tests/system/common.rs +++ b/crates/mega-evm/tests/system/common.rs @@ -12,12 +12,14 @@ use mega_evm::{ SEQUENCER_REGISTRY_CODE, }, test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, + MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, MegaTransactionOutcome, + VolatileDataAccess, }; use revm::{ bytecode::opcode::{ADD, MSTORE, RETURN, RETURNDATACOPY, RETURNDATASIZE}, context::{result::ResultAndState, BlockEnv, TxEnv}, - Database, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, + Database, Inspector, }; /// The sender of every transaction the tests run. @@ -29,8 +31,8 @@ pub(crate) const CONTRACT: Address = address!("0x0000000000000000000000000000000 /// A gas limit below the execution cap, so a transaction has no state-gas reservoir. pub(crate) const GAS_LIMIT: u64 = 100_000_000; -/// A database holding the code of every system contract, as the chain holds it once the fork -/// that deploys them has activated. +/// A database holding the code of every system contract, as a chain that ran the legacy forks +/// holds it. pub(crate) fn system_db() -> MemoryDatabase { MemoryDatabase::default() .account_balance(CALLER, U256::from(1_000_000_000_000_u64)) @@ -70,6 +72,23 @@ pub(crate) fn call_tx(to: Address, data: impl AsRef<[u8]>, value: U256) -> MegaT })) } +/// [`call_tx`] carrying `gas_limit`. +pub(crate) fn call_tx_with_gas( + to: Address, + data: impl AsRef<[u8]>, + value: U256, + gas_limit: u64, +) -> MegaTransaction { + let mut tx = call_tx(to, data, value); + tx.0.base.gas_limit = gas_limit; + tx +} + +/// A `keylessDeploy` transaction carrying `data`, from [`CALLER`], at `gas_limit`. +pub(crate) fn keyless_tx(data: impl AsRef<[u8]>, gas_limit: u64) -> MegaTransaction { + call_tx_with_gas(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO, gas_limit) +} + /// Runs `tx` on a fresh Satin EVM over `db`, without committing. pub(crate) fn run( db: DB, @@ -115,6 +134,34 @@ pub(crate) fn calls_with(scheme: u8, target: Address, data: &[u8], value: u64) - .build() } +/// Appends a `CALL` of `selector` on the access control contract, discarding its status. +pub(crate) fn steer(code: BytecodeBuilder, selector: [u8; 4]) -> BytecodeBuilder { + use revm::bytecode::opcode::{CALL, POP}; + code.mstore(0x0, selector) + .push_number(0_u8) // retSize + .push_number(0_u8) // retOffset + .push_number(4_u8) // argsSize + .push_number(0_u8) // argsOffset + .push_number(0_u8) // value + .push_address(ACCESS_CONTROL_ADDRESS) + .push_number(100_000_u32) + .append_many([CALL, POP]) +} + +/// A call from [`CONTRACT`] to `target` through `scheme`, run as a transaction. +pub(crate) fn through_contract( + target: Address, + scheme: u8, + data: &[u8], + value: u64, +) -> (bool, Bytes) { + let code = calls_with(scheme, target, data, value); + let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = output(&result); + let (status, data) = split_outcome(&outcome); + (status, Bytes::copy_from_slice(data)) +} + /// Splits what [`calls_with`] returns into the inner call's status and its return data. pub(crate) fn split_outcome(output: &[u8]) -> (bool, &[u8]) { let (status, data) = output.split_at(32); @@ -134,3 +181,95 @@ pub(crate) fn revert_data(result: &ResultAndState) -> Bytes { other => panic!("the transaction did not revert: {other:?}"), } } + +/// Whether a state byte costs nothing at the prices in effect: every state-gas entry of the +/// schedule is zero. +/// +/// Only a measurement build arranges that, with `MEGA_SATIN_CPSB` at 0 or at a price every entry +/// rounds to nothing. A test whose scenario is state gas — a limit to cross with it, a bucket to +/// scale it, a charge that cannot be paid — has nothing to run then, and returns early, leaving a +/// note (`note_price_guard`), which the byte-price grid counts. +pub(crate) fn state_is_free() -> bool { + let params = mega_evm::satin_gas_params(); + if !mega_evm::STATE_GAS_REPRICED.iter().all(|&(id, _)| params.get(id()) == 0) { + return false; + } + mega_evm::test_utils::note_price_guard("MEGA_SATIN_CPSB prices a state byte at nothing"); + true +} + +/// The state gas one new account costs at the byte prices in effect, in the minimum bucket. +pub(crate) fn account_state_gas() -> u64 { + mega_evm::satin_gas_params().get(revm::context_interface::cfg::GasId::new_account_state_gas()) +} + +/// The history gas `bytes` bytes cost at the byte prices in effect, by hand rather than through +/// the engine's pricing: the bytes times `COST_PER_HISTORY_BYTE`, 88 gas, at the spec's price. +/// +/// A measurement build may price a history byte with a fraction of a gas, kept in thousandths of +/// a gas; the charge for the bytes is then rounded to the nearest gas, halves up. +pub(crate) fn history(bytes: u64) -> u64 { + use mega_evm::constants::COST_PER_HISTORY_BYTE; + let milli_gas = mega_evm::active_satin_prices().cphb.milli_gas(); + if milli_gas == COST_PER_HISTORY_BYTE * 1_000 { + return bytes * COST_PER_HISTORY_BYTE; + } + let milli_gas = u128::from(bytes) * u128::from(milli_gas); + u64::try_from((milli_gas + 500) / 1_000).expect("the history of the bytes fits a u64") +} + +/// The history gas the body of a transaction carrying `calldata_len` bytes of calldata, and no +/// access list or authorization, pays at the byte prices in effect, by hand: `TX_BODY_SIZE`, 310 +/// bytes, and one byte per byte of calldata. +pub(crate) fn body_history(calldata_len: u64) -> u64 { + history(mega_evm::TX_BODY_SIZE + calldata_len) +} + +/// What a transaction did, and what gas detention made of its reads. +pub(crate) struct Run { + pub(crate) outcome: MegaTransactionOutcome, + pub(crate) accessed: VolatileDataAccess, + pub(crate) limit: Option, +} + +impl Run { + /// The output of the transaction, which must have succeeded. + pub(crate) fn output(&self) -> Bytes { + assert!(self.outcome.result.is_success(), "{:?}", self.outcome.result); + self.outcome.result.output().cloned().unwrap_or_default() + } + + /// The output as a word. + pub(crate) fn word(&self) -> U256 { + U256::from_be_slice(&self.output()) + } + + /// The call status the log at `index` carries. + pub(crate) fn logged_status(&self, index: usize) -> bool { + let logs = self.outcome.result.logs(); + assert!(logs.len() > index, "{} logs, wanted {}", logs.len(), index + 1); + U256::from_be_slice(&logs[index].data.data) == U256::ONE + } +} + +/// Records every answer `remainingComputeGas()` returns, next to the spendable regular gas its +/// caller resumes with. +#[derive(Debug, Default)] +pub(crate) struct AnswerAndResume { + pub(crate) pending: Option, + pub(crate) pairs: Vec<(u64, u64)>, +} + +impl Inspector for AnswerAndResume { + fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + if let Some(answer) = self.pending.take() { + self.pairs.push((answer, interp.gas.tracker().spendable())); + } + } + + fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address == LIMIT_CONTROL_ADDRESS && outcome.result.is_ok() { + self.pending = Some(U256::from_be_slice(&outcome.result.output).to::()); + } + } +} diff --git a/crates/mega-evm/tests/system/control.rs b/crates/mega-evm/tests/system/control.rs index afddd5ce8..a26445c9d 100644 --- a/crates/mega-evm/tests/system/control.rs +++ b/crates/mega-evm/tests/system/control.rs @@ -9,10 +9,7 @@ use mega_evm::{ }; use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; -use crate::common::{ - call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, - CONTRACT, -}; +use crate::common::{call_tx, output, revert_data, run, system_db}; const DISABLE: [u8; 4] = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; const ENABLE: [u8; 4] = IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; @@ -21,15 +18,11 @@ const NOT_INTERCEPTED: [u8; 4] = IMegaAccessControl::NotIntercepted::SELECTOR; /// A call from a contract to the access control contract, run as a transaction. fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { - let code = calls_with(scheme, ACCESS_CONTROL_ADDRESS, data, value); - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - let outcome = output(&result); - let (status, data) = split_outcome(&outcome); - (status, Bytes::copy_from_slice(data)) + crate::common::through_contract(ACCESS_CONTROL_ADDRESS, scheme, data, value) } /// The three methods are intercepted: the two switches return nothing and the query answers -/// `false`, which is what the common execution layer knows while detention is not here. +/// `false` for a caller nothing switched off. What the switch does is in `access_control`. #[test] fn test_the_three_methods_are_intercepted() { let disabled = IMegaAccessControl::isVolatileDataAccessDisabledCall::abi_encode_returns(&false); diff --git a/crates/mega-evm/tests/system/dispatch.rs b/crates/mega-evm/tests/system/dispatch.rs index 300b043fd..51015dca3 100644 --- a/crates/mega-evm/tests/system/dispatch.rs +++ b/crates/mega-evm/tests/system/dispatch.rs @@ -6,11 +6,12 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ system::{ - IMegaAccessControl, IMegaLimitControl, IOracle, ACCESS_CONTROL_ADDRESS, - LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS, + storage_slots::CURRENT_SYSTEM_ADDRESS, IMegaAccessControl, IMegaLimitControl, IOracle, + ACCESS_CONTROL_ADDRESS, LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, }, test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, - MegaEvm, MegaTransactionError, + MegaEvm, MegaTransaction, MegaTransactionError, }; use revm::{ bytecode::opcode::{CALL, POP, STOP}, @@ -142,35 +143,59 @@ fn test_an_inspector_sees_an_intercepted_call() { assert_eq!(evm.inspector().call_ends, vec![LIMIT_CONTROL_ADDRESS, CONTRACT]); } -/// A database error while the system address is read during validation fails the transaction -/// with that error: a database blip must not let the transaction through as a deposit. -#[test] -fn test_a_database_error_reading_the_system_address_fails_the_transaction() { - let mut db = ErrorInjectingDatabase::new(system_db()); - db.fail_on_account = Some(MEGA_SYSTEM_ADDRESS); +/// A system-address transaction: a legacy call from [`MEGA_SYSTEM_ADDRESS`] to the Oracle. +fn system_address_tx() -> MegaTransaction { + let mut tx = call_tx( + ORACLE_CONTRACT_ADDRESS, + IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(), + U256::ZERO, + ); + tx.0.base.caller = MEGA_SYSTEM_ADDRESS; + tx.0.base.chain_id = Some(revm::context::CfgEnv::::default().chain_id); + tx +} - let tx = { - let mut tx = call_tx( - ORACLE_CONTRACT_ADDRESS, - IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(), - U256::ZERO, - ); - tx.0.base.caller = MEGA_SYSTEM_ADDRESS; - tx.0.base.chain_id = - Some(revm::context::CfgEnv::::default().chain_id); - tx - }; +/// Runs [`system_address_tx`] over `db` and answers the database error it failed with. +fn database_error(db: ErrorInjectingDatabase) -> InjectedDbError { let result: Result<_, EVMError> = - MegaEvm::new(context(db)).transact_raw(tx); - + MegaEvm::new(context(db)).transact_raw(system_address_tx()); match result { - Err(EVMError::Database(error)) => { - assert!(format!("{error}").contains(&MEGA_SYSTEM_ADDRESS.to_string()), "{error}"); - } + Err(EVMError::Database(error)) => error, other => panic!("expected a database error, got: {other:?}"), } } +/// A database error while the system address's account is read during validation fails the +/// transaction with that error: a database blip must not let the transaction through as a +/// deposit. +#[test] +fn test_a_database_error_reading_the_system_address_fails_the_transaction() { + let mut db = ErrorInjectingDatabase::new(system_db().sequencer_registry(MEGA_SYSTEM_ADDRESS)); + db.fail_on_account = Some(MEGA_SYSTEM_ADDRESS); + let error = database_error(db); + assert!(format!("{error}").contains(&MEGA_SYSTEM_ADDRESS.to_string()), "{error}"); +} + +/// A database error while the registry is read for the live system address fails the +/// transaction with that error too, whether it is the registry's account or its slot the +/// database cannot serve: the transaction is neither promoted nor run as an ordinary one on a +/// guess. +#[test] +fn test_a_database_error_reading_the_registry_fails_the_transaction() { + let registry = + || ErrorInjectingDatabase::new(system_db().sequencer_registry(MEGA_SYSTEM_ADDRESS)); + + let mut db = registry(); + db.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + let error = database_error(db); + assert!(format!("{error}").contains(&SEQUENCER_REGISTRY_ADDRESS.to_string()), "{error}"); + + let mut db = registry(); + db.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + let error = database_error(db); + assert!(format!("{error}").contains("injected storage() error"), "{error}"); +} + /// The value policy is the interceptor's, not the account's: a value-bearing transaction to a /// control contract is refused with `NonZeroTransfer()` before any value moves. #[test] diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs new file mode 100644 index 000000000..0817418b4 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -0,0 +1,347 @@ +//! What a keyless deployment is charged, charge by charge, below and above the execution cap. +//! +//! Every figure is measured against the same calldata sent to an account with no code, which +//! pays the same intrinsic gas and nothing else: what the `keylessDeploy` transaction spends +//! beyond it is the overhead, the charges its call makes for the creation's start, and what the +//! creation itself spent — its `gasUsed`. + +use mega_evm::{constants::MAX_INITCODE_SIZE, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS}; +use revm::bytecode::opcode::{PUSH0, REVERT}; + +use super::*; +use crate::common::state_is_free; + +/// The length of the runtime the tests deploy. +const RUNTIME_LEN: usize = 5; + +/// Every charge of a deployment by a signer with no account, to an empty address, is accounted +/// for exactly, and the transaction spends the same below and above the execution cap: +/// +/// - the overhead, and the regular gas the `CREATE` opcode charges its frame; +/// - the signer's account and the created account, as state gas, once each; +/// - the two write records the creation's start makes — the signer's nonce and the created account +/// — as history; +/// - what the creation spent, which is `gasUsed`: its regular gas, the state gas of the code it +/// deposited and the history of the same bytes. +#[test] +fn test_every_charge_of_a_deployment_is_accounted_for() { + let init_code = deploying(&runtime(RUNTIME_LEN)); + let opcode = create_regular(init_code.len()); + let deployment = Deployment::new(init_code); + let len = RUNTIME_LEN as u64; + let deposit_state = satin_gas_params().code_deposit_state_gas(RUNTIME_LEN); + let mut spent = None; + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let gas_used = returned(&outcome).gasUsed; + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); + + let new_account = entry(GasId::new_account_state_gas()); + let created = entry(GasId::create_state_gas()); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + new_account + created + 2 * record() + gas_used, + "at {gas_limit}", + ); + assert_eq!(state, new_account + created + deposit_state, "at {gas_limit}"); + assert_eq!(history_gas, 2 * record() + history(len), "at {gas_limit}"); + assert_eq!(history_bytes, 2 * 40 + len, "at {gas_limit}"); + let creation_regular = gas_used - deposit_state - history(len); + assert_eq!( + regular, + KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + creation_regular, + "at {gas_limit}" + ); + assert_eq!(outcome.usage.write_records, 2, "the signer's nonce and the created account"); + + let previous = *spent.get_or_insert((total, gas_used)); + assert_eq!((total, gas_used), previous, "the pools do not move what a deployment costs"); + } +} + +/// A signer with no account is charged its account once, as state gas: the only difference +/// between a signer that holds a wei and one that holds nothing. EIP-2780 charges the transaction's +/// recipient, which is the `KeylessDeploy` contract and exists, so it adds nothing of its own. +#[test] +fn test_an_empty_signer_is_charged_its_account_once() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + for gas_limit in GAS_LIMITS { + let empty = deploy(db_for(&deployment, U256::ZERO), &deployment, gas_limit); + let funded = deploy(db_for(&deployment, U256::from(1)), &deployment, gas_limit); + let [total, regular, state, history_gas, _] = beyond(&empty, &funded); + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!([total, regular, state, history_gas], [new_account, 0, new_account, 0]); + assert_eq!(returned(&empty).gasUsed, returned(&funded).gasUsed); + assert_eq!(nonce(&empty, deployment.signer), 1); + assert_eq!(nonce(&funded, deployment.signer), 1); + } +} + +/// The created account is charged only when the deploy address is empty, as the `CREATE` opcode +/// charges it: an address that already holds a balance is an account already, the deployment +/// lands on it, and the balance stays. +#[test] +fn test_the_created_account_is_charged_only_when_the_address_is_empty() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + for gas_limit in GAS_LIMITS { + let empty = deploy(system_db(), &deployment, gas_limit); + let held = system_db().account_balance(deployment.address, U256::from(7_777)); + let held = deploy(held, &deployment, gas_limit); + assert_eq!(returned(&held).deployedAddress, deployment.address); + assert_eq!( + held.state.get(&deployment.address).map(|account| account.info.balance), + Some(U256::from(7_777)), + ); + let [total, regular, state, history_gas, _] = beyond(&empty, &held); + let created = entry(GasId::create_state_gas()); + assert_eq!([total, regular, state, history_gas], [created, 0, created, 0]); + } +} + +/// A refused call keeps the overhead and nothing else: every charge made after it is taken back +/// with the revert, whatever the pools. +#[test] +fn test_a_refused_call_keeps_the_overhead_alone() { + // A value the signer cannot fund: refused at the last rule, after every read. + let deployment = Deployment::with_value(deploying(&runtime(RUNTIME_LEN)), U256::from(1)); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); + assert_eq!( + [total, regular, state, history_gas, history_bytes], + [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0, 0], + "at {gas_limit}", + ); + assert_eq!(outcome.usage.write_records, 0); + } +} + +/// A deployment whose init code reverts gives the created account's charge back, and the record +/// of the account it did not create; the signer's account and its nonce record stay, because the +/// nonce stays spent. +#[test] +fn test_a_failed_deployment_gives_the_created_account_back() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let error = failure(&outcome); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = error else { + panic!("expected ExecutionReverted, got {error:?}"); + }; + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, history_bytes] = beyond(&outcome, &reference); + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!(state, new_account, "at {gas_limit}"); + assert_eq!(history_gas, record(), "at {gas_limit}"); + assert_eq!(history_bytes, 40, "at {gas_limit}"); + assert_eq!( + regular, + KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(3) + gas_used, + "at {gas_limit}" + ); + assert_eq!(total, regular + state + history_gas); + assert_eq!(nonce(&outcome, deployment.signer), 1, "the nonce stays spent"); + assert_eq!(outcome.usage.write_records, 1, "the signer's nonce"); + } +} + +/// The call pays the regular gas the `CREATE` opcode charges its frame on top of the overhead, +/// whatever the pools: the schedule's `create` entry, 12,000, and EIP-3860's 2 gas per word of +/// init code, 65,536 for init code of the maximum size. Init code of zero bytes stops at once and +/// deploys nothing, so the creation, refused its empty deposit, spends nothing and reverts: the +/// deployed account's state gas and its record's history come back, and what stays charged is the +/// signer's account and the signer's nonce record. +#[test] +fn test_the_call_pays_the_create_opcodes_regular_gas() { + assert_eq!(create_regular(1), 12_000 + 2); + assert_eq!(create_regular(33), 12_000 + 4); + assert_eq!(create_regular(MAX_INITCODE_SIZE), 12_000 + 65_536); + let state = entry(GasId::new_account_state_gas()); + for len in [1, 33, MAX_INITCODE_SIZE] { + let deployment = Deployment::new(vec![0; len].into()); + // Gas limits that cover the body of a transaction carrying a mebibyte of calldata, below + // and above the execution cap. + for gas_limit in tiers_carrying(deployment.call_data(LARGE_OVERRIDE).len()) { + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + assert_eq!(gas_used, 0); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state_gas, history_gas, _] = beyond(&outcome, &reference); + let regular_expected = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(len); + assert_eq!(regular, regular_expected, "{len} bytes at {gas_limit}"); + assert_eq!(state_gas, state, "{len} bytes at {gas_limit}"); + assert_eq!(history_gas, record(), "{len} bytes at {gas_limit}"); + assert_eq!(total, regular_expected + state + record(), "{len} bytes at {gas_limit}"); + } + } +} + +/// `gasUsed` is what the creation spent before refunds: a constructor that fills a slot and +/// clears it again earns a refund, which is the transaction's, as any frame's is. The charges add +/// up to the transaction's spend before its refund, and the receipt's gas is that spend less the +/// refund. +#[test] +fn test_gas_used_counts_the_creations_spend_before_its_refund() { + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .sstore(U256::ZERO, U256::ONE) + .sstore(U256::ZERO, U256::ZERO) + .build_vec(); + let init_code = constructor(&prefix, &runtime(1)); + let opcode = create_regular(init_code.len()); + let deployment = Deployment::new(init_code); + let upfront = + entry(GasId::new_account_state_gas()) + entry(GasId::create_state_gas()) + 2 * record(); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let gas_used = returned(&outcome).gasUsed; + let refund = outcome.result.gas().inner_refunded(); + assert!(refund > 0, "the constructor earns a refund at {gas_limit}"); + let [total, ..] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + opcode + upfront + gas_used, + "at {gas_limit}" + ); + assert_eq!( + outcome.result.gas().tx_gas_used(), + outcome.result.gas().total_gas_spent() - refund, + "at {gas_limit}", + ); + } +} + +/// Both upfront charges are priced by the SALT bucket they land in — the signer's account in the +/// signer's, the created account in the deploy address's — and regular gas does not move with it. +#[test] +fn test_the_upfront_charges_scale_with_their_buckets() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + let new_account = entry(GasId::new_account_state_gas()); + let created = entry(GasId::create_state_gas()); + for gas_limit in GAS_LIMITS { + let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); + for (m_signer, m_address) in [(2, 1), (1, 2), (3, 2)] { + let envs = crowded( + crowded(TestExternalEnvs::new(), deployment.signer, m_signer), + deployment.address, + m_address, + ); + let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); + assert_eq!(crowded_run.gas.regular, minimal.gas.regular, "m does not touch regular"); + assert_eq!( + crowded_run.gas.state - minimal.gas.state, + (m_signer - 1) * new_account + + (m_address - 1) * (created + satin_gas_params().code_deposit_state_gas(5)), + "signer at m = {m_signer}, address at m = {m_address}, gas limit {gas_limit}", + ); + } + } +} + +/// A deployment that fails gives the created account back at the price it was charged, however +/// crowded the deploy address's bucket, and the bucket is read once for both; the signer's +/// account is kept at its own bucket's price. +#[test] +fn test_a_failed_deployment_gives_the_created_account_back_at_its_price() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let new_account = entry(GasId::new_account_state_gas()); + for gas_limit in GAS_LIMITS { + for m in [1, 2, 8] { + let envs = crowded( + crowded(TestExternalEnvs::new(), deployment.address, m), + deployment.signer, + m, + ); + let outcome = salt_run(system_db(), envs.clone(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + let reference = salt_run( + system_db(), + TestExternalEnvs::new(), + &Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])), + gas_limit, + ); + assert_eq!(outcome.gas.state, m * new_account, "m = {m}, gas limit {gas_limit}"); + assert_eq!(outcome.gas.regular, reference.gas.regular, "m = {m}"); + assert_eq!( + envs.bucket_queries(bucket(deployment.address)), + 1, + "one read priced the charge and its refund", + ); + } + } +} + +/// A signer that sends its own deployment is the transaction's sender, whose account the body +/// counts: the creation's nonce bump makes no record of its own, only the created account does, +/// and the signer, an account already, is charged nothing for it. The transaction's own bump took +/// it to nonce 1, and the creation's bump from there is taken back. +/// +/// That bump's record would go back with it at the end, so the ledgers of a deployment that runs +/// cannot show whether step 14 charged it. What can is the forward: below the execution cap the +/// call's charges come out of its regular gas, and a forward they leave short of the signed gas +/// limit is refused `GasLimitTooLow` with what they left. Sent by its signer, the call is left the +/// `CREATE` opcode's regular gas, the created account and one record short of what it had after +/// its overhead; sent by a relayer for a signer holding a wei, one record more. +/// +/// Rule [S15.22]. Expected values `constants`: the charges are the schedule's `create`, initcode +/// and created-account entries and one record's history at the cost per history byte; what the +/// call has after its overhead is set by the test on a gas limit built by hand — the call's +/// EIP-2780 intrinsic, its calldata's cost, its body's history and the keyless overhead — so an +/// intrinsic the engine got wrong would move the forward too. +#[test] +fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { + let init_code = deploying(&runtime(RUNTIME_LEN)); + let deployment = Deployment::new(init_code.clone()); + let from_signer = |gas_limit| { + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx.0.base.caller = deployment.signer; + MegaEvm::new(context(system_db())).execute_transaction(tx).expect("a valid transaction") + }; + for gas_limit in GAS_LIMITS { + let outcome = from_signer(gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + // The transaction bumped its sender from 0 to 1; the creation's bump is taken back. + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert_eq!(outcome.usage.write_records, 1, "the created account alone"); + let deposit_state = satin_gas_params().code_deposit_state_gas(RUNTIME_LEN); + assert_eq!(outcome.gas.state, entry(GasId::create_state_gas()) + deposit_state); + } + + // What each call has after its overhead: the creation's charges with one record, and one gas + // short of the signed gas limit beside them, so the forward is refused whoever sends the call + // and at any byte price. + let data = deployment.call_data(LARGE_OVERRIDE); + let created = create_regular(init_code.len()) + entry(GasId::create_state_gas()); + let left = SIGNED_GAS_LIMIT - 1 + created + record(); + let gas_limit = intrinsic(&data) + KEYLESS_DEPLOY_OVERHEAD_GAS + left; + let provided = |outcome: &MegaTransactionOutcome| match refusal(outcome) { + KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } => { + assert_eq!(tx_gas_limit, SIGNED_GAS_LIMIT); + provided_gas_limit + } + other => panic!("refused {other:?}, not for the forward"), + }; + let by_relayer = + run_with(db_for(&deployment, U256::ONE), data, gas_limit, EvmTxRuntimeLimits::no_limits()); + assert_eq!( + provided(&from_signer(gas_limit)), + left - created - record(), + "sent by its signer: the created account's record alone", + ); + assert_eq!( + provided(&by_relayer), + left - created - 2 * record(), + "sent by a relayer: the signer's nonce record too", + ); +} diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs new file mode 100644 index 000000000..2fd93df66 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -0,0 +1,928 @@ +//! What a keyless deployment deploys and reports: the native creation runs the init code as any +//! creation does, and the call answers with what it did. + +use alloy_primitives::{address, hex, B256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + system::{ + keyless::{ + tests::{ + CREATE2_FACTORY_CODE_HASH, CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, + CREATE2_FACTORY_TX, EIP1820_CODE_HASH, EIP1820_CONTRACT, EIP1820_DEPLOYER, + EIP1820_TX, + }, + IKeylessDeploy, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + IOracle, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{BytecodeBuilder, ErrorInjectingDatabase}, + MegaTransaction, +}; +use revm::{ + bytecode::opcode::{ + CALL, CREATE, DELEGATECALL, GAS, GASPRICE, INVALID, JUMP, JUMPDEST, LOG0, LOG1, MLOAD, + ORIGIN, POP, PUSH0, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFDESTRUCT, SHR, SSTORE, + STATICCALL, + }, + context::BlockEnv, + primitives::KECCAK_EMPTY, + Database, DatabaseCommit, +}; + +use super::*; +use crate::common::{calls_with, split_outcome, with_contract, CALLER as RELAYER, CONTRACT}; + +/// An account the deployments below call into. +const HELPER: Address = address!("0x0000000000000000000000000000000000500000"); + +/// The beneficiary of the blocks the fee tests run in. +const BENEFICIARY: Address = address!("0x0000000000000000000000000000000000beef01"); + +/// Init code that runs `prefix` and deploys a one-byte runtime. +fn running(prefix: BytecodeBuilder) -> Bytes { + constructor(&prefix.build_vec(), &runtime(1)) +} + +/// A `CALL` of `target` with no value and no data, forwarding all the gas, its status popped. +fn calling(code: BytecodeBuilder, target: Address, scheme: u8) -> BytecodeBuilder { + let code = code.push_number(0_u64).push_number(0_u64).push_number(0_u64).push_number(0_u64); + let code = if scheme == CALL { code.push_number(0_u64) } else { code }; + code.push_address(target).append(GAS).append(scheme).append(POP) +} + +/// The canonical `CREATE2` factory deploys at its canonical address, from its canonical signer, +/// with or without a reservoir, and its signer's nonce is spent. +#[test] +fn test_keyless_deploy_create2_factory() { + for gas_limit in GAS_LIMITS { + let data = keyless_deploy_call(CREATE2_FACTORY_TX, U256::from(LARGE_OVERRIDE)); + let outcome = run_with(system_db(), data, gas_limit, EvmTxRuntimeLimits::no_limits()); + let ret = returned(&outcome); + assert_eq!(ret.deployedAddress, CREATE2_FACTORY_CONTRACT, "at {gas_limit}"); + assert!(ret.errorData.is_empty()); + assert!(ret.gasUsed > 0); + assert_eq!(code_hash(&outcome, CREATE2_FACTORY_CONTRACT), Some(CREATE2_FACTORY_CODE_HASH)); + assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 1); + } +} + +/// The EIP-1820 registry, the other canonical Nick's-Method deployment. +#[test] +fn test_keyless_deploy_eip1820() { + for gas_limit in GAS_LIMITS { + let data = keyless_deploy_call(EIP1820_TX, U256::from(LARGE_OVERRIDE)); + let outcome = run_with(system_db(), data, gas_limit, EvmTxRuntimeLimits::no_limits()); + assert_eq!(returned(&outcome).deployedAddress, EIP1820_CONTRACT, "at {gas_limit}"); + assert_eq!(code_hash(&outcome, EIP1820_CONTRACT), Some(EIP1820_CODE_HASH)); + assert_eq!(nonce(&outcome, EIP1820_DEPLOYER), 1); + } +} + +/// A deployment lands at the signer's first creation address, whoever the signer is, and the +/// deployed code is the runtime the init code returned. +#[test] +fn test_the_deploy_address_is_the_signers_first_creation_address() { + for gas_limit in GAS_LIMITS { + for len in [1, 2, 3] { + let deployment = Deployment::new(deploying(&runtime(len))); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.signer.create(0)); + assert_eq!(code_hash(&outcome, deployment.address), Some(keccak(&runtime(len)))); + } + } +} + +/// The hash of `code`. +fn keccak(code: &[u8]) -> B256 { + alloy_primitives::keccak256(code) +} + +/// What a deployment writes survives a commit: the account is created with its code. +#[test] +fn test_a_deployment_survives_a_commit() { + for gas_limit in GAS_LIMITS { + let mut db = system_db(); + let data = keyless_deploy_call(CREATE2_FACTORY_TX, U256::from(LARGE_OVERRIDE)); + let outcome = run_with(db.clone(), data, gas_limit, EvmTxRuntimeLimits::no_limits()); + assert!(outcome.result.is_success()); + db.commit(outcome.result_and_state.state); + let deployed = db.basic(CREATE2_FACTORY_CONTRACT).unwrap().expect("the account exists"); + assert_eq!(deployed.code_hash, CREATE2_FACTORY_CODE_HASH); + assert_eq!(deployed.nonce, 1); + } +} + +/// Init code that reverts: the call succeeds and reports `ExecutionReverted` with the revert +/// data, the deployment writes no code, and the signer's nonce is spent. +#[test] +fn test_keyless_deploy_execution_reverted() { + let deployment = + Deployment::new(BytecodeBuilder::default().revert_with_data([0xc0, 0xff, 0xee]).build()); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::ExecutionReverted { gas_used, output } = failure(&outcome) else { + panic!("expected ExecutionReverted: {:?}", outcome.result); + }; + assert_eq!(output, Bytes::from_static(&[0xc0, 0xff, 0xee])); + assert_eq!(gas_used, returned(&outcome).gasUsed); + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + +/// Init code that hits an invalid opcode: `ExecutionHalted`, and the halt spends the whole +/// forward. +#[test] +fn test_keyless_deploy_execution_halted_invalid_opcode() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[INVALID])); + let outcome = run_with( + system_db(), + deployment.call_data(2_000_000), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionHalted: {:?}", outcome.result); + }; + assert_eq!(gas_used, 2_000_000, "a halt spends what it was forwarded"); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// A constructor that runs out of gas halts the same way, below and above the execution cap, +/// and spends its whole forward in both. +#[test] +fn test_a_constructor_out_of_gas_is_execution_halted() { + let deployment = Deployment::new(Bytes::from_static(&[JUMPDEST, PUSH0, JUMP])); + for gas_limit in GAS_LIMITS { + let outcome = run_with( + system_db(), + deployment.call_data(SIGNED_GAS_LIMIT), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionHalted: {:?}", outcome.result); + }; + assert_eq!(gas_used, SIGNED_GAS_LIMIT, "at {gas_limit}"); + } +} + +/// A halted deployment is paid for, and its nonce is spent: the transaction spends the overhead, +/// the `CREATE` opcode's regular gas, the signer's account and its nonce record, and the whole +/// forward. +#[test] +fn test_a_halted_deployment_is_paid_for_and_spends_the_nonce() { + let deployment = Deployment::new(Bytes::from_static(&[INVALID])); + for gas_limit in GAS_LIMITS { + let data = deployment.call_data(SIGNED_GAS_LIMIT); + let outcome = + run_with(system_db(), data.clone(), gas_limit, EvmTxRuntimeLimits::no_limits()); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 1); + let [total, ..] = beyond(&outcome, &reference(data, gas_limit)); + let new_account = entry(GasId::new_account_state_gas()); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(1) + + new_account + + record() + + SIGNED_GAS_LIMIT, + "at {gas_limit}", + ); + } +} + +/// Init code that returns nothing deploys no code: `EmptyCodeDeployed`, and the nonce is spent. +#[test] +fn test_keyless_deploy_empty_initcode() { + for gas_limit in GAS_LIMITS { + for init_code in [Bytes::new(), Bytes::from_static(&[PUSH0, PUSH0, RETURN])] { + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + assert_eq!(gas_used, returned(&outcome).gasUsed); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } + } +} + +/// A deployment whose initcode returns empty code at the deploy address is refused: the creation +/// reverts, the call answers `EmptyCodeDeployed`, and the deploy address keeps no account, so the +/// signed bytes can still be deployed. The initcode returns empty code when it has more than +/// 2,000,000 gas left and a one-byte runtime otherwise, so whoever submits the signed bytes first +/// chooses the outcome through `gasLimitOverride`: the second submission, with a forward that +/// makes the initcode deploy, finds the address free and deploys. The signer stays at nonce 1, +/// the first creation's bump from 0 being the replay barrier and the second's from 1 taken back. +#[test] +fn test_an_empty_code_deployment_leaves_the_address_deployable() { + let gas_dependent = Bytes::from(hex!("5a621e848010600d5760015ff35b5f5ff3").to_vec()); + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(gas_dependent.clone()); + let mut db = system_db(); + let first = run_nth( + db.clone(), + deployment.call_data(5_000_000), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + 0, + ); + assert!( + matches!(failure(&first), KeylessDeployError::EmptyCodeDeployed { .. }), + "{:?}", + first.result + ); + assert_eq!(nonce(&first, deployment.signer), 1, "the first bump stands"); + assert!( + first.state.get(&deployment.address).is_none_or(|account| account.info.nonce == 0), + "the deploy address keeps no nonce" + ); + assert!( + code_hash(&first, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY), + "and no code" + ); + db.commit(first.result_and_state.state); + + let second = run_nth( + db, + deployment.call_data(SIGNED_GAS_LIMIT), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + 1, + ); + assert_eq!(returned(&second).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(nonce(&second, deployment.signer), 1, "the second bump is taken back"); + assert_eq!(nonce(&second, deployment.address), 1); + } +} + +/// A deploy address at nonce 1 without code — what a Rex6 deployment whose creation returned +/// empty code left — passes the occupancy rule, which reads the code alone, and the creation +/// collides there before its init code runs: whatever the init code would do, the call answers +/// `ExecutionHalted` with the whole forward spent, the address keeps its nonce and no code, and the +/// signer's bump from 0 stands. +#[test] +fn test_a_deploy_address_with_a_nonce_and_no_code_collides() { + let init_codes = + [deploying(&runtime(1)), Bytes::new(), Bytes::from_static(&[INVALID]), logging(32)]; + for init_code in init_codes { + let deployment = Deployment::new(init_code); + let db = system_db().account_nonce(deployment.address, 1); + for gas_limit in GAS_LIMITS { + for forward in [SIGNED_GAS_LIMIT, 2 * SIGNED_GAS_LIMIT] { + let outcome = run_with( + db.clone(), + deployment.call_data(forward), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionHalted: {:?}", outcome.result); + }; + assert_eq!(gas_used, forward, "a collision spends the forward, at {gas_limit}"); + assert_eq!(nonce(&outcome, deployment.signer), 1, "the bump from 0 stands"); + assert_eq!(nonce(&outcome, deployment.address), 1, "the address keeps its nonce"); + assert_eq!(code_hash(&outcome, deployment.address), Some(KECCAK_EMPTY)); + assert!(outcome.result.logs().is_empty(), "the init code never ran"); + } + } + } +} + +/// An empty deposit is refused at the deploy address alone: a constructor's own `CREATE` that +/// returns empty code is admitted, and the deployment around it succeeds. +#[test] +fn test_a_constructors_own_creation_may_return_empty_code() { + for gas_limit in GAS_LIMITS { + // CREATE of empty init code, then the deployment's own runtime. + let prefix = [PUSH0, PUSH0, PUSH0, CREATE, POP]; + let deployment = Deployment::new(constructor(&prefix, &runtime(1))); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + let inner = deployment.address.create(1); + assert_eq!(nonce(&outcome, inner), 1, "the inner creation stands, with no code"); + assert_eq!(code_hash(&outcome, inner), Some(KECCAK_EMPTY)); + } +} + +/// Init code that destroys its own account: the value it held goes to the beneficiary, no code +/// is left, and the call reports `EmptyCodeDeployed`. +#[test] +fn test_keyless_deploy_init_code_selfdestructs() { + for gas_limit in GAS_LIMITS { + let beneficiary = address!("0x0000000000000000000000000000000000beeef1"); + let init_code = + BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build(); + let deployment = Deployment::with_value(init_code, U256::from(1_000)); + let outcome = deploy(db_for(&deployment, U256::from(1_000)), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert_eq!( + outcome.state.get(&beneficiary).map(|account| account.info.balance), + Some(U256::from(1_000)), + ); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// A constructor that has its own account destroyed through a `DELEGATECALL` and then returns +/// code reports `EmptyCodeDeployed`: the code the constructor returned is not code the account +/// keeps (EIP-6780), and the answer is read from the account, not from the return. +#[test] +fn test_a_constructor_destroyed_through_delegatecall_deploys_no_code() { + for gas_limit in GAS_LIMITS { + let helper = Bytes::from_static(&[PUSH0, SELFDESTRUCT]); + let deployment = + Deployment::new(running(calling(BytecodeBuilder::default(), HELPER, DELEGATECALL))); + let db = system_db().account_code(HELPER, helper); + let outcome = deploy(db, &deployment, gas_limit); + let ret = returned(&outcome); + assert_eq!(ret.deployedAddress, Address::ZERO); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert!(outcome + .state + .get(&deployment.address) + .is_some_and(|account| account.is_selfdestructed()),); + } +} + +/// Code starting with `0xEF` is refused by the creation (EIP-3541): `ExecutionHalted`. +#[test] +fn test_code_starting_with_ef_is_refused() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&[0xef, 0x00])); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + +/// Code over the contract size limit is refused by the creation (EIP-170): `ExecutionHalted`. +#[test] +fn test_code_over_the_size_limit_is_refused() { + for gas_limit in GAS_LIMITS { + let size = mega_evm::constants::MAX_CONTRACT_SIZE as u64 + 1; + let init_code = + BytecodeBuilder::default().push_number(size).push_number(0_u64).append(RETURN).build(); + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. })); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + +/// A deployment carrying a value moves it from the signer to the contract. +#[test] +fn test_keyless_deploy_with_value_transfer() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); + let outcome = deploy(db_for(&deployment, U256::from(10_000)), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); + assert_eq!(balance(deployment.address), Some(U256::from(7_777))); + assert_eq!(balance(deployment.signer), Some(U256::from(2_223))); + } +} + +/// A constructor that writes another contract's storage: the write is kept. +#[test] +fn test_keyless_deploy_modifies_other_contract_state() { + for gas_limit in GAS_LIMITS { + let store = + Bytes::from_static(&[PUSH0, revm::bytecode::opcode::CALLDATALOAD, PUSH0, SSTORE]); + let value = U256::from(0x1234_5678_u64); + let prefix = BytecodeBuilder::default() + .mstore(0, value.to_be_bytes::<32>()) + .push_number(0_u64) + .push_number(0_u64) + .push_number(32_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(HELPER) + .append(GAS) + .append(CALL) + .append(POP); + let deployment = Deployment::new(running(prefix)); + let outcome = deploy(system_db().account_code(HELPER, store), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let slot = outcome.state[&HELPER].storage.get(&U256::ZERO).map(|slot| slot.present_value); + assert_eq!(slot, Some(value)); + } +} + +/// A constructor that creates a contract: the child is deployed at the new contract's first +/// creation address (its nonce starts at 1). +#[test] +fn test_keyless_deploy_creates_child_contract() { + for gas_limit in GAS_LIMITS { + let child_init = deploying(&[0x00]); + let prefix = BytecodeBuilder::default() + .mstore(0, &child_init) + .push_number(child_init.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .append(CREATE) + .append(POP); + let deployment = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let child = deployment.address.create(1); + assert_eq!(code_hash(&outcome, child), Some(keccak(&[0x00]))); + assert_eq!(nonce(&outcome, deployment.address), 2, "the contract created one child"); + } +} + +/// A constructor that reads another contract, and keeps what it read in its own storage. +#[test] +fn test_keyless_deploy_reads_existing_contract() { + for gas_limit in GAS_LIMITS { + let reader = + BytecodeBuilder::default().return_with_data(U256::from(42).to_be_bytes::<32>()).build(); + let prefix = BytecodeBuilder::default() + .push_number(32_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(HELPER) + .append(GAS) + .append(STATICCALL) + .append(POP) + .push_number(0_u64) + .append(MLOAD) + .push_number(0_u64) + .append(SSTORE); + let deployment = Deployment::new(running(prefix)); + let outcome = deploy(system_db().account_code(HELPER, reader), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let slot = + outcome.state[&deployment.address].storage.get(&U256::ZERO).map(|s| s.present_value); + assert_eq!(slot, Some(U256::from(42))); + } +} + +/// A constructor that writes storage and then reverts leaves neither the storage nor code, and +/// the call still reports the revert with a gas figure. +#[test] +fn test_failed_initcode_keeps_no_storage() { + let init_code = + BytecodeBuilder::default().sstore(U256::from(1), U256::from(7)).revert().build(); + let deployment = Deployment::new(init_code); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let KeylessDeployError::ExecutionReverted { gas_used, .. } = failure(&outcome) else { + panic!("expected ExecutionReverted: {:?}", outcome.result); + }; + assert!(gas_used > 0); + let kept = outcome + .state + .get(&deployment.address) + .and_then(|account| account.storage.get(&U256::from(1)).map(|slot| slot.present_value)); + assert!(kept.is_none_or(|value| value.is_zero()), "at {gas_limit}"); + assert!(code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + assert_eq!(outcome.gas.state, entry(GasId::new_account_state_gas())); + } +} + +/// A constructor's log is the transaction's: it is in the receipt, emitted by the deployed +/// address. +#[test] +fn test_keyless_deploy_emits_logs() { + for gas_limit in GAS_LIMITS { + let prefix = BytecodeBuilder::default() + .mstore(0, B256::repeat_byte(0xab)) + .push_number(32_u64) + .push_number(0_u64) + .append(LOG0); + let deployment = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let logs = outcome.result.logs(); + assert_eq!(logs.len(), 1); + assert_eq!(logs[0].address, deployment.address); + assert_eq!(logs[0].data.data, Bytes::from(B256::repeat_byte(0xab).to_vec())); + } +} + +/// Init code that logs and deploys nothing keeps no log: the call reports `EmptyCodeDeployed`, and +/// the creation, refused its empty deposit, reverted with its log. +#[test] +fn test_an_empty_code_deployment_keeps_no_log() { + for gas_limit in GAS_LIMITS { + let topic = B256::repeat_byte(0x11); + let init_code = BytecodeBuilder::default() + .mstore(0, [0xde, 0xad, 0xbe, 0xef]) + .push_bytes(topic) + .push_number(4_u64) + .push_number(0_u64) + .append(LOG1) + .return_empty() + .build(); + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert!(outcome.result.logs().is_empty()); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// And init code that logs nothing leaves none. +#[test] +fn test_an_empty_code_deployment_adds_no_log() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(BytecodeBuilder::default().return_empty().build()); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + assert!(outcome.result.logs().is_empty()); + } +} + +/// A deployment that fails keeps no log: the creation's revert takes its logs with it. +#[test] +fn test_a_failed_deployment_keeps_no_log() { + for gas_limit in GAS_LIMITS { + let init_code = BytecodeBuilder::default() + .push_number(0_u64) + .push_number(0_u64) + .append(LOG0) + .revert() + .build(); + let deployment = Deployment::new(init_code); + let outcome = deploy(system_db(), &deployment, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert!(outcome.result.logs().is_empty()); + } +} + +/// The `keylessDeploy` transaction from the relayer at `gas_price`, at `gas_limit`. +fn priced_tx(deployment: &Deployment, gas_limit: u64, gas_price: u128) -> MegaTransaction { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx.0.base.gas_price = gas_price; + tx +} + +/// `ORIGIN` and `GASPRICE` in the init code are the transaction's own: the relayer, and the gas +/// price the relayer pays — not the signer, and not the price the deployment was signed at. +#[test] +fn test_origin_and_gasprice_follow_the_outer_transaction() { + let prefix = BytecodeBuilder::default() + .append(ORIGIN) + .push_number(0_u64) + .append(SSTORE) + .append(GASPRICE) + .push_number(1_u64) + .append(SSTORE); + let deployment = Deployment::new(running(prefix)); + for gas_limit in GAS_LIMITS { + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(priced_tx(&deployment, gas_limit, 7)) + .expect("a valid transaction"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let slot = |key: u64| { + outcome.state[&deployment.address] + .storage + .get(&U256::from(key)) + .map(|s| s.present_value) + }; + assert_eq!(slot(0), Some(U256::from_be_slice(RELAYER.as_slice())), "ORIGIN"); + assert_eq!(slot(1), Some(U256::from(7)), "GASPRICE"); + } +} + +/// The block's beneficiary is paid for the whole transaction, deployment included, whether the +/// deployment succeeds or fails, and the signer pays nothing. +fn assert_beneficiary_paid(init_code: Bytes) { + let deployment = Deployment::new(init_code); + let block = BlockEnv { beneficiary: BENEFICIARY, ..block() }; + let outcome = MegaEvm::new(context(system_db()).with_block(block)) + .execute_transaction(priced_tx(&deployment, GAS_LIMITS[0], 5)) + .expect("a valid transaction"); + assert!(outcome.result.is_success()); + let used = outcome.result.gas().tx_gas_used(); + assert_eq!( + outcome.state.get(&BENEFICIARY).map(|account| account.info.balance), + Some(U256::from(used) * U256::from(5)), + ); + assert_eq!( + outcome.state.get(&deployment.signer).map(|account| account.info.balance), + Some(U256::ZERO), + ); +} + +/// The beneficiary is paid for a deployment that succeeds. +#[test] +fn test_beneficiary_receives_fees_on_success() { + assert_beneficiary_paid(deploying(&runtime(1))); +} + +/// And for one that fails. +#[test] +fn test_beneficiary_receives_fees_on_execution_failure() { + assert_beneficiary_paid(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); +} + +/// A contract's `keylessDeploy` call is not dispatched: it runs the method body, which reverts +/// with `NotIntercepted()`, and nothing is deployed. +#[test] +fn test_keyless_deploy_not_intercepted_for_inner_calls() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(deploying(&runtime(1))); + let code = + calls_with(CALL, KEYLESS_DEPLOY_ADDRESS, &deployment.call_data(LARGE_OVERRIDE), 0); + let mut tx = call_tx(CONTRACT, [], U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(with_contract(code))) + .execute_transaction(tx) + .expect("a valid transaction"); + let output = outcome.result.output().cloned().unwrap_or_default(); + let (status, returned) = split_outcome(&output); + assert!(!status); + assert_eq!(returned, IKeylessDeploy::NotIntercepted::SELECTOR); + assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); + assert!(!outcome.state.contains_key(&deployment.address)); + } +} + +/// A `keylessDeploy` call made inside a keyless deployment is a contract's call like any other: +/// not dispatched. The contract's bytecode runs and reverts with `NotIntercepted()`, which the +/// outer constructor stores, and nothing of the inner deployment happens: its address holds no +/// code and its signer's nonce is unspent. The outer deployment deploys. +/// +/// A call answered without the bytecode — refused by an interceptor, or run as a deployment that +/// fails — could fail the same way, but not with the four bytes of `NotIntercepted()`. +/// +/// Rule [S15.3]. Expected values `independent`: the error's selector is computed here from its +/// signature, `NotIntercepted()`, not taken from the contract's binding. +#[test] +fn test_keyless_deploy_nested_inside_a_keyless_deployment_is_not_intercepted() { + let not_intercepted = &alloy_primitives::keccak256("NotIntercepted()")[..4]; + let selector = U256::from_be_slice(not_intercepted); + for gas_limit in GAS_LIMITS { + let inner = Deployment::new(deploying(&[0x00, 0x00])); + let data = inner.call_data(LARGE_OVERRIDE); + // The inner call's status in slot 0, the size of its revert data in slot 2, and the first + // four bytes of that data, as a number, in slot 1. + let prefix = BytecodeBuilder::default() + .mstore(0, &data) + .push_number(0_u64) + .push_number(0_u64) + .push_number(data.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(KEYLESS_DEPLOY_ADDRESS) + .append(GAS) + .append(CALL) + .push_number(0_u64) + .append(SSTORE) + .append(RETURNDATASIZE) + .push_number(2_u64) + .append(SSTORE) + .append_many([RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY, PUSH0, MLOAD]) + .push_number(224_u64) + .append(SHR) + .push_number(1_u64) + .append(SSTORE); + let outer = Deployment::new(running(prefix)); + let outcome = deploy(system_db(), &outer, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, outer.address); + let slot = |index: u64| { + outcome.state[&outer.address] + .storage + .get(&U256::from(index)) + .map(|slot| slot.present_value) + }; + assert_eq!(slot(0), Some(U256::ZERO), "the inner call failed"); + assert_eq!(slot(2), Some(U256::from(4)), "with four bytes of revert data"); + assert_eq!(slot(1), Some(selector), "which are NotIntercepted(): the bytecode ran"); + assert!(code_hash(&outcome, inner.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + assert_eq!(nonce(&outcome, inner.signer), 0); + } +} + +/// A constructor's storage writes are priced by the SALT environment the transaction runs in: a +/// crowded bucket at the deploy address makes the deposited code cost more state gas, and the +/// creation's `gasUsed` grows by exactly that. +#[test] +fn test_a_deployment_is_priced_by_the_transactions_salt_env() { + let deployment = Deployment::new(deploying(&runtime(5))); + let deposit = satin_gas_params().code_deposit_state_gas(5); + for gas_limit in GAS_LIMITS { + let minimal = salt_run(system_db(), TestExternalEnvs::new(), &deployment, gas_limit); + let envs = crowded(TestExternalEnvs::new(), deployment.address, 3); + let crowded_run = salt_run(system_db(), envs, &deployment, gas_limit); + assert_eq!( + returned(&crowded_run).gasUsed - returned(&minimal).gasUsed, + 2 * deposit, + "at {gas_limit}", + ); + } +} + +/// A constructor that sends an Oracle hint reaches the node's oracle service: the creation runs +/// in the transaction's own environment. +#[test] +fn test_a_constructor_reaches_the_oracle_service() { + for gas_limit in GAS_LIMITS { + let topic = B256::repeat_byte(0x11); + let hint = Bytes::from_static(b"a hint from a constructor"); + let data: Bytes = IOracle::sendHintCall { topic, data: hint.clone() }.abi_encode().into(); + let prefix = BytecodeBuilder::default() + .mstore(0, &data) + .push_number(0_u64) + .push_number(0_u64) + .push_number(data.len() as u64) + .push_number(0_u64) + .push_number(0_u64) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append(GAS) + .append(CALL) + .append(POP); + let deployment = Deployment::new(running(prefix)); + let envs = TestExternalEnvs::::new(); + let outcome = salt_run(system_db(), envs.clone(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let hints = envs.recorded_hints(); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].from, deployment.address); + assert_eq!(hints[0].topic, topic); + assert_eq!(hints[0].data, hint); + } +} + +/// What a deployment writes is the transaction's usage, counted where it is written: the +/// signer's nonce, the created account, a slot the constructor fills, the code it deposits. +#[test] +fn test_a_deployment_is_counted_where_it_writes() { + let prefix = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)); + let deployment = Deployment::new(running(prefix)); + for gas_limit in GAS_LIMITS { + let outcome = deploy(system_db(), &deployment, gas_limit); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!(outcome.usage.write_records, 3, "at {gas_limit}"); + assert_eq!(outcome.usage.data_size - reference.usage.data_size, 3 * 40 + 1); + } +} + +/// A signer's first deployment pays for its account; a retry, from the account the first attempt +/// created, does not. +#[test] +fn test_a_retry_does_not_pay_for_the_signer_again() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let mut db = system_db(); + let first = run_nth( + db.clone(), + deployment.call_data(LARGE_OVERRIDE), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + 0, + ); + assert!(matches!(failure(&first), KeylessDeployError::ExecutionReverted { .. })); + db.commit(first.result_and_state.state.clone()); + let retry = run_nth( + db, + deployment.call_data(LARGE_OVERRIDE), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + 1, + ); + assert!(matches!(failure(&retry), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(first.gas.state - retry.gas.state, entry(GasId::new_account_state_gas())); + assert_eq!(retry.gas.state, 0); + } +} + +/// A transaction that fails with a database error inside a keyless deployment leaves nothing +/// behind for the next: the next transaction on the same EVM runs as if the first never had. +#[test] +fn test_a_failed_keyless_transaction_leaves_nothing_for_the_next() { + for gas_limit in GAS_LIMITS { + let failing = address!("0x0000000000000000000000000000000000fa11ed"); + let prefix = BytecodeBuilder::default() + .push_address(failing) + .append(revm::bytecode::opcode::BALANCE) + .append(POP); + let deployment = Deployment::new(running(prefix)); + let answer = BytecodeBuilder::default().return_with_data([0x2a]).build(); + let mut db = ErrorInjectingDatabase::new(system_db().account_code(HELPER, answer)); + db.fail_on_account = Some(failing); + let mut evm = MegaEvm::new(context(db)); + + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + assert!(evm.execute_transaction(tx).is_err(), "the deployment fails with the database"); + + let mut next = call_tx(HELPER, [], U256::ZERO); + next.0.base.gas_limit = gas_limit; + let outcome = evm.execute_transaction(next).expect("the next transaction is valid"); + assert_eq!(outcome.result.output().cloned(), Some(Bytes::from_static(&[0x2a]))); + assert_eq!(outcome.usage.write_records, 0, "no record of the deployment is left over"); + } +} + +/* ---------- EIP-7708 transfer logs ---------- */ + +/// Counts the logs an inspector is told of. +#[derive(Default)] +struct LogCounter(usize); + +impl revm::Inspector, revm::interpreter::interpreter::EthInterpreter> + for LogCounter +{ + fn log(&mut self, _: &mut MegaContext, _: alloy_primitives::Log) { + self.0 += 1; + } +} + +/// A deployment carrying value moves it from the signer to the created account at the creation's +/// start, and revm journals the EIP-7708 transfer log of the move, which the receipt carries and +/// an inspector is told of once. The `keylessDeploy` call itself carries none. The log is data +/// size and nothing else: next to the same deployment without value, each against a transaction +/// carrying its calldata and nothing else, it counts 160 bytes more and the same records, history +/// gas and history bytes. +#[test] +fn test_a_deployment_carrying_value_logs_the_move() { + let with_value = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); + let without = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let moved = deploy(db_for(&with_value, U256::from(10_000)), &with_value, gas_limit); + assert_eq!(returned(&moved).deployedAddress, with_value.address); + let transfer = mega_evm::test_utils::transfer_log( + with_value.signer, + with_value.address, + U256::from(7_777), + ); + assert_eq!(moved.result.logs(), [transfer], "at {gas_limit}"); + + let still = deploy(db_for(&without, U256::ZERO), &without, gas_limit); + assert!(still.result.logs().is_empty()); + let beyond_reference = |outcome: &MegaTransactionOutcome, deployment: &Deployment| { + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + ( + outcome.usage.data_size - reference.usage.data_size, + outcome.usage.write_records, + beyond(outcome, &reference)[3..].to_vec(), + ) + }; + let (moved_bytes, moved_records, moved_history) = beyond_reference(&moved, &with_value); + let (still_bytes, still_records, still_history) = beyond_reference(&still, &without); + assert_eq!(moved_bytes, still_bytes + 160, "the transfer log's bytes, at {gas_limit}"); + assert_eq!((moved_records, moved_history), (still_records, still_history)); + + let mut evm = MegaEvm::new(context(db_for(&with_value, U256::from(10_000)))) + .with_inspector(LogCounter::default()); + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, with_value.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let inspected = evm.execute_transaction(tx).expect("the transaction is valid"); + assert_eq!(inspected.result, moved.result, "inspected as plain"); + assert_eq!(evm.inspector().0, 1, "the inspector is told of the log once"); + } +} + +/// The transfer log is counted with the creation's start, before revm builds the creation and +/// moves the value: a creation whose budget holds its two records and not the log is stopped at +/// its start, alone, with the value unmoved and no log journaled — the debug build's check of +/// every frame start holds it to exactly that. The same deployment without value deploys under +/// the same limit. +#[test] +fn test_a_creation_is_stopped_on_its_transfer_log_before_the_value_moves() { + let with_value = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); + let without = Deployment::new(deploying(&runtime(1))); + // The creation gets 98% of what the call leaves: 235 bytes, room for its records' 80 and + // its byte of code, not for the log's 160 on top of the records. + let limits = |deployment: &Deployment, gas_limit| { + let body = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit).usage.data_size; + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 240) + }; + for gas_limit in GAS_LIMITS { + let stopped = run_with( + db_for(&with_value, U256::from(10_000)), + with_value.call_data(LARGE_OVERRIDE), + gas_limit, + limits(&with_value, gas_limit), + ); + let KeylessDeployError::ExecutionReverted { output, .. } = failure(&stopped) else { + panic!("the creation was not stopped: {:?}", stopped.result); + }; + let stop = mega_evm::MegaLimitExceeded::abi_decode(&output).expect("a limit stop"); + assert_eq!(stop.kind, mega_evm::LimitKind::DataSize.as_u8(), "at {gas_limit}"); + assert!(stopped.result.logs().is_empty(), "no log is journaled"); + let balance = |address| stopped.state.get(&address).map(|account| account.info.balance); + assert_eq!(balance(with_value.signer), Some(U256::from(10_000)), "the value is unmoved"); + assert!(balance(with_value.address).is_none_or(|balance| balance.is_zero())); + assert_eq!(nonce(&stopped, with_value.signer), 1, "a stopped creation spends the nonce"); + + let deployed = run_with( + db_for(&without, U256::ZERO), + without.call_data(LARGE_OVERRIDE), + gas_limit, + limits(&without, gas_limit), + ); + assert_eq!(returned(&deployed).deployedAddress, without.address, "at {gas_limit}"); + } +} diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs new file mode 100644 index 000000000..f6afb2d1f --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -0,0 +1,686 @@ +//! A keyless deployment under gas detention. +//! +//! The `keylessDeploy` call is the transaction's own frame and runs no code: it charges its own +//! work — the overhead, then the `CREATE` opcode's regular gas — on gas held to what the compute +//! limit leaves it, and its creation is an ordinary frame below it. So a deployment is detained +//! as any transaction is: a read of volatile data anywhere in it caps what it may still compute, +//! its charges count as compute, and a crossing stops the frame that makes it — the call, which +//! takes the deployment back whole, or the creation, whose stop the call answers as any failed +//! creation's — and the control contracts and the Oracle answer its constructor as they answer +//! any frame. +//! +//! Every case runs below the execution cap and above it ([`GAS_LIMITS`]). + +use alloy_primitives::TxKind; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + alloy_op_evm::OpTx, + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, + decode_volatile_data_access_disabled, + system::{ + keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, IMegaAccessControl, IMegaLimitControl, IOracle, + ACCESS_CONTROL_ADDRESS, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS, + }, + test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder}, + ExternalEnvTypes, LimitCheck, LimitKind, MegaLimitExceeded, MegaTransaction, + VolatileDataAccess, +}; +use revm::{ + bytecode::opcode::{ + BALANCE, CALL, COINBASE, DUP1, GAS, JUMPDEST, JUMPI, MLOAD, POP, PUSH0, SSTORE, STATICCALL, + STOP, SUB, SWAP1, TIMESTAMP, + }, + context::{BlockEnv, TxEnv}, + interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, Interpreter}, + primitives::KECCAK_EMPTY, + Inspector, +}; + +use super::*; +use crate::common::{context, keyless_tx, AnswerAndResume, Run, CALLER as RELAYER}; + +/// The block beneficiary of the cases where nobody in the transaction is the beneficiary. +const BENEFICIARY: Address = address!("0x0000000000000000000000000000000000beef02"); + +/// The cap a read of the block environment sets, by default. +const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; + +/// The default runtime limits, with the block-environment cap at `cap`. +fn capped(cap: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap) +} + +/// A Satin context over `db`, in a block whose beneficiary is `beneficiary`, under `limits`. +fn context_in( + db: MemoryDatabase, + beneficiary: Address, + limits: EvmTxRuntimeLimits, +) -> MegaContext { + context(db).with_block(BlockEnv { beneficiary, ..block() }).with_tx_runtime_limits(limits) +} + +/// Runs `tx` in `ctx`, through an inspector when `inspected`. +fn run_tx( + ctx: MegaContext, + tx: MegaTransaction, + inspected: bool, +) -> Run { + let mut evm = MegaEvm::new(ctx); + if inspected { + let mut evm = evm.with_inspector(revm::inspector::NoOpInspector); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let detention = evm.ctx().detention(); + return Run { outcome, limit: detention.compute_limit(), accessed: detention.accessed() }; + } + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let detention = evm.ctx().detention(); + Run { outcome, limit: detention.compute_limit(), accessed: detention.accessed() } +} + +/// Runs the `keylessDeploy` transaction `data` from the relayer over `db` at `gas_limit`, in a +/// block whose beneficiary is `beneficiary`, under the default limits with the block-environment +/// cap at `cap`. +fn run_in(db: MemoryDatabase, beneficiary: Address, data: Bytes, gas_limit: u64, cap: u64) -> Run { + run_tx(context_in(db, beneficiary, capped(cap)), keyless_tx(data, gas_limit), false) +} + +/// Runs a `keylessDeploy` of `deployment` at `gas_limit` under `limits`, plain and inspected, and +/// asserts the two alike: the inspected path settles the deployment as the plain one does. +fn run_both(deployment: &Deployment, gas_limit: u64, limits: EvmTxRuntimeLimits) -> Run { + let run = |inspected| { + let ctx = context_in(db_for(deployment, U256::ZERO), BENEFICIARY, limits); + run_tx(ctx, keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit), inspected) + }; + let (plain, inspected) = (run(false), run(true)); + assert_eq!(inspected.outcome.result, plain.outcome.result, "at {gas_limit}"); + assert_eq!(inspected.outcome.gas, plain.outcome.gas, "at {gas_limit}"); + assert_eq!((inspected.limit, inspected.accessed), (plain.limit, plain.accessed)); + plain +} + +/// Runs `init_code` as a creation transaction from the relayer at `gas_limit` under `limits`: the +/// same constructor run by the transaction's own frame, with no `keylessDeploy` call above it. +fn run_as_creation(init_code: Bytes, gas_limit: u64, limits: EvmTxRuntimeLimits) -> Run { + let tx = OpTx(op_transaction(TxEnv { + caller: RELAYER, + kind: TxKind::Create, + data: init_code, + gas_limit, + ..Default::default() + })); + run_tx(context_in(system_db(), BENEFICIARY, limits), tx, false) +} + +/// Asserts `run` of `deployment` at `gas_limit` was stopped by gas detention, having computed up +/// to the charge that crossed its limit, `left` short of it, past its intrinsic gas, and kept +/// nothing of the deployment. +fn assert_stopped(run: &Run, deployment: &Deployment, gas_limit: u64, left: u64) { + let limit = run.limit.expect("a read set a limit"); + let ExecutionResult::Revert { output, .. } = &run.outcome.result else { + panic!("expected the detention stop, got {:?}", run.outcome.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(output).expect("the revert data is a limit stop"), + MegaLimitExceeded { kind: LimitKind::ComputeGas.as_u8(), limit }, + ); + let used = limit - left; + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used, + frame_local: false + }), + ); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!( + run.outcome.gas.regular, + reference.gas.regular + used, + "the transaction computed up to the charge that crossed its limit, at {gas_limit}", + ); + assert_eq!(run.outcome.gas.state, 0, "a stop keeps no state"); + assert_eq!(nonce(&run.outcome, deployment.signer), 0, "the signer's nonce is taken back"); + assert!(code_hash(&run.outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); +} + +/// Appends `rounds` rounds of a counting loop, twenty-six gas a round, to `code`, which starts +/// the init code. +fn burn(code: BytecodeBuilder, rounds: u16) -> BytecodeBuilder { + let code = code.push_number(rounds); + let dest = u16::try_from(code.len()).expect("a short prefix"); + code.append(JUMPDEST) + .push_number(1_u8) + .append_many([SWAP1, SUB, DUP1]) + .push_number(dest) + .append_many([JUMPI, POP]) +} + +/// Init code that runs `first` — a read, or a same-priced opcode that reads nothing — then +/// `rounds` rounds of [`burn`], and deploys a one-byte runtime. +pub(super) fn reads_then_burns(first: u8, rounds: u16) -> Bytes { + let prefix = burn(BytecodeBuilder::default().append_many([first, POP]), rounds); + constructor(&prefix.build_vec(), &runtime(1)) +} + +/// Appends a `STATICCALL` of `to` with `data`, all gas forwarded, keeping 32 bytes of what it +/// returns at `0x100`, and dropping its status. +fn static_calls(code: BytecodeBuilder, to: Address, data: &[u8]) -> BytecodeBuilder { + code.mstore(0x200, data) + .push_number(32_u8) + .push_number(0x100_u16) + .push_number(u8::try_from(data.len()).expect("short calldata")) + .push_number(0x200_u16) + .push_address(to) + .append_many([GAS, STATICCALL, POP]) +} + +/// The error a deployment whose creation reverted reports, when it is a refused read of volatile +/// data: the kind it names. +fn refused_read(outcome: &MegaTransactionOutcome) -> VolatileDataAccess { + let KeylessDeployError::ExecutionReverted { output, .. } = failure(outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + decode_volatile_data_access_disabled(&output).expect("a refused read") +} + +/// Asserts `run` of `deployment` at `gas_limit` had its creation stopped by gas detention, having +/// computed up to the charge that crossed its limit, `left` short of it, past its intrinsic gas: +/// the call answers the creation's stop as `ExecutionReverted`, charging nothing more on its +/// resume, so the transaction succeeds within the limit, deploys nothing, and keeps the signer's +/// nonce the creation's start spent. +fn assert_creation_stopped(run: &Run, deployment: &Deployment, gas_limit: u64, left: u64) { + let limit = run.limit.expect("a read set a limit"); + let KeylessDeployError::ExecutionReverted { output, .. } = failure(&run.outcome) else { + panic!("the creation did not revert: {:?}", run.outcome.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(&output).expect("the creation's revert data is a limit stop"), + MegaLimitExceeded { kind: LimitKind::ComputeGas.as_u8(), limit }, + ); + assert_eq!(run.outcome.limit_exceeded, None, "the call caught the stop"); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!( + run.outcome.gas.regular, + reference.gas.regular + limit - left, + "the transaction computed up to the charge that crossed its limit, at {gas_limit}", + ); + assert_eq!(nonce(&run.outcome, deployment.signer), 1, "the creation's start spent the nonce"); + assert!(code_hash(&run.outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); +} + +/* ---------- the call's own work ---------- */ + +/// A signer that is the block beneficiary: the call reads the beneficiary's account for its +/// rules, through the journal, and the creation runs for that account, so the deployment is +/// detained from the read, at the call's compute then — the overhead — as a sender that is the +/// beneficiary is from its start. Under the spec's cap it deploys as without the read. Under a cap +/// its `CREATE` opcode's regular gas crosses, it stops at that charge, before the creation starts, +/// the call's first charge after the read: the whole cap is left. +/// A signer that is not the beneficiary is not detained. +#[test] +fn test_a_signer_that_is_the_beneficiary_detains_its_deployment() { + let init_code = deploying(&runtime(1)); + let deployment = Deployment::new(init_code.clone()); + let data = deployment.call_data(LARGE_OVERRIDE); + for gas_limit in GAS_LIMITS { + let plain = + run_in(db_for(&deployment, U256::ZERO), BENEFICIARY, data.clone(), gas_limit, 1); + assert_eq!(returned(&plain.outcome).deployedAddress, deployment.address); + assert_eq!((plain.limit, plain.accessed), (None, VolatileDataAccess::empty())); + + let signer = deployment.signer; + let detained = + run_in(db_for(&deployment, U256::ZERO), signer, data.clone(), gas_limit, CAP); + assert_eq!(detained.accessed, VolatileDataAccess::BENEFICIARY_BALANCE); + assert_eq!(detained.limit, Some(KEYLESS_DEPLOY_OVERHEAD_GAS + CAP), "read at the overhead"); + assert_eq!(detained.outcome.result, plain.outcome.result, "at {gas_limit}"); + assert_eq!(detained.outcome.gas, plain.outcome.gas, "at {gas_limit}"); + + let cap = create_regular(init_code.len()) - 1; + let stopped = run_in(db_for(&deployment, U256::ZERO), signer, data.clone(), gas_limit, cap); + assert_eq!(stopped.limit, Some(KEYLESS_DEPLOY_OVERHEAD_GAS + cap)); + assert_stopped(&stopped, &deployment, gas_limit, cap); + } +} + +/* ---------- the creation ---------- */ + +/// A constructor that reads volatile data is held to the cap as any frame is. The limit is the +/// transaction's compute at the read plus the cap, and that compute holds the call's own work: +/// the limit is the same constructor's as a creation transaction's, plus the overhead and the +/// `CREATE` opcode's regular gas. Within the cap the deployment is the same as its twin's, whose +/// constructor reads nothing in the read's place (`PUSH0`, the same two gas), on every ledger. +/// Past it, the constructor stops at the first charge of its loop past the limit: the call answers +/// the creation's stop as `ExecutionReverted`, and nothing is deployed. Plain and inspected, below +/// and above the execution cap. +#[test] +fn test_a_constructor_that_reads_volatile_data_is_held_to_the_cap() { + let init_code = reads_then_burns(TIMESTAMP, 1_000); + let (reads, twin) = + (Deployment::new(init_code.clone()), Deployment::new(reads_then_burns(PUSH0, 1_000))); + let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(init_code.len()); + for gas_limit in GAS_LIMITS { + let deployed = run_both(&reads, gas_limit, capped(CAP)); + let undetained = run_both(&twin, gas_limit, capped(CAP)); + assert_eq!(returned(&deployed.outcome).deployedAddress, reads.address); + assert_eq!(deployed.outcome.gas, undetained.outcome.gas, "as without the read"); + assert_eq!(deployed.accessed, VolatileDataAccess::TIMESTAMP); + let as_creation = run_as_creation(init_code.clone(), gas_limit, capped(CAP)); + assert_eq!(deployed.limit, Some(as_creation.limit.unwrap() + charges), "at {gas_limit}"); + assert_eq!(deployed.limit, Some(charges + 2 + CAP), "the read's own two gas"); + + let stopped = run_both(&reads, gas_limit, capped(1_000)); + assert_eq!(stopped.limit, Some(charges + 2 + 1_000)); + // The read's `POP`, then the loop: the push of its counter, and 26 gas a round — its + // `JUMPDEST`, `PUSH1`, `SWAP1`, `SUB`, `DUP1`, the push of its start and `JUMPI`. + let left = crossing_left(1_000, &[2, 3], &[1, 3, 3, 3, 3, 3, 10]); + assert_creation_stopped(&stopped, &reads, gas_limit, left); + let twin_deploys = run_both(&twin, gas_limit, capped(1_000)); + assert_eq!(returned(&twin_deploys.outcome).deployedAddress, twin.address); + } +} + +/// A sender that is the beneficiary is detained from its start, before the call charges anything: +/// the call's work and the constructor's together are held to the cap. A cap that pays both +/// deploys as without the read; one gas less, and the deployment's last regular charge crosses: +/// the hash of its one-byte runtime, one word at six gas, which leaves five. The charge is the +/// creation's, whose stop the call answers. +#[test] +fn test_a_sender_that_is_the_beneficiary_holds_the_whole_deployment_to_the_cap() { + let init_code = reads_then_burns(PUSH0, 100); + let deployment = Deployment::new(init_code.clone()); + let data = deployment.call_data(LARGE_OVERRIDE); + for gas_limit in GAS_LIMITS { + let plain = + run_in(db_for(&deployment, U256::ZERO), BENEFICIARY, data.clone(), gas_limit, 1); + let intrinsic = reference(data.clone(), gas_limit).gas.regular; + let compute = plain.outcome.gas.regular - intrinsic; + assert!(compute > KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(init_code.len())); + + let fits = + run_in(db_for(&deployment, U256::ZERO), RELAYER, data.clone(), gas_limit, compute); + assert_eq!(fits.limit, Some(compute), "detained from its start"); + assert_eq!(fits.outcome.result, plain.outcome.result, "at {gas_limit}"); + assert_eq!(fits.outcome.gas, plain.outcome.gas, "at {gas_limit}"); + let short = + run_in(db_for(&deployment, U256::ZERO), RELAYER, data.clone(), gas_limit, compute - 1); + assert_creation_stopped(&short, &deployment, gas_limit, 6 - 1); + } +} + +/// A sender that is the beneficiary, under a cap below the overhead: the call is held to the cap +/// before it charges anything, so the overhead is the charge that crosses, and the transaction +/// stops having computed nothing. A call held only once its charges were paid would pay the +/// overhead and the `CREATE` opcode's regular gas in full, past the cap, and stop at its +/// creation's first charge instead. Plain and inspected. +#[test] +fn test_a_sender_that_is_the_beneficiary_is_held_before_the_overhead() { + let deployment = Deployment::new(deploying(&runtime(1))); + let data = deployment.call_data(LARGE_OVERRIDE); + let cap = KEYLESS_DEPLOY_OVERHEAD_GAS - 1; + for gas_limit in GAS_LIMITS { + for inspected in [false, true] { + let ctx = context_in(db_for(&deployment, U256::ZERO), RELAYER, capped(cap)); + let run = run_tx(ctx, keyless_tx(data.clone(), gas_limit), inspected); + assert_eq!(run.limit, Some(cap), "detained from its start, at no compute"); + assert_stopped(&run, &deployment, gas_limit, cap); + } + } +} + +/* ---------- the control contracts ---------- */ + +/// A deployment in a subtree where volatile-data access is switched off keeps the refusal. With +/// the switch off from the transaction's own frame — the keyless call — or from the creation, the +/// constructor's `TIMESTAMP` is refused: the creation reverts with +/// `VolatileDataAccessDisabled`, which the call reports as `ExecutionReverted`, having read and +/// capped nothing, and the signer's nonce is spent as by any failed deployment. Off only from +/// below the creation, the constructor reads. +#[test] +fn test_a_deployment_in_a_subtree_with_volatile_access_off_is_refused_its_reads() { + let deployment = Deployment::new(reads_then_burns(TIMESTAMP, 1)); + for gas_limit in GAS_LIMITS { + for from in [0, 1, 2] { + let ctx = context_in(db_for(&deployment, U256::ZERO), BENEFICIARY, capped(CAP)) + .with_volatile_access_disabled_from(from); + let tx = keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let run = run_tx(ctx, tx, false); + if from == 2 { + assert_eq!(returned(&run.outcome).deployedAddress, deployment.address); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); + continue; + } + assert_eq!( + refused_read(&run.outcome), + VolatileDataAccess::TIMESTAMP, + "off from {from}" + ); + assert_eq!((run.limit, run.accessed), (None, VolatileDataAccess::empty())); + assert_eq!(nonce(&run.outcome, deployment.signer), 1); + } + } +} + +/// A constructor that switches volatile-data access off for itself is refused its own read after +/// it, as any frame is. +#[test] +fn test_a_constructor_that_switches_volatile_access_off_is_refused_its_own_read() { + let disable = IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; + let prefix = BytecodeBuilder::default() + .mstore(0x200, disable) + .append_many([PUSH0, PUSH0]) + .push_number(4_u8) + .push_number(0x200_u16) + .append(PUSH0) + .push_address(ACCESS_CONTROL_ADDRESS) + .append_many([GAS, CALL, POP, TIMESTAMP, POP]); + let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); + for gas_limit in GAS_LIMITS { + let run = run_both(&deployment, gas_limit, capped(CAP)); + assert_eq!(refused_read(&run.outcome), VolatileDataAccess::TIMESTAMP); + assert_eq!((run.limit, run.accessed), (None, VolatileDataAccess::empty())); + } +} + +/// `remainingComputeGas()` called from a constructor answers what the constructor could still +/// spend: exactly the spendable regular gas it resumes with. Undetained, that is its own gas. A +/// constructor that read the block environment hears what the cap leaves it after the read. From +/// a sender that is the beneficiary, detained from its start, it hears the cap less all the +/// transaction computed — the call's overhead and `CREATE` opcode's regular gas included. +#[test] +fn test_remaining_compute_gas_answers_a_constructor_its_allowance() { + let query = IMegaLimitControl::remainingComputeGasCall::SELECTOR; + let init_code = |first: u8| { + let prefix = static_calls( + BytecodeBuilder::default().append_many([first, POP]), + LIMIT_CONTROL_ADDRESS, + &query, + ); + constructor(&prefix.build_vec(), &runtime(1)) + }; + for gas_limit in GAS_LIMITS { + for (first, sender_is_beneficiary) in [(PUSH0, false), (TIMESTAMP, false), (PUSH0, true)] { + let init_code = init_code(first); + let deployment = Deployment::new(init_code.clone()); + let beneficiary = if sender_is_beneficiary { RELAYER } else { BENEFICIARY }; + let ctx = context_in(db_for(&deployment, U256::ZERO), beneficiary, capped(CAP)); + let mut evm = MegaEvm::new(ctx).with_inspector(AnswerAndResume::default()); + let outcome = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("the transaction is valid"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let pairs = evm.inspector().pairs.clone(); + let [(answer, resumes)] = pairs[..] else { panic!("one answer: {pairs:?}") }; + assert_eq!(answer, resumes, "{first} {sender_is_beneficiary} at {gas_limit}"); + let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(init_code.len()); + match (first, sender_is_beneficiary) { + (TIMESTAMP, _) => assert!(answer < CAP && answer > CAP - 5_000, "{answer}"), + (_, true) => { + assert!(answer < CAP - charges && answer > CAP - charges - 5_000, "{answer}") + } + _ => assert!(answer > CAP, "its own gas: {answer}"), + } + } + } +} + +/// Records every answer `remainingComputeGas()` gives, next to the regular gas its caller has +/// spent in all when it resumes. +#[derive(Debug, Default)] +struct AnswerAndSpent { + pending: Option, + pairs: Vec<(u64, u64)>, +} + +impl Inspector for AnswerAndSpent { + fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + if let Some(answer) = self.pending.take() { + self.pairs.push((answer, interp.gas.total_gas_spent())); + } + } + + fn call_end(&mut self, _context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + if inputs.target_address == LIMIT_CONTROL_ADDRESS && outcome.result.is_ok() { + self.pending = Some(U256::from_be_slice(&outcome.result.output).to::()); + } + } +} + +/// From a sender that is the beneficiary, detained from its start, `remainingComputeGas()` read +/// from the constructor answers exactly the cap less every regular charge the transaction has made +/// by then: the call's overhead, the regular gas of the `CREATE` opcode that started the +/// constructor, and what the constructor itself has spent. The deployment's charges count against +/// the cap the transaction's detention holds, as an ordinary creation transaction's frames do. +#[test] +fn test_remaining_compute_gas_in_a_constructor_is_the_cap_less_the_deployments_charges() { + let query = IMegaLimitControl::remainingComputeGasCall::SELECTOR; + let prefix = static_calls(BytecodeBuilder::default(), LIMIT_CONTROL_ADDRESS, &query); + let init_code = constructor(&prefix.build_vec(), &runtime(1)); + let deployment = Deployment::new(init_code.clone()); + let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(init_code.len()); + for gas_limit in GAS_LIMITS { + let ctx = context_in(db_for(&deployment, U256::ZERO), RELAYER, capped(CAP)); + let mut evm = MegaEvm::new(ctx).with_inspector(AnswerAndSpent::default()); + let outcome = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("the transaction is valid"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let pairs = evm.inspector().pairs.clone(); + let [(answer, spent)] = pairs[..] else { panic!("one answer: {pairs:?}") }; + assert!(spent > 0, "the constructor has spent gas by then"); + assert_eq!(answer, CAP - charges - spent, "at {gas_limit}"); + } +} + +/* ---------- the Oracle ---------- */ + +/// A context over `db` whose oracle service answers `envs`, under the default limits with the +/// Oracle's cap at `oracle_cap`. +fn oracle_context( + db: MemoryDatabase, + envs: TestExternalEnvs, + oracle_cap: u64, +) -> MegaContext> { + MegaContext::<_, TestExternalEnvs>::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, + ) + .with_block(BlockEnv { beneficiary: BENEFICIARY, ..block() }) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits( + EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(oracle_cap), + ) +} + +/// Init code that reads the Oracle's slot 0 through `getSlot`, keeps what it read in its own slot +/// 0, runs `rounds` rounds of [`burn`] and deploys a one-byte runtime. +fn reads_the_oracle(rounds: u16) -> Bytes { + let get_slot = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let prefix = static_calls(BytecodeBuilder::default(), ORACLE_CONTRACT_ADDRESS, &get_slot) + .push_number(0x100_u16) + .append_many([MLOAD, PUSH0, SSTORE]); + constructor(&burn(prefix, rounds).build_vec(), &runtime(1)) +} + +/// A constructor reads the Oracle's storage as any frame does: it gets the service's value when +/// the service answers and the chain's otherwise, at the same price either way, and the read is +/// volatile, under the Oracle's cap. Past a cap of 1,000, the constructor stops at its write of +/// what it read — a fresh, cold slot, whose dynamic charge of 22,000 no such cap pays — after the +/// Oracle's return and the constructor's `POP`, push, `MLOAD`, `PUSH0` and `SSTORE`'s static gas, +/// and the call answers the creation's stop, deploying nothing. +#[test] +fn test_a_constructor_reads_the_oracle_as_any_frame_does() { + let deployment = Deployment::new(reads_the_oracle(1_000)); + let db = || { + db_for(&deployment, U256::ZERO).account_storage( + ORACLE_CONTRACT_ADDRESS, + U256::ZERO, + U256::from(5), + ) + }; + let service = TestExternalEnvs::new().with_oracle_storage(U256::ZERO, U256::from(7)); + let stored = |run: &Run| { + run.outcome.state[&deployment.address] + .storage + .get(&U256::ZERO) + .map(|slot| slot.present_value) + }; + for gas_limit in GAS_LIMITS { + let tx = || keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let answered = + run_tx(oracle_context(db(), service.clone(), ORACLE_ACCESS_COMPUTE_GAS), tx(), false); + let from_state = run_tx( + oracle_context(db(), TestExternalEnvs::new(), ORACLE_ACCESS_COMPUTE_GAS), + tx(), + false, + ); + assert_eq!(returned(&answered.outcome).deployedAddress, deployment.address); + assert_eq!( + (stored(&answered), stored(&from_state)), + (Some(U256::from(7)), Some(U256::from(5))) + ); + assert_eq!(answered.outcome.gas, from_state.outcome.gas, "priced alike, at {gas_limit}"); + assert_eq!(answered.accessed, VolatileDataAccess::ORACLE); + assert!(answered.limit.is_some()); + + // The Oracle's own instructions after its load, measured on its frame in a run the cap + // does not stop. + let mut evm = + MegaEvm::new(oracle_context(db(), service.clone(), ORACLE_ACCESS_COMPUTE_GAS)) + .with_inspector(OracleTail::default()); + evm.execute_transaction(tx()).expect("the transaction is valid"); + let tail = evm.inspector().tail(); + let left = crossing_left(1_000, &[tail, 2, 3, 3, 2, 100, 22_000], &[]); + assert!(left > 0, "the write is the charge that crosses: {left}"); + + let stopped = run_tx(oracle_context(db(), service.clone(), 1_000), tx(), true); + assert_creation_stopped(&stopped, &deployment, gas_limit, left); + assert_eq!(stopped.accessed, VolatileDataAccess::ORACLE); + } +} + +/// What `allowance` has left at the first charge it cannot pay, of `charges` then `round` over +/// and over: what a frame the limit left `allowance` at the read has when it crosses the limit. +pub(super) fn crossing_left(mut allowance: u64, charges: &[u64], round: &[u64]) -> u64 { + for charge in charges.iter().chain(round.iter().cycle()) { + if *charge > allowance { + return allowance; + } + allowance -= charge; + } + panic!("the charges end within the allowance") +} + +/// Measures what the Oracle's frame spends after its storage load: what it has at its next +/// instruction, less what it returns with. +#[derive(Default)] +struct OracleTail { + loading: bool, + after_load: Option, + returned: Option, +} + +impl OracleTail { + fn tail(&self) -> u64 { + self.after_load.expect("the Oracle loaded") - self.returned.expect("the Oracle returned") + } +} + +impl Inspector, EthInterpreter> + for OracleTail +{ + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + use revm::interpreter::interpreter_types::Jumps; + if interp.input.target_address != ORACLE_CONTRACT_ADDRESS { + return; + } + if self.loading && self.after_load.is_none() { + self.after_load = Some(interp.gas.remaining()); + } + self.loading = interp.bytecode.opcode() == revm::bytecode::opcode::SLOAD; + } + + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == ORACLE_CONTRACT_ADDRESS { + self.returned = Some(outcome.result.gas.remaining()); + } + } +} + +/* ---------- what a deployment reports it read ---------- */ + +/// The volatile data a constructor reads is the transaction's: the block environment, the +/// coinbase — which is not a read of the beneficiary's account — the beneficiary's balance, and +/// the Oracle's storage, each recorded as the kind it is, and each capping the transaction. +#[test] +fn test_a_constructors_reads_are_the_transactions() { + let balance_of_coinbase = BytecodeBuilder::default().append_many([COINBASE, BALANCE, POP]); + let cases = [ + (reads_then_burns(TIMESTAMP, 1), VolatileDataAccess::TIMESTAMP), + (reads_then_burns(COINBASE, 1), VolatileDataAccess::COINBASE), + ( + constructor(&balance_of_coinbase.build_vec(), &runtime(1)), + VolatileDataAccess::COINBASE | VolatileDataAccess::BENEFICIARY_BALANCE, + ), + (reads_the_oracle(1), VolatileDataAccess::ORACLE), + ]; + for (init_code, read) in cases { + let deployment = Deployment::new(init_code); + for gas_limit in GAS_LIMITS { + let run = run_both(&deployment, gas_limit, capped(CAP)); + assert_eq!(returned(&run.outcome).deployedAddress, deployment.address); + assert_eq!(run.accessed, read, "at {gas_limit}"); + assert!(run.limit.is_some(), "the read caps the transaction"); + } + } +} + +/// A deployment that fails still keeps the reads its creation made: a constructor that reads the +/// timestamp and deploys no code fails with `EmptyCodeDeployed`, and the read stands. +#[test] +fn test_a_failed_deployment_keeps_the_reads_its_creation_made() { + let deployment = + Deployment::new(BytecodeBuilder::default().append_many([TIMESTAMP, POP, STOP]).build()); + for gas_limit in GAS_LIMITS { + let run = run_both(&deployment, gas_limit, capped(CAP)); + assert!( + matches!(failure(&run.outcome), KeylessDeployError::EmptyCodeDeployed { .. }), + "at {gas_limit}" + ); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); + assert!(run.limit.is_some()); + } +} + +/// A deployment another limit stops still reports the reads its creation made, and the stop stays +/// that limit's: a constructor that reads the timestamp and fills a slot the data-size limit has no +/// room for is stopped on data size, not on compute, and the call answers that stop. +#[test] +fn test_a_deployment_another_limit_stops_keeps_the_reads_its_creation_made() { + let prefix = + BytecodeBuilder::default().append_many([TIMESTAMP, POP]).sstore(U256::ZERO, U256::ONE); + let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); + // The body, the creation's two start records and the slot's record, one byte short. + let body = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; + let limit = body + 3 * mega_evm::WRITE_RECORD_SIZE - 1; + for gas_limit in GAS_LIMITS { + let run = run_both(&deployment, gas_limit, capped(CAP).with_tx_data_size_limit(limit)); + let KeylessDeployError::ExecutionReverted { output, .. } = failure(&run.outcome) else { + panic!("expected the creation's data-size stop, got {:?}", run.outcome.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(&output).unwrap(), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + ); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); + assert!(run.limit.is_some()); + assert_eq!(nonce(&run.outcome, deployment.signer), 1, "the creation's start spent it"); + } +} diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs new file mode 100644 index 000000000..a0fff80aa --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -0,0 +1,1051 @@ +//! A differential record of keyless deployments: a fixed set of scenarios, each run without an +//! inspector, under one that records everything it is told, under one that also rewrites every +//! frame result into a success, and under one that answers every creation itself, and each +//! rendered as a canonical text record — the result and the state, the gas by ledger, the usage, +//! the stop, what gas detention made of the transaction, and every event the inspector saw with +//! the journal depth it saw it at. +//! +//! An in-tree insta snapshot pins one line per case: its name and the keccak256 digest of its +//! complete four-mode record, including line endings, plus the record's case, run, byte and line +//! counts. It compares at the spec's byte prices; the recorded-versus-plain assertions run at +//! every price. Review digest changes with the full dump: when `MEGA_KEYLESS_RECORD` names a +//! file, the record is written there, and two builds can be compared line by line. The test also +//! holds every scenario's recorded run to its plain one, on everything but the events. +//! +//! The scenarios: every rule a call can be refused by, and every charge it can run out of gas +//! on; a deployment from nonce 0 and from nonce 1, one that moves value, one by a delegated +//! signer, a constructor that reverts, halts, logs, writes, and destroys itself; the limits a +//! deployment crosses, from either nonce; gas detention holding the call and its creation; a +//! body over the limit, which validation rejects; a system call; and the calls that are not +//! dispatched. Each at a gas limit below +//! the execution cap and one above it, where it can run there. + +use std::fmt::Write as _; + +use alloy_primitives::{address, keccak256, Log}; +use mega_evm::{ + constants::{MAX_INITCODE_SIZE, TX_GAS_LIMIT_CAP}, + system::{ + keyless::{ + tests::{CREATE2_FACTORY_TX, NON_CONTRACT_CREATION_TX, POST_EIP155_CHAIN_1_TX}, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + MEGA_SYSTEM_ADDRESS, + }, + test_utils::BytecodeBuilder, + MegaTransaction, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLER, CREATE, GAS, INVALID, POP, PUSH0, REVERT, SELFDESTRUCT, STATICCALL, STOP, + TIMESTAMP, + }, + context::{BlockEnv, CfgEnv, ContextTr, JournalTr}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, + }, + state::{AccountInfo, Bytecode, EvmState}, + Database, InspectSystemCallEvm, Inspector, SystemCallEvm, +}; + +use super::{detention::reads_then_burns, *}; +use crate::common::{context, CALLER as RELAYER}; + +/// Where the record is written, when set. +const RECORD_PATH: &str = "MEGA_KEYLESS_RECORD"; + +/// Every scenario, in every mode: the recorded runs match the plain ones, the case digests are +/// snapshotted, and the full record is written where `MEGA_KEYLESS_RECORD` says. +#[test] +fn test_keyless_differential_record() { + let mut record = String::new(); + let mut cases = Vec::new(); + for scenario in scenarios() { + let start = record.len(); + let plain = scenario.run(Mode::Plain); + let recorded = scenario.run(Mode::Recorded); + assert_eq!( + recorded.outcome, plain.outcome, + "{}: an inspector that only records changes nothing", + scenario.name + ); + for mode in [Mode::Rewritten, Mode::Answered] { + let run = scenario.run(mode); + writeln!(record, "== {} [{mode:?}]\n{}{}", scenario.name, run.outcome, run.events) + .unwrap(); + } + writeln!(record, "== {} [Plain]\n{}", scenario.name, plain.outcome).unwrap(); + writeln!( + record, + "== {} [Recorded]\n{}{}", + scenario.name, recorded.outcome, recorded.events + ) + .unwrap(); + cases.push(format!( + "{} | keccak256={}", + scenario.name, + keccak256(&record.as_bytes()[start..]) + )); + } + if let Ok(path) = std::env::var(RECORD_PATH) { + std::fs::write(&path, &record).expect("the record is written"); + } + crate::assert_sorted_json_snapshot!(serde_json::json!({ + "summary": { + "cases": cases.len(), + "runs": cases.len() * 4, + "bytes": record.len(), + "lines": record.lines().count(), + }, + "cases": cases, + })); +} + +/* ---------- the scenarios ---------- */ + +/// One transaction to run. +#[derive(Clone)] +struct Scenario { + name: String, + db: MemoryDatabase, + from: Address, + to: Address, + data: Bytes, + value: U256, + gas_limit: u64, + limits: EvmTxRuntimeLimits, + beneficiary: Address, + eip3607_off: bool, + /// Run as a system call from the system address, which takes no gas limit or value. + system_call: bool, +} + +impl Scenario { + /// A `keylessDeploy` transaction carrying `data` over `db` at `gas_limit`, with no runtime + /// limit. + fn new(name: impl Into, db: MemoryDatabase, data: Bytes, gas_limit: u64) -> Self { + Self { + name: format!("{} @ {gas_limit}", name.into()), + db, + from: RELAYER, + to: KEYLESS_DEPLOY_ADDRESS, + data, + value: U256::ZERO, + gas_limit, + limits: EvmTxRuntimeLimits::no_limits(), + beneficiary: Address::ZERO, + eip3607_off: false, + system_call: false, + } + } + + /// A `keylessDeploy` of `deployment`, with the largest override. + fn deploying( + name: impl Into, + db: MemoryDatabase, + deployment: &Deployment, + gas_limit: u64, + ) -> Self { + Self::new(name, db, deployment.call_data(LARGE_OVERRIDE), gas_limit) + } + + fn limits(mut self, limits: EvmTxRuntimeLimits) -> Self { + self.limits = limits; + self + } + + fn beneficiary(mut self, beneficiary: Address) -> Self { + self.beneficiary = beneficiary; + self + } + + fn value(mut self, value: U256) -> Self { + self.value = value; + self + } + + fn from(mut self, from: Address) -> Self { + self.from = from; + self + } + + fn to(mut self, to: Address) -> Self { + self.to = to; + self + } + + fn eip3607_off(mut self) -> Self { + self.eip3607_off = true; + self + } + + fn system_call(mut self) -> Self { + self.system_call = true; + self + } + + fn context(&self) -> MegaContext { + let mut ctx = context(self.db.clone()); + if self.eip3607_off { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.disable_eip3607 = true; + ctx = ctx.with_cfg(cfg); + } + ctx.with_block(BlockEnv { beneficiary: self.beneficiary, ..block() }) + .with_tx_runtime_limits(self.limits) + } + + fn tx(&self) -> MegaTransaction { + let mut tx = call_tx(self.to, self.data.clone(), self.value); + tx.0.base.gas_limit = self.gas_limit; + tx.0.base.caller = self.from; + tx + } + + /// Runs the scenario in `mode`. + fn run(&self, mode: Mode) -> Run { + let evm = MegaEvm::new(self.context()); + let Some(recorder) = mode.recorder() else { + let mut evm = evm; + let outcome = if self.system_call { + let result = SystemCallEvm::system_call_with_caller( + &mut evm, + MEGA_SYSTEM_ADDRESS, + self.to, + self.data.clone(), + ); + render_system_call(result.map(|r| (r.result, r.state))) + } else { + render_outcome(evm.execute_transaction(self.tx())) + }; + let outcome = outcome + &render_detention(evm.ctx()); + return Run { outcome, events: String::new() }; + }; + let mut evm = evm.with_inspector(recorder); + let outcome = if self.system_call { + let result = InspectSystemCallEvm::inspect_system_call_with_caller( + &mut evm, + MEGA_SYSTEM_ADDRESS, + self.to, + self.data.clone(), + ); + render_system_call(result.map(|r| (r.result, r.state))) + } else { + render_outcome(evm.execute_transaction(self.tx())) + }; + let outcome = outcome + &render_detention(evm.ctx()); + let recorder = evm.inspector(); + let mut events = String::new(); + for line in recorder.lines.iter().chain(recorder.pending_steps().as_ref()) { + writeln!(events, " {line}").unwrap(); + } + Run { outcome, events } + } +} + +/// What a run rendered: everything but the events, and the events. +struct Run { + outcome: String, + events: String, +} + +/// How a scenario is run. +#[derive(Clone, Copy, Debug)] +enum Mode { + /// Without an inspector. + Plain, + /// Under an inspector that records everything it is told. + Recorded, + /// Under one that also rewrites every frame result into a success, reviving creations. + Rewritten, + /// Under one that answers every creation with a revert in its place. + Answered, +} + +impl Mode { + fn recorder(self) -> Option { + match self { + Self::Plain => None, + Self::Recorded => Some(Recorder::default()), + Self::Rewritten => Some(Recorder { rewrite: true, ..Default::default() }), + Self::Answered => Some(Recorder { answer_creations: true, ..Default::default() }), + } + } +} + +/// Init code that fills a fresh slot and deploys a one-byte runtime. +fn filling_a_slot() -> Bytes { + let prefix = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).build_vec(); + constructor(&prefix, &runtime(1)) +} + +/// The gas limit, below the execution cap, at which a call carrying `data` has `left` once it +/// paid its overhead. +fn leaving(data: &Bytes, left: u64) -> u64 { + reference(data.clone(), GAS_LIMITS[0]).result.gas().total_gas_spent() + + KEYLESS_DEPLOY_OVERHEAD_GAS + + left +} + +/// `db` with an EIP-7702 delegation to `delegate` on `signer`, at `nonce`. +fn delegated( + mut db: MemoryDatabase, + signer: Address, + delegate: Address, + nonce: u64, +) -> MemoryDatabase { + let delegation = Bytecode::new_eip7702(delegate); + db.insert_account_info( + signer, + AccountInfo { + nonce, + code_hash: delegation.hash_slow(), + code: Some(delegation), + ..Default::default() + }, + ); + db +} + +/// Every scenario the record holds. +fn scenarios() -> Vec { + let mut all = Vec::new(); + let small = Deployment::new(deploying(&runtime(1))); + let one_byte_init = deploying(&runtime(1)).len(); + + for gas_limit in GAS_LIMITS { + let at = |name: &str| name.to_string(); + let submit = |name: &str, db: MemoryDatabase, tx: &[u8], gas_limit_override: u64| { + Scenario::new( + name, + db, + keyless_deploy_call(tx, U256::from(gas_limit_override)), + gas_limit, + ) + }; + + /* The rules. */ + all.push( + Scenario::deploying(at("rule: value"), system_db(), &small, gas_limit).value(U256::ONE), + ); + all.push( + Scenario::new( + "rule: value, arguments that do not decode", + system_db(), + Bytes::from(IKeylessDeploy::keylessDeployCall::SELECTOR.to_vec()), + gas_limit, + ) + .value(U256::ONE), + ); + all.push(Scenario::new( + "rule: arguments that do not decode", + system_db(), + Bytes::from([&IKeylessDeploy::keylessDeployCall::SELECTOR[..], &[0xab; 7]].concat()), + gas_limit, + )); + all.push(submit( + "rule: malformed transaction", + system_db(), + &[0xde, 0xad, 0xbe, 0xef], + LARGE_OVERRIDE, + )); + let mut trailing = CREATE2_FACTORY_TX.to_vec(); + trailing.push(0); + all.push(submit("rule: a trailing byte", system_db(), &trailing, LARGE_OVERRIDE)); + all.push(submit( + "rule: not a creation", + system_db(), + NON_CONTRACT_CREATION_TX, + LARGE_OVERRIDE, + )); + all.push(submit( + "rule: not pre-EIP-155", + system_db(), + POST_EIP155_CHAIN_1_TX, + LARGE_OVERRIDE, + )); + let nonce_one = Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + all.push(Scenario::deploying( + "rule: signed at nonce 1", + system_db(), + &nonce_one, + gas_limit, + )); + all.push(submit( + "rule: override below the signed gas limit", + system_db(), + CREATE2_FACTORY_TX, + 99_999, + )); + let mut corrupted = CREATE2_FACTORY_TX.to_vec(); + corrupted[102..134].fill(0xff); + all.push(submit("rule: invalid signature", system_db(), &corrupted, LARGE_OVERRIDE)); + all.push(Scenario::deploying( + "rule: signer nonce 2", + system_db().account_nonce(small.signer, 2), + &small, + gas_limit, + )); + all.push(Scenario::deploying( + "rule: signer with code", + system_db().account_code(small.signer, Bytes::from_static(&[0x00])), + &small, + gas_limit, + )); + all.push( + Scenario::deploying( + "rule: signer with code, EIP-3607 off", + system_db().account_code(small.signer, Bytes::from_static(&[0x00])), + &small, + gas_limit, + ) + .eip3607_off(), + ); + all.push(Scenario::deploying( + "rule: occupied address", + system_db().account_code(small.address, Bytes::from_static(&[0x60, 0x00])), + &small, + gas_limit, + )); + let carrying = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); + all.push(Scenario::deploying( + "rule: value the signer cannot fund", + db_for(&carrying, U256::from(9)), + &carrying, + gas_limit, + )); + + /* Deployments. */ + all.push(Scenario::deploying( + "deploys from nonce 0, empty signer", + system_db(), + &small, + gas_limit, + )); + all.push(Scenario::deploying( + "deploys from nonce 0, funded signer", + db_for(&small, U256::ONE), + &small, + gas_limit, + )); + all.push(Scenario::deploying( + "deploys from nonce 1", + system_db().account_nonce(small.signer, 1), + &small, + gas_limit, + )); + all.push(Scenario::deploying( + "the address already has a balance", + system_db().account_balance(small.address, U256::from(5)), + &small, + gas_limit, + )); + all.push(Scenario::deploying( + "moves value", + db_for(&carrying, U256::from(10)), + &carrying, + gas_limit, + )); + all.push(Scenario::deploying( + "moves value from nonce 1", + db_for(&carrying, U256::from(10)).account_nonce(carrying.signer, 1), + &carrying, + gas_limit, + )); + all.push(submit("the CREATE2 factory", system_db(), CREATE2_FACTORY_TX, LARGE_OVERRIDE)); + let reverting = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let halting = Deployment::new(Bytes::from_static(&[INVALID])); + let logging_deployment = Deployment::new(logging(64)); + let writing = Deployment::new(filling_a_slot()); + let empty = Deployment::new(Bytes::from_static(&[STOP])); + let destroying = Deployment::new(Bytes::from_static(&[CALLER, SELFDESTRUCT])); + for (name, deployment) in [ + ("a constructor that reverts", &reverting), + ("a constructor that halts", &halting), + ("a constructor that logs", &logging_deployment), + ("a constructor that writes a slot", &writing), + ("a constructor that deploys nothing", &empty), + ("a constructor that destroys itself", &destroying), + ] { + all.push(Scenario::deploying( + format!("{name}, nonce 0"), + system_db(), + deployment, + gas_limit, + )); + all.push(Scenario::deploying( + format!("{name}, nonce 1"), + system_db().account_nonce(deployment.signer, 1), + deployment, + gas_limit, + )); + } + let starved = Deployment::signed(0, 30_000, U256::ZERO, deploying(&runtime(1))); + all.push(Scenario::new( + "a constructor out of gas", + system_db(), + starved.call_data(30_000), + gas_limit, + )); + + /* A signer that sends its own deployment. */ + let rich = U256::from(1_000_000_000_000_u64); + all.push( + Scenario::deploying("the signer sends it", db_for(&small, rich), &small, gas_limit) + .from(small.signer), + ); + all.push( + Scenario::deploying( + "the signer sends it, and it reverts", + db_for(&reverting, rich), + &reverting, + gas_limit, + ) + .from(reverting.signer), + ); + + /* Delegated signers. */ + let delegate = address!("0x00000000000000000000000000000000000d1e6a"); + all.push(Scenario::deploying( + "a delegated signer", + delegated(system_db(), small.signer, delegate, 1), + &small, + gas_limit, + )); + let creating_twice = Bytes::from_static(&[ + PUSH0, PUSH0, PUSH0, CREATE, POP, PUSH0, PUSH0, PUSH0, CREATE, POP, STOP, + ]); + let calling_the_signer = [PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, CALLER, GAS, CALL, POP]; + for (name, init_code) in [ + ( + "a delegated signer spending nonces, deploys", + constructor(&calling_the_signer, &runtime(1)), + ), + ( + "a delegated signer spending nonces, reverts", + Bytes::from([&calling_the_signer[..], &[PUSH0, PUSH0, REVERT]].concat()), + ), + ] { + let deployment = Deployment::new(init_code); + let db = delegated( + system_db().account_code(delegate, creating_twice.clone()), + deployment.signer, + delegate, + 1, + ); + all.push(Scenario::deploying(name, db, &deployment, gas_limit)); + } + + /* Limits. */ + let data_size = Deployment::new(logging(2_000)); + let body = reference(data_size.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; + let compute = Deployment::new(reads_then_burns(TIMESTAMP, 1_000)); + for nonce in [0, 1] { + let db = |d: &Deployment| system_db().account_nonce(d.signer, nonce); + all.push( + Scenario::deploying( + format!("limit: tx data size, nonce {nonce}"), + db(&data_size), + &data_size, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 80 + 100)), + ); + all.push( + Scenario::deploying( + format!("limit: compute, nonce {nonce}"), + db(&compute), + &compute, + gas_limit, + ) + .limits( + EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(1_000), + ), + ); + all.push( + Scenario::deploying( + format!("limit: frame data size, nonce {nonce}"), + db(&data_size), + &data_size, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(1_000)), + ); + all.push( + Scenario::deploying( + format!("limit: the call's budget, nonce {nonce}"), + db(&small), + &small, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39)), + ); + all.push( + Scenario::deploying( + format!("limit: the creation's start, nonce {nonce}"), + db(&small), + &small, + gas_limit, + ) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 40)), + ); + } + all.push( + Scenario::deploying("limit: a body over the limit", system_db(), &small, gas_limit) + .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100)), + ); + all.push( + Scenario::deploying("limit: the default limits", system_db(), &small, gas_limit) + .limits(EvmTxRuntimeLimits::default()), + ); + + /* Gas detention. */ + let capped = + |cap| EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + all.push( + Scenario::deploying( + "detention: a signer that is the beneficiary", + system_db(), + &small, + gas_limit, + ) + .beneficiary(small.signer) + .limits(capped(20_000_000)), + ); + all.push( + Scenario::deploying( + "detention: a signer that is the beneficiary, crossing at the CREATE charge", + system_db(), + &small, + gas_limit, + ) + .beneficiary(small.signer) + .limits(capped(create_regular(one_byte_init) - 1)), + ); + all.push( + Scenario::deploying( + "detention: the sender is the beneficiary, below the overhead", + system_db(), + &small, + gas_limit, + ) + .beneficiary(RELAYER) + .limits(capped(1)), + ); + let burning = Deployment::new(reads_then_burns(PUSH0, 100)); + for cap in [60_000, 150_000, 400_000] { + all.push( + Scenario::deploying( + format!("detention: the sender is the beneficiary, cap {cap}"), + system_db(), + &burning, + gas_limit, + ) + .beneficiary(RELAYER) + .limits(capped(cap)), + ); + } + all.push( + Scenario::deploying( + "detention: a constructor that reads, within the cap", + system_db(), + &compute, + gas_limit, + ) + .limits(capped(20_000_000)), + ); + + /* Not dispatched. */ + all.push(Scenario::new( + "not dispatched: version()", + system_db(), + // `version()`. + Bytes::from_static(&[0x54, 0xfd, 0x4d, 0x50]), + gas_limit, + )); + all.push(Scenario::new( + "not dispatched: no selector", + system_db(), + Bytes::new(), + gas_limit, + )); + let relaying = BytecodeBuilder::default() + .mstore(0, small.call_data(LARGE_OVERRIDE)) + .push_number(0_u8) + .push_number(0_u8) + .push_number(u16::try_from(small.call_data(LARGE_OVERRIDE).len()).unwrap()) + .push_number(0_u8) + .push_number(0_u8) + .push_address(KEYLESS_DEPLOY_ADDRESS) + .append_many([GAS, CALL, POP, STOP]) + .build(); + let relayer = address!("0x0000000000000000000000000000000000c0de01"); + all.push( + Scenario::new( + "not dispatched: from a contract", + system_db().account_code(relayer, relaying), + Bytes::new(), + gas_limit, + ) + .to(relayer), + ); + let static_relaying = BytecodeBuilder::default() + .mstore(0, small.call_data(LARGE_OVERRIDE)) + .push_number(0_u8) + .push_number(0_u8) + .push_number(u16::try_from(small.call_data(LARGE_OVERRIDE).len()).unwrap()) + .push_number(0_u8) + .push_address(KEYLESS_DEPLOY_ADDRESS) + .append_many([GAS, STATICCALL, POP, STOP]) + .build(); + all.push( + Scenario::new( + "not dispatched: a STATICCALL from a contract", + system_db().account_code(relayer, static_relaying), + Bytes::new(), + gas_limit, + ) + .to(relayer), + ); + + /* Where the contract is not deployed. */ + all.push(Scenario::deploying( + "no contract code", + MemoryDatabase::default().account_balance(RELAYER, U256::from(1_000_000_000_000_u64)), + &small, + gas_limit, + )); + + /* A system call. */ + all.push( + Scenario::deploying("a system call", system_db(), &small, gas_limit).system_call(), + ); + } + + /* Below the execution cap only: the charges a call can run out of gas on. */ + let data = small.call_data(LARGE_OVERRIDE); + all.push(Scenario::new( + "out of gas: the overhead", + system_db(), + data.clone(), + leaving(&data, 0) - 1, + )); + all.push(Scenario::new( + "out of gas: the signer's account", + system_db(), + data.clone(), + leaving(&data, 1_000), + )); + let signed = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + let signed_data = signed.call_data(LARGE_OVERRIDE); + let new_account = entry(GasId::new_account_state_gas()); + all.push(Scenario::new( + "rule: the signer's account takes the forward below the signed gas limit", + system_db(), + signed_data.clone(), + leaving(&signed_data, new_account + 500_000 - 1), + )); + let small_signed = Deployment::signed(0, 1_000, U256::ZERO, deploying(&runtime(1))); + let small_data = small_signed.call_data(LARGE_OVERRIDE); + all.push(Scenario::new( + "out of gas: the creation's charges", + db_for(&small_signed, U256::ONE), + small_data.clone(), + leaving(&small_data, 1_500), + )); + all.push(Scenario::new( + "rule: the creation's charges take the forward below the signed gas limit", + db_for(&signed, U256::ONE), + signed_data.clone(), + leaving(&signed_data, 500_000), + )); + all.push(Scenario::new( + "the forward at the signed gas limit exactly", + db_for(&signed, U256::ONE), + signed_data.clone(), + leaving(&signed_data, 500_000) + + create_regular(one_byte_init) + + entry(GasId::create_state_gas()) + + 2 * record(), + )); + + /* Above the execution cap only: a forward near the cap. */ + let near_cap = + Deployment::signed(0, TX_GAS_LIMIT_CAP - 50_000, U256::ZERO, deploying(&runtime(1))); + all.push(Scenario::deploying( + "rule: a forward below a signed gas limit near the cap", + db_for(&near_cap, U256::ONE), + &near_cap, + GAS_LIMITS[1], + )); + + /* A mebibyte of init code, at gas limits that cover its body. */ + let too_large = Deployment::new(vec![0; MAX_INITCODE_SIZE + 1].into()); + for gas_limit in [TX_GAS_LIMIT_CAP * 3 / 4, 10 * TX_GAS_LIMIT_CAP] { + all.push(Scenario::deploying( + "rule: init code over the limit", + system_db(), + &too_large, + gas_limit, + )); + } + all +} + +/* ---------- the recorder ---------- */ + +/// Records every frame start and end, every log, every self-destruct and every interpreter +/// initialized, with the journal depth it was told at; folds the steps between two of those into +/// a count and a digest. +#[derive(Default)] +struct Recorder { + lines: Vec, + steps: u64, + digest: u64, + /// Rewrites every frame result into a success, a creation's at its address. + rewrite: bool, + /// Answers every creation with a revert in its place. + answer_creations: bool, +} + +impl Recorder { + fn mix(&mut self, value: u64) { + for byte in value.to_le_bytes() { + self.digest = (self.digest ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); + } + } + + /// The steps folded since the last event, as a line. + fn pending_steps(&self) -> Option { + (self.steps > 0).then(|| format!("steps n={} digest={:016x}", self.steps, self.digest)) + } + + fn push(&mut self, line: String) { + if let Some(steps) = self.pending_steps() { + self.lines.push(steps); + self.steps = 0; + self.digest = 0; + } + self.lines.push(line); + } +} + +fn depth(ctx: &MegaContext) -> usize { + ctx.journal_ref().depth() +} + +fn render_gas(gas: &Gas) -> String { + format!("{gas:?}") +} + +impl Inspector, EthInterpreter> for Recorder { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + ctx: &mut MegaContext, + ) { + let line = format!( + "initialize_interp d={} target={} code={} gas={}", + depth(ctx), + interp.input.target_address, + interp.bytecode.hash().unwrap_or_default(), + render_gas(&interp.gas), + ); + self.push(line); + } + + fn step(&mut self, interp: &mut Interpreter, ctx: &mut MegaContext) { + self.steps += 1; + self.mix(depth(ctx) as u64); + self.mix(interp.bytecode.pc() as u64); + self.mix(u64::from(interp.bytecode.opcode())); + self.mix(interp.gas.remaining()); + self.mix(interp.gas.reservoir()); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.mix(interp.gas.remaining()); + self.mix(interp.gas.state_gas_spent() as u64); + self.mix(interp.gas.history_gas_spent() as u64); + } + + fn log(&mut self, ctx: &mut MegaContext, log: Log) { + self.push(format!("log d={} {log:?}", depth(ctx))); + } + + fn call(&mut self, ctx: &mut MegaContext, inputs: &mut CallInputs) -> Option { + let input = inputs.input.bytes(ctx); + let line = format!( + "call d={} {} -> {} code_at={} value={:?} scheme={:?} static={} gas_limit={} \ + reservoir={} charged={} input={}:{} mem={:?} known_code={}", + depth(ctx), + inputs.caller, + inputs.target_address, + inputs.bytecode_address, + inputs.value, + inputs.scheme, + inputs.is_static, + inputs.gas_limit, + inputs.reservoir, + inputs.charged_new_account_state_gas, + input.len(), + keccak256(&input), + inputs.return_memory_offset, + inputs.known_bytecode.0, + ); + self.push(line); + None + } + + fn call_end( + &mut self, + ctx: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + let line = format!( + "call_end d={} {} -> {} result={:?} output={} gas={} mem={:?} precompile={} \ + precompile_logs={} charged={} charged_at={} known_code={}", + depth(ctx), + inputs.caller, + inputs.target_address, + outcome.result.result, + outcome.result.output, + render_gas(&outcome.result.gas), + outcome.memory_offset, + outcome.was_precompile_called, + outcome.precompile_call_logs.len(), + outcome.charged_new_account_state_gas, + outcome.charged_state_gas_address, + inputs.known_bytecode.0, + ); + self.push(line); + if self.rewrite { + outcome.result.result = InstructionResult::Stop; + outcome.result.output = Bytes::new(); + } + } + + fn create( + &mut self, + ctx: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + let line = format!( + "create d={} {} scheme={:?} value={} gas_limit={} reservoir={} init={}:{} \ + charged={} charged_at={}", + depth(ctx), + inputs.caller(), + inputs.scheme(), + inputs.value(), + inputs.gas_limit(), + inputs.reservoir(), + inputs.init_code().len(), + keccak256(inputs.init_code()), + inputs.charged_create_state_gas(), + inputs.charged_state_gas_address(), + ); + self.push(line); + self.answer_creations.then(|| CreateOutcome { + result: InterpreterResult::new( + InstructionResult::Revert, + Bytes::new(), + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()), + ), + address: None, + charged_create_state_gas: inputs.charged_create_state_gas(), + charged_state_gas_address: inputs.charged_state_gas_address(), + }) + } + + fn create_end( + &mut self, + ctx: &mut MegaContext, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let line = format!( + "create_end d={} {} result={:?} address={:?} output={} gas={} charged={} charged_at={}", + depth(ctx), + inputs.caller(), + outcome.result.result, + outcome.address, + outcome.result.output, + render_gas(&outcome.result.gas), + outcome.charged_create_state_gas, + outcome.charged_state_gas_address, + ); + self.push(line); + if self.rewrite { + outcome.result.result = InstructionResult::Return; + outcome.result.output = Bytes::new(); + outcome.address = Some(inputs.created_address(1)); + } + } + + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.push(format!("selfdestruct {contract} -> {target} value={value}")); + } +} + +/* ---------- rendering ---------- */ + +fn render_state(state: &EvmState) -> String { + let mut accounts: Vec<_> = state.iter().collect(); + accounts.sort_by_key(|(address, _)| **address); + let mut out = String::new(); + for (address, account) in accounts { + let info = &account.info; + let code = info + .code + .as_ref() + .map_or_else(|| "unloaded".to_string(), |code| format!("{}", code.len())); + writeln!( + out, + " {address}: status={:?} tx={:?} nonce={} balance={} code_hash={} code={code}", + account.status, account.transaction_id, info.nonce, info.balance, info.code_hash, + ) + .unwrap(); + let mut slots: Vec<_> = account.storage.iter().collect(); + slots.sort_by_key(|(key, _)| **key); + for (key, slot) in slots { + writeln!(out, " {key}: {slot:?}").unwrap(); + } + } + out +} + +fn render_outcome(outcome: Result) -> String { + let outcome = match outcome { + Ok(outcome) => outcome, + Err(error) => return format!("error: {error:?}\n"), + }; + format!( + "result: {:?}\nledgers: {:?}\nusage: {:?}\nlimit_exceeded: {:?}\nstate:\n{}", + outcome.result, + outcome.gas, + outcome.usage, + outcome.limit_exceeded, + render_state(&outcome.state), + ) +} + +fn render_system_call( + result: Result<(R, EvmState), E>, +) -> String { + match result { + Ok((result, state)) => format!("result: {result:?}\nstate:\n{}", render_state(&state)), + Err(error) => format!("error: {error:?}\n"), + } +} + +fn render_detention(ctx: &MegaContext) -> String { + let detention = ctx.detention(); + format!( + "detention: limit={:?} accessed={:?} detains={}\n", + detention.compute_limit(), + detention.accessed(), + detention.detains(), + ) +} diff --git a/crates/mega-evm/tests/system/keyless.rs b/crates/mega-evm/tests/system/keyless/dispatch.rs similarity index 66% rename from crates/mega-evm/tests/system/keyless.rs rename to crates/mega-evm/tests/system/keyless/dispatch.rs index fa846c82e..e877fe363 100644 --- a/crates/mega-evm/tests/system/keyless.rs +++ b/crates/mega-evm/tests/system/keyless/dispatch.rs @@ -1,21 +1,35 @@ //! The `KeylessDeploy` dispatch: which calls are recognised, what they are charged, and which //! run the deployed bytecode instead. +//! +//! A recognised call pays the fixed overhead before anything else, then either starts its +//! deployment or is refused. The tests here send transactions a rule refuses, so that what is +//! left beyond the reference transaction — the same calldata to an account with no code — is the +//! overhead alone. use alloy_primitives::{Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; -use mega_evm::system::keyless::{ - IKeylessDeploy, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, +use mega_evm::{ + system::keyless::{ + IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + EvmTxRuntimeLimits, }; use revm::{ bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}, context::result::ExecutionResult, }; +use super::{beyond, reference, refusal, run_with, GAS_LIMITS}; use crate::common::{ - call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, - CONTRACT, GAS_LIMIT, + body_history, call_tx, calls_with, output, revert_data, run, split_outcome, system_db, + with_contract, CONTRACT, GAS_LIMIT, }; +/// No runtime limit. +fn no_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits() +} + const KEYLESS_DEPLOY: [u8; 4] = IKeylessDeploy::keylessDeployCall::SELECTOR; const NOT_INTERCEPTED: [u8; 4] = IKeylessDeploy::NotIntercepted::SELECTOR; const NO_ETHER_TRANSFER: [u8; 4] = IKeylessDeploy::NoEtherTransfer::SELECTOR; @@ -39,27 +53,18 @@ fn unknown_selector(data: &Bytes) -> Bytes { Bytes::from(data) } -/// A dispatched `keylessDeploy` transaction pays the fixed overhead, and then runs the deployed -/// bytecode, because the rewrite that turns it into a deployment is not here yet. +/// A dispatched `keylessDeploy` transaction pays the fixed overhead, then is refused by the +/// rules: bytes that do not decode as a signed transaction are `MalformedEncoding()`. The +/// deployed bytecode does not run, and the overhead is all the refusal keeps. #[test] fn test_a_keyless_deploy_transaction_pays_the_overhead() { let data = keyless_deploy(b"a transaction"); - let dispatched = run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO)); - let plain = - run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&data), U256::ZERO)); - - assert_eq!( - revert_data(&dispatched), - Bytes::from_static(&NOT_INTERCEPTED), - "the deployed bytecode runs after the charge", - ); - // What each transaction spent, not what its receipt reports: the calldata floor of - // EIP-7623 lifts the receipt of the cheaper one above what it spent. - let charged = dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent(); - assert!( - (KEYLESS_DEPLOY_OVERHEAD_GAS..KEYLESS_DEPLOY_OVERHEAD_GAS + 1_000).contains(&charged), - "{charged} is not the fixed overhead plus what the two paths differ by in the bytecode", - ); + for gas_limit in GAS_LIMITS { + let dispatched = run_with(system_db(), data.clone(), gas_limit, no_limits()); + assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); + let [total, regular, ..] = beyond(&dispatched, &reference(data.clone(), gas_limit)); + assert_eq!([total, regular], [KEYLESS_DEPLOY_OVERHEAD_GAS; 2], "at {gas_limit}"); + } } /// A call that carries value is refused with the ABI's own `NoEtherTransfer()`, and the @@ -99,8 +104,10 @@ fn test_a_call_from_a_contract_is_not_dispatched() { let (status, returned) = split_outcome(&outcome); assert!(!status, "scheme {scheme:#x}"); assert_eq!(returned, NOT_INTERCEPTED, "scheme {scheme:#x}"); + // The transaction's body is its only history: what it spent beside it is less than the + // overhead. assert!( - result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS, + result.result.gas().total_gas_spent() - body_history(0) < KEYLESS_DEPLOY_OVERHEAD_GAS, "scheme {scheme:#x} paid the overhead of a dispatch that did not happen", ); } @@ -124,8 +131,11 @@ fn test_an_unknown_selector_is_not_dispatched() { "an input of {} bytes reverted with data the contract has no code to return", input.len(), ); + // The transaction's body is its only history: what it spent beside it is less than the + // overhead. + let spent = result.result.gas().total_gas_spent() - body_history(input.len() as u64); assert!( - result.result.gas().total_gas_spent() < KEYLESS_DEPLOY_OVERHEAD_GAS, + spent < KEYLESS_DEPLOY_OVERHEAD_GAS, "an input of {} bytes paid an overhead it does not owe", input.len(), ); @@ -137,7 +147,8 @@ fn test_an_unknown_selector_is_not_dispatched() { #[test] fn test_a_call_that_cannot_pay_the_overhead_runs_out_of_gas() { let data = keyless_deploy(b"a transaction"); - let gas_limit = 60_000; + // 60,000 on top of the body's history: the intrinsic gas and less than the overhead beside it. + let gas_limit = 60_000 + body_history(data.len() as u64); let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); tx.0.base.gas_limit = gas_limit; @@ -154,35 +165,24 @@ fn test_a_call_that_cannot_pay_the_overhead_runs_out_of_gas() { /// payload. #[test] fn test_the_overhead_does_not_depend_on_the_payload() { - let charge_of = |payload: &[u8]| { + for payload in [&b""[..], &[0xab; 512]] { let data = keyless_deploy(payload); - let dispatched = - run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO)); - let plain = - run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&data), U256::ZERO)); - assert!(dispatched.result.gas().total_gas_spent() < GAS_LIMIT); - dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent() - }; - let (empty, payload) = (charge_of(b""), charge_of(&[0xab; 512])); - assert!(empty >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{empty} is below the fixed overhead"); - assert!(payload >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{payload} is below the fixed overhead"); + let dispatched = run_with(system_db(), data.clone(), GAS_LIMIT, no_limits()); + assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); + let [total, ..] = beyond(&dispatched, &reference(data, GAS_LIMIT)); + assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS, "a payload of {} bytes", payload.len()); + } } /// Admission is the selector alone here too: a payload too short to hold the arguments the ABI -/// names is still dispatched and charged. What the deployment makes of it is the deployment's -/// to decide — it rejects a transaction it cannot decode. +/// names is still dispatched and charged, and the deployment rejects what it cannot decode with +/// `MalformedEncoding()`. #[test] fn test_a_truncated_payload_is_still_dispatched() { let truncated: Bytes = KEYLESS_DEPLOY.iter().copied().chain([0_u8; 16]).collect::>().into(); - let dispatched = - run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, truncated.clone(), U256::ZERO)); - let plain = - run(system_db(), call_tx(KEYLESS_DEPLOY_ADDRESS, unknown_selector(&truncated), U256::ZERO)); - - let charged = dispatched.result.gas().total_gas_spent() - plain.result.gas().total_gas_spent(); - assert!( - charged >= KEYLESS_DEPLOY_OVERHEAD_GAS, - "{charged} is below the overhead a dispatched call pays", - ); + let dispatched = run_with(system_db(), truncated.clone(), GAS_LIMIT, no_limits()); + assert_eq!(refusal(&dispatched), KeylessDeployError::MalformedEncoding); + let [total, ..] = beyond(&dispatched, &reference(truncated, GAS_LIMIT)); + assert_eq!(total, KEYLESS_DEPLOY_OVERHEAD_GAS); } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs new file mode 100644 index 000000000..780cdbfc2 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -0,0 +1,386 @@ +//! The `keylessDeploy` call as a frame: revm builds it on the contract, as any call's, and puts it +//! on its frame stack; its actions are made by hand, so the contract's bytecode never runs for a +//! call the dispatch takes; the creation is its child, one frame above it on the stack; and an +//! inspector sees it as one call frame in which no interpreter runs. + +use mega_evm::{ + alloy_consensus::{ + proofs::{state_root_unhashed, storage_root_unhashed}, + TrieAccount, + }, + system::keyless::{KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::BytecodeBuilder, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, POP, STOP}, + context::{ContextTr, JournalTr}, + database::{states::bundle_state::BundleRetention, PlainAccount, State}, + handler::{EvmTr, FrameResult, ItemOrResult}, + interpreter::{ + interpreter::EthInterpreter, interpreter_action::FrameInit, CallInput, CallInputs, + CallOutcome, CallScheme, CallValue, CreateScheme, FrameInput, InstructionResult, + Interpreter, SharedMemory, + }, + primitives::KECCAK_EMPTY, + Database, DatabaseCommit, Inspector, +}; + +use super::*; +use crate::common::{context, CALLER}; + +/// The transaction's own frame: a `keylessDeploy` call of `data` from [`CALLER`], forwarded +/// `gas_limit`, over the contract's code as the transaction loads it. +fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> FrameInit { + FrameInit { + depth: 0, + memory: SharedMemory::new(), + frame_input: FrameInput::Call(Box::new(CallInputs { + input: CallInput::Bytes(data), + return_memory_offset: 0..0, + gas_limit, + reservoir: 0, + bytecode_address: KEYLESS_DEPLOY_ADDRESS, + known_bytecode: (KEYLESS_DEPLOY_CODE_HASH, code), + target_address: KEYLESS_DEPLOY_ADDRESS, + caller: CALLER, + value: CallValue::Transfer(U256::ZERO), + scheme: CallScheme::Call, + is_static: false, + charged_new_account_state_gas: false, + })), + } +} + +/// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand: revm builds +/// it at depth 0; its first run starts the creation as its child, at depth 1, which revm builds +/// above it on the stack; the creation returns into it; and on its resume it answers in the ABI, +/// as the outermost frame. +#[test] +fn test_the_call_is_a_frame_on_revms_stack() { + let deployment = Deployment::new(deploying(&runtime(1))); + let mut evm = MegaEvm::new(context(system_db())); + let journal = evm.ctx_mut().journal_mut(); + journal.load_account(CALLER).unwrap(); + let code = journal.load_account_with_code(KEYLESS_DEPLOY_ADDRESS).unwrap().info.code.clone(); + let init = call_frame(code.unwrap(), deployment.call_data(LARGE_OVERRIDE), 10_000_000); + + let ItemOrResult::Item(call) = EvmTr::frame_init(&mut evm, init).unwrap() else { + panic!("revm builds the call's frame"); + }; + assert_eq!(call.depth, 0); + assert_eq!(call.interpreter.input.target_address, KEYLESS_DEPLOY_ADDRESS); + assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(0)); + + let ItemOrResult::Item(creation) = EvmTr::frame_run(&mut evm).unwrap() else { + panic!("the call's first run starts its creation"); + }; + assert_eq!(creation.depth, 1, "the creation is the call's child"); + let FrameInput::Create(inputs) = &creation.frame_input else { + panic!("the child is a creation: {:?}", creation.frame_input); + }; + assert_eq!(inputs.caller(), deployment.signer); + assert_eq!(inputs.scheme(), CreateScheme::Custom { address: deployment.address }); + let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, creation).unwrap() else { + panic!("revm builds the creation's frame"); + }; + assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(1), "above the call on the stack"); + + let ItemOrResult::Result(created) = EvmTr::frame_run(&mut evm).unwrap() else { + panic!("the creation runs to its end"); + }; + assert!(matches!(&created, FrameResult::Create(outcome) if outcome.result.is_ok())); + let returned = EvmTr::frame_return_result(&mut evm, created).unwrap(); + assert!(returned.is_none(), "the creation returns into the call"); + assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(0)); + + let ItemOrResult::Result(answer) = EvmTr::frame_run(&mut evm).unwrap() else { + panic!("the call answers on its resume"); + }; + let answer = EvmTr::frame_return_result(&mut evm, answer).unwrap(); + let Some(FrameResult::Call(outcome)) = answer else { + panic!("the call is the outermost frame: {answer:?}"); + }; + assert_eq!(outcome.result.result, InstructionResult::Return); + let ret = + IKeylessDeploy::keylessDeployCall::abi_decode_returns(&outcome.result.output).unwrap(); + assert_eq!(ret.deployedAddress, deployment.address); + assert!(EvmTr::frame_stack(&mut evm).index().is_none(), "no frame is left"); +} + +/// What an inspector was told, and at which journal depth. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Seen { + Call(usize, Address), + CallEnd(usize, InstructionResult), + Interpreter(Address), + Step(Address), +} + +/// Records the frame starts and ends of calls, every interpreter initialized and every step. +#[derive(Default)] +struct Watcher { + seen: Vec, +} + +impl Inspector, EthInterpreter> for Watcher { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + self.seen.push(Seen::Interpreter(interp.input.target_address)); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.seen.push(Seen::Step(interp.input.target_address)); + } + + fn call(&mut self, ctx: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.seen.push(Seen::Call(ctx.journal_ref().depth(), inputs.target_address)); + None + } + + fn call_end(&mut self, ctx: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + self.seen.push(Seen::CallEnd(ctx.journal_ref().depth(), outcome.result.result)); + } +} + +/// Runs `data` to `to` from [`CALLER`] over `db` at `gas_limit`, carrying `value`, under a +/// [`Watcher`]. +fn watched( + db: MemoryDatabase, + to: Address, + data: Bytes, + value: U256, + gas_limit: u64, +) -> (MegaTransactionOutcome, Vec) { + let mut tx = call_tx(to, data, value); + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(context(db)).with_inspector(Watcher::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + (outcome, evm.inspector().seen.clone()) +} + +/// An inspector sees the call as one call frame, started and ended at the transaction's journal +/// depth, in which no interpreter is initialized and no step runs: every step it sees is the +/// creation's, whose interpreter is the only one. So for a deployment, and for a call a rule +/// refuses. +#[test] +fn test_the_inspector_sees_one_call_frame_in_which_nothing_runs() { + let deployment = Deployment::new(deploying(&runtime(1))); + let refused = Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let (outcome, seen) = watched( + system_db(), + KEYLESS_DEPLOY_ADDRESS, + deployment.call_data(LARGE_OVERRIDE), + U256::ZERO, + gas_limit, + ); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let calls: Vec<_> = + seen.iter().filter(|s| matches!(s, Seen::Call(..) | Seen::CallEnd(..))).collect(); + assert_eq!( + calls, + [&Seen::Call(0, KEYLESS_DEPLOY_ADDRESS), &Seen::CallEnd(0, InstructionResult::Return)], + "at {gas_limit}", + ); + assert!(seen.contains(&Seen::Interpreter(deployment.address))); + assert!( + seen.iter().all(|s| !matches!(s, Seen::Interpreter(a) | Seen::Step(a) + if *a == KEYLESS_DEPLOY_ADDRESS)), + "nothing runs in the call's frame: {seen:?}", + ); + + let (outcome, seen) = watched( + system_db(), + KEYLESS_DEPLOY_ADDRESS, + refused.call_data(LARGE_OVERRIDE), + U256::ZERO, + gas_limit, + ); + assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); + assert_eq!( + seen, + [Seen::Call(0, KEYLESS_DEPLOY_ADDRESS), Seen::CallEnd(0, InstructionResult::Revert)], + "at {gas_limit}", + ); + } +} + +/// Code that stores 1 at slot 0, then stops: run, it leaves a mark. +fn marking() -> Bytes { + BytecodeBuilder::default().sstore(U256::ZERO, U256::ONE).append(STOP).build() +} + +/// Whether `outcome` left the mark [`marking`] makes at the contract. +fn marked(outcome: &MegaTransactionOutcome) -> bool { + outcome + .state + .get(&KEYLESS_DEPLOY_ADDRESS) + .and_then(|account| account.storage.get(&U256::ZERO)) + .is_some_and(|slot| slot.present_value == U256::ONE) +} + +/// The contract's bytecode never runs for a call the dispatch takes, whatever the bytecode: with +/// code at the address that would leave a mark, a deployment deploys and a refused call is +/// refused, neither leaving it. A call the dispatch does not take runs the bytecode as any call +/// does: another selector, and a `keylessDeploy` call a contract makes. +#[test] +fn test_the_contracts_bytecode_never_runs_for_a_dispatched_call() { + let deployment = Deployment::new(deploying(&runtime(1))); + let data = deployment.call_data(LARGE_OVERRIDE); + let relayer = address!("0x0000000000000000000000000000000000c0de02"); + let relaying = BytecodeBuilder::default() + .mstore(0, &data) + .push_number(0_u8) + .push_number(0_u8) + .push_number(u16::try_from(data.len()).unwrap()) + .push_number(0_u8) + .push_number(0_u8) + .push_address(KEYLESS_DEPLOY_ADDRESS) + .append_many([GAS, CALL, POP, STOP]) + .build(); + let db = + system_db().account_code(KEYLESS_DEPLOY_ADDRESS, marking()).account_code(relayer, relaying); + for gas_limit in GAS_LIMITS { + let (deployed, seen) = + watched(db.clone(), KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO, gas_limit); + assert_eq!(returned(&deployed).deployedAddress, deployment.address, "at {gas_limit}"); + assert!(!marked(&deployed), "a deployment runs no bytecode at {gas_limit}"); + assert!(!seen.contains(&Seen::Interpreter(KEYLESS_DEPLOY_ADDRESS))); + + let (refused, _) = + watched(db.clone(), KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ONE, gas_limit); + assert_eq!(refusal(&refused), KeylessDeployError::NoEtherTransfer); + assert!(!marked(&refused), "a refused call runs no bytecode at {gas_limit}"); + + let version = Bytes::from_static(&[0x54, 0xfd, 0x4d, 0x50]); + let (other, _) = + watched(db.clone(), KEYLESS_DEPLOY_ADDRESS, version, U256::ZERO, gas_limit); + assert!(marked(&other), "another selector runs the bytecode at {gas_limit}"); + + let (from_a_contract, seen) = + watched(db.clone(), relayer, Bytes::new(), U256::ZERO, gas_limit); + assert!(marked(&from_a_contract), "a contract's call runs the bytecode at {gas_limit}"); + assert!(seen.contains(&Seen::Interpreter(KEYLESS_DEPLOY_ADDRESS))); + } +} + +/// The dispatch is by address and selector, whatever the address holds: where the state holds no +/// contract code, the call's frame is built on the contract's own, and the call deploys. +#[test] +fn test_a_call_is_dispatched_where_the_state_holds_no_contract_code() { + let deployment = Deployment::new(deploying(&runtime(1))); + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_000_u64)); + for gas_limit in GAS_LIMITS { + let outcome = run_with( + db.clone(), + deployment.call_data(LARGE_OVERRIDE), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + } +} + +/// The state root over `accounts`, as a node computes it from the committed state. +fn state_root<'a>(accounts: impl IntoIterator) -> B256 { + state_root_unhashed(accounts.into_iter().map(|(address, account)| { + let storage = account.storage.iter().filter(|(_, value)| !value.is_zero()); + let leaf = TrieAccount { + nonce: account.info.nonce, + balance: account.info.balance, + storage_root: storage_root_unhashed( + storage.map(|(key, value)| (B256::from(*key), *value)), + ), + code_hash: account.info.code_hash, + }; + (address, leaf) + })) +} + +/// Where the state holds no contract code, the call's frame is built on an account that does not +/// exist, and the call touches it as it touches any target. A touched empty account is not +/// committed (EIP-161): once the state is applied the account is still absent, the changes the +/// block hands on hold nothing for it, and the state root is the root of the other accounts alone, +/// which a committed empty account would have moved. +#[test] +fn test_a_call_where_the_state_holds_no_contract_code_commits_nothing_for_it() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let db = + MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_000_u64)); + let mut state = State::builder().with_database(db).with_bundle_update().build(); + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(&mut state)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + let contract = &outcome.state[&KEYLESS_DEPLOY_ADDRESS]; + assert!(contract.is_touched(), "the call touches its target"); + assert!(contract.is_loaded_as_not_existing(), "which does not exist"); + + state.commit(outcome.result_and_state.state); + state.merge_transitions(BundleRetention::Reverts); + assert_eq!(state.basic(KEYLESS_DEPLOY_ADDRESS).unwrap(), None, "still absent"); + let bundle = state.take_bundle(); + assert!(bundle.account(&KEYLESS_DEPLOY_ADDRESS).is_none(), "no change for the contract"); + assert!(bundle.account(&deployment.address).is_some(), "the deployment is committed"); + + let accounts: Vec<_> = state.cache.trie_account().into_iter().collect(); + let root = state_root(accounts.iter().copied()); + let others = + accounts.iter().copied().filter(|(address, _)| *address != KEYLESS_DEPLOY_ADDRESS); + assert_eq!(root, state_root(others), "the root is the other accounts' alone"); + let empty = PlainAccount::new_empty_with_storage(Default::default()); + assert_eq!(empty.info.code_hash, KECCAK_EMPTY); + let with_empty = accounts.iter().copied().chain([(KEYLESS_DEPLOY_ADDRESS, &empty)]); + assert_ne!(root, state_root(with_empty), "a committed empty account moves the root"); + } +} + +/// A call carrying value is refused before revm builds its frame, which would move the value: +/// its start counts nothing — no record of the contract's account, no transfer log — so a data-size +/// limit that holds the body and not the 200 bytes a value call's start counts does not stop it, +/// and the refusal is what it reports. It pays the overhead, as any call the dispatch takes does. +#[test] +fn test_a_call_carrying_value_is_refused_before_its_start_is_counted() { + let deployment = Deployment::new(deploying(&runtime(1))); + let data = deployment.call_data(LARGE_OVERRIDE); + let body = reference(data.clone(), GAS_LIMITS[0]).usage.data_size; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 199); + for gas_limit in GAS_LIMITS { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ONE); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(system_db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert_eq!(refusal(&outcome), KeylessDeployError::NoEtherTransfer, "at {gas_limit}"); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.usage.data_size, body, "nothing but the body is counted"); + assert!(outcome.gas.regular > KEYLESS_DEPLOY_OVERHEAD_GAS, "the overhead is paid"); + } +} + +/// revm builds the call's frame on the contract as its target, as any call's: the contract's +/// account, which the transaction loads with its code to start its first frame, is touched by a +/// call that returns, and not by one that reverts, whose journal checkpoint takes the touch back. +#[test] +fn test_the_call_touches_the_contract_as_any_call_does() { + let deployment = Deployment::new(deploying(&runtime(1))); + let refused = Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let contract = |outcome: &MegaTransactionOutcome| { + outcome.state.get(&KEYLESS_DEPLOY_ADDRESS).cloned().expect("the target is loaded") + }; + let deployed = deploy(system_db(), &deployment, gas_limit); + assert!(contract(&deployed).info.code.is_some(), "loaded with its code"); + assert!(contract(&deployed).is_touched(), "touched by a call that returns"); + let reverted = deploy(system_db(), &refused, gas_limit); + assert!(contract(&reverted).info.code.is_some(), "loaded with its code"); + assert!(!contract(&reverted).is_touched(), "untouched by a call that reverts"); + } +} diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs new file mode 100644 index 000000000..554ac26eb --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -0,0 +1,420 @@ +//! What an inspector sees of a keyless deployment: the frames it is made of. The transaction calls +//! `KeylessDeploy`, and that call creates: the inspector is told the call starts, then the +//! creation, one journal depth below it, then every step of the init code, the creation's end and +//! the call's, each with the gas and the output it had. + +use alloy_sol_types::SolError; +use mega_evm::{ + system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, LimitKind, + MegaLimitExceeded, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{LOG0, PUSH0, REVERT}, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, CreateScheme, Gas, InstructionResult, Interpreter, + InterpreterResult, + }, + primitives::KECCAK_EMPTY, + Database, Inspector, +}; +use revm_inspectors::tracing::{types::CallKind, TracingInspector, TracingInspectorConfig}; + +use super::*; +use crate::common::{context, keyless_tx, CALLER}; + +/// What an inspector was told, in order. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Event { + Call(Address), + CallEnd(InstructionResult), + Create(Address, CreateScheme), + CreateEnd(InstructionResult, Option
), + Step(u8), + Log(Address), +} + +/// Records every frame start and end, every step and every log. +#[derive(Default)] +struct Recorder { + events: Vec, + /// When set, answers every creation with a revert instead of letting it run. + answer_creations: bool, +} + +impl Inspector, EthInterpreter> for Recorder { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.events.push(Event::Step(interp.bytecode.opcode())); + } + + fn log(&mut self, _: &mut MegaContext, log: alloy_primitives::Log) { + self.events.push(Event::Log(log.address)); + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.events.push(Event::Call(inputs.target_address)); + None + } + + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + self.events.push(Event::CallEnd(outcome.result.result)); + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.events.push(Event::Create(inputs.caller(), inputs.scheme())); + self.answer_creations.then(|| CreateOutcome { + result: InterpreterResult::new( + InstructionResult::Revert, + Bytes::new(), + Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()), + ), + address: None, + charged_create_state_gas: inputs.charged_create_state_gas(), + charged_state_gas_address: inputs.charged_state_gas_address(), + }) + } + + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.events.push(Event::CreateEnd(outcome.result.result, outcome.address)); + } +} + +/// Runs `deployment` under `recorder`, and returns what the recorder saw. +fn inspect(deployment: &Deployment, recorder: Recorder, gas_limit: u64) -> (Outcome, Recorder) { + let mut evm = MegaEvm::new(context(system_db())).with_inspector(recorder); + let outcome = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("valid"); + let seen = Recorder { + events: evm.inspector().events.clone(), + answer_creations: evm.inspector().answer_creations, + }; + (outcome, seen) +} + +type Outcome = MegaTransactionOutcome; + +/// The inspector sees the call to `KeylessDeploy` start, then the creation it starts — the signer +/// creating at its Nick's-Method address — every step of the init code and its log, the creation +/// ending at that address, and last the call ending with the answer it gave. +#[test] +fn test_the_inspector_sees_the_call_and_the_creation_it_starts() { + let prefix = + BytecodeBuilder::default().push_number(0_u64).push_number(0_u64).append(LOG0).build_vec(); + let init_code = constructor(&prefix, &runtime(1)); + let deployment = Deployment::new(init_code.clone()); + for gas_limit in GAS_LIMITS { + let (outcome, recorder) = inspect(&deployment, Recorder::default(), gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let events = recorder.events; + assert_eq!( + events[..2], + [ + Event::Call(KEYLESS_DEPLOY_ADDRESS), + Event::Create( + deployment.signer, + CreateScheme::Custom { address: deployment.address } + ), + ], + ); + assert_eq!( + events[events.len() - 2..], + [ + Event::CreateEnd(InstructionResult::Return, Some(deployment.address)), + Event::CallEnd(InstructionResult::Return), + ], + ); + let steps: Vec = events + .iter() + .filter_map(|event| match event { + Event::Step(opcode) => Some(*opcode), + _ => None, + }) + .collect(); + assert_eq!(steps.len(), 10, "every instruction of the init code: {steps:02x?}"); + assert_eq!(steps[0], init_code[0]); + assert!(steps.contains(&LOG0)); + assert!(events.contains(&Event::Log(deployment.address))); + } +} + +/// A call the rules refuse is reported as the call it is, its start and end paired around the +/// refusal; no creation starts. +#[test] +fn test_a_refused_call_is_seen_as_a_call() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); + let (outcome, recorder) = inspect(&deployment, Recorder::default(), gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + assert_eq!( + recorder.events, + [Event::Call(KEYLESS_DEPLOY_ADDRESS), Event::CallEnd(InstructionResult::Revert)], + ); + } +} + +/// A creation whose init code reverts ends as a revert in the trace, and the call, which reports +/// the failure in its return, ends as a success. +#[test] +fn test_a_failed_deployment_ends_as_a_revert_in_the_trace() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let (outcome, recorder) = inspect(&deployment, Recorder::default(), gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + let events = recorder.events; + assert_eq!( + events[events.len() - 2..], + [ + Event::CreateEnd(InstructionResult::Revert, Some(deployment.address)), + Event::CallEnd(InstructionResult::Return), + ], + ); + } +} + +/// An inspector that answers the creation itself — a tool's rewrite — starts no creation: the +/// signer's nonce is not spent, so neither its account nor the created one is charged, and the +/// call reports what the inspector answered. The transaction spends the overhead, the regular gas +/// the `CREATE` opcode charges whatever its frame does, and the reference's gas, and nothing +/// else. +#[test] +fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { + let deployment = Deployment::new(deploying(&runtime(1))); + let opcode = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(deploying(&runtime(1)).len()); + for gas_limit in GAS_LIMITS { + let recorder = Recorder { answer_creations: true, ..Default::default() }; + let (outcome, recorder) = inspect(&deployment, recorder, gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 0); + let [total, regular, state, history_gas, history_bytes] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + [total, regular, state, history_gas, history_bytes], + [opcode, opcode, 0, 0, 0], + "at {gas_limit}", + ); + assert_eq!( + recorder.events, + [ + Event::Call(KEYLESS_DEPLOY_ADDRESS), + Event::Create( + deployment.signer, + CreateScheme::Custom { address: deployment.address } + ), + Event::CreateEnd(InstructionResult::Revert, None), + Event::CallEnd(InstructionResult::Return), + ], + ); + } +} + +/// A transaction whose body crosses the data-size limit is rejected at validation on the inspected +/// path too: the inspector sees no frame, neither the call nor a creation. +#[test] +fn test_a_rejected_transaction_is_seen_as_nothing() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100); + let mut evm = MegaEvm::new(context(system_db()).with_tx_runtime_limits(limits)) + .with_inspector(Recorder::default()); + let error = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect_err("rejected at validation"); + let error = format!("{error:?}"); + assert!(error.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "at {gas_limit}: {error}"); + assert_eq!(evm.inspector().events, [], "at {gas_limit}"); + } +} + +/// A tracer sees the frames a keyless deployment is made of: at the root, at journal depth 0, the +/// transaction's call to `KeylessDeploy`, which returns the ABI answer; as its one child, one +/// depth below, the creation from the signer at the deploy address, which returns the runtime it +/// deploys. Each reports the gas it took from its gas limit — the call what the transaction spent +/// beyond its intrinsic gas, the creation its `gasUsed` — less, above the execution cap, the state +/// and history gas the reservoir paid, as for any frame. The parity and geth call traces built +/// from it say the same, and no trace has a frame of its own. +#[test] +fn test_a_tracer_sees_the_call_and_the_creation_it_starts() { + let deployment = Deployment::new(deploying(&runtime(3))); + for gas_limit in GAS_LIMITS { + let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); + let mut evm = MegaEvm::new(context(system_db())).with_inspector(tracer); + let outcome = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("valid"); + let answer = returned(&outcome); + assert_eq!(answer.deployedAddress, deployment.address); + let tracer = evm.inspector().clone(); + + let [root, child] = tracer.traces().nodes() else { + panic!("expected two frames: {:#?}", tracer.traces().nodes()); + }; + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [spent, regular, ..] = beyond(&outcome, &reference); + let deposit = satin_gas_params().code_deposit_state_gas(3) + history(3); + let (call_took, creation_took) = if gas_limit > TX_GAS_LIMIT_CAP { + (regular, answer.gasUsed - deposit) + } else { + (spent, answer.gasUsed) + }; + assert_eq!( + (root.trace.kind, root.trace.depth, root.trace.caller, root.trace.address), + (CallKind::Call, 0, CALLER, KEYLESS_DEPLOY_ADDRESS), + ); + assert_eq!((root.parent, root.children.as_slice()), (None, &[1][..])); + assert_eq!(root.trace.status, Some(InstructionResult::Return)); + assert_eq!(Some(&root.trace.output), outcome.result.output()); + assert_eq!(root.trace.gas_used, call_took, "at {gas_limit}"); + assert_eq!( + (child.trace.kind, child.trace.depth, child.trace.caller, child.trace.address), + (CallKind::Create, 1, deployment.signer, deployment.address), + ); + assert_eq!(child.parent, Some(0)); + assert_eq!(child.trace.status, Some(InstructionResult::Return)); + assert_eq!(child.trace.output, Bytes::from(runtime(3))); + assert_eq!(child.trace.gas_used, creation_took, "at {gas_limit}"); + + let parity = + serde_json::to_value(tracer.clone().into_parity_builder().into_transaction_traces()) + .unwrap(); + let [call, create] = parity.as_array().expect("a list of traces").as_slice() else { + panic!("expected two parity traces: {parity:#}"); + }; + assert_eq!(call["type"], "call", "{parity:#}"); + assert_eq!(call["action"]["from"], json_address(CALLER)); + assert_eq!(call["action"]["to"], json_address(KEYLESS_DEPLOY_ADDRESS)); + assert_eq!(call["traceAddress"], serde_json::json!([])); + assert_eq!(call["subtraces"], 1); + assert_eq!(create["type"], "create", "{parity:#}"); + assert_eq!(create["action"]["from"], json_address(deployment.signer)); + assert_eq!(create["result"]["address"], json_address(deployment.address)); + assert_eq!(create["traceAddress"], serde_json::json!([0])); + + let geth = serde_json::to_value( + tracer + .into_geth_builder() + .geth_call_traces(Default::default(), outcome.result.gas().tx_gas_used()), + ) + .unwrap(); + assert_eq!(geth["type"], "CALL", "{geth:#}"); + assert_eq!(geth["from"], json_address(CALLER)); + assert_eq!(geth["to"], json_address(KEYLESS_DEPLOY_ADDRESS)); + let [create] = geth["calls"].as_array().expect("the call's children").as_slice() else { + panic!("expected one child: {geth:#}"); + }; + assert_eq!(create["type"], "CREATE", "{geth:#}"); + assert_eq!(create["from"], json_address(deployment.signer)); + assert_eq!(create["to"], json_address(deployment.address)); + assert!(create.get("calls").is_none(), "{geth:#}"); + } +} + +/// `address` as a trace's JSON holds it. +fn json_address(address: Address) -> serde_json::Value { + serde_json::to_value(address).unwrap() +} + +/// Revives every creation that failed, as Foundry's `expectRevert` does: the result becomes a +/// success at `0x…01`, which is no address the deployment pinned. +struct Revives; + +impl Inspector, EthInterpreter> for Revives { + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + if !outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(Address::with_last_byte(1)); + } + } +} + +/// A deployment whose creation fails and is revived by an inspector reports a creation at an +/// address the deployment did not pin: the call reverts with `AddressMismatch()`, which a plain +/// run never produces — it answers `ExecutionReverted`. The call's revert takes the whole +/// deployment back, the signer's nonce bump included, which the plain run keeps. +#[test] +fn test_a_revived_keyless_creation_answers_address_mismatch() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let plain = MegaEvm::new(context(system_db())) + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + let plain = plain.expect("valid"); + assert!(matches!(failure(&plain), KeylessDeployError::ExecutionReverted { .. })); + + let mut evm = MegaEvm::new(context(system_db())).with_inspector(Revives); + let revived = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("valid"); + assert_eq!(refusal(&revived), KeylessDeployError::AddressMismatch, "at {gas_limit}"); + assert_eq!(nonce(&plain, deployment.signer), 1, "the plain run spends the nonce"); + assert_eq!(nonce(&revived, deployment.signer), 0, "the reverted call takes the bump back"); + assert!(code_hash(&revived, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + +/// A creation a transaction-level limit stopped is a failed creation like any other, so a revived +/// one is answered as the reverted one above: the constructor's `LOG0` of 2,000 bytes crosses the +/// transaction's data-size limit, which holds the body, the start's two records and 100 bytes +/// more. Without the inspector the call answers the stop as `ExecutionReverted` and keeps the +/// signer's nonce; with it, the creation is revived at an address the deployment did not pin, and +/// the call reverts with `AddressMismatch()`, taking the bump back, and reports no stop. +#[test] +fn test_a_revived_keyless_creation_a_limit_stopped_answers_address_mismatch() { + let prefix = BytecodeBuilder::default().push_number(2_000_u64).push_number(0_u64).append(LOG0); + let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); + let body = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; + let limit = body + 2 * WRITE_RECORD_SIZE + 100; + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + for gas_limit in GAS_LIMITS { + let plain = MegaEvm::new(context(system_db()).with_tx_runtime_limits(limits)) + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("valid"); + let KeylessDeployError::ExecutionReverted { output, .. } = failure(&plain) else { + panic!("the creation did not revert: {:?}", plain.result); + }; + assert_eq!( + MegaLimitExceeded::abi_decode(&output).expect("a limit stop"), + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + "at {gas_limit}: the constructor's log crossed the transaction's limit" + ); + assert_eq!(nonce(&plain, deployment.signer), 1, "the plain run spends the nonce"); + + let mut evm = MegaEvm::new(context(system_db()).with_tx_runtime_limits(limits)) + .with_inspector(Revives); + let revived = evm + .execute_transaction(keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit)) + .expect("valid"); + assert_eq!(refusal(&revived), KeylessDeployError::AddressMismatch, "at {gas_limit}"); + assert_eq!(revived.limit_exceeded, None, "at {gas_limit}: no stop is the call's result"); + assert_eq!(nonce(&revived, deployment.signer), 0, "the reverted call takes the bump back"); + assert!(code_hash(&revived, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY)); + } +} + +/// An inspector sees the creation of a deployment that returned empty code end as a revert, the +/// outcome of the refused deposit, and the call answers `EmptyCodeDeployed`. +#[test] +fn test_an_inspector_sees_an_empty_code_deployment_end_as_a_revert() { + let deployment = Deployment::new(Bytes::new()); + for gas_limit in GAS_LIMITS { + let (outcome, recorder) = inspect(&deployment, Recorder::default(), gas_limit); + assert!(matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. })); + let ends: Vec<_> = + recorder.events.iter().filter(|event| matches!(event, Event::CreateEnd(..))).collect(); + let end = Event::CreateEnd(InstructionResult::Revert, Some(deployment.address)); + assert_eq!(ends, [&end], "at {gas_limit}"); + } +} diff --git a/crates/mega-evm/tests/system/keyless/interface.rs b/crates/mega-evm/tests/system/keyless/interface.rs new file mode 100644 index 000000000..466a38882 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/interface.rs @@ -0,0 +1,31 @@ +//! The errors `IKeylessDeploy` declares, against the error set the `KeylessDeploy` spec page lists +//! for Satin. + +use std::collections::BTreeSet; + +use mega_evm::system::keyless::IKeylessDeploy::IKeylessDeployErrors; + +/// The `KeylessDeploy` spec page. +const KEYLESS_DEPLOY_MD: &str = + include_str!("../../../../../docs/spec/system-contracts/keyless-deploy.md"); + +/// The summary line of the page's block that lists Satin's error set. +const SATIN_ERROR_SET: &str = "Satin (unstable): error set"; + +/// The error signatures the page's Satin block lists: every bullet that is a single code span. +fn documented_errors() -> BTreeSet<&'static str> { + let start = KEYLESS_DEPLOY_MD.find(SATIN_ERROR_SET).expect("the page lists Satin's error set"); + let block = &KEYLESS_DEPLOY_MD[start..]; + let block = &block[..block.find("
").expect("the block closes")]; + block.lines().filter_map(|line| line.strip_prefix("- `")?.strip_suffix('`')).collect() +} + +/// The generated binding declares exactly the errors the spec page lists for Satin, so an error +/// added to or removed from the interface without the page, or from the page without the +/// interface, fails here. +#[test] +fn test_the_interface_declares_exactly_the_documented_errors() { + let declared: BTreeSet<&str> = IKeylessDeployErrors::SIGNATURES.iter().copied().collect(); + assert_eq!(declared.len(), IKeylessDeployErrors::SIGNATURES.len(), "a signature repeats"); + assert_eq!(declared, documented_errors()); +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs new file mode 100644 index 000000000..90a8b9a40 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -0,0 +1,525 @@ +//! The limits a keyless deployment is held to, and what a stop leaves behind. +//! +//! The creation is an ordinary frame below its `keylessDeploy` call, so it is held to everything +//! an ordinary creation is: its share of the data-size budget, the transaction's limits. A limit +//! the creation crosses, its budget or the transaction's, reverts the creation alone, and the call +//! answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start +//! wrote. A limit the call itself crosses — its budget, crossed by the nonce record a failed +//! creation leaves it — reverts the call with the stop, which takes back everything the deployment +//! wrote, the signer's nonce included, and the sender pays for what ran and gets the rest of its +//! gas and its reservoir back. +//! +//! The creation's stop is pinned as a column of the matrix: every limit a creation can cross, +//! from a signer at nonce 0 and at nonce 1, below the execution cap and above it, with and without +//! an inspector that records every frame's end. +//! +//! The last tests pin the three places gas a mechanism grants a frame could leak back to a +//! caller or to the sender: an answer built without a frame, the settlement of a stopped +//! transaction, and the return of the frame's unspent gas. + +use alloy_sol_types::SolError; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, LimitCheck, + LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{PUSH0, REVERT, TIMESTAMP}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + InstructionResult, + }, + primitives::KECCAK_EMPTY, + Database, Inspector, +}; + +use super::{ + detention::{crossing_left, reads_then_burns}, + *, +}; +use crate::common::context; + +/// Init code that fills a fresh slot and deploys a one-byte runtime. +fn filling_a_slot() -> Bytes { + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .build_vec(); + constructor(&prefix, &runtime(1)) +} + +/// The data size a transaction carrying `deployment`'s calldata counts before any frame: its +/// body. +fn body_bytes(deployment: &Deployment) -> u64 { + reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size +} + +/// Runs a `keylessDeploy` of `deployment` at `gas_limit` under `limits`. +fn limited(deployment: &Deployment, gas_limit: u64, limits: EvmTxRuntimeLimits) -> Outcome { + run_with(system_db(), deployment.call_data(LARGE_OVERRIDE), gas_limit, limits) +} + +type Outcome = MegaTransactionOutcome; + +/// The stop a transaction reverted with. +fn stop(outcome: &Outcome) -> MegaLimitExceeded { + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("the transaction did not revert: {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(output).expect("the revert data is a limit stop") +} + +/// The stop a deployment's creation reverted with, reported as its `ExecutionReverted` output. +fn creation_stop(outcome: &Outcome) -> MegaLimitExceeded { + let KeylessDeployError::ExecutionReverted { output, .. } = failure(outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(&output).expect("the creation's revert data is a limit stop") +} + +/// A transaction stopped inside its keyless deployment keeps nothing of it: the signer's nonce +/// is where it was, no code is deployed, no state or history gas beyond the body is spent, no +/// record is kept, and above the execution cap the whole reservoir but the body's history comes +/// back. The sender pays the overhead and what ran. +fn assert_stopped_whole(outcome: &Outcome, deployment: &Deployment, gas_limit: u64) { + assert_nothing_kept(outcome, deployment, gas_limit, 0, ""); +} + +/// [`assert_stopped_whole`], for a signer whose nonce was `signer_nonce`: the transaction leaves +/// it there, whether it touched the signer's account or not. +fn assert_nothing_kept( + outcome: &Outcome, + deployment: &Deployment, + gas_limit: u64, + signer_nonce: u64, + case: &str, +) { + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let nonce = outcome.state.get(&deployment.signer).map_or(signer_nonce, |a| a.info.nonce); + assert_eq!(nonce, signer_nonce, "{case}: the signer's nonce is taken back"); + assert!( + code_hash(outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY), + "{case}: no code is deployed" + ); + let [_, regular, state, history_gas, history_bytes] = beyond(outcome, &reference); + assert_eq!([state, history_gas, history_bytes], [0; 3], "{case} at {gas_limit}"); + assert!(regular >= KEYLESS_DEPLOY_OVERHEAD_GAS, "{case}: the overhead stays spent"); + assert_eq!(outcome.usage.write_records, 0, "{case}: no record is kept"); + if gas_limit > TX_GAS_LIMIT_CAP { + assert_eq!( + outcome.result.gas().reservoir_remaining(), + reference.result.gas().reservoir_remaining(), + "{case}: the reservoir comes back", + ); + } +} + +/// A log that crosses the creation's own data-size budget reverts the creation alone: the call +/// reports `ExecutionReverted` with the stop, the transaction is not stopped, and the signer's +/// nonce is spent. +#[test] +fn test_a_deployment_crossing_its_data_size_budget_reverts_alone() { + let deployment = Deployment::new(logging(2_000)); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(1_000), + ); + // The call's own lane gets the frame cap, and its creation 98% of that. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 980 }); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(nonce(&outcome, deployment.signer), 1); + assert_eq!(outcome.usage.write_records, 1, "the signer's nonce record"); + } +} + +/// The records the creation's start makes are held before the creation is built: a transaction +/// limit that holds one record but not two stops the creation before its init code runs. The +/// start still bumps the signer's nonce, whose record the call keeps within the limit, and the +/// call answers the stop. +#[test] +fn test_the_creations_start_crossing_the_limit_stops_the_creation() { + let deployment = Deployment::new(deploying(&runtime(1))); + let limit = body_bytes(&deployment) + 40; + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit }); + assert_eq!(outcome.limit_exceeded, None, "at {gas_limit}"); + assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); + assert_eq!( + outcome.usage.data_size, limit, + "at {gas_limit}: the signer's nonce record, which meets the limit" + ); + assert!( + code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY), + "at {gas_limit}: no code is deployed" + ); + } +} + +/// A failed creation leaves its creator's nonce record on the call's lane, which no check held it +/// to: a call whose budget cannot hold that record reverts alone with its own stop, and takes the +/// nonce back with it. The outcome names the call's budget, whose crossing produced the result of +/// the transaction's own frame. +#[test] +fn test_the_signers_record_can_put_the_call_over_its_budget() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: 39, + used: WRITE_RECORD_SIZE, + frame_local: true, + }), + "a budget, not the transaction's limit" + ); + assert_stopped_whole(&outcome, &deployment, gas_limit); + } +} + +/// A failed creation by a signer at nonce 1 leaves no record on the call: its nonce bump is taken +/// back, and the record with it. The same budget then holds the call, which answers with the +/// creation's own stop, and the signer stays at 1. +#[test] +fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { + let deployment = Deployment::new(deploying(&runtime(1))); + for gas_limit in GAS_LIMITS { + let outcome = run_with( + system_db().account_nonce(deployment.signer, 1), + deployment.call_data(LARGE_OVERRIDE), + gas_limit, + EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39), + ); + // The call's lane gets the frame cap, and its creation 98% of that. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 38 }); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(outcome.usage.write_records, 0, "at {gas_limit}"); + } +} + +/// A limit that holds the whole deployment lets it through. +#[test] +fn test_a_deployment_within_every_limit_deploys() { + let deployment = Deployment::new(filling_a_slot()); + // The creation gets 98% of what the call has left, rounded down: room for its three records + // and its byte of code. + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(body_bytes(&deployment) + 3 * 40 + 1 + 10); + for gas_limit in GAS_LIMITS { + let outcome = limited(&deployment, gas_limit, limits); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + } +} + +/// An answer built without a frame carries the reservoir the call inherited: a call refused after +/// it paid for the signer's account — the forward capped below the signed gas limit, which only a +/// signed gas limit near the execution cap reaches above it — gives the charge back to the +/// reservoir and the sender gets all of it but the body's history. +#[test] +fn test_a_refusal_after_the_charges_gives_the_reservoir_back() { + let deployment = + Deployment::signed(0, TX_GAS_LIMIT_CAP - 50_000, U256::ZERO, deploying(&runtime(1))); + let gas_limit = GAS_LIMITS[1]; + let outcome = limited(&deployment, gas_limit, EvmTxRuntimeLimits::no_limits()); + assert!(matches!(refusal(&outcome), KeylessDeployError::GasLimitTooLow { .. })); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, _] = beyond(&outcome, &reference); + assert_eq!( + [total, regular, state, history_gas], + [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0] + ); + assert_eq!( + outcome.result.gas().reservoir_remaining(), + reference.result.gas().reservoir_remaining(), + ); +} + +/// And a call refused after the charges of the creation's start — the forward the `CREATE` +/// opcode's regular gas takes below the signed gas limit, which above the execution cap only a +/// signed gas limit just under what the call has left reaches — gives their state and history gas +/// back to the reservoir, and keeps their regular gas, as it keeps the overhead. +#[test] +fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { + let gas_limit = GAS_LIMITS[1]; + let init_code = deploying(&runtime(1)); + // Above the cap the call has what the execution cap leaves once the body's regular gas — all + // the reference spends — and the overhead are paid. The signed gas limit is one less, and is + // part of the calldata the body is priced by, so the two are settled together. + let mut signed = TX_GAS_LIMIT_CAP - 200_000; + let (deployment, left) = (0..10) + .find_map(|_| { + let deployment = Deployment::signed(0, signed, U256::ZERO, init_code.clone()); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let left = TX_GAS_LIMIT_CAP - reference.gas.regular - KEYLESS_DEPLOY_OVERHEAD_GAS; + let settled = left - 1 == signed; + signed = left - 1; + settled.then_some((deployment, left)) + }) + .expect("the signed gas limit settles"); + let outcome = limited(&deployment, gas_limit, EvmTxRuntimeLimits::no_limits()); + let opcode = create_regular(init_code.len()); + assert_eq!( + refusal(&outcome), + KeylessDeployError::GasLimitTooLow { + tx_gas_limit: signed, + provided_gas_limit: left - opcode + }, + ); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [total, regular, state, history_gas, _] = beyond(&outcome, &reference); + let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + opcode; + assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); + assert_eq!( + outcome.result.gas().reservoir_remaining(), + reference.result.gas().reservoir_remaining(), + ); +} + +/// The call gets back what its creation did not spend, the same way whether the creation +/// succeeds or reverts: the transaction spends the overhead, the `CREATE` opcode's regular gas, +/// what the call kept of the creation's start, and the creation's `gasUsed`, and nothing else, +/// below and above the execution cap. +#[test] +fn test_the_unspent_forward_comes_back_on_success_and_revert_alike() { + let succeeding = Deployment::new(deploying(&runtime(1))); + let reverting = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let new_account = entry(GasId::new_account_state_gas()); + for gas_limit in GAS_LIMITS { + let success = limited(&succeeding, gas_limit, EvmTxRuntimeLimits::no_limits()); + let [total, ..] = + beyond(&success, &reference(succeeding.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(deploying(&runtime(1)).len()) + + new_account + + entry(GasId::create_state_gas()) + + 2 * record() + + returned(&success).gasUsed, + "success at {gas_limit}", + ); + + let revert = limited(&reverting, gas_limit, EvmTxRuntimeLimits::no_limits()); + let [total, ..] = + beyond(&revert, &reference(reverting.call_data(LARGE_OVERRIDE), gas_limit)); + assert_eq!( + total, + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(3) + + new_account + + record() + + returned(&revert).gasUsed, + "revert at {gas_limit}", + ); + } +} + +/* ---------- the stop, as a column of the matrix ---------- */ + +/// A limit a deployment's creation crosses. +#[derive(Clone, Copy, Debug)] +enum Crossing { + /// The constructor's `LOG0` of 2,000 bytes crosses the data-size limit. + DataSize, + /// The constructor reads the block's timestamp, then computes past the cap. + Compute, +} + +/// The cap on a read of the block environment the compute crossing runs under. +const COMPUTE_CAP: u64 = 1_000; + +impl Crossing { + const ALL: [Self; 2] = [Self::DataSize, Self::Compute]; + + /// The init code whose run crosses the limit. + fn init_code(self) -> Bytes { + match self { + Self::DataSize => logging(2_000), + Self::Compute => reads_then_burns(TIMESTAMP, 1_000), + } + } + + /// The limits under which a deployment of `deployment`, by a signer at either nonce, crosses + /// the limit, with the stop its creation returns: its kind, its limit, and what it counts as + /// used where the constructor crosses. + fn limits(self, deployment: &Deployment) -> (EvmTxRuntimeLimits, Crossed) { + let limits = EvmTxRuntimeLimits::no_limits(); + match self { + Self::DataSize => { + // The body, the two records of the creation's start and 100 bytes more; the + // constructor's log crosses with all its bytes. + let start = body_bytes(deployment) + 2 * WRITE_RECORD_SIZE; + let limit = start + 100; + let used = start + LOG_BASE_SIZE + 2_000; + ( + limits.with_tx_data_size_limit(limit), + Crossed::new(LimitKind::DataSize, limit, used), + ) + } + Self::Compute => { + // Read at the call's charges and the read's own two gas. The stop lands on the + // first charge of the constructor's loop the cap leaves no room for — after the + // read's `POP` and the push of its counter, 26 gas a round: `JUMPDEST`, `PUSH1`, + // `SWAP1`, `SUB`, `DUP1`, the push of its start and `JUMPI` — and counts as used + // the compute before it. + let charges = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(self.init_code().len()); + let limit = charges + 2 + COMPUTE_CAP; + let left = crossing_left(COMPUTE_CAP, &[2, 3], &[1, 3, 3, 3, 3, 3, 10]); + let limits = limits.with_block_env_access_compute_gas_limit(COMPUTE_CAP); + (limits, Crossed::new(LimitKind::ComputeGas, limit, limit - left)) + } + } + } +} + +/// What a crossing reports: the kind of the stop, its limit, and what it counts as used. +#[derive(Clone, Copy, Debug)] +struct Crossed { + kind: LimitKind, + limit: u64, + used: u64, +} + +impl Crossed { + const fn new(kind: LimitKind, limit: u64, used: u64) -> Self { + Self { kind, limit, used } + } +} + +/// Records the result of every frame it sees end, and rewrites nothing. +#[derive(Default)] +struct Recorder { + /// The frames that ended, deepest first: whether each was a creation, and its result. + ended: Vec<(bool, InstructionResult)>, +} + +impl Inspector, EthInterpreter> for Recorder { + fn call_end(&mut self, _: &mut MegaContext, _: &CallInputs, outcome: &mut CallOutcome) { + self.ended.push((false, outcome.result.result)); + } + + fn create_end( + &mut self, + _: &mut MegaContext, + _: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.ended.push((true, outcome.result.result)); + } +} + +/// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit` under `limits`, without an +/// inspector and under a [`Recorder`]: both outcomes, and the frames the recorder saw end. +fn plain_and_recorded( + db: MemoryDatabase, + deployment: &Deployment, + gas_limit: u64, + limits: EvmTxRuntimeLimits, +) -> (Outcome, Outcome, Vec<(bool, InstructionResult)>) { + let plain = run_with(db.clone(), deployment.call_data(LARGE_OVERRIDE), gas_limit, limits); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Recorder::default()); + let recorded = evm.execute_transaction(tx).expect("the transaction is valid"); + let ended = evm.inspector().ended.clone(); + (plain, recorded, ended) +} + +/// The creation's stop, as a column of the matrix: each limit a deployment's creation can cross — +/// data size and gas detention's compute limit — crossed from a signer at nonce 0 and at nonce 1, +/// below the execution cap and above it, without an inspector and under one that records every +/// frame's end. +/// +/// The creation reverts with the stop, which names the limit the constructor's crossing brings the +/// transaction past: so the crossing is the constructor's, not the creation's start or the call's +/// charges. The call answers it as `ExecutionReverted` with the stop's revert data, and keeps what +/// the creation's start wrote and nothing else of the deployment: from nonce 0 the signer's nonce, +/// spent, and its record; from nonce 1 nothing, the bump taken back. No code is deployed. A +/// compute stop bills what it counts as used past the body — the call's charges, the read, and the +/// constructor's compute up to the charge that crosses the cap — and the call charges nothing on +/// its resume. The transaction reports no stop: the result of its own frame is the call's answer. +/// The recorder sees the creation end with the stop, then the call return, and changes nothing. +#[test] +fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { + for crossing in Crossing::ALL { + let deployment = Deployment::new(crossing.init_code()); + for signer_nonce in [0, 1] { + let (limits, expected) = crossing.limits(&deployment); + let Crossed { kind, limit, used } = expected; + let db = match signer_nonce { + 0 => system_db(), + nonce => system_db().account_nonce(deployment.signer, nonce), + }; + for gas_limit in GAS_LIMITS { + let row = format!("{crossing:?}, signer at {signer_nonce}, gas limit {gas_limit}"); + let (plain, recorded, ended) = + plain_and_recorded(db.clone(), &deployment, gas_limit, limits); + for (column, outcome) in [("plain", &plain), ("recorded", &recorded)] { + let cell = format!("{row}, {column}"); + assert_eq!( + creation_stop(outcome), + MegaLimitExceeded { kind: kind.as_u8(), limit }, + "{cell}" + ); + assert_eq!(outcome.limit_exceeded, None, "{cell}: the call caught the stop"); + assert_eq!(nonce(outcome, deployment.signer), 1, "{cell}: the signer's nonce"); + let records = u64::from(signer_nonce == 0); + assert_eq!(outcome.usage.write_records, records, "{cell}: the nonce's record"); + assert!( + code_hash(outcome, deployment.address).is_none_or(|h| h == KECCAK_EMPTY), + "{cell}: no code is deployed" + ); + if kind == LimitKind::ComputeGas { + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [_, regular, ..] = beyond(outcome, &reference); + assert_eq!(regular, used, "{cell}: computed up to the charge that crossed"); + } else { + assert!(outcome.usage.data_size <= limit, "{cell}: within the limit"); + } + } + assert_eq!( + ended, + [(true, InstructionResult::Revert), (false, InstructionResult::Return)], + "{row}: the creation ended with the stop, then the call returned its answer", + ); + assert_eq!(recorded.result_and_state, plain.result_and_state, "{row}"); + assert_eq!(recorded.gas, plain.gas, "{row}"); + assert_eq!(recorded.usage, plain.usage, "{row}"); + } + } + } +} + +/// A transaction the protocol sends is held to no limit, keyless deployments included: the +/// deployment that a transaction limit stops for a user deploys for a system call. +#[test] +fn test_a_deployment_is_counted_but_not_stopped_under_the_exemption() { + let deployment = Deployment::new(logging(2_000)); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(1); + let mut evm = MegaEvm::new(context(system_db()).with_tx_runtime_limits(limits)); + let outcome = alloy_evm::Evm::transact_system_call( + &mut evm, + mega_evm::system::MEGA_SYSTEM_ADDRESS, + KEYLESS_DEPLOY_ADDRESS, + deployment.call_data(LARGE_OVERRIDE), + ) + .expect("a system call runs"); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the system call did not succeed: {:?}", outcome.result); + }; + let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()).unwrap(); + assert_eq!(ret.deployedAddress, deployment.address); +} diff --git a/crates/mega-evm/tests/system/keyless/mod.rs b/crates/mega-evm/tests/system/keyless/mod.rs new file mode 100644 index 000000000..1c369b637 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/mod.rs @@ -0,0 +1,328 @@ +//! `KeylessDeploy`: the dispatch of `keylessDeploy`, the rules a deployment is held to, and the +//! native creation it runs as — what it deploys, what it is charged, the limits it is held to and +//! what an inspector sees of it. +//! +//! Every case that depends on the pools runs at a gas limit under the execution cap, where the +//! transaction has no state-gas reservoir, and at one above it, where the reservoir pays the state +//! and history gas first ([`GAS_LIMITS`]). + +mod charges; +mod deploy; +mod detention; +mod differential; +mod dispatch; +mod frame; +mod inspector; +mod interface; +mod limits; +mod precedence; +mod rules; + +use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + alloy_consensus::{Signed, TxLegacy}, + constants::TX_GAS_LIMIT_CAP, + satin_gas_params, + system::keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + test_utils::MemoryDatabase, + BucketId, EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, + MegaTransactionOutcome, SaltEnv, TestExternalEnvs, MIN_BUCKET_SIZE, +}; +use revm::{ + bytecode::opcode::{CODECOPY, PUSH0, RETURN}, + context::result::ExecutionResult, + context_interface::cfg::GasId, +}; + +use crate::common::{block, call_tx, context, system_db}; + +/// A gas limit under the execution cap, and one above it. +pub(crate) const GAS_LIMITS: [u64; 2] = [TX_GAS_LIMIT_CAP / 4, TX_GAS_LIMIT_CAP * 2]; + +/// The gas limits a transaction carrying `calldata_len` bytes of calldata runs at: three quarters +/// of the execution cap, below it, where the body's history is paid out of regular gas; and ten +/// times the cap, above it, where the reservoir pays it. +/// +/// The tier below the cap is left out where the body's history at the byte prices in effect leaves +/// it less than 25,000,000 and two new accounts for the rest: no transaction that large can pay for +/// its own body below the cap there. +pub(crate) fn tiers_carrying(calldata_len: usize) -> Vec { + let below = TX_GAS_LIMIT_CAP * 3 / 4; + let room = 25_000_000 + 2 * crate::common::account_state_gas(); + let fits = crate::common::body_history(calldata_len as u64) + room <= below; + [below, 10 * TX_GAS_LIMIT_CAP].into_iter().filter(|&tier| fits || tier > below).collect() +} + +/// The gas limit the tests sign their deployments with. +pub(crate) const SIGNED_GAS_LIMIT: u64 = 1_000_000; + +/// A `gasLimitOverride` above what any transaction here can forward, so the forward is capped +/// to what the call has left. +pub(crate) const LARGE_OVERRIDE: u64 = 10_000_000_000; + +/// The gas price the tests sign their deployments at. +pub(crate) const SIGNED_GAS_PRICE: u128 = 100_000_000_000; + +/// A pre-EIP-155 signed creation, as Nick's Method makes one: a fixed signature (`r = s = +/// 0x2222…22`, `v = 27`) over a transaction nobody holds the key of, so the signer is whatever the +/// transaction's contents recover to. +#[derive(Clone, Debug)] +pub(crate) struct Deployment { + /// The signed transaction, RLP-encoded: `keylessDeploymentTransaction`. + pub(crate) tx: Bytes, + /// Its signer. + pub(crate) signer: Address, + /// Where it deploys: the signer's first creation address. + pub(crate) address: Address, +} + +impl Deployment { + /// A deployment of `init_code` with no value, signed at nonce 0. + pub(crate) fn new(init_code: Bytes) -> Self { + Self::signed(0, SIGNED_GAS_LIMIT, U256::ZERO, init_code) + } + + /// A deployment of `init_code` carrying `value`, signed at nonce 0. + pub(crate) fn with_value(init_code: Bytes, value: U256) -> Self { + Self::signed(0, SIGNED_GAS_LIMIT, value, init_code) + } + + /// A deployment signed with every field chosen. + pub(crate) fn signed(nonce: u64, gas_limit: u64, value: U256, init_code: Bytes) -> Self { + let tx = TxLegacy { + nonce, + gas_price: SIGNED_GAS_PRICE, + gas_limit, + to: TxKind::Create, + value, + input: init_code, + chain_id: None, + }; + let word = U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )); + let signed = Signed::new_unchecked(tx, Signature::new(word, word, false), B256::ZERO); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + let signer = signed.recover_signer().expect("a Nick's-Method signature recovers"); + Self { tx: encoded.into(), signer, address: signer.create(0) } + } + + /// The calldata of a `keylessDeploy` call deploying this, with `gas_limit_override`. + pub(crate) fn call_data(&self, gas_limit_override: u64) -> Bytes { + keyless_deploy_call(&self.tx, U256::from(gas_limit_override)) + } +} + +/// The calldata of a `keylessDeploy` call carrying `tx` and `gas_limit_override`. +pub(crate) fn keyless_deploy_call(tx: &[u8], gas_limit_override: U256) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: Bytes::copy_from_slice(tx), + gasLimitOverride: gas_limit_override, + } + .abi_encode() + .into() +} + +/// Init code that deploys `runtime`. +pub(crate) fn deploying(runtime: &[u8]) -> Bytes { + constructor(&[], runtime) +} + +/// Init code that runs `prefix`, then deploys `runtime`, which it copies from its own tail. +pub(crate) fn constructor(prefix: &[u8], runtime: &[u8]) -> Bytes { + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let tail = u16::try_from(prefix.len() + 11).expect("a short prefix").to_be_bytes(); + let mut code = prefix.to_vec(); + code.extend_from_slice(&[0x60, len, 0x61, tail[0], tail[1], PUSH0, CODECOPY]); + code.extend_from_slice(&[0x60, len, PUSH0, RETURN]); + code.extend_from_slice(runtime); + code.into() +} + +/// A runtime of `len` bytes that stops. +pub(crate) fn runtime(len: usize) -> Vec { + vec![0x00; len] +} + +/// Init code that logs `len` bytes of data and deploys a one-byte runtime. +pub(crate) fn logging(len: u64) -> Bytes { + use mega_evm::test_utils::BytecodeBuilder; + use revm::bytecode::opcode::LOG0; + let prefix = + BytecodeBuilder::default().push_number(len).push_number(0_u64).append(LOG0).build_vec(); + constructor(&prefix, &runtime(1)) +} + +/// A database holding the system contracts, the relayer's balance and `balance` on the signer of +/// `deployment`. +pub(crate) fn db_for(deployment: &Deployment, balance: U256) -> MemoryDatabase { + let db = system_db(); + if balance.is_zero() { + return db; + } + db.account_balance(deployment.signer, balance) +} + +/// Runs the `keylessDeploy` transaction `data` from the relayer over `db` at `gas_limit`, under +/// `limits`. +pub(crate) fn run_with( + db: MemoryDatabase, + data: Bytes, + gas_limit: u64, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + run_nth(db, data, gas_limit, limits, 0) +} + +/// [`run_with`], as the relayer's transaction at `nonce`. +pub(crate) fn run_nth( + db: MemoryDatabase, + data: Bytes, + gas_limit: u64, + limits: EvmTxRuntimeLimits, + nonce: u64, +) -> MegaTransactionOutcome { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx.0.base.nonce = nonce; + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the transaction is valid") +} + +/// Runs a `keylessDeploy` of `deployment` over `db` at `gas_limit`, with no runtime limit. +pub(crate) fn deploy( + db: MemoryDatabase, + deployment: &Deployment, + gas_limit: u64, +) -> MegaTransactionOutcome { + run_with(db, deployment.call_data(LARGE_OVERRIDE), gas_limit, EvmTxRuntimeLimits::no_limits()) +} + +/// What a `keylessDeploy` call that succeeded returned. +pub(crate) fn returned(outcome: &MegaTransactionOutcome) -> IKeylessDeploy::keylessDeployReturn { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the call did not succeed: {:?}", outcome.result); + }; + IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy return") +} + +/// The error a deployment that ran and failed reports in `errorData`. +pub(crate) fn failure(outcome: &MegaTransactionOutcome) -> KeylessDeployError { + let ret = returned(outcome); + assert_eq!(ret.deployedAddress, Address::ZERO, "a failed deployment deploys nothing"); + decode_error_result(&ret.errorData).expect("errorData is a keyless deploy error") +} + +/// The error a `keylessDeploy` call reverted with. +pub(crate) fn refusal(outcome: &MegaTransactionOutcome) -> KeylessDeployError { + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("the call did not revert: {:?}", outcome.result); + }; + decode_error_result(output).expect("the revert data is a keyless deploy error") +} + +/// The nonce `address` ends the transaction with; zero when the transaction did not touch it. +pub(crate) fn nonce(outcome: &MegaTransactionOutcome, address: Address) -> u64 { + outcome.state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// The code hash `address` ends the transaction with, if the transaction touched it. +pub(crate) fn code_hash(outcome: &MegaTransactionOutcome, address: Address) -> Option { + outcome.state.get(&address).map(|account| account.info.code_hash) +} + +/// An account with no code: the target of the reference transactions. +pub(crate) const NOBODY: Address = address!("0x0000000000000000000000000000000000c0ffee"); + +/// The same calldata sent to [`NOBODY`] at the same gas limit: a transaction that pays the +/// intrinsic gas a `keylessDeploy` transaction carrying `data` pays, and nothing else. +pub(crate) fn reference(data: Bytes, gas_limit: u64) -> MegaTransactionOutcome { + let mut tx = call_tx(NOBODY, data, U256::ZERO); + tx.0.base.gas_limit = gas_limit; + MegaEvm::new(context(system_db())).execute_transaction(tx).expect("the transaction is valid") +} + +/// What `outcome` spent beyond `reference`: `[total, regular, state, history, history bytes]`. +pub(crate) fn beyond( + outcome: &MegaTransactionOutcome, + reference: &MegaTransactionOutcome, +) -> [u64; 5] { + let total = |o: &MegaTransactionOutcome| o.result.gas().total_gas_spent(); + [ + total(outcome) - total(reference), + outcome.gas.regular - reference.gas.regular, + outcome.gas.state - reference.gas.state, + outcome.gas.history - reference.gas.history, + outcome.gas.history_bytes - reference.gas.history_bytes, + ] +} + +/// The schedule's entry `id`. +pub(crate) fn entry(id: GasId) -> u64 { + satin_gas_params().get(id) +} + +/// The regular gas the `CREATE` opcode charges its frame for init code of `len` bytes, which a +/// `keylessDeploy` call pays on top of its overhead: the schedule's `create` entry and EIP-3860's +/// cost per word. +pub(crate) fn create_regular(len: usize) -> u64 { + satin_gas_params().create_cost() + satin_gas_params().initcode_cost(len) +} + +/// The history gas of one write record, `WRITE_RECORD_SIZE` bytes, by hand. +pub(crate) fn record() -> u64 { + history(mega_evm::WRITE_RECORD_SIZE) +} + +/// The history gas of `bytes` bytes, by hand. +pub(crate) fn history(bytes: u64) -> u64 { + crate::common::history(bytes) +} + +/// The intrinsic gas a call carrying `data` pays below the execution cap, by hand: EIP-2780's +/// `TX_BASE_COST` of 12,000 and 3,000 for the recipient's access, the calldata at 4 gas a zero +/// byte and 16 a non-zero one, and the history of the body, which spills onto the regular gas +/// where there is no reservoir. +pub(crate) fn intrinsic(data: &[u8]) -> u64 { + let calldata: u64 = data.iter().map(|&byte| if byte == 0 { 4 } else { 16 }).sum(); + 12_000 + 3_000 + calldata + crate::common::body_history(data.len() as u64) +} + +/// A Satin context over `db` reading `envs`. +pub(crate) fn salt_run( + db: MemoryDatabase, + envs: TestExternalEnvs, + deployment: &Deployment, + gas_limit: u64, +) -> MegaTransactionOutcome { + let context = MegaContext::<_, TestExternalEnvs>::new_with_external_envs( + db, + MegaSpecId::SATIN, + ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, + ) + .with_block(block()) + .with_chain(mega_evm::test_utils::zero_fee_l1_block_info()); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + MegaEvm::new(context).execute_transaction(tx).expect("the transaction is valid") +} + +/// The bucket `account`'s own state lives in. +pub(crate) fn bucket(account: Address) -> BucketId { + as SaltEnv>::bucket_id_for_account(account) +} + +/// `envs` with `account`'s bucket at multiplier `m`. +pub(crate) fn crowded( + envs: TestExternalEnvs, + account: Address, + m: u64, +) -> TestExternalEnvs { + envs.with_bucket_capacity(bucket(account), MIN_BUCKET_SIZE as u64 * m) +} diff --git a/crates/mega-evm/tests/system/keyless/precedence.rs b/crates/mega-evm/tests/system/keyless/precedence.rs new file mode 100644 index 000000000..46db0ffa9 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/precedence.rs @@ -0,0 +1,381 @@ +//! Which error a `keylessDeploy` call reports when several rules refuse it: the legacy engine's. +//! +//! The rules are checked in the legacy engine's order, and the one charge it made among them — +//! the signer's account, which the creation's nonce bump creates for an empty signer — is made +//! where it made it: after the signer's rules, with the forward checked right after, before the +//! deploy address and the balance. So each pair of failing rules below reports the error the +//! legacy engine reported for it. What the `CREATE` opcode charges the call for the creation's +//! start is this engine's alone, and comes after every rule: a call a rule refuses is refused +//! with that rule, whether or not it could have paid those charges. The last test pins what those +//! charges refuse on their own, where the legacy engine charged nothing. +//! +//! One pair reports an error the legacy engine never reported: a call carrying value whose +//! arguments do not decode is refused for the value, where the legacy engine ran the bytecode and +//! reverted with empty data. + +use mega_evm::{ + system::keyless::{decode_error_result, KEYLESS_DEPLOY_OVERHEAD_GAS}, + test_utils::MemoryDatabase, +}; + +use super::*; +use crate::common::state_is_free; + +/// The gas limit the matrix's deployments are signed with: 500,000 on top of the state gas of the +/// account the creation adds, at the byte prices in effect, so the creation's charges leave part of +/// it whatever a state byte costs. +fn signed_gas() -> u64 { + 500_000 + entry(GasId::create_state_gas()) +} + +/// What a call is answered with. +#[derive(Debug, PartialEq, Eq)] +enum Answer { + /// A revert with a rule's error. + Refused(KeylessDeployError), + /// An out-of-gas halt. + OutOfGas, +} + +/// A call that fails the rules named, over `db`, carrying `data`, at `gas_limit`. +struct Case { + rules: &'static str, + db: MemoryDatabase, + data: Bytes, + gas_limit: u64, + answer: Answer, +} + +impl Case { + fn check(self) { + let outcome = run_with(self.db, self.data, self.gas_limit, EvmTxRuntimeLimits::no_limits()); + let answer = match &outcome.result { + ExecutionResult::Revert { output, .. } => { + Answer::Refused(decode_error_result(output).expect("a keyless deploy error")) + } + ExecutionResult::Halt { .. } => Answer::OutOfGas, + other => panic!("{}: the call was not refused: {other:?}", self.rules), + }; + assert_eq!(answer, self.answer, "{} at {}", self.rules, self.gas_limit); + } +} + +/// A deployment signed with `gas_limit`, carrying `value`. +fn signed(gas_limit: u64, value: u64) -> Deployment { + Deployment::signed(0, gas_limit, U256::from(value), deploying(&runtime(1))) +} + +/// `db` with code at `deployment`'s address. +fn occupied(db: MemoryDatabase, deployment: &Deployment) -> MemoryDatabase { + db.account_code(deployment.address, Bytes::from_static(&[0x00])) +} + +/// `db` with `deployment`'s signer holding one wei: an account, which its nonce bump does not +/// create. +fn funded(db: MemoryDatabase, deployment: &Deployment) -> MemoryDatabase { + db.account_balance(deployment.signer, U256::ONE) +} + +/// The gas limit, below the execution cap, at which a call carrying `data` has `left` once it +/// paid its overhead. +fn leaving(data: &Bytes, left: u64) -> u64 { + reference(data.clone(), GAS_LIMITS[0]).result.gas().total_gas_spent() + + KEYLESS_DEPLOY_OVERHEAD_GAS + + left +} + +/// `GasLimitTooLow` for a deployment signed with [`signed_gas`], with `provided`. +fn too_low(provided: u64) -> Answer { + Answer::Refused(KeylessDeployError::GasLimitTooLow { + tx_gas_limit: signed_gas(), + provided_gas_limit: provided, + }) +} + +/// Pairs of failing rules that do not depend on the call's gas, at both gas limits: the rule the +/// legacy engine checked first is the one reported. +#[test] +fn test_a_call_two_rules_refuse_reports_the_first_the_legacy_engine_checked() { + let plain = signed(signed_gas(), 0); + let carrying = signed(signed_gas(), 1); + for gas_limit in GAS_LIMITS { + let data = plain.call_data(LARGE_OVERRIDE); + let cases = [ + Case { + rules: "gasLimitOverride below the signed gas limit, and an occupied address", + db: occupied(funded(system_db(), &plain), &plain), + data: plain.call_data(signed_gas() - 1), + gas_limit, + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "the signer's nonce, and an occupied address", + db: occupied(system_db().account_nonce(plain.signer, 2), &plain), + data: data.clone(), + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), + }, + Case { + rules: "the signer's nonce, and a value it cannot fund", + db: system_db().account_nonce(carrying.signer, 2), + data: carrying.call_data(LARGE_OVERRIDE), + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }), + }, + Case { + rules: "the signer's code, and an occupied address", + db: occupied( + system_db().account_code(plain.signer, Bytes::from_static(&[0x00])), + &plain, + ), + data, + gas_limit, + answer: Answer::Refused(KeylessDeployError::SignerHasCode), + }, + Case { + rules: "an occupied address, and a value the signer cannot fund", + db: occupied(system_db().account_nonce(carrying.signer, 1), &carrying), + data: carrying.call_data(LARGE_OVERRIDE), + gas_limit, + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + ]; + cases.into_iter().for_each(Case::check); + } +} + +/// A call that carries value and whose arguments do not decode, or carry a transaction that does +/// not, is refused for the value: the value rule comes before decoding. The same call without +/// value is refused `MalformedEncoding()`. The legacy engine let both fall through to the +/// bytecode, which reverted with empty data. +#[test] +fn test_a_value_bearing_call_that_does_not_decode_is_refused_for_the_value() { + let truncated: Bytes = + IKeylessDeploy::keylessDeployCall::SELECTOR.iter().copied().chain([0; 16]).collect(); + let undecodable_tx = keyless_deploy_call(b"a transaction", U256::from(LARGE_OVERRIDE)); + for gas_limit in GAS_LIMITS { + for (payload, data) in [("arguments", &truncated), ("transaction", &undecodable_tx)] { + for (value, answer) in [ + (0, KeylessDeployError::MalformedEncoding), + (1, KeylessDeployError::NoEtherTransfer), + ] { + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::from(value)); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(tx) + .expect("a valid transaction"); + assert_eq!( + refusal(&outcome), + answer, + "undecodable {payload}, value {value}, at {gas_limit}", + ); + } + } + } +} + +/// Pairs of failing rules one of which is the call's gas, below the execution cap, where the call +/// pays every charge out of the gas it forwards. The signer's account and the forward come before +/// the deploy address and the balance, as they did in the legacy engine; the charges of the +/// creation's start come after every rule, so a rule they would have run out of gas behind still +/// refuses the call. +#[test] +fn test_the_signers_account_and_the_forward_come_before_the_address_and_the_balance() { + let new_account = entry(GasId::new_account_state_gas()); + // What a call left one short of the signer's account has once it paid its overhead. The cases + // that leave it are filtered out below where the account costs nothing. + let short_of_the_account = new_account.saturating_sub(1); + let plain = signed(signed_gas(), 0); + let carrying = signed(signed_gas(), 1); + let carrying_two = signed(signed_gas(), 2); + let small = signed(1_000, 0); + let small_carrying = signed(1_000, 1); + let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); + let cases = [ + Case { + rules: "the signer's account the call cannot pay, and an occupied address", + db: occupied(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), short_of_the_account), + answer: Answer::OutOfGas, + }, + Case { + rules: "the signer's account the call cannot pay, and a value it cannot fund", + db: system_db(), + data: data(&carrying), + gas_limit: leaving(&data(&carrying), short_of_the_account), + answer: Answer::OutOfGas, + }, + Case { + rules: "a forward below the signed gas limit, and an occupied address", + db: occupied(funded(system_db(), &plain), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "a forward the signer's account takes below the signed gas limit, and an \ + occupied address", + db: occupied(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), new_account + signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: "a forward below the signed gas limit, and a value the signer cannot fund", + db: funded(system_db(), &carrying_two), + data: data(&carrying_two), + gas_limit: leaving(&data(&carrying_two), signed_gas() - 1), + answer: too_low(signed_gas() - 1), + }, + Case { + rules: + "an occupied address, and a forward the creation's charges would take below the \ + signed gas limit", + db: occupied(funded(system_db(), &plain), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas()), + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + Case { + rules: "an occupied address, and creation charges the call cannot pay", + db: occupied(funded(system_db(), &small), &small), + data: data(&small), + gas_limit: leaving(&data(&small), 1_500), + answer: Answer::Refused(KeylessDeployError::ContractAlreadyExists), + }, + Case { + rules: "a value the signer cannot fund, and a forward the creation's charges would \ + take below the signed gas limit", + db: system_db(), + data: data(&carrying), + gas_limit: leaving(&data(&carrying), new_account + signed_gas()), + answer: Answer::Refused(KeylessDeployError::InsufficientBalance), + }, + Case { + rules: "a value the signer cannot fund, and creation charges the call cannot pay", + db: system_db(), + data: data(&small_carrying), + gas_limit: leaving(&data(&small_carrying), new_account + 1_500), + answer: Answer::Refused(KeylessDeployError::InsufficientBalance), + }, + ]; + // An account that costs nothing is one any call can pay for: the two cases of a signer's + // account the call cannot pay have nothing to run where a state byte is free. + let free = state_is_free(); + cases + .into_iter() + .filter(|case| { + !(free && case.rules.starts_with("the signer's account the call cannot pay")) + }) + .for_each(Case::check); +} + +/// Above the execution cap the reservoir pays the signer's account, and only a signed gas limit +/// near the cap leaves the forward short of it: the forward still comes before the deploy address +/// and the balance. +#[test] +fn test_the_forward_comes_before_the_address_and_the_balance_above_the_cap() { + let near_cap = TX_GAS_LIMIT_CAP - 50_000; + let plain = Deployment::signed(0, near_cap, U256::ZERO, deploying(&runtime(1))); + let carrying = Deployment::signed(0, near_cap, U256::from(2), deploying(&runtime(1))); + for (rules, db, deployment) in [ + ( + "a forward below the signed gas limit, and an occupied address", + occupied(funded(system_db(), &plain), &plain), + &plain, + ), + ( + "a forward below the signed gas limit, and a value the signer cannot fund", + funded(system_db(), &carrying), + &carrying, + ), + ] { + let outcome = run_with( + db, + deployment.call_data(LARGE_OVERRIDE), + GAS_LIMITS[1], + EvmTxRuntimeLimits::no_limits(), + ); + let KeylessDeployError::GasLimitTooLow { tx_gas_limit, provided_gas_limit } = + refusal(&outcome) + else { + panic!("{rules}: {:?}", outcome.result); + }; + assert_eq!(tx_gas_limit, near_cap, "{rules}"); + assert!(provided_gas_limit < near_cap, "{rules}"); + } +} + +/// What the `CREATE` opcode charges the call for the creation's start can refuse a call no rule +/// refuses: a call that cannot pay it runs out of gas, and one it leaves short of the signed gas +/// limit is refused `GasLimitTooLow` with what it left. The legacy engine charged none of it to +/// the call, and ran such a deployment in its sandbox on what the call had. Above the execution +/// cap the refusal is +/// `limits::test_a_refusal_after_the_creations_charges_gives_the_reservoir_back`. +#[test] +fn test_the_creations_charges_can_refuse_a_call_no_rule_refuses() { + let plain = signed(signed_gas(), 0); + let small = signed(1_000, 0); + let data = |deployment: &Deployment| deployment.call_data(LARGE_OVERRIDE); + let charges = create_regular(deploying(&runtime(1)).len()) + + entry(GasId::create_state_gas()) + + 2 * record(); + let cases = [ + Case { + rules: "creation charges the call cannot pay", + db: funded(system_db(), &small), + data: data(&small), + gas_limit: leaving(&data(&small), 1_500), + answer: Answer::OutOfGas, + }, + Case { + rules: "a forward the creation's charges take below the signed gas limit", + db: funded(system_db(), &plain), + data: data(&plain), + gas_limit: leaving(&data(&plain), signed_gas()), + answer: too_low(signed_gas() - charges), + }, + ]; + cases.into_iter().for_each(Case::check); +} + +/// An out-of-gas at step 14 halts the call, consuming its regular gas, and gives back the state +/// and history gas the call was charged: the transaction's gas used is its gas limit, its state +/// ledger is empty and its history ledger is its body's. +/// +/// Two calls run out at the `CREATE` opcode's regular gas: one whose signer holds a wei, which +/// was charged nothing before, and one whose signer has no account, which step 10 charged its +/// account's state gas first. Below the execution cap that charge spilled onto the regular gas: +/// the halt gives it back to the state ledger and then consumes it with the rest, so the second +/// call's gas used is its whole gas limit too. Neither creation started, so the signer's nonce is +/// unspent. +/// +/// Rules [S15.8], [S15.22]. Expected values `independent`: the gas limit is the transaction's own, +/// and the empty ledgers are zero; the body's history is the schedule's price of its bytes +/// (`constants`). +#[test] +fn test_an_out_of_gas_at_the_creations_charges_consumes_the_regular_gas_alone() { + let small = signed(1_000, 0); + let data = small.call_data(LARGE_OVERRIDE); + for (signer, db, left) in [ + ("holding a wei", funded(system_db(), &small), 1_500), + ("without an account", system_db(), crate::common::account_state_gas() + 1_500), + ] { + let gas_limit = leaving(&data, left); + let outcome = run_with(db, data.clone(), gas_limit, EvmTxRuntimeLimits::no_limits()); + assert!( + matches!(outcome.result, ExecutionResult::Halt { .. }), + "a signer {signer}: {:?}", + outcome.result + ); + assert_eq!(outcome.result.tx_gas_used(), gas_limit, "a signer {signer}: the regular gas"); + assert_eq!(outcome.gas.state, 0, "a signer {signer}: the state gas is given back"); + assert_eq!( + outcome.gas.history, + crate::common::body_history(data.len() as u64), + "a signer {signer}: the history gas is the body's", + ); + assert_eq!(nonce(&outcome, small.signer), 0, "a signer {signer}: no creation started"); + } +} diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs new file mode 100644 index 000000000..52a5b414a --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -0,0 +1,1170 @@ +//! The rules a `keylessDeploy` call is held to before its creation starts, and what a refusal +//! leaves behind: nothing but the regular gas the call spent — the overhead, and after the +//! creation's charges the `CREATE` opcode's regular gas. +//! +//! The rules, their order and the error ABI are the legacy engine's; `precedence` pins the error a +//! call several rules refuse reports. What moved is the balance rule, which asks the signer for +//! the transaction's value alone — a deployment pays no gas out of the signer's balance — and +//! rule 4, which now counts real nonces: a deployment keeps the creation's bump from 0 to 1, and +//! takes it back from 1, as the legacy engine did, unless the signer's own code spent a nonce +//! after it. A signer at nonce 1 stays there however often its deployment fails, whoever submits +//! it, and once it deploys; a delegated signer whose code spends a nonce in its constructor, +//! creating an account at it or not, ends above 1, and is refused thereafter. + +use alloy_primitives::{address, keccak256, Signature}; +use mega_evm::{ + active_satin_prices, + alloy_consensus::TxEip1559, + constants::MAX_INITCODE_SIZE, + system::keyless::{ + tests::{ + CREATE2_FACTORY_CONTRACT, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_TX, + EIP1820_CONTRACT, EIP1820_DEPLOYER, EIP1820_TX, NON_CONTRACT_CREATION_TX, + POST_EIP155_CHAIN_1_TX, + }, + KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + test_utils::{BytecodeBuilder, ErrorInjectingDatabase, InjectedDbError}, + MegaSpecId, MegaTransactionError, TestExternalEnvs, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLER, CREATE, GAS, INVALID, MSTORE, POP, PUSH0, PUSH1, PUSH3, REVERT, STOP, + }, + context::{result::EVMError, CfgEnv}, + context_interface::cfg::GasId, + primitives::KECCAK_EMPTY, + state::{AccountInfo, Bytecode}, + DatabaseCommit, +}; + +use super::*; +use crate::common::state_is_free; + +/// A `keylessDeploy` of `tx` with `gas_limit_override`, over `db`, at `gas_limit`. +fn submit(db: MemoryDatabase, tx: &[u8], gas_limit_override: u64, gas_limit: u64) -> Outcome { + run_with( + db, + keyless_deploy_call(tx, U256::from(gas_limit_override)), + gas_limit, + EvmTxRuntimeLimits::no_limits(), + ) +} + +type Outcome = MegaTransactionOutcome; + +/// A refusal writes nothing: the signer's nonce is where it was and the deploy address holds no +/// code. +fn assert_nothing_written(outcome: &Outcome, deployment: &Deployment, signer_nonce: u64) { + assert_eq!(nonce(outcome, deployment.signer), signer_nonce, "the signer's nonce"); + assert!( + code_hash(outcome, deployment.address) + .is_none_or(|hash| hash == revm::primitives::KECCAK_EMPTY), + "the deploy address holds no code", + ); +} + +/// A deployment of a one-byte runtime, which survives the empty-code check. +fn small() -> Deployment { + Deployment::new(deploying(&runtime(1))) +} + +/// Rule 2: `gasLimitOverride` covers the gas limit the transaction was signed with. +#[test] +fn test_keyless_deploy_gas_limit_too_low() { + for gas_limit in GAS_LIMITS { + let outcome = submit(system_db(), CREATE2_FACTORY_TX, 99_999, gas_limit); + assert_eq!( + refusal(&outcome), + KeylessDeployError::GasLimitTooLow { + tx_gas_limit: 100_000, + provided_gas_limit: 99_999 + }, + ); + } +} + +/// An override equal to the signed gas limit passes rule 2, and the creation runs with exactly +/// that much: signed short of what its creation spends below the execution cap, it runs out of gas +/// having spent all of it. The canonical `CREATE2` factory was signed for a chain that charges no +/// state gas for deployed code: at the spec's prices its 100,000 gas does not cover the code it +/// deposits without a reservoir; above the execution cap the reservoir pays that state gas, and the +/// same gas limit deploys it. +#[test] +fn test_keyless_deploy_gas_limit_exactly_equal() { + let canonical = ( + Bytes::from_static(CREATE2_FACTORY_TX), + 100_000, + CREATE2_FACTORY_DEPLOYER, + CREATE2_FACTORY_CONTRACT, + ); + let short = short_of_their_creation(); + let covered = short.iter().any(|(tx, ..)| *tx == canonical.0); + for (tx, signed, signer, _) in short { + let narrow = submit(system_db(), &tx, signed, GAS_LIMITS[0]); + let KeylessDeployError::ExecutionHalted { gas_used, .. } = failure(&narrow) else { + panic!("expected the creation to run out of gas: {:?}", narrow.result); + }; + assert_eq!(gas_used, signed, "the creation ran on the signed gas limit, and spent it"); + assert_eq!(nonce(&narrow, signer), 1, "the nonce is spent all the same"); + } + if !covered { + // Prices at which 100,000 pays for the factory's code without a reservoir. + let narrow = submit(system_db(), &canonical.0, canonical.1, GAS_LIMITS[0]); + assert_eq!(returned(&narrow).deployedAddress, canonical.3); + } + + let wide = submit(system_db(), &canonical.0, canonical.1, GAS_LIMITS[1]); + assert_eq!(returned(&wide).deployedAddress, canonical.3); +} + +/// What the creation of the public transaction `tx` spends given all the gas it wants: its +/// `gasUsed`, what it spent from either pool, the same below the execution cap as above it. +fn creation_spend(tx: &[u8]) -> u64 { + returned(&submit(system_db(), tx, LARGE_OVERRIDE, GAS_LIMITS[0])).gasUsed +} + +/// A public transaction whose signed gas limit is too little for its creation below the execution +/// cap: its bytes, that gas limit, its signer and the address it deploys at. +type ShortDeployment = (Bytes, u64, Address, Address); + +/// The public transactions whose signed gas limit is too little for their creation below the +/// execution cap, at the prices the schedule was built with. +/// +/// One is signed with a gas less than its creation spends, whatever the prices. The canonical ones +/// join it where their creation spends more than they were signed with: they were signed for chains +/// that charge no state gas for deployed code, and at the spec's prices neither signed gas limit +/// covers the code it deposits. +fn short_of_their_creation() -> Vec { + let init_code = deploying(&runtime(64)); + let spend = creation_spend(&Deployment::new(init_code.clone()).tx); + let one_short = Deployment::signed(0, spend - 1, U256::ZERO, init_code); + let mut short = vec![(one_short.tx, spend - 1, one_short.signer, one_short.address)]; + let canonical: Vec<_> = + CANONICAL.into_iter().filter(|(tx, signed, ..)| creation_spend(tx) > *signed).collect(); + if active_satin_prices().is_constants() { + assert_eq!( + canonical.len(), + CANONICAL.len(), + "at the spec's prices neither covers its code" + ); + } + short.extend( + canonical + .into_iter() + .map(|(tx, signed, signer, address)| (Bytes::from_static(tx), signed, signer, address)), + ); + short +} + +/// The gas limit at which a `keylessDeploy` of `deployment`, carrying `init_len` bytes of init +/// code, leaves the call `forward` to forward to its creation, below the execution cap, for a +/// signer that has an account and a deploy address that is empty: the reference transaction's +/// spend, the overhead, the `CREATE` opcode's regular gas, the created account and the two +/// records, and the forward. +fn gas_limit_forwarding(deployment: &Deployment, init_len: usize, forward: u64) -> u64 { + let intrinsic = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]) + .result + .gas() + .total_gas_spent(); + intrinsic + + KEYLESS_DEPLOY_OVERHEAD_GAS + + create_regular(init_len) + + entry(GasId::create_state_gas()) + + 2 * record() + + forward +} + +/// A signed gas limit the signer's account can take the forward below: 500,000 on top of the +/// account's state gas at the byte prices in effect, so the call can pay for the account out of +/// the forward whatever a state byte costs. +fn signed_above_the_account() -> u64 { + 500_000 + entry(GasId::new_account_state_gas()) +} + +/// The length of the init code the forwarding tests deploy: a one-byte runtime. +fn one_byte_init_len() -> usize { + deploying(&runtime(1)).len() +} + +/// Rule 2 again, once the call has paid for the creation's start: the override is capped to what +/// the call has left, and the capped gas must still cover the signed gas limit. A relayer that +/// sizes its transaction below that is refused, with the capped figure. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself +/// and the reservoir pays the call's state and history charges, so no gas limit leaves the +/// call this little. The refusal above the cap is +/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. +#[test] +fn test_a_forward_capped_below_the_signed_gas_limit_is_refused() { + let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 499_999); + let outcome = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!( + refusal(&outcome), + KeylessDeployError::GasLimitTooLow { tx_gas_limit: 500_000, provided_gas_limit: 499_999 }, + ); + assert_nothing_written(&outcome, &deployment, 0); +} + +/// A transaction that leaves the call exactly the signed gas limit deploys. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself +/// and the reservoir pays the call's state and history charges, so no gas limit leaves the +/// call this little. The refusal above the cap is +/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. +#[test] +fn test_a_forward_at_the_signed_gas_limit_deploys() { + let deployment = Deployment::signed(0, 500_000, U256::ZERO, deploying(&runtime(1))); + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), 500_000); + let outcome = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); +} + +/// The charge for the signer's account comes out of the gas the creation would be forwarded when +/// the transaction has no reservoir, so it can take the forward below the signed gas limit: the +/// same transaction deploys for a signer that has an account and is refused for one that has +/// none. Above the execution cap the reservoir pays the charge, and both deploy. +#[test] +fn test_the_signers_account_can_take_the_forward_below_the_signed_gas_limit() { + // An account that costs nothing takes nothing from the forward. + if state_is_free() { + return; + } + let signed = signed_above_the_account(); + let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); + let new_account = entry(GasId::new_account_state_gas()); + let gas_limit = + gas_limit_forwarding(&deployment, one_byte_init_len(), signed + new_account / 2); + + let funded = submit(db_for(&deployment, U256::ONE), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&funded).deployedAddress, deployment.address, "the control deploys"); + let empty = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!( + refusal(&empty), + KeylessDeployError::GasLimitTooLow { + tx_gas_limit: signed, + provided_gas_limit: signed + new_account / 2 - new_account, + }, + ); + assert_nothing_written(&empty, &deployment, 0); + + let wide = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, GAS_LIMITS[1]); + assert_eq!(returned(&wide).deployedAddress, deployment.address, "the reservoir pays"); +} + +/// Rule 3: the signer is recovered from the signature. `r` above the curve order recovers +/// nothing. +#[test] +fn test_keyless_deploy_invalid_signature() { + for gas_limit in GAS_LIMITS { + let mut corrupted = CREATE2_FACTORY_TX.to_vec(); + corrupted[102..134].fill(0xff); + let outcome = submit(system_db(), &corrupted, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); + } +} + +/// So does `r = 0`, which no signature has. +#[test] +fn test_keyless_deploy_rejects_corrupted_signature() { + for gas_limit in GAS_LIMITS { + let signed = mega_evm::system::keyless::decode_keyless_tx(CREATE2_FACTORY_TX).unwrap(); + let s = signed.signature().s(); + let corrupted = Signed::new_unchecked( + signed.tx().clone(), + Signature::new(U256::ZERO, s, false), + B256::ZERO, + ); + let mut encoded = Vec::new(); + corrupted.rlp_encode(&mut encoded); + let outcome = submit(system_db(), &encoded, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InvalidSignature); + } +} + +/// A different `s` is a different signer, not an invalid signature: the deployment goes to that +/// signer's address, never to the canonical one. +#[test] +fn test_keyless_deploy_modified_s_changes_signer() { + for gas_limit in GAS_LIMITS { + let mut modified = CREATE2_FACTORY_TX.to_vec(); + modified[135..167].fill(0x33); + let outcome = submit(system_db(), &modified, LARGE_OVERRIDE, gas_limit); + let deployed = returned(&outcome).deployedAddress; + assert_ne!(deployed, CREATE2_FACTORY_CONTRACT); + assert_ne!(deployed, Address::ZERO); + assert_eq!( + nonce(&outcome, CREATE2_FACTORY_DEPLOYER), + 0, + "the canonical signer is untouched" + ); + } +} + +/// The transaction must be RLP a legacy transaction decodes from. +#[test] +fn test_keyless_deploy_malformed_encoding() { + for gas_limit in GAS_LIMITS { + for garbage in [&[0xde, 0xad, 0xbe, 0xef][..], &[], &CREATE2_FACTORY_TX[..100]] { + let outcome = submit(system_db(), garbage, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "{garbage:02x?}"); + } + let mut trailing = CREATE2_FACTORY_TX.to_vec(); + trailing.push(0x00); + let outcome = submit(system_db(), &trailing, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding, "a trailing byte"); + } +} + +/// An EIP-2718 typed envelope is not a legacy transaction. +#[test] +fn test_keyless_deploy_rejects_eip2718_typed_envelope() { + for gas_limit in GAS_LIMITS { + let tx = TxEip1559 { + chain_id: 1, + nonce: 0, + gas_limit: 100_000, + max_fee_per_gas: 100_000_000_000, + max_priority_fee_per_gas: 1_000_000_000, + to: TxKind::Create, + value: U256::ZERO, + input: Bytes::from_static(&[0x60, 0x80, 0x60, 0x40, 0x52]), + access_list: Default::default(), + }; + let signed = Signed::new_unchecked( + tx, + Signature::new(U256::from(0x1234), U256::from(0x5678), false), + B256::ZERO, + ); + let mut encoded = vec![0x02]; + signed.rlp_encode(&mut encoded); + let outcome = submit(system_db(), &encoded, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::MalformedEncoding); + } +} + +/// The transaction must be a creation. +#[test] +fn test_keyless_deploy_not_contract_creation() { + for gas_limit in GAS_LIMITS { + let outcome = submit(system_db(), NON_CONTRACT_CREATION_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::NotContractCreation); + } +} + +/// The transaction must carry no chain id: that is what makes it valid on every chain. +#[test] +fn test_keyless_deploy_not_pre_eip155() { + for gas_limit in GAS_LIMITS { + let outcome = submit(system_db(), POST_EIP155_CHAIN_1_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::NotPreEIP155); + } +} + +/// The transaction must be signed at nonce 0: the deploy address is the signer's first. +#[test] +fn test_keyless_deploy_non_zero_tx_nonce() { + for gas_limit in GAS_LIMITS { + let deployment = + Deployment::signed(1, SIGNED_GAS_LIMIT, U256::ZERO, deploying(&runtime(1))); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::NonZeroTxNonce { tx_nonce: 1 }); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// Rule 8: the init code is within the initcode size limit the spec fixes. +#[test] +fn test_init_code_over_the_limit_is_refused() { + let deployment = Deployment::new(vec![0; MAX_INITCODE_SIZE + 1].into()); + // Gas limits that cover the body of a transaction carrying a mebibyte of calldata: its + // history alone is past the narrow limit of the other tests. + for gas_limit in tiers_carrying(deployment.call_data(LARGE_OVERRIDE).len()) { + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!( + refusal(&outcome), + KeylessDeployError::InitCodeTooLarge { + size: MAX_INITCODE_SIZE as u64 + 1, + max: MAX_INITCODE_SIZE as u64, + }, + "at {gas_limit}", + ); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// Init code of exactly the limit passes rule 8. Its zero bytes stop at once, so the creation +/// deploys nothing. +#[test] +fn test_init_code_at_the_limit_is_admitted() { + let deployment = Deployment::new(vec![0; MAX_INITCODE_SIZE].into()); + for gas_limit in tiers_carrying(deployment.call_data(LARGE_OVERRIDE).len()) { + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!( + matches!(failure(&outcome), KeylessDeployError::EmptyCodeDeployed { .. }), + "at {gas_limit}", + ); + } +} + +/// Rule 4: the signer's nonce is at most 1. +#[test] +fn test_keyless_deploy_signer_nonce_too_high() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_nonce(deployment.signer, 2); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerNonceTooHigh { signer_nonce: 2 }); + assert_nothing_written(&outcome, &deployment, 2); + } +} + +/// The two canonical keyless deployments: the transaction, the gas limit it was signed with, its +/// signer and the address it deploys at. Signed for chains that charge no state gas for deployed +/// code: at the spec's prices, without a reservoir, the signed gas limit does not cover the code +/// either deposits. +const CANONICAL: [(&[u8], u64, Address, Address); 2] = [ + (CREATE2_FACTORY_TX, 100_000, CREATE2_FACTORY_DEPLOYER, CREATE2_FACTORY_CONTRACT), + (EIP1820_TX, 800_000, EIP1820_DEPLOYER, EIP1820_CONTRACT), +]; + +/// Anybody may submit a signer's public transaction with a gas limit it cannot deploy on — here, +/// the signed gas limit, which is too little — and make it fail, as often as it likes: the signer +/// ends at nonce 1, and a relayer that forwards enough gas deploys at the signer's address. +#[test] +fn test_failing_attempts_by_anybody_leave_the_address_deployable() { + let short = short_of_their_creation(); + for deploying_at in GAS_LIMITS { + for (tx, signed, signer, address) in &short { + fail_then_deploy(tx, *signed, *signer, *address, GAS_LIMITS[0], deploying_at); + } + } + // Init code that expands memory past what its signed gas limit pays for fails on it, whatever + // the pools. + let expanding = + BytecodeBuilder::default().push_number(0_u64).push_number(0x1_0000_u64).append(MSTORE); + let tight = + Deployment::signed(0, 10_000, U256::ZERO, constructor(&expanding.build_vec(), &runtime(1))); + for failing_at in GAS_LIMITS { + for deploying_at in GAS_LIMITS { + fail_then_deploy( + &tight.tx, + 10_000, + tight.signer, + tight.address, + failing_at, + deploying_at, + ); + } + } +} + +/// Submits `tx` three times with `gasLimitOverride` at its `signed` gas limit, at `failing_at`, +/// and requires each to fail with the signer at nonce 1; then submits it with a large override +/// at `deploying_at`, and requires it to deploy at `address` with the signer still at 1. Returns +/// the state the deployment left, committed. +fn fail_then_deploy( + tx: &[u8], + signed: u64, + signer: Address, + address: Address, + failing_at: u64, + deploying_at: u64, +) -> MemoryDatabase { + let mut db = system_db(); + for attempt in 0..3 { + let outcome = run_nth( + db.clone(), + keyless_deploy_call(tx, U256::from(signed)), + failing_at, + EvmTxRuntimeLimits::no_limits(), + attempt, + ); + assert!( + matches!(failure(&outcome), KeylessDeployError::ExecutionHalted { .. }), + "attempt {attempt} at {failing_at}", + ); + assert_eq!(nonce(&outcome, signer), 1, "attempt {attempt} at {failing_at}"); + db.commit(outcome.result_and_state.state); + } + let deployed = run_nth( + db.clone(), + keyless_deploy_call(tx, U256::from(LARGE_OVERRIDE)), + deploying_at, + EvmTxRuntimeLimits::no_limits(), + 3, + ); + assert_eq!(returned(&deployed).deployedAddress, address, "at {deploying_at}"); + assert_eq!(nonce(&deployed, signer), 1, "the creation's bump from 1 is taken back"); + db.commit(deployed.result_and_state.state); + db +} + +/// A deployment that succeeds after failing attempts leaves the signer at 1, so a resubmission of +/// the same public transaction finds the address taken — `ContractAlreadyExists()`, the answer a +/// deployment that succeeded from nonce 0 gives and the one the legacy engine gave — and not a +/// signer whose nonce is spent. +#[test] +fn test_a_resubmission_after_failures_and_a_deployment_finds_the_address_taken() { + let short = short_of_their_creation(); + for deploying_at in GAS_LIMITS { + for (tx, signed, signer, address) in &short { + let (signer, address) = (*signer, *address); + let db = fail_then_deploy(tx, *signed, signer, address, GAS_LIMITS[0], deploying_at); + let resubmitted = run_nth( + db, + keyless_deploy_call(tx, U256::from(LARGE_OVERRIDE)), + deploying_at, + EvmTxRuntimeLimits::no_limits(), + 4, + ); + assert_eq!( + refusal(&resubmitted), + KeylessDeployError::ContractAlreadyExists, + "{address} at {deploying_at}", + ); + assert_eq!(nonce(&resubmitted, signer), 1, "{address} at {deploying_at}"); + } + } +} + +/// A deployment that succeeds from nonce 1 leaves the signer at 1 too: the creation's bump goes +/// with its record, so the deployment costs exactly one record's history less than the same one +/// from nonce 0, which keeps its bump. The record stays when the creation moved value out of the +/// signer's account, and then stands for that write. +#[test] +fn test_a_success_from_nonce_one_leaves_the_nonce_at_one() { + for gas_limit in GAS_LIMITS { + for (value, kept) in [(U256::ZERO, 0), (U256::ONE, 1)] { + let deployment = Deployment::with_value(deploying(&runtime(1)), value); + let funded = db_for(&deployment, U256::from(1_000)); + let at_zero = deploy(funded.clone(), &deployment, gas_limit); + let at_one = deploy(funded.account_nonce(deployment.signer, 1), &deployment, gas_limit); + assert_eq!(returned(&at_one).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(at_one.usage.write_records, 1 + kept, "value {value} at {gas_limit}"); + let taken_back = 1 - kept; + assert_eq!( + beyond(&at_zero, &at_one), + [taken_back * record(), 0, 0, taken_back * record(), taken_back * 40], + "value {value} at {gas_limit}", + ); + } + } +} + +/// A deployment that fails from nonce 1 keeps nothing of the signer: its records, its data size, +/// its history gas and its history bytes are those of a transaction that bumped no nonce — the +/// reference, which pays the same intrinsic gas and writes nothing — and it spends exactly one +/// record's history less than the same failure from nonce 0, which keeps its bump. +#[test] +fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let at_one = + deploy(system_db().account_nonce(deployment.signer, 1), &deployment, gas_limit); + let at_zero = deploy(db_for(&deployment, U256::ONE), &deployment, gas_limit); + assert_eq!(nonce(&at_one, deployment.signer), 1, "at {gas_limit}"); + assert_eq!(nonce(&at_zero, deployment.signer), 1, "at {gas_limit}"); + + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [_, _, state, history_gas, history_bytes] = beyond(&at_one, &reference); + assert_eq!([state, history_gas, history_bytes], [0; 3], "at {gas_limit}"); + assert_eq!(at_one.usage, reference.usage, "at {gas_limit}"); + + assert_eq!(at_zero.usage.write_records, 1, "the signer's nonce record"); + assert_eq!(beyond(&at_zero, &at_one), [record(), 0, 0, record(), 40], "at {gas_limit}"); + } +} + +/// However a deployment from nonce 1 fails — its init code reverts or halts, it deploys no code, +/// or a limit stops its creation at its start — the signer stays at 1 and its nonce record goes. +/// A creation that deployed no code is refused its empty deposit and reverts, so it keeps neither +/// the record of the account it created nor the value it moved. +#[test] +fn test_every_way_a_deployment_from_nonce_one_fails_leaves_the_nonce_at_one() { + let one = U256::ONE; + // The call's lane gets 39 bytes, and its creation 98% of that: less than its start's two + // records. + let a_share_short_of_the_start = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39); + let cases = [ + ( + "revert carrying value", + Deployment::with_value(Bytes::from_static(&[PUSH0, PUSH0, REVERT]), one), + EvmTxRuntimeLimits::no_limits(), + 0, + ), + ( + "halt", + Deployment::new(Bytes::from_static(&[INVALID])), + EvmTxRuntimeLimits::no_limits(), + 0, + ), + ("no code", Deployment::new(Bytes::new()), EvmTxRuntimeLimits::no_limits(), 0), + ( + "no code carrying value", + Deployment::with_value(Bytes::new(), one), + EvmTxRuntimeLimits::no_limits(), + 0, + ), + ( + "stopped at its start", + Deployment::new(deploying(&runtime(1))), + a_share_short_of_the_start, + 0, + ), + ]; + for gas_limit in GAS_LIMITS { + for (name, deployment, limits, records) in &cases { + let db = db_for(deployment, U256::from(1_000)).account_nonce(deployment.signer, 1); + let outcome = run_with(db, deployment.call_data(LARGE_OVERRIDE), gas_limit, *limits); + failure(&outcome); + assert_eq!(nonce(&outcome, deployment.signer), 1, "{name} at {gas_limit}"); + assert_eq!(outcome.usage.write_records, *records, "{name} at {gas_limit}"); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let [_, _, _, history_gas, history_bytes] = beyond(&outcome, &reference); + assert_eq!( + [history_gas, history_bytes], + [records * record(), records * 40], + "{name} at {gas_limit}", + ); + } + } +} + +/// A signer that sends its own deployment is at nonce 1 once its transaction bumped it, so a +/// deployment that fails leaves it there; it makes no record of its own to take back. +#[test] +fn test_a_signer_that_sends_its_failing_deployment_ends_at_nonce_one() { + let deployment = Deployment::new(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + for gas_limit in GAS_LIMITS { + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx.0.base.caller = deployment.signer; + let outcome = MegaEvm::new(context(system_db())) + .execute_transaction(tx) + .expect("a valid transaction"); + assert!(matches!(failure(&outcome), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&outcome, deployment.signer), 1, "the transaction's own bump alone"); + assert_eq!(outcome.usage.write_records, 0, "at {gas_limit}"); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit); + assert_eq!(outcome.usage.data_size, reference.usage.data_size, "at {gas_limit}"); + } +} + +/// Rule 9: the signer has no code — EIP-3607 for a sender that is not the transaction's. +#[test] +fn test_a_signer_with_code_is_refused() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::SignerHasCode); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// A chain that disables EIP-3607 disables rule 9 with it, as it does for its own transactions. +#[test] +fn test_disabling_eip3607_disables_the_signer_code_rule() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let db = system_db().account_code(deployment.signer, Bytes::from_static(&[0x00])); + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.disable_eip3607 = true; + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(db).with_cfg(cfg)) + .execute_transaction(tx) + .expect("a valid transaction"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + } +} + +/// A chain that disables EIP-3607 does not read the signer's code at all: a node missing the +/// signer's bytecode deploys, where one that holds the rule fails on the read. +#[test] +fn test_a_disabled_eip3607_reads_no_signer_code() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let code = Bytes::from_static(&[0x00]); + let code_hash = keccak256(&code); + let db = || { + let mut db = ErrorInjectingDatabase::new( + system_db().account_lazy_code(deployment.signer, code_hash), + ); + db.fail_on_code_by_hash = Some(code_hash); + db + }; + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.disable_eip3607 = true; + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let outcome = MegaEvm::new(context(db()).with_cfg(cfg)) + .execute_transaction(tx) + .expect("the signer's code is never read"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + + assert_db_error(run_on(db(), &deployment.tx, gas_limit), "injected code_by_hash() error"); + } +} + +/// An EIP-7702 delegation is not code: a signer that delegated deploys. +#[test] +fn test_a_delegated_signer_deploys() { + for gas_limit in GAS_LIMITS { + let deployment = small(); + let delegation = + Bytecode::new_eip7702(address!("0x00000000000000000000000000000000000d1e6a")); + let mut db = system_db(); + db.insert_account_info( + deployment.signer, + AccountInfo { + balance: U256::ZERO, + nonce: 1, + code_hash: delegation.hash_slow(), + code: Some(delegation), + ..Default::default() + }, + ); + let outcome = submit(db, &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + assert_eq!(nonce(&outcome, deployment.signer), 1); + } +} + +/// A delegated signer's own code can spend its nonces while its deployment runs: a constructor +/// that calls the signer runs the delegation, which creates two accounts at the signer's next +/// nonces. Those stay spent, and so does the creation's own bump below them — the settlement +/// takes back nothing — so the nonce never goes back below an account the signer created, and +/// the signer's next creations land at fresh addresses. The signer ends at 4, and a resubmission +/// is refused `SignerNonceTooHigh` at that nonce. A creation that reverts takes the delegation's +/// creations back with it, as does a creation refused its empty deposit: the bump is the last one +/// again, it is taken back, the signer ends at 1, and a resubmission runs and fails as the first +/// did. +#[test] +fn test_nonces_a_delegated_signer_spends_in_its_deployment_stay_spent() { + let delegate = address!("0x00000000000000000000000000000000000d1e6a"); + let creating_twice = Bytes::from_static(&[ + PUSH0, PUSH0, PUSH0, CREATE, POP, PUSH0, PUSH0, PUSH0, CREATE, POP, STOP, + ]); + let calling_the_signer = [PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, CALLER, GAS, CALL, POP]; + let with_suffix = |suffix: &[u8]| Bytes::from([&calling_the_signer[..], suffix].concat()); + let cases = [ + ("deploys", constructor(&calling_the_signer, &runtime(1)), 4), + ("deploys nothing", with_suffix(&[STOP]), 1), + ("reverts", with_suffix(&[PUSH0, PUSH0, REVERT]), 1), + ]; + for gas_limit in GAS_LIMITS { + for (name, init_code, ends_at) in &cases { + let deployment = Deployment::new(init_code.clone()); + let delegation = Bytecode::new_eip7702(delegate); + let mut db = system_db().account_code(delegate, creating_twice.clone()); + db.insert_account_info( + deployment.signer, + AccountInfo { + nonce: 1, + code_hash: delegation.hash_slow(), + code: Some(delegation), + ..Default::default() + }, + ); + let outcome = deploy(db.clone(), &deployment, gas_limit); + let deployed = returned(&outcome).deployedAddress; + assert_eq!(deployed == deployment.address, *name == "deploys", "{name} at {gas_limit}"); + assert_eq!(nonce(&outcome, deployment.signer), *ends_at, "{name} at {gas_limit}"); + for spent in 2..*ends_at { + let created = deployment.signer.create(spent); + assert_eq!(nonce(&outcome, created), 1, "{name}: nonce {spent} at {gas_limit}"); + } + db.commit(outcome.result_and_state.state); + + // The same deployment submitted again, by the relayer's next transaction. + let limits = EvmTxRuntimeLimits::no_limits(); + let again = + run_nth(db.clone(), deployment.call_data(LARGE_OVERRIDE), gas_limit, limits, 1); + if *ends_at > 1 { + assert_eq!( + refusal(&again), + KeylessDeployError::SignerNonceTooHigh { signer_nonce: *ends_at }, + "{name}: resubmitted at {gas_limit}", + ); + } else { + let error = failure(&again); + let as_first = if *name == "deploys nothing" { + matches!(error, KeylessDeployError::EmptyCodeDeployed { .. }) + } else { + matches!(error, KeylessDeployError::ExecutionReverted { .. }) + }; + assert!(as_first, "{name}: resubmitted at {gas_limit}: {error:?}"); + } + assert_eq!(nonce(&again, deployment.signer), *ends_at, "{name}: resubmitted"); + + // The signer's next two creations, its delegation run by a plain call. + let next = [ends_at, &(ends_at + 1)].map(|nonce| deployment.signer.create(*nonce)); + for address in next { + let info = revm::Database::basic(&mut db, address).expect("in memory"); + assert!(info.is_none(), "{name}: {address} is fresh at {gas_limit}"); + } + let mut tx = call_tx(deployment.signer, Bytes::new(), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + tx.0.base.nonce = 1; + let later = MegaEvm::new(context(db)).execute_transaction(tx).expect("a valid call"); + assert!(later.result.is_success(), "{name} at {gas_limit}"); + assert_eq!(nonce(&later, deployment.signer), ends_at + 2, "{name} at {gas_limit}"); + for address in next { + assert_eq!(nonce(&later, address), 1, "{name}: {address} created at {gas_limit}"); + } + } + } +} + +/// A nonce the signer's own code spends in the constructor stays spent whether an account stands +/// at it or not: a delegated signer whose delegation makes one `CREATE` of init code that reverts +/// spends its nonce 2 and leaves nothing at `create(signer, 2)`. The creation's bump below it is +/// kept all the same — the settlement takes the bump back only when it is the last nonce change, +/// and never moves the nonce back under a later bump, which may stand for an account — so the +/// signer ends at 3, and a resubmission is refused `SignerNonceTooHigh` there. +#[test] +fn test_a_delegated_signer_whose_creation_reverts_keeps_every_bump() { + let delegate = address!("0x00000000000000000000000000000000000d1e6b"); + // One `CREATE` of `PUSH0 PUSH0 REVERT`: the nonce is spent and no account is created. + let creating_a_reverting_child = Bytes::from_static(&[ + PUSH3, PUSH0, PUSH0, REVERT, PUSH0, MSTORE, PUSH1, 3, PUSH1, 29, PUSH0, CREATE, POP, STOP, + ]); + let calling_the_signer = [PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, CALLER, GAS, CALL, POP]; + let deployment = Deployment::new(constructor(&calling_the_signer, &runtime(1))); + let delegation = Bytecode::new_eip7702(delegate); + let mut db = system_db().account_code(delegate, creating_a_reverting_child); + db.insert_account_info( + deployment.signer, + AccountInfo { + nonce: 1, + code_hash: delegation.hash_slow(), + code: Some(delegation), + ..Default::default() + }, + ); + let spent = deployment.signer.create(2); + for gas_limit in GAS_LIMITS { + let outcome = deploy(db.clone(), &deployment, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!(nonce(&outcome, deployment.signer), 3, "every bump stays at {gas_limit}"); + let at_spent = outcome.state.get(&spent); + assert!( + at_spent.is_none_or(|account| { + account.info.nonce == 0 && + account.info.code_hash == KECCAK_EMPTY && + !account.is_created() + }), + "nothing stands at {spent} at {gas_limit}: {at_spent:?}", + ); + + // The same deployment submitted again, by the relayer's next transaction. + let mut committed = db.clone(); + committed.commit(outcome.result_and_state.state); + let limits = EvmTxRuntimeLimits::no_limits(); + let again = run_nth(committed, deployment.call_data(LARGE_OVERRIDE), gas_limit, limits, 1); + assert_eq!( + refusal(&again), + KeylessDeployError::SignerNonceTooHigh { signer_nonce: 3 }, + "resubmitted at {gas_limit}", + ); + assert_eq!(nonce(&again, deployment.signer), 3, "resubmitted at {gas_limit}"); + } +} + +/// Rule 5: the deploy address holds no code. The occupancy read goes through the journal, so the +/// deploy address is in the transaction's state — the witness a stateless client replays the +/// refusal from — even though the call reverts. +#[test] +fn test_keyless_deploy_contract_already_exists() { + let db = system_db().account_code(CREATE2_FACTORY_CONTRACT, Bytes::from_static(&[0x60, 0x00])); + for gas_limit in GAS_LIMITS { + let outcome = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists, "at {gas_limit}"); + assert_eq!(nonce(&outcome, CREATE2_FACTORY_DEPLOYER), 0); + assert!( + outcome.state.contains_key(&CREATE2_FACTORY_CONTRACT), + "the occupancy read is in the witness, at {gas_limit}", + ); + } +} + +/// A second deployment of the same transaction finds its address taken. +#[test] +fn test_keyless_deploy_twice_fails_second_time() { + for gas_limit in GAS_LIMITS { + let mut db = system_db(); + let first = submit(db.clone(), CREATE2_FACTORY_TX, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&first).deployedAddress, CREATE2_FACTORY_CONTRACT); + revm::DatabaseCommit::commit(&mut db, first.result_and_state.state); + let data = keyless_deploy_call(CREATE2_FACTORY_TX, U256::from(LARGE_OVERRIDE)); + let second = run_nth(db, data, gas_limit, EvmTxRuntimeLimits::no_limits(), 1); + assert_eq!(refusal(&second), KeylessDeployError::ContractAlreadyExists); + } +} + +/// Rule 6: the signer funds the transaction's value, and nothing else. A signer with nothing is +/// refused a deployment that carries a value. +#[test] +fn test_keyless_deploy_insufficient_balance_zero() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(1)); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// A signer holding part of the value is refused too, and the refusal writes nothing. +#[test] +fn test_keyless_deploy_insufficient_balance_partial() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); + let outcome = + submit(db_for(&deployment, U256::from(9)), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(refusal(&outcome), KeylessDeployError::InsufficientBalance); + assert_nothing_written(&outcome, &deployment, 0); + } +} + +/// A signer holding exactly the value deploys, and the value moves to the contract. +#[test] +fn test_keyless_deploy_balance_exactly_sufficient() { + for gas_limit in GAS_LIMITS { + let deployment = Deployment::with_value(deploying(&runtime(1)), U256::from(10)); + let outcome = + submit(db_for(&deployment, U256::from(10)), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + let balance = |address| outcome.state.get(&address).map(|account| account.info.balance); + assert_eq!(balance(deployment.signer), Some(U256::ZERO)); + assert_eq!(balance(deployment.address), Some(U256::from(10))); + } +} + +/// A deployment pays no gas out of the signer's balance: a signer with nothing deploys a +/// deployment that carries no value, whatever gas price it was signed at. +#[test] +fn test_a_signer_with_nothing_deploys_what_carries_no_value() { + let deployment = small(); + for gas_limit in GAS_LIMITS { + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert_eq!(returned(&outcome).deployedAddress, deployment.address, "at {gas_limit}"); + assert_eq!( + outcome.state.get(&deployment.signer).map(|account| account.info.balance), + Some(U256::ZERO), + ); + } +} + +/// Rule 7: a call that cannot pay the overhead runs out of gas at once, before any rule reads the +/// state: the signer is untouched. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, +/// and the reservoir pays the state charges, so no gas limit leaves the call this little. +#[test] +fn test_a_call_below_the_overhead_reads_nothing() { + let deployment = small(); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); + let intrinsic = reference.result.gas().total_gas_spent(); + let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS - 1; + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_eq!(outcome.result.gas().tx_gas_used(), gas_limit); + assert!(!outcome.state.contains_key(&deployment.signer), "no rule read the signer"); +} + +/// A call that cannot pay for the signer's account runs out of gas before the creation starts: +/// no nonce is bumped and nothing is deployed. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself, +/// and the reservoir pays the state charges, so no gas limit leaves the call this little. +#[test] +fn test_a_call_that_cannot_pay_the_signers_account_runs_out_of_gas() { + // An account that costs nothing is one any call can pay for. + if state_is_free() { + return; + } + let deployment = small(); + let reference = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]); + let intrinsic = reference.result.gas().total_gas_spent(); + // One short of the account, once the overhead is paid. + let short = entry(GasId::new_account_state_gas()) - 1; + let gas_limit = intrinsic + KEYLESS_DEPLOY_OVERHEAD_GAS + short; + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(outcome.result, ExecutionResult::Halt { .. }), "{:?}", outcome.result); + assert_nothing_written(&outcome, &deployment, 0); + assert_eq!(outcome.gas.state, 0, "the halt takes the charges back"); +} + +/// A call refused after it paid for the creation's start — the forward capped below the signed +/// gas limit — keeps none of its state and history: no account was added, so neither the signer's +/// account nor the created one is charged, the refusal writes nothing, and no record is kept. The +/// regular gas the `CREATE` opcode charged stays spent, as the overhead does. +/// +/// Below the execution cap only: above it the transaction's frame is forwarded the cap itself +/// and the reservoir pays the call's state and history charges, so no gas limit leaves the +/// call this little. The refusal above the cap is +/// `limits::test_a_refusal_after_the_charges_gives_the_reservoir_back`. +#[test] +fn test_a_call_refused_after_its_charges_keeps_their_regular_gas_alone() { + // An account that costs nothing takes nothing from the forward. + if state_is_free() { + return; + } + let signed = signed_above_the_account(); + let deployment = Deployment::signed(0, signed, U256::ZERO, deploying(&runtime(1))); + // Enough for everything but the signer's account, which the empty signer adds. + let gas_limit = gas_limit_forwarding(&deployment, one_byte_init_len(), signed); + let outcome = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(refusal(&outcome), KeylessDeployError::GasLimitTooLow { .. })); + let [total, regular, state, history_gas, _] = + beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); + let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(one_byte_init_len()); + assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); + assert_nothing_written(&outcome, &deployment, 0); +} + +/// The signer's account is charged exactly when its nonce is spent: a refused call does neither, +/// a deployment that fails at run time does both. +/// +/// The refusal runs below the execution cap, as the refusals above; the failure runs at both. +#[test] +fn test_the_signers_account_is_charged_exactly_when_its_nonce_is_spent() { + let signed = signed_above_the_account(); + let deployment = + Deployment::signed(0, signed, U256::ZERO, Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + // An account that costs nothing takes nothing from the forward, and refuses nothing. + if !state_is_free() { + let refused = submit( + system_db(), + &deployment.tx, + LARGE_OVERRIDE, + gas_limit_forwarding(&deployment, 3, signed), + ); + assert!(matches!(refusal(&refused), KeylessDeployError::GasLimitTooLow { .. })); + assert_eq!(nonce(&refused, deployment.signer), 0); + assert_eq!(refused.gas.state, 0); + } + + for gas_limit in GAS_LIMITS { + let failed = submit(system_db(), &deployment.tx, LARGE_OVERRIDE, gas_limit); + assert!(matches!(failure(&failed), KeylessDeployError::ExecutionReverted { .. })); + assert_eq!(nonce(&failed, deployment.signer), 1); + assert_eq!(failed.gas.state, entry(GasId::new_account_state_gas())); + } +} + +/// A database read a rule needs fails the transaction with the database's error: the deploy +/// address's, whose occupancy rule 5 reads. +#[test] +fn test_a_failed_read_of_the_deploy_address_fails_the_transaction() { + for gas_limit in GAS_LIMITS { + let mut db = ErrorInjectingDatabase::new(system_db()); + db.fail_on_account = Some(CREATE2_FACTORY_CONTRACT); + assert_db_error(run_on(db, CREATE2_FACTORY_TX, gas_limit), "injected basic() error"); + } +} + +/// The occupancy read never loads the deploy address's code, so a node that has the account but +/// not its bytecode — a stateless client's witness — still refuses an occupied address with +/// `ContractAlreadyExists`, rather than failing. +#[test] +fn test_the_occupancy_read_needs_no_code() { + for gas_limit in GAS_LIMITS { + let code = Bytes::from_static(&[0x60, 0x00]); + let code_hash = keccak256(&code); + let mut db = ErrorInjectingDatabase::new( + system_db().account_lazy_code(CREATE2_FACTORY_CONTRACT, code_hash), + ); + db.fail_on_code_by_hash = Some(code_hash); + let outcome = + run_on(db, CREATE2_FACTORY_TX, gas_limit).expect("the occupancy read needs no code"); + assert_eq!(refusal(&outcome), KeylessDeployError::ContractAlreadyExists); + } +} + +/// The signer's read, which rules 4 and 9 need, fails the transaction the same way. +#[test] +fn test_a_failed_read_of_the_signer_fails_the_transaction() { + for gas_limit in GAS_LIMITS { + let mut db = ErrorInjectingDatabase::new(system_db()); + db.fail_on_account = Some(CREATE2_FACTORY_DEPLOYER); + assert_db_error(run_on(db, CREATE2_FACTORY_TX, gas_limit), "injected basic() error"); + } +} + +/// A `keylessDeploy` of `tx` over `db`, at `gas_limit`. +fn run_on( + db: ErrorInjectingDatabase, + tx: &[u8], + gas_limit: u64, +) -> Result> { + let mut call = call_tx( + KEYLESS_DEPLOY_ADDRESS, + keyless_deploy_call(tx, U256::from(LARGE_OVERRIDE)), + U256::ZERO, + ); + call.0.base.gas_limit = gas_limit; + MegaEvm::new(context(db)).execute_transaction(call) +} + +/// Requires `result` to be the database error `expected` names. +fn assert_db_error( + result: Result>, + expected: &str, +) { + match result { + Err(EVMError::Database(error)) => { + assert!(error.to_string().contains(expected), "got: {error}"); + } + other => { + panic!("expected a database error, got: {:?}", other.map(|o| o.result_and_state.result)) + } + } +} + +/// A SALT lookup a charge needs fails the transaction with the cause the environment reported, +/// for either of the two accounts the call charges: the price is never guessed. +#[test] +fn test_a_failed_salt_lookup_fails_the_transaction() { + // A charge that costs nothing costs nothing at any capacity, and the engine asks for none. + if state_is_free() { + return; + } + for gas_limit in GAS_LIMITS { + let deployment = small(); + for failing in [deployment.signer, deployment.address] { + let bucket = + as mega_evm::SaltEnv>::bucket_id_for_account(failing); + let envs = + TestExternalEnvs::::new().with_failing_bucket(bucket, "salt down".into()); + let context = + mega_evm::MegaContext::<_, TestExternalEnvs>::new_with_external_envs( + system_db(), + MegaSpecId::SATIN, + mega_evm::ExternalEnvs { salt_env: envs.clone(), oracle_env: envs }, + ) + .with_block(crate::common::block()) + .with_chain(mega_evm::test_utils::zero_fee_l1_block_info()); + let mut tx = + call_tx(KEYLESS_DEPLOY_ADDRESS, deployment.call_data(LARGE_OVERRIDE), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + match MegaEvm::new(context).execute_transaction(tx) { + Err(EVMError::Custom(message)) => { + assert!(message.contains("salt down"), "{message}") + } + other => panic!( + "expected the SALT failure, got {:?}", + other.map(|o| o.result_and_state.result) + ), + } + } + } +} diff --git a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap new file mode 100644 index 000000000..d9448bd75 --- /dev/null +++ b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap @@ -0,0 +1,153 @@ +--- +source: crates/mega-evm/tests/system/keyless/differential.rs +expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": cases.len(), \"runs\": cases.len() * 4, \"bytes\": record.len(),\n \"lines\": record.lines().count(),\n }, \"cases\": cases,\n})" +--- +{ + "cases": [ + "rule: value @ 50000000 | keccak256=0xb5a5ac86d1fae7f5e736ca81732ad3c9d376a7bbac67681509c8c11cad0fe21e", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0x8cb374010ef32a5b928292a27304c9ff3df52dc6e29bb7dc3378cbea850ae292", + "rule: arguments that do not decode @ 50000000 | keccak256=0x4873273b34dd03636298cf421a82fa400e22c641ca56fea88d493e6d759c138c", + "rule: malformed transaction @ 50000000 | keccak256=0x8736f4dcd9908c3bd36c0b87bebef88fc498fb79c412e8710b84f624f5ef2304", + "rule: a trailing byte @ 50000000 | keccak256=0x6d63b733472ee70ca12153d130895554e40d3576812f5be0e881c43c152cd093", + "rule: not a creation @ 50000000 | keccak256=0x11925b46a5532a3c576d8a095b29b86cd873a33bbd523481641138a9296cd2c7", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0x65165db7ef0c4d75c7d0db224328b34b50bdeb792624bf21212e55f4cd95dfe9", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x8b7363b60e2b5e351baa81fca15777fb579647fa7754835a4f776da548966267", + "rule: override below the signed gas limit @ 50000000 | keccak256=0x4c688e0f80991bb11360110133e41549a0dedfafc587ab1b3b2646c1032fce5f", + "rule: invalid signature @ 50000000 | keccak256=0x336f5ea6b4275fc3d79318d8eb9a6d5f53efbb87115c458282fb25e34b8d7688", + "rule: signer nonce 2 @ 50000000 | keccak256=0x784863cbfebafe7f52b34279b301fefd3fe22a1d3a40d20a12f669a36efecc8f", + "rule: signer with code @ 50000000 | keccak256=0xdf3bde8c053f4f048fc1d3a40ed8c1700e056bc631adc33bf36a95663534f997", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc990151441bd899dd9a9c441f70e395ae898e580c2d23dc162b10f4da2e2ba21", + "rule: occupied address @ 50000000 | keccak256=0xfe77891e1596dfc0e17c6aa4b342d2d4e20ae2c8d7f30162ec01134fb186a432", + "rule: value the signer cannot fund @ 50000000 | keccak256=0xbdf2d161642260839f7abd86b915c550fb7981b53605cbc47de42824a8632915", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x854194a30e818cbc3e9e62adbcd5e9e6a0892b7ff6f9cf8fc94496388e20f705", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xaa0b7d00ffbb61a885bed9e69808248023f4d9cf6a527f94591e79ae8391f6ea", + "deploys from nonce 1 @ 50000000 | keccak256=0x1e38b97533ce81f692e2447bf2cc32a6469210d30e0a6ba5a04e2c81663ffb11", + "the address already has a balance @ 50000000 | keccak256=0x1c0f949828b4bc72f1baf27f0b744b9f15ccbe227fcce4ea5c59bbdcc3b827f4", + "moves value @ 50000000 | keccak256=0xd2beb5e62d347eba371882f82a4e30318fbbc9d43b0e57df063b9049f53bebf7", + "moves value from nonce 1 @ 50000000 | keccak256=0x0bdc41e79d10e1e4ea7b68f35e5556790d45cda9551f6761707bef4496d94e59", + "the CREATE2 factory @ 50000000 | keccak256=0xb2ecb5cf3ea5d5fbaaf3fce280431d390fe86795538c8ad1fff617dde998e5b4", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x3ad22e63f14ded44a13f1e15bab3451f03d9c6fc4e33ade9a66d08626f29b75e", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x8909f08d1f86bb0af70c417b964ba8d79ff369bcb3558c6a84f232989e64fd46", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xdd4a8355d943e2f22af2fdec3c38e37c5dd7ddc63613c0d9e72b500b61136807", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df27a735363f4758e4bd567ffd2cde36f7f9f7f88b088a763f2dea01d3985f2", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xb80e17a2e7939e95262c7efb0f7809a708c46f9ffbacc61bb7012b9228e06cba", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x25606317ab5eba31abfcbc5f24421a37e94aed0e04e53ed4edda18bfb18d2df7", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x27077cb99c3f49dcf9c6f9041fe2ffb1b26437a31a32b82807c9a3411c9c2efe", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x17c7152fe5947693070eb1627f4f858975b5403cce1e0ae07ba25e3a292f6475", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x265bc4dd1e96384237e9b90cebd4be1d68f3a8f7b6a6607804bebca25894f552", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x751a90caf62483d4706d2367d403f1c9d793cc3d12ed41ab96f2098459986690", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x9c37a4c741b5dbecdec991084171b2f36a07aa8dd1ebea9f6568a0359c927917", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x2ec59b5a0ebe01e93f5d791d951f2cf0149ca9fbfa30aa14534ce3a2226117f7", + "a constructor out of gas @ 50000000 | keccak256=0xbbeb48fca5fe19e74924ea6bfd705899920f01410ebb67f8ce64cd0c0baae4a7", + "the signer sends it @ 50000000 | keccak256=0xf4e163092bc6483934a37e6069b79be53cba1090721dfa1c4b783db7c8f78a9d", + "the signer sends it, and it reverts @ 50000000 | keccak256=0x57ef3326c672cfbe88fc9e7828a9e7d8deba35e2876b18153b2f6429ff165660", + "a delegated signer @ 50000000 | keccak256=0x0064a10239803109ee59bd0d16911f7decf55a346d05d57e18dce03e84fa99d0", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xcd8b9ea08cc5d3e4877320057b96181c0483eaa28d99f08469468b15ea5d3d59", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x7c33d51d018dd7be35a4727c89a401d5d07ee0ff1712cf4a04fe3a660d95d800", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x55a77222c7212b63b30697325a075db2bcb1e0d3a290678eeaa96927a5422db3", + "limit: compute, nonce 0 @ 50000000 | keccak256=0xb60e1f212cff27717b50251f22920f60a266d67387cffb4886d9bf1097bdadff", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x9e2e2b613e18eabd9a69df5ddd3204e0f8d663621abcedef4e8367f0db09baa9", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x6c591038e8021803ab4a3f338e45878adf3917f1345899376d715e746d8d2f64", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x92c4b677efbf06476c5b9c9aa7e85e4cf3923af232d571eb6664ecd6fb7476a6", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x4286eada20e5f558e7c2ed6c826d15fdb4d3d50186e43da02a4d77655b7a4cd1", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x2d65b3a7fdb37ae17b12ab3c9b9dec67fd93bf92b365d1b86b26a3bebff461ea", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xf7a1feafa45b6895ff67602578ba339bf8e037bade29b6271e67d2e1797e3782", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x8800b8030288909004fea33f41c96fc7c97e77342c75d3c1b51dcae69390d796", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xdf3dbf511f3df59eaa39d299e5d2cb0a80712cbf8ab0ad577f4dffe6f1cea31d", + "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", + "limit: the default limits @ 50000000 | keccak256=0x401e8a4d34c0a257a9f6d5eb3c191ef9e04259932d15df8f69ef9d284c44597d", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x67d17bdcceef5522f067097fb8b5bb9535b7e3c50edfc735b7a17281baa83a79", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xee5119ad3ae3a1ed755fa53d53e1dce456fb500e2142cb3ab4cddbc6c5ef2a93", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xd36808e24a3e4424b5c1983330c2b072a37aadd913bb8f7bfc6f40a93c7aa762", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xee6c92b0634bb05ad67f16e49fbee64807792ed5210108bb7227a6e0a44c52ea", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xda6467b28250e76945cd72fb1c61e87e4ff082c572e77c699398a8986702ecb1", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x476ebf8d0d9b175a438951231459d7eff3e3d4cff678fdf874926c58c66e1103", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x30e7f681371492a39eb7b8cce401b2d3305ac108573b9b31904caf0d84c45172", + "not dispatched: version() @ 50000000 | keccak256=0x1bcdfb0c443aedd9aa2dc040e14363bb98e50e81a143c794ed140aa08997127a", + "not dispatched: no selector @ 50000000 | keccak256=0x472f5c2dcd74cee319c67289882d7ae5de0827e9ab51e3189cc994f9030a8c41", + "not dispatched: from a contract @ 50000000 | keccak256=0x1c294e98bc947c88900950d97d417766b82b79a0730db66c83325f049a72e59c", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x82ece1017f1c33999f1543b189848287c03fafd8abab52e663bde37910d48caf", + "no contract code @ 50000000 | keccak256=0x61a84ade88a26edc2149aadbdff8cf04d12724cff24b5177848f93ef00e41e53", + "a system call @ 50000000 | keccak256=0xa0f9654dc5d720d585bd5262f59c3eb57dfc5e0a2e2cfbb4a4d4195d1bb8e582", + "rule: value @ 400000000 | keccak256=0xd303c37d1d7da78c74d1a96a932bcb273b9fdc308308f4006413974f816f1061", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0x90ac683d459875174607b7de159993d754ffbfff2d1bde2f45327e31eff58a30", + "rule: arguments that do not decode @ 400000000 | keccak256=0xc2291f0a80a04b8650aee76c9bd25d4efb87a1197f98e511fb254121d900eb1a", + "rule: malformed transaction @ 400000000 | keccak256=0x483bd928fe503c1c518a50616f83f71abf2e5cb62bfde657f3bb76f422c690c1", + "rule: a trailing byte @ 400000000 | keccak256=0xf2f566ffc210e9e80e3d61f995cb7fbe4aeb13753a717e637754e5f586dd28e7", + "rule: not a creation @ 400000000 | keccak256=0x51107b2d6b41035c93f36a9473aaf257606f435d3e4309f399308a140654e8a5", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0x4ebf62eef276a4b331f8a06f51dea3fd8498df29aa0f4601e45378917ac30b4e", + "rule: signed at nonce 1 @ 400000000 | keccak256=0xe52fdae23846ea20448d0f1718077ac94f32b9974fd0a7715a19bde74255eeae", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x90e4f5261d501523f740ccc40dd40eb30e9e5b7f89cc7e14e9f27cba2f1b9a37", + "rule: invalid signature @ 400000000 | keccak256=0x520a8ea364be745edac070d2b7647b72009651c15cc92c89f31e7275d92b5890", + "rule: signer nonce 2 @ 400000000 | keccak256=0xbd17b75de1e42505f2ee5082ccc16a3311baa780b8692a84d77ceec24b4b893e", + "rule: signer with code @ 400000000 | keccak256=0xec1da80a88bfab4fd9508199c44446a7a2712b502e2e01c249836b10e5d0c7e4", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xf194b8d24aff31661c0ab3bd59a18f006b92ce704683ad7237294a2bd7c7e423", + "rule: occupied address @ 400000000 | keccak256=0xbdc9f465f12c2e0f064ee17721cb8b7124e5bd348daf8ff08488ea72aee8df01", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x1e190910f68843e409de4da0c031f3c1e29b9bbb9310b781891c55b1cad48b6a", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x404d2ce242ff28ee98306359e5ad4b216e74387e803f08a5803d3c47aa0ae764", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xaa02134b6ab8240d6425e5e3ee34b4d035790c4d78995cc721001941564afcb5", + "deploys from nonce 1 @ 400000000 | keccak256=0x8b1ccbd6d099d0e1b1371aec903a117c33a2a3b398a355098ab4a37e239d2102", + "the address already has a balance @ 400000000 | keccak256=0x23b1e10d7f6d8135f85779bdaa1ee01943b79b711810cbcf2355dce52626cfb8", + "moves value @ 400000000 | keccak256=0x92c5f7758579e2ea93bd39c77e516e03476c6c66eb65aac6c31ccc79bf0d5881", + "moves value from nonce 1 @ 400000000 | keccak256=0x8d87dc75052ef30e13e395be1b673b7a874f843c85bfd0bf8c33ebc09188827c", + "the CREATE2 factory @ 400000000 | keccak256=0xddc26d1ec888e72def99e14f179859577a6d5c263db65710414136b00f784636", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xcbf6d3addfc90a9b82ef149891785585747b23b84e6e6feea48408c0927b05fb", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x4e8ae911031010a24c172fd27a23a45e572301e31d8e3942c9b78958fc1c812b", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x11d6d8106eec4144fb4b27aa8048e61ebd3e28ff5e34a3ab258e58870c2029be", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x58da2c85e1b4aed114d883890f022c19bc6ab5306bf321d91499d43bc74fe1ee", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe0964b9f5609b93ab45e0fb18d0d641dc29de37d524eb743b5010334d5789fce", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0xf652556af0037df5691da20eda38055aed1ab41a0ad98fae98979bbe4e1c165c", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x6c0ecb273aac09d6ad165e7b627ef64bd9df6fc70e6e82c353dc440d5c96b8f7", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x7a3b943b6d397f733c8cbf3f4434feae3b84079f10aa6fd9ee7b2873aad76b19", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x95d24bcd22a84c68dffab292724f1e7c796a6b75c3df83e538bf81323747ef75", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x433ce029fff43e9d2a3293c22c889d4f1daff43d301460404e24bd71f846cba9", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xf873d861f34095986d68362bd6931829e01d2ec3ce8e4db6fdb888ad786ddd64", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xe982dd88cd68a044a422609dc8934c114c048189a82860d730ac0334256c82cd", + "a constructor out of gas @ 400000000 | keccak256=0x27652b56760f6fcf1213bc170730a622ecb6c8c7fcc4269ee80d62304eb79f4a", + "the signer sends it @ 400000000 | keccak256=0xd78efd6fd17a7921cee7edcefbf4049630fc2fe902c65969f3e2e1d10db65c10", + "the signer sends it, and it reverts @ 400000000 | keccak256=0xfadd6b105b17e3e8173859cc7ea6e21f3058d66859c3f772e8b993e6022f035c", + "a delegated signer @ 400000000 | keccak256=0x75dcb0c5b12fcfdc2ec9d5fb412f2a356d2b6b4c08498f592cb77d695f24fade", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x912a471ac573f1137c7ff715bbd4c716d896290ea34c38918f341dd5bd4fcd7c", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xd7cb0a921f3295e113674bc4766d4d1c846e169fe1aeb479f30060b613904a68", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x34226a40534a6d1a5db718843ddf4ed03dd8e88c2dc532a9d1277a908efbaf17", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x220083af3453245d7157fce25daf5ae7b146135fe68a4e67fb957b3081ae5f1f", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfe881a80d9f1ea7971209d7555df06b46c5657581f03b17ba771a2c62a2c0875", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x1b9c5fa7ce5f8c7720eb855681d2ce4c242161487366162aa11f92a0fe795f0f", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ae6445d4fc7034526b72b03f278548083826e5f864ea499fca9a38c8fba127c", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x5adb3dfbb10b12745e6ae864bd4b245ba9a18b438615f6d5f3caa277aeb78f99", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x1730186a0ab9121039c156b8c1aaa81326de8a4169a409783d8960467ca16a6f", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x713d112b4aac78b020780ba0f2d604f45ea2e2f35eccb200ff28cedca809939c", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xae24e0359fe82a35095090953c820f194176cb9312f8f0c76d0a3e9b2d310747", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x9891361cdbebda97af570c4a61f0857a55e8696f1707c5a7df546895ab4a0476", + "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", + "limit: the default limits @ 400000000 | keccak256=0x53c838e3841fda75efc979f830a995785fd6053d207e339657d4326c087b15c6", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x6b31a69eab1eea9f014065acfc3616431a7153c9a951dbbfbb8dc4c02c496d10", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x70c93c1e49bb3f82ee27b6df2e74542f134daf45511344c7b06af84148b15c01", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa41b5f6fd60a0a7154a11d40792fb6c273c69b21e49c5e4e4500c48a7c74ad95", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x767616227fc4acae739ee2d88a2d706b4dd8506312cad721ca51dd8f3e46e5ff", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x422863b3415771d5169477ca5fc7f3c49012fce27dd20287dcb57129ead7977f", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x02747b270c6ef30361086a8b120b3a9a3b7368ffc212402eadf2ea09833dc6e9", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xfc8b374ddae00ab903e7c7eb7e61a3b6b327365514d104289baca17db3c63289", + "not dispatched: version() @ 400000000 | keccak256=0x21d0fa310f4524f0b6e8506cf6ba99eb84418b6e3f0ddcb2e0deb6003b207fd0", + "not dispatched: no selector @ 400000000 | keccak256=0x68cfd5c7dbdde76046afb03872c58b7c798d53eaea467a999c9f7b3635da9eed", + "not dispatched: from a contract @ 400000000 | keccak256=0x60fbdbf02f2571dd99675222f8697d42508b159a9d424852f19aa3a1f2148c51", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x906b081db7ac18f4d82e58ea150ff78a00919fd4d4234d2b0f9f5ac93a541cbc", + "no contract code @ 400000000 | keccak256=0xafac51c3747f80833d5f3296750254d077e3bf6c2d6cec6c36cd8555993ac0dc", + "a system call @ 400000000 | keccak256=0xff3ddad83eca747c58bae960be9ebdba8ab07a3794a8014a8b1721ea8778a416", + "out of gas: the overhead @ 161535 | keccak256=0xe2b170867ee82b5c184c55d46183a6b0f757d90341f439ef72e7a43f2b775a85", + "out of gas: the signer's account @ 162536 | keccak256=0xdfe860c27a35a9c33d54e3e47c64c4afc141c4bb6cabfc87f45cf12df47c8052", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x07b0e90b13e66371d8d7abb066a23367672a4bc8899b77d381aac2b0e84f53e4", + "out of gas: the creation's charges @ 163024 | keccak256=0x589fee35bc1e64ba2ee3e7a6c5ad7e9eb8f84f54c82657a285cfb10f31823b50", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1c92a67f868f90f76bb5072ab6e2dbe42a4a60d64d31e739dafd3f5dd1b53178", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0xfc312c015b3d41364fc2ad03a1b68ab5e28f1d8b2b6cb360058df6360212c280", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x0f84ba12e978600a79b6d268f088a54cd2a15d063ce1f8ebe91dce8e99f7d828", + "rule: init code over the limit @ 150000000 | keccak256=0xa2498a026c354cd59572ab576b85a982356e60b06704fb79a8a6fe21717a91d3", + "rule: init code over the limit @ 2000000000 | keccak256=0x8e0e07266b270414f4eb958872388f1a26baf80ff2262daba5da7553b7435e8e" + ], + "summary": { + "bytes": 2392466, + "cases": 139, + "lines": 11444, + "runs": 556 + } +} diff --git a/crates/mega-evm/tests/system/limit_control.rs b/crates/mega-evm/tests/system/limit_control.rs index a252b7002..03c0eca3a 100644 --- a/crates/mega-evm/tests/system/limit_control.rs +++ b/crates/mega-evm/tests/system/limit_control.rs @@ -4,23 +4,16 @@ use alloy_primitives::{Bytes, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, NON_ZERO_TRANSFER_REVERT_DATA}; -use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL, STATICCALL}; +use revm::bytecode::opcode::{CALL, CALLCODE, DELEGATECALL}; -use crate::common::{ - call_tx, calls_with, output, revert_data, run, split_outcome, system_db, with_contract, - CONTRACT, GAS_LIMIT, -}; +use crate::common::{call_tx, output, revert_data, run, system_db, GAS_LIMIT}; const REMAINING_COMPUTE_GAS: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; const NOT_INTERCEPTED: [u8; 4] = IMegaLimitControl::NotIntercepted::SELECTOR; /// A call from a contract to the limit control contract, run as a transaction. fn through_contract(scheme: u8, data: &[u8], value: u64) -> (bool, Bytes) { - let code = calls_with(scheme, LIMIT_CONTROL_ADDRESS, data, value); - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - let outcome = output(&result); - let (status, data) = split_outcome(&outcome); - (status, Bytes::copy_from_slice(data)) + crate::common::through_contract(LIMIT_CONTROL_ADDRESS, scheme, data, value) } /// Decodes what `remainingComputeGas()` answered. @@ -29,8 +22,9 @@ fn remaining(data: &Bytes) -> u64 { .expect("the answer is a uint64") } -/// `remainingComputeGas()` is intercepted and answers the regular gas the call was forwarded, -/// which is below the execution cap and below what the caller had. +/// `remainingComputeGas()` is intercepted and answers the caller's regular gas, which is below the +/// execution cap and below what the transaction had. What the figure is exactly is in +/// `remaining_compute_gas`. #[test] fn test_remaining_compute_gas_is_intercepted() { let (status, data) = through_contract(CALL, &REMAINING_COMPUTE_GAS, 0); @@ -44,57 +38,6 @@ fn test_remaining_compute_gas_is_intercepted() { ); } -/// A transaction calling the contract directly is intercepted, and answers a figure below the -/// transaction's own gas limit. -#[test] -fn test_a_direct_transaction_is_intercepted() { - let result = - run(system_db(), call_tx(LIMIT_CONTROL_ADDRESS, REMAINING_COMPUTE_GAS, U256::ZERO)); - let answer = remaining(&output(&result)); - assert!( - answer > 0 && answer < GAS_LIMIT, - "{answer} is not between the intrinsic cost and the limit" - ); -} - -/// A `STATICCALL` reaches the interceptor: the method only reads. -#[test] -fn test_a_static_call_is_intercepted() { - let (status, data) = through_contract(STATICCALL, &REMAINING_COMPUTE_GAS, 0); - assert!(status); - assert!(remaining(&data) > 0); -} - -/// The answer falls as the caller spends: a second query further along the same frame reports -/// less than the first. -#[test] -fn test_the_answer_falls_as_the_caller_spends() { - use mega_evm::test_utils::BytecodeBuilder; - use revm::bytecode::opcode::{GAS, POP, RETURN}; - - // Two queries in a row, both written into memory and returned. - let mut code = BytecodeBuilder::default().mstore(0x0, REMAINING_COMPUTE_GAS); - for slot in [0x20_u64, 0x40] { - code = code - .push_number(32_u64) // retSize - .push_number(slot) // retOffset - .push_number(4_u64) // argsSize - .push_number(0_u64) // argsOffset - .push_number(0_u64) // value - .push_address(LIMIT_CONTROL_ADDRESS) - .append(GAS) - .append(CALL) - .append(POP); - } - let code = code.push_number(64_u64).push_number(0x20_u64).append(RETURN).build(); - - let result = run(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); - let outcome = output(&result); - let first = U256::from_be_slice(&outcome[..32]); - let second = U256::from_be_slice(&outcome[32..64]); - assert!(second < first, "{second} is not below {first}"); -} - /// A call that carries value is refused with `NonZeroTransfer()`: the method reads and takes no /// value. #[test] diff --git a/crates/mega-evm/tests/system/main.rs b/crates/mega-evm/tests/system/main.rs index 8ff049f36..51a97c9fa 100644 --- a/crates/mega-evm/tests/system/main.rs +++ b/crates/mega-evm/tests/system/main.rs @@ -1,10 +1,16 @@ //! Tests of the system contracts: the interceptor dispatch, what each contract answers, and the //! system-address transaction. +mod access_control; mod common; mod control; mod dispatch; mod keyless; mod limit_control; mod oracle; +mod oracle_storage; +mod predeploys; +mod remaining_compute_gas; +#[path = "../shared/snapshot.rs"] +mod snapshot; mod system_tx; diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 4563c06b0..26fb4b91d 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -17,7 +17,9 @@ use revm::{ context::result::ResultAndState, }; -use crate::common::{block, call_tx, calls_with, run, system_db, with_contract, CALLER, CONTRACT}; +use crate::common::{ + block, call_tx, calls_with, run, steer, system_db, with_contract, CALLER, CONTRACT, +}; /// A topic and payload the tests send. const TOPIC: B256 = B256::repeat_byte(0x7a); @@ -25,6 +27,16 @@ const TOPIC: B256 = B256::repeat_byte(0x7a); /// The hint the two data-size cases send, so the limit they set is the same number. const METERED_HINT: &[u8] = b"a hint the transaction is metered for"; +/// A top-level `sendHint`: the body counts the calldata, and the hint counts it again. +fn top_level_hint(payload: u64) -> u64 { + mega_evm::TX_BODY_SIZE + payload + payload +} + +/// A nested hint. The transaction's own calldata is empty, so only the body and the hint count. +fn nested_hint(payload: u64) -> u64 { + mega_evm::TX_BODY_SIZE + payload +} + /// The calldata of `sendHint(TOPIC, data)`. fn send_hint(data: &[u8]) -> Bytes { Bytes::from( @@ -42,8 +54,8 @@ fn run_with_oracle( (outcome.result_and_state, hints, outcome.usage) } -/// [`run_with_oracle`] under `limits`, returning the whole outcome: the stop a crossed limit -/// latched is what the outcome reports, not the output alone. +/// [`run_with_oracle`] under `limits`, returning the whole outcome: the stop of the transaction's +/// own frame is what the outcome reports, not the output alone. fn run_with_oracle_under( db: MemoryDatabase, tx: MegaTransaction, @@ -87,14 +99,14 @@ fn test_the_hint_payload_is_counted_on_the_transaction() { let (_, hints, usage) = run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO)); assert_eq!(hints.len(), 1); - assert_eq!(usage.data_size, data.len() as u64); + assert_eq!(usage.data_size, top_level_hint(data.len() as u64)); // The same call with bytes the ABI decoder drops pays for them too. let padded: Vec = data.iter().copied().chain([0_u8; 64]).collect(); let (_, hints, padded_usage) = run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &padded, U256::ZERO)); assert_eq!(hints.len(), 1, "the trailing bytes do not stop the decoding"); - assert_eq!(padded_usage.data_size, padded.len() as u64); + assert_eq!(padded_usage.data_size, top_level_hint(padded.len() as u64)); } /// A payload that does not decode is paid for and forwards nothing. @@ -105,7 +117,7 @@ fn test_a_malformed_payload_is_paid_for_and_not_forwarded() { let (_, hints, usage) = run_with_oracle(system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, &data, U256::ZERO)); assert!(hints.is_empty(), "a payload that does not decode carries no hint"); - assert_eq!(usage.data_size, data.len() as u64); + assert_eq!(usage.data_size, top_level_hint(data.len() as u64)); } /// A `STATICCALL` forwards the hint: `sendHint` is a view method. @@ -133,7 +145,11 @@ fn test_a_value_bearing_call_forwards_nothing() { let (status, _) = crate::common::split_outcome(&outcome); assert!(!status, "the bytecode refuses the value"); assert!(hints.is_empty()); - assert_eq!(usage.data_size, 0, "nothing was materialised for a hint that is not forwarded"); + assert_eq!( + usage.data_size, + nested_hint(0), + "nothing was materialised for a hint that is not forwarded" + ); } /// A call forwarded no gas forwards nothing: it cannot run the contract either, so its hint @@ -161,7 +177,7 @@ fn test_a_call_without_gas_forwards_nothing() { assert!(result.result.is_success(), "the caller survives the failed call"); assert!(hints.is_empty()); - assert_eq!(usage.data_size, 0); + assert_eq!(usage.data_size, nested_hint(0)); } /// A call forwarded one gas does forward its hint, and the frame it was sent from then runs out @@ -197,7 +213,7 @@ fn test_a_call_with_one_gas_forwards_the_hint_it_cannot_deliver() { let (status, _) = crate::common::split_outcome(&outcome); assert!(!status, "one gas does not run the contract's dispatcher"); assert_eq!(hints.len(), 1, "the hint reached the service before the frame ran out of gas"); - assert_eq!(usage.data_size, data.len() as u64, "and its bytes stay counted"); + assert_eq!(usage.data_size, nested_hint(data.len() as u64), "and its bytes stay counted"); } /// `CALLCODE` and `DELEGATECALL` never reach the interceptor, so they forward nothing. @@ -209,7 +225,7 @@ fn test_callcode_and_delegatecall_forward_nothing() { let (_, hints, usage) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); assert!(hints.is_empty(), "scheme {scheme:#x} must not reach the interceptor"); - assert_eq!(usage.data_size, 0); + assert_eq!(usage.data_size, nested_hint(0)); } } @@ -229,7 +245,7 @@ fn test_an_unknown_selector_runs_the_bytecode() { "the contract has no code to answer a selector it does not declare", ); assert!(hints.is_empty()); - assert_eq!(usage.data_size, 0); + assert_eq!(usage.data_size, mega_evm::TX_BODY_SIZE + 4); } /// Reading the Oracle's storage is not intercepted: `getSlot` runs the contract's code. @@ -273,41 +289,48 @@ fn test_a_reverting_frame_does_not_take_the_hint_bytes_back() { assert_eq!(hints.len(), 1, "the hint reached the service before the revert"); assert_eq!( usage.data_size, - data.len() as u64, + nested_hint(data.len() as u64), "the bytes stay counted: a revert cannot take the hint back", ); } /// A payload that does not fit in what is left of the transaction's data-size limit is not -/// forwarded, and the crossing stops the transaction: the hint's bytes are counted before the -/// payload is decoded, so the limit is crossed before the frame the call would have started. +/// forwarded, and the crossing stops the transaction: the limit is checked on the hint's bytes +/// before the payload is decoded, so it is crossed before the frame the call would have started. /// -/// The bytes stay counted — the crossing is what the transaction is stopped for, and the usage -/// is what shows it — and the transaction settles as a revert carrying the stop's own data. +/// The bytes are not counted: the payload never left the machine, so the stopped transaction +/// keeps its body alone, and a block's data-size counter takes nothing for the hint. The stop +/// reports the usage the hint would have reached, and the transaction settles as a revert +/// carrying the stop's own data. #[test] fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { let data = send_hint(METERED_HINT); - let limit = data.len() as u64 - 1; + // The body already counts the calldata. The hint would count it again, and that second copy + // holds the byte that crosses. + let body = mega_evm::TX_BODY_SIZE + data.len() as u64; + let reached = top_level_hint(data.len() as u64); + let limit = reached - 1; let (outcome, hints) = run_with_oracle_under( system_db(), - call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), + call_tx(ORACLE_CONTRACT_ADDRESS, data, U256::ZERO), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); assert_eq!( - outcome.usage.data_size, - data.len() as u64, - "the whole payload is counted: the count is what crossed the limit", + outcome.usage, + LimitUsage { data_size: body, write_records: 0 }, + "a hint that was not forwarded is not counted: the body is what the transaction keeps", ); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, - used: data.len() as u64, + used: reached, frame_local: false, }), + "the stop reports the usage the hint would have reached", ); assert_eq!( outcome.result.output().cloned().unwrap_or_default(), @@ -324,11 +347,283 @@ fn test_a_hint_at_the_data_size_limit_is_forwarded() { let (outcome, hints) = run_with_oracle_under( system_db(), call_tx(ORACLE_CONTRACT_ADDRESS, data.clone(), U256::ZERO), - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(data.len() as u64), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(top_level_hint(data.len() as u64)), ); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(hints.len(), 1); - assert_eq!(outcome.usage.data_size, data.len() as u64); + assert_eq!(outcome.usage.data_size, top_level_hint(data.len() as u64)); + assert_eq!(outcome.limit_exceeded, None); +} + +/* ---------- the legacy engine's hint rows ---------- */ + +/// A second contract, calling the first. +const INNER: alloy_primitives::Address = + alloy_primitives::address!("0x0000000000000000000000000000000000300002"); + +/// Appends a `CALL` of the Oracle with `data` and `gas`, the calldata written at 0x100, leaving +/// the call's status on the stack. +fn call_oracle(code: BytecodeBuilder, data: &[u8], gas: u64) -> BytecodeBuilder { + code.mstore(0x100, data) + .push_number(0_u8) // retSize + .push_number(0_u8) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0x100_u16) // argsOffset + .push_number(0_u8) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(gas) + .append(CALL) +} + +/// Appends a return of the status on the stack. +fn return_status(code: BytecodeBuilder) -> Bytes { + use revm::bytecode::opcode::{MSTORE, PUSH0, RETURN}; + code.append_many([PUSH0, MSTORE]).push_number(32_u8).append_many([PUSH0, RETURN]).build() +} + +/// The status a contract of [`return_status`] returned. +fn returned_status(outcome: &MegaTransactionOutcome) -> U256 { + U256::from_be_slice(outcome.result.output().expect("the contract returns its status")) +} + +const DISABLE: [u8; 4] = + mega_evm::system::IMegaAccessControl::disableVolatileDataAccessCall::SELECTOR; +const ENABLE: [u8; 4] = + mega_evm::system::IMegaAccessControl::enableVolatileDataAccessCall::SELECTOR; + +/// A contract's hint reaches the service with the contract as its sender, and the call runs the +/// Oracle's `sendHint`, which succeeds. +#[test] +fn test_a_contracts_hint_reaches_the_service_from_the_contract() { + let data = send_hint(&[0xde, 0xad, 0xbe, 0xef]); + let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); + let (result, hints, _) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + + let outcome = result.result.output().cloned().unwrap_or_default(); + assert_eq!(U256::from_be_slice(&outcome), U256::ONE, "sendHint succeeded"); + assert_eq!( + hints, + vec![RecordedHint { + from: CONTRACT, + topic: TOPIC, + data: Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef]) + }], + ); +} + +/// The Oracle's code at another address is not the Oracle: its `sendHint` runs and forwards +/// nothing. +#[test] +fn test_the_oracles_code_elsewhere_forwards_no_hint() { + use mega_evm::system::ORACLE_CONTRACT_CODE; + + let elsewhere = alloy_primitives::address!("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"); + let db = system_db().account_code(elsewhere, ORACLE_CONTRACT_CODE); + let (result, hints, _) = + run_with_oracle(db, call_tx(elsewhere, send_hint(b"hint"), U256::ZERO)); + assert!(result.result.is_success(), "{:?}", result.result); + assert!(hints.is_empty()); +} + +/// Two hints reach the service in the order they were sent. +#[test] +fn test_hints_reach_the_service_in_the_order_they_were_sent() { + use revm::bytecode::opcode::POP; + + let first = IOracle::sendHintCall { + topic: B256::repeat_byte(0x11), + data: Bytes::from_static(&[0xaa, 0xbb]), + }; + let second = IOracle::sendHintCall { + topic: B256::repeat_byte(0x22), + data: Bytes::from_static(&[0xcc, 0xdd]), + }; + let code = call_oracle(BytecodeBuilder::default(), &first.abi_encode(), 1_000_000).append(POP); + let code = call_oracle(code, &second.abi_encode(), 1_000_000).append(POP).stop().build(); + let (_, hints, _) = run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!( + hints, + vec![ + RecordedHint { from: CONTRACT, topic: first.topic, data: first.data }, + RecordedHint { from: CONTRACT, topic: second.topic, data: second.data }, + ], + ); +} + +/// A malformed `sendHint` payload, and one followed by bytes the decoder drops, are counted +/// whole: the first forwards nothing, the second forwards its envelope. Under a limit that holds +/// half of the payload, both are stopped before anything is forwarded: the call is answered with +/// the stop, which the contract catches, returning the failed call's status. +#[test] +fn test_a_malformed_or_padded_hint_is_counted_whole() { + let malformed: Vec = IOracle::sendHintCall::SELECTOR + .iter() + .copied() + .chain(core::iter::repeat_n(0xab, 1024)) + .collect(); + let padded: Vec = + send_hint(&[]).iter().copied().chain(core::iter::repeat_n(0xcd, 4096)).collect(); + for (data, forwarded) in [(malformed, 0), (padded, 1)] { + let code = return_status(call_oracle(BytecodeBuilder::default(), &data, 1_000_000)); + let total = data.len() as u64; + + let (outcome, hints) = run_with_oracle_under( + with_contract(code.clone()), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(outcome.result.is_success()); + assert_eq!(hints.len(), forwarded); + assert!(hints.iter().all(|hint| hint.data.is_empty()), "the padding is dropped"); + assert_eq!(outcome.usage.data_size, nested_hint(total), "the whole calldata is counted"); + + let limit = nested_hint(total / 2); + let (outcome, hints) = run_with_oracle_under( + with_contract(code), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert!(hints.is_empty(), "a hint past the limit is not forwarded"); + assert!(outcome.result.is_success(), "the contract catches the stop"); + assert_eq!(returned_status(&outcome), U256::ZERO, "the call was stopped"); + assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); + assert_eq!(outcome.usage.data_size, nested_hint(0), "and it is not counted"); + } +} + +/// Hints add up on the transaction: under a limit that holds one and a half, the first is +/// forwarded, and the second's call is answered with the stop, which the contract catches. +#[test] +fn test_consecutive_hints_add_up_on_the_transaction() { + use revm::bytecode::opcode::POP; + + let data = send_hint(&[0_u8; 256]); + let len = data.len() as u64; + let code = call_oracle(BytecodeBuilder::default(), &data, 1_000_000).append(POP); + let code = return_status(call_oracle(code, &data, 1_000_000)); + let limit = nested_hint(len + len / 2); + let (outcome, hints) = run_with_oracle_under( + with_contract(code), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_eq!(hints.len(), 1, "the first hint was forwarded, the second was not"); + assert!(outcome.result.is_success(), "the contract catches the stop"); + assert_eq!(returned_status(&outcome), U256::ZERO, "the second call was stopped"); assert_eq!(outcome.limit_exceeded, None); + assert_eq!( + outcome.usage, + LimitUsage { data_size: nested_hint(len), write_records: 0 }, + "the forwarded hint stays counted and the one that crossed is not", + ); +} + +/// A contract's hint whose payload crosses the transaction's data-size limit is not forwarded, and +/// the crossing stops the Oracle call with a revert carrying the stop, not a halt: the contract +/// catches it and returns the failed call's status, and the transaction is billed what ran rather +/// than its gas limit. +#[test] +fn test_data_size_overflow_blocks_forwarding_and_stops_the_call() { + const LIMIT: u64 = 2_048; + let data = send_hint(&[0_u8; 4_096]); + let call = || call_oracle(BytecodeBuilder::default(), &data, 1_000_000); + let (outcome, hints) = run_with_oracle_under( + with_contract(return_status(call())), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(LIMIT), + ); + + assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); + assert!(outcome.result.is_success(), "the contract catches the stop: {:?}", outcome.result); + assert_eq!(returned_status(&outcome), U256::ZERO, "the call was stopped"); + assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: nested_hint(0), write_records: 0 }, + "the transaction keeps its body: the hint never left the machine", + ); + + // What ran is the contract's code, its call, which the stop answered at the Oracle's start, + // handing back what it forwarded, and the return of the status: the same code calling an Oracle + // with no code, without limits, runs exactly that. + let (ran, _) = run_with_oracle_under( + with_contract(return_status(call())).account_code(ORACLE_CONTRACT_ADDRESS, Bytes::new()), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(ran.result.is_success(), "{:?}", ran.result); + assert_eq!(returned_status(&ran), U256::ONE); + assert_eq!(outcome.gas, ran.gas, "billed what ran"); +} + +/// A frame that switched its volatile-data access off sends no hint: `sendHint` still runs and +/// succeeds, and nothing reaches the service. +#[test] +fn test_a_frame_that_switched_access_off_sends_no_hint() { + let data = send_hint(&[0_u8; 64]); + let code = + return_status(call_oracle(steer(BytecodeBuilder::default(), DISABLE), &data, 100_000)); + let (result, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + let outcome = result.result.output().cloned().unwrap_or_default(); + assert_eq!(U256::from_be_slice(&outcome), U256::ONE, "the call ran and succeeded"); + assert!(hints.is_empty()); + assert_eq!(usage.data_size, nested_hint(0), "a withheld hint is not counted"); +} + +/// A frame whose access is on sends its hint, and so does one that switched it off and back on. +#[test] +fn test_a_frame_with_access_on_sends_its_hint() { + let data = send_hint(&[0_u8; 64]); + for code in + [BytecodeBuilder::default(), steer(steer(BytecodeBuilder::default(), DISABLE), ENABLE)] + { + let code = return_status(call_oracle(code, &data, 100_000)); + let (_, hints, usage) = + run_with_oracle(with_contract(code), call_tx(CONTRACT, [], U256::ZERO)); + assert_eq!(hints.len(), 1); + assert_eq!(usage.data_size, nested_hint(data.len() as u64)); + } +} + +/// A child of a frame that switched access off sends no hint, although it switched nothing off +/// itself. +#[test] +fn test_a_child_of_a_frame_that_switched_access_off_sends_no_hint() { + let data = send_hint(&[0_u8; 64]); + let inner = return_status(call_oracle(BytecodeBuilder::default(), &data, 100_000)); + let outer = steer(BytecodeBuilder::default(), DISABLE) + .push_number(0_u8) + .push_number(0_u8) + .push_number(0_u8) + .push_number(0_u8) + .push_number(0_u8) + .push_address(INNER) + .push_number(10_000_000_u32) + .append(CALL); + let outer = return_status(outer); + let db = with_contract(outer).account_code(INNER, inner); + let (result, hints, _) = run_with_oracle(db, call_tx(CONTRACT, [], U256::ZERO)); + let outcome = result.result.output().cloned().unwrap_or_default(); + assert_eq!(U256::from_be_slice(&outcome), U256::ONE, "the child ran"); + assert!(hints.is_empty()); +} + +/// A withheld hint is not counted, so a payload far past the transaction's data-size limit does +/// not stop a transaction that switched access off first. +#[test] +fn test_a_withheld_hint_is_not_counted() { + let data = send_hint(&[0_u8; 4096]); + let code = + return_status(call_oracle(steer(BytecodeBuilder::default(), DISABLE), &data, 1_000_000)); + let (outcome, hints) = run_with_oracle_under( + with_contract(code), + call_tx(CONTRACT, [], U256::ZERO), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(nested_hint(2_048)), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert!(hints.is_empty()); } diff --git a/crates/mega-evm/tests/system/oracle_storage.rs b/crates/mega-evm/tests/system/oracle_storage.rs new file mode 100644 index 000000000..728123a12 --- /dev/null +++ b/crates/mega-evm/tests/system/oracle_storage.rs @@ -0,0 +1,831 @@ +//! The Oracle's storage, read through the oracle environment: an `SLOAD` in the Oracle's own +//! frame loads the slot through the journal, answers the node's oracle service's value when it +//! has one and the loaded value otherwise, is always priced as a cold access, and is a read of +//! volatile data for gas detention. + +use std::{cell::RefCell, collections::HashMap, rc::Rc}; + +use alloy_op_evm::OpTx; +use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + system::{IOracle, ORACLE_CONTRACT_ADDRESS}, + test_utils::{ + op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, ReplayingOracleEnv, + }, + volatile_data_access_disabled_revert_data, EmptyExternalEnv, EvmTxRuntimeLimits, ExternalEnvs, + LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, OracleEnv, OracleRead, VolatileDataAccess, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLDATASIZE, DELEGATECALL, DUP2, GAS, JUMPDEST, JUMPI, MSTORE, POP, PUSH0, PUSH1, + RETURN, SLOAD, SSTORE, STOP, SUB, SWAP1, TIMESTAMP, + }, + context::TxEnv, + interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, + Inspector, +}; + +use crate::common::{ + block, call_tx, calls_with, split_outcome, system_db, CALLER, CONTRACT, GAS_LIMIT, +}; + +/// A second contract, which never is the Oracle. +const OTHER: Address = address!("0x0000000000000000000000000000000000300002"); + +/// The slot the tests read, and the two values it can hold: the one the oracle service answers +/// and the one the chain's state holds. +const SLOT: U256 = U256::from_limbs([42, 0, 0, 0]); +const SERVICE_VALUE: U256 = U256::from_limbs([0x1234_5678_90ab_cdef, 0, 0, 0]); +const STATE_VALUE: U256 = U256::from_limbs([0xfedc_ba98_7654_3210, 0, 0, 0]); + +/// What the oracle service saw, in the order it saw it. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Seen { + /// A hint, with its topic and data. + Hint(B256, Bytes), + /// A read of a slot. + Read(U256), +} + +/// An oracle service that answers the slots it holds and records every hint and read. +/// +/// A hint whose data is one word tells the service to fetch that value for the slot its topic +/// names, so a read after it finds the value and a read before it does not. +#[derive(Clone, Debug, Default)] +struct Service { + values: Rc>>, + seen: Rc>>, +} + +impl Service { + fn holding(slot: U256, value: U256) -> Self { + let service = Self::default(); + service.values.borrow_mut().insert(slot, value); + service + } + + fn seen(&self) -> Vec { + self.seen.borrow().clone() + } +} + +impl OracleEnv for Service { + fn get_oracle_storage(&self, slot: U256) -> Option { + self.seen.borrow_mut().push(Seen::Read(slot)); + self.values.borrow().get(&slot).copied() + } + + fn on_hint(&self, _from: Address, topic: B256, data: Bytes) { + self.seen.borrow_mut().push(Seen::Hint(topic, data.clone())); + if data.len() == 32 { + self.values.borrow_mut().insert(topic.into(), U256::from_be_slice(&data)); + } + } +} + +type Envs = (EmptyExternalEnv, Service); + +/// What a transaction did, what gas detention made of its reads, and the oracle reads the EVM +/// reports for it afterwards. +struct Run { + outcome: MegaTransactionOutcome, + accessed: VolatileDataAccess, + limit: Option, + evm_reads: Vec, +} + +/// Runs `tx` over `db` against `service`, under `limits`. +fn run_under( + db: MemoryDatabase, + service: &Service, + limits: EvmTxRuntimeLimits, + configure: impl FnOnce(MegaContext) -> MegaContext, + tx: MegaTransaction, +) -> Run { + let envs = ExternalEnvs { salt_env: EmptyExternalEnv, oracle_env: service.clone() }; + let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, envs) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(limits); + let mut evm = MegaEvm::new(configure(ctx)); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let detention = evm.ctx().detention(); + Run { + outcome, + accessed: detention.accessed(), + limit: detention.compute_limit(), + evm_reads: evm.oracle_reads().to_vec(), + } +} + +/// Runs `tx` over `db` against `service`, under the default limits, which detain. +fn run(db: MemoryDatabase, service: &Service, tx: MegaTransaction) -> Run { + run_under(db, service, EvmTxRuntimeLimits::default(), |ctx| ctx, tx) +} + +/// The calldata of `getSlot(slot)`. +fn get_slot(slot: U256) -> Vec { + IOracle::getSlotCall { slot }.abi_encode() +} + +/// The word a successful call to the Oracle, made through [`calls_with`], returned. +fn returned_word(run: &Run) -> U256 { + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + let (status, data) = split_outcome(&output); + assert!(status, "the call to the Oracle failed"); + U256::from_be_slice(data) +} + +/// A database holding the system contracts, with `SLOT` of the Oracle at `STATE_VALUE`. +fn db_with_state() -> MemoryDatabase { + system_db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, STATE_VALUE) +} + +/// Code that reads `SLOT` twice and returns what each read cost: the price of `GAS`, of pushing +/// the slot, of the `SLOAD` and of popping its value. +fn two_reads() -> Bytes { + let read = |code: BytecodeBuilder| code.push_u256(SLOT).append_many([SLOAD, POP, GAS]); + read(read(BytecodeBuilder::default().append(GAS))) + // [g0, g1, g2]: store g1 - g2 at 0x20 and g0 - g1 at 0. + .append_many([DUP2, SUB]) + .push_number(0x20_u8) + .append(MSTORE) + .append_many([SWAP1, SUB, PUSH0, MSTORE]) + .push_number(0x40_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// What each of the two reads [`two_reads`] makes cost, run at `at`. +fn read_costs(db: MemoryDatabase, service: &Service, at: Address) -> (u64, u64) { + let run = run(db.account_code(at, two_reads()), service, call_tx(at, [], U256::ZERO)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + ( + U256::from_be_slice(&output[..32]).to::(), + U256::from_be_slice(&output[32..64]).to::(), + ) +} + +/// The oracle service's value is what a contract reading the Oracle's slot sees, over the value +/// the chain's state holds, and the read is a read of the Oracle's storage. +#[test] +fn test_oracle_storage_sload_uses_oracle_env() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &get_slot(SLOT), 0); + let run = run( + db_with_state().account_code(CONTRACT, code), + &service, + call_tx(CONTRACT, [], U256::ZERO), + ); + + assert_eq!(returned_word(&run), SERVICE_VALUE); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)]); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); +} + +/// A slot the oracle service has no value for is read from the chain's state, and is still a +/// read of the Oracle's storage. +#[test] +fn test_oracle_storage_sload_fallback_to_database() { + let service = Service::default(); + let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &get_slot(SLOT), 0); + let run = run( + db_with_state().account_code(CONTRACT, code), + &service, + call_tx(CONTRACT, [], U256::ZERO), + ); + + assert_eq!(returned_word(&run), STATE_VALUE); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "the service was asked"); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); +} + +/// A transaction that calls the Oracle directly reads through the service too: the Oracle's own +/// frame is the transaction's. +#[test] +fn test_oracle_storage_sload_direct_call() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let run = run( + db_with_state(), + &service, + call_tx(ORACLE_CONTRACT_ADDRESS, get_slot(SLOT), U256::ZERO), + ); + + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(run.outcome.result.output().unwrap()).unwrap(), + B256::from(SERVICE_VALUE), + ); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); +} + +/// Three reads of one slot cost the same whether the service answered them or the chain's +/// state did: a replaying node cannot tell which source the node that built the block read. +#[test] +fn test_oracle_sload_determinism_between_oracle_env_and_state() { + let code = BytecodeBuilder::default() + .push_u256(SLOT) + .append_many([SLOAD, POP]) + .push_u256(SLOT) + .append_many([SLOAD, POP]) + .push_u256(SLOT) + .append_many([SLOAD, POP, STOP]) + .build(); + let from_service = run( + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(ORACLE_CONTRACT_ADDRESS, code.clone()), + &Service::holding(SLOT, SERVICE_VALUE), + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + let from_state = run( + MemoryDatabase::default() + .account_balance(CALLER, U256::from(1_000_000)) + .account_code(ORACLE_CONTRACT_ADDRESS, code) + .account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, SERVICE_VALUE), + &Service::default(), + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + + assert!(from_service.outcome.result.is_success()); + assert!(from_state.outcome.result.is_success()); + assert_eq!(from_service.outcome.result.tx_gas_used(), from_state.outcome.result.tx_gas_used()); + assert_eq!(from_service.outcome.gas, from_state.outcome.gas, "every ledger is the same"); + assert_eq!(from_service.accessed, VolatileDataAccess::ORACLE); + assert_eq!(from_state.accessed, VolatileDataAccess::ORACLE); +} + +/// Every read of the Oracle's storage is a cold access, the second read of a slot in the same +/// transaction included, whichever source answered. The same code in another contract pays the +/// warm price for the second read. +#[test] +fn test_every_oracle_read_is_cold() { + let params = mega_evm::satin_gas_params(); + let (warm, cold_extra) = + (params.warm_storage_read_cost(), params.cold_storage_additional_cost()); + // GAS, the push of the slot, the SLOAD and the POP. + let read = |sload: u64| 2 + 3 + sload + 2; + let cold = read(warm + cold_extra); + + for service in [Service::holding(SLOT, SERVICE_VALUE), Service::default()] { + let costs = read_costs(db_with_state(), &service, ORACLE_CONTRACT_ADDRESS); + assert_eq!(costs, (cold, cold), "both reads of the Oracle's slot are cold"); + assert_eq!(service.seen(), vec![Seen::Read(SLOT), Seen::Read(SLOT)], "and both ask"); + } + + let service = Service::holding(SLOT, SERVICE_VALUE); + let costs = read_costs(db_with_state(), &service, OTHER); + assert_eq!(costs, (cold, read(warm)), "another contract's second read is warm"); + assert!(service.seen().is_empty(), "and never asks the oracle service"); +} + +/// A read of the Oracle's storage is a read of volatile data under the Oracle's own cap: the +/// limit it sets is the transaction's compute at the read — the push and the `SLOAD`, with its +/// cold access — plus the Oracle's cap, not the block environment's. +#[test] +fn test_an_oracle_read_is_detained_under_the_oracles_cap() { + let code = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); + for service in [Service::holding(U256::ZERO, SERVICE_VALUE), Service::default()] { + let limits = EvmTxRuntimeLimits::default() + .with_block_env_access_compute_gas_limit(7_000_000) + .with_oracle_access_compute_gas_limit(5_000_000); + let run = run_under( + system_db().account_code(ORACLE_CONTRACT_ADDRESS, code.clone()), + &service, + limits, + |ctx| ctx, + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + assert!(run.outcome.result.is_success()); + assert_eq!(run.accessed, VolatileDataAccess::ORACLE); + assert_eq!(run.limit, Some(2 + 2_100 + 5_000_000)); + } + + // Under the default limits the cap is the spec's. + let run = run( + system_db().account_code(ORACLE_CONTRACT_ADDRESS, code), + &Service::default(), + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + assert_eq!(run.limit, Some(2 + 2_100 + ORACLE_ACCESS_COMPUTE_GAS)); +} + +/// A hint reaches the oracle service before a read the transaction makes after it, so the read +/// finds what the hint asked the service to fetch; a read made before the hint does not, and +/// reads the chain's state. +#[test] +fn test_a_hint_reaches_the_service_before_a_later_read() { + let hint = IOracle::sendHintCall { + topic: B256::from(SLOT), + data: Bytes::copy_from_slice(&SERVICE_VALUE.to_be_bytes::<32>()), + } + .abi_encode(); + let read = get_slot(SLOT); + + // Each call writes its calldata at 0x100, and a read returns its word at 0. + let call = |code: BytecodeBuilder, data: &[u8]| { + code.mstore(0x100, data) + .push_number(32_u8) // retSize + .push_number(0_u8) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0x100_u16) // argsOffset + .push_number(0_u8) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .append(GAS) + .append_many([CALL, POP]) + }; + let finish = + |code: BytecodeBuilder| code.push_number(32_u8).append_many([PUSH0, RETURN]).build(); + + for (hint_first, expected, seen) in [ + ( + true, + SERVICE_VALUE, + vec![ + Seen::Hint(B256::from(SLOT), SERVICE_VALUE.to_be_bytes::<32>().into()), + Seen::Read(SLOT), + ], + ), + ( + false, + STATE_VALUE, + vec![ + Seen::Read(SLOT), + Seen::Hint(B256::from(SLOT), SERVICE_VALUE.to_be_bytes::<32>().into()), + ], + ), + ] { + let code = if hint_first { + finish(call(call(BytecodeBuilder::default(), &hint), &read)) + } else { + // The read's word is at 0 before the hint is sent; the hint returns nothing. + finish(call(call(BytecodeBuilder::default(), &read), &hint)) + }; + let service = Service::default(); + let run = run( + db_with_state().account_code(CONTRACT, code), + &service, + call_tx(CONTRACT, [], U256::ZERO), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!( + U256::from_be_slice(run.outcome.result.output().unwrap()), + expected, + "hint first: {hint_first}" + ); + assert_eq!(service.seen(), seen, "hint first: {hint_first}"); + } +} + +/// A read outside the Oracle's own frame is not a read of the Oracle's storage: a contract that +/// runs the Oracle's code on its own storage, through `DELEGATECALL`, reads its own slot from the +/// chain's state, never asks the service, and reads nothing volatile. +#[test] +fn test_a_read_outside_the_oracles_frame_is_an_ordinary_read() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let code = calls_with(DELEGATECALL, ORACLE_CONTRACT_ADDRESS, &get_slot(SLOT), 0); + let db = + db_with_state().account_code(CONTRACT, code).account_storage(CONTRACT, SLOT, U256::from(7)); + let run = run(db, &service, call_tx(CONTRACT, [], U256::ZERO)); + + assert_eq!(returned_word(&run), U256::from(7), "the caller's own slot"); + assert!(service.seen().is_empty()); + assert_eq!(run.accessed, VolatileDataAccess::empty()); + assert_eq!(run.limit, None); +} + +/// A frame that cannot pay the cold access reads nothing: it runs out of gas as revm's own +/// skipped cold load does, the service is not asked, and nothing volatile was read. +#[test] +fn test_a_read_the_frame_cannot_pay_for_asks_nothing() { + let oracle = BytecodeBuilder::default().append_many([PUSH0, SLOAD, STOP]).build(); + // The caller forwards 1,000 gas: enough for the push and the warm part of the `SLOAD`, not + // for its cold access. + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .push_number(1_000_u16) + .append(CALL) + .append_many([PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build(); + let service = Service::holding(U256::ZERO, SERVICE_VALUE); + let db = + system_db().account_code(ORACLE_CONTRACT_ADDRESS, oracle).account_code(CONTRACT, caller); + let run = run(db, &service, call_tx(CONTRACT, [], U256::ZERO)); + + assert!(run.outcome.result.is_success()); + assert_eq!( + U256::from_be_slice(run.outcome.result.output().unwrap()), + U256::ZERO, + "the call failed" + ); + assert!(service.seen().is_empty(), "a read the frame cannot pay for asks nothing"); + assert!(run.outcome.oracle_reads.is_empty(), "and records nothing"); + assert_eq!(run.accessed, VolatileDataAccess::empty()); +} + +/// A read refused because the frame's volatile-data access is off asks the service nothing: the +/// frame reverts with `VolatileDataAccessDisabled(Oracle)`. +#[test] +fn test_a_refused_read_asks_nothing() { + let service = Service::holding(SLOT, SERVICE_VALUE); + let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &get_slot(SLOT), 0); + let run = run_under( + db_with_state().account_code(CONTRACT, code), + &service, + EvmTxRuntimeLimits::default(), + |ctx| ctx.with_volatile_access_disabled_from(1), + call_tx(CONTRACT, [], U256::ZERO), + ); + + assert!(run.outcome.result.is_success()); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + let (status, data) = split_outcome(&output); + assert!(!status); + assert_eq!(data, &volatile_data_access_disabled_revert_data(VolatileDataAccess::ORACLE)[..]); + assert!(service.seen().is_empty()); + assert!(run.outcome.oracle_reads.is_empty(), "a refused read records nothing"); + assert_eq!(run.accessed, VolatileDataAccess::empty()); +} + +/// Every read a transaction makes through the service is on its outcome, in the order the +/// service was asked, with the answer the frame saw: the service's value, or `None` where the +/// service had none and the loaded value stood. The record is the service's own view of the +/// transaction, so a validator given it in place of the service answers every read alike. +#[test] +fn test_the_reads_a_transaction_made_are_on_its_outcome() { + let answered = Service::holding(SLOT, SERVICE_VALUE); + let code = calls_with(CALL, ORACLE_CONTRACT_ADDRESS, &get_slot(SLOT), 0); + let tx = || call_tx(CONTRACT, [], U256::ZERO); + let with_answer = run(db_with_state().account_code(CONTRACT, code.clone()), &answered, tx()); + assert_eq!(returned_word(&with_answer), SERVICE_VALUE); + let read = OracleRead { slot: SLOT, answer: Some(SERVICE_VALUE) }; + assert_eq!(with_answer.outcome.oracle_reads, [read]); + assert_eq!(with_answer.evm_reads, [read], "the EVM reports the last transaction's reads"); + + let silent = Service::default(); + let without = run(db_with_state().account_code(CONTRACT, code), &silent, tx()); + assert_eq!(returned_word(&without), STATE_VALUE, "the loaded value stood"); + assert_eq!(without.outcome.oracle_reads, [OracleRead { slot: SLOT, answer: None }]); + + // Two reads of one slot in one frame are two records, in order, as the service saw them. + let answered = Service::holding(SLOT, SERVICE_VALUE); + let db = db_with_state().account_code(ORACLE_CONTRACT_ADDRESS, two_reads()); + let twice = run(db, &answered, call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO)); + assert!(twice.outcome.result.is_success(), "{:?}", twice.outcome.result); + assert_eq!(twice.outcome.oracle_reads, [read, read]); + assert_eq!(answered.seen(), [Seen::Read(SLOT), Seen::Read(SLOT)]); +} + +/// Runs `tx` over `db` as a validator does, under the default limits, answering the Oracle's +/// reads from `oracle` in place of a service. +fn validate( + db: MemoryDatabase, + oracle: O, + tx: MegaTransaction, +) -> MegaTransactionOutcome { + let envs = + ExternalEnvs::<(EmptyExternalEnv, O)> { salt_env: EmptyExternalEnv, oracle_env: oracle }; + let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, envs) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits(EvmTxRuntimeLimits::default()); + MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is valid") +} + +/// One transaction can be answered two values for one slot: it reads the slot, sends a hint that +/// has the service fetch another value, and reads the slot again. Its outcome records both +/// answers, in order, and a validator given that record replays the transaction. A validator that +/// runs no service answers each read from the Oracle's slot, which only the system address writes, +/// so the transaction finds one value there at both reads: whichever of the two answers the node +/// has the slot hold, the other read comes out differently, and the transaction computes another +/// result. +#[test] +fn test_two_answers_for_one_slot_replay_only_from_the_record() { + let hint = IOracle::sendHintCall { + topic: B256::from(SLOT), + data: Bytes::copy_from_slice(&SERVICE_VALUE.to_be_bytes::<32>()), + } + .abi_encode(); + let read = get_slot(SLOT); + + // Each call writes its calldata at 0x100 and its answer at `ret`: the first read's at 0, the + // second's at 0x20. The hint returns nothing. + let call = |code: BytecodeBuilder, data: &[u8], ret: u16| { + code.mstore(0x100, data) + .push_number(32_u8) // retSize + .push_number(ret) // retOffset + .push_number(data.len() as u64) // argsSize + .push_number(0x100_u16) // argsOffset + .push_number(0_u8) // value + .push_address(ORACLE_CONTRACT_ADDRESS) + .append(GAS) + .append_many([CALL, POP]) + }; + let code = call(call(call(BytecodeBuilder::default(), &read, 0), &hint, 0x40), &read, 0x20) + .push_number(64_u8) + .append_many([PUSH0, RETURN]) + .build(); + let db = || db_with_state().account_code(CONTRACT, code.clone()); + let tx = || call_tx(CONTRACT, [], U256::ZERO); + let words = |outcome: &MegaTransactionOutcome| { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let output = outcome.result.output().cloned().unwrap_or_default(); + (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])) + }; + + // The building node: its service has no value for the slot until the hint, so the first read + // takes the chain's value and the second the value the hint had the service fetch. + let built = run(db(), &Service::default(), tx()).outcome; + assert_eq!(words(&built), (STATE_VALUE, SERVICE_VALUE)); + assert_eq!( + built.oracle_reads, + [ + OracleRead { slot: SLOT, answer: None }, + OracleRead { slot: SLOT, answer: Some(SERVICE_VALUE) } + ], + "two answers for one slot, in order" + ); + + // A validator given the record answers both reads as the service did. + let record = ReplayingOracleEnv::new(built.oracle_reads.clone()); + let replayed = validate(db(), record.clone(), tx()); + assert!(record.replayed_exactly(), "every recorded answer was replayed, in order"); + assert_eq!(replayed.result, built.result); + assert_eq!(replayed.state, built.state); + assert_eq!(replayed.gas, built.gas); + assert_eq!(replayed.usage, built.usage); + assert_eq!(replayed.oracle_reads, built.oracle_reads); + + // A validator without a service finds one value in the slot at both reads, whichever of the + // two answers the slot holds. + for held in [STATE_VALUE, SERVICE_VALUE] { + let db = db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, held); + let without = validate(db, ReplayingOracleEnv::absent(), tx()); + assert_eq!(words(&without), (held, held), "the slot holds {held:#x}"); + assert_ne!(without.result, built.result, "the slot holds {held:#x}"); + } +} + +/// A detained frame whose regular gas holds the cold access, but which may not spend it past the +/// compute limit, reads and asks the service all the same: the read's charge then stops the +/// transaction at the limit, and the Oracle read is not marked. A frame whose regular gas cannot +/// hold the cold access at all asks nothing +/// ([`test_a_read_the_frame_cannot_pay_for_asks_nothing`]). +#[test] +fn test_a_detained_frame_that_may_not_spend_the_cold_access_asks_and_is_stopped() { + let code = BytecodeBuilder::default().append_many([TIMESTAMP, POP, PUSH0, SLOAD, STOP]).build(); + let service = Service::default(); + let run = run_under( + system_db().account_code(ORACLE_CONTRACT_ADDRESS, code), + &service, + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(1_500), + |ctx| ctx, + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + + assert_eq!(service.seen(), vec![Seen::Read(U256::ZERO)], "the service was asked"); + assert!( + matches!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "{:?}", + run.outcome.limit_exceeded + ); + assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP, "the Oracle read is not marked"); + assert_eq!(run.limit, Some(2 + 1_500), "the timestamp's limit binds"); +} + +/* ---------- which source answered leaves no trace ---------- */ + +/// Below the execution cap, and above it, where the reservoir pays state and history gas first. +const TIERS: [u64; 2] = [GAS_LIMIT, TX_GAS_LIMIT_CAP + GAS_LIMIT]; + +/// A transaction from [`CALLER`] to `to` with `data`, carrying `gas_limit`. +fn tx_with_gas(to: Address, data: &[u8], gas_limit: u64) -> MegaTransaction { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::copy_from_slice(data), + gas_limit, + ..Default::default() + })) +} + +/// Code for the Oracle's own frame that reads `SLOT` when `read` is set, then writes 7 to it and +/// returns what the write cost the frame's regular gas, with the two pushes and the `GAS` that +/// measure it. +fn write_after(read: bool) -> Bytes { + let code = BytecodeBuilder::default(); + let code = if read { code.push_u256(SLOT).append_many([SLOAD, POP]) } else { code }; + code.append(GAS) + .push_number(7_u8) + .push_u256(SLOT) + // [g0, g1]: return g0 - g1. + .append_many([SSTORE, GAS, SWAP1, SUB, PUSH0, MSTORE]) + .push_number(32_u8) + .append_many([PUSH0, RETURN]) + .build() +} + +/// A write after a read of the Oracle's slot costs the same whether the oracle service answered +/// the read or the chain's state did, below and above the execution cap: both load the slot +/// through the journal, so the write finds it warm either way, and a node that replays the block +/// without the service prices it as the node that built it did. The chain holds the value the +/// service answers, as it does for the replaying node. Without the read the same write pays the +/// cold access. +#[test] +fn test_a_write_after_a_read_costs_the_same_whichever_source_answered() { + let cold_write = mega_evm::satin_gas_params().cold_storage_cost(); + for gas_limit in TIERS { + let at = |read: bool, service: &Service| { + let db = system_db() + .account_code(ORACLE_CONTRACT_ADDRESS, write_after(read)) + .account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, SERVICE_VALUE); + let run = run(db, service, tx_with_gas(ORACLE_CONTRACT_ADDRESS, &[], gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let cost = U256::from_be_slice(run.outcome.result.output().unwrap()).to::(); + (cost, run.outcome) + }; + let service = Service::holding(SLOT, SERVICE_VALUE); + let (from_service, served) = at(true, &service); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "at {gas_limit}: the service answered"); + let (from_state, read) = at(true, &Service::default()); + let (unread, _) = at(false, &Service::default()); + + assert_eq!(from_service, from_state, "at {gas_limit}: the write costs the same"); + assert_eq!(served.result.tx_gas_used(), read.result.tx_gas_used(), "at {gas_limit}"); + assert_eq!(served.gas, read.gas, "at {gas_limit}: every ledger is the same"); + assert_eq!(unread, from_state + cold_write, "at {gas_limit}: the read warmed the slot"); + } +} + +/// The same through the deployed Oracle, which any sender reaches: `multiCall` runs `getSlot`, +/// then `setSlot`, whose body writes the slot before its check reverts the call for a sender that +/// is not the system address. The transaction costs the same whichever source answered the read, +/// below and above the execution cap. +#[test] +fn test_a_multicall_read_then_write_costs_the_same_whichever_source_answered() { + let get = IOracle::getSlotCall { slot: SLOT }.abi_encode(); + let set = IOracle::setSlotCall { slot: SLOT, value: B256::from(U256::from(7)) }.abi_encode(); + let data = IOracle::multiCallCall { data: vec![get.into(), set.into()] }.abi_encode(); + let not_system_address = &alloy_primitives::keccak256("NotSystemAddress()")[..4]; + for gas_limit in TIERS { + let at = |service: &Service| { + let db = system_db().account_storage(ORACLE_CONTRACT_ADDRESS, SLOT, SERVICE_VALUE); + let run = run(db, service, tx_with_gas(ORACLE_CONTRACT_ADDRESS, &data, gas_limit)); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + assert!(!run.outcome.result.is_success(), "at {gas_limit}: {:?}", run.outcome.result); + assert_eq!(&output[..], not_system_address, "at {gas_limit}"); + run.outcome + }; + let service = Service::holding(SLOT, SERVICE_VALUE); + let served = at(&service); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)], "at {gas_limit}: the service answered"); + let read = at(&Service::default()); + + assert_eq!(served.result.tx_gas_used(), read.result.tx_gas_used(), "at {gas_limit}"); + assert_eq!(served.gas, read.gas, "at {gas_limit}: every ledger is the same"); + } +} + +/// The slot a read loaded is in the transaction's state, which a stateless witness is built +/// from, whichever source answered: a node that replays the block without the service finds it +/// there. The state holds the chain's value, not the service's, and the read changed nothing. +#[test] +fn test_the_read_slot_is_in_the_transactions_state_whichever_source_answered() { + for (service, answered) in + [(Service::holding(SLOT, SERVICE_VALUE), SERVICE_VALUE), (Service::default(), STATE_VALUE)] + { + let run = run( + db_with_state(), + &service, + call_tx(ORACLE_CONTRACT_ADDRESS, get_slot(SLOT), U256::ZERO), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!( + IOracle::getSlotCall::abi_decode_returns(run.outcome.result.output().unwrap()).unwrap(), + B256::from(answered), + ); + + let slot = run.outcome.state[&ORACLE_CONTRACT_ADDRESS] + .storage + .get(&SLOT) + .unwrap_or_else(|| panic!("answered {answered}: the slot is in the state")); + assert_eq!((slot.original_value, slot.present_value), (STATE_VALUE, STATE_VALUE)); + assert!(!slot.is_changed(), "answered {answered}"); + } +} + +/* ---------- reads next to writes and in nested frames ---------- */ + +/// A read after the Oracle's frame wrote the slot answers the service's value over the one the +/// frame stored, as on the legacy engine, and costs the cold access like every other read; with +/// no value from the service it answers what the frame stored. +#[test] +fn test_the_services_value_wins_over_the_frames_own_write() { + let params = mega_evm::satin_gas_params(); + // The push of the slot, the `SLOAD` and the `GAS` after it. + let cold = 3 + params.warm_storage_read_cost() + params.cold_storage_additional_cost() + 2; + let code = BytecodeBuilder::default() + .push_number(99_u8) + .push_u256(SLOT) + .append_many([SSTORE, GAS]) + .push_u256(SLOT) + // [g0, value, g1]: the value at 0, g0 - g1 at 0x20. + .append_many([SLOAD, GAS, SWAP1, PUSH0, MSTORE, SWAP1, SUB]) + .push_number(0x20_u8) + .append(MSTORE) + .push_number(0x40_u8) + .append_many([PUSH0, RETURN]) + .build(); + + for (service, expected) in [ + (Service::holding(SLOT, SERVICE_VALUE), SERVICE_VALUE), + (Service::default(), U256::from(99)), + ] { + let run = run( + db_with_state().account_code(ORACLE_CONTRACT_ADDRESS, code.clone()), + &service, + call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO), + ); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + let output = run.outcome.result.output().cloned().unwrap_or_default(); + assert_eq!(U256::from_be_slice(&output[..32]), expected); + assert_eq!(U256::from_be_slice(&output[32..64]).to::(), cold, "the read is cold"); + assert_eq!(service.seen(), vec![Seen::Read(SLOT)]); + } +} + +/// Records what every `SLOAD` cost the frame that ran it, with the frame's depth. +#[derive(Debug, Default)] +struct SloadCosts { + running: Option<(usize, u64)>, + costs: Vec<(usize, u64)>, +} + +impl Inspector for SloadCosts { + fn step(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + if interp.bytecode.opcode() == SLOAD { + self.running = Some((interp.input.depth, interp.gas.remaining())); + } + } + + fn step_end(&mut self, interp: &mut Interpreter, _context: &mut CTX) { + if let Some((depth, before)) = self.running.take() { + self.costs.push((depth, before - interp.gas.remaining())); + } + } +} + +/// Every read of a nested Oracle frame goes through the service and costs the cold access too: +/// the Oracle reads the slot once, calls itself, and the nested frame reads it twice. +#[test] +fn test_reads_in_a_nested_oracle_frame_are_cold_and_ask() { + let params = mega_evm::satin_gas_params(); + let cold = params.warm_storage_read_cost() + params.cold_storage_additional_cost(); + // Called with calldata, the code jumps to the nested frame's reads. + let outer = BytecodeBuilder::default() + .push_u256(SLOT) + .append_many([SLOAD, POP, PUSH0, PUSH0]) + .push_number(1_u8) // argsSize + .append_many([PUSH0, PUSH0]) // argsOffset, value + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP, STOP]) + .build_vec(); + let nested = BytecodeBuilder::default() + .append(JUMPDEST) + .push_u256(SLOT) + .append_many([SLOAD, POP]) + .push_u256(SLOT) + .append_many([SLOAD, POP, STOP]) + .build_vec(); + let mut code = vec![CALLDATASIZE, PUSH1, (4 + outer.len()) as u8, JUMPI]; + code.extend(outer); + code.extend(nested); + + for service in [Service::holding(SLOT, SERVICE_VALUE), Service::default()] { + let envs: ExternalEnvs = + ExternalEnvs { salt_env: EmptyExternalEnv, oracle_env: service.clone() }; + let db = db_with_state().account_code(ORACLE_CONTRACT_ADDRESS, Bytes::from(code.clone())); + let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, envs) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(SloadCosts::default()); + let outcome = evm + .execute_transaction(call_tx(ORACLE_CONTRACT_ADDRESS, [], U256::ZERO)) + .expect("the transaction is valid"); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(evm.inspector().costs, vec![(0, cold), (1, cold), (1, cold)]); + assert_eq!(service.seen(), vec![Seen::Read(SLOT); 3]); + } +} diff --git a/crates/mega-evm/tests/system/predeploys.rs b/crates/mega-evm/tests/system/predeploys.rs new file mode 100644 index 000000000..5fb84f78c --- /dev/null +++ b/crates/mega-evm/tests/system/predeploys.rs @@ -0,0 +1,182 @@ +//! The predeploys and the check Satin's activation block makes of them: the list, a matching +//! account read as it is, and every other account refused with one error. + +use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; +use mega_evm::{ + system::{ + check_system_contract, + keyless::{KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH}, + system_contract_specs, SystemContractCheckError, SystemContractSpec, + ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH, CREATE2_FACTORY_ADDRESS, + CREATE2_FACTORY_CODE, CREATE2_FACTORY_CODE_HASH, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE_HASH, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE_HASH, SYSTEM_CONTRACT_ADDRESSES, SYSTEM_CONTRACT_COUNT, + }, + test_utils::{ErrorInjectingDatabase, MemoryDatabase}, +}; +use revm::primitives::KECCAK_EMPTY; + +/// The factory's pinned hash is the hash of the runtime the list names. +#[test] +fn test_the_factory_code_hashes_to_its_pinned_hash() { + assert_eq!(keccak256(CREATE2_FACTORY_CODE), CREATE2_FACTORY_CODE_HASH); +} + +/// [S18.8] The list is the six `MegaETH` contracts in address order, then the factory, each with +/// the code hash of its code, and the public address list is the list's addresses in that order. +/// +/// Expected values: constants (the addresses and code hashes are the production constants). +#[test] +fn test_the_spec_list_is_the_seven_predeploys_in_order() { + let specs = system_contract_specs(); + assert_eq!(specs.len(), SYSTEM_CONTRACT_COUNT); + assert_eq!( + specs.clone().map(|spec| (spec.address, spec.code_hash)), + [ + (ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE_HASH), + (HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE_HASH), + (KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE_HASH), + (ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE_HASH), + (LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE_HASH), + (SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE_HASH), + (CREATE2_FACTORY_ADDRESS, CREATE2_FACTORY_CODE_HASH), + ] + ); + assert_eq!(specs.clone().map(|spec| spec.address), SYSTEM_CONTRACT_ADDRESSES); + for spec in &specs { + assert_eq!(keccak256(&spec.code), spec.code_hash, "{}", spec.address); + } +} + +/// The spec of `address` in the list. +fn spec_at(address: Address) -> SystemContractSpec { + system_contract_specs() + .into_iter() + .find(|spec| spec.address == address) + .expect("the address is a predeploy") +} + +/// [S18] An address holding the expected code passes whatever else it holds — the nonce mainnet's +/// six hold (0), the factory's (in the thousands), a balance, storage — and the check returns the +/// account as a read-only entry, as held: neither touched nor created, no storage, the nonce kept. +/// +/// Expected values: independent (the account each test puts in the database). +#[test] +fn test_the_expected_code_is_read_as_it_is() { + for spec in system_contract_specs() { + for nonce in [0, 1, 1_443] { + let mut db = MemoryDatabase::default() + .account_code(spec.address, spec.code.clone()) + .account_nonce(spec.address, nonce) + .account_balance(spec.address, U256::from(9)) + .account_storage(spec.address, U256::from(1), U256::from(7)); + let state = check_system_contract(&mut db, &spec) + .unwrap_or_else(|error| panic!("{} at nonce {nonce}: {error}", spec.address)); + assert_eq!(state.len(), 1, "{}: the account alone", spec.address); + let account = &state[&spec.address]; + assert!(!account.is_touched() && !account.is_created(), "{}", spec.address); + assert!(account.storage.is_empty(), "{}: nothing written", spec.address); + assert_eq!(account.info.code_hash, spec.code_hash); + assert_eq!((account.info.nonce, account.info.balance), (nonce, U256::from(9))); + } + } +} + +/// [S18] Anything but the expected code is refused with the one error, naming the address, the +/// expected hash and the one held: no account, an account without code — funded, or at a used +/// nonce — an older version of the contract, another contract's version and other code. Satin +/// creates and upgrades nothing. +/// +/// Expected values: independent (the code hash each state holds). +#[test] +fn test_anything_else_is_unexpected_code() { + use mega_system_contracts::{oracle, sequencer_registry}; + let mut near_miss = oracle::V1_1_0_CODE.to_vec(); + *near_miss.last_mut().unwrap() ^= 1; + let near_miss = Bytes::from(near_miss); + let cases: Vec<(&str, Address, MemoryDatabase, B256)> = vec![ + ("no account", ORACLE_CONTRACT_ADDRESS, MemoryDatabase::default(), KECCAK_EMPTY), + ( + "a funded account without code", + SEQUENCER_REGISTRY_ADDRESS, + MemoryDatabase::default().account_balance(SEQUENCER_REGISTRY_ADDRESS, U256::from(1)), + KECCAK_EMPTY, + ), + ( + "an account without code at a used nonce", + CREATE2_FACTORY_ADDRESS, + MemoryDatabase::default().account_nonce(CREATE2_FACTORY_ADDRESS, 42), + KECCAK_EMPTY, + ), + ( + "the Oracle at 1.0.0", + ORACLE_CONTRACT_ADDRESS, + MemoryDatabase::default().account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_0_0_CODE), + oracle::V1_0_0_CODE_HASH, + ), + ( + "the Oracle at 1.1.0", + ORACLE_CONTRACT_ADDRESS, + MemoryDatabase::default().account_code(ORACLE_CONTRACT_ADDRESS, oracle::V1_1_0_CODE), + oracle::V1_1_0_CODE_HASH, + ), + ( + "the registry at 1.0.0", + SEQUENCER_REGISTRY_ADDRESS, + MemoryDatabase::default() + .account_code(SEQUENCER_REGISTRY_ADDRESS, sequencer_registry::V1_0_0_CODE), + sequencer_registry::V1_0_0_CODE_HASH, + ), + ( + "the Oracle's 1.0.0 at the registry's address", + SEQUENCER_REGISTRY_ADDRESS, + MemoryDatabase::default().account_code(SEQUENCER_REGISTRY_ADDRESS, oracle::V1_0_0_CODE), + oracle::V1_0_0_CODE_HASH, + ), + ( + "a near miss of the Oracle's 1.1.0", + ORACLE_CONTRACT_ADDRESS, + MemoryDatabase::default().account_code(ORACLE_CONTRACT_ADDRESS, near_miss.clone()), + keccak256(&near_miss), + ), + ( + "other code at the factory's address", + CREATE2_FACTORY_ADDRESS, + MemoryDatabase::default() + .account_code(CREATE2_FACTORY_ADDRESS, Bytes::from_static(&[0xfe])), + keccak256([0xfe]), + ), + ]; + for (name, address, mut db, held) in cases { + let spec = spec_at(address); + let error = check_system_contract(&mut db, &spec).expect_err(name); + match &error { + SystemContractCheckError::UnexpectedCode { address: at, expected, found } => { + assert_eq!((*at, *expected, *found), (address, spec.code_hash, held), "{name}") + } + other => panic!("{name}: expected UnexpectedCode, got {other}"), + } + let message = error.to_string(); + assert!(message.contains(&address.to_string()), "{name}: {message}"); + assert!(message.contains(&spec.code_hash.to_string()), "{name}: {message}"); + let holding = if held == KECCAK_EMPTY { + "it holds no code".to_string() + } else { + format!("it holds code hash {held}") + }; + assert!(message.ends_with(&holding), "{name}: {message}"); + } +} + +/// A failed account load is [`SystemContractCheckError::Database`], and that inner error is the +/// `source` of the check's error. +#[test] +fn test_a_database_error_is_the_source_of_the_check_error() { + let mut db = ErrorInjectingDatabase::new(MemoryDatabase::default()); + db.fail_on_account = Some(ORACLE_CONTRACT_ADDRESS); + let err = check_system_contract(&mut db, &spec_at(ORACLE_CONTRACT_ADDRESS)) + .expect_err("the load fails"); + assert!(matches!(err, SystemContractCheckError::Database(_)), "{err}"); + assert!(core::error::Error::source(&err).is_some(), "the database error is the source"); +} diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs new file mode 100644 index 000000000..f20ffb471 --- /dev/null +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -0,0 +1,597 @@ +//! What `MegaLimitControl.remainingComputeGas()` answers: the compute the calling frame could +//! still spend, the lesser of its own regular gas — with the gas the call forwarded counted back, +//! because the answer hands it back — and what gas detention's limit leaves the transaction once +//! it read volatile data. +//! +//! Most cases read the caller's gas with `GAS` right after the call returns: the answer gives the +//! forward back untouched, so the caller's own gas at the call is that reading plus the `POP` of +//! the call's status and the `GAS` itself, four gas. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + system::{IMegaLimitControl, IOracle, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, +}; +use revm::{bytecode::opcode::*, context::BlockEnv}; + +use crate::common::{body_history, call_tx_with_gas, system_db, AnswerAndResume, CALLER}; + +const CONTRACT: Address = address!("0x0000000000000000000000000000000000300001"); +const CONTRACT2: Address = address!("0x0000000000000000000000000000000000300002"); +const CONTRACT3: Address = address!("0x0000000000000000000000000000000000300003"); + +/// The cap a read of the block environment sets. +const CAP: u64 = BLOCK_ENV_ACCESS_COMPUTE_GAS; + +/// Below the execution cap: no reservoir. +const BELOW: u64 = 100_000_000; +/// Above it: a reservoir of 100,000,000. +const ABOVE: u64 = TX_GAS_LIMIT_CAP + 100_000_000; +const TIERS: [u64; 2] = [BELOW, ABOVE]; + +/// What the POP of the call's status and the `GAS` after it cost. +const READING: u64 = 4; + +const SELECTOR: [u8; 4] = IMegaLimitControl::remainingComputeGasCall::SELECTOR; + +/// A block whose beneficiary is `beneficiary`. +fn block(beneficiary: Address) -> BlockEnv { + BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, beneficiary, ..Default::default() } +} + +/// A transaction from [`CALLER`] to `to` with `data`, carrying `gas_limit`. +fn tx(to: Address, data: &[u8], gas_limit: u64) -> MegaTransaction { + call_tx_with_gas(to, data, U256::ZERO, gas_limit) +} + +/// Runs `tx` over `db` in a block whose beneficiary is `beneficiary`, under the default limits, +/// which detain. +fn execute_in( + db: MemoryDatabase, + beneficiary: Address, + tx: MegaTransaction, +) -> MegaTransactionOutcome { + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_block(block(beneficiary)) + .with_chain(zero_fee_l1_block_info()); + let outcome = MegaEvm::new(ctx).execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome +} + +/// Runs `tx` over `db`, the beneficiary being nobody the tests use. +fn execute(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + execute_in(db, Address::ZERO, tx) +} + +/// The words the transaction returned. +fn words(outcome: &MegaTransactionOutcome) -> Vec { + let output = outcome.result.output().cloned().unwrap_or_default(); + output.chunks(32).map(|word| U256::from_be_slice(word).to::()).collect() +} + +/// Appends a query through `scheme`, forwarding `gas` (all it has when `None`), that keeps the +/// answer at `0x20 * slot` and, next to it, what `GAS` reads once the call returned. +fn query(code: BytecodeBuilder, scheme: u8, gas: Option, slot: u64) -> BytecodeBuilder { + let code = code + .mstore(0x200, SELECTOR) + .push_number(32_u8) // retSize + .push_number(0x20 * slot) // retOffset + .push_number(4_u8) // argsSize + .push_number(0x200_u16); // argsOffset + let code = if scheme == CALL { code.push_number(0_u8) } else { code }; + let code = code.push_address(LIMIT_CONTROL_ADDRESS); + let code = match gas { + Some(gas) => code.push_number(gas), + None => code.append(GAS), + }; + code.append_many([scheme, POP, GAS]).push_number(0x20 * (slot + 1)).append(MSTORE) +} + +/// Appends a return of the first `words` words of memory. +fn returning(code: BytecodeBuilder, words: u64) -> Bytes { + code.push_number(0x20 * words).append_many([PUSH0, RETURN]).build() +} + +/// Appends `rounds` pushes and pops, five gas each. +fn burn(mut code: BytecodeBuilder, rounds: u32) -> BytecodeBuilder { + for _ in 0..rounds { + code = code.push_number(1_u8).append(POP); + } + code +} + +/// The answer to a query `code` makes, and what `GAS` read after it, running as [`CONTRACT`]. +fn answer_of(code: Bytes, gas_limit: u64) -> (u64, u64) { + let outcome = execute(system_db().account_code(CONTRACT, code), tx(CONTRACT, &[], gas_limit)); + let words = words(&outcome); + (words[0], words[1]) +} + +/* ---------- the legacy engine's rows ---------- */ + +/// A transaction that calls the contract itself hears the regular gas its own frame was given: +/// its gas limit less all it paid before the frame below the execution cap, where nothing but +/// regular gas pays; the cap less its intrinsic regular gas above it, where the reservoir paid the +/// rest. +#[test] +fn test_direct_tx_remaining_compute_gas() { + for gas_limit in TIERS { + let outcome = execute(system_db(), tx(LIMIT_CONTROL_ADDRESS, &SELECTOR, gas_limit)); + let answer = IMegaLimitControl::remainingComputeGasCall::abi_decode_returns( + outcome.result.output().unwrap(), + ) + .unwrap(); + if gas_limit < TX_GAS_LIMIT_CAP { + // What it paid before the frame, which the answer spends nothing of: the receipt's + // figure where the EIP-7623 floor does not bind, as it does not at the spec's prices. + let paid = outcome.result.gas().total_gas_spent(); + assert_eq!(answer, gas_limit - paid, "below the cap"); + } else { + assert_eq!(answer, TX_GAS_LIMIT_CAP - outcome.gas.regular, "above the cap"); + assert_eq!( + outcome.gas.history, + body_history(SELECTOR.len() as u64), + "the body's history came out of the reservoir", + ); + } + } +} + +/// A `STATICCALL` hears the caller's own gas, the forward counted back. +#[test] +fn test_remaining_compute_gas_staticcall() { + for gas_limit in TIERS { + let (answer, gas) = answer_of( + returning(query(BytecodeBuilder::default(), STATICCALL, None, 0), 2), + gas_limit, + ); + assert_eq!(answer, gas + READING, "at {gas_limit}"); + assert!(answer <= TX_GAS_LIMIT_CAP, "regular gas never exceeds the execution cap"); + } +} + +/// Compute spent before the query comes off the answer, gas for gas. +#[test] +fn test_remaining_compute_gas_decreases_after_compute_work() { + let (base, _) = + answer_of(returning(query(BytecodeBuilder::default(), CALL, None, 0), 2), BELOW); + let (heavy, _) = answer_of( + returning(query(burn(BytecodeBuilder::default(), 20_000), CALL, None, 0), 2), + BELOW, + ); + assert_eq!(base - heavy, 20_000 * 5); +} + +/// A second query hears less than the first, by what the caller spent between the two: the +/// query itself costs the caller only its call's overhead. +#[test] +fn test_remaining_compute_gas_sequential_queries_decrease() { + let code = query(query(BytecodeBuilder::default(), CALL, None, 0), CALL, None, 2); + let words = words(&execute( + system_db().account_code(CONTRACT, returning(code, 4)), + tx(CONTRACT, &[], BELOW), + )); + let [first, first_gas, second, second_gas] = words[..] else { panic!("{words:?}") }; + assert_eq!(first, first_gas + READING); + assert_eq!(second, second_gas + READING); + assert!(second < first); + assert!(first - second < 1_000, "the second query's overhead: {}", first - second); +} + +/// The exact value: the frame's own gas, see [`test_direct_tx_remaining_compute_gas`]; here with +/// the query's calldata padded, which the transaction pays for before its frame. +#[test] +fn test_remaining_compute_gas_exact_value_matches_tracker() { + let data: Vec = SELECTOR.iter().copied().chain([0xff; 64]).collect(); + let outcome = execute(system_db(), tx(LIMIT_CONTROL_ADDRESS, &data, 1_000_000)); + let answer = IMegaLimitControl::remainingComputeGasCall::abi_decode_returns( + outcome.result.output().unwrap(), + ) + .unwrap(); + assert_eq!(answer, 1_000_000 - outcome.result.gas().total_gas_spent()); +} + +/// A caller that forwards the query little still hears its own gas, not the forward: the answer +/// is about the caller. +#[test] +fn test_remaining_compute_gas_inner_call_returns_frame_remaining() { + let (answer, gas) = + answer_of(returning(query(BytecodeBuilder::default(), CALL, Some(100_000), 0), 2), BELOW); + assert_eq!(answer, gas + READING); + assert!(answer > 99_000_000, "{answer}"); +} + +/// A query from a frame two levels down hears that frame's gas, not its caller's. +#[test] +fn test_remaining_compute_gas_two_level_nesting_returns_inner_frame() { + let inner = returning(query(BytecodeBuilder::default(), CALL, None, 0), 2); + let outer = burn(BytecodeBuilder::default(), 50_000) + .push_number(64_u8) // retSize + .push_number(0_u8) // retOffset + .append_many([PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT2) + .push_number(50_000_000_u32) + .append_many([CALL, POP]); + let outer = returning(outer, 2); + let db = system_db().account_code(CONTRACT, outer).account_code(CONTRACT2, inner); + let words = words(&execute(db, tx(CONTRACT, &[], BELOW))); + assert_eq!(words[0], words[1] + READING); + assert!(words[0] < 50_000_000, "at most what the frame was given: {}", words[0]); +} + +/// What a child spent is gone from its caller's answer even when the child reverted: compute is +/// not undone. +#[test] +fn test_remaining_compute_gas_persistent_after_inner_revert() { + let child = burn(BytecodeBuilder::default(), 20_000).revert().build(); + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT2) + .push_number(50_000_000_u32) + .append_many([CALL, POP]); + let caller = returning(query(caller, CALL, None, 0), 2); + let db = system_db().account_code(CONTRACT, caller).account_code(CONTRACT2, child); + let after_revert = words(&execute(db, tx(CONTRACT, &[], BELOW))); + let (base, _) = + answer_of(returning(query(BytecodeBuilder::default(), CALL, None, 0), 2), BELOW); + assert_eq!(after_revert[0], after_revert[1] + READING); + assert!(base - after_revert[0] > 20_000 * 5, "the child's compute stays spent"); +} + +/// After a read of the block environment the answer is what the cap leaves: the cap less what the +/// caller spent since the read, which `GAS` right after the read and right after the query +/// measure. The caller's own gas is far above it. +#[test] +fn test_remaining_compute_gas_clamped_by_detention_limit() { + for gas_limit in TIERS { + let code = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP, GAS]) + .append_many([PUSH0, MSTORE]); + // The read's gas at 0, the answer at 0x20, the gas after it at 0x40. + let code = returning(query(code, CALL, None, 1), 3); + let words = + words(&execute(system_db().account_code(CONTRACT, code), tx(CONTRACT, &[], gas_limit))); + let [at_read, answer, after] = words[..] else { panic!("{words:?}") }; + // `GAS` after the read reads the `POP` and its own two gas less than the read left; the + // caller held `after + READING` at the query. + let spent_since_the_read = (at_read + 2 + 2) - (after + READING); + assert_eq!(answer, CAP - spent_since_the_read, "at {gas_limit}"); + assert!(after + READING > CAP, "the caller's own gas is not what binds"); + } +} + +/* ---------- the four boundaries: below and above the cap, with and without a read ---------- */ + +/// A transaction that is the beneficiary is detained from its start, before its frame: calling +/// the contract directly, it hears the cap, below and above the execution cap alike. The same +/// transaction from an ordinary sender hears its frame's own gas. +#[test] +fn test_a_detained_transactions_own_call_hears_the_cap() { + for gas_limit in TIERS { + let detained = + execute_in(system_db(), CALLER, tx(LIMIT_CONTROL_ADDRESS, &SELECTOR, gas_limit)); + let undetained = execute(system_db(), tx(LIMIT_CONTROL_ADDRESS, &SELECTOR, gas_limit)); + let answer = |outcome: &MegaTransactionOutcome| { + IMegaLimitControl::remainingComputeGasCall::abi_decode_returns( + outcome.result.output().unwrap(), + ) + .unwrap() + }; + assert_eq!(answer(&detained), CAP, "at {gas_limit}"); + assert!(answer(&undetained) > CAP, "at {gas_limit}: its own gas"); + } + + // A detained transaction whose frame has less than the cap hears its own gas. + let outcome = execute_in(system_db(), CALLER, tx(LIMIT_CONTROL_ADDRESS, &SELECTOR, 10_000_000)); + let answer = IMegaLimitControl::remainingComputeGasCall::abi_decode_returns( + outcome.result.output().unwrap(), + ) + .unwrap(); + assert_eq!(answer, 10_000_000 - outcome.result.gas().total_gas_spent()); +} + +/// A contract's query, without a read and after one, below and above the execution cap: its own +/// gas without the read, capped at the execution cap; what the cap leaves after it. The two tiers +/// hear the same answer after the read, and answers that differ by the reservoir's share of the +/// intrinsic cost without it. +#[test] +fn test_a_contracts_query_below_and_above_the_execution_cap() { + let plain = + returning(query(BytecodeBuilder::default().append_many([PUSH0, POP]), CALL, None, 0), 2); + let read = returning( + query(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), CALL, None, 0), + 2, + ); + let mut after_read = vec![]; + for gas_limit in TIERS { + let (answer, gas) = answer_of(plain.clone(), gas_limit); + assert_eq!(answer, gas + READING, "without a read, at {gas_limit}"); + assert!(answer < gas_limit.min(TX_GAS_LIMIT_CAP)); + + let (answer, gas) = answer_of(read.clone(), gas_limit); + assert!(answer < CAP && gas + READING > answer, "after the read, at {gas_limit}"); + after_read.push(answer); + } + assert_eq!(after_read[0], after_read[1], "the cap leaves the same compute in both tiers"); +} + +/// A detained caller whose own gas is below what the cap leaves hears its own gas: the answer is +/// the lesser of the two. +#[test] +fn test_a_detained_caller_with_less_than_the_allowance_hears_its_own_gas() { + let inner = returning(query(BytecodeBuilder::default(), CALL, None, 0), 2); + let outer = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .push_number(64_u8) // retSize + .push_number(0_u8) // retOffset + .append_many([PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT2) + .push_number(1_000_000_u32) + .append_many([CALL, POP]); + let db = system_db().account_code(CONTRACT, returning(outer, 2)).account_code(CONTRACT2, inner); + let words = words(&execute(db, tx(CONTRACT, &[], BELOW))); + assert_eq!(words[0], words[1] + READING, "the child's own gas"); + assert!(words[0] < 1_000_000); +} + +/// A read a child made binds its caller's answer once the child returned: the limit is the +/// transaction's. +#[test] +fn test_a_childs_read_binds_its_callers_answer() { + let child = BytecodeBuilder::default().append_many([TIMESTAMP, POP, STOP]).build(); + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT2) + .push_number(1_000_000_u32) + .append_many([CALL, POP]); + let caller = returning(query(caller, CALL, None, 0), 2); + let db = system_db().account_code(CONTRACT, caller).account_code(CONTRACT2, child); + let words = words(&execute(db, tx(CONTRACT, &[], BELOW))); + assert!(words[0] < CAP && words[0] > CAP - 10_000, "what the cap leaves: {}", words[0]); + assert!(words[1] + READING > CAP, "not the caller's own gas"); +} + +/* ---------- the answer is what the caller can spend when it resumes ---------- */ + +/// Runs `tx` over `db` in a block whose beneficiary is `beneficiary`, under the default limits, +/// and returns every answer with the spendable gas its caller resumed with. +fn answers_and_resumes( + db: MemoryDatabase, + beneficiary: Address, + tx: MegaTransaction, +) -> Vec<(u64, u64)> { + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_block(block(beneficiary)) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(AnswerAndResume::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let answers = evm.inspector(); + assert_eq!(answers.pending, None, "every answer was followed by its caller's next step"); + answers.pairs.clone() +} + +/// Appends a `CALL` of `target` forwarding `gas` and carrying `value`, discarding its status. +fn calls(code: BytecodeBuilder, target: Address, gas: u64, value: u64) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(value) + .push_address(target) + .push_number(gas) + .append_many([CALL, POP]) +} + +/// Code that reads the block's timestamp. +fn reads_timestamp(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([TIMESTAMP, POP]) +} + +/// Code that queries through `CALL`, forwarding all it has, and stops. +fn queries() -> Bytes { + query(BytecodeBuilder::default(), CALL, None, 0).stop().build() +} + +/// The answer is exactly the spendable regular gas the caller resumes with — what it can still +/// spend — whether nothing detains it, its own read does, a child's read does before a child that +/// halted, it was started by a value call from a caller detained or not, its sender is the +/// beneficiary, or it read the Oracle's storage; below and above the execution cap. +#[test] +fn test_the_answer_is_what_the_caller_resumes_with() { + let get_slot = IOracle::getSlotCall { slot: U256::ZERO }.abi_encode(); + let reads_oracle = || { + BytecodeBuilder::default() + .mstore(0x0, &get_slot) + .append_many([PUSH0, PUSH0]) + .push_number(get_slot.len() as u64) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + }; + let halts = BytecodeBuilder::default().append(INVALID).build(); + + for gas_limit in TIERS { + let cases: [(&str, MemoryDatabase, Address, usize); 8] = [ + ("undetained", system_db().account_code(CONTRACT, queries()), Address::ZERO, 1), + ( + "detained by its own read, a small forward and a STATICCALL", + system_db().account_code( + CONTRACT, + query( + query(reads_timestamp(BytecodeBuilder::default()), CALL, Some(100), 0), + STATICCALL, + None, + 2, + ) + .stop() + .build(), + ), + Address::ZERO, + 2, + ), + ( + "detained by a child's read, after a child that halted", + system_db() + .account_code( + CONTRACT, + query( + calls( + calls(BytecodeBuilder::default(), CONTRACT2, 1_000_000, 0), + CONTRACT3, + 500_000, + 0, + ), + CALL, + None, + 0, + ) + .stop() + .build(), + ) + .account_code( + CONTRACT2, + reads_timestamp(BytecodeBuilder::default()).stop().build(), + ) + .account_code(CONTRACT3, halts.clone()), + Address::ZERO, + 1, + ), + ( + "a value-called callee", + system_db() + .account_code( + CONTRACT, + calls(BytecodeBuilder::default(), CONTRACT2, 50_000, 1).stop().build(), + ) + .account_balance(CONTRACT, U256::from(10)) + .account_code(CONTRACT2, queries()), + Address::ZERO, + 1, + ), + ( + "a value-called callee that read", + system_db() + .account_code( + CONTRACT, + calls(BytecodeBuilder::default(), CONTRACT2, 50_000, 1).stop().build(), + ) + .account_balance(CONTRACT, U256::from(10)) + .account_code( + CONTRACT2, + query(reads_timestamp(BytecodeBuilder::default()), CALL, None, 0) + .stop() + .build(), + ), + Address::ZERO, + 1, + ), + ( + "a value-called callee of a caller that read", + system_db() + .account_code( + CONTRACT, + calls(reads_timestamp(BytecodeBuilder::default()), CONTRACT2, 50_000, 1) + .stop() + .build(), + ) + .account_balance(CONTRACT, U256::from(10)) + .account_code(CONTRACT2, queries()), + Address::ZERO, + 1, + ), + ("a beneficiary sender", system_db().account_code(CONTRACT, queries()), CALLER, 1), + ( + "after an Oracle read", + system_db() + .account_code(CONTRACT, query(reads_oracle(), CALL, None, 0).stop().build()), + Address::ZERO, + 1, + ), + ]; + for (case, db, beneficiary, queries) in cases { + let pairs = answers_and_resumes(db, beneficiary, tx(CONTRACT, &[], gas_limit)); + assert_eq!(pairs.len(), queries, "{case}, at {gas_limit}"); + for (answer, spendable) in pairs { + assert_eq!(answer, spendable, "{case}, at {gas_limit}"); + } + } + } +} + +/// A callee a value call started hears the stipend counted, whether or not the transaction is +/// detained: detention counts the stipend outside compute, so its allowance carries it as the +/// callee's own gas does, and the callee hears the stipend more than the same callee a call +/// without value started. +#[test] +fn test_a_value_called_callee_hears_its_stipend_whether_or_not_detained() { + let stipend = 2_300; + let answer = |caller_reads: bool, value: u64| { + let caller = BytecodeBuilder::default(); + let caller = if caller_reads { reads_timestamp(caller) } else { caller }; + let db = system_db() + .account_code(CONTRACT, calls(caller, CONTRACT2, 50_000, value).stop().build()) + .account_balance(CONTRACT, U256::from(10)) + .account_code(CONTRACT2, queries()); + let pairs = answers_and_resumes(db, Address::ZERO, tx(CONTRACT, &[], BELOW)); + assert_eq!(pairs.len(), 1); + pairs[0].0 + }; + for caller_reads in [false, true] { + assert_eq!( + answer(caller_reads, 1), + answer(caller_reads, 0) + stipend, + "read: {caller_reads}" + ); + } + assert_eq!(answer(false, 1), answer(true, 1), "detained or not, the same answer"); +} + +/// A caller that acts on the answer can spend it and no more: after a read, a loop that spends a +/// little less than the answer completes, and one that spends a little more is stopped at the +/// compute limit. +#[test] +fn test_a_caller_can_spend_the_answer_and_no_more() { + // After the query, `answer / 26 + extra` rounds of a loop whose body costs 26 gas: + // JUMPDEST 1, PUSH1 3, SWAP1 3, SUB 3, DUP1 3, PUSH1 3, JUMPI 10. + for extra in [-4_i64, 4] { + let code = query(reads_timestamp(BytecodeBuilder::default()), CALL, None, 0) + .append_many([PUSH0, MLOAD]) + .push_number(26_u8) + .append_many([SWAP1, DIV]) + .push_number(extra.unsigned_abs()); + let code = if extra < 0 { code.append_many([SWAP1, SUB]) } else { code.append(ADD) }; + let mut code = code.build_vec(); + let start = u8::try_from(code.len()).expect("the loop starts within a PUSH1"); + code.extend([JUMPDEST, PUSH1, 1, SWAP1, SUB, DUP1, PUSH1, start, JUMPI, STOP]); + + let ctx = MegaContext::new( + system_db().account_code(CONTRACT, Bytes::from(code)), + MegaSpecId::SATIN, + ) + .with_block(block(Address::ZERO)) + .with_chain(zero_fee_l1_block_info()) + .with_tx_runtime_limits( + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(100_000), + ); + let outcome = MegaEvm::new(ctx) + .execute_transaction(tx(CONTRACT, &[], BELOW)) + .expect("the transaction is valid"); + + if extra < 0 { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + } else { + assert!( + matches!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ), + "{:?}", + outcome.limit_exceeded + ); + } + } +} diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 2d7a1409f..84ab99255 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -1,26 +1,35 @@ //! The system-address transaction: what it may do, what it pays, and what still validates it. use alloy_evm::Evm; -use alloy_op_evm::OpTx; +use alloy_op_evm::{OpTx, OpTxError}; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ - is_deposit_like_transaction, is_mega_system_transaction_with, IOracle, ISequencerRegistry, - MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, - SEQUENCER_REGISTRY_ADDRESS, + is_mega_system_transaction_with, IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE, }, - test_utils::{op_transaction, MemoryDatabase}, - MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + test_utils::{op_transaction, ErrorInjectingDatabase, GasInspector, MemoryDatabase}, + EvmTxRuntimeLimits, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaTransaction, + MegaTransactionOutcome, }; use mega_system_contracts::sequencer_registry::storage_slots::CURRENT_SYSTEM_ADDRESS; +use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpTransactionError}; use revm::{ - context::{result::ExecutionResult, CfgEnv, TxEnv}, - database::State, + bytecode::opcode::{SLOAD, STOP}, + context::{ + result::{EVMError, ExecutionResult, InvalidTransaction}, + transaction::{AccessList, AccessListItem}, + CfgEnv, TxEnv, + }, + database::{states::bundle_state::BundleRetention, State}, DatabaseCommit, }; -use crate::common::{block, context, system_db, CALLER, GAS_LIMIT}; +use crate::common::{ + account_state_gas, block, context, state_is_free, system_db, CALLER, GAS_LIMIT, +}; /// The chain the tests run on. const CHAIN_ID: u64 = 4326; @@ -28,23 +37,17 @@ const CHAIN_ID: u64 = 4326; /// A contract that is not on the whitelist. const OFF_WHITELIST: Address = address!("0x00000000000000000000000000000000000dead1"); -/// The refusal every transaction from the system address that is not a system transaction gets: -/// the rule it broke, whichever way it broke it. -const NOT_A_SYSTEM_TRANSACTION: &str = - "a transaction from the system address must be a legacy call to a whitelisted contract"; +/// A balance that pays any fee the tests' transactions carry. +const FUNDS: u64 = 1_000_000_000_000_000; /// The Oracle's slot the system transactions write. const ORACLE_SLOT: U256 = U256::ZERO; /// A database with the system contracts in place and the registry naming -/// [`MEGA_SYSTEM_ADDRESS`] the current system address, which is what lets an Oracle write from -/// it through. +/// [`MEGA_SYSTEM_ADDRESS`] the current system address: that is what makes a legacy call from it +/// to the Oracle a system-address transaction, and what lets its Oracle write through. fn chain_db() -> MemoryDatabase { - system_db().account_storage( - SEQUENCER_REGISTRY_ADDRESS, - CURRENT_SYSTEM_ADDRESS, - U256::from_be_slice(MEGA_SYSTEM_ADDRESS.as_slice()), - ) + system_db().sequencer_registry(MEGA_SYSTEM_ADDRESS) } /// A legacy transaction from `caller`, as the sequencer builds one. @@ -153,7 +156,6 @@ fn test_a_system_transaction_is_promoted_to_a_deposit() { let mut evm = MegaEvm::new(chain_context(chain_db())); let tx = system_tx(0, B256::with_last_byte(0x11)); assert!(is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS)); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); assert!(evm.transact_raw(tx).expect("the transaction is valid").result.is_success()); assert_eq!( @@ -190,13 +192,6 @@ fn test_a_system_transaction_pays_no_fee() { ); } -/// A system transaction needs no balance at all: nothing is deducted from its caller. -#[test] -fn test_a_system_transaction_needs_no_balance() { - let outcome = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x33))); - assert!(outcome.result.is_success(), "{:?}", outcome.result); -} - /// A system transaction that carries value moves exactly that value, and no fee with it. #[test] fn test_a_system_transaction_moves_only_its_value() { @@ -218,33 +213,180 @@ fn test_a_system_transaction_moves_only_its_value() { assert_eq!(outcome.state[&ORACLE_CONTRACT_ADDRESS].info.balance, transferred); } -/// A transaction from the system address to a contract that is not on the whitelist is -/// rejected, and so is one that creates a contract. +/// `tx` with its type set to `tx_type`: an EIP-2930 (1) or EIP-1559 (2) transaction with the same +/// fields and an empty access list. An EIP-1559 one tips its whole fee cap, so it pays the price +/// the legacy one does on a block with no base fee. +fn typed(mut tx: MegaTransaction, tx_type: u8) -> MegaTransaction { + tx.0.base.tx_type = tx_type; + if tx_type == 2 { + tx.0.base.gas_priority_fee = Some(tx.0.base.gas_price); + } + tx +} + +/// A call to the Oracle's `getSlot`, which reads nothing of the registry itself. +fn get_slot() -> Bytes { + IOracle::getSlotCall { slot: ORACLE_SLOT }.abi_encode().into() +} + +/// The transactions from `caller` that do not have the system shape: a legacy call off the +/// whitelist, a legacy creation, and an EIP-2930 and an EIP-1559 call to the Oracle. +fn other_shapes(caller: Address) -> [(&'static str, MegaTransaction); 4] { + let oracle = TxKind::Call(ORACLE_CONTRACT_ADDRESS); + [ + ("off the whitelist", legacy_tx(caller, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0)), + ("a creation", legacy_tx(caller, TxKind::Create, Bytes::from_static(&[STOP]), 0)), + ("EIP-2930", typed(legacy_tx(caller, oracle, get_slot(), 0), 1)), + ("EIP-1559", typed(legacy_tx(caller, oracle, get_slot(), 0), 2)), + ] +} + +/// A transaction from the live system address that does not have the system shape — off the +/// whitelist, a creation, another type than legacy — is invalid: refused with the same error +/// whether or not the system address could pay its fee, and changing nothing. #[test] -fn test_the_whitelist_is_what_the_system_address_may_call() { - let off_whitelist = - legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); - let refused = rejection(chain_db(), off_whitelist); - assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); +fn test_another_shape_from_the_live_system_address_is_invalid() { + let db = || chain_db().account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])); + for (shape, tx) in other_shapes(MEGA_SYSTEM_ADDRESS) { + for db in [db(), db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(FUNDS))] { + let error = MegaEvm::new(chain_context(db)) + .execute_transaction(tx.clone()) + .expect_err("the system address sends the system shape alone"); + let EVMError::Transaction(OpTxError(OpTransactionError::Base( + InvalidTransaction::Str(message), + ))) = &error + else { + panic!("{shape}: not the shape's refusal: {error:?}"); + }; + assert_eq!(message, SYSTEM_ADDRESS_WITHOUT_SYSTEM_SHAPE, "{shape}"); + } + } +} - let creation = legacy_tx( - MEGA_SYSTEM_ADDRESS, - TxKind::Create, - Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xf3]), - 0, - ); - let refused = rejection(chain_db(), creation); - assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); +/// Every transaction reads the registry when it is validated, whatever its shape and whoever +/// sends it: its returned state holds the registry's account, untouched, and the system-address +/// slot, unchanged, and a database that cannot serve the registry's account or that slot fails it +/// with the database's error, a deposit included. +#[test] +fn test_every_transaction_reads_the_registry() { + let funded = || { + chain_db() + .account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])) + .account_balance(CALLER, U256::from(FUNDS)) + }; + let shaped = legacy_tx(CALLER, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 0); + let deposit = deposit_tx(CALLER, TxKind::Call(OFF_WHITELIST), U256::ZERO, 0); + let transactions = other_shapes(CALLER) + .into_iter() + .chain([("the system shape", shaped), ("a deposit", deposit)]); + for (shape, tx) in transactions { + let outcome = MegaEvm::new(chain_context(funded())) + .execute_transaction(tx.clone()) + .expect("an ordinary transaction"); + assert!(outcome.result.is_success(), "{shape}: {:?}", outcome.result); + let registry = &outcome.state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "{shape}: a read-only entry"); + let slot = ®istry.storage[&CURRENT_SYSTEM_ADDRESS]; + assert!(!slot.is_changed(), "{shape}"); + assert_eq!(slot.present_value(), U256::from_be_slice(MEGA_SYSTEM_ADDRESS.as_slice())); + + let mut account = ErrorInjectingDatabase::new(funded()); + account.fail_on_account = Some(SEQUENCER_REGISTRY_ADDRESS); + let mut slot = ErrorInjectingDatabase::new(funded()); + slot.fail_on_storage = Some((SEQUENCER_REGISTRY_ADDRESS, CURRENT_SYSTEM_ADDRESS)); + for db in [account, slot] { + let error = MegaEvm::new(chain_context(db)) + .execute_transaction(tx.clone()) + .expect_err("the registry is read"); + assert!(matches!(error, EVMError::Database(_)), "{shape}: {error:?}"); + } + } } -/// A transaction from the system address that is not a legacy one is refused whatever it calls: -/// the sequencer builds the legacy shape, and the promotion is what turns it into a deposit. +/// Every transaction starts with the registry's account and its system-address slot warm, as +/// EIP-3651 starts the block beneficiary warm: validation reads the live system address for every +/// transaction, whatever its shape. A user's call to the Oracle's `setSlots` makes the Oracle ask +/// the registry for the system address itself, and that `SLOAD` pays the warm price, as a legacy +/// call, as an EIP-2930 call, and as one whose access list names the slot alike: the shape of the +/// envelope changes nothing the transaction pays, and the access list adds only its own +/// intrinsic cost. +#[test] +fn test_every_transaction_warms_the_registry_and_its_slot() { + let run = |tx: MegaTransaction| { + let mut evm = + MegaEvm::new(chain_context(chain_db().account_balance(CALLER, U256::from(FUNDS)))) + .with_inspector(GasInspector::new()); + let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); + assert!(!outcome.result.is_success(), "the Oracle refuses a write from a user"); + let sloads: Vec = evm + .inspector() + .records() + .iter() + // The transaction's frame is at journal depth 1, the registry's call below it at 2. + .filter(|record| record.opcode.get() == SLOAD && record.depth == 2) + .map(|record| record.gas_cost()) + .collect(); + assert_eq!(sloads.len(), 1, "the registry reads its one slot: {sloads:?}"); + (outcome, sloads[0]) + }; + let write = || { + legacy_tx( + CALLER, + TxKind::Call(ORACLE_CONTRACT_ADDRESS), + set_slot(ORACLE_SLOT, B256::with_last_byte(1)), + 0, + ) + }; + + let warm = mega_evm::satin_gas_params().warm_storage_read_cost(); + + let (shaped, legacy) = run(write()); + let (unshaped, typed_call) = run(typed(write(), 1)); + for (shape, outcome) in [("legacy", &shaped), ("EIP-2930", &unshaped)] { + let registry = &outcome.state[&SEQUENCER_REGISTRY_ADDRESS]; + assert!(!registry.is_touched(), "{shape}: the read writes nothing"); + assert!(registry.storage.contains_key(&CURRENT_SYSTEM_ADDRESS), "{shape}: the slot"); + } + assert_eq!(legacy, warm, "the legacy call's SLOAD is warm"); + assert_eq!(typed_call, warm, "and so is the EIP-2930 call's"); + assert_eq!(shaped.gas, unshaped.gas, "the two spend the same gas on every ledger"); + + let mut listed = typed(write(), 1); + listed.0.base.access_list = AccessList(vec![AccessListItem { + address: SEQUENCER_REGISTRY_ADDRESS, + storage_keys: vec![B256::from(CURRENT_SYSTEM_ADDRESS)], + }]); + let (_, listed) = run(listed); + assert_eq!(listed, warm, "an access list naming the slot makes it no warmer"); +} + +/// The registry's account and slot every transaction reads are an untouched entry of its state, +/// and a commit skips an account nothing touched: committing a transaction writes nothing of the +/// registry, whether the state holds a registry or not, so the state root moves as it would +/// without the read. #[test] -fn test_a_non_legacy_transaction_from_the_system_address_is_refused() { - let mut tx = system_tx(0, B256::with_last_byte(0xaf)); - tx.0.base.tx_type = 2; // EIP-1559 - let refused = rejection(chain_db(), tx); - assert!(refused.contains(NOT_A_SYSTEM_TRANSACTION), "{refused}"); +fn test_committing_a_transaction_writes_nothing_of_the_registry() { + for (holds, db) in [("a registry", chain_db()), ("no registry", MemoryDatabase::default())] { + let db = db + .account_balance(CALLER, U256::from(FUNDS)) + .account_code(OFF_WHITELIST, Bytes::from_static(&[STOP])); + let mut state = State::builder().with_database(db).with_bundle_update().build(); + let mut evm = MegaEvm::new(chain_context(&mut state)); + let tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); + let outcome = evm.execute_transaction(tx).expect("an ordinary transaction"); + assert!(outcome.result.is_success(), "{holds}: {:?}", outcome.result); + assert!(outcome.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), "{holds}: it was read"); + drop(evm); + state.commit(outcome.state.clone()); + + state.merge_transitions(BundleRetention::Reverts); + let bundle = state.take_bundle(); + assert!(bundle.state.contains_key(&CALLER), "{holds}: the commit wrote the sender"); + assert!( + !bundle.state.contains_key(&SEQUENCER_REGISTRY_ADDRESS), + "{holds}: and nothing of the registry" + ); + } } /// The whitelist holds for the system address alone: anyone else may call anything, and pays @@ -272,7 +414,7 @@ fn test_a_user_deposit_is_not_a_system_transaction() { let mut tx = legacy_tx(CALLER, TxKind::Call(OFF_WHITELIST), Bytes::new(), 0); tx.0.deposit.source_hash = B256::repeat_byte(0x11); - assert!(is_deposit_like_transaction(&tx, MEGA_SYSTEM_ADDRESS)); + assert_eq!(revm::context::Transaction::tx_type(&tx), DEPOSIT_TRANSACTION_TYPE); assert!(!is_mega_system_transaction_with(&tx, MEGA_SYSTEM_ADDRESS)); let outcome = run_outcome(db, tx); assert!(outcome.result.is_success(), "{:?}", outcome.result); @@ -370,29 +512,48 @@ fn test_a_system_address_with_code_is_refused() { assert!(rejected.contains("RejectCallerWithCode"), "{rejected}"); } -/// The checks a caller switches off for user transactions are switched off here too: one shape -/// of validation, not two. -#[test] -fn test_the_configuration_switches_hold_for_system_transactions() { - let run_with = |mutate: fn(&mut CfgEnv), db: MemoryDatabase, tx| { - let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); - cfg.chain_id = CHAIN_ID; - mutate(&mut cfg); - MegaEvm::new(context(db).with_cfg(cfg)).execute_transaction(tx) - }; +/// Runs `tx` on `db` under the chain's configuration with `mutate` applied. +fn run_with( + mutate: fn(&mut CfgEnv), + db: MemoryDatabase, + tx: MegaTransaction, +) -> Result> { + let mut cfg = CfgEnv::new_with_spec(mega_evm::MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + mutate(&mut cfg); + MegaEvm::new(context(db).with_cfg(cfg)).execute_transaction(tx) +} - // A foreign chain id goes through when the chain-id check is off. - let foreign = legacy_tx_with_chain_id( - MEGA_SYSTEM_ADDRESS, - TxKind::Call(ORACLE_CONTRACT_ADDRESS), - set_slot(ORACLE_SLOT, B256::with_last_byte(0xee)), - 0, - Some(31_337), - ); - let outcome = run_with(|cfg| cfg.tx_chain_id_check = false, chain_db(), foreign) - .expect("the chain-id check is off"); +/// The chain id is checked whatever the caller's configuration says: the spec fixes the check on. +/// A transaction carrying another chain's id is refused, a system transaction as a user's, and a +/// typed transaction must carry one; a user's legacy transaction may carry none (pre-EIP-155), a +/// system transaction may not. +#[test] +fn test_the_chain_id_is_checked_whatever_the_configuration_says() { + let off = |cfg: &mut CfgEnv| cfg.tx_chain_id_check = false; + let funded = || chain_db().account_balance(CALLER, U256::from(FUNDS)); + let oracle = TxKind::Call(ORACLE_CONTRACT_ADDRESS); + let write = || set_slot(ORACLE_SLOT, B256::with_last_byte(0xee)); + let refusal = |db, tx| format!("{:?}", run_with(off, db, tx).expect_err("refused")); + + let foreign_system = legacy_tx_with_chain_id(MEGA_SYSTEM_ADDRESS, oracle, write(), 0, Some(1)); + assert!(refusal(chain_db(), foreign_system).contains("InvalidChainId")); + let bare_system = legacy_tx_with_chain_id(MEGA_SYSTEM_ADDRESS, oracle, write(), 0, None); + assert!(refusal(chain_db(), bare_system).contains("MissingChainId")); + + let foreign_user = legacy_tx_with_chain_id(CALLER, oracle, get_slot(), 0, Some(1)); + assert!(refusal(funded(), foreign_user.clone()).contains("InvalidChainId")); + assert!(refusal(funded(), typed(foreign_user, 2)).contains("InvalidChainId")); + let bare_user = legacy_tx_with_chain_id(CALLER, oracle, get_slot(), 0, None); + assert!(refusal(funded(), typed(bare_user.clone(), 2)).contains("MissingChainId")); + let outcome = run_with(off, funded(), bare_user).expect("a pre-EIP-155 transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); +} +/// The nonce and code checks a caller switches off for user transactions are switched off here +/// too: one shape of validation, not two. +#[test] +fn test_the_configuration_switches_hold_for_system_transactions() { // A stale nonce goes through when the nonce check is off. let db = chain_db().account_nonce(MEGA_SYSTEM_ADDRESS, 7); let outcome = run_with(|cfg| cfg.disable_nonce_check = true, db, system_tx(0, B256::ZERO)) @@ -407,10 +568,11 @@ fn test_the_configuration_switches_hold_for_system_transactions() { assert!(outcome.result.is_success(), "{:?}", outcome.result); } -/// Validating a system transaction does not warm the system address: the transaction pays the -/// cold access its first touch of any account would. +/// Validating a system transaction reads the system address's account, the transaction's caller, +/// which every transaction starts warm: the system transaction pays for its own account what any +/// sender pays for its own. #[test] -fn test_validating_a_system_transaction_does_not_warm_the_system_address() { +fn test_validating_a_system_transaction_charges_its_caller_as_any_senders() { // `getSlot` reads one slot and writes nothing, so what the two transactions differ by is // the access to the caller's own account. let read = Bytes::from(IOracle::getSlotCall { slot: ORACLE_SLOT }.abi_encode()); @@ -452,7 +614,7 @@ fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { tx }); let one_account = reference.gas.state; - assert!(one_account > 0, "a fresh recipient costs state gas"); + assert_eq!(one_account, account_state_gas(), "a fresh recipient costs state gas"); // A system transaction whose sender does not exist yet creates it, for the same charge. let created = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x77))); @@ -472,19 +634,6 @@ fn test_a_deposit_creates_its_caller_and_pays_for_it_once() { ); } -/// A deposit-like transaction whose caller already exists pays no account-creation charge for -/// it. -#[test] -fn test_a_deposit_with_an_existing_caller_pays_nothing_extra() { - let existing = chain_db().account_balance(MEGA_SYSTEM_ADDRESS, U256::from(1)); - let fresh = chain_db(); - let (existing, fresh) = ( - run_outcome(existing, system_tx(0, B256::with_last_byte(0x88))).gas.state, - run_outcome(fresh, system_tx(0, B256::with_last_byte(0x88))).gas.state, - ); - assert!(fresh > existing, "{fresh} is not above {existing}"); -} - /// A deposit whose recipient is its own caller pays for that one account once: by the time the /// recipient is looked at, the caller's materialisation has created it. #[test] @@ -520,24 +669,84 @@ fn test_a_deposit_that_creates_two_accounts_pays_for_both() { assert_eq!(two, one * 2, "two accounts created, two charges"); } -/// A deposit that cannot pay for the account it creates for its caller is an out-of-gas halt, -/// as a transaction that runs out in its runtime phase is. -#[test] -fn test_a_deposit_that_cannot_pay_for_its_caller_halts() { - let sender = address!("0x00000000000000000000000000000000000f0006"); +/// A deposit from `sender`, an account that does not exist, to the Oracle, whose gas limit is one +/// short of its intrinsic gas and the account it creates for its caller, at the byte prices in +/// effect. It carries no value and no calldata, so its intrinsic gas, which is its floor too, is +/// EIP-2780's base of 12,000 and 3,000 for the recipient. +fn deposit_one_short_of_its_caller(sender: Address) -> MegaTransaction { + const INTRINSIC: u64 = 12_000 + 3_000; let mut tx = deposit_tx(sender, TxKind::Call(ORACLE_CONTRACT_ADDRESS), U256::ZERO, 0); - tx.0.base.gas_limit = 30_000; + tx.0.base.gas_limit = INTRINSIC + account_state_gas() - 1; + tx +} +/// A deposit that cannot pay for the account it creates for its caller runs out of gas before its +/// first frame, and a deposit that does is a failed deposit: the `FailedDeposit` halt, not an +/// out-of-gas, billed its whole gas limit. +/// +/// Rules: [S5], [S21.5], [S21.7], [S5.12]. Independence: constants — the intrinsic gas is +/// EIP-2780's, the caller account's state gas the schedule's entry at the price in effect. +#[test] +fn test_a_deposit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { + // An account that costs nothing is one any deposit can pay for. + if state_is_free() { + return; + } + let sender = address!("0x00000000000000000000000000000000000f0006"); + let tx = deposit_one_short_of_its_caller(sender); + let gas_limit = tx.0.base.gas_limit; let outcome = run_outcome(chain_db(), tx); assert!( - matches!(outcome.result, ExecutionResult::Halt { .. }), - "{:?} is not a halt", + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?} is not a failed deposit", + outcome.result, + ); + assert_eq!(outcome.gas.gas_used, gas_limit, "a failed deposit bills its whole gas limit"); +} + +/// The account a deposit creates for its caller is charged before its first frame, and a body over +/// the data-size limit does not waive the charge: a deposit that cannot pay for it is a failed +/// deposit, which reports the failure and not the data-size stop, and keeps its body counted. +/// +/// Rules: [S11], [S10.15], [S21.7]. Independence: constants — the body is `TX_BODY_SIZE`, the gas +/// limit as [`deposit_one_short_of_its_caller`] works it out. +#[test] +fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_is_a_failed_deposit() { + // An account that costs nothing is one any deposit can pay for. + if state_is_free() { + return; + } + let sender = address!("0x00000000000000000000000000000000000f0008"); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE - 1); + + let tx = deposit_one_short_of_its_caller(sender); + let gas_limit = tx.0.base.gas_limit; + let outcome = MegaEvm::new(chain_context(chain_db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx) + .expect("the deposit is included"); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?} is not a failed deposit", outcome.result, ); + assert_eq!(outcome.gas.gas_used, gas_limit, "a failed deposit bills its whole gas limit"); + assert_eq!(outcome.limit_exceeded, None, "the failure is not a data-size stop"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + "the body stays counted", + ); } -/// The registry the Oracle reads the current system address from is seeded as the chain seeds -/// it, so a write from the system address is the one the Oracle accepts. +/// The registry the Oracle reads the current system address from holds it as a chain's registry +/// does, so a write from the system address is the one the Oracle accepts. #[test] fn test_the_oracle_accepts_the_system_address_the_registry_names() { let current = ISequencerRegistry::currentSystemAddressCall {}.abi_encode(); @@ -626,25 +835,34 @@ fn test_a_deposit_that_creates_a_contract_pays_for_its_caller_too() { assert!(fresh.result.is_success(), "{:?}", fresh.result); assert!(existing.result.is_success(), "{:?}", existing.result); - assert!( - fresh.gas.state > existing.gas.state, + assert_eq!( + fresh.gas.state, + existing.gas.state + account_state_gas(), "the created caller costs state gas on top of the created contract", ); } -/// A transaction that already carries the system source hash is not executed as one: the -/// promotion is the engine's own, made once per execution, and a transaction that arrives -/// promoted has skipped the validation that precedes it. +/// A transaction that already carries the system source hash is a deposit by type, so it does +/// not have the system shape: from the live system address it is a failed deposit, as every +/// deposit from that address is. No promotion is made for +/// it, so none of the promotion's checks runs: its nonce is not the system address's. /// /// A block's transactions are decoded from their legacy encoding, which carries no source hash, /// so this is the shape a caller hands the engine directly, not one a block holds. #[test] -fn test_a_transaction_that_arrives_promoted_is_refused() { - let mut tx = system_tx(0, B256::with_last_byte(0xaf)); +fn test_a_transaction_that_arrives_promoted_is_a_failed_deposit() { + let mut tx = + legacy_tx(MEGA_SYSTEM_ADDRESS, TxKind::Call(ORACLE_CONTRACT_ADDRESS), get_slot(), 7); tx.0.deposit.source_hash = MEGA_SYSTEM_TRANSACTION_SOURCE_HASH; - let refused = rejection(chain_db(), tx); + let outcome = MegaEvm::new(chain_context(chain_db())) + .execute_transaction(tx) + .expect("a deposit is not refused"); assert!( - refused.contains(NOT_A_SYSTEM_TRANSACTION), - "the refusal names the rule, not the whitelist alone: {refused}", + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.result ); } diff --git a/crates/mega-evm/tests/tracers/gas.rs b/crates/mega-evm/tests/tracers/gas.rs new file mode 100644 index 000000000..8026e440c --- /dev/null +++ b/crates/mega-evm/tests/tracers/gas.rs @@ -0,0 +1,197 @@ +//! What the scenarios are charged, worked out from the Satin schedule and the byte prices in +//! effect rather than read back from the engine. +//! +//! Every figure goes through the schedule's entries and the engine's price functions, so it holds +//! at any byte price a measurement build runs. + +use mega_evm::{history_gas, satin_gas_params, tx_body_history_bytes, write_record_history_gas}; +use revm::{ + context_interface::cfg::{gas::LOG, GasId}, + primitives::{eip2780, eip8038}, +}; + +/// The schedule's entry `id`. +pub(crate) fn entry(id: GasId) -> u64 { + satin_gas_params().get(id) +} + +/// The history gas of `bytes` bytes. +pub(crate) fn history(bytes: u64) -> u64 { + history_gas(bytes).expect("a byte count has a price") +} + +/// The history gas of `records` write records. +pub(crate) fn records(records: u64) -> u64 { + write_record_history_gas(records).expect("a record has a price") +} + +/// The history gas of the body of a transaction carrying `calldata_len` bytes of calldata and no +/// access list or authorization. +pub(crate) fn body(calldata_len: usize) -> u64 { + history(tx_body_history_bytes(calldata_len as u64, 0, 0, 0)) +} + +/// The state gas of one fresh storage slot, in the minimum bucket. +pub(crate) fn slot_state() -> u64 { + entry(GasId::sstore_set_state_gas()) +} + +/// The regular gas of an `SSTORE` that fills a fresh, cold slot: its static cost, the cost of a +/// fresh slot before the load, and the cold load. +pub(crate) fn sstore_fresh_cold() -> u64 { + entry(GasId::sstore_static()) + + entry(GasId::sstore_set_without_load_cost()) + + entry(GasId::cold_storage_cost()) +} + +/// The bytes in one EVM word. +const WORD: u64 = 32; + +/// The ledgers a scenario's transaction is billed, worked out from the schedule, and the +/// EIP-7623 floor its receipt cannot fall below. +/// +/// No scenario earns a refund. The floor raises the receipt and nothing else: where the three +/// ledgers sum to less, the receipt reports the floor, while each ledger still reports what was +/// spent on it. At the spec's prices the floor never binds, history gas outpricing it on the same +/// bytes; at a byte price low enough it does. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Ledgers { + /// Regular gas: the intrinsic regular gas and what the frames ran. + pub(crate) regular: u64, + /// State gas the transaction kept. + pub(crate) state: u64, + /// History gas the transaction kept, its body included. + pub(crate) history: u64, + /// The EIP-7623 floor. + pub(crate) floor: u64, +} + +impl Ledgers { + /// The raw spend: the three ledgers' sum. + pub(crate) const fn spent(self) -> u64 { + self.regular + self.state + self.history + } + + /// What the receipt reports: the raw spend, at least the floor. + pub(crate) const fn receipt(self) -> u64 { + if self.spent() > self.floor { + self.spent() + } else { + self.floor + } + } +} + +/// The gas `data` costs as calldata: one token per zero byte and the schedule's multiplier per +/// non-zero byte, at the schedule's cost per token. +pub(crate) fn calldata(data: &[u8]) -> u64 { + let multiplier = entry(GasId::tx_token_non_zero_byte_multiplier()); + let tokens: u64 = data.iter().map(|byte| if *byte == 0 { 1 } else { multiplier }).sum(); + tokens * entry(GasId::tx_token_cost()) +} + +/// The floor tokens of `data` (EIP-7623, as EIP-7976 amends it): the schedule's zero-byte +/// multiplier per zero byte and its non-zero multiplier per non-zero byte. +fn floor_tokens(data: &[u8]) -> u64 { + let zero = entry(GasId::tx_floor_token_zero_byte_multiplier()); + let non_zero = entry(GasId::tx_token_non_zero_byte_multiplier()); + data.iter().map(|byte| if *byte == 0 { zero } else { non_zero }).sum() +} + +/// The EIP-7623 floor of a call to another account carrying `data`: under EIP-2780 the decomposed +/// base the intrinsic gas starts from (the base, the recipient's access and the value's charge), +/// plus the calldata's floor tokens at the floor's cost per token. +pub(crate) fn call_floor(data: &[u8], carries_value: bool) -> u64 { + let value = if carries_value { eip2780::TX_VALUE_COST } else { 0 }; + eip2780::TX_BASE_COST + + eip8038::COLD_ACCOUNT_ACCESS + + value + + floor_tokens(data) * entry(GasId::tx_floor_cost_per_token()) +} + +/// The EIP-7623 floor of a creation running `init_code`: the base and the creation's access, plus +/// the init code's floor tokens at the floor's cost per token. EIP-3860's cost per word is not in +/// it. +pub(crate) fn create_floor(init_code: &[u8]) -> u64 { + eip2780::TX_BASE_COST + + entry(GasId::tx_create_access_cost()) + + floor_tokens(init_code) * entry(GasId::tx_floor_cost_per_token()) +} + +/// The EIP-2780 intrinsic regular gas of a call to another account carrying `data`: the base, +/// the recipient's access, the value's charge when it carries value, and the calldata. +pub(crate) fn call_intrinsic(data: &[u8], carries_value: bool) -> u64 { + let value = if carries_value { eip2780::TX_VALUE_COST } else { 0 }; + eip2780::TX_BASE_COST + eip8038::COLD_ACCOUNT_ACCESS + value + calldata(data) +} + +/// The EIP-2780 intrinsic regular gas of a creation running `init_code`: the base, the creation's +/// access, EIP-3860's cost per word of init code, and the calldata. +pub(crate) fn create_intrinsic(init_code: &[u8]) -> u64 { + eip2780::TX_BASE_COST + + entry(GasId::tx_create_access_cost()) + + satin_gas_params().initcode_cost(init_code.len()) + + calldata(init_code) +} + +/// The words `bytes` bytes occupy. +pub(crate) const fn words(bytes: u64) -> u64 { + bytes.div_ceil(WORD) +} + +/// What expanding memory from nothing to `words` words costs. +pub(crate) fn memory(words: u64) -> u64 { + entry(GasId::memory_linear_cost()) * words + + words * words / entry(GasId::memory_quadratic_reduction()) +} + +/// The regular gas of a `LOG` with `topics` topics and `len` bytes of data, its memory aside. +pub(crate) fn log(topics: u64, len: u64) -> u64 { + LOG + entry(GasId::logtopic()) * topics + entry(GasId::logdata()) * len +} + +/// The access of an account the transaction has not touched. +pub(crate) fn cold_account() -> u64 { + entry(GasId::warm_storage_read_cost()) + entry(GasId::cold_account_additional_cost()) +} + +/// The access of an account already warm, such as a precompile. +pub(crate) fn warm_account() -> u64 { + entry(GasId::warm_storage_read_cost()) +} + +/// The regular gas a creation's deposit of `len` bytes costs: the regular per-byte cost and the +/// hashing of the code. +pub(crate) fn deposit_regular(len: usize) -> u64 { + entry(GasId::code_deposit_cost()) * len as u64 + + entry(GasId::keccak256_per_word()) * words(len as u64) +} + +/// Everything a creation's deposit of `len` bytes costs, which `return_create` charges after the +/// creation's last step: its regular part, the code's state gas and its history gas. +pub(crate) fn deposit(len: usize) -> u64 { + deposit_regular(len) + satin_gas_params().code_deposit_state_gas(len) + history(len as u64) +} + +/// The state gas of a created account and `len` bytes of code deposited in it. +pub(crate) fn created_state(len: usize) -> u64 { + entry(GasId::create_state_gas()) + satin_gas_params().code_deposit_state_gas(len) +} + +/// The state gas of one new account, in the minimum bucket. +pub(crate) fn account_state() -> u64 { + entry(GasId::new_account_state_gas()) +} + +/// The compute a frame that loops on `cycle` reaches before a charge would take it past `limit`, +/// starting from `compute`: gas detention stops it on the first charge its spendable gas cannot +/// pay, without making it. +pub(crate) fn compute_at_crossing(mut compute: u64, limit: u64, cycle: &[u64]) -> u64 { + for charge in cycle.iter().cycle() { + if compute + charge > limit { + return compute; + } + compute += charge; + } + unreachable!("the cycle never ends") +} diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs new file mode 100644 index 000000000..528a056e2 --- /dev/null +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -0,0 +1,793 @@ +//! Run `MegaEvm` under `revm-inspectors` tracers and compare their output with insta snapshots. +//! +//! The views are sorted JSON snapshots with their gas figures redacted, one file per scenario and +//! view, under `tests/tracers/snapshots/`. A mismatch fails the test. Outside CI, +//! insta also writes the new value beside the old one as a `.snap.new` file. +//! +//! Review a change with `cargo insta review`, which shows each snapshot's diff and accepts or +//! rejects it on its own. Without `cargo-insta`, diff each `.snap.new` the failing run left against +//! its `.snap` and accept it on its own, by moving it over the `.snap` without its +//! `assertion_line:` header line, which insta's own accept leaves out. The comparisons run only at +//! the spec's byte prices. + +use std::{ + cell::RefCell, + collections::BTreeSet, + io::{self, Write}, + rc::Rc, +}; + +use alloy_primitives::{Address, Bytes, Log, B256}; +use alloy_rpc_types_trace::geth::{ + AccountState, CallConfig, CallFrame, CallLogFrame, DefaultFrame, GethDebugTracingOptions, + GethDefaultTracingOptions, GethTrace, PreStateConfig, PreStateFrame, PreStateMode, StructLog, +}; +use alloy_sol_types::SolError; +use mega_evm::{ + alloy_evm::Evm as _, + op_revm::constants::L1_BLOCK_CONTRACT, + system::keyless::KEYLESS_DEPLOY_ADDRESS, + test_utils::{ + op_transaction, zero_fee_l1_block_info, MemoryDatabase, RecordingDatabase, WitnessRecord, + }, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, + MegaTransaction, MegaTransactionOutcome, L1_BLOCK_INFO_SLOTS, +}; +use revm::{ + context::{result::ExecutionResult, BlockEnv, TxEnv}, + inspector::inspectors::TracerEip3155, + primitives::{KECCAK_EMPTY, U256}, + Database, +}; +use revm_inspectors::tracing::{ + types::{CallTraceNode, CallTraceStep, TraceMemberOrder}, + DebugInspector, TracingInspector, TracingInspectorConfig, +}; + +use crate::gas::Ledgers; + +/// A block with room for any transaction these tests run. +pub(crate) fn block() -> BlockEnv { + BlockEnv { + number: U256::from(1), + timestamp: U256::from(1_700_000_000), + gas_limit: 10_000_000_000, + ..Default::default() + } +} + +/// A Satin context over `db` with zero L1 fees. +pub(crate) fn context(db: DB) -> MegaContext { + MegaContext::new(db, MegaSpecId::SATIN).with_block(block()).with_chain(zero_fee_l1_block_info()) +} + +/// A call from `caller` to `to` carrying `data` and `value`. +pub(crate) fn call_tx( + caller: Address, + to: Address, + data: Bytes, + value: U256, + gas_limit: u64, +) -> MegaTransaction { + mega_evm::alloy_op_evm::OpTx(op_transaction(TxEnv { + caller, + kind: revm::primitives::TxKind::Call(to), + data, + value, + gas_limit, + ..Default::default() + })) +} + +/// A contract creation from `caller` running `init_code`. +pub(crate) fn create_tx(caller: Address, init_code: Bytes, gas_limit: u64) -> MegaTransaction { + mega_evm::alloy_op_evm::OpTx(op_transaction(TxEnv { + caller, + kind: revm::primitives::TxKind::Create, + data: init_code, + gas_limit, + ..Default::default() + })) +} + +/// A writer the EIP-3155 tracer writes into and the test reads back. +#[derive(Clone, Debug, Default)] +struct SharedBuf(Rc>>); + +impl Write for SharedBuf { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.borrow_mut().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// One Satin-engine execution under a tracer that records steps, logs and state diffs. +#[derive(Debug)] +pub(crate) struct Traced { + /// What the engine reported, including the three gas ledgers. + pub outcome: MegaTransactionOutcome, + /// The inspector after the transaction finished. + pub inspector: TracingInspector, + /// The pre-state database the prestate tracer reads. + pub pre_db: MemoryDatabase, + /// Every account, slot and code the first run read from the pre-state database. + pub reads: WitnessRecord, + /// The transaction, kept to run it again under another tracer. + tx: MegaTransaction, + /// The runtime limits it ran under. + limits: EvmTxRuntimeLimits, +} + +impl Traced { + /// Runs `tx` on a fresh Satin EVM over `db`, recording every read the database serves. + pub(crate) fn run(db: MemoryDatabase, tx: MegaTransaction, limits: EvmTxRuntimeLimits) -> Self { + let pre_db = db.clone(); + let record = Rc::new(RefCell::new(WitnessRecord::default())); + let recording = RecordingDatabase::new(db, record.clone()); + let inspector = TracingInspector::new(TracingInspectorConfig::all()); + let mut evm = MegaEvm::new(context(recording).with_tx_runtime_limits(limits)) + .with_inspector(inspector); + let outcome = evm.execute_transaction(tx.clone()).expect("the transaction is valid"); + let inspector = evm.inspector().clone(); + drop(evm); + let reads = record.borrow().clone(); + Self { outcome, inspector, pre_db, reads, tx, limits } + } + + /// The EIP-3155 trace: one JSON line per step, then the summary line. + /// + /// The transaction runs again, on a fresh EVM over the same pre-state, under the revm fork's + /// `TracerEip3155`, which is the tracer the state-test runner runs Satin under. + pub(crate) fn eip3155(&self) -> String { + let buf = SharedBuf::default(); + let mut evm = + MegaEvm::new(context(self.pre_db.clone()).with_tx_runtime_limits(self.limits)) + .with_inspector(TracerEip3155::new(Box::new(buf.clone()))); + let outcome = evm.execute_transaction(self.tx.clone()).expect("the transaction is valid"); + assert_eq!(outcome.result, self.outcome.result, "the EIP-3155 run executed differently"); + let bytes = buf.0.borrow().clone(); + String::from_utf8(bytes).expect("EIP-3155 output is UTF-8") + } + + /// What a node's `debug_traceTransaction` returns for this transaction under `opts`. + /// + /// The transaction runs again, on a fresh EVM over the same pre-state, under revm-inspectors' + /// `DebugInspector` built from `opts`, and the trace is built by `DebugInspector::get_result`, + /// which is what reth's debug API calls. It sets the root frame's gas limit and caller to the + /// transaction's before it builds a view, and hands the call and opcode tracers the receipt's + /// gas used. + fn node_trace(&self, opts: GethDebugTracingOptions) -> GethTrace { + let inspector = DebugInspector::new(opts).expect("a built-in tracer"); + let mut evm = + MegaEvm::new(context(self.pre_db.clone()).with_tx_runtime_limits(self.limits)) + .with_inspector(inspector); + let outcome = evm.execute_transaction(self.tx.clone()).expect("the transaction is valid"); + assert_eq!(outcome.result, self.outcome.result, "the traced run executed differently"); + let mut pre_db = self.pre_db.clone(); + evm.inspector_mut() + .get_result(None, &self.tx, &block(), &outcome.result_and_state, &mut *pre_db) + .expect("the trace builds") + } + + /// Geth call tracer output. + pub(crate) fn call_frame(&self, with_log: bool) -> CallFrame { + let config = CallConfig { only_top_call: Some(false), with_log: Some(with_log) }; + self.node_trace(GethDebugTracingOptions::call_tracer(config)) + .try_into_call_frame() + .expect("a call frame") + } + + /// Geth opcode / struct-log tracer, with the options a node gets when `debug_traceTransaction` + /// names none: the stack and the storage an `SLOAD` or `SSTORE` touched are kept, memory and + /// return data are not. + pub(crate) fn struct_logs(&self) -> DefaultFrame { + let config = GethDefaultTracingOptions::default(); + self.node_trace(GethDebugTracingOptions { config, ..Default::default() }) + .try_into_default_frame() + .expect("a struct-log frame") + } + + /// Geth prestate tracer. + pub(crate) fn prestate(&self, diff_mode: bool) -> PreStateFrame { + let config = PreStateConfig { + diff_mode: Some(diff_mode), + disable_code: Some(false), + disable_storage: Some(false), + }; + self.node_trace(GethDebugTracingOptions::prestate_tracer(config)) + .try_into_pre_state_frame() + .expect("a prestate frame") + } + + /// The transaction's gas limit. + pub(crate) fn gas_limit(&self) -> u64 { + self.tx.0.base.gas_limit + } +} + +/// The call tracer's `logs` are exactly `expected`, in order. +pub(crate) fn assert_logs(logs: &[CallLogFrame], expected: &[Log]) { + let got: Vec<_> = logs + .iter() + .map(|log| { + ( + log.address, + log.topics.clone().unwrap_or_default(), + log.data.clone().unwrap_or_default(), + ) + }) + .collect(); + let expected: Vec<_> = expected + .iter() + .map(|log| (Some(log.address), log.topics().to_vec(), log.data.data.clone())) + .collect(); + assert_eq!(got, expected, "the call tracer's logs"); +} + +/// Known shape: the call tracer numbers a log among every log the transaction emitted, those a +/// failed frame discarded included. +/// +/// revm-inspectors gives a log the count of logs it has recorded so far, in every frame, as its +/// `index`, and never takes back the logs of a frame that fails; the call builder then drops a +/// failed frame's logs and keeps the survivors' numbers. So the `index` of a log the receipt +/// keeps is its index in the receipt plus the logs discarded before it — under Satin among them +/// the EIP-7708 transfer log of a value call whose callee fails, and a log a limit refused after +/// the tracer saw it. `discarded_before` gives that count for each of the root frame's logs. +/// +/// A tracer that numbers the kept logs only makes this fail: require the receipt's index then. +pub(crate) fn assert_log_index_counts_discarded(traced: &Traced, discarded_before: &[u64]) { + let root = traced.call_frame(true); + assert_eq!(root.logs.len(), discarded_before.len(), "the root frame's logs"); + let receipt = traced.outcome.result.logs(); + for (log, discarded) in root.logs.iter().zip(discarded_before) { + let kept = log.clone().into_log(); + let receipt_index = + receipt.iter().position(|logged| *logged == kept).expect("the receipt keeps the log"); + assert_eq!( + log.index, + Some(receipt_index as u64 + discarded), + "known shape: the call tracer's log index ({:?}) is the receipt's ({receipt_index}) \ + plus the {discarded} log(s) a failed frame discarded before it; a tracer that numbers \ + kept logs only makes them equal: require the receipt's index here and review the \ + snapshots with `cargo insta review`", + log.index, + ); + } +} + +/// The struct-log step of the first `op` at `depth` in the node's opcode trace. +pub(crate) fn step(traced: &Traced, op: &str, depth: u64) -> StructLog { + traced + .struct_logs() + .struct_logs + .into_iter() + .find(|log| log.op == op && log.depth == depth) + .unwrap_or_else(|| panic!("no {op} step at depth {depth}")) +} + +/// The op lines of the EIP-3155 trace, without the summary. +pub(crate) fn eip3155_steps(traced: &Traced) -> Vec { + traced + .eip3155() + .lines() + .map(|line| serde_json::from_str::(line).expect("a JSON line")) + .filter(|line| line.get("opName").is_some()) + .collect() +} + +/// The scenarios whose opcode-level view, the node's struct logs, is pinned as well. +/// +/// Both show what only an opcode trace shows of gas detention: the step a crossing ends on reads as +/// an out-of-gas, and a parent's steps resume after the child's stop at depth 1. +const OPCODE_VIEWS: [&str; 2] = + ["timestamp_detention", "detention_stop_crosses_again_in_the_parent"]; + +/// The keys whose values are gas figures, in the call frames and the struct logs. +const GAS_KEYS: [&str; 4] = ["gas", "gasUsed", "gasCost", "refund"]; + +/// What stands in a snapshot for a gas figure. +const GAS_REDACTED: &str = "[gas]"; + +/// The kind of a `MegaLimitExceeded` stop whose limit is a gas figure: gas detention's. +const COMPUTE_STOP_KIND: u8 = 2; + +/// `value` with every gas figure replaced by a placeholder, so a snapshot holds the trace's +/// structure and no figure the gas schedule or the byte prices set. +/// +/// Redacted: the values under [`GAS_KEYS`], the value a `GAS` step pushes, the compute limit a +/// detention stop reports in its revert data (it is the compute at the read plus the cap), and the +/// leading `gasUsed` word of a successful `keylessDeploy` answer. A data-size stop's limit is a +/// byte count and stays. The figures are asserted against the schedule by the scenario, not here. +fn redact_gas(value: &mut serde_json::Value) { + use serde_json::Value; + match value { + Value::Object(map) => { + let keyless_answer = map.get("to").and_then(Value::as_str) == + Some(format!("{KEYLESS_DEPLOY_ADDRESS:#x}").as_str()) && + !map.contains_key("error"); + for (key, field) in map.iter_mut() { + if GAS_KEYS.contains(&key.as_str()) { + *field = Value::String(GAS_REDACTED.into()); + } else if matches!(key.as_str(), "output" | "returnValue") { + redact_output(field, keyless_answer); + } else { + redact_gas(field); + } + } + if let Some(logs) = map.get_mut("structLogs").and_then(|logs| logs.as_array_mut()) { + redact_gas_pushes(logs); + } + } + Value::Array(items) => items.iter_mut().for_each(redact_gas), + _ => {} + } +} + +/// The value a `GAS` step leaves on the stack, in the struct-log step that follows it at the same +/// depth: a gas figure, which a `CALL`'s gas argument carries into its own step. +fn redact_gas_pushes(logs: &mut [serde_json::Value]) { + for at in 1..logs.len() { + let after_gas = logs[at - 1]["op"] == "GAS" && logs[at - 1]["depth"] == logs[at]["depth"]; + let top = logs[at].get_mut("stack").and_then(|stack| stack.as_array_mut()); + if let (true, Some(top)) = (after_gas, top.and_then(|stack| stack.last_mut())) { + *top = serde_json::Value::String(GAS_REDACTED.into()); + } + } +} + +/// [`redact_gas`] for a hex `output`: a detention stop's limit and a keyless answer's `gasUsed`. +fn redact_output(output: &mut serde_json::Value, keyless_answer: bool) { + let Some(bytes) = output.as_str().and_then(|text| text.parse::().ok()) else { + return; + }; + if let Ok(stop) = MegaLimitExceeded::abi_decode(&bytes) { + if stop.kind == COMPUTE_STOP_KIND { + *output = + serde_json::Value::String(format!("MegaLimitExceeded({COMPUTE_STOP_KIND}, [gas])")); + } + } else if keyless_answer && bytes.len() >= 32 { + *output = serde_json::Value::String(format!( + "{GAS_REDACTED}{}", + Bytes::copy_from_slice(&bytes[32..]) + )); + } +} + +/// `view` as JSON with its gas figures redacted. +fn redacted(view: &impl serde::Serialize) -> serde_json::Value { + let mut value = serde_json::to_value(view).expect("a tracer view is JSON"); + redact_gas(&mut value); + value +} + +/// Pins the tracer views of `traced` under `scenario`'s name, as sorted JSON with the gas figures +/// redacted: the call tracer with logs and the prestate diff for every scenario, and the struct +/// logs for the [`OPCODE_VIEWS`] scenarios. +/// +/// The figures are asserted against the schedule (`assert_ledgers` and the relations beside it), +/// so a gas-only change moves no snapshot. The comparisons run only at the spec's byte prices. +pub(crate) fn pin_tracer_views(scenario: &str, traced: &Traced) { + crate::assert_sorted_json_snapshot!( + format!("{scenario}__call_with_log"), + &redacted(&traced.call_frame(true)) + ); + crate::assert_sorted_json_snapshot!( + format!("{scenario}__prestate_diff"), + &redacted(&traced.prestate(true)) + ); + if OPCODE_VIEWS.contains(&scenario) { + crate::assert_sorted_json_snapshot!( + format!("{scenario}__struct_logs"), + &redacted(&traced.struct_logs()) + ); + } +} + +/// The transaction is billed `expected`, ledger by ledger, under the expected floor, and its +/// receipt is their sum, at least the floor. +pub(crate) fn assert_ledgers(traced: &Traced, expected: Ledgers) { + let gas = &traced.outcome.gas; + assert_eq!( + (gas.regular, gas.state, gas.history), + (expected.regular, expected.state, expected.history), + "the ledgers (regular, state, history)" + ); + assert_eq!(gas.floor, expected.floor, "the EIP-7623 floor"); + assert_eq!(gas.gas_used, expected.receipt(), "the receipt's gas used"); +} + +/// The tracer's own figure for the transaction's frame, against the ledgers. +/// +/// revm-inspectors records the regular gas the engine handed the transaction's frame as the root +/// node's `gas_limit` and, when the frame ends, what the frame spent of it as `gas_used` +/// (`Gas::total_gas_spent`: the limit less what is left, so state and history gas that spilled +/// onto regular gas is in it, and what the reservoir paid is not). What the frame did not spend +/// and the reservoir left are the gas the transaction did not use; everything else its gas limit +/// bought is its raw spend, the three ledgers' sum: +/// +/// `gas_limit = (regular + state + history) + (root.gas_limit − root.gas_used) + given_back + +/// reservoir left` +/// +/// The refund and the EIP-7623 floor change only how much of that the receipt bills, so neither +/// is in it. +/// +/// `given_back` is the state and history gas the frame spilled onto its regular gas and got back +/// because it failed. revm gives a failed frame that gas back when the frame's result is merged +/// (`handle_reservoir_remaining_gas`, for the transaction's own frame in `last_frame_result`), +/// which is after the inspector's `call_end` read it: the tracer counts it as spent, the receipt +/// does not bill it. +/// +/// The first run's inspector is read here: the node path overwrites the root's gas limit with the +/// transaction's. +pub(crate) fn assert_root_frame_settles(traced: &Traced, given_back: u64) { + let root = &traced.inspector.traces().nodes()[0].trace; + let unspent = root.gas_limit - root.gas_used; + let gas = &traced.outcome.gas; + let spent = gas.regular + gas.state + gas.history; + assert_eq!( + traced.gas_limit(), + spent + unspent + given_back + gas.reservoir_remaining, + "the raw spend ({spent}), the root frame's unspent gas ({unspent}), what its failure gave \ + back ({given_back}) and the reservoir left do not make up the gas limit" + ); +} + +/// The steps the first run's inspector recorded, in execution order, each with the index of the +/// frame that ran it. +fn steps_in_order(traced: &Traced) -> Vec<(usize, &CallTraceStep)> { + fn walk<'a>(nodes: &'a [CallTraceNode], idx: usize, out: &mut Vec<(usize, &'a CallTraceStep)>) { + let node = &nodes[idx]; + for member in &node.ordering { + match member { + TraceMemberOrder::Step(step) => out.push((idx, &node.trace.steps[*step])), + TraceMemberOrder::Call(child) => walk(nodes, node.children[*child], out), + TraceMemberOrder::Log(_) => {} + } + } + } + let mut out = Vec::new(); + walk(traced.inspector.traces().nodes(), 0, &mut out); + out +} + +/// The `gasUsed` of the EIP-3155 trace's summary line. +pub(crate) fn eip3155_summary_gas_used(traced: &Traced) -> u64 { + let eip3155 = traced.eip3155(); + let summary = eip3155.lines().last().expect("the summary line"); + let summary: serde_json::Value = serde_json::from_str(summary).expect("a JSON line"); + quantity(&summary["gasUsed"]) +} + +/// A `0x`-prefixed hex quantity of the EIP-3155 trace. +fn quantity(value: &serde_json::Value) -> u64 { + let text = value.as_str().expect("a hex quantity"); + u64::from_str_radix(text.trim_start_matches("0x"), 16).expect("a hex quantity") +} + +/// The EIP-3155 trace against the other tracer's steps and the receipt. +/// +/// - Its op lines are the steps the first run's inspector recorded, in execution order, the +/// creation of a keyless deployment included: the same program counter, opcode, gas before the +/// step and cost. +/// - Its summary passes exactly when the transaction succeeded. +/// - Its summary's `fork` is `Osaka`: the fork's tracer prints the L1 name of the spec the +/// configuration runs, which for Satin is Karst's base, not the schedule Satin prices with. +/// - Its summary's `gasUsed` is the transaction's gas limit less the regular gas the last executed +/// step left: the fork's `GasInspector` tracks nothing else, and starts from nothing when no +/// frame ran a step. Where that step is the transaction's own frame's, the frame is a call and it +/// was not stopped by gas detention, whose crossing the tracer sees zeroed, it is the raw spend, +/// the three ledgers' sum, plus the reservoir left: the reservoir is not regular gas, so the +/// summary counts what is left of it as used, and the refund and the EIP-7623 floor, which change +/// only what the receipt bills, are not in it. A creation is charged its deposit after its last +/// step, which the creation and keyless scenarios assert by themselves. Where a child frame ran +/// the last step, as in a stop that spans frames, the figure is that child's leftover read +/// against the transaction's gas limit, and bears no relation to the receipt. +pub(crate) fn assert_eip3155_agrees(traced: &Traced) { + let lines: Vec = traced + .eip3155() + .lines() + .map(|line| serde_json::from_str(line).expect("a JSON line")) + .collect(); + let (summary, ops) = lines.split_last().expect("the summary line"); + assert!(summary.get("stateRoot").is_some(), "the last line is the summary: {summary}"); + assert_eq!( + summary["fork"], "Osaka", + "the fork's tracer prints the L1 name of the Karst base spec, not the schedule's" + ); + let steps = steps_in_order(traced); + assert_eq!(ops.len(), steps.len(), "the EIP-3155 op lines are the inspector's steps"); + for (line, (_, step)) in ops.iter().zip(&steps) { + let recorded = + (step.pc as u64, u64::from(step.op.get()), step.gas_remaining, step.gas_cost); + let printed = ( + line["pc"].as_u64().expect("pc"), + line["op"].as_u64().expect("op"), + quantity(&line["gas"]), + quantity(&line["gasCost"]), + ); + assert_eq!(printed, recorded, "EIP-3155 step (pc, op, gas, gasCost)"); + } + assert_eq!(summary["pass"], traced.outcome.result.is_success(), "the summary's pass"); + let left = steps.last().map_or(0, |(_, step)| step.gas_remaining - step.gas_cost); + let gas_used = quantity(&summary["gasUsed"]); + assert_eq!(gas_used, traced.gas_limit() - left, "the summary's gasUsed"); + let detained = matches!( + traced.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, .. }) + ); + let is_call = traced.tx.0.base.kind.is_call(); + if steps.last().is_some_and(|(frame, _)| *frame == 0) && is_call && !detained { + let gas = &traced.outcome.gas; + assert_eq!( + gas_used, + gas.regular + gas.state + gas.history + gas.reservoir_remaining, + "the summary's gasUsed is the raw spend plus the reservoir left" + ); + } +} + +/// The root frame's `gas` in both call tracer views is the transaction's gas limit, as a node +/// reports it. +/// +/// What the engine hands the first frame is less: the intrinsic gas, the body's history and what +/// is charged before the first frame are taken out of it, and the reservoir above the execution +/// cap is not regular gas at all. `DebugInspector::get_result` overwrites the root's gas limit +/// with the transaction's before it builds the call frames, so neither shows here. +pub(crate) fn assert_root_gas_is_the_gas_limit(traced: &Traced) { + for with_log in [false, true] { + let frame = traced.call_frame(with_log); + assert_eq!( + frame.gas, + U256::from(traced.gas_limit()), + "root gas (withLog = {with_log}) is not the transaction's gas limit" + ); + } +} + +/// The root frame's `gasUsed` in both call tracer views is the receipt's gas used, as a node +/// reports it: `DebugInspector::get_result` hands the call tracer the receipt's figure. +pub(crate) fn assert_root_gas_used_is_the_receipt(traced: &Traced) { + for with_log in [false, true] { + assert_eq!( + traced.call_frame(with_log).gas_used, + U256::from(traced.outcome.gas.gas_used), + "root gasUsed (withLog = {with_log}) is not the receipt's gas used" + ); + } +} + +/// The prestate names every account the engine read from the database, with what it read. +/// +/// The first run read the pre-state through a `RecordingDatabase`, which records every account, +/// slot and code it serves the engine. The prestate tracer instead walks the state the +/// transaction returned and reads the pre-state database itself. An account the engine read that +/// the returned state does not carry — a read outside the journal, or a frame's accounts dropped +/// on a stop — would be recorded here and missing from the prestate, as it would from a witness +/// built from the same state. +/// +/// One read is outside every transaction's state by design, and is the only one excused: op-revm +/// reads the L1 block contract's account and the slots of `L1_BLOCK_INFO_SLOTS` on the database +/// itself, not through the journal, to price a transaction's L1 fee. Block execution hands +/// exactly those keys to the witness as a pre-block read (`read_l1_block_info`). The excuse is +/// those keys, read or not, and nothing else. +/// +/// An account the engine read without its code — the `SequencerRegistry`'s, which every +/// transaction's validation reads by its code hash — is named with the code the pre-state holds, +/// which the prestate tracer reads itself, as a witness carries it. +pub(crate) fn assert_prestate_covers_reads(traced: &Traced) { + let PreStateFrame::Default(PreStateMode(prestate)) = traced.prestate(false) else { + panic!("the default prestate mode"); + }; + let reads = &traced.reads; + let traced_accounts: BTreeSet
= prestate.keys().copied().collect(); + let missing: Vec<_> = reads + .accounts + .keys() + .copied() + .filter(|address| *address != L1_BLOCK_CONTRACT && !traced_accounts.contains(address)) + .collect(); + assert!(missing.is_empty(), "the prestate misses accounts the engine read: {missing:?}"); + for (address, served) in reads.accounts.iter().filter(|(a, _)| **a != L1_BLOCK_CONTRACT) { + let served = served.clone().unwrap_or_default(); + let code = (served.code_hash != KECCAK_EMPTY).then(|| { + reads + .codes + .get(&served.code_hash) + .cloned() + .unwrap_or_else(|| { + let held = traced.pre_db.clone().basic(*address).expect("the pre-state"); + held.and_then(|info| info.code).expect("the pre-state holds the code") + }) + .original_bytes() + }); + let expected = AccountState::from_account_info(served.nonce, served.balance, code); + let traced = &prestate[address]; + assert_eq!(traced.balance, expected.balance, "prestate balance of {address}"); + assert_eq!(traced.nonce, expected.nonce, "prestate nonce of {address}"); + assert_eq!(traced.code, expected.code, "prestate code of {address}"); + } + for ((address, slot), value) in &reads.storage { + if *address == L1_BLOCK_CONTRACT { + assert!(L1_BLOCK_INFO_SLOTS.contains(slot), "an L1 block slot outside the pricing's"); + continue; + } + let traced = + prestate.get(address).and_then(|account| account.storage.get(&B256::from(*slot))); + assert_eq!(traced, Some(&B256::from(*value)), "prestate slot {slot} of {address}"); + } +} + +/// The kind and limit of a `MegaLimitExceeded` revert. +pub(crate) fn decode_stop(output: &[u8]) -> (LimitKind, u64) { + let stop = MegaLimitExceeded::abi_decode(output) + .unwrap_or_else(|_| panic!("not MegaLimitExceeded: {}", Bytes::copy_from_slice(output))); + (LimitKind::from_u8(stop.kind).expect("a limit kind"), stop.limit) +} + +/// The transaction was stopped by the transaction-level limit `kind` at `limit`, and every one of +/// its `frames` call frames returns that stop, as the node's call tracer shows them: the one that +/// crossed it first, and every caller, which resumed on what the limit left it and crossed it +/// again. +pub(crate) fn assert_every_frame_stops( + traced: &Traced, + kind: LimitKind, + limit: u64, + frames: usize, +) { + let Some(LimitCheck::ExceedsLimit { kind: stopped, limit: stopped_at, frame_local, .. }) = + traced.outcome.limit_exceeded + else { + panic!("the transaction is not stopped: {:?}", traced.outcome.result); + }; + assert_eq!((stopped, stopped_at), (kind, limit), "the limit that stopped the transaction"); + assert!(!frame_local, "a transaction-level limit"); + let ExecutionResult::Revert { output, .. } = &traced.outcome.result else { + panic!("a stop settles as a revert: {:?}", traced.outcome.result); + }; + assert_eq!(decode_stop(output), (kind, limit), "the transaction's revert data"); + fn walk(frame: &CallFrame, expected: (LimitKind, u64), seen: &mut usize) { + *seen += 1; + let output = frame.output.as_ref().unwrap_or_else(|| panic!("no output: {frame:?}")); + assert_eq!( + frame.error.as_deref(), + Some("execution reverted"), + "frame {}", + frame.to.unwrap_or_default() + ); + assert_eq!(decode_stop(output), expected, "frame {}", frame.to.unwrap_or_default()); + for child in &frame.calls { + walk(child, expected, seen); + } + } + let mut seen = 0; + walk(&traced.call_frame(true), (kind, limit), &mut seen); + assert_eq!(seen, frames, "the frames the stop spans"); +} + +/// Gas detention stopped the transaction at `compute`: the compute the stop reports as used, which +/// the regular ledger bills. +pub(crate) fn assert_compute_at_stop(traced: &Traced, compute: u64) { + let Some(LimitCheck::ExceedsLimit { kind: LimitKind::ComputeGas, used, .. }) = + traced.outcome.limit_exceeded + else { + panic!("gas detention did not stop the transaction: {:?}", traced.outcome.limit_exceeded); + }; + assert_eq!(used, compute, "the compute at the crossing"); +} + +/// The transaction's own frame resumed after the call that returned the stop and ran on to +/// `last`, its last struct-log step at depth 1. +pub(crate) fn assert_parent_resumed(traced: &Traced, last: &str) { + let logs = traced.struct_logs().struct_logs; + let call = logs.iter().position(|log| log.depth == 1 && log.op == "CALL").expect("a call"); + let resumed = logs.iter().skip(call + 1).filter(|log| log.depth == 1).last(); + assert_eq!( + resumed.map(|log| log.op.to_string()), + Some(last.to_string()), + "the parent resumed after the call that was stopped" + ); +} + +/// Known shape: the last opcode step of a gas-detention stop reads as an out-of-gas that cost +/// the frame all the gas it had, though the engine never made that charge. +/// +/// The crossing charge fails in the interpreter the way an out-of-gas does, which zeroes the +/// frame's gas, and both the struct-log builder and the EIP-3155 tracer take the step's cost and +/// status in `step_end`, from that state. The engine puts the frame's gas back to what it had +/// before the charge only when it settles the frame's result, after the step, so the receipt +/// bills the compute before the charge while the step shows the frame's whole gas as its cost. +/// +/// If the engine starts settling the crossing before `step_end` sees it, or a tracer stops +/// reading it there, this fails: the step then has a cost no larger than the charge that +/// crossed, and the assertion should require that instead. +pub(crate) fn assert_detention_step_reads_as_out_of_gas(traced: &Traced, crossing_op: &str) { + let logs = traced.struct_logs().struct_logs; + let last = logs.last().expect("the frames ran"); + let shape = "the detention crossing's step reads as an out-of-gas that spent the frame's \ + whole gas (a fix makes this fail: require the step's own cost instead)"; + assert_eq!(last.op, crossing_op, "{shape}"); + let error = last.error.as_deref(); + assert!(error.is_some_and(|error| error.contains("OutOfGas")), "{shape}: error {error:?}"); + assert_eq!(last.gas_cost, last.gas, "{shape}"); + // How revm-inspectors renders the error, apart from what it is: the `Debug` of the step's + // `Option` status. A tracer that prints the status alone changes only this. + assert_eq!( + error, + Some("Some(OutOfGas)"), + "revm-inspectors renders a step's error as the Debug of an Option; a tracer that prints \ + the status alone makes this fail: update the expected string and review the detention \ + snapshots with `cargo insta review`" + ); + assert!(last.gas_cost > traced.outcome.gas.gas_used, "{shape}: the receipt bills none of it"); + let eip3155 = traced.eip3155(); + let last_step = eip3155.lines().rfind(|line| line.contains("\"opName\"")).expect("a step"); + let step: serde_json::Value = serde_json::from_str(last_step).expect("a JSON line"); + assert_eq!(step["opName"], crossing_op, "{shape} (EIP-3155)"); + assert_eq!(step["error"], "OutOfGas", "{shape} (EIP-3155)"); + assert_eq!(step["gasCost"], step["gas"], "{shape} (EIP-3155)"); +} + +/// The keyless call frame recorded no opcode steps; the creation frame recorded some. +/// +/// This reads the inspector's own record of the frames. What a node's opcode tracer makes of it +/// is [`assert_keyless_struct_logs_miss_the_creation`]. +pub(crate) fn assert_keyless_steps(traced: &Traced, expect_create: bool) { + let nodes = traced.inspector.traces().nodes(); + assert!(!nodes.is_empty(), "the tracer recorded a call frame"); + let call_steps = nodes[0].trace.steps.len(); + assert_eq!( + call_steps, 0, + "the keyless call frame now runs {call_steps} step(s): this lifts the known limitation \ + `assert_keyless_struct_logs_miss_the_creation` names; update both together" + ); + if expect_create { + assert!(nodes.len() >= 2, "expected a creation child, got {} frames", nodes.len()); + assert!( + !nodes[1].trace.steps.is_empty(), + "the keyless creation frame must have struct-log steps" + ); + } else { + assert_eq!(nodes.len(), 1, "a refused keyless call starts no creation"); + } +} + +/// Known limitation: the opcode tracer a node runs shows no step of a keyless deployment, though +/// the creation ran its init code. +/// +/// The engine runs no instruction in the `keylessDeploy` call's frame, so the frame has no steps, +/// and the creation is its child one level below. revm-inspectors' struct-log builder starts +/// from the root frame's steps and enters a child frame only through a call-opcode step of its +/// parent (`push_steps_on_stack`), so it never reaches the creation's steps, which the inspector +/// did record and the EIP-3155 trace prints. +/// +/// A change on either side — the engine giving the call frame a step that leads to its child, or +/// the builder walking a frame's children without one — makes this fail; that is the moment to +/// require the creation's steps in the struct logs instead and review the keyless snapshots. +pub(crate) fn assert_keyless_struct_logs_miss_the_creation(traced: &Traced) { + let nodes = traced.inspector.traces().nodes(); + let creation_steps = nodes[1].trace.steps.len(); + let call_steps = nodes[0].trace.steps.len(); + assert_eq!( + call_steps, 0, + "known limitation lifted on the engine's side: the keyless call frame now runs \ + {call_steps} step(s), which may lead the struct-log builder to its creation; require the \ + creation's steps in the struct logs here instead of their absence, update \ + `assert_keyless_steps`, and review the keyless snapshots with `cargo insta review`" + ); + assert!(creation_steps > 0, "the inspector recorded the creation's steps"); + let eip3155_steps = traced.eip3155().lines().filter(|line| line.contains("\"opName\"")).count(); + assert_eq!(eip3155_steps, creation_steps, "the EIP-3155 trace prints the creation's steps"); + let struct_logs = traced.struct_logs().struct_logs; + assert!( + struct_logs.is_empty(), + "known limitation lifted: the struct logs of a keyless deployment now show {} step(s) of \ + its creation (the inspector recorded {creation_steps}); require them in \ + `assert_keyless_struct_logs_miss_the_creation` instead of their absence, and review the \ + keyless snapshots with `cargo insta review`", + struct_logs.len() + ); +} diff --git a/crates/mega-evm/tests/tracers/main.rs b/crates/mega-evm/tests/tracers/main.rs new file mode 100644 index 000000000..02a23e5af --- /dev/null +++ b/crates/mega-evm/tests/tracers/main.rs @@ -0,0 +1,40 @@ +//! Snapshot tests of `revm-inspectors` tracer output on the Satin engine. +//! +//! These live next to the other Satin integration tests under `crates/mega-evm/tests/`, not +//! under `bin/mega-evme`: pinning the JSON against the engine's own `test-utils` keeps the +//! snapshots independent of CLI argument parsing and of the legacy 1.7.1 leg `mega-evme` still +//! links. +//! +//! The geth views are what a node returns: each is built by revm-inspectors' `DebugInspector`, +//! whose `get_result` is what reth's debug API calls. The CLI (`bin/mega-evme/src/common/trace.rs`) +//! calls the trace builders directly, without setting the root frame's gas limit to the +//! transaction's, so the root `gas` it prints is the first frame's budget instead. +//! +//! The EIP-3155 trace is the revm fork's `TracerEip3155`, the tracer the state-test runner runs +//! Satin under. +//! +//! The snapshots are the output of the tracers `Cargo.lock` resolves: revm-inspectors 0.40.4 (the +//! workspace asks for `0.40.1` or later) and the revm fork's inspector crate. A lock update that +//! changes what a tracer prints moves them, and fails the named tracer-shape assertions it +//! touches, such as the keyless struct logs' gap and the detention step's rendering. +//! +//! Each scenario pins two snapshots under `tests/tracers/snapshots/`, the call tracer with logs and +//! the prestate tracer's diff, and two scenarios (`OPCODE_VIEWS`) pin the opcode tracer as well. +//! The snapshots hold the trace's structure with every gas figure redacted (`redact_gas`): the +//! frame tree, the logs, the revert data and the accounts and slots a transaction reads and +//! writes. The figures are asserted against the schedule instead (`assert_ledgers`, +//! `assert_root_gas_used_is_the_receipt` and the relations beside them), so a change to a price +//! moves no snapshot. The comparison runs only at the spec's byte prices. +//! +//! Review a change with `cargo insta review`, which shows each snapshot and accepts or rejects it +//! on its own. Without `cargo-insta`, diff each `.snap.new` the failing run left against its +//! `.snap` and accept it on its own, by moving it over the `.snap` without its `assertion_line:` +//! header line. A tracer-shape change moves many snapshots at once; each is still reviewed and +//! accepted on its own, never all at once. A snapshot no test refers to is unreferenced, which +//! `cargo insta test --check --unreferenced=reject` rejects. + +mod gas; +mod harness; +mod scenarios; +#[path = "../shared/snapshot.rs"] +mod snapshot; diff --git a/crates/mega-evm/tests/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs new file mode 100644 index 000000000..1f1935d75 --- /dev/null +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -0,0 +1,952 @@ +//! The Satin scenarios the tracer snapshots pin, listed in [`SCENARIOS`], one test each so a +//! mismatch names the case. +//! +//! Every test asserts what its scenario must show — what it is billed on each ledger, worked out +//! from the schedule; the limit that stops it; what the tracers make of it — before it compares +//! a snapshot, so a snapshot cannot pin output a relation rejects. Where a tracer shows +//! something other than what the engine did, the shape is asserted by name with its reason, so a +//! change on either side fails that assertion rather than moving a snapshot. + +use std::collections::BTreeMap; + +use alloy_primitives::{address, hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_rpc_types_trace::geth::PreStateFrame; +use alloy_sol_types::SolCall; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + satin_gas_params, satin_precompiles, + system::{ + keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_OVERHEAD_GAS, + }, + ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE, HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_CODE, LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE, + ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, SEQUENCER_REGISTRY_ADDRESS, + SEQUENCER_REGISTRY_CODE, + }, + test_utils::{op_transaction, transfer_log, BytecodeBuilder, MemoryDatabase}, + tx_body_history_bytes, EvmTxRuntimeLimits, LimitKind, MegaTransaction, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CODECOPY, GAS as GAS_OP, JUMP, JUMPDEST, LOG0, LOG1, POP, PUSH0, RETURN, STATICCALL, + TIMESTAMP, + }, + context::{result::ExecutionResult, TxEnv}, + context_interface::cfg::{ + gas::{BASE, JUMPDEST as JUMPDEST_GAS, MID, VERYLOW}, + GasId, + }, + precompile::kzg_point_evaluation as kzg, +}; + +use crate::{ + gas::{self, Ledgers}, + harness::{ + assert_compute_at_stop, assert_detention_step_reads_as_out_of_gas, assert_eip3155_agrees, + assert_every_frame_stops, assert_keyless_steps, + assert_keyless_struct_logs_miss_the_creation, assert_ledgers, + assert_log_index_counts_discarded, assert_logs, assert_parent_resumed, + assert_prestate_covers_reads, assert_root_frame_settles, assert_root_gas_is_the_gas_limit, + assert_root_gas_used_is_the_receipt, call_tx, create_tx, decode_stop, eip3155_steps, + eip3155_summary_gas_used, pin_tracer_views, step, Traced, + }, +}; + +const CALLER: Address = address!("0x0000000000000000000000000000000000400000"); +const PAYEE: Address = address!("0x0000000000000000000000000000000000400001"); +const CONTRACT: Address = address!("0x0000000000000000000000000000000000400002"); +const CHILD: Address = address!("0x0000000000000000000000000000000000400003"); + +/// Every scenario, by the name its snapshots are pinned under. +const SCENARIOS: [&str; 15] = [ + "create", + "data_size_first_frame_start_stop", + "data_size_stop_caught_by_the_parent", + "deposit", + "detention_stop_crosses_again_in_the_parent", + "eth_transfer", + "frame_budget_child_revert", + "identity_precompile", + "keyless_refused", + "keyless_success", + "nested_inner_revert", + "precompile_child", + "reservoir_sstore", + "sstore_new_slot", + "timestamp_detention", +]; + +/// A margin every scenario's gas limit carries on top of what the scenario is billed and holds in +/// passing ([`gas_limit`]). Nothing a scenario does may rely on it: what a scenario needs is in +/// its bill and its `held`. It is there so that a derivation that falls a few charges short is +/// reported by the assertion on the ledger it got wrong, not as an out-of-gas. +const ROOM: u64 = 1_000_000; + +/// The gas limit of a scenario billed `expected` that must also hold `held` in passing, at the +/// byte prices in effect, with [`ROOM`] on top. +/// +/// The bill is the receipt, the EIP-7623 floor included: a gas limit below the floor is refused. +/// What a scenario holds in passing is gas it is not billed: what it is charged and given back, +/// the 64th a call keeps back from its forward ([`kept_back`]), and what a rule, a limit or an +/// assertion needs it to hold without spending it. +fn gas_limit(expected: Ledgers, held: u64) -> u64 { + ROOM + expected.receipt() + held +} + +/// What a caller holds beyond `forwarded` for a forward of all but a 64th of its gas to still +/// cover `forwarded`: a 63rd of it, rounded up. +const fn kept_back(forwarded: u64) -> u64 { + forwarded.div_ceil(63) +} + +/// The gas limit the keyless deployments are signed with, which the call's forward must cover. +const SIGNED_GAS_LIMIT: u64 = 1_000_000; + +fn funded() -> MemoryDatabase { + MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000_000_000_000_u64)) +} + +/// Holds `traced` to the relations every scenario meets — it is billed `expected` — then pins its +/// views under `name`. +/// +/// Every test calls this last, so a relation that fails stops the test before any snapshot is +/// compared. +fn pin(name: &str, traced: &Traced, expected: Ledgers) { + pin_given_back(name, traced, expected, 0); +} + +/// [`pin`], for a transaction whose own frame failed after `given_back` of its state and history +/// gas had spilled onto its regular gas: the failure gives it back after the tracer read the +/// frame (see `assert_root_frame_settles`). +fn pin_given_back(name: &str, traced: &Traced, expected: Ledgers, given_back: u64) { + assert!(SCENARIOS.contains(&name), "{name} is not listed in SCENARIOS"); + assert_ledgers(traced, expected); + assert_root_frame_settles(traced, given_back); + assert_eip3155_agrees(traced); + assert_prestate_covers_reads(traced); + assert_root_gas_is_the_gas_limit(traced); + assert_root_gas_used_is_the_receipt(traced); + pin_tracer_views(name, traced); +} + +/// The regular gas [`BytecodeBuilder::call`] spends before its callee runs: four `PUSH0`, a +/// `PUSH32` of the value, a `PUSH20` of the target, `GAS`, and the `CALL`'s cold access, with the +/// value transfer's charge when it carries value. +fn call_regular(carries_value: bool) -> u64 { + let value = if carries_value { gas::entry(GasId::transfer_value_cost()) } else { 0 }; + 4 * BASE + 2 * VERYLOW + BASE + gas::cold_account() + value +} + +/// The regular gas [`BytecodeBuilder::sstore`] of a fresh, cold slot spends: two `PUSH32` and the +/// `SSTORE`. +fn sstore_regular() -> u64 { + 2 * VERYLOW + gas::sstore_fresh_cold() +} + +/// Ordinary ETH transfer. The 7708 transfer log is what `call_with_log` pins. +#[test] +fn test_eth_transfer_emits_7708_log() { + // The recipient does not exist: EIP-2780 charges the account the transfer adds, and the + // transaction's own frame makes one record, the recipient's. + let expected = Ledgers { + regular: gas::call_intrinsic(&[], true), + state: gas::account_state(), + history: gas::body(0) + gas::records(1), + floor: gas::call_floor(&[], true), + }; + let traced = Traced::run( + funded(), + call_tx(CALLER, PAYEE, Bytes::new(), U256::from(1), gas_limit(expected, 0)), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + assert_logs(&traced.call_frame(true).logs, &[transfer_log(CALLER, PAYEE, U256::from(1))]); + assert_log_index_counts_discarded(&traced, &[0]); + pin("eth_transfer", &traced, expected); +} + +/// What a call that writes one fresh slot and stops is billed, whichever pool pays: the slot's +/// `SSTORE`, its state gas and its record. +fn fresh_slot_ledgers() -> Ledgers { + Ledgers { + regular: gas::call_intrinsic(&[], false) + sstore_regular(), + state: gas::slot_state(), + history: gas::body(0) + gas::records(1), + floor: gas::call_floor(&[], false), + } +} + +/// A call that writes a fresh storage slot, so the receipt carries state gas. +#[test] +fn test_sstore_new_slot_charges_state_gas() { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); + let traced = Traced::run( + funded().account_code(CONTRACT, code), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(fresh_slot_ledgers(), 0)), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + assert_eq!(traced.outcome.gas.state, gas::slot_state(), "a fresh slot costs state gas"); + // Below the execution cap there is no reservoir: the slot's state gas and its record's + // history spill onto regular gas, so the opcode tracer shows them in the step's cost. + assert_eq!(traced.outcome.gas.reservoir_remaining, 0, "no reservoir below the cap"); + let sstore = step(&traced, "SSTORE", 1); + let spilled = gas::slot_state() + gas::records(1); + assert_eq!(sstore.gas_cost, gas::sstore_fresh_cold() + spilled, "the SSTORE step's cost"); + let written = BTreeMap::from([(B256::with_last_byte(1), B256::with_last_byte(1))]); + assert_eq!(sstore.storage, Some(written), "the SSTORE step shows the slot it filled"); + pin("sstore_new_slot", &traced, fresh_slot_ledgers()); +} + +/// A creation transaction that deposits a non-empty runtime: the deposit is charged its hashing, +/// state and history gas, and the code is in the post-state the diff tracer reports. +#[test] +fn test_create_deploys_runtime_code() { + // The created account and its record, the init code, and the deposit: its hashing, the code's + // state gas and its history. + let init = deploying_runtime(); + let len = runtime().len(); + let expected = Ledgers { + regular: gas::create_intrinsic(&init) + deploying_runtime_regular(), + state: gas::created_state(len), + history: gas::body(init.len()) + gas::records(1) + gas::history(len as u64), + floor: gas::create_floor(&init), + }; + let traced = Traced::run( + funded(), + create_tx(CALLER, init, gas_limit(expected, 0)), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + let created = CALLER.create(0); + let code = traced.outcome.state[&created].info.code.as_ref().expect("the code is in the state"); + assert_eq!(code.original_bytes(), runtime(), "the created account holds the runtime"); + let PreStateFrame::Diff(diff) = traced.prestate(true) else { panic!("the diff mode") }; + assert_eq!(diff.post[&created].code.as_ref(), Some(&runtime()), "the diff shows the code"); + // The EIP-3155 summary reads the frame's gas after its last step, the `RETURN`; the deposit is + // charged after it, in `return_create`. + let summary = eip3155_summary_gas_used(&traced); + assert_eq!(summary + gas::deposit(len), expected.spent(), "EIP-3155 summary"); + pin("create", &traced, expected); +} + +/// A value call whose callee writes a fresh slot and emits a log, then reverts; the caller then +/// emits a log of its own. Everything the callee was charged on the state and history ledgers is +/// given back: the slot's state gas, its record, its log, and the two records of the value +/// transfer its start made. Its logs, the EIP-7708 transfer log of the value included, are +/// discarded with it. +#[test] +fn test_nested_call_inner_reverts() { + let child = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .push_number(0x42_u8) + .append_many([PUSH0, PUSH0, LOG1]) + .revert() + .build(); + let parent = BytecodeBuilder::default() + .call(CHILD, U256::from(1)) + .append_many([POP, PUSH0, PUSH0, LOG0]) + .stop() + .build(); + // The callee ran on what the caller forwarded and the value's stipend, and handed back what it + // left, so the caller pays the callee's regular spend less the stipend; the callee's state and + // history gas came back with its revert. + let callee_regular = sstore_regular() + VERYLOW + 2 * BASE + gas::log(1, 0) + 2 * BASE; + let caller = call_regular(true) + BASE + 2 * BASE + gas::log(0, 0); + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + caller + callee_regular - + gas::entry(GasId::call_stipend()), + state: 0, + history: gas::body(0) + gas::history(LOG_BASE_SIZE), + floor: gas::call_floor(&[], false), + }; + // Held in passing: the value call forwards all but a 64th of what the caller has and pays its + // two records' history out of that 64th, so the caller holds 64 times that history; the + // callee pays its slot and the slot's record before its revert gives them back; and the + // forward must cover all the callee spends, which the 64th kept back does not reach. + let spilled = gas::slot_state() + gas::records(1); + let held = 64 * gas::records(2) + spilled + kept_back(callee_regular + spilled); + let traced = Traced::run( + funded() + .account_code(CONTRACT, parent) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, child), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "the caller succeeds: {:?}", traced.outcome.result); + // The callee's charge was made: below the execution cap its slot's state gas and the slot's + // record spilled onto its regular gas, which the opcode tracer shows in the step's cost. + let sstore = step(&traced, "SSTORE", 2); + assert_eq!(sstore.gas_cost, gas::sstore_fresh_cold() + spilled, "the callee's SSTORE step"); + // And given back: no state gas stands, and the history the transaction keeps is its body + // and the caller's log alone. + assert_eq!(traced.outcome.gas.state, 0, "the callee's slot is given back"); + assert_eq!( + traced.outcome.gas.history, + gas::body(0) + gas::history(LOG_BASE_SIZE), + "the callee's records and log are given back" + ); + let root = traced.call_frame(true); + let [callee] = root.calls.as_slice() else { panic!("one callee: {root:?}") }; + assert_eq!(callee.error.as_deref(), Some("execution reverted")); + // The call tracer's `gasUsed` of the reverted callee counts the state and history gas its + // revert gave back: revm gives a failed frame that gas back when its caller merges the + // result, after the tracer read the frame. + assert_eq!( + callee.gas_used, + U256::from(callee_regular + spilled), + "the reverted callee's gasUsed counts what its revert gave back" + ); + assert!(callee.logs.is_empty(), "the callee's logs are discarded"); + assert_eq!(root.logs.len(), 1, "the caller's log alone, no transfer log"); + assert_eq!(root.logs[0].address, Some(CONTRACT)); + // The receipt keeps the caller's log alone, at index 0; before it the callee's transfer log + // and its `LOG1` were emitted and discarded with the callee. + assert_log_index_counts_discarded(&traced, &[2]); + pin("nested_inner_revert", &traced, expected); +} + +fn system_db() -> MemoryDatabase { + funded() + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE) + .account_code(HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, HIGH_PRECISION_TIMESTAMP_ORACLE_CODE) + .account_code(KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE) + .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) + .account_code(LIMIT_CONTROL_ADDRESS, LIMIT_CONTROL_CODE) + .account_code(SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE) +} + +/// A pre-EIP-155 signed creation, as Nick's Method makes one. +struct Deployment { + tx: Bytes, + /// The address the signature recovers to. + signer: Address, +} + +impl Deployment { + fn signed(value: U256, init_code: Bytes) -> Self { + let tx = mega_evm::alloy_consensus::TxLegacy { + nonce: 0, + gas_price: 100_000_000_000, + gas_limit: SIGNED_GAS_LIMIT, + to: TxKind::Create, + value, + input: init_code, + chain_id: None, + }; + let word = U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )); + let signed = mega_evm::alloy_consensus::Signed::new_unchecked( + tx, + Signature::new(word, word, false), + B256::ZERO, + ); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + let signer = signed.recover_signer().expect("Nick's-Method signature recovers"); + Self { tx: encoded.into(), signer } + } + + fn call_data(&self) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: self.tx.clone(), + gasLimitOverride: U256::from(10_000_000_000_u64), + } + .abi_encode() + .into() + } +} + +/// The runtime the creation scenarios deploy: it returns nothing. +fn runtime() -> Bytes { + BytecodeBuilder::default().return_empty().build() +} + +/// The regular gas [`deploying_runtime`] spends, its deposit's included: three pushes of a byte or +/// two and two `PUSH0`, the `CODECOPY` of the runtime into one word of memory, the `RETURN`, and +/// the deposit's regular part. +fn deploying_runtime_regular() -> u64 { + let len = runtime().len() as u64; + let codecopy = VERYLOW + gas::entry(GasId::copy_per_word()) * gas::words(len); + 3 * VERYLOW + + 2 * BASE + + codecopy + + gas::memory(gas::words(len)) + + gas::deposit_regular(len as usize) +} + +/// Init code that copies [`runtime`] from its own tail and deposits it. +fn deploying_runtime() -> Bytes { + let runtime = runtime(); + let len = u8::try_from(runtime.len()).expect("a short runtime"); + let prefix = BytecodeBuilder::default() + .push_number(len) + .push_number(0_u16) + .append(PUSH0) + .append(CODECOPY) + .push_number(len) + .append(PUSH0) + .append(RETURN); + let tail = u16::try_from(prefix.len()).expect("a short prefix"); + BytecodeBuilder::default() + .push_number(len) + .push_number(tail) + .append(PUSH0) + .append(CODECOPY) + .push_number(len) + .append(PUSH0) + .append(RETURN) + .append_many(runtime) + .build() +} + +fn keyless_tx(data: Bytes, gas_limit: u64) -> MegaTransaction { + call_tx(CALLER, KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO, gas_limit) +} + +/// A `keylessDeploy` that deploys: the answer names the signer's first creation address and no +/// error, and that address holds the runtime afterwards. +#[test] +fn test_keyless_deploy_succeeds() { + let deployment = Deployment::signed(U256::ZERO, deploying_runtime()); + // The call's overhead, the `CREATE` opcode's regular gas, the signer's account (it was empty) + // and the created account, the creation's two records (the signer's nonce and the created + // account), and what the creation spent: its init code and its deposit. + let calldata = deployment.call_data(); + let init = deploying_runtime(); + let len = runtime().len(); + let expected = Ledgers { + regular: gas::call_intrinsic(&calldata, false) + + KEYLESS_DEPLOY_OVERHEAD_GAS + + satin_gas_params().create_cost() + + satin_gas_params().initcode_cost(init.len()) + + deploying_runtime_regular(), + state: gas::account_state() + gas::created_state(len), + history: gas::body(calldata.len()) + gas::records(2) + gas::history(len as u64), + floor: gas::call_floor(&calldata, false), + }; + // Held in passing: what the call forwards to the creation must still cover the signed gas + // limit. + let traced = Traced::run( + system_db(), + keyless_tx(calldata, gas_limit(expected, SIGNED_GAS_LIMIT)), + EvmTxRuntimeLimits::no_limits(), + ); + let ExecutionResult::Success { output, .. } = &traced.outcome.result else { + panic!("the keyless call succeeds: {:?}", traced.outcome.result); + }; + let answer = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy answer"); + let deployed = deployment.signer.create(0); + assert_ne!(deployed, Address::ZERO); + assert_eq!(answer.deployedAddress, deployed, "the answer names the deploy address"); + assert!(answer.errorData.is_empty(), "a deployment that deployed reports no error"); + let code = + traced.outcome.state[&deployed].info.code.as_ref().expect("the code is in the state"); + assert_eq!(code.original_bytes(), runtime(), "the deploy address holds the runtime"); + // `gasUsed` is what the creation spent from both pools: its init code and its deposit, the + // deposit's state and history gas included. Below the execution cap there is no reservoir, + // so all of it drew the creation frame's regular gas, which the tracer measured. + let creation_spend = deploying_runtime_regular() + + satin_gas_params().code_deposit_state_gas(len) + + gas::history(len as u64); + assert_eq!(answer.gasUsed, creation_spend, "gasUsed is the creation's init code and deposit"); + let nodes = traced.inspector.traces().nodes(); + let (call, creation) = (&nodes[0].trace, &nodes[1].trace); + assert_eq!(answer.gasUsed, creation.gas_used, "and the tracer measured the creation the same"); + // The call forwards all it has left once it paid for itself: the overhead, the `CREATE` + // opcode's regular gas, the signer's account and the created account, and the creation's two + // records, which spilled onto its regular gas. + let call_charges = KEYLESS_DEPLOY_OVERHEAD_GAS + + satin_gas_params().create_cost() + + satin_gas_params().initcode_cost(init.len()) + + gas::account_state() + + gas::entry(GasId::create_state_gas()) + + gas::records(2); + assert_eq!( + creation.gas_limit, + call.gas_limit - call_charges, + "the creation gets what the call has left after its own charges" + ); + assert_keyless_struct_logs_miss_the_creation(&traced); + assert_keyless_steps(&traced, true); + // The EIP-3155 summary reads the creation's gas after its last step, the `RETURN`, two frames + // away from the receipt: the deposit is charged after it, in `return_create`, and the call + // frame returns what is left of the creation's gas, spending nothing more. + let summary = eip3155_summary_gas_used(&traced); + assert_eq!(summary + gas::deposit(len), expected.spent(), "EIP-3155 summary"); + pin("keyless_success", &traced, expected); +} + +/// A `keylessDeploy` the rules refuse: value with an unfunded signer. No creation starts. +#[test] +fn test_keyless_deploy_refused() { + let deployment = Deployment::signed(U256::from(1), deploying_runtime()); + // A refusal keeps the regular gas the call spent, the overhead, and gives back the signer's + // account it charged before the balance rule refused. + let calldata = deployment.call_data(); + let expected = Ledgers { + regular: gas::call_intrinsic(&calldata, false) + KEYLESS_DEPLOY_OVERHEAD_GAS, + state: 0, + history: gas::body(calldata.len()), + floor: gas::call_floor(&calldata, false), + }; + // Held in passing: the signer's account, until the refusal gives it back, and the signed gas + // limit, which what the call has left once it paid that account must still cover when the + // rules check the forward, before the balance rule. + let held = gas::account_state() + SIGNED_GAS_LIMIT; + let traced = Traced::run( + system_db(), + keyless_tx(calldata, gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits(), + ); + let ExecutionResult::Revert { output, .. } = &traced.outcome.result else { + panic!("the keyless call reverts: {:?}", traced.outcome.result); + }; + assert_eq!( + decode_error_result(output), + Some(KeylessDeployError::InsufficientBalance), + "the signer cannot fund the carried value" + ); + assert_keyless_steps(&traced, false); + // The call frame paid the signer's account out of its regular gas before the refusal gave it + // back. + pin_given_back("keyless_refused", &traced, expected, gas::account_state()); +} + +/// A parent that calls [`CHILD`] with all its gas and no value, then, if it resumes, writes a +/// slot and stops. A stop that reaches the parent must keep that write from running. +fn calling_child() -> Bytes { + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::ZERO, U256::from(1)) + .stop() + .build() +} + +/// A frame that emits one `LOG0` of `data_len` bytes of memory, then stops. +fn logging(data_len: u8) -> Bytes { + BytecodeBuilder::default().push_number(data_len).append_many([PUSH0, LOG0]).stop().build() +} + +/// The regular gas [`logging`] spends: a `PUSH1`, a `PUSH0`, and the `LOG0` with its memory. +fn logging_regular(data_len: u8) -> u64 { + let len = u64::from(data_len); + VERYLOW + BASE + gas::log(0, len) + gas::memory(gas::words(len)) +} + +/// The data size of a `LOG0` of `data_len` bytes: its address word and its data. +fn log0_size(data_len: u8) -> u64 { + LOG_BASE_SIZE + u64::from(data_len) +} + +/// A first frame whose start crosses the transaction's data-size limit, at the smallest limit +/// validation admits the transaction under: its body fits, and the record and the transfer log of +/// its value do not. The frame is answered with the stop before it runs, so it runs no instruction +/// and its value never moves. A body over the limit is no scenario: validation rejects it, and a +/// rejected transaction has no trace. +#[test] +fn test_data_size_limit_stops_the_first_frame_at_its_start() { + let limit = TX_BODY_SIZE; + assert_eq!(tx_body_history_bytes(0, 0, 0, 0), limit, "the body fits exactly"); + // The sender pays the intrinsic gas and the body's history, and nothing ran: the history of + // the recipient's record, charged before the first frame and held here, comes back with it. + let held = mega_evm::write_record_history_gas(1).expect("a record has a price"); + let expected = Ledgers { + regular: gas::call_intrinsic(&[], true), + state: 0, + history: gas::body(0), + floor: gas::call_floor(&[], true), + }; + let traced = Traced::run( + funded().account_code(CONTRACT, BytecodeBuilder::default().stop().build()), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::from(1), gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_every_frame_stops(&traced, LimitKind::DataSize, limit, 1); + assert!(traced.inspector.traces().nodes()[0].trace.steps.is_empty(), "no instruction ran"); + // The record's history was charged on the transaction's gas before the frame and comes back + // after the tracer read the frame, as a failed frame's spill does. + pin_given_back("data_size_first_frame_start_stop", &traced, expected, held); +} + +/// A child's `LOG0` that crosses the transaction's data-size limit and, with it, its own frame +/// budget. The transaction limit is the one the child's stop names, and only the child reverts: +/// the parent resumes, writes a slot within what the transaction has left, and succeeds. +#[test] +fn test_data_size_limit_stop_is_caught_by_the_parent() { + // What the transaction may produce besides its body; the child's log is larger, the parent's + // record is not. + let room = 100; + let data_len = 128; + assert!(log0_size(data_len) > room, "the log crosses the transaction's limit"); + let limit = TX_BODY_SIZE + room; + // The child's `LOG0` charged its regular gas before its record crossed the limit; its log was + // never made, so it cost no history. The parent then drops the call's status and writes a + // fresh slot. + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + + call_regular(false) + + logging_regular(data_len) + + BASE + + sstore_regular(), + state: gas::slot_state(), + history: gas::body(0) + gas::records(1), + floor: gas::call_floor(&[], false), + }; + // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // child spends. + let held = kept_back(logging_regular(data_len)); + let traced = Traced::run( + funded().account_code(CONTRACT, calling_child()).account_code(CHILD, logging(data_len)), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + assert_eq!(traced.outcome.limit_exceeded, None, "a stop below the transaction's own frame"); + let root = traced.call_frame(true); + assert_eq!(root.error, None, "the parent succeeds"); + let [child] = root.calls.as_slice() else { panic!("one child frame: {root:?}") }; + assert_eq!(child.error.as_deref(), Some("execution reverted")); + assert_eq!( + decode_stop(child.output.as_ref().expect("the child's revert data")), + (LimitKind::DataSize, limit), + "the child reverts with the transaction's limit" + ); + assert!(child.logs.is_empty(), "the child's log was never made"); + assert_parent_resumed(&traced, "STOP"); + assert_eq!( + traced.outcome.usage.data_size, + TX_BODY_SIZE + WRITE_RECORD_SIZE, + "the transaction keeps its body and the parent's record, within its limit" + ); + pin("data_size_stop_caught_by_the_parent", &traced, expected); +} + +/// A child's `LOG0` that crosses its own frame budget, 98/100 of what its parent has left, but +/// not the transaction's limit. Only the child reverts, with its budget; the parent resumes and +/// emits a log of its own, and the transaction succeeds. +#[test] +fn test_frame_budget_reverts_the_child_alone() { + let room = 200; + let budget = room * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let data_len = 166; + assert!(log0_size(data_len) > budget, "the log crosses the child's budget"); + assert!(log0_size(data_len) <= room, "and not what the transaction has left"); + let parent = BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append_many([POP, PUSH0, PUSH0, LOG0]) + .stop() + .build(); + let parent_regular = call_regular(false) + BASE + 2 * BASE + gas::log(0, 0); + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + parent_regular + logging_regular(data_len), + state: 0, + history: gas::body(0) + gas::history(LOG_BASE_SIZE), + floor: gas::call_floor(&[], false), + }; + // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // child spends. + let held = kept_back(logging_regular(data_len)); + let traced = Traced::run( + funded().account_code(CONTRACT, parent).account_code(CHILD, logging(data_len)), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE + room), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + assert!(traced.outcome.limit_exceeded.is_none(), "a frame budget below is no stop"); + let root = traced.call_frame(true); + assert_eq!(root.error, None, "the parent succeeds"); + assert_eq!(root.logs.len(), 1, "the parent resumed and logged"); + // The tracer saw the child's `LOG0` before the frame budget refused it; the receipt keeps the + // parent's log alone, at index 0. + assert_log_index_counts_discarded(&traced, &[1]); + let [child] = root.calls.as_slice() else { panic!("one child frame: {root:?}") }; + assert_eq!(child.error.as_deref(), Some("execution reverted")); + assert_eq!( + decode_stop(child.output.as_ref().expect("the child's revert data")), + (LimitKind::DataSize, budget), + "the child reverts with its own budget" + ); + assert!(child.logs.is_empty(), "the child's log was never made"); + assert_eq!( + traced.outcome.usage.data_size, + TX_BODY_SIZE + LOG_BASE_SIZE, + "the transaction keeps its body and the parent's log" + ); + pin("frame_budget_child_revert", &traced, expected); +} + +/// A transaction's own frame that reads `TIMESTAMP` and then loops past the detention cap. The +/// crossing is in the transaction's own frame, which the engine settles when the transaction +/// ends rather than when a child returns. +#[test] +fn test_timestamp_detention_stop() { + let cap = 80; + let code = BytecodeBuilder::default() + .append(TIMESTAMP) + .append(POP) + .append(JUMPDEST) + .push_number(2_u64) + .append(JUMP) + .build(); + // The compute at the read is the `TIMESTAMP` itself. + let limit = BASE + cap; + // The transaction is billed its compute before the charge that crossed: the `TIMESTAMP`, the + // `POP`, and the loop up to the limit. + let compute = gas::compute_at_crossing(2 * BASE, limit, &[JUMPDEST_GAS, VERYLOW, MID]); + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + compute, + state: 0, + history: gas::body(0), + floor: gas::call_floor(&[], false), + }; + // Held in passing: what the frame holds when it crosses. The charge that crosses, the + // `JUMP`'s: detention stops a charge the frame's whole gas covers, and one beyond it is an + // out-of-gas. On top of it the receipt, so the crossing step, which reads as spending the + // frame's whole gas, shows a cost the receipt cannot have billed. + let at_crossing = expected.receipt() + MID; + let traced = Traced::run( + funded().account_code(CONTRACT, code), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, at_crossing)), + EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(cap), + ); + assert_every_frame_stops(&traced, LimitKind::ComputeGas, limit, 1); + assert_detention_step_reads_as_out_of_gas(&traced, "JUMP"); + assert_compute_at_stop(&traced, compute); + pin("timestamp_detention", &traced, expected); +} + +/// A parent that reads `TIMESTAMP` and calls a child that loops: the child crosses the compute +/// limit the parent's read set and returns the stop; the parent resumes on what the limit leaves +/// it, its `POP` and the first push of its write fit, the second push crosses the limit again, +/// and the parent returns the same stop. +#[test] +fn test_detention_stop_crosses_again_in_the_parent() { + // Enough for the parent's call and a few dozen iterations of the child's loop, the last of + // them two gas short of a round, so that its `JUMP` is the charge that crosses. + let cap = BASE + call_regular(false) + 32 * (JUMPDEST_GAS + VERYLOW + MID) - 2; + let parent = BytecodeBuilder::default() + .append_many([PUSH0, POP, TIMESTAMP, POP]) + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::ZERO, U256::from(1)) + .stop() + .build(); + let child = BytecodeBuilder::default().append(JUMPDEST).push_number(0_u8).append(JUMP).build(); + // The compute at the read: `PUSH0`, `POP` and the `TIMESTAMP` itself. + let limit = 3 * BASE + cap; + // The parent's work up to and with its call, then the child's loop up to the limit, then the + // parent's `POP` and the pushes of its write up to the limit. + let before_loop = 3 * BASE + BASE + call_regular(false); + let at_the_child = gas::compute_at_crossing(before_loop, limit, &[JUMPDEST_GAS, VERYLOW, MID]); + let compute = gas::compute_at_crossing(at_the_child, limit, &[BASE, VERYLOW, VERYLOW]); + assert_eq!(limit - compute, 1, "the second push crosses, one gas short"); + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + compute, + state: 0, + history: gas::body(0), + floor: gas::call_floor(&[], false), + }; + // Held in passing: what the child holds when it crosses. The charge that crosses, the child's + // `JUMP`: detention stops a charge the frame's whole gas covers, and one beyond it is an + // out-of-gas. On top of it the receipt, so the crossing step, which reads as spending the + // child's whole gas, shows a cost the receipt cannot have billed. And the 64th the parent keeps + // back from a forward that must cover the child's loop and all that. + let at_crossing = expected.receipt() + MID; + let held = at_crossing + kept_back(compute - before_loop + at_crossing); + let traced = Traced::run( + funded().account_code(CONTRACT, parent).account_code(CHILD, child), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, held)), + EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(cap), + ); + assert_every_frame_stops(&traced, LimitKind::ComputeGas, limit, 2); + assert_parent_resumed(&traced, "PUSH32"); + assert_detention_step_reads_as_out_of_gas(&traced, "PUSH32"); + assert_compute_at_stop(&traced, compute); + pin("detention_stop_crosses_again_in_the_parent", &traced, expected); +} + +/// Gas limit above the 200M execution cap, so a fresh slot is paid from the reservoir first. +#[test] +fn test_reservoir_pays_state_gas() { + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).stop().build(); + // The reservoir pays the body's history before the first frame, then the slot's state gas and + // its record's history at the `SSTORE`: it holds them at the prices in effect, with the margin + // on top. The regular gas below the execution cap pays the rest. + let slot = gas::slot_state() + gas::records(1); + let reservoir = ROOM + gas::body(0) + slot; + let traced = Traced::run( + funded().account_code(CONTRACT, code), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, TX_GAS_LIMIT_CAP + reservoir), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + assert_eq!(traced.outcome.gas.state, gas::slot_state()); + // The reservoir paid the body's history before the first frame, then the slot's state gas + // and its record's history at the `SSTORE`; what is left goes back to the sender. + assert_eq!( + traced.outcome.gas.reservoir_remaining, + reservoir - gas::body(0) - slot, + "the reservoir left" + ); + // The opcode tracer shows only the regular part of the `SSTORE`: the rest came out of the + // reservoir, which only the EIP-3155 trace shows. + assert_eq!(step(&traced, "SSTORE", 1).gas_cost, gas::sstore_fresh_cold(), "the regular part"); + let steps = eip3155_steps(&traced); + let at = |op: &str| { + let line = steps.iter().find(|line| line["opName"] == op).expect("the step"); + u64::from_str_radix(line["reservoir"].as_str().unwrap().trim_start_matches("0x"), 16) + .unwrap() + }; + assert_eq!(at("PUSH32"), reservoir - gas::body(0), "the reservoir when the frame starts"); + assert_eq!(at("STOP"), at("SSTORE") - slot, "the reservoir the SSTORE drew"); + // The pools change who pays, not what is billed. + pin("reservoir_sstore", &traced, fresh_slot_ledgers()); +} + +/// A transaction to the identity precompile: its own frame is the precompile, which runs no +/// instruction and echoes its input. +#[test] +fn test_identity_precompile() { + let precompile = Address::with_last_byte(4); + let input = Bytes::from_static(&[0xde, 0xad, 0xbe, 0xef]); + let price = satin_precompiles() + .get(&precompile) + .and_then(|identity| identity.required_gas(&input)) + .expect("the Satin table prices identity"); + let expected = Ledgers { + regular: gas::call_intrinsic(&input, false) + price, + state: 0, + history: gas::body(input.len()), + floor: gas::call_floor(&input, false), + }; + let traced = Traced::run( + funded(), + call_tx(CALLER, precompile, input.clone(), U256::ZERO, gas_limit(expected, 0)), + EvmTxRuntimeLimits::no_limits(), + ); + let ExecutionResult::Success { output, .. } = &traced.outcome.result else { + panic!("the precompile succeeds: {:?}", traced.outcome.result); + }; + assert_eq!(output.data(), &input, "identity echoes its input"); + pin("identity_precompile", &traced, expected); +} + +/// The c-kzg test vector `verify_kzg_proof_case_correct_proof_4_4`, as the precompile takes it: +/// `versioned_hash ++ z ++ y ++ commitment ++ proof`. +fn kzg_input() -> Vec { + let commitment = hex!( + "8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca2\ + 5f26936857bc3a7c2539ea8ec3a952b7" + ); + let mut input = kzg::kzg_to_versioned_hash(&commitment).to_vec(); + input.extend(hex!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000")); + input.extend(hex!("1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9")); + input.extend(commitment); + input.extend(hex!( + "a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc216074\ + 4faf0070725e00b60ad9a026a15b1a8c" + )); + input +} + +/// A contract that `STATICCALL`s the KZG point evaluation precompile, the one Satin reprices: the +/// call tracer shows the precompile as a child frame that spent the Satin price. +#[test] +fn test_precompile_child_frame() { + let input = kzg_input(); + let len = u8::try_from(input.len()).expect("192 bytes"); + let code = BytecodeBuilder::default() + .mstore(0, &input) + .append_many([PUSH0, PUSH0]) + .push_number(len) + .append(PUSH0) + .push_address(kzg::ADDRESS) + .append_many([GAS_OP, STATICCALL, POP]) + .stop() + .build(); + let price = satin_precompiles() + .get(&kzg::ADDRESS) + .and_then(|precompile| precompile.required_gas(&input)) + .expect("the Satin table prices KZG"); + // Six words stored (a `PUSH32`, a `PUSH8` of the offset and an `MSTORE` each) and the memory + // they take, the call's five pushes and `GAS`, the precompile's warm access and its price, and + // the `POP`. + let words = gas::words(input.len() as u64); + let stores = words * 3 * VERYLOW + gas::memory(words); + let call = 2 * BASE + VERYLOW + BASE + VERYLOW + BASE + gas::warm_account() + price; + let expected = Ledgers { + regular: gas::call_intrinsic(&[], false) + stores + call + BASE, + state: 0, + history: gas::body(0), + floor: gas::call_floor(&[], false), + }; + // Held in passing: the 64th the contract keeps back from a forward that must cover the + // precompile's price. + let traced = Traced::run( + funded().account_code(CONTRACT, code), + call_tx(CALLER, CONTRACT, Bytes::new(), U256::ZERO, gas_limit(expected, kept_back(price))), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + let root = traced.call_frame(false); + let [child] = root.calls.as_slice() else { panic!("one child frame: {root:?}") }; + assert_eq!(child.typ, "STATICCALL"); + assert_eq!(child.to, Some(kzg::ADDRESS)); + assert_eq!(child.error, None, "the proof verifies"); + assert_eq!(child.gas_used, U256::from(price), "the child spent the Satin price"); + let answer = child.output.as_ref().expect("the evaluation's answer"); + assert_eq!(answer.as_ref(), &kzg::RETURN_VALUE[..], "the evaluation's answer"); + pin("precompile_child", &traced, expected); +} + +/// A deposit that mints and carries value to a contract which stops. The value is logged; the +/// mint is not. A deposit pays no history gas. +#[test] +fn test_deposit_transaction() { + let mint = 1_000_u128; + let value = U256::from(7); + // A deposit pays its intrinsic gas and what it ran, here nothing, and no history. + let expected = Ledgers { + regular: gas::call_intrinsic(&[], true), + state: 0, + history: 0, + floor: gas::call_floor(&[], true), + }; + let mut tx = op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(CONTRACT), + value, + gas_limit: gas_limit(expected, 0), + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x42); + tx.deposit.mint = Some(mint); + let traced = Traced::run( + funded().account_code(CONTRACT, BytecodeBuilder::default().stop().build()), + mega_evm::alloy_op_evm::OpTx(tx), + EvmTxRuntimeLimits::no_limits(), + ); + assert!(traced.outcome.result.is_success(), "{:?}", traced.outcome.result); + let history = (traced.outcome.gas.history, traced.outcome.gas.history_bytes); + assert_eq!(history, (0, 0), "a deposit pays no history"); + let root = traced.call_frame(true); + assert_logs(&root.logs, &[transfer_log(CALLER, CONTRACT, value)]); + assert_log_index_counts_discarded(&traced, &[0]); + let PreStateFrame::Diff(diff) = traced.prestate(true) else { panic!("the diff mode") }; + let before = diff.pre[&CALLER].balance.expect("the caller's balance"); + assert_eq!( + diff.post[&CALLER].balance, + Some(before + U256::from(mint) - value), + "the caller holds its balance, plus the mint, less the value" + ); + pin("deposit", &traced, expected); +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__call_with_log.snap new file mode 100644 index 000000000..5de229c5e --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__call_with_log.snap @@ -0,0 +1,14 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x600361000b5f3960035ff35f5ff3", + "output": "0x5f5ff3", + "to": "0x84b48846131a217635c4abd490c5e11486253fd9", + "type": "CREATE", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__prestate_diff.snap new file mode 100644 index 000000000..4b24febbd --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__create__prestate_diff.snap @@ -0,0 +1,20 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + }, + "0x84b48846131a217635c4abd490c5e11486253fd9": { + "code": "0x5f5ff3", + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap new file mode 100644 index 000000000..a205dd458 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap @@ -0,0 +1,15 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000136", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x1" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap new file mode 100644 index 000000000..6d31977f5 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap @@ -0,0 +1,26 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400002", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "0x84b902670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000019a", + "to": "0x0000000000000000000000000000000000400003", + "type": "CALL", + "value": "0x0" + } + ], + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__prestate_diff.snap new file mode 100644 index 000000000..3fcd008ec --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__prestate_diff.snap @@ -0,0 +1,25 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + }, + "0x0000000000000000000000000000000000400002": { + "storage": { + "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000001" + } + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x0000000000000000000000000000000000400002": { + "balance": "0x0", + "code": "0x5f5f5f5f7f00000000000000000000000000000000000000000000000000000000000000007300000000000000000000000000000000004000035af1507f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000005500" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__call_with_log.snap new file mode 100644 index 000000000..bbe098789 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__call_with_log.snap @@ -0,0 +1,26 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "logs": [ + { + "address": "0xfffffffffffffffffffffffffffffffffffffffe", + "data": "0x0000000000000000000000000000000000000000000000000000000000000007", + "index": "0x0", + "position": "0x0", + "topics": [ + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", + "0x0000000000000000000000000000000000000000000000000000000000400000", + "0x0000000000000000000000000000000000000000000000000000000000400002" + ] + } + ], + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x7" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__prestate_diff.snap new file mode 100644 index 000000000..c87eca36c --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__deposit__prestate_diff.snap @@ -0,0 +1,24 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c683e1", + "nonce": 1 + }, + "0x0000000000000000000000000000000000400002": { + "balance": "0x7" + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x0000000000000000000000000000000000400002": { + "balance": "0x0", + "code": "0x00" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__call_with_log.snap new file mode 100644 index 000000000..9fbea73d8 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__call_with_log.snap @@ -0,0 +1,28 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400002", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "MegaLimitExceeded(2, [gas])", + "to": "0x0000000000000000000000000000000000400003", + "type": "CALL", + "value": "0x0" + } + ], + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "MegaLimitExceeded(2, [gas])", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__struct_logs.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__struct_logs.snap new file mode 100644 index 000000000..8326360a3 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__detention_stop_crosses_again_in_the_parent__struct_logs.snap @@ -0,0 +1,1119 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.struct_logs())" +--- +{ + "failed": true, + "gas": "[gas]", + "returnValue": "MegaLimitExceeded(2, [gas])", + "structLogs": [ + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH0", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "POP", + "pc": 1, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "TIMESTAMP", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "POP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x6553f100" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH0", + "pc": 4, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH0", + "pc": 5, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH0", + "pc": 6, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH0", + "pc": 7, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0", + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH32", + "pc": 8, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0", + "0x0", + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH20", + "pc": 41, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0", + "0x0", + "0x0", + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "GAS", + "pc": 62, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0", + "0x0", + "0x0", + "0x0", + "0x400003" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "CALL", + "pc": 63, + "refund": "[gas]", + "stack": [ + "0x0", + "0x0", + "0x0", + "0x0", + "0x0", + "0x400003", + "[gas]" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH1", + "pc": 1, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 2, + "error": "Some(OutOfGas)", + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 3, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "POP", + "pc": 64, + "refund": "[gas]", + "stack": [ + "0x0" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH32", + "pc": 65, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "error": "Some(OutOfGas)", + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH32", + "pc": 98, + "refund": "[gas]", + "stack": [ + "0x1" + ] + } + ] +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__call_with_log.snap new file mode 100644 index 000000000..4786be797 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__call_with_log.snap @@ -0,0 +1,26 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "logs": [ + { + "address": "0xfffffffffffffffffffffffffffffffffffffffe", + "data": "0x0000000000000000000000000000000000000000000000000000000000000001", + "index": "0x0", + "position": "0x0", + "topics": [ + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", + "0x0000000000000000000000000000000000000000000000000000000000400000", + "0x0000000000000000000000000000000000000000000000000000000000400001" + ] + } + ], + "to": "0x0000000000000000000000000000000000400001", + "type": "CALL", + "value": "0x1" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__prestate_diff.snap new file mode 100644 index 000000000..66b5b48dd --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__eth_transfer__prestate_diff.snap @@ -0,0 +1,23 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c67fff", + "nonce": 1 + }, + "0x0000000000000000000000000000000000400001": { + "balance": "0x1" + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x0000000000000000000000000000000000400001": { + "balance": "0x0" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__call_with_log.snap new file mode 100644 index 000000000..3df1c7d2d --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__call_with_log.snap @@ -0,0 +1,35 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400002", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "0x84b90267000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c4", + "to": "0x0000000000000000000000000000000000400003", + "type": "CALL", + "value": "0x0" + } + ], + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "logs": [ + { + "address": "0x0000000000000000000000000000000000400002", + "data": "0x", + "index": "0x1", + "position": "0x1", + "topics": [] + } + ], + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__frame_budget_child_revert__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__call_with_log.snap new file mode 100644 index 000000000..31c03d54f --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__call_with_log.snap @@ -0,0 +1,14 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0xdeadbeef", + "output": "0xdeadbeef", + "to": "0x0000000000000000000000000000000000000004", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__identity_precompile__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__call_with_log.snap new file mode 100644 index 000000000..a600d0685 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__call_with_log.snap @@ -0,0 +1,15 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x846365d5000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000002540be4000000000000000000000000000000000000000000000000000000000000000061f85f8085174876e800830f424080018e600361000b5f3960035ff35f5ff31ba02222222222222222222222222222222222222222222222222222222222222222a0222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000", + "output": "0xf4d678b8", + "to": "0x6342000000000000000000000000000000000003", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_refused__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__call_with_log.snap new file mode 100644 index 000000000..3d3fa202c --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__call_with_log.snap @@ -0,0 +1,26 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "from": "0x321d4f4b0b29391cf2978fba82b6900524a09945", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x600361000b5f3960035ff35f5ff3", + "output": "0x5f5ff3", + "to": "0xcdde5625080d22bb0772fb7b1197e9b68b5d881f", + "type": "CREATE", + "value": "0x0" + } + ], + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x846365d5000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000002540be4000000000000000000000000000000000000000000000000000000000000000061f85f8085174876e800830f424080808e600361000b5f3960035ff35f5ff31ba02222222222222222222222222222222222222222222222222222222222222222a0222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000", + "output": "[gas]0x000000000000000000000000cdde5625080d22bb0772fb7b1197e9b68b5d881f00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000", + "to": "0x6342000000000000000000000000000000000003", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__prestate_diff.snap new file mode 100644 index 000000000..802796966 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__keyless_success__prestate_diff.snap @@ -0,0 +1,26 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + }, + "0x321d4f4b0b29391cf2978fba82b6900524a09945": { + "nonce": 1 + }, + "0xcdde5625080d22bb0772fb7b1197e9b68b5d881f": { + "code": "0x5f5ff3", + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x321d4f4b0b29391cf2978fba82b6900524a09945": { + "balance": "0x0" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__call_with_log.snap new file mode 100644 index 000000000..8130d96fc --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__call_with_log.snap @@ -0,0 +1,34 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400002", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "to": "0x0000000000000000000000000000000000400003", + "type": "CALL", + "value": "0x1" + } + ], + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "logs": [ + { + "address": "0x0000000000000000000000000000000000400002", + "data": "0x", + "index": "0x2", + "position": "0x1", + "topics": [] + } + ], + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__nested_inner_revert__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__call_with_log.snap new file mode 100644 index 000000000..35ab54804 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__call_with_log.snap @@ -0,0 +1,24 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "calls": [ + { + "from": "0x0000000000000000000000000000000000400002", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff000000001522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e98f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c", + "output": "0x000000000000000000000000000000000000000000000000000000000000100073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", + "to": "0x000000000000000000000000000000000000000a", + "type": "STATICCALL" + } + ], + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__precompile_child__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__call_with_log.snap new file mode 100644 index 000000000..25372310b --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__call_with_log.snap @@ -0,0 +1,13 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__prestate_diff.snap new file mode 100644 index 000000000..adcf87e03 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__reservoir_sstore__prestate_diff.snap @@ -0,0 +1,25 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + }, + "0x0000000000000000000000000000000000400002": { + "storage": { + "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000001" + } + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x0000000000000000000000000000000000400002": { + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000015500" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__call_with_log.snap new file mode 100644 index 000000000..25372310b --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__call_with_log.snap @@ -0,0 +1,13 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__prestate_diff.snap new file mode 100644 index 000000000..adcf87e03 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__sstore_new_slot__prestate_diff.snap @@ -0,0 +1,25 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + }, + "0x0000000000000000000000000000000000400002": { + "storage": { + "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000001" + } + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + }, + "0x0000000000000000000000000000000000400002": { + "balance": "0x0", + "code": "0x7f00000000000000000000000000000000000000000000000000000000000000017f00000000000000000000000000000000000000000000000000000000000000015500" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__call_with_log.snap new file mode 100644 index 000000000..3774051db --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__call_with_log.snap @@ -0,0 +1,15 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.call_frame(true))" +--- +{ + "error": "execution reverted", + "from": "0x0000000000000000000000000000000000400000", + "gas": "[gas]", + "gasUsed": "[gas]", + "input": "0x", + "output": "MegaLimitExceeded(2, [gas])", + "to": "0x0000000000000000000000000000000000400002", + "type": "CALL", + "value": "0x0" +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__prestate_diff.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__prestate_diff.snap new file mode 100644 index 000000000..5a5321502 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__prestate_diff.snap @@ -0,0 +1,16 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&traced.prestate(true)" +--- +{ + "post": { + "0x0000000000000000000000000000000000400000": { + "nonce": 1 + } + }, + "pre": { + "0x0000000000000000000000000000000000400000": { + "balance": "0x38d7ea4c68000" + } + } +} diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__struct_logs.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__struct_logs.snap new file mode 100644 index 000000000..77035f017 --- /dev/null +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__timestamp_detention__struct_logs.snap @@ -0,0 +1,235 @@ +--- +source: crates/mega-evm/tests/tracers/harness.rs +expression: "&redacted(&traced.struct_logs())" +--- +{ + "failed": true, + "gas": "[gas]", + "returnValue": "MegaLimitExceeded(2, [gas])", + "structLogs": [ + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "TIMESTAMP", + "pc": 0, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "POP", + "pc": 1, + "refund": "[gas]", + "stack": [ + "0x6553f100" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMPDEST", + "pc": 2, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "gas": "[gas]", + "gasCost": "[gas]", + "op": "PUSH8", + "pc": 3, + "refund": "[gas]", + "stack": [] + }, + { + "depth": 1, + "error": "Some(OutOfGas)", + "gas": "[gas]", + "gasCost": "[gas]", + "op": "JUMP", + "pc": 12, + "refund": "[gas]", + "stack": [ + "0x2" + ] + } + ] +} diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index d58520810..a1c80cc18 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -1,35 +1,45 @@ # AGENTS.md ## OVERVIEW -Ethereum execution-specification state-test fixtures and runner adapted for MegaEVM equivalence validation and regression detection. +The execution-spec state-test runner of the Satin engine: Ethereum's fixtures through `MegaEvm` in equivalence mode (a gate) and Satin mode (a report), the witness replay of a fixture's transaction (a gate), and the blockchain tests through Satin's block executor (a gate). Published as `mega-state-test`; the library keeps the `state_test` import name. -The `state-test` CLI (`crates/state-test`) is a thin front-end over this crate. +The `state-test` CLI (`crates/state-test`) is a thin front end over this crate. +`README.md` says what the two modes are and how a test is judged. ## STRUCTURE -- `src/runner.rs`: test discovery, execution pipeline, validation, worker concurrency. -- `src/types/`: forked revm statetest data model and deserializers. -- `src/utils.rs`: root/hash validation helpers and utility glue. -- `tests/`: replay-corpus validation, fixture benches, and dump round-trip tests (rely on `bench/replay/fixtures/`, so they are excluded from the published package). +- `src/runner.rs`: discovery, parallel execution, judging a test, the report, the summary and the gate. +- `src/mode.rs`: the two configurations a test runs under, built from `mega-evm`'s `test_utils::{neutral_cfg, neutralize_evm}`. +- `src/fork.rs`: the fixture forks a run executes (Osaka, Amsterdam). +- `src/exceptions.rs`: validation errors mapped to the execution-spec exception names. +- `src/skips.rs`: the reference runner's skips, with their reasons. +- `src/deviations.rs`: the registry of places Satin differs on purpose, each with the exact entries it explains and the hashes Satin produces for them; `DEVIATIONS.md` is rendered from it. +- `src/roots.rs`: the post-state root and the logs hash. +- `src/blockchain/`: the blockchain tests' gate. `mod.rs`: discovery, judging a test block by block, the report and the gate; `fixture.rs`: the fixture as the runner reads it, every block decoded from its RLP; `chain.rs`: a test's chain imported through `MegaBlockExecutor`, its schedule with every fork at genesis (`chain_spec`), the seven predeploys seeded once into the chain's genesis state, in the shape Rex6 left them, where the fixture's pre-state lacks them (the registry's roles, `registry_roles`, bind nothing), and the accounts the seed and a Satin block add (`SATIN_ACCOUNTS`); `skips.rs`: the classes a test is skipped for, decided from its content. +- `src/witness.rs`: `check_replay`, a fixture entry executed on a recorder of every read and replayed on a strict database and environments serving exactly a witness: the record of every read, and, for an entry the engine executed, the channel witness a node builds; `Replayed` says which. +- `tests/runner.rs`: the runner on fixtures written in the test, filled from revm's mainnet EVM on the fixture's fork. +- `tests/blockchain.rs`: the blockchain runner on chains written in the test, filled block by block from revm's mainnet EVM on Osaka, the pre-block system calls included. +- `tests/witness.rs`: `check_replay` on two fixtures written in the test, an executed one and a rejected one, and on the execution-spec fixtures `MEGA_STATE_TEST_FIXTURES` names (always ignored by default: it runs only with `-- --ignored` and the variable set; `.github/workflows/exec-spec-satin.yml` runs it on every file of both releases in both modes). + +The fixture types are the revm fork's own (`revm::statetest_types`, the `test-types` feature), re-exported as `state_test::types`. ## KEY PATTERNS -- Runner forces MegaEVM compatibility assumptions from this crate's adaptation layer. -- Expected-exception handling and output/root validation are centralized in `runner.rs`. -- Known slow/problematic vectors are explicitly skipped by filename list. -- Failure debugging path can re-run with tracer context for inspection. -- Parallel execution uses shared queue and atomic counters with optional single-thread mode. -- BaseFeeVault state changes are pruned as MegaETH-specific normalization. -- The SALT bucket hasher comes from `mega_evm::AHashBucketHasher` (via the `test-utils` feature); never introduce a standalone salt/hasher dependency. +- A fixture's expectation is Ethereum's; a test here that needs one fills it from revm's mainnet EVM, never from `MegaEvm`. +- Every failure is a `FailureKind`; equivalence mode names the deviation that explains it, and one it does not name is unattributed. +- A deviation lists the exact entries it explains — file, test, data, gas and value indices — with the hashes Satin produces; a failure is its only with those hashes, and `--expect-deviations` requires every listed entry to fail exactly as listed. +- Skips mirror the reference runner's, so the executed and skipped counts equal the ones `.github/workflows/exec-spec.yml` pins for it. +- A blockchain test is skipped only for a class decided from its content (`src/blockchain/skips.rs`); a block that differs passes only when a deviation the registry already has lists that test and block with exactly the outcome Satin produces, and the chain is imported on from Satin's state, so a listed block exempts no later one. +- An account is taken out of a blockchain test's state root only by `SATIN_ACCOUNTS`, only when the pre-state does not hold it and it holds exactly what the seed or a Satin block put there. ## ANTI-PATTERNS -- Do not spread exception matching logic across multiple files. -- Keep it centralized to avoid drift. -- Do not bypass `compute_test_roots` when changing validation outputs. -- Do not add ad-hoc skip conditions outside `skip_test`. -- Keep skip reasons documented in-place by filename. +- Do not accept any error for an expected exception; map the error in `src/exceptions.rs`. +- Do not register a deviation for a failure that is a bug; a deviation is a rule Satin keeps on purpose, with its reason. +- Do not skip a test to make the gate pass; a skip is one the reference runner makes too. +- Do not reach an engine switch from here; the neutral configuration lives in `mega-evm` behind `test-utils`. ## WHERE TO LOOK -- Add/adjust skip policy: `runner.rs::skip_test`. -- Change validation semantics for roots/output/exception: `runner.rs::{validate_exception,validate_output,check_evm_execution}`. -- Change worker behavior or fail-fast policy: `runner.rs::{run_test_worker,run,TestRunnerConfig}`. -- Update JSON schema mapping for test fixtures: `src/types/*` and deserializer modules. -- Change CLI flags or path handling: `crates/state-test/src/main.rs`. +- Add or move a deviation: `src/deviations.rs`, its entries taken from a `--json-outcome` run, then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +- Change what a mode configures: `src/mode.rs`, and `mega-evm`'s `src/test_utils/neutral.rs`. +- Change how a test is judged: `src/runner.rs::check`, `src/exceptions.rs`. +- Change how a blockchain test is judged: `src/blockchain/mod.rs`; its skips: `src/blockchain/skips.rs`; what is taken out of its state root: `src/blockchain/chain.rs`. +- Add a blockchain test to a deviation: its `blockchain_entries`, every differing block taken from a `state-test btest --json-outcome` run (a failure's `differing` lists them all, the chain imported to its end), then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +- Change the pinned executed and skipped counts: `.github/workflows/exec-spec-satin.yml`. diff --git a/crates/mega-state-test/Cargo.toml b/crates/mega-state-test/Cargo.toml index 7c917ae4d..2aa2624aa 100644 --- a/crates/mega-state-test/Cargo.toml +++ b/crates/mega-state-test/Cargo.toml @@ -6,10 +6,8 @@ rust-version.workspace = true license.workspace = true homepage.workspace = true repository.workspace = true -description = "Self-contained EEST-compatible state-test fixtures and runner for mega-evm" -# The integration tests read fixtures from `bench/replay/fixtures/`, which is -# outside this crate directory and thus absent from the published package. -exclude = ["tests/"] +description = "Execution-spec state-test runner for the mega-evm Satin engine" +readme = "README.md" [lints] workspace = true @@ -17,25 +15,28 @@ workspace = true [dependencies] mega-evm = { workspace = true, features = ["default", "test-utils"] } +# revm +# `test-types` brings the fork's own state-test fixture types, the ones its runner reads. +revm = { workspace = true, features = ["std", "test-types", "tracer"] } + # alloy -alloy-eips = { workspace = true, features = ["serde"] } -alloy-primitives.workspace = true -alloy-rlp.workspace = true -alloy-serde.workspace = true +alloy-rlp = { workspace = true, features = ["std"] } +alloy-trie = { workspace = true, features = ["std", "ethereum"] } # misc -hash-db.workspace = true -indicatif.workspace = true -k256.workspace = true -plain_hasher.workspace = true -serde.workspace = true -serde_json.workspace = true -thiserror.workspace = true -triehash.workspace = true +serde = { workspace = true, features = ["derive", "std"] } +serde_json = { workspace = true, features = ["raw_value", "std"] } +thiserror = { workspace = true, features = ["std"] } walkdir.workspace = true -# Published as `mega-state-test`; the library keeps the `state_test` import name -# so the `state-test` CLI and the mega-evme / mega-t8n consumers are unaffected. +[dev-dependencies] +# alloy +alloy-eips.workspace = true + +# misc +tempfile.workspace = true + +# Published as `mega-state-test`; the library keeps the `state_test` import name. [lib] name = "state_test" path = "src/lib.rs" diff --git a/crates/mega-state-test/DEVIATIONS.md b/crates/mega-state-test/DEVIATIONS.md new file mode 100644 index 000000000..aff8790d1 --- /dev/null +++ b/crates/mega-state-test/DEVIATIONS.md @@ -0,0 +1,140 @@ +# Deviations + + + +The places Satin differs from Ethereum on purpose that the execution-spec gate meets, each with the fixture entries it explains and the hashes Satin produces for them. +In equivalence mode a failure is a deviation's only when the deviation lists its entry with the hashes it produced, and every listed entry must fail exactly as listed: a failure no deviation explains, and a listed entry that passes or fails another way, fail the gate. + +## `amsterdam-opcodes-on-osaka` + +2 failed entries of the pinned Osaka fixtures. + +**Rule.** +Satin runs DUPN, SWAPN and EXCHANGE (EIP-8024) and SLOTNUM (EIP-7843), which its Osaka base leaves undefined. + +**Reason.** +Satin takes the Amsterdam schedule and the opcodes with it. +The instruction table is Satin's machinery, which equivalence mode keeps, so an Osaka fixture that executes one of the four bytes, expecting the undefined-opcode halt Osaka gives it, runs the opcode instead. +With the four entries taken back out of the table, every Osaka fixture passes. + +**Failures.** Each entry with its data, gas and value indices, how it fails and the hashes Satin produces; paths are relative to the release's `state_tests` directory. + +- `frontier/opcodes/test_all_opcodes.json` + - `tests/frontier/opcodes/test_all_opcodes.py::test_all_opcodes[fork_Osaka-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x2790bb00bde351feb12b3607acea67097e9f7d0a3913d61c7269c3603a77b8c5` +- `static/state_tests/stBadOpcode/undefinedOpcodeFirstByte.json` + - `tests/static/state_tests/stBadOpcode/undefinedOpcodeFirstByteFiller.yml::undefinedOpcodeFirstByte[fork_Osaka-state_test-]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xefc47fa41b70e7a1b1aa1ac3c0b04af29ccb2ed2f766fe42ff764e1f3b9fe0de` + +**Blockchain tests.** 3 tests of the pinned main release's `blockchain_tests`, each with every block whose outcome is not its header's — the gas used, the keccak hash of the logs bloom, the receipts root and the state root Satin produces for it, and why it differs — and how the chain ends; every other block of the test matches its header, and paths are relative to the release's `blockchain_tests` directory. + +- `frontier/opcodes/test_all_opcodes.json` + - `tests/frontier/opcodes/test_all_opcodes.py::test_all_opcodes[fork_Osaka-blockchain_test_from_state_test]` + - block 0 (the rule acts): gas used 8129268, logs bloom hash `0xbe67c3e27ea8993a93e1784dfad43146e9c48f71d7d56dfd86d6c1041920b232`, receipts root `0xa8efe1faeb804a16183cc48903e6d13ed9c9786bfb146708b605feb6448bdd93`, state root `0x311f0607743b16ef7eb341125d364a002eaceb2f05ac936bbd0f839865d2711d` + - End: the chain ends on a state a listed block left; its head is compared and its post-state is not: its one block runs the four opcodes Osaka halts on, so the chain ends on the state they leave. +- `frontier/scenarios/test_scenarios.json` + - `tests/frontier/scenarios/test_scenarios.py::test_scenarios[fork_Osaka-blockchain_test-test_program_program_INVALID-debug]` + - block 0 (the rule acts): gas used 5386221, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf`, state root `0x50cc3c920ca4d635bb156978614d544911917dda2314da86c6ae47f86d8668ff` + - block 1 (the rule acts): gas used 5386221, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf`, state root `0x7a432172471d48e4eabea2f6f7843ae1dc13ba9db35ebb90ea7b71e2797381b8` + - block 2 (the rule acts): gas used 5386224, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xc8a1e306c05c6c22dcc04fb01dd3e84c3ba16088eccf053cfa10c07d1d604c89`, state root `0x6492319287311df06e117d1bf0167868072f0ec0522a168cbae279e88f6edeb5` + - block 3 (the rule acts): gas used 5386224, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xc8a1e306c05c6c22dcc04fb01dd3e84c3ba16088eccf053cfa10c07d1d604c89`, state root `0x8b428b568632e6056542468c6fc7ed031c32db3a7b7286b04285b6e735c30a53` + - block 4 (the rule acts): gas used 5376889, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x44b3958d3a4da284d93cd9413fdd02affc4fa0d2c2ae0dd4e08c98a38d7a6504`, state root `0xfa2a2f0e8f686cc0f5d1bf7d01f6048c17795b0d6f8c319816742ada3d5353ed` + - block 5 (the rule acts): gas used 5386221, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf`, state root `0xd76637032c7aba3c937f7fbe047a1bc277dccd78377e63681570ebeb239ab721` + - block 6 (the rule acts): gas used 5386221, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf`, state root `0xc4217d76247c681511a0c3e6b7bb5712fc08c8e08f8d666992cb24d40ab3b7e5` + - block 7 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0x150535f0c70945d4025bbd207f255412568187ff74ec5c4f068a6c3159a1b215` + - block 8 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0xca8b4f50f5ee3e3b992db528da9cf18d3495161478583903f26d7c58590c434b` + - block 9 (the rule acts): gas used 5376889, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x44b3958d3a4da284d93cd9413fdd02affc4fa0d2c2ae0dd4e08c98a38d7a6504`, state root `0x32c1d16829c873e7f9762e026d6d9e7f007aedf4b96c60a7a774d70cf68652ab` + - block 10 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0x3c04b7a4296b76ee622d099c6a7e5195cf9884f4e005a452dc24f431fe8679ca` + - block 11 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0x3c2819d923e552d459a255be2e68e04210cac0b31ca3fb45bce60b5ff9cfdfcd` + - block 12 (the rule acts): gas used 5399627, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26`, state root `0x8646405e196a3332ee3bb75af4cb1ba7f0c51c646c1f74fe88193f9971d27019` + - block 13 (the rule acts): gas used 5399627, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26`, state root `0xc95eee62b72c78d47f25497acb8715f3ed6c6b1ef1cf48fc5810bef03c87d26e` + - block 14 (the rule acts): gas used 5383592, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x1b4b33d4f2db7ecb0071a2ed95938ca5bf97df8c4c259c1b1542ee79cfad93b4`, state root `0x4f98fc50f394e6a3264df2c21dc77d9d0f0134b741f1faf42654ed1e9b3e2ea9` + - block 15 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0x1ee283e5862adf81f60e3cef87613b7f7dc02b3eef325e2246a212e24ad439bc` + - block 16 (the rule acts): gas used 5392924, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344`, state root `0xf72728582c1345a0b218adf1baa60e68cfa6d1bb9f16fb3d9c83be03d277f9b4` + - block 17 (the rule acts): gas used 5399627, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26`, state root `0xc9b1b1e13a3ae1a8640ca3204c1bcb5b82dcc01a75135105ad2ad43629708305` + - block 18 (the rule acts): gas used 5399627, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26`, state root `0xe5521ec635fa43963276146cd72c55fcd3119123c1fdbab42667de6c76b6b86b` + - block 19 (the rule acts): gas used 5383592, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x1b4b33d4f2db7ecb0071a2ed95938ca5bf97df8c4c259c1b1542ee79cfad93b4`, state root `0x7ca5f100fa3a11694d1fb64a2c57359f2bc60aa9f492413dd47c93936d2efb10` + - block 20 (the rule acts): gas used 5412989, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xa22daee9f564b06c805a9b32ba0f6b26e267388fe3bd24de782c7a8e3bd3200c`, state root `0xd70438c04dd69c9d1c2450a8f719e89c530aa86da49e4f1de4806b6d5219113a` + - block 21 (the rule acts): gas used 5412974, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x02e92ec835e38ac88ac8bb94790955bf8aadc3d53b34733e4fa77fd18bda5f82`, state root `0x7e69c5919cf9e7a663ccc53d78b3dd11128f65809862a53a58d12c12dfec4d50` + - block 22 (the rule acts): gas used 5425218, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xae1970250c7686623887a6629c3b89de2107591e74db05483e6cfa549d83721d`, state root `0x3d2e7d5f919008960dc9043f0aff0fcd960c6324d07900feb6be5d7829c9e25d` + - block 23 (the rule acts): gas used 5425218, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xae1970250c7686623887a6629c3b89de2107591e74db05483e6cfa549d83721d`, state root `0xc76d312ba2294d1e2a2e4744c47948d97e23effc4f884f6afe2d92c56971d00c` + - block 24 (the rule acts): gas used 5431921, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x80d1b6b1cc4c436be347448203fe33fb20a10269a969d4d7584607e81e20a523`, state root `0x9795b537f1c4a81c45ecbd68cd6a768f1edf4851c1af2f58dd36df2ce990a60c` + - block 25 (the rule acts): gas used 5431921, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x80d1b6b1cc4c436be347448203fe33fb20a10269a969d4d7584607e81e20a523`, state root `0xd520334239c6aca8938bcc6000730ab1d092abb057e8a9e9d48bec67d09b561d` + - block 26 (the rule acts): gas used 5425197, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x4592127747c3ae6dcf115d65b2cce745607a8318fe7f8e664e0555193ffb7e56`, state root `0x68bd60a5015b88c0b8e7e185f8be77cfdb27cd5589f1f215d98b7678bc414d76` + - block 27 (the rule acts): gas used 5425197, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x4592127747c3ae6dcf115d65b2cce745607a8318fe7f8e664e0555193ffb7e56`, state root `0x7dd74978b8093b1e70baf3100ae39040303bcda411a13beec70e22ee72a29833` + - block 28 (the rule acts): gas used 5431900, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x95c628e38ba7c4cfe057b1f25eabf4839e440366a6ac77af656eb6e613363a1d`, state root `0x757f6d279391869cc5645519509c639664976d262443f14c260ea0dd6555a9bc` + - block 29 (the rule acts): gas used 5431900, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x95c628e38ba7c4cfe057b1f25eabf4839e440366a6ac77af656eb6e613363a1d`, state root `0x112f123f5e1e6bb8b62435629d05b78b41241e7cad87f164fdfc5251514fdaab` + - block 30 (the rule acts): gas used 5354342, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x77d8bb582b975327486b5eaf11eefab2c24f4d7eea18a068393a0bf07fe4a12f`, state root `0xdd0f896ef11e7b76ca47798934817924b7ff6d4f69a6332dc58479a91bed4bae` + - block 31 (the state block 30 left): gas used 6996648, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x11e83acea62ae5fa281bbc0e08cbb0e8096b6639aa23b482e09be96b634478d1`, state root `0x62884511e634038fe0d74ba175861b715288e3f0f22ef2d833e90308b3d692e7` + - block 32 (the rule acts): gas used 5374242, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x49e5cee7b540b0aa0c1da72b0f14ce1c6f0462b9a5d912dc2d07f025d9703c47`, state root `0x50aa0f67eadbc50b215297d51f9963dab59f8820c0f5175eb236bc6a58eab823` + - block 33 (the rule acts): gas used 10692884, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x11f8bdf99c03a9e5a4434febe2b60a3d448beea5a90859e9aeaf64f1a7f39aa9`, state root `0x42f64807cbdc63fd10bff15150e7d7a6a49d74706107891f9ef43c3b81573473` + - block 34 (the rule acts): gas used 10742872, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xb46d2b23868948b3dca1ee22d01e7555454b3299a9b46938b0468425524b6d62`, state root `0x6124ecf0c28fafaf690def9ad816ed272a9111021599e3ffb0dcf12174de6682` + - block 35 (the rule acts): gas used 10692890, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xc23d5fbdb417f4a15b3c25cb25d1aa377be4e3534f218c075e24a27fcffc6e41`, state root `0xf9001fb3d1ba34652291e969f128d8ad39018e0addaae5b73c84184e4add58b8` + - block 36 (the rule acts): gas used 10692890, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0xc23d5fbdb417f4a15b3c25cb25d1aa377be4e3534f218c075e24a27fcffc6e41`, state root `0xba79f738e1ded0240a5c87b6ee54daa4e0352b497af0ae1886df1234dbfd47e3` + - End: the chain ends on a state a listed block left; its head is compared and its post-state is not: every block runs the program's four opcodes Osaka halts on or carries the state they left, so the chain ends on that state. +- `static/state_tests/stBadOpcode/undefinedOpcodeFirstByte.json` + - `tests/static/state_tests/stBadOpcode/undefinedOpcodeFirstByteFiller.yml::undefinedOpcodeFirstByte[fork_Osaka-blockchain_test_from_state_test-]` + - block 0 (the rule acts): gas used 3969244, logs bloom hash `0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5`, receipts root `0x9a8f3b88fe2bb353fe86d44bd5be426458c3544f423b8e70f0dff0a06c9634bc`, state root `0xa1527ad75667d1f7455aa215c374f3c21c9fde318ec9fb652ee9c8fac11dc72b` + - End: the chain ends on a state a listed block left; its head is compared and its post-state is not: its one block runs the four opcodes Osaka halts on, so the chain ends on the state they leave. + +## `selfdestruct-burns-on-osaka` + +37 failed entries of the pinned Amsterdam fixtures. + +**Rule.** +A contract self-destructed in the transaction that created it is removed as on Satin's Osaka base, a balance it sent to itself burned: EIP-8246, which keeps that balance and clears the account only at the end of the transaction, is not active. + +**Reason.** +revm gates EIP-8246 on the Amsterdam spec id, in the journal, and Satin's spec runs on Karst, an Osaka base: Satin takes Amsterdam's rules one switch at a time — EIP-8037, EIP-2780, the opcodes — and EIP-8246 has no switch, so no configuration can turn it on. +An Amsterdam fixture in which a contract destructs to itself expects the balance kept, and the EIP-7708 transfer logs a kept balance produces when it is sent on. +revm itself, on an Osaka base with Amsterdam's configuration, produces exactly the hashes listed for every one of these entries, and the fixtures' own on the Amsterdam spec. +Whether Satin takes EIP-8246 is a decision for its specification, not for this gate. + +**Failures.** Each entry with its data, gas and value indices, how it fails and the hashes Satin produces; paths are relative to the release's `state_tests` directory. + +- `for_amsterdam/amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json` + - `tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_top_frame_charges.py::test_initcode_selfdestruct_keeps_top_frame_state_charge[fork_Amsterdam-state_test-non-zero_value-self_beneficiary]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x8a227aa6adf983ba803d01b09126eb9d226cf95a1e083f194c39f0e29e8a1e44` +- `for_amsterdam/amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json` + - `tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_call.py::test_call_value_to_self_destructed_same_tx_account[fork_Amsterdam-state_test-create2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x5857f66aee23a75fbc2b874e871eb146226ff2dab2194b4597cb87b9b954347c` + - `tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_call.py::test_call_value_to_self_destructed_same_tx_account[fork_Amsterdam-state_test-create]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x13370ccc6e5eb2bf5a75774bef80223d973990a429e9a3a6e2abe32eea70d091` +- `for_amsterdam/amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json` + - `tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_selfdestruct.py::test_selfdestruct_to_self_in_create_tx[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xd1e99d8e4322d56db48a9c6fbf91231d405a592394fe30943639d7bb8e4af3e9` +- `for_amsterdam/amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json` + - `tests/amsterdam/eip8038_state_access_gas_cost_increase/test_selfdestruct_gas.py::test_same_tx_created_selfdestruct_self_burn[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x60ec6fdd1f4b9afbf1f6bae43abbc3a21fc917cf921bc7f43827d2dda86f411b` +- `for_amsterdam/amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json` + - `tests/amsterdam/eip8246_selfdestruct_no_burn/test_selfdestruct_no_burn.py::test_create_transaction_initcode_selfdestruct[fork_Amsterdam-state_test-kept]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x8a227aa6adf983ba803d01b09126eb9d226cf95a1e083f194c39f0e29e8a1e44` +- `for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE2]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x5c00fce098c2fe994de7c23a67990d729c20a258651d132e2b21c3a2d0b5803a`, state root `0x2f2356140f67ac4504ff5f416e56edd0264e8ec19ed39ac6f8897b9023d27307` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x6aa38fb5b844e13cd8efa6b776f957550e0a4b27815a2f34cf3fa9bc4cae730e`, state root `0xf08b417e5ac7138f3e58e07dc90970a2780901935979e0a3010ba8ebe5aae924` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE2]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0xc6f151ee88a456efe8faee5993fac962f32645dd408bdf75e86a411e4d2b5b35`, state root `0xd42fe0ac1ad09661381fc6c43ee67a7c169bcb4610e89ec0c60aaa793d8831c4` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0xf76e4fa7500c4db34112ba382a1365e5503307c1ae300be79fa59550ba4eef32`, state root `0x9903a0c8f461940cadd5f48ea90bddfe1f019182c65d3f6a6b2533d336199063` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x2c2102d3296f1610fdf87d1182226cd4e793882caa71c96f965f0e5e7af21590` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x7cb1c8d882ce555bf85cff9961ebde8c14542d96d2394935edbf95b745c5265f` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_single_self_recipient-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xa695e4f522a7e47293590084faa0dc45ab419b7c0a2449808fd7e2a716968c80` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_single_self_recipient-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x97844214d20796ee78c52c1d5a6338e21dfa8bdf6031a19cc359b9c46d5da076` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE2]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x5c00fce098c2fe994de7c23a67990d729c20a258651d132e2b21c3a2d0b5803a`, state root `0x7db1f7e8a7499e52962e8b457cbaa28545b035ec6d3491621ad8a10f0abcfec4` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x6aa38fb5b844e13cd8efa6b776f957550e0a4b27815a2f34cf3fa9bc4cae730e`, state root `0x7ae7c17d34642ed4d4a56e2613cc50ab5eeb617b5b2c965f946de58060b99447` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE2]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x79545168c90d8fed276adcd2bfe3610a0ba259044ba117fb9cafb0bcbbf3a3df`, state root `0x4f389b292dedd1e7effa9c1947e9ec9fb83a40f049f9cf4b87262e1d96c9682a` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x7c73347bddfb53f07057096e6949c82c32d3fb61532a008261cbf1bf43fcd19e`, state root `0x254f07b354bf3e97b96e4a06ddee51489ca23a71fb6e088df9f460c35d880698` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self-create_opcode_CREATE2]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x4bd3e188f8d440a5762a67eb84a9d133a6e2979fb68d7414b1e0a08bcee83d48`, state root `0x807ff3a9c69267c578eae95089ba8087582eb630fe514aae537500b9edbcf880` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self-create_opcode_CREATE]` d=0 g=0 v=0: `logs-mismatch`, logs hash `0x88bd5130a835f0eb5cce6c8229e768ae96dec7a79cd757dca32b5e3ce57b86b0`, state root `0xe331c545e628b14d64deccaac85755e699f0e75aba8189847ed810e4a4f0ddf8` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xfbd1f3e7d906012db567e5429e1236dab7466d40798973c4dc4ba2984d621f72` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xd75f439c744aae2d05d0151919fa298073b99086c3af81087202b5c4464b2a02` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_single_self_recipient-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x1c0a70089f50f9da9183fa04210ae0f04affc03d146fcb78d32f3c5ef2853a47` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_single_self_recipient-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x0c7614fbae22b3855669bfe3ee994bc18b31b32d84903a0372834f966a265b8d` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-single_call_self-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xaa95dfb767c86d4d4c261252b2a6224f32d15955eaf92650c4c97bb5c7892d95` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-single_call_self-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x9c91de53b0bc52572ca1c1ea6ccffcf42f725876a8f439ae676b7cdf9567d43a` +- `for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-call_times_2-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xdc78c509c41771960af990fbbcf5dbd0e6f72e8a6615bcb5cc1b75c8f12dc0bd` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-call_times_2-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x8eda22cdda403dd638ac173e1e6e648414d1d20aa8559e3a26af76939eda5d4b` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-call_times_2-create_opcode_CREATE2]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x998432460e11445f1529c1fde7e70e3c97818e9af0d2b3180e2329bd719d5e4c` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-call_times_2-create_opcode_CREATE]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x6989f4cf277b4f10675e678976e0ffde965e2d23634946b31f42e61b948fe31f` +- `for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json` + - `tests/cancun/eip6780_selfdestruct/test_selfdestruct_revert.py::test_selfdestruct_created_in_same_tx_with_revert[fork_Amsterdam-state_test-outer_selfdestruct_before_inner_call-same_tx]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x68de4499d08d8c9e6260ade80ed6a4203630f49dc1947b2312d308a7fd104e40` +- `for_amsterdam/frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json` + - `tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_False]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x723798b921cd0f3a700aa00dffcb87da7df2440def96d3ed96b36e2bc0a1e545` + - `tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_True]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xd82f53b114fbab4d8784e89069ef7b272e1d74f2cc26a363f96141b9eb771b6c` + - `tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE2-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_False]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x52695eb8bf3c83b205d4cfd24acb88af856a2db2ec5236e66202833d8aa94f3c` +- `for_amsterdam/ported_static/stCreate2/create2_suicide/create2_suicide.json` + - `tests/ported_static/stCreate2/test_create2_suicide.py::test_create2_suicide[fork_Amsterdam-state_test-d6]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xe6d927efd83aabb7d94664d06b79744a361a74374f377f6c8dd31307e577ccde` + - `tests/ported_static/stCreate2/test_create2_suicide.py::test_create2_suicide[fork_Amsterdam-state_test-d7]` d=0 g=0 v=0: `state-root-mismatch`, state root `0x087df75fad91a65e75b9373ad835882429c431166f9a3e6d086206cd39e2f662` +- `for_amsterdam/ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json` + - `tests/ported_static/stInitCodeTest/test_transaction_create_suicide_in_initcode.py::test_transaction_create_suicide_in_initcode[fork_Amsterdam-state_test]` d=0 g=0 v=0: `state-root-mismatch`, state root `0xf6456935a8fdccc4fa60c10233d27e602088fdfbce68c9db41363767cffd367d` diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md new file mode 100644 index 000000000..18bc0aa3f --- /dev/null +++ b/crates/mega-state-test/README.md @@ -0,0 +1,144 @@ +# mega-state-test + +The execution-spec state-test runner of the Satin engine. +It runs Ethereum's execution-spec state-test fixtures through `MegaEvm`; the `state-test` CLI (`crates/state-test`) is its front end. +The library keeps the `state_test` import name. +It also imports the execution-spec blockchain tests through Satin's block executor ([Blockchain tests](#blockchain-tests)). + +## Two modes + +- **Equivalence** — a gate. + Satin's machinery (its handler, frame lifecycle, Host and instruction table) runs priced as the fixture's own fork prices it, with every dimension of pricing only MegaETH has turned off. + Every test either passes, is skipped for a reason the reference runner shares, or fails on a [registered deviation](DEVIATIONS.md); one failure no deviation explains fails the gate. +- **Satin** — a report. + The same fixtures under Satin's own configuration, counted by outcome. + Satin prices state and history on purpose, prices state access as Amsterdam does (EIP-8038), and logs every value movement (EIP-7708) where Osaka's fixtures log none, so almost every stateful fixture differs; the count is what CI shows, and it never fails the job. + +A run executes the entries one fork defines: Osaka's in the main fixture release, Amsterdam's in the glamsterdam devnet release. +Satin's base spec is Osaka, so those are the two forks it can be configured to. + +## The neutral configuration + +Equivalence mode is built from test tooling in `mega-evm`, behind its `test-utils` feature, and unreachable from a default build: + +- `MegaContext::with_neutral_cfg` takes every configuration field as given, the ones the Satin spec fixes included, and prices no history gas for any transaction. +- `test_utils::neutral_cfg(fork)` is that configuration for Osaka or Amsterdam: the fork's gas schedule, its EIP-8037, EIP-2780 and EIP-7708 switches, EIP-7825's execution cap and its code-size limits. +- `test_utils::neutralize_evm(evm, fork)` gives the EVM the two parts of the fork's pricing it carries: Ethereum's precompile set for the fork, not op-revm's Karst set with MegaETH's KZG price, and the fork's static opcode prices. +- SALT pricing needs nothing: without a SALT environment every bucket is minimal. +- The runtime limits are MegaETH's, so equivalence mode installs `EvmTxRuntimeLimits::no_limits()` itself rather than rely on the engine's default. + +What stays Satin's is the machinery, and with it two rules no configuration can change: the instruction table's Amsterdam opcodes, and the rules revm gates on the spec id, which is Osaka's. +Both are in the registry. + +## How a test is judged + +As the revm fork's reference runner judges it, and more strictly where that runner is lenient: + +- the post-state root and the logs hash for a transaction that executes; +- for one the fixture expects to be rejected, the exception it names, not any error, and the pre-state left as it was (`src/exceptions.rs` maps each validation error to the names that describe it); +- an expected output must be produced, not merely not contradicted; +- a fixture value that does not fit its width is a failure, not a value clamped to fit; +- a test name that appears twice in a file fails the file, rather than one test replacing the other. + +Base fees go to Optimism's base-fee vault on Satin, where Ethereum burns them. +The runner takes the vault back out of the post-state only when the fee routing made it: the pre-state has no vault, and the vault holds exactly the base fee of the gas the transaction used. + +The runner skips what the reference runner skips (`src/skips.rs`), for the same reasons: the EIP-7610 collision fixtures with storage, which revm cannot see, and a transaction that cannot be built when the fixture expects it to be invalid — here only when the fixture names the reason it cannot be, an invalid signature or a blob or EIP-7702 transaction without a recipient. +So the two runners execute the same population, and the executed and skipped counts equal the reference runner's. + +## Running it + +```bash +# The fixture releases the revm fork's `scripts/run-tests.sh` names at the pinned tag. +cargo run --release -p state-test -- --fork Osaka
/state_tests +cargo run --release -p state-test -- --fork Amsterdam /state_tests +cargo run --release -p state-test -- --mode satin --fork Osaka
/state_tests +``` + +`--expect-executed`, `--expect-skipped` and `--expect-deviations` turn a full run into the pinned gate CI runs (`.github/workflows/exec-spec-satin.yml`). +`--json-outcome` prints one JSON line per test, a failure's produced hashes included, and `--trace` runs each test under an EIP-3155 tracer. + +## Blockchain tests + +`state-test btest` imports the execution-spec blockchain tests through Satin's block executor (`src/blockchain/`): the tests of the main release's `blockchain_tests` filled for Osaka, the release and the network the state-test gate's Osaka run uses. +The devnet release's blockchain tests are not run, as the revm fork's own runner does not run them. +A blockchain test is a chain: a pre-state, a genesis block, and blocks a node imports one after the other, several transactions to a block and several blocks to a test, some of which it must refuse. + +### How a block is imported + +Every block is decoded from its RLP, as a node receives it, and runs through `MegaBlockExecutor` on `MegaEvm` in equivalence mode's configuration — the neutral Osaka configuration, the fork's precompile set and static opcode prices — over a copy of the state the chain holds. +The executor makes the EIP-2935 and EIP-4788 pre-block system calls before the transactions, as it does for every block; `BLOCKHASH` reads the hashes of the chain's own blocks. +Satin runs on a chain that holds its predeploys — the six `MegaETH` system contracts and the EIP-7997 factory — and deploys none of them, so the runner seeds each one the fixture's pre-state lacks into the chain's genesis state, as a chain that ran Rex6 holds it, the `SequencerRegistry` naming roles that promote no fixture's transaction (`blockchain::registry_roles`). +The runner holds the blocks to no protocol limit in place of Satin's, through the executor's test-and-tool override, as equivalence mode holds a state test's transaction to none. +Each block is told whether it admits only deposits, and whether Satin activates in it, as a node works them out, from the schedule (`blockchain::chain_spec`) and its parent's timestamp; the schedule activates every fork at genesis, so no block the runner imports is either. + +### How a block is judged + +- A block the fixture expects to be valid must be accepted, and must produce the gas used, logs bloom, receipts root and state root its header carries. +- A block the fixture expects to be invalid for a `TransactionException` must be refused for one of the exceptions it names (`src/exceptions.rs`), not for any error, and leaves the chain at the previous block. +- Once every block is imported, the chain must end at the fixture's last block, holding the fixture's post-state. + +A receipt of an OP transaction that is not a deposit encodes as an Ethereum receipt, so the receipts root is Ethereum's. + +The runner and a Satin block add accounts to the state an Ethereum block leaves, and the runner takes them out of the post-state before computing its root (`blockchain::SATIN_ACCOUNTS`): + +- the seven predeploys the runner seeds: the six `MegaETH` system contracts and the EIP-7997 factory, each taken out when it holds exactly what the seed wrote — the code, the nonce, the storage and no balance; +- OP's base-fee vault, which holds the base fee Ethereum burns, taken out when it holds exactly the base fees of the blocks the chain accepted; +- OP's L1-fee and operator-fee vaults, credited nothing under the neutral configuration, taken out when they hold nothing. + +An account on the list is taken out only when the fixture's pre-state does not hold it. +Any other account that differs, and an account on the list that holds anything else, moves the root, and the block fails. + +### Skips + +A test is skipped only for a class decided from its content before anything runs, never from how it fares, and each class is counted apart; the printed summary and the JSON summary (`skip_reasons`) give each class's reason beside its count: + +- `withdrawals`: a block carries withdrawals, which an OP chain does not process; +- `blob-transactions`: a block carries a blob transaction, or expects an exception only a blob transaction raises; an OP chain has no blob transactions; +- `requests`: the test is an EIP-7002, EIP-7251 or EIP-7685 request test, or a block expects an exception about requests; an OP chain makes no requests and no post-block system call; +- `header-or-body`: a block expects only `BlockException`s for its header or body — its gas limit, base fee, blob gas fields, size, encoding, withdrawals root or hash — a consensus check a node makes before execution; a `BlockException` outside the list is compared, so the executor must refuse the block; +- `undecodable-invalid-transaction`: a block the fixture expects to be invalid carries a transaction an OP block cannot encode — an EIP-7702 transaction without a recipient, or a fee wider than 128 bits — the transactions the state-test gate skips as unbuildable; +- `create-collision-with-storage`: the state-test gate's EIP-7610 files (`src/skips.rs`), whose collisions with storage revm cannot see. + +The EIP-2935 and EIP-4788 tests are not skipped: their system calls are made and compared like everything else. + +### The gate + +A deviation the registry already has may list a test block by block: every block whose outcome is not its header's, with the outcome Satin produces for it — its gas used, the keccak hash of its logs bloom, its receipts root and its state root — and why it differs: the deviation's rule acts in it, or it runs as on Ethereum and differs only in the state an earlier listed block left. +A block that differs passes only when its test's entry lists that block with exactly that outcome; the chain is imported on from Satin's own state, so every later block is held to its header or to its own listed outcome in turn, and a block that differs and is not listed fails the test. +The chain's head is always compared, and its post-state too when the chain ends on a state its last header describes; when it ends on a state a listed block left, the entry must say so and why. +A listed test that does not deviate exactly as listed fails, and the summary counts the blocks checked against Ethereum — matched or refused as the fixture expects — apart from the blocks matched to a deviation. +`--expect-executed`, `--expect-skipped REASON=N` (every class) and `--expect-deviations` pin a full run, as `.github/workflows/exec-spec-satin.yml` does: + +```bash +cargo run --release -p state-test -- btest
/blockchain_tests --expect-executed \ + --expect-skipped withdrawals= ... --expect-deviations +``` + +### The legacy state tests + +The legacy `GeneralStateTests` are covered through the release's `static/state_tests`: the same tests re-filled for Osaka, which the state-test gate runs as state tests and this gate runs as blockchain tests. +The `ethereum/legacytests` repository holds no Osaka entries, and Satin's neutral configuration exists for Osaka and Amsterdam only. + +## Replaying from a witness + +`witness::check_replay` executes an entry on a database and environments that record every read, then replays it twice on a strict database and environments that serve exactly a witness and refuse everything else: once on the record of every database read, once on the witness a node builds from the transaction's returned state and the engine's exports, with the oracle reads the transaction recorded. +Each replay is held to the first run: the result, the state, the gas by ledger, the usage, the stop, the state changes, and the buckets and block hashes the engine exported. +The replay on the channel witness is the check a stateless validator's witness must pass, run on Ethereum's fixtures; the database-level replay shows the transaction reads nothing outside its database and environments. +An entry the engine rejects replays on the record of every database read alone: it has no returned state to build the channel witness from, and is in no block. +`check_replay` says which witnesses an entry replayed on (`Replayed`), and the fixture test counts the two apart: the entries executed and replayed on both witnesses, and the entries rejected and replayed on the database record alone. +A fixture written into the test always runs, an executed one and a rejected one; the test over the execution-spec fixtures is always ignored by default and runs only with `-- --ignored` (or `--include-ignored`) and `MEGA_STATE_TEST_FIXTURES` set, as `.github/workflows/exec-spec-satin.yml` runs it for every file of both releases in both modes: + +```bash +MEGA_STATE_TEST_FIXTURES=$PWD/
/state_tests cargo test -p mega-state-test --release --test witness -- --ignored +``` + +`MEGA_STATE_TEST_SAMPLE` is how many fixture files to take, spread over the tree (300 unless set, 0 for all), `MEGA_STATE_TEST_FORK` the fork (`Osaka` unless set) and `MEGA_STATE_TEST_MODE` the mode (`satin` unless set). + +## Deviations + +A deviation lists the exact entries it explains: the fixture file (relative to the release's `state_tests` directory), the test, the data, gas and value indices, and the hashes Satin produces — the state root, or for a logs mismatch the logs hash and the state root. +A failure is the deviation's only when its entry is listed and it produced those hashes; any other failure is unattributed, in whatever file it is. +`--expect-deviations` requires every listed entry to fail exactly as listed, so an entry that starts to pass, fails another way or no longer runs fails the gate; the count a deviation explains is derived from its list. + +A deviation added or moved updates `src/deviations.rs`, its entries taken from a `--json-outcome` run, and regenerates [`DEVIATIONS.md`](DEVIATIONS.md) with `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. diff --git a/crates/mega-state-test/src/blockchain/chain.rs b/crates/mega-state-test/src/blockchain/chain.rs new file mode 100644 index 000000000..304f4d636 --- /dev/null +++ b/crates/mega-state-test/src/blockchain/chain.rs @@ -0,0 +1,540 @@ +//! A blockchain test's chain, imported block by block through Satin's block executor. +//! +//! Each block runs through [`MegaBlockExecutor`] — the pre-block system calls, every transaction +//! and the end of the block — on a `MegaEvm` in the neutral configuration of the Osaka fixtures +//! (`Mode::Equivalence`), over a copy of the state the chain holds. A block the executor accepts +//! becomes the chain's head and its state the chain's; a block it refuses is dropped with its copy, +//! so the chain stays at the previous block. +//! +//! Satin runs on a chain that ran the legacy forks, which holds the six system contracts, and OP's +//! EIP-7997 factory, and deploys none of them; the runner seeds each of the seven the fixture's +//! pre-state lacks into the chain's genesis state, once, as such a chain holds them +//! ([`rex6_predeploys`]), the `SequencerRegistry` with roles that bind nothing on an Osaka fixture +//! ([`registry_roles`], which says why). +//! +//! Each block's context tells the executor whether the block admits only deposits and whether +//! Satin activates in it, worked out as a node works them out: from the schedule and the timestamp +//! of the chain's head, the block's parent. Under [`chain_spec`], which activates every fork at +//! genesis, no block the runner imports is either, so no block checks the predeploys. +//! +//! A Satin chain holds accounts an Ethereum chain does not: the seven predeploys, which Satin +//! requires and does not create, so the chain's pre-state holds them; and the fee vaults op-revm +//! routes fees to. [`SATIN_ACCOUNTS`] lists them, each with the rule it is taken out of the +//! post-state by before the root is computed; any other account that differs is a failure. + +use std::collections::{BTreeMap, BTreeSet}; + +use mega_evm::{ + alloy_consensus::transaction::{Recovered, SignerRecoverable}, + alloy_evm::block::{BlockExecutionError, BlockExecutor, BlockValidationError}, + alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder, + alloy_primitives::Bloom, + op_revm::constants::{BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT}, + revm::{ + bytecode::Bytecode, + context::BlockEnv, + database::{CacheState, PlainAccount, State}, + primitives::{keccak256, Address, B256, KECCAK_EMPTY, U256}, + state::AccountInfo, + }, + system::{ + keyless::KEYLESS_DEPLOY_ADDRESS, ACCESS_CONTROL_ADDRESS, CREATE2_FACTORY_ADDRESS, + HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, LIMIT_CONTROL_ADDRESS, MEGA_SYSTEM_ADDRESS, + ORACLE_CONTRACT_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, + }, + test_utils::{rex6_predeploys, SequencerRegistryRoles}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaHardforkConfig, MegaHardforks, + ProtocolLimits, +}; + +use super::fixture::DecodedBlock; +use crate::{ + exceptions, + roots::{logs_bloom, receipts_root, state_root}, + types::blockchain::Account, + Fork, Mode, +}; + +/// The fork whose neutral configuration the blocks run under. +pub const FORK: Fork = Fork::Osaka; + +/// How many of the most recent block hashes `BLOCKHASH` can read. +const BLOCK_HASH_WINDOW: u64 = 256; + +/// Why an account a Satin chain holds is in the post-state, and so what it must hold to be taken +/// out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Added { + /// A predeploy, which Satin requires and neither creates nor upgrades: the chain's pre-state + /// holds it as a chain that ran Rex6 holds it ([`rex6_predeploys`]), the `SequencerRegistry` + /// with the roles of [`registry_roles`]. It is taken out when it holds exactly that: the code, + /// the nonce, the storage, and no balance. + PreState, + /// The vault op-revm credits the base fee to, where Ethereum burns it. It is taken out when it + /// holds exactly the base fees of the blocks the chain accepted, and nothing else. + BaseFeeVault, + /// A vault op-revm credits a fee the neutral configuration prices at nothing — the L1 data fee + /// and the operator fee. It is taken out when it holds nothing; EIP-161 has then already + /// removed it, since crediting nothing touches it. + UnpaidFeeVault, +} + +/// An account a Satin chain holds that an Ethereum chain does not. +#[derive(Clone, Copy, Debug)] +pub struct SatinAccount { + /// Its address. + pub address: Address, + /// Why it is there. + pub added: Added, + /// What puts it there. + pub reason: &'static str, +} + +/// The accounts a Satin chain holds that an Ethereum chain does not: the one its pre-state holds +/// for Satin, and the ones a Satin block adds to the state an Ethereum block leaves. +/// +/// One is taken out of the post-state before its root is computed only when the fixture's +/// pre-state does not hold it — an account the fixture put there is Ethereum's to compare — and +/// only when it holds exactly what Satin put there ([`Added`]). Anything else stays, and the root +/// it moves is a failure. +pub const SATIN_ACCOUNTS: [SatinAccount; 10] = [ + SatinAccount { + address: ORACLE_CONTRACT_ADDRESS, + added: Added::PreState, + reason: "the Oracle, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: HIGH_PRECISION_TIMESTAMP_ORACLE_ADDRESS, + added: Added::PreState, + reason: "the high-precision timestamp oracle, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: KEYLESS_DEPLOY_ADDRESS, + added: Added::PreState, + reason: "KeylessDeploy, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: ACCESS_CONTROL_ADDRESS, + added: Added::PreState, + reason: "MegaAccessControl, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: LIMIT_CONTROL_ADDRESS, + added: Added::PreState, + reason: "MegaLimitControl, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: SEQUENCER_REGISTRY_ADDRESS, + added: Added::PreState, + reason: "the SequencerRegistry, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: CREATE2_FACTORY_ADDRESS, + added: Added::PreState, + reason: "the EIP-7997 factory, a predeploy the chain's pre-state holds", + }, + SatinAccount { + address: BASE_FEE_RECIPIENT, + added: Added::BaseFeeVault, + reason: "OP's base-fee vault: op-revm credits it the base fee Ethereum burns", + }, + SatinAccount { + address: L1_FEE_RECIPIENT, + added: Added::UnpaidFeeVault, + reason: "OP's L1-fee vault: op-revm credits it the L1 data fee, nothing here", + }, + SatinAccount { + address: OPERATOR_FEE_RECIPIENT, + added: Added::UnpaidFeeVault, + reason: "OP's operator-fee vault: op-revm credits it the operator fee, nothing here", + }, +]; + +/// The roles of the `SequencerRegistry` the chain's pre-state holds: [`MEGA_SYSTEM_ADDRESS`] in +/// every one. +/// +/// They bind nothing on a fixture: the registry's system address is the only one whose +/// transactions are promoted, and only a legacy call to one of `MegaETH`'s whitelisted contracts +/// is, which no Ethereum fixture makes; no role change is ever pending, so no block makes the +/// `applyPendingChanges()` call. +pub fn registry_roles() -> SequencerRegistryRoles { + SequencerRegistryRoles::from(MEGA_SYSTEM_ADDRESS) +} + +/// The schedule the blocks run on: every fork active from genesis. +pub fn chain_spec() -> MegaHardforkConfig { + MegaHardforkConfig::default().with_all_activated() +} + +/// The limits the blocks are held to in place of Satin's: none ([`ProtocolLimits::no_limits`]). +/// +/// Equivalence mode takes out what `MegaETH` sets and Ethereum does not, its limits among them, +/// as the gate's state-test runner does (`EvmTxRuntimeLimits::no_limits()`): no data-size limit, +/// per transaction, per frame or per block, and no gas detention. The executor installs the +/// per-transaction half before every transaction, whatever the EVM carried. +pub(crate) fn limits() -> ProtocolLimits { + ProtocolLimits::no_limits() +} + +/// The fixture's `account` as the state holds it: its code hash computed from its code, and its +/// code served by hash, as a node's state serves it. An `AccountInfo` that carried no code would +/// read as an account without any (`AccountInfo::default` carries the empty code). A nonce wider +/// than 64 bits is a fixture error rather than a value clamped to fit. +pub(crate) fn plain_account(account: &Account) -> Result { + let nonce = u64::try_from(account.nonce) + .map_err(|_| format!("nonce {} does not fit a u64", account.nonce))?; + let code_hash = if account.code.is_empty() { KECCAK_EMPTY } else { keccak256(&account.code) }; + Ok(PlainAccount { + info: AccountInfo { + balance: account.balance, + nonce, + code_hash, + code: None, + ..Default::default() + }, + storage: account.storage.iter().map(|(slot, value)| (*slot, *value)).collect(), + }) +} + +/// The root of a state the fixture writes out, such as its post-state. +pub(crate) fn fixture_state_root(accounts: &BTreeMap) -> Result { + let plain = accounts + .iter() + .map(|(address, account)| Ok((*address, plain_account(account)?))) + .collect::, String>>()?; + Ok(state_root(plain.iter().map(|(address, account)| (*address, account)))) +} + +/// What a block the executor accepted produced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BlockOutput { + /// The gas the block used. + pub(crate) gas_used: u64, + /// The root of its receipts. + pub(crate) receipts_root: B256, + /// The bloom of its logs. + pub(crate) logs_bloom: Bloom, + /// The root of the state it left, the accounts Satin added taken out. + pub(crate) state_root: B256, +} + +/// Why the executor, or the node around it, refused a block. +#[derive(Debug)] +pub(crate) struct Refusal { + /// The execution-spec exception names the refusal satisfies, without their prefix; empty for + /// one no name describes. + pub(crate) names: &'static [&'static str], + /// The refusal as the executor reported it. + pub(crate) detail: String, +} + +/// A test's chain: the state its head left, and the hashes `BLOCKHASH` reads. +pub(crate) struct Chain { + /// The state the head block left, the accounts Satin added included. + state: CacheState, + /// The hashes of the chain's blocks, by number. + hashes: BTreeMap, + /// The head block's hash. + pub(crate) head: B256, + /// The head block's timestamp: the parent's of the next block. + head_timestamp: u64, + /// The base fees of the blocks the chain accepted: what the base-fee vault holds. + routed_base_fee: U256, + /// The accounts the fixture's pre-state holds. + pre: BTreeSet
, + /// The chain id. + chain_id: u64, + /// The fraction the blob base fee is updated by. + blob_base_fee_update_fraction: u64, + /// The schedule the blocks run on. + spec: MegaHardforkConfig, +} + +impl Chain { + /// The chain at its genesis block, numbered and hashed `genesis` and stamped + /// `genesis_timestamp`, holding `pre` and every predeploy Satin requires whose address `pre` + /// does not hold ([`Added::PreState`]). + pub(crate) fn new( + pre: &BTreeMap, + genesis: (u64, B256), + genesis_timestamp: u64, + chain_id: u64, + blob_base_fee_update_fraction: u64, + ) -> Result { + let mut state = CacheState::new(); + for (address, account) in pre { + let plain = plain_account(account).map_err(|error| format!("{address}: {error}"))?; + if !account.code.is_empty() { + state + .contracts + .insert(plain.info.code_hash, Bytecode::new_raw(account.code.clone())); + } + state.insert_account_with_storage(*address, plain.info, plain.storage); + } + for (address, info, storage) in rex6_predeploys(registry_roles()) { + if pre.contains_key(&address) { + continue; + } + if let Some(code) = &info.code { + state.contracts.insert(info.code_hash, code.clone()); + } + let storage = storage.into_iter().filter(|(_, value)| !value.is_zero()).collect(); + state.insert_account_with_storage(address, info, storage); + } + Ok(Self { + state, + hashes: BTreeMap::from([genesis]), + head: genesis.1, + head_timestamp: genesis_timestamp, + routed_base_fee: U256::ZERO, + pre: pre.keys().copied().collect(), + chain_id, + blob_base_fee_update_fraction, + spec: chain_spec(), + }) + } + + /// The root of the state the chain holds, the accounts Satin added taken out. + pub(crate) fn state_root(&self) -> B256 { + state_root( + self.state + .trie_account() + .into_iter() + .filter(|(address, account)| !self.added_by_satin(*address, account)), + ) + } + + /// Whether the account at `address` is one a Satin block added, holding exactly what Satin put + /// there. + fn added_by_satin(&self, address: Address, account: &PlainAccount) -> bool { + if self.pre.contains(&address) { + return false; + } + let Some(added) = SATIN_ACCOUNTS.iter().find(|a| a.address == address).map(|a| a.added) + else { + return false; + }; + let storage: BTreeMap<_, _> = + account.storage.iter().filter(|(_, value)| !value.is_zero()).collect(); + let info = &account.info; + match added { + Added::PreState => { + rex6_predeploys(registry_roles()).into_iter().any(|(predeploy, held, slots)| { + let held_storage: BTreeMap<_, _> = slots + .iter() + .filter(|(_, value)| !value.is_zero()) + .map(|(slot, value)| (slot, value)) + .collect(); + predeploy == address && + info.nonce == held.nonce && + info.balance == held.balance && + info.code_hash == held.code_hash && + storage == held_storage + }) + } + Added::BaseFeeVault => { + info.balance == self.routed_base_fee && + info.nonce == 0 && + info.code_hash == KECCAK_EMPTY && + storage.is_empty() + } + Added::UnpaidFeeVault => { + info.balance.is_zero() && + info.nonce == 0 && + info.code_hash == KECCAK_EMPTY && + storage.is_empty() + } + } + } + + /// The environment of `block`, from its header. + fn block_env(&self, block: &DecodedBlock) -> BlockEnv { + let header = &block.header; + let mut env = BlockEnv { + number: U256::from(header.number), + beneficiary: header.beneficiary, + timestamp: U256::from(header.timestamp), + gas_limit: header.gas_limit, + basefee: header.base_fee_per_gas.unwrap_or_default(), + difficulty: header.difficulty, + prevrandao: Some(header.mix_hash), + ..Default::default() + }; + if let Some(excess) = header.excess_blob_gas { + env.set_blob_excess_gas_and_price(excess, self.blob_base_fee_update_fraction); + } + env + } + + /// Imports `block`: runs it through the executor on a copy of the chain's state, and, when the + /// executor accepts it, makes it the head and answers what it produced. A refused block leaves + /// the chain as it was. + pub(crate) fn import(&mut self, block: &DecodedBlock) -> Result { + let header = &block.header; + let mut state = State::builder().with_cached_prestate(self.state.clone()).build(); + let window = header.number.saturating_sub(BLOCK_HASH_WINDOW); + state.block_hashes.extend(self.hashes.range(window..).map(|(n, hash)| (*n, *hash))); + + let evm = Mode::Equivalence.evm(FORK, &mut state, self.block_env(block), self.chain_id); + let only_deposits = self.spec.admits_only_deposits(self.head_timestamp, header.timestamp); + let activates_satin = + self.spec.is_satin_activation_block(self.head_timestamp, header.timestamp); + let ctx = MegaBlockExecutionCtx::new( + header.parent_hash, + header.parent_beacon_block_root, + header.extra_data.clone(), + BlockLimits::no_limits(), + ) + .with_no_user_tx_activation_block(only_deposits) + .with_satin_activation_block(activates_satin); + let mut executor = + MegaBlockExecutor::new(evm, ctx, self.spec.clone(), OpAlloyReceiptBuilder::default()) + .with_protocol_limits(limits()); + executor.apply_pre_execution_changes().map_err(refusal)?; + for tx in &block.body.transactions { + let signer = tx.recover_signer().map_err(|error| Refusal { + names: &["INVALID_SIGNATURE_VRS"], + detail: format!("the signature recovers no sender: {error}"), + })?; + executor.execute_transaction(&Recovered::new_unchecked(tx, signer)).map_err(refusal)?; + } + let (_, result) = executor.finish().map_err(refusal)?; + + let routed_base_fee = self.routed_base_fee + + U256::from(header.base_fee_per_gas.unwrap_or_default()) * U256::from(result.gas_used); + self.state = state.cache; + self.routed_base_fee = routed_base_fee; + self.head = header.hash_slow(); + self.head_timestamp = header.timestamp; + self.hashes.insert(header.number, self.head); + Ok(BlockOutput { + gas_used: result.gas_used, + receipts_root: receipts_root(&result.receipts), + logs_bloom: logs_bloom(&result.receipts), + state_root: self.state_root(), + }) + } +} + +/// The exception names a refusal of the executor satisfies. +fn refusal(error: BlockExecutionError) -> Refusal { + let names = match &error { + BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. }) => { + error.as_invalid_tx_err().map_or(&[][..], |error| exceptions::names(FORK, error)) + } + BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. }, + ) => &["GAS_ALLOWANCE_EXCEEDED"], + _ => &[], + }; + Refusal { names, detail: error.to_string() } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The removal list names every predeploy the pre-state holds and the three fee vaults, each + /// once. + #[test] + fn test_the_list_names_every_account_a_satin_chain_adds() { + let listed: BTreeSet<_> = SATIN_ACCOUNTS.iter().map(|a| a.address).collect(); + assert_eq!(listed.len(), SATIN_ACCOUNTS.len(), "an address listed twice"); + let listed_as = |added: Added| -> BTreeSet<_> { + SATIN_ACCOUNTS.iter().filter(|a| a.added == added).map(|a| a.address).collect() + }; + let predeploys: BTreeSet<_> = + rex6_predeploys(registry_roles()).into_iter().map(|(address, ..)| address).collect(); + assert_eq!(listed_as(Added::PreState), predeploys); + let vaults: BTreeSet<_> = SATIN_ACCOUNTS + .iter() + .filter(|a| a.added != Added::PreState) + .map(|a| a.address) + .collect(); + assert_eq!( + vaults, + BTreeSet::from([BASE_FEE_RECIPIENT, L1_FEE_RECIPIENT, OPERATOR_FEE_RECIPIENT]) + ); + } + + /// [S10] The schedule the chain runs on loads, and the blocks are held to no limit: + /// equivalence mode takes out every one `MegaETH` sets. + /// + /// Expected values: constants (no limit at all). + #[test] + fn test_the_chain_spec_loads_and_the_blocks_are_held_to_no_limit() { + let spec = chain_spec(); + assert!(spec.validate_schedule().is_ok()); + assert_eq!(limits(), ProtocolLimits::no_limits()); + assert_eq!(limits().tx_runtime_limits, mega_evm::EvmTxRuntimeLimits::no_limits()); + assert_eq!(limits().block_txs_data_limit, u64::MAX); + } + + /// [S1.8] [S21.12] [S1] A block's context says whether it admits only deposits, from the + /// schedule and the head's timestamp, as a node works it out. Under a schedule that activates + /// Satin at the block's timestamp, with the genesis a second earlier, the block is Satin's + /// activation block: a user transaction in it is refused, and the block without it is + /// imported. The next block, whose parent is that block, admits the transaction. Under the + /// runner's own schedule every fork is active from genesis, so no block it imports is an + /// activation block. + /// + /// Expected values: independent (the schedule's own timestamps and the rule). + #[test] + fn test_an_imported_block_is_told_whether_it_admits_only_deposits() { + use mega_evm::{ + alloy_consensus::{BlockBody, Header, Signed, TxLegacy}, + alloy_hardforks::ForkCondition, + alloy_primitives::{Bytes, Signature, TxKind}, + MegaHardfork, MegaTxEnvelope, + }; + + const ACTIVATION: u64 = 1_000; + let tx = TxLegacy { + chain_id: Some(1), + nonce: 0, + gas_price: 10, + gas_limit: 100_000, + to: TxKind::Call(Address::repeat_byte(0xc0)), + value: U256::ZERO, + input: Bytes::new(), + }; + let signature = + Signature::new(U256::from(0x23f5_c4da_u64), U256::from(0x42f9_035f_u64), false); + let tx = MegaTxEnvelope::Legacy(Signed::new_unhashed(tx, signature)); + let sender = tx.recover_signer().expect("the signature recovers a sender"); + let funded = Account { balance: U256::from(10).pow(U256::from(18)), ..Default::default() }; + let pre = BTreeMap::from([(sender, funded)]); + let block = |number: u64, timestamp: u64, transactions: Vec| { + let header = Header { + number, + timestamp, + gas_limit: 30_000_000, + base_fee_per_gas: Some(7), + parent_beacon_block_root: Some(B256::ZERO), + excess_blob_gas: Some(0), + ..Default::default() + }; + DecodedBlock::new(header, BlockBody { transactions, ommers: vec![], withdrawals: None }) + }; + let satin_at_activation = MegaHardforkConfig::default() + .with(MegaHardfork::Satin, ForkCondition::Timestamp(ACTIVATION)); + + let mut chain = Chain::new(&pre, (0, B256::ZERO), ACTIVATION - 1, 1, 5_007_716).unwrap(); + chain.spec = satin_at_activation; + let refusal = chain + .import(&block(1, ACTIVATION, vec![tx.clone()])) + .expect_err("a user transaction in Satin's activation block"); + assert!( + refusal.detail.contains("non-deposit transaction in fork activation block"), + "{}", + refusal.detail + ); + chain.import(&block(1, ACTIVATION, vec![])).expect("the activation block, without it"); + chain.import(&block(2, ACTIVATION + 1, vec![tx])).expect("the block after admits it"); + + assert!( + !chain_spec().admits_only_deposits(0, u64::MAX), + "under the runner's schedule no parent and no block make an activation block" + ); + } +} diff --git a/crates/mega-state-test/src/blockchain/fixture.rs b/crates/mega-state-test/src/blockchain/fixture.rs new file mode 100644 index 000000000..6edfeca16 --- /dev/null +++ b/crates/mega-state-test/src/blockchain/fixture.rs @@ -0,0 +1,184 @@ +//! A blockchain test as the execution-spec fixtures write it, read only as far as the runner +//! judges it. +//! +//! A fixture file maps test names to tests; a test carries its pre-state, its genesis block, its +//! blocks, the post-state its last valid block leaves and the hash of that block. Every block is +//! carried as its RLP, which is what the runner executes: an invalid block has no decoded header +//! or transactions beside it, only `rlp_decoded`, which may itself be absent when the RLP does not +//! decode. The decoded transactions and withdrawals are read only to decide whether a test is +//! skipped, before anything runs. + +use std::collections::BTreeMap; + +use mega_evm::{ + alloy_consensus::{Block, Header}, + revm::primitives::{Address, Bytes, B256, U256}, + MegaTxEnvelope, +}; +use serde::{ + de::{Error as _, IgnoredAny, MapAccess, Visitor}, + Deserialize, Deserializer, +}; +use serde_json::value::RawValue; + +use crate::types::{blockchain::Account, deserialize_maybe_empty}; + +/// The network name of the entries the runner executes. +pub const NETWORK: &str = "Osaka"; + +/// A fixture file's tests, each still unparsed, so that only the entries of [`NETWORK`] are read +/// in full. A name that appears twice is an error rather than one test silently replacing the +/// other. +pub(crate) struct Suite<'a>(pub(crate) BTreeMap); + +impl<'de: 'a, 'a> Deserialize<'de> for Suite<'a> { + fn deserialize>(deserializer: D) -> Result { + struct Tests<'a>(core::marker::PhantomData<&'a ()>); + impl<'de: 'a, 'a> Visitor<'de> for Tests<'a> { + type Value = Suite<'a>; + + fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("a map of test names to tests") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut tests = BTreeMap::new(); + while let Some(name) = map.next_key::()? { + let test: &'de RawValue = map.next_value()?; + if tests.insert(name.clone(), test).is_some() { + return Err(A::Error::custom(format!("test {name:?} appears twice"))); + } + } + Ok(Suite(tests)) + } + } + deserializer.deserialize_map(Tests(core::marker::PhantomData)) + } +} + +/// The network a test is filled for, read without parsing the rest of it. +#[derive(Deserialize)] +pub(crate) struct Network { + pub(crate) network: String, +} + +/// A blockchain test. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Test { + /// The RLP of the genesis block, whose state root is the pre-state's. + #[serde(rename = "genesisRLP")] + pub(crate) genesis_rlp: Bytes, + /// The blocks, in the order they are imported. + pub(crate) blocks: Vec, + /// The state the genesis block holds. + pub(crate) pre: BTreeMap, + /// The state the last valid block leaves. + pub(crate) post_state: BTreeMap, + /// The hash of the last valid block. + pub(crate) lastblockhash: B256, + /// The chain the test runs on. + pub(crate) config: ChainConfig, +} + +/// The chain configuration a test carries. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ChainConfig { + /// The chain id. + pub(crate) chainid: U256, + /// The blob fee parameters of each fork, by fork name. + pub(crate) blob_schedule: BTreeMap, +} + +/// One fork's blob fee parameters. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct BlobParams { + /// The fraction the blob base fee is updated by. + pub(crate) base_fee_update_fraction: U256, +} + +/// A block of a test. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct FixtureBlock { + /// The block's RLP. + pub(crate) rlp: Bytes, + /// The exception a node raises importing the block, as one name or alternatives joined by + /// `|`; `None` for a valid block. + pub(crate) expect_exception: Option, + /// The block's transactions, decoded, for a valid block. + #[serde(default)] + pub(crate) transactions: Vec, + /// The block's withdrawals, for a valid block. + #[serde(default)] + pub(crate) withdrawals: Vec, + /// The block decoded from its RLP, for an invalid block whose RLP decodes. + #[serde(rename = "rlp_decoded")] + pub(crate) rlp_decoded: Option, +} + +/// An invalid block's body, decoded. +#[derive(Debug, Deserialize)] +pub(crate) struct Decoded { + /// The block's transactions. + #[serde(default)] + pub(crate) transactions: Vec, + /// The block's withdrawals. + #[serde(default)] + pub(crate) withdrawals: Vec, +} + +/// A decoded transaction, read for what decides whether its test is skipped. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct FixtureTx { + /// The transaction's EIP-2718 type; `None` for a legacy transaction written without one. + #[serde(rename = "type")] + pub(crate) ty: Option, + /// The recipient; `None` for a creation. + #[serde(default, deserialize_with = "deserialize_maybe_empty")] + pub(crate) to: Option
, + /// The gas price of a legacy or EIP-2930 transaction. + pub(crate) gas_price: Option, + /// The fee cap of a dynamic-fee transaction. + pub(crate) max_fee_per_gas: Option, + /// The priority fee cap of a dynamic-fee transaction. + pub(crate) max_priority_fee_per_gas: Option, +} + +impl FixtureBlock { + /// The block's transactions as the fixture decodes them, the invalid block's included. + pub(crate) fn transactions(&self) -> impl Iterator { + self.transactions + .iter() + .chain(self.rlp_decoded.iter().flat_map(|decoded| decoded.transactions.iter())) + } + + /// Whether the block carries a withdrawal, valid or not. + pub(crate) fn has_withdrawals(&self) -> bool { + !self.withdrawals.is_empty() || + self.rlp_decoded.as_ref().is_some_and(|decoded| !decoded.withdrawals.is_empty()) + } + + /// The names the block's expected exception gives, without their alternatives' separator; + /// empty for a valid block. + pub(crate) fn exception_names(&self) -> impl Iterator { + self.expect_exception.iter().flat_map(|names| names.split('|').map(str::trim)) + } +} + +/// A block decoded from its RLP: its header and its transactions as an OP chain carries them. +pub(crate) type DecodedBlock = Block; + +/// Decodes the block `rlp` holds, which must be exactly one block. +pub(crate) fn decode_block(rlp: &[u8]) -> Result { + let mut buf = rlp; + let block = ::decode(&mut buf) + .map_err(|error| format!("the block's RLP does not decode: {error}"))?; + if !buf.is_empty() { + return Err(format!("{} bytes follow the block's RLP", buf.len())); + } + Ok(block) +} diff --git a/crates/mega-state-test/src/blockchain/mod.rs b/crates/mega-state-test/src/blockchain/mod.rs new file mode 100644 index 000000000..3ff405710 --- /dev/null +++ b/crates/mega-state-test/src/blockchain/mod.rs @@ -0,0 +1,840 @@ +//! The execution-spec blockchain tests, imported through Satin's block executor. +//! +//! A blockchain test is a chain: a pre-state, a genesis block, and blocks a node imports one after +//! the other, some of which it must refuse. [`run`] imports every test the fixtures under a set +//! of paths define for Osaka through [`MegaBlockExecutor`](mega_evm::MegaBlockExecutor) — many +//! transactions to a block, many blocks to a test, the pre-block system calls before every block +//! — on `MegaEvm` in equivalence mode's neutral configuration, and judges each block: +//! +//! - a block the fixture expects to be valid must be accepted, and must produce the header's gas +//! used, logs bloom and receipts root, and leave its state root, the accounts a Satin block adds +//! to the state taken out ([`SATIN_ACCOUNTS`]); +//! - a block the fixture expects to be invalid for a `TransactionException` must be refused, for +//! one of the exceptions it names ([`exceptions`](crate::exceptions)), and leaves the chain at +//! the previous block; +//! - once every block is imported, the chain's head must be the fixture's last block and its state +//! the fixture's post-state. +//! +//! A [deviation](crate::deviations) the state-test registry already has may list a test, block by +//! block: an accepted block whose outcome is not its header's passes only when the test's entry +//! lists that block with exactly the outcome Satin produces — its gas used, logs bloom, receipts +//! root and state root — and the chain is imported on from Satin's own state, so every later block +//! is held to its header or to its own listed outcome in turn. The chain's head is always +//! compared; its post-state is compared when the chain ends on a state its last header +//! describes, and otherwise only when the entry says why it is not. +//! +//! Each test is passed, deviated (every block matching its header or its listed outcome, and the +//! chain ending as listed), skipped for a [reason](SkipReason) decided from its content before +//! anything runs, or failed; [`Report::gate`] fails on a failed test. The summary counts the +//! blocks checked against Ethereum apart from the blocks matched to a deviation. +//! +//! The devnet release's blockchain tests are not run: the revm fork's own runner skips them too. + +mod chain; +mod fixture; +pub mod skips; + +use std::{ + collections::BTreeMap, + fmt, + panic::{catch_unwind, AssertUnwindSafe}, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicUsize, Ordering}, + Mutex, + }, +}; + +pub use chain::{chain_spec, registry_roles, Added, SatinAccount, FORK, SATIN_ACCOUNTS}; +pub use fixture::NETWORK; +use mega_evm::{ + alloy_consensus::Header, + revm::primitives::{keccak256, B256}, +}; +use serde::Serialize; +pub use skips::SkipReason; + +use self::{ + chain::{BlockOutput, Chain}, + fixture::{decode_block, Network, Suite, Test}, +}; +use crate::{ + deviations::{self, BlockchainEntry, Cause, ChainEnd, Deviation}, + exceptions::{check_names, Mismatch}, +}; + +/// How a run executes its fixtures. +#[derive(Clone, Copy, Debug)] +pub struct Config { + /// Worker threads; one runs the files in order. + pub threads: usize, + /// Print one JSON line per test to standard error. + pub json_outcome: bool, + /// The registry whose entries explain blocks that differ: + /// [`deviations::DEVIATIONS`](crate::deviations::DEVIATIONS) for the gate. + pub deviations: &'static [Deviation], +} + +/// Which test a result is about. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +pub struct TestId { + /// The fixture file, as it was found under the paths the run was given. + pub path: String, + /// The test's name within the file. + pub name: String, +} + +impl fmt::Display for TestId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} :: {}", self.path, self.name) + } +} + +/// How a test failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum FailureKind { + /// The executor refused a block the fixture expects to be valid. + UnexpectedException, + /// The executor accepted a block the fixture expects to be invalid. + MissingException, + /// The executor refused a block for another reason than the ones the fixture names. + WrongException, + /// The executor refused a block with an error no execution-spec exception names. + UnnamedException, + /// An accepted block used other gas than its header says. + GasUsedMismatch, + /// An accepted block's logs bloom is not its header's. + LogsBloomMismatch, + /// An accepted block's receipts root is not its header's. + ReceiptsRootMismatch, + /// An accepted block's state root is not its header's. + StateRootMismatch, + /// Once every block is imported, the chain's head is not the fixture's last block, or its + /// state is not the fixture's post-state. + PostStateMismatch, + /// The test is listed by a deviation, and does not deviate as listed: a listed block matched + /// its header or produced another outcome, a block names a cause that does not hold, or the + /// chain does not end as listed. + NotAsListed, + /// The fixture could not be read, parsed or decoded. + Fixture, + /// Running the test panicked. + Panic, +} + +impl FailureKind { + /// Every kind, in the order a block's comparisons are made. + pub const ALL: [Self; 12] = [ + Self::UnexpectedException, + Self::MissingException, + Self::WrongException, + Self::UnnamedException, + Self::GasUsedMismatch, + Self::LogsBloomMismatch, + Self::ReceiptsRootMismatch, + Self::StateRootMismatch, + Self::PostStateMismatch, + Self::NotAsListed, + Self::Fixture, + Self::Panic, + ]; + + /// The kind's name, as the summary prints it. + pub const fn name(self) -> &'static str { + match self { + Self::UnexpectedException => "unexpected-exception", + Self::MissingException => "missing-exception", + Self::WrongException => "wrong-exception", + Self::UnnamedException => "unnamed-exception", + Self::GasUsedMismatch => "gas-used-mismatch", + Self::LogsBloomMismatch => "logs-bloom-mismatch", + Self::ReceiptsRootMismatch => "receipts-root-mismatch", + Self::StateRootMismatch => "state-root-mismatch", + Self::PostStateMismatch => "post-state-mismatch", + Self::NotAsListed => "not-as-listed", + Self::Fixture => "fixture", + Self::Panic => "panic", + } + } +} + +/// What Satin produces for an accepted block: the block, and the gas used, logs bloom, receipts +/// root and state root it produced — every field a block is held to. +/// +/// The bloom is kept as its keccak hash, which pins its 256 bytes in 32: the receipts root commits +/// to each receipt's bloom, not to the block's, which the runner aggregates on its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] +pub struct Produced { + /// The block's index among the test's blocks. + pub block: usize, + /// The gas the block used. + pub gas_used: u64, + /// The keccak hash of the block's logs bloom. + pub logs_bloom_hash: B256, + /// The root of the block's receipts. + pub receipts_root: B256, + /// The root of the state the block left, the accounts Satin added taken out. + pub state_root: B256, +} + +impl fmt::Display for Produced { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "block {}: gas used {}, logs bloom hash {}, receipts root {}, state root {}", + self.block, self.gas_used, self.logs_bloom_hash, self.receipts_root, self.state_root + ) + } +} + +/// An accepted block whose outcome is not its header's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Differing { + /// What Satin produced for it. + pub produced: Produced, + /// Whether its state root is the only field that differs from its header. + pub state_root_only: bool, + /// Whether the test's entry lists the block with exactly this outcome, and its cause holds. + pub listed: bool, +} + +/// A failed test. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Failure { + /// How it failed. + pub kind: FailureKind, + /// The index of the block it failed at, when it failed at one. + pub block: Option, + /// What was expected and what happened. + pub detail: String, + /// Every accepted block the test imported whose outcome is not its header's, listed or not: + /// what an entry for the test lists. + pub differing: Vec, +} + +impl Failure { + fn new(kind: FailureKind, block: Option, detail: impl Into) -> Self { + Self { kind, block, detail: detail.into(), differing: Vec::new() } + } +} + +/// What happened to a test. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "outcome", rename_all = "kebab-case")] +pub enum Outcome { + /// It was imported, and every block and the chain's end matched its fixture. + Passed, + /// It was imported, every block matched its header or the outcome its deviation lists for it, + /// and the chain ended as listed. + Deviated { + /// The deviation that lists it. + deviation: &'static str, + }, + /// It was not executed. + Skipped { + /// Why not. + reason: SkipReason, + }, + /// It was imported, or failed to be, and did not match its fixture or its listed outcome. + Failed(Failure), +} + +/// The blocks of a test the runner imported, by how each was judged. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Blocks { + /// Blocks the executor accepted that matched their headers: checked against Ethereum. + pub matched: usize, + /// Blocks the executor refused for an exception the fixture names: checked against Ethereum. + pub refused: usize, + /// Blocks the executor accepted whose outcome is not their header's and is exactly the one a + /// deviation lists: matched to a deviation, not to Ethereum. + pub deviated: usize, +} + +impl Blocks { + /// The blocks checked against Ethereum: matched or refused as the fixture expects. + pub const fn checked(&self) -> usize { + self.matched + self.refused + } +} + +/// A test and what happened to it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TestResult { + /// The test. + pub id: TestId, + /// What happened to it. + pub outcome: Outcome, + /// The blocks it imported, up to a failure that stopped it. + pub blocks: Blocks, +} + +/// Every test a run was given, and what happened to each. +#[derive(Debug, Serialize)] +pub struct Report { + /// The registry the run held differing blocks to. + #[serde(skip)] + pub deviations: &'static [Deviation], + /// The fixture files the run found. + pub files: usize, + /// Every test, ordered by file and name. + pub results: Vec, + /// The fixture files that could not be read or parsed, in path order, and why. + pub file_failures: Vec<(String, Failure)>, +} + +/// The counts of a [`Report`]. +#[derive(Debug, Default, PartialEq, Eq, Serialize)] +pub struct Summary { + /// The fixture files the run found. + pub files: usize, + /// The tests the files define for Osaka: executed and skipped. + pub defined: usize, + /// The tests that executed: passed, deviated or failed. + pub executed: usize, + /// The tests that executed and matched their fixture in every block and at the chain's end. + pub passed: usize, + /// The tests that were not executed, by reason. + pub skipped: BTreeMap, + /// The tests that failed, by kind. + pub failed: BTreeMap, + /// The tests a deviation lists that deviated exactly as listed, by deviation. + pub deviated: BTreeMap<&'static str, usize>, + /// The failed tests: no listed outcome explains them. + pub unattributed: usize, + /// The tests a deviation lists that did not deviate as listed, by deviation. + pub unreproduced: BTreeMap<&'static str, usize>, + /// The fixture files that could not be read or parsed. + pub file_failures: usize, + /// The blocks the executed tests imported: checked against Ethereum (matched or refused) and + /// matched to a deviation, counted apart. + pub blocks: Blocks, +} + +impl Summary { + /// The tests that were not executed. + pub fn skipped_total(&self) -> usize { + self.skipped.values().sum() + } + + /// The tests that failed. + pub fn failed_total(&self) -> usize { + self.failed.values().sum() + } + + /// The tests that deviated as listed. + pub fn deviated_total(&self) -> usize { + self.deviated.values().sum() + } +} + +impl Report { + /// Counts the report. + pub fn summary(&self) -> Summary { + let mut summary = Summary { + files: self.files, + file_failures: self.file_failures.len(), + ..Default::default() + }; + for result in &self.results { + summary.defined += 1; + summary.blocks.matched += result.blocks.matched; + summary.blocks.refused += result.blocks.refused; + summary.blocks.deviated += result.blocks.deviated; + match &result.outcome { + Outcome::Passed => { + summary.executed += 1; + summary.passed += 1; + } + Outcome::Deviated { deviation } => { + summary.executed += 1; + *summary.deviated.entry(deviation).or_default() += 1; + } + Outcome::Skipped { reason } => *summary.skipped.entry(*reason).or_default() += 1, + Outcome::Failed(failure) => { + summary.executed += 1; + summary.unattributed += 1; + *summary.failed.entry(failure.kind).or_default() += 1; + } + } + } + for unreproduced in self.unreproduced() { + *summary.unreproduced.entry(unreproduced.deviation.id).or_default() += 1; + } + summary + } + + /// The failed tests: no listed outcome explains them. + pub fn unattributed(&self) -> impl Iterator { + self.results.iter().filter_map(|result| match &result.outcome { + Outcome::Failed(failure) => Some((&result.id, failure)), + _ => None, + }) + } + + /// The tests the registry lists that did not deviate as listed: a test is reproduced when + /// exactly one result of the run is the test's and it deviated under the deviation that lists + /// it. + pub fn unreproduced(&self) -> impl Iterator> { + self.deviations.iter().flat_map(move |deviation| { + deviation.blockchain_entries.iter().filter_map(move |entry| { + let seen: Vec<_> = + self.results.iter().filter(|result| entry.is(&result.id)).collect(); + let reproduced = matches!( + seen.as_slice(), + [TestResult { outcome: Outcome::Deviated { deviation: id }, .. }] + if *id == deviation.id + ); + (!reproduced).then_some(Unreproduced { deviation, entry, seen }) + }) + }) + } + + /// What the gate finds wrong with this run: a fixture file that could not be read, a failed + /// test, and, for each count given, a count that differs from it. Empty when the gate passes. + /// + /// `expected_skipped` pins every class: a class it does not name is pinned at zero. With + /// `check_deviations`, every test a registered deviation lists must deviate exactly as listed. + pub fn gate( + &self, + expected_executed: Option, + expected_skipped: Option<&BTreeMap>, + check_deviations: bool, + ) -> Vec { + let summary = self.summary(); + let mut problems = Vec::new(); + if summary.file_failures > 0 { + problems.push(format!("{} fixture files could not be read", summary.file_failures)); + } + if summary.unattributed > 0 { + problems.push(format!( + "{} blockchain tests failed: no listed outcome explains them", + summary.unattributed + )); + } + if let Some(expected) = expected_executed.filter(|&n| n != summary.executed) { + problems.push(format!("{} tests executed, {expected} pinned", summary.executed)); + } + if let Some(expected) = expected_skipped { + for reason in SkipReason::ALL { + let skipped = summary.skipped.get(&reason).copied().unwrap_or(0); + let pinned = expected.get(&reason).copied().unwrap_or(0); + if skipped != pinned { + problems.push(format!( + "{skipped} tests skipped for {}, {pinned} pinned", + reason.name() + )); + } + } + } + if check_deviations { + for deviation in self.deviations { + let listed = deviation.blockchain_entries.len(); + let unreproduced = summary.unreproduced.get(deviation.id).copied().unwrap_or(0); + if unreproduced > 0 { + problems.push(format!( + "deviation {}: {unreproduced} of the {listed} blockchain tests it lists \ + did not deviate as listed", + deviation.id + )); + } + } + } + problems + } +} + +/// A test a deviation lists that did not deviate as listed. +#[derive(Debug)] +pub struct Unreproduced<'a> { + /// The deviation. + pub deviation: &'static Deviation, + /// The test it lists. + pub entry: &'static BlockchainEntry, + /// The results the run has for the test: none when the run did not execute it. + pub seen: Vec<&'a TestResult>, +} + +/// Imports every Osaka test `files` define, and reports each. +pub fn run(files: &[PathBuf], config: Config) -> Report { + let next = AtomicUsize::new(0); + let results = Mutex::new((Vec::new(), Vec::new())); + let threads = config.threads.clamp(1, files.len().max(1)); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = files.get(index) else { break }; + let file = run_file(path, config); + let mut results = results.lock().expect("no worker panics holding the lock"); + match file { + Ok(tests) => results.0.extend(tests), + Err(failure) => results.1.push((path.to_string_lossy().into_owned(), failure)), + } + }); + } + }); + let (mut results, mut file_failures) = + results.into_inner().expect("no worker panics holding the lock"); + results.sort_by(|a, b| a.id.cmp(&b.id)); + file_failures.sort_by(|a, b| a.0.cmp(&b.0)); + Report { deviations: config.deviations, files: files.len(), results, file_failures } +} + +/// Every Osaka test the file at `path` defines, and what happened to each; or why the file could +/// not be read. +pub fn run_file(path: &Path, config: Config) -> Result, Failure> { + let path_str = path.to_string_lossy().into_owned(); + let json = std::fs::read_to_string(path) + .map_err(|error| Failure::new(FailureKind::Fixture, None, format!("read: {error}")))?; + let suite = serde_json::from_str::>(&json) + .map_err(|error| Failure::new(FailureKind::Fixture, None, format!("parse: {error}")))?; + + let mut results = Vec::new(); + for (name, raw) in &suite.0 { + let network = serde_json::from_str::(raw.get()).map_err(|error| { + Failure::new(FailureKind::Fixture, None, format!("{name}: network: {error}")) + })?; + if network.network != NETWORK { + continue; + } + let id = TestId { path: path_str.clone(), name: name.clone() }; + let (outcome, blocks) = match serde_json::from_str::(raw.get()) { + Ok(test) => catch_unwind(AssertUnwindSafe(|| { + run_test(&id, &test, deviations::blockchain_entry(config.deviations, &id)) + })) + .unwrap_or_else(|panic| { + let failure = Failure::new(FailureKind::Panic, None, panic_message(&panic)); + (Outcome::Failed(failure), Blocks::default()) + }), + Err(error) => { + let failure = Failure::new(FailureKind::Fixture, None, format!("parse: {error}")); + (Outcome::Failed(failure), Blocks::default()) + } + }; + if config.json_outcome { + print_outcome(&id, &outcome); + } + results.push(TestResult { id, outcome, blocks }); + } + Ok(results) +} + +fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { + panic + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_else(|| "a panic without a message".into()) +} + +fn print_outcome(id: &TestId, outcome: &Outcome) { + let line = serde_json::json!({ "path": id.path, "test": id.name, "result": outcome }); + eprintln!("{line}"); +} + +/// Imports the test `id` and judges it against its fixture and the entry `listed`, the deviation +/// that lists it and its entry for it, unless it is skipped. +fn run_test( + id: &TestId, + test: &Test, + listed: Option<(&'static Deviation, &'static BlockchainEntry)>, +) -> (Outcome, Blocks) { + if let Some(reason) = skips::skip_test(&id.path, &id.name, test) { + return (Outcome::Skipped { reason }, Blocks::default()); + } + let mut blocks = Blocks::default(); + let outcome = match import_test(test, listed.map(|(_, entry)| entry), &mut blocks) { + Ok(()) => match listed { + Some((deviation, _)) => Outcome::Deviated { deviation: deviation.id }, + None => Outcome::Passed, + }, + Err(failure) => Outcome::Failed(failure), + }; + (outcome, blocks) +} + +/// The fields of an accepted block's outcome that differ from its header. +#[derive(Clone, Copy, Debug)] +struct Differences { + gas_used: bool, + logs_bloom: bool, + receipts_root: bool, + state_root: bool, +} + +impl Differences { + fn of(header: &Header, output: &BlockOutput) -> Self { + Self { + gas_used: output.gas_used != header.gas_used, + logs_bloom: output.logs_bloom != header.logs_bloom, + receipts_root: output.receipts_root != header.receipts_root, + state_root: output.state_root != header.state_root, + } + } + + const fn any(self) -> bool { + self.gas_used || self.logs_bloom || self.receipts_root || self.state_root + } + + /// Whether the block ran as on Ethereum and left another state: only its state root differs. + const fn state_root_only(self) -> bool { + self.state_root && !self.gas_used && !self.logs_bloom && !self.receipts_root + } + + /// The first field that differs, in the order a block is compared, as a failure. + const fn kind(self) -> FailureKind { + if self.gas_used { + FailureKind::GasUsedMismatch + } else if self.logs_bloom { + FailureKind::LogsBloomMismatch + } else if self.receipts_root { + FailureKind::ReceiptsRootMismatch + } else { + FailureKind::StateRootMismatch + } + } + + /// Every field that differs, with what the executor produced and what the header says. + fn detail(self, header: &Header, output: &BlockOutput) -> String { + let mut details = Vec::new(); + if self.gas_used { + details.push(format!("gas used {}, header {}", output.gas_used, header.gas_used)); + } + if self.logs_bloom { + details.push(format!("logs bloom {}, header {}", output.logs_bloom, header.logs_bloom)); + } + if self.receipts_root { + details.push(format!( + "receipts root {}, header {}", + output.receipts_root, header.receipts_root + )); + } + if self.state_root { + details.push(format!("state root {}, header {}", output.state_root, header.state_root)); + } + details.join("; ") + } +} + +/// What Satin produced for the accepted block at `index`. +fn produced(index: usize, output: &BlockOutput) -> Produced { + Produced { + block: index, + gas_used: output.gas_used, + logs_bloom_hash: keccak256(output.logs_bloom), + receipts_root: output.receipts_root, + state_root: output.state_root, + } +} + +/// Whether the cause `entry` gives for its block at `index`, which differs from its header in +/// `differences`, holds: the deviation's rule may act in any block, and a block whose state an +/// earlier listed block left must otherwise run as on Ethereum. +fn cause_holds( + cause: Cause, + index: usize, + differences: Differences, + entry: &BlockchainEntry, +) -> bool { + match cause { + Cause::Rule => true, + Cause::StateLeftBy(earlier) => { + earlier < index && entry.block(earlier).is_some() && differences.state_root_only() + } + } +} + +/// `failure`, carrying the blocks that differed before it. +fn with_differing(mut failure: Failure, differing: &[Differing]) -> Failure { + failure.differing = differing.to_vec(); + failure +} + +/// Imports every block of `test`, counting in `blocks` how each was judged, and checks where the +/// chain ends. +/// +/// An accepted block that differs from its header passes only when `entry` lists it with exactly +/// the outcome Satin produced and a cause that holds; the chain is imported on from Satin's own +/// state either way, so a failure names every block that differs, not only the first. A refusal +/// the fixture does not expect, or a block it expects refused that is accepted, stops the test. +fn import_test( + test: &Test, + entry: Option<&'static BlockchainEntry>, + blocks: &mut Blocks, +) -> Result<(), Failure> { + let fixture = |detail: String| Failure::new(FailureKind::Fixture, None, detail); + let chain_id = u64::try_from(test.config.chainid) + .map_err(|_| fixture(format!("chain id {} does not fit a u64", test.config.chainid)))?; + let fraction = test + .config + .blob_schedule + .get(NETWORK) + .ok_or_else(|| fixture(format!("no {NETWORK} blob schedule")))? + .base_fee_update_fraction; + let fraction = u64::try_from(fraction) + .map_err(|_| fixture(format!("blob base fee update fraction {fraction} does not fit")))?; + let genesis = + decode_block(&test.genesis_rlp).map_err(|error| fixture(format!("genesis: {error}")))?; + let genesis_id = (genesis.header.number, genesis.header.hash_slow()); + let mut chain = Chain::new(&test.pre, genesis_id, genesis.header.timestamp, chain_id, fraction) + .map_err(|error| fixture(format!("pre-state: {error}")))?; + // The pre-state is the genesis block's: nothing has run yet, so nothing Satin adds is there. + let root = chain.state_root(); + if root != genesis.header.state_root { + return Err(fixture(format!( + "the pre-state's root is {root}, the genesis block's {}", + genesis.header.state_root + ))); + } + + let mut differing = Vec::new(); + let mut unlisted = None; + // Whether the chain holds the state its last accepted block's header describes. + let mut on_fixture_state = true; + for (index, block) in test.blocks.iter().enumerate() { + let decoded = decode_block(&block.rlp).map_err(|error| { + let failure = + Failure::new(FailureKind::Fixture, Some(index), format!("block {index}: {error}")); + with_differing(failure, &differing) + })?; + let header = &decoded.header; + match (&block.expect_exception, chain.import(&decoded)) { + (None, Ok(output)) => { + let differences = Differences::of(header, &output); + on_fixture_state = !differences.state_root; + if !differences.any() { + blocks.matched += 1; + continue; + } + let produced = produced(index, &output); + let listed_block = entry.and_then(|entry| Some((entry, entry.block(index)?))); + let listed = listed_block.is_some_and(|(entry, listed)| { + listed.produced == produced && + cause_holds(listed.cause, index, differences, entry) + }); + differing.push(Differing { + produced, + state_root_only: differences.state_root_only(), + listed, + }); + if listed { + blocks.deviated += 1; + } else if unlisted.is_none() { + let note = if listed_block.is_some() { + "; its deviation lists another outcome or a cause that does not hold" + } else { + "" + }; + let detail = + format!("block {index}: {}{note}", differences.detail(header, &output)); + unlisted = Some(Failure::new(differences.kind(), Some(index), detail)); + } + } + (None, Err(refusal)) => { + let failure = Failure::new( + FailureKind::UnexpectedException, + Some(index), + format!("block {index} refused: {}", refusal.detail), + ); + return Err(with_differing(failure, &differing)); + } + (Some(expected), Ok(_)) => { + let failure = Failure::new( + FailureKind::MissingException, + Some(index), + format!("block {index}: expected {expected}, the executor accepted it"), + ); + return Err(with_differing(failure, &differing)); + } + (Some(expected), Err(refusal)) => { + let failure = match check_names(expected, refusal.names) { + Ok(()) => { + blocks.refused += 1; + continue; + } + Err(Mismatch::Wrong { got }) => Failure::new( + FailureKind::WrongException, + Some(index), + format!( + "block {index}: expected {expected}, refused as {got:?}: {}", + refusal.detail + ), + ), + Err(Mismatch::Unnamed) => Failure::new( + FailureKind::UnnamedException, + Some(index), + format!("block {index}: expected {expected}, refused: {}", refusal.detail), + ), + }; + return Err(with_differing(failure, &differing)); + } + } + } + if let Some(failure) = unlisted { + return Err(with_differing(failure, &differing)); + } + + // Every block the entry lists deviated as listed. + let not_as_listed = |block, detail: String| { + with_differing(Failure::new(FailureKind::NotAsListed, block, detail), &differing) + }; + for listed in entry.map_or(&[][..], |entry| entry.blocks) { + let index = listed.produced.block; + if !differing.iter().any(|block| block.listed && block.produced.block == index) { + return Err(not_as_listed( + Some(index), + format!("block {index} is listed, and the run did not produce its listed outcome"), + )); + } + } + + // The chain ends at the fixture's last valid block, holding the fixture's post-state, unless + // its entry says why that state is not the fixture's. + if chain.head != test.lastblockhash { + let detail = format!( + "the chain ends at block {}, the fixture's last block is {}", + chain.head, test.lastblockhash + ); + return Err(with_differing( + Failure::new(FailureKind::PostStateMismatch, None, detail), + &differing, + )); + } + match (on_fixture_state, entry.map(|entry| entry.end)) { + (true, None | Some(ChainEnd::FixtureState)) => { + let post_root = chain::fixture_state_root(&test.post_state) + .map_err(|error| fixture(format!("post-state: {error}")))?; + let root = chain.state_root(); + if root != post_root { + let detail = format!( + "the chain ends with state root {root}, the fixture's post-state has \ + {post_root}" + ); + return Err(with_differing( + Failure::new(FailureKind::PostStateMismatch, None, detail), + &differing, + )); + } + } + (false, Some(ChainEnd::DeviatedState(_))) => {} + (true, Some(ChainEnd::DeviatedState(_))) => { + return Err(not_as_listed( + None, + "the entry says the chain ends on a state a listed block left, and it ends on \ + the state its last header describes" + .into(), + )) + } + (false, None | Some(ChainEnd::FixtureState)) => { + return Err(not_as_listed( + None, + "the chain ends on a state a listed block left, and its entry gives no reason \ + the post-state is not compared" + .into(), + )) + } + } + Ok(()) +} diff --git a/crates/mega-state-test/src/blockchain/skips.rs b/crates/mega-state-test/src/blockchain/skips.rs new file mode 100644 index 000000000..d7d54d058 --- /dev/null +++ b/crates/mega-state-test/src/blockchain/skips.rs @@ -0,0 +1,358 @@ +//! The blockchain tests the runner does not execute, and why. +//! +//! Every skip is decided from the test's own content before anything runs — its name, its blocks' +//! withdrawals and transactions as the fixture decodes them, and the exceptions its blocks expect +//! — never from how it fares. Each class is a part of Ethereum's block an OP chain does not have, +//! or a check a node makes on a block before it hands the block to an executor. +//! +//! The pre-block system calls are not skipped: the executor makes the EIP-2935 and EIP-4788 calls +//! before every block, and what they write is compared with everything else. + +use mega_evm::revm::primitives::U256; +use serde::Serialize; + +use super::fixture::{FixtureBlock, FixtureTx, Test}; + +/// Why a blockchain test is not executed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum SkipReason { + /// A block carries withdrawals: an OP chain has no beacon-chain withdrawals, and its blocks + /// process none. + Withdrawals, + /// A block carries a blob transaction (type 3), or expects an exception only a blob + /// transaction raises: an OP chain has no blob transactions. + BlobTransactions, + /// The test is about the execution-layer requests of EIP-7685 — EIP-7002 withdrawal requests + /// and EIP-7251 consolidation requests, which Ethereum's post-block system calls dequeue — or + /// a block expects an exception about requests: an OP chain makes no requests and no + /// post-block system call. + Requests, + /// A block expects a `BlockException` for its header or body — its gas limit, base fee, blob + /// gas fields, size, encoding, withdrawals root or hash: a consensus check a node makes before + /// it executes the block, not one the block executor makes. + HeaderOrBody, + /// A block the fixture expects to be invalid carries a transaction an OP block cannot encode — + /// an EIP-7702 transaction without a recipient, or a fee wider than 128 bits — so its RLP does + /// not decode and no executor sees it. The state-test gate skips the same transactions as + /// unbuildable. + UndecodableInvalidTransaction, + /// The test creates an account at an address whose pre-state holds storage and nothing else + /// (EIP-7610). revm reads storage slot by slot and never asks the database whether an account + /// has any, so it cannot see the collision. The state-test gate skips the same files, by the + /// same list (`crate::skips::skip_file`). + CreateCollisionWithStorage, +} + +impl SkipReason { + /// Every reason, in the order the runner tests them. + pub const ALL: [Self; 6] = [ + Self::Withdrawals, + Self::BlobTransactions, + Self::Requests, + Self::HeaderOrBody, + Self::UndecodableInvalidTransaction, + Self::CreateCollisionWithStorage, + ]; + + /// The reason's name, as the summary prints it and the command line takes it. + pub const fn name(self) -> &'static str { + match self { + Self::Withdrawals => "withdrawals", + Self::BlobTransactions => "blob-transactions", + Self::Requests => "requests", + Self::HeaderOrBody => "header-or-body", + Self::UndecodableInvalidTransaction => "undecodable-invalid-transaction", + Self::CreateCollisionWithStorage => "create-collision-with-storage", + } + } +} + +impl SkipReason { + /// Why a test of this class is not executed, in one line, as the summary prints it. + pub const fn reason(self) -> &'static str { + match self { + Self::Withdrawals => "an OP chain processes no withdrawals", + Self::BlobTransactions => "an OP chain has no blob transactions", + Self::Requests => { + "an OP chain makes no EIP-7685 requests and no post-block system call" + } + Self::HeaderOrBody => "a header or body check a node makes before execution", + Self::UndecodableInvalidTransaction => { + "a transaction an OP block cannot encode, in a block expected to be invalid" + } + Self::CreateCollisionWithStorage => { + "a collision with storage alone, which revm cannot see (EIP-7610)" + } + } + } +} + +impl core::str::FromStr for SkipReason { + type Err = String; + + fn from_str(s: &str) -> Result { + Self::ALL.into_iter().find(|reason| reason.name() == s).ok_or_else(|| { + let names: Vec<_> = Self::ALL.iter().map(|reason| reason.name()).collect(); + format!("unknown skip reason {s:?}; expected one of: {}", names.join(", ")) + }) + } +} + +/// The directories of the request tests, as the test names carry them. +const REQUEST_TESTS: [&str; 3] = [ + "tests/prague/eip7002_el_triggerable_withdrawals/", + "tests/prague/eip7251_consolidations/", + "tests/prague/eip7685_general_purpose_el_requests/", +]; + +/// The exceptions only a blob transaction raises, beyond the `TYPE_3_` ones. +const BLOB_EXCEPTIONS: [&str; 1] = ["TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS"]; + +/// The block exceptions about requests: the header's requests hash, the layout of a deposit event +/// a request is parsed from, and the post-block system call that dequeues requests. +const REQUEST_EXCEPTIONS: [&str; 3] = [ + "BlockException.INVALID_REQUESTS", + "BlockException.INVALID_DEPOSIT_EVENT_LAYOUT", + "BlockException.SYSTEM_CONTRACT_CALL_FAILED", +]; + +/// The block exceptions for a block's header or body that a node checks before execution. +/// +/// The list names what the pinned release expects; a block exception outside it, and outside +/// [`REQUEST_EXCEPTIONS`], is not skipped: the runner then requires the executor to refuse the +/// block, so a new one fails the gate until it is classified. +const HEADER_OR_BODY_EXCEPTIONS: [&str; 9] = [ + "BlockException.BLOB_GAS_USED_ABOVE_LIMIT", + "BlockException.INCORRECT_BLOB_GAS_USED", + "BlockException.INCORRECT_EXCESS_BLOB_GAS", + "BlockException.INVALID_BASEFEE_PER_GAS", + "BlockException.INVALID_BLOCK_HASH", + "BlockException.INVALID_GASLIMIT", + "BlockException.INVALID_WITHDRAWALS_ROOT", + "BlockException.RLP_BLOCK_LIMIT_EXCEEDED", + "BlockException.RLP_STRUCTURES_ENCODING", +]; + +/// The type of a blob transaction. +const BLOB_TX_TYPE: u8 = 3; + +/// Whether the test named `name`, in the fixture file at `path`, is skipped, and why: the first of +/// [`SkipReason::ALL`] that applies. +pub(crate) fn skip_test(path: &str, name: &str, test: &Test) -> Option { + let blocks = &test.blocks; + if blocks.iter().any(FixtureBlock::has_withdrawals) { + return Some(SkipReason::Withdrawals); + } + if blocks.iter().any(is_blob_block) { + return Some(SkipReason::BlobTransactions); + } + if REQUEST_TESTS.iter().any(|dir| name.starts_with(dir)) || + blocks.iter().any(|block| expects_only(block, &REQUEST_EXCEPTIONS)) + { + return Some(SkipReason::Requests); + } + if blocks.iter().any(|block| expects_only(block, &HEADER_OR_BODY_EXCEPTIONS)) { + return Some(SkipReason::HeaderOrBody); + } + if blocks + .iter() + .any(|block| block.expect_exception.is_some() && block.transactions().any(is_undecodable)) + { + return Some(SkipReason::UndecodableInvalidTransaction); + } + if crate::skips::skip_file(path) == Some(crate::skips::SkipReason::CreateCollisionWithStorage) { + return Some(SkipReason::CreateCollisionWithStorage); + } + None +} + +/// The type of an EIP-7702 transaction. +const SET_CODE_TX_TYPE: u8 = 4; + +/// Whether an OP block cannot encode `tx`: an EIP-7702 transaction without a recipient, or a fee +/// wider than the 128 bits OP's transaction types give it. +fn is_undecodable(tx: &FixtureTx) -> bool { + let wide = |fee: Option| fee.is_some_and(|fee| u128::try_from(fee).is_err()); + (tx.ty == Some(U256::from(SET_CODE_TX_TYPE)) && tx.to.is_none()) || + wide(tx.gas_price) || + wide(tx.max_fee_per_gas) || + wide(tx.max_priority_fee_per_gas) +} + +/// Whether `block` carries a blob transaction or expects an exception only one raises. +fn is_blob_block(block: &FixtureBlock) -> bool { + block.transactions().any(|tx| tx.ty == Some(U256::from(BLOB_TX_TYPE))) || + block.exception_names().any(|name| { + name.starts_with("TransactionException.TYPE_3_") || BLOB_EXCEPTIONS.contains(&name) + }) +} + +/// Whether `block` expects an exception, and every alternative it names is one of `names`. +fn expects_only(block: &FixtureBlock, names: &[&str]) -> bool { + let mut expected = block.exception_names().peekable(); + expected.peek().is_some() && expected.all(|name| names.contains(&name)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn test(blocks: serde_json::Value) -> Test { + serde_json::from_value(json!({ + "genesisRLP": "0x", + "blocks": blocks, + "pre": {}, + "postState": {}, + "lastblockhash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "config": { "chainid": "0x01", "blobSchedule": {} }, + })) + .expect("a test") + } + + fn reason(name: &str, blocks: serde_json::Value) -> Option { + skip_test("blockchain_tests/a/b.json", name, &test(blocks)) + } + + #[test] + fn test_a_plain_test_is_not_skipped() { + let blocks = + json!([{ "rlp": "0x", "transactions": [{ "type": "0x02" }], "withdrawals": [] }]); + assert_eq!(reason("tests/x.py::t", blocks), None); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.NONCE_MISMATCH_TOO_LOW" }]); + assert_eq!(reason("tests/x.py::t", blocks), None); + } + + #[test] + fn test_withdrawals_valid_or_not() { + let blocks = json!([{ "rlp": "0x", "withdrawals": [{ "index": "0x0" }] }]); + assert_eq!(reason("t", blocks), Some(SkipReason::Withdrawals)); + let blocks = json!([{ "rlp": "0x", "expectException": "BlockException.INVALID_WITHDRAWALS_ROOT", + "rlp_decoded": { "withdrawals": [{ "index": "0x0" }] } }]); + assert_eq!(reason("t", blocks), Some(SkipReason::Withdrawals)); + } + + #[test] + fn test_blob_transactions_valid_or_not() { + let blocks = json!([{ "rlp": "0x", "transactions": [{ "type": "0x03" }] }]); + assert_eq!(reason("t", blocks), Some(SkipReason::BlobTransactions)); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", + "rlp_decoded": { "transactions": [{ "type": "0x03" }] } }]); + assert_eq!(reason("t", blocks), Some(SkipReason::BlobTransactions)); + // A block whose RLP does not decode is a blob test by the exception it expects. + let blocks = json!([{ "rlp": "0x", "expectException": + "BlockException.RLP_STRUCTURES_ENCODING|TransactionException.TYPE_3_TX_WITH_FULL_BLOBS" }]); + assert_eq!(reason("t", blocks), Some(SkipReason::BlobTransactions)); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.INSUFFICIENT_MAX_FEE_PER_BLOB_GAS" }]); + assert_eq!(reason("t", blocks), Some(SkipReason::BlobTransactions)); + } + + #[test] + fn test_requests_by_name_or_exception() { + let plain = json!([{ "rlp": "0x" }]); + for dir in REQUEST_TESTS { + assert_eq!( + reason(&format!("{dir}test_x.py::t"), plain.clone()), + Some(SkipReason::Requests) + ); + } + assert_eq!(reason("tests/prague/eip6110_deposits/test_x.py::t", plain), None); + for name in REQUEST_EXCEPTIONS { + let blocks = json!([{ "rlp": "0x" }, { "rlp": "0x", "expectException": name }]); + assert_eq!( + reason("tests/prague/eip6110_deposits/t", blocks), + Some(SkipReason::Requests) + ); + } + } + + #[test] + fn test_header_or_body_only_when_every_alternative_is_one() { + for name in HEADER_OR_BODY_EXCEPTIONS { + let blocks = json!([{ "rlp": "0x", "expectException": name }]); + assert_eq!(reason("t", blocks), Some(SkipReason::HeaderOrBody), "{name}"); + } + let blocks = json!([{ "rlp": "0x", "expectException": + "BlockException.INVALID_WITHDRAWALS_ROOT|BlockException.INVALID_BLOCK_HASH" }]); + assert_eq!(reason("t", blocks), Some(SkipReason::HeaderOrBody)); + // An alternative the executor raises keeps the block compared. + let blocks = json!([{ "rlp": "0x", "expectException": + "BlockException.INVALID_GASLIMIT|TransactionException.GAS_ALLOWANCE_EXCEEDED" }]); + assert_eq!(reason("t", blocks), None); + // A block exception the list does not name is compared, not skipped. + let blocks = + json!([{ "rlp": "0x", "expectException": "BlockException.INVALID_STATE_ROOT" }]); + assert_eq!(reason("t", blocks), None); + } + + /// The classes are tested in order: a test with withdrawals and a blob transaction is skipped + /// for its withdrawals. + #[test] + fn test_the_first_class_that_applies() { + let blocks = json!([{ "rlp": "0x", "withdrawals": [{}], "transactions": [{ "type": "0x03" }], + "expectException": "BlockException.INVALID_GASLIMIT" }]); + assert_eq!(reason(REQUEST_TESTS[0], blocks), Some(SkipReason::Withdrawals)); + } + + /// A transaction an OP block cannot encode skips its test only when the fixture expects the + /// block to be invalid. + #[test] + fn test_undecodable_invalid_transactions() { + let set_code = json!({ "type": "0x04", "maxFeePerGas": "0x07" }); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.TYPE_4_TX_CONTRACT_CREATION", + "rlp_decoded": { "transactions": [set_code] } }]); + assert_eq!(reason("t", blocks), Some(SkipReason::UndecodableInvalidTransaction)); + let wide = json!({ "type": "0x00", "to": "0x0000000000000000000000000000000000000001", + "gasPrice": "0x0100000000000000000000000000000000" }); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", + "rlp_decoded": { "transactions": [wide] } }]); + assert_eq!(reason("t", blocks), Some(SkipReason::UndecodableInvalidTransaction)); + // A fee of exactly 128 bits encodes, and a set-code transaction with a recipient does. + let fits = json!({ "type": "0x02", "to": "0x0000000000000000000000000000000000000001", + "maxFeePerGas": "0xffffffffffffffffffffffffffffffff", "maxPriorityFeePerGas": "0x00" }); + let set_code_to = + json!({ "type": "0x04", "to": "0x0000000000000000000000000000000000000001" }); + let blocks = json!([{ "rlp": "0x", "expectException": "TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", + "rlp_decoded": { "transactions": [fits, set_code_to] } }]); + assert_eq!(reason("t", blocks), None); + // Valid blocks carry no such transaction; one would fail the gate rather than skip. + let blocks = json!([{ "rlp": "0x", "transactions": [{ "type": "0x04" }] }]); + assert_eq!(reason("t", blocks), None); + } + + /// The collision files are the state-test gate's, matched on the fixture's path. + #[test] + fn test_create_collisions_by_the_state_test_list() { + let plain = test(json!([{ "rlp": "0x" }])); + for path in [ + "blockchain_tests/paris/eip7610_create_collision/test_init_collision_create_tx.json", + "blockchain_tests/static/state_tests/stCreate2/create2collisionStorageParis.json", + ] { + assert_eq!(skip_test(path, "t", &plain), Some(SkipReason::CreateCollisionWithStorage)); + } + // The state-test gate's other skips are not this gate's. + for path in + ["blockchain_tests/a/ValueOverflowParis.json", "blockchain_tests/a/loopMul.json"] + { + assert_eq!(skip_test(path, "t", &plain), None); + } + } + + /// Every class has a reason of its own to print. + #[test] + fn test_every_class_has_a_distinct_reason() { + let reasons: std::collections::BTreeSet<_> = + SkipReason::ALL.iter().map(|reason| reason.reason()).collect(); + assert_eq!(reasons.len(), SkipReason::ALL.len()); + assert!(reasons.iter().all(|reason| !reason.is_empty())); + } + + #[test] + fn test_reason_names_round_trip() { + for reason in SkipReason::ALL { + assert_eq!(reason.name().parse::(), Ok(reason)); + } + assert!("slow".parse::().is_err()); + } +} diff --git a/crates/mega-state-test/src/deviations.rs b/crates/mega-state-test/src/deviations.rs new file mode 100644 index 000000000..0310ba950 --- /dev/null +++ b/crates/mega-state-test/src/deviations.rs @@ -0,0 +1,1521 @@ +//! The places Satin differs from Ethereum on purpose, and the fixture entries each one fails. +//! +//! Equivalence mode runs a fixture on Satin's machinery priced as the fixture's fork prices it, +//! so a failure there is either a bug or a rule `MegaETH` keeps that no configuration can turn +//! off. Every rule of the second kind is registered here, once, with the reason Satin keeps it and +//! the failures it explains; a failure no entry explains is unattributed, and one unattributed +//! failure fails the gate. +//! +//! A deviation lists every entry it explains on the pinned fixture release — the fixture file, +//! the test, the entry's data, gas and value indices — with the hashes Satin produces for it: the +//! state root, or for a logs mismatch the logs hash and the state root. It explains a failure only +//! of a listed entry and only with those hashes, so a listed entry that fails another way is +//! unattributed; and the gate requires every listed entry to fail exactly as listed, so one that +//! starts to pass, or stops running, fails the gate as surely as a new failure. The count of +//! failures a deviation explains is derived from its list. + +use core::fmt; + +use revm::primitives::b256; +use serde::Serialize; + +use crate::{ + blockchain, + runner::{Produced, TestId}, + Fork, +}; + +/// A place Satin differs from Ethereum on purpose. +#[derive(Debug, Serialize)] +pub struct Deviation { + /// A short, stable name. + pub id: &'static str, + /// The `MegaETH` rule the fixtures meet. + pub rule: &'static str, + /// Why Satin keeps the rule, and why the neutral configuration cannot express Ethereum's. + pub reason: &'static str, + /// The fork whose fixtures meet the rule. + pub fork: Fork, + /// Every entry of the fork's pinned fixture release the rule fails, in path, name and index + /// order. + pub entries: &'static [Entry], + /// Every blockchain test of the pinned main release the rule fails, in path and name order. + /// Only an Osaka deviation lists any: the blockchain tests run are the Osaka ones. + pub blockchain_entries: &'static [BlockchainEntry], +} + +/// A blockchain test a deviation explains: every block of it whose outcome is not its header's, +/// with the outcome Satin produces for it, and how the chain ends. +/// +/// The runner imports the whole chain, every listed block on Satin's own post-state, and holds +/// every block to its header or to its listed outcome exactly; a block that differs and is not +/// listed fails the test, as does a listed block that does not produce its listed outcome. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct BlockchainEntry { + /// The fixture file, relative to the release's `blockchain_tests` directory. + pub path: &'static str, + /// The test's name within the file. + pub name: &'static str, + /// Every block whose outcome is not its header's, in block order. + pub blocks: &'static [ListedBlock], + /// How the chain ends, and so whether its post-state is compared. + pub end: ChainEnd, +} + +/// A block of a listed blockchain test whose outcome is not its header's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ListedBlock { + /// What Satin produces for the block; its index is the block's. + pub produced: blockchain::Produced, + /// Why the block differs. + pub cause: Cause, +} + +/// Why a listed block's outcome is not its header's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Cause { + /// The deviation's rule acts in this block. + Rule, + /// The block runs as on Ethereum — its gas used, logs bloom and receipts root are its + /// header's — and its state root differs only by the state the listed block it names left + /// behind. The runner holds the claim: a block listed so whose own outcome differs, or that + /// names a block that is not an earlier listed one, fails the test. + StateLeftBy(usize), +} + +/// How a listed blockchain test's chain ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum ChainEnd { + /// The chain ends on a state its last block's header describes: its head and its post-state + /// are compared with the fixture's. + FixtureState, + /// The chain ends on a state a listed block left, which the fixture's post-state does not + /// describe: its head is compared with the fixture's and its post-state is not, for the + /// reason given. + DeviatedState(&'static str), +} + +/// A fixture entry a deviation explains, and the hashes Satin produces for it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Entry { + /// The fixture file, relative to the release's `state_tests` directory. + pub path: &'static str, + /// The test's name within the file. + pub name: &'static str, + /// The entry's data, gas and value indices. + pub indexes: (usize, usize, usize), + /// The hashes Satin produces for the entry, and with them how it fails. + pub produced: Produced, +} + +impl Deviation { + /// The entries the deviation lists for `fork`. + pub fn listed(&self, fork: Fork) -> &'static [Entry] { + if self.fork == fork { + self.entries + } else { + &[] + } + } + + /// The blockchain test `id`, as this deviation lists it, if it does. + pub fn blockchain_entry(&self, id: &blockchain::TestId) -> Option<&'static BlockchainEntry> { + self.blockchain_entries.iter().find(|entry| entry.is(id)) + } + + /// Whether a failure of the entry `id` of `fork`, which produced `produced`, is this + /// deviation's: the entry is listed, with exactly those hashes. + pub fn explains(&self, fork: Fork, id: &TestId, produced: Option) -> bool { + produced.is_some_and(|produced| { + self.listed(fork).iter().any(|entry| entry.produced == produced && entry.is(id)) + }) + } +} + +impl BlockchainEntry { + /// Whether `id` is this test: the same name, in a file whose path ends with this entry's path. + pub fn is(&self, id: &blockchain::TestId) -> bool { + id.name == self.name && path_ends_with(&id.path, self.path) + } +} + +impl BlockchainEntry { + /// The listed block at `index`, if the entry lists it. + pub fn block(&self, index: usize) -> Option<&'static ListedBlock> { + self.blocks.iter().find(|block| block.produced.block == index) + } +} + +/// The deviation in `registry` that lists the blockchain test `id`, and its entry for it. +/// +/// No test is listed by two deviations (a test checks it on the registry), so the first is the +/// one. +pub fn blockchain_entry( + registry: &'static [Deviation], + id: &blockchain::TestId, +) -> Option<(&'static Deviation, &'static BlockchainEntry)> { + registry.iter().find_map(|deviation| deviation.blockchain_entry(id).map(|e| (deviation, e))) +} + +impl fmt::Display for BlockchainEntry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} :: {}", self.path, self.name) + } +} + +/// Whether `path` ends with `suffix` on a path component boundary. +fn path_ends_with(path: &str, suffix: &str) -> bool { + let path = path.replace('\\', "/"); + path.strip_suffix(suffix).is_some_and(|dir| dir.is_empty() || dir.ends_with('/')) +} + +impl Entry { + /// Whether `id` is this entry: the same test and indices, in a file whose path ends with this + /// entry's path. + pub fn is(&self, id: &TestId) -> bool { + id.name == self.name && id.indexes == self.indexes && path_ends_with(&id.path, self.path) + } +} + +impl fmt::Display for Entry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (d, g, v) = self.indexes; + write!(f, "{} :: {} [d={d} g={g} v={v}]", self.path, self.name) + } +} + +/// Every registered deviation. +pub const DEVIATIONS: &[Deviation] = &[AMSTERDAM_OPCODES_ON_OSAKA, SELFDESTRUCT_BURNS_ON_OSAKA]; + +/// Satin's instruction table carries four Amsterdam opcodes on its Osaka base. +pub const AMSTERDAM_OPCODES_ON_OSAKA: Deviation = Deviation { + id: "amsterdam-opcodes-on-osaka", + rule: "Satin runs DUPN, SWAPN and EXCHANGE (EIP-8024) and SLOTNUM (EIP-7843), which its Osaka \ + base leaves undefined.", + reason: "Satin takes the Amsterdam schedule and the opcodes with it. The instruction table is \ + Satin's machinery, which equivalence mode keeps, so an Osaka fixture that executes \ + one of the four bytes, expecting the undefined-opcode halt Osaka gives it, runs the \ + opcode instead. With the four entries taken back out of the table, every Osaka \ + fixture passes.", + fork: Fork::Osaka, + blockchain_entries: &[ + BlockchainEntry { + path: "frontier/opcodes/test_all_opcodes.json", + name: "tests/frontier/opcodes/test_all_opcodes.py::test_all_opcodes[fork_Osaka-blockchain_test_from_state_test]", + blocks: &[ + ListedBlock { + produced: blockchain::Produced { + block: 0, + gas_used: 8_129_268, + logs_bloom_hash: b256!( + "0xbe67c3e27ea8993a93e1784dfad43146e9c48f71d7d56dfd86d6c1041920b232" + ), + receipts_root: b256!( + "0xa8efe1faeb804a16183cc48903e6d13ed9c9786bfb146708b605feb6448bdd93" + ), + state_root: b256!( + "0x311f0607743b16ef7eb341125d364a002eaceb2f05ac936bbd0f839865d2711d" + ), + }, + cause: Cause::Rule, + }, + ], + end: ChainEnd::DeviatedState( + "its one block runs the four opcodes Osaka halts on, so the chain ends on the state they leave", + ), + }, + BlockchainEntry { + path: "frontier/scenarios/test_scenarios.json", + name: "tests/frontier/scenarios/test_scenarios.py::test_scenarios[fork_Osaka-blockchain_test-test_program_program_INVALID-debug]", + blocks: &[ + ListedBlock { + produced: blockchain::Produced { + block: 0, + gas_used: 5_386_221, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf" + ), + state_root: b256!( + "0x50cc3c920ca4d635bb156978614d544911917dda2314da86c6ae47f86d8668ff" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 1, + gas_used: 5_386_221, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf" + ), + state_root: b256!( + "0x7a432172471d48e4eabea2f6f7843ae1dc13ba9db35ebb90ea7b71e2797381b8" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 2, + gas_used: 5_386_224, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xc8a1e306c05c6c22dcc04fb01dd3e84c3ba16088eccf053cfa10c07d1d604c89" + ), + state_root: b256!( + "0x6492319287311df06e117d1bf0167868072f0ec0522a168cbae279e88f6edeb5" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 3, + gas_used: 5_386_224, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xc8a1e306c05c6c22dcc04fb01dd3e84c3ba16088eccf053cfa10c07d1d604c89" + ), + state_root: b256!( + "0x8b428b568632e6056542468c6fc7ed031c32db3a7b7286b04285b6e735c30a53" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 4, + gas_used: 5_376_889, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x44b3958d3a4da284d93cd9413fdd02affc4fa0d2c2ae0dd4e08c98a38d7a6504" + ), + state_root: b256!( + "0xfa2a2f0e8f686cc0f5d1bf7d01f6048c17795b0d6f8c319816742ada3d5353ed" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 5, + gas_used: 5_386_221, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf" + ), + state_root: b256!( + "0xd76637032c7aba3c937f7fbe047a1bc277dccd78377e63681570ebeb239ab721" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 6, + gas_used: 5_386_221, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x55de3d2d9f2c2c5622556508e5cda2ddca148e43439eb16a46115b797792d3bf" + ), + state_root: b256!( + "0xc4217d76247c681511a0c3e6b7bb5712fc08c8e08f8d666992cb24d40ab3b7e5" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 7, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0x150535f0c70945d4025bbd207f255412568187ff74ec5c4f068a6c3159a1b215" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 8, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0xca8b4f50f5ee3e3b992db528da9cf18d3495161478583903f26d7c58590c434b" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 9, + gas_used: 5_376_889, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x44b3958d3a4da284d93cd9413fdd02affc4fa0d2c2ae0dd4e08c98a38d7a6504" + ), + state_root: b256!( + "0x32c1d16829c873e7f9762e026d6d9e7f007aedf4b96c60a7a774d70cf68652ab" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 10, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0x3c04b7a4296b76ee622d099c6a7e5195cf9884f4e005a452dc24f431fe8679ca" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 11, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0x3c2819d923e552d459a255be2e68e04210cac0b31ca3fb45bce60b5ff9cfdfcd" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 12, + gas_used: 5_399_627, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26" + ), + state_root: b256!( + "0x8646405e196a3332ee3bb75af4cb1ba7f0c51c646c1f74fe88193f9971d27019" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 13, + gas_used: 5_399_627, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26" + ), + state_root: b256!( + "0xc95eee62b72c78d47f25497acb8715f3ed6c6b1ef1cf48fc5810bef03c87d26e" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 14, + gas_used: 5_383_592, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x1b4b33d4f2db7ecb0071a2ed95938ca5bf97df8c4c259c1b1542ee79cfad93b4" + ), + state_root: b256!( + "0x4f98fc50f394e6a3264df2c21dc77d9d0f0134b741f1faf42654ed1e9b3e2ea9" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 15, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0x1ee283e5862adf81f60e3cef87613b7f7dc02b3eef325e2246a212e24ad439bc" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 16, + gas_used: 5_392_924, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x20e47a185042afce840b786dcbf99dea66b1488180e2cce569511d133fcb4344" + ), + state_root: b256!( + "0xf72728582c1345a0b218adf1baa60e68cfa6d1bb9f16fb3d9c83be03d277f9b4" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 17, + gas_used: 5_399_627, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26" + ), + state_root: b256!( + "0xc9b1b1e13a3ae1a8640ca3204c1bcb5b82dcc01a75135105ad2ad43629708305" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 18, + gas_used: 5_399_627, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x5532612bb2ec2b05606828aafab98443ddeede215ae17df462f7b6859e9fff26" + ), + state_root: b256!( + "0xe5521ec635fa43963276146cd72c55fcd3119123c1fdbab42667de6c76b6b86b" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 19, + gas_used: 5_383_592, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x1b4b33d4f2db7ecb0071a2ed95938ca5bf97df8c4c259c1b1542ee79cfad93b4" + ), + state_root: b256!( + "0x7ca5f100fa3a11694d1fb64a2c57359f2bc60aa9f492413dd47c93936d2efb10" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 20, + gas_used: 5_412_989, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xa22daee9f564b06c805a9b32ba0f6b26e267388fe3bd24de782c7a8e3bd3200c" + ), + state_root: b256!( + "0xd70438c04dd69c9d1c2450a8f719e89c530aa86da49e4f1de4806b6d5219113a" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 21, + gas_used: 5_412_974, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x02e92ec835e38ac88ac8bb94790955bf8aadc3d53b34733e4fa77fd18bda5f82" + ), + state_root: b256!( + "0x7e69c5919cf9e7a663ccc53d78b3dd11128f65809862a53a58d12c12dfec4d50" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 22, + gas_used: 5_425_218, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xae1970250c7686623887a6629c3b89de2107591e74db05483e6cfa549d83721d" + ), + state_root: b256!( + "0x3d2e7d5f919008960dc9043f0aff0fcd960c6324d07900feb6be5d7829c9e25d" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 23, + gas_used: 5_425_218, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xae1970250c7686623887a6629c3b89de2107591e74db05483e6cfa549d83721d" + ), + state_root: b256!( + "0xc76d312ba2294d1e2a2e4744c47948d97e23effc4f884f6afe2d92c56971d00c" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 24, + gas_used: 5_431_921, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x80d1b6b1cc4c436be347448203fe33fb20a10269a969d4d7584607e81e20a523" + ), + state_root: b256!( + "0x9795b537f1c4a81c45ecbd68cd6a768f1edf4851c1af2f58dd36df2ce990a60c" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 25, + gas_used: 5_431_921, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x80d1b6b1cc4c436be347448203fe33fb20a10269a969d4d7584607e81e20a523" + ), + state_root: b256!( + "0xd520334239c6aca8938bcc6000730ab1d092abb057e8a9e9d48bec67d09b561d" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 26, + gas_used: 5_425_197, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x4592127747c3ae6dcf115d65b2cce745607a8318fe7f8e664e0555193ffb7e56" + ), + state_root: b256!( + "0x68bd60a5015b88c0b8e7e185f8be77cfdb27cd5589f1f215d98b7678bc414d76" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 27, + gas_used: 5_425_197, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x4592127747c3ae6dcf115d65b2cce745607a8318fe7f8e664e0555193ffb7e56" + ), + state_root: b256!( + "0x7dd74978b8093b1e70baf3100ae39040303bcda411a13beec70e22ee72a29833" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 28, + gas_used: 5_431_900, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x95c628e38ba7c4cfe057b1f25eabf4839e440366a6ac77af656eb6e613363a1d" + ), + state_root: b256!( + "0x757f6d279391869cc5645519509c639664976d262443f14c260ea0dd6555a9bc" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 29, + gas_used: 5_431_900, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x95c628e38ba7c4cfe057b1f25eabf4839e440366a6ac77af656eb6e613363a1d" + ), + state_root: b256!( + "0x112f123f5e1e6bb8b62435629d05b78b41241e7cad87f164fdfc5251514fdaab" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 30, + gas_used: 5_354_342, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x77d8bb582b975327486b5eaf11eefab2c24f4d7eea18a068393a0bf07fe4a12f" + ), + state_root: b256!( + "0xdd0f896ef11e7b76ca47798934817924b7ff6d4f69a6332dc58479a91bed4bae" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 31, + gas_used: 6_996_648, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x11e83acea62ae5fa281bbc0e08cbb0e8096b6639aa23b482e09be96b634478d1" + ), + state_root: b256!( + "0x62884511e634038fe0d74ba175861b715288e3f0f22ef2d833e90308b3d692e7" + ), + }, + cause: Cause::StateLeftBy(30), + }, + ListedBlock { + produced: blockchain::Produced { + block: 32, + gas_used: 5_374_242, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x49e5cee7b540b0aa0c1da72b0f14ce1c6f0462b9a5d912dc2d07f025d9703c47" + ), + state_root: b256!( + "0x50aa0f67eadbc50b215297d51f9963dab59f8820c0f5175eb236bc6a58eab823" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 33, + gas_used: 10_692_884, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x11f8bdf99c03a9e5a4434febe2b60a3d448beea5a90859e9aeaf64f1a7f39aa9" + ), + state_root: b256!( + "0x42f64807cbdc63fd10bff15150e7d7a6a49d74706107891f9ef43c3b81573473" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 34, + gas_used: 10_742_872, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xb46d2b23868948b3dca1ee22d01e7555454b3299a9b46938b0468425524b6d62" + ), + state_root: b256!( + "0x6124ecf0c28fafaf690def9ad816ed272a9111021599e3ffb0dcf12174de6682" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 35, + gas_used: 10_692_890, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xc23d5fbdb417f4a15b3c25cb25d1aa377be4e3534f218c075e24a27fcffc6e41" + ), + state_root: b256!( + "0xf9001fb3d1ba34652291e969f128d8ad39018e0addaae5b73c84184e4add58b8" + ), + }, + cause: Cause::Rule, + }, + ListedBlock { + produced: blockchain::Produced { + block: 36, + gas_used: 10_692_890, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0xc23d5fbdb417f4a15b3c25cb25d1aa377be4e3534f218c075e24a27fcffc6e41" + ), + state_root: b256!( + "0xba79f738e1ded0240a5c87b6ee54daa4e0352b497af0ae1886df1234dbfd47e3" + ), + }, + cause: Cause::Rule, + }, + ], + end: ChainEnd::DeviatedState( + "every block runs the program's four opcodes Osaka halts on or carries the state they left, so the chain ends on that state", + ), + }, + BlockchainEntry { + path: "static/state_tests/stBadOpcode/undefinedOpcodeFirstByte.json", + name: "tests/static/state_tests/stBadOpcode/undefinedOpcodeFirstByteFiller.yml::undefinedOpcodeFirstByte[fork_Osaka-blockchain_test_from_state_test-]", + blocks: &[ + ListedBlock { + produced: blockchain::Produced { + block: 0, + gas_used: 3_969_244, + logs_bloom_hash: b256!( + "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" + ), + receipts_root: b256!( + "0x9a8f3b88fe2bb353fe86d44bd5be426458c3544f423b8e70f0dff0a06c9634bc" + ), + state_root: b256!( + "0xa1527ad75667d1f7455aa215c374f3c21c9fde318ec9fb652ee9c8fac11dc72b" + ), + }, + cause: Cause::Rule, + }, + ], + end: ChainEnd::DeviatedState( + "its one block runs the four opcodes Osaka halts on, so the chain ends on the state they leave", + ), + }, + + ], + entries: &[ + Entry { + path: "frontier/opcodes/test_all_opcodes.json", + name: "tests/frontier/opcodes/test_all_opcodes.py::test_all_opcodes[fork_Osaka-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x2790bb00bde351feb12b3607acea67097e9f7d0a3913d61c7269c3603a77b8c5" + )), + }, + Entry { + path: "static/state_tests/stBadOpcode/undefinedOpcodeFirstByte.json", + name: "tests/static/state_tests/stBadOpcode/undefinedOpcodeFirstByteFiller.yml::undefinedOpcodeFirstByte[fork_Osaka-state_test-]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xefc47fa41b70e7a1b1aa1ac3c0b04af29ccb2ed2f766fe42ff764e1f3b9fe0de" + )), + }, + ], +}; + +/// A contract self-destructed in its creating transaction is removed as on Satin's Osaka base, +/// where Amsterdam keeps a balance it sent to itself (EIP-8246). +pub const SELFDESTRUCT_BURNS_ON_OSAKA: Deviation = Deviation { + id: "selfdestruct-burns-on-osaka", + rule: "A contract self-destructed in the transaction that created it is removed as on Satin's \ + Osaka base, a balance it sent to itself burned: EIP-8246, which keeps that balance and \ + clears the account only at the end of the transaction, is not active.", + reason: "revm gates EIP-8246 on the Amsterdam spec id, in the journal, and Satin's spec runs \ + on Karst, an Osaka base: Satin takes Amsterdam's rules one switch at a time — EIP-8037, \ + EIP-2780, the opcodes — and EIP-8246 has no switch, so no configuration can turn it \ + on. An Amsterdam fixture in which a contract destructs to itself expects the balance \ + kept, and the EIP-7708 transfer logs a kept balance produces when it is sent on. revm \ + itself, on an Osaka base with Amsterdam's configuration, produces exactly the hashes \ + listed for every one of these entries, and the fixtures' own on the Amsterdam spec. \ + Whether Satin takes EIP-8246 is a decision for its specification, not for this gate.", + fork: Fork::Amsterdam, + blockchain_entries: &[], + entries: &[ + Entry { + path: "for_amsterdam/amsterdam/eip2780_reduce_intrinsic_tx_gas/top_frame_charges/initcode_selfdestruct_keeps_top_frame_state_charge.json", + name: "tests/amsterdam/eip2780_reduce_intrinsic_tx_gas/test_top_frame_charges.py::test_initcode_selfdestruct_keeps_top_frame_state_charge[fork_Amsterdam-state_test-non-zero_value-self_beneficiary]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x8a227aa6adf983ba803d01b09126eb9d226cf95a1e083f194c39f0e29e8a1e44" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json", + name: "tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_call.py::test_call_value_to_self_destructed_same_tx_account[fork_Amsterdam-state_test-create2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x5857f66aee23a75fbc2b874e871eb146226ff2dab2194b4597cb87b9b954347c" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_call/call_value_to_self_destructed_same_tx_account.json", + name: "tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_call.py::test_call_value_to_self_destructed_same_tx_account[fork_Amsterdam-state_test-create]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x13370ccc6e5eb2bf5a75774bef80223d973990a429e9a3a6e2abe32eea70d091" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip8037_state_creation_gas_cost_increase/state_gas_selfdestruct/selfdestruct_to_self_in_create_tx.json", + name: "tests/amsterdam/eip8037_state_creation_gas_cost_increase/test_state_gas_selfdestruct.py::test_selfdestruct_to_self_in_create_tx[fork_Amsterdam-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xd1e99d8e4322d56db48a9c6fbf91231d405a592394fe30943639d7bb8e4af3e9" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip8038_state_access_gas_cost_increase/selfdestruct_gas/same_tx_created_selfdestruct_self_burn.json", + name: "tests/amsterdam/eip8038_state_access_gas_cost_increase/test_selfdestruct_gas.py::test_same_tx_created_selfdestruct_self_burn[fork_Amsterdam-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x60ec6fdd1f4b9afbf1f6bae43abbc3a21fc917cf921bc7f43827d2dda86f411b" + )), + }, + Entry { + path: "for_amsterdam/amsterdam/eip8246_selfdestruct_no_burn/selfdestruct_no_burn/create_transaction_initcode_selfdestruct.json", + name: "tests/amsterdam/eip8246_selfdestruct_no_burn/test_selfdestruct_no_burn.py::test_create_transaction_initcode_selfdestruct[fork_Amsterdam-state_test-kept]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x8a227aa6adf983ba803d01b09126eb9d226cf95a1e083f194c39f0e29e8a1e44" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x5c00fce098c2fe994de7c23a67990d729c20a258651d132e2b21c3a2d0b5803a"), + state_root: b256!("0x2f2356140f67ac4504ff5f416e56edd0264e8ec19ed39ac6f8897b9023d27307"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x6aa38fb5b844e13cd8efa6b776f957550e0a4b27815a2f34cf3fa9bc4cae730e"), + state_root: b256!("0xf08b417e5ac7138f3e58e07dc90970a2780901935979e0a3010ba8ebe5aae924"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0xc6f151ee88a456efe8faee5993fac962f32645dd408bdf75e86a411e4d2b5b35"), + state_root: b256!("0xd42fe0ac1ad09661381fc6c43ee67a7c169bcb4610e89ec0c60aaa793d8831c4"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0xf76e4fa7500c4db34112ba382a1365e5503307c1ae300be79fa59550ba4eef32"), + state_root: b256!("0x9903a0c8f461940cadd5f48ea90bddfe1f019182c65d3f6a6b2533d336199063"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x2c2102d3296f1610fdf87d1182226cd4e793882caa71c96f965f0e5e7af21590" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x7cb1c8d882ce555bf85cff9961ebde8c14542d96d2394935edbf95b745c5265f" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_single_self_recipient-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xa695e4f522a7e47293590084faa0dc45ab419b7c0a2449808fd7e2a716968c80" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-multiple_calls_single_self_recipient-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x97844214d20796ee78c52c1d5a6338e21dfa8bdf6031a19cc359b9c46d5da076" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x5c00fce098c2fe994de7c23a67990d729c20a258651d132e2b21c3a2d0b5803a"), + state_root: b256!("0x7db1f7e8a7499e52962e8b457cbaa28545b035ec6d3491621ad8a10f0abcfec4"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x6aa38fb5b844e13cd8efa6b776f957550e0a4b27815a2f34cf3fa9bc4cae730e"), + state_root: b256!("0x7ae7c17d34642ed4d4a56e2613cc50ab5eeb617b5b2c965f946de58060b99447"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x79545168c90d8fed276adcd2bfe3610a0ba259044ba117fb9cafb0bcbbf3a3df"), + state_root: b256!("0x4f389b292dedd1e7effa9c1947e9ec9fb83a40f049f9cf4b87262e1d96c9682a"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_repeating_sendall_recipients_including_self_last-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x7c73347bddfb53f07057096e6949c82c32d3fb61532a008261cbf1bf43fcd19e"), + state_root: b256!("0x254f07b354bf3e97b96e4a06ddee51489ca23a71fb6e088df9f460c35d880698"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x4bd3e188f8d440a5762a67eb84a9d133a6e2979fb68d7414b1e0a08bcee83d48"), + state_root: b256!("0x807ff3a9c69267c578eae95089ba8087582eb630fe514aae537500b9edbcf880"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::Logs { + logs: b256!("0x88bd5130a835f0eb5cce6c8229e768ae96dec7a79cd757dca32b5e3ce57b86b0"), + state_root: b256!("0xe331c545e628b14d64deccaac85755e699f0e75aba8189847ed810e4a4f0ddf8"), + }, + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xfbd1f3e7d906012db567e5429e1236dab7466d40798973c4dc4ba2984d621f72" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_multiple_sendall_recipients_including_self_last-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xd75f439c744aae2d05d0151919fa298073b99086c3af81087202b5c4464b2a02" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_single_self_recipient-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x1c0a70089f50f9da9183fa04210ae0f04affc03d146fcb78d32f3c5ef2853a47" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-multiple_calls_single_self_recipient-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x0c7614fbae22b3855669bfe3ee994bc18b31b32d84903a0372834f966a265b8d" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-single_call_self-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xaa95dfb767c86d4d4c261252b2a6224f32d15955eaf92650c4c97bb5c7892d95" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/create_selfdestruct_same_tx.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_create_selfdestruct_same_tx[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-single_call_self-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x9c91de53b0bc52572ca1c1ea6ccffcf42f725876a8f439ae676b7cdf9567d43a" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-call_times_2-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xdc78c509c41771960af990fbbcf5dbd0e6f72e8a6615bcb5cc1b75c8f12dc0bd" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_0-call_times_2-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x8eda22cdda403dd638ac173e1e6e648414d1d20aa8559e3a26af76939eda5d4b" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-call_times_2-create_opcode_CREATE2]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x998432460e11445f1529c1fde7e70e3c97818e9af0d2b3180e2329bd719d5e4c" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct/self_destructing_initcode.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct.py::test_self_destructing_initcode[fork_Amsterdam-state_test-selfdestruct_contract_initial_balance_100000-call_times_2-create_opcode_CREATE]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x6989f4cf277b4f10675e678976e0ffde965e2d23634946b31f42e61b948fe31f" + )), + }, + Entry { + path: "for_amsterdam/cancun/eip6780_selfdestruct/selfdestruct_revert/selfdestruct_created_in_same_tx_with_revert.json", + name: "tests/cancun/eip6780_selfdestruct/test_selfdestruct_revert.py::test_selfdestruct_created_in_same_tx_with_revert[fork_Amsterdam-state_test-outer_selfdestruct_before_inner_call-same_tx]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x68de4499d08d8c9e6260ade80ed6a4203630f49dc1947b2312d308a7fd104e40" + )), + }, + Entry { + path: "for_amsterdam/frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json", + name: "tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_False]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x723798b921cd0f3a700aa00dffcb87da7df2440def96d3ed96b36e2bc0a1e545" + )), + }, + Entry { + path: "for_amsterdam/frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json", + name: "tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_True]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xd82f53b114fbab4d8784e89069ef7b272e1d74f2cc26a363f96141b9eb771b6c" + )), + }, + Entry { + path: "for_amsterdam/frontier/create/create_suicide_during_init/create_suicide_during_transaction_create.json", + name: "tests/frontier/create/test_create_suicide_during_init.py::test_create_suicide_during_transaction_create[fork_Amsterdam-create_opcode_CREATE2-state_test-operation_Operation.SUICIDE_TO_ITSELF-transaction_create_False]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x52695eb8bf3c83b205d4cfd24acb88af856a2db2ec5236e66202833d8aa94f3c" + )), + }, + Entry { + path: "for_amsterdam/ported_static/stCreate2/create2_suicide/create2_suicide.json", + name: "tests/ported_static/stCreate2/test_create2_suicide.py::test_create2_suicide[fork_Amsterdam-state_test-d6]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xe6d927efd83aabb7d94664d06b79744a361a74374f377f6c8dd31307e577ccde" + )), + }, + Entry { + path: "for_amsterdam/ported_static/stCreate2/create2_suicide/create2_suicide.json", + name: "tests/ported_static/stCreate2/test_create2_suicide.py::test_create2_suicide[fork_Amsterdam-state_test-d7]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0x087df75fad91a65e75b9373ad835882429c431166f9a3e6d086206cd39e2f662" + )), + }, + Entry { + path: "for_amsterdam/ported_static/stInitCodeTest/transaction_create_suicide_in_initcode/transaction_create_suicide_in_initcode.json", + name: "tests/ported_static/stInitCodeTest/test_transaction_create_suicide_in_initcode.py::test_transaction_create_suicide_in_initcode[fork_Amsterdam-state_test]", + indexes: (0, 0, 0), + produced: Produced::StateRoot(b256!( + "0xf6456935a8fdccc4fa60c10233d27e602088fdfbce68c9db41363767cffd367d" + )), + }, + ], +}; + +/// The deviation in `registry` that explains a failure of the entry `id` of `fork`, which +/// produced `produced`, if one does. +/// +/// No entry is listed by two deviations (a test checks it on the registry), so the first that +/// explains a failure is the one. +pub fn attribute( + registry: &'static [Deviation], + fork: Fork, + id: &TestId, + produced: Option, +) -> Option<&'static Deviation> { + registry.iter().find(|deviation| deviation.explains(fork, id, produced)) +} + +/// The registry as the crate's `DEVIATIONS.md` has it, one sentence to a line. +pub fn render_markdown() -> String { + let sentences = |text: &str| text.replace(". ", ".\n"); + let mut out = String::from( + "# Deviations\n\n\ + \n\n\ + The places Satin differs from Ethereum on purpose that the execution-spec gate meets, \ + each with the fixture entries it explains and the hashes Satin produces for them.\n\ + In equivalence mode a failure is a deviation's only when the deviation lists its entry \ + with the hashes it produced, and every listed entry must fail exactly as listed: a \ + failure no deviation explains, and a listed entry that passes or fails another way, \ + fail the gate.\n", + ); + for deviation in DEVIATIONS { + out.push_str(&format!("\n## `{}`\n\n", deviation.id)); + out.push_str(&format!( + "{} failed entries of the pinned {} fixtures.\n\n", + deviation.entries.len(), + deviation.fork + )); + out.push_str(&format!("**Rule.**\n{}\n\n", sentences(deviation.rule))); + out.push_str(&format!("**Reason.**\n{}\n\n", sentences(deviation.reason))); + out.push_str( + "**Failures.** Each entry with its data, gas and value indices, how it fails and the \ + hashes Satin produces; paths are relative to the release's `state_tests` \ + directory.\n\n", + ); + let mut path = ""; + for entry in deviation.entries { + if entry.path != path { + path = entry.path; + out.push_str(&format!("- `{path}`\n")); + } + let (d, g, v) = entry.indexes; + let hashes = match entry.produced { + Produced::StateRoot(root) => format!("state root `{root}`"), + Produced::Logs { logs, state_root } => { + format!("logs hash `{logs}`, state root `{state_root}`") + } + }; + out.push_str(&format!( + " - `{}` d={d} g={g} v={v}: `{}`, {hashes}\n", + entry.name, + entry.produced.kind().name() + )); + } + if !deviation.blockchain_entries.is_empty() { + out.push_str(&format!( + "\n**Blockchain tests.** {} tests of the pinned main release's `blockchain_tests`, \ + each with every block whose outcome is not its header's — the gas used, the keccak \ + hash of the logs bloom, the receipts root and the state root Satin produces for it, \ + and why it differs — and how the chain ends; every other block of the test matches \ + its header, and paths are relative to the release's `blockchain_tests` \ + directory.\n\n", + deviation.blockchain_entries.len() + )); + for entry in deviation.blockchain_entries { + out.push_str(&format!("- `{}`\n - `{}`\n", entry.path, entry.name)); + for listed in entry.blocks { + let produced = listed.produced; + let cause = match listed.cause { + Cause::Rule => "the rule acts".to_string(), + Cause::StateLeftBy(block) => format!("the state block {block} left"), + }; + out.push_str(&format!( + " - block {} ({cause}): gas used {}, logs bloom hash `{}`, receipts \ + root `{}`, state root `{}`\n", + produced.block, + produced.gas_used, + produced.logs_bloom_hash, + produced.receipts_root, + produced.state_root + )); + } + let end = match entry.end { + ChainEnd::FixtureState => { + "the chain ends on its last header's state; its head and post-state are \ + compared" + .to_string() + } + ChainEnd::DeviatedState(reason) => format!( + "the chain ends on a state a listed block left; its head is compared and \ + its post-state is not: {reason}" + ), + }; + out.push_str(&format!(" - End: {end}.\n")); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runner::FailureKind; + use revm::primitives::B256; + use std::collections::BTreeSet; + + fn id(entry: &Entry, dir: &str) -> TestId { + TestId { + path: format!("{dir}{}", entry.path), + name: entry.name.into(), + entry: 0, + indexes: entry.indexes, + } + } + + #[test] + fn test_ids_are_unique_and_every_entry_is_complete() { + let ids: BTreeSet<_> = DEVIATIONS.iter().map(|d| d.id).collect(); + assert_eq!(ids.len(), DEVIATIONS.len(), "duplicate deviation id"); + for deviation in DEVIATIONS { + assert!(!deviation.rule.is_empty() && !deviation.reason.is_empty(), "{}", deviation.id); + assert!( + !deviation.entries.is_empty(), + "{}: a deviation that lists nothing", + deviation.id + ); + for entry in deviation.entries { + assert!(!entry.name.is_empty(), "{}: {entry}", deviation.id); + assert!( + entry.path.ends_with(".json") && + !entry.path.starts_with('/') && + !entry.path.contains('\\') && + entry.path.split('/').all(|part| !part.is_empty() && part != ".."), + "{}: {} is not a path relative to `state_tests`", + deviation.id, + entry.path + ); + assert!( + matches!( + entry.produced.kind(), + FailureKind::StateRootMismatch | FailureKind::LogsMismatch + ), + "{}: {entry}", + deviation.id + ); + } + assert_eq!(deviation.listed(deviation.fork).len(), deviation.entries.len()); + for fork in Fork::ALL.into_iter().filter(|fork| *fork != deviation.fork) { + assert!(deviation.listed(fork).is_empty(), "{}", deviation.id); + } + } + } + + /// Only an Osaka deviation lists blockchain tests, each complete, in path and name order, each + /// once across the registry, its blocks in order and its causes naming earlier listed blocks; + /// an entry is the test's wherever the release's `blockchain_tests` directory is. + #[test] + fn test_blockchain_entries() { + let mut all = BTreeSet::new(); + for deviation in DEVIATIONS { + if deviation.fork != Fork::Osaka { + assert!(deviation.blockchain_entries.is_empty(), "{}", deviation.id); + } + let keys: Vec<_> = + deviation.blockchain_entries.iter().map(|e| (e.path, e.name)).collect(); + assert!( + keys.windows(2).all(|pair| pair[0] < pair[1]), + "{}: out of order", + deviation.id + ); + for entry in deviation.blockchain_entries { + assert!(all.insert((entry.path, entry.name)), "{entry} is listed twice"); + assert!( + !entry.name.is_empty() && + entry.path.ends_with(".json") && + !entry.path.starts_with('/') && + entry.path.split('/').all(|part| !part.is_empty() && part != ".."), + "{}: {entry}", + deviation.id + ); + // Blocks are listed once each, in block order, and a block whose state an earlier + // block left names a listed block before it. + assert!(!entry.blocks.is_empty(), "{entry}: lists no block"); + let indexes: Vec<_> = entry.blocks.iter().map(|b| b.produced.block).collect(); + assert!(indexes.windows(2).all(|pair| pair[0] < pair[1]), "{entry}: block order"); + for listed in entry.blocks { + assert_eq!(entry.block(listed.produced.block), Some(listed)); + if let Cause::StateLeftBy(earlier) = listed.cause { + assert!(earlier < listed.produced.block, "{entry}: a later block named"); + assert!(entry.block(earlier).is_some(), "{entry}: an unlisted block named"); + } + } + if let ChainEnd::DeviatedState(reason) = entry.end { + assert!(!reason.is_empty(), "{entry}: an end without a reason"); + } + // The entry is the test's wherever the release's directory is, and nowhere else. + for dir in ["", "fixtures/main/blockchain_tests/", "/tmp/x/blockchain_tests/"] { + let id = blockchain::TestId { + path: format!("{dir}{}", entry.path), + name: entry.name.into(), + }; + assert_eq!(deviation.blockchain_entry(&id), Some(entry)); + let (found, _) = blockchain_entry(DEVIATIONS, &id).expect("listed"); + assert_eq!(found.id, deviation.id); + } + let elsewhere = blockchain::TestId { + path: format!("x{}", entry.path), + name: entry.name.into(), + }; + assert!(blockchain_entry(DEVIATIONS, &elsewhere).is_none()); + let renamed = blockchain::TestId { + path: entry.path.into(), + name: format!("{}x", entry.name), + }; + assert!(blockchain_entry(DEVIATIONS, &renamed).is_none()); + } + } + } + + /// Entries are listed in path, name and index order, each once, and no entry is listed by two + /// deviations. + #[test] + fn test_entries_are_ordered_and_disjoint() { + let mut all = BTreeSet::new(); + for deviation in DEVIATIONS { + let keys: Vec<_> = + deviation.entries.iter().map(|e| (e.path, e.name, e.indexes)).collect(); + assert!( + keys.windows(2).all(|pair| pair[0] < pair[1]), + "{}: entries out of order or listed twice", + deviation.id + ); + for key in keys { + assert!(all.insert((deviation.fork, key)), "{key:?} is listed twice"); + } + } + } + + /// Every listed entry is attributed to its deviation with the hashes it lists, wherever the + /// release's `state_tests` directory is; with any other hashes, or none, it is attributed to + /// nothing, and neither is the same entry of another fork. + #[test] + fn test_an_entry_is_explained_only_with_its_hashes() { + for deviation in DEVIATIONS { + for entry in deviation.entries { + for dir in ["", "fixtures/main/state_tests/", "/tmp/x/state_tests/"] { + let id = id(entry, dir); + let explained = + attribute(DEVIATIONS, deviation.fork, &id, Some(entry.produced)); + assert_eq!(explained.map(|d| d.id), Some(deviation.id), "{entry}"); + } + let id = id(entry, "fixtures/"); + let other = match entry.produced { + Produced::StateRoot(root) => { + Produced::Logs { logs: B256::repeat_byte(1), state_root: root } + } + Produced::Logs { state_root, .. } => Produced::StateRoot(state_root), + }; + assert!(attribute(DEVIATIONS, deviation.fork, &id, Some(other)).is_none()); + assert!(attribute(DEVIATIONS, deviation.fork, &id, None).is_none()); + for fork in Fork::ALL.into_iter().filter(|fork| *fork != deviation.fork) { + assert!(attribute(DEVIATIONS, fork, &id, Some(entry.produced)).is_none()); + } + } + } + } + + /// An entry is its own test and indices in a file whose path ends with the entry's path, on + /// a path component boundary. + #[test] + fn test_an_entry_is_matched_by_its_whole_id() { + let entry = Entry { + path: "cancun/a.json", + name: "t", + indexes: (1, 2, 3), + produced: Produced::StateRoot(B256::ZERO), + }; + let at = |path: &str, name: &str, indexes| TestId { + path: path.into(), + name: name.into(), + entry: 0, + indexes, + }; + assert!(entry.is(&at("cancun/a.json", "t", (1, 2, 3)))); + assert!(entry.is(&at("fixtures/state_tests/cancun/a.json", "t", (1, 2, 3)))); + assert!(entry.is(&at("fixtures\\state_tests\\cancun\\a.json", "t", (1, 2, 3)))); + assert!(!entry.is(&at("fixtures/xcancun/a.json", "t", (1, 2, 3)))); + assert!(!entry.is(&at("fixtures/cancun/a.json/b.json", "t", (1, 2, 3)))); + assert!(!entry.is(&at("fixtures/cancun/a.json", "u", (1, 2, 3)))); + assert!(!entry.is(&at("fixtures/cancun/a.json", "t", (1, 2, 4)))); + assert!(!entry.is(&at("fixtures/cancun/a.json", "t", (0, 2, 3)))); + } + + /// `DEVIATIONS.md` is the rendered registry. `UPDATE_DEVIATIONS=1` writes it instead. + #[test] + fn test_the_rendered_registry_is_up_to_date() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("DEVIATIONS.md"); + let rendered = render_markdown(); + if std::env::var_os("UPDATE_DEVIATIONS").is_some() { + std::fs::write(&path, &rendered).expect("the file is writable"); + return; + } + let checked_in = std::fs::read_to_string(&path).expect("DEVIATIONS.md is checked in"); + assert_eq!( + checked_in, rendered, + "DEVIATIONS.md is out of date; regenerate it with \ + UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations" + ); + } +} diff --git a/crates/mega-state-test/src/exceptions.rs b/crates/mega-state-test/src/exceptions.rs new file mode 100644 index 000000000..3c8b04618 --- /dev/null +++ b/crates/mega-state-test/src/exceptions.rs @@ -0,0 +1,322 @@ +//! Matching a rejected transaction against the exception its fixture expects. +//! +//! A fixture names the exception an invalid transaction must raise (`expectException`), as one +//! name or as alternatives joined by `|`: `TransactionException.INTRINSIC_GAS_TOO_LOW`. A +//! rejection passes only if it is one of the named ones: the runner maps each validation error +//! the engine raises to the names that describe it, and a rejection for another reason — or for a +//! reason with no name here — is a failure, not a pass. Accepting any error would let a +//! transaction rejected for the wrong reason, say a nonce check that fires before the gas check a +//! fixture is about, pass the gate. +//! +//! One pair of names labels a single rule. The execution specs reject a gas limit below the +//! intrinsic cost or below the EIP-7623 calldata floor with one error; the fixtures' two names, +//! `INTRINSIC_GAS_TOO_LOW` and `INTRINSIC_GAS_BELOW_FLOOR_GAS_COST`, label which of the two costs +//! the test drew the larger, in the fixture's own accounting. The Amsterdam fixtures' accounting +//! can call `INTRINSIC_GAS_TOO_LOW` a limit revm finds above the intrinsic cost and below the +//! floor, so on the Amsterdam fixtures a floor shortfall satisfies both names. The Osaka fixtures +//! never do, and on them each shortfall satisfies only its own name; an intrinsic shortfall +//! satisfies only its own on both. + +use mega_evm::{ + op_revm::OpTransactionError, + revm::context::result::{EVMError, InvalidTransaction}, +}; + +use crate::{ + types::{TestError, TestUnit}, + Fork, +}; + +/// The prefix of every transaction exception name. +const PREFIX: &str = "TransactionException."; + +/// The execution-spec exception names `error` satisfies on `fork`'s fixtures, without the +/// `TransactionException.` prefix; empty for an error no fixture exception describes. +pub fn names(fork: Fork, error: &InvalidTransaction) -> &'static [&'static str] { + use InvalidTransaction as E; + match error { + E::PriorityFeeGreaterThanMaxFee => &["PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS"], + E::GasPriceLessThanBasefee => &["INSUFFICIENT_MAX_FEE_PER_GAS"], + E::CallerGasLimitMoreThanBlock => &["GAS_ALLOWANCE_EXCEEDED"], + E::CallGasCostMoreThanGasLimit { .. } => &["INTRINSIC_GAS_TOO_LOW"], + E::GasFloorMoreThanGasLimit { .. } => match fork { + Fork::Osaka => &["INTRINSIC_GAS_BELOW_FLOOR_GAS_COST"], + Fork::Amsterdam => &["INTRINSIC_GAS_BELOW_FLOOR_GAS_COST", "INTRINSIC_GAS_TOO_LOW"], + }, + E::RejectCallerWithCode => &["SENDER_NOT_EOA"], + E::LackOfFundForMaxFee { .. } => &["INSUFFICIENT_ACCOUNT_FUNDS"], + E::OverflowPaymentInTransaction => &["GASLIMIT_PRICE_PRODUCT_OVERFLOW"], + E::NonceOverflowInTransaction => &["NONCE_IS_MAX"], + E::NonceTooHigh { .. } => &["NONCE_MISMATCH_TOO_HIGH"], + E::NonceTooLow { .. } => &["NONCE_MISMATCH_TOO_LOW"], + E::CreateInitCodeSizeLimit => &["INITCODE_SIZE_EXCEEDED"], + E::InvalidChainId | E::MissingChainId => &["INVALID_CHAINID"], + E::TxGasLimitGreaterThanCap { .. } => &["GAS_LIMIT_EXCEEDS_MAXIMUM"], + E::BlobGasPriceGreaterThanMax { .. } => &["INSUFFICIENT_MAX_FEE_PER_BLOB_GAS"], + E::EmptyBlobs => &["TYPE_3_TX_ZERO_BLOBS"], + E::BlobCreateTransaction => &["TYPE_3_TX_CONTRACT_CREATION"], + E::TooManyBlobs { .. } => { + &["TYPE_3_TX_BLOB_COUNT_EXCEEDED", "TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED"] + } + E::BlobVersionNotSupported => &["TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH"], + E::EmptyAuthorizationList => &["TYPE_4_EMPTY_AUTHORIZATION_LIST"], + _ => &[], + } +} + +/// Why a rejection does not satisfy what its fixture expects. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Mismatch { + /// The error has a name, and it is not one the fixture expects. + Wrong { + /// The names the error satisfies. + got: &'static [&'static str], + }, + /// The error has no execution-spec name at all. + Unnamed, +} + +/// Whether `error` is one of the exceptions `expected`, in a fixture of `fork`, names. +pub fn check( + fork: Fork, + expected: &str, + error: &EVMError, +) -> Result<(), Mismatch> { + let EVMError::Transaction(OpTransactionError::Base(invalid)) = error else { + return Err(Mismatch::Unnamed); + }; + check_names(expected, names(fork, invalid)) +} + +/// The exception names a transaction the fixture types cannot build satisfies: an invalid +/// signature for one without a key to sign it or with a key that recovers no sender, a creation +/// for a blob or EIP-7702 transaction without a recipient. Empty for anything else. +pub fn unbuildable_names(error: &TestError, unit: &TestUnit) -> &'static [&'static str] { + let invalid_type = || { + if unit.transaction.max_fee_per_blob_gas.is_some() { + &["TYPE_3_TX_CONTRACT_CREATION"][..] + } else if unit.transaction.authorization_list.is_some() { + &["TYPE_4_TX_CONTRACT_CREATION"][..] + } else { + &[][..] + } + }; + match error { + TestError::UnknownPrivateKey(_) => &["INVALID_SIGNATURE_VRS"], + TestError::InvalidTransactionType => invalid_type(), + TestError::UnexpectedException { got_exception, .. } => match got_exception.as_deref() { + Some("Missing secret key") => &["INVALID_SIGNATURE_VRS"], + Some("Invalid transaction type") => invalid_type(), + _ => &[], + }, + } +} + +/// Whether a transaction the fixture types cannot build is invalid for one of the reasons +/// `expected` names. +pub fn check_unbuildable( + expected: &str, + error: &TestError, + unit: &TestUnit, +) -> Result<(), Mismatch> { + check_names(expected, unbuildable_names(error, unit)) +} + +/// Whether `got`, the names an error satisfies, includes one of the ones `expected` names. +pub(crate) fn check_names(expected: &str, got: &'static [&'static str]) -> Result<(), Mismatch> { + if got.is_empty() { + return Err(Mismatch::Unnamed); + } + let mut expected = + expected.split('|').map(|name| name.trim().strip_prefix(PREFIX).unwrap_or(name)).peekable(); + if expected.peek().is_some() && expected.any(|name| got.contains(&name)) { + Ok(()) + } else { + Err(Mismatch::Wrong { got }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::convert::Infallible; + + fn tx_error(error: InvalidTransaction) -> EVMError { + EVMError::Transaction(OpTransactionError::Base(error)) + } + + #[test] + fn test_check_accepts_a_named_exception() { + let error = tx_error(InvalidTransaction::RejectCallerWithCode); + assert_eq!(check(Fork::Osaka, "TransactionException.SENDER_NOT_EOA", &error), Ok(())); + } + + #[test] + fn test_check_accepts_any_alternative() { + let error = tx_error(InvalidTransaction::LackOfFundForMaxFee { + fee: Box::default(), + balance: Box::default(), + }); + assert_eq!( + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW|TransactionException.INSUFFICIENT_ACCOUNT_FUNDS", + &error + ), + Ok(()) + ); + } + + #[test] + fn test_check_rejects_the_wrong_reason() { + let error = tx_error(InvalidTransaction::NonceTooLow { tx: 0, state: 1 }); + assert_eq!( + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Wrong { got: &["NONCE_MISMATCH_TOO_LOW"] }) + ); + } + + #[test] + fn test_check_rejects_an_unnamed_error() { + let error = tx_error(InvalidTransaction::Eip7873NotSupported); + assert_eq!( + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + let error: EVMError = EVMError::Custom("boom".into()); + assert_eq!( + check(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + let error = EVMError::Transaction(OpTransactionError::MissingEnvelopedTx); + assert_eq!( + check::(Fork::Osaka, "TransactionException.INTRINSIC_GAS_TOO_LOW", &error), + Err(Mismatch::Unnamed) + ); + } + + /// On the Amsterdam fixtures a gas limit below the calldata floor satisfies either name of the + /// one rule, and on the Osaka fixtures only its own; one below the intrinsic cost satisfies + /// only its own on both. + #[test] + fn test_floor_and_intrinsic_shortfalls() { + const FLOOR: &str = "TransactionException.INTRINSIC_GAS_BELOW_FLOOR_GAS_COST"; + const TOO_LOW: &str = "TransactionException.INTRINSIC_GAS_TOO_LOW"; + let floor = + tx_error(InvalidTransaction::GasFloorMoreThanGasLimit { gas_floor: 2, gas_limit: 1 }); + let intrinsic = tx_error(InvalidTransaction::CallGasCostMoreThanGasLimit { + initial_gas: 2, + gas_limit: 1, + }); + for fork in Fork::ALL { + assert_eq!(check(fork, FLOOR, &floor), Ok(()), "{fork}"); + assert_eq!(check(fork, TOO_LOW, &intrinsic), Ok(()), "{fork}"); + assert_eq!( + check(fork, FLOOR, &intrinsic), + Err(Mismatch::Wrong { got: &["INTRINSIC_GAS_TOO_LOW"] }), + "{fork}" + ); + } + assert_eq!(check(Fork::Amsterdam, TOO_LOW, &floor), Ok(())); + assert_eq!( + check(Fork::Osaka, TOO_LOW, &floor), + Err(Mismatch::Wrong { got: &["INTRINSIC_GAS_BELOW_FLOOR_GAS_COST"] }) + ); + } + + /// A name without the prefix is not a different name; an empty expectation matches nothing. + #[test] + fn test_check_reads_names_with_or_without_the_prefix() { + let error = tx_error(InvalidTransaction::EmptyBlobs); + assert_eq!(check(Fork::Osaka, "TYPE_3_TX_ZERO_BLOBS", &error), Ok(())); + assert!(check(Fork::Osaka, "", &error).is_err()); + } + + fn unit(transaction: serde_json::Value) -> TestUnit { + let mut tx = serde_json::json!({ + "data": ["0x"], "gasLimit": ["0x5208"], "nonce": "0x00", "value": ["0x00"], + }); + for (key, value) in transaction.as_object().unwrap() { + tx[key] = value.clone(); + } + serde_json::from_value(serde_json::json!({ + "env": { + "currentCoinbase": "0x0000000000000000000000000000000000000000", + "currentGasLimit": "0x01", "currentNumber": "0x01", "currentTimestamp": "0x01", + }, + "pre": {}, "post": {}, "transaction": tx, + })) + .unwrap() + } + + /// A transaction that cannot be built is invalid for the reason its shape says, and a fixture + /// that expects another reason does not get a skip. + #[test] + fn test_unbuildable_transactions_are_matched_by_name() { + let missing_key = TestError::UnexpectedException { + expected_exception: None, + got_exception: Some("Missing secret key".into()), + }; + let plain = unit(serde_json::json!({})); + assert_eq!( + check_unbuildable("TransactionException.INVALID_SIGNATURE_VRS", &missing_key, &plain), + Ok(()) + ); + assert_eq!( + check_unbuildable("TransactionException.INTRINSIC_GAS_TOO_LOW", &missing_key, &plain), + Err(Mismatch::Wrong { got: &["INVALID_SIGNATURE_VRS"] }) + ); + let bad_key = TestError::UnknownPrivateKey(Default::default()); + assert_eq!( + check_unbuildable("TransactionException.INVALID_SIGNATURE_VRS", &bad_key, &plain), + Ok(()) + ); + + let blob = unit(serde_json::json!({ "maxFeePerBlobGas": "0x01" })); + let auth = unit(serde_json::json!({ "authorizationList": [] })); + for error in [ + TestError::InvalidTransactionType, + TestError::UnexpectedException { + expected_exception: None, + got_exception: Some("Invalid transaction type".into()), + }, + ] { + assert_eq!( + check_unbuildable( + "TransactionException.TYPE_3_TX_CONTRACT_CREATION", + &error, + &blob + ), + Ok(()) + ); + assert!(check_unbuildable( + "TransactionException.TYPE_4_TX_CONTRACT_CREATION", + &error, + &blob + ) + .is_err()); + assert_eq!( + check_unbuildable( + "TransactionException.TYPE_4_TX_CONTRACT_CREATION", + &error, + &auth + ), + Ok(()) + ); + assert_eq!( + check_unbuildable( + "TransactionException.TYPE_3_TX_CONTRACT_CREATION", + &error, + &plain + ), + Err(Mismatch::Unnamed) + ); + } + let overflow = TestError::UnexpectedException { + expected_exception: None, + got_exception: Some("Nonce overflow".into()), + }; + assert_eq!( + check_unbuildable("TransactionException.NONCE_IS_MAX", &overflow, &plain), + Err(Mismatch::Unnamed) + ); + } +} diff --git a/crates/mega-state-test/src/fork.rs b/crates/mega-state-test/src/fork.rs new file mode 100644 index 000000000..3dea687fb --- /dev/null +++ b/crates/mega-state-test/src/fork.rs @@ -0,0 +1,101 @@ +//! The fixture forks the runner executes. + +use core::{fmt, str::FromStr}; + +use mega_evm::EthSpecId; +use serde::Serialize; + +use crate::types::SpecName; + +/// A fork whose fixture entries the runner executes. +/// +/// Satin's base spec is Osaka, so these are the forks it has a neutral configuration for +/// (`mega_evm::test_utils::neutral_cfg`): Osaka, which the main fixture release is written for, +/// and Amsterdam, which the glamsterdam devnet release is. A fixture file carries entries for +/// several forks; a run executes the entries of one. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +pub enum Fork { + /// Osaka: the main fixture release. + Osaka, + /// Amsterdam: the glamsterdam devnet fixture release. + Amsterdam, +} + +impl Fork { + /// Every fork the runner executes. + pub const ALL: [Self; 2] = [Self::Osaka, Self::Amsterdam]; + + /// The Ethereum spec of this fork. + pub const fn spec_id(self) -> EthSpecId { + match self { + Self::Osaka => EthSpecId::OSAKA, + Self::Amsterdam => EthSpecId::AMSTERDAM, + } + } + + /// The key of this fork's entries in a fixture's `post` map. + pub const fn name(self) -> &'static str { + match self { + Self::Osaka => "Osaka", + Self::Amsterdam => "Amsterdam", + } + } + + /// Whether a fixture's `post` key names this fork. + pub fn is(self, spec: &SpecName) -> bool { + matches!( + (self, spec), + (Self::Osaka, SpecName::Osaka) | (Self::Amsterdam, SpecName::Amsterdam) + ) + } +} + +impl fmt::Display for Fork { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// Error returned when a string names no fork the runner executes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("unknown fork {0:?}; expected one of: Osaka, Amsterdam")] +pub struct UnknownFork(pub String); + +impl FromStr for Fork { + type Err = UnknownFork; + + fn from_str(s: &str) -> Result { + Self::ALL.into_iter().find(|fork| fork.name() == s).ok_or_else(|| UnknownFork(s.into())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_fork_names_round_trip() { + for fork in Fork::ALL { + assert_eq!(fork.name().parse::(), Ok(fork)); + assert_eq!(fork.to_string(), fork.name()); + } + assert!("Prague".parse::().is_err()); + assert!("osaka".parse::().is_err()); + } + + #[test] + fn test_fork_matches_its_post_key_only() { + let key = |s: &str| serde_json::from_str::(&format!("\"{s}\"")).unwrap(); + assert!(Fork::Osaka.is(&key("Osaka"))); + assert!(!Fork::Osaka.is(&key("Amsterdam"))); + assert!(!Fork::Osaka.is(&key("Prague"))); + assert!(Fork::Amsterdam.is(&key("Amsterdam"))); + assert!(!Fork::Amsterdam.is(&key("Osaka"))); + } + + #[test] + fn test_fork_spec_ids() { + assert_eq!(Fork::Osaka.spec_id(), EthSpecId::OSAKA); + assert_eq!(Fork::Amsterdam.spec_id(), EthSpecId::AMSTERDAM); + } +} diff --git a/crates/mega-state-test/src/lib.rs b/crates/mega-state-test/src/lib.rs index 7af297a0d..0f65f5c73 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -1,10 +1,41 @@ -//! Self-contained EEST-compatible state-test fixtures and runner for mega-evm. +//! The execution-spec state-test runner of the Satin engine. +//! +//! It runs Ethereum's execution-spec state-test fixtures through [`MegaEvm`](mega_evm::MegaEvm) +//! in one of two [modes](Mode): +//! +//! - **Equivalence** — Satin's machinery (its handler, frame lifecycle, Host and instruction table) +//! priced as the fixture's own fork prices it, with every dimension only `MegaETH` prices turned +//! off (`MegaContext::with_neutral_cfg`). It is a gate: every test the fork's entries define +//! passes, is skipped for a [reason the reference runner shares](skips), or fails on a +//! [registered deviation](deviations) — a place Satin differs from Ethereum on purpose. +//! - **Satin** — the same fixtures under Satin's own configuration, counted by outcome. It is a +//! report: Satin prices state and history on purpose, and state access as Amsterdam does +//! (EIP-8038), so almost every stateful fixture differs, and the count is what is worth watching. +//! +//! The fixture types are the revm fork's own ([`types`]), the ones its reference runner reads, so +//! the two runners parse, skip and count the same population. +//! +//! The [`blockchain`] module runs the execution-spec blockchain tests — chains of blocks, many +//! transactions to a block — through Satin's block executor in equivalence mode's configuration, +//! and judges every block's gas used, logs bloom, receipts root and state root, and every block the +//! fixture expects to be refused. #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] -pub mod types; - +pub mod blockchain; +pub mod deviations; +pub mod exceptions; +mod fork; +mod mode; +pub mod roots; pub mod runner; +pub mod skips; +pub mod witness; + +pub use fork::*; +pub use mode::*; -pub mod utils; +/// The execution-spec state-test fixture types, as the revm fork's reference runner reads +/// them. +pub use revm::statetest_types as types; diff --git a/crates/mega-state-test/src/mode.rs b/crates/mega-state-test/src/mode.rs new file mode 100644 index 000000000..a4eb2685d --- /dev/null +++ b/crates/mega-state-test/src/mode.rs @@ -0,0 +1,198 @@ +//! The two configurations the runner executes a fixture under. + +use core::{fmt, str::FromStr}; + +use mega_evm::{ + alloy_evm::Database, + revm::{ + context::{BlockEnv, CfgEnv}, + inspector::NoOpInspector, + }, + test_utils::{neutral_cfg, neutralize_evm, zero_fee_l1_block_info}, + EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, +}; +use serde::Serialize; + +use crate::Fork; + +/// The most blobs a transaction may carry under the fixture forks, as the reference runner +/// configures it from Osaka on. +pub const MAX_BLOBS_PER_TX: u64 = 6; + +/// How the runner configures `MegaEvm` for a fixture. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Mode { + /// Satin's machinery priced as the fixture's fork prices it: the neutral configuration + /// (`MegaContext::with_neutral_cfg`) built for the fork, and the fork's own precompile set and + /// static opcode prices (`test_utils::neutralize_evm`). No runtime limit is enforced: the + /// data-size limit and frame budgets are `MegaETH`'s, and Ethereum has none. + /// + /// What is left to differ from the fixture is what the machinery does, which is why this mode + /// is a gate. + Equivalence, + /// Satin's own configuration, whatever the fixture's fork: its schedule, EIP-8037 and + /// EIP-2780, its execution cap and code-size limits, history gas and its precompile set. + /// The fixture's chain id and blob limit are kept. Its runtime limits are a bare context's, + /// the spec's own (`ProtocolLimits::for_spec`): the transaction data-size limit, every frame's + /// share of it, and gas detention's caps. + Satin, +} + +impl Mode { + /// Both modes. + pub const ALL: [Self; 2] = [Self::Equivalence, Self::Satin]; + + /// The name the command line takes. + pub const fn name(self) -> &'static str { + match self { + Self::Equivalence => "equivalence", + Self::Satin => "satin", + } + } + + /// The configuration a test of `fork` runs under, on chain `chain_id`. + pub fn cfg(self, fork: Fork, chain_id: u64) -> CfgEnv { + let mut cfg = match self { + Self::Equivalence => { + neutral_cfg(fork.spec_id()).expect("every runner fork has a neutral configuration") + } + Self::Satin => CfgEnv::new_with_spec(MegaSpecId::SATIN), + }; + cfg.chain_id = chain_id; + cfg.max_blobs_per_tx = Some(MAX_BLOBS_PER_TX); + cfg + } + + /// The context a test of `fork` runs in: this mode's configuration, `block`, and L1 block + /// info that charges no L1 fee and is already the block's, so op-revm reads nothing to price + /// the transaction's L1 cost. Equivalence mode installs no runtime limit, whatever the + /// engine's default is. + pub fn context( + self, + fork: Fork, + db: DB, + block: BlockEnv, + chain_id: u64, + ) -> MegaContext { + self.context_with_envs(fork, db, block, chain_id, ExternalEnvs::default()) + } + + /// [`context`](Self::context) over the external environments `envs`, for a run that records + /// or replays what the SALT and oracle environments answer. + pub fn context_with_envs( + self, + fork: Fork, + db: DB, + block: BlockEnv, + chain_id: u64, + envs: ExternalEnvs, + ) -> MegaContext { + let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, envs); + let cfg = self.cfg(fork, chain_id); + let ctx = match self { + Self::Equivalence => { + ctx.with_neutral_cfg(cfg).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + } + Self::Satin => ctx.with_cfg(cfg), + }; + let mut l1 = zero_fee_l1_block_info(); + l1.l2_block = Some(block.number); + ctx.with_block(block).with_chain(l1) + } + + /// The EVM a test of `fork` runs on: [`context`](Self::context), with the fork's precompile + /// set and static opcode prices in equivalence mode and Satin's in Satin mode. + pub fn evm( + self, + fork: Fork, + db: DB, + block: BlockEnv, + chain_id: u64, + ) -> MegaEvm { + self.evm_with_envs(fork, db, block, chain_id, ExternalEnvs::default()) + } + + /// [`evm`](Self::evm) over the external environments `envs`. + pub fn evm_with_envs( + self, + fork: Fork, + db: DB, + block: BlockEnv, + chain_id: u64, + envs: ExternalEnvs, + ) -> MegaEvm { + let mut evm = MegaEvm::new(self.context_with_envs(fork, db, block, chain_id, envs)); + if self == Self::Equivalence { + neutralize_evm(&mut evm, fork.spec_id()) + .expect("every runner fork has a neutral configuration"); + } + evm + } +} + +impl fmt::Display for Mode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// Error returned when a string names no mode. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("unknown mode {0:?}; expected equivalence or satin")] +pub struct UnknownMode(pub String); + +impl FromStr for Mode { + type Err = UnknownMode; + + fn from_str(s: &str) -> Result { + Self::ALL.into_iter().find(|mode| mode.name() == s).ok_or_else(|| UnknownMode(s.into())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + revm::{context::ContextTr, database::EmptyDB, primitives::U256}, + satin_gas_params, + }; + + #[test] + fn test_mode_names_round_trip() { + for mode in Mode::ALL { + assert_eq!(mode.name().parse::(), Ok(mode)); + } + assert!("Equivalence".parse::().is_err()); + } + + /// Equivalence mode runs the fork's configuration, neutrally and without runtime limits, on + /// the context and on the EVM built from it; Satin mode runs Satin's. Both keep the fixture's + /// chain id and the blob limit. + #[test] + fn test_modes_configure_the_context() { + let block = BlockEnv { number: U256::from(9), ..Default::default() }; + for fork in Fork::ALL { + let ctx = Mode::Equivalence.context(fork, EmptyDB::default(), block.clone(), 7); + assert!(ctx.is_neutral()); + assert!(!ctx.prices_history()); + assert_eq!(ctx.additional_limit().limits(), &EvmTxRuntimeLimits::no_limits()); + let evm = Mode::Equivalence.evm(fork, EmptyDB::default(), block.clone(), 7); + assert_eq!(evm.tx_runtime_limits(), &EvmTxRuntimeLimits::no_limits()); + assert_eq!( + ctx.cfg().gas_params.table(), + neutral_cfg(fork.spec_id()).unwrap().gas_params.table() + ); + assert_eq!(ctx.cfg().chain_id, 7); + assert_eq!(ctx.cfg().max_blobs_per_tx, Some(MAX_BLOBS_PER_TX)); + + let ctx = Mode::Satin.context(fork, EmptyDB::default(), block.clone(), 7); + assert!(!ctx.is_neutral()); + assert_eq!(ctx.cfg().gas_params.table(), satin_gas_params().table()); + assert_eq!(ctx.cfg().tx_gas_limit_cap, Some(TX_GAS_LIMIT_CAP)); + assert_eq!(ctx.cfg().chain_id, 7); + assert_eq!(ctx.chain().l2_block, Some(U256::from(9)), "no L1 info read"); + } + } +} diff --git a/crates/mega-state-test/src/roots.rs b/crates/mega-state-test/src/roots.rs new file mode 100644 index 000000000..acff5f35a --- /dev/null +++ b/crates/mega-state-test/src/roots.rs @@ -0,0 +1,167 @@ +//! The roots a test's expectation is written in: the post-state root and the hash of the logs a +//! state test carries, computed the way the reference runner computes them, and the receipts root +//! and logs bloom a block header carries. + +use alloy_trie::{root::storage_root_unhashed, HashBuilder, Nibbles, TrieAccount}; +use mega_evm::{ + alloy_consensus::{proofs::calculate_receipt_root, TxReceipt}, + alloy_primitives::Bloom, + op_alloy_consensus::OpReceiptEnvelope, + revm::{ + database::PlainAccount, + primitives::{keccak256, Address, Log, B256}, + }, +}; + +/// The keccak hash of the RLP list of `logs`: a state test's `logs` field. +pub fn logs_hash(logs: &[Log]) -> B256 { + let mut out = Vec::with_capacity(alloy_rlp::list_length(logs)); + alloy_rlp::encode_list(logs, &mut out); + keccak256(&out) +} + +/// The receipts root over `receipts`: a block header's `receiptsRoot`. +/// +/// Each receipt is a leaf at the RLP of its index, encoded as EIP-2718 has it with its bloom. A +/// receipt of an OP transaction that is not a deposit is an Ethereum receipt, and encodes as one. +pub fn receipts_root(receipts: &[OpReceiptEnvelope]) -> B256 { + calculate_receipt_root(receipts) +} + +/// The bloom of every log of `receipts`: a block header's `logsBloom`. +pub fn logs_bloom(receipts: &[OpReceiptEnvelope]) -> Bloom { + let mut bloom = Bloom::ZERO; + for receipt in receipts { + bloom.accrue_bloom(&receipt.bloom()); + } + bloom +} + +/// The state root over `accounts`: a state test's `hash` field, and a block header's +/// `stateRoot`. +/// +/// A zero slot is not a leaf of an account's storage trie, which is how an account's storage +/// root forgets a slot the transaction cleared. +pub fn state_root<'a>(accounts: impl IntoIterator) -> B256 { + let mut leaves: 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)), + ); + let leaf = TrieAccount { + nonce: account.info.nonce, + balance: account.info.balance, + storage_root, + code_hash: account.info.code_hash, + }; + (keccak256(address), leaf) + }) + .collect(); + leaves.sort_unstable_by_key(|(key, _)| *key); + + let mut builder = HashBuilder::default(); + let mut rlp = Vec::new(); + for (key, leaf) in leaves { + rlp.clear(); + alloy_rlp::Encodable::encode(&leaf, &mut rlp); + builder.add_leaf(Nibbles::unpack(key), &rlp); + } + builder.root() +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::{ + alloy_consensus::{proofs::calculate_receipt_root, Receipt, ReceiptEnvelope}, + revm::{ + primitives::{b256, Bytes, KECCAK_EMPTY}, + state::AccountInfo, + }, + }; + + /// No receipts have the empty trie's root and an empty bloom. + #[test] + fn test_no_receipts() { + assert_eq!(receipts_root(&[]), alloy_trie::EMPTY_ROOT_HASH); + assert_eq!(logs_bloom(&[]), Bloom::ZERO); + } + + /// A receipt of an OP transaction that is not a deposit has the root the same Ethereum + /// receipt has, whatever its type, and the block's bloom holds every receipt's logs. + #[test] + fn test_op_receipts_root_and_bloom_as_ethereum_s() { + let log = |byte: u8| { + Log::new_unchecked( + Address::repeat_byte(byte), + vec![B256::repeat_byte(byte)], + Bytes::from(vec![byte]), + ) + }; + let receipt = |status: bool, gas: u64, byte: u8| { + Receipt { status: status.into(), cumulative_gas_used: gas, logs: vec![log(byte)] } + .with_bloom() + }; + let op = [ + OpReceiptEnvelope::Legacy(receipt(true, 21_000, 1)), + OpReceiptEnvelope::Eip2930(receipt(false, 42_000, 2)), + OpReceiptEnvelope::Eip1559(receipt(true, 63_000, 3)), + OpReceiptEnvelope::Eip7702(receipt(true, 84_000, 4)), + ]; + let ethereum = [ + ReceiptEnvelope::Legacy(receipt(true, 21_000, 1)), + ReceiptEnvelope::Eip2930(receipt(false, 42_000, 2)), + ReceiptEnvelope::Eip1559(receipt(true, 63_000, 3)), + ReceiptEnvelope::Eip7702(receipt(true, 84_000, 4)), + ]; + assert_eq!(receipts_root(&op), calculate_receipt_root(ðereum)); + assert_ne!(receipts_root(&op), receipts_root(&op[..3])); + + let bloom = logs_bloom(&op); + let mut expected = Bloom::ZERO; + expected.accrue_logs(&[log(1), log(2), log(3), log(4)]); + assert_eq!(bloom, expected); + assert_ne!(bloom, logs_bloom(&op[..3])); + } + + /// No logs hash to the keccak of an empty RLP list, the value every fixture without logs + /// carries. + #[test] + fn test_logs_hash_of_no_logs() { + assert_eq!( + logs_hash(&[]), + b256!("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347") + ); + } + + /// An empty state has the empty trie's root. + #[test] + fn test_state_root_of_nothing() { + assert_eq!(state_root([]), alloy_trie::EMPTY_ROOT_HASH); + } + + /// A slot holding zero is not a leaf: an account whose only slot is zero has the root of an + /// account without storage. + #[test] + fn test_state_root_drops_zero_slots() { + let info = AccountInfo { + balance: mega_evm::revm::primitives::U256::from(1), + code_hash: KECCAK_EMPTY, + ..Default::default() + }; + let bare = PlainAccount { info: info.clone(), storage: Default::default() }; + let mut zeroed = PlainAccount { info, storage: Default::default() }; + zeroed.storage.insert( + mega_evm::revm::primitives::U256::from(1), + mega_evm::revm::primitives::U256::ZERO, + ); + let address = Address::repeat_byte(1); + assert_eq!(state_root([(address, &bare)]), state_root([(address, &zeroed)])); + assert_ne!(state_root([(address, &bare)]), state_root([])); + } +} diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index a47644200..f8966439d 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -1,1418 +1,779 @@ -#![allow(missing_docs)] +//! Finding, executing and judging state tests. +//! +//! [`run`] executes every entry the fixtures under a set of paths define for one [`Fork`], in one +//! [`Mode`], and reports each: passed, skipped (with the [reason](SkipReason) the reference +//! runner shares) or failed (with the [kind](FailureKind) of failure, the hashes it +//! [produced](Produced) when it failed on them and, in equivalence mode, the +//! [deviation](crate::deviations::Deviation) that explains it, if one does). +//! [`Report::summary`] counts them, and [`Report::gate`] is what the gate checks. +//! +//! A test is judged the way the reference runner judges it — the post-state root and the logs +//! hash for a transaction that executes, the exception for one that must not — and more strictly +//! where that runner is lenient: +//! +//! - an expected exception must be the one the fixture names ([`exceptions`]), not any error, and +//! the state it leaves must be the fixture's post-state; a transaction the fixture types cannot +//! build is skipped only when the fixture names the reason it cannot be; +//! - a test name that appears twice in a file fails the file, rather than one test replacing the +//! other; +//! - an expected output must be produced, not merely not contradicted; +//! - a fixture value that does not fit its width is a failure, not a value clamped to fit. +//! +//! Base fees go to Optimism's base-fee vault on Satin, where Ethereum burns them. The runner takes +//! the vault back out of the post-state before computing its root, but only the account the fee +//! routing created: one the fixture's pre-state does not hold, holding exactly the base fee of the +//! gas the transaction used and nothing else. Any other vault stays, and the root it moves is a +//! failure. -use crate::{ - types::{ - tx_env_at, Env, SpecName, Test, TestError as TxBuildError, TestSuite, TestUnit, - TxPartIndices, +use std::{ + collections::BTreeMap, + fmt, + io::stderr, + panic::{catch_unwind, AssertUnwindSafe}, + path::{Path, PathBuf}, + sync::{ + atomic::{AtomicUsize, Ordering}, + Mutex, }, - utils::{compute_test_roots, TestValidationResult}, }; -use alloy_primitives::address; -use indicatif::{ProgressBar, ProgressDrawTarget}; + use mega_evm::{ + alloy_op_evm::OpTx, + op_revm::{constants::BASE_FEE_RECIPIENT, OpHaltReason, OpTransaction, OpTransactionError}, revm::{ - context::{block::BlockEnv, cfg::CfgEnv, tx::TxEnv}, - context_interface::{ + context::{ result::{EVMError, ExecutionResult}, - Cfg, + BlockEnv, CfgEnv, }, - database, - database::State, - database_interface::EmptyDB, + database::{EmptyDB, State}, inspector::{inspectors::TracerEip3155, InspectCommitEvm}, - primitives::{hardfork::SpecId, Bytes, B256}, + primitives::{Bytes, B256, KECCAK_EMPTY, U256}, ExecuteCommitEvm, }, - AHashBucketHasher, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransaction, - MegaTransactionError, }; -use serde_json::json; -use std::{ - convert::Infallible, - fmt::Debug, - io::stderr, - path::{Path, PathBuf}, - sync::{ - atomic::{AtomicBool, AtomicUsize, Ordering}, - Arc, Mutex, - }, - time::{Duration, Instant}, +use serde::{ + de::{Error as _, MapAccess, Visitor}, + Deserialize, Deserializer, Serialize, }; -use thiserror::Error; -use walkdir::{DirEntry, WalkDir}; +use walkdir::WalkDir; -/// Error that occurs during test execution -#[derive(Debug, Error)] -#[error("Path: {path}\nName: {name}\nError: {kind}")] -pub struct TestError { - pub name: String, - pub path: String, - pub kind: TestErrorKind, -} +use crate::{ + deviations::{self, Deviation}, + exceptions::{self, Mismatch}, + mode::MAX_BLOBS_PER_TX, + roots::{logs_hash, state_root}, + skips::{skip_file, SkipReason}, + types::{Test, TestSuite, TestUnit}, + Fork, Mode, +}; -/// Specific kind of error that occurred during test execution -#[derive(Debug, Error)] -#[allow(missing_docs)] -pub enum TestErrorKind { - #[error("logs root mismatch: got {got}, expected {expected}")] - LogsRootMismatch { got: B256, expected: B256 }, - #[error("state root mismatch: got {got}, expected {expected}")] - StateRootMismatch { got: B256, expected: B256 }, - #[error("gas used mismatch: got {got}, expected {expected}")] - GasUsedMismatch { got: u64, expected: u64 }, - #[error("status mismatch: got {got:?}, expected {expected:?}")] - StatusMismatch { got: String, expected: String }, - /// The raw key is kept for programmatic use but deliberately redacted from - /// the `Display` output: fixture `secretKey` values flow through error - /// messages into logs and CI output. - #[error("unable to recover sender from fixture secretKey (key redacted)")] - UnknownPrivateKey(B256), - #[error("unexpected exception: got {got_exception:?}, expected {expected_exception:?}")] - UnexpectedException { expected_exception: Option, got_exception: Option }, - #[error("unexpected output: got {got_output:?}, expected {expected_output:?}")] - UnexpectedOutput { expected_output: Option, got_output: Option }, - #[error(transparent)] - SerdeDeserialize(#[from] serde_json::Error), - #[error("thread panicked")] +/// How a run executes its fixtures. +#[derive(Clone, Copy, Debug)] +pub struct Config { + /// The configuration each test runs under. + pub mode: Mode, + /// The fork whose entries run; every other entry is not part of the run. + pub fork: Fork, + /// Worker threads; one runs the files in order. + pub threads: usize, + /// Print one JSON line per test to standard error. + pub json_outcome: bool, + /// Run each test under an EIP-3155 tracer writing to standard error. + pub trace: bool, + /// The registry equivalence mode attributes failures to: [`deviations::DEVIATIONS`] for the + /// gate. + pub deviations: &'static [Deviation], +} + +/// Which test a result is about. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +pub struct TestId { + /// The fixture file, as it was found under the paths the run was given. + pub path: String, + /// The test's name within the file. + pub name: String, + /// The position of the entry within the fork's entries for the test. + pub entry: usize, + /// The entry's data, gas and value indices. + pub indexes: (usize, usize, usize), +} + +/// How a test failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum FailureKind { + /// The transaction was rejected, and the fixture expects it to execute. + UnexpectedException, + /// The transaction executed, and the fixture expects it to be rejected. + MissingException, + /// The transaction was rejected for another reason than the one the fixture names. + WrongException, + /// The transaction was rejected with an error no execution-spec exception names. + UnnamedException, + /// The transaction's output is not the one the fixture expects. + OutputMismatch, + /// The hash of the logs is not the fixture's. + LogsMismatch, + /// The post-state root is not the fixture's. + StateRootMismatch, + /// The fixture could not be read, parsed or turned into a transaction. + Fixture, + /// Executing the test panicked. Panic, - #[error("path does not exist")] - InvalidPath, - #[error("no JSON test files found in path")] - NoJsonFiles, - #[error("fixture execution error: {0}")] - FixtureError(String), - #[error("{failed} tests failed out of {total}")] - TestsFailed { failed: usize, total: usize }, } -impl From for TestErrorKind { - /// Maps a transaction-build error to its runner-level kind, preserving the - /// underlying cause instead of collapsing everything to - /// [`TestErrorKind::UnknownPrivateKey`], which would mask the real cause. - fn from(e: TxBuildError) -> Self { - match e { - TxBuildError::UnknownPrivateKey(k) => Self::UnknownPrivateKey(k), - other => Self::FixtureError(other.to_string()), +impl FailureKind { + /// The kind's name, as the summary prints it. + pub const fn name(self) -> &'static str { + match self { + Self::UnexpectedException => "unexpected-exception", + Self::MissingException => "missing-exception", + Self::WrongException => "wrong-exception", + Self::UnnamedException => "unnamed-exception", + Self::OutputMismatch => "output-mismatch", + Self::LogsMismatch => "logs-mismatch", + Self::StateRootMismatch => "state-root-mismatch", + Self::Fixture => "fixture", + Self::Panic => "panic", } } } -/// Find all JSON test files in the given path -/// If path is a file, returns it in a vector -/// If path is a directory, recursively finds all .json files -pub fn find_all_json_tests(path: &Path) -> Vec { - if path.is_file() { - vec![path.to_path_buf()] - } else { - WalkDir::new(path) - .into_iter() - .filter_map(Result::ok) - .filter(|e| e.path().extension() == Some("json".as_ref())) - .map(DirEntry::into_path) - .collect() - } -} - -/// Check if a test should be skipped based on its filename -/// Some tests are known to be problematic or take too long -/// -/// These tests are skipped by `revm`, so we also skip them. -fn skip_test(path: &Path) -> bool { - // A path with no file name or a non-UTF-8 name cannot match any entry on - // the skip list, so it is simply not skipped (and must not panic). - let Some(name) = path.file_name().and_then(|n| n.to_str()) else { - return false; - }; - - matches!( - name, - // Test check if gas price overflows, we handle this correctly but does not match tests - // specific exception. - | "CreateTransactionHighNonce.json" - - // Test with some storage check. - | "RevertInCreateInInit_Paris.json" - | "RevertInCreateInInit.json" - | "dynamicAccountOverwriteEmpty.json" - | "dynamicAccountOverwriteEmpty_Paris.json" - | "RevertInCreateInInitCreate2Paris.json" - | "create2collisionStorage.json" - | "RevertInCreateInInitCreate2.json" - | "create2collisionStorageParis.json" - | "InitCollision.json" - | "InitCollisionParis.json" - - // Malformed value. - | "ValueOverflow.json" - | "ValueOverflowParis.json" - - // These tests are passing, but they take a lot of time to execute so we are going to skip them. - | "Call50000_sha256.json" - | "static_Call50000_sha256.json" - | "loopMul.json" - | "CALLBlake2f_MaxRounds.json" - ) -} - -struct TestExecutionContext<'a> { - name: &'a str, - unit: &'a TestUnit, - test: &'a Test, - cfg: &'a CfgEnv, - block: &'a BlockEnv, - tx: &'a TxEnv, - cache_state: &'a database::CacheState, - elapsed: &'a Arc>, - trace: bool, - print_json_outcome: bool, -} - -struct DebugContext<'a> { - name: &'a str, - path: &'a str, - index: usize, - unit: &'a TestUnit, - test: &'a Test, - cfg: &'a CfgEnv, - block: &'a BlockEnv, - tx: &'a TxEnv, - cache_state: &'a database::CacheState, - error: &'a TestErrorKind, -} - -fn build_json_output( - test: &Test, - test_name: &str, - exec_result: &Result< - ExecutionResult, - EVMError, - >, - validation: &TestValidationResult, - spec: MegaSpecId, - error: Option, -) -> serde_json::Value { - json!({ - "stateRoot": validation.state_root, - "logsRoot": validation.logs_root, - "output": exec_result.as_ref().ok().and_then(|r| r.output().cloned()).unwrap_or_default(), - "gasUsed": exec_result.as_ref().ok().map(|r| r.gas_used()).unwrap_or_default(), - "pass": error.is_none(), - "errorMsg": error.unwrap_or_default(), - "evmResult": format_evm_result(exec_result), - "postLogsHash": validation.logs_root, - "fork": spec, - "test": test_name, - "d": test.indexes.data, - "g": test.indexes.gas, - "v": test.indexes.value, - }) +/// The hashes a test produced where its fixture expects others. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Produced { + /// The post-state root, the logs hash being the fixture's. + StateRoot(B256), + /// The logs hash, and the post-state root beside it, whether or not the fixture expects that + /// root. + Logs { + /// The logs hash. + logs: B256, + /// The post-state root. + state_root: B256, + }, } -fn format_evm_result( - exec_result: &Result< - ExecutionResult, - EVMError, - >, -) -> String { - match exec_result { - Ok(r) => match r { - ExecutionResult::Success { reason, .. } => format!("Success: {reason:?}"), - ExecutionResult::Revert { .. } => "Revert".to_string(), - ExecutionResult::Halt { reason, .. } => format!("Halt: {reason:?}"), - }, - Err(e) => e.to_string(), +impl Produced { + /// The failure these hashes are. + pub const fn kind(self) -> FailureKind { + match self { + Self::StateRoot(_) => FailureKind::StateRootMismatch, + Self::Logs { .. } => FailureKind::LogsMismatch, + } } } -fn validate_exception( - test: &Test, - exec_result: &Result< - ExecutionResult, - EVMError, - >, -) -> Result { - match (&test.expect_exception, exec_result) { - (None, Ok(_)) => Ok(false), // No exception expected, execution succeeded - (Some(_), Err(_)) => Ok(true), // Exception expected and occurred - _ => Err(TestErrorKind::UnexpectedException { - expected_exception: test.expect_exception.clone(), - got_exception: exec_result.as_ref().err().map(|e| e.to_string()), - }), +impl fmt::Display for Produced { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::StateRoot(root) => write!(f, "state root {root}"), + Self::Logs { logs, state_root } => { + write!(f, "logs hash {logs}, state root {state_root}") + } + } } } -fn validate_output( - expected_output: Option<&Bytes>, - actual_result: &ExecutionResult, -) -> Result<(), TestErrorKind> { - // No expectation → nothing to check. But when the fixture expects output, - // an execution that produced none (a halt) is a failure, not a pass — - // a `zip` over the two options would short-circuit that case silently. - let Some(expected) = expected_output else { - return Ok(()); - }; - let actual = actual_result.output(); - if actual != Some(expected) { - return Err(TestErrorKind::UnexpectedOutput { - expected_output: Some(expected.clone()), - got_output: actual.cloned(), - }); - } - Ok(()) +/// A failed test. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Failure { + /// How it failed. + pub kind: FailureKind, + /// The hashes it produced, when it failed on them: a state-root or a logs mismatch. + pub produced: Option, + /// What was expected and what happened. + pub detail: String, + /// The deviation that explains it, in equivalence mode, if one does. + pub deviation: Option<&'static str>, } -/// Canonical status string for an execution result: `"success"`, `"revert"`, or -/// `"halt"`. -/// -/// Single source shared by validation (`megaStatus` checks) and by -/// `mega-evme --dump-fixture` so the dumped status and the validated status can -/// never disagree. -pub fn execution_status(result: &ExecutionResult) -> &'static str { - match result { - ExecutionResult::Success { .. } => "success", - ExecutionResult::Revert { .. } => "revert", - ExecutionResult::Halt { .. } => "halt", +impl Failure { + fn new(kind: FailureKind, detail: impl Into) -> Self { + Self { kind, produced: None, detail: detail.into(), deviation: None } } -} -/// Halt reason (`Debug` form) when the result is a halt, `None` otherwise. -/// -/// Anchors halted executions more precisely than the three-value status string: -/// two halts with different reasons typically burn the same (full) gas with no -/// output and no logs, so a status-level comparison cannot tell them apart. -pub fn halt_reason(result: &ExecutionResult) -> Option { - match result { - ExecutionResult::Halt { reason, .. } => Some(format!("{reason:?}")), - _ => None, + fn produced(produced: Produced, detail: impl Into) -> Self { + Self { + kind: produced.kind(), + produced: Some(produced), + detail: detail.into(), + deviation: None, + } } } -/// Validate the MegaETH-specific explicit expectations (`megaGasUsed`, -/// `megaStatus`) when present. -/// -/// These produce readable, targeted diffs for replay-derived fixtures. They are -/// in addition to — not a replacement for — the state-root / logs-root backstop, -/// and are skipped entirely for pure-Ethereum tests that omit the fields. -fn validate_mega_expectations( - test: &Test, - actual_result: &ExecutionResult, -) -> Result<(), TestErrorKind> { - if let Some(expected) = test.mega_gas_used { - let got = actual_result.gas_used(); - if got != expected { - return Err(TestErrorKind::GasUsedMismatch { got, expected }); +/// What happened to a test. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "outcome", rename_all = "kebab-case")] +pub enum Outcome { + /// It executed and matched its fixture. + Passed, + /// It was not executed. + Skipped { + /// Why not. + reason: SkipReason, + }, + /// It executed, or failed to, and did not match its fixture. + Failed(Failure), +} + +/// A test and what happened to it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct TestResult { + /// The test. + pub id: TestId, + /// What happened to it. + pub outcome: Outcome, +} + +/// Every test a run was given, and what happened to each. +#[derive(Debug, Serialize)] +pub struct Report { + /// The configuration the tests ran under. + pub mode: Mode, + /// The fork whose entries ran. + pub fork: Fork, + /// The registry failures were attributed to. + #[serde(skip)] + pub deviations: &'static [Deviation], + /// The fixture files the run found. + pub files: usize, + /// Every test, ordered by file, name and entry. + pub results: Vec, + /// The fixture files that could not be read or parsed, in path order, and why. + pub file_failures: Vec<(String, Failure)>, +} + +/// The counts of a [`Report`]. +#[derive(Debug, Default, PartialEq, Eq, Serialize)] +pub struct Summary { + /// The fixture files the run found. + pub files: usize, + /// The entries the files define for the fork: executed and skipped. + pub defined: usize, + /// The tests that executed. + pub executed: usize, + /// The tests that executed and matched their fixture. + pub passed: usize, + /// The tests that were not executed, by reason. + pub skipped: BTreeMap, + /// The tests that failed, by kind. + pub failed: BTreeMap, + /// The failed tests a deviation explains, by deviation. + pub deviated: BTreeMap<&'static str, usize>, + /// The failed tests no deviation explains. + pub unattributed: usize, + /// The entries a deviation lists for the fork that did not fail as listed, by deviation. + pub unreproduced: BTreeMap<&'static str, usize>, + /// The fixture files that could not be read or parsed. No deviation explains one, and the + /// entries such a file defines are counted nowhere else. + pub file_failures: usize, +} + +impl Summary { + /// The tests that were not executed. + pub fn skipped_total(&self) -> usize { + self.skipped.values().sum() + } + + /// The tests that failed. + pub fn failed_total(&self) -> usize { + self.failed.values().sum() + } + + /// The tests a deviation explains. + pub fn deviated_total(&self) -> usize { + self.deviated.values().sum() + } +} + +impl Report { + /// Counts the report. + pub fn summary(&self) -> Summary { + let mut summary = Summary { + files: self.files, + file_failures: self.file_failures.len(), + ..Default::default() + }; + for result in &self.results { + summary.defined += 1; + match &result.outcome { + Outcome::Passed => { + summary.executed += 1; + summary.passed += 1; + } + Outcome::Skipped { reason } => *summary.skipped.entry(*reason).or_default() += 1, + Outcome::Failed(failure) => { + summary.executed += 1; + *summary.failed.entry(failure.kind).or_default() += 1; + match failure.deviation { + Some(id) => *summary.deviated.entry(id).or_default() += 1, + None => summary.unattributed += 1, + } + } + } } - } - if let Some(expected) = &test.mega_status { - let got = execution_status(actual_result); - if got != expected { - return Err(TestErrorKind::StatusMismatch { - got: got.to_string(), - expected: expected.clone(), - }); + for unreproduced in self.unreproduced() { + *summary.unreproduced.entry(unreproduced.deviation.id).or_default() += 1; } - } - Ok(()) -} - -fn check_evm_execution( - test: &Test, - expected_output: Option<&Bytes>, - test_name: &str, - exec_result: &Result< - ExecutionResult, - EVMError, - >, - db: &State, - spec: MegaSpecId, - print_json_outcome: bool, -) -> Result<(), TestErrorKind> { - let validation = compute_test_roots(exec_result, db); - - let print_json = |error: Option<&TestErrorKind>| { - if print_json_outcome { - let json = build_json_output( - test, - test_name, - exec_result, - &validation, - spec, - error.map(|e| e.to_string()), - ); - eprintln!("{json}"); + summary + } + + /// The failed tests no deviation explains. + pub fn unattributed(&self) -> impl Iterator { + self.results.iter().filter_map(|result| match &result.outcome { + Outcome::Failed(failure) if failure.deviation.is_none() => Some((&result.id, failure)), + _ => None, + }) + } + + /// The entries the registry lists for the run's fork that did not fail as listed, in + /// equivalence mode. Satin mode attributes nothing, and has nothing to reproduce. + /// + /// An entry fails as listed when exactly one result of the run is the entry's and its + /// deviation explains that result, which it does only for the hashes it lists. + pub fn unreproduced(&self) -> impl Iterator> { + let registry = if self.mode == Mode::Equivalence { self.deviations } else { &[] }; + registry.iter().flat_map(move |deviation| { + deviation.listed(self.fork).iter().filter_map(move |entry| { + let seen: Vec<_> = + self.results.iter().filter(|result| entry.is(&result.id)).collect(); + let reproduced = matches!( + seen.as_slice(), + [TestResult { outcome: Outcome::Failed(failure), .. }] + if failure.deviation == Some(deviation.id) + ); + (!reproduced).then_some(Unreproduced { deviation, entry, seen }) + }) + }) + } + + /// What equivalence mode's gate finds wrong with this run: an unattributed failure, and, for + /// each count given, a count that differs from it. Empty when the gate passes. + /// + /// With `check_deviations`, every entry a registered deviation lists for the run's fork must + /// fail exactly as listed — an entry that passes, fails another way or does not run is as much + /// a change as a failure no entry explains — and, derived from that, each deviation explains + /// as many failures as it lists. + pub fn gate( + &self, + expected_executed: Option, + expected_skipped: Option, + check_deviations: bool, + ) -> Vec { + let summary = self.summary(); + let mut problems = Vec::new(); + if summary.file_failures > 0 { + problems.push(format!("{} fixture files could not be read", summary.file_failures)); } - }; - - // Check if exception handling is correct - let exception_expected = validate_exception(test, exec_result).inspect_err(|e| { - print_json(Some(e)); - })?; - - // If exception was expected and occurred, we're done - if exception_expected { - print_json(None); - return Ok(()); - } - - // Validate output if execution succeeded - if let Ok(result) = exec_result { - validate_output(expected_output, result).inspect_err(|e| { - print_json(Some(e)); - })?; - - // MegaETH explicit expectations (replay fixtures): readable gas/status diff. - validate_mega_expectations(test, result).inspect_err(|e| { - print_json(Some(e)); - })?; - } - - // Validate logs root - if validation.logs_root != test.logs { - let error = - TestErrorKind::LogsRootMismatch { got: validation.logs_root, expected: test.logs }; - print_json(Some(&error)); - return Err(error); - } - - // Validate state root - if validation.state_root != test.hash { - let error = - TestErrorKind::StateRootMismatch { got: validation.state_root, expected: test.hash }; - print_json(Some(&error)); - return Err(error); - } - - print_json(None); - Ok(()) -} - -/// Sets the per-spec maximum blobs per transaction on the config. -/// -/// Single source of truth shared by [`execute_test_suite`] and single-unit -/// execution so the validation and dump paths stay byte-identical. -fn configure_max_blobs(cfg: &mut CfgEnv) { - // OSAKA (which implies PRAGUE) caps blobs back at 6, while the PRAGUE-only - // window allows 9 — so the OSAKA arm must be checked first and is distinct - // from the pre-PRAGUE default of 6 despite the same value. - if cfg.spec.into_eth_spec().is_enabled_in(SpecId::OSAKA) { - cfg.set_max_blobs_per_tx(6); - } else if cfg.spec.into_eth_spec().is_enabled_in(SpecId::PRAGUE) { - cfg.set_max_blobs_per_tx(9); - } else { - cfg.set_max_blobs_per_tx(6); - } -} - -/// Resolve a unit's `currentChainID` into the `u64` the EVM config takes. -/// -/// An absent field defaults to `MegaETH`'s 6342 (intentional EEST behavior), -/// but a present value that does not fit in a `u64` is a fixture error rather -/// than a silent fallback to the default chain. -fn resolve_chain_id(env: &Env) -> Result { - match env.current_chain_id { - None => Ok(6342), - Some(id) => id.try_into().map_err(|_| { - TestErrorKind::FixtureError(format!("currentChainID {id} does not fit in u64")) - }), - } -} - -/// Execute a single test suite file containing multiple tests -/// -/// # Arguments -/// * `path` - Path to the JSON test file -/// * `elapsed` - Shared counter for total execution time -/// * `trace` - Whether to enable EVM tracing -/// * `print_json_outcome` - Whether to print JSON formatted results -pub fn execute_test_suite( - path: &Path, - elapsed: &Arc>, - trace: bool, - print_json_outcome: bool, -) -> Result<(), TestError> { - if skip_test(path) { - return Ok(()); - } - - let path = path.to_string_lossy().into_owned(); - let s = std::fs::read_to_string(&path).map_err(|e| TestError { - name: "Unknown".to_string(), - path: path.clone(), - kind: TestErrorKind::FixtureError(format!("read: {e}")), - })?; - let suite: TestSuite = serde_json::from_str(&s).map_err(|e| TestError { - name: "Unknown".to_string(), - path: path.clone(), - kind: e.into(), - })?; - - for (name, unit) in suite.0 { - // Prepare initial state - let cache_state = unit.state(); - - // Setup base configuration - let mut cfg = CfgEnv::default(); - cfg.chain_id = resolve_chain_id(&unit.env).map_err(|kind| TestError { - name: name.clone(), - path: path.clone(), - kind, - })?; - - // Post and execution - for (spec_name, tests) in &unit.post { - // Skip Constantinople spec - if *spec_name == SpecName::Constantinople { - continue; - } - - cfg.spec = spec_name.to_spec_id().map_err(|e| TestError { - name: name.clone(), - path: path.clone(), - kind: TestErrorKind::FixtureError(format!("post spec: {e}")), - })?; - configure_max_blobs(&mut cfg); - - // Setup block environment for this spec - let block = unit.block_env(&cfg); - - for (index, test) in tests.iter().enumerate() { - // Setup transaction environment - let tx = match test.tx_env(&unit) { - Ok(tx) => tx, - // Only a transaction that is invalid *by construction* — - // an underivable transaction type (e.g. a blob tx without - // a destination), which `Test::tx_env` reports either - // directly or remapped to `UnexpectedException` — may - // satisfy `expectException`: that is the failure the - // fixture deliberately encodes. Structural fixture - // defects (unrecoverable secret key, out-of-bounds part - // index, out-of-range field value) are errors in the - // fixture itself and must propagate, never be counted as - // an expected exception. - Err( - TxBuildError::InvalidTransactionType | - TxBuildError::UnexpectedException { .. }, - ) if test.expect_exception.is_some() => continue, - // Propagate the real underlying cause instead of masking - // every failure as an unknown private key. - Err(e) => { - return Err(TestError { name, path, kind: e.into() }); - } - }; - - // Execute the test - let result = execute_single_test(TestExecutionContext { - name: &name, - unit: &unit, - test, - cfg: &cfg, - block: &block, - tx: &tx, - cache_state: &cache_state, - elapsed, - trace, - print_json_outcome, - }); - - if let Err(e) = result { - // Handle error with debug trace if needed - static FAILED: AtomicBool = AtomicBool::new(false); - if print_json_outcome || FAILED.swap(true, Ordering::SeqCst) { - return Err(TestError { name, path, kind: e }); - } - - // Re-run with trace for debugging - debug_failed_test(DebugContext { - name: &name, - path: &path, - index, - unit: &unit, - test, - cfg: &cfg, - block: &block, - tx: &tx, - cache_state: &cache_state, - error: &e, - }); - - return Err(TestError { path, name, kind: e }); + if summary.unattributed > 0 { + problems.push(format!("{} failed tests no deviation explains", summary.unattributed)); + } + if let Some(expected) = expected_executed.filter(|&n| n != summary.executed) { + problems.push(format!("{} tests executed, {expected} pinned", summary.executed)); + } + let skipped = summary.skipped_total(); + if let Some(expected) = expected_skipped.filter(|&n| n != skipped) { + problems.push(format!("{skipped} tests skipped, {expected} pinned")); + } + if check_deviations { + for deviation in self.deviations { + let listed = deviation.listed(self.fork).len(); + let unreproduced = summary.unreproduced.get(deviation.id).copied().unwrap_or(0); + if unreproduced > 0 { + problems.push(format!( + "deviation {}: {unreproduced} of the {listed} entries it lists on {} did \ + not fail as listed", + deviation.id, self.fork + )); + } + let explained = summary.deviated.get(deviation.id).copied().unwrap_or(0); + if explained != listed { + problems.push(format!( + "deviation {} explains {explained} failed tests on {}, {listed} listed", + deviation.id, self.fork + )); } } } + problems } - Ok(()) -} - -/// Build the `MegaETH` external environment for a test unit, reproducing the -/// recorded SALT bucket capacities and oracle storage. Falls back to an empty -/// environment for pure-Ethereum tests, which omit the `megaEnv` field. -/// -/// Uses [`AHashBucketHasher`] so that bucket IDs match those recorded during -/// `mega-evme replay` — a different hasher would map keys to different buckets -/// and reproduce different gas. -fn external_envs_for( - unit: &TestUnit, -) -> Result, TestErrorKind> { - let mega_env = unit.mega_env.clone().unwrap_or_default(); - mega_env.validate().map_err(TestErrorKind::FixtureError)?; - Ok(mega_env.to_external_envs::()) -} - -/// Inject the fixture's recorded `blockHashes` into the [`State`] cache so -/// `BLOCKHASH` answers come from the fixture instead of [`EmptyDB`]'s synthetic -/// keccak-of-number hashes. -/// -/// A key that does not fit in a `u64` could never be requested by the EVM -/// (block numbers are `u64` on the `BLOCKHASH` path), so it is a fixture error -/// rather than a silently dropped entry. -fn inject_block_hashes(state: &mut State, unit: &TestUnit) -> Result<(), TestErrorKind> { - let Some(hashes) = &unit.env.block_hashes else { - return Ok(()); - }; - for (number, hash) in hashes { - let number = u64::try_from(*number).map_err(|_| { - TestErrorKind::FixtureError(format!("blockHashes key {number} does not fit in u64")) - })?; - state.block_hashes.insert(number, *hash); - } - Ok(()) -} - -fn execute_single_test<'a>(ctx: TestExecutionContext<'a>) -> Result<(), TestErrorKind> { - // Prepare state - let mut cache = ctx.cache_state.clone(); - cache.set_state_clear_flag(ctx.cfg.spec.into_eth_spec().is_enabled_in(SpecId::SPURIOUS_DRAGON)); - let mut state = - database::State::builder().with_cached_prestate(cache).with_bundle_update().build(); - inject_block_hashes(&mut state, ctx.unit)?; - - let evm_context = MegaContext::default() - .with_db(&mut state) - .with_cfg(ctx.cfg.clone()) - .with_block(ctx.block.clone()) - .with_external_envs(external_envs_for(ctx.unit)?.into()); - let mut tx = MegaTransaction::new(ctx.tx.clone()); - tx.enveloped_tx = Some(Bytes::default()); - - // Execute - let timer = Instant::now(); - let (db, exec_result) = if ctx.trace { - let mut evm = MegaEvm::new(evm_context) - .with_inspector(TracerEip3155::buffered(stderr()).without_summary()); - let res = evm.inspect_tx_commit(tx); - let db = evm.into_inner().ctx.into_inner().journaled_state.database; - (db, res) - } else { - let mut evm = MegaEvm::new(evm_context); - let res = evm.transact_commit(tx); - let db = evm.into_inner().ctx.into_inner().journaled_state.database; - (db, res) - }; - *ctx.elapsed.lock().unwrap() += timer.elapsed(); - - // Optimism special handling: prune the changes to BaseFeeVault - prune_base_fee_vault_changes(db); - - // Check results - check_evm_execution( - ctx.test, - ctx.unit.out.as_ref(), - ctx.name, - &exec_result, - db, - ctx.cfg.spec(), - ctx.print_json_outcome, - ) -} - -/// Canonical post-execution outcome of running a single [`TestUnit`]. -/// -/// Returned by [`execute_unit_collect`] and used by `mega-evme --dump-fixture` -/// to fill a fixture's `post` expectation. Because dump and validation share -/// this exact execution + root-computation path, a fixture written from these -/// values is self-consistent: re-running it through [`execute_test_suite`] -/// reproduces the same roots. -#[derive(Debug, Clone)] -pub struct ExecutedUnit { - /// Post-state trie root over the unit's account closure. - pub state_root: B256, - /// RLP hash of the emitted logs. - pub logs_root: B256, - /// Total gas used by the transaction. - pub gas_used: u64, - /// Execution status: `"success"`, `"revert"`, or `"halt"`. - pub status: String, - /// Halt reason (`Debug` form) when `status` is `"halt"`, `None` otherwise. - /// See [`halt_reason`]. - pub halt_reason: Option, - /// Transaction output bytes, if any. - pub output: Option, -} - -/// Execute a single [`TestUnit`] at transaction index 0 for the given spec, in -/// isolation, timing only the EVM `transact` call. -/// -/// This runs the same `MegaEVM` pipeline as [`execute_test_suite`] — including the -/// reproduced external environment and the Optimism `BaseFeeVault` pruning. When -/// `compute_roots` is set, the post-state / logs roots are computed (outside the -/// timed region); otherwise they are skipped for leaner repeated benchmarking. -fn run_unit_once( - unit: &TestUnit, - spec: &SpecName, - compute_roots: bool, -) -> Result<(Duration, ExecutionResult, Option), TestErrorKind> -{ - let mut cfg = CfgEnv::default(); - cfg.chain_id = resolve_chain_id(&unit.env)?; - cfg.spec = spec.to_spec_id().map_err(|e| TestErrorKind::FixtureError(format!("spec: {e}")))?; - configure_max_blobs(&mut cfg); - - let block = unit.block_env(&cfg); - let tx = tx_env_at(unit, TxPartIndices { data: 0, gas: 0, value: 0 })?; - - let mut cache = unit.state(); - cache.set_state_clear_flag(cfg.spec.into_eth_spec().is_enabled_in(SpecId::SPURIOUS_DRAGON)); - let mut state = - database::State::builder().with_cached_prestate(cache).with_bundle_update().build(); - inject_block_hashes(&mut state, unit)?; - - let evm_context = MegaContext::default() - .with_db(&mut state) - .with_cfg(cfg.clone()) - .with_block(block) - .with_external_envs(external_envs_for(unit)?.into()); - let mut megatx = MegaTransaction::new(tx); - megatx.enveloped_tx = Some(Bytes::default()); - - let mut evm = MegaEvm::new(evm_context); - let timer = Instant::now(); - let exec_result = evm.transact_commit(megatx); - let elapsed = timer.elapsed(); - - let db = evm.into_inner().ctx.into_inner().journaled_state.database; - prune_base_fee_vault_changes(db); - let validation = compute_roots.then(|| compute_test_roots(&exec_result, db)); - - let result = exec_result.map_err(|e| TestErrorKind::FixtureError(e.to_string()))?; - Ok((elapsed, result, validation)) -} - -/// Execute a single [`TestUnit`] at transaction index 0 for the given spec and -/// collect its canonical post-execution roots, gas, status, and output. -/// -/// Returns the computed values instead of comparing them against an expectation; -/// it is the dump-time counterpart to validation. -pub fn execute_unit_collect( - unit: &TestUnit, - spec: &SpecName, -) -> Result { - let (_elapsed, result, validation) = run_unit_once(unit, spec, true)?; - let validation = validation.expect("roots requested"); - Ok(ExecutedUnit { - state_root: validation.state_root, - logs_root: validation.logs_root, - gas_used: result.gas_used(), - status: execution_status(&result).to_string(), - halt_reason: halt_reason(&result), - output: result.output().cloned(), - }) -} - -/// Execute a single [`TestUnit`] at transaction index 0 once, returning the time -/// spent in the EVM `transact` call together with the gas used and status. -/// -/// The primitive behind [`bench_test_suite`] / `state-test --bench`: it measures -/// EVM throughput in isolation (excluding root computation). -pub fn time_unit_execution( - unit: &TestUnit, - spec: &SpecName, -) -> Result<(Duration, u64, String), TestErrorKind> { - let (elapsed, result, _validation) = run_unit_once(unit, spec, false)?; - Ok((elapsed, result.gas_used(), execution_status(&result).to_string())) } -/// Benchmark result for one [`TestUnit`]: the timing distribution plus the gas -/// and status it executed with. +/// An entry a deviation lists that did not fail as listed. #[derive(Debug)] -pub struct UnitBench { - /// Suite key (unit name) the result belongs to. - pub name: String, - /// Gas used by the (identical) execution. - pub gas_used: u64, - /// Whether the execution succeeded. - pub success: bool, - /// Number of timed iterations. - pub runs: u32, - /// Fastest observed iteration. - pub min: Duration, - /// Median iteration time. - pub median: Duration, - /// Mean iteration time. - pub mean: Duration, +pub struct Unreproduced<'a> { + /// The deviation. + pub deviation: &'static Deviation, + /// The entry it lists. + pub entry: &'static deviations::Entry, + /// The results the run has for the entry: none when the run did not execute it, and more than + /// one when the entry's id names several. + pub seen: Vec<&'a TestResult>, } -impl UnitBench { - /// Throughput in millions of gas per second, from the median time. - pub fn mgas_per_sec(&self) -> f64 { - let secs = self.median.as_secs_f64(); - if secs > 0.0 { - self.gas_used as f64 / secs / 1.0e6 - } else { - f64::INFINITY - } +impl fmt::Display for TestId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (d, g, v) = self.indexes; + write!(f, "{} :: {} [d={d} g={g} v={v}]", self.path, self.name) } } -/// Benchmark every unit in a fixture file by timing its isolated EVM execution. -/// -/// The fixture is self-contained (pre-state closure + transaction + block env), -/// so this needs no RPC and no archive node: any source that can produce a -/// state-test fixture — a `mega-evme --dump-fixture` replay, a `prestateTracer` -/// snapshot, or a hand-crafted case — can be benchmarked offline through the -/// same path used to validate it. -/// -/// `spec_override` selects the spec to run under; when `None`, the unit's single -/// `post` spec is used (and a unit with zero or several post specs is an error). -pub fn bench_test_suite( - path: &Path, - runs: u32, - warmup: u32, - spec_override: Option, -) -> Result, TestError> { +/// Every JSON file under `path`, or `path` itself when it is a file, in path order. +pub fn find_json_files(path: &Path) -> Vec { + if path.is_file() { + return vec![path.to_path_buf()]; + } + let mut files: Vec<_> = WalkDir::new(path) + .into_iter() + .filter_map(Result::ok) + .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json")) + .map(walkdir::DirEntry::into_path) + .collect(); + files.sort(); + files +} + +/// Executes every entry `files` define for `config.fork`, in `config.mode`, and reports each. +pub fn run(files: &[PathBuf], config: Config) -> Report { + let next = AtomicUsize::new(0); + let results = Mutex::new((Vec::new(), Vec::new())); + let threads = config.threads.clamp(1, files.len().max(1)); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = files.get(index) else { break }; + let file = run_file(path, config); + let mut results = results.lock().expect("no worker panics holding the lock"); + match file { + Ok(tests) => results.0.extend(tests), + Err(failure) => results.1.push((path.to_string_lossy().into_owned(), failure)), + } + }); + } + }); + let (mut results, mut file_failures) = + results.into_inner().expect("no worker panics holding the lock"); + results.sort_by(|a, b| a.id.cmp(&b.id)); + file_failures.sort_by(|a, b| a.0.cmp(&b.0)); + Report { + mode: config.mode, + fork: config.fork, + deviations: config.deviations, + files: files.len(), + results, + file_failures, + } +} + +/// Every entry the file at `path` defines for `config.fork`, and what happened to each; or why +/// the file could not be read. +pub fn run_file(path: &Path, config: Config) -> Result, Failure> { let path_str = path.to_string_lossy().into_owned(); - let fixture_err = |msg: String| TestError { - name: "bench".to_string(), - path: path_str.clone(), - kind: TestErrorKind::FixtureError(msg), - }; - - if runs == 0 { - return Err(fixture_err("bench requires at least one run".to_string())); - } - let s = std::fs::read_to_string(path).map_err(|e| fixture_err(format!("read: {e}")))?; - let suite: TestSuite = serde_json::from_str(&s).map_err(|e| TestError { - name: "Unknown".to_string(), - path: path_str.clone(), - kind: e.into(), - })?; + let json = std::fs::read_to_string(path) + .map_err(|error| Failure::new(FailureKind::Fixture, format!("read: {error}")))?; + let suite = serde_json::from_str::(&json) + .map_err(|error| Failure::new(FailureKind::Fixture, format!("parse: {error}")))? + .0; + let skip = skip_file(&path_str); let mut results = Vec::new(); - for (name, unit) in suite.0 { - let spec = match spec_override { - Some(s) => s, - None => { - let mut specs = unit.post.keys(); - match (specs.next(), specs.next()) { - (Some(s), None) => *s, - (Some(_), Some(_)) => { - return Err(fixture_err(format!( - "unit {name} has multiple post specs; pass --bench-spec" - ))) - } - (None, _) => { - return Err(fixture_err(format!( - "unit {name} has no post spec; pass --bench-spec" - ))) - } + for (name, unit) in &suite.0 { + for (spec, tests) in &unit.post { + if !config.fork.is(spec) { + continue; + } + for (entry, test) in tests.iter().enumerate() { + let id = TestId { + path: path_str.clone(), + name: name.clone(), + entry, + indexes: (test.indexes.data, test.indexes.gas, test.indexes.value), + }; + let outcome = match skip { + Some(reason) => Outcome::Skipped { reason }, + None => catch_unwind(AssertUnwindSafe(|| run_test(config, unit, test))) + .unwrap_or_else(|panic| { + Outcome::Failed(Failure::new(FailureKind::Panic, panic_message(&panic))) + }), + }; + let outcome = attribute(config, &id, outcome); + if config.json_outcome { + print_outcome(config, &id, &outcome); } + results.push(TestResult { id, outcome }); } - }; - // Reject an unmapped spec at selection time, so the error names the - // unit instead of surfacing from deep inside execution. - if spec == SpecName::Unknown { - return Err(fixture_err(format!( - "unit {name} selects an unknown spec; pass a valid --bench-spec" - ))); } - - for _ in 0..warmup { - time_unit_execution(&unit, &spec) - .map_err(|e| fixture_err(format!("warmup {name}: {e}")))?; - } - let mut durations = Vec::with_capacity(runs as usize); - let mut gas_used = 0u64; - let mut status = String::new(); - for _ in 0..runs { - let (elapsed, gas, st) = time_unit_execution(&unit, &spec) - .map_err(|e| fixture_err(format!("run {name}: {e}")))?; - durations.push(elapsed); - gas_used = gas; - status = st; - } - durations.sort_unstable(); - let median = durations[durations.len() / 2]; - let min = durations[0]; - let mean = durations.iter().sum::() / durations.len() as u32; - results.push(UnitBench { - name, - gas_used, - success: status == "success", - runs, - min, - median, - mean, - }); } Ok(results) } -/// Compute and write the `post` expectation for every unit in a fixture file, -/// in place — the offline analog of `--dump-fixture`'s post-fill step, for a -/// fixture that has no `post` yet (a hand-built or `prestateTracer`-snapshot -/// case). It re-uses the same `execute_unit_collect` + [`Test::for_dump`] the -/// dump path uses, so the result is a self-validating fixture that -/// [`execute_test_suite`] checks like any other. Returns the number of units -/// filled. -/// -/// `spec_override` selects the spec to execute/record under; when `None`, the -/// unit's single existing `post` spec is used (so a fixture with an empty `post` -/// must pass a spec). -/// -/// Filling replaces the unit's entire `post` map (single spec, single index -/// `{0,0,0}`) with circularly-derived expectations, so a unit that already has a -/// non-empty `post` is refused unless `force` is set. -pub fn fill_test_suite( - path: &Path, - spec_override: Option, - force: bool, -) -> Result { - let path_str = path.to_string_lossy().into_owned(); - let fixture_err = |msg: String| TestError { - name: "fill".to_string(), - path: path_str.clone(), - kind: TestErrorKind::FixtureError(msg), - }; +/// A fixture file's tests, read so that a name appearing twice is an error rather than one test +/// silently replacing the other. +struct UniqueNames(TestSuite); - // Validation skips these filenames entirely, so a filled fixture here would - // never be checked — refuse rather than produce a vacuously-valid file. - if skip_test(path) { - return Err(fixture_err( - "this filename is on the validation skip list; the filled fixture would never \ - be validated" - .to_string(), - )); - } +impl<'de> Deserialize<'de> for UniqueNames { + fn deserialize>(deserializer: D) -> Result { + struct Tests; + impl<'de> Visitor<'de> for Tests { + type Value = UniqueNames; - let s = std::fs::read_to_string(path).map_err(|e| fixture_err(format!("read: {e}")))?; - let suite: TestSuite = serde_json::from_str(&s).map_err(|e| TestError { - name: "Unknown".to_string(), - path: path_str.clone(), - kind: e.into(), - })?; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a map of test names to tests") + } - let mut filled = std::collections::BTreeMap::new(); - for (name, mut unit) in suite.0 { - if !force && unit.post.values().any(|tests| !tests.is_empty()) { - return Err(fixture_err(format!( - "unit {name} already has a post expectation; pass --force to overwrite" - ))); - } - let spec = match spec_override { - Some(s) => s, - None => { - let mut specs = unit.post.keys(); - match (specs.next(), specs.next()) { - (Some(s), None) => *s, - _ => { - return Err(fixture_err(format!( - "unit {name} has no single post spec; pass --bench-spec to fill" - ))) + fn visit_map>(self, mut map: A) -> Result { + let mut tests = BTreeMap::new(); + while let Some(name) = map.next_key::()? { + let unit = map.next_value()?; + if tests.insert(name.clone(), unit).is_some() { + return Err(A::Error::custom(format!("test {name:?} appears twice"))); } } + Ok(UniqueNames(TestSuite(tests))) } - }; - // Reject an unmapped spec at selection time, so the error names the - // unit instead of surfacing from deep inside execution. - if spec == SpecName::Unknown { - return Err(fixture_err(format!( - "unit {name} selects an unknown spec; pass a valid --bench-spec" - ))); - } - // Validation skips Constantinople (mirroring upstream revme), so a post - // recorded under it would never be checked. - if spec == SpecName::Constantinople { - return Err(fixture_err(format!( - "unit {name}: validation skips Constantinople; a post filled under it \ - would never be checked" - ))); - } - let executed = execute_unit_collect(&unit, &spec) - .map_err(|e| fixture_err(format!("execute {name}: {e}")))?; - unit.out = executed.output.clone(); - let test = Test::for_dump( - executed.state_root, - executed.logs_root, - executed.gas_used, - executed.status, - ); - unit.post = std::collections::BTreeMap::from([(spec, vec![test])]); - filled.insert(name, unit); - } - - let count = filled.len(); - let json = serde_json::to_string_pretty(&TestSuite(filled)) - .map_err(|e| fixture_err(format!("serialize: {e}")))?; - // Write to a sibling temp file and rename so an interrupted write cannot - // truncate the original fixture. - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, json).map_err(|e| fixture_err(format!("write: {e}")))?; - std::fs::rename(&tmp, path).map_err(|e| fixture_err(format!("rename: {e}")))?; - Ok(count) -} - -fn prune_base_fee_vault_changes(db: &mut State) { - let base_fee_vault = address!("0x4200000000000000000000000000000000000019"); - db.cache.accounts.remove(&base_fee_vault); -} - -fn debug_failed_test<'a>(ctx: DebugContext<'a>) { - println!("\nTraces:"); - - // Re-run with tracing - let mut cache = ctx.cache_state.clone(); - cache.set_state_clear_flag(ctx.cfg.spec.into_eth_spec().is_enabled_in(SpecId::SPURIOUS_DRAGON)); - let mut state = - database::State::builder().with_cached_prestate(cache).with_bundle_update().build(); - - // The main run already validated the unit's `megaEnv` and `blockHashes`, so - // a failure here is unreachable; bail out of the debug re-run rather than - // panic. - if inject_block_hashes(&mut state, ctx.unit).is_err() { - return; - } - let Ok(external_envs) = external_envs_for(ctx.unit) else { - return; - }; - let evm_context = MegaContext::default() - .with_db(&mut state) - .with_cfg(ctx.cfg.clone()) - .with_block(ctx.block.clone()) - .with_external_envs(external_envs.into()); - let mut tx = MegaTransaction::new(ctx.tx.clone()); - tx.enveloped_tx = Some(Bytes::default()); - let mut evm = MegaEvm::new(evm_context) - .with_inspector(TracerEip3155::buffered(stderr()).without_summary()); - - let exec_result = evm.inspect_tx_commit(tx); - - let state_after = evm.into_inner().ctx.into_inner().journaled_state.database; - prune_base_fee_vault_changes(state_after); - - println!("\nExecution result: {exec_result:#?}"); - println!("\nExpected exception: {:?}", ctx.test.expect_exception); - println!("\nState before: {:#?}", ctx.cache_state); - println!("\nState after: {:#?}", state_after); - println!("\nSpecification: {:?}", ctx.cfg.spec); - println!("\nTx: {:#?}", ctx.tx); - println!("Block: {:#?}", ctx.block); - println!("Cfg: {:#?}", ctx.cfg); - println!( - "\nTest name: {:?} (index: {}, path: {:?}) failed:\n{}", - ctx.name, ctx.index, ctx.path, ctx.error - ); -} - -#[derive(Clone, Copy)] -struct TestRunnerConfig { - single_thread: bool, - trace: bool, - print_outcome: bool, - keep_going: bool, -} - -impl TestRunnerConfig { - fn new(single_thread: bool, trace: bool, print_outcome: bool, keep_going: bool) -> Self { - // Trace implies print_outcome - let print_outcome = print_outcome || trace; - // print_outcome or trace implies single_thread - let single_thread = single_thread || print_outcome; - - Self { single_thread, trace, print_outcome, keep_going } - } -} - -#[derive(Clone)] -struct TestRunnerState { - n_errors: Arc, - console_bar: Arc, - queue: Arc)>>, - elapsed: Arc>, -} - -impl TestRunnerState { - fn new(test_files: Vec) -> Self { - let n_files = test_files.len(); - Self { - n_errors: Arc::new(AtomicUsize::new(0)), - console_bar: Arc::new(ProgressBar::with_draw_target( - Some(n_files as u64), - ProgressDrawTarget::stdout(), - )), - queue: Arc::new(Mutex::new((0usize, test_files))), - elapsed: Arc::new(Mutex::new(Duration::ZERO)), } - } - - fn next_test(&self) -> Option { - let (current_idx, queue) = &mut *self.queue.lock().unwrap(); - let idx = *current_idx; - let test_path = queue.get(idx).cloned()?; - *current_idx = idx + 1; - Some(test_path) + deserializer.deserialize_map(Tests) } } -fn run_test_worker(state: TestRunnerState, config: TestRunnerConfig) -> Result<(), TestError> { - loop { - if !config.keep_going && state.n_errors.load(Ordering::SeqCst) > 0 { - return Ok(()); - } - - let Some(test_path) = state.next_test() else { - return Ok(()); - }; - - let result = - execute_test_suite(&test_path, &state.elapsed, config.trace, config.print_outcome); - - state.console_bar.inc(1); - - if let Err(err) = result { - state.n_errors.fetch_add(1, Ordering::SeqCst); - if !config.keep_going { - return Err(err); - } +/// Names the deviation that explains a failure of the entry `id`, in equivalence mode. +fn attribute(config: Config, id: &TestId, outcome: Outcome) -> Outcome { + match outcome { + Outcome::Failed(mut failure) if config.mode == Mode::Equivalence => { + failure.deviation = + deviations::attribute(config.deviations, config.fork, id, failure.produced) + .map(|deviation| deviation.id); + Outcome::Failed(failure) } - } + outcome => outcome, + } +} + +fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { + panic + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_else(|| "a panic without a message".into()) +} + +fn print_outcome(config: Config, id: &TestId, outcome: &Outcome) { + let line = serde_json::json!({ + "mode": config.mode, + "fork": config.fork, + "path": id.path, + "test": id.name, + "d": id.indexes.0, + "g": id.indexes.1, + "v": id.indexes.2, + "result": outcome, + }); + eprintln!("{line}"); +} + +/// The chain id `unit` runs on: its own, or mainnet's when it names none, as the reference runner +/// has it. One that does not fit a `u64` is a fixture error rather than a value clamped to fit. +pub(crate) fn chain_id(unit: &TestUnit) -> Result { + let id = unit.env.current_chain_id.unwrap_or(U256::ONE); + id.try_into().map_err(|_| { + Failure::new(FailureKind::Fixture, format!("currentChainID {id} does not fit a u64")) + }) } -fn determine_thread_count(single_thread: bool, n_files: usize) -> usize { - match (single_thread, std::thread::available_parallelism()) { - (true, _) | (false, Err(_)) => 1, - (false, Ok(n)) => n.get().min(n_files), +/// Executes one entry and judges it against its fixture. +fn run_test(config: Config, unit: &TestUnit, test: &Test) -> Outcome { + match execute_and_check(config, unit, test) { + Ok(None) => Outcome::Passed, + Ok(Some(reason)) => Outcome::Skipped { reason }, + Err(failure) => Outcome::Failed(failure), } } -/// Run all test files in parallel or single-threaded mode -/// -/// # Arguments -/// * `test_files` - List of test files to execute -/// * `single_thread` - Force single-threaded execution -/// * `trace` - Enable EVM execution tracing -/// * `print_outcome` - Print test outcomes in JSON format -/// * `keep_going` - Continue running tests even if some fail -pub fn run( - test_files: Vec, - single_thread: bool, - trace: bool, - print_outcome: bool, - keep_going: bool, -) -> Result<(), TestError> { - let config = TestRunnerConfig::new(single_thread, trace, print_outcome, keep_going); - let n_files = test_files.len(); - let state = TestRunnerState::new(test_files); - let num_threads = determine_thread_count(config.single_thread, n_files); - - // Spawn worker threads - let mut handles = Vec::with_capacity(num_threads); - for i in 0..num_threads { - let state = state.clone(); - - let thread = std::thread::Builder::new() - .name(format!("runner-{i}")) - .spawn(move || run_test_worker(state, config)) - .unwrap(); - - handles.push(thread); - } - - // Collect results from all threads - let mut thread_errors = Vec::new(); - for (i, handle) in handles.into_iter().enumerate() { - match handle.join() { - Ok(Ok(())) => {} - Ok(Err(e)) => thread_errors.push(e), - Err(_) => thread_errors.push(TestError { - name: format!("thread {i} panicked"), - path: String::new(), - kind: TestErrorKind::Panic, - }), - } - } - - state.console_bar.finish(); - - // Print summary - println!( - "Finished execution. Total CPU time: {:.6}s", - state.elapsed.lock().unwrap().as_secs_f64() - ); - - let n_errors = state.n_errors.load(Ordering::SeqCst); - let n_thread_errors = thread_errors.len(); +fn execute_and_check( + config: Config, + unit: &TestUnit, + test: &Test, +) -> Result, Failure> { + let Ready { chain_id, block, tx } = match prepare(config.fork, unit, test)? { + Ok(ready) => ready, + Err(reason) => return Ok(Some(reason)), + }; - if n_errors == 0 && n_thread_errors == 0 { - println!("All tests passed!"); - Ok(()) + let basefee = block.basefee; + let mut state = + State::builder().with_cached_prestate(unit.state()).with_bundle_update().build(); + let evm = config.mode.evm(config.fork, &mut state, block, chain_id); + let result = if config.trace { + let mut evm = evm.with_inspector(TracerEip3155::buffered(stderr()).without_summary()); + evm.inspect_tx_commit(tx) } else { - println!("Encountered {n_errors} errors out of {n_files} total tests"); - - // No thread carried a structured error (e.g. failures under - // `keep_going`): report the failure count as an error instead of - // exiting the process — this is library code, the CLI owns the - // exit-code contract. - if n_thread_errors == 0 { - return Err(TestError { - name: "summary".to_string(), - path: String::new(), - kind: TestErrorKind::TestsFailed { failed: n_errors, total: n_files }, - }); - } - - if n_thread_errors > 1 { - println!("{n_thread_errors} threads returned an error, out of {num_threads} total:"); - for error in &thread_errors { - println!("{error}"); + let mut evm = evm; + evm.transact_commit(tx) + }; + if let Ok(result) = &result { + undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); + } + check(config.fork, test, unit.out.as_ref(), &result, &state)?; + Ok(None) +} + +/// An entry ready to run: its chain id, block and transaction. +pub(crate) struct Ready { + /// The chain id the entry runs on. + pub(crate) chain_id: u64, + /// The block the entry runs in. + pub(crate) block: BlockEnv, + /// The transaction the entry runs. + pub(crate) tx: OpTx, +} + +/// Builds what an entry of `fork` runs: the chain id, the block, built the way the reference +/// runner builds it from the fork's Ethereum configuration (the blob base fee fraction and the +/// default `prevrandao` come from there), and the transaction; or the reason the entry is not +/// executed. A transaction the fixture types cannot build is a skip when the fixture names the +/// reason it cannot be, a failure otherwise. +pub(crate) fn prepare( + fork: Fork, + unit: &TestUnit, + test: &Test, +) -> Result, Failure> { + let chain_id = chain_id(unit)?; + + let mut eth_cfg = CfgEnv::new(); + eth_cfg.chain_id = chain_id; + eth_cfg.set_spec_and_mainnet_gas_params(fork.spec_id()); + eth_cfg.set_max_blobs_per_tx(MAX_BLOBS_PER_TX); + let block = unit.block_env(&mut eth_cfg); + + let tx = match (test.tx_env(unit), &test.expect_exception) { + (Ok(tx), _) => tx, + (Err(error), Some(expected)) => { + return match exceptions::check_unbuildable(expected, &error, unit) { + Ok(()) => Ok(Err(SkipReason::UnbuildableInvalidTransaction)), + Err(_) => Err(Failure::new( + FailureKind::WrongException, + format!("expected {expected}, the transaction cannot be built: {error}"), + )), } } - Err(thread_errors.swap_remove(0)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use mega_evm::revm::context::result::{Output, SuccessReason}; - use serde_json::json; - - fn success(gas_used: u64) -> ExecutionResult { - ExecutionResult::Success { - reason: SuccessReason::Stop, - gas_used, - gas_refunded: 0, - logs: vec![], - output: Output::Call(Bytes::new()), - } - } - - fn revert(gas_used: u64) -> ExecutionResult { - ExecutionResult::Revert { gas_used, output: Bytes::new() } - } - - fn test_with_mega(mega_gas_used: Option, mega_status: Option<&str>) -> Test { - let mut value = json!({ - "indexes": { "data": 0, "gas": 0, "value": 0 }, - "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "logs": "0x0000000000000000000000000000000000000000000000000000000000000000", - }); - if let Some(gas) = mega_gas_used { - value["megaGasUsed"] = json!(gas); - } - if let Some(status) = mega_status { - value["megaStatus"] = json!(status); + (Err(error), None) => { + return Err(Failure::new(FailureKind::Fixture, format!("transaction: {error}"))) } - serde_json::from_value(value).expect("valid Test json") - } - - #[test] - fn test_execution_status_strings() { - assert_eq!(execution_status(&success(21_000)), "success"); - assert_eq!(execution_status(&revert(21_000)), "revert"); - } - - // Full domain of `halt_reason`: None for success/revert, the Debug-formatted - // reason for halts — the value `--dump-fixture` cross-checks so two halts - // with different reasons cannot be conflated. - #[test] - fn test_halt_reason_domain() { - assert_eq!(halt_reason(&success(21_000)), None); - assert_eq!(halt_reason(&revert(21_000)), None); - let reason = halt_reason(&halt()).expect("halt has a reason"); - assert!(reason.contains("DataLimitExceeded"), "unexpected reason: {reason}"); - } - - #[test] - fn test_mega_expectations_pass_when_matching() { - let test = test_with_mega(Some(21_000), Some("success")); - assert!(validate_mega_expectations(&test, &success(21_000)).is_ok()); - } + }; + let tx = + OpTx(OpTransaction { base: tx, enveloped_tx: Some(Bytes::new()), ..Default::default() }); + Ok(Ok(Ready { chain_id, block, tx })) +} - #[test] - fn test_mega_expectations_absent_fields_skip() { - // Pure-Ethereum test: no mega expectations → never fails on gas/status. - let test = test_with_mega(None, None); - assert!(validate_mega_expectations(&test, &success(99_999)).is_ok()); +/// Takes back out of `state` the base-fee vault account Satin's fee routing created, where +/// Ethereum burns the fee: the fixture's pre-state has no vault, and the vault holds the base fee +/// of the `gas_used` the transaction reports and nothing else. +/// +/// The L1 and operator fee vaults are credited nothing here, so they are touched and empty, and +/// EIP-161 has already removed them; one that is not stays for the root to show. +fn undo_fee_vault_credit(unit: &TestUnit, state: &mut State, basefee: u64, gas_used: u64) { + if unit.pre.contains_key(&BASE_FEE_RECIPIENT) { + return; } - - #[test] - fn test_mega_expectations_gas_mismatch() { - let test = test_with_mega(Some(21_000), None); - let err = validate_mega_expectations(&test, &success(21_042)).unwrap_err(); - match err { - TestErrorKind::GasUsedMismatch { got, expected } => { - assert_eq!(got, 21_042); - assert_eq!(expected, 21_000); - } - other => panic!("expected GasUsedMismatch, got {other:?}"), - } + let Some(cached) = state.cache.accounts.get(&BASE_FEE_RECIPIENT) else { return }; + let fee = U256::from(basefee) * U256::from(gas_used); + let routed_fee_only = cached.account.as_ref().is_none_or(|account| { + account.info.balance == fee && + account.info.nonce == 0 && + account.info.code_hash == KECCAK_EMPTY && + account.storage.is_empty() + }); + if routed_fee_only { + state.cache.accounts.remove(&BASE_FEE_RECIPIENT); } +} - #[test] - fn test_mega_expectations_status_mismatch() { - let test = test_with_mega(None, Some("success")); - let err = validate_mega_expectations(&test, &revert(21_000)).unwrap_err(); - match err { - TestErrorKind::StatusMismatch { got, expected } => { - assert_eq!(got, "revert"); - assert_eq!(expected, "success"); +/// Judges an executed entry of `fork` against its fixture. +/// +/// A rejected transaction must be rejected for the reason the fixture names and must leave the +/// fixture's post-state, which is its pre-state; an executed one must produce the fixture's +/// output, logs and post-state. A logs or state-root mismatch carries the hashes produced, the +/// state root included when the logs already differ. +fn check( + fork: Fork, + test: &Test, + expected_output: Option<&Bytes>, + result: &Result, EVMError>, + state: &State, +) -> Result<(), Failure> { + match (&test.expect_exception, result) { + (Some(expected), Err(error)) => match exceptions::check(fork, expected, error) { + Ok(()) => {} + Err(Mismatch::Wrong { got }) => { + return Err(Failure::new( + FailureKind::WrongException, + format!("expected {expected}, rejected as {got:?}: {error:?}"), + )) } - other => panic!("expected StatusMismatch, got {other:?}"), - } - } - - fn success_with_output(output: &[u8]) -> ExecutionResult { - ExecutionResult::Success { - reason: SuccessReason::Stop, - gas_used: 21_000, - gas_refunded: 0, - logs: vec![], - output: Output::Call(Bytes::copy_from_slice(output)), - } - } - - fn halt() -> ExecutionResult { - ExecutionResult::Halt { - reason: MegaHaltReason::DataLimitExceeded { limit: 0, actual: 0 }, - gas_used: 21_000, - } - } - - // Full domain of the (expected, actual) output predicate. - #[test] - fn test_validate_output_no_expectation_never_fails() { - // Expected absent: no check, regardless of what execution produced. - assert!(validate_output(None, &success_with_output(b"\x01")).is_ok()); - assert!(validate_output(None, &halt()).is_ok()); - } - - #[test] - fn test_validate_output_matching_passes() { - let expected = Bytes::copy_from_slice(b"\x01\x02"); - assert!(validate_output(Some(&expected), &success_with_output(b"\x01\x02")).is_ok()); - } - - #[test] - fn test_validate_output_mismatch_fails() { - let expected = Bytes::copy_from_slice(b"\x01\x02"); - let err = validate_output(Some(&expected), &success_with_output(b"\xff")).unwrap_err(); - assert!(matches!(err, TestErrorKind::UnexpectedOutput { .. }), "got {err:?}"); - } - - #[test] - fn test_validate_output_expected_but_none_produced_fails() { - // A halt produces no output; an expectation must not be - // silently satisfied by `zip` short-circuiting. - let expected = Bytes::copy_from_slice(b"\x01\x02"); - let err = validate_output(Some(&expected), &halt()).unwrap_err(); - match err { - TestErrorKind::UnexpectedOutput { expected_output, got_output } => { - assert_eq!(expected_output, Some(expected)); - assert_eq!(got_output, None); + Err(Mismatch::Unnamed) => { + return Err(Failure::new( + FailureKind::UnnamedException, + format!("expected {expected}, rejected with {error:?}"), + )) } - other => panic!("expected UnexpectedOutput, got {other:?}"), - } - } - - #[test] - fn test_skip_test_domain() { - // On the skip list. - assert!(skip_test(Path::new("/tests/ValueOverflow.json"))); - // Ordinary name, not skipped. - assert!(!skip_test(Path::new("/tests/regular_fixture.json"))); - // No file name at all: not skipped, must not panic. - assert!(!skip_test(Path::new("/"))); - } - - #[cfg(unix)] - #[test] - fn test_skip_test_non_utf8_name_is_not_skipped() { - use std::{ffi::OsStr, os::unix::ffi::OsStrExt}; - // 0xff is not valid UTF-8; such a name can never match the skip list. - let path = Path::new(OsStr::from_bytes(b"/tests/\xff\xfe.json")); - assert!(!skip_test(path)); - } - - fn env_with_chain_id(chain_id: Option<&str>) -> Env { - let mut json = json!({ - "currentCoinbase": "0x3000000000000000000000000000000000000003", - "currentGasLimit": "0x0", - "currentNumber": "0x0", - "currentTimestamp": "0x0", - }); - if let Some(id) = chain_id { - json["currentChainID"] = json!(id); + }, + (Some(expected), Ok(result)) => { + return Err(Failure::new( + FailureKind::MissingException, + format!("expected {expected}, executed: {}", describe(result)), + )) } - serde_json::from_value(json).expect("valid Env json") - } - - // Full domain of the chain-id predicate: absent, in-range, boundary, overflow. - #[test] - fn test_resolve_chain_id_absent_defaults() { - assert_eq!(resolve_chain_id(&env_with_chain_id(None)).unwrap(), 6342); - } - - #[test] - fn test_resolve_chain_id_in_range_values() { - assert_eq!(resolve_chain_id(&env_with_chain_id(Some("0x1"))).unwrap(), 1); - // u64::MAX is the largest representable chain id. - assert_eq!( - resolve_chain_id(&env_with_chain_id(Some("0xffffffffffffffff"))).unwrap(), - u64::MAX - ); - } - - #[test] - fn test_resolve_chain_id_overflow_is_fixture_error() { - // u64::MAX + 1 must be a structured error, not a silent 6342 run. - let err = resolve_chain_id(&env_with_chain_id(Some("0x10000000000000000"))).unwrap_err(); - match err { - TestErrorKind::FixtureError(msg) => { - assert!(msg.contains("currentChainID"), "message names the field: {msg}"); - } - other => panic!("expected FixtureError, got {other:?}"), + (None, Err(error)) => { + return Err(Failure::new(FailureKind::UnexpectedException, format!("{error:?}"))) } + (None, Ok(result)) => check_output(expected_output, result)?, + } + let logs: &[_] = result.as_ref().map(ExecutionResult::logs).unwrap_or_default(); + let logs_hash = logs_hash(logs); + let root = state_root(state.cache.trie_account()); + let executed = result.as_ref().map(|r| format!("; {}", describe(r))).unwrap_or_default(); + if logs_hash != test.logs { + return Err(Failure::produced( + Produced::Logs { logs: logs_hash, state_root: root }, + format!( + "logs hash {logs_hash}, expected {}; state root {root}, expected {}{executed}", + test.logs, test.hash + ), + )); } - - #[test] - fn test_tx_build_error_mapping_preserves_cause() { - // Cause masking: every non-key error keeps its real message. - let kind: TestErrorKind = - TxBuildError::PartIndexOutOfBounds { part: "data", index: 7, len: 1 }.into(); - match kind { - TestErrorKind::FixtureError(msg) => assert!(msg.contains("out of bounds"), "{msg}"), - other => panic!("expected FixtureError, got {other:?}"), - } - - let key = B256::repeat_byte(0xcd); - let kind: TestErrorKind = TxBuildError::UnknownPrivateKey(key).into(); - match kind { - TestErrorKind::UnknownPrivateKey(k) => assert_eq!(k, key), - other => panic!("expected UnknownPrivateKey, got {other:?}"), - } + if root != test.hash { + return Err(Failure::produced( + Produced::StateRoot(root), + format!("state root {root}, expected {}{executed}", test.hash), + )); } + Ok(()) +} - #[test] - fn test_unknown_private_key_display_redacted() { - // Neither error layer's Display may contain key material. - let key = B256::repeat_byte(0xcd); - let msg = TestErrorKind::UnknownPrivateKey(key).to_string(); - assert!(!msg.contains("cdcd"), "display leaks key material: {msg}"); - assert!(msg.contains("redacted"), "display should say redacted: {msg}"); +/// An expected output must be produced: a halt, which produces none, does not satisfy one. +fn check_output( + expected: Option<&Bytes>, + result: &ExecutionResult, +) -> Result<(), Failure> { + let Some(expected) = expected else { return Ok(()) }; + if result.output() != Some(expected) { + return Err(Failure::new( + FailureKind::OutputMismatch, + format!("output {:?}, expected {expected}", result.output()), + )); } + Ok(()) +} - #[test] - fn test_tests_failed_display() { - let msg = TestErrorKind::TestsFailed { failed: 3, total: 10 }.to_string(); - assert!(msg.contains('3') && msg.contains("10"), "{msg}"); - } +fn describe(result: &ExecutionResult) -> String { + let status = match result { + ExecutionResult::Success { reason, .. } => format!("success ({reason:?})"), + ExecutionResult::Revert { .. } => "revert".into(), + ExecutionResult::Halt { reason, .. } => format!("halt ({reason:?})"), + }; + format!("{status}, gas used {}", result.tx_gas_used()) } diff --git a/crates/mega-state-test/src/skips.rs b/crates/mega-state-test/src/skips.rs new file mode 100644 index 000000000..6b8ae5571 --- /dev/null +++ b/crates/mega-state-test/src/skips.rs @@ -0,0 +1,113 @@ +//! The tests the runner does not execute, and why. +//! +//! Every skip is one the revm fork's reference runner makes too, for the same reason, so the two +//! runners execute the same population and their executed and skipped counts can be compared +//! number for number. Satin inherits every one of the reasons from revm: none of them is a place +//! Satin differs from Ethereum, which is what a [deviation](crate::deviations) is. + +use serde::Serialize; + +/// Why a test was not executed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum SkipReason { + /// The test creates an account at an address whose pre-state holds storage and nothing else + /// (EIP-7610). revm reads storage slot by slot and never asks the database whether an account + /// has any, so it cannot see the collision. + CreateCollisionWithStorage, + /// The fixture's transaction cannot be built — an invalid signature, a blob or an EIP-7702 + /// transaction without a recipient — and the fixture expects it to be invalid. + UnbuildableInvalidTransaction, + /// A value in the fixture overflows the width revm gives it. + MalformedValue, + /// The test passes but takes minutes. + Slow, +} + +impl SkipReason { + /// Every reason. + pub const ALL: [Self; 4] = [ + Self::CreateCollisionWithStorage, + Self::UnbuildableInvalidTransaction, + Self::MalformedValue, + Self::Slow, + ]; + + /// The reason's name, as the summary prints it. + pub const fn name(self) -> &'static str { + match self { + Self::CreateCollisionWithStorage => "create-collision-with-storage", + Self::UnbuildableInvalidTransaction => "unbuildable-invalid-transaction", + Self::MalformedValue => "malformed-value", + Self::Slow => "slow", + } + } +} + +/// The directory of the EIP-7610 collision tests, every one of which collides with storage. +const CREATE_COLLISION_DIR: &str = "paris/eip7610_create_collision"; + +/// Whether the file at `path` is skipped whole, and why: the reference runner's list, file for +/// file. +pub fn skip_file(path: &str) -> Option { + if path.replace('\\', "/").contains(CREATE_COLLISION_DIR) { + return Some(SkipReason::CreateCollisionWithStorage); + } + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + match name { + "RevertInCreateInInit_Paris.json" | + "RevertInCreateInInit.json" | + "dynamicAccountOverwriteEmpty.json" | + "dynamicAccountOverwriteEmpty_Paris.json" | + "RevertInCreateInInitCreate2Paris.json" | + "create2collisionStorage.json" | + "RevertInCreateInInitCreate2.json" | + "create2collisionStorageParis.json" | + "InitCollision.json" | + "InitCollisionParis.json" | + "test_init_collision_create_opcode.json" => Some(SkipReason::CreateCollisionWithStorage), + "ValueOverflow.json" | "ValueOverflowParis.json" => Some(SkipReason::MalformedValue), + "Call50000_sha256.json" | + "static_Call50000_sha256.json" | + "loopMul.json" | + "CALLBlake2f_MaxRounds.json" => Some(SkipReason::Slow), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_skip_file_matches_the_collision_directory() { + assert_eq!( + skip_file("fixtures/state_tests/paris/eip7610_create_collision/test_init_collision_create_tx.json"), + Some(SkipReason::CreateCollisionWithStorage) + ); + assert_eq!( + skip_file("devnet/state_tests/for_amsterdam/paris/eip7610_create_collision/revert_in_create/x.json"), + Some(SkipReason::CreateCollisionWithStorage) + ); + } + + #[test] + fn test_skip_file_matches_names_not_substrings() { + assert_eq!( + skip_file("static/state_tests/stCreate2/create2collisionStorageParis.json"), + Some(SkipReason::CreateCollisionWithStorage) + ); + assert_eq!(skip_file("a/ValueOverflow.json"), Some(SkipReason::MalformedValue)); + assert_eq!(skip_file("a/loopMul.json"), Some(SkipReason::Slow)); + assert_eq!(skip_file("a/xloopMul.json"), None); + assert_eq!(skip_file("a/loopMul.json.bak"), None); + assert_eq!(skip_file("osaka/eip7951_p256verify_precompiles/test_valid.json"), None); + assert_eq!(skip_file(""), None); + } + + #[test] + fn test_reason_names_are_distinct() { + let names: std::collections::BTreeSet<_> = SkipReason::ALL.map(SkipReason::name).into(); + assert_eq!(names.len(), SkipReason::ALL.len()); + } +} diff --git a/crates/mega-state-test/src/types/account_info.rs b/crates/mega-state-test/src/types/account_info.rs deleted file mode 100644 index dcdd146a0..000000000 --- a/crates/mega-state-test/src/types/account_info.rs +++ /dev/null @@ -1,20 +0,0 @@ -use std::collections::BTreeMap; - -use mega_evm::revm::primitives::{Bytes, StorageKey, StorageValue, U256}; -use serde::{Deserialize, Serialize}; - -/// Account information -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct AccountInfo { - /// Account balance in wei - pub balance: U256, - /// Account bytecode - pub code: Bytes, - /// Account nonce (transaction count) - #[serde(with = "alloy_serde::quantity")] - pub nonce: u64, - /// Account storage (key-value pairs), ordered by slot so serialized fixtures - /// are byte-reproducible. - pub storage: BTreeMap, -} diff --git a/crates/mega-state-test/src/types/deserializer.rs b/crates/mega-state-test/src/types/deserializer.rs deleted file mode 100644 index a41d41d55..000000000 --- a/crates/mega-state-test/src/types/deserializer.rs +++ /dev/null @@ -1,44 +0,0 @@ -use mega_evm::revm::primitives::Address; -use serde::{de, Deserialize, Serialize, Serializer}; - -/// Deserializes a [string][String] as a [u64]. -pub fn deserialize_str_as_u64<'de, D>(deserializer: D) -> Result -where - D: de::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(serde::de::Error::custom) -} - -/// Deserializes a [string][String] as an optional [Address]. -pub fn deserialize_maybe_empty<'de, D>(deserializer: D) -> Result, D::Error> -where - D: de::Deserializer<'de>, -{ - let string = String::deserialize(deserializer)?; - if string.is_empty() { - Ok(None) - } else { - string.parse().map_err(de::Error::custom).map(Some) - } -} - -/// Serializes an optional [Address], writing `""` for `None` (contract creation) -/// so it round-trips with [`deserialize_maybe_empty`]. The default `Option` -/// serializer would emit `null`, which that deserializer rejects — breaking any -/// re-serialization of a CREATE transaction (e.g. `--dump-fixture` / `--fill`). -pub fn serialize_maybe_empty(addr: &Option
, serializer: S) -> Result -where - S: Serializer, -{ - match addr { - Some(address) => address.serialize(serializer), - None => serializer.serialize_str(""), - } -} diff --git a/crates/mega-state-test/src/types/env.rs b/crates/mega-state-test/src/types/env.rs deleted file mode 100644 index a36b324fb..000000000 --- a/crates/mega-state-test/src/types/env.rs +++ /dev/null @@ -1,91 +0,0 @@ -use std::collections::BTreeMap; - -use alloy_eips::eip4895::Withdrawal; -use mega_evm::revm::primitives::{Address, B256, U256}; -use serde::{Deserialize, Serialize}; - -/// Environment variables -#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Env { - /// Chain ID for the current execution - #[serde(rename = "currentChainID", skip_serializing_if = "Option::is_none")] - pub current_chain_id: Option, - /// Block coinbase address (miner/validator) - pub current_coinbase: Address, - /// Block difficulty (pre-merge) or prevrandao (post-merge) - #[serde(default)] - pub current_difficulty: U256, - /// Block gas limit - pub current_gas_limit: U256, - /// Current block number - pub current_number: U256, - /// Current block timestamp - pub current_timestamp: U256, - /// EIP-1559 base fee per gas - #[serde(skip_serializing_if = "Option::is_none")] - pub current_base_fee: Option, - /// Previous block hash - #[serde(skip_serializing_if = "Option::is_none")] - pub previous_hash: Option, - /// Parent block timestamp - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_timestamp: Option, - /// Parent block gas used - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_gas_used: Option, - /// Parent block gas limit - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_gas_limit: Option, - /// Parent block base fee - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_base_fee: Option, - /// Parent block hash - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_hash: Option, - /// Parent block uncle hash - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_uncle_hash: Option, - /// Parent block beacon block root - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_beacon_block_root: Option, - /// Parent block difficulty - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_difficulty: Option, - - /// Block hashes - #[serde(skip_serializing_if = "Option::is_none")] - pub block_hashes: Option>, - /// Ommers - #[serde(skip_serializing_if = "Option::is_none")] - pub ommers: Option>, - /// Withdrawals - #[serde(skip_serializing_if = "Option::is_none")] - pub withdrawals: Option>, - - /// Current block randomness (EIP-4399 prevrandao) - #[serde(skip_serializing_if = "Option::is_none")] - pub current_random: Option, - /// Current beacon chain root (EIP-4788) - #[serde(skip_serializing_if = "Option::is_none")] - pub current_beacon_root: Option, - /// Current withdrawals root - #[serde(skip_serializing_if = "Option::is_none")] - pub current_withdrawals_root: Option, - - /// Parent block blob gas used (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_blob_gas_used: Option, - /// Parent block excess blob gas (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_excess_blob_gas: Option, - /// Parent block target blobs per block (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_target_blobs_per_block: Option, - /// Current block excess blob gas (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none")] - pub current_excess_blob_gas: Option, - /// Current block blob gas used (EIP-4844) - #[serde(skip_serializing_if = "Option::is_none")] - pub current_blob_gas_used: Option, -} diff --git a/crates/mega-state-test/src/types/error.rs b/crates/mega-state-test/src/types/error.rs deleted file mode 100644 index 959798b48..000000000 --- a/crates/mega-state-test/src/types/error.rs +++ /dev/null @@ -1,66 +0,0 @@ -use mega_evm::revm::primitives::{B256, U256}; -use thiserror::Error; - -/// Errors that can occur during test setup and execution -#[derive(Debug, Error)] -pub enum TestError { - /// Unknown private key. - /// - /// The raw key is kept for programmatic use but deliberately redacted from - /// the `Display` output: fixture `secretKey` values flow through error - /// messages into logs and CI output. - #[error("unable to recover sender from fixture secretKey (key redacted)")] - UnknownPrivateKey(B256), - /// Invalid transaction type. - #[error("invalid transaction type")] - InvalidTransactionType, - /// A transaction part index points past the end of its array. - #[error("transaction part index {index} out of bounds for `{part}` (len {len})")] - PartIndexOutOfBounds { - /// Name of the indexed transaction part (`gasLimit`, `data`, or `value`). - part: &'static str, - /// The requested index. - index: usize, - /// The array's length. - len: usize, - }, - /// A transaction field's fixture value does not fit the integer width the - /// EVM uses for it (e.g. a `nonce` beyond `u64::MAX`). - #[error("transaction `{field}` value {value} exceeds the supported range")] - ValueOutOfRange { - /// Name of the out-of-range transaction field. - field: &'static str, - /// The fixture value that did not fit. - value: U256, - }, - /// Unexpected exception. - #[error("unexpected exception: got {got_exception:?}, expected {expected_exception:?}")] - UnexpectedException { - /// Expected exception. - expected_exception: Option, - /// Got exception. - got_exception: Option, - }, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn unknown_private_key_display_redacts_key_material() { - // The fixture secret key must never appear in the message. - let key = B256::repeat_byte(0xab); - let msg = TestError::UnknownPrivateKey(key).to_string(); - assert!(!msg.contains("abab"), "display leaks key material: {msg}"); - assert!(!msg.contains(&format!("{key:?}")), "display leaks key material: {msg}"); - assert!(msg.contains("redacted"), "display should say redacted: {msg}"); - } - - #[test] - fn value_out_of_range_display_names_field_and_value() { - let msg = TestError::ValueOutOfRange { field: "nonce", value: U256::MAX }.to_string(); - assert!(msg.contains("nonce"), "missing field name: {msg}"); - assert!(msg.contains(&U256::MAX.to_string()), "missing value: {msg}"); - } -} diff --git a/crates/mega-state-test/src/types/mega_env.rs b/crates/mega-state-test/src/types/mega_env.rs deleted file mode 100644 index e6e7162b2..000000000 --- a/crates/mega-state-test/src/types/mega_env.rs +++ /dev/null @@ -1,92 +0,0 @@ -use mega_evm::{revm::primitives::U256, BucketHasher, TestExternalEnvs}; -use serde::{Deserialize, Serialize}; -use std::convert::Infallible; - -/// `MegaETH` external-environment inputs that are not part of the standard EEST -/// state-test schema but are required to deterministically reproduce a `MegaETH` -/// transaction (dynamic SALT-bucket gas pricing and oracle reads). -/// -/// When a `TestUnit` omits this field the runner falls back to the empty -/// external environment, leaving pure-Ethereum tests unaffected. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MegaEnv { - /// SALT bucket capacity pairs `(bucket_id, capacity)`. - #[serde(default)] - pub bucket_capacities: Vec<(u32, u64)>, - /// Oracle contract storage `(slot, value)` pairs served during execution. - #[serde(default)] - pub oracle_storage: Vec<(U256, U256)>, -} - -impl MegaEnv { - /// Checks that the recorded values are usable by the runner. - /// - /// Every bucket capacity must be at least [`mega_evm::MIN_BUCKET_SIZE`]: - /// `DynamicGasCost` asserts this at lookup time, so a smaller capacity in a - /// hand-edited fixture would abort the process instead of failing the test. - pub fn validate(&self) -> Result<(), String> { - for &(bucket_id, capacity) in &self.bucket_capacities { - if capacity < mega_evm::MIN_BUCKET_SIZE as u64 { - return Err(format!( - "megaEnv bucket {bucket_id} capacity {capacity} is below \ - MIN_BUCKET_SIZE ({})", - mega_evm::MIN_BUCKET_SIZE - )); - } - } - Ok(()) - } - - /// Build a [`TestExternalEnvs`] that reproduces the recorded SALT bucket - /// capacities and oracle storage. - /// - /// The hasher is left generic so callers in different crates (which use - /// different concrete bucket hashers) can pick their own. - pub fn to_external_envs(&self) -> TestExternalEnvs { - let mut envs = TestExternalEnvs::new(); - for &(bucket_id, capacity) in &self.bucket_capacities { - envs = envs.with_bucket_capacity(bucket_id, capacity); - } - for &(slot, value) in &self.oracle_storage { - envs = envs.with_oracle_storage(slot, value); - } - envs - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_mega_env_json_roundtrip() { - let env = MegaEnv { - bucket_capacities: vec![(1, 100), (42, 2_000_000)], - oracle_storage: vec![(U256::from(0), U256::from(7)), (U256::from(9), U256::MAX)], - }; - - let json = serde_json::to_string(&env).expect("serialize"); - let back: MegaEnv = serde_json::from_str(&json).expect("deserialize"); - assert_eq!(env, back); - } - - #[test] - fn test_mega_env_camel_case_field_names() { - let env = MegaEnv { - bucket_capacities: vec![(1, 100)], - oracle_storage: vec![(U256::from(0), U256::from(7))], - }; - let value = serde_json::to_value(&env).expect("serialize"); - assert!(value.get("bucketCapacities").is_some(), "expected camelCase bucketCapacities"); - assert!(value.get("oracleStorage").is_some(), "expected camelCase oracleStorage"); - } - - #[test] - fn test_mega_env_empty_fields_default() { - // Missing fields should default to empty vectors. - let env: MegaEnv = serde_json::from_str("{}").expect("deserialize empty"); - assert!(env.bucket_capacities.is_empty()); - assert!(env.oracle_storage.is_empty()); - } -} diff --git a/crates/mega-state-test/src/types/mod.rs b/crates/mega-state-test/src/types/mod.rs deleted file mode 100644 index eb97ca8ea..000000000 --- a/crates/mega-state-test/src/types/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! # state-test-types -//! # This module is copied from `revm`'s `revm-statetest-types` crate. -//! -//! This module provides type definitions and utilities for Ethereum state tests, -//! specifically tailored for use with REVM. -//! -//! It includes structures for representing account information, environment settings, -//! test cases, and transaction data used in Ethereum state tests. - -mod account_info; -mod deserializer; -mod env; -mod error; -mod mega_env; -mod spec; -mod test; -mod test_authorization; -mod test_suite; -mod test_unit; -mod transaction; - -pub use account_info::*; -pub use deserializer::*; -pub use env::*; -pub use error::*; -pub use mega_env::*; -pub use spec::*; -pub use test::*; -pub use test_authorization::*; -pub use test_suite::*; -pub use test_unit::*; -pub use transaction::*; diff --git a/crates/mega-state-test/src/types/spec.rs b/crates/mega-state-test/src/types/spec.rs deleted file mode 100644 index 4f5e672ce..000000000 --- a/crates/mega-state-test/src/types/spec.rs +++ /dev/null @@ -1,235 +0,0 @@ -use mega_evm::MegaSpecId; -use serde::{Deserialize, Serialize}; -use thiserror::Error; - -/// Error returned when a [`SpecName`] has no [`MegaSpecId`] mapping. -/// -/// Produced for [`SpecName::Unknown`], which is what any unrecognized spec -/// string in a fixture's `post` map (or a future spec this crate does not know -/// yet) deserializes to. The original string is not retained by serde's -/// `other` fallback, so callers should add the surrounding fixture context. -#[derive(Debug, Error, PartialEq, Eq)] -#[error("unknown or unsupported spec name (an unrecognized spec string deserializes to `SpecName::Unknown`)")] -pub struct UnknownSpecError; - -/// Ethereum specification names -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)] -pub enum SpecName { - /// Frontier hardfork (Ethereum launch, July 2015) - Frontier, - /// Transition from Frontier to Homestead at block 5 - FrontierToHomesteadAt5, - /// Homestead hardfork (March 2016) - Homestead, - /// Transition from Homestead to DAO fork at block 5 - HomesteadToDaoAt5, - /// Transition from Homestead to EIP-150 at block 5 - HomesteadToEIP150At5, - /// EIP-150 hardfork (Tangerine Whistle, October 2016) - EIP150, - /// EIP-158/EIP-161 hardfork (Spurious Dragon, November 2016) - EIP158, // EIP-161: State trie clearing - /// Transition from EIP-158 to Byzantium at block 5 - EIP158ToByzantiumAt5, - /// Byzantium hardfork (October 2017) - Byzantium, - /// Transition from Byzantium to Constantinople at block 5 (skipped) - ByzantiumToConstantinopleAt5, // SKIPPED - /// Transition from Byzantium to Constantinople Fix at block 5 - ByzantiumToConstantinopleFixAt5, - /// Constantinople hardfork (skipped due to reentrancy bug) - Constantinople, // SKIPPED - /// Constantinople Fix hardfork (Petersburg, February 2019) - ConstantinopleFix, - /// Istanbul hardfork (December 2019) - Istanbul, - /// Berlin hardfork (April 2021) - Berlin, - /// Transition from Berlin to London at block 5 - BerlinToLondonAt5, - /// London hardfork (August 2021, includes EIP-1559) - London, - /// Paris hardfork (part of The Merge) - Paris, - /// The Merge (September 2022, `PoW` to `PoS` transition) - Merge, - /// Shanghai hardfork (April 2023, includes withdrawals) - Shanghai, - /// Cancun hardfork (March 2024, includes EIP-4844) - Cancun, - /// Prague hardfork (future) - Prague, - /// Osaka hardfork (skipped) - Osaka, // SKIPPED - /// `MegaETH` `MiniRex` hardfork - MiniRex, - /// `MegaETH` `MiniRex1` alias spec (behavior: `Equivalence`) - MiniRex1, - /// `MegaETH` `MiniRex2` alias spec (behavior: `MiniRex`) - MiniRex2, - /// `MegaETH` `Equivalence` spec (Ethereum-equivalent baseline) - Equivalence, - /// `MegaETH` `Rex` spec - Rex, - /// `MegaETH` `Rex1` spec - Rex1, - /// `MegaETH` `Rex2` spec - Rex2, - /// `MegaETH` `Rex3` spec - Rex3, - /// `MegaETH` `Rex4` spec - Rex4, - /// `MegaETH` `Rex5` spec - Rex5, - /// `MegaETH` `Rex6` spec - Rex6, - /// `MegaETH` `Rex7` spec - Rex7, - /// Unknown or unsupported specification - #[serde(other)] - Unknown, -} - -impl SpecName { - /// Converts to a [`MegaSpecId`]. - /// All Ethereum spc is converted to [`MegaSpecId::EQUIVALENCE`]. Some tests may fail to - /// execute. We will skip them case by case. - /// - /// # Errors - /// - /// Returns [`UnknownSpecError`] for [`SpecName::Unknown`], i.e. a fixture - /// spec string that did not match any known name. - pub fn to_spec_id(&self) -> Result { - match self { - Self::MiniRex => Ok(MegaSpecId::MINI_REX), - Self::MiniRex1 => Ok(MegaSpecId::MINI_REX_1), - Self::MiniRex2 => Ok(MegaSpecId::MINI_REX_2), - Self::Rex => Ok(MegaSpecId::REX), - Self::Rex1 => Ok(MegaSpecId::REX1), - Self::Rex2 => Ok(MegaSpecId::REX2), - Self::Rex3 => Ok(MegaSpecId::REX3), - Self::Rex4 => Ok(MegaSpecId::REX4), - Self::Rex5 => Ok(MegaSpecId::REX5), - Self::Rex6 => Ok(MegaSpecId::REX6), - Self::Rex7 => Ok(MegaSpecId::REX7), - Self::Unknown => Err(UnknownSpecError), - // All Ethereum specs (and `Equivalence`) map to the equivalent baseline. - _ => Ok(MegaSpecId::EQUIVALENCE), - } - } - - /// Returns the [`SpecName`] corresponding to a [`MegaSpecId`]. - /// - /// Used when dumping a replay fixture so the `post` map is keyed by the spec - /// the transaction actually executed under. - pub fn from_mega_spec(spec: MegaSpecId) -> Self { - match spec { - MegaSpecId::MINI_REX => Self::MiniRex, - MegaSpecId::MINI_REX_1 => Self::MiniRex1, - MegaSpecId::MINI_REX_2 => Self::MiniRex2, - MegaSpecId::EQUIVALENCE => Self::Equivalence, - MegaSpecId::REX => Self::Rex, - MegaSpecId::REX1 => Self::Rex1, - MegaSpecId::REX2 => Self::Rex2, - MegaSpecId::REX3 => Self::Rex3, - MegaSpecId::REX4 => Self::Rex4, - MegaSpecId::REX5 => Self::Rex5, - MegaSpecId::REX6 => Self::Rex6, - MegaSpecId::REX7 => Self::Rex7, - _ => Self::Unknown, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_to_spec_id_known_specs_succeed() { - // MegaETH specs map to their own ids. - assert_eq!(SpecName::MiniRex.to_spec_id(), Ok(MegaSpecId::MINI_REX)); - assert_eq!(SpecName::MiniRex1.to_spec_id(), Ok(MegaSpecId::MINI_REX_1)); - assert_eq!(SpecName::MiniRex2.to_spec_id(), Ok(MegaSpecId::MINI_REX_2)); - assert_eq!(SpecName::Rex.to_spec_id(), Ok(MegaSpecId::REX)); - assert_eq!(SpecName::Rex1.to_spec_id(), Ok(MegaSpecId::REX1)); - assert_eq!(SpecName::Rex2.to_spec_id(), Ok(MegaSpecId::REX2)); - assert_eq!(SpecName::Rex3.to_spec_id(), Ok(MegaSpecId::REX3)); - assert_eq!(SpecName::Rex4.to_spec_id(), Ok(MegaSpecId::REX4)); - assert_eq!(SpecName::Rex5.to_spec_id(), Ok(MegaSpecId::REX5)); - assert_eq!(SpecName::Rex6.to_spec_id(), Ok(MegaSpecId::REX6)); - // Every Ethereum spec (and `Equivalence`) maps to the equivalent - // baseline — sample the oldest, a transition, and the newest. - for eth in [ - SpecName::Frontier, - SpecName::HomesteadToDaoAt5, - SpecName::Constantinople, - SpecName::Cancun, - SpecName::Osaka, - SpecName::Equivalence, - ] { - assert_eq!(eth.to_spec_id(), Ok(MegaSpecId::EQUIVALENCE)); - } - } - - #[test] - fn test_to_spec_id_unknown_is_a_clean_error() { - assert_eq!(SpecName::Unknown.to_spec_id(), Err(UnknownSpecError)); - } - - #[test] - fn test_unrecognized_spec_string_deserializes_to_unknown_and_errors() { - // An unrecognized fixture spec string takes serde's `other` fallback - // and must then convert to a structured error, never a panic. - let spec: SpecName = serde_json::from_str("\"FutureFork9000\"").expect("deserialize"); - assert_eq!(spec, SpecName::Unknown); - assert!(spec.to_spec_id().is_err()); - } - - #[test] - fn test_from_mega_spec_round_trips_known_specs() { - for spec in [ - MegaSpecId::MINI_REX, - MegaSpecId::MINI_REX_1, - MegaSpecId::MINI_REX_2, - MegaSpecId::EQUIVALENCE, - MegaSpecId::REX, - MegaSpecId::REX1, - MegaSpecId::REX2, - MegaSpecId::REX3, - MegaSpecId::REX4, - MegaSpecId::REX5, - MegaSpecId::REX6, - MegaSpecId::REX7, - ] { - assert_eq!(SpecName::from_mega_spec(spec).to_spec_id(), Ok(spec)); - } - } - - #[test] - fn test_alias_spec_names_match_mega_evm_names() { - // A fixture dumped under an alias spec keys its `post` map by the - // serialized `SpecName`, and `--override.spec` parses the same string - // through `MegaSpecId`'s `FromStr` — the two name surfaces must agree. - for (spec_name, mega_name) in [ - (SpecName::MiniRex1, mega_evm::name::MINI_REX_1), - (SpecName::MiniRex2, mega_evm::name::MINI_REX_2), - ] { - let serialized = serde_json::to_string(&spec_name).expect("serialize"); - assert_eq!(serialized, format!("\"{mega_name}\"")); - } - } - - #[test] - fn test_from_mega_spec_maps_the_latest_spec() { - // `MegaSpecId` is `#[non_exhaustive]`, so `from_mega_spec` needs a wildcard - // arm and a newly introduced spec silently falls through to `Unknown` - // instead of failing to compile. `MegaSpecId::default()` always tracks the - // latest spec, so pinning it here turns that silent mis-mapping — which - // would key a dumped replay fixture's `post` map by `Unknown` — into a test - // failure. - let latest = MegaSpecId::default(); - assert_ne!(SpecName::from_mega_spec(latest), SpecName::Unknown); - assert_eq!(SpecName::from_mega_spec(latest).to_spec_id(), Ok(latest)); - } -} diff --git a/crates/mega-state-test/src/types/test.rs b/crates/mega-state-test/src/types/test.rs deleted file mode 100644 index ec1e7eb70..000000000 --- a/crates/mega-state-test/src/types/test.rs +++ /dev/null @@ -1,318 +0,0 @@ -use mega_evm::{ - revm::{ - context::tx::TxEnv, - primitives::{Address, Bytes, HashMap, TxKind, B256}, - }, - Either, -}; -use serde::{Deserialize, Serialize}; - -use super::{error::TestError, transaction::TxPartIndices, AccountInfo, TestUnit}; -use crate::utils::recover_address; - -/// State test indexed state result deserialization. -#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Test { - /// Expected exception for this test case, if any. - /// - /// This field contains an optional string describing an expected error or exception - /// that should occur during the execution of this state test. If present, the test - /// is expected to fail with this specific error message or exception type. - #[serde(skip_serializing_if = "Option::is_none")] - pub expect_exception: Option, - - /// Indexes - pub indexes: TxPartIndices, - /// Post state hash - pub hash: B256, - /// Post state - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - pub post_state: HashMap, - - /// Logs root - pub logs: B256, - - /// Output state. - /// - /// Note: Not used. - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - state: HashMap, - - /// Tx bytes - #[serde(skip_serializing_if = "Option::is_none")] - pub txbytes: Option, - - /// `MegaETH`: expected total gas used by the transaction. - /// - /// When present, the runner checks the actual gas used against this value - /// and reports a readable diff on mismatch (in addition to the state-root - /// backstop). Absent for pure-Ethereum tests. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mega_gas_used: Option, - - /// `MegaETH`: expected execution status — one of `"success"`, `"revert"`, - /// or `"halt"`. When present, the runner checks the actual status against - /// this value. Absent for pure-Ethereum tests. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mega_status: Option, -} - -impl Test { - /// Construct a `post` expectation for a dumped replay fixture. - /// - /// Records the canonical state/logs roots plus the explicit `MegaETH` gas and - /// status expectations, at transaction index 0. `expect_exception`, - /// `post_state`, `state`, and `txbytes` are left empty/`None` — they are not - /// part of a replay-derived fixture. - pub fn for_dump(hash: B256, logs: B256, mega_gas_used: u64, mega_status: String) -> Self { - Self { - expect_exception: None, - indexes: TxPartIndices { data: 0, gas: 0, value: 0 }, - hash, - post_state: HashMap::default(), - logs, - state: HashMap::default(), - txbytes: None, - mega_gas_used: Some(mega_gas_used), - mega_status: Some(mega_status), - } - } - - /// Create a transaction environment from this test and the test unit. - /// - /// This function sets up the transaction environment using the test's - /// indices to select the appropriate transaction parameters from the - /// test unit. - /// - /// # Arguments - /// - /// * `unit` - The test unit containing transaction parts - /// - /// # Returns - /// - /// A configured [`TxEnv`] ready for execution, or an error if setup fails - /// - /// # Errors - /// - /// Returns an error if: - /// - The private key cannot be used to recover the sender address - /// - The transaction type is invalid and no exception is expected - /// - A transaction field value does not fit its EVM integer width - pub fn tx_env(&self, unit: &TestUnit) -> Result { - tx_env_at(unit, self.indexes).map_err(|e| match e { - // Preserve the existing expect-exception messaging for state tests that - // intentionally encode an invalid transaction type. - TestError::InvalidTransactionType if self.expect_exception.is_some() => { - TestError::UnexpectedException { - expected_exception: self.expect_exception.clone(), - got_exception: Some("Invalid transaction type".to_string()), - } - } - other => other, - }) - } -} - -/// Build a [`TxEnv`] from a unit's transaction at the given part indices. -/// -/// Shared by [`Test::tx_env`] (which selects indices per post-state entry) and by -/// single-unit dump/replay execution (which always uses index 0). Returns -/// [`TestError::InvalidTransactionType`] when the transaction type cannot be -/// derived; callers that expect an exception remap it. -pub fn tx_env_at(unit: &TestUnit, indexes: TxPartIndices) -> Result { - // Setup sender - let caller = if let Some(address) = unit.transaction.sender { - address - } else { - recover_address(unit.transaction.secret_key.as_slice()) - .ok_or(TestError::UnknownPrivateKey(unit.transaction.secret_key))? - }; - - // Transaction specific fields - let tx_type = - unit.transaction.tx_type(indexes.data).ok_or(TestError::InvalidTransactionType)?; - - let tx = TxEnv { - caller, - gas_price: unit - .transaction - .gas_price - .or(unit.transaction.max_fee_per_gas) - .unwrap_or_default() - .try_into() - .unwrap_or(u128::MAX), - gas_priority_fee: unit - .transaction - .max_priority_fee_per_gas - .map(|b| { - u128::try_from(b).map_err(|_| TestError::ValueOutOfRange { - field: "maxPriorityFeePerGas", - value: b, - }) - }) - .transpose()?, - blob_hashes: unit.transaction.blob_versioned_hashes.clone(), - max_fee_per_blob_gas: unit - .transaction - .max_fee_per_blob_gas - .map(|b| { - u128::try_from(b) - .map_err(|_| TestError::ValueOutOfRange { field: "maxFeePerBlobGas", value: b }) - }) - .transpose()? - .unwrap_or(u128::MAX), - tx_type: tx_type as u8, - gas_limit: unit - .transaction - .gas_limit - .get(indexes.gas) - .ok_or(TestError::PartIndexOutOfBounds { - part: "gasLimit", - index: indexes.gas, - len: unit.transaction.gas_limit.len(), - })? - .saturating_to(), - data: unit - .transaction - .data - .get(indexes.data) - .ok_or(TestError::PartIndexOutOfBounds { - part: "data", - index: indexes.data, - len: unit.transaction.data.len(), - })? - .clone(), - nonce: u64::try_from(unit.transaction.nonce).map_err(|_| TestError::ValueOutOfRange { - field: "nonce", - value: unit.transaction.nonce, - })?, - value: *unit.transaction.value.get(indexes.value).ok_or( - TestError::PartIndexOutOfBounds { - part: "value", - index: indexes.value, - len: unit.transaction.value.len(), - }, - )?, - access_list: unit - .transaction - .access_lists - .get(indexes.data) - .cloned() - .flatten() - .unwrap_or_default(), - authorization_list: unit - .transaction - .authorization_list - .clone() - .map(|auth_list| { - auth_list.into_iter().map(|i| Either::Left(i.into())).collect::>() - }) - .unwrap_or_default(), - kind: match unit.transaction.to { - Some(add) => TxKind::Call(add), - None => TxKind::Create, - }, - ..TxEnv::default() - }; - - Ok(tx) -} - -#[cfg(test)] -mod tests { - use super::*; - use mega_evm::revm::primitives::U256; - - /// Minimal valid unit: explicit sender (no key recovery), legacy transfer. - fn unit_json() -> serde_json::Value { - serde_json::json!({ - "env": { - "currentCoinbase": "0x3000000000000000000000000000000000000003", - "currentDifficulty": "0x0", - "currentGasLimit": "0x1c9c380", - "currentNumber": "0x10", - "currentTimestamp": "0x3e8" - }, - "pre": {}, - "post": {}, - "transaction": { - "type": 0, - "data": ["0x"], - "gasLimit": ["0x30d40"], - "gasPrice": "0x0", - "nonce": "0x0", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x1000000000000000000000000000000000000001", - "to": "0x2000000000000000000000000000000000000002", - "value": ["0x0"] - } - }) - } - - fn unit_with(patch: impl FnOnce(&mut serde_json::Value)) -> TestUnit { - let mut json = unit_json(); - patch(&mut json["transaction"]); - serde_json::from_value(json).expect("parse unit") - } - - const ZERO_INDEXES: TxPartIndices = TxPartIndices { data: 0, gas: 0, value: 0 }; - - fn assert_out_of_range(unit: &TestUnit, field: &'static str) { - match tx_env_at(unit, ZERO_INDEXES) { - Err(TestError::ValueOutOfRange { field: got, .. }) => assert_eq!(got, field), - other => panic!("expected ValueOutOfRange for `{field}`, got {other:?}"), - } - } - - #[test] - fn tx_env_at_in_range_values_succeed() { - // Largest representable values must still build (full predicate domain). - let unit = unit_with(|tx| { - tx["nonce"] = serde_json::json!(format!("{:#x}", u64::MAX)); - tx["maxPriorityFeePerGas"] = serde_json::json!(format!("{:#x}", u128::MAX)); - tx["maxFeePerGas"] = serde_json::json!(format!("{:#x}", u128::MAX)); - }); - let tx = tx_env_at(&unit, ZERO_INDEXES).expect("in-range values must build"); - assert_eq!(tx.nonce, u64::MAX); - assert_eq!(tx.gas_priority_fee, Some(u128::MAX)); - } - - #[test] - fn tx_env_at_nonce_overflow_is_structured_error() { - let unit = - unit_with(|tx| tx["nonce"] = serde_json::json!(format!("{:#x}", u64::MAX as u128 + 1))); - assert_out_of_range(&unit, "nonce"); - } - - #[test] - fn tx_env_at_priority_fee_overflow_is_structured_error() { - let unit = unit_with(|tx| { - tx["maxPriorityFeePerGas"] = serde_json::json!(format!("{:#x}", U256::MAX)); - }); - assert_out_of_range(&unit, "maxPriorityFeePerGas"); - } - - #[test] - fn tx_env_at_blob_fee_overflow_is_structured_error() { - let unit = unit_with(|tx| { - // EIP-4844 shape needs an explicit type + destination (already set). - tx["type"] = serde_json::json!(3); - tx["maxFeePerBlobGas"] = serde_json::json!(format!("{:#x}", U256::MAX)); - }); - assert_out_of_range(&unit, "maxFeePerBlobGas"); - } - - #[test] - fn tx_env_at_gas_price_and_gas_limit_keep_saturating() { - // Intentionally-preserved EEST behavior: gasPrice and gasLimit saturate - // instead of erroring, so upstream corpus runs are unaffected. - let unit = unit_with(|tx| { - tx["gasPrice"] = serde_json::json!(format!("{:#x}", U256::MAX)); - tx["gasLimit"] = serde_json::json!([format!("{:#x}", U256::MAX)]); - }); - let tx = tx_env_at(&unit, ZERO_INDEXES).expect("saturating fields must not error"); - assert_eq!(tx.gas_price, u128::MAX); - assert_eq!(tx.gas_limit, u64::MAX); - } -} diff --git a/crates/mega-state-test/src/types/test_authorization.rs b/crates/mega-state-test/src/types/test_authorization.rs deleted file mode 100644 index 205dc82a4..000000000 --- a/crates/mega-state-test/src/types/test_authorization.rs +++ /dev/null @@ -1,75 +0,0 @@ -use mega_evm::revm::context_interface::transaction::SignedAuthorization; -use serde::{de::Error, Deserialize, Deserializer, Serialize}; - -/// Struct for test authorization -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TestAuthorization { - #[serde(flatten)] - inner: SignedAuthorization, -} - -impl From for SignedAuthorization { - fn from(auth: TestAuthorization) -> Self { - auth.inner - } -} - -impl<'de> Deserialize<'de> for TestAuthorization { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - // This is a hack to remove duplicate yParity and v fields which can be used by the test - // files for cross client compat - let mut value: serde_json::Value = Deserialize::deserialize(deserializer)?; - if let Some(val) = value.as_object_mut() { - if val.contains_key("v") && val.contains_key("yParity") { - val.remove("v"); - } - } - let inner: SignedAuthorization = serde_json::from_value(value).map_err(D::Error::custom)?; - Ok(Self { inner }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn recover_auth() { - // Test named: - // tests/prague/eip7702_set_code_tx/test_gas. - // py::test_account_warming[fork_Prague-state_test-single_valid_authorization_single_signer-check_delegated_account_first_True] - - let auth = r#"{ - "chainId": "0x00", - "address": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", - "nonce": "0x00", - "v": "0x01", - "r": "0x5a8cac98fd240d8ef83c22db4a061ffa0facb1801245283cc05fc809d8b92837", - "s": "0x1c3162fe11d91bc24d4fa00fb19ca34531e0eacdf8142c804be44058d5b8244f", - "signer": "0x6389e7f33ce3b1e94e4325ef02829cd12297ef71" - }"#; - - let auth: TestAuthorization = serde_json::from_str(auth).unwrap(); - println!("{auth:?}"); - } - - #[test] - fn recover_auth_duplicate_v_yparity() { - let auth = r#"{ - "chainId": "0x00", - "address": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", - "nonce": "0x00", - "v": "0x01", - "yParity": "0x01", - "r": "0x5a8cac98fd240d8ef83c22db4a061ffa0facb1801245283cc05fc809d8b92837", - "s": "0x1c3162fe11d91bc24d4fa00fb19ca34531e0eacdf8142c804be44058d5b8244f", - "signer": "0x6389e7f33ce3b1e94e4325ef02829cd12297ef71" - }"#; - - let _: TestAuthorization = serde_json::from_str(auth).unwrap(); - } -} diff --git a/crates/mega-state-test/src/types/test_suite.rs b/crates/mega-state-test/src/types/test_suite.rs deleted file mode 100644 index e5c774f41..000000000 --- a/crates/mega-state-test/src/types/test_suite.rs +++ /dev/null @@ -1,8 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; - -use super::TestUnit; - -/// The top level test suite struct -#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct TestSuite(pub BTreeMap); diff --git a/crates/mega-state-test/src/types/test_unit.rs b/crates/mega-state-test/src/types/test_unit.rs deleted file mode 100644 index 02b7ee0bd..000000000 --- a/crates/mega-state-test/src/types/test_unit.rs +++ /dev/null @@ -1,163 +0,0 @@ -use mega_evm::{revm::primitives::eip4844, MegaSpecId}; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; - -use super::{AccountInfo, Env, MegaEnv, SpecName, Test, TransactionParts}; -use mega_evm::revm::{ - context::{block::BlockEnv, cfg::CfgEnv}, - context_interface::block::calc_excess_blob_gas, - database::CacheState, - primitives::{ - eip4844::TARGET_BLOB_GAS_PER_BLOCK_CANCUN, hardfork::SpecId, keccak256, Address, Bytes, - B256, - }, - state::Bytecode, -}; - -/// Single test unit struct -#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] -//#[serde(deny_unknown_fields)] -// field config -pub struct TestUnit { - /// Test info is optional. - #[serde(default, rename = "_info")] - pub info: Option, - - /// Test environment configuration. - /// - /// Contains the environmental information for executing the test, including - /// block information, coinbase address, difficulty, gas limit, and other - /// blockchain state parameters required for proper test execution. - pub env: Env, - - /// Pre-execution state. - /// - /// A mapping of addresses to their account information before the transaction - /// is executed. This represents the initial state of all accounts involved - /// in the test, including their balances, nonces, code, and storage. Ordered - /// by address so serialized fixtures are byte-reproducible. - pub pre: BTreeMap, - - /// Post-execution expectations per specification. - /// - /// Maps each Ethereum specification name (hardfork) to a vector of expected - /// test results. This allows a single test to define different expected outcomes - /// for different protocol versions, enabling comprehensive testing across - /// multiple Ethereum upgrades. - pub post: BTreeMap>, - - /// Transaction details to be executed. - /// - /// Contains the transaction parameters that will be executed against the - /// pre-state. This includes sender, recipient, value, data, gas limits, - /// and other transaction fields that may vary based on indices. - pub transaction: TransactionParts, - - /// Expected output data from the transaction execution. - /// - /// Optional field containing the expected return data from the transaction. - /// This is typically used for testing contract calls that return specific - /// values or for CREATE operations that return deployed contract addresses. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub out: Option, - - /// `MegaETH` external-environment inputs (SALT bucket capacities, oracle - /// storage) required to deterministically reproduce a `MegaETH` transaction. - /// - /// Absent for pure-Ethereum tests, which run against the empty external - /// environment. - #[serde(default, rename = "megaEnv", skip_serializing_if = "Option::is_none")] - pub mega_env: Option, - - /// Fields outside the schema (e.g. the EEST `config` block or custom - /// metadata), captured verbatim so a deserialize→serialize round-trip — - /// notably a `--fill` rewrite — preserves them instead of silently - /// deleting them. Execution ignores these fields. - #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] - pub extra: BTreeMap, -} - -impl TestUnit { - /// Prepare the state from the test unit. - /// - /// This function uses [`TestUnit::pre`] to prepare the pre-state from the test unit. - /// It creates a new cache state and inserts the accounts from the test unit. - /// - /// # Returns - /// - /// A [`CacheState`] object containing the pre-state accounts and storages. - pub fn state(&self) -> CacheState { - let mut cache_state = CacheState::new(false); - 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 acc_info = mega_evm::revm::state::AccountInfo { - balance: info.balance, - code_hash, - code: Some(bytecode), - nonce: info.nonce, - }; - cache_state.insert_account_with_storage( - *address, - acc_info, - info.storage.iter().map(|(k, v)| (*k, *v)).collect(), - ); - } - cache_state - } - - /// Create a block environment from the test unit. - /// - /// This function sets up the block environment using the current test unit's - /// environment settings and the provided configuration. - /// - /// # Arguments - /// - /// * `cfg` - The configuration environment containing spec and blob settings - /// - /// # Returns - /// - /// A configured [`BlockEnv`] ready for execution - pub fn block_env(&self, cfg: &CfgEnv) -> BlockEnv { - let mut block = BlockEnv { - 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), - difficulty: self.env.current_difficulty, - prevrandao: self.env.current_random.map(|i| i.into()), - ..BlockEnv::default() - }; - - // Handle EIP-4844 blob gas - if let Some(current_excess_blob_gas) = self.env.current_excess_blob_gas { - block.set_blob_excess_gas_and_price( - current_excess_blob_gas.to(), - eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_CANCUN, - ); - } else if let (Some(parent_blob_gas_used), Some(parent_excess_blob_gas)) = - (self.env.parent_blob_gas_used, self.env.parent_excess_blob_gas) - { - block.set_blob_excess_gas_and_price( - calc_excess_blob_gas( - parent_blob_gas_used.to(), - parent_excess_blob_gas.to(), - self.env - .parent_target_blobs_per_block - .map(|i| i.to()) - .unwrap_or(TARGET_BLOB_GAS_PER_BLOCK_CANCUN), - ), - eip4844::BLOB_BASE_FEE_UPDATE_FRACTION_CANCUN, - ); - } - - // Set default prevrandao for merge - if cfg.spec.into_eth_spec().is_enabled_in(SpecId::MERGE) && block.prevrandao.is_none() { - block.prevrandao = Some(B256::default()); - } - - block - } -} diff --git a/crates/mega-state-test/src/types/transaction.rs b/crates/mega-state-test/src/types/transaction.rs deleted file mode 100644 index 238669ff0..000000000 --- a/crates/mega-state-test/src/types/transaction.rs +++ /dev/null @@ -1,164 +0,0 @@ -use super::{ - deserializer::{deserialize_maybe_empty, serialize_maybe_empty}, - TestAuthorization, -}; -use mega_evm::revm::{ - context::TransactionType, - context_interface::transaction::AccessList, - primitives::{Address, Bytes, B256, U256}, -}; -use serde::{Deserialize, Serialize}; - -/// Transaction parts. -#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TransactionParts { - /// Transaction type (0=Legacy, 1=EIP-2930, 2=EIP-1559, 3=EIP-4844, 4=EIP-7702) - #[serde(rename = "type")] - pub tx_type: Option, - /// Transaction data/input (multiple variants for different test cases) - pub data: Vec, - /// Gas limit values (multiple variants for different test cases) - pub gas_limit: Vec, - /// Gas price (for legacy and EIP-2930 transactions) - pub gas_price: Option, - /// Transaction nonce - pub nonce: U256, - /// Private key for signing the transaction - pub secret_key: B256, - /// if sender is not present we need to derive it from secret key. - #[serde(default)] - pub sender: Option
, - /// Recipient address (None for contract creation) - #[serde( - default, - deserialize_with = "deserialize_maybe_empty", - serialize_with = "serialize_maybe_empty" - )] - pub to: Option
, - /// Ether value to transfer (multiple variants for different test cases) - pub value: Vec, - /// Maximum fee per gas (EIP-1559 transactions) - pub max_fee_per_gas: Option, - /// Maximum priority fee per gas (EIP-1559 transactions) - pub max_priority_fee_per_gas: Option, - /// Initcodes for contract creation (EIP-7873) - pub initcodes: Option>, - /// Access lists for different test cases (EIP-2930) - #[serde(default)] - pub access_lists: Vec>, - /// Authorization list (EIP-7702) - pub authorization_list: Option>, - /// Blob versioned hashes (EIP-4844) - #[serde(default)] - pub blob_versioned_hashes: Vec, - /// Maximum fee per blob gas (EIP-4844) - pub max_fee_per_blob_gas: Option, -} - -impl TransactionParts { - /// Returns the transaction type. - /// - /// As this information is derived from the fields it is not stored in the struct. - /// - /// Returns `None` if the transaction is invalid: - /// * It has both blob gas and no destination. - /// * It has authorization list and no destination. - pub fn tx_type(&self, access_list_index: usize) -> Option { - if let Some(tx_type) = self.tx_type { - return Some(TransactionType::from(tx_type)); - } - - let mut tx_type = TransactionType::Legacy; - - // If it has access list it is EIP-2930 tx - if let Some(access_list) = self.access_lists.get(access_list_index) { - if access_list.is_some() { - tx_type = TransactionType::Eip2930; - } - } - - // If there is max_fee it is EIP-1559 tx - if self.max_fee_per_gas.is_some() { - tx_type = TransactionType::Eip1559; - } - - // If it has max_fee_per_blob_gas it is EIP-4844 tx - if self.max_fee_per_blob_gas.is_some() { - // target need to be present for EIP-4844 tx - self.to?; - return Some(TransactionType::Eip4844); - } - - // And if it has authorization list it is EIP-7702 tx - if self.authorization_list.is_some() { - // Target need to be present for EIP-7702 tx - self.to?; - return Some(TransactionType::Eip7702); - } - - Some(tx_type) - } -} - -/// Transaction part indices. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct TxPartIndices { - /// Index into the data array - pub data: usize, - /// Index into the `gas_limit` array - pub gas: usize, - /// Index into the value array - pub value: usize, -} - -#[cfg(test)] -mod test { - - use super::*; - - #[test] - fn decode_tx_parts() { - let tx = r#"{ - "nonce": "0x00", - "maxPriorityFeePerGas": "0x00", - "maxFeePerGas": "0x07", - "gasLimit": [ - "0x0423ff" - ], - "to": "0x0000000000000000000000000000000000001000", - "value": [ - "0x00" - ], - "data": [ - "0x" - ], - "accessLists": [ - [ - { - "address": "0x6389e7f33ce3b1e94e4325ef02829cd12297ef71", - "storageKeys": [ - "0x0000000000000000000000000000000000000000000000000000000000000000" - ] - } - ] - ], - "authorizationList": [ - { - "chainId": "0x00", - "address": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", - "nonce": "0x00", - "v": "0x01", - "r": "0x5a8cac98fd240d8ef83c22db4a061ffa0facb1801245283cc05fc809d8b92837", - "s": "0x1c3162fe11d91bc24d4fa00fb19ca34531e0eacdf8142c804be44058d5b8244f", - "signer": "0x6389e7f33ce3b1e94e4325ef02829cd12297ef71" - } - ], - "sender": "0x8a0a19589531694250d570040a0c4b74576919b8", - "secretKey": "0x9e7645d0cfd9c3a04eb7a9db59a4eb7d359f2e75c9164a9d6b9a7d54e1b6a36f" - }"#; - - let _: TransactionParts = serde_json::from_str(tx).unwrap(); - } -} diff --git a/crates/mega-state-test/src/utils.rs b/crates/mega-state-test/src/utils.rs deleted file mode 100644 index 1354f31ad..000000000 --- a/crates/mega-state-test/src/utils.rs +++ /dev/null @@ -1,122 +0,0 @@ -#![allow(missing_docs)] - -use alloy_rlp::{RlpEncodable, RlpMaxEncodedLen}; -use hash_db::Hasher; -use k256::ecdsa::SigningKey; -use mega_evm::{ - revm::{ - context::result::{EVMError, ExecutionResult}, - database::{EmptyDB, PlainAccount, State}, - primitives::{keccak256, Address, Log, B256, U256}, - }, - MegaHaltReason, MegaTransactionError, -}; -use plain_hasher::PlainHasher; -use std::convert::Infallible; -use triehash::sec_trie_root; - -#[derive(Debug)] -pub struct TestValidationResult { - pub logs_root: B256, - pub state_root: B256, -} - -pub fn compute_test_roots( - exec_result: &Result< - ExecutionResult, - EVMError, - >, - db: &State, -) -> TestValidationResult { - TestValidationResult { - logs_root: log_rlp_hash(exec_result.as_ref().map(|r| r.logs()).unwrap_or_default()), - state_root: state_merkle_trie_root(db.cache.trie_account()), - } -} - -pub fn log_rlp_hash(logs: &[Log]) -> B256 { - let mut out = Vec::with_capacity(alloy_rlp::list_length(logs)); - alloy_rlp::encode_list(logs, &mut out); - keccak256(&out) -} - -pub fn state_merkle_trie_root<'a>( - accounts: impl IntoIterator, -) -> B256 { - trie_root( - accounts - .into_iter() - .map(|(address, acc)| (address, alloy_rlp::encode_fixed_size(&TrieAccount::new(acc)))), - ) -} - -#[derive(RlpEncodable, RlpMaxEncodedLen)] -struct TrieAccount { - nonce: u64, - balance: U256, - root_hash: B256, - code_hash: B256, -} - -impl TrieAccount { - fn new(acc: &PlainAccount) -> Self { - Self { - nonce: acc.info.nonce, - balance: acc.info.balance, - root_hash: sec_trie_root::( - acc.storage - .iter() - .filter(|(_k, &v)| !v.is_zero()) - .map(|(k, v)| (k.to_be_bytes::<32>(), alloy_rlp::encode_fixed_size(v))), - ), - code_hash: acc.info.code_hash, - } - } -} - -#[inline] -pub fn trie_root(input: I) -> B256 -where - I: IntoIterator, - A: AsRef<[u8]>, - B: AsRef<[u8]>, -{ - sec_trie_root::(input) -} - -#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)] -pub struct KeccakHasher; - -impl Hasher for KeccakHasher { - type Out = B256; - type StdHasher = PlainHasher; - const LENGTH: usize = 32; - - #[inline] - fn hash(x: &[u8]) -> Self::Out { - keccak256(x) - } -} - -/// Recover the address from a private key ([`SigningKey`]). -pub fn recover_address(private_key: &[u8]) -> Option
{ - let key = SigningKey::from_slice(private_key).ok()?; - let public_key = key.verifying_key().to_encoded_point(false); - Some(Address::from_raw_public_key(&public_key.as_bytes()[1..])) -} - -#[cfg(test)] -mod tests { - use super::*; - use mega_evm::revm::primitives::{address, hex}; - - #[test] - fn sanity_test() { - assert_eq!( - Some(address!("a94f5374fce5edbc8e2a8697c15331677e6ebf0b")), - recover_address(&hex!( - "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8" - )) - ) - } -} diff --git a/crates/mega-state-test/src/witness.rs b/crates/mega-state-test/src/witness.rs new file mode 100644 index 000000000..96d82bdd8 --- /dev/null +++ b/crates/mega-state-test/src/witness.rs @@ -0,0 +1,251 @@ +//! Replaying a fixture from the witness of its own execution. +//! +//! [`check_replay`] executes an entry once on a database and environments that record every read +//! ([`RecordingDatabase`], [`RecordingEnvFactory`]), then twice more on a strict database and +//! environments that serve exactly a witness and refuse everything else ([`StrictDatabase`], +//! [`StrictEnvFactory`]): once on the record of every database read, once on the witness a node +//! builds from its channels — the accounts and slots the transaction's returned state names, as +//! the pre-state holds them, with the code the pre-state holds for those accounts, the block +//! hashes and buckets the engine exported, and the oracle reads the transaction recorded. Each +//! replay is held to the first run: the result, the state, the gas by ledger, the usage and the +//! stop, the state changes committed, and the buckets and block hashes the engine exported. A +//! replay that reads what its witness does not hold fails on the read; one that computes +//! something else fails on the comparison. +//! +//! The channel witness is what a stateless validator is given for the transaction, so its replay +//! is the check the witness must pass; the database-level replay shows the transaction reads +//! nothing outside its database and environments. An entry the engine rejects is not replayed on +//! the channels: it has no returned state, and is in no block. + +use std::collections::BTreeMap; + +use mega_evm::{ + alloy_evm::Database, + revm::{ + database::{ + states::bundle_state::BundleRetention, BundleState, CacheDB, CacheState, EmptyDB, State, + }, + primitives::B256, + state::{AccountInfo, Bytecode}, + DatabaseCommit, + }, + test_utils::{ + RecordingDatabase, RecordingEnvFactory, SharedWitnessRecord, StrictDatabase, + StrictEnvFactory, WitnessKeys, WitnessRecord, + }, + BucketId, EmptyExternalEnv, ExternalEnvFactory, MegaTransactionOutcome, SaltEnv, +}; + +use crate::{ + runner::{prepare, Ready}, + skips::SkipReason, + types::{Test, TestUnit}, + Fork, Mode, +}; + +/// What one run of an entry produced. +struct Run { + /// The transaction's outcome, or the error it was rejected with. + outcome: Result, + /// The state changes committed. + bundle: BundleState, + /// The state cache after the run: everything loaded and committed. + cache: CacheState, + /// The buckets the engine exported. + bucket_ids: Vec, + /// The block hashes the engine exported. + block_hashes: BTreeMap, +} + +/// The pre-state of `unit` as a database: every account with its code and storage. +fn prestate(unit: &TestUnit) -> CacheDB { + let mut db = CacheDB::new(EmptyDB::default()); + for (address, account) in &unit.pre { + let code = Bytecode::new_raw_checked(account.code.clone()) + .unwrap_or_else(|_| Bytecode::new_legacy(account.code.clone())); + let info = AccountInfo { + balance: account.balance, + nonce: account.nonce, + code_hash: code.hash_slow(), + code: Some(code), + ..Default::default() + }; + db.insert_account_info(*address, info); + for (key, value) in &account.storage { + db.insert_account_storage(*address, *key, *value).expect("an in-memory insert"); + } + } + db +} + +/// Runs the entry on `db` with the environments `factory` makes, in `mode`. +fn run( + mode: Mode, + fork: Fork, + db: DB, + factory: F, + block: mega_evm::revm::context::BlockEnv, + chain_id: u64, + tx: mega_evm::MegaTransaction, +) -> Run +where + DB: Database, + F: ExternalEnvFactory, +{ + let mut state = State::builder().with_database(db).with_bundle_update().build(); + let envs = factory.external_envs(block.number.saturating_to()); + let (outcome, bucket_ids, block_hashes) = { + let mut evm = mode.evm_with_envs(fork, &mut state, block, chain_id, envs); + let outcome = evm.execute_transaction(tx).map_err(|error| error.to_string()); + (outcome, evm.get_accessed_bucket_ids(), evm.get_accessed_block_hashes()) + }; + if let Ok(outcome) = &outcome { + state.commit(outcome.state.clone()); + } + state.merge_transitions(BundleRetention::Reverts); + Run { outcome, bundle: state.take_bundle(), cache: state.cache, bucket_ids, block_hashes } +} + +/// How [`check_replay`] checked an entry that passed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Replayed { + /// The engine executed the entry, and it replayed on both witnesses: the record of every + /// database read and the witness a node builds from its channels. + Both, + /// The engine rejected the entry, and it replayed on the record of every database read + /// alone: a rejected transaction has no returned state to build the channel witness from. + RecordOnly, + /// The entry was not executed, for the reason the reference runner shares. + Skipped(SkipReason), +} + +/// Executes the entry `test` of `unit` on `fork` in `mode`, records what it read, replays it on +/// exactly the record and, when the engine executed it, on the witness a node builds from the +/// transaction's returned state and the engine's exports, and compares each replay to the first +/// run. +/// +/// `Ok` with the witnesses it replayed on when every replay produced the same result, state, +/// ledgers, usage, stop, state changes and exports, having read nothing its witness does not +/// hold, or with the reason the entry is not executed; `Err` with what differed, or what the +/// fixture lacks, otherwise. +pub fn check_replay( + mode: Mode, + fork: Fork, + unit: &TestUnit, + test: &Test, +) -> Result { + let Ready { chain_id, block, tx } = + match prepare(fork, unit, test).map_err(|failure| failure.detail)? { + Ok(ready) => ready, + Err(reason) => return Ok(Replayed::Skipped(reason)), + }; + + let record = SharedWitnessRecord::default(); + let recorded = run( + mode, + fork, + RecordingDatabase::new(prestate(unit), record.clone()), + RecordingEnvFactory::new(EmptyExternalEnv, record.clone()), + block.clone(), + chain_id, + tx.clone(), + ); + let record: WitnessRecord = record.take(); + + // A replay that asks for a key its witness does not hold is refused the read and fails with + // it, so the comparison is what catches a missing key. + let strict = StrictEnvFactory::::replaying(&record); + let replayed = run( + mode, + fork, + StrictDatabase::new(record), + strict.clone(), + block.clone(), + chain_id, + tx.clone(), + ); + + compare(&recorded, &replayed)?; + if !strict.oracle().replayed_exactly() { + return Err("the oracle reads were not replayed in order".into()); + } + + // The channel witness: what a node builds for a transaction it includes, so only for an + // entry the engine executed. + let Ok(outcome) = &recorded.outcome else { + return Ok(Replayed::RecordOnly); + }; + let mut keys = WitnessKeys::default(); + keys.add_state(&outcome.state); + let buckets = recorded + .bucket_ids + .iter() + .map(|id| { + (*id, EmptyExternalEnv.get_bucket_capacity(*id).map_err(|error| error.to_string())) + }) + .collect(); + let witness = WitnessRecord::from_channels( + &mut prestate(unit), + &keys, + recorded.block_hashes.clone(), + buckets, + outcome.oracle_reads.clone(), + ) + .map_err(|error| format!("the pre-state could not be read: {error}"))?; + let strict = StrictEnvFactory::::replaying(&witness); + let channel = + run(mode, fork, StrictDatabase::new(witness), strict.clone(), block, chain_id, tx); + compare(&recorded, &channel).map_err(|why| format!("on the channel witness: {why}"))?; + if !strict.oracle().replayed_exactly() { + return Err("the oracle reads were not replayed in order on the channel witness".into()); + } + Ok(Replayed::Both) +} + +/// What differs between two runs of one entry, if anything. +fn compare(a: &Run, b: &Run) -> Result<(), String> { + match (&a.outcome, &b.outcome) { + (Ok(x), Ok(y)) => { + if x.result != y.result { + return Err(format!("result: {:?} against {:?}", x.result, y.result)); + } + if x.gas != y.gas { + return Err(format!("gas: {:?} against {:?}", x.gas, y.gas)); + } + if x.usage != y.usage { + return Err(format!("usage: {:?} against {:?}", x.usage, y.usage)); + } + if x.limit_exceeded != y.limit_exceeded { + return Err(format!("stop: {:?} against {:?}", x.limit_exceeded, y.limit_exceeded)); + } + if x.state != y.state { + return Err("the transaction's state differs".into()); + } + } + (Err(x), Err(y)) => { + if x != y { + return Err(format!("rejection: {x} against {y}")); + } + } + (x, y) => { + return Err(format!( + "one run executed and the other was rejected: {:?} against {:?}", + x.as_ref().map(|o| &o.result), + y.as_ref().map(|o| &o.result) + )) + } + } + if a.bundle != b.bundle { + return Err("the state changes differ".into()); + } + if a.cache != b.cache { + return Err("the state cache differs".into()); + } + if a.bucket_ids != b.bucket_ids { + return Err(format!("buckets: {:?} against {:?}", a.bucket_ids, b.bucket_ids)); + } + if a.block_hashes != b.block_hashes { + return Err(format!("block hashes: {:?} against {:?}", a.block_hashes, b.block_hashes)); + } + Ok(()) +} diff --git a/crates/mega-state-test/tests/bench_fixture.rs b/crates/mega-state-test/tests/bench_fixture.rs deleted file mode 100644 index 9489a02cd..000000000 --- a/crates/mega-state-test/tests/bench_fixture.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Covers `bench_test_suite` — the offline fixture-benchmark path that lets any -//! self-contained state-test fixture (no RPC) be timed, used by the replay-bench -//! driver's `fixture` cases and by `state-test --bench`. - -use std::path::Path; - -use state_test::runner::bench_test_suite; - -/// Benchmarking a self-contained corpus fixture times its isolated execution and -/// reports the same gas it validates with, using the fixture's own `post` spec. -#[test] -fn test_bench_test_suite_times_a_fixture() { - let path = Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../bench/replay/fixtures/large_defi.json" - )); - - let results = bench_test_suite(path, 3, 1, None).expect("bench should succeed"); - - assert_eq!(results.len(), 1, "one unit in the fixture"); - let r = &results[0]; - assert!(r.success, "the corpus transaction succeeds"); - assert_eq!(r.gas_used, 600_700, "gas matches the recorded fixture gas"); - assert_eq!(r.runs, 3); - assert!(r.mgas_per_sec() > 0.0, "throughput is positive"); - assert!(r.min <= r.median, "min ≤ median"); -} diff --git a/crates/mega-state-test/tests/blockchain.rs b/crates/mega-state-test/tests/blockchain.rs new file mode 100644 index 000000000..65e25d4d3 --- /dev/null +++ b/crates/mega-state-test/tests/blockchain.rs @@ -0,0 +1,668 @@ +//! The blockchain-test runner on chains written here, whose expectations come from revm's own +//! mainnet EVM on Osaka — Ethereum, and not `MegaEvm` — so a chain that passes passes because +//! Satin's block executor agrees with Ethereum on it, and one that fails is judged the way the +//! gate judges it. +//! +//! A chain is filled block by block: the EIP-2935 and EIP-4788 pre-block system calls, then every +//! transaction, on revm's mainnet EVM; the header carries the gas used, logs bloom, receipts root +//! and state root that produced. Each transaction is signed with one fixed signature, which +//! recovers to a different sender for each transaction, and the pre-state funds every sender. + +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + eip7685::EMPTY_REQUESTS_HASH, +}; +use mega_evm::{ + alloy_consensus::{ + proofs::{calculate_receipt_root, calculate_transaction_root}, + transaction::SignerRecoverable, + Block, BlockBody, Header, Receipt, ReceiptEnvelope, Signed, TxEnvelope, TxLegacy, + EMPTY_OMMER_ROOT_HASH, EMPTY_ROOT_HASH, + }, + alloy_primitives::{Bloom, Signature}, + op_revm::constants::BASE_FEE_RECIPIENT, + revm::{ + bytecode::Bytecode, + context::{BlockEnv, CfgEnv, TxEnv}, + database::{CacheState, State}, + handler::{MainBuilder, MainContext}, + primitives::{address, b256, keccak256, Address, Bytes, TxKind, B256, U256}, + state::AccountInfo, + Context, ExecuteCommitEvm, SystemCallCommitEvm, + }, +}; +use serde_json::{json, Value}; +use state_test::{ + blockchain::{ + run, Blocks, Config, Differing, FailureKind, Outcome, Produced, Report, SkipReason, + }, + deviations::{BlockchainEntry, Cause, ChainEnd, Deviation, ListedBlock, DEVIATIONS}, + roots::state_root, + Fork, +}; + +/// The contract the transactions call: `SSTORE(0, 42)`, then `LOG0` of the word 7. +const STORE_AND_LOG: &str = "0x602a5f5560075f5260205fa000"; + +/// A contract that stores the hash of block 1 at slot 0. +const STORE_BLOCKHASH_1: &str = "0x6001405f5500"; + +const CONTRACT: Address = address!("0x00000000000000000000000000000000000c0de0"); +const BLOCKHASH_READER: Address = address!("0x00000000000000000000000000000000000c0de1"); +const COINBASE: Address = address!("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba"); +const BASE_FEE: u64 = 7; +const GAS_LIMIT: u64 = 0x0727_0e00; +const CHAIN_ID: u64 = 1; +/// Prague's and Osaka's blob base fee update fraction. +const BLOB_FRACTION: u64 = 5_007_716; + +/// A transaction to be filled into a block. +#[derive(Clone)] +struct Tx { + nonce: u64, + to: Address, + value: U256, + gas_limit: u64, +} + +impl Tx { + fn call(to: Address) -> Self { + Self { nonce: 0, to, value: U256::ZERO, gas_limit: 100_000 } + } + + /// The transaction, signed with the fixed signature, and the sender it recovers to. + fn signed(&self) -> (TxEnvelope, Address) { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce: self.nonce, + gas_price: 10, + gas_limit: self.gas_limit, + to: TxKind::Call(self.to), + value: self.value, + input: Bytes::new(), + }; + let signature = Signature::new( + U256::from_be_bytes( + b256!("0x23f5c4da0aaeea7f2b85535873ef6c0665d118aa4db9eaa01fdde520abeda0da").0, + ), + U256::from_be_bytes( + b256!("0x42f9035fed519beffb0d2ac54f577ea12c24a4f5857d1fa51c786061ee30387a").0, + ), + false, + ); + let signed = TxEnvelope::Legacy(Signed::new_unhashed(tx, signature)); + let sender = signed.recover_signer().expect("the fixed signature recovers a sender"); + (signed, sender) + } +} + +/// A block to be filled: its transactions, and the exception it is expected to raise, which +/// leaves it unfilled. +struct BlockSpec { + txs: Vec, + expect_exception: Option<&'static str>, +} + +impl BlockSpec { + fn valid(txs: Vec) -> Self { + Self { txs, expect_exception: None } + } + + fn invalid(txs: Vec, exception: &'static str) -> Self { + Self { txs, expect_exception: Some(exception) } + } +} + +fn account(balance: U256, code: &str, nonce: u64) -> Value { + json!({ "balance": balance, "code": code, "nonce": U256::from(nonce), "storage": {} }) +} + +/// The pre-state: the two pre-block system contracts, the two contracts the transactions call, +/// every sender the blocks' transactions recover to, funded, and `extra`. +fn pre_state(blocks: &[BlockSpec], extra: &[(Address, Value)]) -> BTreeMap { + let ether = U256::from(10).pow(U256::from(21)); + let mut pre = BTreeMap::from([ + (HISTORY_STORAGE_ADDRESS, account(U256::ZERO, &HISTORY_STORAGE_CODE.to_string(), 1)), + (BEACON_ROOTS_ADDRESS, account(U256::ZERO, &BEACON_ROOTS_CODE.to_string(), 1)), + (CONTRACT, account(U256::ZERO, STORE_AND_LOG, 1)), + (BLOCKHASH_READER, account(U256::ZERO, STORE_BLOCKHASH_1, 1)), + ]); + for tx in blocks.iter().flat_map(|block| &block.txs) { + pre.insert(tx.signed().1, account(ether, "0x", 0)); + } + pre.extend(extra.iter().cloned()); + pre +} + +/// The state `pre` describes, as revm's runner loads it. +fn cache(pre: &BTreeMap) -> CacheState { + let mut cache = CacheState::new(); + for (address, value) in pre { + let code: Bytes = serde_json::from_value(value["code"].clone()).unwrap(); + let code_hash = keccak256(&code); + if !code.is_empty() { + cache.contracts.insert(code_hash, Bytecode::new_raw(code)); + } + let info = AccountInfo { + balance: serde_json::from_value(value["balance"].clone()).unwrap(), + nonce: serde_json::from_value::(value["nonce"].clone()).unwrap().to(), + code_hash, + code: None, + ..Default::default() + }; + cache.insert_account_with_storage(*address, info, Default::default()); + } + cache +} + +fn header_of(parent: &Header, number: u64) -> Header { + Header { + parent_hash: parent.hash_slow(), + ommers_hash: EMPTY_OMMER_ROOT_HASH, + beneficiary: COINBASE, + number, + gas_limit: GAS_LIMIT, + timestamp: number * 12, + base_fee_per_gas: Some(BASE_FEE), + withdrawals_root: Some(EMPTY_ROOT_HASH), + blob_gas_used: Some(0), + excess_blob_gas: Some(0), + parent_beacon_block_root: Some(B256::repeat_byte(number as u8)), + requests_hash: Some(EMPTY_REQUESTS_HASH), + ..Default::default() + } +} + +fn rlp(header: Header, txs: Vec) -> Bytes { + let block = Block { + header, + body: BlockBody { + transactions: txs, + ommers: vec![], + withdrawals: Some(Default::default()), + }, + }; + alloy_rlp::encode(&block).into() +} + +/// A chain filled from revm's mainnet EVM on Osaka: the test's JSON. +fn chain(blocks: &[BlockSpec]) -> Value { + chain_with(blocks, &[]) +} + +/// [`chain`], with `extra` accounts in its pre-state. +fn chain_with(blocks: &[BlockSpec], extra: &[(Address, Value)]) -> Value { + let pre = pre_state(blocks, extra); + let mut state = State::builder().with_cached_prestate(cache(&pre)).build(); + let genesis = Header { + state_root: state_root(state.cache.trie_account()), + ..header_of(&Header::default(), 0) + }; + let genesis = Header { parent_hash: B256::ZERO, timestamp: 0, ..genesis }; + let mut cfg = CfgEnv::new(); + cfg.set_spec_and_mainnet_gas_params(Fork::Osaka.spec_id()); + cfg.chain_id = CHAIN_ID; + + let mut parent = genesis.clone(); + let mut fixture_blocks = Vec::new(); + for spec in blocks { + let mut header = header_of(&parent, parent.number + 1); + let txs: Vec<_> = spec.txs.iter().map(Tx::signed).collect(); + let envelopes: Vec<_> = txs.iter().map(|(tx, _)| tx.clone()).collect(); + header.transactions_root = calculate_transaction_root(&envelopes); + if let Some(exception) = spec.expect_exception { + fixture_blocks.push(json!({ + "rlp": rlp(header, envelopes), + "expectException": exception, + "rlp_decoded": { "transactions": [], "withdrawals": [] }, + })); + continue; + } + let mut block_env = BlockEnv { + number: U256::from(header.number), + beneficiary: header.beneficiary, + timestamp: U256::from(header.timestamp), + gas_limit: header.gas_limit, + basefee: BASE_FEE, + prevrandao: Some(header.mix_hash), + ..Default::default() + }; + block_env.set_blob_excess_gas_and_price(0, BLOB_FRACTION); + state.block_hashes.insert(parent.number, parent.hash_slow()); + let mut evm = Context::mainnet() + .with_block(block_env) + .with_cfg(cfg.clone()) + .with_db(&mut state) + .build_mainnet(); + evm.system_call_commit(HISTORY_STORAGE_ADDRESS, header.parent_hash.0.into()).unwrap(); + let root = header.parent_beacon_block_root.unwrap(); + evm.system_call_commit(BEACON_ROOTS_ADDRESS, root.0.into()).unwrap(); + let mut receipts = Vec::new(); + let mut cumulative = 0; + for (tx, sender) in &txs { + let TxEnvelope::Legacy(signed) = tx else { unreachable!() }; + let legacy = signed.tx(); + let env = TxEnv::builder() + .tx_type(Some(0)) + .caller(*sender) + .gas_limit(legacy.gas_limit) + .gas_price(legacy.gas_price) + .kind(legacy.to) + .value(legacy.value) + .nonce(legacy.nonce) + .chain_id(legacy.chain_id) + .build() + .unwrap(); + let result = evm.transact_commit(env).expect("Ethereum executes the transaction"); + cumulative += result.tx_gas_used(); + let receipt = Receipt { + status: result.is_success().into(), + cumulative_gas_used: cumulative, + logs: result.into_logs(), + }; + receipts.push(ReceiptEnvelope::Legacy(receipt.with_bloom())); + } + drop(evm); + header.gas_used = cumulative; + header.receipts_root = calculate_receipt_root(&receipts); + let mut bloom = Bloom::ZERO; + for receipt in &receipts { + bloom.accrue_bloom(receipt.logs_bloom()); + } + header.logs_bloom = bloom; + header.state_root = state_root(state.cache.trie_account()); + fixture_blocks.push(json!({ + "rlp": rlp(header.clone(), envelopes), + "transactions": spec.txs.iter().map(|_| json!({ "type": "0x00" })).collect::>(), + "withdrawals": [], + })); + parent = header; + } + + let post: BTreeMap<_, _> = state + .cache + .trie_account() + .into_iter() + .map(|(address, account)| { + let code = state.cache.contracts.get(&account.info.code_hash); + let code = code.map_or_else(Bytes::new, |code| code.original_bytes()); + let storage: BTreeMap<_, _> = + account.storage.iter().filter(|(_, v)| !v.is_zero()).collect(); + let value = json!({ + "balance": account.info.balance, + "code": code, + "nonce": U256::from(account.info.nonce), + "storage": storage, + }); + (address, value) + }) + .collect(); + json!({ + "network": "Osaka", + "genesisRLP": rlp(genesis, vec![]), + "blocks": fixture_blocks, + "pre": pre, + "postState": post, + "lastblockhash": parent.hash_slow(), + "config": { + "network": "Osaka", + "chainid": U256::from(CHAIN_ID), + "blobSchedule": { "Osaka": { "target": "0x06", "max": "0x09", + "baseFeeUpdateFraction": U256::from(BLOB_FRACTION) } }, + }, + }) +} + +/// Writes `tests` as one fixture file at `relative` under `dir`. +fn write(dir: &Path, relative: &str, tests: Value) -> PathBuf { + let path = dir.join(relative); + std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory"); + std::fs::write(&path, serde_json::to_string_pretty(&tests).expect("json")).expect("a file"); + path +} + +fn config(deviations: &'static [Deviation]) -> Config { + Config { threads: 2, json_outcome: false, deviations } +} + +fn run_one(test: Value) -> Report { + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "a.json", json!({ "t": test })); + run(&[path], config(DEVIATIONS)) +} + +fn outcome(report: &Report) -> &Outcome { + assert_eq!(report.results.len(), 1, "{:?}", report.file_failures); + &report.results[0].outcome +} + +fn failure_kind(report: &Report) -> Option { + match outcome(report) { + Outcome::Failed(failure) => Some(failure.kind), + _ => None, + } +} + +/// The block at `index` of `test`, decoded. +fn decoded(test: &Value, index: usize) -> Block { + let rlp: Bytes = serde_json::from_value(test["blocks"][index]["rlp"].clone()).unwrap(); + alloy_rlp::Decodable::decode(&mut rlp.as_ref()).unwrap() +} + +/// Replaces the block at `index` of `test` with one whose header `edit` changed, and the +/// fixture's last block hash with the new header's when the block was the last. +fn edit_header(test: &mut Value, index: usize, edit: impl FnOnce(&mut Header)) { + let mut block = decoded(test, index); + let was_last = json!(block.header.hash_slow()) == test["lastblockhash"]; + edit(&mut block.header); + if was_last { + test["lastblockhash"] = json!(block.header.hash_slow()); + } + test["blocks"][index]["rlp"] = json!(rlp(block.header, block.body.transactions)); +} + +/// What Satin produces for the block at `index` of `test`, which is Ethereum's, as its header +/// says before any edit. +fn produced(test: &Value, index: usize) -> Produced { + let header = decoded(test, index).header; + Produced { + block: index, + gas_used: header.gas_used, + logs_bloom_hash: keccak256(header.logs_bloom), + receipts_root: header.receipts_root, + state_root: header.state_root, + } +} + +/// A registry of one deviation, `listed`, listing the test `t` of `a.json` with `blocks` and +/// `end`. +fn registry(blocks: Vec, end: ChainEnd) -> &'static [Deviation] { + let entry = BlockchainEntry { path: "a.json", name: "t", blocks: blocks.leak(), end }; + Box::leak(Box::new([Deviation { + id: "listed", + rule: "the rule", + reason: "the reason", + fork: Fork::Osaka, + entries: &[], + blockchain_entries: vec![entry].leak(), + }])) +} + +/// Runs `test`, as `t` of `a.json`, against `registry`. +fn run_listed(test: &Value, registry: &'static [Deviation]) -> Report { + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "a.json", json!({ "t": test })); + run(&[path], config(registry)) +} + +/// A chain of two blocks of calls, filled from Ethereum. Neither reads a block hash, so a header +/// edited in one block changes nothing the other produces. +fn two_blocks() -> Value { + chain(&[ + BlockSpec::valid(vec![Tx::call(CONTRACT)]), + BlockSpec::valid(vec![Tx { gas_limit: 100_001, ..Tx::call(CONTRACT) }]), + ]) +} + +/// [`two_blocks`] with block 0's header claiming another state root, so that block 0 differs from +/// its header in its state root alone while Satin's state stays Ethereum's. +fn first_block_differs() -> (Value, ListedBlock) { + let mut test = two_blocks(); + let listed = ListedBlock { produced: produced(&test, 0), cause: Cause::Rule }; + edit_header(&mut test, 0, |h| h.state_root = B256::repeat_byte(1)); + (test, listed) +} + +/// Two blocks of calls filled from Ethereum pass on Satin's block executor: the pre-block system +/// calls, the gas and the receipts of several transactions to a block, the base fee Ethereum burns +/// and Satin routes to its vault, the predeploys the pre-state holds for Satin, and a `BLOCKHASH` +/// of the first block read in the second. +#[test] +fn test_a_chain_filled_from_ethereum_passes() { + let test = chain(&[ + BlockSpec::valid(vec![Tx::call(CONTRACT), Tx { gas_limit: 100_001, ..Tx::call(CONTRACT) }]), + BlockSpec::valid(vec![ + Tx::call(BLOCKHASH_READER), + Tx { value: U256::from(5), ..Tx::call(COINBASE) }, + ]), + ]); + let report = run_one(test); + assert_eq!(outcome(&report), &Outcome::Passed, "{report:?}"); + let summary = report.summary(); + assert_eq!((summary.executed, summary.passed), (1, 1)); + assert_eq!(summary.blocks, Blocks { matched: 2, refused: 0, deviated: 0 }); + assert!(report + .gate(Some(1), Some(&BTreeMap::new()), true) + .iter() + .all(|p| !p.contains("executed"))); +} + +/// A block the fixture expects to be invalid for its nonce is refused for that reason, and the +/// chain stays at the previous block: the fixture's last block and post-state are the first +/// block's. +#[test] +fn test_a_refused_block_leaves_the_chain_at_the_previous_block() { + let test = chain(&[ + BlockSpec::valid(vec![Tx::call(CONTRACT)]), + BlockSpec::invalid( + vec![Tx { nonce: 1, ..Tx::call(CONTRACT) }], + "TransactionException.NONCE_MISMATCH_TOO_HIGH", + ), + ]); + let report = run_one(test); + assert_eq!(outcome(&report), &Outcome::Passed, "{report:?}"); + assert_eq!(report.summary().blocks, Blocks { matched: 1, refused: 1, deviated: 0 }); +} + +/// A refusal for another reason than the one named, and a refusal of a block the fixture expects +/// to be valid, fail. +#[test] +fn test_a_refusal_must_be_the_one_named_and_expected() { + let blocks = [BlockSpec::invalid( + vec![Tx { nonce: 1, ..Tx::call(CONTRACT) }], + "TransactionException.INTRINSIC_GAS_TOO_LOW", + )]; + assert_eq!(failure_kind(&run_one(chain(&blocks))), Some(FailureKind::WrongException)); + + let mut test = chain(&[BlockSpec::invalid( + vec![Tx { nonce: 1, ..Tx::call(CONTRACT) }], + "TransactionException.NONCE_MISMATCH_TOO_HIGH", + )]); + test["blocks"][0].as_object_mut().unwrap().remove("expectException"); + assert_eq!(failure_kind(&run_one(test)), Some(FailureKind::UnexpectedException)); +} + +/// A block the executor accepts fails when the fixture expects it to be refused. +#[test] +fn test_an_accepted_block_that_should_be_refused_fails() { + let mut test = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + test["blocks"][0]["expectException"] = json!("TransactionException.NONCE_MISMATCH_TOO_HIGH"); + let report = run_one(test); + assert_eq!(failure_kind(&report), Some(FailureKind::MissingException)); +} + +/// A change to a block's header. +type HeaderEdit = fn(&mut Header); + +/// Each of the four header fields an accepted block is held to fails the test when the header +/// says otherwise, and the failure carries what Satin produced, the bloom's hash included. +#[test] +fn test_every_header_comparison_can_fail() { + let clean = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + let header = decoded(&clean, 0).header; + let cases: [(FailureKind, HeaderEdit); 4] = [ + (FailureKind::GasUsedMismatch, |h| h.gas_used += 1), + (FailureKind::LogsBloomMismatch, |h| h.logs_bloom = Bloom::ZERO), + (FailureKind::ReceiptsRootMismatch, |h| h.receipts_root = B256::repeat_byte(1)), + (FailureKind::StateRootMismatch, |h| h.state_root = B256::repeat_byte(1)), + ]; + for (kind, edit) in cases { + let mut test = clean.clone(); + edit_header(&mut test, 0, edit); + let report = run_one(test); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{kind:?} passed") }; + assert_eq!(failure.kind, kind); + assert_eq!(failure.block, Some(0)); + let produced = Produced { + block: 0, + gas_used: header.gas_used, + logs_bloom_hash: keccak256(header.logs_bloom), + receipts_root: header.receipts_root, + state_root: header.state_root, + }; + let state_root_only = kind == FailureKind::StateRootMismatch; + assert_eq!(failure.differing, [Differing { produced, state_root_only, listed: false }]); + } +} + +/// The chain must end where the fixture's does, holding its post-state. +#[test] +fn test_the_chain_must_end_at_the_fixture_s_post_state() { + let mut test = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + let mut post: BTreeMap = + serde_json::from_value(test["postState"].clone()).unwrap(); + post.get_mut(&CONTRACT).unwrap()["balance"] = json!("0x01"); + test["postState"] = json!(post); + assert_eq!(failure_kind(&run_one(test)), Some(FailureKind::PostStateMismatch)); + + let mut test = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + test["lastblockhash"] = json!(B256::repeat_byte(9)); + assert_eq!(failure_kind(&run_one(test)), Some(FailureKind::PostStateMismatch)); +} + +/// An account the removal list names is taken out only when the pre-state does not hold it and it +/// holds exactly what Satin puts there: a base-fee vault the fixture holds is Ethereum's to +/// compare, and Satin's credit to it fails the block; a vault a transaction sent value to holds +/// more than the base fees, and stays, and the credit beside the value fails the block. +#[test] +fn test_only_what_satin_added_is_taken_out() { + let blocks = [BlockSpec::valid(vec![Tx::call(CONTRACT)])]; + let vault = [(BASE_FEE_RECIPIENT, account(U256::ZERO, "0x", 1))]; + let report = run_one(chain_with(&blocks, &vault)); + assert_eq!(failure_kind(&report), Some(FailureKind::StateRootMismatch)); + + let blocks = + [BlockSpec::valid(vec![Tx { value: U256::from(1), ..Tx::call(BASE_FEE_RECIPIENT) }])]; + let report = run_one(chain(&blocks)); + assert_eq!(failure_kind(&report), Some(FailureKind::StateRootMismatch)); + + // The predeploys the pre-state holds for Satin are taken out: without them the root is + // Ethereum's. + assert_eq!(outcome(&run_one(chain(&[BlockSpec::valid(vec![])]))), &Outcome::Passed); +} + +/// Tests are skipped by their content before anything runs, and only Osaka's run at all. +#[test] +fn test_skips_and_other_networks() { + let dir = tempfile::tempdir().unwrap(); + let mut withdrawals = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + withdrawals["blocks"][0]["withdrawals"] = json!([{ "index": "0x00" }]); + let mut prague = chain(&[BlockSpec::valid(vec![Tx::call(CONTRACT)])]); + prague["network"] = json!("Prague"); + let path = write(dir.path(), "a.json", json!({ "w": withdrawals, "p": prague })); + let report = run(&[path], config(DEVIATIONS)); + assert_eq!(report.results.len(), 1, "the Prague test is not part of the run"); + assert_eq!(report.results[0].outcome, Outcome::Skipped { reason: SkipReason::Withdrawals }); + let pins = BTreeMap::from([(SkipReason::Withdrawals, 1)]); + assert!(report.gate(Some(0), Some(&pins), false).is_empty()); + let problems = report.gate(None, Some(&BTreeMap::new()), false); + assert_eq!(problems, ["1 tests skipped for withdrawals, 0 pinned"]); +} + +/// A block a deviation lists with exactly the outcome Satin produces passes, and the chain goes on +/// from Satin's own state: the next block is held to its header, and the chain ends on the +/// fixture's state, whose post-state is compared. +#[test] +fn test_a_listed_block_deviates_and_the_chain_goes_on() { + let (test, listed) = first_block_differs(); + let report = run_listed(&test, registry(vec![listed], ChainEnd::FixtureState)); + assert_eq!(outcome(&report), &Outcome::Deviated { deviation: "listed" }, "{report:?}"); + assert_eq!(report.results[0].blocks, Blocks { matched: 1, refused: 0, deviated: 1 }); + let summary = report.summary(); + assert_eq!((summary.passed, summary.deviated_total(), summary.unattributed), (0, 1, 0)); + assert_eq!(summary.blocks.checked(), 1, "the listed block is not counted as checked"); + assert!(report.gate(Some(1), None, true).is_empty(), "{:?}", report.gate(Some(1), None, true)); +} + +/// A block after a listed one that differs from its header and is not listed fails the test, and +/// the gate: a listed block exempts nothing after it. +#[test] +fn test_an_unlisted_difference_after_a_listed_block_fails() { + let (mut test, listed) = first_block_differs(); + edit_header(&mut test, 1, |h| h.gas_used += 1); + let report = run_listed(&test, registry(vec![listed], ChainEnd::FixtureState)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::GasUsedMismatch, Some(1))); + let listed_flags: Vec<_> = failure.differing.iter().map(|d| d.listed).collect(); + assert_eq!(listed_flags, [true, false]); + let summary = report.summary(); + assert_eq!((summary.unattributed, summary.unreproduced.get("listed").copied()), (1, Some(1))); + assert!(!report.gate(None, None, false).is_empty()); +} + +/// An outcome that differs from the listed one in the block's aggregated logs bloom alone fails +/// unattributed: the bloom is part of the fingerprint. +#[test] +fn test_a_bloom_only_difference_from_the_listed_outcome_fails() { + let (test, mut listed) = first_block_differs(); + listed.produced.logs_bloom_hash = keccak256(Bloom::repeat_byte(1)); + let report = run_listed(&test, registry(vec![listed], ChainEnd::FixtureState)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::StateRootMismatch, Some(0))); + assert!(failure.detail.contains("its deviation lists another outcome"), "{}", failure.detail); + assert_eq!(report.summary().unattributed, 1); + assert!(!report.gate(None, None, true).is_empty()); +} + +/// A listed test must deviate exactly as listed: a listed block that matches its header, a cause +/// that does not hold, and a chain that ends otherwise than its entry says, each fail it. +#[test] +fn test_a_listed_test_must_deviate_as_listed() { + // A listed block that matches its header. + let test = two_blocks(); + let listed = ListedBlock { produced: produced(&test, 0), cause: Cause::Rule }; + let report = run_listed(&test, registry(vec![listed], ChainEnd::FixtureState)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::NotAsListed, Some(0))); + + // Block 1 differs from its header in its state root alone, the state block 0 left: listed so, + // with the chain ending on that state, the test deviates as listed. + let (mut test, first) = first_block_differs(); + let second = ListedBlock { produced: produced(&test, 1), cause: Cause::StateLeftBy(0) }; + edit_header(&mut test, 1, |h| h.state_root = B256::repeat_byte(2)); + let end = ChainEnd::DeviatedState("the state block 0 left"); + let report = run_listed(&test, registry(vec![first, second], end)); + assert_eq!(outcome(&report), &Outcome::Deviated { deviation: "listed" }, "{report:?}"); + assert_eq!(report.results[0].blocks, Blocks { matched: 0, refused: 0, deviated: 2 }); + + // The same chain, whose entry says it ends on the fixture's state. + let report = run_listed(&test, registry(vec![first, second], ChainEnd::FixtureState)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::NotAsListed, None)); + + // A cause naming a block that is not an earlier listed one does not hold. + let wrong = ListedBlock { cause: Cause::StateLeftBy(1), ..second }; + let report = run_listed(&test, registry(vec![first, wrong], end)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::StateRootMismatch, Some(1))); + + // A block that differs in more than its state root is not one whose state alone was left. + let (mut test, first) = first_block_differs(); + let second = ListedBlock { produced: produced(&test, 1), cause: Cause::StateLeftBy(0) }; + edit_header(&mut test, 1, |h| h.gas_used += 1); + let report = run_listed(&test, registry(vec![first, second], ChainEnd::FixtureState)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::GasUsedMismatch, Some(1))); + + // A chain that ends on the fixture's state, whose entry says it ends on a listed block's. + let (test, first) = first_block_differs(); + let report = run_listed(&test, registry(vec![first], end)); + let Outcome::Failed(failure) = outcome(&report) else { panic!("{report:?}") }; + assert_eq!((failure.kind, failure.block), (FailureKind::NotAsListed, None)); +} diff --git a/crates/mega-state-test/tests/dump_roundtrip.rs b/crates/mega-state-test/tests/dump_roundtrip.rs deleted file mode 100644 index 77dac4816..000000000 --- a/crates/mega-state-test/tests/dump_roundtrip.rs +++ /dev/null @@ -1,175 +0,0 @@ -//! End-to-end self-consistency test for the replay-fixture pipeline. -//! -//! This exercises the same code path `mega-evme replay --dump-fixture` uses to -//! compute a fixture's `post` expectation ([`execute_unit_collect`]) and then -//! verifies that the resulting fixture validates when re-run through the state -//! test runner ([`execute_test_suite`]) — without needing an RPC replay. - -use std::{ - sync::{Arc, Mutex}, - time::Duration, -}; - -use state_test::{ - runner::{execute_test_suite, execute_unit_collect, fill_test_suite}, - types::{SpecName, Test, TestSuite, TestUnit}, -}; - -/// A minimal `MegaETH` unit: a funded sender transfers value to a pre-existing -/// recipient, under a `megaEnv` carrying a non-default SALT bucket capacity. -fn sample_unit_json() -> &'static str { - r#"{ - "env": { - "currentChainID": "0x18c6", - "currentCoinbase": "0x3000000000000000000000000000000000000003", - "currentDifficulty": "0x0", - "currentGasLimit": "0x1c9c380", - "currentNumber": "0x10", - "currentTimestamp": "0x3e8", - "currentBaseFee": "0x0", - "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000000001", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x1000000000000000000000000000000000000001": { - "balance": "0xde0b6b3a7640000", - "code": "0x", - "nonce": "0x0", - "storage": {} - }, - "0x2000000000000000000000000000000000000002": { - "balance": "0x0", - "code": "0x", - "nonce": "0x0", - "storage": {} - } - }, - "transaction": { - "type": 0, - "data": ["0x"], - "gasLimit": ["0x30d40"], - "gasPrice": "0x0", - "nonce": "0x0", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x1000000000000000000000000000000000000001", - "to": "0x2000000000000000000000000000000000000002", - "value": ["0x3e8"] - }, - "post": {}, - "megaEnv": { - "bucketCapacities": [[100, 4096]], - "oracleStorage": [] - } - }"# -} - -/// Build the dumped fixture suite (unit with computed `post`) the way -/// `mega-evme --dump-fixture` does, and write it as JSON. -fn dump_fixture_json() -> (String, state_test::runner::ExecutedUnit) { - let mut unit: TestUnit = serde_json::from_str(sample_unit_json()).expect("parse unit"); - let spec = SpecName::Rex5; - - let executed = execute_unit_collect(&unit, &spec).expect("execute unit"); - - unit.out = executed.output.clone(); - unit.post = std::collections::BTreeMap::from([( - spec, - vec![Test::for_dump( - executed.state_root, - executed.logs_root, - executed.gas_used, - executed.status.clone(), - )], - )]); - - let suite = TestSuite(std::collections::BTreeMap::from([("dump_test".to_string(), unit)])); - (serde_json::to_string_pretty(&suite).expect("serialize"), executed) -} - -#[test] -fn test_dumped_fixture_self_validates() { - let (json, executed) = dump_fixture_json(); - - // Sanity: the value transfer succeeds and consumes a positive amount of gas. - assert!(executed.gas_used > 0); - assert_eq!(executed.status, "success"); - - let dir = std::env::temp_dir().join("mega_evme_dump_roundtrip"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join("self_validate.json"); - std::fs::write(&path, &json).expect("write fixture"); - - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - execute_test_suite(&path, &elapsed, false, false) - .expect("dumped fixture should self-validate when re-run"); -} - -#[test] -fn test_fill_computes_post_for_empty_fixture() { - // The sample unit ships with an empty `post`; fill must compute one that - // then self-validates, leaving no temp file behind. - let suite_json = format!("{{\"fill_test\": {}}}", sample_unit_json()); - let dir = std::env::temp_dir().join("mega_evme_dump_roundtrip"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join("fill_empty.json"); - std::fs::write(&path, &suite_json).expect("write fixture"); - - let n = fill_test_suite(&path, Some(SpecName::Rex5), false).expect("fill"); - assert_eq!(n, 1); - assert!(!path.with_extension("json.tmp").exists(), "temp file must be renamed away"); - - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - execute_test_suite(&path, &elapsed, false, false).expect("filled fixture self-validates"); -} - -#[test] -fn test_fill_refuses_existing_post_without_force() { - let (json, _) = dump_fixture_json(); - let dir = std::env::temp_dir().join("mega_evme_dump_roundtrip"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join("fill_force.json"); - std::fs::write(&path, &json).expect("write fixture"); - - let err = fill_test_suite(&path, Some(SpecName::Rex5), false) - .expect_err("non-empty post must be refused without force"); - assert!(format!("{err}").contains("--force"), "error should point at --force: {err}"); - // The refused file is untouched. - assert_eq!(std::fs::read_to_string(&path).expect("read back"), json); - - let n = fill_test_suite(&path, Some(SpecName::Rex5), true).expect("fill with force"); - assert_eq!(n, 1); - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - execute_test_suite(&path, &elapsed, false, false).expect("refilled fixture self-validates"); -} - -#[test] -fn test_undersized_bucket_capacity_fails_instead_of_panicking() { - // A hand-edited capacity below MIN_BUCKET_SIZE must surface as a fixture - // error, not abort the process via the DynamicGasCost assert. - let bad = sample_unit_json().replace("[[100, 4096]]", "[[100, 1]]"); - assert_ne!(bad, sample_unit_json(), "capacity replacement applied"); - let unit: TestUnit = serde_json::from_str(&bad).expect("parse unit"); - - let err = execute_unit_collect(&unit, &SpecName::Rex5) - .expect_err("undersized capacity must fail execution"); - assert!(format!("{err}").contains("MIN_BUCKET_SIZE"), "unexpected error: {err}"); -} - -#[test] -fn test_tampered_gas_fails_validation() { - let (json, executed) = dump_fixture_json(); - // Corrupt the recorded gas so the explicit gas check must fail. - let from = format!("\"megaGasUsed\": {}", executed.gas_used); - let to = format!("\"megaGasUsed\": {}", executed.gas_used + 42); - let tampered = json.replace(&from, &to); - assert_ne!(tampered, json, "tamper replacement applied"); - - let dir = std::env::temp_dir().join("mega_evme_dump_roundtrip"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join("tampered.json"); - std::fs::write(&path, &tampered).expect("write fixture"); - - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - let result = execute_test_suite(&path, &elapsed, false, false); - assert!(result.is_err(), "tampered gas must fail validation"); -} diff --git a/crates/mega-state-test/tests/hardening.rs b/crates/mega-state-test/tests/hardening.rs deleted file mode 100644 index bf6c2b09b..000000000 --- a/crates/mega-state-test/tests/hardening.rs +++ /dev/null @@ -1,348 +0,0 @@ -//! Audit-driven hardening tests for the published runner API. -//! -//! The runner was extracted from a CLI into a library; these tests pin down -//! that former CLI-era behaviors (panics, process exits, swallowed or masked -//! errors) now surface as structured [`TestError`]s through the public API. - -use std::{ - path::{Path, PathBuf}, - sync::{Arc, Mutex}, - time::Duration, -}; - -use state_test::{ - runner::{ - bench_test_suite, execute_test_suite, execute_unit_collect, fill_test_suite, run, - TestError, TestErrorKind, - }, - types::{SpecName, TestUnit}, -}; - -/// Minimal valid unit JSON: a funded sender sends a legacy transaction to a -/// recipient whose code is `code` (use `"0x"` for a plain transfer). -fn unit_json(code: &str) -> serde_json::Value { - serde_json::json!({ - "env": { - "currentChainID": "0x18c6", - "currentCoinbase": "0x3000000000000000000000000000000000000003", - "currentDifficulty": "0x0", - "currentGasLimit": "0x1c9c380", - "currentNumber": "0x10", - "currentTimestamp": "0x3e8", - "currentBaseFee": "0x0", - "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000000001", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x1000000000000000000000000000000000000001": { - "balance": "0xde0b6b3a7640000", - "code": "0x", - "nonce": "0x0", - "storage": {} - }, - "0x2000000000000000000000000000000000000002": { - "balance": "0x0", - "code": code, - "nonce": "0x0", - "storage": {} - } - }, - "transaction": { - "type": 0, - "data": ["0x"], - "gasLimit": ["0x30d40"], - "gasPrice": "0x0", - "nonce": "0x0", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x1000000000000000000000000000000000000001", - "to": "0x2000000000000000000000000000000000000002", - "value": ["0x0"] - }, - "post": {} - }) -} - -/// A `post` entry with dummy roots; usable when the error under test fires -/// before root validation is ever reached. -fn dummy_post_entry() -> serde_json::Value { - serde_json::json!({ - "indexes": { "data": 0, "gas": 0, "value": 0 }, - "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "logs": "0x0000000000000000000000000000000000000000000000000000000000000000" - }) -} - -/// Write a one-unit suite to a unique temp file and return its path. -fn write_suite(file_name: &str, unit: &serde_json::Value) -> PathBuf { - let suite = serde_json::json!({ "hardening_test": unit }); - let dir = std::env::temp_dir().join("mega_state_test_hardening"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join(file_name); - std::fs::write(&path, serde_json::to_string_pretty(&suite).expect("serialize")) - .expect("write fixture"); - path -} - -fn run_suite(path: &Path) -> Result<(), TestError> { - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - // `print_json_outcome: true` keeps the failure path single-shot (no debug - // re-run with tracing), so error assertions stay quiet and fast. - execute_test_suite(path, &elapsed, false, true) -} - -fn expect_fixture_error(result: Result<(), TestError>, needle: &str) { - let err = result.expect_err("suite must fail"); - match &err.kind { - TestErrorKind::FixtureError(msg) => { - assert!(msg.contains(needle), "error should mention {needle:?}: {msg}") - } - other => panic!("expected FixtureError mentioning {needle:?}, got {other:?}"), - } -} - -// Fix 1: an unreadable suite file is a structured error, not a panic. -#[test] -fn unreadable_suite_file_is_fixture_error() { - let path = - std::env::temp_dir().join("mega_state_test_hardening").join("does_not_exist_4928.json"); - expect_fixture_error(run_suite(&path), "read"); -} - -// Fix 6: a present-but-overflowing currentChainID must not silently run as 6342. -#[test] -fn chain_id_overflow_is_fixture_error() { - let mut unit = unit_json("0x"); - unit["env"]["currentChainID"] = serde_json::json!("0x10000000000000000"); - let path = write_suite("chain_id_overflow.json", &unit); - expect_fixture_error(run_suite(&path), "currentChainID"); -} - -// Fix 2: an unknown spec key in `post` is a clean error, not a panic. -#[test] -fn unknown_post_spec_is_fixture_error() { - let mut unit = unit_json("0x"); - unit["post"] = serde_json::json!({ "FutureFork9000": [dummy_post_entry()] }); - let path = write_suite("unknown_post_spec.json", &unit); - expect_fixture_error(run_suite(&path), "spec"); -} - -// Fix 8 (kept behavior): a transaction invalid *by construction* — here a blob -// tx without a destination, whose type cannot be derived — still satisfies -// `expectException`. -#[test] -fn underivable_tx_type_satisfies_expect_exception() { - let mut unit = unit_json("0x"); - let tx = &mut unit["transaction"]; - tx.as_object_mut().unwrap().remove("type"); - tx["maxFeePerBlobGas"] = serde_json::json!("0x1"); - tx["to"] = serde_json::json!(""); - let mut entry = dummy_post_entry(); - entry["expectException"] = serde_json::json!("TransactionException.TYPE_NOT_SUPPORTED"); - unit["post"] = serde_json::json!({ "Rex5": [entry] }); - - let path = write_suite("expect_exception_invalid_type.json", &unit); - run_suite(&path).expect("invalid-by-construction tx with expectException passes"); -} - -// A structural fixture defect — an out-of-bounds part index — -// must propagate even when the fixture expects an exception. -#[test] -fn out_of_bounds_index_propagates_despite_expect_exception() { - let mut unit = unit_json("0x"); - let mut entry = dummy_post_entry(); - entry["indexes"]["data"] = serde_json::json!(5); - entry["expectException"] = serde_json::json!("TransactionException.INTRINSIC_GAS_TOO_LOW"); - unit["post"] = serde_json::json!({ "Rex5": [entry] }); - - let path = write_suite("expect_exception_oob_index.json", &unit); - expect_fixture_error(run_suite(&path), "out of bounds"); -} - -// Fixes 3 + 8: an out-of-range fixture value (nonce > u64::MAX) is a structured -// error and is never counted as an expected exception. -#[test] -fn nonce_overflow_propagates_despite_expect_exception() { - let mut unit = unit_json("0x"); - unit["transaction"]["nonce"] = serde_json::json!("0x10000000000000000"); - let mut entry = dummy_post_entry(); - entry["expectException"] = serde_json::json!("TransactionException.NONCE_OVERFLOW"); - unit["post"] = serde_json::json!({ "Rex5": [entry] }); - - let path = write_suite("expect_exception_nonce_overflow.json", &unit); - expect_fixture_error(run_suite(&path), "nonce"); -} - -// Fixes 4a + 4b + 8: an unrecoverable secret key propagates as -// `UnknownPrivateKey` (not masked, not an expected-exception pass), and its -// rendered message never contains the key material. -#[test] -fn unrecoverable_secret_key_propagates_and_is_redacted() { - let mut unit = unit_json("0x"); - // No explicit sender → recovery from the (invalid, all-zero) key must fail. - unit["transaction"].as_object_mut().unwrap().remove("sender"); - let mut entry = dummy_post_entry(); - entry["expectException"] = serde_json::json!("TransactionException.SENDER_NOT_EOA"); - unit["post"] = serde_json::json!({ "Rex5": [entry] }); - - let path = write_suite("unknown_key_redacted.json", &unit); - let err = run_suite(&path).expect_err("unknown key must propagate"); - assert!(matches!(err.kind, TestErrorKind::UnknownPrivateKey(_)), "got {:?}", err.kind); - let msg = err.to_string(); - assert!( - !msg.contains("0000000000000000000000000000000000000000000000000000000000000000"), - "rendered error leaks key material: {msg}" - ); - assert!(msg.contains("redacted"), "rendered error should say redacted: {msg}"); -} - -// Fix 4b: without `expectException`, the real underlying cause propagates -// instead of being remapped to `UnknownPrivateKey`. -#[test] -fn structural_error_is_not_masked_as_unknown_key() { - let mut unit = unit_json("0x"); - let mut entry = dummy_post_entry(); - entry["indexes"]["data"] = serde_json::json!(5); - unit["post"] = serde_json::json!({ "Rex5": [entry] }); - - let path = write_suite("unmasked_cause.json", &unit); - let err = run_suite(&path).expect_err("out-of-bounds index must fail"); - assert!( - !matches!(err.kind, TestErrorKind::UnknownPrivateKey(_)), - "cause masked as UnknownPrivateKey: {:?}", - err.kind - ); - match &err.kind { - TestErrorKind::FixtureError(msg) => assert!(msg.contains("out of bounds"), "{msg}"), - other => panic!("expected FixtureError, got {other:?}"), - } -} - -// Fix 5: `run()` returns `TestsFailed` instead of exiting the process when -// tests fail without a thread error (the `keep_going` path). -#[test] -fn run_returns_tests_failed_instead_of_exiting() { - let mut unit = unit_json("0x"); - // Wrong roots: execution succeeds but validation must fail. - unit["post"] = serde_json::json!({ "Rex5": [dummy_post_entry()] }); - let path = write_suite("run_tests_failed.json", &unit); - - let err = run(vec![path], true, false, true, true).expect_err("failing tests must error"); - match err.kind { - TestErrorKind::TestsFailed { failed, total } => { - assert_eq!(failed, 1); - assert_eq!(total, 1); - } - other => panic!("expected TestsFailed, got {other:?}"), - } -} - -#[test] -fn run_returns_ok_when_all_pass() { - // Self-validate via fill, then drive the full `run()` happy path. - let unit = unit_json("0x"); - let path = write_suite("run_all_pass.json", &unit); - fill_test_suite(&path, Some(SpecName::Rex5), false).expect("fill"); - run(vec![path], true, false, false, false).expect("passing suite returns Ok"); -} - -/// Recipient code `PUSH1 0x0f; BLOCKHASH; PUSH1 0x00; SSTORE`: stores the hash -/// of block 15 (current block is 0x10 = 16) into storage slot 0, making the -/// post-state root depend on the BLOCKHASH answer. -const BLOCKHASH_PROBE_CODE: &str = "0x600f40600055"; - -fn blockhash_unit(hashes: Option) -> TestUnit { - let mut unit = unit_json(BLOCKHASH_PROBE_CODE); - if let Some(hashes) = hashes { - unit["env"]["blockHashes"] = hashes; - } - serde_json::from_value(unit).expect("parse unit") -} - -// Recorded blockHashes are injected and actually change the -// BLOCKHASH answer the EVM sees. -#[test] -fn block_hashes_are_injected_into_execution() { - let h1 = serde_json::json!({ - "0xf": "0x1111111111111111111111111111111111111111111111111111111111111111" - }); - let h2 = serde_json::json!({ - "0xf": "0x2222222222222222222222222222222222222222222222222222222222222222" - }); - - let run1 = execute_unit_collect(&blockhash_unit(Some(h1)), &SpecName::Rex5).expect("run h1"); - let run2 = execute_unit_collect(&blockhash_unit(Some(h2)), &SpecName::Rex5).expect("run h2"); - assert_eq!(run1.status, "success"); - assert_eq!(run2.status, "success"); - assert_ne!( - run1.state_root, run2.state_root, - "different recorded block hashes must produce different post-state roots" - ); - - // Absent blockHashes: execution still works on the synthetic default. - let synthetic = execute_unit_collect(&blockhash_unit(None), &SpecName::Rex5) - .expect("run without blockHashes"); - assert_eq!(synthetic.status, "success"); -} - -// Fix 11: a blockHashes key beyond u64 is a fixture error, not a silent drop. -#[test] -fn block_hashes_key_overflow_is_fixture_error() { - let overflow = serde_json::json!({ - "0x10000000000000000": - "0x1111111111111111111111111111111111111111111111111111111111111111" - }); - let err = execute_unit_collect(&blockhash_unit(Some(overflow)), &SpecName::Rex5) - .expect_err("overflowing blockHashes key must fail"); - assert!(err.to_string().contains("blockHashes"), "unexpected error: {err}"); -} - -// Fix 11: the suite validation path injects the same hashes the fill path used, -// so a filled BLOCKHASH-dependent fixture self-validates. -#[test] -fn block_hashes_fixture_round_trips_through_fill_and_validate() { - let mut unit = unit_json(BLOCKHASH_PROBE_CODE); - unit["env"]["blockHashes"] = serde_json::json!({ - "0xf": "0x3333333333333333333333333333333333333333333333333333333333333333" - }); - let path = write_suite("blockhash_roundtrip.json", &unit); - fill_test_suite(&path, Some(SpecName::Rex5), false).expect("fill"); - run_suite(&path).expect("filled BLOCKHASH fixture must self-validate"); -} - -// Fixes 2 + 10 adjacent: bench/fill reject an unknown post spec at selection -// time with an actionable message. -#[test] -fn bench_rejects_unknown_post_spec() { - let mut unit = unit_json("0x"); - unit["post"] = serde_json::json!({ "FutureFork9000": [] }); - let path = write_suite("bench_unknown_spec.json", &unit); - let err = bench_test_suite(&path, 1, 0, None).expect_err("unknown spec must be rejected"); - assert!(err.to_string().contains("unknown spec"), "unexpected error: {err}"); -} - -#[test] -fn fill_rejects_unknown_post_spec() { - let mut unit = unit_json("0x"); - unit["post"] = serde_json::json!({ "FutureFork9000": [] }); - let path = write_suite("fill_unknown_spec.json", &unit); - let err = fill_test_suite(&path, None, false).expect_err("unknown spec must be rejected"); - assert!(err.to_string().contains("unknown spec"), "unexpected error: {err}"); -} - -// A `--fill` rewrite must not delete fields outside the schema (e.g. the EEST -// `config` block): `TestUnit::extra` captures them and round-trips verbatim. -#[test] -fn fill_preserves_unknown_unit_fields() { - let mut unit = unit_json("0x"); - unit["config"] = serde_json::json!({ "network": "Rex5", "custom": [1, 2, 3] }); - let path = write_suite("fill_preserves_extra.json", &unit); - fill_test_suite(&path, Some(SpecName::Rex5), false).expect("fill"); - let rewritten: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&path).expect("read")).expect("json"); - let (_, rewritten_unit) = rewritten.as_object().expect("suite").iter().next().expect("unit"); - assert_eq!( - rewritten_unit["config"], - serde_json::json!({ "network": "Rex5", "custom": [1, 2, 3] }), - "unknown unit fields must survive a fill rewrite" - ); -} diff --git a/crates/mega-state-test/tests/replay_corpus.rs b/crates/mega-state-test/tests/replay_corpus.rs deleted file mode 100644 index 468a83f49..000000000 --- a/crates/mega-state-test/tests/replay_corpus.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! Offline correctness guard over the shared replay corpus (`bench/replay/`). -//! -//! The fixtures under `bench/replay/fixtures/` are a single corpus used two -//! ways: this test validates their recorded post-state (every PR), and the -//! replay-throughput benchmark (`bench/replay/run.py`) times them (on demand). -//! Each is a self-contained EEST state test — most produced by `mega-evme -//! replay --dump-fixture` from a real `MegaETH` transaction (gas and status -//! checked against the on-chain receipt at dump time) — so re-executing them in -//! isolation checks the state root, logs root, gas, and status with no RPC, -//! deterministically in CI. Fixtures without an on-chain origin (e.g. the -//! `attack_deploy` prestate snapshot) have their `post` filled offline with -//! `state-test --fill`, so they are validated here just like the dumped ones. -//! -//! A failure here means a code change altered execution for the covered spec -//! (gas, result, or post-state). To extend coverage, dump more fixtures: -//! -//! ```bash -//! mega-evme replay --rpc \ -//! --dump-fixture bench/replay/fixtures/.json -//! ``` - -use std::{ - sync::{Arc, Mutex}, - time::Duration, -}; - -use state_test::runner::{execute_test_suite, find_all_json_tests}; - -#[test] -fn test_replay_corpus_self_validates() { - let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../bench/replay/fixtures"); - let fixtures = find_all_json_tests(std::path::Path::new(dir)); - - assert!(!fixtures.is_empty(), "replay corpus is empty at {dir}"); - - let elapsed = Arc::new(Mutex::new(Duration::ZERO)); - let mut passed = 0usize; - for path in &fixtures { - execute_test_suite(path, &elapsed, false, false).unwrap_or_else(|e| { - panic!("replay fixture {} failed to validate: {e}", path.display()) - }); - passed += 1; - } - assert_eq!(passed, fixtures.len(), "all corpus fixtures must validate"); -} diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs new file mode 100644 index 000000000..3f71fc110 --- /dev/null +++ b/crates/mega-state-test/tests/runner.rs @@ -0,0 +1,501 @@ +//! The runner on fixtures written here, whose expectations come from revm's own mainnet EVM on the +//! fixture's fork — Ethereum, and not `MegaEvm` — so a fixture that passes passes because Satin's +//! machinery agrees with Ethereum on it, and one that fails is judged the way the gate judges it. + +use std::path::{Path, PathBuf}; + +use mega_evm::revm::{ + context::{result::ExecutionResult, CfgEnv, Context}, + database::State, + handler::{MainBuilder, MainContext}, + primitives::B256, + ExecuteCommitEvm, +}; +use serde_json::{json, Value}; +use state_test::{ + deviations::{Deviation, Entry, DEVIATIONS}, + roots::{logs_hash, state_root}, + runner::{run, Config, FailureKind, Outcome, Report}, + skips::SkipReason, + types::TestSuite, + Fork, Mode, +}; + +const SENDER: &str = "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"; +const SENDER_KEY: &str = "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"; +const CONTRACT: &str = "0x00000000000000000000000000000000000c0de0"; +const COINBASE: &str = "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba"; +const BASE_FEE_VAULT: &str = "0x4200000000000000000000000000000000000019"; + +/// `SSTORE(0, 42)`, then `LOG0` of the word 7. +const STORE_AND_LOG: &str = "0x602a5f5560075f5260205fa000"; + +fn config(mode: Mode, fork: Fork) -> Config { + Config { mode, fork, threads: 2, json_outcome: false, trace: false, deviations: DEVIATIONS } +} + +/// A unit calling `CONTRACT` with `transaction` fields over the defaults, and one entry per fork +/// in `forks` with placeholder roots. +fn unit(forks: &[Fork], transaction: Value) -> Value { + let mut tx = json!({ + "data": ["0x"], + "gasLimit": ["0x186a0"], + "gasPrice": "0x0a", + "nonce": "0x00", + "secretKey": SENDER_KEY, + "sender": SENDER, + "to": CONTRACT, + "value": ["0x01"], + }); + for (key, value) in transaction.as_object().expect("an object") { + tx[key] = value.clone(); + } + let entry = json!([{ + "indexes": { "data": 0, "gas": 0, "value": 0 }, + "hash": B256::ZERO, + "logs": B256::ZERO, + }]); + let post: serde_json::Map<_, _> = + forks.iter().map(|fork| (fork.name().to_string(), entry.clone())).collect(); + json!({ + "env": { + "currentCoinbase": COINBASE, + "currentGasLimit": "0x1000000", + "currentNumber": "0x01", + "currentTimestamp": "0x03e8", + "currentBaseFee": "0x07", + "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000020000", + "currentExcessBlobGas": "0x00", + }, + "pre": { + SENDER: { "balance": "0x3635c9adc5dea00000", "code": "0x", "nonce": "0x00", "storage": {} }, + CONTRACT: { "balance": "0x00", "code": STORE_AND_LOG, "nonce": "0x01", "storage": {} }, + }, + "transaction": tx, + "post": post, + }) +} + +/// Fills every entry of `unit` with what revm's mainnet EVM on the entry's fork produces: the +/// post-state root and the logs hash, which for a rejected transaction are the pre-state's and +/// the empty list's. +fn fill_from_ethereum(mut unit: Value) -> Value { + let parsed: TestSuite = serde_json::from_value(json!({ "t": unit.clone() })).expect("a unit"); + let parsed = &parsed.0["t"]; + for (spec, tests) in &parsed.post { + let fork = Fork::ALL.into_iter().find(|fork| fork.is(spec)).expect("a runner fork"); + for (index, test) in tests.iter().enumerate() { + let mut cfg = CfgEnv::new(); + cfg.set_spec_and_mainnet_gas_params(fork.spec_id()); + cfg.set_max_blobs_per_tx(6); + let block = parsed.block_env(&mut cfg); + let mut state = + State::builder().with_cached_prestate(parsed.state()).with_bundle_update().build(); + let result = match test.tx_env(parsed) { + Ok(tx) => Context::mainnet() + .with_block(block) + .with_cfg(cfg) + .with_db(&mut state) + .build_mainnet() + .transact_commit(tx) + .ok(), + Err(_) => None, + }; + let logs = result.as_ref().map(ExecutionResult::logs).unwrap_or_default(); + let entry = &mut unit["post"][fork.name()][index]; + entry["hash"] = json!(state_root(state.cache.trie_account())); + entry["logs"] = json!(logs_hash(logs)); + } + } + unit +} + +/// Writes `units` as one fixture file at `relative` under `dir`. +fn write(dir: &Path, relative: &str, units: Value) -> PathBuf { + let path = dir.join(relative); + std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory"); + std::fs::write(&path, serde_json::to_string_pretty(&units).expect("json")).expect("a file"); + path +} + +fn outcomes(report: &Report) -> Vec<&Outcome> { + report.results.iter().map(|result| &result.outcome).collect() +} + +fn failure_kind(outcome: &Outcome) -> Option { + match outcome { + Outcome::Failed(failure) => Some(failure.kind), + _ => None, + } +} + +/// A priced call that writes a slot and logs, filled from Ethereum, passes on Satin's machinery +/// in equivalence mode under both forks: the gas, the refund to the sender, the fee to the +/// beneficiary, the base fee Ethereum burns and Satin routes to its vault, the slot and the log. +#[test] +fn test_a_fixture_ethereum_filled_passes_in_equivalence_mode() { + let dir = tempfile::tempdir().unwrap(); + let path = write( + dir.path(), + "a.json", + json!({ "call": fill_from_ethereum(unit(&Fork::ALL, json!({})))}), + ); + for fork in Fork::ALL { + let report = run(std::slice::from_ref(&path), config(Mode::Equivalence, fork)); + assert_eq!(outcomes(&report), [&Outcome::Passed], "{fork}"); + let summary = report.summary(); + assert_eq!((summary.defined, summary.executed, summary.passed), (1, 1, 1)); + assert!(report.gate(Some(1), Some(0), false).is_empty()); + } +} + +/// The same call fails in Satin mode: Satin's own configuration charges history gas and prices +/// state its own way, so a sender with gas enough for both pays more than Ethereum's post-state +/// says; and it emits the EIP-7708 transfer log of the call's value, which Osaka's logs do not +/// carry, so a call that moves value fails on its logs before its state root is compared. +#[test] +fn test_the_same_fixture_fails_in_satin_mode() { + let dir = tempfile::tempdir().unwrap(); + for (value, kind) in + [("0x00", FailureKind::StateRootMismatch), ("0x01", FailureKind::LogsMismatch)] + { + let unit = unit(&[Fork::Osaka], json!({ "gasLimit": ["0x0f4240"], "value": [value] })); + let path = write(dir.path(), "a.json", json!({ "call": fill_from_ethereum(unit) })); + let report = run(std::slice::from_ref(&path), config(Mode::Equivalence, Fork::Osaka)); + assert_eq!(outcomes(&report), [&Outcome::Passed], "value {value}"); + + let report = run(&[path], config(Mode::Satin, Fork::Osaka)); + assert_eq!(failure_kind(outcomes(&report)[0]), Some(kind), "value {value}"); + let summary = report.summary(); + assert_eq!(summary.unattributed, 1, "Satin mode attributes nothing"); + assert!(summary.deviated.is_empty()); + } +} + +/// A post-state root or a logs hash that is not what executes is a failure no deviation explains. +#[test] +fn test_wrong_roots_fail() { + let dir = tempfile::tempdir().unwrap(); + let filled = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let mut wrong_root = filled.clone(); + wrong_root["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let mut wrong_logs = filled; + wrong_logs["post"]["Osaka"][0]["logs"] = json!(B256::repeat_byte(1)); + let path = write(dir.path(), "a.json", json!({ "a_root": wrong_root, "b_logs": wrong_logs })); + + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + let kinds: Vec<_> = outcomes(&report).into_iter().map(failure_kind).collect(); + assert_eq!(kinds, [Some(FailureKind::StateRootMismatch), Some(FailureKind::LogsMismatch)]); + assert_eq!(report.summary().unattributed, 2); + assert_eq!(report.gate(None, None, false), ["2 failed tests no deviation explains"]); +} + +/// An expected exception must be the one raised, and must leave the pre-state; an unexpected one, +/// or a missing one, fails. +#[test] +fn test_exceptions_are_matched_by_name() { + let dir = tempfile::tempdir().unwrap(); + let too_little_gas = json!({ "gasLimit": ["0x5208"], "data": ["0x00"] }); + let named = |exception: &str| { + let mut unit = fill_from_ethereum(unit(&[Fork::Osaka], too_little_gas.clone())); + unit["post"]["Osaka"][0]["expectException"] = json!(exception); + unit + }; + let mut missing = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + missing["post"]["Osaka"][0]["expectException"] = + json!("TransactionException.INTRINSIC_GAS_TOO_LOW"); + let unexpected = fill_from_ethereum(unit(&[Fork::Osaka], too_little_gas.clone())); + let path = write( + dir.path(), + "a.json", + json!({ + "a_named": named("TransactionException.INTRINSIC_GAS_TOO_LOW"), + "b_alternatives": named("TransactionException.NONCE_IS_MAX|TransactionException.INTRINSIC_GAS_TOO_LOW"), + "c_wrong": named("TransactionException.NONCE_MISMATCH_TOO_HIGH"), + "d_missing": missing, + "e_unexpected": unexpected, + }), + ); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + let kinds: Vec<_> = outcomes(&report).into_iter().map(failure_kind).collect(); + assert_eq!( + kinds, + [ + None, + None, + Some(FailureKind::WrongException), + Some(FailureKind::MissingException), + Some(FailureKind::UnexpectedException), + ] + ); +} + +/// An expected output must be produced; a call that returns nothing does not satisfy one. +#[test] +fn test_an_expected_output_must_be_produced() { + let dir = tempfile::tempdir().unwrap(); + let mut unit = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + unit["out"] = json!("0x01"); + let path = write(dir.path(), "a.json", json!({ "call": unit })); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + assert_eq!(failure_kind(outcomes(&report)[0]), Some(FailureKind::OutputMismatch)); +} + +/// Only the run's fork's entries count; every entry of a file on the skip list is skipped and +/// counted as defined; a transaction that cannot be built is skipped when the fixture expects it +/// invalid for the reason it cannot be, a wrong exception when the fixture names another reason, +/// and a fixture failure when it expects none. +#[test] +fn test_what_is_counted_and_what_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let both = fill_from_ethereum(unit(&Fork::ALL, json!({}))); + let collision = + write(dir.path(), "paris/eip7610_create_collision/c.json", json!({ "c": &both })); + let mut unbuildable = unit(&[Fork::Osaka], json!({})); + unbuildable["transaction"].as_object_mut().unwrap().remove("secretKey"); + let mut expected_invalid = unbuildable.clone(); + expected_invalid["post"]["Osaka"][0]["expectException"] = + json!("TransactionException.INVALID_SIGNATURE_VRS"); + let mut other_reason = unbuildable.clone(); + other_reason["post"]["Osaka"][0]["expectException"] = + json!("TransactionException.INTRINSIC_GAS_TOO_LOW"); + let others = write( + dir.path(), + "o.json", + json!({ + "a_both": both, + "b_expected_invalid": expected_invalid, + "c_unbuildable": unbuildable, + "d_other_reason": other_reason, + }), + ); + + let report = run(&[collision, others], config(Mode::Equivalence, Fork::Osaka)); + let outcomes = outcomes(&report); + assert_eq!(outcomes.len(), 5, "one entry per unit for Osaka, none for Amsterdam"); + assert_eq!(outcomes[0], &Outcome::Passed); + assert_eq!( + outcomes[1], + &Outcome::Skipped { reason: SkipReason::UnbuildableInvalidTransaction } + ); + assert_eq!(failure_kind(outcomes[2]), Some(FailureKind::Fixture)); + assert_eq!(failure_kind(outcomes[3]), Some(FailureKind::WrongException)); + assert_eq!(outcomes[4], &Outcome::Skipped { reason: SkipReason::CreateCollisionWithStorage }); + let summary = report.summary(); + assert_eq!((summary.defined, summary.executed, summary.skipped_total()), (5, 3, 2)); + assert_eq!(report.gate(Some(3), Some(2), false), ["2 failed tests no deviation explains"]); + assert_eq!( + report.gate(Some(4), Some(1), false)[1..], + ["3 tests executed, 4 pinned".to_string(), "2 tests skipped, 1 pinned".to_string()] + ); +} + +/// A test name that appears twice in a file fails the file, rather than the second test silently +/// replacing the first. +#[test] +fn test_a_duplicate_test_name_fails_the_file() { + let dir = tempfile::tempdir().unwrap(); + let unit = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let path = dir.path().join("twice.json"); + std::fs::write(&path, format!("{{\"t\": {unit}, \"t\": {unit}}}")).unwrap(); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + assert!(report.results.is_empty()); + assert_eq!(report.file_failures.len(), 1); + assert!( + report.file_failures[0].1.detail.contains("appears twice"), + "{:?}", + report.file_failures + ); +} + +/// A file that cannot be parsed is a failure of the run, not a set of skipped tests. +#[test] +fn test_an_unreadable_file_fails_the_gate() { + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "broken.json", json!({ "t": { "env": {} } })); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + assert!(report.results.is_empty()); + assert_eq!(report.file_failures.len(), 1); + let summary = report.summary(); + assert_eq!((summary.file_failures, summary.defined), (1, 0)); + assert_eq!(report.gate(None, None, false), ["1 fixture files could not be read"]); +} + +/// The base-fee vault Satin credits is taken back only when the fee routing made it: a vault the +/// pre-state already holds stays, and the fee it received is a post-state Ethereum does not have. +#[test] +fn test_the_fee_vault_is_taken_back_only_when_the_routing_made_it() { + let dir = tempfile::tempdir().unwrap(); + let mut unit = unit(&[Fork::Osaka], json!({})); + unit["pre"][BASE_FEE_VAULT] = + json!({ "balance": "0x01", "code": "0x", "nonce": "0x00", "storage": {} }); + let path = write(dir.path(), "a.json", json!({ "call": fill_from_ethereum(unit) })); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + assert_eq!(failure_kind(outcomes(&report)[0]), Some(FailureKind::StateRootMismatch)); +} + +/// A chain id that does not fit a `u64`, and a fixture value the transaction builder cannot take, +/// fail the test they belong to and nothing else. +#[test] +fn test_bad_fixture_values_fail_their_own_test() { + let dir = tempfile::tempdir().unwrap(); + let good = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let mut chain = good.clone(); + chain["env"]["currentChainID"] = json!("0x010000000000000000"); + let fee = unit( + &[Fork::Osaka], + // One more than `u128::MAX`, which the fixture types' transaction builder refuses with a + // panic rather than an error. + json!({ "maxFeePerGas": "0x0a", "maxPriorityFeePerGas": "0x0100000000000000000000000000000000" }), + ); + let path = + write(dir.path(), "a.json", json!({ "a_chain": chain, "b_fee": fee, "c_good": good })); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + let kinds: Vec<_> = outcomes(&report).into_iter().map(failure_kind).collect(); + assert_eq!(kinds, [Some(FailureKind::Fixture), Some(FailureKind::Panic), None]); +} + +/// A registry of one Osaka deviation listing every failure of `report`, in the file at `path` +/// under the run's directory, with the hashes it produced. +fn registry_of(report: &Report, path: &'static str) -> &'static [Deviation] { + let entries: Vec<_> = report + .results + .iter() + .filter_map(|result| match &result.outcome { + Outcome::Failed(failure) => Some(Entry { + path, + name: result.id.name.clone().leak(), + indexes: result.id.indexes, + produced: failure.produced.expect("a hash mismatch"), + }), + _ => None, + }) + .collect(); + Box::leak(Box::new([Deviation { + id: "listed", + rule: "the rule", + reason: "the reason", + fork: Fork::Osaka, + entries: entries.leak(), + blockchain_entries: &[], + }])) +} + +/// A deviation explains exactly the entries it lists, with the hashes they produce, and the gate +/// holds every one of them to its listing. Each edit below fails the gate on its own: a listed +/// failure made to pass, an unlisted entry of the same file broken — the two together keep the +/// count the deviation explains, which is all a count could see — and a listed entry that fails +/// with other hashes, the state root of a logs mismatch included. +#[test] +fn test_a_deviation_holds_the_entries_it_lists() { + let dir = tempfile::tempdir().unwrap(); + let filled = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let root = filled["post"]["Osaka"][0]["hash"].clone(); + let mut wrong_root = filled.clone(); + wrong_root["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let mut wrong_logs = filled.clone(); + wrong_logs["post"]["Osaka"][0]["logs"] = json!(B256::repeat_byte(1)); + let units = json!({ "a_root": wrong_root, "b_logs": wrong_logs, "c_passes": filled }); + + const PATH: &str = "cancun/deviated.json"; + let path = write(dir.path(), PATH, units.clone()); + let equivalence = config(Mode::Equivalence, Fork::Osaka); + let registry = registry_of(&run(std::slice::from_ref(&path), equivalence), PATH); + assert_eq!(registry[0].entries.len(), 2); + let run_with = |units: &Value| { + write(dir.path(), PATH, units.clone()); + run(std::slice::from_ref(&path), Config { deviations: registry, ..equivalence }) + }; + let gate = |units: &Value| run_with(units).gate(None, None, true); + + let report = run_with(&units); + assert_eq!(report.gate(None, None, true), Vec::::new()); + let summary = report.summary(); + assert_eq!(summary.deviated.get("listed"), Some(&2)); + assert_eq!((summary.unattributed, summary.unreproduced.len()), (0, 0)); + + let unreproduced = + "deviation listed: 1 of the 2 entries it lists on Osaka did not fail as listed"; + let explains_one = "deviation listed explains 1 failed tests on Osaka, 2 listed"; + let unattributed = "1 failed tests no deviation explains"; + + // The listed state-root failure made to pass. + let mut passes = units.clone(); + passes["a_root"]["post"]["Osaka"][0]["hash"] = root; + assert_eq!(gate(&passes), [unreproduced, explains_one]); + let report = run_with(&passes); + let seen: Vec<_> = report.unreproduced().collect(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].entry.name, "a_root"); + assert!(matches!(seen[0].seen.as_slice(), [result] if result.outcome == Outcome::Passed)); + + // The passing entry of the same file broken. + let mut broken = units.clone(); + broken["c_passes"]["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(2)); + assert_eq!(gate(&broken), [unattributed]); + + // Both at once: two failures in the file, as the deviation lists, and the gate still fails. + let mut both = passes.clone(); + both["c_passes"] = broken["c_passes"].clone(); + let report = run_with(&both); + assert_eq!(report.summary().failed_total(), 2); + assert_eq!(report.gate(None, None, true), [unattributed, unreproduced, explains_one]); + + // The listed entries failing with other hashes: a sender that starts with one more wei moves + // the post-state root, and leaves the logs as they were. + for name in ["a_root", "b_logs"] { + let mut other = units.clone(); + other[name]["pre"][SENDER]["balance"] = json!("0x3635c9adc5dea00001"); + let report = run_with(&other); + let failure = report + .results + .iter() + .find_map(|result| match &result.outcome { + Outcome::Failed(failure) if result.id.name == name => Some(failure.clone()), + _ => None, + }) + .expect("the entry fails"); + assert_eq!( + failure.kind, + registry[0].entries.iter().find(|e| e.name == name).unwrap().produced.kind() + ); + assert_eq!(failure.deviation, None, "{name}"); + assert_eq!( + report.gate(None, None, true), + [unattributed, unreproduced, explains_one], + "{name}" + ); + } + + // The same tests in another file are not the listed entries. + let elsewhere = write(dir.path(), "cancun/elsewhere.json", units); + let report = run(&[elsewhere], Config { deviations: registry, ..equivalence }); + assert_eq!(report.summary().unattributed, 2); + assert_eq!(report.summary().unreproduced.get("listed"), Some(&2)); + + // Satin mode attributes nothing, and has nothing to reproduce. + let report = run(&[path], Config { deviations: registry, ..config(Mode::Satin, Fork::Osaka) }); + let summary = report.summary(); + assert!(summary.deviated.is_empty() && summary.unreproduced.is_empty()); +} + +/// A failure of an entry the registry lists, with hashes the registry does not list, is +/// unattributed: the registry explains its own failures, not the place they are in. +#[test] +fn test_the_registry_does_not_absorb_another_failure_of_its_entries() { + let dir = tempfile::tempdir().unwrap(); + let listed = &DEVIATIONS + .iter() + .find(|deviation| deviation.fork == Fork::Osaka) + .expect("an Osaka deviation") + .entries[0]; + let mut wrong = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + wrong["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let path = write(dir.path(), listed.path, json!({ listed.name: wrong })); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + assert!(matches!( + &report.results[0].outcome, + Outcome::Failed(failure) if failure.kind == listed.produced.kind() && failure.deviation.is_none() + )); + assert_eq!(report.summary().unattributed, 1); +} diff --git a/crates/mega-state-test/tests/witness.rs b/crates/mega-state-test/tests/witness.rs new file mode 100644 index 000000000..f3ca0b993 --- /dev/null +++ b/crates/mega-state-test/tests/witness.rs @@ -0,0 +1,184 @@ +//! Fixtures replayed from the witness of their own execution: two fixtures written here, always, +//! and the execution-spec fixtures where they are named. +//! +//! The execution-spec fixtures are the ones the gate downloads. Point `MEGA_STATE_TEST_FIXTURES` +//! at a `state_tests` directory, by an absolute path (the test runs in the package's directory), +//! and run the ignored test, as the gate's workflow does for every file of both releases in both +//! modes: +//! +//! ```text +//! MEGA_STATE_TEST_FIXTURES=$PWD/fixtures/main/state_tests cargo test -p mega-state-test \ +//! --release --test witness -- --ignored +//! ``` +//! +//! `MEGA_STATE_TEST_SAMPLE` is how many fixture files to take, spread over the tree (300 unless +//! set; 0 for all of them), `MEGA_STATE_TEST_FORK` the fork whose entries run (`Osaka` unless +//! set) and `MEGA_STATE_TEST_MODE` the mode (`satin` unless set). +//! +//! It reports the entries the engine executed, which replayed on both witnesses, apart from the +//! entries it rejected, which replayed on the record of every database read alone. + +use std::{ + panic::{catch_unwind, AssertUnwindSafe}, + path::PathBuf, +}; + +use state_test::{ + runner::find_json_files, + types::TestSuite, + witness::{check_replay, Replayed}, + Fork, Mode, +}; + +/// A fixture of the execution-spec shape: a call to a contract that writes one slot, expected to +/// execute. The post-state hashes are the fixture's own and are not judged here. +const FIXTURE: &str = r#"{ + "a call that writes a slot": { + "env": { + "currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentGasLimit": "0x07270e00", + "currentNumber": "0x01", + "currentTimestamp": "0x03e8", + "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000000000", + "currentDifficulty": "0x00", + "currentBaseFee": "0x07", + "currentExcessBlobGas": "0x00" + }, + "pre": { + "0x42b24e5d48846699cab68f8318fdff2110dd6d8e": { + "nonce": "0x01", + "balance": "0x00", + "code": "0x600160005500", + "storage": {} + }, + "0x9a15735b9b881d3856d5e62a71ecde96976a8443": { + "nonce": "0x00", + "balance": "0x3635c9adc5dea00000", + "code": "0x", + "storage": {} + } + }, + "transaction": { + "nonce": "0x00", + "maxPriorityFeePerGas": "0x00", + "maxFeePerGas": "0x07", + "gasLimit": ["0x01000000"], + "to": "0x42b24e5d48846699cab68f8318fdff2110dd6d8e", + "value": ["0x00"], + "data": ["0x"], + "accessLists": [[]], + "sender": "0x9a15735b9b881d3856d5e62a71ecde96976a8443", + "secretKey": "0xcd44b7e62d9916d0ee4baf3f42b24e5d48846699cab68f8318fdff2110dd6d8e" + }, + "post": { + "Osaka": [ + { + "hash": "0x6b4267d9ce94c1314036f184414bb7e814651dc524bd20520f7dc41bb22de73e", + "logs": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "txbytes": "0x", + "indexes": { "data": 0, "gas": 0, "value": 0 } + } + ] + }, + "config": { + "blobSchedule": { + "Osaka": { "target": "0x06", "max": "0x09", "baseFeeUpdateFraction": "0x4c6964" } + }, + "chainid": "0x01" + } + } +}"#; + +/// Checks every Osaka entry of `fixture` in both modes, expecting `expected` of each. +fn check_fixture(fixture: &str, expected: Replayed) { + let suite: TestSuite = serde_json::from_str(fixture).expect("a fixture"); + let (_, unit) = suite.0.iter().next().expect("one test"); + let tests = unit.post.iter().find(|(spec, _)| Fork::Osaka.is(spec)).expect("Osaka").1; + for mode in Mode::ALL { + for test in tests { + assert_eq!(check_replay(mode, Fork::Osaka, unit, test), Ok(expected), "{mode}"); + } + } +} + +/// The fixture above executes, and replays on both witnesses in both modes. +#[test] +fn test_a_fixture_replays_from_its_witness() { + check_fixture(FIXTURE, Replayed::Both); +} + +/// The fixture above with a sender that cannot pay for its gas: the engine rejects it, so it +/// replays on the record of every database read alone, in both modes. +#[test] +fn test_a_rejected_fixture_replays_from_its_record_alone() { + let unfunded = FIXTURE.replace("0x3635c9adc5dea00000", "0x00"); + assert_ne!(unfunded, FIXTURE, "the sender's balance is in the fixture"); + check_fixture(&unfunded, Replayed::RecordOnly); +} + +/// A sample of the execution-spec fixtures replays from its witness. Ignored: it needs the +/// fixtures, named by `MEGA_STATE_TEST_FIXTURES`. +#[test] +#[ignore = "needs the execution-spec fixtures: set MEGA_STATE_TEST_FIXTURES to a state_tests directory"] +fn test_a_sample_of_the_fixtures_replays_from_its_witness() { + let root = PathBuf::from( + std::env::var("MEGA_STATE_TEST_FIXTURES") + .expect("MEGA_STATE_TEST_FIXTURES names the fixtures"), + ); + let sample: usize = + std::env::var("MEGA_STATE_TEST_SAMPLE").map_or(300, |n| n.parse().expect("a count")); + let fork: Fork = + std::env::var("MEGA_STATE_TEST_FORK").map_or(Fork::Osaka, |f| f.parse().expect("a fork")); + let mode: Mode = + std::env::var("MEGA_STATE_TEST_MODE").map_or(Mode::Satin, |m| m.parse().expect("a mode")); + + let files = find_json_files(&root); + assert!(!files.is_empty(), "no fixtures under {}", root.display()); + let stride = files.len().checked_div(sample).unwrap_or(1).max(1); + let sampled: Vec<_> = + files.iter().step_by(stride).take(if sample == 0 { usize::MAX } else { sample }).collect(); + + let (mut both, mut record_only, mut skipped, mut failed) = (0, 0, 0, Vec::new()); + for path in &sampled { + let json = std::fs::read_to_string(path).expect("a readable fixture"); + let suite: TestSuite = match serde_json::from_str(&json) { + Ok(suite) => suite, + Err(error) => { + failed.push(format!("{}: parse: {error}", path.display())); + continue; + } + }; + for (name, unit) in &suite.0 { + for (spec, tests) in &unit.post { + if !fork.is(spec) { + continue; + } + for (entry, test) in tests.iter().enumerate() { + let outcome = + catch_unwind(AssertUnwindSafe(|| check_replay(mode, fork, unit, test))); + match outcome { + Ok(Ok(Replayed::Both)) => both += 1, + Ok(Ok(Replayed::RecordOnly)) => record_only += 1, + Ok(Ok(Replayed::Skipped(_))) => skipped += 1, + Ok(Err(why)) => { + failed.push(format!("{}::{name}[{entry}]: {why}", path.display())) + } + Err(_) => { + failed.push(format!("{}::{name}[{entry}]: panicked", path.display())) + } + } + } + } + } + } + eprintln!( + "witness replay of {} fixture files in {mode} mode on {fork}: {both} executed and replayed on both witnesses, {record_only} rejected and replayed on the database record alone, {skipped} skipped, {} failed", + sampled.len(), + failed.len() + ); + for failure in failed.iter().take(50) { + eprintln!(" {failure}"); + } + assert!(failed.is_empty(), "{} entries did not replay from their witness", failed.len()); + assert!(both > 0, "nothing executed"); +} diff --git a/crates/state-test/AGENTS.md b/crates/state-test/AGENTS.md index d20279268..64a348c84 100644 --- a/crates/state-test/AGENTS.md +++ b/crates/state-test/AGENTS.md @@ -1,12 +1,14 @@ # AGENTS.md ## OVERVIEW -Thin CLI front-end over the `mega-state-test` runner library (`crates/mega-state-test`), used to run Ethereum state tests against MegaEVM. -This crate is not published; the runner, fixture types, and validation logic all live in `mega-state-test`. +Thin CLI front end over the `mega-state-test` runner library (`crates/mega-state-test`), which runs Ethereum's execution-spec state tests on the Satin engine. +This crate is not published; the runner, the modes, the deviation registry and the fixture types all live in `mega-state-test`. ## STRUCTURE -- `src/main.rs`: CLI entrypoint, flag parsing, and path-level orchestration. +- `src/main.rs`: flag parsing, the printed summary, and the exit-code contract. +- `src/btest.rs`: the `btest` subcommand, the blockchain tests' gate, with the same contract; `main` hands it every argument after `btest`, so the state tests' command is unchanged. +- `tests/cli.rs`: the exit-code contract CI relies on. ## WHERE TO LOOK -- Change CLI flags or path handling: `src/main.rs`. -- Anything about test execution, validation, skip policy, or fixture types: `crates/mega-state-test` (see its `AGENTS.md`). +- Change CLI flags, the summary or the exit codes: `src/main.rs`, and `src/btest.rs` for the blockchain tests. +- Anything about execution, judging, skips, deviations or fixture types: `crates/mega-state-test` (see its `AGENTS.md`). diff --git a/crates/state-test/Cargo.toml b/crates/state-test/Cargo.toml index d9aad2eae..f425e3029 100644 --- a/crates/state-test/Cargo.toml +++ b/crates/state-test/Cargo.toml @@ -6,7 +6,7 @@ rust-version.workspace = true license.workspace = true homepage.workspace = true repository.workspace = true -description = "CLI to run Ethereum State Tests for mega-evm" +description = "CLI running the execution-spec state tests on the mega-evm Satin engine" # The runner library lives in the published `mega-state-test` crate; this CLI is # a thin front-end and is not published. publish = false @@ -17,11 +17,21 @@ workspace = true [[bin]] name = "state-test" path = "src/main.rs" +# The library it fronts is `state_test`, whose documentation would share the bin's file name. +doc = false [dependencies] -mega-evm = { workspace = true, features = ["default", "test-utils"] } mega-state-test.workspace = true # misc clap = { workspace = true, features = ["default"] } -serde_json.workspace = true +serde_json = { workspace = true, features = ["std"] } + +[dev-dependencies] +mega-evm.workspace = true + +# alloy +alloy-rlp = { workspace = true, features = ["std"] } + +# misc +tempfile.workspace = true diff --git a/crates/state-test/README.md b/crates/state-test/README.md index 58ee76f85..7f573970d 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -1,18 +1,25 @@ -# MegaEVM state test +# state-test -The `state-test` CLI is a thin front-end over the `mega-state-test` runner library (`crates/mega-state-test`), which is a fork of `revme` in the official `revm` repository. +The command-line front end of the `mega-state-test` runner (`crates/mega-state-test`): it runs Ethereum's execution-spec state-test fixtures through the Satin engine. -The changes made to run `execution-specification-tests` on MegaEVM is: -- `MegaTransaction`'s `enveloped_tx` is always set to `Some(vec![].into())` so that there is no L1 data fee induced. -- State changes to the `BaseFeeVault` (`0x4200000000000000000000000000000000000019`) are pruned after transaction execution. -- The EVM spec of all Ethereum's official test cases are forced to be `MegaSpecId::EQUIVALENCE`, which is equivalent to `SpecId::PRAGUE`. +```bash +state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] ... +``` -## Modes +- `--mode equivalence` (the default) is the gate: it exits non-zero when a failure is not explained by a registered deviation, when a fixture file cannot be read, or when a count differs from the pin it is given. +- `--mode satin` is the report: it runs the same entries under Satin's own configuration, prints the counts by outcome, and exits zero unless a fixture file cannot be read. +- `--fork` names the fork whose fixture entries run. +- `--expect-executed N`, `--expect-skipped N` and `--expect-deviations` pin the counts of a full run; CI passes all three. +- `--summary-json FILE` writes the counts as JSON, `--json-outcome` prints one JSON line per test on standard error, `--trace` runs every test under an EIP-3155 tracer and `--threads` sets the worker count. -Every mode operates on self-contained EEST fixtures (`TestUnit { env, pre, transaction, post, out }`); none need a network. +```bash +state-test btest [options] ... +``` -- **Validate** (default) — `state-test ` executes each fixture and checks its recorded `post` (state root, logs root, gas, status). This is how the official Ethereum tests and the replay corpus (`bench/replay/fixtures/`, via `replay_corpus.rs`) are checked. -- **`--bench`** — `state-test --bench [--bench-runs N] [--bench-warmup W] [--bench-spec SPEC] ` times each fixture's isolated EVM execution and prints `{ gas_used, success, bench: { min/median/mean, mgasPerSec } }` as JSON instead of validating. This is the only EVM-throughput benchmark entry point; the replay-throughput benchmark (`bench/replay/run.py`) drives it. -- **`--fill`** — `state-test --fill --bench-spec SPEC ` computes each fixture's `post` and writes it back in place (atomically, via a temp file). This is the offline analog of `mega-evme replay --dump-fixture`'s post-fill step, for a fixture that has no on-chain origin (a hand-built case, or a `prestateTracer` snapshot such as `bench/replay/fixtures/attack_deploy.json`). After filling, the fixture is self-validating like any dumped one. A fixture that already has a non-empty `post` is refused unless `--force` is passed — filling replaces the whole `post` map with circularly-derived expectations, so an accidental run against real expectations (e.g. the official test suites) would destroy them. Filenames on the validation skip list and the Constantinople spec are refused outright, since validation would never check the result. +`btest` imports the execution-spec blockchain tests through Satin's block executor: the Osaka tests of the main release's `blockchain_tests`. -`--bench-spec` selects the spec to run under; without it, the fixture's single `post` spec is used (so `--fill` needs it when the `post` is still empty). \ No newline at end of file +- It exits non-zero when a test fails — a block differs from its header without the exact outcome a registered deviation lists for it, or a listed test does not deviate as listed — when a fixture file cannot be read, or when a count differs from the pin it is given. +- `--expect-executed N` pins the tests executed, `--expect-skipped REASON=N` the tests skipped for one reason (repeated for each; once one is given, every reason not given is pinned at zero), and `--expect-deviations` requires every blockchain test a registered deviation lists to deviate exactly as listed; CI passes all three. +- `--summary-json FILE`, `--json-outcome` and `--threads` work as for the state tests; the summary gives each skip class's reason beside its count, and the JSON summary lists every class's reason under `skip_reasons`. + +What the two modes are, how a state test and a blockchain test are judged and the deviation registry are described in the `mega-state-test` crate's `README.md` and `DEVIATIONS.md`. diff --git a/crates/state-test/src/btest.rs b/crates/state-test/src/btest.rs new file mode 100644 index 000000000..3db133df1 --- /dev/null +++ b/crates/state-test/src/btest.rs @@ -0,0 +1,199 @@ +//! `state-test btest`: the execution-spec blockchain tests, imported through Satin's block +//! executor. +//! +//! `state-test btest ` imports every Osaka test of the blockchain fixtures under `paths` +//! and exits non-zero when a test fails — a block differs from its header without the exact +//! outcome a registered deviation lists for it, or a listed test does not deviate as listed — +//! when a fixture file cannot be read, or when a count differs from the pin it is given. See the +//! `mega-state-test` crate's `blockchain` module for how a test is judged. + +use std::{collections::BTreeMap, path::PathBuf, process::ExitCode}; + +use clap::Parser; +use state_test::{ + blockchain::{run, Config, Outcome, Report, SkipReason, Summary, TestResult, NETWORK}, + deviations, + runner::find_json_files, +}; + +/// How many unattributed failures, and how many unreproduced tests, the summary lists. +const LISTED_FAILURES: usize = 50; + +/// Command-line arguments of `state-test btest`. +#[derive(Parser, Debug)] +#[command( + name = "state-test btest", + about = "Imports the execution-spec blockchain tests through Satin's block executor" +)] +pub(crate) struct Cmd { + /// Fixture files, or directories searched recursively for `.json` files. + #[arg(required = true, num_args = 1..)] + paths: Vec, + /// Worker threads (default: one per core). + #[arg(long)] + threads: Option, + /// Print one JSON line per test to standard error. + #[arg(long)] + json_outcome: bool, + /// Write the summary, as JSON, to this file. + #[arg(long, value_name = "FILE")] + summary_json: Option, + /// Fail unless exactly this many tests execute. + #[arg(long, value_name = "N")] + expect_executed: Option, + /// Fail unless exactly this many tests are skipped for this reason; once one is given, every + /// reason not given is pinned at zero. Repeat it for each reason. + #[arg(long, value_name = "REASON=N", value_parser = parse_pin)] + expect_skipped: Vec<(SkipReason, usize)>, + /// Fail unless every blockchain test a registered deviation lists deviates exactly as listed: + /// every block matching its header or its listed outcome, and the chain ending as listed. + #[arg(long)] + expect_deviations: bool, +} + +/// A `REASON=N` pin. +fn parse_pin(pin: &str) -> Result<(SkipReason, usize), String> { + let (reason, count) = + pin.split_once('=').ok_or_else(|| format!("expected REASON=N, got {pin:?}"))?; + let count = count.parse().map_err(|error| format!("{count:?}: {error}"))?; + Ok((reason.parse()?, count)) +} + +/// Runs `state-test btest` with `args`, the subcommand's name first. +pub(crate) fn main(args: impl IntoIterator) -> ExitCode { + let cmd = Cmd::parse_from(args); + let mut pins = BTreeMap::new(); + for (reason, count) in &cmd.expect_skipped { + if pins.insert(*reason, *count).is_some() { + eprintln!("error: --expect-skipped pins {} twice", reason.name()); + return ExitCode::FAILURE; + } + } + let mut files = Vec::new(); + for path in &cmd.paths { + if !path.exists() { + eprintln!("error: {} does not exist", path.display()); + return ExitCode::FAILURE; + } + let found = find_json_files(path); + if found.is_empty() { + eprintln!("error: no JSON fixtures under {}", path.display()); + return ExitCode::FAILURE; + } + files.extend(found); + } + + let threads = + cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); + let config = + Config { threads, json_outcome: cmd.json_outcome, deviations: deviations::DEVIATIONS }; + let report = run(&files, config); + let summary = report.summary(); + print_summary(&report, &summary); + + if let Some(path) = &cmd.summary_json { + let json = serde_json::json!({ + "suite": "blockchain", + "fork": NETWORK, + "summary": summary, + "skip_reasons": skip_reasons(), + }); + let json = serde_json::to_string_pretty(&json).expect("a summary serializes"); + if let Err(error) = std::fs::write(path, json + "\n") { + eprintln!("error: writing {}: {error}", path.display()); + return ExitCode::FAILURE; + } + } + + let pins = (!pins.is_empty()).then_some(&pins); + let problems = report.gate(cmd.expect_executed, pins, cmd.expect_deviations); + for problem in &problems { + println!("gate: {problem}"); + } + if problems.is_empty() { + println!("gate: passed"); + ExitCode::SUCCESS + } else { + ExitCode::FAILURE + } +} + +/// Every skip class's reason, by its name. +fn skip_reasons() -> BTreeMap<&'static str, &'static str> { + SkipReason::ALL.iter().map(|reason| (reason.name(), reason.reason())).collect() +} + +fn print_summary(report: &Report, summary: &Summary) { + println!("blockchain tests, {NETWORK} fixtures: {} files", summary.files); + println!( + " defined {} executed {} passed {} deviated {} failed {} skipped {}", + summary.defined, + summary.executed, + summary.passed, + summary.deviated_total(), + summary.failed_total(), + summary.skipped_total() + ); + let blocks = summary.blocks; + println!( + " blocks checked against Ethereum {} (matched {}, refused as expected {}) matched to a \ + deviation {}", + blocks.checked(), + blocks.matched, + blocks.refused, + blocks.deviated + ); + for (reason, count) in &summary.skipped { + println!(" skipped {:<34} {count:<6} {}", reason.name(), reason.reason()); + } + for (kind, count) in &summary.failed { + println!(" failed {:<34} {count}", kind.name()); + } + for deviation in report.deviations { + let listed = deviation.blockchain_entries.len(); + if listed > 0 { + let deviated = summary.deviated.get(deviation.id).copied().unwrap_or(0); + println!(" deviated {:<34} {deviated} (listed {listed})", deviation.id); + } + } + println!(" unattributed {}", summary.unattributed); + for (id, failure) in report.unattributed().take(LISTED_FAILURES) { + println!(" {id}\n {}: {}", failure.kind.name(), failure.detail); + } + if summary.unattributed > LISTED_FAILURES { + println!(" ... and {} more", summary.unattributed - LISTED_FAILURES); + } + let unreproduced: usize = summary.unreproduced.values().sum(); + println!(" unreproduced {unreproduced}"); + for entry in report.unreproduced().take(LISTED_FAILURES) { + println!( + " {}\n {} lists {} blocks; {}", + entry.entry, + entry.deviation.id, + entry.entry.blocks.len(), + seen(&entry.seen) + ); + } + if unreproduced > LISTED_FAILURES { + println!(" ... and {} more", unreproduced - LISTED_FAILURES); + } + for (path, failure) in &report.file_failures { + println!(" unreadable {path}\n {}", failure.detail); + } +} + +/// What a run did with a listed test, given the results it has for it. +fn seen(results: &[&TestResult]) -> String { + match results { + [] => "the run did not execute it".into(), + [result] => match &result.outcome { + Outcome::Passed => "it passed".into(), + Outcome::Deviated { deviation } => format!("it deviated under {deviation}"), + Outcome::Skipped { reason } => format!("it was skipped: {}", reason.name()), + Outcome::Failed(failure) => { + format!("it failed: {}: {}", failure.kind.name(), failure.detail) + } + }, + results => format!("{} results of the run are the test's", results.len()), + } +} diff --git a/crates/state-test/src/compare.txt b/crates/state-test/src/compare.txt deleted file mode 100644 index f9a550a7b..000000000 --- a/crates/state-test/src/compare.txt +++ /dev/null @@ -1,85 +0,0 @@ -CacheState { - accounts: { - 0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 203478, - nonce: 0, - code_hash: 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x00, - original_len: 0, - jump_table: JumpTable { - map: "", - }, - }, - ), - ), - }, - storage: {}, - }, - ), - status: InMemoryChange, - }, - 0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b: CacheAccount { - account: None, - status: LoadedNotExisting, - }, - 0x8a0a19589531694250d570040a0c4b74576919b8: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 999999999999999321740, - nonce: 1, - code_hash: 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x00, - original_len: 0, - jump_table: JumpTable { - map: "", - }, - }, - ), - ), - }, - storage: {}, - }, - ), - status: InMemoryChange, - }, - 0x1000000000000000000000000000000000001000: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 0, - nonce: 1, - code_hash: 0xfbd649b5e89a9cd9340bdbad17eb49cdb4136b87cedffb34823393fa48be10a0, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x600060006000600073a94f5374fce5edbc8e2a8697c15331677e6ebf0b5af460025561201560015500, - original_len: 41, - jump_table: JumpTable { - map: "000000000000", - }, - }, - ), - ), - }, - storage: { - 2: 1, - 1: 8213, - }, - }, - ), - status: Changed, - }, - }, - contracts: {}, - has_state_clear: true, -} \ No newline at end of file diff --git a/crates/state-test/src/compare_failed.txt b/crates/state-test/src/compare_failed.txt deleted file mode 100644 index 5633f5db5..000000000 --- a/crates/state-test/src/compare_failed.txt +++ /dev/null @@ -1,85 +0,0 @@ -CacheState { - accounts: { - 0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 203478, - nonce: 0, - code_hash: 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x00, - original_len: 0, - jump_table: JumpTable { - map: "", - }, - }, - ), - ), - }, - storage: {}, - }, - ), - status: InMemoryChange, - }, - 0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b: CacheAccount { - account: None, - status: LoadedNotExisting, - }, - 0x8a0a19589531694250d570040a0c4b74576919b8: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 999999999999999321740, - nonce: 1, - code_hash: 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x00, - original_len: 0, - jump_table: JumpTable { - map: "", - }, - }, - ), - ), - }, - storage: {}, - }, - ), - status: InMemoryChange, - }, - 0x1000000000000000000000000000000000001000: CacheAccount { - account: Some( - PlainAccount { - info: AccountInfo { - balance: 0, - nonce: 1, - code_hash: 0xfbd649b5e89a9cd9340bdbad17eb49cdb4136b87cedffb34823393fa48be10a0, - code: Some( - LegacyAnalyzed( - LegacyAnalyzedBytecode { - bytecode: 0x600060006000600073a94f5374fce5edbc8e2a8697c15331677e6ebf0b5af460025561201560015500, - original_len: 41, - jump_table: JumpTable { - map: "000000000000", - }, - }, - ), - ), - }, - storage: { - 2: 1, - 1: 8213, - }, - }, - ), - status: Changed, - }, - }, - contracts: {}, - has_state_clear: true, -} \ No newline at end of file diff --git a/crates/state-test/src/main.rs b/crates/state-test/src/main.rs index 65b70acda..7c24e0cdd 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -1,270 +1,203 @@ -//! State test crate +//! Runs the execution-spec state tests on the Satin engine. +//! +//! `state-test --fork Osaka ` executes every Osaka entry of the fixtures under `paths` in +//! equivalence mode and exits non-zero when a failure is not explained by a registered deviation; +//! `--mode satin` runs the same entries under Satin's own configuration and only reports. See the +//! `mega-state-test` crate for what the two modes are. +//! +//! `state-test btest ` imports the blockchain tests through Satin's block executor +//! ([`btest`]). #![cfg_attr(not(test), warn(unused_crate_dependencies))] -#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] + +mod btest; + +use std::{path::PathBuf, process::ExitCode}; use clap::Parser; use state_test::{ - runner::{ - bench_test_suite, fill_test_suite, find_all_json_tests, run, TestError, TestErrorKind, - UnitBench, - }, - types::SpecName, + deviations, + runner::{find_json_files, run, Config, Outcome, Report, Summary, TestResult}, + Fork, Mode, }; -use std::{path::PathBuf, str::FromStr}; -use mega_evm::MegaSpecId; -use serde_json::json; +/// How many unattributed failures, and how many unreproduced entries, the summary lists. +const LISTED_FAILURES: usize = 50; -/// `statetest` subcommand +/// Command-line arguments. #[derive(Parser, Debug)] -pub struct Cmd { - /// Path to folder or file containing the tests - /// - /// If multiple paths are specified they will be run in sequence. - /// - /// Folders will be searched recursively for files with the extension `.json`. +#[command( + name = "state-test", + about = "Runs execution-spec state tests on the Satin engine", + after_help = "`state-test btest --help` describes the blockchain tests' subcommand." +)] +struct Cmd { + /// Fixture files, or directories searched recursively for `.json` files. #[arg(required = true, num_args = 1..)] paths: Vec, - /// Run tests in a single thread - #[arg(short = 's', long)] - single_thread: bool, - /// Output results in JSON format - /// - /// It will stop second run of evm on failure. + /// The configuration the tests run under: `equivalence` (a gate) or `satin` (a report). + #[arg(long, default_value = "equivalence")] + mode: Mode, + /// The fork whose fixture entries run: `Osaka` or `Amsterdam`. + #[arg(long)] + fork: Fork, + /// Worker threads (default: one per core). + #[arg(long)] + threads: Option, + /// Print one JSON line per test to standard error. #[arg(long)] - json: bool, - /// Output outcome in JSON format - /// - /// If `--json` is true, this is implied. - /// - /// It will stop second run of EVM on failure. - #[arg(short = 'o', long)] json_outcome: bool, - /// Keep going after a test failure - #[arg(long, alias = "no-fail-fast")] - keep_going: bool, - /// Benchmark each fixture's isolated EVM execution instead of validating it. - /// - /// Emits per-unit timing (min/median/mean) and Mgas/s as JSON. The fixture - /// is self-contained, so this needs no RPC — any state-test fixture (a - /// dumped replay, a prestate snapshot, a hand-crafted case) can be measured. + /// Trace every test with an EIP-3155 tracer on standard error; runs on one thread. + #[arg(long)] + trace: bool, + /// Write the summary, as JSON, to this file. + #[arg(long, value_name = "FILE")] + summary_json: Option, + /// Equivalence mode: fail unless exactly this many tests execute. + #[arg(long, value_name = "N")] + expect_executed: Option, + /// Equivalence mode: fail unless exactly this many tests are skipped. + #[arg(long, value_name = "N")] + expect_skipped: Option, + /// Equivalence mode: fail unless every entry a registered deviation lists for the fork fails + /// exactly as listed, with the hashes listed. #[arg(long)] - bench: bool, - /// Timed iterations per unit when `--bench` is set. - #[arg(long, default_value_t = 50)] - bench_runs: u32, - /// Discarded warmup iterations before timing when `--bench` is set. - #[arg(long, default_value_t = 5)] - bench_warmup: u32, - /// Spec to benchmark / fill under (default: the fixture's single `post` spec). - #[arg(long, value_name = "SPEC")] - bench_spec: Option, - /// Compute and write each fixture's `post` expectation in place. - /// - /// The offline analog of `--dump-fixture`'s post-fill: makes a fixture that - /// has no `post` (a hand-built or prestate-snapshot case) self-validating. - /// Use `--bench-spec` to choose the spec when the fixture has no `post` yet. - /// Refuses fixtures that already have a `post` unless `--force` is set. - #[arg(long, conflicts_with_all = ["bench", "bench_runs", "bench_warmup"])] - fill: bool, - /// Overwrite an existing non-empty `post` when filling with `--fill`. - #[arg(long, requires = "fill")] - force: bool, + expect_deviations: bool, } -impl Cmd { - /// Runs `statetest` command. - pub fn run(&self) -> Result<(), TestError> { - if self.fill { - return self.run_fill(); +fn main() -> ExitCode { + // `btest` names the blockchain tests' subcommand; anything else is the state tests' command, + // whose arguments are unchanged. + let mut args = std::env::args_os(); + if args.nth(1).is_some_and(|first| first == "btest") { + return btest::main(std::env::args_os().skip(1)); + } + let cmd = Cmd::parse(); + let mut files = Vec::new(); + for path in &cmd.paths { + if !path.exists() { + eprintln!("error: {} does not exist", path.display()); + return ExitCode::FAILURE; } - if self.bench { - return self.run_bench(); + let found = find_json_files(path); + if found.is_empty() { + eprintln!("error: no JSON fixtures under {}", path.display()); + return ExitCode::FAILURE; } - for path in &self.paths { - if !path.exists() { - return Err(TestError { - name: "Path validation".to_string(), - path: path.display().to_string(), - kind: TestErrorKind::InvalidPath, - }); - } - - println!("\nRunning tests in {}...", path.display()); - let test_files = find_all_json_tests(path); - - if test_files.is_empty() { - return Err(TestError { - name: "Path validation".to_string(), - path: path.display().to_string(), - kind: TestErrorKind::NoJsonFiles, - }); - } - - run(test_files, self.single_thread, self.json, self.json_outcome, self.keep_going)? - } - Ok(()) + files.extend(found); } - /// Parse `--bench-spec` into a [`SpecName`], if given. - fn resolve_spec(&self) -> Result, TestError> { - self.bench_spec - .as_deref() - .map(|s| { - // Derived from `MegaSpecId::ALL` so the roster tracks the ladder (aliases and - // new specs included) instead of drifting as a hand-written list. - let invalid_spec = || TestError { - name: "spec".to_string(), - path: s.to_string(), - kind: TestErrorKind::FixtureError(format!( - "invalid --bench-spec {s:?}; expected one of: {}", - MegaSpecId::ALL - .iter() - .copied() - .filter(|spec| SpecName::from_mega_spec(*spec) != SpecName::Unknown) - .map(<&'static str>::from) - .collect::>() - .join(", ") - )), - }; - let spec = MegaSpecId::from_str(s) - .map(SpecName::from_mega_spec) - .map_err(|_| invalid_spec())?; - // A spec id that parses but has no fixture-facing name (a - // future `MegaSpecId` this crate does not map yet) would - // otherwise fail much later, deep inside execution — reject it - // here with the same actionable message. - if spec == SpecName::Unknown { - return Err(invalid_spec()); - } - Ok(spec) - }) - .transpose() - } - - /// Fill every fixture's `post` expectation in place (see `--fill`). - fn run_fill(&self) -> Result<(), TestError> { - let spec_override = self.resolve_spec()?; - for path in &self.paths { - if !path.exists() { - return Err(TestError { - name: "Path validation".to_string(), - path: path.display().to_string(), - kind: TestErrorKind::InvalidPath, - }); - } - for file in find_all_json_tests(path) { - let n = fill_test_suite(&file, spec_override, self.force)?; - println!("Filled post for {n} unit(s) in {}", file.display()); - } + let threads = if cmd.trace { + 1 + } else { + cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())) + }; + let config = Config { + mode: cmd.mode, + fork: cmd.fork, + threads, + json_outcome: cmd.json_outcome, + trace: cmd.trace, + deviations: deviations::DEVIATIONS, + }; + let report = run(&files, config); + let summary = report.summary(); + print_summary(&report, &summary); + + if let Some(path) = &cmd.summary_json { + let json = + serde_json::json!({ "mode": report.mode, "fork": report.fork, "summary": summary }); + let json = serde_json::to_string_pretty(&json).expect("a summary serializes"); + if let Err(error) = std::fs::write(path, json + "\n") { + eprintln!("error: writing {}: {error}", path.display()); + return ExitCode::FAILURE; } - Ok(()) } - /// Benchmark every fixture under the given paths and print the results as JSON. - /// - /// A single benchmarked unit prints one object `{ gas_used, success, bench }`; - /// multiple units print a JSON array of `{ name, ... }` objects. The - /// replay-bench driver (`bench/replay/run.py`) consumes this output. - fn run_bench(&self) -> Result<(), TestError> { - let spec_override = self.resolve_spec()?; - - let mut all: Vec = Vec::new(); - for path in &self.paths { - if !path.exists() { - return Err(TestError { - name: "Path validation".to_string(), - path: path.display().to_string(), - kind: TestErrorKind::InvalidPath, - }); + match cmd.mode { + Mode::Equivalence => { + let problems = + report.gate(cmd.expect_executed, cmd.expect_skipped, cmd.expect_deviations); + for problem in &problems { + println!("gate: {problem}"); } - for file in find_all_json_tests(path) { - all.extend(bench_test_suite( - &file, - self.bench_runs, - self.bench_warmup, - spec_override, - )?); + if problems.is_empty() { + println!("gate: passed"); + ExitCode::SUCCESS + } else { + ExitCode::FAILURE } } - - let bench_json = |u: &UnitBench| { - json!({ - "runs": u.runs, - "gasUsed": u.gas_used, - "minNs": u.min.as_nanos(), - "medianNs": u.median.as_nanos(), - "meanNs": u.mean.as_nanos(), - "mgasPerSec": u.mgas_per_sec(), - }) - }; - let output = if all.len() == 1 { - let u = &all[0]; - json!({ "gas_used": u.gas_used, "success": u.success, "bench": bench_json(u) }) - } else { - json!(all - .iter() - .map(|u| json!({ - "name": u.name, - "gas_used": u.gas_used, - "success": u.success, - "bench": bench_json(u), - })) - .collect::>()) - }; - println!("{}", serde_json::to_string_pretty(&output).expect("serialize bench output")); - Ok(()) + // A report: it fails only when a fixture could not be run at all, which is the runner's + // failure rather than Satin's. + Mode::Satin if summary.file_failures > 0 => ExitCode::FAILURE, + Mode::Satin => ExitCode::SUCCESS, } } -fn main() { - let cmd = Cmd::parse(); - // CI exit-code contract: any error — including `TestsFailed` when tests - // fail under `--keep-going` — prints to stderr and exits with code 1. - if let Err(e) = cmd.run() { - eprintln!("{e}"); - std::process::exit(1); +fn print_summary(report: &Report, summary: &Summary) { + println!("{} mode, {} fixtures: {} files", report.mode, report.fork, summary.files); + println!( + " defined {} executed {} passed {} failed {} skipped {}", + summary.defined, + summary.executed, + summary.passed, + summary.failed_total(), + summary.skipped_total() + ); + for (reason, count) in &summary.skipped { + println!(" skipped {:<34} {count}", reason.name()); } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn cmd_with_bench_spec(spec: &str) -> Cmd { - Cmd::parse_from(["state-test", "fixture.json", "--bench-spec", spec]) - } - - #[test] - fn resolve_spec_none_when_absent() { - let cmd = Cmd::parse_from(["state-test", "fixture.json"]); - assert_eq!(cmd.resolve_spec().expect("no spec is fine"), None); + for (kind, count) in &summary.failed { + println!(" failed {:<34} {count}", kind.name()); } - - #[test] - fn resolve_spec_accepts_every_known_spec() { - // Driven off `MegaSpecId::ALL`, so a newly introduced spec or alias joins here - // automatically — and a spec left without a fixture-facing `SpecName` fails loudly - // instead of being quietly absent from the roster. - for spec in MegaSpecId::ALL.iter().copied() { - let s: &str = spec.into(); - let resolved = - cmd_with_bench_spec(s).resolve_spec().expect("valid spec").expect("present"); - assert_eq!(resolved, SpecName::from_mega_spec(spec), "--bench-spec {s}"); - // No accepted spec may slip through as Unknown and fail later. - assert_ne!(resolved, SpecName::Unknown, "--bench-spec {s}"); + if report.mode == Mode::Equivalence { + for deviation in report.deviations { + let listed = deviation.listed(report.fork).len(); + if listed > 0 { + let explained = summary.deviated.get(deviation.id).copied().unwrap_or(0); + println!(" deviated {:<34} {explained} (listed {listed})", deviation.id); + } + } + println!(" unattributed {}", summary.unattributed); + for (id, failure) in report.unattributed().take(LISTED_FAILURES) { + println!(" {id}\n {}: {}", failure.kind.name(), failure.detail); + } + if summary.unattributed > LISTED_FAILURES { + println!(" ... and {} more", summary.unattributed - LISTED_FAILURES); + } + let unreproduced: usize = summary.unreproduced.values().sum(); + println!(" unreproduced {unreproduced}"); + for entry in report.unreproduced().take(LISTED_FAILURES) { + println!( + " {}\n {} lists {}, {}; {}", + entry.entry, + entry.deviation.id, + entry.entry.produced.kind().name(), + entry.entry.produced, + seen(&entry.seen) + ); } + if unreproduced > LISTED_FAILURES { + println!(" ... and {} more", unreproduced - LISTED_FAILURES); + } + } + for (path, failure) in &report.file_failures { + println!(" unreadable {path}\n {}", failure.detail); } +} - #[test] - fn resolve_spec_rejects_unparseable_string() { - let err = cmd_with_bench_spec("FutureFork9000") - .resolve_spec() - .expect_err("unknown spec string must be rejected"); - assert!( - err.to_string().contains("invalid --bench-spec"), - "error should be actionable: {err}" - ); +/// What a run did with a listed entry, given the results it has for it. +fn seen(results: &[&TestResult]) -> String { + match results { + [] => "the run did not execute it".into(), + [result] => match &result.outcome { + Outcome::Passed => "it passed".into(), + Outcome::Skipped { reason } => format!("it was skipped: {}", reason.name()), + Outcome::Failed(failure) => { + format!("it failed: {}: {}", failure.kind.name(), failure.detail) + } + }, + results => format!("{} results of the run are the entry's", results.len()), } } diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs new file mode 100644 index 000000000..d9d3348d9 --- /dev/null +++ b/crates/state-test/tests/cli.rs @@ -0,0 +1,322 @@ +//! The exit-code contract the CI gate relies on: equivalence mode exits non-zero on a failure no +//! deviation explains and on a count that differs from its pin; Satin mode reports and exits zero +//! unless a fixture could not be read; `btest` exits non-zero as equivalence mode does. + +use std::{ + path::{Path, PathBuf}, + process::{Command, Output}, +}; + +use mega_evm::{ + alloy_consensus::{Block, BlockBody, Header, TxEnvelope, EMPTY_ROOT_HASH}, + revm::{ + database::PlainAccount, + primitives::{address, Bytes, B256, U256}, + state::AccountInfo, + }, +}; +use serde_json::json; +use state_test::{ + blockchain::SkipReason, + roots::{logs_hash, state_root}, + types::TestSuite, +}; + +/// A fixture whose transaction cannot pay its intrinsic gas — 21,000 for a call carrying one byte +/// — and which expects `exception`. A rejected transaction leaves the pre-state, so the expected +/// roots are the pre-state's and the empty list's, whichever engine rejects it. +fn fixture(dir: &Path, exception: &str) -> PathBuf { + let mut unit = json!({ + "env": { + "currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "currentGasLimit": "0x1000000", + "currentNumber": "0x01", + "currentTimestamp": "0x03e8", + "currentBaseFee": "0x07", + "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000020000", + }, + "pre": { + "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": { + "balance": "0x3635c9adc5dea00000", "code": "0x", "nonce": "0x00", "storage": {} + }, + }, + "transaction": { + "data": ["0x00"], + "gasLimit": ["0x5208"], + "gasPrice": "0x0a", + "nonce": "0x00", + "secretKey": "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8", + "to": "0x00000000000000000000000000000000000c0de0", + "value": ["0x00"], + }, + "post": { "Osaka": [{ + "indexes": { "data": 0, "gas": 0, "value": 0 }, + "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "logs": "0x0000000000000000000000000000000000000000000000000000000000000000", + "expectException": exception, + }]}, + }); + let parsed: TestSuite = serde_json::from_value(json!({ "t": unit.clone() })).expect("a unit"); + let pre = parsed.0["t"].state(); + unit["post"]["Osaka"][0]["hash"] = json!(state_root(pre.trie_account())); + unit["post"]["Osaka"][0]["logs"] = json!(logs_hash(&[])); + + let path = dir.join(format!("{}.json", exception.len())); + std::fs::write(&path, serde_json::to_string(&json!({ "t": unit })).unwrap()).unwrap(); + path +} + +fn state_test(args: &[&str], path: &Path) -> Output { + Command::new(env!("CARGO_BIN_EXE_state-test")) + .args(args) + .arg(path) + .output() + .expect("the binary runs") +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn test_a_passing_run_exits_zero() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + let summary = dir.path().join("summary.json"); + let output = state_test( + &[ + "--fork", + "Osaka", + "--expect-executed", + "1", + "--expect-skipped", + "0", + "--summary-json", + summary.to_str().unwrap(), + ], + &path, + ); + assert!(output.status.success(), "{}", stdout(&output)); + assert!(stdout(&output).contains("gate: passed")); + let summary: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(summary).unwrap()).unwrap(); + assert_eq!(summary["mode"], "equivalence"); + assert_eq!(summary["summary"]["executed"], 1); + assert_eq!(summary["summary"]["passed"], 1); +} + +#[test] +fn test_a_count_off_its_pin_exits_non_zero() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + let output = state_test(&["--fork", "Osaka", "--expect-executed", "2"], &path); + assert_eq!(output.status.code(), Some(1)); + assert!(stdout(&output).contains("gate: 1 tests executed, 2 pinned"), "{}", stdout(&output)); + + // Every registered deviation lists entries of the full release; one test runs none of them. + let output = state_test(&["--fork", "Osaka", "--expect-deviations"], &path); + assert_eq!(output.status.code(), Some(1)); + let out = stdout(&output); + assert!( + out.contains( + "gate: deviation amsterdam-opcodes-on-osaka: 2 of the 2 entries it lists on Osaka \ + did not fail as listed" + ) && out.contains("gate: deviation amsterdam-opcodes-on-osaka explains 0 failed tests"), + "{out}" + ); + assert!(out.contains("unreproduced 2") && out.contains("the run did not execute it"), "{out}"); +} + +#[test] +fn test_an_unattributed_failure_fails_the_gate_but_not_the_report() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.NONCE_IS_MAX"); + let output = state_test(&["--fork", "Osaka"], &path); + assert_eq!(output.status.code(), Some(1)); + let out = stdout(&output); + assert!(out.contains("unattributed 1") && out.contains("wrong-exception"), "{out}"); + + let output = state_test(&["--mode", "satin", "--fork", "Osaka"], &path); + assert!(output.status.success(), "{}", stdout(&output)); + assert!(stdout(&output).contains("failed wrong-exception")); +} + +#[test] +fn test_bad_arguments_exit_non_zero() { + let dir = tempfile::tempdir().unwrap(); + let output = state_test(&["--fork", "Osaka"], &dir.path().join("missing")); + assert_eq!(output.status.code(), Some(1)); + let output = state_test(&["--fork", "Osaka"], dir.path()); + assert_eq!(output.status.code(), Some(1), "a directory with no fixtures"); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + assert!(!state_test(&["--fork", "Prague"], &path).status.success()); + assert!(!state_test(&[], &path).status.success(), "the fork is required"); + + std::fs::write(dir.path().join("broken.json"), "{").unwrap(); + for mode in ["equivalence", "satin"] { + let output = state_test(&["--mode", mode, "--fork", "Osaka"], dir.path()); + assert_eq!(output.status.code(), Some(1), "{mode}: an unreadable fixture"); + } +} + +/// A blockchain fixture of one empty block on a pre-state of one funded account, with +/// `edit` applied to the block's header. With no pre-block contract and no transaction the block +/// changes nothing on Ethereum, so its expected roots are the pre-state's and the empty trie's, +/// whichever engine imports it. +fn blockchain_fixture(dir: &Path, name: &str, edit: impl FnOnce(&mut Header)) -> PathBuf { + let sender = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); + let balance = U256::from(10).pow(U256::from(21)); + let info = AccountInfo { balance, ..Default::default() }; + let pre = PlainAccount { info, storage: Default::default() }; + let root = state_root([(sender, &pre)]); + let genesis = Header { state_root: root, gas_limit: 30_000_000, ..Default::default() }; + let mut header = Header { + parent_hash: genesis.hash_slow(), + number: 1, + timestamp: 12, + gas_limit: 30_000_000, + base_fee_per_gas: Some(7), + state_root: root, + receipts_root: EMPTY_ROOT_HASH, + transactions_root: EMPTY_ROOT_HASH, + withdrawals_root: Some(EMPTY_ROOT_HASH), + blob_gas_used: Some(0), + excess_blob_gas: Some(0), + parent_beacon_block_root: Some(B256::ZERO), + ..Default::default() + }; + edit(&mut header); + let rlp = |header: &Header| { + let block = Block:: { + header: header.clone(), + body: BlockBody { + transactions: vec![], + ommers: vec![], + withdrawals: header.withdrawals_root.map(|_| Default::default()), + }, + }; + Bytes::from(alloy_rlp::encode(&block)) + }; + let test = json!({ + "network": "Osaka", + "genesisRLP": rlp(&genesis), + "blocks": [{ "rlp": rlp(&header), "transactions": [], "withdrawals": [] }], + "pre": { sender.to_string(): { "balance": balance, "code": "0x", "nonce": "0x00", "storage": {} } }, + "postState": { sender.to_string(): { "balance": balance, "code": "0x", "nonce": "0x00", "storage": {} } }, + "lastblockhash": header.hash_slow(), + "config": { "chainid": "0x01", "blobSchedule": { "Osaka": { "baseFeeUpdateFraction": "0x4c6964" } } }, + }); + let path = dir.join(format!("{name}.json")); + std::fs::write(&path, serde_json::to_string(&json!({ "t": test })).unwrap()).unwrap(); + path +} + +fn btest(args: &[&str], path: &Path) -> Output { + Command::new(env!("CARGO_BIN_EXE_state-test")) + .arg("btest") + .args(args) + .arg(path) + .output() + .expect("the binary runs") +} + +#[test] +fn test_btest_a_passing_run_exits_zero() { + let dir = tempfile::tempdir().unwrap(); + let path = blockchain_fixture(dir.path(), "a", |_| {}); + let summary = dir.path().join("summary.json"); + let output = btest( + &[ + "--expect-executed", + "1", + "--expect-skipped", + "withdrawals=0", + "--summary-json", + summary.to_str().unwrap(), + ], + &path, + ); + assert!(output.status.success(), "{}", stdout(&output)); + assert!(stdout(&output).contains("gate: passed")); + let summary: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(summary).unwrap()).unwrap(); + assert_eq!(summary["suite"], "blockchain"); + assert_eq!(summary["fork"], "Osaka"); + assert_eq!(summary["summary"]["executed"], 1); + assert_eq!(summary["summary"]["passed"], 1); + assert_eq!(summary["summary"]["blocks"]["matched"], 1); + assert_eq!(summary["summary"]["blocks"]["deviated"], 0); + assert!(stdout(&output).contains( + "blocks checked against Ethereum 1 (matched 1, refused as expected 0) matched to a \ + deviation 0" + )); + // Every skip class is named with its reason, whether or not a test was skipped for it. + let reasons = summary["skip_reasons"].as_object().unwrap(); + assert_eq!(reasons.len(), SkipReason::ALL.len()); + for reason in SkipReason::ALL { + assert_eq!(reasons[reason.name()], reason.reason()); + } +} + +#[test] +fn test_btest_a_count_off_its_pin_exits_non_zero() { + let dir = tempfile::tempdir().unwrap(); + let path = blockchain_fixture(dir.path(), "a", |_| {}); + let output = btest(&["--expect-executed", "2"], &path); + assert_eq!(output.status.code(), Some(1)); + assert!(stdout(&output).contains("gate: 1 tests executed, 2 pinned"), "{}", stdout(&output)); + + let output = btest(&["--expect-skipped", "header-or-body=1"], &path); + assert_eq!(output.status.code(), Some(1)); + let out = stdout(&output); + assert!(out.contains("gate: 0 tests skipped for header-or-body, 1 pinned"), "{out}"); + + // Every registered deviation lists tests of the full release; one test runs none of them. + let output = btest(&["--expect-deviations"], &path); + assert_eq!(output.status.code(), Some(1)); + let out = stdout(&output); + assert!( + out.contains( + "gate: deviation amsterdam-opcodes-on-osaka: 3 of the 3 blockchain tests it lists \ + did not deviate as listed" + ) && out.contains("unreproduced 3"), + "{out}" + ); +} + +#[test] +fn test_btest_an_unattributed_failure_fails_the_gate() { + let dir = tempfile::tempdir().unwrap(); + let path = blockchain_fixture(dir.path(), "a", |header| header.gas_used = 1); + let output = btest(&[], &path); + assert_eq!(output.status.code(), Some(1)); + let out = stdout(&output); + assert!(out.contains("unattributed 1") && out.contains("gas-used-mismatch"), "{out}"); + assert!( + out.contains("gate: 1 blockchain tests failed: no listed outcome explains them"), + "{out}" + ); + // The help says what the deviation pin requires of a listed test. + let help = Command::new(env!("CARGO_BIN_EXE_state-test")) + .args(["btest", "--help"]) + .output() + .expect("the binary runs"); + let help = stdout(&help).split_whitespace().collect::>().join(" "); + assert!(help.contains("deviates exactly as listed"), "{help}"); + assert!(!help.contains("fails exactly as listed"), "{help}"); +} + +#[test] +fn test_btest_bad_arguments_exit_non_zero() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(btest(&[], &dir.path().join("missing")).status.code(), Some(1)); + assert_eq!(btest(&[], dir.path()).status.code(), Some(1), "a directory with no fixtures"); + let path = blockchain_fixture(dir.path(), "a", |_| {}); + for pin in ["slow=1", "withdrawals", "withdrawals=x"] { + assert!(!btest(&["--expect-skipped", pin], &path).status.success(), "{pin}"); + } + let twice = ["--expect-skipped", "withdrawals=0", "--expect-skipped", "withdrawals=0"]; + assert_eq!(btest(&twice, &path).status.code(), Some(1)); + std::fs::write(dir.path().join("broken.json"), "{").unwrap(); + assert_eq!(btest(&[], dir.path()).status.code(), Some(1), "an unreadable fixture"); +} diff --git a/crates/state-test/tests/cli_exit.rs b/crates/state-test/tests/cli_exit.rs deleted file mode 100644 index e3b20cc5e..000000000 --- a/crates/state-test/tests/cli_exit.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! Exit-code contract tests for the `state-test` CLI. -//! -//! The runner library no longer calls `std::process::exit`; the CLI owns the -//! contract CI relies on: failing tests (or any error) → stderr message + -//! exit code 1, passing run → exit code 0. - -use std::{path::PathBuf, process::Command}; - -/// A unit whose execution succeeds but whose recorded roots are wrong, so -/// validation must fail. -const FAILING_SUITE: &str = r#"{ - "exit_code_test": { - "env": { - "currentChainID": "0x18c6", - "currentCoinbase": "0x3000000000000000000000000000000000000003", - "currentDifficulty": "0x0", - "currentGasLimit": "0x1c9c380", - "currentNumber": "0x10", - "currentTimestamp": "0x3e8", - "currentBaseFee": "0x0", - "currentRandom": "0x0000000000000000000000000000000000000000000000000000000000000001", - "currentExcessBlobGas": "0x0" - }, - "pre": { - "0x1000000000000000000000000000000000000001": { - "balance": "0xde0b6b3a7640000", - "code": "0x", - "nonce": "0x0", - "storage": {} - } - }, - "transaction": { - "type": 0, - "data": ["0x"], - "gasLimit": ["0x30d40"], - "gasPrice": "0x0", - "nonce": "0x0", - "secretKey": "0x0000000000000000000000000000000000000000000000000000000000000000", - "sender": "0x1000000000000000000000000000000000000001", - "to": "0x1000000000000000000000000000000000000001", - "value": ["0x0"] - }, - "post": { - "Rex5": [{ - "indexes": { "data": 0, "gas": 0, "value": 0 }, - "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", - "logs": "0x0000000000000000000000000000000000000000000000000000000000000000" - }] - } - } -}"#; - -fn write_fixture(file_name: &str, contents: &str) -> PathBuf { - let dir = std::env::temp_dir().join("state_test_cli_exit"); - std::fs::create_dir_all(&dir).expect("mkdir"); - let path = dir.join(file_name); - std::fs::write(&path, contents).expect("write fixture"); - path -} - -fn run_cli(args: &[&str]) -> std::process::Output { - Command::new(env!("CARGO_BIN_EXE_state-test")).args(args).output().expect("spawn state-test") -} - -#[test] -fn failing_tests_exit_with_code_1() { - let path = write_fixture("failing.json", FAILING_SUITE); - let path = path.to_str().expect("utf8 path"); - - // `--keep-going` exercises the `TestsFailed` summary path (no thread error). - let out = run_cli(&[path, "--keep-going", "--json-outcome"]); - assert_eq!(out.status.code(), Some(1), "failing tests must exit 1 (keep-going)"); - assert!( - String::from_utf8_lossy(&out.stderr).contains("failed"), - "stderr should report the failure" - ); - - // Without `--keep-going` the first thread error propagates; still exit 1. - let out = run_cli(&[path, "--json-outcome"]); - assert_eq!(out.status.code(), Some(1), "failing tests must exit 1 (fail-fast)"); -} - -#[test] -fn invalid_path_exits_with_code_1() { - let out = run_cli(&["/nonexistent/state_test_cli_exit_4928"]); - assert_eq!(out.status.code(), Some(1)); - assert!(!out.stderr.is_empty(), "stderr should carry the error message"); -} - -#[test] -fn passing_run_exits_with_code_0() { - // The same unit with an empty `post` validates trivially: the run completes - // with zero errors and must keep exiting 0. - let mut suite: serde_json::Value = serde_json::from_str(FAILING_SUITE).expect("parse"); - suite["exit_code_test"]["post"] = serde_json::json!({}); - let passing = serde_json::to_string(&suite).expect("serialize"); - - let path = write_fixture("passing.json", &passing); - let out = run_cli(&[path.to_str().expect("utf8 path")]); - assert_eq!(out.status.code(), Some(0), "passing run must exit 0"); -} diff --git a/crates/system-contracts/AGENTS.md b/crates/system-contracts/AGENTS.md index d0519b7fe..9a65176c8 100644 --- a/crates/system-contracts/AGENTS.md +++ b/crates/system-contracts/AGENTS.md @@ -6,10 +6,13 @@ System-contract artifact crate that validates Solidity bytecode at build time an ## STRUCTURE - `build.rs`: forge-driven bytecode generation, hash validation, versioned constant codegen. - `src/lib.rs`: generated constant includes and `alloy_sol_types::sol!` interface bindings. +- `src/generated/`: the checked-in Rust constants generated from `artifacts/`, which `src/lib.rs` includes; the build regenerates them and fails if the checked-in file differs. - `contracts/`: Solidity implementations. - `contracts/interfaces/`: ABI interface sources used by Rust bindings. - `artifacts/`: versioned bytecode JSON artifacts and `*-latest.json` references. - `scripts/`: Foundry scripts used by build-time bytecode generation. +- `test/`: Foundry tests (`forge test`, the `system-contracts` CI job). +- `tests/`: Rust tests of the generated constants and of the `SequencerRegistry`'s storage layout. ## KEY PATTERNS - Build script is authoritative for artifact consistency checks. @@ -20,13 +23,13 @@ System-contract artifact crate that validates Solidity bytecode at build time an ## ANTI-PATTERNS - Do not update Solidity code without updating artifacts and validating hashes. -- Do not hand-edit generated files in `OUT_DIR` expectations. -- Modify `build.rs` or artifacts instead. +- Do not hand-edit `src/generated/`. + Change the artifacts or `build.rs`, build once (the build rewrites the file and fails, asking for it to be committed), and commit the rewritten file. - Do not collapse versioned artifacts into a single mutable JSON file. - Preserve immutable historical versions for spec traceability. ## WHERE TO LOOK - Add a new system contract export: update `build.rs` contract list and `src/lib.rs` module include + interface binding. -- Rotate to a new bytecode version: add `artifacts/-X.Y.Z.json` and update `-latest.json`. +- Rotate to a new bytecode version: add `artifacts/-X.Y.Z.json` and update `-latest.json`, then build and commit the regenerated `src/generated/_artifacts.rs`. - Debug bytecode mismatch failures: `build.rs::validate_contract_bytecode` diagnostics. - Update ABI interface only: `contracts/interfaces/*.sol` and consuming modules in `src/lib.rs`. diff --git a/crates/system-contracts/build.rs b/crates/system-contracts/build.rs index 8bc092b8c..90261defd 100644 --- a/crates/system-contracts/build.rs +++ b/crates/system-contracts/build.rs @@ -18,7 +18,8 @@ use std::{ env, fmt::Write, fs, - path::Path, + io::ErrorKind, + path::{Path, PathBuf}, process::{Command, Stdio}, }; @@ -261,6 +262,38 @@ fn verify_generated_constants( } } +/// One `rerun-if-changed` per Solidity file under `dir`. +/// +/// Cargo keeps a directory trigger by that directory's own mtime, which an edit of a file inside +/// it does not move, so each source is named on its own. The bytecode check compiles the +/// contracts, the interfaces they import and the forge scripts that write the artifacts. +fn emit_solidity_reruns(dir: &Path) { + let mut sources = Vec::new(); + collect_sol_files(dir, &mut sources); + sources.sort(); + for path in sources { + println!("cargo::rerun-if-changed={}", path.display()); + } +} + +/// Appends every `.sol` file under `dir`, descending into subdirectories. +fn collect_sol_files(dir: &Path, out: &mut Vec) { + let entries = match fs::read_dir(dir) { + Ok(entries) => entries, + Err(err) if err.kind() == ErrorKind::NotFound => return, + Err(err) => panic!("failed to read {}: {err}", dir.display()), + }; + for entry in entries { + let entry = entry.unwrap_or_else(|err| panic!("failed to read {}: {err}", dir.display())); + let path = entry.path(); + if path.is_dir() { + collect_sol_files(&path, out); + } else if path.extension().is_some_and(|ext| ext == "sol") { + out.push(path); + } + } +} + fn main() { let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let crate_dir = Path::new(&manifest_dir); @@ -294,12 +327,10 @@ fn main() { }, ]; - // Set up rerun-if-changed triggers + // Set up rerun-if-changed triggers. + emit_solidity_reruns(&crate_dir.join("contracts")); + emit_solidity_reruns(&crate_dir.join("scripts")); for config in &contracts { - println!( - "cargo::rerun-if-changed={}", - crate_dir.join(format!("contracts/{}.sol", config.name)).display() - ); println!( "cargo::rerun-if-changed={}", crate_dir.join(format!("artifacts/{}-latest.json", config.name)).display() diff --git a/crates/system-contracts/contracts/interfaces/IKeylessDeploy.sol b/crates/system-contracts/contracts/interfaces/IKeylessDeploy.sol index 2c45be5aa..02aa2264d 100644 --- a/crates/system-contracts/contracts/interfaces/IKeylessDeploy.sol +++ b/crates/system-contracts/contracts/interfaces/IKeylessDeploy.sol @@ -26,9 +26,9 @@ interface IKeylessDeploy { /// @notice Failed to recover signer from signature (invalid signature). error InvalidSignature(); - /// @notice The signer does not have enough balance to cover the sandbox transaction's - /// pre-execution debit. Pre-Rex5 specs require `gas_limit × gas_price + value`; - /// Rex5+ requires `value` only because the sandbox transaction runs fee-free. + /// @notice The signer does not have enough balance to fund the deployment's value. + /// @dev The deployment pays no gas out of the signer's balance, so the value is all the + /// signer must hold. error InsufficientBalance(); /// @notice The deploy address already has code (contract already exists). @@ -38,27 +38,19 @@ interface IKeylessDeploy { /// @param signerNonce The on-chain nonce of the recovered signer. error SignerNonceTooHigh(uint64 signerNonce); - /// @notice The sandbox execution reverted. - /// @param gasUsed The amount of gas used before reverting. - /// @param output The revert output data. + /// @notice The deployment's creation reverted. + /// @param gasUsed The gas the creation spent. + /// @param output The creation's revert data. error ExecutionReverted(uint64 gasUsed, bytes output); - /// @notice The sandbox execution halted (out of gas, stack overflow, etc.). - /// @param gasUsed The amount of gas used before halting. + /// @notice The deployment's creation halted (out of gas, an invalid opcode, code the creation + /// refuses, etc.). + /// @param gasUsed The gas the creation spent. error ExecutionHalted(uint64 gasUsed); - /// @notice Rex5 preflight rejected the call because the parent transaction's remaining budget - /// for a resource dimension is smaller than the sandbox's known pre-frame intrinsic usage. - /// @dev Emitted as a Revert by the Rust interceptor when the preflight check fails. - /// Not used by the on-chain KeylessDeploy bytecode. - /// @param kind The resource dimension that exceeded (0=DataSize, 1=KVUpdate, 2=ComputeGas, - /// 3=StateGrowth). - /// @param limit The parent's remaining limit for that dimension. - /// @param used The sandbox's known pre-frame intrinsic usage for that dimension. - error ParentBudgetExceeded(uint8 kind, uint64 limit, uint64 used); - - /// @notice Contract creation succeeded but returned empty bytecode. - /// @param gasUsed The amount of gas used. + /// @notice The deployment's creation completed but left no code at the deploy address: its + /// init code returned empty code, or the created contract destroyed itself. + /// @param gasUsed The gas the creation spent. error EmptyCodeDeployed(uint64 gasUsed); /// @notice Contract creation succeeded but no address was returned. @@ -76,46 +68,27 @@ interface IKeylessDeploy { /// @param providedGasLimit The gas limit override provided by the caller. error GasLimitTooLow(uint64 txGasLimit, uint64 providedGasLimit); - /// @notice The remaining compute gas is insufficient to pay for the keyless deploy overhead. - /// @param limit The configured compute gas limit. - /// @param used The compute gas usage. - error InsufficientComputeGas(uint64 limit, uint64 used); - - /// @notice The init code of the keyless deployment transaction exceeds the configured - /// maximum initcode size for the current spec. - /// @dev REX5+: enforced by the Rust interceptor before the sandbox is constructed, because - /// the deposit-style sandbox bypasses op-revm's `validate_env` (which would otherwise - /// apply the same limit via revm's EIP-3860 check). + /// @notice The init code of the keyless deployment transaction exceeds the maximum initcode + /// size (EIP-3860). + /// @dev No validation of the outer transaction holds the carried init code to the limit, so + /// the deployment checks it itself. /// @param size The init code length in bytes. - /// @param max The configured maximum init code size (from `cfg().max_initcode_size()`). + /// @param max The maximum init code size. error InitCodeTooLarge(uint64 size, uint64 max); - /// @notice The recovered signer of the keyless deployment transaction has non-empty, - /// non-EIP-7702 code in parent state, so it cannot originate transactions per - /// EIP-3607. - /// @dev REX5+: enforced by the Rust interceptor because the deposit-style sandbox - /// bypasses op-revm's `validate_account_nonce_and_code` check. + /// @notice The recovered signer of the keyless deployment transaction has code other than an + /// EIP-7702 delegation, so it cannot originate transactions per EIP-3607. + /// @dev The signer is not the outer transaction's sender, so no validation of the outer + /// transaction checks it; the deployment does, unless the node disables EIP-3607. error SignerHasCode(); - /// @notice Internal sandbox failure (DB I/O, header validation, etc.). - /// @dev Selector-only: precompile return data is consensus-affecting, so the wire - /// must not pin consensus to upstream revm/op-revm `Display` impls. - error InternalError(); - - /// @notice Sandbox rejected the inner transaction as a tx-validation error — any - /// `IsTxError::is_tx_error() == true` outcome of the sandbox `transact_raw` call. - /// Behaviorally identical to `InternalError` (outer call reverts, signer is not - /// charged because `pre_execution()` never ran); a dedicated selector lets - /// relayer-side decoders distinguish this from a genuine internal failure. - /// @dev Selector-only for the same consensus-decoupling reason as `InternalError`. - error InvalidTransaction(); - - /// @notice The call was not intercepted by the EVM (called on unsupported network). + /// @notice The call was not intercepted by the EVM: it is not the transaction's own call, or + /// the network does not intercept it. error NotIntercepted(); /// @notice Deploys a contract using a pre-EIP-155 signed transaction with a custom gas limit. /// @dev The keyless deployment transaction must be a valid RLP-encoded legacy transaction: - /// - nonce: any value + /// - nonce: must be 0 /// - gasPrice: any value (typically 100 gwei for Nick's Method) /// - gasLimit: any value (must be <= gasLimitOverride) /// - to: must be empty (contract creation) @@ -125,9 +98,9 @@ interface IKeylessDeploy { /// - r: signature component /// - s: signature component /// @param keylessDeploymentTransaction The RLP-encoded pre-EIP-155 signed transaction. - /// @param gasLimitOverride The gas limit for the inner deployment transaction. - /// Must be >= the gas limit in the keyless transaction. - /// @return gasUsed The amount of gas used by the deployment transaction execution. + /// @param gasLimitOverride The gas forwarded to the deployment's creation, capped to the gas the + /// call has left. Must be >= the gas limit in the keyless transaction. + /// @return gasUsed The gas the deployment's creation spent. /// Uses uint64 to match the EVM's native gas accounting type (max ~18 exagas). /// @return deployedAddress The address of the deployed contract (zero if execution failed). /// @return errorData ABI-encoded error if execution failed, empty bytes on success. diff --git a/crates/system-contracts/contracts/interfaces/IMegaLimitControl.sol b/crates/system-contracts/contracts/interfaces/IMegaLimitControl.sol index a9548ec28..e73e46c1f 100644 --- a/crates/system-contracts/contracts/interfaces/IMegaLimitControl.sol +++ b/crates/system-contracts/contracts/interfaces/IMegaLimitControl.sol @@ -10,10 +10,10 @@ interface IMegaLimitControl { /// @notice The call carries non-zero transferred ETH for a view/control method. error NonZeroTransfer(); - /// @notice Returns remaining compute gas of the current call. - /// @dev In Rex4+, returns the caller's per-frame remaining compute gas (not the 98/100 forwarded child budget). - /// @dev For direct TX calls with no active frame, returns TX compute limit minus intrinsic compute gas. - /// @dev In pre-Rex4, this falls back to transaction-level remaining compute gas. - /// @return remaining The remaining compute gas of the current call. + /// @notice Returns the compute gas the calling frame can still spend. + /// @dev The figure is read when the call reaches the EVM, after the calling opcode charged its + /// own costs. The gas forwarded to this call comes back untouched, so it is not deducted. + /// How compute gas is metered, and what limits it, is the active spec's. + /// @return remaining The compute gas the calling frame can still spend. function remainingComputeGas() external view returns (uint64 remaining); } diff --git a/crates/system-contracts/test/KeylessDeploy.t.sol b/crates/system-contracts/test/KeylessDeploy.t.sol new file mode 100644 index 000000000..77615f3bc --- /dev/null +++ b/crates/system-contracts/test/KeylessDeploy.t.sol @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {Test} from "forge-std/Test.sol"; +import {KeylessDeploy} from "../contracts/KeylessDeploy.sol"; +import {IKeylessDeploy} from "../contracts/interfaces/IKeylessDeploy.sol"; + +/// @notice The bytecode a node deploys, run with no engine interceptor in front of it. +/// `version` is the path that returns. `keylessDeploy` reverts `NotIntercepted`. +/// The contract has no fallback, so an unknown selector reverts with empty data, +/// and a value-bearing call does too: the method is not payable, so the dispatcher +/// reverts before the body. +contract KeylessDeployTest is Test { + KeylessDeploy internal deploy; + + function setUp() public { + deploy = new KeylessDeploy(); + } + + function test_version() public view { + assertEq(deploy.version(), "1.0.0"); + } + + function test_keylessDeploy_revertsNotIntercepted() public { + vm.expectRevert(IKeylessDeploy.NotIntercepted.selector); + deploy.keylessDeploy("", 0); + } + + function test_keylessDeploy_staticcallRevertsNotIntercepted() public view { + (bool ok, bytes memory data) = address(deploy).staticcall(abi.encodeCall(IKeylessDeploy.keylessDeploy, ("", 0))); + assertFalse(ok); + assertEq(data, abi.encodeWithSelector(IKeylessDeploy.NotIntercepted.selector)); + } + + function test_keylessDeploy_withValueRevertsBeforeTheBody() public { + (bool ok, bytes memory data) = + address(deploy).call{value: 1}(abi.encodeCall(IKeylessDeploy.keylessDeploy, ("", 0))); + assertFalse(ok); + assertEq(data, ""); + } + + function test_unknownSelector_revertsWithEmptyData() public { + (bool ok, bytes memory data) = address(deploy).call(hex"deadbeef"); + assertFalse(ok); + assertEq(data, ""); + } + + function test_unknownSelector_withValueRevertsWithEmptyData() public { + (bool ok, bytes memory data) = address(deploy).call{value: 1}(hex"deadbeef"); + assertFalse(ok); + assertEq(data, ""); + } + + function test_unknownSelector_staticcallRevertsWithEmptyData() public view { + (bool ok, bytes memory data) = address(deploy).staticcall(hex"deadbeef"); + assertFalse(ok); + assertEq(data, ""); + } +} diff --git a/crates/system-contracts/test/MegaAccessControl.t.sol b/crates/system-contracts/test/MegaAccessControl.t.sol new file mode 100644 index 000000000..462bb49e4 --- /dev/null +++ b/crates/system-contracts/test/MegaAccessControl.t.sol @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {Test} from "forge-std/Test.sol"; +import {MegaAccessControl} from "../contracts/MegaAccessControl.sol"; +import {IMegaAccessControl} from "../contracts/interfaces/IMegaAccessControl.sol"; + +/// @notice The bytecode a node deploys, run with no engine interceptor in front of it. +/// Each declared control method reverts `NotIntercepted`. The payable fallback +/// reverts with the same error for an unknown selector, with or without value. +/// A value-bearing call to a declared method never reaches that fallback: the +/// method is not payable, so the dispatcher reverts with empty data. +contract MegaAccessControlTest is Test { + MegaAccessControl internal control; + + bytes internal constant UNKNOWN = hex"deadbeef"; + + function setUp() public { + control = new MegaAccessControl(); + } + + function test_version() public view { + assertEq(control.version(), "1.0.0"); + } + + function test_disableVolatileDataAccess_revertsNotIntercepted() public { + vm.expectRevert(IMegaAccessControl.NotIntercepted.selector); + control.disableVolatileDataAccess(); + } + + function test_enableVolatileDataAccess_revertsNotIntercepted() public { + vm.expectRevert(IMegaAccessControl.NotIntercepted.selector); + control.enableVolatileDataAccess(); + } + + function test_isVolatileDataAccessDisabled_revertsNotIntercepted() public { + vm.expectRevert(IMegaAccessControl.NotIntercepted.selector); + control.isVolatileDataAccessDisabled(); + } + + function test_disableVolatileDataAccess_staticcallRevertsNotIntercepted() public view { + (bool ok, bytes memory data) = + address(control).staticcall(abi.encodeCall(IMegaAccessControl.disableVolatileDataAccess, ())); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_revertsNotIntercepted() public { + (bool ok, bytes memory data) = address(control).call(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_withValueRevertsNotIntercepted() public { + (bool ok, bytes memory data) = address(control).call{value: 1}(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_staticcallRevertsNotIntercepted() public view { + (bool ok, bytes memory data) = address(control).staticcall(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_knownSelector_withValueRevertsBeforeTheBody() public { + (bool ok, bytes memory data) = + address(control).call{value: 1}(abi.encodeCall(IMegaAccessControl.disableVolatileDataAccess, ())); + assertFalse(ok); + assertEq(data, ""); + } + + function notIntercepted() internal pure returns (bytes memory) { + return abi.encodeWithSelector(IMegaAccessControl.NotIntercepted.selector); + } +} diff --git a/crates/system-contracts/test/MegaLimitControl.t.sol b/crates/system-contracts/test/MegaLimitControl.t.sol new file mode 100644 index 000000000..97cbc5038 --- /dev/null +++ b/crates/system-contracts/test/MegaLimitControl.t.sol @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {Test} from "forge-std/Test.sol"; +import {MegaLimitControl} from "../contracts/MegaLimitControl.sol"; +import {IMegaLimitControl} from "../contracts/interfaces/IMegaLimitControl.sol"; + +/// @notice The bytecode a node deploys, run with no engine interceptor in front of it. +/// `remainingComputeGas` reverts `NotIntercepted`. The payable fallback reverts +/// with the same error for an unknown selector, with or without value. A +/// value-bearing call to the declared method never reaches that fallback: the +/// method is not payable, so the dispatcher reverts with empty data. +contract MegaLimitControlTest is Test { + MegaLimitControl internal control; + + bytes internal constant UNKNOWN = hex"deadbeef"; + + function setUp() public { + control = new MegaLimitControl(); + } + + function test_version() public view { + assertEq(control.version(), "1.0.0"); + } + + function test_remainingComputeGas_revertsNotIntercepted() public { + vm.expectRevert(IMegaLimitControl.NotIntercepted.selector); + control.remainingComputeGas(); + } + + function test_remainingComputeGas_staticcallRevertsNotIntercepted() public view { + (bool ok, bytes memory data) = + address(control).staticcall(abi.encodeCall(IMegaLimitControl.remainingComputeGas, ())); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_revertsNotIntercepted() public { + (bool ok, bytes memory data) = address(control).call(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_withValueRevertsNotIntercepted() public { + (bool ok, bytes memory data) = address(control).call{value: 1}(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_unknownSelector_staticcallRevertsNotIntercepted() public view { + (bool ok, bytes memory data) = address(control).staticcall(UNKNOWN); + assertFalse(ok); + assertEq(data, notIntercepted()); + } + + function test_knownSelector_withValueRevertsBeforeTheBody() public { + (bool ok, bytes memory data) = + address(control).call{value: 1}(abi.encodeCall(IMegaLimitControl.remainingComputeGas, ())); + assertFalse(ok); + assertEq(data, ""); + } + + function notIntercepted() internal pure returns (bytes memory) { + return abi.encodeWithSelector(IMegaLimitControl.NotIntercepted.selector); + } +} diff --git a/docs/mega-evme/commands/replay.md b/docs/mega-evme/commands/replay.md index b21c9a96d..cf7682795 100644 --- a/docs/mega-evme/commands/replay.md +++ b/docs/mega-evme/commands/replay.md @@ -1,5 +1,5 @@ --- -description: Fetch and re-execute an on-chain transaction with optional overrides and tracing. +description: Fetch and re-execute an on-chain transaction, or whole blocks compared with the chain, with optional overrides and tracing. --- # replay @@ -8,10 +8,13 @@ Re-execute a historical transaction locally using an RPC endpoint or a previousl In online mode, `mega-evme` fetches the transaction, block environment, and pre-state from the RPC and re-executes locally. In offline mode (`--rpc.replay-file`), all data is served from a local fixture captured by an earlier run — no network access is required. +With `--block`, `replay` re-executes whole blocks instead and compares every receipt with the chain's; see [Replaying Whole Blocks](#replaying-whole-blocks). + ## Usage ``` mega-evme replay [OPTIONS] +mega-evme replay --block [OPTIONS] ``` ## Arguments @@ -40,7 +43,7 @@ mega-evme replay --rpc https://mainnet.megaeth.com/rpc `mega-evme replay` supports a transport-level JSON-RPC fixture mechanism that records every request/response pair to a single file and serves them back on later runs without touching the network. It is useful for pinning a reproducible replay (e.g. for regression tests, debugging sessions, or offline review) and for running `replay` in environments that cannot reach the RPC endpoint. -Unlike the generic [RPC Cache](../configuration/state-management.md#rpc-cache-and-retry), which is keyed on a small allow-list of cacheable methods and stored per chain under the platform cache directory, the cache file covers every single (non-batch) JSON-RPC call issued during the replay and lives at a user-chosen path. +Unlike the generic [RPC Cache](../configuration/state-management.md#rpc-cache-and-retry), which is keyed on a small allow-list of cacheable methods and stored per endpoint under the platform cache directory, the cache file covers every single (non-batch) JSON-RPC call issued during the replay and lives at a user-chosen path. The mechanism has two modes, selected by two mutually exclusive flags. @@ -51,6 +54,8 @@ Capture mode. Requires `--rpc`. On the first run, every JSON-RPC request and response issued while serving the replay is captured in memory and the complete envelope is written to `` atomically on clean exit. On subsequent runs the existing file is loaded, its entries are merged into the in-memory transport cache, and only missing requests are fetched from the RPC endpoint. The updated set of entries is persisted back to the same file on clean exit. +`mega-evme` reads back at most 64 MiB of cache file, so it writes no more than that: a capture that would grow the file past the limit fails with an error and leaves the file as it was. +Capture into a new file, or delete the old one. The file also embeds an external-environment snapshot — currently the set of `--bucket-capacity` values in effect — so the captured fixture is self-contained. If `--bucket-capacity` is not passed on a subsequent run, the previous envelope's values are reused; passing `--bucket-capacity` overrides them. @@ -86,6 +91,12 @@ Replay the captured transaction fully offline: mega-evme replay --rpc.replay-file ./fixtures/tx.json 0xabc123... ``` +## The Receipt of a Replayed Transaction + +`replay ` runs the transactions the block included before the target, then the target, and prints the target's receipt. +A transaction the block executor refuses is skipped, and the receipt's `transactionIndex` counts the transactions that were included. +Each log carries its transaction's index and hash, and its `logIndex` counts from the first log of the block: the logs of the earlier transactions that were included come first. + ## Self-Validating Fixture Dump `--dump-fixture ` turns a single replay into a self-validating regression fixture. @@ -112,6 +123,7 @@ It then additionally cross-checks the isolated execution against the full replay One channel stays open by construction: the isolated run's sender balance is shifted by the zeroed L1 fee, so a contract that stores a balance-derived value bakes that shifted value into `post` (and the sender's final balance in `post` likewise differs from the chain). The fixture still self-validates and reproduces gas exactly; only such balance-derived state values differ. +`--dump-fixture` is available on the legacy specs, where it is the 1.7.1 tool's dump: the fixture is re-executed by a state-test runner that prices the transaction as the chain did, and no such runner exists for Satin, so on Satin the dump is refused. `--dump-fixture` cannot be combined with transaction overrides or `--override.spec` (a forced spec would record a what-if, not the on-chain transaction), and deposit transactions are not supported. A target transaction that reads a block hash via `BLOCKHASH` is also rejected: fixtures carry no historical block hashes, so the isolated re-execution could not reproduce the values the replay observed. Block hash reads by preceding transactions in the same block do not matter — only the target transaction's reads are checked. @@ -126,43 +138,125 @@ mega-evme replay --rpc https://mainnet.megaeth.com/rpc \ # Offline: re-dump reproducibly from the capture (receipt already captured): mega-evme replay --rpc.replay-file ./cap.json --dump-fixture ./fixtures/0xabc123.json 0xabc123... -# Validate the fixture (and detect any gas/status/result drift): -state-test ./fixtures/0xabc123.json -``` - -## Throughput Benchmark - -To benchmark a replayed transaction, dump it to a fixture and time the fixture with the `state-test` runner — there is no `replay`-side benchmark flag: - -```bash -mega-evme replay --rpc --dump-fixture /tmp/tx.json 0xabc123... -state-test --bench /tmp/tx.json +# The fidelity gate checks the dump against the receipt as it is written. +# To re-run it later, use the 1.7.1 release's state-test runner: +# this repository's `state-test` runs the Osaka and Amsterdam fixtures only. ``` -`state-test --bench` reports `min` / `median` / `mean` time and throughput (Mgas/s), timing only the EVM `transact` call. A committed corpus of characteristic transactions and a base-vs-PR comparison driver build on this to track real-transaction throughput across changes; see `bench/replay/` and the `replay-bench` CI workflow. - ## Spec Auto-Detection -The EVM spec controls which opcodes, gas rules, and MegaETH-specific behaviors are active during execution. +The EVM spec controls which opcodes, gas rules, and MegaETH-specific behaviors are active during execution, and which of the two engines runs it (see [Engines](../configuration/chain-and-spec.md#engines)). `replay` auto-detects the spec from the chain ID and the block timestamp of the replayed transaction. Hardcoded hardfork configs exist for: - **Chain 6343** — MegaETH testnet v2 - **Chain 4326** — MegaETH mainnet -For any other chain, `replay` enables every hardfork up to a pinned spec at genesis — currently `Rex7`. -That pin does not follow the newest spec automatically: introducing a spec leaves unrecognized chains where they are, so a replay of history they already produced keeps its meaning. -Use `--override.spec` below to replay such a chain under a different spec. +On these chains a block runs on Satin from the timestamp the chain's schedule activates it, and on the legacy engine before it, which resolves the legacy spec from the chain's legacy schedule. +Neither chain schedules Satin yet, so every block of theirs replays on the legacy engine, exactly as the 1.7.1 tool replayed it. +To pick the engine, a transaction replay without `--override.spec` first reads the chain ID over RPC (one `eth_chainId` request, or the replay file's), and on a chain that schedules Satin also the timestamp of the block the transaction runs in; a legacy replay then makes the 1.7.1 tool's own requests. + +Any other chain is refused: the tool cannot tell which engine its blocks ran on, so the replay names it, with `--override.spec` below, or gives the chain's genesis file. +The 1.7.1 tool ran such a chain through `Rex7`, the legacy line's unstable spec, which Satin supersedes. + +Given the chain's genesis file (`--genesis `, see [A chain's genesis file](../configuration/chain-and-spec.md#a-chains-genesis-file)), the file decides instead: a block runs on Satin from the file's `satinTime`, under Satin's limits, and a block before it is refused, whether it would run on the legacy engine or `--override.spec` forces Satin on it. +A replay on another chain than the file's is refused for its chain, before any engine is picked. ### `--override.spec ` Override the auto-detected spec. Useful when you want to test how the transaction would behave under a different spec, or when replaying against a chain that isn't recognized. +`--override.spec Satin` replays the transaction as it would run on Satin: a counterfactual, on the same forked state, under the chain's schedule with Satin active from genesis, so no block of it is Satin's activation block and it checks no predeploy. ``` mega-evme replay --override.spec Rex2 +mega-evme replay --override.spec Satin +``` + +A Satin replay needs a state whose system contracts are at the versions Satin runs, which MegaETH mainnet and testnet reach at `Rex6`: Satin deploys and upgrades none of them, and the `SequencerRegistry` it reads before every transaction must be at version 2.0.0, which Rex6 left. +Replayed at its activation block, under a genesis file, Satin checks them and refuses a block whose state does not hold them, with an error naming the contract; a counterfactual checks nothing, so on an older block a transaction runs on whatever the state holds there. + +### `--override.limits ` + +Replay on Satin under other protocol limits than Satin's, a counterfactual: the fields the JSON object names replace Satin's, and every other stays. +Without it, a Satin replay runs on Satin's limits, which the spec fixes for every chain. +The object's shape, Satin's values and what is refused are in [Protocol limits](../configuration/chain-and-spec.md#protocol-limits). +It applies to both the transaction replay and the block replay; a replay that runs on the legacy engine is refused with it, and so is a legacy block of a block replay. +The limits a replay ran under are reported: a transaction replay's in its `satin.limits_override`, a block's in the `satin.limits_override` of its block record, and in text mode as `limits overridden` on the block's line. + +``` +mega-evme replay --override.spec Satin --override.limits '{"txRuntimeLimits":{"txDataSizeLimit":100000}}' +mega-evme replay --block 26400001 --rpc --block-cache ./blocks --override.spec Satin --override.limits limits.json ``` +## Replaying Whole Blocks + +`--block ` replays block `N`, and `--block ..` blocks `N` through `M`. +Each block runs on the engine its spec names: the one `--override.spec` forces, or the one the chain's schedule gives at the block's timestamp. +Every transaction of the block runs in order after the block's pre-block changes, as a node runs the block, and every receipt is compared with the chain's: status, gas used, cumulative gas used, and every log's address, topics and data; the replayed receipts root is compared with the header's. +The state the block leaves is not compared with the header's state root, so a difference that leaves every receipt as it was (a storage write that emits no log) passes. + +A block's inputs are the block with its transactions, the chain's receipts, and the state its parent left for everything the block reads, built from a `prestateTracer` trace of the block, and, for a Satin block that needs it (below), the parent block's timestamp. +A read the trace does not cover (what only a pre-block system call reads, or a path a counterfactual takes that the chain did not) is read from the parent block over RPC. + +On Satin a block in which a fork activates admits only deposits, as the [Satin upgrade](../../spec/upgrades/satin.md#1-base-layer-optimism-karst-ethereum-osaka) states: Satin itself, or an Optimism fork at or after Jovian. +The replay works this out as a node does, from the schedule the block runs under and the parent block's timestamp, and tells block execution; every transaction of such a block but its deposits is reported `refused`. +A transaction replay works it out the same way, from the parent block it forks, and refuses a non-deposit transaction of such a block with an error. +The parent's timestamp decides the answer only for a Satin block at which a fork its schedule activates after genesis is active; for such a block alone the replay fetches the parent's header over `--rpc` and keeps its timestamp in the cache. +Every other block, a legacy one or one whose schedule activates every fork it runs at genesis as the Satin counterfactual's does, replays from what the cache holds and never asks for the parent. +Satin's activation block also checks the predeploys (the six system contracts and the EIP-7997 factory), which the legacy engine never read in full, so a block cached from a legacy replay may need them over `--rpc` once. +Offline, a block that needs the parent's timestamp and whose cache entry lacks it (an entry written before the cache kept it, or by a replay that did not need it) fails rather than guess, and the error says so. +To recover, replay it once with `--rpc`: the replay fetches the timestamp and writes it to the cache, and the block then replays offline. + +| Flag | Description | +| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--block ` | The blocks to replay; conflicts with `TX_HASH`, tracing, state dump, fixture dump, transaction overrides and the RPC cache file | +| `--block-cache ` | Read a block from `DIR` when it is there; write a block fetched over `--rpc` to it, with what its replay read beyond the trace, so the next run is offline | +| `--verify` | Exit with code 2 when a block differs from the chain | +| `--rpc ` | Fetch what the cache lacks: `eth_getBlockByNumber` (of the parent too, for a Satin block that needs its timestamp), `eth_getBlockReceipts`, `debug_traceBlockByNumber` and the parent block's state | +| `--json` | Print one JSON record per transaction and per block instead of a line per block | + +The endpoint needs the `debug` namespace and historical state at the parent block: an archive node. +Without `--rpc`, a read the cache does not hold fails its block with an error naming the read. + +The cache layout is `blocks//.json.zst`, one zstd-compressed JSON file per block, and `codes//.bin`, contract code shared between blocks. + +### Records + +With `--json`, every transaction prints a record with `kind: "tx"` and every block one with `kind: "block"`: + +| Field (transaction) | Description | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| `block`, `index`, `hash` | Where the transaction is | +| `engine`, `spec` | What it ran on: `legacy` or `satin`, and the spec | +| `status` | `success`, `revert`, `halt`, or `refused` when the engine did not include it | +| `gas_used`, `cumulative_gas_used`, `logs` | As replayed | +| `reason` | Why it reverted, halted or was refused | +| `chain` | The chain's `status` (`success` or `failure`), `gas_used`, `cumulative_gas_used` and `logs` | +| `differs` | The fields that differ from the chain's: `refused`, `status`, `gas_used`, `cumulative_gas_used`, `logs` | +| `satin` | On Satin only: the [Satin output](../configuration/chain-and-spec.md#satin-output) object | + +| Field (block) | Description | +| ------------------------------------------------- | ---------------------------------------------------------------------------- | +| `block`, `hash`, `engine`, `spec`, `transactions` | The block and what it ran on | +| `refused`, `differing` | Transactions refused, and transactions that differ from the chain | +| `gas_used`, `chain_gas_used` | The block's gas, as replayed and as recorded | +| `receipts_root`, `chain_receipts_root` | The replayed receipts root and the header's | +| `matches_chain` | Every transaction and the receipts root match the chain | +| `rpc_reads` | Reads the cached pre-state did not hold, served by the parent block over RPC | +| `satin` | On Satin only: the sum of the transactions' `satin` objects | + +A block that could not be replayed prints `{ "kind": "block", "block": N, "error": "..." }` and the run goes on to the next block. + +The exit code is 0, 1 when a block could not be replayed, or 2 when `--verify` is given and a block differs from the chain. + +### The Satin counterfactual + +`--override.spec Satin` runs every block as it would run on Satin: every transaction as signed, on the state its parent block left, under Satin's protocol limits, or those `--override.limits` gives, with no building policy of a block builder applied. +A transaction the Satin engine refuses (it cannot pay for its gas, or a block budget is full) is reported `refused` and left out, and the block goes on. +A transaction signed with a gas limit sized for legacy costs can run out of gas on Satin: that is the counterfactual's answer, not a tool fault. +`--override.spec Satin` runs no block as Satin's activation block, so it checks no predeploy; what it reads beyond the legacy replay is the L1 fee overhead slot, which every Satin block reads with the rest of the L1 block info. + ## Transaction Overrides Override flags let you modify the transaction before re-executing it. @@ -196,8 +290,6 @@ See the linked pages for full details. See [Tracing Overview](../tracing/overview.md). - **Fixture dump** — Write a self-validating EEST state-test fixture via `--dump-fixture`. See [Self-Validating Fixture Dump](#self-validating-fixture-dump) above. -- **Throughput benchmark** — Dump a fixture (`--dump-fixture`) and time it with `state-test --bench`. - See [Throughput Benchmark](#throughput-benchmark) above. ## Examples @@ -234,6 +326,26 @@ mega-evme replay --rpc https://mainnet.megaeth.com/rpc --override.input 0xdeadbe mega-evme replay --rpc https://mainnet.megaeth.com/rpc --override.spec Rex2 0xabc123... ``` +**Replay a transaction on Satin** + +```bash +mega-evme replay --rpc https://mainnet.megaeth.com/rpc --override.spec Satin --json 0xabc123... +``` + +**Check a range of blocks against the chain, recording them for offline runs** + +```bash +mega-evme replay --block 26400000..26400199 \ + --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify +``` + +**Replay the recorded blocks on Satin; once a Satin run has cached them, later runs can drop `--rpc`** + +```bash +mega-evme replay --block 26400000..26400199 --block-cache ./blocks \ + --rpc https://mainnet.megaeth.com/rpc --override.spec Satin --json > satin.ndjson +``` + ## See Also - [`run`](./run.md) — Execute raw EVM bytecode locally without fetching from RPC diff --git a/docs/mega-evme/commands/run.md b/docs/mega-evme/commands/run.md index 8fd2f1a1b..0c7c59929 100644 --- a/docs/mega-evme/commands/run.md +++ b/docs/mega-evme/commands/run.md @@ -51,7 +51,7 @@ Each group is documented on its own page. | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | | Transaction | `--create`, `--gas`, `--basefee`, `--priority-fee`, `--tx-type`, `--value`, `--sender`, `--receiver`, `--nonce`, `--input`, `--inputfile`, `--source-hash`, `--mint`, `--auth`, `--access` | [Transaction Types](../transaction-types.md) | | State management | `--prestate`, `--sender.balance`, `--faucet`, `--balance`, `--storage`, `--block-hash`, `--fork`, `--fork.block`, `--rpc`, `--dump`, `--dump.output` | [State Management](../configuration/state-management.md) | -| Chain and spec | `--spec`, `--chain-id` | [Chain and Spec](../configuration/chain-and-spec.md) | +| Chain and spec | `--spec`, `--chain-id`, `--override.limits` | [Chain and Spec](../configuration/chain-and-spec.md) | | Block environment | `--block.number`, `--block.coinbase`, `--block.timestamp`, `--block.gaslimit`, `--block.basefee`, `--block.difficulty`, `--block.prevrandao`, `--block.blobexcessgas` | [Block Environment](../configuration/block-environment.md) | | SALT buckets | `--bucket-capacity` | [SALT Buckets](../configuration/salt-buckets.md) | | RPC cache / retry | `--rpc.cache-size`, `--rpc.cache-dir`, `--rpc.no-cache-file`, `--rpc.clear-cache`, `--rpc.max-retries`, `--rpc.backoff-ms`, `--rpc.rate-limit` | [RPC Cache and Retry](../configuration/state-management.md#rpc-cache-and-retry) | @@ -62,7 +62,7 @@ Each group is documented on its own page. | Option | Default | | ------------ | -------------------------------------------- | -| `--spec` | `Rex7` | +| `--spec` | `Rex6`; `Satin` under `--genesis` | | `--gas` | `10000000` | | `--sender` | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` | | `--receiver` | `0x0000000000000000000000000000000000000000` | @@ -74,17 +74,18 @@ No banners or diagnostic text are printed in JSON mode — stdout contains exact The object includes these fields: -| Field | Type | Description | -| ------------------ | ---------------- | ---------------------------------------------------------------------------- | -| `success` | `bool` | Whether execution succeeded | -| `gas_used` | `number` | Gas consumed | -| `output` | `string \| null` | Hex-encoded return data (present only on success with non-empty output) | -| `contract_address` | `string \| null` | Deployed address (present only for successful `--create` transactions) | -| `logs_count` | `number` | Number of log entries emitted | -| `revert_reason` | `string \| null` | Decoded revert reason (present only on revert) | -| `halt_reason` | `string \| null` | Halt reason (present only on halt) | -| `trace` | `object \| null` | Execution trace (when `--trace` is enabled without `--trace.output`) | -| `state` | `object \| null` | Post-execution state dump (when `--dump` is enabled without `--dump.output`) | +| Field | Type | Description | +| ------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `success` | `bool` | Whether execution succeeded | +| `gas_used` | `number` | Gas consumed | +| `output` | `string \| null` | Hex-encoded return data (present only on success with non-empty output) | +| `contract_address` | `string \| null` | Deployed address (present only for successful `--create` transactions) | +| `logs_count` | `number` | Number of log entries emitted | +| `revert_reason` | `string \| null` | Decoded revert reason (present only on revert) | +| `halt_reason` | `string \| null` | Halt reason (present only on halt) | +| `trace` | `object \| null` | Execution trace (when `--trace` is enabled without `--trace.output`) | +| `state` | `object \| null` | Post-execution state dump (when `--dump` is enabled without `--dump.output`) | +| `satin` | `object` | On `--spec Satin` only: the gas by ledger and the limits' counts, see [Satin output](../configuration/chain-and-spec.md#satin-output) | When `--trace` or `--dump` is used with an output file (`--trace.output`, `--dump.output`), data is written to that file and the corresponding JSON field is omitted. When no output file is specified, the data is inlined into the JSON object. @@ -327,13 +328,16 @@ RPC Options: Chain Options: --spec - Name of spec to use, possible values: `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6`, `Rex7` (`MiniRex1`/`MiniRex2` are alias specs executing `Equivalence`/`MiniRex` behavior) + Name of spec to use. `Satin` runs on the Satin engine; `Equivalence`, `MiniRex`, `MiniRex1`, `MiniRex2`, `Rex`, `Rex1`, `Rex2`, `Rex3`, `Rex4`, `Rex5`, `Rex6` run on the legacy engine, the released 1.7.1 (`MiniRex1`/`MiniRex2` are alias specs executing `Equivalence`/`MiniRex` behavior). Under `--genesis` the default is `Satin` - [default: Rex7] + [default: Rex6] --chain-id Chain ID [default: 6342] [aliases: --chainid] + --override.limits + Satin only: run under these protocol limits instead of the spec's, a counterfactual. A JSON object in `ProtocolLimits`' shape (camelCase, per-transaction limits under `txRuntimeLimits`), inline or in a file; the fields it names replace the spec's, every other stays. Refused when it names an unknown field or a value of the wrong type + Block Options: --block.number Block number [default: 1] --block.coinbase Block coinbase [default: 0x0...0] [aliases: --block.beneficiary] diff --git a/docs/mega-evme/commands/tx.md b/docs/mega-evme/commands/tx.md index ce45e33b9..c7f3577fa 100644 --- a/docs/mega-evme/commands/tx.md +++ b/docs/mega-evme/commands/tx.md @@ -32,7 +32,8 @@ mega-evme tx 0x02f8... --input 0xdeadbeef If `RAW_TX` is omitted, `mega-evme` builds the transaction entirely from CLI flags. The default sender is `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` and the default gas limit is `10000000`. -> **Note:** If the chain ID embedded in the raw transaction doesn't match `--chain-id`, `mega-evme` logs a warning but still proceeds. +> **Note:** On Satin, a raw transaction whose embedded chain ID is not `--chain-id` is refused (`InvalidChainId`), whatever the configuration says, and a typed one must carry a chain ID; a legacy transaction without one (pre-EIP-155) runs. +> On a legacy spec, `mega-evme` logs a warning and proceeds, as the legacy engine checks no chain ID. ## Fork Mode @@ -67,7 +68,7 @@ Each group has its own reference page with the full flag table. | ----------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | Transaction | Sender, receiver, value, gas, calldata, nonce, tx type | [Transaction Types](../transaction-types.md) | | State management | Prestate file, sender balance, faucet, storage overrides, state dump | [State Management](../configuration/state-management.md) | -| Chain / spec | Spec version, chain ID | [Chain and Spec](../configuration/chain-and-spec.md) | +| Chain / spec | Spec version, chain ID, protocol limits override | [Chain and Spec](../configuration/chain-and-spec.md) | | Block environment | Block number, timestamp, coinbase, basefee, gas limit, prevrandao | [Block Environment](../configuration/block-environment.md) | | SALT buckets | Per-bucket capacity overrides for dynamic gas pricing | [SALT Buckets](../configuration/salt-buckets.md) | | RPC cache / retry | Cache size, cache dir, retry and rate-limit | [RPC Cache and Retry](../configuration/state-management.md#rpc-cache-and-retry) | @@ -79,12 +80,24 @@ Each group has its own reference page with the full flag table. Pass `--json` to emit a single `ExecutionSummary` JSON object to stdout instead of the human-readable banner. No banners or diagnostic text are printed in JSON mode — stdout contains exactly one JSON object. -The output includes the same fields as [`run --json`](run.md#json-output), plus one additional field: +The output includes the same fields as [`run --json`](run.md#json-output) (with `satin` on `--spec Satin`), plus one additional field: | Field | Type | Description | | --------- | ---------------- | --------------------------------------------------------------------------- | | `receipt` | `object \| null` | Full transaction receipt with status, logs, gas usage, and contract address | +The receipt's `transactionHash`, and the `transactionHash` of each of its logs, is the hash of the transaction that ran: + +- A raw transaction run as it is signed prints its own hash. +- A deposit built from flags prints the hash of its encoding, which holds `--source-hash` and `--mint`, so deposits that differ in either print different hashes. +- Any other transaction built from flags prints the zero hash. + `mega-evme` signs nothing, so there is no hash for it to print. +- A raw transaction that a flag changed prints the zero hash, because the signed bytes no longer encode what ran. + +`transactionIndex` is 0 and `logIndex` counts from 0, as the transaction is alone in its block. +Changing only the type of a raw transaction (`--tx-type`) runs it as that type: the priority fee, access list and authorization list the new type cannot carry are dropped. +A flag that names one of them for a type that cannot carry it is refused. + ```bash mega-evme tx --fork --rpc https://mainnet.megaeth.com/rpc \ --sender.balance 1ether \ @@ -213,8 +226,9 @@ RPC Options: --rpc.rate-limit Retry-layer compute-units-per-second budget [default: 660] Chain Options: - --spec Spec [default: Rex7] + --spec Spec: `Satin`, or a legacy spec `Equivalence` to `Rex6` [default: Rex6; Satin under --genesis] --chain-id Chain ID [default: 6342] [aliases: --chainid] + --override.limits Satin only: protocol limits to run under instead of the chain's Block Options: --block.number Block number [default: 1] diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index b38561260..d7ae2e73a 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -4,16 +4,18 @@ description: Select which MegaETH spec version and chain ID to use. # Chain and Spec Selection -These options control which MegaETH spec and chain ID the EVM uses during execution. +These options control which MegaETH spec and chain ID the EVM uses during execution, and so which of the two engines runs it. They are available in the `run` and `tx` commands. The `replay` command auto-detects the spec from the chain ID and block timestamp (see [replay](../commands/replay.md#spec-auto-detection)). ## Options -| Flag | Default | Aliases | Description | -| ----------------- | ------- | ----------- | ------------------- | -| `--spec ` | `Rex7` | — | MegaETH spec to use | -| `--chain-id ` | `6342` | `--chainid` | Chain ID | +| Flag | Default | Aliases | Description | +| -------------------------------- | ---------- | ----------- | ------------------------------------------------------------------------------------------ | +| `--spec ` | `Rex6` | — | MegaETH spec to use; `Satin` by default under `--genesis` | +| `--chain-id ` | `6342` | `--chainid` | Chain ID | +| `--override.limits ` | the spec's | — | Satin only: protocol limits to run under instead, see [Protocol limits](#protocol-limits) | +| `--genesis ` | — | — | Satin only: the chain's genesis file, see [A chain's genesis file](#a-chains-genesis-file) | ## Available Specs @@ -21,6 +23,7 @@ Spec names are case-sensitive. | Name | Description | | ------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `Satin` | The Satin engine: EIP-8037 state gas, history gas, and the Satin resource limits; not yet activated on any chain | | `Equivalence` | Optimism Isthmus compatibility mode | | `MiniRex` | Initial MegaETH execution model with multidimensional gas | | `MiniRex1` | Alias rung: executes `Equivalence` behavior (mainnet rollback window) | @@ -32,7 +35,100 @@ Spec names are case-sensitive. | `Rex4` | Per-call-frame resource budgets, relative gas detention, storage gas stipend | | `Rex5` | SequencerRegistry, dynamic system address (Oracle v2.0.0), storage-gas-stipend separated allowance, resource-accounting fixes | | `Rex6` | Unified gas-metering order, consolidated EIP-7702 accounting, system-tx metering exemption | -| `Rex7` | No behavioral change over `Rex6` yet (**unstable**) | + +`Rex7` is refused: it was the legacy line's unstable spec, it never activated on a chain, and Satin supersedes it. + +## Engines + +Every spec belongs to exactly one engine, so the spec a command runs names the engine it runs on; there is no separate engine flag. + +| Specs | Engine | +| ----------------------- | --------------------------------------------------------------------------- | +| `Satin` | The Satin engine | +| `Equivalence` to `Rex6` | The legacy engine: the released `mega-evme` and `mega-evm` 1.7.1, linked in | + +A command on a legacy spec is handed, with its arguments unchanged, to the released 1.7.1 tool: what it prints is what 1.7.1 printed. + +### Satin output + +On Satin, every output field keeps its legacy name and meaning, and one field is added: `satin`, with what only the Satin engine counts. + +| Field | Description | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `regular_gas` | Execution gas, before the refund | +| `state_gas` | EIP-8037 state gas for the state the transaction added, net of refills | +| `history_gas` | Gas for the bytes the transaction appended to history, net of refills | +| `history_bytes` | The history bytes it appended: its body, one 40-byte record per kept write, its logs but the EIP-7708 transfer logs, its code | +| `reservoir_remaining` | The EIP-8037 reservoir left unspent, which the sender gets back | +| `floor_gas` | The EIP-7623 floor the receipt's gas used cannot fall below | +| `data_size` | Data-size bytes the transaction kept | +| `write_records` | Account and storage write records it kept: its KV count | +| `limit_exceeded` | `null`, or the limit that stopped it: `kind` (`data_size`, `compute_gas`), `limit`, `used` | +| `limits_override` | Present only under `--override.limits`: the protocol limits the run was held to, in the shape the flag takes | + +In text mode the same numbers follow the summary under `=== Satin Gas ===`. +A legacy run has no `satin` field. + +### Protocol limits + +A Satin run is held to Satin's protocol limits, which the spec fixes and no chain configures, as a node holds a Satin block of any chain. + +| Limit | Value | +| ------------------------------------------------------------------------ | ---------- | +| A transaction's data size (`txDataSizeLimit`) | 13,107,200 | +| A block's data size (`blockTxsDataLimit`) | 13,107,200 | +| Compute after a block-environment read (`blockEnvAccessComputeGasLimit`) | 20,000,000 | +| Compute after an Oracle read (`oracleAccessComputeGasLimit`) | 20,000,000 | +| A frame's data size beyond its share (`frameDataSizeLimit`) | unlimited | + +The values are provisional, as Satin is. +`run` and `tx` hold the transaction to the per-transaction limits; `replay` holds a whole block to them and to the block's budgets. + +`--override.limits` runs under other limits, a counterfactual. +It takes a JSON object in the limits' shape, inline or as the path of a file. +The fields it names replace Satin's, and every other stays. +The whole shape, at Satin's values: + +```json +{ + "txRuntimeLimits": { + "txDataSizeLimit": 13107200, + "frameDataSizeLimit": 18446744073709551615, + "blockEnvAccessComputeGasLimit": 20000000, + "oracleAccessComputeGasLimit": 20000000 + }, + "blockTxsDataLimit": 13107200 +} +``` + +`18446744073709551615` (`u64::MAX`) leaves a limit unlimited, and both compute caps at it leave a transaction undetained. +An override is refused when it names an unknown field or gives a value that is not a 64-bit integer; any other value is run, since an override is a counterfactual. +A transaction a limit stops reports it in `satin.limit_exceeded`. +Its `used` is the usage where the limit was crossed. +A limit stops the frame that crosses it: a stop of a frame below the transaction's own is caught by its caller, and the transaction then reports none, whatever its result. +A transaction whose body, with 40 bytes for each entry of its authorization list, is over `txDataSizeLimit` is not stopped but refused, as a node refuses it at validation: the command exits with the validation error, and in a replay the transaction is `refused`, or, for a deposit, included as a failed deposit. +A run under an override reports the limits it was held to in `satin.limits_override`, the merged object whole, so a counterfactual's output says what it ran under; in text mode they follow the Satin numbers as `Limits Override:`. +A command on a legacy spec is refused with `--override.limits`: the legacy engine's limits are its spec's. + +### A chain's genesis file + +A chain the tool does not know, a devnet for one, is replayed as its nodes run it only with its own Satin configuration: which blocks run Satin. +Without it a replay of such a chain is refused, unless `--override.spec` names the engine; `run` and `tx` with `--spec Satin` run a counterfactual on any chain, with Satin active from genesis. +`--genesis ` takes it from the chain's genesis file, on every command, `replay` included. +The file's `config` object (or a file that is the `config` object) is read for its `chainId` and its Satin key, `satinTime`, with the parser the node and the stateless validator read it with, so a key the node refuses is refused here too: a `satin`-prefixed key other than `satinTime`, the registry roles an earlier format named among them. +For that chain the file replaces the tool's table: a block runs Satin from the file's `satinTime`. +The file names no limit and no `SequencerRegistry` role: a Satin run under it is held to Satin's limits, as every Satin run is, and a Satin block reads the registry the chain's state holds, which the legacy forks deployed. +Satin's activation block refuses a state whose registry is missing or holds other code; a later block makes no such check and runs on the state it is given, where a missing registry names no system address. +Every command under it holds to one rule: a run the file cannot configure is refused, never run on the tool's own table. + +- A command on another chain than the file's `chainId` is refused first, whatever its spec. +- A command on a legacy spec is refused: the legacy engine runs a chain on its own table and knows nothing of the file. + `run` and `tx` run `Satin` when `--spec` is left out, the one spec the file configures. +- A Satin run before the file's `satinTime` is refused, and so is every Satin run on a file without Satin keys. + For `run` and `tx` the run's timestamp is `--block.timestamp`, `1` by default, so a file that activates Satin later needs a `--block.timestamp` at or after its `satinTime`. + For `replay` it is the block's: a block before the file's `satinTime` would run on the legacy engine and is refused, and so is one `--override.spec Satin` forces there. + +`--override.limits` still replaces the fields it names. ## Examples @@ -45,4 +141,16 @@ mega-evme tx --spec Equivalence --receiver 0x1234... # Custom chain ID mega-evme run 0x600160005260... --chain-id 1 + +# The same bytecode on Satin +mega-evme run 0x600160005260... --spec Satin + +# On Satin, with a transaction allowed to keep its body and one write record +mega-evme run 0x600160005260... --spec Satin --override.limits '{"txRuntimeLimits":{"txDataSizeLimit":350}}' + +# A devnet block, replayed on the devnet's own Satin configuration +mega-evme replay --block 12 --rpc http://localhost:8545 --genesis devnet/genesis.json + +# Bytecode on the devnet's Satin configuration, at a timestamp from its satinTime on +mega-evme run 0x600160005260... --genesis devnet/genesis.json --block.timestamp 1800000000 ``` diff --git a/docs/mega-evme/configuration/state-management.md b/docs/mega-evme/configuration/state-management.md index 86584df83..eb47a04b4 100644 --- a/docs/mega-evme/configuration/state-management.md +++ b/docs/mega-evme/configuration/state-management.md @@ -160,13 +160,13 @@ The output uses the same JSON format as prestate files, so you can feed it direc Each top-level key is a checksummed or lowercase hex address. The value is an account object with these fields: -| Field | Type | Description | -| ---------- | ------------ | --------------------------------- | -| `balance` | hex quantity | Account balance in wei | -| `nonce` | hex quantity | Transaction nonce | -| `code` | hex bytes | Deployed bytecode (`0x` for EOAs) | -| `codeHash` | hex bytes | Keccak256 hash of `code` | -| `storage` | object | Map of storage slot to value | +| Field | Type | Description | +| ---------- | ------------------- | --------------------------------------------------------------------------- | +| `balance` | hex quantity | Account balance in wei | +| `nonce` | hex quantity | Transaction nonce | +| `code` | hex bytes or `null` | Deployed bytecode (`0x` for EOAs); `null` names the code by `codeHash` only | +| `codeHash` | hex bytes | Keccak256 hash of `code` | +| `storage` | object | Map of storage slot to value | Example: @@ -201,16 +201,37 @@ All numeric values use Ethereum quantity encoding: - `balance` is in wei. - Storage keys and values are 32-byte hex strings (zero-padded to 64 hex characters). +An account with `"code": null` and a `codeHash` that is not the empty code's names its code by hash only. +A state dump writes such an account when the code was never fetched, and loads the code into the dump first whenever the database has it. +Loading a file that holds one: + +- With `--fork`, the code is fetched from the RPC endpoint at the account's address and checked against `codeHash`. + A code that does not match is an error. +- Without `--fork`, there is nothing to fetch it from, and the file is refused with an error naming the account. + Put the code in the file, or run with `--fork`. + +A `code` that is present is checked against `codeHash` and refused if they differ. + +### Overrides + +`--balance`, `--faucet` and `--storage` name one field of an account and leave the others as the prestate or the fork holds them. +They hold for an account `run` or `tx` adds code to afterwards: the `run` receiver and the system contracts. + +A Satin `run` or `tx` puts the six system contracts and the EIP-7997 factory where the state does not hold their code, as a chain that ran `Rex6` holds them: an address that already holds the code is left as it is. +Without `--fork` an address that lacks it gets the account `Rex6` left — the six at nonce 0, the `SequencerRegistry` naming `0xa887dcb9d5f39ef79272801d05abdf707cfbbd1d` in every role, the factory at nonce 1 — over any account the prestate file holds there, whose nonce and balance it replaces and whose slots it writes its own over; with `--fork` it gets the code alone, its nonce, balance and storage as the prestate or the fork holds them. +Either way the overrides above hold over the account installed, whether or not the prestate file holds one at the address. + ## RPC Cache and Retry When using fork mode, `mega-evme` caches RPC responses to avoid redundant network calls and supports configurable retry behavior for resilience against transient failures. These options take effect only when an RPC endpoint is actually contacted: on `run` and `tx` that requires `--fork` (without `--fork` they are accepted but silently ignored); on `replay` they apply to its `--rpc` fetches (an offline `--rpc.replay-file` run contacts no endpoint and does not use them). -### Per-Chain Cache Files +### Per-Endpoint Cache Files -Each chain gets its own cache file named `rpc-cache-{chain_id}.json` inside the cache directory. -The per-chain filename makes cross-chain contamination impossible by construction: a cache populated from mainnet physically cannot be loaded during a testnet run. +Each endpoint of a chain gets its own cache file named `rpc-cache-{chain_id}-{endpoint}.json`. +`{endpoint}` is a short hash of the URL with any userinfo removed, so the name does not contain the URL. +A cache populated from one endpoint cannot be loaded for another, including another endpoint of the same chain. The default cache directory is the platform cache directory: @@ -219,12 +240,12 @@ The default cache directory is the platform cache directory: ### Cache Flags -| Flag | Type | Default | Description | -| ------------------------ | ----- | ------------------ | ------------------------------------------------------------------------------------------------------------------------ | -| `--rpc.cache-size ` | `u32` | `10000` | Maximum number of items in the in-memory RPC LRU cache. Set to `0` to disable the cache layer entirely. | -| `--rpc.cache-dir ` | path | Platform cache dir | Directory for per-chain cache files. Each chain's cache is stored as `{cache_dir}/rpc-cache-{chain_id}.json`. | -| `--rpc.no-cache-file` | flag | `false` | Disable on-disk cache persistence. The in-memory LRU cache still applies — use `--rpc.cache-size 0` to disable that too. | -| `--rpc.clear-cache` | flag | `false` | Delete the current chain's cache file before loading it. Recovery path for a polluted or corrupt cache. | +| Flag | Type | Default | Description | +| ------------------------ | ----- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `--rpc.cache-size ` | `u32` | `10000` | Maximum number of items in the in-memory RPC LRU cache. Set to `0` to disable the cache layer entirely. | +| `--rpc.cache-dir ` | path | Platform cache dir | Directory for per-endpoint cache files, `{cache_dir}/rpc-cache-{chain_id}-{endpoint}.json`. `{endpoint}` hashes the URL with userinfo removed. | +| `--rpc.no-cache-file` | flag | `false` | Disable on-disk cache persistence. The in-memory LRU cache still applies — use `--rpc.cache-size 0` to disable that too. | +| `--rpc.clear-cache` | flag | `false` | Delete this endpoint's cache file before loading it. Recovery path for a polluted or corrupt cache. | ### Retry Flags diff --git a/docs/mega-evme/cookbook.md b/docs/mega-evme/cookbook.md index f554220de..d0c842fe6 100644 --- a/docs/mega-evme/cookbook.md +++ b/docs/mega-evme/cookbook.md @@ -46,6 +46,38 @@ mega-evme tx \ Compare the `gasUsed` in the output to understand the impact of spec changes on your contract. +## Compare a Call on the Legacy Engine and on Satin + +The same command runs on the legacy engine under a legacy spec and on the Satin engine under `Satin`; the Satin output adds the gas by ledger: + +```bash +# Rex6, the chain's current spec, on the legacy engine +mega-evme run 0x60aa600055 --json + +# The same bytecode on Satin: `satin.state_gas` prices the new slot, +# `satin.history_gas` the transaction's body and its write record +mega-evme run 0x60aa600055 --json --spec Satin +``` + +## Check Blocks Against the Chain, Then Replay Them on Satin + +Replay a range of blocks on the engine the chain ran them on, compare every receipt and the receipts root with the chain's, and record the blocks in a cache: + +```bash +mega-evme replay --block 26400000..26400099 \ + --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify +``` + +Replay the same blocks on Satin and keep the per-transaction records. +The first Satin run reads over RPC what Satin reads beyond the legacy replay (the L1 fee overhead slot of the L1 block contract, which its pre-block changes read with the rest of the L1 block info) and adds it to the cache; later runs of the same blocks can drop `--rpc`: + +```bash +mega-evme replay --block 26400000..26400099 --block-cache ./blocks \ + --rpc https://mainnet.megaeth.com/rpc --override.spec Satin --json > satin.ndjson +``` + +Each transaction record carries the chain's values beside the replayed ones (`chain`, `differs`) and Satin's ledgers (`satin`). + ## Deploy and Interact in Two Steps Deploy a contract, capture the state, then call it: diff --git a/docs/mega-evme/overview.md b/docs/mega-evme/overview.md index 3801406bb..05b52fedc 100644 --- a/docs/mega-evme/overview.md +++ b/docs/mega-evme/overview.md @@ -7,13 +7,21 @@ description: Execute and debug EVM bytecode locally with MegaETH's gas model, tr A command-line tool for executing and debugging EVM bytecode on MegaETH specs. Similar to go-ethereum's `evm` command, `mega-evme` provides full control over the execution environment — including MegaETH-specific features like SALT bucket configuration, multidimensional resource limits, and gas detention. +`mega-evme` carries two engines and runs every command on the one its spec names. +`Satin` runs on the Satin engine. +`Equivalence` through `Rex6`, the specs the chain has run, run on the legacy engine, the released `mega-evme` and `mega-evm` 1.7.1, so they print exactly what the 1.7.1 tool printed. +See [Chain and Spec](configuration/chain-and-spec.md#engines). + ## Installation ```bash -cargo build --release -p mega-evme +cargo build --release --manifest-path bin/mega-evme/Cargo.toml # Binary: target/release/mega-evme ``` +The tool is selected by its manifest path rather than with `-p mega-evme`, because it links the released `mega-evme` 1.7.1, a package of the same name. +`--no-default-features` builds a binary that runs Satin only, without the legacy engine. + ### Prebuilt binary Every release also attaches a prebuilt `mega-evme` (Linux x86_64, built on `ubuntu-24.04`) and a `SHA256SUMS` file to its [GitHub Release](https://github.com/megaeth-labs/mega-evm/releases). @@ -33,7 +41,7 @@ The same binary is published to the MegaETH artifact registry for internal use. | ------------------------------ | ------------------------------------------------------------------------------ | | [`run`](commands/run.md) | Execute arbitrary EVM bytecode directly | | [`tx`](commands/tx.md) | Run a transaction with full transaction context and optional RPC state forking | -| [`replay`](commands/replay.md) | Replay an existing on-chain transaction from RPC | +| [`replay`](commands/replay.md) | Replay an on-chain transaction, or whole blocks compared with the chain | ## Quick Start @@ -69,6 +77,19 @@ mega-evme replay 0xabc123... \ --trace --tracer opcode ``` +Run the same bytecode on Satin, which adds the gas by ledger to the output: + +```bash +mega-evme run 0x60016000526001601ff3 --spec Satin --json +``` + +Replay a range of blocks and check every receipt against the chain: + +```bash +mega-evme replay --block 26400000..26400009 \ + --rpc https://mainnet.megaeth.com/rpc --block-cache ./blocks --verify +``` + ## Global Options These flags apply to all commands. @@ -79,6 +100,21 @@ These flags apply to all commands. | `--log.file ` | stderr | `--log-file` | Write logs to a file instead of stderr | | `--log.no-color` | `false` | `--log-no-color` | Disable colored console output | +## Output and Exit Status + +An error is written once, as one line on stderr, and nothing is written to stdout. +The exit code is 1, whether or not stderr could take the line. +A command that prints its result to a stdout that was closed (`mega-evme … | head -0`) ends quietly with the status it had. + +Text a person reads on a terminal is filtered: escape sequences, control characters (the C0 and C1 ranges, including the one-character CSI and OSC introducers), DEL and the bidirectional overrides are dropped, and line breaks and tabs stay. +This covers error lines and a transaction's revert reason. +`--json` output is not filtered: a JSON string carries the same characters, escaped. + +The URL given to `--rpc` is written to no log line, error or cache file name with its userinfo (`user:password@`). +The userinfo is the part of the authority before its last `@`, and it is removed from a URL written without its scheme too. +A credential anywhere else in the URL, such as an API key in the path or the query, is not recognised and is printed with the URL. +The URL has to start with `http://` or `https://`. + ## Read more - **[Cookbook](cookbook.md)** — Real-world recipes and worked examples. diff --git a/docs/spec/SUMMARY.md b/docs/spec/SUMMARY.md index 69e615e9d..8cc78497c 100644 --- a/docs/spec/SUMMARY.md +++ b/docs/spec/SUMMARY.md @@ -39,7 +39,7 @@ - [Rex4](upgrades/rex4.md) - [Rex5](upgrades/rex5.md) - [Rex6](upgrades/rex6.md) -- [Rex7](upgrades/rex7.md) +- [Satin](upgrades/satin.md) ## Reference diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 226a02b9b..359d3df64 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -58,6 +58,41 @@ Because it is never part of a frame's gas, any undrawn allowance is not returned See the [Rex4](upgrades/rex4.md) and [Rex5](upgrades/rex5.md) network upgrades for details. +## State gas + +_(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) gas a transaction pays for the state it adds — a fresh storage slot, a new account, deployed code, an EIP-7702 delegation indicator — priced at MegaETH's cost per state byte and scaled by the [multiplier](#multiplier) of the [SALT bucket](#salt-bucket) the state lands in. + +Drawn from the [reservoir](#reservoir) first, then from regular gas. + +See the [Satin](upgrades/satin.md) network upgrade. + +## History gas + +_(Satin, unstable)_ Gas a transaction pays for the bytes it appends to the chain's history — its body, its logs, its [write records](#write-record) and its deployed code — at MegaETH's cost per history byte. + +Drawn from the [reservoir](#reservoir) first, then from regular gas, and never scaled by SALT. + +See the [Satin](upgrades/satin.md) network upgrade. + +## Execution cap + +_(Satin, unstable)_ The most regular gas one transaction may spend: 200,000,000. +Gas limit above the cap goes to the [reservoir](#reservoir). + +## Reservoir + +_(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) state-gas reservoir: the part of a transaction's gas limit above the [execution cap](#execution-cap), which pays [state gas](#state-gas) and [history gas](#history-gas) before they spill onto regular gas. + +## Write record + +_(Satin, unstable)_ One account or storage write a transaction keeps, 40 bytes of data size and of [history gas](#history-gas). +The KV-update count is the number of write records. + +## History allowance + +_(Satin, unstable)_ A 160-byte allowance of [history gas](#history-gas) that a value-transferring `CALL` or `CALLCODE` below the transaction's own frame grants the frame it starts, drawn only by that frame's logs. +Replaces the [storage gas stipend](#storage-gas-stipend) under Satin. + ## SALT Small Authentication Large Trie. @@ -100,6 +135,14 @@ At `multiplier > 1`, storage gas scales linearly. The multiplier is determined per-account and per-storage-slot based on which SALT bucket they reside in. +## Stateless witness + +_(Satin, unstable)_ What a validator re-executing a block is given: every account and storage slot the block's pre-block steps and included transactions load, in any frame, reverted or halted ones and those of a deposit that failed included, as the chain held it before the block — absent accounts as absent, with no slot of theirs, and zero slots of held accounts as zero — with the code of every account named, whether or not the load that named it loaded its code; the hashes `BLOCKHASH` read and the capacities of the [SALT buckets](#salt-bucket) its state charges were priced in, both exported by the block's execution; and the oracle service's answers the included transactions recorded, or the chain's slots holding them where every answer is the slot's value at its read. + +A stateless validator re-executes the block from it, and must produce the same receipts, state changes, gas ledgers and block counters. + +See the [Satin](upgrades/satin.md) network upgrade. + ## Gas detention A mechanism that caps remaining compute gas after a transaction accesses [volatile data](evm/gas-detention.md). @@ -163,7 +206,8 @@ A set of MegaETH verifiable behaviors: the complete definition of what a correct Captures the execution-layer semantics that determine node correctness. -Progression: `EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → REX7`. +Progression: `EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → SATIN`. +`SATIN` is unstable. `MINI_REX_1` and `MINI_REX_2` are [alias rungs](#alias-spec) executing `EQUIVALENCE` and `MINI_REX` behavior respectively. ## Alias Spec diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index 1fbd9623e..3c1e25f79 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -51,17 +51,17 @@ Protocol-level changes outside the verifiable execution layer (e.g., networking, ## Spec Progression ``` -EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → REX7 +EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → SATIN ``` -Each newer behavior-introducing spec includes all previous behaviors. +Each newer behavior-introducing spec includes all previous behaviors, except where a spec replaces them: SATIN restates the execution layer and replaces many of REX6's rules (see the [Satin upgrade page](upgrades/satin.md)). The alias rungs `MINI_REX_1` (behavior: `EQUIVALENCE`) and `MINI_REX_2` (behavior: `MINI_REX`) are the exception: an alias rung introduces no behavior of its own and instead executes exactly its target's earlier behavior (see [Alias Specs](#alias-specs-behavior-vs-position)). -All specs build on Optimism Isthmus (Ethereum Prague) as the base layer. -All specs through REX6 are frozen; REX7 is **unstable** and under active development. +Every spec through REX6 builds on Optimism Isthmus (Ethereum Prague) as the base layer; SATIN builds on Optimism Karst (Ethereum Osaka). +All specs through REX6 are frozen; SATIN is **unstable** and under active development. Frozen and activated are separate properties. A frozen spec's semantics no longer change, but it takes effect on a network only once that network schedules the corresponding hardfork. -REX7 is unstable and has no activation timestamp on either mainnet or testnet. +SATIN is unstable and has no activation timestamp on either mainnet or testnet. ### Backward Compatibility @@ -184,9 +184,21 @@ REX6 is frozen and scheduled on both networks; see the [upgrade overview](upgrad _See [Rex6 Network Upgrade](upgrades/rex6.md) for full details._ -### REX7 +### SATIN -REX7 is the current **unstable** spec under active development. -It introduces no behavioral change over REX6 yet; its semantics may change at any time before it is frozen. +SATIN is the current **unstable** spec under active development, scheduled by the `Satin` hardfork. +It is not scheduled on any network, and its semantics may change at any time before it is frozen. +It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather than adding to REX6's: -_See [Rex7 Network Upgrade](upgrades/rex7.md) for the current state._ +- **Two-pool gas** — [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 per-transaction execution cap, with the rest of the gas limit as a state-gas reservoir, replacing the [dual gas model](evm/dual-gas-model.md). +- **State gas** — EIP-8037's byte counts at MegaETH's cost per state byte, scaled by the [SALT bucket](glossary.md#salt-bucket) the state lands in. +- **History gas** — a price per byte on the transaction body, logs, write records and deployed code, replacing the storage gas on logs and calldata, the intrinsic storage gas, and the [storage gas stipend](glossary.md#storage-gas-stipend). +- **Resource limits** — data size per transaction, with no KV-update, state-growth or separate compute-gas limit; every limit stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, which its caller can catch. +- **[Gas detention](evm/gas-detention.md)** — enforced on the gas a frame is allowed to spend, withholding the rest inside the frame's own gas. +- **[EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs**, the `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` opcodes, and 63/64 gas forwarding. +- **[KeylessDeploy](system-contracts/keyless-deploy.md)** — the deployment runs as a native creation frame instead of a sandbox. +- **System calls** — at most 30,000,000 of a system call's gas is regular gas, and the pre-block calls run before every block; the block in which Satin activates checks that the system contracts and the EIP-7997 factory hold the code Satin runs, and Satin deploys none of them. +- **Live system address** — every transaction reads the [SequencerRegistry](system-contracts/sequencer-registry.md) itself, and a system-address transaction without the system shape is invalid. +- **Block limits** — data size is a packing budget that never refuses a deposit or a Mega System Transaction. + +_See [Satin Network Upgrade](upgrades/satin.md) for the current state._ diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 6dbbe651a..3854c1540 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -47,13 +47,22 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview | **Optimism EVM** | [op-revm v8.1.0](https://github.com/bluealloy/op-revm) | | **Alloy EVM** | [alloy-evm v0.15.0](https://github.com/alloy-rs/alloy-evm) | +
+Satin (unstable): base layer and reference implementation + +Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 (`v40.0.3-mega.4`), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 (`v20.0.0-mega.3`), and alloy-evm 0.36. +See the [Satin Network Upgrade](upgrades/satin.md). + +
+ ## Spec Progression MegaETH uses a spec system to version its verifiable behavior at each stage of the protocol's evolution. Each newer behavior-introducing spec includes all previous behaviors: ``` -EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → REX7 +EQUIVALENCE → MINI_REX → MINI_REX_1 → MINI_REX_2 → REX → REX1 → REX2 → REX3 → REX4 → REX5 → REX6 → SATIN ``` `MINI_REX_1` and `MINI_REX_2` are [alias rungs](hardfork-spec.md#alias-specs-behavior-vs-position) with no behavior of their own: they execute `EQUIVALENCE` and `MINI_REX` behavior respectively, expressing a rollback while the spec ladder keeps climbing. @@ -74,7 +83,7 @@ Contracts deployed under a given spec will continue to behave identically, regar - **REX4** — Per-call-frame resource budgets, relative gas detention, [storage gas stipend](glossary.md#storage-gas-stipend), MegaAccessControl and MegaLimitControl system contracts. - **REX5** — SequencerRegistry system contract, Oracle v2.0.0 with dynamic system address, caller-account update deduplication, storage-gas-stipend separated-allowance model, value-transfer CALL/CALLCODE parent compute-gas attribution, CREATE code-deposit compute-gas atomicity, EIP-2935/EIP-4788 pre-block gas floor with fail-closed block rejection, CREATE2 empty-initcode short-circuit, KeylessDeploy trailing-bytes rejection and empty-code log forwarding. - **REX6** — Unified per-opcode gas metering order, consolidated EIP-7702 authorization accounting, CREATE-frame accounting corrections, KeylessDeploy sandbox hardening, post-execution fee-reward accounting, system-originated transaction metering exemption, extended beneficiary detention coverage, and SequencerRegistry v2.0.0 rotation hardening. -- **REX7** — The **unstable** spec, currently open for development. No behavioral change over REX6 yet. +- **SATIN** — The **unstable** spec, not scheduled on any network. Restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka): EIP-8037 regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas, revert-class limit stops, gas detention on withheld gas, EIP-7708 transfer logs, native KeylessDeploy creation, and block limits as packing budgets. See [Hardforks and Specs](hardfork-spec.md) for full details. diff --git a/docs/spec/system-contracts/keyless-deploy.md b/docs/spec/system-contracts/keyless-deploy.md index fef43f0c1..82466abdb 100644 --- a/docs/spec/system-contracts/keyless-deploy.md +++ b/docs/spec/system-contracts/keyless-deploy.md @@ -17,6 +17,17 @@ The protocol therefore needs a mechanism that preserves the original signer and ## Specification +
+Satin (unstable): native keyless deployment + +Under Satin a node MUST NOT run the deployment in a sandbox. +A `keylessDeploy(bytes,uint256)` call that is the transaction's own frame MUST deploy the carried creation as an ordinary creation frame, a child of the call, created by the recovered signer at the deploy address. +Its checks and charges and their order, the signer's nonce, the answer and the limits are those of [Native Keyless Deployment](../upgrades/satin.md#15-native-keyless-deployment) in the Satin specification. +The sandbox execution model, the state merge, the preflight, the gas reservation and the rescue this page specifies do not apply under Satin. +The contract's address, bytecode and code hash are unchanged; its interface declares the errors [Error Classes](#error-classes) lists for Satin. + +
+ ### Address The KeylessDeploy system contract MUST exist at `KEYLESS_DEPLOY_ADDRESS`. @@ -252,6 +263,43 @@ This enforces the EIP-3607 caller-with-code rule, keeping the keyless-deploy val The KeylessDeploy interceptor is active only at call depth 0; calls from contracts are not intercepted and MUST revert through the on-chain `NotIntercepted()` path, so sandbox validation/internal-error returndata is not observable by an inner caller's `RETURNDATASIZE` or `RETURNDATACOPY` instructions. This top-level returndata can affect RPC responses, traces, relayer decoders, and exact-output replay tooling, but it is not included in transaction receipts and cannot be copied into contract storage through KeylessDeploy's intercepted path. +
+Satin (unstable): error set + +Under Satin the `IKeylessDeploy` interface declares exactly the following errors, and a node MUST NOT produce any other. + +A refusal reverts the `keylessDeploy` call: + +- `MalformedEncoding()` +- `NotContractCreation()` +- `NotPreEIP155()` +- `NonZeroTxNonce(uint64)` +- `NoEtherTransfer()` +- `InvalidSignature()` +- `InsufficientBalance()` +- `ContractAlreadyExists()` +- `SignerNonceTooHigh(uint64)` +- `GasLimitTooLow(uint64,uint64)` +- `InitCodeTooLarge(uint64,uint64)` +- `SignerHasCode()` +- `AddressMismatch()` +- `NoContractCreated()` +- `NotIntercepted()` + +An answer returns normally, with the error as `errorData`: + +- `ExecutionReverted(uint64,bytes)` +- `ExecutionHalted(uint64)` +- `EmptyCodeDeployed(uint64)` + +`ParentBudgetExceeded(uint8,uint64,uint64)`, `InsufficientComputeGas(uint64,uint64)`, `InternalError()` and `InvalidTransaction()` are removed from the interface. +They reported the sandbox's preflight, the compute-gas check of the dispatch overhead, a failed read and the sandbox's own transaction validation, none of which a native deployment has: a call that cannot pay the overhead runs out of gas, and a failed database read or SALT lookup gives the transaction no outcome. +`AddressMismatch()` and `NoContractCreated()` answer a creation reported at another address or at none, which no deployment reaches. +`NotIntercepted()` is produced only by the contract's bytecode, for a call the node does not intercept. +Removing the four errors changes neither the contract's bytecode nor its code hash: the bytecode names none of them. + +
+ ## Constants | Constant | Value | Description | diff --git a/docs/spec/upgrades/overview.md b/docs/spec/upgrades/overview.md index b79328b9e..588768154 100644 --- a/docs/spec/upgrades/overview.md +++ b/docs/spec/upgrades/overview.md @@ -1,5 +1,5 @@ --- -description: MegaETH network upgrade history — hardfork timeline from MiniRex through Rex7 with activation dates and behavioral deltas. +description: MegaETH network upgrade history — hardfork timeline from MiniRex through Satin with activation dates and behavioral deltas. --- # Overview @@ -141,7 +141,7 @@ Per-[call-frame](../glossary.md#call-frame) resource budgets, relative gas deten Unified per-opcode [gas metering order](../evm/dual-gas-model.md#gas-metering-order), consolidated EIP-7702 authorization accounting with dynamic SALT account-creation gas for net-new authorities, CREATE-frame accounting corrections, [KeylessDeploy](../system-contracts/keyless-deploy.md) sandbox hardening, post-execution fee-reward accounting, [system-originated transaction](../system-contracts/system-tx.md#system-originated-transaction-metering-exemption) metering exemption, extended beneficiary detention / volatile-access coverage, per-log [data size](../evm/resource-accounting.md#data-size) base, forwarded-gas return on compute-limit halts, value self-transfer account-info dedup, [SequencerRegistry](../system-contracts/sequencer-registry.md) v2.0.0 rotation hardening (EIP-712 possession proof + minimum rotation delay). -### [Rex7](rex7.md) +### [Satin](satin.md) {% tabs %} {% tab title="Testnet" %} @@ -153,7 +153,7 @@ Not yet scheduled {% endtabs %} Unstable; under active development. -No behavioral change over Rex6 yet. +Optimism Karst (Ethereum Osaka) base, [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas per byte appended, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs, native [KeylessDeploy](../system-contracts/keyless-deploy.md) creation, system calls on 30,000,000 regular gas plus reservoir, the live system address read by the transaction, the block's data-size limit as a packing budget, and the EIP-7997 factory. ## How to Read These Pages diff --git a/docs/spec/upgrades/rex6.md b/docs/spec/upgrades/rex6.md index 11d8772c2..610cc45d8 100644 --- a/docs/spec/upgrades/rex6.md +++ b/docs/spec/upgrades/rex6.md @@ -386,7 +386,7 @@ For the `SequencerRegistry`, pre-Rex6 blocks keep deploying and running the vers The version 2.0.0 upgrade preserves the storage layout (slots 0–12 are byte-identical; slot 13 is appended per the layout's append-only rule) and changes no behavior of `applyPendingChanges`, so validators' role resolution and the pre-block apply flow are unaffected. Rex6 is frozen: no further change to its semantics will be made. -Because no network has scheduled it yet, none of the changes on this page is live; each takes effect on a network at the block where that network activates Rex6. +It is scheduled on both networks (see the [upgrade overview](overview.md) for the activation timestamps), and each change on this page takes effect on a network at the block where that network activates Rex6. ## References diff --git a/docs/spec/upgrades/rex7.md b/docs/spec/upgrades/rex7.md deleted file mode 100644 index dcdaba798..000000000 --- a/docs/spec/upgrades/rex7.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -description: Rex7 network upgrade — the current unstable spec, open for development and carrying no behavioral change over Rex6 yet. ---- - -# Rex7 Network Upgrade - -This page is an informative summary of the Rex7 specification. -For the full normative definition, see the Rex7 spec in the mega-evm repository. - -{% hint style="warning" %} -**Unstable** — Rex7 is under active development. -Anything recorded on this page may change before Rex7 is frozen, and nothing here should be relied on. -{% endhint %} - -## Summary - -Rex7 is the spec currently open for development. -It inherits every [Rex6](rex6.md) behavior and, as of this page, changes none of them: a transaction executed under Rex7 produces the same result as the same transaction executed under Rex6. - -Rex7 exists so that new behavior has somewhere to land. -[Rex6](rex6.md) is frozen — its semantics are fixed and may no longer be modified — so any change to gas costs, opcode behavior, resource accounting, or a system contract must be introduced under Rex7. - -## What Changed - -Nothing yet. - -Each change landed under Rex7 will be recorded here as a **Previous behavior** / **New behavior** pair, in the order it is specified. - -## Developer Impact - -None. - -Rex7 is not scheduled on any network, and it is behaviorally identical to Rex6, so no contract, tool, or integration needs to do anything today. - -## Safety and Compatibility - -Rex7 changes nothing about how blocks under earlier specs are executed. -Every spec through Rex6 is frozen: a node replaying historical blocks resolves each block's spec from its timestamp and applies that spec's semantics, unaffected by Rex7's existence. - -Because Rex7 is unstable, its semantics may change in either direction until it is frozen. -Any node, tool, or test fixture pinned to Rex7 must expect its results to move. -A deployment that needs stable semantics must select a frozen spec explicitly rather than relying on the latest one. - -## References - -- [Hardforks and Specs](../hardfork-spec.md) — how specs are versioned, frozen, and activated. -- [Rex6 Network Upgrade](rex6.md) — the frozen spec Rex7 inherits from. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md new file mode 100644 index 000000000..43fb960ee --- /dev/null +++ b/docs/spec/upgrades/satin.md @@ -0,0 +1,1103 @@ +--- +description: Satin network upgrade (unstable) — MegaETH's execution rules restated on Optimism Karst (Ethereum Osaka) — EIP-8037 regular and state gas under a 200,000,000 execution cap with a state-gas reservoir, a history-gas ledger for the bytes a transaction appends, SALT-scaled state gas, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, EIP-7708 transfer logs, keyless deployment as a native creation, system calls on a split budget, the live system address read by the transaction itself, the block's data-size limit as a packing budget, and the witness a stateless validator re-executes a block from. +--- + +# Satin Network Upgrade + +This page is the Satin specification. +The concept pages under `docs/spec/` still describe Rex6; this page states, normatively, the rules Satin executes on in their place. + +{% hint style="warning" %} +**Unstable** — Satin is under active development. +Every value and rule on this page may change before Satin is frozen, and nothing here should be relied on. +{% endhint %} + +## Summary + +Satin restates MegaETH's execution rules on a new base, Optimism Karst (Ethereum Osaka), and replaces the [dual gas model](../evm/dual-gas-model.md) with the two gas pools of [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037). +A transaction's gas is split into regular gas, which pays for computation and is capped at 200,000,000 per transaction (the [execution cap](../glossary.md#execution-cap)), and a state-gas [reservoir](../glossary.md#reservoir) that holds the rest of its gas limit. +State growth is paid in [state gas](../glossary.md#state-gas) — EIP-8037's byte counts at MegaETH's own cost per state byte, scaled by the [SALT bucket](../glossary.md#salt-bucket) the state lands in — and the bytes a transaction appends to the chain's history (its body, its logs, its [write records](../glossary.md#write-record), its deployed code) are paid in a third ledger, [history gas](../glossary.md#history-gas). +Together they replace [storage gas](../glossary.md#storage-gas), the 39,000 intrinsic storage gas, the 10× multiplier on logs and calldata, and the 23,000-gas [storage gas stipend](../glossary.md#storage-gas-stipend). + +The per-transaction resource limits keep data size and drop the KV-update, state-growth and compute-gas limits: write records are bounded by the data size they weigh and priced in history gas, state growth is priced in state gas, and compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md). +Every limit — data size and detention's compute limit — now stops the frame that crosses it with a revert carrying `MegaLimitExceeded(kind, limit)` instead of a halt: the frame's caller can catch the stop and carry on within what the limits leave, and a transaction whose own frame is stopped pays only for what ran. +Detention holds each frame's spendable regular gas inside the frame's own gas, so a transaction that read volatile data runs exactly as it would have without the read until a regular charge needs the gas it is not allowed to spend. + +Satin also brings EIP-7708 transfer logs, deploys a `keylessDeploy` transaction as a native creation instead of in a sandbox, runs system calls on at most 30,000,000 of regular gas with the rest as reservoir, has a system-address transaction read the live system address itself, and makes the block's data-size limit, its one block-level execution limit, a packing budget that never refuses a deposit or a Mega System Transaction. + +Satin follows [Rex6](rex6.md) on the spec ladder, so every **Previous behavior** below is Rex6's. +Satin does not add to the Rex6 rules one by one: it restates the execution layer, and a Rex6 rule this page does not carry over does not apply under Satin. + +The changes, in the order this page records them: + +1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 transaction gas cap. +2. **Precompiles.** Karst's set, with KZG point evaluation still at 100,000. +3. **Contract size limits.** 512 KiB of code and 1 MiB of initcode. +4. **Two-pool gas.** EIP-8037 regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. +5. **Gas schedule and intrinsic gas.** Amsterdam's schedule, EIP-8038's state-access prices included, and EIP-2780 intrinsic cost. +6. **State gas and SALT pricing.** `entry × multiplier` on EIP-8037's byte counts, replacing `base × (multiplier − 1)`. +7. **History gas.** A price per byte on everything a transaction appends to history. +8. **History allowance.** A 160-byte allowance for value calls, replacing the 23,000-gas storage gas stipend. +9. **Gas forwarding.** The standard 63/64 rule, replacing 98/100. +10. **Resource limits.** Data size over a byte table and write records, and no KV-update, state-growth or compute-gas limit. +11. **The revert-class stop.** Every limit stops the frame that crosses it with a revert, which its caller can catch. +12. **Gas detention on withheld gas.** +13. **Volatile-data access control and `remainingComputeGas()`.** +14. **EIP-7708 transfer logs.** +15. **Native keyless deployment.** +16. **Oracle storage reads and hints.** +17. **The live system address.** +18. **System calls and pre-block calls.** +19. **The protocol's own transactions.** +20. **Block limits.** +21. **Transaction and block refusals.** +22. **The stateless witness.** What a validator re-executing a block must be given, and what the engine exports for it. + +## What Changed + +### 1. Base Layer: Optimism Karst (Ethereum Osaka) + +#### Previous behavior + +- Every spec through Rex6 builds on Optimism Isthmus (Ethereum Prague); every standard EVM, transaction and block rule the specification does not override is Isthmus's. +- The Osaka opcode `CLZ` and the Amsterdam opcodes `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` are undefined. + +#### New behavior + +- Satin builds on Optimism Karst, whose Ethereum base is Osaka. + Every standard EVM, transaction and block rule this page does not override MUST be Karst's, including the Optimism changes of Jovian and Karst and the Ethereum changes of Osaka (for example `CLZ`, [EIP-7939](https://eips.ethereum.org/EIPS/eip-7939)). +- The per-transaction gas limit cap of [EIP-7825](https://eips.ethereum.org/EIPS/eip-7825) MUST NOT be applied. + The execution cap of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) bounds a transaction's regular gas instead, and a transaction's gas limit is bounded by the block's gas limit; a block builder MAY refuse a larger declared gas limit as building policy, which a node validating a block does not apply (see [Block Limits](#20-block-limits)). +- A node MUST enable four opcodes that Osaka does not have: `DUPN` (`0xE6`), `SWAPN` (`0xE7`) and `EXCHANGE` (`0xE8`) from [EIP-8024](https://eips.ethereum.org/EIPS/eip-8024), and `SLOTNUM` (`0x4B`) from [EIP-7843](https://eips.ethereum.org/EIPS/eip-7843). + `SLOTNUM` MUST push the block's slot number, an unsigned 64-bit integer the node supplies with the block. + The slot number has no absent value: a block for which the node supplies no other number runs with slot number zero, which `SLOTNUM` pushes like any other. +- The Karst block rules apply to MegaETH blocks: + - A block in which Satin activates, or in which an Optimism fork at or after Jovian in the Optimism fork order activates, MUST contain only deposit transactions; a non-deposit transaction in it makes the block invalid. + A fork activates in a block when it is active at the block's timestamp and not at the parent block's, as the chain configuration schedules it; a fork the configuration does not schedule never activates. + The rule covers Jovian, Karst and every later Optimism fork the chain configuration schedules. + A Mega System Transaction is a legacy transaction, so it is refused in such a block too, and the Satin activation block owes none: nothing writes the [Oracle](#16-oracle-storage-reads-and-hints) in it, because the only transactions the block admits are deposits, and a deposit from the system address is a failed deposit that runs no call (see [The Live System Address](#17-the-live-system-address)). + - Each non-deposit transaction's data-availability footprint — its compressed size times the footprint gas scalar held by the L1 block contract — MUST accumulate against the block's gas limit, and the block MUST report the sum as its blob gas used. + A transaction whose footprint does not fit in what the block has left MUST NOT be included. + With no scalar in state the scalar is zero, and the rule costs nothing. + - Every non-deposit transaction MUST be priced against the L1 block information that the block's own L1 attributes deposit wrote. + The information MUST be what the contract holds on the state the transactions before the block's first non-deposit transaction other than a Mega System Transaction left, and MUST hold for every later transaction of the block; the footprint gas scalar MUST be read from the contract again for each non-deposit transaction, a Mega System Transaction included. +- Satin starts from the L1 block contract Rex6 left: OP's L1Block 1.6.0 (Isthmus), whose data-availability footprint gas scalar and operator fee scalars are zero. + So at Satin's activation the Karst data-availability footprint limit costs nothing and the Jovian operator fee is zero; both take effect only once the L1 block contract is upgraded and the scalars are set, which Satin itself does not do. + +### 2. Precompiles + +#### Previous behavior + +- The precompile set is Isthmus's with two MegaETH overrides: KZG point evaluation (`0x0A`) at a fixed 100,000 gas, and ModExp (`0x05`) on the Osaka schedule ([EIP-7823](https://eips.ethereum.org/EIPS/eip-7823) and [EIP-7883](https://eips.ethereum.org/EIPS/eip-7883)). +- `P256VERIFY` (`0x100`) costs 3,450 gas. +- Input size limits: BN254 pairing (`0x08`) 112,687 bytes; BLS12-381 G1 MSM (`0x0C`) 513,760 bytes, G2 MSM (`0x0E`) 488,448 bytes, pairing (`0x0F`) 235,008 bytes. + +#### New behavior + +The precompile set MUST be Karst's, with KZG point evaluation at MegaETH's price: + +| Precompile | Address | Satin | +| ---------------------- | ------- | --------------------------------------------------------------- | +| KZG point evaluation | `0x0A` | Fixed 100,000 gas (unchanged) | +| ModExp | `0x05` | Osaka schedule (unchanged) | +| `P256VERIFY` | `0x100` | 6,900 gas ([EIP-7951](https://eips.ethereum.org/EIPS/eip-7951)) | +| BN254 pairing | `0x08` | Input of at most 57,600 bytes | +| BLS12-381 G1 MSM | `0x0C` | Input of at most 288,960 bytes | +| BLS12-381 G2 MSM | `0x0E` | Input of at most 278,784 bytes | +| BLS12-381 pairing | `0x0F` | Input of at most 156,672 bytes | +| Every other precompile | Any | As Karst defines it | + +An input over a size limit fails the call before any gas check, as the Optimism specification of the limit has it, a call forwarded no gas included; like every precompile call that fails, it consumes all the gas forwarded to it. +KZG point evaluation keeps its Rex6 semantics: a call given less than 100,000 gas fails with an out-of-gas before any verification runs, and a successful call is charged exactly 100,000. +A KZG call given at least 100,000 gas that fails otherwise — an input of the wrong length, a versioned hash that does not match the commitment, a proof that does not verify — consumes all the gas forwarded to it, not 100,000. + +### 3. Contract Size Limits + +#### Previous behavior + +- Deployed code of at most 524,288 bytes; initcode of at most 548,864 bytes (the code limit plus 24,576). + +#### New behavior + +- Deployed code MUST be at most `MAX_CONTRACT_SIZE` = 524,288 bytes. +- Initcode MUST be at most `MAX_INITCODE_SIZE` = 1,048,576 bytes, twice the code limit, the ratio [EIP-3860](https://eips.ethereum.org/EIPS/eip-3860) sets between the two. +- The creation opcodes MUST make their checks and charges in this order: the static context; the value, offset and size operands, and the size's range; the initcode size; EIP-3860's initcode cost; the offset's range and the memory the initcode is read from (neither checked for empty initcode); for `CREATE2`, the salt operand, then the 12,000 and the hashing cost of the initcode, and for `CREATE` the 12,000. + Satin adds no charge ahead of these. + So a creation in a static frame fails before its operands are read, and a `CREATE2` short of its salt pays the initcode cost and the memory first: the halt consumes the frame's gas either way, but under [gas detention](#12-gas-detention-on-withheld-gas) those charges can be the crossing, which stops the frame with a revert where the stack underflow would have halted it. + +### 4. Two-Pool Gas (EIP-8037) Replaces the Dual Gas Model + +#### Previous behavior + +- A transaction's gas is one pool; `total_gas_used = compute_gas_used + storage_gas_used`. +- Compute gas is separately limited to 200,000,000 per transaction. + Crossed during execution, the limit reverts the frame that crossed it, the transaction's own frame included; crossed by usage recorded outside every frame's budget — the pre-frame intrinsic compute, or the limit a read of volatile data lowers — it halts the transaction. +- Storage gas is charged out of the same pool for `SSTORE` of a fresh slot, account creation and contract creation (`base × (multiplier − 1)`), code deposit (10,000 per byte), logs (3,750 per topic and 80 per data byte) and calldata (40 per zero byte and 160 per non-zero byte, floors 100 and 400), plus 39,000 intrinsic storage gas per transaction. + +#### New behavior + +A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amsterdam applies it, with the parameters below. + +- **The execution cap.** + `EXECUTION_CAP` = 200,000,000. + At the start of execution: + + ``` + regular_budget = min(gas_limit, EXECUTION_CAP) − intrinsic_regular_gas + reservoir = max(0, gas_limit − EXECUTION_CAP) + ``` + + - `gas_limit` — the transaction's gas limit. + - `intrinsic_regular_gas` — the regular part of the transaction's intrinsic gas (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + + The intrinsic state gas — under Satin, the history gas of the transaction's body (see [History Gas](#7-history-gas)) — MUST be taken from the reservoir first, and only its excess from the regular budget. + +- **Three kinds of charge.** + A regular charge (every inherited opcode and intrinsic cost) MUST draw only the regular budget. + A state charge (see [State Gas](#6-state-gas-and-salt-pricing)) and a history charge (see [History Gas](#7-history-gas)) MUST draw the reservoir first and spill onto the regular budget only past it. + `GAS` MUST return the regular budget the frame has left, not the reservoir. +- **Frames.** + A call or creation MUST forward regular gas as the inherited rules have it (see [Gas Forwarding](#9-gas-forwarding)), and the child MUST inherit the caller's whole reservoir; what the child leaves of the reservoir returns to the caller. + When a frame reverts or halts, the state and history gas it charged MUST be given back: the part the reservoir paid returns to the reservoir, and the part that spilled returns to the frame's regular budget. + A revert then returns the frame's unspent regular gas to its caller; an exceptional halt consumes it, the returned spill included. +- **The transaction.** + When the transaction ends, the reservoir left MUST return to the sender, and so MUST the unspent regular gas unless the transaction's own frame halted; this holds when the transaction reverts or is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). + The receipt's gas used is what the transaction spent from both pools — regular, state and history gas together — after the inherited refund and floor rules. + When that spend less the refund is below the floor, the gas used MUST be the floor and no refund is made: the sender gets back its gas limit less the floor, the floor's excess over the spend coming out of the unspent regular gas and the reservoir alike. +- **Three ledgers.** + A node MUST split a transaction's spend into three ledgers, all paid from the pools above: + - _regular gas_ — `total − state − history`; + - _state gas_ — the state charges it kept; + - _history gas_ — the history charges it kept, the body included. + + State or history gas that spilled onto the regular budget stays on its own ledger. + The [EIP-7623](https://eips.ethereum.org/EIPS/eip-7623) floor, as [EIP-7976](https://eips.ethereum.org/EIPS/eip-7976) and [EIP-7981](https://eips.ethereum.org/EIPS/eip-7981) amend it, MUST be computed and validated as Amsterdam computes it; the figure a block counts on its execution ledger is `max(regular, floor)`, with history gas taken out of the regular ledger before the floor applies. + +- **Validation.** + A node MUST reject a transaction, before it is included: + - whose body, with `WRITE_RECORD_SIZE` bytes for each entry of its authorization list, exceeds the transaction's data-size limit (see [Resource Limits](#10-resource-limits)), unless it is system-originated (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)); every entry counts, whether its authorization will apply or not; + - whose gas limit is below its intrinsic regular gas plus the history gas of its body (`CallGasCostMoreThanGasLimit`); + - whose floor exceeds its gas limit (`GasFloorMoreThanGasLimit`); + - whose gas limit exceeds `EXECUTION_CAP` while its intrinsic regular gas or its floor exceeds `EXECUTION_CAP` (`GasFloorMoreThanGasLimit`). + + The checks MUST be made in this order, and the first that fails names the error: the body and its authorization records against the data-size limit, before any gas is looked at (an invalid transaction whose reason is that the body and authorization records exceed the transaction data-size limit); the gas limit against the intrinsic regular gas alone (`CallGasCostMoreThanGasLimit`, carrying the intrinsic regular gas); the floor against the gas limit (`GasFloorMoreThanGasLimit`); the execution cap (`GasFloorMoreThanGasLimit`, carrying the larger of the intrinsic regular gas and the floor, against `EXECUTION_CAP`); and last the gas limit against the intrinsic regular gas plus the history gas of the body (`CallGasCostMoreThanGasLimit`, carrying that sum). + So a gas limit that covers the intrinsic regular gas but neither the floor nor the body's history gas is refused for the floor. + A deposit that fails any of these checks is included as a failed deposit instead (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + The body and the records of the authorities a transaction applies are all it counts as data size before its first frame, so a transaction that passes validation cannot cross the data-size limit before its first frame. + At the spec's numbers the data-size check refuses no transaction the gas checks admit: the floor holds calldata and access list together to at most 3,124,812 bytes, and the execution cap holds the authorization list to at most 25,587 entries, so a body with its authorization records is at most 6,732,889 bytes, about half the 13,107,200-byte limit. + +Satin has no separate compute-gas limit: compute is regular gas, bounded by the execution cap and, after a read of volatile data, by [gas detention](#12-gas-detention-on-withheld-gas). + +### 5. Gas Schedule and Intrinsic Gas + +#### Previous behavior + +- The gas schedule is Prague's. +- Intrinsic gas is 21,000 (plus 32,000 for a creation) plus calldata, access-list and EIP-7702 costs, plus 39,000 intrinsic storage gas and the storage gas of the calldata. +- An EIP-7702 authorization costs 25,000 intrinsic gas, with 12,500 refunded for an authority that already exists. +- Code deposit costs 200 gas per byte, plus 10,000 storage gas per byte. + +#### New behavior + +The gas schedule MUST be Amsterdam's — including [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038)'s state-access prices, [EIP-2780](https://eips.ethereum.org/EIPS/eip-2780)'s decomposition of the intrinsic cost, EIP-7976's calldata floor and EIP-7981's access-list floor — with two changes: + +- the EIP-8037 state-gas entries MUST be rebuilt at MegaETH's cost per state byte (see [State Gas](#6-state-gas-and-salt-pricing)); +- the history gas of deposited code MUST be the cost of one history byte (see [History Gas](#7-history-gas)); Amsterdam prices it at zero. + +Every other entry MUST be Amsterdam's: every regular-gas entry, the regular code-deposit cost (zero), the EIP-7702 entries, and the entries Amsterdam introduced for EIP-8037, EIP-2780, EIP-7976 and EIP-7981. +So creating state is split between the two dimensions as Amsterdam splits it: the regular gas pays for the access and the write EIP-8038 prices, and the new state itself is paid in state gas alone. +A value call that creates its recipient pays no regular gas for the new account beyond the account write its value transfer carries, a creation pays 12,000 of regular gas for its access, a fresh slot pays the 10,000 of a storage write, and a `SELFDESTRUCT` that moves a balance to a new account pays an account write of 9,000. +The static gas every opcode pays before its dynamic cost MUST be Amsterdam's too: `EXTCODESIZE` and `EXTCODECOPY` pay EIP-8038's base of two warm accesses, one for the account and one for its code, and every other opcode's static gas is Osaka's and Amsterdam's alike. + +Regular-gas entries that EIP-8038 or EIP-8037 reprice, and the other entries that differ from Osaka: + +| Entry | Osaka | Satin | +| ---------------------------------------------------- | ------ | ------- | +| Warm storage read | 100 | 100 | +| Cold account access, additional | 2,500 | 2,900 | +| Cold storage access of an `SLOAD`, additional | 2,000 | 2,000 | +| Cold storage access of an `SSTORE` | 2,100 | 2,000 | +| Value transfer of a call, with its 2,300 stipend | 9,000 | 11,300 | +| New account of a call | 25,000 | 0 | +| New account of `SELFDESTRUCT` | 25,000 | 9,000 | +| `SSTORE` static cost | 100 | 100 | +| `SSTORE` of a fresh slot, before the load cost | 19,900 | 10,000 | +| `SSTORE` reset, before the cold load | 2,800 | 10,000 | +| `SSTORE` refund of a restored fresh slot | 19,900 | 10,000 | +| `SSTORE` refund of a restored reset | 2,800 | 10,000 | +| `SSTORE` refund of a cleared slot | 4,800 | 11,616 | +| `CREATE` and `CREATE2` | 32,000 | 12,000 | +| `EXTCODESIZE` and `EXTCODECOPY`, static gas | 100 | 200 | +| Creation transaction (unused under EIP-2780) | 32,000 | 12,000 | +| Access-list address, with its 20 bytes at 64 gas | 2,400 | 4,180 | +| Access-list storage key, with its 32 bytes at 64 gas | 1,900 | 4,048 | +| Code deposit, regular gas per byte | 200 | 0 | +| Code deposit, state gas per byte | 0 | 1,530 | +| Code deposit, history gas per byte | 0 | 88 | +| Fresh-slot `SSTORE`, state gas | 0 | 97,920 | +| New account, state gas | 0 | 183,600 | +| Created account, state gas | 0 | 183,600 | +| EIP-7702 delegation indicator, state gas | 0 | 35,190 | +| EIP-7702 authorization, intrinsic regular gas | 25,000 | 7,816 | +| EIP-7702 refund for an existing authority | 12,500 | 0 | +| Account write (EIP-2780) | 0 | 9,000 | +| Creation access (EIP-2780) | 0 | 12,000 | +| Floor cost per token | 10 | 16 | +| Floor base | 21,000 | 12,000 | +| Floor tokens per zero calldata byte | 1 | 4 | +| Floor tokens per access-list byte | 0 | 4 | + +The warm read, the `SLOAD` cold surcharge and the `SSTORE` static cost are EIP-8038's own values and Osaka's alike. +EIP-8038 folds the warm base into a cold slot's access, so a cold `SSTORE` pays 2,100 for it with its static cost, as a cold `SLOAD` does. + +Under EIP-2780 the floor's base is not the 12,000 entry: it MUST be the transaction's own decomposed base (below) without its calldata, access-list, authorization and initcode costs, which is 12,000 for a transfer to the sender itself, 15,000 for a call to another account without value, 21,000 for one with value, and 24,000 for a creation. +The floor is that base plus 64 gas per calldata byte, zero or non-zero, a creation's initcode included, and 64 gas per access-list byte, 20 bytes for an address and 32 for a storage key. + +The EIP-2780 intrinsic regular gas of a transaction MUST be `TX_BASE_COST` = 12,000, plus, for a call to another account, 3,000 for the recipient's access and 6,000 more when it carries value; plus, for a creation, 12,000 and EIP-3860's initcode cost; plus the calldata, access-list and per-authorization costs. +A transfer to the sender itself pays the base alone. +The 7,816 per authorization MUST be charged as every intrinsic entry is, by the transaction's validation; an authority that already exists is refunded nothing when its authorization is applied. +The state-dependent parts — a recipient or created account that does not exist, an authority that does not exist, a delegation indicator, an authority's first write — MUST be charged at the start of execution, as EIP-2780 and EIP-8037 specify, with every state charge priced as [State Gas](#6-state-gas-and-salt-pricing) says. +A deposit-like transaction whose caller account does not exist MUST be charged the new-account state gas for it exactly once. +A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an authorization's charges, the history of the write records made outside a frame (see [History Gas](#7-history-gas)), or a charge for the first frame's start — MUST run out of gas without running a frame. +Everything applied before the first frame, other than what validation did to the sender's account (its fee and a call's nonce) and the account a deposit-like transaction creates for its caller, is then taken back: the applied EIP-7702 authorizations with their nonce and delegation writes, the sender's own authorization included, their state gas and their write records. +The intrinsic gas and the body's history gas stay charged, the rest of the regular budget is consumed, and what is left of the reservoir returns to the sender; the sender of a creation keeps the nonce bump the creation would have made. +A deposit that runs out of gas this way is instead a failed deposit, which uses its whole gas limit, reservoir included (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + +Deposited code MUST be charged, once the creation's code passed its checks and in this order: the regular per-byte cost (zero), the hashing cost of the code at 6 gas per 32-byte word, the state gas of the code, and its history gas. +A creation that cannot pay any of the four runs out of gas and leaves no code. + +A node MUST charge account access to the addresses the inherited rules treat as warm from the start of a transaction — precompiles, the block beneficiary and access-list addresses listed without storage keys — as warm, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) has it: Rex6's cold charge on the first `CALL`-family or `SELFDESTRUCT`-beneficiary touch of such an address does not apply. +The `SequencerRegistry`'s account and its `_currentSystemAddress` slot MUST be warm from the start of every transaction as well, the slot as an access-list storage key is: validation reads both for every transaction (see [The Live System Address](#17-the-live-system-address)). + +### 6. State Gas and SALT Pricing + +#### Previous behavior + +- Dynamic storage gas is `base × (multiplier − 1)` with bases 20,000 (fresh slot), 25,000 (new account) and 32,000 (contract creation), where `multiplier = bucket_capacity / MIN_BUCKET_SIZE`. +- A write into a minimum-size bucket pays no storage gas. + +#### New behavior + +Every EIP-8037 state charge MUST be `entry × m`: + +- `entry` — the schedule's state-gas entry: EIP-8037's byte count of the state times `COST_PER_STATE_BYTE` = 1,530. +- `m` — the multiplier of the [SALT bucket](../glossary.md#salt-bucket) the state lands in, `floor(bucket_capacity / MIN_BUCKET_SIZE)` with `MIN_BUCKET_SIZE` = 256. + +| State | Bytes | `entry` at `m = 1` | Bucket | +| --------------------------------------- | ----- | ------------------ | --------------------- | +| Fresh storage slot (`SSTORE` 0 → non-0) | 64 | 97,920 | The slot's | +| New account | 120 | 183,600 | The account's | +| Created contract account | 120 | 183,600 | The created account's | +| Deployed code, per byte | 1 | 1,530 | The created account's | +| EIP-7702 delegation indicator | 23 | 35,190 | The authority's | + +- A state charge MUST be made where the state is added: a fresh slot by the `SSTORE` that fills it; a new account by the `CALL` that moves value to it, by a `SELFDESTRUCT` that moves a balance to it, by the transaction whose value creates it, and by an applied EIP-7702 authorization that creates it; a created account by `CREATE`, `CREATE2` or a creation transaction. +- `m` scales state gas and nothing else: regular gas never scales. +- A bucket's multiplier MUST be read at most once per transaction: every later charge, and every give-back, in that bucket MUST use the same `m`, so a give-back cancels its charge exactly. +- A bucket capacity below `MIN_BUCKET_SIZE`, or a capacity the node cannot read, is a fault of the node, including for a deposit: the transaction MUST NOT be priced at any multiplier or settled, and the node MUST report an internal error (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). +- A slot restored to its original zero value in the same transaction MUST give its state gas back at the price it was charged, as EIP-8037 specifies: first to the frame's regular gas, up to what the frame's state charges spilled onto it, and the rest to the reservoir. +- The protocol's own transactions MUST be priced at `m = 1` whatever their buckets hold (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). + A deposit that is not system-originated is not one of them and MUST be priced by bucket, although it pays no history gas (see [History Gas](#7-history-gas)). + +At `m = 1` every state charge is the schedule's own number, so, unlike Rex6, a fresh slot or account in a minimum-size bucket is not free: it pays its state gas. + +### 7. History Gas + +#### Previous behavior + +- There is no history ledger. + Logs pay 10× their standard cost as storage gas, calldata pays storage gas per byte, every transaction pays 39,000 intrinsic storage gas, and deployed code pays 10,000 storage gas per byte. + +#### New behavior + +History gas prices the bytes a transaction appends to the chain's history, at `COST_PER_HISTORY_BYTE` = 88 gas per byte. +It MUST NOT be scaled by SALT. +The bytes MUST be those of the byte table below, which is also the table the data-size limit counts (see [Resource Limits](#10-resource-limits)), so a record's history bytes are its own data size. + +| Item | Bytes | +| ----------------------------------------- | ------------------------------------------------------ | +| Transaction body | `TX_BODY_SIZE` = 310 | +| Calldata (a creation's initcode included) | 1 per byte, zero or non-zero | +| Access-list address | `ACCESS_LIST_ADDRESS_SIZE` = 20 | +| Access-list storage key | `ACCESS_LIST_SLOT_SIZE` = 32 | +| EIP-7702 authorization | `AUTHORIZATION_SIZE` = 101 | +| Log | `LOG_BASE_SIZE` = 32, plus 32 per topic, plus its data | +| Write record | `WRITE_RECORD_SIZE` = 40 | +| Deployed code | 1 per byte | + +- `TX_BODY_SIZE` is `TX_BASE_SIZE` = 110 for the envelope plus `TX_FIXED_WRITE_RECORDS` = 5 write records: the sender's account and the settlement writes of the four accounts a transaction's fees are credited to (the block beneficiary, the L1 fee vault, the base fee vault and the operator fee vault). + It is an upper bound, charged whether or not every fee account is written; it covers every account write to the sender (a storage write to the sender's slots is a record of its own), and of the fee accounts only the fee credits: a write execution makes to a fee account that is not the sender is a record of its own (see [Resource Limits](#10-resource-limits)). +- A write record is one account or storage write the transaction keeps (see [Resource Limits](#10-resource-limits)). + +When each charge is made: + +- The body — `TX_BODY_SIZE`, the calldata, the access list and the authorizations — MUST be charged before execution, as intrinsic state gas: the reservoir pays it first and its excess the regular budget, and it is not part of the intrinsic regular gas the execution cap is validated against. + A gas limit that cannot cover it MUST make the transaction invalid (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + The body's history gas MUST NOT be reported on the state ledger. +- The records of the applied EIP-7702 authorities, and the record the transaction's own frame makes (its value's recipient or its created account), MUST be charged before the first frame. + The authorities' records are the transaction's own and MUST be kept when the first frame fails or is stopped; the first frame's record is that frame's, and comes back with it. + A transaction that runs out of gas before its first frame keeps neither: the out-of-gas takes the authorizations back with their records (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). +- A log, a storage write's record and the record of a `SELFDESTRUCT`'s beneficiary MUST be charged by the opcode, once it completed. + An opcode that fails after its write was observed — an `SSTORE` or a `SELFDESTRUCT` that cannot pay the gas it charges after its load — keeps nothing and is charged no history; a `LOG` observes its write after every charge of the inherited opcode, so only the limits and its history charge, below, can fail it after its write was observed. +- A `CALL`, `CALLCODE`, `CREATE` or `CREATE2` MUST charge its own frame for the records the frame it starts makes (a value transfer's sender and recipient; a creation's creator nonce and created account), after the gas it forwards is computed, so the forward is not reduced by them. + A caller that cannot pay MUST halt with out-of-gas, and the frame MUST NOT start. + A value `CALL` to an empty account (EIP-161) MUST charge its caller in this order: its regular gas — the access's static 100, memory, the value transfer, then the cold surcharge with the new account's regular gas, which is zero — then the new account's state gas, reservoir first, then the 63/64 forward of the regular gas left, then the history of the start's records; a state charge that spills onto the regular budget so shrinks the forward, and the records' history does not. + A `CREATE` or `CREATE2` likewise charges the created account's state gas, when the account at the created address is empty, before it computes the forward. +- Deployed code MUST be charged at the deposit (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). +- What a frame does not keep — a failed frame's records and logs, a slot written back to its original value — MUST be given back at the price it was charged, to whoever paid it. + +A record an opcode commits — a storage write, a log, a `SELFDESTRUCT`'s beneficiary — MUST be checked against the limits before its history is charged, so a record a limit refuses is not charged. +A frame that cannot pay that history charge MUST halt with out-of-gas, keeping neither the record nor its bytes. +At a frame start the order is the reverse: the calling opcode pays for the records before the frame starts and they are counted, so a caller that cannot pay runs out of gas first, and the charge for a start a limit stops is given back when the stopped frame returns. + +These MUST NOT pay history gas: + +- an [EIP-7708 transfer log](#14-eip-7708-transfer-logs), which is data size only; +- an Oracle hint's payload, which goes to the oracle service rather than into a block; +- any byte of a deposit transaction, of a system-originated transaction, or of a system call (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). + For these the deposited-code history gas MUST be zero too. + The exemption is from history gas alone: a deposit that is not system-originated MUST still be priced by bucket (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), held to every per-transaction limit and detained (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). + +The EIP-7623 floor is still computed and validated. +At these prices it never raises the gas used of a transaction that pays history gas, because the history gas of the same bytes is higher; it can still raise that of a transaction exempt from history gas, a deposit or one of the protocol's own; and it does bind the figure a block counts on its execution ledger, `max(regular, floor)` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +Where it binds, the gas used is the floor, drawn from the whole gas limit, the reservoir included, and the transaction gets back its gas limit less the floor (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)); a deposit, which paid nothing, is charged nothing either way, and only its receipt's and the block's figures move. + +### 8. History Allowance Replaces the Storage Gas Stipend + +#### Previous behavior + +- A value-transferring internal `CALL` or `CALLCODE` grants its callee a separate allowance of 23,000 gas, drawn only at storage-gas surcharge sites. + +#### New behavior + +- A value-transferring `CALL` or `CALLCODE` below the transaction's own frame MUST grant the frame it starts a [history allowance](../glossary.md#history-allowance) of `HISTORY_ALLOWANCE_BYTES` = 160 bytes at the cost per history byte (14,080 gas): one three-topic event carrying one word. +- Only a log's history charge in that frame MAY draw on it, before the frame's gas pays the rest. + A write record MUST NOT draw on it. +- The allowance MUST NOT enter the frame's gas: it cannot pay for computation or state, it is never returned as gas, and what it pays for is on no gas ledger. + The history bytes it pays for still count as bytes the transaction appended. +- The transfer log of the value that granted the allowance MUST NOT draw on it. + +### 9. Gas Forwarding + +#### Previous behavior + +- A call or creation forwards at most 98/100 of the caller's remaining gas. + +#### New behavior + +- A call or creation MUST forward regular gas under the inherited [EIP-150](https://eips.ethereum.org/EIPS/eip-150) rule: at most all but one 64th of the caller's remaining regular gas. +- The child inherits the caller's reservoir whole (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +### 10. Resource Limits + +#### Previous behavior + +- Four runtime transaction-level limits: compute gas `TX_COMPUTE_GAS_LIMIT` = 200,000,000, data size `TX_DATA_LIMIT` = 13,107,200 bytes, KV updates `TX_KV_UPDATE_LIMIT` = 500,000, state growth `TX_STATE_GROWTH_LIMIT` = 1,000 new accounts and slots. +- Every call frame gets 98/100 of its parent's remaining budget in each of the four dimensions. +- Data size and KV updates are counted by Rex6's own per-operation rules; the post-execution fee-reward credits are recorded after the transaction's result is final, and cannot change it. +- A frame crossing its budget reverts alone, the transaction's own frame included, whose budget is what the transaction has left; usage recorded outside every frame's budget — the pre-frame intrinsic usage, an Oracle hint's bytes, the compute limit a read of volatile data lowers — that crosses a transaction-level limit halts the transaction. + +#### New behavior + +One dimension is limited per transaction, data size; compute is not one (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)), and neither are KV updates or state growth. + +| Dimension | Counted in | Transaction limit | Frame budget | +| --------- | ----------------------- | ---------------------------- | ------------ | +| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 | Yes | + +- **Data size** counts the byte table of [History Gas](#7-history-gas), plus two items that pay no history: an EIP-7708 transfer log, counted as `TRANSFER_LOG_SIZE` = 160 bytes (a `LOG3` of one word), and an Oracle hint's payload, counted by its length before it is forwarded. + It counts the body before any frame; the applied authorities' records before the first frame; a frame start's records and transfer log when the frame starts; a storage write's record, a log, and a `SELFDESTRUCT`'s beneficiary record and transfer log once the opcode completed; deployed code once every deposit charge is made and before the creation commits; a hint before it is forwarded, on the transaction and on no frame's budget, unless it would cross the transaction's limit, in which case it is neither counted nor forwarded (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). + A deposit's data size is counted like any transaction's, and a deposit that fails keeps what it counted: its body and the hints it admitted. +- **Write records.** + One record per account or storage write the transaction keeps: a slot's first change in the transaction (taken back when the slot is written back to its original value); a value transfer's sender and recipient; a creation's creator nonce and created account; a `SELFDESTRUCT` that moves a balance to another account (its beneficiary); an applied EIP-7702 authority; the transaction's value recipient or created account. + The sender's account is one of the body's five fixed records and MUST NOT be counted as a record again, whatever writes it: a frame running as the sender, a value transfer or a `SELFDESTRUCT` that moves value to the sender, an applied EIP-7702 authority that is the sender, and a keyless deployment whose signer is the sender record nothing for it. + The four fee accounts are in the body only for the fee credits the transaction's settlement makes: a write execution makes to a fee account that is not the sender — for example a value transfer to it, a `SELFDESTRUCT` that moves a balance to it, or an applied EIP-7702 authority that is one of them — MUST be recorded like a write to any other account. + Records MUST be deduplicated per frame, not per transaction: a frame records an account once, and each value-transferring call records its target on the lane of the frame it starts, which merges into the caller's when the call succeeds. + N value transfers from one frame to the same recipient keep N records and pay N records' history gas, so a transaction's record count is an upper bound on the accounts it wrote, like the body's fixed fee-account records. + A value-transferring `CALLCODE` moves the value from the calling account to that same account: it MUST record that account once, as the transfer's sender, with no recipient record beside it, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. + A value-transferring `CALL` to the calling account itself MUST likewise record that account once, its recipient being its sender, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. + A successful frame's records and bytes MUST merge into its caller's; a failed frame's MUST be discarded, except that a creator's nonce record survives its creation's failure once the nonce was bumped, and lands on the creator. + The KV count is the write-record count; every record weighs `WRITE_RECORD_SIZE` bytes of data size, counted and taken back with it, so `KV × 40 ≤ data size` at every point. + No limit holds the KV count: the data-size limit bounds it — a transaction keeps fewer than 327,680 write records (13,107,200 / 40) — and history gas prices every record (see [History Gas](#7-history-gas)). +- **Frame budgets.** + The transaction's own frame MUST get what the transaction has left once its body and pre-frame records are counted; every child MUST get `FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = 98/100 of what its parent has left, rounded down. + Satin sets no further per-frame cap. + A frame that crosses its budget MUST revert with `MegaLimitExceeded(kind, budget)` and its caller continues. + The budget keeps a caller's own work within reach of what it calls: a child inherits its caller's whole reservoir and history gas draws the reservoir first, so EIP-150's 63/64 forwarding does not bound the bytes a child can append, and without a budget a callee could take the transaction to its limit and leave its caller, which can catch the stop (see [The Revert-Class Stop](#11-the-revert-class-stop)), nothing to carry on with. +- **State growth** is not limited. + EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), so what bounds state growth is what it costs: the transaction's gas limit and the block's. + That the bound stays within the state growth the chain's storage sustains is a property of the state-gas prices, not of a limit. +- **Order at one site.** + A record that crosses the transaction's data-size limit and its frame's budget at once MUST stop its frame with the transaction's limit in the revert data: the transaction limit is checked before the frame budget. +- **A frame start** is counted before the frame is built. + A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be charged nothing, and be stopped by no limit. + A creation onto an occupied address is counted, and a crossing it causes stops it where it would otherwise have failed on the collision. +- **The limits are fixed per spec.** + The transaction's data-size limit, the per-frame share, the detention caps (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) and the block's data-size limit (see [Block Limits](#20-block-limits)) are protocol values of the Satin spec, the same on every chain. + They are not chain configuration: no chain configuration carries them, and a node MUST hold every Satin transaction and block to them, never to values a configuration names or a node is handed with a block. + A later spec that changes one states its own value. + A node MUST hold the transactions of block execution and validation, the executions whose result the chain agrees on, to these values. + A call, a gas estimate or a simulation executed outside a block SHOULD use the same per-transaction limits and detention caps, so that its result predicts block execution. + A node that runs one under other limits, such as an `eth_call` with detention off, does so as its own policy: the result is no part of the chain, and the node SHOULD keep `eth_call` and `eth_estimateGas` consistent with each other. + +### 11. The Revert-Class Stop + +#### Previous behavior + +- A transaction crossing a runtime transaction-level limit through usage recorded outside every frame's budget halts: it produces a failed receipt, its remaining gas is preserved and refunded to the sender, and it is included in the block. + A crossing during a frame's execution, the transaction's own frame included, reverts that frame with its budget's `MegaLimitExceeded` (see [Resource Limits](#10-resource-limits)). +- A frame crossing its budget reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` and its parent continues. + +#### New behavior + +Every limit — the transaction's data-size limit, a frame's data-size budget, and gas detention's compute limit — MUST stop the frame that crosses it with a revert, never a halt. +The stop applies to a transaction that passes validation and pays every charge made before its first frame. +A transaction that fails validation, or that cannot pay a charge made before its first frame (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)), MUST report no stop: a non-deposit transaction that fails validation is rejected, and a deposit that fails validation — a system deposit, which the inherited rules refuse under Regolith, and a deposit whose body is over the data-size limit included — or that cannot pay a charge made before its first frame is included as a failed deposit, whatever kind of deposit it is (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). +The body of such a deposit MUST stay counted as data size. +For a transaction the stop applies to: + +1. The frame that crosses a limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. + The write or the charge that crossed MUST NOT be kept or made, and every write and log the frame made MUST be reverted, as a `REVERT` reverts them. +2. Its caller MUST resume as after any revert: the call fails, its return data is the stop's revert data, and the gas the frame had — before the charge that crossed, for gas detention's limit — returns to the caller, its reservoir included. +3. What the frame counted MUST be discarded with it, so the caller resumes within every limit. + A caller that carries on is held to what the transaction has left: a write or a charge of its own that crosses a limit again MUST stop the caller's frame in turn. + A transaction therefore never keeps more data size than its limit, and never computes past gas detention's limit but by what [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas) allows. +4. A caller that catches the stop MUST run on as after any failed call: a transaction whose frames catch every stop below its own frame MAY succeed, keeping what its frames did and nothing of a frame that was stopped. +5. A stop of the transaction's own frame is the transaction's result. + The transaction MUST settle like an EIP-8037 revert: every write and log its frames made MUST be reverted, the value its first frame carried and that frame's write record included; the sender pays the intrinsic gas, the body's history gas, the charges of what it keeps from before the first frame (below), and what ran; the unspent regular gas and the reservoir return to the sender. + The transaction is included with a failed receipt, and its usage counts towards the block's counters. + +What was applied before the first frame is not the frames' doing, and a stop of the transaction's own frame MUST NOT revert it, as a revert of the first frame does not: + +- the sender's nonce and the fees it pays; for a deposit, its mint and the caller account it created, with that account's state gas; +- the EIP-7702 authorizations admitted before the first frame: their authorities' nonce and delegation writes, their state gas, their write records, and the history gas those records cost. + +An Oracle hint a frame admitted is not the frames' state either: it MUST stay counted as data size through any stop, whether its payload reached the oracle service or failed to decode (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). +A hint that would itself cross the data-size limit is neither forwarded nor counted. + +A limit is enforced before the writes it guards: + +- A frame whose start would cross a limit MUST be answered with the stop before it is built, so no value moves. + A stopped creation still bumps its creator's nonce, and that write's record lands on the creator, which MUST be held to its limits with it before it runs on and be stopped if it crosses one. +- A frame answered without running whose answer is then rewritten to the stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST have what its start moved reverted with it, as a frame that fails has. +- Nothing counted before the first frame — the body, and the records of the EIP-7702 authorities applied — crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +A real out-of-gas, a precompile given less than its price, and an invalid opcode still halt and consume the frame's gas. + +The revert data: + +| `kind` | Dimension | `limit` | +| ------ | ----------------------- | -------------------------------------------------------------------------------------------------- | +| 0 | Data size | The limit or frame budget crossed, in bytes | +| 2 | Compute (gas detention) | The compute limit of the binding read: the transaction's compute at that read plus the cap, in gas | + +The discriminants are Rex6's, so a decoder of the Rex6 revert data decodes Satin's. +Kinds 1 and 3, Rex6's KV updates and state growth, are not reported: no limit holds either dimension. +Kind 2 names the limit; the compute the transaction is billed can exceed it when frames halt because they cannot pay an opcode's static gas — the first of them taking the compute past the limit, each later one holding it there — by less than that static gas per halting frame, added over those frames (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). +A contract can revert with the same bytes, and so can a caller that re-raises the stop a frame below it returned, so the revert data alone does not identify a stop: the stop of a transaction is the crossing that produced the result of its own frame (see [Developer Impact](#developer-impact)). + +### 12. Gas Detention on Withheld Gas + +#### Previous behavior + +- A volatile read sets `effective_detained_limit = current_compute_gas_used + cap` on the compute-gas ledger; the most restrictive read binds. +- Crossing the detained limit halts the transaction with `VolatileDataAccessOutOfGas`; the detained gas is refunded at the end of the transaction. +- `BLOBHASH` is volatile; a transaction whose sender is the system address is exempt from oracle detention, and a system-originated transaction from detention. + +#### New behavior + +- **What is volatile.** + The block environment (`NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH`); the block beneficiary's account, through `BALANCE`, `SELFBALANCE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the four call opcodes and the EIP-7702 delegate they follow, `SELFDESTRUCT` at either end, a sender or recipient that is the beneficiary, a recipient that delegates to it, an applied EIP-7702 authority that is the beneficiary, and a keyless deployment's signer that is the beneficiary; and the Oracle's storage, through `SLOAD` in the Oracle's own frame. + `BLOBHASH` MUST NOT be volatile: it reads the transaction's own blob hashes. + A read MUST be marked where the value is loaded, and only once the opcode completed; a load that fails, and a read whose opcode then fails, mark nothing. + `BLOCKHASH` loads the block number before it decides whether its operand is in range, so every `BLOCKHASH` is a read of the block environment, one of the current block, a future block or a block outside the last 256 included, and one in range reads the hash as well. + A `CREATE` or `CREATE2` MUST NOT be marked as a read, even when its creator or its created address is the block beneficiary: the loads it makes of them — the creator's, to check its balance and nonce, and the created address's, to decide the created account's state gas — mark nothing, and a frame then running as the beneficiary marks the beneficiary's account by its own `SELFBALANCE`, `SELFDESTRUCT` and the other reads above (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas) for what those loads do with access off). +- **Compute.** + A transaction's compute is its regular ledger — the running frame's regular gas spent, plus every suspended caller's, each less its child's whole gas limit — less the state and history gas that spilled onto regular gas, and less what halting frames burned. + A child's gas limit includes a value call's 2,300 stipend, which its caller did not spend: what the callee spends of it is not compute, and what the callee leaves of it lowers the caller's spent regular gas when it returns. + What a halting frame burns is not compute, with one exception: when an opcode's static gas cannot be paid, what the halting frame had left counts as compute. +- **The limit.** + A read MUST set `limit = compute_at_read + cap`, with `cap` = `BLOCK_ENV_ACCESS_COMPUTE_GAS` = 20,000,000 for the block environment and the beneficiary and `ORACLE_ACCESS_COMPUTE_GAS` = 20,000,000 for the Oracle; the limit only goes down, so the most restrictive read binds. + The caps are protocol values fixed per spec with the other limits (see [Resource Limits](#10-resource-limits)). + Both are below 199,987,900, the most compute a transaction can spend, so that they can stop one: the execution cap less EIP-2780's base cost of 12,000, which every transaction pays, and the 100 of a warm account access, the least a frame pays for the code it runs. +- **Withheld gas.** + Once a limit is set, every frame's regular gas MUST be split into a spendable part, held at what the limit leaves the transaction (`limit − compute`, or zero once the compute is past the limit), and a withheld part, the rest. + The split MUST be applied when the read's opcode completes, when a frame starts or resumes, and after an `SSTORE` (whose restore of a slot can refill regular gas). + Only a regular charge MUST be limited to the spendable part. + Every other reader of the frame's gas MUST see both parts: `GAS`, the 63/64 forward and the clamp of an explicit call gas, the `SSTORE` minimum-gas check, the checks that decide whether a cold load is attempted, the gas a child returns, and the settlement at the end of the transaction. + At the settlement the withheld part MUST be unspent gas: it returns to the sender with the rest of the unspent gas, and it is not part of the gas used that caps the EIP-3529 refund at a fifth. + A forward and a spill of state or history gas MUST draw the withheld part first. + So a transaction that read volatile data runs exactly as it would without the read until a regular charge needs the withheld part. +- **The crossing.** + A regular charge that the spendable part cannot pay but the frame's whole regular gas can is the crossing: the charge MUST NOT be made, the frame's gas MUST be put back to what it was before the charge, and the frame MUST be stopped with `MegaLimitExceeded(2, limit)` (see [The Revert-Class Stop](#11-the-revert-class-stop)). + What the frame spent before the crossing charge stays spent, and its caller MUST get back everything the frame had, the withheld part included. + The transaction's compute at the crossing is then at most the limit and less than the crossing charge short of it, with one exception. + A caller the stop returns into resumes held to what the limit leaves the transaction, which is less than the charge that crossed, so any regular charge of its own past that is a crossing too. + A frame that halts because it cannot pay an opcode's static gas counts what it had left as compute (see Compute, above), and that can take the transaction's compute past the limit without a crossing, by less than the static charge the frame failed to pay: at most 4,999 gas per such frame, `SELFDESTRUCT`'s static gas of 5,000 being the largest. + Its caller then resumes with no spendable gas; a caller whose whole regular gas cannot pay its next opcode's static gas either halts the same way and adds what it had left, so the overshoots accumulate along such a chain of frames, each adding less than its own static charge, with no fixed total. + From then on the spendable part is zero, so the next non-zero regular charge that a frame's whole regular gas can pay MUST be the crossing, and the compute stays past the limit by the overshoots together. + A transaction whose frames make no such charge after the overshoot ends as it would without the read, its compute past the limit. + A regular charge beyond the frame's whole regular gas, and every other out-of-gas, MUST halt as it would without the read. +- **Precompiles.** + A call to a precompile forwarded more regular gas than the frame's allowance MUST be decided from the precompile's price before it runs: priced within the allowance, it runs on its whole forward; priced past the allowance but within the forward, it MUST NOT run and is the crossing; priced past its whole forward, it runs on the forward and fails, as without the read. + Every precompile of the Satin set has a price; an input over a size limit is priced at zero, since it is refused before any gas check. + An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check is the crossing too. + A call refused on its caller's account runs no precompile and is answered as without the read. +- **Interceptor answers.** + A system contract's intercepted answer that spent more regular gas than the frame's allowance, state and history gas that spilled onto its regular gas not counted, MUST be the crossing. + The answer's whole regular spend MUST be treated as the one charge that crossed: none of it is billed, the part within the allowance included, so the stop's compute is the transaction's compute when the frame started. +- **Refused reads.** + See [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas). +- **Exemptions.** + A system-originated transaction and a system call MUST NOT be detained, whatever they read (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). + +{% hint style="info" %} +A precompile a node adds or replaces is outside the Satin set and outside this specification. +The reference implementation has no price for one, so it runs such a precompile on the allowance and treats running out of it as the crossing. +{% endhint %} + +### 13. Volatile-Data Access Control and `remainingComputeGas()` + +#### Previous behavior + +- A read refused by `disableVolatileDataAccess()` reverts the frame immediately with `VolatileDataAccessDisabled(VolatileDataAccessType)`; `BLOCKHASH` and `BLOBHASH` are refused before their operands are checked. +- `MegaLimitControl.remainingComputeGas()` answers from a separate compute-gas ledger with per-frame budgets of 98/100 of the caller's remaining compute, and can exceed the caller's gas. + +#### New behavior + +- `MegaAccessControl`'s interface, errors, and the scope of `disableVolatileDataAccess()`, `enableVolatileDataAccess()` and `isVolatileDataAccessDisabled()` are unchanged. +- `disableVolatileDataAccess()` switches access off once its answer is settled; an answer gas detention turns into the compute stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST leave the switch as it was. +- A read is refused where the opcode loads the value, after it read its operands: an opcode that fails on its operands (a stack underflow, for example) fails as it would with access on. + The load comes before the opcode pushes its result, so a read on a full stack is refused rather than overflowing it. + A `BLOCKHASH` is refused as `BLOCKHASH` (7) whatever its operand. +- A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas: the refused read pays its static gas and nothing else — not a cold access, not a copy's memory, not a call's value transfer. + The static gas is the opcode's base cost: 2 for `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE` and `SLOTNUM`; 5 for `SELFBALANCE`; 20 for `BLOCKHASH`; 100 for `BALANCE`, `EXTCODEHASH`, the four call opcodes and an `SLOAD` of the Oracle's storage (whose cold surcharge is not paid); 200 for `EXTCODESIZE` and `EXTCODECOPY`, EIP-8038's base of two warm accesses (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)); and 5,000 for `SELFDESTRUCT`. + What the opcode charged after its static gas and before the load — the memory and the copy cost of `EXTCODECOPY`, a call's memory and value-transfer cost — MUST be given back. +- A `CREATE` or `CREATE2` in a frame whose access is off is outside this rule when it loads the block beneficiary's account: the creator's, which it loads first for its balance and nonce, or the created address's, which it loads to decide the created account's state gas once the endowment, nonce and depth checks passed; that load is refused as a load the frame cannot make, and the creating frame MUST halt with an out-of-gas, consuming its gas, instead of reverting with the error. +- The error's argument MUST be ABI-encoded as a `uint8`: + + | `accessType` | Read | + | ------------ | ------------------------------- | + | 0 | `NUMBER` | + | 1 | `TIMESTAMP` | + | 2 | `COINBASE` | + | 4 | `GASLIMIT` | + | 5 | `BASEFEE` | + | 6 | `PREVRANDAO` (`0x44`) | + | 7 | `BLOCKHASH` | + | 8 | `BLOBBASEFEE` | + | 10 | The block beneficiary's account | + | 11 | The Oracle's storage | + | 12 | `SLOTNUM` | + + Values 3 (`Difficulty`) and 9 (`BlobHash`) are not produced. + Value 12 is outside the contract's `VolatileDataAccessType` enum, whose ABI decoder reverts on it: a handler MUST decode the argument as a `uint8`. + The system contracts' bytecode is unchanged. + +- `remainingComputeGas()` MUST answer the lesser of two figures, read when the call reaches the interceptor: the calling frame's own regular gas with the gas the call forwarded counted back, and, once a read of volatile data set a limit, what the limit leaves the transaction. + It is regular gas only: the reservoir is not in it, so a transaction above the execution cap hears at most the cap's share. + A transaction that calls the contract directly hears its own frame's regular gas, or less when it is detained from its start (its sender is the block beneficiary, or an EIP-7702 authority it applies is). + +### 14. EIP-7708 Transfer Logs + +#### Previous behavior + +- A value transfer emits no log. + +#### New behavior + +A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): + +- Every movement of value to another account — the transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT` that moves a balance to another account — MUST emit `Transfer(address indexed from, address indexed to, uint256 value)` from `0xfffffffffffffffffffffffffffffffffffffffe`, with topic `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef`. +- The log MUST appear in the receipt in execution order among the contracts' own logs, and a failed frame's logs are discarded with the rest of its logs. +- A `CALLCODE`, a call to the caller itself, and a transaction's value sent to its own sender move nothing to another account and MUST NOT log. +- A deposit's value is logged; its mint is not. +- Satin applies the `Transfer` log of EIP-7708 and nothing else of any revision of that EIP: [EIP-8246](https://eips.ethereum.org/EIPS/eip-8246), which EIP-7708 lists among its requirements, MUST NOT be applied, so a balance can still be burned, and a burn MUST NOT log — no `Burn` log is ever emitted, whatever revision of EIP-7708 defines one. + Two burns remain, both silent: a `SELFDESTRUCT` to itself of an account created in the same transaction burns the balance at once, and an account destroyed in the transaction is removed at its end with whatever balance it then holds, a value it received after its destruction included (the `CALL` that sent it logged the transfer). +- A transfer log is data size (`TRANSFER_LOG_SIZE` = 160 bytes), counted where the value moves: with the start of the frame that moves it, before any value moves, or with the `SELFDESTRUCT` that moves it. + It is not a write record, pays no history gas, and does not draw on a history allowance. +- A frame start that the caller's account refuses moves nothing and logs nothing. +- A creation with an endowment onto an occupied address counts its transfer log with its start, as any creation with an endowment does, though the collision then moves nothing and logs nothing: a crossing the count causes stops it first (see [Resource Limits](#10-resource-limits)), and otherwise the count is discarded with the failed creation. + +### 15. Native Keyless Deployment + +#### Previous behavior + +- A top-level `keylessDeploy(bytes,uint256)` call runs the signed creation in a sandbox: a separate, fee-free transaction with its own resource trackers, capped to the parent's remaining budgets, whose state is merged into the parent afterwards. +- Inside the sandbox `ORIGIN` is the signer and `GASPRICE` is 0. +- A transaction-level limit crossed after the sandbox ran halts the outer call with `OutOfGas` and merges none of the sandbox's state or logs, while its resource usage and volatile-access marks stay merged, since they are what crossed the limit; a sandbox preflight failure reverts with `ParentBudgetExceeded`; a failed read reverts with `InternalError()`. +- `gasUsed` is the sandbox transaction's gas used, its intrinsic gas included. + +#### New behavior + +A `keylessDeploy(bytes,uint256)` call that is the transaction's own frame (depth 0, to `KEYLESS_DEPLOY_ADDRESS` = `0x6342000000000000000000000000000000000003`) MUST deploy the carried creation as an ordinary creation frame, a child of the call; no code runs in the call's frame itself. +The call is recognized by its depth, its scheme (`CALL`), its target and its selector alone, whatever code the state holds at the address. +A `keylessDeploy` call a contract makes MUST run the contract's bytecode: without value it reverts with `NotIntercepted()`, and with value it reverts with empty data, the method not being payable. + +The call MUST make these charges and checks, in this order. +A rule's refusal reverts the call with the error named: the state and history gas the call was charged are given back, and the regular gas it spent stays spent. +An out-of-gas step halts the call, consuming its regular gas. + +| Step | Check or charge | Refusal | +| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 1 | Charge `KEYLESS_DEPLOY_OVERHEAD_GAS` = 100,000 regular gas | Out-of-gas | +| 2 | The call carries no value | `NoEtherTransfer()`, before the frame is built: no value moves | +| 3 | The arguments and the carried transaction decode: a signed legacy creation, no chain id, no trailing bytes | `MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()` | +| 4 | The carried transaction's nonce is 0 | `NonZeroTxNonce(uint64)` | +| 5 | The initcode is within `MAX_INITCODE_SIZE` | `InitCodeTooLarge(uint64,uint64)` | +| 6 | `gasLimitOverride` covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 7 | The signer can be recovered, from a signature with a low or a high `s` value: EIP-2's bound on `s` does not apply | `InvalidSignature()` | +| 8 | The signer's nonce is at most 1 | `SignerNonceTooHigh(uint64)` | +| 9 | Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation | `SignerHasCode()` | +| 10 | If the signer's account is empty (EIP-161), charge its new-account state gas (`183,600 × m`) | Out-of-gas | +| 11 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 12 | The deploy address `keccak256(rlp([signer, 0]))[12:]` holds no code | `ContractAlreadyExists()` | +| 13 | The signer's balance covers the carried value | `InsufficientBalance()` | +| 14 | Charge what a `CREATE` charges its frame: 12,000 plus EIP-3860's initcode cost, the created account's state gas if the deploy address is empty, and the history gas of the created account's record and, unless the signer is the transaction's sender, the signer's nonce record | Out-of-gas | +| 15 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | + +- Steps 1 to 13 keep Rex6's order, so a call several rules refuse reports the Rex6 error. +- The read of the signer's account that steps 8 to 10 and 13 check, and the deploy-address read of step 12, MUST load the account into the transaction's state as an account access loads it, warm, the deploy address without its code. + Neither read is charged, and no charge the call or its creation makes depends on either account's warmth: the creation loads both again when it starts, as a creation loads its creator and the address it creates. +- Step 12 checks the deploy address's code alone: an address that holds a nonce but no code passes it, and the creation then collides there, as any creation onto an occupied address does, and fails, the call answering `ExecutionHalted` with the creation's whole forward spent and the signer's nonce kept or taken back as below. + Rex6 left such accounts: a Rex6 deployment whose creation returned empty code completed and left the deploy address at nonce 1 with no code, and a signed deployment there now collides whatever its initcode does. + Under Satin no deployment leaves one: a creation at the deploy address that returns empty code is refused its empty deposit and reverts, as one that reverted, halted or was stopped does, so the address stays deployable. + A constructor that destroyed its own account leaves none either, and a creation the constructor itself makes may return empty code. + The only creations at the deploy address are those whose address is derived from the signer and nonce 0: the signed deployment, which anyone may submit while the signer's nonce is 0 or 1, and a creation transaction the signer's own key sends at nonce 0. + Whether the initcode returns empty code is its own to decide, from what it runs on, and whoever submits the deployment chooses part of that: the gas forwarded to it, which can be raised above the signed gas limit through `gasLimitOverride`, the outer transaction (its `ORIGIN`, `GASPRICE`, access list and authorizations), and the block and the state it runs in, the oracle service's answers and the SALT capacities included. + An initcode that branches on any of them can be made to return empty code, and the deployment then answers `EmptyCodeDeployed`, but it occupies nothing: the same signed bytes can be submitted again. +- A signer that is the block beneficiary MUST be detained as a read of the beneficiary's account, made when the signer's account is read, once step 7 recovered it and before step 8's check: the read's compute is the call's 100,000 of step 1, so the limit is 100,000 plus the cap, unless an earlier read set a lower limit. +- The creation MUST then start as a creation by the signer at the deploy address, one level below the call, forwarding `min(gasLimitOverride, remaining gas)`; the forward draws the call's withheld gas first (see [Gas Detention](#12-gas-detention-on-withheld-gas)). + From there it is an ordinary creation frame: priced, limited, detained and logged as one. + `ORIGIN` and `GASPRICE` in the initcode are the transaction's own. +- **The signer's nonce.** + The creation bumps the signer's nonce as any creation bumps its creator's. + A deployment from nonce 0 MUST keep the bump. + From nonce 1, when the creation's bump is the last nonce change the deployment made, the node MUST take the bump back, whether the deployment succeeded or failed. + The bump's write record and that record's history gas go back with it, unless the creation returned without a revert or a halt — a constructor that destroyed its own account included, and a creation refused its empty deposit not — and moved value out of the signer, whose account then keeps a write of its own. + A signer whose own code spent a nonce during the creation that survives it keeps every bump. +- **The answer.** + The call MUST succeed with `(gasUsed, deployedAddress, errorData)`: the deploy address and empty `errorData` when the deploy address holds code afterwards; otherwise the zero address and `ExecutionReverted(uint64 gasUsed, bytes output)`, `ExecutionHalted(uint64 gasUsed)` or `EmptyCodeDeployed(uint64 gasUsed)` — the last for a creation that returned empty code for the deploy address, which is refused and reverts, and also for a constructor that destroyed its own account. + `gasUsed` MUST be what the creation spent from both pools, with no intrinsic gas and before the EIP-3529 refund: the regular gas it spent and the state and history gas it kept, net of every give-back within the creation — a slot written back to its original value, a record taken back, the upfront state gas of a frame it started that failed; the call's own charges of steps 1 and 14 are not in it, and a give-back is not a refund. + It is never less than the regular gas the creation spent. +- **Limits.** + A limit the creation crosses — its frame budget, the transaction's data-size limit or gas detention's compute limit, at its start or in its initcode — stops the creation, and the call answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start wrote. + A limit the call's own charges cross — gas detention's compute limit — stops the call: it reverts with the stop, and the deployment, the signer's nonce included, is taken back. + When the signer's nonce record, which survives a failed creation, takes the call over a limit — its own frame budget or the transaction's data-size limit — the call reverts with that stop and the deployment, the nonce included, is taken back; since the call is the transaction's own frame, the stop reported for the transaction is that one. +- The contract's interface no longer declares the four errors only Rex6 and earlier produced: `ParentBudgetExceeded(uint8,uint64,uint64)`, `InvalidTransaction()`, `InsufficientComputeGas(uint64,uint64)` and `InternalError()`. + A node MUST NOT produce them: a failed database read or SALT lookup gives the transaction no outcome, as [Transaction and Block Refusals](#21-transaction-and-block-refusals) says. + `AddressMismatch()` and `NoContractCreated()` remain as answers to a creation reported at another address or at none, which no deployment reaches. + [KeylessDeploy](../system-contracts/keyless-deploy.md) lists the errors the interface declares. +- The `KeylessDeploy` contract's bytecode and code hash are unchanged: the bytecode names none of the removed errors. + +### 16. Oracle Storage Reads and Hints + +#### Previous behavior + +- An `SLOAD` of the Oracle's storage is always charged as a cold access and triggers oracle detention. +- A `sendHint` is forwarded to the oracle service when the call is forwarded gas, its payload decodes, it stays within the data-size limit, and the calling frame's volatile-data access is on; its payload counts as data size. + +#### New behavior + +- An `SLOAD` in the Oracle's own frame MUST load the slot from state, then ask the oracle service, and answer the service's value when it gives one and the loaded value otherwise. + The service's value MUST win over whatever the slot holds at the read, a value the Oracle's own frame wrote earlier in the transaction included; with no value from the service the read answers the slot's present value, that write included. +- Every such read MUST be charged as a cold access (2,100 gas), however often the slot was read, and the slot MUST be loaded whichever source answers, so a later write finds it warm and a stateless witness carries it. +- A frame whose regular gas, its withheld part included, cannot pay the cold access MUST read nothing and ask nothing; a refused read asks nothing. +- A system call MUST NOT ask the service at all: its read answers the chain's value (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). +- A `sendHint` MUST reach the service synchronously, when it is called, and only when the call is forwarded gas, carries no value, and comes from a frame whose volatile-data access is on. + A hint that fails any of those conditions is dropped and counts nothing; the call runs the Oracle's bytecode either way. + The value condition is new. + The service MUST be handed the hint's topic, its data, and the address of the frame that made the call: the transaction's sender for a `sendHint` that is the transaction's own call. + Only a `CALL` or a `STATICCALL` to the Oracle is a `sendHint`: a `CALLCODE` or `DELEGATECALL` of the method runs the Oracle's bytecode in a frame of the caller's own context, reaches no service and counts nothing. +- An admitted hint MUST count the call's whole input length as data size on the transaction, before the input is decoded, and pays no history gas. + A `sendHint` that is the transaction's own call MUST count its input twice: once as calldata in the transaction's body, and once as the hint. + Every admitted input stays counted, whatever the calling frame or the transaction does afterwards — a revert, a halt, a later stop, a failed deposit — and that includes an input that fails to decode, which reaches no service. + Two reasons keep the count, each on its own: a payload forwarded to the service cannot be taken back, and admitting an input and decoding it is work the node has done whether or not the input decodes. +- A hint whose input length would take the transaction's data size over its data-size limit MUST NOT be forwarded and MUST NOT be counted. + The `sendHint` call MUST be answered with the stop, without running the Oracle's bytecode: the stop is the call's, which its caller can catch, and when the call is the transaction's own frame the stop the transaction reports counts the data size the hint would have reached as used. + The data size the transaction keeps, which the block's data-size budget counts, holds none of the hint's bytes: the payload never left the node, so it is taken back as a log that crosses the limit is. + The check is against the transaction's limit alone, because a hint's bytes are on no frame's budget. + +### 17. The Live System Address + +#### Previous behavior + +- The system address is resolved per block from `SequencerRegistry.currentSystemAddress()` after the pre-block changes commit. +- A Mega System Transaction is a legacy transaction from that address to a contract on `MEGA_SYSTEM_TX_WHITELIST`. +- A transaction from the system address without that shape is refused, with an error that is not a transaction's: a deposit from the system address is refused the same way rather than included as a failed deposit, so a block that holds one cannot be executed. +- A Mega System Transaction's nonce and, unless EIP-3607 is disabled, its sender's code are checked before it is promoted to a deposit; its chain id is not, as no transaction's is: the chain-id check is off in every configuration Rex6 runs. + +#### New behavior + +- The system shape is tested on the transaction's own fields: type `0x0`, a call (not a creation) to an address on `MEGA_SYSTEM_TX_WHITELIST` (the Oracle). +- Every transaction MUST read the registry when it is validated, whatever its shape and whoever sent it: the node loads the registry's account and, from the transaction's own state, its `_currentSystemAddress` slot. + When the registry's code hash is that of version 2.0.0, which this spec requires, and the slot holds a non-zero address, that address is the live system address. + The read compares the registry's code hash and MUST NOT load or run the registry's code. + The account and the slot MUST be warm for the rest of the transaction, as the block beneficiary is under [EIP-3651](https://eips.ethereum.org/EIPS/eip-3651), whatever the registry holds: an access to either costs every transaction the same, whatever its envelope. + The read is not charged and writes nothing, so committing the transaction leaves the registry as it was. + It lands in the transaction's returned state, and so in the block's witness, whatever the pre-block states also hold of the registry; it does not load the registry's code, but the witness carries that code as it carries the code of every account the block loads (see [The Stateless Witness](#22-the-stateless-witness)), and the Oracle's own check of its caller runs it. +- A transaction of the system shape whose caller is the live system address is a Mega System Transaction. + A registry that is absent, holds other code, or names the zero address names no live system address, and MUST make no transaction a Mega System Transaction. + Satin's activation block refuses a chain whose registry is absent or holds other code (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)), so on a chain Satin runs on those two arise only in a state built apart from the chain, such as a test's. +- A transaction from the live system address without the system shape MUST be invalid, whatever its type, a deposit included: a transaction other than a deposit is rejected, and a deposit, which is never of the system shape, is included as a failed deposit, which runs no call (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + That includes a deposit carrying the source hash the promotion stamps, which a block never holds: a Mega System Transaction is promoted from its legacy envelope, and one handed to a node already promoted is a failed deposit. + The Oracle authorizes writes on the sender alone, so no transaction from the system address other than a Mega System Transaction reaches the Oracle. +- A transaction from any other address is never a Mega System Transaction, and is an ordinary transaction, validated and charged as a user's: that includes a transaction from an address a rotation retired, which is no longer the live system address. +- A Mega System Transaction MUST be validated before it is promoted to a deposit, and a failure is a rejection: it MUST carry the chain's id, which a user's legacy transaction may omit and it MUST NOT; its nonce MUST be the system address's; and the system address MUST have no code, as [EIP-3607](https://eips.ethereum.org/EIPS/eip-3607) requires of any sender. + It is then executed as a deposit, which checks no signature, nonce or fee of its own. +- Because a role change can only be scheduled for a later block — the registry refuses an activation block at or before the current one — and is applied by that block's pre-block call, every transaction of a block reads the address the block's pre-block step left; a call to `applyPendingChanges()` inside the block, which anyone may make, finds no change due that the pre-block step did not apply. +- A registry read the node fails to make gives the transaction no outcome (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + +### 18. System Calls and Pre-Block Calls + +#### Previous behavior + +- The EIP-2935, EIP-4788 and `SequencerRegistry.applyPendingChanges()` pre-block calls run on `max(block_gas_limit, 30,000,000)` gas, fail-closed. +- `applyPendingChanges()` runs before the registry deploy step, which from Rex6 upgrades a version 1.0.0 registry in place. +- Every block installs the MegaETH system contracts the forks so far introduced, at nonce 0, and upgrades the Oracle's older versions in place; no block deploys the EIP-7997 factory. + +#### New behavior + +- **The split.** + A system call MUST run on at most `SYSTEM_CALL_REGULAR_GAS_LIMIT` = 30,000,000 of regular gas; the rest of its gas limit is its state-gas reservoir, as EIP-8037 specifies for system calls. + `GAS` inside a system call reads at most 30,000,000. + A transaction is not a system call: every transaction's gas is split by the execution cap, a Mega System Transaction's included. +- **The pre-block budget.** + Each pre-block call MUST run from `0xfffffffffffffffffffffffffffffffffffffffe` on `max(block_gas_limit, 30,000,000)`; what the budget adds above 30,000,000 is reservoir. + In a block whose gas limit is at most 30,000,000 the call MUST have no reservoir, and its state gas MUST spill onto its regular gas (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +- **The pre-block sequence.** + Before its transactions, a block MUST, in order: + 1. make the EIP-2935 call; + 2. make the EIP-4788 call (a block without a parent beacon block root is invalid, as EIP-4788 defines); + 3. in the block in which Satin activates, and in no other, check the six MegaETH system contracts in address order — Oracle, High-Precision Timestamp, KeylessDeploy, MegaAccessControl, MegaLimitControl, SequencerRegistry — and then the [EIP-7997](https://eips.ethereum.org/EIPS/eip-7997) `CREATE2` factory at `0x4e59b44847b379578588920ca78fbf26c0b4956c`, as below; + 4. read whether the `SequencerRegistry` has a role change due in the block, and if it has, call `applyPendingChanges()`; + 5. read the L1 block contract's account and its five fee slots, as [the stateless witness](#22-the-stateless-witness) lays out. +- **The activation check.** + Satin runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs, and whose genesis OP's tooling gave the EIP-7997 factory: Satin deploys, upgrades and seeds none of them. + The block in which Satin activates — Satin active at its timestamp and not at its parent's — MUST read the seven addresses, and each MUST hold exactly the code Satin expects: the Oracle and the SequencerRegistry at version 2.0.0, the other four system contracts at the bytecode Rex6 runs, and the factory's runtime, code hash `0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989`. + Their nonces, balances and storage are not checked. + An address with no account, an account without code, an older version of its contract or any other code MUST make the block invalid. + The reference implementation reports every such refusal as one error, `MegaBlockExecutionError::UnexpectedSystemContractCode`, which names the address, the code hash expected and the one held, and is a verdict on the block. + The check writes nothing: each address it reads is a read-only entry of the activation block's pre-block states, in the order above. + No other block reads the seven addresses before its transactions. +- **Oracle reads in a system call.** + A system call MUST NOT ask the oracle service: an `SLOAD` in the Oracle's own frame during one reads the slot's value on the chain, which is loaded and priced as an Oracle read is (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)), and records no answer. + The pre-block calls run whatever code sits at the EIP-2935 and EIP-4788 addresses: on MegaETH's chains that is EIP-2935's and EIP-4788's own code, which reads no Oracle, and the rule keeps a system call a function of the state a stateless validator is given, which carries no service answer, whatever that code is. + The rule ends with the call: the transactions of the block are answered by the service as they are outside it. +- **Failure.** + A pre-block call that does not succeed MUST make the block invalid, before its state is used. + A database error the node's database declares fatal is an internal error of the node, not a verdict on the block; any other failure of a call — a non-fatal database error, another EVM error, an outcome that is not a success — makes the block invalid. + A database error in the activation check, in the due-change read or in the read of the L1 block info is always an internal error. + The L1 block info is read for every block, whatever its transactions, so a node whose database cannot serve the L1 block contract's account, or one of the five slots of a contract the chain holds, cannot execute the block: it fails before the block's first transaction, as an internal error, even for a block of deposits alone, which prices nothing against the contract, or a block whose transactions never read the overhead slot (5). + +### 19. The Protocol's Own Transactions + +#### Previous behavior + +- A system-originated transaction — a pre-block call from `0xfffffffffffffffffffffffffffffffffffffffe`, or a Mega System Transaction before or after its promotion — is charged dynamic storage gas at the minimum bucket, is not halted by the four resource limits or by detention, and has its usage recorded. + +#### New behavior + +A transaction MUST be system-originated when it is a Mega System Transaction, before or after its promotion; when its caller is `0xfffffffffffffffffffffffffffffffffffffffe`, the caller of the pre-block calls; or when it is a deposit carrying the source hash the promotion stamps, `keccak256("MEGA_SYSTEM_TRANSACTION")`, whoever its caller. +The test is the transaction's own fields, in a block as outside one: a transaction of any type from that caller, or a deposit carrying that source hash, is treated as the protocol's wherever it is executed, a call or simulation included; no transaction a block derives from L1 carries either, and that caller's key is held by nobody, so in a block the set is the promoted Mega System Transactions. +Only a deposit carries a source hash: a transaction handed to a node with one is a deposit, and is executed as one, whatever type its other fields name, so no transaction of another type carries the promotion's. + +A system-originated transaction and every system call: + +- MUST be priced at `m = 1` and MUST NOT read a bucket capacity; +- MUST pay no history gas, the body and deposited code included; +- MUST NOT be stopped by any per-transaction limit or frame budget; +- MUST NOT be detained; +- still have their usage counted. + +A system-originated transaction's usage is reported and counts towards the block's counters; the pre-block calls do not count towards the block's counters or limits. + +A deposit pays no history gas either (see [History Gas](#7-history-gas)), but a user's deposit is not system-originated: it is held to every per-transaction limit, detained, and priced by bucket (see [State Gas](#6-state-gas-and-salt-pricing)). + +### 20. Block Limits + +#### Previous behavior + +- Block-level runtime limits on data size (13,107,200), KV updates (500,000) and state growth (1,000); the first transaction that reaches one is included and later candidates are skipped. +- There is no block-level compute-gas limit. + +#### New behavior + +A block MUST count, per transaction, its regular (as `max(regular, floor)`), state and history gas, its history bytes, its data size and its write records. +One of those counts is limited: + +| Block limit | Counted | Checked | Limit | +| ----------- | ------------------------------- | -------------------------------- | ---------------- | +| Data size | Data-size bytes per transaction | Before the next transaction runs | 13,107,200 bytes | + +- It is a packing budget: the transaction that reaches the limit MUST be included, and later transactions MUST be skipped. + A builder that executes several candidates before it commits one MUST hold each to the block's counters again when it commits it, together with the block gas limit and the data-availability footprint; a validator commits every transaction before it executes the next, so for it the second check finds what the first found. + Such a builder MUST NOT commit a candidate whose sender's nonce or balance — the system address's, for a Mega System Transaction — another commit moved since the candidate executed: committing it would write the sender's account over what that commit did. + Any other state a candidate read and a commit since changed is the builder's to account for, by executing the candidate again; a candidate that read the Oracle executed before a Mega System Transaction that writes it, committed after that transaction, commits the value it read. +- A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by it, and MUST count towards it. + A Mega System Transaction MUST NOT be refused by it either, nor by a building policy, and MUST count towards it, so the oracle update the sequencer must be able to include is never skipped for a budget the block's other transactions used up. + The block decides that before the transaction runs, from its envelope and the live system address (see [The Live System Address](#17-the-live-system-address)): a legacy transaction of the system shape sent from that address. + A transaction from that address of another shape is no Mega System Transaction here; the block treats it as any other transaction, and it is invalid as [The Live System Address](#17-the-live-system-address) states. + A Mega System Transaction is still held to the block gas limit, and, its envelope being legacy, to the block's data-availability footprint, which it counts towards with its data-availability size; the exemption is from the data-size budget and from building policy alone. +- Execution, state and history gas have no block limit beyond the block gas limit; state gas prices the state a block adds, so the block gas limit bounds it. + The block's history bytes and write records are reported, not limited. +- The block gas limit is unchanged: a transaction's declared gas limit MUST fit in what the block has left. +- The limit is a protocol value fixed per spec with the per-transaction limits (see [Resource Limits](#10-resource-limits)), the same on every chain; no chain configuration carries it. + A node validating a block MUST hold it to that value, as the rules above state them, and to no other value. +- A block builder MAY pack tighter, as building policy: it MAY refuse a transaction for its declared gas limit, its encoded size or its data-availability size, hold the block to an encoded-size or data-availability budget, and hold the data-size limit below the protocol's value, never above it. + A building policy MUST NOT refuse a deposit, which the block derived from L1 must include: none of those per-transaction limits and budgets applies to one. + It MUST NOT refuse a Mega System Transaction either: none of them applies to one, and the policy's cap on the data-size budget does not. + A deposit counts towards the block's encoded size and not towards its data-availability size; a Mega System Transaction counts towards both; the block gas limit holds either as it holds every transaction. + A node validating a block MUST NOT apply a building policy, and a policy never changes what a packed block computes: it only decides which transactions the builder packs. +- Satin sets no limit on a transaction's or a block's encoded size; a block-size rule of the base layer, where a chain adopts one, is the node's to apply and is not one of these limits. + +### 21. Transaction and Block Refusals + +#### Previous behavior + +- Rex6's refusals: the inherited validation errors, the resource-limit halts of [Resource Limits](../evm/resource-limits.md), and the fail-closed pre-block calls. +- Rex6 checks no transaction's chain id: the chain-id check is off in every configuration it runs, and a transaction carrying another chain's id, or a typed transaction carrying none, is valid. + +#### New behavior + +A transaction MUST be rejected before inclusion when: + +- its body, with `WRITE_RECORD_SIZE` bytes for each entry of its authorization list, exceeds the transaction's data-size limit, unless it is system-originated (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)); +- its gas limit is below its intrinsic regular gas plus the history gas of its body (`CallGasCostMoreThanGasLimit`); +- its floor exceeds its gas limit, or, above the execution cap, its intrinsic regular gas or floor exceeds the cap (`GasFloorMoreThanGasLimit`); +- it is sent from the live system address and does not have the system shape (see [The Live System Address](#17-the-live-system-address)); +- it carries a chain id that is not the chain's, or it is not a legacy transaction and carries none; a legacy transaction without a chain id (pre-[EIP-155](https://eips.ethereum.org/EIPS/eip-155)) is valid, unless it is a Mega System Transaction (see [The Live System Address](#17-the-live-system-address)). + The check is part of the spec, not of a node's configuration: a node MUST make it whatever its configuration says; +- it is a Mega System Transaction that fails the chain-id, nonce or EIP-3607 check; +- it fails any inherited validation. + +A deposit MUST NOT be rejected for failing a validation check: a deposit that fails any of these checks MUST be included as a failed deposit instead, which bumps its sender's nonce, credits its mint, uses its whole gas limit and applies nothing else. +A read the node fails to make is not a validation check, for a deposit as for any transaction (below). +A Mega System Transaction is a legacy transaction until it passes its own chain-id, nonce and EIP-3607 checks, so failing one of those is a rejection; once it passes them it runs as a deposit, and a check it fails after that includes it as a failed deposit. +A failed deposit — one that fails a check, or whose execution halts — reports its whole gas limit as regular gas, and no state gas and no history gas on any ledger, the transaction's or the block's: the caller account it creates for a sender that did not exist carries no state gas, unlike the one a deposit that runs to a success or a revert creates (see [The Revert-Class Stop](#11-the-revert-class-stop)). + +A transaction MUST be skipped for the current block, and MAY be included in a later one, when: + +- its declared gas limit does not fit in the block's remaining gas; +- its data-availability footprint does not fit in what the block's gas limit has left for footprints; +- it is neither a deposit nor a Mega System Transaction and the block has reached its data-size limit; +- it is not a deposit and the block activates Satin or an Optimism fork at or after Jovian in the Optimism fork order, as the chain configuration schedules it (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)). + +A block that contains a transaction it should have skipped is invalid. + +A block builder MAY also skip a transaction other than a deposit or a Mega System Transaction under its own building policy (see [Block Limits](#20-block-limits)): a per-transaction declared-gas, encoded-size or data-availability limit, a block encoded-size or data-availability budget, or the block's data-size limit held below the protocol's value. +A transaction over a builder's per-transaction limit never fits that builder's blocks, and the builder MAY drop it. +A block is not invalid for a transaction a building policy would have skipped. + +A transaction MUST be included with a failed receipt when it reverts, halts, or its own frame is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). +A failed bucket-capacity read or database read is a fault of the node, never an outcome of the transaction, for a deposit as for any transaction: the transaction gets no outcome and MUST NOT be settled, as a failed deposit or otherwise. +The node MUST report the failure as an internal error with its cause: a failed bucket-capacity read always; a failed database read the transaction's execution makes when the node's database declares the error fatal, and otherwise as an invalid-block verdict, as for a pre-block call (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); and a failed read block execution makes for the transaction outside its execution — the L1 block contract's account and footprint gas scalar before a non-deposit transaction, a transaction's sender's account before the transaction runs — always, as the activation check's is. +A node that meets the failure cannot execute the block past that transaction: it reaches no verdict on the block, except that a non-fatal database error met inside the transaction's execution is reported as an invalid block (above); a builder, which has no outcome to include for that transaction, MAY leave a non-deposit transaction out of the block it builds, but a deposit MUST be included, so the block that must hold it cannot be built while the read fails. + +A block MUST be invalid when: + +- a pre-block call does not succeed (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); +- it is the block in which Satin activates, and a system-contract address or the factory's does not hold the code Satin expects (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); +- it contains a transaction the rules above skip. + +### 22. The Stateless Witness + +#### Previous behavior + +- Block execution exported the SALT bucket ids of one cache, reset once per block, and the buckets a keyless deployment's sandbox asked about were never merged into it; the block hashes a block read were whatever its state cache held, which may include hashes an earlier block read. +- The node collected the pre-block states through a state hook it installed on block execution. +- The L1 block info a block's transactions were priced against was read on the block's state and landed in no state a node collects. +- The oracle service's answers were known only to the node's own service, which sees every candidate the builder executes, included or not. + +#### New behavior + +A stateless validator re-executes a block from a witness of what the block read. +The witness is defined by what the block's execution returns and exports, and a node building it and a validator consuming it MUST agree on the following. + +- **The witness.** + A block's witness holds: + - every account and every storage slot the block loads, in a pre-block step or in a transaction the block includes, as the chain held it before the block — an absent account recorded as absent, an empty slot of an account the chain holds as zero, and no slot of an absent account — and the code the chain held for every such account before the block, whether or not the load that named the account loaded its code; + - the hash of every block `BLOCKHASH` read, which the block's execution exports; + - the capacity of every SALT bucket the block's execution exports; + - the oracle service's answer to every oracle read the block's included transactions recorded, in block order. + A transaction loads every account and slot its execution reads from the state: in its validation (the registry's account and system-address slot every transaction reads included), in its fee settlement, and in any of its frames, a frame that reverted or halted included, and a frame of a deposit that failed. + A failed frame's writes are taken back, not its reads; a failed deposit takes back everything but its sender's nonce bump and mint, not its reads; and a validator re-executing the transaction makes the same reads in the same frames. + The one exception is the L1 block info the transaction is priced against, which the pre-block phase loads for the whole block (see the L1 block info, below). + A read that gas or a limit skipped loads nothing (see the reads a validator makes again, below). + Execution reports what it loaded in the states the block commits: a pre-block step in the state it commits on its own, and a transaction in its returned state, which the block commits and which names every account and slot the transaction loaded, whether it wrote it or not, whether the frame that loaded it succeeded or not, and, for a deposit, whether the deposit failed or not. + The set is a function of those states and the exports alone, not of how the node caches state: a node that serves a block's execution from a state cache another block filled builds the same witness, because the states name what was loaded whether or not a database was asked for it. + A state names the keys; the values are the chain's. + A slot of an account the chain does not hold before the block is not recorded: such an account has no storage, and a validator MUST answer every slot of it with zero without looking it up. + The code in particular is not the code a returned state carries: a transaction that replaces an account's code — an EIP-7702 authority delegated anew — is admitted against the code the chain held, and its returned state carries the code it wrote. +- **What the block reads, and where it lands.** + A transaction's loads are in its returned state: its sender, its recipient or created address, every account and every slot any of its frames loads, the fee recipients, the registry's account and system-address slot every transaction reads, and a keyless deployment's signer and deploy address; the state names an account whether or not the load brought its code. + The pre-block phase's reads land in the states it commits, one per step, in order: the two EIP calls' states, in Satin's activation block each predeploy's read-only entry, the registry's pending slots the due-change decision read, the `applyPendingChanges()` call's state, and last the L1 block info. + Each state is committed whole, read-only entries included, and a node MUST collect the states as they are committed: what a commit keeps of a state is only what it changed, which holds none of the read-only entries. + `BLOCKHASH` reads the chain's history outside the journal and its reads are exported; a SALT bucket's capacity and the oracle service's answer are read outside the database and are exported or recorded. + The header, the chain configuration — the schedule — the parent hash, the parent beacon block root, the extra data, whether the block admits only deposits (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)), whether Satin activates in it, and the block's slot number are inputs a validator is given beside the witness. + `SLOTNUM` pushes the slot number the node supplies, so a validator MUST be given the number the building node supplied, zero included. +- **The L1 block info.** + A non-deposit transaction is priced against the L1 block contract (`0x4200000000000000000000000000000000000015`): its L1 base fee slot (1), its Ecotone fee scalars slot (3), its Ecotone blob base fee slot (7), its operator fee scalars slot (8), which also holds the DA footprint gas scalar, and, only when the Ecotone scalars are empty (the blob base fee scalar and the eight bytes of the two scalars zero), its L1 fee overhead slot (5). + These reads are made on the block's state, not through a transaction's journal, so they land in no transaction's returned state. + None is made before the block's first non-deposit transaction other than a Mega System Transaction, and each finds the state the transactions before it left: whether the overhead is read is decided by the scalars they left, not by the scalars the chain held before the block, and a deposit that empties the scalars names no overhead in its returned state. + The pre-block phase MUST therefore read the contract's account and all five slots, whatever the scalars it reads hold, and commit them as a state of their own, of read-only entries, after every other pre-block step. + Every OP chain holds the contract from genesis; a state that does not, such as a test's, records the account as not existing and reads no slot. + A witness so holds the overhead of a block that never reads it again, and a block cannot be executed on a state that cannot serve the contract's account or one of the five slots, whether or not a transaction would have been priced with it: the failure is an internal error of the node, not a verdict on the block, and for a stateless validator a defect of the witness it was given. + The read changes nothing: the entries are not written, and a transaction finds the same values, or the ones the block's L1 attributes deposit wrote over them, which are in that deposit's own returned state. +- **The reads a validator makes again.** + A read that gas or a limit skipped is skipped again on replay, so the witness need not carry it: a cold `SLOAD` or account load with less gas than the cold surcharge, a `BLOCKHASH` of the current block or outside the last 256 blocks, an oracle read the frame cannot pay, a read a frame whose volatile-data access is off is refused, a keyless deployment's reads after a rule refused it, and the bucket of a charge a system-originated transaction or a system call makes. +- **The SALT buckets.** + Block execution exports the set of SALT buckets the SALT environment answered with a valid capacity during the block, emptied when the block starts and accumulated over everything executed for the block. + A bucket is in the set once it was answered with a valid capacity, whether or not the transaction that asked is in the block: a candidate the builder executed and dropped leaves its buckets in the set, which a validator does not need. + A lookup that failed MUST NOT be in the set, whether the environment could not answer it or answered a capacity below `MIN_BUCKET_SIZE`: it is a fault of the node, including for a deposit: its transaction gets no outcome, and the node that meets it can neither build nor validate a block holding that transaction while the lookup fails (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + A witness MUST prove the capacity of every bucket in the set. + The set is complete for the transactions the block's own execution ran: a bucket is asked about at a state charge site and nowhere else, and a validator re-executing the block's transactions reaches the same charge sites. + A node that runs the block's transactions on several executions, or that empties the set between transactions, MUST take the union of what each reports; a transaction executed elsewhere and committed into the block adds nothing to the set of the execution it was committed into. + The pre-block calls and the system transactions price at the minimum bucket and add none. +- **The block hashes.** + Block execution exports every hash `BLOCKHASH` was served, emptied when the block starts. + It is not what a node's state cache holds, which may carry hashes an earlier block read. +- **The oracle.** + An `SLOAD` in the Oracle's own frame loads the chain's slot, which is in the transaction's returned state and so in the witness, then takes the service's answer over it. + The answer is in no database. + The engine records every read a transaction makes through the service, with the answer, in order, on the transaction's outcome; an answer can be none, where the service had no value and the slot's loaded value stood. + A node MUST take the oracle reads of the transactions it includes from their outcomes, in block order, and nothing of a candidate it executed and dropped. + A validator MUST do one of the following: + - be given those records, and answer each read its own execution makes from them, in order; or + - run no service, and find each answer in the Oracle's slot at its read — the value the journal holds for the slot when the read is made, as the block's earlier included transactions and the reading transaction's own frames left it. + This reproduces the block only when every answer an included transaction recorded equals the slot's value at that read; an answer of none always does. + Meeting it is the node's to arrange, by including a transaction that writes every value its service answers into the Oracle's storage before the transaction that reads it. + It cannot always be arranged: one transaction can be answered two values for one slot — it reads the slot, sends a hint that has the service fetch another value, and reads the slot again — and only the system address writes the Oracle's storage, so a transaction the system address does not send finds one value in the slot at both reads, and no value the slot can hold reproduces both. + A node that serves validators running no service MUST either give them the included transactions' own records, as the first option has it, or leave out of the block every transaction whose recorded answers the slot cannot hold at its reads. + A validator without a service that finds another value in the slot computes another block; a transaction that wrote the value but was dropped by the builder wrote nothing the chain holds. + Hints reach the service alone: they are not in the witness, and change nothing a validator computes except through the answers the service then gives, which the records carry. +- **The check.** + A block replayed on exactly its witness MUST produce the same receipts, state changes, gas ledgers, logs, block counters and exports as the block's execution, and MUST read nothing the witness does not hold. + +## Developer Impact + +Gas numbers move for every transaction. +At the minimum bucket: an empty call uses 42,280 gas (15,000 regular and 27,280 history), a transfer to an existing account 51,800, a fresh `SSTORE` 155,826 (97,920 of it state gas), a `LOG1` with 32 bytes of data about 51,750, and a value `CALL` that creates its recipient about 244,940 (183,600 of it state gas); the last two move by a few gas with the code that sets them up. +Calldata, logs and deployed code cost 88 gas per byte of history; a fresh slot or account costs state gas even in a minimum-size bucket, and `m` times that in a bucket `m` times larger. + +Gas limits above 200,000,000 behave differently: at most 200,000,000, less the intrinsic regular gas, is available to computation and `GAS`, and the rest can pay only state and history gas. +A contract that checks `gasleft()` against a large constant sees at most the regular budget. + +A frame stopped by a resource limit or by gas detention now reverts rather than halting the transaction, with `MegaLimitExceeded(kind, limit)` as its output: its caller sees a failed call whose return data is the stop, and can catch it and carry on within what the limits leave. +A transaction whose own frame is stopped reverts with the stop, and its sender pays only for what ran. +No KV-update or state-growth limit stops a transaction, so kinds 1 and 3 are never reported. +A transaction that reads volatile data is still held to its compute at the read plus the cap (20,000,000), but until a regular charge needs gas past that limit, `GAS`, call forwarding and state or history charges see its whole gas, and the stop is a revert of the frame that makes that charge. +`VolatileDataAccessDisabled` can carry the value 12 (`SLOTNUM`), which a Solidity handler must decode as a `uint8`. + +Every movement of value to another account now emits a `Transfer` log from `0xff…fe`, which indexers see in receipts beside the contracts' own logs; a `CALLCODE`, a call to oneself, a deposit's mint and a self-destruct to oneself emit none. + +A `keylessDeploy` constructor now sees the transaction's `ORIGIN` and `GASPRICE` and runs one call level deeper than the same initcode in a creation transaction; `gasUsed` counts no intrinsic gas. +The call pays 183,600 × `m` of state gas for an empty signer's account, where Rex6 charged 25,000 × (`m` − 1) of storage gas. +A signer at nonce 1 stays at 1 whether its deployment succeeds or fails, so an attempt by anyone whose creation reverts, halts or is stopped cannot make its address undeployable; only a delegated signer whose own code spends a nonce during the creation moves past it. +A creation that returns empty code for the deploy address is refused its empty deposit and reverts, where Rex6 let it complete and leave the address occupied: the call answers `EmptyCodeDeployed`, the creation's logs and writes are dropped, and the address stays deployable. +Whether a constructor returns empty code is the signed initcode's own behaviour on what it runs in, and whoever submits the deployment chooses part of that: the gas forwarded above the signed gas limit, the outer transaction, and the block and state it runs in. +`IKeylessDeploy` no longer declares `ParentBudgetExceeded`, `InvalidTransaction`, `InsufficientComputeGas` and `InternalError`, so a decoder built from the Satin interface does not name them in `errorData` a Rex6 block produced. + +A `receive()` hook reached through Solidity's `transfer()` can emit one three-topic event with one word of data from the history allowance; a second event must be paid from the 2,300-gas stipend and cannot be. + +### Node integrators + +A node, a stateless validator and a replay tool must agree on everything below, or they execute different chains. + +- **The execution configuration.** + The spec fixes part of the configuration a transaction runs on, whatever a node supplies: the Satin gas schedule, EIP-8037, EIP-2780 and EIP-7708 on, the 200,000,000 execution cap, the chain-id check on, and the 512 KiB and 1 MiB code-size limits. + A node build must not enable the `mega-evm/satin-price-override` feature (it reads `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` at run time). + A node that reads the configuration before it executes anything — gas estimation reads the execution cap — must read these values, not its own. + The limits are fixed by the spec too (see [Resource Limits](#10-resource-limits) and [Block Limits](#20-block-limits)): a node passes none of them, neither in its chain configuration nor with a block, and the reference implementation holds a block's transactions, and, unless the node chooses otherwise as its own policy, an execution outside a block — a call, a gas estimate — to the same values without being told, so by default a node's calls and estimates stop what its blocks stop. +- **Precompiles.** + A node adds or replaces a precompile only through `MegaEvm::with_dyn_precompiles` or the factory's precompile builder. + The engine prices a call to a Satin precompile from its own table, by the precompile's identifier, so a set put in place around those two routes, through the mutable access to the precompile map that revm and alloy-evm expose, keeps the Satin prices for every entry that carries a Satin identifier: gas detention then decides a call from a price the replacing precompile does not charge. +- **What a transaction pool can check without state.** + The body, with `WRITE_RECORD_SIZE` bytes for each entry of the authorization list, must fit the transaction's data-size limit, and the chain id must be the chain's, a typed transaction's included; neither depends on the node's configuration. + The gas limit must cover the intrinsic regular gas (EIP-2780's base and recipient and value charges, calldata, access list, authorizations, init code) plus the history gas of the transaction's body, and the calldata floor; above the execution cap, the intrinsic regular gas and the floor must fit under the cap. + A transaction from the live system address without the system shape is refused too. + The reference implementation reports the body-size refusal (`TX_BODY_OVER_DATA_SIZE_LIMIT`) and the system-shape refusal as invalid-transaction errors with fixed messages, which a pool maps to its own error. + The rest of the stateless validation is the base layer's. + Whether a recipient, a created account or an authority is new is the state's to say: EIP-2780 charges it when the transaction runs, and a gas limit that cannot pay it runs out of gas rather than being refused. + The history of the write records a transaction's start makes is charged when it runs too: one record for the recipient of its value (none for value sent to the sender itself or to an authority it applied) or the account it creates, and one for each authority that applies other than the sender. + So the least gas limit validation admits is not what a transaction needs: at that gas limit a transfer of value to another account runs out of gas on its recipient's record, and one to a new account needs that account's state gas as well. + A deposit and a Mega System Transaction pay no history gas; a pool that recognizes the latter, and refuses a transaction from the live system address without the system shape, needs the live system address from the state. + That address changes only in a block's pre-block step and then holds for the whole block, so a pool reads it again for every block, from the state after that block's pre-block changes. + An address read from another state treats the old system address's transactions as the protocol's and the new one's as a user's, or the reverse. + A deposit is never refused for failing validation: one that fails validation is included as a failed deposit, which bumps its sender's nonce and uses its whole gas limit. + A bucket or database read the node fails to make is not a validation failure, for a deposit either: the transaction gets no outcome; a failed bucket read, a database error the database declares fatal, or any database error on a read block execution makes around the transaction is an internal error of the node, while any other database error the transaction's execution meets makes the block invalid; a builder, which has no outcome to include for that transaction, may then leave a non-deposit transaction out, but cannot build a block that must hold the deposit while the read fails. +- **Activation blocks.** + Block execution does not work out whether a block admits only deposits: it is told, and refuses a non-deposit transaction only when told so. + The chain's rule is therefore enforced by the nodes that derive and build the chain, not by the executor alone: MegaETH's op-node MUST enforce deposit-only activation blocks for Satin and for every later MegaETH fork, and a block builder MUST compute the flag from the MegaETH schedule, since a node that knows only the Optimism schedule cannot tell that Satin activates. + A node works it out from its configuration and the parent block's timestamp — whether a MegaETH fork, Satin itself, or an Optimism fork at or after Jovian in the Optimism fork order, is active at the block's timestamp and not at the parent's (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)) — for every block it builds and every block it validates, and a stateless validator is given it beside the witness. + An execution that is not told runs the block as one that admits non-deposit transactions, and accepts one in an activation block, which makes the block invalid. + It is told separately whether Satin activates in the block (`MegaBlockExecutionCtx::satin_activation_block`, from `MegaHardforks::is_satin_activation_block` and the parent's timestamp), which has it check the predeploys (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)): the two flags differ, since an Optimism fork's activation block admits only deposits too. + An execution that is not told checks no predeploy, and runs on a state that may lack them. +- **The L1 block information.** + Block execution reads the L1 block contract at the block's first non-deposit transaction other than a Mega System Transaction, after the block's L1 attributes deposit wrote it, unless the node handed it the information for this block beforehand, which it then prices with, the footprint gas scalar aside; a node that hands it over must hand over what that deposit writes, so that the block's transactions are priced as [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka) requires. +- **The witness.** + A node builds a block's witness from the states the block commits, in order: each pre-block step's state, committed on its own, read-only entries included, then each included transaction's returned state (see [The Stateless Witness](#22-the-stateless-witness)). + The reference implementation commits them through the database's commit, so a hook on that commit — revm's `State::set_state_hook` — receives each state whole; the block's transitions and bundle keep only what a state changed, and a witness taken from them misses the activation block's predeploys, the registry's pending slots and the L1 block info. + Block execution hands the pre-block states to nothing else. +- **The predeploys.** + Satin runs on a chain that ran the legacy forks: Rex5 deployed the SequencerRegistry and upgraded the Oracle to 2.0.0, and Rex6 upgraded the SequencerRegistry to 2.0.0, so the chain holds the six system contracts at the versions Satin runs, and OP's genesis tooling gave it the EIP-7997 factory. + Satin's activation block checks that they are there and is invalid otherwise (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); it deploys, upgrades and seeds nothing, so a chain must have run a Rex6 block before `satinTime`. + The registry's roles are what it holds: the legacy forks' own configuration keys (`rex5InitialSequencer`, `rex5InitialAdmin`, `rex6MinRotationDelay`) seeded it, and Satin reads none of those keys. +- **Committing a delayed outcome.** + A builder that executes a transaction and commits it after other commits MUST commit through the checked commit (`commit_transaction_outcome`), which refuses an outcome whose sender's nonce or balance another commit moved (see [Block Limits](#20-block-limits)). + The refusal is an internal error of the node (`MegaBlockExecutionError::StaleOutcome`), not a verdict on the block or the transaction: the builder executes the transaction again. +- **Packing a Mega System Transaction.** + A block's data-size budget and a builder's policy never refuse one (see [Block Limits](#20-block-limits)), so a builder has no reason to skip it for either and requeue the transaction that triggered it; the block gas limit and the data-availability footprint still hold it, and a builder keeps room for both. + The execution result tells a node which transactions the block treated so: `MegaBlockTxResult::is_system_transaction`, beside `is_deposit`, which stays the envelope's. +- **Reporting a limit stop.** + A stop is a revert whose output is `MegaLimitExceeded(kind, limit)`, and a contract can revert with the same bytes, as can a caller that re-raises the stop a frame below it returned. + Execution reports the crossing that produced the result of the transaction's own frame — the transaction's data-size limit, gas detention's compute limit, or that frame's own data-size budget — and none when that result is not the stop's revert; a node must read that report, and must not infer a stop from the output alone. + A stop a caller caught produced no result of the transaction's own frame: the transaction reports none, and it can succeed, so a node maps an RPC error or a builder's handling of a stopped transaction from that report alone (`LimitStop::from_result`, or `MegaTransactionOutcome::limit_stop`), never from the output bytes. +- **The chain configuration.** + A genesis file's `config` object carries Satin as one key beside the other forks'. + + | Key | Value | + | ----------- | ------------------------------------ | + | `satinTime` | The activation timestamp, an integer | + + Satin carries no parameter. + No key names a limit: the limits are the spec's (see [Resource Limits](#10-resource-limits)). + No key names the `SequencerRegistry`'s roles either: the registry is the one the legacy forks left (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). + A key that starts with `satin`, in any ASCII letter case, and is not `satinTime` exactly is refused, so a file written against an earlier version of the format, which named the registry's roles (`satinInitialSystemAddress`, `satinInitialSequencer`, `satinInitialAdmin`, `satinMinRotationDelay`), `satinInitialFromBlock` or the limits, does not load, whether or not it carries `satinTime`. + A key given twice is refused only where the reader still sees both copies, as a parser handed the object's text does; a reader that first parses the file into a JSON value, as the reference CLI and a node do, sees only the last copy and reads it. + `satinTime` is a JSON number up to 2^64 − 1. + The key format is provisional until a network publishes a genesis file carrying it. + + The Satin key does not time the forks Satin runs on: Optimism Karst and the Ethereum forks it includes, Osaka among them, are timed by the configuration's own keys for them, and a node must check their timing against `satinTime` both ways when it loads the configuration. + Each of those forks must be active by `satinTime`: every Satin block executes on Karst's rules, and a Satin block before one of them would be executed on rules the node's own schedule does not apply to it. + The reference implementation's schedule check refuses a schedule in which an Ethereum fork from Shanghai to Osaka or an Optimism fork from Regolith to Karst is not active at `satinTime`, so a node that runs that check on the schedule it builds from the file has this half. + Jovian, Karst and Osaka must not activate before `satinTime` either, since every earlier block executes on Rex6's rules, which build on Isthmus whatever the configuration times those forks at; their times in the configuration must equal `satinTime`, and a node must refuse a configuration that activates one of them earlier, a half the reference implementation does not check. + The reference implementation reads only the chain id and the Satin key and builds a schedule in which every base fork is active by `satinTime` — it places them at genesis, which no Satin block can tell apart, since Satin never asks the schedule about a block before `satinTime` — and runs every Satin block on Karst's rules, the pre-block calls the node's schedule gates among them, whatever the file times Karst at. + +## Safety and Compatibility + +Satin changes nothing about blocks under earlier specs: a node replaying history resolves each block's spec from its timestamp and applies that spec's rules. +Satin is a restatement rather than a delta, so a Rex6 rule this page does not carry over — the compute-gas limit, the storage-gas formulas, the sandbox, the 98/100 forwarding, the cold first touch of preload-warm addresses — does not apply to Satin blocks. + +The six system contracts keep their Rex6 bytecode and ABI, but for the four errors `IKeylessDeploy` no longer declares; Satin deploys and upgrades none of them, and its activation block refuses a chain that does not hold them, and the EIP-7997 factory, at the versions Rex6 left. +A transaction from the live system address without the system shape is refused, as in Rex6, now as an invalid transaction: a deposit from the system address, which Rex6 refused with an error that left its block unexecutable, is a failed deposit, so the engine no longer depends on the L1 portal refusing deposits from each system address a rotation installs. + +The per-transaction and block limits and the detention caps are protocol values fixed by the spec, not chain configuration, so every node executing any chain holds its Satin blocks to the same ones: the data-size limits at 13,107,200 bytes and the detention caps at 20,000,000 each. +No chain can set a limit that stops the block's L1 attributes deposit, whose data size is its body, its calldata and a write record for each slot of the L1 block contract it changes: 526 bytes on recorded mainnet blocks within one L1 origin. +The per-transaction gas-limit, encoded-size and data-availability limits are a block builder's policy, not the chain's: a node validating a block does not apply them. + +Satin is unstable and not scheduled on any network: its prices, limits and rules may change in either direction until it is frozen. + +## References + +- [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) — state gas and the reservoir. +- [EIP-2780](https://eips.ethereum.org/EIPS/eip-2780) — the decomposed intrinsic cost. +- [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) — the state-access prices. +- [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) — transfer logs. +- [EIP-7997](https://eips.ethereum.org/EIPS/eip-7997) — the deterministic `CREATE2` factory. +- [EIP-8024](https://eips.ethereum.org/EIPS/eip-8024) and [EIP-7843](https://eips.ethereum.org/EIPS/eip-7843) — `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM`. +- [Rex6 Network Upgrade](rex6.md) — the behavior every Previous behavior above describes. +- [Dual Gas Model](../evm/dual-gas-model.md), [Resource Limits](../evm/resource-limits.md), [Resource Accounting](../evm/resource-accounting.md), [Gas Detention](../evm/gas-detention.md) — the Rex6 mechanisms Satin replaces. +- [KeylessDeploy](../system-contracts/keyless-deploy.md), [MegaAccessControl](../system-contracts/mega-access-control.md), [MegaLimitControl](../system-contracts/mega-limit-control.md), [Oracle](../system-contracts/oracle.md), [SequencerRegistry](../system-contracts/sequencer-registry.md), [Mega System Transactions](../system-contracts/system-tx.md) — the system contracts. +- [Hardforks and Specs](../hardfork-spec.md) — how specs are versioned, frozen, and activated. +- [mega-evm](https://github.com/megaeth-labs/mega-evm) — reference implementation. diff --git a/mutants/README.md b/mutants/README.md index 776d89b47..713a61683 100644 --- a/mutants/README.md +++ b/mutants/README.md @@ -12,6 +12,9 @@ Two scopes, mutated and gated separately: The two scopes are disjoint; a mutant belongs to exactly one of them. +The infrastructure job runs nightly, and on a pull request only when it changes `.cargo/mutants-infra.toml`, the scenario runner, `scripts/mutation_test.sh` or `scripts/mutation_gate.py` (the `infra` path filter in `.github/workflows/mutation.yml`). +It never reads `.cargo/mutants.toml`, and a change to `mutants/suppressions.toml` alone does not start it on a pull request: the suppression-hygiene job and the nightly run cover that file. + ## Layout | Path | Purpose | @@ -29,7 +32,7 @@ The two scopes are disjoint; a mutant belongs to exactly one of them. # Mutate only what your branch changed (what CI runs on a PR): scripts/mutation_test.sh diff origin/main python3 scripts/mutation_gate.py report --results target/mutants/mutants.out \ - --suppressions mutants/suppressions.toml + --recheck target/mutants/recheck/mutants.out --suppressions mutants/suppressions.toml # One subsystem while iterating: scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' @@ -37,13 +40,14 @@ scripts/mutation_test.sh file 'crates/mega-evm/src/limit/**' # The infrastructure scope (its own output directory, so it does not overwrite the production run): OUT_DIR=target/mutants-infra scripts/mutation_test.sh infra python3 scripts/mutation_gate.py report --results target/mutants-infra/mutants.out \ - --suppressions mutants/suppressions.toml + --recheck target/mutants-infra/recheck/mutants.out --suppressions mutants/suppressions.toml # Shard k of n of a large run (cargo-mutants' --shard), each into its own directory: MUTANTS_SHARD=0/4 OUT_DIR=target/mutants-0 scripts/mutation_test.sh diff origin/main ``` -The driver needs bash 4 or later and Python 3.11 or later on `PATH`; with the macOS defaults (bash 3.2, Python 3.9) it fails before mutating anything. +The driver needs bash 5 or later and Python 3.11 or later on `PATH`; it refuses to start under an older bash (macOS's `/bin/bash` is 3.2), and under an older Python (macOS's `python3` is 3.9) the gate's scripts say so and exit before anything is mutated. +The gate's own tests run with `python3 -m unittest discover -s scripts -p 'test_*.py'`, on the same Python; an older one runs a single test in their place, which fails with the reason. When to shard is in `REVIEW.md` (Test gates, Mutation testing). ## The gate @@ -53,6 +57,18 @@ Policy is **no new survivors**: if a mutant on changed code survives and is not To pass, either add a test that kills it, or — only if it is provably equivalent/dead — add a justified entry to `suppressions.toml`. The reported mutation score is informational. +The gate reads a run **fail-closed**: it scores `outcomes.json`, and only a run that finished, whose baseline succeeded, and whose every selected mutant has an outcome. +cargo-mutants rewrites `outcomes.json` after every outcome, so a run that stops part way leaves one that looks whole; the gate reads completion from the two things the producer writes for it. +One is `end_time`, which stays null until the run finishes. +The other is `mutants.json`, the selection written before any mutant is tested, which the outcomes must name exactly. +`total_mutants` counts the outcomes recorded so far, not the mutants selected, and the gate does not read it. +Missing results, a run that did not finish, a missing or failed baseline, or a selected mutant without an outcome fail the gate with the reason, instead of reading as nothing to test. +A run that tested nothing passes only on the producer's own word for it: cargo-mutants' empty `mutants.json` when its filters leave no mutant, or, when `--in-diff` leaves none and cargo-mutants writes no results at all, the line it printed saying so, which the driver records in `no-mutants.txt`. + +A mutant that **timed out** was tested beside the others the run tests at once, each running the whole suite on the same cores, so the driver re-runs every unsuppressed one once, alone (`--jobs 1`, into `recheck/mutants.out`), and the gate takes that outcome for it. +One caught alone is caught, one that survives alone is a survivor, and one that times out again stays inconclusive and fails the gate. +A re-check that exits abnormally proves nothing by the files it left, so the driver records its exit in its results (`run-failed.txt`), and the gate refuses to score them, saying why. + ## Suppressions (hybrid) A survivor that is *not* a real gap (an **equivalent mutant** that can't change behavior, or dead/defensive code) is recorded in `suppressions.toml` with a justification and reviewer. @@ -81,12 +97,13 @@ Run the `improve-mutation-score` skill: it triages each survivor (equivalent vs. cargo-mutants applies a fixed, generic operator set and cannot be extended. To mutate mega-evm-specific constructs — starting with **spec gates**, the lever for backward-compatibility — there is a second engine built on [universalmutator](https://github.com/agroce/universalmutator) in `--comby` mode. -The two engines are complementary and **share one gate**: both produce the `caught.txt`/`missed.txt` file contract that `scripts/mutation_gate.py` scores, so suppressions, the PR comment, and the exit code are identical for both. +The two engines are complementary and **share one gate**: both write `outcomes.json` in cargo-mutants' shape, with the `caught.txt`/`missed.txt` lists beside it, which `scripts/mutation_gate.py` scores, so suppressions, the PR comment, and the exit code are identical for both. +`umutate.py` keeps the same completion contract: it writes `mutants.json` with every mutant it selected before it tests any, and `outcomes.json`, with its `end_time`, only once every one has an outcome. ``` cargo-mutants ─(mutation_test.sh)─┐ - ├─► caught.txt / missed.txt ─► mutation_gate.py ─► gate -custom packs ─(umutate.py)────────┘ (shared contract) (shared) + ├─► outcomes.json ─► mutation_gate.py ─► gate +custom packs ─(umutate.py)────────┘ (shared contract) (shared) ``` ## Operator packs @@ -148,4 +165,7 @@ python3 scripts/umutate.py run --packs spec-gate --diff origin/main --output tar ## Suppressions and CI Spec-gate equivalents (e.g. a gate guarding a state no test exercises — expect a meaningful rate) go in the **same** `suppressions.toml`, as `kind = "line"` entries matching the mutant text, prefixed with the pack name. -The PR gate runs diff-scoped (instant on PRs that touch no gate lines); the full crate sweep runs on a nightly schedule (the `spec-gate-sweep` job in `.github/workflows/mutation.yml`). +A single-spec engine has no spec gate for these operators to mutate, so mutation CI does not run the pack. +The operator pack stays on disk. +Suppression hygiene still plans it and accepts an empty plan. +The commands above run it by hand once a later spec has a gate to mutate. diff --git a/mutants/operators/spec-gate/generate.py b/mutants/operators/spec-gate/generate.py index f6eb55f0d..36f5a43a2 100755 --- a/mutants/operators/spec-gate/generate.py +++ b/mutants/operators/spec-gate/generate.py @@ -32,9 +32,15 @@ from pathlib import Path # The behavior-introducing MegaSpecId progression, oldest -> newest, frozen and -# unstable alike (see crates/mega-evm/src/evm/spec.rs). Keep in spec order. +# unstable alike. Keep in spec order. # This is the *adjacency* universe: it decides which spec sits next to which. # +# It is the legacy engine's ladder, which ends at REX6. SATIN, the unstable spec +# that follows it, is deliberately absent: the engine that runs SATIN is +# single-spec, with no `is_enabled` gate and no per-spec instruction table, so a +# rule naming it could match nothing. When that engine gains its first gate, with +# the spec after SATIN, this list becomes that engine's ladder. +# # The alias rungs (MINI_REX_1, MINI_REX_2) are deliberately absent: is_enabled # gates compare behavior projections, and an alias executes an earlier spec's # behavior instead of introducing its own — on the behavior axis these rungs do @@ -49,11 +55,10 @@ "REX4", "REX5", "REX6", - "REX7", ] -# The specs whose gates may be mutated. Currently everything through REX6 (see -# CLAUDE.md for the current unstable spec). +# The specs whose gates may be mutated. Currently every spec above: every rung of +# the legacy ladder is frozen. # # This is a *subset* of ALL_SPECS, not a replacement for it, and the distinction # matters in both directions: @@ -61,13 +66,14 @@ # * A gate on a frozen spec is the mutation SOURCE — its activation fork is # fixed, so shifting it is a backward-compatibility bug a test must catch. # * The spec shifted TO is only a destination. It may be the unstable spec: -# `is_enabled(REX6) ==> is_enabled(REX7)` is the classic "gated one fork too -# late" regression — it silently disables frozen REX6 behavior on a REX6 -# chain — and is exactly what freezing REX6 promises to catch. +# shifting the newest frozen spec's gate onto the unstable spec above it is +# the classic "gated one fork too late" regression — it silently disables +# frozen behavior on a chain running the frozen spec — and is exactly what +# freezing that spec promises to catch. # # Conflating the two lists drops every mutant whose destination is the unstable # spec, leaving the newest frozen spec's gates probed from one side only. -FROZEN_SPECS = [s for s in ALL_SPECS if s != "REX7"] +FROZEN_SPECS = list(ALL_SPECS) # Per-spec instruction-table modules wired in evm/instructions.rs, in spec order. # diff --git a/mutants/operators/spec-gate/spec-gate.rules b/mutants/operators/spec-gate/spec-gate.rules index a78d0e22e..237a5a723 100644 --- a/mutants/operators/spec-gate/spec-gate.rules +++ b/mutants/operators/spec-gate/spec-gate.rules @@ -19,7 +19,6 @@ is_enabled(MegaSpecId::REX4) ==> is_enabled(MegaSpecId::REX5) is_enabled(MegaSpecId::REX5) ==> is_enabled(MegaSpecId::REX4) is_enabled(MegaSpecId::REX5) ==> is_enabled(MegaSpecId::REX6) is_enabled(MegaSpecId::REX6) ==> is_enabled(MegaSpecId::REX5) -is_enabled(MegaSpecId::REX6) ==> is_enabled(MegaSpecId::REX7) # --- SPEC_MATCH_MISROUTE: reroute a per-spec instruction-table arm --- :[pre~[^_A-Za-z0-9]]mini_rex::instruction_table ==> :[pre]rex::instruction_table diff --git a/mutants/suppressions.toml b/mutants/suppressions.toml index 592ecf856..f92faa38d 100644 --- a/mutants/suppressions.toml +++ b/mutants/suppressions.toml @@ -17,7 +17,11 @@ # missed.txt OR timeout.txt. Use for a single surviving # mutant inside an otherwise-tested function, or to accept # a genuinely non-terminating/equivalent timed-out mutant. -# `mutant` is the literal text (without "file:line:col: "). +# `mutant` is the literal text (without "file:line:col: "), +# or, when several mutants share that text, the full +# "file:line:col: text" line of each one suppressed: a +# bare text that matches more than one mutant fails the +# gate. # # Every entry also carries: # category = "equivalent" | "dead" @@ -58,28 +62,36 @@ mutant = "replace ::external_envs justification = "EmptyExternalEnv is a unit struct; real body builds ExternalEnvs{salt_env:EmptyExternalEnv, oracle_env:EmptyExternalEnv}; from(Default::default()) resolves to Default for ExternalEnvs producing identical fields. Value-identical, no observable behavioral difference." reviewer = "improve-mutation-score (William Aaron Cheung)" -# --- DeterministicHasher::write line-125 `|` combine (equivalent) ------------------ -# `let combined = (value[0] as u128) | ((value[1] as u128) << 64);` where -# `value: [u64; 2] = read_small(data)`. The first operand `value[0] as u128` is a u64 widened -# to u128, so it occupies ONLY bits 0..63 (bits 64..127 are always zero). The second operand -# `(value[1] as u128) << 64` occupies ONLY bits 64..127 (bits 0..63 are always zero). The two +# --- DeterministicHasher::write `|` combines, lines 120 and 125 (equivalent) -------------- +# Both combines have one shape, `(lo as u128) | ((hi as u128) << 64)` with `lo` and `hi` u64: +# line 120 over `front`/`back` (the mid branch, 9..=16 bytes) and line 125 over +# `value: [u64; 2] = read_small(data)` (the small branch, 0..=8 bytes). The first operand is a +# u64 widened to u128, so it occupies ONLY bits 0..63 (bits 64..127 are always zero). The second +# operand `(hi as u128) << 64` occupies ONLY bits 64..127 (bits 0..63 are always zero). The two # operands therefore have DISJOINT set bits for every possible input, so `a | b == a ^ b` -# identically — `|` and `^` agree on all inputs at this site. This is structurally guaranteed +# identically — `|` and `^` agree on all inputs at both sites. This is structurally guaranteed # by the u64->u128 widening + 64-bit shift, independent of the bytes hashed, so no reachable # input distinguishes `|` from `^` here. (Pinning a specific bucket id, e.g. for "hello", # cannot kill it: the combined value — and thus the hash and bucket id — is identical under -# the mutant.) The sibling line-120 `|` combine over `front`/`back<<64` is the same shape but -# is already pinned by `ahash_bucket_id_mid_input_is_pinned`; line 125 is the small-input -# branch and is the equivalent one. +# the mutant.) The `|` -> `&` mutants at the same two sites are not equivalent and are not +# suppressed. [[suppress]] kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/hasher/fallback.rs" -mutant = "replace | with ^ in ::write" +mutant = "crates/mega-evm/src/external/hasher/fallback.rs:120:48: replace | with ^ in ::write" +justification = "Equivalent: `(front as u128) | ((back as u128) << 64)` ORs a u64-widened low half (bits 0..63 only) with a u64-widened high half shifted into bits 64..127 only. The operands have disjoint set bits by construction for every input, so | == ^ identically; no reachable input distinguishes them." +reviewer = "RealiCZ" + +[[suppress]] +kind = "line" +category = "equivalent" +file = "crates/mega-evm/src/external/hasher/fallback.rs" +mutant = "crates/mega-evm/src/external/hasher/fallback.rs:125:47: replace | with ^ in ::write" justification = "Equivalent: `(value[0] as u128) | ((value[1] as u128) << 64)` ORs a u64-widened low half (bits 0..63 only) with a u64-widened high half shifted into bits 64..127 only. The operands have disjoint set bits by construction for every input, so | == ^ identically; no reachable input distinguishes them." reviewer = "improve-mutation-score (William Aaron Cheung)" -# --- DeterministicHasher typed write_uN / update mutants (dead: unreachable from public API) ------- +# --- DeterministicHasher typed write_uN / update mutants (dead outside the unit tests) ------------ # `AHashBucketHasher` — the crate's ONLY public hasher — computes bucket ids via # `hash(bytes)` (hasher/mod.rs), which calls `DeterministicHasher::write(&[u8])` (the slice # write) and `finish()`. The slice `write` routes exclusively through `large_update`; it @@ -87,74 +99,73 @@ reviewer = "improve-mutation-score (William Aaron Cheung)" # # `update` is reached ONLY from `write_u8/u16/u32/u64` (and `write_usize` -> `write_u64`); # those typed `write_uN` methods are reached ONLY through `core::hash::Hasher` trait dispatch. -# `DeterministicHasher` / `RandomState` are `pub(crate)` and are NOT re-exported, so no -# integration test (a separate crate) can construct a hasher and drive the typed writes; and -# a grep of the whole `mega-evm` src confirms ZERO non-test callers of any typed `write_uN`, -# `.update(`, `build_hasher`, `DeterministicHasher`, or `RandomState` outside the hasher -# module itself. The typed methods exist solely to satisfy the `core::hash::Hasher` trait -# contract; they are dead with respect to every reachable code path of the public API. +# `DeterministicHasher` / `RandomState` live in the hasher's private `fallback` module, so no +# integration test (a separate crate) can construct a hasher and drive the typed writes, and no +# non-test code outside the hasher module names them. The typed methods exist solely to satisfy +# the `core::hash::Hasher` trait contract; no bucket id depends on them. # -# Because they are unreachable, mutating them (`write_uN -> ()`, or `^` -> `|`/`&` inside the -# dead `update`) cannot change any observable output of `AHashBucketHasher::bucket_id` (the -# full mega-evm suite is green with each mutant applied). The inline `#[cfg(test)]` unit test -# `test_hasher_typed_write_methods` does exercise them via the crate-internal `RandomState`, -# but the mutation run builds the integration test targets only, so that unit test cannot -# kill them — and the public API offers no path to do so. Recorded here as dead code. +# The mutation run executes the lib's unit tests (nextest over the whole package), so the inline +# unit test `test_hasher_typed_write_methods` does run the typed writes. It asserts only that the +# typed hashes of one value differ from one another and that `write_u64` and `write_usize` +# agree, never what a hash is. It kills `update -> ()` (the typed writes then collide) and +# `write_usize -> ()` (it then differs from `write_u64`), which are not suppressed. The seven +# mutants below keep those relations: applied one at a time, each passes the hasher's unit tests +# and the whole mega-evm lib and test suite. Recorded here as dead code. [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ^ with | in DeterministicHasher::update" -justification = "Dead/unreachable from the public API: AHashBucketHasher::bucket_id drives only the slice write() -> large_update; update() is reached solely via the typed write_uN methods, which are unreachable (pub(crate) DeterministicHasher/RandomState are not re-exported, no integration test can construct them, and zero non-test callers exist crate-wide). The ^->| mutant changes no observable bucket_id output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: bucket_id drives only the slice write() -> large_update, and update() is reached solely via the typed write_uN methods, which no non-test code calls. test_hasher_typed_write_methods runs it but asserts only that the typed hashes differ from one another, which `new_data | buffer` keeps; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ^ with & in DeterministicHasher::update" -justification = "Dead/unreachable from the public API: see the ^->| entry for update — update() is only reached via the unreachable typed write_uN methods. The ^->& mutant changes no observable bucket_id output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: see the ^->| entry for update. test_hasher_typed_write_methods asserts only that the typed hashes differ from one another, which `new_data & buffer` keeps; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ::write_u8 with ()" -justification = "Dead/unreachable from the public API: bucket_id uses only the slice write() -> large_update; write_u8 is reached only via core::hash::Hasher trait dispatch on the pub(crate), non-re-exported DeterministicHasher, which no integration test (or any non-test crate caller) can invoke. Stubbing it to () changes no observable bucket_id output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: bucket_id uses only the slice write() -> large_update, and no non-test code calls write_u8. test_hasher_typed_write_methods calls it but asserts only that its hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ::write_u16 with ()" -justification = "Dead/unreachable from the public API: same as write_u8 — write_u16 is reached only via trait dispatch on the non-re-exported pub(crate) hasher; never on any bucket_id path. Stubbing it to () changes no observable output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: same as write_u8. test_hasher_typed_write_methods asserts only that write_u16's hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ::write_u32 with ()" -justification = "Dead/unreachable from the public API: same as write_u8 — write_u32 is reached only via trait dispatch on the non-re-exported pub(crate) hasher; never on any bucket_id path. Stubbing it to () changes no observable output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: same as write_u8. test_hasher_typed_write_methods asserts only that write_u32's hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ::write_u64 with ()" -justification = "Dead/unreachable from the public API: same as write_u8 — write_u64 (and write_usize, which delegates to it) is reached only via trait dispatch on the non-re-exported pub(crate) hasher; never on any bucket_id path. Stubbing it to () changes no observable output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: same as write_u8; write_usize delegates to it. test_hasher_typed_write_methods asserts only that write_u64 and write_usize agree, which they still do, both hashing nothing; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" [[suppress]] kind = "line" category = "dead" file = "crates/mega-evm/src/external/hasher/fallback.rs" mutant = "replace ::write_u128 with ()" -justification = "Dead/unreachable from the public API: bucket_id's slice write() never delegates to write_u128 (it calls large_update directly); write_u128 is reached only via trait dispatch on the non-re-exported pub(crate) hasher, which no non-test caller invokes. Stubbing it to () changes no observable output." -reviewer = "improve-mutation-score (William Aaron Cheung)" +justification = "Dead outside the unit tests: bucket_id's slice write() calls large_update directly, never write_u128, and no non-test code calls it. test_hasher_typed_write_methods asserts only that its hash differs from the other typed writes', which the hash of an unwritten hasher still does; observed passing the hasher tests and the whole mega-evm suite. Changes no bucket id." +reviewer = "RealiCZ" # --- DeterministicHasher::write line-109 `> 16` -> `>= 16` (equivalent) ------------ # `if data.len() > 16 { large branch } else { mid branch }`. The `>=` mutant only diverges @@ -167,17 +178,16 @@ reviewer = "improve-mutation-score (William Aaron Cheung)" # NO loop pass runs and no extra update happens. # Both paths therefore feed the identical little-endian u128 to a single large_update, yielding # the identical buffer and bucket id. (Pinning a len-16 input cannot kill it; the test -# ahash_bucket_id_len16 was removed for this reason.) The two SIBLING `> 16` -> `>= 16` mutants +# ahash_bucket_id_len16 was removed for this reason.) The two SIBLING `>` -> `>=` mutants # that share this same mutant text — line 108 (`> 8`) and the line-112 loop guard — are NOT -# equivalent and are killed by ahash_bucket_id_len8_boundary_is_pinned / -# ahash_bucket_id_len32_loop_boundary_is_pinned; cargo-mutants reports them CAUGHT, so only the -# line-109 survivor reaches this filter. +# equivalent: under them a len-8 and a len-32 input hash to other bucket ids. They are not +# suppressed; this entry names the line-109 mutant alone. [[suppress]] kind = "line" category = "equivalent" file = "crates/mega-evm/src/external/hasher/fallback.rs" -mutant = "replace > with >= in ::write" -justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs at len == 16, where both the mid branch (front | (back<<64)) and the large branch (read_last_u128, with no loop pass since 16 is not > 16) feed the identical le_u128(bytes[0..16]) to a single large_update. Same buffer, same bucket id; no input distinguishes them. The line-108 and line-112 mutants sharing this text are non-equivalent and are caught by the len-8 / len-32 tests." +mutant = "crates/mega-evm/src/external/hasher/fallback.rs:109:27: replace > with >= in ::write" +justification = "Equivalent (line 109 `> 16`): the > vs >= boundary only differs at len == 16, where both the mid branch (front | (back<<64)) and the large branch (read_last_u128, with no loop pass since 16 is not > 16) feed the identical le_u128(bytes[0..16]) to a single large_update. Same buffer, same bucket id; no input distinguishes them. The line-108 and line-112 mutants sharing this text are non-equivalent and are not suppressed." reviewer = "improve-mutation-score (William Aaron Cheung)" # ───────────────────────────────────────────────────────────────────────────── @@ -233,56 +243,3 @@ file = "crates/mega-evm/src/test_utils/scenario.rs" mutant = "delete field gas_limit from struct BlockEnv expression in Scenario::block" justification = "Equivalent: the field writes u64::MAX and revm 40's BlockEnv::default() already has gas_limit: u64::MAX, so the struct is identical with or without it. test_block_is_fixed_except_for_the_beneficiary pins the value, so the mutant becomes killable the moment the upstream default moves." reviewer = "RealiCZ" - -# ───────────────────────────────────────────────────────────────────────────── -# crates/mega-evm/src/ survivors of the common execution layer. - -# --- inspect_frame_init: logs journaled by frame init (dead while EIP-7708 is off) -------- -# `inspect_frame_init` mirrors revm's: after `frame_init`, the logs journaled since `logs_i` -# (EIP-7708 transfer logs, a precompile's logs) go to the inspector's `log` callback. Satin's -# spec configuration fixes EIP-7708 off (`MegaContext::with_cfg`), and op-revm's precompile set -# journals no log, so frame init never journals one: the length comparisons are always false -# and `inspect_logs` is never entered. Flipping `!=` to `==` would call `inspect_logs` over an -# empty range, a no-op; stubbing it changes nothing reachable. Live again when the Satin gas -# table switches EIP-7708 on, at which point a transfer-log test kills them. -[[suppress]] -kind = "line" -category = "dead" -file = "crates/mega-evm/src/evm/execution.rs" -mutant = "replace != with == in >::inspect_frame_init" -justification = "Dead in Satin: frame init journals no log (EIP-7708 is fixed off by the spec configuration, op-revm's precompiles journal none), so both `logs().len() != logs_i` comparisons are always false; with `==` the call hands the inspector an empty range, a no-op. Becomes live, and killable, when EIP-7708 is switched on." -reviewer = "RealiCZ" - -[[suppress]] -kind = "line" -category = "dead" -file = "crates/mega-evm/src/evm/execution.rs" -mutant = "replace inspect_logs with ()" -justification = "Dead in Satin: only called for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile). Becomes live, and killable, when EIP-7708 is switched on." -reviewer = "RealiCZ" - -# --- DeclaredObserver::log forwarding (dead while EIP-7708 is off) ---------------------- -# revm hands a log to `Inspector::log` (without an interpreter) only from the frame-init path -# above; every log an opcode emits goes to `log_full`, which the forwarding test covers. -[[suppress]] -kind = "line" -category = "dead" -file = "crates/mega-evm/src/evm/inspector.rs" -mutant = "replace for DeclaredObserver>::log with ()" -justification = "Dead in Satin: revm calls `Inspector::log` only for logs journaled by frame init, which Satin never journals (EIP-7708 fixed off, no logging precompile); opcode logs reach `log_full`, which test_declared_observer_forwards_every_callback covers. Becomes live when EIP-7708 is switched on." -reviewer = "RealiCZ" - -# --- AdditionalLimit::discard_stale_record (equivalent) --------------------------------- -# Every wrapper discards a record staged before its opcode on entry. The three wrapped opcodes -# each stage their own record through the Host whenever they complete (SSTORE through -# sstore_skip_cold_load, LOG through log, SELFDESTRUCT through selfdestruct), which overwrites a -# stale one, and a failing opcode's wrapper discards whatever is staged. So a stale record can -# never be committed with or without the entry discard; it is the contract's guard for a future -# wrapped opcode that completes without a Host call. -[[suppress]] -kind = "line" -category = "equivalent" -file = "crates/mega-evm/src/limit/limit.rs" -mutant = "replace AdditionalLimit::discard_stale_record with ()" -justification = "Equivalent: each wrapped opcode (SSTORE, LOG0-4, SELFDESTRUCT) stages its own record through the Host whenever it completes, overwriting a stale one, and a failing opcode's wrapper discards the staged record, so no stale record can be committed with or without the entry discard (test_wrapper_discards_a_stale_record_on_entry shows the stale log is not counted either way)." -reviewer = "RealiCZ" diff --git a/scripts/fuzz_price_monotonic.py b/scripts/fuzz_price_monotonic.py new file mode 100755 index 000000000..1c886747e --- /dev/null +++ b/scripts/fuzz_price_monotonic.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Compare two price records of the fuzz target's `test_property_price_record`. + +Each record is written by the `mega-evm` fuzz target under the `satin-price-override` feature, +with `MEGA_FUZZ_PRICE_RECORD` naming the file, one line per case: + + + +Both records must come from the same seed and case count, so the cases match by index. Where a +case followed the same path at both prices (the same result kind, logs, output and state but for +balances), its state gas must not fall as the cost per state byte rises, nor its history gas as +the cost per history byte rises; its history bytes must be the same, since they are a count. Where +the path differs, a dearer byte may have stopped the transaction sooner, and nothing is implied. + +Usage: fuzz_price_monotonic.py +Exits 1 on the first violation, when the two records do not line up, or when no case was +on the same path at both prices. +""" +import sys + + +def read(path): + rows = {} + with open(path) as f: + for line in f: + parts = line.split() + if len(parts) != 9: + sys.exit(f"{path}: malformed line: {line.rstrip()}") + index = int(parts[0]) + rows[index] = { + "cpsb": int(parts[1]), + "cphb": int(parts[2]), + "kind": parts[3], + "state": int(parts[4]), + "history": int(parts[5]), + "history_bytes": int(parts[6]), + "gas_used": int(parts[7]), + "path": parts[8], + } + return rows + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__) + low, high = read(sys.argv[1]), read(sys.argv[2]) + if low.keys() != high.keys(): + sys.exit("the two records do not hold the same cases: run both with the same seed and case count") + if not low: + sys.exit("the records are empty") + first_low, first_high = next(iter(low.values())), next(iter(high.values())) + if first_low["cpsb"] > first_high["cpsb"] or first_low["cphb"] > first_high["cphb"]: + sys.exit("the first record must be the one at the lower prices") + same_path = 0 + for index in sorted(low): + a, b = low[index], high[index] + if a["kind"] == "refused" or b["kind"] == "refused": + continue + if a["kind"] != b["kind"] or a["path"] != b["path"]: + continue + same_path += 1 + if a["state"] > b["state"]: + sys.exit(f"case {index}: state gas fell from {a['state']} to {b['state']} as the cost per state byte rose") + if a["history"] > b["history"]: + sys.exit(f"case {index}: history gas fell from {a['history']} to {b['history']} as the cost per history byte rose") + if a["history_bytes"] != b["history_bytes"]: + sys.exit(f"case {index}: the history bytes moved from {a['history_bytes']} to {b['history_bytes']} on the same path") + if same_path == 0: + sys.exit(f"{len(low)} cases, none on the same path at both prices") + print(f"{len(low)} cases, {same_path} on the same path at both prices: state and history gas are monotone") + + +if __name__ == "__main__": + main() diff --git a/scripts/keyless_deploy.sh b/scripts/keyless_deploy.sh deleted file mode 100755 index def19ec92..000000000 --- a/scripts/keyless_deploy.sh +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env bash - -# Keyless deployment script for MegaETH -# -# Usage: -# PRIVATE_KEY= ./scripts/keyless_deploy.sh -# -# Environment variables: -# PRIVATE_KEY - Private key of a funded account (required) -# RPC_URL - RPC endpoint (default: http://localhost:8545) -# MEGA_EVME - Path to mega-evme binary (default: mega-evme from PATH) -# FUND_MARGIN - Extra wei to fund above simulated cost (default: 0) - -KEYLESS_TX="${1:?Usage: PRIVATE_KEY= $0 }" -: "${PRIVATE_KEY:?PRIVATE_KEY environment variable is required}" -RPC_URL="${RPC_URL:-http://localhost:8545}" - -SYSTEM_CONTRACT="0x6342000000000000000000000000000000000003" -MEGA_EVME="${MEGA_EVME:-mega-evme}" -FUND_MARGIN="${FUND_MARGIN:-0}" # default 0 ether funding margin -export FOUNDRY_DISABLE_NIGHTLY_WARNING=1 # Suppress foundry nightly warning - -# Check required commands -MISSING=() -for cmd in cast jq python3 "$MEGA_EVME"; do - if ! command -v "$cmd" &>/dev/null; then - MISSING+=("$cmd") - fi -done -if [ ${#MISSING[@]} -ne 0 ]; then - echo "ERROR: Required command(s) not found: ${MISSING[*]}" - echo "Please install them before running this script." - echo "Aborting." - exit 1 -fi - -# Strip 0x prefix if present -KEYLESS_TX="${KEYLESS_TX#0x}" - -echo "=== Keyless Deployment ===" -echo "RPC: $RPC_URL" -echo "mega-evme: $MEGA_EVME" -echo "FUND_MARGIN: $FUND_MARGIN" -echo "" - -# Step 1: Decode the keyless transaction -echo "--- Step 1: Decoding keyless transaction ---" -DECODED=$(cast decode-tx "0x${KEYLESS_TX}" --json) - -SIGNER=$(echo "$DECODED" | jq -r '.signer') -GAS_PRICE=$(echo "$DECODED" | jq -r '.gasPrice') -ORIG_GAS=$(echo "$DECODED" | jq -r '.gas') -TX_VALUE=$(echo "$DECODED" | jq -r '.value') - -# Convert hex values to decimal -GAS_PRICE_DEC=$(cast to-dec "$GAS_PRICE") -ORIG_GAS_DEC=$(cast to-dec "$ORIG_GAS") -TX_VALUE_DEC=$(cast to-dec "$TX_VALUE") - -echo "Signer: $SIGNER" -echo "Gas Price: $GAS_PRICE_DEC wei" -echo "Gas Limit: $ORIG_GAS_DEC" -echo "Value: $TX_VALUE_DEC wei" -echo "" - -# Step 2: Pre-deployment checks -echo "--- Step 2: Pre-deployment checks ---" - -SIGNER_NONCE=$(cast nonce "$SIGNER" --rpc-url "$RPC_URL") -echo "Signer nonce: $SIGNER_NONCE" -if [ "$SIGNER_NONCE" -gt 1 ]; then - echo "ERROR: Signer nonce is $SIGNER_NONCE (must be <= 1). Keyless deploy is permanently disabled." - exit 1 -fi - -EXPECTED_ADDR=$(cast compute-address "$SIGNER" --nonce 0 | grep -oE '0x[0-9a-fA-F]{40}') -echo "Expected deployment address: $EXPECTED_ADDR" - -EXISTING_CODE=$(cast code "$EXPECTED_ADDR" --rpc-url "$RPC_URL") -if [ "$EXISTING_CODE" != "0x" ]; then - EXISTING_HASH=$(cast keccak "$EXISTING_CODE") - echo "ERROR: Contract already exists at $EXPECTED_ADDR (codehash: $EXISTING_HASH)" - exit 1 -fi -echo "No existing code at deployment address (OK)" -echo "" - -# Step 3: Simulate with mega-evme to find gas used -echo "--- Step 3: Simulating with mega-evme ---" - -DUMP_FILE=$(mktemp) -trap "rm -f $DUMP_FILE" EXIT - -SIMULATION_OUTPUT=$("$MEGA_EVME" tx \ - "0x${KEYLESS_TX}" \ - --fork --fork.rpc "$RPC_URL" \ - --sender.balance 1000ether \ - --gas 1000000000 \ - --nonce 0 \ - --spec Rex2 \ - --dump --dump.output "$DUMP_FILE" \ - 2>&1) - -echo "$SIMULATION_OUTPUT" | head -20 - -# Check execution status -STATUS=$(echo "$SIMULATION_OUTPUT" | sed -n 's/.*Status:[[:space:]]\+\([^[:space:]]\+\).*/\1/p') -if [ "$STATUS" != "Success" ]; then - echo "ERROR: Simulation failed with status: $STATUS" - echo "Full output:" - echo "$SIMULATION_OUTPUT" - exit 1 -fi - -# Parse gas_used and contract address from Receipt JSON -RECEIPT_JSON=$(echo "$SIMULATION_OUTPUT" | awk '/=== Receipt ===/{f=1; next} /^===/ && f{exit} f{print}') -GAS_USED=$(echo "$RECEIPT_JSON" | jq -r '.gasUsed') -DEPLOYED_ADDR=$(echo "$RECEIPT_JSON" | jq -r '.contractAddress // empty') - -# Compute actual balance spent from state dump (accounts for L1 data fees) -INITIAL_BALANCE="1000000000000000000000" # 1000 ether in wei -SIGNER_LOWER=$(echo "$SIGNER" | tr '[:upper:]' '[:lower:]') -FINAL_BALANCE_HEX=$(jq -r "to_entries[] | select(.key | ascii_downcase == \"$SIGNER_LOWER\") | .value.balance" "$DUMP_FILE") -FINAL_BALANCE=$(python3 -c "print(int('$FINAL_BALANCE_HEX', 16))") -BALANCE_SPENT=$(python3 -c "print($INITIAL_BALANCE - $FINAL_BALANCE)") - -echo "" -echo "Simulation results:" -echo " Gas used: $GAS_USED" -echo " Deployed address: $DEPLOYED_ADDR" -echo " Balance spent: $BALANCE_SPENT wei" - -if [ -z "$DEPLOYED_ADDR" ] || [ "$DEPLOYED_ADDR" = "null" ]; then - echo "ERROR: Simulation shows deployment would fail (no contract address)" - exit 1 -fi -echo "" - -# Step 4: Compute gasLimitOverride and funding amount -echo "--- Step 4: Computing funding requirements ---" - -GAS_OVERRIDE=$(cast to-dec "$GAS_USED") -FUND_AMOUNT=$(python3 -c "print($BALANCE_SPENT + $FUND_MARGIN)") - -echo "Gas override: $GAS_OVERRIDE" -echo "Fund amount: $FUND_AMOUNT wei ($(python3 -c "print(f'{$FUND_AMOUNT / 10**18:.6f}')") ETH)" -echo "" - -# Step 5: Fund the signer -echo "--- Step 5: Funding signer ---" - -SIGNER_BALANCE=$(cast balance "$SIGNER" --rpc-url "$RPC_URL") -DEFICIT=$(python3 -c "d = $FUND_AMOUNT - $SIGNER_BALANCE; print(d if d > 0 else 0)") - -if [ "$DEFICIT" = "0" ]; then - echo "Signer already has sufficient balance ($SIGNER_BALANCE wei), skipping funding" -else - echo "Signer balance: $SIGNER_BALANCE wei, need $FUND_AMOUNT wei, sending $DEFICIT wei..." - printf "Proceed with funding? [y/N] " - read -r confirm - if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then - echo "Funding aborted by user." - echo "" - echo "=== Funding Transaction ===" - echo "To: $SIGNER" - echo "Value: ${DEFICIT} wei" - exit 1 - fi - set +e - FUND_RESULT=$(cast send "$SIGNER" \ - --value "${DEFICIT}wei" \ - --rpc-url "$RPC_URL" \ - --private-key "$PRIVATE_KEY" \ - --json 2>&1) - FUND_STATUS=$? - set -e - - if [ $FUND_STATUS -ne 0 ]; then - echo "ERROR: Failed to fund signer" - echo "$FUND_RESULT" - exit 1 - fi - FUND_TX=$(echo "$FUND_RESULT" | jq -r '.transactionHash') - echo "Funded successfully (tx: $FUND_TX)" -fi -echo "" - -# Step 6: Perform keyless deployment -echo "--- Step 6: Deploying ---" - -printf "Proceed with deployment? [y/N] " -read -r confirm -if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then - echo "Deployment aborted by user." - echo "" - echo "=== Deployment Transaction ===" - echo "To: $SYSTEM_CONTRACT" - echo "Function: keylessDeploy(bytes,uint256)" - echo "Args: 0x${KEYLESS_TX} $GAS_OVERRIDE" - echo "" - echo "Calldata:" - cast calldata "keylessDeploy(bytes,uint256)" "0x${KEYLESS_TX}" "$GAS_OVERRIDE" - exit 1 -fi - -set +e -DEPLOY_RESULT=$(cast send "$SYSTEM_CONTRACT" \ - "keylessDeploy(bytes,uint256)" \ - "0x${KEYLESS_TX}" "$GAS_OVERRIDE" \ - --rpc-url "$RPC_URL" \ - --private-key "$PRIVATE_KEY" \ - --json 2>&1) -DEPLOY_STATUS=$? -set -e - -if [ $DEPLOY_STATUS -ne 0 ]; then - echo "ERROR: Failed to send deployment transaction" - echo "$DEPLOY_RESULT" - exit 1 -fi -DEPLOY_TX=$(echo "$DEPLOY_RESULT" | jq -r '.transactionHash') -echo "Deploy tx: $DEPLOY_TX" -echo "" - -# Step 7: Verify deployment -echo "--- Step 7: Verifying deployment ---" - -DEPLOYED_CODE=$(cast code "$EXPECTED_ADDR" --rpc-url "$RPC_URL") -if [ "$DEPLOYED_CODE" = "0x" ]; then - echo "ERROR: No code found at $EXPECTED_ADDR after deployment" - exit 1 -fi - -CODE_LEN=$(( (${#DEPLOYED_CODE} - 2) / 2 )) -CODE_HASH=$(cast keccak "$DEPLOYED_CODE") -echo "Contract deployed successfully at $EXPECTED_ADDR ($CODE_LEN bytes, codehash: $CODE_HASH)" diff --git a/scripts/mutation_gate.py b/scripts/mutation_gate.py index f93dfc871..1ea725151 100755 --- a/scripts/mutation_gate.py +++ b/scripts/mutation_gate.py @@ -1,18 +1,58 @@ #!/usr/bin/env python3 -"""Score and gate a cargo-mutants run for mega-evm. +"""Score and gate a mutation run for mega-evm. -Two subcommands: +Subcommands: exclude-re --suppressions Print one `--exclude-re ` pair per line for every function-scoped suppression. Consumed by scripts/mutation_test.sh so suppressed functions are never generated as mutants. - report --results [--suppressions ] - [--comment ] [--summary ] - Read the run outcomes, apply line-scoped suppressions, compute the - mutation score, write a Markdown report, and exit non-zero if any - unsuppressed survivor remains (the "no new survivors" gate). + note-empty --log --results + Record that cargo-mutants itself said it had nothing to mutate. With + `--in-diff`, cargo-mutants writes no results at all when the diff is + empty, changes no Rust source file or touches no mutant, and says so + only in its output; this writes + that line to /no-mutants.txt. Does nothing when + exists, and fails when it does not and the output says no such thing. + + timeout-re --results [--suppressions ] + Print one `--re ` pair per line for every unsuppressed mutant + that timed out, each regex matching that mutant's name alone. Consumed + by scripts/mutation_test.sh to re-run those mutants one at a time. + + report --results [--recheck ] + [--suppressions ] [--comment ] [--summary ] + Read the run outcomes, take the re-check's outcome for a mutant that + timed out, apply line-scoped suppressions, compute the mutation score, + write a Markdown report, and exit non-zero if any unsuppressed survivor + or timeout remains (the "no new survivors" gate). Exits 2, with a + report saying why, when the results cannot be scored. + + orphans --suppressions --universe + Flag suppressions that match no live mutant, and a locator-less line + suppression that matches more than one. + +The results a run leaves are read fail-closed, on the contract cargo-mutants 27 +keeps and scripts/umutate.py keeps with it. Before it tests anything the +producer writes `mutants.json`, a list of objects each with the `name` of a +mutant it selected. It then writes `outcomes.json`: `outcomes`, each with a +`scenario`, `"Baseline"` or `{"Mutant": {"name": ...}}`, and a `summary`; and +`end_time`, null until the run finishes. cargo-mutants rewrites `outcomes.json` +after every outcome, so a run that stops part way leaves one that looks whole; +its `total_mutants` counts the outcomes recorded so far, not the mutants +selected, and proves nothing about completion. A run is scored only if its +`end_time` is set, its baseline succeeded, and its outcomes name exactly the +mutants `mutants.json` selects. A run without `outcomes.json` tested nothing, +and passes only on the producer's own word that it had nothing to test: a +`mutants.json` holding `[]`, which cargo-mutants writes when its filters leave +no mutant, or a `no-mutants.txt` written by `note-empty`. Anything else fails: +no results directory, no outcomes, a run that did not finish, a baseline that +failed or is missing, no `mutants.json` beside the outcomes, a selected mutant +without an outcome or an outcome of a mutant not selected, an outcome of a kind +this script does not know, and results holding the `run-failed.txt` that +scripts/mutation_test.sh writes into them when the run that wrote them exited +abnormally, whatever else they hold. The gate is intended to run diff-scoped (cargo mutants --in-diff), so every mutant it sees lives on a line the PR changed; an unsuppressed survivor there is @@ -21,15 +61,50 @@ from __future__ import annotations import argparse +import json import re import sys -import tomllib -from pathlib import Path +from collections import Counter + +# tomllib is new in Python 3.11: say so rather than fail on the import below. +if sys.version_info < (3, 11): + sys.exit(f"scripts/mutation_gate.py needs Python 3.11 or newer, for tomllib; this is Python " + f"{sys.version.split()[0]}.") + +import tomllib # noqa: E402 +from dataclasses import dataclass, field # noqa: E402 +from pathlib import Path # noqa: E402 # Cap how many survivors are rendered inline in the PR comment (GitHub caps a # single comment at 65536 chars). The rest live in the run artifacts. MAX_SURVIVORS_SHOWN = 20 +# What cargo-mutants 27 prints, and writes no results for, when `--in-diff` +# leaves it nothing to mutate: a diff touching no mutant, an empty diff, and a +# diff changing no `.rs` file (a module guide under src/, say). +NOTHING_TO_MUTATE = ( + "No mutants to filter", + "Diff file is empty", + "Diff changes no Rust source files", +) + +# The file `note-empty` records such a line in. +NO_MUTANTS_NOTE = "no-mutants.txt" + +# The file scripts/mutation_test.sh writes into the results of a run it started that exited +# abnormally: an exit the files the run left cannot show. +RUN_FAILED_NOTE = "run-failed.txt" + +# The outcome kinds a mutant can have, by the list they are reported in. +MUTANT_SUMMARIES = { + "CaughtMutant": "caught", + "MissedMutant": "missed", + "Timeout": "timeout", + "Unviable": "unviable", +} + +ANSI = re.compile(r"\x1b\[[0-9;]*m") + def load_suppressions(path: Path) -> tuple[list[dict], list[dict]]: """Return (function_scoped, line_scoped) suppression entries.""" @@ -67,51 +142,296 @@ def mutant_body(line: str) -> str: return parts[1] if len(parts) == 2 else line +class ResultsError(Exception): + """Results that cannot be scored.""" + + +@dataclass +class Run: + """What a run decided about its mutants, by name.""" + + caught: list[str] = field(default_factory=list) + missed: list[str] = field(default_factory=list) + timeout: list[str] = field(default_factory=list) + unviable: list[str] = field(default_factory=list) + # Set when the run tested nothing: the producer's own word for it. + nothing_to_test: str | None = None + + +def nothing_to_mutate(line: str) -> bool: + """Whether a line of cargo-mutants' output says it had nothing to mutate.""" + return any(re.search(rf"\b(INFO|WARN)\s+{re.escape(m)}\s*$", line) for m in NOTHING_TO_MUTATE) + + +def read_selection(results: Path) -> list[str] | None: + """The names of the mutants a run selected, from its `mutants.json`; None without one.""" + listed = results / "mutants.json" + if not listed.exists(): + return None + try: + mutants = json.loads(listed.read_text()) + if not isinstance(mutants, list) or not all( + isinstance(m, dict) and isinstance(m.get("name"), str) for m in mutants): + raise TypeError("not a list of objects each with a string `name`") + except (json.JSONDecodeError, TypeError) as err: + raise ResultsError(f"{listed} is not a list of mutants: {err!r}") from err + return [m["name"] for m in mutants] + + +def empty_list_evidence(results: Path) -> str | None: + """The producer's own word that it had nothing to test, if it gave it.""" + selected = read_selection(results) + if selected is not None: + if not selected: + return "the mutant list under the run's filters was empty" + raise ResultsError( + f"{results / 'mutants.json'} lists {len(selected)} mutants but {results} has no " + f"outcomes.json: the run stopped before it recorded an outcome" + ) + note = results / NO_MUTANTS_NOTE + if note.exists(): + text = note.read_text().strip() + if nothing_to_mutate(text): + return f"cargo-mutants said: `{text}`" + raise ResultsError(f"{note} does not hold a line cargo-mutants prints: {text!r}") + return None + + +def load_run(results: Path) -> Run: + """Read a run's results fail-closed; see the module docstring.""" + if not results.is_dir(): + raise ResultsError( + f"no results at {results}: the run did not happen, crashed before it wrote " + f"anything, or wrote elsewhere" + ) + failed = results / RUN_FAILED_NOTE + if failed.exists(): + raise ResultsError( + f"the run that wrote {results} exited abnormally ({failed.read_text().strip()}), " + f"so what it left does not show that it finished" + ) + outcomes_path = results / "outcomes.json" + if not outcomes_path.exists(): + evidence = empty_list_evidence(results) + if evidence is None: + raise ResultsError( + f"{results} has no outcomes.json and no word from the producer that it had " + f"nothing to test: the run aborted or changed its output format" + ) + return Run(nothing_to_test=evidence) + try: + data = json.loads(outcomes_path.read_text()) + outcomes = data["outcomes"] + if not isinstance(outcomes, list) or not all(isinstance(o, dict) for o in outcomes): + raise TypeError("`outcomes` is not a list of objects") + except (json.JSONDecodeError, KeyError, TypeError) as err: + raise ResultsError(f"{outcomes_path} is not a mutation run's outcomes: {err!r}") from err + + end_time = data.get("end_time") + if not isinstance(end_time, str) or not end_time: + raise ResultsError( + f"{outcomes_path} records no end_time ({end_time!r}): the producer sets it only once " + f"the run finishes, so this is the record of a run that stopped part way" + ) + + baselines = [o for o in outcomes if o.get("scenario") == "Baseline"] + if not baselines: + raise ResultsError( + f"{outcomes_path} has no baseline outcome: nothing shows the unmutated tree " + f"passes its tests, so a failing test proves nothing about a mutant" + ) + failed = [o.get("summary") for o in baselines if o.get("summary") != "Success"] + if failed: + raise ResultsError( + f"the baseline failed ({failed[0]}): the unmutated tree does not pass its tests, " + f"so every mutant would read as caught. Fix the tests first" + ) + + run = Run() + mutants = [o for o in outcomes if isinstance(o.get("scenario"), dict)] + for outcome in mutants: + try: + name = outcome["scenario"]["Mutant"]["name"] + except (KeyError, TypeError) as err: + raise ResultsError(f"an outcome in {outcomes_path} names no mutant: {outcome!r}") from err + kind = MUTANT_SUMMARIES.get(outcome.get("summary")) + if kind is None: + raise ResultsError( + f"{name}: outcome {outcome.get('summary')!r} is none this gate knows " + f"({', '.join(MUTANT_SUMMARIES)})" + ) + getattr(run, kind).append(name) + + selected = read_selection(results) + if selected is None: + raise ResultsError( + f"{results} has outcomes.json but no mutants.json: nothing says which mutants the " + f"run selected, so nothing shows each has an outcome" + ) + tested = Counter(o["scenario"]["Mutant"]["name"] for o in mutants) + untested = Counter(selected) - tested + if untested: + raise ResultsError( + f"{sum(untested.values())} of the {len(selected)} mutants mutants.json selects have " + f"no outcome in {outcomes_path}, `{next(iter(untested))}` among them: the run did not " + f"test them all" + ) + unselected = tested - Counter(selected) + if unselected: + raise ResultsError( + f"{outcomes_path} records {sum(unselected.values())} outcomes of mutants mutants.json " + f"does not select, `{next(iter(unselected))}` among them: the two are not one run's" + ) + if not selected: + run.nothing_to_test = "the run tested no mutant" + return run + + +def cmd_note_empty(args: argparse.Namespace) -> int: + results = Path(args.results) + if results.exists(): + return 0 + log = Path(args.log) + lines = [ANSI.sub("", ln).rstrip() for ln in log.read_text().splitlines()] if log.exists() else [] + said = [ln.strip() for ln in lines if nothing_to_mutate(ln)] + if not said: + print( + f"ERROR: cargo-mutants wrote no results at {results}, and its output ({log}) does not " + f"say it had nothing to mutate.", + file=sys.stderr, + ) + return 1 + results.mkdir(parents=True) + (results / NO_MUTANTS_NOTE).write_text(said[-1] + "\n") + print(f"cargo-mutants had nothing to mutate: {said[-1]}", file=sys.stderr) + return 0 + + +def line_suppressions(path: str | None) -> list[dict]: + """The line-scoped suppression entries, or none when no file is given.""" + if not path: + return [] + _, line_supp = load_suppressions(Path(path)) + return line_supp + + +def suppressed_names(path: str | None) -> set[str]: + """The mutants line-scoped suppressions name. + + A line suppression matches either the bare mutation text (`mutant` written + without a locator) or the full `file:line:col: text` line. The latter lets + two mutants that share identical source text be suppressed independently. + A bare text that is the body of more than one mutant fails the gate. + """ + return {e["mutant"].strip() for e in line_suppressions(path) if "mutant" in e} + + +def locatorless_matching_several(entries: list[dict], mutants: list[str]) -> list[str]: + """Locator-less line suppressions whose text is the body of more than one mutant. + + A bare `mutant` matches every mutant with that text. Two of them have to be + named with their `file:line:col` locators, or one suppression hides both. + """ + counts = Counter(mutant_body(name) for name in mutants) + found: list[str] = [] + for entry in entries: + text = str(entry.get("mutant", "")).strip() + # A locator is `file:line:col: text`; the bare text has no `: `. + if not text or ": " in text: + continue + if counts[text] > 1 and text not in found: + found.append(text) + return found + + +def is_suppressed(name: str, supp: set[str]) -> bool: + return name in supp or mutant_body(name) in supp + + +def cmd_timeout_re(args: argparse.Namespace) -> int: + try: + run = load_run(Path(args.results)) + except ResultsError as err: + # Nothing to re-check; the gate reports why the results cannot be scored. + print(f"no timed-out mutants to re-check: {err}", file=sys.stderr) + return 0 + supp = suppressed_names(args.suppressions) + for name in run.timeout: + if is_suppressed(name, supp): + continue + print("--re") + print(f"^{re.escape(name)}$") + return 0 + + +def write_report(report: str, args: argparse.Namespace) -> None: + if args.comment: + Path(args.comment).write_text(report) + if args.summary: + with open(args.summary, "a") as fh: + fh.write(report) + print(report) + + def cmd_report(args: argparse.Namespace) -> int: results = Path(args.results) + try: + run = load_run(results) + recheck = None + if run.timeout and args.recheck and Path(args.recheck).exists(): + recheck = load_run(Path(args.recheck)) + except ResultsError as err: + write_report( + "## 🧬 Mutation testing — ❌ FAIL\n\n" + f"**The results cannot be scored:** {err}.\n", + args, + ) + return 2 - # Guard against a silent pass when the run produced no results. We must tell - # apart two cases that both leave the outcome lists empty: - # * the results dir is absent -> no run happened (e.g. the diff had no - # mutatable changes); benign, report "nothing tested" and pass. - # * the results dir exists but the expected files are missing -> the run - # aborted, wrote elsewhere, or the tool renamed its output. Refusing to - # report a 100% pass here is the whole point. - if not results.exists(): - report = "## 🧬 Mutation testing\n\nNo results at " - report += f"`{results}` — nothing was mutated (e.g. no mutatable changes).\n" - if args.comment: - Path(args.comment).write_text(report) - if args.summary: - with open(args.summary, "a") as fh: - fh.write(report) - print(report) + if run.nothing_to_test is not None: + note = f"**Nothing to test**: {run.nothing_to_test}" + write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) return 0 - for required in ("caught.txt", "missed.txt"): - if not (results / required).exists(): - print( - f"ERROR: {results / required} is missing although {results} exists. " - f"The mutation run aborted or changed its output format — refusing to " - f"report a passing gate on incomplete results.", - file=sys.stderr, - ) - return 2 - missed = read_lines(results / "missed.txt") - caught = read_lines(results / "caught.txt") - unviable = read_lines(results / "unviable.txt") - timeout = read_lines(results / "timeout.txt") + line_supp = line_suppressions(args.suppressions) + ambiguous = locatorless_matching_several( + line_supp, [*run.caught, *run.missed, *run.timeout, *run.unviable] + ) + if ambiguous: + listed = "\n".join(f"- `{text}`" for text in ambiguous) + write_report( + "## 🧬 Mutation testing — ❌ FAIL\n\n" + "A locator-less line suppression matches more than one mutant.\n" + "Name each with its `file:line:col` locator.\n\n" + f"{listed}\n", + args, + ) + return 1 + + caught, missed, timeout = list(run.caught), list(run.missed), [] + rechecked: dict[str, list[str]] = {"caught": [], "missed": [], "timeout": [], "absent": []} + if recheck is not None: + verdicts = {n: k for k in ("caught", "missed", "timeout", "unviable") for n in getattr(recheck, k)} + for name in run.timeout: + verdict = verdicts.get(name) + if verdict == "caught": + caught.append(name) + rechecked["caught"].append(name) + elif verdict == "missed": + missed.append(name) + rechecked["missed"].append(name) + else: + timeout.append(name) + rechecked["timeout" if verdict else "absent"].append(name) + else: + timeout = list(run.timeout) - _, line_supp = load_suppressions(Path(args.suppressions)) if args.suppressions else ([], []) - # A line suppression matches either the bare mutation text (`mutant` written - # without a locator) or the full `file:line:col: text` line. The latter lets - # two mutants that share identical source text be suppressed independently. supp = {e["mutant"].strip() for e in line_supp if "mutant" in e} def partition(items: list[str]) -> tuple[list[str], list[str]]: sup, real = [], [] for m in items: - (sup if (m in supp or mutant_body(m) in supp) else real).append(m) + (sup if is_suppressed(m, supp) else real).append(m) return sup, real suppressed, real_survivors = partition(missed) @@ -129,22 +449,13 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: # ---- Markdown report (PR comment + step summary) ---- status = "✅ PASS" if gate_pass else "❌ FAIL" - # No viable mutants and nothing inconclusive (typical diff run whose changed - # lines contain nothing mutatable). Reporting "100% (0/0)" reads like a real - # result and confuses readers — say plainly that nothing was tested. + # No viable mutants and nothing inconclusive (every mutant unviable, or every + # timeout suppressed). Reporting "100% (0/0)" reads like a real result and + # confuses readers — say plainly that nothing was tested. if viable == 0 and not real_timeouts: - note = "**Nothing to test** — no mutants were generated" - if unviable or timeout: - note += f" ({len(unviable)} unviable, {len(timeout)} timed out)" - else: - note += " on the changed lines" - report = f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n" - if args.comment: - Path(args.comment).write_text(report) - if args.summary: - with open(args.summary, "a") as fh: - fh.write(report) - print(report) + note = "**Nothing to test** — no viable mutant" + note += f" ({len(run.unviable)} unviable, {len(timeout)} timed out)" + write_report(f"## 🧬 Mutation testing — ✅ PASS\n\n{note}.\n", args) return 0 md = [ @@ -156,9 +467,18 @@ def partition(items: list[str]) -> tuple[list[str], list[str]]: f"- survived (real gaps): **{len(real_survivors)}**", f"- timed out (inconclusive): **{len(real_timeouts)}**", f"- suppressed (equivalent/dead-code): {len(suppressed) + len(supp_timeouts)}", - f"- unviable: {len(unviable)} · timeout total: {len(timeout)}", - "", + f"- unviable: {len(run.unviable)} · timeout total: {len(timeout)}", ] + if run.timeout: + if recheck is None: + md.append(f"- re-checked: none of the {len(run.timeout)} that timed out (no re-check results)") + else: + md.append( + f"- re-checked alone after timing out: {len(run.timeout)} — " + f"{len(rechecked['caught'])} caught, {len(rechecked['missed'])} survived, " + f"{len(rechecked['timeout'])} timed out again, {len(rechecked['absent'])} not re-run" + ) + md.append("") def section(title: str, blurb: str, items: list[str], artifact: str) -> list[str]: out = [f"### {title}", "", blurb, ""] @@ -191,14 +511,7 @@ def section(title: str, blurb: str, items: list[str], artifact: str) -> list[str md += ["", "_Tip: run `/improve-mutation-score` to triage and fix these._"] else: md.append("No new test gaps introduced by this change. 🎉") - report = "\n".join(md) + "\n" - - if args.comment: - Path(args.comment).write_text(report) - if args.summary: - with open(args.summary, "a") as fh: - fh.write(report) - print(report) + write_report("\n".join(md) + "\n", args) return 0 if gate_pass else 1 @@ -240,14 +553,21 @@ def cmd_orphans(args: argparse.Namespace) -> int: m = e.get("mutant", "").strip() if m and m not in bodies and m not in full: orphans.append(f'[line] {e.get("file", "?")}: "{m[:90]}"') + ambiguous = locatorless_matching_several(line, universe) total = len(func) + len(line) + if ambiguous: + print(f"❌ {len(ambiguous)} locator-less line suppression(s) each match more than one mutant.") + print("Name each with its file:line:col locator:") + for text in ambiguous: + print(f' - "{text[:90]}"') if orphans: print(f"❌ {len(orphans)}/{total} suppressions are stale (no live mutant matches).") print("Remove or update these — a suppression that matches nothing is a " "silent blind spot:") for o in orphans: print(f" - {o}") + if orphans or ambiguous: return 1 print(f"✅ all {total} suppressions match a live mutant.") return 0 @@ -261,8 +581,20 @@ def main() -> int: pe.add_argument("--suppressions", required=True) pe.set_defaults(func=cmd_exclude_re) + pn = sub.add_parser("note-empty", help="record cargo-mutants saying it had nothing to mutate") + pn.add_argument("--log", required=True, help="cargo-mutants' output") + pn.add_argument("--results", required=True) + pn.set_defaults(func=cmd_note_empty) + + pt = sub.add_parser("timeout-re", help="--re arguments selecting the mutants that timed out") + pt.add_argument("--results", required=True) + pt.add_argument("--suppressions", default=None) + pt.set_defaults(func=cmd_timeout_re) + pr = sub.add_parser("report") pr.add_argument("--results", required=True) + pr.add_argument("--recheck", default=None, + help="results of re-running the timed-out mutants one at a time") pr.add_argument("--suppressions", default=None) pr.add_argument("--comment", default=None, help="write Markdown report here") pr.add_argument("--summary", default=None, help="append report here (GITHUB_STEP_SUMMARY)") diff --git a/scripts/mutation_test.sh b/scripts/mutation_test.sh index 2be52d012..5de5b115e 100755 --- a/scripts/mutation_test.sh +++ b/scripts/mutation_test.sh @@ -13,17 +13,46 @@ # own. # # Results land in $OUT_DIR/mutants.out/ (missed.txt, caught.txt, outcomes.json). -# Run scripts/mutation_gate.py afterwards to score + gate the run. +# When cargo-mutants has nothing to mutate and writes no results, which it does +# when --in-diff leaves no mutant, the driver records its saying so there +# instead. A mutant that timed out is re-run once, alone, into +# $OUT_DIR/recheck/mutants.out/; a re-check that exits abnormally has its exit +# recorded there, in run-failed.txt, and the gate refuses it. Run +# scripts/mutation_gate.py afterwards to score + gate the run, passing both. # # MUTANTS_SHARD=k/n runs only shard k (0-based) of n of whichever mutant set the # subcommand selects (cargo-mutants' own --shard), for a diff too large for one # job; give each shard its own OUT_DIR and gate each one. See REVIEW.md. + +# Bash 5 or newer: the driver relies on mapfile and on expanding empty arrays +# under `set -u`, which bash 3.2 (macOS's /bin/bash) does not have. Written in +# POSIX sh so the refusal itself runs under any shell. +case "${BASH_VERSION:-}" in + [5-9].* | [1-9][0-9].*) ;; + *) + echo "scripts/mutation_test.sh needs bash 5 or newer; this shell is ${BASH_VERSION:+bash }${BASH_VERSION:-not bash}." >&2 + echo "Install a newer bash (on macOS: brew install bash) and run it as 'bash scripts/mutation_test.sh ...' with that bash first on PATH." >&2 + exit 1 + ;; +esac set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" OUT_DIR="${OUT_DIR:-$ROOT_DIR/target/mutants}" + +cd "$ROOT_DIR" + +# Clear the results before anything that can fail, so a run that stops early +# leaves nothing behind for the gate to mistake for its results. +rm -rf "$OUT_DIR" + SUPPRESS="${SUPPRESS:-$ROOT_DIR/mutants/suppressions.toml}" -JOBS="${JOBS:-$(nproc)}" +# The files cargo-mutants can mutate: the crate's Rust sources, at any depth. The +# `:(glob)` magic lets `**/` match no directory, so the files at the top of src/ +# are in; git's default pathspec would need a second `/` there and leave them out. +SRC_PATHSPEC=':(glob)crates/mega-evm/src/**/*.rs' +# macOS has no nproc. The count then comes from sysctl, then from POSIX getconf. +JOBS="${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN)}" PKG_ARGS=(--package mega-evm) CONFIG_ARGS=() @@ -33,8 +62,6 @@ INFRA_FILES=( crates/mega-evm/src/test_utils/scenario.rs ) -cd "$ROOT_DIR" - if ! cargo mutants --version >/dev/null 2>&1; then echo "cargo-mutants is required. Install with 'cargo install cargo-mutants --locked'." >&2 exit 1 @@ -55,34 +82,83 @@ EXCLUDE_ARGS=() SHARD_ARGS=() [[ -n "${MUTANTS_SHARD:-}" ]] && SHARD_ARGS=(--shard "$MUTANTS_SHARD") +# cargo-mutants exit codes (https://mutants.rs/exit-codes.html): 0 = all caught, +# 2 = missed mutants, 3 = timeouts. Those three are normal run outcomes that the +# gate (scripts/mutation_gate.py) is responsible for scoring, so swallow them and +# let the gate be the single source of truth for pass/fail. Everything else +# (1 usage, 4 baseline broken, 5/6 bad --in-diff, 70 internal) is a real failure +# of the run itself and must abort. +run_outcome() { + case "$1" in + 0 | 2 | 3) return 0 ;; + *) return "$1" ;; + esac +} + run_mutants() { rm -rf "$OUT_DIR" mkdir -p "$(dirname "$OUT_DIR")" # cargo-mutants creates OUT_DIR itself but not its parents # --no-shuffle: test mutants in deterministic source order so runs are # reproducible and comparable (recommended by https://mutants.rs/pr-diff.html). # -vV: verbose progress + version banner, for diagnosable CI logs. + local args=( + "${CONFIG_ARGS[@]}" + "${PKG_ARGS[@]}" + --jobs "$JOBS" + --output "$OUT_DIR" + --no-shuffle + -vV + "${EXCLUDE_ARGS[@]}" + "${SHARD_ARGS[@]}" + "$@" + ) + # A listing writes no results: there is nothing to record or re-check. + if [[ " $* " == *" --list "* ]]; then + cargo mutants "${args[@]}" + return + fi + local rc=0 + cargo mutants "${args[@]}" 2>&1 | tee "$OUT_DIR.log" || rc=$? + run_outcome "$rc" || return + python3 "$ROOT_DIR/scripts/mutation_gate.py" note-empty \ + --log "$OUT_DIR.log" --results "$OUT_DIR/mutants.out" + recheck_timeouts +} + +# A mutant that timed out was tested beside $JOBS others, each running the whole +# suite on the same cores, so it may have timed out on the contention alone. +# Re-run each once, alone; the gate takes that outcome for it. One that is +# caught or survives alone is decided; one that times out again stays +# inconclusive. Suppressed timeouts are not re-run. +recheck_timeouts() { + local re_output + if ! re_output="$(python3 "$ROOT_DIR/scripts/mutation_gate.py" timeout-re \ + --results "$OUT_DIR/mutants.out" --suppressions "$SUPPRESS")"; then + echo "failed to list the timed-out mutants in $OUT_DIR/mutants.out" >&2 + return 1 + fi + [[ -n "$re_output" ]] || return 0 + local re_args=() + mapfile -t re_args <<< "$re_output" + echo "Re-checking $((${#re_args[@]} / 2)) timed-out mutant(s) one at a time" >&2 local rc=0 cargo mutants \ "${CONFIG_ARGS[@]}" \ "${PKG_ARGS[@]}" \ - --jobs "$JOBS" \ - --output "$OUT_DIR" \ + --jobs 1 \ + --output "$OUT_DIR/recheck" \ --no-shuffle \ -vV \ - "${EXCLUDE_ARGS[@]}" \ - "${SHARD_ARGS[@]}" \ - "$@" || rc=$? - - # cargo-mutants exit codes (https://mutants.rs/exit-codes.html): 0 = all caught, - # 2 = missed mutants, 3 = timeouts. Those three are normal run outcomes that the - # gate (scripts/mutation_gate.py) is responsible for scoring, so swallow them and - # let the gate be the single source of truth for pass/fail. Everything else - # (1 usage, 4 baseline broken, 5/6 bad --in-diff, 70 internal) is a real failure - # of the run itself and must abort. - case "$rc" in - 0 | 2 | 3) return 0 ;; - *) return "$rc" ;; - esac + "${re_args[@]}" 2>&1 | tee "$OUT_DIR/recheck.log" || rc=$? + # A re-check that fails as a run proves nothing by the files it left, which + # can look like a finished run's. Its exit goes into its results, which the + # gate then refuses to score, saying why, rather than the job ending here + # without a report. + if ! run_outcome "$rc"; then + echo "the re-check of the timed-out mutants failed (exit $rc); see $OUT_DIR/recheck.log" >&2 + mkdir -p "$OUT_DIR/recheck/mutants.out" + echo "cargo-mutants exited $rc" > "$OUT_DIR/recheck/mutants.out/run-failed.txt" + fi } cmd="${1:-}" @@ -92,13 +168,12 @@ case "$cmd" in base="${1:?usage: mutation_test.sh diff }" diff_file="$OUT_DIR.diff" mkdir -p "$(dirname "$diff_file")" - # Only src/ is mutatable; scoping the diff there avoids a non-empty diff - # (and a wasted run) when a PR touches only tests/, Cargo.toml, etc. - git diff --no-color "$base"...HEAD -- 'crates/mega-evm/src/**' > "$diff_file" - if [[ ! -s "$diff_file" ]]; then - echo "No changes under crates/mega-evm vs $base; nothing to mutate." >&2 - exit 0 - fi + # Only the crate's Rust sources are mutatable; scoping the diff to them + # avoids a non-empty diff (and a wasted run) when a PR touches only tests/, + # Cargo.toml or a module guide under src/. An empty diff still goes to + # cargo-mutants, which says it has nothing to mutate, so the gate passes on + # its word rather than on missing results. + git diff --no-color "$base"...HEAD -- "$SRC_PATHSPEC" > "$diff_file" run_mutants --in-diff "$diff_file" ;; full) @@ -122,4 +197,4 @@ esac echo echo "Mutation results written to $OUT_DIR/mutants.out/" -echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out" +echo "Score + gate with: python3 scripts/mutation_gate.py report --results $OUT_DIR/mutants.out --recheck $OUT_DIR/recheck/mutants.out" diff --git a/scripts/price_grid.sh b/scripts/price_grid.sh new file mode 100755 index 000000000..c1df50c0f --- /dev/null +++ b/scripts/price_grid.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# Runs the mega-evm test suite at state and history byte prices other than the constants. +# +# Usage: +# scripts/price_grid.sh --pr the pull-request points (PR_POINTS below) +# scripts/price_grid.sh --full the whole grid (CPSB_AXIS x CPHB_AXIS, and EXTRA_POINTS) +# scripts/price_grid.sh CPSB/CPHB ... the points named, e.g. 312.5/20 5000/300 +# +# A point is a cost per state byte and a cost per history byte, as `MEGA_SATIN_CPSB` and +# `MEGA_SATIN_CPHB` take them (a decimal with at most three places); `-` on either side leaves that +# variable unset, which is the constant. The suite is built once with the `satin-price-override` +# feature, which reads the two variables at run time, and run once per point with +# `--no-fail-fast`, so every failing test of every point is reported. +# +# Each point's output lands in $OUT_DIR/_.log (default target/price-grid), and the +# notes its tests left in _.guards, one per line: the tests a price guard held back +# (`note_price_guard`), and apart from them the tests that skipped only a snapshot comparison, +# since snapshots are pinned at the spec's prices (`note_snapshot_skipped`). A summary line per +# point, with how many passed, were guarded, skipped a snapshot and failed, goes to stdout and, +# when $GITHUB_STEP_SUMMARY is set, a table to the step summary. Exits 1 if any point fails. +# +# The grid brackets the prices under consideration and adds the edges the code allows: a price of +# nothing on either axis, the smallest price the code represents (0.001), the cheapest price that +# charges a byte at all (1), and a point past the dearest candidate on both axes. The suite holds +# at a price of nothing and at any price from 1 up to that point; below 1 the schedule's entries +# round to nothing one at a time, and no test is held there. + +set -uo pipefail + +CPSB_AXIS="0 1 312.5 700 1530 2000 5000 10000" +CPHB_AXIS="0 1 20 50 88 100 200 300 1000" +EXTRA_POINTS="0.001/0.001" +# Both bytes free; both at one gas, where a premise that a charge cannot be paid holds only if a +# byte is dear; the cheapest and the dearest pair under consideration; and a point past every +# candidate. Between them they have failed every test the full grid failed. +PR_POINTS="0/0 1/1 312.5/20 5000/300 10000/1000" + +FEATURES="satin-price-override,test-utils" +# The reason `note_snapshot_skipped` leaves (`test_utils::SNAPSHOT_SKIPPED`): a test that skipped a +# snapshot comparison ran every assertion it makes, so it is counted apart from the guards. +SNAPSHOT_SKIPPED="snapshot comparison skipped" + +cd "$(dirname "$0")/.." || exit 1 +OUT_DIR="${OUT_DIR:-target/price-grid}" + +case "${1:-}" in + --pr) + points="$PR_POINTS" + ;; + --full) + points="" + for cpsb in $CPSB_AXIS; do + for cphb in $CPHB_AXIS; do + points="$points $cpsb/$cphb" + done + done + points="$points $EXTRA_POINTS" + ;; + "" | -h | --help) + sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//' + exit 2 + ;; + *) + points="$*" + ;; +esac + +rm -rf "$OUT_DIR" +mkdir -p "$OUT_DIR" +# The tests run in their package's directory, so the guard file is named by its absolute path. +out_abs="$(cd "$OUT_DIR" && pwd)" + +echo "Building the test binaries with --features $FEATURES" +if ! cargo test -p mega-evm --features "$FEATURES" --locked --no-run; then + echo "error: the test binaries do not build" >&2 + exit 1 +fi + +summary="| CPSB | CPHB | result | passed | guarded | snapshot skips | failed |"$'\n'"|---|---|---|---:|---:|---:|---:|" +failed_points="" +for point in $points; do + cpsb="${point%/*}" + cphb="${point#*/}" + set -- env -u MEGA_SATIN_CPSB -u MEGA_SATIN_CPHB + [ "$cpsb" != "-" ] && set -- "$@" "MEGA_SATIN_CPSB=$cpsb" + [ "$cphb" != "-" ] && set -- "$@" "MEGA_SATIN_CPHB=$cphb" + name="${cpsb//-/unset}_${cphb//-/unset}" + log="$OUT_DIR/$name.log" + guards="$out_abs/$name.guards" + set -- "$@" "MEGA_PRICE_GUARD_LOG=$guards" + + start=$(date +%s) + "$@" cargo test -p mega-evm --features "$FEATURES" --locked --no-fail-fast >"$log" 2>&1 + status=$? + seconds=$(($(date +%s) - start)) + + passed=$(grep -E '^test result:' "$log" | sed -E 's/.* ([0-9]+) passed.*/\1/' | awk '{s += $1} END {print s + 0}') + failed=$(grep -cE '^test .* \.\.\. FAILED$' "$log") + guarded=0 + snapshot_skips=0 + if [ -f "$guards" ]; then + snapshot_skips=$(grep -c "^$SNAPSHOT_SKIPPED: " "$guards") + guarded=$(grep -vc "^$SNAPSHOT_SKIPPED: " "$guards") + fi + if [ "$status" -eq 0 ]; then + result="ok" + else + result="FAILED" + failed_points="$failed_points $point" + fi + printf '%-12s %-7s %5s passed %4s guarded %4s snapshot skips %4s failed %4ss %s\n' \ + "$point" "$result" "$passed" "$guarded" "$snapshot_skips" "$failed" "$seconds" "$log" + if [ "$status" -ne 0 ]; then + grep -E '^test .* \.\.\. FAILED$' "$log" | sed 's/^/ /' + # A failure that is not a test's, such as a build error, shows in the log's tail. + [ "$failed" -eq 0 ] && tail -20 "$log" | sed 's/^/ /' + fi + summary="$summary"$'\n'"| $cpsb | $cphb | $result | $passed | $guarded | $snapshot_skips | $failed |" +done + +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + { + echo "## mega-evm at other byte prices" + echo + echo "$summary" + } >>"$GITHUB_STEP_SUMMARY" +fi + +if [ -n "$failed_points" ]; then + echo "error: the suite fails at:$failed_points (logs in $OUT_DIR)" >&2 + exit 1 +fi +echo "the suite passes at every point" diff --git a/scripts/test_mutation_gate.py b/scripts/test_mutation_gate.py new file mode 100644 index 000000000..d329a767e --- /dev/null +++ b/scripts/test_mutation_gate.py @@ -0,0 +1,671 @@ +#!/usr/bin/env python3 +"""Tests of scripts/mutation_gate.py and of the guards of scripts/mutation_test.sh. + +Run from the repository root with Python 3.11 or newer (the gate reads TOML with +tomllib): + + python3 -m unittest discover -s scripts -p 'test_*.py' -v + +Each case writes the files a mutation run leaves in a temporary directory, in the +shapes cargo-mutants 27.1.0 and scripts/umutate.py write them, and runs the gate's +subcommands on it. +""" +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from argparse import Namespace +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parent + +# The gate reads TOML with tomllib, new in Python 3.11. An older Python runs one test in place of +# the rest, which fails with the reason: a failure, not a skip, so a job on an old Python fails +# rather than passing on nothing tested. +TOO_OLD = sys.version_info < (3, 11) +REASON = (f"the mutation gate and its tests need Python 3.11 or newer, for tomllib; this is " + f"Python {sys.version.split()[0]}") + + +class PythonVersion(unittest.TestCase): + def test_python_is_new_enough(self) -> None: + if TOO_OLD: + self.fail(REASON) + + +def load_tests(loader: unittest.TestLoader, tests: unittest.TestSuite, + pattern: str | None) -> unittest.TestSuite: + """On an older Python, the version test alone: the others need the gate, which cannot load.""" + return loader.loadTestsFromTestCase(PythonVersion) if TOO_OLD else tests + + +def load_script(name: str): + spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py") + module = importlib.util.module_from_spec(spec) + # Registered before it runs: its dataclasses look their module up. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +gate = None if TOO_OLD else load_script("mutation_gate") +umutate = None if TOO_OLD else load_script("umutate") + +CAUGHT = "crates/mega-evm/src/a.rs:1:1: replace f -> u64 with 0" +MISSED = "crates/mega-evm/src/a.rs:2:5: replace + with - in g" +TIMEOUT = "crates/mega-evm/src/system/keyless/dispatch.rs:367:23: delete ! in prepare" +UNVIABLE = "crates/mega-evm/src/a.rs:3:9: replace h -> Foo with Default::default()" + + +# When a run finished, as cargo-mutants writes `end_time`. +FINISHED = "2026-09-27T07:17:03.989998Z" + + +def mutant(name: str, summary: str) -> dict: + return {"scenario": {"Mutant": {"name": name}}, "summary": summary} + + +def outcomes_json(*mutants: dict, baseline: str | None = "Success", + end_time: str | None = FINISHED) -> dict: + """An `outcomes.json` as cargo-mutants 27.1.0 writes it, after every outcome and once more + when it finishes: its counters are the outcomes recorded so far, and `end_time` is null + until the run finishes.""" + outcomes = [] if baseline is None else [{"scenario": "Baseline", "summary": baseline}] + outcomes += list(mutants) + summaries = [m["summary"] for m in mutants] + return { + "outcomes": outcomes, + "total_mutants": len(mutants), + "missed": summaries.count("MissedMutant"), + "caught": summaries.count("CaughtMutant"), + "timeout": summaries.count("Timeout"), + "unviable": summaries.count("Unviable"), + "success": summaries.count("Success"), + "start_time": "2026-09-27T07:16:56.385727Z", + "end_time": end_time, + "cargo_mutants_version": "27.1.0", + } + + +def mutants_json(*names: str) -> str: + """A `mutants.json`: every mutant a run selected, written before it tests any.""" + return json.dumps([{"name": n, "file": n.split(":", 1)[0]} for n in names]) + + +class GateCase(unittest.TestCase): + def setUp(self) -> None: + self.tmp = Path(tempfile.mkdtemp(prefix="mutation-gate-test-")) + self.addCleanup(shutil.rmtree, self.tmp) + + def results(self, name: str = "mutants.out", outcomes: dict | None = None, + files: dict[str, str] | None = None, selected: list[str] | None = None) -> Path: + """A results directory. With `outcomes` and no `mutants.json` of its own, it selects the + mutants the outcomes name, as a run that finished does.""" + path = self.tmp / name + path.mkdir(parents=True) + files = files or {} + if outcomes is not None: + (path / "outcomes.json").write_text(json.dumps(outcomes)) + if selected is None and "mutants.json" not in files: + selected = [o["scenario"]["Mutant"]["name"] for o in outcomes["outcomes"] + if isinstance(o.get("scenario"), dict)] + if selected is not None: + (path / "mutants.json").write_text(mutants_json(*selected)) + for file, text in files.items(): + (path / file).write_text(text) + return path + + def suppressions(self, *mutants: str) -> Path: + path = self.tmp / "suppressions.toml" + entries = [f'[[suppress]]\nkind = "line"\nfile = "x"\nmutant = "{m}"\n' for m in mutants] + path.write_text("\n".join(entries)) + return path + + def report(self, results: Path, recheck: Path | None = None, + suppressions: Path | None = None) -> tuple[int, str]: + comment = self.tmp / "comment.md" + args = Namespace( + results=str(results), + recheck=str(recheck) if recheck else None, + suppressions=str(suppressions) if suppressions else None, + comment=str(comment), + summary=None, + ) + with contextlib.redirect_stdout(io.StringIO()): + code = gate.cmd_report(args) + text = comment.read_text() + return code, text + + +class ResultsThatCannotBeScored(GateCase): + """Every way a run can leave results that say nothing is a failure, with its reason.""" + + def assert_unscorable(self, results: Path, reason: str) -> None: + code, text = self.report(results) + self.assertEqual(code, 2, text) + self.assertIn("FAIL", text) + self.assertIn("cannot be scored", text) + self.assertRegex(text, reason) + + def test_no_results_directory(self) -> None: + self.assert_unscorable(self.tmp / "absent", "no results at") + + def test_a_directory_without_outcomes(self) -> None: + # What a driver that crashed after cargo-mutants created its directory leaves, + # and what the empty lists of an aborted run look like. + results = self.results(files={"caught.txt": "", "missed.txt": "", "timeout.txt": ""}) + self.assert_unscorable(results, "no outcomes.json") + + def test_a_failed_baseline(self) -> None: + results = self.results(outcomes=outcomes_json(baseline="Failure")) + self.assert_unscorable(results, "baseline failed") + + def test_a_failed_baseline_with_an_exit_status(self) -> None: + results = self.results(outcomes=outcomes_json(baseline={"Failure": 101})) + self.assert_unscorable(results, "baseline failed") + + def test_no_baseline(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"), baseline=None)) + self.assert_unscorable(results, "no baseline outcome") + + def test_a_run_stopped_after_its_baseline(self) -> None: + # What cargo-mutants 27.1.0 leaves when it stops once its baseline passed and before it + # records a mutant: the selection in mutants.json, and an outcomes.json holding the + # baseline alone, counting no mutant, with no end_time. + record = outcomes_json(end_time=None) + self.assertEqual(record["total_mutants"], 0) + results = self.results(outcomes=record, selected=[CAUGHT, MISSED]) + self.assert_unscorable(results, "records no end_time") + + def test_a_run_stopped_after_catching_part_of_its_selection(self) -> None: + # The same record once some of the selection was caught: total_mutants counts the + # outcomes recorded, so it equals them and says nothing of the mutants still to test. + record = outcomes_json(mutant(CAUGHT, "CaughtMutant"), end_time=None) + self.assertEqual(record["total_mutants"], 1) + results = self.results(outcomes=record, selected=[CAUGHT, MISSED]) + self.assert_unscorable(results, "records no end_time") + + def test_a_record_without_an_end_time(self) -> None: + record = outcomes_json(mutant(CAUGHT, "CaughtMutant")) + del record["end_time"] + self.assert_unscorable(self.results(outcomes=record), "records no end_time") + + def test_a_finished_record_missing_a_selected_mutant(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant")), + selected=[CAUGHT, MISSED]) + self.assert_unscorable(results, "1 of the 2 mutants mutants.json selects have no outcome") + + def test_a_mutant_selected_twice_needs_two_outcomes(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant")), + selected=[CAUGHT, CAUGHT]) + self.assert_unscorable(results, "1 of the 2 mutants mutants.json selects have no outcome") + + def test_an_outcome_of_a_mutant_not_selected(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "CaughtMutant")), selected=[CAUGHT]) + self.assert_unscorable(results, "outcomes of mutants mutants.json does not select") + + def test_outcomes_without_a_selection(self) -> None: + results = self.results(files={"outcomes.json": json.dumps( + outcomes_json(mutant(CAUGHT, "CaughtMutant")))}) + self.assert_unscorable(results, "no mutants.json") + + def test_a_selection_that_is_not_a_list_of_mutants(self) -> None: + results = self.results(outcomes=outcomes_json(), files={"mutants.json": json.dumps([CAUGHT])}) + self.assert_unscorable(results, "is not a list of mutants") + + def test_an_outcome_of_an_unknown_kind(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "Exploded"))) + self.assert_unscorable(results, "none this gate knows") + + def test_outcomes_that_are_not_json(self) -> None: + results = self.results(files={"outcomes.json": "{"}) + self.assert_unscorable(results, "is not a mutation run's outcomes") + + def test_outcomes_that_are_not_objects(self) -> None: + results = self.results(files={"outcomes.json": json.dumps( + {"total_mutants": 1, "outcomes": ["Baseline", CAUGHT]})}) + self.assert_unscorable(results, "not a list of objects") + + def test_a_listed_run_without_outcomes(self) -> None: + results = self.results(files={"mutants.json": json.dumps([{"name": CAUGHT}])}) + self.assert_unscorable(results, "stopped before it recorded an outcome") + + def test_a_note_that_is_not_cargo_mutants_own(self) -> None: + results = self.results(files={"no-mutants.txt": "nothing to see here\n"}) + self.assert_unscorable(results, "does not hold a line cargo-mutants prints") + + def test_a_broken_recheck_of_a_timeout(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json(baseline="Failure")) + code, text = self.report(results, recheck) + self.assertEqual(code, 2, text) + self.assertIn("baseline failed", text) + + def test_a_recheck_that_exited_abnormally(self) -> None: + # Its files record the timeout caught and the run finished; the driver's note of its exit + # outweighs them. + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json(mutant(TIMEOUT, "CaughtMutant")), + files={"run-failed.txt": "cargo-mutants exited 70\n"}) + code, text = self.report(results, recheck) + self.assertEqual(code, 2, text) + self.assertIn("exited abnormally (cargo-mutants exited 70)", text) + + +class NothingToTest(GateCase): + """A run that tested nothing passes only on the producer's own word for it.""" + + def assert_nothing_to_test(self, results: Path, evidence: str) -> None: + code, text = self.report(results) + self.assertEqual(code, 0, text) + self.assertIn("PASS", text) + self.assertIn("Nothing to test", text) + self.assertIn(evidence, text) + + def test_cargo_mutants_listed_no_mutant(self) -> None: + # What cargo-mutants writes when its filters leave nothing: mutants.json holding + # [] and no outcomes; umutate.py writes the same when it generates nothing. + results = self.results(files={"mutants.json": "[]\n", "caught.txt": "", "missed.txt": ""}) + self.assert_nothing_to_test(results, "mutant list under the run's filters was empty") + + def test_cargo_mutants_said_so_for_a_diff(self) -> None: + results = self.results(files={"no-mutants.txt": "INFO No mutants to filter\n"}) + self.assert_nothing_to_test(results, "No mutants to filter") + + def test_cargo_mutants_said_so_for_an_empty_diff(self) -> None: + results = self.results(files={"no-mutants.txt": "INFO Diff file is empty\n"}) + self.assert_nothing_to_test(results, "Diff file is empty") + + def test_cargo_mutants_said_so_for_a_diff_of_no_rust_source(self) -> None: + results = self.results(files={"no-mutants.txt": "INFO Diff changes no Rust source files\n"}) + self.assert_nothing_to_test(results, "Diff changes no Rust source files") + + def test_every_mutant_unviable(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(UNVIABLE, "Unviable"))) + code, text = self.report(results) + self.assertEqual(code, 0, text) + self.assertIn("Nothing to test", text) + self.assertIn("1 unviable", text) + + +class Scoring(GateCase): + """What survives or times out fails the gate unless suppressed or re-checked.""" + + def test_all_caught_passes(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(UNVIABLE, "Unviable"))) + code, text = self.report(results) + self.assertEqual(code, 0, text) + self.assertIn("100.0%", text) + + def test_a_survivor_fails(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) + code, text = self.report(results) + self.assertEqual(code, 1, text) + self.assertIn(MISSED, text) + + def test_a_suppressed_survivor_passes(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(MISSED, "MissedMutant"))) + for suppressed in (MISSED, gate.mutant_body(MISSED)): + code, text = self.report(results, suppressions=self.suppressions(suppressed)) + self.assertEqual(code, 0, text) + + def test_a_locatorless_suppression_of_two_mutants_fails(self) -> None: + body = gate.mutant_body(MISSED) + other = f"crates/mega-evm/src/b.rs:4:1: {body}" + results = self.results(outcomes=outcomes_json( + mutant(MISSED, "MissedMutant"), mutant(other, "CaughtMutant"))) + code, text = self.report(results, suppressions=self.suppressions(body)) + self.assertEqual(code, 1, text) + self.assertIn("more than one mutant", text) + self.assertIn(body, text) + + def test_located_suppressions_of_one_shared_text_pass(self) -> None: + body = gate.mutant_body(MISSED) + other = f"crates/mega-evm/src/b.rs:4:1: {body}" + results = self.results(outcomes=outcomes_json( + mutant(MISSED, "MissedMutant"), mutant(other, "MissedMutant"))) + code, text = self.report(results, suppressions=self.suppressions(MISSED, other)) + self.assertEqual(code, 0, text) + + def test_a_timeout_without_a_recheck_fails(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"))) + code, text = self.report(results, self.tmp / "no-recheck") + self.assertEqual(code, 1, text) + self.assertIn("none of the 1 that timed out", text) + + def test_a_suppressed_timeout_passes(self) -> None: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"))) + code, text = self.report(results, suppressions=self.suppressions(TIMEOUT)) + self.assertEqual(code, 0, text) + + def recheck_of_the_timeout(self, summary: str) -> tuple[int, str]: + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json(mutant(TIMEOUT, summary))) + return self.report(results, recheck) + + def test_a_timeout_caught_alone_passes(self) -> None: + code, text = self.recheck_of_the_timeout("CaughtMutant") + self.assertEqual(code, 0, text) + self.assertIn("1 caught, 0 survived, 0 timed out again", text) + self.assertIn("(2/2 viable mutants killed)", text) + + def test_a_timeout_that_survives_alone_is_a_survivor(self) -> None: + code, text = self.recheck_of_the_timeout("MissedMutant") + self.assertEqual(code, 1, text) + self.assertIn("Survivors needing attention", text) + self.assertNotIn("Timed-out mutants", text) + + def test_a_timeout_that_times_out_alone_stays_inconclusive(self) -> None: + code, text = self.recheck_of_the_timeout("Timeout") + self.assertEqual(code, 1, text) + self.assertIn("1 timed out again", text) + self.assertIn("Timed-out mutants", text) + + def test_a_timeout_the_recheck_did_not_run_stays_inconclusive(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"))) + code, text = self.report(results, recheck) + self.assertEqual(code, 1, text) + self.assertIn("1 not re-run", text) + + def test_a_recheck_only_speaks_for_the_timeouts(self) -> None: + # A mutant the first run decided is not re-decided by a re-check that happens to + # include it. + results = self.results(outcomes=outcomes_json( + mutant(MISSED, "MissedMutant"), mutant(TIMEOUT, "Timeout"))) + recheck = self.results("recheck", outcomes=outcomes_json( + mutant(MISSED, "CaughtMutant"), mutant(TIMEOUT, "CaughtMutant"))) + code, text = self.report(results, recheck) + self.assertEqual(code, 1, text) + self.assertIn(MISSED, text) + + +class UmutateRecord(GateCase): + """scripts/umutate.py writes the record the gate scores, on the contract cargo-mutants keeps.""" + + def test_a_finished_run_is_scored(self) -> None: + out = self.results("umutate") + umutate.write_selection(out, [CAUGHT, MISSED]) + umutate.write_outcomes(out, umutate.now(), [CAUGHT], [MISSED], []) + code, text = self.report(out) + self.assertEqual(code, 1, text) + self.assertIn("(1/2 viable mutants killed)", text) + self.assertIn(MISSED, text) + + def test_a_run_that_stops_part_way_is_refused(self) -> None: + # The selection is on disk before any mutant is tested, the outcomes only once all are. + out = self.results("umutate") + umutate.write_selection(out, [CAUGHT, MISSED]) + code, text = self.report(out) + self.assertEqual(code, 2, text) + self.assertIn("stopped before it recorded an outcome", text) + + def test_a_run_that_generates_nothing_has_nothing_to_test(self) -> None: + out = self.results("umutate") + umutate.write_selection(out, []) + code, text = self.report(out) + self.assertEqual(code, 0, text) + self.assertIn("mutant list under the run's filters was empty", text) + + +class NoteEmpty(GateCase): + """`note-empty` records cargo-mutants saying it had nothing to mutate, and nothing else.""" + + def note(self, log_text: str | None, results: Path) -> int: + log = self.tmp / "run.log" + if log_text is not None: + log.write_text(log_text) + with contextlib.redirect_stderr(io.StringIO()): + return gate.cmd_note_empty(Namespace(log=str(log), results=str(results))) + + def test_it_records_what_cargo_mutants_printed(self) -> None: + results = self.tmp / "mutants.out" + # As CI prints it, with CARGO_TERM_COLOR=always. + log = "Found 0 mutants\n\x1b[32m INFO\x1b[0m No mutants to filter\n" + self.assertEqual(self.note(log, results), 0) + self.assertEqual((results / "no-mutants.txt").read_text(), "INFO No mutants to filter\n") + code, text = self.report(results) + self.assertEqual(code, 0, text) + + def test_it_records_a_diff_of_no_rust_source(self) -> None: + # What cargo-mutants 27.1.0 prints, and all it does, for a diff that changes only + # Markdown files: it writes no results and exits 0. + results = self.tmp / "mutants.out" + log = "\x1b[32m INFO\x1b[0m Diff changes no Rust source files\n" + self.assertEqual(self.note(log, results), 0) + self.assertEqual((results / "no-mutants.txt").read_text(), + "INFO Diff changes no Rust source files\n") + code, text = self.report(results) + self.assertEqual(code, 0, text) + + def test_it_refuses_output_that_says_no_such_thing(self) -> None: + results = self.tmp / "mutants.out" + self.assertEqual(self.note("error: could not compile\n", results), 1) + self.assertFalse(results.exists()) + self.assertEqual(self.note(None, results), 1) + self.assertFalse(results.exists()) + + def test_it_leaves_results_cargo_mutants_wrote_alone(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(CAUGHT, "CaughtMutant"))) + self.assertEqual(self.note(" INFO Diff file is empty\n", results), 0) + self.assertFalse((results / "no-mutants.txt").exists()) + + +class TimeoutRe(GateCase): + """`timeout-re` selects exactly the unsuppressed mutants that timed out.""" + + def regexes(self, results: Path, suppressions: Path | None = None) -> list[str]: + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + code = gate.cmd_timeout_re(Namespace( + results=str(results), suppressions=str(suppressions) if suppressions else None)) + self.assertEqual(code, 0) + lines = out.getvalue().splitlines() + self.assertEqual(lines[0::2], ["--re"] * (len(lines) // 2)) + return lines[1::2] + + def test_one_anchored_regex_per_timeout(self) -> None: + other = "crates/mega-evm/src/system/keyless/dispatch.rs:367:23: delete ! in prepare2" + results = self.results(outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"), mutant(other, "Timeout"))) + regexes = self.regexes(results) + self.assertEqual(len(regexes), 2) + names = [CAUGHT, TIMEOUT, other] + for regex, timed_out in zip(regexes, [TIMEOUT, other]): + self.assertEqual([n for n in names if re.search(regex, n)], [timed_out]) + + def test_suppressed_timeouts_are_not_rerun(self) -> None: + results = self.results(outcomes=outcomes_json(mutant(TIMEOUT, "Timeout"))) + self.assertEqual(self.regexes(results, self.suppressions(TIMEOUT)), []) + + def test_results_without_outcomes_select_nothing(self) -> None: + self.assertEqual(self.regexes(self.results(files={"mutants.json": "[]"})), []) + self.assertEqual(self.regexes(self.tmp / "absent"), []) + + +class DiffScope(unittest.TestCase): + """The diff the driver hands cargo-mutants holds every Rust source of the crate and nothing else.""" + + ROOT = SCRIPTS.parent + SRC = "crates/mega-evm/src" + + def ls_files(self, *pathspecs: str) -> list[str]: + run = subprocess.run(["git", "ls-files", "--", *pathspecs], cwd=self.ROOT, + capture_output=True, text=True, timeout=60) + if run.returncode != 0: + self.skipTest(f"not a git checkout: {run.stderr.strip()}") + return run.stdout.splitlines() + + def test_the_pathspec_selects_every_rust_source_and_nothing_else(self) -> None: + driver = (SCRIPTS / "mutation_test.sh").read_text() + match = re.search(r"^SRC_PATHSPEC='([^']+)'$", driver, re.MULTILINE) + self.assertIsNotNone(match, "the driver names its pathspec") + tracked = self.ls_files(self.SRC) + rust = [path for path in tracked if path.endswith(".rs")] + self.assertIn(f"{self.SRC}/lib.rs", rust) + self.assertTrue(any(not path.endswith(".rs") for path in tracked), + "src/ holds files that are not Rust sources, which the scope leaves out") + self.assertEqual(self.ls_files(match.group(1)), rust) + + +def bash5() -> str | None: + """A bash 5 or newer, if this machine has one.""" + for shell in (shutil.which("bash"), "/opt/homebrew/bin/bash", "/usr/local/bin/bash", + "/usr/bin/bash", "/bin/bash"): + if shell and Path(shell).exists() and (DriverGuard.bash_major(shell) or 0) >= 5: + return shell + return None + + +# A stand-in for `cargo mutants`: it writes the results the test prepared for the run it is asked +# for, the first run or the re-check (the one given `--re`), and exits as the test says. +FAKE_CARGO = """#!/bin/sh +[ "$1" = mutants ] || exit 99 +shift +if [ "$1" = --version ]; then echo "cargo-mutants 27.1.0"; exit 0; fi +out=""; run=main +while [ $# -gt 0 ]; do + case "$1" in + --output) out="$2"; shift ;; + --re) run=recheck ;; + esac + shift +done +if [ -d "$FAKE_RUNS/$run" ]; then + mkdir -p "$out/mutants.out" + cp -R "$FAKE_RUNS/$run/." "$out/mutants.out/" +fi +exit "$(cat "$FAKE_RUNS/$run.exit")" +""" + + +class DriverRecheck(GateCase): + """scripts/mutation_test.sh re-runs a timed-out mutant alone and carries a failed re-check's + exit into its results, which the gate then refuses.""" + + def drive(self, recheck_exit: int, recheck: dict | None) -> tuple[int, str, Path]: + shell = bash5() + if shell is None: + self.skipTest("no bash 5 or newer on this machine") + runs = self.tmp / "runs" + self.results("runs/main", outcomes=outcomes_json( + mutant(CAUGHT, "CaughtMutant"), mutant(TIMEOUT, "Timeout"))) + (runs / "main.exit").write_text("3\n") + if recheck is not None: + self.results("runs/recheck", outcomes=recheck) + (runs / "recheck.exit").write_text(f"{recheck_exit}\n") + bin_dir = self.tmp / "bin" + bin_dir.mkdir() + (bin_dir / "cargo").write_text(FAKE_CARGO) + (bin_dir / "cargo").chmod(0o755) + (bin_dir / "python3").symlink_to(sys.executable) + out = self.tmp / "out" / "mutants" + env = {"PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_RUNS": str(runs), "OUT_DIR": str(out), + "JOBS": "1", "SUPPRESS": str(self.tmp / "no-suppressions.toml")} + run = subprocess.run([shell, str(DriverGuard.DRIVER), "file", "crates/mega-evm/src/a.rs"], + capture_output=True, text=True, timeout=120, env=env) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn("Re-checking 1 timed-out mutant(s) one at a time", run.stderr) + code, text = self.report(out / "mutants.out", out / "recheck" / "mutants.out") + return code, text, out / "recheck" / "mutants.out" + + def test_a_recheck_that_finishes_decides_the_timeout(self) -> None: + code, text, recheck = self.drive(0, outcomes_json(mutant(TIMEOUT, "CaughtMutant"))) + self.assertFalse((recheck / "run-failed.txt").exists()) + self.assertEqual(code, 0, text) + self.assertIn("1 caught, 0 survived, 0 timed out again", text) + + def test_a_recheck_that_exits_abnormally_is_refused(self) -> None: + # Its files are those of a finished run that caught the timeout: only its exit says + # otherwise. + code, text, recheck = self.drive(70, outcomes_json(mutant(TIMEOUT, "CaughtMutant"))) + self.assertEqual((recheck / "run-failed.txt").read_text(), "cargo-mutants exited 70\n") + self.assertEqual(code, 2, text) + self.assertIn("exited abnormally (cargo-mutants exited 70)", text) + + def test_a_recheck_that_writes_nothing_is_refused(self) -> None: + code, text, recheck = self.drive(1, None) + self.assertEqual(sorted(p.name for p in recheck.iterdir()), ["run-failed.txt"]) + self.assertEqual(code, 2, text) + self.assertIn("exited abnormally (cargo-mutants exited 1)", text) + + +class DriverGuard(unittest.TestCase): + """scripts/mutation_test.sh refuses to run on a shell that is not bash 5 or newer.""" + + DRIVER = SCRIPTS / "mutation_test.sh" + + @staticmethod + def bash_major(shell: str) -> int | None: + """The bash major version `shell` is, or None when it is not bash.""" + out = subprocess.run([shell, "-c", 'echo "${BASH_VERSION:-}"'], capture_output=True, + text=True).stdout.strip() + return int(out.split(".")[0]) if out else None + + def assert_refused(self, shell: str) -> None: + major = self.bash_major(shell) + if major is not None and major >= 5: + self.skipTest(f"{shell} is bash {major}") + # A subcommand the driver does not have and a scratch output directory: were the guard to + # let the shell through, the driver would print its usage and touch nothing else. + with tempfile.TemporaryDirectory() as out: + run = subprocess.run([shell, str(self.DRIVER), "guard-check"], capture_output=True, + text=True, timeout=60, env={"PATH": "/usr/bin:/bin", + "OUT_DIR": f"{out}/mutants"}) + self.assertEqual(run.returncode, 1, run.stderr) + self.assertIn("needs bash 5 or newer", run.stderr) + self.assertEqual(run.stdout, "") + + def test_a_posix_shell_is_refused(self) -> None: + # dash on Debian and Ubuntu, bash 3.2 in POSIX mode on macOS. + self.assert_refused("/bin/sh") + + def test_an_old_bash_is_refused(self) -> None: + if not Path("/bin/bash").exists(): + self.skipTest("no /bin/bash") + self.assert_refused("/bin/bash") + + +class OrphanSuppressions(GateCase): + """A suppression must name live mutants, and a bare line must name one.""" + + def orphans(self, suppressions: Path, universe: list[str]) -> tuple[int, str]: + path = self.tmp / "universe.txt" + path.write_text("".join(f"{line}\n" for line in universe)) + args = Namespace(suppressions=str(suppressions), universe=str(path)) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = gate.cmd_orphans(args) + return code, buf.getvalue() + + def test_a_locatorless_line_suppression_matching_two_mutants_fails(self) -> None: + body = gate.mutant_body(MISSED) + other = f"crates/mega-evm/src/b.rs:4:1: {body}" + code, text = self.orphans(self.suppressions(body), [MISSED, other]) + self.assertEqual(code, 1, text) + self.assertIn("more than one mutant", text) + + def test_a_located_line_suppression_matches_one_of_two(self) -> None: + body = gate.mutant_body(MISSED) + other = f"crates/mega-evm/src/b.rs:4:1: {body}" + code, text = self.orphans(self.suppressions(MISSED), [MISSED, other]) + self.assertEqual(code, 0, text) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/umutate.py b/scripts/umutate.py index 8215b8b9f..b1960d5aa 100755 --- a/scripts/umutate.py +++ b/scripts/umutate.py @@ -24,7 +24,14 @@ run [--diff ] [--packs a,b] --output Full pipeline: generate -> mutate -> analyze (run the test command per mutant) -> write caught.txt/missed.txt/unviable.txt/timeout.txt into - , ready for `mutation_gate.py report --results `. + , ready for `mutation_gate.py report --results `. It keeps the + gate's contract as cargo-mutants 27 does: mutants.json, every mutant the + run selected, is written before any is tested, and outcomes.json, the + baseline and one outcome per selected mutant with the `end_time` that + marks the run finished, only when every one is tested. A run that + generates no mutant writes mutants.json holding [] and no outcomes. A + failing baseline, or a run that stops part way, leaves the selection + without outcomes, which the gate refuses. In `--diff ` mode only files AND lines changed vs are mutated (the PR-gate scope); without it, every gate site in the crate is mutated. @@ -32,9 +39,11 @@ from __future__ import annotations import argparse +import datetime import difflib import fnmatch import glob +import json import os import re import shutil @@ -42,8 +51,14 @@ import subprocess import sys import tempfile -import tomllib -from pathlib import Path + +# tomllib is new in Python 3.11: say so rather than fail on the import below. +if sys.version_info < (3, 11): + sys.exit(f"scripts/umutate.py needs Python 3.11 or newer, for tomllib; this is Python " + f"{sys.version.split()[0]}.") + +import tomllib # noqa: E402 +from pathlib import Path # noqa: E402 ROOT = Path(__file__).resolve().parent.parent OPERATORS_DIR = ROOT / "mutants" / "operators" @@ -261,6 +276,36 @@ def _run_test(test_cmd: str) -> str: return "timeout" +def now() -> str: + """The time, as cargo-mutants writes `start_time` and `end_time`.""" + return datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z") + + +def write_selection(out: Path, selected: list[str]) -> None: + """Write mutants.json: every mutant the run selected, before it tests any. + + The gate holds a run's outcomes to this list, so a run that stops part way is + refused rather than scored on the mutants it reached.""" + (out / "mutants.json").write_text(json.dumps([{"name": n} for n in selected], indent=2) + "\n") + + +def write_outcomes(out: Path, start_time: str, caught: list[str], missed: list[str], + timeouts: list[str]) -> None: + """Write outcomes.json in cargo-mutants' shape: a successful baseline, one outcome per + mutant, and the `end_time` that says the run finished. Written once, when every + selected mutant has an outcome.""" + outcomes = [{"scenario": "Baseline", "summary": "Success"}] + for names, summary in ((caught, "CaughtMutant"), (missed, "MissedMutant"), + (timeouts, "Timeout")): + outcomes += [{"scenario": {"Mutant": {"name": n}}, "summary": summary} for n in names] + (out / "outcomes.json").write_text(json.dumps({ + "outcomes": outcomes, + "total_mutants": len(caught) + len(missed) + len(timeouts), + "caught": len(caught), "missed": len(missed), "timeout": len(timeouts), "unviable": 0, + "start_time": start_time, "end_time": now(), + }, indent=2) + "\n") + + def baseline_ok(test_cmd: str) -> bool: """The test command must pass on the UNMUTATED tree; otherwise every mutant looks 'caught' (non-zero) and the run is meaningless.""" @@ -320,8 +365,13 @@ def cmd_plan(args) -> int: def cmd_run(args) -> int: require_tools() + start_time = now() out = Path(args.output) out.mkdir(parents=True, exist_ok=True) + # An earlier run's record must not outlive this one, whatever this one writes. + for name in ("outcomes.json", "mutants.json", "caught.txt", "missed.txt", "timeout.txt", + "unviable.txt"): + (out / name).unlink(missing_ok=True) caught, missed, timeouts = [], [], [] packs = load_packs(args.packs) changed_files = changed_lines = None @@ -345,21 +395,30 @@ def ensure_baseline(tc: str) -> None: baselined.add(tc) with tempfile.TemporaryDirectory() as tmp: + # Generate every pack's mutants first, so the selection is on disk before + # any mutant is tested. + planned, selected = [], [] for pack in packs: rules = ensure_rules(pack) for src in resolve_targets(pack, changed_files, args.files): md = Path(tmp) / pack["name"] / src.replace("/", "_") allowed = changed_lines.get(src) if changed_lines is not None else None generate_mutants(pack, rules, src, md, allowed) - if not any(p.is_file() for p in md.glob("*")): + files = sorted(p for p in md.glob("*") if p.is_file()) + if not files: continue - ensure_baseline(pack.get("test_cmd", DEFAULT_TEST_CMD)) - c, s, t = analyze(pack, src, md) - for names, sink in ((c, caught), (s, missed), (t, timeouts)): - for name in names: - a = _adapt(pack, src, name, md, allowed) - if a: - sink.append(a) + planned.append((pack, src, md, allowed)) + ids = (_adapt(pack, src, m.name, md, allowed) for m in files) + selected += [a for a in ids if a] + write_selection(out, selected) + for pack, src, md, allowed in planned: + ensure_baseline(pack.get("test_cmd", DEFAULT_TEST_CMD)) + c, s, t = analyze(pack, src, md) + for names, sink in ((c, caught), (s, missed), (t, timeouts)): + for name in names: + a = _adapt(pack, src, name, md, allowed) + if a: + sink.append(a) def write(name, items): (out / name).write_text("\n".join(items) + ("\n" if items else "")) @@ -370,6 +429,11 @@ def write(name, items): # Spec-gate mutants are valid Rust by construction, so there is no unviable # bucket; write an empty file so the gate's reader is happy. write("unviable.txt", []) + # The record the gate scores, in the shape cargo-mutants writes it. With no + # baseline run, no mutant was generated, and the selection written above, + # holding [], says so as cargo-mutants does. + if baselined: + write_outcomes(out, start_time, caught, missed, timeouts) print(f"caught: {len(caught)} missed: {len(missed)} timeout: {len(timeouts)} -> {out}") print(f"score with: python3 scripts/mutation_gate.py report --results {out} " f"--suppressions mutants/suppressions.toml") From 2f21e9bcf2293111f739c2b6466d5c8ec2a494b6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 15:17:31 +0800 Subject: [PATCH 184/201] docs(skills): review the Satin engine as #386, with what #407 still changes The stack merged down into #386, and the skeleton (#385) merged into `satin` first, so the guide now names #386 as the pull request under review and `a8f8c7c9..` as the range that still holds the skeleton. - A table of the engine's modules says which are stable and which #407 still changes, derived from the diff of `cz/feat/satin-w9` against this branch and the work still to land in it; it replaces the old "What follows" section. - The fork bullet keeps this branch's tag pins and names the fork pull requests that review the commit pins #407 moves to. - Module headings, three checks and the decided items #407 revisits say so. --- .claude/skills/satin-review/SKILL.md | 107 +++++++++++++++++---------- 1 file changed, 67 insertions(+), 40 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5b40e67ff..4b6c0e57b 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -1,19 +1,26 @@ --- name: satin-review -description: Guide for reviewing the Satin engine pull request (#385) in megaeth-labs/mega-evm, after the stacked pull requests merged down into it. Use when reviewing #385 or the Satin engine, or when the user says "review satin". Gives the scope, the module map with the invariants to check, the reading order, how to rate a finding and the decisions already made. Temporary: removed before the Satin pull request merges. +description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, which modules are stable and which #407 still changes, the module map with the invariants to check, the reading order, how to rate a finding and the decisions already made. Temporary: removed before the Satin pull request merges. --- -# Reviewing the Satin engine (pull request #385) +# Reviewing the Satin engine (pull request #386) This guide is temporary. It is deleted before the Satin pull request merges, so nothing else may link to it. -It is a map: where each part of the engine lives, what to check there, and what is already decided. +It is a map: where each part of the engine lives, what to check there, what is still changing, and what is already decided. Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them and does not restate them. [`REVIEW.md`](../../../REVIEW.md) is the repository's own review rubric; its consensus-critical list overlaps the checks below. +The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merges. ## What is under review -- The Satin engine, in pull request #385 (`satin` is the base branch; the diff range is `satin..`), judged at its final state once the stacked pull requests #386–#400 and #404 have merged down into it. +- The Satin engine, in pull request #386 (`cz/feat/satin-w2` into `satin`), judged at its final state. + The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) have merged into it; each description explains its part as it was merged, and a later part may have changed an earlier one. +- The review range is `a8f8c7c9..`, `` being the head of #386. + `a8f8c7c9` is the CI-only commit on `satin` before the Satin skeleton; the skeleton (#385) merged into `satin` before #386, so GitHub's diff of #386 no longer shows it, but it is part of the engine under review. + See the whole range with `git diff a8f8c7c9...`. + Most of its deletions are the legacy engine the skeleton removed (183 files): skim them, or hide them with `--diff-filter=d`. +- One pull request still changes part of the engine: #407 (`cz/feat/satin-w9` into this branch), which merges before #386 merges into `satin`; see "What is still moving". - Judge the final code. A defect an earlier commit introduced and a later one fixed is not a defect; history only explains why something is as it is. A test deleted or parked in an intermediate commit is not a finding either: test completeness is judged on the whole. @@ -21,7 +28,9 @@ Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specifi Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` (`v40.0.3-mega.4`) and `megaeth-labs/op-revm` (`v20.0.0-mega.3`) forks at their tags are pinned dependencies with their own review; their diff is not part of this pull request. +- Fork code: the `megaeth-labs/revm` and `megaeth-labs/op-revm` forks are pinned dependencies with their own review; their diff is not part of this pull request. + On this branch they are pinned at the tags `v40.0.3-mega.4` and `v20.0.0-mega.3`. + #407 pins them by commit (`rev`) instead; the fork pull requests megaeth-labs/revm#76 (stacked on megaeth-labs/revm#75) and megaeth-labs/op-revm#8 are the review of those commits. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). - Where code belongs: upstream revm first, then the fork, then mega-evm. @@ -29,6 +38,34 @@ Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specifi For each mechanism, ask whether it sits in the cheapest layer. - The OP base may move (Karst to a later OP fork) before launch; a finding that depends on Karst specifics should say so. +## What is still moving + +#407 changes part of the engine before #386 merges. +It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, and changes the gas detention and write-record rules with it. +The work still to land in it deletes the inspector's rewrite settlement and admission gate, gives the pre-block calls one fixed gas budget, and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction. +Review the stable modules now and a changing one after #407 merges into this branch; if you read a changing module earlier, report a defect only if #407 would not remove it. +This table is updated when #407 merges. +Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. + +| Module | Files | Status | +| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| Block executor and block rules | `src/block/` except `limit.rs`, `eips.rs` and `genesis.rs` | Stable, except the inspector admission gate in `executor.rs` and `factory.rs` | +| System contracts and the system address | `src/system/` except `keyless/`; `crates/system-contracts/` | Stable, except the pre-block call's gas budget in `sequencer_registry.rs` | +| Pricing | `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` | Stable | +| Node surface and the witness | `src/lib.rs`, `src/evm/factory.rs`, `src/evm/state.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs` | Stable; `src/lib.rs` drops the exports of what #407 deletes | +| Tools, benches and CI | `bin/mega-evme/`, `benches/`, `.github/workflows/`, `scripts/`, `mutants/` | Stable; #407 changes how `mega-evme` attaches its tracer and how CI reads a `rev` pin | +| Limits | `src/limit/`, `src/block/limit.rs`, `src/constants.rs` | Changing: the byte pool replaces the lanes; KV and state-growth limits per transaction, frame and block | +| Execution and frames | `src/evm/`: `execution.rs`, `context.rs`, `frame.rs`, `host.rs`, `instructions.rs`, `result.rs`, `mod.rs` | Changing: writes and frame starts in the fork's hooks; the per-frame shares; the destruction refunds | +| Gas detention | `src/access/` | Changing: stipend-funded work is compute; a halting frame's burn is read off the fork | +| Inspector contract | `src/evm/inspector.rs` and the admission gate | Changing: deleted; block execution admits any inspector | +| Keyless deployment | `src/system/keyless/` | Changing | +| Gas schedule | `src/evm/schedule.rs` | Changing: the history allowance and the frame byte share enter the schedule | +| Pre-block calls | `src/block/eips.rs` | Changing: one fixed gas budget | +| Genesis and stateless validation | `src/block/genesis.rs`, `src/evm/validation.rs` | Changing: how a repeated `satinTime`, or one in object form, reads; how intrinsic gas separates history from state | +| Outcome tooling | `crates/state-test/`, `crates/mega-state-test/` except `src/witness.rs` | Changing: an outcome digest, and runs under tighter limits | +| Tests | `tests/` of the changing modules, `src/test_utils/neutral.rs` | Changing with them | +| Specification and guides | `docs/spec/upgrades/satin.md`, `AGENTS.md`, `REVIEW.md` | Changing with the rules above | + ## Running the checks Commands are in [`AGENTS.md`, "Build & Development Commands"](../../../AGENTS.md#build--development-commands) and the gates in [`AGENTS.md`, "Test Gates"](../../../AGENTS.md#test-gates). @@ -50,6 +87,7 @@ A golden or snapshot changes only for a stated reason: regenerate it and read th 4. The node surface, validation and the witness. 5. Tools, tests, goldens and CI. Skim the goldens and snapshots; read what changes them. +Until #407 merges, take the stable modules of the table above first, in this order, and the changing ones after it. Skim without reading: the SALT bucket-hasher internals, the generated pricing table, the tracer snapshots, the receipt goldens and the keyless differential digest. The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; each entry names which to read first. A test name or a line count is not a reason to trust the code: read the code against the spec. @@ -74,7 +112,7 @@ A test name or a line count is not a reason to trust the code: read the code aga Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. For each module: where it is, what to check, the spec sections, and the `AGENTS.md` subsection with the detail. -### Limits: data size, write records, the stop +### Limits: data size, write records, the stop (changing in #407) - **Where:** `src/limit/` (byte table, `LimitKind`, `AdditionalLimit`, `FrameLimitTracker`, `Lane`, `StagedRecord`), `src/block/limit.rs` (`ProtocolLimits::for_spec`), `src/constants.rs`. - **Read first:** the module docs of `src/limit/mod.rs` and `src/limit/limit.rs`. @@ -89,7 +127,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A hint that would cross the limit is neither counted nor forwarded; an admitted hint stays counted through any stop. - **Spec:** §7, §10, §11, §19, §20. **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer). -### Execution and frames +### Execution and frames (changing in #407) - **Where:** `src/evm/execution.rs` (`MegaHandler`, the frame lifecycle), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/host.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`. - **Read first:** the module docs of `src/evm/execution.rs` and `src/evm/host.rs`. @@ -97,13 +135,13 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - The Host only observes; a staged record is committed after the opcode completes and dropped when it fails. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A frame whose start would cross a limit is answered with the stop before it is built, so no value moves; `take_back_a_stopped_answer` takes back what an answer rewritten into a crossing had moved. - - A frame start is counted before revm decides the frame, by predicting its refusals (`caller_refuses_start`, `assert_start_as_counted`); see "What follows" for what changes here. + - A frame start is counted before revm decides the frame, by predicting its refusals (`caller_refuses_start`, `assert_start_as_counted`); #407 replaces the prediction. - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on). - Per-transaction state resets with the transaction; a system call has its own entry point and reservoir split. - **Spec:** §3, §4, §5, §9, §11, §14, §21. **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today). -### Gas detention +### Gas detention (changing in #407) - **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, `hold_precompile` and `settle_answer` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. - **Read first:** the module doc of `src/access/detention.rs`. @@ -113,10 +151,10 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A crossing leaves the frame's gas as it was before the charge and stops the frame with `MegaLimitExceeded(2, limit)`; the caller gets everything the frame had. - A precompile is decided from its price before it runs; one outside the Satin set runs on the allowance. - A system-originated transaction and a system call are never detained. - - Compute today excludes what a callee spends of a value call's 2,300 stipend and counts a halting frame's leftover through the halt-noting machinery; both change (see "What follows"), so report a defect in the current rules only if that change would not remove it. + - Compute today excludes what a callee spends of a value call's 2,300 stipend and counts a halting frame's leftover through the halt-noting machinery; #407 changes both, so report a defect in the current rules only if that change would not remove it. - **Spec:** §12, §13. **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention). -### Block executor and block rules +### Block executor and block rules (stable, except `limit.rs`, `eips.rs` and the inspector gate) - **Where:** `src/block/` (`executor.rs`, `limit.rs`, `result.rs`, `eips.rs`, `l1_block_info.rs`, `factory.rs`, `helpers.rs`). - **Read first:** the module doc of `src/block/executor.rs`. @@ -126,12 +164,12 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A deposit and an MST are never refused by the packing budget or building policy and count towards them; the header gas limit (`BlockLimiter::pre_execution_check`) and the DA footprint (`check_da_footprint`) still apply. - `commit_transaction_outcome` refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal). - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info; a pre-block call that does not succeed makes the block invalid, and a fatal database error is an internal error. - - A rewriting inspector is refused at every block-execution entry, as an internal error. - - The block's ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited. + - A rewriting inspector is refused at every block-execution entry, as an internal error (#407 deletes the gate). + - The block's ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited (#407 adds block limits on KV and state growth). - When the OP base moves, diff the file against the new base's `OpBlockExecutor`. - **Spec:** §1, §18, §19, §20, §21. -### System contracts and the system address +### System contracts and the system address (stable, except keyless) - **Where:** `src/system/` (`intercept.rs`, `oracle.rs`, `control.rs`, `limit_control.rs`, `keyless/`, `tx.rs`, `predeploys.rs`, `sequencer_registry.rs`), `crates/system-contracts/`. - **Read first:** the module doc of `src/system/tx.rs`. @@ -143,12 +181,12 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - An MST is validated (chain id, nonce, EIP-3607) before it is promoted to a deposit. - Satin deploys, upgrades and seeds no predeploy. The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage; anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`. No other block reads them. - An Oracle read in a system call reads chain storage, never the oracle service. - - Keyless: the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set. + - Keyless (changing in #407): the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set. - The interceptor dispatch order is scheme guard, address, selector, then value policy; an unknown selector is not intercepted. - Deployed bytecode and code hashes match the attested artifacts (`build.rs`). - **Spec:** §13, §15, §16, §17, §18, §19. -### Gas schedule and pricing +### Gas schedule and pricing (stable, except `schedule.rs`) - **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`. - **Check:** @@ -162,7 +200,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - The constants are provisional; a build with `satin-price-override` must never reach a node. - **Spec:** §2, §4, §5, §6, §7, §8, §9. -### Inspector contract +### Inspector contract (deleted in #407) - **Where:** `src/evm/inspector.rs`, and the admission checks in `src/evm/mod.rs`, `src/block/factory.rs`, `src/block/executor.rs`. - **Check:** @@ -172,7 +210,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A pre-block system call runs on the plain system-call path, with no callback. - A declared observer must not answer a frame, edit inputs or rewrite a result (checked in debug builds). -### Node surface, validation and the stateless witness +### Node surface, validation and the stateless witness (stable, except genesis and validation) - **Where:** `src/lib.rs` (explicit exports), `src/block/hardfork.rs`, `src/block/chain.rs`, `src/block/genesis.rs`, `src/evm/validation.rs`, `src/evm/state.rs`, `src/block/l1_block_info.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs`. - **Check:** @@ -183,7 +221,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - The witness is the sequence of states the block commits: each pre-block step commits its state on its own, read-only entries included, where a commit hook on `State` receives it whole; nothing else hands the pre-block states out. - **Spec:** §1, §21, §22, "Node integrators". -### Tools, tests, goldens, benches and CI +### Tools, tests, goldens, benches and CI (stable, except the outcome tooling) - **Where:** `bin/mega-evme/` (`bin/mega-evme/src/engine.rs` picks the engine from `--spec`: Satin in-tree, legacy specs on a released crate; `run` and `tx` default to the legacy `Rex6`), `crates/mega-state-test/`, `crates/state-test/`, `crates/mega-evm/tests/` (`satin/`, `block/`, `system/`, `fuzz/`, `tracers/`), `crates/mega-evm/benches/`, `.github/workflows/`, `scripts/`, `mutants/suppressions.toml`. - **Check:** @@ -196,7 +234,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ## Judging a finding -1. **Reachability first.** Does the node's block execution or building path reach it? With the default configuration, or only with a non-default limit? Is it listed below, or in "What follows"? +1. **Reachability first.** Does the node's block execution or building path reach it? With the default configuration, or only with a non-default limit? Is it decided below, or does #407 change it ("What is still moving")? 2. **Severity**, in this order: 1. not reachable from block execution or building: at most low (tools, test APIs); 2. reachable only with a non-default configuration: one level lower; @@ -210,8 +248,9 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. ## Already decided — do not re-report Each is a decision with its reason; "in this pull request" means review the code, not the decision. +An item marked (#407) is one #407 revisits; until it merges, the item describes this branch. -- **KV, state-gas and block execution-gas limits are removed**: data size bounds the records and history gas prices them, state gas prices state, so removal changes no result. +- (#407) **KV, state-gas and block execution-gas limits are removed**: data size bounds the records and history gas prices them, state gas prices state, so removal changes no result. - **Consensus limits are one per-spec table** (`ProtocolLimits::for_spec`), not chain configuration: configured values could stop the L1-attributes deposit and cost a silent factory fallback. - **No latch**: a crossing is a native revert of the crossing frame, which callers may catch; with data size and detention as the only limits no transaction ends over a limit. - **An oversize transaction body is refused at validation** (a deposit becomes a failed deposit): the body is known before execution, and at Satin's constants the bound is unreachable (6,732,889 < 13,107,200). @@ -221,10 +260,10 @@ Each is a decision with its reason; "in this pull request" means review the code - **An MST is never refused by a packing budget or builder policy**: it serves a user transaction already admitted. - **Satin has no deploy or upgrade path**: it runs on a chain that ran the legacy forks, and its activation block refuses any predeploy without Satin's code; no contract changes. - **Keyless refuses only an empty code deposit** at the deploy address; the four producer-less errors are deleted, which changes no deployed byte. -- **Creation revival by an inspector is allowed** (Foundry parity), settled as a frame that kept nothing; the upfront refund is given back at the price it was charged at. +- (#407) **Creation revival by an inspector is allowed** (Foundry parity), settled as a frame that kept nothing; the upfront refund is given back at the price it was charged at. - **The Amsterdam regular gas table is taken wholesale**: the earlier press-back to Osaka priced creation twice. - **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart. An unknown chain has no schedule (`hardfork_schedule` answers `None`). -- **A rewriting inspector in block execution is an internal error**, not a block verdict: the inspector is the node's own choice. +- (#407) **A rewriting inspector in block execution is an internal error**, not a block verdict: the inspector is the node's own choice. - **Explicit crate-root exports; dead helpers and legacy-era remnants are deleted.** - **Satin carries no fork parameter**, and the fork-parameter mechanism was removed with nothing using it. - **An absurd state-gas price makes the operation run out of gas**; no reachable divergence. @@ -232,24 +271,12 @@ Each is a decision with its reason; "in this pull request" means review the code - **Precompile prices are looked up by id**: a precompile set replaced around the engine, through the mutable accessors, keeps the built-in prices; the spec states the boundary, and nodes change the set through `with_dyn_precompiles` or the factory builder. - **A keyless signer that is the block beneficiary is detained**, as in the legacy engine. - **No MST in the activation block**: it admits only deposits and every MST consumer is a non-deposit; documented in the spec. -- **Write records are deduplicated per frame**, not per transaction: documented as an upper bound. +- (#407) **Write records are deduplicated per frame**, not per transaction: documented as an upper bound. - **The limit override is an explicit tool opt-out** (`with_tx_runtime_limits`); block execution and validation use the chain's limits. - **No spec ladder in Satin yet**: it comes with the next spec, with the extension points kept; `AGENTS.md` says how to add it. -- **The fork finalizes the journal on an error** (`bluealloy/revm#3780`, carried early): kept; a fork documentation note is pending. -- **Answered-frame settlement stays in mega-evm**, and `OpBlockExecutor` is not composed (it requires `PostExecEvm` and returns `OpTxResult`). +- **The fork finalizes the journal on an error** (`bluealloy/revm#3780`, carried early): kept; the fork documents it in megaeth-labs/revm#75. +- (#407) **Answered-frame settlement stays in mega-evm**, and `OpBlockExecutor` is not composed (it requires `PostExecEvm` and returns `OpTxResult`). - **The 98/100 frame budget and dropping a hint from a frame whose volatile access is off are kept**: without a latch the budget protects the caller's own work. -- **An inspector answer with effects is mis-accounted** (a mock that transfers value, an isolated run): the settlement assumes none; tools only, kept. -- **Mechanisms kept as in the legacy engine** (not under review): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the data-size limit's 98/100 share, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint, and the inspector admission gate. +- (#407) **An inspector answer with effects is mis-accounted** (a mock that transfers value, an isolated run): the settlement assumes none; tools only, kept. +- **Mechanisms kept as in the legacy engine** (not under review): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the data-size limit's 98/100 share, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint, and the inspector admission gate (#407 deletes the gate). - **The upstream revm change `new_answer`** for answers to frames that did not run (`bluealloy/revm#3979`) is opt-in: the handler does not normalise answers, because real inspectors' answers can have effects. - -## What follows - -Two changes follow this pull request, and the code under review is the code before them. -The first changes detention's final semantics and the frame-start corners, with a small revm fork release. -Detention will count every successful regular charge, stipend-funded work included, with `SSTORE` refills not subtracted, computed in mega-evm from the suspended frames' sum; the halt-noting machinery (`CallerRecord`, `note_halt`, `unbounded_charge!`) goes, and the fork adds only a cold-path record of the gas remaining before a failed charge, so halting frames are exact. -Frame-start records will be counted in `MegaEvm::frame_init` after revm decides the start, replacing the prediction (`caller_refuses_start`, `assert_start_as_counted`); two corners change and go into the spec: a creation onto an occupied address no longer stops the transaction when its records would cross, and a start revm refuses is charged then refunded, so an underfunded caller short of about 7,040 gas halts out of gas. -The fork pin then moves to the next fork tag. -Report a defect in the current rules only if that change would not remove it. - -The second change is a simplification of `limit/` after the first: one byte dimension, no prediction, and counters for hints and transfer logs, with no result change as its target and its own pull request. -It starts from a reviewed design note and may close if the note finds little to slim. From c4bf2d84cc8a09ed9f39c87de414213b5835b1d0 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 15:29:31 +0800 Subject: [PATCH 185/201] docs(skills): review #386 on its own diff against the review base; name what #407 still adds --- .claude/skills/satin-review/SKILL.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 4b6c0e57b..84a73fdfe 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -14,12 +14,15 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg ## What is under review -- The Satin engine, in pull request #386 (`cz/feat/satin-w2` into `satin`), judged at its final state. +- The Satin engine, in pull request #386 (`cz/feat/satin-w2`), judged at its final state. The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) have merged into it; each description explains its part as it was merged, and a later part may have changed an earlier one. -- The review range is `a8f8c7c9..`, `` being the head of #386. - `a8f8c7c9` is the CI-only commit on `satin` before the Satin skeleton; the skeleton (#385) merged into `satin` before #386, so GitHub's diff of #386 no longer shows it, but it is part of the engine under review. - See the whole range with `git diff a8f8c7c9...`. +- The review range is the pull request's own diff. + Its base, `cz/feat/satin-review-base`, is `satin` before the Satin skeleton: `a8f8c7c9`, the CI-only commit before it. + So GitHub's "Files changed" holds the skeleton (#385) and every later series: the whole engine. + The local equivalent is `git diff a8f8c7c9...`, `` being the head of #386. Most of its deletions are the legacy engine the skeleton removed (183 files): skim them, or hide them with `--diff-filter=d`. +- #386 targets the review base only while it is reviewed. + It is retargeted to `satin` before it merges, after #407 has merged into it, and it must never be merged into the review base. - One pull request still changes part of the engine: #407 (`cz/feat/satin-w9` into this branch), which merges before #386 merges into `satin`; see "What is still moving". - Judge the final code. A defect an earlier commit introduced and a later one fixed is not a defect; history only explains why something is as it is. @@ -41,8 +44,8 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg ## What is still moving #407 changes part of the engine before #386 merges. -It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, and changes the gas detention and write-record rules with it. -The work still to land in it deletes the inspector's rewrite settlement and admission gate, gives the pre-block calls one fixed gas budget, and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction. +It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, changes the gas detention and write-record rules with it, and deletes the inspector admission gate. +The work still to land in it runs inspectors on revm's own inspected lifecycle, removing the engine's inspected copies of the frame lifecycle, its step guard and the inspector's rewrite settlement; gives the pre-block calls one fixed gas budget; and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction. Review the stable modules now and a changing one after #407 merges into this branch; if you read a changing module earlier, report a defect only if #407 would not remove it. This table is updated when #407 merges. Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. @@ -57,7 +60,7 @@ Paths are relative to `crates/mega-evm/` unless they start with another top-leve | Limits | `src/limit/`, `src/block/limit.rs`, `src/constants.rs` | Changing: the byte pool replaces the lanes; KV and state-growth limits per transaction, frame and block | | Execution and frames | `src/evm/`: `execution.rs`, `context.rs`, `frame.rs`, `host.rs`, `instructions.rs`, `result.rs`, `mod.rs` | Changing: writes and frame starts in the fork's hooks; the per-frame shares; the destruction refunds | | Gas detention | `src/access/` | Changing: stipend-funded work is compute; a halting frame's burn is read off the fork | -| Inspector contract | `src/evm/inspector.rs` and the admission gate | Changing: deleted; block execution admits any inspector | +| Inspector contract | `src/evm/inspector.rs` and the admission gate | Changing: deleted; inspectors run on revm's inspected lifecycle, and block execution admits any inspector | | Keyless deployment | `src/system/keyless/` | Changing | | Gas schedule | `src/evm/schedule.rs` | Changing: the history allowance and the frame byte share enter the schedule | | Pre-block calls | `src/block/eips.rs` | Changing: one fixed gas budget | From 85a418d8dfca962d4c999c25179922035b1b4506 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Thu, 22 Oct 2026 17:05:59 +0800 Subject: [PATCH 186/201] docs(skills): state the revert-or-halt rule and its deliberate exceptions --- .claude/skills/satin-review/SKILL.md | 34 +++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 84a73fdfe..da59e8e49 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -1,6 +1,6 @@ --- name: satin-review -description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, which modules are stable and which #407 still changes, the module map with the invariants to check, the reading order, how to rate a finding and the decisions already made. Temporary: removed before the Satin pull request merges. +description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, which modules are stable and which #407 still changes, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. --- # Reviewing the Satin engine (pull request #386) @@ -46,6 +46,7 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg #407 changes part of the engine before #386 merges. It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, changes the gas detention and write-record rules with it, and deletes the inspector admission gate. The work still to land in it runs inspectors on revm's own inspected lifecycle, removing the engine's inspected copies of the frame lifecycle, its step guard and the inspector's rewrite settlement; gives the pre-block calls one fixed gas budget; and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction. +That work also makes a write that crosses a frame's budget and the transaction's limit at once name the budget in its stop. Review the stable modules now and a changing one after #407 merges into this branch; if you read a changing module earlier, report a defect only if #407 would not remove it. This table is updated when #407 merges. Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. @@ -248,6 +249,37 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. 4. **A mechanism** is open to question unless the Satin design settled it: ask what problem it solves, whether that problem still exists, whether a native replacement exists, and how it could be simpler. 5. A consensus defect is a difference in state root, receipts root, gas used, logs or block validity between two honest nodes, or between the engine and its specification. +## Revert or halt + +Read this before rating a finding that says a failure reverts where it should halt, or halts where it should revert. + +A refusal the protocol imposes reverts; an execution fault halts. +Every limit stop — the transaction's data-size limit, a frame's data-size budget, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, which resumes and may catch the stop. +An execution fault — a real out-of-gas, a precompile given less than its price, an invalid opcode, a charge the frame cannot pay — halts and consumes the frame's gas, as in revm. +One ABI serves every kind of stop, and there is no third ending: the halt reasons are op-revm's (`MegaHaltReason`), and the engine makes no halt of its own. + +The KV and state-growth stops, and naming the frame budget rather than the transaction limit when a write crosses both, are still to land in #407; on this branch such a write names the transaction limit (`AdditionalLimit::check`). + +The deliberate exceptions: + +| What happens | Why | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose execution halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | +| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set: the size check is the precompile's own input check, which fails the call like any bad input. Gas detention prices such an input at zero, so it is never a crossing. | +| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs, and it decides from the price; a check made after the gas check is not visible to it. A precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | +| A call whose start (its value transfer's records and transfer log) crosses the data-size limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward. | A limit is enforced at the writes it guards, and a start writes before its callee runs. Here the start is counted before revm runs the callee, which then never runs; #407 counts it after revm answered and replaces a failed answer with the stop, to the same end. | +| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made. Of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | +| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data. All are catchable, and the outcome's `limit_exceeded` stays empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | +| One size rule has three endings: initcode over the size limit is rejected at validation in a creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`. Deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes: rules of the EVM, not MegaETH's resource limits, so they stay halts. A keyless call checks the init code among its rules before any creation starts, and every rule refuses with a revert and its own error. | + +Not exceptions, but easy to mistake for one: + +- A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an EIP-7702 authorization's charges, the history of the records made before the first frame — ends out of gas with no frame: its whole regular budget is consumed and its reservoir returned. + That is EIP-2780's runtime out-of-gas path, a gas fault (`pre_execution` in `src/evm/execution.rs`). +- A keyless creation that reverts, halts or is stopped makes the `keylessDeploy` call succeed, with `ExecutionReverted`, `ExecutionHalted` or `EmptyCodeDeployed` in its ABI return, a stop's revert data carried inside `ExecutionReverted`. + The call itself reverts with the stop only when its own charges or the signer's nonce record cross a limit (`answer` in `src/system/keyless/settle.rs`). +- Under gas detention, only a regular charge the withheld part would have paid is a crossing; a charge beyond the frame's whole regular gas, and a failed state or history charge, halt as they would without the read. + ## Already decided — do not re-report Each is a decision with its reason; "in this pull request" means review the code, not the decision. From 5c48df462d9becfed34c56ff05cccb6a0477fd7f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 09:03:25 +0800 Subject: [PATCH 187/201] docs(skills): the Satin review guide at the engine's final state --- .claude/skills/satin-review/SKILL.md | 393 +++++++++++++++++++-------- 1 file changed, 273 insertions(+), 120 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index da59e8e49..5f51a5eae 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -1,29 +1,29 @@ --- name: satin-review -description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, which modules are stable and which #407 still changes, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. +description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine: the stacked pull requests merged into it, and #407 merges into it before it is retargeted. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. --- # Reviewing the Satin engine (pull request #386) This guide is temporary. It is deleted before the Satin pull request merges, so nothing else may link to it. -It is a map: where each part of the engine lives, what to check there, what is still changing, and what is already decided. -Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them and does not restate them. +It is a map: where each part of the engine lives, what to check there, what changed after the stacked pull requests were described, and what is already decided. +Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them, and restates a rule only to say what changed. [`REVIEW.md`](../../../REVIEW.md) is the repository's own review rubric; its consensus-critical list overlaps the checks below. -The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merges. +The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. ## What is under review - The Satin engine, in pull request #386 (`cz/feat/satin-w2`), judged at its final state. - The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) have merged into it; each description explains its part as it was merged, and a later part may have changed an earlier one. + The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) merged into it, and #407 (`cz/feat/satin-w9`) merges into it next; each description explains its part as it was merged, and a later part may have changed an earlier one. + "Design changes a reviewer must know" below lists what #407 changed. - The review range is the pull request's own diff. Its base, `cz/feat/satin-review-base`, is `satin` before the Satin skeleton: `a8f8c7c9`, the CI-only commit before it. So GitHub's "Files changed" holds the skeleton (#385) and every later series: the whole engine. The local equivalent is `git diff a8f8c7c9...`, `` being the head of #386. - Most of its deletions are the legacy engine the skeleton removed (183 files): skim them, or hide them with `--diff-filter=d`. + Most of its deletions are the legacy engine, its tests and its tools (184 files): skim them, or hide them with `--diff-filter=d`. - #386 targets the review base only while it is reviewed. - It is retargeted to `satin` before it merges, after #407 has merged into it, and it must never be merged into the review base. -- One pull request still changes part of the engine: #407 (`cz/feat/satin-w9` into this branch), which merges before #386 merges into `satin`; see "What is still moving". + It is retargeted to `satin` before it merges, and it must never be merged into the review base. - Judge the final code. A defect an earlier commit introduced and a later one fixed is not a defect; history only explains why something is as it is. A test deleted or parked in an intermediate commit is not a finding either: test completeness is judged on the whole. @@ -31,9 +31,8 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` and `megaeth-labs/op-revm` forks are pinned dependencies with their own review; their diff is not part of this pull request. - On this branch they are pinned at the tags `v40.0.3-mega.4` and `v20.0.0-mega.3`. - #407 pins them by commit (`rev`) instead; the fork pull requests megaeth-labs/revm#76 (stacked on megaeth-labs/revm#75) and megaeth-labs/op-revm#8 are the review of those commits. +- Fork code: the `megaeth-labs/revm` fork at `2fc8edf33b2ffddb195cebc17be9adabfd95417c` and the `megaeth-labs/op-revm` fork at `f599efdabc3e5b36a280f1aa72978751bd64c160`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. + Their diff is not part of this pull request. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). - Where code belongs: upstream revm first, then the fork, then mega-evm. @@ -43,32 +42,125 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg ## What is still moving -#407 changes part of the engine before #386 merges. -It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, changes the gas detention and write-record rules with it, and deletes the inspector admission gate. -The work still to land in it runs inspectors on revm's own inspected lifecycle, removing the engine's inspected copies of the frame lifecycle, its step guard and the inspector's rewrite settlement; gives the pre-block calls one fixed gas budget; and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction. -That work also makes a write that crosses a frame's budget and the transaction's limit at once name the budget in its stop. -Review the stable modules now and a changing one after #407 merges into this branch; if you read a changing module earlier, report a defect only if #407 would not remove it. -This table is updated when #407 merges. -Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. - -| Module | Files | Status | -| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -| Block executor and block rules | `src/block/` except `limit.rs`, `eips.rs` and `genesis.rs` | Stable, except the inspector admission gate in `executor.rs` and `factory.rs` | -| System contracts and the system address | `src/system/` except `keyless/`; `crates/system-contracts/` | Stable, except the pre-block call's gas budget in `sequencer_registry.rs` | -| Pricing | `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` | Stable | -| Node surface and the witness | `src/lib.rs`, `src/evm/factory.rs`, `src/evm/state.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs` | Stable; `src/lib.rs` drops the exports of what #407 deletes | -| Tools, benches and CI | `bin/mega-evme/`, `benches/`, `.github/workflows/`, `scripts/`, `mutants/` | Stable; #407 changes how `mega-evme` attaches its tracer and how CI reads a `rev` pin | -| Limits | `src/limit/`, `src/block/limit.rs`, `src/constants.rs` | Changing: the byte pool replaces the lanes; KV and state-growth limits per transaction, frame and block | -| Execution and frames | `src/evm/`: `execution.rs`, `context.rs`, `frame.rs`, `host.rs`, `instructions.rs`, `result.rs`, `mod.rs` | Changing: writes and frame starts in the fork's hooks; the per-frame shares; the destruction refunds | -| Gas detention | `src/access/` | Changing: stipend-funded work is compute; a halting frame's burn is read off the fork | -| Inspector contract | `src/evm/inspector.rs` and the admission gate | Changing: deleted; inspectors run on revm's inspected lifecycle, and block execution admits any inspector | -| Keyless deployment | `src/system/keyless/` | Changing | -| Gas schedule | `src/evm/schedule.rs` | Changing: the history allowance and the frame byte share enter the schedule | -| Pre-block calls | `src/block/eips.rs` | Changing: one fixed gas budget | -| Genesis and stateless validation | `src/block/genesis.rs`, `src/evm/validation.rs` | Changing: how a repeated `satinTime`, or one in object form, reads; how intrinsic gas separates history from state | -| Outcome tooling | `crates/state-test/`, `crates/mega-state-test/` except `src/witness.rs` | Changing: an outcome digest, and runs under tighter limits | -| Tests | `tests/` of the changing modules, `src/test_utils/neutral.rs` | Changing with them | -| Specification and guides | `docs/spec/upgrades/satin.md`, `AGENTS.md`, `REVIEW.md` | Changing with the rules above | +Nothing, once #407 merges into this branch. +#407 holds everything its description listed as still to be added: inspectors on revm's own inspected lifecycle, a rewritten result taken as given, one fixed gas budget for the pre-block calls, the cleanups, and the KV-update and state-growth limits with their 98/100 frame shares and the destruction table's give-backs. +It also counts a creator's nonce record when the creation returns, which its description did not list. +Until #407 merges, the final code of the modules it changes is on its head (`cz/feat/satin-w9`). +With #407 merged, every module is at its final state for this review: there is no longer a table of stable and changing modules, nor a rule to hold back findings in a changing one. +What follows this pull request changes no rule. +The fork pins move from the reviewed commits to the merged commits of megaeth-labs/revm#76 and megaeth-labs/op-revm#8, and to release tags once the line is final. +Performance work is left for later: the optimisations #407 recorded are made together once the structural work is done, measured against CodSpeed's report. + +## Design changes a reviewer must know + +The stacked pull requests' descriptions predate #407, which changed parts of what they describe. +Each change is stated here in plain words with its reason; the specification has the rule and `AGENTS.md` the mechanism. + +### Where the engine meets revm + +- **Inspectors run on revm's own inspected lifecycle, and the engine has no inspector-specific code.** + The engine's inspected copies of the frame lifecycle, its step guard and `src/evm/inspector.rs` are gone: every per-frame mechanism sits in the frame start, run result and return (`frame_init`, `frame_run_result`, `frame_return_result`) that revm's plain and inspected loops share. + A result an inspector rewrites is settled by the caller as revm settles it, with no correction of the engine's, and an answer it gives in place of a frame never reaches the engine's frame start, so the depth guard, the interceptors and gas detention see none of it. + Block execution admits any inspector. + Why: a second copy of the lifecycle had to be kept in step with revm's and made an inspected run differ from a plain one, and which inspectors run on block production is the node's choice. +- **The fork's loop hooks.** + revm's frame run returns an action set on a frame before it runs, without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`: a `keylessDeploy` call's creation and answer, and the stop of a caller a child left over a limit, come back through revm's own run. + The run-result hook (`EvmTr::frame_run_result`) is called once a frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end` and before `frame_return_result`; gas detention turns a crossing into the stop there, so inspectors and tracers see the stop the caller gets. + Why: both are points in the middle of revm's own loop that mega-evm cannot reach from outside, which is what the fork is for, and with them the engine has no frame run of its own. +- **Writes and frame starts are metered in the fork's instruction hooks.** + `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made. + The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, and the frame's own part is declared on the start (`FrameStart::charge`) for the fork to refund when the frame fails. + Why: a write the opcode's own failure takes back is never counted, and the engine no longer rebuilds revm's state from outside with instruction wrappers. + +### What is counted + +- **Data size, KV updates and state growth are pools on revm's gas tracker.** + Each is a pool on every frame's `GasTracker`, which the fork forwards to a child at a start and settles on the child's return as it settles the EIP-8037 reservoir; the transaction's limits are held beside the pools, on what the transaction keeps. + The engine's per-frame record lanes, its journal wrapper and its ledger are gone, and the context's journal is revm's own. + Why: a frame's budget then fails and succeeds with the frame's own gas, by revm's settlement, instead of a second account kept beside the journal. +- **Write records follow the net change.** + An account's record exists while its nonce, balance or code differs from what the transaction loaded, and a slot's while its value differs from its original. + The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes. + Why: the record measures the state the transaction keeps, by revm's own notion of a change; the per-frame count over-counted, and charged history gas for writes that leave nothing. +- **A frame start is held to the limits once revm decided it.** + Its records and transfer log are read off the journal before revm decides the start, and counted on the started frame's pools once it has. + A frame revm built returns the stop before its first instruction, and an answer revm gave without building a frame gives way to the stop on the untouched forward, a success's value move taken back. + A creation onto an occupied address fails on the collision, and is not stopped for what its start would count. + Why: the limit judges what the start did, instead of a prediction of revm's refusals that duplicated revm's rules in the engine; the opcode's history charge is still priced from the journal's state before revm decides, which on the plain path is exact because the opcode makes revm's refusal checks first. +- **A creator's nonce record is counted on the creator when the creation returns with the nonce bumped.** + The creation's budget is the share taken at the opcode, before that record, which is Rex6's order. + The record is held to the creator's budget, not the creation's, and survives the creation's failure; a keyless signer's is counted on the call at its settlement, and the keyless creation's share is of the call's whole pools, which the call draws nothing from before it. + The frame-start hook only prices: it charges the start's history and counts nothing (`hold_creator` in `src/evm/execution.rs` counts the record). + A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing, and its records are those revm then made; the specification says nothing of inspectors, and `AGENTS.md` states this. + Why: the bump is a fact only once revm made it, and the creator's pools are in reach again only at the return, so nothing is counted before revm decides and nothing has to be given back. +- **A frame a failure below it left over the transaction's limit is stopped as it resumes.** + A failed frame's counts go back to what the frames kept when it started, a record of theirs it took back included, while an Oracle hint it admitted stays counted; a hint sent into the room such a take-back freed leaves the transaction over its data-size limit, and the frame it returns into returns the transaction's stop before its next instruction (`AdditionalLimit::hold_caller`), whether the frame below reverted, halted or was itself stopped. + Why: without it a caller that catches the failure could end the transaction above its limit. +- **KV updates and state growth are limited again**, per transaction (`TX_KV_UPDATE_LIMIT` = 500,000 write records, `TX_STATE_GROWTH_LIMIT` = 1,000 new accounts and slots), per frame (98/100 of what the parent has left) and per block (`BLOCK_KV_UPDATE_LIMIT` = 500,000, `BLOCK_STATE_GROWTH_LIMIT` = 1,000, packing budgets as the block's data size is). + The KV count is the write-record count. + State growth rises by one where EIP-8037 charges the state gas of one new account or slot, and for the caller a failed deposit creates, which pays no state gas; it falls when a slot whose original is zero is written back to zero; a frame's net is signed, and a negative net never enlarges a child's budget. + An EIP-7702 list that would cross either limit is skipped whole, and the transaction's own frame is stopped before it runs. + Why: these are Rex6's limits, and gas does not stand in for the count: 1,000 fresh slots cost 97,920,000 state gas, which a gas limit can cover; at Satin's constants data size binds before the KV count, and the KV check is still made. +- **The destruction table.** + The first effective `SELFDESTRUCT` of an account created in the same transaction gives back what the transaction made of it: each part absent at the transaction's start and present before the destruction — the account leaf, its deployed code, each slot written non-zero — is refilled at the state gas it was charged, to the destroying frame; the leaf and each such slot lower state growth by one and have their write records and those records' history taken back, and the code's data size and history gas are taken back. + A slot's value at the start is its original in the transaction, so a slot of the created account first accessed after the creation is zero there whatever the state held; a leaf is absent when no account stood at the address: the database answered none (`None`, not an empty account), or an earlier transaction on the same journal destroyed it (`Accounts::was_absent_at_start` in `src/limit/record.rs`). + A part present at the start is an ordinary deletion; a failure of the destroying frame, or of a frame that contains it, discards all of it. + From the mark the account adds no further state growth or record, and every state charge on it is priced at nothing (`Host::state_gas_price`), so a later `SSTORE` or a deposit of its constructor's code is never charged state gas rather than charged and refilled; the table's own give-back prices outside that rule (`MegaContext::priced_state_gas`). + The neutral configuration counts the table and prices state gas as the fixture's fork does, which gives none back, so equivalence mode's transactions that create and destroy an account report other usage than before the table, and nothing else differs. + The op-revm baseline pins the divergence (`test_a_creation_that_destroys_itself_diverges_from_op_revm`). + Why: a part the transaction made does not remain for a node to store, so the count and the charge stay aligned; EIP-8037 refills nothing for this destruction and Rex6 refunded no storage gas, so this departs from both on purpose. +- **A fact about a transaction's start is read off that transaction's journal.** + revm's account flags of a database load (`LoadedAsNotExisting`), of a touch and of a destruction are set once per journal and outlive the transaction that set them when a journal runs several transactions without finalizing; the engine reads such a fact with what the journal records of the running transaction — the original info, the transaction id of what it loaded, its entries (`JournalEntry::AccountDestroyed`'s status, `AccountTouched`) and the local created and destroyed flags — and never off such a flag alone. + So what the engine decides on such a journal follows what revm charges there, as it does on a fresh one: the destruction table's leaf, the keyless empty-deposit rule and its answer (`Accounts::is_destroyed`), and the authorities an EIP-7702 list created (`applied_authorities` in `src/evm/execution.rs`, which counts one where revm charged it a new account). + Why: a node's block executor finalizes each transaction, but `transact_one` on the public API does not, and a count must not part from its charge on either path. + +### Gas + +- **The 98/100 forwards.** + A call or a creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, in place of EIP-150's 63/64 (the schedule's `call_stipend_reduction`, 50), and a value call's 2,300 stipend is added after the cap. + Every child receives `remaining − remaining × 2 / 100` of the caller's reservoir, whatever regular gas the call asks for; the transaction's own frame and a system call's outermost frame take the whole reservoir, and a keyless deployment's creation forwards `min(gasLimitOverride, remaining)` of regular gas with the reservoir share. + The three pools give a child `remaining × 98 / 100`, rounded down, so the two formulas differ at some values. + Why: the regular forward is Rex6's, and the reservoir share keeps a caller's own work within reach of what it calls, since state and history gas draw the reservoir first; EIP-8037 passes the reservoir whole, which would let a callee spend all of it. +- **The history allowance replaces the storage-gas stipend.** + A value `CALL` or `CALLCODE` below the transaction's own frame gives the frame it starts 160 bytes of history (`HISTORY_ALLOWANCE_BYTES`, 14,080 gas at the cost per history byte, the schedule's `call_history_allowance`), on which only a log's history charge draws. + It never enters the frame's gas and is on no ledger. + Why: a `receive()` reached through Solidity's `transfer()` can still emit one event, and an allowance that is not gas leaves nothing to burn on return. +- **One fixed gas budget for the pre-block calls.** + Each runs on `PRE_BLOCK_CALL_GAS_LIMIT` = 31,566,720, whatever the block's gas limit: 30,000,000 of regular gas and a reservoir of sixteen fresh slots at the minimum bucket. + Why: a pre-block call does not draw on the block's gas; Rex6's `max(block gas limit, 30,000,000)` was widened for storage gas a crowded bucket multiplied, which a system call no longer pays; a pre-block call on MegaETH's chains writes at most six fresh slots, and none of the three contracts reads `GAS`. + +### Gas detention + +- **Compute counts the work run on a value call's stipend, and never what a halting frame burns.** + The stipend is not forwarded gas, so what a callee runs on it is compute, and what it leaves of it does not lower compute when it comes back. + What a halting frame burned is read off the fork's failed-charge record and is not compute, so no halt takes a detained transaction past its limit. + Why: the old figure let a callee spend the stipend uncounted after a read, and counting the gas a halting frame had left overshot the limit. +- **A value call's own charges come first.** + Its static 100, its memory, the 11,300 value transfer and a cold access are decided as any opcode's charges are, and one that crosses the limit stops the calling frame before anything moves, whether or not the caller can fund the value; only then is a precompile decided from its price. + Why: an opcode's own charges are held where they are made, and the outcome must not depend on whether the value could be funded; the specification now says so where it states the precompile exception. +- **The volatile-data rules.** + `BLOBHASH` is not volatile: it reads the transaction's own blob hashes. + `SLOTNUM` is a read of the block environment, and its refusal carries access type 12, which the contract's enum does not declare, so a handler decodes the argument as a `uint8`. + A call to the EIP-2935 history contract is a read of the block environment, through the `NUMBER` its `get` path executes before it loads the slot; an `SLOAD` of the storage the EIP-2935 and EIP-4788 pre-block calls wrote is state the block starts with, and is no read. + A `CREATE` or `CREATE2` is neither marked nor refused for loading its creator or created address, the block beneficiary included. + Why: volatile data is data the block, the sequencer or the oracle changes under the transaction; the blob hashes are the transaction's own, the history contract's answer depends on the block number it reads, the pre-block storage is fixed before the first transaction, and a creation's loads are the creation opcode's own checks under EIP-8037, as a value call's check of its caller's balance is. + +### The stop and the configuration + +- **Limit stops are revert-class in four dimensions, in a fixed order.** + A crossing of data size (kind 0), KV updates (kind 1), state growth (kind 3) or gas detention's compute limit (kind 2) reverts the crossing frame with `MegaLimitExceeded(kind, limit)`, and its caller may catch it. + An operation that crosses several counted dimensions at one site stops on the first of data size, KV updates, state growth; compute is decided at the regular charge, before the write is counted. + Inside a dimension the frame budget is tested first, and the stop names the budget whenever the budget is crossed, the transaction limit only when it is not. + Why: the order across dimensions and the discriminants are Rex6's, so a Rex6 decoder reads the stop, and a frame that crosses its budget is told the budget it crossed. +- **Limits files of the first shape still run.** + A limits file written before the KV-update and state-growth limits returned, such as one given to `mega-evme --override.limits`, reads with the default spec's values for the four newer fields; every field that shape had stays required, and an unknown field is refused. + Why: a tool's existing files keep working; consensus never reads such a file. +- **Smaller changes of the node surface.** + A Satin key given twice in a genesis `config` object is read as its last copy by every reader, because a node and the reference CLI parse the file into a JSON value that keeps only the last copy. + `satinTime` is also read from `{"$serde_json::private::Number": ""}`, decimal digits alone, the form `serde_json` hands a number over in with `arbitrary_precision` on. + A witness replay's exports must be a subset of the building node's and may be a proper one, because the building node's also hold what candidates it executed and dropped asked for. + Satin's configuration fixes off the fork's switch back to revm 40.0.3's journal semantics, which exists for the legacy engine. + The handler splits a system call's gas itself, at most `SYSTEM_CALL_REGULAR_GAS_LIMIT` = 30,000,000 of it regular, and reads the reservoir a result settled with (`AdditionalLimit::reservoir_remaining`), which the fork no longer does. ## Running the checks @@ -80,35 +172,41 @@ Four notes that are easy to miss: - after any test change, run `scripts/price_grid.sh --pr`; - the execution-spec gate needs Ethereum's fixture releases, at the versions `.github/workflows/exec-spec-satin.yml` downloads. -Evidence that a change alters no result: `state-test --mode satin --json-outcome` at two commits, detached, sorted and compared byte for byte, plus the gates and the byte-price grid. +Evidence that a change alters no result: `state-test --json-digest` at two commits, detached, over both fixture releases, in equivalence mode, in Satin mode and in Satin mode under tighter limits (the `--limit-*` options), each sorted and compared byte for byte, plus the gates and the byte-price grid. +The digest hashes each transaction's whole outcome, its gas by ledger and its usage counts included, so it catches a shift between ledgers that `--json-outcome` does not. A golden or snapshot changes only for a stated reason: regenerate it and read the diff. ## Reading order -1. The consensus core: limits (the vocabulary of lane, stop and crossing), then execution and frames with gas detention, then the block executor, then the system contracts and system address. +1. The consensus core: limits (the vocabulary of pool, record, stop and crossing), then execution and frames with gas detention, then the block executor, then the system contracts and system address. 2. The gas schedule and pricing. 3. The inspector contract. 4. The node surface, validation and the witness. -5. Tools, tests, goldens and CI. Skim the goldens and snapshots; read what changes them. +5. Tools, tests, goldens and CI. + Skim the goldens and snapshots; read what changes them. -Until #407 merges, take the stable modules of the table above first, in this order, and the changing ones after it. Skim without reading: the SALT bucket-hasher internals, the generated pricing table, the tracer snapshots, the receipt goldens and the keyless differential digest. -The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; each entry names which to read first. +The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; where an entry names what to read first, start there. A test name or a line count is not a reason to trust the code: read the code against the spec. ## Glossary of the terms the checks use - **Live system address**: the address the `SequencerRegistry` names (`_currentSystemAddress`). - `MEGA_SYSTEM_ADDRESS` in code is only the default a test's registry names (`test_utils::MemoryDatabase::sequencer_registry`). + `MEGA_SYSTEM_ADDRESS` in code is only the address the registry named when Rex5 created it, which a chain's registry holds until a rotation. - **Pre-block caller**: `0xff…fe`, the EIP-4788 system address, the caller of the pre-block system calls. It is a different address from the live system address. - **MST** (Mega System Transaction): a signed legacy transaction from the live system address to a whitelisted system contract (today the Oracle), promoted to a deposit by the engine. - **System-originated** (spec §19, `originates_from_the_protocol` in `src/system/tx.rs`), decided from the transaction's own fields: an MST before or after promotion; any transaction whose caller is the pre-block caller; any deposit carrying the source hash the promotion stamps, `keccak256("MEGA_SYSTEM_TRANSACTION")`, whoever sends it. - Such work is exempt from history gas, per-transaction limits and detention, and priced at the minimum bucket. -- **Lane**: the per-frame record of data size and write records; a success merges into the caller's lane, a failure discards it. -- **Stop**: what a limit does. The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, its caller resumes and may catch it. -- **Answered frame**: a frame that gets a result without running (an interceptor, the engine, an inspector's hook). + Such work is exempt from history gas, every per-transaction limit and frame budget, and detention, and priced at the minimum bucket; its usage is still counted. +- **Pool**: a frame's budget in data size, KV updates or state growth, held on its `GasTracker`; the fork forwards a child its share at the start and settles the child's pools on its return, as it does the reservoir. +- **Write record**: one per account or storage slot the transaction keeps changed, by the net change; 40 bytes of data size and of history; the KV count. +- **State growth**: the net count of new accounts and new slots the transaction keeps. +- **Stop**: what a limit does. + The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, and its caller resumes and may catch it. +- **Answered frame**: a frame that gets a result without running (a precompile, a call to an account with no code, an interceptor, the engine, an inspector's hook). +- **Start charge**: the history gas a frame start charges its caller for the records the started frame makes, declared on the start and refunded by the fork when the frame fails. +- **Failed-charge record**: the regular gas a frame had before a charge that failed, which the fork keeps, so the engine knows exactly what a halting frame burned. - **Byte-price grid**: the CI job that runs the suite at other costs per state and history byte, because the prices are provisional. ## Module map @@ -116,64 +214,82 @@ A test name or a line count is not a reason to trust the code: read the code aga Paths are relative to `crates/mega-evm/` unless they start with another top-level directory. For each module: where it is, what to check, the spec sections, and the `AGENTS.md` subsection with the detail. -### Limits: data size, write records, the stop (changing in #407) +### Limits: data size, KV updates, state growth, the stop -- **Where:** `src/limit/` (byte table, `LimitKind`, `AdditionalLimit`, `FrameLimitTracker`, `Lane`, `StagedRecord`), `src/block/limit.rs` (`ProtocolLimits::for_spec`), `src/constants.rs`. -- **Read first:** the module docs of `src/limit/mod.rs` and `src/limit/limit.rs`. +- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`. +- **Read first:** the module doc of `src/limit/mod.rs` and the doc of `AdditionalLimit` in `src/limit/limit.rs`. - **Check:** - - A record is counted where it is made and taken back with its frame; the one exception is a failed creation's creator-nonce record, which lands on the creator and is held to the creator's limits. - - The transaction limit is checked before the frame budget, at one site (`AdditionalLimit::check`); every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work. - - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a charge of its own crosses again. - - `LimitKind` keeps its encoding: data size 0, compute gas 2, and `from_u8` answers `None` for 1 and 3. - - Limits are per-spec constants, never chain configuration; a bare `MegaContext` defaults to them; `BlockLimits` is builder policy and can only tighten. - - Nothing limits the KV count, state growth or the block's execution gas; the ledgers and `BlockGasCounters` report them. + - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas. + - The transaction's limits are held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints, the authorities' records and the accounts they created, a deposit's created caller, and what the frames keep, restored when a start's frame keeps nothing (`AdditionalLimit::close_start`). + - A completed write and a decided start are held in one function (`AdditionalLimit::check`, through `draw`, `count_start` and `hypothetical_start`): in the order data size, KV updates, state growth (`limit::COUNTED`), the frame budget, then the transaction limit; a hint, the authorization list and a caller's hold at a child's return check the same limits directly. + - The stop names the budget when the budget is crossed, and the transaction limit only when it is not, which a framed write reaches only in data size, after Oracle hints used what the transaction had left; a start names it too when a deposit-like transaction's created caller stands on a state-growth limit of nothing, which only a tool's limit sets. + - Every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work and system calls. + - A write record follows the net change: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original; the sender's account and the fee credits the settlement makes are the body's, not records. + - A creator's nonce record is counted on the creator when the creation returns with the nonce bumped, held to the creator's budget, and survives the creation's failure; the creation's budget is the share taken at the opcode, before it. + - State growth rises by one at each EIP-8037 account-leaf or fresh-slot charge site and for the caller a failed deposit creates, and a slot written from an original zero back to zero falls by one; a frame's net is signed, a negative net never enlarges a child's budget (`cap_the_shares` in `src/evm/execution.rs`), and a transaction reports `max(net, 0)`. + - The first effective `SELFDESTRUCT` of an account created in the transaction applies the destruction table: each part absent at the transaction's start (a slot by its original in the transaction, a leaf by no account standing there) and present before the destruction is refilled at the price it was charged, to the destroying frame, the leaf and each such slot lower state growth by one and lose their write records, and the code's data size and history gas are taken back; from the mark the account adds no further state growth, state gas or write record, and a failure of the destroying frame, or of a frame that contains it, discards it all. + - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a count or a charge of its own crosses again; a caller a failure below it left over the transaction's data-size limit, a hint having filled room a take-back freed, returns the transaction's stop before its next instruction (`AdditionalLimit::hold_caller`). + - `LimitKind` keeps Rex6's encoding: data size 0, KV updates 1, compute gas 2, state growth 3. + - Limits are per-spec constants, never chain configuration; a bare `MegaContext` runs under them; `BlockLimits` is builder policy and can only tighten. - `KV × 40 ≤ data size` holds after every instruction. + - An EIP-7702 list long enough to cross the KV-update or state-growth limit is simulated whole before the first frame, writing and warming nothing; one that would cross is skipped whole, and the transaction's own frame is stopped before it runs (`hold_authorization_list` in `src/evm/execution.rs`); a shorter list cannot cross and is applied as EIP-7702 applies it. - A hint that would cross the limit is neither counted nor forwarded; an admitted hint stays counted through any stop. -- **Spec:** §7, §10, §11, §19, §20. **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer). +- **Spec:** §7, §10, §11, §19, §20. +- **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer). -### Execution and frames (changing in #407) +### Execution and frames -- **Where:** `src/evm/execution.rs` (`MegaHandler`, the frame lifecycle), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/host.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`. -- **Read first:** the module docs of `src/evm/execution.rs` and `src/evm/host.rs`. +- **Where:** `src/evm/execution.rs` (`MegaHandler`; `MegaEvm`'s frame start and return, `frame_init` and `frame_return_result`, and the run-result hook `frame_run_result`), `src/evm/host.rs` (the completed-write and frame-start hooks), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`. +- **Read first:** the docs of `frame_init` and `frame_return_result` in `src/evm/execution.rs`, and the module doc of `src/evm/host.rs`. - **Check:** - - The Host only observes; a staged record is committed after the opcode completes and dropped when it fails. + - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. + - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. + - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. + - A start's records and transfer log are read off the journal before revm decides the start (the engine's `FrameStart::of` in `src/evm/execution.rs`) and counted on the started frame's pools once it has (`AdditionalLimit::count_start`); a start revm refuses on its caller's account counts nothing and is charged nothing. + - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); an answer revm gave gives way to the stop on its untouched forward, and a success's value move and log are taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`). - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - - A frame whose start would cross a limit is answered with the stop before it is built, so no value moves; `take_back_a_stopped_answer` takes back what an answer rewritten into a crossing had moved. - - A frame start is counted before revm decides the frame, by predicting its refusals (`caller_refuses_start`, `assert_start_as_counted`); #407 replaces the prediction. - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. - - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on). - - Per-transaction state resets with the transaction; a system call has its own entry point and reservoir split. -- **Spec:** §3, §4, §5, §9, §11, §14, §21. **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today). + - The forwards: regular gas `remaining − remaining × 2 / 100`, plus a value call's stipend after the cap; the reservoir by the same subtraction, the transaction's own frame and a system call's outermost frame taking the whole; each pool `remaining × 98 / 100`, rounded down. + - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on, the contract size limit at 512 KiB and the initcode size limit at 1 MiB, the fork's legacy journal semantics off). + - Per-transaction state resets with the transaction; a system call has its own entry point, and the handler splits its gas (`MegaHandler::tx_gas`). + - A fact about the transaction's start is read with what the journal records of the transaction (its original info, its entries, its transaction id), never off an account flag revm sets once per journal alone, so on a journal that runs several transactions unfinalized the engine's counts follow what revm charges there. +- **Spec:** §3, §4, §5, §9, §10, §11, §14, §21. +- **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today). -### Gas detention (changing in #407) +### Gas detention -- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, `hold_precompile` and `settle_answer` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. -- **Read first:** the module doc of `src/access/detention.rs`. +- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer` and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`. +- **Read first:** the module doc of `src/access/mod.rs`. - **Check:** - The split into spendable and withheld gas is applied when a read completes, when a frame starts or resumes, and after an `SSTORE`; only regular charges are held to the spendable part, every other reader sees both. - - The withheld part goes back to the sender unspent. - - A crossing leaves the frame's gas as it was before the charge and stops the frame with `MegaLimitExceeded(2, limit)`; the caller gets everything the frame had. - - A precompile is decided from its price before it runs; one outside the Satin set runs on the allowance. + - The withheld part goes back to the sender unspent, except from a failed deposit. + - A crossing is classified in the run-result hook (`frame_run_result`, `Detention::on_frame_end`), and only on an out-of-gas: the frame's gas is put back to what it was before the charge, the frame stops with `MegaLimitExceeded(2, limit)`, and its caller gets everything the frame had. + - Compute is every regular charge the frames make, the work run on a value call's stipend included, less the state and history gas that spilled onto regular gas, and less what halting frames burned, which is read off the fork's failed-charge record. + - A value call's own regular charges are decided first, and stop the calling frame if they cross; a precompile is then decided from its price before it runs, and one the engine cannot price runs on the allowance. + - What is volatile: the block environment (`SLOTNUM` and `BLOCKHASH` among it, `BLOBHASH` not), the block beneficiary's account, the Oracle's storage; a call to the EIP-2935 history contract reads the block number, and a `CREATE`'s loads of its creator and created address are no reads. - A system-originated transaction and a system call are never detained. - - Compute today excludes what a callee spends of a value call's 2,300 stipend and counts a halting frame's leftover through the halt-noting machinery; #407 changes both, so report a defect in the current rules only if that change would not remove it. -- **Spec:** §12, §13. **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention). +- **Spec:** §12, §13. +- **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention). -### Block executor and block rules (stable, except `limit.rs`, `eips.rs` and the inspector gate) +### Block executor and block rules - **Where:** `src/block/` (`executor.rs`, `limit.rs`, `result.rs`, `eips.rs`, `l1_block_info.rs`, `factory.rs`, `helpers.rs`). - **Read first:** the module doc of `src/block/executor.rs`. - **Check:** - The activation-block rule is caller-set (`no_user_tx_activation_block`, default `false`); `MegaHardforks::admits_only_deposits` is what a builder computes it from. - A transaction is an MST when it is a legacy transaction of the system shape from the live system address, decided before it runs; a failed read of the address is an internal error. - - A deposit and an MST are never refused by the packing budget or building policy and count towards them; the header gas limit (`BlockLimiter::pre_execution_check`) and the DA footprint (`check_da_footprint`) still apply. - - `commit_transaction_outcome` refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal). - - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info; a pre-block call that does not succeed makes the block invalid, and a fatal database error is an internal error. - - A rewriting inspector is refused at every block-execution entry, as an internal error (#407 deletes the gate). - - The block's ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited (#407 adds block limits on KV and state growth). + - The block's packing budgets are data size 13,107,200, KV updates 500,000 and state growth 1,000, checked in that order before a transaction runs (`BlockLimiter::pre_execution_check`): the transaction that reaches one is packed, and every later ordinary transaction is refused. + - A deposit and an MST are never refused by the packing budgets or building policy and count towards them; both are held to the header gas limit (`BlockLimiter::pre_execution_check`), and an MST, a legacy envelope, to the DA footprint (`check_da_footprint`), which a deposit is exempt from. + - `commit_transaction_outcome` checks the counters again and refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal). + - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info. + - Every pre-block call runs through one helper (`transact_pre_block_call` in `eips.rs`) on `PRE_BLOCK_CALL_GAS_LIMIT`, whatever the block's gas limit; one that does not succeed makes the block invalid, and a database error the database declares fatal is an internal error. + - The pre-block calls count towards no block budget. + - Block execution admits any inspector; the node decides which run on block production. + - The block's counters: regular gas as `max(regular, floor)`, state and history gas, history bytes, data size, write records and state growth; the three gas ledgers are reported, not limited. - When the OP base moves, diff the file against the new base's `OpBlockExecutor`. - **Spec:** §1, §18, §19, §20, §21. -### System contracts and the system address (stable, except keyless) +### System contracts and the system address - **Where:** `src/system/` (`intercept.rs`, `oracle.rs`, `control.rs`, `limit_control.rs`, `keyless/`, `tx.rs`, `predeploys.rs`, `sequencer_registry.rs`), `crates/system-contracts/`. - **Read first:** the module doc of `src/system/tx.rs`. @@ -181,64 +297,84 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - Every transaction reads the registry's account and its `_currentSystemAddress` slot, warm, by comparing the code hash, without running the registry's code. - A transaction from the live system address without the system shape is invalid; a deposit from it, which never has the shape, is a failed deposit, including one carrying the MST source hash. - A deposit carrying the MST source hash from any **other** sender is not refused: it is system-originated, so it is held to no limit, pays no history gas, is not detained and is priced at the minimum bucket. - The spec's basis is that no deposit derived from L1 carries the hash. This is the widest exemption in the engine, so check that claim. + The spec's basis is that no deposit derived from L1 carries the hash. + This is the widest exemption in the engine, so check that claim. - An MST is validated (chain id, nonce, EIP-3607) before it is promoted to a deposit. - - Satin deploys, upgrades and seeds no predeploy. The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage; anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`. No other block reads them. + - Satin deploys, upgrades and seeds no predeploy. + The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage. + Anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`. + No other block reads them. - An Oracle read in a system call reads chain storage, never the oracle service. - - Keyless (changing in #407): the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set. + - Keyless: the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set. + - The keyless creation forwards `min(gasLimitOverride, remaining)` of regular gas, the reservoir share of what the call has left and the child share of each of the call's pools; the signer's nonce record is counted on the call at its settlement, once the creation returned. - The interceptor dispatch order is scheme guard, address, selector, then value policy; an unknown selector is not intercepted. - Deployed bytecode and code hashes match the attested artifacts (`build.rs`). - **Spec:** §13, §15, §16, §17, §18, §19. -### Gas schedule and pricing (stable, except `schedule.rs`) +### Gas schedule and pricing - **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`. - **Check:** - Every regular entry is Amsterdam's; state creation is paid once, in state gas. + - The forwards are schedule entries: `call_stipend_reduction` = 50 (the regular-gas cap), `reservoir_kept_percent` = 2, and `pool_kept_percent` = 2 for each of the three pools; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir. - State gas = schedule entry × bucket multiplier `m`; regular gas never scales. A failed capacity lookup is a node fault: the transaction gets no outcome and is not settled, and the node reports an internal error with the cause. - History gas uses the limit layer's byte table, so a record's history bytes are its data size; the three sites where the totals part are in the `src/limit/mod.rs` module doc, "The byte table". - A deposit, a protocol-produced transaction and a system call pay no history gas. - - The history allowance (160 bytes, `storage_call_stipend()` in `src/evm/history.rs`) draws only on a log's charge. + - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, the schedule's `call_history_allowance`) draws only on a log's charge. - The EIP-7623 floor is still computed and validated. - The constants are provisional; a build with `satin-price-override` must never reach a node. - **Spec:** §2, §4, §5, §6, §7, §8, §9. -### Inspector contract (deleted in #407) +### Inspector contract -- **Where:** `src/evm/inspector.rs`, and the admission checks in `src/evm/mod.rs`, `src/block/factory.rs`, `src/block/executor.rs`. +- **Where:** the `evm` module documentation (`src/evm/mod.rs`, "Inspectors") and `src/evm/execution.rs` (`frame_init`, `frame_run_result`, `frame_return_result`; `frame_run` and `InspectorEvmTr` are revm's), `test_utils::ReadOnlyObserver`. - **Check:** - - The module documentation of `src/evm/inspector.rs` is the contract (the spec does not describe inspectors); check that each rewrite it permits is settled as it says. - - An answered frame and a revived call settle as a frame that kept nothing: state and history gas rolled back, refund dropped, lane discarded, the upfront charge given back at the price it was made at. - - A success rewritten into a failure has its journal taken back to the frame's checkpoint. + - The module documentation of `src/evm/mod.rs` is the contract (the spec does not describe inspectors): an inspector runs on revm's inspected lifecycle unchanged, and every per-frame mechanism sits in the frame start, run result or return both loops share. + - A rewritten result is taken as given: the caller settles it as revm does, with no correction of the engine's. + - An inspector's answer never reaches the engine's frame start, so the depth guard, the interceptors and gas detention see none of it, and it settles on the gas it is built on. + - A frame that crosses the compute limit is seen to end with the stop: the stop is made in the fork's run-result hook (`frame_run_result`), before the inspector's `call_end`, `create_end` and `frame_end`. + - A `keylessDeploy` call's frame is handed to no `initialize_interp` and gets no `step`: the inspector sees the call start, its creation, and the call end. + - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made. - A pre-block system call runs on the plain system-call path, with no callback. - - A declared observer must not answer a frame, edit inputs or rewrite a result (checked in debug builds). + - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof. +- **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors. -### Node surface, validation and the stateless witness (stable, except genesis and validation) +### Node surface, validation and the stateless witness - **Where:** `src/lib.rs` (explicit exports), `src/block/hardfork.rs`, `src/block/chain.rs`, `src/block/genesis.rs`, `src/evm/validation.rs`, `src/evm/state.rs`, `src/block/l1_block_info.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs`. - **Check:** - `validate_schedule` refuses a schedule in which a base fork Satin runs on is not active by `satinTime`. - The genesis format has exactly one key, `satinTime`; Satin carries no parameter, and every other `satin*` key (the old registry and limit keys included) is refused. + - A key given twice is read as its last copy by every reader, and `satinTime` is also read from the `arbitrary_precision` object form, decimal digits alone. - The pool and the engine refuse the same oversize body with the same error (`TX_BODY_OVER_DATA_SIZE_LIMIT`): body + 40 × authorizations over the transaction limit. - - The witness holds every read: block hashes, SALT bucket ids, the Oracle reads of the block's transactions (none for system calls), the L1 block info, the registry. + - The witness holds every read: block hashes, SALT bucket ids, the Oracle reads of the block's transactions (none for system calls), the L1 block info, the registry, and every authority the authorization-list simulation loaded. - The witness is the sequence of states the block commits: each pre-block step commits its state on its own, read-only entries included, where a commit hook on `State` receives it whole; nothing else hands the pre-block states out. + - A witness replay's exports are a subset of the building node's, and may be a proper one. + - A node's database answers an address it holds no account for as no account (`None`), never as an empty account: the destruction table gives a leaf back only when no account stood there. - **Spec:** §1, §21, §22, "Node integrators". -### Tools, tests, goldens, benches and CI (stable, except the outcome tooling) +### Tools, tests, goldens, benches and CI - **Where:** `bin/mega-evme/` (`bin/mega-evme/src/engine.rs` picks the engine from `--spec`: Satin in-tree, legacy specs on a released crate; `run` and `tx` default to the legacy `Rex6`), `crates/mega-state-test/`, `crates/state-test/`, `crates/mega-evm/tests/` (`satin/`, `block/`, `system/`, `fuzz/`, `tracers/`), `crates/mega-evm/benches/`, `.github/workflows/`, `scripts/`, `mutants/suppressions.toml`. - **Check:** - No consensus path changed for a tool's sake; tool overrides (`--override.limits`, `with_tx_runtime_limits`, `with_protocol_limits` under `test-utils`) are explicit and never default. + - A limits file of the first shape, without the KV-update and state-growth fields, reads with the default spec's values for them; every other field stays required, and an unknown one is refused. + - `state-test --json-digest` hashes each transaction's whole outcome, and the `--limit-*` options run Satin mode under tighter limits in each dimension. - A test pins a spec rule, not the implementation; a new or changed test says which rule it checks (some headers carry a `[S
.]` tag: the spec section and item). - A figure the schedule determines is asserted against its derivation, not pinned; snapshots and goldens own only outputs with no computable expectation. + - The limit matrix (`tests/satin/limit_matrix/`) runs every row, none of them ignored. + - `mega-evme`'s recorded mainnet blocks are one deterministic archive, `bin/mega-evme/tests/fixtures/blocks.tar.xz`, extracted once per test binary into cargo's target scratch directory, each file moved into place on its own so racing extractions all succeed; `bin/mega-evme/scripts/pack_blocks_fixture.py --check` holds a repack of it byte-identical. - The suite passes at the byte-price grid's points, not only at the spec's prices. - The mutation gate is fail-closed: a suppression without a locator may cover only one mutant. - A fuzz run that checks nothing fails (zero cases, zero comparisons). ## Judging a finding -1. **Reachability first.** Does the node's block execution or building path reach it? With the default configuration, or only with a non-default limit? Is it decided below, or does #407 change it ("What is still moving")? +1. **Reachability first.** + Does the node's block execution or building path reach it? + With the default configuration, or only with a non-default limit? + Is it decided below? 2. **Severity**, in this order: 1. not reachable from block execution or building: at most low (tools, test APIs); 2. reachable only with a non-default configuration: one level lower; @@ -254,51 +390,61 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. Read this before rating a finding that says a failure reverts where it should halt, or halts where it should revert. A refusal the protocol imposes reverts; an execution fault halts. -Every limit stop — the transaction's data-size limit, a frame's data-size budget, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, which resumes and may catch the stop. +Every limit stop — the transaction's data-size, KV-update and state-growth limits, a frame's budget in those three, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, its reservoir and pools included, and the caller resumes and may catch the stop. An execution fault — a real out-of-gas, a precompile given less than its price, an invalid opcode, a charge the frame cannot pay — halts and consumes the frame's gas, as in revm. One ABI serves every kind of stop, and there is no third ending: the halt reasons are op-revm's (`MegaHaltReason`), and the engine makes no halt of its own. - -The KV and state-growth stops, and naming the frame budget rather than the transaction limit when a write crosses both, are still to land in #407; on this branch such a write names the transaction limit (`AdditionalLimit::check`). +An operation that crosses several counted dimensions at one site stops on the first of data size (kind 0), KV updates (kind 1) and state growth (kind 3); compute (kind 2) is decided at the regular charge, before the write is counted. +Inside a dimension the frame budget is tested before the transaction limit, and the stop names the budget whenever the budget is crossed. The deliberate exceptions: -| What happens | Why | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose execution halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | -| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set: the size check is the precompile's own input check, which fails the call like any bad input. Gas detention prices such an input at zero, so it is never a crossing. | -| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs, and it decides from the price; a check made after the gas check is not visible to it. A precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | -| A call whose start (its value transfer's records and transfer log) crosses the data-size limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward. | A limit is enforced at the writes it guards, and a start writes before its callee runs. Here the start is counted before revm runs the callee, which then never runs; #407 counts it after revm answered and replaces a failed answer with the stop, to the same end. | -| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made. Of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | -| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data. All are catchable, and the outcome's `limit_exceeded` stays empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | -| One size rule has three endings: initcode over the size limit is rejected at validation in a creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`. Deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes: rules of the EVM, not MegaETH's resource limits, so they stay halts. A keyless call checks the init code among its rules before any creation starts, and every rule refuses with a revert and its own error. | +| What happens | Why | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | +| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. | +| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | +| A call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward; a precompile priced past detention's allowance whose start's records also cross is that records' stop, not the compute stop. | A limit is enforced at the writes it guards, and a start writes before its callee runs, so revm's answer, whatever it was, gives way to the stop, and the value has moved before the price is consulted, so the records are decided first. | +| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | +| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | +| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. | Not exceptions, but easy to mistake for one: - A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an EIP-7702 authorization's charges, the history of the records made before the first frame — ends out of gas with no frame: its whole regular budget is consumed and its reservoir returned. That is EIP-2780's runtime out-of-gas path, a gas fault (`pre_execution` in `src/evm/execution.rs`). +- An EIP-7702 list that would take the transaction over its KV-update or state-growth limit is skipped whole, and the transaction's own frame is stopped before it runs, naming the transaction limit (kind 1 when both would cross). + The crossing happens before any frame, yet it is a limit stop, where Rex6 halted; the intrinsic gas, the body's history and its data size stay, and nothing of the list is kept. +- A deposit whose own frame is stopped settles as a revert, like any transaction's, and is not a failed deposit. +- A failed deposit that creates its caller counts that account as one unit of state growth, for the transaction and the block, and no limit stops it: it has already failed. - A keyless creation that reverts, halts or is stopped makes the `keylessDeploy` call succeed, with `ExecutionReverted`, `ExecutionHalted` or `EmptyCodeDeployed` in its ABI return, a stop's revert data carried inside `ExecutionReverted`. - The call itself reverts with the stop only when its own charges or the signer's nonce record cross a limit (`answer` in `src/system/keyless/settle.rs`). + The call itself reverts with the stop only when its own charges or the signer's nonce record cross a limit; otherwise `answer` in `src/system/keyless/settle.rs` builds its ABI return when the creation returned (`frame_return_result` in `src/evm/execution.rs`). - Under gas detention, only a regular charge the withheld part would have paid is a crossing; a charge beyond the frame's whole regular gas, and a failed state or history charge, halt as they would without the read. +- Under gas detention, a value call whose own charges cross stops the calling frame before anything moves, whatever its target and whether or not the caller can fund the value. +- A creator that its creation's nonce record takes over a limit is stopped when the creation returns, before it runs another instruction, whatever the creation's own result. +- A frame a failure below it left over the transaction's data-size limit — the failure put back a record of a frame above, and a hint the failed frame sent stays — is stopped as it resumes, before it runs another instruction, whether the frame below reverted, halted or was itself stopped. +- The destruction table's give-back crosses nothing; the operation's positive effects are held after it, in the order data size, KV updates, state growth, and one that crosses stops the destroying frame, which then keeps nothing of the operation; a regular charge of the `SELFDESTRUCT` that crosses gas detention stops the frame before the opcode completes, and none of the table applies. ## Already decided — do not re-report Each is a decision with its reason; "in this pull request" means review the code, not the decision. -An item marked (#407) is one #407 revisits; until it merges, the item describes this branch. -- (#407) **KV, state-gas and block execution-gas limits are removed**: data size bounds the records and history gas prices them, state gas prices state, so removal changes no result. +- **KV updates and state growth are limited, per transaction, frame and block; state gas and the block's execution gas are not**: the count, not the gas, stops the 1,001st slot, and the KV check is made though at Satin's constants data size binds first. - **Consensus limits are one per-spec table** (`ProtocolLimits::for_spec`), not chain configuration: configured values could stop the L1-attributes deposit and cost a silent factory fallback. -- **No latch**: a crossing is a native revert of the crossing frame, which callers may catch; with data size and detention as the only limits no transaction ends over a limit. +- **No latch**: a crossing is a native revert of the crossing frame, which callers may catch, and a caller that runs on is held to what the transaction has left, so no transaction keeps more than its limits. - **An oversize transaction body is refused at validation** (a deposit becomes a failed deposit): the body is known before execution, and at Satin's constants the bound is unreachable (6,732,889 < 13,107,200). +- **An EIP-7702 list over the KV-update or state-growth limit is skipped whole** and stops the first frame before it runs: Rex6's all-or-nothing rule, as a revert-class stop, because a stop of the first frame does not revert what was applied before it. +- **The stop names the frame budget when both the budget and the transaction limit are crossed**; when a block is full on several budgets, a node may name them in the order data size, KV updates, state growth, and two nodes need not name the same one. - **`tx_chain_id_check` is pinned on**: it is revm 40's default, and it makes the system-transaction chain-id guard effective. - **Every transaction pre-warms the registry read**, so gas does not depend on the envelope type; the non-warming journal read is not a generic upstream candidate. - **A delayed commit re-checks only the sender's nonce and balance**: other staleness is the builder's documented responsibility, as the system-transaction-first flow requires. - **An MST is never refused by a packing budget or builder policy**: it serves a user transaction already admitted. - **Satin has no deploy or upgrade path**: it runs on a chain that ran the legacy forks, and its activation block refuses any predeploy without Satin's code; no contract changes. - **Keyless refuses only an empty code deposit** at the deploy address; the four producer-less errors are deleted, which changes no deployed byte. -- (#407) **Creation revival by an inspector is allowed** (Foundry parity), settled as a frame that kept nothing; the upfront refund is given back at the price it was charged at. +- **A rewritten result is taken as given, as revm takes it**: a revived creation settles as the success the inspector made of it (Foundry parity), and an inspector's answer settles on the gas it is built on. - **The Amsterdam regular gas table is taken wholesale**: the earlier press-back to Osaka priced creation twice. -- **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart. An unknown chain has no schedule (`hardfork_schedule` answers `None`). -- (#407) **A rewriting inspector in block execution is an internal error**, not a block verdict: the inspector is the node's own choice. +- **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart. + An unknown chain has no schedule (`hardfork_schedule` answers `None`). +- **Block execution admits any inspector**: which inspectors run on block production is the node's decision. - **Explicit crate-root exports; dead helpers and legacy-era remnants are deleted.** - **Satin carries no fork parameter**, and the fork-parameter mechanism was removed with nothing using it. - **An absurd state-gas price makes the operation run out of gas**; no reachable divergence. @@ -306,12 +452,19 @@ An item marked (#407) is one #407 revisits; until it merges, the item describes - **Precompile prices are looked up by id**: a precompile set replaced around the engine, through the mutable accessors, keeps the built-in prices; the spec states the boundary, and nodes change the set through `with_dyn_precompiles` or the factory builder. - **A keyless signer that is the block beneficiary is detained**, as in the legacy engine. - **No MST in the activation block**: it admits only deposits and every MST consumer is a non-deposit; documented in the spec. -- (#407) **Write records are deduplicated per frame**, not per transaction: documented as an upper bound. +- **Write records follow the transaction-wide net change**, not Rex6's per-operation count: the record measures the state the transaction keeps, which is what history gas prices. - **The limit override is an explicit tool opt-out** (`with_tx_runtime_limits`); block execution and validation use the chain's limits. - **No spec ladder in Satin yet**: it comes with the next spec, with the extension points kept; `AGENTS.md` says how to add it. - **The fork finalizes the journal on an error** (`bluealloy/revm#3780`, carried early): kept; the fork documents it in megaeth-labs/revm#75. -- (#407) **Answered-frame settlement stays in mega-evm**, and `OpBlockExecutor` is not composed (it requires `PostExecEvm` and returns `OpTxResult`). -- **The 98/100 frame budget and dropping a hint from a frame whose volatile access is off are kept**: without a latch the budget protects the caller's own work. -- (#407) **An inspector answer with effects is mis-accounted** (a mock that transfers value, an isolated run): the settlement assumes none; tools only, kept. -- **Mechanisms kept as in the legacy engine** (not under review): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the data-size limit's 98/100 share, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint, and the inspector admission gate (#407 deletes the gate). +- **`OpBlockExecutor` is not composed**: it requires `PostExecEvm` and returns `OpTxResult`. +- **The 98/100 shares and dropping a hint from a frame whose volatile access is off are kept**: without a latch the frame budgets and the reservoir share protect the caller's own work. +- **The neutral configuration forwards as Ethereum does** (EIP-150's 63/64, the whole reservoir): equivalence mode is Ethereum's forward, not Satin's. +- **An inspector's answer built on `Gas::new(limit)` carries no reservoir and unlimited pools**, so above the execution cap its caller keeps only the 2 per cent of its reservoir it kept, and the caller's budgets are lifted for the rest of its frame: tools only, kept. +- **Satin does not apply EIP-7610's storage collision**: the engine reads storage slot by slot and cannot see storage it has not loaded; the execution-spec gate skips those fixtures. +- **The destruction table refills state gas, which EIP-8037 does not**: a part the transaction made does not remain for a node to store. +- **The table's slot column follows the transaction's original**: a slot of a created account first accessed after the creation is zero at the start whatever the state held, as revm loads it; only a slot accessed before the creation keeps its value, and the specification says so. +- **The neutral configuration counts the destruction table**, and prices it as the fixture's fork does: equivalence mode's usage of a transaction that creates and destroys an account differs from a count without the table, no fixture checks usage, and no second counting rule is kept for the neutral configuration. +- **`BLOBHASH` is not volatile**, unlike in Rex6: it reads the transaction's own blob hashes. +- **The pre-block calls run on one constant budget** (`PRE_BLOCK_CALL_GAS_LIMIT`), not on the block's gas limit. +- **Mechanisms whose existence is kept from the legacy engine** (whether to have them is not under review; their Satin rules, which the specification states against Rex6, are): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the 98/100 frame share and Rex6's numbers for the data-size, KV-update and state-growth limits, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint. - **The upstream revm change `new_answer`** for answers to frames that did not run (`bluealloy/revm#3979`) is opt-in: the handler does not normalise answers, because real inspectors' answers can have effects. From be2a56f740c085782100824c0b4e4933c7118d83 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:25:17 +0800 Subject: [PATCH 188/201] feat!: meter Satin's writes and frame starts in the revm fork's hooks, on a per-frame byte pool (#407) Co-authored-by: mega-putin Co-authored-by: William Cheung --- .github/workflows/exec-spec-satin.yml | 15 +- .github/workflows/exec-spec.yml | 15 +- AGENTS.md | 300 ++- Cargo.lock | 44 +- Cargo.toml | 28 +- REVIEW.md | 21 +- bin/mega-evme/AGENTS.md | 1 + bin/mega-evme/Cargo.toml | 2 + bin/mega-evme/scripts/pack_blocks_fixture.py | 55 + bin/mega-evme/src/block/record.rs | 1 + bin/mega-evme/src/block/satin.rs | 22 +- bin/mega-evme/src/common/outcome.rs | 11 +- bin/mega-evme/src/replay/cmd.rs | 31 +- bin/mega-evme/tests/block_replay.rs | 41 +- bin/mega-evme/tests/common/blocks.rs | 9 +- bin/mega-evme/tests/common/mod.rs | 121 + bin/mega-evme/tests/differences.rs | 4 +- bin/mega-evme/tests/fixtures/blocks.tar.xz | Bin 0 -> 133744 bytes .../blocks/blocks/2640/26400001.json.zst | Bin 21070 -> 0 bytes .../blocks/blocks/2640/26400007.json.zst | Bin 15182 -> 0 bytes .../blocks/blocks/2640/26400110.json.zst | Bin 14860 -> 0 bytes ...29f62d443a99baaa366699ef84f802ae5801b4.bin | Bin 17424 -> 0 bytes ...32584526f97a5ca267c8eef73a1831f53720f2.bin | Bin 1106 -> 0 bytes ...c621c8d9b020d9aa6e83879561426943aee0b0.bin | Bin 1480 -> 0 bytes ...0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin | Bin 362 -> 0 bytes ...31a5d59bde918169800b8d219754360a1f58b2.bin | Bin 2670 -> 0 bytes ...92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin | Bin 8592 -> 0 bytes ...65c80e43b953eaa41c27d9a03515fb9cad660f.bin | Bin 5148 -> 0 bytes ...81d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin | Bin 2227 -> 0 bytes ...b887f802218d9ac86f142ef0994da43ea5eeb6.bin | Bin 515 -> 0 bytes ...9fa5e552daf4719552131a0abce779daec0a5d.bin | Bin 83 -> 0 bytes ...17cb2a2327d87970645a2c1012e61f617551ee.bin | Bin 24357 -> 0 bytes ...d08af36ea1ead283270da9bf554c306a6c87b9.bin | Bin 15686 -> 0 bytes ...34f57600420d103a4401ef7555bd50b229dc55.bin | Bin 2664 -> 0 bytes ...a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin | Bin 24314 -> 0 bytes ...3516ec43590177c4009049afc16fa1bc9f8dc4.bin | Bin 19034 -> 0 bytes ...3a32662470f639863b356e5cd453b03bb0ce42.bin | Bin 348 -> 0 bytes ...5ab0b3d5c8861acb422b6fec63cf36234f36a6.bin | Bin 170 -> 0 bytes ...e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin | Bin 1710 -> 0 bytes ...ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin | Bin 397 -> 0 bytes ...2b7d433b94a4aa840e943aa9b6ada3f7847cad.bin | Bin 1969 -> 0 bytes ...61c8cca605219541f7e9bb9aadc66ee9e277fe.bin | Bin 1969 -> 0 bytes ...0c2fc6640176b13d2c10b5df218f920f3a1dc5.bin | Bin 9995 -> 0 bytes ...3c5edc085ef7ece05077c3382b8d3b367863b0.bin | Bin 23791 -> 0 bytes ...65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin | Bin 5365 -> 0 bytes ...184f4e6642e083d8031f89854e6de590c5b999.bin | Bin 1969 -> 0 bytes ...17fb06613189b4e0459b3a2263fc0ed240cf5c.bin | Bin 5009 -> 0 bytes ...23477c857b80d45c69929c1f38b031ff5d2919.bin | Bin 5223 -> 0 bytes ...a2b574f528d515f6f765506edc1205705b4139.bin | Bin 20724 -> 0 bytes ...52f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin | Bin 97 -> 0 bytes ...a262aeb634b015222134d5abfd8f7b7828276a.bin | Bin 5692 -> 0 bytes ...d09d575674eb0852c0fa3187e59e98ef977998.bin | Bin 2059 -> 0 bytes ...b722b2b22633e13900c4b13767742b9f5f5a90.bin | Bin 141 -> 0 bytes .../fixtures/test_satin_run_basic_return.json | 1 + .../fixtures/test_satin_run_codefile.json | 1 + .../tests/fixtures/test_satin_run_create.json | 1 + .../fixtures/test_satin_run_dump_inline.json | 1 + .../tests/fixtures/test_satin_run_input.json | 1 + .../fixtures/test_satin_run_prestate.json | 1 + .../tests/fixtures/test_satin_run_revert.json | 1 + .../test_satin_run_rpc_args_parse.json | 1 + .../test_satin_run_storage_override.json | 1 + .../fixtures/test_satin_run_trace_inline.json | 1 + .../tests/fixtures/test_satin_tx_create.json | 1 + .../fixtures/test_satin_tx_halt_oog.json | 1 + .../tests/fixtures/test_satin_tx_revert.json | 1 + .../test_satin_tx_value_transfer.json | 1 + bin/mega-evme/tests/limits.rs | 20 +- bin/mega-evme/tests/rex6_forward.rs | 266 ++ bin/mega-evme/tests/satin-differences.md | 2 +- crates/mega-evm/README.md | 66 +- crates/mega-evm/benches/transact.rs | 25 +- crates/mega-evm/src/access/detention.rs | 682 +++-- crates/mega-evm/src/access/mod.rs | 29 +- crates/mega-evm/src/block/eips.rs | 48 +- crates/mega-evm/src/block/executor.rs | 97 +- crates/mega-evm/src/block/factory.rs | 40 +- crates/mega-evm/src/block/genesis.rs | 105 +- crates/mega-evm/src/block/limit.rs | 279 ++- crates/mega-evm/src/block/result.rs | 26 + crates/mega-evm/src/constants.rs | 45 +- crates/mega-evm/src/evm/context.rs | 266 +- crates/mega-evm/src/evm/execution.rs | 1818 ++++++++------ crates/mega-evm/src/evm/factory.rs | 8 +- crates/mega-evm/src/evm/frame.rs | 171 +- crates/mega-evm/src/evm/history.rs | 16 +- crates/mega-evm/src/evm/host.rs | 417 +++- crates/mega-evm/src/evm/inspector.rs | 670 ----- crates/mega-evm/src/evm/instructions.rs | 412 +--- crates/mega-evm/src/evm/mod.rs | 174 +- crates/mega-evm/src/evm/precompiles.rs | 32 +- crates/mega-evm/src/evm/result.rs | 27 +- crates/mega-evm/src/evm/schedule.rs | 159 +- crates/mega-evm/src/evm/validation.rs | 5 +- crates/mega-evm/src/lib.rs | 37 +- crates/mega-evm/src/limit/frame_limit.rs | 706 ------ crates/mega-evm/src/limit/limit.rs | 2196 ++++++----------- crates/mega-evm/src/limit/mod.rs | 327 ++- crates/mega-evm/src/limit/record.rs | 1072 ++++++-- crates/mega-evm/src/system/AGENTS.md | 8 +- .../mega-evm/src/system/keyless/dispatch.rs | 128 +- crates/mega-evm/src/system/keyless/mod.rs | 28 +- crates/mega-evm/src/system/keyless/settle.rs | 101 +- crates/mega-evm/src/system/limit_control.rs | 8 +- crates/mega-evm/src/system/oracle.rs | 13 +- .../mega-evm/src/system/sequencer_registry.rs | 44 +- crates/mega-evm/src/test_utils/mod.rs | 2 + crates/mega-evm/src/test_utils/neutral.rs | 23 +- .../src/test_utils/read_only_observer.rs | 264 ++ crates/mega-evm/tests/block/counters.rs | 53 +- crates/mega-evm/tests/block/eips.rs | 149 +- crates/mega-evm/tests/block/factory.rs | 28 +- crates/mega-evm/tests/block/inspector.rs | 242 +- crates/mega-evm/tests/block/limits.rs | 274 +- crates/mega-evm/tests/block/main.rs | 5 + crates/mega-evm/tests/block/predeploys.rs | 8 +- .../mega-evm/tests/block/receipt_goldens.rs | 15 +- .../mega-evm/tests/block/system_tx_budgets.rs | 61 +- crates/mega-evm/tests/block/transfer_logs.rs | 24 +- crates/mega-evm/tests/block/witness/state.rs | 8 +- crates/mega-evm/tests/block/witness/stops.rs | 46 +- crates/mega-evm/tests/fuzz/blocks.rs | 43 +- crates/mega-evm/tests/fuzz/gen/case.rs | 23 +- crates/mega-evm/tests/fuzz/gen/program.rs | 76 +- crates/mega-evm/tests/fuzz/gen/world.rs | 98 +- crates/mega-evm/tests/fuzz/harness.rs | 16 + crates/mega-evm/tests/fuzz/properties.rs | 189 +- crates/mega-evm/tests/fuzz/regressions.rs | 144 +- crates/mega-evm/tests/satin/common.rs | 62 +- crates/mega-evm/tests/satin/compute_gas.rs | 8 +- crates/mega-evm/tests/satin/count_order.rs | 21 +- crates/mega-evm/tests/satin/data_size.rs | 729 +++++- .../mega-evm/tests/satin/data_size_counts.rs | 41 +- crates/mega-evm/tests/satin/deposit_charge.rs | 57 +- .../tests/satin/detained_transfers.rs | 326 ++- crates/mega-evm/tests/satin/detention.rs | 421 +++- crates/mega-evm/tests/satin/equivalence.rs | 164 +- crates/mega-evm/tests/satin/failed_deposit.rs | 63 +- crates/mega-evm/tests/satin/gas_forward.rs | 276 +++ ...e_call_stipend.rs => history_allowance.rs} | 119 +- crates/mega-evm/tests/satin/history_bytes.rs | 66 +- .../mega-evm/tests/satin/history_exemption.rs | 10 +- crates/mega-evm/tests/satin/history_gas.rs | 218 +- .../mega-evm/tests/satin/history_reservoir.rs | 58 +- .../mega-evm/tests/satin/inherited_costs.rs | 113 +- crates/mega-evm/tests/satin/inspector.rs | 184 +- .../tests/satin/inspector_cheatcodes.rs | 63 +- .../mega-evm/tests/satin/inspector_limits.rs | 186 +- .../tests/satin/inspector_settlement.rs | 912 ++++--- crates/mega-evm/tests/satin/kv_updates.rs | 285 +++ .../mega-evm/tests/satin/limit_exemption.rs | 94 +- .../tests/satin/limit_matrix/block.rs | 334 +++ .../tests/satin/limit_matrix/deposits.rs | 130 + .../tests/satin/limit_matrix/destruction.rs | 1365 ++++++++++ .../tests/satin/limit_matrix/forwarding.rs | 438 ++++ .../tests/satin/limit_matrix/keyless.rs | 682 +++++ .../tests/satin/limit_matrix/limits.rs | 418 ++++ .../mega-evm/tests/satin/limit_matrix/mod.rs | 587 +++++ .../tests/satin/limit_matrix/records.rs | 266 ++ .../mega-evm/tests/satin/limit_matrix/stop.rs | 306 +++ crates/mega-evm/tests/satin/main.rs | 10 +- crates/mega-evm/tests/satin/neutral.rs | 89 +- crates/mega-evm/tests/satin/outcome.rs | 18 +- crates/mega-evm/tests/satin/pricing-table.md | 9 +- crates/mega-evm/tests/satin/pricing_table.rs | 24 +- .../mega-evm/tests/satin/reservoir_drain.rs | 1751 +++++++++++++ .../mega-evm/tests/satin/reservoir_share.rs | 200 ++ crates/mega-evm/tests/satin/salt.rs | 5 +- crates/mega-evm/tests/satin/salt_refund.rs | 128 +- crates/mega-evm/tests/satin/schedule.rs | 8 +- ...atin__corpus__corpus_outcomes_and_gas.snap | 2 +- crates/mega-evm/tests/satin/spec_numbers.rs | 94 +- crates/mega-evm/tests/satin/state_growth.rs | 826 ++++++- crates/mega-evm/tests/satin/stops.rs | 535 +++- crates/mega-evm/tests/satin/strategic_stop.rs | 82 +- .../tests/satin/synthetic_frame_gas.rs | 123 +- crates/mega-evm/tests/satin/system_call.rs | 274 +- crates/mega-evm/tests/satin/tool_writes.rs | 154 ++ crates/mega-evm/tests/satin/transfer_logs.rs | 652 +++-- crates/mega-evm/tests/satin/withheld_gas.rs | 322 ++- crates/mega-evm/tests/satin/write_records.rs | 1080 ++++++-- crates/mega-evm/tests/shared/op_reference.rs | 221 ++ .../mega-evm/tests/system/access_control.rs | 131 +- .../mega-evm/tests/system/keyless/charges.rs | 50 + .../mega-evm/tests/system/keyless/deploy.rs | 90 +- .../tests/system/keyless/detention.rs | 10 +- .../tests/system/keyless/differential.rs | 20 +- crates/mega-evm/tests/system/keyless/frame.rs | 18 +- .../tests/system/keyless/inspector.rs | 99 +- .../mega-evm/tests/system/keyless/limits.rs | 161 +- crates/mega-evm/tests/system/keyless/rules.rs | 2 +- ...erential__keyless_differential_record.snap | 278 +-- crates/mega-evm/tests/system/oracle.rs | 6 +- .../tests/system/remaining_compute_gas.rs | 9 +- crates/mega-evm/tests/system/system_tx.rs | 12 +- crates/mega-evm/tests/tracers/harness.rs | 8 +- crates/mega-evm/tests/tracers/scenarios.rs | 45 +- ...first_frame_start_stop__call_with_log.snap | 2 +- ...p_caught_by_the_parent__call_with_log.snap | 2 +- crates/mega-state-test/AGENTS.md | 2 + crates/mega-state-test/README.md | 25 + crates/mega-state-test/src/digest.rs | 358 +++ crates/mega-state-test/src/lib.rs | 3 + crates/mega-state-test/src/runner.rs | 132 +- crates/mega-state-test/tests/runner.rs | 115 +- crates/state-test/README.md | 5 + crates/state-test/src/main.rs | 82 +- crates/state-test/tests/cli.rs | 51 + .../mega-evme/configuration/chain-and-spec.md | 14 +- docs/spec/glossary.md | 40 +- docs/spec/hardfork-spec.md | 6 +- docs/spec/overview.md | 4 +- docs/spec/upgrades/overview.md | 2 +- docs/spec/upgrades/satin.md | 729 +++++- 214 files changed, 22440 insertions(+), 8779 deletions(-) create mode 100644 bin/mega-evme/scripts/pack_blocks_fixture.py create mode 100644 bin/mega-evme/tests/fixtures/blocks.tar.xz delete mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst delete mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst delete mode 100644 bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/39/3927f2a4803c5e18153ff5742d0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/3f/3f77685d5db0f99bf10bf1f0cd31a5d59bde918169800b8d219754360a1f58b2.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/45/459716bd908d0ccf47599b42af92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/4d/4d9be648c5bf39973670d9f8b481d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6f/6f5dd02efc31c07c6d99d8d36417cb2a2327d87970645a2c1012e61f617551ee.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/6f/6f77a5c9db7cfef9a4d05faff0d08af36ea1ead283270da9bf554c306a6c87b9.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/78/78dd15e7753d3e60a8003bda403516ec43590177c4009049afc16fa1bc9f8dc4.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/7e/7eff9da33cc2042d53428940c03a32662470f639863b356e5cd453b03bb0ce42.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/8e/8e3fe7a416d3e5f3b7be74ddd4e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/a2/a220f51e097a419ab9cc99098261c8cca605219541f7e9bb9aadc66ee9e277fe.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/ab/ab5d51e60951e30c2843d8fa783c5edc085ef7ece05077c3382b8d3b367863b0.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/cc/cc7e366c8e998368260791347f23477c857b80d45c69929c1f38b031ff5d2919.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f5/f57acd40259872606d76197ef052f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/f7/f7bdad905f90d6e7cb07182aeba262aeb634b015222134d5abfd8f7b7828276a.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/fa/fa8c9db6c6cab7108dea276f4cd09d575674eb0852c0fa3187e59e98ef977998.bin delete mode 100644 bin/mega-evme/tests/fixtures/blocks/codes/fd/fdf85d183a122fe611bc878683b722b2b22633e13900c4b13767742b9f5f5a90.bin create mode 100644 bin/mega-evme/tests/rex6_forward.rs delete mode 100644 crates/mega-evm/src/evm/inspector.rs delete mode 100644 crates/mega-evm/src/limit/frame_limit.rs create mode 100644 crates/mega-evm/src/test_utils/read_only_observer.rs create mode 100644 crates/mega-evm/tests/satin/gas_forward.rs rename crates/mega-evm/tests/satin/{storage_call_stipend.rs => history_allowance.rs} (87%) create mode 100644 crates/mega-evm/tests/satin/kv_updates.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/block.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/deposits.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/destruction.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/forwarding.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/keyless.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/limits.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/mod.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/records.rs create mode 100644 crates/mega-evm/tests/satin/limit_matrix/stop.rs create mode 100644 crates/mega-evm/tests/satin/reservoir_drain.rs create mode 100644 crates/mega-evm/tests/satin/reservoir_share.rs create mode 100644 crates/mega-evm/tests/satin/tool_writes.rs create mode 100644 crates/mega-evm/tests/shared/op_reference.rs create mode 100644 crates/mega-state-test/src/digest.rs diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml index 104068d6c..caa593fb0 100644 --- a/.github/workflows/exec-spec-satin.yml +++ b/.github/workflows/exec-spec-satin.yml @@ -144,27 +144,28 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) + # A release tag, or a release's commit until its tag is cut. + sources=$(grep -oE 'git\+https://github.com/megaeth-labs/revm\?(tag|rev)=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2 exit 1 fi - tag=${sources#*tag=} - tag=${tag%%#*} + ref=${sources#*=} + ref=${ref%%#*} commit=${sources##*#} - echo "fork tag $tag at $commit" - echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "fork ref $ref at $commit" + echo "ref=$ref" >> "$GITHUB_OUTPUT" echo "commit=$commit" >> "$GITHUB_OUTPUT" - uses: actions/checkout@v4 with: repository: megaeth-labs/revm - ref: ${{ steps.pin.outputs.tag }} + ref: ${{ steps.pin.outputs.ref }} path: revm-fork sparse-checkout: scripts persist-credentials: false - - name: Check the tag names the locked revision + - name: Check the ref names the locked revision working-directory: revm-fork env: COMMIT: ${{ steps.pin.outputs.commit }} diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml index 227f3c190..0f9c545b1 100644 --- a/.github/workflows/exec-spec.yml +++ b/.github/workflows/exec-spec.yml @@ -60,26 +60,27 @@ jobs: - name: Read the fork pin from Cargo.lock id: pin run: | - sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) + # A release tag, or a release's commit until its tag is cut. + sources=$(grep -oE 'git\+https://github.com/megaeth-labs/revm\?(tag|rev)=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u) if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2 exit 1 fi - tag=${sources#*tag=} - tag=${tag%%#*} + ref=${sources#*=} + ref=${ref%%#*} commit=${sources##*#} - echo "fork tag $tag at $commit" - echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "fork ref $ref at $commit" + echo "ref=$ref" >> "$GITHUB_OUTPUT" echo "commit=$commit" >> "$GITHUB_OUTPUT" - uses: actions/checkout@v4 with: repository: megaeth-labs/revm - ref: ${{ steps.pin.outputs.tag }} + ref: ${{ steps.pin.outputs.ref }} path: revm-fork persist-credentials: false - - name: Check the tag names the locked revision + - name: Check the ref names the locked revision working-directory: revm-fork env: COMMIT: ${{ steps.pin.outputs.commit }} diff --git a/AGENTS.md b/AGENTS.md index eb470a8c2..6f106e02d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,8 @@ cargo run --release -p state-test -- btest /blockchain_tests --ex # the fixtures named by an absolute path (the test runs in the package's directory) MEGA_STATE_TEST_FIXTURES=$PWD//state_tests MEGA_STATE_TEST_SAMPLE=0 MEGA_STATE_TEST_FORK=Osaka \ MEGA_STATE_TEST_MODE=satin cargo test --release -p mega-state-test --test witness -- --ignored --nocapture +# The whole-outcome digest: one line per executed transaction (the canonical record of its MegaTransactionOutcome, hashed; `-full` adds the record), for a base-against-head `sort | cmp` +cargo run --release -p state-test -- --mode satin --fork Osaka /state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest # Regenerate the rendered deviation registry after changing crates/mega-state-test/src/deviations.rs UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations @@ -102,9 +104,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - `cargo tree -i revm` must show exactly one revm, from the fork: the engine's graph (the default member) never reaches another. The workspace also locks revm 27.1.0, linked only by `mega-evme`: its `legacy` feature, and its `mega-state-test` 1.7.1 dev-dependency, which is unconditional, so a test build without `legacy` links it too (`cargo tree --workspace -i revm@27.1.0`). - The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them. -- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), and on the fork's precompile price (`Precompile::required_gas`), neither of which upstream revm has. +- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), on the fork's failed-charge record, the regular gas a frame had before every deduction that failed and before a halt on a cold access it could not pay (`failed_charge_remaining`, `set_failed_charge_remaining`), which tells what a halting frame burned, and on the fork's precompile price (`Precompile::required_gas`), none of which upstream revm has. +- Writes and frame starts are metered inside revm's instructions, through the fork's two instruction hooks on `Host`, which upstream revm does not have: `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge they make has been made, and the four calls and two creations call `frame_starting` once the forward is taken and before the frame's input is built. + `CompletedWrite` and `FrameStartKind` are exhaustive on purpose, so the engine's matches over them carry no wildcard arm and a new kind is a compile error here. +- The actions the engine makes for a frame outside an instruction — a `keylessDeploy` call's creation and its answer, and the stop of a frame a child returned into over a limit — come back through revm's own frame run, plain or inspected: the fork's run returns an action set on a frame's interpreter before it runs without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`, so the engine's `frame_run` only forwards to revm's. + A frame's own end is decided in the fork's run-result hook (`EvmTr::frame_run_result`), which revm's plain and inspected loops call once a frame's run returns and before the inspector's `call_end`, `create_end` and `frame_end` and `frame_return_result`: gas detention's classification is made there, so an inspector sees the stop the caller gets. +- The fork pins at a published commit of its byte-pool branch, and op-revm at a published commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done. + The byte-pool branch carries three resource pools on every frame's gas tracker, which the engine gives their meaning (`PoolId`, `GasTracker::record_pool`, `refill_pool`, `pool_remaining`, `pool_spent`), each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`, the part the caller keeps) and settled as the reservoir is, and the reservoir itself forwarded by its own share (`GasId::reservoir_kept_percent`, `GasTracker::forward_to_child`), the child's return adding what it left to what the caller kept; a start charge the frame-start hook declares on the start (`FrameStart::charge`, `StartCharge`) and the fork refunds when the frame fails; the history allowance a value call gives its child (`GasId::call_history_allowance`, `GasTracker::draw_history_allowance`); a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`). + The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`). + Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off. - The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance. -- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation. +- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation, lending it the creating frame's tracker, whose pool the code's bytes are drawn from. ## Architecture @@ -123,39 +133,41 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat ### Core Source Layout (`crates/mega-evm/src/`) -| Module | Holds | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, and the system-transaction promotion in `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, the volatile-read wrappers, the out-of-gas notes and the `KECCAK256` and copy wrappers that exist for them, and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, and which calls gas detention may price from it (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver`, the settlement of a frame that kept nothing, the journal's revert of a success an inspector rewrites into a failure and the guard that keeps an inspector's refused charge from classifying a frame (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch and the system-call reservoir split the spec fixes on, whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`); the system-call entry points, `transact_system_call_with_gas_limit` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | -| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size budget), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its data-size limit (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | -| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes, write records, history allowances and the log and code bytes of the history byte count (`frame_limit.rs`), staging, the stops its frames return and the one the transaction reports, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; `EvmTxRuntimeLimits` (the data-size limit: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | -| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | -| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | -| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | -| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | -| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | +| Module | Holds | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | +| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | +| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the exemption, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | +| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | +| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | +| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) | +| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) | ### How Satin executes today - `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments. + Its journal is revm's own (`Journal`): what the transaction keeps of the data-size limit is drawn from the byte pool on each frame's gas tracker and counted on the common execution layer (see the contracts below), not beside the journal. It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together. -- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, a system call's gas above 30M in its reservoir (the fork's `system_call_state_gas_margin_in_reservoir` on), the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB and the initcode size limit at 1 MiB. +- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB, the initcode size limit at 1 MiB, and the fork's journal semantics (`legacy_journal_semantics` off). That function is exported as `spec_cfg`: a node builds its `EvmEnv` through it, so what reads the env before an EVM exists (reth's gas estimation reads the execution cap) reads the configuration the EVM runs with. - What a transaction pool can decide without state is the handler's own `validate_env` and `validate_initial_tx_gas`, run on an EVM over an empty database (`validate_transaction_stateless`, `evm/validation.rs`). `validate_env` is split at the state read of the live system address (`MegaHandler::validate_env_as`): the pool passes the address in, read with `system::live_system_address`, and the system address's nonce and code are left to the state, as every sender's are. It reports the intrinsic gas by ledger (`IntrinsicGas`): regular, state (zero under EIP-2780, which charges the state a transaction adds when it runs), the body's history, and the floor. op-revm includes a deposit that fails validation as a failed deposit rather than refusing it, so for a deposit or a promoted system-address transaction the error says it would fail. Gas above the 200M execution cap goes to the EIP-8037 reservoir. -- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte, and the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`). +- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with four changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte; the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`), and a value call's history allowance at `HISTORY_ALLOWANCE_BYTES` of it; a child starts with 98/100 of its caller's reservoir and of each of its three pools (`GasId::reservoir_kept_percent`, `GasId::pool_kept_percent`); and a call or creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, Rex6's rule in place of EIP-150's 63/64 (`GasId::call_stipend_reduction`). Every regular-gas entry is Amsterdam's, EIP-8038's state-access prices included, so creating state costs the access and the write in regular gas and the new state itself in state gas alone, as upstream. The static opcode prices, which revm keeps in the instruction table, are Amsterdam's too (`satin_gas_table`): they part from the Osaka base's only in EIP-8038's 200-gas base of `EXTCODESIZE` and `EXTCODECOPY`. It is built once per process, with a second copy that prices that entry at zero for a transaction exempt from history gas (`satin_gas_params_history_exempt`); the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables. `crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, what nine probe transactions spent, and what two of those probes spend with the bucket they write into crowded; a test renders it and compares it to the file. -- The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the metering wrappers go in; `CLZ` is gated on Osaka and needs no activation. +- The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the volatile-read wrappers go in; `CLZ` is gated on Osaka and needs no activation. `SLOTNUM` pushes `BlockEnv::slot_num`, which the node supplies, and zero for a block that leaves it unset. - The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000, carried as an alloy-evm `PrecompilesMap` so a node can add or replace an address (`MegaEvmFactory::with_dyn_precompiles_builder`). -- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did, the block-hash read the Host records, the state-gas price the Host scales and the loads of volatile data the Host marks or refuses. +- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the two instruction hooks that meter a completed write and a frame start, the block-hash read the Host records, the state-gas price the Host scales and the loads of volatile data the Host marks or refuses. Satin's one divergence from op-revm on an ordinary transaction is the history gas it charges: `tests/satin/equivalence.rs` holds every baseline case to op-revm's total plus the history ledger, on op-revm's own state gas, logs and state, and pins what that ledger is made of; a later change that alters behavior on purpose updates that baseline. + A transaction that destroys an account it created diverges beside it by the state gas the destruction table gives back, which EIP-8037 does not (`test_a_creation_that_destroys_itself_diverges_from_op_revm`). - SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`). A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales. A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or the address a creation transaction deploys at, by an applied EIP-7702 authority (its account and its delegation indicator), by the beneficiary a `SELFDESTRUCT` moves a balance to, by the caller a deposit-like transaction creates, and by a keyless deployment's signer when the creation's nonce bump creates it and its deploy address; the bytes a creation deposits are charged in the deployed address's bucket. @@ -165,9 +177,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed. - History gas prices the bytes a transaction appends to the chain, at `MegaETH`'s cost per history byte and never scaled by SALT — history bytes live in no bucket (`evm/history.rs`). The byte table is the `limit` module's, the same counts the data-size limit meters, so a record's history bytes are its own data size and the two cannot drift apart: a transaction body of 310 bytes (110 for the envelope and one 40-byte record for each of the five writes every transaction makes — the sender's account and the four accounts its fees are credited to), one byte per calldata byte, 20 per access-list address and 32 per key, 101 per EIP-7702 authorization, a log's 32 for its address and 32 per topic plus its data, one 40-byte record per kept account or storage write, and one byte per byte of deployed code. - The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body in the EIP-8037 intrinsic state-gas slot, where the reservoir pays it first and it is not held to the execution cap, and the two record charges in pre-execution, where the records are made. - A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas, and the settled result takes the body back out of the state gas it reports. - Every other charge is made where the record is: the opcode wrappers charge what the Host staged for them, and `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their caller for the records the frame they start makes, out of what the caller kept rather than out of what it forwards. + The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame carries its record's charge on its input (`charged_start`), which the shared first-frame settlement gives back when it fails. + A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas. + Every other charge is made where the record is: the completed-write hook charges a storage write's record, a log's and a `SELFDESTRUCT`'s records at the end of its opcode, and the frame-start hook charges the caller of a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` for the records the frame it starts makes, out of what the caller kept rather than out of what it forwards, and declares the frame's own on the start (`FrameStart::charge`), which the fork refunds when the frame fails. What a frame does not keep comes back, at the same price, to whoever paid it. The pairing is per record: per transaction the two totals part at three sites, each by decision — an Oracle hint's payload is data size that is never history, an EIP-7708 transfer log is data size that is never history either, and the body's five records are an upper bound, so a transfer to the block beneficiary or a fee vault pays a record the body already bound. A deposit, a transaction the protocol itself produced and a system call pay no history at all (`MegaContext::prices_history`), and an exempt transaction runs a schedule that prices a deposited byte at zero, so the one history charge revm makes itself is off it too. @@ -180,39 +192,62 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat - EIP-7708 is on: every value movement — the transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT`'s balance moved to another account — emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm journals itself, without a `LOG` opcode, and the receipt carries in execution order among the contracts' own logs. A `CALLCODE`, a call to itself and a transaction's value to its own sender move nothing to another account and log nothing; a deposit's value is logged and its mint is not; a destruction to itself burns the balance of an account created in the transaction without a log, because the base spec predates EIP-8246 and this revm emits no `Burn` log. A transfer log is data size like any log, counted by the rule a `LOG3` of one word is — 160 bytes, `TRANSFER_LOG_SIZE` — and nothing else: it is no write record and pays no history gas, because Ethereum prices it at nothing and it is not a byte the transaction chose to write. - It is counted where the value moves, on the lane of the frame whose journal checkpoint holds the move: a frame start's log with its records, before revm builds the frame and so before its checkpoint, which lets a crossing answer the frame with the stop before any value moves; a `SELFDESTRUCT`'s with its beneficiary's record once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. - A frame start is counted before revm decides it, from what revm itself checks as far as the caller's account decides it, read from the journal without loading anything (`caller_refuses_start` in `evm/execution.rs`): a start revm refuses there — a value its caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes nothing, so it counts no log and no record, is charged no history, and no limit stops it. - The one refusal decided after the count is a creation onto an occupied address, which revm reads off the created address's account only when it builds the frame: its records and log are counted, so a crossing they cause stops the creation where revm would have failed it on the collision. - A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted, so no start is counted for a nonce revm never bumps. - A debug build asserts after every frame start that revm refused exactly the starts predicted and journaled exactly the log that was counted; `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. + It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. + A frame start's records and log are read off the journal before revm decides the start, as the hook that charged its caller read them, and drawn on the pool the frame starts with once revm decided it, in `MegaEvm::frame_init` (`AdditionalLimit::count_start`), with a journal mark at every start: a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; an answer revm gave without building the frame — a call to an account with no code, to a precompile, failed or not — gives way to the stop on its untouched gas, and a success's committed move and log are taken back to the mark (`take_back_a_stopped_answer`). + A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which predicts a start's records from the journal's state and sees the caller cannot fund the value. + A creation it would answer before bumping its creator's nonce — an endowment the creator cannot fund, a creator whose nonce is at its maximum — is refused by the `CREATE` and `CREATE2` opcodes themselves, before the start's hook under EIP-8037, and otherwise reaches the hook without a created address, for which it predicts no record, so a plain run charges and counts nothing for it; only an inspector that rewrites the creation's input after the hook reaches revm's refusal, which bumps nothing and so counts nothing: the declared part of what the opcode charged comes back with the refused start, and the history of the creator's record, which is not declared, stays charged. + A creation onto an occupied address, which revm fails after the nonce bump, is held to nothing at its start: it fails on the collision, its records and log go with the failure, and the nonce record is counted on the creator once the creation returned, held to the creator's limits. + The one decision taken before revm's is gas detention's answer to a precompile whose price crosses the compute limit, given without running it (`hold_precompile`): it is not given to a value call whose caller cannot fund the value, which revm refuses first. + A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted. + A start's log is predicted from the journal's state, as revm's transfer decides it (another account, a value the caller can fund); `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. - The data-size limit holds a transaction to `EvmTxRuntimeLimits::tx_data_size_limit` and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left, under an optional frame cap. - The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes). + A frame's budget is a pool on its gas tracker (`limit::DATA_SIZE_POOL`; the KV-update and state-growth budgets are the other two pools): the transaction's tracker starts with what the body and the counts made before the frame leave (`AdditionalLimit::first_frame_pools`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::pool_kept_percent` = 2, so a child gets 98%), capped where the caller suspends (`cap_the_shares`: the frame cap, and a frame's remaining clamped to its budget, so a negative net never enlarges a child's share), and settles a returning child's pool as it settles the reservoir; the transaction's limit is held beside the pools on what the transaction keeps (`AdditionalLimit::usage`). + In each counted dimension the frame budget is tested before the transaction limit: a crossing of both names the budget, and the transaction limit is named only when the budget is not crossed — after Oracle hints used what the transaction had left, or when a deposit-like transaction's created caller stands on a state-growth limit of nothing; the budgets of the frames on the stack add up to what the transaction has left, so otherwise a frame that crosses the transaction limit crosses its own budget too. + The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts, held to the limits once revm decided it (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s records (the account it clears and its beneficiary) once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes). A frame that crosses its budget or the transaction's limit reverts alone, and its caller resumes (the contracts below). Every `MegaContext`, a bare one included, runs under its spec's limits, and a block executor installs the same (see the protocol limits below): Satin holds each transaction to `TX_DATA_LIMIT` and the block to `BLOCK_DATA_LIMIT`, 12.5 MiB each. The block's data size is a packing budget (see the block executor below). `tests/satin/data_size.rs` derives where the stop gives way to out-of-gas: a top-level fresh `SSTORE` is counted at 152,306 gas, and keeping its record costs its 3,520 history on top. -- A limit stop names one of two runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), counted on the lanes with a transaction limit and frame budgets, and compute gas (2), gas detention's stop. - The legacy engine's KV updates (1) and state growth (3) name no dimension: `LimitKind::from_u8` answers `None` for them. -- No limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write, deduplicated per frame and taken back with a write-back or a failed frame — and the count is still reported, in the outcome's usage and the block's. - The sender's account and the fee accounts are the body's, not records, so a transaction that writes nothing counts none. +- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), KV updates (1) and state growth (3), each drawn from a pool of the frames' gas trackers under a transaction limit, and compute gas (2), gas detention's stop. + An operation that crosses more than one counted dimension stops on the first of data size, KV updates, state growth (`limit::COUNTED`); compute is decided at the regular charge, before the write is counted. +- The KV-update limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original, each taken back by a write that returns the account or the slot and with a failed frame — to `EvmTxRuntimeLimits::tx_kv_update_limit` (`TX_KV_UPDATE_LIMIT`, 500,000) and every frame to 98% of what its parent has left, on the KV-update pool (`limit::KV_UPDATE_POOL`); a crossing reverts the frame with `MegaLimitExceeded(1, limit)` (`tests/satin/kv_updates.rs`), and the count is reported, in the outcome's usage and the block's. + The sender's account is the body's, not a record, and so are the fee credits the settlement makes, so a transaction that writes nothing counts none; a write execution makes to a fee account that is not the sender is a record like a write to any other account. A record is forty bytes of data size, counted and taken back with them, so `KV × 40 ≤ data size` holds after every instruction (`tests/satin/write_records.rs`), and at the production data-size caps a transaction or a block keeps at most 327,680 records. History gas prices every record. -- No limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in, so what bounds it is what it costs — the transaction's gas limit and the block's (`tests/satin/state_growth.rs`). + At the spec's numbers 500,000 records weigh 20,000,000 bytes, more than `TX_DATA_LIMIT`, so the data size binds first; the KV check is still made. + An EIP-7702 list that would keep more records than the limit allows is skipped whole (`hold_authorization_list` in `evm/execution.rs`, see the authorization list below). +- The state-growth limit holds the net count of new accounts and new slots a transaction keeps to `EvmTxRuntimeLimits::tx_state_growth_limit` (`TX_STATE_GROWTH_LIMIT`, 1,000) and every frame to 98% of what its parent has left, on the state-growth pool (`limit::STATE_GROWTH_POOL`); a crossing reverts the frame with `MegaLimitExceeded(3, limit)` (`tests/satin/state_growth.rs`), and the count is reported, in the outcome's usage (`LimitUsage::state_growth`, `max(net, 0)`) and the block's. + One unit rises where EIP-8037 charges the state gas of one, counted where the record of the same write is (`limit/record.rs`): an `SSTORE` from an original and present zero to non-zero, and falls on the write from an original zero back to zero; a value transfer that moves value its caller can fund to another account empty under EIP-161 (a value `CALL`, the transaction's own value), a creation at an empty address (the transaction's own included), both counted on the started frame and read off the journal before revm decides the start (`Accounts::transfer_growth`, `creation_growth`, in `FrameStart::of`, which loads a creation's address first where EIP-8037 is off and the opcode did not); a `SELFDESTRUCT` moving a balance to another account that does not exist; a creator's nonce bump that creates the creator, a keyless deployment's signer, counted with the creator's record on the creating frame once the creation returned (`Accounts::creator_counted`); and, before the first frame and on the transaction, each authority an applied authorization list created and the caller a deposit-like transaction created, which no failure takes back (`AdditionalLimit::count_authorities`, `count_created_caller`). + A fee credit, a `CALLCODE`, a value call to the calling account, deployed code and a delegation indicator are no rise; a failed frame's net goes with it. + An applied EIP-7702 authority counts as created where revm charged it as a new account — empty, loaded as not existing and untouched when the application reached it — read after the application as loaded as not existing, empty at the transaction's start and touched first by the application (`applied_authorities` in `evm/execution.rs`), so on a journal that runs several transactions unfinalized the count follows revm's charge, the flag of an earlier transaction's touch included (see the destruction table below). + EIP-8037 still charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in; the count is what stops the 1,001st slot, which the gas a transaction can pay would not. + An EIP-7702 list that would create more accounts than the limit allows is skipped whole, as one over the KV count is (`hold_authorization_list`). +- The first effective `SELFDESTRUCT` of an account created in the transaction applies the destruction table (`limit/record.rs`, `DestroyedParts`; the completed-write hook in `evm/host.rs`): every part of the account the transaction made comes back to the destroying frame, whichever frame paid — the leaf when the transaction found no account there at its start (`Accounts::was_absent_at_start`: its original info empty, and the database answered none, `is_loaded_as_not_existing`, or an earlier transaction on the same journal destroyed it, which revm's record of this destruction names `LocallySelfdestroyed`), with its new-account state gas, its unit of state growth and the account's write record; the code deposited at it, with its state gas, its data size and its history; each slot it made non-zero from an original of zero, with its state gas, its unit and its record. + A part that existed at the start, such as the leaf of an address funded before the transaction or one empty under EIP-161 with storage, is an ordinary deletion: no refill, no fall, and its write record stands. + Every fact is the journal's: an account revm created in the transaction (`is_created_locally`), the first destruction of one (`SelfDestructResult::previously_destroyed` false), the account's original info and each slot's original value; a slot of an account created in the transaction that the journal does not hold yet loads as zero, so the slots it gives back are the ones it made non-zero, in key order. + revm's flags of an account the database answered none for and of a touched account are set at the account's first load or touch on the journal and outlive the transaction that set them on a journal that runs several transactions without finalizing; a fact about this transaction's start is read with what the journal records of this transaction: its original info, its entries (`JournalEntry::AccountDestroyed`'s status, `AccountTouched`), and the transaction id of what it loaded. + What the parts take back is in the same check as what the operation adds, so the beneficiary's record, its transfer log and its unit are held after the give-back; once the check passed, each part's state gas is refilled at the price it was charged, re-priced through `state_gas_price` at the site it landed on, with the history of the records and the schedule's history of the code, before the operation's own records are charged. + The refills follow the refill order, the frame's spill first; a failure of the destroying frame, or of a frame that contains it, takes back the mark with the journal and the give-back with the frame. + From the mark until the transaction ends the account counts nothing more (`Accounts::is_destroyed`): its nonce no longer is what the transaction loaded, so no write to it makes or takes back its record and a value moved to it adds no account, and an `SSTORE` of one of its slots counts nothing; the pricing hook prices every state charge on the account at nothing, so such an `SSTORE` neither charges nor refills fresh-slot state gas and code its own constructor deposits after destroying it (through a `DELEGATECALL`) is charged no state gas, whatever gas the frame holds, its data size and history standing; the table's own give-back prices the parts outside that rule (`MegaContext::priced_state_gas`). + A slot of the account loaded before the creation, which only a tool's load reaches, keeps the value it held at the start: the deletion refills nothing for it and makes its record while it still holds that value. + The account's logs stay counted. + The neutral configuration counts the table as the spec's does and prices state gas as the fixture's fork does, which gives none back for this destruction (`MegaContext::destruction_table_prices_state_gas`). - The limits that change a result are protocol values fixed per spec, as the legacy engine's were: `ProtocolLimits::for_spec` (`block/limit.rs`) is the one table of them, keyed by `MegaSpecId`, with one arm, `SATIN`, every field written out. - It holds the four per-transaction limits (`tx_runtime_limits`, an `EvmTxRuntimeLimits`: data size per transaction 13,107,200, no frame cap beyond the 98/100 share, detention's two caps 20,000,000 each) and the block's data-size budget, 13,107,200; the values are provisional with the constants. + It holds the per-transaction limits (`tx_runtime_limits`, an `EvmTxRuntimeLimits`: data size per transaction 13,107,200, KV updates per transaction 500,000, state growth per transaction 1,000, no frame cap beyond the 98/100 share, detention's two caps 20,000,000 each) and the block's three packing budgets, data size 13,107,200, KV updates 500,000 and state growth 1,000; the values are provisional with the constants. No chain configuration carries them: they are not fork params, a genesis file names none, and a node passes none of them; a test holds them to what the removed load-time check held a chain's values to (none zero, the data size above `TX_BODY_SIZE`, the detention caps below `MAX_TX_COMPUTE_GAS`, 199,987,900, so detention binds), and `tests/block/l1_attributes.rs` holds the block's L1 attributes deposit to them. Three layers keep three scopes: `ProtocolLimits::for_spec` the consensus values; `EvmTxRuntimeLimits` what one EVM runs under, the table's by default (`Default` is the default spec's), which a tool or a test may replace; `BlockLimits` the builder's policy, which only tightens. `MegaContext::new` starts under its spec's limits, so an EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) and a bare context run under the limits block execution would hold their block to without being told; `MegaEvmFactory::with_tx_runtime_limits` and `MegaContext::with_tx_runtime_limits` are the explicit opt-outs, for equivalence, tools and tests. - The block executor reads the table for the spec its EVM executes, installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to its data-size budget; `MegaBlockExecutor::with_protocol_limits`, which exists only under `cfg(test)` or `test-utils`, holds a block to other limits, for tests and for `mega-evme --override.limits`. + The block executor reads the table for the spec its EVM executes, installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to its packing budgets; `MegaBlockExecutor::with_protocol_limits`, which exists only under `cfg(test)` or `test-utils`, holds a block to other limits, for tests and for `mega-evme --override.limits`. The block's gas limit is the executor's state (`BlockLimiter::block_gas_limit`), taken from the block environment; no policy carries one. - The node's block context carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap on the data-size budget that `BlockLimits::within` holds below the protocol's, so a policy tightens and never loosens; its default restricts nothing, and a validator leaves it so. + The node's block context carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and caps on the three packing budgets that `BlockLimits::within` holds below the protocol's, so a policy tightens and never loosens; its default restricts nothing, and a validator leaves it so. A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/building_policy.rs`). Satin carries no fork parameter: the `SequencerRegistry`'s roles are what the registry the legacy forks left holds. A genesis file's `config` object carries Satin as one key, `satinTime`, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads it with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value that is not a 64-bit integer, and a schedule `validate_schedule` refuses; the key format is provisional. - The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them. It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit. + The exemption covers the KV updates and state growth beside data size. What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is. - A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction it refuses as any legacy transaction, because the block decides on the envelope (see the block executor below). + A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction the block's packing budgets and the builder's policy never refuse, while the block's gas limit and the data-availability footprint hold it as any legacy transaction, because the block decides on the envelope (see the block executor below). A user's deposit is not system-originated and is held to every per-transaction limit. - Gas detention caps the compute a transaction may spend once it read volatile data — the block environment, the block beneficiary's account, the Oracle's storage — at its compute at the read plus a cap, a runtime limit of 20,000,000 by default (see Gas detention below). It holds a frame's spendable gas with the revm fork's withheld part, which every reader of the frame's gas but a regular charge counts, so a detained transaction runs as it would without the read until a regular charge needs the withheld part. @@ -222,11 +257,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The block's data-size limit, known only after execution, packs the transaction that reaches it and then refuses every later transaction before it runs. It never refuses a deposit or a Mega System Transaction: it is a packing budget for the transactions the builder chooses, and neither is chosen; both still count towards it, so the transactions after them find the room they used. Nor does the builder's policy refuse either. - No block limit holds the execution, state or history ledger, or the write records: they are counted and reported. - A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which an activation block refuses and which the data-availability limits and footprint hold like any non-deposit transaction, but the block decides before the engine promotes it that it is one (`MegaBlockTxResult::is_system_transaction`: a legacy call of the system shape from the live system address, read with `live_system_address` and `classify_system_transaction`), and the data-size budget and the builder's policy do not refuse it; the commit-time check reads the same flag. + The block's KV-update and state-growth limits (`BLOCK_KV_UPDATE_LIMIT`, 500,000 write records, and `BLOCK_STATE_GROWTH_LIMIT`, 1,000 new accounts and slots) are packing budgets of the same kind, checked after the data size and in that order (`BlockLimiter::pre_execution_check`), so a block full on several names the first; the transaction that reaches one is packed, every later ordinary one is refused before it runs, and neither refuses a deposit or a Mega System Transaction, which still count; the block's gas limit does not stand in for the state-growth budget (`tests/block/limits.rs`, `tests/block/system_tx_budgets.rs`). + No block limit holds the execution, state or history ledger: they are counted and reported. + A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which an activation block refuses and which the data-availability limits and footprint hold like any non-deposit transaction, but the block decides before the engine promotes it that it is one (`MegaBlockTxResult::is_system_transaction`: a legacy call of the system shape from the live system address, read with `live_system_address` and `classify_system_transaction`), and the packing budgets and the builder's policy do not refuse it; the commit-time check reads the same flag. alloy-evm's `commit_transaction` cannot fail, and its contract is that an outcome commits before the next transaction executes; a builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the counters again and refuses what no longer fits, and a debug build asserts the same check in `commit_transaction`. The checked commit also refuses an outcome whose sender's nonce or balance — the system address's, for a system-address transaction — another commit moved since it executed (`MegaBlockExecutionError::StaleOutcome`, an internal error; the executor reads the sender's account before every transaction into `MegaBlockTxResult::{sender, sender_nonce, sender_balance}`), and a debug build asserts it in `commit_transaction`; any other state a candidate read is the builder's to keep fresh, which the system-transaction-first flow relies on (`tests/block/stale.rs`). - It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, read-only entries included — that sequence of committed states, with the included transactions' and the exports, is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`), which receives each state whole, where the block's transitions keep only what a state changed; after the two EIP calls it checks the seven predeploys in Satin's activation block alone (see below), applies a role change the `SequencerRegistry` has due in the block (see the system calls below), and last commits the L1 block contract's account and every slot the transactions can be priced against (`L1_BLOCK_INFO_SLOTS`: 1, 3, 5, 7 and 8) as read-only entries (`read_l1_block_info`), because op-revm and the executor read them on the block's state rather than through a transaction's journal, so they land in no transaction's state. + `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, read-only entries included — that sequence of committed states, with the included transactions' and the exports, is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`), which receives each state whole, where the block's transitions keep only what a state changed; after the two EIP calls it checks the seven predeploys in Satin's activation block alone (see below), applies a role change the `SequencerRegistry` has due in the block (see the system calls below), and last commits the L1 block contract's account and every slot the transactions can be priced against (`L1_BLOCK_INFO_SLOTS`: 1, 3, 5, 7 and 8) as read-only entries (`read_l1_block_info`), because op-revm and the executor read them on the block's state rather than through a transaction's journal, so they land in no transaction's state. The overhead (5) is in the entry whatever the Ecotone scalars hold: op-revm reads it when the scalars it finds at the block's first non-deposit transaction are empty, which a deposit earlier in the block decides, so an entry listing it only under empty pre-block scalars would leave a read no state names (`tests/block/witness/state.rs`). The pre-block step does not read the live system address: the executor reads it before every non-deposit transaction, as above, and every transaction reads it itself when it is validated (see below). - Satin deploys, upgrades and seeds no contract: it runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs (the Oracle at v2.0.0, Rex5's, and the `SequencerRegistry` at v2.0.0, Rex6's), and whose genesis OP's tooling gave the EIP-7997 factory. @@ -249,12 +285,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat Every such read by a transaction is recorded with its answer on the transaction's outcome (`MegaTransactionOutcome::oracle_reads`, the context's `OracleReadRecord`, emptied before every transaction and system call), which is where a node building a stateless witness takes the oracle answers of the transactions it includes from. - A `keylessDeploy(bytes,uint256)` call a transaction makes is a native keyless deployment (`system/keyless/`): the pre-EIP-155 creation it carries is deployed as a `CREATE` of its signer, at the signer's Nick's-Method address. The dispatch (`keyless::is_dispatched`) runs in `frame_init` before interception, and revm builds the call's frame as any call's: on the contract, at depth 0, on revm's frame stack, with its own journal checkpoint and gas. - No code runs in it: `frame_run` makes its actions by hand (`keyless::run`), on its first run the refusal or the creation, and on its resume, once the creation returned into it, the answer. - An inspector sees the frames the deployment is made of: the call, started and ended as any call's, with no interpreter initialized and no step in it, and the creation as its child, one journal depth below. + No code runs in it: its actions are made by hand, its first where revm built the frame (`keyless::start`, in `frame_init`) — a refusal ends the frame before it runs, as the stop of a start does, and the creation is set on the frame's interpreter — and its answer once the creation returned into it (`keyless::answer`, in `frame_return_result`), set on the interpreter the same way; revm's frame run, plain or inspected, returns an action set on a frame before it runs. + An inspector sees the frames the deployment is made of: the call, started and ended as any call's, and the creation as its child, one journal depth below; the call's interpreter is handed to no `initialize_interp` and gets no `step`, since revm's inspected run returns an action set on a frame before any `step` and skips `initialize_interp` for a frame built with one, and a refused call is seen to start and end and nothing else. It charges the fixed overhead, which pays for decoding the transaction and recovering its signer, and holds the call to the legacy engine's nine rules and error ABI in the legacy engine's order, so a call several rules refuse reports the legacy engine's error. Among the rules it charges the signer's account when the creation's nonce bump creates it, SALT-priced state gas, where the legacy engine charged it; after every rule, what the `CREATE` opcode charges its frame: its regular gas (the schedule's `create` entry and EIP-3860's cost per word of init code), the created account, SALT-priced state gas, and the creation's two write records. It then starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left, which must still cover the signed gas limit. - Its lane is the one any depth-0 call pushes, running as the signer from the first run on. + It is held to its limits as any depth-0 call is, running as the signer from the first run on: the creation's start charge and share of its pool are the call's, and the signer's nonce record is counted on the call's pool once the creation returned, at the settlement (`keyless::settle`), as a `CREATE`'s creator's record is on the creator. The creation returns into the call through `frame_return_result`, which reads the creation's outcome before revm merges it (`keyless::returning`) and takes the nonce back after (`keyless::settle`), before the call resumes, and the call answers in the ABI on its resume. The frame is built on the contract as its target: the contract's account, which the transaction loads with its code to start its first frame, is touched by a call that returns, as a call's target is; a witness holds the account and its code for any transaction to the contract, so the frame adds nothing to it. A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm builds its frame, so no value moves and nothing its start would write is counted. @@ -278,21 +314,22 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat The read names no address unless the registry holds the code this engine requires (v2.0.0) and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution Satin's activation block refuses a chain whose registry does not hold the code, and a later block runs on the state it is given. It is a read of the transaction's own, so the slot is in every transaction's state and witness, not in the pre-block witness. - A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which its state writes draw first before spilling onto the regular budget. - The split is the fork's (`Handler::system_call_gas`, both system-call paths), switched on by `spec_cfg`; the neutral configuration leaves it off for both forks, as revm's runner does, and no state fixture makes a system call. - A system call stays the protocol's own work: priced at the minimum SALT bucket, paying no history gas, held to no per-transaction limit and not detained, so it settles exactly as op-revm's does on the same configuration (`tests/satin/system_call.rs`, `tests/satin/equivalence.rs`). + The split is the handler's (`MegaHandler::tx_gas`, through which revm builds a system call's gas on both system-call paths), for every system call whatever the configuration (`MegaContext::splits_system_call_gas`); the neutral configuration leaves a system call's gas whole for both forks, as revm's runner does, and no state fixture makes a system call. + What a system call left of its reservoir is `AdditionalLimit::reservoir_remaining`, which revm's result does not carry. + A system call stays the protocol's own work: priced at the minimum SALT bucket, paying no history gas, held to no per-transaction limit and not detained, so it settles exactly as op-revm's does on the same configuration with the same split (`tests/satin/system_call.rs`, `tests/satin/equivalence.rs`). A transaction is not a system call: every transaction's gas is split by the execution cap, the system-address transaction's included. The system calls the engine makes, and their gas limits: - | System call | Target | Gas limit | Regular | Reservoir | - | ------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------------------- | ------------------------ | --------------------------------------- | - | EIP-2935 block hashes, pre-block | `0x0000F908…2935` | `pre_block_call_gas_limit`: max(block gas limit, 30M) | 30M | the block gas limit less 30M, or none | - | EIP-4788 beacon root, pre-block | `0x000F3df6…Beac02` | the same | 30M | the same | - | `SequencerRegistry.applyPendingChanges()`, pre-block, when a change is due | `0x6342…0006` | the same | 30M | the same | - | alloy-evm's `transact_system_call`, revm's `SystemCallEvm` and `InspectSystemCallEvm` | the caller's | revm's `SYSTEM_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 | - | `MegaEvm::transact_system_call_with_gas_limit` | the caller's | the caller's | the lesser of it and 30M | the rest | + | System call | Target | Gas limit | Regular | Reservoir | + | ------------------------------------------------------------------------------------- | ------------------- | ------------------------------------------------- | ------- | --------------------------------------- | + | EIP-2935 block hashes, pre-block | `0x0000F908…2935` | `constants::PRE_BLOCK_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 | + | EIP-4788 beacon root, pre-block | `0x000F3df6…Beac02` | the same | 30M | the same | + | `SequencerRegistry.applyPendingChanges()`, pre-block, when a change is due | `0x6342…0006` | the same | 30M | the same | + | alloy-evm's `transact_system_call`, revm's `SystemCallEvm` and `InspectSystemCallEvm` | the caller's | revm's `SYSTEM_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 | The pre-block calls run as the EIP-4788 system address (`0xff…fe`). - Their budget is the legacy engine's, kept as it was rather than replaced: it was widened for the storage gas a crowded SALT bucket multiplied past 30M, which a system call no longer pays, and what it adds above 30M is reservoir, which nobody pays for when the call does not draw it; a block of 30M or less gives no reservoir, and the calls' few writes spill onto 30M of regular gas. + Their budget is one constant `MegaETH` owns, whatever the block's gas limit, which a pre-block call does not draw on: 30M of regular gas and a reservoir of sixteen fresh slots at the minimum bucket, which holds the most any pre-block call writes (six fresh slots, an `applyPendingChanges()` that applies both roles) more than twice over; it equals revm's default today and does not move with it. + None of the three contracts reads `GAS`, so the reservoir changes no call's result; the legacy engine's `max(block gas limit, 30M)`, widened for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays, is gone. A pre-block call that does not succeed refuses the block before its state is committed. One helper runs all three pre-block calls and holds one rule for them (`block/eips.rs`, `transact_pre_block_call`): a database error the database calls fatal (`DBErrorMarker::is_fatal`) is an internal error (`BlockExecutionError::other`), because a read the database could not serve says nothing about the block and a node must not refuse a valid block because its storage failed; any other failure — a database error that is not fatal (under revm's `State`, an EIP-7928 block access list that does not cover a read), an EVM error other than the database's, or an outcome that is not a success — refuses the block with the call's own validation error (`BlockValidationError::BlockHashContractCall`, `BlockValidationError::BeaconRootContractCall`, `MegaBlockExecutionError::ApplyPendingChangesFailed`). It is the rule alloy-evm's block executor holds a transaction's database error to (`BlockExecutionError::evm`). @@ -309,54 +346,65 @@ Detention caps how much a transaction may still compute once it read such data ( - **What is volatile.** The block environment (`NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH`); the block beneficiary's account, through every account opcode, the four calls and the EIP-7702 delegate they follow, `SELFDESTRUCT` at either end, a sender or recipient that is the beneficiary, a recipient that delegates to it, an applied EIP-7702 authority that is, and a keyless deployment's signer that is (the call reads the signer's account through the journal, so it marks the read itself, at its compute then); the Oracle's storage, through `SLOAD` in the Oracle's own frame. `BLOBHASH` is not: it reads the transaction's own blob hashes. + A call to the EIP-2935 history contract is a block-environment read, through the `NUMBER` its code runs before it loads the slot; the storage the EIP-2935 and EIP-4788 pre-block calls write is state the block starts with, and an `SLOAD` of it is none (`test_the_history_contract_reads_the_block_number_and_the_beacon_roots_contract_reads_state`). A system-originated transaction and a system call are not detained, whatever they read, the block environment included: the same rule exempts them from every per-transaction limit. Neither is a transaction under `no_limits()`, which the execution-spec gate's runner installs. - **Where a read is marked.** Where the Host loads the value (`evm/host.rs`), and committed by the opcode's wrapper once the opcode completed (`evm/instructions.rs`), as a write record is; a load that fails, and a read whose opcode then fails, mark nothing. + The Host refuses and marks a load only while a wrapper runs its opcode (`Detention::begin_read`): `CREATE`'s and `CREATE2`'s loads of their creator and created address, which revm makes through the Host, and an inspector's loads are no reads, neither refused nor marked, as a value call's check of its caller's balance is none. - **The cap.** Compute is the regular gas the transaction spends on what it runs, read off `Gas`: a frame's limit less what it has left — its withheld part included, so withheld gas is never spent — less the state and history gas that spilled onto its regular gas; what a halting frame burns is not compute either. - The transaction's compute is the running frame's regular gas spent plus every suspended caller's, each less its child's gas limit, which takes a value call's stipend off with it, less what halts burned: the regular ledger at every moment, the burns taken out. - The stipend stays outside compute on purpose, compute being regular gas drawn from the transaction's own pools: a callee may run up to 2,300 gas on each value call's stipend, and each value call costs its caller at least 9,100 of compute, so the gas run after a read is at most about 25% more than the cap. + The transaction's compute is the running frame's regular gas spent plus every suspended caller's, each less the gas it forwarded its child, plus the stipends of the value calls that returned, less what halts burned: every regular charge an instruction makes, whoever funds it, the burns taken out. + What a callee runs on a value call's stipend is compute: the stipend is not forwarded gas, so a caller's contribution while its child runs takes off its forward alone, and once a value call returned its stipend is counted apart, since what the callee left of it came back to the caller's gas on top of the forward; so compute is the regular ledger plus the stipends, less what halts burned, and the gas run after a read is at most the cap. + A precompile that runs out of gas counts nothing of its forward: its answer halts and burns it, a value call's stipend included. A read sets a limit — the transaction's compute at the read plus its cap, `EvmTxRuntimeLimits::block_env_access_compute_gas_limit` or `oracle_access_compute_gas_limit`, 20,000,000 each by default (`BLOCK_ENV_ACCESS_COMPUTE_GAS`, `ORACLE_ACCESS_COMPUTE_GAS`) — and the limit only goes down, so the most restrictive read binds. - Nothing per frame is kept for the figure until a read sets a limit: `MegaEvm::frame_init` records a caller's regular gas spent and gas limit when revm is about to build a child of it (`record_caller`, `Detention::on_child_build`), and the first read rebuilds what the frames it runs under add from those records (`Detention::track`); from there every frame is kept as it starts, suspends, resumes and ends, and debug builds keep the eager figures from the first frame on and assert the kept ones equal to them. + The frames' figures are kept for every transaction detention holds, from its first frame on, as each frame starts, suspends, resumes and ends, so a read at any depth finds the compute of the frames it runs under already summed. `no_limits()` leaves both caps unlimited, and a transaction whose caps are both unlimited is not detained: that is how the neutral configuration's runner turns detention off. It turns detention off together with every other per-transaction limit, so it is for equivalence mode and tests, not for executing the chain; `EvmTxRuntimeLimits::default()` and `ProtocolLimits::for_spec` detain, with caps below `MAX_TX_COMPUTE_GAS`, so a node running the chain never turns detention off. - **The enforcement point: the withheld part.** The revm fork keeps a frame's regular gas in two parts (`GasTracker`): a spendable part, the only one a regular charge draws, and a withheld part. - Every other reader sees their sum — `GAS`, the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold checks, the gas a child returns, the reimbursement — and a forward or a state or history spill draws the withheld part first. - Detention holds a frame's spendable part at what the limit leaves the transaction (`Gas::limit_spendable`): at the read, once its wrapper committed it; at the frame's start and every resume (`before_frame_run`); and after `SSTORE`, whose restore of a slot to its original value refills regular gas. + Every other reader sees their sum — `GAS`, the 98/100 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold checks, the gas a child returns, the reimbursement — and a forward or a state or history spill draws the withheld part first. + The forward is Rex6's subtraction, `remaining − remaining × 2 / 100`, in place of EIP-150's 63/64: the fork's `GasParams::call_stipend_reduction` with the quotient 50 (the schedule's `GasId::call_stipend_reduction`) is that subtraction exactly, as `remaining − remaining / 50`; a value call's 2,300 stipend joins the forward after the cap, and a keyless deployment's creation keeps its own forward, `min(gasLimitOverride, remaining)`. + The neutral configuration (`MegaContext::with_neutral_cfg`) keeps EIP-150's 63/64, and gives a child the whole reservoir: equivalence mode is Ethereum's forward, not Satin's. + `no_limits()` is a separate switch. + It turns detention and every other per-transaction limit off, and it does not change the forward. + Detention holds a frame's spendable part at what the limit leaves the transaction (`Gas::limit_spendable`): at the read, once its wrapper committed it; at the frame's start, once revm built it (`frame_init`), and every resume (`frame_return_result`); and after `SSTORE`, in the completed-write hook, whose restore of a slot to its original value refills regular gas. So a detained transaction runs exactly as it would without the read until a regular charge needs the withheld part: that charge fails as it would with nothing withheld, and the fork records a `WithheldCrossing` holding the regular gas the frame had before it, both parts together. Nothing withheld is ever released: a frame's withheld part goes back to its caller with the rest of its gas, and `return_create`'s deposit and hash charges, the creating frame's own compute, draw the spendable part like any other regular charge. - **The classification.** A frame whose result carries a crossing record crossed the cap (`Detention::on_frame_end`). - It is read in `after_frame_run`, after revm processed the frame's last action — `return_create` included — and before the result reaches the caller, or, for the transaction's own frame, `last_frame_result`, which overwrites the frame's gas with the transaction's. + It is read in the fork's run-result hook (`frame_run_result`, `end_frame`), which revm's plain and inspected loops call once a frame's run returns, after revm processed the frame's last action — `return_create` included — and before anything else sees the result: the inspector's `call_end`, `create_end` and `frame_end`, then `frame_return_result` and the caller, or, for the transaction's own frame, `last_frame_result`, which overwrites the frame's gas with the transaction's; only an out-of-gas is read, since a crossing only ever ends a frame on one. + So an inspector and a tracer see the frame end with the stop, as the receipt bills it, and a rewrite of the stop is taken as given like any other; a frame that ends before it runs, which `frame_init` returns, is classified where it ends (`end_before_it_runs`). The frame becomes the stop's revert, `MegaLimitExceeded(2, limit)`, with its gas put back to the record's `remaining`: the charge that crossed is not made, the spendable and withheld parts go back to its caller, and the transaction's compute at the crossing is less than one charge short of the limit. The caller resumes held to what the limit leaves, less than the charge that crossed, so a regular charge of its own past that crosses again and stops it in turn; one that ends within it ends the transaction within the limit. The settlement is the same whether the halt zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, `return_create`'s own out-of-gas on a deposit charge). - The stop reports the transaction's compute at the crossing as what was used (`LimitCheck::ExceedsLimit`), the figure the regular ledger bills, computed the same way at every crossing site; the size of the charge that crossed is not kept, so it is at most the limit, unless a halting frame's leftover, counted as compute, took the transaction past the limit before the charge. + The stop reports the transaction's compute at the crossing as what was used (`LimitCheck::ExceedsLimit`), the figure the regular ledger bills with the stipends of the transaction's value calls on top, computed the same way at every crossing site; the size of the charge that crossed is not kept, so it is at most the limit — but where an inspector's answer, taken as given, spent past what the limit left its frame, whose spending is its caller's compute. Every other out-of-gas halts and burns as it would without the read: an operand above `usize`, a failed state or history charge, a regular charge beyond the frame's whole gas. - **Answers.** revm runs a precompile inside the frame's start, against the frame's gas limit, so a precompile forwarded more than the allowance its frame would start with is decided before it runs (`hold_precompile` in `MegaEvm::frame_init`). One the engine prices (`PricedPrecompiles::price`, `evm/precompiles.rs`) is decided from its price, read with `Precompile::required_gas` off the Satin table's own entry: priced within the allowance, it runs on its whole forward, as without the read; priced past the allowance and within the forward, it is answered without running, out of gas and marked `WithheldCrossing::with_remaining(forward)` (`Detention::cross_at_price`), and stopped by the same classification; priced past its whole forward, it runs on the forward and runs out of gas, a failed call its caller survives, as without the read. - A call revm refuses on its caller's account runs no precompile and is answered as without the read. + A call revm refuses on its caller's account runs no precompile and is answered as without the read: the answer given without running is not given to a value call whose caller cannot fund the value, which a comparison of the caller's balance with the value decides, as revm's transfer does. + None of this precedes the call's own regular charges, made at the opcode as any opcode's — its static gas, the value transfer, a cold access — and one that crosses stops the calling frame before the price is read, whether or not the caller can fund the value (`tests/satin/detained_transfers.rs`). One residual is a choice: the price does not tell whether an input passes the checks a precompile makes after its gas check, so an input priced between the allowance and the forward that would fail such a check is the stop, where without the read the check fails the call, which its caller survives. The Satin table prices an address only while the dispatched entry is still its own: not an address a node replaced through `MegaEvm::with_dyn_precompiles` (recorded, whatever id its precompile carries), not one whose dispatched entry carries another id, and nothing once the neutral configuration installed the fixture fork's set; a node's own precompiles carry no price either. Every entry of the Satin table carries one, op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing included: the op-revm fork prices an input within a wrapper's size limit as the run it wraps does, and one past it, which the wrapper refuses before any gas check, at nothing. alloy-evm's `PrecompilesMap` erases what it holds once a node changes it, so a change made around the engine, through the mutable reference to the map that revm's `EvmTr::all_mut` and alloy-evm's `Evm::components_mut` hand out, is not seen: an entry replaced through the map's mutable accessors under the replaced entry's id, and a whole set put in the map's place, whose entries are then priced from the Satin table wherever they carry its ids. Neither accessor is a sign of a change — revm reaches the context through `all_mut` on every frame, and alloy-evm's tracer calls `components_mut` — so a node changes the set through `with_dyn_precompiles` or the factory's builder. A precompile the engine cannot price is run on the allowance and sees it as its gas limit; its answer gets the rest of the forward back (`Detention::restore_forward`), and one that runs out of the allowance is marked as a crossing with its forward and stopped, whether its price is within the forward or not. - An interceptor builds its answer on the whole forward, the caller's withheld part included: an answer that spent more regular gas than the allowance the frame would have run on is answered out of gas, marked with `set_withheld_crossing` — its spending the charge that crossed, so its frame gets its whole gas back, less a spill the revert credits — and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer in `inspect_frame_init`); the one answer of the engine's own that spends regular gas is that of a `keylessDeploy` call carrying value, and a crossing answer is settled on the limit the caller forwarded, whatever limit an inspector built it on. + An interceptor builds its answer on the whole forward, the caller's withheld part included: an answer that spent more regular gas than the allowance the frame would have run on is answered out of gas, marked with `set_withheld_crossing` — its spending the charge that crossed, so its frame gets its whole gas back, less a spill the revert credits — and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`); the one answer of the engine's own that spends regular gas is that of a `keylessDeploy` call carrying value, and a crossing answer is settled on the limit the caller forwarded. + An inspector's answer never reaches the engine's frame start, and is taken as given: no limit holds it. An answer that halts otherwise burns its whole gas limit. - **A keyless deployment's call.** - The call is the transaction's own frame and runs no code, and detention holds it as any frame: its gas is held to what the limit leaves it when it first runs (`before_frame_run`), before it charges anything, so its own work — the overhead, then the `CREATE` opcode's regular gas — draws the spendable part, and a charge past the limit is a crossing its frame end stops, whether a rule would then have refused the call or its creation would have run. + The call is the transaction's own frame and runs no code, and detention holds it as any frame: its gas is held to what the limit leaves it once revm built it, before it charges anything, so its own work — the overhead, then the `CREATE` opcode's regular gas — draws the spendable part, and a charge past the limit is a crossing its frame end stops, whether a rule would then have refused the call or its creation would have run. The forward to the creation is not the call's work and draws the withheld part first, as a `CREATE` opcode's does. A call that starts its creation suspends on it as a frame suspends on its child, so the creation's first run adds the call's charges to the transaction's compute, as a caller's work before a `CREATE` is, and the creation runs under what the limit leaves it like any frame; its crossing stops the creation, and the call answers that stop as `ExecutionReverted` on its resume. On its resume the call is held again, as every frame's resume is; it charges nothing more. A call carrying value is an answer, held by the rule above. - **What a halt burns.** - An out-of-gas zeroes a frame's gas before the frame returns, so the wrapper of the opcode whose charge failed notes what the frame had first (`Detention::note_halt`); `KECCAK256` and the four copies into memory are wrapped for that alone, their charge having no bound, and so is `EXP`, whose exponent charge reaches 1,600; a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails. - The one charge no wrapper sees is an opcode's static gas, which the step loop makes before the opcode runs: when it fails, what the halting frame had left counts as compute, per halting frame, under the failed charge's price (at most 4,999, on `SELFDESTRUCT`). - Burned gas is counted as compute, so the stop comes earlier, never later; a frame whose leftover takes the compute past the limit does so without a crossing, so the stop is its caller's next charge, and the regular ledger at the stop holds that leftover's part past the limit beside the limit. + An out-of-gas zeroes a frame's gas before the frame returns, so the revm fork records what the frame had first: before every deduction that fails, an opcode's static gas, which the step loop charges before the opcode runs, included, and before a halt on a cold access the frame cannot pay (`Gas::failed_charge_remaining`); `Detention::on_frame_end` reads the record, and a halt that zeroes nothing leaves the frame's gas readable in its result. + So what every halting frame burns is exact, and none of it is compute. + A frame-starting opcode whose caller cannot pay the start's records starts no frame: the frame-start hook hands the forward back before the opcode fails, and records what the frame has then, since the failed charge recorded the gas left after the forward was taken. + An inspector's refused charge leaves its record as an opcode's does, as revm leaves it: a later halt that records nothing of its own is read off it. - **Refused reads.** `MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, once the answer is settled and only when gas detention did not turn it into the stop (`Detention::disable_access_on_answer`), until that frame calls `enableVolatileDataAccess()` or returns; a frame below cannot switch back on what a frame above switched off (`DisabledByParent()`), and `isVolatileDataAccessDisabled()` answers for the caller. The caller is the frame one level above the one the call would start (frame depth = the frame-init depth less one, where the legacy engine used the caller's journal depth, the same frame); a transaction that calls the contract directly has no frame above it, so disabling changes nothing, enabling succeeds and the query answers `false`. @@ -370,68 +418,85 @@ Detention caps how much a transaction may still compute once it read such data ( Every later mechanism plugs into these; a change to one comes back to this layer. -- **The Host only observes.** - `sstore`, `log` and `selfdestruct` stage the facts revm hands them (`StagedRecord`) and record nothing. - Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop a frame for a write that never happened. -- **Commit after the opcode.** - The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed, and charge the frame the history the record costs — which is the record's own data size, so the charge and the count are the same number. - A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its record, and is charged nothing for it. - The wrappers of `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their own frame for the records the frame they start makes, after revm computed the gas they forward, so the frame's budget carries none of them. - Two things follow from charging after revm's instruction has built the frame's input: the frame carries a copy of the caller's reservoir, taken before the charge, so the wrapper writes the post-charge reservoir back into it — a frame that inherited the earlier one would hand the charge back on return, and a frame answered without running would hand it back twice. - And the frame is already pending as the interpreter's action, which halts on an instruction's error only when no action is pending, so a caller that cannot pay drops the pending frame before it fails; otherwise the frame starts and its records are never paid for. - The opcodes that can read volatile data run in detention's read wrapper, around the wrapper above when they have one (see Gas detention). +- **Writes are counted once their opcode completed.** + The Host's write methods (`sstore`, `log`, `selfdestruct`) only write, whoever calls them. + revm's `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` call the completed-write hook (`MegaContext::write_completed`) once the write is in the journal and every charge the opcode makes has been made, so a write the opcode's own failure takes back (an out-of-gas after the write) is never counted, and no limit stops a frame for a write that never happened. + A tool's write through the Host, an inspector's log among them, reaches no hook and is not counted. +- **The completed-write hook.** + It counts the record on the running frame's pools (`AdditionalLimit::draw`) and holds it to the limits first — in each counted dimension the frame's budget, then the transaction's limit; a crossing is the stop, a revert of the frame — then charges the frame the history the record costs, which is the record's own data size, so the charge and the count are the same number: a log draws on the frame's history allowance first, a charge the frame cannot pay is an out-of-gas, and a record taken back refills its history. + A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its records, and is charged nothing for it. + After an `SSTORE` it holds the frame to the compute limit again (`Detention::hold`, the one formula over the frame's `GasTracker`): a restore refills the state gas, revm before the hook, and the history gas, the hook, that spilled onto regular gas. +- **The frame-start hook.** + revm's `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it (`MegaContext::frame_starting`) after every charge they make and after the forward is taken from the caller, before they build the frame's input: it charges the caller the history of the records the start makes, out of what the caller kept, and declares the part the frame's own records cost on the start (`FrameStart::charge`), which revm carries on the frame's input and outcome and refunds to the caller when the frame fails; the history of a creator's nonce record is charged there and not declared, the record outliving the creation. + The hook only prices, and counts nothing: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and nothing is given back. + After the hook revm takes the frame's share of the caller's reservoir and of each pool out of the caller (`GasTracker::forward_to_child`) and puts it on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (the schedule's `GasId::reservoir_kept_percent` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs, and the child's return adds what it left back to what the caller kept, unwinding the caller's outstanding spill first (`absorb_returned_reservoir`). + A keyless deployment's creation takes the same share of what the call has left after the call's start charges (`keyless::start`, through `forward_to_child`). + The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole. + A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame. + The records are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode and again where revm decides the start, a creation's at the address it takes (`FrameStart::target`), and counted on the started frame's pool once revm decided it; a debug build holds those to what revm's start made of the accounts, exactly for every record. + A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, and its declared part comes back only as it does for any start whose frame keeps nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value; its records are those revm then made. +- **The instruction table.** + The opcodes that can read volatile data run in detention's read wrapper (see Gas detention). Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's Amsterdam one. - **Write records.** - One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account. - The sender's own account is part of the transaction body: it is never a record, and a frame running as the sender (through an EIP-7702 delegation) counts it as recorded. - Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped. - That record lands on the creator after the creation's own check, so the creator is held to its budget with it before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_frame_return`). - The KV count a node reports is the write-record count; no limit holds it. -- **Lanes stay aligned with frames.** - `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran. - A `keylessDeploy` call's frame has the lane any depth-0 call has, and its creation's lane is pushed above it as any child's. + One 40-byte record per account or storage write, which follows the net change: a slot's record exists while its value differs from its original in the transaction (made by its first change, taken back on a write-back), an account's while its nonce, balance or code differs from what the transaction loaded, revm's original info (`Accounts::is_changed`): a start's records are read off the journal before revm makes the start — a value transfer's two sides on the balances it leaves them, a creation's creator and created account (an address the transaction funded, or a `SELFDESTRUCT` paid, before the creation lands on it is changed already, and the creation adds no record for it) — and a `SELFDESTRUCT`'s after it, its beneficiary and the account it clears rebuilt as they were from the balance it moved (`CompletedWrite::SelfDestruct::balance`); the applied EIP-7702 authorities and the transaction's own recipient or created account are counted where they are made. + So a transfer to an account already changed adds nothing, one that returns an account takes its record back (its history credited to the caller once the frame's start is kept), a value `CALLCODE` or a call to the calling account itself records nothing, and a start whose value the caller cannot fund is charged nothing. + The sender's own account is part of the transaction body: validation changes it before execution, so no write to it — a frame running as the sender (through an EIP-7702 delegation), value sent back to it — records it again; a fee account is unchanged until execution writes it, which records it. + Records live on the pool of the frame that made them: a success hands them to the caller, a failure takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its pool once the creation returned with the nonce bumped, the creation's share having been taken at the opcode before it, so it survives the creation's failure and is held to the creator's budget, not the creation's. + It is held to the creator's budget and then to the transaction's limit as it is counted, before the creator runs on, which reverts alone if it crossed (`hold_creator`). + The KV count a node reports is the write-record count, which the KV-update limit holds. +- **The byte pool decides.** + A frame's data-size budget is the byte pool on its gas tracker, which the revm fork forwards and settles as it does the reservoir: what the transaction's own execution keeps is drawn there where it is made — a frame start's records and transfer log on the started frame, a completed write and a deposit's code from the Host's hooks — and a frame that fails gives its draws back with its state and history gas. + The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). + The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. + Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. + Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. +- **A start's charge rides on revm's carriers.** + The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. + The history allowance a value call gives its child is the fork's tracker field, set from the schedule's `call_history_allowance`; only a log draws on it. - **The stop.** - A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, the one verdict, which the exemption answers), what it counted goes with its lane, and its caller resumes as after any revert. - There is no latch: a caller that resumes is within every limit, is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and computes past detention's limit only by what halting frames left; a caller that catches the stop and ends lets the transaction succeed. - The frame budget is what keeps a caller's own work within reach of a callee: a child inherits the whole reservoir and history gas draws it first, so gas does not bound what a child appends, and without a budget a callee could take the transaction to its limit and leave the caller that caught its stop nothing to carry on with. - The one stop a frame returns before running another instruction is the one a child left it (`AdditionalLimit::stop_before_run`, `before_frame_run`): a failed creation's nonce record, which lands on its creator unchecked, putting the creator over a limit. - A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender. + A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, for the data size and gas detention's compute stop alike, answering the exemption), what it counted goes with its frame, and its caller resumes as after any revert. + There is no latch: a caller that resumes is within every limit — but where a failure below it put back a record a frame above made while a hint the failed frame sent stays, which stops the caller as it resumes (below) — is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and never computes past detention's limit; a caller that catches the stop and ends lets the transaction succeed. + The frame budget is what keeps a caller's own work within reach of a callee: a child inherits 98/100 of the caller's reservoir and history gas draws it first, so gas does not bound what a child appends, and without a budget a callee could take the transaction to its limit and leave the caller that caught its stop nothing to carry on with; the reservoir the caller keeps, `remaining × 2 / 100`, is what is left of its gas for state and history whatever the child spends. + A child gets 98/100 of the remaining reservoir by the subtraction `remaining − remaining × 2 / 100`, and 98/100 of the parent's remaining data size by `parent_remaining × 98 / 100`, rounded down. + The neutral configuration keeps the whole reservoir and EIP-150's 63/64 forward. + A frame returns a stop before running another instruction in two cases: when its own start crossed a limit once revm built it, which ends the frame in `frame_init` before it runs, returned as an answer is (`end_before_it_runs`); and on a resume, when the nonce record of a creation it made, counted on it as the creation returns, puts it over a limit (`hold_creator`), or a child's failure leaves the transaction over one — the failure restores what the frames kept at the child's start, and an Oracle hint the child sent into room a take-back freed stays (`AdditionalLimit::hold_caller`) — which `frame_return_result` sets on the frame's interpreter for its run to return. + A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender; the history charged before execution for that frame's write record comes back with its start charge at the settlement, whenever the frame did not keep the record. Nothing is rescued for the sender on a stop, because nothing was taken from it: the stop settles on the gas the frames hold, and detention withholds inside a frame's own tracker. A stop of the transaction's own frame reverts what the frames did, the first frame's value and write record included, and nothing pre-execution applied: an admitted EIP-7702 authority keeps its nonce, its delegation, its state gas, its record and that record's history, and a deposit keeps its mint and the caller account it created, as through any failed first frame (`tests/satin/state_growth.rs`). - A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed). + A limit is enforced on the writes it guards before anything runs on them: a frame whose start crosses it returns the stop before its first instruction, or its answer gives way to the stop, and what the start moved goes back with it (a creation keeps its creator's nonce bump, which revm makes before the frame's checkpoint, so a stopped creation transaction cannot be replayed). Nothing counted before the first frame crosses the data-size limit: validation (`MegaHandler::validate_initial_tx_gas`, before any gas check) refuses a transaction whose body, with a 40-byte record for each entry of its authorization list, exceeds it (`AdditionalLimit::admits_tx_body`, `TX_BODY_OVER_DATA_SIZE_LIMIT`, an `InvalidTransaction::Str`), the system-originated exempt; a deposit refused so is a failed deposit, and a pool refuses it through `validate_transaction_stateless` alike. - `record_tx_body` is a pure count, and `record_applied_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`). + The body is a pure count, and `AdditionalLimit::count_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`). A frame revm answers with a success and the engine then rewrites to the stop — gas detention's crossing — has its journal taken back to where its start began, at any depth, as revm takes back a frame that fails (`take_back_a_stopped_answer`): its caller resumes and keeps its own writes, and no caller's revert follows to take the answer's back. - A record is checked before its history is charged, so a record the limit rejects is not charged and the stop is what its frame reports; at a frame start the caller pays at its opcode, before the records are counted, so there an out-of-gas comes first. + A record is checked before its history is charged, so a record the limit rejects is not charged and the stop is what its frame reports; at a frame start the caller pays at its opcode, before revm decides the start and its records are held to the limits, so there an out-of-gas comes first, even for a start revm then refuses. A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted and keeps the body. The layer's state belongs to one transaction: the handler resets it first thing, in `validate_env`, once it knows whether the transaction is the protocol's own, and every system-call entry point of `MegaEvm` resets it before it runs the handler's system-call path. - The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own data-size budget — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none. + The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own budget in data size, KV updates or state growth — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none. `LimitStop::from_result` (and `MegaTransactionOutcome::limit_stop`) reads a stop off the two together, for an RPC's error; `decode_mega_limit_exceeded` reads the bytes alone, which make no stop by themselves. - `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing. + `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes the inspector made of them. - **A per-frame gas cap stays inside the frame's tracker.** - Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame ends (`after_frame_run`). + Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame's run returns (`frame_run_result`). A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges. - **Synthetic frame results carry the caller's pools.** - A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`). -- **The admission gate.** - A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses — as an internal error, since the inspector is the node's choice and no verdict on the block — and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds. - alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type: block execution checks it wherever an outcome is produced or chosen — the pre-block changes, a transaction's execution, the end of the block and `commit_transaction_outcome`, the checked commit — because an inspector can be enabled after the block was set up and a caller can run transactions without setting it up. - alloy-evm's `commit_transaction` checks nothing and needs no check: it cannot fail, runs no code, and commits the outcome the last execution produced under the gate, which no inspector enabled since can reach. - `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route. - In a block a declared observer sees the transactions, user and system alike, and nothing else: the pre-block calls run on the handler's plain system-call path, as alloy-evm's `transact_system_call` runs one, and the end of the block runs no code; the module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase. - No rewrite is refused: a failed creation an inspector turns into a success settles as a frame that kept nothing, like a call it revives (below), and its caller is handed the address the inspector gave. - A creation stopped by a limit is a failed creation like any other, and is settled the same way if revived. + A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir and byte share (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags and start charge, so revm's own frame return settles it exactly like a result of its own. +- **Inspectors in block execution.** + Block execution admits any inspector: which inspectors may run on block production is a node's decision, not the engine's. + A block builds from an EVM the node made with `MegaEvmFactory::create_evm_with_inspector` (or `MegaEvm::with_inspector`) and `MegaBlockExecutorFactory::create_executor` (or `MegaBlockExecutor::new`). + An inspector sees the transactions, user and system alike, and nothing else: the pre-block calls run on the handler's plain system-call path, as alloy-evm's `transact_system_call` runs one, and the end of the block runs no code; the `evm` module doc holds what an inspector sees and may rewrite. + `test_utils::ReadOnlyObserver` wraps an inspector that is meant to write nothing back and proves it in debug builds, for tests. + No rewrite is refused, and none is corrected: the engine takes a rewritten result as given (below). The test utilities' inspectors are not declared. -- **A frame that kept nothing settles as one, whatever an inspector made of its result.** - A frame an inspector answered in place of running never started, and a frame that failed had its journal checkpoint reverted before the inspector saw its result. - Whatever the inspector hands the caller for either, the caller gets the success, the output and the regular gas it chose, and nothing else (`settle_kept_nothing` in `evm/inspector.rs`): no state or history gas and no refund, no write record — the lane is discarded as a failure's, and the history its caller paid for the records comes back — and the upfront state gas its caller's opcode was charged for an account the frame did not add comes back — for a call, as recorded before the inspector's hooks ran, so a rewritten target does not change the price it comes back at — as does, for the transaction's own frame, the history of its write record. - So Foundry's `expectRevert` on a call that wrote and reverted bills the transaction as the revert does. - The reverse holds too: a success an inspector rewrites into a failure has its journal taken back to the frame's checkpoint — for a start revm answered without building a frame, to where the start began — as revm takes back a frame that fails, so the state follows the failure its ledgers settle as (`ResultSource` and `revert_journal_to` in `evm/inspector.rs`); a creation keeps its creator's nonce bump, which revm makes before the checkpoint, and the journal's depth is left as it was. - Everything journaled since the checkpoint goes, what the inspector wrote to the journal in the callback that rewrote the result included: the one place the rewrite and a real failure part, since revm takes a failed frame back before `call_end`. +- **A rewritten result is taken as given, as revm takes it.** + revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's result, and the caller settles the result the inspector hands back, its classification, output and gas, reservoir and byte pool included; the engine adds nothing to that settlement. + A failed frame revived into a success — Foundry's `expectRevert` on a call that wrote and reverted — keeps its journal reverted and settles as a success: its state gas, history, refund and the records it counted merge into its caller, and the upfront charge its caller's opcode made stays. + A success rewritten into a failure keeps its journal, the inspector's own writes in that callback included, and settles as a failure: its charges roll back, its counts are restored with its start's entry and its start charge is refunded. + A frame an inspector answers in place of running never started: what its caller's opcode was charged for it — the upfront state gas and the history of its start's records — stays charged unless the answer carries the upfront-charge flags and the start charge back; a creation's creator record is not counted, revm having bumped no nonce, and its history stays charged; and the answer settles on the gas it is built on. + So a tool's state and its ledgers can part under a rewrite, as they do under revm; keeping them consistent is the tool's business, and block execution runs no rewriting inspector the node did not choose. + The write records and transfer logs the transaction reports follow the result its caller settles, as the byte pool does (`AdditionalLimit::close_start`). - **An inspector's writes to gas.** Gas an inspector writes in the `step_end` of a frame's last instruction reaches nobody: the instruction copied the frame's gas into its result; the result's gas, rewritten in `call_end`, is what the caller merges, reservoir included. - An answer is the exception: the frame it stands for never ran, so it carries nothing but the regular gas the inspector chose, and its caller merges back the reservoir it forwarded whatever `Gas` the answer was built on — `Gas::new(limit)`, which Foundry answers every cheatcode on, carries none, and Foundry's default gas limit of 2^30 is above the execution cap. - A charge the frame cannot pay is refused and takes nothing, and the frame runs on; revm's instruction loop sees the inspector through `StepGuard`, which puts back the withheld-part crossing such a refusal records, so gas detention never stops a frame for an inspector's charge. + An answer settles on the `Gas` it is built on: `Gas::new(limit)`, which Foundry answers every cheatcode on, carries no reservoir and unlimited pools, so above the execution cap — Foundry's default gas limit of 2^30 is above it — the caller is left only the 2 per cent of its reservoir it kept when it handed the call its share, as the fork's add-settlement has it. + A charge the frame cannot pay is refused and takes nothing, and the frame runs on, with the record of the refused charge left on its gas, as revm leaves it: a withheld-part crossing stops nothing in a frame that ends without an out-of-gas, and a later halt that records nothing of its own is read off the failed-charge record. An inspector that overwrites the interpreter's gas (Foundry's `pauseGasMetering` restores a snapshot before every instruction) overwrites detention's split with it, and the frame runs on the snapshot's split until detention next holds it: at a read, a start or resume, or after an `SSTORE`. - **The interceptor dispatch.** Its order is the scheme guard, the address, the selector, then the method's value policy, each step cheaper than the next: `CALLCODE` and `DELEGATECALL` never reach an interceptor, because they run the callee's code in the caller's context; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes; the selector is peeked without materialising the calldata behind it, and is admitted on its four bytes alone, trailing bytes and all. @@ -443,6 +508,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer `Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced. A charge is given back two ways, and neither reads a second table: `SSTORE`'s own restore, a caller's upfront charge for a call or creation that did not add the leaf, the transaction-level refund and the settlement of a synthetic frame result re-price the same `(id, site)` pair through the hook; a frame that fails rolls its own charges back by the amounts it recorded while running, without asking for a price at all. Both cancel the charge exactly whatever the price was — the re-priced sites because a bucket's multiplier is read once per transaction, so the two cannot disagree even if the environment's answer would, and the rolled-back amounts because nothing but the hook priced them. + The one exception is an inspector's: revm reads the account a call's upfront charge is given back for off the frame's inputs, so an inspector that rewrites a call's target has the charge given back at the new target's price, as under revm (`tests/satin/inspector_settlement.rs`). + A charge on an account created in the transaction and destroyed since prices at nothing: its destruction gave back what the transaction had charged for it, at the prices charged and outside that rule (`MegaContext::priced_state_gas`), so a re-pricing after the mark — the restore of a slot it gave back — gives back nothing a second time. A mechanism that adds a state charge adds a `StateGasCharge` at the site the state lands on; it must not price the charge itself. - **Three ledgers, and the bytes beside the third.** `MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger. @@ -453,14 +520,15 @@ Every later mechanism plugs into these; a change to one comes back to this layer It is the history the schedule prices, not the chain's physical growth: an exempt transaction's bytes are not in it, and a body counts its five fixed write records even when fewer fee accounts are written. For a transaction that pays history it is the data size the transaction kept less its Oracle hints' payloads and its transfer logs: both columns read one count at every site, deployed code included, which the data-size limit makes before the creation commits and only for code revm deposits. `gas_used` is the receipt's figure; `BlockGasCounters` sums the three ledgers and the history bytes per block. + `reservoir_remaining` is what the EIP-8037 reservoir held where revm built the result's gas, before the EIP-7623 floor absorbs it; revm's `ResultGas` does not carry it, so the handler reads it and the layer reports it (`AdditionalLimit::reservoir_remaining`), for a system call too. ## Test Organization (`crates/mega-evm/tests/`) - `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`). -- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters, the factory and the admission gate; under `block/witness/`, the witness-replay harness: a block executed on a recorder of every read, then again on a strict database and environments that serve exactly a witness — the record of every read, and the witness a node builds from the states the block committed (the pre-block steps' and the included transactions') and the exports — each replay held to the recording, one case per mechanism that reads and per read that gas or a limit skips. +- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters and the factory; under `block/witness/`, the witness-replay harness: a block executed on a recorder of every read, then again on a strict database and environments that serve exactly a witness — the record of every read, and the witness a node builds from the states the block committed (the pre-block steps' and the included transactions') and the exports — each replay held to the recording, one case per mechanism that reads and per read that gas or a limit skips. - `system/` — tests of the system contracts: the interceptor dispatch, what each contract answers, keyless deployment (`system/keyless/`) and the system-address transaction. - `fuzz/` — randomized tests: properties the engine must hold on any input, and the neutral differential against op-revm and revm's mainnet EVM (see Randomized tests below). -- `shared/` — no target: `snapshot.rs` holds `assert_sorted_json_snapshot!`, which every target includes with `#[path = "../shared/snapshot.rs"] mod snapshot;`. +- `shared/` — no target: `snapshot.rs` holds `assert_sorted_json_snapshot!`, which every target includes with `#[path = "../shared/snapshot.rs"] mod snapshot;`, and `op_reference.rs` the op-revm reference the baselines compare with, op-revm's handler with Satin's system-call split and the reservoir its result settled with, which the `satin` and `block` targets include the same way. It has no `main.rs`, so Cargo builds nothing there; the snapshot files live in `snapshots/` beside the file that asserts. - Unit tests live next to the code in `#[cfg(test)] mod tests`. @@ -490,12 +558,13 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te - **A failure is reproducible.** The runner panics with the property's name, the reason, the seed and case count that reproduce the run, and the case proptest shrank to within its shrink limits (two minutes and 4,096 steps, so not always the minimal one), rendered as the generator types (`Case`, `BlockCase`), from which a regression test is written by hand into `regressions.rs`. - **The generators** (`gen/`) build a `Case`: a `World` (four fixed accounts, a beneficiary that may be one of them, a delegation, SALT capacities with multipliers above one and a failing bucket, the Oracle's answers, runtime limits in place of the spec's, the block), a `Tx` of one of six shapes (call, creation, EIP-7702, deposit, system-address, keyless) at five gas tiers, and the `Program`s of the three contracts, lists of self-contained ops biased towards what the engine meters. + A call, an account read or a `SELFDESTRUCT` may name the address one of the program's own `CREATE2` ops lands on (`Target::Created`), so a program can fund or pay an account before it creates it. A keyless deployment carries its own world: the signer's funds, nonce and code, what the deploy address holds, how the carried transaction is encoded and what it is signed for, so that each of its rules is reached. The keyless property also pads one init code in eight with zero bytes, which never run, to the initcode size limit, one byte past it or twice it; the other properties draw init code at its own size, since a mebibyte of calldata in their cases would buy nothing they check. The weights keep what refuses a transaction before it runs rare — about one case in five — because most properties have nothing to check of a refusal. `Case::execute` runs it on a fresh EVM; `blocks.rs` runs envelopes through `MegaBlockExecutor`. `Flavor::Neutral` replaces what only `MegaETH` has by its plain counterpart, for the differential, and `Case::without_destruction_in_creation` takes every self-destruction out of init code for the one comparison that settles it otherwise, Ethereum's on Amsterdam. -- **What the properties state** (`properties.rs`, `keyless.rs`, `blocks.rs`, `differential.rs`): the same outcome twice, under a recording inspector, and on an EVM that already ran another transaction, one that ended in an error included; the gas ledgers, the reservoir exactly; `KV × 40 ≤ data size` after every instruction, and every transaction keeps its body and the hints it forwarded; what a stop keeps; a keyless deployment's rules in the spec's order, its answer and its signer's nonce; a block's counters as the sum of what its transactions report, and its budgets; the neutral differential. +- **What the properties state** (`properties.rs`, `keyless.rs`, `blocks.rs`, `differential.rs`): the same outcome twice, under a recording inspector, and on an EVM that already ran another transaction, one that ended in an error included; the gas ledgers, the reservoir exactly; `KV × 40 ≤ data size` after every instruction, and every transaction keeps its body and the hints it forwarded; the write-record count as the net change of the state, computed from the case's pre-state and the outcome's state with the settlement's fee credits taken out; what a stop keeps; a keyless deployment's rules in the spec's order, its answer and its signer's nonce; a block's counters as the sum of what its transactions report, and its budgets; the neutral differential. A panic fails whichever property draws the case. Several print a tally of what they reached (`--nocapture`): how the previous transaction ended, each keyless rule, the cases rewritten for Amsterdam. - **To add a property**, write a `#[test]` that calls `harness::check(name, bounded_cases, || case(Flavor::Satin), |case| { ... })` and returns `Err` through `prop_eq!` / `prop_check!` where the outcome breaks the property; keep the bounded case count such that the whole target stays under a minute in debug. @@ -513,6 +582,9 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te - **The op-revm baseline** (`tests/satin/equivalence.rs`): an ordinary transaction through `MegaEvm` against op-revm on the same configuration, which Satin differs from by its history ledger alone. - **The execution-spec gate** (`crates/mega-state-test`, `.github/workflows/exec-spec-satin.yml`): Ethereum's state-test fixtures through `MegaEvm`, on the fixture releases the fork's own runner (`.github/workflows/exec-spec.yml`) uses. - Equivalence mode is the gate: Satin's machinery — handler, frame lifecycle, Host, instruction table — priced as the fixture's fork prices it, through the neutral configuration (`MegaContext::with_neutral_cfg`, `test_utils::{neutral_cfg, neutralize_evm}`), which exists only behind `test-utils`, and held to no runtime limit (`EvmTxRuntimeLimits::no_limits()`, installed by the runner itself). + The neutral configuration keeps EIP-150's 63/64 forward and gives a child the whole reservoir. + `no_limits()` is the separate switch that turns the per-transaction limits off. + The counts it reports (`LimitUsage`: data size, write records, state growth) are the engine's own, by Satin's rules, and no fixture checks them: the neutral configuration prices what the fixture's fork prices and counts what Satin counts, the destruction table's give-backs included, so a change to a counting rule moves an equivalence-mode transaction's whole-outcome digest in `usage` alone, which is that change's and is no deviation. Every failure must be explained by a deviation in `crates/mega-state-test/src/deviations.rs`, with its rule, its reason and the exact entries it explains, each with the hashes Satin produces, and every listed entry must fail exactly as listed; the executed and skipped counts are pinned in the workflow and equal the fork runner's. - Satin mode is a report: the same fixtures under Satin's own configuration, counted by outcome in the step summary; it never fails the job. - The blockchain tests are a gate too (`state-test btest`, `crates/mega-state-test/src/blockchain/`): the main release's Osaka `blockchain_tests`, imported block by block through `MegaBlockExecutor` on `MegaEvm` in equivalence mode's configuration, held to no limit (`ProtocolLimits::no_limits()`, installed by the runner through the executor's test-and-tool override), as the state-test runner holds a transaction. @@ -601,7 +673,7 @@ When the agent is requested to implement a new feature or bug fix, it should con - **Keep the op-revm baseline honest.** A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed. - **Hold a test at any byte price.** - A gas limit is regular room on top of what the scenario adds at the prices in effect (`satin_gas_params()`, `history_gas`), never a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for. + A gas limit is regular room on top of what the scenario adds at the prices in effect (`satin_gas_params()`, `history_gas`), never a number that happened to cover it at the constants; a call or creation that forwards all but 2 per cent of its gas keeps a fiftieth of what it held, so it must hold 50 times the history of the records it pays for (`common::holding_to_keep` inverts the split). A charge a scenario must not be able to pay is derived the same way — a gas limit one short of it — not a number that is short of it only while a byte is dear. A test that pins the spec's own numbers returns early at other prices (`runs_at_measurement_prices`); run `scripts/price_grid.sh --pr` before committing a test change. - **Pin only outputs with no computable expectation.** diff --git a/Cargo.lock b/Cargo.lock index b50a95875..869ba3e17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2384,7 +2384,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2514,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3316,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3917,7 +3917,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]] @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.3#58bc98e2fcaffcdea23595b2680fc68daddd7b69" +source = "git+https://github.com/megaeth-labs/op-revm?rev=f599efdabc3e5b36a280f1aa72978751bd64c160#f599efdabc3e5b36a280f1aa72978751bd64c160" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec" +source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" dependencies = [ "alloy-eip7928 0.4.11", "k256", @@ -5764,7 +5764,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6429,7 +6429,7 @@ dependencies = [ "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6985,7 +6985,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ae3ba2ae5..319b4d467 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built -# against the revm tag above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.3" } +# against the revm pin above. +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "f599efdabc3e5b36a280f1aa72978751bd64c160" } diff --git a/REVIEW.md b/REVIEW.md index 8451aeeb4..d04b1ce12 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -24,27 +24,28 @@ Defer to the baseline for everything not listed here; the rules below take prece - Pre-block helpers (the activation block's predeploy check, pre-block system calls, the registry's due-change read, the L1 block info read) return their state (an `EvmState`, or a `ResultAndState` for a system call) for the block executor to commit on its own, in order; they never call `db.commit(...)`. An idempotent "no change" path returns an `EvmState` that carries the observed account as a read-only entry; returning nothing drops the account from the stateless witness read set and produces an incomplete proof. The same applies inside execution: read through the journal with revm's own loads (`load_account`, `sload`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state. -- **The Host only observes; the opcode's wrapper commits.** - `sstore`, `log` and `selfdestruct` stage a record and record nothing; the wrapper commits it after the opcode completed and discards it if the opcode failed. +- **A write is counted once its opcode completed.** + The Host's `sstore`, `log` and `selfdestruct` only write and count nothing; revm's write instructions call the completed-write hook (`Host::write_completed`) after every charge they make, and the frame-starting instructions call the frame-start hook (`Host::frame_starting`) after the forward and before the frame's input is built. A record, a charge or a read mark made before the opcode can still fail counts a write that never happened. - Check that every exit path of a wrapped instruction (stack underflow, out of gas, decode failure, a failed inner call) leaves the staged record discarded and nothing counted. + The frame-start hook only prices: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and none is given back. + Check that nothing is counted in the Host's write methods, that no charge lands in a write instruction after the hook (the fork's call sites), and that the engine's matches over `CompletedWrite` and `FrameStartKind` carry no wildcard arm. - **A limit is enforced before the write it guards.** - A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop. + A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit, unless the failure put back a record a frame above made while an Oracle hint the failed frame sent stays, when the caller returns the transaction's stop as it resumes; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop. Flag a stop that surfaces as a halt, a limit that is checked after the state change it guards, a stopped frame whose writes, logs or counted bytes survive into its caller, and an answer the engine turns into the stop whose journal is not taken back. The outcome's `limit_exceeded`, not the output bytes, tells a stop from a contract that reverts with the same bytes. -- **Lanes, pools and ledgers stay aligned with frames.** - `frame_init` pushes one lane per frame result revm returns, including a frame answered without running; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`. - A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at. +- **Pools and ledgers stay aligned with frames.** + A frame's byte pool is on its gas tracker and settles with it; `frame_init` opens one entry per start revm decided (`AdditionalLimit::open_start`), which the result returning at that depth closes (`close_start`), and a start revm did not decide opens none; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`. + A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at, unless an inspector rewrote the call's target, which revm reads the refund's account off. The three ledgers (regular, state, history) add up to the raw spend, and the block counts `max(regular, floor)` with history taken out first. - **Gas detention caps a frame inside the frame's own tracker.** It withholds a part of the frame's regular gas (`Gas::limit_spendable`) that every reader but a regular charge counts, so there is nothing to move or release; a mechanism that caps a frame's gas uses the same part, holds the frame at its start and after every credit, and never releases a creating frame's withheld part before `return_create`. A read of volatile data is marked where the Host loads the value and committed by the opcode's wrapper once the opcode completed; a new volatile-derived read or side effect (the block environment, the beneficiary's account through any account opcode, the Oracle's storage, an EIP-7702 delegate) has to be marked, and the delegate resolved before marking. Flag a bound or an economic claim in a comment or the spec that the code does not meet. - **Keyless deployment is a native creation.** - The `keylessDeploy` call's frame runs no code and makes its actions by hand; check that the creation's outcome returns into the call through `frame_return_result`, that every effect (gas, the data-size lane, volatile access, logs, state) is reconciled in the one frame stack, that the signer's nonce rule holds on success and on failure, and that a value validated before execution (a gas-limit override) is not mutated afterwards. + The `keylessDeploy` call's frame runs no code and makes its actions by hand; check that the creation's outcome returns into the call through `frame_return_result`, that every effect (gas, the data-size pool, volatile access, logs, state) is reconciled in the one frame stack, that the signer's nonce rule holds on success and on failure, and that a value validated before execution (a gas-limit override) is not mutated afterwards. - **The interceptor dispatch is ordered cheapest-first and fails closed.** The call-scheme guard, then the address, then the selector, then the method's value policy; only `CALL` and `STATICCALL` reach an interceptor; an unknown selector is not intercepted and falls through to the contract's bytecode; a method that takes no value answers a value-bearing call with its error. -- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits and history gas, priced at the minimum SALT bucket and not detained; a pre-block call with dynamic cost takes a `block.gas_limit`-derived budget; a database error the database calls fatal is an internal error and any other failure refuses the block with the call's own validation error; a system-address transaction validates nonce, chain id and EIP-3607 against replay, and a commit step that re-checks block limits re-checks the sender's nonce and balance too. +- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits and history gas, priced at the minimum SALT bucket and not detained; a pre-block call runs on the one pre-block budget (`constants::PRE_BLOCK_CALL_GAS_LIMIT`), whatever the block's gas limit; a database error the database calls fatal is an internal error and any other failure refuses the block with the call's own validation error; a system-address transaction validates nonce, chain id and EIP-3607 against replay, and a commit step that re-checks block limits re-checks the sender's nonce and balance too. - **The stateless witness must hold every read.** A change that makes block execution read state outside a transaction's journal commits the read as a read-only entry of a pre-block state or exports it, and adds a witness-replay case; nothing may depend on which source (the database, the SALT environment, the oracle service) answered. - **Hot-path accounting stays O(1)** in attacker-controlled call depth and authorization count — no frame-stack walk per opcode, no unindexed `Vec` scan per authorization. @@ -77,7 +78,7 @@ Defer to the baseline for everything not listed here; the rules below take prece Flag a new state-gas assertion that lacks it: the failure only shows in the configuration nobody watches. - Every other test holds at a byte price of nothing and at any price from one gas per byte up to the grid's dearest point, and the byte-price grid job checks it. Below one gas per byte the schedule's entries round to nothing one at a time, and past the grid a fixed-size scenario outgrows any transaction below the execution cap; no test is held there. - A gas limit is its regular room on top of what the scenario adds at the prices in effect, read off the schedule and `history_gas`, not a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for. + A gas limit is its regular room on top of what the scenario adds at the prices in effect, read off the schedule and `history_gas`, not a number that happened to cover it at the constants; a call or creation that forwards all but 2 per cent of its gas keeps a fiftieth of it, so it must hold 50 times the history of the records it pays for. A case whose scenario is state or history gas — a limit to cross, a bucket to scale, a charge that cannot be paid — returns early where that byte costs nothing (`state_is_free`, `history_is_free` in each test target's `common.rs`), and its other assertions still run. - **Benchmark methodology.** A perf-comparison PR must pin comparable hardforks on both arms. diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md index 780505a48..96d1408c1 100644 --- a/bin/mega-evme/AGENTS.md +++ b/bin/mega-evme/AGENTS.md @@ -14,6 +14,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6` - `src/tx/`: full transaction execution command with raw-tx override support. - `src/replay/`: RPC-backed historical transaction replay through block executor (Satin; a legacy spec is the 1.7.1 CLI's). - `src/block/`: `replay --block`, whole blocks on either engine compared with the chain: inputs and the block cache (`inputs.rs`), the parent state in plain data (`state.rs`), one executor per engine exchanging only plain data (`satin.rs`, `legacy.rs`), the plain data both hand back (`exec.rs`), records and the comparison (`record.rs`), the driver (`cmd.rs`). +- `tests/fixtures/blocks.tar.xz`: the three recorded Rex6 blocks and their code store in the block cache layout, one deterministic archive extracted once per test binary (`tests/common/mod.rs`); `scripts/pack_blocks_fixture.py ` repacks it, `--check` requires a repack of the committed archive to be byte-identical. - `tests/satin-differences.md`: the pinned differences between the engines, rendered by `tests/differences.rs` (`UPDATE_EVME_DIFFERENCES=1` rewrites it). ## KEY PATTERNS diff --git a/bin/mega-evme/Cargo.toml b/bin/mega-evme/Cargo.toml index ebdf0760f..13ec51fe6 100644 --- a/bin/mega-evme/Cargo.toml +++ b/bin/mega-evme/Cargo.toml @@ -9,6 +9,8 @@ repository.workspace = true description = "MegaETH executable EVM" readme = "README.md" default-run = "mega-evme" +# Test data and the scripts that pack it stay out of the published crate. +exclude = ["scripts/", "tests/fixtures/"] [lints] workspace = true diff --git a/bin/mega-evme/scripts/pack_blocks_fixture.py b/bin/mega-evme/scripts/pack_blocks_fixture.py new file mode 100644 index 000000000..6c16ae049 --- /dev/null +++ b/bin/mega-evme/scripts/pack_blocks_fixture.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Pack a block cache tree into the deterministic `tests/fixtures/blocks.tar.xz`. + +Usage: scripts/pack_blocks_fixture.py [] + +`` holds `blocks/` and `codes/`. +Members are regular files only, in sorted path order, in ustar with mode 0644, uid/gid 0, empty +owner names and mtime 0; the tar is compressed with xz preset 9 extreme, single-threaded. +Packing the same files therefore always gives the same bytes. +`--check ` unpacks nothing: it repacks the archive's own members and requires the same bytes. +""" +import io +import lzma +import sys +import tarfile +from pathlib import Path + +DEFAULT_ARCHIVE = Path(__file__).resolve().parent.parent / "tests/fixtures/blocks.tar.xz" + + +def pack(members): + """members: sorted list of (relative posix path, bytes).""" + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w", format=tarfile.USTAR_FORMAT) as tar: + for name, data in members: + info = tarfile.TarInfo(name) + info.size = len(data) + info.mode = 0o644 + info.uid = info.gid = 0 + info.uname = info.gname = "" + info.mtime = 0 + tar.addfile(info, io.BytesIO(data)) + filters = [{"id": lzma.FILTER_LZMA2, "preset": 9 | lzma.PRESET_EXTREME}] + return lzma.compress(raw.getvalue(), format=lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, filters=filters) + + +def main(): + args = sys.argv[1:] + if args and args[0] == "--check": + archive = Path(args[1] if len(args) > 1 else DEFAULT_ARCHIVE) + with tarfile.open(archive, "r:xz") as tar: + members = [(m.name, tar.extractfile(m).read()) for m in tar.getmembers() if m.isfile()] + if pack(members) != archive.read_bytes(): + sys.exit(f"{archive}: a repack of its members differs") + print(f"{archive}: repack is byte-identical") + return + root = Path(args[0]) + out = Path(args[1]) if len(args) > 1 else DEFAULT_ARCHIVE + files = sorted(p for p in root.rglob("*") if p.is_file()) + members = [(p.relative_to(root).as_posix(), p.read_bytes()) for p in files] + out.write_bytes(pack(members)) + print(f"{out}: {len(members)} members, {out.stat().st_size} bytes") + + +main() diff --git a/bin/mega-evme/src/block/record.rs b/bin/mega-evme/src/block/record.rs index 7c1dde2bb..31cc673d8 100644 --- a/bin/mega-evme/src/block/record.rs +++ b/bin/mega-evme/src/block/record.rs @@ -215,6 +215,7 @@ fn sum_satin<'a>(reports: impl Iterator) -> SatinReport floor_gas: acc.floor_gas + r.floor_gas, data_size: acc.data_size + r.data_size, write_records: acc.write_records + r.write_records, + state_growth: acc.state_growth + r.state_growth, limit_exceeded: None, limits_override: None, }) diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs index 3e2eb3159..9917d2a9d 100644 --- a/bin/mega-evme/src/block/satin.rs +++ b/bin/mega-evme/src/block/satin.rs @@ -4,16 +4,15 @@ use alloy_consensus::transaction::Recovered; use alloy_eips::{Decodable2718, Encodable2718}; use alloy_primitives::U256; use mega_evm::{ - alloy_evm::{block::BlockExecutor, EvmEnv}, + alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}, alloy_op_evm::block::OpAlloyReceiptBuilder, revm::{ context::{result::ExecutionResult, BlockEnv, CfgEnv}, database::State, - inspector::NoOpInspector, primitives::eip4844, }, - BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, - MegaHardforkConfig, MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits, }; use super::{ @@ -68,11 +67,7 @@ pub(super) fn execute( for &(bucket, capacity) in bucket_capacities { envs = envs.with_bucket_capacity(bucket, capacity); } - let factory = MegaBlockExecutorFactory::new( - OpAlloyReceiptBuilder::default(), - &hardforks, - MegaEvmFactory::new().with_external_env_factory(envs), - ); + let evm_factory = MegaEvmFactory::new().with_external_env_factory(envs); let only_deposits = admits_only_deposits(&hardforks, header.number, parent_timestamp, header.timestamp)?; // Without the parent's timestamp the block admits every transaction only where no fork the @@ -90,12 +85,9 @@ pub(super) fn execute( let result = { let mut db = State::builder().with_database(SatinDb(state)).with_bundle_update().build(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut db, - EvmEnv::new(cfg, block_env), - block_ctx, - NoOpInspector, - ); + let evm = evm_factory.create_evm(&mut db, EvmEnv::new(cfg, block_env)); + let mut executor = + MegaBlockExecutor::new(evm, block_ctx, &hardforks, OpAlloyReceiptBuilder::default()); if let Some(limits) = limits_override { executor = executor.with_protocol_limits(limits); } diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs index 942cbfe83..bb9f78360 100644 --- a/bin/mega-evme/src/common/outcome.rs +++ b/bin/mega-evme/src/common/outcome.rs @@ -60,8 +60,11 @@ pub struct SatinReport { pub data_size: u64, /// Account and storage write records the transaction kept: its KV count. pub write_records: u64, + /// New accounts and new storage slots the transaction kept, net: its state growth. + pub state_growth: u64, /// The limit that stopped the transaction, if one did: the crossing that produced the result - /// of its own frame, a transaction-level limit or that frame's own data-size budget. + /// of its own frame, a transaction-level limit or that frame's own budget in data size, KV + /// updates or state growth. pub limit_exceeded: Option, /// The protocol limits the run was held to, in the shape `--override.limits` takes them; /// present only when that flag replaced the schedule's, so the record of a counterfactual @@ -73,7 +76,7 @@ pub struct SatinReport { /// A limit that stopped a Satin transaction. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct LimitStop { - /// The dimension: `data_size` or `compute_gas`. + /// The dimension: `data_size`, `kv_updates`, `compute_gas` or `state_growth`. pub kind: &'static str, /// The limit crossed, in the dimension's unit. pub limit: u64, @@ -94,6 +97,7 @@ impl SatinReport { floor_gas: gas.floor, data_size: outcome.usage.data_size, write_records: outcome.usage.write_records, + state_growth: outcome.usage.state_growth, limit_exceeded: match outcome.limit_exceeded { Some(LimitCheck::ExceedsLimit { kind, limit, used, .. }) => { Some(LimitStop { kind: limit_kind_name(kind), limit, used }) @@ -109,7 +113,9 @@ impl SatinReport { pub const fn limit_kind_name(kind: LimitKind) -> &'static str { match kind { LimitKind::DataSize => "data_size", + LimitKind::KvUpdate => "kv_updates", LimitKind::ComputeGas => "compute_gas", + LimitKind::StateGrowth => "state_growth", } } @@ -253,6 +259,7 @@ pub fn print_satin_report(report: &SatinReport) { println!("Floor Gas: {}", report.floor_gas); println!("Data Size: {}", report.data_size); println!("Write Records: {}", report.write_records); + println!("State Growth: {}", report.state_growth); if let Some(stop) = report.limit_exceeded { println!("Limit Exceeded: {} (limit {}, used {})", stop.kind, stop.limit, stop.used); } diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs index 032b47bff..b2256685e 100644 --- a/bin/mega-evme/src/replay/cmd.rs +++ b/bin/mega-evme/src/replay/cmd.rs @@ -8,7 +8,7 @@ use clap::Parser; use mega_evm::{ alloy_evm::{ block::{BlockExecutionError, BlockExecutor}, - Evm, EvmEnv, + Evm, EvmEnv, EvmFactory, }, alloy_op_evm::block::OpAlloyReceiptBuilder, revm::{ @@ -19,8 +19,8 @@ use mega_evm::{ primitives::{eip4844, Address, Log}, DatabaseRef, Inspector, }, - BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory, - MegaHardforks, MegaSpecId, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforks, + MegaSpecId, }; use tracing::{debug, info, trace, warn}; @@ -443,11 +443,6 @@ impl Cmd { let evm_env = EvmEnv::new(cfg_env, block_env); let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs); - let block_executor_factory = MegaBlockExecutorFactory::new( - OpAlloyReceiptBuilder::default(), - &hardforks, - evm_factory, - ); // The block is held to Satin's protocol limits, or the override's, with no building // policy, as a validator holds it; the block's gas limit comes from its header. Whether // it admits only deposits comes from the schedule and the parent block's timestamp, as a @@ -465,18 +460,14 @@ impl Cmd { .with_satin_activation_block(activates_satin); let start = Instant::now(); - // The tracer reads and writes nothing back, so block execution admits it declared. - // It is attached only for `--trace`: otherwise preceding transactions would be recorded - // and then discarded. - let mut inspector = DeclaredObserver::new(ReplayTracer::from_args(&self.trace_args)); + // The tracer is attached only for `--trace`: otherwise preceding transactions would be + // recorded and then discarded. + let mut inspector = ReplayTracer::from_args(&self.trace_args); let mut state = StateBuilder::new().with_database(&mut database).with_bundle_update().build(); - let mut block_executor = block_executor_factory.create_executor_with_trusted_inspector( - &mut state, - evm_env, - block_ctx, - &mut inspector, - ); + let evm = evm_factory.create_evm_with_inspector(&mut state, evm_env, &mut inspector); + let mut block_executor = + MegaBlockExecutor::new(evm, block_ctx, &hardforks, OpAlloyReceiptBuilder::default()); if let Some(limits) = limits_override { block_executor = block_executor.with_protocol_limits(limits); } @@ -541,7 +532,7 @@ impl Cmd { .unwrap_or(0); // The trace covers the target transaction only. - if let ReplayTracer::On(tracer) = &mut block_executor.evm_mut().inspector_mut().0 { + if let ReplayTracer::On(tracer) = block_executor.evm_mut().inspector_mut() { tracer.fuse(); } let outcome = block_executor @@ -570,7 +561,7 @@ impl Cmd { state: evm_state.clone(), }; - let trace_data = match &block_executor.inspector().0 { + let trace_data = match block_executor.inspector() { ReplayTracer::On(tracer) => Some(self.trace_args.generate_trace( tracer, &result_and_state, diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs index 1fd09502f..ec3a4c4da 100644 --- a/bin/mega-evme/tests/block_replay.rs +++ b/bin/mega-evme/tests/block_replay.rs @@ -1,5 +1,5 @@ //! `mega-evme replay --block`: whole blocks on either engine, compared with the chain, on the -//! recorded mainnet blocks of `tests/fixtures/blocks` (see `common/blocks.rs`). +//! recorded mainnet blocks of `tests/fixtures/blocks.tar.xz` (see `common/blocks.rs`). #![cfg(feature = "legacy")] mod common; @@ -33,6 +33,38 @@ fn replay(number: u64, dir: &Path, extra: &[&str]) -> common::blocks::Run { run_evme(&args) } +/// Extractions of the fixture archive racing into one directory all succeed and leave every +/// member in place, as test processes that start at once on a cold run extract it. +#[test] +fn test_racing_extractions_of_the_fixture_archive_all_succeed() { + const WRITERS: usize = 8; + let archive = common::fixtures_dir().join("blocks.tar.xz"); + let destination = common::extracted_root().join(format!(".race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&destination); + let barrier = std::sync::Barrier::new(WRITERS); + std::thread::scope(|scope| { + for _ in 0..WRITERS { + scope.spawn(|| { + barrier.wait(); + common::install_archive(&archive, &destination); + }); + } + }); + let listing = std::process::Command::new("tar").arg("-tJf").arg(&archive).output().unwrap(); + assert!(listing.status.success()); + let members: Vec = String::from_utf8(listing.stdout) + .unwrap() + .lines() + .filter(|member| !member.ends_with('/')) + .map(str::to_string) + .collect(); + assert!(!members.is_empty()); + for member in &members { + assert!(destination.join(member).is_file(), "{member} is in place"); + } + std::fs::remove_dir_all(&destination).unwrap(); +} + /// The legacy leg replays each recorded block exactly as the chain executed it: every /// transaction's status, gas used, cumulative gas used and logs, and the receipts root. /// Offline, a replay writes nothing to the cache. @@ -268,10 +300,13 @@ fn test_an_override_replays_a_satin_block_under_other_limits() { assert!(reason.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{reason}"); continue; } + // The frame that crosses the transaction's limit crosses its own budget, a share of + // what the limit leaves, which the stop names with what that frame used of it. let stop = &tx["satin"]["limit_exceeded"]; assert_eq!(stop["kind"], "data_size", "{tx}"); - assert_eq!(stop["limit"], limit, "{tx}"); - assert!(stop["used"].as_u64().unwrap() > limit, "{tx}"); + let budget = stop["limit"].as_u64().unwrap(); + assert!(budget <= limit, "{tx}"); + assert!(stop["used"].as_u64().unwrap() > budget, "{tx}"); } } assert!(protocols > 0 && others > 0, "{protocols} {others}"); diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs index 6c4e012df..666ba0500 100644 --- a/bin/mega-evme/tests/common/blocks.rs +++ b/bin/mega-evme/tests/common/blocks.rs @@ -1,4 +1,4 @@ -//! The recorded mainnet blocks under `tests/fixtures/blocks`, and running the binary on them. +//! The recorded mainnet blocks of `tests/fixtures/blocks.tar.xz`, and running the binary on them. //! //! The fixtures are three `MegaETH` mainnet blocks (Rex6) in the block cache layout, recorded //! from the chain: each block with its transactions, the chain's receipts, and the state its @@ -9,6 +9,7 @@ use std::{ path::{Path, PathBuf}, process::Command, + sync::OnceLock, }; use alloy_primitives::{address, Address, B256, U256}; @@ -41,9 +42,11 @@ pub(crate) fn overhead_slot() -> B256 { B256::with_last_byte(5) } -/// The recorded block cache. +/// The recorded block cache: `tests/fixtures/blocks.tar.xz` extracted once per test binary (see +/// `super::fixture_archive`). Read-only; a test that writes takes [`cache_copy`]. pub(crate) fn fixtures() -> &'static Path { - Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks")) + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| super::fixture_archive("blocks.tar.xz")) } /// Where block `number` lives in the cache at `dir`. diff --git a/bin/mega-evme/tests/common/mod.rs b/bin/mega-evme/tests/common/mod.rs index 1ebbaa75e..39db1b4ad 100644 --- a/bin/mega-evme/tests/common/mod.rs +++ b/bin/mega-evme/tests/common/mod.rs @@ -11,10 +11,131 @@ pub(crate) mod blocks; +use std::{ + path::{Path, PathBuf}, + process::Command, + sync::atomic::{AtomicUsize, Ordering}, +}; + use clap::Parser; use mega_evme::common::RpcArgs; use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; +/// Resolve an archive in `tests/fixtures/` holding many fixtures, extracting +/// all of its members, and return the directory they were extracted into. +/// +/// `name` names the archive itself (`blocks.tar.xz`). Each member is then the +/// file of that relative path in the returned directory. The directory is +/// returned only once every member is in place; see [`install_archive`] for why +/// an extraction is safe to share across runs and concurrent test binaries. +pub(crate) fn fixture_archive(name: &str) -> PathBuf { + let archive = fixtures_dir().join(name); + assert!( + archive.is_file(), + "no fixture archive named {name}: {} does not exist", + archive.display() + ); + extracted(&archive) +} + +/// The directory `archive` is extracted into, extracting it first unless an +/// earlier extraction already completed there. +fn extracted(archive: &Path) -> PathBuf { + let destination = extraction_dir(archive); + if !destination.join(EXTRACTION_COMPLETE).is_file() { + install_archive(archive, &destination); + } + destination +} + +/// Marker [`install_archive`] writes into an extraction directory once every +/// member of the archive is in place. +const EXTRACTION_COMPLETE: &str = ".extraction-complete"; + +/// Directory an archive is extracted into: under [`extracted_root`], named by +/// the keccak-256 of the archive's bytes. +fn extraction_dir(archive: &Path) -> PathBuf { + let bytes = + std::fs::read(archive).unwrap_or_else(|e| panic!("cannot read {}: {e}", archive.display())); + extracted_root().join(format!("{:x}", alloy_primitives::keccak256(&bytes))) +} + +/// Extract every member of `archive` into `destination`, its +/// [`extraction_dir`], and mark the directory complete. +/// +/// Naming the directory by the archive's digest means: +/// +/// - an extraction is reused by every later test binary and every later run for as long as its +/// archive is unchanged, so the directory does not grow from run to run; +/// - a changed archive (a recapture, or a branch switch) has a different digest, so an extraction +/// of an earlier version is never served for it; that earlier extraction stays until `cargo +/// clean`; +/// - concurrent extractions — parallel tests, or test binaries running at once — each unpack into a +/// private scratch directory and rename every file into place, which is atomic, so a reader sees +/// either no file or a complete one, and two writers write the same bytes. The completion marker +/// is renamed into place last, so a directory carrying it holds every member. +/// +/// Extraction shells out to `tar -xJf` rather than linking a decompressor: +/// every platform that runs these tests has one, and this is the only place +/// that reads an archive. +pub(crate) fn install_archive(archive: &Path, destination: &Path) { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let scratch = extracted_root().join(format!( + ".extracting-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&scratch).expect("failed to create the extraction directory"); + let status = Command::new("tar") + .arg("-xJf") + .arg(archive) + .arg("-C") + .arg(&scratch) + .status() + .expect("failed to run tar"); + assert!(status.success(), "failed to extract {}", archive.display()); + + move_files(&scratch, destination); + let marker = scratch.join(EXTRACTION_COMPLETE); + std::fs::write(&marker, b"").expect("failed to write the extraction marker"); + std::fs::rename(&marker, destination.join(EXTRACTION_COMPLETE)) + .expect("failed to mark the extraction complete"); + let _ = std::fs::remove_dir_all(&scratch); +} + +/// Move every file under `from` to the same path under `to`, creating the directories on the way. +/// +/// Each file is renamed on its own, which is atomic and replaces a file of the same name, so a +/// second writer moving the same members succeeds where renaming a directory onto one already in +/// place would fail. +fn move_files(from: &Path, to: &Path) { + std::fs::create_dir_all(to).expect("failed to create the extraction directory"); + for entry in std::fs::read_dir(from).expect("failed to read the extraction directory") { + let entry = entry.expect("failed to read an extracted member"); + let target = to.join(entry.file_name()); + if entry.file_type().expect("failed to read an extracted member's type").is_dir() { + move_files(&entry.path(), &target); + } else { + std::fs::rename(entry.path(), &target) + .expect("failed to move an extracted fixture into place"); + } + } +} + +/// Directory the committed fixtures live in. +pub(crate) fn fixtures_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +/// Directory compressed fixtures are extracted into. +/// +/// It lives under cargo's per-target scratch directory (`CARGO_TARGET_TMPDIR`), +/// which persists across test runs and is removed by `cargo clean`. Exposed so a +/// test that normalizes the paths a run prints can name it. +pub(crate) fn extracted_root() -> PathBuf { + Path::new(env!("CARGO_TARGET_TMPDIR")).join("mega-evme-fixtures") +} + /// A mock JSON-RPC server tuned for mega-evme integration tests. /// /// All mounted mocks match `POST` (the JSON-RPC verb) and use priorities so diff --git a/bin/mega-evme/tests/differences.rs b/bin/mega-evme/tests/differences.rs index 8dfa53f59..cfdc25c09 100644 --- a/bin/mega-evme/tests/differences.rs +++ b/bin/mega-evme/tests/differences.rs @@ -9,7 +9,7 @@ //! The inputs are the ones this repository can build without a chain: the `run` and `tx` //! fixtures, each run on both engines (`test_.json` and `test_satin_.json`, whose //! outputs `tests/integration.rs` holds the binary to), and the recorded mainnet blocks of -//! `tests/fixtures/blocks`, whose legacy replay matches the chain. +//! `tests/fixtures/blocks.tar.xz`, whose legacy replay matches the chain. #![cfg(feature = "legacy")] mod common; @@ -155,7 +155,7 @@ fn render_blocks(out: &mut String) { writeln!(out, "## Recorded mainnet blocks\n").unwrap(); writeln!( out, - "The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The \ + "The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both engines. The \ legacy replay of each matches the chain (every receipt and the receipts root), so the \ legacy column is the chain's. Satin runs the transactions as signed, on the state \ their parent block left.\n" diff --git a/bin/mega-evme/tests/fixtures/blocks.tar.xz b/bin/mega-evme/tests/fixtures/blocks.tar.xz new file mode 100644 index 0000000000000000000000000000000000000000..4e80ba1c4eac5182f638633b5e66cb49197c2a0f GIT binary patch literal 133744 zcmV(wKvo~3PK^XMV<&IT&Dl7 zx}3^P%(R0VWu9NN=N3M@5|Ew$`so@?(DDFk5VZ=Ua!L~W`di79)TWx5E&p-Ez+&I0 zYhcfvh}^p1eLt!}SskC1?8cn0p~(XKd)Gpht(EWlSs7UjF|xi=mUJLX&}^-rAz6gp zX~`hl*pternjpbS-bN*X3VVbM34lu~W-+QC;GxP%>A&+tm+yGGkMW#K;89Q95+bv< z`Z1CdC2nA0AGux0ymO9hcAsOTrw(3}vvCPfj+1WbbgJ#buQTWV9d#*8;A4hRK=RG< z!kRCZE$A-|DCd;RE5|%J4+=yVg#c3Kbx4xE!WYimD0Vj zCFq#N-g|+54Oz*+Sn~k?MOk;0jYYvy!tb91jzd1o7>19U_(Lv*kGzTl^X0ao%U_b; z-_zne52Q{oYZjT*g8eSzZ7N2hTO>fNy!|V&=g=ZYj#1KY*m9|`tlORqU#_E$LXrkX ze+$+>4qlk!6qZ^l+{WHE!*mVr$HX~nPl(F{2?p4NQC1EYtcb(^*0!8AxYeUY@L-h9 zkuWbq9A6(9|E%fRI|Wh~2|uv|$qXCX(!S9awm9*O?`lY;uwUWUUZB0hIzr;YUL-Tk z+#&GJc>Y3{TdiqtY0`_d?E|&+M7v9{(?T7zWC|%o!+7_WP9^u^AEV=Hjz;kss6s$RrcDx1=8SYA5${rbc9-*n{Ab1wA zq-6-}=}(sBzv;5s+2(~(?6y(CNzVw~_3v7`3Qi`ICv{Ge>r1mkxcaEF;!A zHyG_o*`7J7v>yYaX3fNTlKg1-e0M+VMx$#kw+C5M1RcO5KK?p9h0!t~Hg9CDzw}$` zzKQ%uCrORo`4cjfu!LSJ?&}P8rp(p~#ui%ns=)5T1o2|%Q`~xzZ1C#I;Q#U?(GxlH z%LK(1nd42`qZ0qK#}8b}cFXUR=07sbMN!CE0gPj(`;GlDD>AJ60!q)o-8{&L<4_4R zhp;wLbf-v2xT9)HD;`+&!hNZpQ^oN8@xX}4!O%cYlQdo=ZNgB|D(v}D)p78P`Gd!5 z1{aQWlt`!$o7z)ek@m`SmE&Na)7lk*c-PivB=5yXDCr<$5+y5eS^f^CgO~}o&rCG* z6dBhb4}W#XwBzJ=PgWR8&QDHq6rxutw#pj|GQj5KEAu;a=bkq~mxPm=$0B9JwPir% zReY;cc6nt@@t}1iQS-3;)OmdlPJr-yDcv=3!y?pei^{q$-s#i;G48W{xy)%iB@2Rs z91SzZ@GC2$wWHQHwNQ!nWl_;>iV!(^tDOar@|MX^1Ecd^Ka#Y z3JU1|scv_U&^4paYD$PsnCL6n17HlUU3VBiPjKZjm-}6ufXhc~Q{_uE!+V=lCpUY3 zyasVjj3yh*TYUQC;{`tNZGii=G!KKsfm@9)JCVGlTm6H0V1W2K9oXt@iw%l7lm z9sqV_uq^R7Vr6*($r#IPNqGspQI!k>z@lv(JrHl@UJM)>K65|io$tpn{jjG6=7A6Q z0%@AgRE6q|UMriiCVT2gE#JUs98e%j(vhbpm+i!_ZjjZe!(YX*-6S#_9cfsc9YwXRMc!3&VSES%~I zX0Fl2Wx?!`mucqc1TgWe+u>~5HB&vylW?-j05^lYO8}mGZ}R*PM}D|H&rQ2-<>UYw zik1^z{8TQP$4*AorBB&U{KnonP)i5Rt{5AmpH3nGXAECn{%>dtxr93ols>x4%hkk1 zNS9Z1*uRs)<1?aW^aD$}}_`mmEJ6PgBGN>I@<*4ET=9ZZIr#-GT6@M+v~@hZ3^ z{AkHc-g61}gg6W}y5c^~vH2)q_m? z^7IdfEs<_ANx@uSyWM8^5**=ONSx+e$z8l+}Gqv`f_cGo<)S&mqpNaEYYw zS*|b@2tJbYGMnQV3fB}7^?Z=`ZF0Ix7&m`yE$^()C^kWUM;G5WqaFPwii&e5MIo0> z!J)l5I+pAJGGjU&sa$+!Z-sZT>0m!*sX82rkG0avqBmBQzZat_qNL6c!ew>Y1TiC9 z@-HxXNICSpYC%FImt34p)oeTwl}27gI4~zUOY*h)O6=3l6Xh>qpxB)DnzW9#%Ny82 z<>If{aSgwEed^6cAh8GEtfOPrgD>sAVhegeaB^YFwo zM~`!N!gL;y&FLUOlY|Pi^NUc#p;ltq*xIzN?Kunc{AD&LFCrlK==9yMldvt%MsaI7 zI63?c#VjLRxHsoR&4;wbFobMk8V_BnfTaW;lSu#zK*szC(8N!^RU08E7@dfe5Lph38|1 zWVP}{EvW^Vbk3(?%H$*1b2Rt-G8Ip8JetTlHi!vssoOv57yX|bmco>|K*@$P8cqOy5eKS1U|1q!sWhFKtGstxp%fuK0G@r-RZL83IL&Blj;XG zhB~F@Pufq_DUQpt2%D;?s`6F8D`;*>``7%&`H*7^H_WgtTsxVEIiktYfKt6Dh`@Qw zGjw5G{B*0;s}UArnmB14*~Yj{yZsvqQ4G%WsSFuu>GhJGU60T=;y5nu=|U{@P0=qtaxrDC+)nvBmQ3j}HfMiv3tA^uH1p!RjbO&|=xy6Fhv&++5 z2rX~Re(qZi))K#InNb=JdYh=>Bp&;7>PwiG=7Q9DyTZSQ0beNfC&&7%g-FPodeGTT zlVYtPidAl#PD&=CZtF8~jueNv{vox4siSvY?!=e?kN-fhWudXt*&&zyC>8|Efr+pg z(Ix~gg~cr=SdOLsbGR9=^Gd2$B@v0=^Kme@`FS<21HgFJCn`&<0t~7ht1_|^Luz!n zsK_(lg>Y{Cd`DKW$O%HwK~mXQ8@rX1%?3p&Z24$-(YsW+0fND~pD?4v#E~Jx6>+CE zCm`t)$W_2%4trpZst0Ip&tG8}rt&Kau7(;SI4UEo8TmHr;5*T#PyqT)&72yA4=Nvh z;}|`F+CoNLpJ0tr9qkP4Fd)R!s-z1Ahio>RUhFA!otkRvu{lz5JxIW*RObs4z=%0W zEcCX`n;N`mFN|0f7_mJUS!30{+CHU^p8z`8iWG`%uOel}jr==;RogPX)$i6BT&tpN z^6i~x#Z$F;1I{+J3y)w2R5evNA?>NSHr6vRkay-7i%L)u@;GBuoM3$a5v@5==y z(Q5hG#`fs;s{FiYpwp=s-aQy(8uYbX9OXqY^*v(6>pVd`WAm>FPN}czc%vVb z9|zOAHe-Bx3fU@`1SS@p3v^G9Lz?Dg==*910OLj88GHMJWC(F?gj!TmBrYZMJZwZ> zU0h4t3Z{QuP$l%fhUy92?iL^Uu`MRhp)*r#qXjfm326eS!?>5m_Y+Mtew6&o)x!Z~ zp81QYy<*d?Y`)<;}?R0I-Rd9EE zes>SzVaIT>fD)b*;VT_7{QlyExY2LZd0!T%Z6 ztlNe6{Ds=LcBEM&Qyv3S94E>RNOlVc+%*CUWcT^v(^2qfcEB~|sGQY6eT4BPbH)x_ z6Q;G%45ml8C|*?Cj~u)+JiP6gz^Z(#hIpSuY%~*1Xr=XVAuJ&3p!JixVx_y~tto+_ z4SUZ*Xm;SRmQlJ(+_*Tp$R|g$%9}%Q-Jft$H7FNeew?v%eJ4t0*JdBy)co1mbnIfj znxUkouj#S*j0Z)};7YE*o4o>YIXNMi+B6t!%XD65R!1$EF+;)h3QXDQojB`SSB0VJ z93*i6WE6GO+Y9EZ}r3@b=4>2k>IzI;^BYa8#GRG#R`yka@0#h zl;Z)q1fFw1)kA`1xA~s`r91ZaK>sAi$#qULFCU7J-KIWG@q?b^&&DQLC9MLtt8Xe2aYxSxXuaZuz zc!yQdGNDAqJhCp`+6oMi@Nb<<{S0B)J%MsM5DSpo5=1%8#P# z?P%h9&jUU#xCcqwmz4Ew(VnhLH2b4B28zFSvwoq$iYId5;1V3J%)i>-bfI4w?FL97 zg=|N>R4V8zOIadzdsjA@;(%!M=~REIAv6K2u%H$qMt77RqdCKf!yu%8h7dH72>ex5 z(qjSMt*>GZax@br$BK5mJ6eSliZ*sBwmhG$lIDojJcWL8{>9Y(fQTAjphARmsk^uI zk*F1~4Ni$iB{wWfhp5c7c`T-7UzWH~Av`r1EMtpw)tIxKpXqJiMSwN7Z2C1mi>cS- z9kQ!kdg5pFkWH7(f8d8TJsxw}6dz@?kFZ>=Pew#k#k4KDpp(PeXrP4tepVe6+>>jm z+g49WpfSw`i7+(hLPc%q@a9n{nvO z<)0nj+?*8zXS3jUR%odXdW$Qz<faZO5()slEdI&mjl&c zb}42Nw|$y>qOQ69ere}db|H{LZORvdn#L-v5PCdDAM@^ti%O+d%x$zbRO?|nBtY0I z7+O0ZBA?*+ltK-KBE_U?TKd?`*4L;Lw+D!B++R4;*$V|VOc}x%ISdlhQ|sl(SZa$V zS+iYee5lMN=Fo+8H8f@A@IITg_#i42Xl`!zDrs<>sPq)o%hgg7+6IR7oDo>eil^IeIG) z*2C(~eLuw0&gYo35q^Z-OI+F*KQ~Um$wl<2ORoi(wSgu`{408qh)$JklH_N|D5+9u z3(O;s+MgOMso~8&8NoDvQQhyqmk^g7u#@}ehSq;}LjU>q)@n{-jL4;rOi zKFpsar?ktg5d>Gh^8$QF!Kjk4Ma427K)_}H2G6*8iCcn#hMh~S@zwKnFM`#RsD{?v zMH5OxfP*bWJ|HDAGY{u0UEAs~c>mUWk`7ynYfrgQo&qr=_I-G?@utxbmD6-agd~`= zf-ti7lFZQSeTjg(tswtzv&V0^NmAy&ARlZ`ph@ zOL8=q6-(9Lz`r2z<1~#djx&H2btjcPW^zF2JJ4gMq#$7c>dsK`>_GCy&jn<0A zN(BrN-?ckoTyS=n1jSW(R+Cy`xcKOm6?c8~HwrLrI;_aOh66Rr@Ptfmm}vk z3O8_(i&r%}W$!nms95;NYnvK0O~|%LW*IpHt)li64|IU&2D|9I!^E?LnO5`&ohaT-ZJ^CoY=s7^-ggSzrGg4$$74tA7CU^HEzshJ2Xk*Gj{xnJ4pQ4kGQFt6+p+sa)5PLVMmm{k3R{*JF{wrc#_pDXo=(-`sMhPA7nsu6LSrVcGC|9A-wc3}%u z~8~U@rW_IGf^g%w*LppS@ zR`a0(Vsio|A@xoC<|B$Psw9Si`3z?ih&FE-7C_0k;KpvSCrT2inotBog7=Z6g)6Kj zv1(u?`c(#WC$W>#D&*#Opo2S@)&EgTZ({;Dt>ncAx|dBDgnLp@gVKKJp_P9dr(zzS z39-fy{j1bccEBJ+SKu>W*5*px1C49GkugGu;4sA#h`f#Krxej7Ut5f(v{KF_;dld4 zd_s!Q3;YC4+>&=E?3VMt3B|d*sf~iLvUENOK0m;;gDddwo%i_Q1f(OO(KY>Ot5P`- z>*OO_yI-<65h~U-TH;0-lIZK&a>2s>DzYd7;fBFfRo3vZB_4(c7JbiEL@r_T3AloA zdtz!iy=y@RxGYE|Ce?lDC2V9FI_z-t0)7JDXSlgQPIF_5+49`XeioT5-BxLStkPlM zD&iE>Uv;x!W}r>n4sJ>@xi6fp66eCwQjup=QCa7s8wX_`{2s!!pUL?>1f{===kJfX zpZde7da3Yco1r@KfFOPz8HA4A!y~yGm+W1tJFY8PJh8y1i}Gj-EBKXk0UVJV7*1}t zd{~YD`v9VuvBC6NpC_MH&$~u$q;mR?&b8pQs zt(01@tAt0P*9TFWEB8SInWkHTV@`)f!w)9Hre)B<)}@FBK+vEFz!VmrG#0B{fP5D9OgNhoOap^kIHG71&};%^eR0@edpWFt z3(4u?JXkpM!`5@c3XT-TDHvX(a2Q*OZ@LZg9;w;#kjb_^SXW#hjtiMANLx&$_)MM0 zz5Z4AU5w|tnLlGHyMh+osy|+E*t`=TRk>-T1hmtDd~AH&{Yx-(KO^dg+8h@id-Z1r7BCv~bOSSFSBlK4tcei)i|@W>_89QIkX77#9SX2^(tr(HpV= zW&=JobMxQi(eee*cvT{&XWlqshvNVCEv^%VQN`m}%)L?D8#;qMgj4x#t`9fur_dM^ zLCm3gS9TM+8&60ea@NI{H@2ROd^EDvY6Y95-?7?chsQj*#y-pqs`UB@pjB6m?x*G^ z7l=BkT~dtXk5tm<@F{_wZV4BQa41W|*NW-aa0M5dk?II+Berhpq&0;$iQ0|eB2tkC zfooYUnt++kj#7|zDYtgB*IgPsRce36%>3RJLf_i!@?9;wN8{}uNOjsS* z6Q~HZ+MgL<{;cUUt(!NcDec~0BVV0uu{x+w(>1hm<1j-Pl9=9Yf+)g|;r&y!NR;l0 zqVnvrKRO+y{#FY<-Dh6fuoQOoa+#|U1UR*cCC?q0Ot51=z#_ zc`fP`d`#!jcH_Ah)*lvt=y6qw&ACu9SB9EmP|reXpC3cus9Qw!Vjqw7$n=SPA2V+w z9}?Cc@^MswX@-?E4i|2rv$!#3*W8Z=^lZ~B8g-6<V`4PEk6CDZPtY## z*saNO)+P_AHHuV{kbfU0{2#@J(PEE+Ui6`|%ih{1r$VnTneRU>Znko5M)ue_(Os=} zalE1U4o~1{158GCr#?9NS{OWX^MI^ewKqScxG^x;xOnZ#D0Y%wJ7>k>{;SVmR0Uwv zTgkq&j@1Q-`Yb9{G-xtjN{o-a_sA7?x1hPa0A+FR%x25iuC!*Xb8S&nl0N#caY&3{ zdwtH0iQ=GAB9OS9aPY4@d(s=b#rISW)1C!3Uc$=+6P{(418ps=^p^iOT7W_w`T>^f z4YZlN)8|RS z{k?X?xidg264wIW`JKtG`u%&N^IsVnYBQVef@?hn-5S^ta{=r%M^*~+ZXhnO$B<9| zULN`gTy3{aXv)8Z!o%i5r`kq)eWxk`g)Oj$9G_fMq60w=u5Hq#hs<(c0PGBvS3;%z$_(y$00~>c6}0He~r=n zuP!rocV{V2#J#EMz`R|NyedYqI&CydqMQg0%9iA(k|SB|d{zPIo46%(aYIi3be5K> zUIHBUMSnvmnffQF$^5NmB$stTrg!P}42@7T#G#sacATajcjTOfnr`>tWaLcu-1%)}7(`K~e(MAgfQ zgH4XnBFpp&lcdzkKN-yeajeKn%*^a zZW1>4+L0u%KxD1E2`?p6<%GH)|FZ@Qmc(e_d`vZ==eU0_R)9Tnojwpe*!I(F@Mgk} zNd>iO6>)({9&zxr`-IG?;QVA5hHbkMr!1@rObhLhe!y17S7kg4+(`oHe+~oqv^YW% zyu~K$yIc+7@IM*=odrH9>vZuxX!jtgGvF1fi%E$>t7#A^XFWe(AAeSoh_tPB-Ob^4 zdQmDgIz)*~4FiT*tlCP>w6)5T~4$2jfAgiJfmXM{bMYMS)(}cC|4B;BgBV4Tr!`}Keb%Cq_Q|(VT#Bke#(p~ zO7wemm!#XOwBH^JJDO=9q5qKOXUcHfDf(12uBSDwsOZ1_FqVLSm^Y&u&}TjG1E>89bHcLr4(5$1mI*%Nutc$1x2?+?&hZ7OX z^vy6z9gbXL#l^R`=-}m!CA!DNPxt!Jm(2iyEdfz7o9x9ZRnqxJ1TN8C`0bUlzY+-Q zgx>ELXzt&3Spu1sje4?cFgH_DXP?Yoo5IfmoXbx{3hEKyWf-DSQnOy>>lf=(x48bl zhZ^J(Mz<$%J|tzvIOsH!)_;ilRsmMRjf6lyh=sguYUC{6)daV3lew?9)6 zU#9_?RV$;dBPf3~wd-sa{C?@9FG;-BCgj~>t)uGp0jWpPfEFgbYaM!;8hb)LVk4af zj}H8#(jnFE)TMsa=^8d!(^w31_oAvbjGFnHWU1!Omq^sbe`cm=m&vF#)l{Bg%$qg_ z=FP^y9YLlZ&Ie`?pR&)aA$f=(HwH4wd@((^fm9dG%DR@0KN#Qk(6)SGNk-Hk(_#r) zDGW!`+lD4uq81O+Md6**+KHf1Uie^_ql8wGicnSP@T+26kMrfM^y2lSlvWT+)#UQk z0OdWe=$-3bh;tqfQ}#t8&lVSXU7282@BfQgvLgs@6msHo{y=#yg^ zKf{y8&B6yR4f8fJ1RK3ESK$}t&c2;%%GV=I^~~J|ji&!h+|^eXIb2593``a^t0sSJ z4@u}Ly|ec$OvYi8eN1eg9NjG&9JlmA%4ZC^3QL6DfLquftk=Ou#S|11b(Wez8y9|Z zB_(l}5$yTJ#F5K>w(Pg){WRgh(q=UNd(7h-to&#v_S-LoCk%?pua$Tnb+9s7^U-En zWjwVJVr|I80WPCM$N1@eJ~TbJU&lK$jHdsZH!G%~JrgW8lwGWNTV7jGUk^F+mLM-C zasKnEF9ERE>_&WZhcePGBW6^nk<%2G-S}5bGp(j{itA__`|EkeyS88>2pQs?nZVP5OwuQ}LrFuylM3mG`3jPTN`)V~#XaViWgr?8=j}{6ZlXJ=Hk#UG2W2 zL87o)A=GY!TzyMdyW#KaP_B5!_VKXe4$B?3;kgY(G}89-7cz(&egL`L7GN#}*`CoK z;nlG{5S^C3(9V0ByeCbbYuUDi6JWMQ$CeH1FlC%R9q>J<_^ZqVor0O;+&Cv^@p6ZE z8Z5ODgJdE8j(tuY9Ru=QPg4Q?n7=+DOG|t}F`!7%JWWo{wu3?deqTZ5f%gb@W9&u? zX*WGLcc1TW1{?%{VIm_hP|8OCpZ~m`KDd@Qi)B_nS>c%bf8ygNaEteUHew&4fNL(oQ)Mt9DbXZswWl zA7ru84rM!+-y-&-J4}7?H(h_F0+Ubq*RP}w5;Zfz&I$Y5>s}Y=`|m}z8QHK65c@U0 z{@ENgj-_dI%L~|*CgZ&hPF-59%OYzbq~{vgi@)ORNA$AuWN%cT;p#BN;l$jcX07_K z)24K(oeOZN|2u>E;F( z-&B*tmkC~eB5_Uw=$}6(g3UjAMdb-WZoXhE(Lym>469C<_58+Ly&J8 zFB0QQghqu)x*5qkU; zJcJuc@blCCa6vuf}V%%j!+|8vuu^EjVIW(2e=Vv4j_ChhT`V_59O`f;KEWb zGD!&7^Qv#S_V&B@-c$D+mbZOv^Ej_ZKl;!J$aP*_iw^a^fnwcyWFfMo^p+GYs6v3+{r2sREvb9&Y`C%0vjrDjBFS$wjTG?Rm-> zBL-$B_(KdGk&i%8;DLBhom=aavCH-NSIR?Qi>pL8CeIL7lavZ>UCs3g_C0#EVbV~z zmW$T+IYWZ;M6PQNFP?SDIT4H-#Oaon;g+PJ0@wTRq_AUFUzgV7_nIn{{~SJ4oXCj{ ze>C@2R)q3=6YzY5JA8G{ntgAg(xPfm1Z3U`35BLH9&-XQs?jtvf_%e)@!1zF~~RZ-#6 zz8rpp4=|ZX!fLMGjsCCZPCQ$Ijdt6mf- zofjV;cE6*wsGL$@iL!N7Iu*u4A6uqM zuYk7mle~NBNQC=rZp7uD4y$laaxv7}KirZ7)0uePc532RTFvNUEhF$8ssXDS!wTy( zP)FQMJ}Js}X(6<3^bN?}uF_PJ9s}*ifcmz{7D_}|%{A?{Fl3lSb8F31u!LQ{5u2D^ zw?l-d)MdKIg=Ip>A*lxt-nXqFGW>%Zkerk>kQI?a@Gtso_4j~Ih5d+@Fi!`1E7El( z**i*;z<7@%%pc)xN7~bwY28F5ZF5cywPy1$3F*k;6wmWu; z)=uW|ng)g`4I|DVl^d|*3%KE2_Fi{ZN0StTzs{M`JC#-q(H!f<^+h0lUBsJ!E5=|Dhs2}-{pe}+8&ei!Xqsm*2{$>u(RHSu# z?DLwl7Bv149{LjBJML&zAKce`<;Z*qCnx`3xEWJ%^S zgd~XyDkr^jP^a4S7(~vvcs(b?0P-T3{MT{^JNj58ye$N9#cQLQ>;hA2PMrD=6!1?* zJscnWQiJy(7qDhZz0x3Zoo2~~rBp@9$9*n(>VFe<@`ji^81&uEANC8d_eGwg!)bW6 zn=@%!0I+nnnPdz*44L`_(fA)(03{Ifu<&vjScr+XG~zQuT1t=-1^Q{ZogUmj)R}_i z&N>sNkJMisf^RVAsL@(XnN}oF(oK6`4V*-G4lCIrG3fr_J3S4-*nyp5lTs4Gij^2T zT(WxRDNGV(Kd0;Dn96xK-70Z69Pfj-P5HvdTA~^H)o;U?r%l<6m3UJ6h3Nzq?%Hpy z8xexW<`k=9gfqGm=SXF}ZY)j0Jpd2{t?3rmwg8IFS;lPiur12}u!L;p0zh+tX652U zv2n`nK=6y^H+HA@%V83*-{R)2mMu-w3VNO=$5{c$?L*x%-T!=FG9y12Q{8xRMN{YH z&{e~G!$ztne~;o$Hjnm8Aln|BJ?IhW_vMI_J0Fr2JkfEtYhisK)0scbn9j^8r-)!L zf4nCV6>QIX8r=V3?j&4x2I)$MJwQn3pnh+NeY7g|(FvEwCSvcM$CkzMT>``bFt2$w zSW{q2NAmmR9ljR&MPz|_g6iPzL(W>L1XbbVyRXOU6uo@z-t)fvvy^^$czm6`qer#p z-Mm*XWr~ryn>94Fj6ubT?<~R$shvT)04BSa%W25k(Pctb;G!C>*w}I-F+*fj*)dd6 zM+f!=BB>Btsd=1IIQ4%ps6&X!S-)NzkQ|Ax*vYk0P~lWQ@≈79bNmMp_fNST;UE z($P2;z!Z}-E*3t?TqqBs`L4UL(QVY5z&97!^Bde`jB!8WG<<5!I825z8$+I`RL3Gq z$s_X=uEYWMzFISWz>(8bL(^ft1#tXldBtx$@RX2>Y-jjQQSEvR*mT?uj3auER_KQl z#j*qb@G;yBO3;X6`CvATMQNOwdFLk5dWMN-&IK^(s4d6nI=G=_VL-fgw1eZBDHLO4 zZ--@dY?!rb>t155uP;$@O0G_S%a4=!et}#`MFaCy@Jh1Ma{NHdxF&?eg4wAx<^z7# ze$Q)CmUVC3?U7ZIInXr=pgg*S)$+np9+A5Zsy>e2aYWifOeC~ zjlUpYM+#wydW4>8EM7958zYdvP6|`|K5@N$NuR<(3|13$+9vqNz)w2cQCxQmS2B?P z#!yLl4%hWnWN76RPguB7=Blinn{keN2<0Vp>DD9n9ABO@au(>#HAYW*Hkt2{O_Y;U zxOsS8D#!J2T;=Cla!M8Q>xzGb^E1OuV-9&>Ax%iPDhve*;~tq`abvlZtuk^^xI=C2 z%{I)EX|fvFvXyoUe8S~Q|LRl)Kex&E>_G65@q^vNmK~*)aB7hcjj=~ zag-jAl`km7J{wm2h3X>SRGo`V?@0g5-s$yIuE>KQRXe}yW$_>06obRdY#YBVdjrq3TP^eL6U3V zuqK|dz$XQhWv#yzpH{?MLQ;A?ph{;c$yf^~jphgXaWu2(n;^r$5 zd&~3#J^A#aAd(HM%)&Z_yxPj2l@lGBDfwUb;;8>l-pCHGM!RzW6J7v;B!JD6+2Vo6sl2QeOC%um~0|j zFtgJnmOtk>6oSZTIXZ+lDXtueNb*ETFeqDs=ATINcw5n5W8$AH5vHl~ABL%X@bvds z&XK?O2SD5L7eAvRh!$>@#EmzfE)=4qELe&Um9J=giV2ANd~>fINEpL1{FvSKihdcQ z+*m*}7ydqa$Fy8+pJhJEj&08&&=E1>*Q7*2P!K>)Fk?J5n4@*mVJ{QFeZeJsx4||8 znn(n>F1Rj3Eq`;B(djtRQ)l+!k1eEy82Z4^VxLgl8b=1DV|#BqvA={D4wzCrW^(UX zS6HV87X-gV&j(e%1B64-0Wc4E{DI&Ee0p}gj<=Eq*9=_pVv^6mMO#8W$r&ceFo_@? zW?)PPgP!|aqw1d)Hh;RQl-Zb2WJma_{s>lWz@WRd^0er>{wR>Bm47J9aW=Ba z+s^^(@?tLe@3@uG^->Uy1$9Pi-w%IK2WbP-Y*L|vcZqroGWtHB=femx5a0w_CG2zb zam&0ZKl;&Vh&<#Mk*1g#A+)xk*P1y7G#{Msu0X0fuwrimt&MGC(s$hk{PjxOLC58dxbvc&>keO zQ%G>TX#bbH2!ycU@odn5fV(skiNn!jAeQ@U z*439wx_d7x*d-aPyu=#I4dKrSBX7pAJIlq5<_7p!WZ9uhkV8>w?wUx%Gu-RXDW03+ zK8teIZ|!0yQz|KnOk?1LMhQXNo&FTsj=+)1oohVK zEu=_V>S)#(zhU%(Wooro=0WnlHH%5qGEQ1S`9h=dx@LXJc_@6`v#Z8kW2-?kd$13| z#+;U{?TM~}k-UA$YncWal)X#KjXz_VMPQjr#IzxxStD%*7Gah@sX(7FU(itc)3Hpo z`aLxoM@aN*<}HtXa9O%a0cqL-d8Bb`|3jT);HCpz;gH_;Vh2#KTT_7eU$orjdPs|! zywL_PO@*lLxzt14_sCGtqVfWV^20}J!6qdH{{Qs8Um?q#!C)AJK4($X38x+io+t!)KWS`gNT7_V~5>2CI`%jDFP`(6rEON&yCUkL;(Hy?h3?K z#K4Q-(kJHL(VotZ?;+)rKgLopt)#W(;GE5p0c_e~m?{W~kg9euioWAgR;(V^{f~?a zGA0y)t2>T4o#03LCX9aY8f0xLKLevUnCd};LF`Vq+WLjc;hC_^|-B z*ben`Z)!<_3?H+B=}p z8apoB=d$R6ku3f5354=iMeJWpFE-6*y7K`2kr9s0V+6e0@jo@KH7=dm2t2=uQ%Sds zWi$7b_qoyor5sj!a3!?+c*8+S1v3~F9B?Fppxfva@)Ep^VSahBoX2* zT~dbokY6)`)+Kj~?B{I1?03u4vpeclh-*7lm*P2L$yIC#mZ(txbEiYMB+!pBtJ8KL zOjOUx9G19Ai`Ka`r(gV#DJIN$jE??<+~DyTG^s6VUpKKWiS%2<8YFiiDe=0eE6hc= z6=-C8iB~K>$of!eB_B$@_Ed+86AAI``{{p-!xjAhKvQ;R*ivw`n`As2+4+m`shco- znY(nTxqN4YroH;BHeU5HiQ7siq)u6@nQ;dOPd8ou*p8Z=M-lqMHv*fyPO{PEz7?j)P`5J=4I0G`? z;8atFkD7}u7!u@aW?JiGsv6$#f0!m&&%o8+zpB5K+{4p!mk_xx-h%G1&jRpx|Jv;lS`M9)~T4 z2veWV%(r)2yy8?x5{s3C#FP;}K3-yB_GDQpg*SaU(Bh;Z@0yju9_K1K$^_p3dXQ}?d>P=n(HkZ(vmp8kBm z-GHFgR5Od+b^8I@Df5?4THz>>enTwY%Ej*t!iwETr>GK8^Ota0HF^{Url=y=KYa`5 zTH%q%Ybi_z{rexILx)BWA;6nr$Sa1~(22<3+G@1FgR~i_DqpNB4x$5;)HYxCj{KR~ z5?38a?e!@bKeb8a=2Cc4iLfCSs!OB^mDp=RaSc#F0#l66WoH`%mY>xmVhc z<<~Xt(Zj#nSEGlc5ChxWV-3$3j_jh_vB~Q%wkfz#rkk?va9e@!?2t>T$7bxELGd^f z2^vye(1AgM6&D2+^CzP=;4;VW7yJG-Kir||Y$Xi4baXh~;X~|NNY*&+Vxo@&$ioB+ zfW@oBV&uKVs&rbG2?uwK{w(6JLO7nwJ*oPPe_HWJ1xuVbuk=*)I!{u`%+nlUIDqY zvFn&S;6fMVfENu9M$P$3G!D>O5KiaGB$w^i%20w*&hm2afn%RR>9fn3BsDFON{F`! zGfFTFk>%@H-`dd^1WxEH6H=LiDNYP$A)QFnY7^$E!cu}vFzO*lD{)kgKhZ_ypH7F$NDz+s6qxHI3pBX_STq#%fI?H`00dOo zgR500zYSnT0SZizHVXSR=)wD#fr%Wgtx*n5b}6e&TeTPOZp>`eBkjCftXn|DFuxQON!OG0`QC2wda9oEhK;n$XFv7SQxo)UYgi!{lqs}aT)qJ_jB zT&)uP2^mP?s~h1aG^c^+OWt?Bmmag(-X>*mxwHPr?!c~PsFZsp5dH~`P4n(_et|mS z0O2BS^(6SIrO#t!HO^SQzY&D zoyu;v`bNCSC50n1Z}Z|Ad>Tr+dKQ0V)0B*ZK^hlYfWkORLY!)bz8ii_K51;<)Xhnw z+>mxj+V8Cze5~=Y(UtBnFk=?q&YG}Pp~G>>1O>>w#v7eZmVv>=Oil6b)!4lp+(%3l zs5ffsqjv+*ebxuxA!<=Dt4&e`RP53?ap`i&H|-zNF-E@t3?4+=zVA8>SPu4s6%d9{ z?E{7tm8LL#HSc(HX=z#O(?c1+;C`+zMh!cj4NVfOJ=0}@;=y{+7<`y_6>K;t}0@QL3VkP4()CXtm{-O)^JChXQB zuTr^$KwgXQ;HOSefjNjg+||R86Qte9^vIIFG6;Zdy2i!VB}GpHhD5RXNPujdZB;AV*|td_u;z%f$aoWG8HFLH z?h4|QJH)hx$Y=_e%Hhv*$`T(3pEU-XEqkYbW*`jmfZ8br zerTR-c5*1}NKvC(Z3p_HLa5=d)}Xj3>|xmzP5y#VGGM`B04{yyxL$gDFazdw&%cWm zOx@`OY1eV~?D+1OWV9M6tEcqR-QE(vS&%x*TNW6t9`({&U@`e40=SewS|e#4bYssE z%4FReW2KY@NB{CQMmQaqfi$1TJ{@U}PG1qEF0n~uLQCzcQPaT@`kXBo85WauNq z-`}pP&&$qv{mHMUZS2BDQs{DOkI=>I?)@o%b?dLq`fa`8m#Nra8PbYe3EldnSEkdN|^8=weXq-=*y%eQ0MxbHbBb(ibDoRoM5;6X&zx&^^n?*AC=&RqsR-?`!hD zr5^CBwGynV6iG?+2WWE*{8l;fG|mmUfGBI2(?KdxYj#4#iYSi9#XH)r0mB14)!{%YbQIU5QFF{E>+fLml|2dCSKg@N)Q|!QnJdv- zDiW|j24v2%)T~3J#oW8d_d=b^v^)fvAgNRD@Pj_pI4xehv1)P6QRf$D(D?uKzMYLM zb!IO1Xmax<`n3E-SBXvvHLYi8OL*5~C<4Mhv=4Fd8^}8VkjZ{Z9r5}-z~{HXrBWz8 z3#f;{n>3AWb!HN)SQ}HlU#)8#%{=_PbTpS+1ovHYEnPm@L61*Yf%(nqo9Q4kwl6rT zp~0VMqx9s3L`KeDd4k5CFt;hIWF6=P>h_S_7 z`4Q%Li2PN|`Bis8YWN@F2{5^Bn*~HvXd+7HOzJlxYCn7bXl8CCloHzN%gUJ0QYx&@ zxBx&XTwA1vES?8L=^TnUmGu@ zG*w-76DV=gpD>6@6BBxDtRcLD$v$EFx@KdS?}-_|Xhzgo_>=oe+<>u&k|Jd|pr4l= zPY8@pV`rLD?lVfGaIj(JK#4JB1OK)}>ZYTF-C)i8n|f1nc;x2znPZAlqhDaGt)QV_ zNQw$76gW~!R)ulW_y}{A84*&61GM)=67G)jH4!>LEc$ZX1DO)XAZfhKX0V#;MJmU` zMGP%ePh3Nh92j=f(dBKNf;R2Xnflnm_8rZ+K|1GmOE%W79GCYbn+8t!tr+v|laYBxOqkw4P-flW{3>@aGEO?jbY7=O zBKd?!gt5$dpbOr;1O*g`G&jQ51W}-=3yb&SD7O3+TwHL&9E!i zad#Fvu(wUIZ!Rt1$ROOfUH|&{qf46n+a=i%LH)Bm$$<%%5btp!x7Q}!ib}BIIkTCV zTT1*ePp)ySfs!S2B)Yc~0Ic5wiBqSlb*Tl}T8LkW-Z*36T-%*lpUnEk7Y6`k zUh;RSZn6HTk;Oojq^^ZQT=k|fIx)+ja~8ZVria4S?+@>+5IA;j&VaBrr;Z5KD##E|i38_$iXl*vud-T) z_f{MR2j-7jtH&gNm5(}&KZG%Bsf`Fy+P~8XYj^5%JX@yfXHQ9Y8R0w|b+<%fQ{~(1 zrAD#e(*xQYjwIFz&xl1FtT%AKMm}m~cLTh`+COK>k%oflh=x9&2Z0LiQFR@F1R*2uqjWoo72euiR@2OSaOgnv0cGs#*W-tLZFl+bAd1q$=k=wdX8kD zt!Jm{hD8PZyUb`c?4lsjwY(L6ubfhPUiGncMQ7?DYbwgzy?sy-1U^-gif(;7MG??MBrJCz7(qO^)ode5$r#HhE8!Cv2dc`nw#4W^z zr)k8yfNqp-^xCe;+JFCwJE^?=JPU3#P4SertkszuSC}m`N&7-4psXR{V(xs$(b0fA zaPs>Bn{#RkcOLMA#_jFklkv-x+4nvo#PqHTZix31I^KQv9{t2kc?I*02A$7~j3P&7 zpl0|LoQwSQP1Y||_w(ht!3YJl4^FtK8;CxPf6CC=G)8cX1DV?7oqkH)XX=xb8UWPfnvd3nzx>g`|mArhTeHA>NB?B5+WWr@T^lxZG2gc<;+ zb&Z&W^Qg0(<_dW3u?j6U=+opx*LgnakTsradvW?zW`rlrK6KhY$+NkEbqRZ^6C9h{ zW7>7+?(LDjS5bQkf%*3EnPKISaPA|L;UHR&Y(3#DDZh6JY#9KUN$Zb0vifpeDF|jh zfJ_K;DCvoKf7~BL=l%za#JT77q&}rgV0owVW%}>{Z}v!OE78rLsQLe9ZxIzv6`IS; zc!>I97N>ilKqKnxZ|s&{(>S(Fg7>Of>Jb@Aq403X|74stBI}CYuTe-SaUexo4{xGC z**A3(NoDU(;eT17;*}!r?s}hf2IVd}YGAOf;j84@O=ps3BJc$5TCd|}W$EuI^by`J zrxS>D&?B%wo(miD8o6nlHOgHn)gANdE`nAk#l{m=bUEz^j95y9simjb=HY)KXz7X3 zBZq2eBvTHGwx8?0R!8|a4U?w3pDI!K43^rjqgt)KI(-Bn-;Iw42e!Vo336#7?;}FKqzP~x!U~>7f=;_x~SKnK{oJP@`s9wink}?c+ogd=0dJ>J1NPJ zgkJTURs6c;r3X5O!NMq;(dQn`gsI_Ys%=8~8yqBSRY1-1b4E5)8616dl~xQ<@(RhH z?5CgqHh_(?Rfx%v0B5O=pNNO=UKa20quE(?p1rFjz}SkZqa1c?GPKG-<3Ap1;I$gc zc;S2XPL)UCbSLafpDn+GJ}^eOL+c)OOBu!zlI*qRKki33zKr$=xXf>w&EGpmYXAdp zd$smMR0)#Wxiwv-IPM2#pG#qVz-Os(`v)P#BQK2#N>P;EPOkZG-^uhddheO)?I z2BQU)Ht9n+ZKyf?R!^cG6rYiR@bieLsvw8!PY1s~vUPin3G)Xj0TZcpmvNe}he`Dy zFL%bD?x9&;0MnBI$X0sl@o7J{UQ(eM`dhpGQhEtnrv6$g+Etl_3P^npYrn0?;zI_$ zi!JpQa%6gJj$<=q!#Asck?en;>;&y0yP*lLzDZDco6$rMes%St8*OTjj^Py7@Epx- zQ=INCbuB)*e5Y_?SzedgUSWVr8uj&2|H_9(2neEn$14N$9!aH)b}PYsrTsE!;6_Ke ztD-@8@9qOo2mQXe?Y0~^@fdB=q9#$HlTH}A=>AY_ zZ}@9cmMNjI>p%dOpLS~-H&+pSv7Ga)uNzkzdLAKgmYgpDWct2xhQqFLFQUVpN~BB$vEP6@ zx@(ZHUsupQ6g{2+hPar%hvjyxV$jdwCF;5itPe}mU04oD7FP>J;^``F6oPCLhyeFL z`bbt?bMU0v-Vx$VWRqZ}4;H^}12VCw=Ls&MOl5W6$wF z{>5-d$bP2V|L^ukIVgEfuvxNGZBbeKUCLk;%a zRZ%0dM_2(u5_Zn{pgG-aCZP_+r#ZcNXGZ@+OEG_%ImS0)nxwi6ruY27$lFlob(sJd zuFG_SIC}S!4^T!fJQs$A-a$V>&e}DrmgbZs=KU{ zuiAWo8VQq?2?*Wh=|=*~|4~Hkrb_HF$?e$8iin##9QZ1Hh1b*jDi# z<*&m7v*q0zFT!MSpy+S&;bUUWsi*=wbvhyWq4TWt>WwiO0k|Nr*J0uWvC3HS((w)$ z4U+3nPNcC+h>ew1x)X)%OQmn>jGZ`aDa+K%)&vI1tUA6^cPir7XA4FxQ$j3~$ozL% zF76=5Vzmh>wxbgfi%02Af@u#xSk_TplS#SWn`} zb1c#r8pj_y54^@i5ltgTzh93By_F07X<#>}G%gA3WOt46i`>$m(-9^eufU|2WBW(v zabPiQ53@N7u}7O&(YS!+h_nP@1oeX1o-h81oP>r1PY!}&#z`;0R&t}i=wcrMNpwZ4@{{F(Xf$D zP_g&e2|j*oaMBFO%u_-v{b)sTPc2xNZc5g0H!H{ZmKDm@djpr!^~nG0lgCdY3C-Bl zQcou7Io7phEMtU+*Jp)!YM4P#`WEN5x;PQY74*CEIfWJhuj){(?gRITgu@`?gdD|H z+U^Se>T?`bBUJuh$`)=p_Ha|SvfG;(#DPK#J3s_{^{xlvMf%kVCT+8GIL*@-`)_l~ z_l04ipnn=0tBN;0F!;DRg`*GA3cxIY*$5=4q;j|bcmq3xCU&>>cpNb}dZIE@?8keZ zw)#`B20e0T)Bg(zOL_{nC}attYApOrQclOpEj?KTTuTpvhSF8{6g=s7r6rcRhj1E@Z5!Bh+v26j;hJQU2s zX)I}GT_54B^NFN9r>5%@T2jHU>NsIv=LRF;VwvD3tfsKlw)Xu0D{l|{XFG!v6gOh0 zk#{xsJr)ZrKNCX2^2hA$*};KS;#%$2B%tB@&H4WC9y zquQct`ulVT+$a+$W{Bju<&t@H<=&Igqv2lQ>gmm;U%-q;Ke<*B@U3xt<}yo*5!y}$I$FXF_b#r@w_MMAKd%}=Sc{ql698?=#I*r z){F~3@?jd|DPZ$}7Hkr%Z9h%qG90$}nO%XD2#Xis@}Y2AHClb52!!`(>6NF6hL^#` zB8M&Pfhx!KoEDCIt3hO&;TQQ;Ykaay#&3b+dTZ+JRhAXHy)>!uCW)ps2EZ{YF)6ykx7g#?Mt zrcu~vQR7kcI*ZnoZLa@@sClj1|7@1;yYUeVHNoZ%@OadexsB&yGGUCmy(LA{;!+bK z`y!xyFRj!!l!5j>Tx~tlui8qmRn1UW zSNvJhThF`b;xbOO+8*^6r5Lz!RTO?LZ9+O&4H8sRSkD25%Ilt$By)P7iP`J-t8idD z2Vk(Ex65yUPtNq=DzZGGpc2(Kj8SsWJQFh@N}t7ZQYFc~jl6xpc7jrDQ`xd- zVGD)XM>;d!yBb5N#&5F!falTawR%?k99~%w%#d$34(waN7?~_tx;JKfc$q;WF|4%r zaH?cl%iQxM@|TI#!`Rx=2=y=G`054^XFM|Kgq$XUi?MvWdD&H6*!7ty==5kGx6SJw z<&WWnMMeHO)P0>()Rf4?+;p6BH0k|_lyhU=9jd*y25&k^3{2W^1^RsI8rnG(7IMLY zz8l@v#Vesg7SNsT<1ZLr^nM(NlYR{HYS1g0dDz*`Q9zwUZD+qM0$i+$io&!MUu6!x zx3l|@!1Cw*L2gdGRYUonWeqB?RNk6=n@`L9 zb2vq{VKNvED`3@|ppJpLiaieVfbFowgR5$!!lg`YG51fn?WE3vNqw}7+5}8CG7s$P zEQ7Bma@y_ChUh6l zsLWtJ8@};-)mBeyDBl0srHO?mu-4;JrShugIV*oYOx1oe(tYUZ<@*-#Up~!EB?Fbm62scc?LA=ezf>x}YmhQrU zx4!3(1zpc&gjCs2Qzan0>2%KW`JmWTo@VuSC&NR}#w#)7cSh!qh1-1IK@CI4(v+Kr zmnC7m$yJipeY$ebPL|G^E!rYn^oVOqEdUC@2=yo!Uqtz^Typ8oiwttgXz#&l2I$QZ z`e0;2d%K=bM#JF-x?5&$_jZaTRJLH9<~9wbF#@(dAUIRHP>l z2QB{49C@A3rN_P=nH={$*=3chJ8-G~Y6~Ej5C5_8t5?mDyx6~KklS6FLPK8pQq=-9 zb>aE*yD2tBdqY8iYYcEW+bO}$T)WeOs7;Z+Ohl=+x65(k`dCokzZeF*UMHA}zj{?1 ze^5R^A(Sqs6auju5Oo$eSK{(K*EHkZ82y4^R6 zhq{whwcCtex}%WPc1-+-Z)73#;6oeVm*OawEQjJ2@LEs5$&`ep*rKYw>{ zRLbAWsD$|Ycr|n=8GJk*d%EpjQ7muyv?gmmFFDnfA&TRIYsRVUfC4HD$Psm%2=~fQ z?lAwct(v&Fr)Toi+MpMA!+WxgqH5Um5|i_K0t8pt#v$$gz0pR|p*Gt$)zPfksWDzC zwz=FkNTJ!YS?JrvzCLAR9hU&TN}8gp>g7bh>(;q-S9_2Mwfx-~Qs>HNY_+MtdsnXh zIAi3GLo_79BGgO3%3Ljt?tSpE-#i4>SO0gXm<%eE^m=^e7%Fk0LB);^Mh-Kxeayca=bQrS| zx?(ocip$khj?g*#n9|HDGH9g|sb@B}uBy_BIw(@Ol9IUyQqyO_`q zS9x z3_gC&K?~c<=zx8 z&F`5-%^M0#m{QXbuQLBOh=JzHg%jH$#;sBMe21nbUfL+k+YOYTkmQu|#hyXnI2=->kf1$KFY581tFt%wYH}<~Ss>uCX6CB$2DoJVdh#+`l{7MQ1~ z{L(-I>NtRrLMhSuCNK*4Am`Ku3Xw^Js_*b(0mZdgtW}J;bL&ZR4PS5ZM3Op&!9Src zvw}i6{O{?G@x5VzKpR;&){CVX9obqzXZNxjy#^~4mI&@N&HAb*A+S@z+tCrtF7~=| z+}c?&ipu1L7Xdojmt<6ro{Yb0yJD;!JjCb|v*wWj(x5Gy-5DejvpvQEgQ`#Crtx4} z=`uQZq)EBa!DSww9ue?Pl6^*sl(s!Nt=TR49dPe;l-_~GSpYb{NWQ;7I<=shF;ccm zgfT(z%$52Q1YyYznKX=crID#aw!3%4z%EY;be^UP567N9-3qxkD3EL(GVlk#*}wHT zo9zQ&w9>+A!6(A~0F{f~&gA-nmuf)to5*X=(7O5d1&t6tO+t!Tza1v~YRf>HWkoLG z{x?hZW0!(48Wc~5L#bCMaqk^Ip$0t?x5m+F9xTronAdKlg}vw)2XRua_D^Dk@LA=k z{k*ColOz(eHhL_vPAMp7RAQD?1;n3#ulFVBi@6$sitYMB*a!>a*6zc-!Ynk@xILvO zvDPf#UFO}P@%zX$%gDKYsx56-482JUD|dxWQd!^?K5u-d)UFIPAp3f7|lV zezP>#8XS`munzUyDO%7EFXT2a$TerMk(52B4wyAJFXllRn(O4hg;V+EG2S_(lP?&H zyYXhz5}N4<&jnb%Fne<94ls#O0*t(poP^k(3QRt0agM7--tTQCN^|c-kf5SikQ({- z(95o9r#~~o0o;@-lPyffc1}-3dY}fNP(A8fJr(oF#R(T2gaQH`x_hWK--O|F?FT}` zsgEpNO8=&JkgTOyqvQHOw|fr^?ZH_>aC1#89I$dZMGd+Po$aJMcAJ)1DsHNe|JdLL z*}YxuX^~(B&onZfJZBd`3zR)eBBul945*USx^*T7{AkIal2_kP<_l5_R5yy-89{yp zVl_yCiMy9b^v@&z_{s<6&Yg$#-zSA*cnPa6Xo=3Z00V@kp@|1iCs)M~7cyDI=j;z&YF!RjTs9#slV8eIS0ej09UE*le$@A* zMR+j|lw@^7a6d97jJy_&8bPJR_(Q~}@vn7CYul6P8aY-QpucXUN5Rbz0Wohg(%Pi{ z|Fh&Nhb%Z5?)w2L7p*GM(ADliR)UfK_v5@EAxzrbbGkt2kqEFyCl!gP3y`kjq|129 zW<{L54&(;E-r51<%FBNysyD{*XuaTa&@@xc&Hr7wso)T23%KD~Q1E2I(Q!w24mPIV z!bq3~P;Srf%}Ks7RcDN5<6#X-2gI9=hq{2(VX$@rJwK||zhPX^lWNW>%$h3(_Vx84p2;3lfd$jI#eA1-zfYJAPo zf=-QH1BM_hf9iQfr#QnkG^uV@MD&2;|DpbTzWzUUtR&K1hmI5I#>V2`EW#o<%D*~e zUjIvNXV2J_GJkE?%OG{mpU}XKz8>fa^tevD8a(?TuOQEQEL!ztHBPt`!G>2T#20kNk1D!G0ol=& z_<39_X8-RJ`V@(;n$fwD4#m_9LlNBe!zbK6DIIx;sJ+({W+@iNN9eyX@8&k+N*98fTtcLlQCJ_MUu)^5|3(|0>@KM8g-0`V8< z8+^>lUjBSJ1l#d1?=s2{=KU{1Gih=M2L~Z9cw02uTXV#)I?L8qE#Kd>O^q`D(eC5w zCUg{MiV_s|$Z3gQOf6s#)3=4=+`nO})CZ6R-cul&TNZ05Jy5wsueLv;QKuh{F*my3 zykRi9tye3OxJolx!u&;F5YD1NbqVD;@INlK6t#Qa@7@XVK@6D(tM@$d`FV&++)l7d zp20A0xIs6Fr;72N5*8|V=W#W9Ulx3%g^AOw*%63Z`O8*G2 zA$+7+s*X7aGN?CMY$_7AvE#Zp@)iVrdZQ@9@ z=sD)war*2;wbjS4|Hq6ZB+x5PE?;@bM()buVi4|O?RmD2!|77y$(l$PZe1x{@+l3I z;TJ)e+aRK%Kwq*@qO{0L~GSJu4$F19lqWmY2hD z&6HSdMKmrRf@SMe0@%@os%-5lGpj zvnqpef`Lg>UWGh*|0Iz_io{|mA%q4<>RS@oF6-oF)n^$URrc8 z0iC-8E5-a>_W(CL1X$G%HNoDaXzb;s4Bsz7rv7}Jyl$UuN{P6h|y+M83!w(M;>G1Clz~~xh zL{ITM=_ol+KRGJZ+e4A>VWn#YP&aiK8>mf!;=_TTvsvP3$`W2!Pl;jaZQ;}SQ#~=N zHvz}%YWG)H{*U%&cT52kJ_V~)MziFmTj`SOKa z^6#f|hiB{oP30e~)!WrBO@GyMEdJYVdp(VaU)vg0+%&TH;cJ)Mq)^n51KZGU6D}r0 z8W|bOfezw#yyp45a3;PLR}Rts7f#@qD>7NB!kHJI5G@tl*2uq9z<5#lilCLD8zLow z!}RcQ(dRpq_#V}jQcv~s!e9o7(uw=~1581ua1o~tJi#VmL!#T-nst8x;V?~P?PBVt zf{w_uH?E1M9-}jbGm<$Leu{J+MolHZv7VVlvm-mNAJxwd7*}2;S4~`C3l|UlprEKH zy0c2726~+afA1(gnJgt+*x=Q|nEF#=qU6Z$NI$yTpl7=$-M^J(7({MG z%T7nEqaZ&l=xXm-8hO4D)pqIxMI>Od7J12Qd%NbX;v`o^{s#1(+UsMuTmPFTl|YXQ zup|#w%}Gs>bQTU1?Ovm$+|`hzPRdQw7y9a|awCs{SaemJx;?34LTSNjT2$zz?qq6 z*<`Woy-JSnbWwQYV(H1aFih1LHBM z&IkG-u1TupGwkMs72=4c;j0uXFTN?|5MLy=P*)ce%-;!~pZY;u`vNSK8|G514s2=K zWH7W5*5y#G^Ed}q1VWx!mBMv96L_C4!>9|SFEwQ<6L*ZY)LDHFbDe#}`)p;f@rXeL z7;Qi>S0@XGqv&k))${5i{&R-Rb(t_YtD5oBg5xk&bPa}((a^1~s5pD2++ zJW5B*Ro=&>q3{YR+G?!B08KY0`v!v z?x#<3G^BOY1MS8Tl%(P8UhC6UEsUi(>r2I%hCl6Q^R4VC+PX<+2zQ z*1d3w;A~AnM;7-)?PJOOkqXBo&qwd-sU*3l7Rw0cgVDb`_TeM1qek%OH4W1r`;$hp zEh9qQ^|F#sEdmg;<|)@>C}0zOEU0p3o$iOR|2tdpiqHysBN0Im>Rei!(cd2J!q^5g z*&YpBh>GK&;H*|FQSz>KQzhomI$6tkCn+YJ$d!@VbU2yw-�*6zW4CucZB>=}TmA zRw7=i9Xpc;WnON59WinYUCMGam@6jNT2N6!+5p4+oR;yopufv%UH$8J%w11be(9P{ zKK(*kv7_-B;SOrMkE@}uGd>)wHOtJ?fwHEkCl0n?sh2*@$65u3Zh#^Q3C{E?@+CtN z(15w|d#ZD_vswvVs6UK}|KVe#zyOC{rH|HKi3O%nJjappZa?eR86PHXU^n@D&}SW9 zRmb`E+?Dtg0E@kk1>?W#_I&ZtdiVnsB#U<-ROFxb)NKuE*V)Z8kpBor>o=7G)Aw zI5W*EN)iS&^n8~_8<{fT3_-_IBQ$cJ1H&dtGj<5y3*u+T>3^+ZD`Mb%7{gnWPl#2r z#$8-#W*&W-Z8_4DqR@4EQL;1lq@+Wz$H}1qn|tWqRa4pW5GPoq!~*_sC7%OW+6iw9 zV(akDu3?}L-osl4hMmJHNcHAKCNmi74!%sQUPK^<`CPHK zB35JG!fy4$3F#?@>w_=H)`nNTYsJ%84%56m2y39Asof>@PPZq*P$z62*L>+9Z>RBg z_>NN@dis26TRCjWYub=d5BRjy#h>Oc$e%iY;k5(1z5?L?F8CAUeUl+gQzKJhorZDm z(VVw%_&|}6Z8NS2(ywOLgxzdmrJzHqjMp!#jOBqc8+%&?2f7oW{M=esFqn)vEIgG5 zxaUgH&RbSku*$f)v^u%MvBN!hk}S$evHC%xi{w*HkPj=Y4G}>X_(Q~BeUpddL}oyp zqE-4SnO1QZ5O|k$oP~cn76$M^-VX%`p?^zdz_#8&A|R|7rSnB^AdHx5K{MD|-t-?% z++Q_7F=r<0@lE5-TzyWFWAi=bR6A2$33$;yQAdCo01T0E^Y2+#R$kfTT9qqJxzbB+ zbuX;Bk}$n{8oJrRUflm8_(g*BDHx38cAJFLnKE~oT(@=C)!ty8 zQ%2ug0IY&t>zI(nQGGkKD;x6pwpaOLn%J#wWe*j^$yP|IzwJ=$)WsL` zxb2%u2U2>D%rBt3EwJKdm55AOq7jKZi2ULQPGeWK>E(s@s ze8&=a>02io#-dUGd6I{1?(le!hZMD#PDyc(uuzfyMosbD+@!8Se=c&La-gnx(XP7S zao45p$OmKYBUK0284=6P>p}{ z&^ZlynUtVH!?v$dAdiLO4M}P(t9kjECqLcW`I)el?w36!efR9$J`v}6egbfKZS=sj zLY;c8PG zi^EpxT^WYs?FE$QzsuAb@*@j@thWg|i|NN}izw{z>?d*L-ur(IYb#}2^7l;3$-~mI z>$2{xO*~&j(6S|ao~CGovi!fsNVH%jY1~4g*$^5>_0qFz)|}~W(b~L2^27;DtU+U7 zynLBIMA5zK(aD9xg2!=epF1-FGEy4#m@F`%C9}i-_33*GsFBt>^d&kqyM{p*@yx?q zI17<0G{DV-2cU>-7g8i6$){oriQ1E;L}7ZJK6cYtGtPI77~03@Hn&Jvgx}?s%xXIW zY>eOKkh3(8tKR}Bv@r4&hjf_CjF#+miXk3EV1sbnL%I!Hjj(KXS)h^$SC+snB*!M4S=3)tXXqy{mXoxRjB#eW*65Vp~q;1c5BUoF7$lLumzh^!?)xR05x>FG)4+~ zB^4EBzT$FP^S@D6b7;pM{n<6Oq3e`HA>Y**FZeUZMTqT@DmE*0NNQ9$Z$h(aR|^Bo zeG3w#N!I3CSD(!~3kee+89G>K-erfCGwb$|+js0Za+j@%FcK6v6#psQ`V@-F=YFxM zjw}5=!OHt7ei2nZew}$4#y-tJgB)8S2t)Sbd{Td6GvQkoR$%ak8cNz*>?vk$b z1>Im>sG4_vtYWEqrMUOC1qsR7yCl|4j5yS$fl#bkFpRgD}O zE0}R4MMp6kU?o~tC*a{z(gU!L^=~rHBxIXZd(mj65eA_J$F^?b>2v>7F`2(hTS%7Y zP{L{)yn6+!-;;!D02b|M#(lhS`$c2QF9)iHsTZ%@Z6<_72GBSg0!6UpSwm(3zLu*r zM`Q(UTu=-gjq{qU>2Y3DY8yHq>M59; z>=r1EHsuiNX=nO`cf&8Y|1tj>r=vP|>ZafJ*1|TJhZ8|z@(=YBJfAx_-rq#H=Nr(e zug}P`b=Z0aXm&b7J96ifPCNP&D4_RI=4fYjxSXI;)myb1EXKX{gtQ&2E88$jovpn* zz3c$xi{|+!lRP%Ga%fG#JzT6HFP9Z~NnoOPR#)HcujTLU_=^rBQj6@OjLBjL>*86~ z*6zRnneKSy4T`~-25}}oYb74S@Qc~Ds#Dr++`vWV@8)rXxqG_sQlxYF1qf_%)GJzD z#MF`6ly)z{{?}#D@P7?`UF}}MG7Igoy^1uO>soFC(7zvo2-X&o5lcF{An$hq5k36# zE<01aKa0WwKpQxK`)eta&}9`^98ExV&GXTQGg_i!85fD8$nMKXNi8NYO>CqLH5k2H z`h?}25D_P#FeC^<@vf7v`rB&lbRGhA$MbVVat0}*0#tsN_fYo* zxqEI_S7Y5bR3N}T1N#Dz#n#V?(cpI8M3|(-u%5dC#LMszpML{X+f0qOZlri4JV5GY z?5c318VESl&insl934UHZw>K%AqXF(Dq|H=e;Oe&XUfG6Uh7cG#yO`ROA(}#zf&#~ zOaQP>$KbHtZaaR4XzHMOorZ}I?{aAr`eL_$(~w@9L}%G4#RpXzqda#oL;HNEsc)!E zZ`SQ}RlRh(X`(Ius4q(ry{dsO=ums#`+hmek}?U)luT5#Vlb`@eYFJ}KU6DU!cJ2T z^7YAjmv^r5Jz#4dBfeY^fe#%pF|9eGer0x9+DfzGTnsQ9+o*;+g#gI#Sg2Jz}noN}J6_ zb3;SLVlF^15I7$$3B%D1 zgjke3Y;)XYF1q;QTzpd3r*nRAUQK}muBxnPqq-J$;ay|`RC`>`(qY_272R0 zB<$4dzp$wpOpARg&x*Y3VGk7A99v|~CSiW}U zQS{#ec)-)KUc#V8;t~17&GY2%k4ch^3VGOyd<)s)KS0ECQ(Qx~lSF1!ucBH+%GkUbPJocKKa(oeeLnKIp~TnRDlIKOzCTBAf=xhykac%5Deh7f6>;42ZsXur2;!c)vh zh^nzibPFdi&Cn&JkrW(tzuR(r`i^fzPU1 zdn2LcuttRW8Kf`-ow#aR^MM z(n^H=kq$}2#1{KY2u(1-;*L;{t=ZGB>DH+-_Op74+A3FeK-|k_Pk|p2s zo@KQuV{<$8zz9qZ`Aks%2XYSs)f8RpcxO}+=-lG)ub>+&H5n0zVar~s*Z@ySL zkHiahSOeJ}XLACKmb+VZ*7m4?aRS3nurrH{0Yn&lK;ok39=@mQ_o(#N2?x$|YlO^= z$xwexDqOzA?H3AQtC6o!_U!por%`B{xN)ir`7Ms#L`k`=#I0kKp8o!1UNt+X&ckgvJD4ylwJ1ApgdcrG1~+RNy+{X-n+>*cVeqp&@fH(@ zfjXGgXbyl=I{$8-8d>~~Qq&PE6F}NKV)&L1D>4~vZ}0^dp^4nU1~RodAw+I?T*+bu z61LJ7|JRo7s8iVe9eXgmYO9zG1EWciq7bs(8Z|iR9B@yRu@n$u_1knczUbSBZHBNt zB=UdxWc^F`L7wv6nyO+9BWW6qZ4cmuRKH-+K6|-P6Vi7~50Z=~f4|?58ekCayn|;c z2o2~AJgP8GbffAZdPW#DvWQ6xJ(b(WW=#9}WexHmzbSEh9nJNvgr3E&px*joZ+ zc*V*`Fx74K#p8~%@Vx4>g<#6=z?aP)nCAu|f=n5%dl1LV_~*xq5zL>(2f|p8Zi6Yh zD$oL`%-$n1aU#t5snY&zt)S2V2?qj_V<@Mmi=<;Sh#Ksk7AI2k%}wsGigw+vae=0) zDWuW%s4>OT>D>gt)c0WD@*qR*Yocr!VS;kqN~1Lk2D^-TN20(0rQTpGq|$RfHfx-E zN6M&gl3b?$u{Hm2gJZYG+L&fcHu~DV++(f7@;#$!+JORPfkqT=_*~9BK28uRbdudI z{WS;NMV>ToNP={1*>O)x;jzkMf?2I?A3vP!ZwS7M7H5|}&q-rRMDb)-E)sq0kAuPp z*7?p)M-^1@3L%6@acZ)+q}H|ZnkW%g$F_{k7!tY9WZEiRb(cRSMp)xhgJ-JCgrPvs1d5 zrF8TRWD2ko%=??`uC#~kwmH}qVoY0>5)+j?OI4`+G?+`wToU0h);uQ-eK__lH5+pq z=hBBq@%DC1_!wccYhsWm$JB;lLG*d0dQrxa-X3#dS-2blp5)) zbjKobIqe%y@9Bw-n`MKqBqnW(#}#l_UAF-erGV23v?#M-vXSJ6BZ@_zqDj^0ql}!; zz}@&=JKawCB`?|_`3vrIOb`wH;YLCrt(jVcT0w7PSRsR{4a?UPV+Q!(HnrD(dFlef zr?I2rs2oj#_N5btSwcVkAp4kZ(9WATEyoIUHaX-CwgrFbB%bB^S9O(rlG0S2gxSg+LJs0Ke9 z9;c2ijP%A0Tc;556L4p}&H!XJy~;8~0%pQg{Qom2_d62O{WyPD-TN+-J}9Iy7G}s(sf1Qv!91WNJ?d05Y9X`~i zj=0lfl|G==!WO8#zt(f;Def7N+vX+SGzHm^DJTwoxs|kl!zG(mL9(R=ECpZOtXeEioRVy3{Ub^zSx_%R{G9>*YFx^&whPA?$Wq zcGo@}76^>#yq}ucN@wr~Re}Zr5SrGSU!XA2*|r9|%w<#QKg0%>eiXM~@m=u()X5gJE5X=pT7f~nchAUsL1P}!?Vl=)3ry=?ON4X85-M(= zGU#qPQdT>8cydrs>;gr@*Jmj)0%|1#Sf}~lZ~t3Qc)PoFVH`T*$Owc*Ot%TBzu~3Q zD%`ij$_!G;!gFt6WxbKMPyciOIatGfuprBUwUjJo0KT+{`jHNyJ_y5h`83S!MThXS`_tz*mbf~<8YVS zTTGhpMQ-dbFTYlFSmV+2oXplJsGdUqEvse}Tp55}zD{Q#st|0eO2i?`>R|UmMb|>T zf>1kOV_U-N6caKB@5PA(g2PQAA-c2Ibfl0>fbRx$QyGml!By_7U$|Y$UfWv_g?7U3 zKYU#kfUMy!kKI=DS4~-6$%9$awty{8#0Iav=rKsPG3Qw?SV!CF$0BkYG1Iuq8ahUR zB2J4;uc%@@#77S+^I_*U5KJz2aRri|L~o{@rNUrcp~@~DA(+YESYqF>Qv?02)O%|V z_LVHCc|8P+Kbi4C7npQq1+xpTBb=nZIEgJvwv8=3W1GR)K4X8Aq%GpG5M`-xj<4v& zr4i6rcp^&Z*-~()oQQ`BMgGOSEH*ZKv_K=#&qSCtgb5ai=o;9YG}`bndVYmbp0{Lo z<0CqUe}w@gcvx8!+iP$jXlmo;NWYG3V$ben&r^6w@${ixdbCO{{e;fR^q-(nc#x!mX zm7b;C)R6i!)%A~RV0h)15(G_|OmvMdSL{cK*pV#V2ZCP+YIq-ykG;VxB&<;weajT82LS zj&tYGS;@t7rNB-WNgf^-p?-8uUH>f0>1C=c*+8(?nr>LeV%i>YogWwc|IR~+TSe`j zoPKG?O)$Gt7yPWc<^?iAU*vjVgXK(Itw5aXWj;30eMHHFnDcN<@)){24KEq4R;m zRNaheM&E`q2FxU!>83SlCjk@Mv`uKm=~Jb-Hxb+U5FbL{>Z@`=2BtWu89Ie~$;ztZ zu5c7?EFsHKT(Z#0UE>3w@*q|$3ECS){Xsq?gT#BsYGudS_ia-ULCW(dEjJeC`D!r7XraSkGok?K^7 z73;F<^OvL6*n^Tut)K^5UMR>AVMjd-;QsUmN&N!!d?Z@VkKHRiic7*C8vM_YXt{GM zCZWRBxn?&6OQ+FO2dd%e&V3FS21)Gq{UJFQJ%JRIj*k$Fz(RJTy}WE>CVBh~eN)t> znJI(xJ~nFC$zN?mwKiY_a1@hik`aQ+N%kbw3MuE!rgF+VwpXwrnk!;)Cby(r(QMW* z`TXW?Ah}1UeqJ}X_($}N1HJ=w-EB3PJYZIGVaA@iaS(w-I4u&mZM`9(z44pXmbO-j zG++Nr?{_XhF*0A;eTw+3<)25dZSmSPT?yUIYh?lqR2WWZHCbdtKTHb(d3i1gd5h@iBf2QA$0{?rrg zm^fxMJxSbR1uKSl4T?V;i>(jZh}ylE^)mZ@67qmYm|6hhc#~OJ#8$BSigujp%Hn$( zhzf79mpgd10FdNQRS1pb#HAnIXM%Mt>5JdSHL|YO&i$H&ES^f`0~fQG`ZK7Qj+Q!r z9GXGOwOE5XII;t;Cd@k3JR{oIWouXZ5+#2lM^OBxC5vSvPGej)DRT~iyyX<8F5?7S zIO9j@uiv4Z@s1H7%(*y}w`)iytA3ru!x7G|ME@f0?nEU+j_T(VF*@wJ51b-}zoh%_ zxA0wL<``Ms1t|fcdKt>89;D6^k1aF2hafYIPQ=7^JioQ%p=@vs_%~glw`F1JwUgdp zF^1w-9n((s*w%j0NYz$z#~)F|XU+<76FNa(j-I&lK&bo(D z6$=Og&Amq@uiyXjp{~9bqq=QeX@O!E%7CNg5t&xW1`75mg|By*QN^~y2SyS0hfNQ8 z7*r=c8DX}u=cV&ZAPY6blw~t1jEgHrRWFQ%h|P`v|BAKJyATHR7}E?l6&FYo0(=a- zQYkfUh^tQsom0Dxs|vH=;xV_WxwgZC`_{uSl6D%+pv;!*8$^t|(x`b>*CR|y?~^J| zvVLcQxA}PVIfE_hdsU!SNRGkqXs1%ev^7>9Knf%V>^UKo9e(wba+aV+O25j0k(HkO z_uu*m-VudY9m}s8K#prNvXXch$2fwE#ukldX)yImyiw_LeQAb|bd9y~Om5kRPA4Z{ zhWid~i71dCE||m#egr;JD53i@CZoy)r5K`%5#O}U0@eT%w z5wYOYxSKWzs_iMEtBlRb*Ay`7fA@V~=s9Te9%C*fHq9=3BgU2mV$8wV`Tj3jt{A+AdFGqppkay5~ZZ@FpZ*i>LG(8#p=CRl5X3P4&NDm;}b>dXn>x z76Cpgf5SG9sb-^^?$5HF!lKnT={mMI+1$G0+H5wY{pufb-vy-`Tqa}Yv2-ZzOg{c# zfkkarxUxBbIBOs;Wm&O)pn=bpv5zhq{f693i;#$D?UO=7ElL{1vjXJ2_q;O_@jIM! zke0>omPnv!UPYLZm`={JSp}_?qDfAqVUC(M5shDEhfO1kP0pq0mwq@}h?4QGplGEr zU#zs&+`M$KP)!DZLEtitLeV;uHaieM13n2;dF3*3S?2C@Ld`})NwEtSzUH3}sr}|g zCQ3tz>2rb-1_rcxFq2{TSxbp@#F*3I`T&x1N=E})Xybhvv?F6+K?WA*ObB-R?JeIVI*Zv#yMNj)7;Q{%I zFYC>nH3yu(R3gQ>_*pii4(`##Q^93FoQt8bp+%L$;Z@#i^7I?+!QT_mQ0Ty=7ts%M zBCdf+7>hs~LoBZGr2+F!Qhes*(mtuzDN5eqU?kB!G`@A-m!gjm9ty;n?%kw zs_c=RJd%_oiV=|DHnFt{KjFl;1<0hfqoW$U^=M6`jKpa|2WSyzI$pV(n?KTj)e!L~ z`Zatxa<4KDEw7jCdrl8B;@%CiY-^WwK=D+b(iN-c$t~9D@S#Bm6i<4Z_b^TPx>m6E z7o!5;7br+eN^^RK+}=E|hp~sfwD~T=sq-h1$ZfWq`5;8ZxzEJ2O0g+Zvz*pb+MsZR znJ_jXm*_6h-2+zjc5Okl-O z-*Fdoh5i|lf#E^fcF(>Swq@6~tArsUDW@VVca|36sTYn@p;Y_|V4!ffLeNn#@zTGm ze|s2xrW3iNo%;;s^CxV+bO?u0CM8ufI;E4At^BA2O890&b&uW5s-jt5>LQCzOXdC6 zYPAPPKuO=!s_SUmOFjv9`N%O)u|2+!?7t2M0Xw z%EBr#gqU9ws#0GM+z-$JDI&L!UGXenC*d~SckEm*Zd6fJU4iq5yN}^pUS8lTp%M4HS{@B1 zj^L8QE$2$Q;U|JBgV`2iQ-U|AnQ&f-QG@O3NBghvzO;ZSfpv zc)|Nr=`}?a{Yf~m$m#OU{?fdQv7h(X*-UrUMGfjOnGEv-B!4Vi#6)V&{~h*wT(`fU z;$vJR7_K5oMT4!$c=at8`)!w>wME7j*W(@^Gtkom{m=_cnw}T@AjG z(K<2vGLV~y{MgLBoJCPQ0z2VK#TWUk`wB}VFTuhUlfe2zOd*V~2B{Sav>?1L#DY)* z5Vp=<-Mu5}Xt!+-^bgmG-5&jLV=#KVgEV&QCy`%-B&Qqs%*?|QkgIhMcjA302_4#7 zsyWycAxB-5yv*7rFeQDUii##zkJk6y_jdC@RB7&=s}g}OBN(q^<2x@InX>7P;Ob3M zpgpQi>xW#OqcDnvk8+`KWI5tE-U_VV_$;z-WgmsA{Lb9|l^Ui0Y0x1&FYxkuop8v8 z2`UJt?XNtthPtYu+WhSTPNoej<-p6wYwIj%-Y=}@>$mgZIyNSU)!?^aNLTC70ll&@?hy}0k#)_BXvXQ^i))NwV}qz zt3 z|443HX)JsW8S~u+NYOOK2IUD;vcWz4QcwkrHI@+1`o^La)pgRs%fhZC!(m{^VRD|g zH${31c&v5Q6Vl2}`ffvtDRWaAMR|8t?jhmp?>k#GRcoTUzZrU<_xv@%^(_A6w(;N- zQ408S__i+zn$LgC5T)3Uf`0M%L|ciR*W4WpL7%iW>pdySBP2yYCl-vuk95R_^zK2m zDEZa?VS8sWIV}un@0S@IKS6}HIWf~Roi<&oi8yOxHujvr+LOt=DWjl z$?SvK#*AV7Rv&-witWK}v`>krq3kf}lhaXIVf3WO8-ZZJ=?ZG@jNCC6WY3eMQ))UZ zgT1i{ScT@tZ^@S0fIEuf1VC_x2(@HG&Vg$#9$`G_XCJcI;c7rAfnvxyr+w_Cz##3i z)`2e_X%ab#&QLw}1_$phX%TgR#nPNO>W@EZ!XDzAEFb-S=lnSnkX5rV61Kj^28 zK6!iwUM$?AjXb{R>8&ilWR(*?pC-F*kA?Y(mC|N^wUi+53A2-8d!Kja~zMG?cy2sAkYM?K9)L)D7>75gqO0 zWzG&R9VCY-cEiO*Sbd~sc+0Ax_N9MB38G4Y9}Yk-xa`|fHbIaY(QZ+(f5*HqTGRN& z)(s^Ajw+A@nmje#;;3OuHuhzcb zU*Jqj!mqe7|8m?b91IzvRr7Bz{2uNK5 zkb*w&aFxSyO>nN!ci?sVHw%D@xR>0ktd6M%RME8o_h1&A53K>B00+blQkF06A}TsR zd@CX<^@$^2EiQ*p zx7LZ=ocS(;xQT0iY^u?m&>>j_{=a?&Jpy^I;;~S3pL|rn@SGJyy&|c09DheBpH#LJ zjNKbe9%BZ)P8!*<)jTt?-YnT)NN%kiMKHfnp{#uy{6v6n^U+Oe67u|Xi|?=D9D8!e zRPwJN<_0y-VB5RQ>$lt;gbvRB-z` z);tRRFad2vU(NfP(-nx9K9`3*!+Hvx{A?Vz8~w%G;qs9*;g$%;d*6!;l&a!(&=uh* zd>1x$!3Q5-(P*&L-@p6~qPUeCgnp6DKmNXsz}c0#weU>o4&*r#M6ik8GP4TlmmePM z9Bs-}#nAZ->4f7!+TzlNZ_@wm#mIm_Ok?=@Wl!KHlF-a_lwvrCOj(U{L~9mqpZPbi zruN}yhN#<2*dHq(GM&0fh+ zkO|0L@hxdQ#tDR^n1*b{ah>D^1^-UYiHj6xxH}sedyEo6GNR zts!=N*o)5cr&elaxQ=j&*%z|VLN01VM1%q|K+%5zWOPKN=Z>H)U7z-8Xsi4W*vwQF zrj7`NMl<{n>_?fgnu&Q0wMZRmupTMfnAg`jx;tg+NGzj{OU+#Dj1HSPUbJo+P^RKU zr~}4ix6$H1QMGxK{EHF+AWdUgIaMild6I`y5$C@v=et3SP`#o)JgAGD5RdlGhvLuI z@;YG*qvk>2XQDb|dWS=Ud7MP4+V?$}w`0Pd&hmTVYRRDL~aRbmbaIzOx&RMyk7}fiMIy$P;i~1dvlMQFv$MHZ z)>E5f2d?3MRcYVLE2xhp!)gcyaF8RGC8$ggPM%WTgskL{3ndYyiirUpv4L{~ zYQ|Gml)rlWj!g>^u2sdK>&U6LGNp4qGXy!sEj5$fBdlluMEcR`B#AjoEQSF0BpuDH z=gm(Dms)6r=&ZgLqJxZu)ai?T6cnc<5h*WpfPb?MMYlL6eCVoaA(kRYD>TrdKk^ElBI9o!N#|AzgEO&AZmSW%<){Q$@A)FPacD?L>FRvOjj_+T~+BvD*IAMrI`u@sDUL-PhJj-hOVuwIbHF8fiZzpm`MpqwRzWB`bZb3^(MIrPGUzZu%P?901a%< z*Tu-@S8J>>H1s`PhHiQ4o0Sa-o^$p7QM+eF)vm>z{`G^R-zKDFU7pm`)>$zMT_Y;x zbr}Xt_cl9cGe#mD8gv_kA#^oA@V3DP%uRfHwZqC|;>r+VbkFv&qLCXA42L6YDN{+h z7^LE7Ct8(zXB-Xc=`XuEl*;c*{4e)XHZ;Zz-ML4$&Zr<=v)0CE_xR;GwnlD*u%H3C zT|^Z85I-3XN>@)rBduszuBoPrGR?YAEUde_KIowsEni5t{V0;s;mFZ3#QxQ}ifBb^ zWta_T)8}u0SyOID0q7uE@bGX282HN4RNU8TX`rMta`;U5-tbEb=t=X$SK%Ba$Uo3B zhCKDws<-RQs^4Vr(5um8VYmJOkjnKFP`CxY$_IkyYa)DRv0C&klqb&7W_khB&IJj* z_9iIAD8z>jS2Ktjkb@nup#we1#ov0C!K=+=EegY^5|YU$e(ZV-IH93S;)yr zbyRmDwHsfuPe32kaQU{j;-VM1fy5(EkZI2+Uo96=9lQ1!Km_gV{h)5l)=5?7bg|Ug z+;-H4o1@^oJi3{8!?u6^NzOm|n&Ms0 zUaj2ZpO=>bQMaksrbr>ke3=09Z>ZG70)Y<18F&eDjyIhii~AJqsP=ZuloidS!}vVN zdhTWXH^@6xTG{7UH#w+KVP#vIC-J=09U6WhGm(NADD*O*H26k-H#bdgVX?Sk%a$q% z&0vX->GuO0b4K*g6ZWWPpQWw+S)QvNVq>rH#WJHYw8SE|qs8yChM~{b*u8)@Fm!uH zZTnTD8f3C8K|Zlq53|UVfO0`p8k`@&XJ%}Aa{(2_7&4b(HQWZvdeIbYMSw{8-PP%MNX6V zRCPN0YUQfx6C6c5Sshy1Uf1#}*Y_13Z6Hqc_L59cE35IYT9@tB7s~Dnr}KrKNjq8t zWZT0$Dj!X)SO=5E%H(-TzTA3pRw0ad$3=(IHyf*>ucvJPy$AXk>~pSUAwt;ts_uOW zpk6$Jk*eV60f6W&taXgZk0Cki+jA}&1GrJJVsRZ{J7IE)7*#%^6)F1G*t)s~5pOO+ z2u2HaG8XWnJp-uQ`FTLc3M1Wc^2 z`rM`#v6c%mt6xULq4Bk4~0-i?(-;bc;mCfuT=Cm z_gTev#kD-AIkvce<40f|K?!B(5Uk~C%+3PEypkMTyMXyWiIW}sea3!Sp`tgLQwh~iBZ>>%I zSte&~+XmP+RwwKWLT!Cve}p|=V^7~_UO_?+5kXS@epsx3Y^==xp@N9yZFP~3M0p=K zAON(v0-+BQm_>}`&DmR|!och*49W1+R(a?}=c03pKgHhq1$QymZeDzmdB{d9;&vI6 z!cyC$UKB{M?>`nS5gcL9aFXf15~KbR?DmX5X}T<0ChZw1eY(j#{;<*Y83w{r5u(e%bQXCi=KP}xaxx+GY8UU%DTDp>EDQrW?8PEbQVm+i z0utSjh5Ixp$b;G!R#{@^b^#ckhd=87W0mdGLb}*?xNnO~a@7&_Zsj9-K4*=W;SxFEC~-tmC+s0BgHUKT~t>4~Q-XB>!p>N&Go= zAp{`~KS>MP39=T%5+YgU!}*VSQO7wVk;Ax%g)T)`67{sFIDUCdsQl^Su&+)jqx8Qq z5%U2aqb}2avEX(C5&sdR+BDs>vF+`P4rPP~H`ft?&k$a+Wu1&Y>u{*C+bY2(!Pp?Ao3!`D9d z!*ap>o_I8zWNeHL{!OFlhd0(0@)rMrgxq;aMP#sXmP>>_Qg`_7%79Y^Ox59p7jyT; zr+!DHfl<2-a?Y=mo!WNl{LypNe-_H}uBP^*nN$7}k)bq%Oqm@26KaFM&aDC&MS}oq zVoA-5J0nS(s`*BBxvhaYwQ29$LD36Yd2W@~ z%|sxkbJopeCdKm1sB=eloN@(_Y&f$DPK$gYh4I6 zW1=g2{{x_|v6KyzS@EAtSFg%Y?z>l3Gif)eqLw-{)a13X@w-GKwu=Rnh63~*z$k@a z89q%w!<~E9+W~A=T4lJ0afJjBC{RZ&b|XC5?`p3`1)h{3Whh4p$`GN_OI=(T^3=Wi zUuyx~V(ihoBeDrbK4rmzsnOwLuCY8@dI1YE2N zb#O}k=+EIq48WN-?7E`mj1++IC26$3rWqj9mob@X|6ZJ+t-cq9S{@A62A22Z><$Tp zmRp6}Ej}R7Fz^*+$XU6WP-? zXCwxh26)2?mrHS?SF?^iss5Fx-W&g(nqtBdmB7eqVNWMN={;~m%*`KrAW>lb7Eq>S zgbQ|kpMWIxng@jeRbj!7-b%;n?9m-~m@BFji_Im0>h`W3fa5c6iBiw~ZygeEPp4g6 znRwq<9eb-)c$tXSdsNYz2qkGM>CQ?Vhj5ay7wm;iv*D`5iB|%fBSrD`zSrf2x(;0W z96S+XaA%7OXg_BU{0)ckW6xj2|9Qop2yh|maMtiWrWw0{>M+bM74a~ee@6$){&Xu0;&Z@!g#dfIa2GF&rD*Xp* z#N9D2e7NzfW$h>cGh^KG(&js`JlwLQISJ0KdQY4 zjS6Q)$c4_vzM2sxO?5i?-^)z))$&k%%@hp?(LJGEX(~eYvV_LveRM4-RaE2%xl57;! z@}}A?Z`kj0lL2r?!6dE$PZX|&p$xq9eX(^pchLvSJo}3G)Ht|?YF%c#YFnN)$xx$u zL1@~XSbUhoI$_QEc5);$fGNv!LhGo2uK_;M&oJEpkc_}t$5MvxUZys_uua5wmQ zjy+H=jQqhGU{3Dl80D)`P)#S{JzAX9QUUX^RSdL4zRS7K!!cOZY_JPoknHycxrf;ShPm6gxB{KKhk7@}FeBVz2S0 z9!(iB&hA45?)p0<%hNN^8#S zZuH&dd#R6%M53i1oRnOvv-q4FitCWR+dg3$?K6+Ggz2!+`@60m-q!|KxVZ^5_a<~x z9;gcDQ98Ukd1S#DM@ntRQzvOsQAIHm7Th}axadxa!xkeE1x15-Yfl5WoV9oWJFV?^ zckJoP+K2E-N?u*KMa2xEo`7^+gu9;PxEN|Y+!`}Gl~|k-;_-*UbWM1<*rzqI3A4p= zX-Ik&lZ_wx!Mj;U?Rw9g90~`k>Zh3GWlwQAwHoGl#zgBbZkjJG5XK`KieuMXS8l8aO?m8Q}O@^fh4_DC`IS(-S2)eD?y6syaSU9wt(#z z>ps}KRiy^`IS_PZeTwc@hac+gK0@qpqUvE!$znY2pj1%CMwsR{ghV|a=H0NI?CDK> z{k1i#GMKHqyQH?CmQgAg>7(5U?c{-KtF|3F+vAS(2{h!=&T_g<^#2zon+-5g1gt zSEzi76j4S2?0qD962yoO)n$_&M9I{H$ieM_sT4G^oeFo;{P^4&mc{``G@VRiqA=qw zD5G!c077xIz$*!V<)>(k>J;Eoswm-%L2=ADseusyl8*i@%r64^pJ9c55bZ>Oi1gHd z_0A-5wtrk<*>LwpWZUo%(;|FU($H>&H_PVxc1(};l(GW10cZlR&-z6paX?ve;Mf|7 ztge2}UpI$~{EaKJshfD=t^c2#Jo>T__ab9MPJm8dCMY5In;`@FJ1D=$Ys6?kWE)0g z;lki%X5f4H5fOZ$W}IHS{ix!0IW)9z>u5O~_f2%Ry5F9oFd8MFIGudX2;bVJz_o7l z1A5J#UG)N42;EKs&)$z5iM+YSp^J1&rgoXoE$XQsfM%8Ns5S#qf2*G+EtZVkWlpFU zO0{=-vY!aSnhMPl<+Qh>`Vb{-#BuaHwX$LyTggfpqNwo_!@s%6%=pI;FKJ0Ey@lvZ zK3=0dt^+SFl|RTb+16B1k(LJGH&@YQ`sb0jqzpDm6BlW{wWI&T(pprDXW;y`m76rx zwm%wkL8c`0Z9J~JcVr>`eQjyWhEp~MQS6}0F&V}XjL0{&MUIOs#4rb`V1+kK3JhVm3rE{M=BsA2Sg&t?8 z%qipft;kQP`L^5~iCcTKxT?`!20|^4mL$(TAnti%4^e21`KUzJ_<=4PHrQ*Xb~@WUukvB2vqA5K!AD>+c|lTk-E z?1n?T_NhA|pZh|_X-IsB3kJ>QBYT~)XCfY(wlcjSYOM+Ng6k{kSx8d41*Fcnd6xl8 zEpzan2|f<#oT)tFQ3zzJMqt5!1P(Spp-1W<$aDMsRNSzy^#WJi6y%*oC!uCfNc1n1 zi03>9PwLyDaJIK~NN0C%KlfNFK2hm~R-ShR{xC)5%_aF8l+q!UvSUlSF$1Nyne_>OZ zISw`gr^4fQWQ>X2*;=TN;Llp=d8DNJ+CdJ%#N%bo+4Mi9%9Q*H(e0(8cK}sAod}) z4ts(|<;!THPIlv#7+rUQ&Z*w_)h4q2?AeBiyXA-7V9F;d^}${%Ld!RLsRZ2ate|{> zba<`!&MF+Kl5@ijNYxi*>ddQK=Pk+b7=};ym%NJGaz$kX(hW@T^X zIz-X8M=5W5++FTDzIl5*H$ujw7%731rP-;7ne5h{V37Uf%`gdph8kJj8Pw!gH0W~a z=wCsj_915M$bR4vm%bo16@#R|I(0ca#te6CZnYNCgyfB3EIiWw6!Uzx+7Ix3V;}}J zv*IP=ttVALJqZo2S9{ch_iA2U{q|2ooL12dSK?fp)&&R3hQ@^L{3{gmiJd&2yQzwD z*Hr~jMimUqv-isc)+STkGD`n(KBkkG*P-#$;|9Y$0&BpG{M6S1cf(N)2-gckTW0mn zo&^$ad7UenIdW5)a z?NNgupWJi6(}zw!2H5XK#&Wf$I5LU#*NBQHEQzpg_`VyD3$`bH_G-P7D)*%QgmLw~ z_{SOYVLc6>nqnXfwU9^IPHP;rx~v-#Qk5ODD*{b;2T_vwN zgXi-N5XqNMTa}?`$|@`rATla-&c%7EQbhsJ*kDXl0iK3EOR$>~le;f21qW}EBZqnw zoFr&YzRE4|9DXX5Ou@%QS*zZno}Xhz^*2=xwi~uI)9S)mx+?u($QXVD79*2DZ-eyK-_NBGzglR*Et<|r=>~2{R~AaL_%)ph4I zPVOa~x3sg(q1gn{yTADv2!$uSNLMe-r9J;V9*rgd#NRGQ3mv!c|F;Yl zgQj;n28g*<0R?zmj>i8b9#4-NpfC0<0zCpR@iNv{&p)?tP5WkfXDQ)j0;KQ0lh;uQ zuOXRkrs-mK|9Y0+|<){Il>;LOFFh$Y3&WsYj*=txgJ zeL}#v)>%r`W03!&r)(uu5NT^uJ5FTha{uGy%(r-JohIzF(D9As)S93_X;)JrR4iw2 zgqt~N_s}YUA8hC>#;Z(5eB2-m?en_Emww|e5pH>X*q`#i_Fx)i8fg{XI5Scy zzA8aWpvw&8JWV=>t_!Gq<`W~*Sxu`W0*&->*?W$Fbos<}HoNLV1NH#!bjE;^DrDNI zhfv1>CbXLH$P(KquJ51!!3ct+5SHr}-h#)Ksb(vsQJK{14km`zazlCiXcblzCtmUJ z?O&UcnIkguh65X;@Xc(+#XWkWQ!8z+EtamZ2iN!1!79TXlfC{dy^j9SYw+K)f%$zA znpmN?R=!y}IhzHfLx9!xm)L6v!%KOW;w^uGNmF}~BDoUY=bL@)sJp9VBf7}pkT2dx zLfy{*+2VuDbVY&91sJl3{0WX(Pk0pbPy${*HwpByQ??Gvzn3*YZwQRRjf|1;=Eqc!H(f&I4d&IyibR<<$DK>8>)0ay)fBsI`Vro6I`=6Sk!DGfT%# z>mBNH+E59*-AS)`Yh4v_=oH9y69q%o~!0N?d{aRdbf`z-v8Nydm2qW%G?v;Zj{~ZGqVXI z0DrD$_`M8+;6usY6K;kMR#2K%PMKDlK3U5~Y~D>~2IZN2{e`HbbaOOCZ#D=d4q3UrKm21$GK{K*jq|7! zf$&s4VqPV4Mt5td9R>4dMHQIXZ;=XYlF+9EvV_&NO1>8YiXymX?#BuU5(%Xku;+#A zuOa5bpn4>zRFMu`u%;LJNUHbom7q8t;-FCWz{_=n>1mWY%jP~VTaV{sw}HQ$T6M9T z(~`z_d8U|3si#10WN99F+I3~=!c&?xWn%oH;Q6&IgGvS`&x%>4sVH0mbG{iA9YVwL zuO2?Y>NHmKP`9M?x8WyoNR1M}5bO?5JmwO}VDCue**K1n66p^hy~;Lt^3gSXuT;uv z-Ue^cWonSzoRlW$To1$l5ShrVmwKX!J!V_w1t{0yv{!aP6f6q_`8h$E$RkQ?%4aLh z>pFUysVdxWf(Cu&XEv2UK7rvf=*NG(6){l%_l@pGQ!sk|DsFhygmrJQm3Yls8poa% zh?&?iB(jrVQ>H|gT=X*iv#f%bz8Riag2a$MMjxXSX2)bkkeR&S8hSUSb@-i^?JQvF zmDx%UEpVGTm_9ekFry3l@ZcU;9)9o1j!q~?hIuvvUgWF?rT+>$9KQ{oMCy+DW@}>w zkEeIRt`9BolUlzK?ZmnyU~8h3*9uu*f(uxT_xxzG?p zgb}}?PSO&%wP(OzH&>2=TgKubIg=PMB3XpuJB!b0CC96nyOPdJlsLxW81~WUzMNd5 z#X=D{FqpS}((Sj8Nq|dH$4&r}b}T*NJ<(6A8SznDC0qUzOctSs1KSOsS}l6(ag;4C z474y_1mFg%AC?(MG-wwsAwxj#U5B1(Ur586kDbdy<2#N@N(2xFQ!th+&FUQ-(4E#M`vs#mB*xjPO4w=c-mvFieKr;`&B!Df zK!qz*gcpllzcywPVU!kSI_)lApp0C=x6o@nf(hR#^3z|=5mM*n%VLsD1S3L(qEtjE zd4wVAMu}+Aft5jc>escC{Xdc}#V1@0-4G_%q(yBkpb)}?1$7T~0AaXQ%li3T_FRmg z%}d2wLzh;e>6#+%cxzI{c$&r=Iw4#F-e|8(E17H|0u~!0Vzt2yHk9)}d3w-hmLN7- zLc}HZ_VI1}?k{P~337E!fo5Jlj7+l&>Z*SGXyJ=%5Tk`EK!QnhqTjfCh7p4@gXPkV+- z2O#l0dvPu4p&TLI8*p2yT9`{PA=eWk9mnVx6S0(WxXty`YdF>u7bayXp$&}$*mAA0 z`77-DHOe%NQB~**RaMGguU>(nF|;(Vu}Qc)Ey-;>kyU4`Km&#@*2&$tZO)~t^gyW) z&&RN|P8~_$t1p2hQBuL4IC4`3(s4xU>&DJ?XcEC=mcRe-|7SHv77{s2Q$>Cbw`b%w`_Uv`s84|%mAai$1qYmv zPW4@9GrpQ08_aJwEW?`H>y;0Y*s2%0fZ2h!ksrs3#WU4iWeVRe*SPVQMZvkd)#q;LJ zuR38^*=JaOCR`^%mz|HK*cVf!W#eRzQ|q!+LIBqE$TjgZZQkm-tqmSIiF~8#IY`XQ zW^_|Ijl^ML*$Nk<6lL+(Q!Ss;#A?`KbFWyabjT~4VMH-m?jES0-=&Ia;nsmubTrLd zAyqgcbIB3&YA@QX06I@V!6UsJVV6{3@}rBId{ zLjLg_b37uC5C24E@u9z3de}fc!`VY(K(5%F_DhCFQ(m`ub%X8LF)&C_j zAi&V-B>%f;g2HouWsjv)Or%LoYb)Tm4c9>|lZcHI?H=wAThYk?Ep*PZ54Lf{3)?Ok{z7vq@uvh@w&}NP;wYsQ)+WvW_ioAfULY&JdhK1{_l^)$rcc%4Z>cag z$C4RfQQR5XbInK;Z9j{Pb5$TS5NAOJjnbU73!55}CE8ZnFRs?HVam~_!Hys@v5{Ri z;7!6p-$|l2Q=~6ND-N9e|_GSvfI010)X24HaRYN}#Eyi|jOK|$eS&Bf6a1h@G=GgR16sR`6 zX*N}_TfFz16eP-r?Pgy=){Zu&tpykYLY*j6)U^Ek3(el+uH+{hNzBV(Q%cxk^))OL z62+NK%!;`i3!=(&IBR;=krbzazw@H5!d5Pqt2iiQS$U2W_-EipZ-aKVhQ|FI*Y=@@H|UA|$0u;& z&$(IX3FDuf?5)}O%ZcnaZN~T51NxuyS!Ew7#Bp+DF|}(J&jPtZiAvVQX~X}Epx8VN zf6mmSuD?s7#SZdzJ+x>tKAr01>wh(C>Xa`wju2HK&{FKhg!0x<)9qoI=(FO?2|Q&Z z6VT25d;56Y8_8b+M=wpfRc+cdsayNB@AKu)H6=DnrrxcJBh$hn{_TA&m-;U)SOGE? zHupT{gX(kYfML5%kRT|l0_jk=vvhjx(SS~hsMbhQdsld+k)RE}lXZ#6L&3EKGDPuz zlD_ku32}#eLD^6w)D_1P$`12l$IDwCfR{} zXVQIoxk=?zt)=n>u>=CYB7{R$>pqCR8dpV0Zd_KWe3ABxdo!|T>-Y3$I8h;*pjL5H1vGqar>U2lpmR6mg*c4ee@eil>9c@9Rcs*Xs|B9jJDH__+z(cDu-XM2l{UQ{XLMl3F$4wOTUh^@AFd~9l@PW(*4t9k7 zjG6;Zs`Lath0c*;t*ZNIXp7)_UtPf~Qm0Jr1L`Q)M2j_VK={m1IL{sN(YDw#1sUdh z0->NxD@AQplaYHJ$8#}-P_(`zLEf0EkMr(3a4ym(pG`&D1rRg{+m9J0=ICf~>I}tM zXG-jc^CXEIN?=FqZNnyRA77P>&}v!i|4x&S{?YWZ8UIR5uKMuVsd!lAQ)$u2(mP%p zcfs+EuXfKYXt+!#>To|I(l+f+F!4#oDe(w_W`9TPm`f{{DJ#7M(7+Pc7J*qu0Y`ae zA@LgsIds;Dw~np|ER`CJuOdrhG&N6(r9N|_jWSF)-R=*8YAA)O^BG6Vm$apZ##!8w zATl$1%&~h`N5*@bImKZCnb4DiMS1K`3zX;L_RMs~m-MvXaTz*q!SO26B~S@qPq9) z9#mf}HH}}FGl1(QC~nRTNs)bT0U*3Stcd>|$26%Fgn6^^FyHW>;@ZprOwl%(twlSq zr_)NE2?%C0vRa2y;0Ap~l)xf$2?OIy=Sky?<7@&$Ze>E;seSgbd0N=_2{U~=!5GNL zb15=+OL|&{Y$KD+w647}db^W92|86pvazmeND3<>Sqvbj7Cb)1RW zi)s*LP`;ol8t05ic|ea6KD%eV-Z(C@Y2e5|e>V8Xg&!V`C=U*OK8KDhC>kbi9pFgP zf*}{YAx>#GoU$m74?imK*rT8 z)RlEjlcvYEZxlMXH$E#xx{#Yi(h*3TlT4luI;#QNj;{U*2macH_cjN648`}&nQ!4& zoC^GIve*-FIUv2GWeVilx$Z42_zxh0zZr!a;LIo==x(t}$31Q(NgLHh8O@-v+(9iE z;jIHOgUA>Vo{KsAepEhWDCz~kWbx`(5R#pAnEnsp?*w0>7yu4^s5my#(h#orahdP$ z9r?TQ$APf~5t4^#V%;9Hxk@RN?3}cC80Y>qM_O(d;=cDG0fxrivpWA|LZke9PqH!lhY^@v@rq02S_OVATK`LIu~ir)@@xEktXXbLB(#`%7mb z>0zuO2j{0u-Xa^!wbC*|@WPdSkndaYTYe7wzm_37jRK96DTahyUv%IO57~ylkhnP? zJdbqW?<5`1e-A;8LhnX)Ef-iqMc*EG=MSdsFtaa2>l@N6+ag<&u{Ig$Zo&|6)89_V z!PVb@Z0(LC{RqLDbbW42ChDwT^kst64)B^_BA?_o<_@y^s4?)7LjPeGY$t4FQ|EKC z9`wEDHxTRy-kVRT@x0=);lEBnLe~Tvh>hI>cQKClf+bV&#!gI@xA4=sBWR9~wbKTj zn~(WooqL|LwG`xtx4Ag`ok^ggE)Bv&Flo5lIwubMLRA{8Zi8hmy0STq%eac~JE^ ztJ+1!G?1K-P0wL&%>#&tR<{ff)NubOuU&WIJ~`~C@Xc!iU$p6$GH+drZ#g|Ov`J4L zVl82D2My=olsv`kWu*CYXFaS4ywi4MwL&SOp9PvABiugXF(rfQ3#rs4xj%3AYJ{d| zi{Z5lUFLtPqjOf6wlWH)iEmwAS!VXQX+#;}o(z~^L6-vpDbsC+e)b@PRLx58CH{}Y zTN)v}lS&H0RAbA3Z4I`<3}$1g41@T+@;x9tC$+u}Ir({v+B`E%yuPFX3*(H? zva-oe1%8)S2$<>J)WFq)n5j>O;S^T%`SA#VL1{EkgU8W+5Ry5Ew;pww?7{2T$Rt6C zQP)dSGdRJuE0sKV&e*;o=Js^bRDo7Z074iwQi9vo$ne5^G+ee+%c2uutl zfikP;R(fr*^~4k?h#uD$hFKEra{MPtc%2EAKBMCz5J#8?(zQ?e+Ap9gHRfQaSw6z) zP(ISIRU!zv&U`|w=6bONtQnGE5b0%*wZKCdPVB zs~D_{YB4Pz_g;-S^d(=Q_7xkvZxxqZ@|I5dt{{Mn4>E&E-y!g~Y5`egT7+DrmW35E z#q0^cKD(Y;qt7-2MCSB`ur!C1lOSEpi#uq{8a%Ch@oLEsy9emS3B@Uvto?`{~Do=NDynUJy!w&Wq#6eHFzDdjefMZJrav@9K2w2%5}Aek|M1g7u~<( za4$WOVtHRBU;~#I?4SUnfN3yewYNGew=_TwcxV-Kv#;aO&zcTk?>&`IF)y$ypG2!N zJFYhQICsQY-8&!Ukodr4nj_Ypq}xN0ox?9~QhPL;gH^6ekvbD3SN0CY;sM7?XzD}0 zc*@|&N{i-P)p*O~COegEZGf$uamIq7ngXhyZc+zQLbbg=9nVe&pq&+if??~4c*2d{#C#n0G>kBA*kdKl}yK!q~6r$G|EE>ySciZnf4? zNrga+W1B+fQ;I91cMOEWc-O2_RCxkVVi{Z}!&i9BgfezhsvHZLtiSU8%-r$S9C2S8 zlM_j8{|CcTPV6D=l>AqMjq*lGZkRuRPr>od=e#+ImP*63nBhnVzGiX=b>?>zU3G6~WXW)Z1NLv1k|S%Vvi;i9bipi|J~HL5P_?p;VdBvCXj}F%me;S-sG{^5 zoF??ix34S*&(r?tngSDMP>T{Pvf;Bzcut_$gSGrmBfpvi*A8RS<&uU=QtQLKu%n=> z0ohj9sH|A&I_Q6kN{(qQ3CT@Rpx+%IZ0zO^pJc2P#V}#528Yrnm5IpNx>z#&#~4&zC~(H z&Eb<~uF`PfWs#Sa~9kh2r{RvPc{ zP#$2XF}_Z$+9(AyE8s4qDHl2~RgVH;4FL`MGb%cc)(x5Gw;&P=IMePz+H39yY1E!G z9giK(@){qH#X!cE`+M>E?rjR_N`@9(Ig)BIR7u4B)I+`fx{jvBv3lWL${~I4upy0_ zW?L&{Q}+pJ1Q$O$C#bd~naSR|jO~xiQE0E3&_dazv6KE7@emzSh;jJiWg8Vx$uA6lQJ2M5!$gg}ih!!s}|{C1m9i zet}**taJG+&h;k@v(pYU=DAaCMs%f{ngLvy(V14$Eet1#?|sI0u1Dxn1t-Qw0_=;W z5k;!C?dzWss-b?~&1`dSG!XNOW_*`p(jvX22MCq1i*?RD4w1|LudLCfyn3O}90|y2 zFjypy&?2+_qVnZ!_A7{SCm&*D&@g_sqB>W$mCXnh^275n};M)gTpQ(^;5C?-w-e_5ITkTkYNLj9{`pEO!=ZriuS49e8BfHxLNN_3-B(-KBLmy za481DIGm(W^^w8D25}t+Td*z?D%qCB{KpILKVL`s@D=$3S)F@9#LXkP)>ECH;>qM! zP{P^x7d*^KrfN)qSkV2U4 z%{bWS_jtGeM1Gp2t!(t3)RH>$!1h4oj%s`cTo0`YIacI}#GCeAep(Ow1ZXxN)DJ(C zLuF^<4%5-O--|HhAaw!0S<>-1@!ZuuAV^5X95$h488iW_>Xb+rbo31Xmpy%iMUb=S zWE!RFpB9FYAo4h6F@;y@WAJsk!|-il=%b!0oUT^>yctuFyiEU&?A3K_1yHZGt#v%~ zD@gXOy9x+Jv?JAKU7eU+DJGc>7uLn?cHhw~S3@{o2ZWTE7HU1VUGWv;{;+l%Lcwqt9c<)jD48T zs^|`T6h#uo7O9Peu8WUYf`;_vETp*LGb=e?o@c_kr~`oN>ym+k3ZQ<04wqRyY@g+> z>q>%2VjZXxICmQV(?S>gN0Ttr0){CPpp0ib=*>%2y8)~)g+YyWR{j;R7U ztj=OBYO8{h4T;WocO|9ZLoQiEfmX1YAFO1PSe(CXS>ko~BxM{ARxqV@q)PGqx`sXG z2yX*F8Q;XbynS0nwoJ)T2G@d@nsIddX%z7p?thpzhk=Y_nO+G(8+<#Ti><}vcOroE z+jwwrC@4ZC1iZf%*LSq*13AHAxliB&f5V+haj|8CDfS>rK;~uQ8d%Snp64mo(=hBm z!&E7y1m;6X&7QSX)ZC&GQ;7{-z@C4y(9_ot?uvj(v6+NKlr0zGq%ARr9tm4p zZ3x&KYNKOBUI9Zw1_iowicSiivH%ged5BG&Jv__|^Zg-))!P(*8tqU7VFr>e?AW#$ z94+|P^X6B9w`0lAbefp1+Gwd>t?T8ZieE2A-gUe9k6}8}oj%F(Uk(yy1+vL1S=HK- z_Opeb;eeZCDX#I~X}+xc6#qJJZYRxJx~b*c*ewi5LG2QUJ`8tT8Wcf$nteM>%qP7_fr zE#0`Hx=ZJF~C`T&7u~NPP zE-H5`kiC*uy}ezzQqOD||4~Llergn~PaLt&MY=_pFU%j}F!d2*8Cb5h5QEGiRh#1* z4mUYNQHuE9%%qX&X;$?4yKjP|BUMU-Qo7lTTk6Q9cTz!NQOc?YV$p!t7WS&U=eliOdV<+yIFXN1`Wk3{P0{1Zh;~ zMR=K8Ud
2V-6rN2ZFI?LhTZZl(hs)Hi4gX1xIYe?i%vO zRS-B%AZdr4<7WGqG%a90y&M_*`RL|#k;rH7q!l~Ec+7Q=R;%4m1Dc*?d5dC$o06BU z&~nd>kjJ2VHXKOLE}ub%in(vzx8APTL$$z&;j5=;8&|#%ar9#@#xYiQ+4EYYVGFp# zK+->-3w_ii3qLGyBT{P&`L@;?HXW=I#b^dCeuwEjxH5*G!r*k$V^YU^z#`XF{JTSO zg{MA4sfakpU>musi%3CjC- z%f8>vaFi(@O7&?3D{E7s*jnQZqVdrFV=luoLcCe}(OXGdB~bLKV7rI*)G!JelnXKO zLnQS37jIc-y}YLkSonCl5-goqMa=^40JlPfG**&QWQMzTGPwXWTRcf0#)Jgv5cMns zMa-D6P6ry@GaT%&+WngiT_gtaUO-zEA@f7dkv4_FmgTJ5Ks)s z`bfl;uX)C3c8Ru*wbkj3LVS)rgUR9$95md`ir4H;86U2mpTk^`b<5O+4-3fIs!Db# zJtr0g8W^hmV)3=FAq4ovz4@R+blNx2`W_R$56e*oSuk^z($-o0f+dM!*-0lWVl10p zU*VfVEGwRHcAdJ|BcRyPvh3)&(U+=dI)sfR079Al=6g(-;W|CL&IW!xP*7%bg1cNn z^P+mWxN$sgusL?)`2x|NZ+aR1T2XUxUJZMK^O84@f{g12Siz+P^(j1eZ=E0Vt0pZ| zBdsXkt&&PaaB3cr=$D^wZaIJO2HH3&P_uXK8?R4jHdDhS6&J-YK&dO;8f|?gBmCCJ;pcnZxHV3lJ*p{!QvxHlU0|p)|Vr3N*BciE!1Gj*xbYN zV!&|Dq-W0^gpa!S4~JA~ri`z^_5te^iCynDj-;TpqZNgw!kUg}KhEy55JT_|i z5b|Tu0fRJ!?e=Zc9O>PDZ^zB%Bk~K+d1l>1I!U@DKWD!e<`gs~4uL^_L}IeV>bm47 z^muLkL6@%b%_o5f{&~VLm&R|qGkI6K_pmNpDeX2@vOe{UDMDR9NCMx~;acQ=c!fP< z9My{SdPw(e;}033EbsQ+L4_+bdPjC|mfQZXCxhz)G2n4{`*L-7CvR=$REG9@QEPeT z&r+T(X3CD`G}Ri0OpFLHr>gOqg0_FdW37d z2E7wxm*$9kB)jFLW|2#2h#)7kZKZKE1=QdLur+d5bjcq!nAThGn{D$uktedGTTCvb z=_q-sr$n}BM@()G(?N;y%@2!P?y`41dg@-$L?y^u`{zpla_SvZFBxuDk>D9h%Z1HM zrfFOTqr4f+i;Mo-8AeD8uDi0a`Q6U%yCb~@*smK!n4s}4JPLlaj_~TUuw!kETehiB zFdnmi)RV_)IR98h)S>AvY3?=Ysy7GKSZIq<6-XAB$j=_RQW+DZU12LUEiWz1KLC;E zK;@A{Ag_C_Bn16$Pe9dPkok^PO{?D8eD<_7oZ!pHk@<)fhk*blF2nBtUs7`9ozOxE zzT!P*J`QJkM)XHe4ZPooKo1y#WZ#Qt36vf%u_hC- z8%dm;s5L(*@}dz?J(a&u(24{uB3|C!@Uue5eO;ng*^gAWs+Zb-ng&bW9@fgS0*#_)#lN3Hy2wQe$#k-Ud)%tW7nfh<#9T;%Lfdm$Tw%3 zDA&|Ur&PU66cYtcZMae}1`#2lu2n)l-IO{qwXr?(eEIg#p>BxWAz_&=>fVoJp^jtP ziM&LB`jAJ3&v7K~3?{oR`KsD}zU)+uD*FP!(G4^#YbdsD+GZHxJI0e?pN+`wnKxI( zuicXVO7Irp=lrJwmtnQb6resHRh{@5U*%vVu%%C=dgszG92B(;#`y6#rM~nK7GChk z^aeXjv-1txvd4S($wD)&QpXdn1|(uhuDT4;_W%|a+B~5wvJA>l=b1tSQ!FrN!H3W(N@k}l59PE z5owYdB~MZ;SBadwAFX<9^dMA}*=lya)=2-+df$Q9r@P zrkc(?y|N;ZO3mmFq+qO`rTsln#ifQR5X-%3BmcBgpJ{tOp`9MrDO;`zV{As~R zJ5%|Q`q>-)F7Oj8)?VhvKPcpT6tuc%y)LM=j$kiGl_G^aE9@}rcX8PscbrK*wa=MdfVK|uYmFR$@%dfX{ucr_G6Jg-TAUCH7RTb|l#f_! zK%3z`Bq(}I)ETqCCWB1~MRJ~Z8wO>o?T?RQTH+sxZwPNT&H*Df>JWv_Qh}YM9Wz#cElcY7sYtCHrC!7DMJsd!K0*uOPWB=5c~b0LtQmDY^Rzk| z$MHI(%GuTiA^YPHYYc1VlhSTuqv!ez$=@i~=Z}?1;dp1~0jmD&>o@DWm|b`(uOIvo z%6aEFiF*XGrUg1uZa!)Y^&csZzpkRW4mN|QgzWq~zf2u8lBht4uc%2B_dE{N>sF&{%eZryu5sz-1FR7jp2 z=Bb?~M*rod|JMRir-E}&UyrN5kRH_W{5$ONSmsq5>&ej0 zm-G3;JQ3LrbCvlW$3gy2+1Ck9XvcNK7GwIO&#jC|NECpg8fvZ(;UvKj-7;rRibUW? z9-D_=DkpHln%`4GM2BBmTOwVh{Vis3GWajvn^t%B{M)Ao$dPivAP5 zG5A>nX%k-6HlKs1lOjk5I2oK8gU_E@PR5~Iyga4*Dc=F_r1t!G=M+~S59x!tH?Pc_tPm>ddn2)mYPL!^9vjv7k0(?Q<=E0kX8>nmaHFV;JmN4NM~VW<_om zg2_H1BU%VM*N_jtJ=ISI6AuTo^#@RasR~C45+z=A8lVc&17FEpZ|5#PiaUt345$ME z&iV3<=GhQjuMafslmD*{DN*+h$jUc_*ziheLioV!{B%Sd6v&61%#3-ZfZl3EUxwlw zz8k2D%f1(@w!!#^6t7{PsH|3orDf0KNJqEHrGUo1xD&3RGHJbStWRIwc2Ew1CbqHz zKc5Hs3eYh&&S3{dU5EQxHz2xUip~&a!kn}Mqe4p*i)L^-EkphOyZz`C@F@yz6r3k% zagKSRzll0g&G6M#H04!PaH7yKVa~mADa7E5fq^vmKv&b8tef} z(wL8XAc-$i;M_6E{RkN%fMpAuDRqh6LGa|;p6-eUHi-7YzYy=A(f~{8Qoci;s8Pg) znz*Tqvo*@x|=ijLxg^O*dDPK_iJC}Con zWWVI?-kCdq+}z)g$uk`UH6P@X61`wm+6 z{MV|v1q!hD*~V|WP5}h5d^y{XHQ$os%{>G19RHK182e0$E_?kVDP} zDdS6$logn83bIP-Kv4h;WdL{PT-q?6OVxh>Wox=ty6ZeLT>CpfH6cIZp&e}hG+JJY zlFjdN)Qw&}Z#Vt)mk1Z*11Z3{i+wPA{BNXNSB>oA7fy; z7tfqVQ;q-p*e+&C}-Q@;> z(&qL|X~KP8AGxcI=QX^b%IYaYNY1=$l|eKZvI)9&oV_;z5M@K`r*bU5?X3y_eby-~ z{f^A`3q!1+$0TCA==X!^lQdV-3M?y9#y&rqcubOX#iO%|d;ZBP#$TuPrW)28V6~=? zJF>ZJlw*gA2ZbeMbK@$2%m>skMJ}x%d;(_XH&L+Ijy%dnzr}e2>CR9he_P8@_jb=! zx#K&Q1Yz;0n+P`sm8iK(!B}r{8w-yE)FUkMFMoC1pjc=*v>}jmeJN)jO`fBCLdFr+ zgsc^eMSi*9t&;SyaLt0&!)+-1F*i4ae9ORY)HMZ?*x}4g*|F*s%~5)#Tga$IB#!M3 z;PNZl#$FwZ5?q6Rm4Dhox_>DE`2qMJ2TVz@*(*prlh$(kH}+JTuc%@`OD5B$(kHbW z0n92e1JW0q$OudViU~eO#aCOSyl`(cUJfS*ND(JP*hZ9xiUz>)sbL`!$D*#xhQ&Z) ztA!IpgC1&}p2HIY_VdCTa^*-(@Gja#gS<`7t7;e5%J3IQOcA~bL})?Gs&N)16#+t6 z69Ad=#bxvrL^bha_C*xuC#j=PRv?VqB>D*rZTK~TEIPcpx%gd*6D7wf)G)OZ$HRP1}1p<+|ziyX5BaPu9JQ(L-wQFz{ytbFO!=2tE z5RTw#!AT`E6u;_GqjCGACnih>CNrnwMph_-wB#itg@UJSxc!lqiHX&aalidcK4|TT zQC$N6C|ki?b%9KAG6*r2?7UAju)Jed9rG5JV1?bv9)G~Pp#F%MHpm8pWC$yrgh`xh zhp6PuzEqKHIJigR#|BJw7RpC*sT-D%2}~I`A2+Na4qJBINbRi$mb&_m59fyOGvQu^ zW102;LV3{xdaK#6{MgqVW0mDD;k~=5$0?4PN+_{*g_6mKJ<}RheTT-Dhr>TH+h^-4 zQ_i|zHq;sp>b}|)C}x0M*x^>N0Sct)-d17CZ*#uU3?#1G=nB{S|cQ zTW5~As3=-dPjwF0cKb`&;F*s7@jW(UW?ra$yM#AS95pr;%cmYI&w`hT*p3`T(K26jWh5rrAhNwJ0uIUMnH3Hso3L zs5j*ApmJ8~*QvVmC$4=>R77bhyjcRt;qK+~!M-vwZ}jUWNW6*GV^X!*Y&v74P8L2s z${~eK13k0CAs-|4g8Eb0!ZSAPYvCOhUmCZ)h|PhSEMwJogXZ~txYoj5Lj(}L?uwy! zhK`%CWlqr}I1Ycv{+6o$A5>=DQqveGqCU35E-c&7DY(Tbr4v^jWD7ovr1mfu_*3^XA2&vTc48V=qq%dxpi?WL z%l!TEjYj2$xKax3CK&?2c~Qlhx<9CpD_;|O$i(j(TC(DRj^B^>`@Jl{43KYC z9wPS7o60aGa35n!g;CcYpj=@oq#+F`%B2R~n4x;2)IMB#l%Pq#8F*fIog7;XSp0nsZ$9V-4lkm1N2PXT`)gQL zR{yW~E39Cykt)bM|H@m=ac@fVO=`>CQD8|nD2ITJg92D0z#8q!%`PQr8AJMq^wlYK zdsta%gR@upYeK$;2*Jye1J;ARYub+0P2==k3{Y`=3vnw?{R-WTuh@wBNyD1|SU5fL zn^e;!W2th=h(U{4Y}Ip6UzeQp5QBh}`fuE%J+_4cx{63>YaKMToss^zZ=2Yxc+G=q zxASwklmu5b4nCG6IthD3?ypY~G)@{&$JpYKCNwW=yeFdGPHA3_CEM``0QE9PjOtg= znvFVfFN;9%IOz`yC&{o<`A952OgBa-3)_u9S9O+xi^B7S^nL$!bLs^vo3(CTHWvLw zrxW8xS@al}gK8V%*tq-LL3O3c!Z$P$jB3}*yKmRWJ zEvu;_rBzydFo8H}NKpS^WW2L0xZfxguWVW1T*H*lub6yctD329He>B8Npdja<6OG) z*itmU#&RffwzQbn6#HT-CLP&;Z>;vYl6*vf31Hx5l3@ehH!;ucFZRrkjNM-miu z(G^UWw6Q(nCtOw<{HBC=%ITG#A@pSp7q|eu8nTM=j~^q=eH6Y|GHiVF644A0u+cjU zrZ)pUQ8uf`u(No|xSwxSAG@subv&dZ?L+3>PzG%@z}iq|;HCneOD-NHHeL>&?D7|N?Km}Ml>Xj({s3=w*%OxLD$(jQmVpUe5lHhQuf z=cpa5;ap{fPg({2Qgv5l-;mM{-vVg+b(6)ZZq=K2?yp7;g}vfA^lIHa|g>-)9Qq9v!G7TSK(L_0Z|W zun4ns2RgsW+L9%nQvCc+4&?O=T2+yc`I|L6vu;2F2B(YbgjxUq){k7upvUe9X|m?< zZ1A$mrfbDk>P%-ZJ`MI*=?WW>Q={Kf^Kg3yH2_0EyuVGc8BzsW{+PqPBZO3X!GYX9 zp6Wlnp7TEKU*Z&e3O(f*0BEAKh-E`meybNKGzcZIm9lm}hYuVQVZ{e*-7Q|B-6;Zm zxP#JulNO61dP~NwcXzMVSQR$N47MI32d^97~x5H-RFtW15u3QH3NZ61U_ zVy`yZ6~C*0DQ5qCtgC0Ll2;(T{gUC+iB_YizocZ0Ke9A}Ns-}m1c@u9=nYS;uvokh zF;>BAg?OGQ>4`Z=sKRjl0NUZyI{Vv#ah@=F7?|&KoX1=Hny>tG0uvGK8(BZ*K1i`w zw(`csoW2a{%Oz%!rjNGatkV6sisqRsKeU}3$z;4lp*OlBHKG}!-cOqKRkk{lfW_%) zS+yqWc>-KnbD(+Cgt`m;4@=KCOHHr^hzvk3xU_#nmNa-l<%ZrMscP}eHx<_X)*IeBb7S#1UA4nam zXm^MC4~I7(l3pUoft6tJbIDEqxv@IDm-Sgmuy+bH$gmcenOTX-i+;$5G6iI^5K9XeXT>W=Sc*(y zet_J=e=6~01TXl*w6%lOC*H_C{jKZkINDtPbB!`hnI1BpF4qe7lF?=?H17-?q7!h5 zxeSRueFX22hAG8OR^ur+M=5Gt3Be*xUR&=9ra4*?E1!oT7!G0uzD+qh`x6aof1ryu zIku_K*w9Xhsc3bTw6JC)p47%yTp5t4XE|Y;-FCbay4#M%z^K+xGc4oN+L~<_J)7Tf z?Y7Fc>u+U_yivW;P%I*LL?J$;P6KXy@lhIq-OM|c<+~RH7 zoD&yM6W-&P{E+4!27iSWnj5{?#zQhFmr(qteENZ1QsaI$9Or@Q?;b4ypGM*lJS^SaMTi z8A}@O!enz_U!6KbIops0qTFOFTmuBV{B(67OhPLDZ(Z;+*ZX+wUb1Fq=~9R7qmZ>( z8Q}E8`nrn&goOy_4^h(3xexNlVwKj!5%)HyiGb+h%P;?0Nzr(z6bi^d)E0*0odx4v znab;E;ZTTW0c;scnXcm1Qx9N>u0|wdaPKMW<(rl*qpd59Jgxi=yHBTVt&v1Mv2>;i z0ASdQb{>+Osfun=zzq@~OKKKO;sg+K(lHu10r;n!>cU{i45uHm7z+JViD5YF>Vn+L z6E?H1VzeHqBoCFdZ}k`nIl#qxU@kPc|UCmd~8C&b0DV9BmY z;Fi}P0+B-nuM0PBPQ?3{=%h{j%zZ)JU2)-PdmhzN(MppREHr4_it9>6jB1`z$~JQ) zZ^R#ubk}s5nu&pdoQY$|WolIjG;s8v5l+2Re^e(P1lKG0ExfDk%cNb_5V)D4J0|@2 zbiE|8m<~;hmqnywJ9CS3qyXld5%IE{Syw-Eh%!m@GjCPu+o#v7bx92hvx_hVcQHtM zbWvV=C(c*@sVjEfk8bRzYkO;mXu`*}=T>E=Wg%^|9p7(IPQn~~f@jg=3k9!2LjtRx5wzBtSs+|^U-PF5eeT{$1!5>QWbDg=lZJQIR+ha`Z=Ju)a0SHG<`6jOw0u_$i^!Y zrnG|Hhh0yJ5WN`{qss+lYCc5!59c!htrrO79qAitXQ`(yHb=Pe;juaKl2;MRlpEA( zD;QGPT}RiK>rp#J?GXJVs@XMH>)KJz<)hIBU2bMv2C?L9;r^1IC{xKbpYGPklCKNg zTx53RkEzT+cLMVNh|F0Aw`t@Ka>GdrZA=t69W0n2-_drz^vu9BJg|iAajn{V?Q44) z>4Xn1??`B62(aSHLJYW9^)``h*4U2v2U$=RLfZJY2aW^j(9DH618~oB$iwr&Hz4j6 zGf?|q|DQ%f@+84-2qWxHQ__d1EpnHHi>!s0o3f?!810#EDu!Z5qygYZbke)-0Q)2$ zh1&qvp+wZ%p5x&!W9ibaUdpOG@{mf`B%DM*u1n#rZ(iIuS)@1}jZg(~4)rF#FC=0aM+> zAjob7@BpNfTeeYqnsHrahu3!9?V`MU8Sb^H@HF(t{VpG$i;_YaMQ&^49YJL|dHfHk z;6SG=Ol%^zpSiXBsq;+DdXgm{xbJgH1~x@I%Ei3*$e$*)AnU{92N)I}JWK8R!G!RV zvRJuWlw>o`4W)(e9E{oy*yVu-zZ#izA1FWgf?(S`rmSdVO*A<7GNAX9)sj|=aC9=R z@0t><`x0z^Je^EpAhUnSRZRs! z4yBZb+qP_GgNeFPL8D5O_if_0^y-#kJ=nnyYk5iJlF|?NKah4*g+Pdm!!Y&rg-~1| zX064sX6RT`+F8cMpDm_Qt)@}XpOY{8ocf92&=rg+$IaSs<@``^6Jjtes(RmmRWus> zvJL?d(El(PSBE4Am1Wt&x*-lKJ4~FGE@pioZcD)eIWkNflJa+`K!!An&sFIy%>jJ} zlFwL-iR-982jW7u|8ydok5g>}4fd)t^QAx@X_X;hKE-|&`695*QPX8Sl4pi=$ogF^ zM*dJhV|WqerPq1JkpIMG8FSf)C2{ePWu6>b?zL72Ll!(okc%aUAq%LPWeh1=NjStw z8A6#Hep+e-jTWpZ-KYOwc(}W)W7OTOK6YtH#NJ+kD>R%=(MW;1rAk^Ps0b@>ZeRh< z2swwt;z7eEr=A9SNMpuo9T0fqsx=fIKx3dlP-6W3W)}*NnsZKhu4}g+Y&=5edwaer zT=)ItvSl0~1<8+M(juQkj%xyhc-{*I!Ex!vOXrq(nM_nET4MqUzVB$-Le^)i=-&yj z_>1e%01Y20hAvm|QlO;b- z6J`pW$NrbDr!jBeXl+y_?AmfD#}gDI3G|>;4Z<5oph5pIY|1L-4-W5tFOPc{QqP1&Hq^fmC z(9W`*o+K?3hwKOKNd_q~{^IUJOKoH7m?AAA_P69)_cUsy@Mh(LfMV4lyDu0%esB&& zBlkAbQVBrI8f-wKB$AJkGAPeOe!OI0i=QlW_)riOzH_uH94v_?b2i${BGfy`ef<6? zAba3-69`JNC4Np5diECMFi*fj4mCIJl}{;zyTV^_^jeNV=ukEl%KInJ`bV zhbv%9;nw0EP&jt(q%SF$ERxHcBpCKn^jPLQppf<0F!I9<_k^IFimoSvA^Z4Kv+EEd z-IS1CFoiKoO&oRryDvY-4vsk^##JLtDNu=`m;(yn;kz{z;Me3d8Ao{>ArF;A9kaZ% zydG+>uLEV?F@Gov)-n0fP%oHX3_P>AdKAKz4G7)+HZX|IR}YEIk?r?+#J`HsQPDkX zhLpOldDy>nkoRY5!mZBLLVMp{B<;59%5uRYbL@Qq$4(Jy<$+8#^;R}_R)oD(>! zfY5q@uqrjRM8(@;snT0L9jj;Wz`gW`-D3Rl)3VJhebb0s^jhF>iPjBNFly$I_TXB- zP}mJc<&9_6#9>{sp2@$5wQ@%LC!=?HlE9yvJD2L8%+R)mC?=77l7pzA=wj_F)ufC3 zz;rL0oL-I)op{aKs!>~|S9L1l-X^OTychxmnNE_p!C`lLLIY*6i;Bsq#-++vV+3Ny$>T>0gU19#3=K#387*<1SNB^k zVvqogH1uYRZKu!UUXM4lhJi}BrKnq}IJ#Kght=?*u+Bno1l6~-=qhdXw>ePqWdJMQ z>{Ps)Qqy)Q(JYtHS!{iNIKSYk42b=U@MQ0>p_k|3(lz(HTYt>5~5;jAnH+4)Tp4m@s)!vZdgx7EBZ zN6ZjCsrBBb9=zFZ>|pX2tP2Visw0V3RwdXU{9{yV3?X~xuZD$9Zkz3GT|{K2$X%`- zvpj`Qv}-9I2yM3-1MV`x<}~v%L+Hr&^l-m4#+H!=Ew(qo{MKyy?NdVGN+k>%baPRS z&|0Bb_fz_^Nyamc_|>HRjWf!^hHbnC*|QOj3@WqxRaUkKnsL`sXdG~#plU3Pi_Hmo zJ`o#cU5Q_IcWY0)MnS2%VHUQ~gkPrL?H(k&yJ7B&a?*P&3i1Tfb6O7h;v1qQKhOW3 zO3o}hT`y>VA9}-Jn{5Z@TJ?-XC8z%OE!y)dr5yVKq!;{6j#8PEdvDSvXmhz) ziAlO>E`pUA!XE4)bp6~+j7sX&jKL~v`k%xjJDG<_Z7=yqI0>y&G{hVywf>nN3c2i4 zO7|Ag1OC=K9-fBW%VC9NXml@-}vvTiWQ^$q0%qw zuugZ+_KC!q7Ybwp(Sx(@VjgexGI2Q!mr{D_L*V zGw=~`R^A>)R{!=hj%>rp61RUr>mt&Hoq6&HEMv)F2^5Fuhh3vDbx)zj!3t06N2_MP zqhg(GkdW^1i^P(~XvtX4h7Bn+5<;#n_LKCUcdeA~07#3+_hW!1pD6iq zF?XVsE8z(ky$C7ooTkU}&+OuDGpjtBirstRl&mSOd^@xSL-FZGb^rn16frJcc<$}% z0wQbv^EVG3CqsruQN2+cg-SZthWfFhmMR#I(D(&ff?J!prTHuTJ26qRk^K4zAvhB;o45O?%9hapN1qQL4s$*J~V5FLS8 z+~aD_5q)%AWk0fsT(qSz%$*2#YV$uwq(!^sSZp5M;>f`F2t(dy_hc9=y9gb0^D{hD ztY*BX^qk)U{((r6u^wh`1l~}U&}mzZw_Z|GkwU%gtt4jirzI;$8@eR@)RIJ%M{|s! z%AQ;*yB{rd4%~SW2h>1jY8b9}8Lc-Cvg1;FFUUq{^Lv;gfiC!*6x5SNa_3G zH@t4GgQQ5a1CX?~HS(nHk=4pgzjpFGO zk@M~;LSM&D9CfL`23H0f@%vX+C!~-7-jO}j=zueCIc~;v)>c6=Ry2jOh`^VvFlrOa zzHHt;D=ZHB>C`aJ9)8Zkwb4LEO$i@8FHzln$~sJ_${?RIE@z#H)}$d1TE))B|329K zUNJs#*mVlOTtlj zys}L3JQ)AhuGHC91|H`rmKES3032zln}N&_{Np8&fPVI}^lMcD*vT(Z_V7@hmpz+m zyXEfq|3k-V&)iX4J2xF%m9}?|Eg8Aq)OLSa9$p{i+BuWBkw8?Vd(XV-;8IIi))r-{ z_l$`hMj`m#+z{bvtP2C7C*pU7-Y+ZWu`o|IVTRrE{m9wq05Xqo6wt$U?; z2+-e^ayDW$Qd_7>B4J0V?98jKJZJ&hq;r5V^1wvyV{8lEittg>yz@+mMJ#6>UV7ii zi>^Lt4;OQwS)N8bDH(^qgYjc|cJ+A;S197!*V!SQGGpc-?}E+TChGNuGShtv4kZjxLlC{XME0?h!w1`hdaj==RFqaBUV8pw`&AGA^zcjrvCtkv|T zYE%Y0ChzfG!B~yNN^g~^+Y%+$KOgIQ2-@!nPipDQ4eT{SRN2!kSrKfm6FV`W-zaW9 zA=J^8R1!{^glZ%8S~5MFok*AoM-~Yj0gh>!@EmK!Oy*zqNeQqCYNbn45=HKNHB?f0 z%{--bf%~RtEqH2Tx3*%7f63G&b=Vdh@ z7*0SKq0oHSeT4*>?B|LJ4e9D)awK_WDl_Qj`-=%Wyop_fGDA9~K$+3$E%w?Ne&;h6 z@tY{*jvK<~HMLvSzqic|&|bSgtS{6U>is{%YroT*$<)Ov@ZM}{#i~myO}j1X(`9pM zT{d_pKu@5qx0622yP&gj(HDx=9mjlcK1jc`AX3;O&5I5&)QV7Bf`h#yTEjzop^lS~ zU8#)H+4`f#E{268jAz)Bm};@e2w1_LI7hj_v8@YCx}cwGDU?(g^Oa}DEk#4zT4?O} z?10Q~UY(a{vLo^5ZbP7tqu0LUNm!NO0q$DJwU}KtiSV53as}+gm}P6%V;GM=la(3%ksBI-l?(_VAK>3IyKGOfZsm+QWj0FdYM0 zM?LLkOP!@ZG88linAykUR|AN21w?`_d{`S@v0Zr)vVg_Y5Z=UC;N3_xnmxAhrSTNM z9fRMg2`hL2dT-`DQGPv`vhF$ttMO@+kx2rJ=W}97?nYx54xId8kdVE`FgPtLT5OR{ z;XBlYHCqUST(hR^Hwr8p3bZ8hTY9w(efR$k)!DU|@#7+xQ(8yrx|1Ag^g+QGaT%Fp?^CqT=A)9F=czNY(Oan_p}Y&{h7zxxh~HPp_uHqQ zZ97@lqlo|jQ{tJFUdbav*$iGdx5(Ni@7DPHtnUASnn`K-9u`{@gzwSs0C$gw|p^}G4u?Z>W9!{^Ycld(WA;gg7bg} zFVK)zx8;J&E^jnd#~%N{)LbeBeu;wD zzG9RJ7+XDQ&s-vY#fSA|GYCh}*G~2>C&&AiOG{SAuXa^|1S}6QT5yOg-;5yh-V>$| zVHR!+*kLJfHe~P`F;dj6*~6q(DT?lsofq;t*1$p}vW*)AK0o5IFO#@^*Q|31YwN=V zHRyUi-~CJV@3FyixD;7DHYLVN(iv3MU;b-bA9poEmk;o+h!(q(WTQ z06L)bVrOul#rc`cxF8_r3Ea474QzQs+@kLW;pzu;@$9UtmJn&eh%HcQY%8lP<;Xf! zN{2ncmYVND&(Ub-Rm z*$dt8epwW{I~fJ49|QVgeF3YG8HS{bL%cp%Om?hGsjl;9B!Fg!Om#-@HhJ=|!x10> z;RvSDHhD|!Hgph1mmh)mVR82OT)&FKDlrGa@gWMa*hdZ#Fp9AbxW~paS5OkBmGZtK zHJTX^>Npmg9TXlO53Kvymkktc_5+p$u!5Wf-H$3(yQ!^TL1VBdEmb5IUhRflzfrh? zNJ}=%eW*0Ggr)oEC}&xSGobfo85+G=zURs5Bl94%nviM1IP344vBtXU7e;oc1|bQ6 z+vG!0k%PDTFx=hhf_h|PHoC%lcs5eZy}N2OW{SV%_?(|YUA>YgNrWR{cfuVCDb0H% z65z*Q29}ht?s^e#wdjTXU@ELb zcSLk^z|*Cb!i(Ga1eEeqB%KpD&%GN!3srUt*A4jDI36}%U<;CC7ce*giO+H2m&np* z+W*A%1hte`K=Nf8&WH`XoieGKvkxA@_z@2LN1aN~NdmLrT+*HFm8{y>9*P1NfCF^4 zk)l6P&D-da>;q1P>F{#fp==-1JIfPHMtbQqwwE5E7*TE$O=VZ-p_ybF!M~_*4 z;D?_HMhQ~Uz%GC6H%GzF^my_c)a-0nJ&4*byN8mZT~r*~nV2nBbs3jqM!U3wqSEzw z2FYx^i=G49#e>f~Y}9i}NDB;$^iz2mcFZKZax{k3$0^No(yRkRNkS}70OaB!VLq`e zzNoqH6}zs_EJTR3fb)IMKskL7Aic>QBMtcr<_-C;)FfiU{^>vQX2# zRsYd{`Zo87E)9s@FND09e6C-TCu<7U%PqCP9>M&R1F5!fnU>LDfu3utA_FR1eYZi8!|DT)Nj{Y|WRWXpp5cy&==LBBxX z=u0Vw>*LBCw@J}){GS=j6&*>gy3X)WQuP+(F_k^tXxD_9G>1aIC4Df~muiOun@FBb zCH=3dUuX=AD3g1IwXi4GZj)kLbx3T#VXrUi%qX>>I~j#|U3xOPLt<^zLXSY*<`pLX^mWL%#ArMTnKE#t^GB6}k8HaJCKRLN#RC_({ zT6*c>mQ*hmHX>59-m}HnRDiW;&_&1;_ydZmk^)z z?mWBk+W4HtJ%?kg{8GGHL@X*lefIM-rtpzl$II_>2GrJZ1_iOO)umg78J6Tfi|dno zbg_UGxNqH&-Fy!uPSTE6b0uL^jo3QlgR)**EC{UHie?;l7-0r-233_>8U8q>ot=MU zw`iBxu#@Mz7m!{t{j%WW9~FwcKxJgd2jk-2BCFtMXZyL2#xHQ$=*!1oX~Ng@P~)27 zWOs=VPuBuSnD-gP`^u)^EaOVKb+1Y;H-;0FgGqCx)@b{VDQU9{vWvTwXoAdbW z-unqbl`%~HEc-)J>A^|Kw_Q|r19*l=!!7MTF- zr35@h%!WgeGx|F#g0YV-j*M`v7TdaB5~$(fvaQ|MScx~i1z};hin5}^n~fl;>ica=4&8Nb(`NEkbY{gdjq$1sF@cP3$HL9a z;sLV(_wYhmM`id=#9RK1xkKWKZwwcYoxVINgI7Uf1R+(adABI?$QtIN&$iS0B#H53 ztfR7a@-Uw=z^#AQ%TO|Hk=5br#V>tBa2^cMD6n!w%frXZrFfWZOEJHC)5N3kv4x^c zB$}XS%PU_W5ir54CmV3@IqgU*MD`Kt{=ypi+`iQt>qWYOx1}W0eCoU%GtIiTXVpNJ zfIlBK>qmit!EL6<_v>KidZ~~%<_Nw^z&DK>0tiAak47`fM~_vUKK!REKpjisF_<-M`gkT4|+e4P|CfEI*p#;Q?T9Rg%Ih) zx^*l~;lI7q#u4RnV^!Pw&!{}TXRV)LXxXgdRP8K*mGLCJPOM~t4`G(Mnqc(z^d(B9 zlNA@}fPHO$zvtG2rV$PsEjz5+#Y@7eGOny8xF+FKdI!70%T(qi9PtoP!sQ@X%%N~+$nh;vuhtJM4_ zn>lGX;VQ(pbkH@sWYU!Oh-)yFEdM#1+@a-Br=87M0y^Pqr*PTABiFIzA0=lyKFU+4 z3k$RFT23AqrHF|_=xtaK75?a>6vr~G>FPOI8te0~C_AYdFij(W?&5C`j?dCDD^tL9 zwze7Op9*Siim%N_0)7Exg!@IMO$ry|{ij&al|Ibu$6$Fpyc2MX&EfK5546vHsrxG6O2Tcr#Oi!aa?gVqglSV;;O3? zT)=tvQr{JMdg_!T>SXX;MfQbuwfpO>&<5Z6v?@%pM9~c@G2!J10!TeEELRz8IG%NF z&RG!R`~qGW#T3$?#}~Eh>J?Ct@AI9?Ac=0-&%xBs>UoBsl+n+`F8^#zNe9O|HujH- zGlgQ*ektL(kR6+Lm21=Xe#j<0fj|h}moF#R$b1}1!`m91-FCi8?x=9M4Ij|Dfb;fd zBvQV{+}+b?jBW$*E@OUaFLzuQr{eb!uKKP+qJQ!6S7qwkC6B(EyKf)8M4x`gWn8us z6BB87z|%+(?#Bc>8Y}*Ne}n9b#gi197g;UcF8@Q3e0pMO z`17e$4S`<5jod}DeidF6jhcQ(b5-xVAhEkh($Y@54LNOE?(G`JA>6l_5ocE(6`$=k zH%HbFH42%wwN@l{^heK}M$aE4#HH_fAfquMKx?yaAp;hbVl=~Q6XJ%rkDLGn9x=)5 zS^Jq4E3z=ONS4To=B?$k#6i6{56D;oL?0UOGOCnwv%;~h%d-!$R7f?)w30?-jKY7J z11bB}O3T>zV+;5W+UNdK&1Z7Gph^M=7_`?uV!A<0K(dL;KF>oo=S~K-!7sO5HjT{L zngnfGkDzXcE%^nkQaFi=u%hR$k*-S7jG-B_4r>8yZ6BXXu9S^sL0|E6D_(h5MeXp0 zSRmBakf`gq)6|B?fjF6ln|q}UGxwd=XBRB?M~366{7CTHaw`zO4aq>!Q2SdLHKk@6 z5jG~MX%gw7+noMu0UYdxl@M~wZya>Jg4*4@zNxZa^ssIa@Sd8=G#G68jJl5!^$!U? znYbXe&>QvTc8(7R925)Doyl5QGnlQwT~`mLOudAFa+SN{d%^xI$}1>yi0NKuFw{ic zul+PeP1Cj;Jahc!s^N6sJbh&Qgyx?nyyJstQ~CHN_w!7>F@mnjFPryj&zUhfvevmB zyOIN-shfUz$h4T$_lSQ;*tw_Bsw`x3D?-B4U($b+Qa}gMAzFD7244Qivlv8~KqQc5 z8r=JTb5;0O;Hi^E;G!)H-*^&~vQwfQR{M}b*bbw6D0{ZAM{Ao8s--{N?Qz~p!dqr< z23~OI^VziHN6@z&A5%cG31AwlU{N*)7^ZyyMX{2BC#+Zd70)#SG0!c92|EMZEEfsn z%y(B2^a1HAS_%JV1h{|AZp+H3Shd!Y3yh25_Q7!DLODPA3xq|nBkwFGu z@bO8ECJ=~&nw`DZ*7)Vy|ESD__&Cjy5Pu?s2^}& zAIEaB_1ne_;7s^TRX;J%xdz6($!p?!3M7m0)A4Se4zE36Wlfe)hx_6u$8dzIAAaOE zj4}uNx~ifQE^;mM)~Dj6vlG^JMfI^euP!&(wlGvNBqdkw#_PDy2p-zu1?~(+ixTeB z$s|BmH~cdUT$!Lxjb@wS*e4ZAjRJA>s&Vt&;z9j6to?sxP%JzNPRWU6E{eC*7+4I!IO6WPLoAn*!u z%Hc9`h+pFImrqRAqP9+HzKiiLIMg8E8P+e~gbsy*Wh zE8QkEBTs|Q1)>BAuTVA;C@M7&(Efw)M!mGIt_^uGvvCKxyNX=86ZTA>*tx)oZ}Mx4 zzm1b9E+cJj;g^Ul9G=|^m&%0~5vP5F%P(al4+X3e%wJQamhpEGM}pPl(?Mi!E@y7@ z@Q9mv55g7XMeYC?IN6tVxa)__iBew3AeLY%^M2L3py?_j(IvHm+suS7r#k6pL-ybW zYhd=9@h5!RmI_G~OUJK4x`|C1KT7|K>v&Kdc9Q*i0fCxtb_!j2c*ggG@d?Wzma>`|+fQ`lE}eZnhLkzJy(=X3z~vgW7_Ia1z%(UwLSNcRkus^;loaGMxLE z4MYdeP`$qifq`rhbxRUi3c1ZYv2X6OB!mYk#X2Ug06|5cN67_^BL!UaF&3vmPe&9N zU4rosyqv7Alk&TBaVA=~AzM9B-Nf#&z%@Y&AKFYiK})aHVn-8I@SgWWWsvrd={VXw z&*h)**rB~`h1X6Iq@fcp`;cZ=uCMPvw06*!Atn4@TV+l^No^{2=Pn*1tIitej1eu3 zHNTxn`|?mrUgZDI$*lL%Y>Fy8wcu%r4nJ*n7!i@CsuTd-@L&@Co2Rc#Id>C&yX82P zGj9hvir98T>`Cg?Uc3@$%;mi|IJH8~Us0%l8td zDYC2ppMJm6ehiY*(xe$!3~oGZI#zpPXdD0l8S5%-!iJ8H zRk1!(IcdyFwW5=b?IVZ7fzg5VSOS+*PQfE;h@e;!R@1A}ae;;8%nZ!fG}+lZ;rAew zDta29MZrv1EXNMi<_2<~XLSNDUj+UB!A@V076!i7fm9a2zfNJJOtkn}T7a10mtezfxUCh>-3lY+Q8&H1ZOXT727oiG+ zTIdAVGz!7B$uBDUO+bpa(!Nndw>0dSZbT+OOw%mn0Wu!4;>%L9^2QX{YIfGq&B((# z7A#p|LyPi*jRr}x5$^WwNKi64o%fZxz~08&8$dUWEETLy^-#p1&l>HM^v2fnE4sh^ z)6v(^o9vWm5%05o2PYRWdSQ{_4K+U%pU}SANGLR1Csfg_)BKBydk-QZfch*1pbT9b zpUT3Bb4e!}To4C$Rac#mqq(u_rxBcAH_ik`J)wNzrMx+1fdH?@gCYniX|tWQ{MkGH zpAi(QC0;|H0=aA?9+Zd?di2h6BUAORtN3OUl(frhR4F}B-+#}!M#Rh^^;k6{R{K?j zhoWa@6{m~3YWjRRGVEOBU@F66fK2eb9T>$5Eb>%cHTk)$gxHcG@YhSiZXnt zNZ$DY+B|8qV0-86w**Cgrfxoy^ zh?Sq!YUm92Dan0vW@g&asR8{tbM6QVJw64%g=vyZt0DBVUu{ra3Vd+$dd0`WZOOVN z+Ja%c2R)o1WtW@yJU8Kpg*9><13F>Mkzv$0+_j7ieN(-;vliHaTiRAKSTrf~isU3& zlaK0Rg}Fy(;D-)-dPIrcHTWAmcNqFS$XX~;!XC=c8Fr*(DFQ|D-xh8z)` zSl>Z%vnz1rbvC_}vGxkMIZM_`kMx#jtz20j1F~^AvnXYQZ%~V8x&uLpdn!sqLQbb; zzZg|yVySpNHmRK0ZHE*>8zy5jmgaxG#ds*AEfJkghI$8E%T3 z>xi#yYE0#eDmKb!>8S1Hu&?5?`RfK&lIckUuZJ?lR%w1tjz2AfxZYOmdIsz)3*-XyM$eH(deP$k=e_o7SndA( zJU-H5RX9>aGM>q6iF-v23(Z17r6Li9u-%*vgzAny6GzNF@cyXs| z^^kSE(xQyxj=X|Sa0N2a=p?Zx>CUXW%oF0^_e*01d4k8azdTx7v=1M7U-BnQ7CK`a zNe&9{Q`q<910?dgucMT882Z97=;7YhIh0xUYs!MZE*~-^^fhSaH)~PBq2(R9&yyix z1blLY^W-2yRAxE0FfK*6odFLW)AeeckEP%l-v4?ZQD)5k8k^E+4AJba#zWgPxBswS zngbp3F9a;s>4aHW_FBBhA>R4^x&|FNhiVy#&T_=YlDn|-2^Sz}UwBv$GrgN0Jry}O85D~)XV!ida_qCT) z(8P872id4?&UJCNhJe0c`e{h+YT_j3X-qfA&^8<3JWEUIfY*0RC`d5+P#EH)8t9y8A@FW1{#0r!5W1QGet z*f2)JzgeMWa>BVw9zp%Q(R7$lMUm)R`P*I>=iI@-I=SK z#U>n!m=TGU)J-#F!2Qoc3xZszh4&>?pPKOl8d|gIHB(yEHimEamsNbUWn|F?+gODf zcx4Nb1AcdWVA?l9kY0rb8it)D`ez-$FOAPtBnU+#%cF&XZSR8E2Iz1(j^}FZf7*f( z)!soM?y{*o7vupI7gy@;O>qS#ZB{X4cv5-y%}HFgTUvK__geEb;&eW51D+zaD?6>| z`=Z`nJ*i#Ut?q@=C+UIB#`0(qTbk$!R}70>P)g$$!#^$FXT8F^e_dsC`#>W?n71X3 zx2e;(0Z#g4&SK|_T0vfTQ>e&65&b#0_M3{oiOyf-MYp_ver&*aOh@(u%HP|=#b|GPVy_+uz8weP+1S~6oYj)Z z%&z=LcuM4mO+>O}PP~4~^pAJJaxc|6p{c?&k|`Zay4*EiVoJ3oHnpOpe<=`JU;fgE z$nS1bf+VA8*?;C`Jms6@H1T#piAv$nHrQm20qBo?Y15Gv0*mYi$}rlClm@|PQb&y2 zs6n_7vr#pTm*=1TUml)A2;M|#(f>>qQKQS<^Oz%;;L&iEZg9llrY+#446c8zPzU{3 zG+`z}K56gX1;Z?ms2>DsoHu>}%WEyOXLbQt{!e?v6JLIE(% z{wJ0#9+TZrwsW1ovs?i1Gb_)4Hkvk zl@Udo3S-`8r)iD>Iw5F4&8K?V67yIf;I!~adcC!qv5+eh`&h;SdpgZtOR9Cem$kwO z_u5(xQct%KVsor{z;dnf0VeXlF0pqi&0pUikIcto0#KQgR|r1jjEoP+$%&w6=V2K2 zTL4r*tG}RoH6(;31AN61Cw#?pp=~Pd+;5#orxWCdw&WnpTP*37ohRPVw4|iHaG4Ct ziF$u};1BnqgB*KV66f;ql>)T4g;FLjT1rht2T{yyG6w`SUf`rp6d+b)D^j751CM^| zHb>&rn(Lz;f7b;nTk8liF}BF|uBLthr_X&PR}N{8&bjxAdHUM(JNQcUK;JCLdNdN; z&K5N(LCmNcvdNHF_`v-(vw+xO9V8ucnDPsKxZzlNY7}u)wJ`zo#=c@iA1uf zm{m-p=PgG{S_;8LSh5+Y2QY{-Q~97xnFvA3u^82i8_GYo|GiH~DyQB?`K9sqgC{#? zBr9w};aw7aI#&I8P?y-qBY@D0*+qZf#N@iB`QS9Ujd|RN;<>U#!29I1nBXiMQyHD9 zEZmUUL-iDxzZng}lNf5B6%+CAAI}fC&O5)!&SltkM{z*p<1VeD$)nC~A7l4gd5SIh z3a^z+3AVk$sa^VlgOT`GGb9n~M#iaGS58BNhs+~sTwRwkzw_}W^k!kIL_VToj3Err z^ptpu-Y|~jO6LC*kc6assyeiipC+bc9$XY6zRI$S-GwAPXF_U{( zto24!wJ1rc(2G3~1qzU^?7koMcXUpEsTH1O~8CwX^*{Fzk z`dzE4=qZ7JU!ZTqG{^>D^?_X2f|IKIvMcobl^q`OGd_v&^L@}~cY?8slJCE@AIeK@ z`qU?9=?>3uM!A||t8T7r&Kir)O&=TB@hMlJv}iUPg=6_BMg@N6)y4XC@-j3*U2nea z_PEi_TReAyR8xo;_V=1y8Q%bHdo@J9%My^n@pb&uo661oB20Ez92v#p#MYrDR4y=y zGrZi>lk&Fdd-!O@HHh^J!6rcO5j(a=YXKShqw$13@Eu}E5|U*J+BtpNHp$w^T?VQ@ zQ-b|0AR>vOSU6BurU(cwv!oPR&Mu(i$cE;oEU7#TrJ;*!A_EUTXYVENmMP0mghH}K z%ui7j2Ani_Y5N8UmmE$MYPIvrr{57L1AM8Rs|#P*iiO6<%E{o(qH53<*5t+V%enEq z#&tZKH?}z93>jPt*R_+O01~h4@bYQ$pANgNe+kMANZ89*wP#k6+r4u-#Kx&432?Mp zt@OX0J*|k}yN!IiI6c9~JHt3EXI{_ed9%g!=iwAIE4-87*$XRPyjpyb!Atb&CG-|4 zRW^`4rP7DKDE%mz`Q`s!m{ru^aBCu)TLYadMh`c`?|18yb80*{rRFu zMw>m*>I(Rv4#|B63Hv1m`1AQ5WL?Q$S2_F0GK~1GiZAP~7tmX&qIUd??g-s%8ovk? zX3|l-l!T09a&=O=ASoU%{x`|uN$bkEHGKL^OP1|1pJ)z=;;q|z!7r`QCv6hD6&^`UDr| z1}FhE_cGmuU8(UtbS~4P@xd(}EAC5n`UM(P3`50qZgKxfbWIrkG^yU{G=`+$gq@$^ ziy}9XZg+@@0Fm(KryZB4mTf(~A=u^g6drPOT;pO2+?w)9@d;^9FidVSk$@o;ZxXzg<9I@ve0v>sYPk8jk2NQ5$W!PS3_?GE7 zBqS=Wc6yGnXMwbfzu)S;Pz7Mkf7}Fu=U_c|(hYdQa|IonQ9(83#{UBB0L{l<9B|*p zfSfXRtX&)1Yg|nCJ1LLkl?eoUa0^#)SLXkZbB`Y|Su3QTV`K444Zp?7es11_`UdEJ zd>zDaPrq8p1Yn2;m`Oz?9s1=P*$G4#J_MHq+2>WH270t|(GSzm%PbpcS_XmM0;G{! z*#V+p;EC__(hm9#nm^ZoxCFHSmup2GS0}(FSlZ?T*zb=AY)CgA?LBnNO{dZlx~cX2 zsl`E0os!MvepA#c6UY43{#gTa2 z1a+tlHNq7%)p~a46z5YfJs)ccaK_Y&|7@;58nwSqx?ekio?D^1VwCe|2z?FR3m?_E z$dF0X$~{gB@j|O)McjCp*W1Y;ZC|*dj%d39mEzJGP@pglGHiA8a^7L!Ih^EB$-=~` zZP_!r!RB3`5QcKB1D!BX@a-@XAjw22Kj@{fciT1q>vwG_2JmEWtZ)9#dXWC7J1naj zYH>77A2#;xUc6o(NT!;4gkJ1KDmx)b>{o=B@+eT;I#^s~^*qn^#BiXHPB{wz?DauM ztQr*}`~`_1BvUw+JvYXr{zpLN${Z46GNjieZPIAk68QHkC$!ppOs0LrC)SR<9$eNOHyt=@q$W_&?HVLF!@&n?2P^=ki4KA6 zV!rSuM7vnN{idn?etUW3Y1Sv8g5_ti<>n3hU=y{_n*yvF;C26&d|KR#VbP!mG9enBdWbecI|FngeGj7Kbi&{W={_ z+rOYKBkQ3oI#yj*_OBm({oNbu z%yjucAWbJDx15#C^G9leVRA{{VzU~LIPxcJa!gHM`8A4_e3B(Bi2tOwX+NAH~|Fa!=Y6GH6f$^Ux4ttWHh3^NfrrOcW zE6krBCqFO{P59KVohR7#N}lxo0~=bIW+enC#-sXb)mD7Smg)Yn!QT6X{2Vd#ihcSf zbHn%&!SrxcEu-lrB`;YZx@oiJfOIW`wd@%}MYKb2;MuQ{H36pJ0jak&OS=iS-9V1} z$#mdVvms+*c?@H~G3Vu1q;+6ELwqXb~K)a?UxnwU9q2ueZP;+wOjCUoZ7Jw4oJR;B3FO--~{=Cf24t^dA^GR zyS;?7S_S>E|HQuM&PL5#*x@?qV%Jb;r0+WO)Nkc;>pF#+g5^$;D`b=bv@2T~m(^)= z768CRZn;i-w`}ScC5&W$f8SH9X0{6V8<-_n#(yurI@`JMjNyh>)Z*u)t`8u2{O^r; zB>QB3!g{7l7_r+oWIVv#;kc5!AB+OoXqT!*_`^od@wX|5uoiBaohHHFnIs%P8JJpE z);IW}li_SsN2UF!0^VC`ks@x&Nr}=HGCW%0ENn(JVx? zUDpO0qr;LpPJxv17QVLj5*VEc74WenqM6pmk@0CRJ$h0CP?N%v=UI0e3L>7`VK4rj z($`YlspF1r9e{i_8*TLPUHDN%KAZJh7{MGRBTe}U`UIomYkBcU z;1*d^Kp<5BrDQZ@GBr{vUzv~kqE~*I;lis5p#F&~WLi1_OSHdx{k||h<3W$st4=`Q z_f~rN!s6eO`MwI)c(A9g5je{GyS3a^+`}kaTOryPNwC3cNl4D+0T}DfWv5bYQC=-V zw!^Rsac)FXY^3*zX&@6;B-@-y0mSxhLFD?o<2%k<e}(L_dD2*D`}n2E3>eL&H$wSo&sSv}-|zC0*`5 zz9Z-H@278iaTS^ab6VJ*9J`p(0cnSWk(VOm8!r;;%jtQLCsYBjLri#yyC5VvU#<5y z$4f&ZRAbqvztwFhfd}-rtrnQiNbU>yM=T~`f_OqbBP4k@4a~&=*r=FYwO0`gbeVS@ zR4jzRGX~~D*Wvj}0Hz4xN2z-=*?;?V_m$uEBf;xg$M<}vQ@HEuv&l?dsjpXO%a|*P zlN5a80d0n+Ou69Ie|l#h?SfT|W%8T$|futUH1&-v1!)X*qMK zGGDkPGpDQvfaCH6_j`{AME~DE9tf)q8*k#tnO#B?<(fFKAaogl4?Xre>JgT!=W6}K z&XCfhPKDM}8hnGG6Yt%O6%X+kn6JhR3&=QtdER=6ETbiL#IZXRtnn8x)~N1hN)2un zw0ZYIX=(w8jGZaDbv9ppb8+)zCD8t=>X64qF0n3Oor&gSWEX_?$@ZM+qwbyV30y=( z2=QJfkTv4C(*aSftG{%rqPF(LZwS2U;z2-iA|l2~*6p`B$r**5aQQJAqD!7G^9>xD zaAIh%P@F;)Yac9L_mAGK6u@RtT;d>Pq&h~!&~&q=8pZlmEXd97gAT%L^l~68=!PnSpOJG3s1BuuQhz1v~ryrIc$QZPU z$}Gc5PGr0R{2It_k~5CtQ(OTi8Llyp+Ophns?EnnWl8b1jb05!eiPx&B{qJEjQ?#z zD_?n-pTgCl4ei1BekJw4nZKLilfjIQ&Y7EiA69m;-Wj;>XgkylRTqk0$IA4>hwB{c zYzRKt0I?p2f0$x~dRRuvys~<0+6Kb}(d8lh1sWq(;-yO*q76>CmYj&C zp6%HUyIBB4;Y82c;~Eih zkX^weD`Y?Gq~N6)8PZl*ncsiDXe}<=zkNVW7IOL%3%uLx#fVDG3oUZ~#aX8yTjcS~ z9(GPD5SV`}i3&`St)4hD_ZGj){x3(;mw;GFDtXX`Yw>}>2lALV4Qg?bH{GDyasm}0 z*EiNP4g6=5ygKLs%!wp+;dV9fd?$b`JW_z z5;0$1CCyVd4OE;;E_sBvH(QOs?OALr&+u7C$B?o7G#+2|bm6ApghYw+*Aj58*sMow zzle7XYj3Sq`yV_TrQv1a%ql)2&M>X!s(*R>d?Sq%gROoH2#f6S8B8velrPH0@#+rQ zJxe!6i}lAe_bic%cbR`0Ph|8lHNoB6^|N}EE7S%td^psoOMrach@b?sDnb@iejrL0 zCExxNkf{!Jfv3D07tTvlNb4|P-Nb(x3j?Dae(&epH#y`W?~!rST>`hMm&cbmZFfTb z#$WawoxIraNIe>=yh;^J{c?-RQL^&!LH*1BTdH)7B71_hB@jtYH_b(Pk%~g9Mui3! zJf9*V=Q;j`9A&?vSKCNQlL|+G4`(x+PTnsM(l;y(=%}T=$|^NUtUpAyEmgoo$abBdPA=uT$ErG%(_xzp7q@*!cCEqWDe<#RsGAoY@Bw4m zy~$(Bu89f|g;c6}UUWr$&Ge!!M7^1j<8mPu(&$;|5@DPt0N;gDvNe?X6qpa=5h%Ea85>PxYAg45Pha}BL*c0q%ESm!+E&mGv> zfyj3>um)nV?BYMP!vFb3s4DlZ?&sR_jXJazJK}_2j^b9hv(1Ue7Vckzi*o|aYc603 zzjfByYg=dx%A90`S`1^a&eBkQ3$Bd+{(*hTt0w@*0-7vP%zi+M@Z7AF4c2`~!!8L` zS6IIVN5F&x$^Dt&>|0=wS6vm!j z)$+x(BLp!14RDIbp|T2+t(+5;Mp&n(+A6a%WC7h8<4eLnPSLpV1c-1>$ME-*a&~B{ z$$T04Jm%Wo+QKiNF+_|WyEp9>SX}G6xW?rvyVG!v49CYNYZ}0L)ds~2{%#@YU1)Xx z{Kjz;<1@Q-WqgjaICmN=@VT@bbTfu7_q?IiU}F+vN5~N9PiN&sNcTV|E~~6e0(>$# z7MHeRQEn7>6vygpr~+`H4g3Vkgnr`*wUozSl>cO5tHXWUSx)7gh{6;3VSnRq$v#<} zWd#QN*D$^GlzeWVR#P0qYpD1NjsgJ;yx{*NN@)=l-KO4ZJOZnI&%x29jIixP5m8kg z5B%A-zy8?PeUgsfZM@<(nS1w)LLl@`i^QVHm48S-eW*;<1s28z9yl7_iUx!I4g6Vq3Nx6P<|Gu0`>Qw@hwY{P_}@19|8cYPE0+%Wlv0SD-KY`cjopV4H%&^lnVvbR zy?WGPh+eVygn{cPuRW%BGKDYcLM-LFeP<~I?w6>@`G@aGO1JOGk50qdzoVEo0J$aF4mM$}@U%05jlX-h?5wGDWJFEv&#V)D!~trciLz2e(_d^YCH8 ze^Q<#C|V?I+3V5O$X}5Y9fw+dPjv|>S-v0UNjKK(lZ6kFAg=9y$`%{2`ia}uYZL^= ze1Y{FMs!r(d$CSk~{wwnH>f$6Oey`i{LaJrb`d;P?ekd0On)Z zdc2nYBXQ=zU96KmfL#_Xr;dVzg{ipb6W_}T4xrCQ!{8E7hP7?>OcY)v)g@>-y-IuH zL$}wpm~P&9$Mq^1yn@|aRW9$|qw0eVjZw0YM0x2>!T69&Ugp>`;X)PiLmmr-1PQu2ncx^I(EICJYo|?%Hx=HlJ7?_NLDu-UNz?~DZ)1amxG)7?^rZ~0 z%Jr=SE?#N0Oo(oamoXejy_^jn)bvD*7vHlj+=TgjM*G0gG^dvy1O75qa+;N#cj4y9 zU4_PL<~kOhQ(mr`BmF8ik1 z<*ZU0F9e*tEF(FuM4kM;6b*d|@sg&5jJ3^$g&E^c?U zs7tY+v%y)FUw_xoDM?Ef#9X_%ZKU)>IFWhRM%6hb3Py(34T6Qo53tj>ksQ&cI6a$K zqhR0Yk4NHLc&rN>ZED}nSSCGD=3ro}5-flX)ZyQbjS63OtFk4Lj!91Vik!Di^?1%->5$=!k(Inw~{U%I3#Z>ci#fc zX1h}rfE;AsIk4;v_am%XJLkxYj>_OfJUp{$_yv$`9^`q zCho=pB+nQciU0kfa9vOF(lh6-qM(he#8j6e{*W`HV#sUyo9L_B+>MdUOoN?w@({(~ z?wjP8^XTgI>wGPI%I<##-+^bjMLB{rX2x9Gu}Hq?h%=`&pGXe@?{+cbo3zB|PC+zJ zTASWtBWLP`BTY8xzBPT8Jr0vQnG#QtA|MAXh>7<~L^tb&7jXs&UAYzOypx5T7(AD& zy(pWmNaG<*OPvZ8)B1a8+a+siz#!(H;lHYV^b40tyzlH9S~})n9)hS8MrcxKX*{2h z;kKNM!meGd%vpS873hYh8UYgDQt;Sda#hpYXr7l%@PnOQFG>YTI67Gg)#B3bHaN@k zNG|plmUW)?m^7~31HKBz zs^)LjOSSi@4QlS;y}c_aTsShoth!nfNR3+e#GTly!5XPC(LNhRh7tws*$qX@ejz`aS4}QG^SylvC5I;j~>Ojd9SSdo?m0+ z_rtR(yqzodY^!-6Fv0jw(Dh$ECkYr_i;Kysc43Z(h^b9@z2$>K?@R88a_y;DNEaB# z5HapDNVVCTO?19pfxkLpB6J@&D8$Ty^>!>mKGH&|wZd8REfAXW^hS2IzRw17uX+Jh z&|t+xm#h=|jbR@cN^6n2R}%ICYXE<^TE}B$dcyD%vnDcCT*x%FqrY&PIgKm80}W&~ z_`NA4WVpg$vNEJXxs$NUUSS*xXjkMfLsc^App21TITRQ9x2M`j3ps{25^m!N>@(`Y z$c8V_EWxXgY^feE{rqkh8unj$XA?`oeyhIfX9#NC0sJa|nIHC`DY`$NVyhUB>vbj6#}NxRZ z02ex3RP4)w@#Gxae%=%9#c2rj7$6pPo+8$;DWc7`iPBk-!vAD70QtVx?Co80nCE=< zf)Vh7pbaFRZx&FT>AnqHP4TN8ZUEpRzvS#OKo~N^g89tOWP(yMr`fYRQBvtb6Sx#v z+-QXwG^6&Vb27Lw8Lo>$(K60_;~t~;?35=Zt|rP&mv=f&G~YK@hoN$X3q^|pBsc{> zv}ybkY5npZ#axNz_k}q1Z(yB03jWBet(0Zz)_23giUB+F_i>=x;z8G2kK*}OqM?33 zw2QK43W!u!D2E5pY7lXofDWvxGjhv**+vN5prrlXQkH9Pk$Q*AA$bM$#6nxp|B$ysUGB4HiF>C~hp~ zkCb@NbhT^Vh-HQ{Ra;=*^4?JgGtU7_4I=!?Vp68}4+=58iT_;Q7+z}p{4KVW!I!}C z`Gv(vNEY$a{ulLXUB=4qitfPztZAhv=ZT-=Kp=thC&JLMLtjhtZofeX2ZvAKkh$*w z0B9EUuCnPoEU@(PHeQxmm%JQdEiBq_7#QU@=gV{EC zg2~JNN&MSKJKmNL2^zfbI*dNzO&~z}2oZ$JQ1F=TrNcRqwO|DaGI;u>PnIbNWY`r2 z;SGc^-hY;8df)z9U@2>7i{XJqsB2j~N%ltplR-Oyl=*QFeXol+j|%fUx43J7fM2mZ zbcAoeBnb~C;%tT-l*2zA(@z&P{m!Ud<1Uhw`zxQ(5gb@wy_lr3zE?xqR*5Ohqpi&9 zjgJk9Qf%whP69GOgSXfIgTuh$e`2DJFo(sQKl^^Yq-u*Uk zGci?~FqSqphFA&&Z_DXaOgyz>i8{zUc|0|fG^OoO(Z+TjBc5;2QLg74!sc8G`B_Ee zSx=89uzV_4HQkL{A6R^C@ZEIjSLla_zt=dsjj$zxtrCanm9?!{_mo--Vza63!s~Jt ze&S25%u0)m&2QSZ!c?!gO`F(DLqZIBO0;XLn5lUQSuw)W z`*hO_^?i;Qr~a+1VMS*%^ifk6^hBDJepSe`)#K}*Gxeotn&5qoHiR2XH~oQE6>`W0 z$C{jezHtvVwf(Krok)-%F4N4pN<^d?%2?dA8q2XhhY2WxB90jY>OX$J6VF=c>$+I= zxk4dFiOa9GzF!Y+x>&gHwX|b6^_1DRHloIY9E<&GdT`a}SK;5A)yh>?bsKkb)})Z5 z?NxA`lV-C&T~BgWrZB=NriI_d%bI2g~zjnU6{7{y+JH zS*4aN34Cq&mi(3(q1Z_`n9yEem2j!ye3fYlnQ)W=U~N4mWzMjPg+|c~v|t%1J75jL`domz)(tG|EPnWK+v znJa|H+@mYpJ5EK`e&ozt2vq7CNGb$Jl1~@ZE_MC0H!Lpa6uYPjI zMt|oxMtH&I*-aD8(oubZgx6KHDtEQTKyo`P;Ttb0a_Ip8+*k&=F)CP4a4o{I)L3Ukb1{<^oP$)qU%53R z5tL5#wyjn7Eg$w$)#OxwKuY8%DhC|;N>srgj6vC^VrBsD;3(rJwVT6QtAoGsaypO@ z2TDLbDORw_v0)0A9^-;TiYJ-E_OO+Q4k#zGl}WBp;-q~LkS5m^tMC8LD?x_$B>BTZ z1t=5lh9hUCOsh`kxFX{)Tsvl5O4{2gW4=&Qb#+vjM&eyPs@B%tfMNs{?T8z-4Jugy zulnC5H6y#oD!(*;Oylg>Ey5Hsq76OnGD4ze8zRt|(!^B&rMMZJ^$9<1bFsHc!L_=s zRCog0F*I~IscZ_&lLQc;{o@xuE|^+jMGd$$KWqfqa z^saSga3oPQYQr1jWwJs!PwA-q*j>X83@_sQn&ib{x;r2L`xxypb2Ta|NYdBn!2wa?NX;I*uut;QfYv4qJCLJ@b_V`c_WA(h0!pU9NBX6tNwy;j^7jp zf}Y(zr&PMRG;b4PKSfHWd}~1sYKw}}f2v*t zSH65~%aACgQZ^XQ+_0zQxY4?HO(T^EW1z(Cd+do-2>ME6(baN0Oa18PNX0j6dr!eb z_#imG787_Ktv@Ins&@e>Gv9tGwq5WlKhB%245Ft1$^&aEx+26kDPO6BEzkxl{azrd z1dH+G0+TuU&CzZsdyXFqCm=JEp|4f$n*l29DX~KsS(R+=)Qe$R|8#y0@rDT%#urd=vd$@4j`85O* z*!^O-mi42#UgK$5svloOzb(cC=Y-l9ai~517kYpH7*h!b>%EAY494)=MPBn{JUP(2 zV$$72+!5mJ@cc{FGeanynX6yPT%ro4XIhVRqWw{oKKNAct|tlBn6=+T@~~2?nQlQn z4+n27d`&FwA8+MFOy!sUy;f^}nNv3Bq$?+~M&N%|!ZK?UR1J`FIg$nG^ z1fk1kQseHB)n)*F>&FYp!Cq;TmC*UtKAAP;zpa8niJJ9&WIgR!;6bIjzsp^P#&2N_YQ^8&fqSf=z!^sNq$srXfTmLiPGiX8uzEd1-6g$JWV zC_=}9ayQF}-!59(aeFxW%9mt9%L~k>$NMaUNkM;#5oov@6?fTL%VO>AdcI~v%%v4z zBa|bd(0x`Gbx3u|=;1!jPc`AI`pp3Pv(3%BfsLgRao0w45TD@+lNMv0B2Zm+u-v`? zm-jLje9^%UmP=Re z#b(EXbB=CTfCC$k9j4ncGe{u*`1B|*#F^VTaobAT5bH9H*zg?tSm-^v{!YPW#R-W| zx~=r9`sZk{9C=Rz1g3*{d2bbfKi)Sn6_iG@TYV7!)!6RHNtp}ZVA3Fzb2o4xRur{W zvE$6jw+eVmL_hDd!d2S2r%W1WM;PgAi$1Km$`sPAggYmum0ii+>xm(R;EzhGE$cwu z5>N~O6y@A$_ggB`>@NSo%Z_yC`fjEv2b)-beh#kuWLm6*&T_$vQx5;mCoA4yTy%6E z6bwVvWYeJ1i$wcI^txWYaPyfW!s*8>emGA4(#ng*UKeZtW2H@{Wk_+@a`5wvZW6>m zY>x`(G11-dDyMgv> zl1n~RE?GGtjeGkA{il_mI=IzZsX(Zu8qv-zBOpu1rG@K|O*gO|hsH4966awU+n^wEzIxsJl~1`&@1#ehnUMGCW?O(T){v6O4gz!|ZAK%)+C?m5Y7`MOQRfgq;JsMrXi ziFoxKp6)p#t&`dB3{GigSV> zVu>#Lb-{i0;87GaFz1p>vEi69x;Br{nC`~0JuCb^kV$C?#Qtx-)!<({2Ji-_^%B`= zH-ow@wWrS(W-Kk86EX?gLvXQGv?aB_R0Xy=?=VOtZzd9MzoJy|PYlQ7w5uXsY^}NK z-p-ut)TqvHg@f+8l16>;P@y{ zsP!`*GgLs8VqRGAYZb~F`N(Zxw#qDKFAx4qgGVwb`oHd-?S5q z*8qk-&E=Gm{c?;maXr?y){ylNW~^dP5On=w|CjWxYUbJ}lW^RJMpAHJQ3%H^UTip| zTnb*4%KP|@9tS6d$euIlb6j~+`j`gfN7RvAX}I8FkPokexW?C(uKmQQfNJL_YPAS* zP{#S6P}gX7q+h2a)o7-C`5ea?~tQBLQZS>|0uPz4DuGbPwH0g>O;XzCu0` z?#X0!pH@PKa!L?0B_f(CXuZ0+pvLUREGq}=4^G}%Sx{)W%h9zh7(A^XWG*W%gP};b zt|z~s-lkTV_ZL-lBF899cbp<Iq_L#MU{R|EV`t+N!LJ46H8iRLBxI*!jEk`SD<>cVt_U9l! zQaP(QmE-xfZgU~AI|4*cWfuan5M9uCK_ipOIJw9D&LU&7}GO(j+xp# z`s%moFrG;~8Qa1K)H=-46P7YZKvls^v4>IpUF=A71>v&|gr??dshUqrVjgws1E!k4z&dmRY1iJQ#cXJQzQ9j8|tw zWo_7I;@I%;uLo-Ru|^UbwL_@*hhsqS!VgUJ@h4{fz#yYZ|EpSpCb_ap@xdYeSRkJB zTWatAINdj^$i$*&l)1?kWxYi(bsfazp~QRdGKD%tY8>J#$aIvKCSUXIGl#Kl{cT^y zIKbfh=Jh3kDtf$1j))ZeIcyB!RyGREV{T(02f+R)52?UEHAu zL@r1GV=}Lz%QnkLRey{;_1Ly)aXv?o_yy4TT(yPqWYU%tg>pv$j9E~w(JkZ94LmJ= zCqLcN$DCcvEbSdFq-ZMBbsUG@Y~Tmkf1VSbJq5-aNye&=yi~z!*5ZKKN`;l&xc^{2 z-D2!PGEER{davvPVk3yK$kQvWQEGL=YqNvOQ@vcAeJ=6B6nhN(((ONlW#OaJhbo6FDOv1T=4pN1hodP0zk|9feKznnchS zP|OO`H{S~C+4mjV+_WQiq_{>8M7wiG^albLyK7L^8fdt*RK zn=!zEm509$g{;}y;4kb#e;mu5kP#7#-hT(Jf^KuQl)N2$MQ?{NhT!|(oWR8AAGD{; znQNR-w9lxkZ*~r6g!6b3*CoeJB-a-wFLQ+%e)fV>foU);J=4-Lw(wEI40PXRlvvRN z!E4IFYG0d}_<%#Kq@`BM={?^`Q6IeX2gc$tx~N%;zzDQRm|Lg~%HvZ~Z8NK$q*J|9 z;p_bhKND!cqtIJ^0Ngzznqbn;pm-t01T6;=(SyzV*J3=j#=S=SzP4i8`^dQk6M^Os z`f;EgG(Me-?Iu{q*B6PM1uglU^ssb|`!ZFq4ZcYQ6qgX*KJ=zk-HyNluxB*Z6SeE~ zrDt}c)FIQ|D4C`2iTDcwIa=P{9fU=m8G-MEa;!yUK2Q}MUJr-uUUd42y+_B@-wO9s zS2Yn)TCw&l&GjPSZT`BpIAp#Gk%B*@rN`2|HF-Kkok6Aps*AJk-D<)O^*wxIH>}s3 z=kn5-d~wgmBc03Kx_h>_MTSUL{UT$#+7ak(Q(8wEv#?n`yNSdrDhhj zDN9;dWTc`gE*SQ&%X$mgdD$El+l-iV}n{jwP*K7sn45Hg>1 z)U<$=Vn+O5?QYqC_Z_65PygntWFx+0kTUGUxI-ucl>rbM&duz$_$^WVQU8ob8m#`w#%~50 z*+=rBkAWp~j`0yYAQlPF?YCqAV7MIn6qKpXi@W+9gHn~2Wau2k^rQeJ*U!?tAeF#| z3|;*ckFJL^a9+(-OkM{YwS|g5^q3i`da?T(v@guCnZ!C6rH943IFF! z)S-w9-S0<*TRxumie{<#d;p}{IN^z{?k;yy@q~s~up?Elwr}oCoi0t66-W3QZtK22 ztAJrU0i*t#C(c7rYPOlaOD)ikwm@W{15Bz}MZ(cYp;S_7NpYjY(dz!)y#66hBT*{O zKCqm5-F%8Tgn$UWk}(&c=PQe}3e(Gb)+POkA%JM8Eh%xo-XXO6SVZb!R&9h8wAE+* z9ol+65jQ+^*85DQQGG3ABtR?x^}T~_Z7{)J4>bcUJBBcso1E()t|$TPufq}Bro_Wt zHkW;mhz>{CEj`%Day7W0KxEEUT*7Zyr=_BARRK`rSX4)a7K#s7_s>Llct4c zo7JS$BIZDRsLHczzcnirdNQF&g3CK+1FMg~RE$I-y*V~Ovnh5vh#Y%aM%bb#ePiPY z{BiqOw{ls$$G7VjWjFuX?AUOvn*klp;>@7T9*+Mkd>!lay!>Ihve)Bc@Y$hl?fhKV z2+k99E0)mRRZljfy2yR5LH)3Pl&1i1PQvZ-H0rd9u5 zIc1|JvQzk}wkYW~UZZ%^7e383B_ei|%=>40PGxszP7a}72srQOdK)^h@%Bhk&K!~W z)!|eg(9{~(3Kq0W+wzZ%=`MbajcZ#Q@BB!H{N|}k1^PgK@03rF3spZCZRrP>XcJfI z+1K3&Uj26@VBxYnu`VDdMTfBQmScM}ovoPLo1*ez(Bzej$NFJN_gk{_&>u7kf{>T`Qu-TSC$_fEp}v&4bK*WgEP30#47D$&eHz zQlr!@u_r|HefQBg&E)I1$CMJTi=J46}NM#6LD>K}9BO!bP@Wf}8#*}HOzsZ?PM>Jp)nMd0?k#~4z=aiaPdlJPSn zAUKo7)w1+{NNXo@`e_M{81&~Dgt#WmoO6(x{-w=3PS_?kYajm z7~RLiUn#c#FspvK#6N$O7@(8NJS)3IaV4ucWOGU1>-A27TbUi0H$)UeOHP>Xy>Y@&{ex-WTyGO|Db(k;jTQ{O7_ORG9Y{ z{LJ#dYAN^}22M%^;;&3THx>n?A*2V_+uKdN%xcKXhwVbG;z|SeJ)~78?&FqD#DeYQ z8p*yBBflV85w=Wc^9j9&?ljr|PTy=)r|up3tZ*uPT7C;dY$J(|tr+QOdlTRr!S}Tk z|07w_>TW_&1;;t{XdmLFaQTQSleCCEqV?>>L{I>8BcF~Z@yDFxsU=M5NFQMF{iu=( zS(Q7_pb?K%_G6eo7^Ha=Rs8y~^_C54TUf@>h5$7O%;N8J3X=7adO!|X{pZmG(&}z% zLOq_mBro3W^eX{JMdS)c&!`G7rPO=Xh6^*)z2>IO;}*suYVGqb7>8t=IeIj*3PP?F z36oy?ld`TrDf57$qOTWLTgD&;BA-o5E}V3z1{>FPNPKIpML)uY)+Qn(6}E~&;agSW08jG+!<|_By?Ikd9AheaP+$d|GyT5di|9m zV8un4RY3V)@lz90Qv=*~$Jx`GmD)u6O&Le#C99?3P9}ut7OB=)RRtA0{%gZ*^YB^w z2A;uSdz9ApvJ&@{;Kh)R>5?=23(2|Jg+A3y+~%54BYK)}CY1ymg{ z%{2e#a+N)WJS>(Gr@}j^9>2$t*IWFdh5!9t5#+5bv7u*N{zcHvWz;Dz7xqL29Lb}+ z@8adY9HjvPWG*)NKelG=gDn%PLg+X<^AB}A%*LAwBJmvl>;{clp#y${IMRf**7_(l z28lZN=^#Ffzs&`b!YTTxYriq5b%@s>59BwxUC8jnx;y@w#~LjqhxTsP%A5`LVir48 znAOtC7fBY^_Y8yT$NRp{2)&B!gT6%jln~0U_S9cF@Ty> zA`Xy1&bA%=F^cn@p*8+>F@0h4DiTpNB;0j}B&`*Hg8S1@YogI2VMHY0ya%x5dtR+y zzKUrg@Sl$Ew^h&x9{9`bd;dJ(nJb_%kADyWzegJ{*`1|}mUq3t+Y$UwqIZft`@9dm zDzT|MQ_QBFxvgm!f#C0?B4jX=E`j*Ysw-RnP3@vJMjReg-zE={ z7=WW%8ltYCKi=UZpp1!B>&?CuDm7zw@EDzuWXa(X2 zu)RD(-9XXzW5vKVy_anP2oK*2N<$wlDLS?+Zz4cF&j&5w4z*4^a+Kd{kY3Bwz=1IM%_Q`HXUPH2(GXPgwdxK0Zq} zBS=I`R-?C(h1rm!f5=)}NfryNhk+g0Lps8ff{-aI8UKZ@!qH2Mi)bDbw3ljLcU)lXSl`d-Y*5~^`eSQPi{AxY^REC+-!xjh z6(B~y0x1&lO6vVbXIQ*inv;z&Wjs?UO`8;ifnjaFcFY)nj<4ewN_ZKgW+>_g0pKK) z5I0q|h?K5GxQQF1tffb0j$f1$HbXt49!X9p_u>~|g+U`99WEJcwcK9U=9KRDGIctc zOOV#HGBrVOSILXvd*7e)2}S!iP`emefyK#zIA{PGSffPi;npN*LODDT&S#y115*P& znyw}LJ6_I&gx;P)gDV|(8L~X-@d)|Q&U$6+`Ghq7JK zw&xy*I%oFJcbilZcP*C@vI~AaDc^)BHG-4}ESWwV&w%o)?v&9Zvk~SnpyO%I*i7oM zpPl5OK{;s(ZE@?CxM$R4Pa=05#T>K=Of@_$hoX98;|$IBJ-kXPE@n@SDg05X4EXS( zHNl*7!pl1^8$pQYr$hH_ZUETr97^eToYWI?JFz^wZRABoaY15hFkDwU-*JEv}G<3o}b-7oEXsfmsH1b+# z-J>`u(yrw*;EsEnc0TQM>8OS0ncP%?Kb32#FzUMI4Ai^*welOi21E@Srh~KBpQ6)c zoQJJnrKkhmammFeKr;3p(e}N<)GC8K<&cPki7v7^CmiBF0^1wf>O@BpTjN(_bB~QY zvsyrKteP@}oPx4^M<(T6l z`LoVzTr1365e~u5CDQ7dt8h;~gCvs`YTrDlEl-~PVC7aeS;HBOF<%ZE5`Bs$*EH_P zNTnpJiACj(qOa*5aR6^G{O%MWCI-EI z^hKtj*yJmY?b;TWZLaKG6aeu+b7+Yh4*;zv-l>I*aUP?oB``ox_4^-Zf~bwS6*Wrt$7pDarkQz>Ag6{LvzBgkayCB7YPNFdv zKA4y}ox*>LLKSC3M2?N}eOJv&CYx2DUImyD90lbaQ4R&xD=A74mR^if4!2B-cq;Apbp_cwbmW+5 zI_Oely(X_n-!9Cx@?XhBO;y_pQFP-2mF8;g1GGdSGmv0KqtL$iqDR7k}k{tl#$F~N>js})p1E+ zrz_DcYGg|s==l?r^&K1jP8VU8KAo?y7EFjx9d}|xxQ1&;o$6PgK<8K-(e2L;V>q~{ zcDTDHvyM2FDGVb+P446AP#o@3@J{|g@)0w8)#*;R?)p1R6l_t)A%jEF4;97W|LY}u z(^X-Vs5BsG-Vaw-=zahWz@I<@5XH5;%^a2CGG_q~xZ--C4=<00Rl_Q+4{<-RT`2E3dmxGyUBg`$yLgJ8hnH6Dk0j* zJ)309dw$Ydw*kf|wa=1mzfIV;d;i~Q;0AwF zl<6_a{>Gh5jh7qdF>XzuMqs~rI5)x;MeK%fYmv*)(yTQ)CSF3vfThj9O!Grfp9ABOo;a`Du zbNwFr>F_!_nQIJy7)=%o^$DxAU}D8JlM(IXz!`m5!X3WWypiUiAH4Q@WulXL0Q$*! zOUcRxRY7r$UIY@H!fb?pVr=dYD^ z&V>LbuheN&^a4_DqDS*rm$xlPK%MK@WEJ;N1WM)FIWkY6WS#KKM0-r%mu3uI08ax5 zaQ;S%lH8LK#;LVw6O74tpIceeVVRlh25A#I@96JZas+)m5fq$(-GtsUMQHaq5Wjy7yD@AAwy&TDhvh)k?n7q4hz@Jo%yB?9M9NMiXNyk0l?+-sjWd0# zH#M;bFE(Tlyo2{tB+@++Z}c!o?XD~7HD9@1)Z6V5h= z{IT)?Juxwtwp2%|)&-hu2Rn69q$g|Slg6M87B-9tf3ogB&J?GoSQWF?XKN%|U3|Ym zCsq!x6};X)M#mXK-;srOXLx4tZN z3J#(S%-)TIZ$ddnQ6zgaD=i)01n(66QWG5#;#D~9v!XtC%)!~L z`rq179k!{6GiAT2yMOsg%>_1{&k`XPEW>$%_)pS_dw3$UAq0EeRqsmznI}ZuqOJJk z$@hm{{4%f#b~Bv;QLr(mO`L<&{$tdNo-NTm9hUg=%i;*(6RV{SvVeXayyZ4eYUiAF zSo2NcJJ^~aG?2xpjwVyUtl)j-{lDz^XOr{{55CYXb5U~0y?#UH$$IL{iuf?Z8=GD1 z&h+!-?+dn z{<>`)376^p>ytY^J`P-~(LCVf+D|3PDKiD3p+@w;j>#U(_%+l60(&d{{PZ@r(v-2L zg>Y!AADql0EV}b^K!%DC_ggH!w*)rLSx9m3=~1;&9GMC@|FphhFR;xZak0AWQJlmk zLGBy{(vw@$XKJgx9;?1Go*24!^9S{#48xM4Z6id4bpo`p37ZZDQmbT7D6~O-9czWj z2L4gZbv%~t+O%g8q`IipR-j|ZvWft$BfhjcLi`|OY8+sC7h9qntg``ardaSk3Zu6N z>_Gs}UYVz0K07AfT{7U;!`|yRMyDA#u^1czJo)gfr?r4u+3#^Ht^eRjE1jqobi(7%)PXm_U&q*D@$((3oU7M?l;Ks&i*ABbZVp-lRl z_!1esvI#0XT0GyDJu7_=?id6sN6tY#<~KSC(+g`9b~23sVo}?|vXEZ|hXE632sg35 znQ?SP)vbCE9{|4Vt*E}|{|Xp|r?Ax&>5mjLQS6OB^Oex>henKR-^%QG zQ>nEa&biP+C$l-6osjfCOi&;+sR_bd1zNL$Uuvy-t2lp!!XOS%z$iykVDTvQVmr#) zw+Rg8d&Pk>Tn-w-T!()`#7GjU!nh? z2|4odfLA2>6jRPahQeo13CWUkyJn{1N*&Y2S*?~!qQIihMv@hrar{!tWt^^qwa1`~ zC{H+t9-ltTf-YGna|*0lA+%loDeM8oxr>R+@t%=Pz-+Y*fkB{)JuZ7*V)8;t#%9zfbOsgYa*| zx9?WMLZ_tH`K&4KE-go)3J?}<4)VjItb|VV7-%S<*B~}M{JhyoL+#Aoe*$CsBZGes z<^m#b%jZ;TP8td;XY_~#8}I0?MfZEgUxH|DqN;&!Xk?@*e6=#O4ml!1v?DJ8WIj=T zD^vkzLB845@VHz^!jvzk@l;#^oaKiV=K|PRyf8HT|2oz%nn*6y&qBJy5lyEXS6L;yYpb2tkL*0z;cZ7oLJ0cs^<*;im zhL?5kf;teA)(*9p7P`B+oE1<5PY&$yUynS`JgLJQaR1GIil}#_-&;xDY?bAYsh3q| z1~qVbo{Mgb^+*Y0b)B(53ED;|5a8W#mt9;z3Z|`OK8?o@*+sFPkc(j=};*4wd=xPqCTfJQdF{S1Dlg%f+QqX8ZS4A zh~otKK8D-%`L(g};e-ooo9ryj@nLLu?ci82p&!kL^y7f2n>F4zkhqo~sJH<(pv%JA zH=%i;{f*3ApC3GcB}sQ|X&)K7BS|GlXziDoT4iY!sqpf~KPw%xJ`aQ(!j^!u`Xm5) zZ(E1}U+0D*=01n$dc*;kzt~Gz_7Loxltg674-MY3#d@yj%0Sz7uH>ywNoG3Fp~$^v zj`5ZiK8RI3f%+OQ6nOopeKi+t+W-reqB+SMLDCRX;S{P@h)P@`74WKw?8G2;PB;D# zx9CJ}L$k3Y1j7J3TY07=28IQd=1Vp9a#YFYb2P$DvFuA<6~~uAzPj+Ds_;Au^gax0Qk( zUErJp12{ebCw>9Wbu9oq?fFy~HUgn7o~^;j`ku`)KI~kJ$0$B~BI+3S)J$?4hYAR` zux)IJc~L<%#ca(&m>Oleoar;5f|Z&@U&Ag?P_V(M7IxTK{GV&mE|SPsz^K23F93w@ zojDX+QNIpp;V&wXN?7+i2(!_rh?xPdwWKLQvc+V={emNz*u%B+OvKPR?W#g~ zi9c#_E@m<06h2{t)aZkoTjd<-QD zRFPnbNq8g9S~7xftlaDoR2+=hXhO!{Yb$=BMHubHE0EX+BdG>M$vQ`#%QmJ$A*64o z>Zn1$k{cT^6$&;d#U@BM&8_KxTFRH~0;IofF*rk^Lbdb>4wJ0Uu2Phn{<+zyft8P) z74JSs@H8RDlGzdnugMI5-(igC78_;*Gi|opD zyS{_5QrvTRq<6^bgO!YePQ3KLYX`=#@|5m_;jn&XHql}72Go}d+SGZY=PpshFoUq_ z+#I;X5JB`V;T&vI4sR_7S>v?bM6XrGL`Oag1yRc6zv%HRS2c81=u^p6+PmdIB8s?d zaSZ8!=*C87Wq{3|2pB^e$lXMpq$rcLWKPgK6jVBF0m(V^j_6z*dfq$ug?;j(_e2^o4^ zu}HEAjJ6=Z)Zn-X+EK&OA%80~9o1e(7M0^c)j0tPxLM$w){CZM9@n^XjRE_s_5aF| zB#~BO_-0x$M8u(m^h*u?`g{Kw!#T5o=*bzG^WW5C+c2F%p1v9qf?@p#_Ib0;E;VU2bt& zz(x0GIwht}BVydvAMWtbVqkr_so13FviQq$iX>={KV6O(Xvwrxu1{Xj)~r>Ilu%?h zIRPCVg(Ov$Iqy*ZCkc>7KOd^=mG*a+Qj8rAb0}Y5jW{DdauH-VPjk_woEjl6Q17>L z4(7cZ(*tt!y&sVX$qF>AEL=nMW!R3Dy5}TAzACLwS+Qa5{^~CPU%`Mh+H#^h~P$i(&7h3KdL_ z&i+WGihQJ~9?kpPMXEocqun;VnNE>-cl%SQDw;gi0{Qc^K)6B`vwwp1op>BGP6W+P zD#>Ke(n4!TFXvV@-;~IBR&wpq_DZbyOi-#<0JE0Y9iPwK5%BMa{Z>_X^C_mUgrPHg zO9cB56)a(b7h=wriCy#fhaev<=nY%F=l&FFyxre|Ce7R4Ealga7cS%#GFacMu54ak zN1k)}ZrHYQ(oz3;26M>?!g%i^;?s=h`mYs!ha~av4eg3mIJjds*hELW?sqBuyGQV9xNU zUbrbaxAt_Z=&{Y8F@&;DtUiZsBKJMstoKaoeu{@%tp-+!DBKT~47;eXKShIbbZQqA z$JPNHJ^lmE;b&5#X0QT$3_GrfL*0CcMLom`t2B3Tiw8Con$7vPnY8se)=_p{WiqTt zNicb124%Coy=E=CEzcsQ*GplG@#4f0K~|DbQHEFyGrb*Ct@V#IT3tt7MgSoXZu7CT zk#*%I4)5tQgfu`OX)5tDAA! z@OC@@Y=KBvR0>xNF+WV+NS{zQZQ;?c({MO7rD2ic1EVv{h;6)yVG3*~4>GuUV4*P? zFKs^&Bi|9$&YHWrokmK5WF6W~QZ4GULW2th7dZobp{r;q?no8keI8UGN4r+MN*66y z1OYsn*i-(q#r8;*NJ@o(NV|fGQ7BZxO_ zMlFL>#hUo3Q2QLmb|{ z@+hqgcuIwY^3}hcTSK57y^C}{X$w7yz#)&e$)%0wpxsmnY4!;LOnO416(t5@c4_Zb z7dqR~c5XObez9uHAv8f64s2KdchXNlD*D+qv>DVqA>Xvi1!1osw@*RlYVT1qpe5tK+shY64d0o(ogg z7X<`bY%^5Y%Yi28BV~@Eq+y+*6|FJ!$SU&F zffi+caDqN7!#(&a5XLVn4SJHL#RRV!Yt>V_&msU6p8N|f$5lZDw&5}z)I}u1(n4)i z1kz2caqhbfAw!u7zCV5z1&Hp)o-&QsiqRD3I>2H;L=tjv16U_0fN8*>p9FK^QB;Qa zO0zJ{^Lz-8RVsi!jU2hhnfJx&b~GBpQ{!Vme+N}U7{m4H|?X4f^PgM!l>8e(xAE?6-iYrza#Y{;N zIR1iZ2d06w7cvTE2q5?2h7%eP;1z;{JXw#`wMr<;*b{!V653X>_HKxTj768rqwIyv z;op*0V`sZBupXup*DNG5%5(s4l49H zkE0j#*h33Q9_C#(Z}4=58Q#q(m(uy*J$T+gFQg+1KLEM=o@+dVH;H@WxIa5#WbJ4V zz)-I0eWFekX!G>v4k9^$++t-N#=9wYip%w@Fz=^BTZ<7b2nS?OZ!#nl+992vsG>tr zPVlj9f&iAI$YccaqD~I4iIZ%h3>ncJBP4d!g_AThx~d<3_=|ZRxRXVIH&IC%?AY&@G5j18e)6$r$;>glW6rOVx^K_uST9J=KYzyy8-9 zFoX=bc~>;qL=;J6mPkU;vtPw3A&(BG#OW8=QumH*a!_2l5*r{C)}v)GqcmPT&p*R+XhrW#X0J8I(s1q_2jl z*M%5ZM`fG$_aQoGG~&ZLrTg)Wfk%&}~! zK{4jqW#@O7UFoZJS+h57D~ltf59T!`)0udOGb)^2i7=@G&D2(&#pDsXzdoS+hDn_a7HFS{>*i}^Lf87y;T)^|q=l`hwl>xup-JP3okFhDL(&=)x zA|P%H!W`wb;vR6`n7KgDF3ZyAc)KxQbnsMtA#YhS?C1~ksP!M?3GK?u)znBVnS=Et z;2iygKgC)1Uwo9Mwu;&HGjq~m?Gdcct>q9yUrXIDgKph$nFJ=j+but`a>tKtKF}^R zL|+{4HMDdKtYyF&APBfx@zwikxZ=I6=%8{x^M>)qS;TjDU}zGleC;Bn2D~AF;QLU7 zzZ4Tg)(1$CJ{p9QmU7!dk@x=Ek(q!_%>^UtY(6azCR~_C^^7p&Rvw9>iF<%8lwD9b zfJS_0p8;^t+-U&8y{ttAZ>T-Uymu1s?4Ra>(yi0ei(IV>-K{xeFc?B z0JX}Y1P%(TC8kD;l;~kxGK!d~{BkTw;ijplxM5; z1+?I2(DRdQ9w6ncQgK4T`X1Q&Lg%kyjUAzdoAkZHXin5Z2?bTl^HVU)ea&y{-~o8n z9tqKx(JuJOi+wt1|Jn9D*LMkD!c6%!mNLV`{ALPK+Os_`cuH1qWqk7#kYT3t@>4EC-~2hwc!khsEN@wl|j7Mzk(Fb^dQdVnP7*{;-y{TDD-vAgBA~LtO z4;!fMx{pt`b{Sh1Z&&PR?4(ry6I)#C9ul3uml84DuA5|yhd2>)%r5LqN4bhea+9%r zFprH?Kr;HR_!9U!qVX@{kbsw9UGO2=l>3cC837mxg4Lz0&{oldk#I^>ur0y8!hl-G z33`Lm6c#cWjwZ`fi)TlctNACog?^zeHTXpMn#y|tAX|sWXYez$t@$OMDReQTSQm_C zZ65xFu6^87zn2!iV|EGCdzmP%95|qTHeUHq3K8-5t*7*L!LgAIfLIu{A3A0c9L^;v z^v~ju0u6jP(*-;mx})&7MS$?$XJe)(+DuwCK9*CXD~W^XsCW5C#;A^X;wN0@mLhi| zRy<1zm7GO~eZH6C*MMX=aiH^2M_kbU7+_*{r|I)!6;5zoQrn5ka#V( z(QTTpeNEyEv=jr=SJ+-)=yithv|d6co%0$E1CovgBq9g)++Un{P73HBQGC(df)`a_lE;=>HH z+TVq~5NGQY_tez5fTKUq@QRK6-kB-Q0!0> z%JNRKwq-WwSq=LOd5y98?D4vh_O&b6!9+LEf@WP=^*)n;zeP$k@Bpd{so-|Tebvv^|NjQv`W*8hVsRyA`1o~-Xng~@a`^xuf;+0~X$WEs0` z|K3zIk+LghbZ9R_*C6rDt79)U!5`Q|iNisK4o~3KwP>gl#{o;j@Ta@jnQz`R>c6!; z+`lmTeA|DrQ2rKw`8_G_$jOP2O|5r)uQ9M8qh>;D0|nzPgTKmm<|SYMmFs3AvLw;+ z3))Z^k-GY@C-lm&i0rxrq#+P0kPp5R+=Y-H9T@4C=D_RRY1)QR$9x}VP<7#o05>|# ziMM*dEVl|QB+eAl(&;Zcgc3LzAl~n;VNpc4JQ}sFvU#`J4G~gd2`pTZDvPtw986px zX!`x^Xxue+4S>J?bCI?3H^}UF*zui0egBux8&#C zj_Jd_Lp*aPmSdAsg`Qm8VYM7=n7@cb={IK%*b9&c!tHCo0v?I10bc}mTq2f@=fAQq z+Pj{g=%Ng~*UjrrMnM3P5+Me!*vW90^s>nP$PTJv82v`wMHo zw|bixlssk8E6r|;e;=dlr{&*X+AM4GlQ+EU;pVZ~=0qk}Lv9<~It<%@(xLQ^yMV{x z&$k_2IP0`}+ipQ3TxspB1Wtb)ka#+bNi zKMUwfUHyQbX%=Zxc+4`!Y*Y{`Js0=n{0pW0Bi60L4PXC$Eby#;(wiDvF|h9=29O_D z?EvX2*%5OQo#kFRk0lt3aL87di&5MX`%0pI6lcVA4n>7yp}%cY z{QSC`;IQ9shpk!R3p)?RGqPEG1H<2Qh$R=|L&(PrN@rogNa0B#2rrD-YCENfEKT6B&=L=3`eL#82QK194IWk;3hsm_GpA*PKu@$SMd5{ z!|dP%EC7DR=c2P%t4={ZKkTcqQjZM)n8q~!7OqMd!j9)l-Cl}v5e;I@6 z%Mkt>N={Z8BxPQ0pSeh4o|%7ez^mKt8d z{)q-eAIKyFmMyRIa50N+4M6hLSx@kMuGZO|%eSwJdA;TC++g7$Uc7CChTri^@s4Pq zyIx-@K5U3+D+KfC_9@Dn&bR<_vQ32^Gqcgv?&5_;Kl^xjD&~=kL(<8m7NCS%c)W@aF6SqP#n6&w=WXYJ-{KYi6(k3|j(H<)qI!4HMKY}$ znc#a^<(~qMlGQ96rM6jsF2Y&xlOMBS7UVGuNOo)w8pDtS56=>yqd11_^1liW@mOd;cFMZ|MZvIaZ0Eui zZ;xMB;+oP;VWH$!EZ$h8BWfWlWAuJ3Mck?(`aKi<@rLWgo!Z06izZ9M{{#saS?dj9 zenlAa;>i&x7;SjPqdB7STC;Rl^7UD8(h|}Wr)85}BThSxju-;V9CetL&V>w=XL1N) zc{#P`*|TT&{xA=V`zQ+yB;bV`v4eDDeZ#2w$mBv#KDerL&H{f%%F)X`6WWleja3!1r4cQq=qo)Lkv%LIGH} z5+{2MX51r@>g>UdQsTI2$#WRDM)r8#Ma1R+zg>{C)QfKa5-1gt`m2gM0}kK`Ywz_D zI+-zCTp&{VJFTk|2<4iz*s-+UAObzLnA)bT<|)rU$s5k)ESAG@;jVnXe^doF*O@3J zBcD$jx-=>Pj#+}mv<80l5iA0n*n42Z0DsW}@rgZ)1u2dIcV=#>q;Tt(c#2rULT;tW zs72kU2iXom!GMVvw{Z-E@CTfD)n*Wcafw5uYB$D9YNg9%u2R=*?)9UC^tH-|OKnQs zLJjsnQMq$U-%1(yw>PvM_!OJv3>S$O?#oZNtyTKXr5+7C;z}B^OBmk$@}8?%pjc*@ zMIGfA&~=2>FuX#T9SR~X$YO)>VEWo``FPv^Lb{W8J5_x2;qhmU{<)DASc3+B8yF1P zvQ?@|!3Ra?Wv$f=I*q|9`6qhGun?!i?>lNIj) z3G6aJPj!YI&N0uvhi}J><)B{efUgF^%+ETX$&T&CH9%^z9fX;G6hzsN$N@6CG%M^@W^f(v08 ztFU5~0Qm9J{*d>VBwp@40-j+O|0Ky(V59j#Xx+{`xB+8bvjaVjR-$Te&Rc~Xj zF#kS`a$d%gW=!mW*CRb=IU5k>66Q#uvPC%`~1uAUeGtvR^xR#pHg@!$cCt+SwE0ycS5asP!laxU8ny9+a^|nmf%w zb{xZZ{2~#A%T}OsyK2C&tYrSD9$`BIn(lW^Rbn(Bkd)k;VnOE&{}qo++Hkj{PDq(% zo*&^6Y>t|H)7kzv%dR-7ouG`yM+3I)EpI#(h@1q|DT9eN+b_y{uQR<*U+Tu{`VG5~LF7YD%{Op(les z2htQ4lkdvP+;S^59*;~AWxseQMBjsf(9N2lit_e@PLE<0j@9M)tf`+kA+3y9r1wxK z6=^z70s!tS$6}wr=%$^HGjrm}N=#lUZL$Y1+GEALAM1RuYsc+{X~GqmKvs?^A)PBP zlU~#}>xQ*(ez!3>t8&+mq!Z^>u~Ucx)Tt^2w{S*3N{P{lz~zE5%JA0Hw|0xcu<`8Q zfbiv=3}Vr@!d-tw#m&s<23w3$dc5!jIJ+KtA2+#(=+pMwo?A;xA<^Vu9~UDWyF)V7 z5o?90Zzy<{PiaLj;I_FmMUMXfyJkzT=;UWbOqRck*jCl%oV^p81rS$|qSZBB4s&nW z_~RDWJ{iIp#A*3Jk-2e~1AoTf4gi@M9CS@Ejob2jGZOt?7q<_8#CO-@-@jXd4<36%$px-5xM^_ zL>1(xyDe${kN?#}#h44CG+c_W1fyni_TNJ{9f)t%p#m7c-*^oW4*O7)RD@xg zT^j;lvuL$1x3q=aD+Nmnwa0D-ZnvL}3a*r_kRWNIrOOe2WHtuY+IxRq*lIVYe3RH; z7NhR0hS~#Hl5pVMVLwKE?sMZ2QQw~GZy_%j>DXl?y@k)KH68t|>Qj-}Lr@Vth4E3T z{e^1}!M=YEbsCh)7T`|Y)JJk0D#X4?#Q%m-%NS*hT#IYy`4r#{14eo*OVbAJ|!(+Z5d zUIIi!nj4hP{m&r^|0kS0@*{{czN(JWTL?)xSIp7g1w&O+1OF*Qwfl_*A)aCwgYxx! zxL%Qeh~UHjb)(;Iotelp)zzG_`G&ZtPdTs|)^2l{NC%AZgi2~SAGO)yL#j+kMQ52mlF?bJBcMG zCa&4)^RB?T3G%qV8S}oE?Vwl8@6`zfUf(nvs`-7#N#bk)B4NW0&1RYb3lng1-%Gzv z-F1;WmUq2xAiXd)Vr`(w(7F=v4$%^IsEqq<&bGq_D9++t=K0GoLcAquK20?_NprW} zRigmxMHnsWtL+?KJ=n^J591Z_6GTWxxOU#wu7(li%N?@i>$<^g8i-MZ3VB27gGc&B zo)BB`H!#=^qkl^1;wIBe#eVkXBv8B?mc_nXMgP{{+!?~VyO>m!x?Wu%Z5MmytBc9F z1*;UWH6i~B)=g zx)u>S#qlIe;*H*~Fyzs*Lb)Y4k1zf^@IlOcY+$lNF>7SjE2HdGB%w>F=Y&-bIp14p zxAX!Si5bp{N~LTgEuP{jRir9&pPv)g?t}^>ij3lvWmO89TrlAC{y8NGSKv%n{%jZ_ z-<=ZjRj1ZKCb`)($z?-rS5WtLlsv)MT|toM-xX;IDAW+qJ8v1t?bv~O)#`D z0{Z#1Xovh9Mv96Cnnj*0YXEq*Xz5M|*?@tM>`)`5g%E8yV)c(C-Db5mvWTC9V()Sp>h@$dV3@KdW z@U6sD`?r{34+j_`!2KTxdrzf&55F|dvIu%NFv-p4XkkQ=_a~rV@SfP1c}Sb%VPx(< zOn`Lf`DJ$Xw?qaCG?K$uMwk4H&Z-ktTD&i@{8B8u9=2`Qhl-=JYeEnZ(9yNy!EZL60iEO?-o1T9K&k|l@S9_BP z%1Z(T z<;xj6(>YGHME89BV-|ljb65e9QwkVnb})20ptJ4yeCi51Wf1@~K+L~qM%n3m6xJxowB|{W3R`xzPFvhS;ar~^^Jw|swU9} zsKIm_DobB{k3*~=(5!C$Osr3Zi=y{J-~$!HK(oXbm*3x}3k{x!i!r^t4|GYuB9cS4 zf5>;se|+tdIgBV&-vSj}Jp(pmDS#Wp|h6woI<2Ess=P5>5h!IlGcR~O*2J4nl#m{|3s#R%{Vj6c&tsWdCAu z2UM0#)E#ol)qCpOF%;ulfb!xVE472q=aG201(17aQ&k8ttm$Gd*@(VtQPL^PI8G`i zpSw?QxfDc(fvYTz4Ex=5${B7a66y5smRGCppR~BBE0eguVOM~A73cH8 z=!F#;>1fi8@#P52vGOpR1_3xrf<4a)8SDJA|CEclplHWLb*x=l$JgG9l?EDm9 zD=3XMFltntFQDCH3K;&_t78z4Z~CMU7-sh)^roBc-llH@^vW|Up391y1H?U`-mSQ* z90Hk1e0F`ekZ*aiL34@XT?1A=7z4eksJI+2J=oyII5y0_{hC`0`*SAa$%PlK zZ*pqZ__rc0w~gpj=$2BJDObI@q~}4w6djrhlWYW6U{T$wOgX>+N_e$V<_joXEi7}e z(8m_P+N%k&>qBTZDeiL+2~8VsgNENvT;|U@*mx+h-$GtjFzvD(i{a|DV5W)tXK%vD zr(QQsxqZX=bBepmj-TzM(`XsI9-lWFwBX=t2*vAqGRx;h%_TV76r6FU9$R=BsrX3x zKe6c5uWaqPX+-+NF0WXh=M@!WmBEko{H89opNIVS|C!Xn+n3$o2%j%O|8G!ARVuE^%GR z6UipLAP1teGhHy}B^Dts%W6t+hvMm)6|HL{s2tkV_q%Wu{DqUn1WGSh3bQ&{0Q(m@ z+a;t_UV@H4n}pruW_Q-%P4Fzv=F)_vr8rT{5w0{p%?$cLYxeT`Vkk!J_L>(i|dV0_bqgkXqqy~# zUm>n{xx3LvV|haR++Ly2j(t;u_(&By)$K6zZm9(~0#do=!;f=Dhm|!^_MJd4&D_Ki zSd{h8o6{ItwXaUnOVnQX_~`;IPR0uBRhiqbVjInPOyF+1QB3i?cvau7&YxfMKcn+W zvwNV838*FEb-WrjNGGV~Us~ebW=BI+oJ~7V^b$54d2=h@aYP6KljP+bsoN9W&Vv77 z+SjDBC4>3b1Zr={8(~vx9?O#;alz@M%uj_)(+a8;e zEXOoUOit%AZVQYgz=PEUUrO)NMwA@BnO|eC6XZ0f^+-DYc*!z=h=^_O_}K>^8$!`w zVLmerU2xEg^-CwPNjs{~VPC^0;I~m@6zjYCw7K5#s6=3kMwE~I*b-g3p-iX7=W3alPmZ#AL-}79Mp&C@A^yoo!vOc8J48>) zY&MOD@SuKpb%r>q(IZw76ERZXL)Dk^&jISQTWA(z2H7zyV_=}yL|i<2fsA0$pl z=2q-2h~~7e*k~J=7F?YA6O3T>Dl0$d{DhrS?tOzT9^vuLMA6Hq-#|6B<2*h2LANk1{LTf=Vdg;4wq5bq~G4eKzQ|Tae^-&5hk>(MJYpq=|cjg9AXH! zRNLsbw?u>xO1x~O(7l}@GOA5yI++rK^{18W+@!ofD@Pf36+7fun>5YV4b@V*0U&@y z$U9PgVd5ZZRe)ILl{n6%1XhcF)0Sg+Y?0NI&^k;L7gpn<`Z^O|WuSszw|?9p+sehtz) z9%~t1(c_XYU=FO8XjuLJVde!}1N^0;1X!%se0as|s%gaS+|9pl!PR@8%^fH#?L(Hm zo}$FXZ0Ujl&_bSr3wU@Du>sF|ZYlaIh}-zr9z8BLbJWZVi7;-@{{_y2QHJ9SR=dxr zU=kZfX&L*nUA}Zu45({52a1|%Yo&u1OU6ClLemthkml5SHHrfniZO9(pUuu~&N}FW zu(DFxD9E;^G&~o`%?i@)Oo}o90ZYm6Trz2SQq9nWt7oH%EkW=0$9;0D@yn&`)w%$2 z2dO3^B01l^-0U(~v2OS`TTKMexK`@s?Xy{nVXiwW=@?eH%5DP>bv&Ub|4=MEr?JHc z?wPIM`APUN@HVN^hx*Au1KGy_)Yd$uiB}v5GI!Uyowqx{!B!|qK_>ZfQQb2Urk5vJ zml?ojmA@`r{jG^KfWJ`1e*I5Cm$Ec`Xs>YQez<(+*GsotC6Kk@~ z?2Q6FxDW0Y2>#`ZQP%yls|SQm7{%5A#g2AWpPvRrs4bxAqd^TaOTG*BS0gujMSn;` z$wYnAJ6~_pQQZorm`Ne2!lxF=qEjA5Gzx#UwnNt}9ll?|wQEXd1)v+YFZc#&WWI{f z*dDgpL?ao2%7Q~OSNy5yHaYw3!0E!J+1cW3JfV;-vp^rI-M@NE8^xu!5#eLi9qO?@ z3NYmK=l>v#ov9flZaar&;<@9=^1|dm5*+ULXiORnC{d4(?6{Y-G37KYG0!yFG5w^= zogOa~uzzPCG}C-DzqXp>r(3PMhzi?vv}I`b(dXBLGpenW zlsO`Ny;NJBN7f%Eg66%;d0RnWN5JwO#m0^J<0s^2L(|}(xTFCi8|(yh!3kf*gbqp2 z4@533a$t%C8X^lao`9fll51$Te0jij8Ne@n`fG z&88p)WBZ5~2OOlTxo&H{Vmj}fj);G(iVo{NJ=53!Z{Hi3Sb)9)$hmYa&3Z9rwV(0<-NK3f`;s4S2pgt8I1Ihn!DrHdh#J=5hctFL%T6ag#4KSKfGz=H3#uzuXHcmwU? zap8_rCS_m6)bIuG(+6j}XxdeRwnS*vi~gMbbjEEy z4}tf7M=^3TqD26?8fezhuJFgQA=M*)aXbQj86UQd#Ily!_wNNWac8gr=Xlj#H18bG z0Ia@(E3U5wD9Myx6Qsx>(|WuGXG-yu57*7`JRH=&!_4 zqy!z*T%+^6a^{W`RL}BSa#GJ{|IPn=db*IN^@sBGO*;fU_$PoIbe_?PTc9qPtiANu zvP#A+)$M29(AGFo*aJx1V#ZKvN7(jgT;Hn)wlHY^Wq-pNUM}CzHU`s#Nx7WU{!XkP zOrf}+QvM(DWtN0yLT;<-Q8q^SZ5r&_UTmuYN^LWX<3q^=sC6Zv9mx^VXyW(3D_*d? zerp-+qNvc(1xv~;+dqga#^CfkRB*?$m;thSBZKEcA>`H6!6_APO|OPEDG&-S5T#O) z+8oRVN{2tD^aJ@mDL*WzZ){-=H9bSPd{E|>^t>6yD}fN0j6b^46sk|>U$EBjUzzz1 z{ipF#@umUMbpxeevXD6akXdR&S0hZYFlEe-1g&Tn$G=sjBI~LI{*nnAz_yOJLzux& zmC#Ze8wkIh76l1PQDA@_C$si-jCI?tXBZ0mujag3rg*KrBr(ZPp@Xbc3ED2z&Z%Ov zwC6d;z~I1M0skw+{k0>(CU3lu|E~W+4Vz&dP}3E-EGqG%Gu$9u!>xd(FigJ1qTxNa z=}V7&0`U8#_6QpEVy>2Bh6*((Q--6uu_gf-kAvk45a!B#+jH@nqf?kgbM*-9gXt6G z0$ur%9&eF;wU}SLp&3*#Kh}wV>`PbF8#|i(r1!CR%7KiZhKM?sb&HRDB&8@nE27aJ z>cjy6I7Z~7)p9`$kmUteG7rAN%20@xda;H0H5u*(<3b@C^BPepdNSIq^e48KsGM(j zAmB;AYbLKlv*dr+cX8Bvxs2I44I1Q4d2uBM=e9v{QLo`Wu6@cpvM@{e|cxo`@;hb8cW`bj$qUU5`Ra;jpuT;G+ z*@kE%!@t&n3%;f4nwD?vo;m!jBSD8laKeRe@xRl%zzuXlS^X^rlNNEpyu; z(VOfe*xKe&r)W{0EoC!9{KSI9S6yOFqjg(D#U;N7)f}Agw|veEWq5V<)H3e`vyZFO zd%KD6xQa)aaL`Zmk0Q|rmjY;>gB>V4+1f5uIFZN91~TdO1r^2a?9PwZpd3vZEefWl z8I-^B>C!<^q+yY_D4a6>==)(HwVsT4;i&hIWC{^?Bclwrt|(7bZw|ll#a^DVgu0(i zs*o#;9%gyB#uPGIRq7N}wWXLo3fp9qLL}qA^ElW@C<~$$e56V3PBIlY{2|Ecb`Ngk zj?GF^$n2q#>8ZRXc`hu`xyj)YyJ(Oh4TW{~vCo-8Ue#3SRhaF6`CC0lc=2#njUo#ti3rqnh9t1PrIOR#2xJI53?&nX$0 zt<(i;#%=ecZ=&v(l6bM%CCDGvA7?1KV?&&(8M;i%hFxSK$->Sl>+kvtg=8`75;tqY zipri0Z9q*E*X1D&R96Vq+SLuo15d51atY)G)bWN>8`FHf6Q%O}&pMW;n*TdiDvYKC z-7qI7L|wM2T~ZIpI)(i%Lx@kK!c#`~36oC_MC#ft7&!Ly+^HE`o!8v96spF`M=afe zU2bI6w%zLBj0X0@<&7E>U0%;dGbK5%(%c554aqNG{h9>-p7NE9fvS*^!nafNKMEAS zt=ucz`;*|tqHoBzbeSO`wRw{XK#z_M5?>7fSD9# z3ib*x{1CxberFUe8MQ+TtIDQ^(>gY$ljo)e_Y@_R{$RFw9<%#NpRO9+{R0nU_}~g}yBo<5zOV0?K?yCrg}OI_hoRP=tyzMdxCp`Op?)(cqah=8u9~S{Won6%{dP%`JJE;cGuI~6+(e}#yBGQ-UmAFmE9)xDku%;^!-d9HLA|x685~xg`^S;(f>(>Lp~`7S$B%s0! z<3{@_)lGmD^Z+G%uKsfTy7eJhvz-u54|7u;^%SLUY*>dNR`K#C{KzAyh5!`JC(38MiQ1RFKk@qZPlEkNtRv-oiMk9vni8*nc+9vExpbAm%BQO z@uzZN%0!MiSZZvYF%)#dnXwZaUL1iVdn_U$sfGdqO_JRkrM{2~NfRWQlj zNbIvueEpOrdGlrArf_ALb;0-Ocz4iFS17&pF(pcD{?7M%CIpVW(NhBw5Jg17s`65C z^{=X2Y09enUgly@*~vZ^MOUG&mK-S;xk+!S?6LY=BpQ%y@^g+!_HeNu9-1LeKx=i+ zI=fmC#{*jm1dU>>Wq%(=;H!v0vnsD9)L5awiN)`^6hWt=5+*!JBO!LTf&VZusfMBG z8#!8M3AhJ~2Oqrx$WnC^dc#}M=(QyY8TBr4$($Y zde+e>M!eg#5Vc@YO%`gtgf}`hi+6L=uQug}!RXZ?JGtXZrv=I}q7>7J!h{D47{mM{ z>t@oxX$zrN04MRRMEzreGQErx+Mm!raO2=?#s~_%I%0Is!fmKmB>@UGw;LG+ZbF%R z`qg%ScSeskm`{Ju$;G>#^0V60xmpJ1HJ~p*)Ww?pSzC>^U=g6$H{a6g8x7vp3?3)U z5=)6|b_J-Mp~rcrogYe@14?P9Ry};1VJ|%x!lhR$Fity?|G~FIn z6t|_l=b?D3K{y_7p@eIJtO%XFFrW@dXDNl!D&x)s{y=lN+i z%p#ZQK5eh)#lZ4b6N_4sku^<|{a90Mk2N6|(~i14xQ;wU#bHEIqkMh*syG6%Ho#yjWMQm3U9BZlDVOZv9yHQaVXm+Q?60lUN^3*yW`Zv4NC`-{zal3 zjM4Q}+_x5qLC%y5W9E2m?fW%Ds{^1%eT);Qyg#RY0nN;q&7Pl=)qRD*PMicE$S?mO*}$#5|*Hu5}+vx!)kO2qHT7b4>I- zoV>$wk08fbTkIlz!Aei3~pD97~%gTL5j@o9NeOTK?Mu zJfa}NifuCpEp3tE;TrN9+2d$P0kde+MAU0wBcH!Vwyz;|5C}Nyw0t01TM9r6`)%S^ zX#Q^PIT!%^4vTvOQin5+;#)K`&+Dtdw_dCOX)=v)AJG zSFvNPUyW6#4BKRc+{=XqbTzFe)h*4Sdg{{5+*=f(KCt#Z8gw+EmxtAP=n+FEz=j=z zp*0%R!|@VgJhNzkCp6?I0EftZDN-In#~&y1kYdf;hklOfma^#AM;$@cqx}=Vj2+h; zmc@PPiuR@>6Pv`J z)0(u~rqgKTnJ)d-Z;fHwtAfoS-y3y1zfY8lN_%Vm01a)L)cF`M;mA?!5K*h>?4R^V z+u+XqktJa#|6Y~yW1a(i=tIK|f(87-_t0T}KV%Uet#y#gW~oWs6VQBHZZPU$r%?e*_N?ZX(2fHHloKj5O*=iZ3=cmC%wgUsXa^;K`Bq@y(K#J zz1D1`a}dRb$6b3xHm4k=qlwS8c`=f`&ag%miY}8vkXP-7)&%}qBGw6fWG#|Mm)G}v zOE-72cjtD4ZVDUGhAy$l4xoI-`2sLC0IH%Tox75(U-3_g%py+E1i35E=S*iEyY&1C zKZ2=^E;o9JAc86!E8S@Jh-`!AxpD3EH)wVY0YRYZ3lI8D9RY3=)Ph)~NVJU9Y!7q3h>Hjf zmF)qs%$K}v8o0}}S?jhLrKI3smfQuUs=r9xN#cJ@4v zu_^LeTIqoK>xF!rz~Z~|`CgxFr60*Ln}7Ts8RzutW7uXjf`I;G^A$!U6~?qXHGNqj z1rdXne7psW*81?zE+M7Xc*rk3!2grPr_zruuCyCX1wr(ue4L0&If5(g8Y# zH2V;SwfH&PDXvCN{4t#3cMdJlI4lVh!|2qkIsJ;R*>y;-{65mgUL9%@ES<#iU_0B) zG*XRdO4;Dvj5t~nrkM8$@&T(3p9ojM1O^2FfQr~EBmf4@lJ5E}Z-4r^5=(;5?}4Hh zv6?@D^4cl#9@&D)(P&!MU#~}k6mfwBQL)-Ld^vLkt=Y=$*mN&A4eXN&qOCNJDrF{0 zON?M}rCkxP;G}TBBKpkqU-7YIB*mnE7NXl3<8&{Aetz=9&#UU82ea!XR>)t@PmD*_ zolmrjFnMJ*4m>s~8fB*mIkJ0V$%oH5@k@>>Z$GCYG?rP^NuN1DiniR-8Rx3o_|_HV ziUe4EH@FcR$N^u%XML9>lt;IX_qAQ7MKv80BiFsPoX_V|Wm5$7Z>u$^>rbc{Z3*yJ z@$+`1Fvci1M@H0hJKb~WT)i0<>>&Uoo&vk3IT}Sc%}qf7nwuaq$!Z2{e0{BX)1QNV z(|?K=5S=)f%TPVJ4(g(Rq;NzMwO(Zksx$u-zmh3is^Ac>j48D$3`SEav7YnX7aR~Q zfcy!fvmz8vwD$D9hr7|6800nR+4RJe;*5T;Qc^(>`iIX*Fpo>gZ2nI%grC5Exj4XL za=LCnxj3;E@oVn!a-Cy|l>}wV&O9o=D@N_&N8lWtm?i+cNeW%G8srV>iATyf2eK%R zmQX9ju}Q!l8DgbE2z&H$$?$#;1_I%fgkGxWw);7SZ)b5Tkfvz= ze^>1`8<;WK3i?$k?R$4~C2V`m+?rm(4($I_iviH@(%vTTrbA(PQg?WI$c7!Pd<^AG z|10KnKgNrti<*1ZuNwjaz&F;0BrM-Pg{sqRJ5g;wAW~vQj%S(_QM%fQ+43kh7T+mp z?xuCMYAXS2)1r`Mr27Vye&WTM@sXxpSgQDP-EfgRJmsGpzr8Hq{dhSvc_g5Nq`{oh zHV+|d%=0VtLpsZFx6bgxk2C-=;Isru*3RnGi9eS=hNdqBAorXM2PG6eJhAHBXOIAB zn|=awZN(3&4<^8TxuxJgz96kaD60owj;aNO!lu5%ts2D`M3?7+b?-11A~dP44_sK~ z-HW1f^SB%OU_=;%PzsRBl&Da%_ru+xHbh!^0=(g_aK0&}b=* z0Sr~_3Y$D^!l>H&^QjC2&w~1ip}q(>S8|NYY9J`8Q-j;gbIy(`4u>W05-dRrxZG~Ab=G_5>nS68X=nQ77f*k z&C!rDU|0+hD~_5p=sXga4hh|p#MFNj7-pMPnkAoEoP7D~x1gIG#zge^LuC};tF%Ha z$UH@ZHQP1QLg0)gzy@>{$*eEuXtToA9*OWL87b5eUQdC?>en4o)d;+%N#PWER*#7U zqm2CheF@;@2Z9HfjBieQNaP^;n}(%9g&rPfT*^EPiutfzhB`*ZM~APlPw;nulI_Qz zD3 zF6KwihvL$=KtQqK_s@THxm*utG5c}i1Lay3|0hFZ9$@isD`S{kfCDA)_K7UeZXtU@ z+k=)B2pN}=RSn|3iV~Qx4q?^&kru2@_+n|=cUA0+dWbb76QavYh6Nv7A|q5A54w2y z-Jmw7T{Jyr4sb*M=cWk{Nwi&fqZ90VLM_V3r=`)ddgA@K6$=^3{aDF21Jgo zXUzSkWh2L~Dx8&?1_y_UZ=Ih|AO1FN;*$sg%w-cIXO#2P8_qGf3iO+csu^OW6#P|n z>99sWQJ5DO>W%xCvan}?+_Pr{eZ?j`jj?j?Y?b5?_Y;A(y!e~Nx? zh|yTw+{9Pq96UeYILBN)COtbO=i18%u3wrYr6CLsN)vJ4*I)pVF@m^pLx;uL8)ktZ z^SLy;S~rzbs5R)03Ti@w=u^$4{3%V$8w(o>?FBt>;T&1 zj72KN9L1-LL2`L9jL7t z)aiR8yun*{a>`298AL8eyC;H#rj?_8swFT2(eG~jWP^JR3To+$mJc2k8yqrl!q`Sz zF-CBAZ*M+OlCs2f z?@g`UX}=*@d=Njwfjmr+h`$s8OFB>Oa+r+>Dd!z~YIxSUX8cafrcu(5TDt4}h;z?( z;wb>8!eyNk1lPh^yYT3kEpzURd*`&uhefa@IsJmG^sGq|Ku28&h8)P0imK*^;BY?b z^{w`IDV!YgmgBnbneT^pmTU??@ebN%;!X`mY~5aw=j3?juIaOhYXkHEFk ztW7hsNQjNeb2GCJ-e{aXl9;Hl2_zkOLwqwh%sy_~^2z-;tV7sS%DR18S zo?&ewbm$NmYwD)CYPo9NJgRoNK^^T1!i7ThEiRji1Z-~3c<}i~#9;8GDLqLpoh~O# zSOowQuUZSE!*+ek`*YpjvzU8R{wSJ9g;tY_KYKk+)@KE_L4I~cMqi|Ri|0l}va1&^ zI3IFSq~`M@{N1~*1kZefuOwn#D^xDtNg%6G>COrXn6vB^G}B_eOt*i$)? z$UzhCcTwWE<6FEj7$3B1b!sOJWLk7qm>5k)!+1(n{S=hfe7E2X*;6! z!)%s&79Va7*}cdRAewmIs}~(6T7+mbFLzY5!jg_xnH{zU-)1rJ6kO@I4)ah_;scjW zC)xt6?C-j>9BN-S2i)aX%Z4?l(32`AARy5Kp?_(l`;y&hr!rHm{!+FAF&nMrU~~HY zom(0B=H`k)y#{eJ<<#esOIbYB78Gb{3s|1Tn8^K8$NlV4 z&HR?SEVe#z$}k~KnhN7WQNaBP4U#nrD)r z1(RTz7D>~V>pI#7r&y+KB-)bWru8SrA0GMMuoREO{N+)0D2}YdU`ApV$Ez-ON*Pab z%Bv%Bsf^~DHTDK{-b=^vzbre29ot4Jch3&V>0E&Aq$+u(FpkvT74dw64|G+W0cDqg zuVx8>(IiJa&T{X}f@0GZO?U(fOt8nBPd36}YPBl)kR||B(sZk;ta>n{l^#lXFOMf31#P#(M}scD`iE7OpHS-;Jy+9cZUAm zV#2--k~rJsRPB$l{_mK{@3EjTxN!qH|7MA!1BTjiv+T|LQ(>pl;sn(-z|zXwrs1Iu zKE%js6|Ih#pPR6-M^1+$Wx0!#S0#(x{HWw&Yq6Z8|x6CD@fLKP0VQ2 zcC16XaEah@Dr{KpI;sHcQjkqSrh3&!W<#;B#fYD9L613O9GVDK(9nXTW=(1@{!&sf z*dX!H54yQ+P~Xv$8S2tX^d@FL0lKa4iN#mwz=B=VdO37_Bcf_XKYz|j~*f0 zO$kg5W6F&(+RE@u_l8*m2!kAuZwfEla9;`nmf zvj|(%vM^B%jE8x;hY!AiH@kO)`{~=Q1GxU)EAXS}lEn4DC;AD@asBM_W#klya?3%w zy)ShX!TWz891CVy;_`I@{X_V!yx(BNu5TfIWnQ~DFV9)bx&i2GI zlw4G0%TkLxgOsckW~2HMQ;$?}&FLjmQqvXVET?yR4r-vdz908tN&)6zp>!fiH2{uO z%DkIRw`=r!@>QIqv$9k5bbW${tvptbO>t>~cK?=m3g12kz?e&QeP*X5JSV64v-_TOSKBHA1#?lc|n{v7h z5>Wx_B+4R5jew6$z|T}gapNdVdCQNs@6=yDmN!=0dJ;Gq@tb{D!~(ov&d9 z-4(1YyyNCvTf4GVc0#ME!lxvg1R!rCTap?HDI=#gf!{*UD2n>Nh_VRp(Jf7R224#~ zV+=i)8btpGd$|)tYnDXC0<9uHiL)uYL!JZV;`lFr;bl*qLCtpG+0M2zV+0hIAK_XJ zX!%v&C{=@EwEz=ajy%B?c*jHStZadUr4f)3E4T6CsnSTwr~!s_;zT*%n|+M?(4iGbD=JvGt`+?h^_%Mi8_ZG(AR`T{hwZ z7Gdv!M>jO6m+6MU-5uUeSm>nut(&0}>s>)O=}OF34z2A>Eo@>OIc;2^3kL%t{t}&q zv#2=YJU5qqDP6&Jc{piNEusc-6|OByv^O$BwA={RvG6gxwx;t#5T{YJk3lQyBK9#( zPl%t-6MinE#8tnEesrH6zlA|B^|$s}||R}8*=<}YTIB`zD`%XdphnnS(o zMDFJ(ZkOB>CSII|JaBoBf|7tC_Ne6#RdUIT&mBDnGB=>55lP6XMcrK1Vh+VBTZ7G$ zvs4@AyV@q>Rv_!+D%5O8nUM(@3_p^w3Eq8ic2OTE16x^`grWfvA1z$12+2zA1w5Vc zSe4Fq-G{JtiOXCyC^oXAMCYxVS4+$?6f0wOx9i|J?8gsHY9Oq7=xjcS;Fs-9aVKrV z1R!3Cb(7hbGm=jgf&o+yfMciN)_(|rBdLnp=c;V zjtAjRa^6IKvQC>hUW;~`u*Y+0l(FA8>{pnvbt znPR&0+>GQ2+!O+nL%NmK*?au_HRaHVVOh(sH z_Dw+<2)x!gGEe;Ti*TpnEeqMbgX;yz5)Q|Nsw8(`%B$fIDSW5iN5&Se85eGZF}Hxd z6gZH&LtpcLY%iZ(Y%z44Za9N+0An3KX;Mwu&XjbD5v?LUWP1gEp>NWhrRIL|O62SE z$|Iz89c4Mqo)K>w}@Y4bqs`|mK64% z{z;AugMr+u8~+v1ycb)QUXD3shQbUVnHeDy%Ou+4^Q`AzgX(!Wb>~z8VPj^X^iUnGTB(^zif)qC|)AoNw_&=-^O zNlc#B-af3A%`^H3y0!Y}juZpY{t_&v%0~<5eV^l~*;+F}Rn=c2w7(D0By1>~TuNSS z)@4nC{Z}#wKl}0ycaXj3q)C3bLN`5=R`kFfpoQFxZQiXNMJW@CRc0#*(UdKF`#Z$Y zY+pkjdbD8nP6lnJB_vN{yO!poewKNIsdR_Z#;2yzL=khwI}f654L977t96-)DXOa$ zZu6j=Q1!_?NHBT+_w4OO4X~~p{49Gj@$oOQiga|y1L(`v{9xyPT} ziprZm%zo()7&~x{tz!64H-WlE@1Re6Yt;vC#x_7sRek{@qwsK^bdr;(bacUj-kbD# zm~?VBSfGDlxFrom_w)9ABm+y0Zat_}9in+1fmAWpZmRUBh+uljvKQ45$|$M!GN~wxi$`fc(iXI4>q|Td~HFWBkQu)+c_>Af{#BD$L`f;#pGm;@-fJyyqHW~qbN2YAyPl*=mvmzNKWv3>0 zoV#gsRmmPPKL=al9yR~}L@Bg4_Xcb}`wH&mkc~*YToR%3&6@vc5zfM%wN%;Bx|@8m z5DdTkS#~zghr3QCsGSJjIf-HXdMY2is|Q%qi0z@lvJ6%r8E9*N*e2 zJcldH$k16udH8>k#Ii{AE8Nap1*YQKVqBy z{ASB`Q5UZZ^SS40$-+2x?Ln22U5IvjdeQ72klmx&2^DYTtlW!wCYNu{<}DlxcO#k! zqJ$H{9ai&Iu0oDGuG`?!KSVRdIw?9UngV1qhjkwf-t*~UOpNd9=KbB20r%0ONVC|W z8m?Hzn=_h1Z$tqZAFN3C^*7Q0F)rj{^J zpCq&C1+^cWEff>?^u!~G*Wdx1wY)OO{W|Tzu-sOOUaKb>C&)sR9hs(pO{>GkpZ>xv zl38_28*52%LL(?^CVt#TpEFtY#*lBI>VlLPYw-?Yt%X>-bKu<4jZ(%gXZz3BJ`v;^ISh1rKb7n2#u{U{wcgU7zUw1 zN<^m<(}!g;H{&3h4rkZ}2rux|15;=f`V4g7rOvIh#-oo2ZbnHQYB(@`jlbnkK^ifmX-v4=OL)KIcC znqLZoMOp-(bLk2k{Xo<2pqrSD(HCZ;6grBglJpx=aZ0Yf2c!yOG99sJS1(cvR&bmH zwbT`wDkN6QUgP&Q7G5E8o%=FQ6%Sn|>4Y}d3>b{Qfr35Yrdt6Atps@YO32v2U;7S^ zEUGbtd&feqYKp>4Q=;H`2{o+{W&V6<1z~xKa)o@{*VIa{33>t$+9-aUi~G`t;V3KG z?d3d}Ee9%ry0fq)VI;3t>USjX^dr!}MrlTz5I&YDmw{!Vy{uIuL%}cML$Md6Gthfw z(?s_k81GmaG5oPYI=CB#V2cSGZt2a(0YXN)CpKM@y(+&yohqXUBS9QB(r^!%jDQw4 zNgH3&9I)Wm37A_fUF7hYN{q=an$KWS$jAOP*yMx)sP#KEib^wexVUPw&G1CGlN;}7 zw4;D4&Hn2r0{`iDk4m}8F=IO20;{6-j{s2W7(M#M5u{@ZPSkSaia5tb;o$m>pxK^3 zK@Wy-6FE4fA9=$zm{pg-M7|i)_CLElpk-`%`+}AZN}Y4RLB;Xj#Yw=FPo=ZB>@m;%fbEF@SH=hm>LczcDrDAqEi_y#Z&agK#9pF$+1`; z@?@k648R%e<4WueYhob`@i%)7{K$jP%@k42)CK{pmsYOvMg{%aWX$gN_pm_bw2pqt zfS)iT`5#L&{`x0hxlLm>UTiZI%GE~zs=Au^K_=K4g+qUVqM=VLLu)7Ee5ObHN!emu z%2B!%h469qsZ~BwTGWx&l!L4%OOTNW(X&2i?oGj*`wEMFdIGc1#Lf{$B{Ru3m|7H5UnyHftsf&DYZDqBbm{cgbH7Fo*l$x+1LaM&tC)5 zK3!hSiCZ<$Ti}Bp)~|N`iZNbV7KRD~fmY@j4@9^)_Z}-&MD1jlcKJP=To^T%Cqz>y zF^ zpX_f;?fS37g!J48CEPA;W!@&>fzmAF+IiMr2}h7e!J_aEA9QO5B#e6AJ;9(Pj#X3^ z9JZwYwF(@mdYG?Kiszg*UJ1u+<#8*7@@0m_Pu$@ei(wU{;GQ7MRj{P->!Ag^lp$`( z6W1t~4OSafneTZo>}ZG1k8tfgCDs<}#fBXiK5RNbb~2&J8W4z{FqI(rZUh2ByPDQdu<--zVsp-h3Ir7>I6bpff@xPMLZQiFd==msWiCtB9U(HULwLCi+1; zEXoi@P()X#n&x!7Y$DTvp^Y7Z@v2)Oa1tTn$mn>Ro1R{$OW?DjuJBD3l;&)AdHqVs zgv6l5qKAD@PfF1zEhPqXm{M*H{Y*cQqRK`T^`s>4H!7p78!GdiJmua15Hz-3y3Ebh< z=EU40v~ZRdWwTd~2dGEEl^&kDM6j{N=m%~HuMvsfOM>c%`M zzaj(flIHs*XU$9Z{;<)xusi>a09FE9eB917DILly`T^I#3dv(J}cxH`+b(=w~G%Jivi`%ux zWE{`X?ZS|WZOJt|Jb}ch0zKHrkHh#X4Ceg3{S=QvmP}D)^ZnWEec!2fvF!G#sT)XM zs9`ccv^oP3M#REG+WV3|Ve}m3ZfXiA-v^d7J8$-NjW(Qs z%t`$S1Ti-w%7yX&23ulzt-o-_s5`y z;xF5Al;*U%BewrzbzKC!(ABrImU8u5b+-6DEn%kz>-k1l?=CYJHQ;pRX=pjH>^pV4 zpfq!zI>737Pz^u~@6Pe!6$*{lkA5kLYlPF)lN222See&5uTnjrtNKjiwwgBSSiPpA zZKodzkHn>V>xIgapd$-|fF$M0%F*%`E7y#Qg?$>y1@4g>QO}lI1sO%U9*=yG&0g5- zClEhq-$Z^BxN2d5Rb;}Hth9GX${RUskN#Q=H|5mllE^HnNSQL#vm-Ri>6l~{R}2oU zMP|UG+vfA)wvY{)F19K717d_&q90tN8@uv&RsF71A( zor10IC5gx(l!#o|Mv=%Ppy-0_|EZ)AY*~sBM+$~L1zt8>Fq`;3sjiUvrzFi%^M2=o zw9GqR%J$-=xPrA2;8>dPOS`k8OJYGytxPw7S? zOI)w0Bw9u!iCoVuN$(+62E@u)+w`m_*y+I!!O#>6pZnfRc}_nQAZGSD%^@F>)>Hcs zOD0>%jimcM$G-LcM4d6!u@-Izt2eBRsClu{S3ZxO8|yc46>y=BBaxvFB4O}s5SsLF z01Sj^?8&^JI#3(5_PYDv&eEV9?n!o8I5U@n;Ix%ao!b8$MDF!-DX}`sc}=Va^L$kx z0kix5ChsRP-1|U6iOvmK$^4^@b$Ug;?2F;_w_=P76LFjL zKzlrZbU&u}+@)DhHzV60Xj4+0G&|&(HL9H^Ci0d5aWK`mJ{o!ABcCQHdSB`B@}qLX zRtHBquB59hw2p%s4zpzJ2kQ@f&JnS4xVqdRCgoO(Rz?$Yg&0|$&tMw;LYw+_P?qN1 z#-@z6h{^8Mp(b!950h_e<%zZ3M>z2&#Cu6QIUz&M67HbrrL#M0JdN!IRM?q5Y7%=s zYZ!#ahKrJH#F=`bsVz`kFTuNCG(>-e2x#?~*B`*l_gPAv&jOB|RCI%uRIp(QOV3?~ zum3(IWB^CTCV$W#9Ip6oby7}mpE(saMERNVfm8^T6M8gOZVeml*~mF#dDH)N$=PZD zvhS#m)FZvYHt-o=2p3TMS@pDJit~kpLJ34lmK-yJ5X2mv?tF3ihpyv9{+jTns7A^; zkXmYb{m9CFvLd0YCvV@o<$)(g^| z>bHFOorgDHBx~;=9Jutk*HmGsxBAMT$@*H8dwmjMmD^G)C*-4v_$NL(|Caflqmw9 zABS3OR1X0hiRETmE-xmXexYM&V*%Hz-@jM93>a?X(;JwsNl2z>w*%OL>KW}x+HG6h z>%w)K+LFfx_yTKdvmD>(Hxx#BgkA>_YJ@%(;W02rLR;v@j1YBf0*_~x%+fXobK(jHU3EVzDZI{cYGEFraQ9pOdvdmD$pgL ze95F2D!s%esD1@1@i#y)!>OeeA6--V}CKjw;)t@>{}`4hhw75-u#9 z&8p50W3w@7(gm(Sq-MD5E?!mdLUNN0Is$=}jIl!({meVuO=r6dAJBXtfOKO!GJE{r zTLu%2^PzyXmQM+dJ_gM(3a1=>^zp38l@(pO>u8kbKP2kBdQ|UlBM?(k(gFNG#vjiBaL6PX;yC}k@t+5eG)a<~4IEWf zRaI~Uh6lq2!3K{>(o;62R=h$KaPe<#@~kJjvcsvOJ;Y>h>iptoq9-IY|8&a7WUU4% zlxW5sNlqd*uT0Ec^LI5ONETs-iggC#e&XgN%wd%XT(mdD#SCr};V4bx^&IU_thB^w zZ|OI85<*~zR#gs>z8@~BGMB3IGP|*|Jj9p~n-j$iR*ujc4!jG;;M^U8t!uux7xA!z z!q3|Hp=*8+&$w|Et3MBn zD|OzGGezFa&{30XuM~omacm%M*PSxmK&|;f{vtGZ^w$yGk=ic=@708R$*aN?6Uh*e zQm#FlN13rmT$!Y0*Dv**>l>-pf5Ucb_w9>ydhi=zWh_$A9KOx3Cq>nXqU(n;-(8wK zHw)p{>xd>)ifk|{!mhx!cq1-J*(HISb#Gk1ezQ2nD>VIFbih}yp%g8-4Bt-P(q-B| z^FCqfJ?ywMu#aNae(m;Nvhgk`;-ly+D|@I8x!yl{^PRa^bl_6={^R`lwnnJnTihN( z*3CJC&DrDeWcX&_KS|ydrY=;=P^QaJZ)t&caY8LlS2wt=MSDGtDV&mxMj`XIOd=B^ z8Qp!%=30;r7tWVHg`y%TV$=K{V)(EBMUwPSl4vDWJKcZNujBNWqL0xVF!=6fhtKqs zf33%?Ke1+B8s~vygEf-V zQPItc)rb2o(q1Mf#Y&;dtit}w1RD$H?~nCW#UUfXZR(3G*kjpQ2$k1XVQHZ*cxaNS zlH&TF=MeFlQbCLz41qRPy_Qs1R$Z=|_C{4jX0|FXM(mmm7)X!+1`M28oArEbX09=a zRa`G-=+aufh7u`eh@f&HXdpoa6i84313sV`_^kPWX5e7KL9k?p!snTm-hIZv?^TPI z2!oUOp7hqa+!%sNF43CB8n*-$wEWC9k5Fkdgy|gok3T*OrPk|7lPEGWyo`1fITKFf z*!#reucF>r@HhUmR;Oo&p3H{uWxCgg(7O`NTRrX&K7KH^qpRj>e$%VR+-yezqDasW zdB;vl99j_(uga;`j)YxVgf5(MaI(pY59fk_gIF+vgOH#C27Dk6BG7;a5-^}Z1KuC- zo&W&~=zs(jC<8!H!NG!qosHS)o5&50s&kTV&O6efelX{=sGUBIX8r- zuEK>fno|he#m>S(0{b}3A|f*+2Q)B&1mgBq0p|b)v;z$$FbWz(w0c+Y2MZ4J^hm-< zF575??I?`*IotBY$c@xG5zBd$Fv#^|aPZo>0uE5X;9$XlqXt0G;6MZt0KmZnB*1}# z1qY^KA&`K|*Y9hVu<(bRDvl**(13w+U<3Qh zJxFG&k}7=IN)f8q-Yz=VHJIKoTDS>VD@o_RWI-2T3NRpm2`FH70SJHr1LrWn9t2jk zpb?NRh+(`<5l_d22;W@hAh);wyJOKq094t6EkCwa%(zMk=N2e(hOm_JouUlo)A#~93uGlMC)zfC#2lTap z5gNlfXs1k`VF)=X}!4hF&f`lMpqH1Dff<)9+L26*z9b@L;wNks2#a)Xt&czVu;@tvG`TD3G85D}xENf(8c*4p4&Sm~83( z8(a9D{^!JF45uJ9pZe!GT_jXC>B?bLN^U>_1r6{9+JM2qf&-D5s=z0ZAOi;r4zMVz zqxz>r<4FoNRIXT!P^(lk-{RR?SXFF8_72{~+`_;yz!N}#)B+3+794P8`f%W48Z{TR z3$u7*3{@0zYjmoTEv%dW_iki(54ySsXfT0Spc*(>a1iF_I+OViF>E9`PKYZSG%n99 z*9wC3p4=vCdud2F5<>Vu901_J0u0mw2O$6L(o+nk(-mo>p zRh*c)4D;v%u?sni(N@ETNSAPWL1rW7v!;`3)(BZ@=|&4_KbNf4Pe&l45}+%4TW4A}z3n8*BZh`#9KWXv&*YgE^OK<_E0q2^Uc4P{RZXm?yhVZya7i zS*}_~XsQm>HM3n|1KLq{CZDeb3B3GW7y?yM!;Ch0aA(t=Rs?Zf)eKxqGA&Ju%l2Aw zv2Beld)bfpz7cv?qvb363(K+j!ikiORuR3pu;Hw*DK`)EO!XP1o=ehXmf1)o)8YFp zt*0=T?0twT4OPNzcSNbsiP~k}2IQ79hODn{r_`04?mng8kriRw-mzb}O29_0> zWYL*mUp={&#gTaWsF&9qL(hldqlqVC{(EF_-NHo+V$_CP6S7BU!Fri8KIF;~;h@5w z3ZfWV(t=!S7lM48Bc==41eAbyVl5Qw8|ogHE07B{`-X<6ZVrAul*3G|7>!Wm)yyHJ zoSg4Q_?TBzPM<*7G@;CeW#X?DmHC)1uXWihrg5Ynsj@AYB9LNLa&>=4bJcGr!ZGU^ z6K#Y2en53PVbS+s((IZNKZw|)*cDbIYl>GFA)0PVR_uK9HdsjmeUJ&&dO_E-i;P&_ zXz`}C;xzSX=>|s5e&Yt#v z&h2&IHydv)F*Y@bWcf|_kwp=?4{kq5a=BtdGS2-5%d={;XFQV)54jE%W@b;G0g7?H%x9dYm;k5Vmi%{8G2>Bf`y$Ke)$iy zmY}YaWMO&9H0ouwh_5Wg-Vb?-ztM?G5X2emOgiwzx!Li z>=sI(%X{m|30%#IGdwMEPNCgJ7ah;sZ$5lHUrWWrV1)@UsdcpR84IbtQo;LOw)9uW z_Jyhh71wFnAx;_tGouGIT zR;tNKB2a743@HI8T+2!b^@PX68=o7R$HM&MEDoK1U=GBBU1Ud=sqM|x;dSP;M$hs8 z@gF+myA_&;+8?2_%Q)fo!*Syc_BUFQt%&oTP_kbhUkY2@Tsu7(XNQH(tP0h>ISV6& zQi1gGq(ewhb%}3bFqsS@62ux50`p}i{g4JRHPY4SAlQ_bb46KFAw^aaf?9sggP4sX!V2^c{6vFR;{> ztcMee5TQKvbK>~^njjIc!(m3%DxU*SSUv1qa~4yA3$OA7rn;#@3maT&?h_i+^vh2x zA=9hb02GL0qXnj@01f*=bnMP^Jlnyul6d>oY23etrV$r4x}BXn;@we@ojs-0|sS8Ht`4(8*G!AQQ4T7|IH&mJ%k-H z8j9Ab%?%~OQp_o$kAc4*HEH!lEZq}gerCRc}^^vd^X^7vUW)@ zGfWD_zYiHE)Ei>9$&F|~nH*N7)Aa3w8@~o%qdP%zN0g$%|Md!(t3Aiu*jOWT@WK{8x&p?s4xM_M25j`E{hdFkyA>J)>{W zJksu~dv-Er7`vWmLe?-Eg^IQ}_h;K8iMA1=@P%x|Zn@UoLzc>QT56B&!>!R_t20#* zbvBCRfk7vbEOXm}smpa3uWnqP5hKREhZ(UEQP&`uF)x|O?xucaOs%z!q{T(Oc@x6$ zq)W-sUA?r}Na%u91V7z`ZN+=9<>)i5B-Q7U&@0g;;@|&Fzn(XF`K=12DD3{;9F_wH@*rNzOx@o~5lv;PT9LZwfuCe%v*j+Mjdb zPd`~Q=<1W9&?@GJ3bgrARhgK;Z>}=g4q{Uzo^UBr_WSyCb3dHr6!#%tuU~6o+Y` zK)3%9>ds@#a0y9I%MeM8Vn2G}L>lXhb)zSub=jSZA0B~0PGUUQ?TvnfV+ym1Dym#r zkYbTljD5E~6n;$@s-!a$5}fvw3UT@!KZ_Vk!&YRk)SY31f+lCeuW^;Cci5b7hF=pc zj@d4aiHeudIHFMI!HC<-0jq0%RlM{$yuK^CZjiZe@WI7!T9wd&cBnQ;%@l`#p_-Xw zq(V6crAwo7PCq7vjGg?k(M#TwPaLt;j9fO4@uYDx1=e%#%W~Z+IU65Q5KB{T(?1`M zCe7c$$W5aUra}MA)&p7l7U{;kUB|+iWmbn3U75~|kU4xrF{RHy52tk*ND)PiRv5pp zLc@m+MpTIsiN;dNxYsengI4#;BqiIqvsWXYRvYQkJ?*q!;g^cFy6Z#Wj2H~0+5D4U z0V&dFADL2ABm~?yw@No=9L%2xbWb>cI1&_^P&@5;og`c+3NzKK=qc&g_`h>wGgf(| zwJylI`Sh!c-{rw4T6z(>O?%8`l;UH!DSCRFg6D5jc%kbLZ;R3)y;ERqYg;=*NHO>)pN`NRy9{Ik-fClr#S(9kg;nO0M1?m5ZF za=)b`$0X9o&K3L$Yb!*PyofcoL|qDRm(LTB9O=R$VXj=V6(ddhl&`nnsb7T<&dI|o zV$#Ld?xq?f&`~)4Cu+JGH)@n%jjAWarpL@pn}fK-cAFj2{_QDKj&>e$#HE9hS1ZFE zCK84c-H67e%jA5>3mSgpdNyE|hLR7F(CelsE~3q|>SbE7%RH!dQE?k2ib7m37sE=4 z!9!%#{6oA?jyJ@$JYBI?l0T)>9hMavN&6Rb(?a0DPyT_n6}j9#DiSg^!JYg$xI*YH z5fpH$O=OEM0W8nQdcyI)d_)(HQT|W2T$eO)NScTs;_;cQQ0qX zx1?!;LdraLRho~((wku*LYlA~zhfCPaG=vv5b27FFfsEUxY)dFNt%L@goSawXnp}B z5P74cMLFH2Iy~D4v;UzB9O!PBeHV^6SeS{4AQL0!WQDad@qu9}Crf5(&Wc9fn~jz_ zNcE|H5YB|i(%eSGFJADX$r>tS3=XOf_^J^s7@}72kTG{!qF9bH(&o;ganHRN(@v(1 zcd}%rMx*+oSSbUZ6^$$yfiu8>J^&8dJ3v7Oyn=ZEBKE<82^>&&Xk*~ptff1l$_Tud z{*0&*vAzy7srq|nQnMnDzx@A!IFJAU4j8Zm8la$o9*6*cCq${%JqiBuECm=4fS6UF z7*KYA00aYG0Kotr2nG%oU;qOgm;e9=3>bI?-2rI8T0w&eC}8$~uRw$XLUR!BfCLQ` z102Wz2l!yYfpDOKHW#~n@-0fKbg{3 z%vg&pjx6xUuzM!{DI-5Dn{o)o;Um`>LKm>g{yV?Ld%iG4SHOV=Iza`fEf{J#gZ~8_ z)Nz1<0Z1@`1R0pXxQDdC$yv4IqM;l<456(+(eIcEbN{sDXk;?QWkH>?9j*gkvwS>Go4`0D=oSl(diu>9v&Znu6@AsuK ze1>PK?~U#(nwC)X?2gYb`j9liiRrFCPBic=bW3uVS-|`%&EkvbUuO%Rbo(Fr`v#k8 zgWo!m%c6r*f8Q$neFpROY&ns>Yr4%Y*+A9zFH`h^hIuEgjZ0VS&vsp!2SfQ$*xZN5 zQY?oV^$BrFwY0vMj~Z6LdN<6rhHZOtPpA$TD`id6v#yO{@~U(JBX3tI#MN|Z$hiA% z>-=um@EX+a@#bJFy02%a>{hlJX*SvyFIu5Y`f|y+!_9nXcf-gv8C%oN!NoUtj!jpO(a^D)I)cZ^0*h>(Ok&bd_oL%XjY0wt^Q{&4= zzOxQnJ9-f)lrp`1p@+kSV5W4T6BzI+f^8(e2X1e~?b4&Uo-f+KAw}2*!&{Jjc0ZP# zs0u4VivNvnXZdUF$?8TBw>Y-#LQtTqwI7ZYBePn6Y>_pi@b9i3Xe6F{eW|Y(O|m$6 zpdoY)Y~oB6yoEG76Q{zE(MYG#u?~}tiYAk6XX!{@eh-dw%8Uhutf0PxjqaLJ{Euc` z^QzL0g;(5-8K2mPlZQ_Z#{46+m5ZpHq$6`mJMmN{&N`&@zZYVDLnjAA-=%U-*ZlJc za^aQ(a+yZhrdKh_U%ClXjD{C4uZKX~DyH*Tq4kN6m9D|Kz0!xyB@fryxFfWL->{a5 zhce+=?lj11_y+gu%<8 zo%Amuqpq9w+7xj}n3Xk`O0@GO4c+O(M+k-664%hdZ* zX-p&-v6jmmWs8Q3{GD07C>w2s(Yxrnb5Bieubeszo}jF|$npxb;agIPm*>QjJeXaj z|8ur%QxH$fmQbO>+@<*m8^y&M>7~VSu-Z1e?aJ0^sqWs~`P+Y2WYqZ`Hpdxbk)qzk zSJZIbRny?66@8q$v}AKdhM5zF8>rJaI}QXf1|dTTF~$%=2tkPT0~dfG7!U>of@ASS znN}YYz(7U=ad;pSibH`wAPfeBf`A|x3`)@!V--L0{o3(y=bJz`8Uv*d%p=7)dDNvQnqMB6g+SeEYXM& z5H%Lo`;GM2FU7dfU}Zhru0~7X>o$Sby|V!V>@stcpcy)TzJOk4!vk_?=L2aW*tq~r z2D39EtmjDH?3u&VR2cGtB-YqY!D&csv%wAo7a`%14Q z0@#L1L8Th`(?qv-Vbb0E(!xb12 zziVi1KN;bI&P!n_#z2Bby<-bT89~EfVaa2h2mX6>K?mpvExH+X#DfeNf80Ef07`(Y zsDygikNm$Ky(zVb)=CA;K5Y;kDjU40tB>0ql|^ia0HC1<=j?@=)FJ%`)@{{4Gz{5z z7GM`f3H;+I-StsjGE5aiPaM3nl;G?OGVsF@%G5-qjS8|!m+(P=YFD^{8gHR`AvRIt zyVm8z);VD9r8UAIMs$1N?Mrl)9 zCISFQP*;waTD1>eG8yIsWBxZINn3*P2zcxsV@#kwm9P|J;DGM8WDCYjKs(dQ@)_aZ zvW&JXM#x9z{w<6#Y@o7~t_5S_K&g;iRWQ!m2y~FQvTC1yc#uI|hpRWYu(4)^nqg_A zhdQcDy#IobczOl)zU?$~D|%VrgT#oQfYTg7~ zV(oSozMNAcjWe>(CmhU+35so=bPld)@GK%O3^M@RC|!cL)5GNuG7}$1m0@{^CC?*= zsAh5cv4OGxLuw;GrFQ^=VQbwYkcW09B`5^Yx4l?Ix2{tn6DAE#d|IA0>C z5hK01YxN{i4l}H(TpRJ@Z&2KQsxPsgm=lAm;6vOTmh3?k<0wG2Z%yD1Y?}e;WaRNA zm^jD5hAT0gJyQ{1gqFn19^_#T9D5B>`iMpHY~hDF2Jv15Y5#Srhj9poPsOGn`v_cp zOU&_&GBIcL9r0{)HpKU^9`TUhWkAMcaZyBvOPELyaDd^#S1C3=G;@xrOH3fLXB-d& z2h+2_MEOZnF%!EkFasXzgsjnl2HpAhLokW5d#v%@TQmMESdlikZq#l)H{6hLz7Q*L zay~jXq#<1<>@k?}xYQv8p`8j$oC$WI>C|}=0A$V;dk`S=Hbz%W%wPiJyf}PdBNC3? z!Pwx8^L}wo!whhwa*Y{*2EoDVs$|3n<}rumF@_1`aS2J1SfmAL z8j)QrIygM$y^h7Oe?~&vQj7A6y0EZ%7DVYO`v@#)vc>#B3cw8x%nFo!-s%lTAQ4$W z(s?;BpocULsa=UrKkMZ%gqh?*+u>|0LNb)Y))i-(|duQ6uDX{WX!mD{7 zS;Y&uxUD4&w6Xez>IlR@yB%;sF1Qf0e;U_ZJM?R@3412aLu4VqT;&H)y#^b|#amzu z6Z|w>3@pby%OC*E$)xu!C^lcx4YL0uV^Xa_fyA^mzFu-BVsh?9W&03|#iYC~+|m!; zo^LsFp7|#aU;Q@_e8Mfc&8@vVBd; zb9*ZsG3?ogZ9XYa=JBd!L1oX?$D}+T*Ng#6i;b?m6y?c~h48$NxntlkDWp8!+A)`n z4TZVDot-z6*s-ApfUL!rBA}7?lur9?^@i(`u`<}dK01*34X9f@G}PGsFen%F&3*c zT8%IvIrX_ugURkcitcwf%73t(ITiHyCB}*^ZEibv7}^7Nz77D={z;C4!67DGBlK=_ z2J6SHZp|1dV#|~+zZD=L5j*H@Tfoe1Y%aI0D>q5Ox+Nf=?ye$KPTO{=T@#*uNx`zV z1zoA^z$$h?CN5$=tGR?VzGR~LPzZ`6G5Ws7aUMJl0KjjTBUmY29B{MXjH`|yO`M+_ z0I}dDzr(RBhkJzmE<)+ulJ4Q$W$zv*JoU21aMlsTC&dHnehJV;MFD8DqA8in%;JNF zCczJ$2m%1A;OLI2@{y&yAX7_yC>SssS(i@w2D^9s9L08s5PADa0r1S)9S6@`Al)$242_i=@%X}BJMIouXdU2|WdF3G!qqTyE{|7*55O&WIRG$tF$uRgW4Q9I&_yitrSy6==(kAi?~~NuDx1GS zc7Kob{x13ZHoffZ{;hqzKeT}N793jJncV`}4p0$u4QOn>`Uk>H#B~38=_B(1W~~G_ zV0IA@8-;X%%>vTzG2jZ@uxKFOUO<8NySd*L{(qbU@4z2op)j0GG=S@c?&jZUaUTO@ z&w!Mdi6hYQy~hZ&!DlhA5dlA9mSi&^MnYuJZJ79-t=-};^7eU$G7 z=w_-?sRVWBj$+3$i!YjAG|A@Y+GMNrFoEpX)2VZHvJ-gmYlH6Fe8BY~)<^269&li# z%P7G*rtq+q$BG+0HPb$z)!?TkL$;LG1GmoufPXsR>goA^Jny`70~s}O*IpjhDG8iUF#w$+z&%BQbBclQ zlmqA~-_9w#=_%olFOW{N0og5uu@AWLYp-UU{ewOpXT1(%w2B>204_-zPli#H)WUiu~5tfTRP z+~=K}j}|>Co#043aEa{ye;fAB$e&rM!pq{Z8JCgY22^2`EY+d%{s${6o!HL9^gJTmPKW@s@Fp%J5R@A#cvzuSHdlbiXgeiG!I~9tw`_?!EGD2C z5l9HU>n6}@QBvD${Qallz21m(<4yVx(8DjUPnI|1<=y%+Sz^8cKGKSfE+CU;S8(~D z?P?gvK+qp!cQZSRlzkEQ0>~_PFGzGC=*p-rATvNWkoh=Dzgo)88tLLQp2q0qXze$+ zpY9#)Ej(4#&ov%lbh+fCERr=4ImMIQ)f4E6>q;GHsZro`NZ?aDh)b=@9prAp;4bNG z{KA88evd63bTF-aFdWMgVlGq#>(pVAA>Qx~3U0>SjOWd5zV(Zeho6P{B21 zHq;n-sNpiG#>Pesl}8&VaLE<3f`u-y!=F|^j&D;SBRyog#_6!j>o?+t@#B|nz`uZb z2~ZSVZ_IQ}OdcP%!V>^s_z$`QuJ;J2sTmHsD?D+Rn{`*Y>$}8ZcQt)?`FwYYMeo|2 zPj;92`32JCXb%8N#7A?W4Jgh!m*yAF+4ZPm=*Puvr$?O|;J^Xe=%45A@D&CCXv4cYZ3#ad4GuIHn=wKyS8;q1 z9R7Z8uwqar0{vG2>#093+W>&_U`G>-9*4NcQTqUA z>CsW9?hIJEh&?^|c(`lQ*f9+1__iKX)8uuw1l*7Ztwlp&9rE+ge6ARso_*a;<)`VS zoR2k=ELAYdvv6)CKAIyS0#fH8=&aboWmBM*1I8HcEEzJI}O3Ysgxg zeMpb04a}7?_IwjmU2e^qlXfTohlD8x4QZtqyS?$@Sems{Ml>StM|+H`+I&uC&gSX@ z97;f#(}W_3OO~Mw)1(ht_XN_6HT@&D`~7<{X^Vo=!7?vV_vg;##igbiWe!}k6S~1< zpiI7C(Dozoy7GX5omrR7MP)>0XNDm{1Njd@mV3QCK!S`p<1KPN_{7{Qy;@sDa2PHmZmB5bc0 z90S9|!><)XMHR!5WWfNc&=CQ=v^lnM(^U=tO#T@B6Cd*t-W zdch^#F#(Iqs$0$lvIVdOQgJy?sjgXt^w>poi;9dJbFAc-Bvwpe+e_2ZvFBX2Ck_MK ztnvp;q%L0D$IH-9haDW8mg_COdwNZc^O%t-G2|q1`#%J16(juh38o`1G7}76bsQ^Q zJ-0zGB#;%2%?*ZEX#3K7?3<7i=*y&ZOv|aUXhq!u`{j zzG(BuX?z<-EZi169YpCr77VNKEPB=5Pd3P(({2BFTAQfpNF949 zq`E_wGA|{Nn=E1l#;p&wZlUk=|kV>3&(!cktb zS!_3SgEMl3;KU4F62h-U_((63vlqD*^c?EfRemW!yvC$H$A@M~6NL@}a78WsDAQIz&lM9?^=CPQ?S?tqntV}{+* z81g!(saX(0MheHT@C|gspl&!+iY*ej*FnfPmWGJPa7jCA>%GGQ$L#;%AWLvbb~81y z2pG)t5b1?@^aF9QU{?7;i^7G45WLeix}GDkGKA1e97w;GW?ATG_^tkLByy3)f?AU_ z-fT#1D1$ECUCG$^a4-$c{5Qv4&}?r^@>~wi0ri^ggOJDUO6QC`b+zzk2ccxe$XK|g zl#VLQx42f$eG{Y5Y#f$Sb+TM4kHB`7S>ZmkhY1vl2BS_m>rT)FKmS@|A|STqNKLSG zEZuX?l$mQBY2N2$A;SwrXbRy|cV1sXm`uz{NTq`iIXS0T)_O^W8FXwVaUJuOlI*OM zB`T5)mmem4&SRrg>bg5BsVhZ|g%8_}Eh)i6DXHplhTUp;;R@GG(ySOH9m&}8fWNuU z#(2SZ0;T*7&nHZGv-NIJ3L*9DU)jDq+`Op{H#?`7&t+)G=;03(ijvJkcOueWCuAms zKcRzE<4N_;(V0vr|F>YDzo7J_dz!!Py-&9`)(0XtC~P{vwRcF0&@j&Yh)dPkwzlQN zPV+Iw8H`PsY=t-fq)k+_ zqWuJ`Z}g0X-LSZyLh_CghOqCOegp^Y`^qbQjbwNnVKWq@_&%^SXuU=?%^!c91n#Y? zWoiq@6dmM=oHx|3V$txDLDY;ms7$f-1Z50sb+N%!_CT`pK71)&0j+?72ByKTorun> zp+YidDOj&PW^Vd99vCo#nFS-o1ibSsKMHtLzy}M&D92FNh$a-5LzIl=aYE#e;Nac) zIt)WA26PWZ0DuD#0RRpdG?;(`6fo<72mo;46=>jK!308u2=^NBEYL`JoZFqxDUP_T zkf=6H9j2~cCdy?MuAB)Oi76bB9ZB>ve{&A8lO;1X8PJMGa4_I{7`d(r;u9efYAS@h zFN=l^m9WE`dTE}z(VF=YNhF!I0_|Hco_vcdeS7<=5zT6r}IH z_dkKd#-k|0?g?XJ|Ay<-r+G{$%E$>UXVx|h9J&viipydJcl?;7lZb-^ci7S@?5^rx zqmC@y?LJ(ba75Z>V%ZZF{6(^(DW_zT{tIjp9OSQ5H(u2XpL0V{Cl9`y=uC;trDnQd zLKJ%%RIA(tqXVjQw&5^&8Xaz6M{Wor@_|sp4iw5b?mx7;RkQf{%ryo+y&x{L-_#Bq z3e)PMe)Jlm<6qyROY{91x06i~{}QP<-Cllp+O)lxg^Eo#9aR#u?bd>QUr{LM#|M@V zj=g%1LAmn6Y-%kd#d&!kt7y$;75(Tbw0|-Q;>HxAbRH+kHh+pOgira}bFmE)auRnt zu!lh9m|Ee|3u{l8KKin5skAFI-lya*ux1CDiSQW0hB?1(t)Td_1LKXdDdyi;1sgKUcD%k2Yz`w+4&SpfI}yg6vu1|x5>-ke9a9m9_C7DR_#t`Ty4D?VOZ1QTqDpi@7qY0br6Zjknh3D$8M)|+haq8(V+dgX5v?a z;dY8Ih$d`wW`@c{`w)q>KHo~&jcSphH|+1XV(|RoX9X6|`3XcZ9mJ?q6r!DcXn1r> zM)|nb#a)Pob<{PR26C)mmv*X#f0x z+_ZE3ywo-+DyNMbR8?ous$*6c-n36BitGJ=w~i8BF>Q?{!JIV2V;1(#&wJ#jSe5gS-y2+l~FTzx7<)@ z>_8^d8b5v^Xr8zBM($WO25xnw@UXeWDFzPWrYjiYS7{UD`aTweNJBS(X} ztnW)3H~8~q9F!zv5q{|u7aC?rL+-`B8JTMyO}rNQDvzKb&Jn30J?4qCw-B?Gz#Gz0 zeWa9J>G03f-;=leMPI)0JS)N`@h$f~5qJ?hD%ZAQ0R{Cspon{Ls_~OJ4WCQmN+`79 zOe-9YkS*_Ra>xumi*yC;%V2XFPvH^Jt3E<=gkGh;vf(n3)O$1Ams@t0q13PT|ry>{|I8W-kcS7x0jBskwSP+wSA3@!nF`4D{x@p!@PaGbqZcj*M7#qaigBC zA$gSoPlOe}4ZUYe*UyTx(v*)$BORvW#Dg>Rf*2MPVRYb~=I-D&7x0@`+8qVEOyYvL zDu#!13kGMC_m!~J8Xnga6BHR#LbtKx_H2)y3+6^!OQ;Q>9e9M9^lKdIe6wqv%8W%_ zSJ=af6XD=i*ZFvS_;OnO4;A@dIv$@gVU-#Pki;4a}KVF(dPzUqw1ZoRYCXGooLSjCQaZ>J(+mjV0Fy4g>spyhu zWr(AIMI&J$6EWXIdYWSp(hnXBv0iwF))~$9hojyh1Xua^wv&T?8j-ux*2JesKZm(J z6N=BA$MkK{xd{GYD7npU-dMgu!Vdw%j6R>`_imZ12Fwr<&>L^ke6^a+R1t%QY!nb9 zPz8;&w>YHXneOE_gF^&f7apR=q@57!;}NYR{fL zUjBH~gMaf&0grlp+YHSztoY+(S=QPF(wKeN4btV@72aQz9T8>sGQx%BR&m^e&Wa+d z%VO+IQt&XN74AcLIC?i2%2=uG9?|mjc(9PP;h`(}k|FoiBYfPM1?te<(xO72j1pv$lDpC@(L%<9 z#pqDjKgGuDF%5J;o6X`Q1jp}sp8#k_OsK;5%`YdG4baJXY+>5Y20o! zyltrLOI^(65aL6yl+&dLb(t&5rkkS+6L0g$z4kTjl3g;qd*MQV2!9>d_%GV43mLZP zk%u7!AFJkf`{}G!zjvjNC+lb1Euxr~c93A(Fs>oy1<{-pU2Z%hZk*WaJ4y?U_iOw= zH4!1~a)v-=)?EJbAw;E1vRJ2$;L&!WNp$*%NZ}XS79L{^qY+VX;RWW`{R{r5Ei7g~ zZ`UDE=OR5+gxf0bwx=b zwl-xfIDeTIfBDd#U{Oylng?m3B%GZ0>%$zU@?YE2!uwIr;ORr7??ua6{ZD1I8=P7F zYJYDqut^SO_?pnPbhBCKnjttCYwXrpm-(_GQquLJZ&m1W7rEz8B=p7Ev(;Y7oXMt1 zk!O^fh4wD}xkC?34>^>>680oFbYNBY`6&PAi_-RWf9O{ZZFSM*C?*zG3@wF*XD53@ z#tKT&oHn1{PluM)3UjzAHam?>S`m7aX+5K|3e!7>$rQ_$t=a?AA~Mt1yMG!dJIy^R zc<>EG@8iLPU276kmrnR(=;De7ufJPXB$n_YP)CMhaXmZ?^@nTYv$G@8)+~QxWDY7^ zSFMJ!Gn(5)Bw_9=7@_~aR;|$CM|fvm2z{q=YP!yqoP*Cia)`~_e~Dw2$@6CC`yOkX zl&j;6bAdO=KLxY)B(Kg$>X4CpXy-lNNHratDosN%=;_=9K4o+^)D6rboEA1!D#@6_ za8c-8^APXSchirlCDrm#xf5nwQXW28TvT@V!h?tVo_AeA0=!J7KkF7ewq6J1Qn#UpuMsoao+>od)zvbiJgHq^(MN#4`sutA5HS)o!iBN)L5 zMlgb4wW8*l38nON-g-r90q6MB(2I?F?zQ_SkVMCX=#)8K3#mjxO9)eQV#f?c;Yr9c zEqRFhf=j0K4d=p~$0NntK9NGu=$GEZcnT5}f6|;VD^ziVQ;4EtRcibhYD~UsY3?vu zrVwEiaYigwF40q$D2pw% zD3sZHixTLsS>y2wqcndDYl)bUct1MF=9XW{&3)gc6k>koj*?dy9o>1ku6|HC*NwlQfAE-`%DNzN z=M$nGXwr9USvD-=vMcYd52H>qXIfWXs01_bhENKO=~w0+I^cegvTyWT=f#cmrYh>Q zpd{pT(y@opWwa^5wbwg7LYcAzzJ80Fe>XYW zgQ_;)%!l9h=Mhn`gJ2Mi@bpV-rBxveh79+&-w%WYoTI6Ep;eZ^&=vTR6n0;N3IpA;J5BNN*FHFU!0mJ#2_TJ~U?**HB)MUK7-kjQ^FEMI_v# zUn6Uf4A$mieQ}rLz!-wR4@T4X{aM%_l(g|-}ZV*m4~5UWc4 z%s^CM9D-0<3(I2YURbYM=e|GNJ!e*qr$B-E@4WBKbrH%!yhZ1wXxdoI%^5|cI?cl` zu>9qZv;@cQ*Do90Su0k*lZ@#EaB(0x(>|q6@rO= z;B@7`1fQ19+6z1W+R3Z+E15^M+#Nf|N?K-XD-JJi{0uF&*i+K;s1}GKZ~{9gtp%w_ zlhc=$3lZ$G^PApq3X4C2hrl@I+-PBp|E%wSE%>D24Q{&jvVFT!Fcb^Jbsu3hQ4dKe z^4c;zZRXO+VZ#)TXm{thTtG7MkNqB1-7c(oE*@3-pi9_ECH^DF^L%>yVB(G_=?|Cs#?dj*Bwv zQyf~I;DxoQgUB+B!XU;NV+bO~7-JAoiai4sU?30(4u}H;!Z1>Vq7M_mzzhU|AQTFR z!vRq!31ksbS#gQM>@Q8ApkI|Se-f%gx0M9K+;S#%edi4M51U3O-2Z+2a=g&61F*d7LmpV z-^qe%skswff8a{x*6vB{^s6{1Gwwip46YY)!0JtJapXrJQf$8sD>;Ush(?a*(!1e5 zp}}HO8yOa#9~Jl|?J2hY*w;mO2>K@_aP7OGvq%q7^6cP#SN!3ZS({yDF-)>CW>Wkm!= zd~Q4Fr*M?Nu9W2SC#9Eq(|S2w(n{La(o5EG_vuIVK86ptzpxRMJrUy82Ntx~*(n70 z&1RTcMIHr=Q3qEdzWX8x5fXl|(lAI|S$QyA=qxibunbC^g&N-6$L#Z-a&*XP zmvtsYQLoZva8BLpG!6^VJ}w;G=MzZY?gZb&#HYBE)CzI>htwNE*3;K)O2;}#1t=vl>(j}KfoVtBp*1vUz_dTl> zit?H1U;bX`tf)T*g+2r5H9FpfkqC%E`%{C7lJXna<@pL%@&~+ z?36v1U7L)o!}G{xk}G~KbvNwHJKE&Ud~T&U#dR`nVZ1+}6PH6!)e(JnC-Lh`{rK7F z(l#7)9BG2M3JcX*J?cg&K(0d4PXIHt0uX=@*6Ro(`kYf2&F~C_PLVXwrMcO160H1= zjQR_dKrYjQuNfrDa>S{pbn)DBIGu`+Mf7!4?tD;nLDT%6=KxJe)W3R^vTqrJBLPdWe|yO(x8AHUj9fQlLtqk=HA%gTEwk zS&9CmxKGoq^{ z9$FI32XmWKo8jQ|S5dB6;<(dr*Tg_=0h;{=2#%=31S9RRV_$oN;OCol2H^Kp1vl#a zn-MkyC{tL80tbx?(KlH&psR^D4O&KkE4VW^ekY+MR`t!wjpQ3pN`mwM7C)~5*F^~w zsAUO4xD=2wQWkGJIGPqDuFFg3$bK~WARFqC4N78)&m8Fe!zK4hjCxi4lK!S>%s5n2 z5%Pl2cR-n}Ljghc z0@*bZcM&r#fu#DvlG-5C6!{FueD;q}E-G7Ry9=92z>hQ0Vuxw_?)X`NND=<+Y>g3$ ztzjeEc%H&&FvD>$GSz0_fyGJ^f1ChlK;)3f%7J;7;oe`?F-sE_NL7Z|p@V-fR+{i3 z&iuJbR<@_6XjT)e|3ApeMtqnF!#5^fDx?P!891Eh{B@myNCX;WY~h)({>a||!W3gW zKj=&UU+k}hM`xJ}RaFw{%%p%I zv{m5?_97-7avHFQAdX;ddwwcoS754aJfmO4<<>XY85yy1XJm9W4rV>eALS=p1U2<( z=1rH_%afQKVXdt4`a^?OHiPq~1OZ0E_eA)TWmB>_)HsuTyH9L4Z9#)<6MMt^8K@LP zcsL2dx#i&G`36?5?qaQF3O{e|bF&p$5pWfzKrHzm+OFA{di6KEJZ{A8UzaE96jyiW z;|t&A?PpMV;EJy@ejFwrez3!eB$ne@glGa#16|Q2Alcddx%N}2e(`ijD$}zh>kHIR zZ`}wOm!Y#~T*QI?^^A=uV-}yH86j>pwx!Hg6GXQC%RQoyAIH4*tzXkrHY|1Pa@D6u zNq|H*g|SZ}_UiZdP``%Y|1kJ}koFHQxHjz~D1{{|ar(^$xeMMA%~2>wbtMQpbZUZ) zpC&mz0~W5I8UX6z3rOC5)G3OBOVr(sgel}f++ww#m|s$d7e?y86gbYE+?D>xar`Kp zQhdL}I9O8Z8cb5PMMhx@;0D=Gpr3Gc03Vp6t1ax%^|<-49Uj{Bc?nRcvc0X+lQIK= z(noqB6!#4;94Mopo@bKrCXrHr%Zn6i5=i7PE=-rbqiErxPXy z2;*y9?Ys1c|fDb{3$<5mD` zs$?%t@6?=(JH>1P_zxK@N(Co3#4bYrHYijdT21_5X`_~39wm~Itf^BNg$(&|O_cP_ zUP&jwASLQTHG2F%^mF^^mf>db5}`Y32I`CH`1dPeCVXv0ARwnIKUJQS&tj(`2&b0K1x!ROB!SoxMRaCf*q~VyhrN`m$Xrx z&r$ANX(J)uEMRXFM@$1q%?)hch$@Jca@e#{a6q&&vJyGc8D^q`-CFAmDi5 zpU$J6MdkzN2lnQtEFs-5xW`5t4=BcwgDar2AzyhXNo++~+GHT}GD(VMO*KK=@IAz# zn5(`>V2|u{QmXKA$L?mMARRiI7@4b9F!T;~212z{00EDW>*hRe9tgtP=`<-~@1GFN)K$lIaAnxx{WnJJS28%&bZ| z`+WL0=If;$=MS`vVz45|c|cc@!b%;%0Z>iInmK+0M(i*Pc0|q#v5W1*amSmsM;z%L z@?Q!Y>s9CIEC_<6S0s+~r~#Ro&GMGmC z`B|I>b&DNxWR#UmS%4379zPHrE^(a0nJOs=O%#oV%|H}^1Osxv8FKilrA2;iLz*hd zB5ZV81`*NhAcZ_HL=U0Fr9RiojK>mxz*{tCX5#)E)~L4 zJI)jpoRX8wH0W47Y3?ZKd6hvic_Npp4j^6p1l_Vu0AU0vj6pjm~Rp$7qms409t5*S8zy9 z#ug%D8{pFMqNY@`@T*Zg0MQAv@|XE7bV>XNtuwrH%B!0#9nk@fGvDcg7pwu17B% zs0-(x{gT9hby1=)&UaGJ3dGUcw-LB;3tNGD;#gU9AL36Qe!_66{0~i_B4{cNO9VKv z7;whj9v_G0n{CER$od25d|jVjIKUdZZs89Nae4B@Pdp40ma=ZCT^p`Nw?{ap(?iUV z6u|Zg>p)PQHPtgXlK1h|y0DI(-OdyPd_6Aig?(2%u6Y`w$5ukXs0ah7`s`np(sD6P Z5eS$`D4h|%|KlzWMEd8z`}e~W1p5P&V!!|Z diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst deleted file mode 100644 index 1d7a3d2b50582460ea6e1a9555cb5f133da371a6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 15182 zcmV-UJF&zlwJ-euScLolIxzZ6BM?(k(gFNG#vcz5P)>#sqB#G(@t+4TBu$c;4IEWf zRaI~UHU)76a|B#Ep~m`-`K2$m(^$HPj@bF3r)4B6h*743hxY8EF*kDU&k)i#xYYQB z*s2Pwa;ZUzZ;WEG!;L1rtRvCj4E#_SIrwEn9U@7FQ3U< z803jJyW!K<6!aaA?bE>d*a^W#2{cOaeIyxQUq@o9`8o0+)Y#VnF@(4??lE(bV_Dhw zVGX`C<>RsOW)<;t_{Ut&wZ84SWs!TyZW&{%;pvblx3N%aEYvVHVJwB-^LgD9^-|@Y z4xKwx=nqNq5YKwL#zxf6_$qO z_YzsGRApAU|1xM}Xw_>;Qdd@8uA25nRYhjDg(@#b?3xW2NRR*q44hdt_}I*ZJ`}46 zy_ca&YxNpRq?Z_|50RF2l|+S zVJV0{tGqasUR=nvK$Q)Qx!-IQ7WnW~oRdB5&|K;7*U6HZf2gu%^#&U)>Zv)-4dJO! z7()5X10ix3I}4*khhwvd$i(D;1~MRlxV=@tIWU2Cpg{(Vf(EVL75u@11Jp4VU2XM9 z`!T7edF|a!jX@PcG<8|#@F6e)V>(grznm-J00j&V7999#00a#VL?8hG985q095`5T zuwg0$5->PeaA1ZzhPRSwS;|GZS)p9Y^`<8GLnd4~vZ|p5 z9t9M;c$*@gj=>1uT;?FR2#uX7A3~FFWBO3UOrRdn3fck}_lMMEfbyNWZYo(E%O-!n+fd(XS_6iOb9C)2^n2fs)CTkirTa1Z3f-I$4r}7eY z!v_m!j6nY(cq^xabPAWd(U)S5tSH65Joo?tBWx*pgW2R5)+g zZ@WSVXpjM~Ks9i%;DCwS_+x#?MY;Ej+hvhL@RO~_zIoBmwrm-md3gI#!v_37901_J z0u0mw2O_Pp-LI~L;lGOg2 zM@Ff9G1Tz*oilU%HQ~r+6*K&^tV~GnWrAym)G`zczOoPQs@w6Vd(E!61k8ELxz!9? z@y(0Hw_37K&$*T#8`3MG+TW*}ZSj|y#I7(#xq(46U<4v@q)Y0y-U<|T`JwA$uH>e< zbP_^@2pF=hCK+{1J}+^y5;gG8N|%OpSKPo*Ss4ab=Xtq*nrzn-SAH*B!fC$vwl`N| zYfwelhz>o%w|qyow(Ja2t2`G%5QXBC6dln;-qckJ{tBzimpu;}W=?G9CX9RB=&Y6% z4w(bXxk#f++2iIbey={X^YF=SwocU`dz8vchI^-={uFOfdCk(+6c)aqq@ggAhtqFl zGPJ^UlC(7-bL;+UGsy|2Pf&R(x13Wybv5@GnV+}d%~!V-wk+8~Zq|AIZCUBBllN$8 zS0GjO`w%b?Hx|B!t(ZYK7DW8sb>t`yR!g~15@KbP(Qxb)ok?Tyb zC0=?7Z^^gq#JeKm?&ruIbFo(p8)R3q7>9!(oh634zeHzUpFG!|=ljqf!v3flz5ksy zXG3a2|2fM^XY%Fv1tniS!U|)CU$y<+CnWms;Yoip<+TFkaJtG+2`jaFo=%mtH*U>v z6(?pcyA1Sk*L9r5XREjv>4HH6%521EEhp9ZbOc?fRn{=lK#p+RTFMEI*$uqHX(FCUSq5jBlq72{hnOKP%qz)EEp~e0{panyp!nq7y`wLoq=zYJS%nL6OA@?; z3hB!qdV5_+%=M^#8k1k?qhL|R5UZK6PMgnj!~VjcX2qg6yXdxvYg~8B9%oWvtTFEx zyVkjc=S;IydNM~XP|pk2Zu?>q3O4CRHdRS>W9>(X5MIeRowj#FU1GAzwKVN5+iOXP zZR=~y$_ixx z$ywsKEyIPn5Y9Cp#WTYANpVi#ero?v9+guMQf?cKLD&9*L^-oQg>_VrpX1;Pwm$Q9 zpR(~~hPKhH0f#5thvy#NV0)*Z9Ks}&2L)PmD3J>}4_Ti|XuwdauxUjr=J?o6amsAr zF*dRH8S|nO_Q%7(d1v<_-A6i)Q4R7N_u=lcQg55y7CM{;pJXi0N%AHh=DKAzR9;VV?WnpB!91oU-s?>+WL+TZD9^z{ZnG!gXZ7{|nuGiQW(@D6c=7 zM{DfC&O?Y%?zN5JKhfa38zi`?56`vGxS8VeC{SahFcNN0_`murTPb~-#ivKghA^wh zVeJ%7ICPtK_~qhYhc8n_HriI}{5iB0SlO>y6LhBgm?o)G{qYM$YL2zem)V(LnWdqnI=Ovk*!^WrC{o_dLplNxJ@9X!3rF2FzDmz&9nlc-doVBef%tVC_ z4jZqd&`q*4Kfy8nBjyNQuC@?U@l$Fg>d2T7>?Nuto2gkuvIZj7)j_QQGDhuEU9(zr;Rwa=V|xHt)OcRh3#E=brw zK|)-QggOZoXo7r_e1d3#f|3FW1sx>`B_SONWkjSr6&*LfI`>)xaVB*B)-a1fiB5TP zB8>0N6c~cv7NHG4VfMIQn9r>X=|HozrIziL;rtMsL+$XUd_8HXkrpCUbKi3J3>zgk z<2VU!bwKI9N@y1XzfmSc_v|8W1P&xwKfgQ-Mihden?xN6c|lbse; zWT<|0MxR=NV?|@yQ{4$J7kVw~sf!*%IoZVq@R# z;W}w|pjh67!BMn$+6mWsp@rr85l`nOI|O^=6Xe1=)d&=pP0rEJdA5+U+a%EWXHq!1 zY{I$O?OPbpIlT>ItD`v?or%wrmsO5#5*REEJ!t5EK%;J~J`L+5kz!1#4+@zL4$*qA zK|9=|S5DjPS84RR=7oA!ht9vY`1mcmcWFg?=en}V@zXB@TLyRa7S*R?y4Zo8c8*@tEf;5KU-!eJNXcq9eoOKwsvJy7p{VjB$;r|IYd2jU`7Mm>ZZ8>Mn- z3wA*(WAUW2b9Z4w<~x(vQ;7GbNl~2tjSw7l+AH{XK~F?4kbMJF&i3uS{Zan8jRk9( z`n9B5;=MYJ;38J?ftQ?_XI4*?nHmbsS5*p8qFVTud!rq%plOl+S zob67Q%+zQi_XR7O`jZa zW`yF=4@;c#T16aoEQQ>?yw^+ATPJ5ZY3GEJ?3QNKF0dV3YYD~j^I!s}?atX-*D^axhGO|iBc@3hHQUb?x#D^Xjyj1J;Lgm1ya)lJ&zSQEGT zDYShJA;nDFS@5a{E@z;jB=O@AT8KhW#al#qNJ*n0>oL=S{4@0kh5Swv0)s&H2A-amFHox z#dlMZA|-~Z%Jneu)5UG^;(aqN?e_JggsO39VZf8MmSO`o}YZ#BHC$L!RAkSUvG=+p^n-LkdkA z*k&}xnaloyw-Kw(!cAbkCn~>_`2|IEzAp=HY2kJ0{y30SW;3~EXf=^)4aUi9!AKRa zv}Ic*YL!;}T$@rVy5+@WkGMrKRB@27vE*voZajS{VL4Cgx&zO>2lZz84c8vjP75mc zIYIs>|4Y@vVep{kIaBQ29UNC9T{aslkM;cnRxP5uVemRDGY#iS6h#+1X}j#_jkF+K zHVq3LPOm|?zl=rSOVe0``@N+CgtptRxsACvI zj6^YG3^9ZdLWl$+GwB0E7N8&)5C#OoV{w5z$vzW+K!)N_fEW&lLP0PP5CnpPU?3m} z0to^P1_HrAAP^u11q7lvxqJioz|2$WYvNW31`z3{`4GqVgfzMjIHI@1MUfxOx_EX| zDaQ0IeMTtMjYGDmT5%$P_PNT$+ZHWtmM)pJzcK0w{Gk9#836?z%MIHz z9>(E=S6Qr$aVzjx9;{)+KXF^gIPd)1YqG&tk9Alt$?k5J%(l%Gve+2YXp)wJ$N}H-5?4Pts9rbLgkHQV1Hz z7FpxUs0w0UUJ}HA5xJyYDzk7LRE1#aE1;xa-vYB!G!x+P?Z@}RxWee?2|-?kI{Lva zL%4b1!G=Mf>*w!ylAn7r{cpM>xFT%v9aN_~KBG_?U)d4gI!4{0X z6kRWCff9ZDrPw1~B*1YT83M!$S|@4DdbcTju?En?v9VrsAU1b(5@jP*%zn>F2E=Sm>~9SWTXd-k}yjd8Gde3+scfO z0!tNG9b-mdAv-o^R0@pJi~VJs2Np1FQH#PjPjO!9K<-M}L8*SQ8>POC$wC(N0SLhV z!NBpY9Xuy^$0dtAt~=QE1B_9Mpu}SlY}fQYxxnz+BpC+RRSovd^73;21#9qjB((}Y}v@D7RaZuY^6LZpOkQH3PbNq z#(9vh!dR^Nr6K>@i}GaNo|ZMhj*Do4Un^K(@fK(UaCTi3ew{>ahZp4;c;QInqD&b* zkOl?2PO3vksK;4s1HNMqjtrDi&;~liCBtA#kNvng44_-A;a=#8oP^vByddk?cPxi! zDcu5&wMQ64H~9Y)c;uV~(gA?49ZF_so= z4GTg`3DrzGXQSSIv*ned8XMWk0>LT-AL1~evBg1RRR?3hK}0Dt*+hqXB`qcDv6kcw z)m}=l>}!mO%8>`HblxB6EL0HW9sEg4%?1jeO0q@F`*d2#GDeg60AD3Ci|P!Hjied{LhN!_lTeg{ zIO=;0#f3FkWw_-8t}U=rEfKlncUCe~Q8kdq5-aD}SZl4l!|Bus24e3R6$RIL*CMX| zgKN%iO|A4>iOAfvUEu`-_Dxox5jBw9hXVzvKg$)qp9ccd2lgFPd8|H^heQB~2m4wl zn7cR3mpu%S`>-JFvWL*i_nX6hK5UDzT)H|8LHgOGEewKKw?B{-X7FzZG2UlZy+O(i zq@c`DeT18bL=c`8UiY^lG*)yr_$~keo+uCYWe&N6bA2&J3jhcU=dePidbcY-rwDF=+9@LAjVqaW;F?x}0U%csFlsdogJp6^FldxjS zZE-B{3fC4@a-`~UobmW%8Q7aC9)VUNi?`ds0)THMKvyHi&@Y69_G_C+!}Rwd0PO^P z6d~Go$-q7bA9lwdBEtNkjQ46?_1l-O;Spv{{o^elz~pJ&G6M!vj6nGI=H~fw1$=D)^rwNEJ5r_zwtE(N#j=Q&JKO zGrlz(Lv4UL%M=+|b07K?9!D?@lC1+DxSET4wdC&UPqV6g<0;Y1j#LHd0CiFNx2pbV z)imSB(l@R>9sm#?)=!;HeWd)#6Pv`NY91n!l@y1bzP(#(epNXv#$)iW0l=$pxMN>i zUjfN)caGTrRRt6(;W(7O38Z>M=ED{3fGr0tzb83s8hgiz zJbGaautC%#E$e;8)@a2Eqn||X$=C{S<_~OCl@u}=H5aDqPyiraD@gYH)7k5%q4izg z8i2LP^=)@+XS>L}6>2t&Go3rlf>dv%p|>Ix-vTz?O8UNW+7*)l0L=wxN$`L*X5M+d z{*$n?dkiS6tFgZrd1-x`ac`Xuf>Fuc4^Ra-%@v{4 za_dfGjVb_m$^nO2MgUrvI$g+47a|-Nc1IV2S{JHS7xvDDRrx|2>cT96E)4J$+BaWJ zIy}$-pb#1mCZs^>ZZ`Y7h+uLQr|=H*v#28l(#O|1gSN5}J$LqQ^b;__h zv(2F#ml*^EZ#1B{?LSA%aXBXqdo{9B6`g%{s~cW&T{is^Y|b|SNw z24=pcm{j2rqu@bpyYUeQB@w1@hpA*0;9llE>KZVnud_ACz#3ZDzG;D>Q6&PKA>9y) z7JoRe^i9B}%3~bT*OM~Q8T>I(|rS%MA1>@cBZ8c>;+EsI;@J5PNW?d`c zM?jXVC!bG~_hA4m*p=%X=-Ct$sUZ!_6T#j>%u?dQkdEpfrQ}NEKTm&8hW$WD z@fUsh#`CNQo5Z(-?}@k&v7-{&HVjWrL*t3Kqlcy7RO3M+D1I)9E1l3{Ff9x>Lbk+F zq8%cCdVDkYEYgMAA<-siJcS3I-(Gmt2Q~-xDt#y$E)z+W@Mg9zVcA)d^7SwT^{2FtN1jw9GJZ25>Fktc^DRC4$kRUSvny2kMQ zos#j3&EmzpB*f2xo{?88(Ho!pgluPrZWC78{p7k#BA~eHg@<#?p|i>R3NE#VM`(%(ibNIcHkR>b%ni)! zJ=>$f<#MB~1#9uM;{shK{TgEh-|Wi4vY;2{t}Cpswy_lO0xdP}AQ9h%g|pwgVQ{-K z;pt;j;c$?PWds*%Tb16hW0y0wAA+vCMdIj;cy(liHn=pticOknFbhxgUr3V(>R{d- zq_!|+(wJ1EBj#{1PRfnBJy|%&7edI8iY|#(Vgw4j3N#TB5n%_Id6#K^D5M`ehOu53 z?5s1I>%)zDW5}&?;IN&H`a$`AmTnWDB6xBpSN0KR^x^Khd~pI#?IT5Ki>{xQl!HDJ1XL;hTO02i#TTXI7u|pHk`_Mr0@W#9_;jRlpEoA|}~z2i>dm zGlZ0bYLy_n{Ov?{jY4BViOV`YEMJtudxUr%XS011Clm`e$0=R`t$>0y4R-Ckb6yP< zk}*rUdNutVkHbqev*4o`ybwIg0|mS(;DZHXG-M}hv>c*082RoTI_$7@0^I`<0N_AG z0DuDq4Klz13Yhgk1OPbj3N&!AU;;5FT)~P);@+Esh)5EJOX0vWUd0PmG!l}-PKw1h zWQ6zT)x^`dT2<h!`V7w z&=hXm^x=HDp#MpUy85|ERkUzY>=;%;zM|RPFp&5%Y0zFnrv58lor}3BmfIuOOyhMQ z{j~Z|c*78O3t1S+l!nXuZ=3!lVps^iJ)eBy-J|7XWB-j3a_rB+2483aY;Ol;ZY zi)g|G)xzCnN>1CqP%P35=VS)9>cBlizAKu)BFT#|7zi^RIRx@!*0lF7vXCq0Fw@NT zrf=pIPGNM4&O&km+gGx!I$Q_I22r`+BMUU;luXhekWGS7K9uUlt9spYE}}YlaL9?} z5V5bbnLMP$da}dV{mdQzNT@C@awui*{O=*W^QvUfUB0zMA1M~ymC0F>Q;x)1+dJb$ znDf_>4@7A1z%q{TkF9RiLlKh2!{-pwy=iw9g0FZKOR{g{dzV0p>k!w+0HwMI)9U7n?J>d_$gl-9CPw^8`%-5{89@;dR=YMrH>9-Vckug zO1m=SeM&wcYc|SE;2+}R1P|R>sQ0W{L8@cIj1J~s2u11M9r?m2n_hkxE3_fAY`@SU zPf};9)`_|IKGAsYl6DY+C>o4KXjl=m=XwcDr--0F6rMg2?t09&dkW#Y zU+^Y0v;y5ZM)1Z3iEJr!B|bK`FhWKMkFa`HtW-_(X^cb|D+Lm_$JSc~N>l`753GF& zQM5h|i2XPj^hrz8^=YCXb((_TEy|vQ$5x_BsLzT+f0T?qg(13LsJWmx2TRr4eiVG@ zk`qdlsHdCu5|6TSbIA?$ZZ7;2h6#F9T9OHWEgJkv=k1*)3Uxt|x~}%@$>ZgJ!FbZ9 z=RV9Y;RWjTZL>2=T=8$N{F^MxTAMf;v&UVOF6S#!R#tlqez=&b0my6nZy zB%$Ms7KRVu;pknold+RpQsW9q-tCSaXOGtUxNv>Dc75Au>`roo58SP^#E#fmlg+BQN-(-@KyV5Mr zLdJu}wXd*kJ4eHRK8+%Vo$PBBPOf_ONg&eeRJTx6y11tl?IWev90F;`2sWMpD^log zI-CwigIsFSS(UkjVQvihJ0FKOTpM`2O7VW&J6(4Jxwmjy`^ep;oL2DMa@w8PoSI4Flvns&)98Qu*Tuph%;$2Gpn{=aBL1t|coJ25Sssn!mXYa70`y9_9rv!cs=!HD}NwmJk# zL+lH`#{W|jff#PXyPSw*X3gaz)Q*_D&kCbY$*KsAS2Bd?f26j3#a+4& z>^314u|iQ2#@42cq4Sq%@s|&MkSprRJ#&=Kc@G^f$Ep0+HfUY=QBU+N@uAW8qGhfA zr!v|_=e>Vq^-%j8=8#QtDDi8sX(`O6Ylhrhtg%~Xh0K@5NJ-Za9ae=x?w$yCh+xlF z8%idaY?>5#M!B6mhGBb`{)BKImyQ_gokKY+xIwb2JNPL7Z-?&3er0T{5M6#^Vz^>w zDKtDg*^3z~Cq)yqIcWH4Y-uf=aGPSY)5j!7GFpMX$+VtPS#{~1!(@78%U11iX%U%e z?A^aK%hTr`g^s>R^gfP`7Fv_IJdUVKCwww=Z$;7TLs-@$7JQ7;k)haI567YY$I!;X zf(0UN&GI)sW>nz{)oLd@qq$u~`+Old;R}t<|6i+CDBMSQX9mO$K_#f^I#+VeJ@ZJo zYu^5lH&&TEA>S7QDy%Ha*WVJ}FH@4>jn7 zK@Q62Y^RINA)JPrDwSkRVYesrt{Lt^NKM~O4@@mjX@_a~z2i<4=&kGQWP?TymV|cF zTRaaX9j^I%_+D8oU#fP^R>#JsE5e^S(Rc)2++J$q2_qQ62u3ghCz24oh?aBR3qhHY z2s)~jKy#hIFMQ7oVKbGgdcx-@cUT)GJrl7HjGEIF@pt3t9s;*&?xx>MS;|-h<-v?h z=3GrFy$l!on9*=osti*SEDs4isAk8+W+Tf4Zc19~H{CDMFm;#TxufJ&Mu9@`a$WtP za;`A`9{jPDuke0Tl`1_7RZABUh9525iznO0s?w%frG;D5Bh-(g6<{jy{7;zlVoLOA4y#Blf)sl?= zm6k;W!=HyfR+J3Z=3;$um%zw}=!aeOYBxV($|A3yv&m7a`hnW!Tdu zU|U{R2(z2BrbgHzWT}!=BNWc>$*z)HBC$zj(unp^+l-mn5mH9S7|6nTJnW?#(w3j7 zxVtiNS8&{|)UDZ)`MgO7*S+SdHjH5C4VL9Z#9^o(v1QWD@OX=TB0`47+3-n!K80;L z>csxRqe84I^)r#Ez8Fy`t%YSTbOWwet#gMDwi}#TInu`J2`MiBo%fx&LSR{lx9GeS zO`G$HNOhWr2W0t>KhhE$yI;R-6oR#0^*hPP?nY++@^9BZ*CufmvENvcaF&L2p4jhZ z|J$~ZGd}L2FM_1pb$Eu)Zb9us_m<(%s;h4PRK9juY~M2u70gpl)jQejC>XRpuxSnl zYp6TB5`Ipr(8xSrh$i}R)0O{%J}sSCAuRCMPKH_!CG&TdyJNwxl9t)pio=WhKC#92 z+NPxEPYsD8Zjham)=(^z(D)!{HC{?y5c}bcs?n#RJ#E7&MtHE${TT43cOWLe! zJWWnDp?}%2vS~epTdj-;#F-oVPN=J=O_Y~282D_&$p7|Ux$OwqHm*btmtCC@rSlwAkCq16dyBfN`DiH%b^Bke85vk`-7jVf4@BsC3Ph9S!wCJpgDm6thE7=#t5BY0wt!YGD8#t=k|LB=q{)E?6nfFKwI zU^E&Ms9C6l+6NN=!p%c*SR4$9L_%QR?8L>zXZMAC;Ilm2hl>Ej0{iDfb z@_mK*+X;c;LnVDtAD3DSzVpzPgt|K0aDQf#x~vzZ-6e?Ls&+hcH^@?%J80%#*dt>E zEXE^BS)d?7YAwp0q)tL6jqUKCWF*Wh9y$<7ltCpvCH*$dw$hEpct`c+eHh?Z@Bz`L zRrX$TPa8XgdYVvy^+jy6PFdd%X-SpDfuEWg6WO=qy1$gW-X8YT870mDW;(85(IsMF zP3;2K@)97^X_2f^L9YjgKx=c4MBBiFfNUoMJ{%TS!2VWikZ2Qg?JXWw9tr7^x@2Q5 zZj+F4_k=NRM+_wx1|JM3LrRzmNUJ3vRtJqVU*LhxM>YBw-d#bQLfXS`e_Y1oP+tJ* zu;0yHf!(y}W5R2i%sCnM!6DqaLT#bbSaYh&{72M6^Ksz2#aov+)G++cYvZp~ztu2E zJ(3DN!ykgAXuv}>Jagv1SAx@Qi4(mEtf%soHxUYIKnAck-)mZ0VW_7RJVDhBq9XT< zPP@%G2>9<_Yqd?yB>vs^{IUk?WUM^8XEo#USDSj^xTA>*f#MlPZNyqHx0*^a@t2_6 z$N1w}SjGO7UgJHva73E@2k+farzc8?4UD7~D3RR{G@1~2OGHp-j%&B|fM z({CB~zLg6lgJcJ7U95G+2Ke|)>&OJ!br~+300IrkYOo^Dw_DP@fHE$L%)bv1z~N?30B#-Vj>-JFl1v(?38W^CYX5QlREYDDwR0F zRbYE^P?v3i54b>z(`?%VzXh_&-UwUB6dz(UYaUZ>__c&H1rS8~?Kg?jOzM3!Bazo9 zqJjFOiZ||o{Z_&O-|UYv)aV<}o`mkqEK^VDjdI7veQ3xdH>wl0tZGBJta^=f`${pz zlgLa}m*tPwD!P%9q~L(#I^*byqy5Y`r_M$El!DrPD|m^Bcun;X>%hc zAWuv#?THW*U_+DGV7uNDy|rZcAQZKz7BDV3YZo2Gn_WSQ*3vC8b7)L5Fn>*s$P81u zXu~S*I+L1=T7rylNX)4ly!(HBKx_iKm;fg6{_RNUbhC8BJsV^^HHBXGfhBOJ3eDdbRk9kLM$3L(>LK{GFO9K@^b1`+HhNI&sIr!^?4mBuXx ztd{jUwtCoqDA7>w-maQ-5%5U)&SEf*-vM@9xT=qf&R?TM z7ME(uh;%DsBIu%sX&pzow0fegY2p^&$UFC~{nH;N+5uNxOnL$6p6oXK*FXr*2y8~L zFpCR7qgRPGj71?x(#CrZcvta4HE2pX%4Fv`c6$7C-YH>O9) znahjs7yu3;V^c|2RB`_a22et1@DGwrj`%zRmDUWpLmMd|nSqoRo5Q2YnB1s#c@yjq z#jpoOkoiWn&m_Y#6Q+dzA$Le9H_Xh}V|%0CN4)zwhgggnGSd73LcB}OIuK~H*}jzM zO*b&H5dp`+l^g}A7BvD6c+>#FLFmR#N*rZA3Id1KV@Z~5L`^_=i^5kEdo&CurTPNm z9{L`p9C0F&JwwF(&H{MKK^zZ^2?)*TSgA1<$%yRnP;dhpqmNw?&XUjp?JY;7dS`^Q z@fVUYi$h_qN0Fkb-tJ@qr5JDVqIBxm{y}EbEh8#${?H0bfo*C*MoQ4Mxqu7E)PyBZ zhMZ${IetVCRxZlqFBC44K{tQ9Vn+Fp;$XZ-K^LSjMwsausVFDHQ%L|zqcbfdF4*ZI zb&<|z`F(Hvwe}qfqR`TFH~~?BfLT0L2a*fO{vRfD3teNl4$`ZfSc?ZGlOYgqz!xBT zJJ8@jfUM6}XQU0Cooj{EX=+J=UpZM`Kzxgh9!X3 zcW+Kl{{oNKMQ0<85CT{gy?@*I96;@?19Y$;6W%U-2%6bdF1tpDrcS&Js5+K;v7^H) zgjstV2Vl0``I28O2|YkZ4_8%Op?r{5CREIepcq_`G{&#L?c6Be0oMn_gu&I2aRxc2 z7`6%BMBr$taJ+Xj+tX~(De7H)zB6O0K)>3Dr?EM_wl2<{PGg_8oR2TxBrNb4+!HI@ zaff9^!m70l6Fp`wHA+f>9v|^XLZod`vkS9$jESR|VZ0_hVMp>CHE{cd8l_=8Ljqqs z40j^}fZ0(V9=pEF$rcqbI$X#E?QY#e!-6MS$XTqHHjrUxZV0_r#{j30oo=KcX1*Q9 zpkxQ~!cAatcpAA?o)F|fa10Q<5ri`+JoZ3c<2j(Nt$G|7yuX`#qeD_Mix`=1m~*D400Ny1~* zg3ph57Qs)dyguJ?WW&X43euvnSy89#o*-~?&kt@KK~?MA!T?9Yx^qvM7#H=dEEVs# zgi}c(EUY*jqd}NeE%`z-8S+}g7I1Csju*D5>IA6a5>v@8i$?JSB4&8yvytATe$C6d z&5cb22-rCmqESUq^9o|yjdTKWBQsmx*h0WWvS;BMMfstVxGh$r+@6<~ai5J1{lAU* zTb&!}HR|KEUu?0NN?}?>6mY@E;w?YX@j}8qBn@x`C%;O40X8lR>!y-%Wgqy7N=;}r!DjDdwoW;Fxd-iyp0Bc@iDxqsHFw!H78;EI{+63-b_{Noim?`MmYNQj$ z*V);!#^P^%i)*wZ5Ho|=?8ZKVi;9UQZzKrXv2u-D1!6`Bi`6JMz)SP8pEuHLqM(-E IF65fr2?m0OxBvhE diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst deleted file mode 100644 index 324da2d61b739d9b0f43bfe288dabb59d2202d4a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14860 zcmV+nI`hRSwJ-euSiA)RS~?z0BM?(k(gFNG#vjiBa2T6ph~xbC#(y5XFbuLQlX*3pT|K7)X!+1`NJ?HGbu(yUS3ILLho!Yc(2g za)!R-#mFKE8c0w91rk)ifVH{#z-HiJ!9fJAd8HBr9L$0d9JmA(FhD*K2N7sM0|^*V zpn>-fyib4t1$01y3YGyNsNi71!E7)@sSh5*j2MiH8lLIUesU|wPAd(CxRj~jpiNaK z3$);1Lu%wPoowipAWyXzc*+*J!q=%Byp6)HF>&Qv`;UhPYXgTuVKVy=yS-Y@XR}2< zHQ34_J$02A+h~83*5)k+AdPox_YT!oEqhDs@WAdtd_KNNS&$04dxjX1B&eK&T+&Mja>JLQ>2G#>xfm@(~1Rgk8a1b>W z)&Lbe1O5x}43-ZT9DGke!2|~j4(`K6Z-Q2hxA5_4$^^AvLP}V!vhhq0x@Hy&OI8(# zwd?~D8@9m`U@K_wfj?MqAjP3}PXig)1`Iv}5;QniaA3T?=+6KG5%nBp5@bMv1TfeN z94t8aGanVs00$;GSa1M>1{mN#OAvwtez4#msx)duA||S8X0kFWA|q!eA|wM8P=Eme zFsJ|p7&usP@SYv!VS|ys;z^KJCuv}~XO3BJFAg9QgD z?DY{I8gIXuSukW1;bgEc{Y}k_`mo5hp2_`jPR~4LFaZS;H0Wh8!B)`VV8KC2%Vo&$ zNn2mFDVT-Z>8+b4XrVXELi&Ep&AxP_plY1QKMRNXw%< zOvy$dDcme&u^J&?DepeUGq&Vibi;nn_v&_G@EGU`AV6yY1_uicP_xEqazmwL2;Q68 z9F)aB2{q(lgk8f$pG6H$DSHTc5*fj9ubfdv?>1r9_2fP)J(1sLFi1vgXxIB*FlFo6VXfj(Fu063U{ z0tpyY@Etf1L7_kNXvhR}k@>2O-S8ggg0A;5lx~Nh-jxyeAZ@4WJ;~RVUDCG%wwoSa z;T`^JNO_H$N6|Ms$Du&Kt<<=&Ni!-}RNu~c6&;_QiK0vLUTe;Kdtnhysd%pa9pPP4 z71|0b@A{mM`eR!hf`77=GQy#4RnP~G$6khnvFI)JlE``x?DDM;9wHFYbVLf(h1hNGSczl~^-UOOFuZ@N*dn0}BuY7RXxl3Bq#$P&-K#a$8J9^Mx&`to`D@K;qb^5ZL>yR;ik{ z(nBT*Ww4LrSt{rPNe6Ci59k)eAthnMY+5ldnR5tkJBBcmO}9iVI_a=4Sgs>-eL?TF zL=->mKV(e??>?ShW}J!2Fw^(-Tn#ZVw$!uYaGTpE{cxWhl3_ovGTa1xi%p9~)I@UZ zs5G2V>Nf5?uju(fI(XF^!aGr|&N32RI6QNHRWOEfEyT<&Je&w}-zh9iGx3tJGW8SM zv@M+Y!+)V*d55a-0fQGCJ~ExoI){vhmq{zH$%W%&P7+&Z{^M{&NR2IhKJp@g=07Z_ z6fo-V%>D3tN}Ff|vRv7!xD&f_mi1w~lDC{lt}v-)-5Ux)(hSSkOIbSn zTOWI@M$o~dDGCl{>lH{_yyiS?1q-iv=4Y4M+A;vht<4x-L*kzP-^m!il+j?`W6DND`JH z_w`Nsj!t-9cg6{NQKHSO=40Vj!d<#b3#-Z;xgUMkX}I9L97xXdth`|#e&FK0LeWC^h}6s@u7I-zKm{}4tpy83K2lVT#~LQB3QdSJo1{f2SlF!q@jvGlux#8!Yf+V5ELZmBf??*MsUT-`Y;k6`ws2cCO zUU1cqkdf{T5gn{XAEre@R%T(W!f5tudse~AeHnA8QyhIlin+4X!lj2lPx!~Xk^1+h zan>h;ZcS;obs^PsFsmc(Ks--LxGW)J!pNujNjS;wiDjFq=v3L{utDEh65VwJuRiZN zT{xBd5@RTQT`$%;-h*asxhyz>@oI@CV!U0`Mr*NDHsWiBij-!J-snp+1q)5}%^8wi z+joM>r8dPDrEmKmri4W3quYu@AuU0vdIPOZ8*`4}xvhDil#4pA39VUj7hHBI)OG=7 z!`XJ2ee@;GJpMSjo^i}#qRAM~{Tf?H)3#PlO`hQ4V)QXsV zhhx;SE(y8)A3E3qQ$=HkB~4Pwl#+H=YY*+-MwLc<4-OK(Fa_Bs=?KBjkKK{XE$9}? zWp0om&&64oi16-B+vQ7?BN>vGqE#ib!=l4>By^r(kl^Jg#2>aBH&E(!dHrorZfJfA z@r7r2is+82B&RID8iFUHh@a~&?3Wr8$S(sHe}tnam%ppL_>HiwWz`4mo0ADPTH1o* zPC+Sy@MO>kjx4!*!-TpoVQ_fZIn6&SsX{|98Kp!BzNGrJT^{|^;C^><>}8uop;Ag# z>F>2F-9h{1b9QP|uTC0HAGc1b+=0@!D^#|4+;l+%4pi;9qleX@1@xM z5Xv04`u|eCmn_$5lri2+I=)b*h565F%V4!g*-a73B*FMbO>2m3?mw+>9bBfZ`Yf#Q z1nGYnX>N@P$euo=u03zXWsyo)DOUb}6FkKC1gta51XE(uFN z9zl4;+Z#q3*%5DCOghmq%#m2$SgI6+o#wbc9CFAw!75U!ci zMOUkX&gF#6tNLnh9+gMX#fg#I!j@dHo1+V#dO!@%k z-+zSkWpTZ1Ee#HZ^6IdM4Y}jRwGO6O_)05sMqx?2OcI(n!^CMT5qGI5GQteW^M24w zcrX4|x}>l|NU=QJeA4D1Emc9wEl=B4db~^WvUYIOLNT@2hph6&?_GK*Qetc7l+dXU z4nbQSPH_Xvn|JHggvMlKy+S+B4PCB5zbr=>M~?NKDNYy|XhkDo;XPnbrf@hGxmJNE z!_BLSXGP^mVj|v=CEiza_QAd@yf?2Vg}Al)#-0d)dE|RmG(zFMJqn$;l}LtO4Oh!_ zv}C4cHSw%yhNC=aBd&LGs5;!jn=(gBW@;w9H?Jn1;_}^OLUDnugBU~Qy(``uV>g4%F3qgZ8OkG-;P#hKiGv{ z|Bmzd5FgSfvOm+oQ*k#1iyKIM?zoNTQ5}1(p!vtr&@rj1ln;DFp?9kY+MnC^s1Bk+QF(1;ol^Yfh1-N0uiH7pV^aEI`L zIFJAU4j8lq8la%T9*Dq$i%+02q(G5TySL#+&WeXAz<>bKtb)bBwgUtp82AFX;DKP^ zU;zd&z<~(>aKM1USKuCi2E7$Dn1F)r58*2i5fKrgfHqJ04oJ{oF~ETgaG)7*pusj6 z!2wcAhU@u2gNf#lHdT+pAslhSv$m>i-t}nuZVy9f<@Th(qZa;rrn`@;DVsH8#h<#U z+R%~>zWgo5qPNd^$>61-YWeF!cUu7m8teoWkbr^>SD!%$3pl9b00jfMKvRGL0Z1@` z1R0pXx(7?a9iObcX4XXdPF{Sq!$01cfR!9A>7_xjIJn^VgyYzqLz2Jra=p*+<*4Ce zH}|-F)wVY8`4c`k(?&Ls&eVC5@5|1H8N%_n%exYf$0`Zl`rVsv8D@XJYmzOD2V4$v zb!oPLT1&Z5grySngOcwO*I^0qVtTMg8eY5ORLEy1-3}q=7U3d1PH5Lqzgyb|mks+s zia5)AqoY(T)^x!_uPR@NKgpoV)*ja?uK3e&H)7><7ziVn@q41Hj{$49F(bB>shu1kejq56Q zm|08H#@)551ebJY9m<|yO@S-4T^VD+qtB`Ce%=v7U?Lon-u36XlgyAfS6rFmD_4j0 z82(-vAx!N(@r2rR!?KxbqA3Pf)=IUF;AgdQ{5->$LK5{DHaY}+Eb1v{ru|rP8{uWN0*{#OfwiEcn*bHRHNJ;}TJ^PLta8&Sku6s}heYoT1py zau5o;)hB_MFM`H8(BGGVZr!j2XM#@PG3)3ij4RcALk#`#to$b?PCmj6$gU_M zZi3uXT^uI{$0WI~a@9+PM5tqEI}9Y1L4*)O2q8p7gy?(|7l0rb5DElBgqa*m$_Ep` z0L9`!h$IdOgTYW35C#InKp+?l1cHG;Fc1g?g970|5C&p|DnE;KX<42+0VcV`RC1kc zBfW2ch^@A1j1VAT2)1qvevzPZdo`kcB6hZY<3ZrDzgeKs9GFT;HfaP7oIwq*4x`+` zW82r=cqqtqdsw=S^xg!#WW=hPN+Z<5>?Q=Pu=A%|s;mHWmWo=tX%qoK&<47bHkBSY z;XS~uOpFNg9_W|?Yvh1#|ZIlV<6H+#73ii<1Ocm4X=Sl zddY$kCXz)fO#b>)6$ST<0F;T!AFn^UfT$7*Tw9tn0@SJ*`v9KWI$C2&hK0)qz>z%G zz5pbSVe1cl5&)6nc)7S?TYq#}9MU+9b$tE#}wACg;H+u7}T05b)$5^$f_p=jVx|((&9zi z!1T0~u>x)F_;VbmEjRyTowjsP^!sE|q3)tV1tuP|~gP`7WjKTx!Ze2BF zAUCLnO_C35GR6fa55caC9)dU+z|xG*0y`kFEu%-kLPFV^(dpaLYRijpUNyE+T{}Xp3j@Ea60Os45&>XhRLl(jrL|LV$>bk`=YMfL;9aq-!YKL8 z)M8tXah~(#t{g&<0>ko*nF3{Oz|v%#_lDOc&?_fswj<+{02xcLlyOnean9Q(Xh=s;%q zEHeD0s?ig~WWQgN7CubJmmDT+FTWE*b9^t8bepH3L6y%4*mxk9C4h-2yq|4FaH$ z9dCiQ;AJ}wZs9ZB$iowb2??>45A!QoO#QPP0yqhAC{Lbv#KaOuA(7X*#R=Aqkl=)Ob@WS&iKDe=ogkqA(O#o^AC>BY1a||F8 zI4*~8_XomKyv5k;iH14QC|?d=H%P6}jX{QxUf}Ww19+S}gs`|1&xg%tD3pnq-*wOE zdwHG-c=8*~W`GX_mVl1ruA>NpqFz!zMhb}fpaZ&k9CVx%(KII;A>kqcd>fN*Z3b{m z0dJulPUb$IZAK29CsI2krQA11w#By_C}jMgf(;DrE(Ad9ON|$F%h{2W%#OyQz;X!k z$Yx3P*Prfg8c>fK?d|M;PbkXcL3Yh{>BC6}bxz8wgVoapr5uATJ1K7msu|j-UkB{$ zNqMBVKXiqSrflm^%6ozcCq#ejfSo-lj|8`4SB@_O+j>%-7*rKHA1#yhJt+?W{^*Bb zRg-J#NqKCKS$_nflIzDwdDUJw!Y5sFw(H4~5)-Vb^t6=s4G~sz?Tc)uKyfZ0yT(j9Oji%BZ`0;@qi zkCSp~ZtBB*Z(ttO8838}0sPqaP4PPffF_(F@muU{W)frs9+^r48L$rHA`W1nrihrM z-c~bKHllp^-+>M&(k6z&bj6=FpeXwrxJLqpCF zA#IkZIeWuV89M`v&LJc!)@B~G;NL?C=s^pjiQ{I?k##fPHapgaM9Ae)E;!y0n?D5M zrqU@$dDe{u=75HXBZDmXkBTD-z|%ih9@i3Lv-cE>GuiwbL7}feyD+`(_-Y zQ-Ca^T9J>biz`?q00OsoOMQm`aiCH$O?eTx{lU`p;?wcs@%f}Q#}CflALJarxFo(v ztnm&nwkSb-E4$x~2i@#2?d<`kU=Vb(5eqW`!ZciEq$L?}%cwI%pq%+E7hq!^SH&K(7|A#luUY|e29GMBh~7X*M}F%@+2 zm3uL}`Yc=V;zoTjrF+q+dvUmVF}?alHSk4A?!%s%9+u1%^Gh2@puKEsPAln_Oma>P zz03^=uOcun+8n|PGp{mSO$xkM)mEC0>isF2z$A8|$;=>L`hh6M8MiKT?)Uh1=&yx# zmo@WyvHE&3UDxZyy646H^`gLe805@*NaK3N+~lq8AONUaIL^mFF~cZtI;bHSvP#Xk zMAub_jN**DKr0fc?E|XR4o-`}A0QZBkAc4ic7G9n|1$La#dN+U>G4uYq)gviKkci{7R?oa?s^BjTV2!;7z7Yl5ay#k!Aza13)`8y5}; ze}!}>?tMVj>BWTohwFtHc_oKRq+ zJQ{j=ZEHl+RCPdU)&M|k0WuDN-KwAx955m`smZn<^RJ>dE)R%j$QqS`Ejjc+RvKfIq>{mzROk`_0B_krl)%MK zpZkHf%28Iu;+yj~KbaYC1-H!El|PorF97EaK5|$ba-eElrm&-57JCjb!HKDL#!%UQ zSkXX&Ru|>-DURdWKbX{j^+>R=p~%}$^uBSwiCDuEx{*-;fD8icvNk2I+|qTH03D)m zjK+|soqonq&lUznl4S>Nz#W*4-iSSbvH<|0%ZnBeCe%RDA~Tw|-N1NObMqJwlOYJ$ zQ>0GIz)_GukfshX9pfE0xXEJ0=10i!<``Q%mZvC}mKNKhjARG&W zzo4c*ZfnG@t6!hhhW%b1@q8EnkYkKQ8xTptwAiX(!N~WZ znhDsh8bVf}L2!ceIHlxL%xLpu0xasUn9>t(B3G-Qp7mxY0MT@P=UaD^{O}lw$JAD_ zKKh%801kIhKI@L{GNe*;fHA3^U4o1zpvmD)IEFqd5!fT5hCKS~!;7VF0)UuJ<9{}-vD?fT_7I}LV@Z!GBt!8-LuVQfgvxCgGqrZX6#=S+BHR&|lsO?hx) z*h7@n&7dP^a*q_D#9zk6se`38!AgbN)6>jc(D>fzM_J>pyy*lcLIjrT0<&X9X{ANGm_c@9(_#Ft$Pb@`SZWWyiTlKi9(h0a<7&-h5boBB*{cdH`b;W4pJKCtH;pz@ zNmFz@)6xPR?_F1>vTWF*pyAtPCwHV2=Niq_U!T@q1FYbZ@b z8n@jRAD-wm#7M^ncWfcQ9h-`$(3!&}RFd%@hzOzxbl(0PFdox*CuKqfnXZ(~|J6r) zO!;dQfAju8P|JnxZ00dEs-Vf?CFl?L?6_$&Pm){MHf@Zq5mNVIOe*_m zE0+xi{A=s!bf?qQ40YcqLTb$Y>)TP zJ^XwiN|+;TUeAe!#=ep+6V*?&PK=%8h;V_0?Jn#lStn1l_p3S9*Fvc5Q>)EHJd=FVwkv+l&_?)#a6~7*$037* zGm=5G-A50{WD+dfd3ipB)}V z*(ub!u9+#s)lG8tCm4uWcsg?7y?NCH<4#`R z+rseFd4qH7eS2X%U3@F&kX3AW9Ge75W-HQJoA@7&989By+|z?GH^$Rf{{NyhdkuD_1W1G zt*_PxYwXUIt}9gsozs!w~VVdYOK=a%;=qrLBXZd*l$k*~2N0 zm1@riLPqj!PJ`J!hYvPZQr`K-xol1efzr%h>B}{gJT;UL?cV1ddum$xdz#cX7ISas zCi}MW+i*F%Ls~6aS4zp6!jMrY{OTdzX+5+4HMw}WVXA3xo`0gFU|wh_d>cAha{jc) ziC;C%@gg038pF1j2B~5;;~g6tuegBrMDsC`6|OnincRAkx2pCR15TEYh;8SDvY?#_ zbh^RaLrZR~=t|aqAC727MO4p1ZNSeA>o{jYRDJYHv8vuz#A{E%PNO5S!kvbh|8>od zceWW6n)GC+P|@<-f4}q>mKB&6Wkb)fOnn|2f99ur6h8^?%>Hb@5Rg~#&E%V-~eBJ#%?6dcR%Higc#TnECk5H8Y zTW8&~dMQa~?eGFmob(F80K#kk3%RQ>EbdhAvU??o1Z z)qOMGZNWB}-Ru;h2!K7I7* z1XEu}U~e4jHF-)gG@Jh)nCB`vc|;R7wTD&AM-d)ztETrI3dC@!NHh+ zw-Xz&gd=zsPwcFZVLlMpo|I)B7ee~Jl@G;f%U{q?^fTv}eS1M&W`T7*a46@G!e)4c zu))G>HGF7f*S19rSEz@hiq|~j7#b1S`W7TikK6iJw@|e$>*I=|x*c0u@GFXK4H2>> zng%$#tq`Wmn)=t1tGS)EFmKjt+@x2(Qq>du9 zXMZNuqi*Ht7Z%?#h49ll{p0{kd=DV(8U6DUS&=I+zfH zWI-rp3B!Lj-fY{Vh8wH2Aw0hj^bRB2&fvo`Yg6qy!(q;5hT$cumO?zHA`UGS{gH35 zLuLu#$*weZD`;U^b``2zx$nDejW5$^|76JCcY?LcQi#!zGQmxv?mA2dS^w)%X`#jH z=qV5NZeuXjJ_(8HVuB~grimQhnwXd0!{XYg*;e6-QFZxvz*Cb5^5{q`rwKbqRYVP+ z`f86Uv>`fF@?qq9Lf;;Tv5}Qd!mAFn&&D5!mg-Ox>N!FWi?m4umkT}-co96yVTpo! zo+$F4e@ypO^CxkeL7C*2P>AzvD-TD=_>cmhT-v*M=tDkFrMeUHZXcznpc$d2Vl{a< z$i=i1o@u?8t!vH$_h+dS{~hv{s&Z_2%HV#l!&1!!GViL>s*~`c(#1XPMJ1j z8tN$&YV!LV)tQngISrxSkf~17UId>~R2`{gDrbMBXv`O#EAf8QCGv46MolD@QdXw7 zT*Sc(f$}CO}F`D z$@0OwG~j5N7TW~Un1y6c@%r}4@Ikg85&f7?BVJmLQ+8MudtVrXXO!}DW-Bj*^mI6L z8p;^Tq1GDn5pj>tr==3d$FgV;P35p38RE_?Fp9ougAKnN@@hnN+^C&OW~lQ^+@5lO zB0fEA#3}A$VyEqypbet3?IWH+rj`>r>4Ncw?zM2W%uzY;d#GrWrCWX_UJgBVvo9Ht zmlT7LDM>M1=@-kq0z+=;hTy^?8vbJ|F7h+CLO~lPgUKjqd#RbCh0F)duVbYfyUtz+ z8fZ2%428p1%Lu4Ehpnr_>a`0_nn8b)1JoJyk1tQ5aM_|Va}eQZV_6Q zz1(zro(7%}m^NK}Js9TS^_ThR-=)?3M-WkQVpMP|dXT$%_dXa?%qA2Kjs=OSOC;+s z;k3n+up(U?!WCZi-7;faAeGeSm7 zJ)M5;%bYsh99>QXo1pD%p~hd-OQxAGFFj;@*g?+=zY(e|giyrU*>ZKMVT>O^C!ii? zMqlr0aR1xkEf4RdKd-$(-Hs8(wsNL?JxI`P8rcx_QdWm$xgF1_9VfW_j?~ie0$YbL zHE+|*t(jzI-t|F3W|Y2Yi@Dke9yL;OhC<`QYm8|$B8o1&><-J}CeI~5+`6=w zg)qU+Gs*ER_^O(*$_LY(Pw7!vL{+oN8dA4AT4gvc*;P?mvs6`!-i3#dnJ`?x z&FN;=6)9zKvC3F}hqA2>^+VwVi+q&PKE;WY@cdBcsXnmrZQ+I4*L?k<+3-c&TOISqSO>yS=M@`-YKV3qs*Y=@vhme|idq=)Tvs|&A3F+o$I>ETi5 z)L=oWrXv`^2u3i1gS6NEm7wI7`E2$uwf+9r7ua1gp!)~ue$dP-#0&k!ltDr+O8uK3 z@-x;j1Ye^t`+*UWI!D2~$bmwHJ%46@IYMm{YOdtLSV=3sfWa&kFGO!PBjE+gLkf}M zyxG;G;50TNH4%DyosqUjr5VPJA@$#zPO+;c zg{pCbBZeMcw-d#~g){q@kRee+f~$AbO;Q9O6QhoiWarAqU;!nZgsue(%2UGC5lZqz zH^aj-$ds3u%_8?eszMo2{6XqseWaEg|lP+RM$gWmK(>eqN28EC_a zecI!fyB9tqQ?MsLsl^ZU=_gz2f#cp8RXNWZE18EbdN@?|IUW)kql2@3&A+s>B%VVE z*`nDl6+CC{4f|EYk@fX>m0DX8n=nqLDzMx#Yp>K zm>q@-CgwR73XNxDxMpsC`R_6vTZQG`LATLgIQGEFuFj+cfY`Qzf66(ox<>^c;WUh!Ya1VmHjv3o2f?l!mT z_-e0*p-Q{oeFEr}vrt0O^l{Fl;DEDZU7q)%^6_ESkk!n%x)o4vSpa!%pMy1UNHC6dX9;NY{n?1eR< zt7n%&E)xp7vTK7!s4{d48Doecgb+hSL`0-&526YX1R=mcj08bvnNklDKwwc0V<3p4 zAdEo}0U?AC0Wro9LIi{mqYxpAkx~yljCf@-+lg{XfU}IVh^$`$4nmTG_r{;MMNZtH z<+5=6dLb%M#yPyPRti`f(STClE)?kWu8WDox_xLXKxM%5vjtUjVL>^J0bT5 zHZ7(krfB%1z5w!kCQuoW-g(|8xK8tF(GbT4*+3xP1q;LmM@~JEBX9@y)0V783A`iT zG&O7PI-duP!5dG3*T}ozFFOqgQo~^#sO4R5;>^IYVHo9>QU?hHSP*O}M!>Ca45j@Z zA`FL+!cz4T%)~KHp<{SJYT4BzGZRougR_&!fXl9zMR(Qr-a4%Pxuvx`Z}KsbLcy`D za55e-S?Ziwi)_UUy*WHMozfL*ZZu561MYN?N%ruD5e|?ll*$g>hlpldwc0vbFc8%U z&U{2+Eyjs8M%L+3P^X=v`y~CBp`?_NE2tj=i8p77+y^>oo6#YF;=STX5MfAsws@3P zYiu1cHEIFzeQ$J3l>urkP_q)X5vwvyXK^5-%;Q5H@7^bHLEUouK~S4&6=H%MpqU4lNpz{`w9*&cpg40cTxS zuU0tW$8+c4hKw^qw;Oc+_0X{5MS!m9$4y0a@H+#^b=d#j7CkOr)uwox7WWCX6D~7l zKsiro^SLF$PX&YB_Y&u%&+Wsae?{eGXiN0$Zukkr=USAcf~HcK$wuR0VBee&gX9(P zCtg!4M;Hg6TEv`}%D)8XCSx=o2R4=hXq955$I2LnB%6=C;1LL@TlvfOI})lDU2GZR zAmF{KGH5q3OS_FK1YMQ#-4-Tla<4K%fVN?WLk+L$#P}z68e_Sejs+Sv0T3J*E5)l( zoXl`FZP3>&okW8LNR)X-AS*$W0N_vH3Clt@4MSK?k~!xbOAits2e0NP#t=G0kS(CS zi|8Xxk6IHH^LUN)`pXX^ z`ioyv{&@%*5<70s^(b(rYnBa^)c-89lK#>GEwjYp0)-V`Hp%rl{>*5v1R#`hg&8zb z1Llw8d#c{n@CVR7|IfSerq{P5h}U7&LPmuTPz^Ketu`J5n(!s2drvVBJ2n1}w~>R$ zJp7*<1c~A75e^8iuh8jO_PWGHYEHC!1oSa-? zB^qFaMgz46gC?U=A*gpWghOD7^qLmyDzYFeT^#Xvh4CDS*B@qlOQdcGVt31Lt98BKR>tnxD5isiIX6`ssQZaH84w@H50-BZ8m7 zgT0WYz;OxX(?R{FwqtG}U?^C95QhXuNbLt$@`icBD^$P0L7h3H_XGeC- z*OC663jkKH&Z&E;v8lvh$CwjWgK31<)?PKLrn7DS@^#dT5+hhk)qi*z3As=qJbofqY$oY{ zqRg9S8Zi(aWKo;1u>t2U?jr-P7@&oZP8;Y?`Qqwl)~WrGeIf}D3P&d`o#+v#B{OnJ zRGZC%0KnXUTH#aD)+8AqR-r7hyO)iALoHZ&+-r^h*o9mm`Z&fPtV+JAw_v8SoKAcp zs$GOyTzf-Zj2Xpc``W1iA_`5`aUTOXr?Cfbhf#?QEM^J>G+#{)UpRi|@~YZ$fjsZX z%}+E9CR@DPc%8B}Qg12+isCWhB3FlZsN+8|A1ASagMpBNJ{nnIEQrZQT(Wv;h+`ze zUIcB~>4oEQ0oPHqbrhd9i-xk(p%JYKHml4N=4Cv*M2H-0f*=6TZx6GtHSayjz=<{` z+QHk&{Z7Yf_F)>F5FvwdZ!u24V_I30#8K319>zrqZqUH?jxneakDPkBrWqHh%D@QvIzUj`WlS$bB}F?FXJQ(#t5Qc~X}5Mtbe$)en5_ zP$@1L%D*olaC`lSV2UDW^N#T?`@KuROES~;R#VFBMkNl_F=T078kWwDo+A!UfC&6L!RLQh@AZkUiYd8WshG7#ZuEspODB;(hul5`wt>KoLfz zZ^n-%Ux7~Z`p>--gpE#~LL9^7TZP-BBJ;^ZsT@9L4ohscs8* zl+Xi${VgMo^Z@N!50vQD#}Py@m6*KB9YugltZa_-^a3KLU)X-&lfvrA@CD5KuKTD< yQ3T(?F+L?3UJBqP#b}jTZl2JlQfMGo)nXQcTvq{qAaDMHb{p~S-V=!MMrkyP>n^7N diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin b/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin deleted file mode 100644 index 17ca87df93a3abb58f762f0780eaa9c4ed9c7bad..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17424 zcmcJ03w%`NnKzRJL;~bGXA)*00|ZFGkdOf35+Hzf{j}OigdErDI_Dv_Zms*(#ctPL zJ!dYtBj=o%$s_@kPq)_oN?X6GU24~swyW)aZg*XarCsf=tyb%P;%dFr+A8~h-uIlj zB?#>I`}irm=bZQQywCOjJnuW&QLVdIE8AGJA&2OT)=ht5ZIddn_)cW6kp_bs;sx}b{S!3x-4DjlyavtKCDFBLHlcZN&d=u6QrSajCa-)7^p;+S=H%*^ zUPZG7%}0*h{L@-0c^A#^-Z$rdG{21I56^hxX!7PC4<;@{vkT3i-}m6PXf~kv(&@La zsU^>&YX7^lZ##lkT(EpSdA_G=-5a&idQUaC$@2(#{x^B8AEHgPlFgL*s<+EnZ^6cq|)N5KGs+3YmrK)+fXZ;G5crg7L zt!x7YzS$R^74F|PD|Jx&r9T2Sh`bx_FZrK4|DZkZK8l$ga!NWj()^42!nS2v)cpIt z3td(VQps(+@S1DHHcX@UbvZ{QN4XYsXqV)Az1VNAqn5WvD)~N@Ki3y__iBpG%Du{W z`X0PG5zvnM>lF)syH5%>;4}BmI{OCl=W@8!`Wtt{(*;%fK`E%xJ&vH-8r{xXZfjI} zYd*o+r5h}*af8*7zgWbg(ldrOC!lB^qc#F1Y*Isl?zlo_wQ4w~=>hSqQ0WtDI26)? zR*03t^m>_}1>9p{Yr!OyzHMt26ns9Z-5*daYW;R!*zi)>MHnB|sr0)LhsO#TN^KOY zL*YvAr`F$So|yJvK#31h>wSG;D`{F0?>3Sa!(F z)4Z}_NMG|LZ7rDADhARyg0Q$wWmjYMvK`cVlje!@>H~4HdjA`jJ^5v*ucM?wEAy15 z{|x?U?Ry|>B@z}-QPB4ijEa><3&KvoPmgX@(d=5))PjCFBv;STVdujH!V58?n zr=QQhk`4WpEu(M+SAccz!-j7rDi zGr?i-EUI|Dr8H-sGYm!sD))WB|6}dfe&&x>7WMR^XCwd9q5a;kUCON+%y;GZddOhT zl@3vPBF^JC^iK;YJQ>6~joB`_qSrLnm-Rux=iQCxTj)hzVWD)Ahx8 zpL*?|UZ(|Pp59oGO&8s!X$d)QeHqRfAp-{-^v11ly@9ohoLklK6z45r``baeDiG!&P9<8BXF+8On*8fHI zhQ~030cf+05>t3 zWdno_?4jwbp1NP*u%!nSUp9*8BN!gLpXS{l&1oL|ADa`^J|!mMp>Wl?ku%A;`oXgj zT>beR!TFHj{Tbm3(b0mO2bgK~g}1n?cjqFw+*SD&xvTPB&aUSF!tI+k6O~h*(=QS} zJN@#noy+MLioX04ec?P$U;YKKvMlSKqQX1jRpazm=p`5)Rq}fkztYVt{=~fEtD(pc zU}9FG#JLxj7QeWmXb4CNYTZW6V@HkNc#ody_1GRW5;owx=6`{mm)RGN_OKUB#yv^X z_E?(7L-YR<@mGX%kEM7V=PSID^B%yc=(X&mTgtQnX2jH*_9Vr83D!6(>ZJvfs&+JO zre(+n6i_rU+D_S4#0=Ad2C?&mGDwR7dvsbb!eUzR7ph!_7F=N~vWcOLBotqo=BKb1 z-~dUvGo_g}?JTmO1r-oqGL*DLA4Xf2Qbh{}0q?*F{1*}*48%`butM|&kNBHml-QQx zwc=&9(pL-gw%~+XhL3qzrP{?RX4dmNa<4L@l|EYVIvh@K!H}Kqke*@<5nQmMuu)4v zj6*c(_Fy^pwHZ}BmMI;(^VT$!NPY23%z&XdCDlqa_EOt&SQ% zDHWFv#pBfQ$-Xf5jozccUtX%51=YsKI92Q)8o7fizB4|ey&OOu^QzyZ24qbWTK9-p zhj&Q}Tk&Ry7jrfPo>sh}QpItLD*nczh1cP`q}+hYu*Vf+fv?DfEeGaJtri){L*nd)NeE>`yfJsz+QgzgfD(|z*0dS3ZELNh*9}L9~ zWEnar7^>;Ln%)Bz2y*@ea_ph1c@|Zkwjg;ix5H>n*L$qPVC->Ayp9@*ZCVaTC&2lt zwJKGuuq~=;kgT_b0LIhfpccRYoU2-4Qq|7LL~DfpuTuT(JykIsA}n6F|Mo@wDbVu3M8Z%`3FbDTMWKkU2k{h!45 z7`~6-`_J(%k`~`NLKsG2CT5vZVHHC=7T8yD<_z-r>aVj7?t!)NSp0Ps9};zQQJ8Ns zZtKtp;ZGDhii|%tqYFtzy{Uv(*QpjM7}fr*8iB0SRI^07j&x)q9F0@$z3eDzGveL6fvpT z3I1jYCqrr0trRcxSzhR`jD+Y4%Yn_X4&kHS-hVv!h`q;(q&i#C@dxZru0!!~`7oSM1=p@BIkNIT!c6yX^Cc`#TppSE@J;N9Y55RxKMlUHzRWFW*08xx#qR~p7lsJ>GdwG;jUB&IP^ z`k=(1fV`-nOb1w^78eX)K5K7^l&ge>SRt)xZy|f0;SXjgTR*~5nu`42o^3~L zqrmQy3^@k9vg>wm&rt-oI#1)_2J1tw+9zy5AmxbOPGjySFSPk1V!ROI`_0T(Kai8o_P6j-5d zE5l&&-8DE&zL(P}@_jXxjcq2aT7c*xx(|aEwzuivCn-Os7+M^yLl*vN3!ISmWeOo%;?ID0$ds4ts`;K;b{@(S{?EpQ8(U-vu6 zfjP-+s$VSFU+*=kz9KR%qWNL5zp2S2)u9MwVc(fMGgRMhQ@s}g;-P8LB{X#yJ}3h| zkB4k%z3&w$u9*tih>$Ym%2LaL`E&5{?g>pl!3LLpa7kVYt!N?V}} zJJt-lRfO;Qe{>?ZEp;K!+xXfsA}?h7E`bt(X7NYHXXP!2k8rFUobx`;1l8O3n8IP? zgY+mH4i`UM6d3K*wK9~vB3dKTrbP@W}v! zdIsw!16)Q2wD7;^U`;k16INM8{s&;e{%g3FEjBvLV@!kmOu(X(X4o=AwCL~IU?$DU zJa`R*nIL})48|X0n;s$mp%nRV9lR?;{;y2lHF4*WJB8}pS#0CLqeHH;D%uGIaH(iT z=9`WTlYbE+uN?w~`D;9rxifO)@R3l_#A#*>Xo3FNhG4X9sN#s;V;4^^Q=r%1_MS)>PwSiAeN40?% z%U=LmlNNnO0@}bnxJ;vm^Qgexsz(cQ%9)qpw!7&nqI+RDTzpSaID|A1jLd92T%2NE zSUge`4;OESS6J!0z<9X+^XHC-i$Chb!vM~xisNCsuP`1i{xe~Dh==Wk@i2fq4jjh} zT$gw>5Y=X*ih(?^;8ANR)#lAB!CUcfl^1L)?D75sD$(B!uE^z%e)OG}oLtU|Iv85i z?X4&(L1vVrnif#<4SLC57>v*cM(HLLzz_uux{8hLr3@$d^<&o(IGlI=qi3 zTxu22`yMLo`GhvCW9^4XpJbv zgBC@*R5(CM#tnvtmb~Pm0;D*znb=1IN{NM%jS{hDSdJOqf5p|myFGV^8!@V>;Wpjv&MUy|2J*L)Nb}O zcs?1>y8WDSq(+(uy{fmX<|n z{r6!iXQJ343Mk7Tms)%hc82(1=TLW0qVDC7po8!{w6vQx)Ied2lLEoVI7h^kR*^s! ztE7$Fzq!Bv#^s}%KK109H8ty=E_rMJ-(3EqImS=FxAtRy)pXk{&&)z$d1-27aAc4+ zpf13n)aboCk{&Q{J}M>z?aM=eE3p_Yeb}ar-4H9H>GIvGRx(se%h#($HiDQ&tv92U z;;jd4bq!lmy{ug8ju|Y?NI6O?jxC5T)m`E%KC5n4#+5b_sCh?4vV?b0)rT0eD;vKp%awR~&_)WhYbwtt4#*Y~@CXHa!6w;Ht5qptiE?nS`jwve>yk zi#cgo3VoOT9`%_Btl%V+!ivzc5O$poMS8&h-S8GU;o?8Yuc~e(`W}V0cYWx4X|d9WBAw9xMcbAkJ}1u_%TAKcpkt8mM2w7?tnr| zf2H=H@-2K9e#AN5#txR>7msRBI82m-Y5AwI@|-s}tjgWa5EEJY^iR?7CNu|Fr4UdU~0USi) z!KTJ9+Dmw-ap|Utzb=_;1tQ287*+(l@(~#(&B8 z`zxAw$cn0ILukb^H$XM|1St3;YySo={XmO_(DfKl0N)Q;@uJAE;P~?IG&K1juD!1QV_7aaIO-(E zqj$=*{K+^Ue(ZH$)gwE{A#+Hqw{qD`>#bC0TCe>A)@z?>J=`c-X&ZU_i#z*U`IuY} zr`wK8V26pA9)?THOU*?+M^vEBWks*$%h4h3h&7kt_yW8$hs;?NVZP>7-^CT64I zs;LW&hShaLqQ$82`JJ`QF9P?)JjYT z*lS~`W6Da`2qKA)>j7X(wlQj6B)8jK6Q}vdP#YMeRqynLd&S<95o($Q2G78$+em)+ z!jtF@JyWEj;S9m{G4PR=>qSb{{Bac~=l4`L5=Gh&A`_yOfMw8WOnRdgieYk|4`q8X#h{YR#nxe_31u$vMIT}ODPlSpsv+P^ zeEHY|xhNw=y}Ckl&Waj|RlbndRG&-8$g^e=^6Gb4$gAOx&no2A51&=Yt1mASGUwL$ zLSB8j5c295&sWG0<7yn3=ka|tT&<(PIliyPrOJHPwhQint!HQL>dVw3&gS6envdke z%{8|c!OgX^!2t+33pcY_Eju#6yO!UfgA~x3uU`P%oV==`^3E4OpP&GvJ{&6ZXPH@72el5lf7Jc1C5fSWB>7QxN-z0^{QzAb-V2sbbJ zZXVox;v8^uI*@F65I}Ov|IG)IEzjhDa$M_U z-9Za@r7T{jiH1*Y-Fg5yGkUR)cmti71>66^PiaLol-tf4x_p zhXL8)cB}{{IEsP9x!9CNg-C6EBH>0nk)h#!zrmN| z95MO&&tx{bP#Y@w$y6vki7Hm^I<7vcc_12w-0MD!B_IgN|87n&b-xWRt?L^Ykhesz z&I{lOZ~;V+*Ae+Jy4`MqX$c2pth)joCqffAjCZ1ajHQMvEm*33FRDJ-E5UjyOG7)Z zg<}$MKjzVsLj46fz`yzHu_n;EmrV!JgbkF~+e=_+A%+tYngAl?kTvMl9M15@%uobp z58;u`j+skgb(q4T+pDLXALrDz1IGq@cqrAj<14JT9g*p33rh0Tw&RQEP}}u2 zXHnbr3s`N%iqvuBtZKV{W4_w1_c#*k*pGDun-h>wHt?QPLLHmo!9?N3jf68L!`i%D zm2{3*_o7 z_iz7)Yk!c->2H`TZu8QHH3qzbxP&570drsFtXX2G@B_5rdNnMvixVhYp`&9%Ctx*l zg1vCj{Id$$u#IbLy5k0PcF=h?D(-Yk;(S^u=HWCI_XhpAERD$u2XcCTw!s)?3hMCF zhYi0FJSs?<+0ErbkC!h?ZJfuhfG^l!Flcx*pv^{g5cTVZR64Co3!z$JmIs$wDB8)J)_F7bGo+)H)nO)bQjywrkmABdQ@~6MiMEn zs~~We(xwQk`OFwscF`@Qj*jyd5uZ@Q8d3lmI$u@w0~U2Yii5q*=Ja@GVp67C;yhEg zDyb8fDA-l5L;;A;+vOfJ9H`);#S>(NjB zXn9`VO1pE2cD3WgIu$yATY=Qc7q~*1$uw=MNW|0e!)Xwl9;HnU<70;oi>|3bSA4i; zh(t9V85c~0($#ZlL1llE#TG;{F>C8%!W-|U&R&?-I`z%}k+UUKLN}gHbQ}=wg$t!g z5W~@-eXkS-%Vtt#j^gwIi@=94#9>0k`LtlNxD>nbJ9sJj;R+{o_c$J%OF(>;PW<5l z4}ga)Mv1}%%zx9XD$o_Gs$4I|;<+#qlY~Qtj!3yw%n&IrB8tnwxVKE3H;cswvNwY_ zzrzZ+`J-wmR-oLlvt(9TOxoNGs!%#WnKB!{P^yBT(48_kJcz4HgTm$!c=y6RF;PJr zRl^Oq^npOxHRz8^;vELj<|p9Zp>KtxJIV$(@+|wGU;w{_gA*~cr;L2rlQ!?bK$Lf+ z|6prIq7jsC_GlqcvbZ|PRf2-PADrG7CNBC~wB@swcE-&mU^kI+OPn{Dd1no)qc>g& zt-)>M2=HGNgT4q!=5CPYoic1Wu7ZRJL~4n8SD}Z5_6RZIU%6B91cv5$$1Q)D!8?N9 zeD7$&J#Gcaa=jyM-E2$kQ%vEmT>l5QvF-vJrtK8piVy-(aI|iT%ggNlwjV6=e^8Ne z+Bz~UhB}wlXnPF)&xZd?BjdhHx!&k2wZ?#dsM;UO(6)ui(6AL69H6duQ^RAT3x0f6c!$x=MW(Vp>fAunxvP^E1*gIl;pmn$#c;g%N@P&G}*BSZ^#&31bta8O>MI|moN;0#iv z!doRXF%NSFIk)qJI59u|IvN1N@Qf)w_Gzw*5XJpT(FMKXTPJ-JX2u*BB0zxJzNpAB zW1_En0V_h=*1~K;BecD32zN*L{<}q6QGtLf+Z#${;LX|Xia~HBnDH#WTo4pvSF<(i z#Ye;=yg1(%7S~E(qq!E$zrDzjZ~vC#$hi{3jyxNIW^m+uk)qI%!@`kchG|EMAebGw zyz05*2kgjqv=%#Z49Iun+kcyNsI$9dn)1jR8pN z)({N7-@J1!?7aJDDs}&Z%0%Z>gxSI=r(lW#j7{CA*}rr@D@Q=rq)UtCu4IczbVtWa zsrzBoosT^r)Dpj{&5LeXsKnN>m%7I+89fy0#x+5$UEf112RW=TW-k04O>XC)58=z1 zA%=Z=Po4g?_MCfa+P~z3^|2hL7kbGGg_KjfIZ#X8a2lxIyPJu-o2kWq@goKFi;I3c zaN|a7W*Q53tvDMC;m(U#xC_V{Oh*-*nVwzsf>_9=FWCx!P{hKW|D0vvP8^nKO)d+Y zrn4~XLfBbkS-A7DJm&1AvodEViceYQ?Bv^ewCkg^>spz+z3Nmk(-T7j2zL`xhcbu6 z?MzuOK)xWZvW+_~et=P}BYU4oyW+GP)5m*~@!o-gALwhEpK%IKM`M1}ulV;zdNM8* z4(gRQQvoxn*!MufpyzkA>&2PrIh2_acjN6?!cp)-f(8o-+U?B|G?-724T8A#fwQtG z;3+8MA3MK4VNM^CREXsXec4?fsAX1JCce+c>$f zeQM$lyog-`wYPrtQ0(|*ev4?g~}&Uyb<{q_qB PKljt8JcnvN@cI7&)sym1 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin b/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin deleted file mode 100644 index 4240bb68e5f5869b74c41e80124f67be88e58ada..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1106 zcmbtTO=uHA6rRbh8hWv*$wIBzAUUYFqUk}Kw)lgBKO~FnO6Rci*w|JSs^s9I;Oe~X z_T8P2ydk_ai6_I8as}Oan<-!*H$3upO9vL?qZRiDnhcG=#&GZrgb z$QLMnslyhV3(FV?fKCOVZM9g(+7f9y@iN?%XNyIkZ|jMxohk(FRiq+s&d5GbsnF?G zE2c!&0~*TESal)Ib>`p&K~-lI zEqn~C%;9-4tM%kSdlC1h7)mVJM>-;t!|AiVlSij7{+6=MbxfY&I<_4f`3p|Z#c&k` z_x)b=?1k~#=^Z`!T^qA6Yp;(Yp@14($iD35j`w#Vx)!Ni~_aI4c HCwqPZe7`vr diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin b/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin deleted file mode 100644 index 3b3dc27059a4f3bc772ce9e62db4cf8a9a28cd74..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1480 zcmbVMO=#3W6wYk2R#0%a?yg9ME=2?{Le;H@qOENY>Y*k%Y}AOIaf?+b_*3u~?PQXy z9uy~8wSwY5D5CYIQb7a}Jcx?ai&R)WNYQ!{RFtZ3Cfn9SEz&n6c{A_5@BL0N#m(k& znkGuZ!U`R=b*wcch;kKnIb2>q3&k7P>ykv-Ytceq&3P4AyTYajGJw5zd8+|zH?TjK zd};*NiJ&4|*w=%IuNdi15#`31sCD4@ZMmm~w(?>I>~qjsx3PaauSmv6Gm@^5j9F4V0$R!p~)FCF-8^bHiDX@_I0q0rKAfG1)ONE zKI7iMkZ3sfz^^ zlz12wl@hgusKZA|yj>U&)z~_xrMW1#f$nm>Bo>#-ILkb>I!)Bwl?#>&grK*5&7s{> zbXUQOiC1II#0y2_(8erveF-!W0kK@ySdl18f`eDlx#Oci_i?R@s)_oca+Y%(q4M2= zhp7AWHpTH8(d99Se|*ch$we6lIZnc7$$4p_HCpgU2q;~^Opl>ZcO3*?kGbGO+Zeel z`KV+wKLIEEEHCGo;vn=zPMR^zOU)zk1;6OBYr&~s;Yw3hCuczFGpzQ(@h>ZAc2>+L zApfHI@#}3`6UYNaVb|e`YfI$XE=GMLTmg{2+9+kZ zK(@59hqHPlX_ny7=!kN^%{VO`>=39Sw z3rIpt8-TpJHf;hCm;|!VI@t0DK;DSi)om82+k~~NXtquAEJ$L-IOSq27InwL)-PM7 zt6W%gl~lIlqS#ZAzi>g!HPBDRC4g*K0r{*!ae8Hna9FON0r@Y(^+Eo-XnLN>L&~WQ zO4@Ot?igmJG;z4OAHU07HcK{IA+k5rjvXR@F?Yv2!3 zuVR|WDa+9`<6_y!1>wgv3Sy3Uh!RFV&IngHF6~`|QxjLo zB-7FChAgOC4Nx<#W8)jBD!!;t_Z?0gO-Qt;jGh;Vr(k%>Wnm@}-;aX@3>GdA=18d& z2iIV5O(n=}8Tm$t#tIRg1Fq|g5Kw+Bnl#|iZdt4Y)P7MTHYqAnK%*NIW7k26>miXP zE=WutRUURia$C_X)A&X*3DzY{NZdbaFW^4xy6lVYEN)|BgF)S_iN-!dENae~{*_mu zx!7LSCcC)KZW^Y$o6YuQvrUlr-spzJ5yL_9CO$8krBca!k&3%|L2?bcT_jlIoDsZ0 z2k8Js-*AgykvCk|2yzf@BUNtx3)hy?`B($#UvC8C*;94ue`I zB$pVyy}giJ7ALTWihJZ`24!qB(SNp^fn=9qLvmBmbj-5oE8!QV^hcH6=I8{00gyZr#C)&t#Bvq8yL6!}GQcEL6S4nMOIgdE+$KA!J$HrYP_si& zZ6S4IU=t4Y^$3bRmzpg^B&1G2ZB8vnnNikJ6;jI#3aKSgm9Ws}APom7FJm=vm|%7| z5cJb{{VeBrN+Twqik@iBKyavK;nIK0u5eEAH9)B%R&GRHO-$ zgdVaSYFz|)ItFy|HNCMMM00mLuC)$5Fkead<-E34ls_x1bgtMxPniwCRmCFsgEtep`w5ZUovj!OX6~ zMBT`kR}$>0Z;7|Z)j}%%ifE`21$=NMG~UHaZ*;7EqO)t&W365*z%Bi#ag)cf(RBxt;7$dSg=(Qg- z@3q(3d#}CLzt-A^$fVvkR4%3#n?x+~rGST|)!C?^qE|~gE95Equ(Mn2)bg$*PkHUp ziNn!cisr@KAN5Cby4iG4aUPogy5Y<%X#O0{Z>6_Spt;15YVe|O2kG>TwJ)G~Et=*9tm&ZEV`%>V*(NWVpQ5>Q^5MB?UXC%a-J!n~q!s0BL^Sus zNE0^P`4>AChJ!T!Q@0aMhuOrepQ0IBB926JA)4V$8?QlAPvk}adXVUi{@rK}Me~u> zm)4_sXKdE(yOzEPv9my8O$QZDp*gzqIu*@}XpVVySUDJSV+_`v`v-v33et#=8qTBn zUs8apoeEp1&{0RyXvGk5l&tNWE8Ae8erVmK+iFa{(&6O@%jOoK$?8&mvuV z#K~t;;SYXHg7~l4q{>Y6(sPX=Yex4_HHNI!)LO=e_OV%mxhM#T=(MWIU`an}vNo`J zRli0r<9htEPNLQcacLQMFjm>y9>ivYLR63XbXD*XA{g6Y3u*C%GA6hP}WzB1=8M%vt+Xq;=I<6yN8}%@a#$&XL4bH?qN-sW>z~FSj43r@W?Qy<<`FA;!n`p8FX1MBEtL&Lk>^yD1um zuxW8+_ae{=v7}r>bv7^g!?}TH6^pihMPPXO?d~Vg=(^ zFj{+M{OgQ?TmJN$ydxcN-MxP6-U9<{t{r>97zCr(E906;r`O!|^$UX!O`O=a>tbHX zrU@^92*y{yn8q351TANOxcXH~FF%Ser3y7CNn;k-KkiDGplzD&QfV&k!qXo0c%Vf# z^dH91vUZHHA)+ z*B&zaz~QT3yOndkCdDPK@X!p=A86HLq8;dS!N=eFYTDHcrWtv`g?!`7*$sPSnPyb! z)V;zVh$d+-{_kF!IBe+A zoA0@4w`1F=%{zbh%+PQCwyUh^{o5b@g1CL8UUAEf=7wd}**;w`HmaooIHG!_#q3{k z`+6Gba^eR5EXla`#t4+~g+CxSK9t0$r#%ug(S*Ow2rMtsu18auab~eZGmCpM*%{Ws5SxIHanWMR$Gf%esuyM>4mB0wp+R*o$bc8jX-(63y z%}SGK7I68BUYm6vKW>0#-NEc1v5R>#Zkom4gg;C=AJd7Ti@HLyu8~rBc-CT5HCgkq z@cd-euy`2^asbF$1M-?AGO-AukU`uD;?88ETL^~@;xQ19^-!vp)bsEg(R~~yvL4|2 z&FV67PLBayPyJ-~muPnXUi6cFcc12vy}&$k_B;rim$YxnuEsQnY#n5H90$E5RLj2C zaJzay*t@JL)9hUu%|FR}6SklIXN9t;YI+od(403^u1DR&!j#HWF+v!wlO^|N^uG6GTvt-A;hZw}ruq9I zPnp7C#7R2Kjey{0E}@A^c+&qBBf{n0D~-h6+=^c)A@Bq8NK#!&s#U?M3arTRD1uHi z>XAyiPa)UIl@(fW0!QSR3S`ZV1SxZa$TCk9(UIn^58{W~I@shd`F-3oXx-($&ZGz- zcBP6C#GlcMpyAI{^dJw&@B;IoELHK9iZ4GqmXduqkQH3My% zGB-c+o5@ofH-FyPw7Hy#pam=h(1O=uOfSxPWuLyT<_Fpz7c4FqG-T=0=vU&Gmxdj= z$?>n-j*cH>jWf}LgW+(P7T?0Q{SI2rnFey0`D?*vR6MQG8dP&g#Tt;k*~Um@1ht6` zumU7#xHH>merGRljm+-L3b-#dkp3)r9&LCOUuZkEHL49g1d26>cYF_lfD+XXSh2k% zc^atgw@t!^PQ%9RfsSRSjxh;8Fag^^GRnx`sO=r|`l;5G9YQS-x{mAk>C(j)`%+0aUQqicl{z;wAAr+(sh!p0##I{q{j3kuVJj34Kvr%> zT>D9E?PSu{fX`$e`r+&Vu%VU|P-vyx`f!gBKfJg7hqd_7e$7>0vkcoG8=V597S zo5@;oX;e59(`WXQL=;9-ClSFOa$bU*mwJ=)UTQg^9&#>1&c$Bj6kX5dup*D8d9jqP z$Q4WJL&2Smc*zk-sEgwU7f~l(Nc0W{nY`?C{D52GiEWb}zj`ZN zq&TQ!jjFXMlH@})Pu7wtv`PMj|*-apnh;o z<>UVrJ+Q*TsRJ1G^|!W6etgdCpVEW-hddBEwc{6cohuxHVp==|U}Q(K4^5hNcHb4B zCB*C~qN4EA72ORakdc%4%v>|9IAzV(fZJQ9vb-f#&9+c+F4Gusp`8#t$}(29F=Zl< zcnwZhtgzIVS%G%0SwOw`kF!Uy7_}~l(^5B_cxZ6-S(|EBmog#Z0dhN=B!c&kpgw`8 zgDlI#bD+wU!BevaMH76wx8>Z7>Bp!2!}2V;I^SUT z#u|GVR-%lpf55q3)f&17MY__*C;Zh%}736W6emz zTuh^`02%d^NttG{P}kh}9O`-^s8ZLH{=hPiM%-b+-QiJ?`cT(lLrEG}Qb<6)9QDD} z1Wi+iwWPk5_-LnK=4A2LkyViRMVRfybvCw*vOoC)%Q60KtMN|U?ONz~j z9XJW}69_UmDP1ff$d(KWEiq12a*H|ZR~}k&=b{j;xE~194!;FQ8;8bHMQStRMahE_ zEqO30UIay2`Zy43sZk!4EX9naNiz_5N;W8qaP8&J;$nClD=|vo_C&tfhDZQ23(!-Aj-u{rI~<29_z}azgxa%63ai$T(41rbNp!6L;vvg_q5dg2wHY z4FG*W5?y7W|DQ!$&L^Tx&o(SLjirWBpa!51m=F9DaFOtwvS_QJp0W^xBdhCHrG@=qnc%r0|X=`&)_W?_kh!ix*QbskWqz~A5W^n z*-ga(B6Xuv@WSL$mi|E}t!Vsyr-3EMo<&h0R?G?+nYi%~%&!PoQ4_S$iXD7`S1sT6 znM0U$y-{!gH${?ZRrLxapD5gP1c#J|P@KqIa%G?mK5Zg}cB?_Lu$Wd{GDehI)V~U? zIKV73MyxC|h@M&=@aWN};+=|+kUXlY&4s7e z6%ziNzU?z}jQA{OUzK?OtK7+Fcu0CV%TSH2%UXyXtn!$#ceOUo#!B+a&x~PBAk|Q0 z5v`1UK&_=!c3PFI(#mxxA1k3pU=&G**_Eq;Cg>WXP^$(JRW}(TqWGE@P=kPpDoN77 zKE}|W>SGi=h)15PT7O{0ax<`Cdv1IYQN5}vD6n3nPC*qWTptqjpb@vLR!N#yPC|EP^%+wA^KB~-niQVCUfL}F$TS3)&D z7O(-imR5Hw;R@%kPJRA_V^`zY-#IHw`*6~5PzV|6O7$uvDY7@@3oC-RH7xi-f;SWb zJ`%kh`ommy{_0scek}zV;#zlX^AGJ`C0O zX^5m+6PzJIVBfn8ue~aZ9~`&%tD0_)PnYo=$V@q-USbb$?gnOZqQcBHVTknk4%elM z)V*KAe=dVX1^9xD+^|?x(}E6HvbdOcyDu1*u6X0Fe^m!4j30nlR9Z7i!hc$WXJbzq zcR`Fzz}N(1te@_`{M^);4^MBNcuk=@@BIz8-4$Ne`AypC1vzi;dt>;~z^d(=ue~5Y X);S{dU~uBp=D80|x!sa!w+#7zJb*A{ diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin b/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin deleted file mode 100644 index fda99a2f9e5ff826d6e6a83f84ce8f283ed018de..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5148 zcmcIoeQX=$8TZA`N7tl@lk=s}ir(4?PzTytw@}&vra^oOTIXu}#%|laZ|ozDn)*`P z5p7p=_ntqhezCi_1%VJ00<=XHMKC(S#86k*N2j7qY#Q{R8ro8X#3m&mq;5%h?rdM| z)M@M>E|Twexx450zR&x-&+~f@smRA6*DY-x>~Qm(=0Nf8Sa4>iR;7ukRf5=bcwlRQP{PSN1co)D}>O4c^ zc?$tSdKKidTZhQvd==ixkG;TNx@SBmQ1{zaCe0bv66MJdw_`;gl3QTR` zMdk9GK9;fC_^_m zU89EeVGbc;T_Uw`KB$igrjMPvw^L;J3<8K^_I2@z{*Y{1C5n)sh{22thdU!#{u6uaFgPosWX-sik{kWOYiN~W8 z?9B0kA3H_(MHFR}xG(9(&gJ|x)19=A&~V91%42)~^UL4Z`Z%N1+euv6ocxGoqH zPy|?%rjy$aUTJFbKM;2;a={3Y2X(zYGAs1=sNnzNd5t0Il- zF;DDxblM046#~N$u881igU+>I^7VbtUoNV($=sfMdIur-X;$vEZPEPts!JvH$$l0_)vc|v26LO?_%9{*QE8$L-7RL zE3tR5Kbh*TTF34#dd9RKl@o=ajM;Ycpx~JrGi`ioCN-~dkeH}oMSEg^QC9t9)83+E5@?taRJWmLX z=VW-*gXi4HtHmcE*(y_pGxgFz0*oG1o^8GJ#CGxCckUTG_2%Y>c0YS$Z0Sdx(vCY0 zUpPCuZ{*xXD62h5!iiS0eV$k}X7;oO0yK!4kw^olSILxud`ji1loel+2kJH-{MW|d z4i~j!x4bEJ>r}mTGSe*6|!`Ug{-+$qAh3 zm!nVx*f`!SP40+UTEC{ux|HaTNs$U$t#pf3udCRK!Dnt5D1#uc#`0lbgF&c0Wv|vG ztV)yu0U<-I{Q-JL#dFV?ifHZ*UNj|ut^G{RXKKH6UittRah5)$(T$Lq`6@>*M(|!Z^iY399HJ@ zT9(V#Q+>HFY?YgtSp)_Z@KzkV#yD|HhA&GeC0o*l3?y(d;GOX~jp-CCXL_%}D0^~^ z&um~GraSIFz3A^Rj;5};UwLxz$eCm3emh^@6ybALc2V4W&m6LeD*%!67A0kkeGCih zRI|Swv+=jDM?`f26;TTfL}?(As=w2GA29M13eF7cT!v?L;Xrj zYZ;2-D27l@3YxQOwEbPhg+O&8#L##lDCp$1Km+sUqk1M)rE+gRw@**0tw z;6B80mKnO%c)PxwAN=PQY@2*?eAfe5*_viP1 z-|zjt_uf&RHpw->%?tro2waJxaw?wTQ3m9YqEdq2;UF(8oH(0R3?v?+)VXmX$d^*C zS_lU#e!EUD1`T}5X-KvX$RCPoOF%mEEDUN0;qq;LOA*L$0}js9JQ)zUX1zu)Ie>jG zU~n>kzxb3*FFSw}F5uJ2fHm|?kX~>Azq^1N2xw|u|5WgM`fJdTsYtyhk!cH^kAM9u z6A(*wLqdzC+PXUu5Yb?LRFe|%-oC{mM7rn`4AmJE!w`$bQ(`+rqw68OQB1|fZiW(5 zkm#ThL_z6VdM!xPjQwrG7S(M&JEj_~RJ6!-6-W>8(-al;P$0W3iy@emO|nkQnKA-_ z5G}XsfS;qN+jEj6DQY&KAKQrf;$n8m^&hM%-|&p`N>%c}%)>X{A+h<5;ZLqyE$sbq zUrFZvwZN+@C$`MaA_-e?6!;+)3?9CQdW|&r_9&`Bvf!CvXTf&`my*C!X*jAxR~2W- z5=QWEDXJvVCLJ@u2wSH3fGMGr)4}uH6h4Z4{!&%}SOcDJ)1<_qn99r&bXdS+Ply|y zLiYY7aln7)WaIgABH)x;tV~?KU@d`)xCwSn!Yr6%i|0`<`fQIc$a`*!_s&z?%_#xr z)LWHLEi=w2WRM8>I@A*IGZR@V7H?!$k0ND*j(*GnJ{7{-wnWQH>5>K_n9RclQ*J=G zm?n+D_c2~uQqdQ5hJSg$vIfE1rl_y(Kr8U0sE=cZ^@PyYF%|fCE%2UZ%bBf(I`9WW zlCBm5e>?>IG0Osid`QN^`d^AH?`wIi5aNx z3|=XO=hs#I8N&oEyz@oKYz6O;(71saq29T?OCvtuHez!mlF*XL#n@=kDC@3RJXRTw z$5IIhr#Oyt8j(f_kaZ}{0528-{-6y7mlSnqyK5hKe>T839hKw8=gYwqvi&13{f3tp4;&rmz@%AGs}I4X}&P-3v)F$#y%N<8AaquO7F_5U>}0 zzqlB8`eFZ>X}$l9rKsU&mu-F?-xrjVX*2c8biPx=9NJ`MScJbKAK|aI zoCxf1Y?tbeTltS}q9niUqKpi&r3@{zND=tk^Y^L^gF$*jcz~aGYqJceLs@Co5a<#j z;7qm5Lc^L-g1BMC4Ldjk=Z9&?TX1>|62dqRyObss2MCi<>x>qQ5LwSpkerlr20o`+ z#te-3CuA6;)ne}?e7*S3D|jE7_+ud)=$uVtW-|6_pwviHaS$O`G+1RMhl35DiTGZ^ z=Q^8UG6Y&sQwEpL18Et{f>kAW446O9~=_f$r;OLQkvV_?a&$3B6}j8 z-R;R$^NPfx&sHcak~?DIvIzbb@7Tf07-cHuqYgGe$S4KL*a_i+pV E2k000tN;K2 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin deleted file mode 100644 index e299bee5cb399af9d9a122ebc9fee2682a829cfa..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 515 zcmaKo&q~8U5XN_C1@YqF77t?g;JH+2ix;8bSxgp54goVuEM5c;MLl+tthor1q*X6o z^aXqx!DC-Q5Ik3%EUk!87na?b`DW(FhYCBQsVb5!y1qa5EG)N|Bx|~U3r8C&I2`X= zYm)7_D$qgqg}%!53L$osts;m7&V{1CU2oJIZ1zDOfkLmu>^c-ZnHmWPc_DpvXd5EQ`|HE^i`g3(3k8;8GI#9xp{=w~$Tc8O;K(P01VA9~ zfBk<(Sc{>01&~=*PM3gqD0~TR`Z{ ZhB(E(9TGNye?A`f&Q60pHowUhz5ykB&+z~N diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin b/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin deleted file mode 100644 index b135cf2c69e8e74211703e2103c4b988924b9b2b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 83 zcmXpm{*MX%i6pp%Cn%UPCpd-2npPnlgm5GTHVbk0 zTsmwg-94kjHV_lYK@JGX{z9?=V#2v$2^&Hmk-a&I0n)9Fh=t4Bdp}C~9V5*NMZ9{Xp$F~~I zF=#e^ZvNvws$7NUx@c^dkE*-STz~s_CZKl&nj5yi*6yR=F*LW{varWT6`w(~>8eK_ z^wGpO&}{kGC1q$XN3*r?XT3fOypQI-pM-vjWC%e&PoZax#Wed=piRPJ$-+Kkk(P-X6`{wy* z{5~|lvi|qL&Ujw!_GQ0l^w9;+pn1n*PaH*a6q;*fQ8%FZ?A#vAJCafT;+^y7`>2SQc>R(2 zx1bs4=F`8yX%-zp^UWhy9zv53_O0~FEod@!-k$eZv3tgUy=LAcJ}SIbZ-1vY@n_KG zczr1qepRQ!xuV*pg2$Fo^{3mywnYWMT0%3v+7>oNVC8hIzhLB(P~ z>nI^_k=fZn3(vHL)8q}vp~p1iBuzQe7Pe%6Otu|)E3Wye@CF^z8a(Y2m6}7|OEBr4 zj`)enb}$PjrG?M7g%jjGlB9uwqzHjuwgv$eEuyw?k14KE5NU?rZ&2YE^e`1B!E_x8 zR5j<#mhgyIgPPwTkJF+H+QNNu{X?GQ8S>tFted9TZQ(+#zsql#RCo;@r^3thu=u1q zH$Zx>3y}Y$EgTa+a69dg>6hapa{Ll}hIn@!T}CezPQYKq$zzFrTJ)c7VMp%T2G85V z2wLK7Fc1h>;QGcU%WQrtoahgA7^zP8IjmlBsuz#&Ut9S4lc8SxmkNc*`!|RPJ^(FR zYK0=?eTyYWKW_X-TNwDUL)as_?`sS9^6hwAI3&k+YGx^UkMiggMlWg$L(o7n;kZTP zGU2W8l&hn^kE(q<3ZROTfGeSvc&Tsz1JPv$T5xD@=wgYesj~yE##`a`!gZVO6VC^u z5PH$~!|j({S+hyJkhvUYk)l~t^%@|r0emJG&*8w$du z1qZ2GU~aWFk(-H%Zj@WIsOW1{eId|QbURhA0$qw(OXSp8=%+drJ>;Y$&GF6(Zoaro z{4p5A&SF`7Ra4QQ6l>7PDwB%dQOuE|k=|&ugJymibB`Ry%~|hpvx1xR*D_Dc`#dNY zi&^RrK?{MvIXlV+d1R9WnMUqY5RasDAs+PwT}~ARD~&p;)5v&?7Dt#pM)s*g^aWZR zU`5i6Q5n}#ay*T^Et#any=`Ib(C86fF)!E=Xd&;*VxR+hO0z*rVxUXBQK^}tm`1+R z1)4iWBY%J51U0_SyuA2+kXV7{(cG;R6nZQZG&bsT-K)ARaJ80-N71)c4|f2uoiu7e zR~L<%-Q6u`vFXCc8UNKm2@}3G;Q>B^VsfChEgZMSfGBpvnM$po5VMdTF=&*(E!^Ie zE?Ef*OX66PAUOB33zuEEyky!1cjImxmvLOWXXsuILyn{FR5V{xrvQ(ZQSr6|WbMhjca1J;Vjf4-EVJXHDCqHE{55cA9vPzL%oll z5{)OR@q2CII@^;LYoicZ5g(12rh~ByMv!+PDn?dnKJ<;gQ8&cp8R3(R`V2pfKCXxH zd7Vz9OKek=y7JK$3p3+rc?WRwU!S|-5-?*YcHaq-HL~|RFz%xwy< z#gNQYyzjiL6whu8CzA;(z63VmTNwHoi&p&^IKxE@B0ZWD>-mDD_>?RAif@*Z#HQkJ zNm1eq5`Ge?td&cubt?XOJQ}C9P8-Osq)exh60mS8O~rqw;y;6u7heN06IH4k3Q2Ob z2{B<~7I41gZJQb)VloWsiqQ;%4wkBod7`>xn-t;}tC*^3U7L|OSwl+eZ6+(c>9(-%Dfbfc1=nZ~8H}qC_sBIWwIW`6wEQx|wOP<9}AD4Yj z63UV;yrnIi@_?~RZigL`KX->acWWq4V=u@~K6a!#In6i(l6XF7U0gbX|4BetVTN!> z?V}IhwrGf!%sVqtO=Az!*gaG|6C^P<>`MN^I;#1Uq%>FXviUGns2Mc&gi@N2YBcud zXx1E(!imOy%cKRPKsPP}n)QCVz^g}X2m%%m=|n2-v>*K0_b{4R%_GIhg<%1@r4V5 zpBeqs!*?J2>whi2_GskpuHC=6c2Cz!zgg6^{td^nqnPRYwmjY_Y*L2lU2~|G=71m;H|$G8*?|U7QIf1D5!D5Fg*+j~@gBA|dX@r!?SvfmYFIG^L>XJfb?`X=WiWSYjHH zCJ9rrk!RfFRHQTyAbo^Uda>l3+rIr zMra&t4v6`2zs2*$Rgb=o9drPP9l+tzMe`JwC{IFEu1GSZuO4 zWDg@W#jF@a7~AlrFX|?{VPHXPc<%p~gDZZ7bCibD5bn>IRj$!L^k@t!8!y2DG!~Uj zA65d*8}3j=BgU)qmyAkfdzJZHb_f>2idm4yAsC7<7eVnwknVOIW^_xm$p$dhpzf?d z%oC?nc7vj*vad*qDmK_3%F`&VafQ6;w z4|D|sZ|Ih(+#~1C^C-$E>GIHH0)l(mPH=~7j+)>O7(&BMve`wOQD?y2l`ugI2(y$q_JC>2J``@%+W|aR{kJ(iIZHNy{coyo} zwID38wkdhL{3&?iRQ|B2PQ_d+&RfprZ&QTIZ)^)U*dZ#1Y-2H>aK*gzvhqo|TH;jr zS|FyCYdds@LRd6meul+aKmjBJlHF|1nG^CLZ9r<_KrN^ncb+_Mq6wEvP8e(!fJH1R z$J__}(_M3sI)hdbutk+qI}x&yaLUt}dEH2l?}x5C>-&jvWm)&0tu(+0*hr;iBhcd?lfa%;l*jKS-)qri zrwr)Gp`BW<+D)hkN@%>7G=&Bb|%vq{x4r1lw%}|qB}{J877U8- z`0vifcQOH`OngVH!c*jbi_ewgI2}nucY2~diDL-UoIWMvJBZ)dvb(E?v{DS}k@xx} z8cv6L@L$MI_mCfMliZ;jzw!S9{KWAa|E)L^c_)bo4*6kp=E6Dt8=wLEdP5z+U|VKf zr`AAjl#l zP%>16z_!p{P%=dOU^ti!3arVg3rO>G4A#H_7_6)=fTZ)QtcI6A{ps@>tV1Oc1-?5B zM@!}vv!Y;U8Q=@NjxDR;P~a6&3lkX%Z2`_ig}=lUJ0#w%^hGG}#Be*Ki2z>%*IHSDwy~w_Z%l)9aETLRWRE>`XwNMwabUAf{Ay_b3_mq z+V3;)_FP9YcbF65`I|KH>A{DIR7MjHb0X-K6~aUqxx?VKqWJuPSIl$)uUH7c*#`mO zhc;eyLcH|P!42{o0=5go^Eq3KD!w3Lpo(5;n%h+IC1smeApQriZ4s}7^&QvZ(oPb$ zWUn~nbAMer;rAz{X%Nf#ok851AO@)7)%Y=*0?$klUrHFK`otT-G%Tch@%eHvrBw67!7lM|P)osA zaNso9@E$Dq5yugbmj9G<#QIB(M}zf~#;!z@gLqLVhl?6Bp2SV`k@whdkzs7;6LXLc z;aWKqtR3V-h{y50UgOIQ1`4@ zz=^eR_&_u|N1N}P_=_bU-TTwP>7O3ByuYjIo%^=GG;vSIyWf58uHE#D`a@|))Jn2X z(WIZlML<9ja^7{5dXi#JM|ZH}SP;w*7gGe>NUJr_8e_K5q`}G|g!b)w-+vzjIyh+1 zn74_^D*qvBhC#yQP5ELyM-$b#=cNUBwi0o9Sb#E-qR6J2CP(w~5|h7}$xBQ=oy|*3 z{%STaG5HQ|az-L8vlGJ*-{ham`3KXSm_?KS8#+*iYdD#a7pxfoPGVZXmfBK=x`t4+ z^6#tWDxFxh#P#oIJRs=>>LqK*piNbKTzUbsR(;$l#p;s|Kr4)r$%uwz@g?2FH#$NmNGJk;E`q zbTAOk?NX!84jnb9YhxzOFla7Gk$KZ&u5-H@EtSJ#Fman9XbY~U9Og6FDYv4U7lD0uq+Df4uO*731-20@6vaNv zAMmSLO|!tUO}`y4^kutn>o&a*NXlEXJOf(ZTOCXh-fmx8IsWqH$wmV#xMEO{VD^Fd|NjKQEkrKm!UxehjogAFjo>mKw zW!h9oa+=zq&b|{q*;Iq3eg-xaBp!<>qtcOKGThK#bs zrD*EIz0yJH=P;<8#!kwu_edx-p7d;`sm1y6Qk|xGRq_xpzh+yB0-6Fh1wLY|jHZob z;QU@IN{iosw}R#QlBOc>6AD=&bcEEu2$~M>gQkYjDVKSN?Vo0@FF`!-U2OFODee2NI{Fl?TTY>&g4LBC1-Ikjfi_^60<8Vx& zk_zQ|T94efdtu277~#(%D=w~A5f>bpTni?gk80%RZJPGGI4uD=r>Le_aUejz5l(wg zor0w@TF|N%Exm`smdk!GH_n?50esHeDF|4UDd1z7B~b_j2$bYNEJWS~g{w#i9DI)3 z!t@1d5fd>Sml15Lxkiy?ET>Q{s_BXI5?QiD<|0drJ$U90NsKO1H05>!>YB%3T)M>A zAD3j1iVY^l8GAsCGj{NKPai9ROlVZ|KT7j5QDTE&Sd}1RoA+#G63FakBAl^Cr|GNB zE}FhfKADcv^iTE4WqRdj4?m62LziZCz>%IYTgNKx7EM2Zx)N1I!c`dQaF%3KH2w4P z8D8;z(4)Kn$Bl8GfV7z+XvPX~$@BwB zgeg$xk*4YRblF6WNF(uB^D;W+3`u5_8c>wPo$%P2$5jL_Ezk_h8XC0(+WT0xx|w0f z;6jL1C~o9g;NsGZ@9O|26PR>wTez>5f$`6Yu6fXR7#6XkC3Xp9_R)%Hxi}h|03pwk zn`VxZ!=u@Q;jrV(luk1zsT)ed$lf@5k1(Nq9rot{%?z7KZaPszh#<|pFc~R{M@neM zbI?#CsP&8QKt8dzmCm-r$KbvU;IqOJmj~@b10x17v_cC6G%l=ZA9&{H*FovKyJ^4N zn0I^b5;0N<6LNMYc|M?-Ka?puk5&i=3~!=<> z;I)!weF~I@6XRo!nH)9yHWa;`5Z^+fj-O^-tcPPXYaClBB0!My&3T&D+h2^VBvrr5{v#xe%9U>1ABStg- z${n|)V*o%t2{G0aN}=k*1T3b8z_~^1=76}d2B;Hb?yanVgu@v|yuh0n<({v)6D^nD z*;96JOC^s7&%JF!&F0A&2Z)d{!$^s3#If@1ns|p2DvHrMA&6&hPSEVeE(vW~@`2KU zn(4JrSOCCi_RZ;>vtZNg%UrC)WZVSU{1!^PXkM$XP8Cx>tDTk;w&dhU3vtFjy1C1c3TiaF66I8z{3(D-tW`qsxj^ z4c%#)Gm_Rv6109x7tQ*5M*Suk4BYOaIc+p&I!1JMV+d~3oV78zY3+0umPDw#$)fd$ z58}e2IXl%XAPu)$j*XkzNj!;&tZ@wDblz4y+83rd*YXUs5z<4B>H-BLZw^>#)?IDk z(->L%EMf)eREXx>W`z=RR1z$OCmbvc6oS2bC2eCS@ib6JbN&luI?Wg3dFynqn%G3i z3f1n`k6XuSZXwP2Yy5-+dz)8*%~v*Uy9C>FU0l#EPSH+`71g zA;##DVDOW&3v#Cd;u_|)ja7D*V`ig?5hU+2F1hvfO0c@9?Y4pe+I%hc-Iv)q&F#{| zeKhBn0G#Ib+kK(#<2JSa0Od*+I%3e?r&9=48#MP(D3`fcJJ|ghh!H?_uT3o7uP3k9+wA#oTF(1HI33)ZfKj%@jjg*$*= z!HYeBx#ce8w&nRS?2cMAZ%xc~6JvpD*#Qh$sgtpOn)PhD_xcdk-gXKfr~B~Hg#p)6 zZK~%~3h+`BO3dW+PE6sHk)=q0$%B_d2h~2NgDm3w#Fp)D*L^zG-pjNmyLbcYstqPu zX0UA6p6&^q1Sn2Nzr&#P_g;Ux=X4p(8vzMu0j3l`j9B`-DnecCymh^a48j<1mF-8r@FY5D5t4^o+ZKbon7>S?dCw}nZcA&3=G||{fjX)7#Q-NfV3fOr zC(RR>gqie!LGvf`o?-pLEs?AP@Qg~DuhIO{xcC?+OK9GuZ76-?89AxA6beo53b`(b z|9StdL;p|nqT%X&whC;^m7#3o(tMbF?hYbxwE+toV2cPe7;F5raFN~+c`Mw&-mr;cH{@HPSDLsa#FViFtVauVQO;tLX?Vw&{q0LN- zTGa%~DwSgv2mPUjn#DR(EiPmgR{I4nzxDt&>>5L~@D9f%YKykq2_Eu@wLv*v+O`Y- z(=}Kbo!fW4b2RrTYPkQ1;twvya5b{51y92x(Gm(Il!uj+KsMaltKgtTQ*{t56PXnD zT)eG}TL)&C$raR#_5szdlf~|{?WaW{on0$g>YaVef;GITjyc5T0QhB0^|4ri>&kIq z&7%8s#bhY(;Vjjnd*mS79RnhcdRdPx`o12vyz+oKw;w`QW6?LIxMhq$RW5?AaME#F zyo46lrhBoalj#mLY4PM<{GCX`bX_!{GMZg%H>x`KUU;amYZkMphaUv@qDzVal(Mro zh--Nxr8?m#LMZT5i?_H_W#{?Wu=5OCF3Y5!e?ti*s7P4(lO!k2<*YJOj6&3n7GKI)028SZ6(Hh3I>G8@U_gc{;O{PtgN;HVIV*EW z#;XWaAVeWA(Xeb3%@{#-tp%J=#4uB@i5vM&e8(DVIi!%9Ny$0!bK>P}mRz z3)MXhGpFuxotFMjEFq-=V0MooktII)1S;Ju+lrM^9c+!dZB$oh<1a~d7eP+!=DI&r zj$%I&0iZdq3}>Ncpe}@0`hiaC@L~eheNR zi)B!zj0-VYc;rAJLR5E{Fg{R(%2|{IvNRo5&~h}(3Esei-=_pDny)bkz}CLYVEP$M_Nu$R-Z_OEIXxR2S-Z5K_fh3X^`ve zYlE5O4KTLsM?3)A&%=iBbV_Wv8%Gc)26#FI{3`5y`KM4DRp=H5 z)ADf%r6+PD)drWhrm#0!z6|Azb#+~|e4E;1Z*Gsv5348AF;%}U`ysJ)D9@;t| z>QDHn_-wL=li;WwU|a@27?#=cw22pf*gJts@5aA)4p3~SYIym-xz)N-m>5Z>AJ!T? zX2n!sBTdVnM%7s(m_0!&Drxy2J7@)p`0+V`mcJF1aZ|`ukRt>Rziq*6gS0B!j+Pt6 zunoLz!H%aRy(34t7I;9eif>RbSF$M+hAo^-XktZ6HZ%cb3mKQN^WzeBG#8gZ9MwxJ zx@4RIIEle){j!t^9ArRN4*zgWp!5~r%)|_$w8Fx<=Rtz{CzQLHnkYbAVC7Ea6MVGd zMZNusjmy0`OMp{}J3sNki|5!;DA~nHiNU7S%85D$fOD49%8hI}tz0tHa+>BT6L!|M0L#5@-;tvFt2;PvBH2tv3N5OSC8NhEEPcHCFPaGX zhpz<7iSZ?o@`$eoCQbd@wA$NC^{?Tpk5-R4O{-_=RR5B7g6d!Bh^kkgF5E};&vsM& zV@bMjJ(gl4$iRyLm+`XPV^jEtZQ)Z;Qi-;3zxw1yagxq4x@aP^Io|@mj)(6vzGMP| zg{!CNA>gZi8Tv!C8dmU-buW|auHJIay8Cci4!`}kx?L1RY3C>L=;}{qkkxPn{Dam1 zig&44Zz<86auD;z4* z@%piVE8dTcwc9u#T z2C`JTrZ_{TYbFh$(lxVlRJx|_A5-a?tNs}(9YkwuPDom7__d_9H61_^=*OZpx5y1M z0j>FVW*=)i^(d{mOA$~eG7j;dqoK|ZqoFl_0}b)im=uJwb_)~E+Hvvzo_?2b)=tbP zoVAVrkZ=?a|8L1+t(hSU6cw%cKiIPkjU&kc(rWFEs2yj&)uFXtS4!KawLg?*MN-2p z*ci$wrnUd!TH`Q7`Hje=~r&H3NLO|f*hnYE+fdM^%H3Qs2K7+ zDG+*`*1g_A>%KhLcH%;8HWhX?Goj5m6o<{Y`>-pQZhdCm2;(niCnu5UyM%OU0Y zr;~Cp)WiA->=BKE@)#wR$NK%Q1qFN?=!>vMnTGm5rV-QhBAzqB@JAC9G&^3dxhXlo z9En9esd%|vZsD$G`!ly>MMMM%JdYR%MtvHKRx@6db?vdM5>5`?G$=U)YdGb|J@8w1 zFdCXK^yE2Ry1tv^H?E<^Y-W5ojrFcD`x3kfHw2y0ZpM9N>$p$*gc7&bgd z8@?68<2}8d$7IM^TG13j+ES8Zr#{7GyA9#Kdm3g$SRzv1>v#zv&=Y8;O%Zk#uJqZ2n=S>t(x%x_+Vm0Hv@YG%Aw&Q90g)p^PA<@i2t6l! zkRp{ZA&s#Kq7|?pz1c^bj-ZG%*{PB_DGMDTFwmx?Nt-sN5NxDPUrHbAI@Nzlu9ZfS zdK3h#`3%~04}{64@9Id&@DsNpu_g07UD$-oFsXctyd9!Vy}&|kurqL6V&j;~=>SnZ zp*X^VO>6B?N;-y|w%|+IpX;(>N!nbR>Q6%h4#|a;(&jz7MVo6?tQ-VHn|H`}btIoC z8V)2eg~S9lw~=G%n^6O?d56=R>XlJd6$O$spBd`b%dm8ShuguiVb*6)RGLf-stJFc zHvfV)|5!3{Led74#U(Lno8FyBsI!!~XJ%wxfM`G{>KqeQ3J*ev9@@f%Nx*i3 z^_kZXz;%bV_~RU2n}?`}3ZLQPOfcYjzCh!a)#yR=Eue;VOf+!Mtxg~IfpSD~LVG2Gy8!faBA;KYV$J~$^bk-2_*UH*9acKzy>Cl0^M}vRw zporzv1NhMa8&z!@3Ld;s6g-#{u+ls5_lgVHQ#>j)o(h%YDTv{SSx#GvSWs>G9cH7g zemmk-ej03}2yFq^Dm=1rg}C%o9S10uz}v>v)_T^ZQl7UTaYh`iSnpZyrnOcpk&8-{ z%mkdi+WNK*tf2N%9v4q(;w^Z`tq6%j9dCURzPoIEUxzRq8BE0zcsbe^cMId>v}vwk z<(Xq*jWQ5W#>*9*q5y91$e=i@^;kU^l)^iX~-YiemDlfu$RN7 z5yver+MzM`jVd`Aagh9i|98BMc8mmRHGz7AqVRg_`rv8nG{S)aJ|ATkMa5PZ(Pt#0 zK}eS9SH&$jH!UDBfjn}cv$>}imPW6P-$MCSAN}~wYo?Yxano(r+;GjLD|Xy;)c@eC z$%T(R_LG`DGbT=$cf@bsOnVEV_f83f1MI@n_+5qVcwLfHDiO={0#qpO?QqO#$0I%c zy`e+>y*QfB(T>Y#$FUyTaep5^1no$udW0^PQm2or$d}aFy?|80hl05??4NsC*RrZ+ zd>VbyD(K7V?j3j1j_=Tp8(^ zqnozx0c$EegfiBO2ED(x&<=%g3mSm`G5<O+)i_-NY=irCN34v;-EP5GU? zG$jxXWy$eCE-+%XyAwfC6kwu!dT%!t!auhCaK`5uS0%@_!}T99MGYhr=77kNOpoZ3 zyb|q5XkBhm~Ee8qVo$tX%)6#NGjK?@JcRVISr3wTsSSZzjpyzRq<}g{%K0t-v zN%()9r%KMl*@9U?LA_KNYckV#f5nQo<$S(zJqc0j33@c_&0~7Z0^zAdURZiUU<_&fV-(~`?$?{pOS>u%hIn68Atg|S zACQnz!O5x*3t>P!^?($BGO=c{ir7_;^rSg~b}eGQomz>BSf@m2*Bsu%M zD!Sd8hBF96`DynWoui8UvQSVIv6+s_Urr&|g`hYDLfVhw&?`L5SOp%eiAR>`ZYPV- z>Y!DGT%H$T7_=MW#ZSB5)$y}XFWVsx182~#S7qRe8WH~9+@VN!RaOOfqus;S(1&%h;ne{@IV2hrlnj=NKU&Ivdy=YKb=^e=4?T!JS zDoHR=&=A;CRI&NMHD?6{KtIyu6uK0DAB{=B6A^rD!HT3JX@vlkeuUz#U&-begiq+3 zc*_+eZP=16Bo3_<$QxAxp-+Rb;iEiCq2FL=Mp;-Bf8#kY6Yb46v4FgXav_HL_uAFh9sEsm$41Q?v7OD*wT;2t>iT z98KN=Tj3cLp~u+RX@T9-9MP%i669amH^Io-VA}fVz`*Mud8P;p@6Uoqnm>Y3PG`5u z{=iJg_j{W6=v`elHQj+9qmq6Ass@@jvW`X_nC5_bnpffR$5PS;mvA6eZTKx}p3k(^ zJY9$1)AYI{%gT_}9De=g^1St_2>~WTSL~RyvO{SW;UUlh*LC2P-=^Qal*#|;W=~#>q%f#=bDC3Ha96#+T)rB{TU{LcjdK?yA`&wW{9VghS!lP^> z6zn%Y03Y2eZ&UNV=^jx4n!phsxF3g$a-~cJ2ruEOH!=9f3LI*F1$l->ylB9Y4;M3{ z&?`nFzZtiJDccGj<|WT+u8IcXwx_mT9M0K>GUtgC#aXsI14;I@TL;f|c=MP-q#p|( z)B?lpX?49&t52PESdjzE!IuBjvxvv;;bO*)!$MxU&bn3Kp2~Sc>=kcsBC94oyz6*Qzz%6b$*;yGqP(U8n zlF0ua&s0yklus=uAh=Lzg}`1%g!ZJE@cNkc_@AUgW;x|nd)Z~dgMyFjY$cofKn+U< z(52C$@FEk$)Ostz6a0&5UJzbutIlpkBOcux^rGfF4xdEE_T@Zg0+f-)R2%~^JyLA7 zVp`>${6s2K6Z30JTKn7We-L|FlR@7~_fo9MFd+2`$q;9%E>K6?Lvg#iI zS#=JO`nnGRQePo~)K_4P#2z*>eAJ-opN<+}pK>aELy5`vB!EoSB^4fcgJp&RX)VuO z>OOfNmHG~QH(-TocEIFs*)ZPldsiD*##&HH4WAIvZFn`(0f@l*+It220jg{jhRMON zVFc~{Jo^T+?p&>*Zm9%zOPd@k};V4wC_4SE5gs3rLf)heVjAL`@%Q^ zEc7(kTP1-s+WRf2qCW7OGHYT9o&YHbaaK+khZ(dFF>N?}^4j)j_>DseN>XzYiAevD zAWRGGO#}3F=rDse!cO%dDUY8MYz(@VQw?aphF?@4E$g||@1-KE!PUGG+RJ(>)FoHz zh)WNK_TD39lv0%J9rg6uDW^AWxdzfd-2eVny#M{k?PLG@^7p^*|HJnp(WjDC{D~s4{hxREM_ObO%l$o1#L3tfkY^Cp$a5*pET#Ro z(UgDX8W&j4_zf0W=?q`)i2Ksyk-z16f18&)|7Z=S;#$<>g7l;Rc_u`F&4nG}0*{k%= zBwfRzOs)PsOrQ%}91CA;k#)}?wpwKSD3UpCt=W&UuZcXOgc~>aEzvxu- z#IcjIC*7SuwyvZ`=CaD*_QZ zAo&hf4BY9A6+?>0vQ~^NkRGW5GH_#Js5XL;8|26|>unot8T8FqJBk~Xxr0az+u(F? zo6b?!tf^z8dN$9}L4-XP;~0^bOP}Sm7VI97sRus+#aY;BzR?qBqY5>YFnppOTZK8; z=!xMc1Yz{Zm!8itdh%Atyeq&fSgmxBGZzQHqYBF%I(Q!f3M^Pqz9wH>Rh5?pJYNX* zgU`V@Zrtin-OFsPvZjISARfUBcpeeL=k@rVh07tWOZiu=1N?^U2UB~#_PxK|_Ugg6 fH!Pic@xk8NSKohX`(JnKA2+79WbAAnoQdgGNg_?Ws z%w!|Vy)y}dfFk%8TU&Qu5$pcCp|;iH`&ergDeg;s4-|@E{@-)%++-34pM5TqbMHNK z?pc1z_xJt%hN&v653r27TsO&TFyxy>^7>#+*w6wjn|TAQ-taas8UOC^I5ox4(CwNa zW1b)Nru%}WsZ_Kagc_h~dNqXUmdJ37=jmr} z=)d$aFLM^wWxFvhq4O}unmgDbdyKGpG9)(5(3<7mKkRnVgz}(IZ7yIp>~T@~+8~-8 zRg2M_h2~h7`z{xadk)QU(;s{Y&3n--@7%Tv&DCgDRsHv6Xx5@RbKZL^(JVr<_PnPv zTr~DW-aOe{gk~Jgx~9%&(7XuEIrn}q%SFYPp*i=gi4`vLJci~O8OnQTYG^LFXrUj? z}?_gODn$>7t^6XRVT$CR|^U|l>s*9Arp}FqSIVaG(2hAJ*c*eVE zPDS&kkvBi+BKHn7+YdLK;Ud>bG&|&A{KXfaJmsPhK{Ov4weX0G zhM$e*6NmPUanZ0>(cHV>+(RzP{tcQhU3oF~ENcy#`*)rHfr~OEVmmZ(*ri|Ue`37Z_=rn0QSFVgod_MtYMHf9VKg_&Q`An`lSddp!{hI8w zR_B%d(0R@66idV7u--Q{&8zlVkwT>{-)LlVyvA&K?8nU;{#ahzv3}yhJ^PpZ={iq%zWoHXR{>37rK z%Xjmu_na8=aqCY$-nst|kFLG*=9?#Me`|kb#es&cWHLzZI?D=zNL7n@dN z8@E$8?vzDk)}<^8A_1|AKmY>xfGo)-8{&!J(+htRlN0e!q_#oBZP|!MbU2sHbwL$0Yhlt$0^0B?%{DD#9)nMXAkZAa1pHMre;fa#w$g~Wbm+Fp*byhe>-ACaQDXa=-c z^cf=h3>0F!W5P%%@dzZ^FpZW`xtHd@yyVKYAOCpWk=J)l8{2ZU$h1}Otc9g1z zH-&tC>RI%wFN^ra$C@zv;~9gx!Es}mW>dm z;-MhsBW(I&Jurh|^8>An;WL8MlVRR>;FIluc^~=_doF3-4R1@~*=w&{v3kY2YrL0S zwes2(%e@z_ShI#!t~g^@O|^u7peDru8dgWcD%rfSmxfJ@wu|le8#L!m=wsZB)13YN z4oK0(%2Ev1Kqcw;_bmO;>ziOV`b16at1j2Ev+RRmUXzCXHWG)|T*Q4?ttr!_r7-CM zIU&bs=*6}yq-Yln``D5)rqZx)AcU#@VE9>FLHbbR|4GtqpO9YuR0}t2Vxu5*)`8-# z4zm#vcWLr#Wr!i0wjYIeK!IrI;99n$)oNvaQ_`}kl-gEY*f4sf5 zvf!fG!+yK#A3ynE-k3m60xLCX__2t<-8$@mE(7MrIH0wxtIRMhZe!zqrEi*rh99>T z93+iEIN*;*;t|M!I3(WPYiiu$Zvu+96yIs=v~67dsT$c}XsVuT7B~v*hE|}OPJ>36 zwv8KcH(rxO9I$aT;sHw!h0+-?d2(HJw&hhv4hcqLd|f&$7rZpO1cZ&Nhc8MRxDlV) z22S@!1F>$np+r)Yk{Po z4t_$Da{Hd8;#C?|MiXAb?vy8mwjM$&bP}dAk~EdJvg+JqCLfkF7Uh?Ys4RL}$zdm?;BtUM;u%+H!awUm>W{)AM#3Q`?VDd%cdufhuET*4d?gseF=cwrTMSs#=I zaEt+#=yC%*VT^mDiLLO`IvgP5aG0@TXosuFWbPt>j?G5guoMSd(XJsRbx~C&JYLQ{ z46oT5YqRFqVa*Yr@SK#hht=a@YrFNZ(|U-oSXWpESN<{QAc*bYD%%@TOe<1my`2b} zT`Gb-16Jn5unRjRPnSb3c}VZ zFINxElRy|AQxqCA2HIq7V7+n5U8#56PPvy;ZXge2! zYwKc6GdwDQQb)d%Mn4yfC7_9TjO`wd?bh%TK*z9mv(lq@ltM+xXKKEJ=v;5$#s`?u zPr0vXl>2Nf*2Q<5CIP}ZVGcAo60m$+GQsW@9s_EIORQyaeU!I=8PDgV(4Hn!2ccae=`o7abn7nQKU3YKpN!*r*U{PB(< zd{I8lBg6FPE#vRP3XesZ)1&Y;Hf~f^8a=Kl6i)y(%38dwRrYI*at~ZF<-Lh$Q3IWl zCkG=q6>r$fN}@6wQVbg%!{GM@LmDeFfkSc6nGBLf-vQymS2*m}B z5V-WyGT*l&7c&+&Bk@6k#7}>dB}H6_B1svFbPni;PKiNMM!DG8=7P_*JhHe6}&k>?EH;kGvarL1@My4Cp;0%c z_cns9<2H-4b=*3^AlarBCJK~*h+}EYQG+=w8znq!0>m4DY=AKy5#Wy<=bl1ckZZb# zr{LO>u^2WFx+Sc$!p|4~ab^!Pu3&7#?e2FeDOilDc1%Go801=-c^l-~^(d=P#1nqC zn-8JJn>oiP0u4PS%&-FsXb8})4Z2bX&roZ{R(MUIn|edTwjtK%>opoEmqU9EtO72E}pWNqjGn3*M1P&)2!q|%x@8-q_ zF;QR4WRUa22xI&jxXG_1@P7s;X}aM{xEB$J@hz*YB{%F~x~SGRe_m3GST8AK20AeJ zk#BKe9ew^QVG3^mG2)Yg8o>|rpQhT6D@a*n0fgm)F#F(8%H9Wy_NoJNw~+z!##uQj zcO-z_I5q~$PEh`al#tX2 zn;|ulOZl5Q>zBVPqDQSbIZpY{MAIHPH?3UpDgT{;M{Q#jv&ZZMU+n^X6@G1luU?f3 zMn)|sb*DITxcx0uFoVfmo*pWgqII-&w)dd`T{v>Q&~n#Mfo|@m2Y6{58<-lXXPC_r zpS3&?h2~MgYF1}CX|OqB&Rl!aJL!V$sZP4^=L4N|;W#+ymLs{pc;xOq8yDpsU)JJW z^>pc~qsrde_Omi2dCBF|UR)UMNiccKom&y~a0gvDW{`vK5DprE$sbp&P$;ky5d-CK zw0vq8_U7aCKD96opV~KgVnZVGzfR`P&AC)~bBa4H0I(bEPP^bv3$IDC_s0o9r4}c^L-nE+ zNmBw-=Qkk+w$*0+-{xMRsLS#$NlIo151D~_B8C+n7yUXti8qM9D>{%Sm=X$y0eR}m zt&#_b51)Rn1DvAP;1sw5fsst5s5!9D*8xBbQ&t;*%3{ECEww!_x4i!HIoh@btt}t# z>yFC%pPznoRP(iqrfxp`&4Cw>80x)He_eOEspwzWUmdQa=x}n!QVbD?OAXw@^>4^P z9|R2%@gMpL58LloPxlS-95{_j;48F(Nw`BQ&PcOIcEHJ#e)Vc(&_)<$Bg=%p)N#KC z+Jc<`(>bf_i}Q|uv+(V5<%54cUs<&0z*B#{vf_)S=YQrK_3??TOV_1mI!WF^#q0Tz zS3Q~HCIS56M~feif|LIa2!M*;6S#n}R=ADt@CBT%hH%U;fQ7=I1K{TD8D55iW(V2@ z<*$$|!3WaVvpB%;lMHV2JB<$ijofJpCP~$eu`7jW_ZeXwf$i8x5Ii>$Ked9wZmv21 zuZ8`Y#Z$l+XEHNtxdtUEcY%rmn4CqqgW46Gdnl5Iac8ngV_&wl_7pJ_RK&N4*+8iU z>6qOwfvL;1X!~)9tpsg9?wZrk_OGX#iI>K0!wOGf`M*s?8lWTIux(FLr!wxZwlx~) zYzKo9D-s7fiwKT_(}^Z4uQOvT)05;aY~z7Y9qBZngtC)K=NXPbS58TgE5c&&{J3s- zY__*#C3oi~tF_h`O@9m217iIWHPYTDu4Dk7l5OdAmr9;UZ}@DEg1pxPbdq-|d4Jm4 zp^|q&TiDx9-VEl@{Rt{L6g!o$Xze2`I9YEI7MusPW9N22Tkizs*pPy3w{(Kh0O5Qp zrLo1_WNc3NV6$Ij~OmB5FaBvwkeD8 ztNB~o+WOzx`oF!E#t*Mkyt>v>!At|~z27=@c>o+1L_fP&w-m zR%!g_=@C-tlbm(ZSOH46D{;cfApwEah zxu-i3&!sY!GX3$VAx+9INk9Fv`S$dygNEr#$D5SB8w??*#!5JCq8m;VSwCJWQ1+@= zLpA28MdU`#a)Uf6d(m1(*<;XyvZJjgRH#Sj7Ss&){tpPS1g|(XTg+o@fGjF+6tU_ci)Ud2ebGQ$P360({Fi2bafCsWk-mo-4^C#*3)UZ25YDhw2K8iyjgYSAQu!h5 zh@IGk7fkek>7xlQEzTAccIr+UhOj=;2~-e8&eGIkaNx3)=HCQXDlW&m6K0&s(|W9o zT0>w7&^fxI#sy3T;BCHX#ovbGp623(QWLI#ELfqlDDS}om*I=hgfMIq$ggOULf2~t zyCSa|le?o>QPK~AbN2IWuQzULMpTYQ<;yui#yJ}ZLP?>5G$eKhv$74WjlyvkA@!+u zaZA^VNYI99;v<-y7wK&ka?lWob@0S7Dih2oUiT+H26mQ@ z+im)IIT$Ynal5VbZt~k)zyTFFXN=_z@xbNr9UpkxIt%L&&y-GDZWqx^S`E>)i)gyF zXaGtoP=~JZY*cuYJR5U@SYU76H0fdf3JuVJJyWRFIc42SOY>KzaG=%p@mTB&^iNYX zA&Tf{-BSnLV+=NZaOECw%rR5^W(IAXZe^Q6@Ul^b# znbI+NDgz^cLPaqNFXD?JtIa(8D;DYkpKQfOHOhceM3^BfVZeITR=ME8++d9QHQWPlG>eD`pXqtXIB2dg~J@}^SfQmeGgG*FOw)?RO zJT5U8N085lWeaq&27F>0j(H6HuducJG#bIDRJ_2}^(FSH;*T25DTYB8$H*;l#Rp8q zRN6Xk6I0=@m=~mqlj3e`N0+!eAb{>qYZWT?Fh*Q~$Z#yvCT>BVRGP9B?B$dTFvb*^ zP_&{^YdEYI^uit13r)U72(f9(4Wg6%PMV^LuiG=T#}xuFWs@ZUoRi_Yh4=BiE~gGS zZS>vp)U0;{BC;t*z|M2tHTPKzoruP3`fwj-p8Pb`p$T*xg$5-37g92)QHsDc@<13# z?Y2O;9c`zPKxzhQ@koQw(YHB;rmo~i8<8J}B~}|uV+%5R`NpP36Hdjn^2->xUSv&S zHh?Cl{v;JmR{jI#EG7L^sd6+~xsF2!?G!XgQ}>9KA!~<(T06Fb6LEqX=tQu{z` zH?1-pns$aQ-At8f+G0b#X~?@fjN86R(a( z`ldJyXf-vhN7L>%EK84mi6|Tb^c$>g{^`{q-c~*{Kqq{v?GQK@ zRaU}10!vK>krQqUw4nnxk+Q6)9f4?mkB=%RaHGKUm#`ilE(0C*;eeY6dtpTFEM~Zq zro!PQ@$=M8=^ z;?Q8NkehK)1wyuzJ8r62hi?@4=07dI(O0XOz-DlNZa^ex`tP8`5L#3>AbkbnsO!SJ z)8tjD-V_l%HUc*AND$v`mgl%D+52{a4>LiYdz5(M*!>mT4RA3*t8Sh1A$`N?# zN%kI|BlnK~%dO;~(4VRR^ateuVOVY$kR(YXfDzKrJ9Jo;T(Mwb5NzBOMs+Dwby3yX zyo!mcHi?$t(5Y&dby1IXQPsoN1tdGbp#oKX2)kPK8dd#)s+yZZ3A>06v{srx9e{{y z2sT@TFPJebNHenHA^}gc{*KjQ?|ov6X5@>FICsnkLpUeJIl<%?ML?K=?51&Y08rsu z3#g35O@k&1-s~^LP>lc|z@1!70s5KIm;Gz+tINNGW^{Il>V2M@-DGFZRGP6{+c3C% zf2JO!nd4EN7N?n$y0PoFw?qvbw7y;B&P54aM}G<2j8FgV5;$J`7Oyi!X_-~|W-loT zu%O>|If^*@nHO2M6KPslVpE58vVYN_1LxtF3o}=n5p(db4q(anzKegtXc{zgw{@s9 z?-HloZ67MAl)eMhaey-s-O$Xx)6D;}cPzow1m8k&oB&~UkP)6*jV>Z>oXB%kMzBhW-E1;iiwsQSkA+!l7w;@v?v zRrd&w++SfMhUfdil9lpo2G~-kgXPLdo35~a0-}33Ofxx&!B=)_S0i0VL)G~%*#;Ws z830d>C{(i+xE31GpVQ8QBeV=SRvD+7>LfUg>uOBtjv*ey8F$A(jVZj4w&v=fi)w;F zA3sT)tS5}h6ax{1?1lpHbHF*X9PyXs@avR0C#M?6WUO@-^A5tmdO3s7Y5AHcKuEx< z1#nZ%vqDb~`hU7W6ct$Z(XvMazh}#CE1YKE05mITWk33cx4ZQiJqm)aZgdqn5d=g` z#wOPwBhymV)}D9kt-WLQk0yS4(|Pi%>u+={@l6_9KjZBB-8Cz&8;KN1QmFYZe200s z|E-B6XYtkCl4aF@{q6QC=X|_!_@aunPt2`-^|RldT>i=U1Lxd7H{WB=!l2solRHbZ zzOc+>gRL-Bo2^Cq>=5#p;6tglNMnC4ra9L&g;3^PJ4M&o4*brDUt6`#wexZ7dixeH zcxLtX6@v|G3N6f|+DmyL-MG1DmpB^ngCYC15Qy4H(7xiQ+`PcI@}2&A6SyP$DJlg_ zCBwd2h@UV~?Gt?HoG+&Rvwvvrnj(O@;7RMwhZOU~MzS^x*DBS14WTRyDJzq|ox+Lo z8hDh+IiXhEKtV!h=nhlQU^85}<;sWI#=UwdL%sF5U!L7m`$;e*4DI`c6r`IQ6{upb zL3Lqaz`E9%B3c+?epo+qKF}K+5%$U{_KJso zXXKK@YsFdQkn}){_tWuuX+i0OWsAz*EWdt2=7en%t0(?`(&dwmOzy1kPC|DnvR;-P zl2gi%hDe!GmXs|Gl}1RTq+DsVn)Nh#iUMYqtq>Jk?xXqN%u>?lpd9SCH-1@Uiz)T zgtxvV{aJcldQ*BwIwXB0eJ&lAj!7qFhnyvkkn?0@hcWRM*&}=93Gx)VN}eUpmCuyV zlFyYdgdPXwWirWEumhskkL2s+b@I(}3mAY7`F7CHo8|5DPI&P0Q*sV-x}4*jlbzMhdCtX7pYu}Za_6^d*#?~#&wrWDS6J@MDhW26XDA|mClf0 z)R|l?el|$+{s+k!H_bbQaF^!&9oEc4@;3_2dkx&1O7otK(!9sTcW55cGk*3(u>#vG z)4YA+E(qP^gJZ?{TiR3zEG-@FEiHQD17-Wg?=9W?Mnz`lvd{xN8^_+Iy!zT_yZ5yhKXOm=@-^38-F%jm IJzlE$|573)g8%>k diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin b/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin deleted file mode 100644 index 78ea0add13f517c7ec7239bccf1811eafc1fcedb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2664 zcma)7TWl0n7~ZopyE{t^mtHn%3AiJ!$Dw?Ox1cpPF`_jxTj82Ttw(a0!bIm`>&J>3iBC zKGhW47#V_iblHP_5Wk1`_n8ZMh!fIKbQGTyD{pK{k3n>rE300+V+@v#Vnv8;EcPqJ zEt8vdY+49$=lQD-LEPNjPrkm~icP1n()w2KIf&nxmWYrjyaMxK+Z!)0qrAe{x=pg98n%_DD49bxJQapc6F z%KABOlU$zN^Y1)Q5N2kWB)>6oaXMSIJR@7}XlxHm=kA_ldxD5R)D#* zM=9Sm1rA?=7%suaC6+!Cf$q4514}^OC15>BuiR~Nd|Egt3KCEfC;?|m!VGjv4|E&A zAQyFwX**r@dQAkTtTFLFJ20iE8JJ*|vb`a`&X+A);NmH~w(Ux&>jlRK%F3`nIn-(P zF1oHjGBT8cYZPpn^T}GKfF+cMa3A82GqufhN{I9myhN;%0_>{x`O8OU)MSn*(xEEY zNi(z)uj=M~{d@Z=tiS)!ocPV{WPSb5?6`i8ZWNn$0MW-$5#Q$}q^jO$;$Nmpa{-Ts zK}d+9>jHTt3*;L}OE9R%^E_FTn^i*H4NJRkQ3>@OSqXGh-0AjKlL&t>hv(_eTJhR|J1Dbi4xysstcL6|8T& z)(*ZT9x)5Hy|y3*B_1pmL>;rPsH2#qx}a%dyQu#d0+=G>%y;JD`PFSKaYi;^@7@Qt zT`$aBDT-{W&uXIN{ZdVH9tm|11)_I0* zVB?|1+Mv>cmF;rHzroUg)UxD(LH8hGNrKiM(T9Lz4ijRw)AyQNk56wMd3*SfJ|bY3 zzG%^}OIKgYonF2HGyaWcercNdqwWqy9)}MFqx#VBlpUm16J}BifCe7Q~KQmZYh;Oje?=`Q)QftcAFf0uDWJvTd<{V+E6QY4fC88o3 z^qOHatwR*rmq&&gH-fFLx&_!;NiG75EGP9=rZM^L%!X8ZQEKZ**Ox5P4obz)D9wr3 zM)U?4A!;mkh|*}sHaku2Uga?Kl`begTA1}Ifv`eN}0(vslpg}^BsrD5z z4Mt?mC3$EuDtcOpEbC6bfdLnie2DdG&lCH1&uzQw8rz^Nsfzm#V*uTgzg;md`rQiQ zEi4`J-y;tEOw-*(C#7GPfndCcdN&Ugw{^O^{!cWIO+~{!ceRcBazkP@4PpASw9iZP zjvk)Dy`*(CL*NFk8C(V&L&GDhZSLW+3^+k?44MU|w@Y_C16re0|Gd9r&-4A24KZz5 GY{7rUr4)ex diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin b/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin deleted file mode 100644 index d43b07e4d1815e15f39bb34510e77acc90ec8136..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 24314 zcmb_^33wA#_jji$$|@~QQc8gaC<3w-O3T_(N}-fB326riC37t(D6isB6d=X%0 zV~5WGx&UU*OC1LA3V^+yzMkG42r%3C_(44x(gWa-F<)N^uob{z34K@UN%k^;dBtC2 z4%q_0(bwKMT2BVm0W5r}W4fLUbOJ1@Tf7h;0XXsR@!#vofD-^`bU*3UlgsE3*2ntZ zswcYlDEPiIP*3{p0$7%NfB?(`IH$wE)AXe8hX5;nDa{3_0G!viV+z2j0Iz*%S9d+> zvl-x$de;zu(*Ry)?)(72_5g2v#=J&PE?q~#x2{z5r1#eVmuD~q4l>i?dv*Rs*7Xf@~@j(pH`Eh{%9r8n4fQta` zUilvO*g)Gp+wQ8F04W}xTe8chC;CkQpO-4Iij*$_zI=W9YJj}~?%VeV=&bz=fcxh? z`Guae+X3*s3H6`qNt=9t2eL+Z^rUqyz=N%}y{jh|eGBlj%a0cT{13om?ME&J*azUr zZm0g#lcf77c=i|wMt2b4nfA7;g4_KsKc@!&4I4f|7%xZYSeEPLRXJ316udkvg2 z@Z-M|1d~-LbeL>Pxm_rx`?iA~l=o-kh_si`@G1Py$^Q3;& zsFA;)emQB~)4z1tU%Bn&TfI|8EUNV^u5MWM)2^Zfn=vhJo3c=MPR01%-Pa%Jc=*e+ ztA2Rxsa{iWxv0mC4>opv|C=`T)>Y|#^yVD#{?)6t^*nU%zL&Cgzun=>4^C%3_PgoD zZ`F_YUjEU7FZ(3O;{D=p%`Ao_J*O=q=@qsJ;4A64D>U+X5oI73wdX@EC8H=?oz~Ze zmVEL1@*Q{2JvuQV`;|2(uG~NM$5R;(-TA}e7fjE*qwSq+vZ*cuX?2ztNvpY})jD6O zlk*HGG^9&5qf&;gbcdQd@4DuJ2Nx6{?|OxcEZ+In{3WmZZOgyyzOkls_o{`zZto4e z$Yjbsw(kw;F5p}#bE^E5z5B+LF4(fw{zLVl9y51V_k6rc`kYH1bkMeY;Gs7K(*<tn(f8Itv^y|Ux}W1k6MWw@-N?uqA)a$sXg{ni{Kf&JzQUUtV3^ zdt>WuYd`6}{oN&lUoxi_59zitx&8Yue)X(IIyELmvZ(?mb4nSVj$m?eKIb*p9e=FT zj@`~_nZodnza%F+?mPV$cWKIGdNy?H0vEF8&{}cP+Oo7({iZa|!4DCtHO?+E-87*DJZIP$X>5^_hrW zMh`yKN9MMIbO?xEpdptxlh#B10W+CByW9@CaSO$2m2--C$;9)GfgvdMfUtxtPnGlX zTT>Iy*Bn%rgtqQxg`)Go>Z*;u$eZ>&f7o(upB?$1WQ<+;%u8>4VaeF}!0eZcZV?(; zfV4iWNr%>7HW6{ZY#;a0bsrvnxNOPbhHL&?_~Ga+v$s|Z>{ejty0jrne2R&R_DXGxo-UN@Pv3OLSX z)U+oo7Eihjo)nzm$VRi6{)n_6w_^ux)om!93IlD4gcLZ8+F zQ)IHmXT&CeJT>6}^2=4Pq*{;ulZ`S~w@?$FblN_ke5%h$e>=~V6G&SZX}he7wB56o zw7qFH8?Tm3y1U$-r;-W&a=Qw8T~l2v?8z{?y&%S;8AhQmXuVn(fWM+eb*Y@&&CQcI zkBq75I3Y7#;$*8v_#vK*Lff?^=H#z1Kd_r}Byo8IwMPrWe=1n}g+ciL{%pGB#w}?jY?7n4Zsfy9)9lJY67Z8UMpO?lZd-p|wuXWn>tQ4s>!C z+9!FO`U9K4J0C8okZx))h@{pgtbSTp%Y4N*<=}7XIyvrhzj)mYzRaOPD)=xUz zPC6XfP)ACC#4;@ggO9NuMLFr#om^U~p) z%`uCKx^zR3x;bJl1-U}+-~;n93Kh-r$DCh%vVnAjPv9q)Jc}s{d;Dg$+Dis#s};4i z`XslNTvFt*s0<@&Xa#&ed0pm~!{Yj1id?8QpI^*>Cf0 zk5BD2=+nVpuNQ)mhmocH6^9!Qn)dk55)4b%kOp2?(s21oX$Tv#_Sq2SyvtXj? za8H1A>;{Ph^!1=TjDb`Kxugpykm{v;a>*NvwUvBD4R8)LzA0NSGd2 zMDolz4JniS5x-I)$t(D<6QG)n)C^6&oEJ>$N-8-O(1y=R{pFahqAuOm946H$yI6(! zl$_?nen`GpaEI&%muJqe=$YrME%_vQI(+`o2D^cDxRQ5TZ+!gQsP1AeYBWV(O(mQj zeRO9i%3l%0P|`~0%o}nqi+L#Ok_k2}J)f%1U|7wL&^RP;Os=9m-eDBzcWC{_5cPS=G*amy9z-4H$DFS%)#>Lso=hU*&bL{Bj&} zuhD*KDsvgllayjo{3;k$vO0h7_;kaKKi!;q*_&sUk20hMuE=Vi@O}3;zIl3B?Xmm6 zHfpAzWK!ss38ITrT(0Csf=@{!DepiOl9ZPP!Rz&Utdfm#8;nNy9ZV$)Iw8@+*#e## zFc|$-IV+jRr;bXV0PYI{=uahFf{SyJNxd)wm2|onW-Uibj#Ew0=`q5AHD&grUs1E6u~OFoSC%>_ z4GYBVWYlG~Rokad#~~R$#zqNAH6Z=0YW$(rO{5qQeV9xwUtL#SS5+G#ERs5zq+Sl& zWbKNzLh%YbR=XZQRSAQ*V8%S6~OGi4(cg8tUFUh zYMu$4Vh08@sO^xtBFc71y|LV04N9(}@`kk}skfEG)MAo^TrLyaNf z#Yi%^5(bqRDNR$TiO5Mpri%lyXulHuVi%ck3*AipZJ0{H!#Z(6Pnl$y!jT9oP(Tb zSQo*G#IT7Ob1u6C-@v$;r@B~$Z{dcs>#;H&3q1?g^l+Td|0(-WIU{koqyhf1sKUU32xe-t5O;;{=`M^ax7UCTe1MIw6XVOo z__WvUC6hS1hZ1&<2@Eo;3+9CDyG&fcx^k}Wf4Jh_ zYyaWvRNc)9GkvxE4cmS$oAln9Pm;fVdHxRxny~hm5N%8A=k`{!hl9&TSfDfF0Syho zFax4`QETjM;YnJB%SI-G;Dk)9y0Z}+@2LYzq(D8Aw8wcxtXfObHuwc@&DwQ7lD3(O z1WDjBR7bi3r=V*(qCSv>WsngD=syT5GrWW}STL?CY(W*&NM^chtY)N<_AhT%1g;K! zxvOgf{$!H&HSN$WWgy}}((a)hIMM~3TgedqGNN;(%psyX>?p!mh~r2;ub0b}%D4cx zo+D{50Gpl1DRMQ2sx}FkAh=dtB@PVZNhY03AWkyr9g6<)a=U}1T|uR`SyD*nVOVpP zH>89hQZyChrLv4MSMw31crLdV;5-K(1;eGC--`+)Q9g|mYD;Vk8a0`m83F|SM$-Gi z24vz&Xay~wJ1Bclc9htRzR)x^_%v3$G{gVFd8b!j=)A#N;C|3uSU46oDtMCqHA(+O z>oO}>$YcIgy~rgoVg8BM(aJlc!~(&cr;NV}{JsnDn}Udwkx zv>|#5N;Nu@9(l(;@y;Xj4wUxSZTaT9F`KvXuivqHtukflOuJ;*=WvPlL5MjEPp{WS zZ$|VLwWjc)k#rW8YCfpR?6Y&=DPyRHr;JfiUbbYU%C>879%1N=stZ9}#75eTB;#+M zWb6Yc2WJ_dfFqvQ&?Rs*T71fZ`@vc)h70>u6vHXeYSO50; z-aj>j30bo29PD!59F3;vDIht=E;#$e|+M;hy6aYVy9t&ZlfV%A>x2>4uiNzSGa*H zNLzvuv&o)nm@6E#olhm*dO`+*bYaR=L5ZnWpTWSCwBqA@W<0E#WyQ=oXety)w>pi+ zy4}+}jm6`|1e+43K-q{KppPfr+X)RoS(vQOokk+vuL%28=|(9n?r3GsrB8JJ{mj~R zAB_0mG`H!Wy*KynZ2R<<^&`IW*!P&OdSv2v5ybZAQ0v?nx`?_A5nGnq?VNdR{O?ge z##{v3HpL)fPO)ZH_Y)Cjl>#o!9GDY>* zNap1vvqJVF4h0HfE)0EU3l$ET%VQ2|aUeq)ggPXdf6|Ese>Xad5B|Gwd&h;f9e2Of(3bq-ym48V zyxjG7jB@5=eKMu0=1Q-4A4f9BU=5iS#5773vT6gNz5;Bj&VTkS>>sl&QI|4}8$x=p z9&T^0hvoHe9gcb=<|5Ps;#raMhl-Fd`*K6KA-adZcgKtsvAm%GsVM6zmG`@lMz+7Yx)Xw>l@3nuiY=I?7ab z&7x}--MEM>UUb`n`Hk%pgkrRUxg8IqoDHM15&7$w3w-o%4!_uHxZ>-ql0u! z-Dw0TOeCv>6eDUwxg*3(*$_;Pn;aE=Dn!^a)Qn`gn69JIvv`SA*=n-UAtJhsuz3ZO zLbBdvJ~|6nN3=3USjJf=HQkzZx_R9S5#75atUWKxfq*RUy_+Y!tHM~gu;(M~w=aN60DD2-0_3@$0Ahf@u`D)M(lkPFj`GUpp5ix zV8}oMgIwA{%5js)Gr`-JrXj*ZGatakr86%?WJTDbz{RB%yo+i@wq?#KKMfgOyXn;M z5z3Q?KK<&I8*ZI&a*2QcT?M(ze(IFo@1Do04~h@ua8AJJyWb(wXPbzR90R%ZEFYdz z+)@;qQAaNQ0jc|;Ii&0*K z*wF;P5jPq&%(*GP&y8Vp;Wxd&n5Xn{#|J{dv!p47sI{RV*Q z|4-p+{ki)`L&Ru@5wkHhuZiV^*vqq~7}#)65T!R-q&2u;?8YU0RcMU1d$HCv3y zjf^gf|I%c^Wj9ilk%hQ4vb2c9LS?snzGAkXI@beeI+6_7hTfivlHIbAI_!QYE!&LX z#U>!js3J1%MP9AeQ%43Yr5*O~#3L)_uAI7Y)iKD0ps-X_cYNIF$bf0QnP$%ijONAA zg3{wYNNecgA->G{-0dIDG5y@@tlzRn}wLb5}P!)P7G-`^dwC<_;X~7VkqU zQ^DY^c~OQI?tiA%f+~qQzvts#0-vvv{zv6t%)S55Kv6K}E?e_GG`Czp=5>Ywry^QV zHP{TY8jwo!_@Z;y+BNq!!C}M=jT%CDqxoheRphgF=fmAfH%GK<0%9L%Q#W!7wXhzv zeBS`XKP56C5S{Ns0gWZ#AeWskXGy&Q2!0|x5u!&bZ58vM6Jrpu` zqC|8Pk1>LLMM}1j)Qyxzo{)vCe4?9WE>KX?dZCyM5TTq0o(L<#78n{)%Gp2$T|?c`L8eGs=R84y zK@Q$U24$p7yNwbNQ3SDo@;vhzkN|K zA-7M-3!dB9if7&id(kb!rE}w_gAO(!jEEZ%iZnvnH1+H0)+nr&gr*%>DhiSa;=({v zc}PQ%LC1(zJ2JSBP>gaAVLozxelqAE_}@=sXQDJx#0)6NB38(1BJ58qL|Ac1b}4U0 z&Rr#gr;@?NWbiY!ZdM$kDt^|Xj|?sgjp%T*5)YP$@S?b5@RI1_4tJ=wgC>Kml121O zKIdmIubLGzkEl!8nvG1YJ6PKxg~>m%QL~ygG9j4VjwS?YQrV)4D2PC9g$YwY9tg&B zzEGG#vWpN-%kCLY_F>H~Hk??9;+wPT6vDr^ICgZ3cC)sak zc8ww-v(th?Y*F@_${LgAtd6gF!=+QBK@ur2$dJ*RMKxr+#_$bfh%=Ix;u$J2>^S6a zcz)`w1gQ9EGYT?4Ov_^G9jzVzSg59Pf!EB}{C_gJSs zb%ie&FkiIOI3bd7VqvJmpm>c5m`4`I({#ho$r?I_T0?cTDj7=T99i=zrtAxCbrcmq zkVIxAqJE1PyG@L71|uIvH4*JsK-i8^byI5zEu4v8Z5$B0;K*xq0NkFV18P1AiHtZ% z&ZLL}&=A6+1WU6F>Cf@#NNyQVaukxYQfA_V2@IM~&84~3+%(?oQJ~yel}4y%Dc4v_ zay}qAdr?YSg=8m6NlDIITG^XY!|Ff-tPXV8B`gVeVTGVVp$D}bVSVQ|x>*%88+{LI zKK(EqTT=5mY!R#Z9JZC#eBQ}cM~ju#)-)~itZ7o_>5VA!bX&EGgHZA2u%G__6mRAx zqIgpzIiJxAjNJB76&S<*DYtu3;jAT*bNgw?b-sM{k8eeiNG$AT;m%;av)8F^n>Qo2 zN#wPJk}Mh>ZAzbw4o^Ja>%4is0!z8V8!-M+2JWEieB6C~|l}hbxOzh`U0473Z^5SuGN({DgX;5MOSKh?*q?(ER*fqRRA9Qpm9F0lb2^ok0$#7ege?#rQSdWM`yD1boLzJIZtb~~iB?7EL zT|@&i{2o>atCHbcS$xgsJn`xsMt6r3g}<7sKOHRnJF@G@UN7t`==IPQgU)R1x$&w5 zoozytTilk&QVB8qVV3WR3$m)XVW$|X9hkt5ms{&^+YWz35?y zPj#p=$?uK;@P$t+smxABZqRTy^8VoWBf;-o>^rOru)SpLhH%C%zSd#o-XJyy!uKe> zp>Cny?F-d;Q$G$?DJxYQyNV}cufggRGOB`%THqt2vb9N!8WH?141P}ve&ciqC4f=0 zv~L=6gIg55`5*R;5&dM;?I`KhN-8*5Y(pZ2Vl%K{LU^5wdW>}tvtwiD@MP2v@gm)c z5j$3JJbK3prtoBRPoL^N&yK}OO(d2f!XHW91;f#&7;jdQ)SbVd%_=e%_5;JZWFGIj2WP9v7Z1rK!J{-jjK0&ekXWl|6ob|Lw<~ zO0h`)W5F?MK~l#6mExhwD^y&$jJ5IbsqDYK| zlHso}^h5SNd((s8R9~f*+~qve?b)_#Kh5g+*+*C3)U@C$rrv9G4Z;9f?j}`U@g|Vy zwMxJZtzB~)t61$?!9mnj;G7i7)_lpN;Q5xKC=n={&^(F?P!{E*b}CR*yXVByvRpF>rQ5P}_@m+|=e1}%FP7mTcpY-M>H6szj zw{Xxg$$>Z+D+W~KDlUgra+rJ$hWJ7h_%|ZHFfWYwIC+VrGBOeo+~#Pruub!b9}8Tx zU~Z)FZ6$6&PF%!~99M1+VIAn9<%dER#gVxNb0#BDFV7fRi8mvi!zwyVs>8k#h5BUN z?NH`$#!#3FIvqEkq6_7faXTp^BhKJpLQ`~+aU(Dj&RvV3XRX`c$jRdnSBcxL!%D{e zqc|@+y5i1$y~i%vRRoD9OM}OYq`COek0jD zj2g+|I4L!l5qT(jB^)ZvVP{iWD@UX0?ud&@8yVkL(hAGmRs>wNQ0w@|wZgLTLs?;& zObg3AEi5e4IgqA~yEoy|vhlT1rDbG1>c^U|EE~TZB%@W9d0Azd$|}p;oT75TlKyv; zmC>g~3y!s;E=`pbH#<4$aJe`dZbaE`X1bB%AR*z?grm#sod&=t?#^%auDjX0h_!|+ z(TE;sS+5msDjm1g(EZYKB;q?%TAKfUO69`(5KuUo{HuT1-C{p(Y>LkuP5BA z9htxp*+;3>?ADG<1aS0Dk~uahmjv12cGPjhQG7@v)bK*+p$kk4zmN%E`9t|O^ofH5 zsN>dtbw!@)WnCfYBzd`7n$Tc$fFksC7tU#-9E2_sKKrkgUlF z*^2P2CL>B@O-7VVreuMpV0*+&OgJa6`q(Lql0|4?@|iitajaG};18f&v`Q-%#j%DG z7;dT=t?-o4fSpe_;z*2@F}C&?N+?LlqsaUshT_1y5t*Ueoy+JwgkHMCU^^`C5Kotl z>xgwB-K1&3CfgG898PhBj*+-DTA@8DxY?bZEeYKeo9rbhSHOvA@oUS3#1xK3HSmu z0oH=_I?K>QrK33t=xK(%^pe;NyJ#_x(rq-&R{8*s7bF0qrF44p3QX((40++gm#T|C<&HXJpwbL!@Rb@oHjf?^Qu-PQ17b%)Umy-9Z7>WeJ%X?) zB^a6BhU}*#!zjimw)}*ijpp7b_l16f3jecV#($g9+~HePg=vYvbwY$be{O7K5 zJHu_70UV)Nvrvqaywtu8FVe+M2v0-Bac~3NM!(xYrrk<&zEky)Y2$O}eCZ+MX~jS| z2w++YzR9#iUW&hy3BjW&HYxz7e$PwJ&rVt&&G_>54U1mhzVOWO)eqP9-}-CiE1Qgc z|ClrFk6yce@j*a(TF|lEs-whE=59e-WUkOul5D{@uHa=ipqk2&`eDa}FEfIKY7L<- zl%EdTps1C{YR80a8xYO8@#G*=FNHnOKs~r=OIr4ff`__;jD9K}+)~nT*1dMNdoyGZ zz7;`6p>1zLNpp^lOi!XJFjyGpU?~aBUsB2RQkIMIM}-x`BWi&5LK2oC4=Z;mh0OSq zC)2-E$n?cX1JOEJoY_N>D5R@ssDpTzfjH^(y%3DTLa0-GXl@Att*$D-UIBtvfv}e! zyEM58oq<r>_$1Rma|LrwB8)~hc9=h$@slbd znbD2uE;3_2gg2RSGks^0Sj*nNkTh!Pk1<$?x`bvZ)HFjeEOS;j?2>fsNHA1|wMIKt ztFiH~$3K+&ayy)q_AP#BD z1sp|0;h-2?G!x9v3L21W?oB7w42{)?MEI1-bzjg*?TU zy2A>cKCe9>VzFf_8fcU$$P%bXn6O~TqKl?5QS!BLvf5LgmBIFrRt@D zSTAom!e?#;reS^0TnLXE%7mIBac~q?CU_A6nK>QKmfI1ijk{BRPgVS`nL0roNZg}m zi8fulc_s!+V4-AG^SQJP!pQ%}Js?)R5rA#_%>T7?)2(;&O&>bs3J>fLwL@U>j=2b$3J|<7!l~H} zO-XCGRO%H#tihhw!mMShsc(n_j^9-eyLmy)9hFPD-xgc?{gJ%j`kT{M)g<pII zPhPtF3!hHe1hIy|4Hd9^KjMhfe;ttn-4x1nxW=MjikkW0;NeSk6yfSrg64DwfODK_cot&rv>QL;rRO zuUFtv2#C$6K^C72&TaW8RD-L2vk1zKI1Y-}j1hha{SEfvgs%cBeEf8y3p>di{P3gk z7p$WT=AStCg87g53tBIWQewUFvO#RUvqrXjy|WO&hNG{!zk<${E1c-6BeSm245}9S z(Jq~e2+^#2qoXq^Au%OMiHOP=RCkg-&7d_?{XT`vI-nGhSw1>ELiV%1qO9joA?sAX zDv{Y2AsMHbMcVUO{N%t7z?jOOKnq8@OG)yi7|84*{OZE7-xM-Chc;C40=KBAW~2U* zj-!&GXR}?d;dxZfg7bzP-D9qyIx7olr*?=DxzIa^ZDc)Muhniupi7L)-)@D(g@~ zLgsV@@|_=j^W0xCqA%()C|#hM!Njxc9{&so=7D;K9Do2^N}ml(=x7{cf-R| zc7FNh`k%d-@BLuha>{bopO4@0Tt(f?K9Hv^NHYgK0VXbGOKnXRoMT!vfTKiGXdD_9 znDZBt30fU9Ir1osn>oM0e2#6zsDjoy6MGh!3j>?j2at-x8Ff?sxSWz3lYINfn;WOVEf^jAsW=wUH`jwtOV6 zaU{%fo?f%IF2KSP5tFVsKwl5$ciY%|!4R_dayFm#Mlcn~sQ8H|6<@2&8&S%N6ucwH zxpit+M+|18E`ys%2|yw9@Nxwj51ls<3zKlX1cuRv&);`b)Dtlm!44!i`efb)u-m*V zSoAPNi;8ny-7Z7SLs6HZ$QI~>zJZR+n^*pCoC*@%ee)MBx#EUdJv*6(-G2Dl&TW4$ sIsWQpi95EW*5|eQ`Ay*>fC~W@&-r8}z$$vDj_0PX+!>QaE` z0Ib`)^bo)a96WJR4ZyJg9k(Ai3UCy_rey~=0UQo+%@q$H1~?3$_t0P&;28j~tQpRk z%;4ZF_G17o09!gfw&jx43vk2GX+D6*0d9P>W+%Y!0k-cxG!5X_0F|a6p8@!HfZHCt zISb(50B*nQPZ)*tzW{f6U-%y2Ujg2BxN0oGw*lThJU1WU>j3Y4;OGwkUk3QV?dLFn zF97`A>UZ7(_%y&Lo}3SvNlya&XvnM$03QMPx9zzv0(=PIHzz*27T^N_k6u*A`MuX! z|KkHUYy)(cm=hYY+~K0(-|=E53fmE0T+fR|D01KD#V!;%(@76{!)$@M!$p_zTzvH7%gKj%ZVX~c4f8%FWZdql$ z{c$xQP-oMuR$HFB6f9NwYU8q?25o*jnlafg*;PeVBv-0>+W;49fH>RJpWe84z$yL| zJCm6OJy|X*#7}$8d6&$V*R5@!HcyM(*eY-Gw0O<^*#fjWk?=g%bE&h8I_4_~Pcxt5 z@cf&mbwS)}eJWXhLJLo&izT|sFR$bto=QQCB&0hD%enB6WL6hu{M;Hyqo4UPER z;WD1@;m;#4#&SrzI^5bHYQ0Ik{T+XMAP|0SJL#Z8lIN=Hf)R?=-O=5lu_~>nTSz-Rv|xa- z&C-pwF1wA%os!+ANp^=zt)YRp(!d}aQWtJ%Qys284_Q_>rLET+zd!?@VuR}hZj~J@ z;Elxt2Sme5^@jh)u?~)4Rk^~2+AL1oK4EAqhufq?4V&N&f?`z>h1V1|xaQ2H`TUrOm0m&7$ZHp8L` zYvyp(v0g4{${&tm+zN*)sO?ZGy-A_`dmY$P^B+Nd`rVYihtjX(vy>T`CEhX2e20w+ zu5h^KXIrUYHShC)LgRBe@CN{V=Sx2nptG^71p;W3vC2sq80q_zez>cP3SLEng7rG}zZ!i@gw3$X>Lxa~dY6Mzk3=L3Gn#0vi8F`&F@iUCxQr8&L{@z|&H&kFp z*N(1k=Iajg*uC?H;7(I3ws(tklWjAM>1LSHsxA~PtnFd;IyVdU5>+K{gc}`Vsgb=h zQDoc(?=4``U<^xawz^%F+oOp@J%{XSTvebUQgJuR)P8rRD8 z)ZFZClb3ts7EiNxU30x~3fesl(IV>m%o>t%9b(mga71qXsqGOq8V*iXkJ4%P)oOnD z09z!x)YT^TcGIUZ# zx9^StuJ-J0@7@!Shftl{UcxMPR_IRL5#{#p)foGC`eKx0)iEQYj)|!elXWivEbWhY z35nu}D{FTYPwcb}Jp2gL#-`YOy4S3`x7p=zV6Bw(j+3%nim4s9`~wl*gq#7sLb9$2 zM70=XY7wNYTcRS=BZDIEVb zA|JKJ#0`7}8+SjmW+rMv`i8#PlEYz9qVvzv;AHB1IghAf^wShsAz(h$YXn}WcrEy1 zryYQ`tJ~G0Cw_a;z0Y6q{X=_})c6=|fyM`+h{pPP{D_8ZDSp8O?1moN^de5~36H<$#+}_anyuX4UrM`d zTM*sAd16%vacrjWCQ*A8Cc~p+7ByiBY{YT*JtjqOd{r^4imxowUnsJnygU)aP~K=t zIS6s)O*nPpFBJb8p^laE4m&AtXM5?F%94~dd*52M^lFQA^;Yldj(zv#?myd8Q9Sdd zFFts(xjQcB9X2S#Sx<7hdled8&4GP>8vPtR%#-E*f&rUi52_k+D*?&QbAQlSv`;Yg zH{9gqw|Lqb;ls+@!8g)?AuD7~{hj{8iaS^u9?)ey{8}Mno3Gt8BQbVQ*iOuB9(>Ta z_~7oeSG=}*+kImX-}?Na!be^n`r#YLN8kUQ{M4t~J5Miv+wglnw<5$aQQ`z^-)QH@(B& z?N{YGe{Gjy@9vN^RkN#pDX0dKc2LA4^BKQ;5ocIw#MeAuo}gM3nABnoZ8&eGNA|93 zYi(@s$e!l)o+j^F5#$(ZVWp8vlOQtEL}WQNH^e0ocD_L5(Ikk-CL$|5o`#F!k0v~l z{Lx7e$ubd%vwEUdQTxSl zwl;d3#WJsN^0t~{cS8!N!(eup!9|j)utnKaa2aQ^;4ExJ&`4j zCJ+2_uXjbXxD1X#F;(*$6jhp#pXDcAs#gB8K=Vp!&=T$wWa>}Tc6rv z6CB$6XD@sl$rVp-OJcf)nx?DSD|6%B8om7SoWPpO39Ts_lVN1=RF>m6PCl<{@iwm% zWaP$Zz2iO>AIO-wNepC|X&^cg&xW<$=BOM)XdobRdlE#<7QWfrJY}u7wXv;nJvW<; z^^uHZcm<6elmrp;LGhYKY$IG?8-&cvGh+~;vEHzhtx;0eJM|T`@MO7^$KH_yZ?+gI zgR@vchXpV$JqaRa0rZjbiVg7uFm8iJ<61Q;`4epLOq_+OH0~i9cN?qfkh*DHH6+nSe!E! zuv8mM$wfmS6&`a!TS6SFRQQoQAXpqHq05445C!l0okCSN0^q}_VHO&n<`*NS@n?ii zC<|YLk345Stlxa$L`3Eyo5mL>p(y4xzhYh6x)v>_B4na=7H3Tx*^@J!WjeQFQxr+I^8% zaUp*$GBuYum5wx%-)W@@$?Sh-0bu`IPfd*t@^YNHH6TWBZS$zGD0)tI~EFqau|GUqrd^3mi6(QLAtr`adsxYL9tHb1Q!tH|iU1yVg0 zo+h7kUo}eu;G;>;##PFt^J&sCn)JabIp^wXI(tH&$x~?ZuzvfP&ZCy1G0(%91|n|W z@oRTH@iJf26D~fUfgzc1mXq(K$@ghAc@ItA+-d5^xiMj`)8Z}_RlfxT$6%tH=fx-C zN{v~+{WfIIClTMx((0p{qy{;$o`F=xVD=lv_k^_dyAyGds2_ohs zqlrjkb3GPPYuGuB5E1@g2cp^p?kkKjjYNcy&B$|@?kgDM5k%Uf{QHRh8IW;b0cROg zlNj$=r(z{C>hO4{bSFW?oT9^q=xMgnP^7P9AD_$ zv60#@5zT>Z8WcGvhZm{gXUpKs&4sgEHsqp7JZ-fp`@6HGCdjnH+!dTEx3tPPQ==!gW4| zOeKCpdm})W&iBozIh~MxI5JC@3i~<`i)P; z9b|GauvwbffqO~NhttRq&j=+mRJH&+Me+YQ*#fSiRE$gdIDE|KEVJ-v%b>29r5OX9 z+*=X~*L#XTwAN<`jj@=F6ttCQBxC>0wxhLiC9aOud)MQR`3hNfcxFkT$s@#{5l0bmzj15 z?aLhD;L@xSR5p}Kk5lO;Ds83GCMvyzN-v<&>aE*oDtvR5rk@Q=Uvo@Ux{^xWSTg~H zKNmV&Tfxe7epg~Tj-^q}Ef#0sM~7>NdIObiDc`b{imT9FR%$g#)~NJ5D*cQ~-=)&G zsPq*o-G}DIe|ETFO8X2t_JQMO{}x;nAK}T5(yxHZznP}Z;!GBQ!&3^=mhd+V{tlOk z$_6Rj!ETx{gl_lPc%>UQBAgUWxcr<1VDQu*(x45=xcDAwLhRIygw zOy}c64j+2_LZR|M@^G%=Fipv_0T;i=^EOXJ^o06~n0I zzZm$S!B(nx2~7Xd-9<~X94^TQ!qa)LH&Jr|zQVyfUVNyN!3FYEnl(kIG;7#ys`xRQ z5-#qWCiNl_yfoRL#ldTF09hY;3sgv$+t13AJc1j6-P3x068cB$9GBS9i&_HUd}01S&}@1WUt-l8kO zEihXHIFtI+>rB3ZZbn-%;PW|+=L{NyK%;Vkpz&@rjmo?*jbl`K259sd6XZ)0mX4ig zmj&h*q9|43MdfsZQaY!kaY~g7Vkki)^wCt-Q{{%Zl&Z{>o`|Bv)wpt(K`Db%ItEG{ zuIE}>j9J{HQst{k*I>7j!@oeQ{F3Kb%CSw_sPbJsmrW8g?14V22eEi8 zTFo%rRINmko93h#bTUC_&c%Wb%_-eYbIyv=Ws-cc$~w=Qfq*4sp_)r=mqa=RYCQ&v~Eb zd>dEv2hE~~+3cfEXM#{dX$HeNTiOhl%u_Eyjuza8X=&ToXSWy58Ea5a;I{t>WGQpkiG$=-1ydVGkID=@zLDXUCa`Y#McN`nwP_Ou>{jC6ZL?6p>dMQzZc~< zUyRGs@(OPY@}eGD$f3Qhag7H#nKeerx{svzgOP6W)v|Pcz5|wCb~2wr^PZ)72a);h z!HYg;KQwPJwg7x3BsPZxS)UxA^%l>S>%b-ad7XKkb&q^%=EIqyb1zLoiqmvfF4FH+ zgq)8US?a9l5>AQmo2#`lu>{sw}Vy-O=Y~bS~_*R15LymLpLOC_WYM5n<}Q zhxFlO+#9@8)qObU8{TKGt#n?y6RI)X7}O6=s`?iWQMn&WRi9GThgexRME9b_Vszm> zjE4!d7*1rO!>rJU$*&(68UKhzgtQ)`)rZ+ff#Rr+G0a4hZ{}QwaTOxML}WDy9!?;t zIq%~nbn$F`pf%z&EJg*x%BK(Xl*_r#iss9Ceh?D~MdP0d)BLTfeuhiuy(bp2?%^f4 zh>PNI8&SHjy6N2ZV}3&Rhh2nF3deUWGZWgPSgCrdlP3^Ke%<5^*;JSvAIp&xC5OS+ zMF+kgQ}qF7zvqLwymf!U&{tG_ujWpbsM>}d!o&uSz_5)}Kcnhz#K)|l`x>9@hSRhC zp-=wJi9pQ05U1iviPpW;_6EHgJ? zT**_|g(>Vp#S#$r@v!^Br&;hQd>WiEJ>E?V_S1p`-Biup7XIBXRTqjq&+j)QF*jZC zK?fCl&%Y=@mazsH_V5nv(d_=*+1%>9vu4x>pHDk~RldBpBbyd(aw3w#hrS4E+&du4 zo=&^13o#HPa1ycVA|XteNQ+*&BMU@U0QWLo$(Equ+t zd9#G~|1O|~ok*)tF+RTb_2^YW@syZG7}u>D!|`xTR#>Qp&wm>B`nBjBJ2I4}aHML;;KA!I2L5H6ch zYjA*>H8{Y`8XWM**5E*ZItK#G5d8(HGb2Eq83F3d2vBE6fR;!%oi9RvAM#f)U7!GDlhC<#&IN!%{8*+havvC$=(8+ zBKiD6HRos31?!#W3qPnBo`e}SAHo^ee1xOmUEazMlEG5_bioNEO5Q}Um_MSk*4Aync|0M2bFt`VKi=NZ zxOPSBrDJpCrAwqQW*@lw*e{!YTXx-(%T_=3#8>w|{Wr_!-|sv8)#}%uOKoWNHq}=T KNFO<%VvRuK zfbuE?}AfF=OULMw4)aH$yWRVLlGcV1hFlqU!}t#w5Y`*ywm* IkjDQ7077`P2mk;8 diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin deleted file mode 100644 index 9f6425adc869b8c54592ef47a91218f123b3a652..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 170 zcmYdjNN@;B;7Z^Li)M&UkVp_okP3@V2n>q`k_-tx^=2GX7FsV{tjLyrLc>#cXYVOH zg|ai|rYjW|p9+Yz(B2c0zzBp3q?yGgghfvX01{>i3=QT$45VA4zSsg;b`1@p3Hjkb z=I3Z2@%P`Nl+1#(;s_-ng}__UfuEk(+zflP`C+etn$vD`siKe5&Uj5PTixtzXQD8FdeCWi^ADqm=e3kbYL_< zcufP%{hxdU+yuV#$K*-ic6)4;v%g^)+xM~x(-833^u{B=gAK2Ht{*4Jo`Ojr0xkn% zpIyrXZvY>9Vs;YvOCx|yzwrU)7eqk0_95`il;yXbvklHxM@i<&wWP(vKO`;55{t?p zrtAuZ5{0Bi@hP`pkjex(UfBK9qV5D|pS!RA8$7YPTXXJuF+YN{tA0F5?Nete_iKj- zE(b_0GK2YHejSe?9JxXh?ktmn$CYi7HpuDo9r>Ior^sB-Af;gBM}|j-A8*8V82yxD zYsl)kJTfdQZYqSKFrJv`5Z7Ar6?ka5-ZSR+EZm_%Si9>+q`m&)02Co6AmXdmz1myR zY`Nc#dWKB1RieiKwX3-=(V6ju*_rv)Hug|!U+7Nmn=5yIB-T1rQKQ@_woAaFjuBBV zFQp)t@4k6%Yfr|u1tCo`ZUa3{Lm2W$N1o4Q?Nf)<>|ExYiqh5e%xl@)$%X8^%56JK zW5Vmq+=6QJIW;%4pdKAjUlAed>pXL2Cg+P&T1cK}!ByTBFG8Z(#PxEl)!a}%xZTa6 ztvnxb?P}#%&8_vXyX*aK)g)GND<*}O-DQ))PQr65u{|mcxrUktnSK!Vss` zkVed;F^#%RN^2A{>AXg=sV6N*Yj&g%6KYrMza^dvBO2EHawe6R!Uy`e@@3tFE8my7 zvYE81I#+%t^&<0UYdXctOk357FjRCNxsRN{R^3>u>6Plr+A3`=`aU->RA`53E4ruq z8A)|YMhS2AA`VZo3Wc6N9wZ$&W+; diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin b/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin deleted file mode 100644 index 5e729b9dea275fb0ec3d6a40d0e952d5d178d755..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 397 zcmYdjNN@;BU@;R&WUvd5H%)jT(~vA;oBUTKk)a^GAzAciPy>+J24sf(^$h?r*8`cy z^m^BW6+|aE1lCJT`B27y2Q&iBX9Oy2n8-ZgZ?s8+Xd**(czpcd=zv6q7NE6Z(F_pL zi7?Swi44EOKxR)66$R>6U<9#2+CM`S?t&;xaA*i@Xku&%N?>gasyEa#&@;f}j0A-y z#-Is-i44moPDo_b4U3K^-SG(ujY08Efei@?EsQ}xvK8pBR>nA>NlmScj6n$w_5bmM h2MO}cjAAW}j1vO_CINBSzlABq`8mnX3> diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin b/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin deleted file mode 100644 index 62386fc02a5f583361177382db69005960d0d4fe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1969 zcmb7FU5pb|6rQ`C{qaS1p*zM%vIBMnVnh*kLv~$h0xt5f$?a@ujbqHYv{S8VTGAHC z8j{XWw~!4aw_UsZB?b+V7$4L(coE}jf*SV02Qfa#KKS#Xi6$;8;!@6?p~GsLbiI?z zd~?n{zxRAIU_w~iVfHhrHx81ytW%JOdzthRz74_RdNYwPf3Ng0>2TakoXuUmiBP`> zgN$SmUfq5K5MDxf=l!`82*2}OdA9gIh$?H#KkE@Dn=1O1ehqzHM3sO+Cf!09U7n!0 zYYoEG%$g2_O4DH5Ge5k7yXH}~S00rRUXSZ;$`Fn~kEMZ1bcAL#z<(E@@bWkNF6iSu z^$lz(>MUK>7cTzwo4buk3o)G$!pM&?v6J7I0t$&M1hPUJHY27@Yz-c;^T9EB`pBDpOjyT~sKSi4YnX&tKg9QA9r7l@t9AxbL&46Vg)U5HR%ycb|4ICPpLXT_KxW#7`>lQ40uU_(W;naMx7UEX-* z>l=RUEr6x1uso)C4G($UVe+po5oXWU&QN}e)+wK*-s$7?+}`^0XbXqFXqD8^fN+qw zR8fwMX+Qdrq^hVQr3A5X?`Q7pE_Ngqm?>6{s!eJ zcRSjaMK-ditNK6Zc(XUhlPqQIW`*L2dYEMn8EP_T6tbI&YATJhoK^45aTam$>7il2 zpZ@{>nq$hvEQ4w~nu8zRX`FCLx2#@F@{{+*oe%vv@!`AkBX4e-{4!wQ eJTmw}&iU-;Uj+h#`!3p>_mEn>B{yOgeL16{W+rEoL5P1FH7x5-3DLLy08 zSrIZb$)>t0++@x6@1_1=A1(By3RT%tDi}|36QL1oq{~v%cS@5-w-SgSjl|lJEf0FhZ9!vMDF4r2=(hQ z%t#jD#qG}m!gC0(y*>Xj!f!lRo-O{r6IJ$>e+Lkzd=>pvzl6R{qe{Rqldd3~THa6b z)H;Oe*>wSgif^#(!SA2MQx{ORS00fNexA_Xlpz{}9$N#I=m@P^kpC_~;fXIM-qgo? z8n?5hsq)f0`oihIe{+v9X(6sNLKyiWE>7~66i`T9A&^zls1>su;%G2nYbDJ{O%`)m zL#25$X{h6dky6vSy!yyv^kE4Xs1DJ145QRI3pGTj3=0P1x`fDP4(e)9#=z z!^%4O1lb`r*FdT{yls1VQbgepA)t!8C{x3mnI$b?=DloR&%}U1<;OKJ>esKu@KgKl$LKUr4(hdn((+!Q3M&Q?jhr zYn0**NK=eRT!yC7Z(*vzI}#LSK%j|T@6|0998J*sM?@I{30+eG64qJpV>f!wh3Ql6 zqWUs%qoQ{jY=sDJrHQOrG+D-cjvdSxyVPVZTg)ZGNtV7-`c-6^3YAV>5q@0lX1GpHk_rbGxr( z2k&|MsrxqU)c%~Fz2zh0%SJs63s-mUjYf`fc=TRN*k2VQSbI~daiE$Y2;>qEy)_Gp#k9_ zaoc^`^TR=1nI}a+mn9&|Z?UB7ev4<6kyVS!hbI4FrIirx>TvXF0&T>}0KF3+a#RrCl zTMfMt-7v?Li&+NMDr;qY>CWJUOS*0MVv-*wW^7U>u^9)ahG-69p||4r#gZWER0$r8 zb|Szc43>#9Lx|{(&whMgSAy&NS@#C-TVoHcnj>4W!>s#WPc!E?b;V@dQ_xtAd-IFQ zK&9%sJLu`ku{s5{LSi+1=i$cj%J7L_dp%`7lP)~EX}$XH*MIGvfQ|3%`$~K9Z0Hwr fUs4Z+&fFT^_U%h!^)~{OsX{K3+#~h$N!$Me4y)&c diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin b/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin deleted file mode 100644 index ce6f13e0ef20de629d2662ea8e5cb3fb39652d72..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9995 zcmbVS31Ab|*6t+fN()_*Y10OhZU`cqg(^ZzL7s{rO+u3(0Wz1c!+U^iErhaP!^J*!y4o}646K_vU#8Wf1eb$#hdlmOtwr(6fDBz$_L3H9(|`;guyUgo z(T{$ILmH?SDqErNOB#^0F-@-3sU~>E8iCU!l1;}S| zOP>YuYarWp`fVtXV}NYe=xP@rI|2FP(N>Ls3s8)Mcl&VjZ@p< zsU653w~n+0vN@1FPaO@B`OR%|yHJZ_`@mC6!NYc16!RC5)-s_bkRJfqd%|E~GNvPt z{TB3v&0?Z}9J>DASuKjb2;{$Pod*NC3dk`_csL?@Fpy)-2_I`wqsu_P^QCzKkXT}` z{f9S!YyspfxYB&|h*&qGj1oCwtg$w(Eho~z+&fUen0pwaB=biWvB#zt-DhDkYLTV~ zkY@&7&jwNhWO-zVw_&qGK>m?C)dXZeAaBlUQz0L5`*Ha!Em9qExbH-cNCavm@vL@8 z^^=1!Wio0#6^m)4@}h)2b|+F5A!9QBoX4T0ZgwY|$5iTRhKd(#3=|2%YvNPgX=iw5BZ$C$e3q$x-5(d zHQns$;IarVD;y@Dfsd3<^Lc22ix)&2c{TmM{A!*c()llzjV$^!<>cbhJ!#txL|r)Y zz_|9VY1i-KiEjoTAAI4NAQ!tl$cgk{*lRN)?PgbYQ%<8ZI6;lnI~_>9T|nxED0!N~ zWYxQx_M+flfRfkRok31_|C5JKGv|_A)(l2tWzt--@UAKySC=)9$+0M#fGnJqF$s5M zK69!TAx&dRVVYJ*(+njXw>w3YG}-P14p?Fh7p#Q;m>ic0?Nb<>A1phid28A7RZ~_XRFFD0Tg&&kS*Y0GDpqlW1 z!X{uK#^{LwK2X?Ahs%e;F2YkY$52V4OD{0$B!ixo7)V$4usQ2IDuj}bI#&CrFnjf* zLQmkMLJvIgC}j_u6NPk_qzti;PwZhiF2>}cNGb>K1TWKgttezXlU9KAv394&A{6v} z;IfENdsr0uwZjQNw}6UK=sE{e2^z)ZN{1Y%c73$5^<-IF=wZ zIqOmg>n6E7D@a(ol(054u_$Db-D!5QC}aVAGL>A64uuq9(v$_|JEYL=q%4AYI=o<# z(?|L-Sqc{fD9@RS&5TiBKnqTei$-DD4zu88sCjdXeehdTY-=-@RKrO?k6rM_EJs=(r4(uN zl}KZj7-;;uPUo*C0Sly;?f#daT*v|thRn}3nI8}iC0v*JMh(=NNdGR@5^B(pN0?g{ z@^XXL4l~P`icy26AWShb+_5{0yL^H)D+mdaWlNNPuaTj%8Yuq4#ZDHIw-QputkO+y~lI9{?A`H-!5)1Va zMY4|S_6x*OJRrCHIKRNo8d(RveEvCk}kxua3k7)T|MnJC6Y!Tu;p z0}cc@g##bR^At>{C@UpWf=@(IeLyG-c};8~B?_Wd)ajVuBrhe16vSGTR)8O{x|VuC z6JURcxu~CHm=<*c8B4*>qt0{0FWBM?l(JM=8fe^xD#^GFBZzTP!?-~79SFT&EgSoA zW@vWt4}vP}fuvox>#Mh;m>|jfW5OgOVpLaC z;c$dhr2O{FdrE~uF}+D3Ng`DFAVIC9w_K8h^P=tTb8!udJ~P-(r;oQB9Xo4l?<>>H z&wbUnZ0F#H8^k>>7Yi7$CM)?0(!`%#)63R$8u0M#d0XhQmXmM)IclM6vf>PM8#Ri# z34J!sgrw2Ul$D9As(VcKD`%MVxP0N-Uh@u7)irBvc861heoju{zQP#xBB5UK$6DV0#gI z!FIS8l+UeKdb$kh@cuEheM8pZ8!nE8%66t`N+NKF+L2V^9g)W98+kM}j*c;@lH zfBkZ!sY`_|`HdYTD_2GCPH}cP)v901j*vN73vA@W!7HM)Re4;)Sq>?$A`52^ngr6yAsXueP!Am}V8EOBRK zQ0kY!KMbL@I>GEgu}3gwTCT)j^%&OnMA}!SFiLtXVZEn;H$_WNnL-5A0;F9QkfA0j z85J5I8tnXEXcYBwm!*7X%kRJKMnre#?Msy<;!01?q!o`3cl+q_>R!FyJ2La?#m~pB z4oI%<*^f*usgba3{xGW(YcZz&<>J}VTdCldWa_jQZck81ho-%s^eFt643&pXURU) z&F*|!f|Vpo{IRxVj7hQ=9bm73nN)SJjbJcl!q{8lC?`OYc$%<6pr#JR&v7UzgMh~P z$qp3XA%l#(mdEU5T>9*RHsWP}@k&ruWL zR$op)ZGCO1AJiuNfD=p#!TIDVn1ME;?Xf z7mp`)FtGw)A^HNIOOGug(hp#aJYgH~zL(@&elF*=avqAzIeEbS#a`EZ>IDG)z#;?F zJ9!dLgh&gRR&r#3iD#jT6dWx-Q{1*Lg<#kturM%`iz=Lm^w*31^%VLKfu~p>Ni9n1 zuSz^nEAh<+_#bC&!)TyIgfc1cP?hly1*Y|V0PSDm42MfVi8kn-^w*)1B<3QVas;Hm zMMhFm5lZB65lS3gs|dj&!GaRIN@XZc!b=JMlzk2@e zl=X}HoqHvy&9@6~4gJ37wTh%w?_WLjmFdfa&_og}4C|!uttRKUVZ(~+HCrt?>m0%0 zw+xveHhiQJbug76sG+Su?q>36KL?rqY%9A4>w*4Ci(gKJoNpL{3?oG{S0O_bWEh8V z@`lzJw$7I|T~iN|aGT|=l?DK>HEbZu3ARUuT~ZdIIEodCJ7Yg&C^+xBDStgihZl9oSgLkae&GYiHE87RK+GR}sEn z?I8t6o;UHdboYX9UVJXSHySl2V|ugM?&RUOCW-! zH8giD3^5zS1i{P;?kS~9PD@&uO{)1_e*P$j49h|GKehwJN^XDcP z99;gH+t$yLF6{eo_}8Bgd-THW)$>}c{L}sIQo7l_zHi)1-FVXnqmqJ}yLhc?Qg*#H zzu+N4TqcgoqhNYLYBFR6-rYgluDl8+`$u)|Kf1N9QES~j+*9XNugH==)^c?^Lye4G za7r5SXv-W@vHiWawB)|xe|{~&66n$c;y!SUW|v>D)j}k7TzBWdh##mO+Y{b%mTVrq zX0K&<=RLhFMPvWEem1wT2ec62)5b#pOQ5WR9gbtJ8n*7bpD9=RJjr!8*FNHjUB1F} zF}_a2H=!^%sjt_E!AX^Hte2iA@N}^t^1`%2HAym<+>`#NffrWB$`Xl{5LhZ6jWPZo+Qk{vmHYzwh+i=`|eywo!WkkkyPgb@kY_ zxu(_Yd5o#hQovc4ODh%YfTI!dj}loQ_5*O&!qQ>auh+p!4K%$OTGi zhFN7wC(cud(x8L%K?4n`JY_ZnK8q7Sk5UF=D?=*wnRPlT=?W~+DCHdoJS`5_>EH${ zr8lrr)yl*wr99wSvhu8k{y_oc-;mT00^Ags5dgKML3~dWtZ=IZvp={>5|}|Xbdp+1 zbmC$d&`atjJO_rq_}>`#JS1)9|FXjnoYtsqPW zE~TQ%ujc!c5x(k1sSmMlB|bX7xGF~oaG&h)g!@>J%I9GVqvxsTvW4n-T9o#o!|Q>| z#x##Z;KgvxrRHhYr(skaqgExbyoyn&RZsm8$t%SSeBl|HIZLNwQQA(2nS+=B z!v0r15HD!!gZVH1RN8V~FY&)a)+No@a=h)QcT3;A-M{0&gX=4n%?_#u>Z$A5pQ>kl zefw(!`p}}cer|N?!sDW=dpD={oD`Crd!)orb}4*`wMbuF-+EPM*xaQZmo85Z8M?1o z_mPu@4*Dq}{z!QXiK zxu9i(hL0ICu1`v=sdwV2{o4o5n5mif^P+_p_U>BCmz-5S*Z0ijm$pXbMotbJG;Z`L M_scE6;#LYiqa;Jgnhf?jdo@T#3N zYnB$yIWv=_&?B9Z-{qFAz zG&yt5d*0=FpY{Jd@2GfOwYDqYnrc6dn;MD5{~nF4R?mbiv%B)*2kx$;Y1c%;@$QEA zeRMponw{&mnTDeleoMEm$!ZYjYYV;6qn!e!x=7Z(iaeJ@RO1@ut@ljT*W_7DtFEAF4|hgY zYn!FUSDEd9iZY?3F?kM?=OB6Zuc7*Rol(cOY?^zgw6zmBgl!lgE@! zLI0p?4#YdibHY?7La};vI%LqikDw2a`fae@unyqfaL9&5E_h;t*g67@M9XLS1-ts&r~)cXDF{)91PHg9q!t^vNlbG z){;)k7RywrY?XA{eT_5jNWHCRWhXp#qK3-;7}5P+RIM6wKHIQNxA&0|xk$-lEH2$@D{n}8FnF*`gvx%G3)9Gm zt+<(OQQ70g0c^VDMPAV8C>HIxx-*)H$MIrkw0qyqe|(>MCKzj1HOkknnqux&s!}?7 z*OGU(UbS~2O?v_)^)}PAKXgWI3O(2vEz-V(SIFzKNwbN;108Wcd5=cO`w{Yf($Rx!pnyjAVnfWd}sjs**`Zt*o_SQ1}{)B97Lh})m ztD2bz4C9W!Hb+aIGu3-bS?l~g_Ek&Ys%bT-I?62`?zJk=feuy3Sm~w7KZwN0*OG)x zVEW^$ruu2}*CXWHpP&UF?TpG|OauGj>m%RoHu>I>j?)HkBA&E{>Jx@$8x;?tksYw) z1tVZ}MpLRWh)=^I`~`0Wc;uOZ0~nIQd=`E(=3EefOc8@{806m6xYz!M$jF1`@YWfk!a5 zyHmwE=qZ7j)S@C891H6!-)zy+X^^nqSO!EWKNAUusr-TVjcg zE!N+os<9A`4Nyh7YAR4geStcEis!{CU1&m&G^V#*U_up_VM0{?Ma-q5YiurKQ^6D} zS}+BhDpKHvbRN7w6(7k8pD-81LrFuVfGUn9X~%cDr-3BxYQ}_w@9F{_S5JT%SQ1PH zI;@=KK-QN869KAtmMTt34^;7RMmjWlXu<2~Vfrkpc%p~8AY6kK?clXh#Y>qCwa&*K zbqCaFReUf?Z zlA`gKm}y!%4!lMSY>YPkAdTOJ34n)&)JUK1o;J_zj21F_iAJx?3tgiDjXy%;Z%E1P zhJ<@=X4cE|tj9aqW3m}JnYM*t(TlK>gXg>){#~$aCu>o~tDtPy$Y9c9whY zj1JI*_w>+&6*S>P`J4M>UsAkZZ|6$j#wGTV>*{+CN;T=VrB?G<2tZ`E29-CU?g<8zFX3q~ zWSpdJb-lti78)dzqltfuMB`8(6W z<#v~^(=s)?m!e19_BNEe0eV+nABkECn<}sE9Vp~A>Cn$QY`8FB!WhU~IorXE7Y8!| z$I4RWNvd@Ev$Pq88>{K;fPq9~(|4xsTBL zqm3aMRQYMV<%At8KM=->D}R&7Xs+cYU;z<4#-BGVumTHB)%YSSOx_tWsmjnoLsgAt zO26oCI#sRWy~V5iR*UKKM%DXARaK5IJxS9iQPsPs>g~cDP)E{hmO1ZKj~B?X=i%yX3tTY^vwa;|FG3-^$&p?-~&wRhXEfN4AUeF zOKUV+;3-aeBN8=f(i!-qMFZ&-$G(jw9qf#@*l7JchMVlSXz~IlH%Kjg{PAKTKo0vU zItz-#$faoV+DNo7PF25Q12B1uMVI!-)e7dSuxqOl;wHfTqRA8)H)hI&-IHMV1WoRv z$?*(rhK~PXL6_{- zOq0_)o@$qkb&`f^1Z%+Qhu*PFOR0nhdvJjX&_y4kdH*WC^5D9g3s2#q&lDZf_&2|mva)9cE{0Y8d0BR>xr<;NX+LPP>n2C;G^^6 zKFp1EGKMPmQgtx$7KZGw?2-`^B_mRGjXMt5`O9E5aEV7o=>GGzNAJ{u(pWfB!cK%3 zsd~F?k{iT!poeo}*bDH0TFgx7a)CT|gXrpfNe~@`DY(GP!f;gmbzvc+BvL$wn~Pok zrlia1u*tg1){@{>vwF=G&FVD)m(|z&px9WIG_F}A>!q5FIwq{a`u~8<5cU%TNHtvv ziQbC=*%)u-QhtA&rZq-j&8F2vfJ9JDhUUTb@MsNb8U+MjDfMs&jJ6?F*5iRogqBGa zc7xvmkr=A^MlT4+J_We2(7kzJa{y`}+pZe3%4ha;y_Qdl(eLZc_aBc9QQ(KrtW@(C zI5#@_JZ=rJ@Wn$kwK9z$2;Pm6qp8q>?DL$wF)yrl6!Y=EnDyOEQ6T!0MD0wCAdOGTQ+LNYF|P}Hr1|#FPT@BIr3azpoO1>br>0;+SY#U z4vP;clQ8mSWj>!Lr#u-i)ehlhX!=!GI8^(t!T>dY4_=aqV6@gxwY?E_n8^>}_Gt%o zT(o;dhi}uEF6TGx6o!8e?+>aG=rJf1g^(!Een5_Yq3iGVizgA2&I)Fgga0kZYuQzH z3VMoT2%`{&uAtf|8$}rIoY|rpYp8ApTgJM|^DJW+!7UbDJ5!s-+P{On;Rqx^{mUaV z4)`2{_>{*355q1q@^Hgx>d(%CR;CuAl|r~MbUZu|J~4Fs7HnOr5G%lcpuow9_NUWW zM%|4d6*Fee9<=(IzI6{^q|>1+v^Bz`x_dK-;8wK4zW1odSOK@3pl$s%ZoQ=ott zIM5Hb6S}4DiJqJY2L}=z$B)UBj~V%68NdJJjqy)Y;62HtSMt)fCP$y7$=H~t9UFkga2RaU4yX(A?@boXs^PZic3U_DVGF(@8K1C{RyGSg zFgZdkzp$wVwx&SFzk_V8mdOxk#yZfZs$nlPP=KI=5wJ5B8_t~q2{Bw`wkK@Jsg5hn8PJ zOa*7Xx7a)EFbHo0v0^Qhih;t*v2wsDEWnVg03I#}mVww-G*CcAj`ie@#i$O9(QV!H z!KyJMs$Zf&DuGuLM!$XqqV+0V!Q>f?-(G?x{tfzRo3wP3s8O6gW!Sh zIhGgWa{ww1KXi8&=m|N)|Ee)5B0g;*i+JFr^F+L7ppT}N^%bZdn?G=jYJR6>J@5=B zeCxCK{k>$uqYje+D68hfMWa~a2f$$nh*^ff(X@!`+yPWL$G}TB9ZmjfY~No6f%l#8kGe zq!nIt!;{h%&%G75#&QC_)zU{1B!%TT8)H8Ybhp&ub6POFs#Y`UaS~>Gsx6*x_c$Ia z7B$Uksz1Tn1^#oQ4Jcq^F69CA<*}h|ss1L&rE2h~hI#`~pI%Chm8gc-@)IB@?PuxW z%|#t7j`lG4t++yA9qrtDY)ixUE}Ow2#YpGeJg=!9n$eF@t6)@M%J8onZ8yTgNB!7` zD^0N)nPz!VHFA6afypFjI`kDy&#{alT>=af6o~`!`YaY{%To_TevR#caK+pFH2nc& zX!!LKAiue|(s-L zAc4W}M7;75BqfQ+&J3il!1U_rXt!_23<*;HPa0-jq%&PoCD9Fo0I>oY(J6^wRWS;(Z{y!FK~@ zqZxCT6S2@{KxKnROG8bJ+tGVY28tG z)a$3vU1KXA)GH2s1}hF7$BNSw+Kb%B`rhJ_k5gzH6c{f#LzjB6n$Q7|pt#lyuQl{8 zy;kApG+xhA=#v>xtsu(fzG&S{JpesRau2H1xryWwR*os_{$ zg$8CU#V#Beb?$z)=`?p2>=*JAGdhzpXx7lU(u`OUSDN`My8RH(0`3g7HD@ZUyhSs5 zOu5%v(BGdi)R8DEif1$=PWTgcd3$WmZZztSm+zE~O=ikbfy3Db<% z1P41WK@o$-bySm0GnYZpAgQJ!nwt!}m+cH3)wh<^n z%s`B0UcnkLAC47hCiG{XX5O0@^c!l{RwLjs&X6$8FoO$?|0Y?9nU7<9nu)9t%{=pF zWB(M)#4)=?4U=RKGKNk+G=x&_K53x1VNP)u8=r_!!}^k4JfU~7Vc+O3vOk0#4{B&o z$JB5d8-WR<(|Cv)KBjr(sG;L67dmddoTuCX7gn~rAtcHYPGQ6CNevu>8yZCCGynpM z<*4CF7dCGA9$;e$0I1Mb-Se8!foP`@_>*FBjO$Hnp*b@X+!yyKbFMu2)U=!rn zO+7U()39;F-JojY_BWww<2+Z%Gi)5A24q^pd8=UOsBvJ3@uJhAUafNj1!_#YTBk=a zK&H7jor{^nTx6=_a@#ce zt7&#SCJeI7uAo_ek&b%|4Y7mudwb=zW25w*T~nOa?5&X@n!T82x7?hS*ZN$7TQ{Hk z8rn_3baL`vK1Q>ac1C-U?412>M#5)b7yC34o|66r#_)P)^eD}~8UON7X0!Wfb_y6f zQmDvyAwM$6=(o$gte?&Xrya1Z%$PIBIV-4l2_XWa0+9dg)W?Zq%)q9LN+0jjDb(2& zH~VSUFC%nu<(u&EEZ84}D>hx+BxAvZa5hq|lZK1$j>5Z5X_&@~_Z3@mLR`-ZQs1-* zw2$RD;0HiH6=3DXUypwc=~AtHzyuVcmwpeN>QuX2 zBjW|Of(5$xmv%0!4ub|79&o`tAL0VQHT(%&a`B&wv*aYbAvaS7e9fkXJWmODN~b{= zYpLM8TnbFH>^~8noYRh)yzsAhRA8&{`>Nf9J2kNlpo@Vw2=|CFrKb0YWzCCGwG9t^ z113P6nj+Zh;^dJR8k4285pbyK0cyHCEl@dgtt17R@1Lo?NclzCTSah4dj%^-53aa2Rek8H|oH|UJ$+-ziZcY=k@0^{E=2|2{Y0fgb z^j(~@>0h;^ZTXfmyy&FnuCv0EZXT zycYra0x9P4I&$)g__lyU@}}C5Ei*g-e&pXu!e8We>cs48_oYTGS~1_$7+$ZIs%lcrU6Lhmw+AS z%X$Er`Y?9@8O|t#WM!aC3~GsWMz8i{ZcQZ0+$MP|&B^u!^D$DK7BpaI7a;MjkQJJM z#jDG8Bun#uXQ>hCHK!^oZFJQKttS!Og7J81{s=liS`wxQuFCxX(##kSrCBA;|1(Q7 z_H6!la3AS?n*U8O1xn4rKw!|EsX4)m8wTJRUhh8igPaLk2rZ#OG~L2#gH@s5;p8{} zKx4;ZF$XNd`qJ?v%Nt&Aou8bzbp}aI<3xI8rDhh6m^~x_&R&R0QkZ`xGb#`A2~a( z4VwVV7A=~PNE{Pj8N<<{MzfFYQ=N|AoDFp z<0oke@NHW1A@CVS`REwPyr{PbGT(S%ka-D+3r6wM;?J|rp+)y35^(zjWL^wi29P;f z1eq7VT?Aoq8^&7n6K>AL8by^C{aQ6?C>%ic{{mNDyfA`}8B=CJdGT(HwiwuzTX3e) z9`JVyEnb5^wCLePY78+ZjU~ru(YLVei~AVZ2DK2_F;biv!;)#y{cH)&dR9b{v2D3D zEgrUeGH|6zA!O7xP61I|2stGXGBUrML&K8cji*W=WWWvZpE&e88z*My_%=|Q7pa;H zXFqh(1GMB4X2&pu2(%Qo zq9tEC2Q6N7CHfc&_t>-um{mCCr$um>W6)U(A7LeM^K(natjPZ?Iaa9_2}psRXp+*~ z3e~#Mv4$!$>uBj$BFcw9yCdE2+j@z2EMo=qseA7`-*^FcOr22kC6RQ7X2vSmmw9c> zms$D=Q5|Dm#?pJ(%UC*eo|i#O??m(iiwWJruEtUnc}R9|#fBHI#UgpA;s|h`Or$^4 zr6VnSA4Ejms(hR&&86Z__olmFxE)2diT1A7IH|?Xl|##Bu%sd^S$d~~D7DI>eZ8PD z-b}QpTWe_9J9vJ})~Z``XY;)pNzk(Wcr8zxzRcXej1(~Iq^HgC=sU;|EUVI!U$&^! zvs!kC^m+8WHKWQLN>O9Amb#Ue0y5&YFFOJWTJ|l+b@46Q1PcWxViP-;alpF(sg^yd zb9Ah+yLaz<^~l%;f$MFp)KSCcM{vJlDI|Htyoj2qJi=+PJ*u(C3?_^uY!0$AX<+VI z1Y3>)pA~-r!0U(tIvc1ntpMDQ3SU~jFDFqRr?Yq>=zRI35u}Gu^11waN6pMj1p8*g zWCA_bfr16!7{Ek;%iUpk(8cXgX`tyfQV;G?tAbn>EJfimU2gJ_s3s3B|FKQ`4|XEx zKz-88(SaK>VC2AHPsfldi`^VYB0+g-Xa$^rfOWvhLvX{i{3^&!y=p{)$ODcF&~i8g z-EH}*bz`)HYL%(TxbRu6B>dIojQGf8al>SaHls?HF+p0PkpJSWI=XbhI)pQr3)}G` zl}bpMq!mC)xK3Kr*JKhlPvHIeCkIs2X?9xiuL)EOZCF^^Z>reuDBV^(A#}sgi?xT4 zFwB5b!6f9kNVpXv(q@!y%EQSQ%&!4kEH*Q1sA1Dr1jMh#9+==S)Zt)CgBi?e5Y$Z9 zQ1eZ^(ak9OLt&V_sZe2>FQAw-fXo^8(*~Jo#jTk1;-Fh~3Q|jPjvmm;!7-xdy`%f^ z43hM+CCJc0Mw_<-xpilE0H44UvW^tGsiPI`pjwfpdLLH7CNO7H^NXODl~JEd8dAJwC)uH$w_c>`htob?gPSpin2voe9anBR-iywMvNzp=VUB~G*&15;D-aUn z4dc(75fn*PX55txXOT1@!8rEMLTOOASGIyyp3pqX-2Ds+M~hTNl~$ToK@QLjEYg8^ zj8*}{*K}nDPk_Oj5ee!Y^{`7Omqn*ce{!9*v!Bqam?}#O+Gf+L_v@X5gPNeW!=S$! z8NDN=45?U^9i>%v5tdv1xd@II+^Q=vkvd*=w_7e5r&a%=3-)ug>ibzWlGP=VQV(g- zs-I<$LumUoxPewZYo>ar9RaPQrc}iMz!ad|S8u1)2L@<$EB*}9>gX-B`ePAVz0NvD zt5;?d>P4W1%jyqA!f?1(^{@q?)ttmVXWW*Pdfek@kINZrz-w?LSO2q6bw0oP zjUutuJQzvP>K~3(Ft33D)O!OlY)l}MG4lUIwYML3!cS{zzz947`i3LC#-ugZ(3-ia zp@J?`&(WIYI+D-RnplR`9E62p;-9mZv8rNuYEJKj^SRlMO{i zUOF;TZ%)PUL~TH#T^M1|u1u)t1_)?JYaVdQHR+ugt*HcYY`76PVBjLBy8kwF;RzXvu3xxm98lO0WAR3FW-^%C%~xto}SP)~|Tae^4UdUbibx0N4(7;KWg)o( ze?pbjYy08C9Th<}Y*@7Rt4V1=Yripo)&{Mu#}s7xh*4T<)pd)%TJd7$KTb&3pC=EGMPX-gJjyvQVf}#ALeH>K_M@GHQmsp7&EQv!4 zJhDmaegl4!btKs*VIOtfV-Z^SZCdwry}Wg&2awwYJ#%u>&BnVy^s0dH2vsatx$fMq zw@1f<08B2Y9tv~d{5yfv`K(88tR2n-KwbvJX;sM$HUA$pNbnrCJHPr9{O2`i7DvQBiW0VIljGWO!E_K6|_}7^fmUKi& zW6+RE?LZ)tvf+c^YpDYOgpr1KvEdd*GfYq17RAzi1T4e&KNDcX)mW9@)g*IY7XMIC zgb8@ks@fC8OQ^H-WXjMyqkKWU#0)$o<3aF3EmJ{LREfiac&j|pF>H(cb*&4vOmfdf zDNhRPk@;f&h_LDdG1~CBP{D#+m};@cB-DE`ga23Q*22vtHFeaIitx6qL@>>tjzmD} zaEyP+Z__MuY}0S2e02ewie;2+6b|#2!eOX>{GOE<^?59tHa;i}nlW^CMhiS`d=v#O zEFsuT?~9xaXP2y!kI%q?v&%fmGM|%>!&;ke!|=4}I-W!d;)zhiL_TU$EaF9)k#`$2 z!U+a5RZW|ga4SrfD~I6iRNCs+kdZ3$p->U89N?$4sSTMd)I4lz!sOAe+6rS0o3`-Q z;)ie1ruV@HB1I@gz*A|{pc|*FX1F*!{KhvTUU_fh8}57hO~zNXdPwlNRZ<=jT7K4;e)Bv$|6IX zUS_^&oo&awXpZ`5!MsVkMrqfL zQ-^@-n=ml?fJn&F0C>oQ1mpPdQE-e5^U{wT9P4U*nh}w_v`KOsC+W6FN2p{-_<&=D za#=))M?HoEUC=;b%qr*M_5E-9X_S6I$|@VAR7dI)Q`M2Ac2U6)Q{;hE;+Z(zJQege zL!*!3F%-3CJ;L;WW>uaN_CfLCc9|Od18wBtFo6*^{~%(PI!c@;65GD+v{T|Q(dLIx zD?@8F%Xc7n)@(wXpQd%EwQB%Ew1%hywpZMP_*)yV1Mk1dNI3PStJ`v^4jt2`F@`5A zh`*DJ=V{vjLho(;5mnt|YEfeUr^f<+GM8^l0{M%Yd0cT4DNI{#r!6OF%K$W$)OOP) zD0oQGs&%L&$WX@zIXv06H$s=qNYZ5ilijM{1^e0V|2BBk5I5_wV4uEtm@lver$cbU z@K9gAm+uOpk$%M`Qq=%?kZ9;PtYhx1kjh{(zZMJ(NoBJB4R60^RL^1>s2MNGb8l;o zgj00cE}ISjhXaVnsSNz;HF{0peax<7&jMhq#;O1Gv92So~rD z6uH8#qRLe@b`z+77n!$i$z0@RqutpKv}9H}d=HQ?EB}qv!U| z-#2t{N2|wp^t)$ly6g-Jsi1j#p{RQU)Cqhe%$X0Ni!nf3FS7dBY%UJ=xlg(10#AoS z{m9Frd@$kZx7rK115II@aLw#?WM6>B8_w-@v~?RyI=C5nz#bzELg>#jhXc~N3;{H4 ztHfbUPWsKOcE5XKYlgRRT7i=-vfsUs(_^wlaVZx_vCS$o`aOmgkTg<|dIvcPnU^Hw zHa@0I+mN@XtxwBCbn39jG=$QJKFL3_z{Nv@UW1Qj_z6MR zMhgZ|=z2-fyG+6cf~R34wtNzziO72k3aj~b_kFDEUufH1Sdb*7ghnzK)EBa3$aS2y z{fxGqLZkjsLT2SLRA@DAK@ps^(^)&4w*9dPx(|n72RR%Y4#jEv<}~m) zj~)Y|tV|f==ofWN!$bLL`{sy@F&c~1yEBsz0~Kw+yxavtTPE<2K~FAsEyk&CXaL%8 ze;s@a7G=A^fSin)WcVC1hXUsFj>bbs^vs4+a!S4)U&_LkatF@%VDVV&FgRJFcIz z^h_Qd1&4M#Q3Qu}Ede;R<9B1=(2iH#e7O8j_QJ?ELkpPDWHZBMT#lMMhy$FRAgCjOxUKKuVN@!KkdxsaGo-Z z1T!L8Q9|*o8^{6lrJesoJ3ohm_gp@Qyd7OxhSf)DCn~UEHFk2T2vZ%TLtwTOXSMva z^D7bB`D@zwbTXUO$Af_n=ocN@c`qc4cK&-(3Sl6o?g`;tb2tmLYwGz~7@XqYnWdc{ z(8-rw<#?aBz%2uV@g5^0?b;_Cg)}v5(}0_?$kDFrfI9OMau)46f#bKkKBDW0TA7H5 z1ePNd9W|2!Qui=t3rC zgzV_#)AQE)_!V^_H3d(vuMvWk?;&EHsy$99wEJsJnH`{^I}f`HnaY(TyPl= z;ptNxY{&;z9eX;Ms^aVKxyo^EAdA0=)@XGrU}Qh--4`(#D8}jepenDDw{bohhSi4} zC;*;1TJ>B#G!QTI#7q|i`b^_70bE@ zkr;V@14DosnZ48Whg$hCm0$I~$ge&Kog0T^hlc?fa3OZ58sU zY=p@ljLMVm^OMW}HPQpQN(2V79fep?(?}XCL&tN2cHx$w779z^arlF>RQ-iP9?zhiE95PwK$j!@!a;!J zT;*)@*Kk~Z6RKq;CxDY{Tx-7LcR=V6y@iaExbBOZ!kqF?xL`dVvn(1chu)Op3q8%FXtNZHbn-$}DEbXx|`S5N(2f zFYIG9yj33qj*XpQAp%!c z&xH0vRGq;*N}%LMGR++ThES467)ilp3?mGJ-!9Kl%Vv9YAyvk3(&^aHd0tTm?Y|2v z&4&*|JB^G3zlPNa%0F9!dI;47KduQppe6taMsULv=C}YD9SZ68OP#6CQ)W{V^V9y* zpnEu+$3Lx03j=lz$i9_-i|cRW+B9n0BI^&Au0Q<$Vf|sOe{4bF3oIy%1#zZH7@tGD z(Qh_GE=X?j?|6vX^6-^VCHXq6(`co+SOjTBZTBbTOJvwa$k|We4W`B$Tujq#_avh- z@*PsrR8o;hSzcr#7sqv!Fv5Dos#9rvX%=z?+|Ci~OuGo9V_}9#Jex}Gm$7Y*ha76( zfP!JnlS@yefAPcQ$w9}8c}t%GM8aHgUWt*-7=ROx8VM%q3)JJQJJ-t+`4sS9ua zb4GtR+?d~nyx{LC9gjaSC1?#`yxe z;s>A?H*s(C;k^vaBZ z3voK|2{>MSyj<7BXgpcIe@BRz0pq#n+DD5AZ;PSSkrj-V2QcaB3!7`3Iwz@Se5Xu& z6r{K4z+W}&o&xwYh8(#ly?n=j#mfSpGbadk&)m+@q|Asxiq3l?XZdnS*O;ChPAUs$ zra*wslPCw2i+4xhf>Z=^Nip~-*WgRTJmTO32KXKdw+ZMm9a0x?B4RNr+zz@(>x~@X0er2B8SXS5Wg)^5WuH!6HMQLr9Fhq zVLA4b6$*=`W0Xm?pR5|&03uijx$)~B{&gk@*#8WW4@}7I`ZpyC>MeCGD*51KXgK$5 zFiun6Pmz9EX%dMH2{~}sGjcaYKBpN%!VSP!FbFt~fEd}5uMdN#D$i4}-Uq({@GJ62 z68wl*B>g64rjRLUjUVq3VCW!1D|8XZaa1~}ztRE`H5Wf=^P@{xZ*os1aXB#^+^Y}6 zi6G!RvR-F}=VoAU?#GnmD=pF>FyI!~dSwH2@Y-aeLvoYWf#TO=@xDttd@&du%-|a& z5SQUGvO$(w?%GLsmi)D29^Qs@yR6s9-OkD>P6xd(Iq-rbuR@mS;KTY`xNM4iix7YLUmK~)un%_-_rby3n+8~ebPXncKqz9CSvnx-spmEn^(D=}@ z48F$^G|thXOL1nM#Xk?aqE$TPlC`Tm5-kkm3%Puj-KKa52M!ORV4GDmeuThu=rkSr z;n@TpphI`}sYW2quj94TFanUu6LKjT?vpp#eL`M3^lduyZvb>Q;F}^j)0OVmU%#=V zJC&6i34ApNU=AT=JgAm)(2kCV#Z~9%y_A>-VHLYV@8sac*5al*bi z$7;z%e5lJ0H_^f^q7Kh_P~*)BM!+PIvu~odk8=fCG#izzDZH z7W(Upf!4aRu0UP+q^{=g`Uzg6t~-Q`w*F!}xz6zS3wC{-zviS1^QNxvq2`&tj4LLF ztLv-Sp)krosO#le9_PVi@vQfaxQ^FxMzQO-xGYlhKv8@PBAhQMjD+ZXgcD_mu6?R< z)H?xe4e;9b`P4P;vuj45;cI++qX}#ojMWx-PeY4vFa}f*&JSmGlf|qqJQqv5VcZll zJ&02nT*493YF8gtk#~U$=oB0TTQtR(|0vI~H-VCic09di^5b7Q6>ZC1{GC(3h*-Q}=hx`QziSH~)I&&t9KY`&yN~qIT%I ip5_0L{q3cn{?Mb>4_tNd_!Wt#zO&`y!GY*kZ~4C@V#?tF diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin b/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin deleted file mode 100644 index 51aee095916cf106a36b356020b0cfb4b4f850c2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5365 zcmb_g4R93I9lw{meB9-d+*dYr66FR(=r9f8BUq@hS3;0!Bi%diV_*aOo-w9W#0i0l z;CQ=xyNQC1ySWHf3<+RWw15;*8SIFr6I%_Fp=D}XIt>LW(y2wEtw<-N|9y7{cVQ1g zhMjEQf8WRd`~TkW9Tu=JFiR*UrjiKH4|6QG%ytmdsR&<qd!QuN@Cow%05gPxx zZuTA^8-659FO|C*BK_sv?|j88LlDavH;&i6bbFAT%3Wh--D2Bj(v*4*UGABL7t%<6d#n}dck8Q==cKnQA}toOl}r6Jk%sNUrUK_vfgi7uN4Eqaci4VQ;( zJE$Tml}ONJ{Y&r*5|RQqR}4gFR9011nX*6FE1`huhn1R2+{==p|3Ufhg)ch?9E*Y= zHO%qXv;rKIGm%=MJE*7-)}d=Hz&Y0(&E~S15VV~A5%6s^_t_WAvs-2|fln+b8H8aD z=Lp6EV zt$j^eT3@&SWTkDW`SjL4l~;GLEV!>$a+VTv3)TJDiKllN2}<>i(mgLIIbiKBy7u?K zA#bMU8MUL<+JgcI#cKIpgvWMb?!!nX?n_}#42lk7{$m7Q;&Fn08sv;u)w~F7)Yym9 zeZnXXVwn;Nu0ZJmRf}<2cg9(G!W=6Q%S@4Y?g?`m%M$aipo_)1#$jMOU=C!C)Jo0G&gE99bl-r z%#b`h9&f^illO>POFXN>TnrLF?-k0$`Nd}|jZ{hXWvaxJyn`g~t+qCzZ<4Z1ils28 zva+G7jA-2LA^8)j?9WOM?oP=uYBOc)`C!Pf{rY>2etwjxS_s<|HAM0^WX%?cq@j%K zCrq235cx;0N(dI}lNMqAnM4taPEwGt|0WlqXeL(HxCkXE!h+4?Nt^t!7GVJtVU_?f zSzJ0e=bf|f?Vfs6diC`RtJF07_FH#5PM&gacy9Z?=X)v-l#Zzet@E#TIqZ2EB`87( zS~pSiZ$b%546&XZr!NgXA>Tj(7f6u6wjXB04cYVedd`mN`J3iUV*5F9JOhV^Z5wfl zVI8wvMnSg#3c9bUnbZXrdhc&)S<|$#v1wJHsd;(p>Q#>?D;aw=fI*^Ph@n^jBUmxr zsK(R!R60Mpv9-5v%e$9q{FVLnUoY-|{PynkWm`%ve!TP5rGcq)d?jKG1)|EIW89H} zyKWoa_f77~C37FB+v71^w4eBV?Y0+wwq((P4@DU!{dVi{>%l|k?CXZe6luuH{%5DZ z@kw+3;ZN$Dr+s_l#y*Te;sOlFE>MMgKv7NA0x{6otZJYzJ|rPIAo$f7@r88T?pa&9)5+nh?OqB`R4yvmi;CBsqx#aP0Z=^eq4zvt4 zjEz12h`lc>$jqL5rw&&LKdyMG?^Dy(`jY)KzC1D5R((hBjJXfrrS@JZJl6oJ2Y>YZ zgwjobx}pWN#Kr~ciX^)B20>k60@M{d0Mr$dqAeMquIP;jDSBf}psr|m9H6ea;0mZK zYNw#iVjQg`sLL9LnI0%vYXAC+KkB|Zjjr@$p07Oqf#e~@zotuX>}cjm@h5QWQQC<| zfgPjxs75@$)PVsEoWefrZF?#?@~_Jyih_M2pyd)v1YYV`$YoTGFH`_%jgH>?mqu2$ zMqXxb9Xc~@!B5J)Jv#0$Sw0S31w6vwa!)D1_YyI}($5M{DF>hLj)R@PDe{7j@+Bn5 zfemT^kH}1iggT%KF&2>mJ%Wg2Xpo9~5ccZX?iJ0dz6&TzF6x>%tdSa?zo$mO`Li%S z+WK_hsnf@iADm=Z%pyY^;y4W1yh+C?@W4i&pC$7I;@B0@Clmy0^)uD+UPPbIXW3Wc zV>s9}36NO~u731}4f}7#!QH9Qd%uYEdsLwigmVN*Ayt9vwdPl!XEN_jIdKNOUKT}b z-g)J_^ByyQdF=GTE$_duZj!%c{jAg7GxzT`Jv*W2)&pu>k4^{!wgF%WcZY%y*ksLW zv~xQ(+LkcdxtAJ^;Yw#1fSYW!T?lq6NDT4td&D)Z9$Nm;?^<#zYJ&e<%-orGzbF0+ zkEJI^o)$KBJ=yT@*FJ*c3h5X+VX_TO<{@civ#XT2-)L^`voqMW-qVPY_YNo467E7BXkK z%V=-At|CIP%sqv6bZ(As0^X>TW-2J)iz&JS?tAGlakDY1KqvObArK+!Cw6e2`jHF2|TWvvAMiFaco`M_F(Iy ND;jG}1-F@O{|822WGw&y diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin b/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin deleted file mode 100644 index ff7f4b086a2219cf49af69140db24f0978d0273f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1969 zcmb7FU2NM_6!vZ0AD)(OsS#qLW-E*_F@CmI)4D=Lr%rvCbmOJTgeP?FVh4hv1SQ#^ z2oc*!GgL8josw?dUIs#�#(Eg(1d6L0TVp;O~L;VXy~~m_$KrqYLNSi&s#jlxxZU ze9k?;_k1>35Y={D1564hL9$kL3i3#pNuT1|Ff4DjQibX@rJqU1lUC|Xe(?{4`dt`d zB!_Tu*K2_ABEmZ#&%cB4N8goii|>!1%HIC>W`ssdMZeaspsx$45-`G~n+W5p2Py8_ zfG|C~p$nnXGI)C5PcPxF%cwdak4gx?P3m6C5RE~ft$|8(gq9oPzY9=&@w>?n^@+a5 z!)zs9S@}d?y71QxZyS@A5;`M`h0v`5(`v^Xgr2dT+VtLB2<=zLJ3_$WHa*S2*|7#qcHiT2xY}G z&0x)+P()mtGW9U@-0Ur%}e@^+`qzCeVP zb@BZgb~dP_4ZxntHgPcbprM=4Q)+QlmUSzc0H_HEHsv+PmPK)1QNQY0wkid(3f8HzRT0++5`CWHNAmocqoS{qFx@D>0t zgv%;nT`QsrE8eML5@vlrpTauiZGu;w45X%lok0s-n9Q!zgiqm#2>O)Ek6wK4W^QoD zD=$B}X^-~j^z40Km_Ib?5m>st=RkDmG)K;gF+s|{uX`t9;abCnnrJhVuX|nIa_O6^ zLG5jTt*x;*(vOMBJhEPKpUjl5aRZ7Zqi49;>+y*tM_#HDA3M}mI- z2mEV}DHpR0s#Vb{_|cug372%+4r7v^CueL@A+Z?;r-o<_VLj&)_{WkU>eL8sjCLZx zG7MITGDC>yPK*8cy{?8f4zS)${=dc^UNc9wVn5DrpBedereY~rr75a diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin b/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin deleted file mode 100644 index d23f1cd60327c9040f416130bc3c6e73e1ddcdc8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5009 zcmcIoeQX=$8TZ-FN9jjm=kC(dYJC^7Ax)}Aamz}JI+L(6Cc&Jm;~Trey>IO!&6@gB z+u7Q#lkYvBgGO6+XRkw`2?F7xOla&=6QF^rf`CHNCNzzqZH)*FG}!)VHX*{&?76dJ zpA)xqITS z`G)rfSQ2<1;Py`++XFBPFgn(MnkDTY*>L982*6(gJQ!K~I6wwq%6OM&$?87?Jhb|Y z8o(65!_P+UW67!^fOP2MivYa>4 zF+ux9?2iss-{fUV1>B60374>zLs8t46Q}{#RzoQ2CW`8Pqf{swjAdGasWSz$AYe?L zTdb9@W9F1(C)NoCqov2PH6#nzhmnA1aacxCo+HgSiZbosNYkXKRs$^|8X!&ig^#nI z%m1c%jpH=ZloTc6Pl-~bHVG7lHO{2OKOjmR@vmsy!zSLOoMVCk^TemwP8h~=r8*ZN zzTM&_Qd5l|?DvlU^NwKWyGPi^_pZ3tcw!{4{p8~x^sZ`oskghZ<%5A2PV$y+ z@txS;-;102A(^n20u;QA`dwyVzC4Vzz*x^E##%2mX5w(4r3)D8jQuhEeb^&qZ~N+Z z4_1R-h`?I_`vu%B&qx$*Z1c_vo0QQkClx*I#5XSHi1*tu2`9iyw)M>6v4y6pPoPE- z_Co}i!`*Pn-qI8K`gSxjoFEwmWmFZVRW(_C--B<0w`L?Wk|*Bb#=Ri77c!JmNaAqW zTLNYF4W`lFAvM0g>?MMmqP+p)-4v4+rrur_XZ{-T-*1|xj%qDcIIF-b>TOwy^hKn;IoG(h~Hh!ngO z8=o)lo^N~~Ne+~&Xlxrqc zv0DOV>kX1-dOj)I_oVql68s33qj`#S?1)LcRzo!N96Ps|i2`ph{dMihQ9irv_xq1O z)%B-`UOwIZ%(>O?yg9w`r~g7Pyl=gAX73-Bcdqux+PJ68_~9CFc0lufbKQru6rDJ6 z_g1s6W1ZIuKD$rV9W_bIo8|cdr_}b16_1LPvSh_BQR7JK2ckCj25@0^UO4k_Jv7Rj z{n-cGzI^(KeDiO2O`ZMqfm`o+@X4t!yw#~3-FfQ0^A}ExPreTwvM)yk+2O*6spG~b zHzyEqgPBDg>5%j#dNP3Sn3AjPmVeN%c@K>JVPF4IKXddRb-(fCQ|!+^uWZ}=rL%uO z|9sL}i$*s=9TH6;Ahjb(N_ADtGB?3z+?yb!W=LjGO#(@yG&!JDcf>NSudA`HWCl}8 z0xjHX?k%=-iG=DFpS@wAOMz0FDwTZ$2B9_7eA z+3wI48E4BkTgK%}GVX^Z8Rs%{(mcs)qe3xXQgu0|Xcj@$mDQbF)%{O3b(@NyGZQqN zQqoE?v#_S-_X<70kt_ZhYdF1i*9$nTCg+VTSGaG1_FPP4ZsM0w7)&%&H+G%(k=47z z8ai>MuL5}>a5)-U^gW&LlHo4=jyxar)+-#vQ4Sa(bIzOM1NpPu~H zT6KRyoN(AB8#w;<6BWmGfGmXO6kmf!5(MkiaK5LPlkae!jJ;6}GaD?-=zJl^k+x4n z2_xEWu%zvEQOkqI%rnJ&5$L^bL zj&sAV>jd72!{E~xwY>{{nnf|Xn-NAwnLFjYKFTlx!&An`z&UFv()-4_g}`1J_{xf8 z!{Xi3!BbaFT=-3V!;9;8oYIelK6{o10@EYswvRve%{L^PYbR~Di;)P0p0oHw$(pZ# zrbD3pAemM)m;b&Uqs5q(Q6O!fi%D76^y)zmpBEw=hnv>xwnHU5H2cWtNElk#(?Y8ZTYE z1|t>mYPa9Z3f17zl2C>J3)pIu;;^--zATm#t}jio;@O-nCiTkk91iB#e@S7jJGudO zrdBPtx(HM>95ZE~8I$VP2Q=1@)1G1%A4v=j-7W8J^w;$352D-MgF9Ix4r|nMgDs;zFuWIe`)%QD?@x9m+xMX72W5s$xMurAat6B}#HFVL z)cyAgs-}71dYoX6zYIWVOg3x?8Kh^a8*a6_R38r|n znh0M(bIH0>j{wySXl6EV8VAkx{DPTJui6Gwe8*YG$5UwjOVvD)iSQZ`UY&wNB)Tf4 z5p+7G;YOJm3Qi#2(w!jtSo5epEl>qwoV1dlGH>YD&9KQzW4>dnFk9|EOdtW#tvpm6w0=oX?(aV=yp#Ws}g#YfH!*X_Rc zH;+DF_SM!u-1x#1uUz%_rg=YO<3^`;O#JB2PnwEpBy6g{n2wXetYl zko(b)A!bdKWm%=YFqofYA?ApVfgI*2n(O!y>mU{h&b7Z@P_RgMdU{l;|8&9)7s*vm zU;ozKOO~WpPJMUj%-L7gp8s(D>$mKqU}2V^a@K;w4wBFwBB5)0wjD`A4;~EkmN1Zv z8v!!T0Hho$_DhZ-_DUj1uQ^%faus7^fW(N^kl@2AJS6%OSHH}3s^~Zo07O#+9t#c| z{7f}Cz)A3*9OHmSK8^(s_C+rV1o6fgMl8q-5_~~rk|r?;3mTP;XblNvRT3I+QUiJ< zGzL0jNL8H6&o@Le2>_-o%b%VG)6)h`V*%N=KRE{`=M0`qpiIV}?1IUz+$1vsU_s!G z8$C5TOi?gGBnZwcIgD#WAfZQc&}4aR4%JdEsakJ)uLNdE$l@G8#e%S1bw7BcspoQS&Uk11A*RXe1n0 z(kyO|QBSE;G8xkVYlOGJrdzyCfp22~4uFLsdz)Y&4l_o=harMgU6s-bZsi59m4=8D z5V(3o+z1L+m_)*-GiK5xrOQ(q?6qArk^mPDkqrDbI)HymHk#ZFlC$s>vl|ZfKzBY= z<{dQO&%gVqIN;g?CQ!Wwk5jSTS#Z?EYeA?Zf$Mp zz_U12iY)GG?YOXOQCsJf%Py9dEK0XFdvw>fwRd%Dx8fE~H9oPZt)sJ*v`iRjYeB#k z-}sS2Dmulp7C@wgTApJ$y^;&wNJ<xu5!iPG-<=>k)`rSK`|i%*-XI=2D0Ea z%RnZ)S_~fFv4u#<9UR4zJ8Iv?>(Bjs`&|pJzN_!A?PLCtX=?c(NJh_A0gn)2CU-pZ zM)?PKpXz`7^`pl|RqvR)`?s&YUJnEdfdF{~Kfa-E;)|Pm-R1XusBGTfaBF{NR0s%` z13|zen5{pPcz*n}>*onCmnF*%>{@V1WC9Ru0fL}Mpl>=>anZZy?b!6YuG<1HfA_YU z`}TYS1P6g21O)uR=}Uic#n&HrvJZrY{LwnnGlne)bmZY#{1($smE3(2b}`a?Sj5Nc zxcyFr$mA`*t zb^F*KL^qG#y5zBWElpeh(=>l;9p88B3uGa}s)!V?m+j3`8ClD#!wH(Gg>$d>R*r^FNyd7u1UdNZX!* z^(Nd1yA=2ikB-a@QGc(s`MnOGKGK%HZ`brgb@Jan-g)4GwYR?&8*47VA+`2T_luv+ zd%{z0`FJoN;^jdu@saZFB-+M35h90%!#qn=`~^y5h}+*nJuA3+cz~x+&w;}$Y*2}# zTSYaF38ME}sF(GQRE0Sq(KWox4Txu?qDz$udgu{3);#-@iiN{~5v_svRB=ev2Q(+z zHa`=oSfj#|&%g){CrPxxSLF3h(IS9U#eNmaA|ylRgea3mF5F)rL6q-;1c8GTv=q5O zwY%T>;@^{ZK6_OA;e~&!@BUu;P}9kY!L_sFU(_sq=k&eL{$#lcKp>GC2T+vY!7ArU z4;6BZKq8YYi$wbT^v>sV1(#VQ9$#$@=`Snp^DrN|ZyB|glXGSia+t*J3ekYO(+pDe z7VjE37$lKBDi{hb5l|(;4TMCVbU~YyH*+CKU=P%F7$Ruo?Lkx+L(&G)tVat8#lYbp zIVUol2L=}`GsX0-b&Gr6j2v+c7Q_!C z2)*$0j9Gabpe6bvFceSjq_WL4{ccurp!@UOY+tX3Fn@__+dfU7lm(iNgO}{Ia}4`D zhI_3X!(L#B1ElhhmGQDaFy|fzcT2!j<%vwj=h-jy0?+>qk}4X?YI#x4E$X#F{G%HXnx{?Vs8FH4He2>lk zmRTERHEKgdi@m5?NlW1a{0>TD@I7G7YClwY@JqmDk;;_v%Q<8#28BNyf@LgZYm{e> z_;*x8)@57C7)b8PAO(VpZFAW35Xyj-2hrFEU_57ae~vQ%YA9on6_^9LrNM!KZ(22F zlYbU)A^kd>NqjaiVf}qR6R2_qv}}k*HHr85$19i_E;m+&8#=zxpCR!r7Kz`P0toR? zII!NcQv9WyMKWNejBlm*vD}z%rT9s|+XLXjqv~vgK&|mJ{vf{_^-8+;p#v}~xn~Kb zO9w&82W{2OK2InPs3-ARfihO$q(g1Ukr&vb!b7U&av#onMAc58xg>k4Dqz(xM3agL zJ`ljlsy9@4yp@vgQaTM7HI#;|>e|74DXG3#Ju3m@1py_fvQIzMvZ(#`jydDvi5=RB w1G`Qg%%+!C&slNP$&+0;+x*_Kd#0|L@xYg_JYDx(OUIpy(=&z9F=6um0Z1vOYybcN diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin b/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin deleted file mode 100644 index a9e9a7ae041de8687d8f99bdbd5e925f28dd48b5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20724 zcmcJ1d0-P|-hZcQDU_?FP14fZrY&+Gx#;XCyIg>9-t_KsIRW#fv{qKpXZrL(zNx(_m3awlV_fpd5-UW z4Wc9#JH(j$1T#e?I^EKFmpe~9mM&Gsjox=4nM^TGbpIW(9L@H z)u++@3ElkZC(P)6hwj8TW~Qb(YB z7~P8dXT6K=Tj*XsCx0Kh2hhEuc@bOU71rH1HVfT-=!(%jTd}1)-4*tf z2he>S-Ib4yO+j}jy0`wz-i+=;=&nBX*e~ebkFIy&YnP+j%DVqZy&m0-=+++1jzPBx z-L-wb-hr-$Zhh+o0d(!GYkukqbT47u_x^ec-I?gVa^iFpx>M0T-fJS;&SZ2?pFh49-SO!D)N|x- z=#D}6Y_B;3&>ey9`MBsNbO)pR+tF9pygAOwwt3t8pqIgkfi7|{bW!>#)*N6>J!?|Y zq-m^KjHdsMXi|HiNqLtwe`3uX*0ATSRje6+#&Q%*(hID)4o$xwShImOb6I0Sljvm) zyG(ctP2W~DeI91b9jwVk(|Z$ZGST!r$C@pyS;?AcH1T($>G2$E*f!$Y&~*EhH9J|8 zgeLZTG%*jb#=)8lG$u5nfWNJ2CfQ;lQ-9||7h{HTtSc7hi>6eeAMeNHk*Po?6V59R zK!29rC({BNa0{EtNdsEi&!#D6iivfSX@yJ|y}i&?&IU|BJMrGzUeOkClj-5AXIAtL zJo(C`2i`bz%@)UzBU698?K0cKCv*Sues|mLr?(x5Yv!+3R7JJ>bME{{yMDc?cFvp? z+cv$lcz@w9wp+iT0iR&);B@zt!z76K!PAbWe1bscy&OC|9MH_0I+3u{1Y$ z-+kUy`N7DXDd9`EX5xoksGr~6?)Wx7)q)~ps&cHQ%8nmgVp|AqI?Qb0mni0D5nzkC zL8h2l08vIywnwSV?{SDWkD#fVLsn(MWl}LuOrFYjE~c4M6^mlvLZ4G?Kj(84vkvo2 z$Me8L%o`l+6!RWkd<8@6CkkEcS?Kap%=cJXlzc*&*k(}|x>U()qSz0eb_tWmzUZ{8 z6gxzt*uIpJz0ieDs)sTzTj+97Y>q-1SF>IoFzTn++bMP##r~OMXNkqtn2%9Rahi$E zO0i2Q)+LHHLRn=S{;;u7N2QFr*}0!F=)!m>;FYn1N1S$w-5Nl%iDDb|waff`VfN~v2<$_M8K zaoO<+>NZRVZntq`brP011-q%+41J)2x~-7M{$c6_#Z5A#>$R+fucKqwG9iiQf2Av+gIq9Q^gqI1{hGqOes|pEV7`=2|*%K60H>1 z09nI?Qk+}I2E}a`MGwV6zJ&%zDAq^(nm_!q{%)B@amU3>MG!MnEuu~E@>i7x+3S!! zLLw7jiVT_KbvFs)1p!NSlx^LuA=wt3T;}iPi#dwW4|wnIr0%oSd~lsC#t3r@vSYdjoh5^-?|_3Rt?)z|0eC5y~vU)C#$lVddzgX?9^jCrdz`i0uXYO z0ML>h8YF`lBL`>oSr(mh2W0BejlI)Mm>&G zkB@2aSy0jtEUj4>yyI6pHP!8sPQ8Q7z=rr!~o0T6N z`tj;^{9wvIa<}+-5N?%O<HK*pE=dkc5r#3Z~v2SX^WfU zAyzvI2&~x_DFDhX;dxn)dKQTW6N-Z35J!u@q%lnfev-;0rq%qKta=5nSGdxxD1ujT zh?$%x1p#`Y+z!5Fdr&cp zHq0OvyKUuWGutu)34kPshH4LPL);tIsQ@)6I;ba|=c(6F#^^Bu^#tEQ&8p&(JZN0% zHAUg7T=Zh-zPtwNHDA{dy()C|+iNimIkeE_&1;OH^R7&m5S?o(^=ho;mX%V#1r0V{ z`EKmPZ*qwcd`@ivqt^+JTyX$eae6H`AjBm#f?xGJ#5Ofx5xqX#xvyHk^8&yR4eM9k zs-nssS^QiUO#VgRQ}0+NOorYHtWobIH}y^paCs?FOft+r>ILhu6RvuX4{HzmW<$hC zA&yT~Ws9m+==9?b-PRO~THy`}NlVq*V{w}z_HUgrS7+HI*F zS=SmlP*HW&7xiBW&mOlOC@qOz{=`=|M)gko$E#;%m4E%wujQA-Zn=z0T3wm@0~+-$ zqQ3L}VqfsM&mkTYZ8e~+V?JmF#+<5GF^R<>H-6=Zw#Hq9Cq+pS9B#1{t+-eAm^A#_ zBoFLf*&+A^Lm2m6vp4`hHzqpDd%r&Ku3EEegKNX${+GG>U%CEr zaZ#E$ojtTfJ@2wtU0`2AxtaQYfK?!sV2k(_+2Jjd8rlIOArJyYkcccDA(G(h%#xrE zN$lvCXqX=mW`0k|S#dk6rjKr2pZMQn_J3_${N|XH*{mC^4~%eKDi3%DTcn@}5us zT>tdBz2Df&`fQ}KtS3$Hp6ipbde(2*YbR|EDe(wC01LFiAXQ~}2+ZP2d_*U7(dh zhkjVJyWe$9$3y{&5N7LT@7Z>R)pSQr(*YTjXUyvhqDW;{Hn$@>b8{zs((i8&G+J1t zP`_$jg7v#omtg%GbqU6Va;N#I-!3lwsNWu$M&Gv(B;N0H7)Bwns)~D6>i2=lg&#y5 zw#gM=<(XZ(v<`>s2=1f=L*gW*gav#%2nWv#7#r3HAZ^hU2H_LeO-w$t>6VQjpNP*N z(z18You)+|cgueoVWwfHHyf`llK&_KxxD0y0qj($n^eK|mkzDlEC!ZD61Y>Ebzl6@)( zVGLOsgn&MUFJcNxUgxFJXJB5-Wt99>cx6i7h4s7<534lhJZuX*c%NhI>(H4tU{JJvWyOpB?teT1693O?|dochdBk0`jV^z zTFqr~>wle5(`{c-(tA~P-g#HAYhl}3{(sn3h=p0KqB-Kq9|7+`#1)I&1To&|1M_QY z1AI-U2nLaeXs*~5JQ(FK_F@H$t;`5dQAP&00e`a$x9|HFNW0v0BI%=pc*QJqp?1&heI*!>y9_X@#r^Z)#+H726Hy zUOw|X28cE`*|9+Zavs~M zrU-E6tS39e4$yDY{i2XmEEikTLqe7dp>{y36xUuFcLAZBQXTYSaOPI##$Zc2qT38M zVvbC)YJ-6-Cz>hcb*DR(#Z3|^_Ory*ToL7NvVhzAsDEpgGGaQWBg>1%y75*|HX;8GQu6y|0-By?Dul!bM&99oVruu}ppo#GoRGMg3=BU&U!%&)&tp*q$oS zjy&~X7~!hj?50#iu5t^^;N#S#3tb-eOI>Mpp_uyLOZ@}7*6P2J2EZV-b9F>%E@%)O zz)$_3^+F{wDFe`3R2IIn$xw&kA?QVzmz{=0He`fj*&`Bv1VLJM(c1oEZ|G%4j{N?y zPD4>m+S=*gEOT{R~?t9$1goPOfM< z1asAdLrd!)&i-KY%l{tm)Pdfgy?rio$B(w>zR=#^ch%vmKN}R~4m+RiVliYo1$!k% zDoJoBQ+lPdL^jC=A5Ko7^!Xsj%H99a{%VkbqlAa25!I1OOeMyHkK@6c*n_65gHLpN zu%ig!o*1KBbUgYEWUW30zen$avio0%%)Gj%f_oF5Kyj|uwrQW*!PuH~4;paWMdX1YcyQ;bU+ z(^fnx)^3u-;3OeAD`^(ZB7`pC1VQ{`YlbWUX=;|}@NL-Trgl$oR$giSOuQ%M?2enR zoq1E^k>%;fedSC3qa;)2M(4^|($luRLkcdrGU}E1y!ic(Uz^)|B)iq0nuX`^1+ z-r%ph^?S$mR|hO^@^y=0x7ImVO4~l_HSARC&TY@Ha!0>1&~3isnV;FMI_Ju#-|zXK zo6k2rdidRsx+U+t;>lfy4rj7k9;dz1^r&T-c#=mz_29D@quFs56K|t=E3nqh8ddxg zY-zu7U{#EcxPt0#cdvKE)zpZq(soyx+U|nsQw$gjpl8y87kOke^dE2rGMM643a7x? z=gerE1{&e6u^XmGkQA78sDfB*VvtzCz7fQNd$;TM3)yNh6MSlx-+;d^`N_5(bOpNx z)(x<2%hworvE@Wj5tOd7C2oiWQIs7Dx8C%W21JGJ(~zhzDUPeUKU61v9h4G$`&rQu z50sQo6Hi4xkQ4Dh^4o8VUj-katSMyM$_x%T=@3xKly%f8Mzi1houUap*E=guKV&jQ zTpJ919o2Tqx|!nEgV(aEC<{?W*>TOK3+B1!EpUpjV0IXw*T!G><=QWM4E|Ewmj*Lc zZ~*ppytmVM?@6*DCy4j3<%svX&#hhB#d}{E@BN2tZ}InLl+TWQ@1eS$9o|!sBr*cU zOaf5$a4M)}zvK9CP{6Q^*#HEYvgg6=Lx_*E%Z=x*(4$V-ON^*f_Fs(~tN1TyB*?m; zHQ2+H{eVK*_v!*UGpHY_U>7Ex+#MtU7c$e62wRGBmO3?wvOn}w_P31^gF?3YyF&%dxmG6sd}0hE`7D1)me}9A6`3SW4xgI83UzH4UKw zkZ~C@K-e$5;>Zml^`4pPL6D}Z__zU7xllH|OnNx5wO;WcHu^=Be`= z>)!pFU(ed)oOaqZQ3z<&IC*nZLjvV|$WCsT(}c*W^|K0P?o{y?F92czL=b+KB+A)~ zL>9bF(5$}(DRH?%XcPhhp0VJWGh8RTgXGFNMF0_Y&3eqx0pIGZr*L9b7^7lD z;%zH$_wx1_YhgLzhjFRCV|NhML6WkJldRn(Of}vT)k8pR~;&fT^E&85Koy^Gj;wiA$i&;s6*+my;JMCD* zapTS}jJL5(rc6Tc5oEK4F22+`#q23Cn=R-kfm=gzvQr+3F1`_JtMY@%-P+~E=;8+u zvRbFxyrP({pE3v-?l*McwsLoqE=91aY@xxIu^m+-RK+4x2$>*APlE&+)VDc2 zw3h~DY`&ZAR!^JZ!0onscJk>njB++2xg+Wf814`9Aki&D<5+X%{ zN&e&Efko$lQx@(SbgZ#T-GAW8go8KVc9(niggd5Qa%$wL-|~kp&%HVEwxR3YZ}j^& z6L*87a85?m?LtqDK27JRDubVpeq_o72QsN!m`-k}2DMk~DKdsqk%wiV!aBT%c+B7- zc(-#f21u zV>>#eftN0H^)vgK_#IdP#<1UZG%uXUx+eM?r;rg91u2{_vLMRUxPWxJ9o^QZ3`WRSKZa2p5K~}?+$DQeRw^Ss8Gg9Sz zlc4BDB7%ewLwG>PBanryYk0tu#4d0Wgqc+ux(1TQLqlU0x=P>@j2`N|AnRx}^n5rr z?X>`iH1rKG+0rp7*z@{FZ`zFWA)3XO2UQw@R+ce_@@c4MF)t*pa7dF}z35!Pt4DPk zXmk(GS{}rxhh;M&qoFAbv$+SIG%VN4uNp+jE6}h)nT8H$)_JRsJw3mgU;1g7Q{jhE z#bb4-kr;Lj&X&K>)d;b-R@g+tZn}%#ZibA!Q)r=KzBT-ssi{U^BNMqTG(4keO=CcV ziubE{FbZQAOe59mrv<(&qOBHD4cMH;EK`YJk!27JR9ILl!J&sj#8y_A5W2CKr!H|_ z%%rt=jA>~`fig-QXm~E7Rm@H=Q*AVSGKldFQ04HsBowa^a0bvszDmO@{Ja{7hF_`C zc$9|F@N4UI#2B~;#V3Fi6XibWq~Ue7{0Uekb;1T3-crvm8)*0zkOyGgOv4}6djT50 z8$Hm9pN1pV!yt=A_v>RC4Sy$e_v3m4TVlPio`!$3mS1A3GwW$WyiO>g#6T`jcB+kD z7Uy4tjWh&9{WRh-KaH5Axi!jN1LDy2mQD${!3Erix%v?Ud<1k17II@lmlqglTPgEJ4E|wz*)?pwJnS!m_Y}(N4{yWKec(+zM zLVV-HH?RI}OaJ^U1Bbicf8zP_@*mvNeO;;GQ9EhW@ZZgBjOqr)ihZ6&?bC_ns*?-u z2JGQbgqVz(x4;vP`dPDgrOe$l5)12PFS+r0*$c*yb?s~qmOwr56IvqLoc`xN21M%uq zQW-sM@x+MzaNcPrF5w4EXS*An6Hx-#E)C_TVF^&2x1PC02y1rTO5bc4Tz{kjD2Sc_ zbQTZIA{2X}Iv|8%+18##0HiCwK(oUyz~+Nf|9%2RLfv^VvcnwQ(QP4r1Nqc6ML$l+ zlj!Vp(3lq8?-JMs$9}1~ zXzYP%rJOrYY6VUdQTrdx@4*pZ6%%96pvoppF#kVxL}Q-^fsMNz$z4PCj8jliJ8osW zirO(J7{X{Q3Y}3=JMKCNRfKL(Ur6H~rEz-xr}5gQp1Vt27rzq=H}kFmG9sdzc{jtH3Pv~G z2ze$@UJWaH0-3W)4=GTMqHKZkZU^O3-d3fIY%7?y&D$aC-2ml1h0#1zo(0@4PZ>*D zF$5ex|k z0avXzf%1p3O(E!*Kgf>{6N(`(xD%2;LG^j-s;O`tmRAE%=J~6fYrswUjMA}*YLu@F ze#%b(a@SM-HO>}Mp!_+Iodd7Txi{?hRDSZwx&04rTkIG%vAC}nRKd(v5r+Lt9(2mp>+M=) z2j!nYWFly^f^t+D_R9Fb7zv)|I!o@5aT*lRReSC@yvX+Lpz|9({?{(s)H4-X^Y<)m zd$8BuY}dpOM_w_a067J9jTiv^>BXp z%Y1{jwLGz4$QYaimB+v?fY01391;(sC*f3jkDbAopf$~e_|RT}p3jHNI>?dWrIcp! zFe%dRx(3%aT(6;Nr(jsBH2oH=)%(z%wc_z$-8@iGne)#ZjxyS6M@z6Q5SsL}5@=@C zfJY%XAygw{oRi{$F;2HAIuKDzV_WSQ$((owv;lcMsX#OZ{ufEC8@>ROTxMCuAj19x zt7CW?5lFUJgTRE`WGq{TUyGGPkfm=$HnNvJ)`laA61zO6Um`05XqF*6W3hTFf&v=w zM13DB>q8>|DMq3(0`LX#4#?tNi^kWpYAj@rG)-AD6BG1IWf52;usR|sLF$#3ule*?? znDMFL7AjbQugNaMOLz(&m6e5JHu~$vHwU3=59E|lQ$hvzF)`Br*Tb8`$cKZW$mxER zm{7r|K&8!-fCC+14~7%5*})jKCRSNADu7DXXmX6^LGg+yO;dQX1Qnw!Q^N8TVkUx4 zlask|z>TW~nTCL5$`_g!NrOzUAjYO6Jd!|@7hz$1(-51E>LT_{$>at4t1=KG(B$cu zRkO<~O-AGmUnF7f6}qPDdOFn8MNW55#B_nsbZgLKNWx!6b9(k@@@bhSf1+=9$vaibGv+i)07=fyGIlno6v1ywr@Cn z({7EfayL_|fI`2XyYZodAGw7vZf!7ou+wrnq5+ z2gFQKaCpmM!Kku}3U&OeQiDAp`K-)mfZxH&9t-DTuO6hZ3uid(N@7_$x8-5OQ(-Td z{mfbb`AOh=Yq^F`o(l0%PUWi$Qf|hExZRF4b23+7JlW5clgz$yQM>{$iH=7Y&q%Q$ z;BTP9yS+Tx8Njzmg%4I!CX5#<+@*SnhlUIHfbsUT$WY-+`bSDscu>_pRBDkVDm=1= zGT+B!RCrS3EJ}sn8TT=E4wK%*=s>VhQCuy5l!_8Gnt`ues3;Ys4xiw5o27}024W=? z!!@}ZT#_$=ie@n)=6{S&rBr_&(>z+BX}#)iXr?0fS}I!N-`KKIUzlyZk&2eBt)-bT zz?)UrZS~x4D=uZ12J6}doCjST@6dmf5Y6z6DEbe4*~s9vMLL`A24^@e=nKMpGH zO~rBE;Qd16+^N`VTsypVX;#fJBw6OL=tbByUMijtd;!2fGSS{_ht}6Nv@|s|2J9QO z4OH|hqdY1mk8ZM}q~5Ea7q*K)#kVSk3{9Zo2k<#raU&J4Lt0a}RLgj6A{B2|U~NFe z!Wu3H&rvQjj)!P!G0$!5 zD^10BqknWIA-t06mSA_wWt!k!^do>g6~Qj-q7_62{X;X4GLLQQi_XgRO}miKiqQ4# z?Zzo)v)hC!S!d;Y&um#0);o6Gz^t0n4$~JiX-rb!oF!J2QNm{^>82<&1*vJdT-9^u z&iwqr7&ZM_wYgk`5qVQwsp3z*^jBdP#|bAOd) z{>;QNYF+qSni$P`VoV|+aap7)&I$sMrmd1`S}Bk~(^hl+M$>Ba5!hc??jC35&ojOa ze#s58rfJ)Z`_b(F^C%zs^<;~lr4P=E$=(o6u;DRrGEIArMN2C4KKsFAd{?Pgo$eUVV()hg7lP&2@ZViG`*4?$1Wz6sTF$Y1>Ycdh^%x_C6Q5`4hyg#jEAN# zYk(}9eHZY-WXbd-K#FN_7{itjRV`>Uh=t=BR7KNYfW%OO6;4K8EAlb7jcMerYKGl5 zroMtN<0;s8v1zgZgBS%*g2dhL8QqvX2gbP#Gb06|8k<1V@h?l@F{Ml{lTbK4V-%xO zfo7l(1s_s75LB8m2&?`sJJ5`i9jXXf$e=ildF!m$WyX^<<6cD+svC^LjUY)H-wg&Y zb=C}MU7Bo>#18(|fe>OCgIjb~;bg6;`Kb1jQ9_OySs~BeUlY?j$q*1To1sT$dYsF) zY}e|yyLNtNvmAV?`SVXi?7EE`S-8ov$UeBOZ4JEMU-F@9Omq12@SQ9CZ}>aFtV7jA z3Fhgdb9zb*Q3V6d9@w%oVF7|P$L2k|*a!vaq}hIi|EmT}o{Q<&8qEaAu}r=x==~~r zeld&LIy3h(iHoDyOswPwyl1ZzqgH1{%nUb4ouW9VxLKiMA%an;i|1e1tJ?3J6%uOJ zDx?}_%|I5&-4MVG4b?~)!YqMnA_kbR+U#{8#KgSRVz_C{(ep_74yWC*gQsQ{C9{?~ zVU01d0wh3g@gC%ihJrr~a_&(eb~P0RLpUwXl3=F?JTlBLm1butb%w1)v-^0(LgS)Q zk*yo+%bV8J`@Hq_)y8OZEzQ2c>4G$#y~t?|c*_G`#kiGBv-2T6s^FZ-X{qefC03u* zadlNJOjC7+E(|#bT?~fi31HuT%w+F87Z?lSX(Q^}?u1euP8ME6EUaNCub^4)AgZMK z-2s|=Gx%P#!ADFNH2x$)A9JsB!Y@?Q7+nkE;xw^P!FxWh)x*tB#To><0uem-3TK6@ z0-A2F!&z;GPSPz|rl;mkbGkr3a|h^UG^q%`V0BpauutcvJ84diTx~560U9Xra#Zj| z6(DqOqEimt4tQ%hoW;y)zEO)OIU251it3XMz}H(FedUcl{yN^C)667}onNw#g|#(S z5O@W&E+1lmm;<6$TI@9E{SD1_&-y02*8}VCo(6wI2$yqCamA_6Vo__X6+8j4m;usD zv#@D*8K4}z59vp9eqph^xv>pv`Td9!N;TGUcXbWT!N26db_cV24(#XPFU_3{g_xP9 zURwn6k)ooaf_@|4D~CT|ra{F2#3qp34t~Rqzzq8ak!C~9U|NtvJq) ze3;R^s)K)?3I99=V9(Ht*y<(!b%x-KZ)O>s0a_i*)ydJQD)ppjlGgx=D*LRe%<#-! z$J;M55QT30tSxornp9&v9q`s!!5uQA8a!>LOCEC8(j|@!8#mou=dTHk^4dbI%bu!M zQY>miiof29275)Z0UE&GY>o_W;^57X59yG;g z?9uPR9{s*r=$lKj0kY-|_C|)CfU&ey^;#=vZVgwai#bzcCwxI`Z3R|1>G61K_!7Qy zk1?qPL}9|YFfAE+FM;$je(=E`7-rriC&Z6GV1<+H#b$JHC!3>nMpQj%enT*TwVCR4 z`(eT|R)sHK`mz&KlaSa(snid=C|(0sL42B{gNUJdFZg`E5aQ*v zR+_g54BUkjQY+Tbym&B+&qSr>Fh>BLrR>{&eP1Z2VWL!K88lSF(fl8A%gZ+q8v4xX zGSPe+p8^nuam?aWHYVDY3I(^`VYj5vu5ilvuQ?Sf&A-a4gsHNwD>y;8w1Wf9--)So zs7f>+MFkQpqWOKnq4V$8tlIA!l$lNQ6&$sL?5yUp(@pbN0iO!^Za!j5x*rasmgd73 z1lP%iXD(?pzXu-)4!CI^>{u%8t9odz7uckE;8nlWxD=co`r{8YKo^x3`IN8*s^_5R z2T?2?MLOg(lVqi`5~2Xex!*Zkip86vR%q;q^Iiuz!j1LYVV+raErB2d@c9oX@_{Iv z##S0t1Q_PA16MwpRJn#be)h`O-yOAwcey=_>`;QkuTd$id)=Cakw>Lx80XEK3J|!d z^!UQxF7R?}wkAum9?$-8u7a?v}OS?M>;2PWEVZ)TaibER!C1>-`f0>c5=wOtyW)*+TcA zUygnA?2G1Gs)SdeaZ8yC>KJP)>*8TRy z6Nc?MaOI&Zu1{Hg^OrkL$=>HP7i1}aziiNJ1*_x!`^|yM@5V-5;QUb=Z{BDv8PWS} zc8;)i%;Sg7%{;c^hADrtem48BQ3e0=qC4sW=NB$8zwq6Qt1aH%-xYsvuRStK{%vCV z#GGeeF3frGnvuV5%HH(nsGQYiCHwfvrnNUb^-*tW+Cy)~&HdnK`*(-LrSp||045TY>6BYk#yM$+fdl{l(Bf29i8_9jeb<>P;p&`-`mper+7p517RlQ+$1rN3K%q ze~hyslSj6$<6VC$SUfVxyQyH=o|_{^=^SN5I*%Ho`IKhpoayE}^qr`2w#;-niv)IS zuAQc+%ktz5QfCioUaRWoYsChB6{-)C)-y-*gGP;a-&U}Q*<%r_xMumMAE7^{uu#l? z!z#Y=z@Iy5p+!oyD7J~#kv6~*QUr<()9J&C(@aWp<4P=MiFJZvjCcLGU z%EQsk3YZWzq%(@BcT%%L~#{g8_A<4B>b&N+*TBTIbOTQ}IISfHI@O zpyB3Tvx?`RdEHf^M&lIA(Gav8sx;H4(xG8T*Ik^eQm-xA)aD!p3QGH2OZ%?QwGC!? z=)FC@1@c2pQei+?6y?!3iIo5ai7E$YWe5O-cb`|Ve6-dF{njaR?Eu$~;)!a(iUA+} zCjcLrQ9->uQU=l%p(S|qCG@EVY|EohHx*0^ZQ>||I6z`kr14?j162wIEDsB%C(rQ0 zhC7CX62MswsmBh-miCi2Y|V-q*B%YgRc=$$VOp}^zAr=D{u&9T{0tyBj z9B#8{dGe0*25#sM77r^LDG}q*^j!PV`qY6_3ax?1Uae59!t%An^L9z2XqDwLXAY9> z;vLJkDbbpH%oy8pl-|a2+gyV(C@C{&5KW@eVuBn=HC$<9G>^LL(w(T*W%E8%7AhY*8u$3PS4=6G^ciz8baG_Q#H#o={D*B9vpMK6GcOxOiqRaZMI z@f4Yn3`jDgNRnhHNK&NJA{~&5Er=)=Mxh4OmY#~wJQoxa#S<|kzWfvhP{MO zN|TnC7Anm%3@j|t)(rz}MiSV(D?-B>8WwQei#A^}oLbm1KCC!%jas>Bk>$4ezVMn0 z+%a6EM#b1US#4QrGq@PO*KB%uc#m3Z+Hhvnpeda%KWJ8TN9SGNG%ZO~6)_hQn>xRd zF2!YY2_r5r%c}F-uv5*Y1Y!*OA#U-64f`kHOkH{I6muspd|j@4s%Z<}6*Dbr_*p}f zgW;m`v-Ut0(Rsq8^i5NHwyvH3>E(m3zc_yH$FJyL|M0?lK4o8f?WOnjpR@jZpMLm) zfq$N}n_^Jf{7vlE8*kZ8+SqoOVw#u$;t&dyJ}ISbPnGhWtB<4S47j zW7Od>F?qQRypiUwlt)lVAvVc5SZBakje#tvwi>2W70fMGti-ZgDnSwyKW7p2ZS|6m@rxyb7JH19%$)^$HS!@I@{R(4`*Q^ZNE zRzibP4`Npp^ficEF0CoE1k$4+(`&=B%0eg&E1NANE;FVYB$J5MONons%NIz#qG^{2 zw@)peNoihuHSazO2+I}P1NNz{fGuc^GvG7h9VfYNG(br9%dupb2w>-^olo-aEeOi? z7?wR{|99_O%B)0dYsWWyLt7-hxCCs$nyrai;0Kkqa1f4xDpX82gfgSPU&B)RzHdU& zeLpkZ$yk7eDOE;Vi`LdAy!+q{JlTn3rH(So!(4qMF610oVV3t*P2O|V4IWS0&`nQT z{0y&dL`V29X#GqGuvq6*$4e3g;hdZUL~q7<%PgG;UPp1WtmT%>7e z(!3VcV61k>rbwHDz2*a%%^WuOz+rQ@A2N3a7JP$ZVN#o&k<({+Z==sn@>QG6?AEm> zyzqkq_nq{-F?8RS+oGj2h1YPARM(r0bvV1QyB>-FRIYpgNR_{WRmx8^okRm13>fVcITZnCC~9L{ z&;I7}9{+u(?My%a$o2R9F1mT$xjTNC|HIHke!t&;#FJ!60QE#PwPk39&DN9+eEX6gy)0E`v<)xMHvE;Kx_~5Qh_F#iq_iW1x~ilv?#4 zSn8@*fd3K&aiJe^=QK@*D-aBcP41xE8MG`hkPRHm5In zs`T?!UqV;+=OVl4Hc?>JKdEj;s}gfkC>k24P~Tp81dAz;o&1euVKC|J9*q#^kZecQD3oceCw zb3P8>mWO`%cw1P=wlKx}?hIYF5x03y7e>xKSAS+{WZS(m(F#*C+^Q(BOxJn$6Vg4n z2n6wECj5%akp7)A;I7k{7sgM9NZ7W_M_bFZ<$hu0$GDAHX2RUKXc&l7DqxQKJbn?a z@ffXvVW(MHWe;9%BUD{xr$F(9*}}F;ZXb_dFZBuw=J6doKIK&_yzga69gQJ8ezV(b zKvp7|J@yc09ketZ88(*}1 zobuLJb1xos^3c-{kMFCVwO;?sKPP%mdtoMdbasF0ROb^VUag0+|s_yO-fm-l~mj`xq@EeTP+CT~3by#SnnClZvG{XE;^RCLH^ z1RGbkpp@_v!qE}ubYr#LU`s38Yx(m5H=#qC-P=>Lw1iIVlq=%zDLPtksr_frgZ zM=PKmmb?6nvrbNLx#r?8Ub1=1ml0d&blEp9Gt###?e=5IuVb|VFSH3JY`J)+D|&1< z!INoo(fAB>2uU?kuDU_kNV@Qch#v5kak@)(S z#7rp~IOPyMhdgR=eM2B``)YO{*H1%|THN*D>0_2$5_r9+xfIv?(S7CS9Vaez7gry+ z{Jy29Mn9XSdE7qc!S|E$_MzWG^R+{7A6&o3<;hQkNW~3Ye~cWWG8?V2uvyqVc~f{L z(RW~&bS@WP_*&mrGZCq%H_Y+XXI^ta)eo9DIpne;hEhr@D{t-{zwF9OuD;;CiS&7m y#|u||;JIyoUD2_3P2tv1kUC0Dx;j#`Rqz9bZ;$N`dz-uuN$ld%WUNu! z`H{O^k_lCJmsbDq53$yd?GJ~b6*h_#M9?DmM?qzv>@N|73a+vu)cL%3N&Fydrr;g9 z_j#Y^d7sbU^M)BLrZ6$G4TQ%vCWP7LJB;`dcIoz35Qa66YzN^JB+v8=ok0(?A$kbt4{m?5iJ8^c0F7?fRvRMS+_!h&N%=vjATIDY$z?iyOI8(INzhbx`9*5I)n z$yAt3(2nY!Bx3y}M!3Bmg7`sI-d&fkK%f&X3qZ7dq-Az)-`xDJ;MnIq5BFYpd3i{F z`pbdvIeC7W9^HHQ;vrkrZQ3vdQvx5+FqeGGr&DhVn>;*HCKiao?qc1zAs2c+b^uYOETR<@sEF8ZJqr3z0T6jN5OxnVX{(x zV|F{*e_o^g9eM}&UeUleZ9-sP)hTcFvXy6YNUC)?w zsj;C_i388Sr^1o9$`QZ|XZg+2=$b=m)L??y4*n;3PaVp3?qK&viBupsRndZi)njsz z41qt3N0~!)>fmdF_-{cl_%{$FlIi3a7QPk6+$ncPW;=j10K zm97J$1_B^BT@D4Y&E~Zi+uYjER4BzQVqF~mUs@oZsUwB)VeQu!SNeYXttS~haNg?u?2Wx&Or3FXp4{td&V{BCZkVen z;V1^b_3mtkLz<6Yq3CbxfZ)#_8$n)x;7449qswB&GM9#KsY*jq(Un#xpWE!p&5N c+O!G-OmK*8D!f3y&m|_Z>G-hFa;vcA4Zz%qc1=O2yOj&5XaIqp=`UwqB-JQLs>=eq*n47LtSbQoV)n@ Self { + Self { name, code } + } + + fn burns() -> Self { + Self::new("INVALID", Bytes::from_static(&[INVALID])) + } +} + +/// The `LOG0` callee: 512 bytes of data from memory expanded first, in a loop that reads `GAS` +/// around each log. +fn logging(stop_on_spill: bool) -> Bytes { + let stop_above = if stop_on_spill { STOP_ABOVE } else { u32::MAX }; + let mut code = vec![PUSH0, PUSH2, 0x01, 0xe0, MSTORE, PUSH0]; + let top = code.len(); + code.extend([JUMPDEST, GAS, PUSH2, 0x02, 0x00, PUSH0, LOG0, GAS, DUP1, PUSH4]); + code.extend(RESERVE.to_be_bytes()); + code.extend([GT, PUSH2, 0, 0, JUMPI]); + let out_on_reserve = code.len() - 3; + code.extend([SWAP1, SUB, PUSH4]); + code.extend(stop_above.to_be_bytes()); + code.extend([LT, PUSH2, 0, 0, JUMPI]); + let out_on_drop = code.len() - 3; + code.extend([PUSH1, 1, ADD, PUSH2]); + code.extend((top as u16).to_be_bytes()); + code.push(JUMP); + let out = (code.len() as u16).to_be_bytes(); + code.extend([JUMPDEST, STOP]); + code[out_on_reserve..out_on_reserve + 2].copy_from_slice(&out); + code[out_on_drop..out_on_drop + 2].copy_from_slice(&out); + code.into() +} + +/// `A`: `GAS`, `CALL(FORWARD, C)`, `GAS`, `work` fresh slots, and the two readings and the flag +/// returned. +fn caller(work: u32) -> Bytes { + let mut code = vec![GAS, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + code.extend(C); + code.push(PUSH4); + code.extend(FORWARD.to_be_bytes()); + code.extend([CALL, GAS, PUSH4]); + code.extend(work.to_be_bytes()); + let top = code.len() as u16; + code.extend([JUMPDEST, DUP1, ISZERO, PUSH2, 0, 0, JUMPI]); + let out_at = code.len() - 3; + code.extend([PUSH1, 1, DUP2, SSTORE, PUSH1, 1, SWAP1, SUB, PUSH2]); + code.extend(top.to_be_bytes()); + code.push(JUMP); + let out = (code.len() as u16).to_be_bytes(); + code[out_at..out_at + 2].copy_from_slice(&out); + code.extend([JUMPDEST, POP, PUSH1, 0x40, MSTORE, PUSH1, 0x20, MSTORE, PUSH0, MSTORE]); + code.extend([PUSH1, 0x60, PUSH0, RETURN]); + code.into() +} + +/// One run's figures. +#[derive(Clone, Debug)] +struct Run { + callee: &'static str, + gas_limit: u64, + work: u32, + status: String, + gas_used: u64, + logs: usize, + /// `A`'s `GAS` before and after the call, when `A` returned. + gas_around_call: Option<(u64, u64)>, + /// The call's flag, when `A` returned. + call_succeeded: Option, +} + +impl Run { + fn completed(&self) -> bool { + self.gas_around_call.is_some() + } +} + +fn run(gas_limit: u64, callee: Callee, work: u32) -> Run { + let db = MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_code(A, caller(work)) + .account_code(C, callee.code); + let block = BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, ..Default::default() }; + let mut context = MegaContext::new(db, MegaSpecId::REX6).with_block(block); + context.modify_chain(|chain| { + chain.operator_fee_scalar = Some(U256::ZERO); + chain.operator_fee_constant = Some(U256::ZERO); + }); + let mut tx = MegaTransaction::new(TxEnv { + caller: SENDER, + kind: TxKind::Call(A), + gas_limit, + ..Default::default() + }); + tx.enveloped_tx = Some(Bytes::new()); + let outcome = MegaEvm::new(context).execute_transaction(tx).expect("the transaction is valid"); + let (status, words) = match &outcome.result { + ExecutionResult::Success { output, .. } => { + let words: Vec = + output.data().chunks(32).map(|w| U256::from_be_slice(w).to::()).collect(); + ("success".to_string(), Some(words)) + } + ExecutionResult::Revert { .. } => ("revert".to_string(), None), + ExecutionResult::Halt { reason, .. } => (format!("halt: {reason:?}"), None), + }; + Run { + callee: callee.name, + gas_limit, + work, + status, + gas_used: outcome.result.gas_used(), + logs: outcome.result.logs().len(), + gas_around_call: words.as_ref().map(|words| (words[0], words[2])), + call_succeeded: words.as_ref().map(|words| words[1] == 1), + } +} + +fn callees() -> [Callee; 3] { + [ + Callee::new("STOP", Bytes::from_static(&[STOP])), + Callee::new("LOG0 512 B", logging(true)), + Callee::new("LOG0 512 B, greedy", logging(false)), + ] +} + +/// The most slots `A` completes after a callee that burns its forward. +fn work_after_a_burned_forward(gas_limit: u64) -> u32 { + let (mut fits, mut fails) = (0, 1_000); + let too_many = run(gas_limit, Callee::burns(), fails); + assert!(too_many.status.contains("OutOfGas"), "the gas binds before 1,000 slots: {too_many:?}"); + while fails - fits > 1 { + let mid = (fits + fails) / 2; + if run(gas_limit, Callee::burns(), mid).completed() { + fits = mid; + } else { + fails = mid; + } + } + fits +} + +fn print_table(title: &str, rows: &[Run], baseline_after: u64) { + println!("\n### {title}\n"); + println!( + "| gas limit | C | logs | C spend | C spend / forward | A GAS before | A GAS after | \ + A work (slots) | status | gas used |" + ); + println!("|{}", "---:|".repeat(10)); + for row in rows { + let shown = |figure: Option| figure.unwrap_or_else(|| "-".into()); + let before = shown(row.gas_around_call.map(|(before, _)| before.to_string())); + let after = shown(row.gas_around_call.map(|(_, after)| after.to_string())); + let spend = row.gas_around_call.map(|(_, after)| baseline_after - after); + println!( + "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |", + row.gas_limit, + row.callee, + row.logs, + shown(spend.map(|s| s.to_string())), + shown(spend.map(|s| format!("{:.2}", s as f64 / f64::from(FORWARD)))), + before, + after, + row.work, + row.status, + row.gas_used, + ); + } +} + +/// Holds every callee to its forward: its spend, read as `A`'s `GAS` after the call against +/// `A`'s after a callee that returned at once, is at most the forward, and `A`'s work completes. +#[track_caller] +fn assert_within_the_forward(rows: &[Run]) -> u64 { + assert!(rows.iter().all(Run::completed), "A's work completes after every callee: {rows:#?}"); + assert!(rows.iter().all(|row| row.call_succeeded == Some(true)), "every callee returns"); + let baseline_after = rows[0].gas_around_call.unwrap().1; + for row in rows { + let spend = baseline_after - row.gas_around_call.unwrap().1; + assert!(spend <= u64::from(FORWARD), "{}: {spend} within the forward", row.callee); + } + baseline_after +} + +#[test] +fn test_rex6_a_callee_spends_within_its_forward() { + const GAS_LIMIT: u64 = 20_000_000; + let work = work_after_a_burned_forward(GAS_LIMIT); + let mut rows: Vec<_> = callees().into_iter().map(|c| run(GAS_LIMIT, c, work)).collect(); + let baseline_after = assert_within_the_forward(&rows); + assert_eq!(rows[1].logs, 1, "the drop includes the log's storage gas from the first log on"); + assert!(rows[2].logs > 1, "the greedy callee logs until its forward runs low"); + + // The two ends of the calibration, for the table. + rows.extend([run(GAS_LIMIT, Callee::burns(), work), run(GAS_LIMIT, Callee::burns(), work + 1)]); + print_table("6a. Rex6, gas limit 20M, forward 1M", &rows, baseline_after); +} + +#[test] +fn test_rex6_a_callee_spends_the_same_at_a_larger_gas_limit() { + let spends = |gas_limit| { + let rows: Vec<_> = callees().into_iter().map(|c| run(gas_limit, c, 0)).collect(); + let baseline_after = assert_within_the_forward(&rows); + let spends: Vec<_> = + rows.iter().map(|row| baseline_after - row.gas_around_call.unwrap().1).collect(); + (rows, baseline_after, spends) + }; + let (_, _, at_20m) = spends(20_000_000); + let (rows, baseline_after, at_400m) = spends(400_000_000); + assert_eq!(at_20m, at_400m, "each callee spends the same at either gas limit"); + print_table("6b. Rex6, gas limit 400M, forward 1M, no work", &rows, baseline_after); +} diff --git a/bin/mega-evme/tests/satin-differences.md b/bin/mega-evme/tests/satin-differences.md index 3f133ef8d..40079bde1 100644 --- a/bin/mega-evme/tests/satin-differences.md +++ b/bin/mega-evme/tests/satin-differences.md @@ -35,7 +35,7 @@ Each fixture's command run on both engines: `tests/fixtures/test_.json` an ## Recorded mainnet blocks -The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The legacy replay of each matches the chain (every receipt and the receipts root), so the legacy column is the chain's. Satin runs the transactions as signed, on the state their parent block left. +The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both engines. The legacy replay of each matches the chain (every receipt and the receipts root), so the legacy column is the chain's. Satin runs the transactions as signed, on the state their parent block left. | Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused | |---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:| diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md index 9bb86423e..29ff43c68 100644 --- a/crates/mega-evm/README.md +++ b/crates/mega-evm/README.md @@ -26,6 +26,7 @@ The legacy spec names do not parse: `"Rex6".parse::()` fails with `P Satin is under construction. Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir. +A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's regular gas, Rex6's rule in place of EIP-150's 63/64, and its child takes the same share of the reservoir its caller has left, whatever regular gas the call asks for; the transaction's own frame and a system call's outermost frame take the whole reservoir. The gas schedule is Amsterdam's, EIP-8038's state-access prices included, with two changes: the EIP-8037 state-gas entries are rebuilt from MegaETH's own cost per state byte, so a new storage slot draws 97,920 state gas and a new account 183,600, and a byte of deployed code is priced at MegaETH's cost per history byte. The schedule also brings the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`) and raises the code-size limits to 512 KiB of contract and 1 MiB of initcode. @@ -38,7 +39,7 @@ Its byte prices are an input: the `satin-price-override` feature, off by default The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000. It is carried as an alloy-evm `PrecompilesMap`, so a node can add or replace an address through `MegaEvmFactory::with_dyn_precompiles_builder`. -The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the stop protocol that reverts the frame crossing a limit, which its caller may catch, and the inspector contract: the admission gate and what a rewrite does not change. +The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes, write records and new state per frame, the stop protocol that reverts the frame crossing a limit, which its caller may catch, and the inspector contract: what a rewrite does not change. The data-size limit is in place on top of it. A transaction is held to a data-size limit, and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left. @@ -47,16 +48,16 @@ A transfer log counts what a `LOG3` of one word counts, 160 bytes, where the val A frame start revm refuses on its caller's account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — counts nothing; a creation onto an occupied address is counted, and revm refuses it after the count. A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped with a revert carrying `MegaLimitExceeded`, and pays only for what ran. A record is checked before its history is charged, so a record the limit rejects costs nothing and the stop is what the transaction reports. -The limits are fixed per spec, `ProtocolLimits::for_spec`: Satin holds each transaction and the block to 12.5 MiB of data size and a detained transaction to 20,000,000 of compute past its read, and every EVM, a bare one included, runs under them; `EvmTxRuntimeLimits` sets others on an EVM, a tool's or a test's counterfactual. -The block's data size is a packing budget: the transaction that crosses it is packed and the next one refused. +The limits are fixed per spec, `ProtocolLimits::for_spec`: Satin holds each transaction and the block to 12.5 MiB of data size, 500,000 write records and 1,000 new accounts and slots, and a detained transaction to 20,000,000 of compute past its read, and every EVM, a bare one included, runs under them; `EvmTxRuntimeLimits` sets others on an EVM, a tool's or a test's counterfactual. +The block's data size, write records and state growth are packing budgets: the transaction that reaches one is packed and the next ordinary one refused. `MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers beside the history bytes, the usage counted and the limit that stopped the transaction, if any. Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read by the first transaction that prices against it, so the block's own L1 info deposit is what the transactions after it are priced with. Every transaction is held to the spec's limits, and the block counts what its transactions spent on each of the three ledgers and the history bytes they appended. -The limits that change a result are protocol values fixed per spec, `ProtocolLimits::for_spec`: the per-transaction runtime limits and the block's data-size budget, the same on every chain, so no chain configuration carries them and a node passes none of them. -The block context a node passes carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap that can lower the block's data-size budget and never raise it, so a validator that leaves it at its default computes the block a builder packed under any policy. +The limits that change a result are protocol values fixed per spec, `ProtocolLimits::for_spec`: the per-transaction runtime limits and the block's three packing budgets, the same on every chain, so no chain configuration carries them and a node passes none of them. +The block context a node passes carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and caps that can lower the block's three packing budgets and never raise them, so a validator that leaves it at its default computes the block a builder packed under any policy. The execution figure a block counts for a transaction is its regular ledger — its gas less state and history, read off revm's `Gas` — at least its EIP-7623 floor. -The block's data-size cap never refuses a deposit, which the block must include; a deposit still counts towards it. +The block's packing budgets never refuse a deposit, which the block must include, or a Mega System Transaction; both still count towards them. A builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the block's counters again; alloy-evm's `commit_transaction` cannot fail and expects each outcome to commit before the next transaction executes, and a debug build asserts it. `apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the node says with `MegaBlockExecutionCtx::satin_activation_block` — checks that the six MegaETH system contracts and the EIP-7997 `CREATE2` factory hold the code Satin runs, which the legacy forks and OP's genesis tooling installed and without which that block is invalid, applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call, and last reads the L1 block contract's account and the five slots the block's transactions can be priced against, which op-revm and the executor read on the database rather than through a transaction. It commits each pre-block state on its own, in order, read-only entries included — the two EIP calls, the activation block's seven reads, the read of the registry's pending changes and its call, and the L1 block info; with the included transactions' states and oracle reads, and the block hashes and buckets the executor exports, the sequence of committed states is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`). @@ -64,8 +65,8 @@ A database that cannot serve one of those L1 reads fails the block before its fi A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which the state it writes draws first. revm's default system-call gas limit, 31,566,720, is 30,000,000 and a reservoir of sixteen fresh slots. -The block's pre-block calls run on the block's gas limit and never less than 30,000,000, the legacy engine's budget kept as it was; what it adds above 30,000,000 is reservoir, not regular gas. -The legacy engine widened it for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays: it prices its state at the minimum bucket. +The block's pre-block calls run on `constants::PRE_BLOCK_CALL_GAS_LIMIT`, 31,566,720, whatever the block's gas limit: 30,000,000 of regular gas and a reservoir of sixteen fresh slots at the minimum bucket, which a system call prices its state at. +The legacy engine's budget, the block's gas limit and never less than 30,000,000, is gone: it was widened for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays. A pre-block call that does not succeed refuses the block with the call's own validation error; a database error the database calls fatal is an internal error instead, since it says nothing about the block. That is the rule alloy-evm's block executor holds a transaction's database error to. A system call pays no history gas, is held to no per-transaction limit and is not detained. @@ -121,7 +122,7 @@ The body is charged at validation, in the EIP-8037 intrinsic state-gas slot so t Everything else is charged where the write is made and given back, at the same price, by whoever's failure takes it back. The records a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` starts a frame for are charged to the caller out of what it kept after forwarding gas: a caller that cannot pay halts, and the frame does not start. A deposit, a transaction the protocol itself sent and a system call pay no history at all. -The last two are held to no per-transaction limit either, for the same reason — the protocol's maintenance must not fail on a resource limit: no data-size limit and no frame budget stops them, and what they use is counted and reported all the same. +The last two are held to no per-transaction limit either, for the same reason — the protocol's maintenance must not fail on a resource limit: no data-size, KV-update or state-growth limit and no frame budget stops them, and what they use is counted and reported all the same. A user's deposit is held to every limit. The pairing between the two counts is per record, not per transaction. @@ -133,15 +134,16 @@ The history bytes a transaction reports count those bytes all the same, so a blo The transfer log of the value that granted an allowance draws nothing from it. The byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, a body counts its five fixed write records even when fewer fee accounts are written, and the transfer logs are not in it. -No limit holds the KV count or the state a transaction adds. -The KV count is the write-record count the layer keeps — one record per account or storage write the transaction keeps, the sender and the fee accounts being the body's. -Every record is forty bytes of data size, so at the production data-size caps a transaction or a block keeps at most 327,680 records. -The transaction's KV count is in its outcome's usage and the block's in its result. -A transaction's state growth is the EIP-8037 state gas it spends, at the price of the SALT bucket it lands in: what bounds it is what it costs. +The KV-update limit is in place beside it. +The KV count is the write-record count the layer keeps — one record per account or storage write the transaction keeps, the sender and the fee accounts being the body's — and a transaction is held to 500,000 of them and every frame to 98% of what its parent has left. +Every record is forty bytes of data size, so at the production data-size caps a transaction or a block keeps at most 327,680 records and the data size binds first; the KV check is still made. +The state-growth limit is in place too: the net count of new accounts and new slots a transaction keeps, where EIP-8037 charges the state gas of one, is held to 1,000, and every frame to 98% of what its parent has left. +A slot written back to zero falls, a failed frame's net goes with it, and a negative net never enlarges the next child's budget; EIP-8037 still prices the state a transaction adds, but the count is what stops the 1,001st slot. +An EIP-7702 list that would keep more records or create more accounts than the transaction may is skipped whole, and the transaction's own frame is stopped before it runs. +The transaction's KV count and state growth are in its outcome's usage and the block's in its result. Gas detention is in place: a transaction that reads volatile data — the block environment, the block beneficiary's account, the Oracle's storage — may compute at most 20,000,000 more gas after the read than it had spent at it. -Compute is the regular gas spent: the state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns. -The one exception is what a frame has left when an opcode's static gas fails, which counts as compute: under that charge's price per halting frame, so the stop only comes earlier. +Compute is the regular gas spent: the state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns, whatever charge it could not pay, an opcode's static gas included. The Host marks the read where it loads the value, and the most restrictive read binds. Every frame's spendable gas is held to what the limit leaves the transaction, and the rest is withheld, with the revm fork's withheld part of a frame's regular gas: a regular charge cannot draw it, and every other reader of the frame's gas — `GAS`, the gas a call forwards, the `SSTORE` sentry, what a callee returns — counts it. So a transaction that reads runs as it would without the read until a regular charge needs the withheld gas. @@ -159,15 +161,16 @@ The error's argument is a `uint8`: a refused `SLOTNUM` names access type 12, whi The two caps are runtime limits, 20,000,000 each by default; `EvmTxRuntimeLimits::no_limits()` leaves them unlimited, and a transaction whose caps are both unlimited is not detained. The protocol's own transactions and the system calls are not detained either. -Every limit — the transaction's data size, a frame's data-size budget and gas detention's compute limit — stops the frame that crosses it the same way. +Every limit — the transaction's data size, KV updates and state growth, a frame's budget in each, and gas detention's compute limit — stops the frame that crosses it the same way. That frame reverts with `MegaLimitExceeded(kind, limit)`, keeping nothing it wrote or logged, and its caller resumes as after any revert: the call fails, the stop is its return data, and the gas the frame had comes back. The caller is held to what the transaction has left, so a write or a charge of its own that crosses again stops it in turn, and a caller that catches the stop and ends lets the transaction succeed. Only a stop of the transaction's own frame is the transaction's result, and `LimitStop` reports only that one. It settles like any EIP-8037 revert: the transaction keeps nothing it wrote or logged, its sender pays the intrinsic gas and what ran, and gets back the rest of its regular gas and the reservoir, less the body's history. Nothing is rescued, because nothing was taken: detention withholds gas inside a frame's own tracker and never spends it. -An inspector may rewrite a stop as it may any failure; a frame that kept nothing settles as one whatever the inspector made of its result. +An inspector may rewrite a stop as it may any failure, and the result it hands back is taken as given, as revm takes it. +An inspector sees a frame that crosses the compute limit end with the stop: the stop is made once the frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end`, so a tracer shows the frame as the receipt bills it. A real out-of-gas and a precompile given less than its price still halt and burn what their frame was given. -`tests/satin/stops.rs` pins every limit crossed by the transaction's own frame and by a frame three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing. +`tests/satin/stops.rs` pins every limit crossed by the transaction's own frame and by a frame three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes it made of them. ## Quick start @@ -204,22 +207,15 @@ for tx in transactions { let (evm, result) = executor.finish_with_counters()?; ``` -Block execution admits an inspected transaction only from an EVM whose inspector is declared read-only: - -```rust,ignore -use mega_evm::DeclaredObserver; - -let evm = MegaEvm::new(context).with_trusted_inspector(DeclaredObserver(tracer)); -assert!(!evm.has_rewriting_inspector()); -``` - -A declared observer sees a block's transactions, user and system alike, and nothing else: the pre-block calls run no inspector, and the end of the block runs no code. -Outside block execution an inspector may rewrite what execution produces — Foundry's cheatcodes are built on that — within the inspector contract. -A failed creation rewritten into a success is refused, and a limit's stop is not rewritten. -A frame an inspector answered in place of running, or a failed frame it turned into a success, settles into its caller as a frame that kept nothing: the caller sees the success, the output and the regular gas the inspector chose, and no state gas, history gas, refund or write record of writes the journal does not hold. -An answer hands its caller back the reservoir it forwarded, whatever gas the inspector built it on. -A success an inspector rewrites into a failure has its journal taken back as a failed frame's is, so the state follows the failure its ledgers settle as. -Gas an inspector writes after a frame's last instruction reaches nobody, and a charge a frame cannot pay is refused without stopping it. +Block execution admits any inspector: a node decides which inspectors may run on block production, and the engine no longer refuses one. +An inspector runs on revm's inspected lifecycle unchanged: the engine's frame start and return are the ones both loops share, and it does nothing extra for an inspector. +An inspector sees a block's transactions, user and system alike, and nothing else: the pre-block calls run no inspector, and the end of the block runs no code. +An inspector may rewrite what execution produces — Foundry's cheatcodes are built on that — within the inspector contract. +A rewritten result is taken as given, as revm takes it: revm commits or reverts the frame's journal before the inspector sees the result, and the caller settles what the inspector hands back, its gas, reservoir and byte pool included. +A failed frame turned into a success keeps its journal reverted and settles as a success, its charges and records merged; a success turned into a failure keeps its journal and settles as a failure; a frame answered in place of running keeps what its caller's opcode was charged for it, and settles on the gas the answer is built on — `Gas::new(limit)` carries no reservoir. +A failed creation rewritten into a success hands its creator the address the inspector gave, with nothing deployed there. +Gas an inspector writes after a frame's last instruction reaches nobody, and a charge a frame cannot pay is refused without stopping it, its record left on the frame's gas as revm leaves it. +An answer an inspector gives in place of a frame is taken as given too: no limit holds it. `tests/satin/inspector_cheatcodes.rs` drives `deal`, `store`, `pauseGasMetering` / `resumeGasMetering` and `expectRevert` through the engine as Foundry's inspector does. ## Node integration diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs index 1acddffa6..81a7def05 100644 --- a/crates/mega-evm/benches/transact.rs +++ b/crates/mega-evm/benches/transact.rs @@ -5,10 +5,11 @@ //! //! - `empty_transaction`, `ether_transfer`: the per-transaction cost. //! - `deep_calls`: a contract calling itself 64 deep, each frame writing a slot and logging, so -//! every frame pays the frame lifecycle's lanes and every `SSTORE` and `LOG` its commit wrapper. +//! every frame pays the frame lifecycle's start and return — its start held to the limits, its +//! byte pool forwarded and settled — and every `SSTORE` and `LOG` its completed-write hook. //! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the -//! `SSTORE` wrapper's commit and refund. -//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit, and the one +//! `SSTORE`'s completed-write hook, its commit and its refund. +//! - `logs`: 200 two-topic logs in one frame: the `LOG`'s completed-write hook, and the one //! `record_history_cost` each log's bytes cost — no allocation, no second pass over the table. //! - `calldata`: a call carrying 4 KiB of calldata, which is 4 KiB of the transaction body's //! history, priced once before the first frame runs. @@ -33,9 +34,9 @@ //! gas detention marks in the Host and commits in the opcode's wrapper; the first caps the frame, //! and the call starts and resumes under the limit. //! - `hashes_and_copies`: 200 rounds of a 32-byte `KECCAK256`, `MCOPY`, `CALLDATACOPY` and -//! `CODECOPY`, an empty `RETURNDATACOPY` and an `EXP` of a one-byte exponent: the wrapper each of -//! them runs in, which notes the frame's gas for gas detention when the opcode's charge fails and -//! compares a result when it does not. +//! `CODECOPY`, an empty `RETURNDATACOPY` and an `EXP` of a one-byte exponent: revm's own +//! instructions, which no wrapper surrounds, since what a failed charge leaves the frame is read +//! off the fork's failed-charge record. //! - `data_size_limit`: 200 fresh slots and 200 two-topic logs in one frame, run under a //! transaction data-size limit equal to exactly what the transaction keeps, so every record is //! checked against a limit it is about to reach (`satin`); the same one byte short of it, so the @@ -554,19 +555,23 @@ fn bench_transact(c: &mut Criterion) { assert!(at_limit.result.is_success(), "data_size_limit: {:?}", at_limit.result); assert_eq!( at_limit.usage, - LimitUsage { data_size: LIMITED_KEPT, write_records: REPEAT }, + LimitUsage { data_size: LIMITED_KEPT, write_records: REPEAT, state_growth: REPEAT }, "data_size_limit: the arm must keep every byte and record it is sized for", ); let stopped = MegaEvm::new(limited(LIMITED_KEPT - 1)) .execute_transaction(OpTx(limited_tx.clone())) .unwrap(); + // The transaction's own frame keeps everything but the body, so the last log crosses that + // frame's budget, what the limit leaves after the body, together with the limit, and the stop + // names the budget. + let body = TX_BODY_SIZE + limited_tx.base.data.len() as u64; assert_eq!( stopped.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: LIMITED_KEPT - 1, - used: LIMITED_KEPT, - frame_local: false, + limit: LIMITED_KEPT - 1 - body, + used: LIMITED_KEPT - body, + frame_local: true, }), "data_size_limit/stopped: the last log must be the byte that crosses", ); diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs index c013d8c30..e8b8723fd 100644 --- a/crates/mega-evm/src/access/detention.rs +++ b/crates/mega-evm/src/access/detention.rs @@ -6,7 +6,10 @@ use core::{cell::Cell, num::NonZeroU64}; use std::vec::Vec; use alloy_primitives::{Bytes, U256}; -use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult}; +use revm::{ + context_interface::cfg::gas::GasTracker, + interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult}, +}; use super::VolatileDataAccess; use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR; @@ -18,7 +21,8 @@ pub(crate) struct ComputeStop { /// The most compute the transaction may reach. pub(crate) limit: u64, /// The transaction's compute before the charge that would have crossed the limit: what its - /// regular ledger bills once the stopped frame's gas is put back. + /// regular ledger bills once the stopped frame's gas is put back, and the stipends of its + /// value calls on top, which that ledger never billed. pub(crate) used: u64, } @@ -27,43 +31,40 @@ pub(crate) struct ComputeStop { struct DetainedFrame { /// The frame's regular gas spent when it suspended on a child ([`regular_spent`]). at_suspension: u64, + /// The stipend of the value call the frame suspended on, which revm adds to the child's gas + /// limit and the frame never paid: zero for any other child. + child_stipend: u64, /// While a child of the frame runs: what the frame adds to the transaction's compute, which is - /// [`at_suspension`](Self::at_suspension) less the child's gas limit. + /// [`at_suspension`](Self::at_suspension) less the gas it forwarded the child — the child's + /// gas limit without the stipend. contribution: u64, } -/// What detention records of a frame when revm is about to build a child of it, while no read has -/// set a limit: enough to rebuild what the frame adds to the transaction's compute while that -/// child runs, should a read below it set the first limit. -#[derive(Clone, Copy, Debug, Default)] -struct CallerRecord { - /// The frame's regular gas spent ([`regular_spent`]). - spent: u64, - /// The frame's own gas limit: what its caller's regular gas spent is taken less of. - limit: u64, -} - -/// The frames' figures the transaction's compute is read from. -/// -/// Detention keeps them from the first read that sets a limit on; debug builds keep a second copy -/// from the transaction's first frame on, by the same updates, and hold the first to it. +/// The frames' figures the transaction's compute is read from, kept from the transaction's first +/// frame on. #[derive(Clone, Debug, Default)] struct FrameFigures { /// One entry per frame that runs or is suspended, the running one last. frames: Vec, /// The compute of the frames suspended on a child that runs. suspended: u64, + /// The stipends of the value calls that returned: gas nobody paid, which came back to the + /// callers' gas with what their children left of it, so the callers' regular gas spent is + /// short of their compute by these. + stipends: u64, } impl FrameFigures { fn clear(&mut self) { self.frames.clear(); self.suspended = 0; + self.stipends = 0; } /// The frame at `depth`, whose gas limit is `gas_limit`, is about to run. On its first run its /// caller's compute is added; on a resume it is taken back out, because the frame's own - /// regular gas spent now accounts for the child. + /// regular gas spent now accounts for the child — but for a value call's stipend, which the + /// child's return handed it on top of what it forwarded, and which is counted apart. fn on_frame_run(&mut self, gas_limit: u64, depth: usize) { if self.frames.len() == depth { let contribution = self.caller_contribution(depth, gas_limit); @@ -74,15 +75,19 @@ impl FrameFigures { self.frames.push(DetainedFrame::default()); } else if let Some(frame) = self.frames.get_mut(depth) { self.suspended = self.suspended.saturating_sub(frame.contribution); + self.stipends = self.stipends.saturating_add(frame.child_stipend); frame.contribution = 0; + frame.child_stipend = 0; } debug_assert_eq!(self.frames.len(), depth + 1, "one entry per frame that runs"); } - /// The frame at `depth`, whose gas is `gas`, suspended to start a child. - fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) { + /// The frame at `depth`, whose gas is `gas`, suspended to start a child that revm gives a + /// value call's `stipend` on top of what the frame forwarded. + fn on_frame_suspend(&mut self, gas: &Gas, depth: usize, stipend: u64) { if let Some(frame) = self.frames.get_mut(depth) { - frame.at_suspension = regular_spent(gas); + frame.at_suspension = regular_spent(gas.tracker()); + frame.child_stipend = stipend; } } @@ -93,28 +98,12 @@ impl FrameFigures { } /// What the caller of a frame at `depth` with `gas_limit` adds to the transaction's compute - /// while the frame runs: its regular gas spent at suspension, less the frame's gas limit. The - /// transaction's own frame has no caller. + /// while the frame runs: its regular gas spent at suspension, less what it forwarded — the + /// frame's gas limit without a value call's stipend. The transaction's own frame has no caller. fn caller_contribution(&self, depth: usize, gas_limit: u64) -> u64 { - depth - .checked_sub(1) - .and_then(|i| self.frames.get(i)) - .map_or(0, |caller| caller.at_suspension.saturating_sub(gas_limit)) - } - - /// Asserts that `kept`, the figures detention keeps, are these, kept from the transaction's - /// first frame on: the same entries, but for the running frame's regular gas spent at its last - /// suspension, which these keep stale until the frame suspends again and nothing reads before. - #[cfg(debug_assertions)] - fn assert_kept(&self, kept: &Self) { - assert_eq!(kept.suspended, self.suspended, "the compute of the suspended frames"); - assert_eq!(kept.frames.len(), self.frames.len(), "one entry per frame that runs"); - if let Some(((last, below), (eager_last, eager_below))) = - kept.frames.split_last().zip(self.frames.split_last()) - { - assert_eq!(below, eager_below, "the frames the running one runs under"); - assert_eq!(last.contribution, eager_last.contribution, "the running frame's"); - } + depth.checked_sub(1).and_then(|i| self.frames.get(i)).map_or(0, |caller| { + caller.at_suspension.saturating_sub(gas_limit.saturating_sub(caller.child_stipend)) + }) } } @@ -125,32 +114,32 @@ impl FrameFigures { /// /// # Compute /// -/// Compute is the regular gas the transaction spends on what it runs. A frame's regular gas spent -/// is read off its [`Gas`]: its limit, less what it has left, less the state and history gas that -/// spilled onto its regular gas, which are not compute. What it has left is the whole of its -/// regular gas, the part withheld from regular charges included, so withheld gas is never spent, -/// and every other reader of the frame's gas sees the same figure. +/// Compute is the regular gas the transaction's frames spend on what they run, whoever funds it. A +/// frame's regular gas spent is read off its [`Gas`]: its limit, less what it has left, less the +/// state and history gas that spilled onto its regular gas, which are not compute. What it has +/// left is the whole of its regular gas, the part withheld from regular charges included, so +/// withheld gas is never spent, and every other reader of the frame's gas sees the same figure. /// /// The transaction's compute is its frames' compute: the frame that runs, and every frame -/// suspended on a child that runs, as it stood when it suspended, less the child's gas limit. A -/// value call's stipend is part of that limit and gas nobody paid, so taking the whole limit off -/// takes the stipend off too, as the caller's regular gas spent does once the child returned. So -/// the figure follows the regular ledger of the transaction's frames at every moment, before, -/// during and after each child: +/// suspended on a child that runs, as it stood when it suspended, less the gas it forwarded the +/// child. A value call's stipend is not forwarded gas: revm adds it to the child's gas limit on +/// top of the forward, and what the child runs on it is compute like the rest of what it runs. +/// When the child returns, what it left of its gas comes back to the caller, the stipend's part +/// included, so the caller's regular gas spent is short of what it and the child computed by the +/// whole stipend, which is counted apart once the child returned. So the figure is the same +/// before, during and after each child: /// /// ```text -/// compute = Σ suspended callers (spent at suspension − child's gas limit) +/// compute = Σ suspended callers (spent at suspension − gas forwarded) /// + regular_spent(running frame) +/// + Σ stipends of the value calls that returned /// − burned /// ``` /// -/// The stipend stays outside compute on purpose: compute is regular gas drawn from the -/// transaction's own pools. A callee may run up to 2,300 gas on each value call's stipend beyond -/// the compute counted. A value call costs its caller 9,100 of compute — the 11,300 of the value -/// transfer less the 2,300 stipend it carries, and a warm access of 100 — and a callee that leaves -/// the stipend unspent returns it, which lowers the caller's spent regular gas: a warm value call -/// to an empty account counts 9,100 − 2,300 = 6,800. So the gas run after a read is at most about -/// 34% (2,300 / 6,800) more than the cap. +/// Every regular charge an instruction makes counts, the ones a callee pays out of a stipend +/// included, and nothing else does, so the gas run after a read is at most the cap. The regular +/// ledger bills the transaction its compute less the stipends, which no pool of the transaction's +/// gas paid. /// /// A keyless deployment's call is the transaction's own frame, and runs no code: it charges its /// own work — the overhead of decoding the signed transaction and recovering its signer, and the @@ -160,29 +149,19 @@ impl FrameFigures { /// /// The one part of the regular ledger that is not compute is what a halt burns (`burned`): a /// frame that halts consumes the gas it had left, and its spill, without running anything with -/// it. A frame answered without running that halts burns its whole gas limit. An out-of-gas zeroes -/// what the frame had before the frame returns; the wrapper of the opcode whose charge failed -/// notes it first, `EXP`'s and the unbounded charges of `KECCAK256` and the copies into memory -/// included. -/// -/// The one charge no wrapper sees is an opcode's static gas, which the interpreter's step loop -/// makes before the opcode runs. When it fails, what the halting frame had left counts as -/// compute: per halting frame, less than the failed charge's price, so at most 4,999, on -/// `SELFDESTRUCT`. Burned gas is counted as compute, so the stop comes earlier, never later. A -/// frame whose leftover takes the compute past the limit does so without a crossing, so the stop -/// is its caller's next charge, and the regular ledger at the stop holds that leftover's part -/// past the limit beside the limit. +/// it. A frame answered without running that halts burns its whole gas limit: a precompile that +/// runs out of gas counts nothing of its forward, nor of a value call's stipend, as compute. An +/// out-of-gas zeroes what the frame had before the frame returns; the revm fork records it first, +/// before every deduction that fails — an opcode's static gas, which the interpreter's step loop +/// charges before the opcode runs, included — and before a halt on a cold access the frame cannot +/// pay, and the frame's end reads the record. A frame whose opcode cannot pay the records of the +/// frame it was starting gets the forward back, and records what it has then, before it halts. /// /// # Keeping the figure /// -/// Only a read that sets a limit, and what follows it, needs the transaction's compute, so the -/// frames' figures are kept only from the first such read on. Before it, what a halt burns and the -/// switch are kept as every frame starts and ends, and nothing else but one record per frame revm -/// builds a child of: its regular gas spent and its own gas limit then, which is what it stands at -/// while that child runs. At the first read, the frames the reading frame runs under are exactly -/// the frames suspended on a running child, and what each adds is rebuilt from its record: its -/// regular gas spent less the gas limit of the frame above it, the reading frame's own for the -/// last. From there every frame is kept as it starts, suspends, resumes and ends. +/// The frames' figures are kept for every transaction detention holds, from its first frame on, +/// as each frame starts, suspends, resumes and ends, so a read at any depth finds the compute of +/// the frames it runs under already summed. /// /// # Refused reads /// @@ -191,12 +170,24 @@ impl FrameFigures { /// `VolatileDataAccessDisabled`. The switch is scoped to the frame that turned it off and the /// frames below it, and turns back on when that frame returns. `MegaAccessControl`'s interceptor /// steers it for the frame that calls the contract. +/// +/// # What is a read +/// +/// The Host refuses and marks a load only while the wrapper of an opcode that reads volatile data +/// runs ([`begin_read`](Self::begin_read)). A load made anywhere else is no volatile read: it is +/// neither refused nor marked. That is `CREATE`'s and `CREATE2`'s loads of their creator and of +/// the created address, which revm makes through the Host to check the creator's balance and +/// nonce and to price the created account — a value call's check of its caller's balance is no +/// read either — and an inspector's load through the Host. #[derive(Clone, Debug, Default)] pub struct Detention { /// What the Host loaded for the running opcode, waiting for its wrapper. observed: Cell, /// What the Host refused to load for the running opcode, waiting for its wrapper. refused: Cell, + /// Whether the wrapper of an opcode that reads volatile data runs it: the Host refuses and + /// marks a load only then. + reading: bool, /// Whether the transaction's reads are held to a cap. A system-originated transaction's are /// not, and neither are a transaction's whose caps are both unlimited. detains: bool, @@ -221,18 +212,8 @@ pub struct Detention { limit: Option, /// The regular gas the frames that halted burned without running anything with it. burned: u64, - /// What the running frame had left when a charge failed on an out-of-gas whose halt zeroes it. - left_at_halt: Option, - /// The frames' figures, once a read set a limit. + /// The frames' figures, for a transaction detention holds. figures: FrameFigures, - /// While no read has set a limit: at each depth, the record of the frame there when revm last - /// built a child of it in the transaction ([`on_child_build`](Self::on_child_build)). An entry - /// below the running frame's depth is its caller's, made when revm built the frame above it. - callers: Vec, - /// The frames' figures kept from the transaction's first frame on, in debug builds, to hold - /// the ones rebuilt at the first read, and every one kept after it, to them. - #[cfg(debug_assertions)] - eager: FrameFigures, } impl Detention { @@ -244,6 +225,7 @@ impl Detention { pub(crate) fn reset(&mut self, detains: bool, block_env_cap: u64, oracle_cap: u64) { self.observed.set(VolatileDataAccess::empty()); self.refused.set(VolatileDataAccess::empty()); + self.reading = false; self.detains = detains && (block_env_cap != u64::MAX || oracle_cap != u64::MAX); self.block_env_cap = block_env_cap; self.oracle_cap = oracle_cap; @@ -260,11 +242,7 @@ impl Detention { self.accessed = VolatileDataAccess::empty(); self.limit = None; self.burned = 0; - self.left_at_halt = None; self.figures.clear(); - self.callers.clear(); - #[cfg(debug_assertions)] - self.eager.clear(); } /// Starts every transaction with volatile-data access switched off from `depth` down, as if @@ -298,23 +276,23 @@ impl Detention { /* The Host */ - /// Whether the Host refuses a load of `access`: the running frame is in a subtree where - /// volatile-data access is switched off. A refusal is recorded for the running opcode's - /// wrapper, which reverts the frame. + /// Whether the Host refuses a load of `access`: a read wrapper's opcode makes it, in a frame + /// in a subtree where volatile-data access is switched off. A refusal is recorded for the + /// wrapper, which reverts the frame. A load outside a wrapper is never refused. #[inline] pub(crate) fn refuses(&self, access: VolatileDataAccess) -> bool { - if !self.refusing { + if !(self.refusing && self.reading) { return false; } self.refused.set(access); true } - /// Records that the Host loaded `access` for the running opcode. Its wrapper commits the read - /// once the opcode completed. + /// Records that the Host loaded `access` for the running read wrapper's opcode. The wrapper + /// commits the read once the opcode completed. A load outside a wrapper marks nothing. #[inline] pub(crate) fn observe(&self, access: VolatileDataAccess) { - if self.detains { + if self.detains && self.reading { self.observed.set(self.observed.get() | access); } } @@ -328,12 +306,21 @@ impl Detention { self.refusing } - /// Forgets what the Host observed or refused outside an opcode's wrapper, so it is not - /// committed for the wrong opcode. + /// A read wrapper starts its opcode: the Host's loads are reads until [`end_read`]. Nothing is + /// observed or refused before, since only a wrapper's opcode observes or refuses, and its + /// wrapper takes what it did. + /// + /// [`end_read`]: Self::end_read #[inline] - pub(crate) fn discard_stale_reads(&self) { - self.observed.set(VolatileDataAccess::empty()); - self.refused.set(VolatileDataAccess::empty()); + pub(crate) fn begin_read(&mut self) { + debug_assert!(!self.has_reads(), "a read left over from before the opcode"); + self.reading = true; + } + + /// The read wrapper's opcode returned: the Host's loads are no reads again. + #[inline] + pub(crate) const fn end_read(&mut self) { + self.reading = false; } /// Whether the Host observed or refused anything for the running opcode. @@ -362,11 +349,10 @@ impl Detention { self.observed.replace(VolatileDataAccess::empty()) } - /// Commits the reads `observed` of the opcode the running frame, at `depth` and whose gas is - /// `gas`, completed: the transaction's limit becomes its compute now plus the reads' cap, + /// Commits the reads `observed` of the opcode the running frame, whose gas is `gas`, + /// completed: the transaction's limit becomes its compute now plus the reads' cap, /// unless it is already lower, and the frame's spendable gas is held to what the limit leaves - /// it. The first read that sets a limit starts keeping the frames' figures - /// ([`track`](Self::track)). + /// it. /// /// `forwarded` is the regular gas the opcode forwarded to a frame it is about to start, which /// the frame's regular gas spent includes and its compute does not. @@ -374,7 +360,6 @@ impl Detention { &mut self, observed: VolatileDataAccess, gas: &mut Gas, - depth: usize, forwarded: u64, ) { self.accessed |= observed; @@ -382,10 +367,7 @@ impl Detention { if cap == u64::MAX { return; } - if self.limit.is_none() { - self.track(gas, depth); - } - let compute = self.compute(gas).saturating_sub(forwarded); + let compute = self.compute(gas.tracker()).saturating_sub(forwarded); let limit = self.lower_limit(compute.saturating_add(cap)); gas.limit_spendable(limit.saturating_sub(compute)); } @@ -411,140 +393,69 @@ impl Detention { /// it resumes on the gas a child handed back, and after a storage write, whose restore of a /// slot to its original value refills the state and history gas that spilled onto regular gas. #[inline] - pub(crate) fn hold(&self, gas: &mut Gas) { + pub(crate) fn hold(&self, gas: &mut GasTracker) { if let Some(limit) = self.limit { gas.limit_spendable(limit.saturating_sub(self.compute(gas))); } } - /// Notes what the running frame has left, `left`, when an opcode's charge failed on an - /// out-of-gas the halt after it zeroes: what the halt burns rather than what the frame ran. - #[inline] - pub(crate) const fn note_halt(&mut self, left: u64) { - self.left_at_halt = Some(left); - } - /* The frame lifecycle */ /// The frame at `depth`, whose gas is `gas`, is about to run: for the first time, or again /// after a child returned into it. /// - /// The switch is read for the frame. Once a read set a limit, a frame's first run adds its - /// caller's compute to the transaction's, now that the frame's gas limit is known — what the - /// caller forwarded, and a value call's stipend; a resumed frame takes it back out, because - /// its own regular gas spent now accounts for the child. Then the frame is held to the limit. + /// The switch is read for the frame. For a transaction detention holds, a frame's first run + /// adds its caller's compute to the transaction's, now that the frame's gas limit is known — + /// what the caller forwarded, and a value call's stipend; a resumed frame takes it back out, + /// because its own regular gas spent now accounts for the child. Then the frame is held to the + /// limit, once a read set one. #[inline] pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) { self.refusing = self.disabled_from.is_some_and(|from| depth >= from); - #[cfg(debug_assertions)] - if self.detains { - self.eager.on_frame_run(gas.limit(), depth); - } - // Only a read of a transaction detention holds sets a limit. - if self.limit.is_none() { + if !self.detains { + debug_assert!(self.limit.is_none(), "a limit on a transaction detention does not hold"); return; } - debug_assert!(self.detains, "a limit on a transaction detention does not hold"); self.figures.on_frame_run(gas.limit(), depth); - #[cfg(debug_assertions)] - self.eager.assert_kept(&self.figures); - self.hold(gas); + self.hold(gas.tracker_mut()); } - /// The frame at `depth`, whose gas is `gas`, suspended to start a child. Its compute stands - /// still until the child returns. + /// The frame at `depth`, whose gas is `gas`, suspended to start a child, to which revm gives + /// a value call's `stipend` on top of the gas the frame forwarded. Its compute stands still + /// until the child returns. #[inline] - pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) { - #[cfg(debug_assertions)] + pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize, stipend: u64) { if self.detains { - self.eager.on_frame_suspend(gas, depth); - } - if self.limit.is_none() { - return; - } - self.figures.on_frame_suspend(gas, depth); - } - - /// Whether revm building a frame's child is to be recorded ([`on_child_build`]): the - /// transaction is detained, and no read has set a limit. - /// - /// [`on_child_build`]: Self::on_child_build - #[inline] - pub(crate) const fn records_callers(&self) -> bool { - self.detains && self.limit.is_none() - } - - /// Records the frame at `depth − 1`, whose gas is `caller`, as revm is about to build a child - /// of it at `depth`, while no read has set a limit ([`records_callers`]): its regular gas - /// spent and its gas limit. Until the child returns, that is what the frame stands at, so a - /// read below it rebuilds what the frame adds to the transaction's compute from it - /// ([`track`](Self::track)). - /// - /// A frame answered without running records its caller too, which the caller's next child - /// overwrites; a read is only ever made in a frame revm built. - /// - /// [`records_callers`]: Self::records_callers - #[inline] - pub(crate) fn on_child_build(&mut self, depth: usize, caller: &Gas) { - debug_assert!(self.records_callers() && depth > 0, "a caller recorded while untracked"); - let index = depth - 1; - if index >= self.callers.len() { - self.callers.resize(index + 1, CallerRecord::default()); + self.figures.on_frame_suspend(gas, depth, stipend); } - self.callers[index] = CallerRecord { spent: regular_spent(caller), limit: caller.limit() }; } - /// Starts keeping the frames' figures at the first read that sets a limit, made by the frame - /// that runs, at `depth` and whose gas is `gas`. - /// - /// The frames it runs under are those suspended on a running child, and each one's record is - /// the one made when revm built that child: what the frame adds to the transaction's compute is - /// its regular gas spent then less the child's gas limit — the next record's, or the reading - /// frame's own for the last. They are added in the order the frames started, as they would - /// have been when each child first ran. - #[cold] - #[inline(never)] - fn track(&mut self, gas: &Gas, depth: usize) { - // Every frame below the reading one was built in the transaction while no read had set a - // limit, so revm building it recorded its caller. - let records = &self.callers[..depth]; - let reading_limit = gas.limit(); - let figures = &mut self.figures; - figures.clear(); - for (index, record) in records.iter().enumerate() { - let child_limit = records.get(index + 1).map_or(reading_limit, |child| child.limit); - let contribution = record.spent.saturating_sub(child_limit); - figures.suspended = figures.suspended.saturating_add(contribution); - figures.frames.push(DetainedFrame { at_suspension: record.spent, contribution }); - } - figures.frames.push(DetainedFrame::default()); - #[cfg(debug_assertions)] - self.eager.assert_kept(&self.figures); - } - - /// Records a read of `access` the running frame, at `depth` and whose gas is `gas`, makes - /// itself rather than through an opcode — a keyless deployment's call reading its signer's - /// account — and holds the frame to the limit it sets, as an opcode's read is committed + /// Records a read of `access` the running frame, whose gas is `gas`, makes itself rather than + /// through an opcode — a keyless deployment's call reading its signer's account — and holds + /// the frame to the limit it sets, as an opcode's read is committed /// ([`commit_reads`](Self::commit_reads)). A transaction detention does not hold records /// nothing, as the Host observes nothing for it. - pub(crate) fn read_by_frame( - &mut self, - access: VolatileDataAccess, - gas: &mut Gas, - depth: usize, - ) { + pub(crate) fn read_by_frame(&mut self, access: VolatileDataAccess, gas: &mut Gas) { if self.detains { - self.commit_reads(access, gas, depth, 0); + self.commit_reads(access, gas, 0); } } /// The frame at `depth` returns `result` with `gas`, after it ran. The switch turns back on if - /// the frame, or a frame below it, turned it off. A frame that halts burns what it had left. + /// the frame, or a frame below it, turned it off. A frame that halts burns what it had left: + /// for an out-of-gas, whose halt zeroed the frame's gas, the regular gas the revm fork + /// recorded before the failed charge, or before the halt when no charge failed + /// (`failed_charge_remaining`); for any other halt, which zeroes nothing, the gas the frame + /// returns. /// - /// Returns the stop when the frame ran out of gas on a charge the withheld part of its gas + /// Returns the stop when the frame halted out of gas on a charge the withheld part of its gas /// would have paid ([`stop`](Self::stop)): the frame crossed the limit, and must revert with /// the stop rather than halt. The stop's compute is the transaction's with the frame's gas - /// put back. + /// put back. A crossing only ever ends a frame on an out-of-gas, so a frame that returns with + /// any other result crossed nothing, whatever record its gas carries: the record of a charge + /// an inspector's callback failed stops no frame that ran on and ended otherwise. The frame's + /// result is read as its run left it, before an inspector sees it, so what an inspector makes + /// of it afterwards is taken as given. #[inline] pub(crate) fn on_frame_end( &mut self, @@ -552,28 +463,24 @@ impl Detention { gas: &mut Gas, depth: usize, ) -> Option { - let left_at_halt = self.left_at_halt.take(); if self.disabled_from.is_some_and(|from| from >= depth) { self.disabled_from = None; } if !self.detains { return None; } - #[cfg(debug_assertions)] - self.eager.on_frame_end(depth); - if self.limit.is_some() { - self.figures.on_frame_end(depth); - #[cfg(debug_assertions)] - self.eager.assert_kept(&self.figures); - } - if let Some(limit) = self.stop(gas) { - return Some(ComputeStop { limit, used: self.compute(gas) }); + self.figures.on_frame_end(depth); + if !result.is_halt() { + return None; } - if result.is_halt() { - // The settlement rolls the spill back into regular gas and burns it all. - let left = left_at_halt.unwrap_or_else(|| gas.remaining()); - self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled()); + if is_out_of_gas(result) { + if let Some(limit) = self.stop(gas) { + return Some(ComputeStop { limit, used: self.compute(gas.tracker()) }); + } } + // The settlement rolls the spill back into regular gas and burns it all. + let left = gas.failed_charge_remaining().unwrap_or_else(|| gas.remaining()); + self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled()); None } @@ -587,7 +494,8 @@ impl Detention { /// The frame at `depth`, whose gas limit was `gas_limit`, was answered without running — /// `result` is the answer: a precompile's, an interceptor's, a `keylessDeploy` call's that - /// carries value, an inspector's, or revm's for a call it did not start. + /// carries value, or revm's for a call it did not start. An inspector's answer never reaches + /// the engine's frame start, and is taken as given. /// /// An answer marked as a crossing — a precompile whose price crosses the limit /// ([`cross_at_price`](Self::cross_at_price)), or one the engine cannot price that ran out of @@ -671,9 +579,8 @@ impl Detention { // The answer spent more than the allowance, and no more than the gas limit, so the // gas limit is above the allowance and the frame would have had the rest withheld. The // one answer of the engine's own that spends regular gas is that of a `keylessDeploy` - // call carrying value; the limit is set to the forward all the same, so - // an inspector's answer built on another limit is settled on what the frame was - // forwarded. + // call carrying value, which is built on the forward; the limit is set to the forward, + // so the stop settles on what the frame was forwarded. // // The record holds the regular gas the frame had before the charge: the gas limit, // less the state and history gas that spilled onto it, which the revert that settles @@ -689,7 +596,7 @@ impl Detention { // had before the charge: the forward less the spill here, the forward for a precompile's, // which spills nothing. Put back, it leaves the answer no regular gas spent, so the stop's // compute is the transaction's when the frame started. - debug_assert_eq!(regular_spent(&result.gas), 0, "a stopped answer spent nothing"); + debug_assert_eq!(regular_spent(result.gas.tracker()), 0, "a stopped answer spent nothing"); Some(ComputeStop { limit, used: self.compute_at_start(depth, gas_limit) }) } @@ -729,12 +636,12 @@ impl Detention { /// /// The frame's regular gas is put back to what it had before the charge that crossed, the /// record's [`remaining`](WithheldCrossing::remaining): the charge is not made, so the - /// transaction is billed its compute at the crossing, less than one charge short of the limit, - /// and all the frame had left, its spendable and withheld parts together, goes back to its - /// caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, - /// or `return_create`'s own out-of-gas on a deposit charge), the settlement is the same. A - /// crossing only ever ends a frame on an out-of-gas, and only a frame detention held carries - /// one. + /// transaction's compute at the crossing is less than one charge short of the limit, and it is + /// billed that compute less the stipends of its value calls, and all the frame had left, its + /// spendable and withheld parts together, goes back to its caller. Whether the halt already + /// zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, or `return_create`'s own + /// out-of-gas on a deposit charge), the settlement is the same. A crossing only ever ends a + /// frame on an out-of-gas, and only a frame detention held carries one. fn stop(&self, gas: &mut Gas) -> Option { let crossing = gas.withheld_crossing()?; gas.set_remaining(crossing.remaining()); @@ -781,16 +688,23 @@ impl Detention { /* Helpers */ /// The transaction's compute while the running frame has `gas`. - fn compute(&self, gas: &Gas) -> u64 { - self.figures.suspended.saturating_add(regular_spent(gas)).saturating_sub(self.burned) + fn compute(&self, gas: &GasTracker) -> u64 { + let figures = &self.figures; + figures + .suspended + .saturating_add(regular_spent(gas)) + .saturating_add(figures.stipends) + .saturating_sub(self.burned) } /// The transaction's compute when a frame at `depth` with `gas_limit` starts, before it runs /// anything: every suspended caller's, the frame's own caller's included. fn compute_at_start(&self, depth: usize, gas_limit: u64) -> u64 { - self.figures + let figures = &self.figures; + figures .suspended - .saturating_add(self.figures.caller_contribution(depth, gas_limit)) + .saturating_add(figures.caller_contribution(depth, gas_limit)) + .saturating_add(figures.stipends) .saturating_sub(self.burned) } @@ -846,10 +760,23 @@ pub fn decode_volatile_data_access_disabled(revert_data: &[u8]) -> Option bool { + matches!( + result, + InstructionResult::OutOfGas | + InstructionResult::MemoryOOG | + InstructionResult::MemoryLimitOOG | + InstructionResult::PrecompileOOG | + InstructionResult::InvalidOperandOOG | + InstructionResult::ReentrancySentryOOG + ) +} + /// The regular gas a frame spent: its limit, less what it has left — the withheld part included — /// less the state and history gas that spilled onto its regular gas. #[inline] -pub(crate) const fn regular_spent(gas: &Gas) -> u64 { +pub(crate) const fn regular_spent(gas: &GasTracker) -> u64 { gas.limit().saturating_sub(gas.remaining()).saturating_sub(gas.state_gas_spilled()) } @@ -890,7 +817,7 @@ mod tests { let mut frame = gas(100_000_000, 7); detention.on_frame_run(&mut frame, 0); assert!(frame.record_regular_cost(1_000)); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert_eq!(detention.compute_limit(), Some(1_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); @@ -906,9 +833,9 @@ mod tests { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert!(frame.record_regular_cost(5_000)); - detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0); assert_eq!(detention.compute_limit(), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS)); assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000); } @@ -920,10 +847,10 @@ mod tests { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert!(frame.record_state_cost(1_000_000)); - detention.hold(&mut frame); - assert_eq!(detention.compute(&frame), 0); + detention.hold(frame.tracker_mut()); + assert_eq!(detention.compute(frame.tracker()), 0); assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); } @@ -938,7 +865,7 @@ mod tests { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert!(frame.record_regular_cost(10)); assert!(!frame.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS)); if zeroed { @@ -949,7 +876,39 @@ mod tests { assert_eq!(stop, Some(ComputeStop { limit, used: 10 }), "{result:?}"); assert_eq!(frame.remaining(), 100_000_000 - 10); assert_eq!(frame.withheld_crossing(), None); - assert_eq!(regular_spent(&frame), 10, "the charge that crossed is not made"); + assert_eq!(regular_spent(frame.tracker()), 10, "the charge that crossed is not made"); + } + } + + /// A frame that ends with anything but an out-of-gas crossed nothing, whatever record of a + /// crossing its gas carries — a charge an inspector's callback failed, left on a frame that + /// ran on and ended otherwise: it is no stop, its gas is left as it ended, and a halt burns + /// what its failed charge recorded. + #[test] + fn test_only_an_out_of_gas_is_a_crossings_end() { + for result in [ + InstructionResult::Return, + InstructionResult::Revert, + InstructionResult::InvalidFEOpcode, + InstructionResult::OutOfGas, + ] { + let mut detention = detaining(); + let mut frame = gas(100_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); + assert!(frame.record_regular_cost(10)); + assert!(!frame.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS)); + let stop = detention.on_frame_end(result, &mut frame, 0); + if result == InstructionResult::OutOfGas { + let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS; + assert_eq!(stop, Some(ComputeStop { limit, used: 10 }), "{result:?}"); + continue; + } + assert_eq!(stop, None, "{result:?}: no stop"); + assert!(frame.withheld_crossing().is_some(), "{result:?}: the record is left as it is"); + assert_eq!(frame.remaining(), 100_000_000 - 10, "{result:?}: the gas as it ended"); + let burned = if result.is_halt() { 100_000_000 - 10 } else { 0 }; + assert_eq!(detention.burned, burned, "{result:?}: a halt burns what it had"); } } @@ -960,10 +919,10 @@ mod tests { let mut detention = detaining(); let mut caller = gas(100_000_000, 0); detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); assert!(caller.record_regular_cost(7_000)); assert!(caller.record_withheld_first_cost(50_000_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let mut child = gas(50_000_000, 0); detention.on_frame_run(&mut child, 1); assert_eq!(child.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 7_000); @@ -983,9 +942,8 @@ mod tests { let mut detention = detaining(); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert!(!frame.record_regular_cost(100_000_001)); - detention.note_halt(frame.remaining()); frame.spend_all(); assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); assert_eq!(detention.burned, 100_000_000); @@ -994,44 +952,49 @@ mod tests { let mut detention = detaining(); let mut frame = gas(1_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); assert_eq!(frame.withheld(), 0, "nothing to withhold"); assert!(!frame.record_regular_cost(1_000_001)); frame.spend_all(); assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None); } - /// A child's compute adds to its caller's; the caller's forwarded gas and the child's stipend - /// do not, and after the child returns the caller's own gas accounts for it the same way. + /// A child's compute adds to its caller's, what it runs on a value call's stipend included; + /// the gas the caller forwarded does not. After the child returns, the caller's own gas holds + /// what the child ran but for the stipend, which it got back on top of its forward, and the + /// stipend is counted apart: the figure is the same. #[test] fn test_compute_spans_frames() { - let mut detention = detaining(); - detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); - let mut caller = gas(100_000, 0); - detention.on_frame_run(&mut caller, 0); - assert!(caller.record_regular_cost(9_000 + 60_000)); - detention.on_frame_suspend(&caller, 0); - assert_eq!(detention.compute_at_start(1, 60_000 + 2_300), 9_000 - 2_300); + for spent in [4_000, 61_000] { + let mut detention = detaining(); + detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); + let mut caller = gas(100_000, 0); + detention.on_frame_run(&mut caller, 0); + assert!(caller.record_regular_cost(9_000 + 60_000)); + detention.on_frame_suspend(&caller, 0, 2_300); + assert_eq!(detention.compute_at_start(1, 60_000 + 2_300), 9_000); - let mut child = gas(60_000 + 2_300, 0); - detention.on_frame_run(&mut child, 1); - assert_eq!(detention.compute(&child), 9_000 - 2_300); - assert!(child.record_regular_cost(4_000)); - assert_eq!(detention.compute(&child), 9_000 + 4_000 - 2_300); - detention.on_frame_end(InstructionResult::Stop, &mut child, 1); + let mut child = gas(60_000 + 2_300, 0); + detention.on_frame_run(&mut child, 1); + assert_eq!(detention.compute(child.tracker()), 9_000); + assert!(child.record_regular_cost(spent)); + assert_eq!(detention.compute(child.tracker()), 9_000 + spent, "{spent}"); + detention.on_frame_end(InstructionResult::Stop, &mut child, 1); - caller.erase_cost(child.remaining()); - detention.on_frame_run(&mut caller, 0); - assert_eq!(detention.compute(&caller), 9_000 + 4_000 - 2_300); - assert_eq!(detention.figures.suspended, 0); + caller.erase_cost(child.remaining()); + assert_eq!(regular_spent(caller.tracker()), 9_000 + spent - 2_300, "{spent}"); + detention.on_frame_run(&mut caller, 0); + assert_eq!(detention.compute(caller.tracker()), 9_000 + spent, "{spent}"); + assert_eq!(detention.figures.suspended, 0); + } } - /// Nothing is kept of the frames before a read sets a limit but what a halt burns and one - /// record per frame revm builds a child of. The first read rebuilds what the frames it runs - /// under add to the transaction's compute from those records: each one's regular gas spent less - /// its child's gas limit, a stipend included, and a halted child's burn taken off. + /// The frames' figures are kept from the transaction's first frame on, before any read: a + /// first read below them sets its limit from what the frames it runs under add to the + /// transaction's compute — each one's regular gas spent less the gas it forwarded its child, + /// which a value call's stipend is no part of — and a halted child's burn taken off. #[test] - fn test_the_first_read_rebuilds_the_compute_of_the_frames_it_runs_under() { + fn test_a_first_read_below_frames_counts_what_they_computed() { const CAP: u64 = 1_000; let mut detention = Detention::default(); detention.reset(true, CAP, CAP); @@ -1041,8 +1004,7 @@ mod tests { // A child that halts after running 1,000 of the 10,000 it was forwarded. assert!(caller.record_withheld_first_cost(10_000)); - detention.on_frame_suspend(&caller, 0); - detention.on_child_build(1, &caller); + detention.on_frame_suspend(&caller, 0, 0); let mut halting = gas(10_000, 0); detention.on_frame_run(&mut halting, 1); assert!(halting.record_regular_cost(1_000)); @@ -1055,26 +1017,25 @@ mod tests { // A value call: 9,000 of its own, 60,000 forwarded and a stipend of 2,300. assert!(caller.record_regular_cost(9_000)); assert!(caller.record_withheld_first_cost(60_000)); - detention.on_frame_suspend(&caller, 0); - detention.on_child_build(1, &caller); + detention.on_frame_suspend(&caller, 0, 2_300); let mut child = gas(60_000 + 2_300, 0); detention.on_frame_run(&mut child, 1); assert!(child.record_regular_cost(4_000)); assert!(child.record_withheld_first_cost(30_000)); - detention.on_frame_suspend(&child, 1); - detention.on_child_build(2, &child); + detention.on_frame_suspend(&child, 1, 0); let mut grandchild = gas(30_000, 0); detention.on_frame_run(&mut grandchild, 2); assert!(grandchild.record_regular_cost(500)); - assert!(detention.figures.frames.is_empty(), "nothing kept before a read"); + assert_eq!(detention.compute_limit(), None, "no read yet"); + assert_eq!(detention.figures.frames.len(), 3, "kept before any read"); assert_eq!(detention.burned, 9_000); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 2, 0); - let caller_adds = 2_000 + 10_000 + 9_000 + 60_000 - (60_000 + 2_300); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 0); + let caller_adds = 2_000 + 10_000 + 9_000 + 60_000 - 60_000; let child_adds = 4_000 + 30_000 - 30_000; assert_eq!(detention.figures.suspended, caller_adds + child_adds); - let compute = 2_000 + 1_000 + 9_000 - 2_300 + 4_000 + 500; - assert_eq!(detention.compute(&grandchild), compute); + let compute = 2_000 + 1_000 + 9_000 + 4_000 + 500; + assert_eq!(detention.compute(grandchild.tracker()), compute); assert_eq!(detention.compute_limit(), Some(compute + CAP)); assert_eq!(grandchild.spendable(), CAP); @@ -1084,41 +1045,21 @@ mod tests { child.erase_cost(grandchild.remaining()); detention.on_frame_run(&mut child, 1); assert_eq!(detention.figures.suspended, caller_adds); - assert_eq!(detention.compute(&child), compute + 600); + assert_eq!(detention.compute(child.tracker()), compute + 600); assert_eq!(child.spendable(), CAP - 600); } - /// A caller is recorded only while it may be needed: the transaction is detained and no read - /// has set a limit yet. From the first read on, the frames are kept as they run. - #[test] - fn test_callers_are_recorded_only_until_the_first_read() { - let mut free = Detention::default(); - free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); - assert!(!free.records_callers(), "a transaction detention does not hold"); - - let mut detention = detaining(); - assert!(detention.records_callers()); - let mut frame = gas(1_000_000, 0); - detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); - assert!(!detention.records_callers(), "a read set a limit"); - - detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); - detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); - assert!(!detention.records_callers(), "a read before any frame set a limit"); - } - /// A transaction can end with frames still running — an error stops it mid-frame — and the - /// next one starts from nothing: a read in its child rebuilds from its own records alone. + /// next one starts from nothing: a read in its child counts its own frames alone. #[test] fn test_a_reset_forgets_the_frames_a_transaction_left_running() { let mut detention = detaining(); let mut caller = gas(1_000_000, 0); detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); assert!(caller.record_regular_cost(7_000)); assert!(caller.record_withheld_first_cost(500_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let mut child = gas(500_000, 0); detention.on_frame_run(&mut child, 1); assert_eq!(detention.figures.suspended, 7_000); @@ -1128,45 +1069,18 @@ mod tests { detention.on_frame_run(&mut caller, 0); assert!(caller.record_regular_cost(3_000)); assert!(caller.record_withheld_first_cost(500_000)); - detention.on_frame_suspend(&caller, 0); - detention.on_child_build(1, &caller); + detention.on_frame_suspend(&caller, 0, 0); let mut child = gas(500_000, 0); detention.on_frame_run(&mut child, 1); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 1, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 0); assert_eq!(detention.figures.suspended, 3_000); assert_eq!(detention.figures.frames.len(), 2); assert_eq!(detention.compute_limit(), Some(3_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); } - /// A reset forgets the callers a transaction recorded: the next one reads only its own. - #[test] - fn test_a_reset_forgets_the_callers_a_transaction_recorded() { - let mut detention = detaining(); - let caller = gas(1_000_000, 0); - detention.on_child_build(1, &caller); - detention.on_child_build(2, &caller); - assert_eq!(detention.callers.len(), 2); - - detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); - assert!(detention.callers.is_empty()); - } - - /// The eager figures debug builds keep catch a kept figure that parts from them. - #[cfg(debug_assertions)] - #[test] - #[should_panic(expected = "the compute of the suspended frames")] - fn test_the_eager_figures_catch_a_kept_one_that_parts_from_them() { - let mut eager = FrameFigures::default(); - eager.on_frame_run(1_000_000, 0); - let mut kept = eager.clone(); - eager.assert_kept(&kept); - kept.suspended = 1; - eager.assert_kept(&kept); - } - /// What a halting child burns is not compute: its caller's compute after it returns is what /// the child ran, not the gas the child was given — whether the halt left the gas in place or - /// zeroed it after the child's wrapper noted it. + /// zeroed it after the failed charge recorded what the child had. #[test] fn test_what_a_halt_burns_is_not_compute() { for zeroed in [false, true] { @@ -1174,13 +1088,13 @@ mod tests { let mut caller = gas(1_000_000, 0); detention.on_frame_run(&mut caller, 0); assert!(caller.record_regular_cost(500_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let mut child = gas(500_000, 0); detention.on_frame_run(&mut child, 1); assert!(child.record_regular_cost(1_000)); assert!(child.record_state_cost(3_000)); let result = if zeroed { - detention.note_halt(child.remaining()); + assert!(!child.record_regular_cost(u64::MAX)); child.spend_all(); InstructionResult::OutOfGas } else { @@ -1190,7 +1104,7 @@ mod tests { // The caller's regular gas spent now holds everything it forwarded. detention.on_frame_run(&mut caller, 0); - assert_eq!(detention.compute(&caller), 1_000, "zeroed: {zeroed}"); + assert_eq!(detention.compute(caller.tracker()), 1_000, "zeroed: {zeroed}"); assert_eq!(detention.burned, 500_000 - 1_000); } } @@ -1203,9 +1117,9 @@ mod tests { let mut detention = detaining(); let mut caller = gas(100_000_000, 0); detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); assert!(caller.record_withheld_first_cost(90_000_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let answer = |spent: u64, result| { let mut gas = gas(90_000_000, 0); @@ -1240,7 +1154,7 @@ mod tests { ); assert_eq!(beyond.result, InstructionResult::OutOfGas); assert_eq!(beyond.gas.remaining(), 90_000_000 - spill); - assert_eq!(regular_spent(&beyond.gas), 0); + assert_eq!(regular_spent(beyond.gas.tracker()), 0); } } @@ -1253,9 +1167,9 @@ mod tests { let mut detention = detaining(); let mut caller = gas(100_000_000, 0); detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); assert!(caller.record_withheld_first_cost(90_000_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let answer = |spent: u64| { let mut gas = gas(90_000_000, 0); assert!(gas.record_regular_cost(spent)); @@ -1291,9 +1205,9 @@ mod tests { let mut detention = detaining(); let mut caller = gas(100_000_000, 0); detention.on_frame_run(&mut caller, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0); assert!(caller.record_withheld_first_cost(90_000_000)); - detention.on_frame_suspend(&caller, 0); + detention.on_frame_suspend(&caller, 0, 0); let allowance = detention.allowance(1, 90_000_000).unwrap(); assert_eq!(allowance, BLOCK_ENV_ACCESS_COMPUTE_GAS); let withheld = NonZeroU64::new(90_000_000 - allowance).unwrap(); @@ -1348,10 +1262,10 @@ mod tests { assert!(call.record_regular_cost(112_000)); assert!(call.record_withheld_first_cost(50_000_000)); - detention.on_frame_suspend(&call, 0); + detention.on_frame_suspend(&call, 0, 0); let mut creation = gas(50_000_000, 0); detention.on_frame_run(&mut creation, 1); - assert_eq!(detention.compute(&creation), 112_000, "the charges, not the forward"); + assert_eq!(detention.compute(creation.tracker()), 112_000, "the charges, not the forward"); assert_eq!(creation.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000); assert_eq!(detention.allowance(2, 0), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000)); } @@ -1364,14 +1278,14 @@ mod tests { let mut call = gas(100_000_000, 0); detention.on_frame_run(&mut call, 0); assert!(call.record_regular_cost(100_000)); - detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0); + detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call); assert_eq!(detention.compute_limit(), Some(100_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS)); assert_eq!(detention.accessed(), VolatileDataAccess::BENEFICIARY_BALANCE); assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS); let mut free = Detention::default(); free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS); - free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0); + free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call); assert_eq!((free.compute_limit(), free.accessed()), (None, VolatileDataAccess::empty())); } @@ -1382,7 +1296,7 @@ mod tests { let mut detention = detaining(); let mut frame = gas(1_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.on_frame_suspend(&frame, 0); + detention.on_frame_suspend(&frame, 0, 0); let mut child = gas(100_000, 0); detention.on_frame_run(&mut child, 1); detention.disable_access(2); @@ -1396,8 +1310,10 @@ mod tests { detention.disable_access(2); assert!(detention.is_access_disabled(1), "a deeper frame keeps the shallower switch"); assert!(!detention.enable_access(2), "a frame below cannot switch it back on"); + detention.begin_read(); assert!(detention.refuses(VolatileDataAccess::BLOCK_NUMBER)); detention.name_refusal(VolatileDataAccess::BLOCK_HASH); + detention.end_read(); assert_eq!(detention.take_refused(), Some(VolatileDataAccess::BLOCK_HASH)); detention.name_refusal(VolatileDataAccess::BLOCK_HASH); assert_eq!(detention.take_refused(), None, "nothing refused, nothing named"); @@ -1409,10 +1325,42 @@ mod tests { detention.disable_access(0); detention.on_frame_run(&mut frame, 0); + detention.begin_read(); assert!(detention.refuses(VolatileDataAccess::TIMESTAMP)); + detention.end_read(); + assert_eq!(detention.take_refused(), Some(VolatileDataAccess::TIMESTAMP)); assert!(detention.enable_access(0), "the frame that switched it off switches it on"); detention.on_frame_run(&mut frame, 0); + detention.begin_read(); assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP)); + detention.end_read(); + } + + /// The Host refuses and marks a load only while a read wrapper runs its opcode: a load outside + /// one — a creation's of its creator or created address, an inspector's — is neither refused + /// nor marked, whether the frame's access is on or off. + #[test] + fn test_only_a_read_wrappers_load_is_refused_or_marked() { + let beneficiary = VolatileDataAccess::BENEFICIARY_BALANCE; + let mut detention = detaining(); + let mut frame = gas(1_000_000, 0); + detention.on_frame_run(&mut frame, 0); + detention.observe(beneficiary); + assert!(!detention.has_reads(), "a load outside a read marks nothing"); + detention.begin_read(); + detention.observe(beneficiary); + detention.end_read(); + assert_eq!(detention.take_observed(), beneficiary); + + detention.disable_access(0); + detention.on_frame_run(&mut frame, 0); + assert!(detention.is_refusing()); + assert!(!detention.refuses(beneficiary), "a load outside a read is not refused"); + assert!(!detention.has_reads()); + detention.begin_read(); + assert!(detention.refuses(beneficiary)); + detention.end_read(); + assert_eq!(detention.take_refused(), Some(beneficiary)); } /// A refusal's revert data decodes back to the kind it names, for every kind the engine @@ -1505,11 +1453,11 @@ mod tests { assert!(detention.detains()); let mut frame = gas(100_000_000, 0); detention.on_frame_run(&mut frame, 0); - detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0); detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); assert_eq!(detention.compute_limit(), None, "an unlimited cap sets no limit"); assert_eq!(frame.withheld(), 0); - detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0); + detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0); assert_eq!(detention.compute_limit(), Some(5)); } } diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs index d02593039..613c9161a 100644 --- a/crates/mega-evm/src/access/mod.rs +++ b/crates/mega-evm/src/access/mod.rs @@ -37,22 +37,27 @@ //! (which every account opcode and every call goes through, the EIP-7702 delegate's included), its //! storage load and its `SELFDESTRUCT`. A load that fails — a cold account the frame cannot pay //! for, a database error — marks nothing, and neither does an opcode that fails after the load: -//! the Host only observes, and the opcode's wrapper commits the read once the opcode completed, -//! as it does with a write record. +//! the Host only marks the read, and the opcode's wrapper commits it once the opcode completed, as +//! a write record is counted only once its opcode completed. +//! +//! A load is a read only when one of those opcodes makes it, inside its wrapper. `CREATE` and +//! `CREATE2` load their creator's account and the created address's through the same Host load, +//! to check the creator's balance and nonce and to price the created account; those loads are the +//! creation's own checks, as a value call's check of its caller's balance is the call's, and are +//! neither marked nor refused, whichever of the two accounts is the beneficiary's. //! //! # The cap //! //! Compute is the regular gas the transaction spends on what it runs, read off revm's `Gas`: state //! and history gas that spilled onto regular gas are not compute, gas withheld from regular -//! charges is never spent, and what a halting frame burns is not compute either ([`Detention`]). -//! The one burn counted as compute is what a frame has left when an opcode's static gas fails, -//! which no wrapper sees: per halting frame, under the failed charge's price (at most 4,999, on -//! `SELFDESTRUCT`). Burned gas is counted as compute, so the stop comes earlier, never later. -//! A value call's stipend is not compute either: compute is regular gas drawn from the -//! transaction's own pools, and the stipend is gas nobody paid. A callee may run up to 2,300 gas -//! on each value call's stipend, and a warm value call to an empty account counts 6,800 of compute -//! (9,100, less the 2,300 stipend the callee leaves unspent and returns to its caller), so the -//! gas run after a read is at most about 34% (2,300 / 6,800) more than the cap. +//! charges is never spent, and what a halting frame burns is not compute either ([`Detention`]), +//! whatever charge it failed on, an opcode's static gas included: the revm fork records what the +//! frame had before the halt zeroed it. What a callee runs on a value call's stipend is compute, as +//! everything a frame runs is: compute counts every regular charge an instruction makes, whoever +//! funds it, and nothing else, so the gas run after a read is at most the cap. The stipend itself +//! is gas nobody paid, so the regular ledger bills the transaction its compute less the stipends of +//! its value calls. A precompile that runs out of gas counts nothing of its forward: it burns it, +//! as a halting frame burns what it has left. //! //! A read sets a limit: the transaction's compute at the read plus the read's cap. The limit only //! goes down, so the most restrictive of several reads is the one that binds, whatever their @@ -64,7 +69,7 @@ //! the frame runs out of regular gas. So the cap is enforced through the frame's gas, with the //! revm fork's two parts of a frame's regular gas: a spendable part, the only one a regular charge //! draws, and a withheld part. Every other reader of the frame's gas sees the two together — `GAS`, -//! the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold +//! the 98/100 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold //! checks, the gas a child returns, the reimbursement — and a forward or a state or history spill //! draws the withheld part first. //! diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs index 54531548f..62e245c28 100644 --- a/crates/mega-evm/src/block/eips.rs +++ b/crates/mega-evm/src/block/eips.rs @@ -5,7 +5,8 @@ //! sequence of committed states, read and write sets whole, is what a node's witness generator //! collects through a commit hook on the block's state. //! -//! A pre-block call is a system call on [`pre_block_call_gas_limit`], and a block whose +//! A pre-block call is a system call on +//! [`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT), and a block whose //! pre-block call does not succeed is refused: the state the protocol maintains before the //! block's transactions is not optional, and a block that could not write it is not one the //! chain can build on. A database error the database calls fatal is not a verdict on the block: @@ -30,12 +31,9 @@ use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use alloy_hardforks::EthereumHardforks; use alloy_primitives::{Address, Bytes, B256}; use op_revm::OpHaltReason; -use revm::{ - context::{ - result::{EVMError, ResultAndState}, - Block, ContextTr, DBErrorMarker, - }, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, +use revm::context::{ + result::{EVMError, ResultAndState}, + Block, ContextTr, DBErrorMarker, }; use crate::{ExternalEnvTypes, MegaEvm}; @@ -43,24 +41,10 @@ use crate::{ExternalEnvTypes, MegaEvm}; /// The caller every pre-block system call runs as. pub use alloy_eips::eip4788::SYSTEM_ADDRESS; -/// The gas limit of every pre-block system call in a block whose gas limit is `block_gas_limit`: -/// the block's gas limit, and never less than 30,000,000. -/// -/// It is the legacy engine's budget, kept as it was rather than replaced by a number nobody -/// chose. The legacy engine sized it to absorb the storage gas a crowded SALT bucket multiplies, -/// which could take a pre-block write past revm's 30M default. On Satin neither half of that -/// holds: a system call prices its state at the minimum bucket, and it runs on at most -/// 30,000,000 of regular gas, the rest of its gas limit being its state-gas reservoir. So what -/// this budget adds above 30M is reservoir, which the call's writes draw first and which nobody -/// pays for when they do not, and the regular budget is 30M whatever the block. In a block whose -/// gas limit is 30M or less the call has no reservoir, and its writes are paid out of the -/// regular budget, which holds them many times over. -pub fn pre_block_call_gas_limit(block_gas_limit: u64) -> u64 { - block_gas_limit.max(SYSTEM_CALL_REGULAR_GAS_LIMIT) -} - /// Runs the pre-block call `name`: a system call from [`SYSTEM_ADDRESS`] to `target` with `data`, -/// on the pre-block budget of the block `evm` is set up for ([`pre_block_call_gas_limit`]). +/// on the pre-block budget +/// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), whatever the +/// block's gas limit. /// Answers its result and state; nothing is committed. /// /// One rule holds for every pre-block call, and it is the rule alloy-evm's block executor holds a @@ -85,15 +69,13 @@ where DB: alloy_evm::Database, ExtEnvs: ExternalEnvTypes, { - let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit()); - let outcome = - match evm.transact_system_call_with_gas_limit(SYSTEM_ADDRESS, target, data, gas_limit) { - Ok(outcome) => outcome, - Err(EVMError::Database(error)) if error.is_fatal() => { - return Err(BlockExecutionError::other(error)) - } - Err(error) => return Err(refused(error.to_string())), - }; + let outcome = match evm.transact_pre_block_system_call(SYSTEM_ADDRESS, target, data) { + Ok(outcome) => outcome, + Err(EVMError::Database(error)) if error.is_fatal() => { + return Err(BlockExecutionError::other(error)) + } + Err(error) => return Err(refused(error.to_string())), + }; if !outcome.result.is_success() { let message = format!("the {name} pre-block call did not succeed: {:?}", outcome.result); return Err(refused(message)); diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs index 39ae6ab14..92e174a38 100644 --- a/crates/mega-evm/src/block/executor.rs +++ b/crates/mega-evm/src/block/executor.rs @@ -30,18 +30,6 @@ //! block contract reads as zeroes, not as an error, and a caller that placed its own info for //! this block keeps it. alloy-op-evm's executor pre-loads no info either. //! -//! # The admission gate -//! -//! Block execution refuses an inspector that may rewrite what execution produces -//! ([`MegaEvm::has_rewriting_inspector`]). alloy-evm's `BlockExecutorFactory` asks for an executor -//! for every `I: Inspector`, so the refusal cannot be a bound on the type: it is checked at every -//! entry point that runs code or moves the block on — the pre-block changes, the execution of a -//! transaction, the commit of an outcome and the end of the block — before anything changes. The -//! trusted route -//! ([`create_executor_with_trusted_inspector`](crate::MegaBlockExecutorFactory::create_executor_with_trusted_inspector)) -//! is the compile-time proof that an inspector observes and writes nothing back; the generic route -//! is the checked one. -//! //! # Committing an outcome //! //! alloy-evm's [`commit_transaction`](BlockExecutor::commit_transaction) cannot fail. Its contract @@ -90,8 +78,9 @@ //! and EIP-4788 calls, in the block in which Satin activates checks that the system contracts and //! the EIP-7997 factory hold the code Satin expects, then applies a role change the //! `SequencerRegistry` has due in this block. Every call is a system call -//! on the pre-block budget ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)), and -//! one that does not succeed refuses the block. +//! on the pre-block budget +//! ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), and one that does +//! not succeed refuses the block. //! //! The pre-block step does not read the live system address, but it is what leaves the registry //! naming this block's address. The executor reads the address off the block's state before every @@ -225,11 +214,6 @@ pub enum MegaBlockExecutionError { /// The footprint the block has left. available_block_da_footprint: u64, }, - /// The EVM runs an inspector that may rewrite what execution produces, which block execution - /// does not admit. - /// - /// The inspector is the node's own choice, not a verdict on the block: an internal error. - RewritingInspector, /// In the block in which Satin activates, a predeploy's address does not hold the code Satin /// expects: it holds other code, an older version of the contract, no code, or no account. /// @@ -277,9 +261,6 @@ impl fmt::Display for MegaBlockExecutionError { transaction_da_footprint: {transaction_da_footprint}, \ available_block_da_footprint: {available_block_da_footprint}" ), - Self::RewritingInspector => f.write_str( - "block execution does not admit an inspector that may rewrite execution", - ), Self::UnexpectedSystemContractCode { address, expected, found } => { write_unexpected_code(f, *address, *expected, *found) } @@ -298,13 +279,12 @@ impl fmt::Display for MegaBlockExecutionError { impl core::error::Error for MegaBlockExecutionError {} impl From for BlockExecutionError { - /// A block refused for what the node itself does is an internal error: an inspector the node - /// runs that may rewrite execution, or an outcome the builder let go stale, says nothing about - /// the block, and a node must not mark a block invalid because of its own choices. Every other + /// A block refused for what the node itself does is an internal error: an outcome the builder + /// let go stale says nothing about the block, and a node must not mark a block invalid because + /// of its own choices. Every other /// refusal is a verdict on the block, a validation error. fn from(error: MegaBlockExecutionError) -> Self { match error { - MegaBlockExecutionError::RewritingInspector | MegaBlockExecutionError::StaleOutcome { .. } => Self::other(error), MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock | MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | @@ -405,14 +385,16 @@ where /// test's, which a node executing the chain never runs. /// /// Their per-transaction half is installed on the EVM and before every transaction from now - /// on, and the block's data-size budget is theirs, lowered to the building policy where that - /// is lower. What the block counted so far stays counted. Behind the `test-utils` feature, so - /// a node build cannot reach it. + /// on, and the block's packing budgets are theirs, each lowered to the building policy where + /// that is lower. What the block counted so far stays counted. Behind the `test-utils` feature, + /// so a node build cannot reach it. #[cfg(any(test, feature = "test-utils"))] pub fn with_protocol_limits(mut self, limits: ProtocolLimits) -> Self { self.evm.set_tx_runtime_limits(limits.tx_runtime_limits); - self.limiter.limits.block_txs_data_limit = - self.ctx.block_limits.within(&limits).block_txs_data_limit; + let held = self.ctx.block_limits.within(&limits); + self.limiter.limits.block_txs_data_limit = held.block_txs_data_limit; + self.limiter.limits.block_kv_update_limit = held.block_kv_update_limit; + self.limiter.limits.block_state_growth_limit = held.block_state_growth_limit; self.protocol_limits = limits; self } @@ -532,19 +514,6 @@ where .map_err(BlockExecutionError::other)?; Ok(classify_system_transaction(tx, system_address).unwrap_or(false)) } - - /// Refuses an EVM that runs an inspector which may rewrite what execution produces. - /// - /// Checked at every entry point rather than once, because the inspector can be enabled after - /// the block was set up ([`Evm::set_inspector_enabled`] through - /// [`evm_mut`](BlockExecutor::evm_mut)) and because a caller may run transactions without - /// calling [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) at all. - fn check_admission(&self) -> Result<(), BlockExecutionError> { - if self.evm.has_rewriting_inspector() { - return Err(MegaBlockExecutionError::RewritingInspector.into()); - } - Ok(()) - } } impl MegaBlockExecutor, R, Spec> @@ -625,7 +594,7 @@ where /// Runs what a block does before its transactions. /// - /// In order: the admission gate, the reset of the block-hash and bucket records, the EIP-2935 + /// In order: the reset of the block-hash and bucket records, the EIP-2935 /// and EIP-4788 pre-block calls, in the block in which Satin activates the check of the /// predeploys, the `SequencerRegistry`'s due role changes and the read of the L1 block info. /// Each step's state is committed here, on its own and read-only entries included, rather @@ -643,8 +612,8 @@ where /// parent beacon root into their own contracts (`0x0…2935` and `0x0…4788`), which are not /// `MegaETH` system contracts and do not read them, so their outcome does not depend on the /// check that follows. Each runs on the pre-block budget - /// ([`pre_block_call_gas_limit`](eips::pre_block_call_gas_limit)), and one that does not - /// succeed refuses the block before its state is committed. + /// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), and one that + /// does not succeed refuses the block before its state is committed. /// /// The check is made once, in the block in which Satin activates /// ([`MegaBlockExecutionCtx::satin_activation_block`]): each of the seven predeploys must hold @@ -661,8 +630,6 @@ where /// it is validated, after these steps are committed, and nothing inside the block can /// change it again. fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { - self.check_admission()?; - // The block starts with empty block-hash and bucket records, so what they hold at the end // is what this block read. self.evm.clear_accessed_block_hashes(); @@ -892,7 +859,7 @@ where self.execute(tx, Some(reported)) } - /// Re-checks the block's admission and commits `output`. + /// Re-checks the block's limits and commits `output`. /// /// This is the commit for a builder that executes several candidates and then chooses among /// them: the block's counters may have moved between a candidate executing and its commit, so @@ -911,7 +878,6 @@ where &mut self, output: MegaBlockTxResult<::TxType>, ) -> Result { - self.check_admission()?; self.check_room(&output)?; self.check_sender_unchanged(&output)?; Ok(self.commit_transaction(output)) @@ -927,8 +893,6 @@ where MegaBlockTxResult<::TxType>, BlockExecutionError, > { - self.check_admission()?; - let (tx_env, tx) = tx.into_parts(); let inner = tx.tx(); let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE; @@ -1035,8 +999,6 @@ where pub fn finish_with_counters( mut self, ) -> Result, BlockExecutionError> { - self.check_admission()?; - let balance_increments = post_block_balance_increments::
(&self.spec, self.evm.block(), &[], None); self.evm @@ -1093,6 +1055,14 @@ mod tests { executor.limiter().limits.block_txs_data_limit, crate::constants::BLOCK_DATA_LIMIT ); + assert_eq!( + ( + executor.limiter().limits.block_kv_update_limit, + executor.limiter().limits.block_state_growth_limit + ), + (crate::constants::BLOCK_KV_UPDATE_LIMIT, crate::constants::BLOCK_STATE_GROWTH_LIMIT), + "and the spec's KV and state-growth budgets" + ); executor.evm_mut().set_inspector_enabled(true); assert!(executor.into_evm().is_inspecting()); } @@ -1117,11 +1087,16 @@ mod tests { assert_eq!(*executor.evm().tx_runtime_limits(), satin.tx_runtime_limits); assert_eq!(executor.limiter().limits.block_txs_data_limit, 13_107_200); - let counterfactual = ProtocolLimits::no_limits().with_block_txs_data_limit(7); + let counterfactual = ProtocolLimits::no_limits() + .with_block_txs_data_limit(7) + .with_block_kv_update_limit(8) + .with_block_state_growth_limit(9); let executor = executor.with_protocol_limits(counterfactual); assert_eq!(executor.protocol_limits(), &counterfactual); assert_eq!(*executor.evm().tx_runtime_limits(), counterfactual.tx_runtime_limits); assert_eq!(executor.limiter().limits.block_txs_data_limit, 7); + assert_eq!(executor.limiter().limits.block_kv_update_limit, 8); + assert_eq!(executor.limiter().limits.block_state_growth_limit, 9); let tighter = MegaBlockExecutor::new( MegaEvm::new(MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN)), @@ -1146,9 +1121,9 @@ mod tests { .unwrap_or_else(|| panic!("not an internal refusal of this engine: {error:?}")) } - /// Every refusal but those for what the node itself does — an inspector it runs, here — is a - /// verdict on the block: a validation error. A predeploy that does not hold Satin's code when - /// Satin activates is one. + /// Every refusal but those for what the node itself does — an outcome it let go stale, here — + /// is a verdict on the block: a validation error. A predeploy that does not hold Satin's code + /// when Satin activates is one. #[test] fn test_a_refusal_of_the_block_is_a_validation_error() { let address = alloy_primitives::Address::repeat_byte(1); @@ -1172,7 +1147,7 @@ mod tests { }; assert_eq!(inner.downcast_ref::(), Some(&refusal)); } - let inspector = MegaBlockExecutionError::RewritingInspector; - assert_eq!(internal(&BlockExecutionError::from(inspector.clone())), &inspector); + let stale = MegaBlockExecutionError::StaleOutcome { tx_hash: B256::ZERO, sender: address }; + assert_eq!(internal(&BlockExecutionError::from(stale.clone())), &stale); } } diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs index 3e4e7bc55..4f3339975 100644 --- a/crates/mega-evm/src/block/factory.rs +++ b/crates/mega-evm/src/block/factory.rs @@ -4,14 +4,14 @@ use alloy_consensus::{Transaction, TxReceipt}; use alloy_eips::Encodable2718; use alloy_evm::{ block::{BlockExecutorFactory, StateDB}, - EvmEnv, EvmFactory, FromRecoveredTx, FromTxWithEncoded, + FromRecoveredTx, FromTxWithEncoded, }; use alloy_op_evm::block::receipt_builder::OpReceiptBuilder; use revm::Inspector; use crate::{ ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockTxResult, MegaContext, - MegaEvm, MegaEvmFactory, MegaHardforks, MegaSpecId, MegaTransaction, TrustedObserver, + MegaEvm, MegaEvmFactory, MegaHardforks, MegaTransaction, }; /// Creates the block executors a node drives. @@ -51,36 +51,6 @@ impl MegaBlockExecutorFactory { } } -impl MegaBlockExecutorFactory> -where - ExtEnvFactory: ExternalEnvFactory, - Spec: MegaHardforks, - R: OpReceiptBuilder, -{ - /// Creates an executor over an EVM that runs a declared observer. - /// - /// This is the one way an inspected transaction reaches a block: the inspector's type - /// declares that it writes nothing back ([`TrustedObserver`]), so what the block executes is - /// what the chain executes, and this bound is the compile-time proof of it. An inspector - /// that arrives through [`create_executor`](BlockExecutorFactory::create_executor) carries no - /// such proof, so block execution checks it at every entry point instead and refuses it with - /// `RewritingInspector`. - pub fn create_executor_with_trusted_inspector( - &self, - db: DB, - evm_env: EvmEnv, - ctx: MegaBlockExecutionCtx, - inspector: I, - ) -> MegaBlockExecutor, &R, &Spec> - where - DB: StateDB, - I: TrustedObserver + Inspector>, - { - let evm = self.evm_factory.create_evm(db, evm_env).with_trusted_inspector(inspector); - MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) - } -} - impl BlockExecutorFactory for MegaBlockExecutorFactory> where @@ -108,10 +78,8 @@ where /// The spec's limits are installed by [`MegaBlockExecutor::new`], so an EVM the caller built /// with others still runs the block's transactions under them. /// - /// alloy-evm asks for an executor for every `I: Inspector`, so this route cannot refuse a - /// rewriting inspector by its type; the executor checks the EVM at every entry point instead. - /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) is - /// the route whose bound proves the inspector observes only. + /// The EVM may carry any inspector: the engine does not refuse one, and a node decides which + /// inspectors run on block production. fn create_executor<'a, DB, I>( &'a self, evm: MegaEvm, diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs index 3fe4ce493..c50facd36 100644 --- a/crates/mega-evm/src/block/genesis.rs +++ b/crates/mega-evm/src/block/genesis.rs @@ -65,11 +65,10 @@ const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number"; /// key cannot stand in for the one it meant, and a file written against an earlier version of the /// format — one that named the registry's roles (`satinInitialSequencer`, ...) or the limits — /// does not load. Every other key is another fork's and is not read. -/// - A key given twice is refused only where the deserializer still shows both copies, as the -/// object's text through a `serde_json::Deserializer` does. A `serde_json::Value` has already -/// kept the last copy, so a reader that parses the file into one first — `mega-evme --genesis` -/// does, and so does a node that serializes its chain-config type — reads the last value and -/// refuses nothing. +/// - A key given twice is read as its last copy, as `serde_json` reads an object into a +/// `serde_json::Value`: a reader handed the object's text, which still shows both copies, and a +/// reader that parses the file into a `Value` first — `mega-evme --genesis` does, and so does a +/// node that serializes its chain-config type — read the same value. /// - A value of the wrong type is refused, naming its key, and so is a schedule /// [`validate_schedule`](MegaHardforks::validate_schedule) refuses. One object is read as an /// integer: `{"$serde_json::private::Number": ""}`, the form `serde_json` hands a number @@ -113,12 +112,9 @@ impl SatinChainConfig { pub fn from_genesis_config<'de, D: Deserializer<'de>>( config: D, ) -> Result, SatinChainConfigError> { - let Entries { mut entries, duplicate } = config + let mut entries = config .deserialize_map(EntriesVisitor) .map_err(|error| SatinChainConfigError::Malformed(error.to_string()))?; - if let Some(key) = duplicate { - return Err(SatinChainConfigError::DuplicateKey(key)); - } if let Some(unknown) = entries.keys().find(|key| !SATIN_CHAIN_CONFIG_KEYS.contains(&key.as_str())) { @@ -175,8 +171,6 @@ pub enum SatinChainConfigError { Malformed(String), /// A key that starts with `satin` but is not `satinTime`. UnknownKey(String), - /// A key that starts with `satin`, given twice. - DuplicateKey(String), /// A key whose value is not of its type. InvalidValue { /// The key. @@ -195,7 +189,6 @@ impl fmt::Display for SatinChainConfigError { write!(f, "the chain configuration is malformed: {message}") } Self::UnknownKey(key) => write!(f, "`{key}` is not a Satin chain-configuration key"), - Self::DuplicateKey(key) => write!(f, "`{key}` is given twice"), Self::InvalidValue { key, expected } => write!(f, "`{key}` must be {expected}"), Self::Schedule(error) => write!(f, "{error}"), } @@ -218,19 +211,12 @@ enum Entry { Other, } -/// A configuration object's entries whose key starts with [`PREFIX`], and the first such key -/// given twice, if one was. -struct Entries { - entries: BTreeMap, - duplicate: Option, -} - -/// Collects a configuration object's entries whose key starts with [`PREFIX`], and skips the -/// others' values without keeping them. +/// Collects a configuration object's entries whose key starts with [`PREFIX`], the last copy of a +/// key given twice, and skips the others' values without keeping them. struct EntriesVisitor; impl<'de> Visitor<'de> for EntriesVisitor { - type Value = Entries; + type Value = BTreeMap; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("a chain configuration object") @@ -238,19 +224,14 @@ impl<'de> Visitor<'de> for EntriesVisitor { fn visit_map>(self, mut map: A) -> Result { let mut entries = BTreeMap::new(); - let mut duplicate = None; while let Some(key) = map.next_key::()? { if is_satin_key(&key) { - let entry = map.next_value::()?; - if entries.contains_key(&key) { - duplicate.get_or_insert_with(|| key.clone()); - } - entries.insert(key, entry); + entries.insert(key, map.next_value::()?); } else { map.next_value::()?; } } - Ok(Entries { entries, duplicate }) + Ok(entries) } } @@ -323,13 +304,16 @@ impl<'de> Visitor<'de> for EntryVisitor { /// `arbitrary_precision` feature, which a node's dependencies may switch on, hands every number /// over as a one-entry map from [`ARBITRARY_PRECISION_NUMBER`] to the number's text. That /// number is read as the same number is read without the feature, so the feature changes - /// nothing a reader accepts. + /// nothing a reader accepts: its text is decimal digits alone, with no sign, which a JSON + /// number cannot carry and `u64::from_str` would otherwise take. fn visit_map>(self, mut map: A) -> Result { let mut entry = Entry::Other; if let Some(key) = map.next_key::()? { if key == ARBITRARY_PRECISION_NUMBER { let text = map.next_value::()?; - entry = text.parse::().map_or(Entry::Other, Entry::Unsigned); + if text.bytes().all(|byte| byte.is_ascii_digit()) { + entry = text.parse::().map_or(Entry::Other, Entry::Unsigned); + } } else { map.next_value::()?; } @@ -527,27 +511,48 @@ mod tests { } } - /// A key given twice is refused where the deserializer shows both, as in the object's text; a - /// `serde_json::Value` has already kept the last one, and a key of another fork given twice is - /// not read. + /// A key given twice is read as its last copy, by every reader: the object's text through a + /// `serde_json::Deserializer`, which shows both copies, reads what a `serde_json::Value`, which + /// kept the last one, reads — the last copy, whether the first is valid or not. A key of + /// another fork given twice is not read. #[test] - fn test_a_key_given_twice_is_refused() { + fn test_the_last_copy_of_a_key_given_twice_is_read() { + let streamed = |text: &str| { + SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(text)) + }; + let as_value = |text: &str| parse(&serde_json::from_str::(text).unwrap()); let text = genesis_config().to_string(); - let twice = text.replacen("\"satinTime\":", "\"satinTime\":1,\"satinTime\":", 1); - assert_eq!( - SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&twice)), - Err(SatinChainConfigError::DuplicateKey(SATIN_TIME_KEY.into())) - ); + let given = |first: &str, last: &str| { + text.replacen( + "\"satinTime\":1800000000", + &format!("\"satinTime\":{first},\"satinTime\":{last}"), + 1, + ) + }; + let refused = Err(SatinChainConfigError::InvalidValue { + key: SATIN_TIME_KEY, + expected: "an integer from 0 to 2^64 - 1", + }); + let at = |time| Ok(Some(SatinChainConfig { activation_time: time })); + for (first, last, expected) in [ + ("1", "1800000000", at(ACTIVATION)), + ("1800000000", "7", at(7)), + ("\"a string\"", "1800000000", at(ACTIVATION)), + ("1800000000", "\"a string\"", refused), + ] { + let twice = given(first, last); + assert_ne!(twice, text, "{first}, then {last}"); + assert_eq!(streamed(&twice), expected, "{first}, then {last}"); + assert_eq!(as_value(&twice), expected, "{first}, then {last}"); + } let other = text.replacen("\"chainId\":", "\"chainId\":1,\"chainId\":", 1); - assert_eq!( - SatinChainConfig::from_genesis_config(&mut serde_json::Deserializer::from_str(&other)), - Ok(Some(config())) - ); + assert_eq!(streamed(&other), Ok(Some(config()))); } /// A number `serde_json` hands over as its `arbitrary_precision` feature does — a map from - /// its token to the number's text — reads as the number, and what the text does not hold as - /// an integer in 64 bits is refused as the number would be; any other map is refused. + /// its token to the number's text — reads as the number. Text that is not an integer in 64 + /// bits written in decimal digits alone — with a sign before them, for one — is refused as the + /// number would be; any other map is refused. #[test] fn test_an_arbitrary_precision_number_reads_as_the_number() { let with_time = |value: Value| { @@ -563,7 +568,9 @@ mod tests { key: SATIN_TIME_KEY, expected: "an integer from 0 to 2^64 - 1", }); - for text in ["1.5", "-1", "18446744073709551616", "1e3"] { + // Decimal digits alone: no sign, which `u64::from_str` would take and the number form + // cannot carry. + for text in ["1.5", "-1", "+7", "+1800000000", "", "18446744073709551616", "1e3"] { assert_eq!(with_time(number(text)), refused, "{text}"); } let mut two = number("1"); @@ -613,9 +620,5 @@ mod tests { .to_string(), "`satinTime` must be an integer" ); - assert_eq!( - SatinChainConfigError::DuplicateKey("satinTime".into()).to_string(), - "`satinTime` is given twice" - ); } } diff --git a/crates/mega-evm/src/block/limit.rs b/crates/mega-evm/src/block/limit.rs index 52a91f768..1274ca0ef 100644 --- a/crates/mega-evm/src/block/limit.rs +++ b/crates/mega-evm/src/block/limit.rs @@ -3,10 +3,11 @@ //! The limits come from two places, by who must agree on them: //! //! - [`ProtocolLimits`] are the limits every node holds a chain's blocks and transactions to, fixed -//! per spec: the per-transaction limits the EVM enforces and the block's data-size budget. +//! per spec: the per-transaction limits the EVM enforces and the block's data-size, KV-update and +//! state-growth budgets. //! - [`BlockLimits`] is the building policy a node passes in the block execution context: the //! limits only a builder applies — a transaction's declared gas, the encoded sizes and the -//! data-availability sizes — and a cap a builder may put on the block's data-size budget below +//! data-availability sizes — and the caps a builder may put on the block's three budgets below //! the protocol's. It never loosens a protocol limit ([`BlockLimits::within`]), and a validator //! leaves it at its default, which restricts nothing. //! @@ -18,11 +19,12 @@ //! its own gas limit, encoded size and data-availability size, and what each of those would add //! to the block. //! -//! The one limit only known after execution — the data-size bytes a transaction kept — is -//! accumulated when the transaction commits. The transaction that crosses it is therefore still -//! packed, and the ones after it are refused; this is what keeps a block full rather than dropping -//! the work already done. A block whose counter has reached its limit refuses every later -//! transaction before it starts — a deposit excepted — so the overshoot is bounded by one +//! The limits only known after execution — the data-size bytes, the write records and the state +//! growth a transaction kept — are accumulated when the transaction commits. The transaction that +//! reaches one is therefore still packed, and the ones after it are refused, the refusal naming the +//! first reached of data size, KV updates and state growth; this is what keeps a block full rather +//! than dropping the work already done. A block whose counter has reached its limit refuses every +//! later transaction before it starts — a deposit excepted — so the overshoot is bounded by one //! transaction, besides what deposits add. //! //! # Deposits @@ -30,11 +32,11 @@ //! A deposit is an L1 message the chain cannot censor: the block derived from L1 must include it, //! and the builder does not choose it. So no limit only a builder applies refuses a deposit — its //! declared gas, its encoded size and its data-availability size, and what those add to the block -//! — and a deposit does not count towards the block's data-availability size. The data-size limit -//! is a packing budget for the transactions the builder chooses, so it does not refuse a deposit -//! either. A deposit still counts towards it, and towards the block's encoded size, so the -//! transactions after it find the room it used. The one limit that holds a deposit is -//! the block's gas limit, which is the header's. +//! — and a deposit does not count towards the block's data-availability size. The data-size, +//! KV-update and state-growth limits are packing budgets for the transactions the builder chooses, +//! so they do not refuse a deposit either. A deposit still counts towards each, and towards the +//! block's encoded size, so the transactions after it find the room it used. The one limit that +//! holds a deposit is the block's gas limit, which is the header's. //! //! A Mega System Transaction, the protocol's own oracle update, which the sequencer must be able //! to include whatever the block holds, is refused by none of those limits either and counts as a @@ -48,11 +50,14 @@ //! # Which dimensions are enforced //! //! The three gas ledgers the block counts ([`BlockGasCounters`]) have no block limit beside the -//! block's gas limit, the header's: state gas prices the state a block adds, so the block's gas -//! limit bounds it, and the history bytes beside the history ledger are reported, not limited. The -//! write-record count, which is the block's KV count, is reported and has no limit: every record -//! weighs forty bytes of data size, so a block held to -//! [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) keeps at most 327,680 records. +//! block's gas limit, the header's, and the history bytes beside the history ledger are reported, +//! not limited. The write-record count, which is the block's KV count, is held to +//! [`BLOCK_KV_UPDATE_LIMIT`](crate::constants::BLOCK_KV_UPDATE_LIMIT); every record weighs forty +//! bytes of data size, so a block held to [`BLOCK_DATA_LIMIT`](crate::constants::BLOCK_DATA_LIMIT) +//! keeps at most 327,680 records, and at the spec's numbers the data size binds first. The state +//! growth is held to [`BLOCK_STATE_GROWTH_LIMIT`](crate::constants::BLOCK_STATE_GROWTH_LIMIT): +//! state gas prices the state a block adds, but the block's gas limit does not stand in for the +//! count. use alloy_primitives::TxHash; @@ -64,7 +69,9 @@ use alloy_evm::block::{BlockExecutionError, BlockValidationError}; use crate::{ constants::{ - BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, + BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, BLOCK_KV_UPDATE_LIMIT, + BLOCK_STATE_GROWTH_LIMIT, ORACLE_ACCESS_COMPUTE_GAS, TX_DATA_LIMIT, TX_KV_UPDATE_LIMIT, + TX_STATE_GROWTH_LIMIT, }, BlockGasCounters, EvmTxRuntimeLimits, LimitUsage, MegaBlockLimitExceededError, MegaGasUsage, MegaSpecId, MegaTxLimitExceededError, @@ -83,9 +90,9 @@ use crate::{ /// transaction that crosses one is stopped, or a frame reverted, and that is the result its /// receipt records. There is no tighter setting a builder could run a transaction under and still /// agree with a validator; a builder that wants to avoid such a transaction leaves it out. -/// - The block's data-size budget holds what a block's transactions keep together. A validator -/// refuses a block that packs a transaction after the block reached it; a builder may pack -/// tighter ([`BlockLimits`]), never looser. +/// - The block's data-size, KV-update and state-growth budgets hold what a block's transactions +/// keep together. A validator refuses a block that packs a transaction after the block reached +/// one of them; a builder may pack tighter ([`BlockLimits`]), never looser. /// /// A tool or a test that runs under other values says so explicitly /// ([`MegaContext::with_tx_runtime_limits`](crate::MegaContext::with_tx_runtime_limits), @@ -93,8 +100,10 @@ use crate::{ /// in block execution `MegaBlockExecutor::with_protocol_limits`, which exists for tests and tools /// only); what it computes is then a counterfactual, not the chain's result. /// -/// It serializes in the shape a tool takes an override in: camelCase, every field required, no -/// other field accepted. +/// It serializes in the shape a tool takes an override in: camelCase, no other field accepted, and +/// every field required but the KV-update and state-growth limits, of a transaction and of a +/// block, which the shape's first published version did not have: a file without them takes the +/// default spec's. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProtocolLimits { @@ -102,15 +111,39 @@ pub struct ProtocolLimits { /// data size, per transaction and per frame, and gas detention's two caps. pub tx_runtime_limits: EvmTxRuntimeLimits, /// The most data-size bytes a block's transactions may keep together. The transaction that - /// reaches it is packed; after it, only a deposit is. + /// reaches it is packed; after it, only a deposit or a Mega System Transaction is. pub block_txs_data_limit: u64, + /// The most write records a block's transactions may keep together: their KV count. The + /// transaction that reaches it is packed; after it, only a deposit or a Mega System + /// Transaction is. A file without it takes the default spec's. + #[serde(default = "default_block_kv_update_limit")] + pub block_kv_update_limit: u64, + /// The most new accounts and new slots a block's transactions may keep together: their state + /// growth. The transaction that reaches it is packed; after it, only a deposit or a Mega + /// System Transaction is. The block's gas limit does not stand in for it. A file without it + /// takes the default spec's. + #[serde(default = "default_block_state_growth_limit")] + pub block_state_growth_limit: u64, +} + +/// The default spec's block KV-update budget, for a limits file that does not name one. +fn default_block_kv_update_limit() -> u64 { + ProtocolLimits::for_spec(MegaSpecId::default()).block_kv_update_limit +} + +/// The default spec's block state-growth budget, for a limits file that does not name one. +fn default_block_state_growth_limit() -> u64 { + ProtocolLimits::for_spec(MegaSpecId::default()).block_state_growth_limit } impl ProtocolLimits { /// The limits a block of `spec`, and every transaction in it, is held to. /// /// [`MegaSpecId::SATIN`]: a transaction keeps at most [`TX_DATA_LIMIT`] (13,107,200) bytes of - /// data size, and a block's transactions together at most [`BLOCK_DATA_LIMIT`] (13,107,200); + /// data size, [`TX_KV_UPDATE_LIMIT`] (500,000) write records and [`TX_STATE_GROWTH_LIMIT`] + /// (1,000) new accounts and slots, and a block's transactions together at most + /// [`BLOCK_DATA_LIMIT`] (13,107,200), [`BLOCK_KV_UPDATE_LIMIT`] (500,000) and + /// [`BLOCK_STATE_GROWTH_LIMIT`] (1,000); /// every frame gets 98/100 of what its parent has left, the transaction's own frame what the /// transaction has left, with no further per-frame cap; a read of volatile data caps the /// transaction's compute at its compute at the read plus [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] or @@ -123,11 +156,15 @@ impl ProtocolLimits { MegaSpecId::SATIN => Self { tx_runtime_limits: EvmTxRuntimeLimits { tx_data_size_limit: TX_DATA_LIMIT, + tx_kv_update_limit: TX_KV_UPDATE_LIMIT, + tx_state_growth_limit: TX_STATE_GROWTH_LIMIT, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: BLOCK_ENV_ACCESS_COMPUTE_GAS, oracle_access_compute_gas_limit: ORACLE_ACCESS_COMPUTE_GAS, }, block_txs_data_limit: BLOCK_DATA_LIMIT, + block_kv_update_limit: BLOCK_KV_UPDATE_LIMIT, + block_state_growth_limit: BLOCK_STATE_GROWTH_LIMIT, }, } } @@ -138,7 +175,12 @@ impl ProtocolLimits { /// For runs that take every limit out — the execution-spec gate's equivalence mode and tests — /// never for executing the chain. pub const fn no_limits() -> Self { - Self { tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), block_txs_data_limit: u64::MAX } + Self { + tx_runtime_limits: EvmTxRuntimeLimits::no_limits(), + block_txs_data_limit: u64::MAX, + block_kv_update_limit: u64::MAX, + block_state_growth_limit: u64::MAX, + } } /// Sets the limits every transaction runs under. @@ -152,10 +194,22 @@ impl ProtocolLimits { self.block_txs_data_limit = limit; self } + + /// Sets the block's KV-update limit. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_limit = limit; + self + } + + /// Sets the block's state-growth limit. + pub const fn with_block_state_growth_limit(mut self, limit: u64) -> Self { + self.block_state_growth_limit = limit; + self + } } -/// The building policy one block is packed under: the limits only a builder applies, and the cap -/// it may put on the block's data-size budget below the protocol's. +/// The building policy one block is packed under: the limits only a builder applies, and the caps +/// it may put on the block's data-size, KV-update and state-growth budgets below the protocol's. /// /// A node passes it in the block execution context. None of it is a protocol value: the /// protocol's limits are [`ProtocolLimits`], which the block executor reads from the spec's @@ -169,8 +223,11 @@ impl ProtocolLimits { /// data-availability size limits are the builder's alone: the protocol holds a transaction's /// declared gas to the block's gas limit, and what a block writes to its data-size budget, which /// counts calldata. -/// - [`block_txs_data_limit`](Self::block_txs_data_limit) is the builder's cap on the protocol's -/// data-size budget: the block executor holds a block to the smaller of the two. +/// - [`block_txs_data_limit`](Self::block_txs_data_limit), +/// [`block_kv_update_limit`](Self::block_kv_update_limit) and +/// [`block_state_growth_limit`](Self::block_state_growth_limit) are the builder's caps on the +/// protocol's packing budgets: the block executor holds a block to the smaller of each pair. None +/// of them refuses a deposit or a Mega System Transaction. /// /// The block's gas limit is not here: it is the header's, which the block executor takes from the /// block environment ([`BlockLimiter::block_gas_limit`]). @@ -195,6 +252,14 @@ pub struct BlockLimits { /// A builder's cap: the block is held to the smaller of this and /// [`ProtocolLimits::block_txs_data_limit`]. pub block_txs_data_limit: u64, + /// The most write records the block's transactions may keep together, as + /// [`block_txs_data_limit`](Self::block_txs_data_limit) holds their bytes: a builder's cap on + /// [`ProtocolLimits::block_kv_update_limit`]. + pub block_kv_update_limit: u64, + /// The most new accounts and new slots the block's transactions may keep together, as + /// [`block_txs_data_limit`](Self::block_txs_data_limit) holds their bytes: a builder's cap on + /// [`ProtocolLimits::block_state_growth_limit`]. + pub block_state_growth_limit: u64, } impl Default for BlockLimits { @@ -215,18 +280,25 @@ impl BlockLimits { tx_da_size_limit: u64::MAX, block_da_size_limit: u64::MAX, block_txs_data_limit: u64::MAX, + block_kv_update_limit: u64::MAX, + block_state_growth_limit: u64::MAX, } } - /// These limits held within `protocol`: the block's data-size budget is the smaller of this - /// policy's cap and the protocol's limit, so a builder's setting can tighten the budget and - /// never loosen it. The limits only a builder applies are kept as they are. + /// These limits held within `protocol`: each of the block's packing budgets — data size, KV + /// updates, state growth — is the smaller of this policy's cap and the protocol's limit, so a + /// builder's setting can tighten a budget and never loosen it. The limits only a builder + /// applies are kept as they are. /// /// A cap above the protocol's limit gives way to it without a word; a node that wants to /// refuse or report such a setting compares the two itself. pub fn within(self, protocol: &ProtocolLimits) -> Self { Self { block_txs_data_limit: self.block_txs_data_limit.min(protocol.block_txs_data_limit), + block_kv_update_limit: self.block_kv_update_limit.min(protocol.block_kv_update_limit), + block_state_growth_limit: self + .block_state_growth_limit + .min(protocol.block_state_growth_limit), ..self } } @@ -266,6 +338,18 @@ impl BlockLimits { self.block_txs_data_limit = limit; self } + + /// Caps the block's KV count. + pub const fn with_block_kv_update_limit(mut self, limit: u64) -> Self { + self.block_kv_update_limit = limit; + self + } + + /// Caps the block's state growth. + pub const fn with_block_state_growth_limit(mut self, limit: u64) -> Self { + self.block_state_growth_limit = limit; + self + } } /// What one committed transaction adds to a block's counters. @@ -273,7 +357,7 @@ impl BlockLimits { pub struct BlockUsage { /// The gas by ledger, and the gas the receipt reports ([`MegaGasUsage::gas_used`]). pub gas: MegaGasUsage, - /// The data-size bytes and write records the transaction kept. + /// The data-size bytes, write records and state growth the transaction kept. pub usage: LimitUsage, /// The transaction's EIP-2718 encoded size, in bytes. pub tx_size: u64, @@ -303,7 +387,7 @@ pub struct BlockLimiter { pub block_gas_used: u64, /// The gas the block's transactions spent, by ledger. pub gas: BlockGasCounters, - /// The data-size bytes and write records the block's transactions kept. + /// The data-size bytes, write records and state growth the block's transactions kept. pub usage: LimitUsage, /// The encoded size of the block's transaction bodies, in bytes. pub block_tx_size_used: u64, @@ -433,6 +517,9 @@ impl BlockLimiter { )); } + // The three packing budgets, known only after a transaction ran: the transaction that + // reaches one is packed, and every later one is skipped before it runs. Where several are + // reached, the skip names the first of data size, KV updates and state growth. if self.usage.data_size >= self.limits.block_txs_data_limit { return Err(invalid_tx( tx_hash, @@ -442,9 +529,26 @@ impl BlockLimiter { }, )); } + if self.usage.write_records >= self.limits.block_kv_update_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::KvUpdateLimit { + block_used: self.usage.write_records, + limit: self.limits.block_kv_update_limit, + }, + )); + } + if self.usage.state_growth >= self.limits.block_state_growth_limit { + return Err(invalid_tx( + tx_hash, + MegaBlockLimitExceededError::StateGrowthLimit { + block_used: self.usage.state_growth, + limit: self.limits.block_state_growth_limit, + }, + )); + } - // `self.gas` and `self.usage.write_records` are accumulated and not checked: none of them - // has a block limit. + // `self.gas` is accumulated and not checked: no ledger has a block limit. Ok(()) } @@ -481,8 +585,8 @@ mod tests { use alloy_primitives::B256; /// Satin's limits, written out so a change to one is a visible diff: 13,107,200 bytes of data - /// size per transaction and per block, no per-frame cap beyond the 98/100 share, and - /// detention's caps at 20,000,000 each. + /// size, 500,000 write records and 1,000 new accounts and slots, per transaction and per block, + /// no per-frame cap beyond the 98/100 share, and detention's caps at 20,000,000 each. /// /// They also hold what a chain configuration's load-time check used to hold a chain's values /// to: no limit is zero, a transaction's data size holds at least a body, and both detention @@ -496,26 +600,36 @@ mod tests { ProtocolLimits { tx_runtime_limits: EvmTxRuntimeLimits { tx_data_size_limit: 13_107_200, + tx_kv_update_limit: 500_000, + tx_state_growth_limit: 1_000, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: 20_000_000, oracle_access_compute_gas_limit: 20_000_000, }, block_txs_data_limit: 13_107_200, + block_kv_update_limit: 500_000, + block_state_growth_limit: 1_000, } ); let EvmTxRuntimeLimits { tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, } = limits.tx_runtime_limits; for limit in [ tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, limits.block_txs_data_limit, + limits.block_kv_update_limit, + limits.block_state_growth_limit, ] { assert_ne!(limit, 0); } @@ -525,19 +639,23 @@ mod tests { } /// The limits serialize in the shape a tool takes an override in, written out here: camelCase, - /// the per-transaction limits nested. A field left out is an error rather than a zero, and so - /// is one the type does not have. + /// the per-transaction limits nested. A field the shape's first published version had is + /// required, so leaving it out is an error rather than a zero, and so is a field the type does + /// not have; a file in that version, without the KV-update and state-growth limits, is read + /// with the spec's values for them. #[test] fn test_protocol_limits_round_trip() { let satin = ProtocolLimits::for_spec(MegaSpecId::SATIN); let limits = satin .with_tx_runtime_limits(satin.tx_runtime_limits.with_frame_data_size_limit(1)) - .with_block_txs_data_limit(7); + .with_block_txs_data_limit(7) + .with_block_kv_update_limit(8) + .with_block_state_growth_limit(9); let json = serde_json::to_string(&limits).expect("serializes"); assert_eq!( json, - r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7}"# + r#"{"txRuntimeLimits":{"txDataSizeLimit":13107200,"txKvUpdateLimit":500000,"txStateGrowthLimit":1000,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":7,"blockKvUpdateLimit":8,"blockStateGrowthLimit":9}"# ); assert_eq!(serde_json::from_str::(&json).expect("deserializes"), limits); @@ -545,6 +663,25 @@ mod tests { assert!(serde_json::from_str::(&missing).is_err(), "{missing}"); let missing_tx = json.replace(r#""frameDataSizeLimit":1,"#, ""); assert!(serde_json::from_str::(&missing_tx).is_err(), "{missing_tx}"); + + // A file in the first published version of the shape. + let first = r#"{"txRuntimeLimits":{"txDataSizeLimit":350,"frameDataSizeLimit":1,"blockEnvAccessComputeGasLimit":5,"oracleAccessComputeGasLimit":6},"blockTxsDataLimit":7}"#; + let read = serde_json::from_str::(first).expect("a first-version file"); + let expected = satin + .with_tx_runtime_limits( + satin + .tx_runtime_limits + .with_tx_data_size_limit(350) + .with_frame_data_size_limit(1) + .with_block_env_access_compute_gas_limit(5) + .with_oracle_access_compute_gas_limit(6), + ) + .with_block_txs_data_limit(7); + assert_eq!(read, expected, "the newer limits at Satin's values"); + assert_eq!(read.block_kv_update_limit, 500_000); + assert_eq!(read.block_state_growth_limit, 1_000); + assert_eq!(read.tx_runtime_limits.tx_kv_update_limit, 500_000); + assert_eq!(read.tx_runtime_limits.tx_state_growth_limit, 1_000); let unknown = json.replace(r#""blockTxsDataLimit":7"#, r#""blockTxsDataLimit":7,"x":1"#); assert!(serde_json::from_str::(&unknown).is_err(), "{unknown}"); } @@ -553,10 +690,16 @@ mod tests { /// so a limit added later cannot be left out of it. #[test] fn test_no_protocol_limits_leaves_every_limit_unlimited() { - let ProtocolLimits { tx_runtime_limits, block_txs_data_limit } = - ProtocolLimits::no_limits(); + let ProtocolLimits { + tx_runtime_limits, + block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, + } = ProtocolLimits::no_limits(); assert_eq!(tx_runtime_limits, EvmTxRuntimeLimits::no_limits()); - assert_eq!(block_txs_data_limit, u64::MAX); + for limit in [block_txs_data_limit, block_kv_update_limit, block_state_growth_limit] { + assert_eq!(limit, u64::MAX); + } } /// The default building policy restricts nothing, so a validator that leaves it holds a block @@ -572,6 +715,8 @@ mod tests { tx_da_size_limit, block_da_size_limit, block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, } = BlockLimits::default(); for limit in [ tx_gas_limit, @@ -580,6 +725,8 @@ mod tests { tx_da_size_limit, block_da_size_limit, block_txs_data_limit, + block_kv_update_limit, + block_state_growth_limit, ] { assert_eq!(limit, u64::MAX); } @@ -590,17 +737,28 @@ mod tests { crate::constants::BLOCK_DATA_LIMIT, "held within the protocol's, the default policy is the protocol's" ); + let held = BlockLimits::default().within(&ProtocolLimits::for_spec(MegaSpecId::SATIN)); + assert_eq!( + (held.block_kv_update_limit, held.block_state_growth_limit), + (crate::constants::BLOCK_KV_UPDATE_LIMIT, crate::constants::BLOCK_STATE_GROWTH_LIMIT), + "and the protocol's KV and state-growth budgets" + ); } - /// A builder's cap on the block's data-size budget holds the block only where it is below the - /// protocol's limit: it tightens, and never loosens. The limits only a builder applies pass - /// through. + /// A builder's cap on each of the block's packing budgets — data size, KV updates, state growth + /// — holds the block only where it is below the protocol's limit: it tightens, and never + /// loosens. The limits only a builder applies pass through. #[test] fn test_a_building_policy_tightens_a_budget_and_never_loosens_it() { - let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_txs_data_limit(300); + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .with_block_txs_data_limit(300) + .with_block_kv_update_limit(301) + .with_block_state_growth_limit(302); let tighter = BlockLimits::no_limits() .with_block_txs_data_limit(30) + .with_block_kv_update_limit(31) + .with_block_state_growth_limit(32) .with_tx_gas_limit(1) .with_tx_encode_size_limit(2) .with_block_txs_encode_size_limit(3) @@ -608,9 +766,14 @@ mod tests { .with_block_da_size_limit(5); assert_eq!(tighter.within(&protocol), tighter, "every cap is below the protocol's"); - let looser = BlockLimits::no_limits().with_block_txs_data_limit(3_000); + let looser = BlockLimits::no_limits() + .with_block_txs_data_limit(3_000) + .with_block_kv_update_limit(3_001) + .with_block_state_growth_limit(3_002); let held = looser.within(&protocol); assert_eq!(held.block_txs_data_limit, 300, "a cap above the protocol's gives way to it"); + assert_eq!(held.block_kv_update_limit, 301, "for the KV count too"); + assert_eq!(held.block_state_growth_limit, 302, "and for the state growth"); assert_eq!( BlockLimits { tx_gas_limit: 7, ..held }, BlockLimits { tx_gas_limit: 7, ..BlockLimits::no_limits().within(&protocol) }, @@ -633,7 +796,7 @@ mod tests { history_bytes: u64::MAX, ..Default::default() }, - usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX }, + usage: LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: 0 }, tx_size: u64::MAX, da_size: u64::MAX, da_footprint: u64::MAX, @@ -683,7 +846,8 @@ mod tests { history: u64::MAX - 1, history_bytes: u64::MAX - 1, }; - limiter.usage = LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1 }; + limiter.usage = + LimitUsage { data_size: u64::MAX - 1, write_records: u64::MAX - 1, state_growth: 0 }; limiter.block_tx_size_used = u64::MAX - 1; limiter.block_da_size_used = u64::MAX - 1; limiter.block_da_footprint_used = u64::MAX - 1; @@ -700,7 +864,10 @@ mod tests { history_bytes: u64::MAX, } ); - assert_eq!(limiter.usage, LimitUsage { data_size: u64::MAX, write_records: u64::MAX }); + assert_eq!( + limiter.usage, + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: 0 } + ); assert_eq!(limiter.block_tx_size_used, u64::MAX); assert_eq!(limiter.block_da_size_used, u64::MAX); assert_eq!(limiter.block_da_footprint_used, u64::MAX); @@ -733,7 +900,7 @@ mod tests { let mut limiter = BlockLimiter::new(BlockLimits::no_limits().with_block_txs_data_limit(1_000), u64::MAX); let deposit = BlockUsage { - usage: LimitUsage { data_size: 600, write_records: 0 }, + usage: LimitUsage { data_size: 600, write_records: 0, state_growth: 0 }, is_deposit: true, ..Default::default() }; @@ -934,7 +1101,7 @@ mod tests { history_bytes: 250, ..Default::default() }, - usage: LimitUsage { data_size: 0, write_records: 30 }, + usage: LimitUsage { data_size: 0, write_records: 30, state_growth: 0 }, ..Default::default() }; diff --git a/crates/mega-evm/src/block/result.rs b/crates/mega-evm/src/block/result.rs index 83243b51c..786b84620 100644 --- a/crates/mega-evm/src/block/result.rs +++ b/crates/mega-evm/src/block/result.rs @@ -145,6 +145,20 @@ pub enum MegaBlockLimitExceededError { /// The block's data-size limit. limit: u64, }, + /// The block's transactions have kept their write records: their KV count. + KvUpdateLimit { + /// The write records the block has kept. + block_used: u64, + /// The block's KV-update limit. + limit: u64, + }, + /// The block's transactions have kept their state growth: new accounts and new slots. + StateGrowthLimit { + /// The new accounts and new slots the block has kept. + block_used: u64, + /// The block's state-growth limit. + limit: u64, + }, /// The transaction's body does not fit in what the block has left. TransactionEncodeSizeLimit { /// The bytes the block's transaction bodies already take. @@ -170,6 +184,8 @@ impl MegaBlockLimitExceededError { pub const fn block_used(&self) -> u64 { match self { Self::TransactionDataLimit { block_used, .. } | + Self::KvUpdateLimit { block_used, .. } | + Self::StateGrowthLimit { block_used, .. } | Self::TransactionEncodeSizeLimit { block_used, .. } | Self::DataAvailabilitySizeLimit { block_used, .. } => *block_used, } @@ -179,6 +195,8 @@ impl MegaBlockLimitExceededError { pub const fn limit(&self) -> u64 { match self { Self::TransactionDataLimit { limit, .. } | + Self::KvUpdateLimit { limit, .. } | + Self::StateGrowthLimit { limit, .. } | Self::TransactionEncodeSizeLimit { limit, .. } | Self::DataAvailabilitySizeLimit { limit, .. } => *limit, } @@ -191,6 +209,12 @@ impl fmt::Display for MegaBlockLimitExceededError { Self::TransactionDataLimit { block_used, limit } => { write!(f, "Block transactions data limit reached: block_used={block_used} >= limit={limit}") } + Self::KvUpdateLimit { block_used, limit } => { + write!(f, "Block KV update limit reached: block_used={block_used} >= limit={limit}") + } + Self::StateGrowthLimit { block_used, limit } => { + write!(f, "Block state growth limit reached: block_used={block_used} >= limit={limit}") + } Self::TransactionEncodeSizeLimit { block_used, tx_used, limit } => write!( f, "Block transactions encode size limit exceeded: block_used={block_used} + tx_used={tx_used} > limit={limit}" @@ -404,6 +428,8 @@ mod tests { fn test_block_limit_error_reports_block_usage_and_limit() { let cases = [ (MegaBlockLimitExceededError::TransactionDataLimit { block_used: 1, limit: 10 }, 1, 10), + (MegaBlockLimitExceededError::KvUpdateLimit { block_used: 2, limit: 11 }, 2, 11), + (MegaBlockLimitExceededError::StateGrowthLimit { block_used: 3, limit: 12 }, 3, 12), ( MegaBlockLimitExceededError::TransactionEncodeSizeLimit { block_used: 4, diff --git a/crates/mega-evm/src/constants.rs b/crates/mega-evm/src/constants.rs index d11367e6f..50be6afb5 100644 --- a/crates/mega-evm/src/constants.rs +++ b/crates/mega-evm/src/constants.rs @@ -15,18 +15,23 @@ //! | [`MAX_INITCODE_SIZE`] | 1,048,576 | the most bytes an initcode may hold | the spec configuration | //! | [`TX_DATA_LIMIT`] | 13,107,200 | data size one transaction may produce (as Rex6) | Satin's protocol limits | //! | [`BLOCK_DATA_LIMIT`] | 13,107,200 | data size one block may produce (as Rex6) | Satin's protocol limits | +//! | [`TX_KV_UPDATE_LIMIT`] | 500,000 | write records one transaction may keep (as Rex6's KV updates) | Satin's protocol limits | +//! | [`BLOCK_KV_UPDATE_LIMIT`] | 500,000 | write records one block's transactions may keep (as Rex6) | Satin's protocol limits | +//! | [`TX_STATE_GROWTH_LIMIT`] | 1,000 | new accounts and slots one transaction may keep (as Rex6) | Satin's protocol limits | +//! | [`BLOCK_STATE_GROWTH_LIMIT`] | 1,000 | new accounts and slots one block's transactions may keep (as Rex6) | Satin's protocol limits | //! | [`BLOCK_ENV_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the block environment or the beneficiary (as Rex6) | Satin's protocol limits | //! | [`ORACLE_ACCESS_COMPUTE_GAS`] | 20,000,000 | compute a transaction may still spend once it read the Oracle's storage (as Rex6) | Satin's protocol limits | //! | [`MAX_TX_COMPUTE_GAS`] | 199,987,900 | the most compute one transaction can spend: the execution cap less EIP-2780's base cost and one warm account access | tests of the protocol limits, whose detention caps are below it | +//! | [`PRE_BLOCK_CALL_GAS_LIMIT`] | 31,566,720 | gas limit of every pre-block system call: 30,000,000 of regular gas and a reservoir of sixteen fresh slots | the block's pre-block calls | //! //! The Satin gas schedule builds its state-gas entries from the EIP-8037 byte counts at //! [`COST_PER_STATE_BYTE`], read through [`SatinPrices`](crate::SatinPrices) so a measurement //! build can run other byte prices without touching this table. [`SLOT_STATE_GAS`] and //! [`ACCOUNT_STATE_GAS`] are two of those products written out: the tests assert the schedule //! against them, and changing one of the two moves a test rather than a price. -//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`] and the two detention caps are Satin's protocol limits -//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)). No limit holds state growth: -//! state gas prices it. +//! [`TX_DATA_LIMIT`], [`BLOCK_DATA_LIMIT`], the KV-update and state-growth limits and the two +//! detention caps are Satin's protocol limits +//! ([`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec)). use revm::{ context_interface::cfg::gas::WARM_STORAGE_READ_COST, @@ -72,6 +77,21 @@ pub const TX_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; /// The most data one block may produce, 12.5 MiB as in Rex6. Provisional. pub const BLOCK_DATA_LIMIT: u64 = 12 * 1024 * 1024 + 512 * 1024; +/// The most write records one transaction may keep: its KV count, as Rex6's KV-update limit. +/// Provisional. +pub const TX_KV_UPDATE_LIMIT: u64 = 500_000; + +/// The most write records one block's transactions may keep together, as Rex6's. Provisional. +pub const BLOCK_KV_UPDATE_LIMIT: u64 = 500_000; + +/// The most new accounts and new storage slots one transaction may keep, net, as Rex6's +/// state-growth limit. Provisional. +pub const TX_STATE_GROWTH_LIMIT: u64 = 1_000; + +/// The most new accounts and new storage slots one block's transactions may keep together, as +/// Rex6's. Provisional. +pub const BLOCK_STATE_GROWTH_LIMIT: u64 = 1_000; + /// The compute a transaction may still spend once it read the block environment or the block /// beneficiary's account: its compute at the read plus this. The value and its relative reading /// are Rex6's. Provisional. @@ -94,6 +114,24 @@ pub const ORACLE_ACCESS_COMPUTE_GAS: u64 = 20_000_000; pub const MAX_TX_COMPUTE_GAS: u64 = TX_GAS_LIMIT_CAP - eip2780::TX_BASE_COST - WARM_STORAGE_READ_COST; +/// The gas limit every pre-block system call runs on — the EIP-2935 and EIP-4788 calls and the +/// `SequencerRegistry`'s `applyPendingChanges()` — whatever the block's gas limit. Provisional. +/// +/// It is the 30,000,000 of regular gas a system call runs on at most +/// ([`SYSTEM_CALL_REGULAR_GAS_LIMIT`](crate::SYSTEM_CALL_REGULAR_GAS_LIMIT)), and a state-gas +/// reservoir of sixteen fresh storage slots at the minimum SALT bucket, which every system call +/// prices at: `30,000,000 + 16 × SLOT_STATE_GAS = 30,000,000 + 16 × 97,920 = 31,566,720`. +/// +/// Where the EIP-2935 and EIP-4788 addresses hold those EIPs' own code, the most fresh slots one +/// pre-block call writes is six: an `applyPendingChanges()` that applies both roles, writing for +/// each its current address, its history's length and the history's new entry, where all three +/// were empty. The EIP-4788 call writes two, and the EIP-2935 call one. So the reservoir holds what +/// any of them writes more than twice over, and at the byte prices of this table no pre-block +/// call's state gas spills onto its regular gas; at a dearer state byte, or under other code at +/// those addresses, what the reservoir does not hold spills onto the 30,000,000. +pub const PRE_BLOCK_CALL_GAS_LIMIT: u64 = + crate::SYSTEM_CALL_REGULAR_GAS_LIMIT + 16 * SLOT_STATE_GAS; + #[cfg(test)] mod tests { use super::*; @@ -111,5 +149,6 @@ mod tests { // The data-size limits and the detention caps are written out with the protocol limits // that read them, in `ProtocolLimits::for_spec`'s own test. assert_eq!(MAX_TX_COMPUTE_GAS, 199_987_900); + assert_eq!(PRE_BLOCK_CALL_GAS_LIMIT, 31_566_720); } } diff --git a/crates/mega-evm/src/evm/context.rs b/crates/mega-evm/src/evm/context.rs index 03d3fe786..7dd04b1b6 100644 --- a/crates/mega-evm/src/evm/context.rs +++ b/crates/mega-evm/src/evm/context.rs @@ -1,39 +1,36 @@ //! The execution context of the Satin engine. -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - use delegate::delegate; use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpSpecId}; use revm::{ context::{ - BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, LocalContext, - Transaction, + BlockEnv, Cfg, CfgEnv, Context, ContextError, ContextSetters, ContextTr, Journal, + LocalContext, Transaction, + }, + context_interface::{ + cfg::{gas::GasTracker, GasId}, + context::CodeDeposit, }, - context_interface::{cfg::GasId, context::CodeDeposit}, primitives::{Address, Bytes, StorageKey}, - Database, Journal, + Database, }; use crate::{ constants, evm::{ history::transaction_body_bytes, - inspector::UpfrontRecord, schedule::{satin_gas_params, satin_gas_params_history_exempt}, }, - system::{ - self, - keyless::{self, KeylessFrame}, - }, + limit::{Accounts, Counted}, + system::{self, keyless}, AdditionalLimit, BlockHashRecord, BucketError, BucketId, BucketMultipliers, BucketRecord, Detention, EmptyExternalEnv, EthSpecId, EvmTxRuntimeLimits, ExternalEnvTypes, ExternalEnvs, - MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, VolatileDataAccess, + LimitUsage, MegaSpecId, MegaTransaction, OracleReadRecord, ProtocolLimits, SaltEnv, + VolatileDataAccess, }; /// The revm context the Satin engine runs on: op-revm's context shape with the `MegaETH` -/// transaction type. +/// transaction type, on revm's own journal. pub(crate) type MegaInnerContext = Context, DB, Journal, L1BlockInfo>; @@ -46,8 +43,9 @@ pub(crate) type MegaInnerContext = /// configuration), so they cannot drift apart. /// /// Every context accessor delegates to the wrapped context, and so does every -/// [`Host`](revm::interpreter::Host) method except the three that stage what a state-writing -/// opcode did and the ones that load volatile data (see the `host` module). It also carries the +/// [`Host`](revm::interpreter::Host) method except the two instruction hooks, which meter a +/// completed write and a frame start, and the ones that load volatile data (see the `host` +/// module). It also carries the /// common execution layer's state for the running transaction ([`AdditionalLimit`]), gas /// detention's ([`Detention`]), the SALT bucket multipliers that transaction has priced state /// gas with ([`BucketMultipliers`]) and the reads of the Oracle's storage it made through the @@ -60,9 +58,6 @@ pub struct MegaContext>, pub(crate) block_hash_record: BlockHashRecord, /// The SALT bucket multipliers the running transaction has read. bucket_multipliers: BucketMultipliers, @@ -79,9 +74,9 @@ pub struct MegaContext, + /// The creation the running transaction's `keylessDeploy` call started, while it runs. See + /// the [`keyless`](crate::system::keyless) module. + pub(crate) keyless_creation: Option, /// Whether the context runs the neutral configuration. See [`MegaContext::with_neutral_cfg`]. #[cfg(any(test, feature = "test-utils"))] neutral: bool, @@ -106,16 +101,15 @@ impl MegaContext { external_envs: ExternalEnvs, ) -> Self { let cfg = spec_cfg(CfgEnv::new_with_spec(spec)); - let inner = Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); + let limits = ProtocolLimits::for_spec(spec).tx_runtime_limits; + let inner: MegaInnerContext = + Context::new(db, spec.into_op_spec()).with_cfg(op_cfg(&cfg)); Self { inner, cfg, external_envs, - additional_limit: AdditionalLimit::new( - ProtocolLimits::for_spec(spec).tx_runtime_limits, - ), + additional_limit: AdditionalLimit::new(limits), detention: Detention::default(), - upfront_records: Vec::new(), block_hash_record: BlockHashRecord::default(), bucket_multipliers: BucketMultipliers::default(), bucket_record: BucketRecord::default(), @@ -123,7 +117,7 @@ impl MegaContext { system_originated: false, system_call: false, prices_history: true, - keyless_frame: None, + keyless_creation: None, #[cfg(any(test, feature = "test-utils"))] neutral: false, } @@ -133,9 +127,9 @@ impl MegaContext { /// /// The fields the spec fixes are set from the spec, whatever `cfg` holds: the gas schedule, /// the EIP-8037 and EIP-2780 switches, the execution cap, the EIP-7708 switch and its - /// disabling flag, the system-call state-gas margin, the chain-id check and the two code-size - /// limits. Every other field (chain id, the other disabled checks, blob schedule) is taken - /// from `cfg`. + /// disabling flag, the chain-id check, the two code-size limits and the fork's switch back to + /// revm 40.0.3's journal semantics. Every other field (chain id, the other disabled checks, + /// blob schedule) is taken from `cfg`. /// /// A context that ran the neutral configuration returns to the spec's. pub fn with_cfg(mut self, cfg: CfgEnv) -> Self { @@ -159,9 +153,13 @@ impl MegaContext { /// /// - Every field is taken from `cfg`, including the ones [`with_cfg`](Self::with_cfg) sets from /// the spec: the gas schedule, the EIP-8037, EIP-2780 and EIP-7708 switches, the execution - /// cap and the code-size limits. + /// cap and the code-size limits. The one exception is the fork's switch back to revm 40.0.3's + /// journal semantics, which stays off: the journal's semantics are part of the machinery + /// under test, not of what is priced. /// - No transaction pays history gas, and none has its schedule swapped for its history /// exemption: every transaction runs `cfg`'s schedule. + /// - A system call's gas is not split: its whole gas limit is regular gas, as revm's own runner + /// has it. /// - SALT pricing needs nothing here: without a SALT environment every bucket is minimal, and /// the multiplier is one. /// - Gas detention is not part of the configuration: its caps are runtime limits, which the @@ -172,7 +170,9 @@ impl MegaContext { /// journal execute. The precompile set is the EVM's, not the context's: a caller that wants /// the fixture fork's replaces it on the [`MegaEvm`](crate::MegaEvm). #[cfg(any(test, feature = "test-utils"))] - pub fn with_neutral_cfg(mut self, cfg: CfgEnv) -> Self { + pub fn with_neutral_cfg(mut self, mut cfg: CfgEnv) -> Self { + // The journal's semantics are part of the machinery, not of what is priced. + cfg.legacy_journal_semantics = false; self.inner = self.inner.with_cfg(op_cfg(&cfg)); self.cfg = cfg; self.neutral = true; @@ -241,10 +241,16 @@ impl MegaContext { /// Enforces `limits` on every transaction from now on, in place of the spec's: a tool's or a /// test's counterfactual. pub fn with_tx_runtime_limits(mut self, limits: EvmTxRuntimeLimits) -> Self { - self.additional_limit.set_limits(limits); + self.set_tx_runtime_limits(limits); self } + /// Holds every transaction from the next one on to `limits`: the data-size limit and gas + /// detention alike. + pub(crate) const fn set_tx_runtime_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.additional_limit.set_limits(limits); + } + /// The block hashes execution has read on this context. /// /// The record belongs to one block: block execution empties it when the block starts, so it @@ -288,6 +294,20 @@ impl MegaContext { &self.additional_limit } + /// What the running (or last) transaction keeps so far: its data-size bytes and write records, + /// with every running frame counted as if it succeeds. It is what the transaction's outcome + /// reports ([`MegaTransactionOutcome::usage`](crate::MegaTransactionOutcome::usage)) once it + /// ran, and what the data-size limit holds it to; the next transaction or system call resets + /// it. + pub fn limit_usage(&self) -> LimitUsage { + self.additional_limit.usage() + } + + /// The accounts the running transaction holds, read for the write records a write makes. + pub(crate) fn accounts(&self) -> Accounts<'_> { + Accounts::of(self.journal_ref(), self.additional_limit.counts_transfer_logs()) + } + /// Gas detention for the running (or last) transaction: the volatile data it read and the /// compute limit that set. See the `access` module. pub const fn detention(&self) -> &Detention { @@ -424,8 +444,36 @@ impl MegaContext { self.system_call } + /// Whether the running execution's gas is split as EIP-8037 splits a system call's: at most + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`](crate::SYSTEM_CALL_REGULAR_GAS_LIMIT) of it regular gas, + /// the rest its state-gas reservoir. Every system call's is, whatever the caller's + /// configuration: which pool pays the protocol's own state writes, and what `GAS` reads inside + /// a system contract, are part of executing the chain. No transaction's is, and under the + /// neutral configuration no system call's either, as revm's own runner has it. + pub(crate) fn splits_system_call_gas(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + return false; + } + self.system_call + } + + /// Whether the destruction table prices state gas: a destruction of an account created in the + /// transaction gives back the state gas of the parts the transaction made, and from that mark + /// the account keeps no further state gas. So under the spec's configuration, which charges + /// EIP-8037 state gas. The neutral configuration prices as the fixture's fork does, and + /// EIP-8037 gives back no state gas for this destruction; the table's counts are the same + /// under both. + pub(crate) fn destruction_table_prices_state_gas(&self) -> bool { + #[cfg(any(test, feature = "test-utils"))] + if self.neutral { + return false; + } + self.inner.cfg.is_amsterdam_eip8037_enabled() + } + /// Prepares the common execution layer for a transaction or a system call that is, or is not, - /// `system_originated`. + /// `system_originated`: the layer begins it, counting its body. /// /// The SALT bucket multipliers and the oracle reads go with it: they are what one transaction /// read, so the next one reads its own. @@ -436,22 +484,19 @@ impl MegaContext { /// it uses is counted all the same. A user's deposit is not system-originated and is held /// to every one of them. fn prepare(&mut self, system_originated: bool) { - self.additional_limit.reset(); - self.additional_limit.set_transfer_logs(emits_transfer_logs(&self.inner.cfg)); + let transfer_logs = emits_transfer_logs(&self.inner.cfg); self.bucket_multipliers.reset(); self.oracle_reads.clear(); - // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call - // unanswered. - self.keyless_frame = None; + // A transaction that failed with an error, or was stopped, left its `keylessDeploy` call's + // creation unsettled. + self.keyless_creation = None; self.system_originated = system_originated; let exempt = self.inner.tx.tx_type() == DEPOSIT_TRANSACTION_TYPE || system_originated; self.set_history_exempt(exempt); - if system_originated { - self.additional_limit.exempt(); - } // The body is data size whether or not the transaction pays history for it. A deposit, // a system transaction and a system call are exempt from the charge, not from the count. - self.additional_limit.record_tx_body(transaction_body_bytes(self.tx())); + let body = transaction_body_bytes(self.tx()); + self.additional_limit.begin_transaction(system_originated, transfer_logs, body); // The protocol's own transactions are not detained: they maintain the volatile data. let limits = self.additional_limit.limits(); self.detention.reset( @@ -550,13 +595,11 @@ impl MegaContext { /// transfer log is data size like any log, and pays no history gas: Ethereum prices it at /// nothing, and it is not a byte the transaction chose to write (see the `limit` module). /// -/// A system call runs as EIP-8037 has it: on at most the base 30,000,000 of regular gas, the -/// rest of its gas limit being its state-gas reservoir, which the state it writes draws first. -/// The switch for it is set on whatever the caller's configuration says, because which pool pays -/// the protocol's own state writes, and what `GAS` reads inside a system contract, are part of -/// executing the chain. It reaches system calls only: every transaction's gas is split by the -/// execution cap as before, the system-address transaction's included, which is a deposit and -/// not a system call. +/// The journal runs with the fork's journal semantics, not revm 40.0.3's: a storage slot warmed +/// while cold inside the current transaction keeps its EIP-2200 baseline, and a reverted code +/// change restores the code the account had. The fork's switch back to revm 40.0.3's semantics +/// exists for the engine that reproduces that version; it is set off here whatever the caller's +/// configuration says, since the journal's own copy of it is written from this configuration. /// /// The chain-id check is on, whatever the caller's configuration says: a transaction that carries /// a chain id must carry the chain's, and one of a type other than legacy must carry one. Which @@ -568,10 +611,10 @@ pub fn spec_cfg(mut cfg: CfgEnv) -> CfgEnv { cfg.tx_gas_limit_cap = Some(constants::TX_GAS_LIMIT_CAP); cfg.enable_amsterdam_eip7708 = true; cfg.amsterdam_eip7708_disabled = false; - cfg.system_call_state_gas_margin_in_reservoir = true; cfg.tx_chain_id_check = true; cfg.limit_contract_code_size = Some(constants::MAX_CONTRACT_SIZE); cfg.limit_contract_initcode_size = Some(constants::MAX_INITCODE_SIZE); + cfg.legacy_journal_semantics = false; cfg } @@ -626,24 +669,39 @@ impl ContextTr for MegaContext) -> Result<(), Bytes> { - let destroyed = self - .journal_ref() - .state - .get(&deposit.address) - .is_some_and(|account| account.is_selfdestructed()); - if keyless::refuses_empty_deposit(&mut self.keyless_frame, deposit, destroyed) { + fn admit_code_deposit( + &mut self, + deposit: &CodeDeposit<'_>, + gas: &mut GasTracker, + ) -> Result<(), Bytes> { + // Destroyed in this transaction: the flag revm keeps for the whole journal may stand from + // an earlier transaction on it. + let destroyed = self.accounts().is_destroyed(deposit.address); + if keyless::refuses_empty_deposit(&mut self.keyless_creation, deposit, destroyed) { return Err(Bytes::new()); } - self.additional_limit.on_code_deposit(deposit) + let check = self.additional_limit.draw(gas, &Counted::bytes(deposit.code.len() as u64)); + if check.exceeded_limit() { + return Err(self.additional_limit.note_frame_stop(&check)); + } + Ok(()) } } @@ -675,12 +733,21 @@ mod tests { assert_eq!(cfg.cap, Some(constants::TX_GAS_LIMIT_CAP), "execution cap"); assert!(cfg.eip7708, "EIP-7708 must be on"); assert!(!cfg.eip7708_disabled, "EIP-7708 must not be disabled"); - assert!(cfg.margin, "a system call's gas above 30M must be its reservoir"); assert!(cfg.chain_id_check, "the chain id must be checked"); assert_eq!(cfg.code_size, Some(constants::MAX_CONTRACT_SIZE), "contract size"); assert_eq!(cfg.initcode_size, Some(constants::MAX_INITCODE_SIZE), "initcode size"); assert_eq!(cfg.gas_params.table(), satin_gas_params().table(), "gas schedule"); + assert!(!cfg.legacy, "revm 40.0.3's journal semantics must stay off"); } + assert_journal_runs_the_spec_switches(ctx); + } + + /// The journal's own copies of the switches it reads, as the context's cfg sync delivered + /// them: the fork's journal semantics, and EIP-7708 transfer logs on. + fn assert_journal_runs_the_spec_switches(ctx: &MegaContext) { + let journal = &ctx.journal_ref().inner; + assert!(!journal.legacy_journal_semantics(), "the journal keeps the fork's semantics"); + assert!(journal.amsterdam_eip7708_enabled(), "the journal emits transfer logs"); } /// The configuration fields the spec fixes, read out of either view. @@ -690,11 +757,11 @@ mod tests { cap: Option, eip7708: bool, eip7708_disabled: bool, - margin: bool, chain_id_check: bool, code_size: Option, initcode_size: Option, gas_params: &'a GasParams, + legacy: bool, } impl<'a> Fixed<'a> { @@ -705,11 +772,11 @@ mod tests { cap: cfg.tx_gas_limit_cap, eip7708: cfg.enable_amsterdam_eip7708, eip7708_disabled: cfg.amsterdam_eip7708_disabled, - margin: cfg.system_call_state_gas_margin_in_reservoir, chain_id_check: cfg.tx_chain_id_check, code_size: cfg.limit_contract_code_size, initcode_size: cfg.limit_contract_initcode_size, gas_params: &cfg.gas_params, + legacy: cfg.legacy_journal_semantics, } } } @@ -756,11 +823,11 @@ mod tests { cfg.tx_gas_limit_cap = Some(1 << 24); cfg.enable_amsterdam_eip7708 = false; cfg.amsterdam_eip7708_disabled = true; - cfg.system_call_state_gas_margin_in_reservoir = false; cfg.tx_chain_id_check = false; cfg.limit_contract_code_size = Some(24 * 1024); cfg.limit_contract_initcode_size = Some(48 * 1024); cfg.gas_params = GasParams::new_spec(EthSpecId::AMSTERDAM); + cfg.legacy_journal_semantics = true; }); assert_satin_cfg(&ctx); @@ -768,6 +835,32 @@ mod tests { assert_eq!(ctx.cfg().chain_id, 4326); } + /// The switch back to revm 40.0.3's journal semantics is the legacy engine's. A configuration + /// carrying every switch at the legacy engine's values — it exports that one on — changes + /// nothing the journal reads: the fork's semantics and transfer logs stay as the spec fixes + /// them, in `cfg` and in the journal's copies, under the spec's configuration and the neutral + /// one. + #[test] + fn test_a_legacy_engine_cfg_does_not_change_the_journal_switches() { + let ctx = context_with(|cfg| { + cfg.enable_amsterdam_eip8037 = false; + cfg.enable_amsterdam_eip2780 = false; + cfg.enable_amsterdam_eip7708 = false; + cfg.legacy_journal_semantics = true; + }); + assert_satin_cfg(&ctx); + + let neutral = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg({ + let mut cfg = osaka_cfg(); + cfg.legacy_journal_semantics = true; + cfg + }); + assert!(neutral.is_neutral()); + assert!(!neutral.mega_cfg().legacy_journal_semantics); + assert!(!neutral.cfg().legacy_journal_semantics); + assert!(!neutral.journal_ref().inner.legacy_journal_semantics()); + } + /// The op-revm view is the `MegaETH` view keyed by the base spec, field for field. #[test] fn test_with_cfg_spec_consistency() { @@ -903,6 +996,25 @@ mod tests { assert!(!ctx.is_system_call(), "nor is a system transaction, which the protocol sends"); } + /// A system call's gas is split as EIP-8037 has it; a transaction's is not, a system-address + /// transaction's neither, and under the neutral configuration no system call's is. + #[test] + fn test_only_a_system_call_splits_its_gas() { + let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN); + assert!(!ctx.splits_system_call_gas()); + ctx.on_new_system_call(); + assert!(ctx.splits_system_call_gas()); + ctx.on_new_tx(false); + assert!(!ctx.splits_system_call_gas(), "a transaction is split by the execution cap"); + ctx.on_new_tx(true); + assert!(!ctx.splits_system_call_gas(), "so is a system-address transaction"); + + let mut neutral = + MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(osaka_cfg()); + neutral.on_new_system_call(); + assert!(!neutral.splits_system_call_gas(), "as revm's own runner has it"); + } + /// Two contexts may read one SALT environment — a node builds an EVM per transaction over /// the block's environments — and each keeps the multipliers it read to itself. #[test] @@ -1046,24 +1158,12 @@ mod tests { /// transaction reads the configuration afresh, and Satin's emits them. #[test] fn test_a_transaction_counts_transfer_logs_where_revm_emits_them() { - let endowed_creation = - revm::interpreter::FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( - Address::repeat_byte(0x11), - revm::interpreter::CreateScheme::Create, - U256::from(1), - revm::primitives::Bytes::new(), - 0, - 0, - ))); let counts = |cfg: CfgEnv| { let mut ctx = MegaContext::new(EmptyDB::default(), MegaSpecId::SATIN).with_neutral_cfg(cfg); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert_eq!( - ctx.additional_limit.frame_start_transfer_log(&endowed_creation), - emits_transfer_logs(ctx.cfg()), - ); + assert_eq!(ctx.additional_limit.counts_transfer_logs(), emits_transfer_logs(ctx.cfg())); emits_transfer_logs(ctx.cfg()) }; let with = |enabled: bool, disabled: bool| { @@ -1084,7 +1184,7 @@ mod tests { }); ctx.set_tx(call_from(Address::repeat_byte(0x11))); ctx.on_new_tx(false); - assert!(ctx.additional_limit.frame_start_transfer_log(&endowed_creation)); + assert!(ctx.additional_limit.counts_transfer_logs()); } /// A context is not neutral unless it is asked to be. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 0db00ef6f..329a8da8b 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -1,8 +1,11 @@ //! The Satin handler and the frame lifecycle of [`MegaEvm`]. //! //! [`MegaHandler`] runs a transaction through op-revm's [`OpHandler`] and overrides the phases -//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] and [`InspectorEvmTr`] itself, so the -//! frame lifecycle (`frame_init`, `frame_run`, `frame_return_result`) is `MegaETH`'s own. +//! `MegaETH` extends. [`MegaEvm`] implements revm's [`EvmTr`] itself, so a frame's start and its +//! return to its caller (`frame_init`, `frame_return_result`) are `MegaETH`'s own; its frame run is +//! revm's, but for an action set on a frame before it runs, which it returns as revm's inspected +//! run does. Its [`InspectorEvmTr`] is revm's inspected lifecycle unchanged, which starts and +//! returns frames through the same two methods. #[cfg(not(feature = "std"))] use alloc as std; @@ -13,52 +16,57 @@ use op_revm::{ transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpHaltReason, OpTransactionError, }; -use std::vec::Vec; +use std::{collections::BTreeMap, vec::Vec}; use alloy_evm::{precompiles::PrecompilesMap, Database}; use revm::{ context::{ result::{FromStringError, InvalidTransaction, ResultGas}, transaction::TransactionType, - ContextError, ContextTr, FrameStack, JournalTr, Transaction, + ContextError, ContextTr, FrameStack, Journal, JournalTr, Transaction, }, context_interface::{ - cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, - journaled_state::{account::JournaledAccountTr, entry::JournalEntry, JournalCheckpoint}, + cfg::{ + gas::{GasTracker, PoolAmounts, PoolId, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, + }, + journaled_state::{entry::JournalEntry, JournalCheckpoint}, Host, }, handler::{ evm::{ContextDbError, FrameInitResult, FrameTr}, execution::runtime_oog_unwind, - instructions::InstructionProvider, + pre_execution::Eip7702AuthFacts, EthFrame, EvmTr, EvmTrError, FrameInitOrResult, FrameResult, Handler, ItemOrResult, PreExecutionOutput, }, - inspector::{ - handler::{frame_start, inspect_instructions}, - InspectorEvmTr, InspectorHandler, JournalExt, - }, + inspector::{InspectorEvmTr, InspectorHandler, JournalExt}, interpreter::{ - interpreter::EthInterpreter, interpreter_action::FrameInit, CallScheme, FrameInput, - InitialAndFloorGas, InstructionResult, InterpreterAction, InterpreterResult, + interpreter::EthInterpreter, interpreter_action::FrameInit, interpreter_types::LoopControl, + CallScheme, FrameInput, Gas, InitialAndFloorGas, InstructionResult, InterpreterAction, + InterpreterResult, }, - primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT, U256}, - Inspector, Journal, + primitives::{Address, Bytes, TxKind, CALL_STACK_LIMIT}, + Inspector, }; use crate::{ access::ComputeStop, - charge_write_records_history, - evm::inspector::{ - frame_end_checked, journal_position, revert_journal_to, ResultSource, StepGuard, - UpfrontRecord, - }, - history_gas, synthetic_frame_result, + charge_write_records_history, history_gas, + limit::{Counted, CreatorBefore}, + synthetic_frame_result, system::keyless, - Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, MegaEvm, MegaInstructions, - PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, + write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, + MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; +#[cfg(debug_assertions)] +use crate::limit::StartRecords; + +/// The regular gas a system call runs on, at most: EIP-8037's system-call budget. The rest of its +/// gas limit is its state-gas reservoir ([`MegaHandler`]'s `tx_gas`). +pub const SYSTEM_CALL_REGULAR_GAS_LIMIT: u64 = 30_000_000; + /// The Satin handler. /// /// It wraps op-revm's [`OpHandler`] and delegates every phase `MegaETH` does not extend to it. @@ -66,17 +74,19 @@ use crate::{ #[derive(Debug)] pub struct MegaHandler { op: OpHandler, - /// Whether validation found the caller of a deposit-like transaction empty, so executing it - /// creates that account. Read by the pre-execution phase, which charges for the account - /// before the transaction runs; by then the caller has been materialised and the fact is no - /// longer visible in the state. - deposit_creates_caller: Cell, + /// The reservoir the transaction's result settled with, read by + /// [`post_execution`](Handler::post_execution) where revm builds the result's gas, and + /// consumed by the report once the result is built + /// ([`execution_result`](Handler::execution_result)) or by the error path + /// ([`catch_error`](Handler::catch_error)), so a handler reused for a system call, whose path + /// makes no capture, reports the system call's own reservoir. + settled_reservoir: Cell>, } impl MegaHandler { /// Creates a handler. pub fn new() -> Self { - Self { op: OpHandler::new(), deposit_creates_caller: Cell::new(false) } + Self { op: OpHandler::new(), settled_reservoir: Cell::new(None) } } } @@ -153,7 +163,9 @@ where /// /// Validation refused every transaction whose body, with a record for each entry of its /// authorization list, crosses the data-size limit, so neither the body nor the authorities' - /// records cross it here, and no limit stops the transaction before its first frame. + /// records cross it here. The KV-update and state-growth limits can be crossed here, by the + /// authorization list: a list that would cross either is not applied, and the transaction's + /// own frame is stopped before it runs. fn pre_execution( &self, evm: &mut Self::Evm, @@ -166,19 +178,33 @@ where // out-of-gas creation cannot be replayed. revm's own pre-execution never needs the bump, // because only an EIP-7702 transaction, always a call, can bail out there; the two // charges made here can fail for a creation too. - if self.deposit_creates_caller.get() && !charge_created_caller(evm.ctx_mut(), gas) { - runtime_oog_unwind(evm.ctx(), checkpoint)?; - return Ok(None); + if deposit_created_caller(evm.ctx()) { + evm.ctx_mut().additional_limit.count_created_caller(); + if !charge_created_caller(evm.ctx_mut(), gas) { + runtime_oog_unwind(evm.ctx(), checkpoint)?; + return Ok(None); + } } - let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { - runtime_oog_unwind(evm.ctx(), checkpoint)?; - return Ok(None); + // The authorization list is decided before it is applied: a list that would keep more + // records or create more accounts than the transaction's limits allow is skipped whole, + // charged nothing, and the transaction's own frame returns the stop before it runs. + let stop = hold_authorization_list(evm.ctx_mut())?; + let eip7702_refund = if let Some(stop) = stop { + evm.ctx_mut().additional_limit.skip_authorization_list(stop); + 0 + } else { + let Some(eip7702_refund) = self.apply_eip7702_auth_list(evm, gas)? else { + runtime_oog_unwind(evm.ctx(), checkpoint)?; + return Ok(None); + }; + eip7702_refund }; - let applied = record_applied_authorities(evm.ctx_mut(), checkpoint.journal_i); + let (applied, created) = applied_authorities(evm.ctx_mut(), checkpoint.journal_i); if !charge_records_made_outside_a_frame(evm.ctx_mut(), gas, applied) { runtime_oog_unwind(evm.ctx(), checkpoint)?; return Ok(None); } + evm.ctx_mut().additional_limit.count_authorities(applied, created); Ok(Some(PreExecutionOutput { eip7702_refund, checkpoint })) } @@ -197,36 +223,24 @@ where self.validate_env_as(evm, system_address, true) } - /// Notes whether this transaction's caller is an account executing it creates, then deducts - /// the caller as op-revm does, which is what creates it. - /// - /// Only a deposit-like transaction can have one: every other transaction pays a fee, which - /// an empty account cannot. The account is charged for in - /// [`pre_execution`](Handler::pre_execution). + /// Deducts the caller as op-revm does. fn validate_against_state_and_deduct_caller( &self, evm: &mut Self::Evm, init_and_floor_gas: &mut InitialAndFloorGas, ) -> Result<(), Self::Error> { - self.deposit_creates_caller.set(deposit_creates_caller(evm.ctx_mut())?); self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) } - /// revm's intrinsic gas, with the history gas of the transaction's body added to the - /// EIP-8037 intrinsic state-gas slot. + /// revm's intrinsic gas, held to a gas limit that covers the history gas of the transaction's + /// body as well, which [`tx_gas`](Handler::tx_gas) charges. /// /// The body's bytes are fixed before the transaction runs, so their price is part of what a /// gas limit has to cover for the transaction to be valid at all: a limit that falls short is /// rejected before inclusion rather than included as an out-of-gas that burns the whole limit. /// revm made that check on its own figure, so the grown figure is checked again here, with the - /// same error naming the same two numbers. - /// - /// The slot it rides in is the state one because that is the pool EIP-8037 pays it from: the - /// reservoir first, spilling onto the regular budget only past it, so a body does not take the - /// execution cap away from computation. The cap check revm made stands as it was — it tests - /// the regular intrinsic gas, which this does not touch — and - /// [`post_execution`](Handler::post_execution) takes the body back out of the state gas the - /// result reports. + /// same error naming the same two numbers. The cap check revm made stands as it was: it tests + /// the regular intrinsic gas, which the body's history does not touch. /// /// A transaction exempt from history gas carries none of it /// ([`MegaContext::prices_history`](crate::MegaContext::prices_history)), so its intrinsic gas @@ -247,11 +261,11 @@ where if !evm.ctx_ref().additional_limit.admits_tx_body(authorizations) { return Err(InvalidTransaction::Str(TX_BODY_OVER_DATA_SIZE_LIMIT.into()).into()); } - let mut gas = self.op.validate_initial_tx_gas(evm)?; + let gas = self.op.validate_initial_tx_gas(evm)?; if !evm.ctx_ref().prices_history() { return Ok(gas); } - let bytes = evm.ctx_ref().additional_limit.body_bytes(); + let bytes = evm.ctx_ref().additional_limit.body(); // A byte count with no price saturates, which no gas limit covers: the transaction is // rejected for not covering its own intrinsic gas. let history = history_gas(bytes).unwrap_or(u64::MAX); @@ -264,75 +278,122 @@ where InvalidTransaction::CallGasCostMoreThanGasLimit { gas_limit, initial_gas }.into() ); } - gas.set_initial_state_gas(gas.initial_state_gas_final() + history); evm.ctx_mut().additional_limit.set_intrinsic_history(history, bytes); Ok(gas) } - /// revm's first frame, with a read of the block beneficiary's account marked for gas detention - /// when the transaction's recipient delegates to the beneficiary: revm resolves that delegate - /// through the journal, where the Host does not see it. + /// revm's transaction-level gas, with the history gas of the transaction's body charged on + /// it, and a system call's split as EIP-8037 has it: at most [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] + /// of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its + /// state-gas reservoir, which the state it writes draws first. + /// + /// The body's history is intrinsic: it comes out of the reservoir first and its excess off the + /// regular budget, as EIP-8037's intrinsic state gas does, so a body does not take the + /// execution cap away from computation; and, as intrinsic gas, no reservoir a frame hands back + /// unwinds it onto the regular budget, so it is charged as no spill. It is charged here rather + /// than before the first frame because revm's runtime out-of-gas fallback rebuilds the + /// transaction's gas through this phase, and a transaction that runs out of gas there keeps its + /// body charged. Validation admitted no gas limit that cannot pay for it + /// ([`validate_initial_tx_gas`](Handler::validate_initial_tx_gas)). + /// + /// revm builds a system call's gas here, on no intrinsic gas, and so does its runtime + /// out-of-gas fallback, which a system call does not reach: it carries no value and its target + /// is no delegator. Every transaction's gas is split by the execution cap alone, the + /// system-address transaction's included, which is a deposit and not a system call; and under + /// the neutral configuration a system call's is not split, as revm's own runner has it. + fn tx_gas(&self, evm: &mut Self::Evm, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.op.tx_gas(evm, init_and_floor_gas); + let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); + if history != 0 { + let spilled = gas.state_gas_spilled(); + let charged = gas.record_history_cost(history); + debug_assert!(charged, "validation admits no gas limit that cannot pay for the body"); + gas.set_state_gas_spilled(spilled); + } + if evm.ctx_ref().splits_system_call_gas() { + let margin = gas.remaining().saturating_sub(SYSTEM_CALL_REGULAR_GAS_LIMIT); + gas.set_remaining(gas.remaining() - margin); + gas.set_reservoir(gas.reservoir() + margin); + } + gas + } + + /// revm's first frame, on the transaction's pool, carrying as its start charge the history + /// charged before execution for the write record it makes; with a read of the block + /// beneficiary's account marked for gas detention when the transaction's recipient delegates + /// to the beneficiary: revm resolves that delegate through the journal, where the Host does + /// not see it. + /// + /// The pools are what the transaction has left of its data-size, KV-update and state-growth + /// limits once its body, the records of the authorities it applied, the accounts they created + /// and a deposit's created caller are counted, the data size under the frame cap + /// ([`AdditionalLimit::first_frame_pools`](crate::AdditionalLimit)); revm hands the frame the + /// whole of each. fn first_frame_input( &mut self, evm: &mut Self::Evm, gas: &mut GasTracker, ) -> Result, Self::Error> { - let Some(frame) = self.op.first_frame_input(evm, gas)? else { + gas.set_pools_remaining(evm.ctx_ref().additional_limit.first_frame_pools()); + let Some(mut frame) = self.op.first_frame_input(evm, gas)? else { // The runtime gas phase could not pay for the first frame's start: EIP-2780's charge // for the account the frame adds, a call's recipient or a creation's account, or the // access to the code a delegated recipient runs, warm or cold. A price of that account // charge that could not be read ends here too: the lookup recorded its cause, which - // fails the transaction when it settles. In each case revm drops the phase's partial - // charges by rebuilding the transaction's gas from its intrinsic cost, and the history - // charged for the first frame's write record went with them: the settlement must not - // give it back a second time, into a reservoir a transaction below the execution cap - // never had. - evm.ctx_mut().additional_limit.set_top_level_write_record_gas(0); + // fails the transaction when it settles. In each case revm takes the phase's state + // back, the authorizations with their records, and drops its partial charges by + // rebuilding the transaction's gas from its intrinsic cost, the history charged for + // the first frame's write record included, which no frame carries back. + evm.ctx_mut().additional_limit.take_back_authorities(); return Ok(None); }; + let charge = StartCharge::new( + evm.ctx_ref().additional_limit.first_frame_charge(), + PoolAmounts::ZERO, + ); + match &mut frame.frame_input { + FrameInput::Call(inputs) => inputs.charged_start = charge, + FrameInput::Create(inputs) => inputs.set_charged_start(charge), + FrameInput::Empty => {} + } evm.ctx_mut().mark_beneficiary_delegate(); Ok(Some(frame)) } - /// Settles the outermost frame: pops its lane, then settles its gas into the transaction's as - /// op-revm does (op-revm replaces revm's settlement, so revm's never runs here): a transaction - /// whose own frame a limit stopped settles like an EIP-8037 revert, its unspent regular gas - /// and reservoir back to the sender. - /// Keeps the history gas the transaction spent: what the body was charged, and what the frames - /// charged net of what they gave back; and the history bytes it appended, which are what those - /// charges were made for. + /// Settles the outermost frame into the transaction's gas as op-revm does (op-revm replaces + /// revm's settlement, so revm's never runs here): a transaction whose own frame a limit stopped + /// settles like an EIP-8037 revert, its unspent regular gas and reservoir back to the sender. + /// + /// The write record the transaction's own frame makes was charged before execution and rides + /// on the frame's input as its start charge, which the settlement gives back when the frame + /// did not succeed, the way EIP-8037 gives back the state gas of the account that frame would + /// have created. A frame answered without returning through + /// [`frame_return_result`](EvmTr::frame_return_result) — revm's answer to the first frame, an + /// interceptor's, an inspector's — closes its start and gives up its stop here. + /// + /// Keeps the history gas the transaction spent, which its gas holds once the frame settled into + /// it: what the body was charged, and what the frames charged net of what they gave back; and + /// the history bytes it appended, which are what those charges were made for. fn last_frame_result( &mut self, evm: &mut Self::Evm, frame_result: &mut FrameResult, parent_gas: &mut GasTracker, ) -> Result<(), Self::Error> { - evm.ctx_mut().additional_limit.on_last_frame_return(frame_result); + let layer = &mut evm.ctx_mut().additional_limit; + layer.close_start(0, frame_result.instruction_result().is_ok()); + layer.take_frame_stop(frame_result, true); self.op.last_frame_result(evm, frame_result, parent_gas)?; - // The write record the transaction's own frame makes was charged before execution; a - // frame that failed keeps no such write, so the charge goes back the way EIP-8037 gives - // back the state gas of the account that frame would have created. - let instruction_result = frame_result.instruction_result(); - if !instruction_result.is_ok() { - parent_gas.refill_history(evm.ctx_ref().additional_limit.top_level_write_record_gas()); - if instruction_result.is_halt() { - parent_gas.spend_all(); - } - *frame_result.gas_mut().tracker_mut() = *parent_gas; - } let priced = evm.ctx_ref().prices_history(); - let layer = &mut evm.ctx_mut().additional_limit; - let history = layer - .intrinsic_history_gas() - .saturating_add_signed(frame_result.gas().history_gas_spent()); - layer.set_history_gas_spent(history); - layer.settle_history_bytes(priced); + let history = 0_u64.saturating_add_signed(frame_result.gas().history_gas_spent()); + evm.ctx_mut().additional_limit.settle_history(priced, history); Ok(()) } - /// revm's post-execution, on the intrinsic gas with the body's history taken back out of the - /// state slot it rode in: the result's state gas is state gas alone, and the history the - /// transaction spent is reported on its own ledger. + /// revm's post-execution, with the reservoir the transaction leaves unspent read first, where + /// revm builds the result's gas: before the EIP-7623 floor check, which absorbs the reservoir + /// into the floor's cost when the floor binds. The refund before it does not move the + /// reservoir. fn post_execution( &self, evm: &mut Self::Evm, @@ -340,9 +401,7 @@ where init_and_floor_gas: InitialAndFloorGas, eip7702_gas_refund: i64, ) -> Result { - let history = evm.ctx_ref().additional_limit.intrinsic_history_gas(); - let init_and_floor_gas = init_and_floor_gas - .with_initial_state_gas(init_and_floor_gas.initial_state_gas_final() - history); + self.settled_reservoir.set(Some(exec_result.gas().reservoir())); self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) } @@ -371,26 +430,54 @@ where self.op.reward_beneficiary(evm, exec_result) } + /// op-revm's result, and the reservoir it settled with reported + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). + /// + /// revm's system-call path settles without [`post_execution`](Handler::post_execution): the + /// result it hands over here is the settled one, and the capture it finds is none, since the + /// report of the execution before consumed it. A deposit that halts is not a result: op-revm + /// turns it into a failed deposit, which leaves no reservoir. fn execution_result( &mut self, evm: &mut Self::Evm, result: FrameResult, result_gas: revm::context::result::ResultGas, ) -> Result, Self::Error> { - self.op.execution_result(evm, result, result_gas) + let reservoir = self.settled_reservoir.take().unwrap_or_else(|| result.gas().reservoir()); + let result = self.op.execution_result(evm, result, result_gas)?; + evm.ctx_mut().additional_limit.set_reservoir_remaining(reservoir); + Ok(result) } /// op-revm's error handling, which answers a deposit's transaction error with a failed-deposit /// halt and discards everything the deposit did. The halt is what the transaction reports; /// what the deposit counted stands, the body and the Oracle hints it forwarded before it /// halted, as for any transaction that halts. Any other error refuses the transaction, and the - /// layer's state is reset by the next one. + /// layer's state is reset by the next one. A reservoir captured for a result that is not + /// reported is dropped here, so the next execution on this handler does not report it. + /// + /// A failed deposit still bumps its caller's nonce and mints, so one whose caller had no + /// account creates it: one account of state growth, which the transaction reports and its + /// block counts, though it pays no state gas for it and no limit stops a deposit that already + /// failed. fn catch_error( &self, evm: &mut Self::Evm, error: Self::Error, ) -> Result, Self::Error> { - self.op.catch_error(evm, error) + self.settled_reservoir.take(); + let result = self.op.catch_error(evm, error); + let failed_deposit = matches!( + result, + Ok(revm::context::result::ExecutionResult::Halt { + reason: OpHaltReason::FailedDeposit, + .. + }) + ); + if failed_deposit && deposit_created_caller(evm.ctx()) { + evm.ctx_mut().additional_limit.count_created_caller(); + } + result } } @@ -405,8 +492,8 @@ where Frame = EthFrame, Inspector: Inspector, EthInterpreter>, >, - // Implied by `EvmTrError`, but the `ContextTr>` bound above stops - // the compiler from normalizing the context's database type down to `DB`. + // Implied by `EvmTrError`, but the `ContextTr>` bound above + // stops the compiler from normalizing the context's database type down to `DB`. ERROR: EvmTrError + From + From> @@ -444,48 +531,73 @@ impl EvmTr for MegaEvm Result, ContextDbError> { - if let Some(result) = self.answered_before_building(&frame_init) { + // The frame on top of the stack, if any, is the caller, which suspends on this start. + if self.inner.frame_stack.index().is_some() { + suspend(&mut self.inner.ctx, self.inner.frame_stack.get(), &mut frame_init); + } + if let Some(result) = call_too_deep(&frame_init) { return Ok(ItemOrResult::Result(result)); } + if frame_init.depth == 0 { + if let Some(mut result) = stop_before_the_first_frame(&mut self.inner.ctx, &frame_init) + { + let gas_limit = input_gas_limit(&frame_init.frame_input); + settle_answer(&mut self.inner.ctx, 0, gas_limit, &mut result); + return Ok(ItemOrResult::Result(result)); + } + } let keyless = keyless::is_dispatched(&self.inner.ctx, &frame_init); let answer = if keyless { keyless::ready(&mut self.inner.ctx, &mut frame_init)? @@ -494,136 +606,185 @@ impl EvmTr for MegaEvm Ok(frame.interpreter.input.target_address), - ItemOrResult::Result(result) => Err(result), - } + if hold == PrecompileHold::Crossing { + // revm never decides the start: what it would have counted is held to the limits as + // the hypothetical the answer gives way to. A creation is never a precompile's. + let mut result = crossing_answer(&frame_init.frame_input); + let verdict = ctx.additional_limit.hypothetical_start(&start.counted, start.shares); + stop_the_answer_at(ctx, &start, &mut result, verdict); + settle_answer(ctx, depth, gas_limit, &mut result); + return Ok(ItemOrResult::Result(result)); + } + let decided = match self.inner.frame_init(frame_init)? { + ItemOrResult::Item(_) => None, + ItemOrResult::Result(result) => Some(result), }; let ctx = &mut self.inner.ctx; - #[cfg(debug_assertions)] - assert_start_as_counted(ctx, counted, outcome.as_ref().err()); - debug_assert!(!keyless || outcome.is_ok(), "revm builds a keylessDeploy call's frame"); - match outcome { - Ok(address) => { - ctx.additional_limit.set_frame_address(address); - if keyless { - ctx.keyless_frame = Some(keyless::KeylessFrame::Built); - } - Ok(ItemOrResult::Item(self.inner.frame_stack.get())) - } - Err(mut result) => { - if let PrecompileHold::Clamped(withheld) = hold { - Detention::restore_forward(result.interpreter_result_mut(), withheld); - } - let succeeded = result.instruction_result().is_ok(); - settle_answer(ctx, depth, gas_limit, &mut result); - match start { - Some(start) => take_back_a_stopped_answer(ctx, start, succeeded, &result), - None => debug_assert!( - !succeeded || result.instruction_result().is_ok(), - "an answer became the stop with no compute limit set" - ), + let Some(mut result) = decided else { + ctx.additional_limit.open_start(depth, start.creator); + let frame = self.inner.frame_stack.get(); + let gas = frame.interpreter.gas.tracker_mut(); + let verdict = ctx.additional_limit.count_start(gas, &start.counted, start.credit); + #[cfg(debug_assertions)] + start.assert_made(ctx); + ctx.detention.on_frame_run(&mut frame.interpreter.gas, depth); + let first = if verdict.exceeded_limit() { + Some(stop_action(ctx, frame, &verdict)) + } else if keyless { + Some(keyless::start(ctx, frame)?) + } else { + None + }; + match first { + Some(action @ InterpreterAction::Return(_)) => { + let result = end_before_it_runs(ctx, frame, action)?; + self.inner.frame_stack.pop(); + return Ok(ItemOrResult::Result(result)); } - Ok(ItemOrResult::Result(result)) + Some(action) => frame.interpreter.bytecode.set_action(action), + None => {} } + return Ok(ItemOrResult::Item(self.inner.frame_stack.get())); + }; + debug_assert!(!keyless, "revm builds a keylessDeploy call's frame"); + if let PrecompileHold::Clamped(withheld) = hold { + Detention::restore_forward(result.interpreter_result_mut(), withheld); } + let succeeded = result.instruction_result().is_ok(); + // A creation revm answers creates nothing: refused on its creator's account, it bumped + // nothing; failed onto an occupied address, it is held to nothing at its start, and its + // failure takes its records and transfer log back. Its creator's record, if revm bumped the + // nonce, is counted on the creator as the answer returns, as a built creation's is. + ctx.additional_limit.open_start(depth, start.creator); + if let FrameResult::Call(_) = result { + let verdict = if succeeded { + let gas = result.gas_mut().tracker_mut(); + ctx.additional_limit.count_start(gas, &start.counted, start.credit) + } else { + ctx.additional_limit.hypothetical_start(&start.counted, start.shares) + }; + stop_the_answer_at(ctx, &start, &mut result, verdict); + } + settle_answer(ctx, depth, gas_limit, &mut result); + take_back_a_stopped_answer(ctx, start.mark, succeeded, &result); + Ok(ItemOrResult::Result(result)) } - /// Runs the frame on top of the stack, unless it has a stop to return: its own, when what a - /// child left it put it over a limit. Then the frame returns the stop without running another - /// instruction (see [`before_frame_run`]). A `keylessDeploy` call's - /// frame runs no instruction at all: its actions are made by hand ([`keyless::run`]). - /// - /// Gas detention holds the frame to the compute limit before it runs, and settles the frame - /// once it suspends on a child or returns (see [`after_frame_run`]). + /// revm's frame run. The actions the engine makes for a frame outside an instruction — the + /// creation a `keylessDeploy` call starts and the call's answer ([`EvmTr::frame_init`], + /// [`EvmTr::frame_return_result`]), and the stop of a frame a child returned into over a limit + /// ([`EvmTr::frame_return_result`]) — are set on the frame's interpreter, and revm's run, plain + /// or inspected, returns an action set before it runs without running an instruction or calling + /// the inspector's `step`. #[inline] fn frame_run( &mut self, ) -> Result, ContextDbError> { - let evm = &mut self.inner; - let frame = evm.frame_stack.get(); - let ctx = &mut evm.ctx; - let action = match before_frame_run(ctx, frame) { - Some(action) => action, - None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, - None => frame.interpreter.run_plain( - evm.instruction.instruction_table(), - evm.instruction.gas_table(), - ctx, - ), - }; - let mut next = frame.process_next_action(ctx, action); - after_frame_run(ctx, frame, &mut next); - next.inspect(|next| { - if next.is_result() { - frame.set_finished(true); - } - }) + self.inner.frame_run() + } + + /// Classifies the result of the frame on top of the stack, which ran and returns, for gas + /// detention ([`end_frame`]). revm's loops, plain and inspected, hand it here once the frame's + /// last action was processed — `return_create` included — and before anything else sees it: + /// the inspector's `call_end`, `create_end` and `frame_end`, then + /// [`frame_return_result`](EvmTr::frame_return_result) and the caller or, for the transaction's + /// own frame, [`last_frame_result`](Handler::last_frame_result). So a frame that crossed the + /// compute limit ends with the stop for all of them, an inspector included. + /// + /// A result [`frame_init`](EvmTr::frame_init) returns does not come here: a frame that ends + /// before it runs is classified where it ends ([`end_before_it_runs`]), and an answer is held + /// to the limit by [`settle_answer`]. + #[inline] + fn frame_run_result( + &mut self, + result: &mut FrameResult, + ) -> Result<(), ContextDbError> { + let depth = self.inner.frame_stack.get().depth; + end_frame(&mut self.inner.ctx, result, depth); + Ok(()) } - /// Pops the returning frame's lane (merged on success, discarded on failure), then returns the - /// result to the caller as revm does. + /// Returns the result to the caller as revm does, in this order: + /// + /// 1. its start is closed: a frame that kept nothing has what the transaction keeps restored to + /// what it kept when its start began, and one that kept its start gives its caller back what + /// the start's credit is ([`close_start`](crate::AdditionalLimit)), refilled on the result + /// before revm merges it, which lands in the caller's pools as a refill after the merge + /// would; + /// 2. revm merges the result into the caller; a creation's creator is then counted the record + /// of the nonce revm bumped for it, held to its budget and then to the transaction's limit + /// ([`hold_creator`]), the caller is held to the transaction's limits with what the frames + /// keep after the return — a failure restores what they kept at its start, which a hint sent + /// meanwhile may leave above a limit + /// ([`AdditionalLimit::hold_caller`](crate::AdditionalLimit)) — and, by gas detention, to + /// the compute limit for its resume ([`on_frame_run`](Detention::on_frame_run)): a caller + /// over a limit returns the stop without running another instruction, set on its interpreter + /// for its run to return. /// /// The creation a `keylessDeploy` call started returns into the call: what the call answers is - /// read off the creation's result before revm merges it ([`keyless::returning`]), and settled - /// into the call after ([`keyless::settle`]). + /// read off the creation's result before revm merges it ([`keyless::returning`]), settled into + /// the call after, the signer's nonce record counted there ([`keyless::settle`]), and set on + /// the call's interpreter, unless it has a stop to return ([`keyless::answer`]). + /// + /// A frame that ran was classified when its run returned + /// ([`frame_run_result`](EvmTr::frame_run_result)); what arrives here is the result the caller + /// settles, an inspector's rewrite included, which is taken as given. #[inline] fn frame_return_result( &mut self, - result: FrameResult, + mut result: FrameResult, ) -> Result, ContextDbError> { - let refund = self.inner.ctx.additional_limit.on_frame_return(&result); + let stack = &mut self.inner.frame_stack; + let (depth, outermost) = match stack.index() { + Some(index) if stack.get().is_finished() => (stack.get().depth, index == 0), + Some(_) => (stack.get().depth + 1, false), + None => (0, true), + }; + let layer = &mut self.inner.ctx.additional_limit; + let (credit, creator) = layer.close_start(depth, result.instruction_result().is_ok()); + if credit != 0 { + result.gas_mut().refill_history(credit); + } + layer.take_frame_stop(&result, outermost); let creation = keyless::returning(&self.inner.ctx, &mut self.inner.frame_stack, &result); let returned = self.inner.frame_return_result(result)?; - // The history of the records the caller paid for and the frame did not keep, given back - // after the merge that adopted the frame's pools. `Some` means the outermost frame - // returned, whose caller is the transaction: it paid for no record of it. if returned.is_some() { - debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); return Ok(returned); } - let caller = &mut self.inner.frame_stack.get().interpreter.gas; - caller.refill_history(refund); - if let Some(creation) = creation { - keyless::settle(&mut self.inner.ctx, caller, creation)?; - } - Ok(returned) + let ctx = &mut self.inner.ctx; + let caller = self.inner.frame_stack.get(); + let (stop, deployment) = match creation { + Some(creation) => { + let gas = &mut caller.interpreter.gas; + let (deployment, stop) = keyless::settle(ctx, gas, creation, creator)?; + (stop, Some(deployment)) + } + None => { + let bumped = creator.filter(|creator| ctx.accounts().bumped(creator)); + let gas = caller.interpreter.gas.tracker_mut(); + (bumped.and_then(|creator| hold_creator(ctx, gas, &creator)), None) + } + }; + let stop = stop.or_else(|| ctx.additional_limit.hold_caller()); + ctx.detention.on_frame_run(&mut caller.interpreter.gas, caller.depth); + let action = match (stop, deployment) { + (Some(stop), _) => stop_action(ctx, caller, &stop), + (None, Some(deployment)) => keyless::answer(ctx, &deployment, caller.interpreter.gas), + (None, None) => return Ok(None), + }; + caller.interpreter.bytecode.set_action(action); + Ok(None) } } @@ -668,178 +829,151 @@ where &mut evm.inspector, ) } +} - /// revm's inspected frame start, with the lanes kept aligned: a frame the inspector answers - /// itself never reaches [`EvmTr::frame_init`], so an empty lane stands in for it, and its - /// answer settles as a frame that never started ([`answered_by_inspector`]). - /// - /// A frame nothing may start, one past the call-stack limit, is answered by - /// [`EvmTr::frame_init`], after the inspector's `frame_start`, as every frame revm does not - /// build is, and the inspector is told it ended. - /// - /// A keyless deployment is seen as the frames it is made of: the transaction's `keylessDeploy` - /// call, and the creation it starts, one journal depth below it, as its child. The call's - /// frame runs no code, so the inspector is not told an interpreter was initialized for it. - #[inline] - fn inspect_frame_init( - &mut self, - mut frame_init: FrameInit, - ) -> Result, ContextDbError> { - // An inspector may have rewritten the input the opcode left pending, or rewrite it at the - // frame's start: the caller's answer is asked again on the input it leaves. - let _ = self.inner.ctx.additional_limit.take_start_refused(); - let (ctx, inspector) = self.ctx_inspector(); - // What the calling opcode charged upfront, before the inspector's hooks can rewrite the - // call it charged for. - let upfront = UpfrontRecord::of(&frame_init.frame_input); - if let Some(output) = frame_start(ctx, inspector, &mut frame_init.frame_input) { - let output = answered_by_inspector(ctx, inspector, &frame_init, output, upfront); - return Ok(ItemOrResult::Result(output)); - } - let (frame_input, depth) = (frame_init.frame_input.clone(), frame_init.depth); - // What the start journals begins here. A start answered with a success without a frame - // is revm's — a call to a precompile or to an account with no code, which takes its - // checkpoint before it journals anything — or an interceptor's, which journals nothing. - let start = journal_position(ctx); - let logs_i = start.log_i; - if let ItemOrResult::Result(mut output) = self.frame_init(frame_init)? { - let (ctx, inspector) = self.ctx_inspector(); - // Logs the frame journaled without running: the EIP-7708 transfer log, and the logs - // of a precompile. - if ctx.journal().logs().len() != logs_i { - inspect_logs(ctx, inspector, logs_i); - } - // Custom precompiles gather their logs outside the journal. - if let FrameResult::Call(outcome) = &output { - if outcome.was_precompile_called { - for log in outcome.precompile_call_logs.clone() { - inspector.log(ctx, log); - } - } - } - let source = ResultSource::Engine(start); - frame_end_checked(ctx, inspector, &frame_input, &mut output, depth, source, upfront); - return Ok(ItemOrResult::Result(output)); - } - let (ctx, inspector, frame) = self.ctx_inspector_frame(); - ctx.upfront_records.resize(depth, None); - ctx.upfront_records.push(upfront); - if ctx.journal().logs().len() != logs_i { - inspect_logs(ctx, inspector, logs_i); - } - if !keyless::runs(ctx, frame) { - inspector.initialize_interp(&mut frame.interpreter, ctx); - } - Ok(ItemOrResult::Item(frame)) - } +/// Settles `caller`, the frame on top of the stack, which suspends to start `child`: gas detention +/// keeps its compute for the child's start to add to the transaction's, with the stipend revm +/// gives a value call's child, which the caller did not forward +/// ([`on_frame_suspend`](Detention::on_frame_suspend)), and the share of its pool the child starts +/// with is held to the frame cap ([`cap_the_shares`]). +/// +/// It runs where the start reaches [`EvmTr::frame_init`]: under an inspector, after the +/// inspector's `frame_start` saw the start. A start the inspector answers itself settles nothing: +/// the caller resumes on the answer as its opcode left it. +#[inline] +fn suspend( + ctx: &mut MegaContext, + caller: &mut EthFrame, + child: &mut FrameInit, +) { + let stipend = value_call_stipend(&child.frame_input, ctx.gas_params().call_stipend()); + ctx.detention.on_frame_suspend(&caller.interpreter.gas, caller.depth, stipend); + let caps = ctx.additional_limit.frame_caps(); + cap_the_shares(ctx.gas_params(), caps, &mut caller.interpreter.gas, child); +} - /// revm's inspected frame run, with the stop short-circuit of [`EvmTr::frame_run`]: a frame - /// with a stop to return returns it without a step, and the inspector sees it end. A - /// `keylessDeploy` call's frame makes its actions by hand, as on the plain path, with no step. - /// - /// The step callbacks run through [`StepGuard`], so a charge the inspector makes on the - /// interpreter's gas and the frame cannot pay does not classify the frame's end. - #[inline] - fn inspect_frame_run( - &mut self, - ) -> Result, ContextDbError> { - let (ctx, inspector, frame, instructions) = self.ctx_inspector_frame_instructions(); - let action = match before_frame_run(ctx, frame) { - Some(action) => action, - None if keyless::runs(ctx, frame) => keyless::run(ctx, frame)?, - None => inspect_instructions( - ctx, - &mut frame.interpreter, - StepGuard(&mut *inspector), - instructions.instruction_table(), - instructions.gas_table(), - ), - }; - let mut next = frame.process_next_action(ctx, action); - after_frame_run(ctx, frame, &mut next); - if let Ok(ItemOrResult::Result(result)) = &mut next { - let source = ResultSource::Engine(frame.checkpoint); - let upfront = ctx.upfront_records.get(frame.depth).copied().flatten(); - frame_end_checked(ctx, inspector, &frame.input, result, frame.depth, source, upfront); - frame.set_finished(true); - } - next - } +/// The action of `frame` that stops it at the limit `verdict` names before it runs another +/// instruction: a revert carrying `MegaLimitExceeded` on the gas the frame holds. A frame revm just +/// built whose start crossed the limit returns it before its first instruction: its journal +/// checkpoint takes back what the start moved and its transfer log, and a creation keeps its +/// creator's nonce bump, which revm makes before the checkpoint, its record counted on the creator +/// once the creation returned. A creator that record put over a limit returns it on its resume. +#[cold] +#[inline(never)] +fn stop_action( + ctx: &mut MegaContext, + frame: &EthFrame, + verdict: &LimitCheck, +) -> InterpreterAction { + let output = ctx.additional_limit.note_frame_stop(verdict); + InterpreterAction::new_return(InstructionResult::Revert, output, frame.interpreter.gas) } -/// The action of a frame about to run: the stop it returns without running an instruction, when -/// it has one ([`stop_before_run`](crate::AdditionalLimit::stop_before_run)); `None` otherwise, -/// and the frame runs. -/// -/// A frame runs here for the first time or after a child returned into it. A stop is always the -/// latter: the child was a failed creation whose nonce record, which lands on its creator, put the -/// creator over a limit, its budget or the transaction's, and the creator reverts alone, as for a -/// write of its own. A child that crossed a limit itself reverted alone, and its caller resumes. +/// Ends `frame`, which revm just built, with `action`, the return made for it before it runs an +/// instruction — the stop its start crossed, or a `keylessDeploy` call's refusal — as revm's +/// frame run ends a frame that returns: revm settles the frame's journal checkpoint and builds its +/// result, which gas detention then classifies ([`end_frame`]). /// -/// Either way gas detention sees the frame first: a frame's first run adds its caller's compute -/// to the transaction's, a resume takes it back, and the frame's spendable gas is held to what the -/// compute limit leaves it — which is how a child's read of volatile data caps every caller it -/// returns into. -#[inline] -fn before_frame_run( +/// The frame never ran an instruction, so it is returned as an answer is, off the stack: its +/// caller resumes on it, and an inspector sees it start and end, and neither an interpreter nor +/// what its start journaled when the return reverts it. +#[cold] +#[inline(never)] +fn end_before_it_runs( ctx: &mut MegaContext, frame: &mut EthFrame, -) -> Option { - ctx.detention.on_frame_run(&mut frame.interpreter.gas, frame.depth); - let stop = ctx.additional_limit.stop_before_run()?; - Some(InterpreterAction::new_return( - InstructionResult::Revert, - ctx.additional_limit.note_frame_stop(&stop), - frame.interpreter.gas, - )) + action: InterpreterAction, +) -> Result>> { + let next = + frame.process_next_action::<_, ContextDbError>>(ctx, action); + let ItemOrResult::Result(mut result) = next? else { + unreachable!("a frame that returns has a result") + }; + end_frame(ctx, &mut result, frame.depth); + Ok(result) } -/// Settles gas detention once the frame ran: a frame that suspends on a child keeps its compute -/// for the child's start to add to the transaction's; a frame that returns is classified. -/// -/// The frame's result is read here, after revm processed its last action — `return_create` -/// included, whose deposit and hash charges are the creating frame's own compute — and before -/// revm hands it to the caller or, for the transaction's own frame, to -/// [`last_frame_result`](Handler::last_frame_result), which overwrites its gas with the -/// transaction's. +/// Classifies `result`, the result of a frame at `depth` that ran, for gas detention, once revm +/// processed the frame's last action — `return_create` included, whose deposit and hash charges +/// are the creating frame's own compute. /// /// A frame that ran out of gas on a charge the withheld part of its gas would have paid crossed /// the compute limit rather than its own gas: its halt becomes the compute stop, a revert of that /// frame alone ([`stop_at_the_compute_limit`]). Every other out-of-gas halts, as it would without /// the read. #[inline] -fn after_frame_run( +fn end_frame( ctx: &mut MegaContext, - frame: &EthFrame, - next: &mut Result>, E>, + result: &mut FrameResult, + depth: usize, ) { - match next { - Ok(ItemOrResult::Item(_)) => { - ctx.detention.on_frame_suspend(&frame.interpreter.gas, frame.depth); - } - Ok(ItemOrResult::Result(result)) => { - let instruction_result = result.instruction_result(); - if let Some(stop) = - ctx.detention.on_frame_end(instruction_result, result.gas_mut(), frame.depth) - { - stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); - } - } - Err(_) => {} + let instruction_result = result.instruction_result(); + if let Some(stop) = ctx.detention.on_frame_end(instruction_result, result.gas_mut(), depth) { + stop_at_the_compute_limit(ctx, result.interpreter_result_mut(), stop); } } -/// Records, for gas detention, the frame revm is about to build a child of at `depth`, while no -/// read has set a limit ([`Detention::on_child_build`]): the caller is still on top of the stack. -#[inline] -fn record_caller( +/// Counts on a creator whose pools `gas` holds, once a creation it started returned into it, what +/// the nonce bump revm made for the creation made of it ([`Accounts::creator_counted`]) — `before` +/// is the creator as it stood before revm decided the creation — and answers the stop the creator +/// returns before it runs on, if the count crossed a limit: the record is held to the creator's +/// budget, then to the transaction's limit, as any count the creator makes +/// ([`draw`](crate::AdditionalLimit)). The creation's budget was taken before the record, at its +/// opcode, so the record is the creator's alone, and it is counted whether the creation succeeded +/// or not, since the bump outlives it. +/// +/// [`Accounts::creator_counted`]: crate::limit::Accounts +pub(crate) fn hold_creator( ctx: &mut MegaContext, - frame_stack: &mut FrameStack>, - depth: usize, -) { - if depth > 0 && ctx.detention.records_callers() { - debug_assert_eq!(frame_stack.index(), Some(depth - 1), "the caller is on top"); - ctx.detention.on_child_build(depth, &frame_stack.get().interpreter.gas); + gas: &mut GasTracker, + before: &CreatorBefore, +) -> Option { + let counted = ctx.accounts().creator_counted(before); + let check = ctx.additional_limit.draw(gas, &counted); + check.exceeded_limit().then_some(check) +} + +/// Holds the share of each of its caller's pools the frame `child` starts with to the share of what +/// the caller has left, its remaining clamped to its budget, and to that pool's frame cap in +/// `caps`, and gives what it forwarded above that back to the caller, whose pools `caller` holds. +/// +/// A frame's remaining is `min(budget, max(0, budget − net))`: a frame whose net is negative — it +/// took back a record or removed state a frame above it made — holds more in its pool than the +/// budget it was given, and the share it forwards is of that budget, not of the pool, so a negative +/// net never enlarges a child's budget. The fork forwarded the schedule's share of the pool the +/// opcode found ([`GasParams::pool_forward_share`]); the caller had that pool and the share +/// together, and its budget is that less its net draw. +#[inline] +fn cap_the_shares(params: &GasParams, caps: PoolAmounts, caller: &mut Gas, child: &mut FrameInit) { + let mut shares = match &child.frame_input { + FrameInput::Call(inputs) => inputs.pool_shares, + FrameInput::Create(inputs) => inputs.pool_shares(), + FrameInput::Empty => return, + }; + let mut capped = false; + for pool in PoolId::ALL { + let share = shares.get(pool); + let mut allowed = caps.get(pool); + let spent = caller.pool_spent(pool); + if spent < 0 { + let had = caller.pool_remaining(pool).saturating_add(share); + let budget = had.saturating_add_signed(spent); + allowed = allowed.min(params.pool_forward_share(pool, budget)); + } + let Some(excess) = share.checked_sub(allowed).filter(|excess| *excess != 0) else { + continue; + }; + caller.set_pool_remaining(pool, caller.pool_remaining(pool).saturating_add(excess)); + shares.set(pool, allowed); + capped = true; + } + if !capped { + return; + } + match &mut child.frame_input { + FrameInput::Call(inputs) => inputs.pool_shares = shares, + FrameInput::Create(inputs) => inputs.set_pool_shares(shares), + FrameInput::Empty => {} } } @@ -895,7 +1029,9 @@ enum PrecompileHold { /// The price does not tell whether the input passes the checks a precompile makes after its gas /// check, so an input priced past the allowance and within the forward is the stop even when /// those checks would fail the call. A call revm refuses on its caller's account — a value it -/// cannot fund — runs no precompile, and revm answers it as without the limit. +/// cannot fund — runs no precompile, and revm answers it as without the limit: the answer given +/// without running is not given in its place, which a comparison of the caller's balance with the +/// value decides, as revm's transfer does. /// /// A precompile the engine cannot price is run on the allowance and sees it as its gas limit /// ([`Clamped`](PrecompileHold::Clamped), with what was taken off the forward); its answer gets the @@ -907,12 +1043,11 @@ fn hold_precompile( precompiles: &PrecompilesMap, priced: &PricedPrecompiles, frame_init: &mut FrameInit, - refused: bool, ) -> PrecompileHold { if ctx.detention.compute_limit().is_none() { return PrecompileHold::Unheld; } - hold_detained_precompile(ctx, precompiles, priced, frame_init, refused) + hold_detained_precompile(ctx, precompiles, priced, frame_init) } /// [`hold_precompile`] once a read set a compute limit. @@ -922,7 +1057,6 @@ fn hold_detained_precompile( precompiles: &PrecompilesMap, priced: &PricedPrecompiles, frame_init: &mut FrameInit, - refused: bool, ) -> PrecompileHold { let FrameInput::Call(inputs) = &mut frame_init.frame_input else { return PrecompileHold::Unheld; @@ -941,7 +1075,16 @@ fn hold_detained_precompile( inputs.gas_limit = allowance; return PrecompileHold::Clamped(withheld); }; - if price <= allowance || price > inputs.gas_limit || refused { + if price <= allowance || price > inputs.gas_limit { + return PrecompileHold::Unheld; + } + let caller = ctx.journal_ref().state.get(&inputs.caller); + let unfunded = inputs + .value + .transfer() + .zip(caller) + .is_some_and(|(value, caller)| caller.info.balance < value); + if unfunded { return PrecompileHold::Unheld; } PrecompileHold::Crossing @@ -959,7 +1102,7 @@ fn crossing_answer(input: &FrameInput) -> FrameResult { } /// The gas limit of the frame `input` starts. -const fn input_gas_limit(input: &FrameInput) -> u64 { +pub(crate) const fn input_gas_limit(input: &FrameInput) -> u64 { match input { FrameInput::Call(inputs) => inputs.gas_limit, FrameInput::Create(inputs) => inputs.gas_limit(), @@ -967,6 +1110,15 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { } } +/// The stipend revm adds to the gas limit of the frame `input` starts, `call_stipend` for a call +/// that transfers value and nothing for any other: gas the caller never paid. +pub(crate) fn value_call_stipend(input: &FrameInput, call_stipend: u64) -> u64 { + match input { + FrameInput::Call(inputs) if inputs.transfers_value() => call_stipend, + _ => 0, + } +} + /// Turns a frame that crossed gas detention's compute limit into the compute stop: a revert of /// that frame alone carrying `MegaLimitExceeded` (kind: compute). The frame's gas is what it had /// before the charge that crossed, which goes back with the revert to its caller. The caller @@ -974,7 +1126,8 @@ const fn input_gas_limit(input: &FrameInput) -> u64 { /// crossed, so a caller that carries on is stopped at its next charge past it. /// /// The crossing charge's size is not kept, so the stop reports the transaction's compute at the -/// crossing as what was used ([`LimitCheck::ExceedsLimit`]): what its regular ledger bills. +/// crossing as what was used ([`LimitCheck::ExceedsLimit`]): what its regular ledger bills, and +/// the stipends of its value calls on top. fn stop_at_the_compute_limit( ctx: &mut MegaContext, result: &mut InterpreterResult, @@ -1010,18 +1163,21 @@ impl MegaEvm { }; crate::system::intercept(&mut self.inner.ctx, inputs, frame_init.depth, caller_remaining) } +} - /// Step 1 of [`EvmTr::frame_init`], the pre-frame check: answers a frame nothing may start, one - /// past the call-stack limit ([`call_too_deep`]), with the empty lane that stands in for it. On - /// the inspected path it comes after the inspector's `frame_start`. - #[inline] - fn answered_before_building(&mut self, frame_init: &FrameInit) -> Option { - let answer = call_too_deep(frame_init); - if answer.is_some() { - self.inner.ctx.additional_limit.push_empty_frame(); - } - answer - } +/// Marks where `journal` stands, without changing its depth: a checkpoint opened and committed at +/// once, which [`revert_to`] takes the journal back to. +pub(crate) fn mark(journal: &mut Journal) -> JournalCheckpoint { + let position = journal.checkpoint(); + journal.checkpoint_commit(); + position +} + +/// Takes back every journal entry, log and self-destruct made since `mark`, as revm takes back a +/// frame that fails; the journal's depth is left as it is. +pub(crate) fn revert_to(journal: &mut Journal, mark: JournalCheckpoint) { + let _ = journal.checkpoint(); + journal.checkpoint_revert(mark); } /// Takes the journal back to `start`, where a frame's start began, when revm answered the frame @@ -1040,53 +1196,349 @@ fn take_back_a_stopped_answer( result: &FrameResult, ) { if succeeded && !result.instruction_result().is_ok() { - revert_journal_to(ctx, start); + revert_to(ctx.journal_mut(), start); + } +} + +/// What holding a frame's start to the limits needs of it once revm consumed its input: where the +/// start began, what it counts and what a stop answering it carries. +struct FrameStart { + /// Where the journal stood before revm decided the start: what revm journals for it — a + /// creator's nonce bump, the value the start moves and its transfer log, a precompile's + /// writes — comes after. + mark: JournalCheckpoint, + /// The records and transfer log the start makes on its frame, read off the journal before + /// revm decides it. + counted: Counted, + /// What the start's caller gets back once the frame returned with its start kept: what it + /// paid for the records on the frame, less the price of those the start makes, and the price + /// of those it takes back. + credit: u64, + /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. + gas_limit: u64, + /// The reservoir the frame inherits. + reservoir: u64, + /// The shares of its caller's pools the frame starts with: its budgets. + shares: PoolAmounts, + /// For a creation a frame makes, its creator as it stands before revm decides the start, which + /// tells once the creation returned what revm's nonce bump made of it. The transaction's own + /// creation has none: its sender's account is the transaction body's. + creator: Option, + /// The records the start makes, for a debug build to hold what revm then made to. + #[cfg(debug_assertions)] + made: MadeRecords, +} + +impl FrameStart { + /// The start of the frame `frame_init` asks for, about to be decided by revm: where the + /// journal stands, the records it makes on its frame as the journal's state stands + /// ([`Accounts::start_records`](crate::limit::Accounts)), and a creation's creator. A + /// creation's creator record is not among the records: it is the creator's, counted from the + /// bump once the creation returned. + fn of( + ctx: &mut MegaContext, + frame_init: &FrameInit, + ) -> Result> { + // A creation's creator and address are loaded before revm decides the start, as revm + // loads them itself, outside the creation's checkpoint, once it decides it: the creator + // first thing, the address once the creator funds the endowment and its nonce bumps. The + // `CREATE` opcode loaded the address already unless EIP-8037 is off, and the creator is + // the frame that runs it, so only an inspector's rewrite, or EIP-8037 off, makes a load + // here that revm would not have made yet; neither changes what revm decides. An address an + // earlier transaction on the same journal left there is not loaded until it is again. + let mut creator = None; + if let FrameInput::Create(inputs) = &frame_init.frame_input { + let info = &ctx.journal_mut().load_account(inputs.caller())?.data.info; + let bumps = info.balance >= inputs.value() && info.nonce != u64::MAX; + let created = inputs.created_address(info.nonce); + if bumps && !ctx.accounts().is_loaded(created) { + ctx.journal_mut().load_account(created)?; + } + if frame_init.depth > 0 { + creator = Some(ctx.accounts().creator_before(inputs.caller())); + } + } + let accounts = ctx.accounts(); + let (records, growth, charged, reservoir, shares) = match &frame_init.frame_input { + FrameInput::Call(inputs) => { + let value = inputs.value.transfer().unwrap_or_default(); + ( + accounts.transfer_records(inputs.caller, inputs.target_address, value), + accounts.transfer_growth(inputs.caller, inputs.target_address, value), + inputs.charged_start.history, + inputs.reservoir, + inputs.pool_shares, + ) + } + FrameInput::Create(inputs) => { + let created = inputs.created_address(account_nonce(ctx, inputs.caller())); + ( + accounts.creation_records(inputs.caller(), Some(created), inputs.value()), + accounts.creation_growth(inputs.caller(), created, inputs.value()), + inputs.charged_start().history, + inputs.reservoir(), + inputs.pool_shares(), + ) + } + FrameInput::Empty => unreachable!( + "a frame input always names a call or a creation, as revm's frame init asserts" + ), + }; + let on_frame = records.on_frame(); + let credit = if ctx.prices_history() { + let price = |records| write_record_history_gas(records).unwrap_or(0); + charged.saturating_sub(price(on_frame.added)).saturating_add(price(on_frame.taken)) + } else { + 0 + }; + #[cfg(debug_assertions)] + let made = MadeRecords::before(ctx, frame_init, records); + Ok(Self { + mark: mark(ctx.journal_mut()), + counted: records.counted().with_growth(growth, 0), + credit, + gas_limit: input_gas_limit(&frame_init.frame_input), + reservoir, + shares, + creator, + #[cfg(debug_assertions)] + made, + }) + } + + /// Asserts revm's start made the records counted for it, read off the journal once revm built + /// the frame. + #[cfg(debug_assertions)] + fn assert_made(&self, ctx: &MegaContext) { + self.made.assert_after(ctx); + } +} + +/// The accounts a start makes its records of on its frame and whether the transaction had changed +/// each before it, for a debug build to hold the records the start counted to what revm's start +/// made of them. +#[cfg(debug_assertions)] +#[derive(Debug)] +struct MadeRecords { + /// The records predicted. + records: StartRecords, + /// The accounts, each with whether it was changed before the start. + accounts: MadeOn, +} + +/// The accounts a start makes its records of on its frame. +#[cfg(debug_assertions)] +#[derive(Debug)] +enum MadeOn { + /// A call's sender and recipient. + Call([(Address, bool); 2]), + /// A creation's created account. Its creator's record is the creator's, read off the journal + /// once the creation returned. + Creation((Address, bool)), +} + +#[cfg(debug_assertions)] +impl MadeRecords { + /// The accounts the start `frame_init` asks for writes, read before revm decides it, and the + /// `records` predicted for it. + fn before( + ctx: &MegaContext, + frame_init: &FrameInit, + records: StartRecords, + ) -> Self { + let journal = ctx.accounts(); + let read = |address: Address| (address, journal.is_changed(address)); + let accounts = match &frame_init.frame_input { + FrameInput::Call(inputs) => { + MadeOn::Call([read(inputs.caller), read(inputs.target_address)]) + } + FrameInput::Create(inputs) => { + let nonce = account_nonce(ctx, inputs.caller()); + MadeOn::Creation(read(inputs.created_address(nonce))) + } + FrameInput::Empty => MadeOn::Call([read(Address::ZERO); 2]), + }; + Self { records, accounts } + } + + /// Asserts the frame revm built made the records predicted: a call's two sides changed and + /// returned as its transfer's records say, a creation's created account as its record says. + fn assert_after( + &self, + ctx: &MegaContext, + ) { + use crate::limit::RecordDelta; + let accounts = ctx.accounts(); + let made = |(address, before): (Address, bool)| { + RecordDelta::of_account(before, accounts.is_changed(address)) + }; + match self.accounts { + MadeOn::Call([first, second]) => { + let made = if first.0 == second.0 { + RecordDelta::NONE + } else { + made(first).with(made(second)) + }; + debug_assert_eq!(made, self.records.transfer, "a call's start made its records"); + } + MadeOn::Creation(created) => { + let record = RecordDelta::of_account(false, self.records.created); + debug_assert_eq!( + made(created), + record, + "a creation made its created account's record" + ); + } + } + } +} + +/// The nonce of an account the journal holds; zero for one it does not. +fn account_nonce( + ctx: &MegaContext, + address: Address, +) -> u64 { + ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) +} + +/// Holds `answer`, revm's or gas detention's answer to the call `start` began, to `verdict`: a +/// crossing is the stop the answer gives way to, on the gas its caller forwarded, untouched, as a +/// frame stopped before it ran ([`stop_the_answer`]). What a successful answer's start moved is +/// taken back with it ([`take_back_a_stopped_answer`]); a failed one's revm took back itself. +fn stop_the_answer_at( + ctx: &mut MegaContext, + start: &FrameStart, + answer: &mut FrameResult, + verdict: LimitCheck, +) { + if verdict.exceeded_limit() { + let output = ctx.additional_limit.note_frame_stop(&verdict); + stop_the_answer(answer, start, output); } } -/// Settles `output`, the answer an inspector gave the frame `frame_init` starts in its place, as -/// [`EvmTr::frame_init`] settles an answer: the depth guard still holds, so an answer cannot reach -/// past the call-stack limit; an empty lane stands in for the frame, and the answer is held to the -/// compute limit ([`settle_answer`]). Then the inspector is told the frame ended, and the answer -/// settles as a frame that kept nothing: the frame never started, so no value moved and no account -/// was added, and the upfront state gas its caller's opcode was charged comes back whatever the -/// answer ([`frame_end_checked`]). -fn answered_by_inspector( +/// Rewrites `answer`, to the call `start` began, into the stop `output`: a revert on the gas the +/// call's caller forwarded, untouched, with the reservoir and the pools the call inherited, and no +/// precompile output, as [`synthetic_frame_result`] answers a frame that never started. +#[cold] +#[inline(never)] +fn stop_the_answer(answer: &mut FrameResult, start: &FrameStart, output: Bytes) { + let FrameResult::Call(outcome) = answer else { + unreachable!("only a call is held to the limits once revm answered it") + }; + let mut gas = Gas::new_with_regular_gas_and_reservoir(start.gas_limit, start.reservoir); + gas.tracker_mut().set_pools_remaining(start.shares); + let allowance = outcome.result.gas.history_allowance(); + gas.set_history_allowance(allowance); + outcome.result = InterpreterResult::new(InstructionResult::Revert, output, gas); + outcome.was_precompile_called = false; + outcome.precompile_call_logs.clear(); +} + +/// The answer to the transaction's own frame `frame_init` when its authorization list was skipped +/// for a limit ([`AdditionalLimit::skip_authorization_list`](crate::AdditionalLimit)): the stop, +/// before the frame runs and before revm moves anything for it, on the gas its input carries, with +/// the reservoir and the start charge, which the first frame's settlement gives back. +fn stop_before_the_first_frame( ctx: &mut MegaContext, - inspector: &mut INSP, frame_init: &FrameInit, - output: FrameResult, - upfront: Option, -) -> FrameResult -where - INSP: Inspector, EthInterpreter>, -{ - let mut output = call_too_deep(frame_init).unwrap_or(output); - ctx.additional_limit.push_empty_frame(); - let gas_limit = input_gas_limit(&frame_init.frame_input); - settle_answer(ctx, frame_init.depth, gas_limit, &mut output); - let (input, depth) = (&frame_init.frame_input, frame_init.depth); - frame_end_checked(ctx, inspector, input, &mut output, depth, ResultSource::Inspector, upfront); - output +) -> Option { + let stop = ctx.additional_limit.take_pre_frame_stop()?; + let output = ctx.additional_limit.note_frame_stop(&stop); + Some(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) } -/// Answers a frame a limit stops before it is built with the stop: a revert with the stop's -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded) output, as a [`synthetic_frame_result`] that -/// settles like a frame revm ran. +/// Decides the transaction's EIP-7702 authorization list before it is applied, as the spec has +/// it: the whole list is simulated in order — each entry with a chain id that is neither zero nor +/// the chain's, a nonce of `2^64 − 1` or a signature that recovers no authority skipped unread; +/// every other authority loaded once, with its code, and skipped when that code is not a +/// delegation; a nonce compared with the authority's effective one, which the simulation bumps +/// for each entry it accepts — and the totals it would keep are held to the transaction's KV and +/// state-growth limits. The stop when they cross one, KV updates first; `None` when they fit, or +/// when the list is too short to cross either. /// -/// A creation still bumps its creator's nonce, as one that starts and reverts does: a nested -/// creation's caller sees an ordinary failed creation, and a creation transaction whose own frame -/// is stopped at its start cannot be replayed. -fn stop_before_building( +/// The simulation writes nothing and warms nothing: the loads are taken back to a journal mark, +/// which leaves the accounts in the transaction's state, cold, so a stateless witness holds every +/// authority the simulation read. A database error reading one is the transaction's error. +fn hold_authorization_list( ctx: &mut MegaContext, - frame_init: &FrameInit, - check: &LimitCheck, -) -> Result>> { - if let FrameInput::Create(inputs) = &frame_init.frame_input { - let _ = ctx.journal_mut().load_account_mut(inputs.caller())?.data.bump_nonce(); +) -> Result, DB::Error> { + if ctx.tx().tx_type() != TransactionType::Eip7702 { + return Ok(None); + } + let entries = ctx.tx().authorization_list_len() as u64; + if !ctx.additional_limit.authorization_list_may_cross(entries) { + return Ok(None); + } + let (records, created) = simulate_authorization_list(ctx)?; + let check = ctx.additional_limit.hold_authorization_list(records, created); + Ok(check.exceeded_limit().then_some(check)) +} + +/// What one authority of a simulated authorization list stands at. +struct SimulatedAuthority { + address: Address, + /// Its nonce, bumped by every entry the simulation accepted. + nonce: u64, + /// Whether its code is empty or a delegation, which an entry needs to apply. + applies: bool, + /// Whether the transaction's state did not hold it, so applying an entry creates it. + absent: bool, + /// Whether an entry for it was accepted. + accepted: bool, +} + +/// The write records and the created accounts the transaction's authorization list would keep +/// were it applied ([`hold_authorization_list`]): one record for each distinct authority an +/// accepted entry changes, the sender's account being the body's, and one created account for each +/// distinct authority it would create. +fn simulate_authorization_list( + ctx: &mut MegaContext, +) -> Result<(u64, u64), DB::Error> { + let chain_id = ctx.cfg().chain_id; + let caller = ctx.tx().caller(); + let entries = Eip7702AuthFacts::collect(ctx.tx(), chain_id); + let start = mark(ctx.journal_mut()); + let mut authorities: Vec = Vec::new(); + // Each authority's place in `authorities`, so a list of any length is simulated without a + // scan of what it has seen. + let mut seen: BTreeMap = BTreeMap::new(); + for entry in &entries { + let Some(authority) = entry.authority else { continue }; + let index = match seen.get(&authority) { + Some(index) => *index, + None => { + let account = ctx.journal_mut().load_account_with_code(authority)?.data; + let applies = account + .info + .code + .as_ref() + .is_none_or(|code| code.is_empty() || code.is_eip7702()); + let absent = + account.info.is_empty() && account.is_loaded_as_not_existing_not_touched(); + authorities.push(SimulatedAuthority { + address: authority, + nonce: account.info.nonce, + applies, + absent, + accepted: false, + }); + seen.insert(authority, authorities.len() - 1); + authorities.len() - 1 + } + }; + let simulated = &mut authorities[index]; + if !simulated.applies || entry.nonce != simulated.nonce { + continue; + } + simulated.nonce += 1; + simulated.accepted = true; } - let output = ctx.additional_limit.note_frame_stop(check); - Ok(synthetic_frame_result(&frame_init.frame_input, InstructionResult::Revert, output)) + revert_to(ctx.journal_mut(), start); + let accepted = authorities.iter().filter(|authority| authority.accepted); + let records = accepted.clone().filter(|authority| authority.address != caller).count(); + let created = accepted.filter(|authority| authority.absent).count(); + Ok((records as u64, created as u64)) } /// The depth guard: a frame past the call-stack limit, of any call scheme or a creation, answered @@ -1095,13 +1547,13 @@ fn stop_before_building( /// revm checks the depth first when it builds a frame, before it moves value or bumps a creator's /// nonce. The guard gives the same answer before anything else sees the frame: an interceptor or an /// inspector answers before revm builds anything, so without the guard a system contract could be -/// reached at any depth; and a start's writes are counted before revm decides it, so without the -/// guard a creation past the limit would count its creator's nonce record — which outlives a failed -/// creation — for a nonce revm never bumps. +/// reached at any depth; and a call's start is held to the limits whatever revm answers but a +/// value its caller cannot fund, so without the guard a call past the limit would be held to them +/// as a start revm made. /// /// No transaction reaches the limit: regular gas is capped by the execution cap and every call -/// forwards at most sixty-three sixty-fourths of what its caller has left, so a frame at depth -/// 1,024 has a few gas. +/// forwards at most 98/100 of what its caller has left, so a frame at depth 1,024 has less than a +/// gas. fn call_too_deep(frame_init: &FrameInit) -> Option { (frame_init.depth > CALL_STACK_LIMIT as usize).then(|| { synthetic_frame_result( @@ -1112,95 +1564,23 @@ fn call_too_deep(frame_init: &FrameInit) -> Option { }) } -/// Asserts that revm started a frame the way the data size counted its start, once revm has built -/// the frame or answered it: that revm refused exactly the start [`caller_refuses_start`] -/// predicted, and journaled exactly the EIP-7708 transfer log counted. `counted` is whether the -/// start counts a transfer log when revm makes it -/// ([`frame_start_transfer_log`](crate::AdditionalLimit)), `refused` whether it was predicted -/// refused and so counted nothing, `logs_i` the journal's log count before revm acted, and -/// `answer` revm's answer when it did not build the frame. -/// -/// The count is made before revm decides, from the frame's input and its caller's account, so this -/// is where a divergence from revm's own rules would show. revm refuses a start on its caller's -/// account with `OutOfFunds`, for a value the caller cannot fund, and with a `Return` for a -/// creation whose creator's nonce cannot be bumped — the one creation it answers with a success. -/// It refuses a start past the call-stack limit too, but the depth guard answers that start -/// before revm sees it ([`call_too_deep`]), so revm never answers one. A built frame has run no -/// instruction yet, so the move is all revm has done. An answered call -/// moved the value when it succeeded — a call to an account with no code, a precompile — and took -/// the move back when it failed. A creation revm answers never moved value: it refused before its -/// checkpoint, or reverted it (a creation onto an occupied address). Only transfer logs are -/// compared: a precompile may journal logs of its own. -#[cfg(debug_assertions)] -fn assert_start_as_counted( - ctx: &MegaContext, - (counted, refused, logs_i): (bool, bool, usize), - answer: Option<&FrameResult>, -) { - debug_assert!( - answer.is_none_or(|answer| answer.instruction_result() != InstructionResult::CallTooDeep), - "the depth guard answers every start past the call-stack limit" - ); - let refused_by_revm = match answer { - None => false, - Some(FrameResult::Call(outcome)) => outcome.result.result == InstructionResult::OutOfFunds, - Some(FrameResult::Create(outcome)) => matches!( - outcome.result.result, - InstructionResult::OutOfFunds | InstructionResult::Return - ), - }; - debug_assert_eq!(refused, refused_by_revm, "the start revm refused is the one predicted"); - let moved = match answer { - None => true, - Some(FrameResult::Call(outcome)) => outcome.result.result.is_ok(), - Some(FrameResult::Create(_)) => false, - }; - let journaled = ctx.journal_ref().logs()[logs_i..] - .iter() - .filter(|log| log.address == revm::primitives::eip7708::ETH_TRANSFER_LOG_ADDRESS) - .count(); - debug_assert_eq!( - journaled, - usize::from(counted && moved), - "the transfer log counted is the one revm journaled" - ); -} - -/// Hands the logs journaled since `logs_i` to the inspector, outside any interpreter. -#[cold] -#[inline(never)] -fn inspect_logs( - ctx: &mut MegaContext, - inspector: &mut INSP, - logs_i: usize, -) where - INSP: Inspector, EthInterpreter>, -{ - let logs = ctx.journal().logs()[logs_i..].to_vec(); - for log in logs { - inspector.log(ctx, log); - } -} - -/// Whether executing this transaction creates its caller's account: a deposit-like transaction -/// whose caller is empty, which the deposit path materialises by bumping its nonce or by minting -/// to it. +/// Whether executing this transaction created its caller's account: a deposit-like transaction +/// whose caller was empty when the transaction loaded it, which the deposit path materialised by +/// bumping its nonce or by minting to it. /// -/// Read before op-revm deducts the caller, which is what materialises the account, and after -/// [`validate_env`](Handler::validate_env), which promoted a system-address transaction: a -/// deposit-like transaction is a deposit by then. Every other transaction pays a fee its caller +/// Read once op-revm deducted the caller, which loaded it and is what materialised it, off the +/// info revm keeps of the account as the transaction first loaded it (`Account::original_info`), +/// and after [`validate_env`](Handler::validate_env), which promoted a system-address transaction: +/// a deposit-like transaction is a deposit by then. Every other transaction pays a fee its caller /// must hold, so it has an account already. -/// -/// The read loads the caller as op-revm's deduction then does: the transaction's caller starts -/// warm, so the read changes nothing the transaction pays. -fn deposit_creates_caller( - ctx: &mut MegaContext, -) -> Result { +fn deposit_created_caller( + ctx: &MegaContext, +) -> bool { if ctx.tx().tx_type() != DEPOSIT_TRANSACTION_TYPE { - return Ok(false); + return false; } let caller = ctx.tx().caller(); - Ok(ctx.journal_mut().load_account(caller)?.data.info.is_empty()) + ctx.journal_ref().state.get(&caller).is_some_and(|account| account.original_info().is_empty()) } /// Charges the state gas of the account a deposit-like transaction creates for its caller, as @@ -1216,127 +1596,73 @@ fn charge_created_caller( gas.record_state_cost(state_gas) } -/// Whether revm refuses to start the frame `input` asks for on what its caller's account holds: -/// a value the caller cannot fund, which revm answers with `OutOfFunds`, and a creation whose -/// creator's nonce cannot be bumped, which it answers with a `Return` and no address. revm checks -/// both before it moves or writes anything, so a start it refuses makes no write record and -/// journals no transfer log: it is charged nothing and counted nothing. -/// -/// A creation onto an occupied address is the one refusal not predicted. revm decides it on the -/// created address's account after the start is counted, and reading that account here would load -/// it, changing what the transaction has warmed. So the creation's records and transfer log are -/// counted, and a crossing they cause stops the creation before revm could refuse it; without a -/// crossing, revm's refusal fails the creation and its lane goes with it. -pub(crate) fn caller_refuses_start( - ctx: &MegaContext, - input: &FrameInput, -) -> bool { - match input { - FrameInput::Call(inputs) => { - inputs.transfers_value() && - caller_refuses(ctx, inputs.caller, inputs.call_value(), false) - } - FrameInput::Create(inputs) => caller_refuses(ctx, inputs.caller(), inputs.value(), true), - FrameInput::Empty => false, - } -} - -/// [`caller_refuses_start`] for the frame `input` asks for, as the opcode starting it — or, for the -/// transaction's own frame, the charge of its record before execution — already found it: nothing -/// between the two changes the caller's account, so a second lookup of it would give the same -/// answer. A debug build makes the lookup and asserts that it does. -/// -/// A start that moves no value and creates nothing is never refused there, and takes nothing. -#[inline] -fn start_refused( - ctx: &mut MegaContext, - input: &FrameInput, -) -> bool { - let refusable = match input { - FrameInput::Call(inputs) => inputs.transfers_value(), - FrameInput::Create(_) => true, - FrameInput::Empty => false, - }; - if !refusable { - return false; - } - let Some(refused) = ctx.additional_limit.take_start_refused() else { - return caller_refuses_start(ctx, input); - }; - debug_assert_eq!( - refused, - caller_refuses_start(ctx, input), - "the answer staged for a frame's start is the one its caller's account gives" - ); - refused -} - -/// Whether `caller`'s account refuses a frame start that moves `value` and, for a `creation`, -/// bumps its nonce: the balance revm's transfer checks, and the nonce revm's creation bumps. -/// -/// The account is read from the journal as it stands, without loading or warming anything, and it -/// is always there. A transaction's sender is loaded by validation, which also credits a deposit's -/// mint (`validate_against_state_and_deduct_caller`, revm's and op-revm's). Any other caller is the -/// account a running frame runs as, which revm loaded to start that frame: a call's target before -/// its value moves, a creation's address when it creates the account. -fn caller_refuses( - ctx: &MegaContext, - caller: Address, - value: U256, - creation: bool, -) -> bool { - let account = ctx.journal_ref().state.get(&caller); - debug_assert!(account.is_some(), "a frame's caller is loaded before the frame starts"); - account.is_some_and(|account| { - account.info.balance < value || (creation && account.info.nonce == u64::MAX) - }) -} - -/// Records the account writes of the EIP-7702 authorities applied since journal entry -/// `journal_i`, and answers how many there are: each applied authorization bumps its authority's +/// The account writes of the EIP-7702 authorities applied since journal entry `journal_i`, and the +/// accounts among them the application created: each applied authorization bumps its authority's /// nonce once, so the distinct authorities other than the sender are the accounts written. The /// sender's write is part of the transaction body. -fn record_applied_authorities( +/// +/// An authority the application created is one revm charged the account's state gas for: one +/// that was empty, loaded as not existing and untouched when the application reached it. Read +/// after the application, that is an authority the database answered no account for, empty at +/// the transaction's start, and touched first by the application — revm's flag of a touched +/// account outlives the transaction that set it on a journal that runs several, so an authority an +/// earlier transaction touched was touched before. Validation's bump of the sender comes first, +/// and never makes the sender a new account. +fn applied_authorities( ctx: &mut MegaContext, journal_i: usize, -) -> u64 { +) -> (u64, u64) { if ctx.tx().tx_type() != TransactionType::Eip7702 { - return 0; + return (0, 0); } let caller = ctx.tx().caller(); - let target = ctx.tx().kind().to().copied(); - let mut authorities: Vec
= ctx.journal_ref().journal()[journal_i..] - .iter() - .filter_map(|entry| match entry { - JournalEntry::NonceBump { address } if *address != caller => Some(*address), - _ => None, - }) - .collect(); + let mut authorities: Vec
= Vec::new(); + let mut touched: Vec
= Vec::new(); + for entry in &ctx.journal_ref().journal()[journal_i..] { + match entry { + JournalEntry::NonceBump { address } if *address != caller => authorities.push(*address), + JournalEntry::AccountTouched { address } => touched.push(*address), + _ => {} + } + } authorities.sort_unstable(); authorities.dedup(); - let target_is_authority = - target.is_some_and(|target| authorities.binary_search(&target).is_ok()); - let applied = authorities.len() as u64; - ctx.additional_limit.record_applied_authorities(caller, applied, target_is_authority); + touched.sort_unstable(); // An applied authority that is the block beneficiary wrote the beneficiary's account. if authorities.binary_search(&ctx.block().beneficiary).is_ok() { ctx.detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE); } - applied + let state = &ctx.journal_ref().state; + let created = authorities + .iter() + .filter(|authority| { + touched.binary_search(authority).is_ok() && + state.get(*authority).is_some_and(|account| { + account.is_loaded_as_not_existing() && account.original_info().is_empty() + }) + }) + .count(); + (authorities.len() as u64, created as u64) } /// Charges the history of the write records a transaction makes outside any frame: one per -/// applied authority, and the one its own frame makes — the recipient of its value, or the -/// account it creates. +/// applied authority, and the one its own frame makes — the recipient of its value, when the +/// value changes an account the transaction has not changed, or the account it creates. +/// +/// The recipient's record is predicted as the journal's state stands before the first frame +/// ([`Accounts::transfer_records`](crate::limit::Accounts)): a recipient that is the sender, or an +/// authority the transaction applied, is changed already, and gets none; the sender's side never +/// makes one, validation having changed its account. A creation's account is charged as a record, +/// as a `CREATE` opcode charges it; the transaction has changed no account but its sender before +/// its first frame, so the account it creates is one it had not changed. /// /// The authorities' records are the transaction's own and outlive a first frame that fails; the -/// first frame's record does not, so what it cost is kept for the settlement to give back, and -/// whether it makes one is left for that frame's lane to check its own count against. A first -/// frame revm refuses to start on its sender's account makes no record, and is charged none -/// ([`caller_refuses_start`]): among the transactions that pay history, that is a creation from an -/// account whose nonce cannot be bumped, which only a caller that turned the nonce check off can -/// run, and which revm answers with a success. The answer is left for the first frame's init, -/// which asks the same of the same account. +/// first frame's record does not, so what it cost is kept for that frame to carry as its start +/// charge, which its failure gives back. A first frame revm refuses to start on its sender's +/// account makes no record, and gets the charge back as any frame that kept nothing does: among +/// the transactions that pay history, that is a creation from an account whose nonce cannot be +/// bumped, which only a caller that turned the nonce check off can run, and which revm answers +/// with a success and no address. /// `false` when the transaction cannot pay, which is an out-of-gas before it runs. fn charge_records_made_outside_a_frame( ctx: &mut MegaContext, @@ -1347,25 +1673,20 @@ fn charge_records_made_outside_a_frame( return true; } let tx = ctx.tx(); - let writes_a_record = match tx.kind() { - TxKind::Create => true, + let first_frame = match tx.kind() { + TxKind::Create => 1, TxKind::Call(to) => { - !tx.value().is_zero() && - to != tx.caller() && - !ctx.additional_limit.target_is_authority() + let predicted = ctx.accounts().transfer_records(tx.caller(), to, tx.value()).transfer; + debug_assert_eq!(predicted.taken, 0, "the sender's value returns no account"); + predicted.added } }; - let (caller, value, creation) = (tx.caller(), tx.value(), tx.kind().is_create()); - let top_level_record = writes_a_record && { - let refused = caller_refuses(ctx, caller, value, creation); - ctx.additional_limit.stage_start_refused(refused); - !refused + let Some((first_frame, _)) = + charge_write_records_history(gas, first_frame, applied_authorities) + else { + return false; }; - let charged = - charge_write_records_history(gas, u64::from(top_level_record), applied_authorities); - let Some((top_level, _)) = charged else { return false }; - ctx.additional_limit.set_top_level_write_record_gas(top_level); - ctx.additional_limit.stage_top_level_records(u64::from(top_level_record)); + ctx.additional_limit.set_first_frame_charge(first_frame); true } @@ -1374,11 +1695,10 @@ mod tests { use super::*; use crate::{test_utils::MemoryDatabase, MegaSpecId}; use alloy_primitives::{address, U256}; - use revm::interpreter::{ - gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory, + use revm::{ + context_interface::journaled_state::account::JournaledAccountTr, + interpreter::{gas::WithheldCrossing, CallInput, CallInputs, CallValue, SharedMemory}, }; - #[cfg(debug_assertions)] - use revm::interpreter::{CreateInputs, CreateScheme}; use std::boxed::Box; const CALLER: Address = address!("00000000000000000000000000000000000e0001"); @@ -1399,23 +1719,21 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: true, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, })) } - /// A `CREATE` its opcode charged the created account for. - #[cfg(debug_assertions)] - fn creation() -> FrameInput { - let mut inputs = - CreateInputs::new(CALLER, CreateScheme::Create, U256::ZERO, Bytes::new(), 100_000, 0); - inputs.set_charged_create_state_gas(true); - inputs.set_charged_state_gas_address(TARGET); - FrameInput::Create(Box::new(inputs)) - } - /// A context whose transaction read the block environment before its first frame under a cap /// of `cap`, so a frame at depth 0 starts with an allowance of `cap`. fn detained(cap: u64) -> MegaContext { - let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); + detained_on(MemoryDatabase::default(), cap) + } + + /// [`detained`] over `db`. + fn detained_on(db: MemoryDatabase, cap: u64) -> MegaContext { + let mut ctx = MegaContext::new(db, MegaSpecId::SATIN); ctx.detention.reset(true, cap, cap); ctx.detention.mark_before_execution(VolatileDataAccess::TIMESTAMP); ctx @@ -1439,6 +1757,9 @@ mod tests { scheme: CallScheme::StaticCall, is_static: true, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } @@ -1451,9 +1772,8 @@ mod tests { dispatched: &PrecompilesMap, to: Address, forward: u64, - refused: bool, ) -> (PrecompileHold, u64) { - hold_input(cap, priced, dispatched, to, &[0; 32], forward, refused) + hold_input(cap, priced, dispatched, to, &[0; 32], forward) } /// [`hold`] for a call of `input`. @@ -1464,19 +1784,18 @@ mod tests { to: Address, input: &[u8], forward: u64, - refused: bool, ) -> (PrecompileHold, u64) { let ctx = detained(cap); let mut frame_init = static_call(to, input, forward); - let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init, refused); + let held = hold_precompile(&ctx, dispatched, priced, &mut frame_init); (held, input_gas_limit(&frame_init.frame_input)) } /// A precompile the engine prices is decided from its price before it runs: within the /// allowance, and past its whole forward, it runs on the forward as without the limit; past /// the allowance and within the forward, it is answered without running, out of gas and - /// marked as a crossing whose record is the forward. A call revm refuses on its caller's - /// account runs as without the limit. + /// marked as a crossing whose record is the forward. A value call its caller cannot fund, + /// which revm refuses before it runs the precompile, runs as without the limit. #[test] fn test_a_priced_precompile_is_decided_from_its_price() { const KZG: Address = crate::kzg_point_evaluation::ADDRESS; @@ -1484,27 +1803,46 @@ mod tests { let (priced, map) = (PricedPrecompiles::default(), crate::satin_precompiles_map()); // Within the allowance: runs on the forward. - let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE, false); + let (held, ran_on) = hold(PRICE, &priced, &map, KZG, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); // Past the allowance, within the forward: the crossing, without running. for forward in [PRICE, 3 * PRICE] { - let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, forward, false); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, forward); assert_eq!((held, ran_on), (PrecompileHold::Crossing, forward), "the input as it was"); } // Past the whole forward: a plain out-of-gas, run on the forward. - let (held, ran_on) = hold(PRICE / 2, &priced, &map, KZG, PRICE - 1, false); + let (held, ran_on) = hold(PRICE / 2, &priced, &map, KZG, PRICE - 1); assert_eq!((held, ran_on), (PrecompileHold::Unheld, PRICE - 1)); - // Refused on the caller's account: revm answers it without running the precompile. - let (held, ran_on) = hold(PRICE - 1, &priced, &map, KZG, 3 * PRICE, true); - assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); + // A value call past the allowance, within the forward: the crossing when its caller can + // fund the value; revm's refusal, without running the precompile, when it cannot. A + // `DELEGATECALL` moves nothing, whatever value it carries for its callee to read and + // whatever its caller holds: the crossing. + for (scheme, balance, held) in [ + (CallScheme::Call, 1_u64, PrecompileHold::Crossing), + (CallScheme::Call, 0, PrecompileHold::Unheld), + (CallScheme::DelegateCall, 0, PrecompileHold::Crossing), + ] { + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(balance)); + let mut ctx = detained_on(db, PRICE - 1); + ctx.journal_mut().load_account(CALLER).unwrap(); + let mut frame_init = static_call(KZG, &[0; 32], 3 * PRICE); + let FrameInput::Call(inputs) = &mut frame_init.frame_input else { unreachable!() }; + (inputs.scheme, inputs.is_static) = (scheme, false); + inputs.value = match scheme { + CallScheme::DelegateCall => CallValue::Apparent(U256::from(1)), + _ => CallValue::Transfer(U256::from(1)), + }; + let case = format!("{scheme:?} holding {balance}"); + assert_eq!(hold_precompile(&ctx, &map, &priced, &mut frame_init), held, "{case}"); + } // A forward within the allowance, and a call to anything but a precompile, run as they are. - let (held, ran_on) = hold(3 * PRICE, &priced, &map, KZG, 3 * PRICE, false); + let (held, ran_on) = hold(3 * PRICE, &priced, &map, KZG, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); - let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE, false); + let (held, ran_on) = hold(PRICE - 1, &priced, &map, TARGET, 3 * PRICE); assert_eq!((held, ran_on), (PrecompileHold::Unheld, 3 * PRICE)); } @@ -1542,9 +1880,8 @@ mod tests { for (precompile, pair, limit, price) in wrappers { let to = *precompile.address(); let two_pairs = std::vec![0; 2 * pair]; - let hold = |cap, input: &[u8], forward| { - hold_input(cap, &priced, &map, to, input, forward, false) - }; + let hold = + |cap, input: &[u8], forward| hold_input(cap, &priced, &map, to, input, forward); // Within the allowance: runs on the forward. assert_eq!(hold(price, &two_pairs, 3 * price), (PrecompileHold::Unheld, 3 * price)); @@ -1611,7 +1948,7 @@ mod tests { (&foreign, KZG), (&foreign, pairing), ] { - let (held, ran_on) = hold(1_000, priced, &map, to, 300_000, false); + let (held, ran_on) = hold(1_000, priced, &map, to, 300_000); let clamped = PrecompileHold::Clamped(NonZeroU64::new(299_000).unwrap()); assert_eq!(held, clamped, "{to}"); assert_eq!(ran_on, 1_000, "{to}: run on the allowance"); @@ -1630,7 +1967,7 @@ mod tests { ] { let case = format!("succeeded {succeeded}, now {result:?}"); let mut ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let start = journal_position(&mut ctx); + let start = mark(ctx.journal_mut()); // What the answer wrote: a bump of the recipient's nonce. let _ = ctx.journal_mut().load_account_mut(TARGET).unwrap().data.bump_nonce(); let answer = synthetic_frame_result(&value_call(), result, Bytes::new()); @@ -1640,74 +1977,77 @@ mod tests { } } - /// The guard trips on a transfer log the data size counted for a frame revm built and did not - /// journal. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the transfer log counted is the one revm journaled")] - fn test_a_transfer_log_counted_and_not_journaled_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (true, false, 0), None); - } - - /// The guard trips on a start revm refused on its caller's account that was not predicted, - /// which the data size would have counted. + /// One handler runs one transaction, and what a phase learns about it is kept on the handler: + /// the reservoir the transaction settled with is read where revm builds its result's gas and + /// reported once the result is built. A handler reused for a system call, whose path builds + /// no result gas and skips that read, reports the system call's own reservoir: the capture is + /// consumed by the report, and by the error path, which gives no report. A transaction below + /// the execution cap leaves a capture of nothing, one above it a capture of its own margin, and + /// a deposit that halts a capture its failed-deposit result never reports; after each, a + /// system call on revm's default gas limit reports the margin above the system-call budget. #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the start revm refused is the one predicted")] - fn test_a_refusal_not_predicted_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - let unfunded = - synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&unfunded)); - } - - /// The guard trips on a start predicted refused that revm made, which the data size did not - /// count. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the start revm refused is the one predicted")] - fn test_a_predicted_refusal_revm_did_not_make_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (false, true, 0), None); - } - - /// The guard trips on a start revm answered past the call-stack limit, which the depth guard - /// answers before revm sees it, for a creation and a call alike. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "the depth guard answers every start past the call-stack limit")] - fn test_a_start_revm_answered_past_the_depth_limit_trips() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - for input in [creation(), value_call()] { - let too_deep = - synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); - assert_start_as_counted(&ctx, (false, false, 0), Some(&too_deep)); + fn test_a_reused_handler_reports_each_executions_own_reservoir() { + use crate::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{op_transaction, zero_fee_l1_block_info}, + MegaTransaction, SYSTEM_CALL_REGULAR_GAS_LIMIT, + }; + use alloy_op_evm::OpTx; + use revm::{ + context::{ContextSetters, TxEnv}, + handler::{system_call::SYSTEM_CALL_GAS_LIMIT, SystemCallTx}, + inspector::NoOpInspector, + }; + const HALTS: Address = address!("00000000000000000000000000000000000e0003"); + const DEFAULT_RESERVOIR: u64 = SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT; + + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(TARGET, Bytes::new()) + .account_code(HALTS, Bytes::from_static(&[revm::bytecode::opcode::INVALID])); + let mut evm = MegaEvm::new( + MegaContext::new(db, MegaSpecId::SATIN).with_chain(zero_fee_l1_block_info()), + ); + let mut handler = MegaHandler::< + MegaEvm, + crate::MegaEvmError, + EthFrame, + >::new(); + let room = 100_000 + history_gas(crate::TX_BODY_SIZE).unwrap(); + let tx = |to: Address, gas_limit: u64, nonce: u64| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + nonce, + gas_limit, + kind: TxKind::Call(to), + ..Default::default() + })) + }; + let mut deposit = tx(HALTS, room, 0); + deposit.0.deposit.source_hash = alloy_primitives::B256::repeat_byte(0x11); + deposit.0.base.gas_price = 0; + + for (case, tx, succeeds) in [ + ("below the cap", tx(TARGET, room, 0), true), + ("above the cap", tx(TARGET, TX_GAS_LIMIT_CAP + 10_000_000, 1), true), + ("a halting deposit", deposit, false), + ] { + evm.inner.ctx.set_tx(tx); + let result = handler.run(&mut evm).expect(case); + assert_eq!(result.is_success(), succeeds, "{case}: {result:?}"); + let settled = evm.ctx().additional_limit().reservoir_remaining(); + assert_ne!(settled, DEFAULT_RESERVOIR, "{case}: the capture would show"); + + let call = MegaTransaction::new_system_tx_with_caller(CALLER, TARGET, Bytes::new()); + evm.inner.ctx.set_tx(call); + evm.inner.ctx.on_new_system_call(); + let result = handler.run_system_call(&mut evm).expect("the system call runs"); + assert!(result.is_success(), "{case}: {result:?}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + DEFAULT_RESERVOIR, + "{case}: the system call's own reservoir, not the capture" + ); } } - - /// The guard expects no log where nothing moved, whatever the input would count: a start - /// revm refuses on its caller's account, predicted — a value call it answers `OutOfFunds`, a - /// creation whose creator's nonce cannot be bumped, answered with a `Return` — and one it - /// fails otherwise — a creation onto an occupied address, a failing precompile; and none for - /// a frame nothing was counted for. - #[test] - #[cfg(debug_assertions)] - fn test_the_guard_expects_no_transfer_log_where_nothing_moved() { - let ctx = MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN); - assert_start_as_counted(&ctx, (false, false, 0), None); - let overflow = synthetic_frame_result(&creation(), InstructionResult::Return, Bytes::new()); - assert_start_as_counted(&ctx, (true, true, 0), Some(&overflow)); - let unfunded = - synthetic_frame_result(&value_call(), InstructionResult::OutOfFunds, Bytes::new()); - assert_start_as_counted(&ctx, (true, true, 0), Some(&unfunded)); - let collision = - synthetic_frame_result(&creation(), InstructionResult::CreateCollision, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&collision)); - let failed = - synthetic_frame_result(&value_call(), InstructionResult::PrecompileError, Bytes::new()); - assert_start_as_counted(&ctx, (true, false, 0), Some(&failed)); - let answered = synthetic_frame_result(&value_call(), InstructionResult::Stop, Bytes::new()); - assert_start_as_counted(&ctx, (false, false, 0), Some(&answered)); - } } diff --git a/crates/mega-evm/src/evm/factory.rs b/crates/mega-evm/src/evm/factory.rs index 32b7a45d9..827f9bf17 100644 --- a/crates/mega-evm/src/evm/factory.rs +++ b/crates/mega-evm/src/evm/factory.rs @@ -365,13 +365,15 @@ mod tests { .tx_runtime_limits .with_tx_data_size_limit(crate::TX_BODY_SIZE + 40); let stopped = run(&MegaEvmFactory::new().with_tx_runtime_limits(one_record)); + // The second record crosses the transaction's own frame's budget, the record the body + // leaves of the limit, which is named. assert_eq!( stopped.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: crate::TX_BODY_SIZE + 40, - used: crate::TX_BODY_SIZE + 2 * 40, - frame_local: false, + limit: 40, + used: 2 * 40, + frame_local: true, }) ); diff --git a/crates/mega-evm/src/evm/frame.rs b/crates/mega-evm/src/evm/frame.rs index f26b53696..e2dc505d1 100644 --- a/crates/mega-evm/src/evm/frame.rs +++ b/crates/mega-evm/src/evm/frame.rs @@ -1,28 +1,28 @@ -//! Frame results built without running a frame, and how they settle. +//! Frame results built without running a frame. //! //! `MegaETH` answers some frames itself: the depth guard, a transaction stopped by a limit, the //! system contract interceptors, a `keylessDeploy` call carrying value, and a precompile call gas //! detention answers from its price without running it. Such a result goes back to the caller like -//! any frame's, and the caller settles it the way revm settles a frame it ran: +//! any frame's, through revm's own frame return, which settles it as a frame revm ran: //! //! 1. an upfront state-gas charge the calling opcode made for the frame (a new account, a creation) //! is priced for refund when the frame failed; -//! 2. [`handle_reservoir_remaining_gas`] merges the frame's gas into the caller's: unused regular -//! gas back on success and revert, the frame's reservoir adopted as the caller's own; -//! 3. the refund is refilled into the caller's reservoir. +//! 2. the frame's gas merges into the caller's: unused regular gas back on success and revert, the +//! frame's reservoir added to what the caller kept, and the frame's pools absorbed into the +//! caller's; +//! 3. the refund is refilled into the caller's reservoir, and the start charge the frame carries — +//! what its caller paid for the records its start makes — is given back when it failed. //! //! The contract for a synthetic result is that it settles exactly like revm's own: its gas carries -//! the reservoir the frame inherited ([`untouched_call_gas`], [`with_pools_of`]), never -//! `Gas::new(limit)`, which would carry none and bill the sender for the whole reservoir; and it -//! carries the calling opcode's upfront-charge flags, so step 1 refunds the charge. -//! [`synthetic_frame_result`] builds one; [`settle_frame_result`] is that settlement, for a caller -//! that settles a result into its own gas outside revm's frame return. +//! the reservoir and the shares of the pools the frame inherited ([`untouched_call_gas`], +//! [`untouched_create_gas`]), never `Gas::new(limit)`, which would carry no reservoir and +//! unlimited pools, billing the sender for the whole reservoir and lifting the caller's budgets; +//! and it carries the calling opcode's upfront-charge flags and start charge, so step 1 and step 3 +//! refund them. [`synthetic_frame_result`] builds one. use alloy_primitives::Bytes; use revm::{ - context::{result::FromStringError, ContextTr}, - context_interface::{cfg::gas::GasTracker, context::take_error, Host}, - handler::{handle_reservoir_remaining_gas, FrameResult}, + handler::FrameResult, interpreter::{ CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Gas, InstructionResult, InterpreterResult, @@ -30,39 +30,29 @@ use revm::{ }; /// The gas of a call result built without running the callee: the call's whole gas limit -/// unspent, and the reservoir the call inherited. +/// unspent, the reservoir the call inherited, and the shares of its caller's pools it was given, +/// undrawn. #[inline] pub const fn untouched_call_gas(inputs: &CallInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir) + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares); + gas } /// The gas of a creation result built without running the init code: its whole gas limit -/// unspent, and the reservoir the creation inherited. +/// unspent, the reservoir the creation inherited, and the shares of its creator's pools it was +/// given, undrawn. #[inline] -pub fn untouched_create_gas(inputs: &CreateInputs) -> Gas { - Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()) -} - -/// `gas_limit` of fresh regular gas carrying `source`'s EIP-8037 pools: its reservoir, the state -/// and history gas it charged, and the part of those charges that spilled onto regular gas. -/// -/// For a result whose regular gas is rebuilt (a precompile's output normalised to the gas limit -/// the caller forwarded): the caller keeps the frame's state and history charges on success and -/// rolls them back on failure, so a rebuilt `Gas` that dropped them would hand the caller an -/// empty reservoir and charges the frame never made. -#[inline] -pub const fn with_pools_of(gas_limit: u64, source: &Gas) -> Gas { - let mut gas = Gas::new(gas_limit); - gas.set_reservoir(source.reservoir()); - gas.set_state_gas_spent(source.state_gas_spent()); - gas.set_state_gas_spilled(source.state_gas_spilled()); - gas.set_history_gas_spent(source.history_gas_spent()); +pub const fn untouched_create_gas(inputs: &CreateInputs) -> Gas { + let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit(), inputs.reservoir()); + gas.tracker_mut().set_pools_remaining(inputs.pool_shares()); gas } /// A result for the frame `input` would start, built without running it: `result` with -/// `output`, the frame's gas untouched and the inherited reservoir carried, and the calling -/// opcode's upfront state-gas flags, as revm builds the results of the frames it answers itself. +/// `output`, the frame's gas untouched, the inherited reservoir and pool shares carried, and the +/// calling opcode's upfront state-gas flags and start charge, as revm builds the results of the +/// frames it answers itself. pub fn synthetic_frame_result( input: &FrameInput, result: InstructionResult, @@ -75,6 +65,7 @@ pub fn synthetic_frame_result( address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: inputs.charged_start(), }), FrameInput::Empty => unreachable!("a frame input always names a call or a creation"), } @@ -95,48 +86,15 @@ pub fn synthetic_call_result( precompile_call_logs: Default::default(), charged_new_account_state_gas: inputs.charged_new_account_state_gas, charged_state_gas_address: inputs.target_address, + charged_start: inputs.charged_start, }) } -/// Settles `result`'s gas into `caller_gas` exactly as revm's frame return does: the calling -/// opcode's upfront state-gas charge priced for refund, [`handle_reservoir_remaining_gas`], then -/// the refund refilled into the caller's reservoir. -/// -/// `ctx` prices the refund through the same hook the charge went through; a failed lookup is -/// the error the hook recorded. -pub fn settle_frame_result( - ctx: &mut CTX, - caller_gas: &mut GasTracker, - result: &mut FrameResult, -) -> Result<(), ERROR> -where - CTX: ContextTr + Host, - ERROR: From<::Error> + FromStringError, -{ - take_error::(ctx.error())?; - let refund = match result.refundable_state_gas_charge() { - Some(charge) => match ctx.state_gas_charge(charge) { - Some(refund) => Some(refund), - None => { - take_error::(ctx.error())?; - return Err(ERROR::from_string("state gas price lookup failed".into())); - } - }, - None => None, - }; - let instruction_result = result.instruction_result(); - handle_reservoir_remaining_gas(instruction_result, caller_gas, result.gas_mut().tracker_mut()); - if let Some(refund) = refund { - caller_gas.refill_reservoir(refund); - } - Ok(()) -} - #[cfg(test)] mod tests { use super::*; use alloy_primitives::{address, Address, U256}; - use revm::interpreter::{CallInput, CallScheme, CallValue}; + use revm::interpreter::{CallInput, CallScheme, CallValue, PoolAmounts}; const TARGET: Address = address!("0000000000000000000000000000000000001234"); @@ -154,6 +112,9 @@ mod tests { is_static: false, reservoir, charged_new_account_state_gas: charged, + charged_start: Default::default(), + pool_shares: PoolAmounts::UNLIMITED, + history_allowance: 0, } } @@ -168,21 +129,6 @@ mod tests { assert_ne!(gas, Gas::new(50_000)); } - /// Rebuilding the regular gas keeps every EIP-8037 pool of the source. - #[test] - fn test_with_pools_of_keeps_the_pools() { - let mut source = Gas::new_with_regular_gas_and_reservoir(100, 1_000); - assert!(source.record_state_cost(1_050)); - assert!(source.record_history_cost(20)); - let rebuilt = with_pools_of(70, &source); - assert_eq!(rebuilt.limit(), 70); - assert_eq!(rebuilt.remaining(), 70); - assert_eq!(rebuilt.reservoir(), source.reservoir()); - assert_eq!(rebuilt.state_gas_spent(), 1_050); - assert_eq!(rebuilt.state_gas_spilled(), source.state_gas_spilled()); - assert_eq!(rebuilt.history_gas_spent(), 20); - } - /// A synthetic call result carries the return range, the untouched gas and the upfront /// charge flags of its inputs. #[test] @@ -203,57 +149,4 @@ mod tests { assert_eq!(outcome.charged_state_gas_address, TARGET); assert!(!outcome.was_precompile_called); } - - /// Settling a failed synthetic call into its caller returns the forwarded gas, keeps the - /// caller's reservoir, and refunds the new-account charge the calling opcode made, as revm's - /// frame return does. - #[test] - fn test_settle_frame_result_refunds_the_upfront_charge() { - use revm::{ - context::{CfgEnv, Context}, - context_interface::cfg::{GasId, GasParams}, - database::EmptyDB, - primitives::hardfork::SpecId, - MainContext, - }; - let mut cfg = CfgEnv::new_with_spec(SpecId::AMSTERDAM); - cfg.enable_amsterdam_eip8037 = true; - cfg.gas_params = GasParams::new_spec(SpecId::AMSTERDAM); - let new_account = cfg.gas_params.get(GasId::new_account_state_gas()); - assert!(new_account > 0); - let mut ctx = Context::mainnet().with_db(EmptyDB::default()).with_cfg(cfg); - - // The caller forwarded 9,000 gas and charged a new account from its 1M reservoir. - let reservoir = 1_000_000; - let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); - assert!(caller.record_state_cost(new_account)); - let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); - let mut result = - synthetic_frame_result(&input, InstructionResult::CallTooDeep, Bytes::new()); - - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .unwrap(); - assert_eq!(caller.remaining(), 100_000, "the forwarded gas comes back"); - assert_eq!(caller.reservoir(), reservoir, "the charge is refunded to the reservoir"); - assert_eq!(caller.state_gas_spent(), 0); - - // A successful synthetic result keeps the charge: the account exists. - let mut caller = GasTracker::new(100_000, 100_000 - 9_000, reservoir); - assert!(caller.record_state_cost(new_account)); - let input = FrameInput::Call(Box::new(call_inputs(9_000, caller.reservoir(), true))); - let mut result = synthetic_frame_result(&input, InstructionResult::Stop, Bytes::new()); - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .unwrap(); - assert_eq!(caller.remaining(), 100_000); - assert_eq!(caller.reservoir(), reservoir - new_account); - assert_eq!(caller.state_gas_spent(), new_account as i64); - } } diff --git a/crates/mega-evm/src/evm/history.rs b/crates/mega-evm/src/evm/history.rs index fbf3be94a..d02b7f7d4 100644 --- a/crates/mega-evm/src/evm/history.rs +++ b/crates/mega-evm/src/evm/history.rs @@ -61,22 +61,22 @@ pub(crate) fn charge_write_records_history( /// The history bytes the allowance of a value-transferring call covers: one three-topic event /// carrying a single word, which is what a `receive()` hook emits. -pub const STORAGE_CALL_STIPEND_BYTES: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; +pub const HISTORY_ALLOWANCE_BYTES: u64 = LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32; /// The history allowance a value-transferring `CALL` or `CALLCODE` grants the frame it starts. /// /// EVM's own `CALL_STIPEND` buys the recipient of a transfer enough computation to notice it; on /// a chain that prices the bytes a log appends it buys no log at all, so a `receive()` hook that /// emits an event would be unreachable through `transfer()`. The allowance is that stipend's -/// counterpart on the history ledger: [`STORAGE_CALL_STIPEND_BYTES`] at the cost per history +/// counterpart on the history ledger: [`HISTORY_ALLOWANCE_BYTES`] at the cost per history /// byte, enough for one event and nothing else. /// /// It is separate from the frame's gas in every sense. It never enters the frame's `Gas`, so no /// settlement can hand it back as gas; it pays history charges and only those, so it cannot buy /// computation or a write record; and what it pays for appears on no ledger, because no pool of /// the transaction's gas paid it. -pub fn storage_call_stipend() -> u64 { - history_gas(STORAGE_CALL_STIPEND_BYTES).unwrap_or(u64::MAX) +pub fn history_allowance_gas() -> u64 { + history_gas(HISTORY_ALLOWANCE_BYTES).unwrap_or(u64::MAX) } /// The data-size bytes of `tx`'s body: the fixed body, the calldata, one record per EIP-7702 @@ -152,10 +152,10 @@ mod tests { if runs_at_measurement_prices() { return; } - assert_eq!(STORAGE_CALL_STIPEND_BYTES, log_history_bytes(3, 32)); - assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); - assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); - assert_eq!(storage_call_stipend(), history_gas(log_history_bytes(3, 32)).unwrap()); + assert_eq!(HISTORY_ALLOWANCE_BYTES, log_history_bytes(3, 32)); + assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); + assert_eq!(history_allowance_gas(), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(history_allowance_gas(), history_gas(log_history_bytes(3, 32)).unwrap()); } /// Every way a transaction moves value, as a name, a database, the transaction at a gas limit diff --git a/crates/mega-evm/src/evm/host.rs b/crates/mega-evm/src/evm/host.rs index cade09497..dc40bdfa2 100644 --- a/crates/mega-evm/src/evm/host.rs +++ b/crates/mega-evm/src/evm/host.rs @@ -1,16 +1,17 @@ //! The Host of the Satin engine. //! -//! # The Host only observes +//! # Writes are counted once their opcode completed //! -//! revm hands the Host the facts of every state-writing opcode: an `SSTORE`'s original, present and -//! new values, a log's topics and data, a `SELFDESTRUCT`'s balance and beneficiary. The Host -//! stages them ([`AdditionalLimit::stage_record`](crate::AdditionalLimit)) and records nothing. -//! The opcode's wrapper commits the staged record after the opcode completed, and charges the -//! frame the history the record costs; it discards the record, and charges nothing, when the -//! opcode failed. Recording in the Host would count a write the opcode's own failure then takes -//! back: `SSTORE` charges its dynamic gas after the Host call, and an out-of-gas there halts the -//! frame with the record already counted — and would have charged the frame for a byte the chain -//! never carries. +//! revm hands the Host the facts of every state-writing opcode twice: as it makes the write (an +//! `SSTORE`'s slot, a log, a `SELFDESTRUCT`'s beneficiary), and once the opcode completed, in the +//! completed-write hook ([`write_completed`](revm::context_interface::Host::write_completed)), +//! after every charge the opcode makes. The Host counts nothing in the first: the write methods +//! only write, whoever calls them. The hook commits the write's record to the running frame, holds +//! it to the limits and charges the frame the history the record costs. Counting at the write +//! would count one the opcode's own failure then takes back: `SSTORE` charges its dynamic gas after +//! the write, and an out-of-gas there halts the frame with the record already counted — and would +//! have charged the frame for a byte the chain never carries. A tool's write through the Host, an +//! inspector's log among them, reaches no hook, and is not counted. //! //! `block_hash` serves the read and records it, so a stateless witness learns of a `BLOCKHASH` //! that bypassed the journal. @@ -51,7 +52,20 @@ //! through this hook. A frame that fails instead rolls its own charges back by the amounts it //! recorded while running, without asking for a price at all. Both cancel exactly, for different //! reasons: the re-priced sites because the multiplier of a bucket is read once per transaction, -//! the rolled-back amounts because nothing but this hook priced them in the first place. +//! the rolled-back amounts because nothing but this hook priced them in the first place. The one +//! exception is an inspector's: a call's upfront charge is given back for the account its frame's +//! inputs name, as revm reads it, so an inspector that rewrites the target has it priced there. +//! +//! A charge on an account created in the transaction and destroyed since is priced at nothing: +//! its destruction gave back what the transaction had charged for it, at the prices charged and +//! outside that rule, so a re-pricing after the mark gives nothing back a second time, and the +//! account keeps no further state gas. +//! +//! The destruction gives the account's leaf back only when no account stood at the address at the +//! transaction's start: the database answered none for it, `None` from +//! [`Database::basic`](revm::Database::basic), or an earlier transaction on the same journal +//! destroyed it. A database that answers an empty account for an address it holds none for gives +//! that leaf back to no destruction: an empty account is a leaf the state holds. //! //! Every other Host method delegates to op-revm's context. @@ -63,9 +77,12 @@ use delegate::delegate; use revm::{ context::ContextTr, context_interface::{ - cfg::{GasId, GasParams, StateGasSite}, + cfg::{ + gas::{GasTracker, PoolAmounts, StartCharge}, + GasId, GasParams, StateGasCharge, StateGasSite, + }, context::{ContextError, SStoreResult, SelfDestructResult, StateLoad}, - host::LoadError, + host::{CompletedWrite, FrameStart, LoadError, WriteVerdict}, journaled_state::AccountInfoLoad, }, primitives::{Address, Log, StorageKey, StorageValue, B256, U256}, @@ -73,8 +90,10 @@ use revm::{ }; use crate::{ - system::ORACLE_CONTRACT_ADDRESS, ExternalEnvTypes, MegaContext, OracleEnv, StagedRecord, - VolatileDataAccess, + charge_write_records_history, history_gas, + limit::{DestroyedParts, HistoryBytes}, + system::ORACLE_CONTRACT_ADDRESS, + ExternalEnvTypes, MegaContext, OracleEnv, VolatileDataAccess, }; impl revm::context_interface::Host @@ -93,6 +112,22 @@ impl revm::context_interface::Host fn is_amsterdam_eip8037_enabled(&self) -> bool; fn tstore(&mut self, address: Address, key: StorageKey, value: StorageValue); fn tload(&mut self, address: Address, key: StorageKey) -> StorageValue; + // A write is counted once its opcode completed, in `write_completed`: what the Host's + // write methods are called with, by an opcode or by a tool, counts nothing. + fn sstore( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + ) -> Option>; + fn sstore_skip_cold_load( + &mut self, + address: Address, + key: StorageKey, + value: StorageValue, + skip_cold_load: bool, + ) -> Result, LoadError>; + fn log(&mut self, log: Log); } } @@ -175,7 +210,10 @@ impl revm::context_interface::Host self.inner.sload_skip_cold_load(address, key, skip_cold_load) } - /// Loads the account, marking a read of the block beneficiary's. + /// Loads the account, marking a read of the block beneficiary's, or refusing it in a frame + /// whose volatile-data access is off, when the load is a read: when an opcode's read wrapper + /// makes it. `CREATE`'s and `CREATE2`'s loads of their creator and of the created address are + /// no reads (see [`Detention`](crate::Detention)). #[inline] fn load_account_info_skip_cold_load( &mut self, @@ -197,42 +235,23 @@ impl revm::context_interface::Host /// Prices one EIP-8037 state gas unit, scaling the schedule's entry by the SALT bucket /// capacity of the account — or, for a slot-scoped entry, of the storage slot — the charge - /// lands on. - /// - /// `state gas = schedule entry x m`, where `m` is the bucket's capacity in minimum buckets. - /// A charge in a minimum-capacity bucket pays the schedule's own number, and a charge in a - /// bucket eight times as large pays eight times as much: state that crowds a region of the - /// trie costs what it makes everyone else pay to carry it. Only the state dimension scales; - /// regular gas is never touched by `m`. + /// lands on ([`priced_state_gas`](MegaContext::priced_state_gas)). /// - /// Two charges are priced without reading SALT at all: an entry the schedule prices at zero, - /// which `m` cannot move off zero, and every charge of a system-originated transaction, - /// which prices at the minimum bucket by rule (see - /// [`is_system_originated`](crate::MegaContext::is_system_originated)). + /// A charge on an account created in the transaction and destroyed since is priced at + /// nothing: from that mark until the transaction ends the account keeps no further state gas, + /// so an `SSTORE` of one of its slots neither charges nor refills fresh-slot state gas, and + /// code its own constructor deposits after destroying it is charged no state gas, whatever gas + /// the frame holds. The destruction gave back what the transaction had charged for the + /// account at the prices charged, outside this rule. The neutral configuration prices as the + /// fixture's fork does ([`destruction_table_prices_state_gas`]). /// - /// Reporting nothing is how a failed capacity lookup travels: the cause is recorded in the - /// context error the way [`Host::sload`](revm::context_interface::Host::sload) records a - /// database failure, and the charge site turns it into a bail-out that the transaction - /// surfaces as an error. A price the engine could not look up is never replaced by one - /// nobody chose. + /// [`destruction_table_prices_state_gas`]: MegaContext::destruction_table_prices_state_gas #[inline] fn state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option { - let base = self.inner.cfg.gas_params.get(id); - if base == 0 || self.is_system_originated() { - return Some(base); - } - let multiplier = match site.slot { - Some(slot) => self.slot_bucket_multiplier(site.address, slot), - None => self.account_bucket_multiplier(site.address), - }; - match multiplier { - Ok(multiplier) => Some(base.saturating_mul(multiplier)), - Err(error) => { - *self.error() = - Err(ContextError::Custom(format!("SALT bucket lookup failed: {error}"))); - None - } + if self.destruction_table_prices_state_gas() && self.accounts().is_destroyed(site.address) { + return Some(0); } + self.priced_state_gas(id, site) } /// Serves the hash and records that this block read it. @@ -249,46 +268,8 @@ impl revm::context_interface::Host Some(hash) } - /// Writes the slot and stages the write's values. - #[inline] - fn sstore_skip_cold_load( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - skip_cold_load: bool, - ) -> Result, LoadError> { - let load = self.inner.sstore_skip_cold_load(address, key, value, skip_cold_load)?; - self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); - Ok(load) - } - - /// Writes the slot and stages the write's values. - #[inline] - fn sstore( - &mut self, - address: Address, - key: StorageKey, - value: StorageValue, - ) -> Option> { - let load = self.inner.sstore(address, key, value)?; - self.additional_limit.stage_record(StagedRecord::Sstore(load.data.clone())); - Some(load) - } - - /// Stages the log's topic count and data length, then appends it. - #[inline] - fn log(&mut self, log: Log) { - self.additional_limit.stage_record(StagedRecord::Log { - topics: log.topics().len() as u8, - data_len: log.data.data.len() as u64, - }); - self.inner.log(log); - } - - /// Destructs the account and stages whether value moved and where to, marking a read of the - /// block beneficiary's account when it is either end: the source's balance is read and - /// cleared, the target's read and credited. + /// Destructs the account, marking a read of the block beneficiary's account when it is either + /// end: the source's balance is read and cleared, the target's read and credited. #[inline] fn selfdestruct( &mut self, @@ -305,16 +286,220 @@ impl revm::context_interface::Host if volatile { self.detention.observe(VolatileDataAccess::BENEFICIARY_BALANCE); } - self.additional_limit.stage_record(StagedRecord::SelfDestruct { - had_value: load.data.had_value, - to_other_account: target != address, - beneficiary: target, - }); Ok(load) } + + /// Counts the record of a write an opcode completed on the running frame's pool, holds it to + /// the limits, and charges the frame the history it costs. revm calls it at the end of + /// `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT`, after every charge the opcode makes, so a write + /// the opcode's own failure takes back is never counted. + /// + /// The record is held to the limits first, and only then is its history charged: a record the + /// limit rejects is not kept, so its history is no charge, and the stop is what the frame + /// reports — a revert whose output is the stop's + /// [`MegaLimitExceeded`](crate::MegaLimitExceeded), on the frame's gas, so its caller resumes + /// as after any revert. A record the limit accepts is charged, and a charge the frame cannot + /// pay, or a byte count with no price, is an ordinary out-of-gas. + /// + /// A log's history is drawn from the frame's history allowance first, and the frame's gas pays + /// the rest ([`history_allowance_gas`](crate::history_allowance_gas)): a write record is the + /// frame's own to pay for, and a record taken back — a slot written back to its original + /// value, an account a `SELFDESTRUCT` returns to what the transaction loaded — gives back what + /// the frame's gas paid, never what an allowance did. Both sides are priced the same way, so a + /// record taken back cancels its own charge exactly, whichever frame made it: a refill below + /// zero is reconciled when the frame merges into its caller. A write that takes records back + /// and makes others is refilled before it is charged, so what it nets to nothing costs + /// nothing. + /// + /// The first effective `SELFDESTRUCT` of an account created in the transaction gives back every + /// part of it the transaction made ([`DestroyedParts`]) to the destroying frame, whichever + /// frame paid: what the parts take back is in the same check as what the operation adds, so + /// the positive effects are held after the give-back; once the check passed, each part's + /// state gas is refilled at the price it was charged, with the history of its records and of + /// its code, before the operation's own records are charged. From that mark an `SSTORE` of + /// one of the account's slots counts nothing, and the pricing hook prices its state gas at + /// nothing ([`state_gas_price`](revm::context_interface::Host::state_gas_price)). + /// + /// A completed `SSTORE` holds the frame to the compute limit again: a slot restored to its + /// original value refills the state gas (revm, before this hook) and the history gas (here) + /// that spilled onto regular gas, and the spill may predate the limit. + #[inline] + fn write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict { + let (from_allowance, holds_again) = match write { + CompletedWrite::Sstore { .. } => (false, true), + CompletedWrite::Log { .. } => (true, false), + CompletedWrite::SelfDestruct { .. } => (false, false), + }; + let (counted, history, destroyed) = self.accounts().write_counted(&write); + let check = self.additional_limit.draw(gas, &counted); + if check.exceeded_limit() { + return WriteVerdict::Revert(self.additional_limit.note_frame_stop(&check)); + } + let state_given_back = match write { + CompletedWrite::SelfDestruct { address, .. } => destroyed + .as_ref() + .is_none_or(|parts| self.refill_destroyed_parts(address, parts, gas)), + CompletedWrite::Sstore { .. } | CompletedWrite::Log { .. } => true, + }; + if !state_given_back { + return WriteVerdict::OutOfGas; + } + if self.prices_history() { + let HistoryBytes { appended, taken } = history; + if taken != 0 { + gas.refill_history(history_gas(taken).unwrap_or(0)); + } + if let Some(parts) = &destroyed { + let code = usize::try_from(parts.code).unwrap_or(usize::MAX); + gas.refill_history(self.inner.cfg.gas_params.code_deposit_history_gas(code)); + } + if appended != 0 { + let Some(cost) = history_gas(appended) else { return WriteVerdict::OutOfGas }; + let cost = if from_allowance { gas.draw_history_allowance(cost) } else { cost }; + if !gas.record_history_cost(cost) { + return WriteVerdict::OutOfGas; + } + } + } + if holds_again { + self.detention.hold(gas); + } + WriteVerdict::Continue + } + + /// Charges the running frame the history of the write records the frame it is starting makes + /// — the accounts a value transfer changes from what the transaction loaded, a creation's + /// created account when the transaction had not changed it, and its creator's nonce — as the + /// journal's state stands ([`Accounts::start_records`](crate::limit::Accounts)). revm calls it + /// at `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2`, once the opcode + /// made every charge and took the gas it forwards, and before it builds the frame's input. + /// + /// It is a price, made at the opcode as revm charges a new account's gas at `CALL`, and counts + /// nothing: the records themselves are counted once revm decided the start, the frame's on the + /// pool it starts with and the creator's on the creator once the creation returned. + /// + /// The charge comes out of what the caller kept rather than out of what the callee gets, so + /// the frame's allowance is free for what the recipient does. What the frame's own records + /// cost is declared on the start ([`FrameStart::charge`]), which the fork carries on the + /// frame's input and gives back to the caller when the frame fails; the creator's record + /// outlives the creation and is not declared. The frame's input copies the caller's + /// reservoir after the charge, so the frame, or the answer revm gives in its place, + /// inherits the reservoir the charge left. An opcode that starts no frame — a creation the + /// balance, the nonce or the depth refuses, an out-of-gas before the forward — never calls + /// it, and makes no records; with EIP-8037 off, such a creation calls it without the address + /// it would take, which makes none either. A start revm then refuses — a value the caller + /// cannot fund, a frame past the call-stack limit — makes no records, and the charge comes + /// back when it returns, as does what a frame that ran did not keep. + /// + /// A charge the caller cannot pay, or a price that does not fit in a `u64`, fails the opcode + /// with an out-of-gas and starts no frame, even where revm would have refused the start. The + /// gas the opcode forwarded goes back to the caller first, so the halt burns it with the rest: + /// the frame never ran, and gas detention must not count the forward as compute. The halt's + /// record of what the frame had, which detention reads where the frame ends, is written again + /// once the forward is back: a failed charge recorded the gas left after the forward was + /// taken, and a price that could not be computed failed before any charge. + #[inline] + fn frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool { + let charge = if self.prices_history() { + let records = + self.accounts().start_records(start.kind, start.caller, start.target, start.value); + let on_frame = records.on_frame().added; + let creator = u64::from(records.creator); + let Some((charge, _)) = charge_write_records_history(gas, on_frame, creator) else { + gas.erase_cost(start.forward); + gas.set_failed_charge_remaining(Some(gas.remaining())); + return false; + }; + charge + } else { + 0 + }; + start.charge = StartCharge::new(charge, PoolAmounts::ZERO); + true + } } impl MegaContext { + /// Prices one EIP-8037 state gas unit `id` at `site`, scaling the schedule's entry by the SALT + /// bucket capacity of the account — or, for a slot-scoped entry, of the storage slot — the + /// charge lands on. + /// + /// `state gas = schedule entry x m`, where `m` is the bucket's capacity in minimum buckets. + /// A charge in a minimum-capacity bucket pays the schedule's own number, and a charge in a + /// bucket eight times as large pays eight times as much: state that crowds a region of the + /// trie costs what it makes everyone else pay to carry it. Only the state dimension scales; + /// regular gas is never touched by `m`. + /// + /// Two charges are priced without reading SALT at all: an entry the schedule prices at zero, + /// which `m` cannot move off zero, and every charge of a system-originated transaction, + /// which prices at the minimum bucket by rule (see + /// [`is_system_originated`](crate::MegaContext::is_system_originated)). + /// + /// Reporting nothing is how a failed capacity lookup travels: the cause is recorded in the + /// context error the way [`Host::sload`](revm::context_interface::Host::sload) records a + /// database failure, and the charge site turns it into a bail-out that the transaction + /// surfaces as an error. A price the engine could not look up is never replaced by one + /// nobody chose. + fn priced_state_gas(&mut self, id: GasId, site: StateGasSite) -> Option { + let base = self.inner.cfg.gas_params.get(id); + if base == 0 || self.is_system_originated() { + return Some(base); + } + let multiplier = match site.slot { + Some(slot) => self.slot_bucket_multiplier(site.address, slot), + None => self.account_bucket_multiplier(site.address), + }; + match multiplier { + Ok(multiplier) => Some(base.saturating_mul(multiplier)), + Err(error) => { + *self.error() = + Err(ContextError::Custom(format!("SALT bucket lookup failed: {error}"))); + None + } + } + } + + /// Refills on `gas`, the destroying frame's, the state gas of the `parts` of the account at + /// `address` its first effective destruction gives back, each at the price it was charged: + /// the leaf's new account, the code deposit's bytes and each slot made non-zero, priced at the + /// site the charge landed on, so SALT gives back what it scaled. The leaf was charged once as a + /// new account, by whichever site made it — a value transfer, a `SELFDESTRUCT`'s balance, the + /// transaction's value, or the creation itself — and every such charge is the same entry. The + /// account is destroyed by now, which the pricing hook prices at nothing, so the parts are + /// priced as they were charged, before the mark ([`priced_state_gas`](Self::priced_state_gas)). + /// + /// Nothing is refilled where the transaction's state gas is not the spec's: the neutral + /// configuration prices as the fixture's fork does, and EIP-8037 gives back nothing for this + /// destruction. `false` when a price could not be looked up, whose cause is recorded and fails + /// the transaction. + fn refill_destroyed_parts( + &mut self, + address: Address, + parts: &DestroyedParts, + gas: &mut GasTracker, + ) -> bool { + if !self.destruction_table_prices_state_gas() { + return true; + } + debug_assert_eq!( + self.inner.cfg.gas_params.get(GasId::new_account_state_gas()), + self.inner.cfg.gas_params.get(GasId::create_state_gas()), + "a leaf a creation charged comes back at the price of one a transfer charged" + ); + let account = StateGasSite::account(address); + let leaf = parts.leaf.then(|| StateGasCharge::one(GasId::new_account_state_gas(), account)); + let code = (parts.code != 0) + .then(|| StateGasCharge::units(GasId::code_deposit_state_gas(), account, parts.code)); + let slots = parts.slots.iter().map(|&key| { + StateGasCharge::one(GasId::sstore_set_state_gas(), StateGasSite::slot(address, key)) + }); + for charge in leaf.into_iter().chain(code).chain(slots) { + let Some(price) = self.priced_state_gas(charge.id, charge.site) else { return false }; + gas.refill_reservoir(charge.total(price)); + } + true + } + /// Reads the block-environment field `access` stands for: `false` when the read is refused, /// and the accessor answers zero instead of the field. #[inline] @@ -395,11 +580,12 @@ mod tests { use alloy_primitives::{address, Bytes}; use revm::context::JournalTr; - /// The Host stages what each state-writing call observed and counts nothing: counting is the - /// opcode wrapper's, after the opcode completed. + /// The Host's write methods count nothing, whoever calls them — an opcode, or a tool such as + /// an inspector appending a log in its `step`: a write is counted once its opcode completed, + /// through the completed-write hook, which only revm's write instructions call. #[test] - fn test_host_stages_observations_and_counts_nothing() { - use crate::{test_utils::MemoryDatabase, MegaSpecId}; + fn test_host_writes_count_nothing() { + use crate::{test_utils::MemoryDatabase, LimitUsage, MegaSpecId, WRITE_RECORD_SIZE}; use revm::{context_interface::Host, primitives::LogData}; const CONTRACT: Address = address!("00000000000000000000000000000000000000c1"); @@ -409,40 +595,27 @@ mod tests { ctx.inner.journaled_state.load_account(CONTRACT).unwrap(); let slot = Host::sstore(&mut ctx, CONTRACT, U256::from(1), U256::from(9)).unwrap(); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::Sstore(slot.data.clone())), - "the non-Berlin entry point stages too" - ); assert_eq!(slot.data.new_value, U256::from(9)); - let slot = - Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(1), U256::from(4), false) - .unwrap(); - assert_eq!(ctx.additional_limit.staged_record(), Some(&StagedRecord::Sstore(slot.data))); - + Host::sstore_skip_cold_load(&mut ctx, CONTRACT, U256::from(2), U256::from(4), false) + .unwrap(); let log = Log { address: CONTRACT, data: LogData::new(vec![B256::ZERO, B256::ZERO], Bytes::from_static(b"abc")).unwrap(), }; Host::log(&mut ctx, log); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::Log { topics: 2, data_len: 3 }) - ); + let destructed = Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); + assert!(destructed.data.had_value); + assert_eq!(ctx.limit_usage(), LimitUsage::ZERO, "the Host counts nothing"); - Host::selfdestruct(&mut ctx, CONTRACT, BENEFICIARY, false).unwrap(); - assert_eq!( - ctx.additional_limit.staged_record(), - Some(&StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: BENEFICIARY, - }) - ); + // The hook is what counts: the slot's first change is one write record, and a slot made + // non-zero from an original of zero is one of state growth. + let mut gas = GasTracker::new(1_000_000, 1_000_000, 0); + let write = + CompletedWrite::Sstore { address: CONTRACT, key: U256::from(1), result: &slot.data }; + assert_eq!(Host::write_completed(&mut ctx, write, &mut gas), WriteVerdict::Continue); assert_eq!( - ctx.additional_limit.usage(), - crate::LimitUsage::ZERO, - "the Host counts nothing" + ctx.limit_usage(), + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 } ); } } diff --git a/crates/mega-evm/src/evm/inspector.rs b/crates/mega-evm/src/evm/inspector.rs deleted file mode 100644 index 88d30da55..000000000 --- a/crates/mega-evm/src/evm/inspector.rs +++ /dev/null @@ -1,670 +0,0 @@ -//! What an inspector may do to a Satin transaction, and what its rewrites do not change. -//! -//! An inspector is not a passive observer. A callback holding a live interpreter can write to its -//! gas and its pending action, a callback holding a frame's inputs can change them or answer the -//! frame itself, and every `*_end` callback can rewrite a result's classification, gas and output. -//! Satin keeps no ledger beside revm's `Gas` (compute is the regular gas spent), so an inspector -//! that changes the gas changes what the transaction owes, and a rewriting inspector gets what it -//! asked for, within the bounds below. Rewriting is a tool feature — Foundry's cheatcodes are built -//! on it — supported and unmeasured. -//! -//! # Where an inspector runs -//! -//! - **A user transaction** runs every callback: `initialize_interp`, `step` and `step_end`, -//! `log_full`, `log` for what a frame journals without running an instruction (an EIP-7708 -//! transfer log, a precompile's logs), `frame_start` and `frame_end`, `call` and `call_end`, -//! `create` and `create_end`, and `selfdestruct`. A keyless deployment is seen as the frames it -//! is made of: its `keylessDeploy` call, which runs no instruction and so gets no -//! `initialize_interp` and no step, and the creation below it. The inspector may rewrite anything -//! outside block execution, within the bounds below. -//! - **A system transaction** — a system-address transaction, promoted to a deposit before its -//! first callback — runs through the same handler and the same callbacks, and may be rewritten -//! the same way. It is the protocol's own work, held to no per-transaction limit, so no limit -//! stops any of its frames. -//! - **A pre-block system call** — the EIP-2935 and EIP-4788 calls, and the `SequencerRegistry`'s -//! `applyPendingChanges()` — runs on the handler's plain system-call path, as alloy-evm's -//! `transact_system_call` runs one: no callback, whatever inspector the EVM holds, so a block's -//! tracer sees the block's transactions and nothing of its preparation. A tool that wants to -//! watch a system call runs it through revm's `InspectSystemCallEvm`, which does hand it to the -//! inspector, with every exemption a system call has. -//! - **The end of a block** runs no code: the post-block balance increments are database writes. No -//! callback runs, and the EVM handed back carries the inspector with what it collected. -//! -//! # The admission gate -//! -//! [`TrustedObserver`] is a declaration, made in source about one inspector type, that none of its -//! callbacks writes anything back. A [`MegaEvm`](crate::MegaEvm) built with -//! [`with_trusted_inspector`](crate::MegaEvm::with_trusted_inspector) carries the declaration, and -//! [`has_rewriting_inspector`](crate::MegaEvm::has_rewriting_inspector) is what block execution -//! refuses on: a rewriting inspector has no route to a block. [`DeclaredObserver`] carries the -//! declaration for a tracer whose type cannot, and in debug builds checks it around every callback. -//! -//! Block execution checks the gate before anything changes wherever an outcome is produced or -//! chosen: the pre-block changes, the execution of a transaction — a system transaction as a user -//! one — the end of the block, and -//! [`commit_transaction_outcome`](crate::MegaBlockExecutor::commit_transaction_outcome), the commit -//! of an outcome a builder chose among candidates. alloy-evm's `commit_transaction` checks nothing -//! and needs no check: it cannot fail, runs no code, and commits the outcome the last execution -//! produced, which passed the gate before it ran and which no inspector enabled since can reach. -//! So a declared observer sees the block's transactions, user and system alike, and a rewriting -//! inspector sees nothing of a block: it is refused before the pre-block calls, which it would not -//! run on anyway, and before any transaction. -//! -//! # What a rewrite does not change -//! -//! - **A frame that kept nothing.** A frame the inspector answered in place of running never -//! started, and a frame that failed had its journal checkpoint reverted before the inspector saw -//! its result. Whatever the inspector hands the caller for either — Foundry's `expectRevert` -//! turns a failed call into a success — the caller sees the success, the output and the regular -//! gas the inspector chose, and nothing else of the frame: no state or history gas, no refund and -//! no write record for writes the journal does not hold, and the upfront state gas its caller's -//! opcode was charged for an account the frame did not add comes back, at the price of the -//! account it was charged for: a call whose target the inspector's `call` hook rewrote gives the -//! charge back as recorded before the hook ran. A creation revived this way hands its creator the -//! address the inspector gave, with nothing deployed there. -//! - **A success rewritten into a failure keeps nothing either.** A frame the inspector turns from -//! a success into a failure — Foundry's `expectRevert` on a call that did not revert — has its -//! journal taken back to its checkpoint, as revm takes back a frame that fails: the frame's own, -//! or, for a start revm answers without building a frame (a call to a precompile or to an account -//! with no code), where the start began. So the state follows the failure its ledgers settle as: -//! no account, slot, code, value moved or log of the frame's is kept, and a creation keeps its -//! creator's nonce bump, which revm makes before the creation's checkpoint, as one that fails -//! does. Everything journaled since the checkpoint goes, what the inspector itself wrote to the -//! journal during the frame or in the callback that rewrote its result included; where revm fails -//! a frame the checkpoint is gone before `call_end`, so a write made there stays. The journal's -//! depth is left as it was. -//! -//! A limit stop is the revert of the frame that crossed the limit, and a rewrite of it is a -//! rewrite of a failure like any other: it settles as above, and the transaction reports no stop -//! once the result of its own frame is no longer the stop's revert. Every other rewrite is the -//! tool's business. -//! -//! # What an inspector's writes to gas cannot do -//! -//! - **Gas changed at a frame's end has no effect.** The instruction that ends a frame copies the -//! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas -//! after it reaches nobody. A tool that changes what a frame returns changes its result, in -//! `call_end`, `create_end` or `frame_end`: that gas is what the caller, or the transaction's -//! settlement, takes in. -//! - **An inspector cannot overdraw a frame.** A charge the frame's spendable gas cannot pay is -//! refused and takes nothing, and the frame is not halted: the interpreter does not ask the -//! callback what it did. A tool that wants a frame out of gas says so through its result. Under -//! gas detention the refusal of an opcode's charge the withheld part would have paid is the -//! crossing; the refusal of an inspector's is not, and classifies nothing ([`StepGuard`]). -//! - **Gas an inspector puts back carries the split it was taken with.** The part gas detention -//! withholds is in the frame's `Gas`, and detention sets it where it can have moved: at a read of -//! volatile data, when the frame starts or resumes, and after an `SSTORE`. An inspector that -//! overwrites the interpreter's gas — Foundry's `pauseGasMetering` puts a snapshot back before -//! every instruction — overwrites the split with it, and the frame runs on the snapshot's split -//! until detention next sets it. Only the crossing record is kept from a callback's write. -//! - **An answer carries only the regular gas the inspector chose.** A frame the inspector answered -//! never ran, so it drew nothing from the reservoir: whatever `Gas` the answer is built on — -//! `Gas::new(limit)`, as Foundry answers a cheatcode, carries no reservoir — its caller merges -//! back the reservoir it forwarded, and none of the state gas, history gas or refund the answer -//! carries. The gas of a result a frame ran to produce is the inspector's to rewrite, reservoir -//! included. - -use revm::{ - context::{ContextTr, JournalTr}, - context_interface::{cfg::StateGasCharge, journaled_state::JournalCheckpoint, Host}, - handler::FrameResult, - inspector::{handler::frame_end, JournalExt, NoOpInspector}, - interpreter::{ - CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, InstructionResult, - Interpreter, InterpreterTypes, - }, - primitives::{Address, Bytes, Log, U256}, - Database, Inspector, -}; - -use crate::{synthetic_frame_result, ExternalEnvTypes, MegaContext}; - -/// A declaration, made in source about one inspector type, that none of its callbacks writes -/// anything back to the EVM: nothing to an interpreter's gas or pending action, nothing to a -/// frame's inputs, nothing to a result's classification, gas or output, and no frame answered -/// itself. It may read anything and write its own state. -/// -/// The declaration is what block execution admits an inspected transaction on. -/// -/// - Implement it for one concrete type at a time, never as a blanket implementation, so each -/// declaration is a line someone wrote about a type they had read. -/// - Do not implement it for an inspector that answers a frame, edits inputs or rewrites a result, -/// however rarely. -/// - A foreign inspector type (a `revm-inspectors` tracer) is wrapped in [`DeclaredObserver`], -/// which is local here and carries the declaration. -/// - The test utilities' inspectors are not declared: they are not part of the gate. -pub trait TrustedObserver {} - -/// The inspector an EVM runs with when none was given observes nothing. -impl TrustedObserver for NoOpInspector {} - -/// A declared observer lent by reference stays declared: `&mut T` is declared exactly when `T` -/// is. -impl TrustedObserver for &mut T {} - -/// Carries a [`TrustedObserver`] declaration for an inspector whose type cannot carry one. -/// -/// It forwards every callback to the inspector inside and adds nothing. `DeclaredObserver(tracer)` -/// says "this tracer writes nothing back", moved from a type definition to the line that wraps -/// the value. -/// -/// A debug build checks the declaration around every callback and panics at the one that breaks -/// it: the interpreter's gas, pending action, stack depth and memory size, the frame's inputs, -/// the frame result, and the journal's entries and logs must be as they were, and no frame may be -/// answered. Writes the check cannot see (a stack word replaced in place, a context field outside -/// the journal) are still false declarations; the check is a tripwire, not a proof. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct DeclaredObserver(pub I); - -impl DeclaredObserver { - /// Declares `inspector` a read-only observer. - pub const fn new(inspector: I) -> Self { - Self(inspector) - } - - /// The inspector inside. - pub fn into_inner(self) -> I { - self.0 - } -} - -impl TrustedObserver for DeclaredObserver {} - -impl Inspector for DeclaredObserver -where - I: Inspector, - CTX: ContextTr, - INTR: InterpreterTypes, -{ - #[inline] - fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.initialize_interp(interp, context); - assert_unwritten(before, interp, context, "initialize_interp"); - } - - #[inline] - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.step(interp, context); - assert_unwritten(before, interp, context, "step"); - } - - #[inline] - fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let before = snapshot(interp, context); - self.0.step_end(interp, context); - assert_unwritten(before, interp, context, "step_end"); - } - - #[inline] - fn log(&mut self, context: &mut CTX, log: Log) { - let before = journal_snapshot(context); - self.0.log(context, log); - assert_journal_unwritten(before, context, "log"); - } - - #[inline] - fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let before = snapshot(interp, context); - self.0.log_full(interp, context, log); - assert_unwritten(before, interp, context, "log_full"); - } - - #[inline] - fn frame_start( - &mut self, - context: &mut CTX, - frame_input: &mut FrameInput, - ) -> Option { - let before = - cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); - let answer = self.0.frame_start(context, frame_input); - debug_assert!(answer.is_none(), "a declared observer answered a frame in `frame_start`"); - if let Some((input, journal)) = before { - debug_assert!(&input == frame_input, "a declared observer rewrote a frame's inputs"); - assert_journal_unwritten(journal, context, "frame_start"); - } - answer - } - - #[inline] - fn frame_end( - &mut self, - context: &mut CTX, - frame_input: &FrameInput, - frame_result: &mut FrameResult, - ) { - let before = result_snapshot(frame_result); - let journal = journal_snapshot(context); - self.0.frame_end(context, frame_input, frame_result); - assert_result_unwritten(before, frame_result, "frame_end"); - assert_journal_unwritten(journal, context, "frame_end"); - } - - #[inline] - fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { - let before = cfg!(debug_assertions).then(|| inputs.clone()); - let journal = journal_snapshot(context); - let answer = self.0.call(context, inputs); - debug_assert!(answer.is_none(), "a declared observer answered a call"); - if let Some(before) = before { - debug_assert!(&before == inputs, "a declared observer rewrote a call's inputs"); - } - assert_journal_unwritten(journal, context, "call"); - answer - } - - #[inline] - fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { - let before = cfg!(debug_assertions).then(|| outcome.clone()); - let journal = journal_snapshot(context); - self.0.call_end(context, inputs, outcome); - if let Some(before) = before { - debug_assert!(&before == outcome, "a declared observer rewrote a call result"); - } - assert_journal_unwritten(journal, context, "call_end"); - } - - #[inline] - fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { - let before = cfg!(debug_assertions).then(|| inputs.clone()); - let journal = journal_snapshot(context); - let answer = self.0.create(context, inputs); - debug_assert!(answer.is_none(), "a declared observer answered a creation"); - if let Some(before) = before { - debug_assert!(&before == inputs, "a declared observer rewrote a creation's inputs"); - } - assert_journal_unwritten(journal, context, "create"); - answer - } - - #[inline] - fn create_end( - &mut self, - context: &mut CTX, - inputs: &CreateInputs, - outcome: &mut CreateOutcome, - ) { - let before = cfg!(debug_assertions).then(|| outcome.clone()); - let journal = journal_snapshot(context); - self.0.create_end(context, inputs, outcome); - if let Some(before) = before { - debug_assert!(&before == outcome, "a declared observer rewrote a creation result"); - } - assert_journal_unwritten(journal, context, "create_end"); - } - - #[inline] - fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { - self.0.selfdestruct(contract, target, value); - } -} - -/// Hands a running frame's instruction-loop callbacks to the inspector inside, and keeps what they -/// do to the interpreter's gas from classifying the frame. -/// -/// A regular charge the frame's spendable gas cannot pay is refused, and when the part gas -/// detention withholds would have paid it the refusal is recorded as the crossing, which stops the -/// transaction at the compute limit when the frame ends. An opcode's refused charge halts the -/// frame at once, so its record is the frame's end. An inspector's does not: the interpreter never -/// sees it fail and the frame runs on. So the record a callback leaves is put back to what it was -/// before the callback, and the frame ends on the charges it made itself. -/// -/// It stands in for the inspector in revm's instruction loop alone (`inspect_instructions`), which -/// makes the four callbacks forwarded here and no other; frame starts and ends reach the inspector -/// itself. The other callbacks are left to the trait's no-op defaults rather than forwarded, -/// because the loop never makes them and a forward nothing reaches is one nothing tests. So a -/// callback the loop gains in a later revision of the fork reaches no inspector until it is -/// forwarded here: a fork upgrade checks the loop's callbacks against this list. -pub(crate) struct StepGuard<'a, I>(pub(crate) &'a mut I); - -impl Inspector for StepGuard<'_, I> -where - I: Inspector, - INTR: InterpreterTypes, -{ - #[inline] - fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); - self.0.step(interp, context); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { - let crossing = interp.gas.withheld_crossing(); - self.0.step_end(interp, context); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { - let crossing = interp.gas.withheld_crossing(); - self.0.log_full(interp, context, log); - interp.gas.set_withheld_crossing(crossing); - } - - #[inline] - fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { - self.0.selfdestruct(contract, target, value); - } -} - -/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. -type JournalSnapshot = Option<(usize, usize)>; - -#[inline] -fn journal_snapshot>(context: &CTX) -> JournalSnapshot { - cfg!(debug_assertions) - .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) -} - -#[inline] -fn assert_journal_unwritten>( - before: JournalSnapshot, - context: &CTX, - callback: &str, -) { - if let Some(before) = before { - debug_assert_eq!( - before, - journal_snapshot(context).expect("debug build"), - "a declared observer wrote to the journal in `{callback}`" - ); - } -} - -/// An interpreter's and the journal's state, for the debug-build proof. -type Snapshot = (GasSnapshot, JournalSnapshot); - -#[inline] -fn snapshot>( - interp: &Interpreter, - context: &CTX, -) -> Snapshot { - (gas_snapshot(interp), journal_snapshot(context)) -} - -#[inline] -fn assert_unwritten>( - (gas, journal): Snapshot, - interp: &Interpreter, - context: &CTX, - callback: &str, -) { - assert_gas_unwritten(gas, interp, callback); - assert_journal_unwritten(journal, context, callback); -} - -/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. -/// `None` in release builds. -type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; - -#[inline] -fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { - use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; - cfg!(debug_assertions) - .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) -} - -#[inline] -fn assert_gas_unwritten( - before: GasSnapshot, - interp: &Interpreter, - callback: &str, -) { - if let Some(before) = before { - debug_assert_eq!( - before, - gas_snapshot(interp).expect("debug build"), - "a declared observer wrote to the interpreter in `{callback}`" - ); - } -} - -/// A frame result's classification, gas and output, and a creation's address, for the -/// debug-build proof. -type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; - -#[inline] -fn result_snapshot(result: &FrameResult) -> ResultSnapshot { - cfg!(debug_assertions).then(|| { - let address = match result { - FrameResult::Call(_) => None, - FrameResult::Create(outcome) => outcome.address, - }; - (result.interpreter_result().clone(), address) - }) -} - -#[inline] -fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { - if let Some(before) = before { - debug_assert!( - before == result_snapshot(result).expect("debug build"), - "a declared observer rewrote a frame result in `{callback}`" - ); - } -} - -/// What the calling opcode charged upfront for a call, as it stood before the inspector could see -/// the call: whether it charged the new-account state gas, and for which address. -/// -/// An inspector's `call` hook holds the call's inputs mutably, and a rewritten target would -/// otherwise be the address the charge is given back at, priced in another SALT bucket than the one -/// it was made in. The record is taken before `frame_start` and written into the frame's result -/// when the frame ends, whatever produced the result. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct UpfrontRecord { - charged_new_account_state_gas: bool, - charged_state_gas_address: Address, -} - -impl UpfrontRecord { - /// The record of the call `input` starts; none for any other frame, whose creation inputs keep - /// what they charged and where in fields an inspector's hook cannot write. - pub(crate) fn of(input: &FrameInput) -> Option { - match input { - FrameInput::Call(inputs) => Some(Self { - charged_new_account_state_gas: inputs.charged_new_account_state_gas, - charged_state_gas_address: inputs.target_address, - }), - _ => None, - } - } - - /// `input` with the call's upfront charge as the record has it. - fn restore(self, input: &FrameInput) -> FrameInput { - let mut input = input.clone(); - if let FrameInput::Call(inputs) = &mut input { - inputs.charged_new_account_state_gas = self.charged_new_account_state_gas; - inputs.target_address = self.charged_state_gas_address; - } - input - } -} - -/// Where the result [`frame_end_checked`] hands the inspector came from. -#[derive(Clone, Copy, Debug)] -pub(crate) enum ResultSource { - /// The inspector answered the frame in place of running it: nothing of the frame is in the - /// journal. - Inspector, - /// The engine produced it — a frame that ran, or a start revm or the engine answered without - /// building a frame — and what the frame journaled begins at the checkpoint: the frame's own, - /// or where the journal stood when the start began. - Engine(JournalCheckpoint), -} - -/// Hands a frame's end to the inspector, then settles what its rewrite does not change. -/// -/// - **A frame that kept nothing.** A frame the inspector answered in place of running, and a frame -/// that failed before the inspector saw it, made no write the journal kept. Whatever the -/// inspector left the result saying, it settles into its caller as such a frame does -/// ([`settle_kept_nothing`]). -/// - **A success rewritten into a failure.** The journal follows the result: what the frame -/// journaled is taken back to its checkpoint, as revm takes back a frame that fails, so the state -/// holds none of the writes the failure's settlement bills nothing for. A frame the inspector -/// answered journaled nothing, so nothing is taken back for it. -/// -/// Every place a frame result reaches the inspector goes through here, so both cover a result -/// a frame ran to produce and one answered without running. -#[inline] -pub(crate) fn frame_end_checked( - context: &mut MegaContext, - inspector: &mut INSP, - frame_input: &FrameInput, - frame_result: &mut FrameResult, - depth: usize, - source: ResultSource, - upfront: Option, -) where - DB: Database, - ExtEnvs: ExternalEnvTypes, - INTR: InterpreterTypes, - INSP: Inspector, INTR, FrameInput, FrameResult>, -{ - let before = frame_result.instruction_result(); - frame_end(context, inspector, frame_input, frame_result); - // What the opcode charged is what was recorded before the inspector saw the call, not what its - // hooks left in the inputs. - let restored = upfront.and_then(|record| { - (UpfrontRecord::of(frame_input) != Some(record)).then(|| record.restore(frame_input)) - }); - let frame_input = restored.as_ref().unwrap_or(frame_input); - if upfront.is_some() { - carry_upfront_flags(frame_input, frame_result); - } - let answered = match source { - ResultSource::Inspector => true, - ResultSource::Engine(checkpoint) => { - if before.is_ok() && !frame_result.instruction_result().is_ok() { - revert_journal_to(context, checkpoint); - } - false - } - }; - if answered || !before.is_ok() { - settle_kept_nothing(context, frame_input, frame_result, depth, answered); - } -} - -/// Settles the result of a frame at `depth` that kept nothing in the journal — one an inspector -/// answered in place of running, or one whose checkpoint was reverted before the inspector saw its -/// result — as such a frame settles, whatever the inspector made of the result. -/// -/// The calling opcode's upfront state-gas charge — the account a value call adds, the account a -/// creation adds, or EIP-2780's for the transaction's own frame — is given back: the frame added -/// no account. The result carries the frame's own upfront-charge flags again, so a result that -/// fails gets it back from revm's settlement, as revm's own do; one an inspector answered carries -/// none of them otherwise. -/// -/// A frame the inspector answered (`answered`) never ran, so it drew nothing from its pools: its -/// answer's gas carries nothing but the regular gas the inspector chose. Whatever `Gas` the answer -/// was built on — `Gas::new(limit)`, which carries no reservoir, or one carrying charges — its -/// state and history charges are rolled back, its refund is dropped, and its reservoir is the one -/// the frame inherited, so its caller merges back the reservoir it forwarded. The rollback comes -/// first: it unwinds the charges against the answer's own reservoir, which the inherited one then -/// replaces, so a charge the answer carries is counted neither in the reservoir nor on a ledger. -/// -/// A result that says success is not one revm's settlement treats as keeping nothing, so it is made -/// to settle like the failure it stands for, save what the inspector chose — the success its caller -/// sees, the output, the regular gas: -/// -/// - its state and history charges are rolled back and its refunds dropped, as a failure's are, -/// before its caller merges them; -/// - the upfront charge comes back through it: the result holds it as state its frame gave back, as -/// a frame that restored a slot its caller filled does, and its caller's merge nets it out; -/// - for the transaction's own frame, the history of the write record charged before execution for -/// its start comes back the same way; -/// - its lane is discarded as a failure's is, so nothing it counted reaches its caller, which gets -/// back the history it paid for the records. -fn settle_kept_nothing( - context: &mut MegaContext, - input: &FrameInput, - result: &mut FrameResult, - depth: usize, - answered: bool, -) { - carry_upfront_flags(input, result); - let success = result.instruction_result().is_ok(); - let gas = result.gas_mut(); - if answered || success { - gas.rollback_state_gas(); - gas.set_refunded(0); - } - if answered { - gas.set_reservoir(inherited_reservoir(input)); - } - if !success { - return; - } - // A creation answered with a success and no address is one revm's settlement gives the - // charge back for itself. - let upfront = upfront_charge(input).filter(|_| result.refundable_state_gas_charge().is_none()); - // A failed lookup records its cause, which fails the transaction before the result settles. - let upfront = upfront.map_or(Some(0), |charge| context.state_gas_charge(charge)); - let history = - if depth == 0 { context.additional_limit.top_level_write_record_gas() } else { 0 }; - let gas = result.gas_mut(); - gas.refill_reservoir(upfront.unwrap_or_default()); - gas.refill_history(history); - context.additional_limit.discard_returning_lane(); -} - -/// Where the journal stands: the checkpoint a frame starting now would take, taken without -/// changing the journal's depth. -#[inline] -pub(crate) fn journal_position( - context: &mut MegaContext, -) -> JournalCheckpoint { - let journal = context.journal_mut(); - let checkpoint = journal.checkpoint(); - journal.checkpoint_commit(); - checkpoint -} - -/// Takes back every journal entry, log and self-destruct made since `checkpoint`, as revm takes -/// back a frame that fails, and leaves the journal's depth as it is: the frame's own checkpoint was -/// already closed, so one is opened for the revert to close. -pub(crate) fn revert_journal_to( - context: &mut MegaContext, - checkpoint: JournalCheckpoint, -) { - let journal = context.journal_mut(); - let _ = journal.checkpoint(); - journal.checkpoint_revert(checkpoint); -} - -/// Sets `result`'s upfront-charge flags to those of `input`, the frame it answers: what revm's -/// settlement reads to give the calling opcode's upfront state-gas charge back. -fn carry_upfront_flags(input: &FrameInput, result: &mut FrameResult) { - match (input, result) { - (FrameInput::Call(inputs), FrameResult::Call(outcome)) => { - outcome.charged_new_account_state_gas = inputs.charged_new_account_state_gas; - outcome.charged_state_gas_address = inputs.target_address; - } - (FrameInput::Create(inputs), FrameResult::Create(outcome)) => { - outcome.charged_create_state_gas = inputs.charged_create_state_gas(); - outcome.charged_state_gas_address = inputs.charged_state_gas_address(); - } - _ => {} - } -} - -/// The reservoir the frame `input` starts inherits from its caller. -const fn inherited_reservoir(input: &FrameInput) -> u64 { - match input { - FrameInput::Call(inputs) => inputs.reservoir, - FrameInput::Create(inputs) => inputs.reservoir(), - FrameInput::Empty => 0, - } -} - -/// The upfront state-gas charge the calling opcode made for the frame `input` starts: the charge -/// revm's settlement gives back when that frame fails. -fn upfront_charge(input: &FrameInput) -> Option { - synthetic_frame_result(input, InstructionResult::Revert, Bytes::new()) - .refundable_state_gas_charge() -} diff --git a/crates/mega-evm/src/evm/instructions.rs b/crates/mega-evm/src/evm/instructions.rs index 7494f5e2c..2634d68eb 100644 --- a/crates/mega-evm/src/evm/instructions.rs +++ b/crates/mega-evm/src/evm/instructions.rs @@ -1,57 +1,41 @@ //! The instruction table of the Satin engine. //! -//! Every opcode runs revm's own instruction, except the ones that write state the resource -//! limits count. Three of them write it themselves — `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` -//! — and four write it by starting a frame: `CALL`, `CALLCODE`, `CREATE` and `CREATE2`. +//! Every opcode runs revm's own instruction, except the ones that can read volatile data. //! -//! The first three run in a wrapper that commits what the Host staged for them after the opcode -//! completed: -//! -//! 1. discard any record staged before the opcode (nothing may commit it for this one); -//! 2. run revm's instruction, whose Host call stages the record and which charges the state gas of -//! a fresh slot or a new beneficiary; -//! 3. discard the record if the opcode failed; if it completed, commit it; -//! 4. charge the frame the history gas of what the record appends — and give it back when the -//! record was taken away, as a slot written back to its original value takes its own back. -//! -//! The history a record costs is its data size, so the charge and the count cannot drift apart: -//! a log pays for its address, its topics and its data, a storage write or a destructed account's -//! beneficiary for the forty bytes of one write record. -//! -//! A commit that crosses a limit stops the opcode's frame with a revert whose output is -//! [`MegaLimitExceeded`](crate::MegaLimitExceeded), and its caller resumes as after any revert -//! (see [`AdditionalLimit`](crate::AdditionalLimit) for the stop). A history charge the frame -//! cannot pay is an ordinary out-of-gas, which burns the frame's gas the way any other does. -//! -//! The other four run in a wrapper that charges their frame for the write records the frame it -//! starts makes — a value transfer's sender and recipient, a creation's creator nonce and created -//! account — before the frame runs, so the gas it forwards is not reduced by them and its -//! allowance is free for what the recipient does. What the frame does not keep goes back to the -//! caller when it returns. The frame the opcode is suspending on carries the caller's reservoir, -//! which the charge has just moved, so the wrapper writes the reservoir it left into the frame's -//! input; and a caller that cannot pay the charge drops that frame before it fails, because an -//! interpreter halts on an instruction's error only when no frame is pending. +//! The opcodes that write state the resource limits count are revm's own, and are metered inside +//! revm's instructions, through two Host hooks (see the `host` module). Three write it themselves — +//! `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` — and revm calls the completed-write hook at the end +//! of each, once the write is in the journal and every charge the opcode makes has been made: the +//! Host counts the write, holds it to the limits and charges the history it costs there, and a +//! failed opcode never reaches the hook, so it counts nothing. Four write it by starting a frame — +//! `CALL`, `CALLCODE`, `CREATE` and `CREATE2` — and revm calls the frame-start hook at every call +//! and creation, once the opcode took the gas it forwards and before it builds the frame's input: +//! the Host charges the caller the history of the write records the start makes there, so the +//! frame inherits the reservoir the charge left, and a caller that cannot pay starts no frame. //! //! Every opcode that can read volatile data — the block-environment opcodes, the account opcodes, //! `SLOAD`, the four calls and `SELFDESTRUCT` — runs in a wrapper that settles the reads its Host //! calls made (see the `access` module): //! -//! 1. discard any read observed or refused before the opcode; -//! 2. keep the frame's gas, when the frame's reads are refused; -//! 3. run the instruction (or the wrapper above it), whose Host calls observe or refuse the reads; -//! 4. on a refusal, hand the frame back the gas it had before the opcode and revert it with +//! 1. keep the frame's gas, when the frame's reads are refused; +//! 2. run revm's instruction as a read, whose Host calls observe or refuse the reads; +//! 3. on a refusal, hand the frame back the gas it had before the opcode and revert it with //! `VolatileDataAccessDisabled`; otherwise, once the opcode completed, commit the reads, which //! holds the frame's spendable gas to what the compute limit leaves it. //! -//! `SSTORE` also holds its frame to the compute limit again once it completed: a slot restored to -//! its original value refills regular gas. +//! The Host observes or refuses a load only while a wrapper runs its opcode. `CREATE` and +//! `CREATE2` are not wrapped: they load their creator's account and the created address's through +//! the Host, to check the creator's balance and nonce and to price the created account, and those +//! loads are no volatile reads, neither refused nor marked, whichever of the two accounts is the +//! block beneficiary's: a value call's check of its caller's balance is no read either. //! //! An opcode whose charge fails with an out-of-gas halts its frame, and the halt zeroes the gas -//! the frame had left before the frame returns. Every wrapper above notes that gas for gas -//! detention first, which does not count what a halt burns as compute; so does a wrapper around -//! the opcodes whose own charge has no bound, `KECCAK256` and the four copies into memory, and -//! around `EXP`, whose exponent charge reaches 1,600. The one charge no wrapper sees is an -//! opcode's static gas, which the interpreter's step loop makes before the opcode runs. +//! the frame had left before the frame returns. The revm fork records that gas first, before +//! every deduction that fails — an opcode's static gas, which the interpreter's step loop charges +//! before the opcode runs, included — and before a halt on a cold access the frame cannot pay; +//! gas detention reads the record where the frame ends, and does not count what a halt burns as +//! compute. The one hook that writes the record itself is the frame-start hook, when the caller +//! cannot pay a start: it hands the forward back to the caller first. //! //! A wrapper keeps the static gas the table charges for its opcode, so the gas schedule is //! unchanged. The static gas table is Amsterdam's ([`satin_gas_table`]). @@ -64,31 +48,29 @@ use revm::{ bytecode::opcode::{ - BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, CALLDATACOPY, CODECOPY, COINBASE, - CREATE, CREATE2, DELEGATECALL, DIFFICULTY, EXP, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, - GASLIMIT, KECCAK256, LOG0, LOG1, LOG2, LOG3, LOG4, MCOPY, NUMBER, RETURNDATACOPY, - SELFBALANCE, SELFDESTRUCT, SLOAD, SLOTNUM, SSTORE, STATICCALL, TIMESTAMP, + BALANCE, BASEFEE, BLOBBASEFEE, BLOCKHASH, CALL, CALLCODE, COINBASE, DELEGATECALL, + DIFFICULTY, EXTCODECOPY, EXTCODEHASH, EXTCODESIZE, GASLIMIT, NUMBER, SELFBALANCE, + SELFDESTRUCT, SLOAD, SLOTNUM, STATICCALL, TIMESTAMP, }, context_interface::Host, handler::instructions::EthInstructions, interpreter::{ enable_amsterdam_opcodes, instruction_table, - instructions::{arithmetic, block_info, contract, host, memory, system}, + instructions::{block_info, contract, host}, interpreter::EthInterpreter, interpreter_types::LoopControl, FrameInput, Gas, Instruction, InstructionContext, InstructionExecResult, InstructionResult, Interpreter, InterpreterAction, }, - primitives::{hardfork::SpecId, Bytes}, + primitives::hardfork::SpecId, Database, }; use crate::{ - charge_write_records_history, history_gas, limit::HistoryBytes, volatile_data_access_disabled_revert_data, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -use super::{caller_refuses_start, satin_gas_table, MegaInstructions}; +use super::{input_gas_limit, satin_gas_table, value_call_stipend, MegaInstructions}; /// The context an instruction of the Satin engine runs with. type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, EthInterpreter>; @@ -96,29 +78,20 @@ type Ctx<'a, DB, ExtEnvs> = InstructionContext<'a, MegaContext, Eth /// An instruction of the Satin engine. type InstructionFn = fn(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult; -/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated, -/// the opcodes that write state the limits count wrapped, and the opcodes that can read volatile -/// data wrapped, on the Satin static gas table. +/// The Satin instruction table: revm's for the base spec, with the Amsterdam opcodes activated and +/// the opcodes that can read volatile data wrapped, on the Satin static gas table. pub(crate) fn mega_instructions( spec: SpecId, ) -> MegaInstructions { let mut table = instruction_table(); enable_amsterdam_opcodes(&mut table); let mut instructions = EthInstructions::new(table, satin_gas_table(), spec); - let wrappers: [(u8, InstructionFn); 34] = [ - (SSTORE, sstore::), - (LOG0, log::<0, DB, ExtEnvs>), - (LOG1, log::<1, DB, ExtEnvs>), - (LOG2, log::<2, DB, ExtEnvs>), - (LOG3, log::<3, DB, ExtEnvs>), - (LOG4, log::<4, DB, ExtEnvs>), + let wrappers: [(u8, InstructionFn); 20] = [ (SELFDESTRUCT, selfdestruct::), (CALL, call::), (CALLCODE, call::), - (DELEGATECALL, volatile_call::), - (STATICCALL, volatile_call::), - (CREATE, create::), - (CREATE2, create::), + (DELEGATECALL, call::), + (STATICCALL, call::), (COINBASE, coinbase::), (TIMESTAMP, timestamp::), (NUMBER, number::), @@ -134,12 +107,6 @@ pub(crate) fn mega_instructions( (EXTCODECOPY, extcodecopy::), (EXTCODEHASH, extcodehash::), (SLOAD, sload::), - (KECCAK256, keccak256::), - (CALLDATACOPY, calldatacopy::), - (CODECOPY, codecopy::), - (RETURNDATACOPY, returndatacopy::), - (MCOPY, mcopy::), - (EXP, exp::), ]; for (opcode, wrapper) in wrappers { let static_gas = instructions.gas_table()[opcode as usize]; @@ -148,273 +115,14 @@ pub(crate) fn mega_instructions( instructions } -/// Runs `inner`, commits the record its Host call staged once it completed, and settles the -/// history gas the record costs. -/// -/// An opcode completes when it returns `Ok` or stops the frame successfully (`SELFDESTRUCT` -/// returns its own `SelfDestruct` result). Any other result fails the opcode, which takes the -/// staged write back with it. -/// -/// The record is held to the data-size limit first, and only then is its history charged. A record -/// the limit rejects is not kept, so its history is not a charge and the stop is what the frame -/// reports. A record the limit accepts is charged, and a charge the frame cannot pay is an -/// out-of-gas. -#[inline(always)] -fn commit_after( - context: Ctx<'_, DB, ExtEnvs>, - inner: InstructionFn, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - host.additional_limit.discard_staged_record(); - let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - let completed = match result { - Ok(()) => true, - Err(result) => result.is_ok(), - }; - if !completed { - host.additional_limit.discard_staged_record(); - return note_halt(interpreter, host, result); - } - let (check, history) = host.additional_limit.commit_staged_record(); - if check.exceeded_limit() { - return Err(stop_frame(interpreter, host.additional_limit.note_frame_stop(&check))); - } - if host.prices_history() { - let settled = settle_history::(interpreter, host, history); - if settled.is_err() { - return note_halt(interpreter, host, settled); - } - } - result -} - -/// Charges the running frame the history gas of the bytes a record appends, or gives back the -/// history of a record that was taken away. -/// -/// Both sides are priced the same way, so a record taken back cancels its own charge exactly, -/// whichever frame made it: a refill below zero is reconciled when the frame merges into its -/// caller. A byte count with no price and a charge the frame cannot pay are both an out-of-gas. -/// -/// With `FROM_ALLOWANCE` the frame's history allowance pays what it can of the charge before the -/// frame's gas pays the rest ([`storage_call_stipend`](crate::storage_call_stipend)). Only the -/// log site sets it: a write record is the frame's own to pay for, and a record taken back gives -/// back what the frame's gas paid, never what the allowance did — the allowance is spent, not -/// lent. -#[inline] -fn settle_history( - interpreter: &mut Interpreter, - host: &mut MegaContext, - history: HistoryBytes, -) -> Result<(), InstructionResult> { - match history { - HistoryBytes::None => Ok(()), - HistoryBytes::Appended(bytes) => { - let Some(cost) = history_gas(bytes) else { return Err(InstructionResult::OutOfGas) }; - let drawn = - if FROM_ALLOWANCE { host.additional_limit.try_consume_stipend(cost) } else { 0 }; - if interpreter.gas.record_history_cost(cost - drawn) { - Ok(()) - } else { - Err(InstructionResult::OutOfGas) - } - } - HistoryBytes::Taken(bytes) => { - interpreter.gas.refill_history(history_gas(bytes).unwrap_or(0)); - Ok(()) - } - } -} - -/// Stops the running frame with the revert a crossed limit asks for: its output is the stop's -/// [`MegaLimitExceeded`](crate::MegaLimitExceeded), `output`, and its gas is the frame's, so the -/// caller gets the unspent part back. -#[cold] -#[inline(never)] -fn stop_frame(interpreter: &mut Interpreter, output: Bytes) -> InstructionResult { - if interpreter.bytecode.action().is_some() { - // A `SELFDESTRUCT` or a return the opcode already set gives way to the stop. - let _ = interpreter.take_next_action(); - } - let result = InstructionResult::Revert; - interpreter.bytecode.set_action(InterpreterAction::new_return(result, output, interpreter.gas)); - result -} - -/// `SSTORE`, committing the slot's write record, then holding the frame to the compute limit -/// again: a slot restored to its original value refills the state and history gas that spilled -/// onto regular gas, and the spill may predate the limit. -fn sstore( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = commit_after::( - InstructionContext { interpreter: &mut *interpreter, host: &mut *host }, - host::sstore, - ); - // Only a restore refills, and a restore takes a record back rather than adding one, so it - // never crosses a limit: no stop's result is pending when the frame is held again. - host.detention.hold(&mut interpreter.gas); - result -} - -/// `LOG0`..`LOG4`, committing the log's bytes. -fn log( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - commit_after::(context, host::log::>) -} - -/// `SELFDESTRUCT`, committing the beneficiary's write record and the read of the block -/// beneficiary's account when it is either end. -fn selfdestruct( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - read_volatile(context, |context| commit_after::(context, host::selfdestruct)) -} - -/// Runs `inner` and charges the frame the history of the write records the frame `inner` starts -/// will make. -/// -/// The charge is made after revm's instruction has computed the gas it forwards, so it comes out -/// of what the caller kept rather than out of what the callee gets. An opcode that starts no frame -/// — a creation the balance, the nonce or the depth refuses, an out-of-gas — makes no records and -/// is charged nothing. Neither is a frame revm will refuse on its caller's account — a value call -/// the caller cannot fund ([`caller_refuses_start`]) — which the data size does not count either; -/// the answer is left for the frame's init, which would otherwise read the caller's account again. -/// A frame revm refuses for another reason — one past the call-stack limit — makes no records, -/// and its failure gives the charge back. A charge the caller cannot pay fails the opcode with an -/// out-of-gas, which takes the frame the opcode was suspending on with it ([`abandon_frame`]). -/// -/// revm's instruction has also charged the caller the state gas of the account the frame would -/// add — a value transfer's new recipient, a created account; a frame revm refuses gives it back. -/// -/// The frame inherits the reservoir the charge left, not the one the caller held before it -/// ([`inherit_reservoir`]). -#[inline(always)] -fn charge_frame_start( - context: Ctx<'_, DB, ExtEnvs>, - inner: InstructionFn, -) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - // An opcode that starts a frame suspends with the frame's input as its action; one that ends - // otherwise — a creation the balance cannot fund, an out-of-gas — leaves no such action and - // makes no records. - let records = match interpreter.bytecode.action() { - Some(InterpreterAction::NewFrame(input)) => { - let refused = caller_refuses_start(host, input); - host.additional_limit.stage_start_refused(refused); - if refused { - return result; - } - host.additional_limit.frame_start_records(input) - } - _ => return note_halt(interpreter, host, result), - }; - if !host.prices_history() { - return result; - } - let charged = charge_write_records_history( - interpreter.gas.tracker_mut(), - records.on_lane, - u64::from(records.caller), - ); - let Some((on_lane, caller)) = charged else { return abandon_frame(interpreter, host) }; - inherit_reservoir(interpreter); - host.additional_limit.stage_frame_charge(records, on_lane, caller); - result -} - -/// Fails the running opcode with an out-of-gas and drops the frame it was suspending on. -/// -/// The four frame-starting opcodes set the frame's input as the interpreter's action inside -/// revm's instruction, before this wrapper runs. An interpreter halts on an instruction's error -/// only when no action is pending, so a frame left pending here would start anyway — and make -/// write records nobody paid for, at any gas limit at which the caller keeps less after the -/// 63/64 forward than its records cost. -/// -/// The gas the opcode forwarded to the dropped frame goes back to the caller, which the halt then -/// burns with the rest: it never ran, so gas detention counts it with what the halt burns rather -/// than as compute. A value call's stipend was never the caller's, and is not handed back. -#[cold] -#[inline(never)] -fn abandon_frame( - interpreter: &mut Interpreter, - host: &mut MegaContext, -) -> InstructionExecResult { - if let InterpreterAction::NewFrame(input) = interpreter.take_next_action() { - interpreter.gas.erase_cost(forwarded_gas(&input, host.gas_params().call_stipend())); - } - note_halt(interpreter, host, Err(InstructionResult::OutOfGas)) -} - -/// Passes `result` on, first noting for gas detention what the running frame has left when -/// `result` is an out-of-gas the interpreter will halt the frame on: the halt zeroes it before the -/// frame returns, and it is what the halt burns rather than what the frame ran. -/// -/// The interpreter halts on an instruction's error only when no action is pending; an opcode that -/// set one ends its frame with that action instead, and burns nothing. -#[inline(always)] -fn note_halt( - interpreter: &mut Interpreter, - host: &mut MegaContext, - result: InstructionExecResult, -) -> InstructionExecResult { - if result == Err(InstructionResult::OutOfGas) && interpreter.bytecode.action().is_none() { - host.detention.note_halt(interpreter.gas.remaining()); - } - result -} - -/// Hands the frame the running opcode is suspending on the reservoir its caller has now. -/// -/// revm's `CALL`, `CALLCODE`, `CREATE` and `CREATE2` copy the caller's reservoir into the frame's -/// input, and they do it before this wrapper charges anything. A returning frame's reservoir is -/// adopted by its caller rather than merged into it, so a frame that inherited the reservoir as -/// it stood before the charge would hand the charge straight back — and a frame answered without -/// running, whose gas is built from the same field, would hand it back a second time. Writing the -/// post-charge reservoir into the input closes both. -#[inline] -fn inherit_reservoir(interpreter: &mut Interpreter) { - let reservoir = interpreter.gas.reservoir(); - if let Some(InterpreterAction::NewFrame(input)) = interpreter.bytecode.action() { - match input { - FrameInput::Call(inputs) => inputs.reservoir = reservoir, - FrameInput::Create(inputs) => inputs.set_reservoir(reservoir), - FrameInput::Empty => {} - } - } -} - -/// `CALL` and `CALLCODE`, charging the caller for the records a value transfer writes and -/// committing the read of the block beneficiary's account when the callee, or the EIP-7702 -/// delegate it runs, is the beneficiary. -/// -/// `CALLCODE` runs the callee's code in the caller's own account, so the two records of a `CALL` -/// — the sender's and the recipient's — are one here. +/// `CALL`, `CALLCODE`, `DELEGATECALL` and `STATICCALL`, committing the read of the block +/// beneficiary's account when the callee, or the EIP-7702 delegate it runs, is the beneficiary. fn call( context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - read_volatile(context, |context| charge_frame_start(context, contract::call::)) -} - -/// `DELEGATECALL` and `STATICCALL`, committing the read of the block beneficiary's account when -/// the callee, or the EIP-7702 delegate it runs, is the beneficiary. They carry no value and write -/// nothing, so no record is charged. -fn volatile_call( - context: Ctx<'_, DB, ExtEnvs>, ) -> InstructionExecResult { read_volatile(context, contract::call::) } -/// `CREATE` and `CREATE2`, charging the creator for the created account's record and for its own -/// nonce. -fn create( - context: Ctx<'_, DB, ExtEnvs>, -) -> InstructionExecResult { - charge_frame_start(context, contract::create::) -} - /// Runs `inner` and settles the reads of volatile data its Host calls made: a refused read /// reverts the frame with `VolatileDataAccessDisabled`, and a read the opcode completed is /// committed, capping the frame at what the compute limit leaves it. @@ -432,11 +140,12 @@ fn read_volatile( inner: impl FnOnce(Ctx<'_, DB, ExtEnvs>) -> InstructionExecResult, ) -> InstructionExecResult { let InstructionContext { interpreter, host } = context; - host.detention.discard_stale_reads(); + host.detention.begin_read(); let gas = host.detention.is_refusing().then_some(interpreter.gas); let result = inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); + host.detention.end_read(); if !host.detention.has_reads() { - return note_halt(interpreter, host, result); + return result; } settle_reads(interpreter, host, result, gas) } @@ -461,7 +170,7 @@ fn settle_reads( } }; if !completed { - return note_halt(interpreter, host, result); + return result; } // A completed opcode leaves no result pending: a `SELFDESTRUCT`'s is built from the frame's // gas once the wrapper returned, and a stop fails the opcode. @@ -471,7 +180,7 @@ fn settle_reads( } _ => 0, }; - host.detention.commit_reads(observed, &mut interpreter.gas, interpreter.input.depth, forwarded); + host.detention.commit_reads(observed, &mut interpreter.gas, forwarded); result } @@ -500,14 +209,7 @@ fn refuse( /// The regular gas the running frame paid for the frame `input` starts: the frame's limit, less /// a value call's stipend, which nobody paid. fn forwarded_gas(input: &FrameInput, call_stipend: u64) -> u64 { - match input { - FrameInput::Call(inputs) if inputs.transfers_value() => { - inputs.gas_limit.saturating_sub(call_stipend) - } - FrameInput::Call(inputs) => inputs.gas_limit, - FrameInput::Create(inputs) => inputs.gas_limit(), - FrameInput::Empty => 0, - } + input_gas_limit(input).saturating_sub(value_call_stipend(input, call_stipend)) } /// Defines an opcode that reads volatile data — a block-environment field, an account or a slot — @@ -538,6 +240,7 @@ volatile_read! { extcodecopy => host::extcodecopy, "EXTCODECOPY", "the block beneficiary's account"; extcodehash => host::extcodehash, "EXTCODEHASH", "the block beneficiary's account"; sload => host::sload, "SLOAD", "the Oracle's storage"; + selfdestruct => host::selfdestruct, "SELFDESTRUCT", "the block beneficiary's account"; } /// `BLOCKHASH`, committing the read of the block number and of the hash. @@ -554,31 +257,6 @@ fn blockhash( }) } -/// Defines an opcode whose own charge no other wrapper sees, as revm's instruction with what the -/// frame had left noted when the charge fails ([`note_halt`]): the charge of `KECCAK256` and of -/// the four copies into memory has no bound, and `EXP`'s exponent charge reaches 1,600. -macro_rules! unbounded_charge { - ($($name:ident => $inner:path, $opcode:literal;)*) => {$( - #[doc = concat!("`", $opcode, "`, noting what the frame had when its charge fails.")] - fn $name( - context: Ctx<'_, DB, ExtEnvs>, - ) -> InstructionExecResult { - let InstructionContext { interpreter, host } = context; - let result = $inner(InstructionContext { interpreter: &mut *interpreter, host: &mut *host }); - note_halt(interpreter, host, result) - } - )*}; -} - -unbounded_charge! { - keccak256 => system::keccak256, "KECCAK256"; - calldatacopy => system::calldatacopy, "CALLDATACOPY"; - codecopy => system::codecopy, "CODECOPY"; - returndatacopy => system::returndatacopy, "RETURNDATACOPY"; - mcopy => memory::mcopy, "MCOPY"; - exp => arithmetic::exp, "EXP"; -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/mega-evm/src/evm/mod.rs b/crates/mega-evm/src/evm/mod.rs index 8893e7efc..f033533c5 100644 --- a/crates/mega-evm/src/evm/mod.rs +++ b/crates/mega-evm/src/evm/mod.rs @@ -1,9 +1,42 @@ //! The Satin EVM. //! //! [`MegaEvm`] runs transactions on a [`MegaContext`] configured for the Satin spec through -//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame lifecycle -//! itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level mechanisms -//! plug in. +//! [`MegaHandler`], which wraps op-revm's handler. The EVM implements revm's frame start and +//! return itself (see [`execution`](self::execution)), which is where `MegaETH`'s frame-level +//! mechanisms plug in. +//! +//! # Inspectors +//! +//! An inspector runs as revm runs it: through revm's inspected handler and frame lifecycle, +//! unchanged, which start a frame, hand over the result of its run and return it through the same +//! three methods the plain path does. The engine does nothing for an inspector, and an inspector +//! keeps its own consistency. +//! +//! - **A rewrite is taken as given.** revm commits or reverts a frame's journal checkpoint before +//! the inspector sees its result, and the caller settles the result the inspector hands back — +//! its classification, output and gas, reservoir and byte pool included — and an answer the +//! inspector gives in place of a frame never reaches the engine's frame start: the depth guard, +//! the interceptors and gas detention see none of it, and it settles on the gas it is built on. +//! - **A callback's writes to gas are the inspector's.** A charge a frame cannot pay is refused, +//! and leaves its record on the frame's gas as an opcode's does: a crossing of the withheld part +//! stops nothing in a frame that ends without an out-of-gas, and a later halt that records +//! nothing of its own is read off the record. An inspector that overwrites the interpreter's gas +//! overwrites gas detention's split and the byte pool with it, until detention next holds the +//! frame. +//! - **What an inspector sees.** A frame's end as the engine settled it: a frame that crossed gas +//! detention's compute limit ends with the stop, which the engine makes of its out-of-gas once +//! its run returns and before the inspector's `call_end`, `create_end` and `frame_end` see it, as +//! the caller and the receipt do. A frame whose start crossed a limit ends with the stop before +//! it runs, and is seen to start and end as an answer is. A `keylessDeploy` call's frame runs no +//! instruction: the action made for it before each of its runs is set on its interpreter, and +//! revm's inspected run returns an action set before it runs without a `step`, and hands a frame +//! built with one to no `initialize_interp`, so the inspector sees the call start, its creation, +//! and the call end. A frame a child returned into over a limit returns the stop the same way, +//! with no `step` after the child's end. +//! - **Where an inspector runs.** Every transaction, the system-address transaction included. A +//! pre-block call runs on the handler's plain system-call path, with no callback; a tool runs a +//! system call through revm's `InspectSystemCallEvm` to watch it. The end of a block runs no +//! code. mod context; mod execution; @@ -11,7 +44,6 @@ mod factory; mod frame; mod history; mod host; -mod inspector; mod instructions; mod precompiles; mod prices; @@ -26,7 +58,6 @@ pub use execution::*; pub use factory::*; pub use frame::*; pub use history::*; -pub use inspector::*; pub use precompiles::*; pub use prices::*; pub use result::*; @@ -92,9 +123,6 @@ pub struct MegaEvm, /// Whether [`alloy_evm::Evm::transact_raw`] runs the inspector. inspect: bool, - /// Whether the inspector's type carries a [`TrustedObserver`] declaration. Set only by the - /// constructors that require the declaration; true without an inspector. - trusted_inspector: bool, /// Which precompile calls gas detention may price from the Satin table. priced_precompiles: PricedPrecompiles, } @@ -110,12 +138,7 @@ impl MegaEvm MegaEvm { /// Replaces the inspector with a tool's. The new inspector runs on every alloy-evm /// [`transact`](alloy_evm::Evm::transact) until it is disabled again. /// - /// The inspector may rewrite what execution produces (see the `inspector` module), so the - /// EVM reports [`has_rewriting_inspector`](Self::has_rewriting_inspector) while it runs, and - /// block execution refuses it. + /// The inspector may rewrite what execution produces (see the module documentation). The engine + /// does not refuse one in block execution: a node decides which inspectors run on block + /// production. pub fn with_inspector(self, inspector: I) -> MegaEvm { MegaEvm { inner: self.inner.with_inspector(inspector), inspect: true, - trusted_inspector: false, priced_precompiles: self.priced_precompiles, } } - /// Replaces the inspector with one whose type is declared a [`TrustedObserver`]: it writes - /// nothing back, so the transactions it observes are the ones the chain executes, and block - /// execution admits them. - pub fn with_trusted_inspector( - self, - inspector: I, - ) -> MegaEvm { - MegaEvm { - inner: self.inner.with_inspector(inspector), - inspect: true, - trusted_inspector: true, - priced_precompiles: self.priced_precompiles, - } - } - - /// Whether the EVM runs an inspector that may rewrite what execution produces: an enabled - /// inspector that did not arrive through - /// [`with_trusted_inspector`](Self::with_trusted_inspector). - /// - /// The admission gate block execution refuses a transaction on. - pub const fn has_rewriting_inspector(&self) -> bool { - self.inspect && !self.trusted_inspector - } - /// The execution context. pub const fn ctx(&self) -> &MegaContext { &self.inner.ctx @@ -221,7 +219,7 @@ impl MegaEvm { /// Enforces `limits` on every transaction this EVM runs from now on. pub const fn set_tx_runtime_limits(&mut self, limits: crate::EvmTxRuntimeLimits) { - self.inner.ctx.additional_limit.set_limits(limits); + self.inner.ctx.set_tx_runtime_limits(limits); } /// The limits every transaction this EVM runs is held to. @@ -290,8 +288,8 @@ where ExtEnvs: ExternalEnvTypes, { /// Executes `tx`, through the inspector when one is enabled, and returns its outcome: the - /// result and state, the gas by ledger, the usage the common execution layer counted, the - /// limit that stopped the transaction, if any, and the reads of the Oracle's storage it made + /// result and state, the gas by ledger, the usage the common execution layer counted, the limit + /// that stopped the transaction, if any, and the reads of the Oracle's storage it made /// through the oracle service. Nothing is committed. pub fn execute_transaction( &mut self, @@ -303,11 +301,12 @@ where result_and_state.result.gas(), layer.history_gas_spent(), layer.history_bytes(), + layer.reservoir_remaining(), ); Ok(MegaTransactionOutcome { result_and_state, gas, - usage: layer.usage(), + usage: self.inner.ctx.limit_usage(), limit_exceeded: layer.limit_exceeded().copied(), oracle_reads: self.inner.ctx.oracle_reads().reads().to_vec(), }) @@ -392,20 +391,6 @@ where { } -/// revm's system-call transaction from `caller` to `contract` with `data` -/// ([`SystemCallTx::new_system_tx_with_caller`]), on `gas_limit` instead of revm's -/// [`SYSTEM_CALL_GAS_LIMIT`](revm::handler::SYSTEM_CALL_GAS_LIMIT). -fn system_tx_with_gas_limit( - caller: Address, - contract: Address, - data: Bytes, - gas_limit: u64, -) -> MegaTransaction { - let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); - tx.0.base.gas_limit = gas_limit; - tx -} - impl SystemCallEvm for MegaEvm { fn system_call_one_with_caller( &mut self, @@ -422,25 +407,26 @@ impl SystemCallEvm for MegaEvm MegaEvm { - /// Runs a system call from `caller` to `contract` with `data` on `gas_limit`, and returns its - /// result and state. Nothing is committed. + /// Runs a pre-block system call from `caller` to `contract` with `data`, and returns its result + /// and state. Nothing is committed. /// - /// It is [`transact_system_call`](alloy_evm::Evm::transact_system_call) on the gas limit the - /// caller names instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]. The limit is split as every - /// system call's is: at most [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas and the - /// rest is the call's state-gas reservoir, so a limit above 30,000,000 widens the reservoir - /// and never the regular budget. The block's pre-block calls run through it. + /// It is [`transact_system_call`](alloy_evm::Evm::transact_system_call) on the pre-block + /// budget, [`PRE_BLOCK_CALL_GAS_LIMIT`], instead of revm's [`SYSTEM_CALL_GAS_LIMIT`]: at most + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`] of it is regular gas, as of every system call, and the + /// rest is the call's state-gas reservoir. What the call left of its reservoir is + /// [`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining). /// + /// [`PRE_BLOCK_CALL_GAS_LIMIT`]: crate::constants::PRE_BLOCK_CALL_GAS_LIMIT /// [`SYSTEM_CALL_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_GAS_LIMIT - /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: revm::handler::SYSTEM_CALL_REGULAR_GAS_LIMIT - pub fn transact_system_call_with_gas_limit( + /// [`SYSTEM_CALL_REGULAR_GAS_LIMIT`]: crate::SYSTEM_CALL_REGULAR_GAS_LIMIT + pub(crate) fn transact_pre_block_system_call( &mut self, caller: Address, contract: Address, data: Bytes, - gas_limit: u64, ) -> Result, EVMError> { - let tx = system_tx_with_gas_limit(caller, contract, data, gas_limit); + let mut tx = MegaTransaction::new_system_tx_with_caller(caller, contract, data); + tx.0.base.gas_limit = crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; let result = self.run_system_call(tx).map_err(map_op_err)?; Ok(ResultAndState::new(result, ExecuteEvm::finalize(self))) } @@ -553,7 +539,7 @@ mod tests { use revm::{ context::{result::InvalidTransaction, ContextSetters, Transaction, TxEnv}, database::State, - handler::{SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT}, + handler::system_call::SYSTEM_CALL_GAS_LIMIT, DatabaseRef, }; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; @@ -734,35 +720,29 @@ mod tests { assert_eq!(evm.ctx().tx().kind(), TxKind::Call(CALLEE)); } - /// The gas limit a caller names is the system call's: the part above 30M is its reservoir, - /// and a limit below 30M is regular gas alone. + /// A pre-block call runs on the pre-block budget whatever the block's gas limit: 30M of + /// regular gas and the rest of the budget as its reservoir. #[test] - fn test_transact_system_call_with_gas_limit_uses_passed_value() { - let mut db = funded_db(); - let mut evm = MegaEvm::new(context(&mut db)); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 123_456_789) - .unwrap(); - assert!(result.result.is_success()); - assert_eq!(evm.ctx().tx().gas_limit(), 123_456_789); - assert_eq!( - result.result.gas().reservoir_remaining(), - 123_456_789 - SYSTEM_CALL_REGULAR_GAS_LIMIT, - "an empty callee draws nothing from the reservoir", - ); - - let result = evm - .transact_system_call_with_gas_limit(CALLER, CALLEE, Bytes::new(), 1_000_000) - .unwrap(); - assert!(result.result.is_success()); - assert_eq!(evm.ctx().tx().gas_limit(), 1_000_000); - assert_eq!(result.result.gas().reservoir_remaining(), 0); + fn test_a_pre_block_call_runs_on_the_pre_block_budget() { + use crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; + for block_gas_limit in [1_000_000, 10_000_000_000] { + let mut db = funded_db(); + let block = BlockEnv { gas_limit: block_gas_limit, ..Default::default() }; + let mut evm = MegaEvm::new(context(&mut db).with_block(block)); + let result = evm.transact_pre_block_system_call(CALLER, CALLEE, Bytes::new()).unwrap(); + assert!(result.result.is_success()); + assert_eq!(evm.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "{block_gas_limit}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT, + "an empty callee draws nothing from the reservoir", + ); + } } /// The default system-call entry point runs on revm's system-call gas limit whatever the /// block's gas limit is: its regular budget is the base 30M, and the margin above it is the - /// reservoir. Only an explicit gas limit moves either. + /// reservoir. #[test] fn test_default_system_call_keeps_the_30m_regular_budget() { let mut db = funded_db(); @@ -777,7 +757,7 @@ mod tests { assert_eq!(evm.ctx().tx().gas_limit(), 31_566_720); assert_eq!(SYSTEM_CALL_GAS_LIMIT, 31_566_720); assert_eq!( - result.result.gas().reservoir_remaining(), + evm.ctx().additional_limit().reservoir_remaining(), 31_566_720 - 30_000_000, "30M of it is regular gas", ); diff --git a/crates/mega-evm/src/evm/precompiles.rs b/crates/mega-evm/src/evm/precompiles.rs index 1ebe4fddb..954fdde2c 100644 --- a/crates/mega-evm/src/evm/precompiles.rs +++ b/crates/mega-evm/src/evm/precompiles.rs @@ -52,14 +52,17 @@ use alloy_evm::{ precompiles::{DynPrecompile, Precompile as _, PrecompilesMap}, Database, }; +use op_revm::{L1BlockInfo, OpSpecId}; use revm::{ + context::{BlockEnv, CfgEnv}, handler::PrecompileProvider, interpreter::{CallInputs, InterpreterResult}, precompile::Precompiles, primitives::{Address, AddressSet, HashMap, OnceLock}, + Context, Journal, }; -use crate::{ExternalEnvTypes, MegaContext, MegaInnerContext, MegaSpecId}; +use crate::{ExternalEnvTypes, MegaContext, MegaSpecId, MegaTransaction}; /// The Satin precompile set: op-revm's Karst set with `MegaETH`'s KZG price. pub fn satin_precompiles() -> &'static Precompiles { @@ -185,10 +188,16 @@ pub mod kzg_point_evaluation { .with_required_gas(required_gas); } -/// Runs the Satin precompile set on a [`MegaContext`]. -/// -/// alloy-evm implements the provider for revm's plain context; every method here hands it the -/// context [`MegaContext`] wraps, which is that context. +/// The context [`MegaContext`] wraps: op-revm's context shape over revm's own journal, the one +/// alloy-evm implements the provider for. +type InnerContext = + Context, DB, Journal, L1BlockInfo>; + +/// Runs the Satin precompile set on a [`MegaContext`], as alloy-evm runs it on the context +/// [`MegaContext`] wraps: the precompile gets the call's input and an +/// [`EvmInternals`](alloy_evm::EvmInternals) over revm's journal, and its output is turned into +/// the call's result the way revm turns any precompile's. A precompile's writes through the +/// internals reach the journal as any tool's do, and count none of the transaction's bytes. impl PrecompileProvider> for PrecompilesMap { @@ -197,7 +206,7 @@ impl PrecompileProvider bool { + fn set_spec(&mut self, _spec: OpSpecId) -> bool { false } @@ -207,17 +216,19 @@ impl PrecompileProvider, inputs: &CallInputs, ) -> Result, String> { - PrecompileProvider::>::run(self, &mut context.inner, inputs) + PrecompileProvider::>::run(self, &mut context.inner, inputs) } + /// The addresses of the set, as alloy-evm's provider answers them. #[inline] fn warm_addresses(&self) -> &AddressSet { - PrecompileProvider::>::warm_addresses(self) + PrecompileProvider::>::warm_addresses(self) } + /// Whether the set holds `address`, as alloy-evm's provider answers it. #[inline] fn contains(&self, address: &Address) -> bool { - PrecompileProvider::>::contains(self, address) + PrecompileProvider::>::contains(self, address) } } @@ -273,6 +284,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, } } diff --git a/crates/mega-evm/src/evm/result.rs b/crates/mega-evm/src/evm/result.rs index b3873f90d..8662b8a57 100644 --- a/crates/mega-evm/src/evm/result.rs +++ b/crates/mega-evm/src/evm/result.rs @@ -46,7 +46,8 @@ pub struct MegaTransactionOutcome { /// is [`LimitUsage::write_records`]. pub usage: LimitUsage, /// The crossing that produced the result of the transaction's own frame, if one did: a - /// transaction-level limit, or that frame's own data-size budget. The result is then a revert + /// transaction-level limit, or that frame's own budget in data size, KV updates or state + /// growth. The result is then a revert /// whose output is its [`MegaLimitExceeded`](crate::MegaLimitExceeded); this, not the output, /// tells a limit stop from a contract reverting with the same bytes, or re-raising those a /// frame below it was stopped with. @@ -117,18 +118,26 @@ pub struct MegaGasUsage { impl MegaGasUsage { /// The ledgers of a transaction that settled into `result_gas`, spent `history` gas on - /// history and appended `history_bytes` bytes of it. + /// history, appended `history_bytes` bytes of it and left `reservoir_remaining` of its + /// reservoir unspent. /// /// [`ResultGas`] has no history field; its total includes history gas, which is taken back - /// out of regular here. - pub const fn new(result_gas: &ResultGas, history: u64, history_bytes: u64) -> Self { + /// out of regular here. Nor does it carry the reservoir: the handler reads that off the + /// settled result + /// ([`AdditionalLimit::reservoir_remaining`](crate::AdditionalLimit::reservoir_remaining)). + pub const fn new( + result_gas: &ResultGas, + history: u64, + history_bytes: u64, + reservoir_remaining: u64, + ) -> Self { let state = result_gas.state_gas_spent_final(); Self { regular: result_gas.total_gas_spent().saturating_sub(state).saturating_sub(history), state, history, history_bytes, - reservoir_remaining: result_gas.reservoir_remaining(), + reservoir_remaining, floor: result_gas.floor_gas(), gas_used: result_gas.tx_gas_used(), } @@ -159,19 +168,19 @@ mod tests { .with_state_gas_spent(state) .with_refunded(refunded) .with_floor_gas(floor) - .with_reservoir_remaining(5_000) } /// The three ledgers add up to the raw spend; the receipt figure is the spend less the refund. #[test] fn test_ledgers_split_the_raw_spend() { - let gas = MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000, 125); + let gas = + MegaGasUsage::new(&result_gas(100_000, 30_000, 4_000, 21_000), 10_000, 125, 5_000); assert_eq!(gas.regular, 60_000); assert_eq!(gas.state, 30_000); assert_eq!(gas.history, 10_000); assert_eq!(gas.history_bytes, 125, "a byte count, carried as it was given"); assert_eq!(gas.regular + gas.state + gas.history, 100_000); - assert_eq!(gas.reservoir_remaining, 5_000); + assert_eq!(gas.reservoir_remaining, 5_000, "carried as it was given"); assert_eq!(gas.gas_used, 96_000); assert_eq!(gas.block_execution_gas(), 60_000); } @@ -179,7 +188,7 @@ mod tests { /// The floor binds the receipt figure and the block's execution gas, not the ledgers. #[test] fn test_floor_binds_receipt_and_block_execution_gas() { - let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000, 0); + let gas = MegaGasUsage::new(&result_gas(50_000, 20_000, 10_000, 45_000), 5_000, 0, 0); assert_eq!(gas.regular, 25_000); assert_eq!(gas.floor, 45_000); assert_eq!(gas.gas_used, 45_000); diff --git a/crates/mega-evm/src/evm/schedule.rs b/crates/mega-evm/src/evm/schedule.rs index 793908eac..f4c1da8b2 100644 --- a/crates/mega-evm/src/evm/schedule.rs +++ b/crates/mega-evm/src/evm/schedule.rs @@ -2,16 +2,28 @@ //! //! Satin takes the Amsterdam schedule — the one that carries EIP-8037 state gas, EIP-8038's //! state-access prices, the EIP-2780 intrinsic decomposition, the EIP-7976 calldata floor and -//! EIP-7981 access-list data — and changes exactly two things: +//! EIP-7981 access-list data — and changes exactly four things: //! //! 1. the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte //! ([`STATE_GAS_REPRICED`]), which is what makes the state dimension `MegaETH`'s rather than //! Glamsterdam's; -//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), the one entry outside -//! Amsterdam's table: upstream leaves it at zero, and Satin gives it the cost of one history -//! byte, which is what makes a deployment pay for the bytes every node has to carry. +//! 2. the history price of deposited code ([`HISTORY_GAS_PRICED`]), and the history allowance a +//! value-transferring call gives the frame it starts, the entries outside Amsterdam's table: +//! upstream leaves them at zero, and Satin gives deposited code the cost of one history byte per +//! byte, which is what makes a deployment pay for the bytes every node has to carry, and the +//! allowance the cost of [`HISTORY_ALLOWANCE_BYTES`]; +//! 3. the share of its caller's pools — data size, KV updates, state growth — and of its caller's +//! EIP-8037 reservoir a frame starts with: upstream forwards the whole of each, and Satin's +//! caller keeps [`FRAME_KEPT_PERCENT`] of what it has left (`GasId::pool_kept_percent`, +//! `GasId::reservoir_kept_percent`). The fork rounds the two differently, as the spec does: a +//! pool's share is `floor(remaining × 98 / 100)`, and the reservoir's `remaining − remaining × 2 +//! / 100`, so a caller keeps nothing of a reservoir below 50. The transaction's own frame and a +//! system call's outermost frame take the whole reservoir; +//! 4. the regular gas a call or creation forwards: at most `remaining − remaining × 2 / 100` of +//! what its caller has left, Rex6's rule, in place of EIP-150's 63/64 +//! ([`FORWARD_REDUCTION_QUOTIENT`], the fork's `GasId::call_stipend_reduction`). //! -//! Every regular-gas entry is Amsterdam's, so state creation is split between the two dimensions +//! Every regular-gas price is Amsterdam's, so state creation is split between the two dimensions //! as Amsterdam splits it: the regular part is the access and write work EIP-8038 prices, and the //! new state itself is state gas alone. A value `CALL` that creates its recipient pays the 11,300 //! of its value transfer, which carries the account write, and no new-account regular gas; a @@ -37,7 +49,16 @@ use revm::{ primitives::{eip8037, hardfork::SpecId, OnceLock}, }; -use crate::evm::prices::{active_satin_prices, SatinPrices}; +use crate::{ + evm::{ + history::HISTORY_ALLOWANCE_BYTES, + prices::{active_satin_prices, SatinPrices}, + }, + limit::{ + DATA_SIZE_POOL, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, KV_UPDATE_POOL, + STATE_GROWTH_POOL, + }, +}; /// A schedule entry and the number of bytes it prices: the entry is that many bytes at a byte /// price. @@ -62,7 +83,27 @@ pub const STATE_GAS_REPRICED: &[ScheduleEntry] = &[ /// Deposited code is the one history charge the schedule prices, because it is the one revm makes /// itself: `return_create` writes the code and charges the entry for its length. Every other /// history charge is made by the engine, which prices its own byte counts (the `history` module). -pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[(GasId::code_deposit_history_gas, 1)]; +/// The allowance a value-transferring call gives the frame it starts is in the schedule because +/// revm's call instruction gives it, where it gives the call stipend; only a log the frame emits +/// draws on it ([`history_allowance_gas`](crate::history_allowance_gas)). +pub const HISTORY_GAS_PRICED: &[ScheduleEntry] = &[ + (GasId::code_deposit_history_gas, 1), + (GasId::call_history_allowance, HISTORY_ALLOWANCE_BYTES), +]; + +/// The part of its pool, in per cent, a caller keeps when it starts a frame, which starts with the +/// rest: its budget, [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what the +/// caller has left. revm's forward of a pool rounds the share down, as the budget's rule does. +pub(crate) const FRAME_KEPT_PERCENT: u64 = + 100 - FRAME_DATA_SHARE_NUMERATOR * 100 / FRAME_DATA_SHARE_DENOMINATOR; +const _: () = + assert!((FRAME_DATA_SHARE_NUMERATOR * 100).is_multiple_of(FRAME_DATA_SHARE_DENOMINATOR)); + +/// The quotient of EIP-150's reduction of the regular gas a call or creation forwards: the fork +/// forwards `remaining − remaining / quotient`, and 50 is Rex6's rule, +/// `remaining − remaining × 2 / 100`, in place of upstream's 64. +pub(crate) const FORWARD_REDUCTION_QUOTIENT: u64 = 100 / FRAME_KEPT_PERCENT; +const _: () = assert!(100 % FRAME_KEPT_PERCENT == 0); /// The Satin gas schedule at the prices in effect. /// @@ -87,7 +128,7 @@ pub fn satin_gas_params_history_exempt() -> GasParams { TABLE .get_or_init(|| { let mut params = satin_gas_params(); - params.override_gas(HISTORY_GAS_PRICED.iter().map(|&(id, _)| (id(), 0))); + params.override_gas([(GasId::code_deposit_history_gas(), 0)]); params }) .clone() @@ -111,6 +152,13 @@ pub fn satin_gas_params_at(prices: SatinPrices) -> GasParams { params.override_gas( HISTORY_GAS_PRICED.iter().map(|&(id, bytes)| (id(), prices.cphb.fixed_size_gas(bytes))), ); + params.override_gas([ + (GasId::pool_kept_percent(DATA_SIZE_POOL), FRAME_KEPT_PERCENT), + (GasId::pool_kept_percent(KV_UPDATE_POOL), FRAME_KEPT_PERCENT), + (GasId::pool_kept_percent(STATE_GROWTH_POOL), FRAME_KEPT_PERCENT), + (GasId::reservoir_kept_percent(), FRAME_KEPT_PERCENT), + (GasId::call_stipend_reduction(), FORWARD_REDUCTION_QUOTIENT), + ]); params } @@ -143,7 +191,12 @@ mod tests { for slot in 0..=u8::MAX { let id = GasId::new(slot); let rebuilt = STATE_GAS_REPRICED.iter().any(|&(entry, _)| entry() == id) || - HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id); + HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) || + id == GasId::pool_kept_percent(DATA_SIZE_POOL) || + id == GasId::pool_kept_percent(KV_UPDATE_POOL) || + id == GasId::pool_kept_percent(STATE_GROWTH_POOL) || + id == GasId::reservoir_kept_percent() || + id == GasId::call_stipend_reduction(); if rebuilt { continue; } @@ -218,22 +271,95 @@ mod tests { } } - /// The schedule an exempt transaction runs prices no history byte and is otherwise the same - /// table. + /// The schedule an exempt transaction runs prices no deposited byte and is otherwise the same + /// table: an exempt transaction is charged no history by the engine, so the allowance, which + /// only a history charge draws, is left as it is. #[test] fn test_the_exempt_schedule_only_drops_the_history_price() { let exempt = satin_gas_params_history_exempt(); let satin = satin_gas_params(); - assert_eq!(exempt.get(GasId::code_deposit_history_gas()), 0); + let id = GasId::code_deposit_history_gas(); + assert_eq!(exempt.get(id), 0); for slot in 0..=u8::MAX { - let id = GasId::new(slot); - if HISTORY_GAS_PRICED.iter().any(|&(entry, _)| entry() == id) { - continue; + let other = GasId::new(slot); + if other != id { + assert_eq!(exempt.get(other), satin.get(other), "{} must not move", other.name()); } - assert_eq!(exempt.get(id), satin.get(id), "{} must not move", id.name()); } } + /// A frame starts with 98 per cent of what its caller has left of its data-size, KV-update and + /// state-growth budgets, which revm forwards at every frame start as the schedule's share of + /// each pool, the caller keeping 2 per cent, rounded down as the budget's rule is; upstream + /// forwards the whole pool. + #[test] + fn test_a_frame_is_forwarded_98_percent_of_its_callers_pools() { + let satin = satin_gas_params(); + for id in [DATA_SIZE_POOL, KV_UPDATE_POOL, STATE_GROWTH_POOL] { + assert_eq!(satin.get(GasId::pool_kept_percent(id)), 2); + assert_eq!(amsterdam().get(GasId::pool_kept_percent(id)), 0); + for pool in [0, 1, 49, 50, 51, 99, 100, 101, 9_690, u64::MAX] { + let floor = (u128::from(pool) * 98 / 100) as u64; + assert_eq!(satin.pool_forward_share(id, pool), floor, "{pool}"); + } + } + } + + /// A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's + /// regular gas, Rex6's rule, which the fork's EIP-150 reduction gives with a quotient of 50; + /// upstream's is 64, the 63/64 rule. + #[test] + fn test_a_call_forwards_at_most_98_percent_of_its_callers_regular_gas() { + let satin = satin_gas_params(); + assert_eq!(satin.get(GasId::call_stipend_reduction()), 50); + assert_eq!(amsterdam().get(GasId::call_stipend_reduction()), 64); + for (remaining, forward) in + [(0, 0), (1, 1), (49, 49), (50, 49), (99, 98), (1_000, 980), (10_000, 9_800)] + { + assert_eq!(satin.call_stipend_reduction(remaining), forward, "{remaining}"); + } + assert_eq!(amsterdam().call_stipend_reduction(1_000), 985, "EIP-150's 63/64"); + assert_eq!(amsterdam().call_stipend_reduction(50), 50, "EIP-150's 63/64"); + } + + /// A frame starts with the reservoir its caller has left less the caller's 2 per cent, the + /// division truncating, so a caller keeps nothing of a reservoir below 50 and the child gets + /// 98 of 99; upstream forwards the whole reservoir. + #[test] + fn test_a_frame_is_forwarded_its_callers_reservoir_less_two_percent() { + let satin = satin_gas_params(); + assert_eq!(satin.get(GasId::reservoir_kept_percent()), 2); + assert_eq!(amsterdam().get(GasId::reservoir_kept_percent()), 0); + for (reservoir, share) in [ + (0, 0), + (1, 1), + (49, 49), + (50, 49), + (99, 98), + (100, 98), + (149, 147), + (1_000, 980), + (1_000_000, 980_000), + (u64::MAX, u64::MAX - u64::MAX / 50), + ] { + assert_eq!(satin.reservoir_forward_share(reservoir), share, "{reservoir}"); + assert_eq!(amsterdam().reservoir_forward_share(reservoir), reservoir, "{reservoir}"); + } + } + + /// The history allowance a value-transferring call gives the frame it starts is + /// [`HISTORY_ALLOWANCE_BYTES`] at the cost per history byte, the same figure the engine + /// prices its history at; Osaka and Amsterdam give none. + #[test] + fn test_a_value_call_is_given_the_history_allowance() { + let id = GasId::call_history_allowance(); + assert_eq!(satin_gas_params().get(id), crate::history_allowance_gas()); + let constants = satin_gas_params_at(SatinPrices::CONSTANTS); + assert_eq!(constants.get(id), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(osaka().get(id), 0); + assert_eq!(amsterdam().get(id), 0); + } + /// Deposited code costs one history byte per byte, which is the whole of Satin's history /// schedule. Osaka and Amsterdam price no history byte at all. #[test] @@ -284,6 +410,7 @@ mod tests { (GasId::code_deposit_state_gas(), 313), (GasId::tx_eip7702_state_gas_bytecode(), 7_188), (GasId::code_deposit_history_gas(), 400), + (GasId::call_history_allowance(), 160 * 400), ]; for slot in 0..=u8::MAX { let id = GasId::new(slot); diff --git a/crates/mega-evm/src/evm/validation.rs b/crates/mega-evm/src/evm/validation.rs index 60d72f154..855f77da0 100644 --- a/crates/mega-evm/src/evm/validation.rs +++ b/crates/mega-evm/src/evm/validation.rs @@ -144,11 +144,10 @@ pub fn validate_transaction_stateless( let handler = MegaHandler::<_, MegaEvmError, EthFrame>::new(); handler.validate_env_as(&mut evm, system_address, false)?; let gas = handler.validate_initial_tx_gas(&mut evm)?; - let history = evm.ctx().additional_limit.intrinsic_history_gas(); Ok(IntrinsicGas { regular: gas.initial_regular_gas(), - state: gas.initial_state_gas_final() - history, - history, + state: gas.initial_state_gas_final(), + history: evm.ctx().additional_limit.intrinsic_history_gas(), floor: gas.floor_gas(), }) } diff --git a/crates/mega-evm/src/lib.rs b/crates/mega-evm/src/lib.rs index 28f859579..8bd049186 100644 --- a/crates/mega-evm/src/lib.rs +++ b/crates/mega-evm/src/lib.rs @@ -32,13 +32,12 @@ pub use access::{ VolatileDataAccess, }; pub use block::{ - chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, - pre_block_call_gas_limit, read_l1_block_info, testnet_hardforks, - transact_beacon_root_contract_call, transact_blockhashes_contract_call, BlockGasCounters, - BlockLimiter, BlockLimits, BlockUsage, ChainActivation, EnrichedMegaTx, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaBlockExecutionResult, MegaBlockExecutor, MegaBlockExecutorFactory, - MegaBlockLimitExceededError, MegaBlockTxResult, MegaFinishedBlock, MegaHardfork, - MegaHardforkConfig, MegaHardforks, MegaTransactionExt, MegaTxLimitExceededError, + chain_activation, estimated_da_size, hardfork_schedule, mainnet_hardforks, read_l1_block_info, + testnet_hardforks, transact_beacon_root_contract_call, transact_blockhashes_contract_call, + BlockGasCounters, BlockLimiter, BlockLimits, BlockUsage, ChainActivation, EnrichedMegaTx, + MegaBlockExecutionCtx, MegaBlockExecutionError, MegaBlockExecutionResult, MegaBlockExecutor, + MegaBlockExecutorFactory, MegaBlockLimitExceededError, MegaBlockTxResult, MegaFinishedBlock, + MegaHardfork, MegaHardforkConfig, MegaHardforks, MegaTransactionExt, MegaTxLimitExceededError, ProtocolLimits, SatinChainConfig, SatinChainConfigError, ScheduleError, CHAIN_ACTIVATIONS, L1_BLOCK_INFO_SLOTS, MAINNET_CHAIN_ID, SATIN_CHAIN_CONFIG_KEYS, SATIN_TIME_KEY, SYSTEM_ADDRESS, TESTNET_CHAIN_ID, @@ -46,16 +45,16 @@ pub use block::{ #[cfg(feature = "satin-price-override")] pub use evm::install_satin_prices; pub use evm::{ - active_satin_prices, history_gas, kzg_point_evaluation, name, satin_gas_params, - satin_gas_params_at, satin_gas_params_history_exempt, satin_precompiles, satin_precompiles_map, - settle_frame_result, spec_cfg, storage_call_stipend, synthetic_call_result, - synthetic_frame_result, transaction_body_bytes, tx_body_history_bytes, untouched_call_gas, - untouched_create_gas, validate_transaction_stateless, with_pools_of, write_record_history_gas, - BlockHashRecord, BucketRecord, BytePrice, DeclaredObserver, DynPrecompilesBuilder, EthSpecId, - IntrinsicGas, MegaContext, MegaEvm, MegaEvmError, MegaEvmFactory, MegaGasUsage, MegaHandler, - MegaSpecId, MegaTransactionOutcome, OpSpecId, OracleRead, OracleReadRecord, ParseMegaSpecError, - SatinPriceError, SatinPrices, TrustedObserver, CPHB_ENV_VAR, CPSB_ENV_VAR, HISTORY_GAS_PRICED, - LEGACY_SPEC_NAMES, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, + active_satin_prices, history_allowance_gas, history_gas, kzg_point_evaluation, name, + satin_gas_params, satin_gas_params_at, satin_gas_params_history_exempt, satin_precompiles, + satin_precompiles_map, spec_cfg, synthetic_call_result, synthetic_frame_result, + transaction_body_bytes, tx_body_history_bytes, untouched_call_gas, untouched_create_gas, + validate_transaction_stateless, write_record_history_gas, BlockHashRecord, BucketRecord, + BytePrice, DynPrecompilesBuilder, EthSpecId, IntrinsicGas, MegaContext, MegaEvm, MegaEvmError, + MegaEvmFactory, MegaGasUsage, MegaHandler, MegaSpecId, MegaTransactionOutcome, OpSpecId, + OracleRead, OracleReadRecord, ParseMegaSpecError, SatinPriceError, SatinPrices, CPHB_ENV_VAR, + CPSB_ENV_VAR, HISTORY_ALLOWANCE_BYTES, HISTORY_GAS_PRICED, LEGACY_SPEC_NAMES, + STATE_GAS_REPRICED, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; #[cfg(any(test, feature = "test-utils"))] pub use external::{ @@ -67,7 +66,7 @@ pub use external::{ }; pub use limit::{ decode_mega_limit_exceeded, log_history_bytes, AdditionalLimit, EvmTxRuntimeLimits, LimitCheck, - LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, StagedRecord, ACCESS_LIST_ADDRESS_SIZE, + LimitKind, LimitStop, LimitUsage, MegaLimitExceeded, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, @@ -79,7 +78,7 @@ pub use types::{ /* Items the crate's modules share through the root, not part of the public surface */ pub(crate) use block::transact_pre_block_call; pub(crate) use evm::{ - charge_write_records_history, MegaInnerContext, MegaInstructions, PricedPrecompiles, + charge_write_records_history, hold_creator, MegaInstructions, PricedPrecompiles, }; /* Re-export of upstream crates, so consumers build against the exact versions used here */ diff --git a/crates/mega-evm/src/limit/frame_limit.rs b/crates/mega-evm/src/limit/frame_limit.rs deleted file mode 100644 index 6c6d19214..000000000 --- a/crates/mega-evm/src/limit/frame_limit.rs +++ /dev/null @@ -1,706 +0,0 @@ -//! The per-frame tracker of data-size bytes and write records. -//! -//! Every frame on the call stack has a lane. What a frame writes is counted on its lane; when the -//! frame returns, a success merges the lane into its caller's and a failure discards it, the way -//! the journal keeps or reverts the writes themselves. What is counted outside any frame (the -//! records of applied EIP-7702 authorities) and what the outermost frame kept sit on the -//! transaction's own lane. -//! -//! The history bytes a frame appends beside its write records — its logs, and the code it -//! deposits when it is a creation — ride on the same lanes and follow the same rule, so what a -//! transaction reports it appended is what it kept. -//! -//! Every operation is O(1): the totals are cached and kept in step with each change. - -#[cfg(not(feature = "std"))] -use alloc as std; -use std::vec::Vec; - -use alloy_primitives::Address; - -use super::{LimitUsage, WRITE_RECORD}; - -/// One frame's lane. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Lane { - /// History gas the caller paid for the records on this lane, which the frame's failure gives - /// back to it. - pub(crate) history_charge: u64, - /// History gas the caller paid for the record of its own account - /// ([`holds_caller_record`](Self::holds_caller_record)), which follows that record's own - /// lifetime: a value transfer's sender record dies with the frame, a creation's nonce record - /// outlives it. - pub(crate) caller_history_charge: u64, - /// Whether the writes this lane stands for were recorded at all. False for a frame answered - /// without running, whose caller paid for records nothing ever made. - pub(crate) records_made: bool, - /// What the frame, and the children it kept, counted. - pub(crate) used: LimitUsage, - /// What the frame, and the children it kept, took back: a slot written back to its original - /// value. - pub(crate) refund: LimitUsage, - /// The account the frame runs as. `None` until known (a creation learns it at frame init). - pub(crate) address: Option
, - /// Whether a write to the frame's own account is already counted, so a value transfer or a - /// creation from the frame does not count it again. - pub(crate) account_recorded: bool, - /// Whether this lane holds the record of its caller's account, made when the frame started - /// (a value transfer's sender, a creation's creator). Its failure discards that record, so the - /// caller's account is no longer recorded either. - pub(crate) holds_caller_record: bool, - /// Whether the caller's record on this lane is a creator's nonce, which survives the - /// creation's failure once the nonce was bumped. - pub(crate) creator_record: bool, - /// The most data-size bytes the frame may keep, `u64::MAX` where the frame has no budget. - pub(crate) budget: u64, - /// What is left of the history allowance this frame was granted, if it was granted one. It - /// never enters the frame's gas, and what it does not spend disappears with the frame. - pub(crate) stipend_remaining: u64, - /// The history bytes the frame, and the children it kept, appended that are not write - /// records: the logs it emitted and, when it is a creation, the code it deposits. Its write - /// records are history too, and are counted in [`used`](Self::used), as are these bytes. - pub(crate) log_and_code_bytes: u64, -} - -impl Lane { - /// A lane for a frame running as `address`, whose caller paid `history_charge` for the - /// records the frame's start makes on it. - pub(crate) const fn new( - address: Option
, - account_recorded: bool, - budget: u64, - history_charge: u64, - ) -> Self { - Self { - used: LimitUsage::ZERO, - refund: LimitUsage::ZERO, - history_charge, - caller_history_charge: 0, - records_made: true, - address, - account_recorded, - holds_caller_record: false, - creator_record: false, - budget, - stipend_remaining: 0, - log_and_code_bytes: 0, - } - } - - /// A lane for a frame that does not run: a result built without an interpreter. Its caller - /// paid `history_charge` for records nothing made, so all of it comes back. - pub(crate) const fn empty(history_charge: u64) -> Self { - Self { records_made: false, ..Self::new(None, false, u64::MAX, history_charge) } - } - - /// The history gas the caller gets back when this frame returns. - /// - /// Everything, when the writes were never recorded; what the frame's failure discards, when - /// they were; nothing, when the frame kept them. A creation's nonce record survives the - /// creation's failure, so the caller keeps paying for it. - pub(crate) const fn history_refund(&self, success: bool) -> u64 { - if !self.records_made { - return self.history_charge.saturating_add(self.caller_history_charge); - } - if success { - return 0; - } - if self.creator_record { - self.history_charge - } else { - self.history_charge.saturating_add(self.caller_history_charge) - } - } - - /// Whether the frame's return hands its caller what no check held the caller to: a failed - /// creation's nonce record, which outlives it and lands on the creator's lane - /// ([`FrameLimitTracker::pop`]), or a success past the frame's own budget, which no frame - /// returns — a frame past its budget failed, and a failure an inspector rewrites into a success - /// has its lane discarded first ([`FrameLimitTracker::discard_running_lane`]) — and which is - /// held all the same. - /// - /// Any other return hands the caller nothing, or what the frame kept within its budget, which - /// is at most the share of what the caller had left. - pub(crate) const fn hands_caller_unchecked(&self, success: bool) -> bool { - if success { - // A lane that stands in for a creation's discarded one carries its creator's nonce - // record, which the discard already landed on the creator. - self.net().exceeds_data_size(self.budget) || (!self.records_made && self.creator_record) - } else { - self.creator_record - } - } - - /// What the frame keeps if it succeeds. - pub(crate) const fn net(&self) -> LimitUsage { - self.used.saturating_sub(self.refund) - } - - /// The data-size bytes the frame may still keep. - pub(crate) const fn remaining_budget(&self) -> u64 { - self.budget.saturating_sub(self.net().data_size) - } -} - -/// The lanes of the running transaction. -#[derive(Clone, Debug, Default)] -pub(crate) struct FrameLimitTracker { - /// What the transaction counted outside any running frame, and what the outermost frame kept. - tx_used: LimitUsage, - /// What the outermost frame kept of its refunds. - tx_refund: LimitUsage, - /// One lane per frame on the call stack, the running frame last. - lanes: Vec, - /// `tx_used` plus every lane's `used`. - total_used: LimitUsage, - /// `tx_refund` plus every lane's `refund`. - total_refund: LimitUsage, - /// The log and code bytes the outermost frame kept, plus every lane's. - log_and_code_bytes: u64, -} - -impl FrameLimitTracker { - /// Clears the tracker for a new transaction, keeping its allocation. - pub(crate) fn reset(&mut self) { - self.tx_used = LimitUsage::ZERO; - self.tx_refund = LimitUsage::ZERO; - self.lanes.clear(); - self.total_used = LimitUsage::ZERO; - self.total_refund = LimitUsage::ZERO; - self.log_and_code_bytes = 0; - } - - /// The number of lanes, which is the number of frames on the call stack. - pub(crate) fn depth(&self) -> usize { - self.lanes.len() - } - - /// What the transaction keeps if every running frame succeeds. - pub(crate) const fn net(&self) -> LimitUsage { - self.total_used.saturating_sub(self.total_refund) - } - - /// The history bytes the transaction appended beside its write records — its logs and the - /// code it deposited — with every running frame counted as if it succeeds. - pub(crate) const fn log_and_code_bytes(&self) -> u64 { - self.log_and_code_bytes - } - - /// The running frame's lane. - pub(crate) fn current(&self) -> Option<&Lane> { - self.lanes.last() - } - - /// The running frame's lane, mutably. - pub(crate) fn current_mut(&mut self) -> Option<&mut Lane> { - self.lanes.last_mut() - } - - /// Grants the running frame a history allowance of `amount`. - /// - /// Must run right after the frame's lane was pushed: the allowance belongs to the frame that - /// is starting, not to the one that granted it. - pub(crate) fn grant_stipend(&mut self, amount: u64) { - if let Some(lane) = self.lanes.last_mut() { - lane.stipend_remaining = amount; - } - } - - /// Draws up to `amount` from the running frame's allowance and reports what it gave. The - /// caller pays the rest out of the frame's gas. - pub(crate) fn consume_stipend(&mut self, amount: u64) -> u64 { - let Some(lane) = self.lanes.last_mut() else { return 0 }; - let drawn = lane.stipend_remaining.min(amount); - lane.stipend_remaining -= drawn; - drawn - } - - /// Pushes the lane of a frame that starts. - pub(crate) fn push(&mut self, lane: Lane) { - self.total_used = self.total_used.saturating_add(lane.used); - self.total_refund = self.total_refund.saturating_add(lane.refund); - self.lanes.push(lane); - } - - /// Counts `usage` on the running frame's lane, or on the transaction's outside any frame. - pub(crate) fn record(&mut self, usage: LimitUsage) { - match self.lanes.last_mut() { - Some(lane) => lane.used = lane.used.saturating_add(usage), - None => self.tx_used = self.tx_used.saturating_add(usage), - } - self.total_used = self.total_used.saturating_add(usage); - } - - /// Counts `bytes` of a log or of deposited code on the running frame's lane, or on the - /// transaction's outside any frame. - pub(crate) fn record_log_and_code_bytes(&mut self, bytes: u64) { - if let Some(lane) = self.lanes.last_mut() { - lane.log_and_code_bytes = lane.log_and_code_bytes.saturating_add(bytes); - } - self.log_and_code_bytes = self.log_and_code_bytes.saturating_add(bytes); - } - - /// Counts `usage` on the transaction's own lane, whatever frame is running: what it stands - /// for is outside the state, so no frame's failure takes it back. - pub(crate) fn record_tx(&mut self, usage: LimitUsage) { - self.tx_used = self.tx_used.saturating_add(usage); - self.total_used = self.total_used.saturating_add(usage); - } - - /// Takes `usage` back on the running frame's lane. Outside any frame nothing is taken back. - pub(crate) fn refund(&mut self, usage: LimitUsage) { - if let Some(lane) = self.lanes.last_mut() { - lane.refund = lane.refund.saturating_add(usage); - self.total_refund = self.total_refund.saturating_add(usage); - } - } - - /// Records the running frame's caller's account on the running frame's lane, unless the - /// caller's lane already counts it. A `creator` record is a creation's nonce, and - /// `history_charge` is what the caller paid for the record. - /// - /// Must run right after the running frame's lane was pushed, with the caller's lane below it. - pub(crate) fn record_caller(&mut self, creator: bool, history_charge: u64) { - let [.., caller, lane] = self.lanes.as_mut_slice() else { return }; - if caller.account_recorded { - return; - } - caller.account_recorded = true; - lane.holds_caller_record = true; - lane.creator_record = creator; - lane.caller_history_charge = history_charge; - lane.used = lane.used.saturating_add(WRITE_RECORD); - self.total_used = self.total_used.saturating_add(WRITE_RECORD); - } - - /// Settles the running frame's lane as its failure would, before the frame returns: what it - /// counted is discarded, its caller's record with it, and an empty lane stands in for it, - /// holding the history its caller gets back for records the failure did not keep. So the frame - /// returns into its caller as a frame that made nothing, whatever it is popped with. - /// - /// For a frame whose journal checkpoint was reverted and whose result then became a success - /// all the same: the lane follows the checkpoint, not the result. - /// - /// A creation's nonce record outlives its failure, so it has landed on the creator's lane - /// unchecked, and the stand-in remembers it: the creator is held to its budget when the - /// stand-in returns, as it is when the creation fails. - pub(crate) fn discard_running_lane(&mut self) { - let Some(lane) = self.pop(false) else { return }; - let mut standing_in = Lane::empty(lane.history_refund(false)); - standing_in.creator_record = lane.creator_record; - self.lanes.push(standing_in); - } - - /// Takes the record of the running frame's own account back from its lane, where a child - /// left it: the nonce record of a creation that failed, whose bump is being taken back. - /// Returns whether the account was recorded, and so whether there was a record to take. - pub(crate) fn take_back_own_record(&mut self) -> bool { - let Some(lane) = self.lanes.last_mut() else { return false }; - if !lane.account_recorded { - return false; - } - lane.account_recorded = false; - lane.used = lane.used.saturating_sub(WRITE_RECORD); - self.total_used = self.total_used.saturating_sub(WRITE_RECORD); - true - } - - /// Pops the lane of the frame that returned: `success` merges it into its caller's lane (or - /// the transaction's), a failure discards it. - /// - /// A creator's record outlives the creation's failure and lands on the caller's lane, which - /// nothing here holds to its budget; any other record of the caller dies with it, and the - /// caller's account stops counting as recorded. - #[inline] - pub(crate) fn pop(&mut self, success: bool) -> Option { - let lane = self.lanes.pop()?; - if success { - match self.lanes.last_mut() { - Some(caller) => { - caller.used = caller.used.saturating_add(lane.used); - caller.refund = caller.refund.saturating_add(lane.refund); - caller.log_and_code_bytes = - caller.log_and_code_bytes.saturating_add(lane.log_and_code_bytes); - if lane.address.is_some() && lane.address == caller.address { - caller.account_recorded |= lane.account_recorded; - } - } - None => { - self.tx_used = self.tx_used.saturating_add(lane.used); - self.tx_refund = self.tx_refund.saturating_add(lane.refund); - } - } - return Some(lane); - } - self.total_used = self.total_used.saturating_sub(lane.used); - self.total_refund = self.total_refund.saturating_sub(lane.refund); - self.log_and_code_bytes = self.log_and_code_bytes.saturating_sub(lane.log_and_code_bytes); - if let Some(caller) = self.lanes.last_mut() { - if lane.creator_record { - caller.used = caller.used.saturating_add(WRITE_RECORD); - self.total_used = self.total_used.saturating_add(WRITE_RECORD); - } else if lane.holds_caller_record { - caller.account_recorded = false; - } - } - Some(lane) - } - - /// Whether the return of `returned`, the lane just popped with `success`, handed the running - /// frame what no check held it to ([`Lane::hands_caller_unchecked`]). - /// - /// A return into no lane hands nothing that needs holding: what the transaction's own frame - /// keeps goes to the transaction, which has no budget of its own and whose total the return - /// does not grow, and no frame runs on after it. - pub(crate) fn hands_unchecked(&self, returned: &Lane, success: bool) -> bool { - !self.lanes.is_empty() && returned.hands_caller_unchecked(success) - } - - /// [`net`](Self::net) recomputed from the lanes, for checking the cache. - #[cfg(test)] - pub(crate) fn net_uncached(&self) -> LimitUsage { - let mut used = self.tx_used; - let mut refund = self.tx_refund; - for lane in &self.lanes { - used = used.saturating_add(lane.used); - refund = refund.saturating_add(lane.refund); - } - used.saturating_sub(refund) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use alloy_primitives::address; - - const ADDR: Address = address!("0000000000000000000000000000000000001234"); - - const fn bytes(data_size: u64) -> LimitUsage { - LimitUsage { data_size, write_records: 0 } - } - - /// The depth and the running lane follow the frame stack: a push adds a lane and a pop takes - /// the running one away, whatever the frame's outcome. - #[test] - fn test_depth_and_the_running_lane_follow_the_frame_stack() { - let mut t = FrameLimitTracker::default(); - assert_eq!(t.depth(), 0); - assert!(t.current().is_none(), "no frame has started"); - t.push(Lane::new(Some(ADDR), false, 7, 0)); - t.push(Lane::empty(0)); - assert_eq!(t.depth(), 2); - assert_eq!(t.current().unwrap().address, None, "the empty lane is the running one"); - assert!(t.pop(false).is_some()); - assert_eq!(t.depth(), 1); - assert_eq!(t.current().unwrap().budget, 7); - assert!(t.pop(true).is_some()); - assert_eq!(t.depth(), 0); - assert!(t.current().is_none()); - assert!(t.pop(true).is_none(), "there is nothing left to pop"); - } - - /// Recording a caller on an empty stack, or on a lane with no caller below it, is a no-op. - #[test] - fn test_record_caller_without_a_caller_lane_is_noop() { - let mut t = FrameLimitTracker::default(); - t.record_caller(true, 0); - assert_eq!(t.net(), LimitUsage::ZERO); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_caller(true, 0); - assert_eq!(t.net(), LimitUsage::ZERO); - assert!(!t.current().unwrap().holds_caller_record); - } - - /// A frame's caller is recorded once per caller frame: a second child finds it recorded. - #[test] - fn test_record_caller_records_a_caller_once() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - assert!(t.pop(true).is_some()); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - assert!(!t.current().unwrap().holds_caller_record, "the caller is recorded already"); - assert_eq!(t.net(), WRITE_RECORD); - } - - /// The cached totals match the lanes after every push, record, refund and pop. - #[test] - fn test_net_usage_cache_matches_uncached() { - let mut t = FrameLimitTracker::default(); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), LimitUsage::ZERO); - - // Outside any frame, usage goes to the transaction and nothing is taken back. - t.record(bytes(100)); - t.refund(bytes(50)); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(100)); - - // Frame 1. - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(30)); - t.refund(bytes(10)); - assert_eq!(t.net(), t.net_uncached()); - - // Frame 2, nested. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(15)); - t.refund(bytes(3)); - assert_eq!(t.net(), t.net_uncached()); - - // Frame 3 fails: its usage and refund leave the totals. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(11)); - t.refund(bytes(2)); - let before_revert = t.net(); - let popped = t.pop(false).expect("frame 3 popped"); - assert_eq!((popped.used, popped.refund), (bytes(11), bytes(2))); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(before_revert.data_size - 9)); - - // Frame 3 again, succeeding: merging moves usage, the totals do not change. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(6)); - t.refund(bytes(1)); - let before_success = t.net(); - t.pop(true); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), before_success); - - // Frame 2 succeeds into frame 1; frame 1 fails. - t.pop(true); - assert_eq!(t.net(), t.net_uncached()); - let frame_1 = t.pop(false).expect("frame 1 popped"); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), bytes(100), "only the transaction's own usage is left"); - assert_eq!(frame_1.net(), bytes(30 + 15 + 6 - 10 - 3 - 1)); - - t.reset(); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.depth(), 0); - } - - /// Log and code bytes follow the frame that appended them: a running frame counts as if it - /// succeeds, a success hands them to its caller, a failure discards them, and what was - /// counted outside any frame is the transaction's. - #[test] - fn test_log_and_code_bytes_follow_their_frame() { - let mut t = FrameLimitTracker::default(); - t.record_log_and_code_bytes(5); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_log_and_code_bytes(10); - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_log_and_code_bytes(100); - assert_eq!(t.log_and_code_bytes(), 115); - - let failed = t.pop(false).expect("the child popped"); - assert_eq!(failed.log_and_code_bytes, 100); - assert_eq!(t.log_and_code_bytes(), 15, "the failed child's bytes are gone"); - - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_log_and_code_bytes(20); - t.pop(true); - assert_eq!(t.log_and_code_bytes(), 35); - assert_eq!( - t.current().unwrap().log_and_code_bytes, - 30, - "the kept child's are its caller's" - ); - - t.pop(false); - assert_eq!(t.log_and_code_bytes(), 5, "only what was outside the outermost frame is left"); - - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record_log_and_code_bytes(7); - t.pop(true); - assert_eq!(t.log_and_code_bytes(), 12, "the outermost frame's success keeps its bytes"); - - t.reset(); - assert_eq!(t.log_and_code_bytes(), 0); - } - - /// A refund larger than the usage clamps the net at zero. - #[test] - fn test_net_usage_saturates_when_refund_exceeds_used() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record(bytes(10)); - t.refund(bytes(100)); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.net(), t.net_uncached()); - t.pop(true); - assert_eq!(t.net(), LimitUsage::ZERO); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A value transfer's sender record dies with the child that failed, and the caller can be - /// recorded again; a creator's record survives the creation's failure. - #[test] - fn test_failed_child_discards_sender_record_but_keeps_creator_record() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(false, 0); - t.record(WRITE_RECORD); - t.pop(false); - assert_eq!(t.net(), LimitUsage::ZERO); - assert!(!t.current().unwrap().account_recorded, "the sender record died with the child"); - - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - t.record(WRITE_RECORD); - t.pop(false); - assert_eq!(t.net(), WRITE_RECORD, "the creator's nonce outlives the creation"); - assert!(t.current().unwrap().account_recorded); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A return hands its caller what no check held the caller to in two cases: the nonce record - /// a failed creation leaves its creator, and a success past the frame's own budget. A success - /// within its budget hands over no more than that budget, and any other failure hands over - /// nothing. - #[test] - fn test_what_a_return_hands_its_caller_unchecked() { - let budget = 200; - // The record of the caller's account the child holds (a creator's or a sender's), the - // bytes it counted beside it, and whether it succeeded. - for (creator, counted, success, unchecked) in [ - (false, 160, true, false), - (true, 160, true, false), - (false, 161, true, true), - (false, 161, false, false), - (false, 0, false, false), - (true, 0, false, true), - ] { - let case = format!("creator {creator}, {counted} bytes, success {success}"); - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(None, true, budget, 0)); - t.record_caller(creator, 0); - t.record(bytes(counted)); - let lane = t.pop(success).unwrap(); - assert_eq!(lane.hands_caller_unchecked(success), unchecked, "{case}"); - let handed = t.net(); - let past_budget = handed.exceeds_data_size(budget); - if success { - assert_eq!(past_budget, unchecked, "{case}: a success hands over what it kept"); - } else { - assert_eq!(handed != LimitUsage::ZERO, unchecked, "{case}: a failure, the record"); - } - } - } - - /// The return of the transaction's own frame hands nothing unchecked, whatever it kept: there - /// is no lane left to hand it to. With a frame below it, the same return does. - #[test] - fn test_a_return_into_no_lane_hands_nothing_unchecked() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, 200, 0)); - t.record(bytes(201)); - let lane = t.pop(true).unwrap(); - assert!(lane.hands_caller_unchecked(true), "it kept more than its budget"); - assert!(!t.hands_unchecked(&lane, true), "but no frame is left to hand it to"); - - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - assert!(t.hands_unchecked(&lane, true), "a caller is"); - assert!(!t.hands_unchecked(&lane, false), "which a failure hands nothing"); - } - - /// A lane discarded before its frame returns keeps nothing, whatever it is popped with: what - /// it counted leaves the totals, its caller's account stops counting as recorded, and the - /// empty lane in its place hands the caller back what the failure gives back — here the - /// charges for the lane's record and for the caller's own. - #[test] - fn test_a_discarded_lane_keeps_nothing_and_gives_the_failures_history_back() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(10)); - t.push(Lane::new(None, false, 100, 7)); - t.record_caller(false, 3); - t.record(WRITE_RECORD); - t.record_log_and_code_bytes(5); - t.discard_running_lane(); - - assert_eq!(t.depth(), 2, "an empty lane stands in for the frame"); - let lane = *t.current().unwrap(); - assert!(!lane.records_made); - assert_eq!(lane.used, LimitUsage::ZERO); - assert_eq!(lane.address, None); - assert_eq!(lane.budget, u64::MAX); - assert_eq!(t.net(), bytes(10), "only the caller's count is left"); - assert_eq!(t.net(), t.net_uncached()); - assert_eq!(t.log_and_code_bytes(), 0); - assert!(!t.lanes[0].account_recorded, "the caller's record went with the frame"); - - let popped = t.pop(true).unwrap(); - assert_eq!(popped.history_refund(true), 7 + 3, "the lane's record and the caller's"); - assert!(!t.hands_unchecked(&popped, true), "it hands nothing"); - assert_eq!(t.net(), bytes(10)); - - // A creator's nonce record outlives the creation: the discard lands it on the creator, - // and the history the creator paid for it is not given back. - t.push(Lane::new(None, false, u64::MAX, 0)); - t.record_caller(true, 4); - t.discard_running_lane(); - assert_eq!(t.net(), bytes(10).saturating_add(WRITE_RECORD)); - let popped = t.pop(true).unwrap(); - assert_eq!(popped.history_refund(true), 0); - assert!(t.hands_unchecked(&popped, true), "the creator is held to its budget with it"); - - // With no lane to discard, nothing happens. - let mut empty = FrameLimitTracker::default(); - empty.discard_running_lane(); - assert_eq!(empty.depth(), 0); - } - - /// The creator record a failed creation left its creator is taken back once, and a lane with - /// no record of its own account has nothing to take. - #[test] - fn test_take_back_own_record_takes_the_creator_record_once() { - let mut t = FrameLimitTracker::default(); - assert!(!t.take_back_own_record(), "no lane"); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.record(bytes(7)); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.record_caller(true, 0); - t.pop(false); - assert_eq!(t.net(), bytes(7).saturating_add(WRITE_RECORD)); - - assert!(t.take_back_own_record()); - assert_eq!(t.net(), bytes(7), "the record, and nothing else, is gone"); - assert!(!t.current().unwrap().account_recorded); - assert!(!t.take_back_own_record(), "taken once"); - assert_eq!(t.net(), bytes(7)); - assert_eq!(t.net(), t.net_uncached()); - } - - /// A child running as its caller's account hands its record flag back on success. - #[test] - fn test_same_account_child_merges_the_recorded_flag() { - let mut t = FrameLimitTracker::default(); - t.push(Lane::new(Some(ADDR), false, u64::MAX, 0)); - t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); - t.pop(true); - assert!(t.current().unwrap().account_recorded); - - let other = address!("0000000000000000000000000000000000005678"); - t.push(Lane::new(Some(other), false, u64::MAX, 0)); - t.push(Lane::new(Some(other), false, u64::MAX, 0)); - t.current_mut().unwrap().account_recorded = true; - t.pop(false); - assert!(!t.current().unwrap().account_recorded, "a failed child hands nothing back"); - - t.push(Lane::new(Some(ADDR), true, u64::MAX, 0)); - assert_eq!(t.depth(), 3); - t.pop(true); - assert!(!t.current().unwrap().account_recorded, "another account's flag is its own"); - t.push(Lane::new(None, true, u64::MAX, 0)); - t.pop(true); - assert!(!t.current().unwrap().account_recorded, "an unknown account is not the caller's"); - } -} diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 6cc04a504..4e772df15 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -1,62 +1,87 @@ //! The per-transaction state of the common execution layer. -use alloy_primitives::{Address, Bytes}; +use alloy_primitives::Bytes; use revm::{ - context_interface::context::CodeDeposit, + context_interface::cfg::gas::{GasTracker, PoolAmounts, PoolId}, handler::FrameResult, - interpreter::{CallInputs, CallScheme, FrameInput, InstructionResult}, + interpreter::InstructionResult, }; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; + use super::{ - frame_limit::{FrameLimitTracker, Lane}, - record::{HistoryBytes, RecordEffect, StagedRecord}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, FRAME_DATA_SHARE_DENOMINATOR, - FRAME_DATA_SHARE_NUMERATOR, TRANSFER_LOG, WRITE_RECORD, WRITE_RECORD_SIZE, + CreatorBefore, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, COUNTED, DATA_SIZE_POOL, + KV_UPDATE_POOL, STATE_GROWTH_POOL, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, }; -use crate::storage_call_stipend; -/// What the common execution layer tracks for the running transaction: the per-frame lanes of -/// data-size bytes and write records, the record the Host staged for the running opcode, the stops -/// its frames return, and whether it is exempt from every limit. +/// What the common execution layer tracks for the running transaction: what it keeps of the +/// data-size, KV-update and state-growth limits and of the frame budgets, the stops its frames +/// return, whether it is exempt from every limit, and the figures the settled transaction reports. +/// +/// It lives on the [`MegaContext`](crate::MegaContext), is begun before each transaction and +/// system call, and is driven by the Host's hooks (a completed write, a frame's start, a code +/// deposit) and by the frame lifecycle (a start revm decided, a frame's return, the stops). +/// +/// # The three counted dimensions +/// +/// Data size, KV updates (write records) and state growth are each limited per transaction and +/// per frame ([`COUNTED`]). A frame's budget in a dimension is a pool on its gas tracker +/// ([`LimitKind::pool`]), which the revm fork forwards and settles as it does the reservoir: the +/// transaction's own frame gets what the transaction has left once its body and the counts made +/// before it are counted ([`first_frame_pools`](Self::first_frame_pools)), every child the +/// schedule's share of what its caller has left (98/100: the caller keeps +/// `GasId::pool_kept_percent`) under the frame cap, a failing frame's draws go back to its pool and +/// a successful one hands its signed net to its caller. A count is drawn where it is made, on the +/// pool of the frame that makes it ([`draw`](Self::draw)): a completed write's record or log, a +/// frame start's records and transfer log on the started frame, deployed code on the creating +/// frame. A creator's nonce record is the creating frame's own, drawn on its pools once the +/// creation returned into it with the nonce bumped ([`close_start`](Self::close_start) hands back +/// what tells): the creation's budgets were taken before it. /// -/// It lives on the [`MegaContext`](crate::MegaContext), is reset before each transaction and -/// system call, and is driven by the Host (staging), the opcode wrappers (commit and discard) -/// and the frame lifecycle (lanes, stops). +/// The transaction's limits are held beside the pools, on what the transaction keeps +/// ([`usage`](Self::usage)): its body, its Oracle hints, the records of its applied authorities, +/// and what its frames keep ([`Kept`]), counted with every draw and restored to what it was at a +/// start when that start's frame kept nothing ([`close_start`](Self::close_start)). The transfer +/// logs the transaction reports apart from its bytes are kept beside them, and restored with them. +/// +/// An operation that crosses more than one dimension stops on the first of them in [`COUNTED`]'s +/// order, and inside a dimension the frame's budget is tested before the transaction's limit: the +/// stop names the budget when the budget is crossed, the transaction's limit only when it is not. +/// A fall — a record taken back, a byte given back — crosses nothing. /// /// # The stop /// /// A limit crossed stops the frame that crossed it with a revert, not a halt: the frame reverts /// with [`MegaLimitExceeded`](crate::MegaLimitExceeded) as its output, whether it crossed the /// transaction's limit or its own frame budget, and its caller resumes as after any revert. What -/// the frame counted goes with it, so a caller that resumes is back within the limits, and a +/// the frame counted goes with it, so a caller that resumes is back within the limits, but where +/// the failure put back a record a frame above made while an Oracle hint the failed frame sent +/// stays: the caller is then stopped as it resumes ([`hold_caller`](Self::hold_caller)). A /// transaction never keeps more than its limit: a caller that carries on is held to what is left, -/// and a charge that crosses again stops the frame that makes it. A crossing the transaction's -/// own frame makes is the transaction's result, which settles like any EIP-8037 revert: its -/// unspent regular gas and the reservoir go back to the sender, who pays only for what ran. -/// Exceptional halts (a real out-of-gas, an invalid opcode) are not limit stops and still burn the -/// frame's gas. +/// and a charge that crosses again stops the frame that makes it. A crossing the transaction's own +/// frame makes is the transaction's result, which settles like any EIP-8037 revert: its unspent +/// regular gas and the reservoir go back to the sender, who pays only for what ran. Exceptional +/// halts (a real out-of-gas, an invalid opcode) are not limit stops and still burn the frame's gas. /// /// # The exemption /// /// The protocol's own work is held to none of the per-transaction limits: a system-originated -/// transaction and a system call are marked exempt before their body is counted, and the mark is +/// transaction and a system call are begun exempt, before their body is counted, and the mark is /// sticky for the transaction ([`is_exempt`](Self::is_exempt)). Every stop the layer hands out -/// comes from one place ([`crossed`](Self::crossed)), which answers an exempt transaction with -/// [`LimitCheck::WithinLimit`] whatever it crossed — a transaction limit or a frame budget, in -/// any dimension. -/// What the transaction uses is counted all the same, so its usage is reported as any other +/// comes from [`crossed`](Self::crossed), which answers an exempt transaction with +/// [`LimitCheck::WithinLimit`] whatever it crossed, and an exempt transaction's pools are +/// unlimited. What it uses is counted all the same, so its usage is reported as any other /// transaction's is. #[derive(Clone, Debug, Default)] pub struct AdditionalLimit { - pub(crate) tracker: FrameLimitTracker, - staged: Option, limits: EvmTxRuntimeLimits, /// Whether the transaction is exempt from every per-transaction limit, sticky for the - /// transaction. See [`exempt`](Self::exempt). + /// transaction. See [`is_exempt`](Self::is_exempt). exempt: bool, - /// The stop the frame a child returned into must return instead of running on, when what the - /// child left it put it over a limit. See [`on_frame_return`](Self::on_frame_return). - resume_stop: Option, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, /// The crossing the result of the frame returning next was made of, noted where the stop /// became that result ([`note_frame_stop`](Self::note_frame_stop)) and taken when the frame /// returns. @@ -64,1344 +89,833 @@ pub struct AdditionalLimit { /// The crossing that produced the result of the transaction's own frame, if one did. See /// [`limit_exceeded`](Self::limit_exceeded). limit_exceeded: Option, - /// Whether the transaction's call target is an applied EIP-7702 authority, whose account - /// write the transaction's lane already counts. - target_is_authority: bool, - /// The transaction's sender, whose account write is part of the transaction body: a frame - /// running as the sender never records it. - sender: Address, - /// Whether the transaction's first frame reached frame init. When it did not, the runtime - /// phase before it ran out of gas and took back the authorizations applied before it. The - /// body stays; see [`on_last_frame_return`](Self::on_last_frame_return). - frame_began: bool, - /// Data-size bytes of the transaction's body. Recorded before any frame and kept on every - /// path, including an out-of-gas before the first frame, which clears the rest of the tracker. - body_bytes: u64, - /// The history gas validation charged for the transaction's body, part of + /// The data-size bytes of the transaction's body. + body: u64, + /// The data-size bytes of the Oracle hints the transaction forwarded, never taken back. + hints: u64, + /// The write records of the EIP-7702 authorities the transaction applied. + authorities: u64, + /// The accounts the EIP-7702 authorities the transaction applied created. + created_authorities: u64, + /// Whether the transaction created its caller's account before its first frame: a + /// deposit-like transaction whose caller had none. Never taken back. + created_caller: bool, + /// The stop the transaction's own frame returns before it runs, when its authorization list + /// would have kept more than a limit allows and was skipped + /// ([`skip_authorization_list`](Self::skip_authorization_list)). + pre_frame_stop: Option, + /// What the transaction's frames keep, every running frame counted as if it succeeds. + kept: Kept, + /// One per start revm decided whose result has not returned, the latest last. + decided: Vec, + /// The history gas of the transaction's body, part of /// [`history_gas_spent`](Self::history_gas_spent). intrinsic_history_gas: u64, - /// The bytes of the transaction's body that - /// [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid for, part of - /// [`history_bytes`](Self::history_bytes). + /// The bytes of the body that [`intrinsic_history_gas`](Self::intrinsic_history_gas) paid + /// for, part of [`history_bytes`](Self::history_bytes). intrinsic_history_bytes: u64, - /// The history gas of the write record the transaction's own frame makes — its value's - /// recipient, or the account it creates — charged before the first frame and given back when - /// that frame fails. - top_level_write_record_gas: u64, - /// The write records the transaction's own frame makes, as the charge of their history before - /// execution found them, for [`push_lane`](Self::push_lane) to check its own count against. - /// See [`stage_top_level_records`](Self::stage_top_level_records). - pending_top_level_records: Option, - /// The history gas the running opcode charged its own frame for the records the frame it is - /// starting will make, waiting for that frame's lane to be pushed. - pending_frame_charge: FrameCharge, - /// Whether revm refuses, on its caller's account, the start of the frame the last - /// frame-starting opcode suspended on — or, before the first frame, the transaction's own - /// frame — as that opcode, or the charge of the transaction's record, found it. See - /// [`stage_start_refused`](Self::stage_start_refused). - pending_start_refused: Option, + /// The history gas charged before the first frame for the write record that frame makes, + /// which the frame carries as its start charge. + first_frame_charge: u64, /// The history gas the settled transaction spent. history_gas_spent: u64, /// The history bytes the settled transaction appended. history_bytes: u64, - /// Whether the running transaction's value movements journal EIP-7708 transfer logs, which - /// revm emits itself and the data size counts where the value moves. - transfer_logs: bool, + /// The EIP-8037 reservoir the settled transaction left unspent. + reservoir_remaining: u64, } -impl AdditionalLimit { - /// A layer enforcing `limits`. - pub fn new(limits: EvmTxRuntimeLimits) -> Self { - Self { limits, ..Default::default() } - } - - /// The limits enforced. - pub const fn limits(&self) -> &EvmTxRuntimeLimits { - &self.limits - } - - /// Replaces the limits enforced from the next transaction on. - pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { - self.limits = limits; - } - - /// Clears the state for a new transaction, keeping allocations and the limits. - pub(crate) fn reset(&mut self) { - self.tracker.reset(); - self.staged = None; - self.exempt = false; - self.resume_stop = None; - self.frame_stop = None; - self.limit_exceeded = None; - self.target_is_authority = false; - self.sender = Address::ZERO; - self.frame_began = false; - self.body_bytes = 0; - self.intrinsic_history_gas = 0; - self.intrinsic_history_bytes = 0; - self.top_level_write_record_gas = 0; - self.pending_top_level_records = None; - self.pending_frame_charge = FrameCharge::NONE; - self.pending_start_refused = None; - self.history_gas_spent = 0; - self.history_bytes = 0; - self.transfer_logs = false; - } - - /// Records whether the running transaction's value movements journal EIP-7708 transfer logs. - /// Called for every transaction, after the reset, from the configuration revm emits them by. - pub(crate) const fn set_transfer_logs(&mut self, emitted: bool) { - self.transfer_logs = emitted; - } - - /// Whether starting `input` journals an EIP-7708 transfer log in the running transaction. - /// See [`moves_value`]. - pub(crate) fn frame_start_transfer_log(&self, input: &FrameInput) -> bool { - self.transfer_logs && moves_value(input) - } - - /* The stops and the exemption */ - - /// The crossing that produced the result of the transaction's own frame, if one did: what - /// [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome) reports. - /// - /// It is a crossing the transaction's own frame made, of the transaction's limit or of its own - /// budget. A crossing below that frame produced the result of the frame that crossed, which its - /// caller caught: a caller that then reverts with the same bytes made its own result, and is no - /// stop. Neither is a stop an inspector rewrote into another result: the frame's result must - /// still be the stop's revert. - /// - /// It is the running transaction's, or the last one's until the next transaction or system - /// call starts: each resets it first. - pub const fn limit_exceeded(&self) -> Option<&LimitCheck> { - self.limit_exceeded.as_ref() - } +/// What a transaction's frames keep: the signed net of each counted dimension, indexed by its +/// pool, and, among the bytes, the EIP-7708 transfer logs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Kept { + /// The net count of each dimension: what the frames added less what they took back. + net: [i64; PoolId::COUNT], + /// EIP-7708 transfer logs. + transfer_logs: u64, +} - /// Notes `stop` as the crossing the result of the frame returning next is made of, and gives - /// the [`MegaLimitExceeded`](crate::MegaLimitExceeded) revert data that frame stops with. - /// - /// Every site that turns a crossing into a frame's result takes the revert data from here, and - /// the frame returns before any other does: so the stop is the returning frame's when - /// [`on_frame_return`](Self::on_frame_return) takes it, and the transaction's when that frame - /// is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). - pub(crate) fn note_frame_stop(&mut self, stop: &LimitCheck) -> Bytes { - debug_assert!(stop.exceeded_limit(), "only a crossing stops a frame"); - self.frame_stop = Some(*stop); - stop.revert_data() +impl Kept { + /// The net count of `kind`. + const fn net(&self, kind: LimitKind) -> i64 { + match kind.pool() { + Some(pool) => self.net[pool.index()], + None => 0, + } } +} - /// Whether the running transaction is exempt from every per-transaction limit. - pub const fn is_exempt(&self) -> bool { - self.exempt - } +/// What one write, or one frame start, adds to what a frame keeps and takes back from it, in each +/// counted dimension. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counted { + /// What it adds, per pool: data-size bytes (records, a log's bytes, deployed code, a transfer + /// log), write records, new accounts and slots. + pub(crate) added: PoolAmounts, + /// What it takes back, per pool: the records of accounts and slots returned to what the + /// transaction loaded, with their bytes; accounts and slots it removes. + pub(crate) taken: PoolAmounts, + /// Whether an EIP-7708 transfer log is among the bytes added. + pub(crate) transfer_log: bool, +} - /// Exempts the running transaction from every per-transaction limit, until the next - /// transaction resets the layer. - /// - /// Called for the protocol's own work — a system-originated transaction and a system call — - /// before its body is counted. See the type's documentation. - pub(crate) const fn exempt(&mut self) { - self.exempt = true; - } +impl Counted { + /// Nothing counted. + pub(crate) const NONE: Self = + Self { added: PoolAmounts::ZERO, taken: PoolAmounts::ZERO, transfer_log: false }; - /// The verdict on `used` crossing `kind`'s `limit`, a frame budget when `frame_local` and a - /// transaction-level limit otherwise: the stop the running frame reverts with, alone, its - /// [`LimitCheck::revert_data`] naming the limit crossed. - /// - /// Every stop the layer hands out comes from here, gas detention's included, so this is where - /// the exemption applies: an exempt transaction's verdict is [`LimitCheck::WithinLimit`], - /// whatever it crossed. - pub(crate) const fn crossed( - &self, - kind: LimitKind, - limit: u64, - used: u64, - frame_local: bool, - ) -> LimitCheck { - if self.exempt { - return LimitCheck::WithinLimit; + /// `added` write records made and `taken` taken back, with an EIP-7708 transfer log when + /// `transfer_log`: each record is [`WRITE_RECORD_SIZE`] bytes and one KV update. + pub(crate) const fn records(added: u64, taken: u64, transfer_log: bool) -> Self { + let log = if transfer_log { TRANSFER_LOG_SIZE } else { 0 }; + Self { + added: PoolAmounts::ZERO + .with(DATA_SIZE_POOL, WRITE_RECORD_SIZE.saturating_mul(added).saturating_add(log)) + .with(KV_UPDATE_POOL, added), + taken: PoolAmounts::ZERO + .with(DATA_SIZE_POOL, WRITE_RECORD_SIZE.saturating_mul(taken)) + .with(KV_UPDATE_POOL, taken), + transfer_log, } - LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Checks the data-size limit after the running frame counted something: what the - /// transaction keeps against its limit, then what the running frame keeps against its budget. - /// A record that crosses both names the transaction's limit. - fn check(&self) -> LimitCheck { - let (kept, limit) = (self.tracker.net(), self.limits.tx_data_size_limit); - if kept.exceeds_data_size(limit) { - return self.crossed(LimitKind::DataSize, limit, kept.data_size, false); - } - if let Some(lane) = self.tracker.current() { - let (kept, budget) = (lane.net(), lane.budget); - if kept.exceeds_data_size(budget) { - return self.crossed(LimitKind::DataSize, budget, kept.data_size, true); - } + /// This count with `rise` new accounts or slots and `fall` accounts or slots it removes: its + /// state growth. + pub(crate) const fn with_growth(self, rise: u64, fall: u64) -> Self { + Self { + added: self.added.with(STATE_GROWTH_POOL, rise), + taken: self.taken.with(STATE_GROWTH_POOL, fall), + transfer_log: self.transfer_log, } - LimitCheck::WithinLimit } - /// The stop the running frame returns instead of running another instruction: the one - /// [`on_frame_return`](Self::on_frame_return) left for a caller its child put over a limit. - /// Taking it clears it, which stops one frame. - pub(crate) const fn stop_before_run(&mut self) -> Option { - self.resume_stop.take() + /// `bytes` bytes that are no write record: a log's, or deployed code. + pub(crate) const fn bytes(bytes: u64) -> Self { + Self { added: PoolAmounts::ZERO.with(DATA_SIZE_POOL, bytes), ..Self::NONE } } - /// What the transaction keeps so far: its data-size bytes and write records, with every - /// running frame counted as if it succeeds. - pub fn usage(&self) -> LimitUsage { - self.tracker.net() + /// This count with `bytes` more bytes that are no write record taken back: deployed code a + /// destruction takes back. + pub(crate) const fn plus_bytes_taken(self, bytes: u64) -> Self { + let taken = self.taken.get(DATA_SIZE_POOL).saturating_add(bytes); + Self { taken: self.taken.with(DATA_SIZE_POOL, taken), ..self } } - /// The history gas the last settled transaction spent. - pub const fn history_gas_spent(&self) -> u64 { - self.history_gas_spent + /// This count and `other` added together: one operation's two parts, whose transfer logs are + /// at most one between them. + pub(crate) fn plus(self, other: Self) -> Self { + debug_assert!(!(self.transfer_log && other.transfer_log), "one transfer log per operation"); + let mut sum = Self { transfer_log: self.transfer_log || other.transfer_log, ..self }; + for pool in PoolId::ALL { + sum.added.set(pool, self.added.get(pool).saturating_add(other.added.get(pool))); + sum.taken.set(pool, self.taken.get(pool).saturating_add(other.taken.get(pool))); + } + sum } - /// The history gas validation charged for the transaction's body: the bytes the transaction - /// carries and the write records its inclusion makes, which are known before it runs. - /// - /// It rides in the EIP-8037 intrinsic state-gas slot, so the reservoir pays it first, and the - /// settled result takes it back out of the state gas it reports: it is history, not state. - pub const fn intrinsic_history_gas(&self) -> u64 { - self.intrinsic_history_gas + /// The data-size bytes it adds. + pub(crate) const fn bytes_added(&self) -> u64 { + self.added.get(DATA_SIZE_POOL) } - /// Records the history gas validation charged for the transaction's body, and the `bytes` of - /// the body it paid for. - pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { - self.intrinsic_history_gas = gas; - self.intrinsic_history_bytes = bytes; + /// The data-size bytes it takes back. + pub(crate) const fn bytes_taken(&self) -> u64 { + self.taken.get(DATA_SIZE_POOL) } - /// The history bytes the last settled transaction appended, whoever paid for them, which a - /// transaction reports as [`MegaGasUsage::history_bytes`](crate::MegaGasUsage::history_bytes); - /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of - /// their price. - pub const fn history_bytes(&self) -> u64 { - self.history_bytes + /// Whether it adds nothing and takes nothing back. + const fn is_none(&self) -> bool { + self.added.is_zero() && self.taken.is_zero() } - /// Settles [`history_bytes`](Self::history_bytes) from what the transaction kept: `priced` is - /// whether it pays history at all. Called once the outermost frame's lane is popped, when - /// everything the transaction kept sits on its own lane. - pub(crate) fn settle_history_bytes(&mut self, priced: bool) { - self.history_bytes = if priced { - self.intrinsic_history_bytes - .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.tracker.net().write_records)) - .saturating_add(self.tracker.log_and_code_bytes()) - } else { - 0 - }; - } - - /// The history gas charged before the first frame for the write record that frame makes: the - /// recipient of the transaction's value, or the account it creates. - /// - /// A first frame that fails keeps no such write, so the charge is given back with the rest of - /// what the failure discards. - pub(crate) const fn top_level_write_record_gas(&self) -> u64 { - self.top_level_write_record_gas - } - - /// Records the history gas charged for the transaction's own write record. - pub(crate) const fn set_top_level_write_record_gas(&mut self, gas: u64) { - self.top_level_write_record_gas = gas; + /// What it adds to `pool` less what it takes back from it. + const fn rise(&self, pool: PoolId) -> i128 { + self.added.get(pool) as i128 - self.taken.get(pool) as i128 } +} - /// Leaves the write records the transaction's own frame makes, as the charge of their history - /// before execution found them, for [`push_lane`](Self::push_lane) to check its own count - /// against when it pushes that frame's lane - /// ([`check_top_level_records`](Self::check_top_level_records)). - /// - /// Only a transaction that pays history is charged, and so leaves one. A first frame answered - /// or refused before its lane is pushed leaves it for the next transaction's reset to clear. - pub(crate) const fn stage_top_level_records(&mut self, records: u64) { - self.pending_top_level_records = Some(records); - } +/// A start revm decided whose result has not returned. +#[derive(Clone, Copy, Debug)] +struct Decided { + /// The started frame's depth, which its result returns at. + depth: usize, + /// What the frames kept when the start began, before its own records. + at_start: Kept, + /// The history gas the start's caller gets back once the frame returned with its start kept: + /// the price of the records the start took back, less what the caller paid for records the + /// start did not make. + credit: u64, + /// For a creation, its creator as it stood before revm decided the start, which tells once the + /// creation returned what record its nonce bump made. + creator: Option, +} - /// Draws up to `amount` from the running frame's history allowance and reports what it gave; - /// the caller pays the rest out of the frame's own gas. - /// - /// Only a history charge may draw, and only the one a log makes: a write record, a state - /// charge and a unit of computation are all paid for by the frame's gas alone. See - /// [`storage_call_stipend`](crate::storage_call_stipend). - #[inline] - pub(crate) fn try_consume_stipend(&mut self, amount: u64) -> u64 { - self.tracker.consume_stipend(amount) +impl AdditionalLimit { + /// A layer enforcing `limits`. + pub fn new(limits: EvmTxRuntimeLimits) -> Self { + Self { limits, ..Default::default() } } - /// Whether the transaction's call target is an applied EIP-7702 authority, whose account - /// write the transaction's own lane already counts, so its first frame writes no recipient. - pub(crate) const fn target_is_authority(&self) -> bool { - self.target_is_authority + /// The limits enforced. + pub const fn limits(&self) -> &EvmTxRuntimeLimits { + &self.limits } - /// Leaves the history gas the running opcode just charged its frame for the records the frame - /// it starts will make: `on_lane` for the records that frame's failure discards, `caller` for - /// the record of the caller's own account, and `records`, the answer the charge was computed - /// from, for [`push_lane`](Self::push_lane) to check its own against. - /// - /// The next lane pushed takes it, whether that is the frame's own or the empty one of a frame - /// answered without running. - #[inline] - pub(crate) const fn stage_frame_charge( - &mut self, - records: FrameStartRecords, - on_lane: u64, - caller: u64, - ) { - self.pending_frame_charge = FrameCharge { records: Some(records), on_lane, caller }; + /// Replaces the limits enforced from the next transaction on. + pub(crate) const fn set_limits(&mut self, limits: EvmTxRuntimeLimits) { + self.limits = limits; } - /// Leaves whether revm refuses the start of the frame about to start on its caller's account, - /// for the frame's init to take ([`take_start_refused`](Self::take_start_refused)) rather than - /// read the caller's account again: found by the opcode starting the frame, or, for the - /// transaction's own frame, by the charge of its record before execution. + /// Clears the state for a new transaction, keeping allocations and the limits, and begins it: + /// exempt from every limit or not, its value movements journaling transfer logs or not, its + /// body weighing `body` bytes. /// - /// Only a start revm can refuse there — a call that transfers value, a creation — takes it. - /// One an opcode makes finds the answer that opcode staged, which stages one for every frame - /// it starts and so replaces whatever an earlier start left. The transaction's own frame finds - /// the one its record's charge staged, or none: the reset cleared what the transaction before - /// it left. A start answered before its init leaves its answer for no other start to take. - /// The one start past the first frame no opcode makes, a keyless deployment's creation, is - /// cleared for ([`set_frame_creator`](Self::set_frame_creator)), and so is every start on the - /// inspected path, whose inspector may rewrite the input. - #[inline] - pub(crate) const fn stage_start_refused(&mut self, refused: bool) { - self.pending_start_refused = Some(refused); - } - - /// Takes what [`stage_start_refused`](Self::stage_start_refused) left for the frame about to - /// start, if anything. - #[inline] - pub(crate) const fn take_start_refused(&mut self) -> Option { - self.pending_start_refused.take() - } - - /// Records the history gas the settled transaction spent. - pub(crate) const fn set_history_gas_spent(&mut self, history_gas_spent: u64) { - self.history_gas_spent = history_gas_spent; + /// The exemption is decided before the body is counted: the protocol's own work is exempt + /// whatever it carries. + pub(crate) fn begin_transaction(&mut self, exempt: bool, transfer_logs: bool, body: u64) { + self.exempt = exempt; + self.transfer_logs = transfer_logs; + self.frame_stop = None; + self.limit_exceeded = None; + self.body = body; + self.hints = 0; + self.authorities = 0; + self.created_authorities = 0; + self.created_caller = false; + self.pre_frame_stop = None; + self.kept = Kept::default(); + self.decided.clear(); + self.intrinsic_history_gas = 0; + self.intrinsic_history_bytes = 0; + self.first_frame_charge = 0; + self.history_gas_spent = 0; + self.history_bytes = 0; + self.reservoir_remaining = 0; } - /* Observe, stage, commit */ + /* What the transaction keeps */ - /// The record the Host staged for the running opcode, if any. - pub const fn staged_record(&self) -> Option<&StagedRecord> { - self.staged.as_ref() - } - - /// Stages the facts the Host observed. Called by the Host, which records nothing itself. - #[inline] - pub(crate) fn stage_record(&mut self, record: StagedRecord) { - self.staged = Some(record); + /// What the transaction keeps so far, every running frame counted as if it succeeds: its + /// data-size bytes, write records and state growth, each the dimension's net, never below zero. + pub(crate) const fn usage(&self) -> LimitUsage { + LimitUsage { + data_size: positive(self.net(LimitKind::DataSize)), + write_records: positive(self.net(LimitKind::KvUpdate)), + state_growth: positive(self.net(LimitKind::StateGrowth)), + } } - /// Commits the staged record to the running frame's lane, and reports the history bytes it - /// appends or takes back. Called by an opcode's wrapper once the opcode completed; a crossed - /// limit in the verdict stops the opcode's frame, and the wrapper charges the history. - /// - /// A `SELFDESTRUCT` that moved value to another account also counts the EIP-7708 transfer log - /// revm journaled for the move, with the beneficiary's record and in the same check. The log - /// is the running frame's, as the move is: the frame's own journal checkpoint takes both back - /// when the frame fails, and its lane the bytes. It is data size and nothing else — no write - /// record, and no history: the bytes reported are the record's alone. - #[inline] - pub(crate) fn commit_staged_record(&mut self) -> (LimitCheck, HistoryBytes) { - let Some(record) = self.staged.take() else { - return (LimitCheck::WithinLimit, HistoryBytes::None); - }; - let effect = record.effect(self.sender); - let history = effect.history_bytes(); - // A log's bytes are history beside the write records; a record's are counted as one. - if let (StagedRecord::Log { .. }, HistoryBytes::Appended(bytes)) = (&record, history) { - self.tracker.record_log_and_code_bytes(bytes); - } - let counted = match effect { - RecordEffect::None => LimitUsage::ZERO, - RecordEffect::Record(usage) => usage, - RecordEffect::Refund(usage) => { - self.tracker.refund(usage); - return (LimitCheck::WithinLimit, history); + /// The transaction's net count of `kind`: what sits on no frame — the body, the hints, the + /// authorities' records and the accounts they created, the caller a deposit created — and + /// what the frames keep. + const fn net(&self, kind: LimitKind) -> i128 { + let frames = self.kept.net(kind) as i128; + let outside = match kind { + LimitKind::DataSize => { + self.body as i128 + + self.hints as i128 + + WRITE_RECORD_SIZE as i128 * self.authorities as i128 } + LimitKind::KvUpdate => self.authorities as i128, + LimitKind::StateGrowth => { + self.created_authorities as i128 + self.created_caller as i128 + } + LimitKind::ComputeGas => 0, }; - let counted = if self.transfer_logs && record.moves_value() { - counted.saturating_add(TRANSFER_LOG) - } else { - counted - }; - if counted == LimitUsage::ZERO { - return (LimitCheck::WithinLimit, history); - } - self.tracker.record(counted); - (self.check(), history) + outside + frames } - /// Discards the staged record. Called by an opcode's wrapper on entry, so a record staged - /// outside a wrapper cannot be committed for the wrong opcode, and when the opcode failed, - /// which takes the observed write back with it. - #[inline] - pub(crate) fn discard_staged_record(&mut self) { - self.staged = None; + /// The transaction's limit on `kind`. + const fn tx_limit(&self, kind: LimitKind) -> u64 { + match kind { + LimitKind::DataSize => self.limits.tx_data_size_limit, + LimitKind::KvUpdate => self.limits.tx_kv_update_limit, + LimitKind::StateGrowth => self.limits.tx_state_growth_limit, + LimitKind::ComputeGas => u64::MAX, + } } - /* Transaction-level records */ - - /// Counts the transaction's body: its envelope, the writes its inclusion makes, its calldata, - /// its authorizations and its access list. - /// - /// The bytes are the transaction's, recorded before any frame, so a revert does not take them - /// back, and neither does an out-of-gas before the first frame. The count is all it does: - /// validation holds the body to the limit ([`admits_tx_body`](Self::admits_tx_body)) on this - /// same count, and refuses a transaction it does not admit, so a transaction that runs never - /// crosses the limit with its body. - pub(crate) fn record_tx_body(&mut self, bytes: u64) { - self.body_bytes = bytes; - if bytes != 0 { - self.tracker.record_tx(LimitUsage { data_size: bytes, write_records: 0 }); - } + /// The data-size bytes of the transaction's body, which it counts before any frame and no + /// revert takes back. + pub(crate) const fn body(&self) -> u64 { + self.body } - /// The data-size bytes of the running transaction's body, as - /// [`record_tx_body`](Self::record_tx_body) counted them. - pub(crate) const fn body_bytes(&self) -> u64 { - self.body_bytes + /// Whether the transaction's value movements journal EIP-7708 transfer logs. + pub(crate) const fn counts_transfer_logs(&self) -> bool { + self.transfer_logs } - /// Whether the running transaction's body, with one write record for each of its - /// `authorizations`, fits its data-size limit: what validation holds a transaction to. + /// Whether the transaction's body, with one write record for each of its `authorizations`, + /// fits its data-size limit: what validation holds a transaction to. /// /// Every entry of the authorization list counts, whether it will apply or not, so the figure is /// an upper bound on what the transaction counts before its first frame — the body, then one /// record for each distinct authority that applies — and a transaction validation admits /// cannot cross the limit there. An exempt transaction is held to nothing. - pub(crate) fn admits_tx_body(&self, authorizations: u64) -> bool { + pub(crate) const fn admits_tx_body(&self, authorizations: u64) -> bool { self.exempt || - !LimitUsage { data_size: self.body_bytes, write_records: 0 } - .saturating_add(WRITE_RECORD.times(authorizations)) - .exceeds_data_size(self.limits.tx_data_size_limit) + self.body.saturating_add(WRITE_RECORD_SIZE.saturating_mul(authorizations)) <= + self.limits.tx_data_size_limit } - /// Counts the `bytes` of an Oracle hint, the payload a `sendHint` call hands to the node's - /// oracle service. - /// - /// The bytes are counted before the payload is decoded, so a caller cannot make the node - /// materialise a payload for free by appending bytes an ABI decoder ignores. They are the - /// transaction's, not the calling frame's, and no frame's budget holds them. Nothing the frame - /// or the transaction does afterwards takes them back, not even for a payload that fails to - /// decode and is never forwarded, for two separate reasons: a payload forwarded to the oracle - /// service cannot be taken back, and admitting a payload and decoding it is work done whether - /// or not it decodes. - /// - /// The limit is checked before the bytes are counted. A hint that would cross it is the stop, - /// with the usage it would have reached, and is neither forwarded nor counted: its payload - /// never left the machine, so the transaction keeps none of it, as it keeps nothing of a log - /// that crossed the limit. - pub(crate) fn record_hint_bytes(&mut self, bytes: u64) -> LimitCheck { - let hint = LimitUsage { data_size: bytes, write_records: 0 }; - let (reached, limit) = - (self.tracker.net().saturating_add(hint), self.limits.tx_data_size_limit); - if reached.exceeds_data_size(limit) { - let stop = self.crossed(LimitKind::DataSize, limit, reached.data_size, false); - if stop.exceeded_limit() { - return stop; - } - } - self.tracker.record_tx(hint); - LimitCheck::WithinLimit - } - - /// Records the account writes of the applied EIP-7702 authorities other than the sender: - /// `authorities` distinct accounts, `target_is_authority` if the transaction's call target is - /// one of them, from the transaction's `sender`. + /// Counts the records of the applied EIP-7702 authorities, `authorities` distinct accounts + /// other than the transaction's sender, and the `created` accounts among them the application + /// created, made before the first frame. An out-of-gas before the first frame takes them back + /// ([`take_back_authorities`](Self::take_back_authorities)). /// /// The records cannot cross the data-size limit: validation admitted the body with a record for /// every entry of the authorization list ([`admits_tx_body`](Self::admits_tx_body)), and only - /// an entry can apply. A debug build asserts it. - pub(crate) fn record_applied_authorities( - &mut self, - sender: Address, - authorities: u64, - target_is_authority: bool, - ) { - self.sender = sender; - self.target_is_authority = target_is_authority; - self.tracker.record(WRITE_RECORD.times(authorities)); + /// an entry can apply. Neither they nor the created accounts cross the KV or the state-growth + /// limit: a list that would was skipped before it was applied + /// ([`hold_authorization_list`](Self::hold_authorization_list)). A debug build asserts both. + pub(crate) fn count_authorities(&mut self, authorities: u64, created: u64) { + self.authorities = authorities; + self.created_authorities = created; debug_assert!( - self.exempt || !self.tracker.net().exceeds_data_size(self.limits.tx_data_size_limit), + self.exempt || !self.usage().exceeds_data_size(self.limits.tx_data_size_limit), "validation admits no body whose authority records cross the data-size limit" ); + debug_assert!( + self.exempt || + (authorities == 0 && created == 0) || + [LimitKind::KvUpdate, LimitKind::StateGrowth] + .iter() + .all(|&kind| self.net(kind) <= self.tx_limit(kind) as i128), + "an authorization list that would cross the KV or state-growth limit is skipped" + ); } - /* Frame lanes */ + /// Takes back the authorities' records and the accounts they created, which an out-of-gas + /// before the first frame takes back with the authorizations. + pub(crate) const fn take_back_authorities(&mut self) { + self.authorities = 0; + self.created_authorities = 0; + } - /// Pushes the lane of a frame about to start and counts the writes its start makes: - /// - /// - a call that transfers value: the sender's account (once per sender frame) and the - /// recipient's, one record when they are the same account; - /// - a creation: the created account, and the creator's nonce (once per creator frame); - /// - the transaction's own frame: the value recipient or the created account. - /// - /// The sender's account is part of the transaction body and never a record here: a frame - /// running as the sender (reached through an EIP-7702 delegation) counts it as recorded, and - /// a value transfer to the sender records no recipient. - /// - /// A frame whose start moves value to another account also counts the EIP-7708 transfer log - /// revm journals for the move, on the frame's own lane and in the same check as its records. - /// revm moves the value, and emits the log, only once it builds the frame, inside the journal - /// checkpoint it makes for it; the count comes before that, so a crossing answers the frame - /// with the stop before any value moves. After the checkpoint it could not: a frame revm - /// answers without running — a call to an account with no code, a precompile — has committed - /// its checkpoint by the time its answer returns, and rewriting the answer would not take the - /// move back. The lane follows the checkpoint from then on: a frame that fails discards both - /// the log and its bytes. - /// - /// So the count is a prediction of what revm will do ([module documentation](super)), and it - /// is called only for a start revm makes as far as the caller's account decides it: a start - /// revm refuses there, and one past the call-stack limit, which the depth guard answers before - /// it is counted, get an empty lane instead ([`push_empty_frame`](Self::push_empty_frame)). - /// - /// A crossed limit in the verdict means the frame must not run: it is answered with the stop. - pub(crate) fn on_frame_init(&mut self, input: &FrameInput, depth: usize) -> LimitCheck { - self.frame_began = true; - self.push_lane(input, depth); - if self.frame_start_transfer_log(input) { - self.tracker.record(TRANSFER_LOG); - } - self.check() + /// Counts the caller account a deposit-like transaction creates before its first frame: one + /// account of state growth on the transaction, which no failure takes back, the deposit's own + /// included. It is one account, so it cannot cross a state-growth limit of one or more by + /// itself, and it is held to none: under a limit of nothing it leaves the first frame nothing. + /// A deposit carries no authorization list, so nothing else is counted before its frame. + pub(crate) const fn count_created_caller(&mut self) { + self.created_caller = true; } - /// Holds the code a creation deposits to the data-size limit, and names the stop when it - /// crosses it: the bytes are counted on the creation's own lane. - /// - /// Called through - /// [`ContextTr::admit_code_deposit`](revm::context::ContextTr::admit_code_deposit), which - /// `return_create` asks once it decided to deposit the code — the code passed every check - /// and every deposit charge is recorded — and before it commits the creation's journal - /// checkpoint. A stop refuses the deposit: `return_create` reverts the checkpoint, so the code - /// is not written, puts the frame's gas back to what it had before the deposit's charges, and - /// ends the creation as a revert carrying the stop. The bytes stay on the lane until the frame - /// returns; a success merges them into the caller, and the failure — the stop included — - /// discards them. - /// - /// A creation `return_create` fails itself is never offered: a revert or a halt of the init - /// code, code it refuses, and a creation that cannot pay one of the deposit's charges, which - /// runs out of gas whatever the limit. Empty code deposits nothing and is held to nothing. - /// - /// The same bytes are history beside the write records, counted here on the same lane, so the - /// history a transaction reports it appended and the data size it kept move together: a - /// creation that deposits nothing, or whose deposit fails, appends neither. - pub(crate) fn on_code_deposit(&mut self, deposit: &CodeDeposit<'_>) -> Result<(), Bytes> { - let bytes = deposit.code.len() as u64; - if bytes == 0 { - return Ok(()); - } - debug_assert!(self.tracker.current().is_some(), "a creation returns on its own lane"); - self.tracker.record(LimitUsage { data_size: bytes, write_records: 0 }); - self.tracker.record_log_and_code_bytes(bytes); - let check = self.check(); + /// Whether an authorization list of `entries` could keep more than the transaction's KV or + /// state-growth limit allows: each entry changes one authority at most and creates one at + /// most, so a list no longer than what both limits leave cannot cross them, and needs no + /// simulation. + pub(crate) const fn authorization_list_may_cross(&self, entries: u64) -> bool { + let records = self.tx_limit(LimitKind::KvUpdate) as i128 - self.net(LimitKind::KvUpdate); + let created = + self.tx_limit(LimitKind::StateGrowth) as i128 - self.net(LimitKind::StateGrowth); + !self.exempt && (entries as i128 > records || entries as i128 > created) + } + + /// The verdict on an authorization list that would keep `records` write records and create + /// `created` accounts were it applied, before the first frame: KV updates first, then state + /// growth, each against the transaction's limit, since no frame budget exists yet. + pub(crate) const fn hold_authorization_list(&self, records: u64, created: u64) -> LimitCheck { + let counted = Counted::records(records, 0, false).with_growth(created, 0); + let check = self.transaction_crossed(LimitKind::KvUpdate, &counted, false); if check.exceeded_limit() { - return Err(self.note_frame_stop(&check)); + return check; } - Ok(()) + self.transaction_crossed(LimitKind::StateGrowth, &counted, false) } - /// The data-size budget of the frame about to start. - /// - /// The transaction's own frame gets what the transaction has left, and never more than the - /// frame cap ([`frame_data_size_limit`](EvmTxRuntimeLimits::frame_data_size_limit)). A child - /// gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent - /// has left, under the same cap. What the parent has left is its budget minus what it has - /// already kept, so a parent that has spent part of its budget forwards a smaller share. - fn frame_budget(&self) -> u64 { - let forwarded = match self.tracker.current() { - Some(caller) => share_of_remaining(caller.remaining_budget()), - None => self.limits.tx_data_size_limit.saturating_sub(self.tracker.net().data_size), - }; - forwarded.min(self.limits.frame_data_size_limit) + /// Skips the transaction's authorization list, which would have kept more than `stop` allows: + /// none of it is applied or counted, and the transaction's own frame returns `stop` before it + /// runs ([`take_pre_frame_stop`](Self::take_pre_frame_stop)). + pub(crate) fn skip_authorization_list(&mut self, stop: LimitCheck) { + debug_assert!(stop.exceeded_limit(), "only a crossing skips the list"); + self.pre_frame_stop = Some(stop); } - fn push_lane(&mut self, input: &FrameInput, depth: usize) { - let budget = self.frame_budget(); - // What the caller paid for these records at its opcode. The transaction's own frame has - // no such caller: its record is charged before execution and given back by the settlement - // ([`top_level_write_record_gas`](Self::top_level_write_record_gas)). - let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - match input { - FrameInput::Call(inputs) => { - let target = inputs.target_address; - let transfers_value = inputs.transfers_value(); - if depth == 0 { - self.sender = inputs.caller; - let written_outside = target == inputs.caller || self.target_is_authority; - let records = u64::from(transfers_value && !written_outside); - self.check_top_level_records(records); - self.tracker.push(Lane::new( - Some(target), - written_outside || transfers_value, - budget, - 0, - )); - self.tracker.record(WRITE_RECORD.times(records)); - return; - } - let records = self.records_the_caller_paid_for(input, charge.records); - let inherited = self.tracker.current().is_some_and(|caller| { - caller.address == Some(target) && caller.account_recorded - }); - let is_sender = target == self.sender; - self.tracker.push(Lane::new( - Some(target), - inherited || is_sender || transfers_value, - budget, - charge.on_lane, - )); - if records.caller { - self.tracker.record_caller(false, charge.caller); - } - self.tracker.record(WRITE_RECORD.times(records.on_lane)); - if grants_stipend(inputs) { - self.tracker.grant_stipend(storage_call_stipend()); - } - } - FrameInput::Create(inputs) => { - let records = self.records_the_caller_paid_for(input, charge.records); - self.tracker.push(Lane::new(None, true, budget, charge.on_lane)); - self.tracker.record(WRITE_RECORD.times(records.on_lane)); - if depth == 0 { - self.sender = inputs.caller(); - self.check_top_level_records(records.on_lane); - } else if records.caller { - self.tracker.record_caller(true, charge.caller); - } - } - // No frame starts from an empty input: revm's own frame init is `unreachable!` on - // one. - FrameInput::Empty => unreachable!( - "a frame input always names a call or a creation, as revm's frame init asserts" - ), - } + /// The stop the transaction's own frame returns before it runs, if its authorization list was + /// skipped; taken once. + pub(crate) const fn take_pre_frame_stop(&mut self) -> Option { + self.pre_frame_stop.take() } - /// The records starting `input` makes, checked against the answer the caller's charge was - /// computed from. - /// - /// The two are separate answers to the same question, asked at two points: the charge at the - /// opcode, on the input revm's instruction built, or at a `keylessDeploy` call's first run, on - /// the creation it starts; and the count here, on the input that survived interception. They - /// agree because nothing between the two changes the input: an interceptor answers a frame or - /// lets it start as it is, and a creation reaches none. A divergence trips here in every debug - /// build rather than mis-charging the caller and mis-splitting the refund its failure gets - /// back. - fn records_the_caller_paid_for( - &self, - input: &FrameInput, - charged: Option, - ) -> FrameStartRecords { - let records = self.frame_start_records(input); - if let Some(charged) = charged { - debug_assert_eq!( - charged, records, - "the records a frame's start makes changed after its caller was charged for them", - ); + /// The pools of the transaction's own frame: what the transaction has left of each limit once + /// its body and the counts made before the frame are counted, the data size under the frame + /// cap; unlimited for an exempt transaction. + pub(crate) const fn first_frame_pools(&self) -> PoolAmounts { + if self.exempt { + return PoolAmounts::UNLIMITED; + } + let caps = self.frame_caps(); + let mut pools = PoolAmounts::UNLIMITED; + let mut index = 0; + while index < COUNTED.len() { + let kind = COUNTED[index]; + let Some(pool) = kind.pool() else { unreachable!() }; + let left = self.tx_limit(kind) as i128 - self.net(kind); + let left = if left < 0 { + 0 + } else if left > u64::MAX as i128 { + u64::MAX + } else { + left as u64 + }; + let cap = caps.get(pool); + pools.set(pool, if left < cap { left } else { cap }); + index += 1; } - records + pools } - /// Checks the write records the transaction's own frame makes on its lane, `counted` here, - /// against the ones its history was charged for before execution - /// ([`stage_top_level_records`](Self::stage_top_level_records)). - /// - /// The two are separate answers to the same question: the charge, on the transaction, and the - /// count here, on the frame input revm built from it. They agree because that input carries - /// the transaction's own caller, target and value, and both read the same answer to whether - /// the target is an applied authority. An inspector that rewrites the input so that the answer - /// changes splits them, as it does for a frame an opcode starts - /// ([`records_the_caller_paid_for`](Self::records_the_caller_paid_for)). A divergence trips - /// here in every debug build rather than charging history for a record the data size does not - /// count, or counting one no history paid for. - fn check_top_level_records(&mut self, counted: u64) { - if let Some(charged) = self.pending_top_level_records.take() { - debug_assert_eq!( - charged, counted, - "the transaction's own frame makes other write records than its history was \ - charged for", - ); + /// The most each of a frame's pools may start with: the data-size frame cap, and no cap on the + /// other pools; nothing for an exempt transaction. + pub(crate) const fn frame_caps(&self) -> PoolAmounts { + if self.exempt { + return PoolAmounts::UNLIMITED; } + PoolAmounts::UNLIMITED.with(DATA_SIZE_POOL, self.limits.frame_data_size_limit) } - /// The write records starting `input` makes at a depth above the transaction's own frame, for - /// the opcode that starts it: `on_lane` are the records the frame's failure discards, `caller` - /// whether its start also writes the caller's own account. + /* Verdicts */ + + /// The verdict on `used` crossing `kind`'s `limit`, a frame budget when `frame_local` and a + /// transaction-level limit otherwise: the stop the running frame reverts with, alone, its + /// [`LimitCheck::revert_data`] naming the limit crossed. /// - /// The caller pays for both at the opcode, before it forwards gas, so the frame's own budget - /// carries none of them — which is what lets a value transfer's allowance pay for what the - /// recipient does with it. - pub(crate) fn frame_start_records(&self, input: &FrameInput) -> FrameStartRecords { - let caller_recorded = self.tracker.current().is_some_and(|lane| lane.account_recorded); - match input { - FrameInput::Call(inputs) => { - if !inputs.transfers_value() { - return FrameStartRecords::NONE; - } - let target = inputs.target_address; - let writes_target = target != inputs.caller && target != self.sender; - FrameStartRecords { on_lane: u64::from(writes_target), caller: !caller_recorded } - } - FrameInput::Create(_) => FrameStartRecords { on_lane: 1, caller: !caller_recorded }, - FrameInput::Empty => FrameStartRecords::NONE, + /// Every stop comes from here, so this is where the exemption applies: an exempt transaction's + /// verdict is [`LimitCheck::WithinLimit`], whatever it crossed. + pub(crate) const fn crossed( + &self, + kind: LimitKind, + limit: u64, + used: u64, + frame_local: bool, + ) -> LimitCheck { + if self.exempt { + return LimitCheck::WithinLimit; } + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } } - /// Sets the account the running frame runs as, once known (a creation's address). - pub(crate) fn set_frame_address(&mut self, address: Address) { - if let Some(lane) = self.tracker.current_mut() { - lane.address = Some(address); - } + /// The verdict on a frame budget of `kind`, whose pool holds `remaining` after a net draw of + /// `spent`, crossed by `rise` more: the budget is the pool the frame started with, which its + /// pool and its net draw add up to, and what it used is its net draw with the rise in. + fn budget_crossed(&self, kind: LimitKind, remaining: u64, spent: i64, rise: u64) -> LimitCheck { + let budget = remaining.saturating_add_signed(spent); + let used = positive(spent as i128 + rise as i128); + self.crossed(kind, budget, used, true) } - /// Makes the running frame start its creation as `creator`: the frame of a `keylessDeploy` - /// call, which runs no code of its own and starts the creation its signer signed. - /// - /// The creation's start writes the creator's nonce, so the frame's lane runs as the creator: - /// the creation records that write as its creator's, on the frame's lane once the creation - /// fails, unless the creator is the transaction's sender, whose account the body counts. - /// - /// No opcode starts the creation, so nothing staged the answer to whether its creator's - /// account refuses it. Clearing the staged answer is defensive: the only answer staged for the - /// call's own start is that of a call carrying value, which is answered before its frame is - /// built and so never starts a creation. Nothing staged can reach the creation; the clear is - /// kept so that none ever does. - pub(crate) fn set_frame_creator(&mut self, creator: Address) { - self.pending_start_refused = None; - let sender = self.sender; - if let Some(lane) = self.tracker.current_mut() { - lane.address = Some(creator); - lane.account_recorded = creator == sender; + /// The verdict on the transaction keeping `counted` more of `kind`: its limit crossed, or + /// within. A count that does not rise crosses nothing, unless `held` asks for the transaction + /// to be held to its limit whatever it counts. + const fn transaction_crossed( + &self, + kind: LimitKind, + counted: &Counted, + held: bool, + ) -> LimitCheck { + let Some(pool) = kind.pool() else { return LimitCheck::WithinLimit }; + let rise = counted.rise(pool); + if !held && rise <= 0 { + return LimitCheck::WithinLimit; + } + let used = self.net(kind) + rise; + let limit = self.tx_limit(kind); + if used > limit as i128 { + return self.crossed(kind, limit, positive(used), false); } + LimitCheck::WithinLimit } - /// Takes back the nonce record a failed creation left its creator, when the nonce bump it - /// stands for is taken back: the running frame is a `keylessDeploy` call whose lane runs as - /// the signer ([`set_frame_creator`](Self::set_frame_creator)). A signer that is the - /// transaction's sender has no such record, its account being the body's. - /// - /// A stop the record left the frame, by putting it over a limit, goes with it: the frame is - /// held to its limits again without the record. Returns whether a record was taken back. - pub(crate) fn take_back_creator_record(&mut self) -> bool { - let sender = self.sender; - if self.tracker.current().is_none_or(|lane| lane.address == Some(sender)) || - !self.tracker.take_back_own_record() - { - return false; + /// The verdict on `counted` kept on a frame whose pools hold `remaining` after net draws of + /// `spent`: in each counted dimension in order, the frame's budget, then the transaction's + /// limit; the first crossing is the verdict. `held` holds the transaction to its limits + /// whatever `counted` adds. + fn check( + &self, + remaining: PoolAmounts, + spent: [i64; PoolId::COUNT], + counted: &Counted, + held: bool, + ) -> LimitCheck { + for kind in COUNTED { + let Some(pool) = kind.pool() else { continue }; + let rise = counted.rise(pool); + if rise > 0 && rise > remaining.get(pool) as i128 { + let check = self.budget_crossed( + kind, + remaining.get(pool), + spent[pool.index()], + rise as u64, + ); + if check.exceeded_limit() { + return check; + } + } + let check = self.transaction_crossed(kind, counted, held); + if check.exceeded_limit() { + return check; + } } - let check = self.check(); - self.resume_stop = check.exceeded_limit().then_some(check); - true + LimitCheck::WithinLimit } - /// Discards the lane of the frame about to return as its failure would, and stands an empty - /// lane in for it, which gives the caller back, when it is popped, the history the failure - /// gives back. - /// - /// For a frame whose journal checkpoint was reverted and whose result an inspector then - /// rewrote into a success: nothing the frame counted was kept, so none of it reaches its - /// caller, whatever the result says. - pub(crate) fn discard_returning_lane(&mut self) { - self.tracker.discard_running_lane(); + /// The pools `gas` holds and the nets it drew on them. + fn pools_of(gas: &GasTracker) -> (PoolAmounts, [i64; PoolId::COUNT]) { + (gas.pools_remaining(), PoolId::ALL.map(|pool| gas.pool_spent(pool))) } - /// Pushes the lane of a frame answered without running: a result built without an - /// interpreter keeps the lanes aligned with the frames revm returns. - /// - /// Such a frame records none of the writes its caller paid for, so the whole charge sits on - /// the lane and comes back when it is popped, whatever the answer was. - pub(crate) fn push_empty_frame(&mut self) { - self.frame_began = true; - let charge = core::mem::replace(&mut self.pending_frame_charge, FrameCharge::NONE); - self.tracker.push(Lane::empty(charge.on_lane.saturating_add(charge.caller))); + /// Counts what the frame whose pools `gas` holds keeps of `counted`, held to the frame's + /// budgets and the transaction's limits in the order [`check`](Self::check) holds them: the + /// amounts `counted` takes back go back to each pool first, and the amounts it adds are drawn. + /// A crossing counts nothing and draws nothing, and is the stop the frame reverts with. A + /// count that adds nothing and takes nothing holds nothing. + pub(crate) fn draw(&mut self, gas: &mut GasTracker, counted: &Counted) -> LimitCheck { + if counted.is_none() { + return LimitCheck::WithinLimit; + } + let (remaining, spent) = Self::pools_of(gas); + let check = self.check(remaining, spent, counted, false); + if check.exceeded_limit() { + return check; + } + Self::apply(gas, counted); + self.count(counted); + LimitCheck::WithinLimit } - /// Pops the lane of the frame `result` returns from: a success merges it into the caller's, - /// a failure discards it, a stop's included, so the caller resumes within its limits. - /// - /// Two returns would add to a caller what no check has held it to, and after them the caller is - /// held to its limits with what it now holds; a crossing is the stop it returns before it runs - /// on ([`stop_before_run`](Self::stop_before_run)), naming its budget or the transaction's - /// limit. - /// - /// - A failed creation leaves its creator the nonce record. The creation counted that record on - /// its own lane, against its own share, and a creation stopped for crossing that share still - /// bumps the nonce — so a creator with fewer bytes left than a record would keep one it may - /// not. - /// - A success past the frame's own budget would hand the caller more than the share it gave. - /// No frame returns one: a frame past its budget failed, and a failure an inspector rewrites - /// into a success has its lane discarded before it returns - /// ([`discard_returning_lane`](Self::discard_returning_lane)). It is held all the same. - /// - /// Any other return leaves the caller within its limits, and is not checked: a failure hands - /// it nothing, and a success hands it no more than the share it gave. Neither is the return of - /// the transaction's own frame, which has no caller to hold. A debug build asserts that the - /// check would have found nothing to stop. - /// - /// The crossing the result is made of, the stop noted for the frame - /// ([`note_frame_stop`](Self::note_frame_stop)), is the transaction's - /// [`limit_exceeded`](Self::limit_exceeded) when the frame is the transaction's own and its - /// result is still the stop's revert. - /// - /// Returns the history gas the caller paid for records this frame did not keep, which the - /// caller gets back once the frame has merged into it. - #[must_use = "the history of the records the frame did not keep goes back to its caller"] - pub(crate) fn on_frame_return(&mut self, result: &FrameResult) -> u64 { - let noted = self.frame_stop.take(); - if self.tracker.depth() == 1 { - self.limit_exceeded = noted.filter(|stop| is_the_revert_of(result, stop)); - } - // A charge an opcode of this frame made for a child that never started died with that - // opcode, which failed after making it. - self.pending_frame_charge = FrameCharge::NONE; - let success = result.instruction_result().is_ok(); - let lane = self.tracker.pop(success); - let refund = lane.as_ref().map_or(0, |lane| lane.history_refund(success)); - let unchecked = lane.is_some_and(|lane| self.tracker.hands_unchecked(&lane, success)); - self.resume_stop = if unchecked { - let check = self.check(); - check.exceeded_limit().then_some(check) - } else { + /// Draws `counted` on the pools `gas` holds, which the checks made sure can pay it. + fn apply(gas: &mut GasTracker, counted: &Counted) { + for pool in PoolId::ALL { + gas.refill_pool(pool, counted.taken.get(pool)); + let drew = gas.record_pool(pool, counted.added.get(pool)); debug_assert!( - self.check().within_limit(), - "a frame's return put its caller over a limit no check held it to" + drew || gas.pool_remaining(pool) == u64::MAX, + "the checks admit the draw" ); - None - }; - refund + if !drew { + gas.clear_pool_crossing(pool); + } + } } - /// Settles the transaction's outermost frame: pops its lane unless the frame already - /// returned through [`on_frame_return`](Self::on_frame_return), which is the case whenever - /// it ran. + /// Adds `counted` to what the frames keep. /// - /// A transaction whose first frame never reached frame init ran out of gas in the runtime - /// phase before it: the out-of-gas took back the authorizations applied before it, so their - /// records go too, and the halt stays a halt. The body is not one of those records. It is put - /// back after the reset. Nothing counted before the first frame can have crossed a limit, - /// validation having held the body and the authorities' records to it, so the halt is what the - /// transaction reports. An exemption stays: it is the transaction's, not its frames'. - pub(crate) fn on_last_frame_return(&mut self, result: &FrameResult) { - if !self.frame_began { - let body = self.body_bytes; - self.tracker.reset(); - self.tracker.record_tx(LimitUsage { data_size: body, write_records: 0 }); - return; - } - debug_assert!(self.tracker.depth() <= 1, "only the outermost lane can be left"); - if self.tracker.depth() == 1 { - // The outermost frame has no caller that paid for its records: the transaction did, - // before execution, and the settlement gives that charge back. - let refund = self.on_frame_return(result); - debug_assert_eq!(refund, 0, "the outermost frame's caller is the transaction"); + /// What a frame takes back the transaction's frames counted: a record or a byte taken back was + /// counted by a frame that is still on the stack or merged into one, so the transaction's net + /// stays at or above zero, which a debug build asserts. A frame's own net goes below zero when + /// it takes back what another frame counted — a slot its caller wrote, cleared, or the parts of + /// an account the transaction created, given back to the frame that destroys it — and the + /// signed net merges into its caller as any net does. + fn count(&mut self, counted: &Counted) { + let kept = &mut self.kept; + for pool in PoolId::ALL { + let net = &mut kept.net[pool.index()]; + *net = net + .saturating_add_unsigned(counted.added.get(pool)) + .saturating_sub_unsigned(counted.taken.get(pool)); } + debug_assert!( + kept.net[DATA_SIZE_POOL.index()] >= 0 && kept.net[KV_UPDATE_POOL.index()] >= 0, + "a frame takes back only what the transaction's frames keep" + ); + kept.transfer_logs += u64::from(counted.transfer_log); } -} - -/// `remaining` × [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`], rounded down. -/// -/// The share is `N / D = 1 − 1 / K` with `K = D / (D − N)` a whole number, so the floor of the -/// product is `remaining − ⌈remaining / K⌉`, which stays in `u64` and never wraps. A `u128` -/// product would call the 128-bit division routine on every frame start, where a division of a -/// `u64` by a constant compiles to a multiplication. -const fn share_of_remaining(remaining: u64) -> u64 { - const N: u64 = FRAME_DATA_SHARE_NUMERATOR; - const D: u64 = FRAME_DATA_SHARE_DENOMINATOR; - const _: () = assert!(N < D && D.is_multiple_of(D - N)); - const K: u64 = D / (D - N); - remaining - remaining.div_ceil(K) -} -/// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the -/// stop's [`MegaLimitExceeded`](crate::MegaLimitExceeded). -fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { - let result = result.interpreter_result(); - result.result == InstructionResult::Revert && result.output == stop.revert_data() -} + /// The verdict on a start revm is not asked to decide — a call gas detention answers without + /// running the precompile it targets — had revm made it: `counted`, the records and transfer + /// log its value transfer would make, held to `shares`, the pools its frame would start with, + /// and to the transaction's limits. Nothing is counted. + pub(crate) fn hypothetical_start(&self, counted: &Counted, shares: PoolAmounts) -> LimitCheck { + self.check(shares, [0; PoolId::COUNT], counted, true) + } -/// Whether starting `input` moves value from one account to another, which is what revm journals -/// an EIP-7708 transfer log for: a call that transfers value to an account other than its caller — -/// the transaction's own value, a value `CALL` — and a creation with an endowment, the -/// transaction's own or a `CREATE`'s or a `CREATE2`'s. -/// -/// A `CALLCODE` transfers its value from the calling account to itself, as a `CALL` to itself does, -/// and revm moves nothing and emits nothing for either. `DELEGATECALL` and `STATICCALL` transfer -/// no value at all. -fn moves_value(input: &FrameInput) -> bool { - match input { - FrameInput::Call(inputs) => { - inputs.transfers_value() && inputs.target_address != inputs.caller + /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and + /// never taken back once counted. A hint is on no frame's budget. + pub(crate) fn admit_hint(&mut self, bytes: u64) -> LimitCheck { + let check = self.transaction_crossed(LimitKind::DataSize, &Counted::bytes(bytes), false); + if check.within_limit() { + self.hints = self.hints.saturating_add(bytes); } - FrameInput::Create(inputs) => !inputs.value().is_zero(), - FrameInput::Empty => false, + check } -} -/// Whether the frame `inputs` starts is granted a history allowance: a value-transferring `CALL` -/// or `CALLCODE` below the transaction's own frame. -/// -/// `DELEGATECALL` and `STATICCALL` carry no value, and the transaction's own frame is not a call -/// anybody made — its sender chose the gas limit. -fn grants_stipend(inputs: &CallInputs) -> bool { - matches!(inputs.scheme, CallScheme::Call | CallScheme::CallCode) && inputs.transfers_value() -} - -/// The write records a frame's start makes, split by whose failure takes them back. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct FrameStartRecords { - /// Records on the frame's own lane, which its failure discards. - pub(crate) on_lane: u64, - /// Whether the frame's start also writes its caller's account. - pub(crate) caller: bool, -} + /* A frame's start */ -impl FrameStartRecords { - /// No record at all. - pub(crate) const NONE: Self = Self { on_lane: 0, caller: false }; -} - -/// The history gas a caller paid for the records the frame it starts makes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct FrameCharge { - /// The records the charge was computed from, when an opcode made one. The transaction's own - /// frame has no such opcode, and neither has a frame of a transaction that prices no history. - records: Option, - /// What the records on the frame's own lane cost. - on_lane: u64, - /// What the record of the caller's own account cost. - caller: u64, -} - -impl FrameCharge { - /// Nothing charged. - const NONE: Self = Self { records: None, on_lane: 0, caller: 0 }; -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, Address, Bytes, U256}; - use revm::interpreter::{CallInput, CallValue}; - - const SENDER: Address = address!("00000000000000000000000000000000000f0001"); - const CALLEE: Address = address!("00000000000000000000000000000000000f0002"); - const TARGET: Address = address!("00000000000000000000000000000000000f0003"); - - #[test] - fn test_share_of_remaining_is_the_floor_of_the_exact_product() { - let exact = |x: u64| { - (u128::from(x) * u128::from(FRAME_DATA_SHARE_NUMERATOR) / - u128::from(FRAME_DATA_SHARE_DENOMINATOR)) as u64 - }; - let mut x = 0x9e37_79b9_7f4a_7c15_u64; - let edges = [0, 1, 49, 50, 51, 99, 100, 101, u64::MAX, u64::MAX - 1, u64::MAX / 100 * 100]; - for v in edges.into_iter().chain((0..100_000).map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x >> (x % 64) - })) { - assert_eq!(share_of_remaining(v), exact(v), "{v}"); - } + /// Opens the start of the frame at `depth` that revm just decided, before its records are + /// counted: what the frames keep now is what the frame's failure restores + /// ([`close_start`](Self::close_start)). A creation's `creator`, read before revm decided it, + /// is handed back when the creation returns. + pub(crate) fn open_start(&mut self, depth: usize, creator: Option) { + self.decided.push(Decided { depth, at_start: self.kept, credit: 0, creator }); } - fn call_inputs(scheme: CallScheme, value: U256) -> CallInputs { - CallInputs { - input: CallInput::Bytes(Bytes::new()), - return_memory_offset: 0..0, - gas_limit: 100_000, - bytecode_address: Address::ZERO, - known_bytecode: Default::default(), - target_address: Address::ZERO, - caller: Address::ZERO, - value: CallValue::Transfer(value), - scheme, - is_static: false, - reservoir: 0, - charged_new_account_state_gas: false, + /// Holds the start revm just decided, whose frame's pools `gas` holds, to the limits, and + /// counts `counted`, the records and transfer log it made, on those pools + /// ([`draw`](Self::draw)): the verdict is the stop the frame returns before it runs, or the + /// one its answer gives way to. `credit` is what the start's caller gets back once the frame + /// returned with its start kept. + /// + /// A start is held to the transaction's limits whatever it counts, nothing included: what the + /// transaction keeps may already stand above a limit, as a frame that resumes may find it + /// ([`hold_caller`](Self::hold_caller)), and the caller a deposit-like transaction created is + /// counted unchecked ([`count_created_caller`](Self::count_created_caller)); a start is where + /// a frame first meets it. + pub(crate) fn count_start( + &mut self, + gas: &mut GasTracker, + counted: &Counted, + credit: u64, + ) -> LimitCheck { + let (remaining, spent) = Self::pools_of(gas); + let check = self.check(remaining, spent, counted, true); + if check.exceeded_limit() { + return check; } + Self::apply(gas, counted); + self.count(counted); + if let Some(start) = self.decided.last_mut() { + start.credit = credit; + } + LimitCheck::WithinLimit } - /// A `CALL` from `caller` to `target` carrying `value`. - fn call_from_to(caller: Address, target: Address, value: U256) -> FrameInput { - FrameInput::Call(Box::new(CallInputs { - caller, - target_address: target, - ..call_inputs(CallScheme::Call, value) - })) - } - - /// A hint is held to the transaction's data-size limit before it is counted: one that fits is - /// counted, one that would cross is the stop at the usage it would have reached and leaves the - /// count as it was, and a later one that fits is counted, the crossing having stopped nothing - /// but its own call. An exempt transaction's is counted whatever it crosses. - #[test] - fn test_a_hint_that_would_cross_the_limit_is_not_counted() { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(100); - let kept = |limit: &AdditionalLimit| limit.usage().data_size; - - let mut limit = AdditionalLimit::new(limits); - limit.record_tx_body(40); - assert_eq!(limit.record_hint_bytes(59), LimitCheck::WithinLimit); - assert_eq!(kept(&limit), 99); - let stop = LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: 101, - frame_local: false, + /// Closes the start of the frame whose result returns at `depth`, `kept` or not, and answers + /// the history its caller gets back for it, with the creator of a creation as it stood before + /// revm decided the start: a frame whose result says it failed has what the frames keep + /// restored to what they kept when its start began, as its pools are, and its caller gets + /// nothing back; one that kept its start, the start's credit. + /// + /// A creation's creator is what its nonce record is read from once the result merged into the + /// creator ([`Accounts::creator_counted`](super::Accounts)): the record is the creator's, so it + /// is counted after the creation's own counts are closed, and outlives the creation's failure. + /// + /// A result revm did not decide the start of — the depth guard's, an interceptor's, an + /// inspector's — has no start to close, and no creator: revm bumped no nonce for it. The depth + /// guard's and an interceptor's carry the start charge their input declared, which revm gives + /// back; an inspector's carries what the inspector built it with. + pub(crate) fn close_start(&mut self, depth: usize, kept: bool) -> (u64, Option) { + let Some(&start) = self.decided.last().filter(|start| start.depth == depth) else { + return (0, None); }; - assert_eq!(limit.record_hint_bytes(2), stop, "two more bytes cross"); - assert_eq!(kept(&limit), 99, "the hint that crossed is not counted"); - assert_eq!(limit.record_hint_bytes(1), LimitCheck::WithinLimit, "one more fits exactly"); - assert_eq!(kept(&limit), 100, "and is counted"); - - let mut exempt = AdditionalLimit::new(limits); - exempt.exempt(); - exempt.record_tx_body(40); - assert_eq!(exempt.record_hint_bytes(61), LimitCheck::WithinLimit); - assert_eq!(kept(&exempt), 101, "an exempt transaction's hint is counted"); + self.decided.pop(); + if kept { + (start.credit, start.creator) + } else { + self.kept = start.at_start; + (0, start.creator) + } } - /// A layer with the transaction's own frame started: `SENDER` calling `CALLEE`, which has - /// recorded nothing of its own yet. - fn with_the_transactions_frame() -> AdditionalLimit { - let mut limit = AdditionalLimit::default(); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit + /// The stop the frame a child just returned into returns before it runs on, if what the + /// transaction keeps now stands above one of its limits: in each counted dimension in order, + /// held whatever the return counted. + /// + /// A child's success hands its caller nothing the limits did not hold as it was counted. A + /// failure restores what the frames kept when its start began, which is more than they keep + /// now when the child took back records or state a frame above it made, while what the + /// transaction keeps on no frame stays: an Oracle hint the child sent into the room the take + /// back freed leaves the transaction above its limit, and the caller is stopped for it. + pub(crate) fn hold_caller(&self) -> Option { + for kind in COUNTED { + let check = self.transaction_crossed(kind, &Counted::NONE, true); + if check.exceeded_limit() { + return Some(check); + } + } + None } - /// The records a frame's start makes are counted from the answer its caller was charged for: - /// a value transfer records the caller's account and the recipient's, the two the charge was - /// computed from. - #[test] - fn test_the_records_counted_are_the_records_the_caller_was_charged_for() { - let mut limit = with_the_transactions_frame(); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - let records = limit.frame_start_records(&inner); - assert_eq!(records, FrameStartRecords { on_lane: 1, caller: true }); - - limit.stage_frame_charge(records, 1, 1); - limit.on_frame_init(&inner, 1); - assert_eq!( - limit.usage(), - LimitUsage { data_size: 2 * WRITE_RECORD_SIZE, write_records: 2 }, - ); - } + /* The stops and the exemption */ - /// A frame answered without running — by the depth guard, a stop, an interceptor or an - /// inspector — keeps none of the records its caller paid for, whatever its answer: its lane is - /// empty, the whole charge comes back, and the transaction's history bytes are its body alone. + /// The crossing that produced the result of the transaction's own frame, if one did: what + /// [`MegaTransactionOutcome::limit_exceeded`](crate::MegaTransactionOutcome) reports. /// - /// The depth guard's answer is reached here rather than through a transaction: under the - /// execution cap no call chain reaches the call-stack limit, because each call forwards at most - /// sixty-three sixty-fourths of what its caller has left, and 200,000,000 gas leaves about - /// twenty at depth 1,024. A stop's and an interceptor's answers are also reached through - /// transactions, in the history-byte tests. - #[test] - fn test_a_frame_answered_without_running_keeps_nothing_whatever_the_answer() { - const BODY: u64 = crate::TX_BODY_SIZE; - for answer in - [InstructionResult::CallTooDeep, InstructionResult::Revert, InstructionResult::Stop] - { - let mut limit = with_the_transactions_frame(); - limit.set_intrinsic_history(1, BODY); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(limit.frame_start_records(&inner), 1_000, 2_000); - limit.push_empty_frame(); - - let result = crate::synthetic_frame_result(&inner, answer, Bytes::new()); - assert_eq!(limit.on_frame_return(&result), 3_000, "{answer:?}: all of it back"); - assert_eq!(limit.usage(), LimitUsage::ZERO, "{answer:?}: nothing kept"); - - let outer = call_from_to(SENDER, CALLEE, U256::ZERO); - let result = - crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&result); - limit.settle_history_bytes(true); - assert_eq!(limit.history_bytes(), BODY, "{answer:?}: the body alone"); - } + /// It is a crossing the transaction's own frame made, of the transaction's limit or of its own + /// budget. A crossing below that frame produced the result of the frame that crossed, which its + /// caller caught: a caller that then reverts with the same bytes made its own result, and is no + /// stop. Neither is a stop an inspector rewrote into another result: the frame's result must + /// still be the stop's revert. + /// + /// It is the running transaction's, or the last one's until the next transaction or system + /// call starts: each resets it first. + pub const fn limit_exceeded(&self) -> Option<&LimitCheck> { + self.limit_exceeded.as_ref() } - /// A charge computed from a different answer than the count is what a rewrite that turns one - /// kind of frame into another would make. It trips rather than passing silently, because the - /// charge and the refund its failure gets back would both be wrong. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "changed after its caller was charged for them")] - fn test_a_charge_computed_from_another_answer_trips() { - let mut limit = with_the_transactions_frame(); - limit.stage_frame_charge(FrameStartRecords::NONE, 0, 0); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); + /// Notes `stop` as the crossing the result of the frame returning next is made of, and gives + /// the [`MegaLimitExceeded`](crate::MegaLimitExceeded) revert data that frame stops with. + /// + /// Every site that turns a crossing into a frame's result takes the revert data from here, and + /// the frame returns before any other does: so the stop is the returning frame's when its + /// result returns ([`take_frame_stop`](Self::take_frame_stop)), and the transaction's when + /// that frame is the transaction's own ([`limit_exceeded`](Self::limit_exceeded)). + pub(crate) fn note_frame_stop(&mut self, stop: &LimitCheck) -> Bytes { + debug_assert!(stop.exceeded_limit(), "only a crossing stops a frame"); + self.frame_stop = Some(*stop); + stop.revert_data() } - /// The transaction's own frame counts on its lane the write records its history was charged - /// for before execution: its value's recipient, unless that is the sender or an applied - /// authority, and the account a creation makes. - #[test] - fn test_the_transactions_own_frame_counts_the_records_its_history_paid_for() { - let one = U256::from(1); - let rows = [ - ("a value call", call_from_to(SENDER, CALLEE, one), false, 1), - ("a call without value", call_from_to(SENDER, CALLEE, U256::ZERO), false, 0), - ("a value call to the sender", call_from_to(SENDER, SENDER, one), false, 0), - ("a value call to an applied authority", call_from_to(SENDER, CALLEE, one), true, 0), - ("a creation", creation(SENDER, U256::ZERO), false, 1), - ("an endowed creation", creation(SENDER, one), false, 1), - ]; - for (name, input, target_is_authority, records) in rows { - let authority = u64::from(target_is_authority); - let mut limit = AdditionalLimit::default(); - limit.record_applied_authorities(SENDER, authority, target_is_authority); - limit.stage_top_level_records(records); - limit.on_frame_init(&input, 0); - assert_eq!(limit.usage().write_records, authority + records, "{name}"); - assert_eq!(limit.pending_top_level_records, None, "{name}: taken once"); + /// Takes the stop noted for the frame whose `result` returns now; for the transaction's own + /// frame (`outermost`), it is the transaction's [`limit_exceeded`](Self::limit_exceeded) while + /// the result is still the stop's revert. A frame with no stop noted leaves the transaction's + /// as it is: the transaction's own frame returns through here once. + pub(crate) fn take_frame_stop(&mut self, result: &FrameResult, outermost: bool) { + let Some(noted) = self.frame_stop.take() else { return }; + if outermost { + self.limit_exceeded = Some(noted).filter(|stop| is_the_revert_of(result, stop)); } } - /// A transaction's own frame that would count a record its history did not pay for trips the - /// check, rather than counting data size no history matches. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_record_its_history_did_not_pay_for_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(0); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::from(1)), 0); + /// Whether the running transaction is exempt from every per-transaction limit. + pub const fn is_exempt(&self) -> bool { + self.exempt } - /// A transaction's own frame that makes no record its history was charged for trips the check, - /// rather than keeping history no data size matches. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_charge_for_a_record_the_frame_does_not_make_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(1); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - } + /* What the transaction pays before its first frame */ - /// A creation as the transaction's own frame is checked too: one whose history paid for no - /// record of the account it creates trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "other write records than its history was charged for")] - fn test_a_top_level_creation_its_history_did_not_pay_for_trips() { - let mut limit = AdditionalLimit::default(); - limit.stage_top_level_records(0); - limit.on_frame_init(&creation(SENDER, U256::ZERO), 0); + /// The history gas of the transaction's body: the bytes the transaction carries and the write + /// records its inclusion makes, which are known before it runs. The transaction's gas pays it + /// before the first frame, reservoir first, as intrinsic gas. + pub const fn intrinsic_history_gas(&self) -> u64 { + self.intrinsic_history_gas } - /// A child frame's budget is 98% of what its parent has left, three frames down, and the - /// transaction's own frame gets what the transaction has left. - #[test] - fn test_a_child_frame_gets_98_percent_of_what_its_parent_has_left() { - let mut limit = - AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(10_000)); - limit.tracker.record_tx(LimitUsage { data_size: 310, write_records: 0 }); - - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let first = 10_000 - 310; - assert_eq!(limit.tracker.current().unwrap().budget, first); - - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - let child = share_of_remaining(first); - assert_eq!(child, 9_496); - assert_eq!(limit.tracker.current().unwrap().budget, child); - - limit.on_frame_init(&call_from_to(TARGET, SENDER, U256::ZERO), 2); - let grandchild = share_of_remaining(child); - assert_eq!(limit.tracker.current().unwrap().budget, grandchild); - - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 3); - assert_eq!( - limit.tracker.current().unwrap().budget, - share_of_remaining(grandchild), - "the fourth frame, at depth 3, still takes 98% of what is left" - ); + /// Records the history gas the transaction's body costs, and the `bytes` of the body it pays + /// for. + pub(crate) const fn set_intrinsic_history(&mut self, gas: u64, bytes: u64) { + self.intrinsic_history_gas = gas; + self.intrinsic_history_bytes = bytes; } - /// The frame cap binds when it is tighter than the share of what the parent has left. - #[test] - fn test_the_frame_cap_binds_when_it_is_tighter_than_the_share() { - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(u64::MAX) - .with_frame_data_size_limit(100), - ); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.tracker.current().unwrap().budget, 100); - limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::ZERO), 1); - assert_eq!(limit.tracker.current().unwrap().budget, 98); + /// Records the history gas charged before execution for the write record the transaction's own + /// frame makes: the recipient of its value, or the account it creates. The frame carries it as + /// its start charge, which its failure gives back. + pub(crate) const fn set_first_frame_charge(&mut self, gas: u64) { + self.first_frame_charge = gas; } - /// A layer with a frame cap of 100 bytes and the transaction's own frame started, which is - /// what the cap gives it; `CALLEE`'s call to `TARGET`, the child, is started below it with - /// 98 of them. - fn with_a_child_of_a_capped_frame() -> (AdditionalLimit, FrameInput) { - let mut limit = - AdditionalLimit::new(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let child = call_from_to(CALLEE, TARGET, U256::ZERO); - limit.on_frame_init(&child, 1); - assert_eq!(limit.tracker.current().unwrap().budget, 98); - (limit, child) + /// The history gas charged before execution for the write record the transaction's own frame + /// makes. + pub(crate) const fn first_frame_charge(&self) -> u64 { + self.first_frame_charge } - /// A success is checked on its return only when it kept more than its own budget, which no - /// frame returns and the check guards against all the same. Within its budget it hands the - /// caller no more than the caller's share, and the caller runs on unchecked; past it, the - /// caller is held to its own budget with what it now keeps, and stops when that crosses it. - #[test] - fn test_a_success_past_its_budget_holds_its_caller_to_the_caller_budget() { - for (kept, caller_stopped) in [(98, false), (99, false), (100, false), (101, true)] { - let (mut limit, child) = with_a_child_of_a_capped_frame(); - limit.tracker.record(LimitUsage { data_size: kept, write_records: 0 }); - let result = - crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); - let stop = limit.stop_before_run(); - let expected = caller_stopped.then_some(LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 100, - used: kept, - frame_local: true, - }); - assert_eq!(stop, expected, "a child that kept {kept} bytes"); - assert_eq!(limit.usage().data_size, kept, "the success merged what it kept"); - } - } + /* What the settled transaction reports */ - /// The premise the unchecked returns rest on is asserted in a debug build. A success within a - /// budget wider than the share its caller gave it — what a share computed wrong would give — - /// puts the caller over its own budget with no check to catch it, and trips. - #[test] - #[cfg(debug_assertions)] - #[should_panic(expected = "no check held it to")] - fn test_a_success_that_hands_its_caller_more_than_its_share_trips() { - let (mut limit, child) = with_a_child_of_a_capped_frame(); - limit.tracker.current_mut().unwrap().budget = u64::MAX; - limit.tracker.record(LimitUsage { data_size: 101, write_records: 0 }); - let result = crate::synthetic_frame_result(&child, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); + /// The history gas the last settled transaction spent. + pub const fn history_gas_spent(&self) -> u64 { + self.history_gas_spent } - /// Whether a start's caller refuses it is staged by the opcode that found it and taken once, - /// by the frame's init. Nothing is left for a later start: a reset drops what the transaction - /// before it left, and a keyless deployment's creation, which no opcode starts, drops what was - /// staged for its call. - #[test] - fn test_a_staged_start_answer_is_taken_once() { - let mut limit = with_the_transactions_frame(); - assert_eq!(limit.take_start_refused(), None, "nothing staged"); - for refused in [false, true] { - limit.stage_start_refused(refused); - assert_eq!(limit.take_start_refused(), Some(refused)); - assert_eq!(limit.take_start_refused(), None, "taken once"); - } - - limit.stage_start_refused(true); - limit.set_frame_creator(TARGET); - assert_eq!(limit.take_start_refused(), None, "the creation's is not the call's"); - - limit.stage_start_refused(true); - limit.reset(); - assert_eq!(limit.take_start_refused(), None, "the next transaction's is not this one's"); + /// The EIP-8037 reservoir the last settled transaction or system call left unspent, which + /// its sender gets back, as a transaction reports it + /// ([`MegaGasUsage::reservoir_remaining`](crate::MegaGasUsage::reservoir_remaining)). It is + /// read before the EIP-7623 floor absorbs it, and a failed deposit leaves none. + pub const fn reservoir_remaining(&self) -> u64 { + self.reservoir_remaining } - /// Limits every dimension holds at zero: anything a transaction counts crosses one. - fn zero_limits() -> EvmTxRuntimeLimits { - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(0).with_frame_data_size_limit(0) + /// Records the reservoir the settled transaction or system call left unspent. + pub(crate) const fn set_reservoir_remaining(&mut self, reservoir: u64) { + self.reservoir_remaining = reservoir; } - /// Counts a body, then starts the transaction's frame and a value call's, and reports the - /// verdicts of the two starts. - fn count_a_transaction(limit: &mut AdditionalLimit) -> [LimitCheck; 2] { - limit.record_tx_body(crate::TX_BODY_SIZE); - let first = limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let records = limit.on_frame_init(&call_from_to(CALLEE, TARGET, U256::from(1)), 1); - [first, records] + /// The history bytes the last settled transaction appended, whoever paid for them, which a + /// transaction reports as [`MegaGasUsage::history_bytes`](crate::MegaGasUsage::history_bytes); + /// [`history_gas_spent`](Self::history_gas_spent) is what the transaction's own gas paid of + /// their price. + pub const fn history_bytes(&self) -> u64 { + self.history_bytes } - /// A transaction that is not exempt is stopped wherever it crosses a limit: counting the - /// body checks nothing, the first check, at its frame's start, is the stop, and a later start - /// that crosses again is a stop of its own, with the usage it reached, not the first one's. - #[test] - fn test_a_transaction_that_is_not_exempt_is_stopped() { - let mut limit = AdditionalLimit::new(zero_limits()); - let [first, records] = count_a_transaction(&mut limit); - let stop = |used| LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: 0, - used, - frame_local: false, + /// Settles the history figures once the transaction's own frame returned: `spent`, the history + /// gas its gas spent, and the history bytes it appended when it pays history at all (`priced`), + /// which are its body and the bytes it keeps but for its Oracle hints and its transfer logs. + pub(crate) fn settle_history(&mut self, priced: bool, spent: u64) { + self.history_gas_spent = spent; + self.history_bytes = if priced { + self.intrinsic_history_bytes + .saturating_add(WRITE_RECORD_SIZE.saturating_mul(self.authorities)) + .saturating_add(positive(self.kept.net(LimitKind::DataSize) as i128)) + .saturating_sub(TRANSFER_LOG_SIZE.saturating_mul(self.kept.transfer_logs)) + } else { + 0 }; - assert_eq!(first, stop(crate::TX_BODY_SIZE), "the body crosses at the first check"); - assert_eq!(records, stop(crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE)); - assert!(!limit.is_exempt()); } +} - /// Validation admits a body whose bytes, with one record for each entry of the authorization - /// list, are within the transaction's limit, and nothing over it; an exempt transaction - /// whatever it carries. +/// `value`, or zero when it is negative, as a `u64` that saturates. +const fn positive(value: i128) -> u64 { + if value <= 0 { + 0 + } else if value > u64::MAX as i128 { + u64::MAX + } else { + value as u64 + } +} + +/// Whether `result` is the revert `stop` makes a frame return: a revert whose output is the +/// stop's [`MegaLimitExceeded`](crate::MegaLimitExceeded). +fn is_the_revert_of(result: &FrameResult, stop: &LimitCheck) -> bool { + let result = result.interpreter_result(); + result.result == InstructionResult::Revert && result.output == stop.revert_data() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A count is none exactly when it adds and takes back nothing in every pool: `NONE` and the + /// default are, and so is a count of no records or no bytes; a count that adds or takes back + /// a record, adds bytes or a transfer log, or moves state growth either way is not. #[test] - fn test_validation_admits_a_body_and_its_authority_records_within_the_limit() { - let body = crate::TX_BODY_SIZE + 2 * crate::AUTHORIZATION_SIZE; - let at = body + 2 * WRITE_RECORD_SIZE; - let layer = |limit: u64, exempt: bool| { - let mut layer = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - ); - if exempt { - layer.exempt(); - } - layer.record_tx_body(body); - layer - }; - assert!(layer(at, false).admits_tx_body(2), "at the limit"); - assert!(!layer(at - 1, false).admits_tx_body(2), "one byte over it"); - assert!(layer(at - 1, false).admits_tx_body(1), "one record fewer"); - assert!(!layer(body - 1, false).admits_tx_body(0), "the body alone over it"); - assert!(layer(0, true).admits_tx_body(2), "an exempt transaction"); - assert_eq!(layer(at, false).body_bytes(), body); - assert_eq!(layer(at, false).usage().data_size, body, "the body is counted"); + fn test_a_count_is_none_only_when_it_moves_no_pool() { + let cases = [ + ("NONE", Counted::NONE, true), + ("the default", Counted::default(), true), + ("no records", Counted::records(0, 0, false), true), + ("no bytes", Counted::bytes(0), true), + ("no growth", Counted::NONE.with_growth(0, 0), true), + ("a record made", Counted::records(1, 0, false), false), + ("a record taken back", Counted::records(0, 1, false), false), + ("a transfer log", Counted::records(0, 0, true), false), + ("bytes", Counted::bytes(1), false), + ("a rise", Counted::NONE.with_growth(1, 0), false), + ("a fall", Counted::NONE.with_growth(0, 1), false), + ]; + for (case, counted, none) in cases { + assert_eq!(counted.is_none(), none, "{case}: {counted:?}"); + } } - /// An exempt transaction is stopped by no limit, in any dimension, at the transaction or at a - /// frame: every verdict is within the limits and no caller is stopped. What it uses is counted - /// all the same. + /// An exempt layer answers every crossing as within the limits, in any dimension and at the + /// transaction or at a frame; the next transaction begins held to its limits again. #[test] - fn test_an_exempt_transaction_is_stopped_by_no_limit() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - assert_eq!(count_a_transaction(&mut limit), [LimitCheck::WithinLimit; 2]); + fn test_the_exemption_answers_every_crossing_and_lasts_one_transaction() { + let mut limit = AdditionalLimit::default(); + limit.begin_transaction(true, false, 0); + assert!(limit.is_exempt()); for kind in [LimitKind::DataSize, LimitKind::ComputeGas] { for frame_local in [false, true] { let verdict = limit.crossed(kind, 0, 1, frame_local); assert_eq!(verdict, LimitCheck::WithinLimit, "{kind:?}, frame-local {frame_local}"); } } - assert_eq!(limit.stop_before_run(), None); + limit.begin_transaction(false, false, 0); + assert!(!limit.is_exempt()); assert_eq!( - limit.usage(), - LimitUsage { data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 }, - ); - - let result = crate::synthetic_frame_result( - &call_from_to(CALLEE, TARGET, U256::from(1)), - InstructionResult::Stop, - Bytes::new(), + limit.crossed(LimitKind::ComputeGas, 0, 1, false), + LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 0, + used: 1, + frame_local: false + }, + "the next transaction is held to its limits" ); - let _ = limit.on_frame_return(&result); - assert_eq!(limit.stop_before_run(), None, "the caller runs on"); } /// Validation admits no body whose authority records cross the data-size limit, so a debug @@ -1411,292 +925,10 @@ mod tests { #[cfg(debug_assertions)] #[should_panic(expected = "validation admits no body whose authority records cross")] fn test_authority_records_that_cross_the_limit_trip() { - let mut limit = AdditionalLimit::new( - EvmTxRuntimeLimits::no_limits() - .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE), - ); - limit.record_tx_body(crate::TX_BODY_SIZE); - limit.record_applied_authorities(SENDER, 2, false); - } - - /// Applied authorities are recorded for an exempt transaction, whatever they cross. - #[test] - fn test_an_exempt_transaction_records_its_authorities() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - limit.record_applied_authorities(SENDER, 2, false); - assert_eq!(limit.usage(), WRITE_RECORD.times(2)); - } - - /// The exemption is the transaction's: a reset clears it, and the next transaction is held to - /// its limits again. An out-of-gas before the first frame keeps it. - #[test] - fn test_the_exemption_lasts_one_transaction() { - let mut limit = AdditionalLimit::new(zero_limits()); - limit.exempt(); - let result = crate::synthetic_frame_result( - &call_from_to(SENDER, CALLEE, U256::ZERO), - InstructionResult::OutOfGas, - Bytes::new(), - ); - limit.on_last_frame_return(&result); - assert!(limit.is_exempt(), "an out-of-gas before the first frame keeps the exemption"); - - limit.reset(); - assert!(!limit.is_exempt()); - let [first, ..] = count_a_transaction(&mut limit); - assert!(first.exceeded_limit(), "after a reset the transaction is held to its limits"); - } - - /// A layer whose transaction's value movements journal transfer logs, under `limits`. - fn logging(limits: EvmTxRuntimeLimits) -> AdditionalLimit { + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_data_size_limit(crate::TX_BODY_SIZE + WRITE_RECORD_SIZE); let mut limit = AdditionalLimit::new(limits); - limit.set_transfer_logs(true); - limit - } - - /// A creation from `caller` endowing the account it creates with `value`. - fn creation(caller: Address, value: U256) -> FrameInput { - FrameInput::Create(Box::new(revm::interpreter::CreateInputs::new( - caller, - revm::interpreter::CreateScheme::Create, - value, - Bytes::new(), - 100_000, - 0, - ))) - } - - /// Exactly the frame starts that move value to another account count a transfer log: a value - /// call to another account and an endowed creation, at the transaction's own frame and below - /// it. A call to itself, a `CALLCODE`, a valueless call of any scheme, a `DELEGATECALL`, a - /// `STATICCALL` and a creation without an endowment count none; and nothing counts one when - /// the transaction's value movements journal no log. - #[test] - fn test_a_frame_start_counts_a_transfer_log_where_value_moves() { - let one = U256::from(1); - let scheme = |scheme, value| { - FrameInput::Call(Box::new(CallInputs { - caller: CALLEE, - target_address: if scheme == CallScheme::CallCode { CALLEE } else { TARGET }, - ..call_inputs(scheme, value) - })) - }; - for (input, moves) in [ - (call_from_to(CALLEE, TARGET, one), true), - (call_from_to(CALLEE, CALLEE, one), false), - (call_from_to(CALLEE, TARGET, U256::ZERO), false), - (scheme(CallScheme::CallCode, one), false), - (scheme(CallScheme::StaticCall, U256::ZERO), false), - (creation(CALLEE, one), true), - (creation(CALLEE, U256::ZERO), false), - ] { - assert_eq!(moves_value(&input), moves, "{input:?}"); - assert!(!with_the_transactions_frame().frame_start_transfer_log(&input), "off"); - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - assert_eq!(limit.frame_start_transfer_log(&input), moves, "{input:?}"); - let before = limit.usage(); - limit.on_frame_init(&input, 1); - let records = limit.usage().write_records - before.write_records; - assert_eq!( - limit.usage().data_size - before.data_size, - WRITE_RECORD_SIZE * records + if moves { TRANSFER_LOG_SIZE } else { 0 }, - "{input:?}", - ); - } - let delegate = FrameInput::Call(Box::new(CallInputs { - value: CallValue::Apparent(one), - ..call_inputs(CallScheme::DelegateCall, one) - })); - assert!(!moves_value(&delegate), "a delegate call carries its caller's value, no transfer"); - - // The transaction's own frame: its value to another account, and its endowed creation. - for (input, moves) in [ - (call_from_to(SENDER, CALLEE, one), true), - (call_from_to(SENDER, SENDER, one), false), - (creation(SENDER, one), true), - ] { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&input, 0); - let log = limit.usage().data_size - WRITE_RECORD_SIZE * limit.usage().write_records; - assert_eq!(log, if moves { TRANSFER_LOG_SIZE } else { 0 }, "{input:?}"); - } - } - - /// A transfer log is data size and nothing else: no write record, and no history byte — the - /// transaction's history is its body and its records, whatever it moved. - #[test] - fn test_a_transfer_log_is_data_size_and_never_history() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.set_intrinsic_history(1, crate::TX_BODY_SIZE); - limit.record_tx_body(crate::TX_BODY_SIZE); - let outer = call_from_to(SENDER, CALLEE, U256::from(1)); - limit.on_frame_init(&outer, 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.stage_frame_charge(limit.frame_start_records(&inner), 0, 0); - limit.on_frame_init(&inner, 1); - assert_eq!( - limit.usage(), - LimitUsage { - data_size: crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE, - write_records: 2, - }, - "the recipient of each move — the inner one's caller is the outer one's — and two logs", - ); - - let result = crate::synthetic_frame_result(&inner, InstructionResult::Stop, Bytes::new()); - let _ = limit.on_frame_return(&result); - let result = crate::synthetic_frame_result(&outer, InstructionResult::Stop, Bytes::new()); - limit.on_last_frame_return(&result); - limit.settle_history_bytes(true); - assert_eq!(limit.history_bytes(), crate::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE); - } - - /// A frame that fails takes its transfer log back with its records, as revm's checkpoint - /// takes back the move and the log. - #[test] - fn test_a_failed_frame_gives_its_transfer_log_back() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - limit.on_frame_init(&inner, 1); - assert_eq!(limit.usage().data_size, 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); - - let result = crate::synthetic_frame_result(&inner, InstructionResult::Revert, Bytes::new()); - let _ = limit.on_frame_return(&result); - assert_eq!(limit.usage(), LimitUsage::ZERO); - } - - /// A frame start whose transfer log crosses a limit is stopped there, before revm moves the - /// value, with a stop that names the limit it crossed, its own budget or the transaction's - /// limit. The records alone - /// fit, so it is the log that crosses; at exactly the limit it holds. - #[test] - fn test_a_frame_start_whose_transfer_log_crosses_is_stopped() { - let records = 2 * WRITE_RECORD_SIZE; - let needs = records + TRANSFER_LOG_SIZE; - let inner = call_from_to(CALLEE, TARGET, U256::from(1)); - // The smallest frame cap whose share, the budget of a child of the first frame, holds it. - let cap = (needs..).find(|cap| share_of_remaining(*cap) >= needs).unwrap(); - assert_eq!(share_of_remaining(cap), needs); - for (cap, fits) in [(cap, true), (cap - 1, false)] { - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - let check = limit.on_frame_init(&inner, 1); - if fits { - assert_eq!(check, LimitCheck::WithinLimit, "exactly the budget"); - } else { - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: needs - 1, - used: needs, - frame_local: true, - }, - ); - } - } - - // The transaction's own value: one record, the recipient's, and the log. - let first = call_from_to(SENDER, CALLEE, U256::from(1)); - let needs = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - for (tx_limit, fits) in [(needs, true), (needs - 1, false), (WRITE_RECORD_SIZE, false)] { - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(tx_limit)); - let check = limit.on_frame_init(&first, 0); - if fits { - assert_eq!(check, LimitCheck::WithinLimit, "exactly the limit"); - continue; - } - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: tx_limit, - used: needs, - frame_local: false, - }, - ); - } - } - - /// A `SELFDESTRUCT` that moved value to another account counts its transfer log with the - /// beneficiary's record, in one check, and reports the record's history alone. To the sender, - /// whose account the body counts, it is the log alone, and the log alone can cross. - #[test] - fn test_a_destruction_counts_its_transfer_log_with_its_beneficiary() { - let destruction = |beneficiary| StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary, - }; - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(TARGET)); - let (check, history) = limit.commit_staged_record(); - assert_eq!(check, LimitCheck::WithinLimit); - assert_eq!(history, HistoryBytes::Appended(WRITE_RECORD_SIZE), "the record's alone"); - assert_eq!( - limit.usage(), - LimitUsage { data_size: WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, - ); - - let mut limit = - logging(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TRANSFER_LOG_SIZE - 1)); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(SENDER)); - let (check, history) = limit.commit_staged_record(); - assert_eq!(history, HistoryBytes::None); - assert_eq!( - check, - LimitCheck::ExceedsLimit { - kind: LimitKind::DataSize, - limit: TRANSFER_LOG_SIZE - 1, - used: TRANSFER_LOG_SIZE, - frame_local: false, - }, - "the log alone crosses", - ); - - let mut limit = AdditionalLimit::default(); - limit.on_frame_init(&call_from_to(SENDER, CALLEE, U256::ZERO), 0); - limit.stage_record(destruction(TARGET)); - let _ = limit.commit_staged_record(); - assert_eq!(limit.usage(), WRITE_RECORD, "no log, no bytes"); - } - - /// The transfer logs are the transaction's to set: a reset turns them off until the next - /// transaction sets them again. - #[test] - fn test_a_reset_turns_the_transfer_logs_off() { - let mut limit = logging(EvmTxRuntimeLimits::no_limits()); - let input = call_from_to(SENDER, CALLEE, U256::from(1)); - assert!(limit.frame_start_transfer_log(&input)); - limit.reset(); - assert!(!limit.frame_start_transfer_log(&input)); - } - - /// The allowance follows the transfer, and only the two schemes that can carry one: a `CALL` - /// or a `CALLCODE` that moves value is granted one, and nothing else is — a valueless call of - /// either scheme, and `DELEGATECALL` and `STATICCALL`, which take no value word at all. - #[test] - fn test_only_a_value_call_or_callcode_is_granted_an_allowance() { - for scheme in [ - CallScheme::Call, - CallScheme::CallCode, - CallScheme::DelegateCall, - CallScheme::StaticCall, - ] { - let carries_value = matches!(scheme, CallScheme::Call | CallScheme::CallCode); - assert_eq!( - grants_stipend(&call_inputs(scheme, U256::from(1))), - carries_value, - "{scheme:?} with value", - ); - assert!(!grants_stipend(&call_inputs(scheme, U256::ZERO)), "{scheme:?} without value"); - } + limit.begin_transaction(false, false, crate::TX_BODY_SIZE); + limit.count_authorities(2, 0); } } diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 226bf53c8..d29dcc328 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -6,15 +6,20 @@ //! data-size limit below, and detention for compute gas. //! //! Gas detention caps compute, [`LimitKind::ComputeGas`]: its state lives beside this module, in -//! [`Detention`](crate::Detention), because what it meters is gas rather than anything the lanes -//! count, and it holds a frame to the cap with the gas the frame may spend. It stops the frame that -//! crosses the cap with the same revert ([`AdditionalLimit`]), with the compute the transaction may -//! reach as the limit, and its compute at the crossing as what was used +//! [`Detention`](crate::Detention), because what it meters is gas rather than bytes, and it holds a +//! frame to the cap with the gas the frame may spend. It stops the frame +//! that crosses the cap with the same revert ([`AdditionalLimit`]), with the compute the +//! transaction may reach as the limit, and its compute at the crossing as what was used //! ([`LimitCheck::ExceedsLimit`]). //! -//! It also counts what the data-size limit meters, at the sites the bytes are made: data-size -//! bytes and write records, on a lane per frame ([`AdditionalLimit`]). The Host stages what it -//! observes ([`StagedRecord`]) and the opcode commits it once it completed. +//! What the data-size limit meters — data-size bytes, among them the write records — is drawn from +//! the byte pool on each frame's gas tracker, which the revm fork forwards to a child as its share +//! and settles as it does the reservoir: a frame that fails gives its draws back, and a frame that +//! succeeds hands its caller what it kept. A write an opcode makes is drawn once the opcode +//! completed, in the Host's completed-write hook, which revm calls after every charge the opcode +//! makes; a frame start's records once revm decided the start, on the pool its frame starts with. +//! [`AdditionalLimit`] holds the transaction's limit beside the pools, on what the transaction +//! keeps, with the stops and the settled figures. //! //! # The data-size limit //! @@ -23,8 +28,13 @@ //! counted, and a child gets [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of //! what its parent has left, under [`EvmTxRuntimeLimits::frame_data_size_limit`]. A frame that //! crosses either reverts alone, its caller resumes, and what the frame counted goes with it, so -//! the caller is back within both ([`AdditionalLimit`]). The budget is what keeps a caller's own -//! work safe from what it calls: a child inherits its caller's whole reservoir, so gas does not +//! the caller is back within both ([`AdditionalLimit`]), but in one case: a failed child's rollback +//! restores what the frames above it kept at its start, a record of theirs it took back included, +//! while an Oracle hint it admitted stays counted, so a hint sent into the room such a take-back +//! freed leaves the transaction over its data-size limit, and the caller returns that limit's stop +//! before it runs another instruction ([`AdditionalLimit::hold_caller`](AdditionalLimit)), whether +//! the child reverted, halted or was itself stopped. The budget is what keeps a caller's own +//! work safe from what it calls: a child inherits 98/100 of its caller's reservoir, so gas does not //! bound the bytes it can append, and without a budget a callee could take the transaction to its //! limit and leave its caller nothing to carry on with once it catches the stop. A creation //! stopped at its start still bumps its creator's nonce, and the record of that write lands on the @@ -36,36 +46,49 @@ //! - the body, before any frame; neither a revert nor an out-of-gas takes it back; //! - the records of the applied EIP-7702 authorities, before the first frame; //! - the records a frame's start makes, when the frame starts; -//! - a storage write's record, a log's bytes and the record of a `SELFDESTRUCT`'s beneficiary, once -//! the opcode completed; -//! - deployed code, on the creation's lane before the creation is committed, so a crossing leaves +//! - a storage write's record, a log's bytes and the records of a `SELFDESTRUCT` — the account it +//! clears and its beneficiary — once the opcode completed; +//! - deployed code, on the creation's pool before the creation is committed, so a crossing leaves //! no code behind. Only code revm would deposit counts: code starting with `0xEF` or over the //! code-size limit, and a creation that cannot pay for its deposit, fail the creation alone and //! are not counted; -//! - an Oracle hint's payload, on the transaction's own lane, before it is forwarded; +//! - an Oracle hint's payload, as the transaction's own, before it is forwarded; //! - an EIP-7708 transfer log, which revm journals itself for every value movement, where the value //! moves: with the records of the frame start that moves it — the transaction's own value, a -//! value `CALL`, a creation's endowment — before revm builds the frame, so a crossing answers the -//! frame with the stop before any value moves; and with a `SELFDESTRUCT`'s beneficiary once the -//! opcode completed. Each is counted by the rule a `LOG3` of one word is ([`TRANSFER_LOG_SIZE`]), -//! on the lane of the frame whose journal checkpoint holds the move, so the failure that takes -//! the move back takes the bytes back. +//! value `CALL`, a creation's endowment — and with a `SELFDESTRUCT`'s beneficiary once the opcode +//! completed. Each is counted by the rule a `LOG3` of one word is ([`TRANSFER_LOG_SIZE`]), on the +//! pool of the frame whose journal checkpoint holds the move, so the failure that takes the move +//! back takes the bytes back. //! -//! A frame start is counted before revm decides it, so what it counts is a prediction of what revm -//! will do. As far as the caller's account decides it, the prediction is revm's own: a start revm -//! refuses there — a value its caller cannot fund, a creation whose creator's nonce cannot be -//! bumped — moves and writes nothing, so it counts nothing and is charged nothing, and no limit -//! stops it. The caller's account is read from the journal without loading anything. The one -//! refusal decided after the count is a creation onto an occupied address, which revm reads off -//! the created address's account only once it builds the frame: its records and transfer log are -//! counted, so a crossing they cause stops the creation where revm would have failed it, and -//! without a crossing the failure discards them. +//! A frame start's records are read off the journal before revm decides the start, as the hook +//! that charges its caller for them reads them, and counted and held to the limits once revm +//! decided it, on the pool its frame starts with; a debug build holds them to what revm's start +//! made of the accounts. A frame revm builds returns the stop on its first run when its start +//! crossed a limit, and its revert takes back the value revm moved and the transfer log it +//! journaled; an answer revm gives without building a frame — a call to an account with no code, to +//! a precompile — gives way to the stop, and what its start moved is taken back with it. A start +//! revm refuses on its caller's account — a value its caller cannot fund, a creation whose +//! creator's nonce cannot be bumped — moves and writes nothing, so it counts nothing and no limit +//! stops it; its opcode, which reads the caller's account first, charged nothing for its records. +//! A start an inspector rewrote after its opcode is not charged again: what the opcode charged +//! stands, and its declared part comes back only as it does for any start whose frame keeps +//! nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value. +//! Its records are those revm then made. +//! +//! A creator's nonce record is counted from what revm did, not predicted: the creator is read +//! before revm decides the creation and again once the creation returned into it, and a nonce revm +//! bumped is counted on the creator then, held to the creator's budget and then to the +//! transaction's limit, a crossing stopping the creator before it runs on. The creation's budget +//! is the share of what the creator had left at its opcode, taken before the record. The record +//! outlives the creation's failure: a creation revm fails after the bump, onto an occupied address, +//! is held to nothing at its start, and its failure discards its records and transfer log, but the +//! creator's record is counted all the same. //! //! A record is checked against the limits before its history is charged: a record the limit //! rejects is not kept, so it is not charged, and the stop is what its frame reports. At a frame //! start the order is the other way round — the caller pays for the records at its opcode, before -//! the frame starts and its records are counted — so a caller that cannot pay runs out of gas -//! first. +//! revm decides the start and its records are held to the limits — so a caller that cannot pay +//! runs out of gas first, whether or not revm would have refused the start. //! //! Nothing counted before the first frame crosses the limit: validation refuses a transaction //! whose body, with a record for each entry of its authorization list, exceeds it @@ -75,25 +98,47 @@ //! //! # Write records //! -//! The write-record count the lanes keep is the KV count a node reports: one record per account -//! or storage write the transaction keeps, deduplicated per frame, taken back with a slot written -//! back to its original value and with the frame that fails. The sender's account and the accounts -//! fees are credited to are the body's, not records. No limit holds the count: a record weighs -//! [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so the data-size -//! limit bounds the records, and history gas prices each of them. +//! The write-record count [`AdditionalLimit`] keeps is the KV count a node reports: one record per +//! account or storage write the transaction keeps, following the net change — a slot's while its +//! value differs from its original, an account's while its nonce, balance or code differs from what +//! the transaction loaded, whichever writes changed it, a creation's created account included — +//! taken back by a write that returns the slot or the account and with the frame that fails. The +//! sender's account and the fee credits the settlement makes are the body's, not records; a write +//! execution makes to a fee account that is not the sender is a record like a write to any other +//! account. The KV-update limit holds the count, per transaction at +//! [`EvmTxRuntimeLimits::tx_kv_update_limit`] and per frame at the same 98/100 share of what the +//! parent has left, on the KV-update pool ([`KV_UPDATE_POOL`]). A record also weighs +//! [`WRITE_RECORD_SIZE`] bytes of data size, counted and taken back with them, so at the spec's +//! numbers the data-size limit binds first; history gas prices each of them. +//! +//! # The order of the counted dimensions +//! +//! An operation that crosses more than one of data size, KV updates and state growth stops on the +//! first of them in that order ([`COUNTED`]). Inside each, the frame's budget is tested before the +//! transaction's limit, and the stop names the budget when the budget is crossed — which a frame +//! that crosses the transaction's limit does too, unless Oracle hints, on no frame's budget, used +//! what the transaction had left. //! //! # State growth //! -//! No limit holds the state a transaction adds. EIP-8037 charges state gas for exactly that state, -//! at the SALT price of the bucket it lands in, so state growth is bounded by what it costs: the -//! transaction's gas limit and the block's. +//! The state growth [`AdditionalLimit`] keeps is the net count of the new accounts and new slots a +//! transaction keeps, one unit where EIP-8037 charges the state gas of one: a slot an `SSTORE` +//! makes non-zero from an original of zero, which a write back to zero takes back; an account a +//! value transfer, a creation, a `SELFDESTRUCT`'s balance, an applied authorization, a deposit or a +//! keyless signer's nonce bump creates. A failed frame's net goes with it, and a negative net never +//! enlarges a child's budget. The state-growth limit holds the count, per transaction at +//! [`EvmTxRuntimeLimits::tx_state_growth_limit`] and per frame at the same 98/100 share, on the +//! state-growth pool ([`STATE_GROWTH_POOL`]). EIP-8037 still prices the same state, at the SALT +//! price of the bucket it lands in; the count is what stops the 1,001st slot. //! //! # The limits //! //! They are the per-transaction half of //! [`ProtocolLimits::for_spec`](crate::ProtocolLimits::for_spec), which for Satin holds a -//! transaction to [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, every frame to -//! its share of it, and a detained transaction to detention's caps. +//! transaction to [`TX_DATA_LIMIT`](crate::constants::TX_DATA_LIMIT) of data size, +//! [`TX_KV_UPDATE_LIMIT`](crate::constants::TX_KV_UPDATE_LIMIT) write records and +//! [`TX_STATE_GROWTH_LIMIT`](crate::constants::TX_STATE_GROWTH_LIMIT) new accounts and slots, every +//! frame to its share of each, and a detained transaction to detention's caps. //! //! # The exemption //! @@ -101,8 +146,9 @@ //! transaction ([`crate::system::is_system_originated`]) and a system call — the pre-block calls //! among them — are exempt ([`AdditionalLimit::is_exempt`]), sticky for the transaction, and the //! one place every stop comes from answers that they are within the limits whatever they cross: -//! the data size and the frame budgets. It is the set that pays no history gas, exempt for the -//! same reason: the protocol's maintenance must not fail on a resource limit. What such a +//! the data size, the KV updates, the state growth and the frame budgets. It is the set that pays +//! no history gas, exempt for the same reason: the protocol's maintenance must not fail on a +//! resource limit. What such a //! transaction uses is counted all the same and reported in its usage and in the block's counters, //! as a deposit's is. A user's deposit is not in the set and is held to every limit. //! @@ -128,19 +174,37 @@ //! recipient is the block beneficiary or a fee vault pays a record the body already bound. It is //! an over-charge, never an under-charge. -mod frame_limit; #[allow(clippy::module_inception)] mod limit; mod record; pub use limit::AdditionalLimit; -pub(crate) use limit::FrameStartRecords; -pub(crate) use record::HistoryBytes; -pub use record::StagedRecord; +pub(crate) use limit::Counted; +pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes}; +#[cfg(debug_assertions)] +pub(crate) use record::{RecordDelta, StartRecords}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; -use revm::context::result::ExecutionResult; +use revm::{context::result::ExecutionResult, interpreter::PoolId}; + +/// The pool of a frame's gas tracker that is the frame's data-size budget: the bytes the frame +/// may still keep. +pub(crate) const DATA_SIZE_POOL: PoolId = PoolId::new(0); + +/// The pool of a frame's gas tracker that is the frame's KV-update budget: the write records the +/// frame may still keep. +pub(crate) const KV_UPDATE_POOL: PoolId = PoolId::new(1); + +/// The pool of a frame's gas tracker that is the frame's state-growth budget: the new accounts +/// and new storage slots the frame may still keep, net. +pub(crate) const STATE_GROWTH_POOL: PoolId = PoolId::new(2); + +/// The dimensions the common execution layer counts and limits, each drawn from the pool of a +/// frame's gas tracker it names ([`LimitKind::pool`]), in the order an operation that crosses more +/// than one of them stops on: data size, KV updates, state growth. +pub(crate) const COUNTED: [LimitKind; 3] = + [LimitKind::DataSize, LimitKind::KvUpdate, LimitKind::StateGrowth]; /// Bytes of one write record: the key and value delta one account or storage write leaves in /// the state diff. @@ -212,10 +276,11 @@ pub const FRAME_DATA_SHARE_NUMERATOR: u64 = 98; /// Denominator of [`FRAME_DATA_SHARE_NUMERATOR`]. pub const FRAME_DATA_SHARE_DENOMINATOR: u64 = 100; -/// What a transaction or a frame counts: data-size bytes and write records. +/// What a transaction or a frame counts: data-size bytes, write records and state growth, each the +/// dimension's net, never below zero. /// -/// The write-record count is the KV count a node reports; no limit holds it. Every record weighs -/// [`WRITE_RECORD_SIZE`] bytes of data size and is taken back with them, so +/// The write-record count is the KV count a node reports, which the KV-update limit holds. Every +/// record weighs [`WRITE_RECORD_SIZE`] bytes of data size and is taken back with them, so /// `write_records × WRITE_RECORD_SIZE` never exceeds `data_size`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct LimitUsage { @@ -223,15 +288,20 @@ pub struct LimitUsage { pub data_size: u64, /// Account and storage write records: the KV count. pub write_records: u64, + /// New accounts and new storage slots, net: the state growth. + pub state_growth: u64, } -/// Limits one transaction's data size and its compute after a read of volatile data. +/// Limits one transaction's data size, its write records, its state growth and its compute after +/// a read of volatile data. /// -/// [`tx_data_size_limit`](Self::tx_data_size_limit) is what the transaction may keep: a frame -/// whose count crosses it reverts alone. A frame's own budget is derived from it: the transaction's -/// frame gets what the transaction has left, and each child gets [`FRAME_DATA_SHARE_NUMERATOR`] / -/// [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent has left. Crossing a frame budget reverts -/// that frame alone. +/// [`tx_data_size_limit`](Self::tx_data_size_limit), +/// [`tx_kv_update_limit`](Self::tx_kv_update_limit) and +/// [`tx_state_growth_limit`](Self::tx_state_growth_limit) are what the transaction may keep: a +/// frame whose count crosses one reverts alone. A frame's own budget in each is derived from it: +/// the transaction's frame gets what the transaction has left, and each child gets +/// [`FRAME_DATA_SHARE_NUMERATOR`] / [`FRAME_DATA_SHARE_DENOMINATOR`] of what its parent has left. +/// Crossing a frame budget reverts that frame alone. /// /// [`frame_data_size_limit`](Self::frame_data_size_limit) is a further cap on every frame's budget. /// @@ -251,6 +321,17 @@ pub struct EvmTxRuntimeLimits { /// The most data-size bytes the transaction may keep. Crossing it reverts the frame that /// crosses it. pub tx_data_size_limit: u64, + /// The most write records the transaction may keep: its KV count. Crossing it reverts the + /// frame that crosses it, and every frame's KV budget is its share of what its parent has + /// left. A limits file without it takes the default spec's. + #[serde(default = "default_tx_kv_update_limit")] + pub tx_kv_update_limit: u64, + /// The most new accounts and new storage slots the transaction may keep, net: its state + /// growth. Crossing it reverts the frame that crosses it, and every frame's state-growth + /// budget is its share of what its parent has left. A limits file without it takes the + /// default spec's. + #[serde(default = "default_tx_state_growth_limit")] + pub tx_state_growth_limit: u64, /// A cap on every frame's data-size budget, applied after the share of what its parent has /// left. Crossing it reverts the frame alone. pub frame_data_size_limit: u64, @@ -271,6 +352,16 @@ pub struct EvmTxRuntimeLimits { pub oracle_access_compute_gas_limit: u64, } +/// The default spec's transaction KV-update limit, for a limits file that does not name one. +fn default_tx_kv_update_limit() -> u64 { + EvmTxRuntimeLimits::default().tx_kv_update_limit +} + +/// The default spec's transaction state-growth limit, for a limits file that does not name one. +fn default_tx_state_growth_limit() -> u64 { + EvmTxRuntimeLimits::default().tx_state_growth_limit +} + impl Default for EvmTxRuntimeLimits { /// The limits of the default spec's table: what a [`MegaContext`](crate::MegaContext) of that /// spec runs under. @@ -293,6 +384,8 @@ impl EvmTxRuntimeLimits { pub const fn no_limits() -> Self { Self { tx_data_size_limit: u64::MAX, + tx_kv_update_limit: u64::MAX, + tx_state_growth_limit: u64::MAX, frame_data_size_limit: u64::MAX, block_env_access_compute_gas_limit: u64::MAX, oracle_access_compute_gas_limit: u64::MAX, @@ -305,6 +398,18 @@ impl EvmTxRuntimeLimits { self } + /// Sets the most write records the transaction may keep. + pub const fn with_tx_kv_update_limit(mut self, limit: u64) -> Self { + self.tx_kv_update_limit = limit; + self + } + + /// Sets the most new accounts and new storage slots the transaction may keep, net. + pub const fn with_tx_state_growth_limit(mut self, limit: u64) -> Self { + self.tx_state_growth_limit = limit; + self + } + /// Caps every frame's data-size budget at `limit`. pub const fn with_frame_data_size_limit(mut self, limit: u64) -> Self { self.frame_data_size_limit = limit; @@ -325,44 +430,39 @@ impl EvmTxRuntimeLimits { } } -/// One write record. -pub(crate) const WRITE_RECORD: LimitUsage = - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }; - -/// One EIP-7708 transfer log: data size, and no write record. -pub(crate) const TRANSFER_LOG: LimitUsage = - LimitUsage { data_size: TRANSFER_LOG_SIZE, write_records: 0 }; - impl LimitUsage { /// Nothing counted. - pub const ZERO: Self = Self { data_size: 0, write_records: 0 }; + pub const ZERO: Self = Self { data_size: 0, write_records: 0, state_growth: 0 }; - /// Whether `self` keeps more data-size bytes than `limit`, the one dimension a limit holds. + /// Whether `self` keeps more data-size bytes than `limit`: what validation holds a body to. pub(crate) const fn exceeds_data_size(self, limit: u64) -> bool { self.data_size > limit } - /// Both counters added, saturating. + /// Every counter added, saturating. pub const fn saturating_add(self, other: Self) -> Self { Self { data_size: self.data_size.saturating_add(other.data_size), write_records: self.write_records.saturating_add(other.write_records), + state_growth: self.state_growth.saturating_add(other.state_growth), } } - /// Both counters subtracted, saturating at zero. + /// Every counter subtracted, saturating at zero. pub const fn saturating_sub(self, other: Self) -> Self { Self { data_size: self.data_size.saturating_sub(other.data_size), write_records: self.write_records.saturating_sub(other.write_records), + state_growth: self.state_growth.saturating_sub(other.state_growth), } } - /// Both counters multiplied by `n`, saturating. + /// Every counter multiplied by `n`, saturating. pub const fn times(self, n: u64) -> Self { Self { data_size: self.data_size.saturating_mul(n), write_records: self.write_records.saturating_mul(n), + state_growth: self.state_growth.saturating_mul(n), } } } @@ -380,15 +480,18 @@ alloy_sol_types::sol! { /// A resource dimension a limit meters. /// /// The discriminants are the `kind` of [`MegaLimitExceeded`] and keep the values the legacy engine -/// encoded, so a contract that decodes the legacy revert data decodes Satin's. The legacy engine's -/// key-value updates, `1`, and state growth, `3`, name no dimension: no limit holds the write -/// records or the state a transaction adds. +/// encoded, so a contract that decodes the legacy revert data decodes Satin's. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LimitKind { /// Bytes of data a transaction produces; metered by the data-size limit. DataSize, + /// The write records a transaction keeps, its KV count; metered by the KV-update limit. + KvUpdate, /// Compute gas, the regular gas a transaction spends; capped by detention. ComputeGas, + /// The new accounts and new storage slots a transaction keeps, net; metered by the + /// state-growth limit. + StateGrowth, } impl LimitKind { @@ -396,7 +499,9 @@ impl LimitKind { pub const fn as_u8(&self) -> u8 { match self { Self::DataSize => 0, + Self::KvUpdate => 1, Self::ComputeGas => 2, + Self::StateGrowth => 3, } } @@ -404,10 +509,23 @@ impl LimitKind { pub const fn from_u8(kind: u8) -> Option { match kind { 0 => Some(Self::DataSize), + 1 => Some(Self::KvUpdate), 2 => Some(Self::ComputeGas), + 3 => Some(Self::StateGrowth), _ => None, } } + + /// The pool of a frame's gas tracker the dimension is drawn from; `None` for compute, which + /// gas detention holds through the frame's gas instead. + pub(crate) const fn pool(&self) -> Option { + match self { + Self::DataSize => Some(DATA_SIZE_POOL), + Self::KvUpdate => Some(KV_UPDATE_POOL), + Self::StateGrowth => Some(STATE_GROWTH_POOL), + Self::ComputeGas => None, + } + } } /// The verdict of a limit check. @@ -430,11 +548,11 @@ pub enum LimitCheck { /// The usage that crossed it. /// /// For [`LimitKind::ComputeGas`] it is the transaction's compute before the charge that - /// would have crossed the limit, which the regular ledger bills: gas detention stops a - /// frame on a regular charge its spendable gas could not pay, does not make it, and puts - /// the frame's gas back to what it had before it. The charge's size is not kept, so this - /// is at most the limit, unless a halting frame's leftover, counted as compute, took the - /// transaction past it before the charge. + /// would have crossed the limit, which the regular ledger bills less the stipends of the + /// transaction's value calls, gas nobody paid: gas detention stops a frame on a regular + /// charge its spendable gas could not pay, does not make it, and puts the frame's gas + /// back to what it had before it. The charge's size is not kept, so this is at most the + /// limit. used: u64, /// Whether the limit is a frame budget rather than a transaction-level limit. frame_local: bool, @@ -473,8 +591,8 @@ impl LimitCheck { /// A limit that stopped a transaction: the dimension, the limit and the usage that crossed it, of /// the crossing that produced the result of the transaction's own frame — a transaction-level -/// limit, or that frame's own data-size budget. It is what an RPC maps a limit stop to, in place of -/// the halt reasons the legacy engine reported one with. +/// limit, or that frame's own budget in data size, KV updates or state growth. It is what an RPC +/// maps a limit stop to, in place of the halt reasons the legacy engine reported one with. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LimitStop { /// The dimension crossed. @@ -538,8 +656,6 @@ mod tests { assert_eq!(AUTHORIZATION_SIZE, 101); assert_eq!(ACCESS_LIST_ADDRESS_SIZE, 20); assert_eq!(ACCESS_LIST_SLOT_SIZE, 32); - // A storage write and an account write are the same record. - assert_eq!(WRITE_RECORD, LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 }); } /// `no_limits` leaves every dimension unlimited: it is what the execution-spec gate installs @@ -548,12 +664,16 @@ mod tests { fn test_no_limits_leaves_every_dimension_unlimited() { let EvmTxRuntimeLimits { tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, } = EvmTxRuntimeLimits::no_limits(); for limit in [ tx_data_size_limit, + tx_kv_update_limit, + tx_state_growth_limit, frame_data_size_limit, block_env_access_compute_gas_limit, oracle_access_compute_gas_limit, @@ -574,6 +694,8 @@ mod tests { assert_eq!( default .with_tx_data_size_limit(u64::MAX) + .with_tx_kv_update_limit(u64::MAX) + .with_tx_state_growth_limit(u64::MAX) .with_block_env_access_compute_gas_limit(u64::MAX) .with_oracle_access_compute_gas_limit(u64::MAX), EvmTxRuntimeLimits::no_limits() @@ -589,15 +711,17 @@ mod tests { #[test] fn test_limit_usage_arithmetic_saturates() { - let max = LimitUsage { data_size: u64::MAX, write_records: u64::MAX }; - assert_eq!(max.saturating_add(WRITE_RECORD), max); - assert_eq!(LimitUsage::ZERO.saturating_sub(WRITE_RECORD), LimitUsage::ZERO); - assert_eq!(WRITE_RECORD.times(3), LimitUsage { data_size: 120, write_records: 3 }); - assert_eq!(WRITE_RECORD.times(u64::MAX).data_size, u64::MAX); + let max = + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: u64::MAX }; + let record = LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 }; + assert_eq!(max.saturating_add(record), max); + assert_eq!(LimitUsage::ZERO.saturating_sub(record), LimitUsage::ZERO); assert_eq!( - WRITE_RECORD.saturating_add(WRITE_RECORD).saturating_sub(WRITE_RECORD), - WRITE_RECORD + record.times(3), + LimitUsage { data_size: 120, write_records: 3, state_growth: 3 } ); + assert_eq!(record.times(u64::MAX).data_size, u64::MAX); + assert_eq!(record.saturating_add(record).saturating_sub(record), record); } /// `within_limit` follows the variant, and is the exact complement of `exceeded_limit`. @@ -626,12 +750,17 @@ mod tests { assert!(frame_local.exceeded_limit()); } - /// The kinds keep the legacy engine's wire encoding: every discriminant survives the round - /// trip, and the legacy engine's key-value updates, `1`, and state growth, `3`, name no - /// dimension, nor does an unknown kind. + /// The kinds keep the legacy engine's wire encoding: data size `0`, KV updates `1`, compute + /// `2`, state growth `3`; every discriminant survives the round trip, and an unknown kind names + /// no dimension. #[test] fn test_limit_kind_keeps_its_wire_encoding() { - for (kind, expected) in [(LimitKind::DataSize, 0), (LimitKind::ComputeGas, 2)] { + for (kind, expected) in [ + (LimitKind::DataSize, 0), + (LimitKind::KvUpdate, 1), + (LimitKind::ComputeGas, 2), + (LimitKind::StateGrowth, 3), + ] { assert_eq!(kind.as_u8(), expected, "{kind:?}"); assert_eq!( LimitKind::from_u8(kind.as_u8()), @@ -639,8 +768,8 @@ mod tests { "round-trip failed for {kind:?}" ); } - for retired in [1, 3, 4, u8::MAX] { - assert_eq!(LimitKind::from_u8(retired), None, "{retired}"); + for unknown in [4, 5, u8::MAX] { + assert_eq!(LimitKind::from_u8(unknown), None, "{unknown}"); } } @@ -649,16 +778,20 @@ mod tests { /// bytes. #[test] fn test_decode_mega_limit_exceeded_accepts_exactly_the_stops_encoding() { - let kinds = [LimitKind::DataSize, LimitKind::ComputeGas]; + let kinds = [ + LimitKind::DataSize, + LimitKind::KvUpdate, + LimitKind::ComputeGas, + LimitKind::StateGrowth, + ]; for kind in kinds { let stop = LimitCheck::ExceedsLimit { kind, limit: 7, used: 8, frame_local: false }; assert_eq!(decode_mega_limit_exceeded(&stop.revert_data()), Some((kind, 7))); } let encoded = |kind: u8| MegaLimitExceeded { kind, limit: 7 }.abi_encode(); - assert_eq!(decode_mega_limit_exceeded(&encoded(1)), None, "a kind no dimension has"); - assert_eq!(decode_mega_limit_exceeded(&encoded(3)), None, "a kind no dimension has"); assert_eq!(decode_mega_limit_exceeded(&encoded(4)), None, "a kind no dimension has"); + assert_eq!(decode_mega_limit_exceeded(&encoded(5)), None, "a kind no dimension has"); assert_eq!(decode_mega_limit_exceeded(&encoded(u8::MAX)), None); let mut wide = encoded(0); wide[4 + 30] = 1; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index fe980e280..fd43e9c3a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -1,239 +1,977 @@ -//! The facts the Host observes for the opcode that is running. +//! What a write counts: the write records it makes and takes back, by the net change of what it +//! writes, and its other bytes. +//! +//! An account's write record exists while the account's info — its nonce, balance or code — +//! differs from what the transaction loaded, revm's original info, which revm sets at the +//! account's first load in the transaction; a storage slot's while its value differs from its +//! original value. A write that changes an unchanged account or slot makes the record, a write that +//! returns one to its original takes it back, and a write to one already changed adds nothing. +//! +//! The facts are read off revm's journal as it stands where a hook runs: before a frame's start, +//! which is where its records are predicted, and after a completed write, where a `SELFDESTRUCT`'s +//! accounts are rebuilt as they were before it from the balance it moved. A creator's nonce record +//! is read off what revm did: the creator as it stood before revm decided the creation, and as it +//! stands once the creation returned. +//! +//! State growth is counted at the same sites, one unit per new account or new slot, where EIP-8037 +//! charges the state gas of one: a slot an `SSTORE` makes non-zero from an original of zero, and +//! takes back by writing it to zero again; an account that is empty under EIP-161 and that a value +//! transfer, a creation, a `SELFDESTRUCT`'s balance or a creator's nonce bump makes. +//! +//! The first effective `SELFDESTRUCT` of an account created in the transaction takes back every +//! part of it the transaction made ([`DestroyedParts`]): its leaf when it was absent at the +//! transaction's start, with the account's record and its unit of state growth; the code deposited +//! at it, with its bytes; and each slot it made non-zero from an original of zero, with its record +//! and its unit. From that mark until the transaction ends the account counts nothing more: its +//! nonce is no longer what the transaction loaded, so no write to the account makes or takes back +//! its record, a value moved to it adds no account, and an `SSTORE` of one of its slots counts +//! nothing ([`Accounts::is_destroyed`]). Every fact is the journal's: revm's flags of an account +//! created and of one destroyed in the transaction, which a failed frame's revert takes back with +//! the rest of it, the account's original info and each slot's original value. -use alloy_primitives::Address; -use revm::interpreter::SStoreResult; +#[cfg(not(feature = "std"))] +use alloc as std; +use std::vec::Vec; -use super::{log_history_bytes, LimitUsage, WRITE_RECORD}; +use revm::{ + context_interface::{ + host::{CompletedWrite, FrameStartKind}, + journaled_state::entry::{JournalEntry, SelfdestructionRevertStatus}, + }, + primitives::{Address, StorageKey, KECCAK_EMPTY, U256}, + state::{Account, AccountInfo, EvmState, TransactionId}, + Journal, +}; -/// What the Host saw an opcode do, staged until the opcode completes. -/// -/// The Host only observes: it stages the facts revm hands it and records nothing. The opcode's -/// wrapper commits the staged record once the opcode completed, or discards it when the opcode -/// failed after the Host call (an out-of-gas on the gas charged after the write, say), because the -/// failure takes the write back with it. +use super::{log_history_bytes, Counted, TRANSFER_LOG_SIZE}; + +/// How a write moves the record count: the records it creates, for accounts it changes from what +/// the transaction loaded, and the records it takes back, for accounts it returns to that. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct RecordDelta { + /// Records created. + pub(crate) added: u64, + /// Records taken back. + pub(crate) taken: u64, +} + +impl RecordDelta { + /// No record moved. + pub(crate) const NONE: Self = Self { added: 0, taken: 0 }; + + /// The delta of one account whose info was changed from what the transaction loaded `before` + /// a write and is changed `after` it: a record when the write changed it, a record taken back + /// when the write returned it, and nothing otherwise. + pub(crate) const fn of_account(before: bool, after: bool) -> Self { + match (before, after) { + (false, true) => Self { added: 1, taken: 0 }, + (true, false) => Self { added: 0, taken: 1 }, + _ => Self::NONE, + } + } + + /// This delta and `other` together. + pub(crate) const fn with(self, other: Self) -> Self { + Self { added: self.added + other.added, taken: self.taken + other.taken } + } +} + +/// The write records a frame's start makes: a call's value transfer's, and a creation's created +/// account and creator nonce; and whether it journals a transfer log. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct StartRecords { + /// The records a call's value transfer makes and takes back: the accounts it changes from what + /// the transaction loaded, and those it returns to that. + pub(crate) transfer: RecordDelta, + /// Whether a creation records the account it creates: one the transaction had not changed. + /// A creation sets the account's nonce to one, so it never returns the account. + pub(crate) created: bool, + /// Whether a creation records its creator's nonce: the bump changes an account the transaction + /// had not changed. The record is the creator's, which the creation's failure leaves with it, + /// and is counted on the creator once the creation returned ([`CreatorBefore`]). + pub(crate) creator: bool, + /// Whether the start journals an EIP-7708 transfer log: value moves to another account. + pub(crate) transfer_log: bool, +} + +impl StartRecords { + /// No record and no log. + pub(crate) const NONE: Self = + Self { transfer: RecordDelta::NONE, created: false, creator: false, transfer_log: false }; + + /// The records the start makes on the started frame, which its failure takes back: a + /// transfer's, and the created account. The creator's is not among them. + pub(crate) const fn on_frame(self) -> RecordDelta { + RecordDelta { added: self.transfer.added + self.created as u64, taken: self.transfer.taken } + } + + /// What the start counts on the started frame: its records there, and its transfer log. + pub(crate) const fn counted(self) -> Counted { + let on_frame = self.on_frame(); + Counted::records(on_frame.added, on_frame.taken, self.transfer_log) + } +} + +/// The parts of an account created in the transaction that its first effective `SELFDESTRUCT` +/// gives back: each part the transaction made, which does not remain for a node to store. A part +/// that existed at the transaction's start is an ordinary deletion and is not among them. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum StagedRecord { - /// An `SSTORE`: the slot's value at the start of the transaction, before the write, and - /// after it. - Sstore(SStoreResult), - /// A `LOG`: its topic count and data length. - Log { - /// Number of topics. - topics: u8, - /// Length of the data, in bytes. - data_len: u64, - }, - /// A `SELFDESTRUCT`. - SelfDestruct { - /// Whether the destructed account had a balance to move. - had_value: bool, - /// Whether the beneficiary is another account than the destructed one. - to_other_account: bool, - /// The beneficiary. - beneficiary: Address, - }, +pub(crate) struct DestroyedParts { + /// Whether the account's leaf was absent at the transaction's start: the leaf's state gas, its + /// unit of state growth and the account's write record come back. + pub(crate) leaf: bool, + /// The bytes of the code deposited at the account, which come back with their state gas, their + /// data size and their history gas. Code is no write record and no unit of state growth. + pub(crate) code: u64, + /// The slots the transaction made non-zero from an original of zero, in key order: each slot's + /// state gas, its unit of state growth and its write record come back. + pub(crate) slots: Vec, + /// The slots that held a non-zero value at the transaction's start, which the transaction + /// loaded and which still hold it: an ordinary deletion, which refills nothing and subtracts + /// nothing, and whose deletion is what makes each slot's write record. + pub(crate) deleted: u64, } -/// How a committed record changes the running frame's usage. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum RecordEffect { - /// Nothing to count. - None, - /// Count this usage. - Record(LimitUsage), - /// Take this usage back. - Refund(LimitUsage), +impl DestroyedParts { + /// The write records the parts take back: the account's, for an absent leaf, and each slot's. + fn records(&self) -> u64 { + u64::from(self.leaf) + self.slots.len() as u64 + } + + /// What the destruction counts of the parts: the records it takes back with their bytes, the + /// code's bytes and one unit of state growth per record taken back, and the records it makes + /// of the deleted slots that held a value at the start. + pub(crate) fn counted(&self) -> Counted { + let records = self.records(); + Counted::records(self.deleted, records, false) + .with_growth(0, records) + .plus_bytes_taken(self.code) + } } -/// The history bytes a committed record appends, or takes back. -/// -/// They are the record's data size and nothing else: what a log or a write record weighs in a -/// block is what the data-size limit meters it at, so the two cannot drift apart. That is the -/// pairing, and it holds per record; a transaction's two totals part where the byte table says -/// they do. +/// The accounts the running transaction holds, as revm's journal holds them, read for the records +/// a write makes. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Accounts<'a> { + state: &'a EvmState, + /// The journal's entries, which revm clears between transactions: this transaction's. + entries: &'a [JournalEntry], + transaction_id: TransactionId, + /// Whether a value movement journals an EIP-7708 transfer log. + transfer_logs: bool, +} + +/// Whether `info` differs from `original` in what a write record stands for: the nonce, the +/// balance or the code. +fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { + info.nonce != original.nonce || + info.balance != original.balance || + info.code_hash != original.code_hash +} + +/// A creation's creator as the transaction held it before revm decided the creation's start: what +/// tells, once the creation returned, whether revm bumped the creator's nonce and what the bump +/// made of the creator ([`Accounts::creator_counted`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum HistoryBytes { - /// Nothing to charge. - None, - /// Bytes the record appends. - Appended(u64), - /// Bytes a record that was taken back no longer appends. - Taken(u64), +pub(crate) struct CreatorBefore { + /// The creator. + address: Address, + /// Its nonce. + nonce: u64, + /// Whether the transaction had changed its account from what it loaded. + changed: bool, + /// Whether its account was empty under EIP-161. + empty: bool, } -impl RecordEffect { - /// The history bytes this effect appends or takes back. - pub(crate) const fn history_bytes(self) -> HistoryBytes { - match self { - Self::None => HistoryBytes::None, - Self::Record(usage) => HistoryBytes::Appended(usage.data_size), - Self::Refund(usage) => HistoryBytes::Taken(usage.data_size), +impl<'a> Accounts<'a> { + /// The accounts `journal` holds, in a transaction whose value movements journal transfer logs + /// or not (`transfer_logs`). + pub(crate) fn of(journal: &'a Journal, transfer_logs: bool) -> Self { + Self { + state: &journal.state, + entries: &journal.journal, + transaction_id: journal.transaction_id, + transfer_logs, } } -} -impl StagedRecord { - /// What committing the record counts, per site: + /// The account at `address` as the transaction loaded it and holds it now: `None` for one + /// the transaction has not loaded, which it has not changed either. + fn loaded(&self, address: Address) -> Option<&'a Account> { + self.state.get(&address).filter(|account| account.transaction_id == self.transaction_id) + } + + /// Whether the transaction has loaded the account at `address`. An account an earlier + /// transaction on the same journal left in it is not loaded until this one loads it again. + pub(crate) fn is_loaded(&self, address: Address) -> bool { + self.loaded(address).is_some() + } + + /// Whether the transaction changed the account at `address` from what it loaded: its nonce, + /// balance or code differs from the account's original info. An account the transaction has + /// not loaded is unchanged. + pub(crate) fn is_changed(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| differs(&account.info, &account.original_info())) + } + + /// Whether the account at `address` would be changed from what the transaction loaded were + /// its balance `balance`, the rest of its info as it is. + fn changed_with_balance(&self, address: Address, balance: U256) -> bool { + match self.loaded(address) { + Some(account) => { + differs(&AccountInfo { balance, ..account.info.clone() }, &account.original_info()) + } + // What the transaction loads for an account it has not loaded is what the chain holds, + // so a balance it does not hold changes it. + None => balance != U256::ZERO, + } + } + + /// Whether the account at `address` was created in the transaction and has been destroyed + /// since: the mark the first effective `SELFDESTRUCT` of such an account leaves, which + /// stands until the transaction ends unless the destroying frame, or a frame that contains + /// it, fails. + pub(crate) fn is_destroyed(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| { + account.is_created_locally() && account.is_selfdestructed_locally() + }) + } + + /// The parts of the account at `address` its `SELFDESTRUCT` that just completed gives back, + /// read off the journal after the write: `None` unless the account was created in the + /// transaction and the destruction is its first effective one (`previously_destroyed` names + /// one the mark already stood for). + /// + /// The leaf was absent at the transaction's start when the transaction found no account + /// there ([`Self::was_absent_at_start`]), which a value transfer, a `SELFDESTRUCT`'s balance, + /// the transaction's value or the creation itself then charged as a new account; a leaf the + /// transaction found, a balance or an account empty under EIP-161 with storage, stands. The + /// code is what the account holds: non-empty code at the transaction's start collides with the + /// creation, so it is code the transaction deposited. A slot the transaction did not load has + /// no record. A slot of an account created in the transaction that the journal does not hold + /// yet loads as zero, so the slots given back are those it made non-zero; one loaded before the + /// creation, which only a tool's load reaches, keeps the value it held at the start, and the + /// deletion makes its record while it still holds that value. + pub(crate) fn destroyed_parts( + &self, + address: Address, + previously_destroyed: bool, + ) -> Option { + let account = self.loaded(address)?; + if previously_destroyed || !account.is_created_locally() { + return None; + } + let original = account.original_info(); + debug_assert_eq!(original.code_hash, KECCAK_EMPTY, "code at the start collides"); + debug_assert!(self.is_changed(address), "a creation changes its account's nonce"); + let leaf = self.was_absent_at_start(address, account); + let code = if account.info.code_hash == KECCAK_EMPTY { + 0 + } else { + account.info.code.as_ref().map_or(0, |code| code.len() as u64) + }; + let loaded = + account.storage.iter().filter(|(_, slot)| slot.transaction_id == self.transaction_id); + let mut slots = Vec::new(); + let mut deleted = 0; + for (key, slot) in loaded { + if slot.original_value.is_zero() { + if !slot.present_value.is_zero() { + slots.push(*key); + } + } else if !slot.is_changed() { + deleted += 1; + } + } + slots.sort_unstable(); + Some(DestroyedParts { leaf, code, slots, deleted }) + } + + /// Whether the transaction found no account at `address`, which it loaded as `account`, when + /// it started: its info then was empty, and no account stood there — the database answered + /// none, or an earlier transaction on the same journal destroyed the account, which its first + /// load in this transaction cleared. An account the database answered with, empty under EIP-161 + /// with storage, stood there. + /// + /// Read at the completed write of the account's `SELFDESTRUCT`. revm's flag of an account the + /// database answered none for was set at its first load on the journal and outlives the + /// transactions after it, so an earlier destruction is read off revm's entry for the one that + /// just completed: [`SelfdestructionRevertStatus::LocallySelfdestroyed`] names a first + /// destruction in this transaction of an account an earlier one destroyed. revm empties its + /// entries when a transaction ends, so they are this transaction's. + fn was_absent_at_start(&self, address: Address, account: &Account) -> bool { + if !account.original_info().is_empty() { + return false; + } + account.is_loaded_as_not_existing() || + self.entries.iter().rev().find_map(|entry| match entry { + JournalEntry::AccountDestroyed { address: destroyed, destroyed_status, .. } + if *destroyed == address => + { + Some(*destroyed_status == SelfdestructionRevertStatus::LocallySelfdestroyed) + } + _ => None, + }) == Some(true) + } + + /// Whether the account at `address` is empty under EIP-161 — no nonce, no balance, no code — + /// as the transaction holds it: a value moved to it, or a creation at it, makes a new account. + /// An account the transaction has not loaded is not known to be empty. + pub(crate) fn is_empty(&self, address: Address) -> bool { + self.loaded(address).is_some_and(|account| account.info.is_empty()) + } + + /// The current balance of the account at `address`; nothing for one the transaction has not + /// loaded. + fn balance(&self, address: Address) -> U256 { + self.loaded(address).map_or(U256::ZERO, |account| account.info.balance) + } + + /// The records a transfer of `value` from `from` to `to` makes and takes back, as the journal's + /// state stands, and whether it journals a transfer log: nothing for a transfer to the same + /// account or of nothing, which revm moves nothing for, and nothing for a value `from` cannot + /// fund, which revm refuses. + pub(crate) fn transfer_records(&self, from: Address, to: Address, value: U256) -> StartRecords { + if from == to || value.is_zero() { + return StartRecords::NONE; + } + let Some(from_after) = self.balance(from).checked_sub(value) else { + return StartRecords::NONE; + }; + let to_after = self.balance(to).saturating_add(value); + let transfer = RecordDelta::of_account( + self.is_changed(from), + self.changed_with_balance(from, from_after), + ) + .with(RecordDelta::of_account( + self.is_changed(to), + self.changed_with_balance(to, to_after), + )); + StartRecords { transfer, transfer_log: self.transfer_logs, ..StartRecords::NONE } + } + + /// The records a creation by `creator` at `created` with an endowment of `value` makes, before + /// revm bumps the creator's nonce: the creator's nonce, when the bump changes an account the + /// transaction had not changed; the account it creates, when the transaction had not changed + /// it; and a transfer log for an endowment. Nothing for an endowment `creator` cannot fund, + /// which revm refuses before it bumps the nonce, nor for a creation that takes no address. + pub(crate) fn creation_records( + &self, + creator: Address, + created: Option
, + value: U256, + ) -> StartRecords { + let Some(created) = created else { return StartRecords::NONE }; + if self.balance(creator) < value { + return StartRecords::NONE; + } + StartRecords { + transfer: RecordDelta::NONE, + created: !self.is_changed(created), + creator: !self.is_changed(creator), + transfer_log: self.transfer_logs && !value.is_zero(), + } + } + + /// The creator at `address` of a creation revm is about to decide, as the transaction holds it. + /// The creator is read loaded: revm loads it first thing when it decides the creation. + pub(crate) fn creator_before(&self, address: Address) -> CreatorBefore { + CreatorBefore { + address, + nonce: self.loaded(address).map_or(0, |account| account.info.nonce), + changed: self.is_changed(address), + empty: self.is_empty(address), + } + } + + /// Whether revm bumped the nonce of the creator `before` was read of: it does for every + /// creation it decides but one it refuses on the creator's account — an endowment the creator + /// cannot fund, a nonce at its maximum — and the bump stands whatever the creation then does. + pub(crate) fn bumped(&self, before: &CreatorBefore) -> bool { + self.loaded(before.address).is_some_and(|account| account.info.nonce != before.nonce) + } + + /// What the nonce bump of the creator `before` was read of made, read off the journal once its + /// creation returned: the creator's write record when the bump changed an account the + /// transaction had not changed, and one account of state growth when the bump made an empty + /// account. The record follows the account's net change, so a keyless deployment's settlement, + /// which may set the signer's nonce back, is read once it did. + pub(crate) fn creator_counted(&self, before: &CreatorBefore) -> Counted { + let record = RecordDelta::of_account(before.changed, self.is_changed(before.address)); + let grows = before.empty && self.loaded(before.address).is_some_and(|a| !a.info.is_empty()); + Counted::records(record.added, record.taken, false).with_growth(u64::from(grows), 0) + } + + /// The account of state growth a transfer of `value` from `from` to `to` makes, as the + /// journal's state stands: one when it moves value `from` can fund to another account that is + /// empty, which the transfer creates. A `CALLCODE`'s transfer is from the calling account to + /// itself, and a `DELEGATECALL` or `STATICCALL` carries none: none of them creates an account. + pub(crate) fn transfer_growth(&self, from: Address, to: Address, value: U256) -> u64 { + let creates = + from != to && !value.is_zero() && self.balance(from) >= value && self.is_empty(to); + u64::from(creates) + } + + /// The account of state growth a creation by `creator` at `created` with an endowment of + /// `value` makes on its frame, as the journal's state stands: one when the creator can fund + /// the endowment and the address is empty, which the creation creates. An address that holds + /// a balance, a nonce or code is no new account, and a collision adds none. + pub(crate) fn creation_growth(&self, creator: Address, created: Address, value: U256) -> u64 { + u64::from(self.balance(creator) >= value && self.is_empty(created)) + } + + /// The records a frame start of `kind` by `caller` makes: a call's value transfer to `target` + /// ([`transfer_records`](Self::transfer_records)); a creation's at `target`, the address it + /// takes ([`creation_records`](Self::creation_records)). The transfer of a `CALLCODE` is from + /// the calling account to itself, and a `DELEGATECALL` or `STATICCALL` carries none: neither + /// makes a record. + pub(crate) fn start_records( + &self, + kind: FrameStartKind, + caller: Address, + target: Option
, + value: U256, + ) -> StartRecords { + match kind { + FrameStartKind::Create | FrameStartKind::Create2 => { + self.creation_records(caller, target, value) + } + FrameStartKind::Call | + FrameStartKind::CallCode | + FrameStartKind::DelegateCall | + FrameStartKind::StaticCall => target + .map_or(StartRecords::NONE, |target| self.transfer_records(caller, target, value)), + } + } + + /// The records a `SELFDESTRUCT` of `address` to `target` that moved `balance` made and took + /// back, read off the journal after the write: a destruction changes balances alone, so the + /// destructed account held `balance` before it, and a beneficiary that is another account its + /// balance less `balance`, all of which it got. + fn destruction_records(&self, address: Address, target: Address, balance: U256) -> RecordDelta { + let source = RecordDelta::of_account( + self.changed_with_balance(address, balance), + self.is_changed(address), + ); + if target == address { + return source; + } + let before = self.balance(target).saturating_sub(balance); + source.with(RecordDelta::of_account( + self.changed_with_balance(target, before), + self.is_changed(target), + )) + } + + /// What the completed write `write` counts, the history bytes it appends and takes back, and, + /// for the first effective `SELFDESTRUCT` of an account created in the transaction, the parts + /// of the account that come back: /// /// - `SSTORE`: the first change of a slot in the transaction is one write record; writing the - /// slot back to its original value takes the record back. - /// - `LOG`: its bytes, one base record for the address, one per topic and the data. - /// - `SELFDESTRUCT`: one write record for the beneficiary, when value moves to another account - /// than the destructed one and the transaction's `sender`, whose account the transaction body - /// counts. - pub(crate) fn effect(&self, sender: Address) -> RecordEffect { - match self { - Self::Sstore(slot) => { - if slot.is_original_eq_present() { + /// slot back to its original value takes the record back; a slot whose original value is zero + /// is one of state growth while it holds another, made by the write from zero and taken back + /// by the write to zero. A slot of an account created in the transaction and destroyed since + /// counts nothing ([`is_destroyed`](Self::is_destroyed)): the destruction took back what its + /// slots counted; + /// - `LOG`: its bytes, one base record for the address, one per topic and the data, which are + /// history beside the records; + /// - `SELFDESTRUCT`: the records of the accounts the move changed and returned — the + /// beneficiary, and the destructed account whose balance the move clears — and, when it moved + /// value to another account, the EIP-7708 transfer log revm journaled for the move, which is + /// data size and no history, and one of state growth when that account did not exist; and + /// what the parts it destroys take back ([`destroyed_parts`](Self::destroyed_parts)), whose + /// records are history taken back beside the move's. The code's history is the schedule's + /// charge for the deposit, which the caller gives back from the parts. + pub(crate) fn write_counted( + &self, + write: &CompletedWrite<'_>, + ) -> (Counted, HistoryBytes, Option) { + let mut destroyed = None; + let counted = match *write { + CompletedWrite::Sstore { address, .. } if self.is_destroyed(address) => Counted::NONE, + CompletedWrite::Sstore { result: slot, .. } => { + let records = if slot.is_original_eq_present() { if slot.is_original_eq_new() { - RecordEffect::None + Counted::NONE } else { - RecordEffect::Record(WRITE_RECORD) + Counted::records(1, 0, false) } } else if slot.is_original_eq_new() { - RecordEffect::Refund(WRITE_RECORD) + Counted::records(0, 1, false) } else { - RecordEffect::None - } + Counted::NONE + }; + let fresh = slot.original_value.is_zero(); + let rise = fresh && slot.present_value.is_zero() && !slot.new_value.is_zero(); + let fall = fresh && !slot.present_value.is_zero() && slot.new_value.is_zero(); + records.with_growth(u64::from(rise), u64::from(fall)) } - Self::Log { topics, data_len } => RecordEffect::Record(LimitUsage { - data_size: log_history_bytes(u64::from(*topics), *data_len), - write_records: 0, - }), - Self::SelfDestruct { had_value, to_other_account, beneficiary, .. } => { - if *had_value && *to_other_account && *beneficiary != sender { - RecordEffect::Record(WRITE_RECORD) - } else { - RecordEffect::None - } + CompletedWrite::Log { topics, data_len, .. } => { + Counted::bytes(log_history_bytes(u64::from(topics), data_len)) } - } + CompletedWrite::SelfDestruct { address, target, balance, result } => { + let records = self.destruction_records(address, target, balance); + let moved = result.had_value && target != address; + let logged = self.transfer_logs && moved; + let creates = moved && !result.target_exists; + let counted = Counted::records(records.added, records.taken, logged) + .with_growth(u64::from(creates), 0); + destroyed = self.destroyed_parts(address, result.previously_destroyed); + destroyed.as_ref().map_or(counted, |parts| counted.plus(parts.counted())) + } + }; + let log = if counted.transfer_log { TRANSFER_LOG_SIZE } else { 0 }; + let code = destroyed.as_ref().map_or(0, |parts| parts.code); + let history = HistoryBytes { + appended: counted.bytes_added() - log, + taken: counted.bytes_taken() - code, + }; + (counted, history, destroyed) } +} - /// Whether the opcode moved value to another account: a `SELFDESTRUCT` of an account that had - /// a balance, to a beneficiary other than itself. revm journals an EIP-7708 transfer log for - /// exactly that move, whoever the beneficiary is — the sender included — and none for a - /// destruction to itself, which burns the balance on Satin's base spec. - pub(crate) const fn moves_value(&self) -> bool { - matches!(self, Self::SelfDestruct { had_value: true, to_other_account: true, .. }) - } +/// The history bytes a completed write appends and takes back. +/// +/// They are the record's data size and nothing else: what a log or a write record weighs in a +/// block is what the data-size limit meters it at, so the two cannot drift apart. That is the +/// pairing, and it holds per record; a transaction's two totals part where the byte table says +/// they do. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct HistoryBytes { + /// Bytes the write appends: the records it creates and, for a log, its own bytes. + pub(crate) appended: u64, + /// Bytes the records the write took back no longer append. Deployed code a destruction takes + /// back is not among them: its history is the schedule's charge for the deposit. + pub(crate) taken: u64, } #[cfg(test)] mod tests { use super::*; - use crate::{LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE}; - use alloy_primitives::{address, U256}; + use crate::{ + limit::{KV_UPDATE_POOL, STATE_GROWTH_POOL}, + test_utils::MemoryDatabase, + LOG_BASE_SIZE, LOG_TOPIC_SIZE, WRITE_RECORD_SIZE, + }; + use alloy_primitives::{address, Bytes}; + use revm::{ + bytecode::Bytecode, + context::JournalTr, + context_interface::{ + context::{SStoreResult, SelfDestructResult}, + journaled_state::account::JournaledAccountTr, + }, + }; const SENDER: Address = address!("0000000000000000000000000000000000005e4d"); const OTHER: Address = address!("0000000000000000000000000000000000000077"); + const DESTRUCTED: Address = address!("0000000000000000000000000000000000000d00"); + const MOVED: SelfDestructResult = + SelfDestructResult { had_value: true, target_exists: true, previously_destroyed: false }; - fn sstore(original: u64, present: u64, new: u64) -> StagedRecord { - StagedRecord::Sstore(SStoreResult { + fn slot(original: u64, present: u64, new: u64) -> SStoreResult { + SStoreResult { original_value: U256::from(original), present_value: U256::from(present), new_value: U256::from(new), - }) + } + } + + /// A journal holding three accounts as the transaction loaded them. + fn journal() -> Journal { + let db = MemoryDatabase::default() + .account_balance(SENDER, U256::from(10)) + .account_balance(OTHER, U256::from(4)) + .account_balance(DESTRUCTED, U256::from(5)); + let mut journal = Journal::new(db); + for address in [SENDER, OTHER, DESTRUCTED] { + journal.load_account(address).unwrap(); + } + journal + } + + /// The `SELFDESTRUCT` of `DESTRUCTED` to `target` that moved `balance`. + const fn destruction(target: Address, balance: u64) -> CompletedWrite<'static> { + CompletedWrite::SelfDestruct { + address: DESTRUCTED, + target, + balance: U256::from_limbs([balance, 0, 0, 0]), + result: &MOVED, + } + } + + /// What an `SSTORE` of `new` over a slot holding `present`, `original` at the transaction's + /// start, counts. + fn sstore_counted(original: u64, present: u64, new: u64) -> Counted { + let journal = journal(); + let slot = slot(original, present, new); + let write = CompletedWrite::Sstore { address: OTHER, key: U256::ZERO, result: &slot }; + Accounts::of(&journal, false).write_counted(&write).0 } /// A slot counts once, on its first change in the transaction; writing it back to its /// original value takes the record back; every other write counts nothing. #[test] fn test_sstore_record_rules() { - assert_eq!(sstore(0, 0, 1).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(5, 5, 0).effect(SENDER), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 0).effect(SENDER), RecordEffect::Refund(WRITE_RECORD)); - assert_eq!(sstore(0, 1, 2).effect(SENDER), RecordEffect::None); - assert_eq!(sstore(3, 3, 3).effect(SENDER), RecordEffect::None); - assert_eq!(sstore(3, 4, 4).effect(SENDER), RecordEffect::None); + let records = |original, present, new| { + let counted = sstore_counted(original, present, new); + (counted.added.get(KV_UPDATE_POOL), counted.taken.get(KV_UPDATE_POOL)) + }; + assert_eq!(records(0, 0, 1), (1, 0)); + assert_eq!(records(5, 5, 0), (1, 0)); + assert_eq!(records(0, 1, 0), (0, 1)); + assert_eq!(records(0, 1, 2), (0, 0)); + assert_eq!(records(3, 3, 3), (0, 0)); + assert_eq!(records(3, 4, 4), (0, 0)); + assert_eq!(sstore_counted(0, 0, 1), Counted::records(1, 0, false).with_growth(1, 0)); + } + + /// An `SSTORE` changes state growth by the slot's original, present and new values, on the + /// spec's eight rows: a rise for original zero, present zero, new non-zero; a fall for original + /// zero, present non-zero, new zero; nothing on the six others, a slot whose original value is + /// not zero never changing it. + #[test] + fn test_an_sstore_grows_state_only_on_a_slot_whose_original_is_zero() { + let growth = |original, present, new| { + let counted = sstore_counted(original, present, new); + (counted.added.get(STATE_GROWTH_POOL), counted.taken.get(STATE_GROWTH_POOL)) + }; + let rows = [ + ((0, 0, 0), (0, 0)), + ((0, 0, 1), (1, 0)), + ((0, 1, 0), (0, 1)), + ((0, 1, 2), (0, 0)), + ((5, 0, 0), (0, 0)), + ((5, 0, 6), (0, 0)), + ((5, 5, 0), (0, 0)), + ((5, 5, 6), (0, 0)), + ]; + for ((original, present, new), expected) in rows { + assert_eq!(growth(original, present, new), expected, "{original}, {present}, {new}"); + } } - /// A log is 32 bytes for its address, 32 per topic and its data. + /// A log is 32 bytes for its address, 32 per topic and its data, all of them history; a + /// transfer log counts what a `LOG3` carrying one word counts. #[test] fn test_log_bytes() { - let log = |topics, data_len| StagedRecord::Log { topics, data_len }.effect(SENDER); - assert_eq!(log(0, 0), RecordEffect::Record(LimitUsage { data_size: 32, write_records: 0 })); - assert_eq!( - log(4, 100), - RecordEffect::Record(LimitUsage { data_size: 32 + 4 * 32 + 100, write_records: 0 }) - ); - assert_eq!( - log(1, u64::MAX), - RecordEffect::Record(LimitUsage { data_size: u64::MAX, write_records: 0 }) - ); + let journal = journal(); + let accounts = Accounts::of(&journal, false); + let counted = |topics, data_len| { + let (counted, history, _) = + accounts.write_counted(&CompletedWrite::Log { address: OTHER, topics, data_len }); + (counted, history) + }; + assert_eq!(counted(0, 0), (Counted::bytes(32), HistoryBytes { appended: 32, taken: 0 })); + assert_eq!(counted(4, 100).0, Counted::bytes(32 + 4 * 32 + 100)); + assert_eq!(counted(1, u64::MAX).0, Counted::bytes(u64::MAX)); + assert_eq!(counted(3, 32).0.bytes_added(), TRANSFER_LOG_SIZE); + assert_eq!(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32, TRANSFER_LOG_SIZE); } - /// A record's history bytes are its data size, at every site: a log's own bytes, a write - /// record's forty, and nothing for a write that leaves no record. + /// A `SELFDESTRUCT`'s records are rebuilt from the journal after the write and the balance it + /// moved, which tells the cases the after state alone cannot: a destructed account and a + /// beneficiary the transaction had not changed are two records; a beneficiary drained earlier, + /// which the move puts back as loaded, takes its record back; a destructed account funded or + /// drained earlier, changed before the move and after it, adds none of its own; and a + /// destruction to itself moves nothing. The move's transfer log is data size and no history. #[test] - fn test_history_bytes_are_the_records_data_size() { + fn test_a_destruction_counts_what_its_move_changed() { + let records_bytes = |records| WRITE_RECORD_SIZE * records; + + let mut fresh = journal(); + fresh.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let (counted, history, _) = + Accounts::of(&fresh, true).write_counted(&destruction(OTHER, 5)); + assert_eq!(counted, Counted::records(2, 0, true)); + assert_eq!(history, HistoryBytes { appended: records_bytes(2), taken: 0 }); assert_eq!( - sstore(0, 0, 1).effect(SENDER).history_bytes(), - HistoryBytes::Appended(WRITE_RECORD_SIZE) + Accounts::of(&fresh, false).write_counted(&destruction(OTHER, 5)).0, + Counted::records(2, 0, false), + "no transfer logs, no log" ); + + // The destructed account sent one away and the beneficiary all it had: the move of the + // four left puts the beneficiary back as loaded, and leaves the destructed account changed. + let mut drained = journal(); + drained.transfer(DESTRUCTED, SENDER, U256::from(1)).unwrap(); + drained.transfer(OTHER, SENDER, U256::from(4)).unwrap(); + drained.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let (counted, history, _) = + Accounts::of(&drained, false).write_counted(&destruction(OTHER, 4)); + assert_eq!(counted, Counted::records(0, 1, false)); + assert_eq!(history, HistoryBytes { appended: 0, taken: records_bytes(1) }); + + let mut funded = journal(); + funded.transfer(SENDER, DESTRUCTED, U256::from(2)).unwrap(); + funded.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); assert_eq!( - sstore(0, 1, 0).effect(SENDER).history_bytes(), - HistoryBytes::Taken(WRITE_RECORD_SIZE) + Accounts::of(&funded, false).write_counted(&destruction(OTHER, 7)).0, + Counted::records(1, 0, false), + "the beneficiary's record alone" ); - assert_eq!(sstore(3, 3, 3).effect(SENDER).history_bytes(), HistoryBytes::None); + + // A pre-existing account destructing to itself keeps its balance: nothing changes. + let to_itself = journal(); assert_eq!( - StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER).history_bytes(), - HistoryBytes::Appended(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + 32) + Accounts::of(&to_itself, true).write_counted(&destruction(DESTRUCTED, 5)).0, + Counted::NONE ); - let to_other = StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: OTHER, + } + + /// A `SELFDESTRUCT` that moves a non-zero balance to another account that does not exist + /// creates it: one of state growth with its records. A beneficiary that exists, a destruction + /// that moves nothing and one to itself create nothing. + #[test] + fn test_a_destruction_grows_state_by_the_beneficiary_it_creates() { + let growth = |target, balance: u64, target_exists| { + let result = SelfDestructResult { + had_value: balance != 0, + target_exists, + previously_destroyed: false, + }; + let write = CompletedWrite::SelfDestruct { + address: DESTRUCTED, + target, + balance: U256::from(balance), + result: &result, + }; + let journal = journal(); + let counted = Accounts::of(&journal, true).write_counted(&write).0; + (counted.added.get(STATE_GROWTH_POOL), counted.taken.get(STATE_GROWTH_POOL)) }; - assert_eq!( - to_other.effect(SENDER).history_bytes(), - HistoryBytes::Appended(WRITE_RECORD_SIZE) - ); + let fresh = address!("00000000000000000000000000000000000000f5"); + assert_eq!(growth(fresh, 5, false), (1, 0), "a new beneficiary"); + assert_eq!(growth(OTHER, 5, true), (0, 0), "a beneficiary that exists"); + assert_eq!(growth(fresh, 0, false), (0, 0), "no balance moved"); + assert_eq!(growth(DESTRUCTED, 5, false), (0, 0), "to itself"); } - /// Only value that moves to another account is a beneficiary write. + /// What `journal` looks like once `SENDER` created an account at `created` with an endowment + /// of `endowment`, the account wrote `slots` (key, value) in order and deposited `code`. + fn created( + db: MemoryDatabase, + created: Address, + endowment: u64, + slots: &[(u64, u64)], + code: &[u8], + ) -> Journal { + let mut journal = Journal::new(db.account_balance(SENDER, U256::from(10))); + journal.load_account(SENDER).unwrap(); + journal.load_account(created).unwrap(); + let spec = journal.cfg.spec; + journal.create_account_checkpoint(SENDER, created, U256::from(endowment), spec).unwrap(); + for &(key, value) in slots { + journal.sstore(created, U256::from(key), U256::from(value)).unwrap(); + } + if !code.is_empty() { + journal.set_code(created, Bytecode::new_legacy(Bytes::copy_from_slice(code))); + } + journal + } + + /// The first effective destruction of an account created in the transaction gives back the + /// parts the transaction made: the leaf when the database held no account there, the code it + /// deposited and each slot it made non-zero, in key order, a slot written back to zero not + /// among them. A leaf the database held — with a balance, or empty under EIP-161 with storage + /// — stands. A repeated destruction and one of an account the transaction did not create give + /// back nothing; from the mark an `SSTORE` of the account's slots counts nothing. #[test] - fn test_selfdestruct_record_rules() { - let sd = |had_value, to_other_account| { - let beneficiary = OTHER; - StagedRecord::SelfDestruct { had_value, to_other_account, beneficiary }.effect(SENDER) + fn test_a_destruction_gives_back_the_parts_the_transaction_made() { + let fresh = address!("00000000000000000000000000000000000c4ea7"); + let slots = [(3, 1), (1, 7), (2, 1), (2, 0)]; + let mut made = created(MemoryDatabase::default(), fresh, 0, &slots, &[0x60, 0x00, 0xff]); + assert!(!Accounts::of(&made, true).is_destroyed(fresh)); + made.selfdestruct(fresh, OTHER, false).unwrap(); + let accounts = Accounts::of(&made, true); + let parts = DestroyedParts { + leaf: true, + code: 3, + slots: vec![U256::from(1), U256::from(3)], + deleted: 0, + }; + assert_eq!(accounts.destroyed_parts(fresh, false), Some(parts.clone())); + assert_eq!(parts.records(), 3); + assert_eq!( + parts.counted(), + Counted::records(0, 3, false).with_growth(0, 3).plus_bytes_taken(3), + "three records with their bytes, three units of growth, the code's three bytes" + ); + assert!(accounts.is_destroyed(fresh)); + assert_eq!(accounts.destroyed_parts(fresh, true), None, "a repeated destruction"); + + // The write's own count carries the parts; the code's bytes are no record's history. + let result = SelfDestructResult { + had_value: false, + target_exists: true, + previously_destroyed: false, }; - assert_eq!(sd(true, true), RecordEffect::Record(WRITE_RECORD)); - assert_eq!(sd(true, false), RecordEffect::None); - assert_eq!(sd(false, true), RecordEffect::None); - assert_eq!(sd(false, false), RecordEffect::None); - let to_sender = StagedRecord::SelfDestruct { - had_value: true, - to_other_account: true, - beneficiary: SENDER, + let write = CompletedWrite::SelfDestruct { + address: fresh, + target: OTHER, + balance: U256::ZERO, + result: &result, }; - assert_eq!(to_sender.effect(SENDER), RecordEffect::None, "the body counts the sender"); + let (counted, history, destroyed) = accounts.write_counted(&write); + assert_eq!(destroyed, Some(parts.clone())); + assert_eq!(counted, parts.counted()); + assert_eq!(history, HistoryBytes { appended: 0, taken: 3 * WRITE_RECORD_SIZE }); + + // After the mark a slot's write counts nothing, whichever transition it makes. + for (original, present, new) in [(0, 0, 1), (0, 1, 0), (0, 7, 8)] { + let slot = slot(original, present, new); + let write = + CompletedWrite::Sstore { address: fresh, key: U256::from(1), result: &slot }; + assert_eq!( + accounts.write_counted(&write).0, + Counted::NONE, + "{original}, {present}, {new}" + ); + } + + // A leaf the database held stands; the code and the slots still come back. + let funded = MemoryDatabase::default().account_balance(fresh, U256::from(2)); + let storage = + MemoryDatabase::default().account_storage(fresh, U256::from(9), U256::from(5)); + for (db, what) in [(funded, "a balance"), (storage, "an empty account with storage")] { + let mut made = created(db, fresh, 0, &[(1, 1)], &[]); + made.selfdestruct(fresh, OTHER, false).unwrap(); + assert_eq!( + Accounts::of(&made, true).destroyed_parts(fresh, false), + Some(DestroyedParts { + leaf: false, + code: 0, + slots: vec![U256::from(1)], + deleted: 0 + }), + "{what}" + ); + } + + // Slots that held a value at the start, loaded before the creation as only a tool loads + // them: the deletion makes the record of the one that still holds it, and the one the + // transaction wrote since keeps the record its write made. Neither refills or falls. + let held = MemoryDatabase::default() + .account_storage(fresh, U256::from(8), U256::from(4)) + .account_storage(fresh, U256::from(9), U256::from(5)); + let mut loaded = Journal::new(held.account_balance(SENDER, U256::from(10))); + loaded.load_account(SENDER).unwrap(); + loaded.load_account(fresh).unwrap(); + for key in [8, 9] { + loaded.sload(fresh, U256::from(key)).unwrap(); + } + let spec = loaded.cfg.spec; + loaded.create_account_checkpoint(SENDER, fresh, U256::ZERO, spec).unwrap(); + loaded.sstore(fresh, U256::from(8), U256::from(6)).unwrap(); + loaded.selfdestruct(fresh, OTHER, false).unwrap(); + let parts = Accounts::of(&loaded, true).destroyed_parts(fresh, false).unwrap(); + assert_eq!(parts, DestroyedParts { leaf: false, code: 0, slots: vec![], deleted: 1 }); + assert_eq!(parts.counted(), Counted::records(1, 0, false)); + + // An account the transaction did not create is an ordinary deletion. + let mut older = journal(); + older.selfdestruct(DESTRUCTED, OTHER, false).unwrap(); + let accounts = Accounts::of(&older, true); + assert_eq!(accounts.destroyed_parts(DESTRUCTED, false), None); + assert!(!accounts.is_destroyed(DESTRUCTED)); } - /// Value moves to another account only when a destructed account had a balance and a - /// beneficiary other than itself, the sender included; a write or a log moves none. + /// An account's delta: a record when a write changes it, a record back when a write returns + /// it, and nothing when it stays as it was, changed or not. #[test] - fn test_only_a_destruction_to_another_account_moves_value() { - let sd = |had_value, to_other_account, beneficiary| StagedRecord::SelfDestruct { - had_value, - to_other_account, - beneficiary, - }; - assert!(sd(true, true, OTHER).moves_value()); - assert!(sd(true, true, SENDER).moves_value(), "the body's record is not the log"); - assert!(!sd(true, false, OTHER).moves_value(), "a destruction to itself burns"); - assert!(!sd(false, true, OTHER).moves_value(), "nothing to move"); - assert!(!sstore(0, 0, 1).moves_value()); - assert!(!StagedRecord::Log { topics: 3, data_len: 32 }.moves_value()); + fn test_an_accounts_delta_follows_its_change() { + assert_eq!(RecordDelta::of_account(false, true), RecordDelta { added: 1, taken: 0 }); + assert_eq!(RecordDelta::of_account(true, false), RecordDelta { added: 0, taken: 1 }); + assert_eq!(RecordDelta::of_account(true, true), RecordDelta::NONE); + assert_eq!(RecordDelta::of_account(false, false), RecordDelta::NONE); + assert_eq!( + RecordDelta::of_account(false, true).with(RecordDelta::of_account(true, false)), + RecordDelta { added: 1, taken: 1 } + ); } - /// A transfer log counts what a `LOG3` carrying one word counts: the same rule, not a number - /// of its own. + /// A transfer's records follow the net change of both sides, on the balances the transfer + /// leaves them; a transfer to the same account, of nothing, or of more than the sender holds + /// records nothing and journals no log. A creation records its created account and its + /// creator's nonce only where the transaction had not changed them, keeps the creator's off + /// the created frame, and journals a log for an endowment. #[test] - fn test_a_transfer_log_counts_what_a_log3_of_one_word_counts() { + fn test_a_starts_records_follow_the_net_change() { + let mut journal = journal(); + let accounts = Accounts::of(&journal, true); + let both = accounts.transfer_records(OTHER, DESTRUCTED, U256::from(1)); + assert_eq!(both.transfer, RecordDelta { added: 2, taken: 0 }); + assert!(both.transfer_log); + assert_eq!(accounts.transfer_records(OTHER, OTHER, U256::from(1)), StartRecords::NONE); + assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::ZERO), StartRecords::NONE); + assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::from(5)), StartRecords::NONE); + + // OTHER sent 1 to DESTRUCTED: sending it back returns both. + journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); + let back = Accounts::of(&journal, true).transfer_records(DESTRUCTED, OTHER, U256::from(1)); + assert_eq!(back.transfer, RecordDelta { added: 0, taken: 2 }); + assert_eq!(back.counted(), Counted::records(0, 2, true)); + + let created = address!("00000000000000000000000000000000000c4ea7"); + let accounts = Accounts::of(&journal, true); + let creation = accounts.creation_records(SENDER, Some(created), U256::from(1)); assert_eq!( - StagedRecord::Log { topics: 3, data_len: 32 }.effect(SENDER), - RecordEffect::Record(crate::limit::TRANSFER_LOG) + creation, + StartRecords { + transfer: RecordDelta::NONE, + created: true, + creator: true, + transfer_log: true + } ); + assert_eq!(creation.on_frame(), RecordDelta { added: 1, taken: 0 }); + let onto_changed = accounts.creation_records(OTHER, Some(DESTRUCTED), U256::ZERO); + assert!(!onto_changed.created && !onto_changed.creator && !onto_changed.transfer_log); + assert_eq!(accounts.creation_records(SENDER, None, U256::ZERO), StartRecords::NONE); + assert_eq!( + accounts.creation_records(SENDER, Some(created), U256::from(11)), + StartRecords::NONE, + "an endowment the creator cannot fund" + ); + } + + /// A creator's record is read off what revm did: nothing while its nonce is where it was + /// before the creation; once revm bumped it, a record when the bump changed an account the + /// transaction had not changed, and one account of state growth when it made an empty one. A + /// nonce set back leaves no record, unless the account keeps another change. + #[test] + fn test_a_creators_record_is_read_off_the_bump() { + let empty = address!("00000000000000000000000000000000000e3e70"); + let mut journal = journal(); + journal.load_account(empty).unwrap(); + journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); + let accounts = Accounts::of(&journal, true); + let [sender, changed, empty_before] = + [SENDER, DESTRUCTED, empty].map(|address| accounts.creator_before(address)); + for before in [sender, changed, empty_before] { + assert!(!accounts.bumped(&before), "{before:?}: nothing moved yet"); + } + + for address in [SENDER, DESTRUCTED, empty] { + assert!(journal.load_account_mut(address).unwrap().data.bump_nonce()); + } + let accounts = Accounts::of(&journal, true); + let record = Counted::records(1, 0, false); + for (before, counted) in + [(sender, record), (changed, Counted::NONE), (empty_before, record.with_growth(1, 0))] + { + assert!(accounts.bumped(&before), "{before:?}"); + assert_eq!(accounts.creator_counted(&before), counted, "{before:?}"); + } + + // A nonce set back: the unchanged account leaves no record, the one that keeps a balance + // change stands as it was. + for address in [SENDER, DESTRUCTED] { + journal.load_account_mut(address).unwrap().data.set_nonce(0); + } + let accounts = Accounts::of(&journal, true); + assert_eq!(accounts.creator_counted(&sender), Counted::NONE); + assert_eq!(accounts.creator_counted(&changed), Counted::NONE); } } diff --git a/crates/mega-evm/src/system/AGENTS.md b/crates/mega-evm/src/system/AGENTS.md index 5f450ba7b..cf25b0016 100644 --- a/crates/mega-evm/src/system/AGENTS.md +++ b/crates/mega-evm/src/system/AGENTS.md @@ -9,7 +9,7 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - `keyless/`: native keyless deployment. The `KeylessDeploy` address, code and ABI and the semantics of a deployment (`mod.rs`); the dispatch, the call's frame and its first run — the overhead, the nine rules, the charges of the creation's start and the creation it starts (`dispatch.rs`); the creation's return into its call and the ABI answer on the call's resume (`settle.rs`); the pre-EIP-155 transaction format and the error ABI (`tx.rs`, `error.rs`). - `control.rs`: `MegaAccessControl`'s address, code, ABI and revert payloads, `SLOT_NUM_ACCESS_TYPE`, and its interceptor, which steers gas detention's switch. - `limit_control.rs`: `MegaLimitControl`'s address, code, ABI and its interceptor, which answers the compute the calling frame could still spend. -- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its two pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness) and `transact_apply_pending_changes` (the system call on `pre_block_call_gas_limit`) — and `load_system_address`, the warming journal read of the registry's account and `_currentSystemAddress` every transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. +- `sequencer_registry.rs`: the `SequencerRegistry`'s address, code and ABI, its two pre-block helpers — `is_apply_pending_changes_due` (the read-only due check and its witness) and `transact_apply_pending_changes` (the system call on `PRE_BLOCK_CALL_GAS_LIMIT`) — and `load_system_address`, the warming journal read of the registry's account and `_currentSystemAddress` every transaction makes (no address unless the registry holds this engine's code and a non-zero address). No interceptor. - `predeploys.rs`: the list of the seven predeploys (`system_contract_specs`: address, code, code hash), the EIP-7997 factory's constants, and `check_system_contract`, the read Satin's activation block makes of each: exactly the expected code, whatever the nonce, balance and storage, or `SystemContractCheckError::UnexpectedCode` naming the address and both hashes. - `intercept.rs`: the dispatch — the address test, the selector peek, the value policy and the shape of an answer. - `tx.rs`: the system-address transaction, its whitelist and shape, the per-transaction decision and the refusal of another shape from the system address (`classify_system_transaction`), and the validation that precedes its promotion to a deposit. @@ -21,9 +21,9 @@ The six system contracts: their addresses and bytecode, the interceptor dispatch - An unknown selector is never intercepted: the call falls through to the deployed bytecode, and what that bytecode answers is the contract's own. The two control contracts revert with `NotIntercepted()` from their fallback; `KeylessDeploy` has no fallback, so a selector it does not declare reverts with empty data while a `keylessDeploy` call a contract makes reaches the method body's `NotIntercepted()`; the Oracle runs its other methods, and reverts with empty data on a selector it does not declare. - `CALL` and `STATICCALL` reach the dispatch. `CALLCODE` and `DELEGATECALL` run the callee's code in the caller's context, so they are refused by the scheme guard before any interceptor. - A method that takes no value answers a value-bearing call with `NonZeroTransfer()`, or with the error its own ABI names (`KeylessDeploy` answers `NoEtherTransfer()`). The policy is per method and is applied after the selector matched, so a value-bearing call to an unknown selector still falls through. -- An answer is a `synthetic_call_result`: the forwarded gas untouched, the caller's reservoir carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. +- An answer is a `synthetic_call_result`: the forwarded gas untouched, the reservoir share the call inherited carried, the calling opcode's upfront state-gas flags kept. Never `Gas::new(limit)`, which carries no reservoir and bills the sender for the whole state-gas pool. - An interceptor that lets the frame run charges nothing: the frame starts as it was built. -- A keyless deployment's call is a real frame at depth 0 in which no code runs: revm builds it on the contract, with its journal checkpoint, its gas and the lane a depth-0 call pushes, and `frame_run` makes its actions by hand (`keyless::run`, keyed on `MegaContext::keyless_frame`). Its first run, held by gas detention as any frame's, pays the overhead and what the `CREATE` opcode charges its frame, runs its lane as the signer, and returns the creation as its child at depth 1, or a refusal. The creation returns into it through `frame_return_result`, which reads the creation's outcome before revm's merge (`keyless::returning`) and applies the nonce take-back after (`keyless::settle`); on its resume the call answers in the ABI, unless it has a stop to return. The contract's account is touched as any call's target is, and its code never runs for a dispatched call. +- A keyless deployment's call is a real frame at depth 0 in which no code runs: revm builds it on the contract, with its journal checkpoint and its gas, the byte pool among it, as any depth-0 call, and its actions are made by hand, where revm built it and where its creation returns into it, and set on its interpreter, which revm's frame run, plain or inspected, returns without running an instruction. Its first action (`keyless::start`, in `frame_init`), once gas detention held the frame as any frame's, pays the overhead and what the `CREATE` opcode charges its frame, runs as the signer, and is the creation as its child at depth 1, or a refusal, which ends the frame before it runs. The creation returns into it through `frame_return_result`, which reads the creation's outcome before revm's merge (`keyless::returning`), applies the nonce take-back after (`keyless::settle`, while `MegaContext::keyless_creation` holds what the call started) and sets the call's answer in the ABI (`keyless::answer`), unless it has a stop to return. The contract's account is touched as any call's target is, and its code never runs for a dispatched call. - What stands after a keyless deployment is what its call keeps: a call that succeeds — the deployment deployed, or failed and reported it — keeps what the creation's start wrote, a signer's nonce spent from 0 to 1, its account and its record; a call that reverts with a stop takes the whole deployment back through its checkpoint. A creation that never started (one an inspector answered) gives the signer's account back. A deployment from nonce 1 keeps no bump when the bump is the last nonce change it made, whether it deployed or failed: the settlement sets the nonce back, so the signer stays at 1, nobody can use up its attempts, and a resubmission of one that deployed is refused `ContractAlreadyExists()`, as in the legacy engine. It takes the record and its history back with the bump, unless the creation succeeded and moved value out of the signer, whose account then keeps a write of its own. A signer whose own code spends a nonce in the constructor that survives it — on a default configuration, a delegated signer's `CREATE` or `CREATE2`, successful or not — keeps every bump, because a later bump may stand for an account and the nonce is never moved back under it; that signer ends above 1 and every later deployment of it is refused `SignerNonceTooHigh`. - The Oracle's `sendHint` is a side effect, not an answer: it forwards the hint and returns `None`, so the contract's own bytecode runs. It forwards only for a call that could deliver it — no value, some gas, a calling frame whose volatile-data access is on — and the payload is counted on the transaction's data size before it is decoded. A hint that fails one of those conditions is neither forwarded nor counted, and neither is one whose payload would cross the transaction's data-size limit: the limit is checked before the bytes are counted, the call is answered with the stop, a revert of the call alone, and the transaction keeps none of the hint's bytes. A payload that is admitted and does not decode is counted and forwards nothing. - An interceptor that acts for its caller takes the caller as the frame one level above the frame the call would start (`depth - 1`). A transaction that calls a system contract directly has no calling frame: `MegaAccessControl` then switches nothing off, enables without refusal and answers `false`, and `remainingComputeGas()` answers the transaction's own frame's regular gas, or detention's cap when it is detained from its start (its sender is the block beneficiary). @@ -69,7 +69,7 @@ The executor commits it on its own, in the order the steps run: a commit hook on ## WHERE TO LOOK - Add a method to an intercepted contract: the contract's own module, next to the selectors it already answers, and a boundary test per `tests/system/`. - Change what a call to a system contract costs: `intercept.rs` for the dispatch, the contract's module for what its own method charges. -- Change a keyless deployment: `keyless/dispatch.rs` for what is dispatched, the rules and the charges of the creation's start; `keyless/settle.rs` for the creation's return into the call and the answer; `evm/execution.rs` for where they are called — `frame_init`, `frame_run` and `frame_return_result`; `tests/system/keyless/` for the tests. +- Change a keyless deployment: `keyless/dispatch.rs` for what is dispatched, the rules and the charges of the creation's start; `keyless/settle.rs` for the creation's return into the call and the answer; `evm/execution.rs` for where they are called — `frame_init` and `frame_return_result`, which set the actions on the call's interpreter for revm's run to return; `tests/system/keyless/` for the tests. - Change the system transaction's validation: `tx.rs::validate_and_promote`, which `MegaHandler::validate_env_as` calls for both the handler's `validate_env` and the stateless pool validation (`evm/validation.rs`, which leaves the system address's nonce and code to the state). - Change what a deposit-like transaction pays for the account it creates: `evm/execution.rs`, where the charge is made in the pre-execution phase. - Add a predeploy: a spec in `predeploys.rs::system_contract_specs`, which Satin's activation block then checks; a contract Satin itself would install needs a mechanism of its own, which the engine no longer has. diff --git a/crates/mega-evm/src/system/keyless/dispatch.rs b/crates/mega-evm/src/system/keyless/dispatch.rs index ccc65c088..990875528 100644 --- a/crates/mega-evm/src/system/keyless/dispatch.rs +++ b/crates/mega-evm/src/system/keyless/dispatch.rs @@ -9,9 +9,12 @@ use alloy_evm::Database; use alloy_primitives::{Address, Bytes, U256}; use alloy_sol_types::SolCall; use revm::{ - context::{Cfg, ContextError, ContextTr, JournalTr, Transaction}, + context::{Cfg, ContextError, ContextTr, JournalTr}, context_interface::{ - cfg::{GasId, StateGasCharge, StateGasSite}, + cfg::{ + gas::{PoolAmounts, StartCharge}, + GasId, StateGasCharge, StateGasSite, + }, Host, }, handler::{EthFrame, FrameResult}, @@ -24,33 +27,20 @@ use revm::{ }; use crate::{ - charge_write_records_history, - limit::FrameStartRecords, - synthetic_call_result, + charge_write_records_history, synthetic_call_result, system::{ intercept::peek_selector, keyless::{ calculate_keyless_deploy_address, decode_keyless_tx, encode_error_result, - recover_signer, settle, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + recover_signer, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, KEYLESS_DEPLOY_CODE, KEYLESS_DEPLOY_CODE_HASH, KEYLESS_DEPLOY_OVERHEAD_GAS, }, }, untouched_call_gas, ExternalEnvTypes, MegaContext, VolatileDataAccess, }; -/// Where a `keylessDeploy` call's frame stands, from its start to its answer: what its first run -/// and its resume need of each other, kept on the context while the frame is on revm's stack. -#[derive(Debug)] -pub(crate) enum KeylessFrame { - /// revm built the call's frame, which has not run. - Built, - /// The call's first run started its creation, which runs. - Deploying(Started), - /// The creation returned into the call, which answers on its resume. - Returned(settle::Returned), -} - -/// What a `keylessDeploy` call's creation is settled into the call with. +/// What a `keylessDeploy` call's creation is settled into the call with, kept on the context while +/// the creation runs. #[derive(Debug)] pub(crate) struct Started { /// The address the creation deploys at. @@ -61,13 +51,12 @@ pub(crate) struct Started { /// What the call was charged for the signer's account, which the creation's start creates: /// zero when the signer had one. pub(super) signer_account_charge: u64, - /// The history the call paid for the signer's nonce record: zero when the signer is the - /// transaction's sender, which makes no record, or when the transaction pays no history. + /// The history the call paid for the signer's nonce record: zero when the transaction had + /// changed the signer's account already — the transaction's sender among them — which makes + /// no record, or when the transaction pays no history. pub(super) signer_record_charge: u64, - /// Whether the creation moves value out of the signer's account. - pub(super) moves_value: bool, /// Whether the deposit of empty code at the deploy address was refused, which reverts the - /// creation ([`refuses_empty_deposit`](settle::refuses_empty_deposit)). + /// creation ([`refuses_empty_deposit`](super::settle::refuses_empty_deposit)). pub(super) empty_deposit_refused: bool, } @@ -102,9 +91,10 @@ pub(crate) fn is_dispatched( /// would be. /// /// Any other call is built as a call to the contract, whose code it never runs: its actions are -/// made by [`run`]. The dispatch is by address and selector, whatever the address holds, so where -/// the state holds no contract code the frame is built on the contract's own. A chain Satin runs -/// on holds it, as Rex2 deployed it, and Satin's activation block checks it. +/// made by hand, its first by [`start`]. The dispatch is by address and selector, whatever the +/// address holds, so where the state holds no contract code the frame is built on the contract's +/// own. A chain Satin runs on holds it, as Rex2 deployed it, and Satin's activation block checks +/// it. #[inline(never)] pub(crate) fn ready( ctx: &mut MegaContext, @@ -119,45 +109,19 @@ pub(crate) fn ready( return Ok(None); } let mut gas = untouched_call_gas(inputs); - ctx.detention.hold(&mut gas); + ctx.detention.hold(gas.tracker_mut()); let Err(refusal) = prepare(ctx, inputs, &mut gas)? else { unreachable!("a call carrying value is refused at rule 2") }; Ok(Some(refusal.answer(inputs, gas))) } -/// Whether `frame` is a `keylessDeploy` call's, whose actions [`run`] makes in place of an -/// interpreter: the transaction's own frame, while the dispatch keeps its state. -#[inline] -pub(crate) fn runs( - ctx: &MegaContext, - frame: &EthFrame, -) -> bool { - frame.depth == 0 && ctx.keyless_frame.is_some() -} - -/// The next action of a `keylessDeploy` call's frame, made by hand: on its first run, the refusal -/// or the creation [`start`] makes; on its resume, once its creation returned into it, its answer -/// ([`settle::answer`]). -/// -/// A frame with a stop to return — a limit the nonce record a failed creation leaves the call -/// crosses — returns it before this runs, as any frame does. -#[inline(never)] -pub(crate) fn run( - ctx: &mut MegaContext, - frame: &mut EthFrame, -) -> Result> { - match ctx.keyless_frame.take() { - Some(KeylessFrame::Built) => start(ctx, frame), - Some(KeylessFrame::Returned(returned)) => { - Ok(settle::answer(ctx, &returned, frame.interpreter.gas)) - } - state => unreachable!("a keylessDeploy call runs when built or returned into: {state:?}"), - } -} - -/// The first run of a `keylessDeploy` call's frame: charges its gas and holds it to the rules, in -/// the order below, then starts the creation it stands for. +/// The first action of a `keylessDeploy` call's frame, which runs no instruction: charges its gas +/// and holds it to the rules, in the order below, then starts the creation it stands for. It is +/// made once revm built the frame and gas detention held it for its first run: a refusal ends the +/// frame before it runs, and the creation is set on the frame's interpreter, which returns it when +/// the frame runs. The call's answer is made when the creation returned into it +/// ([`answer`](super::settle::answer)). /// /// # What the call pays, and what it is held to /// @@ -206,11 +170,13 @@ pub(crate) fn run( /// # The creation /// /// The creation is started as the signer's, at the signer's Nick's-Method address -/// (`CreateScheme::Custom`), as the call's child: its share of the data-size budget, its records, -/// its forward and the reservoir it inherits. The call's lane runs as the signer, whose -/// nonce the creation's start writes. The call's journal checkpoint was taken when revm built its +/// (`CreateScheme::Custom`), as the call's child, on its forward and on its share of the reservoir +/// the call's charges left and of each of the call's pools, from which the call drew nothing. +/// The call's frame runs as the signer, whose nonce the creation's start writes; the record of +/// that nonce is the call's, counted once the creation returned +/// ([`settle`](super::settle::settle)). The call's journal checkpoint was taken when revm built its /// frame, so a call that is stopped takes that write back with the rest. -fn start( +pub(crate) fn start( ctx: &mut MegaContext, frame: &mut EthFrame, ) -> Result> { @@ -225,29 +191,30 @@ fn start( return Ok(InterpreterAction::new_return(result, output, *gas)); } }; - ctx.additional_limit.set_frame_creator(deployment.signer); - if let Some((on_lane, caller)) = deployment.record_charges { - ctx.additional_limit.stage_frame_charge(deployment.records, on_lane, caller); - } + // The creation's shares of the call's reservoir and pools are taken out of the call, as a + // `CREATE` opcode's are: the creation's return adds what it left back to what the call kept. + let shares = gas.tracker_mut().forward_to_child(ctx.gas_params()); let mut create = CreateInputs::new( deployment.signer, CreateScheme::Custom { address: deployment.deploy_address }, deployment.value, deployment.init_code, deployment.gas_limit, - gas.reservoir(), + shares.reservoir, ); create.set_charged_create_state_gas(deployment.charged_create_state_gas); create.set_charged_state_gas_address(deployment.deploy_address); - ctx.keyless_frame = Some(KeylessFrame::Deploying(Started { + let (on_frame, signer_record) = deployment.record_charges.unwrap_or((0, 0)); + create.set_charged_start(StartCharge::new(on_frame, PoolAmounts::ZERO)); + create.set_pool_shares(shares.pools); + ctx.keyless_creation = Some(Started { deploy_address: deployment.deploy_address, signer: deployment.signer, signer_nonce: deployment.signer_nonce, signer_account_charge: deployment.signer_account_charge, - signer_record_charge: deployment.record_charges.map_or(0, |(_, caller)| caller), - moves_value: !deployment.value.is_zero(), + signer_record_charge: signer_record, empty_deposit_refused: false, - })); + }); Ok(InterpreterAction::NewFrame(FrameInput::Create(Box::new(create)))) } @@ -264,10 +231,8 @@ struct Deployment { gas_limit: u64, /// Whether the call was charged the created account. charged_create_state_gas: bool, - /// The records the creation's start makes. - records: FrameStartRecords, - /// What the call paid for them: the created account's, and the signer's. `None` when the - /// transaction pays no history. + /// What the call paid for the records the creation's start makes: the created account's, and + /// the signer's nonce. `None` when the transaction pays no history. record_charges: Option<(u64, u64)>, } @@ -381,7 +346,7 @@ fn prepare( // in a frame of it, which a read of the account started. The call is the transaction's own // frame, at depth 0. if signer == ctx.block().beneficiary { - ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas, 0); + ctx.detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, gas); } if signer_info.nonce > 1 { refuse!(KeylessDeployError::SignerNonceTooHigh { signer_nonce: signer_info.nonce }); @@ -428,12 +393,12 @@ fn prepare( return Ok(Err(Refusal::OutOfGas)); } } - let records = FrameStartRecords { on_lane: 1, caller: signer != ctx.tx().caller() }; + let records = ctx.accounts().creation_records(signer, Some(deploy_address), tx.value); let record_charges = if ctx.prices_history() { let charged = charge_write_records_history( gas.tracker_mut(), - records.on_lane, - u64::from(records.caller), + records.on_frame().added, + u64::from(records.creator), ); if charged.is_none() { return Ok(Err(Refusal::OutOfGas)); @@ -458,7 +423,6 @@ fn prepare( init_code: tx.input.clone(), gas_limit, charged_create_state_gas, - records, record_charges, })) } diff --git a/crates/mega-evm/src/system/keyless/mod.rs b/crates/mega-evm/src/system/keyless/mod.rs index e121e7df4..a6f041077 100644 --- a/crates/mega-evm/src/system/keyless/mod.rs +++ b/crates/mega-evm/src/system/keyless/mod.rs @@ -6,13 +6,14 @@ //! //! A `keylessDeploy(bytes,uint256)` call a transaction makes is dispatched before any interceptor //! sees it ([`is_dispatched`]), and its frame is built as any call's is, but runs no code: its -//! actions are made by hand ([`run`]). On its first run it pays the fixed overhead and what the -//! `CREATE` opcode charges its frame, then starts the creation as its child — as the signer, at -//! the signer's Nick's-Method address, with `gasLimitOverride` capped to what the call has left. -//! From there the creation is an ordinary `CREATE` frame: priced, limited and journaled as one, -//! and returned into the call as one returns into the frame that started it ([`settle`]). On its -//! resume the call answers in the `IKeylessDeploy` ABI. An inspector sees both frames: the call, -//! and the creation as its child. There is no second EVM and no state to merge. +//! actions are made by hand and set on its interpreter, which returns each when the frame runs. +//! Its first ([`start`]) pays the fixed overhead and what the `CREATE` opcode charges its frame, +//! then starts the creation as its child — as the signer, at the signer's Nick's-Method address, +//! with `gasLimitOverride` capped to what the call has left. From there the creation is an +//! ordinary `CREATE` frame: priced, limited and journaled as one, and returned into the call as +//! one returns into the frame that started it ([`settle`]). The call then answers in the +//! `IKeylessDeploy` ABI ([`answer`]). An inspector sees both frames: the call, and the creation as +//! its child. There is no second EVM and no state to merge. //! //! What the native frame means for a deployment: //! @@ -22,7 +23,10 @@ //! transaction's first frame, as for any transaction to the contract, so a witness holds them //! either way; the frame touches the account, as a call touches its target, and a call that //! reverts takes the touch back. An inspector sees one call frame, started and ended as any -//! call's, with no interpreter initialized and no step in it. +//! call's, in which no interpreter is initialized and no step runs: revm's inspected run returns +//! the action set on the frame before any `step`, and hands a frame built with one to no +//! `initialize_interp`; a call a rule refuses ends before it runs, and is seen to start and end +//! and nothing else. //! - A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm //! builds its frame: no value moves, and nothing its start would write is counted. //! - The dispatch is by address and selector, whatever the address holds: where the state holds no @@ -73,8 +77,8 @@ //! crosses — reverts with the stop, taking back the signer's nonce with everything else. //! //! A creation an inspector revives — a tool's `create_end` that turns a failed creation into a -//! success at an address of its own, as Foundry's `expectRevert` does — settles as a frame that -//! kept nothing, and the call answers `AddressMismatch()` when that address is not the deploy +//! success at an address of its own, as Foundry's `expectRevert` does — is taken as given, as +//! revm takes it, and the call answers `AddressMismatch()` when that address is not the deploy //! address. //! //! # The error ABI @@ -108,8 +112,8 @@ mod tx; pub use error::*; pub use tx::*; -pub(crate) use dispatch::{is_dispatched, ready, run, runs, KeylessFrame}; -pub(crate) use settle::{refuses_empty_deposit, returning, settle}; +pub(crate) use dispatch::{is_dispatched, ready, start, Started}; +pub(crate) use settle::{answer, refuses_empty_deposit, returning, settle}; use alloy_primitives::{address, Address}; diff --git a/crates/mega-evm/src/system/keyless/settle.rs b/crates/mega-evm/src/system/keyless/settle.rs index 6ee7de062..293af60a9 100644 --- a/crates/mega-evm/src/system/keyless/settle.rs +++ b/crates/mega-evm/src/system/keyless/settle.rs @@ -20,11 +20,13 @@ use revm::{ }; use crate::{ + hold_creator, + limit::CreatorBefore, system::keyless::{encode_error_result, IKeylessDeploy, KeylessDeployError}, - ExternalEnvTypes, MegaContext, MegaHaltReason, + ExternalEnvTypes, LimitCheck, MegaContext, MegaHaltReason, }; -use super::dispatch::{KeylessFrame, Started}; +use super::dispatch::Started; /// What a `keylessDeploy` call answers from, once its creation returned into it. #[derive(Debug)] @@ -55,9 +57,7 @@ pub(crate) fn returning( stack: &mut FrameStack>, result: &FrameResult, ) -> Option { - if !matches!(ctx.keyless_frame, Some(KeylessFrame::Deploying(_))) { - return None; - } + ctx.keyless_creation.as_ref()?; if !returns_into_the_call(stack) { return None; } @@ -99,12 +99,12 @@ fn returns_into_the_call(stack: &mut FrameStack>) -> bo /// constructor that destroyed its own account (`destroyed`) is left as it is: the account does not /// keep what it returned, and the answer reads that off the journal ([`holds_code`]). pub(crate) fn refuses_empty_deposit( - frame: &mut Option, + creation: &mut Option, deposit: &CodeDeposit<'_>, destroyed: bool, ) -> bool { - match frame { - Some(KeylessFrame::Deploying(started)) + match creation { + Some(started) if deposit.code.is_empty() && deposit.address == started.deploy_address && !destroyed => @@ -117,7 +117,7 @@ pub(crate) fn refuses_empty_deposit( } /// Settles `creation`, which revm has just merged into the `keylessDeploy` call whose gas is -/// `gas`, and keeps what the call answers from on its resume ([`answer`]). +/// `gas`, and returns what the call answers from ([`answer`]). /// /// The merge is revm's own, as for a `CREATE`'s frame: the unspent forward, the reservoir, the /// creation's state and history gas when it succeeded, and the created account's charge when it @@ -128,25 +128,30 @@ pub(crate) fn refuses_empty_deposit( /// the creation's start never created it. And a deployment from nonce 0 keeps the creation's nonce /// bump, while from nonce 1 the bump is taken back, whether the deployment succeeded or failed, /// only when it is the last nonce change the deployment made ([`take_back_bump`]), leaving the -/// nonce at 1, as the legacy engine did; its write record and that record's history go with it, -/// unless the creation succeeded and moved value out of the signer. The call is permissionless -/// and the signed transaction public, so a nonce every failure spent would let anybody make a -/// signer's address undeployable with two failing calls; and a success that spent it would answer -/// a resubmission with `SignerNonceTooHigh` rather than `ContractAlreadyExists`. When the signer's -/// own code spent a nonce in the constructor that survived it — on a default configuration, a -/// delegated signer's `CREATE` or `CREATE2`, successful or not — nothing is taken back: a later -/// bump may stand for an account, so the nonce is never moved back under one. That signer ends -/// above 1, and a resubmission is refused `SignerNonceTooHigh`. +/// nonce at 1, as the legacy engine did; that record's history goes with it, unless the creation +/// succeeded and moved value out of the signer. The call is permissionless and the signed +/// transaction public, so a nonce every failure spent would let anybody make a signer's address +/// undeployable with two failing calls; and a success that spent it would answer a resubmission +/// with `SignerNonceTooHigh` rather than `ContractAlreadyExists`. When the signer's own code spent +/// a nonce in the constructor that survived it — on a default configuration, a delegated signer's +/// `CREATE` or `CREATE2`, successful or not — nothing is taken back: a later bump may stand for an +/// account, so the nonce is never moved back under one. That signer ends above 1, and a +/// resubmission is refused `SignerNonceTooHigh`. /// -/// It runs before the call resumes, because the record it takes back may be what put the call -/// over a limit: the call is held to its limits again without it, and the stop it returns on -/// its resume, if any, is the one that stands then. +/// Then the signer's nonce record is counted on the call, as a `CREATE`'s creator's is on the +/// creator once its creation returned ([`hold_creator`]): read off the signer's account as the +/// settlement left it — `signer` is the signer as it stood before revm decided the creation — when +/// revm bumped the nonce, held to the call's budget and then to the transaction's limit. A nonce +/// set back leaves no record to count, unless the account keeps the value the creation moved. A +/// crossing is the stop the call returns on its resume, before its answer; it runs before the +/// call resumes for that reason. pub(crate) fn settle( ctx: &mut MegaContext, gas: &mut Gas, creation: Creation, -) -> Result<(), ContextError> { - let Some(KeylessFrame::Deploying(started)) = ctx.keyless_frame.take() else { + signer: Option, +) -> Result<(Returned, Option), ContextError> { + let Some(started) = ctx.keyless_creation.take() else { unreachable!("a creation returns into a keylessDeploy call that started it") }; // The creation's start is what creates an empty signer's account. revm bumps the nonce of @@ -157,23 +162,25 @@ pub(crate) fn settle( if nonce == started.signer_nonce { gas.refill_reservoir(started.signer_account_charge); } + let bumped = signer.filter(|signer| ctx.accounts().bumped(signer)); // A deployment from nonce 1 keeps no bump of its own: a failure leaves the address // deployable, a success leaves it occupied. The creation's bump is the one above the nonce // the call started from, and it is taken back only when it is the last one: a later bump the // signer's own code made may stand for an account, so the nonce is never moved back under it. if started.signer_nonce > 0 && nonce == started.signer_nonce + 1 { - take_back_bump(ctx, gas, &started, creation.result)?; + take_back_bump(ctx, gas, &started)?; } - ctx.keyless_frame = Some(KeylessFrame::Returned(Returned { started, creation })); - Ok(()) + let stop = bumped.and_then(|signer| hold_creator(ctx, gas.tracker_mut(), &signer)); + Ok((Returned { started, creation }, stop)) } /// The action of a `keylessDeploy` call resuming on `gas` once its creation `returned` into it, a -/// stop aside: `keylessDeploy`'s return — the deployed address when the creation left code at it, -/// or the zero address and the error the creation failed with, `ExecutionReverted`, -/// `ExecutionHalted`, or `EmptyCodeDeployed` for a creation that left no code, having deployed none -/// or destroyed itself. The call succeeds, and keeps what the creation's start wrote: a signer at -/// nonce 0 whose deployment failed has spent its nonce all the same. +/// stop aside, set on the call's interpreter for its run to return: `keylessDeploy`'s return — the +/// deployed address when the creation left code at it, or the zero address and the error the +/// creation failed with, `ExecutionReverted`, `ExecutionHalted`, or `EmptyCodeDeployed` for a +/// creation that left no code, having deployed none or destroyed itself. The call succeeds, and +/// keeps what the creation's start wrote: a signer at nonce 0 whose deployment failed has spent its +/// nonce all the same. /// /// `gasUsed` is what the creation spent: its regular gas and the state and history gas it kept, /// from whichever pool paid it. It is the same whether the transaction has a state-gas reservoir @@ -224,33 +231,37 @@ fn answer_of( } /// Whether the deployment left code at `address`. The code the journal holds, not the code the -/// constructor returned: a constructor that destroyed its own account (EIP-6780) returned code -/// the account does not keep. +/// constructor returned: a constructor that destroyed its own account (EIP-6780) in this +/// transaction returned code the account does not keep. A destruction an earlier transaction on +/// the same journal made, whose mark revm keeps on the account, is not this one. fn holds_code( ctx: &MegaContext, address: Address, ) -> bool { - ctx.journal_ref().state.get(&address).is_some_and(|account| { - account.info.code_hash != KECCAK_EMPTY && !account.is_selfdestructed() - }) + let code = ctx + .journal_ref() + .state + .get(&address) + .is_some_and(|account| account.info.code_hash != KECCAK_EMPTY); + code && !ctx.accounts().is_destroyed(address) } -/// Takes back the creation's nonce bump of a signer whose nonce was already 1, with its write -/// record and that record's history, so what stands is what would stand had the creation's start -/// not bumped the nonce: the signer stays at 1, however many deployments it makes. +/// Takes back the creation's nonce bump of a signer whose nonce was already 1, with that record's +/// history, so what stands is what would stand had the creation's start not bumped the nonce: the +/// signer stays at 1, however many deployments it makes. The record itself is counted afterwards, +/// off the account as this leaves it, so a nonce set back leaves none to take back. /// -/// The record goes unless the signer's account keeps another write it stands for: the value a -/// creation that succeeded moved out of it. A creation that failed took its value transfer back -/// with the rest of its writes. +/// The record follows the signer's account: it goes when the nonce set back leaves the account +/// as the transaction loaded it, and stays when the account keeps another write it stands for — +/// the value a creation that succeeded moved out of it, or into it. A creation that failed took +/// its value transfer back with the rest of its writes. fn take_back_bump( ctx: &mut MegaContext, gas: &mut Gas, started: &Started, - result: InstructionResult, ) -> Result<(), ContextError> { ctx.journal_mut().load_account_mut(started.signer)?.data.set_nonce(started.signer_nonce); - let moved_value = started.moves_value && result.is_ok(); - if !moved_value && ctx.additional_limit.take_back_creator_record() { + if !ctx.accounts().is_changed(started.signer) { gas.refill_history(started.signer_record_charge); } Ok(()) diff --git a/crates/mega-evm/src/system/limit_control.rs b/crates/mega-evm/src/system/limit_control.rs index 10276934a..cccb146f6 100644 --- a/crates/mega-evm/src/system/limit_control.rs +++ b/crates/mega-evm/src/system/limit_control.rs @@ -59,7 +59,7 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// what a block-environment read's cap leaves it when its frame holds more. /// /// The figure is taken before the forward: taken after it, a caller that forwards what `GAS` -/// reports would hear back one sixty-fourth of its gas. That is the one property carried over +/// reports would hear back the 2 per cent of its gas it kept. That is the one property carried over /// from the legacy engine, whose compute never counted the gas a call forwarded. The figure /// itself departs from the legacy engine's, which came from a separate compute ledger, with /// per-frame budgets of 98/100 of the caller's remaining compute under the transaction's compute @@ -69,9 +69,9 @@ pub use mega_system_contracts::limit_control::IMegaLimitControl; /// It is regular gas only, capped at the execution cap: the state-gas reservoir is not compute, /// and a transaction above the cap hears the cap's share at most. It is not a promise of compute /// either: state or history gas the caller later pays out of its regular gas comes out of the -/// same figure. A frame a value call started holds its stipend in its own regular gas, and -/// detention counts the stipend outside compute, so the frame hears it counted whether or not it -/// is detained. +/// same figure. A frame a value call started holds its stipend in its own regular gas, and hears +/// it with that gas while that gas binds; what it runs on the stipend is compute like the rest, so +/// once detention's limit binds, the stipend adds nothing to what the limit leaves. /// /// The method reads and takes no value. pub(crate) fn intercept( diff --git a/crates/mega-evm/src/system/oracle.rs b/crates/mega-evm/src/system/oracle.rs index c4ab0bc23..9826675aa 100644 --- a/crates/mega-evm/src/system/oracle.rs +++ b/crates/mega-evm/src/system/oracle.rs @@ -68,8 +68,8 @@ pub use mega_system_contracts::oracle::IOracle; /// A `STATICCALL` does forward: `sendHint` is a view method and writes nothing. /// /// The payload is counted toward the transaction's data size before it is decoded -/// ([`AdditionalLimit::record_hint_bytes`](crate::AdditionalLimit)), so trailing bytes an ABI -/// decoder ignores are paid for; a payload that would cross the transaction's limit is neither +/// ([`AdditionalLimit::admit_hint`](crate::AdditionalLimit)), so trailing bytes an ABI decoder +/// ignores are paid for; a payload that would cross the transaction's limit is neither /// forwarded nor counted, and the call is answered with the stop: a revert carrying /// `MegaLimitExceeded`, on the gas it was forwarded, as the frame it would have started. So the /// data size a transaction keeps holds exactly the hints that were admitted. @@ -91,7 +91,7 @@ pub(crate) fn intercept( return None; } let payload = inputs.input.bytes(&*ctx); - let check = ctx.additional_limit.record_hint_bytes(payload.len() as u64); + let check = ctx.additional_limit.admit_hint(payload.len() as u64); if check.exceeded_limit() { let output = ctx.additional_limit.note_frame_stop(&check); return Some(synthetic_call_result(inputs, InstructionResult::Revert, output)); @@ -150,6 +150,9 @@ mod tests { scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, } } @@ -175,11 +178,11 @@ mod tests { assert_eq!(result.output, stop.revert_data()); assert_eq!(result.gas.remaining(), FORWARD, "the forward is untouched"); assert!(envs.recorded_hints().is_empty(), "nothing is forwarded"); - assert_eq!(ctx.additional_limit.usage().data_size, 0, "nothing is counted"); + assert_eq!(ctx.limit_usage().data_size, 0, "nothing is counted"); let (mut ctx, envs) = recording(payload); assert!(intercept(&mut ctx, &inputs, 1).is_none(), "the bytecode runs"); assert_eq!(envs.recorded_hints().len(), 1); - assert_eq!(ctx.additional_limit.usage().data_size, payload); + assert_eq!(ctx.limit_usage().data_size, payload); } } diff --git a/crates/mega-evm/src/system/sequencer_registry.rs b/crates/mega-evm/src/system/sequencer_registry.rs index f7cda377b..ce8d987b8 100644 --- a/crates/mega-evm/src/system/sequencer_registry.rs +++ b/crates/mega-evm/src/system/sequencer_registry.rs @@ -116,7 +116,7 @@ fn read_slot( /// state. Nothing is committed. /// /// It is a system call from the EIP-4788 system address on the pre-block budget -/// ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)): at most 30M of regular gas, +/// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)): 30M of regular gas, /// the rest reservoir, its state priced at the minimum SALT bucket. One call applies whichever of /// the two roles is due; the block executor makes it only when [`is_apply_pending_changes_due`] /// says one is. @@ -212,12 +212,13 @@ fn system_address_named_by(code_hash: B256, current: U256) -> Option
{ #[cfg(test)] mod tests { use super::*; - use crate::{system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId}; + use crate::{ + system::MEGA_SYSTEM_ADDRESS, MegaContext, MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT, + }; use alloy_primitives::address; use revm::{ context::{BlockEnv, ContextTr, JournalTr, Transaction}, database::{InMemoryDB, State}, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, state::{AccountInfo, Bytecode}, Database, DatabaseCommit, }; @@ -376,28 +377,23 @@ mod tests { } } - /// The call runs on the block's gas limit, of which 30M is regular gas and the rest the - /// reservoir: a registry with nothing due writes nothing, and all of the reservoir is left. + /// The call runs on the pre-block budget whatever the block's gas limit, of which 30M is + /// regular gas and the rest the reservoir: a registry with nothing due writes nothing, and all + /// of the reservoir is left, in a block of 1M and in one of 250M. #[test] - fn test_transact_apply_pending_changes_uses_block_gas_limit() { - let mut db = registry_with(&[]); - let mut evm = evm(&mut db, 250_000_000); - let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), 250_000_000); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - 250_000_000 - SYSTEM_CALL_REGULAR_GAS_LIMIT - ); - } - - /// A block whose gas limit is below 30M still gives the call 30M, all of it regular gas. - #[test] - fn test_transact_apply_pending_changes_respects_30m_floor() { - let mut db = registry_with(&[]); - let mut evm = evm(&mut db, 1_000_000); - let outcome = transact_apply_pending_changes(&mut evm).expect("the call succeeds"); - assert_eq!(evm.ctx().tx().gas_limit(), SYSTEM_CALL_REGULAR_GAS_LIMIT); - assert_eq!(outcome.result.gas().reservoir_remaining(), 0); + fn test_transact_apply_pending_changes_runs_on_the_pre_block_budget() { + use crate::constants::PRE_BLOCK_CALL_GAS_LIMIT; + for block_gas_limit in [1_000_000, 250_000_000] { + let mut db = registry_with(&[]); + let mut evm = evm(&mut db, block_gas_limit); + transact_apply_pending_changes(&mut evm).expect("the call succeeds"); + assert_eq!(evm.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "{block_gas_limit}"); + assert_eq!( + evm.ctx().additional_limit().reservoir_remaining(), + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT, + "{block_gas_limit}" + ); + } } /// A read the database cannot serve during the call is the database's error, not a verdict on diff --git a/crates/mega-evm/src/test_utils/mod.rs b/crates/mega-evm/src/test_utils/mod.rs index f3f3de534..5e46a06a6 100644 --- a/crates/mega-evm/src/test_utils/mod.rs +++ b/crates/mega-evm/src/test_utils/mod.rs @@ -8,6 +8,7 @@ mod logs; mod neutral; mod opcode_gen; mod price_guard; +mod read_only_observer; mod scenario; mod witness; @@ -19,5 +20,6 @@ pub use logs::*; pub use neutral::*; pub use opcode_gen::*; pub use price_guard::*; +pub use read_only_observer::*; pub use scenario::*; pub use witness::*; diff --git a/crates/mega-evm/src/test_utils/neutral.rs b/crates/mega-evm/src/test_utils/neutral.rs index 2306bee31..6abeecd7f 100644 --- a/crates/mega-evm/src/test_utils/neutral.rs +++ b/crates/mega-evm/src/test_utils/neutral.rs @@ -58,11 +58,11 @@ use crate::{ /// otherwise keys on the spec id; EIP-7825's execution cap; the EIP-7954 code-size limits, set /// explicitly for the same reason. /// -/// On both, a system call's whole gas limit is regular gas, as revm's runner has it: the switch -/// that makes the part above 30,000,000 a state-gas reservoir, which Satin sets, is off. Under -/// Osaka it would do nothing, EIP-8037 being off. Under Amsterdam upstream revm splits no system -/// call's gas, and no state fixture makes a system call, so neither release the gate runs can -/// tell the two apart. +/// On both, a system call's whole gas limit is regular gas, as revm's runner has it: a context on +/// the neutral configuration does not make the part above 30,000,000 a state-gas reservoir, as +/// Satin's handler does. Under Osaka the split would do nothing, EIP-8037 being off. Under +/// Amsterdam upstream revm splits no system call's gas, and no state fixture makes a system call, +/// so neither release the gate runs can tell the two apart. /// /// Every other field is revm's default: chain id 1, which a caller replaces with the fixture's. pub fn neutral_cfg(fork: EthSpecId) -> Option> { @@ -77,7 +77,6 @@ pub fn neutral_cfg(fork: EthSpecId) -> Option> { cfg.enable_amsterdam_eip2780 = amsterdam; cfg.enable_amsterdam_eip7708 = amsterdam; cfg.tx_gas_limit_cap = None; - cfg.system_call_state_gas_margin_in_reservoir = false; if amsterdam { cfg.limit_contract_code_size = Some(eip7954::MAX_CODE_SIZE); cfg.limit_contract_initcode_size = Some(eip7954::MAX_INITCODE_SIZE); @@ -185,8 +184,7 @@ mod tests { assert_eq!(cfg.max_initcode_size(), eip3860::MAX_INITCODE_SIZE); assert_eq!(cfg.max_code_size(), osaka.max_code_size()); assert_eq!(cfg.max_initcode_size(), osaka.max_initcode_size()); - assert!(!cfg.system_call_state_gas_margin_in_reservoir()); - assert!(!osaka.system_call_state_gas_margin_in_reservoir()); + assert_system_call_gas_is_whole(ctx); } /// Amsterdam's configuration carries what revm's runner derives from the Amsterdam spec id, @@ -203,8 +201,13 @@ mod tests { assert_eq!(cfg.max_code_size(), amsterdam.max_code_size()); assert_eq!(cfg.max_initcode_size(), amsterdam.max_initcode_size()); assert_eq!(cfg.max_code_size(), eip7954::MAX_CODE_SIZE); - assert!(!cfg.system_call_state_gas_margin_in_reservoir()); - assert!(!amsterdam.system_call_state_gas_margin_in_reservoir()); + assert_system_call_gas_is_whole(ctx); + } + + /// A system call on `ctx` runs on its whole gas limit as regular gas, as revm's runner has it. + fn assert_system_call_gas_is_whole(mut ctx: MegaContext) { + ctx.on_new_system_call(); + assert!(!ctx.splits_system_call_gas()); } /// Neither configuration is Satin's, and both run Satin's spec. diff --git a/crates/mega-evm/src/test_utils/read_only_observer.rs b/crates/mega-evm/src/test_utils/read_only_observer.rs new file mode 100644 index 000000000..60043b477 --- /dev/null +++ b/crates/mega-evm/src/test_utils/read_only_observer.rs @@ -0,0 +1,264 @@ +//! An observer that proves, in debug builds, that the inspector it wraps writes nothing back. + +use revm::{ + context::{ContextTr, JournalTr}, + handler::FrameResult, + inspector::JournalExt, + interpreter::{ + CallInputs, CallOutcome, CreateInputs, CreateOutcome, FrameInput, Interpreter, + InterpreterTypes, + }, + primitives::{Address, Log, U256}, + Inspector, +}; + +/// Wraps an inspector that is meant to write nothing back, and proves it in debug builds. +/// +/// It forwards every callback to the inspector inside and adds nothing. A debug build checks +/// around every callback and panics at the one that breaks the claim: the interpreter's gas, +/// pending action, stack depth and memory size, the frame's inputs, the frame result, and the +/// journal's entries and logs must be as they were, and no frame may be answered. Writes the check +/// cannot see (a stack word replaced in place, a context field outside the journal) are not caught; +/// the check is a tripwire, not a proof. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ReadOnlyObserver(pub I); + +impl ReadOnlyObserver { + /// Declares `inspector` a read-only observer. + pub const fn new(inspector: I) -> Self { + Self(inspector) + } + + /// The inspector inside. + pub fn into_inner(self) -> I { + self.0 + } +} + +impl Inspector for ReadOnlyObserver +where + I: Inspector, + CTX: ContextTr, + INTR: InterpreterTypes, +{ + #[inline] + fn initialize_interp(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.initialize_interp(interp, context); + assert_unwritten(before, interp, context, "initialize_interp"); + } + + #[inline] + fn step(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step(interp, context); + assert_unwritten(before, interp, context, "step"); + } + + #[inline] + fn step_end(&mut self, interp: &mut Interpreter, context: &mut CTX) { + let before = snapshot(interp, context); + self.0.step_end(interp, context); + assert_unwritten(before, interp, context, "step_end"); + } + + #[inline] + fn log(&mut self, context: &mut CTX, log: Log) { + let before = journal_snapshot(context); + self.0.log(context, log); + assert_journal_unwritten(before, context, "log"); + } + + #[inline] + fn log_full(&mut self, interp: &mut Interpreter, context: &mut CTX, log: Log) { + let before = snapshot(interp, context); + self.0.log_full(interp, context, log); + assert_unwritten(before, interp, context, "log_full"); + } + + #[inline] + fn frame_start( + &mut self, + context: &mut CTX, + frame_input: &mut FrameInput, + ) -> Option { + let before = + cfg!(debug_assertions).then(|| (frame_input.clone(), journal_snapshot(context))); + let answer = self.0.frame_start(context, frame_input); + debug_assert!(answer.is_none(), "a read-only observer answered a frame in `frame_start`"); + if let Some((input, journal)) = before { + debug_assert!(&input == frame_input, "a read-only observer rewrote a frame's inputs"); + assert_journal_unwritten(journal, context, "frame_start"); + } + answer + } + + #[inline] + fn frame_end( + &mut self, + context: &mut CTX, + frame_input: &FrameInput, + frame_result: &mut FrameResult, + ) { + let before = result_snapshot(frame_result); + let journal = journal_snapshot(context); + self.0.frame_end(context, frame_input, frame_result); + assert_result_unwritten(before, frame_result, "frame_end"); + assert_journal_unwritten(journal, context, "frame_end"); + } + + #[inline] + fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.call(context, inputs); + debug_assert!(answer.is_none(), "a read-only observer answered a call"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a read-only observer rewrote a call's inputs"); + } + assert_journal_unwritten(journal, context, "call"); + answer + } + + #[inline] + fn call_end(&mut self, context: &mut CTX, inputs: &CallInputs, outcome: &mut CallOutcome) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.call_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a read-only observer rewrote a call result"); + } + assert_journal_unwritten(journal, context, "call_end"); + } + + #[inline] + fn create(&mut self, context: &mut CTX, inputs: &mut CreateInputs) -> Option { + let before = cfg!(debug_assertions).then(|| inputs.clone()); + let journal = journal_snapshot(context); + let answer = self.0.create(context, inputs); + debug_assert!(answer.is_none(), "a read-only observer answered a creation"); + if let Some(before) = before { + debug_assert!(&before == inputs, "a read-only observer rewrote a creation's inputs"); + } + assert_journal_unwritten(journal, context, "create"); + answer + } + + #[inline] + fn create_end( + &mut self, + context: &mut CTX, + inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + let before = cfg!(debug_assertions).then(|| outcome.clone()); + let journal = journal_snapshot(context); + self.0.create_end(context, inputs, outcome); + if let Some(before) = before { + debug_assert!(&before == outcome, "a read-only observer rewrote a creation result"); + } + assert_journal_unwritten(journal, context, "create_end"); + } + + #[inline] + fn selfdestruct(&mut self, contract: Address, target: Address, value: U256) { + self.0.selfdestruct(contract, target, value); + } +} + +/// The journal's entry and log counts, for the debug-build proof. `None` in release builds. +type JournalSnapshot = Option<(usize, usize)>; + +#[inline] +fn journal_snapshot>(context: &CTX) -> JournalSnapshot { + cfg!(debug_assertions) + .then(|| (context.journal_ref().journal().len(), context.journal_ref().logs().len())) +} + +#[inline] +fn assert_journal_unwritten>( + before: JournalSnapshot, + context: &CTX, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + journal_snapshot(context).expect("debug build"), + "a read-only observer wrote to the journal in `{callback}`" + ); + } +} + +/// An interpreter's and the journal's state, for the debug-build proof. +type Snapshot = (GasSnapshot, JournalSnapshot); + +#[inline] +fn snapshot>( + interp: &Interpreter, + context: &CTX, +) -> Snapshot { + (gas_snapshot(interp), journal_snapshot(context)) +} + +#[inline] +fn assert_unwritten>( + (gas, journal): Snapshot, + interp: &Interpreter, + context: &CTX, + callback: &str, +) { + assert_gas_unwritten(gas, interp, callback); + assert_journal_unwritten(journal, context, callback); +} + +/// An interpreter's gas, pending action, stack depth and memory size, for the debug-build proof. +/// `None` in release builds. +type GasSnapshot = Option<(revm::interpreter::Gas, bool, usize, usize)>; + +#[inline] +fn gas_snapshot(interp: &Interpreter) -> GasSnapshot { + use revm::interpreter::interpreter_types::{LoopControl, MemoryTr, StackTr}; + cfg!(debug_assertions) + .then(|| (interp.gas, interp.bytecode.is_end(), interp.stack.len(), interp.memory.size())) +} + +#[inline] +fn assert_gas_unwritten( + before: GasSnapshot, + interp: &Interpreter, + callback: &str, +) { + if let Some(before) = before { + debug_assert_eq!( + before, + gas_snapshot(interp).expect("debug build"), + "a read-only observer wrote to the interpreter in `{callback}`" + ); + } +} + +/// A frame result's classification, gas and output, and a creation's address, for the +/// debug-build proof. +type ResultSnapshot = Option<(revm::interpreter::InterpreterResult, Option
)>; + +#[inline] +fn result_snapshot(result: &FrameResult) -> ResultSnapshot { + cfg!(debug_assertions).then(|| { + let address = match result { + FrameResult::Call(_) => None, + FrameResult::Create(outcome) => outcome.address, + }; + (result.interpreter_result().clone(), address) + }) +} + +#[inline] +fn assert_result_unwritten(before: ResultSnapshot, result: &FrameResult, callback: &str) { + if let Some(before) = before { + debug_assert!( + before == result_snapshot(result).expect("debug build"), + "a read-only observer rewrote a frame result in `{callback}`" + ); + } +} diff --git a/crates/mega-evm/tests/block/counters.rs b/crates/mega-evm/tests/block/counters.rs index 9c6557888..3ccd8f89d 100644 --- a/crates/mega-evm/tests/block/counters.rs +++ b/crates/mega-evm/tests/block/counters.rs @@ -193,11 +193,11 @@ fn test_a_block_reports_the_bytes_its_history_gas_does_not_cover() { // Each transaction: its body, the transfer's two records and the receiver's event. let per_tx = mega_evm::TX_BODY_SIZE + 2 * mega_evm::WRITE_RECORD_SIZE + - mega_evm::STORAGE_CALL_STIPEND_BYTES; + mega_evm::HISTORY_ALLOWANCE_BYTES; assert_eq!(counters.history_bytes, 2 * per_tx); assert_eq!( counters.history_bytes * mega_evm::constants::COST_PER_HISTORY_BYTE - counters.history, - 2 * mega_evm::storage_call_stipend(), + 2 * mega_evm::history_allowance_gas(), "the allowances paid for both events, and no gas ledger has them", ); @@ -313,3 +313,52 @@ fn test_an_out_of_gas_before_the_first_frame_bills_the_whole_gas_limit_to_the_bl assert_eq!(recipients_after - recipients_before, paid, "the fee recipients are credited it"); assert_eq!(balance(&mut state, FRESH), U256::ZERO, "the recipient was not created"); } + +/// The pre-block calls are the protocol's own work, and no transaction of the block: what they +/// write is counted towards none of the block's budgets. The EIP-2935 call stores the parent's +/// hash and the EIP-4788 call the block's timestamp and its beacon root, each in a fresh slot, a +/// write record and a unit of state growth were a transaction to make it, and the block's usage +/// stays zero. +#[test] +fn test_the_pre_block_calls_count_towards_no_block_budget() { + use alloy_eips::{ + eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + }; + use alloy_primitives::B256; + use revm::Database as _; + + // The ring buffers both contracts store in. + const BUFFER: u64 = 8_191; + let (parent, root) = (B256::repeat_byte(0x11), B256::repeat_byte(0x22)); + let mut db = common::database(); + db.set_account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()); + let mut state = State::builder().with_database(db).build(); + let slots = [ + (HISTORY_STORAGE_ADDRESS, U256::from((common::BLOCK_NUMBER - 1) % BUFFER), parent.into()), + ( + BEACON_ROOTS_ADDRESS, + U256::from(common::BLOCK_TIMESTAMP % BUFFER), + U256::from(common::BLOCK_TIMESTAMP), + ), + (BEACON_ROOTS_ADDRESS, U256::from(common::BLOCK_TIMESTAMP % BUFFER + BUFFER), root.into()), + ]; + for (address, slot, _) in slots { + assert_eq!(state.storage(address, slot).unwrap(), U256::ZERO, "a fresh slot"); + } + let ctx = mega_evm::MegaBlockExecutionCtx::new( + parent, + Some(root), + Bytes::new(), + mega_evm::BlockLimits::no_limits(), + ); + let mut executor = executor(&mut state, ctx); + executor.apply_pre_execution_changes().expect("the block starts"); + assert_eq!(executor.limiter().usage, mega_evm::LimitUsage::default()); + assert_eq!(*executor.gas(), BlockGasCounters::default()); + drop(executor); + for (address, slot, value) in slots { + assert_eq!(state.storage(address, slot).unwrap(), value, "the pre-block call stored it"); + } +} diff --git a/crates/mega-evm/tests/block/eips.rs b/crates/mega-evm/tests/block/eips.rs index 6a72eb556..89a9cd9c3 100644 --- a/crates/mega-evm/tests/block/eips.rs +++ b/crates/mega-evm/tests/block/eips.rs @@ -5,8 +5,8 @@ //! make leaves that state alone. A call that does not succeed refuses the block, and its state is //! never committed: neither a commit hook nor the database sees it. //! -//! Each call runs on the pre-block budget: the block's gas limit, and never less than 30M, of -//! which at most 30M is regular gas and the rest the call's state-gas reservoir. +//! Each call runs on the pre-block budget, `PRE_BLOCK_CALL_GAS_LIMIT`, whatever the block's gas +//! limit: 30M of regular gas and the rest the call's state-gas reservoir. use alloy_eips::{ eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, @@ -20,16 +20,14 @@ use alloy_hardforks::{EthereumHardfork, ForkCondition}; use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; use alloy_primitives::{Address, Bytes, B256, U256}; use mega_evm::{ - constants::SLOT_STATE_GAS, - pre_block_call_gas_limit, + constants::{PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS}, test_utils::{BytecodeBuilder, CommittedStates, ErrorInjectingDatabase, MemoryDatabase}, BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, - MegaSpecId, + MegaSpecId, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; use revm::{ - bytecode::opcode::{CALLDATALOAD, MLOAD, SSTORE}, + bytecode::opcode::{CALLDATALOAD, GAS, MLOAD, SSTORE}, database::State, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, Database, }; @@ -445,49 +443,72 @@ fn test_a_block_is_refused_when_its_beacon_root_call_halts() { assert_eq!(calls, [HISTORY_STORAGE_ADDRESS]); } -/// The pre-block budget follows the block's gas limit, so a pre-block call that costs more than -/// 30M in all still succeeds in a block that can hold it: 400 fresh slots are 39M of state gas, -/// which the reservoir above 30M pays. In a block of 30M the call has no reservoir, the state -/// gas spills onto the 30M of regular gas, and the call runs out of it. +/// Code that writes `slots` fresh storage slots, then stores the regular gas it has left in the +/// slot after them. +fn fresh_writes_then_gas(slots: u16) -> Bytes { + (0..slots) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .append(GAS) + .push_number(slots) + .append(SSTORE) + .stop() + .build() +} + +/// The pre-block budget is one constant, whatever the block's gas limit: in a block of 1M, of 30M +/// and of 250M each pre-block call runs on [`PRE_BLOCK_CALL_GAS_LIMIT`], 30M of regular gas and +/// a reservoir of sixteen fresh slots. Sixteen fresh writes run the same in each, the regular gas +/// left after them included: the reservoir pays them in a small block too. A call that costs more +/// than the budget in all — 400 fresh slots are 39M of state gas — runs out of gas in each and +/// refuses the block, in a 250M block too. #[test] -fn test_the_block_aware_budget_accepts_a_pre_block_call_above_30m() { - const SLOTS: u16 = 400; - assert_eq!(pre_block_call_gas_limit(250_000_000), 250_000_000); - assert_eq!(pre_block_call_gas_limit(1_000_000), SYSTEM_CALL_REGULAR_GAS_LIMIT); - // The slot count is sized at Satin's own price; other byte prices move the 30M boundary. - if !mega_evm::active_satin_prices().is_constants() { - return; - } - assert!(u64::from(SLOTS) * SLOT_STATE_GAS > SYSTEM_CALL_REGULAR_GAS_LIMIT); +fn test_the_pre_block_budget_does_not_follow_the_block() { + use revm::context::{ContextTr, Transaction}; - let database = || { + const HELD: u16 = 16; + const SLOTS: u16 = 400; + let database = |code: Bytes| { let mut db = common::database(); - db.set_account_code(HISTORY_STORAGE_ADDRESS, fresh_writes(SLOTS)); - db.set_account_code(BEACON_ROOTS_ADDRESS, fresh_writes(SLOTS)); + db.set_account_code(HISTORY_STORAGE_ADDRESS, code.clone()); + db.set_account_code(BEACON_ROOTS_ADDRESS, code); db }; - - let mut state = State::builder().with_database(database()).build(); - let committed = CommittedStates::install(&mut state); - let mut executor = executor_with_env(&mut state, ctx(), env_with_gas_limit(250_000_000)); - executor.apply_pre_execution_changes().expect("a 250M block holds both calls"); - let states = committed.states(); - assert_eq!(states[0][&HISTORY_STORAGE_ADDRESS].storage.len(), usize::from(SLOTS)); - assert_eq!(states[1][&BEACON_ROOTS_ADDRESS].storage.len(), usize::from(SLOTS)); - drop(executor); - - let (calls, started) = start_block(database(), common::evm_env()); - assert_eq!(common::BLOCK_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT); - let err = started.expect_err("a 30M block gives the call no reservoir"); - assert!( - matches!( - &err, - BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { message }) - if message.contains("OutOfGas") - ), - "{err}" - ); - assert!(calls.is_empty(), "{calls:?}"); + let gas_left = [1_000_000, 30_000_000, 250_000_000].map(|block_gas_limit| { + let mut state = + State::builder().with_database(database(fresh_writes_then_gas(HELD))).build(); + let committed = CommittedStates::install(&mut state); + let mut executor = + executor_with_env(&mut state, ctx(), env_with_gas_limit(block_gas_limit)); + executor.apply_pre_execution_changes().expect("the budget holds sixteen fresh writes"); + assert_eq!(executor.evm().ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT); + let states = committed.states(); + let stored = &states[0][&HISTORY_STORAGE_ADDRESS].storage; + assert_eq!(stored.len(), usize::from(HELD) + 1, "in a block of {block_gas_limit}"); + stored[&U256::from(HELD)].present_value() + }); + assert_eq!(gas_left[0], gas_left[2], "a 1M block runs the call as a 250M block does"); + assert_eq!(gas_left[1], gas_left[2], "and so does a 30M block"); + + // The slot count is sized at Satin's own price; other byte prices move the budget's edge. + if !mega_evm::active_satin_prices().is_constants() { + return; + } + assert!(u64::from(SLOTS) * SLOT_STATE_GAS > PRE_BLOCK_CALL_GAS_LIMIT); + for block_gas_limit in [30_000_000, 250_000_000] { + let (calls, started) = + start_block(database(fresh_writes(SLOTS)), env_with_gas_limit(block_gas_limit)); + let err = started.expect_err("no block's budget holds 400 fresh slots"); + assert!( + matches!( + &err, + BlockExecutionError::Validation(BlockValidationError::BlockHashContractCall { + message + }) if message.contains("OutOfGas") + ), + "{err}" + ); + assert!(calls.is_empty(), "{calls:?}"); + } } /// Starts a block at [`BLOCK_NUMBER`] over `db`. @@ -531,28 +552,18 @@ fn test_a_database_error_in_the_beacon_root_call_is_internal() { } /// What the block commits for a pre-block call is the state op-revm's own system call produces -/// for it: the same call from the same state, on the same configuration — the split -/// switched on — and the same pre-block budget. The contract stores the regular gas it had, which -/// is 30M of the 250M budget, and the word it was called with. +/// for it: the same call from the same state, on the same configuration, with the same split of +/// its gas ([`op_reference`](crate::op_reference)) and the same pre-block budget. The contract +/// stores the regular gas it had, which is 30M of the budget, and the word it was called with. #[test] fn test_a_pre_block_call_commits_the_state_op_revm_produces() { - use op_revm::{handler::OpHandler, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; + use crate::op_reference::{self, OpContext}; + use op_revm::{OpEvm, OpSpecId}; use revm::{ bytecode::opcode::{GAS, PUSH0, PUSH1, STOP}, - context::{result::EVMError, BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, TxEnv}, - handler::{EthFrame, ExecuteEvm, Handler, SystemCallTx}, + context::ContextTr, inspector::NoOpInspector, - interpreter::interpreter::EthInterpreter, - Journal, }; - type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, - >; let code = BytecodeBuilder::default() .append_many([GAS, PUSH0, SSTORE]) @@ -569,24 +580,22 @@ fn test_a_pre_block_call_commits_the_state_op_revm_produces() { let delivered = committed.states().into_iter().next().expect("a first step"); assert!(delivered.contains_key(&HISTORY_STORAGE_ADDRESS), "the block hashes call is first"); let (cfg, block) = (executor.evm().ctx().cfg().clone(), executor.evm().ctx().block().clone()); - assert!(cfg.system_call_state_gas_margin_in_reservoir); drop(executor); let mut op = OpEvm::new( OpContext::new(db, OpSpecId::KARST).with_cfg(cfg).with_block(block), NoOpInspector, ); - let mut tx = OpTransaction::::new_system_tx_with_caller( + let outcome = op_reference::system_call( + &mut op, mega_evm::SYSTEM_ADDRESS, HISTORY_STORAGE_ADDRESS, PARENT_HASH.0.into(), - ); - tx.base.gas_limit = pre_block_call_gas_limit(250_000_000); - op.0.ctx.set_tx(tx); - let result: Result<_, EVMError> = - OpHandler::<_, _, EthFrame>::new().run_system_call(&mut op); - assert!(result.expect("op-revm runs the call").is_success()); - let expected = op.finalize(); + PRE_BLOCK_CALL_GAS_LIMIT, + ) + .expect("op-revm runs the call"); + assert!(outcome.result.is_success()); + let expected = outcome.result_and_state.state; assert_eq!(delivered, expected, "the block commits op-revm's state"); let stored = &delivered[&HISTORY_STORAGE_ADDRESS].storage; diff --git a/crates/mega-evm/tests/block/factory.rs b/crates/mega-evm/tests/block/factory.rs index 0a2aa1ddc..d09d03ecf 100644 --- a/crates/mega-evm/tests/block/factory.rs +++ b/crates/mega-evm/tests/block/factory.rs @@ -15,7 +15,7 @@ use alloy_primitives::U256; use alloy_sol_types::SolError; use mega_evm::{ test_utils::{BytecodeBuilder, GasInspector}, - DeclaredObserver, EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, + EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory, MegaLimitExceeded, MegaSpecId, ProtocolLimits, }; use revm::{context::result::ExecutionResult, database::State}; @@ -56,9 +56,9 @@ fn test_trait_path_applies_the_specs_runtime_limits() { assert_eq!(executor.protocol_limits(), &limits()); } -/// The two routes to an executor install the same limits, so neither is a way around them. +/// The routes to an executor install the same limits, so neither is a way around them. #[test] -fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { +fn test_inspector_and_plain_paths_apply_same_runtime_limits() { let trait_path = { let mut state = common::state(); let factory = common::factory(); @@ -73,12 +73,12 @@ fn test_trusted_inspector_and_trait_paths_apply_same_runtime_limits() { let inspector_path = { let mut state = common::state(); let factory = common::factory(); - let executor = factory.create_executor_with_trusted_inspector( + let evm = factory.evm_factory().create_evm_with_inspector( &mut state, common::evm_env(), - common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), + GasInspector::new(), ); + let executor = factory.create_executor(evm, common::unlimited_ctx()); *executor.evm().tx_runtime_limits() }; @@ -151,16 +151,20 @@ fn test_direct_construction_stops_a_transaction_over_the_blocks_data_size_limit( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: DATA_SIZE_LIMIT, - used: mega_evm::TX_BODY_SIZE + 2 * 40, - frame_local: false, - }) + limit: DATA_SIZE_LIMIT - mega_evm::TX_BODY_SIZE, + used: 2 * 40, + frame_local: true, + }), + "the transaction's own frame crosses its budget, what the body leaves of the limit" ); match &outcome.result { ExecutionResult::Revert { output, .. } => assert_eq!( output.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } - .abi_encode(), + MegaLimitExceeded { + kind: LimitKind::DataSize.as_u8(), + limit: DATA_SIZE_LIMIT - mega_evm::TX_BODY_SIZE, + } + .abi_encode(), "the stop's revert data" ), other => panic!("expected a revert-class stop, got {other:?}"), diff --git a/crates/mega-evm/tests/block/inspector.rs b/crates/mega-evm/tests/block/inspector.rs index 82a3430ca..f34dd1331 100644 --- a/crates/mega-evm/tests/block/inspector.rs +++ b/crates/mega-evm/tests/block/inspector.rs @@ -1,5 +1,5 @@ -//! The admission gate: which inspectors reach block execution, and what a declared observer sees -//! of a block's phases. +//! Inspectors in block execution: any inspector reaches a block, and what an observer sees of its +//! phases. use alloy_consensus::transaction::Recovered; use alloy_eips::{ @@ -8,21 +8,21 @@ use alloy_eips::{ }; use alloy_evm::{ block::{BlockExecutor, BlockExecutorFactory}, - Evm, EvmFactory, FromRecoveredTx, + EvmFactory, FromRecoveredTx, }; use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ - test_utils::{BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase}, - transaction_body_bytes, BlockLimits, DeclaredObserver, LimitUsage, MegaBlockExecutionCtx, - MegaBlockExecutionError, MegaContext, MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, - MegaTxEnvelope, + test_utils::{ + BytecodeBuilder, CommittedStates, GasInspector, MemoryDatabase, ReadOnlyObserver, + }, + transaction_body_bytes, BlockLimits, LimitUsage, MegaBlockExecutionCtx, MegaContext, + MegaEvmFactory, MegaTransaction, MegaTransactionOutcome, MegaTxEnvelope, }; use revm::{ bytecode::opcode::{ADD, POP, PUSH0, SLOAD, SSTORE}, context::{ContextTr, JournalTr}, database::State, handler::FrameResult, - inspector::NoOpInspector, interpreter::{ CallInputs, CallOutcome, FrameInput, Gas, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, @@ -33,175 +33,30 @@ use std::cell::Cell; use crate::common::{self, empty_call_gas, system_tx, user_tx}; -/// A declared observer reaches a block: its type says it writes nothing back, so what the block -/// executes is what the chain executes. +/// An inspector reaches a block: the engine refuses none, and a node decides which inspectors run +/// on block production. #[test] -fn test_a_declared_observer_reaches_block_execution() { +fn test_an_inspector_reaches_block_execution() { let mut state = common::state(); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + GasInspector::new(), + ), common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), ); assert!(executor.evm().is_inspecting(), "the inspector runs"); - assert!(!executor.evm().has_rewriting_inspector(), "and is admitted"); - executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + executor.apply_pre_execution_changes().expect("the pre-block calls run"); executor.execute_transaction(&user_tx(0, empty_call_gas())).expect("the transaction executes"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 1); } -/// An inspector that arrived without the declaration does not: block execution refuses it before -/// the block's first call. The refusal is an internal error, not a verdict on the block: the -/// inspector is the node's own choice and says nothing about the block, so a validator that runs -/// one must not mark a valid block invalid. -#[test] -fn test_a_rewriting_inspector_cannot_reach_block_execution() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - assert!(evm.has_rewriting_inspector()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - let err = executor - .apply_pre_execution_changes() - .expect_err("an undeclared inspector has no route to a block"); - assert!( - format!("{err}").contains("does not admit an inspector that may rewrite execution"), - "{err}" - ); - assert!(err.as_validation().is_none(), "not a verdict on the block: {err:?}"); - assert_eq!( - err.as_internal().and_then(|error| error.downcast_other::()), - Some(&MegaBlockExecutionError::RewritingInspector), - "an internal error of the node: {err:?}" - ); -} - -/// An EVM with no inspector at all is admitted, which is the ordinary case. -#[test] -fn test_a_block_without_an_inspector_is_admitted() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert!(!executor.evm().is_inspecting()); - executor.apply_pre_execution_changes().expect("nothing to refuse"); -} - -/// The gate keys on what runs, not on what is held: an inspector that is disabled does not -/// rewrite anything, and the block is admitted. -#[test] -fn test_a_disabled_inspector_is_admitted() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(NoOpInspector); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); -} - -/// The gate is checked at every entry point, not once: an inspector enabled after the block was -/// set up is refused by the transaction that would run under it, by the checked commit and by the -/// end of the block. -#[test] -fn test_enabling_a_rewriting_inspector_after_the_block_started_is_refused() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - - // The one transaction that ran before the inspector was enabled is admitted. - let outcome = executor - .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) - .expect("the block is still clean"); - - executor.evm_mut().set_inspector_enabled(true); - - assert!( - is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), - "no transaction runs" - ); - assert!(is_refused(executor.commit_transaction_outcome(outcome)), "nothing commits"); - assert!(executor.receipts().is_empty(), "the block packed nothing"); - assert!(is_refused(executor.finish_with_counters()), "and the block does not finish"); -} - -/// alloy-evm's `commit_transaction` cannot fail and checks nothing: it commits the outcome the -/// last execution produced, which passed the gate before it ran, so an inspector enabled since -/// cannot reach it. The next execution is the one the gate refuses. -#[test] -fn test_the_unchecked_commit_commits_what_ran_under_the_gate() { - let mut state = common::state(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - evm.set_inspector_enabled(false); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - let outcome = executor - .execute_transaction_without_commit(&user_tx(0, empty_call_gas())) - .expect("the block is still clean"); - - executor.evm_mut().set_inspector_enabled(true); - - executor.commit_transaction(outcome); - assert_eq!(executor.receipts().len(), 1, "the outcome that ran under the gate is committed"); - assert!( - is_refused(executor.execute_transaction(&user_tx(1, empty_call_gas()))), - "nothing runs after" - ); - assert_eq!(executor.receipts().len(), 1); -} - -/// The gate holds for a caller that never runs the block's pre-execution changes: the check is on -/// the path that runs code, not only on the block's setup. -#[test] -fn test_a_rewriting_inspector_is_refused_without_the_pre_execution_changes() { - let mut state = common::state(); - let factory = common::factory(); - let evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(GasInspector::new()); - - let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - - assert!( - is_refused(executor.execute_transaction_without_commit(&user_tx(0, empty_call_gas()))), - "skipping the setup is not a way past the gate" - ); - assert!(is_refused(executor.finish_with_counters()), "and neither is finishing the block"); -} - -/// Whether block execution refused the call because of the inspector. -fn is_refused(result: Result) -> bool { - match result { - Ok(_) => false, - Err(err) => format!("{err}").contains("does not admit an inspector that may rewrite"), - } -} - /// Counts the frames an inspector sees start and the instructions it sees run. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct Seen { @@ -243,23 +98,25 @@ fn recording_ctx() -> MegaBlockExecutionCtx { ) } -/// A declared observer sees each phase of a block as the inspector contract says: nothing of the +/// An observer sees each phase of a block as the inspector contract says: nothing of the /// pre-block calls, which run code of their own, the frames of a system transaction and of a user /// one, and nothing of the block's end, after which the EVM hands the inspector back with what it /// saw. #[test] -fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() { +fn test_an_observer_sees_the_transactions_of_a_block_and_nothing_else() { let mut state = state_with_code(); let committed = CommittedStates::install(&mut state); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + ReadOnlyObserver::new(Seen::default()), + ), recording_ctx(), - DeclaredObserver::new(Seen::default()), ); - executor.apply_pre_execution_changes().expect("a declared observer is admitted"); + executor.apply_pre_execution_changes().expect("the pre-block calls run"); let states = committed.states(); assert_eq!( common::eip_calls(&states), @@ -292,25 +149,7 @@ fn test_a_declared_observer_sees_the_transactions_of_a_block_and_nothing_else() assert_eq!(evm.inspector().0, after_user, "the block's end ran no code"); } -/// A rewriting inspector is refused at a system transaction as at a user one: the gate is the -/// entry point's, and the system transaction does not run. -#[test] -fn test_a_rewriting_inspector_is_refused_at_a_system_transaction() { - let mut state = state_with_code(); - let factory = common::factory(); - let mut evm = MegaEvmFactory::new() - .create_evm(&mut state, common::evm_env()) - .with_inspector(Seen::default()); - evm.set_inspector_enabled(false); - let mut executor = factory.create_executor(evm, recording_ctx()); - executor.apply_pre_execution_changes().expect("a disabled inspector rewrites nothing"); - - executor.evm_mut().set_inspector_enabled(true); - assert!(is_refused(executor.run_transaction(&system_tx())), "the system transaction"); - assert_eq!(*executor.evm().inspector(), Seen::default(), "ran nothing"); -} - -/// An inspector works with the block executor: declared an observer, it reaches block execution and +/// An inspector works with the block executor: it /// sees the transaction's instructions — `CONTRACT` loads a slot, adds one and stores it — each /// taking gas or none, and the block finishes with the transaction's receipt. #[test] @@ -326,11 +165,13 @@ fn test_inspector_works_with_block_executor() { db.set_account_code(common::CONTRACT, increment); let mut state = State::builder().with_database(db).build(); let factory = common::factory(); - let mut executor = factory.create_executor_with_trusted_inspector( - &mut state, - common::evm_env(), + let mut executor = factory.create_executor( + MegaEvmFactory::new().create_evm_with_inspector( + &mut state, + common::evm_env(), + ReadOnlyObserver::new(GasInspector::new()), + ), common::unlimited_ctx(), - DeclaredObserver::new(GasInspector::new()), ); executor.execute_transaction(&user_tx(0, 1_000_000)).expect("the transaction executes"); @@ -396,10 +237,9 @@ where } /// An inspector that answers the calls below the transaction's own frame rewrites what execution -/// produces, so block execution refuses it before the transaction runs. On the EVM, the route a -/// tool takes, its answer stands in for the frame: an empty lane keeps the lanes aligned with the -/// frames, the answered call ends as every call does, and the transaction settles as one whose -/// nested call never ran. +/// produces. Block execution does not refuse it, and on the EVM alike its answer stands in for the +/// frame: it settles with the share and the start charge the frame was given, the answered call +/// ends as every call does, and the transaction settles as one whose nested call never ran. #[test] fn test_inspector_early_return_with_additional_limits() { let caller = BytecodeBuilder::default().call(CONTRACT_B, U256::ZERO).append(POP).stop().build(); @@ -417,8 +257,9 @@ fn test_inspector_early_return_with_additional_limits() { .with_inspector(SkipNestedCallInspector::default()); let factory = common::factory(); let mut executor = factory.create_executor(evm, common::unlimited_ctx()); - assert!(is_refused(executor.execute_transaction(&tx)), "no route to a block"); - assert_eq!(executor.evm().inspector().calls_intercepted.get(), 0, "nothing ran"); + let in_block = executor.run_transaction(&tx).expect("block execution admits the inspector"); + assert!(in_block.inner.result.is_success(), "{:?}", in_block.inner.result); + assert_eq!(executor.evm().inspector().calls_intercepted.get(), 1, "the nested call answered"); let mut state = database(); let mut inspector = SkipNestedCallInspector::default(); @@ -427,6 +268,7 @@ fn test_inspector_early_return_with_additional_limits() { assert_eq!(inspector.calls_intercepted.get(), 1, "the nested call was answered"); assert_eq!(inspector.call_ends.get(), 2, "and both calls ended"); let body = transaction_body_bytes(&tx); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.gas.state, 0); + assert_eq!(in_block.inner.usage, outcome.usage, "a block and a tool settle it alike"); } diff --git a/crates/mega-evm/tests/block/limits.rs b/crates/mega-evm/tests/block/limits.rs index c29782cec..d3b942e2a 100644 --- a/crates/mega-evm/tests/block/limits.rs +++ b/crates/mega-evm/tests/block/limits.rs @@ -122,28 +122,127 @@ fn state_with_incrementing_contract( revm::database::State::builder().with_database(db).build() } -/// The block's KV count is the write records its transactions kept, summed, and no limit refuses a -/// transaction on it: three transactions that keep fifty records each are all packed. -#[test] -fn test_the_block_reports_its_kv_count_and_refuses_nothing_on_it() { - let mut state = state_with_incrementing_contract(50); - // Room in the block's gas for every transaction whatever fifty slots cost. +/// A contract that writes the fresh slots `from..from + count`, for a transaction that keeps that +/// many new slots and records. +fn fresh_writer(from: u64, count: u64) -> Bytes { + (from..from + count) + .fold(BytecodeBuilder::default(), |code, slot| code.sstore(U256::from(slot), U256::from(1))) + .stop() + .build() +} + +/// A second contract, which a deposit calls. +const WRITER: Address = address!("0x1000000000000000000000000000000000000009"); + +/// A block over `state` with room in its gas for every transaction, whatever the slots cost, +/// packed under `policy`. +fn counting_executor( + state: &mut revm::database::State, + policy: BlockLimits, +) -> common::TestExecutor<'_> { let mut env = common::evm_env(); env.block_env.gas_limit = 10_000_000_000; + common::executor_with_env(state, common::block_ctx(policy), env) +} + +/// The block's KV count is the write records its transactions kept, summed, and its KV-update +/// budget packs the transaction that reaches it and refuses the next one before it runs: under a +/// builder's cap of 100, two transactions that keep fifty records each are packed and a third is +/// refused. A deposit is not refused, and counts. +#[test] +fn test_the_block_kv_budget_packs_the_transaction_that_reaches_it() { + let mut state = state_with_incrementing_contract(50); + state.database.set_account_code(WRITER, fresh_writer(1, 3)); let mut executor = - common::executor_with_env(&mut state, common::block_ctx(BlockLimits::no_limits()), env); + counting_executor(&mut state, BlockLimits::no_limits().with_block_kv_update_limit(100)); executor.apply_pre_execution_changes().expect("the block starts"); - for nonce in 0..3 { + for nonce in 0..2 { executor .execute_transaction(&user_tx(nonce, incrementing_gas(50))) .unwrap_or_else(|err| panic!("transaction {nonce} is packed: {err}")); } - assert_eq!(executor.limiter().usage.write_records, 150); + assert_eq!(executor.limiter().usage.write_records, 100, "the budget is reached"); + let err = executor + .execute_transaction(&user_tx(2, incrementing_gas(50))) + .expect_err("the block has no KV updates left"); + assert!(format!("{err}").contains("Block KV update limit reached"), "{err}"); + + let deposit = common::deposit_tx_to(WRITER, Bytes::new(), incrementing_gas(3)); + executor.execute_transaction(&deposit).expect("no packing budget refuses a deposit"); + assert_eq!(executor.limiter().usage.write_records, 103, "and it counts"); let (_, result) = executor.finish_with_counters().expect("the block finishes"); assert_eq!(result.receipts().len(), 3); - assert_eq!(result.usage.write_records, 150, "the block reports its KV count"); + assert_eq!(result.usage.write_records, 103, "the block reports its KV count"); +} + +/// The block's state growth is the new accounts and slots its transactions kept, and its +/// protocol budget is 1,000: a transaction that keeps 1,000 fresh slots reaches it and is packed, +/// the next ordinary transaction is refused before it runs, and a deposit after it is not, counts +/// its new slots, and leaves the block as full for the ordinary transactions that follow. The +/// block's gas limit, ten billion here, does not stand in for the budget. +#[test] +fn test_the_block_state_growth_budget_is_the_protocols_1000() { + assert_eq!(mega_evm::constants::BLOCK_STATE_GROWTH_LIMIT, 1_000); + let mut state = state_with_incrementing_contract(1_000); + state.database.set_account_code(WRITER, fresh_writer(1, 3)); + let mut executor = counting_executor(&mut state, BlockLimits::no_limits()); + executor.apply_pre_execution_changes().expect("the block starts"); + + // Each increment's regular gas, its cold load and its write, on top of what the helper gives. + let gas = incrementing_gas(1_000) + 1_000 * 25_000; + let outcome = executor + .run_transaction(&user_tx(0, gas)) + .expect("the transaction that reaches the budget is packed"); + assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); + executor.commit_transaction_outcome(outcome).expect("and committed"); + assert_eq!(executor.limiter().usage.state_growth, 1_000); + let ordinary = || user_tx(1, incrementing_gas(1)); + let err = executor.execute_transaction(&ordinary()).expect_err("the budget is reached"); + assert!(format!("{err}").contains("Block state growth limit reached"), "{err}"); + + let deposit = common::deposit_tx_to(WRITER, Bytes::new(), incrementing_gas(3)); + executor.execute_transaction(&deposit).expect("no packing budget refuses a deposit"); + assert_eq!(executor.limiter().usage.state_growth, 1_003, "the deposit's three new slots"); + let err = executor.execute_transaction(&ordinary()).expect_err("the block is still full"); + assert!(format!("{err}").contains("Block state growth limit reached"), "{err}"); + + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 2); + assert_eq!(result.usage.state_growth, 1_003, "the block reports its state growth"); +} + +/// Where more than one packing budget is reached, the refusal names the first of data size, KV +/// updates and state growth; the transaction is refused whichever it names. +#[test] +fn test_a_block_full_on_several_budgets_names_them_in_order() { + let cases = [ + ( + BlockLimits::no_limits() + .with_block_txs_data_limit(1) + .with_block_kv_update_limit(1) + .with_block_state_growth_limit(1), + "Block transactions data limit reached", + ), + ( + BlockLimits::no_limits().with_block_kv_update_limit(1).with_block_state_growth_limit(1), + "Block KV update limit reached", + ), + (BlockLimits::no_limits().with_block_state_growth_limit(1), "Block state growth limit"), + ]; + for (policy, named) in cases { + let mut state = state_with_incrementing_contract(1); + let mut executor = counting_executor(&mut state, policy); + executor.apply_pre_execution_changes().expect("the block starts"); + executor + .execute_transaction(&user_tx(0, incrementing_gas(1))) + .expect("the first transaction reaches every budget the case sets"); + let err = executor + .execute_transaction(&user_tx(1, incrementing_gas(1))) + .expect_err("the block is full"); + assert!(format!("{err}").contains(named), "{named}: {err}"); + } } /// A transaction refused before it runs changes nothing: no receipt, and no state. @@ -597,3 +696,158 @@ fn test_commit_time_da_footprint_check_parallel_simulation() { assert_eq!(result.receipts().len(), 1, "only the transaction that fit was packed"); assert!(result.blob_gas_used <= budget, "the block stays within its footprint budget"); } + +/// A database error, fatal as a storage failure or not as a read an EIP-7928 block access list +/// does not cover. +#[derive(Debug)] +struct AuthorityReadError { + fatal: bool, +} + +impl core::fmt::Display for AuthorityReadError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "the authority's account cannot be read (fatal: {})", self.fatal) + } +} + +impl core::error::Error for AuthorityReadError {} + +impl revm::context::DBErrorMarker for AuthorityReadError { + fn is_fatal(&self) -> bool { + self.fatal + } +} + +/// A database that refuses to read one account, if it names one, with an error that is fatal or +/// not. +#[derive(Debug)] +struct RefusesAnAccount { + db: mega_evm::test_utils::MemoryDatabase, + refused: Option
, + fatal: bool, +} + +impl revm::Database for RefusesAnAccount { + type Error = AuthorityReadError; + + fn basic(&mut self, address: Address) -> Result, Self::Error> { + if self.refused == Some(address) { + return Err(AuthorityReadError { fatal: self.fatal }); + } + Ok(self.db.basic(address).expect("the memory database serves")) + } + + fn code_by_hash( + &mut self, + code_hash: alloy_primitives::B256, + ) -> Result { + Ok(self.db.code_by_hash(code_hash).expect("the memory database serves")) + } + + fn storage(&mut self, address: Address, index: U256) -> Result { + Ok(self.db.storage(address, index).expect("the memory database serves")) + } + + fn block_hash(&mut self, number: u64) -> Result { + Ok(self.db.block_hash(number).expect("the memory database serves")) + } +} + +/// An authorization list is simulated before the first frame when it may cross the transaction's +/// KV or state-growth limit, and a database error while it reads an authority gives the +/// transaction no outcome: the block executor reports it as an internal error when the database +/// declares it fatal, and refuses the block for any other, including when an earlier prefix +/// would already have crossed. Three new authorities under a state-growth limit of one: the first +/// two cross it, and the third cannot be read; served, the list is skipped and the transaction +/// included with the stop. A skipped list is not applied, so the simulation is the only read of +/// the third. +/// +/// revm's `State`, which a block runs on, declares every error of the database below it fatal and +/// only a read its EIP-7928 block access list does not cover not fatal, so a block shows the fatal +/// half. The other half is the engine's part of the same rule: it hands back the database's own +/// error, which the executor maps by its fatality (`BlockExecutionError::evm`). +#[test] +fn test_a_database_error_in_the_authorization_list_simulation_is_internal_only_when_fatal() { + use alloy_consensus::{SignableTransaction, TxEip7702}; + use alloy_eips::eip7702::{Authorization, SignedAuthorization}; + use alloy_evm::{ + block::{BlockExecutionError, BlockValidationError}, + Evm, EvmFactory, + }; + use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; + use alloy_primitives::{Signature, B256}; + use mega_evm::{LimitCheck, LimitKind, MegaBlockExecutor, MegaEvmFactory}; + + let authorization = |delegate: Address| { + let word = U256::from_be_bytes([0x22; 32]); + let auth = Authorization { chain_id: U256::ZERO, address: delegate, nonce: 0 }; + let signed = SignedAuthorization::new_unchecked(auth, 0, word, word); + let authority = signed.recover_authority().expect("a Nick's-Method signature recovers"); + (signed, authority) + }; + let (first, _) = authorization(CONTRACT); + let (second, _) = authorization(CALLER3); + let (third, refused) = authorization(CALLER2); + let tx = TxEip7702 { + chain_id: common::CHAIN_ID, + nonce: 0, + gas_limit: 1_000_000 + common::body_history(0) + 4 * common::new_account_state_gas(), + max_fee_per_gas: 0, + max_priority_fee_per_gas: 0, + to: CONTRACT, + value: U256::ZERO, + access_list: Default::default(), + authorization_list: vec![first, second, third], + input: Bytes::new(), + }; + let tx = Recovered::new_unchecked( + MegaTxEnvelope::Eip7702(tx.into_signed(Signature::test_signature())), + CALLER, + ); + let limits = common::loosest() + .with_tx_runtime_limits(common::loosest_tx().with_tx_state_growth_limit(1)); + let database = |refused: Option
, fatal: bool| RefusesAnAccount { + db: common::database(), + refused, + fatal, + }; + let in_a_block = |db: RefusesAnAccount| { + let mut state = revm::database::State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, common::evm_env()); + let mut executor = MegaBlockExecutor::new( + evm, + common::unlimited_ctx(), + common::chain_spec(), + OpAlloyReceiptBuilder::default(), + ) + .with_protocol_limits(limits); + executor.apply_pre_execution_changes().expect("the block starts"); + executor.execute_transaction_without_commit(&tx).map(|result| result.inner.limit_exceeded) + }; + + let stop = in_a_block(database(None, false)).expect("served, the transaction is included"); + assert!( + matches!(stop, Some(LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, .. })), + "the list is skipped and the first frame stopped: {stop:?}" + ); + let err = in_a_block(database(Some(refused), true)).expect_err("the read fails"); + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + assert!(err.to_string().contains("cannot be read"), "{err}"); + + for fatal in [true, false] { + let mut evm = + MegaEvmFactory::new().create_evm(database(Some(refused), fatal), common::evm_env()); + evm.set_tx_runtime_limits(limits.tx_runtime_limits); + let err = evm.transact(&tx).expect_err("the read fails"); + let err = BlockExecutionError::evm(err, B256::ZERO); + if fatal { + assert!(matches!(err, BlockExecutionError::Internal(_)), "{err:?}"); + } else { + assert!( + matches!(err, BlockExecutionError::Validation(BlockValidationError::EVM { .. })), + "{err:?}" + ); + } + assert!(err.to_string().contains("cannot be read"), "{err}"); + } +} diff --git a/crates/mega-evm/tests/block/main.rs b/crates/mega-evm/tests/block/main.rs index f4d0c9747..829bfd4da 100644 --- a/crates/mega-evm/tests/block/main.rs +++ b/crates/mega-evm/tests/block/main.rs @@ -22,6 +22,11 @@ mod salt; mod schedule; mod sequencer_registry; mod sequences; +// This target compares a pre-block call alone: the reference's transactions and the reservoir it +// reads are the `satin` target's. +#[allow(dead_code)] +#[path = "../shared/op_reference.rs"] +mod op_reference; #[path = "../shared/snapshot.rs"] mod snapshot; mod stale; diff --git a/crates/mega-evm/tests/block/predeploys.rs b/crates/mega-evm/tests/block/predeploys.rs index 9986d2c2d..1a893f0f4 100644 --- a/crates/mega-evm/tests/block/predeploys.rs +++ b/crates/mega-evm/tests/block/predeploys.rs @@ -247,13 +247,13 @@ fn test_a_create2_round_trip_through_the_factory() { input.extend_from_slice(&init); let expected = CREATE2_FACTORY_ADDRESS.create2_from_code(salt, init.as_ref()); // 1,000,000 of regular gas on top of the account the creation adds, the history of the body, - // and 64 times the history of the creation's two write records, at the byte prices in effect: - // the factory forwards all but a 64th of its gas to the creation and pays the records from - // the 64th it keeps. + // and 50 times the history of the creation's two write records, at the byte prices in effect: + // the factory forwards all but 2 per cent of its gas to the creation and pays the records from + // the fiftieth it keeps. let gas_limit = 1_000_000 + common::new_account_state_gas() + common::body_history(input.len() as u64) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price"); let outcome = executor .execute_transaction_without_commit(&recovered(tx( diff --git a/crates/mega-evm/tests/block/receipt_goldens.rs b/crates/mega-evm/tests/block/receipt_goldens.rs index db9727e75..a7e811510 100644 --- a/crates/mega-evm/tests/block/receipt_goldens.rs +++ b/crates/mega-evm/tests/block/receipt_goldens.rs @@ -211,17 +211,20 @@ fn test_a_blocks_receipts_pin_their_bytes_bloom_and_cumulative_gas() { outcome.inner.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: DATA_SIZE_LIMIT, - used: stop_body + STOP_START, - frame_local: false, + limit: DATA_SIZE_LIMIT - stop_body, + used: STOP_START, + frame_local: true, }), - "the first frame's start crossed the data-size limit", + "the first frame's start crossed its budget, what the body leaves of the limit", ); let output = stop.clone().expect("the stop reverts"); assert_eq!( output.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: DATA_SIZE_LIMIT } - .abi_encode(), + MegaLimitExceeded { + kind: LimitKind::DataSize.as_u8(), + limit: DATA_SIZE_LIMIT - stop_body, + } + .abi_encode(), "the stop's revert data is MegaLimitExceeded", ); } else { diff --git a/crates/mega-evm/tests/block/system_tx_budgets.rs b/crates/mega-evm/tests/block/system_tx_budgets.rs index c647fc124..46e30fe77 100644 --- a/crates/mega-evm/tests/block/system_tx_budgets.rs +++ b/crates/mega-evm/tests/block/system_tx_budgets.rs @@ -1,6 +1,6 @@ -//! A Mega System Transaction against the block's packing budgets: like a deposit, no data-size -//! budget and no building policy refuses it, and it counts towards both; the header's gas limit and -//! the data-availability footprint still hold it. +//! A Mega System Transaction against the block's packing budgets: like a deposit, no data-size, +//! KV-update or state-growth budget and no building policy refuses it, and it counts towards them; +//! the header's gas limit and the data-availability footprint still hold it. use alloy_consensus::transaction::Recovered; use alloy_eips::Encodable2718; @@ -41,33 +41,40 @@ fn tightest_policy() -> BlockLimits { .with_tx_da_size_limit(0) .with_block_da_size_limit(0) .with_block_txs_data_limit(0) + .with_block_kv_update_limit(0) + .with_block_state_growth_limit(0) } -/// A block whose data-size budget is spent before it starts refuses an ordinary transaction and -/// admits a Mega System Transaction, which counts towards the budget all the same. +/// A block whose data-size, KV-update or state-growth budget is spent before it starts refuses an +/// ordinary transaction and admits a Mega System Transaction, which counts towards each budget all +/// the same: its body's bytes, and the system address's account, which it creates. #[test] -fn test_a_mega_system_transaction_is_admitted_at_a_full_data_size_budget() { - let mut state = common::state(); - let mut executor = executor( - &mut state, - common::block_ctx(BlockLimits::no_limits().with_block_txs_data_limit(0)), - ); - executor.apply_pre_execution_changes().expect("the block starts"); - - executor - .execute_transaction(&user_tx(0, empty_call_gas())) - .expect_err("an ordinary transaction finds the budget spent"); - - let outcome = - executor.run_transaction(&system_tx()).expect("the system transaction is admitted"); - assert!(outcome.inner.result.is_success(), "{:?}", outcome.inner.result); - let data_size = outcome.inner.usage.data_size; - assert!(data_size > 0); - executor.commit_transaction_outcome(outcome).expect("and committed"); - - assert_eq!(executor.limiter().usage.data_size, data_size, "it counts towards the budget"); - let (_, result) = executor.finish_with_counters().expect("the block finishes"); - assert_eq!(result.receipts().len(), 1); +fn test_a_mega_system_transaction_is_admitted_at_a_full_budget() { + for (name, policy) in [ + ("data size", BlockLimits::no_limits().with_block_txs_data_limit(0)), + ("KV updates", BlockLimits::no_limits().with_block_kv_update_limit(0)), + ("state growth", BlockLimits::no_limits().with_block_state_growth_limit(0)), + ] { + let mut state = common::state(); + let mut executor = executor(&mut state, common::block_ctx(policy)); + executor.apply_pre_execution_changes().expect("the block starts"); + + executor + .execute_transaction(&user_tx(0, empty_call_gas())) + .expect_err("an ordinary transaction finds the budget spent"); + + let outcome = + executor.run_transaction(&system_tx()).expect("the system transaction is admitted"); + assert!(outcome.inner.result.is_success(), "{name}: {:?}", outcome.inner.result); + let usage = outcome.inner.usage; + assert!(usage.data_size > 0, "{name}"); + assert_eq!(usage.state_growth, 1, "{name}: the system address's new account"); + executor.commit_transaction_outcome(outcome).expect("and committed"); + + assert_eq!(executor.limiter().usage, usage, "{name}: it counts towards the budgets"); + let (_, result) = executor.finish_with_counters().expect("the block finishes"); + assert_eq!(result.receipts().len(), 1, "{name}"); + } } /// A building policy at its tightest refuses an ordinary transaction and no system transaction: diff --git a/crates/mega-evm/tests/block/transfer_logs.rs b/crates/mega-evm/tests/block/transfer_logs.rs index 1276242de..503366e45 100644 --- a/crates/mega-evm/tests/block/transfer_logs.rs +++ b/crates/mega-evm/tests/block/transfer_logs.rs @@ -59,16 +59,16 @@ fn state() -> State { } /// A gas limit for any transaction here: 1,000,000 of regular gas on top of the state of two new -/// accounts and a fresh slot, a kilobyte of history beyond the body, and 64 times the history of -/// two write records, at the byte prices in effect: [`FORWARDER`] forwards all but a 64th of its -/// gas with the value it passes on, and pays the records of the frame it starts from the 64th it -/// keeps. +/// accounts and a fresh slot, a kilobyte of history beyond the body, and 50 times the history of +/// two write records, at the byte prices in effect: [`FORWARDER`] forwards all but 2 per cent of +/// its gas with the value it passes on, and pays the records of the frame it starts from the +/// fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + 2 * common::new_account_state_gas() + common::slot_state_gas() + common::body_history(1_000) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price") } /// A legacy transaction from `signer` with `value`. @@ -138,8 +138,8 @@ fn test_a_blocks_receipts_carry_its_transfer_logs_in_execution_order() { vec![transfer_log(DESTRUCTOR, PAYEE, U256::from(DESTRUCTOR_BALANCE))], ]; // The records each keeps: the recipient; the forwarder and the payee; the created account; - // the destruction's beneficiary. - let records = [1, 2, 1, 1]; + // the destructed account, whose balance the destruction clears, and its beneficiary. + let records = [1, 2, 1, 2]; let mut data_size = 0; let mut history_bytes = 0; @@ -261,14 +261,14 @@ fn test_a_value_left_on_a_destroyed_account_is_burned_without_a_log() { executor.apply_pre_execution_changes().expect("the block starts"); // 1,000,000 of regular gas on top of what the byte prices in effect charge: the state of up // to three new accounts — the child, the payee, the child again for the late value — the - // history of the body, and 64 times the history of the creation's two start records, because - // the factory forwards all but a 64th of its gas and pays a start's records from the 64th it - // keeps. The creation returns its unused gas before the late value call, whose single record - // costs less: the factory's is already written in this frame. + // history of the body, and 50 times the history of the creation's two start records, because + // the factory forwards all but 2 per cent of its gas and pays a start's records from the + // fiftieth it keeps. The creation returns its unused gas before the late value call, whose + // single record costs less: the factory's is already written in this frame. let gas_limit = 1_000_000 + 3 * common::new_account_state_gas() + common::body_history(0) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price"); + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price"); let tx = common::legacy_from( CALLER, 0, diff --git a/crates/mega-evm/tests/block/witness/state.rs b/crates/mega-evm/tests/block/witness/state.rs index f8300bc5c..f4ad5185a 100644 --- a/crates/mega-evm/tests/block/witness/state.rs +++ b/crates/mega-evm/tests/block/witness/state.rs @@ -58,16 +58,16 @@ fn deploying(runtime: &[u8]) -> Bytes { /// A gas limit with room for a creation and two new accounts at the byte prices in effect: /// 1,000,000 of regular gas on top of the state of two new accounts, a fresh slot and a short -/// runtime's deposit, a kilobyte of history beyond the body, and 64 times the history of two -/// write records — a contract that creates, or a factory that forwards all but a 64th of its gas -/// to the creation, pays the records of the frame it starts from the 64th it keeps. +/// runtime's deposit, a kilobyte of history beyond the body, and 50 times the history of two +/// write records — a contract that creates, or a factory that forwards all but 2 per cent of its +/// gas to the creation, pays the records of the frame it starts from the fiftieth it keeps. pub(super) fn creation_gas() -> u64 { 1_000_000 + 2 * common::new_account_state_gas() + common::slot_state_gas() + 64 * mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()) + common::body_history(1_000) + - 64 * mega_evm::write_record_history_gas(2).expect("two records have a price") + 50 * mega_evm::write_record_history_gas(2).expect("two records have a price") } /// An EIP-7702 call to an authority delegating to the slot writer: the authority's absent account diff --git a/crates/mega-evm/tests/block/witness/stops.rs b/crates/mega-evm/tests/block/witness/stops.rs index 388e1b066..00f5d952d 100644 --- a/crates/mega-evm/tests/block/witness/stops.rs +++ b/crates/mega-evm/tests/block/witness/stops.rs @@ -1,7 +1,7 @@ //! Every stop class through the harness: a transaction stopped by the data-size and compute //! limits, a crossing at a precompile's price, which its caller catches, a crossing in an answer, -//! and a block budget refusing a later transaction. A stop is what the block records, so a -//! validator must produce the same stop from the same witness. +//! a block budget refusing a later transaction, and an authorization list a limit skips. A stop is +//! what the block records, so a validator must produce the same stop from the same witness. use alloy_primitives::{Bytes, U256}; use alloy_sol_types::SolCall; @@ -20,7 +20,8 @@ use revm::{ use super::{ basics::{slot, slot_writer}, - harness::{call, call_with_value, Case, Run}, + harness::{assert_differs, authorization, call, call_with_value, eip7702, Case, Oracle, Run}, + state::creation_gas, }; use crate::common::{self, loosest_tx, CALLER, CONTRACT}; @@ -195,3 +196,42 @@ fn test_a_stop_above_the_execution_cap_replays() { assert_stopped(run, 0, LimitKind::DataSize); assert!(run.tx(0).gas.reservoir_remaining > 0, "the reservoir came back"); } + +/// An authorization list the state-growth limit skips: two new authorities under a limit of one. +/// Before the first frame the engine loads both to decide the list would create two accounts, +/// applies none, and stops the first frame, so neither is written; the witness still holds both, +/// as accounts the chain does not have, and a validator decides the same skip from it. A witness +/// without one of them cannot replay the block. +#[test] +fn test_a_skipped_authorization_list_replays() { + let (first, first_authority) = authorization(CONTRACT, 0); + let (second, second_authority) = authorization(CALLER, 0); + assert_ne!(first_authority, second_authority); + let mut db = common::database(); + db.set_account_code(CONTRACT, slot_writer()); + let limits = + common::loosest().with_tx_runtime_limits(loosest_tx().with_tx_state_growth_limit(1)); + let case = Case::new("skipped authorization list", db).limits(limits).tx(eip7702( + 0, + CONTRACT, + slot(1), + vec![first, second], + creation_gas(), + )); + let recorded = case.record(); + let mut witness = case.channel_witness(&recorded); + assert_stopped(&recorded, 0, LimitKind::StateGrowth); + for authority in [first_authority, second_authority] { + assert_eq!(recorded.record.accounts.get(&authority), Some(&None), "the list loaded it"); + assert_eq!(witness.accounts.get(&authority), Some(&None), "the channel witness holds it"); + let state = &recorded.tx(0).state; + let written = state.get(&authority).is_some_and(|account| account.is_touched()); + assert!(!written, "a skipped list writes no authority"); + } + + witness.accounts.remove(&second_authority); + let short = case.replay(&witness, &recorded.included(), Oracle::Recorded); + assert_differs("skipped authorization list, one authority short", &recorded, &short); + + case.run(); +} diff --git a/crates/mega-evm/tests/fuzz/blocks.rs b/crates/mega-evm/tests/fuzz/blocks.rs index 5adf9a2b0..57605f97d 100644 --- a/crates/mega-evm/tests/fuzz/blocks.rs +++ b/crates/mega-evm/tests/fuzz/blocks.rs @@ -151,6 +151,12 @@ pub(crate) struct Budgets { pub(crate) data: Budget, /// The policy's cap on the same, which only tightens. pub(crate) policy_data: Budget, + /// The block's KV-update budget, in write records, and the policy's cap on it. + pub(crate) kv: Budget, + pub(crate) policy_kv: Budget, + /// The block's state-growth budget, in new accounts and slots, and the policy's cap on it. + pub(crate) growth: Budget, + pub(crate) policy_growth: Budget, /// The policy's cap on a transaction's declared gas. pub(crate) policy_tx_gas: Option, /// The policy's cap on a transaction's encoded size, in bytes. @@ -163,6 +169,8 @@ fn budgets() -> impl Strategy { ( budget(300..=600, 1_000..=5_000), budget(300..=600, 1_000..=5_000), + (budget(1..=3, 4..=12), budget(1..=3, 4..=12)), + (budget(1..=3, 4..=12), budget(1..=3, 4..=12)), proptest::option::weighted( 0.3, prop_oneof![Just(100_000u32), Just(1_000_000), Just(50_000_000)], @@ -170,13 +178,21 @@ fn budgets() -> impl Strategy { proptest::option::weighted(0.3, prop_oneof![Just(80u16), Just(150), Just(2_000)]), proptest::option::weighted(0.3, prop_oneof![Just(200u16), Just(500), Just(5_000)]), ) - .prop_map(|(data, pd, tx_gas, tx_size, block_size)| Budgets { - data, - policy_data: pd, - policy_tx_gas: tx_gas, - policy_tx_size: tx_size, - policy_block_size: block_size, - }) + .prop_map( + |(data, pd, (kv, policy_kv), (growth, policy_growth), tx_gas, tx_size, block_size)| { + Budgets { + data, + policy_data: pd, + kv, + policy_kv, + growth, + policy_growth, + policy_tx_gas: tx_gas, + policy_tx_size: tx_size, + policy_block_size: block_size, + } + }, + ) } /// A block: a world with its programs (the case's transaction is not used), the transactions, the @@ -198,6 +214,8 @@ impl BlockCase { ProtocolLimits { tx_runtime_limits: self.base.world.limits.runtime(), block_txs_data_limit: self.budgets.data.value(), + block_kv_update_limit: self.budgets.kv.value(), + block_state_growth_limit: self.budgets.growth.value(), } } @@ -208,6 +226,8 @@ impl BlockCase { tx_encode_size_limit: b.policy_tx_size.map_or(u64::MAX, u64::from), block_txs_encode_size_limit: b.policy_block_size.map_or(u64::MAX, u64::from), block_txs_data_limit: b.policy_data.value(), + block_kv_update_limit: b.policy_kv.value(), + block_state_growth_limit: b.policy_growth.value(), ..BlockLimits::no_limits() } } @@ -317,8 +337,8 @@ impl BlockCase { /// Whether the block admits a transaction of `gas_limit` and `tx_size` before it runs, by the /// limiter's rules: a deposit is held to the header's gas limit alone; any other transaction to -/// the policy's per-transaction caps and to the data-size packing budget, which refuses the next -/// transaction once reached. +/// the policy's per-transaction caps and to the data-size, KV-update and state-growth packing +/// budgets, each of which refuses the next transaction once reached. fn admits_before(limiter: &BlockLimiter, gas_limit: u64, tx_size: u64, is_deposit: bool) -> bool { let limits = &limiter.limits; if !is_deposit && gas_limit > limits.tx_gas_limit { @@ -332,7 +352,9 @@ fn admits_before(limiter: &BlockLimiter, gas_limit: u64, tx_size: u64, is_deposi } tx_size <= limits.tx_encode_size_limit && tx_size.saturating_add(limiter.block_tx_size_used) <= limits.block_txs_encode_size_limit && - limiter.usage.data_size < limits.block_txs_data_limit + limiter.usage.data_size < limits.block_txs_data_limit && + limiter.usage.write_records < limits.block_kv_update_limit && + limiter.usage.state_growth < limits.block_state_growth_limit } /// Whether a refusal names a block or transaction limit rather than the transaction's validity: @@ -419,6 +441,7 @@ fn run_block(case: &BlockCase) -> Result MemoryDatabase { let mut db = MemoryDatabase::default().rex6_predeploys(SYSTEM_ADDRESS); let world = &self.world; @@ -67,7 +72,10 @@ impl Case { install(&mut db, Who::Contract.address(), &world.contract, Some(self.main.assemble())); install(&mut db, Who::A.address(), &world.a, Some(self.a.assemble())); install(&mut db, Who::B.address(), &world.b, Some(self.b.assemble())); - db.set_account_balance(Who::Beneficiary.address(), world.beneficiary_balance.wei()); + let beneficiary_balance = world.beneficiary_balance.wei(); + if !beneficiary_balance.is_zero() { + db.set_account_balance(Who::Beneficiary.address(), beneficiary_balance); + } if let Some(delegation) = world.delegation { let address = delegation.delegator.address(); let balance = db.basic_ref_balance(address); @@ -299,14 +307,23 @@ fn init_destroys(init: &super::program::InitCode) -> bool { } } -/// Installs `account` at `address`, with `code` when it has any. +/// Installs `account` at `address`, with `code` when it has any; an account that would hold nothing +/// is not installed. fn install( db: &mut MemoryDatabase, address: Address, account: &AccountShape, code: Option>, ) { - if let Some(code) = code.filter(|code| !code.is_empty()) { + let code = code.filter(|code| !code.is_empty()); + if code.is_none() && + account.balance.wei().is_zero() && + account.nonce == 0 && + account.slots.is_empty() + { + return; + } + if let Some(code) = code { db.set_account_code(address, Bytes::from(code)); } db.set_account_balance(address, account.balance.wei()); diff --git a/crates/mega-evm/tests/fuzz/gen/program.rs b/crates/mega-evm/tests/fuzz/gen/program.rs index 5a1fa45d5..79cec5908 100644 --- a/crates/mega-evm/tests/fuzz/gen/program.rs +++ b/crates/mega-evm/tests/fuzz/gen/program.rs @@ -6,7 +6,7 @@ //! the stack as it found it, so any list assembles to valid bytecode, and a program shrinks by //! dropping ops. The assembly is [`BytecodeBuilder`]'s. -use alloy_primitives::{Address, Bytes, U256}; +use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ @@ -71,6 +71,11 @@ pub(crate) enum Target { System(SystemContract), /// A precompile. Precompile(Precompile), + /// An account the running program creates: the address one of its own `CREATE2` ops lands + /// on, the `nth` of them modulo their number, computed from `ADDRESS` as the op computes it; + /// in a program with none, the address a `CREATE2` of empty init code with salt zero would + /// land on. A program can so fund, pay or read an account before it creates it, and after. + Created { nth: u8 }, } impl Target { @@ -83,8 +88,9 @@ impl Target { } } -/// Pushes the target's address. -fn push_target(code: BytecodeBuilder, target: Target) -> BytecodeBuilder { +/// Pushes the target's address; a [`Target::Created`] resolves among `creations`, the `CREATE2` +/// ops of the program the target is in. +fn push_target(code: BytecodeBuilder, target: Target, creations: &Creations) -> BytecodeBuilder { match target { Target::Who(who) => code.push_address(who.address()), Target::SelfAddress => code.append(ADDRESS), @@ -92,6 +98,53 @@ fn push_target(code: BytecodeBuilder, target: Target) -> BytecodeBuilder { Target::Caller => code.append(CALLER), Target::System(contract) => code.push_address(contract.address()), Target::Precompile(precompile) => code.push_address(precompile.address()), + Target::Created { nth } => { + // keccak256(0xff ++ ADDRESS ++ salt ++ keccak256(init code)) over memory 11..96: its + // low twenty bytes are the address, which is all a call, an account read or a + // `SELFDESTRUCT` takes of the word. + let (salt, init_hash) = creations.resolve(nth); + code.append_many([ADDRESS, PUSH0, MSTORE]) + .push_number(0xff_u8) + .push_number(11_u8) + .append(MSTORE8) + .push_number(salt) + .push_number(32_u8) + .append(MSTORE) + .push_bytes(init_hash) + .push_number(64_u8) + .append(MSTORE) + .push_number(85_u8) + .push_number(11_u8) + .append(KECCAK256) + } + } +} + +/// The `CREATE2` ops of a program, in order, as the salt and the init code hash each lands with: +/// what a [`Target::Created`] in the program resolves to. +struct Creations(Vec<(u8, B256)>); + +impl Creations { + fn of(ops: &[Op]) -> Self { + Self( + ops.iter() + .filter_map(|op| match op { + Op::Create { salt: Some(salt), init, .. } => { + Some((*salt, keccak256(init.assemble()))) + } + _ => None, + }) + .collect(), + ) + } + + /// The salt and init code hash of the `nth` creation, modulo their number; salt zero and + /// empty init code for a program with none. + fn resolve(&self, nth: u8) -> (u8, B256) { + if self.0.is_empty() { + return (0, keccak256(InitCode::Empty.assemble())); + } + self.0[usize::from(nth) % self.0.len()] } } @@ -103,6 +156,7 @@ fn target() -> impl Strategy { 1 => Just(Target::Caller), 3 => system_contract().prop_map(Target::System), 2 => precompile().prop_map(Target::Precompile), + 3 => (0u8..4).prop_map(|nth| Target::Created { nth }), ] } @@ -338,9 +392,9 @@ fn precompile_input() -> impl Strategy { /// How much gas a call forwards. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Forward { - /// Everything (`GAS`), which the 63/64 rule caps. + /// Everything (`GAS`), which the 98/100 rule caps. All, - /// A fixed amount, which the 63/64 rule may cap lower. + /// A fixed amount, which the 98/100 rule may cap lower. Gas(u32), } @@ -629,16 +683,17 @@ pub(crate) struct Program { impl Program { /// The program's bytecode. pub(crate) fn assemble(&self) -> Vec { + let creations = Creations::of(&self.ops); let mut code = BytecodeBuilder::default(); for op in &self.ops { - code = op.assemble(code); + code = op.assemble(code, &creations); } match self.end { End::Stop => code.stop(), End::Return { len } => code.push_number(len).append_many([PUSH0, RETURN]), End::Revert { len } => code.push_number(len).append_many([PUSH0, REVERT]), End::Invalid => code.append(INVALID), - End::Selfdestruct { to } => push_target(code, to).append(SELFDESTRUCT), + End::Selfdestruct { to } => push_target(code, to, &creations).append(SELFDESTRUCT), End::Spin => { let dest = code.len() as u32; code.append(JUMPDEST) @@ -753,7 +808,8 @@ impl Op { } } - fn assemble(&self, code: BytecodeBuilder) -> BytecodeBuilder { + /// The op's bytecode, appended to `code`; a [`Target::Created`] resolves among `creations`. + fn assemble(&self, code: BytecodeBuilder, creations: &Creations) -> BytecodeBuilder { match self { Self::Sstore { slot, value } => code.sstore(U256::from(*slot), value.u256()), Self::Sload { slot } => code.push_number(*slot).append_many([SLOAD, POP]), @@ -770,7 +826,7 @@ impl Op { Self::Call { scheme, target, value, forward, args_len } => { let code = code.append_many([PUSH0, PUSH0]).push_number(*args_len).append(PUSH0); let code = if scheme.carries_value() { code.push_u256(value.wei()) } else { code }; - push_forward(push_target(code, *target), *forward) + push_forward(push_target(code, *target, creations), *forward) .append_many([scheme.opcode(), POP]) } Self::System { method, scheme, value } => { @@ -808,7 +864,7 @@ impl Op { } Self::Volatile(read) => read.assemble(code), Self::Account { target, read } => { - let code = push_target(code, *target); + let code = push_target(code, *target, creations); match read { AccountRead::Balance => code.append_many([BALANCE, POP]), AccountRead::CodeSize => code.append_many([EXTCODESIZE, POP]), diff --git a/crates/mega-evm/tests/fuzz/gen/world.rs b/crates/mega-evm/tests/fuzz/gen/world.rs index 4c2a14b61..4e807c46d 100644 --- a/crates/mega-evm/tests/fuzz/gen/world.rs +++ b/crates/mega-evm/tests/fuzz/gen/world.rs @@ -3,7 +3,10 @@ use alloy_primitives::{Address, U256}; use mega_evm::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, MAX_TX_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS}, + constants::{ + BLOCK_ENV_ACCESS_COMPUTE_GAS, MAX_TX_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, + }, EvmTxRuntimeLimits, MegaSpecId, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use proptest::prelude::*; @@ -154,6 +157,36 @@ impl DataLimit { } } +/// A transaction's limit on a count — its write records or its state growth — tight enough for a +/// program's few writes +/// to reach, or the spec's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CountLimit { + /// A handful: crossed by a few writes. + Small(u8), + /// The spec's. + Spec, + Unlimited, +} + +impl CountLimit { + fn value(self, spec: u64) -> u64 { + match self { + Self::Small(n) => u64::from(n), + Self::Spec => spec, + Self::Unlimited => u64::MAX, + } + } +} + +fn count_limit() -> impl Strategy { + prop_oneof![ + 3 => (0u8..=12).prop_map(CountLimit::Small), + 2 => Just(CountLimit::Spec), + 2 => Just(CountLimit::Unlimited), + ] +} + /// A gas detention cap. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum DetentionCap { @@ -202,6 +235,8 @@ pub(crate) enum Limits { /// A valid set of tight limits. Custom { data: DataLimit, + kv: CountLimit, + growth: CountLimit, frame_data: Option, block_env_cap: DetentionCap, oracle_cap: DetentionCap, @@ -217,38 +252,45 @@ impl Limits { Self::Loosest => EvmTxRuntimeLimits::no_limits() .with_block_env_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1) .with_oracle_access_compute_gas_limit(MAX_TX_COMPUTE_GAS - 1), - Self::Custom { data, frame_data, block_env_cap, oracle_cap } => EvmTxRuntimeLimits { - tx_data_size_limit: data.value(), - frame_data_size_limit: frame_data.map_or(u64::MAX, u64::from), - block_env_access_compute_gas_limit: block_env_cap - .value(BLOCK_ENV_ACCESS_COMPUTE_GAS), - oracle_access_compute_gas_limit: oracle_cap.value(ORACLE_ACCESS_COMPUTE_GAS), - }, + Self::Custom { data, kv, growth, frame_data, block_env_cap, oracle_cap } => { + EvmTxRuntimeLimits { + tx_data_size_limit: data.value(), + tx_kv_update_limit: kv.value(TX_KV_UPDATE_LIMIT), + tx_state_growth_limit: growth.value(TX_STATE_GROWTH_LIMIT), + frame_data_size_limit: frame_data.map_or(u64::MAX, u64::from), + block_env_access_compute_gas_limit: block_env_cap + .value(BLOCK_ENV_ACCESS_COMPUTE_GAS), + oracle_access_compute_gas_limit: oracle_cap.value(ORACLE_ACCESS_COMPUTE_GAS), + } + } } } } pub(crate) fn limits() -> impl Strategy { - let custom = ( - // The roomy data-size limits are drawn as often as the tight ones, so the compute stop is - // reached too. - prop_oneof![ - 1 => Just(DataLimit::Body), - 2 => Just(DataLimit::BodyPlusRecord), - 3 => (1u16..=2_000).prop_map(DataLimit::Small), - 3 => Just(DataLimit::Medium), - 3 => Just(DataLimit::Unlimited), - ], - proptest::option::weighted(0.3, prop_oneof![Just(1u16), Just(40), Just(200), Just(2_000)]), - detention_cap(), - detention_cap(), - ) - .prop_map(|(data, frame_data, block_env_cap, oracle_cap)| Limits::Custom { - data, - frame_data, - block_env_cap, - oracle_cap, - }); + let custom = + ( + // The roomy data-size limits are drawn as often as the tight ones, so the compute stop + // is reached too. + prop_oneof![ + 1 => Just(DataLimit::Body), + 2 => Just(DataLimit::BodyPlusRecord), + 3 => (1u16..=2_000).prop_map(DataLimit::Small), + 3 => Just(DataLimit::Medium), + 3 => Just(DataLimit::Unlimited), + ], + count_limit(), + count_limit(), + proptest::option::weighted( + 0.3, + prop_oneof![Just(1u16), Just(40), Just(200), Just(2_000)], + ), + detention_cap(), + detention_cap(), + ) + .prop_map(|(data, kv, growth, frame_data, block_env_cap, oracle_cap)| { + Limits::Custom { data, kv, growth, frame_data, block_env_cap, oracle_cap } + }); prop_oneof![3 => Just(Limits::Default), 2 => Just(Limits::Loosest), 5 => custom] } diff --git a/crates/mega-evm/tests/fuzz/harness.rs b/crates/mega-evm/tests/fuzz/harness.rs index befa05f50..2e4c6e2da 100644 --- a/crates/mega-evm/tests/fuzz/harness.rs +++ b/crates/mega-evm/tests/fuzz/harness.rs @@ -220,6 +220,22 @@ pub(crate) fn runs_at_measurement_prices() -> bool { true } +/// Whether a history byte costs a fraction of a gas at the prices in effect, as the byte-price +/// grid's 0.001 does: each history charge is then rounded on its own, and the history of bytes +/// charged apart is not the history of their sum. A history figure computed from a sum of bytes +/// holds at every other price, and the caller leaves it out here; this leaves the note the +/// byte-price grid counts. +pub(crate) fn history_rounds() -> bool { + if mega_evm::active_satin_prices().cphb.milli_gas().is_multiple_of(1_000) { + return false; + } + mega_evm::test_utils::note_price_guard(&format!( + "{} prices a history byte at a fraction of a gas", + mega_evm::CPHB_ENV_VAR + )); + true +} + /// Holds a property's coverage claim: `missing` lists the classes its run did not reach. /// /// On the default run (see [`FuzzConfig::requires_coverage`]) and at the spec's byte prices a diff --git a/crates/mega-evm/tests/fuzz/properties.rs b/crates/mega-evm/tests/fuzz/properties.rs index a712a150d..a1181029a 100644 --- a/crates/mega-evm/tests/fuzz/properties.rs +++ b/crates/mega-evm/tests/fuzz/properties.rs @@ -9,6 +9,7 @@ use std::{collections::BTreeMap, sync::Mutex}; use alloy_primitives::{Address, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, + op_revm::constants::BASE_FEE_RECIPIENT, system::is_system_originated, test_utils::{GasInspector, MemoryDatabase}, transaction_body_bytes, LimitCheck, LimitKind, MegaContext, MegaTransaction, @@ -130,6 +131,21 @@ fn pre_account(db: &mut MemoryDatabase, address: Address) -> Option Option { + db.basic(address).unwrap_or_default() +} + +/// Whether the outcome's `account` was created in the transaction and destroyed since: its first +/// effective destruction took back every part of it the transaction made — each slot it made +/// non-zero, and, where its leaf was absent at the start, the account's record and its unit of +/// state growth — and from that mark it counted nothing more. +fn destroyed_in_the_transaction(account: &revm::state::Account) -> bool { + account.is_created() && account.is_selfdestructed() +} + /// The gas ledgers, as the spec defines them: /// /// - the three ledgers add up to the raw spend: the regular ledger is defined as the spend less the @@ -279,7 +295,7 @@ fn test_property_kv_weighs_no_more_than_data_size() { context: &mut MegaContext, ) { self.steps += 1; - let usage = context.additional_limit().usage(); + let usage = context.limit_usage(); if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { self.over.get_or_insert((usage, self.steps)); } @@ -317,17 +333,161 @@ fn test_property_kv_weighs_no_more_than_data_size() { "the body and the {hints} bytes of hints forwarded are counted: {usage:?}" ); if !is_exempt(&tx) { - let limit = case.world.limits.runtime().tx_data_size_limit; + let limits = case.world.limits.runtime(); + let limit = limits.tx_data_size_limit; prop_check!( usage.data_size <= limit, "a user's transaction keeps more than its limit of {limit}: {usage:?}" ); + let limit = limits.tx_kv_update_limit; + prop_check!( + usage.write_records <= limit, + "a user's transaction keeps more records than its limit of {limit}: {usage:?}" + ); } Ok(()) }, ); } +/// The write records a transaction reports are the net change of what it kept, computed from the +/// case's pre-state and the outcome's state alone: one for every storage slot whose value differs +/// from its original, and one for every account but the sender whose nonce, balance or code +/// differs from what the case's world held. The sender's account is the body's, and so are the +/// settlement's fee credits, which are taken out of the fee accounts' balances first: the fuzz +/// world prices L1 and operator fees at nothing, so the settlement credits the beneficiary its tip +/// and the base-fee vault the base fee, on the gas the receipt bills, and a transaction that pays +/// no fee — a deposit, or one the protocol sent — credits nothing. What is left of a fee account's +/// change is a write its execution made, a record like any other. +/// +/// An account the transaction created and destroyed keeps no slot's record, and the account's own +/// only where the world held an account there, a balance or an account empty under EIP-161: a +/// leaf that existed at the start is an ordinary deletion, whose record stands, and one that did +/// not is taken back with what the transaction made of it. +#[test] +fn test_property_the_record_count_is_the_net_change() { + check("record_count", CASES, || case(Flavor::Satin), check_record_count); +} + +/// What [`test_property_the_record_count_is_the_net_change`] checks of a case. +pub(crate) fn check_record_count(case: &Case) -> Result<(), proptest::test_runner::TestCaseError> { + let tx = case.transaction(); + let Ok(outcome) = case.execute() else { return Ok(()) }; + let credit = fee_credits(case, &tx, &outcome); + let mut pre = case.database(); + let mut expected = 0; + for (address, account) in &outcome.state { + if destroyed_in_the_transaction(account) { + expected += u64::from(leaf_at_start(&mut pre, *address).is_some()); + continue; + } + let slots = account.storage.values().filter(|slot| slot.is_changed()).count(); + expected += slots as u64; + if *address == tx.caller() { + continue; + } + let before = pre_account(&mut pre, *address).unwrap_or_default(); + let Some(balance) = account.info.balance.checked_sub(credit(*address)) else { + return Err(crate::harness::fail(format!("{address} holds less than its fee credit"))); + }; + let changed = account.info.nonce != before.nonce || + balance != before.balance || + account.info.code_hash != before.code_hash; + expected += u64::from(changed); + } + prop_eq!( + outcome.usage.write_records, + expected, + "the records reported are not the net change of the state" + ); + Ok(()) +} + +/// What the settlement credits each account for `tx`'s fees, which `outcome` billed: the fuzz +/// world prices L1 and operator fees at nothing, so the beneficiary gets the tip and the base-fee +/// vault the base fee, on the gas the receipt bills, and a transaction that pays no fee — a +/// deposit, or one the protocol sent — credits nothing. +fn fee_credits( + case: &Case, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, +) -> impl Fn(Address) -> U256 { + let block = case.block(); + let basefee = u128::from(block.basefee); + let used = u128::from(outcome.gas.gas_used); + let tip = tx.effective_gas_price(basefee).saturating_sub(basefee); + let pays_fees = !is_exempt(tx); + move |address: Address| { + let mut credit = 0; + if pays_fees && address == block.beneficiary { + credit += tip * used; + } + if pays_fees && address == BASE_FEE_RECIPIENT { + credit += basefee * used; + } + U256::from(credit) + } +} + +/// The state growth a transaction reports is the net count of the new accounts and new slots it +/// kept, computed from the case's pre-state and the outcome's state alone: one for every slot whose +/// original value is zero and whose present value is not, and one for every account the case's +/// world held empty, or not at all, that the outcome holds non-empty once the settlement's fee +/// credits are taken out of its balance — a fee credit is no rise. The sender's account is the +/// body's, and is a rise only as the caller a deposit-like transaction created. +/// +/// An account the transaction created and destroyed keeps none of its slots, and its leaf only +/// where the world held it as an account empty under EIP-161: the creation added that account and +/// the destruction does not take a leaf back that existed at the start. One the world did not hold +/// is taken back, and one that held a balance was no new account. +#[test] +fn test_property_state_growth_is_the_net_count_of_new_state() { + check("state_growth", CASES, || case(Flavor::Satin), check_state_growth); +} + +/// What [`test_property_state_growth_is_the_net_count_of_new_state`] checks of a case. +pub(crate) fn check_state_growth(case: &Case) -> Result<(), proptest::test_runner::TestCaseError> { + let tx = case.transaction(); + let Ok(outcome) = case.execute() else { return Ok(()) }; + let credit = fee_credits(case, &tx, &outcome); + let deposit_like = + tx.0.deposit.source_hash != alloy_primitives::B256::ZERO || tx.caller() == SYSTEM_ADDRESS; + let mut pre = case.database(); + let mut expected = 0; + for (address, account) in &outcome.state { + if destroyed_in_the_transaction(account) { + let empty_leaf = leaf_at_start(&mut pre, *address).is_some_and(|info| info.is_empty()); + expected += u64::from(empty_leaf); + continue; + } + let slots = account + .storage + .values() + .filter(|slot| slot.original_value.is_zero() && !slot.present_value.is_zero()) + .count(); + expected += slots as u64; + if *address == tx.caller() && !deposit_like { + continue; + } + if pre_account(&mut pre, *address).is_some() { + continue; + } + let Some(balance) = account.info.balance.checked_sub(credit(*address)) else { + return Err(crate::harness::fail(format!("{address} holds less than its fee credit"))); + }; + let exists = account.info.nonce != 0 || + !balance.is_zero() || + account.info.code_hash != revm::primitives::KECCAK_EMPTY; + expected += u64::from(exists); + } + prop_eq!( + outcome.usage.state_growth, + expected, + "the state growth reported is not the net count of new state" + ); + Ok(()) +} + /// What the Oracle hints `evm`'s transaction forwarded weigh as data size. A forwarded hint's /// payload is its call's whole input: the selector, the topic, the offset and length of the data, /// and the data padded to a word. @@ -342,8 +502,9 @@ fn forwarded_hint_bytes(evm: &mega_evm::MegaEvm) -> } /// A stopped transaction keeps only what the spec says survives: the stop is the crossing of its -/// own frame, which names a limit the case runs under — the transaction's data-size limit, that -/// frame's budget, which is below it, or a compute limit, which no frame budget is — and reverts +/// own frame, which names a limit the case runs under — the transaction's data-size, KV or +/// state-growth limit, that frame's budget in one of them, which is below it, or a compute limit, +/// which no frame budget is — and reverts /// that frame and so everything below it; it is a revert carrying `MegaLimitExceeded`, with no /// log; no storage write stands; no account changes but the sender's /// nonce and fee, the fee recipients' credit, an applied EIP-7702 authority's nonce and @@ -387,17 +548,23 @@ pub(crate) fn check_survivors( "a reported stop that is within the limit\n{rendered}" ))); }; - let tx_limit = case.world.limits.runtime().tx_data_size_limit; + let runtime = case.world.limits.runtime(); + let tx_limit = match kind { + LimitKind::DataSize => runtime.tx_data_size_limit, + LimitKind::KvUpdate => runtime.tx_kv_update_limit, + LimitKind::StateGrowth => runtime.tx_state_growth_limit, + LimitKind::ComputeGas => u64::MAX, + }; match (kind, frame_local) { - (LimitKind::DataSize, false) => { - prop_eq!(limit, tx_limit, "the stop names the transaction's limit\n{rendered}"); - } - (LimitKind::DataSize, true) => { - prop_check!(limit < tx_limit, "a frame budget is below the limit\n{rendered}"); - } (LimitKind::ComputeGas, frame_local) => { prop_check!(!frame_local, "a compute stop is no frame budget\n{rendered}"); } + (_, false) => { + prop_eq!(limit, tx_limit, "the stop names the transaction's limit\n{rendered}"); + } + (_, true) => { + prop_check!(limit <= tx_limit, "a frame budget is within the limit\n{rendered}"); + } } match &outcome.result { ExecutionResult::Revert { output, .. } => { diff --git a/crates/mega-evm/tests/fuzz/regressions.rs b/crates/mega-evm/tests/fuzz/regressions.rs index 518c5f445..8c5ff81ae 100644 --- a/crates/mega-evm/tests/fuzz/regressions.rs +++ b/crates/mega-evm/tests/fuzz/regressions.rs @@ -27,12 +27,14 @@ use crate::{ gen::{ case::Case, - program::{End, Program}, + program::{End, Forward, InitCode, Op, Program, Scheme, Target}, tx::{GasTier, Price, Shape, Tx}, - world::{AccountShape, Balance, BeneficiaryIs, BlockShape, Limits, Salt, World}, + world::{ + AccountShape, Balance, BeneficiaryIs, BlockShape, Delegation, Limits, Salt, World, + }, Value, Who, }, - harness::runs_at_measurement_prices, + harness::{history_rounds, runs_at_measurement_prices}, render::render, }; @@ -114,7 +116,10 @@ fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_ let gas = outcome.result.gas(); let gas_limit = GasTier::Tiny.limit(); assert_eq!(gas.total_gas_spent(), gas_limit, "the whole gas limit burns\n{rendered}"); - assert_eq!(gas.reservoir_remaining(), 0, "nothing comes back from a reservoir\n{rendered}"); + assert_eq!( + outcome.gas.reservoir_remaining, 0, + "nothing comes back from a reservoir\n{rendered}" + ); assert_eq!(outcome.gas.gas_used, gas_limit, "{rendered}"); let body = mega_evm::transaction_body_bytes(&case.transaction()); assert_eq!(outcome.gas.history_bytes, body, "the body alone is kept\n{rendered}"); @@ -145,3 +150,134 @@ fn test_an_out_of_gas_before_the_first_frame_pays_the_operator_fee_on_the_whole_ "the recipient is created empty: the frame never runs, so the value does not move\n{rendered}" ); } + +/// A sender delegated to `B` calls itself, so `B`'s program runs as the sender: it funds the +/// account its `CREATE2` lands on, then creates it, and the init code destroys the account back to +/// the sender. The record-count property's own check holds: the transaction reports the net change +/// of its state, and the account it funded and created, which did not exist at the start, is taken +/// back with its one record by its destruction, which a creation that records its created account +/// whether or not the transaction had changed it would count twice. The case runs on the large gas +/// tier, which the dearest byte prices do not exhaust. +#[test] +fn test_a_delegated_sender_that_funds_then_creates_reports_the_net_change() { + let mut world = plain_world(); + world.caller.balance = Balance::Small; + world.delegation = Some(Delegation { delegator: Who::Caller, delegate: Who::B }); + let b = Program { + ops: vec![ + Op::Call { + scheme: Scheme::Call, + target: Target::Created { nth: 0 }, + value: Value::One, + forward: Forward::All, + args_len: 0, + }, + Op::Create { + value: Value::Zero, + salt: Some(0), + init: InitCode::Selfdestructs { to: Who::Caller }, + }, + ], + end: End::Stop, + }; + let case = Case { + world, + tx: Tx { + shape: Shape::Call { to: Who::Caller, data_len: 0, access_list: vec![] }, + value: Value::Zero, + gas: GasTier::Large, + price: Price::Free, + nonce_ok: true, + }, + main: stop(), + a: stop(), + b, + }; + let execution = case.execute(); + let rendered = render(&execution); + let outcome = execution.as_ref().expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{rendered}"); + if let Err(error) = crate::properties::check_record_count(&case) { + panic!("{error}\n{rendered}"); + } + assert_eq!( + outcome.usage.write_records, 0, + "the account funded and created goes with its destruction\n{rendered}" + ); +} + +/// A program that funds the account its `CREATE2` lands on, named by [`Target::Created`], then +/// creates it, keeps one record for the account and one for itself: the transfer changed both, so +/// neither the creation nor the bump of the program's nonce adds a record. The creation lands on +/// the funded address, which pins that the target resolves to the address the op creates at. +/// +/// Before the created account followed the net-change rule, the creation recorded it a second +/// time: three records where two stand, and a record's history more. +#[test] +fn test_a_program_that_funds_the_account_it_then_creates_keeps_one_record_for_it() { + use alloy_primitives::{keccak256, B256, U256}; + use mega_evm::{LimitUsage, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE}; + + const SALT: u8 = 2; + let main = Program { + ops: vec![ + Op::Call { + scheme: Scheme::Call, + target: Target::Created { nth: 0 }, + value: Value::One, + forward: Forward::All, + args_len: 0, + }, + Op::Create { value: Value::Zero, salt: Some(SALT), init: InitCode::Empty }, + ], + end: End::Stop, + }; + let mut world = plain_world(); + world.contract.balance = Balance::Small; + let case = Case { + world, + tx: Tx { + shape: Shape::Call { to: Who::Contract, data_len: 0, access_list: vec![] }, + value: Value::Zero, + gas: GasTier::Large, + price: Price::Free, + nonce_ok: true, + }, + main, + a: stop(), + b: stop(), + }; + let execution = case.execute(); + let outcome = execution.as_ref().expect("the transaction is valid"); + let rendered = render(&execution); + assert!(outcome.result.is_success(), "{rendered}"); + + let created = Who::Contract + .address() + .create2(B256::from(U256::from(SALT)), keccak256(InitCode::Empty.assemble())); + let account = outcome.state.get(&created).expect("the account is created"); + assert_eq!( + (account.info.nonce, account.info.balance), + (1, U256::from(1)), + "the creation landed on the account the program funded\n{rendered}" + ); + let body = mega_evm::transaction_body_bytes(&case.transaction()); + assert_eq!( + outcome.usage, + LimitUsage { + data_size: body + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 2, + state_growth: 1, + }, + "the contract and the account it funded and created, and the transfer log; the funding \ + made the account, so the creation onto it adds none\n{rendered}" + ); + if !history_rounds() { + assert_eq!( + outcome.gas.history, + mega_evm::history_gas(body + 2 * WRITE_RECORD_SIZE).expect("the bytes have a price"), + "the history of the body and two records: the creation's charge for the account came \ + back\n{rendered}" + ); + } +} diff --git a/crates/mega-evm/tests/satin/common.rs b/crates/mega-evm/tests/satin/common.rs index e70acfc35..c8123427a 100644 --- a/crates/mega-evm/tests/satin/common.rs +++ b/crates/mega-evm/tests/satin/common.rs @@ -95,7 +95,7 @@ pub(crate) fn run( ) -> (ResultAndState, LimitUsage) { let mut evm = MegaEvm::new(context(db)); let result = evm.transact_raw(tx).expect("the transaction is valid"); - let usage = evm.ctx().additional_limit().usage(); + let usage = evm.ctx().limit_usage(); (result, usage) } @@ -125,6 +125,41 @@ pub(crate) fn share(remaining: u64) -> u64 { u128::from(mega_evm::FRAME_DATA_SHARE_DENOMINATOR)) as u64 } +/// The regular gas a call or creation forwards of the `remaining` its caller holds at the forward +/// when it asks for all of it: all but the caller's 2 per cent, the division truncating. +pub(crate) const fn forward_cap(remaining: u64) -> u64 { + remaining - remaining * 2 / 100 +} + +/// The most regular gas a caller can hold at the forward of a call or creation that asks for all of +/// it and keep only `kept` once [`forward_cap`] is taken: a caller keeps a fiftieth of what it +/// holds, rounded down. +pub(crate) const fn holding_to_keep(kept: u64) -> u64 { + 50 * kept + 49 +} + +/// The reservoir a child frame is given of the `remaining` its caller has left: all but the +/// caller's 2 per cent, the division truncating, so a caller keeps nothing of a reservoir below 50. +pub(crate) const fn reservoir_share(remaining: u64) -> u64 { + remaining - remaining * 2 / 100 +} + +/// The smallest reservoir a caller can hold that hands a child exactly `share` +/// ([`reservoir_share`] takes every value, rising by one or by none at each step). +pub(crate) fn reservoir_giving(share: u64) -> u64 { + let mut remaining = share + share / 50; + while reservoir_share(remaining) > share { + remaining -= 1; + } + while reservoir_share(remaining) < share { + remaining += 1; + } + while remaining > 0 && reservoir_share(remaining - 1) == share { + remaining -= 1; + } + remaining +} + /// `tx` as a user's deposit: no fee, and a source hash a user's transaction could carry. pub(crate) fn deposit(mut tx: MegaTransaction) -> MegaTransaction { tx.0.deposit.source_hash = B256::repeat_byte(0x11); @@ -230,6 +265,31 @@ pub(crate) fn history(bytes: u64) -> u64 { u64::try_from((milli_gas + 500) / 1_000).expect("the history of the bytes fits a u64") } +/// Room for the state gas of several new accounts, including in a frame that resumes after a +/// child burned the 98/100 it was forwarded: at least 50,000,000, and 64 times what a value call +/// to a new account costs its caller at the byte prices in effect, more than the 50 times the +/// fiftieth it keeps needs. +pub(crate) fn value_call_room() -> u64 { + (64 * (account_state_gas() + history(4 * mega_evm::WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) +} + +/// `usage` with `growth` new accounts and new slots kept: its state growth. +pub(crate) const fn grown(usage: LimitUsage, growth: u64) -> LimitUsage { + LimitUsage { state_growth: growth, ..usage } +} + +/// What a transaction with an empty calldata keeps: its body, `records` write records and the +/// transfer logs of `moves` value movements. +pub(crate) const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + + records * mega_evm::WRITE_RECORD_SIZE + + moves * mega_evm::TRANSFER_LOG_SIZE, + write_records: records, + state_growth: 0, + } +} + /// The history gas the body of a transaction carrying `calldata_len` bytes of calldata, and no /// access list or authorization, pays at the byte prices in effect, by hand: `TX_BODY_SIZE`, 310 /// bytes, and one byte per byte of calldata. diff --git a/crates/mega-evm/tests/satin/compute_gas.rs b/crates/mega-evm/tests/satin/compute_gas.rs index 279485668..45546c8fe 100644 --- a/crates/mega-evm/tests/satin/compute_gas.rs +++ b/crates/mega-evm/tests/satin/compute_gas.rs @@ -510,9 +510,9 @@ fn test_computation_past_the_execution_cap_is_an_ordinary_out_of_gas() { } } -/// A nested call cannot compute past the cap either. Its callee is forwarded what the cap leaves, -/// runs out of gas and fails; its caller resumes on the sixty-fourth it kept, and the transaction -/// computes less than the cap. +/// A nested call cannot compute past the cap either. Its callee is forwarded 98/100 of what the +/// cap leaves, runs out of gas and fails; its caller resumes on the 2 per cent it kept, and the +/// transaction computes less than the cap. /// /// Only above the cap: below it the gas limit bounds the callee long before the cap does. #[test] @@ -536,7 +536,7 @@ fn test_a_nested_call_cannot_compute_past_the_cap() { "the call failed, and its flag says so", ); assert!(outcome.gas.regular < TX_GAS_LIMIT_CAP, "{:?}", outcome.gas); - assert!(outcome.gas.regular > TX_GAS_LIMIT_CAP / 64 * 63, "the callee burned its share"); + assert!(outcome.gas.regular > TX_GAS_LIMIT_CAP / 100 * 98, "the callee burned its share"); } /// A transaction whose intrinsic gas alone is more computation than the cap allows is rejected diff --git a/crates/mega-evm/tests/satin/count_order.rs b/crates/mega-evm/tests/satin/count_order.rs index 569baeae1..d85e32bff 100644 --- a/crates/mega-evm/tests/satin/count_order.rs +++ b/crates/mega-evm/tests/satin/count_order.rs @@ -1,8 +1,8 @@ //! The order the two data-size counts are checked in, when one record crosses both at once. //! //! A record is counted on the transaction and on the frame that makes it: the transaction against -//! its limit, the frame against its budget. The transaction is checked first, and the first count -//! crossed is the one the stop names. Either reverts the frame that crossed it alone, and the +//! its limit, the frame against its budget. The frame's budget is checked first, and the first +//! count crossed is the one the stop names. Either reverts the frame that crossed it alone, and the //! caller goes on. use alloy_primitives::{address, Address, Bytes, U256}; @@ -25,7 +25,7 @@ const B: Address = address!("0000000000000000000000000000000000f20002"); const GAS_LIMIT: u64 = 100_000_000; /// One record that crosses the transaction's data-size limit and its frame's budget at once is -/// stopped with the transaction's limit, which is checked first. +/// stopped with the frame's budget, which is checked first. /// /// [`A`] keeps two records, so the transaction has 310 + 2 × 40 = 390 bytes when [`B`] makes the /// record that crosses, which brings it to 430 bytes, and [`B`]'s own count to 40 bytes. `A`'s @@ -34,20 +34,21 @@ const GAS_LIMIT: u64 = 100_000_000; /// gets 39. A transaction limit of 390 leaves `A` 80 bytes, and `B` none. /// /// Either way [`B`] reverts alone with `MegaLimitExceeded(kind, limit)` and [`A`] returns what it -/// reverted with: the limit named is the one the order picks. The row that crosses the frame's -/// budget alone shows that the count the first row ranks second is crossed. +/// reverted with: the limit named is the one the order picks, `B`'s budget of none in the first +/// row, where the transaction's limit is crossed too. The row that crosses the frame's budget alone +/// shows the same budget rule with room left in the transaction. /// /// Rules: [S10.48], [S10.31], [S10.33], [S10.34], [S10]. Independence: constants — the usages and /// budgets are hand arithmetic from `TX_BODY_SIZE`, `WRITE_RECORD_SIZE` and the 98/100 share. #[test] -fn test_a_record_crossing_both_counts_is_reported_for_the_transaction() { +fn test_a_record_crossing_both_counts_names_the_frame_budget() { let unlimited = EvmTxRuntimeLimits::no_limits(); let before = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE; let rows: [(&str, EvmTxRuntimeLimits, u64); 2] = [ ( - "the transaction's limit and the frame's budget: the transaction's limit", + "the transaction's limit and the frame's budget: the frame's budget", unlimited.with_tx_data_size_limit(before).with_frame_data_size_limit(120), - before, + 0, ), ("the frame's budget alone", unlimited.with_frame_data_size_limit(120), 39), ]; @@ -76,8 +77,8 @@ fn test_a_record_crossing_both_counts_is_reported_for_the_transaction() { assert_eq!(outcome.limit_exceeded, None, "{row}: no stop of the transaction's own frame"); assert_eq!( outcome.usage, - LimitUsage { data_size: before, write_records: 2 }, - "{row}: A's two records, none of B's" + LimitUsage { data_size: before, write_records: 2, state_growth: 2 }, + "{row}: A's two records and two new slots, none of B's" ); } } diff --git a/crates/mega-evm/tests/satin/data_size.rs b/crates/mega-evm/tests/satin/data_size.rs index 8188ca906..01bb7e7ff 100644 --- a/crates/mega-evm/tests/satin/data_size.rs +++ b/crates/mega-evm/tests/satin/data_size.rs @@ -6,14 +6,15 @@ //! //! The body is counted before any frame and kept on every path; validation rejects a transaction //! whose body, with a record for each authorization it carries, exceeds the limit. Deployed code is -//! counted on the creation's lane, one byte per byte, before the creation is committed, and only -//! when revm would deposit it. +//! drawn on the creating frame's byte pool, one byte per byte, before the creation is committed, +//! and only when revm would deposit it. use alloy_evm::Evm; -use alloy_primitives::{address, keccak256, Address, Bytes, U256}; -use alloy_sol_types::SolError; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::{MAX_CONTRACT_SIZE, TX_GAS_LIMIT_CAP}, + system::{IOracle, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE}, test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransactionOutcome, FRAME_DATA_SHARE_DENOMINATOR, @@ -21,8 +22,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADD, CALL, CREATE, CREATE2, GAS, ISZERO, LOG0, MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, - RETURNDATASIZE, SELFDESTRUCT, SSTORE, STOP, + ADD, CALL, CALLDATASIZE, CREATE, CREATE2, GAS, INVALID, ISZERO, JUMPDEST, JUMPI, LOG0, + MSTORE, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, SELFDESTRUCT, SSTORE, STOP, }, context::result::{ExecutionResult, HaltReason}, context_interface::cfg::GasId, @@ -35,7 +36,8 @@ use revm::{ use crate::common::{ account_state_gas, body_history, call, call_with_data, constructor_returning, context, create, - execute_under, history, history_is_free, history_rounds, share, slot_state_gas, + execute_under, grown, history, history_is_free, history_rounds, holding_to_keep, + reservoir_giving, share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000300000"); @@ -47,11 +49,19 @@ const D: Address = address!("0000000000000000000000000000000000300004"); const GAS_LIMIT: u64 = 20_000_000; /// [`GAS_LIMIT`] on top of twice the history of `bytes` at the byte prices in effect: enough for -/// the frame three calls down to keep `bytes`, after each caller kept a 64th of what it forwards. +/// the frame three calls down to keep `bytes`, after each caller kept a fiftieth of what it held. fn gas_for_history(bytes: u64) -> u64 { GAS_LIMIT + 2 * history(bytes) } +/// [`GAS_LIMIT`] on top of twice the state and history gas of `deployed` bytes of code at the byte +/// prices in effect: enough for a creation, which gets 98% of what its creator holds, to deposit +/// them. +fn gas_for_deposit(deployed: u64) -> u64 { + let per_byte = mega_evm::satin_gas_params().get(GasId::code_deposit_state_gas()); + GAS_LIMIT + 2 * (deployed * per_byte + history(deployed)) +} + /// The least a parent must have left for the child's share of it to hold `bytes`: a limit that /// fits a child's write by exactly its bytes still reverts the child on its own budget, which is /// 98% of the parent's room, rounded down. @@ -119,11 +129,7 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let gas_limit = gas_for_history(budget); let result = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); - ( - result, - evm.ctx().additional_limit().limit_exceeded().copied(), - evm.ctx().additional_limit().usage(), - ) + (result, evm.ctx().additional_limit().limit_exceeded().copied(), evm.ctx().limit_usage()) }; // 32 bytes for the log's address, and the data. Exactly the budget. @@ -142,15 +148,21 @@ fn test_depth_3_frame_budget_reverts_the_child_and_the_parents_resume() { assert!(over.result.logs().is_empty(), "the log died with D"); assert_eq!( usage, - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 3 * 40, write_records: 3 } + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + 3 * 40, + write_records: 3, + state_growth: 3 + }, + "one fresh slot in each caller" ); } -/// The same depth, with the transaction's limit tighter than the frame budgets. `D`'s log crosses -/// the transaction limit, which reverts `D` alone, with the revert data naming the transaction -/// limit: `C`, `B` and `A` resume, each writes its slot within what the transaction has left, and -/// the transaction succeeds. What it keeps is what the same chain keeps without the log: the log -/// went with `D`, and the transaction never kept more than its limit. +/// The same depth, under a transaction limit. `D`'s log crosses the transaction limit and `D`'s own +/// budget with it — a frame's budget is a share of what the transaction has left — which reverts +/// `D` alone, the revert data naming the budget, tested first: `C`, `B` and `A` resume, each +/// writes its slot within what the transaction has left, and the transaction succeeds. What it +/// keeps is what the same chain keeps without the log: the log went with `D`, and the transaction +/// never kept more than its limit. #[test] fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { const TX_LIMIT: u64 = 8_000; @@ -161,9 +173,10 @@ fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { assert!(outcome.result.is_success(), "the callers resume: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "a stop below the transaction's own frame is no stop"); - // `D` reverted with the transaction limit's stop: nothing was written before its log, so the - // log crossed it alone, and the transaction limit is checked before `D`'s budget. - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: TX_LIMIT }; + // `D` reverted with its budget's stop: nothing was written before its log, so its budget is the + // share of a share of a share of what the body leaves. + let budget = share(share(share(TX_LIMIT - mega_evm::TX_BODY_SIZE))); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( evm.inspector().calls.first(), Some(&(D, InstructionResult::Revert, Bytes::from(stop.abi_encode()))), @@ -172,7 +185,11 @@ fn test_depth_3_transaction_limit_reverts_the_child_and_the_parents_resume() { assert!(stored(&outcome.state, A) && stored(&outcome.state, B) && stored(&outcome.state, C)); assert!(outcome.result.logs().is_empty(), "the log went with D"); let three_records = mega_evm::TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE; - assert_eq!(outcome.usage, LimitUsage { data_size: three_records, write_records: 3 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: three_records, write_records: 3, state_growth: 3 }, + "one fresh slot in each caller" + ); assert!(outcome.usage.data_size <= TX_LIMIT); // The same chain without the log keeps exactly as much. @@ -265,7 +282,8 @@ fn test_calldata_counts_in_the_body() { assert!(outcome.result.is_success(), "{:?}", outcome.result); outcome.usage }; - let expected = LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 50, write_records: 0 }; + let expected = + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + 50, write_records: 0, state_growth: 0 }; assert_eq!(run(0), expected, "a zero byte"); assert_eq!(run(0xff), expected, "a non-zero byte"); } @@ -295,7 +313,11 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() ); assert!(kept.result.is_success(), "inspect {inspect}: {:?}", kept.result); assert_eq!(kept.limit_exceeded, None); - assert_eq!(kept.usage, LimitUsage { data_size: full, write_records: 1 }); + assert_eq!( + kept.usage, + LimitUsage { data_size: full, write_records: 1, state_growth: 1 }, + "inspect {inspect}: the created account is new" + ); assert_eq!(kept.state[&created].info.code_hash, code_hash, "inspect {inspect}"); let (over, probe) = run_create( @@ -304,18 +326,19 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() inspect, ); assert!(!over.result.is_success() && !over.result.is_halt(), "{:?}", over.result); + // The creation is the transaction's own frame, whose budget is what the body leaves. assert_eq!( over.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: full - 1, - used: full, - frame_local: false, + limit: full - 1 - body, + used: full - body, + frame_local: true, }) ); assert_eq!( over.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "the stop drops the code and the created account; the body stays" ); assert!( @@ -329,7 +352,7 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() assert_eq!(probe.creates[0].0, InstructionResult::Revert); assert_eq!( probe.creates[0].1.as_ref(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: full - 1 } + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: full - 1 - body } .abi_encode() ); } @@ -340,11 +363,13 @@ fn test_deployed_code_one_byte_over_the_transaction_limit_is_not_left_deployed() /// creator's nonce record stays, and the caller resumes. #[test] fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { - const CAP: u64 = 1_000; - // The transaction's frame is capped at `CAP` and has spent nothing, so the creation gets 98% - // of that. Its start records the created account and the creator's nonce before the code. + const CAP: u64 = 2_000; + // The transaction's frame is capped at `CAP` and has spent nothing when it creates, so the + // creation gets 98% of it, and the creator keeps the 40 bytes its nonce record takes once the + // creation returned. The creation's start records the created account before the code. let child_budget = share(CAP); - let at_start = 2 * WRITE_RECORD_SIZE; + assert_eq!(CAP - child_budget, WRITE_RECORD_SIZE); + let at_start = WRITE_RECORD_SIZE; let fits = child_budget - at_start; let db = |deployed| funded().account_code(A, factory_deploying(deployed)); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(CAP); @@ -354,10 +379,11 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { let mut evm = MegaEvm::new(context(db(deployed)).with_tx_runtime_limits(limits)) .with_inspector(Probe::default()); Evm::set_inspector_enabled(&mut evm, inspect); - let result = evm.transact_raw(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let result = + evm.transact_raw(call(CALLER, A, U256::ZERO, gas_for_deposit(deployed))).unwrap(); ( result, - evm.ctx().additional_limit().usage(), + evm.ctx().limit_usage(), evm.ctx().additional_limit().limit_exceeded().copied(), evm.inspector().clone(), ) @@ -369,7 +395,13 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { assert_eq!(stop, None); assert_eq!( usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + child_budget, write_records: 2 } + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE + child_budget, + write_records: 2, + state_growth: 1, + }, + "the creator's nonce record, and the creation's whole budget; the created account is \ + new" ); assert_eq!(kept.state[&created].info.code_hash, keccak256(vec![0_u8; fits as usize])); @@ -378,7 +410,11 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { assert_eq!(stop, None, "a frame budget below the transaction's own frame is no stop of it"); assert_eq!( usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0 + }, "the creator's nonce stays; the code and the created account do not" ); assert!( @@ -399,6 +435,152 @@ fn test_deployed_code_over_the_frame_budget_reverts_the_creation_alone() { } } +/// A contract that runs `init` through `CREATE` with `value` wei, then returns what the creation +/// returned or reverted with: nothing once it succeeded, the stop's revert data once a limit +/// stopped it. +fn create_returning_its_output(init: &Bytes, value: u64) -> Bytes { + BytecodeBuilder::default() + .mstore(0, init) + .push_number(init.len() as u64) + .push_number(0_u64) + .push_number(value) + .append_many([CREATE, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) + .build() +} + +/// A creation's start counts against the creation's own budget — the share of what its creator +/// has left at its `CREATE` — the created account's record, and with an endowment the transfer +/// log. The record of the creator's nonce is the creator's: counted on it once the creation +/// returned with the nonce bumped, and held to the creator's budget, not the creation's. The +/// creator here is the transaction's own frame, with `R` bytes left under the transaction's limit. +/// +/// The largest `R` whose share falls short of the start stops the creation at its start, and the +/// creator keeps its nonce record: 40 without an endowment, a share of 39 against 40 bytes. One +/// byte more, a share of 40, starts the creation, which fills its share and leaves the creator 1 +/// byte, short of its record: the creator is stopped on its own budget once the creation +/// returned, and since it is the transaction's own frame its stop is the transaction's, the +/// creation and the bump going with it. From 80 left the creator keeps both records. With 2,000 +/// left the share is 1,960, so the creation may deposit the 1,920 bytes beyond its start and the +/// creator keeps the 40 left for its record; the 1,921st stops the creation at its deposit. With +/// an endowment the figures are 204 (a share of 199 against 200 bytes), 205, 240, and 2,160 (a +/// share of 2,116, room for 1,916). +#[test] +fn test_a_creation_is_held_to_its_share_from_its_start() { + let run = |left: u64, endowment: u64, deployed: u64| { + let db = funded() + .account_code( + A, + create_returning_its_output(&constructor_returning(deployed), endowment), + ) + .account_balance(A, U256::from(endowment)); + let tx = call(CALLER, A, U256::ZERO, gas_for_deposit(deployed)); + run_at(db, tx, mega_evm::TX_BODY_SIZE + left) + }; + let stop = |budget| MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + let usage = |bytes, write_records| LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + bytes, + write_records, + state_growth: 0, + }; + let nonce_record_alone = usage(WRITE_RECORD_SIZE, 1); + let nothing_created = |outcome: &MegaTransactionOutcome| { + outcome.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty()) + }; + let assert_stopped = |outcome: &MegaTransactionOutcome, budget: u64, case: &str| { + assert!(outcome.result.is_success(), "{case}: A resumes: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}: a stop below the transaction's frame"); + assert_eq!( + outcome.result.output().unwrap().as_ref(), + stop(budget).abi_encode(), + "{case}: the creation was stopped on its own budget", + ); + assert_eq!(outcome.usage, nonce_record_alone, "{case}: A keeps its nonce record"); + assert_eq!(outcome.state[&A].info.nonce, 1, "{case}"); + assert!(nothing_created(outcome), "{case}: nothing was created"); + }; + + // The creation's budget: the share of what the creator has left at its `CREATE`. + let budget = share; + for endowment in [0, 1] { + let log = if endowment == 0 { 0 } else { TRANSFER_LOG_SIZE }; + let at_start = WRITE_RECORD_SIZE + log; + let starts = child_room(at_start); + + let case = format!("endowment {endowment}, {} left", starts - 1); + assert_stopped(&run(starts - 1, endowment, 0), budget(starts - 1), &case); + + let case = format!("endowment {endowment}, {starts} left"); + let creator_stopped = run(starts, endowment, 0); + assert!( + matches!(creator_stopped.result, ExecutionResult::Revert { .. }), + "{case}: {:?}", + creator_stopped.result + ); + assert_eq!( + creator_stopped.result.output().unwrap().as_ref(), + stop(starts).abi_encode(), + "{case}: the creator is stopped on its own budget once the creation returned", + ); + assert_eq!( + creator_stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: starts, + used: at_start + WRITE_RECORD_SIZE, + frame_local: true, + }), + "{case}: the creation's whole share and the creator's record", + ); + assert_eq!(creator_stopped.usage, usage(0, 0), "{case}: the body alone"); + assert!( + creator_stopped.state.get(&A).is_none_or(|account| account.info.nonce == 0), + "{case}: the bump went with the creator's revert", + ); + assert!(nothing_created(&creator_stopped), "{case}: and the creation with it"); + + let kept = at_start + WRITE_RECORD_SIZE; + let case = format!("endowment {endowment}, {kept} left"); + let started = run(kept, endowment, 0); + assert!(started.result.is_success(), "{case}: {:?}", started.result); + assert_eq!(started.result.output().unwrap(), &Bytes::new(), "{case}: it started"); + assert_eq!( + started.usage, + grown(usage(WRITE_RECORD_SIZE + at_start, 2), 1), + "{case}: both records and the log; the created account is new" + ); + + let left = 2_000 + log; + let room = budget(left) - at_start; + let case = format!("endowment {endowment}, {left} left, {room} bytes deployed"); + let fits = run(left, endowment, room); + assert!(fits.result.is_success(), "{case}: {:?}", fits.result); + assert_eq!(fits.result.output().unwrap(), &Bytes::new(), "{case}: it deployed"); + assert_eq!( + fits.usage, + grown(usage(WRITE_RECORD_SIZE + budget(left), 2), 1), + "{case}: the creator's record, and exactly the creation's share; the created account \ + is new" + ); + assert_eq!( + fits.state[&A.create(0)].info.code_hash, + keccak256(vec![0_u8; room as usize]), + "{case}", + ); + + let case = format!("endowment {endowment}, {left} left, {} bytes deployed", room + 1); + assert_stopped(&run(left, endowment, room + 1), budget(left), &case); + + if endowment == 0 { + assert_eq!((starts - 1, budget(starts - 1), starts, kept), (40, 39, 41, 80)); + assert_eq!((budget(left), room), (1_960, 1_920)); + } else { + assert_eq!((starts - 1, budget(starts - 1), starts, kept), (204, 199, 205, 240)); + assert_eq!((budget(left), room), (2_116, 1_916)); + } + } +} + /// Init code that returns `len` bytes as the deployed contract, the first of them `first` and /// the rest zeros. fn constructor_returning_from(first: u8, len: u64) -> Bytes { @@ -434,17 +616,21 @@ fn factory_noting_failure(init: &Bytes) -> Bytes { /// goes with the creation. The reservoir of a gas limit far above the execution cap pays the state /// gas and the history of a contract of the largest size. /// -/// `A` has 100 bytes left: the creation's start records the created account and `A`'s nonce, and -/// the output comes on top. Afterwards `A` writes a slot to note the failure: the transaction -/// keeps the nonce record and that slot's. +/// `A` has 100 bytes left, and its creation the share of them, 98: the creation's start records +/// the created account, and the output comes on top; `A`'s nonce record is counted on `A` once the +/// creation returned. Afterwards `A` writes a slot to note the failure: the transaction keeps the +/// nonce record and that slot's. #[test] fn test_code_return_create_refuses_is_not_counted() { let limit = mega_evm::TX_BODY_SIZE + 100; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); let at_start = 2 * WRITE_RECORD_SIZE; let max = MAX_CONTRACT_SIZE as u64; + // Three bytes past the room the creation's share leaves its output. + let past_the_share = share(100) - WRITE_RECORD_SIZE + 3; + assert_eq!(past_the_share, 61); let cases = [ - ("0xEF first", 0xEF, 21, InstructionResult::CreateContractStartingWithEF), + ("0xEF first", 0xEF, past_the_share, InstructionResult::CreateContractStartingWithEF), ("over the code-size limit", 0x00, max + 1, InstructionResult::CreateContractSizeLimit), ]; let run = |init: &Bytes, inspect: bool, gas_limit: u64| { @@ -468,8 +654,12 @@ fn test_code_return_create_refuses_is_not_counted() { assert_eq!(failure_noted(&refused), Some(U256::from(1)), "{case}: A caught it"); assert_eq!( refused.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, - "{case}: the nonce record and the slot", + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + at_start, + write_records: 2, + state_growth: 1 + }, + "{case}: the nonce record and the slot; the slot is new", ); assert_eq!( refused.gas.history, @@ -496,15 +686,22 @@ fn test_code_return_create_refuses_is_not_counted() { assert_eq!(failure_noted(&caught), Some(U256::from(1)), "{case}"); assert_eq!( caught.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + at_start, write_records: 2 }, - "{case}: the code went with the creation", + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + at_start, + write_records: 2, + state_growth: 1 + }, + "{case}: the code went with the creation; the slot is new", ); if inspect { - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + // The creation's budget is the share of what `A` has left, which the code crosses + // with the transaction's limit. + let budget = share(limit - mega_evm::TX_BODY_SIZE); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( probe.creates, [(InstructionResult::Revert, Bytes::from(stop.abi_encode()))], - "{case}: the code was counted, and crossed the limit", + "{case}: the code was counted, and crossed the creation's budget", ); } } @@ -520,15 +717,19 @@ fn run_at(db: MemoryDatabase, tx: mega_evm::MegaTransaction, limit: u64) -> Mega .unwrap() } -fn assert_stopped(outcome: &MegaTransactionOutcome, limit: u64, used: u64) { +/// Asserts the transaction's own frame was stopped crossing a transaction limit of `limit` with a +/// usage of `used`, the transaction having counted `before` before the frame: the frame's budget +/// is what the limit leaves, which the crossing crosses too, so the stop names that budget and +/// what the frame used of it. +fn assert_stopped(outcome: &MegaTransactionOutcome, before: u64, limit: u64, used: u64) { assert!(!outcome.result.is_success() && !outcome.result.is_halt(), "{:?}", outcome.result); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used, - frame_local: false, + limit: limit - before, + used: used - before, + frame_local: true, }) ); } @@ -553,10 +754,14 @@ fn test_a_log_one_byte_over_stops_on_the_log() { assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.result.logs().len(), 1); assert_eq!(fits.result.logs()[0].data.data.len(), data_len as usize); - assert_eq!(fits.usage, LimitUsage { data_size: body + log_bytes + 40, write_records: 1 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + log_bytes + 40, write_records: 1, state_growth: 1 }, + "the log, and the fresh slot" + ); let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + log_bytes - 1); - assert_stopped(&over, body + log_bytes - 1, body + log_bytes); + assert_stopped(&over, body, body + log_bytes - 1, body + log_bytes); assert!(over.result.logs().is_empty(), "the log that crossed was dropped"); assert_eq!(over.usage.data_size, body, "the store after the log never counted"); } @@ -579,17 +784,21 @@ fn test_a_storage_write_one_byte_over_stops_on_the_write() { let fits = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record + 32 + 10); assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.result.logs().len(), 1); - assert_eq!(fits.usage, LimitUsage { data_size: body + record + 42, write_records: 1 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + record + 42, write_records: 1, state_growth: 1 }, + "the fresh slot, and the log" + ); let over = run_at(db(), call(CALLER, A, U256::ZERO, GAS_LIMIT), body + record - 1); - assert_stopped(&over, body + record - 1, body + record); + assert_stopped(&over, body, body + record - 1, body + record); assert!(over.result.logs().is_empty(), "the log after the write never ran"); - assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); } /// A value transfer's recipient is one 40-byte record, and the move leaves a transfer log; both are /// counted when the transaction's frame starts. A limit either of them crosses stops the frame -/// there, before any value moves and before the recipient's code runs. +/// there, before the recipient's code runs, and the value goes back with the stop. #[test] fn test_an_account_write_one_byte_over_stops_on_the_recipient() { let db = || { @@ -605,13 +814,17 @@ fn test_an_account_write_one_byte_over_stops_on_the_recipient() { let fits = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), body + start + record); assert!(fits.result.is_success(), "{:?}", fits.result); assert_eq!(fits.state[&B].info.balance, U256::from(1)); - assert_eq!(fits.usage, LimitUsage { data_size: body + start + record, write_records: 2 }); + assert_eq!( + fits.usage, + LimitUsage { data_size: body + start + record, write_records: 2, state_growth: 1 }, + "B's account, the transfer log and B's fresh slot; B exists" + ); for limit in [body + record - 1, body + start - 1] { let over = run_at(db(), call(CALLER, B, U256::from(1), GAS_LIMIT), limit); - assert_stopped(&over, limit, body + start); + assert_stopped(&over, body, limit, body + start); assert!(over.result.logs().is_empty(), "limit {limit}: no transfer log"); - assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(over.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!( over.state.get(&B).map(|account| account.info.balance).unwrap_or_default(), U256::ZERO @@ -744,14 +957,15 @@ fn bound_at(code: &Bytes, gas_limit: u64, data_limit: u64) -> Bound { } /// A gas limit above what any write here needs to be counted, at the byte prices in effect: -/// 1,000,000 on top of a new account, a fresh slot and the body, and 64 times the history of two -/// records, which a value call that forwards all but a 64th of its gas pays from the 64th it keeps. +/// 1,000,000 on top of a new account, a fresh slot and the body, and 50 times the history of two +/// records, which a value call that forwards all but 2 per cent of its gas pays from the fiftieth +/// it keeps. fn high_bound() -> u64 { 1_000_000 + account_state_gas() + slot_state_gas() + body_history(0) + - 64 * history(2 * WRITE_RECORD_SIZE) + 50 * history(2 * WRITE_RECORD_SIZE) } /// The smallest gas limit at which `code`'s write is counted rather than run out of gas. @@ -790,9 +1004,9 @@ const FRESH_SLOT_COUNTED_AT: u64 = 152_306; /// out-of-gas boundary down by exactly the record's history, at a storage write, a log and a /// `SELFDESTRUCT` alike. /// -/// A `SELFDESTRUCT` that moves value counts its transfer log with its beneficiary's record, in one -/// check, so the two cross together; the log is data size and not history, so the boundary moves -/// by the record's history alone. +/// A `SELFDESTRUCT` that moves value counts its transfer log with its two records — the account +/// it clears and its beneficiary — in one check, so the three cross together; the log is data +/// size and not history, so the boundary moves by the records' history alone. #[test] fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { let selfdestruct = BytecodeBuilder::default().push_address(B).append(SELFDESTRUCT).build(); @@ -802,8 +1016,8 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported() { ( "a SELFDESTRUCT that moves value", selfdestruct, - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, ), ]; for (name, code, bytes, history_bytes) in sites { @@ -863,15 +1077,14 @@ fn test_the_fresh_slot_boundary_is_the_sum_of_its_parts() { assert_eq!(record_history, WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE); } -/// The bytes a value call's start counts on the caller's lane, its own account's record, and on -/// the frame's lane, the recipient's record and the transfer log. -const START_ON_THE_CALLER: u64 = WRITE_RECORD_SIZE; -const START_ON_THE_FRAME: u64 = WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; +/// The bytes a value call's start counts on the pool of the frame it starts: the caller's record +/// and the recipient's, and the transfer log. +const START: u64 = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; -/// A transaction limit the start of [`value_call_to_fresh`] fits: the caller's record, and room -/// for the frame's lane under the 98% share the new frame is given of what the caller has left. +/// A transaction limit the start of [`value_call_to_fresh`] fits: room for its bytes under the 98% +/// share the new frame is given of what the caller has left. fn start_fits() -> u64 { - mega_evm::TX_BODY_SIZE + START_ON_THE_CALLER + child_room(START_ON_THE_FRAME) + mega_evm::TX_BODY_SIZE + child_room(START) } /// At a frame start the order is the other way round, and so is the rule's outcome: the caller @@ -888,7 +1101,7 @@ fn start_fits() -> u64 { fn test_a_frame_start_is_charged_before_its_records_are_counted() { let code = value_call_to_fresh(); // `A`'s account and `FRESH`'s, and the transfer log: 240 bytes on top of the body. - let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let start = START; let crosses = mega_evm::TX_BODY_SIZE + start - 1; let fits = start_fits(); let charged_at = gas_where_the_write_is_counted(&code, crosses); @@ -905,25 +1118,26 @@ fn test_a_frame_start_is_charged_before_its_records_are_counted() { ); assert_eq!( started.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 }, - "the frame started and its records were kept, not refused on the frame's budget", + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2, state_growth: 1 }, + "the frame started and its records were kept, not refused on the frame's budget; FRESH is \ + new", ); } -/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but a 64th -/// keeps a 64th one gas short of the price of the two records its value call makes, under a +/// The frame-start order, one gas short by hand [S7.28]: a caller that forwards all but 2 per cent +/// keeps a fiftieth one gas short of the price of the two records its value call makes, under a /// limit those records would cross. The caller pays for the records before they are counted, so /// it runs out of gas first — a halt, no stop, nothing counted beyond the body — and the limit -/// never sees the start. One gas more, the 64th pays the records, they are counted, and the same -/// limit answers the start with the stop, which the caller catches; under a limit they fit, the -/// frame starts. +/// never sees the start. One gas more, the fiftieth pays the records, they are counted, and the +/// same limit answers the start with the stop, which the caller catches; under a limit they fit, +/// the frame starts. /// /// The gas limit is the call's intrinsic 15,000, the body's history, the caller's sixteen gas of /// pushes, the `CALL`'s regular gas — the value transfer, the cold recipient and the new account, /// 11,300, 3,000 and nothing at the schedule's prices — the recipient's state gas (charged before -/// the split), and what the caller must hold at the split for its 64th to be the records' price -/// less one: `64 (price − 1) + 63` (`constants`: the two byte prices in effect; 690,755 at the -/// spec's prices). +/// the split), and what the caller must hold at the split for its fiftieth to be the records' +/// price less one: `50 (price − 1) + 49` (`constants`: the two byte prices in effect; 592,195 at +/// the spec's prices). #[test] fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they_would_cross() { // Records that cost nothing leave no price to be short of, and records priced at a fraction @@ -932,7 +1146,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they return; } let records = history(2 * WRITE_RECORD_SIZE); - let held_at_the_split = 64 * (records - 1) + 63; + let held_at_the_split = holding_to_keep(records - 1); let params = mega_evm::satin_gas_params(); let value_call = params.get(GasId::transfer_value_cost()) + params.get(GasId::warm_storage_read_cost()) + @@ -940,7 +1154,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they params.get(GasId::new_account_cost()); let gas_limit = 15_000 + body_history(0) + 16 + value_call + account_state_gas() + held_at_the_split; - let start = START_ON_THE_CALLER + START_ON_THE_FRAME; + let start = START; let crosses = mega_evm::TX_BODY_SIZE + start - 1; let fits = start_fits(); let db = || funded().account_code(A, value_call_to_fresh()).account_balance(A, U256::from(1)); @@ -958,7 +1172,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they assert_eq!(short.limit_exceeded, None, "under a limit of {limit}: no limit saw the start"); assert_eq!( short.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "under a limit of {limit}: nothing was counted beyond the body", ); assert_eq!(short.gas.history, body_history(0), "under a limit of {limit}"); @@ -970,16 +1184,20 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they assert!(stopped.result.is_success(), "the caller catches the stop: {:?}", stopped.result); assert_eq!( read_the_answer(stopped.result.output().expect("A answers")), - Answer::Stop(LimitKind::DataSize, crosses), - "the start was answered with the stop", + Answer::Stop(LimitKind::DataSize, share(crosses - mega_evm::TX_BODY_SIZE)), + "the start was answered with the stop of the budget it starts with", + ); + assert_eq!( + stopped.usage, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 } ); - assert_eq!(stopped.usage, LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }); let started = run_at(db(), call(CALLER, A, U256::ZERO, gas_limit + 1), fits); assert!(started.result.is_success(), "one gas more, the frame starts: {:?}", started.result); assert_eq!( started.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2 } + LimitUsage { data_size: mega_evm::TX_BODY_SIZE + start, write_records: 2, state_growth: 1 }, + "A's account and FRESH's, and the transfer log; FRESH is new" ); assert_eq!(started.gas.history, body_history(0) + records); assert_eq!(started.gas.state, account_state_gas()); @@ -988,7 +1206,7 @@ fn test_a_caller_one_gas_short_of_its_records_runs_out_of_gas_under_a_limit_they return; } assert_eq!(records, 2 * 40 * 88); - assert_eq!(gas_limit, 690_755); + assert_eq!(gas_limit, 592_195); } /* ---------- a child frame's write, and the order where the reservoir runs out ---------- */ @@ -1062,8 +1280,8 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported_at_a_childs_write ( "a SELFDESTRUCT that moves value", selfdestruct_to_c(), - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, ), ]; for (name, code, bytes, history_bytes) in sites { @@ -1100,8 +1318,9 @@ fn test_whichever_of_gas_and_data_size_binds_first_is_reported_at_a_childs_write } /// Above the cap, where a reservoir one gas short of a record's history makes the order visible -/// [S7.27]: the record's history draws the reservoir first and spills its last gas onto the -/// child, which was forwarded exactly the gas of its write and has none left. Counted under a +/// [S7.27]: the record's history draws the reservoir share the child was given first and spills +/// its last gas onto the child, which was forwarded exactly the gas of its write and has none +/// left. Counted under a /// limit it crosses, the record is refused and nothing is charged — the transaction stops, and /// the spill the child could not pay is never asked of it. A charge made before the check would /// have run the child out of gas instead, and the limit would have reported nothing. Under a @@ -1123,7 +1342,8 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ params.get(GasId::cold_storage_cost()) + params.get(GasId::sstore_set_without_load_cost()); // (site, code, the child's regular gas up to and including the write, the state gas the write - // adds, the bytes the limit counts, the record's history bytes, the records kept) + // adds, the bytes the limit counts, the record's history bytes, the records kept, the new + // accounts and slots kept: the fresh slot, and `C`, which the destruction's wei creates) let sites = [ ( "a fresh slot", @@ -1133,6 +1353,7 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ WRITE_RECORD_SIZE, WRITE_RECORD_SIZE, 1, + 1, ), ( "a log of one byte", @@ -1142,26 +1363,33 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ mega_evm::LOG_BASE_SIZE + 1, mega_evm::LOG_BASE_SIZE + 1, 0, + 0, ), ( "a SELFDESTRUCT that moves value", selfdestruct_to_c(), 3 + (5_000 + params.selfdestruct_cost(true, true)), account_state_gas(), - WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - WRITE_RECORD_SIZE, + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + 2 * WRITE_RECORD_SIZE, + 2, 1, ), ]; let body = body_history(0); - for (name, code, counted_at, state, bytes, history_bytes, records) in sites { + for (name, code, counted_at, state, bytes, history_bytes, records, growth) in sites { let record = history(history_bytes); - let reservoir = body + state + record - 1; + // `A` holds what the body leaves of the reservoir, and hands `B` one gas short of the + // write's state and history, keeping the rest. + let given = state + record - 1; + let reservoir = body + reservoir_giving(given); + let a_keeps = reservoir - body - given; let gas_limit = TX_GAS_LIMIT_CAP + reservoir; let crosses = mega_evm::TX_BODY_SIZE + bytes - 1; let fits = mega_evm::TX_BODY_SIZE + child_room(bytes); let run = |forward, limit| child_outcome(&code, forward, gas_limit, limit); - let body_only = LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }; + let body_only = + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }; // One gas short of the write itself: an out-of-gas before any record exists, under either // limit, with the reservoir untouched beyond the body. @@ -1178,8 +1406,8 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ assert!(matches!(child_bound(&refused), Bound::DataSize), "{name}: {:?}", refused.result); assert_eq!( read_the_answer(refused.result.output().expect("A answers")), - Answer::Stop(LimitKind::DataSize, crosses), - "{name}: the record crossed the transaction's limit", + Answer::Stop(LimitKind::DataSize, share(crosses - mega_evm::TX_BODY_SIZE)), + "{name}: the record crossed the child's budget and the transaction's limit", ); assert_eq!(refused.gas.history, body, "{name}: the refused record was not charged"); assert_eq!(refused.gas.state, 0, "{name}: the stop gave the state gas back"); @@ -1195,16 +1423,26 @@ fn test_a_record_a_limit_refuses_is_not_charged_where_the_reservoir_has_one_gas_ assert_eq!(kept.gas.state, 0, "{name}"); assert_eq!(kept.gas.reservoir_remaining, reservoir - body, "{name}"); - // One gas more pays the spill: the write is kept, and the reservoir is spent to the last - // gas. + // One gas more pays the spill: the write is kept, and the share is spent to the last gas. + // What `A` kept comes back with the transaction's own frame, which merged `B`'s one gas + // of spill, and unwinds it first: all of it when `A` kept nothing, as below a reservoir + // of 50, where two per cent rounds down to nothing. let paid = run(counted_at + 1, fits); assert!(matches!(child_bound(&paid), Bound::Success), "{name}: {:?}", paid.result); - assert_eq!(paid.gas.reservoir_remaining, 0, "{name}: the reservoir spent to the last gas"); + assert_eq!( + paid.gas.reservoir_remaining, + a_keeps.saturating_sub(1), + "{name}: the share spent to the last gas" + ); assert_eq!(paid.gas.history, body + record, "{name}: the body and the record"); assert_eq!(paid.gas.state, state, "{name}: the state the write added"); assert_eq!( paid.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + bytes, write_records: records }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + bytes, + write_records: records, + state_growth: growth + }, "{name}", ); } @@ -1372,7 +1610,11 @@ fn test_a_child_gets_98_percent_of_what_its_parent_has_left_in_slots() { let outcome = run_slots(db, room_for(100)); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); - assert_eq!(outcome.usage, LimitUsage { data_size: room_for(kept), write_records: kept }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: room_for(kept), write_records: kept, state_growth: kept }, + "{name}: every slot kept is fresh" + ); if name == "a parent that writes after its child crossed" { let written = |address: Address| { outcome.state.get(&address).is_some_and(|account| { @@ -1398,7 +1640,12 @@ fn test_the_body_and_the_execution_add_up_to_the_stop() { call_with_data(CALLER, A, Bytes::from(vec![0xab; calldata as usize]), SLOTS_GAS_LIMIT), limit, ); - assert_stopped(&outcome, limit, limit + WRITE_RECORD_SIZE); + assert_stopped( + &outcome, + mega_evm::TX_BODY_SIZE + calldata, + limit, + limit + WRITE_RECORD_SIZE, + ); } } @@ -1447,16 +1694,16 @@ fn call_and_return_its_output(target: Address) -> Bytes { } /// A creation too big for its share still bumps its creator's nonce, and the creator's record of -/// that write outlives the creation: it lands on the creator's own lane. The creator is held to +/// that write outlives the creation: it is drawn on the creator's own pool. The creator is held to /// its budget with it before it runs on. /// -/// `A` calls `B` with 4,000 bytes left, so `B` may keep 3,920. `B` logs, then creates: the -/// creation's start records the created account and `B`'s nonce, 80 bytes against a share below -/// 80, so it is stopped with room to spare in the transaction. When the log left `B` 40 bytes, -/// `B` keeps the nonce record at exactly its budget and succeeds. When it left 39, the record puts -/// `B` one byte over: `B` reverts alone, its log and its nonce with it, and `A` resumes and -/// returns `B`'s revert. Either way the history the transaction pays is that of the bytes it -/// keeps. +/// `A` calls `B` with 4,000 bytes left, so `B` may keep 3,920. `B` logs, then creates: `B`'s nonce +/// record is counted on `B` first, and the creation's start records the created account, 40 +/// bytes against a share of what the record left `B`, which is below 40, so it is stopped with +/// room to spare in the transaction. When the log left `B` 40 bytes, `B` keeps the nonce record at +/// exactly its budget and succeeds. When it left 39, the record puts `B` one byte over: `B` +/// reverts alone, its log and its nonce with it, and `A` resumes and returns `B`'s revert. Either +/// way the history the transaction pays is that of the bytes it keeps. #[test] fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { const A_BUDGET: u64 = 4_000; @@ -1484,7 +1731,11 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { assert_eq!(fits.limit_exceeded, None, "{case}"); assert_eq!( fits.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE + b_budget, write_records: 1 }, + LimitUsage { + data_size: mega_evm::TX_BODY_SIZE + b_budget, + write_records: 1, + state_growth: 0 + }, "{case}: B keeps the nonce record at exactly its budget", ); assert_eq!(fits.gas.history, history_of(fits.usage), "{case}"); @@ -1501,7 +1752,7 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { assert_eq!(over.limit_exceeded, None, "{case}: a frame budget below is no stop"); assert_eq!( over.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{case}: B's log and nonce record went with its revert", ); assert_eq!(over.gas.history, history_of(over.usage), "{case}: and their history"); @@ -1516,3 +1767,235 @@ fn test_a_failed_creations_nonce_record_holds_its_creator_to_its_budget() { } } } + +/// Halts `B` in the first `step` it is handed once a creation it made returned into it, and counts +/// the times it was. +#[derive(Default)] +struct HaltsTheResume { + returned: bool, + handed: usize, +} + +impl Inspector, EthInterpreter> for HaltsTheResume { + fn create_end( + &mut self, + _: &mut MegaContext, + inputs: &CreateInputs, + _: &mut CreateOutcome, + ) { + self.returned |= inputs.caller() == B; + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if self.returned && interp.input.target_address == B { + self.handed += 1; + interp.halt(InstructionResult::OutOfGas); + } + } +} + +/// The stop the engine sets on a creator its failed creation's nonce record left over its budget +/// is the creator's next action: revm returns it before a `step`, so an inspector that would halt +/// the creator on its resume is never handed it, and the run is the plain run, the creator's +/// revert on its budget, in a debug build and a release build alike. +#[test] +fn test_an_inspector_that_would_halt_a_resumes_stop_is_never_handed_it() { + const A_BUDGET: u64 = 4_000; + let logged = share(A_BUDGET) - (WRITE_RECORD_SIZE - 1) - 32; + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(mega_evm::TX_BODY_SIZE + A_BUDGET); + let db = || { + funded() + .account_code(A, call_and_return_its_output(B)) + .account_code(B, log_then_create(logged, false)) + }; + let tx = call(CALLER, A, U256::ZERO, GAS_LIMIT); + let plain = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .execute_transaction(tx.clone()) + .unwrap(); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: share(A_BUDGET) }; + assert_eq!(plain.result.output().unwrap().as_ref(), stop.abi_encode(), "B returns the stop"); + let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) + .with_inspector(HaltsTheResume::default()); + let halted = evm.execute_transaction(tx).unwrap(); + assert!(evm.inspector().returned, "B's creation returned into it"); + assert_eq!(evm.inspector().handed, 0, "B is not handed to a step before its stop"); + assert_eq!(halted.result_and_state, plain.result_and_state); + assert_eq!(halted.gas, plain.gas); + assert_eq!(halted.usage, plain.usage); +} + +/// A creation that counts nothing at its start runs, whatever its creator's nonce record will +/// cost: the record is counted on the creator once the creation returned, held to the creator's +/// budget before the creator runs on. +/// +/// `A` funds `X`, the address `B`'s empty `CREATE2` lands on, keeping two records and the transfer +/// log, and then calls `B`, whose budget is the share of the 39 bytes `A` has left. `B`'s creation +/// records nothing of its own — `X` is changed already, and it carries no endowment — so it starts +/// and returns a success. The record of `B`'s nonce then crosses `B`'s budget: `B` returns the stop +/// of that budget before it runs on, the creation and its nonce going with its revert, and `A` +/// resumes and keeps what it kept. +#[test] +fn test_a_creation_counting_nothing_runs_and_its_creator_is_stopped_at_the_return() { + let x = B.create2(B256::ZERO, keccak256([])); + let a = then_call(BytecodeBuilder::default().call(x, U256::from(1)), B).append(STOP).build(); + let b = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .append(CREATE2) + .append(POP) + .append(STOP) + .build(); + let kept = mega_evm::TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let limit = kept + WRITE_RECORD_SIZE - 1; + // `B`'s budget: the share of what `A` has left once its transfer is kept, which the nonce + // record crosses. + let b_budget = share(limit - kept); + let b_stop = Bytes::from( + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: b_budget }.abi_encode(), + ); + for inspect in [false, true] { + let db = funded() + .account_code(A, a.clone()) + .account_balance(A, U256::from(1)) + .account_code(B, b.clone()); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + assert!(outcome.result.is_success(), "inspect {inspect}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "inspect {inspect}: A caught it"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: kept, write_records: 2, state_growth: 1 }, + "inspect {inspect}: A's transfer alone, which creates X", + ); + assert!(outcome.state.get(&B).is_none_or(|b| b.info.nonce == 0), "inspect {inspect}"); + assert_eq!(outcome.state[&x].info.nonce, 0, "inspect {inspect}: nothing created at X"); + if inspect { + let probe = evm.inspector(); + assert_eq!(probe.creates.len(), 1, "one creation: {:?}", probe.creates); + assert!(probe.creates[0].0.is_ok(), "the creation ran: {:?}", probe.creates); + assert!( + probe.calls.contains(&(B, InstructionResult::Revert, b_stop.clone())), + "B returns the stop of its own budget once the creation returned into it: {:?}", + probe.calls, + ); + } + } +} + +/// A failed frame's counts go back to what the frames kept when its start began, while an Oracle +/// hint, which is on no frame, stays: a frame that took back a record a frame above it made, sent a +/// hint into the room that freed, and failed, leaves the transaction over its limit. The frame it +/// returns into is held to the transaction's limit before it runs on, and stops, whether the frame +/// below reverted, halted or was itself stopped. +/// +/// `A` writes a fresh slot and calls `B`; `B` calls back into `A`, which writes the slot back, then +/// sends the Oracle a hint that fills the transaction's limit, and reverts, halts on an invalid +/// opcode, or writes a fresh slot of its own, which crosses the transaction's limit and stops `B`. +/// Each way `B`'s failure restores the slot's record and the hint stays: `A` returns the +/// transaction's stop as it resumes, and the transaction keeps its body and the hint, its limit +/// exactly. +#[test] +fn test_a_caller_a_failed_callee_left_over_the_transaction_limit_is_stopped() { + let hint = Bytes::from( + IOracle::sendHintCall { topic: B256::repeat_byte(0x7a), data: Bytes::from(vec![0x5a; 64]) } + .abi_encode(), + ); + let hint_bytes = hint.len() as u64; + // `A`: called by the transaction, a fresh slot and a call to `B`; called back with a byte of + // calldata, the slot written back. + let entry = then_call(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)), B) + .append(STOP) + .build_vec(); + let reentry = 4 + entry.len(); + let a = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(u8::try_from(reentry).unwrap()) + .append(JUMPI) + .append_many(entry) + .append(JUMPDEST) + .sstore(U256::ZERO, U256::ZERO) + .stop() + .build(); + assert_eq!(a[reentry], JUMPDEST); + let limit = mega_evm::TX_BODY_SIZE + hint_bytes; + let stop = + Bytes::from(MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }.abi_encode()); + /// How `B` ends once it sent the hint. + #[derive(Clone, Copy, Debug, PartialEq)] + enum Ending { + Reverts, + Halts, + IsStopped, + } + for ending in [Ending::Reverts, Ending::Halts, Ending::IsStopped] { + for inspect in [false, true] { + // `B`: calls `A` with one byte of calldata, sends the hint, and reverts, halts, or + // writes a fresh slot past the transaction's limit, which its own budget + // holds room for: `A`'s take-back merged into it. + let b = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append_many([PUSH0, PUSH0]) + .push_address(A) + .append_many([GAS, CALL, POP]) + .mstore(0, &hint) + .append_many([PUSH0, PUSH0]) + .push_number(hint_bytes) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]); + let b = match ending { + Ending::Reverts => b.revert(), + Ending::Halts => b.append(INVALID), + Ending::IsStopped => b.sstore(U256::from(1), U256::from(1)).stop(), + }; + let db = funded() + .account_code(A, a.clone()) + .account_code(B, b.build()) + .account_code(ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Probe::default()); + Evm::set_inspector_enabled(&mut evm, inspect); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); + let case = format!("B {ending:?}, inspect {inspect}"); + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "{case}: {:?}", + outcome.result + ); + assert_eq!(outcome.result.output().unwrap(), &stop, "{case}: the stop"); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + WRITE_RECORD_SIZE, + frame_local: false, + }), + "{case}: the transaction's limit, which the restored record and the hint cross", + ); + assert_eq!( + outcome.usage, + LimitUsage { data_size: limit, write_records: 0, state_growth: 0 }, + "{case}: the body and the hint, never taken back", + ); + if inspect { + let b_ends = match ending { + Ending::Reverts => (B, InstructionResult::Revert, Bytes::new()), + Ending::Halts => (B, InstructionResult::InvalidFEOpcode, Bytes::new()), + Ending::IsStopped => (B, InstructionResult::Revert, stop.clone()), + }; + assert!( + evm.inspector().calls.contains(&b_ends), + "{case}: B fails as it should, with the stop of the transaction's limit when its \ + slot crossed it: {:?}", + evm.inspector().calls, + ); + } + } + } +} diff --git a/crates/mega-evm/tests/satin/data_size_counts.rs b/crates/mega-evm/tests/satin/data_size_counts.rs index 24c041faf..5c1069362 100644 --- a/crates/mega-evm/tests/satin/data_size_counts.rs +++ b/crates/mega-evm/tests/satin/data_size_counts.rs @@ -12,7 +12,7 @@ use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ test_utils::{BytecodeBuilder, MemoryDatabase}, EvmTxRuntimeLimits, LimitUsage, MegaEvm, MegaTransaction, AUTHORIZATION_SIZE, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + LOG_TOPIC_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ @@ -23,7 +23,8 @@ use revm::{ }; use crate::common::{ - call, call_with_data, constructor_returning, context, create, execute, execute_under, + call, call_with_data, constructor_returning, context, create, execute, execute_under, grown, + records_and_moves, }; const CALLER: Address = address!("0000000000000000000000000000000000400000"); @@ -40,7 +41,7 @@ fn funded() -> MemoryDatabase { /// What a transaction keeps: its body with `extra` body bytes, `bytes` more from its execution, /// and `records` write records among those. const fn kept(extra: u64, bytes: u64, records: u64) -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE + extra + bytes, write_records: records } + LimitUsage { data_size: TX_BODY_SIZE + extra + bytes, write_records: records, state_growth: 0 } } /// `records` write records and nothing else. @@ -48,11 +49,6 @@ const fn records(records: u64) -> LimitUsage { kept(0, records * WRITE_RECORD_SIZE, records) } -/// `records` write records and the transfer logs of `moves` value movements. -const fn records_and_moves(records: u64, moves: u64) -> LimitUsage { - kept(0, records * WRITE_RECORD_SIZE + moves * TRANSFER_LOG_SIZE, records) -} - /// A contract that `CREATE`s `init` and stops. fn factory(init: &Bytes) -> Bytes { BytecodeBuilder::default() @@ -166,7 +162,7 @@ fn test_what_each_transaction_keeps() { "a value transfer to an account that does not exist", funded(), call(CALLER, CALLEE, U256::from(1), GAS_LIMIT), - records_and_moves(1, 1), + grown(records_and_moves(1, 1), 1), ), ( "a value transfer to the sender itself, which moves nothing", @@ -178,7 +174,7 @@ fn test_what_each_transaction_keeps() { "a creation deploying 10 bytes", funded(), create(CALLER, init.clone(), GAS_LIMIT), - kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 1), + grown(kept(init.len() as u64, WRITE_RECORD_SIZE + 10, 1), 1), ), ( "a creation endowing the account it creates", @@ -188,19 +184,19 @@ fn test_what_each_transaction_keeps() { tx.0.base.value = U256::from(1); tx }, - records_and_moves(1, 1), + grown(records_and_moves(1, 1), 1), ), ( "a factory creating a contract of 10 bytes", with_code(factory(&init)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - kept(0, 2 * WRITE_RECORD_SIZE + 10, 2), + grown(kept(0, 2 * WRITE_RECORD_SIZE + 10, 2), 1), ), ( "a storage write", with_code(BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build()), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records(1), + grown(records(1), 1), ), ( "a storage read", @@ -240,10 +236,11 @@ fn test_what_each_transaction_keeps() { kept(0, 0, 0), ), ( - "a value transfer the recipient passes on: its account is recorded once", + "a value transfer the recipient passes on: its account is recorded once, and the wei it \ + passes on creates LIBRARY", with_code(call_to(CALL, LIBRARY, 1).stop().build()), call(CALLER, CALLEE, U256::from(100), GAS_LIMIT), - records_and_moves(2, 2), + grown(records_and_moves(2, 2), 1), ), ( "a child that writes a slot and halts", @@ -263,21 +260,23 @@ fn test_what_each_transaction_keeps() { records(1), ), ( - "a SELFDESTRUCT that moves value to an existing account", + "a SELFDESTRUCT that moves value to an existing account: the account it clears, and \ + the beneficiary", with_code( BytecodeBuilder::default().push_address(EXISTING).append(SELFDESTRUCT).build(), ) .account_balance(CALLEE, U256::from(1_000)) .account_balance(EXISTING, U256::from(1)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records_and_moves(1, 1), + records_and_moves(2, 1), ), ( - "a SELFDESTRUCT that moves value to the sender: the body counts the sender", + "a SELFDESTRUCT that moves value to the sender: the account it clears alone, the \ + sender's account being changed already", with_code(BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build()) .account_balance(CALLEE, U256::from(1_000)), call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT), - records_and_moves(0, 1), + records_and_moves(1, 1), ), ( "a SELFDESTRUCT to itself, which moves nothing", @@ -314,7 +313,7 @@ fn test_a_reverted_childs_write_and_write_back_leave_its_callers_write() { let db = funded().account_code(CALLEE, parent).account_code(LIBRARY, child); let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage, records(1)); + assert_eq!(outcome.usage, grown(records(1), 1), "the caller's fresh slot alone"); assert_eq!( outcome.state[&CALLEE].storage.get(&CALLER_SLOT).map(|slot| slot.present_value), Some(U256::from(1)), @@ -401,6 +400,6 @@ fn test_each_transaction_counts_from_zero() { for run in 0..2 { let result = evm.transact_raw(call(CALLER, CALLEE, U256::ZERO, GAS_LIMIT)).unwrap(); assert!(result.result.is_success(), "{:?}", result.result); - assert_eq!(evm.ctx().additional_limit().usage(), records(1), "run {run}"); + assert_eq!(evm.ctx().limit_usage(), grown(records(1), 1), "run {run}: a fresh slot"); } } diff --git a/crates/mega-evm/tests/satin/deposit_charge.rs b/crates/mega-evm/tests/satin/deposit_charge.rs index 3f05874bc..6ebb66a40 100644 --- a/crates/mega-evm/tests/satin/deposit_charge.rs +++ b/crates/mega-evm/tests/satin/deposit_charge.rs @@ -13,8 +13,9 @@ //! //! Every gas figure here is built by hand from the spec and the schedule, never read off a run //! of the engine. The creation's regular budget is set exactly: `A` calls the creator `B` with an -//! explicit gas, `B` spends a known amount before its `CREATE`, and the EIP-150 split forwards all -//! but a 64th of what `B` holds, which [`holding_for`] inverts. Each case is one gas short of a +//! explicit gas, `B` spends a known amount before its `CREATE`, and the split forwards all but 2 +//! per cent of what `B` holds under Satin (all but a 64th under Osaka's EIP-150, on the neutral +//! configuration), which [`holding_for`] inverts. Each case is one gas short of a //! charge, or exactly enough, and reads every ledger against its derivation. The data-size limit //! holds the deposit after the last of those charges and before `return_create` commits it: with //! exactly enough gas a limit the deposit crosses stops the creation, and one gas short the @@ -46,7 +47,7 @@ use crate::{ const CALLER: Address = address!("0000000000000000000000000000000000a00000"); /// Calls `B` with a chosen gas and stops. const A: Address = address!("0000000000000000000000000000000000a00001"); -/// Creates the code with all but a 64th of what it has, and stops. +/// Creates the code with all the gas the split forwards, and stops. const B: Address = address!("0000000000000000000000000000000000a00002"); /// The words of zeros the creation deploys, and their bytes. @@ -55,9 +56,9 @@ const CODE_LEN: u64 = DEPLOYED_WORDS * 32; /// The words of memory the init code touches before it returns, so that the creation is forwarded /// millions of gas at any byte price: below the execution cap `B` pays the history of the -/// creation's two write records out of the 64th it keeps, which must cover them whatever a +/// creation's two write records out of the fiftieth it keeps, which must cover them whatever a /// history byte costs — at the dearest price the grid runs, 1,000 a byte, the two records are -/// 80,000 gas, and a 64th of the memory's cost alone is 82,400. [`call_gas`] asserts it. +/// 80,000 gas, and a fiftieth of the memory's cost alone is 105,472. [`call_gas`] asserts it. const BURNT_WORDS: u64 = 51_200; /// The reservoir the runs above the execution cap carry: ample for every charge here. @@ -81,7 +82,7 @@ enum Pool { impl Pool { /// The transaction's gas limit: above the cap by [`RESERVOIR`]; below it, room for `A` to - /// forward the largest gas any case calls `B` with — a 64th more than the forward, and a + /// forward the largest gas any case calls `B` with — a 49th more than the forward, and a /// million of slack — which stays below the cap at any byte price the grid runs; or Osaka's /// own ceiling (EIP-7825 holds a transaction to 2^24 gas). fn gas_limit(self) -> u64 { @@ -89,7 +90,7 @@ impl Pool { Self::AboveCap => TX_GAS_LIMIT_CAP + RESERVOIR, Self::BelowCap => { let largest = call_gas(Self::BelowCap, deposits_at(Self::BelowCap)); - let limit = (largest * 64).div_ceil(63) + 1_000_000; + let limit = (largest * 50).div_ceil(49) + 1_000_000; assert!(limit <= TX_GAS_LIMIT_CAP, "below the cap at these prices: {limit}"); limit } @@ -121,6 +122,8 @@ impl Pool { /// `MSTORE` that puts the init code in memory, with the first word of memory; three `PUSH8`; /// EIP-3860's 2 gas for the one word of init code; and `CREATE`'s own charge, Amsterdam's /// 12,000 under Satin and 32,000 under Osaka. + /// + /// The forward's quotient is in [`Pool::quotient`]. const fn b_before_the_split(self) -> u64 { let create = match self { Self::AboveCap | Self::BelowCap => 12_000, @@ -130,6 +133,17 @@ impl Pool { } } +impl Pool { + /// The quotient of the split: a caller keeps `holding / quotient`, 50 under Satin, Rex6's + /// 98/100, and EIP-150's 64 under Osaka. + const fn quotient(self) -> u64 { + match self { + Self::AboveCap | Self::BelowCap => 50, + Self::NeutralOsaka => 64, + } + } +} + /* ---------- the figures by hand ---------- */ /// What `B` spends after the creation returns: the `POP` of its answer. @@ -189,12 +203,12 @@ fn deposits_at(pool: Pool) -> u64 { } } -/// The least gas `B` can hold at its `CREATE`'s split for the creation to be forwarded exactly -/// `forward`: EIP-150 forwards all but a 64th, `r - r / 64`, which `64 (f / 63) + f mod 63` -/// inverts. -fn holding_for(forward: u64) -> u64 { - let holding = 64 * (forward / 63) + forward % 63; - assert_eq!(holding - holding / 64, forward, "the split inverted"); +/// A gas `B` can hold at its `CREATE`'s split for the creation to be forwarded exactly `forward` in +/// `pool`: the split forwards `r - r / q`, which `q (f / (q - 1)) + f mod (q - 1)` inverts. +fn holding_for(pool: Pool, forward: u64) -> u64 { + let q = pool.quotient(); + let holding = q * (forward / (q - 1)) + forward % (q - 1); + assert_eq!(holding - holding / q, forward, "the split inverted"); holding } @@ -207,11 +221,11 @@ fn call_gas(pool: Pool, forward: u64) -> u64 { Pool::BelowCap => created_account_state_gas(), Pool::AboveCap | Pool::NeutralOsaka => 0, }; - let holding = holding_for(forward); + let holding = holding_for(pool, forward); if pool == Pool::BelowCap { assert!( - holding / 64 >= history(2 * WRITE_RECORD_SIZE) + B_AFTER, - "B's 64th pays the creation's two records and B's POP at these prices", + holding / pool.quotient() >= history(2 * WRITE_RECORD_SIZE) + B_AFTER, + "what B keeps pays the creation's two records and B's POP at these prices", ); } holding + pool.b_before_the_split() + spilled @@ -437,7 +451,11 @@ fn assert_runs_out(name: &str, pool: Pool, forward: u64, left: u64, state_charge assert!(!deployed(&outcome), "{name}: no code is left"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0 + }, "{name}: the creator's nonce record outlives the creation, nothing else does", ); assert_ledgers(name, pool, forward, &outcome, 0, TX_BODY_SIZE + WRITE_RECORD_SIZE); @@ -469,8 +487,9 @@ fn assert_deposits(name: &str, pool: Pool, forward: u64) { let bytes = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + CODE_LEN; assert_eq!( outcome.usage, - LimitUsage { data_size: bytes, write_records: 2 }, - "{name}: the creator's nonce, the created account, and the code", + LimitUsage { data_size: bytes, write_records: 2, state_growth: 1 }, + "{name}: the creator's nonce, the created account, and the code; the created account is \ + new", ); assert_ledgers(name, pool, regular_deposit(pool), &outcome, state, bytes); } diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 4b0a209e6..75da0292b 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -1,17 +1,17 @@ //! Gas detention against EIP-7708 transfer logs: value that moves after a read of volatile data. //! //! The two meet where a frame starts and at `SELFDESTRUCT`. A frame start counts its transfer log -//! with its records before revm decides the frame — revm then moves the value, answers the frame -//! or refuses it on the caller's account — and a precompile started after a read runs on what the -//! compute limit leaves its frame. A `SELFDESTRUCT` counts its log with its beneficiary's record -//! once the opcode completed, and revm journals the move before the opcode's last charge, which -//! the cap can fail. +//! with its records, held to the limits once revm decided the frame — revm moves the value, answers +//! the frame or refuses it on the caller's account — and a precompile started after a read runs on +//! what the compute limit leaves its frame. A `SELFDESTRUCT` counts its log with its records once +//! the opcode completed, and revm journals the move before the opcode's last charge, which the cap +//! can fail. //! //! Whatever detention does to the movement, the transfer logs a receipt carries are the ones the //! data size kept: a transaction keeps its body, forty bytes a write record and 160 a transfer //! log, and a frame the cap stops keeps nothing, its movement and its log included. A debug build -//! also asserts at every frame start that revm refused exactly the start predicted and journaled -//! exactly the log counted, so every case below runs that check too. +//! also asserts at every start revm made and kept that it journaled exactly the log counted, so +//! every case below runs that check too. //! //! Each case runs with a read of the block's timestamp first, and with `PUSH0`, which costs the //! same two gas and reads nothing, in its place. @@ -30,9 +30,9 @@ use revm::{ use crate::{ detention::{ - assert_caught, assert_stopped, cold_access, context, failed_status_store, intrinsic, - memory_cost, op, run_on, spin, value_transfer, Calls, Charges, Run, BENEFICIARY, CALLER, - CAP, CHILD, CONTRACT, TIERS, + assert_caught_with_stipends, assert_stopped, assert_stopped_with_stipends, call_stipend, + cold_access, context, failed_status_store, intrinsic, memory_cost, op, run_on, spin, + value_transfer, Calls, Charges, Run, BENEFICIARY, CALLER, CAP, CHILD, CONTRACT, TIERS, }, withheld_gas::{costly_modexp_input, intrinsic_with}, }; @@ -72,8 +72,8 @@ fn calls_with_value(first: u8, to: Address, gas: Option) -> Bytes { /// The regular charges [`calls_with_value`] makes after its first instruction reads, with calldata /// of `len` bytes, up to the call: the read's `POP`; `CALLDATASIZE`, two `PUSH0` and /// `CALLDATACOPY` — its static gas, the copy and the memory it expands — the call's four pushes, -/// the value's and the address's, and `GAS`; and the call's own charges, `call`, less the stipend -/// the callee is given, which nobody paid and is not compute. +/// the value's and the address's, and `GAS`; and the call's own charges, `call`, in full: the +/// stipend revm gives the callee is not taken off, since what the callee runs on it is compute. fn charges_to_the_call(len: u64, call: u64) -> Charges { let words = len.div_ceil(32); Charges::default().then(&[ @@ -91,7 +91,7 @@ fn charges_to_the_call(len: u64, call: u64) -> Charges { 3, 3, 2, - call - 2_300, + call, ]) } @@ -236,10 +236,22 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { let charges = charges_to_the_call(above.len() as u64, call_to_an_empty_precompile()) .then(&[price.unwrap()]); let intrinsic = intrinsic_with(&above, gas_limit); - assert_caught(&detained, intrinsic, charges.left(CAP), &failed_status_store()); + // The call carried value: its stipend, which came back with the answer, is gas the ledger + // never billed. + let left = charges.left(CAP); + assert_caught_with_stipends( + &detained, + intrinsic, + left, + &failed_status_store(), + call_stipend(), + ); // The answer is the stop, having spent nothing. assert_eq!(ended(&calls, MODEXP), (InstructionResult::Revert, 0)); - assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + detained.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_counts_its_transfer_logs(&detained, body, "priced past the allowance"); assert_eq!(balance(&detained, MODEXP), U256::ZERO, "nothing moved"); assert!(plain.outcome.result.is_success()); @@ -266,19 +278,252 @@ fn test_a_value_call_to_a_precompile_after_a_read_keeps_the_log_it_counted() { let left = Charges::default().then(&[price]).left(CAP); assert_eq!(left, CAP); assert_stopped(&detained, plain.outcome.gas.regular - price, left); - assert_eq!(detained.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + detained.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&detained, MODEXP), U256::ZERO, "the transaction's value did not move"); } } +/// A contract that copies its calldata into memory, then, after `first`, calls `to` with it, +/// [`VALUE`] and all its gas, and returns what the call returned or reverted with. +fn calls_with_value_returning(first: u8, to: Address) -> Bytes { + op(BytecodeBuilder::default(), first) + .append_many([CALLDATASIZE, PUSH0, PUSH0, CALLDATACOPY]) + .append_many([PUSH0, PUSH0, CALLDATASIZE, PUSH0]) + .push_number(VALUE) + .push_address(to) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build() +} + +/// A value call to modexp after a read, priced past the allowance and within the forward, is +/// answered without running with gas detention's stop — unless the start it would have made +/// crosses the data size first. The start's records, modexp's and the caller's, and the transfer +/// log of the value it would move are held to the transaction's limit and to the budget its frame +/// would get before detention classifies the answer, so data size wins over compute at one start. +/// +/// Under a transaction limit, or a frame cap, that leaves the start one byte short of its records +/// and its log — which the records alone fit, so the log is what crosses — the call is answered +/// with the data-size stop, naming the budget the start crossed. With room for the start in its +/// frame's share, it is answered with the compute stop. Nothing moves either way, and the +/// transaction keeps its body alone. +#[test] +fn test_a_start_crossing_data_size_and_compute_at_once_is_the_data_size_stop() { + use alloy_sol_types::SolError; + use mega_evm::{LimitKind, MegaLimitExceeded}; + let above = costly_modexp_input(64, 0); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let share = |cap: u64| crate::common::share(cap); + let cap = (start..).find(|cap| share(*cap) == start - 1).expect("a cap whose share is short"); + let room = (start..).find(|room| share(*room) == start).expect("a room whose share fits"); + for gas_limit in TIERS { + let tx = tx_to(CALLER, CONTRACT, &above, 0, gas_limit); + let body = transaction_body_bytes(&tx); + let limits = EvmTxRuntimeLimits::default(); + let rows = [ + // The transaction's own frame gets what the body leaves, and the call's start the + // share of it, which the start crosses before the transaction's limit. + ( + "the transaction's limit", + limits.with_tx_data_size_limit(body + start - 1), + Some(share(start - 1)), + ), + ("the frame cap", limits.with_frame_data_size_limit(cap), Some(start - 1)), + ("room for the start", limits.with_tx_data_size_limit(body + room), None), + ("room under the frame cap", limits.with_frame_data_size_limit(cap + 1), None), + ]; + for (case, limits, data_size) in rows { + let db = accounts(calls_with_value_returning(TIMESTAMP, MODEXP), VALUE); + let (run, _) = run_tx(db, tx.clone(), limits, false); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + let stop = match data_size { + Some(limit) => MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + None => MegaLimitExceeded { + kind: LimitKind::ComputeGas.as_u8(), + limit: run.limit.expect("the read set a limit"), + }, + }; + assert_eq!( + run.outcome.result.output(), + Some(&Bytes::from(stop.abi_encode())), + "{case}: the call's answer" + ); + assert_eq!(balance(&run, MODEXP), U256::ZERO, "{case}: nothing moved"); + let body_alone = LimitUsage { data_size: body, write_records: 0, state_growth: 0 }; + assert_eq!(run.outcome.usage, body_alone, "{case}"); + } + } +} + +/* ---------- a value call's own charges ---------- */ + +/// The ecrecover precompile, whose account is empty. +const ECRECOVER: Address = address!("0000000000000000000000000000000000000001"); +/// A contract that calls [`CONTRACT`] with all its gas and returns what the call returned. +const PARENT: Address = address!("0000000000000000000000000000000000d00023"); + +/// A contract that reads the block's timestamp, then calls `to` with [`VALUE`] and all its gas, +/// and returns what the call returned or reverted with. +fn reads_then_calls_with_value(to: Address) -> Bytes { + op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(VALUE) + .push_address(to) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build() +} + +/// The regular charges [`reads_then_calls_with_value`] makes after its read up to the call's value +/// transfer: the read's `POP`, the call's four `PUSH0`, the pushes of the value and the address, +/// `GAS`, and the call's static gas, the warm access every call pays before its dynamic charges. +fn charges_to_the_transfer() -> Charges { + Charges::default().then(&[2, 2, 2, 2, 2, 3, 3, 2, 100]) +} + +/// A value `CALL`'s own regular charges come before anything it starts, as any opcode's: its +/// static gas, then the value transfer, then a cold access. Under a cap one unit short of the +/// transfer, the transfer is the charge that crosses, whatever the call's target and whether or +/// not the caller can fund the value: the calling frame is stopped at the opcode, before revm +/// decides the start, so no frame starts, nothing moves, nothing is counted, no log is journaled, +/// and a funded call and an unfunded one are billed the same. A caller one frame up catches the +/// stop and ends within the limit. +/// +/// One unit more pays the transfer exactly, and the stop moves to the next regular charge — the +/// cold access, or, for a warm target, the calling frame's own `POP` once the call returned or the +/// precompile's price answered it — with the transaction's whole limit computed. +#[test] +fn test_a_value_calls_own_transfer_crossing_the_cap_stops_its_caller_before_anything_moves() { + use mega_evm::{LimitCheck, LimitKind}; + use revm::context::transaction::{AccessList, AccessListItem, TransactionType}; + + use crate::detention::{execute, stop_data}; + + let cases: [(&str, Address, bool); 4] = [ + ("a cold contract", RECEIVER, false), + ("a warm contract", RECEIVER, true), + ("a precompile", ECRECOVER, false), + ("an account with no code", PAYEE, false), + ]; + let before = charges_to_the_transfer(); + let cap = before.total() + value_transfer() - 1; + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + for gas_limit in TIERS { + for (case, to, warm) in cases { + // An access list warms the target, and a legacy transaction carries none. + let tx_type = if warm { TransactionType::Eip2930 } else { TransactionType::Legacy }; + let tx = |target| { + let warmed = warm.then_some(AccessListItem { address: to, storage_keys: vec![] }); + OpTx(op_transaction(TxEnv { + tx_type: tx_type as u8, + caller: CALLER, + kind: TxKind::Call(target), + gas_limit, + access_list: AccessList(warmed.into_iter().collect()), + ..Default::default() + })) + }; + let body = transaction_body_bytes(&tx(CONTRACT)); + let body_alone = LimitUsage { data_size: body, write_records: 0, state_growth: 0 }; + let stops = MemoryDatabase::default() + .account_code(CONTRACT, BytecodeBuilder::default().stop().build()); + let intrinsic = execute(stops, tx(CONTRACT)).outcome.gas.regular; + let exec = |target, held, cap, inspected| { + let db = accounts(reads_then_calls_with_value(to), held) + .account_code(PARENT, parent.clone()); + let limits = + EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + run_tx(db, tx(target), limits, inspected) + }; + let left = before.clone().then(&[value_transfer()]).left(cap); + assert_eq!(left, value_transfer() - 1, "{case}: the transfer is one unit short"); + + for (target, frame) in [(CONTRACT, "its own frame"), (PARENT, "one frame down")] { + let mut runs = Vec::new(); + for (held, inspected) in [(VALUE, false), (VALUE, true), (VALUE - 1, true)] { + let case = format!("{case}, {frame}, holding {held}, at {gas_limit}"); + let (run, calls) = exec(target, held, cap, inspected); + if target == CONTRACT { + assert_stopped(&run, intrinsic, left); + } else { + let limit = run.limit.expect("the read set a limit"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome); + assert_eq!(run.outcome.result.output(), Some(&stop_data(limit)), "{case}"); + assert_eq!(run.outcome.limit_exceeded, None, "{case}: the stop was caught"); + } + if inspected { + assert!(calls.iter().all(|call| call.0 != to), "{case}: no frame started"); + if target == PARENT { + assert_eq!(ended(&calls, CONTRACT).0, InstructionResult::Revert); + } + } + assert_eq!(run.outcome.usage, body_alone, "{case}: nothing counted"); + assert_eq!(run.outcome.gas.state, 0, "{case}: no state gas"); + assert!(run.outcome.result.logs().is_empty(), "{case}: no log"); + assert_eq!(balance(&run, to), U256::ZERO, "{case}: nothing moved"); + assert_eq!(balance(&run, CONTRACT), U256::from(held), "{case}"); + runs.push(run); + } + for run in &runs[1..] { + let case = format!("{case}, {frame}, at {gas_limit}"); + assert_eq!(run.outcome.result, runs[0].outcome.result, "{case}: the result"); + assert_eq!(run.outcome.gas, runs[0].outcome.gas, "{case}: the bill"); + assert_eq!(run.limit, runs[0].limit, "{case}: the limit"); + } + } + + // One unit more: the transfer is paid, and nothing after it fits. A cold target stops + // the call at its cold access, so nothing starts; a warm one is started, revm answering + // it or running its frame, and the calling frame is stopped by its own `POP` once the + // call returned, the stipend that came back with it computed and not billed. + let started = warm || to == ECRECOVER; + let stipends = if started { call_stipend() } else { 0 }; + for held in [VALUE, VALUE - 1] { + let case = format!("{case}, one unit more, holding {held}, at {gas_limit}"); + let (run, calls) = exec(CONTRACT, held, cap + 1, true); + let limit = assert_stopped_with_stipends(&run, intrinsic, 0, stipends); + assert_eq!( + run.outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit, + used: limit, + frame_local: false + }), + "{case}: the transfer was paid, and the stop is a later charge" + ); + let ending = calls.iter().find(|call| call.0 == to).map(|call| call.1); + let expected = match (started, held == VALUE) { + (false, _) => None, + (true, false) => Some(InstructionResult::OutOfFunds), + // The precompile's price is past the allowance the transfer left: the stop. + (true, true) if to == ECRECOVER => Some(InstructionResult::Revert), + (true, true) => Some(InstructionResult::Stop), + }; + assert_eq!(ending, expected, "{case}: how the call to the target ended"); + assert_eq!(run.outcome.usage, body_alone, "{case}"); + assert_eq!(balance(&run, to), U256::ZERO, "{case}: the stop took the move back"); + } + } + } +} + /* ---------- a value call its caller cannot fund ---------- */ /// A value call its caller cannot fund, after a read: revm refuses it on the caller's account -/// before anything moves, so its start counts no record and no log and is charged nothing, and -/// detention settles the refusal as it settles any answer. A precompile forwarded more than the -/// allowance, run on the allowance, gets the rest of its forward back. The transaction runs as -/// without the read: the call fails with the whole forward back, nothing moves, no log, and the -/// transaction keeps its body alone. +/// before anything moves, so its start counts no record and no log, the charge for its records +/// comes back, and detention settles the refusal as it settles any answer. A precompile forwarded +/// more than the allowance, run on the allowance, gets the rest of its forward back. The +/// transaction runs as without the read: the call fails with the whole forward back, nothing moves, +/// no log, and the transaction keeps its body alone. #[test] fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { let cases: [(&str, Address, Option); 4] = [ @@ -300,7 +545,7 @@ fn test_a_value_call_its_caller_cannot_fund_after_a_read_runs_as_without_it() { let body = transaction_body_bytes(&tx_to(CALLER, CONTRACT, &[0xab; 64], 0, 0)); assert_eq!( detained.outcome.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "{case}: the refused start counted nothing" ); assert!(detained.outcome.result.logs().is_empty(), "{case}"); @@ -327,15 +572,15 @@ fn destruct_after_read() -> u64 { /// A `SELFDESTRUCT` of a balance, after a read, whose frame the cap stops. /// /// - Destructing in the transaction's own frame under a cap that pays exactly the opcode, the -/// balance moves and the receipt carries the log the data size counted with the beneficiary's -/// record, as without the read. A unit less and the cold access, charged after revm journaled the -/// move and the log, crosses the cap: the opcode failed, so nothing is counted, and the stop -/// takes the move and the log back. Less than the opcode's own price, and its static charge -/// crosses before revm moves anything: the same stop. -/// - Destructing in a child, the record and the log land on the child's lane and merge into its -/// caller's. The caller then computes past the cap: the stop takes back the child's move and log -/// with the caller's lane, and the transaction keeps its body alone. Without the spin, the same -/// call keeps the log and the bytes, read or not. +/// balance moves and the receipt carries the log the data size counted with the two records — the +/// destructed account's and the beneficiary's — as without the read. A unit less and the cold +/// access, charged after revm journaled the move and the log, crosses the cap: the opcode failed, +/// so nothing is counted, and the stop takes the move and the log back. Less than the opcode's +/// own price, and its static charge crosses before revm moves anything: the same stop. +/// - Destructing in a child, the records and the log are drawn on the child's pool and merge into +/// its caller's. The caller then computes past the cap: the stop takes back the child's move and +/// log with what the caller kept, and the transaction keeps its body alone. Without the spin, the +/// same call keeps the log and the bytes, read or not. #[test] fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { let own = |first| BytecodeBuilder::default().append_many([first, POP]).selfdestruct(RECEIVER); @@ -356,13 +601,19 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { assert_as_without_read(&detained, &plain, "a cap that pays the destruction"); let logs = assert_counts_its_transfer_logs(&detained, body, "a destruction the cap pays"); assert_eq!(logs, [transfer_log(CONTRACT, RECEIVER, U256::from(VALUE))]); - assert_eq!(detained.outcome.usage.write_records, 1, "the beneficiary's record"); + assert_eq!( + detained.outcome.usage.write_records, 2, + "the destructed account's record and the beneficiary's" + ); for cap in [destruct_after_read() - 1, destruct_after_read() - cold_access() - 1] { let stopped = run_own(TIMESTAMP, cap); let left = Charges::default().then(&[2, 3, 5_000, cold_access()]).left(cap); assert_stopped(&stopped, intrinsic(gas_limit), left); assert_eq!(stopped.limit, Some(2 + cap)); - assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + stopped.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "under {cap}, nothing moved"); } @@ -391,7 +642,10 @@ fn test_a_selfdestructs_transfer_log_goes_with_the_frame_the_cap_stops() { .spin(0) .left(CAP); assert_stopped(&stopped, intrinsic(gas_limit), left); - assert_eq!(stopped.outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!( + stopped.outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); assert_eq!(balance(&stopped, RECEIVER), U256::ZERO, "the child's move was taken back"); } } @@ -567,7 +821,9 @@ fn test_every_detained_frame_start_keeps_the_log_it_counted() { if let Some(charges) = start.stops { let left = charges(input.len() as u64).left(CAP); let intrinsic = intrinsic_with(&input, gas_limit); - assert_caught(&detained, intrinsic, left, &failed_status_store()); + // The stopped call carried value: its stipend is gas the ledger never billed. + let after = failed_status_store(); + assert_caught_with_stipends(&detained, intrinsic, left, &after, call_stipend()); assert_eq!(detained.outcome.usage.write_records, 0, "{case}"); } else { let plain = exec(PUSH0); diff --git a/crates/mega-evm/tests/satin/detention.rs b/crates/mega-evm/tests/satin/detention.rs index 32ad40f7c..7cafb61d9 100644 --- a/crates/mega-evm/tests/satin/detention.rs +++ b/crates/mega-evm/tests/satin/detention.rs @@ -15,10 +15,15 @@ use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::{BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP}, + constants::{ + BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS, TX_GAS_LIMIT_CAP, + TX_STATE_GROWTH_LIMIT, + }, history_gas, system::{IMegaLimitControl, LIMIT_CONTROL_ADDRESS, ORACLE_CONTRACT_ADDRESS}, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, + test_utils::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, volatile_data_access_disabled_revert_data, write_record_history_gas, EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaLimitExceeded, MegaSpecId, MegaTransaction, MegaTransactionOutcome, OracleRead, ProtocolLimits, VolatileDataAccess, @@ -84,6 +89,12 @@ pub(crate) fn value_transfer() -> u64 { crate::salt::entry(GasId::transfer_value_cost()) } +/// The stipend a call carrying value gives its callee on top of the gas it forwards, which its +/// caller does not pay. +pub(crate) fn call_stipend() -> u64 { + mega_evm::satin_gas_params().call_stipend() +} + /// What a write to a fresh slot costs beside its compute: the slot's state gas and its record's /// history, at the prices the schedule was built with. pub(crate) fn fresh_write_spill() -> u64 { @@ -207,6 +218,17 @@ pub(crate) fn stop_data(limit: u64) -> Bytes { /// charge, `left` short of the limit, so the transaction's compute, which the stop reports and its /// regular ledger bills, is the limit less `left`. Returns the limit. pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { + assert_stopped_with_stipends(run, intrinsic, left, 0) +} + +/// [`assert_stopped`] for a transaction whose value calls gave their callees `stipends` of gas in +/// all: gas nobody paid, so the regular ledger bills the transaction's compute less them. +pub(crate) fn assert_stopped_with_stipends( + run: &Run, + intrinsic: u64, + left: u64, + stipends: u64, +) -> u64 { let limit = run.limit.expect("a read set a limit"); match &run.outcome.result { ExecutionResult::Revert { output, .. } => assert_eq!(output, &stop_data(limit)), @@ -224,7 +246,7 @@ pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { ); assert_eq!( run.outcome.gas.regular, - intrinsic + used, + intrinsic + used - stipends, "the transaction computed up to the charge that crossed its limit and not one unit past it" ); assert_eq!(run.outcome.gas.state, 0, "a stop keeps no state"); @@ -241,8 +263,20 @@ pub(crate) fn assert_stopped(run: &Run, intrinsic: u64, left: u64) -> u64 { /// charge crosses the limit again, and that is the stop the transaction reports /// ([`assert_stopped`]). Returns the limit. pub(crate) fn assert_caught(run: &Run, intrinsic: u64, left: u64, after: &Charges) -> u64 { + assert_caught_with_stipends(run, intrinsic, left, after, 0) +} + +/// [`assert_caught`] for a transaction whose value calls gave their callees `stipends` of gas in +/// all: gas nobody paid, so the regular ledger bills the transaction's compute less them. +pub(crate) fn assert_caught_with_stipends( + run: &Run, + intrinsic: u64, + left: u64, + after: &Charges, + stipends: u64, +) -> u64 { if let Some(left) = after.crossing(left) { - return assert_stopped(run, intrinsic, left); + return assert_stopped_with_stipends(run, intrinsic, left, stipends); } let limit = run.limit.expect("a read set a limit"); assert!( @@ -253,7 +287,7 @@ pub(crate) fn assert_caught(run: &Run, intrinsic: u64, left: u64, after: &Charge assert_eq!(run.outcome.limit_exceeded, None, "a stop below the transaction's own frame"); assert_eq!( run.outcome.gas.regular, - intrinsic + limit - left + after.total(), + intrinsic + limit - left + after.total() - stipends, "the transaction computed up to the charge that crossed, then what its caller ran" ); assert!(run.outcome.gas.regular <= intrinsic + limit, "within the limit"); @@ -354,6 +388,12 @@ impl Charges { charges.then(&[2]) } + /// The charges of [`cheap_spin`]'s loop: `JUMPDEST`, the push of the loop's start and `JUMP`, + /// over and over. + pub(crate) fn cheap_spin(self) -> Self { + self.forever(&[1, 3, 8]) + } + /// The charges of [`burn`]'s `rounds` rounds: the push of the counter, then each round — /// `JUMPDEST`, `PUSH1`, `SWAP1`, `SUB`, `DUP1`, the push of the loop's start and `JUMPI` — /// then the `POP` of the counter. @@ -721,6 +761,81 @@ fn test_blobhash_is_not_volatile() { assert_eq!(run.accessed, VolatileDataAccess::empty()); } +/// A call to the EIP-2935 history contract reads the block environment: the contract's `get` runs +/// `NUMBER` before it loads the slot, so the call marks the block number, and in a frame whose +/// access is off it is refused with access type 0 before it loads the slot. A call to the EIP-4788 +/// beacon-roots contract loads storage alone, state the pre-block calls committed before the +/// block's first transaction, which is no volatile read: it marks nothing and is not refused. +#[test] +fn test_the_history_contract_reads_the_block_number_and_the_beacon_roots_contract_reads_state() { + use alloy_eips::{ + eip2935::{HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE}, + eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE}, + }; + // The ring the beacon-roots contract keeps its timestamps and roots in. + const HISTORY_BUFFER_LENGTH: u64 = 8_191; + + let number = block().number.to::() - 1; + let hash = U256::from_be_bytes([0x11; 32]); + let timestamp = block().timestamp.to::(); + let root = U256::from_be_bytes([0x22; 32]); + let history_slot = U256::from(number % HISTORY_SERVE_WINDOW as u64); + let beacon_slot = U256::from(timestamp % HISTORY_BUFFER_LENGTH); + let db = || { + MemoryDatabase::default() + .account_code(HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE.clone()) + .account_storage(HISTORY_STORAGE_ADDRESS, history_slot, hash) + .account_code(BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE.clone()) + .account_storage(BEACON_ROOTS_ADDRESS, beacon_slot, U256::from(timestamp)) + .account_storage( + BEACON_ROOTS_ADDRESS, + beacon_slot + U256::from(HISTORY_BUFFER_LENGTH), + root, + ) + }; + let get = |to: Address, key: u64| { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(to), + data: Bytes::from(U256::from(key).to_be_bytes::<32>()), + gas_limit: BELOW, + ..Default::default() + })) + }; + let answer = |value: U256| Bytes::from(value.to_be_bytes::<32>()); + + let read = execute(db(), get(HISTORY_STORAGE_ADDRESS, number)); + assert_eq!(read.outcome.result.output(), Some(&answer(hash)), "the parent's hash"); + assert_eq!(read.accessed, VolatileDataAccess::BLOCK_NUMBER); + assert!(read.limit.is_some(), "the read caps the transaction"); + let loaded = &read.outcome.state[&HISTORY_STORAGE_ADDRESS].storage; + assert!(loaded.contains_key(&history_slot), "a read the state holds"); + + let mut evm = MegaEvm::new(context(db()).with_volatile_access_disabled_from(0)); + let refused = run_on(&mut evm, get(HISTORY_STORAGE_ADDRESS, number)); + match &refused.outcome.result { + ExecutionResult::Revert { output, .. } => { + let refusal = + volatile_data_access_disabled_revert_data(VolatileDataAccess::BLOCK_NUMBER); + assert_eq!(output, &refusal); + assert_eq!(output[4..], [0; 32], "access type 0"); + } + other => panic!("the history contract is refused: {other:?}"), + } + let storage = &refused.outcome.state[&HISTORY_STORAGE_ADDRESS].storage; + assert!(!storage.contains_key(&history_slot), "refused before it loads the slot"); + + for disabled in [false, true] { + let ctx = context(db()); + let ctx = if disabled { ctx.with_volatile_access_disabled_from(0) } else { ctx }; + let run = run_on(&mut MegaEvm::new(ctx), get(BEACON_ROOTS_ADDRESS, timestamp)); + let case = format!("access disabled: {disabled}"); + assert_eq!(run.outcome.result.output(), Some(&answer(root)), "{case}: the root"); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } +} + /// A read answers with the block's own field: the Host marks the read and serves the value it /// loaded, whether or not the read caps anything. #[test] @@ -951,13 +1066,13 @@ fn test_spending_exactly_the_cap_completes() { } } -/// A value call's stipend is gas nobody paid, so what the callee runs on it is not compute beyond -/// what its caller's ledger shows: a value-carrying child that reads and spins stops with the -/// regular ledger at its compute before the charge that crossed, which its caller catches and -/// ends on, and so does a transaction carrying value, whose own frame is given what the -/// transaction has left and no stipend. +/// A value-called child that reads is counted from its caller's charges in full — the value call's +/// own included, though revm gave the child a stipend the caller never paid — and stops where its +/// own charges after the read reach the cap; its caller catches the stop and ends. The regular +/// ledger bills the transaction its compute less the stipend. A transaction carrying value has no +/// stipend: its own frame is given what the transaction has left, and stops the same way. #[test] -fn test_a_stipend_is_not_compute() { +fn test_a_value_called_child_reads_from_its_callers_whole_charges() { let child = spin(op(BytecodeBuilder::default(), TIMESTAMP)); let parent = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -965,6 +1080,9 @@ fn test_a_stipend_is_not_compute() { .push_address(CHILD) .append_many([GAS, CALL, STOP]) .build(); + // The caller's four `PUSH0`, its `PUSH1`, `PUSH20` and `GAS`, and the call to the cold child + // carrying value; then the child's `TIMESTAMP`. + let at_the_read = 2 * 4 + 3 + 3 + 2 + cold_access() + value_transfer() + 2; for gas_limit in TIERS { let db = MemoryDatabase::default() .account_code(CONTRACT, parent.clone()) @@ -973,7 +1091,14 @@ fn test_a_stipend_is_not_compute() { let run = execute(db, tx(CALLER, CONTRACT, gas_limit)); // Either way the reading frame's `POP` and its loop come after the read. let left = Charges::default().then(&[2]).spin(0).left(CAP); - assert_caught(&run, intrinsic(gas_limit), left, &Charges::default()); + let limit = assert_caught_with_stipends( + &run, + intrinsic(gas_limit), + left, + &Charges::default(), + call_stipend(), + ); + assert_eq!(limit, at_the_read + CAP, "at {gas_limit}"); let db = MemoryDatabase::default() .account_code(CONTRACT, spin(op(BytecodeBuilder::default(), TIMESTAMP))) @@ -986,6 +1111,92 @@ fn test_a_stipend_is_not_compute() { } } +/// The regular charges a contract makes from its first `POP` after a read up to a `CALL` of one wei +/// that forwards no gas to a cold contract: the `POP`, the call's seven pushes, and the call's own +/// charges, the cold access and the transfer. +fn charges_to_a_stipend_call() -> Charges { + Charges::default().then(&[2, 2, 2, 2, 2, 3, 3, 2, cold_access(), value_transfer()]) +} + +/// Appends a `CALL` of one wei to `CHILD` forwarding no gas, so the child runs on its stipend +/// alone, dropping its status. +fn stipend_call(code: BytecodeBuilder) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(CHILD) + .append_many([PUSH0, CALL]) +} + +/// Appends a loop that never ends, twelve gas a round: `JUMPDEST`, a push and `JUMP`. +fn cheap_spin(code: BytecodeBuilder) -> Bytes { + let dest = code.len() as u32; + code.append(JUMPDEST).push_number(dest).append(JUMP).build() +} + +/// What a value call's callee runs on its stipend is compute, whoever funds it: after its caller's +/// read, a callee given the stipend alone, which spins, is stopped at the compute limit once it has +/// run what the limit leaves, though it holds more of the stipend — where it would run out of the +/// stipend if that were not compute. Its caller catches the stop and ends. The regular ledger bills +/// the transaction its compute less the stipend, which is gas the transaction never paid. +#[test] +fn test_stipend_funded_work_is_compute() { + let to_the_call = charges_to_a_stipend_call(); + // A thousand gas past the call, well within the stipend. + let cap = to_the_call.total() + 1_000; + let parent = stipend_call(op(BytecodeBuilder::default(), TIMESTAMP)).stop().build(); + let child = cheap_spin(BytecodeBuilder::default()); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, child.clone()); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, gas_limit)); + + // TIMESTAMP was the first opcode. + let limit = run.limit.expect("the read set a limit"); + assert_eq!(limit, 2 + cap, "at {gas_limit}"); + let call = evm.inspector().calls.iter().find(|call| call.target == CHILD).unwrap(); + assert_eq!(call.result, InstructionResult::Revert, "at {gas_limit}: the stop"); + assert_eq!(call.output, stop_data(limit), "at {gas_limit}"); + assert!(run.outcome.result.is_success(), "at {gas_limit}: {:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "at {gas_limit}: the caller caught it"); + let left = to_the_call.clone().cheap_spin().left(cap); + assert_eq!( + run.outcome.gas.regular, + intrinsic(gas_limit) + limit - left - call_stipend(), + "at {gas_limit}: compute up to the crossing, less the stipend nobody paid" + ); + } +} + +/// A value call that returns leaves its caller's compute counting every charge made since the read +/// — the call's own in full, and what the callee ran on its stipend — though the stipend the callee +/// did not spend came back to the caller's gas: the caller, spinning after the call, is stopped +/// where those charges, its own and its callee's in the order they were made, reach the limit. +#[test] +fn test_a_returned_value_call_counts_what_its_callee_ran() { + // The callee runs eighty rounds of a counting loop, 2,085 gas, within the stipend. + let callee = burn(BytecodeBuilder::default(), 80).stop().build(); + let parent = cheap_spin(stipend_call(op(BytecodeBuilder::default(), TIMESTAMP)).append(POP)); + for gas_limit in TIERS { + let db = MemoryDatabase::default() + .account_code(CONTRACT, parent.clone()) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CHILD, callee.clone()); + let cap = 50_000; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let run = run_on( + &mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), + tx(CALLER, CONTRACT, gas_limit), + ); + let charges = charges_to_a_stipend_call().burn(80).then(&[2]).cheap_spin(); + assert_stopped_with_stipends(&run, intrinsic(gas_limit), charges.left(cap), call_stipend()); + } +} + /// A read made by a call is counted from the compute the caller paid at it: its pushes, its /// static and dynamic gas, and the gas it forwards to the callee less a value call's stipend, /// which nobody paid. The limit is exact for a plain call and for one carrying value. @@ -1165,7 +1376,14 @@ fn test_running_out_of_the_frames_own_gas_still_halts() { /// halts. #[test] fn test_writes_after_a_read_stop_at_the_cap_or_run_out_of_their_own_gas() { + // More fresh slots than the 1,000 the spec's state-growth limit lets a transaction keep, so + // the rows run with that limit lifted: under it the 1,001st slot stops the frame first. let slots = CAP / fresh_write() + 1; + assert!(slots > TX_STATE_GROWTH_LIMIT, "{slots} fresh slots"); + let execute = |db: MemoryDatabase, tx| { + let limits = EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX); + run_on(&mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), tx) + }; let mut code = op(BytecodeBuilder::default(), TIMESTAMP); for slot in 1..=slots { code = code.sstore(U256::from(slot), U256::from(1)); @@ -1487,7 +1705,7 @@ fn test_the_switch_is_scoped_to_its_subtree() { /// An interceptor's answer carries the forwarded gas back without running a frame: the caller /// is held to the limit as it resumes. The call forwards what it forwards without the read — the -/// withheld part of the caller's gas is part of the 63/64 — and gets all of it back, so the +/// withheld part of the caller's gas is part of the 98/100 — and gets all of it back, so the /// caller holds the same gas after the call with the read and without it. /// /// What `remainingComputeGas()` answers is what the caller could still spend: without the read, @@ -1625,9 +1843,13 @@ fn test_state_and_history_gas_are_not_compute() { // Each slot as (slot, original, present), by slot. let written: Vec<_> = (1..=slots).map(|slot| (U256::from(slot), U256::ZERO, U256::from(1))).collect(); + // At cheaper byte prices the cap's compute pays for more fresh slots than the 1,000 the spec's + // state-growth limit lets a transaction keep, so the rows run with that limit lifted. + let limits = EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX); for gas_limit in TIERS { - let run = execute( - MemoryDatabase::default().account_code(CONTRACT, code.clone()), + let db = MemoryDatabase::default().account_code(CONTRACT, code.clone()); + let run = run_on( + &mut MegaEvm::new(context(db).with_tx_runtime_limits(limits)), tx(CALLER, CONTRACT, gas_limit), ); assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); @@ -1648,8 +1870,8 @@ fn test_state_and_history_gas_are_not_compute() { assert_eq!(run.limit, Some(2 + CAP), "{case}: TIMESTAMP set the limit, first"); assert_eq!( run.outcome.usage, - LimitUsage { data_size: history_bytes, write_records: slots }, - "{case}: one write record a slot", + LimitUsage { data_size: history_bytes, write_records: slots, state_growth: slots }, + "{case}: one write record and one new slot a slot", ); } } @@ -1694,6 +1916,171 @@ fn test_a_refill_after_the_read_does_not_lift_the_cap() { assert_stopped(&run, intrinsic(BELOW), left); } +/// A slot written away from a non-zero original value and back takes its record back, and the +/// history the record paid with it; there is no state gas to give back, since the write added no +/// state. That history spilled onto regular gas before the read, and its refill — the +/// completed-write hook's own, after revm's state refill — must not give the frame compute past the +/// cap either. +#[test] +fn test_a_history_refill_after_the_read_does_not_lift_the_cap() { + // A record that costs nothing refills nothing. + if crate::common::history_is_free() { + return; + } + let code = BytecodeBuilder::default().sstore(U256::from(1), U256::from(2)); + let code = op(code, TIMESTAMP).sstore(U256::from(1), U256::from(1)); + let db = MemoryDatabase::default().account_code(CONTRACT, spin(code)).account_storage( + CONTRACT, + U256::from(1), + U256::from(1), + ); + let run = execute(db, tx(CALLER, CONTRACT, BELOW)); + // The `POP`, then the restoring write — two pushes and `SSTORE`'s static gas, the whole of a + // warm write that restores its slot's original value — then the loop. + let left = Charges::default().then(&[2, 3, 3, 100]).spin(0).left(CAP); + assert_stopped(&run, intrinsic(BELOW), left); + assert_eq!(run.outcome.gas.history, history_gas(TX_BODY_SIZE).unwrap(), "the body's alone"); +} + +/// A frame-starting opcode whose caller cannot pay the history of the records the start makes +/// starts no frame, and halts its caller: what the caller forwarded is burned with the rest of its +/// gas, and none of it is compute, since the frame never ran — nor is a value call's stipend, +/// which the caller never held. So a transaction that read before it called that caller computes +/// the caller's charges up to its forward and no more, and is stopped at the cap exactly where +/// those and its own reach it; its regular ledger bills the burned gas on top. +/// +/// `MIDDLE` starts each kind of frame that makes records, with all but 2 per cent of what it holds, +/// a fiftieth short of the records' price; and a value call with an explicit forward that leaves +/// it one gas short. One gas less forwarded leaves it the price: that frame starts, its callee +/// returns the stipend, and the transaction computes the same. A value `CALLCODE` is not among +/// them: it moves nothing and makes no record, so there is no price to fall short of. +#[test] +fn test_a_start_its_caller_cannot_pay_for_counts_none_of_its_forward() { + // Records that cost nothing leave no price to be short of, and records priced at a fraction of + // a gas may round to nothing. + if crate::common::history_is_free() || crate::common::history_rounds() { + return; + } + const MIDDLE: Address = address!("0000000000000000000000000000000000d00004"); + const OTHER: Address = address!("0000000000000000000000000000000000d00005"); + let price = |records| write_record_history_gas(records).expect("records have a price"); + let create = crate::salt::entry(GasId::create()); + let account = crate::salt::entry(GasId::create_state_gas()); + // `PUSH0` ×4, `PUSH1` of the value, `PUSH20 OTHER`, then `GAS` or a push of the forward. + let value_call = |scheme, forward: Option| { + let code = + BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_number(1_u8); + let code = code.push_address(OTHER); + let code = match forward { + Some(forward) => code.push_number(forward), + None => code.append(GAS), + }; + code.append_many([scheme, STOP]).build() + }; + let value_call_charges = |pushed: bool| { + let push = if pushed { 3 } else { 2 }; + vec![2, 2, 2, 2, 3, 3, push, cold_access(), value_transfer()] + }; + /// A start `MIDDLE` makes: its code, its charges up to its forward, the price of the start's + /// records, the state gas it spills before its forward, and the gas it is given — `None` for + /// 50 times the price less one, which leaves it a fiftieth of what it holds a gas short. + struct Start { + name: &'static str, + code: Bytes, + charges: Vec, + price: u64, + spilled: u64, + given: Option, + } + let creation = |name, code: &[u8], charges| Start { + name, + code: BytecodeBuilder::default().append_many(code.iter().copied()).append(STOP).build(), + charges, + price: price(2), + spilled: account, + given: None, + }; + let mut rows = vec![ + Start { + name: "a value CALL", + code: value_call(CALL, None), + charges: value_call_charges(false), + price: price(2), + spilled: 0, + given: None, + }, + creation("a CREATE", &[PUSH0, PUSH0, PUSH0, CREATE], vec![2, 2, 2, create]), + creation("a CREATE2", &[PUSH0, PUSH0, PUSH0, PUSH0, CREATE2], vec![2, 2, 2, 2, create]), + ]; + // An explicit forward: `MIDDLE`, given its charges and 50 times the price less one, forwards + // all but 2 per cent of it, and keeps the price less one. + let charges = value_call_charges(true); + let given = charges.iter().sum::() + 50 * (price(2) - 1); + let forward = 49 * (price(2) - 1); + rows.push(Start { + name: "a value CALL forwarding one gas too many", + code: value_call(CALL, Some(forward)), + charges: charges.clone(), + price: price(2), + spilled: 0, + given: Some(given), + }); + + let run = |middle: Bytes, given: u64| { + let parent = op(BytecodeBuilder::default(), TIMESTAMP) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(MIDDLE) + .push_number(given) + .append_many([CALL, POP]); + let db = MemoryDatabase::default() + .account_code(CONTRACT, spin(parent)) + .account_code(MIDDLE, middle) + .account_balance(MIDDLE, U256::from(1)) + .account_balance(OTHER, U256::from(1)); + let mut evm = MegaEvm::new(context(db)).with_inspector(Calls::default()); + let run = run_on(&mut evm, tx(CALLER, CONTRACT, BELOW)); + let called_other = evm + .inspector() + .calls + .iter() + .find(|call| call.target == OTHER) + .map(|call| (call.result, call.forward)); + (run, called_other) + }; + // After the read: its `POP`; the call to `MIDDLE` — `PUSH0` ×5, `PUSH20`, the push of the gas + // and the cold access; then what `MIDDLE` charged; then the `POP` of the status and the loop. + let left = |middle: &[u64]| { + Charges::default() + .then(&[2, 2, 2, 2, 2, 2, 3, 3, cold_access()]) + .then(middle) + .then(&[2]) + .spin(0) + .left(CAP) + }; + + for Start { name, code: middle, charges, price, spilled, given } in rows { + let spent: u64 = charges.iter().sum(); + let given = given.unwrap_or(50 * price - 1); + if given <= spent + spilled { + note_price_guard("a new account's state gas outweighs 50 times two records' history"); + continue; + } + let (run, called_other) = run(middle, given); + assert_eq!(called_other, None, "{name}: no frame started"); + assert_eq!(run.outcome.usage.write_records, 0, "{name}"); + // `MIDDLE` burned all it was given but its charges; the transaction computed those. + assert_stopped(&run, intrinsic(BELOW) + given - spent, left(&charges)); + } + + let (run, called_other) = run(value_call(CALL, Some(forward - 1)), given); + assert_eq!( + called_other, + Some((InstructionResult::Stop, forward - 1 + call_stipend())), + "one gas less forwarded, the frame starts, with the stipend on top" + ); + assert_stopped_with_stipends(&run, intrinsic(BELOW), left(&charges), call_stipend()); +} + /// A chain's caps must be below [`MAX_TX_COMPUTE_GAS`], the most compute a transaction can /// spend. The transaction that can spend it pays the least a frame that runs code can before its /// first instruction — a call to its own sender, which EIP-2780 charges its base cost alone, whose diff --git a/crates/mega-evm/tests/satin/equivalence.rs b/crates/mega-evm/tests/satin/equivalence.rs index 39e1dc3dc..9ba20e682 100644 --- a/crates/mega-evm/tests/satin/equivalence.rs +++ b/crates/mega-evm/tests/satin/equivalence.rs @@ -9,11 +9,12 @@ //! [`test_the_history_ledger_is_what_satin_adds_to_every_transaction`] pins what that ledger is //! made of. One baseline case runs above the execution cap, because a transaction that has an //! EIP-8037 reservoir pays its history out of it, and a charge that is given back behind the -//! ledger's back shows up nowhere else. The six cases at the end are the ones that diverge for a +//! ledger's back shows up nowhere else. The seven cases at the end are the ones that diverge for a //! reason of their own — the //! system contract interceptors, keyless deployment, the system-address transaction, -//! the account a deposit creates for its sender, a crowded SALT bucket and the history ledger — -//! and they pin both sides, so a divergence is never silently absorbed. Later changes (the +//! the account a deposit creates for its sender, a crowded SALT bucket, a creation that destroys +//! itself and the history ledger — and they pin both sides, so a divergence is never silently +//! absorbed. Later changes (the //! limits) add their own. //! //! Every Satin transaction also reads the live system address when it is validated, which leaves @@ -40,39 +41,29 @@ use mega_evm::{ note_price_guard, op_transaction, take_system_address_read, transfer_log, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, }, - MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + MegaContext, MegaEvm, MegaSpecId, MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use op_revm::{constants::BASE_FEE_RECIPIENT, L1BlockInfo, OpEvm, OpSpecId, OpTransaction}; +use op_revm::{constants::BASE_FEE_RECIPIENT, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{CALL, GAS, POP, PUSH0, PUSH1}, - context::{ - result::{ExecResultAndState, ExecutionResult}, - BlockEnv, CfgEnv, Context, ContextTr, TxEnv, - }, + context::{BlockEnv, CfgEnv, ContextTr, TxEnv}, context_interface::cfg::GasId, inspector::NoOpInspector, state::EvmState, - ExecuteEvm, Journal, + ExecuteEvm, }; -use crate::common::{ - account_state_gas, body_history, history, runs_at_measurement_prices, slot_state_gas, +use crate::{ + common::{ + account_state_gas, body_history, history, holding_to_keep, runs_at_measurement_prices, + slot_state_gas, + }, + op_reference::{self, Op, OpContext, Settled}, }; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CALLEE: Address = address!("0x5000000000000000000000000000000000000001"); -type Outcome = ExecResultAndState, EvmState>; -type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, ->; - fn block() -> BlockEnv { BlockEnv { number: U256::from(1), @@ -84,17 +75,18 @@ fn block() -> BlockEnv { /// Runs `tx` on `db` through `MegaEvm`, then through op-revm's `OpEvm` configured with the /// `CfgEnv` the `MegaEvm` context holds. Returns both outcomes — the `MegaEvm` one with its gas -/// by ledger — and that `CfgEnv`. -fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Outcome, CfgEnv) { +/// by ledger, op-revm's with the reservoir it left ([`op_reference`](crate::op_reference)) — and +/// that `CfgEnv`. +fn run_both(db: MemoryDatabase, tx: TxEnv) -> (MegaTransactionOutcome, Settled, CfgEnv) { run_both_in(db, tx, block()) } /// Runs `tx` on `db` through op-revm's `OpEvm` alone, on the `CfgEnv` a `MegaEvm` context holds: /// for a gas limit that is op-revm's own, which Satin, charging the body's history on top, may /// refuse at validation. -fn run_op_alone(db: MemoryDatabase, tx: TxEnv) -> Outcome { +fn run_op_alone(db: MemoryDatabase, tx: TxEnv) -> Settled { let (_, mut op, _) = both_evms(db, block()); - op.transact(op_transaction(tx)).unwrap() + op_reference::transact(&mut op, op_transaction(tx)).unwrap() } /// [`run_both`] in `block`. @@ -102,10 +94,10 @@ fn run_both_in( db: MemoryDatabase, tx: TxEnv, block: BlockEnv, -) -> (MegaTransactionOutcome, Outcome, CfgEnv) { +) -> (MegaTransactionOutcome, Settled, CfgEnv) { let (mut mega, mut op, cfg) = both_evms(db, block); let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx.clone()))).unwrap(); - let op_outcome = op.transact(op_transaction(tx)).unwrap(); + let op_outcome = op_reference::transact(&mut op, op_transaction(tx)).unwrap(); (mega_outcome, op_outcome, cfg) } @@ -113,7 +105,7 @@ fn run_both_in( fn both_evms( db: MemoryDatabase, block: BlockEnv, -) -> (MegaEvm, OpEvm, CfgEnv) { +) -> (MegaEvm, Op, CfgEnv) { let ctx = MegaContext::new(db.clone(), MegaSpecId::SATIN) .with_block(block.clone()) .with_chain(zero_fee_l1_block_info()); @@ -127,8 +119,8 @@ fn both_evms( /// Asserts the two outcomes agree on everything but the history gas Satin charges: `mega` spends /// exactly its history ledger more than `op` and nothing else moves. The whole `ResultGas` is -/// compared against op-revm's with the two fields history touches rebuilt, so a field added later -/// is covered too. +/// compared against op-revm's with the field history touches rebuilt, so a field added later is +/// covered too, and the reservoir each left, which the result does not carry, beside it. /// /// The reservoir pays history first and the regular budget pays what it cannot, which is why the /// reservoir left over saturates at zero rather than going negative. @@ -144,7 +136,7 @@ fn both_evms( /// The state is compared with the read of the live system address taken out, which holds because /// these transactions carry no gas price: a priced transaction pays the extra gas out of the /// sender's balance ([`test_fees_match_op_revm`]). -fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { +fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Settled) { let history = mega.gas.history; assert!(history >= body_history(0), "every Satin transaction pays for its own body"); let (m, o) = (mega.result.gas(), op.result.gas()); @@ -154,16 +146,13 @@ fn assert_same_but_history(mega: &MegaTransactionOutcome, op: &Outcome) { assert!(m.inner_refunded() >= o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); assert_eq!( - m.reservoir_remaining(), - o.reservoir_remaining().saturating_sub(history), + mega.gas.reservoir_remaining, + op.reservoir_remaining.saturating_sub(history), "reservoir remaining" ); assert_eq!( m, - &(*o) - .with_total_gas_spent(o.total_gas_spent() + history) - .with_reservoir_remaining(o.reservoir_remaining().saturating_sub(history)) - .with_refunded(m.inner_refunded()), + &(*o).with_total_gas_spent(o.total_gas_spent() + history).with_refunded(m.inner_refunded()), "ResultGas" ); assert_eq!(mega.result.logs(), op.result.logs(), "logs"); @@ -182,13 +171,13 @@ fn but_the_system_address_read(state: &EvmState) -> EvmState { /// Asserts the two outcomes agree field by field, then as a whole so a field added later is /// covered too. For the paths that charge no history: a system call, which the protocol pays /// nothing for. -fn assert_same(mega: &Outcome, op: &Outcome) { +fn assert_same(mega: &Settled, op: &Settled) { let (m, o) = (mega.result.gas(), op.result.gas()); assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); - assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(mega.reservoir_remaining, op.reservoir_remaining, "reservoir remaining"); assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); assert_eq!(m, o, "ResultGas"); assert_eq!(mega.result.logs(), op.result.logs(), "logs"); @@ -197,10 +186,10 @@ fn assert_same(mega: &Outcome, op: &Outcome) { } /// Both engines run on the Satin configuration: Karst on the Satin gas schedule, EIP-8037, -/// EIP-2780 and EIP-7708 switched on, the 200M execution cap, `MegaETH`'s code-size limits, and a -/// system call's gas above 30M in its reservoir. So op-revm journals the same transfer logs, and -/// the logs of the two are compared as they are, and op-revm splits a system call's gas as Satin -/// does. +/// EIP-2780 and EIP-7708 switched on, the 200M execution cap and `MegaETH`'s code-size limits. So +/// op-revm journals the same transfer logs, and the logs of the two are compared as they are. A +/// system call's split is no configuration: op-revm runs one through the reference handler, which +/// splits its gas as Satin's does ([`op_reference`](crate::op_reference)). fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.spec, OpSpecId::KARST); assert_eq!(cfg.gas_params.table(), satin_gas_params().table()); @@ -211,7 +200,6 @@ fn assert_satin_cfg(cfg: &CfgEnv) { assert_eq!(cfg.limit_contract_initcode_size, Some(MAX_INITCODE_SIZE)); assert!(cfg.enable_amsterdam_eip7708); assert!(!cfg.amsterdam_eip7708_disabled); - assert!(cfg.system_call_state_gas_margin_in_reservoir); } #[test] @@ -230,11 +218,11 @@ fn test_empty_transaction_matches_op_revm() { assert_satin_cfg(&cfg); assert!(mega.result.is_success()); assert_eq!( - mega.result.gas().reservoir_remaining(), + mega.gas.reservoir_remaining, reservoir - mega.gas.history, "the reservoir paid for the body", ); - assert_eq!(op.result.gas().reservoir_remaining(), reservoir, "op-revm has nothing to pay"); + assert_eq!(op.reservoir_remaining, reservoir, "op-revm has nothing to pay"); assert_same_but_history(&mega, &op); } @@ -444,18 +432,27 @@ fn test_refund_matches_op_revm() { /// fresh slot it writes is paid out of the reservoir, and what is left of it is reported. #[test] fn test_system_call_matches_op_revm() { - use revm::handler::{ - system_call::SystemCallEvm, SYSTEM_CALL_GAS_LIMIT, SYSTEM_CALL_REGULAR_GAS_LIMIT, - }; + use mega_evm::SYSTEM_CALL_REGULAR_GAS_LIMIT; + use revm::handler::system_call::{SystemCallEvm, SYSTEM_CALL_GAS_LIMIT}; let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(3)).stop().build(); let (mut mega, mut op, cfg) = both_evms(MemoryDatabase::default().account_code(CALLEE, code), block()); assert_satin_cfg(&cfg); - let mega_outcome = mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); - let op_outcome = op.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let result_and_state = + mega.system_call_with_caller(CALLER, CALLEE, Default::default()).unwrap(); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega_outcome = Settled { result_and_state, reservoir_remaining }; + let op_outcome = op_reference::system_call( + &mut op, + CALLER, + CALLEE, + Default::default(), + SYSTEM_CALL_GAS_LIMIT, + ) + .unwrap(); assert!(mega_outcome.result.is_success()); assert_eq!( - mega_outcome.result.gas().reservoir_remaining(), + mega_outcome.reservoir_remaining, SYSTEM_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - satin_gas_params().get(GasId::sstore_set_state_gas()), @@ -785,6 +782,47 @@ fn test_a_crowded_salt_bucket_is_where_satin_leaves_op_revm() { assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); } +/// A contract whose constructor destroys the account it is creating: Satin's destruction table +/// gives back what the transaction made of an account its first effective destruction removes — +/// here the new account's state gas, and its write record with the record's history — where +/// EIP-8037, which op-revm runs, gives back nothing for this destruction. Everything else the two +/// engines do is the same, so beside the history ledger the whole difference is the account's state +/// gas. +#[test] +fn test_a_creation_that_destroys_itself_diverges_from_op_revm() { + use revm::bytecode::opcode::{ADDRESS, SELFDESTRUCT}; + + let code = + BytecodeBuilder::default().create(U256::ZERO, [ADDRESS, SELFDESTRUCT]).stop().build(); + let db = MemoryDatabase::default().account_code(CALLEE, code); + // The `CREATE` pays the history of its two records out of the 2 per cent it keeps. + let gas_limit = 1_000_000 + + account_state_gas() + + body_history(0) + + holding_to_keep(history(2 * WRITE_RECORD_SIZE)); + let tx = TxEnv { caller: CALLER, kind: TxKind::Call(CALLEE), gas_limit, ..Default::default() }; + let (mega, op, cfg) = run_both(db, tx); + assert_satin_cfg(&cfg); + assert!(mega.result.is_success() && op.result.is_success(), "{:?}", mega.result); + assert!(but_the_system_address_read(&mega.state)[&CALLEE.create(0)].is_selfdestructed()); + + // The one difference, and its exact size. + let (m, o) = (mega.result.gas(), op.result.gas()); + assert_eq!(o.state_gas_spent_final(), account_state_gas(), "op-revm keeps the account's"); + assert_eq!(m.state_gas_spent_final(), 0, "Satin gives it back"); + assert_eq!( + m.total_gas_spent() + account_state_gas(), + o.total_gas_spent() + mega.gas.history, + "beside the history ledger, the state gas given back is the whole difference", + ); + // The history ledger keeps the body and the creator's record; the created account's record + // went with the account. + assert_eq!(mega.gas.history, body_history(0) + history(WRITE_RECORD_SIZE)); + assert_eq!(mega.result.logs(), op.result.logs(), "logs"); + assert_eq!(mega.result.output(), op.result.output(), "output"); + assert_eq!(but_the_system_address_read(&mega.state), op.state, "state"); +} + /// A transaction that runs out of gas in the runtime gas phase, before its first frame — here on /// EIP-2780's charge for the account its value creates — burns its whole gas limit on both /// engines and keeps nothing but its sender's nonce: no reservoir comes back from a transaction @@ -823,13 +861,14 @@ fn test_an_out_of_gas_before_the_first_frame_matches_op_revm() { let (mega, _, cfg) = run_both(db(), transfer(mega_limit)); let op = run_op_alone(db(), transfer(op_limit)); assert_satin_cfg(&cfg); - for (engine, result, gas_limit) in - [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] - { + for (engine, result, reservoir, gas_limit) in [ + ("Satin", &mega.result, mega.gas.reservoir_remaining, mega_limit), + ("op-revm", &op.result, op.reservoir_remaining, op_limit), + ] { assert!(result.is_halt(), "{engine}: {result:?}"); let gas = result.gas(); assert_eq!(gas.total_gas_spent(), gas_limit, "{engine}: the whole gas limit burns"); - assert_eq!(gas.reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + assert_eq!(reservoir, 0, "{engine}: no reservoir comes back"); assert_eq!(gas.tx_gas_used(), gas_limit, "{engine}: the receipt bills the gas limit"); } assert_eq!(mega.gas.history, body_history(0), "the history ledger reads the body"); @@ -879,16 +918,17 @@ fn test_an_out_of_gas_creation_before_the_first_frame_matches_op_revm() { let (mega, _, cfg) = run_both(db(), creation(mega_limit)); let op = run_op_alone(db(), creation(op_limit)); assert_satin_cfg(&cfg); - for (engine, result, gas_limit) in - [("Satin", &mega.result, mega_limit), ("op-revm", &op.result, op_limit)] - { + for (engine, result, reservoir, gas_limit) in [ + ("Satin", &mega.result, mega.gas.reservoir_remaining, mega_limit), + ("op-revm", &op.result, op.reservoir_remaining, op_limit), + ] { assert!(result.is_halt(), "{engine}: {result:?}"); assert_eq!( result.gas().total_gas_spent(), gas_limit, "{engine}: the whole gas limit burns" ); - assert_eq!(result.gas().reservoir_remaining(), 0, "{engine}: no reservoir comes back"); + assert_eq!(reservoir, 0, "{engine}: no reservoir comes back"); } assert_eq!(mega.gas.history, body_history(init_code.len() as u64), "the ledger reads the body"); // op-revm reaches the charge for the created account and loads its address; Satin falls short diff --git a/crates/mega-evm/tests/satin/failed_deposit.rs b/crates/mega-evm/tests/satin/failed_deposit.rs index 34fed03a6..c5771e264 100644 --- a/crates/mega-evm/tests/satin/failed_deposit.rs +++ b/crates/mega-evm/tests/satin/failed_deposit.rs @@ -22,7 +22,7 @@ use revm::{ context::{result::ExecutionResult, TxEnv}, }; -use crate::common::{account_state_gas, block, call, context}; +use crate::common::{account_state_gas, block, call, context, grown}; const CALLER: Address = address!("0000000000000000000000000000000000f00000"); const CALLEE: Address = address!("0000000000000000000000000000000000f00001"); @@ -65,7 +65,7 @@ fn test_a_system_deposit_over_the_limit_reports_the_failed_deposit() { ); assert_eq!(outcome.gas.gas_used, 100_000, "a failed deposit bills its gas limit"); assert_eq!(outcome.limit_exceeded, None, "the halt is what the deposit reports"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.state[&CALLER].info.nonce, 1, "a failed deposit bumps its sender's nonce"); } @@ -108,7 +108,11 @@ fn test_a_deposit_whose_body_is_over_the_limit_is_a_failed_deposit() { ); assert_eq!(outcome.gas.gas_used, 100_000, "{case}: a failed deposit bills its gas limit"); assert_eq!(outcome.limit_exceeded, None, "{case}: the failure is what it reports"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{case}" + ); assert_eq!(outcome.state[&CALLER].info.nonce, 1, "{case}: the sender's nonce is bumped"); } } @@ -144,7 +148,7 @@ fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { const INTRINSIC: u64 = 12_000 + 3_000; const MINT: u64 = 7; let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE - 1); - let body = LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }; + let body = LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }; let run = |sender: Address, gas_limit: u64, system: bool| { let mut tx = op_transaction(TxEnv { caller: sender, @@ -193,13 +197,61 @@ fn test_a_deposit_over_the_limit_fails_at_every_gas_limit() { (gas_limit, 0, 0), "{row}: all of it regular gas" ); - assert_eq!(outcome.usage, body, "{row}: the body stays counted"); + let created = u64::from(sender == ABSENT); + assert_eq!( + outcome.usage, + grown(body, created), + "{row}: the body stays counted, and an absent sender's new account is state growth" + ); let sender = &outcome.state[&sender].info; assert_eq!(sender.nonce, 1, "{row}: the sender's nonce is bumped"); assert_eq!(sender.balance, U256::from(balance_before + MINT), "{row}: the mint"); } } +/// A failed deposit whose sender had no account creates it, as its nonce bump and mint stand: one +/// account of state growth, which the transaction reports and its block counts, with no state gas +/// for it on any ledger. The deposit has already failed, so no limit stops it, a state-growth limit +/// of nothing included. A sender that had an account adds nothing. +#[test] +fn test_a_failed_deposit_counts_the_caller_it_creates() { + const INTRINSIC: u64 = 12_000 + 3_000; + let run = |sender: Address, limits: EvmTxRuntimeLimits| { + let mut tx = op_transaction(TxEnv { + caller: sender, + kind: TxKind::Call(CALLEE), + gas_limit: INTRINSIC - 1, + ..Default::default() + }); + tx.deposit.source_hash = B256::repeat_byte(0x22); + let db = MemoryDatabase::default().account_balance(CALLER, U256::from(1)); + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + .execute_transaction(OpTx(tx)) + .expect("the deposit is included") + }; + let unlimited = EvmTxRuntimeLimits::no_limits(); + let none_left = unlimited.with_tx_state_growth_limit(0); + for (case, sender, limits, created) in [ + ("an absent sender", ABSENT, unlimited, 1), + ("an absent sender under a limit of nothing", ABSENT, none_left, 1), + ("a sender with an account", CALLER, unlimited, 0), + ] { + let outcome = run(sender, limits); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{case}: {:?}", + outcome.result + ); + assert_eq!(outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(outcome.usage.state_growth, created, "{case}"); + assert_eq!(outcome.gas.state, 0, "{case}: no state gas for the account"); + assert_eq!(outcome.state[&sender].info.nonce, 1, "{case}: the account exists"); + } +} + /// Runs `tx` against a callee that sends the Oracle a hint of `payload` and then halts on /// `INVALID`, and returns the outcome with the number of hints the oracle service received. fn run_hint_then_halt(tx: MegaTransaction, payload: &[u8]) -> (MegaTransactionOutcome, usize) { @@ -253,6 +305,7 @@ fn test_a_failed_deposit_keeps_the_hints_it_forwarded() { let kept = LimitUsage { data_size: mega_evm::transaction_body_bytes(&deposit) + payload.len() as u64, write_records: 0, + state_growth: 0, }; let (outcome, hints) = run_hint_then_halt(deposit, &payload); diff --git a/crates/mega-evm/tests/satin/gas_forward.rs b/crates/mega-evm/tests/satin/gas_forward.rs new file mode 100644 index 000000000..11d4f8cfc --- /dev/null +++ b/crates/mega-evm/tests/satin/gas_forward.rs @@ -0,0 +1,276 @@ +//! The regular gas a call or creation forwards: at most +//! `parent_remaining − parent_remaining × 2 / 100` of what its caller has left after the charges +//! the opcode makes before the forward, Rex6's rule in place of EIP-150's 63/64. A value call's +//! 2,300 stipend joins the forward after the cap and is not taken from the caller; a creation +//! forwards the cap and adds none. +//! +//! An inspector reads the caller's regular gas at the end of the opcode that starts a frame — +//! after the forward is taken, before the frame runs — and the forward off the frame's input, so +//! what the caller had at the forward is the two added up. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, POP, PUSH0, PUSH20, STATICCALL, STOP, + }, + context_interface::cfg::GasId, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{ + account_state_gas, body_history, call, context, forward_cap, history, holding_to_keep, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000730000"); +const A: Address = address!("0000000000000000000000000000000000730001"); +const B: Address = address!("0000000000000000000000000000000000730002"); + +/// The value call's stipend. +const STIPEND: u64 = 2_300; + +/// One frame start seen by [`Forwards`]: the opcode, the caller's regular gas once the opcode took +/// the forward, and the gas limit of the frame it starts. +#[derive(Clone, Copy, Debug)] +struct Start { + opcode: u8, + kept: u64, + gas_limit: u64, +} + +/// Records every frame start of the transaction's own frame: the opcode that made it, the regular +/// gas that frame kept, and the frame's gas limit. +#[derive(Default)] +struct Forwards { + opcode: Option, + kept: u64, + starts: Vec, +} + +impl Inspector, EthInterpreter> for Forwards { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.opcode = Some(interp.bytecode.opcode()); + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.kept = interp.gas.remaining(); + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if let Some(opcode) = self.opcode.take() { + self.starts.push(Start { opcode, kept: self.kept, gas_limit: inputs.gas_limit }); + } + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + if let Some(opcode) = self.opcode.take() { + self.starts.push(Start { opcode, kept: self.kept, gas_limit: inputs.gas_limit() }); + } + None + } +} + +/// `A` starts one frame with `opcode`, asking for all its gas, and stops; `B` stops. A call carries +/// `value`, a creation's init code is a `STOP`. +fn starting(opcode: u8, value: u64) -> MemoryDatabase { + let code = match opcode { + CREATE => BytecodeBuilder::default().create(U256::ZERO, [STOP]).append(POP), + CREATE2 => BytecodeBuilder::default().create2(U256::ZERO, [STOP], U256::ZERO).append(POP), + CALL | CALLCODE => { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + code.push_number(value).append(PUSH20).append_many(B.into_array()).append_many([ + revm::bytecode::opcode::GAS, + opcode, + POP, + ]) + } + _ => BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]) + .append_many(B.into_array()) + .append_many([revm::bytecode::opcode::GAS, opcode, POP]), + }; + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, code.stop().build()) + .account_code(B, Bytes::from_static(&[STOP])) +} + +/// The one start `A` makes with `opcode` at `gas_limit`. +fn start_of(opcode: u8, value: u64, gas_limit: u64) -> Start { + let mut evm = + MegaEvm::new(context(starting(opcode, value))).with_inspector(Forwards::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{opcode:#04x}: {:?}", outcome.result); + let [start] = evm.inspector().starts[..] else { + panic!("{opcode:#04x}: one start: {:?}", evm.inspector().starts) + }; + assert_eq!(start.opcode, opcode); + start +} + +/// Each of the six opcodes, asking for all its gas, forwards all but 2 per cent of what its caller +/// has left, and the caller keeps the 2 per cent; a value call's child gets the stipend on top, +/// which the caller does not pay. Below and above the execution cap alike. A creation's start +/// charges the history of its two records — the created account and the creator's nonce — after +/// the forward, which spills onto the caller's regular gas where there is no reservoir; above the +/// cap the reservoir pays it, as it pays a value call's, so the caller's regular gas is the +/// forward's alone. +#[test] +fn test_a_start_forwards_all_but_two_percent_of_its_callers_regular_gas() { + // The smallest tier holds, below the cap, the body's history and the created account's state + // gas before the forward, and fifty times the records' history after it, which the 2 per cent + // kept must pay, with a million to spare. + let small = account_state_gas() + + body_history(0) + + holding_to_keep(history(2 * WRITE_RECORD_SIZE)) + + 1_000_000; + for gas_limit in [small, 30_000_000.max(small), TX_GAS_LIMIT_CAP + 10_000_000] { + for (opcode, value) in [ + (CALL, 0), + (CALLCODE, 0), + (DELEGATECALL, 0), + (STATICCALL, 0), + (CREATE, 0), + (CREATE2, 0), + ] { + let Start { kept, gas_limit: forwarded, .. } = start_of(opcode, value, gas_limit); + let creation = matches!(opcode, CREATE | CREATE2); + let records = if creation && gas_limit <= TX_GAS_LIMIT_CAP { + history(2 * WRITE_RECORD_SIZE) + } else { + 0 + }; + let had = kept + records + forwarded; + assert_eq!(forwarded, forward_cap(had), "{opcode:#04x} at {gas_limit}"); + assert_eq!( + kept + records, + had * 2 / 100, + "{opcode:#04x} at {gas_limit}: the caller keeps 2%" + ); + } + } + let above = TX_GAS_LIMIT_CAP + 10_000_000; + for opcode in [CALL, CALLCODE] { + let Start { kept, gas_limit, .. } = start_of(opcode, 1, above); + let forwarded = gas_limit - STIPEND; + let had = kept + forwarded; + assert_eq!(forwarded, forward_cap(had), "{opcode:#04x} with value"); + assert_eq!( + kept, + had * 2 / 100, + "{opcode:#04x} with value: the stipend is not the caller's" + ); + } +} + +/// The spec's worked example: a value call whose caller has 10,000 regular gas left after the +/// transfer's charge forwards a cap of 9,800, so its child gets 12,100 and the caller keeps 200; +/// EIP-150 would have forwarded 9,844. +#[test] +fn test_a_value_call_with_ten_thousand_left_forwards_9800_and_its_child_gets_12100() { + assert_eq!(forward_cap(10_000), 9_800); + assert_eq!(forward_cap(10_000) + STIPEND, 12_100); + assert_eq!(10_000 - forward_cap(10_000), 200); + assert_eq!(10_000 - 10_000 / 64, 9_844); + for kept in [0, 1, 7_039] { + let held = holding_to_keep(kept); + assert_eq!(held - forward_cap(held), kept, "{held} keeps {kept}"); + assert_eq!(held + 1 - forward_cap(held + 1), kept + 1, "one gas more keeps one more"); + } +} + +/// The regular gas a frame holds as its call or creation starts, before the opcode's charges, and +/// what it forwards. +#[derive(Default)] +struct Held { + held: Option, + forwarded: Option, +} + +impl Inspector, EthInterpreter> for Held { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if matches!(interp.bytecode.opcode(), CALL | CREATE) { + self.held = Some(interp.gas.remaining()); + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + if inputs.target_address == B { + self.forwarded = Some(inputs.gas_limit); + } + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.forwarded = Some(inputs.gas_limit()); + None + } +} + +/// Runs `A` holding `code` above the execution cap, where the reservoir pays every state and +/// history charge, and returns the regular gas held at the opcode and the gas forwarded. +fn held_and_forwarded(code: Bytes) -> (u64, u64) { + let db = MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(B, U256::from(1)) + .account_code(A, code); + let mut evm = MegaEvm::new(context(db)).with_inspector(Held::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, 5 * TX_GAS_LIMIT_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = evm.inspector(); + (held.held.expect("the opcode ran"), held.forwarded.expect("a frame started")) +} + +/// A `CALL` given all the gas forwards all but 2 per cent of what its caller holds once the call's +/// own charge — the cold access to its target — is paid. +#[test] +fn test_a_call_forwards_all_but_two_percent_of_what_its_charge_leaves() { + let params = mega_evm::satin_gas_params(); + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]) + .append_many(B.into_array()) + .append_many([revm::bytecode::opcode::GAS, CALL, STOP]) + .build(); + let (held, forwarded) = held_and_forwarded(code); + let access = params.get(GasId::warm_storage_read_cost()) + + params.get(GasId::cold_account_additional_cost()); + let left = held - access; + assert_eq!(forwarded, forward_cap(left)); +} + +/// A `CREATE` forwards all but 2 per cent of what its creator holds once the creation's own +/// charges — the `create` entry, EIP-3860's word and the memory the init code occupies — are paid; +/// the created account's state gas comes out of the reservoir. +#[test] +fn test_a_creation_forwards_all_but_two_percent_of_what_its_charges_leave() { + let params = mega_evm::satin_gas_params(); + let code = BytecodeBuilder::default() + .push_number(10_u8) + .append_many([PUSH0, PUSH0, CREATE, STOP]) + .build(); + let (held, forwarded) = held_and_forwarded(code); + let left = held - params.get(GasId::create()) - params.get(GasId::initcode_per_word()) - 3; + assert_eq!(forwarded, forward_cap(left)); +} diff --git a/crates/mega-evm/tests/satin/storage_call_stipend.rs b/crates/mega-evm/tests/satin/history_allowance.rs similarity index 87% rename from crates/mega-evm/tests/satin/storage_call_stipend.rs rename to crates/mega-evm/tests/satin/history_allowance.rs index 0629017e7..270d00cbb 100644 --- a/crates/mega-evm/tests/satin/storage_call_stipend.rs +++ b/crates/mega-evm/tests/satin/history_allowance.rs @@ -22,13 +22,14 @@ use alloy_primitives::{address, Address, Bytes, U256}; use alloy_sol_types::SolCall; use mega_evm::{ constants::COST_PER_HISTORY_BYTE, - storage_call_stipend, + history_allowance_gas, system::{IMegaAccessControl, ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE}, test_utils::{ is_transfer_log, note_price_guard, transfer_log, BytecodeBuilder, MemoryDatabase, }, EvmTxRuntimeLimits, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, + HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + WRITE_RECORD_SIZE, }; use revm::bytecode::opcode::{ ADDRESS, CALL, CALLCODE, CALLDATASIZE, DELEGATECALL, DUP1, GAS, ISZERO, JUMPDEST, JUMPI, LOG3, @@ -116,8 +117,8 @@ fn test_the_allowance_is_one_three_topic_event_of_history() { if runs_at_measurement_prices() { return; } - assert_eq!(STORAGE_CALL_STIPEND_BYTES, 160); - assert_eq!(storage_call_stipend(), 160 * COST_PER_HISTORY_BYTE); + assert_eq!(HISTORY_ALLOWANCE_BYTES, 160); + assert_eq!(history_allowance_gas(), 160 * COST_PER_HISTORY_BYTE); } /// The boundary the allowance exists for: a `transfer()` — 2,300 gas and nothing else — reaches a @@ -253,7 +254,7 @@ fn test_the_allowance_cannot_be_spent_on_computation() { if !the_allowance_outweighs_a_record() { return; } - assert_eq!(storage_call_stipend(), allowance(), "the allowance the engine grants"); + assert_eq!(history_allowance_gas(), allowance(), "the allowance the engine grants"); let turns: u16 = 200; let cost = countdown_gas(u64::from(turns)); @@ -275,6 +276,59 @@ fn test_the_allowance_cannot_be_spent_on_computation() { assert_eq!((allowance(), record_history()), (14_080, 3_520), "160 and 40 bytes at 88 gas"); } +/// The hook's three-topic event over `len` bytes of memory: `PUSH1 3; PUSH1 2; PUSH1 1; PUSH2 len; +/// PUSH0; LOG3; STOP`. +fn event_over(len: u16) -> Bytes { + let [high, low] = len.to_be_bytes(); + Bytes::from(vec![PUSH1, 3, PUSH1, 2, PUSH1, 1, PUSH2, high, low, PUSH0, LOG3, STOP]) +} + +/// What [`event_over`] computes, by hand from the opcode prices: the four pushes, 3 each, and +/// `PUSH0`, 2; `LOG3`'s 375, 375 a topic and 8 a byte of data; and the memory it expands, 3 a word +/// and the square of the words over 512. +const fn event_over_gas(len: u64) -> u64 { + let words = len.div_ceil(32); + 4 * 3 + 2 + 375 + 3 * 375 + 8 * len + 3 * words + words * words / 512 +} + +/// An event larger than the allowance draws the whole allowance and pays the rest out of the +/// frame's gas: a hook given its computation and one gas less than that rest runs out of gas on +/// the history charge, after the allowance paid its part, and keeps no event; given the rest in +/// full it keeps the event, and the transaction pays that rest beside the transfer's records. +/// +/// Expected values `independent`: the hook's computation is summed by hand from the opcode prices, +/// and the two runs are the control that the sum is its whole cost; the event's bytes are its +/// address, its three topics and its data, and the rest is their history less the allowance's 160 +/// bytes, at the cost per history byte in effect (`constants`). +#[test] +fn test_an_event_larger_than_the_allowance_pays_the_rest_or_runs_out_of_gas() { + if !the_allowance_outweighs_a_record() { + return; + } + let len = 1_024; + let computation = event_over_gas(u64::from(len)); + let rest = history(LOG_BASE_SIZE + 3 * LOG_TOPIC_SIZE + u64::from(len)) - allowance(); + + let short = run_hook(event_over(len), computation + rest - 1, U256::ZERO); + assert!(!transfer_succeeded(&short), "one gas short of the rest is out of gas"); + assert!(events(&short).is_empty(), "the hook kept no event"); + assert_eq!(short.gas.history, body_history(0), "the failed hook's transfer records came back"); + + let exact = run_hook(event_over(len), computation + rest, U256::ZERO); + assert!(transfer_succeeded(&exact), "the rest in full is enough"); + assert_eq!(events(&exact).len(), 1, "the hook kept its event"); + assert_eq!( + exact.gas.history, + body_history(0) + 2 * record_history() + rest, + "the transfer's two records and the rest of the event; the allowance's part is on no ledger", + ); + + if runs_at_measurement_prices() { + return; + } + assert_eq!((computation, rest), (9_804, (1_152 - 160) * 88)); +} + /// The hook's `SSTORE(0, 2)`: `PUSH1 2; PUSH0; SSTORE; STOP`. fn writes_slot_zero() -> Bytes { Bytes::from(vec![PUSH1, 2, PUSH0, SSTORE, STOP]) @@ -386,7 +440,7 @@ fn test_a_top_level_transfer_gets_no_allowance() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( outcome.gas.history, - body() + record() + STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE, + body() + record() + HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE, "the body, the recipient's record, and the event the transaction paid for itself", ); } @@ -401,7 +455,7 @@ fn test_a_call_without_value_gets_no_allowance() { let receiver = event().append(STOP).build(); let with_value = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); let without = call_with(CALL, RECEIVER, 0, 1_000_000).append(STOP).build(); - let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + let event_history = HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE; let paid = execute(db(without, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); let granted = execute(db(with_value, receiver), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)); @@ -412,8 +466,8 @@ fn test_a_call_without_value_gets_no_allowance() { } /// `CALLCODE` transfers value and is granted one; `DELEGATECALL` carries none and is not. -/// `CALLCODE` runs the callee's code in the caller's own account, so its transfer writes one -/// account rather than two. +/// `CALLCODE` runs the callee's code in the caller's own account, so its transfer moves the value +/// from the calling account to itself and writes no account at all. /// /// `STATICCALL` carries no value either, and a static frame may not emit a log at all, so there /// is nothing an allowance could buy it. @@ -423,7 +477,7 @@ fn test_callcode_is_granted_one_and_delegatecall_is_not() { return; } let receiver = event().append(STOP).build(); - let event_history = STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE; + let event_history = HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE; let at = |scheme, value| { let sender = call_with(scheme, RECEIVER, value, 1_000_000).append(STOP).build(); execute(db(sender, receiver.clone()), call(CALLER, SENDER, U256::ZERO, GAS_LIMIT)) @@ -431,7 +485,7 @@ fn test_callcode_is_granted_one_and_delegatecall_is_not() { let call_code = at(CALLCODE, 1); assert!(call_code.result.is_success(), "{:?}", call_code.result); - assert_eq!(call_code.gas.history, body() + record(), "one record, and the allowance paid"); + assert_eq!(call_code.gas.history, body(), "no record, and the allowance paid for the event"); let delegate = at(DELEGATECALL, 0); assert!(delegate.result.is_success(), "{:?}", delegate.result); @@ -478,7 +532,7 @@ fn test_an_intercepted_call_neither_takes_nor_adds_an_allowance() { // Enough for the intercepted call and the event's computation, and far below the event's // history, which only the allowance can cover. const FORWARDED: u64 = 8_000; - assert!(FORWARDED < storage_call_stipend(), "the event's history must need the allowance"); + assert!(FORWARDED < history_allowance_gas(), "the event's history must need the allowance"); let sender = call_with(CALL, RECEIVER, 1, FORWARDED).append(STOP).build(); let with_controls = |receiver: Bytes| { db(sender.clone(), receiver) @@ -553,7 +607,7 @@ fn test_a_transaction_level_stop_does_not_hand_the_allowance_back() { ); assert!(spent.gas.gas_used > unspent.gas.gas_used, "the event still costs what it computes"); assert!( - spent.gas.gas_used - unspent.gas.gas_used < storage_call_stipend(), + spent.gas.gas_used - unspent.gas.gas_used < history_allowance_gas(), "and nothing like what its history costs", ); } @@ -584,8 +638,8 @@ fn test_an_unspent_allowance_does_not_return_to_the_caller() { /// A chain of value transfers grants each frame its own allowance, and one frame's spending is /// not another's: three frames each emit their event and the transaction pays for none of them. /// -/// The allowances are on the frames' lanes, which the frame lifecycle keeps aligned with the -/// frames themselves, so a chain cannot draw on an allowance granted further up. +/// An allowance is on the gas tracker of the frame it was granted to, and a child is granted its +/// own rather than handed its caller's, so a chain cannot draw on an allowance granted further up. #[test] fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { if runs_at_measurement_prices() { @@ -612,10 +666,11 @@ fn test_a_chain_of_transfers_grants_each_frame_its_own_allowance() { assert_eq!(events(&outcome).len(), 2, "both hops emitted their event"); assert_eq!(outcome.result.logs().len(), 4, "beside the two transfers' logs"); // The first transfer writes the sender's account and the middle one's; the second writes the - // receiver's, the middle account being recorded already by the value it received. + // receiver's and returns the middle account to what the transaction loaded, taking its record + // back: the middle hop passed on exactly the wei it received. assert_eq!( outcome.gas.history, - body() + 3 * record(), + body() + 2 * record(), "the transfers' account writes, and no event on any ledger", ); } @@ -656,8 +711,8 @@ fn self_calling_loop() -> Bytes { /// /// The allowance is drawn before the frame's own gas rather than after it, so it is a discount on /// the first 160 bytes of every value-transferring call rather than a fallback for a frame that -/// cannot pay. A contract that calls itself pays its own account's record once and nothing after -/// that, so the grant is repeatable for as long as the transaction's gas lasts: the loop below +/// cannot pay. A contract that calls itself moves nothing and pays for no record at all, so the +/// grant is repeatable for as long as the transaction's gas lasts: the loop below /// costs about 10,000 gas a turn, which is some twenty thousand turns inside one transaction at /// the execution cap — around three megabytes of log bytes, and close to 280,000,000 of history /// gas, on no gas ledger. @@ -679,29 +734,29 @@ fn test_the_gap_the_allowance_opens_between_bytes_and_gas_is_pinned() { assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!(outcome.result.logs().len(), GRANTS as usize, "every frame emitted its event"); - // A self-call writes no recipient, and the caller's own account is written once, so the whole - // loop leaves one record behind. - assert_eq!(outcome.usage.write_records, 1); + // A self-call moves the value from the calling account to itself: no account changes, so the + // whole loop leaves no record behind. + assert_eq!(outcome.usage.write_records, 0); assert_eq!( outcome.usage.data_size, - TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, - "the body, the record and every event's bytes are counted", + TX_BODY_SIZE + GRANTS * HISTORY_ALLOWANCE_BYTES, + "the body and every event's bytes are counted", ); assert_eq!( outcome.gas.history, - body() + record(), - "and the history gas is the body and that one record: no event is on it", + body(), + "and the history gas is the body alone: no event is on it", ); assert_eq!( outcome.gas.history_bytes, - TX_BODY_SIZE + WRITE_RECORD_SIZE + GRANTS * STORAGE_CALL_STIPEND_BYTES, + TX_BODY_SIZE + GRANTS * HISTORY_ALLOWANCE_BYTES, "the byte column has every event on it", ); let bytes_paid_for = outcome.gas.history / COST_PER_HISTORY_BYTE; assert_eq!( outcome.gas.history_bytes - bytes_paid_for, - GRANTS * STORAGE_CALL_STIPEND_BYTES, + GRANTS * HISTORY_ALLOWANCE_BYTES, "one allowance per value call, and every one of them off the gas ledger", ); } @@ -721,9 +776,7 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { let sender = call_with(CALL, RECEIVER, 1, 1_000_000).append(STOP).build(); let limits = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(500); let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - assert!( - start + STORAGE_CALL_STIPEND_BYTES <= 490 && start + 2 * STORAGE_CALL_STIPEND_BYTES > 490 - ); + assert!(start + HISTORY_ALLOWANCE_BYTES <= 490 && start + 2 * HISTORY_ALLOWANCE_BYTES > 490); let spent = run_limited( db(sender.clone(), receiver), @@ -744,7 +797,7 @@ fn test_a_frame_budget_revert_does_not_hand_the_allowance_back() { // is the whole of the difference: no allowance came back with either. assert!(spent.gas.regular > quiet.gas.regular, "the events still cost what they compute"); assert!( - spent.gas.regular - quiet.gas.regular < storage_call_stipend(), + spent.gas.regular - quiet.gas.regular < history_allowance_gas(), "and the difference is that computation, not an allowance", ); } @@ -774,7 +827,7 @@ fn test_a_drained_allowance_is_not_refunded_by_a_revert() { "the caller pays for the event's computation and gets no allowance back", ); assert!( - drained.gas.gas_used - quiet.gas.gas_used < storage_call_stipend(), + drained.gas.gas_used - quiet.gas.gas_used < history_allowance_gas(), "and the difference is that computation, not an allowance", ); } diff --git a/crates/mega-evm/tests/satin/history_bytes.rs b/crates/mega-evm/tests/satin/history_bytes.rs index 4bf3bce20..62dc80525 100644 --- a/crates/mega-evm/tests/satin/history_bytes.rs +++ b/crates/mega-evm/tests/satin/history_bytes.rs @@ -21,7 +21,7 @@ use mega_evm::{ test_utils::{is_transfer_log, op_transaction, BytecodeBuilder, MemoryDatabase}, untouched_create_gas, EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, - LOG_BASE_SIZE, LOG_TOPIC_SIZE, STORAGE_CALL_STIPEND_BYTES, TRANSFER_LOG_SIZE, TX_BODY_SIZE, + HISTORY_ALLOWANCE_BYTES, LOG_BASE_SIZE, LOG_TOPIC_SIZE, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ @@ -240,9 +240,11 @@ impl Inspector, EthInterpreter> for AnswersCreations } } -/// A creation answered without running deposits nothing, whatever the answer's output: the bytes -/// the transaction reports are what the history ledger charged for, and the charge its caller made -/// for the creation's records comes back with the creation that never made them. +/// A creation answered without running deposits nothing, whatever the answer's output: no byte of +/// code is counted. The answer is taken as given, as revm takes it: no record is counted, the +/// creator's nonce never having been bumped, and what the `CREATE` was charged for the records its +/// start would make stays charged, so the history ledger carries both records beyond the bytes the +/// transaction reports. #[test] fn test_a_creation_answered_without_running_appends_no_code() { if runs_at_measurement_prices() { @@ -256,9 +258,13 @@ fn test_a_creation_answered_without_running_appends_no_code() { .expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.usage.write_records, 0, "the creation that never ran wrote nothing"); - assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "and appended nothing: its body"); - assert_eq!(outcome.gas.history, TX_BODY_SIZE * CPHB); + assert_eq!(outcome.usage.write_records, 0, "no bump, no record"); + assert_eq!(outcome.gas.history_bytes, TX_BODY_SIZE, "the body alone: no record, no code"); + assert_eq!( + outcome.gas.history, + (TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE) * CPHB, + "the two records' history stays charged" + ); assert_reservoir_paid("a creation answered without running", gas_limit, &outcome); } } @@ -440,7 +446,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, event().stop().build()) }, TX_BODY_SIZE + transfer + log_bytes(3, 32), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "an event larger than the allowance: the receiver's gas pays the rest", @@ -449,7 +455,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, log(BytecodeBuilder::default(), 3, 64).stop().build()) }, TX_BODY_SIZE + transfer + log_bytes(3, 64), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "two events: the allowance pays the first", @@ -459,7 +465,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { .account_code(RECEIVER, code) }, TX_BODY_SIZE + transfer + 2 * log_bytes(3, 32), - STORAGE_CALL_STIPEND_BYTES, + HISTORY_ALLOWANCE_BYTES, ), ( "the receiver reverts: the event is not appended, and the transfer's records neither", @@ -485,7 +491,7 @@ fn test_the_bytes_exceed_the_history_gas_by_what_the_allowances_paid() { }, // The sender's account is written once; each receiver's once. TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 2 * log_bytes(3, 32), - 2 * STORAGE_CALL_STIPEND_BYTES, + 2 * HISTORY_ALLOWANCE_BYTES, ), ]; @@ -542,8 +548,6 @@ enum Run { /// Under a transaction data-size limit of this many bytes, which a frame below the /// transaction's own crosses, whose caller catches the stop. Caught(u64), - /// With an inspector that answers every creation without running it. - AnsweringCreations, } /// The history bytes a transaction reports and the data size it kept are counted from one byte @@ -562,7 +566,7 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { let hint = hint_call().len() as u64; type Case = (&'static str, fn() -> MemoryDatabase, fn(u64) -> MegaTransaction, Run, u64, u64, u64); - let cases: [Case; 35] = [ + let cases: [Case; 34] = [ ( "the body", || callee_running(BytecodeBuilder::default()), @@ -654,11 +658,11 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 1, ), ( - "a SELFDESTRUCT's beneficiary", + "a SELFDESTRUCT's beneficiary, and the account it clears", || funded().account_code(CALLEE, destructs_to(PAYEE)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, ), @@ -737,15 +741,6 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 0, 0, ), - ( - "a creation an inspector answers without running it", - || callee_running(creating(BytecodeBuilder::default(), &deploying())), - |gas| call(CALLER, CALLEE, U256::ZERO, gas), - Run::AnsweringCreations, - TX_BODY_SIZE, - 0, - 0, - ), ( "a first frame answered with the stop", funded, @@ -852,20 +847,21 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { 0, ), ( - "a SELFDESTRUCT's beneficiary the destruction creates", + "a SELFDESTRUCT's beneficiary the destruction creates, and the account it clears", || funded().account_code(CALLEE, destructs_to(FRESH)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, 0, 1, ), ( - "a SELFDESTRUCT to the sender records nothing: the body carries the sender", + "a SELFDESTRUCT to the sender records the account it clears alone: the sender's \ + account the transaction changed already", || funded().account_code(CALLEE, destructs_to(CALLER)), |gas| call(CALLER, CALLEE, U256::ZERO, gas), Run::Plain, - TX_BODY_SIZE, + TX_BODY_SIZE + WRITE_RECORD_SIZE, 0, 1, ), @@ -936,21 +932,13 @@ fn test_the_history_bytes_are_the_data_size_every_record_kept() { for gas_limit in GAS_LIMITS { let limit = match run { Run::Limited(limit) | Run::Caught(limit) => limit, - Run::Plain | Run::AnsweringCreations => u64::MAX, + Run::Plain => u64::MAX, }; // A limit the body alone crosses would stop every case before its first write, and the // case would pin the body's stop rather than its own. assert!(limit > TX_BODY_SIZE, "{name}: the body fits under the limit"); let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limited_to(limit))); - let outcome = match run { - Run::AnsweringCreations => { - evm.with_inspector(AnswersCreations).execute_transaction(tx(gas_limit)) - } - Run::Plain | Run::Limited(_) | Run::Caught(_) => { - evm.execute_transaction(tx(gas_limit)) - } - } - .expect("the transaction is valid"); + let outcome = evm.execute_transaction(tx(gas_limit)).expect("the transaction is valid"); assert_eq!( outcome.limit_exceeded.is_some(), matches!(run, Run::Limited(_)), diff --git a/crates/mega-evm/tests/satin/history_exemption.rs b/crates/mega-evm/tests/satin/history_exemption.rs index 099c248a1..90da9fe90 100644 --- a/crates/mega-evm/tests/satin/history_exemption.rs +++ b/crates/mega-evm/tests/satin/history_exemption.rs @@ -79,9 +79,9 @@ const DEPLOYED_BYTES: u64 = 32; /// The history bytes a user transaction running the program from [`CALLER`] appends: its body /// with no calldata; the program's four write records — the new slot, then `CONTRACT` (the -/// transfer's sender and the creator, recorded once in its frame), `PAYEE` and the created -/// account; its log of one word with no topic; and the deployed code. The transfer's log is data -/// size and appends no history. +/// transfer's sender and the creator, recorded once: the transfer changed it, and its nonce bump +/// adds nothing), `PAYEE` and the created account; its log of one word with no topic; and the +/// deployed code. The transfer's log is data size and appends no history. const PROGRAM_HISTORY_BYTES: u64 = TX_BODY_SIZE + 4 * WRITE_RECORD_SIZE + (LOG_BASE_SIZE + 32) + DEPLOYED_BYTES; @@ -218,8 +218,10 @@ fn test_a_system_transaction_pays_no_history_gas() { LimitUsage { data_size: transaction_body_bytes(&system_tx()) + WRITE_RECORD_SIZE, write_records: 1, + state_growth: 2, }, - "the body and the slot's record are counted, though neither pays history", + "the body and the slot's record are counted, though neither pays history, and the new slot \ + and the system address's new account are its state growth", ); // The state is charged as usual: the new slot, and the system address's own account, which // the database leaves empty, so the transaction creates it, as it does a deposit's caller. diff --git a/crates/mega-evm/tests/satin/history_gas.rs b/crates/mega-evm/tests/satin/history_gas.rs index 0012dc7aa..37bc7f614 100644 --- a/crates/mega-evm/tests/satin/history_gas.rs +++ b/crates/mega-evm/tests/satin/history_gas.rs @@ -3,7 +3,7 @@ //! Every charge is a byte count at the cost per history byte, and every assertion here writes the //! count out, so a repricing moves the numbers without rewriting the test. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use mega_evm::{ constants::{COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, TX_GAS_LIMIT_CAP}, test_utils::{BytecodeBuilder, MemoryDatabase}, @@ -11,11 +11,17 @@ use mega_evm::{ WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, LOG0, POP, PUSH0, PUSH1, REVERT, STOP}, + bytecode::opcode::{ + CALL, CALLCODE, CREATE, CREATE2, DELEGATECALL, GAS, LOG0, POP, PUSH0, PUSH1, RETURN, + REVERT, STATICCALL, STOP, + }, context_interface::cfg::GasId, }; -use crate::common::{call, call_with_data, create, deploying, execute, runs_at_measurement_prices}; +use crate::common::{ + body_history, call, call_with_data, create, deploying, execute, history, history_is_free, + history_rounds, reservoir_share, runs_at_measurement_prices, +}; const CALLER: Address = address!("0000000000000000000000000000000000200000"); const CALLEE: Address = address!("0000000000000000000000000000000000200001"); @@ -104,7 +110,7 @@ fn test_calldata_costs_one_history_byte_per_byte() { assert_eq!(longer.gas.history - zeros.gas.history, 100 * CPHB, "a hundred bytes more"); } -/* ---------- the sites the Host stages ---------- */ +/* ---------- the sites of completed writes ---------- */ /// The body of a `LOG` with `topics` topics over `data_len` bytes of memory, without the `STOP` /// that ends a program. @@ -154,7 +160,7 @@ fn test_a_log_pays_history_on_top_of_the_schedules_price() { /* ---------- a frame-start charge the caller cannot pay ---------- */ /// `CALL(GAS, target, 1 wei, [], [])`, discarding the flag, then `STOP`: a value transfer that -/// forwards everything the caller may forward, so the caller keeps a sixty-fourth of what it held. +/// forwards everything the caller may forward, so the caller keeps 2 per cent of what it held. fn transfers_everything_to(target: Address) -> Bytes { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -185,8 +191,8 @@ fn caller_running(code: Bytes) -> MemoryDatabase { funded().account_balance(CALLEE, U256::from(10_000_000)).account_code(CALLEE, code) } -/// The two records a value call's start makes cost more than a caller under roughly 450,000 gas -/// keeps after the sixty-fourth it may not forward. Such a caller pays for none of them by +/// The two records a value call's start makes cost more than a caller under roughly 352,000 gas +/// at the forward keeps after the 98 per cent it forwards. Such a caller pays for none of them by /// halting: the frame it was starting does not run. #[test] fn test_a_call_whose_caller_cannot_pay_its_records_starts_no_frame() { @@ -194,7 +200,7 @@ fn test_a_call_whose_caller_cannot_pay_its_records_starts_no_frame() { return; } let code = transfers_everything_to(CONTRACT); - let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 560_000)); let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); assert!(!short.result.is_success(), "the caller halts rather than starting the frame"); @@ -213,7 +219,7 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { return; } let code = creates_everything(); - let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 600_000)); + let short = execute(caller_running(code.clone()), call(CALLER, CALLEE, U256::ZERO, 560_000)); let ample = execute(caller_running(code), call(CALLER, CALLEE, U256::ZERO, 1_000_000)); assert!(!short.result.is_success(), "the creator halts rather than starting the creation"); @@ -225,6 +231,160 @@ fn test_a_creation_whose_creator_cannot_pay_its_records_starts_no_frame() { assert_eq!(ample.gas.history, body(0) + 2 * WRITE_RECORD_SIZE * CPHB); } +/// A creation onto an account the transaction already changed makes no record of the created +/// account — the transaction's earlier write made it — so its creator pays for its own nonce's +/// record alone. `CONTRACT` funds the address `CALLEE`'s `CREATE2` lands on with one wei, a call +/// answered without running, then calls `CALLEE` with the gas each case gives it. `CALLEE` runs +/// `CREATE2` of empty init code, which charges four `PUSH0` and the creation's own gas — no state +/// gas, for an account that exists — and forwards all but 2 per cent of what is left, keeping that +/// fiftieth to pay the start's records with. Given 50 times one record's price on top of its +/// charges, it starts the creation; one gas less, it does not. +#[test] +fn test_a_creation_onto_an_account_the_transaction_changed_charges_its_creator_one_record() { + // Records that cost nothing leave no price to be short of, and records priced at a fraction of + // a gas may round to nothing. + if history_is_free() || history_rounds() { + return; + } + let created = CALLEE.create2(B256::ZERO, keccak256([])); + let price = history(WRITE_RECORD_SIZE); + let charges = 4 * 2 + mega_evm::satin_gas_params().get(GasId::create()); + let run = |given: u64| { + let funds_then_calls = BytecodeBuilder::default() + .call(created, U256::from(1)) + .append_many([POP, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CALLEE) + .push_number(given) + .append_many([CALL, POP, STOP]) + .build(); + let creates = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, CREATE2, POP, STOP]) + .build(); + let db = funded() + .account_code(CONTRACT, funds_then_calls) + .account_balance(CONTRACT, U256::from(1)) + .account_code(CALLEE, creates); + let outcome = execute(db, call(CALLER, CONTRACT, U256::ZERO, GAS_LIMIT)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + outcome + }; + + let short = run(charges + 50 * price - 1); + assert_eq!(short.state[&created].info.nonce, 0, "a gas short, the creation never started"); + assert_eq!(short.usage.write_records, 2, "the funding call's: CONTRACT's and the address's"); + assert_eq!(short.gas.history, body_history(0) + 2 * price); + + let exact = run(charges + 50 * price); + assert_eq!(exact.state[&created].info.nonce, 1, "the creation ran"); + assert_eq!(exact.usage.write_records, 3, "and added its creator's record alone"); + assert_eq!(exact.gas.history, body_history(0) + 3 * price); +} + +/// Every call kind reaches the start's charge after its forward. A caller given its charges, an +/// explicit forward and one gas less than what the reservoir leaves of its records' price keeps too +/// little once it forwarded, and starts no frame; given that gas in full it starts the frame and +/// pays the price, the reservoir first and then its own gas. Below the execution cap there is no +/// reservoir; above it the reservoir holds half the price. A `DELEGATECALL` or a `STATICCALL` +/// moves no value, and a `CALLCODE` moves it from the calling account to itself: none makes a +/// record, so from the same gas each starts, and pays no history. +/// +/// `CALLEE` calls `CONTRACT` with the gas each case gives it and returns the call's flag, so the +/// flag says whether `CONTRACT`'s own start happened. `TARGET` holds a balance and no code, so the +/// start is answered without running, and no account is created. +#[test] +fn test_every_call_kind_charges_its_records_after_its_forward() { + if runs_at_measurement_prices() { + return; + } + const TARGET: Address = address!("0000000000000000000000000000000000200003"); + let params = mega_evm::satin_gas_params(); + let cold_access = params.get(GasId::warm_storage_read_cost()) + + params.get(GasId::cold_account_additional_cost()); + let transfer = params.get(GasId::transfer_value_cost()); + // `scheme(forward, TARGET, value, [], [])` and its charges before the forward: four `PUSH0`, a + // `PUSH1` of the value where the scheme carries one, the `PUSH20` and the `PUSH8` of the + // forward, then the cold access and the transfer. + let start = |scheme: u8, forward: u64| { + let code = BytecodeBuilder::default().append_many([PUSH0, PUSH0, PUSH0, PUSH0]); + let (code, charges) = if matches!(scheme, CALL | CALLCODE) { + (code.push_number(1_u8), 8 + 3 + 3 + 3 + cold_access + transfer) + } else { + (code, 8 + 3 + 3 + cold_access) + }; + ( + code.push_address(TARGET).push_number(forward).append_many([scheme, STOP]).build(), + charges, + ) + }; + let run = |code: Bytes, given: u64, reservoir: Option| { + let caller = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CONTRACT) + .push_number(given) + .append(CALL) + .return_top() + .build(); + let db = funded() + .account_code(CALLEE, caller) + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(1)) + .account_balance(TARGET, U256::from(1)); + let gas_limit = + reservoir.map_or(GAS_LIMIT, |reservoir| TX_GAS_LIMIT_CAP + body(0) + reservoir); + let outcome = execute(db, call(CALLER, CALLEE, U256::ZERO, gas_limit)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let started = U256::from_be_slice(outcome.result.output().unwrap()) == U256::from(1); + (started, outcome) + }; + + for (scheme, records) in [(CALL, 2)] { + let price = records * WRITE_RECORD_SIZE * CPHB; + for reservoir in [None, Some(price / 2)] { + let case = format!("scheme {scheme:#04x}, reservoir {reservoir:?}"); + // What the caller's own gas pays once the reservoir it was given is spent — its + // caller's share of the transaction's — and a forward that leaves it one gas less than + // that, the most the 98/100 rule lets it forward. + let given = reservoir.map_or(0, reservoir_share); + let spill = price - given; + let forward = 49 * (spill - 1); + let (code, charges) = start(scheme, forward); + + let (started, short) = run(code.clone(), charges + forward + spill - 1, reservoir); + assert!(!started, "{case}: one gas short, no frame"); + assert_eq!(short.usage.write_records, 0, "{case}"); + assert_eq!(short.gas.history, body(0), "{case}: the body alone"); + if let Some(reservoir) = reservoir { + assert_eq!(short.gas.reservoir_remaining, reservoir, "{case}: the reservoir too"); + } + + let (started, exact) = run(code, charges + forward + spill, reservoir); + assert!(started, "{case}: the gas in full, the frame starts"); + assert_eq!(exact.usage.write_records, records, "{case}"); + assert_eq!(exact.gas.history, body(0) + price, "{case}: the body and the records"); + // The share paid first. The part of the reservoir its caller kept comes back with the + // transaction's own frame, which merged the spill: it unwinds that spill onto regular + // gas before any of it joins the reservoir, so none is left. + if reservoir.is_some() { + assert_eq!( + exact.gas.reservoir_remaining, 0, + "{case}: the spill took what was kept" + ); + } + + // A value `CALLCODE` moves the value from the calling account to itself and makes + // no record, as the two schemes that carry no value make none. + for scheme in [CALLCODE, DELEGATECALL, STATICCALL] { + let case = format!("{case}, then scheme {scheme:#04x} from the same gas"); + let (code, _) = start(scheme, forward); + let (started, outcome) = run(code, charges + forward + spill - 1, reservoir); + assert!(started, "{case}: no records, no charge to fall short of"); + assert_eq!(outcome.usage.write_records, 0, "{case}"); + assert_eq!(outcome.gas.history, body(0), "{case}"); + } + } + } +} + /// Whether a write record is paid for may not depend on how much gas its frame's caller had /// left. Across the gas limits that straddle the point where a caller can no longer pay for the /// records of the frame it starts, the history a transaction pays beyond its body is exactly the @@ -343,3 +503,43 @@ fn test_a_beneficiary_that_is_a_fee_vault_changes_nothing() { assert_eq!(a_vault.gas.history, distinct.gas.history); assert_eq!(a_vault.usage.write_records, 0); } + +/// The record the transaction's own frame makes — its value's recipient — is charged before the +/// frame and given back once: by the frame itself, when the recipient sends the value back and its +/// account returns to what the transaction loaded, so a frame that then succeeds keeps none of it +/// and the settlement gives nothing back again; by the settlement, when the frame fails, its own +/// give-back discarded with it. A recipient that keeps the value keeps the record and its history. +/// +/// Independence: constants — the body and the record are the byte table's, at the price in effect. +#[test] +fn test_the_first_frames_record_is_given_back_once() { + let one = U256::from(1); + let returning = |end: u8| { + BytecodeBuilder::default() + .call(CALLER, one) + .append(POP) + .append_many([PUSH0, PUSH0, end]) + .build() + }; + let cases = [ + ("returns the value and succeeds", returning(RETURN), true, 0), + ("keeps the value", BytecodeBuilder::default().stop().build(), true, 1), + ("returns the value and reverts", returning(REVERT), false, 0), + ]; + for (name, code, succeeds, records) in cases { + let outcome = + execute(funded().account_code(CONTRACT, code), call(CALLER, CONTRACT, one, GAS_LIMIT)); + assert_eq!(outcome.result.is_success(), succeeds, "{name}: {:?}", outcome.result); + assert_eq!( + outcome.gas.history, + body_history(0) + history(WRITE_RECORD_SIZE * records), + "{name}: the body, and the recipient's record where it is kept" + ); + assert_eq!(outcome.usage.write_records, records, "{name}"); + assert_eq!( + outcome.gas.history_bytes, + TX_BODY_SIZE + WRITE_RECORD_SIZE * records, + "{name}: the history bytes follow" + ); + } +} diff --git a/crates/mega-evm/tests/satin/history_reservoir.rs b/crates/mega-evm/tests/satin/history_reservoir.rs index 9de582130..7b8af71f5 100644 --- a/crates/mega-evm/tests/satin/history_reservoir.rs +++ b/crates/mega-evm/tests/satin/history_reservoir.rs @@ -5,7 +5,7 @@ //! gas. Below the cap the reservoir is empty, every charge spills straight onto regular gas, and //! a charge that is silently given back looks exactly like a charge that was made and kept. //! -//! So the rule this lane carries, and the next mechanism inherits: **every ledger invariant gets +//! So the rule these tests carry, and the next mechanism inherits: **every ledger invariant gets //! at least one case above the cap**. Each holds its transaction to //! //! ```text @@ -30,8 +30,12 @@ use mega_evm::{ }; use revm::bytecode::opcode::{CALL, CREATE, GAS, MSTORE, POP, PUSH0, PUSH1, RETURN, REVERT, STOP}; -use crate::common::{ - body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, +use crate::{ + common::{ + body_history, call, execute, history_is_free, history_rounds, runs_at_measurement_prices, + state_is_free, + }, + salt::{crowded_account, minimal_envs, salt_context}, }; const CALLER: Address = address!("0000000000000000000000000000000000700000"); @@ -184,7 +188,7 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { assert!(outcome.result.is_success(), "the caller survives its child's revert"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the reverted transfer kept nothing but the body" ); assert_eq!(outcome.gas.history, BODY, "the body alone"); @@ -195,10 +199,10 @@ fn test_a_reverting_child_gives_its_records_back_to_the_reservoir() { ); } -/// A value call a system contract's interceptor refuses never starts a frame: its lane is empty -/// and the whole charge comes back. It is the path where the caller is paid back twice if the -/// frame inherited the caller's reservoir from before the charge, because the empty lane refills -/// what the adoption already restored. +/// A value call a system contract's interceptor refuses never starts a frame: its start counts +/// nothing and the whole charge comes back. It is the path where the caller is paid back twice if +/// the frame inherited the caller's reservoir from before the charge, because the refund of the +/// start charge refills what the adoption already restored. #[test] fn test_an_intercepted_value_call_gives_its_records_back_once() { if runs_at_measurement_prices() { @@ -218,7 +222,7 @@ fn test_an_intercepted_value_call_gives_its_records_back_once() { assert!(outcome.result.is_success(), "the caller survives the refusal"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the refused call wrote nothing but the body" ); assert_eq!(outcome.gas.history, BODY, "the body alone"); @@ -306,3 +310,39 @@ fn test_the_body_draws_the_reservoir_first_and_only_its_excess_from_regular_gas( assert_eq!(body, 310 * 88, "the body at the spec's price"); assert_eq!(INTRINSIC + ANSWERING + body, 42_295, "the empty call's 42,280 and the program"); } + +/// A transaction above the execution cap that runs out of gas in the runtime gas phase, before its +/// first frame, keeps its body's history charged, and what the reservoir paid of it with it: +/// revm rebuilds the transaction's gas from its intrinsic cost on that path, and the body is +/// intrinsic [S5]. The rest of the regular budget is consumed, and what is left of the reservoir +/// returns to the sender. +/// +/// The phase runs out here on EIP-2780's charge for the account a value call creates, in a bucket +/// crowded past what the regular budget and the reservoir together can pay. A body charged where +/// the rebuild drops it would leave the reservoir whole and the history ledger empty. +#[test] +fn test_an_out_of_gas_before_the_first_frame_keeps_the_body_the_reservoir_paid() { + if history_is_free() || history_rounds() || state_is_free() { + return; + } + const EMPTY: Address = address!("0000000000000000000000000000000000700e00"); + let body = body_history(0); + let reservoir = body + 1_000; + let account = mega_evm::satin_gas_params() + .get(revm::context_interface::cfg::GasId::new_account_state_gas()); + let m = (TX_GAS_LIMIT_CAP + reservoir) / account + 2; + let envs = crowded_account(minimal_envs(), EMPTY, m); + let tx = call(CALLER, EMPTY, U256::from(1), TX_GAS_LIMIT_CAP + reservoir); + let outcome = mega_evm::MegaEvm::new(salt_context(funded(), envs)) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(outcome.result.is_halt(), "{:?}", outcome.result); + assert_eq!(outcome.gas.history, body, "the body stays charged"); + assert_eq!(outcome.gas.state, 0, "the account was not created"); + assert_eq!(outcome.gas.reservoir_remaining, reservoir - body, "the reservoir paid the body"); + assert_eq!(outcome.gas.gas_used, TX_GAS_LIMIT_CAP + body, "the regular budget is consumed"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); +} diff --git a/crates/mega-evm/tests/satin/inherited_costs.rs b/crates/mega-evm/tests/satin/inherited_costs.rs index 7a3ff1e39..a9da22840 100644 --- a/crates/mega-evm/tests/satin/inherited_costs.rs +++ b/crates/mega-evm/tests/satin/inherited_costs.rs @@ -1,39 +1,29 @@ -//! Two costs Satin inherits from Ethereum where the legacy engine departed from it. +//! A cost Satin inherits from Ethereum where the legacy engine departed from it: **a preload-warm +//! address is charged warm.** The precompiles, the block beneficiary and an access-list address +//! are warm from the transaction's start, and the first call to one costs what the second does. +//! The legacy engine's pricing inspected the callee's account before the opcode's own access and +//! charged that first touch cold; Satin's pricing hook inspects no account, so the warmth revm +//! preloads is what the opcode sees. //! -//! - **A preload-warm address is charged warm.** The precompiles, the block beneficiary and an -//! access-list address are warm from the transaction's start, and the first call to one costs -//! what the second does. The legacy engine's pricing inspected the callee's account before the -//! opcode's own access and charged that first touch cold; Satin's pricing hook inspects no -//! account, so the warmth revm preloads is what the opcode sees. -//! - **A call or creation forwards all but a 64th of its gas**, as EIP-150 has it, where the legacy -//! engine forwarded 98/100. The 98% share lives on in the data-size and KV frame budgets, which -//! are not gas. -//! -//! Both are read off the regular ledger, which is the gas the opcodes charge. +//! It is read off the regular ledger, which is the gas the opcodes charge. use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, - MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, + MegaTransaction, }; use revm::{ - bytecode::opcode::{CALL, CALLCODE, CREATE, GAS, POP, PUSH0, STATICCALL, STOP}, + bytecode::opcode::{CALL, CALLCODE, POP, PUSH0, STATICCALL, STOP}, context::{ transaction::{AccessList, AccessListItem, TransactionType}, TxEnv, }, context_interface::cfg::GasId, - interpreter::{ - interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, - CreateInputs, CreateOutcome, Interpreter, - }, - Database, Inspector, }; use crate::{ - common::{block, call, context, execute}, + common::{block, call, execute}, salt::entry, }; @@ -155,86 +145,3 @@ fn test_the_first_call_to_the_beneficiary_is_charged_warm() { let beneficiary = block().beneficiary; assert_eq!(first_call_over_second(CALL, beneficiary, plain), 0); } - -/* ---------- forwarding ---------- */ - -/// The regular gas a frame holds as its call or creation starts, and what it forwards. -#[derive(Default)] -struct Forward { - opcode: u8, - held: Option, - forwarded: Option, -} - -impl Inspector, EthInterpreter> for Forward { - fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { - self.opcode = interp.bytecode.opcode(); - if matches!(self.opcode, CALL | CREATE) { - self.held = Some(interp.gas.remaining()); - } - } - - fn call( - &mut self, - _context: &mut MegaContext, - inputs: &mut CallInputs, - ) -> Option { - if inputs.target_address == EXISTING { - self.forwarded = Some(inputs.gas_limit); - } - None - } - - fn create( - &mut self, - _context: &mut MegaContext, - inputs: &mut CreateInputs, - ) -> Option { - self.forwarded = Some(inputs.gas_limit()); - None - } -} - -/// Runs `CONTRACT` holding `code` above the execution cap, where the reservoir pays every state -/// and history charge, and returns the regular gas held at the opcode and the gas forwarded. -fn forward_of(code: Bytes) -> (u64, u64, MegaTransactionOutcome) { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(CONTRACT, code); - let mut evm = MegaEvm::new(context(db)).with_inspector(Forward::default()); - let outcome = evm - .execute_transaction(call(CALLER, CONTRACT, U256::ZERO, 5 * TX_GAS_LIMIT_CAP)) - .expect("the transaction is valid"); - let forward = evm.inspector(); - (forward.held.expect("the opcode ran"), forward.forwarded.expect("a frame started"), outcome) -} - -/// A `CALL` given all the gas forwards all but a 64th of what its caller holds once the call's own -/// charge — the cold access to its target — is paid. -#[test] -fn test_a_call_forwards_all_but_a_64th_of_its_gas() { - let code = BytecodeBuilder::default() - .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(EXISTING) - .append_many([GAS, CALL, STOP]) - .build(); - let (held, forwarded, outcome) = forward_of(code); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - entry(GasId::warm_storage_read_cost()) - cold_over_warm(); - assert_eq!(forwarded, left - left / 64); -} - -/// A `CREATE` forwards all but a 64th of what its creator holds once the creation's own charges — -/// the `create` entry, EIP-3860's word and the memory the init code occupies — are paid; the -/// created account's state gas comes out of the reservoir. -#[test] -fn test_a_creation_forwards_all_but_a_64th_of_its_gas() { - let code = BytecodeBuilder::default() - .push_number(10_u8) - .append_many([PUSH0, PUSH0, CREATE, STOP]) - .build(); - let (held, forwarded, outcome) = forward_of(code); - assert!(outcome.result.is_success(), "{:?}", outcome.result); - let left = held - entry(GasId::create()) - entry(GasId::initcode_per_word()) - 3; - assert_eq!(forwarded, left - left / 64); -} diff --git a/crates/mega-evm/tests/satin/inspector.rs b/crates/mega-evm/tests/satin/inspector.rs index bfe002245..ebb89e325 100644 --- a/crates/mega-evm/tests/satin/inspector.rs +++ b/crates/mega-evm/tests/satin/inspector.rs @@ -1,18 +1,16 @@ -//! Inspectors on Satin: what a rewriting inspector gets, the one rewrite refused, and the -//! admission gate block execution keys on. +//! Inspectors on Satin: what a rewriting inspector gets and what its rewrites do not change. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ - test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase}, - DeclaredObserver, MegaContext, MegaEvm, TX_BODY_SIZE, WRITE_RECORD_SIZE, + test_utils::{transfer_log, BytecodeBuilder, GasInspector, MemoryDatabase, ReadOnlyObserver}, + MegaContext, MegaEvm, LOG_BASE_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{CALL, CREATE, GAS, INVALID, PUSH0, REVERT, SSTORE}, + bytecode::opcode::{CALL, CREATE, GAS, INVALID, LOG0, PUSH0, REVERT, SSTORE}, context::result::EVMError, - inspector::NoOpInspector, interpreter::{ - interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, CallValue, CreateInputs, CreateOutcome, Gas, InstructionResult, Interpreter, InterpreterResult, }, Database, Inspector, @@ -20,7 +18,7 @@ use revm::{ use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use crate::common::{ - account_state_gas, body_history, call, context, execute_under, history, slot_state_gas, + account_state_gas, body_history, call, context, execute_under, history, share, slot_state_gas, }; const CALLER: Address = address!("0000000000000000000000000000000000400000"); @@ -29,16 +27,16 @@ const B: Address = address!("00000000000000000000000000000000000000B1"); const FAKE: Address = address!("00000000000000000000000000000000000FA4E0"); /// 1,000,000 of regular gas on top of what these scenarios add at the byte prices in effect: two -/// fresh slots and a new account, the body and four records, and 64 times the history of two -/// records, which a call or a creation that forwards all but a 64th of its gas pays for the frame -/// it starts from the 64th it keeps. +/// fresh slots and a new account, the body and four records, and 50 times the history of two +/// records, which a call or a creation that forwards all but 2 per cent of its gas pays for the +/// frame it starts from the fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + 2 * slot_state_gas() + account_state_gas() + body_history(0) + history(4 * WRITE_RECORD_SIZE) + - 64 * history(2 * WRITE_RECORD_SIZE) + 50 * history(2 * WRITE_RECORD_SIZE) } /// Calls `B` with `value` and stores the call's success flag in slot 0. @@ -220,7 +218,7 @@ fn test_short_circuited_value_call_moves_no_value() { ); assert_eq!(result.state[&A].info.balance, U256::from(100), "no value left A"); assert!(result.state.get(&B).is_none_or(|b| b.info.balance.is_zero()), "no value reached B"); - assert_eq!(evm.ctx().additional_limit().usage().write_records, 1, "only A's slot 0"); + assert_eq!(evm.ctx().limit_usage().write_records, 1, "only A's slot 0"); } /// An address rewritten in `create_end` is what the caller sees, but the code is where the @@ -241,48 +239,53 @@ fn test_create_end_address_rewrite_reaches_the_caller_not_the_code() { } /// A creation its own frame budget stops, revived by an inspector: the stop is the creation's alone -/// and no stop of the transaction, so the creation failed as any failed creation does and its -/// revival settles as the failure — the transaction is not refused. Under a data-size limit of the -/// body and 122 bytes, the creator may keep 122 and the creation 98% of them, 119: the creation's -/// start makes two records, 80 bytes, and the write in its init code is a third, 40 more, over its -/// budget, which the transaction's limit still holds. Under the body and 160 bytes the budget holds -/// it, and so does the transaction's limit once the creator stores the address, a fourth record: -/// the same creation succeeds. +/// and no stop of the transaction, so the creation failed as any failed creation does, and its +/// revival settles as the success the inspector made of it — the transaction is not refused. Under +/// a data-size limit of the body and 4,000 bytes the creation gets 98% of them, 3,920: its start +/// makes the created account's record, 40 bytes, and the log in its init code 3,881 more, one byte +/// over its budget, which the transaction's limit still holds. Revived, it hands its creator the +/// record it counted, and the creator keeps that, its nonce record and the address it stores. Under +/// the body and 4,100 bytes the budget, 4,018, holds the log, and the creator keeps its two records +/// on top: the same creation succeeds. #[test] fn test_a_creation_its_frame_budget_stops_may_be_revived() { - // A write of 1 to slot 1, short enough for `create_and_store_address`. + // A log one byte past the creation's share once the created account's record is counted. + const LOGGED: u64 = 3_849; + assert_eq!(WRITE_RECORD_SIZE + LOG_BASE_SIZE + LOGGED, share(4_000) + 1); let init_code = BytecodeBuilder::default() - .push_number(1_u8) - .push_number(1_u8) - .append(SSTORE) + .push_number(LOGGED) + .push_number(0_u8) + .append(LOG0) .stop() .build(); + // What `gas_limit` covers, and the log the creation keeps when its budget holds it. + let gas_limit = gas_limit() + history(LOG_BASE_SIZE + LOGGED) + 100_000; let db = || MemoryDatabase::default().account_code(A, create_and_store_address(&init_code)); let under = |bytes: u64| { mega_evm::EvmTxRuntimeLimits::default().with_tx_data_size_limit(TX_BODY_SIZE + bytes) }; let plain = - |bytes: u64| execute_under(db(), call(CALLER, A, U256::ZERO, gas_limit()), under(bytes)); + |bytes: u64| execute_under(db(), call(CALLER, A, U256::ZERO, gas_limit), under(bytes)); let created = |outcome: &mega_evm::MegaTransactionOutcome| { outcome.state[&A] .storage .get(&U256::ZERO) .is_some_and(|slot| !slot.present_value().is_zero()) }; - let roomy = plain(160); + let roomy = plain(4_100); assert!(roomy.result.is_success() && created(&roomy), "{:?}", roomy.result); // Without the inspector the creation fails alone: its creator stores no address and succeeds, // and the transaction is not stopped. - let stopped = plain(122); + let stopped = plain(4_000); assert!(stopped.result.is_success(), "{:?}", stopped.result); assert_eq!(stopped.limit_exceeded, None, "a frame budget below is no stop"); assert!(!created(&stopped), "the creation failed"); - let limits = under(122); + let limits = under(4_000); let revived = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)) .with_inspector(Rewriter { create_succeeds: true, ..Default::default() }) - .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())) + .execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)) .unwrap(); assert!(revived.result.is_success(), "{:?}", revived.result); assert_eq!(revived.limit_exceeded, None, "and the revival is no stop either"); @@ -299,33 +302,33 @@ fn test_a_creation_its_frame_budget_stops_may_be_revived() { ); } -/// A declared observer that writes back fails its declaration in a debug build. +/// A read-only observer that writes back fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer wrote to the interpreter in `step_end`")] -fn test_false_declaration_fails_in_debug() { +#[should_panic(expected = "a read-only observer wrote to the interpreter in `step_end`")] +fn test_false_read_only_claim_fails_in_debug() { let rewriter = Rewriter { charge_after_sstore: 1, ..Default::default() }; - let mut evm = MegaEvm::new(context(writes_two_slots())) - .with_trusted_inspector(DeclaredObserver(rewriter)); + let mut evm = + MegaEvm::new(context(writes_two_slots())).with_inspector(ReadOnlyObserver(rewriter)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared call rewrite fails too. +/// A read-only observer's call rewrite fails too. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a call result")] -fn test_false_declaration_of_a_call_rewrite_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a call result")] +fn test_false_read_only_claim_of_a_call_rewrite_fails_in_debug() { let db = MemoryDatabase::default() .account_code(A, call_b_and_store_flag(0)) .account_code(B, Bytes::from_static(&[INVALID])); let rewriter = Rewriter { call_succeeds: true, ..Default::default() }; - let mut evm = MegaEvm::new(context(db)).with_trusted_inspector(DeclaredObserver(rewriter)); + let mut evm = MegaEvm::new(context(db)).with_inspector(ReadOnlyObserver(rewriter)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared observer that only reads produces the transaction no inspector produces. +/// A read-only observer that only reads produces the transaction no inspector produces. #[test] -fn test_declared_tracer_changes_nothing() { +fn test_read_only_tracer_changes_nothing() { let db = || { MemoryDatabase::default() .account_code(A, call_b_and_store_flag(0)) @@ -334,7 +337,7 @@ fn test_declared_tracer_changes_nothing() { let plain = MegaEvm::new(context(db())).transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); - let mut evm = MegaEvm::new(context(db())).with_trusted_inspector(DeclaredObserver(tracer)); + let mut evm = MegaEvm::new(context(db())).with_inspector(ReadOnlyObserver(tracer)); let traced = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); assert_eq!(plain.result, traced.result); assert_eq!(plain.state, traced.state); @@ -367,27 +370,6 @@ fn test_the_gas_inspector_keeps_the_byte_of_an_undefined_opcode() { } } -/// The admission gate: only an enabled inspector that did not arrive declared is a rewriting one. -#[test] -fn test_has_rewriting_inspector_truth_table() { - let evm = || MegaEvm::new(context(MemoryDatabase::default())); - assert!(!evm().has_rewriting_inspector(), "no inspector"); - assert!(evm().with_inspector(NoOpInspector).has_rewriting_inspector(), "a tool's inspector"); - assert!( - evm().with_inspector(GasInspector::new()).has_rewriting_inspector(), - "test utilities are tools" - ); - assert!(!evm().with_trusted_inspector(NoOpInspector).has_rewriting_inspector()); - let tracer = TracingInspector::new(TracingInspectorConfig::default_parity()); - assert!(!evm().with_trusted_inspector(DeclaredObserver(tracer)).has_rewriting_inspector()); - - let mut disabled = evm().with_inspector(Rewriter::default()); - disabled.set_inspector_enabled(false); - assert!(!disabled.has_rewriting_inspector(), "a disabled inspector does not run"); - disabled.set_inspector_enabled(true); - assert!(disabled.has_rewriting_inspector()); -} - /// Counts frame starts and ends. #[derive(Default)] struct Pairs { @@ -530,13 +512,13 @@ fn busy_contract() -> MemoryDatabase { MemoryDatabase::default().account_code(A, code).account_code(B, Bytes::from_static(&[0x00])) } -/// A declared observer forwards every callback to the inspector inside. +/// A read-only observer forwards every callback to the inspector inside. #[test] -fn test_declared_observer_forwards_every_callback() { +fn test_read_only_observer_forwards_every_callback() { let mut plain = MegaEvm::new(context(busy_contract())).with_inspector(Recorder::default()); plain.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let mut declared = MegaEvm::new(context(busy_contract())) - .with_trusted_inspector(DeclaredObserver::new(Recorder::default())); + .with_inspector(ReadOnlyObserver::new(Recorder::default())); declared.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); let seen = plain.inspector().clone(); @@ -555,7 +537,7 @@ fn test_declared_observer_forwards_every_callback() { seen.selfdestruct > 0, "every callback ran: {seen:?}" ); - assert_eq!(DeclaredObserver::new(Recorder::default()).into_inner(), Recorder::default()); + assert_eq!(ReadOnlyObserver::new(Recorder::default()).into_inner(), Recorder::default()); } /// Keeps every log handed to `Inspector::log`, the callback for a log journaled outside an @@ -569,16 +551,16 @@ impl Inspector, EthInterpreter> for FrameStartLogs } } -/// A declared observer forwards the EIP-7708 transfer logs a frame's start journals: the +/// A read-only observer forwards the EIP-7708 transfer logs a frame's start journals: the /// transaction's value into `A`, whose frame runs, and `A`'s value into `B`, an account with no /// code, whose frame is answered without running. #[test] -fn test_declared_observer_forwards_the_transfer_logs_of_frame_starts() { +fn test_read_only_observer_forwards_the_transfer_logs_of_frame_starts() { let db = MemoryDatabase::default() .account_balance(CALLER, U256::from(5)) .account_code(A, call_b_and_store_flag(2)); - let mut evm = MegaEvm::new(context(db)) - .with_trusted_inspector(DeclaredObserver::new(FrameStartLogs::default())); + let mut evm = + MegaEvm::new(context(db)).with_inspector(ReadOnlyObserver::new(FrameStartLogs::default())); let outcome = evm.transact_raw(call(CALLER, A, U256::from(5), gas_limit())).unwrap(); assert!(outcome.result.is_success(), "{:?}", outcome.result); assert_eq!( @@ -634,32 +616,32 @@ impl Inspector, EthInterpreter> for Writer { #[cfg(debug_assertions)] fn run_declared(writer: Writer) { let mut evm = - MegaEvm::new(context(writes_two_slots())).with_trusted_inspector(DeclaredObserver(writer)); + MegaEvm::new(context(writes_two_slots())).with_inspector(ReadOnlyObserver(writer)); let _ = evm.transact_raw(call(CALLER, A, U256::ZERO, gas_limit())); } -/// A declared observer that edits a frame's inputs fails its declaration in a debug build. +/// A read-only observer that edits a frame's inputs fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a frame's inputs")] -fn test_false_declaration_of_an_input_edit_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a frame's inputs")] +fn test_false_read_only_claim_of_an_input_edit_fails_in_debug() { run_declared(Writer { edit_inputs: true, ..Default::default() }); } -/// A declared observer that writes to the journal fails its declaration in a debug build. +/// A read-only observer that writes to the journal fails its declaration in a debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer wrote to the journal in `step`")] -fn test_false_declaration_of_a_journal_write_fails_in_debug() { +#[should_panic(expected = "a read-only observer wrote to the journal in `step`")] +fn test_false_read_only_claim_of_a_journal_write_fails_in_debug() { run_declared(Writer { log_in_step: true, ..Default::default() }); } -/// A declared observer that rewrites a frame result in `frame_end` fails its declaration in a +/// A read-only observer that rewrites a frame result in `frame_end` fails its declaration in a /// debug build. #[test] #[cfg(debug_assertions)] -#[should_panic(expected = "a declared observer rewrote a frame result in `frame_end`")] -fn test_false_declaration_of_a_frame_end_rewrite_fails_in_debug() { +#[should_panic(expected = "a read-only observer rewrote a frame result in `frame_end`")] +fn test_false_read_only_claim_of_a_frame_end_rewrite_fails_in_debug() { run_declared(Writer { rewrite_frame_end: true, ..Default::default() }); } @@ -686,10 +668,11 @@ impl Inspector for Seen { } /// A system call runs on the handler's plain system-call path wherever the engine and alloy-evm -/// make one — the pre-block calls' entry point, alloy-evm's and revm's — so the EVM's inspector -/// sees nothing of it, as alloy-evm's own EVMs have it. revm's inspecting entry point is the one -/// that hands it to the inspector, and there the call keeps every exemption a system call has: a -/// data-size limit of zero, which would stop a transaction before its first frame, stops nothing. +/// make one — alloy-evm's and revm's entry points here, the block's pre-block calls in the block +/// tests — so the EVM's inspector sees nothing of it, as alloy-evm's own EVMs have it. revm's +/// inspecting entry point is the one that hands it to the inspector, and there the call keeps every +/// exemption a system call has: a data-size limit of zero, which would stop a transaction before +/// its first frame, stops nothing. #[test] fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { use revm::{InspectSystemCallEvm, SystemCallEvm}; @@ -699,8 +682,6 @@ fn test_only_the_inspecting_system_call_entry_point_runs_the_inspector() { let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(Seen::default()); - let result = evm.transact_system_call_with_gas_limit(CALLER, A, Bytes::new(), 30_000_000); - assert!(result.unwrap().result.is_success()); assert!(Evm::transact_system_call(&mut evm, CALLER, A, Bytes::new()) .unwrap() .result @@ -771,3 +752,34 @@ fn test_intrinsic_data_size_overflow_with_inspector_early_return() { assert_eq!(format!("{inspected:?}"), format!("{plain:?}")); assert!(format!("{plain:?}").contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{plain:?}"); } + +/// Turns every call into a transfer of one wei, whatever value its opcode or the transaction gave +/// it. +struct AddsValue; + +impl Inspector for AddsValue { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + inputs.value = CallValue::Transfer(U256::from(1)); + None + } +} + +/// A rewriting inspector may change what a start writes after its history was charged: the +/// transaction's own call and `A`'s call to `B` carry no value when they are charged — before +/// execution and at `A`'s `CALL` — and one wei each once the inspector rewrote them. The checks +/// that the records counted are the ones charged, which a debug build makes on every other path, +/// are not made under such an inspector, and the rewritten starts run: both transfers move their +/// wei. +#[test] +fn test_a_rewriting_inspector_may_change_what_a_start_writes() { + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, call_b_and_store_flag(0)); + let mut evm = MegaEvm::new(context(db)).with_inspector(AddsValue); + let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit())).unwrap(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&A].storage[&U256::ZERO].present_value, U256::from(1), "B ran"); + assert_eq!(outcome.state[&B].info.balance, U256::from(1), "A's rewritten call moved its wei"); + assert_eq!(outcome.state[&A].info.balance, U256::from(1), "and the transaction's moved A's"); +} diff --git a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs index 7bec7ef3a..697fbf8a7 100644 --- a/crates/mega-evm/tests/satin/inspector_cheatcodes.rs +++ b/crates/mega-evm/tests/satin/inspector_cheatcodes.rs @@ -13,10 +13,11 @@ //! //! What each does to Satin's ledgers follows from the inspector contract: a journal write from a //! callback is on no gas ledger and in no count, a paused region spends no gas of any kind while -//! what it writes is still counted, a failed call `expectRevert` turns into a success settles as -//! the failure on every ledger, and a success it turns into a failure keeps none of its writes. -//! `expectRevert` is honored on a result revm answers without running a frame — a precompile's, a -//! call to an account with no code — as on a frame's. +//! what it writes is still counted, and a result `expectRevert` rewrites is taken as given, as revm +//! takes it — a failed call turned into a success keeps its writes reverted and settles as a +//! success. `expectRevert` is honored on a result revm answers without running a frame — a +//! precompile's, a call to an account with no code — as on a frame's. A cheatcode answered on +//! `Gas::new`, as Foundry answers it, carries no reservoir, and its caller is left none. use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::{sol, SolCall}; @@ -38,7 +39,7 @@ use revm::{ }; use crate::{ - common::{call, context}, + common::{body_history, call, context, reservoir_share}, salt::entry, }; @@ -317,8 +318,9 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { LimitUsage { data_size: idle.usage.data_size + WRITE_RECORD_SIZE, write_records: idle.usage.write_records + 1, + state_growth: idle.usage.state_growth + 1, }, - "the record is counted" + "the record is counted, and the slot is new" ); assert_eq!(worked.gas.history_bytes, idle.gas.history_bytes + WRITE_RECORD_SIZE); @@ -334,8 +336,9 @@ fn test_pause_and_resume_gas_metering_hold_the_gas() { /// `expectRevert` turns the next call's revert into a success that keeps the revert data. `TARGET` /// fills a fresh slot and reverts with a word; the program notes the flag and the word. The -/// failed call settles as the failure it was on every ledger — the transaction is billed and -/// counted as it is without the cheatcode — and only the flag the program noted differs. +/// failed call's journal was reverted, so the slot is not kept, and the call settles as the +/// success the cheatcode made of it: the transaction is billed and counted as it is where `TARGET` +/// fills the slot and returns the word, with no cheatcode. #[test] fn test_expect_revert_turns_a_revert_into_a_success_that_keeps_its_reason() { let reason = keccak256(b"reason"); @@ -364,8 +367,20 @@ fn test_expect_revert_turns_a_revert_into_a_success_that_keeps_its_reason() { let (reverted, _) = run(db(true), false); assert_eq!(slot(&reverted, TEST, 0), U256::from(1), "the caller saw the revert"); assert_eq!(slot(&reverted, TEST, 1), U256::from_be_bytes(reason.0)); - assert_eq!(expected.gas, reverted.gas, "every ledger"); - assert_eq!(expected.usage, reverted.usage, "every count"); + + // Where `TARGET` returns the word in place of reverting with it, the call succeeds and keeps + // the slot: that is what the rewritten call is billed and counted as. + let returning = BytecodeBuilder::default() + .sstore(U256::from(3), U256::from(1)) + .return_with_data(reason) + .build(); + let db = + MemoryDatabase::default().account_code(TEST, program(true)).account_code(TARGET, returning); + let (returned, _) = run(db, false); + assert_eq!(slot(&returned, TEST, 0), U256::from(2), "the caller saw the success"); + assert!(returned.state[&TARGET].storage[&U256::from(3)].is_changed(), "and the slot is kept"); + assert_eq!(expected.gas, returned.gas, "every ledger"); + assert_eq!(expected.usage, returned.usage, "every count"); } /// `expectRevert` is honored on a result revm answers without running a frame. A point off the @@ -396,13 +411,15 @@ fn test_expect_revert_is_honored_on_a_result_no_frame_ran_to_produce() { } /// At Foundry's default gas limit a test transaction runs above the execution cap, with a -/// reservoir, and Foundry answers every cheatcode call on `Gas::new`, which carries none. The -/// answered frame never ran, so its caller merges back the reservoir it forwarded: a program that -/// calls `deal`, fills a fresh slot and notes `GAS` costs, on every ledger, what it costs where the -/// cheatcode's call reaches an account with no code — its state gas drawn from the reservoir rather -/// than spilled onto regular gas — reads the same `GAS`, and ends with the same reservoir. +/// reservoir, and Foundry answers every cheatcode call on `Gas::new`, which carries none. Its +/// caller adds the answer's reservoir to what it kept of its own when it handed the call its +/// share, as revm settles an answer: a program that calls `deal`, fills a fresh slot and notes +/// `GAS` in another is left only the 2 per cent it kept, which pays for both slots, so `GAS` reads +/// what it reads where the cheatcode's call reaches an account with no code, which carries the +/// whole share back. The state and history it is billed, and what it counts, are the same either +/// way. #[test] -fn test_a_cheatcode_keeps_the_reservoir_at_foundrys_default_gas_limit() { +fn test_a_cheatcode_at_foundrys_default_gas_limit_leaves_its_caller_what_it_kept() { let code = cheat(BytecodeBuilder::default(), Vm::dealCall { who: TARGET, newBalance: U256::ONE }) .sstore(U256::ZERO, U256::ONE) @@ -416,8 +433,16 @@ fn test_a_cheatcode_keeps_the_reservoir_at_foundrys_default_gas_limit() { assert_eq!(answered, 1); assert_eq!(cheated.state[&TARGET].info.balance, U256::ONE, "the cheatcode ran"); let (plain, _) = run_with_gas_limit(db(), false, FOUNDRY_GAS_LIMIT); - assert!(plain.gas.reservoir_remaining > 0, "the transaction runs with a reservoir"); - assert_eq!(cheated.gas, plain.gas, "every ledger, the reservoir included"); + // `TEST` holds the whole reservoir when it calls the cheatcode, and the two fresh slots draw + // it. + let whole = FOUNDRY_GAS_LIMIT - mega_evm::constants::TX_GAS_LIMIT_CAP - body_history(0); + let record = mega_evm::history_gas(WRITE_RECORD_SIZE).expect("a record has a price"); + let slots = 2 * (entry(GasId::sstore_set_state_gas()) + record); + assert_eq!(plain.gas.reservoir_remaining, whole - slots, "the slots drew the reservoir"); + let kept = whole - reservoir_share(whole); + assert!(kept > slots, "what `TEST` kept pays for both slots"); + assert_eq!(cheated.gas.reservoir_remaining, kept - slots, "the answer's reservoir: none"); + assert_eq!((cheated.gas.state, cheated.gas.history), (plain.gas.state, plain.gas.history)); assert_eq!(cheated.usage, plain.usage, "every count"); - assert_eq!(slot(&cheated, TEST, 1), slot(&plain, TEST, 1), "the same `GAS`"); + assert_eq!(slot(&cheated, TEST, 1), slot(&plain, TEST, 1), "nothing spilled"); } diff --git a/crates/mega-evm/tests/satin/inspector_limits.rs b/crates/mega-evm/tests/satin/inspector_limits.rs index 86c7d8fef..23a77a7aa 100644 --- a/crates/mega-evm/tests/satin/inspector_limits.rs +++ b/crates/mega-evm/tests/satin/inspector_limits.rs @@ -4,32 +4,38 @@ //! frame's gas into the result it returns, so what `step_end` writes to the interpreter's gas //! after it reaches nobody. What a frame returns is changed on its result, in `call_end`. //! - An inspector cannot overdraw a frame: a charge the frame's spendable gas cannot pay is refused -//! and takes nothing, the frame runs on, and nothing is left behind to classify its end — not -//! even under gas detention, where the same refusal of an opcode's charge is the crossing. -//! - An answer carries only the regular gas its inspector chose: the frame never ran, so its caller -//! merges back the reservoir it forwarded, whatever `Gas` the answer was built on. +//! and takes nothing, and the frame runs on. Under gas detention the refusal of an opcode's +//! charge is the crossing; an inspector's leaves the same record on the frame's gas, as revm +//! leaves it, which stops nothing in a frame that ends without an out-of-gas, and which a later +//! halt that records nothing of its own is read off. +//! - An answer settles on the gas its inspector built it on, as revm settles it: its caller takes +//! the answer's reservoir as its own, and the charges the answer carries as a success's. use alloy_primitives::{address, Address, Bytes, Log, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, test_utils::{BytecodeBuilder, MemoryDatabase}, - untouched_call_gas, with_pools_of, EvmTxRuntimeLimits, MegaContext, MegaEvm, + untouched_call_gas, EvmTxRuntimeLimits, LimitCheck, MegaContext, MegaEvm, MegaTransactionOutcome, }; use revm::{ - bytecode::opcode::{LOG0, POP, PUSH0, TIMESTAMP}, + bytecode::opcode::{BALANCE, CALL, JUMP, JUMPDEST, LOG0, POP, PUSH0, PUSH20, TIMESTAMP}, interpreter::{ - interpreter::EthInterpreter, interpreter_types::LoopControl, CallInputs, CallOutcome, Gas, - InstructionResult, Interpreter, InterpreterAction, InterpreterResult, + instructions::gas_table_spec, interpreter::EthInterpreter, interpreter_types::LoopControl, + CallInputs, CallOutcome, Gas, InstructionResult, Interpreter, InterpreterAction, + InterpreterResult, PoolId, }, + primitives::hardfork::SpecId, Database, Inspector, }; -use crate::common::{call, context}; +use crate::common::{body_history, call, context, reservoir_share}; const CALLER: Address = address!("0000000000000000000000000000000000e00000"); const A: Address = address!("0000000000000000000000000000000000e00001"); const B: Address = address!("0000000000000000000000000000000000e00002"); +/// An account no transaction here touches before `B` reads its balance. +const COLD: Address = address!("0000000000000000000000000000000000e00003"); const GAS_LIMIT: u64 = 1_000_000; /// `A` calls `B` and stops; `B` pushes and pops a word and stops. @@ -140,32 +146,45 @@ fn test_gas_changed_at_a_frames_end_has_no_effect() { /// The callbacks holding the interpreter that [`Overdraws`] charges from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Callback { + InitializeInterp, Step, StepEnd, LogFull, } +/// The frames [`Overdraws`] charges in. +#[derive(Clone, Copy, Debug)] +enum Frames { + /// Any frame. + Any, + /// A frame part of whose gas is withheld. + Detained, + /// A frame running `B`'s code. + B, +} + /// Charges, once, one more gas than the running frame's spendable gas from the callback `from`, -/// the first time it runs while part of the frame's gas is withheld — or at all, when -/// `detained_only` is off — and records whether the charge was refused. +/// the first time it runs in one of `frames`, and records whether the charge was refused. #[derive(Clone)] struct Overdraws { from: Callback, - detained_only: bool, + frames: Frames, refused: Option, } impl Overdraws { - const fn new(from: Callback, detained_only: bool) -> Self { - Self { from, detained_only, refused: None } + const fn new(from: Callback, frames: Frames) -> Self { + Self { from, frames, refused: None } } fn charge(&mut self, from: Callback, interp: &mut Interpreter) { let gas = interp.gas.tracker(); - if from != self.from || - self.refused.is_some() || - (self.detained_only && gas.withheld() == 0) - { + let in_frames = match self.frames { + Frames::Any => true, + Frames::Detained => gas.withheld() > 0, + Frames::B => interp.input.target_address == B, + }; + if from != self.from || self.refused.is_some() || !in_frames { return; } let over = gas.spendable() + 1; @@ -174,6 +193,14 @@ impl Overdraws { } impl Inspector, EthInterpreter> for Overdraws { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + self.charge(Callback::InitializeInterp, interp); + } + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { self.charge(Callback::Step, interp); } @@ -204,7 +231,7 @@ impl Inspector, EthInterpreter> for Overdraws { fn test_an_inspector_cannot_overdraw_a_frame() { let limits = EvmTxRuntimeLimits::no_limits(); let (plain, _) = run::(a_calls_b(), limits, GAS_LIMIT, None); - let overdraws = Overdraws::new(Callback::StepEnd, false); + let overdraws = Overdraws::new(Callback::StepEnd, Frames::Any); let (overdrawn, inspector) = run(a_calls_b(), limits, GAS_LIMIT, Some(overdraws)); assert_eq!(inspector.unwrap().refused, Some(true), "the charge was refused"); assert_eq!(overdrawn.result, plain.result, "nothing was taken, and nothing halted"); @@ -224,7 +251,7 @@ fn test_an_inspector_cannot_overdraw_a_frame() { assert!(plain.result.is_success(), "{:?}", plain.result); for from in [Callback::Step, Callback::StepEnd, Callback::LogFull] { let (overdrawn, inspector) = - run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, true))); + run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, Frames::Detained))); assert_eq!(inspector.unwrap().refused, Some(true), "{from:?}: the withheld part"); assert_eq!(overdrawn.limit_exceeded, None, "{from:?}: no crossing"); assert_eq!(overdrawn.result, plain.result, "{from:?}"); @@ -232,6 +259,65 @@ fn test_an_inspector_cannot_overdraw_a_frame() { } } +/// A charge an inspector's callback could not pay is refused and leaves its record of what the +/// frame had, as revm leaves it: revm does not guard what a callback writes to the interpreter's +/// gas, and neither does the engine. `A` reads the block's timestamp, calls `B` with 2,000 gas, +/// then loops until the compute limit stops it. `B`'s callback charge is refused; `B` then pushes +/// and pops a hundred words and halts on a cold `BALANCE` it cannot pay, which the interpreter +/// refuses before any charge, so no failed deduction of its own records what `B` had. What `B` +/// burns is read off the refused charge's record: what `B` had at the callback, not at its halt. +/// The gas `B` ran in between counts as burned rather than as compute, so `A` runs that much longer +/// to the limit, and is billed that much more, than in the transaction no inspector runs. +#[test] +fn test_a_refused_charge_is_read_as_what_a_later_halt_burns() { + let b = BytecodeBuilder::default() + .append_many([PUSH0, POP].repeat(100)) + .push_address(COLD) + .append(BALANCE) + .stop() + .build(); + let a = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .push_number(2_000_u16) + .append_many([CALL, POP]); + let lap = a.len() as u8; + let a = a.append(JUMPDEST).push_number(lap).append(JUMP).build(); + let db = || MemoryDatabase::default().account_code(A, a.clone()).account_code(B, b.clone()); + let detained = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(20_000); + let (plain, _) = run::(db(), detained, GAS_LIMIT, None); + assert!(plain.limit_exceeded.is_some(), "the loop runs to the limit: {:?}", plain.result); + // What `B` runs before its halt: the pushes and pops, the address and `BALANCE`'s static gas. + let static_gas = gas_table_spec(SpecId::AMSTERDAM); + let to_the_halt = 100 * u64::from(static_gas[PUSH0 as usize] + static_gas[POP as usize]) + + u64::from(static_gas[PUSH20 as usize] + static_gas[BALANCE as usize]); + // What `B` ran before the callback: nothing before its first step, its first `PUSH0` before + // the step's end. + for (from, before) in [ + (Callback::InitializeInterp, 0), + (Callback::Step, 0), + (Callback::StepEnd, u64::from(static_gas[PUSH0 as usize])), + ] { + let (overdrawn, inspector) = + run(db(), detained, GAS_LIMIT, Some(Overdraws::new(from, Frames::B))); + assert_eq!(inspector.unwrap().refused, Some(true), "{from:?}: the charge was refused"); + let stop = |outcome: &MegaTransactionOutcome| match outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, limit, .. }) => Some((kind, limit)), + _ => None, + }; + assert_eq!(stop(&overdrawn), stop(&plain), "{from:?}: the same limit stops it"); + // The stop lands on the first of `A`'s loop charges the limit leaves no room for, so the + // bill grows by the extra room to within the loop's dearest charge, its `JUMP`. + let grown = overdrawn.gas.regular - plain.gas.regular; + assert!( + grown.abs_diff(to_the_halt - before) < u64::from(static_gas[JUMP as usize]), + "{from:?}: what B ran after the callback is burned, and A runs that much longer: \ + {grown} for {}", + to_the_halt - before + ); + } +} + /// How [`AnswersB`] builds the gas of its answer. #[derive(Clone, Copy, Debug)] enum AnswerGas { @@ -240,7 +326,7 @@ enum AnswerGas { /// `Gas::new` of the call's gas limit, as Foundry answers a cheatcode: no reservoir. Fresh, /// Fresh regular gas carrying the pools of the untouched gas after a state and a history - /// charge ([`with_pools_of`]): charges the frame, which never ran, did not make. + /// charge: charges the frame, which never ran, did not make. Charged, } @@ -262,7 +348,16 @@ impl Inspector, EthInterpreter> for AnswersB { assert!( charged.record_state_cost(40_000) && charged.record_history_cost(3_000) ); - with_pools_of(inputs.gas_limit, &charged) + let mut gas = Gas::new(inputs.gas_limit); + gas.set_reservoir(charged.reservoir()); + gas.set_state_gas_spent(charged.state_gas_spent()); + gas.set_state_gas_spilled(charged.state_gas_spilled()); + gas.set_history_gas_spent(charged.history_gas_spent()); + for pool in PoolId::ALL { + gas.set_pool_remaining(pool, charged.pool_remaining(pool)); + gas.set_pool_spent(pool, charged.pool_spent(pool)); + } + gas } }; CallOutcome::new( @@ -273,19 +368,23 @@ impl Inspector, EthInterpreter> for AnswersB { } } -/// An answered frame never ran, so its gas carries nothing but the regular gas its inspector -/// chose: its caller merges back the reservoir it forwarded, whatever `Gas` the answer was built -/// on. Above the execution cap, an answer on the frame's untouched gas, one on `Gas::new` — which -/// carries no reservoir — and one carrying charges the frame never made settle alike, a success, a -/// revert and a halt each, and the transaction keeps the reservoir it keeps when `B` runs. The -/// charges are rolled back against the answer's own reservoir before the inherited one replaces -/// it, so neither the reservoir nor a ledger counts them. +/// An answered frame never ran, and its caller settles the answer on the gas its inspector built +/// it on, as revm does. Above the execution cap, an answer on the frame's untouched gas carries the +/// reservoir share it inherited, and the transaction keeps the reservoir it keeps when `B` runs; +/// one on `Gas::new`, which carries none, leaves its caller only the part of its reservoir it kept +/// from the share, a success, a revert and a halt alike. +/// One carrying charges the frame never made merges them as a success's — the state and history +/// gas on their ledgers, drawn from the reservoir — and a revert or a halt rolls them back. #[test] -fn test_an_answer_carries_the_reservoir_its_caller_merges() { +fn test_an_answer_settles_on_the_gas_it_is_built_on() { let gas_limit = TX_GAS_LIMIT_CAP + 100_000_000; let limits = EvmTxRuntimeLimits::no_limits(); let (plain, _) = run::(a_calls_b(), limits, gas_limit, None); - assert!(plain.gas.reservoir_remaining > 0, "the reservoir comes back"); + // Nothing draws the reservoir: `A` holds all of it when it calls `B`, which takes its share. + let whole = gas_limit - TX_GAS_LIMIT_CAP - body_history(0); + assert_eq!(plain.gas.reservoir_remaining, whole, "the reservoir comes back"); + let kept = whole - reservoir_share(whole); + assert_ne!(kept, 0); for result in [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] { @@ -294,12 +393,27 @@ fn test_an_answer_carries_the_reservoir_its_caller_merges() { run(a_calls_b(), limits, gas_limit, Some(inspector)).0 }; let untouched = answer(AnswerGas::Untouched); + assert!(untouched.result.is_success(), "{result:?}: `A` ignores the answer"); assert_eq!(untouched.gas.reservoir_remaining, plain.gas.reservoir_remaining, "{result:?}"); - for gas in [AnswerGas::Fresh, AnswerGas::Charged] { - let answered = answer(gas); - assert!(answered.result.is_success(), "{result:?}, {gas:?}: `A` ignores the answer"); - assert_eq!(answered.gas, untouched.gas, "{result:?}, {gas:?}: every ledger"); - assert_eq!(answered.usage, untouched.usage, "{result:?}, {gas:?}: every count"); + + let fresh = answer(AnswerGas::Fresh); + assert!(fresh.result.is_success(), "{result:?}, fresh: `A` ignores the answer"); + assert_eq!(fresh.gas.reservoir_remaining, kept, "{result:?}: `Gas::new` carries none"); + assert_eq!(fresh.usage, untouched.usage, "{result:?}, fresh: every count"); + + let charged = answer(AnswerGas::Charged); + assert!(charged.result.is_success(), "{result:?}, charged: `A` ignores the answer"); + assert_eq!(charged.usage, untouched.usage, "{result:?}, charged: every count"); + if result.is_ok() { + assert_eq!(charged.gas.state, untouched.gas.state + 40_000, "{result:?}: merged"); + assert_eq!(charged.gas.history, untouched.gas.history + 3_000, "{result:?}: merged"); + assert_eq!( + charged.gas.reservoir_remaining, + untouched.gas.reservoir_remaining - 43_000, + "{result:?}: drawn from the reservoir" + ); + } else { + assert_eq!(charged.gas, untouched.gas, "{result:?}: rolled back, on every ledger"); } } } diff --git a/crates/mega-evm/tests/satin/inspector_settlement.rs b/crates/mega-evm/tests/satin/inspector_settlement.rs index 0464dce67..bd0d6ddbb 100644 --- a/crates/mega-evm/tests/satin/inspector_settlement.rs +++ b/crates/mega-evm/tests/satin/inspector_settlement.rs @@ -1,44 +1,40 @@ -//! What a frame that kept nothing settles into its caller, whatever an inspector made of its -//! result, and what a success an inspector rewrites into a failure keeps: nothing, the journal -//! following the result as it follows a frame that fails. +//! What a frame's result an inspector rewrites settles into: the result as given, as revm takes it. //! -//! Two frames keep nothing in the journal: one that failed, whose checkpoint was reverted before -//! the inspector saw its result, and one the inspector answered in place of running, which never -//! started. An inspector may still hand the caller a success for either — Foundry's `expectRevert` -//! turns a failed call into a success, and a mocked call is answered without running — and the -//! caller sees the success, the output and the regular gas the inspector left. Nothing else of the -//! frame reaches it: no state gas or history gas for writes the journal does not hold, no refund, -//! no write record, and no upfront charge for an account that was never added. +//! revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's +//! result, and the result the inspector hands back is the one its caller settles. So a failed frame +//! an inspector revives into a success — Foundry's `expectRevert` — keeps its journal reverted and +//! settles as a success: its state gas, history, refund and the records it counted merge into its +//! caller. A success it rewrites into a failure keeps its journal and settles as a failure: its +//! charges are rolled back, its counts restored and its start charge refunded. A frame it answers +//! in place of running never started: the charges its caller's opcode made for it stay charged, +//! since the answer carries no upfront-charge flag and no start charge for revm to give back, and +//! it counts nothing of its own. //! -//! Every expectation here is the rule's: a caller that drops the flag cannot tell a rewritten -//! failure from the failure, and a frame answered without running adds no account and writes -//! nothing, so the transaction's state gas is zero and its history is its body's. An answer -//! carries nothing but the regular gas the inspector chose, so every answer is given twice — on -//! the gas the frame was forwarded, untouched, and on `Gas::new` of it, as Foundry answers, which -//! carries no reservoir — and the two settle alike. Where a new -//! account is charged, its bucket is crowded (`m = 3`), so the charge that comes back is the one -//! that was made, priced at the account it was made for. +//! Every expectation is read off a twin no inspector touches: the same frame succeeding, or +//! failing, or the call running. Where a new account is charged, its bucket is crowded (`m = 3`), +//! so the charge is the one that was made, priced at the account it was made for. use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, history_gas, + op_revm::OpHaltReason, test_utils::{BytecodeBuilder, MemoryDatabase}, - transaction_body_bytes, untouched_call_gas, untouched_create_gas, LimitUsage, MegaContext, - MegaEvm, MegaTransaction, MegaTransactionOutcome, WRITE_RECORD_SIZE, + transaction_body_bytes, untouched_call_gas, untouched_create_gas, EvmTxRuntimeLimits, + LimitUsage, MegaContext, MegaEvm, MegaTransaction, MegaTransactionOutcome, }; use revm::{ bytecode::{ opcode::{CALL, POP, PUSH0, RETURN, REVERT, STOP}, Bytecode, }, - context::{ContextTr, JournalTr}, + context::{result::ExecutionResult, ContextTr, JournalTr}, context_interface::{cfg::GasId, journaled_state::account::JournaledAccountTr, Transaction}, + handler::SYSTEM_ADDRESS, interpreter::{ - interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, Gas, - InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, + interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue, CreateInputs, + CreateOutcome, InstructionResult, Interpreter, InterpreterResult, InterpreterTypes, }, - state::{AccountStatus, EvmStorageSlot}, Inspector, }; @@ -72,40 +68,31 @@ impl Inspector for Revives { } } -/// Answers every call to `target`, and every creation, itself with `result`, on the gas the frame -/// was forwarded, untouched, or, when `fresh`, on `Gas::new` of it: the frame never starts. An -/// answered creation reports `address`. +/// Answers every call to `target`, and every creation when `target` is zero, itself with `result`, +/// on the gas the frame was forwarded, untouched: the frame never starts. An answered creation +/// reports `address`. #[derive(Clone, Copy, Debug)] struct Answers { target: Address, result: InstructionResult, address: Option
, - fresh: bool, } impl Answers { const fn call(target: Address, result: InstructionResult) -> Self { - Self { target, result, address: None, fresh: false } + Self { target, result, address: None } } const fn creation(result: InstructionResult, address: Option
) -> Self { - Self { target: Address::ZERO, result, address, fresh: false } - } - - /// The same answers, built on `Gas::new` of the gas the frame was forwarded, as Foundry - /// answers a cheatcode: gas that carries no reservoir. - const fn on_fresh_gas(self) -> Self { - Self { fresh: true, ..self } + Self { target: Address::ZERO, result, address } } } impl Inspector for Answers { fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { (inputs.target_address == self.target).then(|| { - let gas = - if self.fresh { Gas::new(inputs.gas_limit) } else { untouched_call_gas(inputs) }; CallOutcome::new( - InterpreterResult::new(self.result, Bytes::new(), gas), + InterpreterResult::new(self.result, Bytes::new(), untouched_call_gas(inputs)), inputs.return_memory_offset.clone(), ) }) @@ -113,11 +100,7 @@ impl Inspector for Answers { fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { (self.target == Address::ZERO).then(|| { - let gas = if self.fresh { - Gas::new(inputs.gas_limit()) - } else { - untouched_create_gas(inputs) - }; + let gas = untouched_create_gas(inputs); CreateOutcome::new(InterpreterResult::new(self.result, Bytes::new(), gas), self.address) }) } @@ -144,31 +127,16 @@ where .expect("a valid transaction") } -/// Runs `tx` over `db()` reading `envs()` under `answers`, on the gas the answered frame was -/// forwarded, untouched, and again on `Gas::new` of it; hands back the first once the second -/// settled alike. The frame never ran, so its answer carries nothing but the regular gas the -/// inspector chose, and its caller merges back the reservoir it forwarded whatever the answer was -/// built on. -fn answered( - db: impl Fn() -> MemoryDatabase, - envs: impl Fn() -> SaltEnvs, - tx: &MegaTransaction, - answers: Answers, -) -> MegaTransactionOutcome { - let untouched = inspected(db(), envs(), tx.clone(), answers); - let fresh = inspected(db(), envs(), tx.clone(), answers.on_fresh_gas()); - assert_eq!(fresh.result, untouched.result, "{answers:?}: on fresh gas"); - assert_eq!(fresh.gas, untouched.gas, "{answers:?}: every ledger, on fresh gas"); - assert_eq!(fresh.usage, untouched.usage, "{answers:?}: every count, on fresh gas"); - assert_eq!(fresh.state, untouched.state, "{answers:?}: the state, on fresh gas"); - untouched -} - /// A call from `CALLER` to `to` carrying `value` and `data`, at `gas_limit`. fn to(to: Address, value: u64, data: Bytes, gas_limit: u64) -> MegaTransaction { tx_with_gas(TxKind::Call(to), data, U256::from(value), gas_limit) } +/// What `tx` counts before any frame: its body's bytes, and no write record. +fn body_usage(tx: &MegaTransaction) -> LimitUsage { + LimitUsage { data_size: transaction_body_bytes(tx), write_records: 0, state_growth: 0 } +} + /// A transaction that keeps nothing but its body: no state gas, its body's history alone, and its /// body's bytes alone on the data size. Above the execution cap the reservoir paid for the body and /// nothing else, so what is left of it comes back. @@ -182,7 +150,14 @@ fn assert_keeps_only_its_body(case: &str, tx: &MegaTransaction, outcome: &MegaTr "{case}: the reservoir less the body's history" ); assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!(outcome.usage, body_usage(tx), "{case}"); +} + +/// Requires `outcome` to bill the state gas and the history `charged` bills: the charges the run +/// made and kept, which a result an inspector rewrote kept too. +fn assert_bills_as(case: &str, outcome: &MegaTransactionOutcome, charged: &MegaTransactionOutcome) { + assert_eq!(outcome.gas.state, charged.gas.state, "{case}: the state gas"); + assert_eq!(outcome.gas.history, charged.gas.history, "{case}: the history gas"); } /// Whether `account` holds anything in `outcome`'s state. @@ -190,13 +165,15 @@ fn holds_something(outcome: &MegaTransactionOutcome, account: Address) -> bool { outcome.state.get(&account).is_some_and(|account| !account.info.is_empty()) } +/* ---------- a failure revived into a success ---------- */ + /// `CALLEE` fills a fresh slot, clears a slot it held (a refund), logs a word, then reverts; -/// `CONTRACT` calls it and drops the flag. Rewritten into a success, the call is the revert it was -/// to everything but the flag `CONTRACT` drops: the transaction is the one no inspector runs, on -/// every ledger. Kept, the same writes cost state gas, history and a refund — what the rewrite -/// would otherwise have merged. +/// `CONTRACT` calls it and drops the flag. Revived into a success, the call keeps the state of the +/// revert — its journal was reverted before the inspector saw it, so no slot and no log — and +/// settles as the success: its caller merges the state gas, the history, the refund and the +/// records of the same writes kept, on every ledger. #[test] -fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { +fn test_a_failed_call_revived_into_a_success_settles_as_a_success() { let writes = || { BytecodeBuilder::default() .sstore(U256::from(1), U256::from(1)) @@ -212,36 +189,43 @@ fn test_a_failed_call_rewritten_into_a_success_settles_as_the_failure() { ) }; let reverting = setup(writes().revert().build()); - let stopping = setup(writes().stop().build()); + // Returning nothing costs what reverting with nothing does, so the two spend the same and the + // refund's cap is the same for both. + let stopping = setup(writes().return_empty().build()); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); let kept = plain(stopping.clone(), minimal_envs(), tx.clone()); assert!(kept.result.is_success(), "{:?}", kept.result); - assert_eq!( - kept.gas.state, - entry(GasId::sstore_set_state_gas()), - "kept, the fresh slot costs state gas" - ); + assert_eq!(kept.gas.state, entry(GasId::sstore_set_state_gas()), "the fresh slot"); assert_eq!(kept.usage.write_records, 2, "and both slots are records"); - let failed = plain(reverting.clone(), minimal_envs(), tx.clone()); - let rewritten = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); - assert!(failed.result.is_success(), "CONTRACT drops the flag: {:?}", failed.result); assert_keeps_only_its_body("the failed call", &tx, &failed); - assert_eq!(rewritten.result, failed.result, "no log, and the same bill"); - assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + + let revived = inspected(reverting.clone(), minimal_envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(revived.result.logs().is_empty(), "{case}: the log went with the journal"); + assert_eq!(revived.state, failed.state, "{case}: the state is the revert's"); + assert_bills_as(&case, &revived, &kept); + assert_eq!(revived.gas.history_bytes, kept.gas.history_bytes, "{case}"); + assert_eq!(revived.usage, kept.usage, "{case}: the counts are the success's"); + assert_eq!( + revived.result.gas().inner_refunded(), + kept.result.gas().inner_refunded(), + "{case}: and so is the refund" + ); + assert_eq!(revived.gas, kept.gas, "{case}: every ledger is the success's"); } } /// `CONTRACT` sends a wei to the BN254 pairing precompile with no gas of its own: the stipend is -/// short of the pairing's price, so the call runs out of gas, and the account its value would add -/// — the upfront new-account charge its `CALL` made — goes with it. Rewritten into a success, the -/// call gives that charge back all the same: the transaction is the one no inspector runs. With the -/// gas to run, the same call adds the account and keeps the charge. +/// short of the pairing's price, so the call runs out of gas, and the account its value would add — +/// the upfront new-account charge its `CALL` made — and its start's records go with it. Revived +/// into a success, no wei moved, and the call keeps both charges, as the call that runs keeps them: +/// a success gives back neither. revm decided the start as a failure, which counted nothing, so the +/// transaction counts its body alone. #[test] -fn test_a_failed_value_call_rewritten_into_a_success_gives_the_new_account_charge_back() { +fn test_a_failed_value_call_revived_into_a_success_keeps_its_charges() { let caller = |gas: u64| { BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) @@ -255,28 +239,28 @@ fn test_a_failed_value_call_rewritten_into_a_success_gives_the_new_account_charg }; let envs = || crowded_account(minimal_envs(), PAIRING, 3); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); let ran = plain(db(caller(1_000_000)), envs(), tx.clone()); assert!(holds_something(&ran, PAIRING), "the pairing ran and kept the wei"); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let failed = plain(db(caller(0)), envs(), tx.clone()); - let rewritten = inspected(db(caller(0)), envs(), tx.clone(), Revives); assert_keeps_only_its_body("the failed call", &tx, &failed); - assert!(!holds_something(&rewritten, PAIRING), "no wei moved"); - assert_eq!(rewritten.gas, failed.gas, "gas limit {gas_limit}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "gas limit {gas_limit}: the counts"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + + let revived = inspected(db(caller(0)), envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(!holds_something(&revived, PAIRING), "{case}: no wei moved"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, body_usage(&tx), "{case}: nothing counted"); } } /// The transaction's own frame: a wei sent to the BN254 addition precompile with a point off the /// curve fails, and takes back the account EIP-2780 charged its start for and the write record -/// charged before execution. Rewritten into a success, the transaction reports the success and -/// keeps only its body, as the failure does. With a point on the curve, the same transaction adds -/// the account and keeps both charges. +/// charged before execution. Revived into a success, no wei moved, and the transaction keeps both +/// charges, as the transaction with a point on the curve keeps them; its start counted nothing. #[test] -fn test_the_transactions_own_failed_frame_rewritten_into_a_success_keeps_nothing() { +fn test_the_transactions_own_failed_frame_revived_into_a_success_keeps_its_charges() { let point_off_the_curve = { let mut input = [0_u8; 128]; input[31] = 1; @@ -285,32 +269,102 @@ fn test_the_transactions_own_failed_frame_rewritten_into_a_success_keeps_nothing }; let envs = || crowded_account(minimal_envs(), ADDITION, 3); for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); let valid = to(ADDITION, 1, Bytes::from(vec![0_u8; 128]), gas_limit); - let ran = plain(db(Bytes::new()), envs(), valid.clone()); + let ran = plain(db(Bytes::new()), envs(), valid); assert!(ran.result.is_success(), "{:?}", ran.result); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let body = transaction_body_bytes(&valid); - assert_eq!(ran.gas.history_bytes, body + WRITE_RECORD_SIZE, "the body and the record"); let tx = to(ADDITION, 1, point_off_the_curve.clone(), gas_limit); let failed = plain(db(Bytes::new()), envs(), tx.clone()); assert!(failed.result.is_halt(), "{:?}", failed.result); assert_keeps_only_its_body("the failed transaction", &tx, &failed); - let rewritten = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); - assert!(rewritten.result.is_success(), "the inspector's: {:?}", rewritten.result); - assert_keeps_only_its_body("the rewritten transaction", &tx, &rewritten); - assert!(!holds_something(&rewritten, ADDITION), "no wei moved"); - assert_eq!(rewritten.state, failed.state, "gas limit {gas_limit}: the state"); + let revived = inspected(db(Bytes::new()), envs(), tx.clone(), Revives); + assert!(revived.result.is_success(), "{case}: the inspector's: {:?}", revived.result); + assert!(!holds_something(&revived, ADDITION), "{case}: no wei moved"); + assert_eq!(revived.state, failed.state, "{case}: the state is the failure's"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, body_usage(&tx), "{case}: nothing counted"); + } +} + +/// Turns every failed creation result into a success at `0x…01`, as Foundry's `expectRevert` on a +/// creation does: the revert's output and gas stay as they are, and the address is one the +/// creation never made. +struct RevivesCreations; + +impl Inspector for RevivesCreations { + fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { + if !outcome.result.result.is_ok() { + outcome.result.result = InstructionResult::Return; + outcome.address = Some(Address::with_last_byte(1)); + } + } +} + +/// Where a creation case runs one init code: the code of `CONTRACT` and the transaction. +type CreationSetup<'a> = &'a dyn Fn(&[u8]) -> (Bytes, MegaTransaction); + +/// A creation whose init code fills a fresh slot, logs a word and reverts, revived into a success, +/// keeps the state of the revert — no account, no slot, no log — and settles as the creation that +/// returns no code does: the upfront charge for the account, priced at its bucket (`m = 3`), the +/// slot, the records and the log's bytes, all kept. At the transaction's own frame and one call +/// down, carrying no value and one wei, below and above the execution cap. +#[test] +fn test_a_failed_creation_revived_into_a_success_settles_as_a_success() { + let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); + // Returning no code, as long as reverting, so the transaction's own creation carries a body of + // the same size either way. + let stopping = writes().append_many([PUSH0, PUSH0, RETURN]).build(); + let reverting = writes().revert().build(); + for (gas_limit, value) in GAS_LIMITS.into_iter().flat_map(|limit| [(limit, 0), (limit, 1)]) { + let creates = |init: &[u8]| { + BytecodeBuilder::default().create(U256::from(value), init).append(POP).stop().build() + }; + let own = |init: &[u8]| { + let data = Bytes::copy_from_slice(init); + (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(value), gas_limit)) + }; + let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); + let cases: [(&str, Address, CreationSetup<'_>); 2] = [ + ("the transaction's own", CALLER.create(0), &own), + ("one call down", CONTRACT.create(0), &down), + ]; + for (at, created, setup) in cases { + let envs = || crowded_account(minimal_envs(), created, 3); + let case = format!("{at}, value {value}, gas limit {gas_limit}"); + let (code, tx) = setup(&stopping[..]); + let ran = plain(db(code), envs(), tx); + assert!(holds_something(&ran, created), "{case}: run, the creation adds its account"); + assert_eq!( + ran.gas.state, + 3 * entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()), + "{case}: the account in its bucket and the slot" + ); + + let (code, tx) = setup(&reverting[..]); + let failed = plain(db(code.clone()), envs(), tx.clone()); + assert!(!holds_something(&failed, created), "{case}: reverting, it adds none"); + let revived = inspected(db(code), envs(), tx.clone(), RevivesCreations); + assert!(revived.result.is_success(), "{case}: {:?}", revived.result); + assert!(!holds_something(&revived, created), "{case}: no account"); + assert!(revived.result.logs().is_empty(), "{case}: no log"); + assert_bills_as(&case, &revived, &ran); + assert_eq!(revived.usage, ran.usage, "{case}: the counts are the success's"); + } } } +/* ---------- a frame an inspector answers ---------- */ + /// A value call to an account that does not exist, answered by an inspector with a success, a -/// revert or a halt: the frame never started, so no wei moved and no account was added, and the -/// new-account charge its `CALL` made comes back whatever the answer. The three answers cost the -/// same, and the transaction keeps only its body. Run, the call adds the account in its bucket. +/// revert or a halt: the frame never started, so no wei moved and no account was added, and nothing +/// of the start is counted. The charges the `CALL` made for it — the account, at its bucket, and +/// the history of the records its start would make — stay charged, as for the call that runs: the +/// answer carries no flag and no start charge for revm to give back. #[test] -fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { +fn test_a_value_call_an_inspector_answers_keeps_what_its_opcode_was_charged() { let caller = || value_call(EMPTY).append(POP).stop().build(); let envs = || crowded_account(minimal_envs(), EMPTY, 3); for gas_limit in GAS_LIMITS { @@ -319,27 +373,26 @@ fn test_a_value_call_an_inspector_answers_gives_its_new_account_charge_back() { assert!(holds_something(&ran, EMPTY), "the call added the account"); assert_eq!(ran.gas.state, 3 * entry(GasId::new_account_state_gas()), "in its bucket"); - let answers = - [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas].map( - |result| { - let answered = - answered(|| db(caller()), envs, &tx, Answers::call(EMPTY, result)); - let case = format!("answered with {result:?}, gas limit {gas_limit}"); - assert!(answered.result.is_success(), "{case}: {:?}", answered.result); - assert_keeps_only_its_body(&case, &tx, &answered); - assert!(!holds_something(&answered, EMPTY), "{case}: no account"); - (answered.gas, answered.state.clone()) - }, - ); - assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: a success costs a revert's"); + for result in + [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] + { + let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answered = + inspected(db(caller()), envs(), tx.clone(), Answers::call(EMPTY, result)); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); + } } } /// The transaction's own value transfer to an account that does not exist, answered by an -/// inspector: the account EIP-2780 charged the frame's start for is not added, and neither is the -/// write record charged before execution, whatever the answer. +/// inspector: the account is not added and nothing is counted, and what the transaction was charged +/// before its frame ran — the account EIP-2780 charged its start for, the write record — stays +/// charged, as for the transfer that runs. #[test] -fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_nothing() { +fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_its_charges() { let envs = || crowded_account(minimal_envs(), EMPTY, 3); for gas_limit in GAS_LIMITS { let tx = to(EMPTY, 1, Bytes::new(), gas_limit); @@ -348,19 +401,23 @@ fn test_the_transactions_own_value_transfer_an_inspector_answers_keeps_nothing() for result in [InstructionResult::Stop, InstructionResult::Revert] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = answered(|| db(Bytes::new()), envs, &tx, Answers::call(EMPTY, result)); + let answered = + inspected(db(Bytes::new()), envs(), tx.clone(), Answers::call(EMPTY, result)); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, EMPTY), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); } } } -/// A creation an inspector answers adds no account, whatever the answer — a success with an -/// address, a success with none, a revert — so the creation's upfront charge comes back once, and -/// the three answers cost the same. Run, the creation adds its account in its bucket. +/// A creation an inspector answers adds no account and bumps no nonce, whatever the answer — a +/// success with an address, a success with none, a revert — and the charges its `CREATE` made stay +/// charged, as for the creation that runs: the account at its bucket, the history of its records. +/// It counts no record: the creator's nonce was not bumped, so no record of it stands. The three +/// answers cost the same. #[test] -fn test_a_creation_an_inspector_answers_gives_its_charge_back() { +fn test_a_creation_an_inspector_answers_keeps_what_its_opcode_was_charged() { let caller = || create_with(&[STOP]).append(POP).stop().build(); let created = CONTRACT.create(0); let envs = || crowded_account(minimal_envs(), created, 3); @@ -369,6 +426,7 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { let ran = plain(db(caller()), envs(), tx.clone()); assert!(ran.result.is_success(), "{:?}", ran.result); assert_eq!(ran.gas.state, 3 * entry(GasId::create_state_gas()), "in its bucket"); + let nonce = ran.state[&CONTRACT].info.nonce; let answers = [ (InstructionResult::Return, Some(ANSWERED)), @@ -376,11 +434,14 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { (InstructionResult::Revert, None), ] .map(|(result, address)| { - let answered = answered(|| db(caller()), envs, &tx, Answers::creation(result, address)); let case = format!("answered with {result:?}, gas limit {gas_limit}"); + let answers = Answers::creation(result, address); + let answered = inspected(db(caller()), envs(), tx.clone(), answers); assert!(answered.result.is_success(), "{case}: {:?}", answered.result); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, created), "{case}: no account"); + assert_eq!(answered.state[&CONTRACT].info.nonce, nonce - 1, "{case}: no bump"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage.write_records, 0, "{case}: no bump, no record"); answered.gas }); assert_eq!(answers[0], answers[1], "gas limit {gas_limit}: with an address or without"); @@ -388,11 +449,11 @@ fn test_a_creation_an_inspector_answers_gives_its_charge_back() { } } -/// The transaction's own creation, answered by an inspector: the account EIP-2780 charged the -/// frame's start for is not added, and neither is the write record charged before execution, -/// whatever the answer. Run, the creation adds its account in its bucket. +/// The transaction's own creation, answered by an inspector: the account is not added and nothing +/// is counted, and what the transaction was charged before its frame ran — the account EIP-2780 +/// charged its start for, the write record — stays charged, as for the creation that runs. #[test] -fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { +fn test_the_transactions_own_creation_an_inspector_answers_keeps_its_charges() { let created = CALLER.create(0); let envs = || crowded_account(minimal_envs(), created, 3); for gas_limit in GAS_LIMITS { @@ -407,42 +468,16 @@ fn test_the_transactions_own_creation_an_inspector_answers_keeps_nothing() { (InstructionResult::Revert, None), ] { let case = format!("answered with {result:?}, gas limit {gas_limit}"); - let answered = - answered(|| db(Bytes::new()), envs, &tx, Answers::creation(result, address)); + let answers = Answers::creation(result, address); + let answered = inspected(db(Bytes::new()), envs(), tx.clone(), answers); assert_eq!(answered.result.is_success(), result.is_ok(), "{case}: the answer"); - assert_keeps_only_its_body(&case, &tx, &answered); assert!(!holds_something(&answered, created), "{case}: no account"); + assert_bills_as(&case, &answered, &ran); + assert_eq!(answered.usage, body_usage(&tx), "{case}: nothing counted"); } } } -/// A value call an inspector answers leaves its caller holding none of the state gas its `CALL` -/// was charged for the account: the charge came back. The caller then fills a slot, and holds the -/// slot alone, where the caller whose call ran holds the slot and the account. -#[test] -fn test_an_answered_call_leaves_its_caller_none_of_the_accounts_state_gas() { - let caller = - || value_call(EMPTY).append(POP).sstore(U256::from(1), U256::from(1)).stop().build(); - let slot = entry(GasId::sstore_set_state_gas()); - let tx = to(CONTRACT, 0, Bytes::new(), GAS_LIMITS[0]); - let context = || salt_context(db(caller()), minimal_envs()); - - let ran = MegaEvm::new(context()).execute_transaction(tx.clone()).unwrap(); - assert!(ran.result.is_success(), "{:?}", ran.result); - assert_eq!( - ran.gas.state, - slot + entry(GasId::new_account_state_gas()), - "the slot and the account" - ); - - let answered = MegaEvm::new(context()) - .with_inspector(Answers::call(EMPTY, InstructionResult::Stop)) - .execute_transaction(tx) - .unwrap(); - assert!(answered.result.is_success(), "{:?}", answered.result); - assert_eq!(answered.gas.state, slot, "the slot alone"); -} - /* ---------- a call an inspector retargets ---------- */ /// The address `Retargets` sends a call to. @@ -477,18 +512,18 @@ impl Inspector for Retargets } /// A value call to an account that does not exist charges that account's state gas upfront, in its -/// SALT bucket. An inspector that redirects the call to another account, whose bucket is priced -/// otherwise, changes which account the charge comes back for: it comes back at the price it was -/// made at, the original account's, whatever the new target costs. Both ways — the account dearer -/// than the new target (`m` = 8 and 1) and cheaper (1 and 8) — the call answered in place of -/// running, and the call that runs and reverts, keep nothing: no state gas, the body's history -/// alone, and the reservoir back where it started. A refund at the new target's price would leave -/// state gas behind in one direction and drive the state ledger negative, growing the reservoir, -/// in the other. +/// SALT bucket. An inspector that redirects the call to another account rewrites the inputs revm +/// reads the charge's account off when the frame fails: the call that runs at the new target and +/// reverts gives the charge back at the new target's price. Where the account is dearer (`m` = 8 +/// and 1) the transaction keeps the difference as state gas; where it is cheaper (1 and 8) more +/// comes back than was charged, which revm credits to the reservoir, so the state ledger reads +/// nothing and the sender gets the excess back with the reservoir. The call answered in place of +/// running gives back nothing, as every answer does. #[test] -fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_price_it_was_made_at() { +fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_new_targets_price() { let caller = || value_call(EMPTY).append(POP).stop().build(); let reverts = Bytecode::new_raw(Bytes::from_static(&[PUSH0, PUSH0, REVERT])); + let account = entry(GasId::new_account_state_gas()); for (account_m, retarget_m) in [(8, 1), (1, 8)] { let envs = || { crowded_account(crowded_account(minimal_envs(), EMPTY, account_m), RETARGET, retarget_m) @@ -499,85 +534,32 @@ fn test_a_retargeted_value_calls_upfront_charge_comes_back_at_the_price_it_was_m let ran = plain(db(), envs(), tx.clone()); assert_eq!( ran.gas.state, - account_m * entry(GasId::new_account_state_gas()), + account_m * account, "{account_m}/{retarget_m}: run, the call adds the account in its bucket" ); - for (name, answer) in - [("answered", Some(InstructionResult::Stop)), ("running and reverting", None)] - { - let case = format!("{name}, m {account_m}/{retarget_m}, gas limit {gas_limit}"); - let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; - let outcome = inspected(db(), envs(), tx.clone(), inspector); - assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); - assert_keeps_only_its_body(&case, &tx, &outcome); - assert!(!holds_something(&outcome, EMPTY), "{case}: no account"); - } - } - } -} - -/* ---------- a failed creation rewritten into a success ---------- */ - -/// Turns every failed creation result into a success at `0x…01`, as Foundry's `expectRevert` on a -/// creation does: the revert's output and gas stay as they are, and the address is one the -/// creation never made. -struct RevivesCreations; - -impl Inspector for RevivesCreations { - fn create_end(&mut self, _: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) { - if !outcome.result.result.is_ok() { - outcome.result.result = InstructionResult::Return; - outcome.address = Some(Address::with_last_byte(1)); - } - } -} - -/// A creation whose init code fills a fresh slot, logs a word and reverts, rewritten into a -/// success, is the failure it was to everything but the address its creator is handed: every -/// ledger, the counts and the state are those of the run no inspector touches. The upfront charge -/// the `CREATE` made for the account comes back, priced at the account it was made for — its bucket -/// is crowded (`m = 3`) — and the slot, the log and the account are not kept. At the transaction's -/// own frame and one call down, carrying no value and one wei, below and above the execution cap; -/// run, the creation adds its account. -#[test] -fn test_a_failed_creation_rewritten_into_a_success_settles_as_the_failure() { - let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); - let (reverting, stopping) = (writes().revert().build(), writes().stop().build()); - for (gas_limit, value) in GAS_LIMITS.into_iter().flat_map(|limit| [(limit, 0), (limit, 1)]) { - let creates = |init: &[u8]| { - BytecodeBuilder::default().create(U256::from(value), init).append(POP).stop().build() - }; - let own = |init: &[u8]| { - let data = Bytes::copy_from_slice(init); - (Bytes::new(), tx_with_gas(TxKind::Create, data, U256::from(value), gas_limit)) - }; - let down = |init: &[u8]| (creates(init), to(CONTRACT, 0, Bytes::new(), gas_limit)); - let cases: [(&str, Address, CreationSetup<'_>); 2] = [ - ("the transaction's own", CALLER.create(0), &own), - ("one call down", CONTRACT.create(0), &down), - ]; - for (at, created, setup) in cases { - let envs = || crowded_account(minimal_envs(), created, 3); - let case = format!("{at}, value {value}, gas limit {gas_limit}"); - let (code, tx) = setup(&stopping[..]); - let ran = plain(db(code), envs(), tx); - assert!(holds_something(&ran, created), "{case}: run, the creation adds its account"); + let case = format!("m {account_m}/{retarget_m}, gas limit {gas_limit}"); + let answer = Some(InstructionResult::Stop); + let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer }; + let answered = inspected(db(), envs(), tx.clone(), inspector); + assert!(answered.result.is_success(), "{case}: {:?}", answered.result); + assert_eq!(answered.gas.state, account_m * account, "{case}: answered, kept whole"); + + let inspector = Retargets { from: EMPTY, code: reverts.clone(), answer: None }; + let reverted = inspected(db(), envs(), tx.clone(), inspector); + assert!(reverted.result.is_success(), "{case}: {:?}", reverted.result); + assert!(!holds_something(&reverted, EMPTY), "{case}: no account"); + let body = history_gas(transaction_body_bytes(&tx)).unwrap(); + assert_eq!(reverted.gas.history, body, "{case}: the start's records given back"); + let kept = i128::from(account_m * account) - i128::from(retarget_m * account); + let reservoir = + i128::from(gas_limit.saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(body)); + let reservoir = if reservoir == 0 { (-kept).max(0) } else { reservoir - kept }; assert_eq!( - ran.gas.state, - 3 * entry(GasId::create_state_gas()) + entry(GasId::sstore_set_state_gas()), - "{case}: the account in its bucket and the slot" + i128::from(reverted.gas.state), + kept.max(0), + "{case}: reverting, given back at the new target's price" ); - - let (code, tx) = setup(&reverting[..]); - let failed = plain(db(code.clone()), envs(), tx.clone()); - assert!(!holds_something(&failed, created), "{case}: reverting, it adds none"); - let rewritten = inspected(db(code), envs(), tx.clone(), RevivesCreations); - assert!(rewritten.result.is_success(), "{case}: {:?}", rewritten.result); - assert!(!holds_something(&rewritten, created), "{case}: no account"); - assert!(rewritten.result.logs().is_empty(), "{case}: no log"); - assert_eq!(rewritten.gas, failed.gas, "{case}: every ledger"); - assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.state, failed.state, "{case}: the state"); + assert_eq!(i128::from(reverted.gas.reservoir_remaining), reservoir, "{case}"); } } } @@ -640,7 +622,7 @@ impl Inspector for Fails { /// Runs `tx` over `db()` reading `envs()` under `fails`, and again under the same inspector /// rewriting nothing; hands back the first once the journal's depth was the same at every -/// instruction of both: taking a frame's journal back leaves the depth as it was. +/// instruction of both: a rewrite leaves the depth as it was. fn rewritten( db: impl Fn() -> MemoryDatabase, envs: impl Fn() -> SaltEnvs, @@ -661,35 +643,15 @@ fn rewritten( /// The failures a success is rewritten into: Foundry's revert, and a halt. const FAILURES: [InstructionResult; 2] = [InstructionResult::Revert, InstructionResult::OutOfGas]; -/// An account as a state is compared on without its code: status, balance, nonce and storage. -type AccountBesideCode = (Address, AccountStatus, U256, u64, Vec<(U256, EvmStorageSlot)>); - -/// `outcome`'s state without the code of its accounts, in address order: what two runs whose -/// programs differ in their last opcodes are compared on. -fn state_without_code(outcome: &MegaTransactionOutcome) -> Vec { - let mut accounts: Vec<_> = outcome - .state - .iter() - .map(|(address, account)| { - let mut storage: Vec<_> = - account.storage.iter().map(|(key, slot)| (*key, slot.clone())).collect(); - storage.sort_by_key(|(key, _)| *key); - (*address, account.status, account.info.balance, account.info.nonce, storage) - }) - .collect(); - accounts.sort_by_key(|(address, ..)| *address); - accounts -} - -/// A value call that adds an account, rewritten into a failure, keeps nothing. `EMPTY` has no code, -/// so revm answers the call without building a frame, and what its start journaled — the value's -/// move, the account it touched, the transfer log — is taken back to where the start began: the -/// value stays with its sender and no account is added. The failure then settles as the same -/// failure an inspector answers in place of the call does, on every ledger and in the state: no -/// state gas, the body's history alone. At the transaction's own frame and one call down, below -/// and above the execution cap; run, the call adds the account and logs the transfer. +/// A value call that adds an account, rewritten into a failure, settles as a failure and keeps the +/// state of its success. `EMPTY` has no code, so revm answers the call without building a frame and +/// commits what its start journaled — the value's move, the account it adds, the transfer log — +/// before the inspector sees the result: the wei stays with `EMPTY`. The failure gives back the +/// upfront charge for the account, the history of the start's records and the records themselves, +/// so the transaction bills its body alone. At the transaction's own frame and one call down, +/// below and above the execution cap. #[test] -fn test_a_value_call_rewritten_into_a_failure_keeps_nothing() { +fn test_a_value_call_rewritten_into_a_failure_keeps_its_state_and_bills_its_body() { let envs = || crowded_account(minimal_envs(), EMPTY, 3); let caller = value_call(EMPTY).append(POP).stop().build(); for gas_limit in GAS_LIMITS { @@ -701,33 +663,27 @@ fn test_a_value_call_rewritten_into_a_failure_keeps_nothing() { let db = || db(code.clone()); let ran = plain(db(), envs(), tx.clone()); assert!(holds_something(&ran, EMPTY), "{at}: run, the call adds the account"); - assert_eq!(ran.result.logs().len(), 1, "{at}: and logs the transfer"); for result in FAILURES { let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let rewritten = rewritten(db, envs, &tx, Fails::call(EMPTY, result)); - let answered = inspected(db(), envs(), tx.clone(), Answers::call(EMPTY, result)); + assert!(holds_something(&rewritten, EMPTY), "{case}: the wei moved"); + assert_eq!( + rewritten.state[&EMPTY].info, ran.state[&EMPTY].info, + "{case}: the account the success added" + ); assert_keeps_only_its_body(&case, &tx, &rewritten); - assert!(!holds_something(&rewritten, EMPTY), "{case}: no account"); - assert!(rewritten.result.logs().is_empty(), "{case}: no transfer log"); - assert_eq!(rewritten.gas, answered.gas, "{case}: every ledger"); - assert_eq!(rewritten.usage, answered.usage, "{case}: every count"); - assert_eq!(rewritten.state, answered.state, "{case}: the state"); } } } } -/// Where a creation case runs one init code: the code of `CONTRACT` and the transaction. -type CreationSetup<'a> = &'a dyn Fn(&[u8]) -> (Bytes, MegaTransaction); - -/// A creation rewritten into a failure keeps what a creation that fails keeps: its creator's nonce -/// bump, which revm makes before the creation's checkpoint, and its record — nothing after the -/// checkpoint: no account, no code, no endowment. It settles as a creation whose init code reverts -/// in place of returning does, on the state beside the code, state and history gas and the counts; -/// a revert keeps the regular gas the run spent. At the transaction's own frame and one call down, -/// below and above the execution cap; run, the creation adds its account. +/// A creation rewritten into a failure keeps the state of its success — its account, its code and +/// its endowment — and settles as the creation whose init code reverts in place of returning does: +/// its creator's nonce record, which outlives the creation, and nothing of the creation's own — no +/// state gas, no history and no record of the account. At the transaction's own frame and one call +/// down, below and above the execution cap. #[test] -fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() { +fn test_a_creation_rewritten_into_a_failure_keeps_its_state_and_settles_as_a_failure() { let (deploys, reverts) = (&[PUSH0, PUSH0, RETURN][..], &[PUSH0, PUSH0, REVERT][..]); let creates = |init: &[u8]| { BytecodeBuilder::default().create(U256::from(1), init).append(POP).stop().build() @@ -753,16 +709,13 @@ fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let rewritten = rewritten(|| db(deploying.clone()), envs, &tx, Fails::creation(result)); - assert!(!holds_something(&rewritten, created), "{case}: no account"); - let state = state_without_code(&rewritten); - assert_eq!(state, state_without_code(&failed), "{case}: the state"); + assert_eq!( + rewritten.state[&created].info.balance, ran.state[&created].info.balance, + "{case}: the account and its endowment" + ); assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); - assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); + assert_bills_as(&case, &rewritten, &failed); assert_eq!(rewritten.gas.history_bytes, failed.gas.history_bytes, "{case}"); - if result == InstructionResult::Revert { - assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); - } } } } @@ -772,13 +725,12 @@ fn test_a_creation_rewritten_into_a_failure_keeps_what_a_failed_creation_keeps() type CallSetup<'a> = &'a dyn Fn(&Bytes) -> MemoryDatabase; /// A call whose frame ran and wrote — a fresh slot filled and a word logged — rewritten into a -/// failure keeps none of it: the frame's journal is taken back to its checkpoint, so the slot is -/// not in the state and the log is not in the receipt. It settles as the same writes reverting do, -/// on the state beside the code, state and history gas and the counts; a revert keeps the regular -/// gas the run spent. At the transaction's own frame and one call down, below and above the -/// execution cap; run, the slot and the log are kept. +/// failure keeps its writes: revm committed the frame's checkpoint before the inspector saw the +/// result, so the slot is in the state, and one call down the log is in the receipt. It settles as +/// the same writes reverting do: their state gas, history and records given back. At the +/// transaction's own frame and one call down, below and above the execution cap. #[test] -fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_none_of_it() { +fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_its_writes_and_settles_as_a_failure() { let writes = || BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).log3_word(); let (stopping, reverting) = (writes().stop().build(), writes().revert().build()); let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); @@ -792,23 +744,18 @@ fn test_a_call_that_wrote_rewritten_into_a_failure_keeps_none_of_it() { let slot = |outcome: &MegaTransactionOutcome| { outcome.state[&writer].storage.get(&U256::from(1)).is_some_and(|s| s.is_changed()) }; - let ran = plain(setup(&stopping), minimal_envs(), tx.clone()); - assert!(slot(&ran) && !ran.result.logs().is_empty(), "{at}: run, the writes are kept"); let failed = plain(setup(&reverting), minimal_envs(), tx.clone()); + assert!(!slot(&failed), "{at}: reverting, the slot is not kept"); for result in FAILURES { let case = format!("{at}, rewritten into {result:?}, gas limit {gas_limit}"); let fails = Fails::call(writer, result); let rewritten = rewritten(|| setup(&stopping), minimal_envs, &tx, fails); - assert!(!slot(&rewritten), "{case}: no slot"); - assert!(rewritten.result.logs().is_empty(), "{case}: no log"); - let state = state_without_code(&rewritten); - assert_eq!(state, state_without_code(&failed), "{case}: the state"); - assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); - assert_eq!(rewritten.gas.state, failed.gas.state, "{case}: state gas"); - assert_eq!(rewritten.gas.history, failed.gas.history, "{case}: history gas"); - if result == InstructionResult::Revert { - assert_eq!(rewritten.gas.regular, ran.gas.regular, "{case}: regular gas"); + assert!(slot(&rewritten), "{case}: the slot stays"); + if writer == CALLEE { + assert_eq!(rewritten.result.logs().len(), 1, "{case}: and the log"); } + assert_eq!(rewritten.usage, failed.usage, "{case}: every count"); + assert_bills_as(&case, &rewritten, &failed); } } } @@ -841,13 +788,11 @@ impl Inspector, EthInterpreter> for Writes } } -/// What an inspector writes to the journal in the callback that turns a success into a failure is -/// journaled after the frame's checkpoint, and goes with the frame's writes; written in a callback -/// that leaves the success alone, it stays. Where revm fails the frame itself, the checkpoint is -/// gone before `call_end`, so a write made there stays: the one place the rewrite and a real -/// failure part. +/// What an inspector writes to the journal in `call_end` comes after the frame's checkpoint was +/// committed or reverted, so it stays whatever the frame's result says: left a success, turned into +/// a failure, or failed by revm itself. #[test] -fn test_a_write_an_inspector_makes_as_it_fails_a_frame_goes_with_the_frame() { +fn test_a_write_an_inspector_makes_at_a_frames_end_stays() { let caller = BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP).stop().build(); let db = |callee: Bytes| db(caller.clone()).account_code(CALLEE, callee); let stopping = BytecodeBuilder::default().stop().build(); @@ -857,6 +802,313 @@ fn test_a_write_an_inspector_makes_as_it_fails_a_frame_goes_with_the_frame() { inspected(db(callee.clone()), minimal_envs(), tx.clone(), WritesAtTheEnd { fails }) }; assert!(holds_something(&run(&stopping, false), NOTE), "left a success, the write stays"); - assert!(!holds_something(&run(&stopping, true), NOTE), "failing it, the write goes"); + assert!(holds_something(&run(&stopping, true), NOTE), "failing it, the write stays"); assert!(holds_something(&run(&reverting, false), NOTE), "revm failed it: the write stays"); } + +/// Rewrites the creator of every creation to `creator`: Foundry's `vm.prank` before `new C()`. +struct Pranks { + creator: Address, +} + +impl Inspector for Pranks { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + inputs.set_call(self.creator); + None + } +} + +/// A creation whose creator an inspector rewrites to an account the transaction already changed +/// (the sender, whose validation changed it) runs, and counts the records of what revm did: the +/// account it created, and no record of the rewritten creator, whose bump changed an account +/// changed already. The opcode's creator was never bumped and has no record either; what its +/// opcode was charged for one stays charged. +#[test] +fn test_a_creation_whose_creator_an_inspector_rewrites_to_a_changed_account_runs() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let outcome = inspected(db(caller()), minimal_envs(), tx, Pranks { creator: CALLER }); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 1, "the created account alone"); +} + +/// A creation whose creator an inspector rewrites to an account the transaction has not changed +/// counts that account's nonce record, the record of the account revm bumped, and, the account +/// being empty, one account of state growth for the account the bump made, with the created +/// account's record and growth. +#[test] +fn test_a_creation_whose_creator_an_inspector_rewrites_to_an_empty_account_counts_its_record() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let outcome = inspected(db(caller()), minimal_envs(), tx, Pranks { creator: EMPTY }); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&EMPTY].info.nonce, 1, "revm bumped the rewritten creator"); + assert_eq!(outcome.usage.write_records, 2, "its nonce record and the created account's"); + assert_eq!(outcome.usage.state_growth, 2, "its account, which the bump made, and the created"); +} + +/// A contract `CONTRACT` calls to send a wei to `CALLEE`, which changes `CALLEE` and leaves +/// `CONTRACT` unchanged. +const SENDER: Address = address!("0000000000000000000000000000000000c00011"); + +/// A rewrite of a frame's start, made in the inspector's `call` or `create` after the start's hook +/// charged for the records the start would make. +#[derive(Clone, Copy, Debug)] +enum Rewrite { + /// A zero-value call to `CALLEE` carries a wei: the start moves value between two accounts + /// it left unchanged, two records. + Value, + /// A creation's creator becomes `CALLEE`, which `SENDER` changed: the creator's nonce bump + /// makes no record of its own. + Creator, +} + +impl Rewrite { + /// `CONTRACT`'s code, which makes the start the rewrite is for. + fn code(self) -> Bytes { + match self { + Self::Value => BytecodeBuilder::default().call(CALLEE, U256::ZERO).append(POP), + Self::Creator => BytecodeBuilder::default() + .call(SENDER, U256::ZERO) + .append(POP) + .append_many(create_with(&[STOP]).build_vec()) + .append(POP), + } + .stop() + .build() + } + + /// The state the rewritten run reads: `CONTRACT` and `SENDER` funded, `SENDER` sending a wei. + fn db(self) -> MemoryDatabase { + db(self.code()) + .account_balance(SENDER, U256::from(10u64.pow(9))) + .account_code(SENDER, value_call(CALLEE).append(POP).stop().build()) + } +} + +impl Inspector for Rewrite { + fn call(&mut self, _: &mut CTX, inputs: &mut CallInputs) -> Option { + if matches!(self, Self::Value) && inputs.target_address == CALLEE { + inputs.value = CallValue::Transfer(U256::from(1)); + } + None + } + + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + if matches!(self, Self::Creator) { + inputs.set_call(CALLEE); + } + None + } +} + +/// Every way a tool runs an inspector: alloy-evm's `transact` with the inspector enabled, and +/// revm's `InspectEvm`, `InspectCommitEvm` and `InspectSystemCallEvm` called directly, with +/// alloy-evm's switch off. +#[derive(Clone, Copy, Debug)] +enum Entry { + AlloyTransact, + InspectOneTx, + InspectTx, + InspectOne, + Inspect, + InspectTxCommit, + InspectCommit, + InspectOneSystemCall, + InspectOneSystemCallWithCaller, + InspectSystemCall, + InspectSystemCallWithCaller, + InspectOneSystemCallWithInspector, + InspectSystemCallWithInspector, + InspectOneSystemCallWithInspectorAndCaller, + InspectSystemCallWithInspectorAndCaller, +} + +impl Entry { + const ALL: [Self; 15] = [ + Self::AlloyTransact, + Self::InspectOneTx, + Self::InspectTx, + Self::InspectOne, + Self::Inspect, + Self::InspectTxCommit, + Self::InspectCommit, + Self::InspectOneSystemCall, + Self::InspectOneSystemCallWithCaller, + Self::InspectSystemCall, + Self::InspectSystemCallWithCaller, + Self::InspectOneSystemCallWithInspector, + Self::InspectSystemCallWithInspector, + Self::InspectOneSystemCallWithInspectorAndCaller, + Self::InspectSystemCallWithInspectorAndCaller, + ]; + + /// Runs a zero-value call to `CONTRACT` under `rewrite` through this entry point: a transaction + /// from `CALLER`, or a system call. + fn run(self, rewrite: Rewrite) -> ExecutionResult { + use mega_evm::alloy_evm::Evm as _; + use revm::{InspectCommitEvm, InspectEvm, InspectSystemCallEvm}; + let mut evm = + MegaEvm::new(salt_context(rewrite.db(), minimal_envs())).with_inspector(rewrite); + if !matches!(self, Self::AlloyTransact) { + evm.set_inspector_enabled(false); + } + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let (caller, data) = (SYSTEM_ADDRESS, Bytes::new()); + let result = match self { + Self::AlloyTransact => { + return evm.execute_transaction(tx).expect("valid").result_and_state.result + } + Self::InspectOneTx => evm.inspect_one_tx(tx), + Self::InspectTx => evm.inspect_tx(tx).map(|done| done.result), + Self::InspectOne => evm.inspect_one(tx, rewrite), + Self::Inspect => evm.inspect(tx, rewrite).map(|done| done.result), + Self::InspectTxCommit => evm.inspect_tx_commit(tx), + Self::InspectCommit => evm.inspect_commit(tx, rewrite), + Self::InspectOneSystemCall => evm.inspect_one_system_call(CONTRACT, data), + Self::InspectOneSystemCallWithCaller => { + evm.inspect_one_system_call_with_caller(caller, CONTRACT, data) + } + Self::InspectSystemCall => evm.inspect_system_call(CONTRACT, data).map(|r| r.result), + Self::InspectSystemCallWithCaller => { + evm.inspect_system_call_with_caller(caller, CONTRACT, data).map(|r| r.result) + } + Self::InspectOneSystemCallWithInspector => { + evm.inspect_one_system_call_with_inspector(CONTRACT, data, rewrite) + } + Self::InspectSystemCallWithInspector => { + evm.inspect_system_call_with_inspector(CONTRACT, data, rewrite).map(|r| r.result) + } + Self::InspectOneSystemCallWithInspectorAndCaller => evm + .inspect_one_system_call_with_inspector_and_caller(caller, CONTRACT, data, rewrite), + Self::InspectSystemCallWithInspectorAndCaller => evm + .inspect_system_call_with_inspector_and_caller(caller, CONTRACT, data, rewrite) + .map(|r| r.result), + }; + result.expect("valid") + } +} + +/// An inspector may rewrite a frame's start after the start's hook charged for its records — a +/// call's value, a creation's creator — whichever entry point runs it: the run settles the start +/// revm made. +#[test] +fn test_every_inspected_entry_point_runs_a_start_an_inspector_rewrote() { + for entry in Entry::ALL { + for rewrite in [Rewrite::Value, Rewrite::Creator] { + let result = entry.run(rewrite); + assert!(result.is_success(), "{entry:?}, {rewrite:?}: {result:?}"); + } + } +} + +/// The records a rewritten start counts are those revm made. A zero-value call rewritten to carry +/// a wei moves it between `CONTRACT` and `CALLEE`, two accounts the transaction left unchanged +/// until then: two records and the transfer log. A creation whose creator is rewritten to `CALLEE`, +/// which `SENDER`'s wei changed, bumps an account changed already, which makes no record: the +/// transaction keeps `SENDER`'s transfer, two records and its log, and the created account. +#[test] +fn test_a_rewritten_start_counts_the_records_revm_made() { + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + for (rewrite, records, logs) in [(Rewrite::Value, 2, 1), (Rewrite::Creator, 3, 1)] { + let outcome = inspected(rewrite.db(), minimal_envs(), tx.clone(), rewrite); + assert!(outcome.result.is_success(), "{rewrite:?}: {:?}", outcome.result); + assert_eq!(outcome.usage.write_records, records, "{rewrite:?}"); + assert_eq!(outcome.result.logs().len(), logs, "{rewrite:?}: the transfer log"); + } +} + +/// Raises the endowment of every creation to `value`. +struct Endows { + value: U256, +} + +impl Inspector for Endows { + fn create(&mut self, _: &mut CTX, inputs: &mut CreateInputs) -> Option { + inputs.set_value(self.value); + None + } +} + +/// A creation revm refuses on its creator's account — an inspector raised the endowment past the +/// creator's balance — bumps no nonce and makes no frame, so it counts no record: the transaction +/// keeps its body alone, at either gas limit. What the `CREATE` was charged at its opcode stays +/// charged, as for a start an inspector answers: the history of the created account's record, +/// which the start declared, comes back with the refusal, and that of the creator's record, which +/// it did not declare, stays. +#[test] +fn test_a_creation_refused_on_its_creators_account_counts_no_record() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + for gas_limit in GAS_LIMITS { + let case = format!("gas limit {gas_limit}"); + let tx = to(CONTRACT, 0, Bytes::new(), gas_limit); + let ran = plain(db(caller()), minimal_envs(), tx.clone()); + let nonce = ran.state[&CONTRACT].info.nonce; + let refused = + inspected(db(caller()), minimal_envs(), tx.clone(), Endows { value: U256::MAX }); + assert!(refused.result.is_success(), "{case}: {:?}", refused.result); + assert_eq!(refused.state[&CONTRACT].info.nonce, nonce - 1, "{case}: no bump"); + assert_keeps_only_its_body_and_the_opcodes_charge(&case, &tx, &refused); + } +} + +/// [`assert_keeps_only_its_body`], for a creation an inspector made revm refuse: the history of +/// the record of its creator's nonce, which its `CREATE` was charged and its start did not declare, +/// is on the history ledger beyond the body's bytes. +fn assert_keeps_only_its_body_and_the_opcodes_charge( + case: &str, + tx: &MegaTransaction, + outcome: &MegaTransactionOutcome, +) { + let body = transaction_body_bytes(tx); + let charged = history_gas(body + mega_evm::WRITE_RECORD_SIZE).unwrap(); + assert_eq!(outcome.gas.state, 0, "{case}: no state gas"); + assert_eq!(outcome.gas.history, charged, "{case}: the body's history and the opcode's charge"); + assert_eq!( + outcome.gas.reservoir_remaining, + tx.gas_limit().saturating_sub(TX_GAS_LIMIT_CAP).saturating_sub(charged), + "{case}: the reservoir less what the history ledger bills" + ); + assert_eq!(outcome.gas.history_bytes, body, "{case}: the body's bytes"); + assert_eq!(outcome.usage, body_usage(tx), "{case}"); +} + +/// A refused creation draws nothing on its creator's pool: the creator writes one fresh slot after +/// it, and that write's record fits a data-size limit of the body and 40 bytes, and no tighter +/// one. +#[test] +fn test_a_refused_creation_leaves_its_creators_pool_whole() { + let code = || create_with(&[STOP]).append(POP).sstore(U256::ZERO, U256::from(1)).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let run = |limit: u64| { + let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit); + MegaEvm::new(salt_context(db(code()), minimal_envs()).with_tx_runtime_limits(limits)) + .with_inspector(Endows { value: U256::MAX }) + .execute_transaction(tx.clone()) + .expect("a valid transaction") + }; + let fits = transaction_body_bytes(&tx) + 40; + let kept = run(fits); + assert!(kept.result.is_success(), "{:?}", kept.result); + assert_eq!(kept.limit_exceeded, None, "the one slot's record fits"); + assert_eq!(kept.usage.write_records, 1, "the slot's record, and not the creator's"); + assert!(run(fits - 1).limit_exceeded.is_some(), "one byte less does not"); +} + +/// A creator with nothing left in its pool, whose creation revm refuses, is held to nothing: no +/// record was counted, and it resumes within its budget. +#[test] +fn test_a_refused_creation_holds_an_empty_pool_to_nothing() { + let caller = || create_with(&[STOP]).append(POP).stop().build(); + let tx = to(CONTRACT, 0, Bytes::new(), 30_000_000); + let limits = + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(transaction_body_bytes(&tx)); + let refused = + MegaEvm::new(salt_context(db(caller()), minimal_envs()).with_tx_runtime_limits(limits)) + .with_inspector(Endows { value: U256::MAX }) + .execute_transaction(tx.clone()) + .expect("a valid transaction"); + assert!(refused.result.is_success(), "{:?}", refused.result); + assert_eq!(refused.limit_exceeded, None, "no stop"); + assert_keeps_only_its_body_and_the_opcodes_charge("empty pool", &tx, &refused); +} diff --git a/crates/mega-evm/tests/satin/kv_updates.rs b/crates/mega-evm/tests/satin/kv_updates.rs new file mode 100644 index 000000000..dfb1af658 --- /dev/null +++ b/crates/mega-evm/tests/satin/kv_updates.rs @@ -0,0 +1,285 @@ +//! The KV-update limit: the write records a transaction keeps, held per transaction at +//! `TX_KV_UPDATE_LIMIT` and per frame at 98/100 of what the parent has left, rounded down. A record +//! that crosses either stops the frame that makes it with `MegaLimitExceeded(1, limit)`, naming the +//! frame's budget when the record crosses it, and its caller resumes. +//! +//! Every figure is hand arithmetic from the record rules: a fresh slot's first write is one record, +//! a write back to its original takes it back. + +use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + constants::{TX_DATA_LIMIT, TX_KV_UPDATE_LIMIT}, + test_utils::{BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaLimitExceeded, MegaSpecId, + MegaTransactionOutcome, ProtocolLimits, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, GAS, POP, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE}, + context::result::ExecutionResult, +}; + +use crate::common::{call, execute_under, share}; + +const CALLER: Address = address!("0000000000000000000000000000000000740000"); +const A: Address = address!("0000000000000000000000000000000000740001"); +const B: Address = address!("0000000000000000000000000000000000740002"); +const C: Address = address!("0000000000000000000000000000000000740003"); +const D: Address = address!("0000000000000000000000000000000000740004"); + +/// Room for a few hundred fresh slots and the calls around them, at any byte price the grid runs. +const GAS_LIMIT: u64 = 2_000_000_000; + +/// Writes the fresh slots `from..from + count`. +fn writes(code: BytecodeBuilder, from: u64, count: u64) -> BytecodeBuilder { + (from..from + count).fold(code, |code, slot| code.sstore(U256::from(slot), U256::from(1))) +} + +/// Calls `to` with all its gas, then returns what the call returned or reverted with. +fn then_call_returning(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(to) + .append_many([GAS, CALL, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) +} + +/// The revert data of a KV stop naming `limit`. +fn kv_stop(limit: u64) -> Bytes { + MegaLimitExceeded { kind: LimitKind::KvUpdate.as_u8(), limit }.abi_encode().into() +} + +/// Runs a call to `A` over `db` under `limits`. +fn run(db: MemoryDatabase, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + execute_under(db, call(CALLER, A, U256::ZERO, GAS_LIMIT), limits) +} + +/// Limits holding the transaction to `records` write records, and nothing else. +fn kv(records: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_kv_update_limit(records) +} + +/// The spec's numbers: 500,000 records per transaction, more than the data size can hold at 40 +/// bytes each, which is why the data size binds first at the protocol's values. +#[test] +fn test_the_kv_limit_is_the_specs() { + assert_eq!(TX_KV_UPDATE_LIMIT, 500_000); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + assert_eq!(limits.tx_kv_update_limit, TX_KV_UPDATE_LIMIT); + const { + assert!( + TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE > TX_DATA_LIMIT, + "data size is the tighter cap" + ) + }; + assert_eq!(EvmTxRuntimeLimits::no_limits().tx_kv_update_limit, u64::MAX); +} + +/// The transaction's own frame gets what the transaction has left — all ten records of a limit of +/// ten when nothing was counted before it — and the eleventh record stops it, kind 1, naming that +/// budget. The stop settles as a revert and keeps nothing the frame wrote; ten records fit. +#[test] +fn test_the_eleventh_record_stops_the_transactions_own_frame() { + let db = |count| { + MemoryDatabase::default() + .account_code(A, writes(BytecodeBuilder::default(), 1, count).stop().build()) + }; + let fits = run(db(10), kv(10)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 10); + + let stopped = run(db(11), kv(10)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 10, + used: 11, + frame_local: true + }) + ); + match &stopped.result { + ExecutionResult::Revert { output, .. } => assert_eq!(output, &kv_stop(10)), + other => panic!("expected the stop, got {other:?}"), + } + assert_eq!( + stopped.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); +} + +/// A child gets 98/100 of what its caller has left, rounded down: under a limit of ten, a caller +/// that kept two records gives its child seven, and the child's eighth record stops it, kind 1, +/// naming seven. The caller catches the stop with its eight records left, and keeps writing within +/// them: eight more fit, which a ninth would not. +#[test] +fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { + assert_eq!(share(10 - 2), 7); + let child = writes(BytecodeBuilder::default(), 1, 8).stop().build(); + let caller = |after: u64| { + let code = writes(BytecodeBuilder::default(), 1, 2) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append_many([GAS, CALL, POP]); + let code = writes(code, 3, after); + code.append_many([ + RETURNDATASIZE, + PUSH0, + PUSH0, + RETURNDATACOPY, + RETURNDATASIZE, + PUSH0, + RETURN, + ]) + .build() + }; + let db = |after| { + MemoryDatabase::default().account_code(A, caller(after)).account_code(B, child.clone()) + }; + + let caught = run(db(8), kv(10)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(7)), "the child's stop names its budget"); + assert_eq!(caught.limit_exceeded, None, "a stop below the transaction's own frame"); + assert_eq!(caught.usage.write_records, 10, "the caller's ten records, none of the child's"); + + let stopped = run(db(9), kv(10)); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 10, + used: 11, + frame_local: true + }), + "the caller's own eleventh record stops it in turn, naming its budget" + ); +} + +/// The budgets at depth, under a limit of 100: the transaction's own frame gets 100, a child 98, +/// a grandchild 96, the next frame 94, each the share of what the frame above has left; the 95th +/// record of the frame three calls down stops it, kind 1, naming 94, and every caller resumes. +#[test] +fn test_the_kv_budgets_at_depth() { + assert_eq!((share(100), share(share(100)), share(share(share(100)))), (98, 96, 94)); + let db = |records: u64| { + MemoryDatabase::default() + .account_code(A, then_call_returning(BytecodeBuilder::default(), B).build()) + .account_code(B, then_call_returning(BytecodeBuilder::default(), C).build()) + .account_code(C, then_call_returning(BytecodeBuilder::default(), D).build()) + .account_code(D, writes(BytecodeBuilder::default(), 1, records).stop().build()) + }; + let fits = run(db(94), kv(100)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 94); + + let caught = run(db(95), kv(100)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(94)), "D's stop, returned up the chain"); + assert_eq!(caught.usage.write_records, 0, "D's records went with its revert"); +} + +/// One record that crosses the data-size frame budget and the KV frame budget at once stops on +/// data size, the first of the counted dimensions: kind 0, naming the data-size budget. +#[test] +fn test_a_record_crossing_data_size_and_kv_stops_on_data_size() { + let db = MemoryDatabase::default() + .account_code(A, writes(BytecodeBuilder::default(), 1, 2).stop().build()); + let limits = EvmTxRuntimeLimits::no_limits() + .with_tx_kv_update_limit(1) + .with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE); + let stopped = run(db, limits); + assert_eq!( + stopped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: WRITE_RECORD_SIZE, + used: 2 * WRITE_RECORD_SIZE, + frame_local: true + }) + ); +} + +/// A frame's remaining is its budget less its net, never more than the budget: a child that takes +/// back a record its caller made has a net of minus one, and the frame it starts still gets 98% of +/// the child's budget, not of the budget and the record it took back. +/// +/// `A` writes its slot 1 and `DELEGATECALL`s `B`, which runs on `A`'s storage: under a limit of +/// 100, `A` has 99 left and `B` gets 97. `B` writes slot 1 back to its original, which takes `A`'s +/// record back, and calls `C`, which gets 98% of `B`'s 97, 95 — not of the 98 `B`'s pool holds — +/// and writes slots of its own: the 96th stops it, naming 95. +#[test] +fn test_a_negative_net_does_not_enlarge_the_next_childs_budget() { + use revm::bytecode::opcode::DELEGATECALL; + assert_eq!((share(99), share(97), share(98)), (97, 95, 96)); + let a = writes(BytecodeBuilder::default(), 1, 1) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(B) + .append_many([GAS, DELEGATECALL, POP, RETURNDATASIZE, PUSH0, PUSH0, RETURNDATACOPY]) + .append_many([RETURNDATASIZE, PUSH0, RETURN]) + .build(); + let b = then_call_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::ZERO), C) + .build(); + let db = |records: u64| { + MemoryDatabase::default() + .account_code(A, a.clone()) + .account_code(B, b.clone()) + .account_code(C, writes(BytecodeBuilder::default(), 100, records).stop().build()) + }; + let fits = run(db(95), kv(100)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.write_records, 95, "C's 95; A's record went back with B's write"); + + let caught = run(db(96), kv(100)); + assert!(caught.result.is_success(), "{:?}", caught.result); + assert_eq!(caught.result.output(), Some(&kv_stop(95)), "C's budget is the share of 97, not 98"); +} + +/// An EIP-7702 list that would keep more records than the transaction's limit allows is not +/// applied: none of its authorities is bumped, delegated or counted, and the transaction's own +/// frame returns the stop before it runs, kind 1, naming the transaction's limit, since no frame +/// budget exists yet. A list within the limit is applied. +#[test] +fn test_an_authorization_list_over_the_kv_limit_is_skipped_and_stops_the_first_frame() { + use crate::common::authorizing_call; + const DELEGATE: Address = address!("0000000000000000000000000000000000740005"); + const AUTHORITIES: [Address; 2] = [ + address!("0000000000000000000000000000000000740006"), + address!("0000000000000000000000000000000000740007"), + ]; + let db = || { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10_u64.pow(18))) + .account_code(A, writes(BytecodeBuilder::default(), 1, 1).stop().build()) + }; + let keys = AUTHORITIES; + let list = [(keys[0], 0), (keys[1], 0)]; + let tx = authorizing_call(CALLER, A, U256::ZERO, GAS_LIMIT, DELEGATE, &list); + + let applied = execute_under(db(), tx.clone(), kv(3)); + assert!(applied.result.is_success(), "{:?}", applied.result); + assert_eq!(applied.usage.write_records, 3, "two authorities and A's slot"); + + let skipped = execute_under(db(), tx, kv(1)); + assert_eq!( + skipped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::KvUpdate, + limit: 1, + used: 2, + frame_local: false + }) + ); + match &skipped.result { + ExecutionResult::Revert { output, .. } => assert_eq!(output, &kv_stop(1)), + other => panic!("expected the stop, got {other:?}"), + } + assert_eq!(skipped.usage.write_records, 0, "nothing of the list is kept"); + for authority in &keys { + let account = skipped.state.get(authority); + assert!(account.is_none_or(|account| account.info.nonce == 0), "{authority}: not bumped"); + assert!( + account.is_none_or(|account| account.info.is_empty_code_hash()), + "{authority}: not delegated" + ); + } +} diff --git a/crates/mega-evm/tests/satin/limit_exemption.rs b/crates/mega-evm/tests/satin/limit_exemption.rs index efe41c39e..ed4e5fc30 100644 --- a/crates/mega-evm/tests/satin/limit_exemption.rs +++ b/crates/mega-evm/tests/satin/limit_exemption.rs @@ -1,10 +1,10 @@ //! Who is held to no per-transaction limit: a transaction the protocol itself sent, and a system //! call. //! -//! The data-size limit and its frame budgets hold what users do. The protocol's own work — the -//! maintenance a system transaction performs, the calls the protocol makes before a block's -//! transactions — must not fail on them, as it pays no history gas for the same reason. What it -//! uses is counted all the same, and reported. +//! The data-size, KV-update and state-growth limits and their frame budgets hold what users do. The +//! protocol's own work — the maintenance a system transaction performs, the calls the protocol +//! makes before a block's transactions — must not fail on them, as it pays no history gas for the +//! same reason. What it uses is counted all the same, and reported. //! //! A user's deposit is not the protocol's work: it is held to every limit, and so is a user's //! transaction that calls a system contract. @@ -77,12 +77,20 @@ fn call_from(caller: Address, to: Address) -> MegaTransaction { } /// Every per-transaction limit the program crosses, one at a time, and all of them together. -fn limits() -> [(&'static str, EvmTxRuntimeLimits); 3] { +fn limits() -> [(&'static str, EvmTxRuntimeLimits); 5] { let none = EvmTxRuntimeLimits::no_limits(); [ ("the transaction's data size", none.with_tx_data_size_limit(TX_BODY_SIZE)), ("a frame's data size", none.with_frame_data_size_limit(WRITE_RECORD_SIZE)), - ("every limit at zero", none.with_tx_data_size_limit(0).with_frame_data_size_limit(0)), + ("the transaction's KV updates", none.with_tx_kv_update_limit(0)), + ("the transaction's state growth", none.with_tx_state_growth_limit(0)), + ( + "every limit at zero", + none.with_tx_data_size_limit(0) + .with_frame_data_size_limit(0) + .with_tx_kv_update_limit(0) + .with_tx_state_growth_limit(0), + ), ] } @@ -95,6 +103,10 @@ fn test_a_system_transaction_is_held_to_no_limit() { assert!(free.result.is_success(), "{:?}", free.result); assert_eq!(free.usage.write_records, 3, "three slots"); assert_eq!(free.usage.data_size, TX_BODY_SIZE + 3 * WRITE_RECORD_SIZE + 32 + 64); + assert_eq!( + free.usage.state_growth, 4, + "three new slots, and the system address's account, which the transaction creates" + ); assert!(free.gas.state >= 3 * slot_state_gas(), "at least its three slots' state gas"); for (name, limits) in limits() { @@ -119,16 +131,13 @@ fn test_a_system_call_is_held_to_no_limit() { let mut evm = MegaEvm::new(context(db()).with_tx_runtime_limits(limits)); let result = Evm::transact_system_call(&mut evm, CALLER, CONTRACT, Bytes::new()) .expect("the system call runs"); - ( - result, - evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().limit_exceeded().copied(), - ) + (result, evm.ctx().limit_usage(), evm.ctx().additional_limit().limit_exceeded().copied()) }; let (free, free_usage, _) = run(EvmTxRuntimeLimits::no_limits()); assert!(free.result.is_success(), "{:?}", free.result); assert_eq!(free_usage.write_records, 3); assert_eq!(free_usage.data_size, 310 + 3 * 40 + 32 + 64, "its body, records and log"); + assert_eq!(free_usage.state_growth, 3, "three new slots"); for (name, limits) in limits() { let (result, usage, stop) = run(limits); @@ -139,26 +148,53 @@ fn test_a_system_call_is_held_to_no_limit() { } } -/// A user's deposit is held to the limits: over the data size, it is stopped. So is a user's -/// transaction to the contract a system transaction may call. +/// A user's deposit is held to the limits: over the data size, the KV count or the state growth, +/// it is stopped on that dimension. So is a user's transaction to the contract a system +/// transaction may call. #[test] fn test_a_deposit_and_a_user_call_to_a_system_contract_are_held_to_the_limits() { - let limits = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(TX_BODY_SIZE); - let cases = [ - ("a deposit", deposit(call_from(CALLER, CONTRACT))), - ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), + let none = EvmTxRuntimeLimits::no_limits(); + let dimensions = [ + (none.with_tx_data_size_limit(TX_BODY_SIZE), LimitKind::DataSize), + (none.with_tx_kv_update_limit(0), LimitKind::KvUpdate), + (none.with_tx_state_growth_limit(0), LimitKind::StateGrowth), ]; - for (name, tx) in cases { - let outcome = execute_under(db(), tx, limits); - let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}: stopped")); - assert!( - matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, .. }), - "{name}: {stop:?}" - ); - assert!( - !outcome.result.is_success() && !outcome.result.is_halt(), - "{name}: {:?}", - outcome.result - ); + for (limits, kind) in dimensions { + let cases = [ + ("a deposit", deposit(call_from(CALLER, CONTRACT))), + ("a user's call to a system contract", call_from(CALLER, ORACLE_CONTRACT_ADDRESS)), + ]; + for (name, tx) in cases { + let outcome = execute_under(db(), tx, limits); + let stop = outcome.limit_exceeded.unwrap_or_else(|| panic!("{name}: stopped")); + assert!( + matches!(stop, mega_evm::LimitCheck::ExceedsLimit { kind: crossed, .. } if crossed == kind), + "{name}, {kind:?}: {stop:?}" + ); + assert!( + !outcome.result.is_success() && !outcome.result.is_halt(), + "{name}, {kind:?}: {:?}", + outcome.result + ); + } } } + +/// Under the spec's own limits a system transaction keeps more than the 1,000 new slots a user's +/// transaction may: 1,001 fresh slots are not stopped, and their count is reported, with the +/// system address's new account, for the block to count. +#[test] +fn test_a_system_transaction_keeps_more_state_growth_than_the_limit() { + use mega_evm::constants::{TX_GAS_LIMIT_CAP, TX_STATE_GROWTH_LIMIT}; + let slots = TX_STATE_GROWTH_LIMIT + 1; + let code = (1..=slots).fold(BytecodeBuilder::default(), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }); + let db = db().account_code(ORACLE_CONTRACT_ADDRESS, code.stop().build()); + let mut tx = call_from(MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS); + tx.0.base.gas_limit = TX_GAS_LIMIT_CAP + slots * slot_state_gas() + 100_000_000; + let outcome = execute_under(db, tx, EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.usage.state_growth, slots + 1, "the slots and the system address"); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/block.rs b/crates/mega-evm/tests/satin/limit_matrix/block.rs new file mode 100644 index 000000000..d92e4fdaf --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/block.rs @@ -0,0 +1,334 @@ +//! What a block skips, and what it still counts. +//! +//! The block's gas limit is the page's bound: the fixture block's 10 billion, not a 30 million +//! stand-in. Per-transaction limits stay the protocol's. The executor installs them itself. + +use alloy_consensus::{transaction::Recovered, Sealed, Signed, TxLegacy}; +use alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory}; +use alloy_op_evm::block::receipt_builder::OpAlloyReceiptBuilder; +use alloy_primitives::{Address, Bytes, Signature, TxKind, B256, U256}; +use mega_evm::{ + system::{MEGA_SYSTEM_ADDRESS, ORACLE_CONTRACT_ADDRESS}, + test_utils::{MemoryDatabase, SequencerRegistryRoles}, + BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig, + MegaSpecId, MegaTxEnvelope, ProtocolLimits, +}; +use op_alloy_consensus::TxDeposit; +use revm::{ + context::{BlockEnv, CfgEnv}, + database::State, + Database, +}; + +use super::{slots_gas, store_n_slots, CALLER, CONTRACT, TX_STATE_GROWTH_LIMIT}; + +const CHAIN_ID: u64 = 4_326; +const BLOCK_GAS: u64 = 10_000_000_000; + +/// A second sender, so the transaction the block should skip is not the one that filled it. +const OTHER: Address = alloy_primitives::address!("0000000000000000000000000000000000ab1008"); +/// The deposit's sender. +const DEPOSITOR: Address = alloy_primitives::address!("0000000000000000000000000000000000ab1009"); + +/// The database a block runs on: Rex6 predeploys, the registry naming the system address, and +/// every sender funded. `CONTRACT` runs `code`. +pub(super) fn database(code: Bytes) -> MemoryDatabase { + let mut db = MemoryDatabase::default() + .rex6_predeploys(SequencerRegistryRoles::from(MEGA_SYSTEM_ADDRESS)) + .account_code(CONTRACT, code) + .account_balance(CALLER, U256::from(10u128.pow(24))) + .account_balance(OTHER, U256::from(10u128.pow(24))) + .account_balance(DEPOSITOR, U256::from(10u128.pow(24))) + .account_balance(MEGA_SYSTEM_ADDRESS, U256::from(10u128.pow(24))); + db.set_account_code(DEPOSITOR, Bytes::new()); + db +} + +fn env() -> EvmEnv { + let mut cfg = CfgEnv::new_with_spec(MegaSpecId::SATIN); + cfg.chain_id = CHAIN_ID; + let block = BlockEnv { number: U256::from(1), gas_limit: BLOCK_GAS, ..Default::default() }; + EvmEnv::new(cfg, block) +} + +/// A legacy call. Gas price 0, chain id [`CHAIN_ID`]. +pub(super) fn legacy( + from: Address, + nonce: u64, + to: Address, + gas_limit: u64, +) -> Recovered { + let tx = TxLegacy { + chain_id: Some(CHAIN_ID), + nonce, + gas_price: 0, + gas_limit, + to: TxKind::Call(to), + value: U256::ZERO, + input: Bytes::new(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Legacy(Signed::new_unchecked(tx, Signature::test_signature(), B256::ZERO)), + from, + ) +} + +/// A user deposit to `to`. +pub(super) fn deposit( + from: Address, + to: Address, + gas_limit: u64, + system: bool, +) -> Recovered { + let deposit = TxDeposit { + source_hash: B256::repeat_byte(0x11), + from, + to: TxKind::Call(to), + mint: 0, + value: U256::ZERO, + gas_limit, + is_system_transaction: system, + input: Bytes::new(), + }; + Recovered::new_unchecked( + MegaTxEnvelope::Deposit(Sealed::new_unchecked(deposit, B256::repeat_byte(0xde))), + from, + ) +} + +/// Runs `txs` in order on a fresh block over `db`. Each entry is `Ok` when the transaction was +/// included, including one whose receipt failed. +pub(super) fn drive( + db: MemoryDatabase, + txs: Vec>, +) -> (Vec>, State) { + drive_with(db, txs, BlockLimits::no_limits(), None) +} + +/// [`drive`] under a builder's `policy`, and under `protocol` in place of the spec's limits when +/// it is given. +pub(super) fn drive_with( + db: MemoryDatabase, + txs: Vec>, + policy: BlockLimits, + protocol: Option, +) -> (Vec>, State) { + let mut state = State::builder().with_database(db).build(); + let evm = MegaEvmFactory::new().create_evm(&mut state, env()); + let ctx = MegaBlockExecutionCtx::new(B256::ZERO, Some(B256::ZERO), Bytes::new(), policy); + let mut executor = MegaBlockExecutor::new( + evm, + ctx, + MegaHardforkConfig::default().with_all_activated(), + OpAlloyReceiptBuilder::default(), + ); + if let Some(protocol) = protocol { + executor = executor.with_protocol_limits(protocol); + } + executor.apply_pre_execution_changes().expect("the block starts"); + let results = txs + .iter() + .map(|tx| executor.execute_transaction(tx).map(|_| ()).map_err(|err| err.to_string())) + .collect(); + drop(executor); + (results, state) +} + +pub(super) fn slot(state: &mut State, address: Address, index: u64) -> U256 { + state.storage(address, U256::from(index)).expect("the slot is readable") +} + +/// The block's state growth is already 1,000. The next ordinary transaction is skipped before it +/// runs. A deposit is not skipped. +#[test] +fn test_an_ordinary_transaction_is_skipped_at_the_block_state_growth_limit() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(OTHER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "the filling transaction is included: {:?}", results[0]); + assert_eq!(slot(&mut state, CONTRACT, 1), U256::from(1)); + assert!(results[1].is_ok(), "a deposit is not skipped: {:?}", results[1]); + assert!( + results[2].is_err(), + "the next ordinary transaction is skipped before it runs: {:?}", + results[2] + ); +} + +/// A block KV limit reduced to 10, so the case is reachable before data size. The transaction +/// whose 10 records reach it is included. A deposit after it is not skipped and counts; the next +/// ordinary transaction is skipped before it runs. +#[test] +fn test_a_reduced_block_kv_limit_skips_the_next_ordinary_transaction() { + let Some(gas) = slots_gas(10) else { return }; + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN).with_block_kv_update_limit(10); + let db = database(store_n_slots(10)); + let (results, mut state) = drive_with( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(OTHER, 0, CONTRACT, gas), + ], + BlockLimits::no_limits(), + Some(protocol), + ); + assert!(results[0].is_ok(), "the transaction that reaches the limit is included"); + assert_eq!(slot(&mut state, CONTRACT, 10), U256::from(1)); + assert!(results[1].is_ok(), "a deposit is not skipped: {:?}", results[1]); + assert!(results[2].is_err(), "the next ordinary transaction is skipped: {:?}", results[2]); +} + +/// The block's data size, KV and state growth are all reached by one transaction under reduced +/// block limits. The next ordinary transaction is skipped. A node may name any of the three, so +/// the test asserts the skip and no dimension. +/// Filling only data size would not hold the other two budgets to the rule. +#[test] +fn test_a_skip_with_every_block_dimension_reached_records_no_dimension() { + let Some(gas) = slots_gas(2) else { return }; + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN) + .with_block_txs_data_limit(1) + .with_block_kv_update_limit(1) + .with_block_state_growth_limit(1); + let db = database(store_n_slots(2)); + let (results, _) = drive_with( + db, + vec![legacy(CALLER, 0, CONTRACT, gas), legacy(OTHER, 0, CONTRACT, gas)], + BlockLimits::no_limits(), + Some(protocol), + ); + assert!(results[0].is_ok(), "the transaction that reaches the limits is included"); + assert!(results[1].is_err(), "the next ordinary transaction is skipped: {:?}", results[1]); +} + +/// A system-originated transaction creates 1,001 new slots. It is not stopped: the slots are +/// kept. Its usage is counted and moves the block's state-growth counter past 1,000, so the +/// ordinary transaction after it is skipped. +#[test] +fn test_a_system_transaction_of_1001_slots_is_not_stopped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = database(store_n_slots(1)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(CALLER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "the system transaction is included: {:?}", results[0]); + assert_eq!( + slot(&mut state, ORACLE_CONTRACT_ADDRESS, TX_STATE_GROWTH_LIMIT + 1), + U256::from(1), + "1,001 slots are kept" + ); + assert!(results[1].is_err(), "the system transaction counted: {:?}", results[1]); +} + +/// A pre-block call creates 1,001 new slots. It is not stopped, and the block counters do not +/// move: the ordinary transaction after it that fills 1,000 slots is included, and only the one +/// after that is skipped. +/// +/// The pre-block calls' gas is fixed at 31,566,720, which at the spec's byte prices cannot pay +/// 1,001 fresh slots, so the test is built with the `satin-price-override` feature and returns +/// early unless the prices in effect fit them. The pre-block call runs no inspector, so the whole +/// reservoir its outermost frame receives is not observed here. +#[cfg(feature = "satin-price-override")] +#[test] +fn test_a_pre_block_call_of_1001_slots_is_not_stopped_and_does_not_move_the_block() { + use alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS; + use revm::context_interface::cfg::GasId; + // A fresh slot's regular gas is the store's own, from the schedule, and the loop's opcodes + // around it, which take less than 100. Its state gas draws the reservoir first and then + // spills onto the regular budget, so the two together must fit the call's whole gas. + let params = mega_evm::satin_gas_params(); + let store_regular = params.get(GasId::sstore_static()) + + params.get(GasId::cold_storage_cost()) + + params.get(GasId::sstore_set_without_load_cost()); + let slots = TX_STATE_GROWTH_LIMIT + 1; + let needed = slots * (crate::common::slot_state_gas() + store_regular + 100); + if needed > mega_evm::constants::PRE_BLOCK_CALL_GAS_LIMIT { + mega_evm::test_utils::note_price_guard("1,001 slots do not fit a pre-block call"); + return; + } + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let mut db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(HISTORY_STORAGE_ADDRESS, store_n_slots(slots as u16)); + let (results, mut state) = + drive(db, vec![legacy(CALLER, 0, CONTRACT, gas), legacy(OTHER, 0, CONTRACT, gas)]); + assert_eq!(slot(&mut state, HISTORY_STORAGE_ADDRESS, slots), U256::from(1), "not stopped"); + assert!(results[0].is_ok(), "the pre-block call moved no counter: {:?}", results[0]); + assert!(results[1].is_err(), "the block is now at 1,000: {:?}", results[1]); +} + +/// The block is already at 1,000 state growth: the ordinary transaction that comes later is +/// skipped. A Mega System Transaction at that point is not skipped, and not stopped by the +/// per-transaction limit: its 1,001 slots are kept. It counts. +#[test] +fn test_a_system_transaction_after_1000_slots_is_not_skipped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = drive( + db, + vec![ + legacy(CALLER, 0, CONTRACT, gas), + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(OTHER, 0, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a system transaction is not skipped: {:?}", results[1]); + assert_eq!( + slot(&mut state, ORACLE_CONTRACT_ADDRESS, TX_STATE_GROWTH_LIMIT + 1), + U256::from(1), + "it is not stopped" + ); + assert!(results[2].is_err(), "the block is at its limit: {:?}", results[2]); +} + +/// A builder's policy holds the block's KV packing budget at 10 and its state-growth packing +/// budget at 2. The ordinary transaction that fills two slots reaches the state-growth budget, +/// so the next ordinary one is not packed; a deposit and a Mega System Transaction are not +/// refused and still count. A validator applies no policy and includes the next one too, and the +/// transactions both packed compute the same. The protocol values stay 500,000 and 1,000. +#[test] +fn test_a_builders_kv_and_state_growth_policy_does_not_bind_a_validator() { + let protocol = ProtocolLimits::for_spec(MegaSpecId::SATIN); + assert_eq!(protocol.block_kv_update_limit, super::TX_KV_UPDATE_LIMIT); + assert_eq!(protocol.block_state_growth_limit, TX_STATE_GROWTH_LIMIT); + let Some(gas) = slots_gas(4) else { return }; + let txs = || { + vec![ + legacy(CALLER, 0, CONTRACT, gas), + deposit(DEPOSITOR, CONTRACT, gas, false), + legacy(MEGA_SYSTEM_ADDRESS, 0, ORACLE_CONTRACT_ADDRESS, gas), + legacy(OTHER, 0, CONTRACT, gas), + ] + }; + let db = || { + let mut db = database(store_n_slots(2)); + db.set_account_code(ORACLE_CONTRACT_ADDRESS, store_n_slots(2)); + db + }; + let policy = + BlockLimits::no_limits().with_block_kv_update_limit(10).with_block_state_growth_limit(2); + let (built, mut built_state) = drive_with(db(), txs(), policy, None); + assert!(built[0].is_ok() && built[1].is_ok() && built[2].is_ok(), "{built:?}"); + assert!(built[3].is_err(), "the builder does not pack it: {:?}", built[3]); + let (validated, mut validated_state) = drive(db(), txs()); + assert!(validated.iter().all(Result::is_ok), "a validator applies no policy: {validated:?}"); + for (address, index) in [(CONTRACT, 2), (ORACLE_CONTRACT_ADDRESS, 2)] { + assert_eq!( + slot(&mut built_state, address, index), + slot(&mut validated_state, address, index) + ); + } +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/deposits.rs b/crates/mega-evm/tests/satin/limit_matrix/deposits.rs new file mode 100644 index 000000000..ca4ce9e23 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/deposits.rs @@ -0,0 +1,130 @@ +//! A user's deposit, and a deposit that has already failed. +//! +//! The created caller of a user deposit is state growth before the first frame. A failed deposit +//! reports `FailedDeposit` and is not stopped. + +use alloy_primitives::{address, Address, U256}; +use mega_evm::{MegaHaltReason, MegaTransaction}; +use revm::context::result::ExecutionResult; + +use super::{ + block, execute, nonce_of, reverted_stop, slot_value, slots_gas, store_n_slots, world, CALLER, + CONTRACT, TX_STATE_GROWTH_LIMIT, +}; +use crate::common; + +const FRESH: Address = address!("0000000000000000000000000000000000ab100a"); +/// A second contract, so a deposit's slots are not the slots an earlier transaction filled. +const OTHER_CONTRACT: Address = address!("0000000000000000000000000000000000ab100c"); + +fn user_deposit(caller: Address, gas_limit: u64, system: bool) -> MegaTransaction { + let mut tx = common::deposit(common::call(caller, CONTRACT, U256::ZERO, gas_limit)); + tx.0.deposit.is_system_transaction = system; + tx +} + +/// A user deposit whose sender had no account, then fresh slots. The created caller is +1 before +/// the first frame. The first frame's budget is 999. The 1,000th slot stops that frame, kind 3, +/// `limit` 999. The caller account stays. +#[test] +fn test_a_new_depositors_1000th_slot_stops_at_999() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = world(&[(CONTRACT, store_n_slots(TX_STATE_GROWTH_LIMIT as u16))]); + let outcome = execute(db, user_deposit(FRESH, gas, false)); + assert_eq!( + reverted_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT - 1 } + ); + assert!(outcome.limit_exceeded.is_some(), "the deposit's own frame stopped"); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO, "the stopped frame keeps no slot"); + assert!(nonce_of(&outcome, FRESH) >= 1, "the created caller stays"); + assert_eq!( + outcome.gas.state, + common::account_state_gas(), + "the created caller keeps its state gas; the stopped slots keep none" + ); +} + +/// A user deposit whose sender already had an account. No pre-frame growth. The 1,001st fresh +/// slot stops the first frame, kind 3, `limit` 1,000. +#[test] +fn test_an_existing_depositors_1001st_slot_stops_at_1000() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let db = world(&[(CONTRACT, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16))]) + .account_balance(FRESH, U256::from(1)); + let outcome = execute(db, user_deposit(FRESH, gas, false)); + assert_eq!( + reverted_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT } + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); +} + +/// The block is already at 1,000 state growth: the ordinary transaction after the deposit is +/// skipped. The deposit, a user's, is not skipped. It runs under the per-transaction limit: the +/// 1,001 slots it tries are stopped, and none is kept. +#[test] +fn test_a_user_deposit_after_1000_slots_is_not_skipped() { + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + let mut db = block::database(store_n_slots(TX_STATE_GROWTH_LIMIT as u16)); + db.set_account_code(OTHER_CONTRACT, store_n_slots((TX_STATE_GROWTH_LIMIT + 1) as u16)); + let (results, mut state) = block::drive( + db, + vec![ + block::legacy(CALLER, 0, CONTRACT, gas), + block::deposit(FRESH, OTHER_CONTRACT, gas, false), + block::legacy(CALLER, 1, CONTRACT, gas), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a user deposit is not skipped: {:?}", results[1]); + assert_eq!( + block::slot(&mut state, OTHER_CONTRACT, 1), + U256::ZERO, + "the deposit is held to the per-transaction limit" + ); + assert!(results[2].is_err(), "the block is at its limit: {:?}", results[2]); +} + +/// A failed deposit whose sender had no account: no state gas for that account, and the limit +/// does not stop it. Its account counts one toward the block's state growth: after an ordinary +/// transaction of 999 slots, one such deposit takes the block to 1,000, so the next ordinary +/// transaction is skipped, and a second such deposit after it is not, taking the counter past +/// 1,000. +#[test] +fn test_a_failed_deposit_from_a_new_sender_is_not_stopped() { + let db = world(&[(CONTRACT, store_n_slots(1))]); + let outcome = execute(db, user_deposit(FRESH, 100_000, true)); + assert!( + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::FailedDeposit, .. } + ), + "{:?}", + outcome.result + ); + assert_eq!(outcome.gas.state, 0, "a failed deposit charges no state gas"); + assert!(outcome.limit_exceeded.is_none(), "the halt is not a limit stop"); + assert_eq!(nonce_of(&outcome, FRESH), 1, "the sender account is created"); + + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT) else { return }; + let db = block::database(store_n_slots((TX_STATE_GROWTH_LIMIT - 1) as u16)); + let (results, _) = block::drive( + db, + vec![ + block::legacy(CALLER, 0, CONTRACT, gas), + block::deposit(FRESH, CONTRACT, 100_000, true), + block::legacy(CALLER, 1, CONTRACT, gas), + block::deposit( + address!("0000000000000000000000000000000000ab100b"), + CONTRACT, + 100_000, + true, + ), + ], + ); + assert!(results[0].is_ok(), "{:?}", results[0]); + assert!(results[1].is_ok(), "a failed deposit is not skipped: {:?}", results[1]); + assert!(results[2].is_err(), "the failed deposit's account counted: {:?}", results[2]); + assert!(results[3].is_ok(), "the counter may pass 1,000: {:?}", results[3]); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/destruction.rs b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs new file mode 100644 index 000000000..cd9d7d23e --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/destruction.rs @@ -0,0 +1,1365 @@ +//! The same-transaction destruction table, and the state growth a `SELFDESTRUCT` adds. +//! +//! A scenario run through [`plain_and_probed`] reads its figures off a plain run and the +//! state-growth net it kept off the probe's budget. The figures are the page's at `m` = 1 and the +//! spec's byte prices: a test that pins them returns early at other prices. Kind 1 runs under a +//! reduced transaction KV limit. + +use alloy_op_evm::OpTx; +use alloy_primitives::{keccak256, Address, Bytes, TxKind, B256, U256}; +use mega_evm::{ + satin_gas_params, + test_utils::{op_transaction, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaLimitExceeded, MegaTransaction, MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{ + ADDRESS, CALL, CALLDATALOAD, CALLDATASIZE, CALLVALUE, GAS, JUMPDEST, JUMPI, LT, MLOAD, POP, + PUSH0, SELFDESTRUCT, SLOAD, SSTORE, STOP, + }, + context::{result::ExecutionResult, TxEnv}, + interpreter::{ + interpreter::EthInterpreter, + interpreter_types::{InputsTr, Jumps}, + Interpreter, + }, + Database, Inspector, +}; + +use super::{ + assert_growth, at_spec_prices, balance_of, call_tx, call_with_gas, create_tx, delegatecall, + execute, has_code, is_destroyed, plain_and_probed, probe_gas, returned_stop, slot_value, + slots_gas, store_n_prefix, store_n_prefix_at, warm_call, world, ACCOUNT_LEAF_STATE_GAS_M1, + BENEFICIARY, BODY_BYTES, BODY_HISTORY, CALLER, CHILD, CODE_DEPOSIT_STATE_PER_BYTE, CONTRACT, + EXECUTION_CAP, EXISTING, GRAND, HISTORY_GAS_PER_BYTE, NEXT, RECORD_HISTORY, SLOT_STATE_GAS_M1, + TRANSFER_LOG_SIZE, TX_STATE_GROWTH_LIMIT, WRITE_RECORD_SIZE, +}; +use crate::common::{self, context, state_is_free}; + +/// Whether the page's state and history figures hold at the prices in effect. +fn pins_state() -> bool { + at_spec_prices() && !state_is_free() && !common::history_is_free() +} + +/// History gas of `bytes` at the spec's byte price. +const fn history(bytes: u64) -> u64 { + bytes * HISTORY_GAS_PER_BYTE +} + +/// State gas of deploying `code` at `m` = 1. +fn code_state(code: &[u8]) -> u64 { + code.len() as u64 * CODE_DEPOSIT_STATE_PER_BYTE +} + +fn runtime_to(beneficiary: Address) -> Bytes { + BytecodeBuilder::default().selfdestruct(beneficiary).build() +} + +fn init_returning(prefix: BytecodeBuilder, runtime: &[u8]) -> Bytes { + prefix.return_with_data(runtime).build() +} + +fn created_at(init: &[u8]) -> Address { + CONTRACT.create2(B256::ZERO, keccak256(init)) +} + +/// `CREATE2` of `init` with salt 0 carrying `endowment`, its address popped, then `tail`. The tail +/// has no absolute jump: a loop in it is placed with `store_n_prefix_at`. +fn after_create(init: Bytes, endowment: U256, tail: BytecodeBuilder) -> Vec { + let mut code = BytecodeBuilder::default() + .create2(endowment, init, U256::ZERO) + .append(POP) + .build() + .to_vec(); + code.extend_from_slice(&tail.build()); + code +} + +fn funded_contract(code: impl Into) -> MemoryDatabase { + let mut db = world(&[(CONTRACT, code.into()), (EXISTING, Bytes::from_static(&[STOP]))]); + db.set_account_balance(CONTRACT, U256::from(10u128.pow(24))); + db +} + +/// [`plain_and_probed`] on a funded contract. `setup` adds accounts to both databases. +fn both( + scenario: Vec, + setup: impl Fn(&mut MemoryDatabase), +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + plain_and_probed(&scenario, |code| { + let mut db = funded_contract(code); + setup(&mut db); + db + }) +} + +/// Runtime that stores its 32-byte calldata into slot 1, or with no calldata self-destructs to +/// `beneficiary`. +fn store_or_destroy(beneficiary: Address) -> Bytes { + let destroy = BytecodeBuilder::default().selfdestruct(beneficiary).build(); + // `CALLDATASIZE`, `PUSH1 store`, `JUMPI` come first. + let store = 4 + destroy.len(); + let mut code = BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(store as u8) + .append(JUMPI) + .build() + .to_vec(); + code.extend_from_slice(&destroy); + code.extend_from_slice( + &BytecodeBuilder::default() + .append_many([JUMPDEST, PUSH0, CALLDATALOAD]) + .push_number(1_u8) + .append_many([SSTORE, STOP]) + .build(), + ); + Bytes::from(code) +} + +/// `CALL` of `target` with all the gas left and one 32-byte word of calldata, `word`. +fn call_with_word(code: BytecodeBuilder, target: Address, word: u64) -> BytecodeBuilder { + code.mstore(0x200, U256::from(word).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .push_number(0x200_u16) + .append(PUSH0) + .push_address(target) + .append_many([GAS, CALL]) +} + +/// Create an account that did not exist, deposit its code, store one fresh slot, and +/// `SELFDESTRUCT` it to a new beneficiary, moving a non-zero balance. The leaf, the code and the +/// slot are given back at the prices charged, and their records and the code's data size and +/// history go with them. The logs, here the two transfer logs, stay counted. The beneficiary is +/// +1 and its leaf, 183,600 at `m` = 1, stays charged: the kept net is 1. +/// +/// The beneficiary is held after the give-back: a destroying frame exactly at its budget, here 0, +/// subtracts the absent leaf and its new slot, `1 + N` = 2, and the beneficiary fits. +#[test] +fn test_a_kept_destruction_gives_back_the_leaf_the_code_and_the_slot() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init.clone(), + U256::from(1), + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the account is removed"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1)); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the new beneficiary stays"); + // Kept: the creator's record and the beneficiary's. The endowment's and the move's transfer + // logs stay counted and pay no history. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_eq!(outcome.gas.history, history(BODY_BYTES + 2 * WRITE_RECORD_SIZE)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_eq!(outcome.result.logs().len(), 2, "the two transfer logs stay"); + assert_growth(&probed, 1); + + // At the budget: the creation is +2 on the creator, which then stores 998 slots, so the + // destroying frame's budget is `floor(0 × 98 / 100)` = 0. + let mut code = after_create(init, U256::from(1), BytecodeBuilder::default()); + code.extend_from_slice(&store_n_prefix_at(code.len(), 998, 1, false)); + code.extend_from_slice(&BytecodeBuilder::default().call(created, U256::ZERO).stop().build()); + let Some(gas) = slots_gas(1_010) else { return }; + let outcome = execute(funded_contract(code), call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the destruction at the budget fits"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1), "the beneficiary fits"); + assert_eq!(slot_value(&outcome, CONTRACT, 998), U256::from(1)); +} + +/// The top frame creates the account. An inner frame calls it, it self-destructs, and the inner +/// frame then reverts. The creation sits outside that revert: the mark, the falls, the give-back +/// and the record takeback are discarded, so the leaf and the code stay charged, the creator's +/// and the created account's records stand, and the kept net is the creation's +1. +#[test] +fn test_a_reverted_inner_frame_discards_the_destruction() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP), + ); + let child = BytecodeBuilder::default().call(created, U256::ZERO).revert().build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, child.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(!is_destroyed(&outcome, created), "the revert discards the destruction"); + assert!(has_code(&outcome, created)); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + code_state(&runtime)); + assert_eq!(outcome.usage.write_records, 2, "the records stand again"); + assert_growth(&probed, 1); +} + +/// A pre-existing contract, a child of the top frame with a state-growth budget of 980, stores +/// 980 slots and self-destructs to a new beneficiary. It was not created in the transaction, so +/// there is no fall and no give-back. The beneficiary's +1 crosses: the stop names the frame +/// budget, kind 3, `limit` 980, and the operation keeps nothing. +#[test] +fn test_a_new_beneficiary_at_a_full_budget_stops_the_frame() { + let mut pre = store_n_prefix(980, 1, false); + pre.extend_from_slice(&runtime_to(BENEFICIARY)); + let mut db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, Bytes::from(pre))]); + db.set_account_balance(CHILD, U256::from(10)); + let Some(gas) = slots_gas(1_000) else { return }; + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 980 }); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "the operation keeps nothing"); + assert_eq!(balance_of(&outcome, CHILD), U256::from(10)); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); +} + +/// Create an account with one fresh slot outside an enclosing frame. The enclosing frame destroys +/// it, stores the slot to another non-zero value, stores it to zero, and destroys it again. +/// +/// When the enclosing frame is kept, the first destruction gives the leaf, the code and the slot +/// back and takes their records back; the later stores do not rise, fall, charge, refill or make +/// a record; the second destruction does nothing. When it reverts, all of that is discarded: the +/// creation's charges and its three records stand, and the kept net is 2. +#[test] +fn test_stores_after_the_mark_and_a_reverted_enclosing_frame() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP), + ); + for kept in [true, false] { + let enclosing = BytecodeBuilder::default().call(created, U256::ZERO).append(POP); + let enclosing = call_with_word(enclosing, created, 2).append(POP); + let enclosing = call_with_word(enclosing, created, 0).append(POP); + let enclosing = enclosing.call(created, U256::ZERO).append(POP); + let enclosing = if kept { enclosing.stop() } else { enclosing.revert() }; + let enclosing = enclosing.build(); + assert_eq!( + sstore_state_gas(&parent, |db| db.set_account_code(CHILD, enclosing.clone()), created), + [SLOT_STATE_GAS_M1 as i64, 0, 0], + "kept {kept}: the stores after the mark move no state gas" + ); + let Some((outcome, probed)) = + both(parent.clone(), |db| db.set_account_code(CHILD, enclosing.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "kept {kept}: {:?}", outcome.result); + if kept { + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "given back once, and nothing after the mark"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); + } else { + assert!(!is_destroyed(&outcome, created)); + assert_eq!(slot_value(&outcome, created, 1), U256::from(1)); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime) + ); + assert_eq!(outcome.usage.write_records, 3, "the records stand again"); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 3 * WRITE_RECORD_SIZE + runtime.len() as u64 + ); + assert_growth(&probed, 2); + } + } +} + +/// Runtime that accepts value and stops, or with no value emits one `LOG3` of a word and +/// self-destructs to `beneficiary`. +fn log_and_destroy(beneficiary: Address) -> Bytes { + let body = BytecodeBuilder::default().log3_word().selfdestruct(beneficiary).build(); + let accept = 4 + body.len(); + let mut code = BytecodeBuilder::default() + .append(CALLVALUE) + .push_number(accept as u8) + .append(JUMPI) + .build() + .to_vec(); + code.extend_from_slice(&body); + code.extend_from_slice(&[JUMPDEST, STOP]); + Bytes::from(code) +} + +/// A kept same-transaction destruction of an account absent at the start, with one fresh slot, +/// deposited code, one `LOG3` of a word and a non-zero balance moved to an existing account. The +/// account's and the slot's records are taken back, and the code's data size and history with +/// them; state gas comes back whole. The `LOG3` stays counted, 160 bytes, and its history stays +/// charged; the transfer logs stay counted and pay none. A later value transfer to the marked +/// account makes no record and is not a rise. +#[test] +fn test_a_destruction_gives_back_record_history_and_keeps_the_logs() { + if !pins_state() { + return; + } + let runtime = log_and_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::from(1), + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::from(1)) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf, the slot and the code come back"); + // Kept records: the creator and the existing beneficiary. Transfer logs: the endowment, the + // move, and the later value. + const LOG3_WORD: u64 = 32 + 3 * 32 + 32; + assert_eq!(outcome.usage.write_records, 2); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD + 3 * TRANSFER_LOG_SIZE + ); + assert_eq!(outcome.gas.history, history(BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + 2 * WRITE_RECORD_SIZE + LOG3_WORD); + assert_eq!(outcome.result.logs().len(), 4, "the LOG3 and the three transfer logs"); + assert_growth(&probed, 0); +} + +/// The creation is +2 on the top frame, whose remaining becomes 998, so the enclosing frame it +/// calls gets `floor(998 × 98 / 100)` = 978. The enclosing frame calls the account, which +/// destroys itself and returns a net of −2. The enclosing frame's remaining stays at its budget, +/// 978, not 980, so the child it then starts gets `floor(978 × 98 / 100)` = 958. +#[test] +fn test_a_destroying_childs_negative_net_does_not_raise_the_parents_budget() { + assert_eq!(super::frame_share(998), 978); + assert_eq!(super::frame_share(978), 958); + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata(), + ); + let enclosing = BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(NEXT, U256::ZERO) + .return_returndata() + .build(); + let mut db = funded_contract(parent); + db.set_account_code(CHILD, enclosing); + db.set_account_code(NEXT, super::probe_code()); + let Some(gas) = probe_gas(2) else { return }; + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 958 }); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); +} + +/// The enclosing frame, given 2,000,000 gas, halts out of gas after a successful destroying +/// child. The mark, the falls, the give-back and the record takeback are discarded: the leaf, the +/// slot and the code stay charged, the three records stand, and the kept net is 2. +#[test] +fn test_a_halt_after_a_destroying_child_discards_the_mark() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, 2_000_000).append(POP), + ); + // A load at offset 2^32 − 1 cannot pay its memory: an out-of-gas halt. + let enclosing = BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .push_number(u32::MAX) + .append_many([MLOAD, STOP]) + .build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, enclosing.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(!is_destroyed(&outcome, created), "the halt discards the destruction"); + assert_eq!(slot_value(&outcome, created, 1), U256::from(1)); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime) + ); + assert_eq!(outcome.usage.write_records, 3, "the records stand again"); + assert_growth(&probed, 2); +} + +/// A second `SELFDESTRUCT` of an account created in the transaction, with no balance moved and no +/// funding between, subtracts nothing, gives nothing back, takes no record back and creates no +/// beneficiary: the beneficiary does not exist and a zero balance does not create it. +#[test] +fn test_a_second_destruction_with_no_balance_subtracts_nothing() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the first destruction gives the leaf and the code back once"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "no beneficiary"); + assert_growth(&probed, 0); +} + +/// The same repeated destruction after the account was funded again, moving that non-zero +/// balance to an account that does not exist. The second destruction still subtracts nothing and +/// gives nothing back; the value sent to the marked account makes no record. The beneficiary is a +/// rise, 183,600 at `m` = 1, and its record is kept. +#[test] +fn test_a_second_destruction_after_refunding_charges_only_the_beneficiary() { + if !pins_state() { + return; + } + let runtime = runtime_to(BENEFICIARY); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(created, U256::ZERO) + .append(POP) + .call(created, U256::from(1)) + .append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, + "the second destruction only adds the beneficiary" + ); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1)); + assert_eq!(outcome.usage.write_records, 2, "the creator and the beneficiary"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_growth(&probed, 1); +} + +/// Value to the counterfactual address A, then `CREATE2` onto A, then A self-destructs to an +/// existing account. The value call is the rise and the leaf's charge; the creation onto a +/// funded address adds neither. A did not exist at the start, so the destruction is the absent +/// row: it gives back the value call's leaf charge and the code, and takes A's record back. +#[test] +fn test_value_then_create2_then_destruct_gives_the_value_calls_leaf_back() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = BytecodeBuilder::default() + .call(created, U256::from(1)) + .append(POP) + .create2(U256::ZERO, init, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP) + .build() + .to_vec(); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the value call's leaf is given back to the destroying frame"); + // Kept: the creator's record and the existing beneficiary's. Transfer logs: the value call and + // the move. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + 2 * TRANSFER_LOG_SIZE); + assert_growth(&probed, 0); +} + +/// The reservoir is empty. A constructor stores three fresh slots, burns its gas down to about +/// 100,000 left after `SELFDESTRUCT`'s static and cold costs, and self-destructs to a new +/// beneficiary, moving its endowment. The destruction would give back 477,360 at `m` = 1, the +/// leaf's 183,600 and three slots of 97,920, but the beneficiary's new-account charge, 183,600, +/// is made first and cannot be paid: the constructor halts out of gas, the give-back is not +/// credited, and the creation fails with no beneficiary. +#[test] +fn test_a_beneficiary_charge_the_frame_cannot_pay_halts_before_the_give_back() { + if !pins_state() { + return; + } + assert_eq!(ACCOUNT_LEAF_STATE_GAS_M1 + 3 * SLOT_STATE_GAS_M1, 477_360); + // `GAS`, `PUSH3`, `LT`, `PUSH1`, `JUMPI`, `JUMPDEST`: 22 gas a turn, 19 after the last `GAS`. + // Then `PUSH20` and `SELFDESTRUCT`'s static 5,000 and the cold beneficiary. + let after_loop = 19 + 3 + 5_000 + satin_gas_params().selfdestruct_cold_cost(); + let target = u32::try_from(100_000 + 22 + after_loop).expect("fits a PUSH3"); + let slots = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(3), U256::from(1)) + .build(); + let entry = slots.len(); + let mut init = slots.to_vec(); + init.extend_from_slice( + &BytecodeBuilder::default() + .append_many([JUMPDEST, GAS]) + .push_bytes(&target.to_be_bytes()[1..]) + .append(LT) + .push_number(entry as u8) + .append(JUMPI) + .selfdestruct(BENEFICIARY) + .build(), + ); + let code = BytecodeBuilder::default().create(U256::from(1), init).return_top().build(); + let outcome = execute(funded_contract(code), call_tx(5_000_000)); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the creator runs on: {:?}", outcome.result); + }; + assert_eq!(output.data().as_ref(), &[0_u8; 32], "the creation failed"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::ZERO, "no beneficiary is kept"); + assert_eq!(outcome.gas.state, 0, "nothing of the failed creation stays charged"); + assert_eq!(outcome.gas.reservoir_remaining, 0); +} + +/// After the mark, an `SSTORE` of the destroyed account's own slot, `(original 0, present +/// non-zero, new 0)`, on the slot the destruction already gave back. No rise, no fall, no +/// fresh-slot charge and no refill: the state gas is still given back exactly once, and the store +/// makes no record. The EIP-3529 refund counter is not pinned here. +#[test] +fn test_a_cleared_slot_after_the_mark_does_not_refill_again() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + call_with_word( + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + created, + 0, + ) + .append(POP), + ); + let fresh = SLOT_STATE_GAS_M1 as i64; + assert_eq!( + sstore_state_gas(&code, |_| {}, created), + [fresh, 0], + "the constructor's store is charged; the clear after the mark moves no state gas" + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "given back once by the table and not refilled again"); + assert_eq!(outcome.usage.write_records, 1, "the store after the mark makes no record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A pre-existing contract, unchanged so far and holding a balance, self-destructs to an account +/// the transaction already changed. Under a transaction KV limit of 3, the top frame's two records +/// for the earlier transfer leave it 1, so the destroying frame's KV budget is +/// `floor(1 × 98 / 100)` = 0. The cleared account's one record crosses it, kind 1, `limit` 0; the +/// beneficiary adds no record; the operation keeps nothing. Under a limit of 4 the budget is 1 +/// and the same operation fits. +#[test] +fn test_a_cleared_account_with_no_kv_room_stops_at_the_frame_budget() { + let code = BytecodeBuilder::default() + .call(EXISTING, U256::from(1)) + .append(POP) + .call(CHILD, U256::ZERO) + .return_returndata() + .build(); + let Some(gas) = slots_gas(2) else { return }; + for (limit, fits) in [(3, false), (4, true)] { + let mut db = funded_contract(code.clone()); + db.set_account_code(CHILD, runtime_to(EXISTING)); + db.set_account_balance(CHILD, U256::from(10)); + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(limit); + let outcome = super::execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + if fits { + assert_eq!(balance_of(&outcome, CHILD), U256::ZERO); + assert_eq!(balance_of(&outcome, EXISTING), U256::from(12)); + } else { + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 0 }); + assert_eq!(balance_of(&outcome, CHILD), U256::from(10), "the operation keeps nothing"); + assert_eq!(balance_of(&outcome, EXISTING), U256::from(2)); + } + } +} + +/// A destruction inside a frame that reverts, then a later destruction of the same account in a +/// frame that is kept. The first mark does not stand, so the later destruction is the first +/// effective one: it gives the leaf, the slot and the code back once and takes their records back +/// once. +#[test] +fn test_only_the_kept_destruction_gives_the_charges_back() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let parent = after_create( + init, + U256::ZERO, + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(created, U256::ZERO) + .append(POP), + ); + let child = BytecodeBuilder::default().call(created, U256::ZERO).revert().build(); + let Some((outcome, probed)) = both(parent, |db| db.set_account_code(CHILD, child.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf, the code and the slot come back once"); + assert_eq!(outcome.usage.write_records, 1, "their records are taken back once"); + assert_eq!(outcome.gas.history, history(BODY_BYTES + WRITE_RECORD_SIZE)); + assert_growth(&probed, 0); +} + +/// A new account destroyed by its constructor, before any code is deposited and before any slot +/// is written. The leaf is refilled and falls, and the account's record is taken back. Nothing +/// else was charged. +#[test] +fn test_a_new_account_destroyed_before_code_or_slots_refills_the_leaf() { + if !pins_state() { + return; + } + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default()); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "the leaf is refilled and nothing else was charged"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A pre-funded address is created onto, and its constructor destroys it to itself, so no balance +/// moves to another account. The leaf was present: no charge, no refill, no fall, and the record +/// the nonce bump made stands. No beneficiary and no transfer log. +#[test] +fn test_a_prefunded_destruction_that_moves_no_balance_keeps_the_nonce_record() { + if !pins_state() { + return; + } + let init = BytecodeBuilder::default().append_many([ADDRESS, SELFDESTRUCT]).build(); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default()); + let Some((outcome, probed)) = both(code, |db| db.set_account_balance(created, U256::from(1))) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "a present leaf is neither charged nor refilled"); + assert_eq!(outcome.usage.write_records, 2, "the creator's and the nonce bump's records"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// Code deposited, then the account is destroyed in a later call. The account was absent at the +/// start. The code deposit's state gas is refilled, and the code's data size and history are taken +/// back; the code is no record and no unit of state growth. +#[test] +fn test_destroyed_code_refills_its_deposit_and_its_history() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert!(code_state(&runtime) > 0, "the runtime deposits code"); + assert_eq!(outcome.gas.state, 0, "the code deposit and the leaf are refilled"); + // The call carries no calldata: the body is 310 bytes, and the creator's record is kept. + assert_eq!(outcome.gas.history, history(BODY_BYTES + WRITE_RECORD_SIZE)); + assert_eq!(outcome.gas.history_bytes, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_eq!(outcome.usage.write_records, 1); + assert_growth(&probed, 0); +} + +/// Two slots, each original zero and present non-zero, one of them restored to zero before the +/// destruction. The non-zero slot is the zero, non-zero, deleted row: refilled, −1, record back. +/// The restored slot is the zero, zero, deleted row and is not counted again. +#[test] +fn test_slots_deleted_with_the_account_refill_once() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let init = init_returning( + BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(1), U256::ZERO), + &runtime, + ); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(outcome.gas.state, 0, "each slot refills once"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_growth(&probed, 0); +} + +/// A creation onto an address that held nonce 0, balance 0, empty code and slot 1 = 5 at the +/// transaction's start. `CREATE2` does not collide on storage. The address is empty under +/// EIP-161, so the creation charges a new account, 183,600 at `m` = 1, and counts a rise; the leaf +/// is the present row, so the destruction neither refills that charge nor subtracts the rise, and +/// the account's record stands. The code was absent and is given back. +/// +/// The runtime's `SLOAD` of slot 1 reads zero, not the 5 the database holds: a slot of an account +/// created in the transaction that the transaction first accesses after the creation reads zero, +/// so its original is zero, and it is the zero, zero, deleted row, which makes no record. Only a +/// slot accessed before the creation keeps the value the database holds (the record unit test). +#[test] +fn test_a_creation_onto_an_empty_address_with_storage_keeps_the_leaf_charge() { + if !pins_state() { + return; + } + let runtime = BytecodeBuilder::default() + .push_number(1_u8) + .append_many([SLOAD, POP]) + .selfdestruct(EXISTING) + .build(); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + ); + let Some((outcome, probed)) = + both(code, |db| db.set_account_storage(created, U256::from(1), U256::from(5))) + else { + return; + }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "the creation did not collide"); + let slot = &outcome.state[&created].storage[&U256::from(1)]; + assert_eq!( + (slot.original_value, slot.present_value), + (U256::ZERO, U256::ZERO), + "the slot loads as zero for an account created in the transaction" + ); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "the leaf's charge stands"); + // The creator's record and the created account's, which the present leaf keeps. + assert_eq!(outcome.usage.write_records, 2); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 1); +} + +/// Runs `txs` in order over `db` twice — each committed before the next runs, and all on one +/// journal that runs them without finalizing — and returns the last one's outcome on the committed +/// path, having held the other path's to it: the same result, gas, usage and limit stop. +fn the_same_on_one_journal( + db: MemoryDatabase, + txs: &[MegaTransaction], + what: &str, +) -> MegaTransactionOutcome { + use revm::{DatabaseCommit, ExecuteEvm}; + let (last, earlier) = txs.split_last().expect("a transaction"); + let mut committed = db.clone(); + for tx in earlier { + let outcome = execute(committed.clone(), tx.clone()); + assert!(outcome.result.is_success(), "{what}: {:?}", outcome.result); + committed.commit(outcome.result_and_state.state); + } + let control = execute(committed, last.clone()); + + let mut evm = mega_evm::MegaEvm::new(context(db)); + for tx in earlier { + let result = ExecuteEvm::transact_one(&mut evm, tx.clone()).expect("valid"); + assert!(result.is_success(), "{what}: {result:?}"); + } + let outcome = evm.execute_transaction(last.clone()).expect("valid"); + assert_eq!(outcome.result_and_state.result, control.result_and_state.result, "{what}"); + assert_eq!(outcome.gas, control.gas, "{what}"); + assert_eq!(outcome.usage, control.usage, "{what}"); + assert_eq!(outcome.limit_exceeded, control.limit_exceeded, "{what}"); + control +} + +/// A leaf an earlier transaction destroyed is absent at the next transaction's start, whether the +/// two run on one journal, as a block builder runs them, or the first is committed before the +/// second runs. The address held an account the first transaction found: a balance, or nothing but +/// storage. The first transaction creates there and destroys the account, the present row, which +/// gives no leaf back; the second does the same onto an address that now holds nothing, the absent +/// row, whose leaf comes back with its state gas, its unit of state growth and its record. The +/// second transaction's outcome is the same on either path, at any byte price. +#[test] +fn test_a_leaf_an_earlier_transaction_destroyed_is_absent_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let tx = |nonce| { + let mut tx = call_tx(BELOW_THE_CAP); + tx.0.base.nonce = nonce; + tx + }; + for (held, what) in [(true, "a balance"), (false, "storage alone")] { + let mut db = funded_contract(code.clone()); + if held { + db.set_account_balance(created, U256::from(1)); + } else { + db.set_account_storage(created, U256::from(1), U256::from(5)); + } + + let first = execute(db.clone(), tx(0)); + assert!(first.result.is_success(), "{what}: {:?}", first.result); + assert!(is_destroyed(&first, created), "{what}: the first transaction destroyed it"); + let charged = if held { 0 } else { common::account_state_gas() }; + assert_eq!(first.gas.state, charged, "{what}: the present row gives no leaf back"); + + let second = the_same_on_one_journal(db, &[tx(0), tx(1)], what); + assert!(second.result.is_success(), "{what}: {:?}", second.result); + assert_eq!(second.gas.state, 0, "{what}: the absent row gives the leaf back"); + assert_eq!(second.usage.state_growth, 0, "{what}"); + assert_eq!(second.usage.write_records, 1, "{what}: the factory's nonce alone"); + assert_eq!(second.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE, "{what}"); + } +} + +/// A creation at the address an earlier transaction funded, destroyed to an existing account, +/// whose leaf the transaction found present: the creation charged no account, so the destruction +/// gives no leaf back, and the created account's record stands beside the factory's and the +/// beneficiary's, with the transfer log of the balance it moved. +fn assert_the_present_row(outcome: &MegaTransactionOutcome, created: Address, what: &str) { + assert!(outcome.result.is_success(), "{what}: {:?}", outcome.result); + assert!(is_destroyed(outcome, created), "{what}: the creation did not collide"); + assert_eq!(outcome.gas.state, 0, "{what}: no leaf was charged or given back"); + assert_eq!(outcome.usage.state_growth, 0, "{what}"); + assert_eq!(outcome.usage.write_records, 3, "{what}: the factory, the account, the beneficiary"); + assert_eq!( + outcome.usage.data_size, + BODY_BYTES + 3 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + "{what}" + ); +} + +/// A leaf an earlier transaction funded is present at the next transaction's start, whether the +/// two run on one journal or the first is committed before the second runs. The address held no +/// account until the first transaction moved 1 wei to it; the second creates there and destroys +/// the account to an existing one. On one journal revm's flag of the account the database answered +/// none for still stands from the first transaction's load, but the leaf held a balance when the +/// second started, so it is the present row, as on the committed path. +#[test] +fn test_a_leaf_an_earlier_transaction_funded_is_present_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let mut create = call_tx(BELOW_THE_CAP); + create.0.base.nonce = 1; + let fund = common::call(CALLER, created, U256::from(1), BELOW_THE_CAP); + let outcome = the_same_on_one_journal(funded_contract(code), &[fund, create], "funded"); + assert_the_present_row(&outcome, created, "funded"); +} + +/// A leaf funded after an earlier transaction destroyed the account there is present at the next +/// transaction's start, on one journal as on the committed path. The first transaction creates at +/// the address and destroys the account; the second moves 1 wei to it; the third creates there +/// again and destroys the account to an existing one. On one journal revm's entry names the third +/// destruction a first one in its transaction of an account an earlier transaction destroyed, but +/// the leaf held a balance when the third started, so it is the present row. The address held no +/// account at first, or a balance the database answered. +#[test] +fn test_a_leaf_funded_after_its_destruction_is_present_at_the_next_start() { + let init = runtime_to(EXISTING); + let created = created_at(&init); + let code = after_create(init, U256::ZERO, BytecodeBuilder::default().append(STOP)); + let create = |nonce| { + let mut tx = call_tx(BELOW_THE_CAP); + tx.0.base.nonce = nonce; + tx + }; + let mut fund = common::call(CALLER, created, U256::from(1), BELOW_THE_CAP); + fund.0.base.nonce = 1; + for (held, what) in [(false, "no account"), (true, "a balance")] { + let mut db = funded_contract(code.clone()); + if held { + db.set_account_balance(created, U256::from(1)); + } + let outcome = the_same_on_one_journal(db, &[create(0), fund.clone(), create(2)], what); + assert_the_present_row(&outcome, created, what); + } +} + +/// After the mark, an `SSTORE` of a slot the destroyed account never wrote, `(original 0, present +/// 0, new non-zero)`: the write happens, but it does not rise, keeps no fresh-slot state gas — the +/// pricing hook prices it at nothing, so the store neither charges nor refills it — and makes no +/// record. +#[test] +fn test_a_fresh_slot_written_after_the_mark_is_neither_charged_nor_counted() { + if !pins_state() { + return; + } + let runtime = store_or_destroy(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + call_with_word( + BytecodeBuilder::default().call(created, U256::ZERO).append(POP), + created, + 7, + ) + .append(POP), + ); + assert_eq!(sstore_state_gas(&code, |_| {}, created), [0], "the store moves no state gas"); + let Some((outcome, probed)) = both(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created)); + assert_eq!(slot_value(&outcome, created, 1), U256::from(7), "the store after the mark ran"); + assert_eq!(outcome.gas.state, 0, "the slot keeps no state gas"); + assert_eq!(outcome.usage.write_records, 1, "only the creator's record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE); + assert_growth(&probed, 0); +} + +/// A created account whose runtime reads the block's timestamp and then self-destructs, under a +/// compute cap its `SELFDESTRUCT` crosses: at the opcode's own gas, before the destruction is +/// written, or at its cold access to the beneficiary, after it. Either way the crossing stops the +/// destroying frame before the opcode completes, so the operation applies none of the table: the +/// account is not destroyed, its leaf, code and slot stay charged and recorded, and its caller +/// resumes and returns the stop. Under a cap that also leaves the caller's own work after the call +/// its room, the destruction completes and gives them back. +#[test] +fn test_a_detention_crossing_at_the_destruction_applies_none_of_the_table() { + use revm::bytecode::opcode::TIMESTAMP; + if !pins_state() { + return; + } + let mut runtime = vec![TIMESTAMP, POP]; + runtime.extend_from_slice(&runtime_to(EXISTING)); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP).return_returndata(), + ); + // After the read: `POP`, `PUSH20`, then the opcode's 5,000 and its cold access. + let cold = satin_gas_params().selfdestruct_cold_cost(); + for cap in [2 + 3 + 5_000 - 1, 2 + 3 + 5_000 + cold - 1] { + let limits = + mega_evm::EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let outcome = + super::execute_under(funded_contract(code.clone()), call_tx(BELOW_THE_CAP), limits); + assert!(outcome.result.is_success(), "cap {cap}: {:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "cap {cap}: the destroying frame is stopped"); + assert!(!is_destroyed(&outcome, created), "cap {cap}"); + assert_eq!( + outcome.gas.state, + ACCOUNT_LEAF_STATE_GAS_M1 + SLOT_STATE_GAS_M1 + code_state(&runtime), + "cap {cap}: nothing is given back" + ); + assert_eq!(outcome.usage.write_records, 3, "cap {cap}: the records stand"); + } + let limits = mega_evm::EvmTxRuntimeLimits::default() + .with_block_env_access_compute_gas_limit(2 + 3 + 5_000 + cold + 100); + let outcome = super::execute_under(funded_contract(code), call_tx(BELOW_THE_CAP), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "within the cap the destruction completes"); + assert_eq!(outcome.gas.state, 0, "and gives the account's state gas back"); +} + +/// A transaction gas limit below the execution cap: no reservoir, so state gas spills onto +/// regular gas and a frame's regular gas is all that pays it. +const BELOW_THE_CAP: u64 = 50_000_000; + +/// `CALL` of `target` with `gas` and one 32-byte word of calldata, `word`. +fn call_with_word_and_gas( + code: BytecodeBuilder, + target: Address, + word: u64, + gas: u32, +) -> BytecodeBuilder { + code.mstore(0x200, U256::from(word).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .push_number(0x200_u16) + .append(PUSH0) + .push_address(target) + .push_number(gas) + .append(CALL) +} + +/// After the mark, a fresh `SSTORE` on 60,000 gas, below the transaction's execution cap where +/// no reservoir pays: the store is charged no state gas, so it completes, where the same store of +/// the account before any destruction needs the slot's 97,920 of state gas and runs out of gas. +#[test] +fn test_a_store_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { + if !pins_state() { + return; + } + const GAS: u32 = 60_000; + assert!(u64::from(GAS) < SLOT_STATE_GAS_M1); + let runtime = store_or_destroy(EXISTING); + let init = init_returning(BytecodeBuilder::default(), &runtime); + let created = created_at(&init); + for destroyed in [true, false] { + let first = if destroyed { + BytecodeBuilder::default().call(created, U256::ZERO).append(POP) + } else { + BytecodeBuilder::default() + }; + let tail = call_with_word_and_gas(first, created, 7, GAS).append(POP).stop(); + let code = after_create(init.clone(), U256::ZERO, tail); + let outcome = execute(funded_contract(code), call_tx(BELOW_THE_CAP)); + assert!(outcome.result.is_success(), "destroyed {destroyed}: {:?}", outcome.result); + let stored = if destroyed { U256::from(7) } else { U256::ZERO }; + assert_eq!(slot_value(&outcome, created, 1), stored, "destroyed {destroyed}"); + } +} + +/// Code deposited after its constructor destroyed the account, on gas that cannot pay the +/// deposit's state gas: the address held a balance before the transaction, so its leaf was +/// present and the destruction refills nothing that could pay for the deposit. The deposit is +/// charged no state gas, so the creation succeeds; the same constructor without the destruction +/// runs out of gas on the deposit, and the creation fails. +/// +/// The transaction carries a reservoir of 10,000 above the cap and the body: the creating frame's +/// share of it pays the history of the `CREATE2`'s two records, 7,040, which the 2 per cent of its +/// regular gas it keeps could not, and leaves the constructor a share of about 2,700. The creating +/// frame is called with 40,000 of regular gas: once the `CREATE2` took its own, the constructor's +/// share covers the destruction and the deposit's hash, and falls short of the deposit's state gas. +/// The destroying constructor deploys from 30,000 up, and the other fails up to 45,000. +#[test] +fn test_a_deposit_after_the_mark_is_not_charged_what_its_frame_cannot_pay() { + if !pins_state() { + return; + } + const CREATOR_GAS: u32 = 40_000; + let runtime = runtime_to(EXISTING); + assert!(code_state(&runtime) > 30_000); + let gas = EXECUTION_CAP + BODY_HISTORY + 10_000; + for destroyed in [true, false] { + let mut init = + if destroyed { delegatecall(GRAND).append(POP).build().to_vec() } else { vec![] }; + init.extend_from_slice(&BytecodeBuilder::default().return_with_data(&runtime).build()); + let init = Bytes::from(init); + let created = CHILD.create2(B256::ZERO, keccak256(&init)); + let creator = + BytecodeBuilder::default().create2(U256::ZERO, &init, U256::ZERO).return_top().build(); + let code = call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, CREATOR_GAS) + .append(POP) + .return_returndata() + .build() + .to_vec(); + let mut db = funded_contract(code); + db.set_account_code(CHILD, creator); + db.set_account_code(GRAND, runtime.clone()); + db.set_account_balance(created, U256::from(1)); + let outcome = execute(db, call_tx(gas)); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("destroyed {destroyed}: {:?}", outcome.result); + }; + let deployed = + U256::from_be_slice(output.data()) == U256::from_be_slice(created.as_slice()); + assert_eq!(deployed, destroyed, "destroyed {destroyed}: the creation succeeds"); + if destroyed { + assert!(is_destroyed(&outcome, created)); + assert!(has_code(&outcome, created), "the code was deposited"); + assert_eq!(outcome.gas.state, 0, "and charged no state gas"); + } + } +} + +/// A constructor that destroys its own account through a `DELEGATECALL` to code that +/// self-destructs, and then returns its runtime. The destruction gives the leaf back; the code is +/// deposited after the mark, so its state gas is not kept, while its data size and history are +/// charged as any deposited code's. A later call that runs the runtime, which self-destructs +/// again, takes nothing back. +#[test] +fn test_code_deposited_after_its_constructor_destroyed_the_account_keeps_no_state_gas() { + if !pins_state() { + return; + } + let runtime = runtime_to(EXISTING); + let mut prefix = delegatecall(CHILD).append(POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().return_with_data(&runtime).build()); + let init = Bytes::from(prefix); + let created = created_at(&init); + for again in [false, true] { + let tail = if again { + BytecodeBuilder::default().call(created, U256::ZERO).append(POP) + } else { + BytecodeBuilder::default() + }; + let code = after_create(init.clone(), U256::ZERO, tail); + let Some((outcome, probed)) = both(code, |db| db.set_account_code(CHILD, runtime.clone())) + else { + return; + }; + assert!(outcome.result.is_success(), "again {again}: {:?}", outcome.result); + assert!(is_destroyed(&outcome, created), "again {again}"); + assert!(has_code(&outcome, created), "again {again}: the code was deposited"); + assert_eq!(outcome.gas.state, 0, "again {again}: the leaf came back, the code kept none"); + let kept = BODY_BYTES + WRITE_RECORD_SIZE + runtime.len() as u64; + assert_eq!(outcome.usage.data_size, kept, "again {again}: the code's bytes stay"); + assert_eq!(outcome.gas.history, history(kept), "again {again}: and their history"); + assert_eq!(outcome.usage.write_records, 1, "again {again}: only the creator's record"); + assert_growth(&probed, 0); + } +} + +/// A creation transaction carrying 1 wei whose constructor writes 999 fresh slots and then +/// self-destructs to an account that does not exist. The created account and its slots use the +/// whole state-growth limit of 1,000, which is the transaction's own frame's budget, and the +/// beneficiary would be a 1,001st unit: the destruction takes back the absent leaf and the 999 +/// slots before the beneficiary is held, so the beneficiary fits and the transaction keeps one new +/// account. Under a limit one unit higher the transaction keeps the same: the limit stops nothing. +#[test] +fn test_a_creation_at_its_growth_limit_that_destroys_itself_to_a_new_account_succeeds() { + let mut init = store_n_prefix(999, 1, false); + init.extend_from_slice(&runtime_to(BENEFICIARY)); + let Some(gas) = slots_gas(1_000) else { return }; + let tx = || { + OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Create, + data: Bytes::from(init.clone()), + value: U256::from(1), + gas_limit: gas, + ..Default::default() + })) + }; + let created = CALLER.create(0); + for limit in [TX_STATE_GROWTH_LIMIT, TX_STATE_GROWTH_LIMIT + 1] { + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_state_growth_limit(limit); + let outcome = super::execute_under(world(&[]), tx(), limits); + assert!(outcome.result.is_success(), "limit {limit}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "limit {limit}"); + assert!(is_destroyed(&outcome, created), "limit {limit}"); + assert_eq!(balance_of(&outcome, BENEFICIARY), U256::from(1), "limit {limit}"); + assert_eq!(outcome.usage.state_growth, 1, "limit {limit}: the beneficiary alone"); + // The beneficiary's record; the created account's and its slots' went with it. + assert_eq!(outcome.usage.write_records, 1, "limit {limit}"); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "limit {limit}"); + } + } +} + +/// The state gas each `SSTORE` an account ran moved on its frame's net, in execution order. +#[derive(Clone, Debug, Default)] +struct SstoreStateGas { + armed: Option<(Address, i64)>, + seen: Vec<(Address, i64)>, +} + +impl Inspector, EthInterpreter> for SstoreStateGas { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + if interp.bytecode.opcode() == SSTORE { + self.armed = Some((interp.input.target_address(), interp.gas.state_gas_spent())); + } + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if let Some((account, before)) = self.armed.take() { + self.seen.push((account, interp.gas.state_gas_spent() - before)); + } + } +} + +/// What each `SSTORE` that ran in `account` moved its frame's state gas by, in order, in the +/// plain run [`both`] makes of `scenario`. +fn sstore_state_gas( + scenario: &[u8], + setup: impl Fn(&mut MemoryDatabase), + account: Address, +) -> Vec { + let mut code = scenario.to_vec(); + code.push(STOP); + let mut db = funded_contract(code); + setup(&mut db); + let gas = probe_gas(10).expect("the scenario fits a gas limit"); + let mut evm = mega_evm::MegaEvm::new(context(db)).with_inspector(SstoreStateGas::default()); + let outcome = evm.execute_transaction(call_tx(gas)).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + evm.inspector().seen.iter().filter(|(at, _)| *at == account).map(|(_, moved)| *moved).collect() +} + +/// What a frame's gas held just before and just after its `SELFDESTRUCT`. +#[derive(Clone, Debug, Default)] +struct DestructionGas { + armed: bool, + /// `(regular remaining, reservoir)` at the opcode, before its static gas. + before: Option<(u64, u64)>, + /// `(regular remaining, reservoir)` once the opcode completed. + after: Option<(u64, u64)>, +} + +impl Inspector, EthInterpreter> for DestructionGas { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + if interp.bytecode.opcode() == SELFDESTRUCT { + self.armed = true; + self.before = Some((interp.gas.remaining(), interp.gas.reservoir())); + } + } + + fn step_end( + &mut self, + interp: &mut Interpreter, + _context: &mut MegaContext, + ) { + if self.armed { + self.armed = false; + self.after = Some((interp.gas.remaining(), interp.gas.reservoir())); + } + } +} + +/// The transaction is below the execution cap, so the reservoir is empty. The destroying frame +/// stores two fresh slots of its own, which spill 195,840 of state gas and 7,040 of history onto +/// its regular gas, and self-destructs to a warm existing account. The table gives back the leaf +/// and its record, slot 1 and its record from the constructor, the code's state gas and history, +/// and the frame's own two slots and records. The frame's regular gas is credited first, up to +/// the 202,880 still spilled, and the rest goes to its reservoir. Read at the opcode with an +/// inspector. At the transaction's end nothing is left in the reservoir and no state gas stays. +#[test] +fn test_a_give_back_onto_an_empty_reservoir_credits_the_spill_first() { + if !pins_state() { + return; + } + let runtime = BytecodeBuilder::default() + .sstore(U256::from(2), U256::from(1)) + .sstore(U256::from(3), U256::from(1)) + .selfdestruct(EXISTING) + .build(); + let init = + init_returning(BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), &runtime); + let created = created_at(&init); + let code = after_create( + init, + U256::ZERO, + BytecodeBuilder::default().call(created, U256::ZERO).append(POP).stop(), + ); + let spilled = 2 * (SLOT_STATE_GAS_M1 + RECORD_HISTORY); + assert_eq!(spilled, 202_880); + let rest = ACCOUNT_LEAF_STATE_GAS_M1 + + RECORD_HISTORY + + SLOT_STATE_GAS_M1 + + RECORD_HISTORY + + code_state(&runtime) + + history(runtime.len() as u64); + let mut evm = mega_evm::MegaEvm::new(context(funded_contract(code))) + .with_inspector(DestructionGas::default()); + let outcome = evm + .execute_transaction(warm_call(50_000_000, &[EXISTING])) + .expect("the transaction is valid"); + let probe = evm.inspector().clone(); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (before, reservoir_before) = probe.before.expect("the account self-destructed"); + let (after, reservoir_after) = probe.after.expect("the opcode completed"); + assert_eq!(reservoir_before, 0, "the reservoir is empty"); + assert_eq!(after + 5_000, before + spilled, "regular gas is credited up to the spill"); + assert_eq!(reservoir_after, rest, "the rest goes to the reservoir"); + assert_eq!(outcome.gas.state, 0); + assert_eq!(outcome.gas.reservoir_remaining, 0, "the credit meets the callers' spill too"); +} + +/// A creation transaction whose constructor destroys its own account. On success the created +/// account's record is given back once, 3,520 at the spec's byte price, and not a second time. +/// When that first frame fails, the table's give-back is discarded and the settlement gives the +/// charge back once. +#[test] +fn test_a_creation_that_destroys_itself_refunds_its_record_once() { + if !pins_state() { + return; + } + let mut prefix = delegatecall(CHILD).append(POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().revert().build()); + let init = Bytes::from(prefix); + let db = world(&[(CHILD, runtime_to(EXISTING))]); + let Some(gas) = slots_gas(1) else { return }; + let outcome = execute(db, create_tx(init.clone(), gas)); + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "a failing constructor reverts the creation: {:?}", + outcome.result + ); + let body = (BODY_BYTES + init.len() as u64) * HISTORY_GAS_PER_BYTE; + assert_eq!(outcome.gas.history, body, "a failed first frame gives the record back once"); + assert_eq!(outcome.gas.state, 0); + + let init = runtime_to(EXISTING); + let Some(gas) = slots_gas(1) else { return }; + let db = world(&[(EXISTING, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, create_tx(init.clone(), gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let body = (BODY_BYTES + init.len() as u64) * HISTORY_GAS_PER_BYTE; + assert_eq!( + outcome.gas.history, body, + "giving the created record back removes {RECORD_HISTORY}, once" + ); + assert_eq!(outcome.gas.history, outcome.gas.history_bytes * HISTORY_GAS_PER_BYTE); + assert_eq!(outcome.gas.state, 0, "the leaf is given back and the beneficiary already exists"); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs new file mode 100644 index 000000000..be1b98ecf --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/forwarding.rs @@ -0,0 +1,438 @@ +//! The gas cap and the reservoir share. +//! +//! A child frame is started with an explicit gas below the caller's cap, so the gas it holds at +//! `CALL` is the number the test names. The opcode's static warm read is not yet charged when the +//! inspector reads `remaining`. + +use alloy_primitives::{Bytes, U256}; +use mega_evm::{ + test_utils::{neutral_cfg, neutralize_evm, note_price_guard, BytecodeBuilder}, + EthSpecId, EvmTxRuntimeLimits, MegaEvm, MegaLimitExceeded, +}; +use revm::bytecode::opcode::{ + CALL, CALLDATALOAD, GAS, MSTORE8, POP, PUSH0, SHR, SSTORE, STOP, TIMESTAMP, +}; + +use super::{ + at_spec_prices, call_tx, call_with_reservoir, execute, execute_forward, execute_forward_under, + forward_to, gas_cap, returned_stop, slot_value, warm_call, world, CALL_STIPEND, CHILD, + CONTRACT, EXECUTION_CAP, EXISTING, GRAND, HISTORY_ALLOWANCE_BYTES, HISTORY_ALLOWANCE_GAS, + HISTORY_GAS_PER_BYTE, RESERVOIR_KEPT_PERCENT, SLOT_STATE_GAS_M1, VALUE_TRANSFER_GAS, WARM_READ, +}; +use crate::common::{self, context}; + +/// Gas the non-value inner frame spends before `CALL`'s static warm read. +/// +/// Five `PUSH0`, one `PUSH20` and `GAS`: `5 × 2 + 3 + 2`. +const NON_VALUE_PREFIX: u64 = 15; + +/// Gas the value inner frame spends before `CALL`'s static warm read. +/// +/// Four `PUSH0`, one `PUSH1`, one `PUSH20` and `GAS`: `4 × 2 + 3 + 3 + 2`. +const VALUE_PREFIX: u64 = 16; + +/// Inner code that calls [`EXISTING`] with all the gas it has. +fn measuring_call(value: bool) -> Bytes { + let mut code = BytecodeBuilder::default(); + if value { + code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_number(1_u8); + } else { + code = code.append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]); + } + code.push_address(EXISTING).append_many([GAS, CALL, STOP]).build() +} + +/// Outer code that gives [`CHILD`] exactly `frame_gas`, carrying no value, so no stipend is added +/// to it. +fn grant(frame_gas: u16) -> Bytes { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(frame_gas) + .append_many([CALL, STOP]) + .build() +} + +/// A warm call above the execution cap. The reservoir pays the history of the inner value call's +/// two records, which the caller could not pay from the 2% of its regular gas it keeps. +fn measuring_tx() -> super::MegaTransaction { + warm_call(EXECUTION_CAP + common::value_call_room(), &[CHILD, EXISTING]) +} + +/// `(gas held at the inner CALL, gas the inner CALL forwarded)`. +fn measure(frame_gas: u16, value: bool) -> (u64, u64) { + let db = world(&[ + (CONTRACT, grant(frame_gas)), + (CHILD, measuring_call(value)), + (EXISTING, Bytes::from_static(&[STOP])), + ]); + let (outcome, probe) = execute_forward(db, measuring_tx(), super::Forward::targeting(EXISTING)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = probe.held.unwrap_or_else(|| { + panic!("the inner CALL was reached; calls {:?}", probe.calls); + }); + let forwarded = probe.gas_limit.expect("the inner CALL forwarded gas"); + (held, forwarded) +} + +/// What EIP-150's 63/64 rule would forward of `remaining`, for contrast. +const fn eip150(remaining: u64) -> u64 { + remaining - remaining / 64 +} + +/// Regular gas left after the warm read, which is the cap's input. +fn left_after_warm(held: u64) -> u64 { + held - WARM_READ +} + +/// Parent reservoir `R = 50 × 97,920`. The child receives `R − R × 2 / 100`. The grandchild +/// receives that share of what the child has left. +#[test] +fn test_a_child_receives_the_reservoir_share() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, forward_to(GRAND)), + (GRAND, Bytes::from_static(&[STOP])), + ]); + let (outcome, probe) = execute_forward(db, call_with_reservoir(R), super::Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(probe.calls.len() >= 2, "child and grandchild: {:?}", probe.calls); + assert_eq!(probe.reservoir_given(CONTRACT), R, "the transaction's own frame takes the whole"); + let child = probe.reservoir_given(CHILD); + let grandchild = probe.reservoir_given(GRAND); + assert_eq!(child, R - R * RESERVOIR_KEPT_PERCENT / 100, "child reservoir {child}"); + assert_eq!( + grandchild, + child - child * RESERVOIR_KEPT_PERCENT / 100, + "grandchild reservoir {grandchild}" + ); +} + +/// The child spends one fresh slot from its reservoir share and reverts. The caller had no +/// outstanding spill, so it holds the reservoir it had after the body's charge. The slot is not +/// kept and the state ledger is zero. +#[test] +fn test_a_reverted_child_returns_its_reservoir_share() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + if common::slot_state_gas() > R { + note_price_guard("one fresh slot costs more than the reservoir this row forwards"); + return; + } + let mut child = super::store_n_prefix(1, 1, false); + child.extend_from_slice(&[PUSH0, PUSH0, 0xfd]); + let db = world(&[(CONTRACT, forward_to(CHILD)), (CHILD, Bytes::from(child))]); + let outcome = execute(db, call_with_reservoir(R)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(outcome.gas.state, 0, "the child's state charge came back"); + assert_eq!(outcome.gas.reservoir_remaining, R); +} + +/// The share a failed child returns when its caller has an outstanding spill. +/// +/// The caller holds `R` and keeps `k = R × 2 / 100` when its first child takes the share. That +/// child fills 50 fresh slots, more than its share pays, and succeeds, so its spill joins the +/// caller's and the caller's kept `k` is not drawn. The second child is given `k − k × 2 / 100` +/// and reverts at once. The share it returns unwinds the caller's spill first, so the caller ends +/// with `k × 2 / 100`, not the `k` it held after the start's charges. At `m` = 1, `R` = +/// 4,896,000, `k` = 97,920 and the reservoir left is 1,958. +/// +/// The caller is the transaction's own frame, so its reservoir is read where its frame ends: +/// the transaction then settles that frame as a caller settles a child, and the 1,958 unwinds +/// the frame's own outstanding spill there, coming back to the sender as regular gas. +#[test] +fn test_a_reverted_childs_share_unwinds_the_callers_spill_first() { + if common::state_is_free() { + return; + } + let r = 50 * common::slot_state_gas(); + let kept = r * RESERVOIR_KEPT_PERCENT / 100; + let left = kept * RESERVOIR_KEPT_PERCENT / 100; + if left == 0 { + note_price_guard("the caller's second keep rounds to nothing"); + return; + } + let parent = BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(GRAND, U256::ZERO) + .append(POP) + .stop() + .build(); + let db = world(&[ + (CONTRACT, parent), + (CHILD, super::store_n_slots(50)), + (GRAND, BytecodeBuilder::default().revert().build()), + ]); + let (outcome, probe) = execute_forward(db, call_with_reservoir(r), super::Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 50), U256::from(1), "the first child succeeded"); + assert_eq!(probe.reservoir_given(GRAND), kept - left, "the second child's share"); + let ended = probe.call_ends.last().expect("the transaction's own frame ended"); + assert_eq!(ended.0, CONTRACT); + assert_eq!( + ended.1, left, + "the returned share unwound the spill; k = {kept}, k × 2 / 100 = {left}" + ); + assert_eq!(outcome.gas.reservoir_remaining, 0, "the transaction's settlement unwound the rest"); +} + +/// `CALL` with gas argument 1 still forwards the reservoir share, `R − R × 2 / 100` of the +/// reservoir `R` the caller holds. The gas argument bounds the regular gas only. +#[test] +fn test_a_one_gas_call_still_forwards_the_reservoir() { + const R: u64 = SLOT_STATE_GAS_M1; + let parent = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(CHILD) + .push_number(1_u8) + .append_many([CALL, STOP]) + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, super::store_n_slots(1))]); + let (outcome, probe) = + execute_forward(db, call_with_reservoir(R), super::Forward::targeting(CHILD)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(probe.gas_limit, Some(1), "the gas argument bounds regular gas"); + assert_eq!(probe.reservoir, Some(super::reservoir_share(R)), "the share, not 1 and not R"); +} + +/// With 1,000 regular gas left, the cap is 980. EIP-150 would forward 985. +#[test] +fn test_a_call_with_1000_gas_left_forwards_980() { + let (held, forwarded) = measure((1_000 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 1_000, "held {held}"); + assert_eq!(forwarded, gas_cap(1_000)); + assert_ne!(forwarded, eip150(1_000), "EIP-150's 985 is not the cap"); +} + +/// With 99 left, the subtraction forwards 98. The frame-budget product would forward 97. +/// EIP-150 also forwards 98, so a pass here does not decide the quotient. +#[test] +fn test_a_call_with_99_gas_left_forwards_98() { + let (held, forwarded) = measure((99 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 99, "held {held}"); + assert_eq!(forwarded, 99 - 99 * RESERVOIR_KEPT_PERCENT / 100); + assert_ne!(forwarded, super::frame_share(99), "the product would forward 97"); +} + +/// With 50 left, the subtraction forwards 49. EIP-150 forwards 50, because `floor(50 / 64)` is 0. +#[test] +fn test_a_call_with_50_gas_left_forwards_49() { + let (held, forwarded) = measure((50 + NON_VALUE_PREFIX + WARM_READ) as u16, false); + assert_eq!(left_after_warm(held), 50, "held {held}"); + assert_eq!(forwarded, 49); + assert_ne!(forwarded, eip150(50), "EIP-150 forwards the whole 50"); +} + +/// After the 11,300 value-transfer charge the caller has 10,000 left and requests all. The cap +/// on 10,000 is 9,800. The child receives 12,100. The caller keeps 200. The 2,300 stipend is +/// already inside the 11,300 and is added after the cap, not taken from the caller. The caller +/// is granted its gas without value, so its own gas has no stipend in it, and the transaction's +/// reservoir pays the history of the value call's records. +#[test] +fn test_a_value_call_with_10000_left_forwards_12100() { + let frame = VALUE_PREFIX + WARM_READ + VALUE_TRANSFER_GAS + 10_000; + let (held, forwarded) = measure(frame as u16, true); + let after_value = held - WARM_READ - VALUE_TRANSFER_GAS; + assert_eq!(after_value, 10_000, "held {held}"); + assert_eq!(forwarded, gas_cap(10_000) + CALL_STIPEND); + assert_eq!(10_000 - gas_cap(10_000), 200, "the caller keeps 200 of the 10,000"); +} + +/// A value `CALL` below the top frame grants 160 history bytes (14,080 gas). The allowance is +/// outside the child's gas limit and outside the reservoir share: the child's gas is the 98/100 +/// cap plus the 2,300 stipend, and its reservoir is the share of what the caller has left after +/// the history of the start's two records. +#[test] +fn test_a_value_call_grants_a_history_allowance_outside_gas() { + if !at_spec_prices() || common::history_is_free() || common::history_rounds() { + return; + } + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let parent = BytecodeBuilder::default().call(CHILD, U256::from(1)).stop().build(); + let db = world(&[ + (CONTRACT, parent), + (CHILD, BytecodeBuilder::default().log3_word().stop().build()), + ]) + .account_balance(CONTRACT, U256::from(10u128.pow(18))); + // The access list adds one 20-byte address to the body. + let gas = EXECUTION_CAP + common::history(super::BODY_BYTES + 20) + R; + let (outcome, probe) = + execute_forward(db, warm_call(gas, &[CHILD]), super::Forward::targeting(CHILD)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let gap = outcome.gas.history_bytes * HISTORY_GAS_PER_BYTE - outcome.gas.history; + assert_eq!( + gap, + HISTORY_ALLOWANCE_BYTES * HISTORY_GAS_PER_BYTE, + "history bytes {} gas {}", + outcome.gas.history_bytes, + outcome.gas.history + ); + assert_eq!(gap, HISTORY_ALLOWANCE_GAS); + let held = probe.held.expect("the value call was reached"); + let forwarded = probe.gas_limit.expect("the value call forwarded gas"); + let left = held - WARM_READ - VALUE_TRANSFER_GAS; + assert_eq!(forwarded, gas_cap(left) + CALL_STIPEND, "the cap plus the stipend, no allowance"); + // The caller's and the child's balances change: two records, paid from the reservoir first. + let after_records = R - 2 * super::RECORD_HISTORY; + assert_eq!(probe.reservoir, Some(super::reservoir_share(after_records))); +} + +/// Reservoir remaining 1 gives the child 1 and the caller 0. A frame whose data-size remaining is +/// 1 gives its child `floor(1 × 98 / 100)` = 0, so one 40-byte record stops that child, kind 0, +/// `limit` 0. +/// +/// A transaction data-size limit of the body plus 2,002 gives the top frame 2,002 and its child +/// `floor(2,002 × 98 / 100)` = 1,961. That child keeps 49 records, 1,960 bytes, and has 1 left. +/// The transaction still has 42, so the grandchild's record crosses its own budget alone. +#[test] +fn test_a_reservoir_of_1_and_a_frame_budget_of_1() { + const TOP: u64 = 2_002; + assert_eq!(super::frame_share(TOP), 1_961); + assert_eq!(super::frame_share(TOP) - 49 * super::WRITE_RECORD_SIZE, 1); + let mut child = super::store_n_prefix(49, 1, false); + child.extend_from_slice( + &BytecodeBuilder::default().call(GRAND, U256::ZERO).return_returndata().build(), + ); + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, Bytes::from(child)), + (GRAND, super::store_n_slots(1)), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(super::BODY_BYTES + TOP); + let (outcome, probe) = + execute_forward_under(db, call_with_reservoir(1), limits, super::Forward::targeting(CHILD)); + assert_eq!(probe.reservoir, Some(1), "a remaining 1 forwards the whole reservoir"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the child caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 0 }); + assert_eq!(slot_value(&outcome, GRAND, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CHILD, 49), U256::from(1), "the child kept its records"); +} + +/// A detained frame forwards with the 98/100 cap computed on spendable plus withheld. The child +/// then makes a regular charge past the compute cap, and that charge stops it, kind 2. +#[test] +fn test_a_detained_frame_forwards_on_spendable_plus_withheld() { + const CAP: u64 = 50_000; + let parent = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .call(CHILD, U256::ZERO) + .return_returndata() + .build(); + // One byte at offset 200_000 expands 6,251 words: about 95,000 gas, past the cap. + let child = BytecodeBuilder::default() + .push_number(1_u8) + .push_number(200_000_u32) + .append_many([MSTORE8, STOP]) + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(CAP); + let (outcome, probe) = execute_forward_under( + db, + warm_call(5_000_000, &[CHILD]), + limits, + super::Forward::targeting(CHILD), + ); + let held = probe.held.expect("the call after TIMESTAMP was reached"); + let forwarded = probe.gas_limit.expect("the call forwarded gas"); + let left = held - WARM_READ; + assert!(left > CAP, "remaining() includes the withheld part: left {left}, cap {CAP}"); + assert_eq!(forwarded, gas_cap(left), "held {held}, forwarded {forwarded}"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2); +} + +/// The equivalence-mode contrast to Satin's forward, of which the page pins no figure. +/// +/// Neutral Amsterdam forwards EIP-150's 985 and passes each child the whole reservoir its caller +/// holds. `no_limits()` on Satin does not change the forward: 980 of regular gas, and at each of +/// the two calls the reservoir share, so the measured grandchild call gets the share of the share. +#[test] +fn test_neutral_forwards_eip150_and_satin_keeps_its_cap_without_limits() { + const R: u64 = 50 * SLOT_STATE_GAS_M1; + let frame = (1_000 + NON_VALUE_PREFIX + WARM_READ) as u16; + let code = [ + (CONTRACT, grant(frame)), + (CHILD, measuring_call(false)), + (EXISTING, Bytes::from_static(&[STOP])), + ]; + // The access list adds two 20-byte addresses to the body. + let gas = EXECUTION_CAP + common::history(super::BODY_BYTES + 40) + R; + let tx = warm_call(gas, &[CHILD, EXISTING]); + + let cfg = neutral_cfg(EthSpecId::AMSTERDAM).expect("Amsterdam has a neutral configuration"); + let mut neutral = MegaEvm::new(context(world(&code)).with_neutral_cfg(cfg)) + .with_inspector(super::Forward::targeting(EXISTING)); + neutralize_evm(&mut neutral, EthSpecId::AMSTERDAM).expect("Amsterdam neutralizes"); + let neutral_outcome = + neutral.execute_transaction(tx.clone()).expect("the transaction is valid"); + let neutral_probe = neutral.inspector().clone(); + assert!(neutral_outcome.result.is_success(), "{:?}", neutral_outcome.result); + let neutral_held = neutral_probe.held.expect("neutral reached the call"); + let neutral_forwarded = neutral_probe.gas_limit.expect("neutral forwarded"); + assert_eq!(neutral_held - WARM_READ, 1_000); + assert_eq!(neutral_forwarded, eip150(1_000), "EIP-150 forwards 985"); + assert_eq!( + neutral_probe.calls[1].2, neutral_probe.calls[0].2, + "neutral passes the whole reservoir: {:?}", + neutral_probe.calls + ); + + let limits = EvmTxRuntimeLimits::no_limits(); + let (outcome, probe) = + execute_forward_under(world(&code), tx, limits, super::Forward::targeting(EXISTING)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let held = probe.held.expect("satin reached the call"); + let forwarded = probe.gas_limit.expect("satin forwarded"); + assert_eq!(held - WARM_READ, 1_000); + assert_eq!(forwarded, gas_cap(1_000)); + let child = R - R * RESERVOIR_KEPT_PERCENT / 100; + assert_eq!(probe.reservoir_given(CONTRACT), R, "the transaction's own frame takes the whole"); + assert_eq!(probe.reservoir_given(CHILD), child, "the child's share"); + assert_eq!(probe.reservoir, Some(child - child * RESERVOIR_KEPT_PERCENT / 100)); +} + +/// Below the execution cap the reservoir starts at 0. The callee fills a fresh slot, so 97,920 of +/// state gas spills onto its regular gas and, on return, onto the caller. The callee then clears +/// the slot. The refill lands in the callee's reservoir and the returned reservoir unwinds the +/// caller's spill, so the caller's reservoir stays 0. A settlement that left the 97,920 in the +/// reservoir would report at least that much still remaining. +#[test] +fn test_a_returned_reservoir_unwinds_the_callers_spill() { + if !at_spec_prices() || common::state_is_free() { + return; + } + // Calldata byte 0 selects the value stored into slot 1. + let child = BytecodeBuilder::default() + .append(PUSH0) + .append(CALLDATALOAD) + .push_number(248_u8) + .append(SHR) + .push_number(1_u8) + .append(SSTORE) + .stop() + .build(); + let call_one_byte = |code: BytecodeBuilder| { + code.append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append_many([PUSH0, PUSH0]) + .push_address(CHILD) + .append_many([GAS, CALL]) + }; + let parent = call_one_byte( + call_one_byte(BytecodeBuilder::default().mstore(0, [1_u8])).append(POP).mstore(0, [0_u8]), + ) + .stop() + .build(); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let outcome = execute(db, call_tx(10_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(outcome.gas.state, 0, "the clear refilled the fresh-slot charge"); + assert_eq!( + outcome.gas.reservoir_remaining, 0, + "the returned refill unwinds the caller's spill instead of staying in the reservoir" + ); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/keyless.rs b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs new file mode 100644 index 000000000..8459f2cc8 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/keyless.rs @@ -0,0 +1,682 @@ +//! Authorization totals and a keyless creation's forward, from the page. Kind 1 on the +//! authorization list runs under reduced transaction limits. A fatal database error is a +//! block verdict; the injected error here is not fatal, so the test checks that the transaction +//! has no outcome. + +use alloy_primitives::{hex, Address, Bytes, Signature, TxKind, B256, U256}; +use alloy_sol_types::{SolCall, SolError}; +use mega_evm::{ + alloy_consensus::{Signed, TxLegacy}, + system::keyless::{ + decode_error_result, IKeylessDeploy, KeylessDeployError, KEYLESS_DEPLOY_ADDRESS, + }, + test_utils::{ + note_price_guard, BytecodeBuilder, ErrorInjectingDatabase, MemoryDatabase, + SequencerRegistryRoles, + }, + MegaEvm, MegaLimitExceeded, MegaTransaction, +}; +use revm::{ + context::{result::ExecutionResult, transaction::TransactionType}, + context_interface::{ + cfg::GasId, + either::Either, + transaction::{Authorization, RecoveredAuthority, RecoveredAuthorization}, + }, +}; + +use super::{ + at_spec_prices, call_tx, delegatecall, execute, execute_forward, frame_share, + halted_out_of_gas, nonce_of, reservoir_share, reverted_stop, store_n_slots, world, Forward, + ACCOUNT_LEAF_STATE_GAS_M1, BODY_BYTES, CALLER, CHILD, CONTRACT, EXECUTION_CAP, EXISTING, + INDICATOR_STATE_GAS, TX_STATE_GROWTH_LIMIT, +}; +use crate::common::{self, context}; + +/// Above any forward a `keylessDeploy` call here can make. +const LARGE_OVERRIDE: u64 = 10_000_000_000; +/// Signed gas of a creation that only stops. Below what the call has left. +const SIGNED_STOP_GAS: u64 = 1_000_000; +/// Signed gas of a creation that fills hundreds of slots. Below the call's regular gas, above the +/// state gas of 980 slots at the spec's byte price. +const SIGNED_SLOT_GAS: u64 = 150_000_000; +/// The gas price Nick's Method signs. The outer transaction's gas price stays zero. +const SIGNED_GAS_PRICE: u128 = 100_000_000_000; + +/// One authorization the list simulates. +struct Auth { + /// `None` is an unrecoverable signature. + authority: Option
, + chain_id: u64, + nonce: u64, + delegate: Address, +} + +/// A pre-EIP-155 creation, signed with Nick's Method's fixed signature. +struct Deployment { + tx: Bytes, + signer: Address, + address: Address, +} + +impl Deployment { + fn signed(gas_limit: u64, init_code: Bytes) -> Self { + let tx = TxLegacy { + nonce: 0, + gas_price: SIGNED_GAS_PRICE, + gas_limit, + to: TxKind::Create, + value: U256::ZERO, + input: init_code, + chain_id: None, + }; + let word = U256::from_be_bytes(hex!( + "2222222222222222222222222222222222222222222222222222222222222222" + )); + let signed = Signed::new_unchecked(tx, Signature::new(word, word, false), B256::ZERO); + let mut encoded = Vec::new(); + signed.rlp_encode(&mut encoded); + let signer = signed.recover_signer().expect("a Nick's-Method signature recovers"); + Self { tx: encoded.into(), signer, address: signer.create(0) } + } + + fn call_data(&self, gas_limit_override: u64) -> Bytes { + IKeylessDeploy::keylessDeployCall { + keylessDeploymentTransaction: self.tx.clone(), + gasLimitOverride: U256::from(gas_limit_override), + } + .abi_encode() + .into() + } +} + +fn keyless_db() -> MemoryDatabase { + // The relayer is [`CALLER`]. The registry's system address is a different account, so this + // call is not a system-address transaction. + MemoryDatabase::default() + .rex6_predeploys(SequencerRegistryRoles::from(mega_evm::system::MEGA_SYSTEM_ADDRESS)) + .account_balance(CALLER, U256::from(10u128.pow(24))) +} + +fn keyless_tx(data: Bytes, gas_limit: u64) -> MegaTransaction { + common::call_with_data(CALLER, KEYLESS_DEPLOY_ADDRESS, data, gas_limit) +} + +/// Gas above the execution cap that can pay `count` new authorities from the reservoir. +fn gas_above(count: u64) -> Option { + let history = common::history(BODY_BYTES + count.saturating_mul(101)); + let per = common::account_state_gas().saturating_add(indicator_at_schedule()); + let state = count.checked_mul(per)?.checked_add(common::account_state_gas())?; + let Some(gas) = history + .checked_add(state) + .and_then(|gas| gas.checked_add(5_000_000)) + .and_then(|gas| gas.checked_add(EXECUTION_CAP)) + else { + note_price_guard("the authorization list does not fit above the execution cap"); + return None; + }; + Some(gas) +} + +/// Gas below the execution cap. A list of 1,001 authorities cannot pay its state gas from it. +fn gas_below(count: u64) -> Option { + let history = common::history(BODY_BYTES + count.saturating_mul(101)); + let floor = history.saturating_add(21_000).saturating_add(count.saturating_mul(25_000)); + if floor >= EXECUTION_CAP { + note_price_guard("the authorization list's history does not fit below the execution cap"); + return None; + } + Some(EXECUTION_CAP - 1) +} + +/// Gas that covers one authority's intrinsic cost and cannot pay its leaf and indicator. +fn gas_under_one_authority() -> Option { + let floor = common::history(BODY_BYTES + 101).saturating_add(80_000); + let bill = common::account_state_gas().saturating_add(indicator_at_schedule()); + if bill <= floor || floor >= EXECUTION_CAP { + note_price_guard("one authority's state gas fits in the gas under test"); + return None; + } + Some(floor) +} + +fn indicator_at_schedule() -> u64 { + mega_evm::satin_gas_params().get(GasId::tx_eip7702_state_gas_bytecode()) +} + +fn pins_state() -> bool { + at_spec_prices() && !common::state_is_free() +} + +fn authority(n: u16) -> Address { + let mut raw = [0u8; 20]; + raw[0] = 0xa1; + raw[18] = (n >> 8) as u8; + raw[19] = n as u8; + Address::from(raw) +} + +fn auth_tx(gas_limit: u64, value: U256, to: Address, auths: &[Auth]) -> MegaTransaction { + let authorization_list = auths + .iter() + .map(|auth| { + Either::Right(RecoveredAuthorization::new_unchecked( + Authorization { + chain_id: U256::from(auth.chain_id), + address: auth.delegate, + nonce: auth.nonce, + }, + auth.authority.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid), + )) + }) + .collect(); + let mut tx = call_tx(gas_limit); + tx.0.base.tx_type = TransactionType::Eip7702 as u8; + tx.0.base.kind = TxKind::Call(to); + tx.0.base.value = value; + tx.0.base.gas_priority_fee = Some(0); + tx.0.base.authorization_list = authorization_list; + tx +} + +/// Code that returns what one `BALANCE` of `address` cost: `GAS`, `PUSH20`, `BALANCE`, `POP`, +/// `GAS`, and the difference, which is the access plus 7. +fn balance_cost(address: Address) -> Bytes { + use revm::bytecode::opcode::{BALANCE, GAS, POP, SUB, SWAP1}; + BytecodeBuilder::default() + .append(GAS) + .push_address(address) + .append_many([BALANCE, POP, GAS, SWAP1, SUB]) + .return_top() + .build() +} + +/// The cost of the `BALANCE` [`balance_cost`] measured. +fn access_cost(outcome: &mega_evm::MegaTransactionOutcome) -> u64 { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the measuring call did not succeed: {:?}", outcome.result); + }; + U256::from_be_slice(output.data()).to::() - 7 +} + +fn new_auth(n: u16, nonce: u64) -> Auth { + Auth { authority: Some(authority(n)), chain_id: 0, nonce, delegate: CHILD } +} + +fn many(count: u16) -> Vec { + (1..=count).map(|n| new_auth(n, 0)).collect() +} + +fn keyless_failure(outcome: &mega_evm::MegaTransactionOutcome) -> KeylessDeployError { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("the keyless call did not succeed: {:?}", outcome.result); + }; + let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy return"); + decode_error_result(&ret.errorData).expect("errorData is a keyless error") +} + +/// The creation's state-gas and history charges the call makes before it forwards the reservoir: +/// the signer's leaf, the deploy address's leaf, and one record for each. +fn start_charges() -> u64 { + 2 * common::account_state_gas() + 2 * common::history(super::WRITE_RECORD_SIZE) +} + +/// 1,001 distinct new authorities, below the execution cap. Apply none. The transaction's own +/// frame stops before it runs, kind 3, `limit` 1,000. No authority is created. +#[test] +fn test_an_authorization_list_of_1001_new_authorities_stops_before_the_first_frame() { + let Some(gas) = gas_below(1_001) else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "no authority account is kept"); + assert_eq!(nonce_of(&outcome, CALLER), 1, "the sender's nonce stands"); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "no authority state gas is charged"); + } +} + +/// 1,000 new authorities fit and are applied. The transaction's value would create one more +/// account. That recipient stops the first frame, kind 3, `limit` 0, and is not kept. The +/// authorities stay. +#[test] +fn test_a_fitting_list_keeps_the_authorities_when_the_recipient_stops() { + let Some(gas) = gas_above(1_000) else { return }; + let recipient = Address::from_word(B256::repeat_byte(0x27)); + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::from(1), recipient, &many(1_000))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 0 }); + assert_eq!(super::balance_of(&outcome, recipient), U256::ZERO, "the recipient is not kept"); + assert_eq!(nonce_of(&outcome, authority(1)), 1, "an applied authority stays"); + assert_eq!(nonce_of(&outcome, authority(1_000)), 1); +} + +/// Signer absent, deploy address empty, a creation that deploys one byte. The call is the top +/// frame. The creation's regular gas is `min(gasLimitOverride, remaining)`, which at this gas +/// limit is above the 98/100 cap of the execution cap. After the call's start charges, the two +/// leaves and the two records, the creation receives the reservoir share. Its state-growth budget +/// is the share of the call's whole 1,000, `floor(1,000 × 98 / 100)` = 980, the signer's rise +/// being counted on the call once the creation returned, and the empty deploy address is +1 +/// against it: 980 fresh slots take it to 981 and stop it at 980. +#[test] +fn test_a_keyless_creation_receives_the_reservoir_share_and_a_980_budget() { + let one_byte = BytecodeBuilder::default().return_with_data([0x00]).build(); + let deployment = Deployment::signed(SIGNED_STOP_GAS, one_byte); + let data = deployment.call_data(LARGE_OVERRIDE); + let reservoir_after_body = 50 * super::SLOT_STATE_GAS_M1; + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + reservoir_after_body; + let (outcome, probe) = execute_forward(keyless_db(), keyless_tx(data, gas), Forward::any()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(super::has_code(&outcome, deployment.address), "the creation succeeds"); + let (forwarded, reservoir) = probe.created.expect("the creation started"); + assert!( + forwarded > super::gas_cap(EXECUTION_CAP), + "regular gas {forwarded} is min(override, remaining), above the 98/100 cap {}", + super::gas_cap(EXECUTION_CAP) + ); + let charges = start_charges(); + assert!(reservoir_after_body > charges, "the reservoir covers the start charges"); + let remainder = reservoir_after_body - charges; + assert_eq!( + reservoir, + reservoir_share(remainder), + "creation reservoir {reservoir}; remainder after the start charges {remainder}; share {}", + reservoir_share(remainder) + ); + + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let filling = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let data = filling.call_data(LARGE_OVERRIDE); + let state = 980 * common::slot_state_gas() + 2 * common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(keyless_db(), keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the creation's revert is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(1_000) }); + assert_eq!(nonce_of(&outcome, filling.signer), 1, "the signer's bump stands"); + assert!(!super::has_code(&outcome, filling.address)); +} + +/// The clauses EIP-7702 already decides come first: one rise, one record and one indicator for two +/// acceptances of one new authority; nothing loaded or counted for a wrong chain id, a nonce of +/// 2^64 − 1 or an unrecoverable signature, and no warm access for the first; a zero delegation +/// target that creates its authority without an indicator; an authorization signed for the +/// sender's pre-transaction nonce, skipped; no rise for an existing authority; no indicator for one +/// that holds one at the start, a clear and a later non-zero authorization included; one indicator +/// for a clear and a later non-zero authorization of an authority that holds none; a database +/// error on a consulted authority, after an overflowing prefix too, gives no outcome. Then the +/// 999 / 1,000 / 1,001 boundaries of the state-growth stop. +/// +/// Where the list would cross both KV and state growth, the kind is 1. Whether a database error is +/// fatal is the node's database's to say, a block verdict this EVM call does not report; the +/// witness of every loaded authority is the block witness harness's, not this outcome's. +#[test] +fn test_authorization_list_boundaries() { + let stop_code = Bytes::from_static(&[0x00]); + let db = world(&[(CONTRACT, stop_code.clone())]); + let Some(gas) = gas_above(2) else { return }; + + // Two acceptances of one new authority: one rise, one record, one indicator. + let twice = [new_auth(1, 0), new_auth(1, 1)]; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &twice)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(1)), 2); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } + + // Wrong chain id, nonce 2^64 − 1, unrecoverable signature: not loaded, not created. + for auth in [ + Auth { authority: Some(authority(2)), chain_id: 7, nonce: 0, delegate: CHILD }, + Auth { authority: Some(authority(3)), chain_id: 0, nonce: u64::MAX, delegate: CHILD }, + Auth { authority: None, chain_id: 0, nonce: 0, delegate: CHILD }, + ] { + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[auth])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + } + assert_eq!( + nonce_of( + &execute( + db.clone(), + auth_tx( + gas, + U256::ZERO, + CONTRACT, + &[Auth { + authority: Some(authority(2)), + chain_id: 7, + nonce: 0, + delegate: CHILD + },] + ) + ), + authority(2) + ), + 0 + ); + + // A zero delegation target creates the account and charges no indicator. + let zero = + Auth { authority: Some(authority(4)), chain_id: 0, nonce: 0, delegate: Address::ZERO }; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[zero])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(4)), 1); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1); + } + + // Signed for the sender's pre-transaction nonce: skipped, and the sender adds no record. + let sender = Auth { authority: Some(CALLER), chain_id: 0, nonce: 0, delegate: CHILD }; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[sender])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + + // An existing authority adds no state growth. The indicator is charged once. + let mut existing = db.clone(); + existing.set_account_balance(authority(5), U256::from(1)); + let outcome = execute(existing, auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(5, 0)])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, INDICATOR_STATE_GAS); + } + + // An authority that already holds an indicator is charged none, a clear and a later + // non-zero authorization included. + let mut delegated = crate::detention::with_delegation(db.clone(), authority(6), CHILD); + delegated.set_account_nonce(authority(6), 1); + delegated.set_account_balance(authority(6), U256::from(1)); + let outcome = execute(delegated.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(6, 1)])); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } + let clear_and_set = [ + Auth { authority: Some(authority(6)), chain_id: 0, nonce: 1, delegate: Address::ZERO }, + new_auth(6, 2), + ]; + let outcome = execute(delegated, auth_tx(gas, U256::ZERO, CONTRACT, &clear_and_set)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(6)), 3); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "an indicator held at the start is never charged"); + } + + // An entry skipped for its chain id is not loaded, so it is not warmed. + let measuring = world(&[(CONTRACT, balance_cost(authority(2)))]); + let wrong_chain = + Auth { authority: Some(authority(2)), chain_id: 7, nonce: 0, delegate: CHILD }; + let outcome = execute(measuring, auth_tx(gas, U256::ZERO, CONTRACT, &[wrong_chain])); + assert!(access_cost(&outcome) > super::WARM_READ, "the skipped authority is cold"); + + // A clear of an authority that holds none, then the first non-zero designator: one indicator. + let clear_then = [ + Auth { authority: Some(authority(7)), chain_id: 0, nonce: 0, delegate: Address::ZERO }, + new_auth(7, 1), + ]; + let outcome = execute(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &clear_then)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, authority(7)), 2); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } + + // A database error on a consulted authority gives the transaction no outcome. + let mut failing = ErrorInjectingDatabase::new(db.clone()); + failing.fail_on_account = Some(authority(8)); + let err = MegaEvm::new(context(failing)).execute_transaction(auth_tx( + gas, + U256::ZERO, + CONTRACT, + &[new_auth(8, 0)], + )); + assert!(err.is_err(), "a database error is not a limit stop: {err:?}"); + + // Both totals crossed: the kind is 1 and `limit` the KV transaction limit. + { + let limits = mega_evm::EvmTxRuntimeLimits::default() + .with_tx_kv_update_limit(3) + .with_tx_state_growth_limit(3); + let outcome = + super::execute_under(db.clone(), auth_tx(gas, U256::ZERO, CONTRACT, &many(4)), limits); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 3 }); + assert_eq!(nonce_of(&outcome, authority(1)), 0); + } + + // The same, after a prefix of 1,001 new authorities that would already cross the limit. + if let Some(gas) = gas_above(1_002) { + let mut failing = ErrorInjectingDatabase::new(db); + failing.fail_on_account = Some(authority(1_002)); + let mut list = many(1_001); + list.push(new_auth(1_002, 0)); + let err = MegaEvm::new(context(failing)).execute_transaction(auth_tx( + gas, + U256::ZERO, + CONTRACT, + &list, + )); + assert!(err.is_err(), "an overflowing prefix does not hide the fault: {err:?}"); + } + + // 999 applied: the first frame's budget is 1. The second fresh slot stops it, `limit` 1. + let Some(gas) = gas_above(999) else { return }; + let db = world(&[(CONTRACT, store_n_slots(2))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(999))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 1 }); + assert!(super::slot_value(&outcome, CONTRACT, 1).is_zero()); + + // 1,000 applied: the budget is 0. One slot stops it, `limit` 0. The authorities stay. + let Some(gas) = gas_above(1_000) else { return }; + let db = world(&[(CONTRACT, store_n_slots(1))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_000))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: 0 }); + assert_eq!(nonce_of(&outcome, authority(1)), 1); + + // 1,001 skip the list. Above the cap, so a success here is the missing stop. + let Some(gas) = gas_above(1_001) else { return }; + let db = world(&[(CONTRACT, stop_code)]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert_eq!(nonce_of(&outcome, authority(1)), 0); + assert_eq!(outcome.usage.write_records, 0); +} + +/// Signer nonce 0, signer absent. With the deploy address's +1, the init code's 980th fresh slot +/// crosses the creation's budget of 980, the share of the call's 1,000; the signer's rise is the +/// call's, counted once the creation returned. The call answers `ExecutionReverted` with that stop. +/// The deploy account and its record are taken back. The signer's bump stands, and its record with +/// it, while the account still differs. +#[test] +fn test_a_keyless_creation_from_nonce_0_stopped_in_its_initcode() { + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let deployment = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let state = 980 * common::slot_state_gas() + 2 * common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(keyless_db(), keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the revert data is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(1_000) }); + assert_eq!(nonce_of(&outcome, deployment.signer), 1); + assert!(!super::has_code(&outcome, deployment.address)); + assert!(outcome.limit_exceeded.is_none(), "the call caught the creation's stop"); + // The signer's record stands, the deploy address's goes with the creation. + assert_eq!(outcome.usage.write_records, 1); + assert_eq!(outcome.usage.data_size, BODY_BYTES + data_len + super::WRITE_RECORD_SIZE); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the signer's leaf"); + } +} + +/// The same creation from signer nonce 1. The bump does not create the signer, so the creation's +/// budget is `floor(1,000 × 98 / 100)` = 980, and the deploy address's rise is inside it. 980 +/// fresh slots cross that budget. The bump is the last nonce change the deployment made and is +/// taken back, with its record and that record's history. +#[test] +fn test_a_keyless_creation_from_nonce_1_takes_the_bump_back() { + if 980 * common::slot_state_gas() > SIGNED_SLOT_GAS { + note_price_guard("980 slots of state gas do not fit the keyless forward"); + return; + } + let deployment = Deployment::signed(SIGNED_SLOT_GAS, store_n_slots(980)); + let mut db = keyless_db(); + db.set_account_nonce(deployment.signer, 1); + db.set_account_balance(deployment.signer, U256::from(1)); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let state = 980 * common::slot_state_gas() + common::account_state_gas(); + let gas = EXECUTION_CAP + common::body_history(data.len() as u64) + state + 5_000_000; + let outcome = execute(db, keyless_tx(data, gas)); + let KeylessDeployError::ExecutionReverted { output, .. } = keyless_failure(&outcome) else { + panic!("the creation did not revert: {:?}", outcome.result); + }; + let stop = MegaLimitExceeded::abi_decode(&output).expect("the revert data is a stop"); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: frame_share(TX_STATE_GROWTH_LIMIT) }); + assert_eq!(nonce_of(&outcome, deployment.signer), 1, "the bump is taken back"); + assert!(!super::has_code(&outcome, deployment.address)); + // The signer is again as the transaction loaded it: its record and the record's history go. + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, BODY_BYTES + data_len); + assert_eq!(outcome.gas.history, common::body_history(data_len)); + if pins_state() { + assert_eq!(outcome.gas.state, 0, "the deploy address's leaf goes with the creation"); + } +} + +/// The constructor `DELEGATECALL`s a library that self-destructs the account, then returns one +/// byte of runtime. The creation's EVM result succeeds, and the call answers `EmptyCodeDeployed` +/// with the zero address. The destruction gives the deploy address's leaf and its record back to +/// the destroying frame, inside the creation, so what the creation spent from both pools net of +/// that give-back is below its regular gas, and `gasUsed` is the regular gas it spent. The code is +/// deposited after the mark: no state gas, and its data size and history stay charged. The +/// account is removed at the end of the transaction. +#[test] +fn test_a_keyless_constructor_that_self_destructs_answers_empty_code() { + if !pins_state() { + return; + } + let library = BytecodeBuilder::default().selfdestruct(EXISTING).build(); + let mut prefix = delegatecall(CHILD).append(revm::bytecode::opcode::POP).build().to_vec(); + prefix.extend_from_slice(&BytecodeBuilder::default().return_with_data([0x00]).build()); + let deployment = Deployment::signed(SIGNED_STOP_GAS, Bytes::from(prefix)); + let mut db = keyless_db(); + db.set_account_code(CHILD, library); + db.set_account_balance(EXISTING, U256::from(1)); + db.set_account_code(EXISTING, Bytes::from_static(&[0x00])); + let data = deployment.call_data(LARGE_OVERRIDE); + let data_len = data.len() as u64; + let gas = EXECUTION_CAP + + common::body_history(data.len() as u64) + + 2 * common::account_state_gas() + + 5_000_000; + let (outcome, probe) = execute_forward(db, keyless_tx(data, gas), Forward::any()); + let KeylessDeployError::EmptyCodeDeployed { gas_used } = keyless_failure(&outcome) else { + panic!("expected EmptyCodeDeployed: {:?}", outcome.result); + }; + let (forwarded, _) = probe.created.expect("the creation started"); + let left = probe.create_end_remaining.expect("the creation ended"); + assert_eq!(gas_used, forwarded - left, "gasUsed is the creation's regular gas"); + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, "only the signer's leaf stands"); + // The signer's record and the deposited byte stay; the deploy address's record goes. + assert_eq!( + outcome.gas.history, + (BODY_BYTES + data_len + super::WRITE_RECORD_SIZE + 1) * super::HISTORY_GAS_PER_BYTE + ); + assert!(super::is_destroyed(&outcome, deployment.address)); +} + +/// The list fits. The authority's state gas cannot be paid. Out of gas, and the authorization is +/// taken back. This is not the limit stop. +#[test] +fn test_an_authority_whose_state_gas_cannot_be_paid_is_taken_back() { + let Some(gas) = gas_under_one_authority() else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &[new_auth(1, 0)])); + assert!(halted_out_of_gas(&outcome), "out of gas, not a limit stop: {:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none()); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "the authorization is taken back"); + assert_eq!(outcome.usage.write_records, 0); +} + +/// The list does not fit, and the state gas it would have charged also cannot be paid. The list is +/// skipped and the first frame stops with the limit. The out-of-gas path is not taken. +#[test] +fn test_a_list_that_does_not_fit_is_not_the_out_of_gas_path() { + let Some(gas) = gas_below(1_001) else { return }; + let db = world(&[(CONTRACT, Bytes::from_static(&[0x00]))]); + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &many(1_001))); + assert!(!halted_out_of_gas(&outcome), "the out-of-gas path is not taken: {:?}", outcome.result); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } +} + +/// The list fits. One authority holds code that is not a delegation. The entry is skipped and its +/// nonce is not bumped; a later entry for it is compared with that unbumped nonce. The authority +/// was loaded before the code check, so it is warm. +#[test] +fn test_an_authority_with_non_delegation_code_is_skipped() { + let Some(gas) = gas_above(1) else { return }; + let mut db = world(&[(CONTRACT, balance_cost(authority(1)))]); + db.set_account_code(authority(1), Bytes::from_static(&[0x00])); + db.set_account_balance(authority(1), U256::from(1)); + let auths = [new_auth(1, 0), new_auth(1, 0)]; + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &auths)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(access_cost(&outcome), super::WARM_READ, "the authority is warm"); + assert_eq!(nonce_of(&outcome, authority(1)), 0, "the simulated nonce is not bumped"); + assert_eq!(outcome.usage.write_records, 0); + if pins_state() { + assert_eq!(outcome.gas.state, 0); + } +} + +/// Two entries for one new authority, both signed for nonce 0. The first is accepted, the +/// simulated nonce becomes 1, and the authority is created once, with one record and one +/// indicator. The second does not match that nonce and is skipped. The authority is warm. +#[test] +fn test_two_entries_for_one_new_authority_accept_the_first() { + let Some(gas) = gas_above(1) else { return }; + let db = world(&[(CONTRACT, balance_cost(authority(1)))]); + let auths = [new_auth(1, 0), new_auth(1, 0)]; + let outcome = execute(db, auth_tx(gas, U256::ZERO, CONTRACT, &auths)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(access_cost(&outcome), super::WARM_READ, "the authority is warm"); + assert_eq!(nonce_of(&outcome, authority(1)), 1); + assert_eq!(outcome.usage.write_records, 1); + if pins_state() { + assert_eq!(outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1 + INDICATOR_STATE_GAS); + } +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/limits.rs b/crates/mega-evm/tests/satin/limit_matrix/limits.rs new file mode 100644 index 000000000..d9d4a5a3f --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/limits.rs @@ -0,0 +1,418 @@ +//! Frame budgets and the transaction limits. +//! +//! Expected stops use the page's kind and `limit`. Gas room follows the schedule at the prices +//! in effect, so a measurement build can still reach the stop. + +use alloy_primitives::{keccak256, Bytes, B256, U256}; +use alloy_sol_types::SolCall; +use mega_evm::{ + system::{IOracle, ORACLE_CONTRACT_ADDRESS}, + test_utils::BytecodeBuilder, + EvmTxRuntimeLimits, MegaLimitExceeded, +}; +use revm::bytecode::opcode::{CALL, GAS, LOG0, POP, PUSH0}; + +use super::{ + balance_of, call_tx, delegatecall, execute, execute_under, forward_to, frame_share, + gas_for_slots, keep_returndata, nonce_of, return_kept, returned_stop, returned_stops, + reverted_stop, slot_value, slots_gas, store_n_prefix, store_n_prefix_at, store_n_slots, world, + BENEFICIARY, BODY_BYTES, CHILD, CONTRACT, GRAND, NEXT, TRANSFER_LOG_SIZE, TX_DATA_LIMIT, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, WRITE_RECORD_SIZE, +}; + +fn join(prefix: Vec, rest: BytecodeBuilder) -> Bytes { + let mut code = prefix; + code.extend_from_slice(&rest.build()); + Bytes::from(code) +} + +/// The transaction's own frame has a state-growth budget of 1,000. The 1,001st fresh slot stops +/// that frame, kind 3, `limit` 1,000. The slot is not kept. The receipt fails and the transaction +/// is included. +#[test] +fn test_the_1001st_fresh_slot_stops_the_transaction() { + let Some(gas) = slots_gas(1_001) else { return }; + let db = world(&[(CONTRACT, store_n_slots(1_001))]); + let outcome = execute(db, call_tx(gas)); + let stop = reverted_stop(&outcome); + assert_eq!(stop, MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT }); + assert!(outcome.limit_exceeded.is_some(), "the transaction's own frame stopped"); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 1_001), U256::ZERO); +} + +/// The caller has kept 20 of a 1,000 budget. The child budget is `floor(980 × 98 / 100)` = 960. +/// Those 960 slots succeed. The caller net becomes 980 and its remaining becomes 20, so a later +/// child receives `floor(20 × 98 / 100)` = 19. +#[test] +fn test_a_child_budget_of_960_then_a_later_child_of_19() { + let Some(gas) = slots_gas(1_000) else { return }; + let parent = join( + store_n_prefix(20, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .call(NEXT, U256::ZERO) + .return_returndata(), + ); + let db = world(&[(CONTRACT, parent), (CHILD, store_n_slots(960)), (NEXT, store_n_slots(20))]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the later child's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 19 }); + assert_eq!(slot_value(&outcome, CONTRACT, 20), U256::from(1)); + assert_eq!(slot_value(&outcome, CHILD, 960), U256::from(1)); + assert_eq!( + slot_value(&outcome, NEXT, 1), + U256::ZERO, + "the later child's 20 slots are discarded" + ); +} + +/// The same caller. The child's 961st slot stops the child, kind 3, `limit` 960. The child's net +/// is discarded, so the caller net stays 20 and its remaining stays 980: a later child receives +/// `floor(980 × 98 / 100)` = 960 again, and its own 961st slot stops it at 960. +#[test] +fn test_a_childs_961st_slot_stops_at_960() { + let Some(gas) = slots_gas(2_000) else { return }; + let rest = BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP); + let rest = keep_returndata(rest, 0x100).call(NEXT, U256::ZERO).append(POP); + let parent = join(store_n_prefix(20, 1, false), return_kept(keep_returndata(rest, 0x180))); + let db = world(&[(CONTRACT, parent), (CHILD, store_n_slots(961)), (NEXT, store_n_slots(961))]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (child, next) = returned_stops(&outcome); + assert_eq!(child, MegaLimitExceeded { kind: 3, limit: 960 }); + assert_eq!(next, MegaLimitExceeded { kind: 3, limit: 960 }, "the caller still had 980 left"); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the child's net is discarded"); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 20), U256::from(1)); +} + +/// Transaction KV limit 10, caller has used 2. The child budget is `floor(8 × 98 / 100)` = 7. +/// The 8th new record stops the child, kind 1, `limit` 7. On that stop the caller still has 8 +/// left, and its own 8 further records fit. At the protocol value 500,000 this shape hits data +/// size first ([`test_kv_weighs_more_than_the_data_size_cap`]). +#[test] +fn test_a_child_kv_budget_of_7_stops_the_eighth_record() { + assert_eq!(frame_share(8), 7); + let Some(gas) = slots_gas(20) else { return }; + let mut parent = store_n_prefix(2, 1, false); + parent + .extend_from_slice(&BytecodeBuilder::default().call(CHILD, U256::ZERO).append(POP).build()); + // Slots 10 down to 1: slots 1 and 2 are already set, so this adds 8 records. + parent.extend_from_slice(&store_n_prefix_at(parent.len(), 10, 1, false)); + // A store leaves the return data alone: the parent returns the child's stop. + parent.extend_from_slice(&BytecodeBuilder::default().return_returndata().build()); + let db = world(&[(CONTRACT, Bytes::from(parent)), (CHILD, store_n_slots(8))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 7 }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + assert_eq!(slot_value(&outcome, CONTRACT, 10), U256::from(1), "the caller had 8 left"); + assert_eq!(outcome.usage.write_records, 10); +} + +/// Not a protocol-gas execution. 500,000 records weigh 20,000,000 bytes, above `TX_DATA_LIMIT` +/// 13,107,200. After a 310-byte body the top frame's data-size budget is 13,106,890. 327,672 +/// records fit. A 327,673rd record would cross that frame budget, kind 0, `limit` 13,106,890. +/// The KV check itself is pinned under reduced KV limits +/// ([`test_a_child_kv_budget_of_7_stops_the_eighth_record`], +/// [`test_the_transactions_own_frame_stops_at_a_reduced_kv_limit`]). +#[test] +fn test_kv_weighs_more_than_the_data_size_cap() { + let weight = TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE; + assert_eq!(weight, 20_000_000); + assert!(weight > TX_DATA_LIMIT); + let budget = TX_DATA_LIMIT - BODY_BYTES; + assert_eq!(budget, 13_106_890); + assert_eq!(327_672 * WRITE_RECORD_SIZE, 13_106_880); + assert!(327_672 * WRITE_RECORD_SIZE <= budget); + assert_eq!(327_673 * WRITE_RECORD_SIZE, 13_106_920); + assert!(327_673 * WRITE_RECORD_SIZE > budget); + let _ = MegaLimitExceeded { kind: 0, limit: budget }; +} + +/// A reduced KV transaction limit of 10, with nothing counted before the frame, so the +/// transaction's own frame has a KV budget of 10. Its 11th record stops it, kind 1, `limit` 10. +/// The data size does not bind. +#[test] +fn test_the_transactions_own_frame_stops_at_a_reduced_kv_limit() { + let Some(gas) = slots_gas(11) else { return }; + let db = world(&[(CONTRACT, store_n_slots(11))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, call_tx(gas), limits); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 10 }); + assert!(outcome.limit_exceeded.is_some()); + assert_eq!(slot_value(&outcome, CONTRACT, 11), U256::ZERO); +} + +/// One fresh `SSTORE` whose record crosses the data-size frame budget and the state-growth frame +/// budget names data size, kind 0, and `limit` is the data-size frame budget. +/// +/// A transaction data-size limit of the body plus 40,000 gives the top frame 40,000 bytes and a +/// child `floor(40,000 × 98 / 100)` = 39,200, 980 records. The child's state-growth budget is 980 +/// too. Its 981st slot crosses both, and not the transaction limit. When the top frame itself +/// makes the 1,001st record, that record crosses the data-size frame budget, 40,000, the +/// data-size transaction limit and the state-growth budget, 1,000, and the stop still names the +/// frame budget, 40,000. +#[test] +fn test_a_record_that_crosses_data_size_and_state_growth_names_data_size() { + let Some(gas) = slots_gas(1_001) else { return }; + let budget = frame_share(40_000); + assert_eq!(budget, 39_200); + assert!(981 * WRITE_RECORD_SIZE > budget); + assert!(980 * WRITE_RECORD_SIZE <= budget); + assert_eq!(frame_share(TX_STATE_GROWTH_LIMIT), 980); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(BODY_BYTES + 40_000); + let db = world(&[(CONTRACT, forward_to(CHILD)), (CHILD, store_n_slots(981))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the child's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: budget }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + + let db = world(&[(CONTRACT, store_n_slots(1_001))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert_eq!( + reverted_stop(&outcome), + MegaLimitExceeded { kind: 0, limit: 40_000 }, + "the frame budget, not the transaction limit {}", + BODY_BYTES + 40_000 + ); +} + +/// State growth at depth 2 and 3, top remaining 1,000. Child 980, grandchild 960, the next frame +/// `floor(960 × 98 / 100)` = 940. The 941st slot there stops that frame, kind 3, `limit` 940. +#[test] +fn test_state_growth_at_depth_2_and_3_stops_at_940() { + let Some(gas) = slots_gas(941) else { return }; + assert_eq!(frame_share(1_000), 980); + assert_eq!(frame_share(980), 960); + assert_eq!(frame_share(960), 940); + let db = world(&[ + (CONTRACT, forward_to(CHILD)), + (CHILD, forward_to(GRAND)), + (GRAND, forward_to(NEXT)), + (NEXT, store_n_slots(941)), + ]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 940 }); + assert_eq!(slot_value(&outcome, NEXT, 1), U256::ZERO); +} + +/// Parent budget 1,000, net 100. The child, a `DELEGATECALL` in the parent's storage, clears +/// those 100: its net is −100 and its remaining stays 882, so the frame it starts receives 864, +/// and that frame's 865th slot stops it at 864. When the child succeeds, the parent's net is 0 +/// and its remaining is 1,000 again, so a later child receives 980. When the child reverts, the +/// parent's net stays 100 and its remaining 900, so a later child receives 882. +#[test] +fn test_a_cleared_net_does_not_raise_the_childs_remaining() { + let Some(gas) = slots_gas(2_000) else { return }; + assert_eq!(frame_share(900), 882); + assert_eq!(frame_share(882), 864); + let parent = { + let rest = keep_returndata(delegatecall(CHILD).append(POP), 0x100); + let rest = keep_returndata(rest.call(NEXT, U256::ZERO).append(POP), 0x180); + join(store_n_prefix(100, 1, false), return_kept(rest)) + }; + for (kept, next) in [(true, 980), (false, 882)] { + let tail = BytecodeBuilder::default().call(GRAND, U256::ZERO); + let tail = if kept { tail.return_returndata() } else { tail.revert_with_returndata() }; + let child = join(store_n_prefix(100, 0, false), tail); + let db = world(&[ + (CONTRACT, parent.clone()), + (CHILD, child), + (GRAND, store_n_slots(865)), + (NEXT, store_n_slots(TX_STATE_GROWTH_LIMIT as u16)), + ]); + let outcome = execute(db, call_tx(gas)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let (grand, later) = returned_stops(&outcome); + assert_eq!(grand, MegaLimitExceeded { kind: 3, limit: 864 }, "kept {kept}"); + assert_eq!(later, MegaLimitExceeded { kind: 3, limit: next }, "kept {kept}"); + assert_eq!(slot_value(&outcome, GRAND, 1), U256::ZERO); + let slot = if kept { U256::ZERO } else { U256::from(1) }; + assert_eq!(slot_value(&outcome, CONTRACT, 1), slot, "kept {kept}"); + } +} + +/// Plants `sendHint`'s selector at memory 0 and calls the Oracle with `len` bytes of calldata. +fn hint_call(len: u32) -> BytecodeBuilder { + BytecodeBuilder::default() + .mstore(0, IOracle::sendHintCall::SELECTOR) + .append_many([ + PUSH0, // retSize + PUSH0, // retOffset + ]) + .push_number(len) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL]) +} + +/// Body 310 plus twelve admitted hints of 1,048,576 bytes is 12,583,222. A child `LOG0` of +/// 524,288 data bytes is 524,320 bytes and crosses the transaction limit. The child's frame +/// budget is not crossed. Kind 0, `limit` 13,107,200. The hints stay counted. The log does not. +#[test] +fn test_hints_then_a_child_log_names_the_transaction_data_limit() { + const HINT: u32 = 1_048_576; + const LOG_DATA: u64 = 524_288; + const BEFORE: u64 = BODY_BYTES + 12 * HINT as u64; + assert_eq!(BEFORE, 12_583_222); + assert_eq!(32 + LOG_DATA, 524_320); + const { assert!(BEFORE + 32 + LOG_DATA > TX_DATA_LIMIT) }; + let mut code = Vec::new(); + for _ in 0..12 { + code.extend_from_slice(&hint_call(HINT).build()); + code.push(POP); + } + code.extend_from_slice( + &BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata().build(), + ); + let child = BytecodeBuilder::default() + .push_number(LOG_DATA as u32) + .append_many([PUSH0, LOG0]) + .stop() + .build(); + let db = world(&[ + (CONTRACT, Bytes::from(code)), + (CHILD, child), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(40_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the caller caught the log's stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: TX_DATA_LIMIT }); + assert_eq!(outcome.usage.data_size, BEFORE); +} + +/// The same log in the transaction's own frame stops that frame, kind 0, `limit` 13,107,200. +/// Failed receipt, included. The admitted hint bytes stay counted. +#[test] +fn test_hints_then_a_top_frame_log_stops_the_transaction() { + const HINT: u32 = 1_048_576; + const LOG_DATA: u64 = 524_288; + const BEFORE: u64 = BODY_BYTES + 12 * HINT as u64; + let mut code = Vec::new(); + for _ in 0..12 { + code.extend_from_slice(&hint_call(HINT).build()); + code.push(POP); + } + code.extend_from_slice( + &BytecodeBuilder::default().push_number(LOG_DATA as u32).append_many([PUSH0, LOG0]).build(), + ); + let db = world(&[ + (CONTRACT, Bytes::from(code)), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(40_000_000)); + assert_eq!(reverted_stop(&outcome), MegaLimitExceeded { kind: 0, limit: TX_DATA_LIMIT }); + assert!(outcome.limit_exceeded.is_some(), "the transaction's own frame stopped"); + assert_eq!(outcome.usage.data_size, BEFORE); +} + +/// One admitted hint whose calldata is exactly 100 bytes: the selector and 96 zero bytes. +fn hint_100() -> BytecodeBuilder { + hint_call(100) +} + +/// Body 310, one admitted hint of 100 bytes, a top-frame record of 40, and a successful child +/// whose net is −40. The transaction's net is 410. The same child reverting keeps the 40, so the +/// net is 450. +#[test] +fn test_a_successful_childs_negative_net_leaves_the_transaction_at_410() { + let success_child = join(store_n_prefix(1, 0, false), BytecodeBuilder::default().stop()); + let db = world(&[ + (CONTRACT, hint_and_store()), + (CHILD, success_child), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(5_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 100); + + let failing = join(store_n_prefix(1, 0, false), BytecodeBuilder::default().revert()); + let db = world(&[ + (CONTRACT, hint_and_store()), + (CHILD, failing), + (ORACLE_CONTRACT_ADDRESS, Bytes::from_static(&[0x00])), + ]); + let outcome = execute(db, call_tx(5_000_000)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 100 + WRITE_RECORD_SIZE); +} + +fn hint_and_store() -> Bytes { + let mut code = hint_100().append(POP).sstore(U256::from(1), U256::from(1)).build().to_vec(); + code.extend_from_slice(&delegatecall(CHILD).stop().build()); + Bytes::from(code) +} + +/// A transaction data-size limit of the body plus 81 gives the top frame 81 bytes. The parent +/// writes one 40-byte record, so 41 remain and the child receives 40. The child returns that record +/// and its remaining stays 40. The frame it starts receives `floor(40 × 98 / 100)` = 39, and one +/// 40-byte record there stops it, kind 0, `limit` 39. +#[test] +fn test_a_negative_data_size_net_does_not_raise_what_a_frame_forwards() { + assert_eq!(frame_share(41), 40); + assert_eq!(frame_share(40), 39); + let child = join( + store_n_prefix(1, 0, false), + BytecodeBuilder::default().call(GRAND, U256::ZERO).return_returndata(), + ); + let parent = join( + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)).build().to_vec(), + delegatecall(CHILD).return_returndata(), + ); + let db = world(&[ + (CONTRACT, parent), + (CHILD, child), + (GRAND, BytecodeBuilder::default().sstore(U256::from(2), U256::from(1)).stop().build()), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_data_size_limit(BODY_BYTES + 81); + let outcome = execute_under(db, call_tx(5_000_000), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); +} + +/// A pre-funded address, balance, nonce 0, no code, is created onto and destroyed. The leaf was +/// present. No refill and no fall, and the net stays 0. 1,000 further slot rises fit. The 1,001st +/// stops the frame, kind 3, `limit` 1,000. +#[test] +fn test_a_prefunded_creation_keeps_a_zero_net_until_the_1001st_slot() { + let init = BytecodeBuilder::default().selfdestruct(BENEFICIARY).build(); + let created = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let only = + BytecodeBuilder::default().create2(U256::ZERO, init.clone(), U256::ZERO).stop().build(); + let mut db = world(&[(CONTRACT, only), (BENEFICIARY, Bytes::from_static(&[0x00]))]); + db = db.account_balance(created, U256::from(1)); + let Some(gas) = gas_for_slots(1) else { return }; + let settled = execute(db, call_tx(gas)); + assert!(settled.result.is_success(), "{:?}", settled.result); + assert_eq!(settled.gas.state, 0, "a present leaf is not charged and not refilled"); + assert!(nonce_of(&settled, CONTRACT) >= 1, "the creator nonce bump stands"); + // The creator's nonce, the created account's nonce, and the beneficiary's balance: the + // created account's record stands. One transfer log for the balance the destruction moved. + assert_eq!(settled.usage.write_records, 3, "the nonce bump's record stands"); + assert_eq!(settled.usage.data_size, BODY_BYTES + 3 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + assert_eq!(balance_of(&settled, created), U256::ZERO); + + // The loop's jumps are absolute. It has to start at its own pc, after the `CREATE2`. + let prefix = + BytecodeBuilder::default().create2(U256::ZERO, init, U256::ZERO).append(POP).build(); + let mut code = prefix.to_vec(); + code.extend_from_slice(&store_n_prefix_at(prefix.len(), 1_001, 1, true)); + let mut db = + world(&[(CONTRACT, Bytes::from(code)), (BENEFICIARY, Bytes::from_static(&[0x00]))]); + db = db.account_balance(created, U256::from(1)); + let Some(gas) = slots_gas(1_001) else { return }; + let outcome = execute(db, call_tx(gas)); + assert_eq!( + reverted_stop(&outcome), + MegaLimitExceeded { kind: 3, limit: TX_STATE_GROWTH_LIMIT } + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/mod.rs b/crates/mega-evm/tests/satin/limit_matrix/mod.rs new file mode 100644 index 000000000..bdc2c1a34 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/mod.rs @@ -0,0 +1,587 @@ +//! The resource-limit matrix of the specification: one test per case of its rules, written from +//! `docs/spec/upgrades/satin.md` alone, independently of the engine — the KV-update and +//! state-growth limits, the reservoir and pool shares, the stop, the block budgets, deposits, +//! keyless deployment and the same-transaction destruction table. A test's doc states the rule it +//! pins. +//! +//! The numbers below are the page's. A test does not import an engine constant for a figure the +//! page states. Gas room around a scenario may follow the schedule at the prices in effect, so +//! the same test still runs when a measurement build changes a byte price. + +pub(super) mod block; +pub(super) mod deposits; +pub(super) mod destruction; +pub(super) mod forwarding; +pub(super) mod keyless; +pub(super) mod limits; +pub(super) mod records; +pub(super) mod stop; + +use alloy_op_evm::OpTx; +use alloy_primitives::{Address, Bytes, TxKind, U256}; +use alloy_sol_types::SolError; +use mega_evm::{ + test_utils::{note_price_guard, op_transaction, BytecodeBuilder, MemoryDatabase}, + EvmTxRuntimeLimits, MegaContext, MegaEvm, MegaHaltReason, MegaLimitExceeded, MegaTransaction, + MegaTransactionOutcome, +}; +use revm::{ + bytecode::opcode::{ + CALL, CREATE, CREATE2, DELEGATECALL, GAS, PUSH0, RETURN, RETURNDATACOPY, RETURNDATASIZE, + }, + context::{ + result::{ExecutionResult, HaltReason}, + transaction::{AccessList, AccessListItem, TransactionType}, + TxEnv, + }, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, + }, + primitives::KECCAK_EMPTY, + Database, Inspector, +}; + +use crate::common::{self, context}; + +/// `TX_DATA_LIMIT` and `BLOCK_DATA_LIMIT` on the page. +pub(super) const TX_DATA_LIMIT: u64 = 13_107_200; +/// `TX_KV_UPDATE_LIMIT` and `BLOCK_KV_UPDATE_LIMIT` on the page. +pub(super) const TX_KV_UPDATE_LIMIT: u64 = 500_000; +/// `TX_STATE_GROWTH_LIMIT` and `BLOCK_STATE_GROWTH_LIMIT` on the page. +pub(super) const TX_STATE_GROWTH_LIMIT: u64 = 1_000; +/// History gas per byte. SALT does not scale it. +pub(super) const HISTORY_GAS_PER_BYTE: u64 = 88; +/// One write record, in bytes. Also its history bytes. +pub(super) const WRITE_RECORD_SIZE: u64 = 40; +/// Data size of one EIP-7708 transfer log, which pays no history. +pub(super) const TRANSFER_LOG_SIZE: u64 = 160; +/// History gas of one write record at the spec's byte price: `40 × 88`. +pub(super) const RECORD_HISTORY: u64 = 3_520; +/// The body's fixed bytes: the envelope and five records. +pub(super) const BODY_BYTES: u64 = 310; +/// History gas of an empty-calldata body at the spec's byte price: `310 × 88`. +pub(super) const BODY_HISTORY: u64 = 27_280; +/// State gas of one fresh slot at the minimum bucket: `64 × 1,530`. +pub(super) const SLOT_STATE_GAS_M1: u64 = 97_920; +/// State gas of one new account leaf at the minimum bucket: `120 × 1,530`. +pub(super) const ACCOUNT_LEAF_STATE_GAS_M1: u64 = 183_600; +/// State gas of one deployed code byte at the minimum bucket. +pub(super) const CODE_DEPOSIT_STATE_PER_BYTE: u64 = 1_530; +/// State gas of one delegation indicator, charged at most once per authority. +pub(super) const INDICATOR_STATE_GAS: u64 = 35_190; +/// Regular gas of a value-transferring `CALL`. The 2,300 stipend is already inside it. +pub(super) const VALUE_TRANSFER_GAS: u64 = 11_300; +/// Stipend added to a value-transferring `CALL` or `CALLCODE` after the cap. +pub(super) const CALL_STIPEND: u64 = 2_300; +/// Warm account access, charged as the `CALL` opcode's static gas. +pub(super) const WARM_READ: u64 = 100; +/// History allowance of a value `CALL` below the transaction's own frame, in bytes. +pub(super) const HISTORY_ALLOWANCE_BYTES: u64 = 160; +/// Gas of that allowance: `160 × 88`. It is not gas and not reservoir. +pub(super) const HISTORY_ALLOWANCE_GAS: u64 = 14_080; +/// The execution cap. Gas above it is the reservoir. Not a transaction-size cap. +pub(super) const EXECUTION_CAP: u64 = 200_000_000; +/// Percent of reservoir a caller keeps. The division truncates toward zero. +pub(super) const RESERVOIR_KEPT_PERCENT: u64 = 2; + +/// The caller every transaction is sent from. +pub(super) const CALLER: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1000"); +/// The contract a transaction calls. +pub(super) const CONTRACT: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1001"); +/// A callee. +pub(super) const CHILD: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1002"); +/// A callee of [`CHILD`]. +pub(super) const GRAND: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1003"); +/// A frame started after another child returned. +pub(super) const NEXT: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1004"); +/// Where a `SELFDESTRUCT` sends the balance. +pub(super) const BENEFICIARY: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1005"); +/// An account that already exists and holds no code worth running. +pub(super) const EXISTING: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab1006"); +/// The state-growth probe: a callee that fills fresh slots until its frame budget stops it. +pub(super) const PROBE: Address = + alloy_primitives::address!("0000000000000000000000000000000000ab100f"); + +/// Reservoir a child receives: `remaining − remaining × 2 / 100`. +pub(super) const fn reservoir_share(remaining: u64) -> u64 { + remaining - remaining * RESERVOIR_KEPT_PERCENT / 100 +} + +/// Frame budget a child receives: `remaining × 98 / 100`, rounded down. +pub(super) const fn frame_share(remaining: u64) -> u64 { + remaining * 98 / 100 +} + +/// Regular-gas cap: the same subtraction as [`reservoir_share`]. +pub(super) const fn gas_cap(remaining: u64) -> u64 { + reservoir_share(remaining) +} + +/// Bytecode that stores `1` into slots `1..=n` and stops. +/// +/// The loop is `PUSH2 n`, a `JUMPDEST` at pc 3, and a back-edge to it. The exit `JUMPDEST` is pc +/// 20 (`PUSH1 0x14`). Slot 0 is left untouched. +pub(super) fn store_n_slots(n: u16) -> Bytes { + Bytes::from(store_n_prefix(n, 1, true)) +} + +/// The loop of [`store_n_slots`] storing `value`, without the trailing `STOP` when `stop` is false, +/// so a caller can append another opcode. +pub(super) fn store_n_prefix(n: u16, value: u8, stop: bool) -> Vec { + let mut code = vec![ + 0x61, + (n >> 8) as u8, + (n & 0xff) as u8, + 0x5b, // JUMPDEST at pc 3 + 0x80, // DUP1 + 0x15, // ISZERO + 0x60, + 0x14, // PUSH1 20, the exit JUMPDEST + 0x57, // JUMPI + 0x60, + value, + 0x81, // DUP2 + 0x55, // SSTORE + 0x60, + 0x01, // PUSH1 1 + 0x90, // SWAP1 + 0x03, // SUB + 0x60, + 0x03, // PUSH1 3 + 0x56, // JUMP + 0x5b, // JUMPDEST at pc 20 + 0x50, // POP + ]; + if stop { + code.push(0x00); + } + code +} + +/// [`store_n_prefix`] placed at `origin`, so a loop appended after other code jumps to its own +/// `JUMPDEST`s. The jump targets are `PUSH2`. `PUSH2` costs the same static gas as the `PUSH1` +/// the origin-zero loop uses. +pub(super) fn store_n_prefix_at(origin: usize, n: u16, value: u8, stop: bool) -> Vec { + let entry = u16::try_from(origin + 3).expect("the loop's entry fits a PUSH2"); + let exit = u16::try_from(origin + 22).expect("the loop's exit fits a PUSH2"); + let mut code = vec![ + 0x61, + (n >> 8) as u8, + n as u8, + 0x5b, // JUMPDEST at origin + 3 + 0x80, // DUP1 + 0x15, // ISZERO + 0x61, + (exit >> 8) as u8, + exit as u8, + 0x57, // JUMPI + 0x60, + value, + 0x81, // DUP2 + 0x55, // SSTORE + 0x60, + 0x01, // PUSH1 1 + 0x90, // SWAP1 + 0x03, // SUB + 0x61, + (entry >> 8) as u8, + entry as u8, + 0x56, // JUMP + 0x5b, // JUMPDEST at origin + 22 + 0x50, // POP + ]; + if stop { + code.push(0x00); + } + code +} + +/// Code that ends a scenario by calling [`PROBE`] with all its gas and returning what the probe +/// returned. +/// +/// The probe tries to fill [`TX_STATE_GROWTH_LIMIT`] fresh slots of its own, more than any child +/// budget, so it always stops, kind 3, at its budget: `floor((1,000 − g) × 98 / 100)` when the +/// scenario before it kept a state-growth net of `g`. For `g` up to 49 the budget pins `g`. +pub(super) fn then_probe(scenario: impl AsRef<[u8]>) -> Bytes { + let mut code = scenario.as_ref().to_vec(); + code.extend_from_slice( + &BytecodeBuilder::default().call(PROBE, U256::ZERO).return_returndata().build(), + ); + Bytes::from(code) +} + +/// The probe's code: [`TX_STATE_GROWTH_LIMIT`] fresh slots. +pub(super) fn probe_code() -> Bytes { + store_n_slots(TX_STATE_GROWTH_LIMIT as u16) +} + +/// Asserts that the scenario before [`then_probe`] kept a state-growth net of `kept`: the probe +/// stopped at `floor((1,000 − kept) × 98 / 100)`. +pub(super) fn assert_growth(outcome: &MegaTransactionOutcome, kept: u64) { + assert!(kept < 50, "the probe pins a net below 50"); + assert_eq!( + returned_stop(outcome), + MegaLimitExceeded { kind: 3, limit: frame_share(TX_STATE_GROWTH_LIMIT - kept) }, + "the probe's budget is the share of what a kept net of {kept} leaves" + ); +} + +/// Runs `scenario` twice: ending in `STOP`, for its figures, and ending in [`then_probe`], for +/// the state-growth net it kept. `db` builds the database around the code [`CONTRACT`] runs. +/// Under the state-growth limit the probe is stopped and keeps nothing; an engine without one +/// keeps its slots and their charges, so the scenario's figures are read off the plain run. +pub(super) fn plain_and_probed( + scenario: &[u8], + db: impl Fn(Bytes) -> MemoryDatabase, +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + let gas = probe_gas(10)?; + let mut plain = scenario.to_vec(); + plain.push(0x00); + let outcome = execute(db(Bytes::from(plain)), call_tx(gas)); + let probed = execute(db(then_probe(scenario)), call_tx(gas)); + assert!(probed.result.is_success(), "the probed run: {:?}", probed.result); + Some((outcome, probed)) +} + +/// Gas for a scenario of `slots` fresh slots followed by the probe. +pub(super) fn probe_gas(slots: u64) -> Option { + slots_gas(slots + TX_STATE_GROWTH_LIMIT) +} + +/// `CALL` of `target` carrying `value`, forwarding exactly `gas`, with no calldata. Leaves the +/// success flag. +pub(super) fn call_with_gas( + code: BytecodeBuilder, + target: Address, + value: U256, + gas: u32, +) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_u256(value) + .push_address(target) + .push_number(gas) + .append(CALL) +} + +/// Copies the last call's return data to memory at `offset`. +pub(super) fn keep_returndata(code: BytecodeBuilder, offset: u16) -> BytecodeBuilder { + code.append_many([RETURNDATASIZE, PUSH0]).push_number(offset).append(RETURNDATACOPY) +} + +/// `RETURN` of the 256 bytes from `0x100`, where [`keep_returndata`] kept two return datas, at +/// `0x100` and `0x180`. +pub(super) fn return_kept(code: BytecodeBuilder) -> BytecodeBuilder { + code.push_number(0x100_u16).push_number(0x100_u16).append(RETURN) +} + +/// The two stops a successful transaction returned through [`return_kept`]. +pub(super) fn returned_stops( + outcome: &MegaTransactionOutcome, +) -> (MegaLimitExceeded, MegaLimitExceeded) { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("expected a success that returns two stops, got {:?}", outcome.result); + }; + let data = output.data(); + let decode = |at: usize| { + MegaLimitExceeded::abi_decode(&data[at..at + 68]).unwrap_or_else(|err| { + panic!("return data at {at} is not MegaLimitExceeded ({err}); output {data:?}"); + }) + }; + (decode(0), decode(0x80)) +} + +/// `CALL` of `target` with all remaining gas, then `RETURN` of its return data. +pub(super) fn forward_to(target: Address) -> Bytes { + BytecodeBuilder::default().call(target, U256::ZERO).return_returndata().build() +} + +/// `DELEGATECALL` of `target` with all remaining gas. Leaves the success flag. +pub(super) fn delegatecall(target: Address) -> BytecodeBuilder { + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(target) + .append_many([GAS, DELEGATECALL]) +} + +/// A database with [`CALLER`] funded and [`PROBE`] installed. Each `(address, code)` exists with +/// balance 1, so a call to it is not an account-creation. +pub(super) fn world(code: &[(Address, Bytes)]) -> MemoryDatabase { + let mut db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u128.pow(24))) + .account_code(PROBE, probe_code()) + .account_balance(PROBE, U256::from(1)); + for (address, bytecode) in code { + db = db.account_code(*address, bytecode.clone()).account_balance(*address, U256::from(1)); + } + db +} + +/// A call from [`CALLER`] to [`CONTRACT`]. +pub(super) fn call_tx(gas_limit: u64) -> MegaTransaction { + common::call(CALLER, CONTRACT, U256::ZERO, gas_limit) +} + +/// A creation from [`CALLER`]. +pub(super) fn create_tx(init_code: Bytes, gas_limit: u64) -> MegaTransaction { + common::create(CALLER, init_code, gas_limit) +} + +/// An EIP-2930 call that warms `warm` from the start, so the measured `CALL` pays no cold access. +pub(super) fn warm_call(gas_limit: u64, warm: &[Address]) -> MegaTransaction { + let access_list = AccessList::from( + warm.iter() + .map(|address| AccessListItem { address: *address, storage_keys: vec![] }) + .collect::>(), + ); + OpTx(op_transaction(TxEnv { + tx_type: TransactionType::Eip2930 as u8, + caller: CALLER, + kind: TxKind::Call(CONTRACT), + gas_limit, + access_list, + ..Default::default() + })) +} + +/// Gas that covers `slots` fresh slots above the execution cap at the prices in effect: the +/// slots' state gas, the history of the body and one record each, and regular gas for the loop. +/// +/// `None` when that sum does not fit a `u64`. The caller leaves a price-guard note and returns. +pub(super) fn gas_for_slots(slots: u64) -> Option { + let state = slots.checked_mul(common::slot_state_gas())?; + let bytes = BODY_BYTES.checked_add(slots.checked_mul(WRITE_RECORD_SIZE)?)?; + let history = common::history(bytes); + let regular = slots.checked_mul(40_000)?.checked_add(8_000_000)?; + state.checked_add(history)?.checked_add(regular)?.checked_add(EXECUTION_CAP) +} + +/// [`gas_for_slots`], or a note and `None` when the scenario does not fit. +pub(super) fn slots_gas(slots: u64) -> Option { + match gas_for_slots(slots) { + Some(gas) => Some(gas), + None => { + note_price_guard("the fresh-slot scenario does not fit one gas limit"); + None + } + } +} + +/// Whether this process prices bytes at the spec's constants. +/// +/// A test that pins a spec gas figure returns early otherwise. +/// [`common::runs_at_measurement_prices`] leaves the grid's note. +pub(super) fn at_spec_prices() -> bool { + !common::runs_at_measurement_prices() +} + +/// Runs `tx` and returns its outcome. +pub(super) fn execute(db: MemoryDatabase, tx: MegaTransaction) -> MegaTransactionOutcome { + common::execute(db, tx) +} + +/// Runs `tx` under `limits`. +pub(super) fn execute_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, +) -> MegaTransactionOutcome { + common::execute_under(db, tx, limits) +} + +/// The stop a reverted transaction carries. +pub(super) fn reverted_stop(outcome: &MegaTransactionOutcome) -> MegaLimitExceeded { + let ExecutionResult::Revert { output, .. } = &outcome.result else { + panic!("expected a revert, got {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(output).unwrap_or_else(|err| { + panic!("revert data is not MegaLimitExceeded ({err}); output {output:?}"); + }) +} + +/// The stop a successful transaction returned from a frame it caught. +pub(super) fn returned_stop(outcome: &MegaTransactionOutcome) -> MegaLimitExceeded { + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("expected a success that returns the stop, got {:?}", outcome.result); + }; + MegaLimitExceeded::abi_decode(output.data()).unwrap_or_else(|err| { + panic!("return data is not MegaLimitExceeded ({err}); output {output:?}"); + }) +} + +/// The value of `slot` after `outcome`, or zero when the account has no entry for it. +pub(super) fn slot_value(outcome: &MegaTransactionOutcome, address: Address, slot: u64) -> U256 { + outcome + .state + .get(&address) + .and_then(|account| account.storage.get(&U256::from(slot))) + .map(|entry| entry.present_value()) + .unwrap_or(U256::ZERO) +} + +/// Whether `outcome` destroyed `address`: an account created in the transaction that a +/// `SELFDESTRUCT` deleted. Its code can still be in the state entry, so code is not the test. +pub(super) fn is_destroyed(outcome: &MegaTransactionOutcome, address: Address) -> bool { + outcome.state.get(&address).is_some_and(|account| account.is_selfdestructed()) +} + +/// Whether `address` has code that is not empty. +pub(super) fn has_code(outcome: &MegaTransactionOutcome, address: Address) -> bool { + outcome.state.get(&address).is_some_and(|account| { + account.info.code.as_ref().is_some_and(|code| !code.is_empty()) || + (account.info.code_hash != alloy_primitives::B256::ZERO && + account.info.code_hash != KECCAK_EMPTY) + }) +} + +/// The nonce `outcome` leaves `address`, or zero when the account was not loaded. +pub(super) fn nonce_of(outcome: &MegaTransactionOutcome, address: Address) -> u64 { + outcome.state.get(&address).map(|account| account.info.nonce).unwrap_or(0) +} + +/// The balance `outcome` leaves `address`, or zero when the account was not loaded. +pub(super) fn balance_of(outcome: &MegaTransactionOutcome, address: Address) -> U256 { + outcome.state.get(&address).map(|account| account.info.balance).unwrap_or(U256::ZERO) +} + +/// Whether `outcome` halted because a frame ran out of gas. +pub(super) fn halted_out_of_gas(outcome: &MegaTransactionOutcome) -> bool { + matches!( + outcome.result, + ExecutionResult::Halt { reason: MegaHaltReason::Base(HaltReason::OutOfGas(_)), .. } + ) +} + +/// One forwarded call: the gas the caller held at the opcode, the gas the child was given, and +/// the reservoir the child was given. +#[derive(Clone, Debug, Default)] +pub(super) struct Forward { + want: Option
, + pending: Option, + /// Regular gas the caller held at the opcode, before its static gas. + pub(super) held: Option, + /// Regular gas the child was given. + pub(super) gas_limit: Option, + /// Reservoir the child was given. + pub(super) reservoir: Option, + /// Every call, in order: target, gas limit, reservoir. The first is the transaction's own + /// frame. + pub(super) calls: Vec<(Address, u64, u64)>, + /// Every call's end, in order: target, and the reservoir its frame ended with, before its + /// caller (or, for the transaction's own frame, the transaction) settles it. + pub(super) call_ends: Vec<(Address, u64)>, + /// The creation's gas limit and reservoir, when one started. + pub(super) created: Option<(u64, u64)>, + /// The regular gas the creation returned with, when one ended. + pub(super) create_end_remaining: Option, +} + +impl Forward { + /// Records the call whose target is `want`, and every call besides. + pub(super) fn targeting(want: Address) -> Self { + Self { want: Some(want), ..Self::default() } + } + + /// Records every call and the creation. + pub(super) fn any() -> Self { + Self::default() + } + + /// The reservoir the first call to `target` was given. + pub(super) fn reservoir_given(&self, target: Address) -> u64 { + let call = self.calls.iter().find(|(to, ..)| *to == target); + call.unwrap_or_else(|| panic!("no call to {target}: {:?}", self.calls)).2 + } +} + +impl Inspector, EthInterpreter> for Forward { + fn step(&mut self, interp: &mut Interpreter, _context: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + if matches!(opcode, CALL | DELEGATECALL | CREATE | CREATE2) { + self.pending = Some(interp.gas.remaining()); + } + } + + fn call( + &mut self, + _context: &mut MegaContext, + inputs: &mut CallInputs, + ) -> Option { + self.calls.push((inputs.target_address, inputs.gas_limit, inputs.reservoir)); + if self.want.is_none_or(|want| inputs.target_address == want) { + self.held = self.pending; + self.gas_limit = Some(inputs.gas_limit); + self.reservoir = Some(inputs.reservoir); + } + None + } + + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + self.call_ends.push((inputs.target_address, outcome.result.gas.reservoir())); + } + + fn create( + &mut self, + _context: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.created = Some((inputs.gas_limit(), inputs.reservoir())); + self.held = self.pending; + self.gas_limit = Some(inputs.gas_limit()); + self.reservoir = Some(inputs.reservoir()); + None + } + + fn create_end( + &mut self, + _context: &mut MegaContext, + _inputs: &CreateInputs, + outcome: &mut CreateOutcome, + ) { + self.create_end_remaining = Some(outcome.result.gas.remaining()); + } +} + +/// Runs `tx` over `db` and returns the outcome together with what [`Forward`] recorded. +pub(super) fn execute_forward( + db: MemoryDatabase, + tx: MegaTransaction, + probe: Forward, +) -> (MegaTransactionOutcome, Forward) { + let mut evm = MegaEvm::new(context(db)).with_inspector(probe); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let probe = evm.inspector().clone(); + (outcome, probe) +} + +/// Same as [`execute_forward`], under `limits`. +pub(super) fn execute_forward_under( + db: MemoryDatabase, + tx: MegaTransaction, + limits: EvmTxRuntimeLimits, + probe: Forward, +) -> (MegaTransactionOutcome, Forward) { + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)).with_inspector(probe); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + let probe = evm.inspector().clone(); + (outcome, probe) +} + +/// A call from [`CALLER`] to [`CONTRACT`] whose gas limit is the execution cap plus `reservoir` +/// plus the body's history, so the reservoir left after the body is `reservoir`. +pub(super) fn call_with_reservoir(reservoir: u64) -> MegaTransaction { + let gas = EXECUTION_CAP + common::body_history(0) + reservoir; + call_tx(gas) +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/records.rs b/crates/mega-evm/tests/satin/limit_matrix/records.rs new file mode 100644 index 000000000..923dc4003 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/records.rs @@ -0,0 +1,266 @@ +//! What one slot or one account keeps. +//! +//! A figure pinned below is the page's, at the minimum bucket. Each scenario runs through +//! [`plain_and_probed`]: its figures come from the plain run, and the state-growth net it kept +//! from the probe's budget, which is how a row about the state-growth count observes it. + +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; +use mega_evm::{test_utils::BytecodeBuilder, MegaTransactionOutcome}; +use revm::bytecode::opcode::POP; + +use super::{ + assert_growth, at_spec_prices, balance_of, call_with_gas, has_code, nonce_of, plain_and_probed, + slot_value, world, ACCOUNT_LEAF_STATE_GAS_M1, BODY_BYTES, BODY_HISTORY, CHILD, CONTRACT, + EXISTING, SLOT_STATE_GAS_M1, TRANSFER_LOG_SIZE, WRITE_RECORD_SIZE, +}; +use crate::common::state_is_free; + +/// An address no test funds. +const NOBODY: Address = address!("0000000000000000000000000000000000ab102b"); + +/// Whether a test that pins a spec state-gas figure can run. +fn pins_state() -> bool { + at_spec_prices() && !state_is_free() +} + +/// [`plain_and_probed`] on `world`, with [`CONTRACT`] running `scenario` and `setup` applied. +fn run( + scenario: Bytes, + setup: impl Fn(&mut mega_evm::test_utils::MemoryDatabase), +) -> Option<(MegaTransactionOutcome, MegaTransactionOutcome)> { + plain_and_probed(&scenario, |code| { + let mut db = world(&[(CONTRACT, code), (EXISTING, Bytes::from_static(&[0x00]))]); + setup(&mut db); + db + }) +} + +/// Slot `0 → x → 0` in one frame. The second `SSTORE` is the fall row: state gas is refilled, +/// the record is taken back, and the slot's net state growth is 0. +#[test] +fn test_a_slot_set_and_cleared_refills_its_state_gas() { + if !pins_state() { + return; + } + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO) + .build(); + let Some((outcome, probed)) = run(code, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "the fall refills the fresh-slot charge"); + assert_eq!( + outcome.gas.history, BODY_HISTORY, + "the taken-back record leaves the body's history" + ); + assert_eq!(slot_value(&outcome, CONTRACT, 1), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0, "the record is taken back with the value"); + assert_growth(&probed, 0); +} + +/// `CREATE2` onto an address that held a balance before the transaction, nonce 0, no code, and +/// that this transaction has not changed. The creation is valid and the nonce becomes 1. No +/// state-growth rise and no new-account charge. One record for the target, because its nonce +/// differs from what the transaction loaded, and the creator's nonce record apart from it. +/// +/// Under a transaction KV limit of 1 the creation's KV budget is `floor(1 × 98 / 100)` = 0 and the +/// target's record stops it, kind 1, `limit` 0, while the creator's bump stands, and the creator +/// keeps its record in the 1 it has once the creation returned. +#[test] +fn test_create2_onto_a_prefunded_address_is_not_a_rise() { + let init = BytecodeBuilder::default().stop().build(); + let created = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let code = || { + BytecodeBuilder::default().create2(U256::ZERO, init.clone(), U256::ZERO).append(POP).build() + }; + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_balance(created, U256::from(1)); + }; + let Some((outcome, probed)) = run(code(), setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, created), 1, "the creation bumps the nonce"); + assert_eq!(outcome.gas.state, 0, "a funded address is not empty: no new-account charge"); + assert_eq!(outcome.usage.write_records, 2, "the target's record and the creator's"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE); + assert_growth(&probed, 0); + + { + let mut code = code().to_vec(); + code.extend_from_slice(&BytecodeBuilder::default().return_returndata().build()); + let mut db = world(&[(CONTRACT, Bytes::from(code))]); + setup(&mut db); + let limits = mega_evm::EvmTxRuntimeLimits::default().with_tx_kv_update_limit(1); + let Some(gas) = super::slots_gas(2) else { return }; + let outcome = super::execute_under(db, super::call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + super::returned_stop(&outcome), + mega_evm::MegaLimitExceeded { kind: 1, limit: 0 } + ); + assert_eq!(nonce_of(&outcome, created), 0, "the stopped creation is taken back"); + assert_eq!(nonce_of(&outcome, CONTRACT), 1, "the creator's bump stands"); + assert_eq!(outcome.usage.write_records, 1, "the creator's record"); + } +} + +/// `CREATE2` onto an address this transaction funded earlier. The value call created the leaf: +/// +1 and 183,600 at `m` = 1. The address already has its write record, so the creation adds no +/// record, no rise and no second account charge. +#[test] +fn test_create2_onto_an_address_funded_in_this_transaction_charges_one_leaf() { + if !pins_state() { + return; + } + let init = BytecodeBuilder::default().stop().build(); + let funded = CONTRACT.create2(B256::ZERO, keccak256(init.as_ref())); + let code = BytecodeBuilder::default() + .call(funded, U256::from(1)) + .append(POP) + .create2(U256::ZERO, init, U256::ZERO) + .append(POP) + .build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_balance(CONTRACT, U256::from(10u64.pow(18))); + }; + let Some((outcome, probed)) = run(code, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.gas.state, ACCOUNT_LEAF_STATE_GAS_M1, + "the value call is the one leaf; the creation adds none" + ); + assert_eq!(nonce_of(&outcome, funded), 1); + assert_eq!(outcome.usage.write_records, 2, "the creator's record and the funded address's"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE); + assert_growth(&probed, 1); +} + +/// `CREATE2` onto an address that holds code: a collision. No target-side start is kept: the +/// target account, the endowment and its transfer log are not kept. The creator's nonce bump +/// and its record are retained. The collision adds no state growth. +/// +/// A collision consumes the regular gas it was forwarded, all but 2 per cent of its creator's, +/// so the creator is a child given [`CREATOR_GAS`]: the transaction's own frame keeps the gas the +/// probe after it runs on. +#[test] +fn test_create2_onto_code_keeps_the_creator_nonce_and_not_the_target() { + /// Regular gas for the creator: the `CREATE2` and what it forwards to the collision. The + /// history of the start's records draws the reservoir the creator is given. + const CREATOR_GAS: u32 = 200_000; + let init = BytecodeBuilder::default().stop().build(); + let target = CHILD.create2(B256::ZERO, keccak256(init.as_ref())); + let creator = + BytecodeBuilder::default().create2(U256::from(1), init, U256::ZERO).append(POP).build(); + let code = call_with_gas(BytecodeBuilder::default(), CHILD, U256::ZERO, CREATOR_GAS) + .append(POP) + .build(); + let before = U256::from(7); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_code(CHILD, creator.clone()); + db.set_account_balance(CHILD, U256::from(10u64.pow(18))); + db.set_account_code(target, Bytes::from_static(&[0x00])); + db.set_account_balance(target, before); + }; + let Some((outcome, probed)) = run(code, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(nonce_of(&outcome, CHILD), 1, "the creator nonce bump stands"); + assert_eq!(balance_of(&outcome, target), before, "the target and its endowment are not kept"); + assert!(has_code(&outcome, target), "the target code stays"); + assert_eq!(outcome.gas.state, 0, "a collision is not a rise"); + assert_eq!(outcome.usage.write_records, 1, "the creator's nonce record"); + assert_eq!(outcome.usage.data_size, BODY_BYTES + WRITE_RECORD_SIZE, "no transfer log"); + assert!(outcome.result.logs().is_empty()); + assert_growth(&probed, 0); +} + +/// A value `CALL` the caller cannot fund, to an account that does not exist, counts nothing: no +/// record, no rise, no charge. A creation whose creator nonce cannot be bumped counts nothing +/// either, though the address it would create is empty. No limit stops either. +#[test] +fn test_an_unfunded_value_call_and_a_stuck_nonce_count_nothing() { + let call = BytecodeBuilder::default().call(NOBODY, U256::from(5)).append(POP).build(); + let Some((outcome, probed)) = run(call, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0, "an unfunded value call writes nothing"); + assert_eq!(outcome.usage.data_size, BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "and is charged nothing"); + assert_eq!(balance_of(&outcome, NOBODY), U256::ZERO); + assert!(outcome.limit_exceeded.is_none()); + assert_growth(&probed, 0); + + let init = BytecodeBuilder::default().stop().build(); + let create = BytecodeBuilder::default().create(U256::ZERO, init).append(POP).build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_nonce(CONTRACT, u64::MAX); + }; + let Some((outcome, probed)) = run(create, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.usage.write_records, 0, "a nonce that cannot move writes nothing"); + assert_eq!(outcome.usage.data_size, BODY_BYTES); + assert_eq!(outcome.gas.state, 0); + assert_eq!(nonce_of(&outcome, CONTRACT), u64::MAX); + assert!(outcome.limit_exceeded.is_none()); + assert_growth(&probed, 0); +} + +/// `(original 0, present non-zero, new non-zero)` neither rises nor falls: the slot rose once, at +/// its first write. `(original non-zero, present 0, new non-zero)` neither rises nor falls, and +/// charges no fresh-slot state gas and refills none. +#[test] +fn test_a_second_nonzero_write_neither_rises_nor_falls() { + if !pins_state() { + return; + } + let twice = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::from(2)) + .build(); + let Some((outcome, probed)) = run(twice, |_| {}) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, SLOT_STATE_GAS_M1, "0 → x → y rose once"); + assert_growth(&probed, 1); + + let restored = BytecodeBuilder::default() + .sstore(U256::from(1), U256::ZERO) + .sstore(U256::from(1), U256::from(1)) + .build(); + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_storage(CONTRACT, U256::from(1), U256::from(9)); + }; + let Some((outcome, probed)) = run(restored, setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "a slot that started non-zero charges and refills nothing"); + assert_growth(&probed, 0); +} + +/// `0 → 0` changes nothing. `0 → x → x` and `0 → x → y` rose once. `0 → x → 0 → y` rose, fell, +/// and rose again, net +1. A slot whose original value is non-zero changes nothing on every write. +#[test] +fn test_slot_sequences_in_one_frame_rise_once() { + if !pins_state() { + return; + } + let writes = |values: &[u64]| { + values + .iter() + .fold(BytecodeBuilder::default(), |code, value| { + code.sstore(U256::from(1), U256::from(*value)) + }) + .build() + }; + for (values, rises) in [(&[0][..], 0), (&[1, 1][..], 1), (&[1, 2][..], 1), (&[1, 0, 3][..], 1)] + { + let Some((outcome, probed)) = run(writes(values), |_| {}) else { return }; + assert!(outcome.result.is_success(), "{values:?}: {:?}", outcome.result); + assert_eq!(outcome.gas.state, rises * SLOT_STATE_GAS_M1, "{values:?}"); + assert_eq!(outcome.usage.write_records, rises, "{values:?}"); + assert_growth(&probed, rises); + } + + let setup = |db: &mut mega_evm::test_utils::MemoryDatabase| { + db.set_account_storage(CONTRACT, U256::from(1), U256::from(8)); + }; + let Some((outcome, probed)) = run(writes(&[4, 0, 5]), setup) else { return }; + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.gas.state, 0, "an originally non-zero slot changes nothing"); + assert_growth(&probed, 0); +} diff --git a/crates/mega-evm/tests/satin/limit_matrix/stop.rs b/crates/mega-evm/tests/satin/limit_matrix/stop.rs new file mode 100644 index 000000000..d25f62590 --- /dev/null +++ b/crates/mega-evm/tests/satin/limit_matrix/stop.rs @@ -0,0 +1,306 @@ +//! Which dimension a crossing names, and a caller that catches it. +//! +//! Every kind is observed through the revert data. + +use alloy_primitives::{Bytes, U256}; +use mega_evm::{test_utils::BytecodeBuilder, EvmTxRuntimeLimits, MegaLimitExceeded}; +use revm::{ + bytecode::opcode::{POP, TIMESTAMP}, + context::result::ExecutionResult, +}; + +use super::{ + call_tx, execute_under, returned_stop, slot_value, slots_gas, store_n_prefix, world, CHILD, + CONTRACT, TX_STATE_GROWTH_LIMIT, +}; + +fn extend(prefix: Vec, rest: BytecodeBuilder) -> Bytes { + let mut code = prefix; + code.extend_from_slice(&rest.build()); + Bytes::from(code) +} + +/// Under a transaction KV limit of 10, an applied authorization is one record before the first +/// frame, on no frame, so the transaction's own frame has a KV budget of 9. That frame's 10th +/// record crosses its budget and the transaction limit. Kind 1. `limit` is the frame budget, 9. +#[test] +fn test_a_record_that_crosses_kv_names_the_frame_budget() { + let Some(gas) = slots_gas(12) else { return }; + let authority = alloy_primitives::address!("0000000000000000000000000000000000ab1018"); + let db = world(&[(CONTRACT, super::store_n_slots(10))]); + let tx = crate::common::authorizing_call( + super::CALLER, + CONTRACT, + U256::ZERO, + gas, + CHILD, + &[(authority, 0)], + ); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let outcome = execute_under(db, tx, limits); + assert_eq!(super::reverted_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 9 }); + assert_eq!(super::nonce_of(&outcome, authority), 1, "the admitted authorization stays"); +} + +/// A fresh `SSTORE` whose regular charge crosses detention, and whose completed write would have +/// crossed the state-growth frame budget. The charge is made before the write is counted. Kind +/// 2. The crossing slot is not kept. The parent's earlier slots stay: the stop is the child's. +#[test] +fn test_a_charge_that_crosses_detention_stops_before_the_write_is_counted() { + let child = BytecodeBuilder::default() + .append(TIMESTAMP) + .append(POP) + .sstore(U256::from(1), U256::from(1)) + .stop() + .build(); + let parent = extend( + store_n_prefix(TX_STATE_GROWTH_LIMIT as u16, 1, false), + BytecodeBuilder::default().call(CHILD, U256::ZERO).return_returndata(), + ); + let db = world(&[(CONTRACT, parent), (CHILD, child)]); + let Some(gas) = slots_gas(TX_STATE_GROWTH_LIMIT + 1) else { return }; + // 50 leaves the opcodes between the read and `SSTORE` inside the cap, and `SSTORE`'s charge + // past it. Zero would be a real cap the read itself could not move past. + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(50); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let stop = returned_stop(&outcome); + assert_eq!(stop.kind, 2, "the regular charge stops the opcode before the write is counted"); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the crossing slot is not kept"); + assert_eq!( + slot_value(&outcome, CONTRACT, 1), + U256::from(1), + "the parent frame is outside the stop" + ); +} + +/// KV at depth 2 and 3 under a transaction limit of 100: the child's budget is 98, the +/// grandchild's 96 and the next frame's `floor(96 × 98 / 100)` = 94. The 95th new record there +/// stops that frame, kind 1, `limit` 94. +#[test] +fn test_kv_at_depth_2_and_3_stops_at_94() { + assert_eq!(super::frame_share(100), 98); + assert_eq!(super::frame_share(98), 96); + assert_eq!(super::frame_share(96), 94); + let Some(gas) = slots_gas(95) else { return }; + let db = world(&[ + (CONTRACT, super::forward_to(CHILD)), + (CHILD, super::forward_to(super::GRAND)), + (super::GRAND, super::forward_to(super::NEXT)), + (super::NEXT, super::store_n_slots(95)), + ]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(100); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 94 }); + assert_eq!(slot_value(&outcome, super::NEXT, 1), U256::ZERO); +} + +/// The caller catches a kind-3 stop, continues, and is stopped in turn. The child's stop is not +/// the transaction's result. `limit` is the caller's frame budget. The top frame catches that +/// stop in turn and the transaction succeeds. +/// +/// The same shape for kind 1, under a transaction KV limit of 100. +#[test] +fn test_a_caller_that_catches_a_stop_is_stopped_by_its_own_next_record() { + let child = super::store_n_slots(1); + let mid = extend( + store_n_prefix(980, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::from(981), U256::from(1)), + ); + let parent = + BytecodeBuilder::default().call(super::GRAND, U256::ZERO).return_returndata().build(); + // GRAND is the frame whose budget is 980. CHILD is the frame whose budget is 0. + let db = world(&[(CONTRACT, parent.clone()), (super::GRAND, mid), (CHILD, child)]); + let Some(gas) = slots_gas(1_000) else { return }; + let outcome = execute_under(db, call_tx(gas), EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the top frame caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 3, limit: 980 }); + assert_eq!( + slot_value(&outcome, super::GRAND, 1), + U256::ZERO, + "the stopped caller keeps nothing" + ); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO); + + { + // The caller's KV budget is `floor(100 × 98 / 100)` = 98, its child's 0. + let mid = extend( + store_n_prefix(98, 1, false), + BytecodeBuilder::default() + .call(CHILD, U256::ZERO) + .append(POP) + .sstore(U256::from(99), U256::from(1)), + ); + let db = + world(&[(CONTRACT, parent), (super::GRAND, mid), (CHILD, super::store_n_slots(1))]); + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(100); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.limit_exceeded.is_none(), "the top frame caught the stop"); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 98 }); + assert_eq!(slot_value(&outcome, super::GRAND, 1), U256::ZERO); + } +} + +/// Under a transaction KV limit of 10 the creator, a child of the top frame, has a KV budget of +/// 9. It keeps 9 records and then creates: the creation's budget is the share of the nothing the +/// creator has left, 0, and its own record stops it at its start. The start bumped the creator's +/// nonce, whose record is counted on the creator when the creation returns, before it runs on: +/// the creator stops, kind 1, `limit` 9, its frame budget. +/// +/// With one record of room the creation's budget is still `floor(1 × 98 / 100)` = 0, so the +/// creation is stopped at its start, kind 1, `limit` 0, and the creator keeps the bump and its +/// record in the one it has: its nonce is 1. +#[test] +fn test_a_creator_nonce_record_stops_the_creator_at_its_kv_budget() { + let Some(gas) = slots_gas(12) else { return }; + let limits = EvmTxRuntimeLimits::default().with_tx_kv_update_limit(10); + let creator = |records: u16| { + let mut code = store_n_prefix(records, 1, false); + let init = BytecodeBuilder::default().return_with_data([0x00]).build(); + code.extend_from_slice( + &BytecodeBuilder::default() + .create(U256::ZERO, init) + .append(POP) + .return_returndata() + .build(), + ); + Bytes::from(code) + }; + + let db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, creator(9))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 9 }); + assert_eq!(slot_value(&outcome, CHILD, 1), U256::ZERO, "the stopped creator keeps nothing"); + + let db = world(&[(CONTRACT, super::forward_to(CHILD)), (CHILD, creator(8))]); + let outcome = execute_under(db, call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 0 }); + assert_eq!(super::nonce_of(&outcome, CHILD), 1, "a stopped creation keeps the creator's bump"); + assert_eq!(slot_value(&outcome, CHILD, 8), U256::from(1)); +} + +/// A value `CALL` to the BN254 pairing precompile with no input, whose price, 45,000, is past +/// what a read of the block environment under a cap of 20,000 leaves once the caller's own +/// `CALL` is paid, and within the forward. The start's two records, the caller's +/// balance and the precompile's, are inside every budget, so the price is the stop, kind 2, and +/// the value, the transfer log and the records are taken back with it, the new account's state +/// gas included. A value the caller cannot fund runs no precompile, counts nothing and is stopped +/// by no limit. +/// +/// Under a transaction KV limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, +/// the two records cross it, and the stop is kind 1, `limit` 1, not the price. A precompile the +/// node cannot price needs a node precompile and is not run. +#[test] +fn test_precompile_records_stop_at_the_kv_share_before_the_price() { + const PAIRING: alloy_primitives::Address = + alloy_primitives::address!("0000000000000000000000000000000000000008"); + let paying = |value: u64| { + BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .call(PAIRING, U256::from(value)) + .append(POP) + .return_returndata() + .build() + }; + let gas = super::EXECUTION_CAP + crate::common::value_call_room(); + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(20_000); + + let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the price is the stop"); + assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO, "the value is taken back"); + assert!(outcome.result.logs().is_empty(), "the transfer log is taken back"); + assert_eq!(outcome.usage.write_records, 0, "the records are taken back"); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "the new account's charge comes back"); + + let outcome = execute_under(world(&[(CONTRACT, paying(5))]), call_tx(gas), limits); + let ExecutionResult::Success { output, .. } = &outcome.result else { + panic!("an unfunded value call fails and its caller runs on: {:?}", outcome.result); + }; + assert!(output.data().is_empty(), "no precompile ran and no stop was returned"); + assert!(outcome.limit_exceeded.is_none()); + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + assert_eq!(outcome.gas.state, 0, "the unfunded start is charged nothing"); + + { + let limits = limits.with_tx_kv_update_limit(2); + let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0); + } +} + +/// A precompile the node installed, whose start's records are held before its answer. +/// +/// A precompile the engine cannot price runs on what the compute limit leaves its frame, and the +/// start's records are held to the limits before its answer is: a value `CALL` to a node's own +/// precompile, installed through `with_dyn_precompiles`, whose price, 100,000, is past what a read +/// of the block environment under a cap of 30,000 leaves once the caller's own `CALL` is paid, and +/// within the forward. With the records inside every budget it runs out of that allowance, and +/// that is the stop, kind 2, which takes the value and the records back. Under a transaction KV +/// limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, the two records cross it, +/// and the stop is kind 1, `limit` 1: the same order as for a precompile the engine prices. +#[test] +fn test_an_unpriced_precompile_records_stop_at_the_kv_share_before_its_allowance() { + use alloy_primitives::map::HashMap; + use mega_evm::MegaEvm; + use revm::bytecode::opcode::{CALL, GAS, PUSH0}; + + use crate::withheld_gas::{priced, Runs, PRICED}; + + const PRICE: u64 = 100_000; + let code = BytecodeBuilder::default() + .append_many([TIMESTAMP, POP]) + .mstore(0, U256::from(PRICE).to_be_bytes::<32>()) + .append_many([PUSH0, PUSH0]) + .push_number(32_u8) + .append(PUSH0) + .push_u256(U256::from(1)) + .push_address(PRICED) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + let gas = super::EXECUTION_CAP + crate::common::value_call_room(); + let run = |limits: EvmTxRuntimeLimits| { + let runs = Runs::default(); + let context = crate::common::context(world(&[(CONTRACT, code.clone())])) + .with_tx_runtime_limits(limits); + let outcome = MegaEvm::new(context) + .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])) + .execute_transaction(call_tx(gas)) + .expect("the transaction is valid"); + let ran = runs.lock().unwrap().clone(); + (outcome, ran) + }; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(30_000); + + let (outcome, ran) = run(limits); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the allowance is the stop"); + assert!( + matches!(ran.as_slice(), [(allowance, false)] if *allowance < 30_000), + "it ran once, on the allowance, short of its price: {ran:?}" + ); + assert_eq!(super::balance_of(&outcome, PRICED), U256::ZERO, "the value is taken back"); + assert_eq!(outcome.usage.write_records, 0, "the records are taken back"); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); + + let (outcome, _) = run(limits.with_tx_kv_update_limit(2)); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(super::balance_of(&outcome, PRICED), U256::ZERO); + assert_eq!(outcome.usage.write_records, 0); + assert_eq!(outcome.usage.data_size, super::BODY_BYTES); +} diff --git a/crates/mega-evm/tests/satin/main.rs b/crates/mega-evm/tests/satin/main.rs index dd2ee96c2..dca186240 100644 --- a/crates/mega-evm/tests/satin/main.rs +++ b/crates/mega-evm/tests/satin/main.rs @@ -15,6 +15,8 @@ mod detention; mod equivalence; mod failed_deposit; mod floor_exempt; +mod gas_forward; +mod history_allowance; mod history_bytes; mod history_exemption; mod history_gas; @@ -25,13 +27,19 @@ mod inspector_cheatcodes; mod inspector_limits; mod inspector_settlement; mod intrinsic; +mod kv_updates; mod limit_exemption; +mod limit_matrix; mod limit_stop; mod neutral; +#[path = "../shared/op_reference.rs"] +mod op_reference; mod outcome; mod pool_validation; mod precompile_gas; mod pricing_table; +mod reservoir_drain; +mod reservoir_share; mod salt; mod salt_delegation; mod salt_deposit; @@ -45,10 +53,10 @@ mod state; mod state_growth; mod static_callee; mod stops; -mod storage_call_stipend; mod strategic_stop; mod synthetic_frame_gas; mod system_call; +mod tool_writes; mod transfer_logs; mod volatile_access; mod withheld_gas; diff --git a/crates/mega-evm/tests/satin/neutral.rs b/crates/mega-evm/tests/satin/neutral.rs index da8f4d79b..657c565d1 100644 --- a/crates/mega-evm/tests/satin/neutral.rs +++ b/crates/mega-evm/tests/satin/neutral.rs @@ -30,8 +30,8 @@ use op_revm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, BALANCE, CALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, PUSH1, SSTORE, - TIMESTAMP, + ADDRESS, BALANCE, CALL, DELEGATECALL, EXTCODESIZE, GAS, LOG1, LOG3, NUMBER, POP, PUSH0, + PUSH1, SELFDESTRUCT, SSTORE, STOP, TIMESTAMP, }, context::{ result::{ExecResultAndState, ExecutionResult}, @@ -188,6 +188,56 @@ fn test_neutral_creation_matches_op_revm() { } } +/// A `CREATE` from a contract whose nonce is at its maximum. On Osaka, where EIP-8037 is off, the +/// opcode starts the creation without the address it would take, and revm refuses it before the +/// bump; on Amsterdam the opcode refuses it itself. Either way nothing is created and nothing is +/// counted, and the run is op-revm's. +#[test] +fn test_neutral_creation_from_a_nonce_at_its_maximum_matches_op_revm() { + let code = BytecodeBuilder::default().create(U256::ZERO, [STOP]).return_top().build(); + for fork in FORKS { + let db = funded().account_code(CALLEE, code.clone()).account_nonce(CALLEE, u64::MAX); + let outcome = run_both(fork, db, call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success(), "{fork:?}: {:?}", outcome.0.result); + assert_eq!(outcome.0.result.output(), Some(&Bytes::from(vec![0; 32])), "{fork:?}"); + assert_eq!(outcome.0.state[&CALLEE].info.nonce, u64::MAX, "{fork:?}: not bumped"); + assert_same(fork, outcome); + } +} + +/// A creation whose constructor writes a fresh slot, destroys its own account through a +/// `DELEGATECALL`, writes another fresh slot and returns code. On Satin's configuration the +/// destruction gives back the leaf and the slot's state gas, the slot written after it keeps none, +/// and the code deposited after it keeps none; EIP-8037 gives back nothing for this destruction, +/// and the neutral configuration prices as the fork does, so the run is op-revm's on both forks, +/// Amsterdam's state gas included. +#[test] +fn test_neutral_creation_that_destroys_itself_matches_op_revm() { + const DESTROYER: Address = address!("0x5000000000000000000000000000000000000003"); + let destroyer = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + let init = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(DESTROYER) + .append_many([GAS, DELEGATECALL, POP]) + .sstore(U256::from(2), U256::from(1)) + .return_with_data([STOP, STOP]) + .build(); + let code = BytecodeBuilder::default().create(U256::ZERO, &init).append(POP).stop().build(); + for fork in FORKS { + let db = + funded().account_code(CALLEE, code.clone()).account_code(DESTROYER, destroyer.clone()); + let outcome = run_both(fork, db, call(Bytes::new(), U256::ZERO)); + assert!(outcome.0.result.is_success(), "{fork:?}: {:?}", outcome.0.result); + let created = CALLEE.create(0); + assert!( + outcome.0.state[&created].is_selfdestructed(), + "{fork:?}: the account is destroyed" + ); + assert_same(fork, outcome); + } +} + /// A nested value call: on Satin's configuration its caller pays for the two write records the /// callee's frame makes, and the callee gets a history allowance. Neither shows here. #[test] @@ -372,3 +422,38 @@ fn test_neutral_kzg_call_matches_ethereum() { assert_same(fork, outcome); } } + +/// A creation onto an address an earlier transaction run on the same journal loaded — two +/// transactions in a row, without the journal finalized between them, as a block builder runs one +/// after another — makes a new account, and counts its unit of state growth, as on a fresh +/// journal. On Osaka the `CREATE2` opcode does not load the address itself, EIP-8037 being off, so +/// what the earlier transaction left of the account in the journal is all the start finds. +#[test] +fn test_neutral_creation_onto_an_address_an_earlier_transaction_loaded_counts_its_account() { + const READER: Address = address!("0x5000000000000000000000000000000000000002"); + let init = Bytes::from_static(&[STOP]); + let created = CALLEE.create2(alloy_primitives::B256::ZERO, alloy_primitives::keccak256(&init)); + let factory = BytecodeBuilder::default().create2(U256::ZERO, &init, U256::ZERO).stop().build(); + let reader = + BytecodeBuilder::default().push_address(created).append_many([BALANCE, POP]).stop().build(); + for fork in FORKS { + let db = + funded().account_code(CALLEE, factory.clone()).account_code(READER, reader.clone()); + let ctx = MegaContext::new(db, MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(fork).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx); + neutralize_evm(&mut evm, fork).expect("a neutral fork"); + let read = TxEnv { kind: TxKind::Call(READER), ..call(Bytes::new(), U256::ZERO) }; + let read = ExecuteEvm::transact_one(&mut evm, OpTx(op_transaction(read))).unwrap(); + assert!(read.is_success(), "{fork:?}: {read:?}"); + let create = TxEnv { nonce: 1, ..call(Bytes::new(), U256::ZERO) }; + let create = ExecuteEvm::transact_one(&mut evm, OpTx(op_transaction(create))).unwrap(); + assert!(create.is_success(), "{fork:?}: {create:?}"); + let state = ExecuteEvm::finalize(&mut evm); + assert_eq!(state[&created].info.nonce, 1, "{fork:?}: the account was created"); + assert_eq!(evm.ctx().limit_usage().state_growth, 1, "{fork:?}: its unit of growth"); + } +} diff --git a/crates/mega-evm/tests/satin/outcome.rs b/crates/mega-evm/tests/satin/outcome.rs index d65b69196..d5d9fbf85 100644 --- a/crates/mega-evm/tests/satin/outcome.rs +++ b/crates/mega-evm/tests/satin/outcome.rs @@ -67,7 +67,12 @@ fn test_outcome_reports_the_ledgers() { ); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, write_records: 2 } + LimitUsage { + data_size: TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, + write_records: 2, + state_growth: 2 + }, + "the two write records; both slots are new" ); assert_eq!(outcome.limit_exceeded, None); @@ -92,14 +97,15 @@ fn test_outcome_reports_the_stop() { outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: TX_BODY_SIZE + 40, - used: TX_BODY_SIZE + 80, - frame_local: false - }) + limit: 40, + used: 80, + frame_local: true + }), + "the transaction's own frame crossed its budget, what the body leaves of the limit" ); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "the stop drops the writes and keeps the body" ); } diff --git a/crates/mega-evm/tests/satin/pricing-table.md b/crates/mega-evm/tests/satin/pricing-table.md index a73acf4fa..7405a9559 100644 --- a/crates/mega-evm/tests/satin/pricing-table.md +++ b/crates/mega-evm/tests/satin/pricing-table.md @@ -4,7 +4,7 @@ Generated by `cargo test -p mega-evm --test satin`; the test compares this file ## Schedule entries -Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those two applies. +Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded 98 per cent of what its caller has left of its regular gas, of its reservoir and of its data-size, KV-update and state-growth budgets; the `Satin` column differs from `Amsterdam` in exactly the entries where one of those applies. | Gas id | Osaka | Amsterdam | Satin | |---|---:|---:|---:| @@ -19,7 +19,7 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | memory_quadratic_reduction | 512 | 512 | 512 | | initcode_per_word | 2 | 2 | 2 | | create | 32000 | 12000 | 12000 | -| call_stipend_reduction | 64 | 64 | 64 | +| call_stipend_reduction | 64 | 64 | 50 | | transfer_value_cost | 9000 | 11300 | 11300 | | cold_account_additional_cost | 2500 | 2900 | 2900 | | new_account_cost | 25000 | 0 | 0 | @@ -57,6 +57,11 @@ Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamste | max_refund_quotient | 5 | 5 | 5 | | tx_account_write_cost | 0 | 9000 | 9000 | | tx_create_access_cost | 0 | 12000 | 12000 | +| pool2_kept_percent | 0 | 0 | 2 | +| pool1_kept_percent | 0 | 0 | 2 | +| pool0_kept_percent | 0 | 0 | 2 | +| reservoir_kept_percent | 0 | 0 | 2 | +| call_history_allowance | 0 | 0 | 14080 | | code_deposit_history_gas | 0 | 0 | 88 | ## Measured transactions diff --git a/crates/mega-evm/tests/satin/pricing_table.rs b/crates/mega-evm/tests/satin/pricing_table.rs index 83a524df5..f5dd920d2 100644 --- a/crates/mega-evm/tests/satin/pricing_table.rs +++ b/crates/mega-evm/tests/satin/pricing_table.rs @@ -141,9 +141,11 @@ fn render() -> String { out.push_str( "Every named entry of the schedule, at the Osaka price, at the Amsterdam (glamsterdam \ devnet-8) price and at the Satin price. Satin is Amsterdam with the EIP-8037 state \ - entries rebuilt at `MegaETH`'s cost per state byte and deposited code priced at \ - `MegaETH`'s cost per history byte; the `Satin` column differs from `Amsterdam` in \ - exactly the entries where one of those two applies.\n\n", + entries rebuilt at `MegaETH`'s cost per state byte, deposited code and a value call's \ + history allowance priced at `MegaETH`'s cost per history byte, and a frame forwarded \ + 98 per cent of what its caller has left of its regular gas, of its reservoir and of its \ + data-size, KV-update and state-growth budgets; the `Satin` column differs from \ + `Amsterdam` in exactly the entries where one of those applies.\n\n", ); out.push_str("| Gas id | Osaka | Amsterdam | Satin |\n|---|---:|---:|---:|\n"); for slot in 0..=u8::MAX { @@ -307,11 +309,21 @@ fn test_the_table_shows_where_satin_differs_from_amsterdam() { // Every regular entry is Amsterdam's. The state entries are rebuilt rather than copied, and // land on Amsterdam's numbers because the provisional cost per state byte is the one - // Glamsterdam uses. The history entry is the one Satin adds: upstream prices no history byte - // at all. + // Glamsterdam uses. The history entries are the ones Satin adds — upstream prices no history + // byte at all — and so are the parts of the data-size, KV-update and state-growth pools and of + // the reservoir a caller keeps from the frame it starts, which upstream forwards whole, and the + // quotient of the regular gas a call forwards, Rex6's 98/100 in place of EIP-150's 63/64. assert_eq!( differing, - ["code_deposit_history_gas"], + [ + "call_stipend_reduction", + "pool2_kept_percent", + "pool1_kept_percent", + "pool0_kept_percent", + "reservoir_kept_percent", + "call_history_allowance", + "code_deposit_history_gas" + ], "the entries Satin prices differently from Amsterdam" ); } diff --git a/crates/mega-evm/tests/satin/reservoir_drain.rs b/crates/mega-evm/tests/satin/reservoir_drain.rs new file mode 100644 index 000000000..6ec0a0550 --- /dev/null +++ b/crates/mega-evm/tests/satin/reservoir_drain.rs @@ -0,0 +1,1751 @@ +//! How a callee's charges draw on the EIP-8037 reservoir it inherits from its caller. +//! +//! Under one gas pool, the forward bounds everything a callee spends. Under Satin a call forwards +//! regular gas, at most `remaining − remaining × 2 / 100` of what its caller has left, and hands +//! the callee the same share of its caller's reservoir whatever regular gas it asks for; the +//! callee's state and history charges draw that share before its regular gas. These tests measure +//! how far a callee's charges reach past the forward, and what that leaves its caller. +//! +//! The contracts: +//! - `A`, the transaction's target, reads `GAS`, calls `C` with an explicit forward (or all it may, +//! asking for its `GAS`), reads `GAS` again, then writes `K` fresh slots of its own and returns. +//! - `C` is `STOP`; `INVALID`, which burns its forward and charges nothing else; or a loop of one +//! charging opcode — `LOG0` with data, `LOG4` without data, or a fresh `SSTORE` — that reads +//! `GAS` around the opcode and returns once an iteration's drop exceeds the opcode's regular cost +//! (the reservoir no longer paid the whole charge), or once its regular gas is below what one +//! more iteration costs with the whole charge spilled onto regular gas. The greedy variant never +//! stops on the drop. One more `C` `CREATE`s a contract of zero bytes and stops. +//! +//! `K` is the work a single pool's forward rule would guarantee `A`: the most fresh slots `A` +//! completes after a callee that spent exactly its forward of regular gas and charged the +//! reservoir nothing, which is what the `INVALID` callee does: its halt hands its share of the +//! reservoir back whole. Each slot is a new slot, so the state-growth limit holds `K` to the 1,000 +//! the transaction may add, and the slots `C` keeps come out of them; below that `A`'s gas binds +//! `K`, and the work fails once `C`'s charges, from both pools together, take more than the room +//! the work leaves. +//! +//! Every figure is predicted by a model of the two pools ([`Pools`]) and the three counted budgets +//! ([`Budget`]) built from the spec's rules and the static opcode costs — a regular charge draws +//! regular gas only, a state or history charge draws the reservoir first and spills onto regular +//! gas, `GAS` reads regular gas; a call forwards at most all but 2 per cent of its caller's regular +//! gas and hands the child all but 2 per cent of its caller's reservoir; the child hands back what +//! it leaves, its reservoir unwinding the caller's spill before the rest joins what the caller +//! kept, and a frame that reverts or halts gives its charges back, its share of the reservoir +//! with them; a child's data-size, KV and state-growth budgets are 98/100 of what its caller has +//! left, and a charge that crosses one reverts the frame with the stop — and each run is held to +//! it: the forward, the share, the charges `C` made, the pools it left, `A`'s `GAS` around the +//! call, whether `A`'s work completed, and the receipt with its ledgers and counts. The figures are +//! read by an inspector, and the same run without one settles the same. The tests print their +//! tables (`--nocapture`); a frame's end shows its gas before its caller settles it, so a reverted +//! `C`'s history column is what it charged before the revert gave it back. +//! +//! They pin the spec's numbers, and return early at other byte prices. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::{ + COST_PER_STATE_BYTE, MAX_CONTRACT_SIZE, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, + }, + decode_mega_limit_exceeded, + test_utils::MemoryDatabase, + LimitCheck, LimitKind, LimitUsage, MegaContext, MegaEvm, MegaTransaction, + MegaTransactionOutcome, TX_BODY_SIZE, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{ + ADD, CALL, CREATE, DUP1, DUP2, DUP3, GAS, GT, INVALID, ISZERO, JUMP, JUMPDEST, JUMPI, LOG0, + LOG4, LT, MSTORE, POP, PUSH0, PUSH1, PUSH2, PUSH20, PUSH3, PUSH4, PUSH6, RETURN, SSTORE, + STOP, SUB, SWAP1, + }, + context::result::ExecutionResult, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, InstructionResult, Interpreter, + }, + Database, Inspector, +}; + +use crate::common::{ + account_state_gas, body_history, call, context, execute, forward_cap, history, + reservoir_giving, reservoir_share, runs_at_measurement_prices, share, slot_state_gas, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000710000"); +const A: Address = address!("0000000000000000000000000000000000710001"); +const C: Address = address!("0000000000000000000000000000000000710002"); + +/// The bytes of data each `LOG0` of the log-heavy callee carries. +const LOG_DATA: u64 = 512; + +/* ---------- static costs ---------- */ + +// revm's Amsterdam table, which Satin keeps. + +/// `GAS`, `PUSH0`, `POP`. +const G_BASE: u64 = 2; +/// `PUSHn`, `DUPn`, `SWAPn`, `ADD`, `SUB`, `LT`, `GT`, `ISZERO`, `MSTORE`. +const G_VERYLOW: u64 = 3; +/// `JUMPDEST`. +const G_JUMPDEST: u64 = 1; +/// `JUMP`. +const G_JUMP: u64 = 8; +/// `JUMPI`. +const G_JUMPI: u64 = 10; +/// A `LOG`'s base cost. +const G_LOG: u64 = 375; +/// A `LOG`'s cost per topic. +const G_LOG_TOPIC: u64 = 375; +/// A `LOG`'s cost per byte of data. +const G_LOG_DATA: u64 = 8; +/// A fresh `SSTORE` to a cold slot: `sstore_static` 100, `cold_storage_additional_cost` 2,000 +/// and `sstore_set_without_load_cost` 10,000. +const G_SSTORE_SET_COLD: u64 = 100 + 2_000 + 10_000; +/// EIP-2200's sentry: an `SSTORE` needs more regular gas than the call stipend. +const SSTORE_SENTRY: u64 = 2_300; +/// A `CALL` without value to a cold account: the warm access 100 and the cold surcharge 2,900. +const G_CALL_COLD: u64 = 100 + 2_900; +/// The intrinsic regular gas of a call with no calldata: `TX_BASE_COST` 12,000 and 3,000 for the +/// recipient's access. +const INTRINSIC: u64 = 12_000 + 3_000; + +/// The gas limits of the sweep. +const SWEEP: [u64; 5] = [400_000_000, 800_000_000, 1_200_000_000, 1_600_000_000, 2_000_000_000]; + +/* ---------- the pool model ---------- */ + +/// A frame ran out of gas. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Halt; + +/// A frame's two pools — its regular gas and the EIP-8037 reservoir — and the state and history +/// gas its charges spilled onto its regular gas, which a returning child's reservoir unwinds +/// first. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Pools { + regular: u64, + reservoir: u64, + spill: u64, +} + +impl Pools { + const fn new(regular: u64, reservoir: u64) -> Self { + Self { regular, reservoir, spill: 0 } + } + + /// A regular charge draws regular gas only. + fn regular(&mut self, cost: u64) -> Result<(), Halt> { + self.regular = self.regular.checked_sub(cost).ok_or(Halt)?; + Ok(()) + } + + /// A state or history charge draws the reservoir first and spills the rest onto regular gas. + fn draw(&mut self, cost: u64) -> Result<(), Halt> { + let from_reservoir = cost.min(self.reservoir); + let spill = cost - from_reservoir; + if spill > self.regular { + return Err(Halt); + } + self.reservoir -= from_reservoir; + self.regular -= spill; + self.spill += spill; + Ok(()) + } + + /// A call's start forwarding `gas` of regular gas: the child gets it and the reservoir's + /// share, all but this frame's 2 per cent, whatever `gas` is, and starts with no spill. + fn forward(&mut self, gas: u64) -> Self { + let reservoir = reservoir_share(self.reservoir); + self.regular -= gas; + self.reservoir -= reservoir; + Self::new(gas, reservoir) + } + + /// A child's return, handing back `child`: its regular gas comes back, a kept child's spill + /// joins this frame's, and the reservoir it hands back unwinds this frame's spill onto its + /// regular gas before the rest joins what this frame kept. + fn absorb(&mut self, child: Self, kept: bool) { + self.regular += child.regular; + if kept { + self.spill += child.spill; + } + let unwound = child.reservoir.min(self.spill); + self.regular += unwound; + self.spill -= unwound; + self.reservoir += child.reservoir - unwound; + } +} + +/// The pools the transaction's own frame starts with: the regular gas the execution cap leaves +/// once the intrinsic gas is paid, and the gas limit above the cap. The body's history is paid +/// before the frame, from the reservoir first, so none of it is a spill of the frame's. +fn first_frame(gas_limit: u64) -> Pools { + let mut pools = Pools::new( + gas_limit.min(TX_GAS_LIMIT_CAP) - INTRINSIC, + gas_limit.saturating_sub(TX_GAS_LIMIT_CAP), + ); + pools.draw(body_history(0)).expect("the body fits"); + Pools { spill: 0, ..pools } +} + +/// A limit's stop: the dimension crossed, the budget the frame was given, which the stop names, +/// and the frame's count with the crossing charge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Stop { + kind: LimitKind, + limit: u64, + used: u64, +} + +/// A frame's data-size, KV and state-growth budgets: what it was given and what it has left. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Budget { + given: LimitUsage, + left: LimitUsage, +} + +impl Budget { + /// The transaction's own frame's: what the transaction's limits leave once its body is + /// counted. + const fn first_frame() -> Self { + let given = LimitUsage { + data_size: TX_DATA_LIMIT - TX_BODY_SIZE, + write_records: TX_KV_UPDATE_LIMIT, + state_growth: TX_STATE_GROWTH_LIMIT, + }; + Self { given, left: given } + } + + /// No budget at all. + const fn unlimited() -> Self { + let given = + LimitUsage { data_size: u64::MAX, write_records: u64::MAX, state_growth: u64::MAX }; + Self { given, left: given } + } + + /// A child's: 98/100 of what this frame has left in each dimension, rounded down. + fn child(&self) -> Self { + let given = LimitUsage { + data_size: share(self.left.data_size), + write_records: share(self.left.write_records), + state_growth: share(self.left.state_growth), + }; + Self { given, left: given } + } + + /// Counts `counted`, or stops on the first dimension it crosses, in the order data size, KV + /// updates, state growth, counting nothing. + fn count(&mut self, counted: LimitUsage) -> Result<(), Stop> { + let dimensions = [ + (LimitKind::DataSize, counted.data_size, self.left.data_size, self.given.data_size), + ( + LimitKind::KvUpdate, + counted.write_records, + self.left.write_records, + self.given.write_records, + ), + ( + LimitKind::StateGrowth, + counted.state_growth, + self.left.state_growth, + self.given.state_growth, + ), + ]; + for (kind, add, left, limit) in dimensions { + if add > left { + return Err(Stop { kind, limit, used: limit - left + add }); + } + } + self.merge(counted); + Ok(()) + } + + /// Takes `kept` out of what this frame has left: what it counted, or what a child that + /// returned kept. + fn merge(&mut self, kept: LimitUsage) { + self.left.data_size -= kept.data_size; + self.left.write_records -= kept.write_records; + self.left.state_growth -= kept.state_growth; + } +} + +/// The sum of two counts. +const fn plus(a: LimitUsage, b: LimitUsage) -> LimitUsage { + LimitUsage { + data_size: a.data_size + b.data_size, + write_records: a.write_records + b.write_records, + state_growth: a.state_growth + b.state_growth, + } +} + +/// `a` less `b`: what a frame counted of a budget `a` when it has `b` left. +const fn minus(a: LimitUsage, b: LimitUsage) -> LimitUsage { + LimitUsage { + data_size: a.data_size - b.data_size, + write_records: a.write_records - b.write_records, + state_growth: a.state_growth - b.state_growth, + } +} + +/// What a fresh slot counts: its write record's bytes, the record, and the new slot. +const SLOT_COUNTS: LimitUsage = + LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1, state_growth: 1 }; + +/// What the transaction counts before its frame: its body. +const BODY_COUNTS: LimitUsage = + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }; + +/* ---------- the callee ---------- */ + +/// The charging opcode the callee's loop repeats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Charge { + /// `LOG0` of [`LOG_DATA`] bytes: history only. + Log0Data, + /// `LOG4` of no data: history only. + Log4, + /// A fresh `SSTORE`: state and history. + FreshSlot, +} + +impl Charge { + fn name(self) -> &'static str { + match self { + Self::Log0Data => "LOG0 512 B", + Self::Log4 => "LOG4 0 B", + Self::FreshSlot => "fresh SSTORE", + } + } + + fn opcode(self) -> u8 { + match self { + Self::Log0Data => LOG0, + Self::Log4 => LOG4, + Self::FreshSlot => SSTORE, + } + } + + /// Code that runs once before the loop: `LOG0` reads its data from memory expanded here, so + /// no iteration pays an expansion. + fn prologue(self) -> Vec { + match self { + Self::Log0Data => { + let [hi, lo] = ((LOG_DATA - 32) as u16).to_be_bytes(); + vec![PUSH0, PUSH2, hi, lo, MSTORE] + } + Self::Log4 | Self::FreshSlot => vec![], + } + } + + fn prologue_regular(self) -> u64 { + match self { + Self::Log0Data => { + let words = LOG_DATA / 32; + G_BASE + 2 * G_VERYLOW + 3 * words + words * words / 512 + } + Self::Log4 | Self::FreshSlot => 0, + } + } + + /// The opcodes that push the charging opcode's operands, run with the loop's `[i, g0]` on the + /// stack; the opcode follows and leaves the stack so. + fn operands(self) -> Vec { + match self { + Self::Log0Data => { + let [hi, lo] = (LOG_DATA as u16).to_be_bytes(); + vec![PUSH2, hi, lo, PUSH0] + } + Self::Log4 => vec![PUSH0; 6], + // `SSTORE(key = i, value = 1)`: the counter is a fresh slot each iteration. + Self::FreshSlot => vec![PUSH1, 1, DUP3], + } + } + + fn operands_regular(self) -> u64 { + match self { + Self::Log0Data => G_VERYLOW + G_BASE, + Self::Log4 => 6 * G_BASE, + Self::FreshSlot => 2 * G_VERYLOW, + } + } + + /// The charging opcode's regular gas. + fn opcode_regular(self) -> u64 { + match self { + Self::Log0Data => G_LOG + G_LOG_DATA * LOG_DATA, + Self::Log4 => G_LOG + 4 * G_LOG_TOPIC, + Self::FreshSlot => G_SSTORE_SET_COLD, + } + } + + /// The regular gas of one charge, operands included: what an iteration's `GAS` drop is when + /// the reservoir paid the whole charge, less the closing `GAS`. + fn body_regular(self) -> u64 { + self.operands_regular() + self.opcode_regular() + } + + /// The bytes one charge appends: a log's 32 for its address and 32 per topic plus its data, + /// a write record's 40. + fn bytes(self) -> u64 { + match self { + Self::Log0Data => 32 + LOG_DATA, + Self::Log4 => 32 + 4 * 32, + Self::FreshSlot => WRITE_RECORD_SIZE, + } + } + + /// What one charge counts against the frame's budgets: a log its bytes, a fresh slot its + /// record's bytes, the record and the new slot. + fn counts(self) -> LimitUsage { + match self { + Self::Log0Data | Self::Log4 => { + LimitUsage { data_size: self.bytes(), write_records: 0, state_growth: 0 } + } + Self::FreshSlot => SLOT_COUNTS, + } + } + + /// The state gas of one charge. + fn state(self) -> u64 { + match self { + Self::Log0Data | Self::Log4 => 0, + Self::FreshSlot => slot_state_gas(), + } + } + + /// The history gas of one charge. + fn history(self) -> u64 { + history(self.bytes()) + } + + /// The regular gas the callee keeps before another iteration: that iteration with its whole + /// charge spilled onto regular gas, and the way out. + fn reserve(self) -> u64 { + self.body_regular() + LOOP_REGULAR + self.state() + self.history() + 64 + } +} + +// The callee's loop: its regular gas outside the charge. + +/// `JUMPDEST GAS`, which opens an iteration. +const LOOP_ENTRY: u64 = G_JUMPDEST + G_BASE; +/// `DUP1 PUSH4 GT PUSH2 JUMPI`: out when the regular gas left is below the reserve. +const RESERVE_CHECK: u64 = 4 * G_VERYLOW + G_JUMPI; +/// `SWAP1 SUB PUSH4 LT PUSH2 JUMPI`: out when the drop exceeds the charge's regular gas. +const DROP_CHECK: u64 = 5 * G_VERYLOW + G_JUMPI; +/// `PUSH1 ADD PUSH2 JUMP`: the counter, and back to the top. +const LOOP_NEXT: u64 = 3 * G_VERYLOW + G_JUMP; +/// One iteration's regular gas outside the charge, the closing `GAS` included. +const LOOP_REGULAR: u64 = LOOP_ENTRY + G_BASE + RESERVE_CHECK + DROP_CHECK + LOOP_NEXT; + +/// What `C` runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Callee { + /// `STOP`: returns at once, charging nothing. + Stop, + /// `INVALID`: halts, burning its whole forward and charging nothing else. It spends what a + /// single pool's forward rule lets a callee spend, and no more. + Burn, + /// The loop of `charge`; `stop_on_spill` stops it on the first iteration the reservoir did + /// not pay in full. + Loop { charge: Charge, stop_on_spill: bool }, +} + +impl Callee { + const fn stops_on_spill(charge: Charge) -> Self { + Self::Loop { charge, stop_on_spill: true } + } + + const fn greedy(charge: Charge) -> Self { + Self::Loop { charge, stop_on_spill: false } + } + + fn name(self) -> String { + match self { + Self::Stop => "STOP".into(), + Self::Burn => "INVALID".into(), + Self::Loop { charge, stop_on_spill: true } => charge.name().into(), + Self::Loop { charge, stop_on_spill: false } => format!("{}, greedy", charge.name()), + } + } + + fn charge(self) -> Option { + match self { + Self::Stop | Self::Burn => None, + Self::Loop { charge, .. } => Some(charge), + } + } + + fn code(self) -> Bytes { + let (charge, stop_on_spill) = match self { + Self::Stop => return Bytes::from_static(&[STOP]), + Self::Burn => return Bytes::from_static(&[INVALID]), + Self::Loop { charge, stop_on_spill } => (charge, stop_on_spill), + }; + // The drop that stops the loop: the charge's regular gas and the closing `GAS`. + let stop_above = + if stop_on_spill { charge.body_regular() + G_BASE } else { u64::from(u32::MAX) }; + let u32_bytes = |value: u64| u32::try_from(value).expect("fits a PUSH4").to_be_bytes(); + + let mut code = charge.prologue(); + code.push(PUSH0); + let top = code.len(); + code.extend([JUMPDEST, GAS]); + code.extend(charge.operands()); + code.push(charge.opcode()); + // [i, g0, g1]: out when g1 < reserve. + code.extend([GAS, DUP1, PUSH4]); + code.extend(u32_bytes(charge.reserve())); + code.extend([GT, PUSH2, 0, 0, JUMPI]); + let out_on_reserve = code.len() - 3; + // [i, g0 - g1]: out when the drop exceeds the charge's regular gas. + code.extend([SWAP1, SUB, PUSH4]); + code.extend(u32_bytes(stop_above)); + code.extend([LT, PUSH2, 0, 0, JUMPI]); + let out_on_drop = code.len() - 3; + code.extend([PUSH1, 1, ADD, PUSH2]); + code.extend((top as u16).to_be_bytes()); + code.push(JUMP); + let out = (code.len() as u16).to_be_bytes(); + code.extend([JUMPDEST, STOP]); + code[out_on_reserve..out_on_reserve + 2].copy_from_slice(&out); + code[out_on_drop..out_on_drop + 2].copy_from_slice(&out); + code.into() + } +} + +/// How `C` ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CalleeEnd { + Returned, + /// A charge crossed one of `C`'s budgets: `C` reverts with the stop. + Crossed(Stop), + Halted, +} + +/// What the model says `C` does. +#[derive(Clone, Copy, Debug)] +struct CalleeModel { + end: CalleeEnd, + /// Charging opcodes started, the one that crossed or halted included. + charges: u64, + /// `C`'s pools at its end, before the revert of a crossing gives its charges back. + at_end: Pools, + /// The pools `C` hands back to `A`. + handed_back: Pools, + /// The state and history gas of the charges `C` kept. + state: u64, + history: u64, + /// What `C` kept of its budgets. + kept: LimitUsage, +} + +/// `C` run on the pools `start` and the budgets `budget` its start handed it. +fn model_callee(callee: Callee, start: Pools, budget: Budget) -> CalleeModel { + let (charge, stop_on_spill) = match callee { + Callee::Stop | Callee::Burn => { + // `INVALID` charged nothing, so its halt hands the share back whole. + let (end, handed_back) = match callee { + Callee::Stop => (CalleeEnd::Returned, start), + _ => (CalleeEnd::Halted, Pools::new(0, start.reservoir)), + }; + return CalleeModel { + end, + charges: 0, + at_end: handed_back, + handed_back, + state: 0, + history: 0, + kept: LimitUsage::ZERO, + }; + } + Callee::Loop { charge, stop_on_spill } => (charge, stop_on_spill), + }; + let mut pools = start; + let mut budget = budget; + let mut charges = 0; + let (mut state, mut history) = (0, 0); + let end = (|| -> Result { + pools.regular(charge.prologue_regular() + G_BASE)?; + loop { + pools.regular(LOOP_ENTRY)?; + let g0 = pools.regular; + pools.regular(charge.operands_regular())?; + charges += 1; + if charge == Charge::FreshSlot && pools.regular <= SSTORE_SENTRY { + return Err(Halt); + } + pools.regular(charge.opcode_regular())?; + pools.draw(charge.state())?; + // The completed-write hook counts the write before it charges its history. + if let Err(stop) = budget.count(charge.counts()) { + return Ok(CalleeEnd::Crossed(stop)); + } + pools.draw(charge.history())?; + state += charge.state(); + history += charge.history(); + pools.regular(G_BASE)?; + let g1 = pools.regular; + pools.regular(RESERVE_CHECK)?; + if g1 < charge.reserve() { + pools.regular(G_JUMPDEST)?; + return Ok(CalleeEnd::Returned); + } + pools.regular(DROP_CHECK)?; + if stop_on_spill && g0 - g1 > charge.body_regular() + G_BASE { + pools.regular(G_JUMPDEST)?; + return Ok(CalleeEnd::Returned); + } + pools.regular(LOOP_NEXT)?; + } + })() + .unwrap_or(CalleeEnd::Halted); + let (handed_back, kept) = match end { + CalleeEnd::Returned => (pools, minus(budget.given, budget.left)), + // The revert gives the charges back: what the reservoir paid to the share, what spilled + // to the regular gas it hands back. + CalleeEnd::Crossed(_) => { + (Pools::new(pools.regular + pools.spill, start.reservoir), LimitUsage::ZERO) + } + CalleeEnd::Halted => (Pools::new(0, start.reservoir), LimitUsage::ZERO), + }; + let (state, history) = if end == CalleeEnd::Returned { (state, history) } else { (0, 0) }; + CalleeModel { end, charges, at_end: pools, handed_back, state, history, kept } +} + +/* ---------- the caller ---------- */ + +/// The gas `A` forwards. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Forward { + Explicit(u64), + /// `GAS` as the call's gas, more than the cap: all but 2 per cent of what is left after the + /// call's cost. + All, +} + +impl Forward { + fn name(self) -> String { + match self { + Self::Explicit(gas) => gas.to_string(), + Self::All => "all but 2/100".into(), + } + } +} + +/// `A`'s code, writing `work` fresh slots after the call. +fn caller_code(forward: Forward, work: u64) -> Bytes { + let mut code = vec![GAS, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20]; + code.extend(C); + match forward { + Forward::Explicit(gas) => { + code.push(PUSH4); + code.extend(u32::try_from(gas).expect("fits a PUSH4").to_be_bytes()); + } + Forward::All => code.push(GAS), + } + code.extend([CALL, GAS, PUSH4]); + code.extend(u32::try_from(work).expect("fits a PUSH4").to_be_bytes()); + // [gas0, ok, gas1, k]: while k != 0, `SSTORE(k, 1)` and k -= 1. + let top = code.len() as u16; + code.extend([JUMPDEST, DUP1, ISZERO, PUSH2, 0, 0, JUMPI]); + let out_at = code.len() - 3; + code.extend([PUSH1, 1, DUP2, SSTORE, PUSH1, 1, SWAP1, SUB, PUSH2]); + code.extend(top.to_be_bytes()); + code.push(JUMP); + let out = (code.len() as u16).to_be_bytes(); + code[out_at..out_at + 2].copy_from_slice(&out); + // Returns `gas0`, `ok` and `gas1`, a word each. + code.extend([JUMPDEST, POP, PUSH1, 0x40, MSTORE, PUSH1, 0x20, MSTORE, PUSH0, MSTORE]); + code.extend([PUSH1, 0x60, PUSH0, RETURN]); + code.into() +} + +/// `A`'s regular gas before the `SSTORE` of one fresh slot of its work: `JUMPDEST DUP1 ISZERO +/// PUSH2 JUMPI PUSH1 DUP2`. +const WORK_BEFORE: u64 = G_JUMPDEST + 5 * G_VERYLOW + G_JUMPI; +/// `A`'s regular gas after the `SSTORE`: `PUSH1 SWAP1 SUB PUSH2 JUMP`. +const WORK_AFTER: u64 = 4 * G_VERYLOW + G_JUMP; +/// The way out: the last `JUMPDEST DUP1 ISZERO PUSH2 JUMPI`, `JUMPDEST POP`, three `MSTORE`s with +/// their pushes and the expansion to three words, and `PUSH1 PUSH0 RETURN`. +const WORK_OUT: u64 = (G_JUMPDEST + 3 * G_VERYLOW + G_JUMPI) + + (G_JUMPDEST + G_BASE) + + (2 * (G_VERYLOW + G_VERYLOW) + G_BASE + G_VERYLOW + 3 * 3) + + (G_VERYLOW + G_BASE); + +/// How `A`'s work ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WorkEnd { + /// `A` returns, on these pools. + Completed(Pools), + /// A charge ran out of gas: the transaction halts. + OutOfGas, + /// A slot crossed one of `A`'s budgets: `A` reverts with the stop, on these pools. + Stopped(Stop, Pools), +} + +impl WorkEnd { + const fn completed(self) -> bool { + matches!(self, Self::Completed(_)) + } +} + +/// How `A`'s work of `slots` fresh slots, run on `pools` and `budget` after its second `GAS`, +/// ends. +fn model_work(slots: u64, mut pools: Pools, mut budget: Budget) -> WorkEnd { + let mut work = || -> Result { + pools.regular(G_VERYLOW)?; + for _ in 0..slots { + pools.regular(WORK_BEFORE)?; + if pools.regular <= SSTORE_SENTRY { + return Err(Halt); + } + pools.regular(G_SSTORE_SET_COLD)?; + pools.draw(slot_state_gas())?; + if let Err(stop) = budget.count(SLOT_COUNTS) { + return Ok(WorkEnd::Stopped(stop, pools)); + } + pools.draw(history(WRITE_RECORD_SIZE))?; + pools.regular(WORK_AFTER)?; + } + pools.regular(WORK_OUT)?; + Ok(WorkEnd::Completed(pools)) + }; + work().unwrap_or(WorkEnd::OutOfGas) +} + +/// The most fresh slots `A` completes on `pools` and `budget`. +fn capacity(pools: Pools, budget: Budget) -> u64 { + let bound = (pools.regular / G_SSTORE_SET_COLD).min(budget.left.state_growth); + let (mut fits, mut fails) = (0, bound + 1); + while fails - fits > 1 { + let mid = (fits + fails) / 2; + if model_work(mid, pools, budget).completed() { + fits = mid; + } else { + fails = mid; + } + } + fits +} + +/// One run: a gas limit, the gas `A` forwards and what `C` runs. +#[derive(Clone, Copy, Debug)] +struct Scenario { + gas_limit: u64, + forward: Forward, + callee: Callee, +} + +/// What the model says the run does. +#[derive(Clone, Copy, Debug)] +struct Prediction { + /// The reservoir once the body is paid: what `A` holds at its call. + reservoir_at_call: u64, + gas_before_call: u64, + regular_at_call: u64, + /// The regular gas and the reservoir the call hands `C`. + handed: Pools, + /// `C`'s budgets: 98/100 of what `A` has left, which is the transaction's limits less the + /// body. + budget: Budget, + callee: CalleeModel, + /// `A`'s pools once `C` returned, before its second `GAS`. + pools_after_return: Pools, + gas_after_call: u64, + pools_after_call: Pools, + /// `A`'s budgets once `C` returned. + budget_after_call: Budget, + /// `A`'s work: unless a run names it, the most fresh slots `A` completes after a callee that + /// spent exactly its forward of regular gas and charged the reservoir nothing. + work: u64, + /// The most fresh slots `A` could complete after the call as it happened. + capacity_after_call: u64, + /// How `A`'s work ends. + end: WorkEnd, +} + +fn predict(scenario: Scenario, work: Option) -> Prediction { + let Scenario { gas_limit, forward, callee } = scenario; + let mut pools = first_frame(gas_limit); + let reservoir_at_call = pools.reservoir; + pools.regular(G_BASE).unwrap(); + let gas_before_call = pools.regular; + let gas_operand = match forward { + Forward::Explicit(_) => G_VERYLOW, + Forward::All => G_BASE, + }; + pools.regular(5 * G_BASE + G_VERYLOW + gas_operand).unwrap(); + let regular_at_call = pools.regular; + pools.regular(G_CALL_COLD).unwrap(); + let cap = forward_cap(pools.regular); + let forward = match forward { + Forward::Explicit(gas) => gas.min(cap), + Forward::All => cap, + }; + let handed = pools.forward(forward); + let mut budget_after_call = Budget::first_frame(); + let budget = budget_after_call.child(); + let callee = model_callee(callee, handed, budget); + + // After a callee that burns its forward and charges the reservoir nothing. + let mut kept_by_a_single_pool = pools; + kept_by_a_single_pool.absorb(Pools::new(0, handed.reservoir), false); + kept_by_a_single_pool.regular(G_BASE).unwrap(); + let work = work.unwrap_or_else(|| capacity(kept_by_a_single_pool, budget_after_call)); + + pools.absorb(callee.handed_back, callee.end == CalleeEnd::Returned); + budget_after_call.merge(callee.kept); + let pools_after_return = pools; + pools.regular(G_BASE).unwrap(); + Prediction { + reservoir_at_call, + gas_before_call, + regular_at_call, + handed, + budget, + callee, + pools_after_return, + gas_after_call: pools.regular, + pools_after_call: pools, + budget_after_call, + work, + capacity_after_call: capacity(pools, budget_after_call), + end: model_work(work, pools, budget_after_call), + } +} + +/* ---------- the meter ---------- */ + +/// What `C`'s frame held when it returned to `A`. +#[derive(Clone, Debug)] +struct Returned { + result: InstructionResult, + output: Bytes, + pools: Pools, + history: i64, + state: i64, +} + +/// A frame's pools as an inspector reads them. +fn pools_of(gas: &revm::interpreter::Gas) -> Pools { + Pools { regular: gas.remaining(), reservoir: gas.reservoir(), spill: gas.state_gas_spilled() } +} + +/// Reads `A`'s `GAS` around the call, its pools at the call and after it, what the call hands +/// `C`, what a creation `C` makes is handed, the charges `C` starts and what its frame holds at +/// its return. +#[derive(Clone, Debug, Default)] +struct Meter { + charge: Option, + frames: usize, + gas_pending: bool, + gas_before_call: Option, + gas_after_call: Option, + at_call: Option, + handed: Option, + created_with: Option, + returned: Option, + after_return: Option, + charges: u64, +} + +impl Inspector, EthInterpreter> for Meter { + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + let opcode = interp.bytecode.opcode(); + match self.frames { + 1 => { + if self.returned.is_some() && self.after_return.is_none() { + self.after_return = Some(pools_of(&interp.gas)); + } + if opcode == CALL && self.at_call.is_none() { + self.at_call = Some(pools_of(&interp.gas)); + } + self.gas_pending = opcode == GAS; + } + 2 if Some(opcode) == self.charge => self.charges += 1, + _ => {} + } + } + + fn step_end(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + if !core::mem::take(&mut self.gas_pending) { + return; + } + let gas = interp.stack.peek(0).expect("GAS pushed its answer").to::(); + if self.returned.is_some() { + self.gas_after_call.get_or_insert(gas); + } else { + self.gas_before_call.get_or_insert(gas); + } + } + + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.frames += 1; + if inputs.target_address == C { + self.handed = Some(Pools::new(inputs.gas_limit, inputs.reservoir)); + } + None + } + + fn call_end( + &mut self, + _: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == C { + let gas = &outcome.result.gas; + self.returned = Some(Returned { + result: outcome.result.result, + output: outcome.result.output.clone(), + pools: pools_of(gas), + history: gas.history_gas_spent(), + state: gas.state_gas_spent(), + }); + } + self.frames -= 1; + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.frames += 1; + self.created_with = Some(Pools::new(inputs.gas_limit(), inputs.reservoir())); + None + } + + fn create_end(&mut self, _: &mut MegaContext, _: &CreateInputs, _: &mut CreateOutcome) { + self.frames -= 1; + } +} + +/* ---------- the run ---------- */ + +/// One run's measured figures. +#[derive(Clone, Debug)] +struct Measured { + scenario: Scenario, + prediction: Prediction, + gas_before_call: u64, + gas_after_call: u64, + reservoir_at_call: u64, + handed: Pools, + reservoir_after_call: u64, + callee: Returned, + charges: u64, + outcome: MegaTransactionOutcome, +} + +impl Measured { + fn forward(&self) -> u64 { + self.prediction.handed.regular + } + + /// The regular gas `C` spent of its forward, spills included: all of it when `C` halted. + fn callee_regular(&self) -> u64 { + if self.callee.result.is_halt() { + return self.forward(); + } + self.forward() - self.callee.pools.regular + } + + /// The reservoir `C` consumed: what `A` held at the call less what it holds after it. + fn consumed(&self) -> u64 { + self.reservoir_at_call - self.reservoir_after_call + } + + fn completed(&self) -> bool { + self.outcome.result.is_success() + } + + fn callee_end(&self) -> String { + match self.callee.result { + InstructionResult::Stop => "returned".into(), + InstructionResult::Revert => match decode_mega_limit_exceeded(&self.callee.output) { + Some((kind, limit)) => format!("reverted: {kind:?} stop at {limit}"), + None => "reverted".into(), + }, + other => format!("{other:?}"), + } + } + + fn status(&self) -> String { + status(&self.outcome) + } + + /// Whether `A`'s work needs the reservoir: it does not fit in `A`'s regular gas after the + /// call alone. + fn work_needs_reservoir(&self) -> bool { + needs_reservoir(self.prediction.work, self.gas_after_call) + } +} + +/// Whether `slots` fresh slots of `A`'s work run out of gas on `regular` gas alone, whatever the +/// budgets. +fn needs_reservoir(slots: u64, regular: u64) -> bool { + model_work(slots, Pools::new(regular, 0), Budget::unlimited()) == WorkEnd::OutOfGas +} + +fn status(outcome: &MegaTransactionOutcome) -> String { + match &outcome.result { + ExecutionResult::Success { .. } => "success".into(), + ExecutionResult::Revert { output, .. } => match decode_mega_limit_exceeded(output) { + Some((kind, limit)) => format!("revert: {kind:?} stop at {limit}"), + None => "revert".into(), + }, + ExecutionResult::Halt { reason, .. } => format!("halt: {reason:?}"), + } +} + +/// Runs `tx` on `db` under the meter, and again without it, and holds the two to the same +/// settlement. +#[track_caller] +fn execute_metered( + db: impl Fn() -> MemoryDatabase, + tx: impl Fn() -> MegaTransaction, + meter: Meter, + name: &str, +) -> (MegaTransactionOutcome, Meter) { + let mut evm = MegaEvm::new(context(db())).with_inspector(meter); + let outcome = evm.execute_transaction(tx()).expect("the transaction is valid"); + let meter = evm.inspector().clone(); + let plain = execute(db(), tx()); + assert_eq!(plain.result.is_success(), outcome.result.is_success(), "{name}: the inspector"); + assert_eq!(plain.gas, outcome.gas, "{name}: the ledgers under the inspector"); + assert_eq!(plain.usage, outcome.usage, "{name}: the usage under the inspector"); + (outcome, meter) +} + +/// Holds `outcome` to how the model says `A`'s work ends: `C` kept `callee`'s charges and counts +/// and `A`'s work its slots, or the transaction ended in a halt or a stop that kept neither. +#[track_caller] +fn assert_settled( + name: &str, + outcome: &MegaTransactionOutcome, + scenario: Scenario, + p: &Prediction, + callee: (u64, u64, LimitUsage), +) { + let (callee_state, callee_history, callee_kept) = callee; + let body = body_history(0); + let nothing_kept = |what: &str| { + assert_eq!( + outcome.gas.reservoir_remaining, p.reservoir_at_call, + "{name}: the reservoir comes back whole on {what}" + ); + assert_eq!(outcome.gas.history, body, "{name}: the body alone on {what}"); + assert_eq!(outcome.gas.state, 0, "{name}: no state on {what}"); + assert_eq!(outcome.usage, BODY_COUNTS, "{name}: the body's counts alone on {what}"); + }; + match p.end { + WorkEnd::Completed(left) => { + assert!( + outcome.result.is_success(), + "{name}: A's work completes: {:?}", + outcome.result + ); + assert_eq!( + outcome.gas.history, + body + callee_history + p.work * history(WRITE_RECORD_SIZE), + "{name}: the history ledger" + ); + assert_eq!( + outcome.gas.state, + callee_state + p.work * slot_state_gas(), + "{name}: the state ledger" + ); + assert_eq!( + outcome.gas.reservoir_remaining, left.reservoir, + "{name}: the reservoir left" + ); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - left.regular - left.reservoir, + "{name}: the receipt" + ); + let work_counts = LimitUsage { + data_size: p.work * WRITE_RECORD_SIZE, + write_records: p.work, + state_growth: p.work, + }; + assert_eq!( + outcome.usage, + plus(plus(BODY_COUNTS, callee_kept), work_counts), + "{name}: the counts" + ); + assert_eq!(outcome.limit_exceeded, None, "{name}: no stop"); + } + WorkEnd::OutOfGas => { + assert!( + matches!(outcome.result, ExecutionResult::Halt { .. }), + "{name}: A's work runs out of gas: {:?}", + outcome.result + ); + // The halt gives A's state and history back, C's merged charges included, and burns + // the regular gas: the receipt is the execution cap and the body. + nothing_kept("a halt"); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - p.reservoir_at_call, + "{name}: the receipt" + ); + } + WorkEnd::Stopped(stop, at) => { + assert!( + matches!(outcome.result, ExecutionResult::Revert { .. }), + "{name}: A's work is stopped: {:?}", + outcome.result + ); + assert_eq!( + decode_mega_limit_exceeded(outcome.result.output().unwrap()), + Some((stop.kind, stop.limit)), + "{name}: the stop A reverts with" + ); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: stop.kind, + limit: stop.limit, + used: stop.used, + frame_local: true + }), + "{name}: the stop the outcome names" + ); + // The revert gives A's state and history back, C's merged charges included, the + // spill to the regular gas, which comes back to the sender with the reservoir. + nothing_kept("a stop"); + assert_eq!( + outcome.gas.gas_used, + scenario.gas_limit - p.reservoir_at_call - at.regular - at.spill, + "{name}: the receipt" + ); + } + } +} + +/// Runs `scenario` with and without the meter, holds both runs to the model, and returns what +/// the meter read. +#[track_caller] +fn run(scenario: Scenario) -> Measured { + run_with(scenario, None) +} + +/// [`run`], with `A` writing `work` fresh slots when it is named. +#[track_caller] +fn run_with(scenario: Scenario, work: Option) -> Measured { + let prediction = predict(scenario, work); + let name = format!( + "{} at a {} gas limit, forwarding {}", + scenario.callee.name(), + scenario.gas_limit, + scenario.forward.name() + ); + let db = || { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_code(A, caller_code(scenario.forward, prediction.work)) + .account_code(C, scenario.callee.code()) + }; + let tx = || call(SENDER, A, U256::ZERO, scenario.gas_limit); + + let meter = + Meter { charge: scenario.callee.charge().map(Charge::opcode), ..Default::default() }; + let (outcome, meter) = execute_metered(db, tx, meter, &name); + + let after_return = meter.after_return.expect("A resumed"); + let measured = Measured { + scenario, + prediction, + gas_before_call: meter.gas_before_call.expect("A read GAS before the call"), + gas_after_call: meter.gas_after_call.expect("A read GAS after the call"), + reservoir_at_call: meter.at_call.expect("A called").reservoir, + handed: meter.handed.expect("A called C"), + reservoir_after_call: after_return.reservoir, + callee: meter.returned.clone().expect("C returned"), + charges: meter.charges, + outcome, + }; + let p = &prediction; + + // The reservoir is the gas limit above the execution cap, less the body [S4.4]. + assert_eq!( + meter.at_call, + Some(Pools::new(p.regular_at_call, p.reservoir_at_call)), + "{name}: A's pools at the call" + ); + // `GAS` reads the regular budget, not the reservoir. + assert_eq!(measured.gas_before_call, p.gas_before_call, "{name}: A's GAS before the call"); + // A call forwards at most all but 2 per cent of the regular gas, and the child gets all but + // 2 per cent of the reservoir whatever the call asks for. + assert_eq!(measured.handed, p.handed, "{name}: what the call hands C"); + assert_eq!(measured.charges, p.callee.charges, "{name}: the charges C started"); + match p.callee.end { + CalleeEnd::Returned => { + assert_eq!(measured.callee.result, InstructionResult::Stop, "{name}: C returns"); + assert_eq!( + measured.callee.history, p.callee.history as i64, + "{name}: the history C charged" + ); + assert_eq!(measured.callee.state, p.callee.state as i64, "{name}: the state C charged"); + assert_eq!( + measured.callee.pools, p.callee.handed_back, + "{name}: the pools C hands back" + ); + } + CalleeEnd::Crossed(stop) => { + assert_eq!(measured.callee.result, InstructionResult::Revert, "{name}: C reverts"); + assert_eq!( + decode_mega_limit_exceeded(&measured.callee.output), + Some((stop.kind, stop.limit)), + "{name}: C's budget stopped it" + ); + // A frame's end shows its gas before the settlement: the history of every charge + // before the crossing one, which the caller's merge then gives back to the reservoir. + let charge = scenario.callee.charge().unwrap(); + let charged = (p.callee.charges - 1) * charge.history(); + assert_eq!(measured.callee.history, charged as i64, "{name}: the history C charged"); + assert_eq!(measured.callee.pools, p.callee.at_end, "{name}: C's pools at its end"); + } + CalleeEnd::Halted => { + assert_eq!(scenario.callee, Callee::Burn, "{name}: only INVALID halts C"); + assert_eq!( + measured.callee.result, + InstructionResult::InvalidFEOpcode, + "{name}: C halts" + ); + } + } + // What C hands back, its reservoir unwinding A's spill first, is what A holds after the call. + assert_eq!(after_return, p.pools_after_return, "{name}: A's pools after the call"); + assert_eq!(measured.gas_after_call, p.gas_after_call, "{name}: A's GAS after the call"); + + let callee = (p.callee.state, p.callee.history, p.callee.kept); + assert_settled(&name, &measured.outcome, scenario, p, callee); + if p.end.completed() { + let words: Vec = measured + .outcome + .result + .output() + .expect("A returns") + .chunks(32) + .map(U256::from_be_slice) + .collect(); + assert_eq!( + words, + [ + U256::from(p.gas_before_call), + U256::from(u64::from(p.callee.end == CalleeEnd::Returned)), + U256::from(p.gas_after_call) + ], + "{name}: A's GAS around the call and the call's flag, as A read them" + ); + } + measured +} + +/* ---------- the tables ---------- */ + +fn ratio(numerator: u64, denominator: u64) -> String { + format!("{:.2}", numerator as f64 / denominator as f64) +} + +fn print_table(title: &str, rows: &[Measured]) { + println!("\n### {title}\n"); + println!( + "| gas limit | C | forward | charges | C regular spent | C history charged | \ + C state charged | reservoir at call | reservoir to C | reservoir at return | consumed | \ + consumed / forward | (regular + consumed) / forward | A GAS before | A GAS after | \ + A work (slots) | work needs reservoir | A capacity after | C end | status | gas used |" + ); + println!("|{}", "---:|".repeat(21)); + for row in rows { + println!( + "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | \ + {} | {} | {} | {} | {} |", + row.scenario.gas_limit, + row.scenario.callee.name(), + row.forward(), + row.charges, + row.callee_regular(), + row.callee.history, + row.callee.state, + row.reservoir_at_call, + row.handed.reservoir, + row.reservoir_after_call, + row.consumed(), + ratio(row.consumed(), row.forward()), + ratio(row.callee_regular() + row.consumed(), row.forward()), + row.gas_before_call, + row.gas_after_call, + row.prediction.work, + if row.work_needs_reservoir() { "yes" } else { "no" }, + row.prediction.capacity_after_call, + row.callee_end(), + row.status(), + row.outcome.gas.gas_used, + ); + } +} + +/* ---------- the measurements ---------- */ + +/// One slot of `A`'s work, from both pools: its regular gas and its state and history. +fn slot_cost() -> u64 { + WORK_BEFORE + G_SSTORE_SET_COLD + WORK_AFTER + slot_state_gas() + history(WRITE_RECORD_SIZE) +} + +/// With a 400M gas limit and a forward of 1M, a callee that returns at once leaves `A` the whole +/// reservoir, and a callee that logs until its regular gas runs low charges ten times its forward +/// to its share of it. +/// +/// `A`'s work is the 1,000 slots the state-growth limit lets the transaction add, which `A`'s +/// regular gas pays for alone, so it completes after the log-heavy callee as after one that returns +/// at once, and the slot past it is the stop, kind 3, not an out-of-gas. A callee's charges still +/// reach `A`'s work where the callee spends both its shares: forwarding all, the greedy callee +/// leaves `A` the 2 per cent of its regular gas and of its reservoir that `A` kept, and the 329 +/// slots `A` completes after a callee that burns all it was forwarded run out of gas. +#[test] +fn test_a_log_heavy_callee_charges_past_its_forward_and_leaves_two_percent_of_each_pool() { + if runs_at_measurement_prices() { + return; + } + let scenario = + |callee| Scenario { gas_limit: 400_000_000, forward: Forward::Explicit(1_000_000), callee }; + let baseline = run(scenario(Callee::Stop)); + let heavy = run(scenario(Callee::stops_on_spill(Charge::Log0Data))); + // The work is what a callee that spends exactly its forward leaves room for, and no more. + let burns = run(scenario(Callee::Burn)); + let one_more = run_with(scenario(Callee::Burn), Some(burns.prediction.work + 1)); + print_table( + "1a. Baseline vs. a log-heavy callee (400M, forward 1M)", + &[baseline.clone(), heavy.clone(), burns.clone(), one_more.clone()], + ); + assert!(burns.completed(), "A's work completes after a callee that burns its forward"); + assert_eq!(burns.prediction.work, TX_STATE_GROWTH_LIMIT, "the state-growth limit binds it"); + assert_eq!( + decode_mega_limit_exceeded(one_more.outcome.result.output().unwrap()), + Some((LimitKind::StateGrowth, TX_STATE_GROWTH_LIMIT)), + "one slot more is the stop" + ); + + assert_eq!(baseline.consumed(), 0); + assert!(baseline.completed(), "A's work completes after a callee that charged nothing"); + // The Rex6 comparison in `mega-evme`'s tests runs this callee's bytes on the released + // engine, with these two numbers written out. + assert_eq!(Charge::Log0Data.body_regular() + G_BASE, 4_478, "the drop that stops C"); + assert_eq!(Charge::Log0Data.reserve(), 52_481, "the reserve C keeps"); + + assert!(heavy.callee_regular() <= heavy.forward(), "regular gas stays within the forward"); + assert!(heavy.reservoir_after_call > 0, "the forward ran out before the share"); + assert_eq!(heavy.consumed(), heavy.charges * Charge::Log0Data.history()); + assert!( + heavy.consumed() > 10 * heavy.forward(), + "the share pays ten times the forward: {}", + heavy.consumed() + ); + assert!( + heavy.callee_regular() + heavy.consumed() > heavy.forward() + slot_cost(), + "C charged more than its forward and one slot" + ); + assert!(!heavy.work_needs_reservoir(), "A's regular gas pays for the work alone"); + assert!(heavy.completed(), "so C's charges do not reach it"); + + // Forwarding all, after a callee that burns its forward and after one that spends both + // shares. + let all = |callee| Scenario { gas_limit: 400_000_000, forward: Forward::All, callee }; + let burns_all = run(all(Callee::Burn)); + let work = burns_all.prediction.work; + let greedy = run_with(all(Callee::greedy(Charge::Log0Data)), Some(work)); + print_table("1b. Forwarding all but 2/100 (400M)", &[burns_all.clone(), greedy.clone()]); + assert!(burns_all.completed()); + assert!(work < TX_STATE_GROWTH_LIMIT, "A's regular gas binds it: {work}"); + assert_eq!(greedy.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(greedy.callee.pools.reservoir, 0, "C spent its whole share"); + assert!(greedy.callee.pools.regular < Charge::Log0Data.reserve(), "and its forward"); + assert_eq!( + greedy.reservoir_after_call, + greedy.reservoir_at_call * 2 / 100, + "A keeps its 2 per cent of the reservoir" + ); + assert!( + greedy.callee_regular() + greedy.consumed() > greedy.forward() + slot_cost(), + "C charged more than its forward and one slot" + ); + assert!(!greedy.completed(), "the work A completes after a burned forward fails"); + assert_eq!(greedy.prediction.end, WorkEnd::OutOfGas, "out of gas"); +} + +/// The log-heavy callee at gas limits from 400M to 2B. A forward of 1M bounds it by its regular gas +/// at every limit: it consumes the same reservoir everywhere. Forwarding all but 2 per cent, it +/// consumes its whole share of the reservoir until the share outgrows what its 98/100 data-size +/// budget lets it log; from there its budget stops it first, it reverts, and its history comes back +/// to `A`. The threshold is exact: one gas less of reservoir and the share runs out first. +/// +/// The threshold is the gas limit whose share pays for the logs the budget holds, 1,353,400,537; +/// below it the callee leaves `A` its 2 per cent, and at 400M its share is just below its forward. +/// Either side of the threshold the 2 per cent `A` kept and the regular gas the callee left pay for +/// more than the 1,000 slots the state-growth limit lets `A` add, so that work, which needs the +/// reservoir, completes on both sides. +#[test] +fn test_the_frame_budget_binds_a_callee_once_the_reservoir_outgrows_it() { + if runs_at_measurement_prices() { + return; + } + let callee = Callee::stops_on_spill(Charge::Log0Data); + let at = |gas_limit, forward| run(Scenario { gas_limit, forward, callee }); + + let bounded: Vec<_> = + SWEEP.iter().map(|&limit| at(limit, Forward::Explicit(1_000_000))).collect(); + for row in &bounded { + assert_eq!(row.consumed(), bounded[0].consumed(), "the forward bounds what C logs"); + assert_eq!(row.callee.result, InstructionResult::Stop); + } + + // The budget stops the log that takes C past it, before its history is charged. The share + // pays every earlier log in full once it holds their history. + let budget = share(TX_DATA_LIMIT - TX_BODY_SIZE); + let kept = budget / Charge::Log0Data.bytes(); + let threshold = + TX_GAS_LIMIT_CAP + body_history(0) + reservoir_giving(kept * Charge::Log0Data.history()); + + let mut all: Vec<_> = SWEEP.iter().map(|&limit| at(limit, Forward::All)).collect(); + all.push(at(threshold - 1, Forward::All)); + all.push(at(threshold, Forward::All)); + all.sort_by_key(|row| row.scenario.gas_limit); + for row in &all { + assert_eq!(row.prediction.budget.given.data_size, budget, "C's data-size budget"); + if row.scenario.gas_limit < threshold { + assert_eq!(row.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(row.consumed(), row.handed.reservoir, "C consumed its whole share"); + assert_eq!( + row.reservoir_after_call, + row.reservoir_at_call * 2 / 100, + "A keeps its 2 per cent" + ); + assert_eq!( + row.consumed() > row.forward(), + row.scenario.gas_limit > 400_000_000, + "more than its forward, once its share outgrows A's regular gas" + ); + } else { + assert_eq!(row.charges, kept + 1, "the crossing log is the one past the budget"); + assert_eq!( + decode_mega_limit_exceeded(&row.callee.output), + Some((LimitKind::DataSize, budget)), + "C's budget stops it" + ); + assert_eq!(row.consumed(), 0, "C's history comes back to the reservoir"); + assert!(row.completed(), "A's work completes"); + } + } + assert!(1_200_000_000 < threshold && threshold <= 1_600_000_000, "{threshold}"); + + // `A`'s own work in those rows is bound by its regular gas, so it completes on either side. + // The most `A` may add needs the reservoir on both sides, and the reservoir `A` kept below the + // threshold pays for it. + let below = all.iter().find(|row| row.scenario.gas_limit == threshold - 1).unwrap(); + assert_eq!(below.prediction.capacity_after_call, TX_STATE_GROWTH_LIMIT); + let gas_alone = capacity(below.prediction.pools_after_call, Budget::unlimited()); + assert!(gas_alone > TX_STATE_GROWTH_LIMIT, "A's gas pays for more: {gas_alone}"); + let at_work = |gas_limit| { + run_with(Scenario { gas_limit, forward: Forward::All, callee }, Some(TX_STATE_GROWTH_LIMIT)) + }; + let below = at_work(threshold - 1); + let at_threshold = at_work(threshold); + assert!(below.work_needs_reservoir() && at_threshold.work_needs_reservoir()); + assert!(below.completed(), "the 2 per cent A kept pays for what its regular gas does not"); + assert!(at_threshold.completed(), "C's crossing gave the share back"); + + print_table("2a. Gas-limit sweep, forward 1M", &bounded); + print_table("2b. Gas-limit sweep, forward all but 2/100 (threshold rows included)", &all); + print_table( + "2c. Either side of the threshold, A's work needing the reservoir", + &[below, at_threshold], + ); + println!( + "\nC's data-size budget: {budget} bytes, {kept} logs; threshold gas limit {threshold}; \ + A's capacity below it on gas alone: {gas_alone} slots" + ); +} + +/// Without a reservoir every charge spills onto the callee's regular gas, so the forward bounds all +/// of it: the callee that stops on a spill logs once, the greedy one logs until its forward runs +/// low, and `A`'s work completes after either. At the execution cap that work is the 1,000 slots +/// the state-growth limit allows. +#[test] +fn test_without_a_reservoir_the_forward_bounds_every_charge() { + if runs_at_measurement_prices() { + return; + } + let mut rows = Vec::new(); + for gas_limit in [TX_GAS_LIMIT_CAP, 100_000_000] { + for callee in [Callee::stops_on_spill(Charge::Log0Data), Callee::greedy(Charge::Log0Data)] { + let row = run(Scenario { gas_limit, forward: Forward::Explicit(1_000_000), callee }); + assert_eq!(row.reservoir_at_call, 0); + assert_eq!(row.handed.reservoir, 0); + assert_eq!(row.consumed(), 0); + assert_eq!(row.callee.history, (row.charges * Charge::Log0Data.history()) as i64); + assert!( + row.callee.history as u64 <= row.callee_regular() && + row.callee_regular() + row.consumed() <= row.forward(), + "every charge C made, its history included, came out of its forward" + ); + assert!(row.completed(), "A's work completes"); + rows.push(row); + } + } + assert_eq!(rows[0].charges, 1, "the first log spills"); + assert!(rows[1].charges > 1, "the greedy callee logs until its forward runs low"); + assert_eq!(rows[0].prediction.work, TX_STATE_GROWTH_LIMIT, "the state-growth limit binds"); + assert!(rows[2].prediction.work < TX_STATE_GROWTH_LIMIT, "the gas binds"); + print_table("3. No reservoir (forward 1M)", &rows); +} + +/// The forwards of the forward-size tables. +fn forwards() -> [Forward; 4] { + [ + Forward::Explicit(100_000), + Forward::Explicit(1_000_000), + Forward::Explicit(10_000_000), + Forward::All, + ] +} + +/// One charge's callee, on the forwards from 100k to all but 2 per cent, at 400M. +#[track_caller] +fn forward_sizes(charge: Charge) -> Vec { + forwards() + .into_iter() + .map(|forward| { + run(Scenario { + gas_limit: 400_000_000, + forward, + callee: Callee::stops_on_spill(charge), + }) + }) + .collect() +} + +/// Holds the explicit forwards' rows: regular gas within the forward, and a reservoir consumed +/// past it that grows with it. +#[track_caller] +fn assert_past_the_forward(explicit: &[Measured]) { + for row in explicit { + assert!(row.callee_regular() <= row.forward(), "regular gas stays within the forward"); + assert!(row.consumed() > row.forward(), "the share pays more than the forward"); + } + assert!( + explicit.windows(2).all(|pair| pair[0].consumed() < pair[1].consumed()), + "the reservoir consumed grows with the forward" + ); +} + +/// The reservoir a log-heavy callee consumes against its forward, for `LOG0` with data and `LOG4` +/// without: past the forward at every explicit size, growing with it, and its whole share +/// forwarding all. +/// +/// Forwarding all, the callee consumes its share, which at 400M is 98/100 of a reservoir just below +/// `A`'s regular gas, so just under the forward, and `A` keeps its 2 per cent. +#[test] +fn test_the_reservoir_a_logging_callee_consumes_grows_with_its_forward() { + if runs_at_measurement_prices() { + return; + } + let log0 = forward_sizes(Charge::Log0Data); + let log4 = forward_sizes(Charge::Log4); + for rows in [&log0, &log4] { + let (all, explicit) = rows.split_last().unwrap(); + assert_past_the_forward(explicit); + assert!(all.consumed() > explicit.last().unwrap().consumed()); + assert_eq!(all.callee.result, InstructionResult::Stop, "C returns"); + assert_eq!(all.consumed(), all.handed.reservoir, "C consumes its whole share"); + assert_eq!(all.reservoir_after_call, all.reservoir_at_call * 2 / 100, "A keeps 2 per cent"); + assert!(all.consumed() < all.forward(), "just under the forward at 400M"); + } + print_table("4a. Forward sizes, LOG0 with 512 bytes of data (400M)", &log0); + print_table("4b. Forward sizes, LOG4 with no data (400M)", &log4); +} + +/// The same with fresh `SSTORE`s, whose state and history both draw the reservoir: past the forward +/// at every explicit size and growing with it, until the callee's state-growth budget, 98/100 of +/// the 1,000 new slots the transaction may add, stops it. +/// +/// Forwarding all, the callee's 981st slot crosses its budget of 980 before the share runs out: it +/// reverts, and its charges and the share come back to `A`, which consumes nothing of the +/// reservoir. The slots the callee keeps at an explicit forward come out of the 1,000 too, so `A`'s +/// 1,000 are stopped by the limit after them. +#[test] +fn test_a_writing_callees_state_growth_budget_stops_it_before_its_share_runs_out() { + if runs_at_measurement_prices() { + return; + } + let rows = forward_sizes(Charge::FreshSlot); + let (all, explicit) = rows.split_last().unwrap(); + assert_past_the_forward(explicit); + for row in explicit { + assert_eq!( + row.consumed(), + row.charges * (Charge::FreshSlot.state() + Charge::FreshSlot.history()) + ); + assert_eq!( + row.prediction.budget_after_call.left.state_growth, + TX_STATE_GROWTH_LIMIT - row.charges, + "C's slots come out of A's" + ); + } + let growth = share(TX_STATE_GROWTH_LIMIT); + assert_eq!(all.prediction.budget.given.state_growth, growth); + assert!( + all.handed.reservoir > (growth + 1) * (slot_state_gas() + history(WRITE_RECORD_SIZE)), + "the share would pay for the slot past the budget" + ); + assert_eq!(all.charges, growth + 1, "the crossing slot is the one past the budget"); + assert_eq!( + decode_mega_limit_exceeded(&all.callee.output), + Some((LimitKind::StateGrowth, growth)), + "C's state-growth budget stops it" + ); + assert_eq!(all.consumed(), 0, "C's charges and its share come back to A"); + assert!(all.completed(), "A's work completes"); + print_table("5. Forward sizes, fresh SSTOREs (400M)", &rows); +} + +/* ---------- a callee that deploys code ---------- */ + +/// A callee that `CREATE`s a contract of `size` zero bytes, from the init code +/// `PUSH3 size PUSH0 RETURN`, then stops. +fn deploying(size: u64) -> Bytes { + assert!(size < 1 << 24, "{size} fits a PUSH3"); + let [_, high, middle, low] = (size as u32).to_be_bytes(); + let mut code = vec![PUSH6, PUSH3, high, middle, low, PUSH0, RETURN]; + // The init code lands right-aligned in the first word: bytes 26 to 31. + code.extend([PUSH0, MSTORE, PUSH1, 6, PUSH1, 26, PUSH0, CREATE, POP, STOP]); + code.into() +} + +/// The history of a creation's two write records: the created account and the creator's nonce. +fn creation_records_history() -> u64 { + history(2 * WRITE_RECORD_SIZE) +} + +/// What the creation pays for depositing `size` bytes: each byte's state and history gas. +fn deposit_charges(size: u64) -> u64 { + size * COST_PER_STATE_BYTE + history(size) +} + +/// What the reservoir pays for a creation that deposits `size` bytes: the created account's +/// state gas and the history of its two write records, which its creator pays at the start, and +/// the deposit. +fn deployment_charges(size: u64) -> u64 { + account_state_gas() + creation_records_history() + deposit_charges(size) +} + +/// What a creation that deposits `size` bytes counts: its two records with their bytes, the +/// created account, and the code's bytes. +const fn deployment_counts(size: u64) -> LimitUsage { + LimitUsage { data_size: 2 * WRITE_RECORD_SIZE + size, write_records: 2, state_growth: 1 } +} + +/// A code deposit charges each byte 1,530 state gas and 88 history gas against a few regular gas of +/// memory and hashing, so a callee that deploys code draws hundreds to thousands of times its +/// forward from the reservoir: 96 KiB on a forward of 100,000 and on one of 1,000,000, which +/// consume the same, and the largest contract on a forward of 1,000,000. +/// +/// `C`'s regular gas is not modelled here: the reservoir it consumes is held to the schedule, its +/// regular gas to its forward, and `A`'s work, sized as in the other measurements, to the pools and +/// the budgets the call left it. +/// +/// The creation's start charges `C` the account and the records and hands the creation all but 2 +/// per cent of what that leaves of `C`'s share, which pays the deposit. `A`'s work is the 1,000 +/// slots the state-growth limit allows, and it fails on that limit, the created account having +/// taken one of them, not on gas: the 999 slots the limit leaves `A` fit in its regular gas alone. +#[test] +fn test_a_deploying_callee_charges_the_reservoir_hundreds_of_times_its_forward() { + if runs_at_measurement_prices() { + return; + } + println!("\n### 7. A callee that deploys code\n"); + println!( + "| gas limit | forward | code size | C regular spent | reservoir at call | \ + reservoir to C | reservoir to the creation | reservoir at return | consumed | \ + consumed / forward | A GAS after | A work (slots) | A capacity after | \ + work needs reservoir | status | gas used |" + ); + println!("|{}", "---:|".repeat(16)); + for (gas_limit, forward, size) in [ + (400_000_000, 100_000, 96 * 1024), + (400_000_000, 1_000_000, 96 * 1024), + (1_200_000_000, 1_000_000, MAX_CONTRACT_SIZE as u64), + ] { + let name = format!("{size} bytes at a {gas_limit} gas limit, forwarding {forward}"); + // `A` runs as it does before a callee that returns at once. + let scenario = + Scenario { gas_limit, forward: Forward::Explicit(forward), callee: Callee::Stop }; + let p = predict(scenario, None); + let db = || { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10u64.pow(18))) + .account_code(A, caller_code(Forward::Explicit(forward), p.work)) + .account_code(C, deploying(size)) + }; + let tx = || call(SENDER, A, U256::ZERO, gas_limit); + let (outcome, meter) = execute_metered(db, tx, Meter::default(), &name); + + assert_eq!(meter.gas_before_call, Some(p.gas_before_call), "{name}: A's GAS before"); + assert_eq!(meter.handed, Some(p.handed), "{name}: what the call hands C"); + let created_with = meter.created_with.expect("C created"); + assert_eq!( + created_with.reservoir, + reservoir_share(p.handed.reservoir - account_state_gas() - creation_records_history()), + "{name}: the creation's share" + ); + assert!(deposit_charges(size) <= created_with.reservoir, "{name}: the share pays it"); + let returned = meter.returned.clone().expect("C returned"); + assert_eq!(returned.result, InstructionResult::Stop, "{name}: C returns"); + let callee_regular = forward - returned.pools.regular; + assert!(callee_regular <= forward, "{name}: regular gas stays within the forward"); + let after = meter.after_return.expect("A resumed"); + let consumed = p.reservoir_at_call - after.reservoir; + assert_eq!(consumed, deployment_charges(size), "{name}: the reservoir paid the deployment"); + assert!(consumed > 100 * forward, "{name}: a hundred times the forward: {consumed}"); + + let mut after_gas = after; + after_gas.regular(G_BASE).unwrap(); + assert_eq!(meter.gas_after_call, Some(after_gas.regular), "{name}: A's GAS after"); + let mut budget = Budget::first_frame(); + budget.merge(deployment_counts(size)); + let left = capacity(after_gas, budget); + assert_eq!(p.work, TX_STATE_GROWTH_LIMIT, "{name}: the state-growth limit binds the work"); + assert_eq!(left, TX_STATE_GROWTH_LIMIT - 1, "{name}: the created account took one"); + assert!(!needs_reservoir(left, after_gas.regular), "{name}: A's regular gas pays for it"); + let end = model_work(p.work, after_gas, budget); + assert!( + matches!(end, WorkEnd::Stopped(Stop { kind: LimitKind::StateGrowth, .. }, _)), + "{name}: A's work is stopped on the state-growth limit: {end:?}" + ); + let callee = ( + account_state_gas() + size * COST_PER_STATE_BYTE, + creation_records_history() + history(size), + deployment_counts(size), + ); + assert_settled(&name, &outcome, scenario, &Prediction { end, ..p }, callee); + + let status = status(&outcome); + println!( + "| {gas_limit} | {forward} | {size} | {callee_regular} | {} | {} | {} | {} | \ + {consumed} | {} | {} | {} | {left} | {} | {status} | {} |", + p.reservoir_at_call, + p.handed.reservoir, + created_with.reservoir, + after.reservoir, + ratio(consumed, forward), + after_gas.regular, + p.work, + if needs_reservoir(p.work, after_gas.regular) { "yes" } else { "no" }, + outcome.gas.gas_used, + ); + } +} diff --git a/crates/mega-evm/tests/satin/reservoir_share.rs b/crates/mega-evm/tests/satin/reservoir_share.rs new file mode 100644 index 000000000..0ebf30c3d --- /dev/null +++ b/crates/mega-evm/tests/satin/reservoir_share.rs @@ -0,0 +1,200 @@ +//! The reservoir a frame starts with: the transaction's own frame and a system call's outermost +//! frame take the whole of it, and every child of `CALL`, `CALLCODE`, `DELEGATECALL`, +//! `STATICCALL`, `CREATE` or `CREATE2` takes `remaining − remaining × 2 / 100` of what its caller +//! has left after every charge it made for the start, the history of the start's records +//! included, whatever regular gas the caller asks to forward. The caller keeps the rest while the +//! child runs, and the child's return adds what it left back. +//! +//! An inspector reads the reservoir each start hands its frame off the frame's input, which is +//! where revm puts the share it took out of the caller. + +use alloy_primitives::{address, Address, Bytes, U256}; +use mega_evm::{ + constants::TX_GAS_LIMIT_CAP, + test_utils::{BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, WRITE_RECORD_SIZE, +}; +use revm::{ + bytecode::opcode::{CALL, PUSH0, PUSH1, PUSH20, STOP}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, + }, + Database, Inspector, +}; + +use crate::common::{ + body_history, call, context, history, reservoir_share, runs_at_measurement_prices, +}; + +const SENDER: Address = address!("0000000000000000000000000000000000720000"); +const A: Address = address!("0000000000000000000000000000000000720001"); +const B: Address = address!("0000000000000000000000000000000000720002"); +const C: Address = address!("0000000000000000000000000000000000720003"); + +/// The gas a transaction carries above the execution cap: its reservoir before the body is paid. +const ABOVE_THE_CAP: u64 = 10_000_000; + +/// Records the reservoir every frame start hands its frame, in the order the starts are made. +#[derive(Default)] +struct Shares { + reservoirs: Vec, + gas_limits: Vec, +} + +impl Inspector, EthInterpreter> for Shares { + fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { + self.reservoirs.push(inputs.reservoir); + self.gas_limits.push(inputs.gas_limit); + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut CreateInputs, + ) -> Option { + self.reservoirs.push(inputs.reservoir()); + self.gas_limits.push(inputs.gas_limit()); + None + } +} + +/// `A` calls `B`, which calls `C`, each with all its gas and no value. +fn chain() -> MemoryDatabase { + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_code(A, BytecodeBuilder::default().call(B, U256::ZERO).stop().build()) + .account_code(B, BytecodeBuilder::default().call(C, U256::ZERO).stop().build()) + .account_code(C, Bytes::from_static(&[STOP])) +} + +/// The reservoir the transaction's own frame starts with: what the gas limit carries above the +/// execution cap, less the history of the body, which the reservoir pays first. +fn first_frame_reservoir() -> u64 { + ABOVE_THE_CAP - body_history(0) +} + +/// The transaction's own frame takes the whole reservoir; a child takes all but its caller's 2 per +/// cent, and a grandchild all but 2 per cent of what the child has left. Nothing spends any of it, +/// so it all comes back, and the transaction is reimbursed the whole. +#[test] +fn test_a_child_takes_the_reservoir_less_its_callers_two_percent_at_every_depth() { + let mut evm = MegaEvm::new(context(chain())).with_inspector(Shares::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, TX_GAS_LIMIT_CAP + ABOVE_THE_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + + let whole = first_frame_reservoir(); + let child = reservoir_share(whole); + let grandchild = reservoir_share(child); + assert_eq!(evm.inspector().reservoirs, [whole, child, grandchild]); + assert!(whole * 2 / 100 > 0, "the caller keeps a part of this reservoir"); + assert_eq!(outcome.gas.reservoir_remaining, whole, "every share came back"); +} + +/// `A` calls `B` asking for one unit of regular gas, carrying `value`. +fn asking_for_one(value: u8) -> MemoryDatabase { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH1, value, PUSH20]) + .append_many(B.into_array()) + .append_many([PUSH1, 1, CALL]) + .stop() + .build(); + MemoryDatabase::default() + .account_balance(SENDER, U256::from(10_u64.pow(18))) + .account_balance(A, U256::from(1)) + .account_code(A, code) + .account_code(B, Bytes::from_static(&[STOP])) +} + +/// The regular gas a call asks to forward does not bound the reservoir it hands its frame: a call +/// asking for one unit of gas still hands it the share. A call that moves value hands it the +/// share of what the history of the start's records left the caller — the two accounts the +/// transfer changes — and the stipend joins the forward. +#[test] +fn test_the_regular_gas_a_call_asks_for_does_not_bound_the_reservoir_it_forwards() { + let whole = first_frame_reservoir(); + for (value, gas_limit, records) in [(0, 1, 0), (1, 1 + 2_300, 2)] { + let mut evm = + MegaEvm::new(context(asking_for_one(value))).with_inspector(Shares::default()); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, TX_GAS_LIMIT_CAP + ABOVE_THE_CAP)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "value {value}: {:?}", outcome.result); + let left = whole - history(WRITE_RECORD_SIZE * records); + let shares = evm.inspector(); + assert_eq!(shares.reservoirs, [whole, reservoir_share(left)], "value {value}"); + assert_eq!(shares.gas_limits[1], gas_limit, "value {value}"); + } +} + +/// A system call's outermost frame takes the whole reservoir the split leaves it, and the frame it +/// starts takes the share of it: the protocol's own work is exempt from the limits, not from the +/// split. +#[test] +fn test_a_system_calls_outermost_frame_takes_the_whole_reservoir_and_its_child_the_share() { + use revm::{handler::system_call::SYSTEM_CALL_GAS_LIMIT, InspectSystemCallEvm}; + let mut evm = MegaEvm::new(context(chain())).with_inspector(Shares::default()); + let result = InspectSystemCallEvm::inspect_one_system_call_with_caller( + &mut evm, + SENDER, + A, + Bytes::new(), + ) + .expect("the system call runs"); + assert!(result.is_success(), "{result:?}"); + let whole = SYSTEM_CALL_GAS_LIMIT - mega_evm::SYSTEM_CALL_REGULAR_GAS_LIMIT; + let child = reservoir_share(whole); + assert_eq!(evm.inspector().reservoirs, [whole, child, reservoir_share(child)]); + assert_eq!(evm.ctx().additional_limit().reservoir_remaining(), whole, "it all came back"); +} + +/// The figures above at the spec's numbers: a 10,000,000 margin pays the body's 27,280 of history, +/// and the frames take 9,972,720, 9,773,266 and 9,577,801. +#[test] +fn test_the_shares_at_the_specs_numbers() { + if runs_at_measurement_prices() { + return; + } + let whole = first_frame_reservoir(); + assert_eq!(whole, 9_972_720); + assert_eq!(reservoir_share(whole), 9_773_266); + assert_eq!(reservoir_share(reservoir_share(whole)), 9_577_801); +} + +/// The neutral configuration runs the fixture fork's schedule, which forwards the whole reservoir +/// to every child, as Ethereum's Amsterdam does; `no_limits()` on Satin's own configuration takes +/// out the limits and leaves the share as it is. +#[test] +fn test_the_neutral_configuration_forwards_the_whole_reservoir_and_no_limits_keeps_the_share() { + use mega_evm::{ + test_utils::{neutral_cfg, neutralize_evm, zero_fee_l1_block_info}, + EthSpecId, EvmTxRuntimeLimits, MegaSpecId, + }; + let gas_limit = TX_GAS_LIMIT_CAP + ABOVE_THE_CAP; + + let ctx = MegaContext::new(chain(), MegaSpecId::SATIN) + .with_neutral_cfg(neutral_cfg(EthSpecId::AMSTERDAM).expect("a neutral fork")) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()) + .with_block(crate::common::block()) + .with_chain(zero_fee_l1_block_info()); + let mut evm = MegaEvm::new(ctx).with_inspector(Shares::default()); + neutralize_evm(&mut evm, EthSpecId::AMSTERDAM).expect("a neutral fork"); + let outcome = evm + .execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let [first, child, grandchild] = evm.inspector().reservoirs[..] else { + panic!("three frames: {:?}", evm.inspector().reservoirs) + }; + assert_eq!((child, grandchild), (first, first), "the whole reservoir, at every depth"); + + let ctx = context(chain()).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(ctx).with_inspector(Shares::default()); + evm.execute_transaction(call(SENDER, A, U256::ZERO, gas_limit)) + .expect("the transaction is valid"); + let whole = first_frame_reservoir(); + let child = reservoir_share(whole); + assert_eq!(evm.inspector().reservoirs, [whole, child, reservoir_share(child)]); +} diff --git a/crates/mega-evm/tests/satin/salt.rs b/crates/mega-evm/tests/satin/salt.rs index f7e3511d0..690414e18 100644 --- a/crates/mega-evm/tests/satin/salt.rs +++ b/crates/mega-evm/tests/satin/salt.rs @@ -323,7 +323,8 @@ fn test_the_new_account_charge_of_a_call_scales_with_the_account_s_bucket() { /// A `SELFDESTRUCT` moving a balance to an account that does not exist adds that account's leaf, /// and the beneficiary's own bucket prices it — the same entry and the same site a value `CALL` /// pays, reached from the opcode that empties an account rather than the one that funds it. The -/// history is the body and the beneficiary's record. +/// history is the body and the destruction's two records, the beneficiary's and that of the +/// account it clears. /// /// Rules: [S6.4], [S6.5], [S7.2]. #[test] @@ -331,7 +332,7 @@ fn test_the_selfdestruct_beneficiary_charge_scales_with_the_beneficiary_s_bucket assert_scales( "SELFDESTRUCT to a new account", entry(GasId::new_account_state_gas()), - TX_BODY_SIZE + WRITE_RECORD_SIZE, + TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE, |envs, m| crowded_account(envs, EMPTY, m), || (db(selfdestruct_to(EMPTY).build()), call_contract()), ); diff --git a/crates/mega-evm/tests/satin/salt_refund.rs b/crates/mega-evm/tests/satin/salt_refund.rs index 0d6bad039..4eadc4e9a 100644 --- a/crates/mega-evm/tests/satin/salt_refund.rs +++ b/crates/mega-evm/tests/satin/salt_refund.rs @@ -4,7 +4,7 @@ //! //! One shape names the charge and asks the hook for its price again: the same opcode taking its //! own write back (`SSTORE` 0 -> x -> 0), the upfront charge a caller made for a call or a -//! creation that did not add the leaf after all, the transaction-level refund, and the +//! creation that did not add the leaf after all, the transaction-level refund, and revm's //! settlement of a frame result built without running a frame. Because the site is re-priced //! through the one hook, and because the multiplier of a bucket is read once per transaction, //! the refill is the charge — a bucket cannot be read at one capacity for the charge and another @@ -23,19 +23,21 @@ use alloy_primitives::{address, Address, Bytes, TxKind, U256}; use mega_evm::{ - settle_frame_result, synthetic_frame_result, + synthetic_frame_result, test_utils::{BytecodeBuilder, MemoryDatabase}, MegaTransaction, }; use revm::{ bytecode::opcode::{CALL, PUSH0, RETURN, REVERT}, + context::result::EVMError, context_interface::{ cfg::{gas::GasTracker, GasId, StateGasCharge, StateGasSite}, Host, }, + handler::EthFrame, interpreter::{ - CallInput, CallInputs, CallScheme, CallValue, CreateInputs, CreateScheme, FrameInput, - InstructionResult, + interpreter::EthInterpreter, CallInput, CallInputs, CallScheme, CallValue, CreateInputs, + CreateScheme, FrameInput, InstructionResult, }, }; @@ -389,8 +391,9 @@ struct Settled { } /// Charges `charge` through the pricing hook of a context reading `envs`, hands the frame the -/// reservoir the caller has left, and settles a synthetic failure for it through the public -/// helper — the route a mechanism takes when it answers a frame rather than running it. +/// reservoir the caller has left, and settles a synthetic failure for it into the caller through +/// revm's own frame return — the route a result takes when a mechanism answers a frame rather +/// than running it. fn settle_a_synthetic_failure( envs: &SaltEnvs, reservoir: u64, @@ -404,16 +407,18 @@ fn settle_a_synthetic_failure( assert!(caller.record_state_cost(price), "the caller can pay the crowded charge"); let spilled = caller.state_gas_spilled(); - let mut result = - synthetic_frame_result(&input(caller.reservoir()), InstructionResult::Revert, Bytes::new()); - settle_frame_result::<_, revm::context::result::EVMError>( - &mut ctx, - &mut caller, - &mut result, - ) - .expect("the refund is priced through the same hook"); - - Settled { caller, price, spilled } + // The calling opcode hands the frame the reservoir its charge left, taken out of the caller, + // whose return adds what the frame gives back to what the caller kept. + let share = caller.reservoir(); + caller.forward_reservoir(share); + let result = synthetic_frame_result(&input(share), InstructionResult::Revert, Bytes::new()); + let mut frame = EthFrame::::default(); + *frame.interpreter.gas.tracker_mut() = caller; + frame + .return_result::<_, EVMError>(&mut ctx, result) + .expect("the refund is priced through the same hook"); + + Settled { caller: *frame.interpreter.gas.tracker(), price, spilled } } /// The inputs of a `CALL` whose calling opcode charged the caller for the account it would add. @@ -431,6 +436,9 @@ fn charged_call_input(reservoir: u64) -> FrameInput { is_static: false, reservoir, charged_new_account_state_gas: true, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })) } @@ -467,7 +475,7 @@ fn assert_restores_both_pools(site: &str, envs: &SaltEnvs, reservoir: u64, settl ); } -/// A synthetic `CALL` failure settled through the public helper gives back a SALT-priced upfront +/// A synthetic `CALL` failure settled into its caller gives back a SALT-priced upfront /// charge, both when the reservoir paid for it and when it spilled onto regular gas. #[test] fn test_a_synthetic_call_failure_refunds_the_crowded_upfront_charge() { @@ -573,7 +581,7 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { return; } // The deposit's price on top of the rest, below the execution cap as every probe here runs: - // forwarded 63/64 of it, the creation runs its init code and falls short of the deposit. + // forwarded 98/100 of it, the creation runs its init code and falls short of the deposit. let gas_limit = (without_the_deposit + deposit).min(GAS_LIMIT); let envs = crowd(minimal_envs()); @@ -611,11 +619,13 @@ fn test_a_creation_that_cannot_pay_its_code_deposit_keeps_no_state_gas() { /// A `CREATE` whose init code `SELFDESTRUCT`s the account it is creating, in the same transaction. /// /// EIP-8037's gas refills for `SELFDESTRUCT` say that destruction leaves the account, its code -/// and its storage out of the trie, and still produces no state-gas refill and no change to the -/// state gas the transaction has spent. The created-account charge therefore stands, priced in -/// the created address's bucket, at the minimum multiplier and above it. +/// and its storage out of the trie, and produces no state-gas refill. Satin's destruction table +/// gives back the parts the transaction made: the account was absent at the transaction's start, +/// so its leaf's state gas comes back to the destroying frame at the price it was charged, priced +/// in the created address's bucket, and the transaction keeps none, at the minimum multiplier and +/// above it. #[test] -fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state_gas() { +fn test_a_created_account_selfdestructed_in_the_same_transaction_gives_its_state_gas_back() { // A charge that costs nothing is the same number whether or not it is given back. if state_is_free() { return; @@ -624,7 +634,6 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state // is that account, which the creation itself just added, so no second account is charged. let init = selfdestruct_to_self(); let created = CONTRACT.create(0); - let account = entry(GasId::create_state_gas()); assert_eq!( net_state_at( @@ -632,14 +641,17 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state move |envs, m| crowded_account(envs, created, m), || (db(create_with(&init).stop().build()), call_contract()), ), - [account, account * 2, account * 8], - "the created account's state gas is not refilled", + [0, 0, 0], + "the created account's state gas comes back at the price it was charged", ); - let outcome = run( - db(create_with(&init).stop().build()), - crowded_account(minimal_envs(), created, 8), - call_contract(), + let envs = crowded_account(minimal_envs(), created, 8); + let outcome = run(db(create_with(&init).stop().build()), envs.clone(), call_contract()); + assert_eq!(outcome.gas.state, 0); + assert_eq!( + envs.bucket_queries(account_bucket(created)), + 1, + "one capacity read priced both the charge and the give-back", ); assert!( outcome.state.get(&created).is_some_and(|account| account.is_selfdestructed()), @@ -647,6 +659,64 @@ fn test_a_created_account_selfdestructed_in_the_same_transaction_keeps_its_state ); } +/// A contract created in the transaction and destroyed by a later call gives back every state +/// charge the transaction made for it, each at the price it was charged in its own bucket: the +/// account leaf, the slot its init code wrote and the code it deposited, the leaf and the code in +/// the account's bucket and the slot in the slot's. The transaction keeps none of them, at the +/// minimum multiplier and above it, with either bucket crowded, and each bucket is read once. +#[test] +fn test_a_contract_destroyed_after_its_creation_gives_back_its_leaf_slot_and_code() { + use revm::bytecode::opcode::{ADDRESS, DUP6, GAS, POP, SELFDESTRUCT}; + if state_is_free() { + return; + } + let init = BytecodeBuilder::default() + .sstore(U256::from(SLOT), U256::from(1)) + .return_with_data([ADDRESS, SELFDESTRUCT]) + .build(); + let created = CONTRACT.create(0); + // The creation leaves the created address on the stack, and a call to it destroys it. + let code = || { + create_with(&init) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, DUP6, GAS, CALL, POP, POP]) + .stop() + .build() + }; + type Crowd = fn(SaltEnvs, Address, u64) -> SaltEnvs; + let crowds: [(&str, Crowd); 2] = [ + ("the account's bucket", crowded_account), + ("the slot's bucket", |envs, address, m| crowded_slot(envs, address, U256::from(SLOT), m)), + ]; + for (crowded, crowd) in crowds { + assert_eq!( + net_state_at( + [1, 2, 8], + move |envs, m| crowd(envs, created, m), + || { (db(code()), call_contract()) } + ), + [0, 0, 0], + "{crowded}: every part comes back at the price it was charged", + ); + } + + let envs = + crowded_slot(crowded_account(minimal_envs(), created, 8), created, U256::from(SLOT), 8); + let outcome = run(db(code()), envs.clone(), call_contract()); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert!(outcome.state[&created].is_selfdestructed(), "the call destroyed the contract"); + assert_eq!(outcome.gas.state, 0); + for (bucket, read) in [ + (account_bucket(created), "the account's"), + (slot_bucket(created, U256::from(SLOT)), "the slot's"), + ] { + assert_eq!( + envs.bucket_queries(bucket), + 1, + "{read} bucket priced its charges and give-backs" + ); + } +} + /// Init code that self-destructs the account being created: `ADDRESS SELFDESTRUCT`. fn selfdestruct_to_self() -> Vec { use revm::bytecode::opcode::{ADDRESS, SELFDESTRUCT}; diff --git a/crates/mega-evm/tests/satin/schedule.rs b/crates/mega-evm/tests/satin/schedule.rs index 9f5dd5078..4f1bf0d6f 100644 --- a/crates/mega-evm/tests/satin/schedule.rs +++ b/crates/mega-evm/tests/satin/schedule.rs @@ -29,15 +29,15 @@ const CALLER: Address = address!("0000000000000000000000000000000000900000"); const CALLEE: Address = address!("0000000000000000000000000000000000900001"); /// 1,000,000 of regular gas on top of what the transactions here add at the byte prices in effect: -/// a new account and a fresh slot, a kilobyte of history, and 64 times the history of two records, -/// which a `CREATE` that forwards all but a 64th of its gas pays for the frame it starts from the -/// 64th it keeps. +/// a new account and a fresh slot, a kilobyte of history, and 50 times the history of two records, +/// which a `CREATE` that forwards all but 2 per cent of its gas pays for the frame it starts from +/// the fiftieth it keeps. fn gas_limit() -> u64 { 1_000_000 + account_state_gas() + slot_state_gas() + history(1_000) + - 64 * history(2 * mega_evm::WRITE_RECORD_SIZE) + 50 * history(2 * mega_evm::WRITE_RECORD_SIZE) } /// The gas a transaction used, the state gas inside it, the history gas the schedule does not diff --git a/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap index 6c7df5b53..9cc802228 100644 --- a/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap +++ b/crates/mega-evm/tests/satin/snapshots/satin__corpus__corpus_outcomes_and_gas.snap @@ -56,7 +56,7 @@ expression: gas "selfdestruct_created_in_same_tx_to_existing_account": [ { "outcome": "success", - "gas_used": 372085 + "gas_used": 184965 } ], "sstore_set_spills": [ diff --git a/crates/mega-evm/tests/satin/spec_numbers.rs b/crates/mega-evm/tests/satin/spec_numbers.rs index 38551315b..774c3bf30 100644 --- a/crates/mega-evm/tests/satin/spec_numbers.rs +++ b/crates/mega-evm/tests/satin/spec_numbers.rs @@ -10,7 +10,8 @@ use mega_evm::{ constants::{ ACCOUNT_STATE_GAS, BLOCK_DATA_LIMIT, BLOCK_ENV_ACCESS_COMPUTE_GAS, COST_PER_HISTORY_BYTE, COST_PER_STATE_BYTE, MAX_CONTRACT_SIZE, MAX_INITCODE_SIZE, MAX_TX_COMPUTE_GAS, - ORACLE_ACCESS_COMPUTE_GAS, SLOT_STATE_GAS, TX_DATA_LIMIT, TX_GAS_LIMIT_CAP, + ORACLE_ACCESS_COMPUTE_GAS, PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS, TX_DATA_LIMIT, + TX_GAS_LIMIT_CAP, TX_KV_UPDATE_LIMIT, TX_STATE_GROWTH_LIMIT, }, kzg_point_evaluation, op_revm::precompiles::{ @@ -23,7 +24,6 @@ use mega_evm::{ revm::{ bytecode::opcode::{EXTCODECOPY, EXTCODESIZE}, context_interface::cfg::{gas::WARM_STORAGE_READ_COST, GasId, GasParams}, - handler::SYSTEM_CALL_REGULAR_GAS_LIMIT, interpreter::instructions::gas_table_spec, precompile::secp256r1::{P256VERIFY_BASE_GAS_FEE_OSAKA, P256VERIFY_OSAKA}, primitives::{ @@ -44,10 +44,10 @@ use mega_evm::{ }, LimitKind, MegaSpecId, ProtocolLimits, SatinPrices, VolatileDataAccess, ACCESS_LIST_ADDRESS_SIZE, ACCESS_LIST_SLOT_SIZE, AUTHORIZATION_SIZE, - FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, HISTORY_GAS_PRICED, LOG_BASE_SIZE, - LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, STATE_GAS_REPRICED, STORAGE_CALL_STIPEND_BYTES, - SYSTEM_ADDRESS, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, TX_FIXED_WRITE_RECORDS, - WRITE_RECORD_SIZE, + FRAME_DATA_SHARE_DENOMINATOR, FRAME_DATA_SHARE_NUMERATOR, HISTORY_ALLOWANCE_BYTES, + HISTORY_GAS_PRICED, LOG_BASE_SIZE, LOG_TOPIC_SIZE, MIN_BUCKET_SIZE, STATE_GAS_REPRICED, + SYSTEM_ADDRESS, SYSTEM_CALL_REGULAR_GAS_LIMIT, TRANSFER_LOG_SIZE, TX_BASE_SIZE, TX_BODY_SIZE, + TX_FIXED_WRITE_RECORDS, WRITE_RECORD_SIZE, }; const SATIN_MD: &str = include_str!("../../../../docs/spec/upgrades/satin.md"); @@ -80,7 +80,7 @@ fn named_constants(doc: &str) { require_eq(doc, "AUTHORIZATION_SIZE", AUTHORIZATION_SIZE); require_eq(doc, "WRITE_RECORD_SIZE", WRITE_RECORD_SIZE); require_eq(doc, "TRANSFER_LOG_SIZE", TRANSFER_LOG_SIZE); - require_eq(doc, "HISTORY_ALLOWANCE_BYTES", STORAGE_CALL_STIPEND_BYTES); + require_eq(doc, "HISTORY_ALLOWANCE_BYTES", HISTORY_ALLOWANCE_BYTES); require_eq(doc, "MIN_BUCKET_SIZE", MIN_BUCKET_SIZE as u64); require_eq(doc, "KEYLESS_DEPLOY_OVERHEAD_GAS", KEYLESS_DEPLOY_OVERHEAD_GAS); require_eq(doc, "BLOCK_ENV_ACCESS_COMPUTE_GAS", BLOCK_ENV_ACCESS_COMPUTE_GAS); @@ -96,29 +96,21 @@ fn named_constants(doc: &str) { grouped(LOG_TOPIC_SIZE) ), ); - require(doc, &format!("({} gas)", grouped(STORAGE_CALL_STIPEND_BYTES * COST_PER_HISTORY_BYTE))); + require(doc, &format!("({} gas)", grouped(HISTORY_ALLOWANCE_BYTES * COST_PER_HISTORY_BYTE))); require(doc, &format!("capped at {} per transaction", grouped(TX_GAS_LIMIT_CAP))); require(doc, &format!("at most {} of regular gas", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); - require(doc, &format!("max(block_gas_limit, {})", grouped(SYSTEM_CALL_REGULAR_GAS_LIMIT))); - require(doc, &format!("A {}-byte allowance", STORAGE_CALL_STIPEND_BYTES)); + require_eq(doc, "PRE_BLOCK_CALL_GAS_LIMIT", PRE_BLOCK_CALL_GAS_LIMIT); require( doc, &format!( - "`FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = {}/{}", - FRAME_DATA_SHARE_NUMERATOR, FRAME_DATA_SHARE_DENOMINATOR + "a reservoir of {}, the state gas of sixteen fresh storage slots", + grouped(PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT) ), ); + require(doc, &format!("A {}-byte allowance", HISTORY_ALLOWANCE_BYTES)); + require_eq(doc, "FRAME_DATA_SHARE_NUMERATOR", FRAME_DATA_SHARE_NUMERATOR); + require_eq(doc, "FRAME_DATA_SHARE_DENOMINATOR", FRAME_DATA_SHARE_DENOMINATOR); require(doc, &format!("KV × {WRITE_RECORD_SIZE} ≤ data size")); - let records = TX_DATA_LIMIT / WRITE_RECORD_SIZE; - require( - doc, - &format!( - "fewer than {} write records ({} / {})", - grouped(records), - grouped(TX_DATA_LIMIT), - WRITE_RECORD_SIZE - ), - ); } fn schedule(doc: &str) { @@ -249,21 +241,34 @@ fn limits(doc: &str) { "the page states one detention cap for both" ); - // Data size is the one dimension limited per transaction and per block: no table row names a - // limit on KV updates, state gas or execution gas. + // No table row names a block limit on state gas or execution gas. let resources = section(doc, "### 10. Resource Limits", "### 11. The Revert-Class"); assert!( table_row(resources, "Data size")[2].contains(&grouped(TX_DATA_LIMIT)), "the transaction's data-size limit" ); + assert_eq!( + table_row(resources, "KV updates")[2], + format!("`TX_KV_UPDATE_LIMIT` = {}", grouped(TX_KV_UPDATE_LIMIT)), + "the transaction's KV-update limit" + ); + assert_eq!(defaults.tx_runtime_limits.tx_kv_update_limit, TX_KV_UPDATE_LIMIT); + assert_eq!( + table_row(resources, "State growth")[2], + format!("`TX_STATE_GROWTH_LIMIT` = {}", grouped(TX_STATE_GROWTH_LIMIT)), + "the transaction's state-growth limit" + ); + assert_eq!(defaults.tx_runtime_limits.tx_state_growth_limit, TX_STATE_GROWTH_LIMIT); + require( + resources, + &format!( + "{} records weigh {} bytes", + grouped(TX_KV_UPDATE_LIMIT), + grouped(TX_KV_UPDATE_LIMIT * WRITE_RECORD_SIZE) + ), + ); let blocks = section(doc, "### 20. Block Limits", "### 21. Transaction and Block"); - for (page, removed) in [ - (resources, "KV updates"), - (resources, "State growth"), - (blocks, "Execution gas"), - (blocks, "State gas"), - (blocks, "KV updates"), - ] { + for (page, removed) in [(blocks, "Execution gas"), (blocks, "State gas")] { assert!( !page.lines().any(|line| line.contains(removed) && line.contains('|')), "no table row limits {removed}" @@ -271,17 +276,16 @@ fn limits(doc: &str) { } assert_eq!( *table_row(blocks, "Data size").last().unwrap(), - format!("{} bytes", grouped(BLOCK_DATA_LIMIT)) + format!("`BLOCK_DATA_LIMIT` = {}", grouped(BLOCK_DATA_LIMIT)) ); let safety = section(doc, "## Safety and Compatibility", "## References"); + require(safety, &format!("data size at {} bytes", grouped(TX_DATA_LIMIT))); + require(safety, &format!("KV updates at {}", grouped(TX_KV_UPDATE_LIMIT))); + require(safety, &format!("state growth at {}", grouped(TX_STATE_GROWTH_LIMIT))); require( safety, - &format!( - "the data-size limits at {} bytes and the detention caps at {} each", - grouped(TX_DATA_LIMIT), - grouped(BLOCK_ENV_ACCESS_COMPUTE_GAS) - ), + &format!("the detention caps at {} each", grouped(BLOCK_ENV_ACCESS_COMPUTE_GAS)), ); } @@ -371,20 +375,16 @@ fn detention_and_stops(doc: &str) { ); let stops = section(doc, "### 11. The Revert-Class", "### 12. Gas Detention"); - let kinds = - [(LimitKind::DataSize, "Data size"), (LimitKind::ComputeGas, "Compute (gas detention)")]; + let kinds = [ + (LimitKind::DataSize, "Data size"), + (LimitKind::KvUpdate, "KV updates"), + (LimitKind::ComputeGas, "Compute (gas detention)"), + (LimitKind::StateGrowth, "State growth"), + ]; for (kind, name) in kinds { let cells = row_with_first(stops, &kind.as_u8().to_string()); assert_eq!(cells[1], name, "kind {}", kind.as_u8()); } - for retired in [1_u8, 3] { - assert_eq!(LimitKind::from_u8(retired), None, "kind {retired} names no dimension"); - let first = retired.to_string(); - assert!( - stops.lines().map(cells).all(|cells| cells.first() != Some(&first.as_str())), - "the page lists no kind {retired}" - ); - } let access = section(doc, "### 13. Volatile-Data", "### 14. EIP-7708"); let reads = [ diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 2c4439f10..f237adb5c 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -1,5 +1,6 @@ -//! The state a transaction adds, which no limit holds: EIP-8037 charges state gas for exactly that -//! state, and the transaction's own gas pays for it. +//! The state a transaction adds: EIP-8037 charges state gas for exactly that state, which the +//! transaction's own gas pays for, and the state-growth limit holds its count — the new accounts +//! and new slots it keeps, net — per transaction and per frame. //! //! What each site charges — a fresh slot, an account a value transfer, a creation or a destruction //! adds, an applied EIP-7702 authority — is the schedule's state-gas entry, at the minimum bucket, @@ -14,18 +15,20 @@ use alloy_primitives::{address, Address, Bytes, B256, U256}; use mega_evm::{ + constants::{TX_GAS_LIMIT_CAP, TX_STATE_GROWTH_LIMIT}, test_utils::{BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, LimitCheck, LimitKind, MegaEvm, MegaTransaction, MegaTransactionOutcome, - AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + EvmTxRuntimeLimits, LimitCheck, LimitKind, LimitUsage, MegaEvm, MegaSpecId, MegaTransaction, + MegaTransactionOutcome, ProtocolLimits, AUTHORIZATION_SIZE, TRANSFER_LOG_SIZE, + TX_BODY_OVER_DATA_SIZE_LIMIT, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; -use revm::bytecode::opcode::{ - CALL, CREATE, DELEGATECALL, GAS, INVALID, POP, PUSH0, SELFDESTRUCT, STOP, +use revm::{ + bytecode::opcode::{CALL, CREATE, DELEGATECALL, GAS, INVALID, POP, PUSH0, SELFDESTRUCT, STOP}, + context::result::ExecutionResult, }; use crate::common::{ account_state_gas, authorizing_call, body_history, call, context, execute_under, history, - slot_state_gas, state_is_free, + share, slot_state_gas, state_is_free, }; const CALLER: Address = address!("0000000000000000000000000000000000600000"); @@ -62,16 +65,28 @@ fn run_under_data_size( execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)) } -/// The outcome was stopped by the transaction's data-size limit `limit`, crossed at `used`: a -/// revert carrying `MegaLimitExceeded(0, limit)`, never a halt. -fn assert_data_size_stopped(what: &str, outcome: &MegaTransactionOutcome, limit: u64, used: u64) { +/// The transaction's own frame was stopped crossing the transaction's data-size limit `limit` at +/// `used`, the transaction having counted `before` before the frame: the frame's budget is what the +/// limit leaves, which the crossing crosses too, so the outcome is a revert carrying +/// `MegaLimitExceeded(0, budget)`, never a halt. +fn assert_data_size_stopped( + what: &str, + outcome: &MegaTransactionOutcome, + before: u64, + limit: u64, + used: u64, +) { assert!( !outcome.result.is_success() && !outcome.result.is_halt(), "{what}: {:?}", outcome.result ); - let stop = - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, used, frame_local: false }; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: limit - before, + used: used - before, + frame_local: true, + }; assert_eq!(outcome.limit_exceeded, Some(stop), "{what}"); assert_eq!(outcome.result.output().unwrap(), &stop.revert_data(), "{what}"); } @@ -255,6 +270,77 @@ fn test_an_authorization_adds_state_only_when_it_applies() { } } +/// An authority an earlier transaction funded is no new account, whether the two transactions run +/// on one journal, as a block builder runs them, or the first is committed before the second runs: +/// the application charges it no account, and the transaction counts no rise for it. +#[test] +fn test_an_authority_an_earlier_transaction_funded_is_no_new_account() { + use revm::{DatabaseCommit, ExecuteEvm}; + let fund = call(CALLER, AUTHORITY_1, U256::from(1), BELOW_CAP); + let mut apply = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + apply.0.base.nonce = 1; + let db = funded().account_code(A, Bytes::from_static(&[STOP])); + let first = run(db.clone(), fund.clone()); + assert!(first.result.is_success(), "{:?}", first.result); + + let mut committed = db.clone(); + committed.commit(first.result_and_state.state); + let control = run(committed, apply.clone()); + assert!(control.result.is_success(), "{:?}", control.result); + let (_, delegation) = account_and_delegation(); + assert_eq!(control.gas.state, delegation, "the delegation's bytes alone"); + assert_eq!(control.usage.state_growth, 0, "the authority existed"); + assert_eq!(control.usage.write_records, 1, "the authority's record"); + + let context = + crate::common::context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(context); + assert!(ExecuteEvm::transact_one(&mut evm, fund).expect("valid").is_success()); + let second = evm.execute_transaction(apply).expect("valid"); + assert_eq!(second.result_and_state.result, control.result_and_state.result); + assert_eq!(second.gas, control.gas); + assert_eq!(second.usage, control.usage); + assert_eq!(second.limit_exceeded, control.limit_exceeded); +} + +/// An authority an earlier transaction called without value, which the database holds no account +/// for, is counted as the application charges it, whether the two transactions run on one journal +/// or the first is committed before the second runs: the transaction counts a rise for it exactly +/// when the application charged it a new account beside the delegation's bytes. On one journal the +/// call touched the empty account, and revm's flag of the touch outlives the call's transaction, so +/// the application finds the authority touched and charges it no account. +#[test] +fn test_an_authority_an_earlier_transaction_touched_is_counted_as_it_is_charged() { + use revm::{DatabaseCommit, ExecuteEvm}; + if state_is_free() { + return; + } + let (account, delegation) = account_and_delegation(); + let counted_as_charged = |outcome: &MegaTransactionOutcome, path: &str| { + assert!(outcome.result.is_success(), "{path}: {:?}", outcome.result); + let charged = outcome.gas.state == account + delegation; + assert!(charged || outcome.gas.state == delegation, "{path}: {}", outcome.gas.state); + assert_eq!(outcome.usage.state_growth, u64::from(charged), "{path}: the rise"); + assert_eq!(outcome.usage.write_records, 1, "{path}: the authority's record"); + }; + let touch = call(CALLER, AUTHORITY_1, U256::ZERO, BELOW_CAP); + let mut apply = authorizing(A, U256::ZERO, &[(Some(AUTHORITY_1), 0, 0)]); + apply.0.base.nonce = 1; + let db = funded().account_code(A, Bytes::from_static(&[STOP])); + let first = run(db.clone(), touch.clone()); + assert!(first.result.is_success(), "{:?}", first.result); + + let mut committed = db.clone(); + committed.commit(first.result_and_state.state); + counted_as_charged(&run(committed, apply.clone()), "committed"); + + let context = + crate::common::context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()); + let mut evm = MegaEvm::new(context); + assert!(ExecuteEvm::transact_one(&mut evm, touch).expect("valid").is_success()); + counted_as_charged(&evm.execute_transaction(apply).expect("valid"), "one journal"); +} + /// The state gas an authority costs is charged before the first frame, from the transaction's /// gas. A gas limit that covers it in a minimal bucket but not in a crowded one is not refused at /// validation: the transaction runs out of gas before its first frame, and the out-of-gas takes @@ -361,7 +447,8 @@ fn test_a_stop_keeps_what_was_applied_before_the_first_frame() { let start = if value.is_zero() { 0 } else { WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE }; let limit = TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE + start; let stopped = run_under_data_size(writes, tx.clone(), limit); - assert_data_size_stopped("the slot", &stopped, limit, limit + WRITE_RECORD_SIZE); + let before = TX_BODY_SIZE + AUTHORIZATION_SIZE + WRITE_RECORD_SIZE; + assert_data_size_stopped("the slot", &stopped, before, limit, limit + WRITE_RECORD_SIZE); let applied = run(idle, tx); assert!(applied.result.is_success(), "{:?}", applied.result); @@ -407,7 +494,8 @@ fn test_a_stopped_deposit_keeps_the_caller_it_created() { }; let (writes, tx) = deposit(write_slots(BytecodeBuilder::default(), 0, 1).stop().build()); let stopped = run_under_data_size(writes, tx, TX_BODY_SIZE); - assert_data_size_stopped("the slot", &stopped, TX_BODY_SIZE, TX_BODY_SIZE + WRITE_RECORD_SIZE); + let (body, used) = (TX_BODY_SIZE, TX_BODY_SIZE + WRITE_RECORD_SIZE); + assert_data_size_stopped("the slot", &stopped, body, body, used); let (idle, tx) = deposit(BytecodeBuilder::default().stop().build()); let created = run(idle, tx); assert!(created.result.is_success(), "{:?}", created.result); @@ -444,10 +532,10 @@ fn test_a_destruction_to_itself_grows_no_state() { /// Once the state charge is paid, a frame start still charges the caller the history of the two /// records the frame makes, after the gas it forwards is computed [S7.23]; one gas short of what /// the start costs in all is an out-of-gas too, and the frame does not start [S7.24]. A `CREATE` -/// charges the created account before its 63/64 split, as EIP-8037 has it, so the records come out -/// of the 64th the creator keeps, and the creator must hold 64 times their price after the state -/// charge. EIP-8037 states that order for a creation alone — of a value `CALL` it says only that -/// the charge comes right before the child frame is entered — so, though the engine charges a +/// charges the created account before its 98/100 split, as EIP-8037 has it, so the records come +/// out of the fiftieth the creator keeps, and the creator must hold 50 times their price after the +/// state charge. EIP-8037 states that order for a creation alone — of a value `CALL` it says only +/// that the charge comes right before the child frame is entered — so, though the engine charges a /// `CALL`'s new account before its split too, that order is not pinned here: the `CALL` forwards /// an explicit nothing — the same forward in any order — and its rows hold whatever the order: a /// gas limit short of the state charge, and one gas short of the whole start, runs out of gas. @@ -522,7 +610,7 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() entry(GasId::cold_account_additional_cost()) + entry(GasId::warm_storage_read_cost()), account_state_gas(), - // The beneficiary's record is held before its history is charged. + // The destruction's records are held before their history is charged. 0, false, ), @@ -581,8 +669,8 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() // Three `PUSH0` for an empty init code carrying no value, then the creation's 32,000. call_intrinsic + 3 * 2 + entry(GasId::create()), created_account_state_gas(), - // The two records, out of the 64th the creator keeps after its forward. - 64 * start_records, + // The two records, out of the fiftieth the creator keeps after its forward. + 50 * start_records, false, ), ]; @@ -626,13 +714,701 @@ fn test_a_state_charge_the_frame_cannot_pay_runs_out_of_gas_whatever_the_limit() paid.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit: TX_BODY_SIZE, - frame_local: false, + limit: 0, + frame_local: true, .. }) ), - "{name}, everything paid: the record after the charge is the stop, {:?}", + "{name}, everything paid: the record after the charge crosses the frame's budget of \ + nothing the body leaves, {:?}", paid.limit_exceeded ); } } + +/* ---------- the state-growth limit ---------- */ + +// State growth is the count of the new accounts and new slots a transaction keeps, net, held per +// transaction at `TX_STATE_GROWTH_LIMIT` and per frame at 98/100 of what its parent has left, +// rounded down. A rise that crosses either stops the frame that makes it with +// `MegaLimitExceeded(3, limit)`, naming the frame's budget when the rise crosses it, and its caller +// resumes. Every figure below is hand arithmetic from the rises and falls the spec lists. + +const C: Address = address!("0000000000000000000000000000000000600009"); +const D: Address = address!("000000000000000000000000000000000060000a"); + +/// Gas for `slots` fresh slots and the calls around them at the prices in effect: the execution +/// cap's regular gas, and a reservoir paying every slot's state gas and its record's history, with +/// room for a few new accounts on top. +fn room(slots: u64) -> u64 { + TX_GAS_LIMIT_CAP + + slots * (slot_state_gas() + history(WRITE_RECORD_SIZE)) + + 16 * (account_state_gas() + history(WRITE_RECORD_SIZE)) + + 100_000_000 +} + +/// Limits holding the transaction to `units` of state growth, and nothing else. +fn growth(units: u64) -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(units) +} + +/// The revert data of a state-growth stop naming `limit`. +fn growth_stop(limit: u64) -> Bytes { + LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used: 0, frame_local: true } + .revert_data() +} + +/// The stop of a state-growth crossing of the budget `limit` at `used`, by the frame that made it. +const fn budget_crossed(limit: u64, used: u64) -> Option { + Some(LimitCheck::ExceedsLimit { kind: LimitKind::StateGrowth, limit, used, frame_local: true }) +} + +/// A call to `A` with gas for `slots` fresh slots, run over `db` under `limits`. +fn run_a(db: MemoryDatabase, slots: u64, limits: EvmTxRuntimeLimits) -> MegaTransactionOutcome { + execute_under(db, call(CALLER, A, U256::ZERO, room(slots)), limits) +} + +/// Appends a `CALL` of `to` with all the gas and no value, dropping its status. +fn call_dropping(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.call(to, U256::ZERO).append(POP) +} + +/// Appends a `CALL` of `to` with all the gas and no value, then returns what it returned or +/// reverted with: a frame that ends with its child's answer as its own output. +fn call_answering(code: BytecodeBuilder, to: Address, value: U256) -> Bytes { + code.call(to, value).append(POP).return_returndata().build() +} + +/// Appends a `DELEGATECALL` of `to` with all the gas, dropping its status: `to`'s code on the +/// caller's own storage. +fn delegatecall_dropping(code: BytecodeBuilder, to: Address) -> BytecodeBuilder { + code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).push_address(to).append_many([ + GAS, + DELEGATECALL, + POP, + ]) +} + +/// Appends writes of zero to the slots `from..to`: a fall of each slot an earlier write in the +/// transaction made non-zero from an original of zero. +fn clear_slots(mut builder: BytecodeBuilder, from: u64, to: u64) -> BytecodeBuilder { + for slot in from..to { + builder = builder.sstore(U256::from(slot), U256::ZERO); + } + builder +} + +/// The output of `outcome`'s transaction, the revert data of a stop a frame answered with. +fn output(outcome: &MegaTransactionOutcome) -> Bytes { + outcome.result.output().cloned().unwrap_or_default() +} + +/// The spec's numbers: 1,000 new accounts and slots per transaction, kind 3, every frame budgeted +/// at the same 98/100 share as the data size and the KV count; no limit at all leaves it unlimited. +#[test] +fn test_the_state_growth_limit_is_the_specs() { + assert_eq!(TX_STATE_GROWTH_LIMIT, 1_000); + let limits = ProtocolLimits::for_spec(MegaSpecId::SATIN).tx_runtime_limits; + assert_eq!(limits.tx_state_growth_limit, TX_STATE_GROWTH_LIMIT); + assert_eq!(EvmTxRuntimeLimits::no_limits().tx_state_growth_limit, u64::MAX); + assert_eq!(LimitKind::StateGrowth.as_u8(), 3); + assert_eq!(LimitKind::from_u8(3), Some(LimitKind::StateGrowth)); +} + +/// The transaction's own frame gets what the transaction has left, the whole 1,000 under the spec's +/// limits, and the 1,001st fresh slot stops it, kind 3, naming that budget: the stop settles as a +/// revert, and the slot, like every slot the frame wrote, is not kept. The gas pays for every slot, +/// so the count is what stops it, not the price. 1,000 fresh slots fit. +#[test] +fn test_the_1001st_fresh_slot_stops_the_transactions_own_frame() { + let db = |count: u64| { + funded() + .account_code(A, write_slots(BytecodeBuilder::default(), 1, count + 1).stop().build()) + }; + let limits = EvmTxRuntimeLimits::default(); + let fits = run_a(db(1_000), 1_001, limits); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 1_000); + + let stopped = run_a(db(1_001), 1_001, limits); + assert_eq!(stopped.limit_exceeded, budget_crossed(1_000, 1_001)); + assert!(matches!(&stopped.result, ExecutionResult::Revert { .. }), "{:?}", stopped.result); + assert_eq!(output(&stopped), growth_stop(1_000)); + assert_eq!( + stopped.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, + "nothing the frame wrote is kept" + ); + assert!(stopped.state[&A].storage.values().all(|slot| slot.present_value.is_zero())); +} + +/// A child gets 98/100 of what its caller has left: a caller that kept 20 of the 1,000 gives its +/// child `980 × 98 / 100` = 960, the product rounded down rather than the subtraction's 961. The +/// 960th slot fits and the 961st stops the child, naming 960; the caller catches the stop and runs +/// on within what it has left. After a child that kept 960, the caller has the 20 the transaction +/// has left: 20 more fit, and the 21st stops the caller itself, naming its own budget, 1,000. +#[test] +fn test_a_child_gets_98_percent_of_what_its_caller_has_left() { + assert_eq!(share(1_000 - 20), 960); + let db = |child: u64, after: u64| { + let caller = write_slots(BytecodeBuilder::default(), 1, 21); + let caller = write_slots(call_dropping(caller, B), 21, 21 + after).stop().build(); + funded() + .account_code(A, caller) + .account_code(B, write_slots(BytecodeBuilder::default(), 1, child + 1).stop().build()) + }; + let limits = EvmTxRuntimeLimits::default(); + + let full = run_a(db(960, 20), 1_000, limits); + assert!(full.result.is_success(), "{:?}", full.result); + assert_eq!(full.usage.state_growth, 1_000, "20, the child's 960, and 20"); + + let over = run_a(db(960, 21), 1_001, limits); + assert_eq!(over.limit_exceeded, budget_crossed(1_000, 1_001), "the caller's own budget"); + + let child_over = run_a(db(961, 20), 1_001, limits); + assert!(child_over.result.is_success(), "{:?}", child_over.result); + assert_eq!(child_over.limit_exceeded, None, "a stop below is no stop"); + assert_eq!(child_over.usage.state_growth, 40, "the caller's 40; none of the child's"); + assert!( + child_over + .state + .get(&B) + .is_none_or(|b| b.storage.values().all(|s| s.present_value.is_zero())), + "the child's slots went with its stop" + ); +} + +/// Under the spec's 1,000 a frame two calls down gets 960 and one three calls down 940 +/// (`960 × 98 / 100` rounded down), when nothing above it kept anything: the 940th slot there fits +/// and the 941st stops that frame, naming 940; every caller catches the stop and ends. +#[test] +fn test_the_state_growth_budgets_at_depth() { + assert_eq!(share(share(share(1_000))), 940); + let db = |slots: u64| { + let d = BytecodeBuilder::default(); + funded() + .account_code(A, call_answering(BytecodeBuilder::default(), B, U256::ZERO)) + .account_code(B, call_answering(BytecodeBuilder::default(), C, U256::ZERO)) + .account_code(C, call_answering(BytecodeBuilder::default(), D, U256::ZERO)) + .account_code(D, write_slots(d, 1, slots + 1).stop().build()) + }; + let fits = run_a(db(940), 941, EvmTxRuntimeLimits::default()); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 940); + + let stopped = run_a(db(941), 941, EvmTxRuntimeLimits::default()); + assert!(stopped.result.is_success(), "{:?}", stopped.result); + assert_eq!(stopped.limit_exceeded, None, "the callers caught it"); + assert_eq!(output(&stopped), growth_stop(940), "D's stop, handed up as each caller's answer"); + assert_eq!(stopped.usage.state_growth, 0); +} + +/// A frame's net is signed, and its remaining is clamped to the budget it was given: a caller that +/// added 100 of its 1,000 gives its child 882; the child clears those 100 slots — it runs on the +/// caller's storage — so its net is −100, yet what it forwards is still 98/100 of its 882, 864, and +/// the 865th slot of its own child stops that frame. When the child succeeds its net merges, the +/// caller's net is 0, and a later child gets 980; when it reverts, its net is discarded with its +/// writes, the caller keeps its 100, and a later child gets 882. +#[test] +fn test_a_negative_net_does_not_enlarge_the_next_childs_budget() { + assert_eq!((share(900), share(882), share(1_000)), (882, 864, 980)); + let writer = |slots: u64| write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build(); + let caller = |then: Option
| { + let code = delegatecall_dropping(write_slots(BytecodeBuilder::default(), 1, 101), B); + match then { + Some(child) => call_answering(code, child, U256::ZERO), + None => code.stop().build(), + } + }; + let clearer = |then: Option
, reverts: bool| { + let code = clear_slots(BytecodeBuilder::default(), 1, 101); + let code = match then { + Some(child) => call_dropping(code, child), + None => code, + }; + if reverts { + code.revert().build() + } else { + code.stop().build() + } + }; + let limits = EvmTxRuntimeLimits::default(); + + // The clamp: the clearing child's own child gets 864. + for (slots, fits) in [(864, true), (865, false)] { + let db = funded() + .account_code(A, caller(None)) + .account_code(B, clearer(Some(C), false)) + .account_code(C, writer(slots)); + let outcome = run_a(db, 1_100, limits); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + let kept = if fits { slots } else { 0 }; + assert_eq!(outcome.usage.state_growth, kept, "{slots}: the 100 cleared, and C's slots"); + } + + // The merge, and the revert: the next child gets 980, or 882. + for (reverts, budget) in [(false, 980), (true, 882)] { + for slots in [budget, budget + 1] { + let db = funded() + .account_code(A, caller(Some(D))) + .account_code(B, clearer(None, reverts)) + .account_code(D, writer(slots)); + let outcome = run_a(db, 1_100, limits); + let case = format!("child reverts {reverts}, {slots} slots"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let caller_kept = if reverts { 100 } else { 0 }; + if slots == budget { + assert_eq!(outcome.usage.state_growth, caller_kept + slots, "{case}"); + assert!(output(&outcome).is_empty(), "{case}"); + } else { + assert_eq!(output(&outcome), growth_stop(budget), "{case}: D's budget"); + assert_eq!(outcome.usage.state_growth, caller_kept, "{case}"); + } + } + } +} + +/// An `SSTORE` falls on the slot it writes back to zero from an original of zero, and the fall +/// makes room: under a limit of one, a slot written `0 → 1 → 0` nets nothing, so another fresh +/// slot fits after it, and a third crosses. A fall with no earlier rise in the frame — a child +/// clearing a slot its caller made — leaves the child's remaining at its budget, and later rises +/// consume the fall: the child keeps a net of its budget and no more. +#[test] +fn test_a_slot_written_back_to_zero_falls_and_makes_room() { + let code = |extra: u64| { + let code = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .sstore(U256::from(1), U256::ZERO); + write_slots(code, 2, 3 + extra).stop().build() + }; + let fits = run_a(funded().account_code(A, code(0)), 4, growth(1)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 1, "slot 1 rose and fell; slot 2 rose"); + let crosses = run_a(funded().account_code(A, code(1)), 4, growth(1)); + assert_eq!(crosses.limit_exceeded, budget_crossed(1, 2)); + + // Under ten, the caller keeps one slot and gives its child 8; the child clears the caller's + // slot and writes nine of its own on the caller's storage, a net of 8. + assert_eq!(share(10 - 1), 8); + let child = |slots: u64| { + write_slots(clear_slots(BytecodeBuilder::default(), 1, 2), 100, 100 + slots).stop().build() + }; + for (slots, fits) in [(9, true), (10, false)] { + let caller = delegatecall_dropping(write_slots(BytecodeBuilder::default(), 1, 2), B); + let db = funded().account_code(A, caller.stop().build()).account_code(B, child(slots)); + let outcome = run_a(db, 12, growth(10)); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, if fits { slots } else { 1 }, "{slots}"); + } +} + +/// Each site the spec lists adds one new account or slot, and nothing else does: a transaction's +/// value to an account that does not exist, a value `CALL` to one, a creation at an empty address — +/// whatever code it deploys — a creation transaction, a `SELFDESTRUCT` moving a balance to one, an +/// authorization creating its authority, and a deposit creating its caller. An account that exists, +/// a `CALLCODE`, a value call to the calling account itself, a destruction moving nothing, and an +/// authorization of an account that exists add none. +#[test] +fn test_each_site_adds_one_new_account_or_slot() { + let one = U256::from(1); + let contract = |code: Bytes| funded().account_code(A, code); + let value_call = + |to| contract(BytecodeBuilder::default().call(to, one).append(POP).stop().build()); + let fresh_caller = address!("00000000000000000000000000000000006000fe"); + let cases: Vec<(&str, MegaTransactionOutcome, u64)> = vec![ + ( + "the transaction's value to a new account", + run(funded(), call(CALLER, EMPTY, one, BELOW_CAP)), + 1, + ), + ( + "the transaction's value to an account that exists", + run(funded(), call(CALLER, A, one, BELOW_CAP)), + 0, + ), + ( + "a value CALL to a new account", + run(value_call(EMPTY), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 1, + ), + ( + "a value CALL to an account that exists", + run(value_call(CALLER), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 0, + ), + ( + "a value CALL to the calling account itself", + run(value_call(A), call(CALLER, A, U256::ZERO, BELOW_CAP)), + 0, + ), + ( + "a value CALLCODE", + run( + contract( + BytecodeBuilder::default().callcode(EMPTY, one).append(POP).stop().build(), + ), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 0, + ), + ( + "a CREATE deploying 32 bytes", + run( + contract( + BytecodeBuilder::default() + .create(U256::ZERO, crate::common::deploying(32)) + .append(POP) + .stop() + .build(), + ), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 1, + ), + ( + "a creation transaction", + run(funded(), crate::common::create(CALLER, crate::common::deploying(32), BELOW_CAP)), + 1, + ), + ( + "a SELFDESTRUCT moving a balance to a new account", + run( + contract(BytecodeBuilder::default().selfdestruct(EMPTY).build()), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 1, + ), + ( + "a SELFDESTRUCT moving nothing", + run( + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, BytecodeBuilder::default().selfdestruct(EMPTY).build()), + call(CALLER, A, U256::ZERO, BELOW_CAP), + ), + 0, + ), + ( + "an authorization creating its authority", + run( + funded().account_code(A, BytecodeBuilder::default().stop().build()), + authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]), + ), + 1, + ), + ( + "an authorization of an account that exists", + run( + funded() + .account_balance(AUTHORITY_1, one) + .account_code(A, BytecodeBuilder::default().stop().build()), + authorizing_call(CALLER, A, U256::ZERO, BELOW_CAP, DELEGATE, &[(AUTHORITY_1, 0)]), + ), + 0, + ), + ( + "a deposit creating its caller", + run( + funded().account_code(A, BytecodeBuilder::default().stop().build()), + crate::common::deposit(call(fresh_caller, A, U256::ZERO, BELOW_CAP)), + ), + 1, + ), + ]; + for (site, outcome, expected) in cases { + assert!(outcome.result.is_success(), "{site}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, expected, "{site}"); + } +} + +/// A start its caller's account refuses counts nothing and is stopped by no limit, even with no +/// state growth left: a value call the caller cannot fund, a creation it cannot endow. A creation +/// onto an occupied address fails on the collision, after the creator's nonce bump, and adds no +/// state growth, the address being no new account; nor does a `CREATE2` onto an address that holds +/// a balance, which succeeds under a limit of nothing, keeping the creator's nonce record and the +/// created account's. +#[test] +fn test_a_start_that_makes_no_new_account_is_held_to_nothing() { + let one = U256::from(1); + let poor = |code: Bytes| { + MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_code(A, code) + }; + let refused_call = poor(BytecodeBuilder::default().call(EMPTY, one).append(POP).stop().build()); + let refused_creation = poor( + BytecodeBuilder::default() + .create(one, crate::common::deploying(0)) + .append(POP) + .stop() + .build(), + ); + let init = crate::common::deploying(0); + let target = A.create2(B256::ZERO, alloy_primitives::keccak256(&init)); + let creation = BytecodeBuilder::default() + .create2(U256::ZERO, &init, U256::ZERO) + .append(POP) + .stop() + .build(); + let collision = funded() + .account_code(A, creation.clone()) + .account_code(target, Bytes::from_static(&[STOP])); + let funded_target = funded().account_code(A, creation).account_balance(target, one); + for (case, db) in [ + ("a value call the caller cannot fund", refused_call), + ("a creation the caller cannot endow", refused_creation), + ("a creation onto an address with code", collision), + ("a creation onto an address that holds a balance", funded_target), + ] { + let outcome = run_a(db, 1, growth(0)); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{case}"); + assert_eq!(outcome.usage.state_growth, 0, "{case}"); + assert!(output(&outcome).is_empty(), "{case}"); + } + let onto_funded = run_a( + funded() + .account_code( + A, + BytecodeBuilder::default() + .create2(U256::ZERO, &init, U256::ZERO) + .append(POP) + .stop() + .build(), + ) + .account_balance(target, one), + 1, + growth(0), + ); + assert_eq!(onto_funded.usage.write_records, 2, "the creator's nonce and the created account"); + assert_eq!(onto_funded.state[&target].info.nonce, 1, "created"); +} + +/// A creation's budget is 98/100 of what its creator has left at its `CREATE`, the creator's nonce +/// record being counted on the creator once the creation returned: a creator with the whole 1,000 +/// left, whose nonce bump creates nothing, gives its creation 980, +/// against which the created account is the creation's first rise — its init code fits 979 fresh +/// slots, and the 980th stops it, naming 980, which the creator catches. A creation transaction's +/// own frame is no such child: it gets the whole 1,000, the account and 999 slots. +#[test] +fn test_a_creation_is_budgeted_after_its_creators_counts() { + assert_eq!(share(1_000), 980); + let init = |slots: u64| write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build(); + for (slots, fits) in [(979, true), (980, false)] { + let creator = + BytecodeBuilder::default().create(U256::ZERO, init(slots)).append(POP).stop().build(); + let outcome = + run_a(funded().account_code(A, creator), 1_000, EvmTxRuntimeLimits::default()); + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{slots}"); + let created = if fits { 1 + slots } else { 0 }; + assert_eq!(outcome.usage.state_growth, created, "{slots}: the account and its slots"); + assert_eq!(outcome.state[&A].info.nonce, 1, "{slots}: the creator's bump stands"); + } + for (slots, fits) in [(999, true), (1_000, false)] { + let tx = crate::common::create(CALLER, init(slots), room(1_001)); + let outcome = execute_under(funded(), tx, EvmTxRuntimeLimits::default()); + if fits { + assert!(outcome.result.is_success(), "{slots}: {:?}", outcome.result); + assert_eq!(outcome.usage.state_growth, 1_000, "the account and 999 slots"); + } else { + assert_eq!(outcome.limit_exceeded, budget_crossed(1_000, 1_001), "{slots}"); + } + } +} + +/// A write that crosses more than one counted dimension stops on the first of data size, KV +/// updates and state growth: a fresh slot's record over the data size and its slot over the state +/// growth is kind 0; its record over the KV count and its slot over the state growth, kind 1. +/// Compute is decided at the charge, before the write is counted: a fresh `SSTORE` whose regular +/// charge crosses gas detention stops with kind 2, though its slot would have crossed the state +/// growth. +#[test] +fn test_a_slot_crossing_several_limits_stops_on_the_first_in_order() { + use revm::bytecode::opcode::TIMESTAMP; + let writes = + || funded().account_code(A, write_slots(BytecodeBuilder::default(), 1, 2).stop().build()); + let kind_of = |outcome: &MegaTransactionOutcome| match outcome.limit_exceeded { + Some(LimitCheck::ExceedsLimit { kind, .. }) => kind, + other => panic!("expected a stop: {other:?}"), + }; + let data = growth(0).with_tx_data_size_limit(TX_BODY_SIZE); + assert_eq!(kind_of(&run_a(writes(), 1, data)), LimitKind::DataSize); + let kv = growth(0).with_tx_kv_update_limit(0); + assert_eq!(kind_of(&run_a(writes(), 1, kv)), LimitKind::KvUpdate); + assert_eq!(kind_of(&run_a(writes(), 1, growth(0))), LimitKind::StateGrowth); + + let detained = funded().account_code( + A, + write_slots(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), 1, 2).stop().build(), + ); + let capped = growth(0).with_block_env_access_compute_gas_limit(100); + assert_eq!(kind_of(&run_a(detained.clone(), 1, capped)), LimitKind::ComputeGas); + assert_eq!(kind_of(&run_a(detained, 1, growth(0))), LimitKind::StateGrowth, "undetained"); +} + +/// An authorization list is decided before it is applied, on the accounts it would create: a list +/// whose new authorities would cross the transaction's state growth is skipped whole — no authority +/// is bumped, delegated or counted — and the transaction's own frame returns the stop before it +/// runs, kind 3, naming the transaction's limit, since no frame budget exists yet. A list crossing +/// both counts is the KV count's, kind 1. Repeated acceptances of one new authority create it once. +/// A list that fits is applied, and its accounts are counted on the transaction, so the first +/// frame's budget is what they leave: with none left, the transaction's value to a new account +/// stops that frame at its start, naming a budget of nothing, and the authorities stay applied. +#[test] +fn test_an_authorization_list_is_held_to_the_state_growth_it_would_add() { + let db = || funded().account_code(A, BytecodeBuilder::default().stop().build()); + let both = [(AUTHORITY_1, 0), (AUTHORITY_2, 0)]; + let tx = |value: U256, list: &[(Address, u64)]| { + authorizing_call(CALLER, A, value, room(0), DELEGATE, list) + }; + let untouched = |outcome: &MegaTransactionOutcome| { + for authority in [AUTHORITY_1, AUTHORITY_2] { + let account = outcome.state.get(&authority); + assert!( + account.is_none_or(|account| account.info.nonce == 0), + "{authority}: not bumped" + ); + assert!( + account.is_none_or(|account| account.info.is_empty_code_hash()), + "{authority}: not delegated" + ); + } + }; + + let skipped = execute_under(db(), tx(U256::ZERO, &both), growth(1)); + assert_eq!( + skipped.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 1, + used: 2, + frame_local: false + }) + ); + assert!(matches!(&skipped.result, ExecutionResult::Revert { .. }), "{:?}", skipped.result); + assert_eq!( + skipped.usage, + LimitUsage { data_size: skipped.usage.data_size, write_records: 0, state_growth: 0 } + ); + assert_eq!(skipped.gas.state, 0, "no authority's state gas"); + untouched(&skipped); + + let both_counts = + execute_under(db(), tx(U256::ZERO, &both), growth(1).with_tx_kv_update_limit(1)); + assert!( + matches!( + both_counts.limit_exceeded, + Some(LimitCheck::ExceedsLimit { kind: LimitKind::KvUpdate, limit: 1, .. }) + ), + "{:?}", + both_counts.limit_exceeded + ); + + let repeated = + execute_under(db(), tx(U256::ZERO, &[(AUTHORITY_1, 0), (AUTHORITY_1, 1)]), growth(1)); + assert!(repeated.result.is_success(), "{:?}", repeated.result); + assert_eq!((repeated.usage.write_records, repeated.usage.state_growth), (1, 1)); + assert_eq!(repeated.state[&AUTHORITY_1].info.nonce, 2, "both applied"); + + let fits = execute_under(db(), tx(U256::ZERO, &both), growth(2)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 2); + + let recipient_stopped = execute_under( + funded(), + authorizing_call(CALLER, EMPTY, U256::from(1), room(0), DELEGATE, &both), + growth(2), + ); + assert_eq!(recipient_stopped.limit_exceeded, budget_crossed(0, 1), "the recipient"); + assert_eq!(recipient_stopped.usage.state_growth, 2, "the authorities stay"); + for authority in [AUTHORITY_1, AUTHORITY_2] { + assert_eq!(recipient_stopped.state[&authority].info.nonce, 1, "{authority}: applied"); + } + assert!( + recipient_stopped.state.get(&EMPTY).is_none_or(|account| account.info.is_empty()), + "the recipient was not created" + ); +} + +/// A deposit's caller, created before its first frame, is one account of state growth on the +/// transaction: it outlives a stop of the first frame, and the first frame's budget is what it +/// leaves — under a limit of two, one fresh slot fits and the second stops the frame. +#[test] +fn test_a_deposits_new_caller_is_counted_before_its_first_frame() { + let fresh = address!("00000000000000000000000000000000006000fd"); + let db = |slots: u64| { + funded() + .account_code(A, write_slots(BytecodeBuilder::default(), 1, slots + 1).stop().build()) + }; + let tx = || crate::common::deposit(call(fresh, A, U256::ZERO, room(2))); + let fits = execute_under(db(1), tx(), growth(2)); + assert!(fits.result.is_success(), "{:?}", fits.result); + assert_eq!(fits.usage.state_growth, 2, "the caller and the slot"); + let stopped = execute_under(db(2), tx(), growth(2)); + assert_eq!( + stopped.limit_exceeded, + budget_crossed(1, 2), + "the frame's budget: what the caller left" + ); + assert_eq!(stopped.usage.state_growth, 1, "the caller stays"); + assert_eq!(stopped.state[&fresh].info.nonce, 1, "and exists"); + // Under a limit of nothing, which the spec's 1,000 never is, the caller alone is over it, and + // it is counted all the same: the first frame's start, held to the transaction's limit, is the + // stop, naming that limit, before the frame writes anything. + let none_left = execute_under(db(1), tx(), growth(0)); + assert_eq!( + none_left.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 0, + used: 1, + frame_local: false + }) + ); + assert_eq!(none_left.usage.state_growth, 1, "the caller, over the limit, stays"); + assert!(none_left.state[&A].storage.values().all(|slot| slot.present_value.is_zero())); +} + +/// A frame whose start adds a new account it has no budget for is stopped before it runs, and what +/// its start moved goes back: a value call to a new account under a budget of nothing is answered +/// with the stop, its value not moved, and its caller catches it. A creation's start alike: its +/// init code never runs, and its creator keeps the nonce bump revm made before the creation's +/// checkpoint. A call to a precompile whose start adds an account crosses the state growth before +/// gas detention prices it: the records' stop is the answer, though the price crosses the compute +/// limit too. +#[test] +fn test_a_start_over_the_state_growth_is_stopped_before_it_runs() { + use revm::bytecode::opcode::TIMESTAMP; + let one = U256::from(1); + let value_call = + funded().account_code(A, call_answering(BytecodeBuilder::default(), EMPTY, one)); + let answered = run_a(value_call, 1, growth(0)); + assert!(answered.result.is_success(), "{:?}", answered.result); + assert_eq!(output(&answered), growth_stop(0), "the value call's answer is the stop"); + assert!(answered.state.get(&EMPTY).is_none_or(|account| account.info.is_empty()), "not moved"); + assert_eq!(answered.state[&A].info.balance, U256::from(1_000), "the value came back"); + + let marker = BytecodeBuilder::default().sstore(U256::from(1), one).stop().build(); + let creator = BytecodeBuilder::default().create(U256::ZERO, marker).append(POP).stop().build(); + let created = run_a(funded().account_code(A, creator), 1, growth(0)); + assert!(created.result.is_success(), "{:?}", created.result); + assert_eq!(created.usage.state_growth, 0, "the init code never ran"); + assert_eq!(created.state[&A].info.nonce, 1, "the creator's bump stands"); + assert!(created.state.get(&A.create(0)).is_none_or(|account| account.info.is_empty())); + + // The KZG point evaluation, priced 100,000, past a compute limit of 50,000 after the read, + // which the call's own charges stay within. + let kzg = address!("000000000000000000000000000000000000000a"); + let precompile = funded().account_code( + A, + call_answering(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), kzg, one), + ); + let cap = EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(50_000); + let both = run_a(precompile.clone(), 1, cap.with_tx_state_growth_limit(0)); + assert_eq!(output(&both), growth_stop(0), "the records first"); + let priced = run_a(precompile, 1, cap); + let (kind, _) = mega_evm::decode_mega_limit_exceeded(&output(&priced)).expect("a stop"); + assert_eq!(kind, LimitKind::ComputeGas, "without the state growth, the price"); +} diff --git a/crates/mega-evm/tests/satin/stops.rs b/crates/mega-evm/tests/satin/stops.rs index 781397192..8ece1bcd5 100644 --- a/crates/mega-evm/tests/satin/stops.rs +++ b/crates/mega-evm/tests/satin/stops.rs @@ -1,12 +1,12 @@ //! The revert-class stop, pinned as a matrix. //! -//! A limit — data size or gas detention's compute limit — stops the frame that crosses it with a -//! revert: the frame reverts with `MegaLimitExceeded(kind, limit)` and keeps nothing it did, and -//! its caller resumes as after any revert. A crossing the transaction's own frame makes is the -//! transaction's result, which settles like an EIP-8037 revert: the sender pays for what ran, and -//! its unspent regular gas and the reservoir come back. A frame budget stops its frame the same -//! way. A real out-of-gas and a precompile given less than its price still halt, and burn what -//! their frame was given. +//! A limit — data size, KV updates, state growth or gas detention's compute limit — stops the +//! frame that crosses it with a revert: the frame reverts with `MegaLimitExceeded(kind, limit)` and +//! keeps nothing it did, and its caller resumes as after any revert. A crossing the transaction's +//! own frame makes is the transaction's result, which settles like an EIP-8037 revert: the sender +//! pays for what ran, and its unspent regular gas and the reservoir come back. A frame budget stops +//! its frame the same way. A real out-of-gas and a precompile given less than its price still halt, +//! and burn what their frame was given. //! //! The matrix crosses each limit in the transaction's own frame and in a frame three calls below //! it, below the execution cap and above it, where a reservoir pays the body first, without an @@ -19,12 +19,13 @@ //! stopped transaction keeps. //! //! A column of creations revived by an inspector that rewrites every frame result into a success -//! shows that a revived stop settles as a frame that kept nothing, and is no stop. +//! shows that a revived stop is taken as given — a success that keeps what it counted before the +//! stop — and is no stop. //! -//! The last cells cross a limit three calls down with a frame answered without running — an -//! answer past what the compute limit leaves it, a precompile run on that allowance, and a start -//! whose records cross the data-size limit before the frame is built — and the callers catch the -//! stop the same way. +//! The last cells cross a limit three calls down with a frame answered without running — a +//! precompile run on what the compute limit leaves it, and a start whose records cross the +//! data-size limit before the frame is built — and the callers catch the stop the same way. An +//! inspector's answer past that allowance is taken as given, and is no stop. use alloy_primitives::{address, Address, Bytes, U256}; use mega_evm::{ @@ -92,18 +93,27 @@ const TWIN_REVERT: u64 = 4; #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Limit { DataSize, + KvUpdate, + StateGrowth, Compute, } impl Limit { - const ALL: [Self; 2] = [Self::DataSize, Self::Compute]; + const ALL: [Self; 4] = [Self::DataSize, Self::KvUpdate, Self::StateGrowth, Self::Compute]; const fn kind(self) -> LimitKind { match self { Self::DataSize => LimitKind::DataSize, + Self::KvUpdate => LimitKind::KvUpdate, + Self::StateGrowth => LimitKind::StateGrowth, Self::Compute => LimitKind::ComputeGas, } } + + /// Whether the limit is one the layer counts, crossed by a write, rather than gas detention's. + const fn is_counted(self) -> bool { + !matches!(self, Self::Compute) + } } /// Appends a log with no topic and no data: 32 bytes of data size, and a log a stop must not keep. @@ -142,7 +152,9 @@ fn frame_code(limit: Limit, depth: usize, crossing: usize, twin: bool) -> Bytes let code = match limit { Limit::Compute if twin => code.append(TIMESTAMP), Limit::Compute => work(code.append_many([TIMESTAMP, POP]), ROUNDS), - Limit::DataSize => code.sstore(CROSSING_SLOT, U256::from(1)), + Limit::DataSize | Limit::KvUpdate | Limit::StateGrowth => { + code.sstore(CROSSING_SLOT, U256::from(1)) + } }; if twin { revert(code).build() @@ -297,19 +309,21 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { // The regular gas the frames spent up to the crossing: for the compute limit, up to the read. let before_crossing = twin.gas.regular - intrinsic.gas.regular - TWIN_REVERT; - // The limit crossed, and the usage that crossed it: one more byte than the limit. The compute - // limit is set by the read, at the compute it ran to plus the cap, and the stop reports the - // compute up to the charge that crosses it: after the read's `POP`, one of the work's. - let (configured, value) = limits_of(limit, crossing); - let (value, used) = match value { - Some(value) => (value, value + 1), + // The limit crossed, and the usage that crossed it. A counted limit is crossed by the crossing + // frame's write, which takes the transaction one over its limit and the frame over its own + // budget, which the stop names. The compute limit is set by the read, at the compute it ran + // to plus the cap, and the stop reports the compute up to the charge that crosses it: after + // the read's `POP`, one of the work's. + let (configured, crossing_of) = limits_of(limit, crossing); + let (value, used, frame_local, tx_limit) = match crossing_of { + Some(Crossing { tx_limit, budget, used }) => (budget, used, true, tx_limit), None => { let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); - (before_crossing + CAP, before_crossing + CAP - left) + let value = before_crossing + CAP; + (value, value - left, false, value) } }; - let stop = - LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local: false }; + let stop = LimitCheck::ExceedsLimit { kind: limit.kind(), limit: value, used, frame_local }; // What ran: up to the crossing, and for the compute limit up to the charge that crosses it. // The callers that catch the stop end at no cost. let ran = if limit == Limit::Compute { used } else { before_crossing }; @@ -372,7 +386,13 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { } assert_eq!(outcome.usage, twin.usage, "{cell}: what is kept"); match limit { - Limit::DataSize => assert!(outcome.usage.data_size <= value, "{cell}: within it"), + Limit::DataSize => assert!(outcome.usage.data_size <= tx_limit, "{cell}: within it"), + Limit::KvUpdate => { + assert!(outcome.usage.write_records <= tx_limit, "{cell}: within it") + } + Limit::StateGrowth => { + assert!(outcome.usage.state_growth <= tx_limit, "{cell}: within it") + } Limit::Compute => { let compute = outcome.gas.regular - intrinsic.gas.regular; assert!(compute <= value, "{cell}: within the limit, {compute} of {value}"); @@ -381,7 +401,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { if !caught { assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{cell}: the body stays" ); } @@ -390,7 +410,7 @@ fn assert_cell(limit: Limit, crossing: usize, gas_limit: u64) { // crossed, and every caller resumed and ended. assert_eq!(recorded.gas, plain.gas, "{row}"); assert_eq!(recorder.marker_writes(), 0, "{row}: no frame ran on after the crossing"); - if limit == Limit::DataSize { + if limit.is_counted() { assert_eq!( recorder.last_in(CHAIN[crossing]), Some((SSTORE, Some(CROSSING_SLOT))), @@ -451,9 +471,11 @@ impl Inspector, EthInterpreter> for Halter { /// An inspector that rewrites every frame result into a halt gets the halt: a stop is a revert of /// the frame that crossed, which the rewrite turns into a halt like any other result, so the -/// transaction halts, keeps nothing but its body, and reports no stop, whether the frame that +/// transaction halts, counts nothing but its body, and reports no stop, whether the frame that /// crossed was its own or three calls below, under every limit and at either tier. The stop is -/// in the inspector's hands as every result is. +/// in the inspector's hands as every result is. Each frame above the one that crossed succeeded, +/// and revm committed its journal before the inspector rewrote its result, so the log it made is +/// in the receipt, as revm leaves it. /// /// Rules: [S11.1], [S11.6]. Independence: constants — the body is `TX_BODY_SIZE`. #[test] @@ -478,10 +500,14 @@ fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { evm.execute_transaction(call(CALLER, A, U256::ZERO, gas_limit)).unwrap(); assert!(halted.result.is_halt(), "{case}: {:?}", halted.result); assert_eq!(halted.limit_exceeded, None, "{case}: the result is no stop"); - assert!(halted.result.logs().is_empty(), "{case}"); + assert_eq!( + halted.result.logs().len(), + crossing, + "{case}: the logs of the frames above the one that crossed" + ); assert_eq!( halted.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{case}: the body alone" ); } @@ -490,18 +516,54 @@ fn test_an_inspector_that_rewrites_a_stop_into_a_halt_gets_the_halt() { } } -/// The limits a cell runs under, and the stop's limit where it is known before the run: every -/// dimension but the compute limit, which the read sets. -fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { +/// Where a counted limit is crossed: the transaction's limit, the budget of the frame that crosses +/// it, which the stop names, and what that frame used of it with the write that crossed. +#[derive(Clone, Copy, Debug)] +struct Crossing { + tx_limit: u64, + budget: u64, + used: u64, +} + +/// The limits a cell runs under, and where a counted limit is crossed, which is known before the +/// run: every dimension but the compute limit, which the read sets. +/// +/// The transaction's limit is one short of what the chain keeps with the crossing write. The +/// transaction's own frame gets what the body leaves of it, and each frame below 98% of what its +/// caller has left at its call: `A` has logged and written its [`OWN_SLOTS`] by then, `B` and `C` +/// have logged. The crossing frame's write crosses its budget, the transaction's limit with it. +fn limits_of(limit: Limit, crossing: usize) -> (EvmTxRuntimeLimits, Option) { let frames = crossing as u64 + 1; - match limit { + // What the transaction's own frame keeps before it calls or crosses, what a frame below keeps + // before it calls or crosses, and what the crossing write adds, in the limit's unit. + let (own, below, write) = match limit { + Limit::DataSize => (LOG_BASE_SIZE + OWN_SLOTS * WRITE_RECORD_SIZE, LOG_BASE_SIZE, 40), + // The fresh slots are new slots, one each, as they are write records. + Limit::KvUpdate | Limit::StateGrowth => (OWN_SLOTS, 0, 1), + Limit::Compute => return (EvmTxRuntimeLimits::default(), None), + }; + let (limits, tx_limit, outside) = match limit { Limit::DataSize => { - let value = - TX_BODY_SIZE + frames * LOG_BASE_SIZE + (OWN_SLOTS + 1) * WRITE_RECORD_SIZE - 1; - (EvmTxRuntimeLimits::default().with_tx_data_size_limit(value), Some(value)) + let value = TX_BODY_SIZE + own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_data_size_limit(value), value, TX_BODY_SIZE) + } + Limit::KvUpdate => { + let value = own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_kv_update_limit(value), value, 0) } - Limit::Compute => (EvmTxRuntimeLimits::default(), None), + _ => { + let value = own + (frames - 1) * below + write - 1; + (EvmTxRuntimeLimits::default().with_tx_state_growth_limit(value), value, 0) + } + }; + let share = |left: u64| left * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let mut budget = tx_limit - outside; + let mut kept = own; + for _ in 0..crossing { + budget = share(budget - kept); + kept = below; } + (limits, Some(Crossing { tx_limit, budget, used: kept + write })) } /* ---------- creations under an inspector that revives them ---------- */ @@ -514,7 +576,7 @@ enum Creation { /// The transaction's own frame creates a contract whose init code crosses the limit. Nested, /// The transaction's own frame creates a contract whose start crosses the limit — its write - /// records, or the account it adds — so its init code never runs. + /// records, or the new account it adds — so its init code never runs. NestedStart, } @@ -548,44 +610,77 @@ fn creation_run( } } +/// `creation` for `limit` run without limits, where it succeeds. +fn unlimited_creation_run( + creation: Creation, + limit: Limit, + gas_limit: u64, +) -> MegaTransactionOutcome { + let (db, tx) = creation_run(creation, limit, gas_limit); + let unlimited = + MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) + .execute_transaction(tx) + .expect("the transaction is valid"); + assert!(unlimited.result.is_success(), "{creation:?}, {limit:?}: {:?}", unlimited.result); + unlimited +} + /// The limits under which `creation` crosses `limit` by one unit at the place it names. /// /// Where the init code crosses, the limit is one unit below what the whole transaction uses without -/// limits, whose last write is the init code's; the compute limit is the spec's cap. Where the -/// start crosses, the limit is what the transaction used before it. +/// limits, whose last write is the init code's; the compute limit is the spec's cap. For a nested +/// creation's data size it is one record below: a byte below, the creation's share would hold all +/// it writes, and the stop would be its creator's once its nonce record is counted; a record below, +/// the share falls short of the creation's last write by the part its creator keeps. Where the +/// start crosses, the limit is what the transaction used before it and the creator's nonce record: +/// the creation's share of that falls short of its start, and the creator keeps its record once +/// the creation returned. fn creation_limits(creation: Creation, limit: Limit, gas_limit: u64) -> EvmTxRuntimeLimits { let limits = EvmTxRuntimeLimits::default(); if matches!(creation, Creation::NestedStart) { return match limit { - Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE), + Limit::DataSize => limits.with_tx_data_size_limit(TX_BODY_SIZE + WRITE_RECORD_SIZE), + Limit::KvUpdate => limits.with_tx_kv_update_limit(1), + // `A` exists, so its nonce record is no new account. + Limit::StateGrowth => limits.with_tx_state_growth_limit(0), Limit::Compute => unreachable!("a start charges no compute past the cap"), }; } - let (db, tx) = creation_run(creation, limit, gas_limit); - let unlimited = - MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())) - .execute_transaction(tx) - .expect("the transaction is valid"); - assert!(unlimited.result.is_success(), "{creation:?}, {limit:?}: {:?}", unlimited.result); - match limit { - Limit::DataSize => limits.with_tx_data_size_limit(unlimited.usage.data_size - 1), - Limit::Compute => limits, + let unlimited = unlimited_creation_run(creation, limit, gas_limit); + match (creation, limit) { + (Creation::Nested, Limit::DataSize) => { + limits.with_tx_data_size_limit(unlimited.usage.data_size - WRITE_RECORD_SIZE) + } + (_, Limit::DataSize) => limits.with_tx_data_size_limit(unlimited.usage.data_size - 1), + (_, Limit::KvUpdate) => limits.with_tx_kv_update_limit(unlimited.usage.write_records - 1), + // The created account and the init code's slot are the creation's new state, two of it: + // a nested creation's budget, 98% of the whole count, is one short of them. + (Creation::Nested, Limit::StateGrowth) => { + limits.with_tx_state_growth_limit(unlimited.usage.state_growth) + } + (_, Limit::StateGrowth) => { + limits.with_tx_state_growth_limit(unlimited.usage.state_growth - 1) + } + (_, Limit::Compute) => limits, } } /// A creation the limit stopped, revived by an inspector that rewrites every frame result into a -/// success, settles as a frame that kept nothing, as a revived call does, and is no stop: the -/// result of the transaction's own frame is the inspector's success, so the outcome names no stop. -/// A creation transaction whose init code crosses a limit, a nested creation whose init code -/// crosses one, and a nested creation whose start crosses one each end with the stop before their -/// revival, deploy nothing, keep what the run without the inspector keeps, and bill what it bills, -/// below the execution cap and above it. +/// success, is taken as given, as a revived call is, and is no stop: the result of the +/// transaction's own frame is the inspector's success, so the outcome names no stop. A creation +/// transaction whose init code crosses a limit, a nested creation whose init code crosses one, and +/// a nested creation whose start crosses one each end with the stop before their revival and deploy +/// nothing: the stop reverted the creation's journal. The revival settles as a success, so what the +/// creation counted before it crossed is kept — all the creation counts without limits but the +/// write that crossed. Where its start crossed, it counted nothing of the start: its creator keeps +/// its own nonce record, counted on it once the creation returned, and catches the start's stop, +/// so the revival changes the creation's result alone. Below the execution cap and above it. #[test] -fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { +fn test_a_revived_creation_keeps_what_it_counted_before_its_stop() { let cases = [ (Creation::Transaction, Limit::ALL.as_slice()), (Creation::Nested, Limit::ALL.as_slice()), - (Creation::NestedStart, [Limit::DataSize].as_slice()), + (Creation::NestedStart, [Limit::DataSize, Limit::KvUpdate, Limit::StateGrowth].as_slice()), ]; for (creation, limits) in cases { for &limit in limits { @@ -626,8 +721,30 @@ fn test_a_revived_creation_settles_as_a_frame_that_kept_nothing() { revived.state.get(&created).is_none_or(|account| account.info.is_empty()), "{case}: nothing deployed" ); - assert_eq!(revived.usage, plain.usage, "{case}: what the plain run keeps"); - assert_eq!(revived.gas, plain.gas, "{case}: what the plain run bills"); + let unlimited = unlimited_creation_run(creation, limit, gas_limit); + let counted = match (creation, limit) { + // `A` exists, so its nonce record is no new account. + (Creation::NestedStart, _) => LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 0, + }, + // The crossing write, a fresh slot, is one record and one new slot. + (_, Limit::DataSize | Limit::KvUpdate | Limit::StateGrowth) => LimitUsage { + data_size: unlimited.usage.data_size - WRITE_RECORD_SIZE, + write_records: unlimited.usage.write_records - 1, + state_growth: unlimited.usage.state_growth - 1, + }, + (_, Limit::Compute) => unlimited.usage, + }; + assert_eq!(revived.usage, counted, "{case}: what it counted before its stop"); + if matches!(creation, Creation::NestedStart) { + // `A` catches the start's stop and keeps the same. + assert!(plain.result.is_success(), "{case}: {:?}", plain.result); + assert_eq!(plain.usage, counted, "{case}: the stop kept nothing of the start"); + } else { + assert_ne!(revived.usage, plain.usage, "{case}: which the stop takes back"); + } } } } @@ -919,6 +1036,14 @@ fn slots_past_the_cap() -> u64 { CAP / fresh_write() + 1 } +/// The spec's limits with the state-growth limit lifted, which these rows run under: their writes +/// are [`slots_past_the_cap`] fresh slots, more than the 1,000 new slots the spec's limit lets a +/// transaction keep, so under it the 1,001st slot would stop the frame before its compute reached +/// the cap. +fn detention_limits() -> EvmTxRuntimeLimits { + EvmTxRuntimeLimits::default().with_tx_state_growth_limit(u64::MAX) +} + /// Appends writes of the fresh slots `1..=`[`slots_past_the_cap`]: 20,011,218 of compute at the /// schedule's prices, past the cap. fn writes_past_the_cap(code: BytecodeBuilder) -> BytecodeBuilder { @@ -1007,7 +1132,7 @@ fn test_volatile_data_access_oog_does_not_consume_all_gas() { let code = writes_past_the_cap(BytecodeBuilder::default().append_many([TIMESTAMP, POP])); let db = MemoryDatabase::default().account_code(A, code.stop().build()); let left = pop_then_writes().left(CAP); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); assert_eq!(accessed, mega_evm::VolatileDataAccess::TIMESTAMP); } @@ -1026,7 +1151,7 @@ fn test_nested_call_block_env_access_child_oog() { // charge was not made from. let left = pop_then_writes().left(CAP); let left = Charges::default().then(&[2]).fresh_writes(1).left(left); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 10_000, "the child read near the start: {}", limit - CAP); } @@ -1046,7 +1171,7 @@ fn test_parent_block_env_access_oog_after_nested_call() { .then(&[2, 2, 2, 2, 2, 2, 3, 2, cold_access(), 3, 3, 3, 2, 2]) .fresh_writes(slots_past_the_cap()) .left(CAP); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "the read came first: {}", limit - CAP); } @@ -1058,7 +1183,7 @@ fn test_an_oracle_read_holds_the_transaction_to_its_cap() { let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), None)); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); - let (limit, accessed) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, accessed) = assert_detention_stop(db, detention_limits(), left); assert!(limit - ORACLE_ACCESS_COMPUTE_GAS < 10_000, "{}", limit - ORACLE_ACCESS_COMPUTE_GAS); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1069,7 +1194,7 @@ fn test_oracle_volatile_data_access_oog_does_not_consume_all_gas() { let code = writes_past_the_cap(call_oracle(BytecodeBuilder::default(), Some(0xffff))); let db = with_oracle_read(MemoryDatabase::default().account_code(A, code.stop().build())); let left = oracle_pops_then_writes().left(ORACLE_ACCESS_COMPUTE_GAS); - assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + assert_detention_stop(db, detention_limits(), left); } /// A contract that calls one that reads the Oracle's storage and then writes the fresh slots: the @@ -1096,8 +1221,7 @@ fn test_parent_runs_out_of_gas_after_oracle_access() { 2, ]; let left = Charges::default().then(&sload).left(left); - let (_, accessed) = - assert_detention_stop(with_oracle_read(db), EvmTxRuntimeLimits::default(), left); + let (_, accessed) = assert_detention_stop(with_oracle_read(db), detention_limits(), left); assert_eq!(accessed, mega_evm::VolatileDataAccess::ORACLE); } @@ -1109,7 +1233,7 @@ fn test_both_volatile_data_access_oog_does_not_consume_all_gas() { const ORACLE_CAP: u64 = 1_000_000; let code = call_oracle(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), Some(0xffff)); let db = MemoryDatabase::default().account_code(A, writes_past_the_cap(code).stop().build()); - let limits = EvmTxRuntimeLimits::default().with_oracle_access_compute_gas_limit(ORACLE_CAP); + let limits = detention_limits().with_oracle_access_compute_gas_limit(ORACLE_CAP); let left = oracle_pops_then_writes().left(ORACLE_CAP); let (limit, accessed) = assert_detention_stop(with_oracle_read(db), limits, left); assert!(limit - ORACLE_CAP < 10_000, "the Oracle's read binds: {limit}"); @@ -1126,7 +1250,7 @@ fn test_volatile_access_post_access_cap_enforced() { let code = work(BytecodeBuilder::default().append_many([TIMESTAMP, POP]), ROUNDS); let db = MemoryDatabase::default().account_code(A, code.stop().build()); let left = Charges::default().then(&[2]).work(ROUNDS, 0).left(CAP); - let (limit, _) = assert_detention_stop(db, EvmTxRuntimeLimits::default(), left); + let (limit, _) = assert_detention_stop(db, detention_limits(), left); assert!(limit - CAP < 1_000, "{}", limit - CAP); } @@ -1227,7 +1351,10 @@ fn test_data_limit_exceed_in_nested_call() { let outcome = execute(db, EvmTxRuntimeLimits::default().with_tx_data_size_limit(limit), BELOW); assert!(outcome.result.is_success(), "the caller caught the stop: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); let ran = 15_000 + 15 + 3_000 + 5 + 2_100 + 10_100 + 2; assert_eq!(outcome.gas.regular, ran, "what ran, on the regular ledger"); assert_eq!(outcome.gas.history, body_history(0), "the body's history alone"); @@ -1236,7 +1363,8 @@ fn test_data_limit_exceed_in_nested_call() { } /// A value transfer to a contract that writes a slot, under a limit one byte above the body: the -/// first frame's start crosses it, so the value never moves and the contract never runs. +/// first frame's start crosses it — its own budget of one byte, and the transaction's limit — so +/// the value never moves and the contract never runs. #[test] fn test_state_revert_when_exceeding_limit() { let db = MemoryDatabase::default() @@ -1251,9 +1379,12 @@ fn test_state_revert_when_exceeding_limit() { assert!( matches!( stop, - LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit, frame_local: false, .. } - if limit == TX_BODY_SIZE + 1 + LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, limit: 1, frame_local: true, .. } ), + "the frame's budget, the byte the body leaves: {stop:?}" + ); + assert!( + matches!(stop, LimitCheck::ExceedsLimit { used, .. } if used == WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE), "{stop:?}" ); assert!( @@ -1262,7 +1393,10 @@ fn test_state_revert_when_exceeding_limit() { "{:?}", outcome.result ); - assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }); + assert_eq!( + outcome.usage, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } + ); assert!(outcome.state.get(&A).is_none_or(|a| a.storage.is_empty() && a.info.balance.is_zero())); assert_eq!(outcome.state[&CALLER].info.balance, U256::from(10_000), "the value did not move"); } @@ -1295,15 +1429,15 @@ fn test_detention_plus_intrinsic_data_size_overflow() { } /// A call a data-size limit stopped — its own frame budget, or the transaction's limit — revived -/// into a success by an inspector, hands its caller nothing it counted: its checkpoint was reverted -/// before the inspector saw its result, so its log is not kept, and its lane goes the way its log -/// did. Its caller runs on within the limits, and the transaction is the one no inspector runs: the -/// rewrite changed only the flag `A` drops. +/// into a success by an inspector, hands its caller nothing to count: its checkpoint was reverted +/// before the inspector saw its result, so its log is not kept, and the log was its one write, +/// which the crossing counted nothing of. Its caller runs on within the limits, and the transaction +/// is the one no inspector runs: the rewrite changed only the flag `A` drops. /// /// Under a frame cap of 1,000 bytes `A` gives `B` 98% of it, and `B`'s log of 1,000 bytes counts /// 1,032, which crosses `B`'s budget, and would cross `A`'s were it handed on. Under a transaction -/// limit of the body and 1,000 bytes the same log crosses the transaction's limit, which is checked -/// first. +/// limit of the body and 1,000 bytes the same log crosses the transaction's limit and `B`'s budget, +/// 98% of the 1,000 `A` is given, which is checked first and named. #[test] fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { const CAP: u64 = 1_000; @@ -1321,9 +1455,7 @@ fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { let unlimited = EvmTxRuntimeLimits::no_limits(); let rows = [ ("its frame budget", unlimited.with_frame_data_size_limit(CAP), share), - ("the transaction's limit", unlimited.with_tx_data_size_limit(TX_BODY_SIZE + CAP), { - TX_BODY_SIZE + CAP - }), + ("the transaction's limit", unlimited.with_tx_data_size_limit(TX_BODY_SIZE + CAP), share), ]; for (row, limits, crossed) in rows { let plain = execute(db.clone(), limits, BELOW); @@ -1352,8 +1484,12 @@ fn test_a_call_revived_past_a_limit_hands_its_caller_nothing() { assert_eq!(outcome.limit_exceeded, None, "{row}: a stop below is no stop"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, write_records: 1 }, - "{row}: the body and A's marker: none of B's log" + LimitUsage { + data_size: TX_BODY_SIZE + WRITE_RECORD_SIZE, + write_records: 1, + state_growth: 1 + }, + "{row}: the body and A's marker, a new slot: none of B's log" ); assert!(outcome.result.logs().is_empty(), "{row}: B's log was reverted with B"); assert!(plain.result.is_success(), "{row}: {:?}", plain.result); @@ -1371,14 +1507,14 @@ const EMPTY: Address = address!("0000000000000000000000000000000000500005"); #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Answered { /// An inspector answers the call to `D` having spent all it was forwarded, past what the - /// compute limit leaves the frame. An interceptor's answer is settled the same way; none of - /// this engine's interceptors spends gas. + /// compute limit leaves the frame. An inspector's answer is taken as given: it is no stop + /// (see [`test_an_inspectors_answer_past_the_allowance_is_taken_as_given`]). PastTheAllowance, /// `C` calls a precompile priced past the cap, which revm runs on the allowance: it runs out /// of it without computing. Precompile, /// `C` sends a wei to [`EMPTY`], whose start's records and transfer log cross the data-size - /// limit, before revm builds the frame. + /// limit once revm answered the call. StartRecords, } @@ -1446,27 +1582,41 @@ fn answered_limits(answered: Answered) -> (EvmTxRuntimeLimits, LimitCheck) { stop(LimitKind::ComputeGas, 2 + CAP, 2 + to_the_answer(answered)), ), Answered::StartRecords => { - // The body, and one byte short of the start's two records and its transfer log. - let limit = TX_BODY_SIZE + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE - 1; + // The body, and one byte short of the start's two records and its transfer log. The + // start three calls down crosses the budget it would start with too, 98% of 98% of + // 98% of what the body leaves, which the stop names. + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let limit = TX_BODY_SIZE + start - 1; + let share = + |left: u64| left * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let budget = share(share(share(start - 1))); ( EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), - stop(LimitKind::DataSize, limit, limit + 1), + LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit: budget, + used: start, + frame_local: true, + }, ) } } } /// Answers every call to `D` itself, having spent all the gas it was forwarded, and records every -/// frame it sees end, deepest first, with the result and output it had; with `rewrite`, it then -/// rewrites that result into a success, as [`FrameRecorder`] does. +/// frame it sees end, deepest first, with the result and output it had, and the gas the call to `D` +/// was forwarded; with `rewrite`, it then rewrites that result into a success, as +/// [`FrameRecorder`] does. struct AnswersD { rewrite: bool, ended: Vec<(Address, InstructionResult, Bytes)>, + forward: Option, } impl Inspector, EthInterpreter> for AnswersD { fn call(&mut self, _: &mut MegaContext, inputs: &mut CallInputs) -> Option { (inputs.target_address == D).then(|| { + self.forward = Some(inputs.gas_limit); let mut gas = Gas::new_with_regular_gas_and_reservoir(inputs.gas_limit, inputs.reservoir); gas.spend_all(); @@ -1492,12 +1642,14 @@ impl Inspector, EthInterpreter> for AnswersD { } } -/// A run of an answered chain: its outcome, the frames an inspector saw end, and what the -/// precompile at [`PRICED`] ran on, each with whether its price was within it. +/// A run of an answered chain: its outcome, the frames an inspector saw end, what the precompile +/// at [`PRICED`] ran on, each with whether its price was within it, and the gas an inspector's +/// answer to `D` was forwarded. struct AnsweredRun { outcome: MegaTransactionOutcome, ended: Vec<(Address, InstructionResult, Bytes)>, ran_on: Vec<(u64, bool)>, + forward: Option, } /// Runs the stopped chain of `answered` under `limits` at `gas_limit`, with the precompile at @@ -1514,20 +1666,20 @@ fn run_answered( let evm = MegaEvm::new(context(answered_chain(answered)).with_tx_runtime_limits(limits)) .with_dyn_precompiles(HashMap::from_iter([(PRICED, priced(&runs))])); let tx = call(CALLER, A, U256::ZERO, gas_limit); - let (outcome, ended) = if answered == Answered::PastTheAllowance { - let mut evm = evm.with_inspector(AnswersD { rewrite, ended: Vec::new() }); + let (outcome, ended, forward) = if answered == Answered::PastTheAllowance { + let mut evm = evm.with_inspector(AnswersD { rewrite, ended: Vec::new(), forward: None }); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - (outcome, evm.inspector().ended.clone()) + (outcome, evm.inspector().ended.clone(), evm.inspector().forward) } else if rewrite { let mut evm = evm.with_inspector(FrameRecorder::rewriting()); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); - (outcome, evm.inspector().ended.clone()) + (outcome, evm.inspector().ended.clone(), None) } else { let mut evm = evm; - (evm.execute_transaction(tx).expect("the transaction is valid"), Vec::new()) + (evm.execute_transaction(tx).expect("the transaction is valid"), Vec::new(), None) }; let ran_on = runs.lock().unwrap().clone(); - AnsweredRun { outcome, ended, ran_on } + AnsweredRun { outcome, ended, ran_on, forward } } /// One answered cell, both columns: `answered`'s chain at `gas_limit`, without the rewrite and @@ -1541,40 +1693,50 @@ fn run_answered( /// back. That run is on the same engine, so its bill pins that a stop bills what ran and no more; /// it pins no price, and a charge both runs make, such as `C`'s own `CALL`, would be wrong in both /// alike. +/// +/// A start's stop the inspector rewrites into a success is taken as given: the success gives back +/// neither the account the start's `CALL` was charged for nor the history of the start's records, +/// so that column bills the state and history gas of the run without limits, where the start is +/// kept, while it counts nothing and moves nothing, as the stop left it. fn assert_answered_cell(answered: Answered, gas_limit: u64) { let row = format!("{answered:?}, gas limit {gas_limit}"); let intrinsic = intrinsic(gas_limit); let (limits, stop) = answered_limits(answered); let LimitCheck::ExceedsLimit { kind, used, .. } = stop else { unreachable!() }; - let ran = if kind == LimitKind::ComputeGas { - used + 3 * 2 - } else { + let free = (kind != LimitKind::ComputeGas).then(|| { let free = execute(answered_chain(answered), EvmTxRuntimeLimits::no_limits(), gas_limit); assert!(free.result.is_success(), "{row}: without limits: {:?}", free.result); assert_eq!(balance_of(&free, EMPTY), U256::from(1), "{row}: the start moves its wei"); - free.gas.regular - intrinsic.gas.regular - }; + free + }); + let ran = free.as_ref().map_or(used + 3 * 2, |free| free.gas.regular - intrinsic.gas.regular); let plain = run_answered(answered, limits, gas_limit, false); let rewritten = run_answered(answered, limits, gas_limit, true); for (column, run) in [("not rewritten", &plain), ("rewritten", &rewritten)] { let cell = format!("{row}, {column}"); let outcome = &run.outcome; + let (state, history) = match (&free, column) { + (Some(free), "rewritten") => (free.gas.state, free.gas.history), + _ => (0, intrinsic.gas.history), + }; + let kept = state + history - intrinsic.gas.history; assert!(outcome.result.is_success(), "{cell}: the callers caught the stop"); assert_eq!(outcome.limit_exceeded, None, "{cell}: a stop below is no stop of it"); assert_eq!(outcome.gas.regular, intrinsic.gas.regular + ran, "{cell}: regular"); - assert_eq!(outcome.gas.state, 0, "{cell}: the stop keeps no state gas"); - assert_eq!(outcome.gas.history, intrinsic.gas.history, "{cell}: the body's history alone"); + assert_eq!(outcome.gas.state, state, "{cell}: the state gas"); + assert_eq!(outcome.gas.history, history, "{cell}: the history gas"); assert_eq!(outcome.gas.history_bytes, intrinsic.gas.history_bytes, "{cell}"); assert_eq!( - outcome.gas.reservoir_remaining, intrinsic.gas.reservoir_remaining, - "{cell}: the reservoir comes back, less the body it paid" + outcome.gas.reservoir_remaining, + intrinsic.gas.reservoir_remaining.saturating_sub(kept), + "{cell}: the reservoir comes back, less the body it paid and what is kept" ); - assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran, "{cell}: gas used"); + assert_eq!(outcome.gas.gas_used, intrinsic.gas.gas_used + ran + kept, "{cell}: gas used"); assert!(outcome.result.logs().is_empty(), "{cell}: no log is kept"); assert_eq!( outcome.usage, - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 }, + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 }, "{cell}: the body stays" ); assert_eq!(balance_of(outcome, EMPTY), U256::ZERO, "{cell}: no value moved"); @@ -1583,8 +1745,10 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { assert_eq!(run.ran_on, [(allowance, false)], "{cell}: run on the allowance"); } } - assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); - assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + if free.is_none() { + assert_eq!(rewritten.outcome.result, plain.outcome.result, "{row}"); + assert_eq!(rewritten.outcome.gas, plain.outcome.gas, "{row}"); + } let ended = vec![ (answered.target(), InstructionResult::Revert, stop.revert_data()), (C, InstructionResult::Stop, Bytes::new()), @@ -1595,13 +1759,6 @@ fn assert_answered_cell(answered: Answered, gas_limit: u64) { rewritten.ended, ended, "{row}: the answered frame ended stopped, then every caller ended" ); - if answered == Answered::PastTheAllowance { - // Its answer is an inspector's, which in this column rewrites nothing. - assert_eq!( - plain.ended, ended, - "{row}, not rewritten: the answered frame ended stopped, then every caller ended" - ); - } } /// The balance `address` holds after `outcome`: zero for an account it did not touch. @@ -1610,27 +1767,137 @@ fn balance_of(outcome: &MegaTransactionOutcome, address: Address) -> U256 { } /// A frame three calls down that is answered without running, and whose answer crosses a limit, is -/// the stop as a frame that ran there would be: an answer past what the compute limit leaves the -/// frame, and a precompile run on that allowance and priced past it. Below the execution cap and -/// above it, with and without an inspector that rewrites every frame result into a success, the -/// answer is the stop, its caller catches it, every frame ends, and the transaction bills what -/// ran, keeps the body's history and nothing else, and gets its reservoir back. +/// the stop as a frame that ran there would be: a precompile run on what the compute limit leaves +/// the frame and priced past it. Below the execution cap and above it, with and without an +/// inspector that rewrites every frame result into a success, the answer is the stop, its caller +/// catches it, every frame ends, and the transaction bills what ran, keeps the body's history and +/// nothing else, and gets its reservoir back. #[test] fn test_an_answer_three_calls_down_is_the_stop_its_caller_catches_at_either_tier() { - for answered in [Answered::PastTheAllowance, Answered::Precompile] { - for gas_limit in TIERS { - assert_answered_cell(answered, gas_limit); + for gas_limit in TIERS { + assert_answered_cell(Answered::Precompile, gas_limit); + } +} + +/// An inspector's answer is taken as given, as revm's inspected frame start takes it: gas detention +/// holds the engine's answers to the compute limit, and a frame the inspector answers never +/// reaches the engine's frame start. An inspector's answer to `D`, three calls down, that spent all +/// it was forwarded, past what the compute limit leaves the frame, is no stop: `D` ends as the +/// inspector answered it, and what it spent is `C`'s compute. Every caller then resumes on what the +/// limit leaves the transaction, nothing, and crosses it at its next charge, its `POP`: the +/// inspector sees each end with the stop, and the stop of the transaction's own frame is the +/// transaction's result, which reports the compute at that crossing — the read, the calls down and +/// the answer's forward, past the limit — and bills it. +#[test] +fn test_an_inspectors_answer_past_the_allowance_is_taken_as_given() { + for gas_limit in TIERS { + let row = format!("gas limit {gas_limit}"); + let intrinsic = intrinsic(gas_limit); + let (limits, _) = answered_limits(Answered::PastTheAllowance); + let run = run_answered(Answered::PastTheAllowance, limits, gas_limit, false); + let forward = run.forward.expect("the inspector answered the call to D"); + let used = 2 + to_the_answer(Answered::PastTheAllowance) + forward; + let stop = LimitCheck::ExceedsLimit { + kind: LimitKind::ComputeGas, + limit: 2 + CAP, + used, + frame_local: false, + }; + assert_eq!(run.outcome.limit_exceeded, Some(stop), "{row}: the transaction's own stop"); + match &run.outcome.result { + ExecutionResult::Revert { output, .. } => { + assert_eq!(output, &stop.revert_data(), "{row}: the stop's revert data") + } + other => panic!("{row}: expected the stop, got {other:?}"), } + assert_eq!(run.outcome.gas.regular, intrinsic.gas.regular + used, "{row}: regular"); + let stopped = |frame| (frame, InstructionResult::Revert, stop.revert_data()); + assert_eq!( + run.ended, + [(D, InstructionResult::Stop, Bytes::new()), stopped(C), stopped(B), stopped(A)], + "{row}: D ended as answered, then every caller returned the stop" + ); } } /// A frame three calls down whose start's records and transfer log cross the data-size limit is -/// answered with the stop before revm builds it: no value moves and no account is added. Its -/// caller catches the stop, below the execution cap and above it, with and without the rewriting -/// inspector. +/// answered with the stop once revm answered it, and what its start moved goes back with it: no +/// value stays moved and no account is added. Its caller catches the stop, below the execution +/// cap and above it, with and without the rewriting inspector, whose success keeps what the start +/// was charged at its caller's opcode. #[test] -fn test_a_start_three_calls_down_crossing_the_limit_is_stopped_before_it_is_built() { +fn test_a_start_three_calls_down_crossing_the_limit_is_stopped_at_its_start() { for gas_limit in TIERS { assert_answered_cell(Answered::StartRecords, gas_limit); } } + +/* ---------- a stopped answer gives its caller back its share ---------- */ + +/// A start revm answers without building a frame — a value call to an account with no code — and +/// whose records cross a budget gives way to the stop on the pools the frame would have started +/// with, which go back to its caller as a failed frame's do: the caller then holds what it held +/// before the call, and a write of its own past its budget is stopped by that budget. +/// +/// `B`, given a budget of nine slots, records or growth units by `A`, fills it, sends one wei to an +/// account that does not exist, whose start's records and new account cross the share of nothing +/// it gets, and catches that stop; its next fresh slot crosses its own budget of nine, and `A` +/// returns that stop. In each of the three counted dimensions, below the execution cap and above +/// it. +#[test] +fn test_a_stopped_answer_gives_its_caller_back_its_share() { + const OWN: u64 = 9; + // The call from `CALLER` to `A` carries no value and no calldata: the transaction's own frame + // gets what the limit leaves of the body, and `B` the share of that. The smallest data-size + // limit that leaves `B` nine records is the body and nine records' bytes scaled back up by the + // share, rounded up. + let records = OWN * WRITE_RECORD_SIZE; + let data_size_limit = TX_BODY_SIZE + + (records * FRAME_DATA_SHARE_DENOMINATOR).div_ceil(FRAME_DATA_SHARE_NUMERATOR); + let limits = [ + (LimitKind::DataSize, records, data_size_limit), + (LimitKind::KvUpdate, OWN, 10), + (LimitKind::StateGrowth, OWN, 10), + ]; + let mut b = BytecodeBuilder::default(); + for slot in 1..=OWN { + b = b.sstore(U256::from(slot), U256::from(1)); + } + let b = b + .call(C, U256::from(1)) + .append(POP) + .sstore(U256::from(OWN + 1), U256::from(1)) + .stop() + .build(); + let a = BytecodeBuilder::default().call(B, U256::ZERO).append(POP).return_returndata().build(); + for (kind, budget, limit) in limits { + let mut under = EvmTxRuntimeLimits::default(); + under = match kind { + LimitKind::DataSize => under.with_tx_data_size_limit(limit), + LimitKind::KvUpdate => under.with_tx_kv_update_limit(limit), + LimitKind::StateGrowth => under.with_tx_state_growth_limit(limit), + LimitKind::ComputeGas => unreachable!(), + }; + let held = + |remaining: u64| remaining * FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR; + let own_frame = if kind == LimitKind::DataSize { limit - TX_BODY_SIZE } else { limit }; + assert_eq!(held(own_frame), budget, "{kind:?}: B's budget"); + for gas_limit in TIERS { + let row = format!("{kind:?}, gas limit {gas_limit}"); + let db = MemoryDatabase::default() + .account_code(A, a.clone()) + .account_code(B, b.clone()) + .account_balance(B, U256::from(1)); + let outcome = execute(db, under, gas_limit); + assert!(outcome.result.is_success(), "{row}: {:?}", outcome.result); + let stop = LimitCheck::ExceedsLimit { kind, limit: budget, used: 0, frame_local: true }; + assert_eq!( + outcome.result.output(), + Some(&stop.revert_data()), + "{row}: B's own slot crossed its budget, not a pool the answer lifted" + ); + assert_eq!(outcome.limit_exceeded, None, "{row}: A caught B's stop"); + assert_eq!(outcome.usage, LimitUsage { data_size: TX_BODY_SIZE, ..LimitUsage::ZERO }); + } + } +} diff --git a/crates/mega-evm/tests/satin/strategic_stop.rs b/crates/mega-evm/tests/satin/strategic_stop.rs index c33ef7f6d..c7d45c169 100644 --- a/crates/mega-evm/tests/satin/strategic_stop.rs +++ b/crates/mega-evm/tests/satin/strategic_stop.rs @@ -6,7 +6,9 @@ //! crosses again stops it in turn. A transaction whose own frame is stopped settles like an //! EIP-8037 revert: the sender gets the unspent regular gas and the whole reservoir back. A real //! out-of-gas still halts and burns. The limit here is the configurable data-size cap of -//! `EvmTxRuntimeLimits`; a write record is 40 bytes. +//! `EvmTxRuntimeLimits`; a write record is 40 bytes. A frame that crosses the transaction's limit +//! crosses its own budget too — the budgets of the frames on the stack add up to what the +//! transaction has left — and the stop names the budget, which is tested first. use alloy_evm::Evm; use alloy_primitives::{address, Address, Bytes, U256}; @@ -150,16 +152,19 @@ impl Inspector, EthInterpreter> for Probe { /// Crossing the cap at depth 3 reverts `D` alone, and every caller resumes, held to what the /// transaction has left: `C`'s log after its second write crosses the cap again and stops `C`, /// `B` writes and logs within it, and `A`'s second write crosses it once more and stops the -/// transaction's own frame, which takes back everything below it. Each stop names the cap, and -/// at no point does the transaction keep more than it. +/// transaction's own frame, which takes back everything below it. At no point does the +/// transaction keep more than the cap. /// /// What each crossing reached, above the body: `A`, `B`, `C` and `D`'s first writes are four /// records (160 bytes), and `D`'s second makes 200; `C`'s second write makes 160 again, and its -/// log 192; `B`'s second write and log make 152; `A`'s second write 192. +/// log 192; `B`'s second write and log make 152; `A`'s second write 192. Each crossing crosses the +/// frame's own budget too, so each stop names that budget: `A`'s is the 180 the transaction has +/// left; `B` gets 98% of the 140 `A` has after its write, 137; `C` 98% of `B`'s 97, 95; `D` 98% of +/// `C`'s 55, 53. #[test] fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { let limit = mega_evm::TX_BODY_SIZE + 180; - let stop = limit_exceeded(LimitKind::DataSize, limit); + let stop = |budget| limit_exceeded(LimitKind::DataSize, budget); for inspect in [false, true] { let mut evm = evm_with( chain(), @@ -169,16 +174,16 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { alloy_evm::Evm::set_inspector_enabled(&mut evm, inspect); let outcome = evm.execute_transaction(call(CALLER, A, U256::ZERO, GAS_LIMIT)).unwrap(); - assert_stopped(&outcome.result, LimitKind::DataSize, limit); + assert_stopped(&outcome.result, LimitKind::DataSize, 180); assert_eq!( outcome.limit_exceeded, Some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used: mega_evm::TX_BODY_SIZE + 192, - frame_local: false + limit: 180, + used: 192, + frame_local: true }), - "A's own crossing produced its result" + "A's own crossing of its budget produced its result" ); assert!(outcome.result.logs().is_empty()); for account in [A, B, C, D] { @@ -196,10 +201,10 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { assert_eq!( probe.call_results, vec![ - (D, InstructionResult::Revert, stop.clone()), - (C, InstructionResult::Revert, stop.clone()), + (D, InstructionResult::Revert, stop(53)), + (C, InstructionResult::Revert, stop(95)), (B, InstructionResult::Stop, Bytes::new()), - (A, InstructionResult::Revert, stop.clone()), + (A, InstructionResult::Revert, stop(180)), ], "each frame that crossed returned the stop, the deepest first" ); @@ -213,19 +218,19 @@ fn test_cap_crossed_at_depth_three_stops_each_frame_that_crosses_it() { fn test_stop_refills_the_reservoir_at_any_gas_limit() { let at = |gas_limit: u64| { let result = run(chain(), cap(180), call(CALLER, A, U256::ZERO, gas_limit)); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); - *result.result.gas() + assert_stopped(&result.result, LimitKind::DataSize, 180); + result }; let small = at(100_000_000); let large = at(1_000_000_000); - assert_eq!(small.reservoir_remaining(), 0, "a limit under the cap has no reservoir"); + assert_eq!(small.gas.reservoir_remaining, 0, "a limit under the cap has no reservoir"); assert_eq!( - large.reservoir_remaining(), + large.gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(), "all of it back but the body's history, which the stop does not take back", ); - assert_eq!(small.tx_gas_used(), large.tx_gas_used()); - assert_eq!(small.total_gas_spent(), large.total_gas_spent()); + assert_eq!(small.result.gas().tx_gas_used(), large.result.gas().tx_gas_used()); + assert_eq!(small.result.gas().total_gas_spent(), large.result.gas().total_gas_spent()); } /// An `SSTORE` that runs out of gas after its Host call records nothing, so a cap of zero does @@ -275,9 +280,10 @@ fn test_child_out_of_gas_under_a_cap_is_no_stop() { result.usage, mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE + mega_evm::WRITE_RECORD_SIZE, - write_records: 1 + write_records: 1, + state_growth: 1, }, - "A's record alone, which meets the cap and does not cross it" + "A's record alone, which meets the cap and does not cross it, and its fresh slot" ); } @@ -293,13 +299,17 @@ fn test_cap_crossed_before_the_first_frame_reverts_without_running() { let funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000_000)); let mut evm = evm_with(funded().account_code(B, writer()), cap(39), Probe::default()); let result = evm.transact_raw(call(CALLER, B, U256::from(5), GAS_LIMIT)).unwrap(); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 39); + assert_stopped(&result.result, LimitKind::DataSize, 39); assert!(evm.inspector().steps.is_empty(), "the recipient's code never ran"); assert_eq!(result.state.get(&B).map(|b| b.info.balance).unwrap_or_default(), U256::ZERO); assert_eq!( - evm.ctx().additional_limit().usage(), - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + evm.ctx().limit_usage(), + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "the body stays; the recipient record does not" ); @@ -372,7 +382,11 @@ fn test_frame_budget_of_the_outermost_frame_reverts_the_transaction() { ); assert_eq!( result.usage, - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "the body is all the transaction keeps" ); } @@ -400,8 +414,12 @@ fn test_the_stop_does_not_outlive_its_transaction() { .is_success()); assert!(!stopped(&evm)); assert_eq!( - evm.ctx().additional_limit().usage(), - mega_evm::LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, + evm.ctx().limit_usage(), + mega_evm::LimitUsage { + data_size: mega_evm::TX_BODY_SIZE, + write_records: 0, + state_growth: 0 + }, "an empty call keeps its body" ); @@ -430,7 +448,7 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { let room = init_code.len() as u64 + mega_evm::WRITE_RECORD_SIZE - 1; let tx = crate::common::create(CALLER, init_code.clone(), GAS_LIMIT); let result = run(MemoryDatabase::default(), cap(room), tx); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + room); + assert_stopped(&result.result, LimitKind::DataSize, room - init_code.len() as u64); assert!(result.limit_exceeded.is_some()); assert_eq!(result.state[&CALLER].info.nonce, 1, "the sender's nonce is bumped"); assert!(result.state.get(&CALLER.create(0)).is_none_or(|a| a.info.is_empty_code_hash())); @@ -440,7 +458,7 @@ fn test_create_transaction_stopped_before_its_first_frame_bumps_the_nonce() { let tx = crate::common::create(CALLER, init_code.clone(), 1_000_000_000); let result = run(MemoryDatabase::default(), cap(room), tx); assert_eq!( - result.result.gas().reservoir_remaining(), + result.gas.reservoir_remaining, 1_000_000_000 - TX_GAS_LIMIT_CAP - create_body_history(init_code.len() as u64), ); } @@ -458,7 +476,7 @@ fn test_usage_equal_to_the_limit_does_not_stop() { let result = run(db(), budget, call(CALLER, A, U256::ZERO, GAS_LIMIT)); assert!(result.result.is_success(), "{:?}", result.result); let result = run(db(), cap(119), call(CALLER, A, U256::ZERO, GAS_LIMIT)); - assert_stopped(&result.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 119); + assert_stopped(&result.result, LimitKind::DataSize, 119); } /// A tool's inspector that writes to the running frame's gas. @@ -525,7 +543,7 @@ fn test_stop_refills_the_state_gas_drawn_from_the_reservoir() { assert_eq!(plain.gas.state, 9 * slot_state_gas(), "the chain's nine slots are state gas"); let stopped = execute_with(chain(), cap(180), charger(), gas_limit); - assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); assert_eq!(stopped.gas.reservoir_remaining, reservoir, "refilled by the stop"); assert_eq!(stopped.gas.state, 0); } @@ -553,6 +571,6 @@ fn test_outcome_reports_history_gas() { // The body is charged before the first frame, so the stop keeps it and takes back every // charge the frames made, the inspector's included. let stopped = execute_with(chain(), cap(180), charger(), GAS_LIMIT); - assert_stopped(&stopped.result, LimitKind::DataSize, mega_evm::TX_BODY_SIZE + 180); + assert_stopped(&stopped.result, LimitKind::DataSize, 180); assert_eq!(stopped.gas.history, body_history()); } diff --git a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs index cfcbec37c..ac222def3 100644 --- a/crates/mega-evm/tests/satin/synthetic_frame_gas.rs +++ b/crates/mega-evm/tests/satin/synthetic_frame_gas.rs @@ -70,6 +70,9 @@ fn call_frame_init(depth: usize) -> FrameInit { is_static: false, reservoir: RESERVOIR, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } @@ -152,7 +155,7 @@ fn test_depth_guard_answers_a_creation_and_every_call_scheme() { if let FrameResult::Create(outcome) = &result { assert_eq!(outcome.address, None, "{what}"); } - assert_eq!(evm.ctx().additional_limit().usage(), LimitUsage::ZERO, "{what}: counted"); + assert_eq!(evm.ctx().limit_usage(), LimitUsage::ZERO, "{what}: counted"); assert!(!evm.ctx().journal_ref().state.contains_key(&CALLER), "{what}: no nonce bumped"); } } @@ -198,10 +201,12 @@ impl Inspector for AlwaysAnsw } } -/// An inspector's answer to a call past the limit gives way to `CallTooDeep`, and the inspector -/// still sees the call end. +/// An inspector's answer to a call past the limit is taken as given, as revm's inspected frame +/// start takes it: the depth guard is the engine's frame start, which a frame the inspector +/// answers never reaches, so the answer is the inspector's `Stop` on the gas it built, and the +/// inspector sees the call end. #[test] -fn test_inspect_frame_init_depth_guard_overrides_inspector() { +fn test_an_inspectors_answer_past_the_depth_limit_is_taken_as_given() { let mut evm = MegaEvm::new(context(MemoryDatabase::default())).with_inspector(AlwaysAnswers::default()); let result = InspectorEvmTr::inspect_frame_init( @@ -209,8 +214,12 @@ fn test_inspect_frame_init_depth_guard_overrides_inspector() { call_frame_init(CALL_STACK_LIMIT as usize + 1), ) .expect("inspect_frame_init does not fail"); - let ItemOrResult::Result(result) = result else { panic!("the frame was answered") }; - assert_call_too_deep(&result); + let ItemOrResult::Result(FrameResult::Call(outcome)) = result else { + panic!("the frame was answered") + }; + assert_eq!(outcome.result.result, InstructionResult::Stop, "the inspector's answer"); + assert_eq!(outcome.result.gas.remaining(), GAS_LIMIT, "on the gas the inspector built"); + assert_eq!(outcome.result.gas.reservoir(), 0, "which carries no reservoir"); assert_eq!( (evm.inspector().calls, evm.inspector().call_ends), (1, 1), @@ -232,71 +241,15 @@ fn test_stopped_first_frame_keeps_the_reservoir_at_any_gas_limit() { alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, TARGET, U256::from(1), gas_limit)) .unwrap(); assert!(!result.result.is_success() && !result.result.is_halt(), "{:?}", result.result); - *result.result.gas() + (*result.result.gas(), evm.ctx().additional_limit().reservoir_remaining()) }; - let (small, large) = (at(100_000_000), at(1_000_000_000)); - assert_eq!(small.reservoir_remaining(), 0); - assert_eq!(large.reservoir_remaining(), 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(0)); + let ((small, small_reservoir), (large, large_reservoir)) = (at(100_000_000), at(1_000_000_000)); + assert_eq!(small_reservoir, 0); + assert_eq!(large_reservoir, 1_000_000_000 - TX_GAS_LIMIT_CAP - body_history(0)); assert_eq!(small.tx_gas_used(), large.tx_gas_used()); assert_eq!(small.state_gas_spent_final(), large.state_gas_spent_final()); } -/// `settle_frame_result` settles a result into its caller's gas exactly as revm's frame return -/// does, for a success, a revert and a halt, with state gas drawn from the reservoir and spilled -/// onto regular gas. -#[test] -fn test_settle_frame_result_matches_revms_frame_return() { - use mega_evm::{settle_frame_result, synthetic_frame_result}; - use revm::context::result::EVMError; - - for result_kind in - [InstructionResult::Stop, InstructionResult::Revert, InstructionResult::OutOfGas] - { - let code = Bytes::from_static(&[revm::bytecode::opcode::STOP]); - let mut evm = - MegaEvm::new(context(MemoryDatabase::default().account_code(TARGET, code.clone()))); - let journal = evm.ctx_mut().journal_mut(); - journal.load_account(CALLER).unwrap(); - journal.load_account(TARGET).unwrap(); - let mut caller_init = call_frame_init(1); - if let FrameInput::Call(inputs) = &mut caller_init.frame_input { - let bytecode = revm::state::Bytecode::new_raw(code.clone()); - inputs.known_bytecode = (bytecode.hash_slow(), bytecode); - } - let ItemOrResult::Item(_) = EvmTr::frame_init(&mut evm, caller_init).unwrap() else { - panic!("the caller frame is built"); - }; - - // The child the caller starts: 30,000 gas of the caller's, and its reservoir. - let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); - let caller_frame = frames.get(); - assert!(caller_frame.interpreter.gas.record_regular_cost(30_000)); - let child_input = { - let FrameInput::Call(mut inputs) = call_frame_init(2).frame_input else { - unreachable!() - }; - inputs.gas_limit = 30_000; - inputs.reservoir = caller_frame.interpreter.gas.reservoir(); - FrameInput::Call(inputs) - }; - let mut result = synthetic_frame_result(&child_input, result_kind, Bytes::new()); - // The child spent regular gas, and state gas beyond the reservoir that spilled. - let child_gas = result.gas_mut(); - assert!(child_gas.record_regular_cost(1_000)); - assert!(child_gas.record_state_cost(RESERVOIR + 500)); - - let mut expected = *caller_frame.interpreter.gas.tracker(); - settle_frame_result::<_, EVMError>( - ctx, - &mut expected, - &mut result.clone(), - ) - .unwrap(); - caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); - assert_eq!(caller_frame.interpreter.gas.tracker(), &expected, "{result_kind:?}"); - } -} - /// A gas limit below the execution cap: the transaction has no state-gas reservoir. const NARROW: u64 = 100_000_000; @@ -330,7 +283,7 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected let at = |gas_limit: u64| { let mut tx = crate::common::call_with_data(CALLER, to, data.clone(), gas_limit); tx.0.base.value = value; - let (result, _) = crate::common::run(system_db(), tx); + let result = crate::common::execute(system_db(), tx); let output = result.result.output().cloned().unwrap_or_default(); match &expected { Expected::Answer(answer) => { @@ -349,7 +302,7 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected assert!(result.result.is_success(), "at {gas_limit}: {:?}", result.result); } } - (*result.result.gas(), output) + (result, output) }; let ((narrow, narrow_answer), (wide, wide_answer)) = (at(NARROW), at(WIDE)); @@ -365,15 +318,15 @@ fn assert_the_reservoir_survives(to: Address, data: Bytes, value: U256, expected narrow limit has no reservoir, so its body's history comes off that budget too", ); } - assert_eq!(narrow.reservoir_remaining(), 0, "there is no pool below the cap"); + assert_eq!(narrow.gas.reservoir_remaining, 0, "there is no pool below the cap"); assert_eq!( - wide.reservoir_remaining(), + wide.gas.reservoir_remaining, WIDE - TX_GAS_LIMIT_CAP - body_history(data.len() as u64), "the call spends no state gas, so the whole pool but the body's history comes back", ); assert_eq!( - narrow.tx_gas_used(), - wide.tx_gas_used(), + narrow.result.gas().tx_gas_used(), + wide.result.gas().tx_gas_used(), "the call costs the same with a pool and without one", ); } @@ -521,13 +474,14 @@ fn test_the_keyless_value_refusal_keeps_the_reservoir() { } /// A `keylessDeploy` call forwarded less regular gas than the overhead runs out of gas on its -/// first run, with the reservoir it inherited carried, and that result settles into a caller -/// exactly as revm's own frame return settles a frame that ran out. +/// first action, with the reservoir it inherited carried: the frame revm built for it ends before +/// it runs, and its frame start returns the out-of-gas as an answer is returned. revm's frame +/// return hands its caller none of the call's regular gas back and the reservoir whole, as for +/// any frame that ran out. #[test] fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { use core::convert::Infallible; - use mega_evm::settle_frame_result; use revm::context::result::EVMError; let forwarded = KEYLESS_DEPLOY_OVERHEAD_GAS - 1; @@ -537,15 +491,12 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { journal.load_account(CALLER).unwrap(); journal.load_account_with_code(KEYLESS_DEPLOY_ADDRESS).unwrap(); let init = call_frame_init_to(0, KEYLESS_DEPLOY_ADDRESS, keyless_deploy_call(), forwarded); - let ItemOrResult::Item(_) = + let ItemOrResult::Result(result) = EvmTr::frame_init(&mut evm, init).expect("frame_init does not fail") - else { - panic!("the call's frame is built"); - }; - let ItemOrResult::Result(result) = EvmTr::frame_run(&mut evm).expect("frame_run does not fail") else { panic!("a call that cannot pay the overhead starts no creation"); }; + assert_eq!(EvmTr::all(&evm).3.index(), None, "the call's frame is off the stack"); let FrameResult::Call(outcome) = &result else { panic!("expected a call result: {result:?}") }; assert_eq!(outcome.result.result, InstructionResult::OutOfGas); assert!(outcome.result.output.is_empty()); @@ -569,9 +520,13 @@ fn test_a_keyless_call_below_the_overhead_runs_out_of_gas() { let (ctx, _, _, frames) = EvmTr::all_mut(&mut evm); let caller_frame = frames.get(); - let mut expected = *caller_frame.interpreter.gas.tracker(); - settle_frame_result::<_, EVMError>(ctx, &mut expected, &mut result.clone()) - .unwrap(); + let before = *caller_frame.interpreter.gas.tracker(); + // The call's opcode took the reservoir the answer carries out of the caller, which the answer's + // return adds back to what the caller kept. + caller_frame.interpreter.gas.tracker_mut().forward_reservoir(result.gas().reservoir()); caller_frame.return_result::<_, EVMError>(ctx, result).unwrap(); - assert_eq!(caller_frame.interpreter.gas.tracker(), &expected); + let after = caller_frame.interpreter.gas.tracker(); + assert_eq!(after.remaining(), before.remaining(), "a halt hands none of its gas back"); + assert_eq!(after.reservoir(), RESERVOIR, "and the inherited reservoir comes back whole"); + assert_eq!(after.state_gas_spent(), before.state_gas_spent()); } diff --git a/crates/mega-evm/tests/satin/system_call.rs b/crates/mega-evm/tests/satin/system_call.rs index 5a077f0a1..0ca8dc5f3 100644 --- a/crates/mega-evm/tests/satin/system_call.rs +++ b/crates/mega-evm/tests/satin/system_call.rs @@ -1,59 +1,53 @@ //! How a system call's gas is settled: at most 30M of it regular gas, the rest its state-gas -//! reservoir. +//! reservoir. A system call runs on one of two gas limits: revm's default, which alloy-evm's and +//! revm's entry points use, or the pre-block budget, which the block's pre-block calls use. //! //! Every case runs the same system call through `MegaEvm` and through op-revm's `OpEvm` on the -//! `CfgEnv` the `MegaEvm` context holds — so on the fork with the same switch on — and compares -//! the two field by field: the gas, the reservoir left, the result and the state. A system call is -//! the protocol's own work: it pays no history gas, prices its state at the minimum SALT bucket and -//! is held to no per-transaction limit, so nothing Satin adds to a transaction separates the two. +//! `CfgEnv` the `MegaEvm` context holds — op-revm's handler with EIP-8037's split of a system +//! call's gas, which op-revm leaves to its consumer ([`op_reference`](crate::op_reference)) — and +//! compares the two field by field: the gas, the reservoir left, the result and the state. A +//! system call is the protocol's own work: it pays no history gas, prices its state at the minimum +//! SALT bucket and is held to no per-transaction limit, so nothing Satin adds to a transaction +//! separates the two. //! //! A transaction is not a system call. The last cases hold a system-address transaction, which is //! promoted to a deposit, to the deposit op-revm runs for it, below and above the execution cap: //! its gas is split by the cap, as every transaction's is, and not by the system-call budget. -use std::convert::Infallible; - use alloy_evm::Evm; use alloy_op_evm::OpTx; use alloy_primitives::{address, Address, Bytes, TxKind, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ - constants::{SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, + constants::{PRE_BLOCK_CALL_GAS_LIMIT, SLOT_STATE_GAS, TX_GAS_LIMIT_CAP}, satin_gas_params, system::{ storage_slots::{ CURRENT_SYSTEM_ADDRESS, PENDING_SYSTEM_ADDRESS, SYSTEM_ADDRESS_ACTIVATION_BLOCK, }, - IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, - ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, SEQUENCER_REGISTRY_ADDRESS, - SEQUENCER_REGISTRY_CODE, + transact_apply_pending_changes, IOracle, ISequencerRegistry, MEGA_SYSTEM_ADDRESS, + MEGA_SYSTEM_TRANSACTION_SOURCE_HASH, ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, + SEQUENCER_REGISTRY_ADDRESS, SEQUENCER_REGISTRY_CODE, }, - test_utils::{op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase}, - EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaHaltReason, MegaSpecId, - TestExternalEnvs, MIN_BUCKET_SIZE, -}; -use op_revm::{ - handler::OpHandler, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, L1BlockInfo, OpEvm, - OpSpecId, OpTransaction, OpTransactionError, + test_utils::{ + note_price_guard, op_transaction, zero_fee_l1_block_info, BytecodeBuilder, MemoryDatabase, + }, + EvmTxRuntimeLimits, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, TestExternalEnvs, + MIN_BUCKET_SIZE, SYSTEM_CALL_REGULAR_GAS_LIMIT, }; +use op_revm::{transaction::deposit::DEPOSIT_TRANSACTION_TYPE, OpEvm, OpSpecId, OpTransaction}; use revm::{ bytecode::opcode::{GAS, INVALID, NUMBER, POP, PUSH0, SSTORE, STOP}, - context::{ - result::{EVMError, ExecResultAndState, ExecutionResult}, - BlockEnv, CfgEnv, Context, ContextSetters, ContextTr, Transaction, TxEnv, - }, + context::{result::ExecutionResult, BlockEnv, CfgEnv, ContextTr, Transaction, TxEnv}, context_interface::cfg::GasId, - handler::{ - EthFrame, ExecuteEvm, Handler, SystemCallTx, SYSTEM_CALL_GAS_LIMIT, - SYSTEM_CALL_REGULAR_GAS_LIMIT, - }, + handler::system_call::SYSTEM_CALL_GAS_LIMIT, inspector::NoOpInspector, - interpreter::interpreter::EthInterpreter, - state::EvmState, - Journal, }; -use crate::common::{runs_at_measurement_prices, state_is_free}; +use crate::{ + common::{runs_at_measurement_prices, state_is_free}, + op_reference::{self, Op, OpContext, Settled}, +}; const CALLER: Address = address!("0x4000000000000000000000000000000000000001"); const CONTRACT: Address = address!("0x5000000000000000000000000000000000000001"); @@ -70,17 +64,6 @@ fn slot() -> u64 { satin_gas_params().get(GasId::sstore_set_state_gas()) } -type Outcome = ExecResultAndState, EvmState>; -type OpContext = Context< - BlockEnv, - OpTransaction, - CfgEnv, - MemoryDatabase, - Journal, - L1BlockInfo, ->; -type Op = OpEvm; - fn block() -> BlockEnv { BlockEnv { number: U256::from(1_000), @@ -113,8 +96,7 @@ fn both_evms_with( .with_block(block()) .with_chain(zero_fee_l1_block_info()); let cfg = ctx.cfg().clone(); - assert!(cfg.system_call_state_gas_margin_in_reservoir, "both run with the split"); - assert!(cfg.enable_amsterdam_eip8037, "which needs EIP-8037"); + assert!(cfg.enable_amsterdam_eip8037, "both run EIP-8037's two pools"); (MegaEvm::new(ctx), op_evm(db, cfg)) } @@ -123,45 +105,31 @@ fn both_evms(db: MemoryDatabase) -> (MegaEvm Outcome { - let mut tx = OpTransaction::::new_system_tx_with_caller(caller, contract, data); - tx.base.gas_limit = gas_limit; - op.0.ctx.set_tx(tx); - let result: Result<_, EVMError> = - OpHandler::<_, _, EthFrame>::new().run_system_call(op); - ExecResultAndState::new(result.expect("the system call runs"), op.finalize()) -} - -/// Runs the system call from `caller` to `contract` on `gas_limit` through both engines. +/// Runs the system call from `caller` to `contract` through both engines, on revm's default gas +/// limit. fn run_both( (mut mega, mut op): (MegaEvm, Op), caller: Address, contract: Address, data: Bytes, - gas_limit: u64, -) -> (Outcome, Outcome) { - let mega_outcome = mega - .transact_system_call_with_gas_limit(caller, contract, data.clone(), gas_limit) +) -> (Settled, Settled) { + let result_and_state = Evm::transact_system_call(&mut mega, caller, contract, data.clone()) .expect("the system call runs"); - let op_outcome = op_system_call(&mut op, caller, contract, data, gas_limit); - (mega_outcome, op_outcome) + assert_eq!(mega.ctx().tx().gas_limit(), SYSTEM_CALL_GAS_LIMIT); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let op_outcome = + op_reference::system_call(&mut op, caller, contract, data, SYSTEM_CALL_GAS_LIMIT) + .expect("the system call runs"); + (Settled { result_and_state, reservoir_remaining }, op_outcome) } /// Asserts the two outcomes agree field by field, then as a whole, so a field added later is /// covered too. -fn assert_same(mega: &Outcome, op: &Outcome) { +fn assert_same(mega: &Settled, op: &Settled) { let (m, o) = (mega.result.gas(), op.result.gas()); assert_eq!(m.total_gas_spent(), o.total_gas_spent(), "total gas spent"); assert_eq!(m.state_gas_spent_final(), o.state_gas_spent_final(), "state gas spent"); - assert_eq!(m.reservoir_remaining(), o.reservoir_remaining(), "reservoir remaining"); + assert_eq!(mega.reservoir_remaining, op.reservoir_remaining, "reservoir remaining"); assert_eq!(m.inner_refunded(), o.inner_refunded(), "refund"); assert_eq!(m.floor_gas(), o.floor_gas(), "EIP-7623 floor"); assert_eq!(m.tx_gas_used(), o.tx_gas_used(), "gas used"); @@ -178,7 +146,7 @@ fn gas_to_slot() -> Bytes { } /// What [`gas_to_slot`] stored. -fn stored_gas(outcome: &Outcome) -> u64 { +fn stored_gas(outcome: &Settled) -> u64 { let slot = outcome.state[&CONTRACT].storage[&U256::ZERO].present_value(); slot.to::() } @@ -194,40 +162,21 @@ fn db_with(code: Bytes) -> MemoryDatabase { MemoryDatabase::default().account_code(CONTRACT, code) } -/// A system call whose gas limit is at most 30M is regular gas alone: there is no reservoir, and -/// the fresh slot's state gas is paid out of the regular budget. -#[test] -fn test_a_system_call_within_30m_has_no_reservoir() { - for gas_limit in [1_000_000, SYSTEM_CALL_REGULAR_GAS_LIMIT] { - let (mega, op) = - run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); - assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), 0); - assert_eq!(mega.result.gas().state_gas_spent_final(), slot()); - assert!(stored_gas(&mega) > gas_limit - 10, "all {gas_limit} of it is regular gas"); - assert_same(&mega, &op); - } -} - -/// A system call whose gas limit is above 30M runs on 30M of regular gas, which is what `GAS` -/// reads, and carries the rest as its reservoir: the fresh slot is paid out of it, and what is -/// left is reported. So on revm's default limit and on a far larger one. +/// A system call runs on 30M of regular gas, which is what `GAS` reads, and carries the rest of +/// its gas limit as its reservoir: the fresh slot is paid out of it, and what is left is reported. #[test] fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { - for gas_limit in [SYSTEM_CALL_GAS_LIMIT, 250_000_000] { - let (mega, op) = - run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new(), gas_limit); - assert!(mega.result.is_success(), "{:?}", mega.result); - let gas = stored_gas(&mega); - assert!(gas < SYSTEM_CALL_REGULAR_GAS_LIMIT, "GAS reads the regular budget: {gas}"); - assert!(gas > SYSTEM_CALL_REGULAR_GAS_LIMIT - 10, "all of it: {gas}"); - assert_eq!( - mega.result.gas().reservoir_remaining(), - gas_limit - SYSTEM_CALL_REGULAR_GAS_LIMIT - slot(), - "the excess, less the one slot it paid for", - ); - assert_same(&mega, &op); - } + let (mega, op) = run_both(both_evms(db_with(gas_to_slot())), CALLER, CONTRACT, Bytes::new()); + assert!(mega.result.is_success(), "{:?}", mega.result); + let gas = stored_gas(&mega); + assert!(gas < SYSTEM_CALL_REGULAR_GAS_LIMIT, "GAS reads the regular budget: {gas}"); + assert!(gas > SYSTEM_CALL_REGULAR_GAS_LIMIT - 10, "all of it: {gas}"); + assert_eq!( + mega.reservoir_remaining, + DEFAULT_RESERVOIR.saturating_sub(slot()), + "the excess, less the one slot it paid for", + ); + assert_same(&mega, &op); } /// The default reservoir holds sixteen fresh slots at Satin's price. That many writes empty it and @@ -236,8 +185,8 @@ fn test_a_system_call_above_30m_carries_the_excess_as_reservoir() { /// took is its own regular cost, which the writes before it show, plus the part of its slot the /// reservoir did not hold. /// -/// Where a slot is cheaper, the default reservoir holds more fresh slots than the regular budget -/// can write, so the call is given a reservoir of sixteen. +/// Where a slot is far cheaper, the default reservoir holds more fresh slots than the regular +/// budget can write, and there is no spill to reach. #[test] fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { // Slots that cost nothing never empty the reservoir, and there is nothing to spill. @@ -248,21 +197,25 @@ fn test_a_system_call_s_state_draws_the_reservoir_first_then_spills() { assert_eq!(SLOT_STATE_GAS, slot()); assert_eq!(DEFAULT_RESERVOIR, 16 * SLOT_STATE_GAS); } - let reservoir = DEFAULT_RESERVOIR.min(16 * slot()); + let reservoir = DEFAULT_RESERVOIR; + // A fresh write's regular gas does not move with the byte prices, and 30M of it writes well + // over a thousand slots, so a reservoir that holds no more than that can be emptied. + if reservoir / slot() > 1_000 { + note_price_guard("the default reservoir holds more fresh slots than 30M can write"); + return; + } // The reading is stored into a slot that already holds a value, which writes no new state. - const READING: u64 = 0xff; + // The fresh writes take the slots from zero up, so the reading's key is one none of them reach. + let reading_slot = U256::MAX; let run = |writes| { - let code = - fresh_writes(writes).append(GAS).push_number(READING as u8).append(SSTORE).stop(); - let db = - db_with(code.build()).account_storage(CONTRACT, U256::from(READING), U256::from(1)); - let gas_limit = SYSTEM_CALL_REGULAR_GAS_LIMIT + reservoir; - let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new(), gas_limit); + let code = fresh_writes(writes).append(GAS).push_u256(reading_slot).append(SSTORE).stop(); + let db = db_with(code.build()).account_storage(CONTRACT, reading_slot, U256::from(1)); + let (mega, op) = run_both(both_evms(db), CALLER, CONTRACT, Bytes::new()); assert!(mega.result.is_success(), "{:?}", mega.result); assert_eq!(mega.result.gas().state_gas_spent_final(), writes * slot()); assert_same(&mega, &op); - let reading = mega.state[&CONTRACT].storage[&U256::from(READING)].present_value(); - (reading.to::(), mega.result.gas().reservoir_remaining()) + let reading = mega.state[&CONTRACT].storage[&reading_slot].present_value(); + (reading.to::(), mega.reservoir_remaining) }; // The most slots the reservoir holds, and what the one after them spills. @@ -289,15 +242,9 @@ fn test_reservoir_remaining_is_what_the_writes_left() { let most = DEFAULT_RESERVOIR.checked_div(slot()).map_or(5, |held| held.min(5)); for writes in [0, 1, most] { let code = fresh_writes(writes).stop().build(); - let (mega, op) = run_both( - both_evms(db_with(code)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(code)), CALLER, CONTRACT, Bytes::new()); assert_eq!( - mega.result.gas().reservoir_remaining(), + mega.reservoir_remaining, DEFAULT_RESERVOIR - writes * slot(), "{writes} writes", ); @@ -311,28 +258,16 @@ fn test_reservoir_remaining_is_what_the_writes_left() { #[test] fn test_a_failing_system_call_settles_like_op_revm() { let reverting = fresh_writes(3).revert().build(); - let (mega, op) = run_both( - both_evms(db_with(reverting)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(reverting)), CALLER, CONTRACT, Bytes::new()); assert!(matches!(mega.result, ExecutionResult::Revert { .. }), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR, "nothing kept"); + assert_eq!(mega.reservoir_remaining, DEFAULT_RESERVOIR, "nothing kept"); assert_eq!(mega.result.gas().state_gas_spent_final(), 0); assert_same(&mega, &op); let halting = fresh_writes(3).append(INVALID).build(); - let (mega, op) = run_both( - both_evms(db_with(halting)), - CALLER, - CONTRACT, - Bytes::new(), - SYSTEM_CALL_GAS_LIMIT, - ); + let (mega, op) = run_both(both_evms(db_with(halting)), CALLER, CONTRACT, Bytes::new()); assert!(mega.result.is_halt(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), DEFAULT_RESERVOIR); + assert_eq!(mega.reservoir_remaining, DEFAULT_RESERVOIR); assert_eq!( mega.result.gas().total_gas_spent(), SYSTEM_CALL_REGULAR_GAS_LIMIT, @@ -359,8 +294,7 @@ fn test_a_system_call_with_a_reservoir_stays_exempt() { .with_block_env_access_compute_gas_limit(0), ); - let (mega_outcome, op_outcome) = - run_both((mega, op), SYSTEM_ADDRESS, CONTRACT, Bytes::new(), 250_000_000); + let (mega_outcome, op_outcome) = run_both((mega, op), SYSTEM_ADDRESS, CONTRACT, Bytes::new()); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega_outcome.result.gas().state_gas_spent_final(), 20 * slot(), "m = 1"); assert_eq!(crowded.total_bucket_queries(), 0, "no capacity was read"); @@ -386,29 +320,43 @@ fn registry_with_a_due_change() -> MemoryDatabase { ) } -/// `applyPendingChanges()` on 30M in a crowded SALT region applies the change at the minimum -/// bucket's price: with no reservoir its state gas is paid out of the 30M, which holds it many -/// times over, and it is what op-revm charges, which has no SALT. +/// The pre-block `applyPendingChanges()` call in a crowded SALT region runs on the pre-block +/// budget and applies the change at the minimum bucket's price: its fresh slots are paid out of +/// the reservoir, which holds them, and it is what op-revm charges on the same budget, which has no +/// SALT. #[test] -fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { +fn test_the_pre_block_apply_pending_changes_is_priced_at_the_minimum_bucket() { let crowded = TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); + let (mut mega, mut op) = both_evms_with(registry_with_a_due_change(), crowded.clone()); + let result_and_state = + transact_apply_pending_changes(&mut mega).expect("the pre-block call succeeds"); + assert_eq!(mega.ctx().tx().gas_limit(), PRE_BLOCK_CALL_GAS_LIMIT, "not the block's 10B"); + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega = Settled { result_and_state, reservoir_remaining }; let data = Bytes::from(ISequencerRegistry::applyPendingChangesCall {}.abi_encode()); - let (mega, op) = run_both( - both_evms_with(registry_with_a_due_change(), crowded.clone()), + let op = op_reference::system_call( + &mut op, SYSTEM_ADDRESS, SEQUENCER_REGISTRY_ADDRESS, data, - SYSTEM_CALL_REGULAR_GAS_LIMIT, - ); + PRE_BLOCK_CALL_GAS_LIMIT, + ) + .expect("the system call runs"); assert!(mega.result.is_success(), "{:?}", mega.result); - assert_eq!(mega.result.gas().reservoir_remaining(), 0); + let state = mega.result.gas().state_gas_spent_final(); // Where a state byte is free the slots cost nothing, at any bucket. if !state_is_free() { - let state = mega.result.gas().state_gas_spent_final(); assert!(state > 0, "the change wrote fresh slots"); assert_eq!(state % slot(), 0, "at m = 1"); } + if !runs_at_measurement_prices() { + assert_eq!( + mega.reservoir_remaining, + PRE_BLOCK_CALL_GAS_LIMIT - SYSTEM_CALL_REGULAR_GAS_LIMIT - state, + "the reservoir paid for every slot", + ); + } assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega, &op); } @@ -416,7 +364,7 @@ fn test_apply_pending_changes_at_30m_is_priced_at_the_minimum_bucket() { /// The default system-call entry point runs on revm's default gas limit however large the block, /// in a crowded region too: 30M of regular gas and the margin as reservoir, the EIP-2935 and /// EIP-4788 contracts' writes paid out of it at the minimum bucket. The block's own pre-block -/// calls widen the reservoir with the block (see the block tests); this entry point does not. +/// calls run on the pre-block budget, also whatever the block (see the block tests). #[test] fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_region() { use alloy_eips::{ @@ -432,23 +380,23 @@ fn test_the_default_pre_block_calls_keep_the_30m_regular_budget_in_a_crowded_reg TestExternalEnvs::new().with_default_bucket_capacity(MIN_BUCKET_SIZE as u64 * 2_000); let (mut mega, mut op) = both_evms_with(db, crowded.clone()); let data = Bytes::from(B256::repeat_byte(0x29).0); - let mega_outcome = + let result_and_state = Evm::transact_system_call(&mut mega, SYSTEM_ADDRESS, contract, data.clone()) .expect("the system call runs"); - let op_outcome = revm::handler::SystemCallEvm::system_call_with_caller( + let reservoir_remaining = mega.ctx().additional_limit().reservoir_remaining(); + let mega_outcome = Settled { result_and_state, reservoir_remaining }; + let op_outcome = op_reference::system_call( &mut op, SYSTEM_ADDRESS, contract, data, + SYSTEM_CALL_GAS_LIMIT, ) .expect("the system call runs"); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega.ctx().tx().gas_limit(), SYSTEM_CALL_GAS_LIMIT, "not the block's 10B"); - assert_eq!( - mega_outcome.result.gas().reservoir_remaining(), - DEFAULT_RESERVOIR - slots * slot(), - ); + assert_eq!(mega_outcome.reservoir_remaining, DEFAULT_RESERVOIR - slots * slot()); assert_eq!(crowded.total_bucket_queries(), 0); assert_same(&mega_outcome, &op_outcome); } @@ -495,13 +443,17 @@ fn test_a_system_address_transaction_is_split_by_the_execution_cap() { let mega_outcome = mega.execute_transaction(OpTx(op_transaction(tx))).expect("accepted"); assert!(mega.ctx().is_system_originated(), "it is the protocol's own transaction"); - let op_outcome = op.transact(deposit).expect("accepted"); + let op_outcome = op_reference::transact(&mut op, deposit).expect("accepted"); assert!(mega_outcome.result.is_success(), "{:?}", mega_outcome.result); assert_eq!(mega_outcome.gas.history, 0); - assert_eq!(mega_outcome.result.gas().reservoir_remaining(), reservoir, "{gas_limit}"); - let mut satin = mega_outcome.result_and_state; - let registry = satin.state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("the read"); + assert_eq!(mega_outcome.gas.reservoir_remaining, reservoir, "{gas_limit}"); + let mut satin = Settled { + result_and_state: mega_outcome.result_and_state, + reservoir_remaining: mega_outcome.gas.reservoir_remaining, + }; + let registry = + satin.result_and_state.state.remove(&SEQUENCER_REGISTRY_ADDRESS).expect("the read"); assert!(!registry.is_touched(), "a read-only entry"); assert_eq!(registry.storage.keys().collect::>(), [&CURRENT_SYSTEM_ADDRESS]); assert_same(&satin, &op_outcome); diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs new file mode 100644 index 000000000..6a50c6e83 --- /dev/null +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -0,0 +1,154 @@ +//! The data size of the writes made by anything but the transaction's own execution. +//! +//! What a transaction keeps is counted where its own execution writes: at the completed-write and +//! frame-start hooks, and where revm decides a start. A precompile's writes through +//! `EvmInternals` and an inspector's are not the transaction's own execution, and neither is +//! counted; neither is a start an inspector answers before revm decides it. + +use alloy_evm::precompiles::DynPrecompile; +use alloy_primitives::{address, map::HashMap, Address, Bytes, Log, LogData, B256, U256}; +use mega_evm::{ + test_utils::{transfer_log, BytecodeBuilder, MemoryDatabase}, + MegaContext, MegaEvm, +}; +use revm::{ + bytecode::opcode::STOP, + handler::FrameResult, + interpreter::{ + interpreter::EthInterpreter, CallOutcome, FrameInput, Gas, InstructionResult, + InterpreterResult, + }, + precompile::{PrecompileId, PrecompileOutput}, + Inspector, +}; + +use crate::common::{call, context, grown, records_and_moves, value_call_room}; + +const CALLER: Address = address!("0000000000000000000000000000000000e10000"); +/// The transaction's own frame. +const CONTRACT: Address = address!("0000000000000000000000000000000000e10001"); +/// A contract whose code stops. +const RECEIVER: Address = address!("0000000000000000000000000000000000e10002"); +/// An account with no code. +const PAYEE: Address = address!("0000000000000000000000000000000000e10003"); +/// A node's own precompile, which writes through `EvmInternals`. +const STATEFUL: Address = address!("0000000000000000000000000000000000e10100"); + +/// What every value call moves. +const VALUE: u64 = 1_000; + +/// A log of `address`'s with one topic and no data. +fn marker(address: Address, topic: u8) -> Log { + Log { address, data: LogData::new_unchecked(vec![B256::repeat_byte(topic)], Bytes::new()) } +} + +/// A precompile that writes through `EvmInternals` everything the API lets it: two slots, one of +/// them inside a checkpoint it commits, a log, a value transfer to [`PAYEE`], and, inside a +/// checkpoint it reverts, a third slot and a second log. +fn stateful() -> DynPrecompile { + DynPrecompile::new(PrecompileId::Custom("stateful".into()), |mut input| { + let internals = &mut input.internals; + internals.sstore(STATEFUL, U256::from(1), U256::from(7)).unwrap(); + internals.log(marker(STATEFUL, 1)); + assert_eq!(internals.transfer(STATEFUL, PAYEE, U256::from(1)).unwrap(), None); + let _ = internals.checkpoint(); + internals.sstore(STATEFUL, U256::from(2), U256::from(7)).unwrap(); + internals.checkpoint_commit(); + let checkpoint = internals.checkpoint(); + internals.sstore(STATEFUL, U256::from(3), U256::from(7)).unwrap(); + internals.log(marker(STATEFUL, 2)); + internals.checkpoint_revert(checkpoint); + Ok(PrecompileOutput::new(0, Bytes::new(), input.reservoir)) + }) +} + +/// A node's own precompile that writes through `EvmInternals` — storage, a log, a value transfer, +/// a checkpoint it commits and one it reverts — keeps its writes in the state and the receipt, and +/// counts none of them: the transaction's data size is its body and the start of the value call +/// that reached the precompile, the precompile's record and its caller's and the call's transfer +/// log, as for a precompile that writes nothing. +#[test] +fn test_a_precompiles_writes_through_evm_internals_count_nothing() { + let code = BytecodeBuilder::default().call(STATEFUL, U256::from(VALUE)).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(CONTRACT, U256::from(VALUE)); + let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); + let mut evm = MegaEvm::new(context(db)) + .with_dyn_precompiles(HashMap::from_iter([(STATEFUL, stateful())])); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + let storage = |slot: u64| { + outcome.state[&STATEFUL].storage.get(&U256::from(slot)).map(|slot| slot.present_value) + }; + assert_eq!(storage(1), Some(U256::from(7)), "the precompile's write is kept"); + assert_eq!(storage(2), Some(U256::from(7)), "and the one it committed"); + assert_ne!(storage(3), Some(U256::from(7)), "the one it reverted is not"); + assert_eq!(outcome.state[&PAYEE].info.balance, U256::from(1), "its transfer moved"); + assert_eq!( + outcome.result.logs(), + [ + transfer_log(CONTRACT, STATEFUL, U256::from(VALUE)), + marker(STATEFUL, 1), + transfer_log(STATEFUL, PAYEE, U256::from(1)), + ], + "the receipt carries the call's transfer log, then the precompile's log and transfer log", + ); + assert_eq!( + outcome.usage, + grown(records_and_moves(2, 1), 1), + "the call's start alone is counted, whose value creates STATEFUL" + ); +} + +/// An inspector that answers, in `frame_start`, the call to `target` with a success on the gas +/// the call was given. +struct AnswersAtFrameStart { + target: Address, +} + +impl Inspector, EthInterpreter> for AnswersAtFrameStart { + fn frame_start( + &mut self, + _context: &mut MegaContext, + frame_input: &mut FrameInput, + ) -> Option { + let FrameInput::Call(inputs) = frame_input else { return None }; + (inputs.target_address == self.target).then(|| { + FrameResult::Call(CallOutcome::new( + InterpreterResult::new( + InstructionResult::Stop, + Bytes::new(), + Gas::new(inputs.gas_limit), + ), + inputs.return_memory_offset.clone(), + )) + }) + } +} + +/// A value call an inspector answers in `frame_start`, before revm decides it, starts nothing: +/// the transaction keeps its body alone, whether the answered call is the transaction's own frame +/// or one a contract makes. +#[test] +fn test_a_value_call_answered_at_frame_start_counts_nothing() { + let code = BytecodeBuilder::default().call(RECEIVER, U256::from(VALUE)).stop().build(); + for (case, to, target) in [ + ("below the transaction's frame", CONTRACT, RECEIVER), + ("the transaction's frame", RECEIVER, RECEIVER), + ] { + let db = MemoryDatabase::default() + .account_code(CONTRACT, code.clone()) + .account_balance(CONTRACT, U256::from(VALUE)) + .account_balance(CALLER, U256::from(VALUE)) + .account_code(RECEIVER, Bytes::from_static(&[STOP])); + let value = if to == RECEIVER { VALUE } else { 0 }; + let tx = call(CALLER, to, U256::from(value), value_call_room()); + let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersAtFrameStart { target }); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert!(outcome.result.logs().is_empty(), "{case}: nothing moved"); + assert_eq!(outcome.usage, records_and_moves(0, 0), "{case}"); + } +} diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index fd026b07a..bd954cf08 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -2,26 +2,30 @@ //! //! Every value movement emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm //! journals itself — no `LOG` opcode runs — and the receipt carries. Satin counts it by the rule a -//! `LOG3` carrying one word is counted, 160 bytes, on the lane of the frame whose journal +//! `LOG3` carrying one word is counted, 160 bytes, on the byte pool of the frame whose journal //! checkpoint holds the move, and charges it nothing: //! //! - a frame start that moves value — the transaction's own value, a value `CALL`, a creation's -//! endowment — counts its log with the frame's records, before revm builds the frame, so a -//! crossing answers the frame with the stop before any value moves; -//! - a `SELFDESTRUCT` that moves a balance counts its log with the beneficiary's record, once the -//! opcode completed, and a crossing stops the destructing frame, which takes the move back. +//! endowment — counts its log with the frame's records, held to the limits once revm decided the +//! start, so a crossing stops the frame before it runs and takes the move back; +//! - a `SELFDESTRUCT` that moves a balance counts its log with its records, once the opcode +//! completed, and a crossing stops the destructing frame, which takes the move back. //! //! Every site runs below the execution cap and above it, and is pinned four ways: the exact bytes //! it adds and the log the receipt carries; a frame budget one byte short of them, which stops the //! frame that moves the value and lets its caller resume; the transaction's limit one byte short, //! which does the same, and stops the transaction when the frame is its own; and a failure above //! the move, which takes the log and its bytes back. Each stop is the one a `LOG3` of one word -//! makes in the same place, where the same bytes are counted: its twin below. +//! makes in the same place, where the same bytes are counted: its twin below. A creation's bytes +//! are held to its creator's budget: the creation's share of it holds the created account's record +//! and the log, and the creator's nonce record is counted on the creator once the creation +//! returned, so it is the creator that is one byte short, and its stop takes the move back. //! -//! A frame start is counted before revm decides it. A start revm refuses on its caller's account -//! — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — counts -//! nothing, and runs under a limit as it does without one; a creation onto an occupied address is -//! counted, and revm refuses it after the count. +//! A frame start is held to the limits once revm decided it. A start revm refuses on its caller's +//! account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — +//! counts nothing, and runs under a limit as it does without one; a value call revm answers +//! without building a frame has its move taken back with the stop; a creation onto an occupied +//! address fails on the collision, its start held to nothing. use alloy_op_evm::OpTx; use alloy_primitives::{address, keccak256, Address, Bytes, Log, TxKind, B256, U256}; @@ -40,8 +44,8 @@ use mega_evm::{ }; use revm::{ bytecode::opcode::{ - ADDRESS, CALL, CALLDATASIZE, DELEGATECALL, GAS, JUMPDEST, JUMPI, LOG1, POP, PUSH0, PUSH1, - REVERT, SELFDESTRUCT, STOP, + ADD, ADDRESS, CALL, CALLDATASIZE, GAS, JUMPDEST, JUMPI, LOG1, MSTORE, POP, PUSH0, PUSH1, + RETURN, RETURNDATACOPY, RETURNDATASIZE, REVERT, SELFBALANCE, SELFDESTRUCT, STOP, }, context::{ result::{ExecutionResult, Output}, @@ -51,7 +55,9 @@ use revm::{ Database, Inspector, }; -use crate::common::{account_state_gas, context, execute_under, history_rounds, share}; +use crate::common::{ + account_state_gas, context, execute_under, history_rounds, share, value_call_room, +}; const CALLER: Address = address!("0000000000000000000000000000000000d00000"); /// The contract a nested site's transaction calls: it calls [`ACTOR`] and returns what that @@ -105,7 +111,7 @@ enum Site { enum Variant { /// The move, as it is. Plain, - /// The same bytes on the same lane with no value moved, the last of them a `LOG3` of one word + /// The same bytes on the same pool with no value moved, the last of them a `LOG3` of one word /// where the transfer log is. Twin, /// The move, then a failure above it that takes it back. @@ -124,7 +130,7 @@ impl Site { Self::SelfDestruct, ]; - /// The depth of the frame whose lane holds the log: the transaction's own, or the one the + /// The depth of the frame whose pool holds the log: the transaction's own, or the one the /// actor starts. const fn depth(self) -> u32 { match self { @@ -133,29 +139,52 @@ impl Site { } } + /// The depth of the frame whose budget holds all the bytes the move counts: the frame whose + /// pool holds the log, but for a creation its creator, the actor. The creation's share of the + /// actor's budget holds the created account's record and the log, 200 bytes, whenever the + /// actor's holds those and its own nonce record, 240, which it counts once the creation + /// returned: `share(240)` is 235. + const fn holding_depth(self) -> u32 { + match self { + Self::Create | Self::Create2 => 1, + _ => self.depth(), + } + } + /// The write records the move makes: the recipient's or the created account's, and the - /// caller's own below the transaction's frame; a destruction's beneficiary alone. + /// caller's own below the transaction's frame; a destruction's beneficiary and the account it + /// clears. const fn records(self) -> u64 { match self { - Self::TxValue | Self::TxEndowment | Self::SelfDestruct => 1, + Self::TxValue | Self::TxEndowment => 1, _ => 2, } } - /// The bytes the move counts on its frame's lane: its records and its transfer log. + /// The new accounts and slots `variant` keeps once it ran to its end: the account the move + /// creates — the created account, or [`PAYEE`]'s and the identity precompile's, which hold + /// nothing before the value reaches them — and for the twin, the account it creates or the + /// fresh slots it writes for the records. A move taken back keeps none. + const fn growth(self, variant: Variant) -> u64 { + match (self, variant) { + (_, Variant::TakenBack) => 0, + (Self::TxEndowment | Self::Create | Self::Create2, _) | + (Self::CallWithoutCode | Self::CallToPrecompile, Variant::Plain) => 1, + (_, Variant::Plain) => 0, + (_, Variant::Twin) => self.records(), + } + } + + /// The bytes the move counts: its records and its transfer log. const fn bytes(self) -> u64 { self.records() * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE } - /// What a stop at the move leaves counted beside the body: the nonce record a creation - /// stopped at its start leaves its creator; nothing otherwise. - const fn left_by_a_stop(self) -> LimitUsage { - match self { - Self::Create | Self::Create2 => { - LimitUsage { data_size: WRITE_RECORD_SIZE, write_records: 1 } - } - _ => LimitUsage::ZERO, - } + /// The budget of the frame that holds the move, when the transaction's own frame starts with + /// `first`: that frame itself at the transaction's own frame; below it, 98% of `first` for the + /// actor, and 98% of what the actor has left for the frame it starts. + fn holding_budget(self, first: u64) -> u64 { + budget(self.holding_depth(), first) } /// The account the value moves to. The sender and the actor start at nonce zero. @@ -356,7 +385,11 @@ fn assert_completed( assert_eq!(balance(outcome, site.recipient()), moved, "{case}: the value at the recipient"); assert_eq!( outcome.usage, - LimitUsage { data_size: body + site.bytes(), write_records: site.records() }, + LimitUsage { + data_size: body + site.bytes(), + write_records: site.records(), + state_growth: site.growth(variant) + }, "{case}: the body, the records and one log", ); let history_bytes = body + site.records() * WRITE_RECORD_SIZE + log_history; @@ -373,7 +406,7 @@ fn assert_completed( } /// Asserts `outcome` is `site` stopped at its move by `stop`, with nothing of the move left: no -/// transfer log, no value moved, and only what a stop leaves beside the body counted. +/// transfer log, no value moved, and nothing but the body counted. fn assert_stopped_at_the_move( case: &str, site: Site, @@ -389,10 +422,9 @@ fn assert_stopped_at_the_move( ); assert!(transfer_logs(outcome).is_empty(), "{case}: no transfer log"); assert_eq!(balance(outcome, site.recipient()), U256::ZERO, "{case}: no value moved"); - let left = site.left_by_a_stop(); assert_eq!( outcome.usage, - LimitUsage { data_size: body + left.data_size, write_records: left.write_records }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "{case}: the move's bytes are not counted", ); } @@ -415,18 +447,20 @@ fn test_each_site_counts_its_transfer_log() { } } -/// A frame budget holds the move at exactly its bytes, and one byte short of them stops the frame -/// that moves the value before anything moves, frame-locally: the caller resumes — the relay and -/// the actor return the stop as their output — and the transaction reports no stop. The -/// transaction's own frame has no caller, so its stop reverts the transaction, and the outcome -/// names it, the crossing that produced that frame's result. +/// A frame budget holds the move at exactly the bytes it counts, and one byte short of them stops +/// the frame that holds the move, which keeps nothing of it, frame-locally: the caller resumes — +/// the relay and the actor return the stop as their output — and the transaction reports no stop. +/// The transaction's own frame has no caller, so its stop reverts the transaction, and the outcome +/// names it, the crossing that produced that frame's result. A creation's bytes are held to its +/// creator's budget, whose nonce record is counted on it once the creation returned: one byte +/// short, the creation runs and returns, and the creator is stopped before it runs on. /// /// A `LOG3` of one word where the transfer log is, after the same bytes of records, stops the /// same frame at the same budget with the same revert. #[test] fn test_each_site_stops_one_byte_short_of_its_frame_budget() { for site in Site::ALL { - let cap = cap_for(site.depth(), site.bytes()); + let cap = cap_for(site.holding_depth(), site.bytes()); for gas_limit in GAS_LIMITS { for variant in [Variant::Plain, Variant::Twin] { let case = format!("{site:?} {variant:?} at {gas_limit}"); @@ -470,8 +504,7 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { Some(&Bytes::from(stop.abi_encode())), "{case}: the same stop", ); - let left = site.left_by_a_stop(); - assert_eq!(over.usage.data_size - body, left.data_size, "{case}"); + assert_eq!(over.usage.data_size, body, "{case}: the body alone"); assert!(over.result.logs().is_empty(), "{case}: the log went"); } Variant::TakenBack => unreachable!(), @@ -482,10 +515,11 @@ fn test_each_site_stops_one_byte_short_of_its_frame_budget() { } } -/// The transaction's limit one byte short of the move stops the frame that moves the value there, -/// as its budget does: the stop names the data size and the transaction's limit, the caller -/// resumes — the relay and the actor return the stop as their output — and the move's bytes go -/// with the frame. At the transaction's own frame the stop is the transaction's result, the +/// The transaction's limit one byte short of the move stops the frame that holds the move there, +/// as its budget does: the stop names the data size and the frame's budget, which the limit leaves +/// it, the caller resumes — the relay and the actor return the stop as their output — and the +/// move's bytes go with the frame. For a creation that frame is its creator, stopped once the +/// creation returned. At the transaction's own frame the stop is the transaction's result, the /// outcome names it with the move's bytes in the figure that crossed, and a limit of exactly the /// bytes holds. A `LOG3` of one word where the transfer log is, after the same bytes of records, /// crosses the same way. @@ -504,11 +538,17 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { }; let (outcome, body, limit) = run(1); + // The frame that holds the move crosses its own budget with the transaction's + // limit, and the stop names the budget: at the transaction's own + // frame what the body leaves of the limit; below it, 98% of that + // for the actor, and 98% of what the actor has left for the frame + // it starts. + let budget = site.holding_budget(limit - body); let own_frames = (site.depth() == 0).then_some(LimitCheck::ExceedsLimit { kind: LimitKind::DataSize, - limit, - used: body + site.bytes(), - frame_local: false, + limit: budget, + used: site.bytes(), + frame_local: true, }); assert_eq!( outcome.limit_exceeded, own_frames, @@ -520,7 +560,7 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { "{case}: the caller resumes: {:?}", outcome.result ); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; match variant { Variant::Plain => { assert_stopped_at_the_move(&case, site, &outcome, body, stop); @@ -531,8 +571,7 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { Some(&Bytes::from(stop.abi_encode())), "{case}: the same stop", ); - let left = site.left_by_a_stop(); - assert_eq!(outcome.usage.data_size - body, left.data_size, "{case}"); + assert_eq!(outcome.usage.data_size, body, "{case}: the body alone"); assert!(outcome.result.logs().is_empty(), "{case}: the log went"); } Variant::TakenBack => unreachable!(), @@ -549,6 +588,64 @@ fn test_each_site_stops_one_byte_short_of_the_transaction_limit() { } } +/// A value call revm answers without building a frame — to an account with no code, to a +/// precompile — whose start crosses the transaction's limit is answered with the stop once revm +/// moved the value, and what the start moved is taken back before its caller resumes: the caller, +/// which wrote a slot before the call and reads its own balance before and after it, finds its +/// balance as it was, keeps its slot, and returns the stop it caught. +#[test] +fn test_an_answered_value_call_whose_start_crosses_is_taken_back_before_its_caller_resumes() { + for site in [Site::CallWithoutCode, Site::CallToPrecompile] { + let held = U256::from(10 * VALUE); + let actor = BytecodeBuilder::default() + .sstore(U256::from(1), U256::from(1)) + .append_many([SELFBALANCE, PUSH0, MSTORE]) + .call(site.recipient(), U256::from(VALUE)) + .append_many([POP, SELFBALANCE]) + .push_number(0x20_u8) + .append_many([MSTORE, RETURNDATASIZE, PUSH0]) + .push_number(0x40_u8) + .append_many([RETURNDATACOPY, RETURNDATASIZE]) + .push_number(0x40_u8) + .append_many([ADD, PUSH0, RETURN]) + .build(); + let db = MemoryDatabase::default() + .account_balance(CALLER, U256::from(10u64.pow(18))) + .account_balance(ACTOR, held) + .account_code(ACTOR, actor); + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: 20_000_000, + ..Default::default() + })); + // The body, the slot's record, then the call's two records and its transfer log, but one. + let limit = transaction_body_bytes(&tx) + WRITE_RECORD_SIZE + site.bytes() - 1; + let outcome = + execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + + assert!(outcome.result.is_success(), "{site:?}: {:?}", outcome.result); + assert_eq!(outcome.limit_exceeded, None, "{site:?}: the caller caught the stop"); + let output = outcome.result.output().expect("the caller returns").clone(); + let (before, after) = + (U256::from_be_slice(&output[..32]), U256::from_be_slice(&output[32..64])); + assert_eq!( + (before, after), + (held, held), + "{site:?}: the move is taken back before it reads" + ); + // The actor's budget is what the body leaves; once its slot is kept, the call's start gets + // 98% of what is left, which the move crosses with the transaction's limit. + let budget = crate::common::share(site.bytes() - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + assert_eq!(&output[64..], stop.abi_encode().as_slice(), "{site:?}: the call is the stop"); + assert_eq!(balance(&outcome, site.recipient()), U256::ZERO, "{site:?}: nothing moved"); + assert!(transfer_logs(&outcome).is_empty(), "{site:?}: no transfer log"); + let slot = outcome.state[&ACTOR].storage[&U256::from(1)].present_value; + assert_eq!(slot, U256::from(1), "{site:?}: the caller keeps its own write"); + } +} + /// A failure above the move takes the transfer log back with the move, and its bytes with them: /// the actor reverting after it, or the transaction's own frame failing. What is left counted is /// the body. @@ -565,7 +662,11 @@ fn test_a_failure_takes_each_sites_transfer_log_back() { assert!(!outcome.result.is_halt(), "{case}: {:?}", outcome.result); assert_eq!(outcome.result.is_success(), site.depth() > 0, "{case}: the relay resumes"); assert!(outcome.result.logs().is_empty(), "{case}: the log went with the move"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{case}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{case}" + ); if site == Site::SelfDestruct { assert_eq!(balance(&outcome, DESTRUCTOR), U256::from(VALUE), "{case}"); } @@ -627,23 +728,26 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { .append_many([PUSH0, CALLDATASIZE, PUSH1, end, JUMPI, POP]) .append_many(self_call.build_vec()) .append(JUMPDEST); - let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize); 7] = [ - ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 1, 0), - // The move's sender and recipient are one account, recorded once. - ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 1, 0), - ("a zero-value CALL", db(actor().call(RECEIVER, U256::ZERO)), call(ACTOR, 0), 0, 0), - ("a transaction's value to its sender", db(actor()), call(CALLER, VALUE), 0, 0), + // (case, database, transaction, write records, logs, new accounts and slots) + let cases: [(&str, MemoryDatabase, MegaTransaction, u64, usize, u64); 7] = [ + // The move's sender and recipient are one account, which it leaves as it was: no record. + ("a CALLCODE", db(actor().callcode(RECEIVER, value)), call(ACTOR, 0), 0, 0, 0), + ("a CALL to itself", db(calls_itself_once), call(ACTOR, 0), 0, 0, 0), + ("a zero-value CALL", db(actor().call(RECEIVER, U256::ZERO)), call(ACTOR, 0), 0, 0, 0), + ("a transaction's value to its sender", db(actor()), call(CALLER, VALUE), 0, 0, 0), ( - "a creation that destructs to itself: its endowment's log alone", + "a creation that destructs to itself: its endowment's log alone; the destruction takes \ + back the new account's record and its growth, and the creator's record stands", db(actor().create(value, &burner)), call(ACTOR, 0), - 2, 1, + 1, + 0, ), - ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0), - ("a value call a system contract refuses", db(refused), call(ACTOR, 0), 0, 0), + ("an older account destructing to itself", db(actor()), call(DESTRUCTOR, 0), 0, 0, 0), + ("a value call a system contract refuses", db(refused), call(ACTOR, 0), 0, 0, 0), ]; - for (name, db, tx, records, logs) in cases { + for (name, db, tx, records, logs, growth) in cases { let body = transaction_body_bytes(&tx); let outcome = execute_under(db, tx, EvmTxRuntimeLimits::no_limits()); assert!(outcome.result.is_success(), "{name}: {:?}", outcome.result); @@ -654,6 +758,7 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { LimitUsage { data_size: body + records * WRITE_RECORD_SIZE + logs as u64 * TRANSFER_LOG_SIZE, write_records: records, + state_growth: growth, }, "{name}", ); @@ -673,10 +778,11 @@ fn test_no_transfer_log_where_no_value_moves_to_another_account() { /// A start revm refuses on its caller's account moves nothing and writes nothing, so nothing is /// counted for it, and no limit stops it for what it would have counted: it runs as it does with /// no limit. Here, a value call its caller cannot fund, which revm answers with `OutOfFunds` and no -/// data, which the actor returns: a `CALL`, whose move would count two records and a transfer log, -/// and a `CALLCODE`, whose move to its own account would count the caller's record alone. Neither -/// the transaction's limit nor the frame's budget one byte short of those bytes changes anything. -/// The same call funded to the last wei is made, and both stop it there. +/// data, which the actor returns: a `CALL`, whose move would count two records and a transfer log. +/// Neither the transaction's limit nor the frame's budget one byte short of those bytes changes +/// anything. The same call funded to the last wei is made, and both stop it there. A `CALLCODE` +/// is not among the cases: its move is to the calling account itself, which counts nothing funded +/// or not, so no limit can stop it. #[test] fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { let value = U256::from(VALUE); @@ -695,18 +801,11 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { })); let body = transaction_body_bytes(&tx); let actor = |call: BytecodeBuilder| call.append(POP).return_returndata().build(); - let cases = [ - ( - "a CALL", - actor(BytecodeBuilder::default().call(RECEIVER, value)), - 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - ), - ( - "a CALLCODE", - actor(BytecodeBuilder::default().callcode(RECEIVER, value)), - WRITE_RECORD_SIZE, - ), - ]; + let cases = [( + "a CALL", + actor(BytecodeBuilder::default().call(RECEIVER, value)), + 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + )]; for (name, actor, bytes) in cases { let tx_limit = EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + bytes - 1); let frame_budget = @@ -717,7 +816,11 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { assert!(free.result.is_success(), "{name}: {:?}", free.result); assert_eq!(free.result.output(), Some(&Bytes::new()), "{name}: the refusal's empty data"); assert!(free.result.logs().is_empty(), "{name}"); - assert_eq!(free.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + assert_eq!( + free.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{name}" + ); assert_eq!(balance(&free, ACTOR), U256::from(VALUE - 1), "{name}: nothing moved"); for limits in [tx_limit, frame_budget] { let limited = execute_under(db(VALUE - 1, &actor), tx.clone(), limits); @@ -728,7 +831,9 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { } let stopped = execute_under(db(VALUE, &actor), tx.clone(), tx_limit); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: body + bytes - 1 }; + // The call's start gets 98% of the actor's budget, which the move crosses first. + let budget = crate::common::share(bytes - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; assert_eq!( stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), @@ -745,10 +850,16 @@ fn test_a_value_call_its_caller_cannot_fund_runs_as_without_a_limit() { } } -/// A value call its caller cannot fund is charged nothing for the records it would make, as it -/// counts none: a caller that keeps less gas, once it has forwarded all it can, than those records' -/// history carries on past the refused call. Funded, the same call runs it out of gas at its -/// opcode, which shows the caller does keep less than that. +/// A value call its caller cannot fund is charged nothing at its opcode: the frame-start hook, +/// which charges a start's records from the journal's state, sees the caller cannot fund the value +/// revm then refuses, and the refused call makes no record. So the caller runs on past the refused +/// call, billed its body's history alone and counting nothing more, even where it keeps less than +/// the records would have cost once it has forwarded all it can; the same caller, able to fund the +/// value, runs out of gas at the opcode on the records' history. +/// +/// Before the net-change rule the opcode charged the records whether or not the caller could fund +/// the value, and the charge came back when the refused start returned; a caller that could not +/// pay it halted at the opcode though the start would have been refused. #[test] fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { let actor = @@ -768,26 +879,13 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { ..Default::default() })) }; - // About 150,000 gas for the actor, of which it keeps a sixty-fourth at its `CALL`: less than - // the history of the two records the move would make. Where 64 times that history is not - // above the 20,000 the actor needs to reach its `CALL`, as where a history byte costs - // nothing, no actor both reaches the call and keeps less than the records cost. - let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); - let actor_gas = (64 * records).saturating_sub(1).min(150_000); - if actor_gas < 20_000 { - return; - } - assert!(actor_gas / 64 < records, "the actor keeps less than the records cost"); - let gas_limit = 21_000 + history_gas(transaction_body_bytes(&tx(0))).unwrap() + actor_gas; + let body = transaction_body_bytes(&tx(0)); - let refused = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + let refused = execute_under(db(VALUE - 1), tx(20_000_000), EvmTxRuntimeLimits::no_limits()); assert!(refused.result.is_success(), "{:?}", refused.result); - let funded = execute_under(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); - assert!(funded.result.is_halt(), "{:?}", funded.result); - let body = transaction_body_bytes(&tx(gas_limit)); assert_eq!( refused.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "the refused call counted nothing", ); assert_eq!( @@ -795,128 +893,28 @@ fn test_a_value_call_its_caller_cannot_fund_is_charged_nothing() { history_gas(body).unwrap(), "and paid the body's history alone" ); - assert_eq!(funded.gas.gas_used, gas_limit, "the funded call's halt used the whole gas limit"); -} - -/// Appends a call carrying [`VALUE`] to `MegaAccessControl`, which answers it with -/// `NonZeroTransfer()` before revm looks at the caller's balance, leaving the call's status on the -/// stack. From a caller that holds less, it is a start revm would refuse, answered before its -/// init. -fn call_the_system_contract_answers(code: BytecodeBuilder) -> BytecodeBuilder { - code.mstore(0, IMegaAccessControl::isVolatileDataAccessDisabledCall::SELECTOR) - .append_many([PUSH0, PUSH0]) - .push_number(4u64) - .append(PUSH0) - .push_u256(U256::from(VALUE)) - .push_address(ACCESS_CONTROL_ADDRESS) - .append_many([GAS, CALL]) -} -/// Whether revm refuses a start on its caller's account is found once, by the opcode starting it, -/// and taken by the frame's init. A start answered before its init leaves that answer behind: -/// here a value call its caller cannot fund, which the system contract answers with -/// `NonZeroTransfer()` before revm could refuse it. The frame the caller starts next takes none -/// of it: a `DELEGATECALL` whose two fresh slots cross its budget by a byte reverts on that -/// budget, as it does with no call before it, and keeps nothing. -#[test] -fn test_a_start_answered_before_its_init_leaves_no_refusal_for_the_next() { - const WRITER: Address = address!("0000000000000000000000000000000000d00008"); - let writer = BytecodeBuilder::default() - .sstore(U256::from(1), U256::from(1)) - .sstore(U256::from(2), U256::from(1)) - .stop() - .build(); - // The `ACTOR` holds nothing, so revm would refuse the value; the system contract answers first. - let answered_call = call_the_system_contract_answers; - let delegate_to_writer = |code: BytecodeBuilder| { - code.append_many([PUSH0, PUSH0, PUSH0, PUSH0]) - .push_address(WRITER) - .append_many([GAS, DELEGATECALL]) - .return_top() - }; - let db = |actor: BytecodeBuilder| { - MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) - .account_code(WRITER, writer.clone()) - .account_code(ACTOR, actor.build()) - }; - let tx = OpTx(op_transaction(TxEnv { - caller: CALLER, - kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, - ..Default::default() - })); - let body = transaction_body_bytes(&tx); - let limits = EvmTxRuntimeLimits::no_limits() - .with_frame_data_size_limit(cap_for(1, 2 * WRITE_RECORD_SIZE - 1)); - - let answer = execute_under( - db(answered_call(BytecodeBuilder::default()).append(POP).return_returndata()), - tx.clone(), - limits, - ); - assert_eq!( - answer.result.output(), - Some(&Bytes::from(IMegaAccessControl::NonZeroTransfer::SELECTOR.to_vec())), - "the system contract answers the call, not revm" - ); - - let cases = [ - ("alone", delegate_to_writer(BytecodeBuilder::default())), - ( - "after the answered call", - delegate_to_writer(answered_call(BytecodeBuilder::default()).append(POP)), - ), - ]; - for (name, actor) in cases { - let outcome = execute_under(db(actor), tx.clone(), limits); - assert_eq!( - outcome.result.output(), - Some(&Bytes::from(U256::ZERO.to_be_bytes::<32>())), - "{name}: the DELEGATECALL reverted on its budget", + // About 150,000 gas for the actor, of which it keeps a fiftieth at its `CALL`: less than the + // history of the two records the move would make. Where 50 times that history is not above + // the 20,000 the actor needs to reach its `CALL`, as where a history byte costs nothing, no + // actor both reaches the call and keeps less than the records cost. + let records = history_gas(2 * WRITE_RECORD_SIZE).unwrap(); + let actor_gas = (50 * records).saturating_sub(1).min(150_000); + if actor_gas < 20_000 { + mega_evm::test_utils::note_price_guard( + "two write records' history is too cheap for a caller to keep less than it", ); - assert_eq!(outcome.limit_exceeded, None, "{name}: a frame budget below is no stop"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{name}"); + return; } -} - -/// The answer a transaction's last start left behind is not taken by the next transaction's first -/// frame, whose own answer nothing staged: a deposit pays no history, so no record of its is -/// charged before execution and nothing asks its sender's account before the frame's init. Its -/// value to `RECEIVER` is counted — the recipient's record and the transfer log — as on an EVM -/// that ran nothing before it. -#[test] -fn test_an_answer_a_transaction_leaves_is_not_taken_by_the_next() { - let db = MemoryDatabase::default() - .account_balance(CALLER, U256::from(10u64.pow(18))) - .account_code(ACCESS_CONTROL_ADDRESS, ACCESS_CONTROL_CODE) - .account_code(RECEIVER, Bytes::from_static(&[STOP])) - .account_code( - ACTOR, - call_the_system_contract_answers(BytecodeBuilder::default()).stop().build(), - ); - let answered = OpTx(op_transaction(TxEnv { - caller: CALLER, - kind: TxKind::Call(ACTOR), - gas_limit: 20_000_000, - ..Default::default() - })); - let user_deposit = || deposit(TxKind::Call(RECEIVER), 1_000, 400); - let body = transaction_body_bytes(&user_deposit()); - - let alone = execute_under(db.clone(), user_deposit(), EvmTxRuntimeLimits::no_limits()); - let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits())); - let first = evm.execute_transaction(answered).expect("the transaction is valid"); - assert!(first.result.is_success(), "{:?}", first.result); - let next = evm.execute_transaction(user_deposit()).expect("the transaction is valid"); - - assert_eq!( - next.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, - ); - assert_eq!(next.usage, alone.usage); - assert_eq!(next.result, alone.result); + assert!(actor_gas / 50 < records, "the actor keeps less than the records cost"); + let gas_limit = 21_000 + history_gas(body).unwrap() + actor_gas; + let unfunded = execute_under(db(VALUE - 1), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(unfunded.result.is_success(), "unfunded: charged nothing: {:?}", unfunded.result); + assert_eq!(unfunded.usage, refused.usage, "unfunded: nothing counted"); + assert_eq!(unfunded.gas.history, refused.gas.history, "unfunded: the body's history alone"); + let funded = execute_under(db(VALUE), tx(gas_limit), EvmTxRuntimeLimits::no_limits()); + assert!(funded.result.is_halt(), "funded: out of gas on the records: {:?}", funded.result); + assert_eq!(funded.gas.gas_used, gas_limit, "funded: the halt used the gas limit"); } /// Raises the value of every call to [`RECEIVER`] by one wei as the call starts: an inspector's @@ -936,12 +934,12 @@ impl Inspector, EthInterpreter> for RaisesValue { } } -/// An inspector may rewrite a frame's input after the opcode that starts it found whether revm -/// refuses it, so the inspected start asks again on the input the inspector leaves. The `ACTOR` -/// can fund the value its `CALL` carries and not the one the inspector raises it to: revm refuses -/// the start with `OutOfFunds` and no data, which the actor returns, and nothing is counted for -/// it — under a frame budget one byte short of the records and the transfer log the start would -/// count, which would stop it with the limit's revert data otherwise. +/// An inspector may rewrite a frame's input after the opcode that starts it charged its records, +/// and revm decides the start on the input the inspector leaves. The `ACTOR` can fund the value +/// its `CALL` carries and not the one the inspector raises it to: revm refuses the start with +/// `OutOfFunds` and no data, which the actor returns, and nothing is counted for it — under a +/// frame budget one byte short of the records and the transfer log the start would count, which +/// would stop it with the limit's revert data otherwise. #[test] fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { let actor = BytecodeBuilder::default() @@ -972,20 +970,19 @@ fn test_a_start_an_inspector_rewrites_is_refused_on_the_input_it_leaves() { assert_eq!(outcome.result.output(), Some(&Bytes::new()), "the refusal's empty data"); assert!(transfer_logs(&outcome).is_empty(), "nothing moved"); assert_eq!(balance(&outcome, ACTOR), U256::from(VALUE)); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.limit_exceeded, None); } -/// A creation onto an occupied address is the one refusal decided after its start is counted: -/// revm reads the created address's account only once it builds the frame, and reading it any -/// earlier would load it. Without a limit, the creation fails on the collision after it bumped its -/// creator's nonce, so the creator's record is kept, and the created account's record and the -/// transfer log are not. Under the transaction's limit one byte short of what the start counts, -/// the start's records and transfer log cross it, and the stop comes first: the creation returns -/// the stop rather than the collision's empty data, which the creator returns, and the creator -/// keeps its nonce record either way. +/// A creation onto an occupied address fails on the collision once revm bumped its creator's +/// nonce, and its start is held to nothing: under the transaction's limit one byte short of what +/// its start would count — the created account's record, its creator's nonce and the transfer log +/// — it fails as without a limit, with the collision's empty data, which the creator returns. The +/// created account's record and the transfer log go with the failure; the creator keeps its nonce +/// record, held to its own limits with it, so a limit one byte short of the body and that record +/// stops the creator. #[test] -fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() { +fn test_a_creation_onto_an_occupied_address_fails_on_the_collision() { let occupied = Site::Create2.recipient(); let actor = BytecodeBuilder::default() .create2(U256::from(VALUE), [], U256::ZERO) @@ -1006,6 +1003,13 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() ..Default::default() })); let body = transaction_body_bytes(&tx); + let under = |limit| { + execute_under( + db(), + tx.clone(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ) + }; let free = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); assert!(free.result.is_success(), "{:?}", free.result); @@ -1015,19 +1019,24 @@ fn test_a_creation_onto_an_occupied_address_is_counted_before_revm_refuses_it() assert_eq!(balance(&free, occupied), U256::ZERO, "no value moved"); assert_eq!( free.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE, write_records: 1 }, + LimitUsage { data_size: body + WRITE_RECORD_SIZE, write_records: 1, state_growth: 0 }, "the creator's nonce alone", ); - let limit = body + Site::Create2.bytes() - 1; - let stopped = - execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); - assert!(stopped.result.is_success(), "the creator catches the stop: {:?}", stopped.result); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }; - assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop first"); - assert_eq!(stopped.limit_exceeded, None); - assert_eq!(stopped.usage, free.usage, "the creator's nonce alone"); - assert_eq!(stopped.state[&ACTOR].info.nonce, 1, "the stopped creation bumped it too"); + let limited = under(body + Site::Create2.bytes() - 1); + assert_eq!(limited.limit_exceeded, None); + assert_eq!(limited.result, free.result, "the collision, as without a limit"); + assert_eq!(limited.usage, free.usage, "the creator's nonce alone"); + assert_eq!(limited.gas, free.gas); + + let limit = body + WRITE_RECORD_SIZE - 1; + let stopped = under(limit); + // The creator's nonce record overdraws the actor's budget, which is held first and named. + let stop = + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: WRITE_RECORD_SIZE - 1 }; + assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the creator's"); + assert!(stopped.limit_exceeded.is_some(), "the transaction's own frame is the creator"); + assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); } /// A deposit's value moves in its first frame and is logged there, from the depositor to the @@ -1050,7 +1059,12 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { assert_eq!(balance(&outcome, DEPOSITOR), U256::from(600)); assert_eq!( outcome.usage, - LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, write_records: 1 }, + LimitUsage { + data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, + write_records: 1, + state_growth: 1 + }, + "the recipient's record and the log; the deposit creates its depositor", ); assert_eq!((outcome.gas.history, outcome.gas.history_bytes), (0, 0), "a deposit pays none"); @@ -1071,8 +1085,8 @@ fn test_a_deposits_value_is_logged_and_its_mint_is_not() { ); assert_eq!( stopped.limit_exceeded.map(|stop| (stop.exceeded_limit(), stop.is_frame_local())), - Some((true, false)), - "a user's deposit is stopped at its transfer log", + Some((true, true)), + "a user's deposit is stopped at its transfer log, on its frame's budget", ); assert!(stopped.result.logs().is_empty()); assert_eq!(balance(&stopped, DEPOSITOR), U256::from(1_000), "the mint stays, the value not"); @@ -1107,6 +1121,135 @@ fn test_a_deposit_its_depositor_cannot_fund_fails_as_without_a_limit() { } } +/// A value call whose recipient cannot hold the value — its balance would overflow — is refused by +/// revm with `OverflowPayment` before it journals the move: no transfer log, no record, and the +/// history the actor paid for the records at its opcode comes back with the refusal. A limit one +/// byte short of the start's bytes changes nothing: nothing was counted. +#[test] +fn test_a_value_call_its_recipient_cannot_hold_keeps_nothing() { + let actor = BytecodeBuilder::default().call(PAYEE, U256::from(VALUE)).return_top().build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_balance(PAYEE, U256::MAX) + .account_code(ACTOR, actor.clone()) + }; + for gas_limit in GAS_LIMITS { + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit, + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + start - 1), + ] { + let outcome = execute_under(db(), tx.clone(), limits); + assert!(outcome.result.is_success(), "{limits:?}: {:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::from(vec![0; 32])), "the call failed"); + assert!(outcome.result.logs().is_empty(), "{limits:?}: no transfer log"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); + assert_eq!( + outcome.gas.history, + history_gas(body).unwrap(), + "the records' charge came back" + ); + } + } +} + +/// A value call to a precompile that fails after its gas check — the BN254 pairing given an input +/// of the wrong length — moved its value and journaled its transfer log before the precompile ran, +/// and revm takes both back with the failure. The start is held to the limits as revm made it, on +/// the records and the log it counted before the failure took them back: under a limit one byte +/// short of them the call is answered with the stop rather than the failure, and either way the +/// transaction keeps its body alone. +#[test] +fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { + const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + let actor = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0]) + .push_number(1_u8) + .append(PUSH0) + .push_number(VALUE) + .push_address(EC_PAIRING) + .append_many([GAS, CALL, POP]) + .return_returndata() + .build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_code(ACTOR, actor.clone()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: value_call_room(), + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + + let failed = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + assert!(failed.result.is_success(), "{:?}", failed.result); + assert_eq!(failed.result.output(), Some(&Bytes::new()), "the precompile's failure"); + assert!(failed.result.logs().is_empty(), "the failure took the transfer log back"); + assert_eq!(failed.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); + + let limit = body + start - 1; + let stopped = + execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + let budget = crate::common::share(start - 1); + let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; + assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop"); + assert!(stopped.result.logs().is_empty()); + assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); +} + +/// A `CREATE` from a contract whose nonce cannot be bumped is refused by the opcode itself, which +/// pushes zero before its start's hook: no account, no record, no log, and no history charged for +/// the two records the start would have made. A limit one byte short of the start's bytes changes +/// nothing. +#[test] +fn test_a_nested_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { + let actor = BytecodeBuilder::default().create(U256::from(1), [STOP]).return_top().build(); + let db = || { + MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_nonce(ACTOR, u64::MAX) + .account_code(ACTOR, actor.clone()) + }; + let tx = OpTx(op_transaction(TxEnv { + caller: CALLER, + kind: TxKind::Call(ACTOR), + gas_limit: value_call_room(), + ..Default::default() + })); + let body = transaction_body_bytes(&tx); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + for limits in [ + EvmTxRuntimeLimits::no_limits(), + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + start - 1), + ] { + let outcome = execute_under(db(), tx.clone(), limits); + assert!(outcome.result.is_success(), "{limits:?}: {:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::from(vec![0; 32])), "no address"); + assert!(outcome.result.logs().is_empty(), "{limits:?}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); + assert_eq!(outcome.state[&ACTOR].info.nonce, u64::MAX, "{limits:?}: not bumped"); + assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "no charge for the records"); + } +} + /// A creation from an account whose nonce cannot be bumped is answered by revm with a success /// that creates nothing and moves nothing: a `Return` with no address, and no log. It keeps /// nothing either, and no limit stops it for what it did not do. @@ -1134,7 +1277,11 @@ fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { let outcome = execute_under(db, tx.clone(), limits); assert!(created_nothing(&outcome), "{limits:?}: {:?}", outcome.result); assert_eq!(outcome.limit_exceeded, None, "{limits:?}"); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }, "{limits:?}"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, + "{limits:?}" + ); } let db = MemoryDatabase::default() @@ -1155,7 +1302,7 @@ fn test_a_creation_whose_nonce_cannot_be_bumped_keeps_nothing() { .execute_transaction(tx) .expect("the transaction is valid with the nonce check off"); assert!(created_nothing(&outcome), "{:?}", outcome.result); - assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0 }); + assert_eq!(outcome.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); assert_eq!(outcome.gas.history_bytes, body, "its body alone"); assert_eq!(outcome.gas.history, history_gas(body).unwrap(), "and the history of its body"); } @@ -1202,7 +1349,8 @@ fn test_a_system_transactions_value_is_logged_and_no_limit_stops_it() { outcome.usage, LimitUsage { data_size: body + WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE, - write_records: 1 + write_records: 1, + state_growth: 0, }, "counted all the same", ); @@ -1224,8 +1372,8 @@ fn test_transfer_logs_keep_execution_order() { const MOVED: u64 = 7; let marker = B256::repeat_byte(0x4d); // Regular room, the new account a creation adds, and sixty-four times the history of a few - // records: the creation is forwarded all but a 64th of the gas, and the caller pays the - // records from the 64th it keeps, at whatever a byte costs. + // records: the creation is forwarded all but 2 per cent of the gas, and the caller pays the + // records from the fiftieth it keeps, at whatever a byte costs. let gas_limit = 2_000_000 + 2 * account_state_gas() + crate::common::body_history(0) + diff --git a/crates/mega-evm/tests/satin/withheld_gas.rs b/crates/mega-evm/tests/satin/withheld_gas.rs index d50e617d9..4c9070ec1 100644 --- a/crates/mega-evm/tests/satin/withheld_gas.rs +++ b/crates/mega-evm/tests/satin/withheld_gas.rs @@ -1,7 +1,7 @@ //! Gas detention against every other reader of a frame's gas, and against every out-of-gas. //! //! A detained frame's spendable gas is held at what the limit leaves the transaction, and the rest -//! is withheld: only a regular charge sees the difference. `GAS`, the 63/64 forward, the `SSTORE` +//! is withheld: only a regular charge sees the difference. `GAS`, the 98/100 forward, the `SSTORE` //! sentry, the skip-cold checks and a callee's inheritance see the whole regular gas. So a //! transaction that reads volatile data runs as it does without the read — the same result and the //! same bill on every ledger — unless its compute crosses the limit, which is a regular charge the @@ -426,8 +426,8 @@ fn test_a_callees_out_of_gas_is_caught_as_without_the_read() { /// /// The callee's charge fails on an operand, a memory expansion, a hash, four copies, a log and an /// invalid opcode, all on all the gas; and on the history of the write records a value call makes, -/// after the call forwarded 63/64 of its gas to a frame that never starts. That callee is given -/// 400,000, or less where it would pay that history out of the 64th it keeps, and its caller +/// after the call forwarded 98/100 of its gas to a frame that never starts. That callee is given +/// 400,000, or less where it would pay that history out of the fiftieth it keeps, and its caller /// computes twenty rounds further, so the limit is left less than the callee forwards. Above the /// execution cap the reservoir pays that history, so that case runs below it. A precompile that /// rejects its input halts without running a frame, and burns all it was forwarded too. @@ -456,12 +456,13 @@ fn test_what_a_halting_callee_burns_is_not_compute() { ]; // 6,396 rounds: 19,878,768 of compute before the call. let rounds = 6_396; - // The value call's callee keeps a 64th of what it has at its `CALL`, which has to be less than - // the history of the records the call makes. It spends at most 40,000 before the forward — the - // value transfer, the new account and the cold access. Where 64 times that history is under - // 100,000, as where a history byte costs nothing, the callee cannot also forward past the - // margin its caller leaves, and the case has nothing to show. - let middle_gas = (64 * history(2 * WRITE_RECORD_SIZE)).saturating_sub(1).min(400_000); + // The value call's callee keeps a fiftieth of what it has at its `CALL` once the forward is + // taken, which has to be less than the history of the records the call makes: given less than + // 50 times that history, it keeps less whatever it spends before the forward — the value + // transfer, the new account and the cold access. Where 50 times that history is under 100,000, + // as where a history byte costs nothing, the callee cannot also forward past the margin its + // caller leaves, and the case has nothing to show. + let middle_gas = (50 * history(2 * WRITE_RECORD_SIZE)).saturating_sub(1).min(400_000); for gas_limit in TIERS { for (name, callee) in &cases { let records = name.starts_with("a value call"); @@ -486,11 +487,11 @@ fn test_what_a_halting_callee_burns_is_not_compute() { assert_eq!(slot(&detained, 0), Some(U256::ZERO), "{name}: the call failed"); if records { // `MIDDLE` halted on all it was given; the rest of the regular ledger is compute, - // and it leaves the limit less than the 63/64 `MIDDLE` forwarded, so counting that + // and it leaves the limit less than the 98/100 `MIDDLE` forwarded, so counting that // forward as compute would have stopped the transaction. let compute = plain.outcome.gas.regular - intrinsic(gas_limit) - middle_gas; let margin = detained.limit.unwrap() - compute; - let forwarded = (middle_gas - 40_000) * 63 / 64; + let forwarded = (middle_gas - 40_000) * 98 / 100; assert!(margin < forwarded, "{name}: {margin} short of the limit"); } } @@ -610,73 +611,41 @@ fn test_a_returndatacopy_that_cannot_pay_its_words_burns_what_its_frame_had() { /// for the recipient. The body's history is on the history ledger, whichever pool paid it. const CALL_INTRINSIC: u64 = 12_000 + 3_000; -/// A charge the interpreter's step loop makes before the opcode runs — its static gas — is seen by -/// no wrapper, so what a frame had when it fails counts as compute: burned gas counted as compute, -/// which brings the stop earlier, never later, and by less than the failed charge's price per -/// halting frame. +/// A charge the interpreter's step loop makes before the opcode runs — its static gas — records +/// what the frame had when it fails, as every failed charge does, so a halt on it burns that, and +/// what it burns is not compute. /// /// Fifty children forwarded 5,002 gas each run a `PUSH20` and a `SELFDESTRUCT`, whose static -/// charge of 5,000 fails with 4,999 left. Under a cap of 200,000 the caller stops, though about -/// 8,500 gas of instructions ran after its read. The child that took the compute past the limit -/// did so without a charge crossing it, so the stop is its caller's next charge, and the stop's -/// compute, which the regular ledger bills, is the limit and that child's overshoot, under the -/// 5,000 it failed to pay. Under a cap of 300,000, above fifty times the forward and the caller's -/// own work, the caller completes as without the read. +/// charge of 5,000 fails with 4,999 left. Each burns those, and the caller completes under a cap of +/// 200,000 as without the read: counted as compute, the fifty burns would pass the cap. /// -/// Rules: [S12.18], [S12]. Independence: independent — the limit, the walk of the charges to the -/// crossing and the intrinsic gas are hand arithmetic from the opcode prices and EIP-2780. +/// Rules: [S12.18], [S12]. Independence: independent — every charge is the opcode's price, the +/// burns are the forward less the `PUSH20`, and the intrinsic gas is EIP-2780's. #[test] -fn test_a_halt_on_a_static_charge_counts_what_its_frame_had_as_compute() { +fn test_a_halt_on_a_static_charge_burns_what_its_frame_had() { let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); + // The read and its `POP`, then fifty calls: five pushes, the address, the forward, the access + // (cold the first time), the child's `PUSH20`, and the `POP` of the status. + let warm = crate::salt::entry(GasId::warm_storage_read_cost()); + let compute = 2 + 2 + 50 * (10 + 3 + 3 + 3 + 2) + cold_access() + 49 * warm; + let burned = 50 * (5_002 - 3); + let limit = 2 + 200_000; + assert!(compute <= limit && compute + burned > limit, "only the burns would pass the limit"); for gas_limit in TIERS { - let build = |first| { + let (detained, plain) = with_and_without_read_under(200_000, |first| { let code = calls_to_child(op(BytecodeBuilder::default(), first), 50, 5_002); let db = MemoryDatabase::default() .account_code(CONTRACT, code.stop().build()) .account_code(CHILD, child.clone()); (db, gas_limit) - }; - let (detained, plain) = with_and_without_read_under(200_000, build); - let limit = detained.limit.unwrap(); - assert_eq!(limit, 2 + 200_000); - assert_eq!(detained.outcome.result.output(), Some(&stop_data(limit))); - // The compute after the read: its `POP`, then each call — five pushes, the address, the - // forward's push, the access, cold the first time — and the child's whole forward, which - // it computes with or burns counted as compute, and the caller's `POP`. The caller's first - // charge the limit leaves no room for is the stop. - let mut since_read = 2; - let crossing = 'calls: { - for call in 0..50 { - let access = if call == 0 { cold_access() } else { 100 }; - for charge in [2, 2, 2, 2, 2, 3, 3, access] { - if since_read + charge > 200_000 { - break 'calls since_read; - } - since_read += charge; - } - since_read += 5_002; - if since_read + 2 > 200_000 { - break 'calls since_read; - } - since_read += 2; - } - panic!("the calls fit the cap"); - }; - assert!(crossing > 200_000 && crossing - 200_000 < 5_000, "an overshoot: {crossing}"); - let used = 2 + crossing; + }); + assert_eq!(detained.limit, Some(limit), "the read's compute plus the cap"); + assert_as_without_read(&detained, &plain, "fifty halts on a static charge"); assert_eq!( - detained.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used, - frame_local: false - }) + plain.outcome.gas.regular, + intrinsic(gas_limit) + compute + burned, + "the bill is the intrinsic gas, the compute and the burns" ); - assert_eq!(detained.outcome.gas.regular, CALL_INTRINSIC + used); - assert!(plain.outcome.result.is_success()); - let (detained, plain) = with_and_without_read_under(300_000, build); - assert_as_without_read(&detained, &plain, "fifty halts on a static charge"); } } @@ -692,92 +661,77 @@ fn call_forwarding(code: BytecodeBuilder, to: Address, gas: u32) -> BytecodeBuil .append(CALL) } -/// One case of [`test_a_static_gas_halt_takes_the_compute_past_the_limit`]: the transaction's -/// code after its read, the cap, and the bill worked out by hand. -struct Overshoot { +/// One case of [`test_static_gas_halts_leave_the_compute_where_it_was`]: the transaction's code +/// after its read, the cap, and the bill worked out by hand. +struct StaticHalts { name: &'static str, /// [`CONTRACT`]'s code after its read: the read's `POP`, a call, and what follows it. after_read: fn(BytecodeBuilder) -> BytecodeBuilder, /// The block-environment cap. cap: u64, - /// The transaction's compute, the read's own two gas included, up to the end of the run or - /// to the charge that crossed. + /// The transaction's compute, the read's own two gas included: every charge its frames made. compute: u64, - /// Whether that compute ends on a stop. - stopped: bool, - /// The compute of the same program without the read, which completes. - plain_compute: u64, -} - -/// A frame that halts because it cannot pay an opcode's static gas counts what it had left as -/// compute, and that can take the transaction's compute past the limit without a crossing: no -/// regular charge crossed the limit, so nothing stopped it. The overshoot is less than the static -/// gas the frame failed to pay. Its caller then resumes with no spendable gas, so its next non-zero -/// regular charge is the crossing; a caller whose whole gas cannot pay its own next static gas -/// halts the same way first and adds what it had left, so the overshoots of a chain of halting -/// frames add up. A transaction that makes no non-zero regular charge after the overshoot is not -/// stopped at all, and ends with its compute past the limit. + /// What the halting frames burned: what each had when its static charge failed. + burned: u64, +} + +/// A frame that halts because it cannot pay an opcode's static gas burns what it had left, so a +/// halt adds nothing to the transaction's compute, along a chain of such frames too: the compute +/// stays within the limit where the burns counted as compute would take it past. /// /// Every halt here is a `SELFDESTRUCT`, whose static gas of 5,000 is the largest. The charges, /// from the read on: `TIMESTAMP` 2, which is the compute at the read, then `POP` 2; a call is five /// `PUSH0` at 2, a `PUSH20` and a `PUSH4` at 3, and its cold access of 3,000; a callee forwarded -/// 5,002 runs a `PUSH20` of 3 and halts on its `SELFDESTRUCT` with 4,999 left, all of which is -/// compute. So a call to a halting callee is 3,016 of compute in its caller and the 5,002 it -/// forwarded. +/// 5,002 runs a `PUSH20` of 3 and halts on its `SELFDESTRUCT` with 4,999 left, which it burns. /// -/// - **One frame.** The callee's halt brings the compute from 3,023 to 8,022; under a cap of 3,400 -/// the limit is 3,402, so the halt overshoots it by 4,620, less than 5,000. The caller's `POP` is -/// its next charge and the crossing: the stop reports 8,022, and the bill is the intrinsic gas -/// and that compute, without the `POP`. +/// - **One frame.** The callee's halt leaves the compute at 3,023; under a cap of 3,400 the limit +/// is 3,402, which the caller's `POP` stays within: 3,025, and 4,999 burned. /// - **A chain of two.** [`HALTING_MIDDLE`] is forwarded 12,000, calls [`CHILD`] with 5,002 — /// compute 6,036 at its `CALL`, 6,039 after the child's `PUSH20` — and keeps 12,000 − 3,016 − -/// 5,002 = 3,982. The child's halt brings the compute to 11,038, 4,996 past a limit of 6,042 (a -/// cap of 6,040); the middle frame's next opcode is a `SELFDESTRUCT` its 3,982 cannot pay, so it -/// halts too and adds them: 15,020, 8,978 past the limit, more than either halt could add alone. -/// The caller's `POP` is the crossing. -/// - **No charge after.** The one-frame case ending on `STOP`, which charges nothing, after the -/// call: the transaction succeeds, its compute 8,022, past the limit of 3,402. +/// 5,002 = 3,982. The child's halt burns 4,999, and the middle frame's next opcode is a +/// `SELFDESTRUCT` its 3,982 cannot pay, so it halts too and burns them. The caller's `POP` brings +/// the compute to 6,041, within a limit of 6,042 (a cap of 6,040). +/// - **No charge after.** The one-frame case ending on `STOP` after the call: 3,023. /// -/// Each case runs below the execution cap and above it, and is billed the same in both; without -/// the read the program completes and is billed its whole compute. +/// Each case runs below the execution cap and above it, completes as without the read, and is +/// billed its compute and its burns. /// /// Rules: [S12.18], [S12.24], [S12.38], [S11], [S12]. Independence: independent — every charge is /// the opcode's price, the limit is the read's compute plus the cap, and the intrinsic gas is /// EIP-2780's. #[test] -fn test_a_static_gas_halt_takes_the_compute_past_the_limit() { +fn test_static_gas_halts_leave_the_compute_where_it_was() { let child = BytecodeBuilder::default().push_address(CALLER).append(SELFDESTRUCT).build(); // The middle frame's `SELFDESTRUCT` names the status its call left as the beneficiary. let middle = call_forwarding(BytecodeBuilder::default(), CHILD, 5_002).append(SELFDESTRUCT).build(); - // The cold access the call to the first callee pays, which every case's caps are set above. - let call = 2 + 2 + 10 + 3 + 3 + cold_access(); + // A call to a cold callee: five pushes, the address, the forward and the cold access. + let call = 10 + 3 + 3 + cold_access(); + // The read and its `POP`, then the call to the first callee. + let to_callee = 2 + 2 + call; let cases = [ - Overshoot { + StaticHalts { name: "one frame", after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).append(POP).stop(), cap: 3_400, - compute: call + 5_002, - stopped: true, - plain_compute: call + 5_002 + 2, + compute: to_callee + 3 + 2, + burned: 5_002 - 3, }, - Overshoot { + StaticHalts { name: "a chain of two", after_read: |code| { call_forwarding(code.append(POP), HALTING_MIDDLE, 12_000).append(POP).stop() }, cap: 6_040, - compute: call + 12_000, - stopped: true, - plain_compute: call + 12_000 + 2, + compute: to_callee + call + 3 + 2, + burned: (5_002 - 3) + (12_000 - call - 5_002), }, - Overshoot { + StaticHalts { name: "no charge after", after_read: |code| call_forwarding(code.append(POP), CHILD, 5_002).stop(), cap: 3_400, - compute: call + 5_002, - stopped: false, - plain_compute: call + 5_002, + compute: to_callee + 3, + burned: 5_002 - 3, }, ]; for gas_limit in TIERS { @@ -793,41 +747,16 @@ fn test_a_static_gas_halt_takes_the_compute_past_the_limit() { }); let limit = 2 + case.cap; assert_eq!(detained.limit, Some(limit), "{name}: the read's compute plus the cap"); - assert!(case.compute > limit, "{name}: the halts took the compute past the limit"); - if case.stopped { - assert_eq!( - detained.outcome.result.output(), - Some(&stop_data(limit)), - "{name}: the stop" - ); - assert_eq!( - detained.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit, - used: case.compute, - frame_local: false - }), - "{name}: the stop reports the compute past the limit" - ); - } else { - assert!( - detained.outcome.result.is_success(), - "{name}: {:?}", - detained.outcome.result - ); - assert_eq!(detained.outcome.limit_exceeded, None, "{name}: no stop"); - } - assert_eq!( - detained.outcome.gas.regular, - CALL_INTRINSIC + case.compute, - "{name}: the bill is the intrinsic gas and the compute" + assert!(case.compute <= limit, "{name}: the compute stays within the limit"); + assert!( + case.compute + case.burned > limit, + "{name}: the burns counted as compute would pass it" ); - assert!(plain.outcome.result.is_success(), "{name}: {:?}", plain.outcome.result); + assert_as_without_read(&detained, &plain, name); assert_eq!( plain.outcome.gas.regular, - CALL_INTRINSIC + case.plain_compute, - "{name}: without the read" + CALL_INTRINSIC + case.compute + case.burned, + "{name}: the bill is the intrinsic gas, the compute and the burns" ); } } @@ -1538,6 +1467,69 @@ fn test_the_kzg_point_evaluation_is_priced_and_keeps_no_clamp() { } } +/// Upstream's KZG point evaluation, which costs 50,000, put at the KZG address in place of the +/// Satin entry, which costs 100,000, and called as above, after a read with 80,000 under a cap of +/// 50,000, whose allowance pays neither price. Gas detention decides the same call two ways, +/// priced and unpriced — a failed call against a crossing — and which way follows the route that +/// installed the precompile, not the precompile: +/// +/// - installed through `with_dyn_precompiles`, the route a node changes its set by, it is not +/// priced: it is run on the allowance, runs out of it, and is the stop, which gives its forward +/// back and which its caller catches before it stores the failure; +/// - put in the map around the engine, through the mutable reference `EvmTr::all_mut` hands out, +/// under the Satin entry's id, it is still priced from the Satin table: priced past its forward, +/// it runs on the forward, as the Satin entry does, and fails — on its input, past its own gas +/// check — a failed call that burns its forward, which its caller survives to store. A valid +/// input would compute there, past the cap: the boundary a node keeps to by changing its set +/// through the engine. +#[test] +fn test_a_priced_and_an_unpriced_precompile_part_as_a_failed_call_and_a_crossing() { + let kzg = vec![0_u8; 192]; + let kzg_address = mega_evm::kzg_point_evaluation::ADDRESS; + let upstream = || { + DynPrecompile::new(PrecompileId::KzgPointEvaluation, |input| { + let result = revm::precompile::kzg_point_evaluation::run(input.data, input.gas); + Ok(PrecompileOutput::from_eth_result(result, input.reservoir)) + }) + }; + let cap = 50_000; + let limits = EvmTxRuntimeLimits::default().with_block_env_access_compute_gas_limit(cap); + let allowance = cap - charges_to_the_precompile(kzg.len(), Some(80_000)).total(); + assert!(allowance < 50_000, "the allowance pays neither price"); + for gas_limit in TIERS { + let evm = || { + let db = MemoryDatabase::default() + .account_code(CONTRACT, calls_precompile(TIMESTAMP, kzg_address, Some(80_000))); + MegaEvm::new(context(db).with_tx_runtime_limits(limits)) + }; + let ended = |evm: &MegaEvm| { + let call = evm.inspector().calls.iter().find(|call| call.target == kzg_address); + let call = call.expect("the call ended"); + assert_eq!(call.forward, 80_000); + (call.result, call.precompile_ran) + }; + + let mut unpriced = evm() + .with_dyn_precompiles(HashMap::from_iter([(kzg_address, upstream())])) + .with_inspector(Calls::default()); + let run = run_on(&mut unpriced, tx_with(&kzg, gas_limit)); + let intrinsic = intrinsic_with(&kzg, gas_limit); + assert_caught(&run, intrinsic, allowance, &failed_status_store()); + assert_eq!(ended(&unpriced), (InstructionResult::Revert, true), "the stop, run on the cap"); + + let mut priced = evm().with_inspector(Calls::default()); + revm::handler::EvmTr::all_mut(&mut priced) + .2 + .apply_precompile(&kzg_address, |_| Some(upstream())); + let run = run_on(&mut priced, tx_with(&kzg, gas_limit)); + assert!(run.outcome.result.is_success(), "{:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "a failed call, no stop"); + let ran_and_failed = (InstructionResult::PrecompileError, true); + assert_eq!(ended(&priced), ran_and_failed, "run on its forward, failed on its input"); + assert_eq!(slot(&run, 0), Some(U256::ZERO), "the call fails and its caller goes on"); + } +} + /// A precompile priced between the allowance and its forward whose input fails a check made after /// its gas check: the BN254 pairing of three pairs and a stray byte, priced 147,000 for its three /// whole pairs, which checks the input's length after its gas. Under a cap of 100,000 it is @@ -1811,38 +1803,34 @@ impl Inspector, EthInterpreter> for AnswersPastThe } } -/// An answer past the allowance is the stop, billed the intrinsic gas alone, whatever state or -/// history gas the answer charged: the answer's spending is the charge that crossed, so none of it -/// is made, and the frame, detained from its start, computed nothing before it. Below the -/// execution cap the state or history gas spills onto regular gas and the stop's revert gives it -/// back; above the cap the reservoir pays it and nothing spills. +/// An inspector's answer is taken as given, as revm's inspected frame start takes it: gas +/// detention holds the engine's answers to the compute limit, and an inspector's answer never +/// reaches the engine's frame start. An answer to a frame detained from its start that spent past +/// the cap, with state or history gas on top, is no stop: the transaction succeeds and is billed +/// what the answer spent, the regular gas on the regular ledger and the state or history gas on +/// its own, below the execution cap where it spills onto regular gas and above it where the +/// reservoir pays it. #[test] -fn test_an_answer_past_the_allowance_with_a_spill_is_billed_nothing_of_it() { +fn test_an_inspectors_answer_to_the_transactions_frame_past_the_cap_is_taken_as_given() { for gas_limit in TIERS { for history in [false, true] { + let case = format!("{gas_limit}, history {history}"); let db = MemoryDatabase::default().account_code(CONTRACT, Bytes::from_static(&[STOP])); - let intrinsic = run_on( + let plain = run_on( &mut MegaEvm::new(context(db.clone())), tx(BENEFICIARY, CONTRACT, gas_limit), ) .outcome - .gas - .regular; + .gas; let mut evm = MegaEvm::new(context(db)).with_inspector(AnswersPastTheCapWithASpill { history }); let run = run_on(&mut evm, tx(BENEFICIARY, CONTRACT, gas_limit)); - assert_eq!(run.outcome.result.output(), Some(&stop_data(CAP)), "{gas_limit} {history}"); - assert_eq!( - run.outcome.limit_exceeded, - Some(LimitCheck::ExceedsLimit { - kind: LimitKind::ComputeGas, - limit: CAP, - used: 0, - frame_local: false - }), - "{gas_limit}, history {history}" - ); - assert_eq!(run.outcome.gas.regular, intrinsic, "{gas_limit}, history {history}"); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + assert_eq!(run.outcome.limit_exceeded, None, "{case}: no stop"); + assert_eq!(run.outcome.gas.regular, plain.regular + CAP + 1, "{case}: regular"); + let (state, kept_history) = if history { (0, 1_000) } else { (1_000, 0) }; + assert_eq!(run.outcome.gas.state, plain.state + state, "{case}: state"); + assert_eq!(run.outcome.gas.history, plain.history + kept_history, "{case}: history"); } } } diff --git a/crates/mega-evm/tests/satin/write_records.rs b/crates/mega-evm/tests/satin/write_records.rs index f2aac4aba..1489ee4c9 100644 --- a/crates/mega-evm/tests/satin/write_records.rs +++ b/crates/mega-evm/tests/satin/write_records.rs @@ -1,17 +1,24 @@ -//! The observe-stage-commit layer and the write records it counts. +//! The write records the common execution layer counts, and when it counts them. //! //! A write record is one account or storage write, 40 bytes of data size. The sites: the first //! change of a slot in the transaction (taken back when the slot is written back), a value //! transfer's sender and recipient, a creation's creator nonce and created account, a -//! `SELFDESTRUCT` that moves value to another account, an applied EIP-7702 authority, and the -//! transaction's own value recipient or created account. The sender's own account is part of the -//! transaction body and is not a record. Records are deduplicated per frame and discarded with the -//! frame that fails. +//! `SELFDESTRUCT` that moves value to another account (the account it clears and its beneficiary), +//! an applied EIP-7702 authority, and the transaction's own value recipient or created account. +//! The sender's own account is part of the transaction body and is not a record. +//! +//! An account's record follows the net change of its info within the transaction: a write that +//! makes an unchanged account's nonce, balance or code differ from what the transaction loaded +//! creates the record, a write that returns it to that takes the record back, and a write to an +//! account that already differs adds nothing. A creation's created account follows the same rule: +//! the creation records it when the address was unchanged, and an address the transaction changed +//! before keeps the one record it has. The records a frame made are discarded with the frame that +//! fails; a creator's nonce record is the creating frame's, and survives the creation's failure. //! //! Every value movement also leaves an EIP-7708 transfer log, which is data size and not a record: //! the figures below carry [`TRANSFER_LOG_SIZE`] for each one a transaction keeps. -use alloy_primitives::{address, Address, Bytes, Log, LogData, B256, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, Log, LogData, B256, U256}; use alloy_sol_types::SolCall; use mega_evm::{ system::{ @@ -19,44 +26,47 @@ use mega_evm::{ ORACLE_CONTRACT_ADDRESS, ORACLE_CONTRACT_CODE, }, test_utils::{is_transfer_log, BytecodeBuilder, MemoryDatabase}, - LimitUsage, MegaContext, MegaEvm, StagedRecord, TRANSFER_LOG_SIZE, TX_BODY_SIZE, - WRITE_RECORD_SIZE, + LimitUsage, MegaContext, MegaEvm, TRANSFER_LOG_SIZE, TX_BODY_SIZE, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{ - CALL, CALLDATASIZE, CREATE, GAS, INVALID, JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, - REVERT, SELFDESTRUCT, SSTORE, STOP, + CALL, CALLDATASIZE, CALLER as CALLER_OPCODE, CALLVALUE, CREATE, DELEGATECALL, GAS, INVALID, + JUMPDEST, JUMPI, LOG2, POP, PUSH0, PUSH1, RETURN, REVERT, SELFDESTRUCT, SSTORE, STOP, + }, + context::ContextTr, + interpreter::{ + interpreter::EthInterpreter, interpreter_types::Jumps, CallInputs, CallOutcome, + CreateInputs, CreateOutcome, Interpreter, }, - interpreter::{interpreter::EthInterpreter, interpreter_types::Jumps, Interpreter}, Database, Inspector, }; -use crate::common::{account_state_gas, call, call_with_data, context, create, history, run}; +use crate::common::{ + account_state_gas, call, call_with_data, context, create, deposit, grown, history, run, + value_call_room, +}; const CALLER: Address = address!("0000000000000000000000000000000000100000"); const CALLEE: Address = address!("0000000000000000000000000000000000100001"); const CONTRACT: Address = address!("0000000000000000000000000000000000100002"); const CONTRACT2: Address = address!("0000000000000000000000000000000000100003"); -/// Room for the state gas of several new accounts, including in a frame that resumes after a -/// child burned the 63/64 it was forwarded: at least 50,000,000, and 64 times what a value call to -/// a new account costs its caller at the byte prices in effect. -fn gas_limit() -> u64 { - (64 * (account_state_gas() + history(4 * WRITE_RECORD_SIZE) + 50_000)).max(50_000_000) -} - /// The transaction body and nothing else. const fn body_only() -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE, write_records: 0 } + LimitUsage { data_size: TX_BODY_SIZE, write_records: 0, state_growth: 0 } } /// `n` write records on top of the transaction body. const fn records(n: u64) -> LimitUsage { - LimitUsage { data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, write_records: n } + LimitUsage { + data_size: TX_BODY_SIZE + n * WRITE_RECORD_SIZE, + write_records: n, + state_growth: 0, + } } /// `n` write records and no body: the difference between two transactions that carry the same one. const fn records_only(n: u64) -> LimitUsage { - LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n } + LimitUsage { data_size: n * WRITE_RECORD_SIZE, write_records: n, state_growth: 0 } } fn with_extra(usage: LimitUsage, bytes: u64) -> LimitUsage { @@ -85,21 +95,483 @@ fn append_value_create(builder: BytecodeBuilder) -> BytecodeBuilder { builder.append_many([PUSH0, PUSH0]).append(PUSH1).append(1u8).append(CREATE) } -/* ---------- value transfers and creations, deduplicated per frame ---------- */ +/* ---------- value transfers and creations: a record per account that changed ---------- */ -/// Two value transfers from one frame record the sender once and each recipient. +/// Two value transfers from one frame record the sender once and each recipient: the first +/// transfer changes the sender's balance, and the second finds it changed already. #[test] fn test_two_value_calls_record_the_sender_once() { let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, CONTRACT, CONTRACT2, and a transfer log for each transfer" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, CONTRACT, CONTRACT2, and a transfer log for each transfer; CONTRACT and \ + CONTRACT2 are new" + ); +} + +/// Value transfers to one recipient record it once, and the sender once: the first transfer +/// changes both accounts, and the later ones find them changed. Each transfer still logs. +/// +/// Before the net-change rule a recipient was recorded by every transfer to it — N transfers to +/// one recipient kept N records — and only the sender's record was deduplicated, per frame. +#[test] +fn test_value_calls_to_one_recipient_record_it_once() { + let code = (0..3).fold(BytecodeBuilder::default(), |code, _| { + append_value_call(code, CONTRACT, 1).append(POP) + }); + let (result, usage) = run( + funded().account_code(CALLEE, code.append(STOP).build()), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success()); + assert_eq!( + usage, + grown(with_extra(records(2), 3 * TRANSFER_LOG_SIZE), 1), + "CALLEE once, CONTRACT once, and a transfer log for each transfer; the first transfer \ + creates CONTRACT" + ); +} + +/* ---------- a record follows the net change of its account ---------- */ + +/// `CALLDATASIZE; JUMPI` over `body`, so that a call with empty calldata stops at once: the +/// transaction calls the code with a byte of calldata, and a call back into it carries none. +fn guarded_code(body: BytecodeBuilder) -> Bytes { + BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(5_u8) + .append(JUMPI) + .append(STOP) + .append(JUMPDEST) + .append_many(body.build_vec()) + .build() +} + +/// `CALL(gas=GAS, CALLER, value, [], [])`, leaving the success flag: a transfer of `value` back +/// to whoever called the frame. +fn append_return_to_caller(builder: BytecodeBuilder, value: u8) -> BytecodeBuilder { + builder.append_many([PUSH0, PUSH0, PUSH0, PUSH0]).append(PUSH1).append(value).append_many([ + CALLER_OPCODE, + GAS, + CALL, + ]) +} + +/// Runs the transaction that calls `CALLEE`, holding `callee`, with a byte of calldata, and +/// reports its outcome. +fn run_guarded(callee: Bytes, contract: Bytes) -> mega_evm::MegaTransactionOutcome { + let db = funded().account_code(CALLEE, callee).account_code(CONTRACT, contract); + crate::common::execute( + db, + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + ) +} + +/// What a transaction [`run_guarded`] runs keeps beside `usage`: the byte of calldata it carries. +fn guarded(usage: LimitUsage) -> LimitUsage { + with_extra(usage, 1) +} + +/// The history a transaction [`run_guarded`] runs pays for its body, its byte of calldata and +/// `records` records, at the prices in effect. +fn body_and_records(records: u64) -> u64 { + history(TX_BODY_SIZE + 1 + records * WRITE_RECORD_SIZE) +} + +/// One transfer records its sender and its recipient, and logs. +#[test] +fn test_one_transfer_records_its_sender_and_its_recipient() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + Bytes::new(), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), + "CALLEE, CONTRACT, a log; CONTRACT, which holds no code, is new" + ); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(2)); + } +} + +/// A transfer and its exact return take both records back: the recipient hands the value back to +/// its caller, so both balances are what the transaction loaded, and neither account keeps a +/// record. The two transfer logs stay, and the history the caller paid for the two records comes +/// back to it once the return that took them back is kept. +#[test] +fn test_a_transfer_and_its_exact_return_take_both_records_back() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + // Returns what it was sent, `CALLVALUE`, to `CALLER`. + BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0, CALLVALUE, CALLER_OPCODE, GAS, CALL, POP]) + .stop() + .build(), ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(with_extra(body_only(), 2 * TRANSFER_LOG_SIZE)), + "no record stands; the two transfer logs do" + ); + assert_eq!(outcome.state[&CALLEE].info.balance, U256::from(10_000_000), "back to its balance"); + assert_eq!(outcome.state[&CONTRACT].info.balance, U256::ZERO); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(0), "the records' history came back"); + } +} + +/// A partial return leaves both accounts changed, so both records stand. +#[test] +fn test_a_partial_return_keeps_both_records() { + let outcome = run_guarded( + guarded_code(append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop()), + append_return_to_caller(BytecodeBuilder::default(), 3).append(POP).stop().build(), + ); + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!( + outcome.usage, + guarded(with_extra(records(2), 2 * TRANSFER_LOG_SIZE)), + "CALLEE and CONTRACT still differ from what the transaction loaded" + ); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(2)); + } +} + +/// A child that reverts after writing keeps nothing: a slot it wrote, a transfer it made and +/// the transfer it received go with it, and so does a return of the value it received, which its +/// revert undoes with the receipt. A child whose return alone fails — the call that hands the +/// value back reverts, and the child then succeeds — undoes the take-back and keeps the receipt: +/// both records stand, with the history the caller paid for them, and the child earned no refund +/// for a take-back that did not stand. +#[test] +fn test_a_child_that_reverts_after_writing_keeps_nothing() { + let callee = |returns: u8| { + BytecodeBuilder::default() + .append(CALLDATASIZE) + .push_number(7_u8) + .append(JUMPI) + // A call back into it, carrying no calldata: refuses or accepts the return. + .append_many(if returns == STOP { + [PUSH0, PUSH0, STOP] + } else { + [PUSH0, PUSH0, REVERT] + }) + .append(JUMPDEST) + .append_many( + append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).build_vec(), + ) + .stop() + .build() + }; + let writes_then_reverts = append_value_call( + BytecodeBuilder::default().sstore(U256::from(1), U256::from(1)), + CONTRACT2, + 1, + ) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let returns_then_reverts = append_return_to_caller(BytecodeBuilder::default(), 5) + .append(POP) + .append_many([PUSH0, PUSH0, REVERT]) + .build(); + let returns_then_stops = + append_return_to_caller(BytecodeBuilder::default(), 5).append(POP).stop().build(); + for (case, callee, contract, expected, records) in [ + ( + "a slot and a transfer, then a revert", + callee(STOP), + writes_then_reverts, + guarded(body_only()), + 0, + ), + ( + "the value handed back, then a revert", + callee(STOP), + returns_then_reverts, + guarded(body_only()), + 0, + ), + ( + "the value handed back into a call that reverts", + callee(REVERT), + returns_then_stops, + guarded(with_extra(records(2), TRANSFER_LOG_SIZE)), + 2, + ), + ] { + let outcome = run_guarded(callee, contract); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + let kept = U256::from(5 * records / 2); + assert_eq!(outcome.state[&CONTRACT].info.balance, kept, "{case}: what CONTRACT keeps"); + if !crate::common::history_rounds() { + assert_eq!(outcome.gas.history, body_and_records(records), "{case}"); + } + } +} + +/// A creation that fails leaves its creator's nonce record on the caller: the bump stands, and +/// the creator's account differs by it. A second failing creation adds nothing, the creator being +/// changed already. +#[test] +fn test_a_creation_that_fails_leaves_the_creators_record_on_the_caller() { + for (creations, case) in [(1, "one failed creation"), (2, "two failed creations")] { + let db = funded().account_code(OUTER_CREATOR, reverting_creations(creations)); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "{case}"); + assert_eq!(usage, records(1), "{case}: the creator's nonce record alone"); + assert_eq!(result.state[&OUTER_CREATOR].info.nonce, creations as u64, "{case}"); + } +} + +/// Nested creations record each account once: the outer creator, the account it creates — whose +/// own creation bumps a nonce the creation already changed — and the account that one creates. +#[test] +fn test_nested_creations_record_each_account_once() { + // Init code that creates an account with empty init code and returns no code. + let inner: Vec = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, CREATE, POP]) + .stop() + .build_vec(); + let len = inner.len() as u64; + let outer = BytecodeBuilder::default() + .mstore(0, &inner) + .push_number(len) + .push_number(0_u64) + .push_number(0_u64) + .append_many([CREATE, POP]) + .stop() + .build(); + let (result, usage) = run( + funded().account_code(CALLEE, outer), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!( + usage, + grown(records(3), 2), + "CALLEE, the account it created, and the one that created; both created accounts are new" + ); + let created = CALLEE.create(0); + assert_eq!(result.state[&created].info.nonce, 2, "it created one account of its own"); + assert!(result.state.contains_key(&created.create(1))); +} + +/// A value call to the frame's own account moves nothing and records nothing, and neither does a +/// value `CALLCODE`, which moves the value from the calling account to that same account. +/// +/// Before the net-change rule either recorded the calling account once, as the transfer's sender. +#[test] +fn test_a_value_call_to_self_records_nothing() { + assert_eq!(nested_delta(&[SELF_CALLER]), LimitUsage::ZERO, "a CALL to itself"); + + let code = BytecodeBuilder::default().callcode(CONTRACT, U256::from(1)).append(POP).stop(); + let (result, usage) = run( + funded().account_code(CALLEE, code.build()), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); + assert!(result.result.is_success(), "{:?}", result.result); + assert_eq!(usage, body_only(), "a value CALLCODE"); +} + +/// A transfer to the transaction's sender records nothing for it — validation changed its account +/// already, by its fee and its nonce — and one to a fee account records it, unchanged until +/// execution writes it. The sender of the transfer is recorded either way. +#[test] +fn test_a_transfer_to_the_sender_and_to_a_fee_account() { + for (case, target, expected) in [ + ("the sender", CALLER, with_extra(records(1), TRANSFER_LOG_SIZE)), + ("the block beneficiary", COINBASE, with_extra(records(2), TRANSFER_LOG_SIZE)), + ] { + let code = append_value_call(BytecodeBuilder::default(), target, 1).append(POP).stop(); + let db = funded().account_code(CALLEE, code.build()).account_balance(COINBASE, U256::ONE); + let block = revm::context::BlockEnv { beneficiary: COINBASE, ..crate::common::block() }; + let outcome = MegaEvm::new(context(db).with_block(block)) + .execute_transaction(call(CALLER, CALLEE, U256::ZERO, value_call_room())) + .expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + } +} + +/// A `SELFDESTRUCT` that moves value writes two accounts: the beneficiary, recorded when the +/// move changes it, and the destructed account, whose balance the move clears. A fresh +/// beneficiary is recorded; one a transfer already changed is not; and a destructed account whose +/// whole balance the transaction gave it goes back to what was loaded, taking its record back — +/// as does the caller the value goes back to. +#[test] +fn test_a_destruction_to_a_fresh_and_to_a_changed_beneficiary() { + let destruct_to = |code: BytecodeBuilder, beneficiary: Address| { + code.push_address(beneficiary).append(SELFDESTRUCT) + }; + let sends_then_destructs = destruct_to( + append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP), + CONTRACT, + ); + for (case, callee, contract, balance, expected) in [ + ( + "to a fresh beneficiary, which the destruction creates", + destruct_to(BytecodeBuilder::default(), CONTRACT).build(), + Bytes::new(), + 5, + guarded(grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), + ), + ( + "to a beneficiary a transfer changed, which the transfer creates", + sends_then_destructs.build(), + Bytes::new(), + 5, + guarded(grown(with_extra(records(2), 2 * TRANSFER_LOG_SIZE), 1)), + ), + ( + "of an account whose balance the transaction gave it, back to the giver", + guarded_code( + append_value_call(BytecodeBuilder::default(), CONTRACT, 5).append(POP).stop(), + ), + BytecodeBuilder::default().append_many([CALLER_OPCODE, SELFDESTRUCT]).build(), + 10_000_000, + guarded(with_extra(body_only(), 2 * TRANSFER_LOG_SIZE)), + ), + ] { + let db = funded() + .account_code(CALLEE, callee) + .account_code(CONTRACT, contract) + .account_balance(CALLEE, U256::from(balance)); + let outcome = crate::common::execute( + db, + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + ); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage, expected, "{case}"); + } +} + +/// A creation by `CALLEE`, whose nonce is zero: a `CREATE2` with salt zero, or a `CREATE`. +#[derive(Clone, Copy, Debug)] +enum Creation { + Create2, + Create, +} + +impl Creation { + /// The address a creation of `init_code` lands on. + fn address(self, init_code: &[u8]) -> Address { + match self { + Self::Create2 => CALLEE.create2(B256::ZERO, keccak256(init_code)), + Self::Create => CALLEE.create(0), + } + } + + /// Appends the creation of `init_code`, endowed with `value` wei, and drops its address. + fn append(self, code: BytecodeBuilder, init_code: &[u8], value: u8) -> BytecodeBuilder { + let value = U256::from(value); + match self { + Self::Create2 => code.create2(value, init_code, U256::ZERO), + Self::Create => code.create(value, init_code), + } + .append(POP) + } +} + +/// A creation records the account it creates by the rule every account write follows: when the +/// creation changes an account the transaction had not changed. An address the transaction funded, +/// or a `SELFDESTRUCT` paid, before a creation lands on it is changed already and keeps the one +/// record its first change made, whatever the creation then writes to it, an endowment included. +/// The creator's nonce adds no record either where the transfer that funded the address changed +/// the creator already. +/// +/// The creating opcode charges its caller the created account's history only when the transaction +/// had not changed the address, a `CREATE2`'s as a `CREATE`'s, and the creation's failure gives it +/// back with everything else the creation made: the history the transaction pays is its body's and +/// the records it keeps, at the prices in effect. +/// +/// Before, a creation recorded the account it creates whatever the address held: an address +/// funded then created kept two records, and one paid by a destruction then created kept them with +/// the destructed account's and the creator's. +#[test] +fn test_a_creation_records_its_account_only_when_it_changes_it() { + const DESTRUCTOR: Address = address!("000000000000000000000000000000000000DE57"); + const SUCCEEDS: &[u8] = &[]; + const FAILS: &[u8] = &[PUSH0, PUSH0, REVERT]; + /// What `CALLEE` runs before the creation, given the address X the creation lands on. + type Prelude = fn(BytecodeBuilder, Address) -> BytecodeBuilder; + /// The creation's init code and endowment, if one runs. + type Created = Option<(&'static [u8], u8)>; + let nothing: Prelude = |code, _| code; + let fund: Prelude = |code, x| code.call(x, U256::from(5)).append(POP); + let destruct: Prelude = |code, _| code.call(DESTRUCTOR, U256::ZERO).append(POP); + // (case, what runs before the creation, the creation, the records kept, the transfer logs + // kept, the new accounts kept: X, by the first write that reaches it — a creation onto an + // address the transaction funded adds none) + let rows: [(&str, Prelude, Created, u64, u64, u64); 6] = [ + ("fund X only: CALLEE and X", fund, None, 2, 1, 1), + ("create X only: CALLEE's nonce and X", nothing, Some((SUCCEEDS, 0)), 2, 0, 1), + ("fund X, then create X: CALLEE and X", fund, Some((SUCCEEDS, 0)), 2, 1, 1), + ( + "fund X, then create X with an endowment: CALLEE and X", + fund, + Some((SUCCEEDS, 1)), + 2, + 2, + 1, + ), + ( + "a destruction pays X, then create X: DESTRUCTOR, X and CALLEE's nonce", + destruct, + Some((SUCCEEDS, 0)), + 3, + 1, + 1, + ), + ("fund X, then a creation at X that fails: CALLEE and X", fund, Some((FAILS, 0)), 2, 1, 1), + ]; + for creation in [Creation::Create2, Creation::Create] { + for (case, prelude, created, records_kept, logs, growth) in rows { + let case = format!("{creation:?}, {case}"); + let x = creation.address(created.map_or(SUCCEEDS, |(init, _)| init)); + let mut code = prelude(BytecodeBuilder::default(), x); + if let Some((init, value)) = created { + code = creation.append(code, init, value); + } + let db = funded() + .account_code(CALLEE, code.stop().build()) + .account_code(DESTRUCTOR, BytecodeBuilder::default().selfdestruct(x).build()) + .account_balance(DESTRUCTOR, U256::from(7)); + let outcome = + crate::common::execute(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + let deployed = created.is_some_and(|(init, _)| init == SUCCEEDS); + assert_eq!( + outcome.state.get(&x).map(|account| account.info.nonce), + Some(u64::from(deployed)), + "{case}: X is created where the creation succeeds" + ); + assert_eq!( + outcome.usage, + grown(with_extra(records(records_kept), logs * TRANSFER_LOG_SIZE), growth), + "{case}" + ); + if !crate::common::history_rounds() { + assert_eq!( + outcome.gas.history, + history(TX_BODY_SIZE + records_kept * WRITE_RECORD_SIZE), + "{case}: the body and the records kept, and nothing for a record not made" + ); + } + } + } } /// A creation and a value transfer from one frame record the frame's account once. @@ -107,13 +579,16 @@ fn test_two_value_calls_record_the_sender_once() { fn test_create_then_call_record_the_frame_account_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_call(code, CONTRACT, 1).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, the created account, CONTRACT, and a transfer log for each endowment" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, the created account, CONTRACT, and a transfer log for each endowment; the \ + created account and CONTRACT are new" ); } @@ -122,13 +597,16 @@ fn test_create_then_call_record_the_frame_account_once() { fn test_two_creates_record_the_creator_once() { let code = append_value_create(BytecodeBuilder::default()).append(POP); let code = append_value_create(code).append(POP).append(STOP).build(); - let (result, usage) = - run(funded().account_code(CALLEE, code), call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run( + funded().account_code(CALLEE, code), + call(CALLER, CALLEE, U256::ZERO, value_call_room()), + ); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE once, two created accounts, and a transfer log for each endowment" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2), + "CALLEE once, two created accounts, and a transfer log for each endowment; both created \ + accounts are new" ); } @@ -139,7 +617,7 @@ fn test_failed_child_discards_its_transfer_records() { append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "the outer call succeeds although the child halts"); assert_eq!(usage, body_only()); } @@ -164,15 +642,56 @@ fn test_failed_first_child_lets_the_next_transfer_record_the_sender() { .build(); let db = funded().account_code(CALLEE, code).account_code(CONTRACT, Bytes::from_static(&[INVALID])); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(2), TRANSFER_LOG_SIZE), - "CALLEE and CONTRACT2 and the transfer log, from the second transfer" + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "CALLEE and CONTRACT2 and the transfer log, from the second transfer, which creates \ + CONTRACT2" ); } +/// A library a `DELEGATECALL` runs as its caller: a value transfer to [`CONTRACT`], then a revert +/// when `fails`. +fn library_transferring(fails: bool) -> Bytes { + let code = append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP); + if fails { + code.append_many([PUSH0, PUSH0, REVERT]).build() + } else { + code.append(STOP).build() + } +} + +/// A `DELEGATECALL` runs as its caller, so a value transfer it makes records its caller's account, +/// and that record follows the delegate's frame: kept and handed to the caller when the delegate +/// succeeds, so a later transfer from the caller does not record it again; taken back with the +/// delegate's failure, so the later transfer records it. +#[test] +fn test_a_delegates_record_of_its_callers_account_follows_the_delegate() { + const LIBRARY: Address = address!("0000000000000000000000000000000000100004"); + for fails in [false, true] { + let code = BytecodeBuilder::default() + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_address(LIBRARY) + .append_many([GAS, DELEGATECALL, POP]); + let code = append_value_call(code, CONTRACT2, 1).append(POP).append(STOP).build(); + let db = + funded().account_code(CALLEE, code).account_code(LIBRARY, library_transferring(fails)); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); + assert!(result.result.is_success(), "the caller succeeds"); + let expected = if fails { + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1) + } else { + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 2) + }; + assert_eq!( + usage, expected, + "CALLEE once, then CONTRACT2, and CONTRACT unless it failed; each recipient is new" + ); + } +} + const OUTER_CREATOR: Address = address!("000000000000000000000000000000000000C0FF"); /// `PUSH5 ; PUSH1 0; MSTORE; (PUSH1 5; PUSH1 27; PUSH1 0; CREATE; POP) x @@ -191,7 +710,7 @@ fn reverting_creations(n: usize) -> Bytes { #[test] fn test_reverted_then_retried_create_records_the_creator_once() { let db = funded().account_code(OUTER_CREATOR, reverting_creations(2)); - let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, records(1)); } @@ -208,7 +727,7 @@ fn test_creation_without_funds_records_nothing() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, body_only()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); @@ -220,8 +739,8 @@ const SELF_CALLER: Address = address!("000000000000000000000000000000005E1F0004" fn value_delta(to: Address) -> LimitUsage { let db = || MemoryDatabase::default().account_balance(A, U256::from(1_000_000)); - let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), gas_limit())); - let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, gas_limit())); + let (with_value, usage_value) = run(db(), call(A, to, U256::from(1), value_call_room())); + let (zero_value, usage_zero) = run(db(), call(A, to, U256::ZERO, value_call_room())); assert!(with_value.result.is_success() && zero_value.result.is_success()); usage_value.saturating_sub(usage_zero) } @@ -235,7 +754,11 @@ fn test_top_level_self_transfer_no_double_count() { /// A top-level transfer to another account records the recipient. #[test] fn test_top_level_transfer_counts_the_recipient() { - assert_eq!(value_delta(B), with_extra(records_only(1), TRANSFER_LOG_SIZE), "and its log"); + assert_eq!( + value_delta(B), + grown(with_extra(records_only(1), TRANSFER_LOG_SIZE), 1), + "and its log; the value creates B" + ); } /// `CALLDATASIZE; JUMPI` to a body that calls `targets` with `value`, so an inner call with empty @@ -266,27 +789,21 @@ fn nested_delta(targets: &[Address]) -> LimitUsage { .account_balance(SELF_CALLER, U256::from(1_000_000)) .account_code(SELF_CALLER, self_calling_code(targets, value)); let (result, usage) = - run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), gas_limit())); + run(db, call_with_data(A, SELF_CALLER, Bytes::from_static(&[1]), value_call_room())); assert!(result.result.is_success()); usage }; usage(1).saturating_sub(usage(0)) } -/// A nested transfer to the frame's own account is one account write. -#[test] -fn test_nested_self_call_with_value_counts_once() { - assert_eq!(nested_delta(&[SELF_CALLER]), records_only(1)); -} - /// After a transfer to another account recorded the frame's account, a transfer to itself adds /// nothing. #[test] fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { assert_eq!( nested_delta(&[B, SELF_CALLER]), - with_extra(records_only(2), TRANSFER_LOG_SIZE), - "the transfer to B and its log" + grown(with_extra(records_only(2), TRANSFER_LOG_SIZE), 1), + "the transfer to B and its log; the transfer creates B" ); } @@ -296,9 +813,10 @@ fn test_nested_self_transfer_after_recorded_sender_counts_nothing() { #[test] fn test_sstore_first_change_records_and_write_back_refunds() { type Writes = &'static [(u64, u64)]; + // (writes, the slot's original value, what is kept: a slot written from zero is new) let cases: [(Writes, u64, LimitUsage); 4] = [ - (&[(0, 1)], 0, records(1)), - (&[(0, 1), (0, 2)], 0, records(1)), + (&[(0, 1)], 0, grown(records(1), 1)), + (&[(0, 1), (0, 2)], 0, grown(records(1), 1)), (&[(0, 1), (0, 0)], 0, body_only()), (&[(0, 0)], 5, records(1)), ]; @@ -310,7 +828,7 @@ fn test_sstore_first_change_records_and_write_back_refunds() { let db = MemoryDatabase::default() .account_code(CALLEE, code.stop().build()) .account_storage(CALLEE, U256::ZERO, U256::from(original)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected, "writes {writes:?} over original {original}"); } @@ -323,7 +841,8 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).stop().build(); let failing_child = BytecodeBuilder::default().sstore(U256::ZERO, U256::ZERO).append(INVALID).build(); - for (code, expected) in [(child, body_only()), (failing_child, records(1))] { + // The write-back takes back the caller's new slot with its record, and dies with the child. + for (code, expected) in [(child, body_only()), (failing_child, grown(records(1), 1))] { // CALLEE writes slot 0, then DELEGATECALLs CONTRACT, which writes it back in CALLEE's // storage. let parent = BytecodeBuilder::default() @@ -337,31 +856,36 @@ fn test_write_back_in_a_child_refunds_the_caller_record() { .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, code); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected); } } -/// `SELFDESTRUCT` records the beneficiary only when value moves to another account than the -/// destructed one and the sender, whose account the transaction body counts. A move to the sender -/// still leaves its transfer log; a destruction to itself burns the balance and leaves none. +/// `SELFDESTRUCT` records the accounts the move changes: the destructed account, whose balance it +/// clears, and the beneficiary, unless that is the sender, whose account validation changed. A +/// move to the sender still leaves its transfer log; a destruction to itself, of an account the +/// transaction did not create, moves nothing and leaves none, and so does one of an account with +/// no balance. +/// +/// Before the net-change rule the destructed account was never recorded, only the beneficiary. #[test] fn test_selfdestruct_records_the_beneficiary_when_value_moves() { let destruct_to = |beneficiary: Address| { BytecodeBuilder::default().push_address(beneficiary).append(SELFDESTRUCT).build() }; let cases = [ - (U256::from(5), CONTRACT, with_extra(records(1), TRANSFER_LOG_SIZE)), + // CONTRACT does not exist: the move creates it. + (U256::from(5), CONTRACT, grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1)), (U256::from(5), CALLEE, body_only()), - (U256::from(5), CALLER, with_extra(body_only(), TRANSFER_LOG_SIZE)), + (U256::from(5), CALLER, with_extra(records(1), TRANSFER_LOG_SIZE)), (U256::ZERO, CONTRACT, body_only()), ]; for (balance, beneficiary, expected) in cases { let db = MemoryDatabase::default() .account_code(CALLEE, destruct_to(beneficiary)) .account_balance(CALLEE, balance); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(usage, expected, "balance {balance}, beneficiary {beneficiary}"); } @@ -371,13 +895,17 @@ fn test_selfdestruct_records_the_beneficiary_when_value_moves() { #[test] fn test_top_level_create_records_the_created_account() { // `STOP` is one byte of init code and deposits nothing. - let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[STOP]), gas_limit())); + let (result, usage) = run( + MemoryDatabase::default(), + create(CALLER, Bytes::from_static(&[STOP]), value_call_room()), + ); assert!(result.result.is_success()); - assert_eq!(usage, with_extra(records(1), 1)); + assert_eq!(usage, grown(with_extra(records(1), 1), 1), "the created account is new"); - let (result, usage) = - run(MemoryDatabase::default(), create(CALLER, Bytes::from_static(&[INVALID]), gas_limit())); + let (result, usage) = run( + MemoryDatabase::default(), + create(CALLER, Bytes::from_static(&[INVALID]), value_call_room()), + ); assert!(!result.result.is_success()); assert_eq!(usage, with_extra(body_only(), 1)); } @@ -405,7 +933,8 @@ enum FeeRowPath { /// /// Every row runs from a contract frame, `CALLEE`, which the transaction calls without value and /// which holds ten million wei. A value transfer records its sender, `CALLEE`, and its recipient; -/// a `SELFDESTRUCT` of an account the transaction did not create records its beneficiary alone. +/// a `SELFDESTRUCT` of an account the transaction did not create records the account it clears, +/// `CALLEE`, and its beneficiary. /// Each row moves value to another account, so each keeps one EIP-7708 transfer log, which is /// data size and neither a record nor history. The fee accounts exist before the transaction, so /// no row adds state; the transaction pays a fee at a gas price of ten over a base fee of one, so @@ -426,11 +955,11 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { // (row, the transaction's sender, the account execution writes, the path, the records kept) let rows: [(&str, Address, Address, FeeRowPath, u64); 12] = [ ("the block beneficiary, by a value transfer", CALLER, COINBASE, ValueTransfer, 2), - ("the block beneficiary, by a SELFDESTRUCT", CALLER, COINBASE, SelfDestruct, 1), + ("the block beneficiary, by a SELFDESTRUCT", CALLER, COINBASE, SelfDestruct, 2), ("the L1 fee vault, by a value transfer", CALLER, L1_FEE_RECIPIENT, ValueTransfer, 2), - ("the L1 fee vault, by a SELFDESTRUCT", CALLER, L1_FEE_RECIPIENT, SelfDestruct, 1), + ("the L1 fee vault, by a SELFDESTRUCT", CALLER, L1_FEE_RECIPIENT, SelfDestruct, 2), ("the base fee vault, by a value transfer", CALLER, BASE_FEE_RECIPIENT, ValueTransfer, 2), - ("the base fee vault, by a SELFDESTRUCT", CALLER, BASE_FEE_RECIPIENT, SelfDestruct, 1), + ("the base fee vault, by a SELFDESTRUCT", CALLER, BASE_FEE_RECIPIENT, SelfDestruct, 2), ( "the operator fee vault, by a value transfer", CALLER, @@ -443,10 +972,10 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { CALLER, OPERATOR_FEE_RECIPIENT, SelfDestruct, - 1, + 2, ), ("the sender, by a value transfer", CALLER, CALLER, ValueTransfer, 1), - ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 0), + ("the sender, by a SELFDESTRUCT", CALLER, CALLER, SelfDestruct, 1), ( "the block beneficiary that is the sender, by a value transfer", COINBASE, @@ -459,7 +988,7 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { COINBASE, COINBASE, SelfDestruct, - 0, + 1, ), ]; for (row, sender, target, path, records) in rows { @@ -478,7 +1007,7 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { db = db.account_balance(account, U256::from(1)); } } - let mut tx = call(sender, CALLEE, U256::ZERO, gas_limit()); + let mut tx = call(sender, CALLEE, U256::ZERO, value_call_room()); tx.0.base.gas_price = 10; let block = revm::context::BlockEnv { beneficiary: COINBASE, basefee: 1, ..crate::common::block() }; @@ -528,26 +1057,24 @@ fn test_execution_writes_to_the_fee_accounts_are_records() { /// Records, after each opcode, what the layer holds. #[derive(Default)] struct LayerProbe { - /// `(opcode, staged record left, usage)` after each opcode. - steps: Vec<(u8, bool, LimitUsage)>, + /// `(opcode, usage)` after each opcode. + steps: Vec<(u8, LimitUsage)>, opcode: u8, - /// Stages a log through the Host before every `SSTORE`, as a stale record. - stage_before_sstore: bool, + /// Appends a log through the Host before every `SSTORE`, as a tool's write. + log_before_sstore: bool, } impl Inspector, EthInterpreter> for LayerProbe { fn step(&mut self, interp: &mut Interpreter, context: &mut MegaContext) { self.opcode = interp.bytecode.opcode(); - if self.stage_before_sstore && self.opcode == SSTORE { + if self.log_before_sstore && self.opcode == SSTORE { + let before = context.limit_usage(); let log = Log { address: CALLEE, data: LogData::new(vec![B256::ZERO], Bytes::new()).unwrap(), }; revm::context_interface::Host::log(context, log); - assert!(matches!( - context.additional_limit().staged_record(), - Some(StagedRecord::Log { .. }) - )); + assert_eq!(context.limit_usage(), before, "a tool's log counts nothing"); } } @@ -556,42 +1083,34 @@ impl Inspector, EthInterpreter> for LayerProbe { _interp: &mut Interpreter, context: &mut MegaContext, ) { - let layer = context.additional_limit(); - self.steps.push((self.opcode, layer.staged_record().is_some(), layer.usage())); + self.steps.push((self.opcode, context.limit_usage())); } } -fn probe( - db: MemoryDatabase, - gas_limit: u64, - stage_before_sstore: bool, -) -> Vec<(u8, bool, LimitUsage)> { +fn probe(db: MemoryDatabase, gas_limit: u64, log_before_sstore: bool) -> Vec<(u8, LimitUsage)> { let mut evm = MegaEvm::new(context(db)) - .with_inspector(LayerProbe { stage_before_sstore, ..Default::default() }); + .with_inspector(LayerProbe { log_before_sstore, ..Default::default() }); alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit)).unwrap(); evm.inspector().steps.clone() } -fn after_sstore(steps: &[(u8, bool, LimitUsage)]) -> (bool, LimitUsage) { - let (_, staged, usage) = steps.iter().find(|(op, ..)| *op == SSTORE).copied().unwrap(); - (staged, usage) +fn after_sstore(steps: &[(u8, LimitUsage)]) -> LimitUsage { + steps.iter().find(|(op, _)| *op == SSTORE).map(|(_, usage)| *usage).unwrap() } -/// A completed `SSTORE` commits its record: nothing is left staged and the record is counted by -/// the time the opcode ends. +/// A completed `SSTORE` commits its record by the time the opcode ends. #[test] fn test_completed_sstore_commits_its_record() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), false); - let (staged, usage) = after_sstore(&steps); - assert!(!staged); - assert_eq!(usage, records(1)); + let steps = + probe(MemoryDatabase::default().account_code(CALLEE, code), value_call_room(), false); + assert_eq!(after_sstore(&steps), grown(records(1), 1), "a new slot"); } -/// An `SSTORE` that runs out of gas after its Host call wrote the slot discards the staged -/// record: the Host observed the write, the failure takes it back, and nothing is counted. +/// An `SSTORE` that runs out of gas after its Host call wrote the slot counts nothing: the +/// failure takes the write back, and revm offers the completed-write hook nothing. #[test] -fn test_sstore_out_of_gas_after_the_write_discards_the_record() { +fn test_sstore_out_of_gas_after_the_write_counts_nothing() { // CALLEE calls CONTRACT with 5,000 gas: past the EIP-2200 stipend check, so the Host call // writes the slot, but short of the 22,100 a cold first write charges after it. let child = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); @@ -603,21 +1122,22 @@ fn test_sstore_out_of_gas_after_the_write_discards_the_record() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, parent).account_code(CONTRACT, child); - let steps = probe(db, gas_limit(), false); - let (staged, usage) = after_sstore(&steps); - assert!(!staged, "the record is discarded, not left for the next opcode"); - assert_eq!(usage, body_only(), "a failed opcode's write is not counted"); + let steps = probe(db, value_call_room(), false); + assert_eq!(after_sstore(&steps), body_only(), "a failed opcode's write is not counted"); } -/// A record staged outside an opcode's wrapper is discarded when the next wrapper starts, so it -/// is never committed for that opcode. +/// A log a tool appends through the Host, outside an opcode — here an inspector's, in its `step` +/// before an `SSTORE` — counts nothing, and the `SSTORE` that follows counts its own record alone. #[test] -fn test_wrapper_discards_a_stale_record_on_entry() { +fn test_a_tools_log_in_step_counts_nothing() { let code = BytecodeBuilder::default().sstore(U256::ZERO, U256::from(1)).stop().build(); - let steps = probe(MemoryDatabase::default().account_code(CALLEE, code), gas_limit(), true); - let (staged, usage) = after_sstore(&steps); - assert!(!staged); - assert_eq!(usage, records(1), "the SSTORE's record, and not the stale log's bytes"); + let steps = + probe(MemoryDatabase::default().account_code(CALLEE, code), value_call_room(), true); + assert_eq!( + after_sstore(&steps), + grown(records(1), 1), + "the SSTORE's record and its new slot, and not the tool's log" + ); } /* ---------- applied EIP-7702 authorities ---------- */ @@ -637,7 +1157,7 @@ fn authorizing_call( CALLER, to, U256::from(value), - gas_limit(), + value_call_room(), DELEGATE, authorizations, ) @@ -653,8 +1173,9 @@ fn test_applied_authorities_record_once_each() { authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 0), (AUTHORITY_2, 0), (AUTHORITY_1, 1)]), ); assert!(result.result.is_success(), "{:?}", result.result); - // Three authorization tuples travel in the body; two distinct authorities are applied. - assert_eq!(usage, with_extra(records(2), 3 * mega_evm::AUTHORIZATION_SIZE)); + // Three authorization tuples travel in the body; two distinct authorities are applied, and + // the first authorization of each creates it. + assert_eq!(usage, grown(with_extra(records(2), 3 * mega_evm::AUTHORIZATION_SIZE), 2)); let (result, usage) = run(db(), authorizing_call(CONTRACT, 0, &[(AUTHORITY_1, 7)])); assert!(result.result.is_success()); @@ -674,8 +1195,9 @@ fn test_value_to_an_applied_authority_records_it_once() { assert!(result.result.is_success(), "{:?}", result.result); assert_eq!( usage, - with_extra(records(1), mega_evm::AUTHORIZATION_SIZE + TRANSFER_LOG_SIZE), - "the authority, its authorization and the transfer log" + grown(with_extra(records(1), mega_evm::AUTHORIZATION_SIZE + TRANSFER_LOG_SIZE), 1), + "the authority, its authorization and the transfer log; the authorization creates the \ + authority, and the value finds it" ); // And is charged for once: the transaction's own frame writes no recipient, because the @@ -726,13 +1248,13 @@ fn test_frames_running_as_the_sender_do_not_record_it() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "the transfer happened"); assert_eq!( usage, - with_extra(records(1), TRANSFER_LOG_SIZE), - "CONTRACT2 and the transfer log only; the sender is part of the body" + grown(with_extra(records(1), TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and the transfer log only; the sender is part of the body; CONTRACT2 is new" ); } @@ -751,18 +1273,19 @@ impl Inspector, EthInterpreter> for OverfundCreati } /// A creation that fails before bumping the creator's nonce (here, an endowment an inspector -/// raised past the creator's balance) takes its creator record back with it. +/// raised past the creator's balance) records nothing: the creator's record is counted from the +/// bump, and there is none. #[test] fn test_creation_failing_before_the_nonce_bump_records_nothing() { let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, code))) .with_inspector(OverfundCreations); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 0, "the nonce was never bumped"); - assert_eq!(evm.ctx().additional_limit().usage(), body_only()); + assert_eq!(evm.ctx().limit_usage(), body_only()); } /// A creation that collides with an existing account fails after bumping the creator's nonce, so @@ -771,7 +1294,7 @@ fn test_creation_failing_before_the_nonce_bump_records_nothing() { fn test_colliding_creation_keeps_the_creator_record() { let code = append_value_create(BytecodeBuilder::default()).append(POP).append(STOP).build(); let db = funded().account_code(CALLEE, code).account_nonce(CALLEE.create(0), 1); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the collision comes after the bump"); assert_eq!(usage, records(1), "the creator's nonce only"); @@ -781,8 +1304,9 @@ fn test_colliding_creation_keeps_the_creator_record() { /// is bumped and its record kept, the created account's record goes. #[test] fn test_creation_stopped_at_init_bumps_the_creator_nonce() { - // CALLEE writes a slot (40 bytes of its 100-byte budget), then creates: the creation's two - // records (80 bytes) exceed the 60 bytes left to it. CALLEE stores the created address. + // CALLEE writes a slot (40 bytes of its 80-byte budget), then creates: the creation's share + // of the 40 bytes left, 39, is one short of the created account's record. CALLEE keeps its + // nonce record in those 40 once the creation returned, and stores the created address. let code = BytecodeBuilder::default() .sstore(U256::from(1), U256::from(1)) .append_many([PUSH0, PUSH0, PUSH0]) @@ -792,15 +1316,20 @@ fn test_creation_stopped_at_init_bumps_the_creator_nonce() { .stop() .build(); let db = MemoryDatabase::default().account_code(CALLEE, code); - let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(100); + let limits = mega_evm::EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(80); let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(limits)); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CALLEE].info.nonce, 1, "the stopped creation bumped the nonce"); assert_eq!(result.state[&CALLEE].storage[&U256::ZERO].present_value(), U256::ZERO, "it failed"); - assert_eq!(evm.ctx().additional_limit().usage(), records(2), "slot 1 and the creator's nonce"); + assert_eq!( + evm.ctx().limit_usage(), + grown(records(2), 1), + "slot 1 and the creator's nonce; slot 1 is new, and the failed creation's zero address \ + leaves slot 0 empty" + ); } /// A transaction is held at validation to its body and a record for every entry of its @@ -826,7 +1355,11 @@ fn test_authority_records_are_held_to_the_limit_at_validation() { let largest = TX_BODY_SIZE + tuple + WRITE_RECORD_SIZE; let at_the_cap = with_cap(largest, &once).expect("a transaction at the limit is valid"); assert!(at_the_cap.result.is_success(), "{:?}", at_the_cap.result); - assert_eq!(at_the_cap.usage, with_extra(records(1), tuple)); + assert_eq!( + at_the_cap.usage, + grown(with_extra(records(1), tuple), 1), + "the authority, which the authorization creates" + ); let code = at_the_cap.state[&AUTHORITY_1].info.code.as_ref(); assert_eq!(code.and_then(|code| code.eip7702_address()), Some(DELEGATE), "it is applied"); assert!(refused(largest - 1, &once), "one byte of limit less rejects it"); @@ -836,7 +1369,11 @@ fn test_authority_records_are_held_to_the_limit_at_validation() { assert!(refused(bound - 1, &twice), "two entries are held to two records"); let ran = with_cap(bound, &twice).expect("valid at two records"); assert!(ran.result.is_success(), "{:?}", ran.result); - assert_eq!(ran.usage, with_extra(records(1), 2 * tuple), "the one authority makes one record"); + assert_eq!( + ran.usage, + grown(with_extra(records(1), 2 * tuple), 1), + "the one authority makes one record, and is new once" + ); } /// A funded caller's database, for the runtime out-of-gas tests. @@ -924,12 +1461,137 @@ fn test_an_inspected_runtime_out_of_gas_unwinds_as_a_plain_one() { assert_eq!(inspected.state, plain.state); } -/* ---------- which frame's account counts as recorded ---------- */ +/* ---------- what a transaction changed before its own frame ---------- */ + +/// The accounts the transaction changed from what it loaded as its own frame starts, each with +/// whether its nonce is among what changed: what the journal holds at the first frame's `call` or +/// `create` hook. +#[derive(Default)] +struct ChangedBeforeTheFirstFrame(Option>); + +impl ChangedBeforeTheFirstFrame { + fn note(&mut self, context: &MegaContext) { + if self.0.is_some() { + return; + } + let journal = context.journal_ref(); + let mut changed: Vec<(Address, bool)> = journal + .state + .iter() + .filter(|(_, account)| account.transaction_id == journal.transaction_id) + .filter_map(|(address, account)| { + let (now, loaded) = (&account.info, account.original_info()); + let nonce = now.nonce != loaded.nonce; + (nonce || now.balance != loaded.balance || now.code_hash != loaded.code_hash) + .then_some((*address, nonce)) + }) + .collect(); + changed.sort_unstable(); + self.0 = Some(changed); + } +} + +impl Inspector, EthInterpreter> for ChangedBeforeTheFirstFrame { + fn call(&mut self, context: &mut MegaContext, _: &mut CallInputs) -> Option { + self.note(context); + None + } + + fn create( + &mut self, + context: &mut MegaContext, + _: &mut CreateInputs, + ) -> Option { + self.note(context); + None + } +} + +/// Before its own frame a transaction has changed no account but its sender and the EIP-7702 +/// authorities it applied, whose records the body and the authorities' count hold, and an account +/// it changed there differs by its nonce — but for a creation's sender, whose own creation bumps +/// it later, and which no value goes to. So the transaction's own value, which the history charged +/// before execution prices as the records it makes, takes no record back: its recipient is an +/// account the transaction had not changed, an authority whose nonce no transfer returns, or the +/// sender itself, to which nothing moves. The first frame's start builds on that: it carries no +/// credit for a record taken back; this holds it for every transaction shape, in the release build +/// too. +#[test] +fn test_before_its_own_frame_a_transaction_changed_only_its_sender_and_authorities() { + let sender_funded = || MemoryDatabase::default().account_balance(CALLER, U256::from(1_000)); + let mut minted = deposit(call(CALLER, CONTRACT, U256::from(1), value_call_room())); + minted.0.deposit.mint = Some(5); + let one = U256::from(1); + for (case, db, tx, authorities, records_kept) in [ + ( + "a value call", + sender_funded(), + call(CALLER, CONTRACT, one, value_call_room()), + vec![], + 1, + ), + ( + "a value call to the sender", + sender_funded(), + call(CALLER, CALLER, one, value_call_room()), + vec![], + 0, + ), + ( + "a creation", + sender_funded(), + create(CALLER, Bytes::from_static(&[STOP]), value_call_room()), + vec![], + 1, + ), + ("a deposit that mints and moves value", MemoryDatabase::default(), minted, vec![], 1), + ( + "a value call to the authority it applies", + sender_funded(), + authorizing_call(AUTHORITY_1, 1, &[(AUTHORITY_1, 0)]), + vec![AUTHORITY_1], + 1, + ), + ( + "a value call past the authority it applies", + sender_funded(), + authorizing_call(CONTRACT, 1, &[(AUTHORITY_1, 0)]), + vec![AUTHORITY_1], + 2, + ), + ] { + let recipient = tx.0.base.kind.to().copied(); + let mut evm = + MegaEvm::new(context(db)).with_inspector(ChangedBeforeTheFirstFrame::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert!(outcome.result.is_success(), "{case}: {:?}", outcome.result); + assert_eq!(outcome.usage.write_records, records_kept, "{case}"); + let changed = evm.inspector().0.clone().expect("the first frame started"); + for (account, by_nonce) in &changed { + assert!( + *account == CALLER || authorities.contains(account), + "{case}: {account} changed before the first frame: {changed:?}" + ); + if Some(*account) == recipient && *account != CALLER { + assert!(by_nonce, "{case}: the recipient {account} differs by its nonce"); + } + } + assert!( + authorities.iter().all(|authority| changed.contains(&(*authority, true))), + "{case}: every applied authority is changed, by its nonce: {changed:?}" + ); + } +} + +/* ---------- whose account a frame's writes find changed ---------- */ const D: Address = address!("00000000000000000000000000000000000000D1"); -/// A child that received value records its own account then: its own value transfers do not -/// record it again. +/// A child that received value had its own account recorded by the transfer; passing all of it +/// on returns the account to what the transaction loaded and takes that record back, so what +/// stands is the sender's and the last recipient's. +/// +/// Before the net-change rule the child's account stayed recorded once it was. #[test] fn test_value_receiving_child_records_itself_once() { let a = @@ -939,18 +1601,20 @@ fn test_value_receiving_child_records_itself_once() { .append(STOP) .build(); let db = funded().account_code(CALLEE, a).account_code(CONTRACT, b); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::ZERO, value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); + assert_eq!(result.state[&CONTRACT].info.balance, U256::ZERO, "as it was loaded"); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE, CONTRACT once, CONTRACT2, and two transfer logs" + grown(with_extra(records(2), 2 * TRANSFER_LOG_SIZE), 1), + "CALLEE, CONTRACT2, and two transfer logs: CONTRACT passed on what it received; CONTRACT2 \ + is new" ); } -/// A child that received nothing starts with its own account unrecorded, whatever its caller's -/// state. +/// A child that received nothing has its own account unchanged, whatever its caller's state: its +/// first value transfer records it. #[test] fn test_zero_value_child_starts_unrecorded() { let a = BytecodeBuilder::default() @@ -969,12 +1633,12 @@ fn test_zero_value_child_starts_unrecorded() { .account_code(CALLEE, a) .account_code(CONTRACT, b) .account_balance(CONTRACT, U256::from(5)); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), value_call_room())); assert!(result.result.is_success()); assert_eq!( usage, - with_extra(records(3), 2 * TRANSFER_LOG_SIZE), - "CALLEE as the recipient, CONTRACT, CONTRACT2, and two transfer logs" + grown(with_extra(records(3), 2 * TRANSFER_LOG_SIZE), 1), + "CALLEE as the recipient, CONTRACT, CONTRACT2, and two transfer logs; CONTRACT2 is new" ); } @@ -990,7 +1654,11 @@ fn delegate_to_d() -> Bytes { .build() } -/// A `DELEGATECALL` runs as its caller's account, and inherits whether that account is recorded. +/// A `DELEGATECALL` runs as its caller's account, so a transfer it makes writes that account as +/// the caller left it: changed by the value it received, and returned to what the transaction +/// loaded when the delegate passes that value on, which takes the caller's record back. +/// +/// Before the net-change rule the caller's account stayed recorded once it was. #[test] fn test_delegatecall_child_inherits_the_frame_account_record() { let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -998,18 +1666,18 @@ fn test_delegatecall_child_inherits_the_frame_account_record() { .append(STOP) .build(); let db = funded().account_code(CALLEE, delegate_to_d()).account_code(D, d); - let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLEE, U256::from(1), value_call_room())); assert!(result.result.is_success()); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1), "CALLEE's value moved"); assert_eq!( usage, - with_extra(records(2), 2 * TRANSFER_LOG_SIZE), - "CALLEE as the recipient, CONTRACT2, and two transfer logs" + grown(with_extra(records(1), 2 * TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and two transfer logs: CALLEE passed on the value it received; CONTRACT2 is new" ); } -/// A created frame's account is recorded by the creation; a `DELEGATECALL` from its init code -/// inherits that. +/// A created frame's account is recorded by the creation; a transfer a `DELEGATECALL` from its +/// init code makes finds it changed. #[test] fn test_created_frame_delegatecall_inherits_the_created_account_record() { let d = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -1018,7 +1686,7 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { .build(); let db = funded().account_code(D, d); let tx = { - let mut tx = create(CALLER, delegate_to_d(), gas_limit()); + let mut tx = create(CALLER, delegate_to_d(), value_call_room()); tx.0.base.value = U256::from(5); tx }; @@ -1028,12 +1696,13 @@ fn test_created_frame_delegatecall_inherits_the_created_account_record() { // The init code travels in the body. `STOP` deploys nothing. assert_eq!( usage, - with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), - "the created account, CONTRACT2, and two transfer logs" + grown(with_extra(records(2), delegate_to_d().len() as u64 + 2 * TRANSFER_LOG_SIZE), 2), + "the created account, CONTRACT2, and two transfer logs; both are new" ); } -/// A transaction calling its own sender (delegated) counts the sender as recorded from the start. +/// A transaction calling its own sender (delegated) finds the sender's account changed from the +/// start, by its fee and its nonce: a transfer from it records the recipient alone. #[test] fn test_top_level_self_call_counts_the_sender_as_recorded() { let sender_code = append_value_call(BytecodeBuilder::default(), CONTRACT2, 1) @@ -1045,10 +1714,14 @@ fn test_top_level_self_call_counts_the_sender_as_recorded() { let account = db.load_account(CALLER).unwrap(); account.info.code_hash = delegation.hash_slow(); account.info.code = Some(delegation); - let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, gas_limit())); + let (result, usage) = run(db, call(CALLER, CALLER, U256::ZERO, value_call_room())); assert!(result.result.is_success(), "{:?}", result.result); assert_eq!(result.state[&CONTRACT2].info.balance, U256::from(1)); - assert_eq!(usage, with_extra(records(1), TRANSFER_LOG_SIZE), "CONTRACT2 and its log only"); + assert_eq!( + usage, + grown(with_extra(records(1), TRANSFER_LOG_SIZE), 1), + "CONTRACT2 and its log only; CONTRACT2 is new" + ); } /// Answers every call to `CONTRACT` itself. @@ -1073,10 +1746,10 @@ impl Inspector, EthInterpreter> for AnswerContract } } -/// A call an inspector answers gets an empty lane of its own, so its caller's lane is intact for -/// what the caller does next. +/// A call an inspector answers counts nothing of its own, so what its caller does next is counted +/// as it is without the call. #[test] -fn test_inspector_answered_call_keeps_the_caller_lane() { +fn test_inspector_answered_call_counts_nothing_of_its_own() { let a = BytecodeBuilder::default() .append_many([PUSH0, PUSH0, PUSH0, PUSH0, PUSH0]) .push_address(CONTRACT) @@ -1087,13 +1760,13 @@ fn test_inspector_answered_call_keeps_the_caller_lane() { let mut evm = MegaEvm::new(context(funded().account_code(CALLEE, a))).with_inspector(AnswerContract); let result = - alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, gas_limit())) + alloy_evm::Evm::transact_raw(&mut evm, call(CALLER, CALLEE, U256::ZERO, value_call_room())) .unwrap(); assert!(result.result.is_success()); assert_eq!( - evm.ctx().additional_limit().usage(), - with_extra(records(2), TRANSFER_LOG_SIZE), - "CALLEE and CONTRACT2, and the transfer log" + evm.ctx().limit_usage(), + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "CALLEE and CONTRACT2, and the transfer log; CONTRACT2 is new" ); } @@ -1160,7 +1833,7 @@ fn paired_corpus() -> Vec { beneficiary: Address::ZERO, }; let to_callee = |code: Bytes| funded().account_code(CALLEE, code); - let plain = || call(CALLER, CALLEE, U256::ZERO, gas_limit()); + let plain = || call(CALLER, CALLEE, U256::ZERO, value_call_room()); let calling = |target, value| { append_value_call(BytecodeBuilder::default(), target, value) .append(POP) @@ -1198,13 +1871,13 @@ fn paired_corpus() -> Vec { 0, 0, ), - // Its sender is its recipient: one account, one record, and no transfer log. + // Its sender is its recipient: nothing moves, no record, and no transfer log. case( "a value call to the calling account itself", to_callee(self_calling_code(&[CALLEE], 1)), - call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), gas_limit()), + call_with_data(CALLER, CALLEE, Bytes::from_static(&[1]), value_call_room()), + 0, 0, - 1, ), case( "a log over one word", @@ -1240,10 +1913,11 @@ fn paired_corpus() -> Vec { case( "a creation whose init code reverts", funded().account_code(OUTER_CREATOR, reverting_creations(1)), - call(CALLER, OUTER_CREATOR, U256::ZERO, gas_limit()), + call(CALLER, OUTER_CREATOR, U256::ZERO, value_call_room()), 0, 1, ), + // The account it clears and its beneficiary. Paired { transfer_logs: 1, ..case( @@ -1254,7 +1928,7 @@ fn paired_corpus() -> Vec { .account_balance(CALLEE, U256::from(1)), plain(), 0, - 1, + 2, ) }, case( @@ -1269,7 +1943,7 @@ fn paired_corpus() -> Vec { case( "a transaction carrying calldata", to_callee(Bytes::new()), - call_with_data(CALLER, CALLEE, Bytes::from(vec![7u8; 100]), gas_limit()), + call_with_data(CALLER, CALLEE, Bytes::from(vec![7u8; 100]), value_call_room()), 0, 0, ), @@ -1278,7 +1952,7 @@ fn paired_corpus() -> Vec { ..case( "a value transaction", funded(), - call(CALLER, CONTRACT, U256::from(1), gas_limit()), + call(CALLER, CONTRACT, U256::from(1), value_call_room()), 0, 1, ) @@ -1286,22 +1960,28 @@ fn paired_corpus() -> Vec { case( "a value transaction the recipient reverts", funded().account_code(CONTRACT, reverting), - call(CALLER, CONTRACT, U256::from(1), gas_limit()), + call(CALLER, CONTRACT, U256::from(1), value_call_room()), + 0, 0, + ), + case( + "a creation transaction", + funded(), + create(CALLER, Bytes::new(), value_call_room()), 0, + 1, ), - case("a creation transaction", funded(), create(CALLER, Bytes::new(), gas_limit()), 0, 1), case( "a creation that deploys code", funded(), - create(CALLER, constructor_returning(32), gas_limit()), + create(CALLER, constructor_returning(32), value_call_room()), 32, 1, ), case( "a creation whose revert data is not deployed code", funded(), - create(CALLER, reverting_with(10), gas_limit()), + create(CALLER, reverting_with(10), value_call_room()), 0, 0, ), @@ -1317,7 +1997,7 @@ fn paired_corpus() -> Vec { CALLER, ORACLE_CONTRACT_ADDRESS, send_hint(b"a hint the transaction pays data size for"), - gas_limit(), + value_call_room(), ), 0, 0, @@ -1332,7 +2012,7 @@ fn paired_corpus() -> Vec { { // A fee the beneficiary is actually credited, so the account the transfer // records is one the body's five already bound. - let mut tx = call(CALLER, CONTRACT, U256::from(1), gas_limit()); + let mut tx = call(CALLER, CONTRACT, U256::from(1), value_call_room()); tx.0.base.gas_price = 10; tx }, @@ -1409,14 +2089,12 @@ fn test_every_kept_write_pays_one_record_of_history() { } } -/// A value call an inspector answers makes none of the writes its caller paid for, so all of that -/// history comes back — whatever the inspector answered with. -/// -/// A frame answered without running is the one case where a *successful* result must still give -/// the caller its charge back: the records were never made. An interceptor's refusal and the -/// depth guard both fail, so only an inspector reaches this. +/// A value call an inspector answers makes none of the writes its caller paid for, and counts none. +/// The answer is taken as given, as revm takes it: it carries no start charge for revm to give +/// back, so the history its caller paid at its `CALL` for the records the start would make stays +/// paid, as for the call that runs, while the transaction counts its body alone. #[test] -fn test_an_inspector_answered_value_call_gives_its_history_back() { +fn test_an_inspector_answered_value_call_keeps_its_history_charged() { if crate::common::runs_at_measurement_prices() { return; } @@ -1424,16 +2102,13 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { append_value_call(BytecodeBuilder::default(), CONTRACT, 1).append(POP).append(STOP).build(); let run_with = |inspector: Option| { let db = funded().account_code(CALLEE, code.clone()); - let tx = call(CALLER, CALLEE, U256::ZERO, gas_limit()); + let tx = call(CALLER, CALLEE, U256::ZERO, value_call_room()); match inspector { Some(inspector) => { let mut evm = MegaEvm::new(context(db)).with_inspector(inspector); let result = alloy_evm::Evm::transact_raw(&mut evm, tx).unwrap(); assert!(result.result.is_success(), "{:?}", result.result); - ( - evm.ctx().additional_limit().usage(), - evm.ctx().additional_limit().history_gas_spent(), - ) + (evm.ctx().limit_usage(), evm.ctx().additional_limit().history_gas_spent()) } None => { let outcome = crate::common::execute(db, tx); @@ -1446,17 +2121,17 @@ fn test_an_inspector_answered_value_call_gives_its_history_back() { let (ran_usage, ran_history) = run_with(None); let body = mega_evm::TX_BODY_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE; - assert_eq!(answered_usage, body_only(), "the answered call wrote nothing"); - assert_eq!(answered_history, body, "so its caller pays for nothing beyond its body"); assert_eq!( ran_usage, - with_extra(records(2), TRANSFER_LOG_SIZE), - "the transfer that ran wrote two accounts and left its log" + grown(with_extra(records(2), TRANSFER_LOG_SIZE), 1), + "the transfer that ran wrote two accounts and left its log, and created CONTRACT" ); assert_eq!( ran_history, body + 2 * WRITE_RECORD_SIZE * mega_evm::constants::COST_PER_HISTORY_BYTE ); + assert_eq!(answered_usage, body_only(), "the answered call wrote nothing"); + assert_eq!(answered_history, ran_history, "and its caller's charge for the records stays"); } /* ---------- the KV count and the data size ---------- */ @@ -1472,7 +2147,7 @@ struct KvWeighsNoMore { impl Inspector, EthInterpreter> for KvWeighsNoMore { fn step_end(&mut self, _: &mut Interpreter, context: &mut MegaContext) { self.steps += 1; - let usage = context.additional_limit().usage(); + let usage = context.limit_usage(); if usage.write_records * WRITE_RECORD_SIZE > usage.data_size { self.over.get_or_insert(usage); } @@ -1481,10 +2156,11 @@ impl Inspector, EthInterpreter> for KvWeighsNoMore /// The KV count a node reads is the write-record count, and it never weighs more than the data /// size: every record is forty bytes of it, counted with it and taken back with it. Across the -/// corpus — slots written back, a slot rewritten, accounts recorded once per frame, failed -/// children, a hint — `KV × 40 ≤ data size` holds after every instruction a transaction runs, and -/// what it keeps parts from the records by exactly the bytes that are not records: the body, the -/// logs — the transfer logs among them — the deployed code and the hint's payload. +/// corpus — slots written back, a slot rewritten, accounts written again while they differ from +/// what was loaded, failed children, a hint — `KV × 40 ≤ data size` holds after every instruction +/// a transaction runs, and what it keeps parts from the records by exactly the bytes that are not +/// records: the body, the logs — the transfer logs among them — the deployed code and the hint's +/// payload. /// /// So the data-size limit bounds the records: at the production data-size caps a transaction keeps /// at most 327,680 of them. diff --git a/crates/mega-evm/tests/shared/op_reference.rs b/crates/mega-evm/tests/shared/op_reference.rs new file mode 100644 index 000000000..7f902424d --- /dev/null +++ b/crates/mega-evm/tests/shared/op_reference.rs @@ -0,0 +1,221 @@ +//! op-revm as the reference the comparisons hold Satin to. +//! +//! A target includes this file once, from its `main.rs`: +//! +//! ```ignore +//! #[path = "../shared/op_reference.rs"] +//! mod op_reference; +//! ``` +//! +//! op-revm's handler leaves two things to its consumer that Satin's handler does itself: EIP-8037's +//! split of a system call's gas — at most [`SYSTEM_CALL_REGULAR_GAS`] of it regular gas, the rest +//! its state-gas reservoir — and the reservoir a result settled with, which revm's result does not +//! carry. [`OpReference`] is op-revm's handler with both, so a comparison runs op-revm on the gas +//! Satin runs on, and reads op-revm's reservoir beside its result. +//! +//! The reference overrides every phase op-revm's handler overrides, each forwarded to it, and +//! nothing else: a phase op-revm comes to override must be forwarded here too. + +use std::{cell::Cell, convert::Infallible, ops::Deref}; + +use alloy_primitives::{Address, Bytes}; +use mega_evm::{test_utils::MemoryDatabase, MegaHaltReason}; +use op_revm::{ + handler::OpHandler, L1BlockInfo, OpEvm, OpSpecId, OpTransaction, OpTransactionError, +}; +use revm::{ + context::{ + result::{EVMError, ExecResultAndState, ExecutionResult, ResultGas}, + BlockEnv, CfgEnv, Context, ContextSetters, TxEnv, + }, + context_interface::cfg::gas::GasTracker, + handler::{EthFrame, ExecuteEvm, FrameResult, Handler, SystemCallTx}, + inspector::NoOpInspector, + interpreter::{interpreter::EthInterpreter, InitialAndFloorGas}, + state::EvmState, + Journal, +}; + +/// op-revm's context over a [`MemoryDatabase`]. +pub(crate) type OpContext = Context< + BlockEnv, + OpTransaction, + CfgEnv, + MemoryDatabase, + Journal, + L1BlockInfo, +>; + +/// op-revm's EVM over [`OpContext`]. +pub(crate) type Op = OpEvm; + +type OpError = EVMError; + +/// The regular gas EIP-8037 runs a system call on, at most: the system-call gas limit before +/// EIP-8037. Written out rather than taken from the engine, so the comparison holds the engine's +/// own number to it. +const SYSTEM_CALL_REGULAR_GAS: u64 = 30_000_000; + +/// A result and its state, and the reservoir the result settled with: what a transaction or a +/// system call left of its reservoir, which its sender gets back. +/// +/// Derefs to the result and state, so `outcome.result` and `outcome.state` read through. +#[derive(Debug)] +pub(crate) struct Settled { + pub(crate) result_and_state: ExecResultAndState, EvmState>, + pub(crate) reservoir_remaining: u64, +} + +impl Deref for Settled { + type Target = ExecResultAndState, EvmState>; + + fn deref(&self) -> &Self::Target { + &self.result_and_state + } +} + +/// Runs `tx` on `op` through [`OpReference`], as op-revm's own `transact` runs it. +pub(crate) fn transact(op: &mut Op, tx: OpTransaction) -> Result { + op.0.ctx.set_tx(tx); + let mut handler = OpReference::new(false); + let result = handler.run(op)?; + Ok(Settled { + result_and_state: ExecResultAndState::new(result, op.finalize()), + reservoir_remaining: handler.reservoir.get(), + }) +} + +/// Runs op-revm's system call from `caller` to `contract` with `data` on `gas_limit` through +/// [`OpReference`]: its system-call transaction with the gas limit replaced, run through its +/// handler's system-call path. +pub(crate) fn system_call( + op: &mut Op, + caller: Address, + contract: Address, + data: Bytes, + gas_limit: u64, +) -> Result { + let mut tx = OpTransaction::::new_system_tx_with_caller(caller, contract, data); + tx.base.gas_limit = gas_limit; + op.0.ctx.set_tx(tx); + let mut handler = OpReference::new(true); + let result = handler.run_system_call(op)?; + Ok(Settled { + result_and_state: ExecResultAndState::new(result, op.finalize()), + reservoir_remaining: handler.reservoir.get(), + }) +} + +/// op-revm's handler, splitting a system call's gas as EIP-8037 has it and keeping the reservoir +/// its result settled with. Every phase op-revm's handler overrides is its own. +struct OpReference { + op: OpHandler>, + /// Whether the handler runs a system call, whose gas it splits. + system_call: bool, + /// The reservoir read where revm builds the result's gas of a transaction. + settled: Cell>, + /// The reservoir the result settled with; none for a failed deposit. + reservoir: Cell, +} + +impl OpReference { + fn new(system_call: bool) -> Self { + Self { + op: OpHandler::new(), + system_call, + settled: Cell::new(None), + reservoir: Cell::new(0), + } + } +} + +impl Handler for OpReference { + type Evm = Op; + type Error = OpError; + type HaltReason = MegaHaltReason; + + fn validate_env(&self, evm: &mut Op) -> Result<(), OpError> { + self.op.validate_env(evm) + } + + fn validate_against_state_and_deduct_caller( + &self, + evm: &mut Op, + init_and_floor_gas: &mut InitialAndFloorGas, + ) -> Result<(), OpError> { + self.op.validate_against_state_and_deduct_caller(evm, init_and_floor_gas) + } + + fn tx_gas(&self, evm: &mut Op, init_and_floor_gas: &InitialAndFloorGas) -> GasTracker { + let mut gas = self.op.tx_gas(evm, init_and_floor_gas); + if self.system_call { + let margin = gas.remaining().saturating_sub(SYSTEM_CALL_REGULAR_GAS); + gas.set_remaining(gas.remaining() - margin); + gas.set_reservoir(gas.reservoir() + margin); + } + gas + } + + fn last_frame_result( + &mut self, + evm: &mut Op, + frame_result: &mut FrameResult, + parent_gas: &mut GasTracker, + ) -> Result<(), OpError> { + self.op.last_frame_result(evm, frame_result, parent_gas) + } + + fn post_execution( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + init_and_floor_gas: InitialAndFloorGas, + eip7702_gas_refund: i64, + ) -> Result { + self.settled.set(Some(exec_result.gas().reservoir())); + self.op.post_execution(evm, exec_result, init_and_floor_gas, eip7702_gas_refund) + } + + fn reimburse_caller(&self, evm: &mut Op, exec_result: &mut FrameResult) -> Result<(), OpError> { + self.op.reimburse_caller(evm, exec_result) + } + + fn refund( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + eip7702_refund: i64, + ) -> Result<(), OpError> { + self.op.refund(evm, exec_result, eip7702_refund) + } + + fn reward_beneficiary( + &self, + evm: &mut Op, + exec_result: &mut FrameResult, + ) -> Result<(), OpError> { + self.op.reward_beneficiary(evm, exec_result) + } + + /// revm's system-call path settles without `post_execution`: the result it hands over here is + /// the settled one. + fn execution_result( + &mut self, + evm: &mut Op, + result: FrameResult, + result_gas: ResultGas, + ) -> Result, OpError> { + let reservoir = self.settled.get().unwrap_or_else(|| result.gas().reservoir()); + let result = self.op.execution_result(evm, result, result_gas)?; + self.reservoir.set(reservoir); + Ok(result) + } + + fn catch_error( + &self, + evm: &mut Op, + error: OpError, + ) -> Result, OpError> { + self.op.catch_error(evm, error) + } +} diff --git a/crates/mega-evm/tests/system/access_control.rs b/crates/mega-evm/tests/system/access_control.rs index e1eec4ce0..98cd1f140 100644 --- a/crates/mega-evm/tests/system/access_control.rs +++ b/crates/mega-evm/tests/system/access_control.rs @@ -7,7 +7,7 @@ //! The legacy engine's rows, on Satin's switch. The beneficiary is the block's, `Address::ZERO` in //! these tests. -use alloy_primitives::{address, Address, Bytes, U256}; +use alloy_primitives::{address, keccak256, Address, Bytes, B256, U256}; use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ constants::TX_GAS_LIMIT_CAP, @@ -19,7 +19,7 @@ use mega_evm::{ volatile_data_access_disabled_revert_data, ExternalEnvs, MegaContext, MegaEvm, MegaSpecId, MegaTransaction, TestExternalEnvs, VolatileDataAccess, }; -use revm::bytecode::opcode::*; +use revm::{bytecode::opcode::*, context::BlockEnv}; use crate::common::{block, call_tx_with_gas, steer, system_db, Run, GAS_LIMIT}; @@ -40,10 +40,15 @@ const DISABLED_BY_PARENT: [u8; 4] = IMegaAccessControl::DisabledByParent::SELECT /// Runs `tx` over `db`, with an oracle service that holds slot 0 of the Oracle. fn execute(db: MemoryDatabase, tx: MegaTransaction) -> Run { + execute_in(db, tx, block()) +} + +/// [`execute`] in `block`. +fn execute_in(db: MemoryDatabase, tx: MegaTransaction, block: BlockEnv) -> Run { let envs = TestExternalEnvs::::new() .with_oracle_storage(U256::ZERO, U256::from(0x1234)); let ctx = MegaContext::new_with_external_envs(db, MegaSpecId::SATIN, ExternalEnvs::from(envs)) - .with_block(block()) + .with_block(block) .with_chain(zero_fee_l1_block_info()); let mut evm = MegaEvm::new(ctx); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); @@ -329,6 +334,126 @@ fn test_selfdestruct_beneficiary_not_restricted_without_disable() { assert!(run.logged_status(0)); } +/* ---------- 4b. a creation's own loads ---------- */ + +/// Appends a creation through `scheme` of empty init code carrying `value`, salt zero for a +/// `CREATE2`, leaving the created address on the stack. +fn create_empty(code: BytecodeBuilder, scheme: u8, value: u8) -> BytecodeBuilder { + let code = if scheme == CREATE2 { code.append(PUSH0) } else { code }; + code.append_many([PUSH0, PUSH0]).push_number(value).append(scheme) +} + +/// Where a creation of empty init code by `creator`, whose nonce is `nonce`, lands through +/// `scheme`. +fn created_address(creator: Address, scheme: u8, nonce: u64) -> Address { + if scheme == CREATE2 { + creator.create2(B256::ZERO, keccak256([])) + } else { + creator.create(nonce) + } +} + +/// Asserts that the account at `address` was created, holding `balance`. +fn assert_created(run: &Run, address: Address, balance: u64, case: &str) { + let account = run.outcome.state.get(&address).unwrap_or_else(|| panic!("{case}: not created")); + assert_eq!(account.info.nonce, 1, "{case}: a created account's nonce"); + assert_eq!(account.info.balance, U256::from(balance), "{case}"); +} + +/// The status of the call the parent logged last, after the logs its callee left. +fn last_logged_status(run: &Run) -> bool { + run.logged_status(run.outcome.result.logs().len() - 1) +} + +/// A frame running as the beneficiary that switched access off creates: a `CREATE` carrying value +/// and a `CREATE2` load the creator's account, which is the beneficiary's, for its balance and +/// nonce, and neither load is a volatile read, so neither is refused. The beneficiary's frame +/// succeeds and both accounts are created, the first holding the value. +#[test] +fn test_a_beneficiary_frame_with_access_off_creates() { + let beneficiary = + create_empty(create_empty(disable(BytecodeBuilder::default()), CREATE, 1), CREATE2, 0); + let parent = + log_status(call(BytecodeBuilder::default(), CALL, BENEFICIARY, 50_000_000)).stop().build(); + let db = system_db() + .account_code(PARENT, parent) + .account_code(BENEFICIARY, beneficiary.stop().build()) + .account_balance(BENEFICIARY, U256::from(10)); + let run = execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)); + assert!(last_logged_status(&run), "the beneficiary's frame succeeded"); + assert_created(&run, created_address(BENEFICIARY, CREATE, 0), 1, "CREATE"); + assert_created(&run, created_address(BENEFICIARY, CREATE2, 1), 0, "CREATE2"); + assert_eq!(run.accessed, VolatileDataAccess::BENEFICIARY_BALANCE, "the parent's call of it"); +} + +/// A value `CALL` from a frame running as the beneficiary that switched access off moves the +/// value: the check of the caller's balance is no volatile read, as a creation's is not. +#[test] +fn test_a_value_call_from_a_beneficiary_frame_with_access_off_moves_the_value() { + let beneficiary = disable(BytecodeBuilder::default()) + .append_many([PUSH0, PUSH0, PUSH0, PUSH0]) + .push_number(1_u8) + .push_address(SIBLING) + .push_number(100_000_u32) + .append_many([CALL, STOP]); + let parent = + log_status(call(BytecodeBuilder::default(), CALL, BENEFICIARY, 50_000_000)).stop().build(); + let db = system_db() + .account_code(PARENT, parent) + .account_code(BENEFICIARY, beneficiary.build()) + .account_balance(BENEFICIARY, U256::from(10)); + let run = execute(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT)); + assert!(last_logged_status(&run), "the beneficiary's frame succeeded"); + assert_eq!(run.outcome.state[&SIBLING].info.balance, U256::ONE, "the value moved"); +} + +/// A frame running as the beneficiary that switched access off is still refused its explicit reads +/// of its own account: `SELFBALANCE`, and `BALANCE` and `EXTCODESIZE` of `ADDRESS`. +#[test] +fn test_a_beneficiary_frame_with_access_off_is_refused_its_own_account() { + for (name, read) in [ + ("SELFBALANCE", &[SELFBALANCE][..]), + ("BALANCE", &[ADDRESS, BALANCE][..]), + ("EXTCODESIZE", &[ADDRESS, EXTCODESIZE][..]), + ] { + let beneficiary = disable(BytecodeBuilder::default()) + .append_many(read.iter().copied()) + .append_many([POP, STOP]) + .build(); + let parent = call_and_return_data(BytecodeBuilder::default(), BENEFICIARY); + let run = run(&[(PARENT, parent), (BENEFICIARY, beneficiary)]); + assert_eq!(refused_type(&run.output()), VolatileDataAccessType::Beneficiary, "{name}"); + } +} + +/// A `CREATE` or `CREATE2` whose created address is the block beneficiary loads that address's +/// account to decide the created account's state gas, and the load is no volatile read: it marks +/// nothing and sets no compute limit with access on, and is not refused with access off. The +/// creating frame then runs a wrapped read of non-volatile data, `SLOAD` of its own slot, which +/// commits nothing either. +#[test] +fn test_a_creation_at_the_beneficiary_is_no_read() { + const NONCE: u64 = 1; + for scheme in [CREATE, CREATE2] { + for switched_off in [false, true] { + let case = format!("{scheme:#04x}, access off: {switched_off}"); + let code = BytecodeBuilder::default(); + let code = if switched_off { disable(code) } else { code }; + let parent = log_status(create_empty(code, scheme, 0).append_many([PUSH0, SLOAD, POP])) + .stop() + .build(); + let created = created_address(PARENT, scheme, NONCE); + let db = system_db().account_code(PARENT, parent).account_nonce(PARENT, NONCE); + let block = BlockEnv { beneficiary: created, ..block() }; + let run = execute_in(db, call_tx_with_gas(PARENT, [], U256::ZERO, GAS_LIMIT), block); + assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); + assert_created(&run, created, 0, &case); + assert_eq!(run.accessed, VolatileDataAccess::empty(), "{case}"); + assert_eq!(run.limit, None, "{case}"); + } + } +} + /* ---------- 5. a refused read reads nothing ---------- */ /// A refused read records nothing and sets no compute limit: the block environment, the diff --git a/crates/mega-evm/tests/system/keyless/charges.rs b/crates/mega-evm/tests/system/keyless/charges.rs index 0817418b4..61c17f2d1 100644 --- a/crates/mega-evm/tests/system/keyless/charges.rs +++ b/crates/mega-evm/tests/system/keyless/charges.rs @@ -345,3 +345,53 @@ fn test_a_signer_that_sends_its_own_deployment_makes_no_record_of_its_own() { "sent by a relayer: the signer's nonce record too", ); } + +/// Records the reservoir each frame start hands its frame: the call's, then the creation's. +#[derive(Default)] +struct Reservoirs(Vec); + +impl + revm::Inspector, revm::interpreter::interpreter::EthInterpreter> + for Reservoirs +{ + fn call( + &mut self, + _: &mut MegaContext, + inputs: &mut revm::interpreter::CallInputs, + ) -> Option { + self.0.push(inputs.reservoir); + None + } + + fn create( + &mut self, + _: &mut MegaContext, + inputs: &mut revm::interpreter::CreateInputs, + ) -> Option { + self.0.push(inputs.reservoir()); + None + } +} + +/// The call, the transaction's own frame, takes the whole reservoir; the creation it starts takes +/// all but the call's 2 per cent of what the call has left once it paid for the creation's start — +/// the signer's account, the created account and the two records — as a `CREATE` opcode's child +/// does. +#[test] +fn test_the_creation_takes_the_reservoir_share_of_what_the_call_has_left() { + let deployment = Deployment::new(deploying(&runtime(RUNTIME_LEN))); + let data = deployment.call_data(LARGE_OVERRIDE); + let gas_limit = TX_GAS_LIMIT_CAP * 2; + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data.clone(), U256::ZERO); + tx.0.base.gas_limit = gas_limit; + let mut evm = MegaEvm::new(context(system_db())).with_inspector(Reservoirs::default()); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + assert_eq!(returned(&outcome).deployedAddress, deployment.address); + + let whole = gas_limit - TX_GAS_LIMIT_CAP - history(mega_evm::TX_BODY_SIZE + data.len() as u64); + let left = whole - + entry(GasId::new_account_state_gas()) - + entry(GasId::create_state_gas()) - + 2 * record(); + assert_eq!(evm.inspector().0, [whole, left - left * 2 / 100]); +} diff --git a/crates/mega-evm/tests/system/keyless/deploy.rs b/crates/mega-evm/tests/system/keyless/deploy.rs index 2fd93df66..9144638a0 100644 --- a/crates/mega-evm/tests/system/keyless/deploy.rs +++ b/crates/mega-evm/tests/system/keyless/deploy.rs @@ -884,20 +884,20 @@ fn test_a_deployment_carrying_value_logs_the_move() { } } -/// The transfer log is counted with the creation's start, before revm builds the creation and -/// moves the value: a creation whose budget holds its two records and not the log is stopped at -/// its start, alone, with the value unmoved and no log journaled — the debug build's check of -/// every frame start holds it to exactly that. The same deployment without value deploys under -/// the same limit. +/// The transfer log is counted with the creation's start: a creation whose budget holds its +/// record and not the log is stopped at its start, alone, before it runs, and its revert takes +/// back the value revm moved and the log it journaled. The same deployment without value deploys +/// under the same limit. #[test] fn test_a_creation_is_stopped_on_its_transfer_log_before_the_value_moves() { let with_value = Deployment::with_value(deploying(&runtime(1)), U256::from(7_777)); let without = Deployment::new(deploying(&runtime(1))); - // The creation gets 98% of what the call leaves: 235 bytes, room for its records' 80 and - // its byte of code, not for the log's 160 on top of the records. + // The creation gets 98% of the 200 bytes the call has: 196, room for the created account's + // record and its byte of code, not for the log's 160 on top of the record. The call keeps the + // signer's nonce record in what the creation leaves it. let limits = |deployment: &Deployment, gas_limit| { let body = reference(deployment.call_data(LARGE_OVERRIDE), gas_limit).usage.data_size; - EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 240) + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 200) }; for gas_limit in GAS_LIMITS { let stopped = run_with( @@ -926,3 +926,77 @@ fn test_a_creation_is_stopped_on_its_transfer_log_before_the_value_moves() { assert_eq!(returned(&deployed).deployedAddress, without.address, "at {gas_limit}"); } } + +/// A constructor that returns empty code for the deploy address is refused, unless it destroyed +/// the address in this transaction, and code a constructor returns is kept unless it destroyed the +/// address in this transaction: a destruction an earlier transaction on the same journal made — +/// two transactions run one after another without the journal finalized between them, as a block +/// builder runs them — is not this one. The constructor destroys its account while a probe address +/// is empty, and returns empty code, or one byte, otherwise. The first deployment destroys it; a +/// transfer then funds the probe; the same deployment again returns code for an account it did not +/// destroy: empty code is refused, so the deploy address is not created, and one byte is deployed. +#[test] +fn test_a_destruction_an_earlier_transaction_made_is_not_the_deployments() { + use revm::{ + bytecode::opcode::{BALANCE, ISZERO, JUMPDEST, JUMPI, SELFDESTRUCT}, + context::ContextTr, + ExecuteEvm, + }; + const PROBE: Address = address!("0x00000000000000000000000000000000000ba1a0"); + for returned in [0_u8, 1] { + // `PUSH20 probe; BALANCE; ISZERO; PUSH1 destroy; JUMPI; PUSH1 returned; PUSH0; RETURN; + // JUMPDEST` at 30, then the destruction. + let init = BytecodeBuilder::default() + .push_address(PROBE) + .append_many([BALANCE, ISZERO]) + .push_number(30_u8) + .append(JUMPI) + .push_number(returned) + .append_many([PUSH0, RETURN, JUMPDEST]) + .push_address(NOBODY) + .append(SELFDESTRUCT) + .build(); + assert_eq!(init[30], JUMPDEST); + let deployment = Deployment::new(init); + let mut evm = MegaEvm::new( + context(db_for(&deployment, U256::ZERO)) + .with_tx_runtime_limits(EvmTxRuntimeLimits::no_limits()), + ); + let deploy = |nonce| { + let data = deployment.call_data(LARGE_OVERRIDE); + let mut tx = call_tx(KEYLESS_DEPLOY_ADDRESS, data, U256::ZERO); + tx.0.base.nonce = nonce; + tx + }; + let first = ExecuteEvm::transact_one(&mut evm, deploy(0)).expect("valid"); + assert!(first.is_success(), "returning {returned}: {first:?}"); + assert!( + evm.ctx().journal_ref().state[&deployment.address].is_selfdestructed(), + "returning {returned}: the first deployment destroyed the account" + ); + let mut fund = call_tx(PROBE, Bytes::new(), U256::from(1)); + fund.0.base.nonce = 1; + assert!(ExecuteEvm::transact_one(&mut evm, fund).expect("valid").is_success()); + + let second = ExecuteEvm::transact_one(&mut evm, deploy(2)).expect("valid"); + let ExecutionResult::Success { output, .. } = &second else { panic!("{second:?}") }; + let ret = IKeylessDeploy::keylessDeployCall::abi_decode_returns(output.data()) + .expect("a keylessDeploy return"); + let state = ExecuteEvm::finalize(&mut evm); + let deployed = state.get(&deployment.address); + if returned == 0 { + assert_eq!( + decode_error_result(&ret.errorData), + Some(KeylessDeployError::EmptyCodeDeployed { gas_used: ret.gasUsed }), + "the empty code is refused" + ); + assert!( + deployed.is_none_or(|account| account.info.nonce == 0), + "the refused creation leaves the deploy address uncreated" + ); + } else { + assert_eq!(ret.deployedAddress, deployment.address, "the byte is deployed"); + assert!(deployed.is_some_and(|account| account.info.code_hash != KECCAK_EMPTY)); + } + } +} diff --git a/crates/mega-evm/tests/system/keyless/detention.rs b/crates/mega-evm/tests/system/keyless/detention.rs index f6afb2d1f..9ad75cd0e 100644 --- a/crates/mega-evm/tests/system/keyless/detention.rs +++ b/crates/mega-evm/tests/system/keyless/detention.rs @@ -667,17 +667,21 @@ fn test_a_deployment_another_limit_stops_keeps_the_reads_its_creation_made() { let prefix = BytecodeBuilder::default().append_many([TIMESTAMP, POP]).sstore(U256::ZERO, U256::ONE); let deployment = Deployment::new(constructor(&prefix.build_vec(), &runtime(1))); - // The body, the creation's two start records and the slot's record, one byte short. + // The body, the signer's nonce record, the created account's record and one byte: the + // creation's share of the 81 bytes the call has, 79, holds its start's record and not the + // slot's, and the call keeps the signer's record once the creation returned. let body = reference(deployment.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; - let limit = body + 3 * mega_evm::WRITE_RECORD_SIZE - 1; + let limit = body + 2 * mega_evm::WRITE_RECORD_SIZE + 1; for gas_limit in GAS_LIMITS { let run = run_both(&deployment, gas_limit, capped(CAP).with_tx_data_size_limit(limit)); let KeylessDeployError::ExecutionReverted { output, .. } = failure(&run.outcome) else { panic!("expected the creation's data-size stop, got {:?}", run.outcome.result); }; + // The creation's budget is 98% of what the call has, which the slot's record crosses. + let budget = (limit - body) * 98 / 100; assert_eq!( MegaLimitExceeded::abi_decode(&output).unwrap(), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }, ); assert_eq!(run.accessed, VolatileDataAccess::TIMESTAMP); assert!(run.limit.is_some()); diff --git a/crates/mega-evm/tests/system/keyless/differential.rs b/crates/mega-evm/tests/system/keyless/differential.rs index a0fff80aa..066a53282 100644 --- a/crates/mega-evm/tests/system/keyless/differential.rs +++ b/crates/mega-evm/tests/system/keyless/differential.rs @@ -215,7 +215,7 @@ impl Scenario { self.to, self.data.clone(), ); - render_system_call(result.map(|r| (r.result, r.state))) + render_system_call(result.map(|r| (r.result, r.state)), evm.ctx()) } else { render_outcome(evm.execute_transaction(self.tx())) }; @@ -230,7 +230,7 @@ impl Scenario { self.to, self.data.clone(), ); - render_system_call(result.map(|r| (r.result, r.state))) + render_system_call(result.map(|r| (r.result, r.state)), evm.ctx()) } else { render_outcome(evm.execute_transaction(self.tx())) }; @@ -540,6 +540,9 @@ fn scenarios() -> Vec { /* Limits. */ let data_size = Deployment::new(logging(2_000)); let body = reference(data_size.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; + // The call keeps 40 bytes for the signer's record, and the creation's share of them, 39, + // is one short of its start. + let small_body = reference(small.call_data(LARGE_OVERRIDE), GAS_LIMITS[0]).usage.data_size; let compute = Deployment::new(reads_then_burns(TIMESTAMP, 1_000)); for nonce in [0, 1] { let db = |d: &Deployment| system_db().account_nonce(d.signer, nonce); @@ -588,7 +591,7 @@ fn scenarios() -> Vec { &small, gas_limit, ) - .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(body + 40)), + .limits(EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(small_body + 40)), ); } all.push( @@ -956,6 +959,7 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: Default::default(), }) } @@ -1031,11 +1035,17 @@ fn render_outcome(outcome: Result( +/// A system call's result and state, and the reservoir it left, which its result does not carry. +fn render_system_call( result: Result<(R, EvmState), E>, + ctx: &MegaContext, ) -> String { match result { - Ok((result, state)) => format!("result: {result:?}\nstate:\n{}", render_state(&state)), + Ok((result, state)) => format!( + "result: {result:?}\nreservoir_remaining: {}\nstate:\n{}", + ctx.additional_limit().reservoir_remaining(), + render_state(&state) + ), Err(error) => format!("error: {error:?}\n"), } } diff --git a/crates/mega-evm/tests/system/keyless/frame.rs b/crates/mega-evm/tests/system/keyless/frame.rs index 780cdbfc2..88db12ced 100644 --- a/crates/mega-evm/tests/system/keyless/frame.rs +++ b/crates/mega-evm/tests/system/keyless/frame.rs @@ -47,14 +47,18 @@ fn call_frame(code: revm::state::Bytecode, data: Bytes, gas_limit: u64) -> Frame scheme: CallScheme::Call, is_static: false, charged_new_account_state_gas: false, + charged_start: Default::default(), + pool_shares: revm::interpreter::PoolAmounts::UNLIMITED, + history_allowance: 0, })), } } -/// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand: revm builds -/// it at depth 0; its first run starts the creation as its child, at depth 1, which revm builds -/// above it on the stack; the creation returns into it; and on its resume it answers in the ABI, -/// as the outermost frame. +/// The call is a frame on revm's stack, driven through revm's frame lifecycle by hand, as revm's +/// loop drives it, a frame's run result handed over before it returns: revm builds it at depth 0; +/// its first run starts the creation as its child, at depth 1, which revm builds above it on the +/// stack; the creation returns into it; and on its resume it answers in the ABI, as the outermost +/// frame. #[test] fn test_the_call_is_a_frame_on_revms_stack() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -85,17 +89,19 @@ fn test_the_call_is_a_frame_on_revms_stack() { }; assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(1), "above the call on the stack"); - let ItemOrResult::Result(created) = EvmTr::frame_run(&mut evm).unwrap() else { + let ItemOrResult::Result(mut created) = EvmTr::frame_run(&mut evm).unwrap() else { panic!("the creation runs to its end"); }; + EvmTr::frame_run_result(&mut evm, &mut created).unwrap(); assert!(matches!(&created, FrameResult::Create(outcome) if outcome.result.is_ok())); let returned = EvmTr::frame_return_result(&mut evm, created).unwrap(); assert!(returned.is_none(), "the creation returns into the call"); assert_eq!(EvmTr::frame_stack(&mut evm).index(), Some(0)); - let ItemOrResult::Result(answer) = EvmTr::frame_run(&mut evm).unwrap() else { + let ItemOrResult::Result(mut answer) = EvmTr::frame_run(&mut evm).unwrap() else { panic!("the call answers on its resume"); }; + EvmTr::frame_run_result(&mut evm, &mut answer).unwrap(); let answer = EvmTr::frame_return_result(&mut evm, answer).unwrap(); let Some(FrameResult::Call(outcome)) = answer else { panic!("the call is the outermost frame: {answer:?}"); diff --git a/crates/mega-evm/tests/system/keyless/inspector.rs b/crates/mega-evm/tests/system/keyless/inspector.rs index 554ac26eb..6e2a3a0ed 100644 --- a/crates/mega-evm/tests/system/keyless/inspector.rs +++ b/crates/mega-evm/tests/system/keyless/inspector.rs @@ -5,8 +5,8 @@ use alloy_sol_types::SolError; use mega_evm::{ - system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, LimitKind, - MegaLimitExceeded, WRITE_RECORD_SIZE, + system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, test_utils::BytecodeBuilder, EvmTxRuntimeLimits, + LimitKind, MegaLimitExceeded, WRITE_RECORD_SIZE, }; use revm::{ bytecode::opcode::{LOG0, PUSH0, REVERT}, @@ -75,6 +75,7 @@ impl Inspector, EthInterpreter> for Recorder { address: None, charged_create_state_gas: inputs.charged_create_state_gas(), charged_state_gas_address: inputs.charged_state_gas_address(), + charged_start: Default::default(), }) } @@ -182,12 +183,14 @@ fn test_a_failed_deployment_ends_as_a_revert_in_the_trace() { } /// An inspector that answers the creation itself — a tool's rewrite — starts no creation: the -/// signer's nonce is not spent, so neither its account nor the created one is charged, and the -/// call reports what the inspector answered. The transaction spends the overhead, the regular gas -/// the `CREATE` opcode charges whatever its frame does, and the reference's gas, and nothing -/// else. +/// signer's nonce is not spent, and the call reports what the inspector answered. The answer is +/// taken as given, as revm takes it: what the call was charged for the creation's start stays +/// charged — the history of the signer's nonce record and of the created account's record — and +/// no record is counted, the signer's nonce never having been bumped. The transaction spends the +/// overhead, the regular gas the `CREATE` opcode charges whatever its frame does, those two +/// records' history, and the reference's gas. #[test] -fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { +fn test_a_creation_an_inspector_answers_keeps_what_its_start_was_charged() { let deployment = Deployment::new(deploying(&runtime(1))); let opcode = KEYLESS_DEPLOY_OVERHEAD_GAS + create_regular(deploying(&runtime(1)).len()); for gas_limit in GAS_LIMITS { @@ -199,7 +202,7 @@ fn test_a_creation_an_inspector_answers_charges_nothing_it_did_not_start() { beyond(&outcome, &reference(deployment.call_data(LARGE_OVERRIDE), gas_limit)); assert_eq!( [total, regular, state, history_gas, history_bytes], - [opcode, opcode, 0, 0, 0], + [opcode + 2 * record(), opcode, 0, 2 * record(), 0], "at {gas_limit}", ); assert_eq!( @@ -385,10 +388,13 @@ fn test_a_revived_keyless_creation_a_limit_stopped_answers_address_mismatch() { let KeylessDeployError::ExecutionReverted { output, .. } = failure(&plain) else { panic!("the creation did not revert: {:?}", plain.result); }; + // The creation's budget: 98% of what the call has left, which the log crosses with the + // transaction's limit. + let budget = (limit - body) * 98 / 100; assert_eq!( MegaLimitExceeded::abi_decode(&output).expect("a limit stop"), - MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, - "at {gas_limit}: the constructor's log crossed the transaction's limit" + MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }, + "at {gas_limit}: the constructor's log crossed the creation's budget" ); assert_eq!(nonce(&plain, deployment.signer), 1, "the plain run spends the nonce"); @@ -418,3 +424,76 @@ fn test_an_inspector_sees_an_empty_code_deployment_end_as_a_revert() { assert_eq!(ends, [&end], "at {gas_limit}"); } } + +/// Halts the `keylessDeploy` call's frame whenever it is handed to the inspector, in +/// `initialize_interp` or in a `step`, and counts the times it was. +#[derive(Default)] +struct HaltsTheCall { + handed: usize, +} + +impl HaltsTheCall { + fn halt(&mut self, interp: &mut Interpreter) { + if interp.input.target_address == KEYLESS_DEPLOY_ADDRESS { + self.handed += 1; + interp.halt(InstructionResult::OutOfGas); + } + } +} + +impl Inspector, EthInterpreter> for HaltsTheCall { + fn initialize_interp( + &mut self, + interp: &mut Interpreter, + _: &mut MegaContext, + ) { + self.halt(interp); + } + + fn step(&mut self, interp: &mut Interpreter, _: &mut MegaContext) { + self.halt(interp); + } +} + +/// The actions the engine sets on the call's frame — the creation it starts, the answer once the +/// creation returned, and the stop of a call its creation's nonce record left over the frame's +/// budget — are the frame's own: revm hands a frame built with an action to no +/// `initialize_interp`, and returns an action set before a run without a `step`. So an inspector +/// that would halt the call's frame there is never handed it, and the run is the plain run, in a +/// debug build and a release build alike. +#[test] +fn test_an_inspector_that_would_halt_the_calls_frame_is_never_handed_it() { + let deployment = Deployment::new(deploying(&runtime(1))); + let over_the_budget = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39); + for gas_limit in GAS_LIMITS { + for limits in [None, Some(over_the_budget)] { + let case = format!("{limits:?} at {gas_limit}"); + let context = || match limits { + Some(limits) => context(system_db()).with_tx_runtime_limits(limits), + None => context(system_db()), + }; + let tx = keyless_tx(deployment.call_data(LARGE_OVERRIDE), gas_limit); + let plain = MegaEvm::new(context()).execute_transaction(tx.clone()).expect("valid"); + if limits.is_none() { + assert_eq!(returned(&plain).deployedAddress, deployment.address, "{case}"); + } else { + // The call's first action started its creation, which returned into it, leaving + // the call over its budget: the call returns the stop on its resume. + assert!(plain.limit_exceeded.is_some(), "{case}: the call returns the stop"); + let mut evm = MegaEvm::new(context()).with_inspector(Recorder::default()); + evm.execute_transaction(tx.clone()).expect("valid"); + let events = &evm.inspector().events; + let started = events.iter().any(|event| matches!(event, Event::Create(..))); + let returned = events.iter().any(|event| matches!(event, Event::CreateEnd(..))); + assert!(started && returned, "{case}: the creation started and returned"); + } + let mut evm = MegaEvm::new(context()).with_inspector(HaltsTheCall::default()); + let halted = evm.execute_transaction(tx).expect("valid"); + assert_eq!(evm.inspector().handed, 0, "{case}: the call's frame is never handed over"); + assert_eq!(halted.result_and_state, plain.result_and_state, "{case}"); + assert_eq!(halted.gas, plain.gas, "{case}"); + assert_eq!(halted.usage, plain.usage, "{case}"); + assert_eq!(halted.limit_exceeded, plain.limit_exceeded, "{case}"); + } + } +} diff --git a/crates/mega-evm/tests/system/keyless/limits.rs b/crates/mega-evm/tests/system/keyless/limits.rs index 90a8b9a40..8915a05ac 100644 --- a/crates/mega-evm/tests/system/keyless/limits.rs +++ b/crates/mega-evm/tests/system/keyless/limits.rs @@ -4,10 +4,10 @@ //! an ordinary creation is: its share of the data-size budget, the transaction's limits. A limit //! the creation crosses, its budget or the transaction's, reverts the creation alone, and the call //! answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start -//! wrote. A limit the call itself crosses — its budget, crossed by the nonce record a failed -//! creation leaves it — reverts the call with the stop, which takes back everything the deployment -//! wrote, the signer's nonce included, and the sender pays for what ran and gets the rest of its -//! gas and its reservoir back. +//! wrote. A limit the call itself crosses — its budget, or the transaction's limit, crossed by the +//! signer's nonce record, counted on the call once the creation returned — reverts the call with +//! the stop, which takes back everything the deployment wrote, the signer's nonce included, and the +//! sender pays for what ran and gets the rest of its gas and its reservoir back. //! //! The creation's stop is pinned as a column of the matrix: every limit a creation can cross, //! from a signer at nonce 0 and at nonce 1, below the execution cap and above it, with and without @@ -17,13 +17,14 @@ //! caller or to the sender: an answer built without a frame, the settlement of a stopped //! transaction, and the return of the frame's unspent gas. -use alloy_sol_types::SolError; +use alloy_sol_types::{SolCall, SolError}; use mega_evm::{ - constants::TX_GAS_LIMIT_CAP, system::keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, LimitCheck, - LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, + constants::TX_GAS_LIMIT_CAP, + system::{keyless::KEYLESS_DEPLOY_OVERHEAD_GAS, IOracle, ORACLE_CONTRACT_ADDRESS}, + LimitCheck, LimitKind, MegaLimitExceeded, LOG_BASE_SIZE, WRITE_RECORD_SIZE, }; use revm::{ - bytecode::opcode::{PUSH0, REVERT, TIMESTAMP}, + bytecode::opcode::{CALL, GAS, POP, PUSH0, REVERT, TIMESTAMP}, interpreter::{ interpreter::EthInterpreter, CallInputs, CallOutcome, CreateInputs, CreateOutcome, InstructionResult, @@ -105,8 +106,7 @@ fn assert_nothing_kept( assert_eq!(outcome.usage.write_records, 0, "{case}: no record is kept"); if gas_limit > TX_GAS_LIMIT_CAP { assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), + outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining, "{case}: the reservoir comes back", ); } @@ -124,7 +124,8 @@ fn test_a_deployment_crossing_its_data_size_budget_reverts_alone() { gas_limit, EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(1_000), ); - // The call's own lane gets the frame cap, and its creation 98% of that. + // The call's own pool gets the frame cap, and the creation 98% of it; the signer's nonce + // record is counted on the call once the creation returned. assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 980 }); assert_eq!(outcome.limit_exceeded, None); assert_eq!(nonce(&outcome, deployment.signer), 1); @@ -134,8 +135,8 @@ fn test_a_deployment_crossing_its_data_size_budget_reverts_alone() { /// The records the creation's start makes are held before the creation is built: a transaction /// limit that holds one record but not two stops the creation before its init code runs. The -/// start still bumps the signer's nonce, whose record the call keeps within the limit, and the -/// call answers the stop. +/// start still bumps the signer's nonce, whose record the call keeps within the limit once the +/// creation returned, and the call answers the stop. #[test] fn test_the_creations_start_crossing_the_limit_stops_the_creation() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -146,7 +147,9 @@ fn test_the_creations_start_crossing_the_limit_stops_the_creation() { gas_limit, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); - assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit }); + // The call has the one record's room, and the creation 98% of it, which its own record + // crosses. + assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 39 }); assert_eq!(outcome.limit_exceeded, None, "at {gas_limit}"); assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); assert_eq!( @@ -160,10 +163,10 @@ fn test_the_creations_start_crossing_the_limit_stops_the_creation() { } } -/// A failed creation leaves its creator's nonce record on the call's lane, which no check held it -/// to: a call whose budget cannot hold that record reverts alone with its own stop, and takes the -/// nonce back with it. The outcome names the call's budget, whose crossing produced the result of -/// the transaction's own frame. +/// A failed creation leaves its creator's nonce record to the call, counted on the call's pool +/// once the creation returned and held to the call's budget: a call whose budget cannot hold that +/// record reverts alone with its own stop, and takes the nonce back with it. The outcome names the +/// call's budget, whose crossing produced the result of the transaction's own frame. #[test] fn test_the_signers_record_can_put_the_call_over_its_budget() { let deployment = Deployment::new(deploying(&runtime(1))); @@ -188,6 +191,57 @@ fn test_the_signers_record_can_put_the_call_over_its_budget() { } } +/// The signer's nonce record is counted on the call once the creation returned, after the hint +/// the creation's constructor sent to the Oracle: the hint used what the transaction had left, and +/// the record crosses the transaction's limit, with room to spare in the call's budget. The call +/// reverts with that stop, which takes the whole deployment back; the hint stays counted. +#[test] +fn test_a_hint_the_creation_sent_leaves_the_signers_record_over_the_transaction_limit() { + let hint = Bytes::from( + IOracle::sendHintCall { topic: B256::repeat_byte(0x7a), data: Bytes::from(vec![0x5a; 64]) } + .abi_encode(), + ); + let hint_bytes = hint.len() as u64; + let prefix = mega_evm::test_utils::BytecodeBuilder::default() + .mstore(0, &hint) + .append_many([PUSH0, PUSH0]) + .push_number(hint_bytes) + .append_many([PUSH0, PUSH0]) + .push_address(ORACLE_CONTRACT_ADDRESS) + .append_many([GAS, CALL, POP]) + .build_vec(); + let deployment = Deployment::new(constructor(&prefix, &runtime(1))); + let body = body_bytes(&deployment); + // The created account's record, the hint and the deployed byte, and one byte short of the + // signer's record. + let limit = body + WRITE_RECORD_SIZE + hint_bytes + 1 + WRITE_RECORD_SIZE - 1; + for gas_limit in GAS_LIMITS { + let outcome = limited( + &deployment, + gas_limit, + EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), + ); + assert_eq!(stop(&outcome), MegaLimitExceeded { kind: 0, limit }, "at {gas_limit}"); + assert_eq!( + outcome.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::DataSize, + limit, + used: limit + 1, + frame_local: false, + }), + "at {gas_limit}: the transaction's limit, not the call's budget" + ); + assert_eq!(nonce(&outcome, deployment.signer), 0, "at {gas_limit}: the bump goes back"); + assert!( + code_hash(&outcome, deployment.address).is_none_or(|hash| hash == KECCAK_EMPTY), + "at {gas_limit}: no code is deployed" + ); + assert_eq!(outcome.usage.data_size, body + hint_bytes, "at {gas_limit}: the hint stays"); + assert_eq!(outcome.usage.write_records, 0, "at {gas_limit}"); + } +} + /// A failed creation by a signer at nonce 1 leaves no record on the call: its nonce bump is taken /// back, and the record with it. The same budget then holds the call, which answers with the /// creation's own stop, and the signer stays at 1. @@ -201,7 +255,8 @@ fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { gas_limit, EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39), ); - // The call's lane gets the frame cap, and its creation 98% of that. + // The call's pool gets the frame cap, and the creation 98% of it, 38, which its own + // record crosses. assert_eq!(creation_stop(&outcome), MegaLimitExceeded { kind: 0, limit: 38 }); assert_eq!(outcome.limit_exceeded, None); assert_eq!(nonce(&outcome, deployment.signer), 1, "at {gas_limit}"); @@ -209,6 +264,50 @@ fn test_a_failure_from_nonce_one_leaves_the_call_within_its_budget() { } } +/// Init code that fills the fresh slots `1..=slots` and deploys a one-byte runtime. +fn filling(slots: u64) -> Bytes { + let prefix = (1..=slots) + .fold(mega_evm::test_utils::BytecodeBuilder::default(), |code, slot| { + code.sstore(U256::from(slot), U256::from(1)) + }); + constructor(&prefix.build_vec(), &runtime(1)) +} + +/// A signer the creation's nonce bump creates is one account of state growth on the call, counted +/// with the signer's record once the creation returned, and the empty deploy address is the +/// creation's first rise against its share of what the call has left: under the spec's 1,000 the +/// creation gets `1,000 × 98 / 100` = 980. Under a limit of ten the creation gets 9, of which the +/// deploy address takes one: init code filling eight fresh slots deploys, the call keeping the +/// signer's account in the one it kept, and a ninth slot stops the creation, naming 9, which the +/// call answers, the signer's bump and its new account kept. A signer that exists adds nothing, +/// and its creation gets the same 9: the address and eight slots. +#[test] +fn test_a_new_signer_and_its_deploy_address_are_state_growth() { + assert_eq!(1_000 * 98 / 100, 980); + let limits = EvmTxRuntimeLimits::no_limits().with_tx_state_growth_limit(10); + let (fits, over) = (Deployment::new(filling(8)), Deployment::new(filling(9))); + for gas_limit in GAS_LIMITS { + let deployed = limited(&fits, gas_limit, limits); + assert_eq!(returned(&deployed).deployedAddress, fits.address, "at {gas_limit}"); + assert_eq!(deployed.usage.state_growth, 10, "at {gas_limit}: the signer, the address, 8"); + + let stopped = limited(&over, gas_limit, limits); + assert_eq!(creation_stop(&stopped), MegaLimitExceeded { kind: 3, limit: 9 }); + assert_eq!(stopped.limit_exceeded, None, "at {gas_limit}: the call answered"); + assert_eq!(nonce(&stopped, over.signer), 1, "at {gas_limit}"); + assert_eq!(stopped.usage.state_growth, 1, "at {gas_limit}: the signer's new account"); + + let existing = run_with( + system_db().account_balance(fits.signer, U256::from(1)), + fits.call_data(LARGE_OVERRIDE), + gas_limit, + limits, + ); + assert_eq!(returned(&existing).deployedAddress, fits.address, "at {gas_limit}"); + assert_eq!(existing.usage.state_growth, 9, "at {gas_limit}: the address and eight slots"); + } +} + /// A limit that holds the whole deployment lets it through. #[test] fn test_a_deployment_within_every_limit_deploys() { @@ -240,10 +339,7 @@ fn test_a_refusal_after_the_charges_gives_the_reservoir_back() { [total, regular, state, history_gas], [KEYLESS_DEPLOY_OVERHEAD_GAS, KEYLESS_DEPLOY_OVERHEAD_GAS, 0, 0] ); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), - ); + assert_eq!(outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining,); } /// And a call refused after the charges of the creation's start — the forward the `CREATE` @@ -281,10 +377,7 @@ fn test_a_refusal_after_the_creations_charges_gives_the_reservoir_back() { let [total, regular, state, history_gas, _] = beyond(&outcome, &reference); let kept = KEYLESS_DEPLOY_OVERHEAD_GAS + opcode; assert_eq!([total, regular, state, history_gas], [kept, kept, 0, 0]); - assert_eq!( - outcome.result.gas().reservoir_remaining(), - reference.result.gas().reservoir_remaining(), - ); + assert_eq!(outcome.gas.reservoir_remaining, reference.gas.reservoir_remaining,); } /// The call gets back what its creation did not spend, the same way whether the creation @@ -358,14 +451,17 @@ impl Crossing { let limits = EvmTxRuntimeLimits::no_limits(); match self { Self::DataSize => { - // The body, the two records of the creation's start and 100 bytes more; the - // constructor's log crosses with all its bytes. + // The body, the two records of the deployment's start and 100 bytes more; the + // constructor's log crosses with all its bytes the transaction's limit and the + // creation's budget, which the stop names: 98% of what the call has left, the + // signer's nonce record being counted on the call once the creation returned. let start = body_bytes(deployment) + 2 * WRITE_RECORD_SIZE; let limit = start + 100; - let used = start + LOG_BASE_SIZE + 2_000; + let budget = (limit - body_bytes(deployment)) * 98 / 100; + let used = WRITE_RECORD_SIZE + LOG_BASE_SIZE + 2_000; ( limits.with_tx_data_size_limit(limit), - Crossed::new(LimitKind::DataSize, limit, used), + Crossed::new(LimitKind::DataSize, budget, used), ) } Self::Compute => { @@ -487,7 +583,8 @@ fn test_every_limit_stops_a_deployment_from_either_nonce_at_either_tier() { let [_, regular, ..] = beyond(outcome, &reference); assert_eq!(regular, used, "{cell}: computed up to the charge that crossed"); } else { - assert!(outcome.usage.data_size <= limit, "{cell}: within the limit"); + let tx_limit = limits.tx_data_size_limit; + assert!(outcome.usage.data_size <= tx_limit, "{cell}: within the limit"); } } assert_eq!( diff --git a/crates/mega-evm/tests/system/keyless/rules.rs b/crates/mega-evm/tests/system/keyless/rules.rs index 52a5b414a..95e82d629 100644 --- a/crates/mega-evm/tests/system/keyless/rules.rs +++ b/crates/mega-evm/tests/system/keyless/rules.rs @@ -586,7 +586,7 @@ fn test_a_failure_from_nonce_one_keeps_no_record_of_the_signer() { #[test] fn test_every_way_a_deployment_from_nonce_one_fails_leaves_the_nonce_at_one() { let one = U256::ONE; - // The call's lane gets 39 bytes, and its creation 98% of that: less than its start's two + // The call's pool gets 39 bytes, and its creation 98% of that: less than its start's two // records. let a_share_short_of_the_start = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(39); let cases = [ diff --git a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap index d9448bd75..644a3fff0 100644 --- a/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap +++ b/crates/mega-evm/tests/system/keyless/snapshots/system__keyless__differential__keyless_differential_record.snap @@ -4,150 +4,150 @@ expression: "serde_json::json!({\n \"summary\":\n {\n \"cases\": ca --- { "cases": [ - "rule: value @ 50000000 | keccak256=0xb5a5ac86d1fae7f5e736ca81732ad3c9d376a7bbac67681509c8c11cad0fe21e", - "rule: value, arguments that do not decode @ 50000000 | keccak256=0x8cb374010ef32a5b928292a27304c9ff3df52dc6e29bb7dc3378cbea850ae292", - "rule: arguments that do not decode @ 50000000 | keccak256=0x4873273b34dd03636298cf421a82fa400e22c641ca56fea88d493e6d759c138c", - "rule: malformed transaction @ 50000000 | keccak256=0x8736f4dcd9908c3bd36c0b87bebef88fc498fb79c412e8710b84f624f5ef2304", - "rule: a trailing byte @ 50000000 | keccak256=0x6d63b733472ee70ca12153d130895554e40d3576812f5be0e881c43c152cd093", - "rule: not a creation @ 50000000 | keccak256=0x11925b46a5532a3c576d8a095b29b86cd873a33bbd523481641138a9296cd2c7", - "rule: not pre-EIP-155 @ 50000000 | keccak256=0x65165db7ef0c4d75c7d0db224328b34b50bdeb792624bf21212e55f4cd95dfe9", - "rule: signed at nonce 1 @ 50000000 | keccak256=0x8b7363b60e2b5e351baa81fca15777fb579647fa7754835a4f776da548966267", - "rule: override below the signed gas limit @ 50000000 | keccak256=0x4c688e0f80991bb11360110133e41549a0dedfafc587ab1b3b2646c1032fce5f", - "rule: invalid signature @ 50000000 | keccak256=0x336f5ea6b4275fc3d79318d8eb9a6d5f53efbb87115c458282fb25e34b8d7688", - "rule: signer nonce 2 @ 50000000 | keccak256=0x784863cbfebafe7f52b34279b301fefd3fe22a1d3a40d20a12f669a36efecc8f", - "rule: signer with code @ 50000000 | keccak256=0xdf3bde8c053f4f048fc1d3a40ed8c1700e056bc631adc33bf36a95663534f997", - "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0xc990151441bd899dd9a9c441f70e395ae898e580c2d23dc162b10f4da2e2ba21", - "rule: occupied address @ 50000000 | keccak256=0xfe77891e1596dfc0e17c6aa4b342d2d4e20ae2c8d7f30162ec01134fb186a432", - "rule: value the signer cannot fund @ 50000000 | keccak256=0xbdf2d161642260839f7abd86b915c550fb7981b53605cbc47de42824a8632915", - "deploys from nonce 0, empty signer @ 50000000 | keccak256=0x854194a30e818cbc3e9e62adbcd5e9e6a0892b7ff6f9cf8fc94496388e20f705", - "deploys from nonce 0, funded signer @ 50000000 | keccak256=0xaa0b7d00ffbb61a885bed9e69808248023f4d9cf6a527f94591e79ae8391f6ea", - "deploys from nonce 1 @ 50000000 | keccak256=0x1e38b97533ce81f692e2447bf2cc32a6469210d30e0a6ba5a04e2c81663ffb11", - "the address already has a balance @ 50000000 | keccak256=0x1c0f949828b4bc72f1baf27f0b744b9f15ccbe227fcce4ea5c59bbdcc3b827f4", - "moves value @ 50000000 | keccak256=0xd2beb5e62d347eba371882f82a4e30318fbbc9d43b0e57df063b9049f53bebf7", - "moves value from nonce 1 @ 50000000 | keccak256=0x0bdc41e79d10e1e4ea7b68f35e5556790d45cda9551f6761707bef4496d94e59", - "the CREATE2 factory @ 50000000 | keccak256=0xb2ecb5cf3ea5d5fbaaf3fce280431d390fe86795538c8ad1fff617dde998e5b4", - "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x3ad22e63f14ded44a13f1e15bab3451f03d9c6fc4e33ade9a66d08626f29b75e", - "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x8909f08d1f86bb0af70c417b964ba8d79ff369bcb3558c6a84f232989e64fd46", - "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xdd4a8355d943e2f22af2fdec3c38e37c5dd7ddc63613c0d9e72b500b61136807", - "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x1df27a735363f4758e4bd567ffd2cde36f7f9f7f88b088a763f2dea01d3985f2", - "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xb80e17a2e7939e95262c7efb0f7809a708c46f9ffbacc61bb7012b9228e06cba", - "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x25606317ab5eba31abfcbc5f24421a37e94aed0e04e53ed4edda18bfb18d2df7", - "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x27077cb99c3f49dcf9c6f9041fe2ffb1b26437a31a32b82807c9a3411c9c2efe", - "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x17c7152fe5947693070eb1627f4f858975b5403cce1e0ae07ba25e3a292f6475", - "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x265bc4dd1e96384237e9b90cebd4be1d68f3a8f7b6a6607804bebca25894f552", - "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x751a90caf62483d4706d2367d403f1c9d793cc3d12ed41ab96f2098459986690", - "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x9c37a4c741b5dbecdec991084171b2f36a07aa8dd1ebea9f6568a0359c927917", - "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x2ec59b5a0ebe01e93f5d791d951f2cf0149ca9fbfa30aa14534ce3a2226117f7", - "a constructor out of gas @ 50000000 | keccak256=0xbbeb48fca5fe19e74924ea6bfd705899920f01410ebb67f8ce64cd0c0baae4a7", - "the signer sends it @ 50000000 | keccak256=0xf4e163092bc6483934a37e6069b79be53cba1090721dfa1c4b783db7c8f78a9d", - "the signer sends it, and it reverts @ 50000000 | keccak256=0x57ef3326c672cfbe88fc9e7828a9e7d8deba35e2876b18153b2f6429ff165660", - "a delegated signer @ 50000000 | keccak256=0x0064a10239803109ee59bd0d16911f7decf55a346d05d57e18dce03e84fa99d0", - "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xcd8b9ea08cc5d3e4877320057b96181c0483eaa28d99f08469468b15ea5d3d59", - "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x7c33d51d018dd7be35a4727c89a401d5d07ee0ff1712cf4a04fe3a660d95d800", - "limit: tx data size, nonce 0 @ 50000000 | keccak256=0x55a77222c7212b63b30697325a075db2bcb1e0d3a290678eeaa96927a5422db3", - "limit: compute, nonce 0 @ 50000000 | keccak256=0xb60e1f212cff27717b50251f22920f60a266d67387cffb4886d9bf1097bdadff", - "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x9e2e2b613e18eabd9a69df5ddd3204e0f8d663621abcedef4e8367f0db09baa9", - "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x6c591038e8021803ab4a3f338e45878adf3917f1345899376d715e746d8d2f64", - "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x92c4b677efbf06476c5b9c9aa7e85e4cf3923af232d571eb6664ecd6fb7476a6", - "limit: tx data size, nonce 1 @ 50000000 | keccak256=0x4286eada20e5f558e7c2ed6c826d15fdb4d3d50186e43da02a4d77655b7a4cd1", - "limit: compute, nonce 1 @ 50000000 | keccak256=0x2d65b3a7fdb37ae17b12ab3c9b9dec67fd93bf92b365d1b86b26a3bebff461ea", - "limit: frame data size, nonce 1 @ 50000000 | keccak256=0xf7a1feafa45b6895ff67602578ba339bf8e037bade29b6271e67d2e1797e3782", - "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x8800b8030288909004fea33f41c96fc7c97e77342c75d3c1b51dcae69390d796", - "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0xdf3dbf511f3df59eaa39d299e5d2cb0a80712cbf8ab0ad577f4dffe6f1cea31d", + "rule: value @ 50000000 | keccak256=0xbbb1a321fa8fabf8d27760616c768bf9f2a0d5649438373c76fc4348d88cfb8a", + "rule: value, arguments that do not decode @ 50000000 | keccak256=0xc3ab1c1af149f2cbe5733aeac1c9cdb42eadc2b47e270a5b721b14eed20c410a", + "rule: arguments that do not decode @ 50000000 | keccak256=0xb0db489839a78c2e662f000d2220ddeef36e06c5a473eceaaccf3e0866dc53d8", + "rule: malformed transaction @ 50000000 | keccak256=0xba96cfe68c780d656f805049a752b68a4049a7c1ef502eccefb3f6c6ca81e8f8", + "rule: a trailing byte @ 50000000 | keccak256=0x5c624cfbbeb559e89cd58716f98111cb2d4f07902c8e71d9df478997c0a84619", + "rule: not a creation @ 50000000 | keccak256=0x0386ff909ab7ea665c8b7c11d8181445da53b91efdc2c2941b6533036e92dc3b", + "rule: not pre-EIP-155 @ 50000000 | keccak256=0xc9a0492b8f7f17629e2ebd8bebf7acff541dbf9458a9e262e147cfdaad714b52", + "rule: signed at nonce 1 @ 50000000 | keccak256=0x84315464c623f5cbc5ee897e2bc8bfd119ad900e123143ac721555e0c2e3a3e1", + "rule: override below the signed gas limit @ 50000000 | keccak256=0xc00f787f6cae8873132a89f2038212b36ee02270d3410df38338adcfad75f6ee", + "rule: invalid signature @ 50000000 | keccak256=0x0123d8ec66253bfee2c311b216a5d9f19cb3c15457dd4b99aba8678431cb3303", + "rule: signer nonce 2 @ 50000000 | keccak256=0x74f3e6b4e5ffc6831d4f2322f91a596707fd1887699f43e9f811f2645a0ba3da", + "rule: signer with code @ 50000000 | keccak256=0xc43364d930583df0460bc9dd42d3cc23386abba568218a3b5db7a8d530bf78bd", + "rule: signer with code, EIP-3607 off @ 50000000 | keccak256=0x7e885926e896aac59f698ae640a0a2e6777938661d0f2a7cf7e12d3b1e3ecf00", + "rule: occupied address @ 50000000 | keccak256=0x34719a7157d75c75a400db9d1dde3c03682120e583f3392ec8b1ee36be0613ec", + "rule: value the signer cannot fund @ 50000000 | keccak256=0x199eb3f0514dc7eb89d00b814e9be6ec96147ceb2614753a0e25b762024434be", + "deploys from nonce 0, empty signer @ 50000000 | keccak256=0xa1fcdd4a0bbf7c9c08985315582f9c4c31a37525c5e6f08e2bb045066c2d16b3", + "deploys from nonce 0, funded signer @ 50000000 | keccak256=0x0bf902ac6bebbd9e81996c57e45f893937320dcfb1fa92223d246e9cacae047f", + "deploys from nonce 1 @ 50000000 | keccak256=0xa520227afa0779933441e9c8d0a81b82d5d4796763a0deaec2db7543baf413d4", + "the address already has a balance @ 50000000 | keccak256=0x854e5d67d0b3ae6d8eb7cd5e516475df2baf36301993404093da7e2c78e2aea4", + "moves value @ 50000000 | keccak256=0xe68adf4ea6323e5e85daf9baa8f674dd6780d7c5e09aeea5f6aa950f25135522", + "moves value from nonce 1 @ 50000000 | keccak256=0xbd4dd91295040091c9daa24f413d6c9dac7987ab302fb756f51523feed7c0f69", + "the CREATE2 factory @ 50000000 | keccak256=0xa4eb75201156746b64933d762f2578d85eec1b973fd8f44a27f1a9b82b1fac56", + "a constructor that reverts, nonce 0 @ 50000000 | keccak256=0x814369e9694895a04efcdf10e46d291f77debf3360a7da90f162fbd8ff8b3f81", + "a constructor that reverts, nonce 1 @ 50000000 | keccak256=0x04c1ef35d5661cd9e663bfef971e77257290c620ff0b02ec2a7240ecda007306", + "a constructor that halts, nonce 0 @ 50000000 | keccak256=0xbb72f34db268a2e3887ed09e962acd0594acbdaaa38c886d46fa16b4a9f5a24c", + "a constructor that halts, nonce 1 @ 50000000 | keccak256=0x26959ab40d300c7c80e74399f2cd52a8104f2c8d2df3f2187868e28318a425c9", + "a constructor that logs, nonce 0 @ 50000000 | keccak256=0xc4b37379e510c216a96aaf24979d06e3be3a2fc3a03d6538bf9253fb8e452639", + "a constructor that logs, nonce 1 @ 50000000 | keccak256=0x064dd785d29f0bc752281e4bbce7c180d4d7914bde6eee54f59deac6d4839b91", + "a constructor that writes a slot, nonce 0 @ 50000000 | keccak256=0x5708cede78495e8a958a94377f3e5fbdb437a9a36b5e5b2572cfc3c2a619f1c1", + "a constructor that writes a slot, nonce 1 @ 50000000 | keccak256=0x74c1faf2ea41ef8023efd520ef2a149617e919657d26a3a67f866bf2e99a40d4", + "a constructor that deploys nothing, nonce 0 @ 50000000 | keccak256=0x2ed3583f5a9b25f68e6a68771ed8715b836135a3ce6e7351c0031adbd43ddd46", + "a constructor that deploys nothing, nonce 1 @ 50000000 | keccak256=0x1ddb229bdc98071111d5a644e98a5e3402c89e440056044b50e42d5bb1c98546", + "a constructor that destroys itself, nonce 0 @ 50000000 | keccak256=0x6abf2671730921222c7e0486fc58421a29c3b286f2075c6312bbca64a352a656", + "a constructor that destroys itself, nonce 1 @ 50000000 | keccak256=0x54c19083cb9b9253786f583e80007a9c467a2e1783e3e4dd4aabfb7f456b0829", + "a constructor out of gas @ 50000000 | keccak256=0xed4e182648a6a0eeb5f61018a3eaca23a60974f3a6167f31218ac538280726bf", + "the signer sends it @ 50000000 | keccak256=0x0ced203a45283f8624433c0835beec78f12792ddf7e92d2f12fea1cddea5560a", + "the signer sends it, and it reverts @ 50000000 | keccak256=0xe5713953532d5bc302ea6160476e728624ca3af937bd6e89fc8553f89f9ff2dd", + "a delegated signer @ 50000000 | keccak256=0x38d2ce3b0bb3da4d31d02be4e87013cf7daf22ffc487562e464dc7d41256dcd7", + "a delegated signer spending nonces, deploys @ 50000000 | keccak256=0xf4d03fbc577835fcd11e7288e0cc4d2ed642d48738d44ff0c8280e768598c35d", + "a delegated signer spending nonces, reverts @ 50000000 | keccak256=0x35e254125b51703420e8deb970c97aa8074627918996d8e97bc5671b524e674f", + "limit: tx data size, nonce 0 @ 50000000 | keccak256=0xbe19e2acd0ee697fc43ab05cd0cc9ecada8e8d700b158fda10ec6f6bc5c1e53c", + "limit: compute, nonce 0 @ 50000000 | keccak256=0x2944b7d9bf52ea422166c67d00937280a9ee1c88958fdb4b119298455cc6e82f", + "limit: frame data size, nonce 0 @ 50000000 | keccak256=0x797de99052c6684ca98831510e1746166d2a9dfc6939e65a04d79705c6fac121", + "limit: the call's budget, nonce 0 @ 50000000 | keccak256=0x5451cb823c7026bf7cd782549d118c84c8fadc0b2b0791aad17ea04640b873c2", + "limit: the creation's start, nonce 0 @ 50000000 | keccak256=0x4e3a6609240565a3b8f9ec0278c29e08a15dac083bc70c93cec71dc5b2d4a284", + "limit: tx data size, nonce 1 @ 50000000 | keccak256=0xb4a3e25c6b0253329363c075ad24f7810fa574d9c6b4abf47cfedcd463aa7df8", + "limit: compute, nonce 1 @ 50000000 | keccak256=0x45b1d087eaecc7df26d766ec791eef23560c46269e58faeaf131758e7af705a7", + "limit: frame data size, nonce 1 @ 50000000 | keccak256=0x5845d201af918e1750abfcd4332f0dccae77c77944db18976357cbd43029fffd", + "limit: the call's budget, nonce 1 @ 50000000 | keccak256=0x4ca715d952d52d966160cd70482e6dec9d55396b808afecf01b76f7bb9e6815c", + "limit: the creation's start, nonce 1 @ 50000000 | keccak256=0x769a1fa287ccaebe0944d36d9405909abf987c3260d54922249afb4684096b41", "limit: a body over the limit @ 50000000 | keccak256=0x1a1a367883ad87b2e98ef4e1668bc5d864bd83390282c6d5361e2dfdac20d255", - "limit: the default limits @ 50000000 | keccak256=0x401e8a4d34c0a257a9f6d5eb3c191ef9e04259932d15df8f69ef9d284c44597d", - "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x67d17bdcceef5522f067097fb8b5bb9535b7e3c50edfc735b7a17281baa83a79", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xee5119ad3ae3a1ed755fa53d53e1dce456fb500e2142cb3ab4cddbc6c5ef2a93", - "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0xd36808e24a3e4424b5c1983330c2b072a37aadd913bb8f7bfc6f40a93c7aa762", - "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0xee6c92b0634bb05ad67f16e49fbee64807792ed5210108bb7227a6e0a44c52ea", - "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0xda6467b28250e76945cd72fb1c61e87e4ff082c572e77c699398a8986702ecb1", - "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0x476ebf8d0d9b175a438951231459d7eff3e3d4cff678fdf874926c58c66e1103", - "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x30e7f681371492a39eb7b8cce401b2d3305ac108573b9b31904caf0d84c45172", - "not dispatched: version() @ 50000000 | keccak256=0x1bcdfb0c443aedd9aa2dc040e14363bb98e50e81a143c794ed140aa08997127a", - "not dispatched: no selector @ 50000000 | keccak256=0x472f5c2dcd74cee319c67289882d7ae5de0827e9ab51e3189cc994f9030a8c41", - "not dispatched: from a contract @ 50000000 | keccak256=0x1c294e98bc947c88900950d97d417766b82b79a0730db66c83325f049a72e59c", - "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x82ece1017f1c33999f1543b189848287c03fafd8abab52e663bde37910d48caf", - "no contract code @ 50000000 | keccak256=0x61a84ade88a26edc2149aadbdff8cf04d12724cff24b5177848f93ef00e41e53", - "a system call @ 50000000 | keccak256=0xa0f9654dc5d720d585bd5262f59c3eb57dfc5e0a2e2cfbb4a4d4195d1bb8e582", - "rule: value @ 400000000 | keccak256=0xd303c37d1d7da78c74d1a96a932bcb273b9fdc308308f4006413974f816f1061", - "rule: value, arguments that do not decode @ 400000000 | keccak256=0x90ac683d459875174607b7de159993d754ffbfff2d1bde2f45327e31eff58a30", - "rule: arguments that do not decode @ 400000000 | keccak256=0xc2291f0a80a04b8650aee76c9bd25d4efb87a1197f98e511fb254121d900eb1a", - "rule: malformed transaction @ 400000000 | keccak256=0x483bd928fe503c1c518a50616f83f71abf2e5cb62bfde657f3bb76f422c690c1", - "rule: a trailing byte @ 400000000 | keccak256=0xf2f566ffc210e9e80e3d61f995cb7fbe4aeb13753a717e637754e5f586dd28e7", - "rule: not a creation @ 400000000 | keccak256=0x51107b2d6b41035c93f36a9473aaf257606f435d3e4309f399308a140654e8a5", - "rule: not pre-EIP-155 @ 400000000 | keccak256=0x4ebf62eef276a4b331f8a06f51dea3fd8498df29aa0f4601e45378917ac30b4e", - "rule: signed at nonce 1 @ 400000000 | keccak256=0xe52fdae23846ea20448d0f1718077ac94f32b9974fd0a7715a19bde74255eeae", - "rule: override below the signed gas limit @ 400000000 | keccak256=0x90e4f5261d501523f740ccc40dd40eb30e9e5b7f89cc7e14e9f27cba2f1b9a37", - "rule: invalid signature @ 400000000 | keccak256=0x520a8ea364be745edac070d2b7647b72009651c15cc92c89f31e7275d92b5890", - "rule: signer nonce 2 @ 400000000 | keccak256=0xbd17b75de1e42505f2ee5082ccc16a3311baa780b8692a84d77ceec24b4b893e", - "rule: signer with code @ 400000000 | keccak256=0xec1da80a88bfab4fd9508199c44446a7a2712b502e2e01c249836b10e5d0c7e4", - "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0xf194b8d24aff31661c0ab3bd59a18f006b92ce704683ad7237294a2bd7c7e423", - "rule: occupied address @ 400000000 | keccak256=0xbdc9f465f12c2e0f064ee17721cb8b7124e5bd348daf8ff08488ea72aee8df01", - "rule: value the signer cannot fund @ 400000000 | keccak256=0x1e190910f68843e409de4da0c031f3c1e29b9bbb9310b781891c55b1cad48b6a", - "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x404d2ce242ff28ee98306359e5ad4b216e74387e803f08a5803d3c47aa0ae764", - "deploys from nonce 0, funded signer @ 400000000 | keccak256=0xaa02134b6ab8240d6425e5e3ee34b4d035790c4d78995cc721001941564afcb5", - "deploys from nonce 1 @ 400000000 | keccak256=0x8b1ccbd6d099d0e1b1371aec903a117c33a2a3b398a355098ab4a37e239d2102", - "the address already has a balance @ 400000000 | keccak256=0x23b1e10d7f6d8135f85779bdaa1ee01943b79b711810cbcf2355dce52626cfb8", - "moves value @ 400000000 | keccak256=0x92c5f7758579e2ea93bd39c77e516e03476c6c66eb65aac6c31ccc79bf0d5881", - "moves value from nonce 1 @ 400000000 | keccak256=0x8d87dc75052ef30e13e395be1b673b7a874f843c85bfd0bf8c33ebc09188827c", - "the CREATE2 factory @ 400000000 | keccak256=0xddc26d1ec888e72def99e14f179859577a6d5c263db65710414136b00f784636", - "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0xcbf6d3addfc90a9b82ef149891785585747b23b84e6e6feea48408c0927b05fb", - "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x4e8ae911031010a24c172fd27a23a45e572301e31d8e3942c9b78958fc1c812b", - "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x11d6d8106eec4144fb4b27aa8048e61ebd3e28ff5e34a3ab258e58870c2029be", - "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x58da2c85e1b4aed114d883890f022c19bc6ab5306bf321d91499d43bc74fe1ee", - "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xe0964b9f5609b93ab45e0fb18d0d641dc29de37d524eb743b5010334d5789fce", - "a constructor that logs, nonce 1 @ 400000000 | keccak256=0xf652556af0037df5691da20eda38055aed1ab41a0ad98fae98979bbe4e1c165c", - "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x6c0ecb273aac09d6ad165e7b627ef64bd9df6fc70e6e82c353dc440d5c96b8f7", - "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0x7a3b943b6d397f733c8cbf3f4434feae3b84079f10aa6fd9ee7b2873aad76b19", - "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x95d24bcd22a84c68dffab292724f1e7c796a6b75c3df83e538bf81323747ef75", - "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0x433ce029fff43e9d2a3293c22c889d4f1daff43d301460404e24bd71f846cba9", - "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0xf873d861f34095986d68362bd6931829e01d2ec3ce8e4db6fdb888ad786ddd64", - "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0xe982dd88cd68a044a422609dc8934c114c048189a82860d730ac0334256c82cd", - "a constructor out of gas @ 400000000 | keccak256=0x27652b56760f6fcf1213bc170730a622ecb6c8c7fcc4269ee80d62304eb79f4a", - "the signer sends it @ 400000000 | keccak256=0xd78efd6fd17a7921cee7edcefbf4049630fc2fe902c65969f3e2e1d10db65c10", - "the signer sends it, and it reverts @ 400000000 | keccak256=0xfadd6b105b17e3e8173859cc7ea6e21f3058d66859c3f772e8b993e6022f035c", - "a delegated signer @ 400000000 | keccak256=0x75dcb0c5b12fcfdc2ec9d5fb412f2a356d2b6b4c08498f592cb77d695f24fade", - "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0x912a471ac573f1137c7ff715bbd4c716d896290ea34c38918f341dd5bd4fcd7c", - "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0xd7cb0a921f3295e113674bc4766d4d1c846e169fe1aeb479f30060b613904a68", - "limit: tx data size, nonce 0 @ 400000000 | keccak256=0x34226a40534a6d1a5db718843ddf4ed03dd8e88c2dc532a9d1277a908efbaf17", - "limit: compute, nonce 0 @ 400000000 | keccak256=0x220083af3453245d7157fce25daf5ae7b146135fe68a4e67fb957b3081ae5f1f", - "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfe881a80d9f1ea7971209d7555df06b46c5657581f03b17ba771a2c62a2c0875", - "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0x1b9c5fa7ce5f8c7720eb855681d2ce4c242161487366162aa11f92a0fe795f0f", - "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ae6445d4fc7034526b72b03f278548083826e5f864ea499fca9a38c8fba127c", - "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x5adb3dfbb10b12745e6ae864bd4b245ba9a18b438615f6d5f3caa277aeb78f99", - "limit: compute, nonce 1 @ 400000000 | keccak256=0x1730186a0ab9121039c156b8c1aaa81326de8a4169a409783d8960467ca16a6f", - "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x713d112b4aac78b020780ba0f2d604f45ea2e2f35eccb200ff28cedca809939c", - "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xae24e0359fe82a35095090953c820f194176cb9312f8f0c76d0a3e9b2d310747", - "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0x9891361cdbebda97af570c4a61f0857a55e8696f1707c5a7df546895ab4a0476", + "limit: the default limits @ 50000000 | keccak256=0xb9b6a4f4f4da4ff07d70af782977146943836dd091c23bbe9c4ed7a9e4bb9f27", + "detention: a signer that is the beneficiary @ 50000000 | keccak256=0x23ee0068e75b5a67d97e1a45bc5f5b66e34c2dc8798fa9e752a11080bee93dc1", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 50000000 | keccak256=0xdd925caae45fadd96556e1d7f018b1d83045ad2734d2f4f525a5f911a00975e0", + "detention: the sender is the beneficiary, below the overhead @ 50000000 | keccak256=0x40a829bd5cb26d43f18f3b177e051c1387857cd7265a7440e5a4fae346a31cc8", + "detention: the sender is the beneficiary, cap 60000 @ 50000000 | keccak256=0x56f60b8f8bc96d3815e7a120f09fe74d1cbc3c85cb4d80a5886b98f4a6158122", + "detention: the sender is the beneficiary, cap 150000 @ 50000000 | keccak256=0x2abbe75645d93afdbcc7687b6c0afc479613f57afbe28463f223273e683bbee5", + "detention: the sender is the beneficiary, cap 400000 @ 50000000 | keccak256=0xf279c5307fac715d603ebbe9b8c74aa223c5594b798abb3de195e0cb23ae6bd5", + "detention: a constructor that reads, within the cap @ 50000000 | keccak256=0x92e09638ad6a4e0af87f695337f3aafd6fa9196da822f38cdfbbebc7e0a0c39c", + "not dispatched: version() @ 50000000 | keccak256=0x7c5ee96f08957b0fd43ec3609c12cef5bd0074792d595a9f1ea971ca31fd7875", + "not dispatched: no selector @ 50000000 | keccak256=0xc0be8244d5572b8b9fb9ad4d4c4e0db85d8ffca5002f37279b9c52ddc3fa5b02", + "not dispatched: from a contract @ 50000000 | keccak256=0xa0f75061e50b6327aaadf92e71f9af22665b274ea379aa98bf396b8e08071d20", + "not dispatched: a STATICCALL from a contract @ 50000000 | keccak256=0x268116d81aba3d36b1bfd0f3473a60adf58644ac1dfc8886a2fb0224bd4aa82b", + "no contract code @ 50000000 | keccak256=0x253953af0211838296cd30ba77a533ea7798a45b1c5accd1a2b739e290605d47", + "a system call @ 50000000 | keccak256=0x4ff198380163db3fd96b41cac5955f3c4723a559398265bfb2b32405dd00edc2", + "rule: value @ 400000000 | keccak256=0xa18ebeca543b35b95bcd4fd93a0679cdd9486f1d1c8d0feef804ffc1b9ad4d0f", + "rule: value, arguments that do not decode @ 400000000 | keccak256=0xf986d1cac4109cbb2466259d2110ea80ce1f4de09f3fa2038a51d0f81b4384ae", + "rule: arguments that do not decode @ 400000000 | keccak256=0xeba2668832f3afd0ee12d3a70f506e50ff8c491017c079245bde2181c8c8ba98", + "rule: malformed transaction @ 400000000 | keccak256=0x287361e49cc3a3985b31a7c25a558074861a227e9bbe7643190c426e20720289", + "rule: a trailing byte @ 400000000 | keccak256=0x77cf0ce7ea670c10f24127fc9549928877d70bff052f8b82cdb36829865a65cb", + "rule: not a creation @ 400000000 | keccak256=0x41e892cdfdf1964cfe253027160234eafc5cd532e42ac66d851015a220436675", + "rule: not pre-EIP-155 @ 400000000 | keccak256=0xb8772e8dabb39783785b7999e3c138ead3904b9f5efffe173c44a809b34ccc40", + "rule: signed at nonce 1 @ 400000000 | keccak256=0x302873560dce8cb91d53397f6189cc657823d918512e98c299fdb45b3a9327d3", + "rule: override below the signed gas limit @ 400000000 | keccak256=0x2fd5a2d895fd1dbbf20d73eee0c2e29eebaec2e6476f5d9bc4b614e4f9b3137c", + "rule: invalid signature @ 400000000 | keccak256=0x491f9c8eb64f398c3399171c286cd7db7d01c23e0f256dba72dc36d7b91cfc4f", + "rule: signer nonce 2 @ 400000000 | keccak256=0x91cd17bd5232587c10bc61fec1446a8058a5399723976f4b0af1745ddffd22b1", + "rule: signer with code @ 400000000 | keccak256=0x1a75998f8e5a2654da4b90af611fdc21e4a0b21b3bb7ccec1c3c41066b180eb9", + "rule: signer with code, EIP-3607 off @ 400000000 | keccak256=0x282c1e56d00c8e98ddf030dee7c443ed146bd37bd1950b38fc37a9925eea5a7f", + "rule: occupied address @ 400000000 | keccak256=0x173768aec05d99a3b4f2f8a514bc8189f1f0d699d6ccda32e8ea14238c3228b6", + "rule: value the signer cannot fund @ 400000000 | keccak256=0x496e2dc7b600882979349caf494d574a55f4ca03435079b95e932d84006116b3", + "deploys from nonce 0, empty signer @ 400000000 | keccak256=0x3e2c83f410dee0ba6ba3907641250811618c539150ff18370b00c084bbd718a3", + "deploys from nonce 0, funded signer @ 400000000 | keccak256=0x5008280aa7bf2ecdbcf76ed8d79a74798b58628b93a03683b15979440fd953fc", + "deploys from nonce 1 @ 400000000 | keccak256=0x62aa872f3858800f4ea40b9d1a956f89c3cf8bd3ad7fc22f872c823e8a3c0cfb", + "the address already has a balance @ 400000000 | keccak256=0x3b5b6e733d25fae001d95c053553c30a3e557099851432da7f24b5d9dcc98fa2", + "moves value @ 400000000 | keccak256=0xccd0aaf8e8333f0651d6846a9caff6d2a7561e9545d7db98afe7fb41b162fc85", + "moves value from nonce 1 @ 400000000 | keccak256=0x97de89df5cb3776fab2e0dbc5c8ac479326d7b0413780c9650a9583d376b6b71", + "the CREATE2 factory @ 400000000 | keccak256=0xf2a19245595181d80dc2652cedcd2b6bc2e56a2aa6e0374b8f03490012b0d723", + "a constructor that reverts, nonce 0 @ 400000000 | keccak256=0x4d0e173f5592e65112162b83dd01c4bed23f58304b289aeb7f0a6f0ab86e795d", + "a constructor that reverts, nonce 1 @ 400000000 | keccak256=0x1ec883ee368ed36093aba984eac350045b962d2e6ee6b4b635e0a901f79426c0", + "a constructor that halts, nonce 0 @ 400000000 | keccak256=0x1e3d2de4feb46b93cb142d18a19732fa0f82c41ad5d7e313b76eabcbc5eca33d", + "a constructor that halts, nonce 1 @ 400000000 | keccak256=0x94e3351af11a471277dd64ad107ca6afe43192ed20a0bdfb4a226dbb673cf37a", + "a constructor that logs, nonce 0 @ 400000000 | keccak256=0xf070389fce7571465c57ab2c64a99bf68a33c60afd6cb1f80229e1b07495193d", + "a constructor that logs, nonce 1 @ 400000000 | keccak256=0x690f7ae1f153f7b29374fee5e68181039f1372b68fa9df80931a17dc28e6cef3", + "a constructor that writes a slot, nonce 0 @ 400000000 | keccak256=0x3817844eb1ece2cbc97c7b6b7ecbdb1e543ce3bbc098431dbd45db3682c70f82", + "a constructor that writes a slot, nonce 1 @ 400000000 | keccak256=0xecc6b6a5fd7719e95d1a5775558038aef9d7855b41980a9dd9d203040ab45aa4", + "a constructor that deploys nothing, nonce 0 @ 400000000 | keccak256=0x48df122101a9b81d974c3237bebc381d79551cae986badab597bb412d7dcb6b8", + "a constructor that deploys nothing, nonce 1 @ 400000000 | keccak256=0xe457f48c9514540b08c08824e66ef7ea82cf99fdb4c640aece47340eb0d26a31", + "a constructor that destroys itself, nonce 0 @ 400000000 | keccak256=0x1deb9dc2b89d6ee0d0b3f112b9b7d57f64e9b982cc40c271dacc9794dbae5355", + "a constructor that destroys itself, nonce 1 @ 400000000 | keccak256=0x74086a0c3fa9ed53cc49bc1df8c405d0d2624ba5b99ffaebe58dc52d2066edf1", + "a constructor out of gas @ 400000000 | keccak256=0x6f036558fefbd5f702390c01155793948729106ff9273141de789c93eb9fc6e9", + "the signer sends it @ 400000000 | keccak256=0xfe626210c579451c32e2f626c26834b42d17cddaf18882e101beb02014bdf06c", + "the signer sends it, and it reverts @ 400000000 | keccak256=0x491266db1558879e50eebae46bb33d9d5ea0f16a34ee3b13c7ac2e263036ee93", + "a delegated signer @ 400000000 | keccak256=0x8f487f733dbfbaa181fb520e69d984a19deec1caca1d050c0f3b166a049b6a27", + "a delegated signer spending nonces, deploys @ 400000000 | keccak256=0xa107860c667709332d37c4ec41fdfd0cceeaab19ef93b2e55c679184bc76ac7b", + "a delegated signer spending nonces, reverts @ 400000000 | keccak256=0x2b21304f22f83d0bbb83974ab351c33b78ad2fcd8d052fa838bbe3bad39ecba9", + "limit: tx data size, nonce 0 @ 400000000 | keccak256=0xa10400d847c8bb7dff794681de273610f0abcbb592d60e221e015880dce5904d", + "limit: compute, nonce 0 @ 400000000 | keccak256=0x164eb97b6134fc61fe58d2803253adfad06b514a1443bf12e5b7c23e56b996d8", + "limit: frame data size, nonce 0 @ 400000000 | keccak256=0xfda55f9a2100228c51c54da623f5a69891fa02f564887f61646a2a44ab0e45a7", + "limit: the call's budget, nonce 0 @ 400000000 | keccak256=0xaa6722d542bda19e9050f94e4b82676d3630f6f09be8eecbf67e43da6ef90cc3", + "limit: the creation's start, nonce 0 @ 400000000 | keccak256=0x5ad715ed7e110f818526030bb5f13738d4b7dc330118c23e9a331ae3526c7a05", + "limit: tx data size, nonce 1 @ 400000000 | keccak256=0x6494bb9f4cd13f0f60b1b2d162386905a3fe97299b7f42d844fec3e4863ecefa", + "limit: compute, nonce 1 @ 400000000 | keccak256=0x50426648fa3561c26af727374ede6f44be7f33fef83fd732679ae9b48fc7bfd3", + "limit: frame data size, nonce 1 @ 400000000 | keccak256=0x5fcc23bc18404f8b3325b694cb671119236f914248b22f9508c7f3fdfcaf3d93", + "limit: the call's budget, nonce 1 @ 400000000 | keccak256=0xb549fca44063b07fbb35746c9a92776bf53c9b2eb63557034f99cba42aadd658", + "limit: the creation's start, nonce 1 @ 400000000 | keccak256=0xa84f7ecc5a86208551f0527940f6288e998f795e6621a6c9f67305eb49bf0eb8", "limit: a body over the limit @ 400000000 | keccak256=0xa6e5f1ff16a1a5a060d22687887b468c7de56f4dcfbb698a2cd4a1b240acee4d", - "limit: the default limits @ 400000000 | keccak256=0x53c838e3841fda75efc979f830a995785fd6053d207e339657d4326c087b15c6", - "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x6b31a69eab1eea9f014065acfc3616431a7153c9a951dbbfbb8dc4c02c496d10", - "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x70c93c1e49bb3f82ee27b6df2e74542f134daf45511344c7b06af84148b15c01", - "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0xa41b5f6fd60a0a7154a11d40792fb6c273c69b21e49c5e4e4500c48a7c74ad95", - "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x767616227fc4acae739ee2d88a2d706b4dd8506312cad721ca51dd8f3e46e5ff", - "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x422863b3415771d5169477ca5fc7f3c49012fce27dd20287dcb57129ead7977f", - "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x02747b270c6ef30361086a8b120b3a9a3b7368ffc212402eadf2ea09833dc6e9", - "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0xfc8b374ddae00ab903e7c7eb7e61a3b6b327365514d104289baca17db3c63289", - "not dispatched: version() @ 400000000 | keccak256=0x21d0fa310f4524f0b6e8506cf6ba99eb84418b6e3f0ddcb2e0deb6003b207fd0", - "not dispatched: no selector @ 400000000 | keccak256=0x68cfd5c7dbdde76046afb03872c58b7c798d53eaea467a999c9f7b3635da9eed", - "not dispatched: from a contract @ 400000000 | keccak256=0x60fbdbf02f2571dd99675222f8697d42508b159a9d424852f19aa3a1f2148c51", - "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x906b081db7ac18f4d82e58ea150ff78a00919fd4d4234d2b0f9f5ac93a541cbc", - "no contract code @ 400000000 | keccak256=0xafac51c3747f80833d5f3296750254d077e3bf6c2d6cec6c36cd8555993ac0dc", - "a system call @ 400000000 | keccak256=0xff3ddad83eca747c58bae960be9ebdba8ab07a3794a8014a8b1721ea8778a416", - "out of gas: the overhead @ 161535 | keccak256=0xe2b170867ee82b5c184c55d46183a6b0f757d90341f439ef72e7a43f2b775a85", - "out of gas: the signer's account @ 162536 | keccak256=0xdfe860c27a35a9c33d54e3e47c64c4afc141c4bb6cabfc87f45cf12df47c8052", - "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x07b0e90b13e66371d8d7abb066a23367672a4bc8899b77d381aac2b0e84f53e4", - "out of gas: the creation's charges @ 163024 | keccak256=0x589fee35bc1e64ba2ee3e7a6c5ad7e9eb8f84f54c82657a285cfb10f31823b50", - "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x1c92a67f868f90f76bb5072ab6e2dbe42a4a60d64d31e739dafd3f5dd1b53178", - "the forward at the signed gas limit exactly @ 864178 | keccak256=0xfc312c015b3d41364fc2ad03a1b68ab5e28f1d8b2b6cb360058df6360212c280", - "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x0f84ba12e978600a79b6d268f088a54cd2a15d063ce1f8ebe91dce8e99f7d828", - "rule: init code over the limit @ 150000000 | keccak256=0xa2498a026c354cd59572ab576b85a982356e60b06704fb79a8a6fe21717a91d3", - "rule: init code over the limit @ 2000000000 | keccak256=0x8e0e07266b270414f4eb958872388f1a26baf80ff2262daba5da7553b7435e8e" + "limit: the default limits @ 400000000 | keccak256=0xf2871d0172174549bbfc91d7cf684dfeddc058a330911913403976c47f656c8a", + "detention: a signer that is the beneficiary @ 400000000 | keccak256=0x055cf0c41d75363ebbb2ce416ddd379b3f8f6f931acd8c2852bfbe27da79dfdb", + "detention: a signer that is the beneficiary, crossing at the CREATE charge @ 400000000 | keccak256=0x1c13190dfd8c7ba6f1d4e4b257ba9c4236acd01636e6a5655053b7aa7884925d", + "detention: the sender is the beneficiary, below the overhead @ 400000000 | keccak256=0x343cce5a7e77fff5350bcc29ab8a34044f599cb1bf018cc46624dcf3026c45cd", + "detention: the sender is the beneficiary, cap 60000 @ 400000000 | keccak256=0x1f08a9c99ca1d6c759b171eccb25d3e6820cb40c38bda50976c993b5b2686f5b", + "detention: the sender is the beneficiary, cap 150000 @ 400000000 | keccak256=0x366811708e9a1b60152807d8c5dd3984ed1b88a0016c86ab2f0aa4d763b09ae2", + "detention: the sender is the beneficiary, cap 400000 @ 400000000 | keccak256=0x43602609a20ae5de69612764d022fd449af3d17c1b8cb39698c9cdcb16dd34c4", + "detention: a constructor that reads, within the cap @ 400000000 | keccak256=0x539be37bb5236f91463bf14405e2d8fbecc38ca8d6913c376af276b39258cce0", + "not dispatched: version() @ 400000000 | keccak256=0xf21dab241d0565c2393c9e0c37035f6be5de3b03a33921186dc6044f506775bc", + "not dispatched: no selector @ 400000000 | keccak256=0xec805be7015aa71877a9df3bea1213c555c71c0b8607af8d6044f45fee86f790", + "not dispatched: from a contract @ 400000000 | keccak256=0x77bca1e5ada4917e8ff0dd9e9d481e75f3df2de516327c1ffc50926730d6bf5e", + "not dispatched: a STATICCALL from a contract @ 400000000 | keccak256=0x2a9952071b259bebd707febdf9f9569b4a6401dfef933777e104c432daf84942", + "no contract code @ 400000000 | keccak256=0xfce752eedcc5e1032c0c2d2da6c959bdc5bc642bed36645a002b1f00af0266f7", + "a system call @ 400000000 | keccak256=0x2753d26c7e11d1b72c62b08fdc4f837edc93238506589ed4137a1ae5aac6c656", + "out of gas: the overhead @ 161535 | keccak256=0x46d0e2acc5da4810497ed4749f8176deeeac29fc6325babd64a609f4e02d369f", + "out of gas: the signer's account @ 162536 | keccak256=0x22574237323abc6ea7696732db91b88baf87ae39d55aa4fe95e599e215091c66", + "rule: the signer's account takes the forward below the signed gas limit @ 845135 | keccak256=0x003485722c66eff085661021f5f19626c15898fc5bf93a8beddc1cd2c59d9456", + "out of gas: the creation's charges @ 163024 | keccak256=0xa576d982542405802977013b3806c9bd522dcbaae1ee07fb81b6122b57e032c7", + "rule: the creation's charges take the forward below the signed gas limit @ 661536 | keccak256=0x5de05094feaf6cf89a99eb14871f718dcde64a0b52deb7feb6fa6e9de8db0bd0", + "the forward at the signed gas limit exactly @ 864178 | keccak256=0x37fe0d37c5b7662773341c622b439cfd9cb8159e103834bf92a11032cd307dd3", + "rule: a forward below a signed gas limit near the cap @ 400000000 | keccak256=0x445fccc13f9822d385a925895a79bf1a230fad9dd1e4001d222c4009cbf88046", + "rule: init code over the limit @ 150000000 | keccak256=0x7ec570ba276f8b3c81c80cb731e98c1482d7a42cc327ed79e606851b608a30d1", + "rule: init code over the limit @ 2000000000 | keccak256=0xa1e17bd2b8390974bab623c8d659da58eae6ac84ef35102103a07b429f5d705b" ], "summary": { - "bytes": 2392466, + "bytes": 2577938, "cases": 139, - "lines": 11444, + "lines": 11452, "runs": 556 } } diff --git a/crates/mega-evm/tests/system/oracle.rs b/crates/mega-evm/tests/system/oracle.rs index 26fb4b91d..79bb3ca60 100644 --- a/crates/mega-evm/tests/system/oracle.rs +++ b/crates/mega-evm/tests/system/oracle.rs @@ -319,7 +319,7 @@ fn test_a_hint_that_crosses_the_data_size_limit_is_not_forwarded() { assert!(hints.is_empty(), "the hint the transaction cannot pay for is not forwarded"); assert_eq!( outcome.usage, - LimitUsage { data_size: body, write_records: 0 }, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 }, "a hint that was not forwarded is not counted: the body is what the transaction keeps", ); assert_eq!( @@ -515,7 +515,7 @@ fn test_consecutive_hints_add_up_on_the_transaction() { assert_eq!(outcome.limit_exceeded, None); assert_eq!( outcome.usage, - LimitUsage { data_size: nested_hint(len), write_records: 0 }, + LimitUsage { data_size: nested_hint(len), write_records: 0, state_growth: 0 }, "the forwarded hint stays counted and the one that crossed is not", ); } @@ -541,7 +541,7 @@ fn test_data_size_overflow_blocks_forwarding_and_stops_the_call() { assert_eq!(outcome.limit_exceeded, None, "a stop below is no stop of the transaction"); assert_eq!( outcome.usage, - LimitUsage { data_size: nested_hint(0), write_records: 0 }, + LimitUsage { data_size: nested_hint(0), write_records: 0, state_growth: 0 }, "the transaction keeps its body: the hint never left the machine", ); diff --git a/crates/mega-evm/tests/system/remaining_compute_gas.rs b/crates/mega-evm/tests/system/remaining_compute_gas.rs index f20ffb471..5a4b4a7af 100644 --- a/crates/mega-evm/tests/system/remaining_compute_gas.rs +++ b/crates/mega-evm/tests/system/remaining_compute_gas.rs @@ -521,10 +521,11 @@ fn test_the_answer_is_what_the_caller_resumes_with() { } } -/// A callee a value call started hears the stipend counted, whether or not the transaction is -/// detained: detention counts the stipend outside compute, so its allowance carries it as the -/// callee's own gas does, and the callee hears the stipend more than the same callee a call -/// without value started. +/// A callee a value call started hears the stipend with its own gas, whether or not the +/// transaction is detained, and so the stipend more than the same callee a call without value +/// started: its own gas binds, the cap leaving far more than the call forwarded. What the callee +/// runs on the stipend is compute like the rest, so once the cap binds the stipend adds nothing +/// to what the limit leaves. #[test] fn test_a_value_called_callee_hears_its_stipend_whether_or_not_detained() { let stipend = 2_300; diff --git a/crates/mega-evm/tests/system/system_tx.rs b/crates/mega-evm/tests/system/system_tx.rs index 84ab99255..71f9ac166 100644 --- a/crates/mega-evm/tests/system/system_tx.rs +++ b/crates/mega-evm/tests/system/system_tx.rs @@ -740,8 +740,8 @@ fn test_a_deposit_over_the_data_size_limit_that_cannot_pay_for_its_caller_is_a_f assert_eq!(outcome.limit_exceeded, None, "the failure is not a data-size stop"); assert_eq!( outcome.usage, - LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0 }, - "the body stays counted", + LimitUsage { data_size: mega_evm::TX_BODY_SIZE, write_records: 0, state_growth: 1 }, + "the body stays counted, and the sender's account, which the failed deposit created", ); } @@ -802,7 +802,8 @@ fn test_the_callee_sees_the_system_address_as_its_caller() { } /// The account a deposit-like transaction creates for its caller is the transaction's own -/// account: it is part of the transaction body, so it is not a write record of its own. +/// account: it is part of the transaction body, so it is not a write record of its own. It is a +/// new account all the same, one of state growth on the transaction. #[test] fn test_the_created_caller_is_not_a_write_record() { let fresh = run_outcome(chain_db(), system_tx(0, B256::with_last_byte(0x99))); @@ -812,10 +813,13 @@ fn test_the_created_caller_is_not_a_write_record() { ); assert!(fresh.result.is_success() && existing.result.is_success()); assert_eq!( - fresh.usage, existing.usage, + (fresh.usage.data_size, fresh.usage.write_records), + (existing.usage.data_size, existing.usage.write_records), "creating the sender's own account records nothing a transaction with an existing sender \ does not record", ); + assert_eq!(existing.usage.state_growth, 1, "the Oracle's slot, set from zero"); + assert_eq!(fresh.usage.state_growth, 2, "and the sender's new account"); } /// A deposit-like transaction that creates a contract pays for the account it creates for its diff --git a/crates/mega-evm/tests/tracers/harness.rs b/crates/mega-evm/tests/tracers/harness.rs index 528a056e2..289518da9 100644 --- a/crates/mega-evm/tests/tracers/harness.rs +++ b/crates/mega-evm/tests/tracers/harness.rs @@ -644,7 +644,13 @@ pub(crate) fn assert_every_frame_stops( panic!("the transaction is not stopped: {:?}", traced.outcome.result); }; assert_eq!((stopped, stopped_at), (kind, limit), "the limit that stopped the transaction"); - assert!(!frame_local, "a transaction-level limit"); + // A counted limit the transaction's own frame crosses is that frame's budget too, which the + // stop names; the compute limit is the transaction's. + assert_eq!( + frame_local, + kind != LimitKind::ComputeGas, + "the frame's budget or the compute limit" + ); let ExecutionResult::Revert { output, .. } = &traced.outcome.result else { panic!("a stop settles as a revert: {:?}", traced.outcome.result); }; diff --git a/crates/mega-evm/tests/tracers/scenarios.rs b/crates/mega-evm/tests/tracers/scenarios.rs index 1f1935d75..d15cbe83c 100644 --- a/crates/mega-evm/tests/tracers/scenarios.rs +++ b/crates/mega-evm/tests/tracers/scenarios.rs @@ -91,16 +91,16 @@ const ROOM: u64 = 1_000_000; /// /// The bill is the receipt, the EIP-7623 floor included: a gas limit below the floor is refused. /// What a scenario holds in passing is gas it is not billed: what it is charged and given back, -/// the 64th a call keeps back from its forward ([`kept_back`]), and what a rule, a limit or an +/// the fiftieth a call keeps back from its forward ([`kept_back`]), and what a rule, a limit or an /// assertion needs it to hold without spending it. fn gas_limit(expected: Ledgers, held: u64) -> u64 { ROOM + expected.receipt() + held } -/// What a caller holds beyond `forwarded` for a forward of all but a 64th of its gas to still -/// cover `forwarded`: a 63rd of it, rounded up. +/// What a caller holds beyond `forwarded` for a forward of all but 2 per cent of its gas to still +/// cover `forwarded`: a 49th of it, rounded up. const fn kept_back(forwarded: u64) -> u64 { - forwarded.div_ceil(63) + forwarded.div_ceil(49) } /// The gas limit the keyless deployments are signed with, which the call's forward must cover. @@ -264,12 +264,12 @@ fn test_nested_call_inner_reverts() { history: gas::body(0) + gas::history(LOG_BASE_SIZE), floor: gas::call_floor(&[], false), }; - // Held in passing: the value call forwards all but a 64th of what the caller has and pays its - // two records' history out of that 64th, so the caller holds 64 times that history; the - // callee pays its slot and the slot's record before its revert gives them back; and the - // forward must cover all the callee spends, which the 64th kept back does not reach. + // Held in passing: the value call forwards all but 2 per cent of what the caller has and pays + // its two records' history out of the fiftieth it keeps, so the caller holds 50 times that + // history; the callee pays its slot and the slot's record before its revert gives them back; + // and the forward must cover all the callee spends, which the part kept back does not reach. let spilled = gas::slot_state() + gas::records(1); - let held = 64 * gas::records(2) + spilled + kept_back(callee_regular + spilled); + let held = 50 * gas::records(2) + spilled + kept_back(callee_regular + spilled); let traced = Traced::run( funded() .account_code(CONTRACT, parent) @@ -549,9 +549,9 @@ fn log0_size(data_len: u8) -> u64 { /// A first frame whose start crosses the transaction's data-size limit, at the smallest limit /// validation admits the transaction under: its body fits, and the record and the transfer log of -/// its value do not. The frame is answered with the stop before it runs, so it runs no instruction -/// and its value never moves. A body over the limit is no scenario: validation rejects it, and a -/// rejected transaction has no trace. +/// its value do not. The frame returns the stop before it runs an instruction, and its revert takes +/// back the value revm moved for it. A body over the limit is no scenario: validation rejects it, +/// and a rejected transaction has no trace. #[test] fn test_data_size_limit_stops_the_first_frame_at_its_start() { let limit = TX_BODY_SIZE; @@ -570,7 +570,8 @@ fn test_data_size_limit_stops_the_first_frame_at_its_start() { call_tx(CALLER, CONTRACT, Bytes::new(), U256::from(1), gas_limit(expected, held)), EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit), ); - assert_every_frame_stops(&traced, LimitKind::DataSize, limit, 1); + // The frame's budget is what the body leaves of the limit: nothing, which its start crosses. + assert_every_frame_stops(&traced, LimitKind::DataSize, limit - TX_BODY_SIZE, 1); assert!(traced.inspector.traces().nodes()[0].trace.steps.is_empty(), "no instruction ran"); // The record's history was charged on the transaction's gas before the frame and comes back // after the tracer read the frame, as a failed frame's spill does. @@ -578,8 +579,8 @@ fn test_data_size_limit_stops_the_first_frame_at_its_start() { } /// A child's `LOG0` that crosses the transaction's data-size limit and, with it, its own frame -/// budget. The transaction limit is the one the child's stop names, and only the child reverts: -/// the parent resumes, writes a slot within what the transaction has left, and succeeds. +/// budget. The budget, tested first, is the one the child's stop names, and only the child +/// reverts: the parent resumes, writes a slot within what the transaction has left, and succeeds. #[test] fn test_data_size_limit_stop_is_caught_by_the_parent() { // What the transaction may produce besides its body; the child's log is larger, the parent's @@ -601,7 +602,7 @@ fn test_data_size_limit_stop_is_caught_by_the_parent() { history: gas::body(0) + gas::records(1), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // Held in passing: the fiftieth the parent keeps back from a forward that must cover what the // child spends. let held = kept_back(logging_regular(data_len)); let traced = Traced::run( @@ -617,8 +618,8 @@ fn test_data_size_limit_stop_is_caught_by_the_parent() { assert_eq!(child.error.as_deref(), Some("execution reverted")); assert_eq!( decode_stop(child.output.as_ref().expect("the child's revert data")), - (LimitKind::DataSize, limit), - "the child reverts with the transaction's limit" + (LimitKind::DataSize, room * 98 / 100), + "the child reverts with its budget, 98% of what the body leaves the parent" ); assert!(child.logs.is_empty(), "the child's log was never made"); assert_parent_resumed(&traced, "STOP"); @@ -652,7 +653,7 @@ fn test_frame_budget_reverts_the_child_alone() { history: gas::body(0) + gas::history(LOG_BASE_SIZE), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the parent keeps back from a forward that must cover what the + // Held in passing: the fiftieth the parent keeps back from a forward that must cover what the // child spends. let held = kept_back(logging_regular(data_len)); let traced = Traced::run( @@ -758,8 +759,8 @@ fn test_detention_stop_crosses_again_in_the_parent() { // Held in passing: what the child holds when it crosses. The charge that crosses, the child's // `JUMP`: detention stops a charge the frame's whole gas covers, and one beyond it is an // out-of-gas. On top of it the receipt, so the crossing step, which reads as spending the - // child's whole gas, shows a cost the receipt cannot have billed. And the 64th the parent keeps - // back from a forward that must cover the child's loop and all that. + // child's whole gas, shows a cost the receipt cannot have billed. And the 2 per cent the parent + // keeps back from a forward that must cover the child's loop and all that. let at_crossing = expected.receipt() + MID; let held = at_crossing + kept_back(compute - before_loop + at_crossing); let traced = Traced::run( @@ -889,7 +890,7 @@ fn test_precompile_child_frame() { history: gas::body(0), floor: gas::call_floor(&[], false), }; - // Held in passing: the 64th the contract keeps back from a forward that must cover the + // Held in passing: the 2 per cent the contract keeps back from a forward that must cover the // precompile's price. let traced = Traced::run( funded().account_code(CONTRACT, code), diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap index a205dd458..6e59f94ce 100644 --- a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_first_frame_start_stop__call_with_log.snap @@ -8,7 +8,7 @@ expression: "&redacted(&traced.call_frame(true))" "gas": "[gas]", "gasUsed": "[gas]", "input": "0x", - "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000136", + "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "to": "0x0000000000000000000000000000000000400002", "type": "CALL", "value": "0x1" diff --git a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap index 6d31977f5..1288ccf71 100644 --- a/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap +++ b/crates/mega-evm/tests/tracers/snapshots/tracers__harness__data_size_stop_caught_by_the_parent__call_with_log.snap @@ -10,7 +10,7 @@ expression: "&redacted(&traced.call_frame(true))" "gas": "[gas]", "gasUsed": "[gas]", "input": "0x", - "output": "0x84b902670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000019a", + "output": "0x84b9026700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000062", "to": "0x0000000000000000000000000000000000400003", "type": "CALL", "value": "0x0" diff --git a/crates/mega-state-test/AGENTS.md b/crates/mega-state-test/AGENTS.md index a1c80cc18..fd9b08fad 100644 --- a/crates/mega-state-test/AGENTS.md +++ b/crates/mega-state-test/AGENTS.md @@ -38,6 +38,8 @@ The fixture types are the revm fork's own (`revm::statetest_types`, the `test-ty ## WHERE TO LOOK - Add or move a deviation: `src/deviations.rs`, its entries taken from a `--json-outcome` run, then `UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations`. +- Change what the outcome digest records, or how it is encoded: `src/digest.rs`; every change moves the digest of every transaction it touches, so it is made on its own, with the base's digest taken by the same code. +- Tighten the limits a run is held to: `Config::limits`, from `state-test`'s `--limit-*` options. - Change what a mode configures: `src/mode.rs`, and `mega-evm`'s `src/test_utils/neutral.rs`. - Change how a test is judged: `src/runner.rs::check`, `src/exceptions.rs`. - Change how a blockchain test is judged: `src/blockchain/mod.rs`; its skips: `src/blockchain/skips.rs`; what is taken out of its state root: `src/blockchain/chain.rs`. diff --git a/crates/mega-state-test/README.md b/crates/mega-state-test/README.md index 18bc0aa3f..9dffdb534 100644 --- a/crates/mega-state-test/README.md +++ b/crates/mega-state-test/README.md @@ -58,6 +58,31 @@ cargo run --release -p state-test -- --mode satin --fork Osaka
/state_test `--expect-executed`, `--expect-skipped` and `--expect-deviations` turn a full run into the pinned gate CI runs (`.github/workflows/exec-spec-satin.yml`). `--json-outcome` prints one JSON line per test, a failure's produced hashes included, and `--trace` runs each test under an EIP-3155 tracer. +## The outcome digest + +A verdict is the post-state root and the logs hash, so a change that moves gas between ledgers and keeps the receipt's total, or changes the bytes a limit counted, leaves every verdict as it was. +The digest (`src/digest.rs`) is the record such a change cannot leave alone: the whole `MegaTransactionOutcome` of every transaction that ran, whatever its fixture's verdict. +`--json-digest` prints, per executed transaction, one JSON line on standard error with the test's identity (`mode`, `fork`, `path`, `test`, `d`, `g`, `v`), the Keccak-256 of the canonical record (`digest`) and `row`, `outcome` for a transaction that ended and `panic` for a test that panicked; `--json-digest-full` adds the record (`record`). +A transaction the engine rejects has a record of its own, the error; a test skipped before it ran has none. + +The record holds the status with its halt or revert reason, the output, the created address and the logs in order; `ResultGas` and every field of `MegaGasUsage`; `usage`; `limit_exceeded`; `oracle_reads`; and the post-state, each account with its status flags, balance, nonce, code hash and every storage slot's original and present values. +It is canonical: JSON with every object's keys sorted, 256-bit numbers as lowercase hex without leading zeros, hashes and addresses at full width, maps sorted by key, so it depends on neither a thread count nor a hash map's order. +It is taken from the outcome as the engine produced it, before the runner takes the base-fee vault the fee routing created back out of the state. + +## Tightened limits + +Satin mode holds each transaction to the spec's limits, which the corpus rarely reaches. +`--limit-data-size BYTES` replaces the transaction data-size limit, and with it the frame data-size cap, which follows it unless `--limit-frame-data-size BYTES` names another; `--limit-kv-updates RECORDS` and `--limit-state-growth UNITS` replace the transaction's KV and state-growth limits, every frame's budget following each as its share; `--limit-compute-gas GAS` replaces gas detention's two caps. +A run so limited stops transactions the spec's run lets through, so its verdicts fail; it is read through its digest, whose `limit_exceeded` and `usage` then cover the stop paths of the whole corpus. +The options need `--mode satin`: equivalence mode installs no limit, and refuses them. +There is no write-record limit to tighten: a record is forty bytes of data size and is held by the data-size limit. + +To compare two revisions, run the same command at both, keep the lines that start with `{`, sort them, and compare the files; a line that differs is found by its `path` and `test`, and its full form shows the fields. + +```bash +state-test --mode satin --fork Osaka
/state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest +``` + ## Blockchain tests `state-test btest` imports the execution-spec blockchain tests through Satin's block executor (`src/blockchain/`): the tests of the main release's `blockchain_tests` filled for Osaka, the release and the network the state-test gate's Osaka run uses. diff --git a/crates/mega-state-test/src/digest.rs b/crates/mega-state-test/src/digest.rs new file mode 100644 index 000000000..252c54f25 --- /dev/null +++ b/crates/mega-state-test/src/digest.rs @@ -0,0 +1,358 @@ +//! The canonical record of a transaction's whole outcome, and its hash. +//! +//! A fixture's verdict says whether the post-state root and the logs hash match the fixture's; it +//! says nothing of the gas a transaction spent on each ledger, of the bytes its limits counted, of +//! how it stopped or of the state beneath the root. A change that moves gas between ledgers and +//! keeps the receipt's total, or changes `usage` alone, leaves every verdict as it was. The digest +//! is the record such a change cannot leave alone: everything [`MegaTransactionOutcome`] holds, +//! rendered in one fixed encoding, so two runs of the same fixtures at two revisions can be +//! compared line by line, and a mismatch shows which field differs. +//! +//! The encoding is canonical: a JSON value whose objects list their keys in sorted order, whose +//! 256-bit numbers are `0x`-prefixed lowercase hex without leading zeros, and whose hashes, +//! addresses and byte strings are full-width lowercase hex. Maps are sorted by key before they +//! are written, so nothing in it depends on a hash map's iteration order or on a memory address. +//! The one place that renders a type through `Debug` is a halt or success reason and a rejected +//! transaction's error, whose names are the types' own; a dependency changing those names moves +//! the digest of the transactions that end that way, and the full form shows it. + +use std::collections::BTreeMap; + +use mega_evm::{ + revm::{ + context::result::{ExecutionResult, ResultGas}, + primitives::{keccak256, Address, Log, B256, U256}, + state::{Account, EvmState}, + }, + LimitCheck, LimitUsage, MegaGasUsage, MegaHaltReason, MegaTransactionOutcome, OracleRead, +}; +use serde_json::{Map, Value}; + +/// What a transaction ended in: its outcome, or the error it was rejected with. +pub type Executed<'a> = Result<&'a MegaTransactionOutcome, &'a str>; + +/// A JSON object whose keys are listed in sorted order, whichever order the map keeps. +fn object(entries: impl IntoIterator) -> Value { + let sorted: BTreeMap = entries.into_iter().collect(); + let mut map = Map::new(); + for (key, value) in sorted { + map.insert(key, value); + } + Value::Object(map) +} + +fn fields(entries: [(&str, Value); N]) -> Value { + object(entries.into_iter().map(|(key, value)| (key.to_string(), value))) +} + +/// A 256-bit number as `0x`-prefixed lowercase hex without leading zeros. +fn number(value: U256) -> Value { + Value::String(format!("{value:#x}")) +} + +fn hex(bytes: impl AsRef<[u8]>) -> Value { + Value::String(format!("0x{}", to_hex(bytes.as_ref()))) +} + +fn to_hex(bytes: &[u8]) -> String { + use core::fmt::Write; + bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut out, byte| { + write!(out, "{byte:02x}").expect("writing to a string cannot fail"); + out + }) +} + +fn address(address: &Address) -> String { + format!("0x{}", to_hex(address.as_slice())) +} + +/// A result's gas, with the reservoir the transaction left beside its other fields: revm's +/// [`ResultGas`] does not carry it, the outcome does ([`MegaGasUsage::reservoir_remaining`]). +fn result_gas(gas: &ResultGas, reservoir_remaining: u64) -> Value { + fields([ + ("block_regular_gas_used", gas.block_regular_gas_used().into()), + ("block_state_gas_used", gas.block_state_gas_used().into()), + ("final_refunded", gas.final_refunded().into()), + ("floor_gas", gas.floor_gas().into()), + ("inner_refunded", gas.inner_refunded().into()), + ("reservoir_remaining", reservoir_remaining.into()), + ("state_gas_spent_final", gas.state_gas_spent_final().into()), + ("total_gas_spent", gas.total_gas_spent().into()), + ("tx_gas_used", gas.tx_gas_used().into()), + ]) +} + +fn gas_usage(gas: &MegaGasUsage) -> Value { + let MegaGasUsage { + regular, + state, + history, + history_bytes, + reservoir_remaining, + floor, + gas_used, + } = *gas; + fields([ + ("floor", floor.into()), + ("gas_used", gas_used.into()), + ("history", history.into()), + ("history_bytes", history_bytes.into()), + ("regular", regular.into()), + ("reservoir_remaining", reservoir_remaining.into()), + ("state", state.into()), + ]) +} + +fn usage(usage: &LimitUsage) -> Value { + let LimitUsage { data_size, write_records, state_growth } = *usage; + fields([ + ("data_size", data_size.into()), + ("state_growth", state_growth.into()), + ("write_records", write_records.into()), + ]) +} + +fn log(log: &Log) -> Value { + fields([ + ("address", address(&log.address).into()), + ("data", hex(&log.data.data)), + ("topics", Value::Array(log.data.topics().iter().map(hex).collect())), + ]) +} + +fn logs(logs: &[Log]) -> Value { + Value::Array(logs.iter().map(log).collect()) +} + +fn limit_check(check: &LimitCheck) -> Value { + match check { + LimitCheck::WithinLimit => fields([("check", "within-limit".into())]), + LimitCheck::ExceedsLimit { kind, limit, used, frame_local } => fields([ + ("check", "exceeds-limit".into()), + ("frame_local", (*frame_local).into()), + ("kind", format!("{kind:?}").into()), + ("limit", (*limit).into()), + ("used", (*used).into()), + ]), + } +} + +fn oracle_read(read: &OracleRead) -> Value { + fields([("answer", read.answer.map_or(Value::Null, number)), ("slot", number(read.slot))]) +} + +fn account(account: &Account) -> Value { + let storage = object(account.storage.iter().map(|(key, slot)| { + ( + format!("{key:#066x}"), + fields([ + ("original", number(slot.original_value)), + ("present", number(slot.present_value)), + ]), + ) + })); + fields([ + ("balance", number(account.info.balance)), + ("code_hash", hex(account.info.code_hash)), + ("nonce", account.info.nonce.into()), + ("status", account.status.bits().into()), + ( + "status_flags", + Value::Array(account.status.iter_names().map(|(name, _)| name.into()).collect()), + ), + ("storage", storage), + ]) +} + +fn state(state: &EvmState) -> Value { + object(state.iter().map(|(addr, account_)| (address(addr), account(account_)))) +} + +fn result(result: &ExecutionResult, reservoir_remaining: u64) -> Value { + match result { + ExecutionResult::Success { reason, gas, logs: l, output } => fields([ + ("created", output.address().map_or(Value::Null, |a| address(a).into())), + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("output", hex(output.data())), + ("reason", format!("{reason:?}").into()), + ("status", "success".into()), + ]), + ExecutionResult::Revert { gas, logs: l, output } => fields([ + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("output", hex(output)), + ("status", "revert".into()), + ]), + ExecutionResult::Halt { reason, gas, logs: l } => fields([ + ("gas", result_gas(gas, reservoir_remaining)), + ("logs", logs(l)), + ("reason", format!("{reason:?}").into()), + ("status", "halt".into()), + ]), + } +} + +/// The canonical record of an executed transaction. +pub fn canonical(executed: Executed<'_>) -> Value { + match executed { + Ok(outcome) => fields([ + ("gas", gas_usage(&outcome.gas)), + ("limit_exceeded", outcome.limit_exceeded.as_ref().map_or(Value::Null, limit_check)), + ("oracle_reads", Value::Array(outcome.oracle_reads.iter().map(oracle_read).collect())), + ("result", result(&outcome.result, outcome.gas.reservoir_remaining)), + ("state", state(&outcome.state)), + ("usage", usage(&outcome.usage)), + ]), + Err(error) => fields([("rejected", error.into())]), + } +} + +/// The record of a test that panicked. +pub fn panicked(message: &str) -> Value { + fields([("panic", message.into())]) +} + +/// The digest of a canonical record: the Keccak-256 of its JSON text. +pub fn hash(canonical: &Value) -> B256 { + keccak256(text(canonical)) +} + +/// A canonical record's JSON text, on one line. +pub fn text(canonical: &Value) -> String { + serde_json::to_string(canonical).expect("a JSON value serializes") +} + +#[cfg(test)] +mod tests { + use super::*; + use mega_evm::revm::{ + context::result::{Output, ResultAndState, SuccessReason}, + primitives::Bytes, + state::{AccountInfo, EvmStorageSlot}, + }; + + fn gas() -> ResultGas { + ResultGas::default() + .with_total_gas_spent(100_000) + .with_state_gas_spent(30_000) + .with_refunded(4_000) + .with_floor_gas(21_000) + } + + fn outcome() -> MegaTransactionOutcome { + let mut state = EvmState::default(); + let mut account = Account::from(AccountInfo { nonce: 3, ..Default::default() }); + account.storage.insert( + U256::from(1), + EvmStorageSlot::new_changed(U256::from(7), U256::from(9), Default::default()), + ); + account.mark_touch(); + state.insert(Address::repeat_byte(0xaa), account); + state.insert(Address::repeat_byte(0x11), Account::default()); + MegaTransactionOutcome { + result_and_state: ResultAndState::new( + ExecutionResult::Success { + reason: SuccessReason::Stop, + gas: gas(), + logs: Vec::new(), + output: Output::Call(Bytes::from_static(&[1, 2])), + }, + state, + ), + gas: MegaGasUsage::new(&gas(), 10_000, 125, 5_000), + usage: LimitUsage { data_size: 500, write_records: 3, state_growth: 0 }, + limit_exceeded: None, + oracle_reads: vec![OracleRead { slot: U256::from(4), answer: Some(U256::from(5)) }], + } + } + + fn digest(outcome: &MegaTransactionOutcome) -> B256 { + hash(&canonical(Ok(outcome))) + } + + /// The same outcome, built twice, has the same text and the same hash, whatever order its + /// maps were filled in. + #[test] + fn test_the_digest_is_stable() { + let (a, b) = (outcome(), outcome()); + assert_eq!(text(&canonical(Ok(&a))), text(&canonical(Ok(&b)))); + assert_eq!(digest(&a), digest(&b)); + + let mut reordered = outcome(); + let accounts: Vec<_> = reordered.state.drain().collect(); + for (addr, account) in accounts.into_iter().rev() { + reordered.state.insert(addr, account); + } + assert_eq!(digest(&a), digest(&reordered)); + } + + /// The text names its keys in sorted order, whichever order the JSON map keeps. + #[test] + fn test_the_text_lists_keys_in_sorted_order() { + let text = text(&canonical(Ok(&outcome()))); + assert!(text.starts_with("{\"gas\":{\"floor\":"), "{text}"); + let markers = [ + ",\"limit_exceeded\":", + ",\"oracle_reads\":", + ",\"result\":{", + ",\"state\":{\"0x11", + ",\"usage\":", + ]; + let positions: Vec<_> = markers.iter().map(|m| text.find(m).expect(m)).collect(); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{text}"); + } + + /// Moving history gas to regular gas with the total kept changes the digest, though the + /// receipt's figures stay the same. + #[test] + fn test_one_gas_field_moves_the_digest() { + let base = outcome(); + let mut moved = outcome(); + moved.gas.history -= 100; + moved.gas.regular += 100; + assert_eq!(base.gas.regular + base.gas.history, moved.gas.regular + moved.gas.history); + assert_eq!(base.gas.gas_used, moved.gas.gas_used); + assert_ne!(digest(&base), digest(&moved)); + } + + /// Each of `usage`'s counts moves the digest on its own. + #[test] + fn test_usage_alone_moves_the_digest() { + let base = outcome(); + let mut data = outcome(); + data.usage.data_size += 1; + let mut records = outcome(); + records.usage.write_records += 1; + let mut growth = outcome(); + growth.usage.state_growth += 1; + assert_ne!(digest(&base), digest(&data)); + assert_ne!(digest(&base), digest(&records)); + assert_ne!(digest(&base), digest(&growth)); + } + + /// A slot's original value alone, its present value kept, moves the digest. + #[test] + fn test_an_original_storage_value_alone_moves_the_digest() { + let base = outcome(); + let mut moved = outcome(); + moved + .state + .get_mut(&Address::repeat_byte(0xaa)) + .unwrap() + .storage + .get_mut(&U256::from(1)) + .unwrap() + .original_value = U256::from(8); + assert_ne!(digest(&base), digest(&moved)); + } + + /// A rejection and a panic are records of their own, which differ from an outcome's and from + /// each other. + #[test] + fn test_a_rejection_and_a_panic_have_their_own_records() { + let rejected = hash(&canonical(Err("nonce too low"))); + assert_ne!(rejected, digest(&outcome())); + assert_ne!(rejected, hash(&panicked("nonce too low"))); + } +} diff --git a/crates/mega-state-test/src/lib.rs b/crates/mega-state-test/src/lib.rs index 0f65f5c73..d25456f3d 100644 --- a/crates/mega-state-test/src/lib.rs +++ b/crates/mega-state-test/src/lib.rs @@ -25,6 +25,7 @@ pub mod blockchain; pub mod deviations; +pub mod digest; pub mod exceptions; mod fork; mod mode; @@ -34,6 +35,8 @@ pub mod skips; pub mod witness; pub use fork::*; +/// The per-transaction limits a run can be held to, for [`runner::Config::limits`]. +pub use mega_evm::EvmTxRuntimeLimits; pub use mode::*; /// The execution-spec state-test fixture types, as the revm fork's reference runner reads diff --git a/crates/mega-state-test/src/runner.rs b/crates/mega-state-test/src/runner.rs index f8966439d..2dadd11af 100644 --- a/crates/mega-state-test/src/runner.rs +++ b/crates/mega-state-test/src/runner.rs @@ -38,18 +38,21 @@ use std::{ }; use mega_evm::{ + alloy_evm::Database, alloy_op_evm::OpTx, op_revm::{constants::BASE_FEE_RECIPIENT, OpHaltReason, OpTransaction, OpTransactionError}, revm::{ context::{ - result::{EVMError, ExecutionResult}, + result::{EVMError, ExecutionResult, ResultAndState}, BlockEnv, CfgEnv, }, database::{EmptyDB, State}, - inspector::{inspectors::TracerEip3155, InspectCommitEvm}, + inspector::{inspectors::TracerEip3155, Inspector}, + interpreter::interpreter::EthInterpreter, primitives::{Bytes, B256, KECCAK_EMPTY, U256}, - ExecuteCommitEvm, + DatabaseCommit, ExecuteCommitEvm, }, + EvmTxRuntimeLimits, MegaContext, MegaEvm, }; use serde::{ de::{Error as _, MapAccess, Visitor}, @@ -59,6 +62,7 @@ use walkdir::WalkDir; use crate::{ deviations::{self, Deviation}, + digest, exceptions::{self, Mismatch}, mode::MAX_BLOBS_PER_TX, roots::{logs_hash, state_root}, @@ -80,11 +84,25 @@ pub struct Config { pub json_outcome: bool, /// Run each test under an EIP-3155 tracer writing to standard error. pub trace: bool, + /// Print the digest of every transaction's whole outcome to standard error, in this form. + pub digest: Option, + /// Satin mode: the per-transaction limits the tests run under instead of the spec's, to reach + /// the limit-stop paths. Equivalence mode installs no limit and refuses these. + pub limits: Option, /// The registry equivalence mode attributes failures to: [`deviations::DEVIATIONS`] for the /// gate. pub deviations: &'static [Deviation], } +/// How much of a transaction's digest a run prints. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DigestForm { + /// The test's identity and the hash of the canonical record. + Compact, + /// The same, with the canonical record itself. + Full, +} + /// Which test a result is about. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] pub struct TestId { @@ -226,6 +244,11 @@ pub struct TestResult { pub id: TestId, /// What happened to it. pub outcome: Outcome, + /// The canonical record of what its transaction ended in ([`digest::canonical`]), for a test + /// whose transaction ran, whatever the verdict: a test that did not run, or panicked before + /// its transaction ended, has none. + #[serde(skip)] + pub record: Option, } /// Every test a run was given, and what happened to each. @@ -493,18 +516,28 @@ pub fn run_file(path: &Path, config: Config) -> Result, Failure> entry, indexes: (test.indexes.data, test.indexes.gas, test.indexes.value), }; + let mut executed = None; let outcome = match skip { Some(reason) => Outcome::Skipped { reason }, - None => catch_unwind(AssertUnwindSafe(|| run_test(config, unit, test))) - .unwrap_or_else(|panic| { - Outcome::Failed(Failure::new(FailureKind::Panic, panic_message(&panic))) - }), + None => catch_unwind(AssertUnwindSafe(|| { + run_test(config, unit, test, &mut executed) + })) + .unwrap_or_else(|panic| { + let message = panic_message(&panic); + if let Some(form) = config.digest { + print_digest(config, form, &id, "panic", &digest::panicked(&message)); + } + Outcome::Failed(Failure::new(FailureKind::Panic, message)) + }), }; + if let (Some(form), Some(executed)) = (config.digest, &executed) { + print_digest(config, form, &id, "outcome", executed); + } let outcome = attribute(config, &id, outcome); if config.json_outcome { print_outcome(config, &id, &outcome); } - results.push(TestResult { id, outcome }); + results.push(TestResult { id, outcome, record: executed }); } } } @@ -561,6 +594,34 @@ fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { .unwrap_or_else(|| "a panic without a message".into()) } +/// Prints the digest line of a test to standard error: the compact form names the test and the +/// hash of its canonical record, the full form carries the record too. `row` is `outcome` for a +/// transaction that ended and `panic` for a test that panicked, which a run compared by digest +/// must not have. +fn print_digest( + config: Config, + form: DigestForm, + id: &TestId, + row: &str, + record: &serde_json::Value, +) { + let mut line = serde_json::json!({ + "mode": config.mode, + "fork": config.fork, + "path": id.path, + "test": id.name, + "d": id.indexes.0, + "g": id.indexes.1, + "v": id.indexes.2, + "digest": digest::hash(record), + "row": row, + }); + if form == DigestForm::Full { + line["record"] = record.clone(); + } + eprintln!("{line}"); +} + fn print_outcome(config: Config, id: &TestId, outcome: &Outcome) { let line = serde_json::json!({ "mode": config.mode, @@ -585,8 +646,16 @@ pub(crate) fn chain_id(unit: &TestUnit) -> Result { } /// Executes one entry and judges it against its fixture. -fn run_test(config: Config, unit: &TestUnit, test: &Test) -> Outcome { - match execute_and_check(config, unit, test) { +/// +/// `executed` receives the canonical record of what the transaction ended in as soon as it has +/// ended, so a test that then fails its fixture, or panics while it is judged, still has one. +fn run_test( + config: Config, + unit: &TestUnit, + test: &Test, + executed: &mut Option, +) -> Outcome { + match execute_and_check(config, unit, test, executed) { Ok(None) => Outcome::Passed, Ok(Some(reason)) => Outcome::Skipped { reason }, Err(failure) => Outcome::Failed(failure), @@ -597,6 +666,7 @@ fn execute_and_check( config: Config, unit: &TestUnit, test: &Test, + executed: &mut Option, ) -> Result, Failure> { let Ready { chain_id, block, tx } = match prepare(config.fork, unit, test)? { Ok(ready) => ready, @@ -606,13 +676,15 @@ fn execute_and_check( let basefee = block.basefee; let mut state = State::builder().with_cached_prestate(unit.state()).with_bundle_update().build(); - let evm = config.mode.evm(config.fork, &mut state, block, chain_id); + let mut evm = config.mode.evm(config.fork, &mut state, block, chain_id); + if let Some(limits) = config.limits { + evm.set_tx_runtime_limits(limits); + } let result = if config.trace { let mut evm = evm.with_inspector(TracerEip3155::buffered(stderr()).without_summary()); - evm.inspect_tx_commit(tx) + execute_and_commit(&mut evm, tx, executed) } else { - let mut evm = evm; - evm.transact_commit(tx) + execute_and_commit(&mut evm, tx, executed) }; if let Ok(result) = &result { undo_fee_vault_credit(unit, &mut state, basefee, result.tx_gas_used()); @@ -621,6 +693,38 @@ fn execute_and_check( Ok(None) } +/// Executes `tx` on `evm` and commits what it produced, as `transact_commit` does, keeping the +/// transaction's whole outcome: its canonical record goes to `executed`, and the result is what +/// the fixture is judged on. +fn execute_and_commit( + evm: &mut MegaEvm, + tx: OpTx, + executed: &mut Option, +) -> Result, EVMError> +where + DB: Database + DatabaseCommit, + INSP: Inspector, EthInterpreter>, +{ + match evm.execute_transaction(tx) { + Ok(outcome) => { + *executed = Some(digest::canonical(Ok(&outcome))); + let ResultAndState { result, state } = outcome.result_and_state; + evm.commit(state); + Ok(result) + } + Err(error) => { + *executed = Some(digest::canonical(Err(&format!("{error:?}")))); + Err(match error { + EVMError::Transaction(error) => EVMError::Transaction(error.0), + EVMError::Header(error) => EVMError::Header(error), + EVMError::Database(error) => EVMError::Database(error), + EVMError::Custom(error) => EVMError::Custom(error), + EVMError::CustomAny(error) => EVMError::CustomAny(error), + }) + } + } +} + /// An entry ready to run: its chain id, block and transaction. pub(crate) struct Ready { /// The chain id the entry runs on. diff --git a/crates/mega-state-test/tests/runner.rs b/crates/mega-state-test/tests/runner.rs index 3f71fc110..f94235984 100644 --- a/crates/mega-state-test/tests/runner.rs +++ b/crates/mega-state-test/tests/runner.rs @@ -18,7 +18,7 @@ use state_test::{ runner::{run, Config, FailureKind, Outcome, Report}, skips::SkipReason, types::TestSuite, - Fork, Mode, + EvmTxRuntimeLimits, Fork, Mode, }; const SENDER: &str = "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"; @@ -31,7 +31,16 @@ const BASE_FEE_VAULT: &str = "0x4200000000000000000000000000000000000019"; const STORE_AND_LOG: &str = "0x602a5f5560075f5260205fa000"; fn config(mode: Mode, fork: Fork) -> Config { - Config { mode, fork, threads: 2, json_outcome: false, trace: false, deviations: DEVIATIONS } + Config { + mode, + fork, + threads: 2, + json_outcome: false, + trace: false, + digest: None, + limits: None, + deviations: DEVIATIONS, + } } /// A unit calling `CONTRACT` with `transaction` fields over the defaults, and one entry per fork @@ -499,3 +508,105 @@ fn test_the_registry_does_not_absorb_another_failure_of_its_entries() { )); assert_eq!(report.summary().unattributed, 1); } + +/// The records of a run's tests, in test order: none for a test whose transaction did not run. +fn records(report: &Report) -> Vec> { + report.results.iter().map(|result| result.record.as_ref()).collect() +} + +/// A run's digest does not depend on the thread count or on the run: the records of a file of +/// several tests are the same on one thread and on several, twice over, whatever the verdicts. +#[test] +fn test_the_digest_is_stable_across_runs_and_thread_counts() { + let dir = tempfile::tempdir().unwrap(); + let units: serde_json::Map<_, _> = (0..6) + .map(|n| { + let unit = unit( + &[Fork::Osaka], + json!({ "gasLimit": ["0x0f4240"], "value": [format!("0x{n:02x}")] }), + ); + (format!("call_{n}"), fill_from_ethereum(unit)) + }) + .collect(); + let paths = [write(dir.path(), "a.json", units.clone().into()), { + write(dir.path(), "b.json", units.into()) + }]; + let run_with = |threads| { + let report = run(&paths, Config { threads, ..config(Mode::Satin, Fork::Osaka) }); + records(&report).into_iter().map(|r| r.cloned()).collect::>() + }; + let one = run_with(1); + assert_eq!(one.len(), 12); + assert!(one.iter().all(Option::is_some), "every transaction ran"); + assert_eq!(one, run_with(1)); + assert_eq!(one, run_with(4)); + assert_eq!(one, run_with(4)); + let hashes: std::collections::BTreeSet<_> = + one.iter().flatten().map(state_test::digest::hash).collect(); + assert_eq!(hashes.len(), 6, "six distinct values, two files of each"); +} + +/// A test that fails its fixture still has the record of what ran, and a transaction the engine +/// rejects has one that says so; a test skipped by its fixture has none. +#[test] +fn test_the_digest_covers_failed_and_rejected_tests() { + let dir = tempfile::tempdir().unwrap(); + let filled = fill_from_ethereum(unit(&[Fork::Osaka], json!({}))); + let mut wrong_root = filled.clone(); + wrong_root["post"]["Osaka"][0]["hash"] = json!(B256::repeat_byte(1)); + let mut rejected = fill_from_ethereum(unit( + &[Fork::Osaka], + json!({ "gasLimit": ["0x5208"], "data": ["0x00"] }), + )); + rejected["post"]["Osaka"][0]["expectException"] = + json!("TransactionException.INTRINSIC_GAS_TOO_LOW"); + let path = write( + dir.path(), + "a.json", + json!({ "a_passes": filled, "b_wrong_root": wrong_root, "c_rejected": rejected }), + ); + let report = run(&[path], config(Mode::Equivalence, Fork::Osaka)); + let kinds: Vec<_> = outcomes(&report).into_iter().map(failure_kind).collect(); + assert_eq!(kinds, [None, Some(FailureKind::StateRootMismatch), None]); + let records = records(&report); + assert!(records.iter().all(Option::is_some)); + assert!(records[0].unwrap()["result"]["status"] == "success"); + assert_eq!( + records[0], records[1], + "the same transaction, the same record, whatever the verdict" + ); + assert!(records[2].unwrap()["rejected"] + .as_str() + .unwrap() + .contains("CallGasCostMoreThanGasLimit")); +} + +/// Running under tighter limits stops the transaction a limit holds: its record names the stop, +/// where the same fixture under the spec's limits has none. +#[test] +fn test_tightened_limits_reach_the_limit_stop_paths() { + let dir = tempfile::tempdir().unwrap(); + let path = write( + dir.path(), + "a.json", + json!({ "call": fill_from_ethereum(unit(&[Fork::Osaka], json!({ "gasLimit": ["0x0f4240"] }))) }), + ); + let spec = run(std::slice::from_ref(&path), config(Mode::Satin, Fork::Osaka)); + let tight = run( + &[path], + Config { + limits: Some( + EvmTxRuntimeLimits::default() + .with_tx_data_size_limit(400) + .with_frame_data_size_limit(400), + ), + ..config(Mode::Satin, Fork::Osaka) + }, + ); + let (spec, tight) = (records(&spec)[0].unwrap(), records(&tight)[0].unwrap()); + assert!(spec["limit_exceeded"].is_null()); + assert_eq!(tight["limit_exceeded"]["kind"], "DataSize"); + // The transaction's own frame crosses its budget, what the body leaves of the 400 bytes. + assert_eq!(tight["limit_exceeded"]["limit"], 400 - mega_evm::TX_BODY_SIZE); + assert_ne!(state_test::digest::hash(spec), state_test::digest::hash(tight)); +} diff --git a/crates/state-test/README.md b/crates/state-test/README.md index 7f573970d..b461230f3 100644 --- a/crates/state-test/README.md +++ b/crates/state-test/README.md @@ -10,6 +10,11 @@ state-test [--mode equivalence|satin] --fork Osaka|Amsterdam [options] .. - `--mode satin` is the report: it runs the same entries under Satin's own configuration, prints the counts by outcome, and exits zero unless a fixture file cannot be read. - `--fork` names the fork whose fixture entries run. - `--expect-executed N`, `--expect-skipped N` and `--expect-deviations` pin the counts of a full run; CI passes all three. +- `--json-digest` prints one JSON line per executed transaction on standard error: the test's identity and the hash of the canonical record of the transaction's whole Mega outcome. + `--json-digest-full` adds the record itself to each line. + The two make a whole-outcome differential: run both at two revisions, sort and compare (`sort | cmp`), and read the full lines of the ids that differ. +- `--limit-data-size BYTES`, `--limit-frame-data-size BYTES`, `--limit-kv-updates RECORDS`, `--limit-state-growth UNITS` and `--limit-compute-gas GAS` (Satin mode only) hold every transaction to tighter per-transaction limits than the spec's, so the limit-stop paths run across the corpus; the frame budget follows `--limit-data-size`. + The verdicts of such a run are expected to fail; it is for comparing digests. - `--summary-json FILE` writes the counts as JSON, `--json-outcome` prints one JSON line per test on standard error, `--trace` runs every test under an EIP-3155 tracer and `--threads` sets the worker count. ```bash diff --git a/crates/state-test/src/main.rs b/crates/state-test/src/main.rs index 7c24e0cdd..a95facd70 100644 --- a/crates/state-test/src/main.rs +++ b/crates/state-test/src/main.rs @@ -17,8 +17,8 @@ use std::{path::PathBuf, process::ExitCode}; use clap::Parser; use state_test::{ deviations, - runner::{find_json_files, run, Config, Outcome, Report, Summary, TestResult}, - Fork, Mode, + runner::{find_json_files, run, Config, DigestForm, Outcome, Report, Summary, TestResult}, + EvmTxRuntimeLimits, Fork, Mode, }; /// How many unattributed failures, and how many unreproduced entries, the summary lists. @@ -47,6 +47,34 @@ struct Cmd { /// Print one JSON line per test to standard error. #[arg(long)] json_outcome: bool, + /// Print one JSON line per executed transaction on standard error: the test's identity and the + /// hash of the canonical record of the transaction's whole outcome (result, state, gas by + /// ledger, usage, logs, oracle reads), whatever the fixture's verdict. + #[arg(long)] + json_digest: bool, + /// As `--json-digest`, with the canonical record in each line, to see which field differs. + #[arg(long)] + json_digest_full: bool, + /// Satin mode: hold every transaction to this data-size limit, in bytes, instead of the + /// spec's; the frame budget follows it unless `--limit-frame-data-size` names one. + #[arg(long, value_name = "BYTES")] + limit_data_size: Option, + /// Satin mode: cap every frame's data-size budget at this many bytes. + #[arg(long, value_name = "BYTES")] + limit_frame_data_size: Option, + /// Satin mode: gas detention's two caps, the compute a transaction may still spend once it + /// read volatile data, instead of the spec's. + #[arg(long, value_name = "GAS")] + limit_compute_gas: Option, + /// Satin mode: hold every transaction to this many write records, its KV count, instead of + /// the spec's; every frame's budget is its share of what its parent has left. + #[arg(long, value_name = "RECORDS")] + limit_kv_updates: Option, + /// Satin mode: hold every transaction to this many new accounts and new slots, its state + /// growth, instead of the spec's; every frame's budget is its share of what its parent has + /// left. + #[arg(long, value_name = "UNITS")] + limit_state_growth: Option, /// Trace every test with an EIP-3155 tracer on standard error; runs on one thread. #[arg(long)] trace: bool, @@ -92,12 +120,26 @@ fn main() -> ExitCode { } else { cmd.threads.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())) }; + let limits = match tightened_limits(&cmd) { + Ok(limits) => limits, + Err(error) => { + eprintln!("error: {error}"); + return ExitCode::FAILURE; + } + }; + let digest = match (cmd.json_digest, cmd.json_digest_full) { + (_, true) => Some(DigestForm::Full), + (true, false) => Some(DigestForm::Compact), + (false, false) => None, + }; let config = Config { mode: cmd.mode, fork: cmd.fork, threads, json_outcome: cmd.json_outcome, trace: cmd.trace, + digest, + limits, deviations: deviations::DEVIATIONS, }; let report = run(&files, config); @@ -135,6 +177,42 @@ fn main() -> ExitCode { } } +/// The limits the `--limit-*` options name, over the spec's own, or none when no option is given. +fn tightened_limits(cmd: &Cmd) -> Result, String> { + if cmd.limit_data_size.is_none() && + cmd.limit_frame_data_size.is_none() && + cmd.limit_compute_gas.is_none() && + cmd.limit_kv_updates.is_none() && + cmd.limit_state_growth.is_none() + { + return Ok(None); + } + if cmd.mode == Mode::Equivalence { + return Err( + "the --limit-* options need --mode satin: equivalence mode holds no limit".into() + ); + } + let mut limits = EvmTxRuntimeLimits::default(); + if let Some(bytes) = cmd.limit_data_size { + limits = limits.with_tx_data_size_limit(bytes).with_frame_data_size_limit(bytes); + } + if let Some(bytes) = cmd.limit_frame_data_size { + limits = limits.with_frame_data_size_limit(bytes); + } + if let Some(gas) = cmd.limit_compute_gas { + limits = limits + .with_block_env_access_compute_gas_limit(gas) + .with_oracle_access_compute_gas_limit(gas); + } + if let Some(records) = cmd.limit_kv_updates { + limits = limits.with_tx_kv_update_limit(records); + } + if let Some(units) = cmd.limit_state_growth { + limits = limits.with_tx_state_growth_limit(units); + } + Ok(Some(limits)) +} + fn print_summary(report: &Report, summary: &Summary) { println!("{} mode, {} fixtures: {} files", report.mode, report.fork, summary.files); println!( diff --git a/crates/state-test/tests/cli.rs b/crates/state-test/tests/cli.rs index d9d3348d9..9d6fc4eab 100644 --- a/crates/state-test/tests/cli.rs +++ b/crates/state-test/tests/cli.rs @@ -159,6 +159,57 @@ fn test_bad_arguments_exit_non_zero() { } } +/// The digest options print one line per executed transaction on standard error: the compact form +/// the test and the hash of its record, the full form the record too, and the same line twice. +#[test] +fn test_the_digest_options_print_a_line_per_transaction() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + let lines = |flag: &str| -> Vec { + let output = state_test(&[flag, "--fork", "Osaka"], &path); + assert!(output.status.success(), "{}", stdout(&output)); + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.starts_with('{')) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + }; + let compact = lines("--json-digest"); + assert_eq!(compact.len(), 1); + assert_eq!(compact[0]["row"], "outcome"); + assert!(compact[0]["digest"].as_str().unwrap().starts_with("0x")); + assert!(compact[0].get("record").is_none()); + assert_eq!(compact, lines("--json-digest")); + + let full = lines("--json-digest-full"); + assert_eq!(full.len(), 1); + assert_eq!(full[0]["digest"], compact[0]["digest"]); + assert!(full[0]["record"]["rejected"].is_string(), "the transaction is rejected"); +} + +/// The limit options tighten Satin mode's limits; equivalence mode holds none, so it refuses them. +#[test] +fn test_the_limit_options_need_satin_mode() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture(dir.path(), "TransactionException.INTRINSIC_GAS_TOO_LOW"); + for option in [ + ["--limit-data-size", "1024"], + ["--limit-frame-data-size", "1024"], + ["--limit-compute-gas", "30000"], + ["--limit-kv-updates", "10"], + ["--limit-state-growth", "10"], + ] { + let mut args = vec!["--fork", "Osaka"]; + args.extend(option); + let output = state_test(&args, &path); + assert_eq!(output.status.code(), Some(1), "{option:?} in equivalence mode"); + assert!(String::from_utf8_lossy(&output.stderr).contains("--mode satin")); + + args.extend(["--mode", "satin"]); + assert!(state_test(&args, &path).status.success(), "{option:?} in Satin mode"); + } +} + /// A blockchain fixture of one empty block on a pre-state of one funded account, with /// `edit` applied to the block's header. With no pre-block contract and no transaction the block /// changes nothing on Ethereum, so its expected roots are the pre-state's and the empty trie's, diff --git a/docs/mega-evme/configuration/chain-and-spec.md b/docs/mega-evme/configuration/chain-and-spec.md index d7ae2e73a..e1a82cb37 100644 --- a/docs/mega-evme/configuration/chain-and-spec.md +++ b/docs/mega-evme/configuration/chain-and-spec.md @@ -63,7 +63,8 @@ On Satin, every output field keeps its legacy name and meaning, and one field is | `floor_gas` | The EIP-7623 floor the receipt's gas used cannot fall below | | `data_size` | Data-size bytes the transaction kept | | `write_records` | Account and storage write records it kept: its KV count | -| `limit_exceeded` | `null`, or the limit that stopped it: `kind` (`data_size`, `compute_gas`), `limit`, `used` | +| `state_growth` | New accounts and new storage slots it kept, net: its state growth | +| `limit_exceeded` | `null`, or the limit that stopped it: `kind` (`data_size`, `kv_updates`, `state_growth`, `compute_gas`), `limit`, `used` | | `limits_override` | Present only under `--override.limits`: the protocol limits the run was held to, in the shape the flag takes | In text mode the same numbers follow the summary under `=== Satin Gas ===`. @@ -76,7 +77,11 @@ A Satin run is held to Satin's protocol limits, which the spec fixes and no chai | Limit | Value | | ------------------------------------------------------------------------ | ---------- | | A transaction's data size (`txDataSizeLimit`) | 13,107,200 | +| A transaction's KV updates (`txKvUpdateLimit`) | 500,000 | +| A transaction's state growth (`txStateGrowthLimit`) | 1,000 | | A block's data size (`blockTxsDataLimit`) | 13,107,200 | +| A block's KV updates (`blockKvUpdateLimit`) | 500,000 | +| A block's state growth (`blockStateGrowthLimit`) | 1,000 | | Compute after a block-environment read (`blockEnvAccessComputeGasLimit`) | 20,000,000 | | Compute after an Oracle read (`oracleAccessComputeGasLimit`) | 20,000,000 | | A frame's data size beyond its share (`frameDataSizeLimit`) | unlimited | @@ -87,17 +92,22 @@ The values are provisional, as Satin is. `--override.limits` runs under other limits, a counterfactual. It takes a JSON object in the limits' shape, inline or as the path of a file. The fields it names replace Satin's, and every other stays. +A file written for the shape's first published version, without the KV-update and state-growth limits, runs with Satin's values for them. The whole shape, at Satin's values: ```json { "txRuntimeLimits": { "txDataSizeLimit": 13107200, + "txKvUpdateLimit": 500000, + "txStateGrowthLimit": 1000, "frameDataSizeLimit": 18446744073709551615, "blockEnvAccessComputeGasLimit": 20000000, "oracleAccessComputeGasLimit": 20000000 }, - "blockTxsDataLimit": 13107200 + "blockTxsDataLimit": 13107200, + "blockKvUpdateLimit": 500000, + "blockStateGrowthLimit": 1000 } ``` diff --git a/docs/spec/glossary.md b/docs/spec/glossary.md index 359d3df64..836fd79fd 100644 --- a/docs/spec/glossary.md +++ b/docs/spec/glossary.md @@ -64,6 +64,14 @@ _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) gas Drawn from the [reservoir](#reservoir) first, then from regular gas. +The accounts and fresh slots this gas prices are what Satin counts as state growth, limited per transaction, per frame and per block. + +The first effective `SELFDESTRUCT` of an account created in the same transaction refills this gas only for a part that was absent at the transaction's start: the account leaf, the code deposit and each new slot. +That refill goes to the destroying frame, including when another frame paid it. +A part that existed at the start is not refilled, and state growth does not fall for it. + +A failed deposit's created caller is counted as state growth and pays no state gas, and the limit does not stop that deposit. + See the [Satin](upgrades/satin.md) network upgrade. ## History gas @@ -72,6 +80,10 @@ _(Satin, unstable)_ Gas a transaction pays for the bytes it appends to the chain Drawn from the [reservoir](#reservoir) first, then from regular gas, and never scaled by SALT. +The first effective `SELFDESTRUCT` of an account created in the same transaction gives this gas back for each [write record](#write-record) it takes back, and for deployed code that was absent at the transaction's start and is deleted with the account. +That give-back goes to the destroying frame, including when another frame paid it. +Every other give-back of this gas goes to whoever paid it. + See the [Satin](upgrades/satin.md) network upgrade. ## Execution cap @@ -83,10 +95,28 @@ Gas limit above the cap goes to the [reservoir](#reservoir). _(Satin, unstable)_ The [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) state-gas reservoir: the part of a transaction's gas limit above the [execution cap](#execution-cap), which pays [state gas](#state-gas) and [history gas](#history-gas) before they spill onto regular gas. +The transaction's own frame, and a system call's outermost frame, receive the whole reservoir. + +A child frame of `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2`, and the creation a keyless deployment starts, receives `remaining − remaining × 2 / 100` of the caller's remaining reservoir, taken after every charge the caller makes for that start. + +The explicit gas argument does not bound that share. + +What the child does not spend returns to the caller, and a failed child's charges roll back as EIP-8037 specifies. +On every such return, whether the start was answered without building a frame or a built frame returns, the reservoir the child returns first unwinds the caller's outstanding spill, and the rest joins the reservoir the caller kept. +The part the caller kept is not drawn. +State gas and history gas share that spill. +The caller's own charge for a leaf the child did not add is given back after that. + ## Write record -_(Satin, unstable)_ One account or storage write a transaction keeps, 40 bytes of data size and of [history gas](#history-gas). +_(Satin, unstable)_ One account or storage write a transaction keeps, 40 bytes of data size and of [history gas](#history-gas): an account's record exists while the account's nonce, balance or code differs from what the transaction loaded, whichever writes changed it — a creation's created account included — and a slot's while its value differs from its original value in the transaction. The KV-update count is the number of write records. +The first effective `SELFDESTRUCT` of an account created in the same transaction takes back the write record of each part that was absent at the transaction's start — the account leaf and each new slot — with that record's data size and history gas. +A part that existed at the start keeps its record, because the account or the slot now differs from its original. +Deployed code is not a write record; the same destruction gives back the data size and history gas of code that was absent at the start. +A write to the account or to one of its slots after that mark makes no record. + +Satin limits that count per transaction, per frame and per block: `TX_KV_UPDATE_LIMIT` and `BLOCK_KV_UPDATE_LIMIT` are 500,000. ## History allowance @@ -180,6 +210,8 @@ One of four independent limits enforced per transaction: compute gas, data size, See [resource limits](evm/resource-limits.md). +_(Satin, unstable)_ Satin keeps data size, KV updates and state growth as limited dimensions, each per transaction, per frame and per block, and enforces compute through gas detention on regular gas, with no separate compute-gas limit. + ## Call frame A single execution context within a transaction, corresponding to a message call (CALL, STATICCALL, DELEGATECALL, CALLCODE) or a contract creation (CREATE, CREATE2) as defined in the [Ethereum Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf). @@ -190,6 +222,8 @@ Call frames nest: each CALL or CREATE within a transaction creates a child call Resource trackers (data size, KV updates, state growth) are call-frame-aware — usage within a child call frame is discarded if the child reverts. +_(Satin, unstable)_ A child frame's budget in each of data size, KV updates and state growth is `parent_remaining × 98 / 100`, rounded down. + ## Call-frame-local exceed When a call frame exceeds its per-call-frame resource budget, the call frame **reverts** with `MegaLimitExceeded(uint8 kind, uint64 limit)`. @@ -200,6 +234,10 @@ Distinct from a transaction-level exceed, which **halts** the entire transaction Per-call-frame resource budgets are introduced in Rex4. +_(Satin, unstable)_ Satin stops the frame that crosses a limit with that same revert, the transaction's own frame included, and the caller continues. + +The `kind` values are 0 for data size, 1 for KV updates, 2 for detention's compute limit and 3 for state growth. + ## Spec (`MegaSpecId`) A set of MegaETH verifiable behaviors: the complete definition of what a correct node does at a given stage. diff --git a/docs/spec/hardfork-spec.md b/docs/spec/hardfork-spec.md index 3c1e25f79..c507445d9 100644 --- a/docs/spec/hardfork-spec.md +++ b/docs/spec/hardfork-spec.md @@ -193,12 +193,12 @@ It restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka) rather - **Two-pool gas** — [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 per-transaction execution cap, with the rest of the gas limit as a state-gas reservoir, replacing the [dual gas model](evm/dual-gas-model.md). - **State gas** — EIP-8037's byte counts at MegaETH's cost per state byte, scaled by the [SALT bucket](glossary.md#salt-bucket) the state lands in. - **History gas** — a price per byte on the transaction body, logs, write records and deployed code, replacing the storage gas on logs and calldata, the intrinsic storage gas, and the [storage gas stipend](glossary.md#storage-gas-stipend). -- **Resource limits** — data size per transaction, with no KV-update, state-growth or separate compute-gas limit; every limit stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, which its caller can catch. +- **Resource limits** — data size, KV updates (500,000) and state growth (1,000), each per transaction, per frame at 98/100 of what the parent has left, and per block, with no separate compute-gas limit; every limit stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, which its caller can catch. - **[Gas detention](evm/gas-detention.md)** — enforced on the gas a frame is allowed to spend, withholding the rest inside the frame's own gas. -- **[EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs**, the `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` opcodes, and 63/64 gas forwarding. +- **[EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs**, the `DUPN`, `SWAPN`, `EXCHANGE` and `SLOTNUM` opcodes, and 98/100 forwarding of regular gas and of the reservoir. - **[KeylessDeploy](system-contracts/keyless-deploy.md)** — the deployment runs as a native creation frame instead of a sandbox. - **System calls** — at most 30,000,000 of a system call's gas is regular gas, and the pre-block calls run before every block; the block in which Satin activates checks that the system contracts and the EIP-7997 factory hold the code Satin runs, and Satin deploys none of them. - **Live system address** — every transaction reads the [SequencerRegistry](system-contracts/sequencer-registry.md) itself, and a system-address transaction without the system shape is invalid. -- **Block limits** — data size is a packing budget that never refuses a deposit or a Mega System Transaction. +- **Block limits** — data size, KV updates and state growth are packing budgets that never refuse a deposit or a Mega System Transaction. _See [Satin Network Upgrade](upgrades/satin.md) for the current state._ diff --git a/docs/spec/overview.md b/docs/spec/overview.md index 3854c1540..acd4cbc4a 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -51,7 +51,7 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview Satin (unstable): base layer and reference implementation Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. -Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 (`v40.0.3-mega.4`), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 (`v20.0.0-mega.3`), and alloy-evm 0.36. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `2fc8edf33b2ffddb195cebc17be9adabfd95417c` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `f599efdabc3e5b36a280f1aa72978751bd64c160` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. See the [Satin Network Upgrade](upgrades/satin.md).
@@ -83,7 +83,7 @@ Contracts deployed under a given spec will continue to behave identically, regar - **REX4** — Per-call-frame resource budgets, relative gas detention, [storage gas stipend](glossary.md#storage-gas-stipend), MegaAccessControl and MegaLimitControl system contracts. - **REX5** — SequencerRegistry system contract, Oracle v2.0.0 with dynamic system address, caller-account update deduplication, storage-gas-stipend separated-allowance model, value-transfer CALL/CALLCODE parent compute-gas attribution, CREATE code-deposit compute-gas atomicity, EIP-2935/EIP-4788 pre-block gas floor with fail-closed block rejection, CREATE2 empty-initcode short-circuit, KeylessDeploy trailing-bytes rejection and empty-code log forwarding. - **REX6** — Unified per-opcode gas metering order, consolidated EIP-7702 authorization accounting, CREATE-frame accounting corrections, KeylessDeploy sandbox hardening, post-execution fee-reward accounting, system-originated transaction metering exemption, extended beneficiary detention coverage, and SequencerRegistry v2.0.0 rotation hardening. -- **SATIN** — The **unstable** spec, not scheduled on any network. Restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka): EIP-8037 regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas, revert-class limit stops, gas detention on withheld gas, EIP-7708 transfer logs, native KeylessDeploy creation, and block limits as packing budgets. +- **SATIN** — The **unstable** spec, not scheduled on any network. Restates MegaETH's execution rules on Optimism Karst (Ethereum Osaka): EIP-8037 regular gas under a 200,000,000 execution cap with a state-gas reservoir, 98/100 forwarding of regular gas and of that reservoir, SALT-scaled state gas, history gas, data-size, KV-update (500,000) and state-growth (1,000) limits per transaction, per frame and per block, revert-class limit stops, gas detention on withheld gas, EIP-7708 transfer logs, native KeylessDeploy creation, and data-size, KV and state-growth block limits as packing budgets. See [Hardforks and Specs](hardfork-spec.md) for full details. diff --git a/docs/spec/upgrades/overview.md b/docs/spec/upgrades/overview.md index 588768154..3b05e9229 100644 --- a/docs/spec/upgrades/overview.md +++ b/docs/spec/upgrades/overview.md @@ -153,7 +153,7 @@ Not yet scheduled {% endtabs %} Unstable; under active development. -Optimism Karst (Ethereum Osaka) base, [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 execution cap with a state-gas reservoir, SALT-scaled state gas, history gas per byte appended, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs, native [KeylessDeploy](../system-contracts/keyless-deploy.md) creation, system calls on 30,000,000 regular gas plus reservoir, the live system address read by the transaction, the block's data-size limit as a packing budget, and the EIP-7997 factory. +Optimism Karst (Ethereum Osaka) base, [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) regular gas under a 200,000,000 execution cap with a state-gas reservoir, 98/100 forwarding of regular gas and of that reservoir to a child frame, SALT-scaled state gas, history gas per byte appended, data-size, KV-update (500,000) and state-growth (1,000) limits per transaction, per frame at 98/100 and per block, each stopping the frame that crosses it with a revert, gas detention on withheld gas, [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) transfer logs, native [KeylessDeploy](../system-contracts/keyless-deploy.md) creation, system calls on 30,000,000 regular gas plus reservoir, the live system address read by the transaction, the block's data-size, KV and state-growth limits as packing budgets that never refuse a deposit or a Mega System Transaction, and the EIP-7997 factory. ## How to Read These Pages diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 43fb960ee..c58567a6c 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -1,5 +1,5 @@ --- -description: Satin network upgrade (unstable) — MegaETH's execution rules restated on Optimism Karst (Ethereum Osaka) — EIP-8037 regular and state gas under a 200,000,000 execution cap with a state-gas reservoir, a history-gas ledger for the bytes a transaction appends, SALT-scaled state gas, limits that stop the frame that crosses them with a revert, gas detention on withheld gas, EIP-7708 transfer logs, keyless deployment as a native creation, system calls on a split budget, the live system address read by the transaction itself, the block's data-size limit as a packing budget, and the witness a stateless validator re-executes a block from. +description: Satin network upgrade (unstable). MegaETH's execution rules restated on Optimism Karst (Ethereum Osaka): EIP-8037 regular and state gas under a 200,000,000 execution cap with a state-gas reservoir, a history-gas ledger for the bytes a transaction appends, SALT-scaled state gas, data-size, KV and state-growth limits that stop the frame that crosses them with a revert, 98/100 forwarding of regular gas and of the reservoir, gas detention on withheld gas, EIP-7708 transfer logs, keyless deployment as a native creation, system calls on a split budget, the live system address read by the transaction itself, block data-size, KV and state-growth limits as packing budgets, and the witness a stateless validator re-executes a block from. --- # Satin Network Upgrade @@ -19,27 +19,30 @@ A transaction's gas is split into regular gas, which pays for computation and is State growth is paid in [state gas](../glossary.md#state-gas) — EIP-8037's byte counts at MegaETH's own cost per state byte, scaled by the [SALT bucket](../glossary.md#salt-bucket) the state lands in — and the bytes a transaction appends to the chain's history (its body, its logs, its [write records](../glossary.md#write-record), its deployed code) are paid in a third ledger, [history gas](../glossary.md#history-gas). Together they replace [storage gas](../glossary.md#storage-gas), the 39,000 intrinsic storage gas, the 10× multiplier on logs and calldata, and the 23,000-gas [storage gas stipend](../glossary.md#storage-gas-stipend). -The per-transaction resource limits keep data size and drop the KV-update, state-growth and compute-gas limits: write records are bounded by the data size they weigh and priced in history gas, state growth is priced in state gas, and compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md). -Every limit — data size and detention's compute limit — now stops the frame that crosses it with a revert carrying `MegaLimitExceeded(kind, limit)` instead of a halt: the frame's caller can catch the stop and carry on within what the limits leave, and a transaction whose own frame is stopped pays only for what ran. +The per-transaction resource limits are data size, KV updates and state growth, each also limited per frame and per block. +Write records are the KV count, weighed as data size and priced in history gas. +State growth is the net count of new accounts and new slots, and it is priced in state gas. +Compute is regular gas, bounded by the execution cap and by [gas detention](../evm/gas-detention.md), and Satin keeps no separate compute-gas limit. +Every limit, data size, KV updates, state growth and detention's compute limit, stops the frame that crosses it with a revert carrying `MegaLimitExceeded(kind, limit)`: the frame's caller can catch the stop and carry on within what the limits leave, and a transaction whose own frame is stopped pays only for what ran. Detention holds each frame's spendable regular gas inside the frame's own gas, so a transaction that read volatile data runs exactly as it would have without the read until a regular charge needs the gas it is not allowed to spend. -Satin also brings EIP-7708 transfer logs, deploys a `keylessDeploy` transaction as a native creation instead of in a sandbox, runs system calls on at most 30,000,000 of regular gas with the rest as reservoir, has a system-address transaction read the live system address itself, and makes the block's data-size limit, its one block-level execution limit, a packing budget that never refuses a deposit or a Mega System Transaction. +Satin also brings EIP-7708 transfer logs, deploys a `keylessDeploy` transaction as a native creation instead of in a sandbox, runs system calls on at most 30,000,000 of regular gas with the rest as reservoir, has a system-address transaction read the live system address itself, and makes the block's data-size, KV and state-growth limits packing budgets that never refuse a deposit or a Mega System Transaction. Satin follows [Rex6](rex6.md) on the spec ladder, so every **Previous behavior** below is Rex6's. Satin does not add to the Rex6 rules one by one: it restates the execution layer, and a Rex6 rule this page does not carry over does not apply under Satin. The changes, in the order this page records them: -1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 transaction gas cap. +1. **Base layer.** Optimism Karst (Ethereum Osaka), four Amsterdam opcodes, and no EIP-7825 or EIP-8037 transaction gas cap. 2. **Precompiles.** Karst's set, with KZG point evaluation still at 100,000. 3. **Contract size limits.** 512 KiB of code and 1 MiB of initcode. -4. **Two-pool gas.** EIP-8037 regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. +4. **Two-pool gas.** EIP-8037, as of 4 September 2026, regular gas and state-gas reservoir under a 200,000,000 execution cap, and three gas ledgers. 5. **Gas schedule and intrinsic gas.** Amsterdam's schedule, EIP-8038's state-access prices included, and EIP-2780 intrinsic cost. 6. **State gas and SALT pricing.** `entry × multiplier` on EIP-8037's byte counts, replacing `base × (multiplier − 1)`. 7. **History gas.** A price per byte on everything a transaction appends to history. 8. **History allowance.** A 160-byte allowance for value calls, replacing the 23,000-gas storage gas stipend. -9. **Gas forwarding.** The standard 63/64 rule, replacing 98/100. -10. **Resource limits.** Data size over a byte table and write records, and no KV-update, state-growth or compute-gas limit. +9. **Gas forwarding.** 98/100 of regular gas, as in Rex6, in place of 63/64, and 98/100 of the caller's remaining reservoir to a child frame. +10. **Resource limits.** Data size, KV updates and state growth, per transaction, per frame at 98/100, and per block, with no separate compute-gas limit. 11. **The revert-class stop.** Every limit stops the frame that crosses it with a revert, which its caller can catch. 12. **Gas detention on withheld gas.** 13. **Volatile-data access control and `remainingComputeGas()`.** @@ -67,7 +70,9 @@ The changes, in the order this page records them: - Satin builds on Optimism Karst, whose Ethereum base is Osaka. Every standard EVM, transaction and block rule this page does not override MUST be Karst's, including the Optimism changes of Jovian and Karst and the Ethereum changes of Osaka (for example `CLZ`, [EIP-7939](https://eips.ethereum.org/EIPS/eip-7939)). - The per-transaction gas limit cap of [EIP-7825](https://eips.ethereum.org/EIPS/eip-7825) MUST NOT be applied. - The execution cap of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) bounds a transaction's regular gas instead, and a transaction's gas limit is bounded by the block's gas limit; a block builder MAY refuse a larger declared gas limit as building policy, which a node validating a block does not apply (see [Block Limits](#20-block-limits)). + The execution cap of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model) bounds a transaction's regular gas instead, and a transaction's gas limit is bounded by the block's gas limit. + The EIP-8037 cap `TX_MAX_TOTAL_GAS_LIMIT` = 2^32 − 1 MUST NOT be applied either. + A block builder MAY refuse a larger declared gas limit as building policy, which a node validating a block does not apply (see [Block Limits](#20-block-limits)). - A node MUST enable four opcodes that Osaka does not have: `DUPN` (`0xE6`), `SWAPN` (`0xE7`) and `EXCHANGE` (`0xE8`) from [EIP-8024](https://eips.ethereum.org/EIPS/eip-8024), and `SLOTNUM` (`0x4B`) from [EIP-7843](https://eips.ethereum.org/EIPS/eip-7843). `SLOTNUM` MUST push the block's slot number, an unsigned 64-bit integer the node supplies with the block. The slot number has no absent value: a block for which the node supplies no other number runs with slot number zero, which `SLOTNUM` pushes like any other. @@ -121,6 +126,8 @@ A KZG call given at least 100,000 gas that fails otherwise — an input of the w - Deployed code MUST be at most `MAX_CONTRACT_SIZE` = 524,288 bytes. - Initcode MUST be at most `MAX_INITCODE_SIZE` = 1,048,576 bytes, twice the code limit, the ratio [EIP-3860](https://eips.ethereum.org/EIPS/eip-3860) sets between the two. +- These are Ethereum's size checks at MegaETH's sizes, not resource limits: initcode over `MAX_INITCODE_SIZE` MUST halt the creating frame at the creation opcode, and deployed code over `MAX_CONTRACT_SIZE` MUST halt the creation, each consuming the halting frame's gas as Ethereum does. + Neither is the [revert-class stop](#11-the-revert-class-stop) a resource limit makes. - The creation opcodes MUST make their checks and charges in this order: the static context; the value, offset and size operands, and the size's range; the initcode size; EIP-3860's initcode cost; the offset's range and the memory the initcode is read from (neither checked for empty initcode); for `CREATE2`, the salt operand, then the 12,000 and the hashing cost of the initcode, and for `CREATE` the 12,000. Satin adds no charge ahead of these. So a creation in a static frame fails before its operands are read, and a `CREATE2` short of its salt pays the initcode cost and the memory first: the halt consumes the frame's gas either way, but under [gas detention](#12-gas-detention-on-withheld-gas) those charges can be the crossing, which stops the frame with a revert where the stack underflow would have halted it. @@ -136,7 +143,24 @@ A KZG call given at least 100,000 gas that fails otherwise — an input of the w #### New behavior -A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amsterdam applies it, with the parameters below. +A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) (4 September 2026), with the parameters below, and with the later changes this section names. +Satin adopts the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef) (4 September 2026) as the reference implementation performs it, and does not adopt the transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950) (14 September 2026). +On the return of every start, whether the start is answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns, the reservoir the child returns MUST first unwind the caller's outstanding spill, and the rest MUST join the reservoir the caller kept. +`d = min(returned reservoir, the caller's outstanding spill)`. +The caller's regular gas increases by `d`, its spill decreases by `d`, and its reservoir increases by the returned reservoir less `d`. +The reservoir the caller kept MUST NOT be drawn. +State charges and history charges share that spill (see [History Gas](#7-history-gas)). +A successful child's own spill MUST be added to the caller's spill before this unwind. +A revert or a halt MUST NOT add the child's spill: the child's rollback already credited that spill to the gas the child returns, and a halt then consumes it. +A node MUST NOT cap a transaction's gas limit at `TX_MAX_TOTAL_GAS_LIMIT` = 2^32 − 1. +The gas limit stays bounded by the block's gas limit. +That cap stays open until EIP-8037 is final. +An authority charge made before the first frame is not committed out of the outstanding spill when that frame starts. +The reservoir the first frame returns unwinds that spill by the same rule, together with any other spill still outstanding. +A failure of the first frame returns no reservoir that charge had already drawn, so the charge stays (see [The Revert-Class Stop](#11-the-revert-class-stop)). +That is the failure outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) (14 September 2026), and not its commit of the pre-execution spill, which would keep a later return from unwinding it. +A creation does not collide on storage (see [Resource Limits](#10-resource-limits)), which is the collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) (18 September 2026). +The removal of an unused counter ([commit `052029f362`](https://github.com/ethereum/EIPs/commit/052029f3625328d6f51dec8e62a7090201e66f17)), the co-author lines and the move to Last Call change no rule a transaction executes, and Satin does not track them. - **The execution cap.** `EXECUTION_CAP` = 200,000,000. @@ -157,11 +181,21 @@ A node MUST apply [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037), as Amster A state charge (see [State Gas](#6-state-gas-and-salt-pricing)) and a history charge (see [History Gas](#7-history-gas)) MUST draw the reservoir first and spill onto the regular budget only past it. `GAS` MUST return the regular budget the frame has left, not the reservoir. - **Frames.** - A call or creation MUST forward regular gas as the inherited rules have it (see [Gas Forwarding](#9-gas-forwarding)), and the child MUST inherit the caller's whole reservoir; what the child leaves of the reservoir returns to the caller. - When a frame reverts or halts, the state and history gas it charged MUST be given back: the part the reservoir paid returns to the reservoir, and the part that spilled returns to the frame's regular budget. + A call or creation MUST forward regular gas as [Gas Forwarding](#9-gas-forwarding) specifies. + The transaction's own frame, and a system call's outermost frame, MUST receive the whole reservoir: there is no caller to retain a share from. + A child frame of `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2`, and the creation a keyless deployment starts, MUST receive `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left after every charge the caller makes for that start, and the caller MUST keep the rest. + `remaining` is that reservoir, and the division is integer division, truncating toward zero. + The regular gas the caller asks to forward MUST NOT bound `reservoir_share`. + What the child leaves of its share MUST return to the caller by the child-merge rule above. + When a frame reverts or halts, the state and history gas it charged MUST be given back as [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) specifies: the part the reservoir paid returns to the reservoir, and the part that spilled returns to the frame's regular budget. A revert then returns the frame's unspent regular gas to its caller; an exceptional halt consumes it, the returned spill included. + A failed child therefore returns the share it was given, whether the start was answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns. + That share unwinds the caller's outstanding spill before the rest joins the reservoir the caller kept. + When the caller has no outstanding spill, the caller holds the reservoir it had after the charges it made for the start. + The caller's own charge for a leaf the child did not add is given back after that. - **The transaction.** When the transaction ends, the reservoir left MUST return to the sender, and so MUST the unspent regular gas unless the transaction's own frame halted; this holds when the transaction reverts or is stopped by a limit (see [The Revert-Class Stop](#11-the-revert-class-stop)). + A failed deposit is the exception: it MUST use its whole gas limit, the reservoir included, and nothing returns (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)); a deposit that succeeds, reverts or is stopped by a limit is not a failed deposit and settles as above. The receipt's gas used is what the transaction spent from both pools — regular, state and history gas together — after the inherited refund and floor rules. When that spend less the refund is below the floor, the gas used MUST be the floor and no refund is made: the sender gets back its gas limit less the floor, the floor's excess over the spend coming out of the unspent regular gas and the reservoir alike. - **Three ledgers.** @@ -257,8 +291,10 @@ The EIP-2780 intrinsic regular gas of a transaction MUST be `TX_BASE_COST` = 12, A transfer to the sender itself pays the base alone. The 7,816 per authorization MUST be charged as every intrinsic entry is, by the transaction's validation; an authority that already exists is refunded nothing when its authorization is applied. The state-dependent parts — a recipient or created account that does not exist, an authority that does not exist, a delegation indicator, an authority's first write — MUST be charged at the start of execution, as EIP-2780 and EIP-8037 specify, with every state charge priced as [State Gas](#6-state-gas-and-salt-pricing) says. +The delegation-indicator charge is at most once per authority, and only when the authority holds no indicator at the start of the transaction and no earlier authorization in the list set one (see [Resource Limits](#10-resource-limits)). A deposit-like transaction whose caller account does not exist MUST be charged the new-account state gas for it exactly once. A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an authorization's charges, the history of the write records made outside a frame (see [History Gas](#7-history-gas)), or a charge for the first frame's start — MUST run out of gas without running a frame. +A list that the KV or state-growth limit skips is not charged, and this out-of-gas path does not apply to it (see [Resource Limits](#10-resource-limits)). Everything applied before the first frame, other than what validation did to the sender's account (its fee and a call's nonce) and the account a deposit-like transaction creates for its caller, is then taken back: the applied EIP-7702 authorizations with their nonce and delegation writes, the sender's own authorization included, their state gas and their write records. The intrinsic gas and the body's history gas stay charged, the rest of the regular budget is consumed, and what is left of the reservoir returns to the sender; the sender of a creation keeps the nonce bump the creation would have made. A deposit that runs out of gas this way is instead a failed deposit, which uses its whole gas limit, reservoir included (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). @@ -268,6 +304,7 @@ A creation that cannot pay any of the four runs out of gas and leaves no code. A node MUST charge account access to the addresses the inherited rules treat as warm from the start of a transaction — precompiles, the block beneficiary and access-list addresses listed without storage keys — as warm, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) has it: Rex6's cold charge on the first `CALL`-family or `SELFDESTRUCT`-beneficiary touch of such an address does not apply. The `SequencerRegistry`'s account and its `_currentSystemAddress` slot MUST be warm from the start of every transaction as well, the slot as an access-list storage key is: validation reads both for every transaction (see [The Live System Address](#17-the-live-system-address)). +The sender, and the recipient of a call, are warm from the start as well, as [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) leaves them. ### 6. State Gas and SALT Pricing @@ -283,19 +320,24 @@ Every EIP-8037 state charge MUST be `entry × m`: - `entry` — the schedule's state-gas entry: EIP-8037's byte count of the state times `COST_PER_STATE_BYTE` = 1,530. - `m` — the multiplier of the [SALT bucket](../glossary.md#salt-bucket) the state lands in, `floor(bucket_capacity / MIN_BUCKET_SIZE)` with `MIN_BUCKET_SIZE` = 256. -| State | Bytes | `entry` at `m = 1` | Bucket | -| --------------------------------------- | ----- | ------------------ | --------------------- | -| Fresh storage slot (`SSTORE` 0 → non-0) | 64 | 97,920 | The slot's | -| New account | 120 | 183,600 | The account's | -| Created contract account | 120 | 183,600 | The created account's | -| Deployed code, per byte | 1 | 1,530 | The created account's | -| EIP-7702 delegation indicator | 23 | 35,190 | The authority's | +| State | Bytes | `entry` at `m = 1` | Bucket | +| ---------------------------------------------------------------------- | ----- | ------------------ | --------------------- | +| Fresh storage slot (`SSTORE`, original and present zero, new non-zero) | 64 | 97,920 | The slot's | +| New account | 120 | 183,600 | The account's | +| Created contract account | 120 | 183,600 | The created account's | +| Deployed code, per byte | 1 | 1,530 | The created account's | +| EIP-7702 delegation indicator | 23 | 35,190 | The authority's | - A state charge MUST be made where the state is added: a fresh slot by the `SSTORE` that fills it; a new account by the `CALL` that moves value to it, by a `SELFDESTRUCT` that moves a balance to it, by the transaction whose value creates it, and by an applied EIP-7702 authorization that creates it; a created account by `CREATE`, `CREATE2` or a creation transaction. - `m` scales state gas and nothing else: regular gas never scales. - A bucket's multiplier MUST be read at most once per transaction: every later charge, and every give-back, in that bucket MUST use the same `m`, so a give-back cancels its charge exactly. - A bucket capacity below `MIN_BUCKET_SIZE`, or a capacity the node cannot read, is a fault of the node, including for a deposit: the transaction MUST NOT be priced at any multiplier or settled, and the node MUST report an internal error (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). -- A slot restored to its original zero value in the same transaction MUST give its state gas back at the price it was charged, as EIP-8037 specifies: first to the frame's regular gas, up to what the frame's state charges spilled onto it, and the rest to the reservoir. +- The only `SSTORE` that charges fresh-slot state gas is one whose original value is zero, whose present value is zero, and whose new value is not. + The only `SSTORE` that refills it is one whose original value is zero, whose present value is not, and whose new value is zero, except on an account marked for deletion (see [Resource Limits](#10-resource-limits)), and that refill MUST be the price the slot was charged, in the refill order of [History Gas](#7-history-gas). + Every other `SSTORE` transition charges no fresh-slot state gas and refills none. + That is the same transition table as the state-growth change of an `SSTORE` (see [Resource Limits](#10-resource-limits)). +- The first effective `SELFDESTRUCT` of an account created in the same transaction refills state gas for each part the [destruction table](#the-destruction-table) names. + EIP-8037 specifies that this destruction produces no state-gas refills. - The protocol's own transactions MUST be priced at `m = 1` whatever their buckets hold (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)). A deposit that is not system-originated is not one of them and MUST be priced by bucket, although it pays no history gas (see [History Gas](#7-history-gas)). @@ -335,20 +377,37 @@ When each charge is made: A gas limit that cannot cover it MUST make the transaction invalid (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). The body's history gas MUST NOT be reported on the state ledger. - The records of the applied EIP-7702 authorities, and the record the transaction's own frame makes (its value's recipient or its created account), MUST be charged before the first frame. - The authorities' records are the transaction's own and MUST be kept when the first frame fails or is stopped; the first frame's record is that frame's, and comes back with it. + A list the KV or state-growth limit skips has no authority records, and that history is not charged. + The authorities' records are the transaction's own and MUST be kept when the first frame fails or is stopped. + The first frame's record is that frame's. + Its history gas comes back with that frame when the frame fails or is stopped. + When the destruction table takes that record back inside a first frame that then succeeds, the charge has already come back with the table, and the settlement MUST NOT give that history gas back a second time. + When that first frame then fails, the table's give-back is discarded with the table, and the settlement MUST give the charge back once. A transaction that runs out of gas before its first frame keeps neither: the out-of-gas takes the authorizations back with their records (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). -- A log, a storage write's record and the record of a `SELFDESTRUCT`'s beneficiary MUST be charged by the opcode, once it completed. +- A log, a storage write's record and the records of a `SELFDESTRUCT` — the account it clears and its beneficiary — MUST be charged by the opcode, once it completed, and a record the opcode takes back — a slot written back to its original value, an account a `SELFDESTRUCT` returns to what the transaction loaded, and each part the [destruction table](#the-destruction-table) takes back — MUST be given back by it then, before what it makes is charged. + A part the table takes back is given back to the destroying frame, including when another frame paid it. + Every other record is given back to whoever paid it. An opcode that fails after its write was observed — an `SSTORE` or a `SELFDESTRUCT` that cannot pay the gas it charges after its load — keeps nothing and is charged no history; a `LOG` observes its write after every charge of the inherited opcode, so only the limits and its history charge, below, can fail it after its write was observed. -- A `CALL`, `CALLCODE`, `CREATE` or `CREATE2` MUST charge its own frame for the records the frame it starts makes (a value transfer's sender and recipient; a creation's creator nonce and created account), after the gas it forwards is computed, so the forward is not reduced by them. +- A `CALL`, `CALLCODE`, `CREATE` or `CREATE2` MUST charge its own frame for the records the frame it starts makes (the accounts a value transfer changes from what the transaction loaded; a creation's created account, unless the transaction changed it already, and, when the bump changes the creator's account from what the transaction loaded, its creator nonce — see [Resource Limits](#10-resource-limits)), after the gas it forwards is computed, so the forward is not reduced by them. A caller that cannot pay MUST halt with out-of-gas, and the frame MUST NOT start. - A value `CALL` to an empty account (EIP-161) MUST charge its caller in this order: its regular gas — the access's static 100, memory, the value transfer, then the cold surcharge with the new account's regular gas, which is zero — then the new account's state gas, reservoir first, then the 63/64 forward of the regular gas left, then the history of the start's records; a state charge that spills onto the regular budget so shrinks the forward, and the records' history does not. - A `CREATE` or `CREATE2` likewise charges the created account's state gas, when the account at the created address is empty, before it computes the forward. + The price of a record the start takes back — an account the transfer returns to what the transaction loaded — MUST be given back to the caller once the frame returned with its start kept. + A value `CALL` to an empty account (EIP-161) MUST charge its caller in this order: its regular gas — the access's static 100, memory, the value transfer, then the cold surcharge with the new account's regular gas, which is zero — then the new account's state gas, reservoir first, then the 98/100 forward of the regular gas left (see [Gas Forwarding](#9-gas-forwarding)), then the history of the start's records; a state charge that spills onto the regular budget so shrinks the forward, and the records' history does not. + That forward is regular gas only. + The child is given its reservoir share after the history charge, from the reservoir the charge left the caller, and the gas the caller asks to forward does not bound the share. + A `CREATE` or `CREATE2` likewise charges the created account's state gas, when the account at the created address is empty, before it computes the forward, and gives the creation its reservoir share at the same point a call does, after the history of the start's records. - Deployed code MUST be charged at the deposit (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). -- What a frame does not keep — a failed frame's records and logs, a slot written back to its original value — MUST be given back at the price it was charged, to whoever paid it. +- What a frame does not keep — a failed frame's records and logs, a slot written back to its original value, an account returned to what the transaction loaded — MUST be given back at the price it was charged, to whoever paid it. + A part the [destruction table](#the-destruction-table) takes back is the exception: it is given back to the destroying frame, including when another frame paid it, and a failure of that frame discards the give-back. -A record an opcode commits — a storage write, a log, a `SELFDESTRUCT`'s beneficiary — MUST be checked against the limits before its history is charged, so a record a limit refuses is not charged. +Every give-back of state gas or of history gas MUST follow one refill order. +The frame's regular gas is credited first, up to the spill still outstanding on that frame, and the rest goes to its reservoir. +State charges and history charges share that spill. +A give-back inside a frame uses this order, as the rollback of a failed frame does (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + +A record an opcode commits — a storage write, a log, a `SELFDESTRUCT`'s records — MUST be checked against the limits before its history is charged, so a record a limit refuses is not charged. A frame that cannot pay that history charge MUST halt with out-of-gas, keeping neither the record nor its bytes. At a frame start the order is the reverse: the calling opcode pays for the records before the frame starts and they are counted, so a caller that cannot pay runs out of gas first, and the charge for a start a limit stops is given back when the stopped frame returns. +The opcode charges the records the start makes as the state stands when it runs: a value the caller cannot fund, which revm refuses on the caller's account, makes no record and is charged nothing, the opcode seeing the caller's balance; a creation whose creator's nonce cannot be bumped starts no frame and is charged nothing, since the creation opcode refuses it before it charges for the start, as it refuses an endowment the creator cannot fund and a call depth past the limit: revm's creation opcode makes these three checks first under EIP-8037, before it reads the created address. These MUST NOT pay history gas: @@ -385,8 +444,49 @@ Where it binds, the gas used is the floor, drawn from the whole gas limit, the r #### New behavior -- A call or creation MUST forward regular gas under the inherited [EIP-150](https://eips.ethereum.org/EIPS/eip-150) rule: at most all but one 64th of the caller's remaining regular gas. -- The child inherits the caller's reservoir whole (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +- A `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` or `CREATE2` MUST cap the regular gas it forwards by Rex6's rule, in place of the [EIP-150](https://eips.ethereum.org/EIPS/eip-150) 63/64 rule: + + `forwarded_gas_cap = parent_remaining_gas − parent_remaining_gas × 2 / 100` + + `parent_remaining_gas` is the caller's remaining regular gas after the charges the opcode makes before the forward. + For a value-transferring `CALL` or `CALLCODE` those charges include the value-transfer cost of 11,300, which already contains the 2,300 stipend, so the stipend is not taken from `parent_remaining_gas` again. + The division is integer division, truncating toward zero. + The child's regular gas MUST be `min(requested_gas, forwarded_gas_cap)`, plus the 2,300 stipend for a value-transferring `CALL` or `CALLCODE` and for no other opcode. + The stipend is added to the child after the cap, and it is not taken from the caller's remaining gas. + The stipend is outside the cap, as Rex6 specifies: the cap applies to the forwarded portion, not to the stipend. + `requested_gas` MUST NOT raise the forwarded portion above `forwarded_gas_cap`. + `CREATE` and `CREATE2` have no gas operand, so each forwards `forwarded_gas_cap` and adds no stipend. + A value-transferring `CALL` whose caller has 10,000 regular gas left after the value-transfer charge forwards a cap of 9,800: the child receives 12,100 and the caller keeps 200. + The history allowance (see [History Allowance](#8-history-allowance-replaces-the-storage-gas-stipend)) stays outside the child's gas limit, as the storage-gas stipend did under Rex6. + +- The reservoir is not part of that cap. + The transaction's own frame, and a system call's outermost frame, MUST receive the whole reservoir. + A child frame MUST receive `reservoir_share = remaining − remaining × 2 / 100` of the reservoir its caller has left after every charge the caller makes for the start, the history of the start's records included, and the caller MUST keep the rest (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + `remaining` is that reservoir, under the same integer division. + The regular gas the caller asks to forward MUST NOT bound `reservoir_share`: a call that forwards no regular gas still forwards the share. + A keyless deployment's creation receives this share of the reservoir the call has left after the call's start charges (see [Native Keyless Deployment](#15-native-keyless-deployment)). + That creation's regular-gas forward is `min(gasLimitOverride, remaining gas)`, and the 98/100 cap does not apply to it, as Rex6's sandbox envelope was that minimum and the call charges nothing after the creation returns. + What the child leaves of its share MUST return to the caller by the child-merge rule of [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model). + A frame that reverts or halts gives its state and history charges back as EIP-8037 specifies. + A failed child therefore returns the share it was given, whether the start was answered without building a frame (a precompile, a call to an account with no code, an interceptor's answer) or a built frame returns. + That share unwinds the caller's outstanding spill before the rest joins the reservoir the caller kept. + When the caller has no outstanding spill, the caller holds the reservoir it had after the charges it made for the start. + The caller's own charge for a leaf the child did not add is given back after that. + The reservoir share uses this gas-forwarding formula. + A frame budget under [Resource Limits](#10-resource-limits) uses `remaining × 98 / 100`, rounded down. + The two 98/100 rules are different integers. + The subtraction gives the child 98 of a remaining 99, and the whole remaining value whenever that value is below 50, so a remaining 1 gives the child 1 and the caller 0. + The frame-budget multiplication gives the child 97 of 99 and 0 of 1. +- The fraction is Rex6's. + Rex6 replaced 63/64 because MegaETH's block gas limits run up to 10 billion, and 63/64 leaves enough gas at depth 1,024 to repeat the call-depth attack 63/64 was meant to stop. + The reservoir uses the same fraction for a second reason. + Satin's state-gas prices are far above Rex6's storage-gas prices, so a hard-coded gas argument that also bounded the reservoir would fail calls Rex6's single gas pool could pay, which is why EIP-8037 passes the reservoir whole. + Satin keeps the gas argument off the reservoir. + The caller keeps `remaining × 2 / 100`, and the child receives the share. + When `remaining` is below 50 that product is 0, so the child receives the whole reservoir and the caller keeps none of it. + A reservoir of 1 is that case. + A child that spends its whole share leaves the caller what the caller kept, which a gas argument of zero would not. + A system-originated transaction and a system call are exempt from the per-transaction limits (see [The Protocol's Own Transactions](#19-the-protocols-own-transactions)) and are not exempt from this split: the split is how the reservoir is handed to a child, not a limit. ### 10. Resource Limits @@ -399,41 +499,325 @@ Where it binds, the gas used is the floor, drawn from the whole gas limit, the r #### New behavior -One dimension is limited per transaction, data size; compute is not one (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)), and neither are KV updates or state growth. +Data size, KV updates and state growth are limited per transaction. +Compute is not a fourth limit (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)): it is regular gas, bounded by the execution cap and by gas detention. + +| Dimension | Counted in | Transaction limit | Frame budget | +| ------------ | -------------------------- | ------------------------------- | ------------ | +| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 | Yes | +| KV updates | Write records | `TX_KV_UPDATE_LIMIT` = 500,000 | Yes | +| State growth | New accounts and new slots | `TX_STATE_GROWTH_LIMIT` = 1,000 | Yes | -| Dimension | Counted in | Transaction limit | Frame budget | -| --------- | ----------------------- | ---------------------------- | ------------ | -| Data size | Bytes of the byte table | `TX_DATA_LIMIT` = 13,107,200 | Yes | +The same KV and state-growth numbers limit a block: `BLOCK_KV_UPDATE_LIMIT` = 500,000 and `BLOCK_STATE_GROWTH_LIMIT` = 1,000 (see [Block Limits](#20-block-limits)). - **Data size** counts the byte table of [History Gas](#7-history-gas), plus two items that pay no history: an EIP-7708 transfer log, counted as `TRANSFER_LOG_SIZE` = 160 bytes (a `LOG3` of one word), and an Oracle hint's payload, counted by its length before it is forwarded. - It counts the body before any frame; the applied authorities' records before the first frame; a frame start's records and transfer log when the frame starts; a storage write's record, a log, and a `SELFDESTRUCT`'s beneficiary record and transfer log once the opcode completed; deployed code once every deposit charge is made and before the creation commits; a hint before it is forwarded, on the transaction and on no frame's budget, unless it would cross the transaction's limit, in which case it is neither counted nor forwarded (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). + It counts the body before any frame; the applied authorities' records before the first frame; a frame start's records and transfer log when the frame starts; a storage write's record, a log, and a `SELFDESTRUCT`'s records (the account it clears and its beneficiary) and transfer log once the opcode completed; deployed code once every deposit charge is made and before the creation commits; a hint before it is forwarded, on the transaction and on no frame's budget, unless it would cross the transaction's limit, in which case it is neither counted nor forwarded (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). A deposit's data size is counted like any transaction's, and a deposit that fails keeps what it counted: its body and the hints it admitted. - **Write records.** - One record per account or storage write the transaction keeps: a slot's first change in the transaction (taken back when the slot is written back to its original value); a value transfer's sender and recipient; a creation's creator nonce and created account; a `SELFDESTRUCT` that moves a balance to another account (its beneficiary); an applied EIP-7702 authority; the transaction's value recipient or created account. - The sender's account is one of the body's five fixed records and MUST NOT be counted as a record again, whatever writes it: a frame running as the sender, a value transfer or a `SELFDESTRUCT` that moves value to the sender, an applied EIP-7702 authority that is the sender, and a keyless deployment whose signer is the sender record nothing for it. - The four fee accounts are in the body only for the fee credits the transaction's settlement makes: a write execution makes to a fee account that is not the sender — for example a value transfer to it, a `SELFDESTRUCT` that moves a balance to it, or an applied EIP-7702 authority that is one of them — MUST be recorded like a write to any other account. - Records MUST be deduplicated per frame, not per transaction: a frame records an account once, and each value-transferring call records its target on the lane of the frame it starts, which merges into the caller's when the call succeeds. - N value transfers from one frame to the same recipient keep N records and pay N records' history gas, so a transaction's record count is an upper bound on the accounts it wrote, like the body's fixed fee-account records. - A value-transferring `CALLCODE` moves the value from the calling account to that same account: it MUST record that account once, as the transfer's sender, with no recipient record beside it, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. - A value-transferring `CALL` to the calling account itself MUST likewise record that account once, its recipient being its sender, and pay one record's history gas — or nothing, if the calling frame has already recorded its account. - A successful frame's records and bytes MUST merge into its caller's; a failed frame's MUST be discarded, except that a creator's nonce record survives its creation's failure once the nonce was bumped, and lands on the creator. - The KV count is the write-record count; every record weighs `WRITE_RECORD_SIZE` bytes of data size, counted and taken back with it, so `KV × 40 ≤ data size` at every point. - No limit holds the KV count: the data-size limit bounds it — a transaction keeps fewer than 327,680 write records (13,107,200 / 40) — and history gas prices every record (see [History Gas](#7-history-gas)). + One record per account or storage write the transaction keeps. + A storage slot's record exists while the slot's value differs from its original value in the transaction: the slot's first change makes it, and writing the slot back to its original value takes it back. + An account's record exists while the account's nonce, balance or code differs from what the transaction loaded — the account's original info, which revm sets at the account's first load in the transaction: a write that changes an unchanged account makes the record, a write that returns a changed account to what was loaded takes it back, and a write to an account that already differs adds nothing. + The writes: a value transfer's sender and recipient, on the balances the transfer leaves them; a creation's created account, which the creation leaves changed by its nonce, and the creator's nonce it bumps; a `SELFDESTRUCT`'s beneficiary and the account it clears; an applied EIP-7702 authority; the transaction's value recipient or created account. + A created account is no exception: an address the transaction changed before a creation lands on it — a value transfer funded it, or a `SELFDESTRUCT` paid it — differs already, and the creation adds no record for it. + A record is made where the write is and taken back where a write returns the account: a value transfer that returns an account to what the transaction loaded takes the record back in the frame the transfer starts, with its data size, and the history gas the record cost comes back to the caller once that frame returned with its start kept (see [History Gas](#7-history-gas)), as a storage slot written back gives its record back; a `SELFDESTRUCT` whose move returns an account takes the record back where the opcode completed. + The first effective `SELFDESTRUCT` of an account created in the transaction takes back, where the opcode completed, each write record the [destruction table](#the-destruction-table) names, and it leaves the record of a part that existed at the transaction's start. + Deployed code the table takes back returns its data size and its history gas there, and code is not a write record. + From that mark the account and its slots keep no further record, the account's logs stay charged, and a failure of the destroying frame discards the takeback, as the destruction table specifies. + So N value transfers from one frame to the same recipient keep one record for it and one for the sender, the first transfer having changed both; a transfer and its exact return keep none; a recipient that passes on exactly what it received keeps none of its own; a frame that funds an address and then creates at it keeps two records, its own and the address's: the transfer changed both, so neither the creator's nonce bump nor the creation adds one. + A value-transferring `CALLCODE` moves the value from the calling account to that same account, and a value-transferring `CALL` to the calling account itself likewise: neither changes an account, and neither records one. + The sender's account is one of the body's five fixed records and is never recorded again: validation changes it before execution, by its fee and a call's nonce, and a creation transaction's first frame by its nonce, so no write execution makes to it — a frame running as the sender, a value transfer or a `SELFDESTRUCT` that moves value to the sender, a keyless deployment whose signer is the sender — changes it from what the transaction loaded. + An applied EIP-7702 authority is changed by its nonce and its delegation when it is applied: a write to it afterwards adds nothing, the transaction's own value to it included. + The four fee accounts are in the body only for the fee credits the transaction's settlement makes, and are unchanged until execution writes them: a write execution makes to a fee account that is not the sender — for example a value transfer to it, a `SELFDESTRUCT` that moves a balance to it, or an applied EIP-7702 authority that is one of them — is recorded like a write to any other account. + A successful frame's records and bytes MUST merge into its caller's; a failed frame's MUST be discarded, the records it took back standing again, except that a creator's nonce record is the creating frame's: it MUST be counted on the creator once the creation returned with the nonce bumped, held to the creator's budget and not the creation's, and it survives the creation's failure. + The creation's budget MUST be the share taken at the opcode, before that record. + The KV count is the write-record count. + Every record weighs `WRITE_RECORD_SIZE` bytes of data size, counted and taken back with it, so `KV × 40 ≤ data size` at every point. + History gas prices every record (see [History Gas](#7-history-gas)). + `TX_KV_UPDATE_LIMIT` = 500,000, and the limit is enforced on that count. + A write record taken back cannot cross it. + At these constants 500,000 records weigh 20,000,000 bytes, more than `TX_DATA_LIMIT`, so the data-size cap is the tighter of the two. + That comparison is of the caps. + Under the execution cap a transaction cannot pay the regular gas of enough writes to reach either number, and the KV check is still made. + A later change to the byte weight or to the data-size cap does not retire it. + The count differs from Rex6's KV count where the write record differs, and each difference is that record: + - The sender and the four fee credits are the body's fixed records and are not KV. + Rex6 counts the caller as one KV update that cannot be discarded, and counts each distinct fee recipient after the result, where the count cannot change the outcome. + The body already bounds those writes, and a transaction that writes nothing keeps no record. + - Deduplication is the transaction-wide net change, not once per frame. + The record is the account or slot the transaction keeps changed, which is what history gas prices. + - A creation refused before the creator's nonce is bumped counts nothing, because nothing was written. + Rex6 records the creator even when no bump follows. + - Each applied authority is one record while the account differs from what the transaction loaded, not one record per authorization. + One account was changed once. + - Logs, deployed code, EIP-7708 transfer logs and Oracle hint payloads are not records, as they are not KV updates under Rex6 either. - **Frame budgets.** - The transaction's own frame MUST get what the transaction has left once its body and pre-frame records are counted; every child MUST get `FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR` = 98/100 of what its parent has left, rounded down. + Data size, KV updates and state growth each have a frame budget. + The transaction's own frame MUST get what the transaction has left in that dimension once the body and the pre-frame counts are counted. + Every child MUST get `parent_remaining × FRAME_DATA_SHARE_NUMERATOR / FRAME_DATA_SHARE_DENOMINATOR`, where `FRAME_DATA_SHARE_NUMERATOR` = 98 and `FRAME_DATA_SHARE_DENOMINATOR` = 100, rounded down. + `parent_remaining` is what the parent has left in that dimension, and the three dimensions share one definition of it. + A frame's net in a dimension is signed: what it added, minus what it gave back, plus the nets its successful children merged in. + A fall, a write record taken back, or data size given back can make that net negative. + The frame's remaining is `min(budget, max(0, budget − net))`. + It stays inside the budget the frame was given, including when the net is negative, so a negative net does not raise what the frame forwards. + The transaction's net is what sits on no frame — the body, the applied authorities' records, a deposit's caller and every admitted hint — plus the net of every frame on the stack. + A frame's net includes a child's only after that child succeeded and the net merged, so a failed frame's net is not part of the transaction's net. + The transaction's remaining is the same clamp of that net against the transaction limit, and it never exceeds that limit. + A child that receives this share therefore receives at most 98/100 of the budget its parent was given. + A frame with a state-growth budget of 1,000 that has added 100 has 900 left, and the child it starts receives 882. + If that child removes those 100, its net is −100 and its remaining stays 882, so the frame it starts receives 864. + When a frame succeeds, its signed net merges into its caller and the caller's remaining is computed again from the caller's own budget. + The merge can raise the caller's remaining up to that budget. + After the child above succeeds, the caller's net is 0 and its remaining is again 1,000, so a later child receives 980. + When a frame fails, its net is discarded, its caller's net is unchanged, and the credits inside the failed frame are discarded with it, the state-gas refill, the write-record takeback and the code data size and history gas of a same-transaction destruction included. + A fall with no earlier rise leaves the frame's remaining at its budget. + Later rises may consume that fall, and the kept net still cannot pass the budget. + The count a transaction reports for KV updates and for state growth is `max(net, 0)`. + The fraction is the data-size share, and KV and state growth use the same one. + A `CREATE` or `CREATE2` MUST take the child's share of what the creator has left: the creation receives `parent_remaining × 98 / 100`, rounded down. + The creator's nonce record, and the creator's state growth when the bump creates the creator, MUST be counted on the creator when the creation returns. + The created account's write record and its state growth are the creation's own rise, checked against that budget. + A creation transaction's own frame is not that child. + It receives the whole of what the transaction has left after the body and the pre-frame counts, as every transaction's own frame does. + A creator that has 1,000 of state growth left, and whose nonce bump adds none, gives the creation a state-growth budget of 980. Satin sets no further per-frame cap. + This multiplication is the frame-budget rule. + The gas-forwarding rule is the subtraction in [Gas Forwarding](#9-gas-forwarding), and the two integers differ at some remaining values. A frame that crosses its budget MUST revert with `MegaLimitExceeded(kind, budget)` and its caller continues. - The budget keeps a caller's own work within reach of what it calls: a child inherits its caller's whole reservoir and history gas draws the reservoir first, so EIP-150's 63/64 forwarding does not bound the bytes a child can append, and without a budget a callee could take the transaction to its limit and leave its caller, which can catch the stop (see [The Revert-Class Stop](#11-the-revert-class-stop)), nothing to carry on with. -- **State growth** is not limited. - EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), so what bounds state growth is what it costs: the transaction's gas limit and the block's. - That the bound stays within the state growth the chain's storage sustains is a property of the state-gas prices, not of a limit. + The budget keeps a caller's own work within reach of what it calls. + A child receives 98/100 of its caller's remaining regular gas and 98/100 of its caller's remaining reservoir, and state gas and history gas draw the reservoir first, so the gas forward alone does not bound what a child can append. + Without a frame budget, and without the reservoir share the caller keeps, a callee could take the transaction to a limit and leave its caller, which can catch the stop (see [The Revert-Class Stop](#11-the-revert-class-stop)), nothing to carry on with. + The retained fraction is a share the caller keeps, not a gas argument: the gas the caller asks to forward does not bound the reservoir (see [Gas Forwarding](#9-gas-forwarding)). +- **State growth** is the net count of new accounts and new storage slots the transaction keeps. + Each rise is one unit, at an EIP-8037 account-leaf or fresh-slot charge site (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)), and not one unit per byte of deployed code or of a delegation indicator. + State gas still prices those bytes. + The count is what `TX_STATE_GROWTH_LIMIT` holds. + The rises are: + - a fresh slot, and only the `SSTORE` transition named below; + - a value `CALL` to an account that is empty under EIP-161; + - a `SELFDESTRUCT` that moves a non-zero balance to an account that does not exist; + - the recipient a transaction's value creates; + - an applied EIP-7702 authorization that creates its authority; + - a `CREATE`, a `CREATE2`, a creation transaction, or a keyless creation, when the created address is empty; + - the keyless signer's account, when the creation's nonce bump creates it, counted on the keyless call; + - the caller account a deposit-like transaction creates, charged once (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + An account that already exists is not a rise, and neither is a `CALLCODE`, a value call to the calling account itself, deployed code, or the 23-byte delegation indicator. + An `SSTORE` changes state growth only by the table below. + The columns are the slot's original value in the transaction, its present value, and the value written. + The state-growth change is the same transition as the fresh-slot state-gas charge or refill (see [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing)). + +| Original | Present | New | State growth | +| -------- | -------- | -------- | ------------ | +| zero | zero | zero | none | +| zero | zero | non-zero | +1 | +| zero | non-zero | zero | −1 | +| zero | non-zero | non-zero | none | +| non-zero | zero | zero | none | +| non-zero | zero | non-zero | none | +| non-zero | non-zero | zero | none | +| non-zero | non-zero | non-zero | none | + +A no-op writes the present value and is one of the rows that change nothing, including original zero, present zero, and new zero. +A rewrite of a slot that is already non-zero, and whose original value is zero, changes nothing: the rise was the write that first made it non-zero. +A slot whose original value is not zero changes nothing on every transition, including present zero and new non-zero. +A slot written from zero to a non-zero value and then to another non-zero value rose once. +A slot written from zero to a non-zero value and then back to zero has a net of zero. +A slot written from zero to a non-zero value, back to zero, and then to a non-zero value again rose on the first write, fell on the second, and rose on the third. +The fee credits the settlement writes are not rises. +They are not EIP-8037 charge sites. +Rex6 recorded each distinct fee recipient after the result, where the count could not change the outcome. +Satin does not: the body's five fixed records already bound those accounts for data size, and a count taken after the result cannot stop the frame that wrote them. +The falls happen at the opcode that restores the state. +A fall cannot cross a limit. +The only slot fall is the table's row of original zero, present non-zero, and new zero, and its state gas is given back as [State Gas and SALT Pricing](#6-state-gas-and-salt-pricing) specifies. + +##### The destruction table + +The first effective `SELFDESTRUCT` of an account created in the same transaction applies the table below to every part of that account. +The columns are the part's value at the transaction's start, its value before the destruction, and deleted. +A slot's value at the transaction's start is its original value in the transaction: the value it held when the transaction first accessed it. +A slot of the created account that the transaction first accesses after the creation reads zero, whatever the state held there, and so has an original of zero. +A slot the transaction accessed before the creation keeps the value it held then as its original, and holds that value, or what the transaction writes to it, afterwards. +A part the transaction made, absent at the start, is refilled and taken back. +A part that existed at the start is an ordinary deletion. + +| Part | At the transaction's start | Before | After | Effect | +| ------------- | -------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Account leaf | absent | present | deleted | refill the leaf's state gas; state growth −1; take the account's write record back | +| Account leaf | present | present | deleted | nothing: the leaf existed before the transaction, and its write record stands | +| Deployed code | absent | present | deleted | refill the code deposit's state gas; take back its data size and its history gas | +| Deployed code | absent | absent | deleted | nothing | +| Deployed code | present | present | deleted | not reached: non-empty code at the start collides with the creation | +| Slot | zero | non-zero | deleted | refill the slot's state gas; state growth −1; take the slot's write record back | +| Slot | zero | zero | deleted | nothing: the slot is already clear | +| Slot | non-zero | any | deleted | nothing of the refill or the fall. The write record of a slot the transaction loaded stands, and the deletion makes it when that loaded slot still holds its original value. A slot the transaction did not load has no record | + +A refill MUST be the price that part was charged, the schedule entry times the bucket multiplier of that charge, and it MUST go to the destroying frame, including when another frame paid it. +On the absent row, the account leaf's charge is the one this transaction made for that leaf: at the value transfer that funded the address, at a `SELFDESTRUCT` that paid it, at the transaction's own value, or at the creation when the created address was empty. +State growth falls for the absent leaf and for each slot on the zero, non-zero, deleted row, and for nothing else in the table. +The fall of the absent leaf stands even when the creation itself added no rise, as when the transaction funded the address and then created onto it. +An address that held a balance before the transaction is the present row: the creation adds no rise for that leaf, the destruction subtracts none, and the write record the nonce bump made stands. +The write record taken back returns its data size to the destroying frame's budget and its history gas to that frame, and the KV count falls by that record. +When the destroying frame is the transaction's own frame and that frame succeeds, this return is the record's history gas, once. +The settlement of that frame MUST NOT give the same charge back again (see [History Gas](#7-history-gas)). +Deployed code is not a write record and not a unit of state growth. +Code on the absent, present, deleted row returns its data size and its history gas the same way. +The give-back MUST follow the refill order of [History Gas](#7-history-gas). +It is a give-back of state gas or of history gas, as a slot written back to zero is, and not an EIP-3529 refund. +EIP-8037 specifies that this destruction produces no state-gas refills, and Rex6 refunded none of the storage gas. +Satin refills the state gas because a part the transaction made does not remain for a node to store, so the count and the charge stay aligned. +It MUST be credited with the completed write, after every charge the opcode makes: a charge the frame cannot pay halts the opcode first, and the give-back is not credited. +The give-back MUST NOT raise that frame's remaining above the budget it was given. +When the destroying frame succeeds, the give-back is unspent gas of that frame and returns up the chain. +When the destroying frame fails, or a frame that contains it fails, the mark and every effect of the table are discarded. +The charges then stand, or come back by the ordinary rule for that failure, and a record the table took back stands again. +The discarded give-back is not a further one. +A later `SELFDESTRUCT` of the same account, while the mark stands, applies the table again for nothing: it subtracts nothing, refills nothing and takes nothing back. +A `SELFDESTRUCT` of an account that was not created in the transaction does not apply the table. +It subtracts nothing, refills nothing, and does not mark the account. +EIP-6780 does not delete that account. +From the first effective destruction until the end of the transaction, while the mark stands, the account adds nothing further to state growth and keeps no further state gas. +An `SSTORE` of one of its slots in that span does not rise, does not fall, and neither charges nor refills fresh-slot state gas. +The `SSTORE`'s regular gas is unchanged. +A slot the table already refilled therefore cannot be charged or refilled again. +Code on the absent, absent, deleted row was not deposited when the account was destroyed: a constructor can destroy the account before its code is deposited. +That later deposit's state gas MUST NOT be charged. +Its data size and history gas MUST be charged as any deposited code, and no later destruction takes them back. +Value sent to the marked account afterwards is not a rise, and it makes no write record. +The account still exists until the transaction ends, and it is removed then with the balance it holds (see [EIP-7708 Transfer Logs](#14-eip-7708-transfer-logs)). +From the mark until the transaction ends, a write to the account or to one of its slots makes no record. +The account's logs, and the transfer log of the balance moved, stay counted and stay charged: a log is history the transaction appended, and the transfer log is data size the move made. +Removing the account at the end of the transaction does not take a record back again, and it does not take the code's data size or history gas back again. +A creation collides when the address holds non-empty code or a nonce other than zero, and it does not collide on storage. +EIP-7610 would refuse a creation onto non-empty storage, and it says that rule applies retroactively. +Ethereum's clients apply it, and so do the execution-spec fixtures, including the Osaka files under `paris/eip7610_create_collision`. +Satin does not apply it: the engine reads storage slot by slot and cannot see storage it has not loaded, so it cannot see a collision with storage alone. +The execution-spec gate skips those fixtures for that reason. +A creation can therefore land on an address with nonce zero, empty code and storage. +Execution that has always applied EIP-161 and EIP-6780 does not produce that address: a creation sets the nonce to one, and a same-transaction destruction deletes the account. +The address can still be in the state a block is given. +A slot of it that the transaction first accesses once the account is created reads zero and is on a zero row, and a slot the state held that the transaction never accessed makes no record when the account is destroyed. +The non-zero slot row is a slot of that address the transaction accessed before the creation: it keeps the value it held, and the destruction deletes it with the account as an ordinary deletion, which makes its write record while it still holds that value. +An account that is empty under EIP-161 while its leaf is already in the state the transaction loaded — nonce zero, balance zero, empty code, and storage that is not empty — is the present-leaf row. +The creation may still charge new-account state gas and count a rise, because the address is empty under EIP-161. +That row does not refill the charge and does not subtract the rise. +A `SELFDESTRUCT` that moves a non-zero balance to a distinct account that does not exist is still a rise, a repeated destruction included. +A zero balance creates no account and is not a rise, on a first destruction or a repeated one. +That rise is held to the limits only after the operation's give-back. +The give-back cannot cross a limit. +A frame that is exactly at its state-growth budget, and that destroys an account created in the transaction while moving a non-zero balance to a new beneficiary, subtracts the leaf only when the leaf was absent at the transaction's start, and subtracts one for each of the account's new slots, before it adds the beneficiary. +When the leaf was absent and the account has N new slots, the subtraction is `1 + N` and the beneficiary fits. +When the leaf was present, the subtraction is N, and the beneficiary fits when N is at least one. +Compute is decided before the opcode completes. +A regular charge that crosses gas detention stops the frame at that charge, and the operation applies none of the table and no beneficiary. +The operation first gives back what the table takes back: the state-growth falls, the state-gas refills, the write records, and the deployed code's data size and history gas. +That give-back is part of the completed write, after every charge the opcode makes. +A part taken back is given back before the positive effects are held, as [History Gas](#7-history-gas) requires. +The operation's positive effects are then held, in the dimension order data size, KV updates, then state growth: the records the operation makes — the account it clears, when that account was not created in the transaction and this write makes its record; a loaded pre-existing slot of an account the table covers, when the deletion is what makes that slot's record; and its beneficiary — and its transfer log, then the beneficiary's state growth. +Within each dimension they use the rule in **Order at one site** below. +When a positive effect crosses, the frame stops and the operation keeps nothing: the table's effects, the beneficiary and the transfer log are discarded with it. +The rises and falls are the frame's, as its write records are. +A successful frame's net MUST merge into its caller. +A failed frame's net MUST be discarded. +A child's net is negative when it removes more state growth than it added. +That negative contribution lets a child undo state its caller added, and the remaining that sizes the next frame is the clamp in **Frame budgets** above, so the negative net does not enlarge the child's budget. +The state growth a transaction reports is `max(net, 0)`. +A rise that would make the signed net exceed the transaction limit or the frame budget is the crossing, and that rise MUST NOT be kept. +`TX_STATE_GROWTH_LIMIT` = 1,000. +At `m = 1` a fresh slot costs 97,920 state gas, so 1,000 fresh slots cost 97,920,000, which a transaction's gas limit can cover. +The count is what stops the 1,001st slot. +The gas price does not stand in for the count. +A failed deposit that creates its caller, when that account did not exist, counts that account as one toward the transaction's reported state growth and toward the block counter. +It pays no state gas for the account (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)), and the limit does not stop the deposit, which has already failed. +The account is state the block keeps, so a block of such deposits cannot pass the cap while reporting no state growth. +A deposit that runs to a success or a revert and creates its caller is the ordinary charged rise of one, and a stop of its first frame keeps that account (see [The Revert-Class Stop](#11-the-revert-class-stop)). + - **Order at one site.** - A record that crosses the transaction's data-size limit and its frame's budget at once MUST stop its frame with the transaction's limit in the revert data: the transaction limit is checked before the frame budget. -- **A frame start** is counted before the frame is built. - A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be charged nothing, and be stopped by no limit. - A creation onto an occupied address is counted, and a crossing it causes stops it where it would otherwise have failed on the collision. + At a completed write or a decided frame start, an operation that crosses more than one of data size (kind 0), KV updates (kind 1) and state growth (kind 3) MUST stop on the first of those three, in that order. + The order is Rex6's order across dimensions. + Compute (kind 2) is decided at the regular charge, before the write is counted. + A regular charge that crosses gas detention means the opcode does not complete, so the operation's data size, KV updates and state growth are not counted, and kind 2 is the stop because the write did not happen. + A call to a precompile is the exception: the value has already moved when the price is consulted, so the start's records are decided before the price. + Those records MUST be held to these limits first, in the order of this section. + The price is kind 2 only when the start kept within them. + A value the caller cannot fund runs no precompile, counts nothing and is stopped by no limit. + The same order applies when a precompile the node cannot price runs out of the allowance: the start's records are held first, and running out of the allowance is kind 2 only when the start kept within them. + The exception begins at the price: the call's own regular charges — its static 100, its memory, the 11,300 value transfer and a cold access — MUST be decided first, as any opcode's, and one that crosses MUST stop the calling frame before anything moves, whether or not the caller can fund the value. + Inside data size, KV updates and state growth, the frame budget MUST be tested before the transaction limit. + When the frame budget is crossed, the stop MUST name that budget, and `limit` is that budget, including when the transaction limit of the same dimension is crossed too. + When the frame budget is not crossed, a crossing of the transaction limit MUST name that limit, and `limit` is the transaction limit. + The frame budget is not crossed when none applies, and also when the frame's own budget still holds the write. + No frame budget applies to an Oracle hint's bytes, which are counted on the transaction and on no frame, or to the authorization list, which is decided before the first frame (see above). + A framed write can cross the transaction's data-size limit alone after hints have used what the transaction had left, while the frame's own budget still holds the write, and the stop then names the transaction limit. + The admitted hint bytes stay counted. + A framed write of KV updates or of state growth cannot cross the transaction limit without crossing its frame budget: once a frame is running, those dimensions have no usage that sits on the transaction and on no frame, and a child's budget is a share of what its parent has left. + The body is refused at validation, so it does not cross at runtime. + Gas detention remains kind 2 (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). +- **A frame start** is held to the limits once it is decided: once the value moved and, for a creation, the creator's nonce was bumped and the created account made. + A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be stopped by no limit, and be charged nothing at its opcode (see [History Gas](#7-history-gas)). + A creation onto an occupied address fails on the collision after its creator's nonce was bumped, and MUST NOT be stopped for what its start would count: its failure discards the created account's record and its transfer log, and the creator's nonce record, which survives it, MUST be counted on the creator when the creation returns, the creator held to its limits with it. + The created account was not new, so the collision adds no state growth. + The creator's nonce record is KV on the creator, and state growth only when the bump creates the creator's account, as a keyless signer's bump can. +- **Authorizations before the first frame.** + Before the first frame, a node MUST decide the list by simulating [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) application in list order. + The simulation writes nothing and warms nothing. + An entry whose chain id is neither zero nor this chain's, whose nonce is 2^64 − 1, or whose signature does not recover an authority, is skipped, and its authority account is not read. + Every other entry loads the authority's account, with its code. + An authority account that holds code other than a delegation is skipped, and its simulated nonce is not bumped. + The authorization's nonce is then compared with the authority's effective nonce. + When an earlier entry for the same authority was accepted in this list, the effective nonce is the simulated nonce after those acceptances. + When the authority is the sender and no earlier entry for it was accepted, the effective nonce is the sender's nonce after validation's bump: an authorization signed for the sender's nonce before the transaction does not match. + Otherwise the effective nonce is the account's current nonce. + A nonce that differs skips the entry. + A nonce that matches would apply. + The simulated nonce then becomes one higher. + The simulation MUST walk the whole list, and it MUST NOT stop at the first entry that would cross a limit. + Each distinct authority whose entry passed the chain-id, nonce and signature gates is loaded once. + A later entry for that authority uses the simulated nonce and the code already loaded. + A failure to read an authority the simulation consults is a database fault: the transaction has no outcome. + When the node's database declares that error fatal, the node reports an internal error; any other database error makes the block invalid. + The block is not refused for the limit (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). + This holds when an earlier prefix of the list would already have crossed. + The simulation charges no cold-access gas. + The intrinsic 7,816 per entry is already charged at validation, for every entry, applied or not. + The totals the list would keep, were it applied, are one KV write record for each distinct authority it would change, other than the sender, whose account is the body's record; one state-growth unit for each distinct authority it would create, however many of its entries are accepted; and account-creation state gas once for each such new authority. + Delegation-indicator state gas is charged at most once per authority. + It is charged only when an accepted authorization writes a non-zero delegation designator, the authority holds no delegation indicator at the start of the transaction, and no earlier authorization in the list set one for that authority. + An authority that holds an indicator at the start of the transaction is charged none for it, a clear and a later non-zero authorization included. + A clear charges none. + Two accepted non-zero authorizations for one authority that holds none at the start charge the indicator once. + A zero delegation target still bumps the nonce and can create the account, and it charges no indicator. + The indicator is not a unit of state growth. + Repeated acceptances of one new authority create it once and keep one KV record. + 1,000 new authorities fit `TX_STATE_GROWTH_LIMIT`, and 1,001 do not. + If those KV or state-growth totals would exceed the transaction's limit, the node MUST apply none of the list, charge none of the authority state gas or record history, and MUST stop the transaction's own frame before it runs, with `MegaLimitExceeded` of the crossed kind and that transaction limit. + No frame budget exists yet, so the stop names the transaction limit. + When both KV and state growth would be crossed, the kind is 1. + Data size cannot be crossed here, and compute does not apply. + The body's data size, with a record for each authorization entry, is already refused at validation when it exceeds `TX_DATA_LIMIT` (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)), so a transaction that passes validation is not over the data-size limit before its authorizations are applied. + A skipped list keeps no authority account, no authority write record, no authority state gas and no authority history. + The intrinsic regular gas, the body's history gas and the body's data size stay. + No delegation is written, and no authority nonce is bumped beyond the sender's validation bump. + The consulted authorities are not made warm, except an authority that was already warm from the start of the transaction: the sender, the recipient of a call, the block beneficiary, an access-list address, a precompile, or the `SequencerRegistry`'s account (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + The witness MUST hold every authority account the simulation loaded, with the code the chain held, whether or not the list is applied (see [The Stateless Witness](#22-the-stateless-witness)). + The skip is all or nothing, including an authority that would have fitted by itself. + That all-or-nothing skip is Rex6's rule for this list. + Satin settles it as this revert-class stop rather than Rex6's halt: a stop of the first frame does not revert pre-frame writes (see [The Revert-Class Stop](#11-the-revert-class-stop)), so applying the list would keep more than the limit allows. + When the list fits, it is applied, and EIP-7702 warms every authority whose account the application loads. + An entry skipped for its chain id, for a nonce of 2^64 − 1, or for a signature that does not recover an authority is not loaded, and it is not warmed. + An entry skipped because the authority's code is not a delegation, or because the nonce does not match, is loaded by the application before that check, and that authority is warmed. + The state gas and the history of the authority records are charged then. + Those counts reduce what the first frame is given. + If one of those charges cannot be paid, the transaction takes the out-of-gas path of [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas): the authorizations are taken back, and for a non-deposit this is an out-of-gas halt, not the limit stop. + The limit is decided before those charges, so a list that does not fit never takes that path. + When the list fits, a later stop of the first frame keeps the authorizations. + The caller account a deposit creates is not an authorization. + It is always created and kept, and it is one account, so it cannot by itself cross `TX_STATE_GROWTH_LIMIT`. + The check is made where the accounts are read, during execution. + Validation that does not read state cannot tell which authorities are new, so the skip is not a pool rejection. + At the spec's gas numbers the execution cap admits at most 25,587 authorizations, so the KV form of the skip is not reached. + The state-growth form is: the state gas of 1,001 new authorities fits in a gas limit above the execution cap. - **The limits are fixed per spec.** - The transaction's data-size limit, the per-frame share, the detention caps (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) and the block's data-size limit (see [Block Limits](#20-block-limits)) are protocol values of the Satin spec, the same on every chain. + The transaction's data-size, KV and state-growth limits, the per-frame share, the detention caps (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)), and the block's data-size, KV and state-growth limits (see [Block Limits](#20-block-limits)) are protocol values of the Satin spec, the same on every chain. They are not chain configuration: no chain configuration carries them, and a node MUST hold every Satin transaction and block to them, never to values a configuration names or a node is handed with a block. A later spec that changes one states its own value. A node MUST hold the transactions of block execution and validation, the executions whose result the chain agrees on, to these values. @@ -450,7 +834,15 @@ One dimension is limited per transaction, data size; compute is not one (see [Tw #### New behavior -Every limit — the transaction's data-size limit, a frame's data-size budget, and gas detention's compute limit — MUST stop the frame that crosses it with a revert, never a halt. +Every limit, the transaction's data-size, KV and state-growth limits, a frame's budget in those dimensions, and gas detention's compute limit, MUST stop the frame that crosses it with a revert, never a halt. +A _limit stop_ is that revert, in exactly the four dimensions the revert data below enumerates: data size (kind 0), KV updates (kind 1), compute under gas detention (kind 2) and state growth (kind 3). +Nothing else is a limit stop, and in particular these inherited endings, each of which enforces a size or a payment, are not: + +- initcode over `MAX_INITCODE_SIZE`, for which a non-deposit creation transaction is rejected at validation, a creation opcode halts the creating frame and a keyless deployment is refused with `InitCodeTooLarge` (see [Native Keyless Deployment](#15-native-keyless-deployment)), and deployed code over `MAX_CONTRACT_SIZE`, which halts the creation (see [Contract Size Limits](#3-contract-size-limits)); +- an input over an OP precompile's size limit — the BN254 pairing's and the BLS12-381 MSMs' and pairing's — which the precompile refuses before any gas check, halting the call and consuming its forward (see [Precompiles](#2-precompiles)); +- a failed deposit, which uses its whole gas limit and reports no stop (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)); +- a charge made before the first frame that the transaction cannot pay, which runs out of gas without running a frame (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)). + The stop applies to a transaction that passes validation and pays every charge made before its first frame. A transaction that fails validation, or that cannot pay a charge made before its first frame (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)), MUST report no stop: a non-deposit transaction that fails validation is rejected, and a deposit that fails validation — a system deposit, which the inherited rules refuse under Regolith, and a deposit whose body is over the data-size limit included — or that cannot pay a charge made before its first frame is included as a failed deposit, whatever kind of deposit it is (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). The body of such a deposit MUST stay counted as data size. @@ -459,28 +851,35 @@ For a transaction the stop applies to: 1. The frame that crosses a limit MUST revert with `MegaLimitExceeded(uint8 kind, uint64 limit)` as its output. The write or the charge that crossed MUST NOT be kept or made, and every write and log the frame made MUST be reverted, as a `REVERT` reverts them. 2. Its caller MUST resume as after any revert: the call fails, its return data is the stop's revert data, and the gas the frame had — before the charge that crossed, for gas detention's limit — returns to the caller, its reservoir included. -3. What the frame counted MUST be discarded with it, so the caller resumes within every limit. - A caller that carries on is held to what the transaction has left: a write or a charge of its own that crosses a limit again MUST stop the caller's frame in turn. - A transaction therefore never keeps more data size than its limit, and never computes past gas detention's limit but by what [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas) allows. -4. A caller that catches the stop MUST run on as after any failed call: a transaction whose frames catch every stop below its own frame MAY succeed, keeping what its frames did and nothing of a frame that was stopped. +3. What the frame counted MUST be discarded with it, so the caller resumes within every limit, but in one case. + A failed frame's discard puts back what the frames above it kept when it started, a record of theirs it took back included, while an Oracle hint it admitted stays counted (below); a hint sent into the room such a take-back freed leaves the transaction over its data-size limit once the frame fails. + The frame it returns into MUST then return the stop of the transaction's data-size limit before it runs another instruction, whether the frame below reverted, halted or was itself stopped. + Otherwise a caller that carries on is held to what the transaction has left: a write or a charge of its own that crosses a limit again MUST stop the caller's frame in turn. + A transaction therefore never keeps more data size, KV updates or state growth than its limits, and never computes past gas detention's limit but by what [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas) allows. +4. A caller that catches the stop MUST run on as after any failed call, unless the item above stops it as it resumes: a transaction whose frames catch every stop below its own frame MAY succeed, keeping what its frames did and nothing of a frame that was stopped. 5. A stop of the transaction's own frame is the transaction's result. The transaction MUST settle like an EIP-8037 revert: every write and log its frames made MUST be reverted, the value its first frame carried and that frame's write record included; the sender pays the intrinsic gas, the body's history gas, the charges of what it keeps from before the first frame (below), and what ran; the unspent regular gas and the reservoir return to the sender. The transaction is included with a failed receipt, and its usage counts towards the block's counters. + A deposit whose own frame is stopped settles this way too, as a revert: it is not a failed deposit, which only a deposit that fails validation, cannot pay a charge made before its first frame, or whose own frame halts becomes, and which uses its whole gas limit, the reservoir included (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). What was applied before the first frame is not the frames' doing, and a stop of the transaction's own frame MUST NOT revert it, as a revert of the first frame does not: - the sender's nonce and the fees it pays; for a deposit, its mint and the caller account it created, with that account's state gas; -- the EIP-7702 authorizations admitted before the first frame: their authorities' nonce and delegation writes, their state gas, their write records, and the history gas those records cost. +- the EIP-7702 authorizations admitted before the first frame, which are those the list rule of [Resource Limits](#10-resource-limits) let through: their authorities' nonce and delegation writes, their state gas, their write records, and the history gas those records cost. + A list that rule skipped was not admitted, and the stop keeps nothing of it. An Oracle hint a frame admitted is not the frames' state either: it MUST stay counted as data size through any stop, whether its payload reached the oracle service or failed to decode (see [Oracle Storage Reads and Hints](#16-oracle-storage-reads-and-hints)). A hint that would itself cross the data-size limit is neither forwarded nor counted. -A limit is enforced before the writes it guards: +A limit is enforced on the writes it guards before anything runs on them: -- A frame whose start would cross a limit MUST be answered with the stop before it is built, so no value moves. - A stopped creation still bumps its creator's nonce, and that write's record lands on the creator, which MUST be held to its limits with it before it runs on and be stopped if it crosses one. +- A frame whose start crosses a limit MUST be stopped before it runs an instruction, and what its start moved MUST be reverted with it: the value, the transfer log, a created account. + A frame answered without running — a call to an account with no code, a precompile, whatever it answered — MUST have its answer replaced by the stop, on the gas its caller forwarded, untouched. + When that answer is a precompile whose price crosses gas detention and whose start's records also cross a data-size, KV or state-growth budget, the records' stop is the result, as [Resource Limits](#10-resource-limits) orders the two. + A stopped creation keeps its creator's nonce bump, and that write's record MUST be counted on the creator when the creation returns: the creator MUST be held to its limits with it before it runs on, and be stopped if it crosses one. - A frame answered without running whose answer is then rewritten to the stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST have what its start moved reverted with it, as a frame that fails has. -- Nothing counted before the first frame — the body, and the records of the EIP-7702 authorities applied — crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). +- Nothing counted before the first frame crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + KV updates and state growth can cross before the first frame, on that authorization list, and the list is then skipped (see [Resource Limits](#10-resource-limits)). A real out-of-gas, a precompile given less than its price, and an invalid opcode still halt and consume the frame's gas. @@ -489,11 +888,15 @@ The revert data: | `kind` | Dimension | `limit` | | ------ | ----------------------- | -------------------------------------------------------------------------------------------------- | | 0 | Data size | The limit or frame budget crossed, in bytes | +| 1 | KV updates | The limit or frame budget crossed, as a count of write records | | 2 | Compute (gas detention) | The compute limit of the binding read: the transaction's compute at that read plus the cap, in gas | +| 3 | State growth | The limit or frame budget crossed, as a count of new accounts and new slots | The discriminants are Rex6's, so a decoder of the Rex6 revert data decodes Satin's. -Kinds 1 and 3, Rex6's KV updates and state growth, are not reported: no limit holds either dimension. -Kind 2 names the limit; the compute the transaction is billed can exceed it when frames halt because they cannot pay an opcode's static gas — the first of them taking the compute past the limit, each later one holding it there — by less than that static gas per halting frame, added over those frames (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). +Every limit stop carries `MegaLimitExceeded`, in every dimension, and a refusal the protocol makes that is not a limit stop MUST NOT carry it: a refused volatile read reverts with `VolatileDataAccessDisabled(uint8)` (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)), the system contracts' and a keyless deployment's refusals carry their own errors (see [Native Keyless Deployment](#15-native-keyless-deployment)), a call past the call-depth limit or with a value its caller cannot fund fails with empty return data, and a halt has no return data. +Kind 0, kind 1 and kind 3 name the frame budget when that budget is crossed, including when the transaction limit of the same dimension is crossed too. +They name the transaction limit when the frame budget is not crossed, whether or not a frame budget applies to the operation (see [Resource Limits](#10-resource-limits)). +Kind 2 names the compute limit, which the transaction's compute does not exceed (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). A contract can revert with the same bytes, and so can a caller that re-raises the stop a frame below it returned, so the revert data alone does not identify a stop: the stop of a transaction is the crossing that produced the result of its own frame (see [Developer Impact](#developer-impact)). ### 12. Gas Detention on Withheld Gas @@ -511,11 +914,16 @@ A contract can revert with the same bytes, and so can a caller that re-raises th `BLOBHASH` MUST NOT be volatile: it reads the transaction's own blob hashes. A read MUST be marked where the value is loaded, and only once the opcode completed; a load that fails, and a read whose opcode then fails, mark nothing. `BLOCKHASH` loads the block number before it decides whether its operand is in range, so every `BLOCKHASH` is a read of the block environment, one of the current block, a future block or a block outside the last 256 included, and one in range reads the hash as well. - A `CREATE` or `CREATE2` MUST NOT be marked as a read, even when its creator or its created address is the block beneficiary: the loads it makes of them — the creator's, to check its balance and nonce, and the created address's, to decide the created account's state gas — mark nothing, and a frame then running as the beneficiary marks the beneficiary's account by its own `SELFBALANCE`, `SELFDESTRUCT` and the other reads above (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas) for what those loads do with access off). + A call to the EIP-2935 history contract is a read of the block environment because the contract's `get` path executes `NUMBER` before it loads the slot; the storage the EIP-2935 and EIP-4788 pre-block calls write is state committed before the block's first transaction, and an `SLOAD` of it MUST NOT be a volatile read. + A `CREATE` or `CREATE2` MUST NOT be marked as a read, nor refused in a frame whose access is off (see [Volatile-Data Access Control](#13-volatile-data-access-control-and-remainingcomputegas)), even when its creator or its created address is the block beneficiary: the loads it makes of them — the creator's, to check its balance and nonce, and the created address's, to decide the created account's state gas — are the creation's own checks, which revm's creation opcode makes under EIP-8037, and not volatile reads, as a value call's check of its caller's balance is not one, and as Rex6 neither marked nor refused a creation. + A frame then running as the beneficiary marks the beneficiary's account by its own `SELFBALANCE`, `SELFDESTRUCT` and the other reads above, and with access off is refused them. - **Compute.** - A transaction's compute is its regular ledger — the running frame's regular gas spent, plus every suspended caller's, each less its child's whole gas limit — less the state and history gas that spilled onto regular gas, and less what halting frames burned. - A child's gas limit includes a value call's 2,300 stipend, which its caller did not spend: what the callee spends of it is not compute, and what the callee leaves of it lowers the caller's spent regular gas when it returns. - What a halting frame burns is not compute, with one exception: when an opcode's static gas cannot be paid, what the halting frame had left counts as compute. + A transaction's compute is every regular charge its frames make, whoever funds it: the running frame's regular gas spent, plus every suspended caller's, each less the gas it forwarded its child, less the state and history gas that spilled onto regular gas, and less what halting frames burned. + A value call's 2,300 stipend is not forwarded gas: what the callee runs on it MUST count as compute, as the rest of what it runs does. + The stipend MUST NOT lower compute either: when a value call returns, what the callee left of the stipend comes back to its caller with the rest of the callee's gas, and compute MUST NOT fall with the caller's spent regular gas. + So compute exceeds the transaction's regular ledger by the stipends of its value calls, gas no pool of the transaction paid. + What a halting frame burns — the regular gas it had left when it halted — MUST NOT count as compute, whatever it could not pay: a dynamic charge, an opcode's static gas, a cold access, or state or history gas that spilled past the reservoir. + A precompile that runs out of gas counts nothing of its forward as compute: it burns the forward, a value call's stipend included, as a halting frame burns what it had left, unless it is the crossing (see Precompiles, below), and then the forward returns to its caller. - **The limit.** A read MUST set `limit = compute_at_read + cap`, with `cap` = `BLOCK_ENV_ACCESS_COMPUTE_GAS` = 20,000,000 for the block environment and the beneficiary and `ORACLE_ACCESS_COMPUTE_GAS` = 20,000,000 for the Oracle; the limit only goes down, so the most restrictive read binds. The caps are protocol values fixed per spec with the other limits (see [Resource Limits](#10-resource-limits)). @@ -524,22 +932,22 @@ A contract can revert with the same bytes, and so can a caller that re-raises th Once a limit is set, every frame's regular gas MUST be split into a spendable part, held at what the limit leaves the transaction (`limit − compute`, or zero once the compute is past the limit), and a withheld part, the rest. The split MUST be applied when the read's opcode completes, when a frame starts or resumes, and after an `SSTORE` (whose restore of a slot can refill regular gas). Only a regular charge MUST be limited to the spendable part. - Every other reader of the frame's gas MUST see both parts: `GAS`, the 63/64 forward and the clamp of an explicit call gas, the `SSTORE` minimum-gas check, the checks that decide whether a cold load is attempted, the gas a child returns, and the settlement at the end of the transaction. + Every other reader of the frame's gas MUST see both parts: `GAS`, the 98/100 forward and the clamp of an explicit call gas, the `SSTORE` minimum-gas check, the checks that decide whether a cold load is attempted, the gas a child returns, and the settlement at the end of the transaction. At the settlement the withheld part MUST be unspent gas: it returns to the sender with the rest of the unspent gas, and it is not part of the gas used that caps the EIP-3529 refund at a fifth. + A failed deposit MUST return none of it, as it returns no unspent gas and no reservoir (see [Transaction and Block Refusals](#21-transaction-and-block-refusals)). A forward and a spill of state or history gas MUST draw the withheld part first. So a transaction that read volatile data runs exactly as it would without the read until a regular charge needs the withheld part. - **The crossing.** A regular charge that the spendable part cannot pay but the frame's whole regular gas can is the crossing: the charge MUST NOT be made, the frame's gas MUST be put back to what it was before the charge, and the frame MUST be stopped with `MegaLimitExceeded(2, limit)` (see [The Revert-Class Stop](#11-the-revert-class-stop)). What the frame spent before the crossing charge stays spent, and its caller MUST get back everything the frame had, the withheld part included. - The transaction's compute at the crossing is then at most the limit and less than the crossing charge short of it, with one exception. + The transaction's compute at the crossing is then at most the limit and less than the crossing charge short of it. A caller the stop returns into resumes held to what the limit leaves the transaction, which is less than the charge that crossed, so any regular charge of its own past that is a crossing too. - A frame that halts because it cannot pay an opcode's static gas counts what it had left as compute (see Compute, above), and that can take the transaction's compute past the limit without a crossing, by less than the static charge the frame failed to pay: at most 4,999 gas per such frame, `SELFDESTRUCT`'s static gas of 5,000 being the largest. - Its caller then resumes with no spendable gas; a caller whose whole regular gas cannot pay its next opcode's static gas either halts the same way and adds what it had left, so the overshoots accumulate along such a chain of frames, each adding less than its own static charge, with no fixed total. - From then on the spendable part is zero, so the next non-zero regular charge that a frame's whole regular gas can pay MUST be the crossing, and the compute stays past the limit by the overshoots together. - A transaction whose frames make no such charge after the overshoot ends as it would without the read, its compute past the limit. + What a halting frame burns adds nothing to the compute (see Compute, above), while the frame's paid work before the halt still counts, so no halt takes the transaction's compute past the limit: the compute since a read is at most its cap. A regular charge beyond the frame's whole regular gas, and every other out-of-gas, MUST halt as it would without the read. - **Precompiles.** + The call's own regular charges come first, as any opcode's: one that crosses MUST stop the calling frame before the price is consulted (see Order at one site in [Resource Limits](#10-resource-limits)). A call to a precompile forwarded more regular gas than the frame's allowance MUST be decided from the precompile's price before it runs: priced within the allowance, it runs on its whole forward; priced past the allowance but within the forward, it MUST NOT run and is the crossing; priced past its whole forward, it runs on the forward and fails, as without the read. + When the value has already moved, the start's records are held to the data-size, KV and state-growth limits before that crossing is the stop, and the price is kind 2 only when the start kept within them (see [Resource Limits](#10-resource-limits)). Every precompile of the Satin set has a price; an input over a size limit is priced at zero, since it is refused before any gas check. An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. @@ -573,7 +981,6 @@ The reference implementation has no price for one, so it runs such a precompile - A refused read MUST revert the frame with `VolatileDataAccessDisabled(accessType)` on the gas it had after the opcode's static gas: the refused read pays its static gas and nothing else — not a cold access, not a copy's memory, not a call's value transfer. The static gas is the opcode's base cost: 2 for `NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE` and `SLOTNUM`; 5 for `SELFBALANCE`; 20 for `BLOCKHASH`; 100 for `BALANCE`, `EXTCODEHASH`, the four call opcodes and an `SLOAD` of the Oracle's storage (whose cold surcharge is not paid); 200 for `EXTCODESIZE` and `EXTCODECOPY`, EIP-8038's base of two warm accesses (see [Gas Schedule and Intrinsic Gas](#5-gas-schedule-and-intrinsic-gas)); and 5,000 for `SELFDESTRUCT`. What the opcode charged after its static gas and before the load — the memory and the copy cost of `EXTCODECOPY`, a call's memory and value-transfer cost — MUST be given back. -- A `CREATE` or `CREATE2` in a frame whose access is off is outside this rule when it loads the block beneficiary's account: the creator's, which it loads first for its balance and nonce, or the created address's, which it loads to decide the created account's state gas once the endowment, nonce and depth checks passed; that load is refused as a load the frame cannot make, and the creating frame MUST halt with an out-of-gas, consuming its gas, instead of reverting with the error. - The error's argument MUST be ABI-encoded as a `uint8`: | `accessType` | Read | @@ -614,10 +1021,10 @@ A node MUST apply [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708): - A deposit's value is logged; its mint is not. - Satin applies the `Transfer` log of EIP-7708 and nothing else of any revision of that EIP: [EIP-8246](https://eips.ethereum.org/EIPS/eip-8246), which EIP-7708 lists among its requirements, MUST NOT be applied, so a balance can still be burned, and a burn MUST NOT log — no `Burn` log is ever emitted, whatever revision of EIP-7708 defines one. Two burns remain, both silent: a `SELFDESTRUCT` to itself of an account created in the same transaction burns the balance at once, and an account destroyed in the transaction is removed at its end with whatever balance it then holds, a value it received after its destruction included (the `CALL` that sent it logged the transfer). -- A transfer log is data size (`TRANSFER_LOG_SIZE` = 160 bytes), counted where the value moves: with the start of the frame that moves it, before any value moves, or with the `SELFDESTRUCT` that moves it. +- A transfer log is data size (`TRANSFER_LOG_SIZE` = 160 bytes), counted where the value moves: with the start of the frame that moves it, held to the limits with the start's records, or with the `SELFDESTRUCT` that moves it. It is not a write record, pays no history gas, and does not draw on a history allowance. - A frame start that the caller's account refuses moves nothing and logs nothing. -- A creation with an endowment onto an occupied address counts its transfer log with its start, as any creation with an endowment does, though the collision then moves nothing and logs nothing: a crossing the count causes stops it first (see [Resource Limits](#10-resource-limits)), and otherwise the count is discarded with the failed creation. +- A creation with an endowment onto an occupied address moves nothing and logs nothing: the collision fails it before the endowment moves, and nothing of the log is counted or held to a limit (see [Resource Limits](#10-resource-limits)). ### 15. Native Keyless Deployment @@ -638,23 +1045,23 @@ The call MUST make these charges and checks, in this order. A rule's refusal reverts the call with the error named: the state and history gas the call was charged are given back, and the regular gas it spent stays spent. An out-of-gas step halts the call, consuming its regular gas. -| Step | Check or charge | Refusal | -| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -| 1 | Charge `KEYLESS_DEPLOY_OVERHEAD_GAS` = 100,000 regular gas | Out-of-gas | -| 2 | The call carries no value | `NoEtherTransfer()`, before the frame is built: no value moves | -| 3 | The arguments and the carried transaction decode: a signed legacy creation, no chain id, no trailing bytes | `MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()` | -| 4 | The carried transaction's nonce is 0 | `NonZeroTxNonce(uint64)` | -| 5 | The initcode is within `MAX_INITCODE_SIZE` | `InitCodeTooLarge(uint64,uint64)` | -| 6 | `gasLimitOverride` covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | -| 7 | The signer can be recovered, from a signature with a low or a high `s` value: EIP-2's bound on `s` does not apply | `InvalidSignature()` | -| 8 | The signer's nonce is at most 1 | `SignerNonceTooHigh(uint64)` | -| 9 | Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation | `SignerHasCode()` | -| 10 | If the signer's account is empty (EIP-161), charge its new-account state gas (`183,600 × m`) | Out-of-gas | -| 11 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | -| 12 | The deploy address `keccak256(rlp([signer, 0]))[12:]` holds no code | `ContractAlreadyExists()` | -| 13 | The signer's balance covers the carried value | `InsufficientBalance()` | -| 14 | Charge what a `CREATE` charges its frame: 12,000 plus EIP-3860's initcode cost, the created account's state gas if the deploy address is empty, and the history gas of the created account's record and, unless the signer is the transaction's sender, the signer's nonce record | Out-of-gas | -| 15 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| Step | Check or charge | Refusal | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 1 | Charge `KEYLESS_DEPLOY_OVERHEAD_GAS` = 100,000 regular gas | Out-of-gas | +| 2 | The call carries no value | `NoEtherTransfer()`, before the frame is built: no value moves | +| 3 | The arguments and the carried transaction decode: a signed legacy creation, no chain id, no trailing bytes | `MalformedEncoding()`, `NotContractCreation()`, `NotPreEIP155()` | +| 4 | The carried transaction's nonce is 0 | `NonZeroTxNonce(uint64)` | +| 5 | The initcode is within `MAX_INITCODE_SIZE` | `InitCodeTooLarge(uint64,uint64)` | +| 6 | `gasLimitOverride` covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 7 | The signer can be recovered, from a signature with a low or a high `s` value: EIP-2's bound on `s` does not apply | `InvalidSignature()` | +| 8 | The signer's nonce is at most 1 | `SignerNonceTooHigh(uint64)` | +| 9 | Unless EIP-3607 is disabled, the signer has no code other than an EIP-7702 delegation | `SignerHasCode()` | +| 10 | If the signer's account is empty (EIP-161), charge its new-account state gas (`183,600 × m`) | Out-of-gas | +| 11 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | +| 12 | The deploy address `keccak256(rlp([signer, 0]))[12:]` holds no code | `ContractAlreadyExists()` | +| 13 | The signer's balance covers the carried value | `InsufficientBalance()` | +| 14 | Charge what a `CREATE` charges its frame: 12,000 plus EIP-3860's initcode cost, the created account's state gas if the deploy address is empty, and the history gas of the created account's record, unless the transaction changed the deploy address already, and, unless it changed the signer's account already — the transaction's sender among them — the signer's nonce record | Out-of-gas | +| 15 | `min(gasLimitOverride, remaining gas)` still covers the signed gas limit | `GasLimitTooLow(uint64,uint64)` | - Steps 1 to 13 keep Rex6's order, so a call several rules refuse reports the Rex6 error. - The read of the signer's account that steps 8 to 10 and 13 check, and the deploy-address read of step 12, MUST load the account into the transaction's state as an account access loads it, warm, the deploy address without its code. @@ -668,22 +1075,33 @@ An out-of-gas step halts the call, consuming its regular gas. An initcode that branches on any of them can be made to return empty code, and the deployment then answers `EmptyCodeDeployed`, but it occupies nothing: the same signed bytes can be submitted again. - A signer that is the block beneficiary MUST be detained as a read of the beneficiary's account, made when the signer's account is read, once step 7 recovered it and before step 8's check: the read's compute is the call's 100,000 of step 1, so the limit is 100,000 plus the cap, unless an earlier read set a lower limit. - The creation MUST then start as a creation by the signer at the deploy address, one level below the call, forwarding `min(gasLimitOverride, remaining gas)`; the forward draws the call's withheld gas first (see [Gas Detention](#12-gas-detention-on-withheld-gas)). + That forward is regular gas, and the 98/100 cap does not apply to it, as Rex6's sandbox envelope was that minimum and the call charges nothing after the creation returns. + The creation MUST receive the reservoir share of [Gas Forwarding](#9-gas-forwarding) from the reservoir the call has left after step 14, and the call keeps the rest. + In data size, KV updates and state growth the creation MUST receive the child share of what the call has left. + The signer's nonce record, and the signer's state growth when the bump creates the signer, MUST be counted on the call at its settlement, once the creation returned. From there it is an ordinary creation frame: priced, limited, detained and logged as one. `ORIGIN` and `GASPRICE` in the initcode are the transaction's own. - **The signer's nonce.** The creation bumps the signer's nonce as any creation bumps its creator's. A deployment from nonce 0 MUST keep the bump. From nonce 1, when the creation's bump is the last nonce change the deployment made, the node MUST take the bump back, whether the deployment succeeded or failed. - The bump's write record and that record's history gas go back with it, unless the creation returned without a revert or a halt — a constructor that destroyed its own account included, and a creation refused its empty deposit not — and moved value out of the signer, whose account then keeps a write of its own. + The signer's write record MUST be counted after that: when the nonce set back leaves the signer's account as the transaction loaded it, no record stands, and the history gas charged for it MUST be given back; a signer's account another write changed — the value a creation that returned without a revert or a halt moved out of it, or into it — keeps its record (see [Resource Limits](#10-resource-limits)). A signer whose own code spent a nonce during the creation that survives it keeps every bump. - **The answer.** The call MUST succeed with `(gasUsed, deployedAddress, errorData)`: the deploy address and empty `errorData` when the deploy address holds code afterwards; otherwise the zero address and `ExecutionReverted(uint64 gasUsed, bytes output)`, `ExecutionHalted(uint64 gasUsed)` or `EmptyCodeDeployed(uint64 gasUsed)` — the last for a creation that returned empty code for the deploy address, which is refused and reverts, and also for a constructor that destroyed its own account. - `gasUsed` MUST be what the creation spent from both pools, with no intrinsic gas and before the EIP-3529 refund: the regular gas it spent and the state and history gas it kept, net of every give-back within the creation — a slot written back to its original value, a record taken back, the upfront state gas of a frame it started that failed; the call's own charges of steps 1 and 14 are not in it, and a give-back is not a refund. + `gasUsed` MUST be what the creation spent from both pools, with no intrinsic gas and before the EIP-3529 refund: the regular gas it spent and the state and history gas it kept, net of every give-back within the creation — a slot written back to its original value, a record taken back, the upfront state gas of a frame it started that failed, and the state gas and the history gas a same-transaction destruction gives back, the deployed code's history gas included; the call's own charges of steps 1 and 14 are not in it, and a give-back is not an EIP-3529 refund. It is never less than the regular gas the creation spent. - **Limits.** - A limit the creation crosses — its frame budget, the transaction's data-size limit or gas detention's compute limit, at its start or in its initcode — stops the creation, and the call answers `ExecutionReverted` with the stop's revert data, keeping what the creation's start wrote. - A limit the call's own charges cross — gas detention's compute limit — stops the call: it reverts with the stop, and the deployment, the signer's nonce included, is taken back. - When the signer's nonce record, which survives a failed creation, takes the call over a limit — its own frame budget or the transaction's data-size limit — the call reverts with that stop and the deployment, the nonce included, is taken back; since the call is the transaction's own frame, the stop reported for the transaction is that one. + A limit the creation crosses stops the creation, and the call answers `ExecutionReverted` with the stop's revert data. + The creation keeps only the creator-side effects an ordinary failed creation keeps, under the nonce rule above. + The deploy address's account, the endowment, the transfer log and the deploy address's write record are taken back. + The signer's nonce bump stands when a deployment from nonce 0 fails, and from nonce 1 it is taken back when it is the last nonce change the deployment made. + That limit may be the creation's frame budget in data size, KV updates or state growth, the transaction's limit in one of those dimensions, or gas detention's compute limit, at the creation's start or in its initcode. + A limit the call's own charges cross stops the call: it reverts with the stop, and the deployment, the signer's nonce included, is taken back. + Those charges can cross gas detention's compute limit. + The signer's nonce record, counted on the call at its settlement, can cross the call's frame budget, in data size, in KV updates, and in state growth when the bump creates the signer, and the transaction's data-size limit once Oracle hints the creation sent used what the transaction had left. + When that record, which survives a failed creation, takes the call over either, the call MUST revert with that stop, and the deployment, the nonce included, is taken back. + The call is the transaction's own frame, so the stop reported for the transaction is that one. - The contract's interface no longer declares the four errors only Rex6 and earlier produced: `ParentBudgetExceeded(uint8,uint64,uint64)`, `InvalidTransaction()`, `InsufficientComputeGas(uint64,uint64)` and `InternalError()`. A node MUST NOT produce them: a failed database read or SALT lookup gives the transaction no outcome, as [Transaction and Block Refusals](#21-transaction-and-block-refusals) says. `AddressMismatch()` and `NoContractCreated()` remain as answers to a creation reported at another address or at none, which no deployment reaches. @@ -763,8 +1181,10 @@ An out-of-gas step halts the call, consuming its regular gas. `GAS` inside a system call reads at most 30,000,000. A transaction is not a system call: every transaction's gas is split by the execution cap, a Mega System Transaction's included. - **The pre-block budget.** - Each pre-block call MUST run from `0xfffffffffffffffffffffffffffffffffffffffe` on `max(block_gas_limit, 30,000,000)`; what the budget adds above 30,000,000 is reservoir. - In a block whose gas limit is at most 30,000,000 the call MUST have no reservoir, and its state gas MUST spill onto its regular gas (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + Each pre-block call MUST run from `0xfffffffffffffffffffffffffffffffffffffffe` on `PRE_BLOCK_CALL_GAS_LIMIT` = 31,566,720 gas, whatever the block's gas limit: 30,000,000 of regular gas, and a reservoir of 1,566,720, the state gas of sixteen fresh storage slots at the minimum bucket. + State gas the reservoir cannot pay spills onto the regular gas (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). + On MegaETH's chains, whose EIP-2935 and EIP-4788 addresses hold those EIPs' own code, a pre-block call writes at most six fresh slots — an `applyPendingChanges()` that applies both roles — so at Satin's state-gas price the reservoir pays all of it; other code at those addresses runs on the same budget, and what its state gas the reservoir cannot pay spills. + The block's gas limit, which a pre-block call does not draw on, does not set the budget; on MegaETH's chains neither EIP-2935's nor EIP-4788's code nor `applyPendingChanges()` reads `GAS`, so how much of the budget is reservoir changes no call's result. - **The pre-block sequence.** Before its transactions, a block MUST, in order: 1. make the EIP-2935 call; @@ -806,7 +1226,7 @@ A system-originated transaction and every system call: - MUST be priced at `m = 1` and MUST NOT read a bucket capacity; - MUST pay no history gas, the body and deposited code included; -- MUST NOT be stopped by any per-transaction limit or frame budget; +- MUST NOT be stopped by any per-transaction limit or frame budget, data size, KV updates and state growth included; - MUST NOT be detained; - still have their usage counted. @@ -823,30 +1243,48 @@ A deposit pays no history gas either (see [History Gas](#7-history-gas)), but a #### New behavior -A block MUST count, per transaction, its regular (as `max(regular, floor)`), state and history gas, its history bytes, its data size and its write records. -One of those counts is limited: +A block MUST count, per transaction, its regular (as `max(regular, floor)`), state and history gas, its history bytes, its data size, its KV updates and its state growth. +Three of those counts are limited. +The transaction that reaches a limit MUST be included, and a later ordinary transaction MUST be skipped before it runs. + +| Block limit | Counted | Checked | Limit | +| ------------ | ------------------------------------------ | -------------------------------- | ---------------------------------- | +| Data size | Data-size bytes per transaction | Before the next transaction runs | `BLOCK_DATA_LIMIT` = 13,107,200 | +| KV updates | Write records per transaction | Before the next transaction runs | `BLOCK_KV_UPDATE_LIMIT` = 500,000 | +| State growth | New accounts and new slots per transaction | Before the next transaction runs | `BLOCK_STATE_GROWTH_LIMIT` = 1,000 | -| Block limit | Counted | Checked | Limit | -| ----------- | ------------------------------- | -------------------------------- | ---------------- | -| Data size | Data-size bytes per transaction | Before the next transaction runs | 13,107,200 bytes | +Reaching a limit means the block's counter is at or above it. +The transaction that moves a counter from below the limit to the limit, or past it, is the one included. +When more than one of these limits is already reached, a node MAY report the skip in the order data size, then KV updates, then state growth, which is the order Rex6 checks. +A skip leaves no field in the block. +Two nodes need not name the same dimension. +The transaction is skipped in any case. -- It is a packing budget: the transaction that reaches the limit MUST be included, and later transactions MUST be skipped. - A builder that executes several candidates before it commits one MUST hold each to the block's counters again when it commits it, together with the block gas limit and the data-availability footprint; a validator commits every transaction before it executes the next, so for it the second check finds what the first found. +- A builder that executes several candidates before it commits one MUST hold each to the block's counters again when it commits it, together with the block gas limit and the data-availability footprint; a validator commits every transaction before it executes the next, so for it the second check finds what the first found. Such a builder MUST NOT commit a candidate whose sender's nonce or balance — the system address's, for a Mega System Transaction — another commit moved since the candidate executed: committing it would write the sender's account over what that commit did. Any other state a candidate read and a commit since changed is the builder's to account for, by executing the candidate again; a candidate that read the Oracle executed before a Mega System Transaction that writes it, committed after that transaction, commits the value it read. -- A deposit — a transaction whose envelope is a deposit — MUST NOT be refused by it, and MUST count towards it. - A Mega System Transaction MUST NOT be refused by it either, nor by a building policy, and MUST count towards it, so the oracle update the sequencer must be able to include is never skipped for a budget the block's other transactions used up. +- A deposit, a transaction whose envelope is a deposit, MUST NOT be refused by any of the three, and MUST count towards each. + A Mega System Transaction MUST NOT be refused by any of the three either, nor by a building policy, and MUST count towards each, so the oracle update the sequencer must be able to include is never skipped for a budget the block's other transactions used up. + The exemption covers KV and state growth for the same reason it covers data size: a deposit is derived from L1 and must be included, and a Mega System Transaction is the sequencer's own update. + Refusing either for KV or state growth alone would make the same transaction valid on the data-size budget and skippable on another block limit. + Rex6 skipped every later candidate, deposits included, once any of these counters was at or above its limit. + Satin does not. The block decides that before the transaction runs, from its envelope and the live system address (see [The Live System Address](#17-the-live-system-address)): a legacy transaction of the system shape sent from that address. A transaction from that address of another shape is no Mega System Transaction here; the block treats it as any other transaction, and it is invalid as [The Live System Address](#17-the-live-system-address) states. - A Mega System Transaction is still held to the block gas limit, and, its envelope being legacy, to the block's data-availability footprint, which it counts towards with its data-availability size; the exemption is from the data-size budget and from building policy alone. -- Execution, state and history gas have no block limit beyond the block gas limit; state gas prices the state a block adds, so the block gas limit bounds it. - The block's history bytes and write records are reported, not limited. + A Mega System Transaction is still held to the block gas limit, and, its envelope being legacy, to the block's data-availability footprint, which it counts towards with its data-availability size. + The exemption is from the three packing budgets and from building policy. +- Execution gas, state gas and history gas have no block limit beyond the block gas limit. + State gas prices the state a block adds, and `BLOCK_STATE_GROWTH_LIMIT` counts it. + The block gas limit does not stand in for that count: at `m = 1`, 1,000 fresh slots cost 97,920,000 state gas, and a block gas limit above that does not stop the 1,001st. + History bytes are reported and are not limited. + KV updates are the write-record count, and `BLOCK_KV_UPDATE_LIMIT` limits them. - The block gas limit is unchanged: a transaction's declared gas limit MUST fit in what the block has left. -- The limit is a protocol value fixed per spec with the per-transaction limits (see [Resource Limits](#10-resource-limits)), the same on every chain; no chain configuration carries it. - A node validating a block MUST hold it to that value, as the rules above state them, and to no other value. -- A block builder MAY pack tighter, as building policy: it MAY refuse a transaction for its declared gas limit, its encoded size or its data-availability size, hold the block to an encoded-size or data-availability budget, and hold the data-size limit below the protocol's value, never above it. +- The three packing budgets are protocol values fixed per spec with the per-transaction limits (see [Resource Limits](#10-resource-limits)), the same on every chain; no chain configuration carries them. + A node validating a block MUST hold the block to those values, as the rules above state them, and to no other value. +- A block builder MAY pack tighter, as building policy: it MAY refuse a transaction for its declared gas limit, its encoded size or its data-availability size, hold the block to an encoded-size or data-availability budget, and hold any of the three packing budgets below the protocol's value, never above it. + A builder MAY still pack fewer transactions than the protocol budgets allow, by not selecting them. A building policy MUST NOT refuse a deposit, which the block derived from L1 must include: none of those per-transaction limits and budgets applies to one. - It MUST NOT refuse a Mega System Transaction either: none of them applies to one, and the policy's cap on the data-size budget does not. + It MUST NOT refuse a Mega System Transaction either: none of them applies to one, and a policy's cap on a packing budget does not. A deposit counts towards the block's encoded size and not towards its data-availability size; a Mega System Transaction counts towards both; the block gas limit holds either as it holds every transaction. A node validating a block MUST NOT apply a building policy, and a policy never changes what a packed block computes: it only decides which transactions the builder packs. - Satin sets no limit on a transaction's or a block's encoded size; a block-size rule of the base layer, where a chain adopts one, is the node's to apply and is not one of these limits. @@ -874,18 +1312,19 @@ A transaction MUST be rejected before inclusion when: A deposit MUST NOT be rejected for failing a validation check: a deposit that fails any of these checks MUST be included as a failed deposit instead, which bumps its sender's nonce, credits its mint, uses its whole gas limit and applies nothing else. A read the node fails to make is not a validation check, for a deposit as for any transaction (below). A Mega System Transaction is a legacy transaction until it passes its own chain-id, nonce and EIP-3607 checks, so failing one of those is a rejection; once it passes them it runs as a deposit, and a check it fails after that includes it as a failed deposit. -A failed deposit — one that fails a check, or whose execution halts — reports its whole gas limit as regular gas, and no state gas and no history gas on any ledger, the transaction's or the block's: the caller account it creates for a sender that did not exist carries no state gas, unlike the one a deposit that runs to a success or a revert creates (see [The Revert-Class Stop](#11-the-revert-class-stop)). +A failed deposit, one that fails a check, or whose execution halts, reports its whole gas limit as regular gas, and no state gas and no history gas on any ledger, the transaction's or the block's: the caller account it creates for a sender that did not exist carries no state gas, unlike the one a deposit that runs to a success or a revert creates (see [The Revert-Class Stop](#11-the-revert-class-stop)). +That created account still counts as one of state growth, on the transaction's reported usage and on the block counter (see [Resource Limits](#10-resource-limits)). A transaction MUST be skipped for the current block, and MAY be included in a later one, when: - its declared gas limit does not fit in the block's remaining gas; - its data-availability footprint does not fit in what the block's gas limit has left for footprints; -- it is neither a deposit nor a Mega System Transaction and the block has reached its data-size limit; +- it is neither a deposit nor a Mega System Transaction and the block has reached its data-size limit, its KV-update limit, or its state-growth limit (see [Block Limits](#20-block-limits)); - it is not a deposit and the block activates Satin or an Optimism fork at or after Jovian in the Optimism fork order, as the chain configuration schedules it (see [Base Layer](#1-base-layer-optimism-karst-ethereum-osaka)). A block that contains a transaction it should have skipped is invalid. -A block builder MAY also skip a transaction other than a deposit or a Mega System Transaction under its own building policy (see [Block Limits](#20-block-limits)): a per-transaction declared-gas, encoded-size or data-availability limit, a block encoded-size or data-availability budget, or the block's data-size limit held below the protocol's value. +A block builder MAY also skip a transaction other than a deposit or a Mega System Transaction under its own building policy (see [Block Limits](#20-block-limits)): a per-transaction declared-gas, encoded-size or data-availability limit, a block encoded-size or data-availability budget, or any of the three packing budgets held below the protocol's value. A transaction over a builder's per-transaction limit never fits that builder's blocks, and the builder MAY drop it. A block is not invalid for a transaction a building policy would have skipped. @@ -923,14 +1362,14 @@ The witness is defined by what the block's execution returns and exports, and a A transaction loads every account and slot its execution reads from the state: in its validation (the registry's account and system-address slot every transaction reads included), in its fee settlement, and in any of its frames, a frame that reverted or halted included, and a frame of a deposit that failed. A failed frame's writes are taken back, not its reads; a failed deposit takes back everything but its sender's nonce bump and mint, not its reads; and a validator re-executing the transaction makes the same reads in the same frames. The one exception is the L1 block info the transaction is priced against, which the pre-block phase loads for the whole block (see the L1 block info, below). - A read that gas or a limit skipped loads nothing (see the reads a validator makes again, below). + A read that gas or a limit skipped loads nothing (see the reads a validator makes again, below), except an authority account the authorization preflight consulted: that account is loaded whether or not the list is applied (see [Resource Limits](#10-resource-limits)). Execution reports what it loaded in the states the block commits: a pre-block step in the state it commits on its own, and a transaction in its returned state, which the block commits and which names every account and slot the transaction loaded, whether it wrote it or not, whether the frame that loaded it succeeded or not, and, for a deposit, whether the deposit failed or not. The set is a function of those states and the exports alone, not of how the node caches state: a node that serves a block's execution from a state cache another block filled builds the same witness, because the states name what was loaded whether or not a database was asked for it. A state names the keys; the values are the chain's. A slot of an account the chain does not hold before the block is not recorded: such an account has no storage, and a validator MUST answer every slot of it with zero without looking it up. The code in particular is not the code a returned state carries: a transaction that replaces an account's code — an EIP-7702 authority delegated anew — is admitted against the code the chain held, and its returned state carries the code it wrote. - **What the block reads, and where it lands.** - A transaction's loads are in its returned state: its sender, its recipient or created address, every account and every slot any of its frames loads, the fee recipients, the registry's account and system-address slot every transaction reads, and a keyless deployment's signer and deploy address; the state names an account whether or not the load brought its code. + A transaction's loads are in its returned state: its sender, its recipient or created address, every account and every slot any of its frames loads, the fee recipients, the registry's account and system-address slot every transaction reads, every authority account the authorization preflight consulted, and a keyless deployment's signer and deploy address; the state names an account whether or not the load brought its code. The pre-block phase's reads land in the states it commits, one per step, in order: the two EIP calls' states, in Satin's activation block each predeploy's read-only entry, the registry's pending slots the due-change decision read, the `applyPendingChanges()` call's state, and last the L1 block info. Each state is committed whole, read-only entries included, and a node MUST collect the states as they are committed: what a commit keeps of a state is only what it changed, which holds none of the read-only entries. `BLOCKHASH` reads the chain's history outside the journal and its reads are exported; a SALT bucket's capacity and the oracle service's answer are read outside the database and are exported or recorded. @@ -972,7 +1411,8 @@ The witness is defined by what the block's execution returns and exports, and a A validator without a service that finds another value in the slot computes another block; a transaction that wrote the value but was dropped by the builder wrote nothing the chain holds. Hints reach the service alone: they are not in the witness, and change nothing a validator computes except through the answers the service then gives, which the records carry. - **The check.** - A block replayed on exactly its witness MUST produce the same receipts, state changes, gas ledgers, logs, block counters and exports as the block's execution, and MUST read nothing the witness does not hold. + A block replayed on exactly its witness MUST produce the same receipts, state changes, gas ledgers, logs and block counters as the block's execution, and MUST read nothing the witness does not hold. + Its exports MUST be a subset of the building node's and MAY be a proper one: the building node's also hold the buckets and block hashes that candidates it executed and dropped asked for, which the replay, running the included transactions alone, never asks for. ## Developer Impact @@ -985,7 +1425,17 @@ A contract that checks `gasleft()` against a large constant sees at most the reg A frame stopped by a resource limit or by gas detention now reverts rather than halting the transaction, with `MegaLimitExceeded(kind, limit)` as its output: its caller sees a failed call whose return data is the stop, and can catch it and carry on within what the limits leave. A transaction whose own frame is stopped reverts with the stop, and its sender pays only for what ran. -No KV-update or state-growth limit stops a transaction, so kinds 1 and 3 are never reported. +A KV crossing reverts with kind 1 and a state-growth crossing with kind 3. +`limit` is the count. +At the protocol caps the data-size cap is tighter than the KV cap, because each record weighs 40 bytes and 500,000 records weigh more than 13,107,200 bytes. +Under the execution cap a transaction cannot pay the regular gas of enough writes to reach either number, and the KV check is still made. +The state-growth limit is reachable at the minimum bucket: 1,000 fresh slots cost 97,920,000 state gas. +Destroying a contract created in the same transaction refills, at the price charged, the state gas of each part that was absent at the transaction's start: the account leaf, the deposited code and each new slot. +State growth falls for that leaf and for those slots. +The write records of those parts are taken back, and so are the deposited code's data size and history gas. +A part that existed at the start, such as the leaf of an address funded before the transaction, is an ordinary deletion: no refill, no fall, and its write record stands. +A destruction that moves no balance creates no beneficiary. +EIP-8037 leaves that state gas charged, and Rex6 refunded none of the storage gas and took none of those records back. A transaction that reads volatile data is still held to its compute at the read plus the cap (20,000,000), but until a regular charge needs gas past that limit, `GAS`, call forwarding and state or history charges see its whole gas, and the stop is a revert of the frame that makes that charge. `VolatileDataAccessDisabled` can carry the value 12 (`SLOTNUM`), which a Solidity handler must decode as a `uint8`. @@ -1019,7 +1469,7 @@ A node, a stateless validator and a replay tool must agree on everything below, The reference implementation reports the body-size refusal (`TX_BODY_OVER_DATA_SIZE_LIMIT`) and the system-shape refusal as invalid-transaction errors with fixed messages, which a pool maps to its own error. The rest of the stateless validation is the base layer's. Whether a recipient, a created account or an authority is new is the state's to say: EIP-2780 charges it when the transaction runs, and a gas limit that cannot pay it runs out of gas rather than being refused. - The history of the write records a transaction's start makes is charged when it runs too: one record for the recipient of its value (none for value sent to the sender itself or to an authority it applied) or the account it creates, and one for each authority that applies other than the sender. + The history of the write records a transaction's start makes is charged when it runs too: one record for the recipient of its value (none for a recipient the transaction has changed already: the sender itself, or an authority it applied) or the account it creates, and one for each authority that applies other than the sender. So the least gas limit validation admits is not what a transaction needs: at that gas limit a transfer of value to another account runs out of gas on its recipient's record, and one to a new account needs that account's state gas as well. A deposit and a Mega System Transaction pay no history gas; a pool that recognizes the latter, and refuses a transaction from the live system address without the system shape, needs the live system address from the state. That address changes only in a block's pre-block step and then holds for the whole block, so a pool reads it again for every block, from the state after that block's pre-block changes. @@ -1039,6 +1489,10 @@ A node, a stateless validator and a replay tool must agree on everything below, A node builds a block's witness from the states the block commits, in order: each pre-block step's state, committed on its own, read-only entries included, then each included transaction's returned state (see [The Stateless Witness](#22-the-stateless-witness)). The reference implementation commits them through the database's commit, so a hook on that commit — revm's `State::set_state_hook` — receives each state whole; the block's transitions and bundle keep only what a state changed, and a witness taken from them misses the activation block's predeploys, the registry's pending slots and the L1 block info. Block execution hands the pre-block states to nothing else. +- **An account the state does not hold.** + The destruction table gives an account's leaf back only when no account stood at the address at the transaction's start (see [The destruction table](#the-destruction-table)), and the node's state says which. + An address the state holds no account for must be answered as no account — `None` from revm's `Database::basic` in the reference implementation — never as an empty account, which is a leaf the state holds. + A state that answers an empty account for an address it does not hold gives that leaf back to no destruction, and executes a different chain. - **The predeploys.** Satin runs on a chain that ran the legacy forks: Rex5 deployed the SequencerRegistry and upgraded the Oracle to 2.0.0, and Rex6 upgraded the SequencerRegistry to 2.0.0, so the chain holds the six system contracts at the versions Satin runs, and OP's genesis tooling gave it the EIP-7997 factory. Satin's activation block checks that they are there and is invalid otherwise (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)); it deploys, upgrades and seeds nothing, so a chain must have run a Rex6 block before `satinTime`. @@ -1047,11 +1501,13 @@ A node, a stateless validator and a replay tool must agree on everything below, A builder that executes a transaction and commits it after other commits MUST commit through the checked commit (`commit_transaction_outcome`), which refuses an outcome whose sender's nonce or balance another commit moved (see [Block Limits](#20-block-limits)). The refusal is an internal error of the node (`MegaBlockExecutionError::StaleOutcome`), not a verdict on the block or the transaction: the builder executes the transaction again. - **Packing a Mega System Transaction.** - A block's data-size budget and a builder's policy never refuse one (see [Block Limits](#20-block-limits)), so a builder has no reason to skip it for either and requeue the transaction that triggered it; the block gas limit and the data-availability footprint still hold it, and a builder keeps room for both. + A block's data-size, KV and state-growth budgets, and a builder's policy, never refuse one (see [Block Limits](#20-block-limits)), so a builder has no reason to skip it for any of them and requeue the transaction that triggered it; the block gas limit and the data-availability footprint still hold it, and a builder keeps room for both. The execution result tells a node which transactions the block treated so: `MegaBlockTxResult::is_system_transaction`, beside `is_deposit`, which stays the envelope's. - **Reporting a limit stop.** A stop is a revert whose output is `MegaLimitExceeded(kind, limit)`, and a contract can revert with the same bytes, as can a caller that re-raises the stop a frame below it returned. - Execution reports the crossing that produced the result of the transaction's own frame — the transaction's data-size limit, gas detention's compute limit, or that frame's own data-size budget — and none when that result is not the stop's revert; a node must read that report, and must not infer a stop from the output alone. + Execution reports the crossing that produced the result of the transaction's own frame: the transaction's data-size, KV or state-growth limit, gas detention's compute limit, or that frame's own budget in data size, KV or state growth. + It reports none when that result is not the stop's revert. + A node must read that report, and must not infer a stop from the output alone. A stop a caller caught produced no result of the transaction's own frame: the transaction reports none, and it can succeed, so a node maps an RPC error or a builder's handling of a stopped transaction from that report alone (`LimitStop::from_result`, or `MegaTransactionOutcome::limit_stop`), never from the output bytes. - **The chain configuration.** A genesis file's `config` object carries Satin as one key beside the other forks'. @@ -1064,8 +1520,9 @@ A node, a stateless validator and a replay tool must agree on everything below, No key names a limit: the limits are the spec's (see [Resource Limits](#10-resource-limits)). No key names the `SequencerRegistry`'s roles either: the registry is the one the legacy forks left (see [System Calls and Pre-Block Calls](#18-system-calls-and-pre-block-calls)). A key that starts with `satin`, in any ASCII letter case, and is not `satinTime` exactly is refused, so a file written against an earlier version of the format, which named the registry's roles (`satinInitialSystemAddress`, `satinInitialSequencer`, `satinInitialAdmin`, `satinMinRotationDelay`), `satinInitialFromBlock` or the limits, does not load, whether or not it carries `satinTime`. - A key given twice is refused only where the reader still sees both copies, as a parser handed the object's text does; a reader that first parses the file into a JSON value, as the reference CLI and a node do, sees only the last copy and reads it. + A key given twice is read as its last copy by every reader, whether it is handed the object's text or first parses the file into a JSON value, as the reference CLI and a node do, which keeps the last copy alone. `satinTime` is a JSON number up to 2^64 − 1. + It may also be given as the object `{"$serde_json::private::Number": ""}`, read as the number its decimal digits write, with the same range: that is the form `serde_json` hands a number over in when its `arbitrary_precision` feature is on, and a reader cannot tell it from the same object written in the file. The key format is provisional until a network publishes a genesis file carrying it. The Satin key does not time the forks Satin runs on: Optimism Karst and the Ethereum forks it includes, Osaka among them, are timed by the configuration's own keys for them, and a node must check their timing against `satinTime` both ways when it loads the configuration. @@ -1077,12 +1534,14 @@ A node, a stateless validator and a replay tool must agree on everything below, ## Safety and Compatibility Satin changes nothing about blocks under earlier specs: a node replaying history resolves each block's spec from its timestamp and applies that spec's rules. -Satin is a restatement rather than a delta, so a Rex6 rule this page does not carry over — the compute-gas limit, the storage-gas formulas, the sandbox, the 98/100 forwarding, the cold first touch of preload-warm addresses — does not apply to Satin blocks. +Satin is a restatement rather than a delta, so a Rex6 rule this page does not carry over (the compute-gas limit, the storage-gas formulas, the sandbox, the cold first touch of preload-warm addresses) does not apply to Satin blocks. The six system contracts keep their Rex6 bytecode and ABI, but for the four errors `IKeylessDeploy` no longer declares; Satin deploys and upgrades none of them, and its activation block refuses a chain that does not hold them, and the EIP-7997 factory, at the versions Rex6 left. A transaction from the live system address without the system shape is refused, as in Rex6, now as an invalid transaction: a deposit from the system address, which Rex6 refused with an error that left its block unexecutable, is a failed deposit, so the engine no longer depends on the L1 portal refusing deposits from each system address a rotation installs. -The per-transaction and block limits and the detention caps are protocol values fixed by the spec, not chain configuration, so every node executing any chain holds its Satin blocks to the same ones: the data-size limits at 13,107,200 bytes and the detention caps at 20,000,000 each. +The per-transaction and block limits and the detention caps are protocol values fixed by the spec, not chain configuration, so every node executing any chain holds its Satin blocks to the same ones: data size at 13,107,200 bytes, KV updates at 500,000, state growth at 1,000, and the detention caps at 20,000,000 each. +The KV check is enforced even where the data-size cap binds first. +Dropping it because 40 bytes times 500,000 exceeds 13,107,200 would retire the cap the moment the byte weight or the data-size cap changed. No chain can set a limit that stops the block's L1 attributes deposit, whose data size is its body, its calldata and a write record for each slot of the L1 block contract it changes: 526 bytes on recorded mainnet blocks within one L1 origin. The per-transaction gas-limit, encoded-size and data-availability limits are a block builder's policy, not the chain's: a node validating a block does not apply them. @@ -1090,7 +1549,9 @@ Satin is unstable and not scheduled on any network: its prices, limits and rules ## References -- [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) — state gas and the reservoir. +- [EIP-8037](https://eips.ethereum.org/EIPS/eip-8037) as of [commit `c406bdb2ff`](https://github.com/ethereum/EIPs/commit/c406bdb2ffbf2fbf9d85698e97b3b2e8b6e79112) — state gas and the reservoir. + Satin adopts the child-merge return of [commit `3ff5cff17a`](https://github.com/ethereum/EIPs/commit/3ff5cff17a11ab31273ee14ebea0df8bbc4f4aef), drawing only the reservoir the child returns, and does not adopt the transaction gas cap of [commit `d7087803ca`](https://github.com/ethereum/EIPs/commit/d7087803ca236498c73f64665df0ddac7d621950). + The creation-collision rule of [commit `dbc6d457cb`](https://github.com/ethereum/EIPs/commit/dbc6d457cbf90d5f9d55552f3fd91d58b88cc898) and the first-frame authority outcome of [commit `9dcd72754f`](https://github.com/ethereum/EIPs/commit/9dcd72754f3fe4b48a4dbeffee669dc4c60f7ec5) are this page's own rules, stated in [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model). - [EIP-2780](https://eips.ethereum.org/EIPS/eip-2780) — the decomposed intrinsic cost. - [EIP-8038](https://eips.ethereum.org/EIPS/eip-8038) — the state-access prices. - [EIP-7708](https://eips.ethereum.org/EIPS/eip-7708) — transfer logs. From 07b6ebc0ae2809d685fce2b57c710033a7214661 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:27:06 +0800 Subject: [PATCH 189/201] docs(skills): the Satin review guide with #407 merged --- .claude/skills/satin-review/SKILL.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5f51a5eae..5f6088b08 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -1,6 +1,6 @@ --- name: satin-review -description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine: the stacked pull requests merged into it, and #407 merges into it before it is retargeted. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. +description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests and #407 have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. --- # Reviewing the Satin engine (pull request #386) @@ -15,7 +15,7 @@ The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. ## What is under review - The Satin engine, in pull request #386 (`cz/feat/satin-w2`), judged at its final state. - The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) merged into it, and #407 (`cz/feat/satin-w9`) merges into it next; each description explains its part as it was merged, and a later part may have changed an earlier one. + The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) merged into it, and then #407 (`cz/feat/satin-w9`); each description explains its part as it was merged, and a later part may have changed an earlier one. "Design changes a reviewer must know" below lists what #407 changed. - The review range is the pull request's own diff. Its base, `cz/feat/satin-review-base`, is `satin` before the Satin skeleton: `a8f8c7c9`, the CI-only commit before it. @@ -42,11 +42,10 @@ The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. ## What is still moving -Nothing, once #407 merges into this branch. -#407 holds everything its description listed as still to be added: inspectors on revm's own inspected lifecycle, a rewritten result taken as given, one fixed gas budget for the pre-block calls, the cleanups, and the KV-update and state-growth limits with their 98/100 frame shares and the destruction table's give-backs. +Nothing. +#407 has merged into this branch, and with it everything its description listed as still to be added: inspectors on revm's own inspected lifecycle, a rewritten result taken as given, one fixed gas budget for the pre-block calls, the cleanups, and the KV-update and state-growth limits with their 98/100 frame shares and the destruction table's give-backs. It also counts a creator's nonce record when the creation returns, which its description did not list. -Until #407 merges, the final code of the modules it changes is on its head (`cz/feat/satin-w9`). -With #407 merged, every module is at its final state for this review: there is no longer a table of stable and changing modules, nor a rule to hold back findings in a changing one. +Every module is at its final state for this review: there is no longer a table of stable and changing modules, nor a rule to hold back findings in a changing one. What follows this pull request changes no rule. The fork pins move from the reviewed commits to the merged commits of megaeth-labs/revm#76 and megaeth-labs/op-revm#8, and to release tags once the line is final. Performance work is left for later: the optimisations #407 recorded are made together once the structural work is done, measured against CodSpeed's report. From aa5279a9cfca0afc6cb514518d4151310a643c6a Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:33:34 +0800 Subject: [PATCH 190/201] refactor(limit): count a built frame's or a success answer's start from the journal once revm decided it The records, the state growth and the transfer log a start made on its frame are read off the journal against the start's accounts as they stood before revm decided it. The prediction stays, for now, for the two answers that keep nothing to read and as a debug check that the two agree. --- crates/mega-evm/src/evm/execution.rs | 58 ++++++++++++++------ crates/mega-evm/src/limit/mod.rs | 4 +- crates/mega-evm/src/limit/record.rs | 75 +++++++++++++++++++++++++- crates/mega-evm/src/test_utils/logs.rs | 2 +- 4 files changed, 121 insertions(+), 18 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 329a8da8b..4cd23805c 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -53,7 +53,7 @@ use revm::{ use crate::{ access::ComputeStop, charge_write_records_history, history_gas, - limit::{Counted, CreatorBefore}, + limit::{Counted, CreatorBefore, StartBefore}, synthetic_frame_result, system::keyless, write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, @@ -635,7 +635,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm (inputs.caller, Some(inputs.target_address)), + FrameInput::Create(inputs) => { + (inputs.created_address(account_nonce(ctx, inputs.caller())), None) + } + FrameInput::Empty => unreachable!("matched above"), }; #[cfg(debug_assertions)] let made = MadeRecords::before(ctx, frame_init, records); + let mark = mark(ctx.journal_mut()); Ok(Self { - mark: mark(ctx.journal_mut()), + before: ctx.accounts().start_before(before.0, before.1, mark.log_i), + mark, + charged, counted: records.counted().with_growth(growth, 0), - credit, gas_limit: input_gas_limit(&frame_init.frame_input), reservoir, shares, @@ -1306,6 +1312,28 @@ impl FrameStart { }) } + /// What the start made on its frame, read off the journal once revm decided it — its records + /// and their bytes, its state growth and its transfer log ([`Accounts::start_made`]) — and what + /// its caller gets back once the frame returned with its start kept: what it paid for the + /// records on the frame, less the price of those the start made, and the price of those it + /// took back. + /// + /// [`Accounts::start_made`]: crate::limit::Accounts + fn made( + &self, + ctx: &MegaContext, + ) -> (Counted, u64) { + let (records, counted) = ctx.accounts().start_made(&self.before); + debug_assert_eq!(counted, self.counted, "the start made what was predicted"); + let credit = if ctx.prices_history() { + let price = |records| write_record_history_gas(records).unwrap_or(0); + self.charged.saturating_sub(price(records.added)).saturating_add(price(records.taken)) + } else { + 0 + }; + (counted, credit) + } + /// Asserts revm's start made the records counted for it, read off the journal once revm built /// the frame. #[cfg(debug_assertions)] diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index d29dcc328..5c95cc98e 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -180,7 +180,9 @@ mod record; pub use limit::AdditionalLimit; pub(crate) use limit::Counted; -pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes}; +#[cfg(any(test, feature = "test-utils"))] +pub(crate) use record::is_transfer_log; +pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes, StartBefore}; #[cfg(debug_assertions)] pub(crate) use record::{RecordDelta, StartRecords}; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index fd43e9c3a..50c75539a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -38,7 +38,10 @@ use revm::{ host::{CompletedWrite, FrameStartKind}, journaled_state::entry::{JournalEntry, SelfdestructionRevertStatus}, }, - primitives::{Address, StorageKey, KECCAK_EMPTY, U256}, + primitives::{ + eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC}, + Address, Log, StorageKey, KECCAK_EMPTY, U256, + }, state::{Account, AccountInfo, EvmState, TransactionId}, Journal, }; @@ -156,6 +159,8 @@ pub(crate) struct Accounts<'a> { state: &'a EvmState, /// The journal's entries, which revm clears between transactions: this transaction's. entries: &'a [JournalEntry], + /// The logs the journal holds, which a failed frame's revert takes back with its entries. + logs: &'a [Log], transaction_id: TransactionId, /// Whether a value movement journals an EIP-7708 transfer log. transfer_logs: bool, @@ -184,6 +189,37 @@ pub(crate) struct CreatorBefore { empty: bool, } +/// An account a frame's start may change on its frame, as the transaction held it before revm +/// decided the start. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct AccountBefore { + /// The account. + address: Address, + /// Whether the transaction had changed it from what it loaded. + changed: bool, + /// Whether it was empty under EIP-161. + empty: bool, +} + +/// The accounts a frame's start writes on its frame — a call's caller and target, a creation's +/// created account — as the transaction held them before revm decided the start, and how many logs +/// the journal held then: what tells, once revm decided the start, what it made +/// ([`Accounts::start_made`]). A creation's creator is not among them: its nonce record is the +/// creator's, read off the bump once the creation returned ([`CreatorBefore`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct StartBefore { + /// The accounts, each once. + accounts: [Option; 2], + /// The logs the journal held. + logs: usize, +} + +/// Whether `log` is the EIP-7708 transfer log revm journals for a value movement: a log from the +/// system address `0xff…fe` carrying ERC-20's `Transfer` event, which no contract can emit. +pub(crate) fn is_transfer_log(log: &Log) -> bool { + log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics().first() == Some(Ð_TRANSFER_LOG_TOPIC) +} + impl<'a> Accounts<'a> { /// The accounts `journal` holds, in a transaction whose value movements journal transfer logs /// or not (`transfer_logs`). @@ -191,6 +227,7 @@ impl<'a> Accounts<'a> { Self { state: &journal.state, entries: &journal.journal, + logs: &journal.logs, transaction_id: journal.transaction_id, transfer_logs, } @@ -403,6 +440,42 @@ impl<'a> Accounts<'a> { Counted::records(record.added, record.taken, false).with_growth(u64::from(grows), 0) } + /// The accounts at `first` and `second` as the transaction holds them before revm decides a + /// start that writes them on its frame, read loaded, as revm reads them, the journal holding + /// `logs` logs. An account named twice is read once. + pub(crate) fn start_before( + &self, + first: Address, + second: Option
, + logs: usize, + ) -> StartBefore { + let read = |address| AccountBefore { + address, + changed: self.is_changed(address), + empty: self.is_empty(address), + }; + let second = second.filter(|second| *second != first).map(read); + StartBefore { accounts: [Some(read(first)), second], logs } + } + + /// What the start `before` was read of made on its frame, read off the journal once revm + /// decided it and before anything ran on it: each account's write record, by its change since + /// ([`RecordDelta::of_account`]); one account of state growth for each that was empty and is + /// not; and the EIP-7708 transfer log revm journaled since. The records are answered apart as + /// well, for the price of their history. + pub(crate) fn start_made(&self, before: &StartBefore) -> (RecordDelta, Counted) { + let mut records = RecordDelta::NONE; + let mut growth = 0; + for account in before.accounts.iter().flatten() { + let changed = self.is_changed(account.address); + records = records.with(RecordDelta::of_account(account.changed, changed)); + growth += u64::from(account.empty && !self.is_empty(account.address)); + } + let logs = self.logs.get(before.logs..).unwrap_or_default(); + let logged = logs.iter().any(is_transfer_log); + (records, Counted::records(records.added, records.taken, logged).with_growth(growth, 0)) + } + /// The account of state growth a transfer of `value` from `from` to `to` makes, as the /// journal's state stands: one when it moves value `from` can fund to another account that is /// empty, which the transfer creates. A `CALLCODE`'s transfer is from the calling account to diff --git a/crates/mega-evm/src/test_utils/logs.rs b/crates/mega-evm/src/test_utils/logs.rs index 640d69327..32511273b 100644 --- a/crates/mega-evm/src/test_utils/logs.rs +++ b/crates/mega-evm/src/test_utils/logs.rs @@ -22,7 +22,7 @@ pub fn transfer_log(from: Address, to: Address, value: U256) -> Log { /// Whether `log` is an EIP-7708 transfer log, rather than one a contract emitted. pub fn is_transfer_log(log: &Log) -> bool { - log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics().first() == Some(Ð_TRANSFER_LOG_TOPIC) + crate::limit::is_transfer_log(log) } #[cfg(test)] From 2eb9858ac82bd6fc96be2078419c95abdb15dc67 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:36:52 +0800 Subject: [PATCH 191/201] feat(limit): hold a start's answer only to what the journal kept An answer that failed kept nothing, revm having taken back what its start moved, so it is held to nothing and its result is revm's: a value call to a precompile that fails burns its forward as any failed precompile does, rather than being answered with a limit's stop. A precompile call gas detention answers from its price before revm runs it moved nothing, so it is held to the price alone: the stop is the compute stop, whatever the records its value transfer would have made. --- crates/mega-evm/src/evm/execution.rs | 56 ++++---- crates/mega-evm/src/limit/limit.rs | 8 -- .../tests/satin/detained_transfers.rs | 44 +++---- .../mega-evm/tests/satin/limit_matrix/stop.rs | 52 ++++---- crates/mega-evm/tests/satin/state_growth.rs | 10 +- crates/mega-evm/tests/satin/transfer_logs.rs | 124 +++++++++++++----- 6 files changed, 170 insertions(+), 124 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 4cd23805c..aa00a55be 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -547,12 +547,13 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm( ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) } -/// Holds `answer`, revm's or gas detention's answer to the call `start` began, to `verdict`: a -/// crossing is the stop the answer gives way to, on the gas its caller forwarded, untouched, as a -/// frame stopped before it ran ([`stop_the_answer`]). What a successful answer's start moved is -/// taken back with it ([`take_back_a_stopped_answer`]); a failed one's revm took back itself. +/// Holds `answer`, the success revm answered the call `start` began with, to `verdict`: a crossing +/// is the stop the answer gives way to, on the gas its caller forwarded, untouched, as a frame +/// stopped before it ran ([`stop_the_answer`]), and what the answer's start moved is taken back +/// with it ([`take_back_a_stopped_answer`]). A failed answer kept nothing and is held to nothing. fn stop_the_answer_at( ctx: &mut MegaContext, start: &FrameStart, diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 4e772df15..7e39fd305 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -623,14 +623,6 @@ impl AdditionalLimit { kept.transfer_logs += u64::from(counted.transfer_log); } - /// The verdict on a start revm is not asked to decide — a call gas detention answers without - /// running the precompile it targets — had revm made it: `counted`, the records and transfer - /// log its value transfer would make, held to `shares`, the pools its frame would start with, - /// and to the transaction's limits. Nothing is counted. - pub(crate) fn hypothetical_start(&self, counted: &Counted, shares: PoolAmounts) -> LimitCheck { - self.check(shares, [0; PoolId::COUNT], counted, true) - } - /// Admits an Oracle hint of `bytes`: held to the transaction's limit before it is counted, and /// never taken back once counted. A hint is on no frame's budget. pub(crate) fn admit_hint(&mut self, bytes: u64) -> LimitCheck { diff --git a/crates/mega-evm/tests/satin/detained_transfers.rs b/crates/mega-evm/tests/satin/detained_transfers.rs index 75da0292b..30df02889 100644 --- a/crates/mega-evm/tests/satin/detained_transfers.rs +++ b/crates/mega-evm/tests/satin/detained_transfers.rs @@ -300,18 +300,15 @@ fn calls_with_value_returning(first: u8, to: Address) -> Bytes { } /// A value call to modexp after a read, priced past the allowance and within the forward, is -/// answered without running with gas detention's stop — unless the start it would have made -/// crosses the data size first. The start's records, modexp's and the caller's, and the transfer -/// log of the value it would move are held to the transaction's limit and to the budget its frame -/// would get before detention classifies the answer, so data size wins over compute at one start. +/// answered without running with gas detention's stop, before revm decides the start: its value +/// never moves, so the answer is held to the price alone, and no data size is counted for the +/// records and the transfer log its value transfer would have made. /// -/// Under a transaction limit, or a frame cap, that leaves the start one byte short of its records -/// and its log — which the records alone fit, so the log is what crosses — the call is answered -/// with the data-size stop, naming the budget the start crossed. With room for the start in its -/// frame's share, it is answered with the compute stop. Nothing moves either way, and the -/// transaction keeps its body alone. +/// Under a transaction limit, or a frame cap, that would leave the start one byte short of its +/// records and its log, the call is answered with the compute stop, as it is with room for the +/// start in its frame's share. Nothing moves, and the transaction keeps its body alone. #[test] -fn test_a_start_crossing_data_size_and_compute_at_once_is_the_data_size_stop() { +fn test_a_precompile_answered_from_its_price_at_a_data_size_boundary_is_the_compute_stop() { use alloy_sol_types::SolError; use mega_evm::{LimitKind, MegaLimitExceeded}; let above = costly_modexp_input(64, 0); @@ -324,27 +321,20 @@ fn test_a_start_crossing_data_size_and_compute_at_once_is_the_data_size_stop() { let body = transaction_body_bytes(&tx); let limits = EvmTxRuntimeLimits::default(); let rows = [ - // The transaction's own frame gets what the body leaves, and the call's start the - // share of it, which the start crosses before the transaction's limit. - ( - "the transaction's limit", - limits.with_tx_data_size_limit(body + start - 1), - Some(share(start - 1)), - ), - ("the frame cap", limits.with_frame_data_size_limit(cap), Some(start - 1)), - ("room for the start", limits.with_tx_data_size_limit(body + room), None), - ("room under the frame cap", limits.with_frame_data_size_limit(cap + 1), None), + // The transaction's own frame gets what the body leaves, and the call's start would + // get the share of it, which its value transfer's records and log would cross. + ("the transaction's limit", limits.with_tx_data_size_limit(body + start - 1)), + ("the frame cap", limits.with_frame_data_size_limit(cap)), + ("room for the start", limits.with_tx_data_size_limit(body + room)), + ("room under the frame cap", limits.with_frame_data_size_limit(cap + 1)), ]; - for (case, limits, data_size) in rows { + for (case, limits) in rows { let db = accounts(calls_with_value_returning(TIMESTAMP, MODEXP), VALUE); let (run, _) = run_tx(db, tx.clone(), limits, false); assert!(run.outcome.result.is_success(), "{case}: {:?}", run.outcome.result); - let stop = match data_size { - Some(limit) => MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit }, - None => MegaLimitExceeded { - kind: LimitKind::ComputeGas.as_u8(), - limit: run.limit.expect("the read set a limit"), - }, + let stop = MegaLimitExceeded { + kind: LimitKind::ComputeGas.as_u8(), + limit: run.limit.expect("the read set a limit"), }; assert_eq!( run.outcome.result.output(), diff --git a/crates/mega-evm/tests/satin/limit_matrix/stop.rs b/crates/mega-evm/tests/satin/limit_matrix/stop.rs index d25f62590..440e0dd0d 100644 --- a/crates/mega-evm/tests/satin/limit_matrix/stop.rs +++ b/crates/mega-evm/tests/satin/limit_matrix/stop.rs @@ -189,17 +189,17 @@ fn test_a_creator_nonce_record_stops_the_creator_at_its_kv_budget() { /// A value `CALL` to the BN254 pairing precompile with no input, whose price, 45,000, is past /// what a read of the block environment under a cap of 20,000 leaves once the caller's own -/// `CALL` is paid, and within the forward. The start's two records, the caller's -/// balance and the precompile's, are inside every budget, so the price is the stop, kind 2, and -/// the value, the transfer log and the records are taken back with it, the new account's state -/// gas included. A value the caller cannot fund runs no precompile, counts nothing and is stopped -/// by no limit. +/// `CALL` is paid, and within the forward. Gas detention answers it from its price before revm +/// runs it, so the value never moves: the price is the stop, kind 2, and nothing is moved, logged +/// or recorded, the new account's state gas coming back. A value the caller cannot fund runs no +/// precompile, counts nothing and is stopped by no limit. /// -/// Under a transaction KV limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, -/// the two records cross it, and the stop is kind 1, `limit` 1, not the price. A precompile the -/// node cannot price needs a node precompile and is not run. +/// The answer moved nothing, so it is held to the price alone: under a transaction KV limit of 2, +/// where the started frame's KV share, `floor(2 × 98 / 100)` = 1, could not hold the two records +/// its value transfer would make, the stop is still kind 2. A precompile the node cannot price +/// needs a node precompile and is not run. #[test] -fn test_precompile_records_stop_at_the_kv_share_before_the_price() { +fn test_a_precompile_answered_from_its_price_is_held_to_the_price_alone() { const PAIRING: alloy_primitives::Address = alloy_primitives::address!("0000000000000000000000000000000000000008"); let paying = |value: u64| { @@ -215,10 +215,10 @@ fn test_precompile_records_stop_at_the_kv_share_before_the_price() { let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the price is the stop"); - assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO, "the value is taken back"); - assert!(outcome.result.logs().is_empty(), "the transfer log is taken back"); - assert_eq!(outcome.usage.write_records, 0, "the records are taken back"); + assert_eq!(returned_stop(&outcome).kind, 2, "the price is the stop"); + assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO, "the value never moved"); + assert!(outcome.result.logs().is_empty(), "no transfer log"); + assert_eq!(outcome.usage.write_records, 0, "no record"); assert_eq!(outcome.usage.data_size, super::BODY_BYTES); assert_eq!(outcome.gas.state, 0, "the new account's charge comes back"); @@ -236,24 +236,24 @@ fn test_precompile_records_stop_at_the_kv_share_before_the_price() { let limits = limits.with_tx_kv_update_limit(2); let outcome = execute_under(world(&[(CONTRACT, paying(1))]), call_tx(gas), limits); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(returned_stop(&outcome).kind, 2, "the price alone, not the records"); assert_eq!(super::balance_of(&outcome, PAIRING), U256::ZERO); assert_eq!(outcome.usage.write_records, 0); } } -/// A precompile the node installed, whose start's records are held before its answer. +/// A precompile the node installed, which runs out of the allowance gas detention leaves it. /// -/// A precompile the engine cannot price runs on what the compute limit leaves its frame, and the -/// start's records are held to the limits before its answer is: a value `CALL` to a node's own -/// precompile, installed through `with_dyn_precompiles`, whose price, 100,000, is past what a read -/// of the block environment under a cap of 30,000 leaves once the caller's own `CALL` is paid, and -/// within the forward. With the records inside every budget it runs out of that allowance, and -/// that is the stop, kind 2, which takes the value and the records back. Under a transaction KV -/// limit of 2 the started frame's KV share is `floor(2 × 98 / 100)` = 1, the two records cross it, -/// and the stop is kind 1, `limit` 1: the same order as for a precompile the engine prices. +/// A precompile the engine cannot price runs on what the compute limit leaves its frame: a value +/// `CALL` to a node's own precompile, installed through `with_dyn_precompiles`, whose price, +/// 100,000, is past what a read of the block environment under a cap of 30,000 leaves once the +/// caller's own `CALL` is paid, and within the forward. It runs out of that allowance, and that is +/// the stop, kind 2; revm took the value and the transfer log back with the precompile's failure, +/// so the start kept nothing and is held to nothing. Under a transaction KV limit of 2, where the +/// started frame's KV share, `floor(2 × 98 / 100)` = 1, could not hold the two records its value +/// transfer would make, the stop is still kind 2: the same as for a precompile the engine prices. #[test] -fn test_an_unpriced_precompile_records_stop_at_the_kv_share_before_its_allowance() { +fn test_an_unpriced_precompile_out_of_its_allowance_is_held_to_the_allowance_alone() { use alloy_primitives::map::HashMap; use mega_evm::MegaEvm; use revm::bytecode::opcode::{CALL, GAS, PUSH0}; @@ -288,7 +288,7 @@ fn test_an_unpriced_precompile_records_stop_at_the_kv_share_before_its_allowance let (outcome, ran) = run(limits); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(returned_stop(&outcome).kind, 2, "the records fit: the allowance is the stop"); + assert_eq!(returned_stop(&outcome).kind, 2, "the allowance is the stop"); assert!( matches!(ran.as_slice(), [(allowance, false)] if *allowance < 30_000), "it ran once, on the allowance, short of its price: {ran:?}" @@ -299,7 +299,7 @@ fn test_an_unpriced_precompile_records_stop_at_the_kv_share_before_its_allowance let (outcome, _) = run(limits.with_tx_kv_update_limit(2)); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(returned_stop(&outcome), MegaLimitExceeded { kind: 1, limit: 1 }); + assert_eq!(returned_stop(&outcome).kind, 2, "the allowance alone, not the records"); assert_eq!(super::balance_of(&outcome, PRICED), U256::ZERO); assert_eq!(outcome.usage.write_records, 0); assert_eq!(outcome.usage.data_size, super::BODY_BYTES); diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index f237adb5c..3a0fe9c9a 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -1375,9 +1375,9 @@ fn test_a_deposits_new_caller_is_counted_before_its_first_frame() { /// its start moved goes back: a value call to a new account under a budget of nothing is answered /// with the stop, its value not moved, and its caller catches it. A creation's start alike: its /// init code never runs, and its creator keeps the nonce bump revm made before the creation's -/// checkpoint. A call to a precompile whose start adds an account crosses the state growth before -/// gas detention prices it: the records' stop is the answer, though the price crosses the compute -/// limit too. +/// checkpoint. A value call to a precompile that gas detention answers from its price moves +/// nothing: the price is the stop, kind 2, though the account its value transfer would add has no +/// room in the state growth either. #[test] fn test_a_start_over_the_state_growth_is_stopped_before_it_runs() { use revm::bytecode::opcode::TIMESTAMP; @@ -1407,7 +1407,9 @@ fn test_a_start_over_the_state_growth_is_stopped_before_it_runs() { ); let cap = EvmTxRuntimeLimits::no_limits().with_block_env_access_compute_gas_limit(50_000); let both = run_a(precompile.clone(), 1, cap.with_tx_state_growth_limit(0)); - assert_eq!(output(&both), growth_stop(0), "the records first"); + let (kind, _) = mega_evm::decode_mega_limit_exceeded(&output(&both)).expect("a stop"); + assert_eq!(kind, LimitKind::ComputeGas, "the price alone, not the account"); + assert!(both.state.get(&kzg).is_none_or(|account| account.info.is_empty()), "nothing moved"); let priced = run_a(precompile, 1, cap); let (kind, _) = mega_evm::decode_mega_limit_exceeded(&output(&priced)).expect("a stop"); assert_eq!(kind, LimitKind::ComputeGas, "without the state growth, the price"); diff --git a/crates/mega-evm/tests/satin/transfer_logs.rs b/crates/mega-evm/tests/satin/transfer_logs.rs index bd954cf08..54e1f642e 100644 --- a/crates/mega-evm/tests/satin/transfer_logs.rs +++ b/crates/mega-evm/tests/satin/transfer_logs.rs @@ -51,7 +51,9 @@ use revm::{ result::{ExecutionResult, Output}, TxEnv, }, - interpreter::{interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue}, + interpreter::{ + interpreter::EthInterpreter, CallInputs, CallOutcome, CallValue, InstructionResult, + }, Database, Inspector, }; @@ -1164,16 +1166,14 @@ fn test_a_value_call_its_recipient_cannot_hold_keeps_nothing() { } } -/// A value call to a precompile that fails after its gas check — the BN254 pairing given an input -/// of the wrong length — moved its value and journaled its transfer log before the precompile ran, -/// and revm takes both back with the failure. The start is held to the limits as revm made it, on -/// the records and the log it counted before the failure took them back: under a limit one byte -/// short of them the call is answered with the stop rather than the failure, and either way the -/// transaction keeps its body alone. -#[test] -fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { - const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); - let actor = BytecodeBuilder::default() +/// The BN254 pairing precompile. +const EC_PAIRING: Address = address!("0000000000000000000000000000000000000008"); + +/// An actor that sends [`VALUE`] to the BN254 pairing precompile with an input of one byte, the +/// wrong length, which the precompile refuses after its gas check, forwarding all the gas it may, +/// and returns what the call returned. +fn failing_pairing_actor() -> Bytes { + BytecodeBuilder::default() .append_many([PUSH0, PUSH0]) .push_number(1_u8) .append(PUSH0) @@ -1181,35 +1181,99 @@ fn test_a_failed_precompiles_start_is_held_to_the_limits_it_counted_against() { .push_address(EC_PAIRING) .append_many([GAS, CALL, POP]) .return_returndata() - .build(); - let db = || { - MemoryDatabase::default() - .account_balance(ACTOR, U256::from(VALUE)) - .account_code(ACTOR, actor.clone()) - }; + .build() +} + +/// The world [`failing_pairing_actor`] runs in, and the transaction that calls it. +fn failing_pairing_world() -> (MemoryDatabase, MegaTransaction) { + let db = MemoryDatabase::default() + .account_balance(ACTOR, U256::from(VALUE)) + .account_code(ACTOR, failing_pairing_actor()); let tx = OpTx(op_transaction(TxEnv { caller: CALLER, kind: TxKind::Call(ACTOR), gas_limit: value_call_room(), ..Default::default() })); + (db, tx) +} + +/// A value call to a precompile that fails after its gas check — the BN254 pairing given an input +/// of the wrong length — moved its value and journaled its transfer log before the precompile ran, +/// and revm takes both back with the failure, before the start is held to anything. The start kept +/// nothing, so it is held to nothing: under a limit one byte short of what its value transfer would +/// have counted, the call fails as it does without a limit, with the precompile's failure and not +/// with a limit's stop, and either way the transaction keeps its body alone. +#[test] +fn test_a_failed_precompiles_start_kept_nothing_and_is_held_to_nothing() { + let (db, tx) = failing_pairing_world(); let body = transaction_body_bytes(&tx); let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; - let failed = execute_under(db(), tx.clone(), EvmTxRuntimeLimits::no_limits()); - assert!(failed.result.is_success(), "{:?}", failed.result); - assert_eq!(failed.result.output(), Some(&Bytes::new()), "the precompile's failure"); - assert!(failed.result.logs().is_empty(), "the failure took the transfer log back"); - assert_eq!(failed.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); - + let failed = execute_under(db.clone(), tx.clone(), EvmTxRuntimeLimits::no_limits()); let limit = body + start - 1; - let stopped = - execute_under(db(), tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); - let budget = crate::common::share(start - 1); - let stop = MegaLimitExceeded { kind: LimitKind::DataSize.as_u8(), limit: budget }; - assert_eq!(stopped.result.output(), Some(&Bytes::from(stop.abi_encode())), "the stop"); - assert!(stopped.result.logs().is_empty()); - assert_eq!(stopped.usage, LimitUsage { data_size: body, write_records: 0, state_growth: 0 }); + let short = + execute_under(db, tx, EvmTxRuntimeLimits::no_limits().with_tx_data_size_limit(limit)); + for outcome in [&failed, &short] { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::new()), "the precompile's failure"); + assert!(outcome.result.logs().is_empty(), "the failure took the transfer log back"); + assert_eq!( + outcome.usage, + LimitUsage { data_size: body, write_records: 0, state_growth: 0 } + ); + assert_eq!(outcome.limit_exceeded, None, "no limit stopped it"); + assert_eq!(balance(outcome, ACTOR), U256::from(VALUE), "the value came back"); + } + assert_eq!(short.gas, failed.gas, "the same gas on every ledger"); +} + +/// Records how every call to [`EC_PAIRING`] ends. +#[derive(Default)] +struct PairingEnds(Vec); + +impl Inspector, EthInterpreter> for PairingEnds { + fn call_end( + &mut self, + _context: &mut MegaContext, + inputs: &CallInputs, + outcome: &mut CallOutcome, + ) { + if inputs.target_address == EC_PAIRING { + self.0.push(outcome.clone()); + } + } +} + +/// A failed precompile answer at a frame-budget boundary burns what its caller forwarded, as revm +/// burns the forward of any failed precompile: under a frame cap that gives the precompile's frame +/// one byte less than its value transfer would count, the call halts with the precompile's error +/// and no gas left, where a limit's stop would revert and hand the forward back, and the +/// transaction uses the gas it uses without the cap. An inspector sees the call end so, and the +/// inspected run settles as the plain one. +#[test] +fn test_a_failed_precompile_answer_at_a_frame_budget_boundary_burns_its_forward() { + let (db, tx) = failing_pairing_world(); + let start = 2 * WRITE_RECORD_SIZE + TRANSFER_LOG_SIZE; + let capped = EvmTxRuntimeLimits::no_limits().with_frame_data_size_limit(cap_for(1, start - 1)); + + let unlimited = execute_under(db.clone(), tx.clone(), EvmTxRuntimeLimits::no_limits()); + let plain = execute_under(db.clone(), tx.clone(), capped); + let mut evm = MegaEvm::new(context(db).with_tx_runtime_limits(capped)) + .with_inspector(PairingEnds::default()); + let inspected = evm.execute_transaction(tx).expect("the transaction is valid"); + for outcome in [&plain, &inspected] { + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.result.output(), Some(&Bytes::new()), "the precompile's failure"); + assert_eq!(outcome.limit_exceeded, None); + assert_eq!(outcome.gas, unlimited.gas, "the gas of the run without the cap"); + assert_eq!(outcome.usage, unlimited.usage); + } + let ends = &evm.inspector().0; + let [end] = ends.as_slice() else { panic!("one call to the precompile: {ends:?}") }; + assert_eq!(end.result.result, InstructionResult::PrecompileError, "the precompile's error"); + assert_eq!(end.result.gas.remaining(), 0, "the forward is burned"); + assert!(end.result.output.is_empty(), "no stop's revert data"); } /// A `CREATE` from a contract whose nonce cannot be bumped is refused by the opcode itself, which From 9c6d63ea7c142b49754ccd6bfc78432c87e65dc5 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:39:13 +0800 Subject: [PATCH 192/201] refactor(limit): drop the prediction of a frame start's records What a start counts is read off the journal once revm decided it, so the prediction made before revm's decision, its debug check against the journal and the growth predictors go. The records a start's opcode prices stay, without the transfer log, which costs no history. --- crates/mega-evm/src/evm/execution.rs | 193 +++++---------------------- crates/mega-evm/src/limit/mod.rs | 2 - crates/mega-evm/src/limit/record.rs | 136 +++++++++++-------- 3 files changed, 114 insertions(+), 217 deletions(-) diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index aa00a55be..3ccca2cd9 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -60,9 +60,6 @@ use crate::{ MegaEvm, MegaInstructions, PricedPrecompiles, VolatileDataAccess, TX_BODY_OVER_DATA_SIZE_LIMIT, }; -#[cfg(debug_assertions)] -use crate::limit::StartRecords; - /// The regular gas a system call runs on, at most: EIP-8037's system-call budget. The rest of its /// gas limit is its state-gas reservoir ([`MegaHandler`]'s `tx_gas`). pub const SYSTEM_CALL_REGULAR_GAS_LIMIT: u64 = 30_000_000; @@ -637,8 +634,6 @@ impl EvmTr for MegaEvm( } /// What holding a frame's start to the limits needs of it once revm consumed its input: where the -/// start began, what it counts and what a stop answering it carries. +/// start began, the accounts it writes as they stood before it, what its caller paid for it and +/// what a stop answering it carries. struct FrameStart { /// Where the journal stood before revm decided the start: what revm journals for it — a /// creator's nonce bump, the value the start moves and its transfer log, a precompile's @@ -1213,9 +1209,6 @@ struct FrameStart { before: StartBefore, /// The history gas the start's caller paid at its opcode for the records on the frame. charged: u64, - /// The records and transfer log the start makes on its frame, read off the journal before - /// revm decides it. - counted: Counted, /// The gas limit the frame's caller forwarded, before gas detention held a precompile to less. gas_limit: u64, /// The reservoir the frame inherits. @@ -1226,57 +1219,50 @@ struct FrameStart { /// tells once the creation returned what revm's nonce bump made of it. The transaction's own /// creation has none: its sender's account is the transaction body's. creator: Option, - /// The records the start makes, for a debug build to hold what revm then made to. - #[cfg(debug_assertions)] - made: MadeRecords, } impl FrameStart { /// The start of the frame `frame_init` asks for, about to be decided by revm: where the - /// journal stands, the records it makes on its frame as the journal's state stands - /// ([`Accounts::start_records`](crate::limit::Accounts)), and a creation's creator. A - /// creation's creator record is not among the records: it is the creator's, counted from the - /// bump once the creation returned. + /// journal stands, the accounts the start writes on its frame as the transaction holds them + /// ([`Accounts::start_before`]) — a call's caller and target, a creation's created account — + /// and a creation's creator. A creation's creator is not among the accounts: its nonce record + /// is the creator's, counted from the bump once the creation returned. + /// + /// [`Accounts::start_before`]: crate::limit::Accounts fn of( ctx: &mut MegaContext, frame_init: &FrameInit, ) -> Result> { - // A creation's creator and address are loaded before revm decides the start, as revm - // loads them itself, outside the creation's checkpoint, once it decides it: the creator - // first thing, the address once the creator funds the endowment and its nonce bumps. The - // `CREATE` opcode loaded the address already unless EIP-8037 is off, and the creator is - // the frame that runs it, so only an inspector's rewrite, or EIP-8037 off, makes a load - // here that revm would not have made yet; neither changes what revm decides. An address an - // earlier transaction on the same journal left there is not loaded until it is again. let mut creator = None; - if let FrameInput::Create(inputs) = &frame_init.frame_input { - let info = &ctx.journal_mut().load_account(inputs.caller())?.data.info; - let bumps = info.balance >= inputs.value() && info.nonce != u64::MAX; - let created = inputs.created_address(info.nonce); - if bumps && !ctx.accounts().is_loaded(created) { - ctx.journal_mut().load_account(created)?; - } - if frame_init.depth > 0 { - creator = Some(ctx.accounts().creator_before(inputs.caller())); - } - } - let accounts = ctx.accounts(); - let (records, growth, charged, reservoir, shares) = match &frame_init.frame_input { - FrameInput::Call(inputs) => { - let value = inputs.value.transfer().unwrap_or_default(); - ( - accounts.transfer_records(inputs.caller, inputs.target_address, value), - accounts.transfer_growth(inputs.caller, inputs.target_address, value), - inputs.charged_start.history, - inputs.reservoir, - inputs.pool_shares, - ) - } + let (first, second, charged, reservoir, shares) = match &frame_init.frame_input { + FrameInput::Call(inputs) => ( + inputs.caller, + Some(inputs.target_address), + inputs.charged_start.history, + inputs.reservoir, + inputs.pool_shares, + ), FrameInput::Create(inputs) => { - let created = inputs.created_address(account_nonce(ctx, inputs.caller())); + // A creation's creator and address are loaded before revm decides the start, as + // revm loads them itself, outside the creation's checkpoint, once it decides it: + // the creator first thing, the address once the creator funds the endowment and + // its nonce bumps. The `CREATE` opcode loaded the address already unless EIP-8037 + // is off, and the creator is the frame that runs it, so only an inspector's + // rewrite, or EIP-8037 off, makes a load here that revm would not have made yet; + // neither changes what revm decides. An address an earlier transaction on the same + // journal left there is not loaded until it is again. + let info = &ctx.journal_mut().load_account(inputs.caller())?.data.info; + let bumps = info.balance >= inputs.value() && info.nonce != u64::MAX; + let created = inputs.created_address(info.nonce); + if bumps && !ctx.accounts().is_loaded(created) { + ctx.journal_mut().load_account(created)?; + } + if frame_init.depth > 0 { + creator = Some(ctx.accounts().creator_before(inputs.caller())); + } ( - accounts.creation_records(inputs.caller(), Some(created), inputs.value()), - accounts.creation_growth(inputs.caller(), created, inputs.value()), + created, + None, inputs.charged_start().history, inputs.reservoir(), inputs.pool_shares(), @@ -1286,27 +1272,15 @@ impl FrameStart { "a frame input always names a call or a creation, as revm's frame init asserts" ), }; - let before = match &frame_init.frame_input { - FrameInput::Call(inputs) => (inputs.caller, Some(inputs.target_address)), - FrameInput::Create(inputs) => { - (inputs.created_address(account_nonce(ctx, inputs.caller())), None) - } - FrameInput::Empty => unreachable!("matched above"), - }; - #[cfg(debug_assertions)] - let made = MadeRecords::before(ctx, frame_init, records); let mark = mark(ctx.journal_mut()); Ok(Self { - before: ctx.accounts().start_before(before.0, before.1, mark.log_i), + before: ctx.accounts().start_before(first, second, mark.log_i), mark, charged, - counted: records.counted().with_growth(growth, 0), gas_limit: input_gas_limit(&frame_init.frame_input), reservoir, shares, creator, - #[cfg(debug_assertions)] - made, }) } @@ -1322,7 +1296,6 @@ impl FrameStart { ctx: &MegaContext, ) -> (Counted, u64) { let (records, counted) = ctx.accounts().start_made(&self.before); - debug_assert_eq!(counted, self.counted, "the start made what was predicted"); let credit = if ctx.prices_history() { let price = |records| write_record_history_gas(records).unwrap_or(0); self.charged.saturating_sub(price(records.added)).saturating_add(price(records.taken)) @@ -1331,100 +1304,6 @@ impl FrameStart { }; (counted, credit) } - - /// Asserts revm's start made the records counted for it, read off the journal once revm built - /// the frame. - #[cfg(debug_assertions)] - fn assert_made(&self, ctx: &MegaContext) { - self.made.assert_after(ctx); - } -} - -/// The accounts a start makes its records of on its frame and whether the transaction had changed -/// each before it, for a debug build to hold the records the start counted to what revm's start -/// made of them. -#[cfg(debug_assertions)] -#[derive(Debug)] -struct MadeRecords { - /// The records predicted. - records: StartRecords, - /// The accounts, each with whether it was changed before the start. - accounts: MadeOn, -} - -/// The accounts a start makes its records of on its frame. -#[cfg(debug_assertions)] -#[derive(Debug)] -enum MadeOn { - /// A call's sender and recipient. - Call([(Address, bool); 2]), - /// A creation's created account. Its creator's record is the creator's, read off the journal - /// once the creation returned. - Creation((Address, bool)), -} - -#[cfg(debug_assertions)] -impl MadeRecords { - /// The accounts the start `frame_init` asks for writes, read before revm decides it, and the - /// `records` predicted for it. - fn before( - ctx: &MegaContext, - frame_init: &FrameInit, - records: StartRecords, - ) -> Self { - let journal = ctx.accounts(); - let read = |address: Address| (address, journal.is_changed(address)); - let accounts = match &frame_init.frame_input { - FrameInput::Call(inputs) => { - MadeOn::Call([read(inputs.caller), read(inputs.target_address)]) - } - FrameInput::Create(inputs) => { - let nonce = account_nonce(ctx, inputs.caller()); - MadeOn::Creation(read(inputs.created_address(nonce))) - } - FrameInput::Empty => MadeOn::Call([read(Address::ZERO); 2]), - }; - Self { records, accounts } - } - - /// Asserts the frame revm built made the records predicted: a call's two sides changed and - /// returned as its transfer's records say, a creation's created account as its record says. - fn assert_after( - &self, - ctx: &MegaContext, - ) { - use crate::limit::RecordDelta; - let accounts = ctx.accounts(); - let made = |(address, before): (Address, bool)| { - RecordDelta::of_account(before, accounts.is_changed(address)) - }; - match self.accounts { - MadeOn::Call([first, second]) => { - let made = if first.0 == second.0 { - RecordDelta::NONE - } else { - made(first).with(made(second)) - }; - debug_assert_eq!(made, self.records.transfer, "a call's start made its records"); - } - MadeOn::Creation(created) => { - let record = RecordDelta::of_account(false, self.records.created); - debug_assert_eq!( - made(created), - record, - "a creation made its created account's record" - ); - } - } - } -} - -/// The nonce of an account the journal holds; zero for one it does not. -fn account_nonce( - ctx: &MegaContext, - address: Address, -) -> u64 { - ctx.journal_ref().state.get(&address).map_or(0, |account| account.info.nonce) } /// Holds `answer`, the success revm answered the call `start` began with, to `verdict`: a crossing diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 5c95cc98e..5d6e35d13 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -183,8 +183,6 @@ pub(crate) use limit::Counted; #[cfg(any(test, feature = "test-utils"))] pub(crate) use record::is_transfer_log; pub(crate) use record::{Accounts, CreatorBefore, DestroyedParts, HistoryBytes, StartBefore}; -#[cfg(debug_assertions)] -pub(crate) use record::{RecordDelta, StartRecords}; use alloy_primitives::Bytes; use alloy_sol_types::SolError; diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index 50c75539a..bfee3f93d 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -7,11 +7,13 @@ //! original value. A write that changes an unchanged account or slot makes the record, a write that //! returns one to its original takes it back, and a write to one already changed adds nothing. //! -//! The facts are read off revm's journal as it stands where a hook runs: before a frame's start, -//! which is where its records are predicted, and after a completed write, where a `SELFDESTRUCT`'s -//! accounts are rebuilt as they were before it from the balance it moved. A creator's nonce record -//! is read off what revm did: the creator as it stood before revm decided the creation, and as it -//! stands once the creation returned. +//! The facts are read off revm's journal. What a frame's start made is read off what revm did: +//! the accounts it writes on its frame as they stood before revm decided the start, and as they +//! stand once it did ([`StartBefore`]); a creator's nonce record likewise, the creator as it stood +//! before revm decided the creation, and as it stands once the creation returned. The opcode that +//! starts the frame prices the start's records before revm decides it, as the journal's state +//! stands then ([`StartRecords`]), and a completed write is read after it, where a +//! `SELFDESTRUCT`'s accounts are rebuilt as they were before it from the balance it moved. //! //! State growth is counted at the same sites, one unit per new account or new slot, where EIP-8037 //! charges the state gas of one: a slot an `SSTORE` makes non-zero from an original of zero, and @@ -79,8 +81,9 @@ impl RecordDelta { } } -/// The write records a frame's start makes: a call's value transfer's, and a creation's created -/// account and creator nonce; and whether it journals a transfer log. +/// The write records a frame's start makes, as the journal's state stands before revm decides it, +/// which is what its opcode prices their history at: a call's value transfer's, and a creation's +/// created account and creator nonce. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct StartRecords { /// The records a call's value transfer makes and takes back: the accounts it changes from what @@ -93,26 +96,18 @@ pub(crate) struct StartRecords { /// had not changed. The record is the creator's, which the creation's failure leaves with it, /// and is counted on the creator once the creation returned ([`CreatorBefore`]). pub(crate) creator: bool, - /// Whether the start journals an EIP-7708 transfer log: value moves to another account. - pub(crate) transfer_log: bool, } impl StartRecords { - /// No record and no log. + /// No record. pub(crate) const NONE: Self = - Self { transfer: RecordDelta::NONE, created: false, creator: false, transfer_log: false }; + Self { transfer: RecordDelta::NONE, created: false, creator: false }; /// The records the start makes on the started frame, which its failure takes back: a /// transfer's, and the created account. The creator's is not among them. pub(crate) const fn on_frame(self) -> RecordDelta { RecordDelta { added: self.transfer.added + self.created as u64, taken: self.transfer.taken } } - - /// What the start counts on the started frame: its records there, and its transfer log. - pub(crate) const fn counted(self) -> Counted { - let on_frame = self.on_frame(); - Counted::records(on_frame.added, on_frame.taken, self.transfer_log) - } } /// The parts of an account created in the transaction that its first effective `SELFDESTRUCT` @@ -366,9 +361,8 @@ impl<'a> Accounts<'a> { } /// The records a transfer of `value` from `from` to `to` makes and takes back, as the journal's - /// state stands, and whether it journals a transfer log: nothing for a transfer to the same - /// account or of nothing, which revm moves nothing for, and nothing for a value `from` cannot - /// fund, which revm refuses. + /// state stands: nothing for a transfer to the same account or of nothing, which revm moves + /// nothing for, and nothing for a value `from` cannot fund, which revm refuses. pub(crate) fn transfer_records(&self, from: Address, to: Address, value: U256) -> StartRecords { if from == to || value.is_zero() { return StartRecords::NONE; @@ -385,14 +379,14 @@ impl<'a> Accounts<'a> { self.is_changed(to), self.changed_with_balance(to, to_after), )); - StartRecords { transfer, transfer_log: self.transfer_logs, ..StartRecords::NONE } + StartRecords { transfer, ..StartRecords::NONE } } /// The records a creation by `creator` at `created` with an endowment of `value` makes, before /// revm bumps the creator's nonce: the creator's nonce, when the bump changes an account the - /// transaction had not changed; the account it creates, when the transaction had not changed - /// it; and a transfer log for an endowment. Nothing for an endowment `creator` cannot fund, - /// which revm refuses before it bumps the nonce, nor for a creation that takes no address. + /// transaction had not changed; and the account it creates, when the transaction had not + /// changed it. Nothing for an endowment `creator` cannot fund, which revm refuses before it + /// bumps the nonce, nor for a creation that takes no address. pub(crate) fn creation_records( &self, creator: Address, @@ -407,7 +401,6 @@ impl<'a> Accounts<'a> { transfer: RecordDelta::NONE, created: !self.is_changed(created), creator: !self.is_changed(creator), - transfer_log: self.transfer_logs && !value.is_zero(), } } @@ -476,24 +469,6 @@ impl<'a> Accounts<'a> { (records, Counted::records(records.added, records.taken, logged).with_growth(growth, 0)) } - /// The account of state growth a transfer of `value` from `from` to `to` makes, as the - /// journal's state stands: one when it moves value `from` can fund to another account that is - /// empty, which the transfer creates. A `CALLCODE`'s transfer is from the calling account to - /// itself, and a `DELEGATECALL` or `STATICCALL` carries none: none of them creates an account. - pub(crate) fn transfer_growth(&self, from: Address, to: Address, value: U256) -> u64 { - let creates = - from != to && !value.is_zero() && self.balance(from) >= value && self.is_empty(to); - u64::from(creates) - } - - /// The account of state growth a creation by `creator` at `created` with an endowment of - /// `value` makes on its frame, as the journal's state stands: one when the creator can fund - /// the endowment and the address is empty, which the creation creates. An address that holds - /// a balance, a nonce or code is no new account, and a collision adds none. - pub(crate) fn creation_growth(&self, creator: Address, created: Address, value: U256) -> u64 { - u64::from(self.balance(creator) >= value && self.is_empty(created)) - } - /// The records a frame start of `kind` by `caller` makes: a call's value transfer to `target` /// ([`transfer_records`](Self::transfer_records)); a creation's at `target`, the address it /// takes ([`creation_records`](Self::creation_records)). The transfer of a `CALLCODE` is from @@ -964,18 +939,17 @@ mod tests { ); } - /// A transfer's records follow the net change of both sides, on the balances the transfer - /// leaves them; a transfer to the same account, of nothing, or of more than the sender holds - /// records nothing and journals no log. A creation records its created account and its - /// creator's nonce only where the transaction had not changed them, keeps the creator's off - /// the created frame, and journals a log for an endowment. + /// The records a start's opcode prices follow the net change of both sides of a transfer, on + /// the balances the transfer leaves them; a transfer to the same account, of nothing, or of + /// more than the sender holds records nothing. A creation records its created account and its + /// creator's nonce only where the transaction had not changed them, and keeps the creator's off + /// the created frame. #[test] - fn test_a_starts_records_follow_the_net_change() { + fn test_a_starts_priced_records_follow_the_net_change() { let mut journal = journal(); let accounts = Accounts::of(&journal, true); let both = accounts.transfer_records(OTHER, DESTRUCTED, U256::from(1)); assert_eq!(both.transfer, RecordDelta { added: 2, taken: 0 }); - assert!(both.transfer_log); assert_eq!(accounts.transfer_records(OTHER, OTHER, U256::from(1)), StartRecords::NONE); assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::ZERO), StartRecords::NONE); assert_eq!(accounts.transfer_records(OTHER, DESTRUCTED, U256::from(5)), StartRecords::NONE); @@ -984,23 +958,17 @@ mod tests { journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); let back = Accounts::of(&journal, true).transfer_records(DESTRUCTED, OTHER, U256::from(1)); assert_eq!(back.transfer, RecordDelta { added: 0, taken: 2 }); - assert_eq!(back.counted(), Counted::records(0, 2, true)); let created = address!("00000000000000000000000000000000000c4ea7"); let accounts = Accounts::of(&journal, true); let creation = accounts.creation_records(SENDER, Some(created), U256::from(1)); assert_eq!( creation, - StartRecords { - transfer: RecordDelta::NONE, - created: true, - creator: true, - transfer_log: true - } + StartRecords { transfer: RecordDelta::NONE, created: true, creator: true } ); assert_eq!(creation.on_frame(), RecordDelta { added: 1, taken: 0 }); let onto_changed = accounts.creation_records(OTHER, Some(DESTRUCTED), U256::ZERO); - assert!(!onto_changed.created && !onto_changed.creator && !onto_changed.transfer_log); + assert!(!onto_changed.created && !onto_changed.creator); assert_eq!(accounts.creation_records(SENDER, None, U256::ZERO), StartRecords::NONE); assert_eq!( accounts.creation_records(SENDER, Some(created), U256::from(11)), @@ -1009,6 +977,58 @@ mod tests { ); } + /// What a start made is read off what revm did, against its accounts as they stood before it: + /// a transfer to an empty account makes both sides' records, one account of state growth and + /// the transfer log revm journaled since; sending the value back takes both records back and + /// grows nothing, the recipient no longer being empty; a start that moved nothing, or whose + /// move revm took back, made nothing; a log another account emitted is no transfer log; and an + /// account named twice is counted once. + #[test] + fn test_a_starts_records_are_read_off_what_revm_did() { + let empty = address!("00000000000000000000000000000000000e3e70"); + let mut journal = journal(); + journal.set_amsterdam_eip7708_enabled(true); + journal.load_account(empty).unwrap(); + let before = |journal: &Journal, first, second| { + Accounts::of(journal, true).start_before(first, Some(second), journal.logs.len()) + }; + let made = |journal: &Journal, before| { + Accounts::of(journal, true).start_made(&before) + }; + + let funding = before(&journal, OTHER, empty); + assert_eq!(made(&journal, funding), (RecordDelta::NONE, Counted::NONE), "nothing moved"); + journal.transfer(OTHER, empty, U256::from(1)).unwrap(); + assert_eq!( + made(&journal, funding), + (RecordDelta { added: 2, taken: 0 }, Counted::records(2, 0, true).with_growth(1, 0)) + ); + + let back = before(&journal, empty, OTHER); + journal.transfer(empty, OTHER, U256::from(1)).unwrap(); + assert_eq!( + made(&journal, back), + (RecordDelta { added: 0, taken: 2 }, Counted::records(0, 2, true)) + ); + + let taken_back = before(&journal, OTHER, DESTRUCTED); + let checkpoint = journal.checkpoint(); + journal.transfer(OTHER, DESTRUCTED, U256::from(1)).unwrap(); + journal.checkpoint_revert(checkpoint); + assert_eq!(made(&journal, taken_back), (RecordDelta::NONE, Counted::NONE), "taken back"); + + let logged = before(&journal, OTHER, DESTRUCTED); + journal.log(Log::new_unchecked(OTHER, vec![], Bytes::new())); + assert_eq!(made(&journal, logged), (RecordDelta::NONE, Counted::NONE), "a contract's log"); + + let itself = before(&journal, SENDER, SENDER); + journal.load_account_mut(SENDER).unwrap().data.bump_nonce(); + assert_eq!( + made(&journal, itself), + (RecordDelta { added: 1, taken: 0 }, Counted::records(1, 0, false)) + ); + } + /// A creator's record is read off what revm did: nothing while its nonce is where it was /// before the creation; once revm bumped it, a record when the bump changed an account the /// transaction had not changed, and one account of state growth when it made an empty one. A From 5e6babe50f1fc912623a8bc36d9f0e9182d5d55f Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 10:48:46 +0800 Subject: [PATCH 193/201] docs(satin): state that a start is held to what the journal kept A start's records are counted from what revm did to its accounts. An answer that failed kept nothing and is held to nothing, its result the precompile's failure; a precompile answered from its price before its value moves is held to the price alone, the compute stop. --- .claude/skills/satin-review/SKILL.md | 32 +++++++++++++++------------- AGENTS.md | 21 +++++++++--------- REVIEW.md | 3 ++- crates/mega-evm/src/limit/limit.rs | 9 ++++---- crates/mega-evm/src/limit/mod.rs | 25 +++++++++++++--------- docs/spec/upgrades/satin.md | 18 ++++++++-------- 6 files changed, 59 insertions(+), 49 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 5f6088b08..a3abfc66b 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -81,11 +81,13 @@ Each change is stated here in plain words with its reason; the specification has An account's record exists while its nonce, balance or code differs from what the transaction loaded, and a slot's while its value differs from its original. The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes. Why: the record measures the state the transaction keeps, by revm's own notion of a change; the per-frame count over-counted, and charged history gas for writes that leave nothing. -- **A frame start is held to the limits once revm decided it.** - Its records and transfer log are read off the journal before revm decides the start, and counted on the started frame's pools once it has. - A frame revm built returns the stop before its first instruction, and an answer revm gave without building a frame gives way to the stop on the untouched forward, a success's value move taken back. +- **A frame start is held to the limits once revm decided it, on what it kept.** + Its accounts on the frame are read before revm decides the start and again once it did, and what changed between — each account's record, an account that was empty and is not, the transfer log revm journaled — is counted on the started frame's pools; nothing is predicted. + A frame revm built returns the stop before its first instruction, and a success revm gave without building a frame gives way to the stop on the untouched forward, its value move taken back. + An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: a value call to a precompile that fails at a budget boundary ends as the precompile's failure, which burns its forward, not as a limit's stop. + A precompile gas detention answers from its price before revm runs it moved nothing and is held to the price alone: its stop is kind 2, whatever records its value transfer would have made. A creation onto an occupied address fails on the collision, and is not stopped for what its start would count. - Why: the limit judges what the start did, instead of a prediction of revm's refusals that duplicated revm's rules in the engine; the opcode's history charge is still priced from the journal's state before revm decides, which on the plain path is exact because the opcode makes revm's refusal checks first. + Why: the limit judges what the journal kept, by the same rule at every start, instead of a prediction of revm's start held to the journal only in debug builds and checked hypothetically for the two answers that leave nothing to read; the opcode's history charge is still priced from the journal's state before revm decides, which on the plain path is exact because the opcode makes revm's refusal checks first, and the start's credit settles a price that differs from what revm made. - **A creator's nonce record is counted on the creator when the creation returns with the nonce bumped.** The creation's budget is the share taken at the opcode, before that record, which is Rex6's order. The record is held to the creator's budget, not the creation's, and survives the creation's failure; a keyless signer's is counted on the call at its settlement, and the keyless creation's share is of the call's whole pools, which the call draws nothing from before it. @@ -220,7 +222,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - **Check:** - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas. - The transaction's limits are held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints, the authorities' records and the accounts they created, a deposit's created caller, and what the frames keep, restored when a start's frame keeps nothing (`AdditionalLimit::close_start`). - - A completed write and a decided start are held in one function (`AdditionalLimit::check`, through `draw`, `count_start` and `hypothetical_start`): in the order data size, KV updates, state growth (`limit::COUNTED`), the frame budget, then the transaction limit; a hint, the authorization list and a caller's hold at a child's return check the same limits directly. + - A completed write and a decided start are held in one function (`AdditionalLimit::check`, through `draw` and `count_start`): in the order data size, KV updates, state growth (`limit::COUNTED`), the frame budget, then the transaction limit; a hint, the authorization list and a caller's hold at a child's return check the same limits directly. - The stop names the budget when the budget is crossed, and the transaction limit only when it is not, which a framed write reaches only in data size, after Oracle hints used what the transaction had left; a start names it too when a deposit-like transaction's created caller stands on a state-growth limit of nothing, which only a tool's limit sets. - Every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work and system calls. - A write record follows the net change: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original; the sender's account and the fee credits the settlement makes are the body's, not records. @@ -244,7 +246,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - - A start's records and transfer log are read off the journal before revm decides the start (the engine's `FrameStart::of` in `src/evm/execution.rs`) and counted on the started frame's pools once it has (`AdditionalLimit::count_start`); a start revm refuses on its caller's account counts nothing and is charged nothing. + - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::made` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed, and a precompile gas detention answers from its price, count nothing and are held to nothing but the price; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); an answer revm gave gives way to the stop on its untouched forward, and a success's value move and log are taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`). - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. @@ -397,15 +399,15 @@ Inside a dimension the frame budget is tested before the transaction limit, and The deliberate exceptions: -| What happens | Why | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | -| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. | -| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | -| A call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward; a precompile priced past detention's allowance whose start's records also cross is that records' stop, not the compute stop. | A limit is enforced at the writes it guards, and a start writes before its callee runs, so revm's answer, whatever it was, gives way to the stop, and the value has moved before the price is consulted, so the records are decided first. | -| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | -| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | -| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. | +| What happens | Why | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | +| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. | +| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | +| A call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward when revm built its frame or answered it with a success; a call revm answered with a failure — a precompile that fails after the value moved — kept nothing and halts as revm has it, burning its forward, and a precompile gas detention answers from its price is the compute stop, whatever its records would have crossed. | A limit is enforced at the writes it guards, which are what the journal kept: a success kept the start's writes, so it gives way to the stop; a failure's writes revm took back, and a precompile answered from its price moved nothing, so neither has a write to hold. | +| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | +| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | +| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. | Not exceptions, but easy to mistake for one: diff --git a/AGENTS.md b/AGENTS.md index 6f106e02d..4a2b2f175 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,7 +138,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat | `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) | | `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) | | `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) | -| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the exemption, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | +| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a start's read off what revm did against its accounts as they stood before revm decided it (`StartBefore`), a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the exemption, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) | | `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) | | `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) | | `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off | @@ -193,13 +193,14 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat A `CALLCODE`, a call to itself and a transaction's value to its own sender move nothing to another account and log nothing; a deposit's value is logged and its mint is not; a destruction to itself burns the balance of an account created in the transaction without a log, because the base spec predates EIP-8246 and this revm emits no `Burn` log. A transfer log is data size like any log, counted by the rule a `LOG3` of one word is — 160 bytes, `TRANSFER_LOG_SIZE` — and nothing else: it is no write record and pays no history gas, because Ethereum prices it at nothing and it is not a byte the transaction chose to write. It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. - A frame start's records and log are read off the journal before revm decides the start, as the hook that charged its caller read them, and drawn on the pool the frame starts with once revm decided it, in `MegaEvm::frame_init` (`AdditionalLimit::count_start`), with a journal mark at every start: a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; an answer revm gave without building the frame — a call to an account with no code, to a precompile, failed or not — gives way to the stop on its untouched gas, and a success's committed move and log are taken back to the mark (`take_back_a_stopped_answer`). - A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which predicts a start's records from the journal's state and sees the caller cannot fund the value. - A creation it would answer before bumping its creator's nonce — an endowment the creator cannot fund, a creator whose nonce is at its maximum — is refused by the `CREATE` and `CREATE2` opcodes themselves, before the start's hook under EIP-8037, and otherwise reaches the hook without a created address, for which it predicts no record, so a plain run charges and counts nothing for it; only an inspector that rewrites the creation's input after the hook reaches revm's refusal, which bumps nothing and so counts nothing: the declared part of what the opcode charged comes back with the refused start, and the history of the creator's record, which is not declared, stays charged. + A frame start's records and log are read off what revm did, in `MegaEvm::frame_init`: the start's accounts on its frame — a call's caller and target, a creation's created account — are read before revm decides the start, with a journal mark (`Accounts::start_before`), and again once it did, each account's record by its change since, one account of state growth for each that was empty and is not, and the transfer log revm journaled since the mark (`Accounts::start_made`), drawn on the pool the frame starts with (`AdditionalLimit::count_start`): a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; a success revm gave without building the frame — a call to an account with no code, to a precompile that answers — gives way to the stop on its untouched gas, and its committed move and log are taken back to the mark (`take_back_a_stopped_answer`). + An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: its result is revm's, so a value call to a precompile that fails burns its forward as any failed precompile does, whatever its value transfer would have counted. + A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which prices a start's records from the journal's state and sees the caller cannot fund the value. + A creation it would answer before bumping its creator's nonce — an endowment the creator cannot fund, a creator whose nonce is at its maximum — is refused by the `CREATE` and `CREATE2` opcodes themselves, before the start's hook under EIP-8037, and otherwise reaches the hook without a created address, for which it prices no record, so a plain run charges and counts nothing for it; only an inspector that rewrites the creation's input after the hook reaches revm's refusal, which bumps nothing and so counts nothing: the declared part of what the opcode charged comes back with the refused start, and the history of the creator's record, which is not declared, stays charged. A creation onto an occupied address, which revm fails after the nonce bump, is held to nothing at its start: it fails on the collision, its records and log go with the failure, and the nonce record is counted on the creator once the creation returned, held to the creator's limits. - The one decision taken before revm's is gas detention's answer to a precompile whose price crosses the compute limit, given without running it (`hold_precompile`): it is not given to a value call whose caller cannot fund the value, which revm refuses first. + The one decision taken before revm's is gas detention's answer to a precompile whose price crosses the compute limit, given without running it (`hold_precompile`): it moves nothing, so it is held to the price alone, the compute stop, whatever the records its value transfer would have made; it is not given to a value call whose caller cannot fund the value, which revm refuses first. A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted. - A start's log is predicted from the journal's state, as revm's transfer decides it (another account, a value the caller can fund); `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. + A start's log is the one revm journaled for it; `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log. - The data-size limit holds a transaction to `EvmTxRuntimeLimits::tx_data_size_limit` and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left, under an optional frame cap. A frame's budget is a pool on its gas tracker (`limit::DATA_SIZE_POOL`; the KV-update and state-growth budgets are the other two pools): the transaction's tracker starts with what the body and the counts made before the frame leave (`AdditionalLimit::first_frame_pools`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::pool_kept_percent` = 2, so a child gets 98%), capped where the caller suspends (`cap_the_shares`: the frame cap, and a frame's remaining clamped to its budget, so a negative net never enlarges a child's share), and settles a returning child's pool as it settles the reservoir; the transaction's limit is held beside the pools on what the transaction keeps (`AdditionalLimit::usage`). In each counted dimension the frame budget is tested before the transaction limit: a crossing of both names the budget, and the transaction limit is named only when the budget is not crossed — after Oracle hints used what the transaction had left, or when a deposit-like transaction's created caller stands on a state-growth limit of nothing; the budgets of the frames on the stack add up to what the transaction has left, so otherwise a frame that crosses the transaction limit crosses its own budget too. @@ -217,7 +218,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat At the spec's numbers 500,000 records weigh 20,000,000 bytes, more than `TX_DATA_LIMIT`, so the data size binds first; the KV check is still made. An EIP-7702 list that would keep more records than the limit allows is skipped whole (`hold_authorization_list` in `evm/execution.rs`, see the authorization list below). - The state-growth limit holds the net count of new accounts and new slots a transaction keeps to `EvmTxRuntimeLimits::tx_state_growth_limit` (`TX_STATE_GROWTH_LIMIT`, 1,000) and every frame to 98% of what its parent has left, on the state-growth pool (`limit::STATE_GROWTH_POOL`); a crossing reverts the frame with `MegaLimitExceeded(3, limit)` (`tests/satin/state_growth.rs`), and the count is reported, in the outcome's usage (`LimitUsage::state_growth`, `max(net, 0)`) and the block's. - One unit rises where EIP-8037 charges the state gas of one, counted where the record of the same write is (`limit/record.rs`): an `SSTORE` from an original and present zero to non-zero, and falls on the write from an original zero back to zero; a value transfer that moves value its caller can fund to another account empty under EIP-161 (a value `CALL`, the transaction's own value), a creation at an empty address (the transaction's own included), both counted on the started frame and read off the journal before revm decides the start (`Accounts::transfer_growth`, `creation_growth`, in `FrameStart::of`, which loads a creation's address first where EIP-8037 is off and the opcode did not); a `SELFDESTRUCT` moving a balance to another account that does not exist; a creator's nonce bump that creates the creator, a keyless deployment's signer, counted with the creator's record on the creating frame once the creation returned (`Accounts::creator_counted`); and, before the first frame and on the transaction, each authority an applied authorization list created and the caller a deposit-like transaction created, which no failure takes back (`AdditionalLimit::count_authorities`, `count_created_caller`). + One unit rises where EIP-8037 charges the state gas of one, counted where the record of the same write is (`limit/record.rs`): an `SSTORE` from an original and present zero to non-zero, and falls on the write from an original zero back to zero; a value transfer that moves value its caller can fund to another account empty under EIP-161 (a value `CALL`, the transaction's own value), a creation at an empty address (the transaction's own included), both counted on the started frame and read off what revm did: an account the start found empty and left not empty (`Accounts::start_made`; `FrameStart::of` loads a creation's address first where EIP-8037 is off and the opcode did not); a `SELFDESTRUCT` moving a balance to another account that does not exist; a creator's nonce bump that creates the creator, a keyless deployment's signer, counted with the creator's record on the creating frame once the creation returned (`Accounts::creator_counted`); and, before the first frame and on the transaction, each authority an applied authorization list created and the caller a deposit-like transaction created, which no failure takes back (`AdditionalLimit::count_authorities`, `count_created_caller`). A fee credit, a `CALLCODE`, a value call to the calling account, deployed code and a delegation indicator are no rise; a failed frame's net goes with it. An applied EIP-7702 authority counts as created where revm charged it as a new account — empty, loaded as not existing and untouched when the application reached it — read after the application as loaded as not existing, empty at the transaction's start and touched first by the application (`applied_authorities` in `evm/execution.rs`), so on a journal that runs several transactions unfinalized the count follows revm's charge, the flag of an earlier transaction's touch included (see the destruction table below). EIP-8037 still charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in; the count is what stops the 1,001st slot, which the gas a transaction can pay would not. @@ -433,7 +434,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A keyless deployment's creation takes the same share of what the call has left after the call's start charges (`keyless::start`, through `forward_to_child`). The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole. A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame. - The records are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode and again where revm decides the start, a creation's at the address it takes (`FrameStart::target`), and counted on the started frame's pool once revm decided it; a debug build holds those to what revm's start made of the accounts, exactly for every record. + The records the hook prices are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode, a creation's at the address it takes (`FrameStart::target`); the records counted on the started frame's pool are those revm's start made, read off the journal once revm decided it, and a price that differs from them is settled by the start's credit. A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, and its declared part comes back only as it does for any start whose frame keeps nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value; its records are those revm then made. - **The instruction table.** The opcodes that can read volatile data run in detention's read wrapper (see Gas detention). @@ -450,7 +451,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. - Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. + Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. - **A start's charge rides on revm's carriers.** The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. The history allowance a value call gives its child is the fork's tracker field, set from the schedule's `call_history_allowance`; only a log draws on it. @@ -464,7 +465,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender; the history charged before execution for that frame's write record comes back with its start charge at the settlement, whenever the frame did not keep the record. Nothing is rescued for the sender on a stop, because nothing was taken from it: the stop settles on the gas the frames hold, and detention withholds inside a frame's own tracker. A stop of the transaction's own frame reverts what the frames did, the first frame's value and write record included, and nothing pre-execution applied: an admitted EIP-7702 authority keeps its nonce, its delegation, its state gas, its record and that record's history, and a deposit keeps its mint and the caller account it created, as through any failed first frame (`tests/satin/state_growth.rs`). - A limit is enforced on the writes it guards before anything runs on them: a frame whose start crosses it returns the stop before its first instruction, or its answer gives way to the stop, and what the start moved goes back with it (a creation keeps its creator's nonce bump, which revm makes before the frame's checkpoint, so a stopped creation transaction cannot be replayed). + A limit is enforced on the writes it guards before anything runs on them: a frame whose start crosses it returns the stop before its first instruction, or its success answer gives way to the stop, and what the start moved goes back with it (a creation keeps its creator's nonce bump, which revm makes before the frame's checkpoint, so a stopped creation transaction cannot be replayed); an answer that failed kept nothing and is held to nothing. Nothing counted before the first frame crosses the data-size limit: validation (`MegaHandler::validate_initial_tx_gas`, before any gas check) refuses a transaction whose body, with a 40-byte record for each entry of its authorization list, exceeds it (`AdditionalLimit::admits_tx_body`, `TX_BODY_OVER_DATA_SIZE_LIMIT`, an `InvalidTransaction::Str`), the system-originated exempt; a deposit refused so is a failed deposit, and a pool refuses it through `validate_transaction_stateless` alike. The body is a pure count, and `AdditionalLimit::count_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`). A frame revm answers with a success and the engine then rewrites to the stop — gas detention's crossing — has its journal taken back to where its start began, at any depth, as revm takes back a frame that fails (`take_back_a_stopped_answer`): its caller resumes and keeps its own writes, and no caller's revert follows to take the answer's back. diff --git a/REVIEW.md b/REVIEW.md index d04b1ce12..1fbd4ab13 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -27,7 +27,8 @@ Defer to the baseline for everything not listed here; the rules below take prece - **A write is counted once its opcode completed.** The Host's `sstore`, `log` and `selfdestruct` only write and count nothing; revm's write instructions call the completed-write hook (`Host::write_completed`) after every charge they make, and the frame-starting instructions call the frame-start hook (`Host::frame_starting`) after the forward and before the frame's input is built. A record, a charge or a read mark made before the opcode can still fail counts a write that never happened. - The frame-start hook only prices: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and none is given back. + The frame-start hook only prices: a start's records are counted once revm decided it, from what revm did to the start's accounts (`Accounts::start_made`), and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision, none is predicted and none is given back. + An answer that failed kept nothing and is held to nothing, and a precompile gas detention answers from its price moved nothing and is held to the price alone: flag a stop given to either. Check that nothing is counted in the Host's write methods, that no charge lands in a write instruction after the hook (the fork's call sites), and that the engine's matches over `CompletedWrite` and `FrameStartKind` carry no wildcard arm. - **A limit is enforced before the write it guards.** A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit, unless the failure put back a record a frame above made while an Oracle hint the failed frame sent stays, when the caller returns the transaction's stop as it resumes; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop. diff --git a/crates/mega-evm/src/limit/limit.rs b/crates/mega-evm/src/limit/limit.rs index 7e39fd305..e1ebff2a6 100644 --- a/crates/mega-evm/src/limit/limit.rs +++ b/crates/mega-evm/src/limit/limit.rs @@ -643,11 +643,12 @@ impl AdditionalLimit { self.decided.push(Decided { depth, at_start: self.kept, credit: 0, creator }); } - /// Holds the start revm just decided, whose frame's pools `gas` holds, to the limits, and - /// counts `counted`, the records and transfer log it made, on those pools + /// Holds the start revm just decided — a frame it built, or a call it answered with a success — + /// whose frame's pools `gas` holds, to the limits, and counts `counted`, the records, state + /// growth and transfer log it made, read off the journal, on those pools /// ([`draw`](Self::draw)): the verdict is the stop the frame returns before it runs, or the - /// one its answer gives way to. `credit` is what the start's caller gets back once the frame - /// returned with its start kept. + /// one its answer gives way to. An answer that failed kept nothing and is not held. `credit` is + /// what the start's caller gets back once the frame returned with its start kept. /// /// A start is held to the transaction's limits whatever it counts, nothing included: what the /// transaction keeps may already stand above a limit, as a frame that resumes may find it diff --git a/crates/mega-evm/src/limit/mod.rs b/crates/mega-evm/src/limit/mod.rs index 5d6e35d13..f30e5c408 100644 --- a/crates/mega-evm/src/limit/mod.rs +++ b/crates/mega-evm/src/limit/mod.rs @@ -60,16 +60,21 @@ //! pool of the frame whose journal checkpoint holds the move, so the failure that takes the move //! back takes the bytes back. //! -//! A frame start's records are read off the journal before revm decides the start, as the hook -//! that charges its caller for them reads them, and counted and held to the limits once revm -//! decided it, on the pool its frame starts with; a debug build holds them to what revm's start -//! made of the accounts. A frame revm builds returns the stop on its first run when its start -//! crossed a limit, and its revert takes back the value revm moved and the transfer log it -//! journaled; an answer revm gives without building a frame — a call to an account with no code, to -//! a precompile — gives way to the stop, and what its start moved is taken back with it. A start -//! revm refuses on its caller's account — a value its caller cannot fund, a creation whose -//! creator's nonce cannot be bumped — moves and writes nothing, so it counts nothing and no limit -//! stops it; its opcode, which reads the caller's account first, charged nothing for its records. +//! A frame start's records are counted from what revm did, not predicted: the accounts the start +//! writes on its frame are read before revm decides the start and again once it did, and what +//! changed between, with the transfer log revm journaled, is counted and held to the limits on the +//! pool its frame starts with. The hook that charges the caller for the records prices them from +//! the journal's state at the opcode, and the start's credit settles a price that differs from +//! what revm made. A frame revm builds returns the stop on its first run when its start crossed a +//! limit, and its revert takes back the value revm moved and the transfer log it journaled; a +//! success revm answers without building a frame — a call to an account with no code, to a +//! precompile that answers — gives way to the stop, and what its start moved is taken back with +//! it. An answer that failed kept nothing, revm having taken back what its start moved, so it is +//! held to nothing and its result is revm's; a precompile gas detention answers from its price +//! before revm runs it moved nothing and is held to the price alone. A start revm refuses on its +//! caller's account — a value its caller cannot fund, a creation whose creator's nonce cannot be +//! bumped — moves and writes nothing, so it counts nothing and no limit stops it; its opcode, +//! which reads the caller's account first, charged nothing for its records. //! A start an inspector rewrote after its opcode is not charged again: what the opcode charged //! stands, and its declared part comes back only as it does for any start whose frame keeps //! nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value. diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index c58567a6c..458a465d9 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -736,12 +736,9 @@ A deposit that runs to a success or a revert and creates its caller is the ordin The order is Rex6's order across dimensions. Compute (kind 2) is decided at the regular charge, before the write is counted. A regular charge that crosses gas detention means the opcode does not complete, so the operation's data size, KV updates and state growth are not counted, and kind 2 is the stop because the write did not happen. - A call to a precompile is the exception: the value has already moved when the price is consulted, so the start's records are decided before the price. - Those records MUST be held to these limits first, in the order of this section. - The price is kind 2 only when the start kept within them. + A call to a precompile whose price crosses gas detention is decided from the price before its value moves: it moves nothing and counts nothing, so it MUST be held to the price alone, and the stop is kind 2 whatever records its value transfer would have made. A value the caller cannot fund runs no precompile, counts nothing and is stopped by no limit. - The same order applies when a precompile the node cannot price runs out of the allowance: the start's records are held first, and running out of the allowance is kind 2 only when the start kept within them. - The exception begins at the price: the call's own regular charges — its static 100, its memory, the 11,300 value transfer and a cold access — MUST be decided first, as any opcode's, and one that crosses MUST stop the calling frame before anything moves, whether or not the caller can fund the value. + The call's own regular charges — its static 100, its memory, the 11,300 value transfer and a cold access — MUST be decided before the price, as any opcode's, and one that crosses MUST stop the calling frame before anything moves, whether or not the caller can fund the value. Inside data size, KV updates and state growth, the frame budget MUST be tested before the transaction limit. When the frame budget is crossed, the stop MUST name that budget, and `limit` is that budget, including when the transaction limit of the same dimension is crossed too. When the frame budget is not crossed, a crossing of the transaction limit MUST name that limit, and `limit` is the transaction limit. @@ -753,6 +750,8 @@ A deposit that runs to a success or a revert and creates its caller is the ordin The body is refused at validation, so it does not cross at runtime. Gas detention remains kind 2 (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)). - **A frame start** is held to the limits once it is decided: once the value moved and, for a creation, the creator's nonce was bumped and the created account made. + It MUST be held to what the start kept: the records, the state growth and the transfer log of the accounts it changed. + A call answered with a failure — a precompile that fails after its value moved — kept nothing, its failure taking back the value and the transfer log, so it MUST count nothing and MUST NOT be stopped by a limit; its result is the precompile's failure, which consumes the gas forwarded to it. A start the caller's account refuses — a value the caller cannot fund, a creation whose creator nonce cannot be bumped — MUST count nothing, be stopped by no limit, and be charged nothing at its opcode (see [History Gas](#7-history-gas)). A creation onto an occupied address fails on the collision after its creator's nonce was bumped, and MUST NOT be stopped for what its start would count: its failure discards the created account's record and its transfer log, and the creator's nonce record, which survives it, MUST be counted on the creator when the creation returns, the creator held to its limits with it. The created account was not new, so the collision adds no state growth. @@ -874,8 +873,9 @@ A hint that would itself cross the data-size limit is neither forwarded nor coun A limit is enforced on the writes it guards before anything runs on them: - A frame whose start crosses a limit MUST be stopped before it runs an instruction, and what its start moved MUST be reverted with it: the value, the transfer log, a created account. - A frame answered without running — a call to an account with no code, a precompile, whatever it answered — MUST have its answer replaced by the stop, on the gas its caller forwarded, untouched. - When that answer is a precompile whose price crosses gas detention and whose start's records also cross a data-size, KV or state-growth budget, the records' stop is the result, as [Resource Limits](#10-resource-limits) orders the two. + A frame answered with a success without running — a call to an account with no code, a precompile that answers — MUST have its answer replaced by the stop, on the gas its caller forwarded, untouched. + A frame answered with a failure kept nothing and MUST NOT have its answer replaced by a stop: a precompile that fails consumes the gas forwarded to it, as without a limit. + A precompile whose price crosses gas detention moves nothing and is held to the price alone: its result is the compute stop, whatever records its value transfer would have made (see [Resource Limits](#10-resource-limits)). A stopped creation keeps its creator's nonce bump, and that write's record MUST be counted on the creator when the creation returns: the creator MUST be held to its limits with it before it runs on, and be stopped if it crosses one. - A frame answered without running whose answer is then rewritten to the stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST have what its start moved reverted with it, as a frame that fails has. - Nothing counted before the first frame crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). @@ -947,7 +947,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th - **Precompiles.** The call's own regular charges come first, as any opcode's: one that crosses MUST stop the calling frame before the price is consulted (see Order at one site in [Resource Limits](#10-resource-limits)). A call to a precompile forwarded more regular gas than the frame's allowance MUST be decided from the precompile's price before it runs: priced within the allowance, it runs on its whole forward; priced past the allowance but within the forward, it MUST NOT run and is the crossing; priced past its whole forward, it runs on the forward and fails, as without the read. - When the value has already moved, the start's records are held to the data-size, KV and state-growth limits before that crossing is the stop, and the price is kind 2 only when the start kept within them (see [Resource Limits](#10-resource-limits)). + The value has not moved when the price is consulted, so the call MUST be held to the price alone: the crossing is the stop, kind 2, whatever records its value transfer would have made (see [Resource Limits](#10-resource-limits)). Every precompile of the Satin set has a price; an input over a size limit is priced at zero, since it is refused before any gas check. An input priced between the allowance and the forward that would fail a check the precompile makes after its gas check is the crossing too. A call refused on its caller's account runs no precompile and is answered as without the read. @@ -961,7 +961,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th {% hint style="info" %} A precompile a node adds or replaces is outside the Satin set and outside this specification. -The reference implementation has no price for one, so it runs such a precompile on the allowance and treats running out of it as the crossing. +The reference implementation has no price for one, so it runs such a precompile on the allowance and treats running out of it as the crossing: the failure has taken back the value and the transfer log, so the call is held to the allowance alone, and the stop is kind 2. {% endhint %} ### 13. Volatile-Data Access Control and `remainingComputeGas()` From 0da28a8f10ba6f2b65d9110ddf1004b14b0fa3b8 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 11:00:24 +0800 Subject: [PATCH 194/201] refactor(limit): read a start's accounts with the creator's rule, and state what a precompile's writes do to a start One rule reads what changed of an account since before revm decided a start, for a start's accounts and for a creator alike, and a start counts itself in one step. A node's own precompile that writes the start's accounts in its answer has those writes read with the start, which revm runs it inside; the docs say so, the spec's detention answer is a MUST, and stale prose about the start is restated. --- .claude/skills/satin-review/SKILL.md | 2 +- AGENTS.md | 3 +- crates/mega-evm/src/evm/execution.rs | 40 +++++++------- crates/mega-evm/src/limit/record.rs | 64 ++++++++++++---------- crates/mega-evm/tests/satin/tool_writes.rs | 5 +- docs/spec/upgrades/satin.md | 4 +- 6 files changed, 62 insertions(+), 56 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index a3abfc66b..bf4544671 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -247,7 +247,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::made` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed, and a precompile gas detention answers from its price, count nothing and are held to nothing but the price; a start revm refuses on its caller's account counts nothing and is charged nothing. - - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); an answer revm gave gives way to the stop on its untouched forward, and a success's value move and log are taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`). + - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. - The forwards: regular gas `remaining − remaining × 2 / 100`, plus a value call's stipend after the cap; the reservoir by the same subtraction, the transaction's own frame and a system call's outermost frame taking the whole; each pool `remaining × 98 / 100`, rounded down. diff --git a/AGENTS.md b/AGENTS.md index 4a2b2f175..701fa2f3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -440,7 +440,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The opcodes that can read volatile data run in detention's read wrapper (see Gas detention). Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's Amsterdam one. - **Write records.** - One 40-byte record per account or storage write, which follows the net change: a slot's record exists while its value differs from its original in the transaction (made by its first change, taken back on a write-back), an account's while its nonce, balance or code differs from what the transaction loaded, revm's original info (`Accounts::is_changed`): a start's records are read off the journal before revm makes the start — a value transfer's two sides on the balances it leaves them, a creation's creator and created account (an address the transaction funded, or a `SELFDESTRUCT` paid, before the creation lands on it is changed already, and the creation adds no record for it) — and a `SELFDESTRUCT`'s after it, its beneficiary and the account it clears rebuilt as they were from the balance it moved (`CompletedWrite::SelfDestruct::balance`); the applied EIP-7702 authorities and the transaction's own recipient or created account are counted where they are made. + One 40-byte record per account or storage write, which follows the net change: a slot's record exists while its value differs from its original in the transaction (made by its first change, taken back on a write-back), an account's while its nonce, balance or code differs from what the transaction loaded, revm's original info (`Accounts::is_changed`): a start's records are read off what revm did — a value transfer's two sides and a creation's created account, as they stood before revm decided the start and as they stand once it did, a creation's creator once the creation returned (an address the transaction funded, or a `SELFDESTRUCT` paid, before the creation lands on it is changed already, and the creation adds no record for it) — and a `SELFDESTRUCT`'s after it, its beneficiary and the account it clears rebuilt as they were from the balance it moved (`CompletedWrite::SelfDestruct::balance`); the applied EIP-7702 authorities and the transaction's own recipient or created account are counted where they are made. So a transfer to an account already changed adds nothing, one that returns an account takes its record back (its history credited to the caller once the frame's start is kept), a value `CALLCODE` or a call to the calling account itself records nothing, and a start whose value the caller cannot fund is charged nothing. The sender's own account is part of the transaction body: validation changes it before execution, so no write to it — a frame running as the sender (through an EIP-7702 delegation), value sent back to it — records it again; a fee account is unchanged until execution writes it, which records it. Records live on the pool of the frame that made them: a success hands them to the caller, a failure takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its pool once the creation returned with the nonce bumped, the creation's share having been taken at the opcode before it, so it survives the creation's failure and is held to the creator's budget, not the creation's. @@ -451,6 +451,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. + The one exception is a node's own precompile that writes the start's own accounts in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so those writes are read with the start's (`tests/satin/tool_writes.rs`); the Satin set writes nothing. Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. - **A start's charge rides on revm's carriers.** The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. diff --git a/crates/mega-evm/src/evm/execution.rs b/crates/mega-evm/src/evm/execution.rs index 3ccca2cd9..88052fd64 100644 --- a/crates/mega-evm/src/evm/execution.rs +++ b/crates/mega-evm/src/evm/execution.rs @@ -53,7 +53,7 @@ use revm::{ use crate::{ access::ComputeStop, charge_write_records_history, history_gas, - limit::{Counted, CreatorBefore, StartBefore}, + limit::{CreatorBefore, StartBefore}, synthetic_frame_result, system::keyless, write_record_history_gas, Detention, ExternalEnvTypes, LimitCheck, LimitKind, MegaContext, @@ -538,8 +538,8 @@ impl EvmTr for MegaEvm EvmTr for MegaEvm EvmTr for MegaEvm Result> { let mut creator = None; - let (first, second, charged, reservoir, shares) = match &frame_init.frame_input { + let (account, other, charged, reservoir, shares) = match &frame_init.frame_input { FrameInput::Call(inputs) => ( inputs.caller, Some(inputs.target_address), @@ -1274,7 +1270,7 @@ impl FrameStart { }; let mark = mark(ctx.journal_mut()); Ok(Self { - before: ctx.accounts().start_before(first, second, mark.log_i), + before: ctx.accounts().start_before(account, other, mark.log_i), mark, charged, gas_limit: input_gas_limit(&frame_init.frame_input), @@ -1284,17 +1280,19 @@ impl FrameStart { }) } - /// What the start made on its frame, read off the journal once revm decided it — its records - /// and their bytes, its state growth and its transfer log ([`Accounts::start_made`]) — and what - /// its caller gets back once the frame returned with its start kept: what it paid for the - /// records on the frame, less the price of those the start made, and the price of those it - /// took back. + /// Holds the start, which revm just decided, to the limits on the pools of its frame, which + /// `gas` holds, and counts there what it made, read off the journal — its records and their + /// bytes, its state growth and its transfer log ([`Accounts::start_made`]) — with what its + /// caller gets back once the frame returned with its start kept: what it paid for the records + /// on the frame, less the price of those the start made, and the price of those it took back + /// ([`AdditionalLimit::count_start`](crate::AdditionalLimit)). /// /// [`Accounts::start_made`]: crate::limit::Accounts - fn made( + fn count( &self, - ctx: &MegaContext, - ) -> (Counted, u64) { + ctx: &mut MegaContext, + gas: &mut GasTracker, + ) -> LimitCheck { let (records, counted) = ctx.accounts().start_made(&self.before); let credit = if ctx.prices_history() { let price = |records| write_record_history_gas(records).unwrap_or(0); @@ -1302,7 +1300,7 @@ impl FrameStart { } else { 0 }; - (counted, credit) + ctx.additional_limit.count_start(gas, &counted, credit) } } diff --git a/crates/mega-evm/src/limit/record.rs b/crates/mega-evm/src/limit/record.rs index bfee3f93d..d4d3e855a 100644 --- a/crates/mega-evm/src/limit/record.rs +++ b/crates/mega-evm/src/limit/record.rs @@ -174,18 +174,15 @@ fn differs(info: &AccountInfo, original: &AccountInfo) -> bool { /// made of the creator ([`Accounts::creator_counted`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct CreatorBefore { - /// The creator. - address: Address, + /// The creator's account. + account: AccountBefore, /// Its nonce. nonce: u64, - /// Whether the transaction had changed its account from what it loaded. - changed: bool, - /// Whether its account was empty under EIP-161. - empty: bool, } -/// An account a frame's start may change on its frame, as the transaction held it before revm -/// decided the start. +/// An account a frame's start may change, as the transaction held it before revm decided the +/// start: what tells, once revm did, the write record and the state growth it made of the account +/// ([`Accounts::account_made`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct AccountBefore { /// The account. @@ -210,7 +207,7 @@ pub(crate) struct StartBefore { } /// Whether `log` is the EIP-7708 transfer log revm journals for a value movement: a log from the -/// system address `0xff…fe` carrying ERC-20's `Transfer` event, which no contract can emit. +/// system address `0xff…fe` carrying ERC-20's `Transfer` event. pub(crate) fn is_transfer_log(log: &Log) -> bool { log.address == ETH_TRANSFER_LOG_ADDRESS && log.topics().first() == Some(Ð_TRANSFER_LOG_TOPIC) } @@ -408,10 +405,8 @@ impl<'a> Accounts<'a> { /// The creator is read loaded: revm loads it first thing when it decides the creation. pub(crate) fn creator_before(&self, address: Address) -> CreatorBefore { CreatorBefore { - address, + account: self.account_before(address), nonce: self.loaded(address).map_or(0, |account| account.info.nonce), - changed: self.is_changed(address), - empty: self.is_empty(address), } } @@ -419,7 +414,8 @@ impl<'a> Accounts<'a> { /// creation it decides but one it refuses on the creator's account — an endowment the creator /// cannot fund, a nonce at its maximum — and the bump stands whatever the creation then does. pub(crate) fn bumped(&self, before: &CreatorBefore) -> bool { - self.loaded(before.address).is_some_and(|account| account.info.nonce != before.nonce) + let address = before.account.address; + self.loaded(address).is_some_and(|account| account.info.nonce != before.nonce) } /// What the nonce bump of the creator `before` was read of made, read off the journal once its @@ -428,27 +424,35 @@ impl<'a> Accounts<'a> { /// account. The record follows the account's net change, so a keyless deployment's settlement, /// which may set the signer's nonce back, is read once it did. pub(crate) fn creator_counted(&self, before: &CreatorBefore) -> Counted { + let (record, grew) = self.account_made(&before.account); + Counted::records(record.added, record.taken, false).with_growth(u64::from(grew), 0) + } + + /// The account at `address` as the transaction holds it. + fn account_before(&self, address: Address) -> AccountBefore { + AccountBefore { address, changed: self.is_changed(address), empty: self.is_empty(address) } + } + + /// What changed of the account `before` was read of since, as the journal holds it now: its + /// write record, by its change ([`RecordDelta::of_account`]), and whether it became a new + /// account, empty under EIP-161 then and not now. + fn account_made(&self, before: &AccountBefore) -> (RecordDelta, bool) { let record = RecordDelta::of_account(before.changed, self.is_changed(before.address)); - let grows = before.empty && self.loaded(before.address).is_some_and(|a| !a.info.is_empty()); - Counted::records(record.added, record.taken, false).with_growth(u64::from(grows), 0) + let loaded = self.loaded(before.address); + (record, before.empty && loaded.is_some_and(|account| !account.info.is_empty())) } - /// The accounts at `first` and `second` as the transaction holds them before revm decides a - /// start that writes them on its frame, read loaded, as revm reads them, the journal holding - /// `logs` logs. An account named twice is read once. + /// The accounts a start writes on its frame — `account` and `other`, a call's caller and + /// target, or a creation's created account alone — as the transaction holds them before revm + /// decides the start, the journal holding `logs` logs. An account named twice is read once. pub(crate) fn start_before( &self, - first: Address, - second: Option
, + account: Address, + other: Option
, logs: usize, ) -> StartBefore { - let read = |address| AccountBefore { - address, - changed: self.is_changed(address), - empty: self.is_empty(address), - }; - let second = second.filter(|second| *second != first).map(read); - StartBefore { accounts: [Some(read(first)), second], logs } + let other = other.filter(|other| *other != account).map(|other| self.account_before(other)); + StartBefore { accounts: [Some(self.account_before(account)), other], logs } } /// What the start `before` was read of made on its frame, read off the journal once revm @@ -460,9 +464,9 @@ impl<'a> Accounts<'a> { let mut records = RecordDelta::NONE; let mut growth = 0; for account in before.accounts.iter().flatten() { - let changed = self.is_changed(account.address); - records = records.with(RecordDelta::of_account(account.changed, changed)); - growth += u64::from(account.empty && !self.is_empty(account.address)); + let (record, grew) = self.account_made(account); + records = records.with(record); + growth += u64::from(grew); } let logs = self.logs.get(before.logs..).unwrap_or_default(); let logged = logs.iter().any(is_transfer_log); diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs index 6a50c6e83..138b3ec9a 100644 --- a/crates/mega-evm/tests/satin/tool_writes.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -66,7 +66,10 @@ fn stateful() -> DynPrecompile { /// a checkpoint it commits and one it reverts — keeps its writes in the state and the receipt, and /// counts none of them: the transaction's data size is its body and the start of the value call /// that reached the precompile, the precompile's record and its caller's and the call's transfer -/// log, as for a precompile that writes nothing. +/// log, as for a precompile that writes nothing. revm runs the precompile inside the call's start, +/// and the start is read off the journal once revm decided it, so a precompile's writes to the +/// call's own accounts would be read with the start; this one's transfer leaves the precompile's +/// account changed, as the call's value did, and writes no other account of the start. #[test] fn test_a_precompiles_writes_through_evm_internals_count_nothing() { let code = BytecodeBuilder::default().call(STATEFUL, U256::from(VALUE)).stop().build(); diff --git a/docs/spec/upgrades/satin.md b/docs/spec/upgrades/satin.md index 458a465d9..91a568531 100644 --- a/docs/spec/upgrades/satin.md +++ b/docs/spec/upgrades/satin.md @@ -875,7 +875,7 @@ A limit is enforced on the writes it guards before anything runs on them: - A frame whose start crosses a limit MUST be stopped before it runs an instruction, and what its start moved MUST be reverted with it: the value, the transfer log, a created account. A frame answered with a success without running — a call to an account with no code, a precompile that answers — MUST have its answer replaced by the stop, on the gas its caller forwarded, untouched. A frame answered with a failure kept nothing and MUST NOT have its answer replaced by a stop: a precompile that fails consumes the gas forwarded to it, as without a limit. - A precompile whose price crosses gas detention moves nothing and is held to the price alone: its result is the compute stop, whatever records its value transfer would have made (see [Resource Limits](#10-resource-limits)). + A precompile whose price crosses gas detention moves nothing, and MUST be held to the price alone: its result is the compute stop, whatever records its value transfer would have made (see [Resource Limits](#10-resource-limits)). A stopped creation keeps its creator's nonce bump, and that write's record MUST be counted on the creator when the creation returns: the creator MUST be held to its limits with it before it runs on, and be stopped if it crosses one. - A frame answered without running whose answer is then rewritten to the stop (see [Gas Detention on Withheld Gas](#12-gas-detention-on-withheld-gas)) MUST have what its start moved reverted with it, as a frame that fails has. - Nothing counted before the first frame crosses the data-size limit: validation rejects a transaction whose body, with a record for each entry of its authorization list, would (see [Two-Pool Gas](#4-two-pool-gas-eip-8037-replaces-the-dual-gas-model)). @@ -961,7 +961,7 @@ A contract can revert with the same bytes, and so can a caller that re-raises th {% hint style="info" %} A precompile a node adds or replaces is outside the Satin set and outside this specification. -The reference implementation has no price for one, so it runs such a precompile on the allowance and treats running out of it as the crossing: the failure has taken back the value and the transfer log, so the call is held to the allowance alone, and the stop is kind 2. +The reference implementation has no price for one, so it runs such a precompile on the allowance and treats running out of it as the crossing, kind 2, whatever records its value transfer would have made. {% endhint %} ### 13. Volatile-Data Access Control and `remainingComputeGas()` From 0bfe8c0b07c6d060452a8adb3ed46c13da7c1398 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 11:41:14 +0800 Subject: [PATCH 195/201] chore(deps): pin the revm and op-revm forks at the heads of their pull requests --- .claude/skills/satin-review/SKILL.md | 2 +- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 26 +++++++++++++------------- docs/spec/overview.md | 2 +- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index bf4544671..bcbfff83a 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -31,7 +31,7 @@ The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. Satin is a new spec: simpler semantics win over parity with the legacy engine. - Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates. Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code. -- Fork code: the `megaeth-labs/revm` fork at `2fc8edf33b2ffddb195cebc17be9adabfd95417c` and the `megaeth-labs/op-revm` fork at `f599efdabc3e5b36a280f1aa72978751bd64c160`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. +- Fork code: the `megaeth-labs/revm` fork at `fd230a3427d1b96c88e0b581bab8a7763c8ec298` and the `megaeth-labs/op-revm` fork at `2ecb7dceed1c458a2b59ca4d8993a073968cb111`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8. Their diff is not part of this pull request. A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour. The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks). diff --git a/Cargo.lock b/Cargo.lock index 869ba3e17..1eeebca2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/megaeth-labs/op-revm?rev=f599efdabc3e5b36a280f1aa72978751bd64c160#f599efdabc3e5b36a280f1aa72978751bd64c160" +source = "git+https://github.com/megaeth-labs/op-revm?rev=2ecb7dceed1c458a2b59ca4d8993a073968cb111#2ecb7dceed1c458a2b59ca4d8993a073968cb111" dependencies = [ "auto_impl", "revm 40.0.3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "revm" version = "40.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "revm-bytecode 11.0.1", "revm-context 18.0.3", @@ -5227,7 +5227,7 @@ dependencies = [ [[package]] name = "revm-bytecode" version = "11.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "bitvec", "phf 0.13.1", @@ -5254,7 +5254,7 @@ dependencies = [ [[package]] name = "revm-context" version = "18.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "bitvec", "cfg-if", @@ -5286,7 +5286,7 @@ dependencies = [ [[package]] name = "revm-context-interface" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -5318,7 +5318,7 @@ dependencies = [ [[package]] name = "revm-database" version = "15.0.2" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "alloy-eips 2.1.1", "alloy-provider 2.1.1", @@ -5349,7 +5349,7 @@ dependencies = [ [[package]] name = "revm-database-interface" version = "12.1.1" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "auto_impl", "either", @@ -5382,7 +5382,7 @@ dependencies = [ [[package]] name = "revm-handler" version = "20.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "auto_impl", "derive-where", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "revm-inspector" version = "21.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "auto_impl", "either", @@ -5483,7 +5483,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "37.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "revm-bytecode 11.0.1", "revm-context-interface 19.0.3", @@ -5523,7 +5523,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "36.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "ark-bls12-381", "ark-bn254", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "24.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "alloy-primitives", "once_cell", @@ -5581,7 +5581,7 @@ dependencies = [ [[package]] name = "revm-state" version = "12.0.1" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "alloy-eip7928 0.4.11", "bitflags 2.11.1", @@ -5594,7 +5594,7 @@ dependencies = [ [[package]] name = "revm-statetest-types" version = "19.0.3" -source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c" +source = "git+https://github.com/megaeth-labs/revm?rev=fd230a3427d1b96c88e0b581bab8a7763c8ec298#fd230a3427d1b96c88e0b581bab8a7763c8ec298" dependencies = [ "alloy-eip7928 0.4.11", "k256", diff --git a/Cargo.toml b/Cargo.toml index 319b4d467..bf2738ac7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -232,20 +232,20 @@ codegen-units = 1 [patch.crates-io] # megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks). # All twelve crates move together, otherwise the build resolves a second copy of revm. -revm = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } -revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" } +revm = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } +revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "fd230a3427d1b96c88e0b581bab8a7763c8ec298" } [patch."https://github.com/ethereum-optimism/optimism"] # megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built # against the revm pin above. -op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "f599efdabc3e5b36a280f1aa72978751bd64c160" } +op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "2ecb7dceed1c458a2b59ca4d8993a073968cb111" } diff --git a/docs/spec/overview.md b/docs/spec/overview.md index acd4cbc4a..7e1763185 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -51,7 +51,7 @@ For the current stable behavior as a single reference, see the [MegaEVM Overview Satin (unstable): base layer and reference implementation Satin inherits standard EVM semantics from Optimism Karst (Ethereum Osaka) unless explicitly overridden, and every transaction but a deposit or one of the protocol's own pays history gas, so no transaction that pays it behaves identically to Optimism under Satin. -Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `2fc8edf33b2ffddb195cebc17be9adabfd95417c` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `f599efdabc3e5b36a280f1aa72978751bd64c160` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. +Its reference implementation is the 2.x line of [MegaEVM](https://github.com/megaeth-labs/mega-evm), built on the [MegaETH fork of revm](https://github.com/megaeth-labs/revm) 40.0.3 at commit `fd230a3427d1b96c88e0b581bab8a7763c8ec298` ([megaeth-labs/revm#76](https://github.com/megaeth-labs/revm/pull/76)), the [MegaETH fork of op-revm](https://github.com/megaeth-labs/op-revm) 20.0.0 at commit `2ecb7dceed1c458a2b59ca4d8993a073968cb111` ([megaeth-labs/op-revm#8](https://github.com/megaeth-labs/op-revm/pull/8)), and alloy-evm 0.36. See the [Satin Network Upgrade](upgrades/satin.md). From 6b9f4ff457fbd7f4700b603de5a45fabc4d370e4 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 11:48:02 +0800 Subject: [PATCH 196/201] docs(review): flag a records stop at either answer site of a frame start --- REVIEW.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/REVIEW.md b/REVIEW.md index 1fbd4ab13..9d89a79f1 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -28,7 +28,9 @@ Defer to the baseline for everything not listed here; the rules below take prece The Host's `sstore`, `log` and `selfdestruct` only write and count nothing; revm's write instructions call the completed-write hook (`Host::write_completed`) after every charge they make, and the frame-starting instructions call the frame-start hook (`Host::frame_starting`) after the forward and before the frame's input is built. A record, a charge or a read mark made before the opcode can still fail counts a write that never happened. The frame-start hook only prices: a start's records are counted once revm decided it, from what revm did to the start's accounts (`Accounts::start_made`), and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision, none is predicted and none is given back. - An answer that failed kept nothing and is held to nothing, and a precompile gas detention answers from its price moved nothing and is held to the price alone: flag a stop given to either. + An answer that failed kept nothing and is held to nothing: a failed precompile answer ends as the precompile's own failure, or as the compute stop (kind 2) where gas detention ran a precompile it cannot price on the allowance and the precompile ran out of it. + A precompile gas detention answers from its price moved nothing and is held to the price alone: its answer is the compute stop (kind 2). + Flag a records stop — data size, KV updates or state growth (kinds 0, 1 and 3) — given at either answer site. Check that nothing is counted in the Host's write methods, that no charge lands in a write instruction after the hook (the fork's call sites), and that the engine's matches over `CompletedWrite` and `FrameStartKind` carry no wildcard arm. - **A limit is enforced before the write it guards.** A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit, unless the failure put back a record a frame above made while an Oracle hint the failed frame sent stays, when the caller returns the transaction's stop as it resumes; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop. From bcc3b84727f47ade417f2f4198a3b0bd17203028 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 11:48:02 +0800 Subject: [PATCH 197/201] test(limit): pin what a start reads of a precompile's writes, and that a failed first answer is held to no limit --- AGENTS.md | 3 +- crates/mega-evm/tests/satin/state_growth.rs | 38 +++++++++++++++++ crates/mega-evm/tests/satin/tool_writes.rs | 47 +++++++++++++++++++-- 3 files changed, 83 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 701fa2f3c..cca446832 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -195,6 +195,7 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back. A frame start's records and log are read off what revm did, in `MegaEvm::frame_init`: the start's accounts on its frame — a call's caller and target, a creation's created account — are read before revm decides the start, with a journal mark (`Accounts::start_before`), and again once it did, each account's record by its change since, one account of state growth for each that was empty and is not, and the transfer log revm journaled since the mark (`Accounts::start_made`), drawn on the pool the frame starts with (`AdditionalLimit::count_start`): a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; a success revm gave without building the frame — a call to an account with no code, to a precompile that answers — gives way to the stop on its untouched gas, and its committed move and log are taken back to the mark (`take_back_a_stopped_answer`). An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: its result is revm's, so a value call to a precompile that fails burns its forward as any failed precompile does, whatever its value transfer would have counted. + It is not held to the transaction's limits either, having kept nothing: a deposit whose created caller alone stands over a state-growth limit of nothing, which only a tool's limit sets, and whose first frame is such an answer ends as a failed deposit, not with the stop a success answer there gets (`tests/satin/state_growth.rs`). A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which prices a start's records from the journal's state and sees the caller cannot fund the value. A creation it would answer before bumping its creator's nonce — an endowment the creator cannot fund, a creator whose nonce is at its maximum — is refused by the `CREATE` and `CREATE2` opcodes themselves, before the start's hook under EIP-8037, and otherwise reaches the hook without a created address, for which it prices no record, so a plain run charges and counts nothing for it; only an inspector that rewrites the creation's input after the hook reaches revm's refusal, which bumps nothing and so counts nothing: the declared part of what the opcode charged comes back with the refused start, and the history of the creator's record, which is not declared, stays charged. A creation onto an occupied address, which revm fails after the nonce bump, is held to nothing at its start: it fails on the collision, its records and log go with the failure, and the nonce record is counted on the creator once the creation returned, held to the creator's limits. @@ -451,7 +452,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. - The one exception is a node's own precompile that writes the start's own accounts in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so those writes are read with the start's (`tests/satin/tool_writes.rs`); the Satin set writes nothing. + The one exception is a node's own precompile that writes in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so what the precompile changes of the start's own accounts — the nonce, balance or code an account's record follows, and one account of state growth for each it leaves not empty — and a transfer log it journals are read with the start's, a start counting one transfer log, its value's or the precompile's; its storage writes and its writes to any other account are not (`tests/satin/tool_writes.rs`); the Satin set writes nothing. Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. - **A start's charge rides on revm's carriers.** The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. diff --git a/crates/mega-evm/tests/satin/state_growth.rs b/crates/mega-evm/tests/satin/state_growth.rs index 3a0fe9c9a..fd461d08c 100644 --- a/crates/mega-evm/tests/satin/state_growth.rs +++ b/crates/mega-evm/tests/satin/state_growth.rs @@ -1371,6 +1371,44 @@ fn test_a_deposits_new_caller_is_counted_before_its_first_frame() { assert!(none_left.state[&A].storage.values().all(|slot| slot.present_value.is_zero())); } +/// Under a state-growth limit of nothing a deposit's created caller alone is over it. A first frame +/// revm answers with a success — a precompile that answers — is held to the transaction's limit +/// with what its start adds, nothing, and is the stop; one revm answers with a failure — a +/// precompile whose input fails its check — kept nothing and is held to no limit, so the deposit +/// fails as its frame's halt has it, a failed deposit, and reports no stop. +#[test] +fn test_a_deposits_failed_first_answer_is_held_to_no_limit() { + let fresh = address!("00000000000000000000000000000000006000fe"); + let deposit = |input: u8| { + let mut tx = call(fresh, revm::precompile::bn254::add::ADDRESS, U256::ZERO, room(0)); + tx.0.base.data = Bytes::from(vec![input; 128]); + crate::common::deposit(tx) + }; + let answered = execute_under(funded(), deposit(0), growth(0)); + assert_eq!( + answered.limit_exceeded, + Some(LimitCheck::ExceedsLimit { + kind: LimitKind::StateGrowth, + limit: 0, + used: 1, + frame_local: false + }), + "two points at infinity add up: the answer is held, and the caller is over the limit" + ); + let failed = execute_under(funded(), deposit(0xff), growth(0)); + assert!( + matches!( + failed.result, + ExecutionResult::Halt { reason: mega_evm::MegaHaltReason::FailedDeposit, .. } + ), + "coordinates above the field's modulus fail the precompile: {:?}", + failed.result + ); + assert_eq!(failed.limit_exceeded, None, "the failed answer is held to nothing"); + assert_eq!(failed.usage.state_growth, 1, "the caller stays counted"); + assert_eq!(failed.state[&fresh].info.nonce, 1, "and exists"); +} + /// A frame whose start adds a new account it has no budget for is stopped before it runs, and what /// its start moved goes back: a value call to a new account under a budget of nothing is answered /// with the stop, its value not moved, and its caller catches it. A creation's start alike: its diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs index 138b3ec9a..7e8146c2a 100644 --- a/crates/mega-evm/tests/satin/tool_writes.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -3,7 +3,10 @@ //! What a transaction keeps is counted where its own execution writes: at the completed-write and //! frame-start hooks, and where revm decides a start. A precompile's writes through //! `EvmInternals` and an inspector's are not the transaction's own execution, and neither is -//! counted; neither is a start an inspector answers before revm decides it. +//! counted; neither is a start an inspector answers before revm decides it. The one exception is a +//! precompile's in a success answer, which revm runs inside the call's start: the start is read +//! off the journal once revm decided it, so what the precompile changes of the start's own +//! accounts, and a transfer log it journals, are read with the start. use alloy_evm::precompiles::DynPrecompile; use alloy_primitives::{address, map::HashMap, Address, Bytes, Log, LogData, B256, U256}; @@ -67,9 +70,11 @@ fn stateful() -> DynPrecompile { /// counts none of them: the transaction's data size is its body and the start of the value call /// that reached the precompile, the precompile's record and its caller's and the call's transfer /// log, as for a precompile that writes nothing. revm runs the precompile inside the call's start, -/// and the start is read off the journal once revm decided it, so a precompile's writes to the -/// call's own accounts would be read with the start; this one's transfer leaves the precompile's -/// account changed, as the call's value did, and writes no other account of the start. +/// and the start is read off the journal once revm decided it, so what a precompile changes of the +/// call's own accounts, and a transfer log it journals, would be read with the start, which counts +/// one transfer log; its storage writes and its writes to any other account are not. This one's +/// transfer leaves the precompile's account changed, as the call's value did, its transfer log is +/// the start's second, and [`PAYEE`] is no account of the start. #[test] fn test_a_precompiles_writes_through_evm_internals_count_nothing() { let code = BytecodeBuilder::default().call(STATEFUL, U256::from(VALUE)).stop().build(); @@ -105,6 +110,40 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { ); } +/// A precompile that moves one wei of its own to [`CONTRACT`], which calls it, through +/// `EvmInternals`. +fn paying_its_caller() -> DynPrecompile { + DynPrecompile::new(PrecompileId::Custom("paying its caller".into()), |mut input| { + assert_eq!(input.internals.transfer(STATEFUL, CONTRACT, U256::from(1)).unwrap(), None); + Ok(PrecompileOutput::new(0, Bytes::new(), input.reservoir)) + }) +} + +/// A node's own precompile that, reached by a call moving no value, moves value between the call's +/// own accounts in its success answer has that move read with the call's start, which revm runs it +/// inside: the start counts both accounts' records and the precompile's transfer log, as a value +/// call between them would have, where the call alone counts nothing. +#[test] +fn test_a_precompiles_writes_to_the_starts_own_accounts_are_read_with_the_start() { + let code = BytecodeBuilder::default().call(STATEFUL, U256::ZERO).stop().build(); + let db = MemoryDatabase::default() + .account_code(CONTRACT, code) + .account_balance(STATEFUL, U256::from(VALUE)); + let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); + let mut evm = MegaEvm::new(context(db)) + .with_dyn_precompiles(HashMap::from_iter([(STATEFUL, paying_its_caller())])); + let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); + + assert!(outcome.result.is_success(), "{:?}", outcome.result); + assert_eq!(outcome.state[&CONTRACT].info.balance, U256::from(1), "the precompile's move"); + assert_eq!(outcome.result.logs(), [transfer_log(STATEFUL, CONTRACT, U256::from(1))]); + assert_eq!( + outcome.usage, + records_and_moves(2, 1), + "the call's two accounts and the precompile's transfer log, read with the start" + ); +} + /// An inspector that answers, in `frame_start`, the call to `target` with a success on the gas /// the call was given. struct AnswersAtFrameStart { From cd22e45803121d6cfbcadae8842c84ec111a2388 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 11:48:02 +0800 Subject: [PATCH 198/201] docs(skills): mark in the Satin review guide what changed after #407 merged --- .claude/skills/satin-review/SKILL.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index bcbfff83a..93b033fbc 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -1,6 +1,6 @@ --- name: satin-review -description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests and #407 have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. +description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests and #407 have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 and the commits after it made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges. --- # Reviewing the Satin engine (pull request #386) @@ -10,13 +10,14 @@ It is deleted before the Satin pull request merges, so nothing else may link to It is a map: where each part of the engine lives, what to check there, what changed after the stacked pull requests were described, and what is already decided. Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them, and restates a rule only to say what changed. [`REVIEW.md`](../../../REVIEW.md) is the repository's own review rubric; its consensus-critical list overlaps the checks below. -The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. +The guide describes the code at `cz/feat/satin-w2` with #407 merged into it and the commits after it. ## What is under review - The Satin engine, in pull request #386 (`cz/feat/satin-w2`), judged at its final state. The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) merged into it, and then #407 (`cz/feat/satin-w9`); each description explains its part as it was merged, and a later part may have changed an earlier one. - "Design changes a reviewer must know" below lists what #407 changed. + The commits after #407 on `cz/feat/satin-w2` are part of this pull request and have no description of their own. + "Design changes a reviewer must know" below lists what #407 and those commits changed, a change those commits made marked as such. - The review range is the pull request's own diff. Its base, `cz/feat/satin-review-base`, is `satin` before the Satin skeleton: `a8f8c7c9`, the CI-only commit before it. So GitHub's "Files changed" holds the skeleton (#385) and every later series: the whole engine. @@ -45,6 +46,7 @@ The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it. Nothing. #407 has merged into this branch, and with it everything its description listed as still to be added: inspectors on revm's own inspected lifecycle, a rewritten result taken as given, one fixed gas budget for the pre-block calls, the cleanups, and the KV-update and state-growth limits with their 98/100 frame shares and the destruction table's give-backs. It also counts a creator's nonce record when the creation returns, which its description did not list. +The commits after it on this branch count a frame start's records from what revm did; they are part of this pull request, and the design changes below mark what they changed. Every module is at its final state for this review: there is no longer a table of stable and changing modules, nor a rule to hold back findings in a changing one. What follows this pull request changes no rule. The fork pins move from the reviewed commits to the merged commits of megaeth-labs/revm#76 and megaeth-labs/op-revm#8, and to release tags once the line is final. @@ -52,7 +54,8 @@ Performance work is left for later: the optimisations #407 recorded are made tog ## Design changes a reviewer must know -The stacked pull requests' descriptions predate #407, which changed parts of what they describe. +The stacked pull requests' descriptions predate #407 and the commits after it on this branch, which changed parts of what they describe. +A change made after #407 merged is marked as such: it is not in #407's diff. Each change is stated here in plain words with its reason; the specification has the rule and `AGENTS.md` the mechanism. ### Where the engine meets revm @@ -82,6 +85,7 @@ Each change is stated here in plain words with its reason; the specification has The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes. Why: the record measures the state the transaction keeps, by revm's own notion of a change; the per-frame count over-counted, and charged history gas for writes that leave nothing. - **A frame start is held to the limits once revm decided it, on what it kept.** + Made after #407 merged: #407 already held a start once revm decided it — a built frame stopped before its first instruction, an answer stopped on its untouched forward, a collision not stopped for its start — but to records it predicted from the journal before revm decided, which it held the two answers below to as well; the commits after it count what revm did and hold those two answers to nothing but the price. Its accounts on the frame are read before revm decides the start and again once it did, and what changed between — each account's record, an account that was empty and is not, the transfer log revm journaled — is counted on the started frame's pools; nothing is predicted. A frame revm built returns the stop before its first instruction, and a success revm gave without building a frame gives way to the stop on the untouched forward, its value move taken back. An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: a value call to a precompile that fails at a budget boundary ends as the precompile's failure, which burns its forward, not as a limit's stop. @@ -246,7 +250,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::made` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed, and a precompile gas detention answers from its price, count nothing and are held to nothing but the price; a start revm refuses on its caller's account counts nothing and is charged nothing. + - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed, and a precompile gas detention answers from its price, count nothing and are held to nothing but the price; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. From 913d4133868f6201d6ad84fa06467bbcf66bc055 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 12:02:25 +0800 Subject: [PATCH 199/201] test(limit): pin the new account a precompile's writes add to its start --- AGENTS.md | 2 +- crates/mega-evm/tests/satin/tool_writes.rs | 31 +++++++++++++--------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cca446832..44acd821e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -452,7 +452,7 @@ Every later mechanism plugs into these; a change to one comes back to this layer The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth). The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it. Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws. - The one exception is a node's own precompile that writes in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so what the precompile changes of the start's own accounts — the nonce, balance or code an account's record follows, and one account of state growth for each it leaves not empty — and a transfer log it journals are read with the start's, a start counting one transfer log, its value's or the precompile's; its storage writes and its writes to any other account are not (`tests/satin/tool_writes.rs`); the Satin set writes nothing. + The one exception is a node's own precompile that writes in a success answer, which revm runs inside the start: a start is read off the journal once revm decided it, so what the precompile changes of the start's own accounts — the nonce, balance or code an account's record follows, and one account of state growth for each that was empty and it leaves not empty — and a transfer log it journals are read with the start's, a start counting one transfer log, its value's or the precompile's; its storage writes and its writes to any other account are not (`tests/satin/tool_writes.rs`); the Satin set writes nothing. Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it, on what it made, the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it. - **A start's charge rides on revm's carriers.** The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with. diff --git a/crates/mega-evm/tests/satin/tool_writes.rs b/crates/mega-evm/tests/satin/tool_writes.rs index 7e8146c2a..3ad5171c7 100644 --- a/crates/mega-evm/tests/satin/tool_writes.rs +++ b/crates/mega-evm/tests/satin/tool_writes.rs @@ -76,7 +76,7 @@ fn stateful() -> DynPrecompile { /// transfer leaves the precompile's account changed, as the call's value did, its transfer log is /// the start's second, and [`PAYEE`] is no account of the start. #[test] -fn test_a_precompiles_writes_through_evm_internals_count_nothing() { +fn test_a_precompiles_writes_beyond_its_starts_accounts_count_nothing() { let code = BytecodeBuilder::default().call(STATEFUL, U256::from(VALUE)).stop().build(); let db = MemoryDatabase::default() .account_code(CONTRACT, code) @@ -110,37 +110,42 @@ fn test_a_precompiles_writes_through_evm_internals_count_nothing() { ); } -/// A precompile that moves one wei of its own to [`CONTRACT`], which calls it, through +/// A precompile that moves one wei of [`CONTRACT`]'s, which calls it, to its own account through /// `EvmInternals`. -fn paying_its_caller() -> DynPrecompile { - DynPrecompile::new(PrecompileId::Custom("paying its caller".into()), |mut input| { - assert_eq!(input.internals.transfer(STATEFUL, CONTRACT, U256::from(1)).unwrap(), None); +fn taking_from_its_caller() -> DynPrecompile { + DynPrecompile::new(PrecompileId::Custom("taking from its caller".into()), |mut input| { + assert_eq!(input.internals.transfer(CONTRACT, STATEFUL, U256::from(1)).unwrap(), None); Ok(PrecompileOutput::new(0, Bytes::new(), input.reservoir)) }) } /// A node's own precompile that, reached by a call moving no value, moves value between the call's /// own accounts in its success answer has that move read with the call's start, which revm runs it -/// inside: the start counts both accounts' records and the precompile's transfer log, as a value -/// call between them would have, where the call alone counts nothing. +/// inside: the start counts both accounts' records, the precompile's account, empty before, as a +/// new account, and the precompile's transfer log, as a value call between them would have, where +/// the call alone counts nothing. #[test] fn test_a_precompiles_writes_to_the_starts_own_accounts_are_read_with_the_start() { let code = BytecodeBuilder::default().call(STATEFUL, U256::ZERO).stop().build(); let db = MemoryDatabase::default() .account_code(CONTRACT, code) - .account_balance(STATEFUL, U256::from(VALUE)); + .account_balance(CONTRACT, U256::from(VALUE)); let tx = call(CALLER, CONTRACT, U256::ZERO, value_call_room()); let mut evm = MegaEvm::new(context(db)) - .with_dyn_precompiles(HashMap::from_iter([(STATEFUL, paying_its_caller())])); + .with_dyn_precompiles(HashMap::from_iter([(STATEFUL, taking_from_its_caller())])); let outcome = evm.execute_transaction(tx).expect("the transaction is valid"); assert!(outcome.result.is_success(), "{:?}", outcome.result); - assert_eq!(outcome.state[&CONTRACT].info.balance, U256::from(1), "the precompile's move"); - assert_eq!(outcome.result.logs(), [transfer_log(STATEFUL, CONTRACT, U256::from(1))]); + assert_eq!(outcome.state[&STATEFUL].info.balance, U256::from(1), "the precompile's move"); + assert_eq!( + outcome.result.logs(), + [transfer_log(CONTRACT, STATEFUL, U256::from(1))], + "the receipt carries the precompile's transfer log alone" + ); assert_eq!( outcome.usage, - records_and_moves(2, 1), - "the call's two accounts and the precompile's transfer log, read with the start" + grown(records_and_moves(2, 1), 1), + "the call's two accounts, the precompile's new one and its transfer log, read with the start" ); } From 6b09316340a5c43a1226bdefd08790a52da307d7 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 12:02:25 +0800 Subject: [PATCH 200/201] docs: hold a failed frame-start answer to no records limit in the rubric and the review guide --- .claude/skills/satin-review/SKILL.md | 4 ++-- REVIEW.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 93b033fbc..2be9da72d 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -85,7 +85,7 @@ Each change is stated here in plain words with its reason; the specification has The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes. Why: the record measures the state the transaction keeps, by revm's own notion of a change; the per-frame count over-counted, and charged history gas for writes that leave nothing. - **A frame start is held to the limits once revm decided it, on what it kept.** - Made after #407 merged: #407 already held a start once revm decided it — a built frame stopped before its first instruction, an answer stopped on its untouched forward, a collision not stopped for its start — but to records it predicted from the journal before revm decided, which it held the two answers below to as well; the commits after it count what revm did and hold those two answers to nothing but the price. + Made after #407 merged: #407 already held a start once revm decided it — a built frame stopped before its first instruction, an answer stopped on its untouched forward, a collision not stopped for its start — but to records it predicted from the journal before revm decided, which it held the two answers below to as well; the commits after it count what revm did, and hold a failed answer to no records limit and a detention-priced answer to its price alone. Its accounts on the frame are read before revm decides the start and again once it did, and what changed between — each account's record, an account that was empty and is not, the transfer log revm journaled — is counted on the started frame's pools; nothing is predicted. A frame revm built returns the stop before its first instruction, and a success revm gave without building a frame gives way to the stop on the untouched forward, its value move taken back. An answer that failed kept nothing, revm having taken back what its start moved, and is held to nothing: a value call to a precompile that fails at a budget boundary ends as the precompile's failure, which burns its forward, not as a limit's stop. @@ -250,7 +250,7 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS. - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them. - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held. - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame. - - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed, and a precompile gas detention answers from its price, count nothing and are held to nothing but the price; a start revm refuses on its caller's account counts nothing and is charged nothing. + - A start's records, state growth and transfer log are read off what revm did: its accounts before revm decides the start and again once it did (`FrameStart::of` and `FrameStart::count` in `src/evm/execution.rs`, `Accounts::start_before` and `start_made` in `src/limit/record.rs`), counted on the started frame's pools (`AdditionalLimit::count_start`) for a frame revm built or a call it answered with a success; an answer that failed counts nothing and is held to no records limit, and a precompile gas detention answers from its price counts nothing and is held to the price alone; a start revm refuses on its caller's account counts nothing and is charged nothing. - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); a success revm gave without building a frame gives way to the stop on its untouched forward, its value move and log taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`); an answer that failed is revm's result, held to nothing. - Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump). - A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped. diff --git a/REVIEW.md b/REVIEW.md index 9d89a79f1..30b51e477 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -28,7 +28,7 @@ Defer to the baseline for everything not listed here; the rules below take prece The Host's `sstore`, `log` and `selfdestruct` only write and count nothing; revm's write instructions call the completed-write hook (`Host::write_completed`) after every charge they make, and the frame-starting instructions call the frame-start hook (`Host::frame_starting`) after the forward and before the frame's input is built. A record, a charge or a read mark made before the opcode can still fail counts a write that never happened. The frame-start hook only prices: a start's records are counted once revm decided it, from what revm did to the start's accounts (`Accounts::start_made`), and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision, none is predicted and none is given back. - An answer that failed kept nothing and is held to nothing: a failed precompile answer ends as the precompile's own failure, or as the compute stop (kind 2) where gas detention ran a precompile it cannot price on the allowance and the precompile ran out of it. + An answer that failed kept nothing and is held to no records limit: a failed precompile answer ends as the precompile's own failure, or as the compute stop (kind 2) where gas detention ran a precompile it cannot price on the allowance and the precompile ran out of it. A precompile gas detention answers from its price moved nothing and is held to the price alone: its answer is the compute stop (kind 2). Flag a records stop — data size, KV updates or state growth (kinds 0, 1 and 3) — given at either answer site. Check that nothing is counted in the Host's write methods, that no charge lands in a write instruction after the hook (the fork's call sites), and that the engine's matches over `CompletedWrite` and `FrameStartKind` carry no wildcard arm. From 2ec47583cc27b731963a14e7fe954f7c8a7fa1e6 Mon Sep 17 00:00:00 2001 From: RealiCZ Date: Fri, 23 Oct 2026 12:09:32 +0800 Subject: [PATCH 201/201] docs(skills): mark the frame-start row of the revert-or-halt table as changed after #407 --- .claude/skills/satin-review/SKILL.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md index 2be9da72d..0795c99af 100644 --- a/.claude/skills/satin-review/SKILL.md +++ b/.claude/skills/satin-review/SKILL.md @@ -403,15 +403,15 @@ Inside a dimension the frame budget is tested before the transaction limit, and The deliberate exceptions: -| What happens | Why | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | -| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. | -| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | -| A call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward when revm built its frame or answered it with a success; a call revm answered with a failure — a precompile that fails after the value moved — kept nothing and halts as revm has it, burning its forward, and a precompile gas detention answers from its price is the compute stop, whatever its records would have crossed. | A limit is enforced at the writes it guards, which are what the journal kept: a success kept the start's writes, so it gives way to the stop; a failure's writes revm took back, and a precompile answered from its price moved nothing, so neither has a write to hold. | -| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | -| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | -| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. | +| What happens | Why | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. | +| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. | +| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. | +| Changed after #407 merged: a call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward when revm built its frame or answered it with a success; a call revm answered with a failure — a precompile that fails after the value moved — kept nothing and halts as revm has it, burning its forward, and a precompile gas detention answers from its price is the compute stop, whatever its records would have crossed. | A limit is enforced at the writes it guards, which are what the journal kept: a success kept the start's writes, so it gives way to the stop; a failure's writes revm took back, and a precompile answered from its price moved nothing, so neither has a write to hold. | +| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. | +| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. | +| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. | Not exceptions, but easy to mistake for one: